text
stringlengths 8
6.88M
|
|---|
#pragma once
namespace keng::window_system
{
class IWindowListener
{
public:
virtual void OnWindowResize(int w, int h) = 0;
virtual ~IWindowListener() = default;
};
}
|
#include <cstdio>
using namespace std;
int a[110],b[110];
int main()
{
int n;
scanf("%d",&n);
for (int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
int temp=0;
for (int j=1;j<i;j++)
if (a[i]>a[j]) temp++;
b[i]=temp;
}
for (int i=1;i<=n;i++) printf("%d ",b[i]);
return 0;
}
|
#include "myNode.h"
myNode::myNode() {
data = 0;
next = nullptr;
prev = nullptr;
}
myNode::myNode(int data) {
this->data = data;
this->next = nullptr;
this->prev = nullptr;
}
void myNode::setData(int value) {
if (value > 0)
data = value;
else
return;
}
void myNode::setNext(myNode* next) { this->next = next; }
void myNode::setPrev(myNode* prev) { this->prev = prev; }
int myNode::getData() { return this->data; }
myNode* myNode::getNext(){ return this->next; }
myNode* myNode::getPrev(){ return this->prev; }
|
#include <csignal>
#include <iostream>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include "LDR.h"
using namespace std;
double light;
void timerHandler(int signum)
{
if(signum == 14)
{
light = readLight();
fprintf(stdout, "Light read from LDR sensor is: %.2f Lux\n", light);
fflush(stdout);
}
}
int main(int argC, char **argV)
{
// Install signal hanler for timer interrupts:
if(signal(14, timerHandler)==SIG_ERR)
fprintf(stderr, "Could not install timerHandler\n");
struct itimerval timer;
timer.it_interval.tv_sec = 15;
timer.it_interval.tv_usec = 0;
timer.it_value.tv_sec = 15;
timer.it_value.tv_usec = 0;
int retval = setitimer(ITIMER_REAL, &timer, NULL);
if(retval != 0)
{
fprintf(stderr, "Could not install timer\n");
exit(1);
}
while(1)
{
}
return 0;
}
|
#pragma once
#include "d3d11.h"
#include "WinWrappers/ComPtr.h"
#include "FwdDecl.h"
#include "Keng/GPU/PipelineInput/ISampler.h"
namespace keng::graphics::gpu
{
class Sampler : public core::RefCountImpl<ISampler>
{
public:
Sampler(Device& device, const SamplerParameters& params);
virtual void AssignToPipeline(const ShaderType& shaderType, size_t index) override final;
private:
DevicePtr m_device;
ComPtr<ID3D11SamplerState> m_sampler;
};
}
|
// Created on: 1993-02-03
// Created by: Christian CAILLET
// Copyright (c) 1993-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 _StepData_Protocol_HeaderFile
#define _StepData_Protocol_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Interface_DataMapOfTransientInteger.hxx>
#include <Interface_Protocol.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_SequenceOfAsciiString.hxx>
class Interface_InterfaceModel;
class StepData_EDescr;
class StepData_ESDescr;
class StepData_ECDescr;
class StepData_PDescr;
class StepData_Protocol;
DEFINE_STANDARD_HANDLE(StepData_Protocol, Interface_Protocol)
//! Description of Basic Protocol for Step
//! The class Protocol from StepData itself describes a default
//! Protocol, which recognizes only UnknownEntities.
//! Sub-classes will redefine CaseNumber and, if necessary,
//! NbResources and Resources.
class StepData_Protocol : public Interface_Protocol
{
public:
Standard_EXPORT StepData_Protocol();
//! Gives the count of Protocols used as Resource (can be zero)
//! Here, No resource
Standard_EXPORT Standard_Integer NbResources() const Standard_OVERRIDE;
//! Returns a Resource, given a rank. Here, none
Standard_EXPORT Handle(Interface_Protocol) Resource (const Standard_Integer num) const Standard_OVERRIDE;
//! Returns a unique positive number for any recognized entity
//! Redefined to work by calling both TypeNumber and, for a
//! Described Entity (late binding) DescrNumber
Standard_EXPORT virtual Standard_Integer CaseNumber (const Handle(Standard_Transient)& obj) const Standard_OVERRIDE;
//! Returns a Case Number, specific of each recognized Type
//! Here, only Unknown Entity is recognized
Standard_EXPORT Standard_Integer TypeNumber (const Handle(Standard_Type)& atype) const Standard_OVERRIDE;
//! Returns the Schema Name attached to each class of Protocol
//! To be redefined by each sub-class
//! Here, SchemaName returns "(DEFAULT)"
//! was C++ : return const
Standard_EXPORT virtual Standard_CString SchemaName() const;
//! Creates an empty Model for Step Norm
Standard_EXPORT Handle(Interface_InterfaceModel) NewModel() const Standard_OVERRIDE;
//! Returns True if <model> is a Model of Step Norm
Standard_EXPORT Standard_Boolean IsSuitableModel (const Handle(Interface_InterfaceModel)& model) const Standard_OVERRIDE;
//! Creates a new Unknown Entity for Step (UndefinedEntity)
Standard_EXPORT Handle(Standard_Transient) UnknownEntity() const Standard_OVERRIDE;
//! Returns True if <ent> is an Unknown Entity for the Norm, i.e.
//! Type UndefinedEntity, status Unknown
Standard_EXPORT Standard_Boolean IsUnknownEntity (const Handle(Standard_Transient)& ent) const Standard_OVERRIDE;
//! Returns a unique positive CaseNumber for types described by
//! an EDescr (late binding)
//! Warning : TypeNumber and DescrNumber must give together a unique
//! positive case number for each distinct case, type or descr
Standard_EXPORT virtual Standard_Integer DescrNumber (const Handle(StepData_EDescr)& adescr) const;
//! Records an EDescr with its case number
//! Also records its name for an ESDescr (simple type): an ESDescr
//! is then used, for case number, or for type name
Standard_EXPORT void AddDescr (const Handle(StepData_EDescr)& adescr, const Standard_Integer CN);
//! Tells if a Protocol brings at least one ESDescr, i.e. if it
//! defines at least one entity description by ESDescr mechanism
Standard_EXPORT Standard_Boolean HasDescr() const;
//! Returns the description attached to a case number, or null
Standard_EXPORT Handle(StepData_EDescr) Descr (const Standard_Integer num) const;
//! Returns a description according to its name
//! <anylevel> True (D) : for <me> and its resources
//! <anylevel> False : for <me> only
Standard_EXPORT Handle(StepData_EDescr) Descr (const Standard_CString name, const Standard_Boolean anylevel = Standard_True) const;
//! Idem as Descr but cast to simple description
Standard_EXPORT Handle(StepData_ESDescr) ESDescr (const Standard_CString name, const Standard_Boolean anylevel = Standard_True) const;
//! Returns a complex description according to list of names
//! <anylevel> True (D) : for <me> and its resources
//! <anylevel> False : for <me> only
Standard_EXPORT Handle(StepData_ECDescr) ECDescr (const TColStd_SequenceOfAsciiString& names, const Standard_Boolean anylevel = Standard_True) const;
//! Records an PDescr
Standard_EXPORT void AddPDescr (const Handle(StepData_PDescr)& pdescr);
//! Returns a parameter description according to its name
//! <anylevel> True (D) : for <me> and its resources
//! <anylevel> False : for <me> only
Standard_EXPORT Handle(StepData_PDescr) PDescr (const Standard_CString name, const Standard_Boolean anylevel = Standard_True) const;
//! Records an ESDescr, intended to build complex descriptions
Standard_EXPORT void AddBasicDescr (const Handle(StepData_ESDescr)& esdescr);
//! Returns a basic description according to its name
//! <anylevel> True (D) : for <me> and its resources
//! <anylevel> False : for <me> only
Standard_EXPORT Handle(StepData_EDescr) BasicDescr (const Standard_CString name, const Standard_Boolean anylevel = Standard_True) const;
DEFINE_STANDARD_RTTIEXT(StepData_Protocol,Interface_Protocol)
protected:
private:
Interface_DataMapOfTransientInteger thedscnum;
NCollection_DataMap<TCollection_AsciiString, Handle(Standard_Transient)> thedscnam;
NCollection_DataMap<TCollection_AsciiString, Handle(Standard_Transient)> thepdescr;
NCollection_DataMap<TCollection_AsciiString, Handle(Standard_Transient)> thedscbas;
};
#endif // _StepData_Protocol_HeaderFile
|
/* Author: Mincheul Kang */
#include <harmonious_sampling/Scene.h>
#include <tf/LinearMath/Quaternion.h>
Scene::Scene(planning_scene::PlanningScenePtr& planning_scene, std::string frameID){
planning_scene_ = planning_scene;
frameID_ = frameID;
}
void Scene::addCollisionObjects(){
std::vector<moveit_msgs::CollisionObject> collision_objects;
collision_objects.push_back(addBox("table", 0.0, 0.0, 0.7, 0.6, 1.2, 0.05, 0.0));
collision_objects.push_back(addBox("s0", 0.0 + 2.0, 0.0+1.6, 1.33, 0.8, 0.28, 0.02, 0.0));
collision_objects.push_back(addBox("s1", 0.0 + 2.0, 0.0+1.6, 0.95, 0.8, 0.28, 0.02, 0.0));
collision_objects.push_back(addBox("s2", 0.0 + 2.0, 0.0+1.6, 0.62, 0.8, 0.28, 0.02, 0.0));
collision_objects.push_back(addBox("s3", 0.0 + 2.0, 0.0+1.6, 0.31, 0.8, 0.28, 0.02, 0.0));
collision_objects.push_back(addBox("s4", 0.0 + 2.0, 0.0+1.6, 0.01, 0.8, 0.28, 0.02, 0.0));
collision_objects.push_back(addBox("s5", 0.39+ 2.0, 0.0+1.6, 0.67, 0.02,0.28, 1.34, 0.0));
collision_objects.push_back(addBox("s6",-0.39+ 2.0, 0.0+1.6, 0.67, 0.02,0.28, 1.34, 0.0));
collision_objects.push_back(addBox("s7", 0.0 + 2.0, 0.13+1.6, 0.67, 0.8, 0.02, 1.34, 0.0));
// collision_objects.push_back(addBox("target", 2.0, 1.5, 1.0, 0.03, 0.03, 0.1, 0.0));
planning_scene_interface_.applyCollisionObjects(collision_objects);
}
moveit_msgs::CollisionObject Scene::addBox(std::string name,
double x, double y, double z,
double d_x, double d_y, double d_z,
double yaw){
moveit_msgs::CollisionObject box;
// Add the first table where the cube will originally be kept.
box.id = name;
box.header.frame_id = frameID_;
/* Define the primitive and its dimensions. */
box.primitives.resize(1);
box.primitives[0].type = box.primitives[0].BOX;
box.primitives[0].dimensions.resize(3);
box.primitives[0].dimensions[0] = d_x;
box.primitives[0].dimensions[1] = d_y;
box.primitives[0].dimensions[2] = d_z;
/* Define the pose of the table. */
box.primitive_poses.resize(1);
box.primitive_poses[0].position.x = x;
box.primitive_poses[0].position.y = y;
box.primitive_poses[0].position.z = z;
tf::Quaternion q(tf::Vector3(0, 0, 1), yaw);
box.primitive_poses[0].orientation.w = q.w();
box.primitive_poses[0].orientation.x = q.x();
box.primitive_poses[0].orientation.y = q.y();
box.primitive_poses[0].orientation.z = q.z();
// END_SUB_TUTORIAL
box.operation = box.ADD;
return box;
}
void Scene::updateCollisionScene(){
std::map<std::string, moveit_msgs::CollisionObject> collision_objects_map = planning_scene_interface_.getObjects();
for(auto& kv : collision_objects_map){
planning_scene_->processCollisionObjectMsg(kv.second);
}
}
|
#ifndef _LogoutProcess_H_
#define _LogoutProcess_H_
#include "BaseProcess.h"
class Table;
class Player;
class LogoutProcess:public BaseProcess
{
public:
LogoutProcess();
virtual ~LogoutProcess();
virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* pPacket,Context* pt ) ;
private:
int sendPlayersLogoutInfo(Table* table,Player* leavePlayer);
};
#endif
|
#include "SocketsOps.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <fcntl.h>
#include <cassert>
using SA = struct sockaddr;
const SA* sockaddr_cast(const struct sockaddr_in* addr)
{
return static_cast<const SA*>(implicit_cast<const void*>(addr));
}
SA* sockaddr_cast(struct sockaddr_in* addr)
{
return static_cast<SA*> (implicit_cast<void*>(addr));
}
void setNonBlockAndCloseOnExec(int sockfd)
{
int flags = fcntl(sockfd, FGETFL, 0);
flags |= O_NONBLOCK;
int ret = fcntl(sockfd, F_SETFL, flags);
flags = fcntl(sockfd, FGETFL, 0);
flags |= FD_CLOEXEC;
ret = fcntl(sockfd, F_SETFL, flags);
// 这个地方不能直接 flags |= O_NONBLOCK; flags |= FD_CLOEXEC
// 然后 一次调用 fcntl(sockfd, F_SETFL, flags)设置,这样是只设置了FD_CLOEXEC 和 O_NONBLOCK
// 较大的那个(这个结论是实验获得,不代表所有都是这样)
}
int sockets::createNonblockingOrDie()
{
#if VALGRIND
int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
assert(sockfd >=0, "sockets::createNonblockingOrDie");
setNonBlockAndCloseOnExec(sockfd);
#else
int sockfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP);
assert(sockfd >=0, "sockets::createNonblockingOrDie");
#endif
return sockfd;
}
void sockets::bindOrDie(int sockfd, const struct sockaddr_in& addr )
{
int ret = bind(sockfd, sockaddr_cast(&addr), sizeof addr);
assert(ret ==0 , "sockets::bindOrDie");
}
void sockets::listenOrDie(int sockfd)
{
// 注意第二个参数设置的是established的最大队列长度
// 当然内核 sys.net.core.somaxconn 也对该值得上限做了限制
int ret = listen(sockfd, SOMAXCONN);
assert(ret == 0, "sockets::listenOrDie");
}
int sockets::accept(int sockfd, struct sockaddr_in* addr)
{
socklen_t addrlen = sizeof *addr;
#if VALGRIND
int connfd = accept(sockfd, sockaddr_cast(addr), &addrlen);
setNonBlockAndCloseOnExec(connfd);
#else
int connfd = accept4(sockfd, sockaddr_cast(addr), &addrlen, SOCK_NONBLOCK | SOCK_CLOEXEC);
#endif
if (connfd < 0)
{
int savedErrno == errno;
std::cerr << "Socket::accept\n";
switch (savedErrno)
{
case EAGAIN:
case ECONNABORTED:
case EINTR:
case EPROTO:
case EPERM:
case EMFILE: // per-process limit of open file desctiptor
// expected errors
errno = savedErrno;
break;
case EBADF:
case EFAULT:
case EINVAL:
case ENOBUFS:
case ENOMEM:
case ENOTSOCK:
case EOPNOTSUPP:
// unexpected errors
assert(false, "unexpected")
}
}
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#define INF 1000000000
#define REP(i,n) for(int i=0; i<n; i++)
#define REP_R(i,n,m) for(int i=m; i<n; i++)
#define MAX 100
using namespace std;
int a,b,c,x,y;
int ans = 0;
int tt1, tt2, tt3;
int main() {
scanf("%d %d %d %d %d", &a, &b, &c, &x, &y);
tt1 = a * x + b * y;
int s;
if (x > y) {
tt2 = 2 * c * y;
s = (x - y) * a;
tt2 += s;
} else {
tt2 = 2 * c * x;
s = (y - x) * b;
tt2 += s;
}
tt3 = (x > y) ? 2 * c * x : 2 * c * y;
if (tt1 < tt2 && tt1 < tt3) {
cout << tt1 << endl;
} else if (tt2 < tt1 && tt2 < tt3) {
cout << tt2 << endl;
} else {
cout << tt3 << endl;
}
}
|
/*
* Copyright (c) 2021 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_PROBES_SUS_H_
#define CPPSORT_PROBES_SUS_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <functional>
#include <iterator>
#include <type_traits>
#include <utility>
#include <cpp-sort/sorter_facade.h>
#include <cpp-sort/sorter_traits.h>
#include <cpp-sort/utility/functional.h>
#include <cpp-sort/utility/size.h>
#include <cpp-sort/utility/static_const.h>
#include "../detail/functional.h"
#include "../detail/longest_non_descending_subsequence.h"
namespace cppsort
{
namespace probe
{
namespace detail
{
struct sus_impl
{
template<
typename ForwardIterator,
typename Compare = std::less<>,
typename Projection = utility::identity,
typename = std::enable_if_t<
is_projection_iterator_v<Projection, ForwardIterator, Compare>
>
>
auto operator()(ForwardIterator first, ForwardIterator last,
Compare compare={}, Projection projection={}) const
-> decltype(auto)
{
// We don't need the size information, so we can avoid
// computing it altogether
auto res = cppsort::detail::longest_non_descending_subsequence<false>(
first, last,
0, // Dummy value, not useful here
cppsort::detail::not_fn(compare), std::move(projection)
);
return res.first > 0 ? res.first - 1 : 0;
}
template<typename Integer>
static constexpr auto max_for_size(Integer n)
-> Integer
{
return n == 0 ? 0 : n - 1;
}
};
}
namespace
{
constexpr auto&& sus = utility::static_const<
sorter_facade<detail::sus_impl>
>::value;
}
}}
#endif // CPPSORT_PROBES_SUS_H_
|
/* -*- mode: c++; tab-width: 4 -*-
**
** Copyright (C) 2009 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Test for reading input data into native objects.
**
** Jan Borsodi
*/
group "protobuf.protocolbuffer_input";
require init;
require PROTOBUF_SUPPORT;
require ESUTILS_SYNCIF_SUPPORT;
language c++;
include "modules/scope/src/scope_test_service.h";
include "modules/util/adt/bytebuffer.h";
include "modules/protobuf/src/protobuf_utils.h";
include "modules/protobuf/src/protobuf.h";
include "modules/protobuf/src/protobuf_message.h";
include "modules/protobuf/src/protobuf_input.h";
include "modules/protobuf/src/protobuf_ecmascript.h";
include "modules/protobuf/src/protobuf_types.h";
include "modules/protobuf/src/opvaluevector.h";
include "modules/ecmascript_utils/essyncif.h";
include "modules/ecmascript_utils/esenvironment.h";
include "modules/ecmascript/ecmascript.h";
include "modules/doc/frm_doc.h";
global
{
struct SharedData
{
ES_Environment *esEnvironment;
ES_Runtime *esRuntime;
class ValueCallback : public ES_SyncInterface::Callback
{
public:
ValueCallback()
: runtime(NULL)
{
}
void Reset()
{
if (value.type == VALUE_STRING)
OP_DELETEA((uni_char *) value.value.string);
else if (value.type == VALUE_OBJECT)
runtime->Unprotect(value.value.object);
}
virtual OP_STATUS HandleCallback(Status status, const ES_Value &value)
{
Reset();
this->status = status;
if (status != ESSYNC_STATUS_SUCCESS && status != ES_SyncInterface::Callback::ESSYNC_STATUS_EXCEPTION)
return OpStatus::ERR;
this->value = value;
if (value.type == VALUE_STRING)
{
this->value.value.string = UniSetNewStr(value.value.string);
if (!this->value.value.string)
{
this->value.type = VALUE_UNDEFINED;
return OpStatus::ERR_NO_MEMORY;
}
}
else if (value.type == VALUE_OBJECT)
{
if (!runtime->Protect(value.value.object))
{
this->value.type = VALUE_UNDEFINED;
return OpStatus::ERR_NO_MEMORY;
}
}
return OpStatus::OK;
}
ES_SyncInterface::Callback::Status status;
ES_Value value;
ES_Runtime *runtime;
} syncCallback;
} g_shared;
struct OtStringUtils
{
/* static BOOL IsEqual(const char *a, const char *b, int len)
{
return op_strncmp(a, b, len) == 0;
}*/
typedef const char Type;
template <typename STREAM>
OP_STATUS Construct(SharedData &shared, STREAM &stream, const char *input, int len)
{
return stream.Construct(input, len);
}
};
struct OtESUtils
{
/* static BOOL IsEqual(const char *a, const char *b, int len)
{
return op_strncmp(a, b, len) == 0;
}*/
typedef const char Type;
OP_STATUS Construct(SharedData &shared, OpESInputStream &stream, const char *input, int len)
{
OP_ASSERT(shared.esEnvironment != NULL);
ES_SyncInterface sync(shared.esEnvironment);
RETURN_IF_ERROR(program.Set(input, len));
ES_SyncInterface::EvalData data;
data.program = program.CStr();
RETURN_IF_ERROR(sync.Eval(data, &shared.syncCallback));
if (shared.syncCallback.status != ES_SyncInterface::Callback::ESSYNC_STATUS_SUCCESS)
return OpStatus::ERR;
if (shared.syncCallback.value.type != VALUE_OBJECT)
return OpStatus::ERR;
// FIXME: Should also check if it is an array
return stream.Construct(shared.syncCallback.value.value.object, shared.esEnvironment->GetRuntime());
}
OpString program;
};
struct OtByteUtils
{
/* static BOOL IsEqual(const char *a, const unsigned char *b, int len)
{
const unsigned char *tmp = reinterpret_cast<const unsigned char *>(a);
for (int i = 0; i < len; ++i)
if (*tmp++ != *b++)
return FALSE;
return TRUE;
}*/
typedef const unsigned char Type;
template <typename STREAM>
OP_STATUS Construct(SharedData &shared, STREAM &stream, const unsigned char *input, int len)
{
return stream.Construct(input, len);
}
};
BOOL OtFloatAlmostEqual(double a, double b, double maxrel)
{
if (a == b)
return TRUE;
return op_fabs((a - b) / b) <= maxrel;
}
struct OpTestJSONInputStream : public OpJSONInputStream
{
OP_STATUS Construct(const char *data, int len)
{
RETURN_IF_ERROR(buf.Append(data, len));
return OpJSONInputStream::Construct(buf.GetStorage(), buf.Length());
}
TempBuffer buf;
};
OtScopeTestService_SI::Descriptors g_descriptors;
}
setup
{
g_shared.esEnvironment = NULL;
g_shared.esRuntime = NULL;
}
exit
{
if (g_shared.esEnvironment)
ES_Environment::Destroy(g_shared.esEnvironment);
g_shared.syncCallback.Reset();
}
test("Setup")
{
verify_success(ES_Environment::Create(g_shared.esEnvironment));
verify_not_oom(g_shared.esEnvironment);
g_shared.esRuntime = g_shared.esEnvironment->GetRuntime();
g_shared.syncCallback.runtime = g_shared.esRuntime;
verify(g_shared.esEnvironment->Enabled());
verify_not_oom(g_shared.esRuntime);
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, " [ 4,286 ,31415 , 42,-200,1 ] "}
,{JSON, OpTestJSONInputStream, OtStringUtils, " [ 4,286 ,31415 , 42,-200,1 ] "}
,{XML, OpXMLInputStream, OtStringUtils, "<IntegerMessage><runtimeID>4</runtimeID><objectID>286</objectID><windowID>31415</windowID><scriptID>42</scriptID><htmlID>-200</htmlID><isActive>1</isActive></IntegerMessage>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::VarInt, 4
,2 << 3 | OpProtobufWireFormat::Fixed32, 0x1e, 0x01, 0x00, 0x00 // 286
,3 << 3 | OpProtobufWireFormat::VarInt, 0xb7, 0xf5, 0x1 // 31415
,4 << 3 | OpProtobufWireFormat::VarInt, 84 // 84 = ZigZag(42)
,5 << 3 | OpProtobufWireFormat::Fixed32, 0x38, 0xff, 0xff, 0xff // -200
,6 << 3 | OpProtobufWireFormat::VarInt, 1
}
}
}
{
test("$(name): Integers")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::IntegerMessage msg;
msg.SetRuntimeID(~0u);
msg.SetObjectID(~0u);
msg.SetWindowID(-1);
msg.SetScriptID(-1);
msg.SetHtmlID(-1);
msg.SetIsActive(FALSE);
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::IntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify_success(istream.Read(proxy));
verify(msg.GetRuntimeID() == 4);
verify(msg.GetObjectID() == 286);
verify(msg.GetWindowID() == 31415);
verify(msg.GetScriptID() == 42);
verify(msg.GetHtmlID() == -200);
verify(msg.GetIsActive() == TRUE);
}
}
// Testing values 2^31-1, 2^31, 2^32-1
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[2147483647,2147483648,4294967295]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[2147483647,2147483648,4294967295]"}
,{XML, OpXMLInputStream, OtStringUtils, "<UnsignedIntegerMessage><runtimeID>2147483647</runtimeID><objectID>2147483648</objectID><htmlID>4294967295</htmlID></UnsignedIntegerMessage>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::VarInt, 0xff, 0xff, 0xff, 0xff, 0x07 // 0x7ffffff
,2 << 3 | OpProtobufWireFormat::VarInt, 0x80, 0x80, 0x80, 0x80, 0x08 // 0x8000000
,3 << 3 | OpProtobufWireFormat::Fixed32, 0xff, 0xff, 0xff, 0xff // 0xffffffff
}
}
}
{
test("$(name): Unsigned 32bit Integers")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::UnsignedIntegerMessage msg;
msg.SetRuntimeID(0);
msg.SetObjectID(0);
msg.SetHtmlID(0);
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::UnsignedIntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify_success(istream.Read(proxy));
verify(msg.GetRuntimeID() == 2147483647u);
verify(msg.GetObjectID() == 2147483648u);
verify(msg.GetHtmlID() == 4294967295u);
}
}
// Testing out of bounds detection for uint32 (-1)
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[-1]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[-1]"}
,{XML, OpXMLInputStream, OtStringUtils, "<UnsignedIntegerMessage><runtimeID>-1</runtimeID></UnsignedIntegerMessage>"}
}
{
test("$(name): Unsigned 32bit Out of Bounds (-1)")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::UnsignedIntegerMessage msg;
msg.SetRuntimeID(0);
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::UnsignedIntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify(istream.Read(proxy) == OpStatus::ERR_PARSING_FAILED);
}
}
// Testing out of bounds detection for uint32 (-1337)
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[-1337,0,0]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[-1337,0,0]"}
,{XML, OpXMLInputStream, OtStringUtils, "<UnsignedIntegerMessage><runtimeID>-1337</runtimeID><objectID>0</objectID><htmlID>0</htmlID></UnsignedIntegerMessage>"}
}
{
test("$(name): Unsigned 32bit Out of Bounds (-1337)")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::UnsignedIntegerMessage msg;
msg.SetRuntimeID(0);
msg.SetObjectID(0);
msg.SetHtmlID(0);
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::UnsignedIntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify(istream.Read(proxy) == OpStatus::ERR_PARSING_FAILED);
}
}
// Testing out of bounds detection for uint32 (-2147483648)
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[-2147483648,0,0]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[-2147483648,0,0]"}
,{XML, OpXMLInputStream, OtStringUtils, "<UnsignedIntegerMessage><runtimeID>-2147483648</runtimeID><objectID>0</objectID><htmlID>0</htmlID></UnsignedIntegerMessage>"}
}
{
test("$(name): Unsigned 32bit Out of Bounds (-2147483648)")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::UnsignedIntegerMessage msg;
msg.SetRuntimeID(0);
msg.SetObjectID(0);
msg.SetHtmlID(0);
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::UnsignedIntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify(istream.Read(proxy) == OpStatus::ERR_PARSING_FAILED);
}
}
// Testing out of bounds detection for uint32 (4294967296 > 0xffffffff)
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[4294967296,0,0]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[4294967296,0,0]"}
,{XML, OpXMLInputStream, OtStringUtils, "<UnsignedIntegerMessage><runtimeID>4294967296</runtimeID><objectID>0</objectID><htmlID>0</htmlID></UnsignedIntegerMessage>"}
}
{
test("$(name): Unsigned 32bit Out of Bounds (4294967296)")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::UnsignedIntegerMessage msg;
msg.SetRuntimeID(0);
msg.SetObjectID(0);
msg.SetHtmlID(0);
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::UnsignedIntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify(istream.Read(proxy) == OpStatus::ERR_PARSING_FAILED);
}
}
// Testing out of bounds detection for uint32 (12345678901234567890 > 0xffffffff)
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[12345678901234567890,0,0]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[12345678901234567890,0,0]"}
,{XML, OpXMLInputStream, OtStringUtils, "<UnsignedIntegerMessage><runtimeID>12345678901234567890</runtimeID><objectID>0</objectID><htmlID>0</htmlID></UnsignedIntegerMessage>"}
}
{
test("$(name): Unsigned 32bit Out of Bounds (12345678901234567890)")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::UnsignedIntegerMessage msg;
msg.SetRuntimeID(0);
msg.SetObjectID(0);
msg.SetHtmlID(0);
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::UnsignedIntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify(istream.Read(proxy) == OpStatus::ERR_PARSING_FAILED);
}
}
test("XML: Unsigned 32bit Ignore Whitespace")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::UnsignedIntegerMessage msg;
msg.SetRuntimeID(0);
OtStringUtils::Type input[] = "<UnsignedIntegerMessage><runtimeID> 897456 </runtimeID><objectID>0</objectID><htmlID>0</htmlID></UnsignedIntegerMessage>";
OpXMLInputStream istream;
OtStringUtils helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::UnsignedIntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify_success(istream.Read(proxy));
verify(msg.GetRuntimeID() == 897456);
}
// Testing values +(2^31)-1, -(2^31), -1
// FIXME: The ES input stream cannot read these values, need to figure out why
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{JSON, OpTestJSONInputStream, OtStringUtils, "[0,0,2147483647,-1,-2147483648,0]"}
,{XML, OpXMLInputStream, OtStringUtils, "<IntegerMessage><runtimeID>0</runtimeID><objectID>0</objectID><windowID>2147483647</windowID><scriptID>-1</scriptID><htmlID>-2147483648</htmlID><isActive>0</isActive></IntegerMessage>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::VarInt, 0 // ignore this
,2 << 3 | OpProtobufWireFormat::Fixed32, 0,0,0,0 // ignore this
,3 << 3 | OpProtobufWireFormat::VarInt, 0xff, 0xff, 0xff, 0xff, 0x07 // 2147483647
,4 << 3 | OpProtobufWireFormat::VarInt, 0x03 // ZigZag(-1)
,5 << 3 | OpProtobufWireFormat::Fixed32, 0x00, 0x00, 0x00, 0x80 // -2147483648
,6 << 3 | OpProtobufWireFormat::VarInt, 0 // ignore this
}
}
}
{
test("$(name): Signed 32bit Integers")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::IntegerMessage msg;
msg.SetRuntimeID(~0u);
msg.SetObjectID(~0u);
msg.SetWindowID(-1);
msg.SetScriptID(-1);
msg.SetHtmlID(-1);
msg.SetIsActive(FALSE);
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::IntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify_success(istream.Read(proxy));
verify(msg.GetWindowID() == 2147483647);
verify(msg.GetScriptID() == -1);
verify(msg.GetHtmlID() == -2147483647 - 1); // -2147483648
}
}
// Testing out of bounds on signed int32 (-2147483649)
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{JSON, OpTestJSONInputStream, OtStringUtils, "[0, 0, -2147483649, 0, 0, 0]"}
,{XML, OpXMLInputStream, OtStringUtils, "<IntegerMessage><runtimeID>0</runtimeID><objectID>0</objectID><windowID>-2147483649</windowID><scriptID>0</scriptID><htmlID>0</htmlID><isActive>0</isActive></IntegerMessage>"}
}
{
test("$(name): Signed 32bit Out of Bounds (-2147483649)")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::IntegerMessage msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::IntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify(istream.Read(proxy) == OpStatus::ERR_PARSING_FAILED);
}
}
// Testing out of bounds on signed int32 (2147483648)
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{JSON, OpTestJSONInputStream, OtStringUtils, "[0, 0, 2147483648, 0, 0, 0]"}
,{XML, OpXMLInputStream, OtStringUtils, "<IntegerMessage><runtimeID>0</runtimeID><objectID>0</objectID><windowID>2147483648</windowID><scriptID>0</scriptID><htmlID>0</htmlID><isActive>0</isActive></IntegerMessage>"}
}
{
test("$(name): Signed 32bit Out of Bounds (2147483648)")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::IntegerMessage msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::IntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify(istream.Read(proxy) == OpStatus::ERR_PARSING_FAILED);
}
}
test("XML: Signed 32bit Ignore Whitespace (x < 0)")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::IntegerMessage msg;
msg.SetWindowID(0);
OtStringUtils::Type input[] = "<IntegerMessage><runtimeID>0</runtimeID><objectID>0</objectID><windowID> -897456 </windowID><scriptID>0</scriptID><htmlID>0</htmlID><isActive>0</isActive></IntegerMessage>";
OpXMLInputStream istream;
OtStringUtils helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::IntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify_success(istream.Read(proxy));
verify(msg.GetWindowID() == -897456);
}
test("XML: Signed 32bit Ignore Whitespace (x > 0)")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::IntegerMessage msg;
msg.SetWindowID(0);
OtStringUtils::Type input[] = "<IntegerMessage><runtimeID>0</runtimeID><objectID>0</objectID><windowID> 897456 </windowID><scriptID>0</scriptID><htmlID>0</htmlID><isActive>0</isActive></IntegerMessage>";
OpXMLInputStream istream;
OtStringUtils helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::IntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify_success(istream.Read(proxy));
verify(msg.GetWindowID() == 897456);
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
// TODO: Add some more float numbers, e.g no fraction, with exponent
{ES, OpESInputStream, OtESUtils, "[4.12,3.1415,4,15e3]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[4.12,3.1415,4,15e3]"}
,{XML, OpXMLInputStream, OtStringUtils, "<FloatMessage><fuzzy>4.12</fuzzy><pi>3.1415</pi><sqr>4</sqr><sci>15e3</sci></FloatMessage>"}
}
{
test("$(name): Floating point")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::FloatMessage msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::FloatMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify_success(istream.Read(proxy));
double maxrel = 0.00001;
verify(OtFloatAlmostEqual(msg.GetFuzzy(), 4.12, maxrel));
verify(OtFloatAlmostEqual(msg.GetPi(), 3.1415, maxrel));
verify(OtFloatAlmostEqual(msg.GetSqr(), 4, maxrel));
verify(OtFloatAlmostEqual(msg.GetSci(), 15000, maxrel));
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[\"Macroscopic level/Matter\",\"Molecular level\",\"\"]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[\"Macroscopic level/Matter\",\"Molecular level\",\"\"]"}
,{XML, OpXMLInputStream, OtStringUtils, "<StringMessage><first>Macroscopic level/Matter</first><second>Molecular level</second><empty /></StringMessage>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::LengthDelimited, 24, 'M','a','c','r','o','s','c','o','p','i','c',' ','l','e','v','e','l','/','M','a','t','t','e','r'
,2 << 3 | OpProtobufWireFormat::LengthDelimited, 15, 'M','o','l','e','c','u','l','a','r',' ','l','e','v','e','l'
,3 << 3 | OpProtobufWireFormat::LengthDelimited, 0
}
}
}
{
test("$(name): Strings")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::StringMessage msg;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::StringMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
verify_success(istream.Read(proxy));
verify(msg.GetFirst().Compare("Macroscopic level/Matter") == 0);
verify(msg.GetSecond().Compare("Molecular level") == 0);
verify(msg.GetEmpty().Length() == 0);
verify(msg.GetEmpty().CStr() != NULL);
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[\"yv66vg==\",\"\"]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[\"yv66vg==\",\"\"]"}
,{XML, OpXMLInputStream, OtStringUtils, "<OnesAndZeroes><first>yv66vg==</first><empty /></OnesAndZeroes>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::LengthDelimited, 4, 0xca, 0xfe, 0xba, 0xbe
,2 << 3 | OpProtobufWireFormat::LengthDelimited, 0
}
}
}
{
test("$(name): Bin4ry")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::OnesAndZeroes msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
OpProtobufInstanceProxy proxy(OtScopeTestService::OnesAndZeroes::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(istream.Read(proxy));
verify(msg.GetFirst().Length() == 4);
verify(msg.GetFirst().Extract1(0) == 0xca);
verify(msg.GetFirst().Extract1(1) == 0xfe);
verify(msg.GetFirst().Extract1(2) == 0xba);
verify(msg.GetFirst().Extract1(3) == 0xbe);
verify(msg.GetEmpty().Length() == 0);
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[40,\"Fade to Black\",[256,\"Enter Sandman\",[16384],\"yv66vg==\"]]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[40,\"Fade to Black\",[256,\"Enter Sandman\",[16384],\"yv66vg==\"]]"}
,{XML, OpXMLInputStream, OtStringUtils, "<Outer><a>40</a><b>Fade to Black</b><c><a>256</a><b>Enter Sandman</b><c><a>16384</a></c><d>yv66vg==</d></c></Outer>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::VarInt, 40
,2 << 3 | OpProtobufWireFormat::LengthDelimited, 0xd, 'F','a','d','e',' ','t','o',' ','B','l','a','c','k'
,3 << 3 | OpProtobufWireFormat::LengthDelimited, 30 // InnerMessage size
// Start of InnerMessage
,1 << 3 | OpProtobufWireFormat::VarInt, 0x80, 0x02
,2 << 3 | OpProtobufWireFormat::LengthDelimited, 0xd, 'E','n','t','e','r',' ','S','a','n','d','m','a','n'
,3 << 3 | OpProtobufWireFormat::LengthDelimited, 4 // InnermostMessage size
// Start of InnermostMessage
,1 << 3 | OpProtobufWireFormat::VarInt, 0x80, 0x80, 0x01
,4 << 3 | OpProtobufWireFormat::LengthDelimited, 0x4, 0xca, 0xfe, 0xba, 0xbe
}
}
}
{
test("$(name): Sub-Message")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService::Outer msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
OpProtobufInstanceProxy proxy(OtScopeTestService::Outer::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(istream.Read(proxy));
verify(msg.GetA() == 40);
verify(msg.GetB().Compare(UNI_L("Fade to Black")) == 0);
const OtScopeTestService::Outer::Inner &inner = msg.GetC();
verify(inner.GetA() == 256);
verify(inner.GetB().Compare(UNI_L("Enter Sandman")) == 0);
verify(inner.GetD().Length() == 4);
verify(inner.GetD().Extract1(0) == 0xca);
verify(inner.GetD().Extract1(1) == 0xfe);
verify(inner.GetD().Extract1(2) == 0xba);
verify(inner.GetD().Extract1(3) == 0xbe);
verify(inner.GetC().GetA() == 0x4000);
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[[4,50],[],[5,10,1000],[],[-200,200],[1,0]]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[[4,50],[],[5,10,1000],[],[-200,200],[1,0]]"}
,{XML, OpXMLInputStream, OtStringUtils, "<RepeatedInteger><runtimeIDList><runtimeID>4</runtimeID><runtimeID>50</runtimeID></runtimeIDList><windowIDList><windowID>5</windowID><windowID>10</windowID><windowID>1000</windowID></windowIDList><htmlIDList><htmlID>-200</htmlID><htmlID>200</htmlID></htmlIDList><activationList><activation>1</activation><activation>0</activation></activationList></RepeatedInteger>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::VarInt, 4
,1 << 3 | OpProtobufWireFormat::VarInt, 50
,3 << 3 | OpProtobufWireFormat::VarInt, 5
,3 << 3 | OpProtobufWireFormat::VarInt, 10
,3 << 3 | OpProtobufWireFormat::VarInt, 0xe8, 0x7 // 1000
,5 << 3 | OpProtobufWireFormat::Fixed32, 0x38, 0xff, 0xff, 0xff // -200
,5 << 3 | OpProtobufWireFormat::Fixed32, 0xc8, 0x00, 0x00, 0x00 // 200
,6 << 3 | OpProtobufWireFormat::VarInt, 1
,6 << 3 | OpProtobufWireFormat::VarInt, 0
}
}
}
{
test("$(name): Repeated Integers")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService::RepeatedInteger msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
OpProtobufInstanceProxy proxy(OtScopeTestService::RepeatedInteger::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(istream.Read(proxy));
verify(msg.GetRuntimeIDList().GetCount() == 2);
verify(msg.GetRuntimeIDList().Get(0) == 4);
verify(msg.GetRuntimeIDList().Get(1) == 50);
verify(msg.GetObjectIDList().GetCount() == 0);
verify(msg.GetWindowIDList().GetCount() == 3);
verify(msg.GetWindowIDList().Get(0) == 5);
verify(msg.GetWindowIDList().Get(1) == 10);
verify(msg.GetWindowIDList().Get(2) == 1000);
verify(msg.GetScriptIDList().GetCount() == 0);
verify(msg.GetHtmlIDList().GetCount() == 2);
verify(msg.GetHtmlIDList().Get(0) == -200);
verify(msg.GetHtmlIDList().Get(1) == 200);
verify(msg.GetActivationList().GetCount() == 2);
verify(msg.GetActivationList().Get(0) == 1);
verify(msg.GetActivationList().Get(1) == 0);
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[[4.12,-4.24],[3.1415]]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[[4.12,-4.24],[3.1415]]"}
,{XML, OpXMLInputStream, OtStringUtils, "<RepeatedFloat><fuzzyList><fuzzy>4.12</fuzzy><fuzzy>-4.24</fuzzy></fuzzyList><piList><pi>3.1415</pi></piList></RepeatedFloat>"}
}
{
test("$(name): Repeated Floating point")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService::RepeatedFloat msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
OpProtobufInstanceProxy proxy(OtScopeTestService::RepeatedFloat::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(istream.Read(proxy));
double maxrel = 0.00001;
verify(msg.GetFuzzyList().GetCount() == 2);
verify(OtFloatAlmostEqual(msg.GetFuzzyList().Get(0), 4.12, maxrel));
verify(OtFloatAlmostEqual(msg.GetFuzzyList().Get(1), -4.24, maxrel));
verify(msg.GetPiList().GetCount() == 1);
verify(OtFloatAlmostEqual(msg.GetPiList().Get(0), 3.1415, maxrel));
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[[\"Macroscopic level/Matter\",\"Molecular level\",\"\"]]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[[\"Macroscopic level/Matter\",\"Molecular level\",\"\"]]"}
,{XML, OpXMLInputStream, OtStringUtils, "<RepeatedString><descriptionList><description>Macroscopic level/Matter</description><description>Molecular level</description><description /></descriptionList></RepeatedString>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::LengthDelimited, 24, 'M','a','c','r','o','s','c','o','p','i','c',' ','l','e','v','e','l','/','M','a','t','t','e','r'
,1 << 3 | OpProtobufWireFormat::LengthDelimited, 15, 'M','o','l','e','c','u','l','a','r',' ','l','e','v','e','l'
,1 << 3 | OpProtobufWireFormat::LengthDelimited, 0
}
}
}
{
test("$(name): Repeated Strings")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService::RepeatedString msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
OpProtobufInstanceProxy proxy(OtScopeTestService::RepeatedString::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(istream.Read(proxy));
verify(msg.GetDescriptionList().GetCount() == 3);
verify(msg.GetDescriptionList().Get(0)->Compare("Macroscopic level/Matter") == 0);
verify(msg.GetDescriptionList().Get(1)->Compare("Molecular level") == 0);
verify(msg.GetDescriptionList().Get(2)->Length() == 0);
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[[\"yv66vg==\",\"\"]]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[[\"yv66vg==\",\"\"]]"}
,{XML, OpXMLInputStream, OtStringUtils, "<RepeatedBinary><moccaList><mocca>yv66vg==</mocca><mocca/></moccaList></RepeatedBinary>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::LengthDelimited, 4, 0xca, 0xfe, 0xba, 0xbe
,1 << 3 | OpProtobufWireFormat::LengthDelimited, 0
}
}
}
{
test("$(name): Repeated Bin4ry")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService::RepeatedBinary msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
OpProtobufInstanceProxy proxy(OtScopeTestService::RepeatedBinary::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(istream.Read(proxy));
verify(msg.GetMoccaList().GetCount() == 2);
verify(msg.GetMoccaList().Get(0)->Length() == 4);
verify(msg.GetMoccaList().Get(0)->Extract1(0) == 0xca);
verify(msg.GetMoccaList().Get(0)->Extract1(1) == 0xfe);
verify(msg.GetMoccaList().Get(0)->Extract1(2) == 0xba);
verify(msg.GetMoccaList().Get(0)->Extract1(3) == 0xbe);
verify(msg.GetMoccaList().Get(1)->Length() == 0);
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[[\"42\"],null]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[[\"42\"],null]"}
,{XML, OpXMLInputStream, OtStringUtils, "<OptionalSub><a><a>42</a></a></OptionalSub>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::LengthDelimited, 4
,1 << 3 | OpProtobufWireFormat::LengthDelimited, 2, '4', '2'
}
}
}
{
test("$(name): Optional Sub-Message")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService::OptionalSub msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
OpProtobufInstanceProxy proxy(OtScopeTestService::OptionalSub::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(istream.Read(proxy));
verify(msg.HasA());
verify(msg.GetA() != NULL);
verify(msg.GetA()->GetA().Compare("42") == 0);
verify(!msg.HasB());
verify(msg.GetB() == NULL);
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[[[31415],[-1]]]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[[[31415],[-1]]]"}
,{XML, OpXMLInputStream, OtStringUtils, "<RepeatedSub><itemList><item><value>31415</value></item><item><value>-1</value></item></itemList></RepeatedSub>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::LengthDelimited, 4
// Inner
,1 << 3 | OpProtobufWireFormat::VarInt, 0xb7, 0xf5, 0x1 // 31415
,1 << 3 | OpProtobufWireFormat::LengthDelimited, 6
// Inner
,1 << 3 | OpProtobufWireFormat::VarInt, 0xff, 0xff, 0xff, 0xff, 0xf // -1
}
}
}
{
test("$(name): Repeated Sub-Message")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService::RepeatedSub msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
OpProtobufInstanceProxy proxy(OtScopeTestService::RepeatedSub::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(istream.Read(proxy));
verify(msg.GetItemList().GetCount() == 2);
verify(msg.GetItemList().Get(0)->GetValue() == 31415);
verify(msg.GetItemList().Get(1)->GetValue() == -1);
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[4,null,5,null,-200,1]"}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[4,null,5,null,-200,1]"}
,{XML, OpXMLInputStream, OtStringUtils, "<OptionalInteger><runtimeID>4</runtimeID><windowID>5</windowID><htmlID>-200</htmlID><isActive>1</isActive></OptionalInteger>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::VarInt, 4
,3 << 3 | OpProtobufWireFormat::VarInt, 5
,5 << 3 | OpProtobufWireFormat::Fixed32, 0x38, 0xff, 0xff, 0xff // -200
,6 << 3 | OpProtobufWireFormat::VarInt, 1
}
}
}
{
test("$(name): Optional Integers")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService::OptionalInteger msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
OpProtobufInstanceProxy proxy(OtScopeTestService::OptionalInteger::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify_success(istream.Read(proxy));
verify(msg.HasRuntimeID());
verify(msg.GetRuntimeID() == 4);
verify(!msg.HasObjectID());
verify(msg.HasWindowID());
verify(msg.GetWindowID() == 5);
verify(!msg.HasScriptID());
verify(msg.HasHtmlID());
verify(msg.GetHtmlID() == -200);
verify(msg.HasIsActive());
verify(msg.HasIsActive() == TRUE);
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[\"yv66vg==\",\"ur4=\",\"yv66vg==\",\"ur4=\",[\"yv66vg==\"],[\"ur4=\"]]"}
{JSON, OpTestJSONInputStream, OtStringUtils, "[\"yv66vg==\",\"ur4=\",\"yv66vg==\",\"ur4=\",[\"yv66vg==\"],[\"ur4=\"]]"}
{XML, OpXMLInputStream, OtStringUtils, "<MixedByteType><type1>yv66vg==</type1><type2>ur4=</type2><type3>yv66vg==</type3><type4>ur4=</type4><type5List><type5>yv66vg==</type5></type5List><type6List><type6>ur4=</type6></type6List></MixedByteType>"}
{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::LengthDelimited, 4, 0xca, 0xfe, 0xba, 0xbe
,2 << 3 | OpProtobufWireFormat::LengthDelimited, 2, 0xba, 0xbe
,3 << 3 | OpProtobufWireFormat::LengthDelimited, 4, 0xca, 0xfe, 0xba, 0xbe
,4 << 3 | OpProtobufWireFormat::LengthDelimited, 2, 0xba, 0xbe
,5 << 3 | OpProtobufWireFormat::LengthDelimited, 4, 0xca, 0xfe, 0xba, 0xbe
,6 << 3 | OpProtobufWireFormat::LengthDelimited, 2, 0xba, 0xbe
}
}
}
{
test("$(name): Mixed byte datatype")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::MixedByteType msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::MixedByteType::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify(OpStatus::IsSuccess(helper.Construct(g_shared, istream, input, sizeof(input))));
verify(OpStatus::IsSuccess(istream.Read(proxy)));
verify(msg.GetType1().Extract1(0) == 0xca);
verify(msg.GetType1().Extract1(1) == 0xfe);
verify(msg.GetType1().Extract1(2) == 0xba);
verify(msg.GetType1().Extract1(3) == 0xbe);
verify((UINT8)msg.GetType2().At(0) == 0xba);
verify((UINT8)msg.GetType2().At(1) == 0xbe);
verify(msg.HasType3());
verify(msg.GetType3().Extract1(0) == 0xca);
verify(msg.GetType3().Extract1(1) == 0xfe);
verify(msg.GetType3().Extract1(2) == 0xba);
verify(msg.GetType3().Extract1(3) == 0xbe);
verify(msg.HasType4());
verify((UINT8)msg.GetType4().At(0) == 0xba);
verify((UINT8)msg.GetType4().At(1) == 0xbe);
verify(msg.GetType5List().GetCount() == 1);
verify(msg.GetType5List().Get(0)->Length() == 4);
verify(msg.GetType5List().Get(0)->Extract1(0) == 0xca);
verify(msg.GetType5List().Get(0)->Extract1(1) == 0xfe);
verify(msg.GetType5List().Get(0)->Extract1(2) == 0xba);
verify(msg.GetType5List().Get(0)->Extract1(3) == 0xbe);
verify(msg.GetType6List().GetCount() == 1);
verify(msg.GetType6List().Get(0).Length() == 2);
verify((UINT8)msg.GetType6List().Get(0).At(0) == 0xba);
verify((UINT8)msg.GetType6List().Get(0).At(1) == 0xbe);
}
}
// FIXME: Need to check if nested foreach works, that could solve supporting ES for this test
foreach (NAME, INPUT_BITS, IN_A, IN_B, IN_C, IN_D, IN_E, IN_F, IN_G, IN_H, INPUT_DATA) from
{
{ Empty,
{0, 0, 0, 0, 0, 0, 0, 0},
0, "", {0}, "", 0, "", {0}, "",
"[]"
},
{ Nulls,
{0, 0, 0, 0, 0, 0, 0, 0},
0, "", {0}, "", 0, "", {0}, "",
"[null,null,null,null,null,null,null,null]"
},
{ Integer,
{1, 0, 0, 0, 0, 0, 0, 0},
42, "", {0}, "", 0, "", {0}, "",
"[42]"
},
{ String,
{0, 1, 0, 0, 0, 0, 0, 0},
0, "42", {0}, "", 0, "", {0}, "",
"[null,\"42\"]"
},
{ Bytes,
{0, 0, 1, 0, 0, 0, 0, 0},
0, "", {0xca, 0xfe, 0xba, 0xbe}, "", 0, "", {0}, "",
"[null,null,\"yv66vg==\"]"
},
{ SubMessage,
{0, 0, 0, 1, 0, 0, 0, 0},
0, "", {0}, "42", 0, "", {0}, "",
"[null,null,null,[\"42\"]]"
},
{ IntegerList,
{0, 0, 0, 0, 1, 0, 0, 0},
0, "", {0}, "", 42, "", {0}, "",
"[null,null,null,null,[42]]"
},
{ StringList,
{0, 0, 0, 0, 0, 1, 0, 0},
0, "", {0}, "", 0, "42", {0}, "",
"[null,null,null,null,null,[\"42\"]]"
},
{ BytesList,
{0, 0, 0, 0, 0, 0, 1, 0},
0, "", {0}, "", 0, "", {0xca, 0xfe, 0xba, 0xbe}, "",
"[null,null,null,null,null,null,[\"yv66vg==\"]]"
},
{ SubMessageList,
{0, 0, 0, 0, 0, 0, 0, 1},
0, "", {0}, "", 0, "", {0}, "42",
"[null,null,null,null,null,null,null,[[\"42\"]]]"
},
}
{
test("JSON: $(NAME): Missing input")
{
OtScopeTestService::MissingInput msg;
OpProtobufInstanceProxy proxy(OtScopeTestService::MissingInput::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
OtStringUtils::Type input[] = INPUT_DATA;
OpTestJSONInputStream istream;
verify_success(istream.Construct(input, sizeof(input)));
verify_success(istream.Read(proxy));
bool bits[8] = INPUT_BITS;
if (bits[0])
{
verify(msg.HasA());
verify(msg.GetA() == IN_A);
}
else
verify(!msg.HasA());
if (bits[1])
{
verify(msg.HasB());
verify(msg.GetB().Compare(IN_B) == 0);
}
else
verify(!msg.HasB());
if (bits[2])
{
verify(msg.HasC());
unsigned char data[] = IN_C;
for (unsigned int i = 0; i < ARRAY_SIZE(data); ++i)
verify(data[i] == msg.GetC().Extract1(i));
}
else
verify(!msg.HasC());
if (bits[3])
{
verify(msg.HasD());
verify(msg.GetD() != NULL);
verify(msg.GetD()->GetA().Compare(IN_D) == 0);
}
else
verify(!msg.HasD());
if (bits[4])
{
verify(msg.HasEList());
verify(msg.GetEList().GetCount() == 1);
verify(msg.GetEList().Get(0) == IN_E);
}
else
verify(!msg.HasEList());
if (bits[5])
{
verify(msg.HasFList());
verify(msg.GetFList().GetCount() == 1);
verify(msg.GetFList().Get(0) != NULL);
verify(msg.GetFList().Get(0)->Compare(IN_F) == 0);
}
else
verify(!msg.HasFList());
if (bits[6])
{
verify(msg.HasGList());
verify(msg.GetGList().GetCount() == 1);
unsigned char data[] = IN_G;
ByteBuffer *b = msg.GetGList().Get(0);
verify(b != NULL);
for (unsigned int i = 0; i < ARRAY_SIZE(data); ++i)
verify(data[i] == b->Extract1(i));
verify(msg.GetGList().Get(0)->Length() == ARRAY_SIZE(data));
}
else
verify(!msg.HasGList());
if (bits[7])
{
verify(msg.HasHList());
verify(msg.GetHList().GetCount() == 1);
verify(msg.GetHList().Get(0) != NULL);
verify(msg.GetHList().Get(0)->GetA().Compare(IN_H) == 0);
}
else
verify(!msg.HasHList());
}
}
foreach (name, STREAM_CLS, TYPE_CLS, input_data) from
{
{ES, OpESInputStream, OtESUtils, "[4] "}
,{JSON, OpTestJSONInputStream, OtStringUtils, "[4]"}
,{XML, OpXMLInputStream, OtStringUtils, "<IntegerMessage><runtimeID>4</runtimeID></IntegerMessage>"}
,{PB, OpProtobufInputStream, OtByteUtils,
{1 << 3 | OpProtobufWireFormat::VarInt, 4
}
}
}
{
test("$(name): Missing Fields: Integers")
require success "Setup";
require ESUTILS_SYNCIF_EVAL_SUPPORT;
{
OtScopeTestService_SI::IntegerMessage msg;
TYPE_CLS::Type input[] = input_data;
STREAM_CLS istream;
TYPE_CLS helper;
verify_success(helper.Construct(g_shared, istream, input, sizeof(input)));
OpProtobufInstanceProxy proxy(OtScopeTestService_SI::IntegerMessage::GetMessageDescriptor(&g_descriptors), reinterpret_cast<void *>(&msg));
verify(istream.Read(proxy) == OpStatus::ERR_PARSING_FAILED);
}
}
|
#ifndef StartState_H
#define StartState_H
#include<Ogre.h>
#include "GameState.h"
class StartState: public GameState
{
public:
void enter();
void exit();
void pause();
void resume();
bool frameStarted(GameManager* game, const Ogre::FrameEvent& evt);
bool frameEnded(GameManager* game, const Ogre::FrameEvent& evt);
bool nextLocation(void);
bool mouseMoved(GameManager* game, const OIS::MouseEvent &e) ;
bool mousePressed(GameManager* game, const OIS::MouseEvent &e, OIS::MouseButtonID id );
bool mouseReleased(GameManager* game, const OIS::MouseEvent &e, OIS::MouseButtonID id);
bool keyPressed(GameManager* game, const OIS::KeyEvent &e);
bool keyReleased(GameManager* game, const OIS::KeyEvent &e);
static StartState* getInstance() {return &mStartState;}
bool mouseCheck( int btX, int btY, int btWidth, int btHeight, int mX, int mY );
//bool mouseCheck( float btX, float btY, float btWidth, float btHeight, Ogre::Real mX, Ogre::Real mY );
Ogre::OverlayManager* mOverlayMgr1;
private:
StartState(){}
static StartState mStartState;
bool mContinue;
bool keyState;
//¸¶¿ì½º
int mX, mY, mMouseState;
OIS::Mouse *mMouse;
Ogre::RenderWindow* mWindow;
Ogre::Overlay* mUI_MainOverlay[5];
Ogre::Overlay* mMouseOverlay;
Ogre::OverlayElement* mStartMsg;
};
#endif
|
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int main()
{
int i,j,k,N=1000,cnt=0,numerator,denomentor,ou;
long double p0,p1,pn,q0,q1,qn,ans=0.0;
vector<int>p;
for(i=2;i<=N;i++)
{
p.clear();
j=(int)sqrt(i);
if(j*j==i)
continue;
numerator=j;;
denomentor=1;
denomentor=i-j*j;
numerator=j;
p.push_back((j+numerator)/denomentor);
while(1)
{
if(denomentor==1)
break;
numerator=p[p.size()-1]*denomentor-numerator;
denomentor=(i-numerator*numerator)/denomentor;
if(denomentor!=1)
p.push_back((j+numerator)/denomentor);
else
p.push_back(2*numerator);
}
p0=(long long )sqrtl(i);
p1=(long double)p[0]*p0+1.0;
q0=1LL,q1=(long double)p[0];
for(j=1;j<p.size()-1;j++)
{
pn=(long double)p[j]*p1+p0;
p0=p1;
p1=pn;
qn=(long double)p[j]*q1+q0;
q0=q1,q1=qn;
}
if(p.size()%2!=0)
{
j=p.size()-1;
pn=(long double)p[j]*p1+p0;
p0=p1;
p1=pn;
qn=(long double)p[j]*q1+q0;
q0=q1,q1=qn;
for(j=0;j<p.size()-1;j++)
{
pn=(long double)p[j]*p1+p0;
p0=p1;
p1=pn;
qn=(long double)p[j]*q1+q0;
q0=q1,q1=qn;
}
}
cout<<i<<"\t"<<pn<<"\t"<<qn<<"\n";
if(ans<pn)
ans=pn,ou=i;
}
cout<<"D:"<<ou<<"\n";;
}
|
// Created on: 1993-02-05
// Created by: Jacques GOUSSARD
// Copyright (c) 1993-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 _Contap_TheSegmentOfTheSearch_HeaderFile
#define _Contap_TheSegmentOfTheSearch_HeaderFile
#include <Adaptor2d_Curve2d.hxx>
#include <Contap_ThePathPointOfTheSearch.hxx>
class Standard_DomainError;
class Adaptor3d_HVertex;
class Contap_ThePathPointOfTheSearch;
class Contap_TheSegmentOfTheSearch
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor.
Standard_EXPORT Contap_TheSegmentOfTheSearch();
//! Defines the concerned arc.
void SetValue (const Handle(Adaptor2d_Curve2d)& A);
//! Defines the first point or the last point,
//! depending on the value of the boolean First.
Standard_EXPORT void SetLimitPoint (const Contap_ThePathPointOfTheSearch& V, const Standard_Boolean First);
//! Returns the geometric curve on the surface 's domain
//! which is solution.
const Handle(Adaptor2d_Curve2d)& Curve() const;
//! Returns True if there is a vertex (ThePathPoint) defining
//! the lowest valid parameter on the arc.
Standard_Boolean HasFirstPoint() const;
//! Returns the first point.
const Contap_ThePathPointOfTheSearch& FirstPoint() const;
//! Returns True if there is a vertex (ThePathPoint) defining
//! the greatest valid parameter on the arc.
Standard_Boolean HasLastPoint() const;
//! Returns the last point.
const Contap_ThePathPointOfTheSearch& LastPoint() const;
protected:
private:
Handle(Adaptor2d_Curve2d) arc;
Standard_Boolean hasfp;
Contap_ThePathPointOfTheSearch thefp;
Standard_Boolean haslp;
Contap_ThePathPointOfTheSearch thelp;
};
#define TheVertex Handle(Adaptor3d_HVertex)
#define TheVertex_hxx <Adaptor3d_HVertex.hxx>
#define TheArc Handle(Adaptor2d_Curve2d)
#define TheArc_hxx <Adaptor2d_Curve2d.hxx>
#define ThePathPoint Contap_ThePathPointOfTheSearch
#define ThePathPoint_hxx <Contap_ThePathPointOfTheSearch.hxx>
#define IntStart_Segment Contap_TheSegmentOfTheSearch
#define IntStart_Segment_hxx <Contap_TheSegmentOfTheSearch.hxx>
#include <IntStart_Segment.lxx>
#undef TheVertex
#undef TheVertex_hxx
#undef TheArc
#undef TheArc_hxx
#undef ThePathPoint
#undef ThePathPoint_hxx
#undef IntStart_Segment
#undef IntStart_Segment_hxx
#endif // _Contap_TheSegmentOfTheSearch_HeaderFile
|
#pragma once
#include <iberbar/Utility/Platform.h>
#include <iberbar/Utility/Result.h>
namespace iberbar
{
namespace OS
{
enum class EDpiAwareness
{
Unaware,
System
};
class __iberbarUtilityApi__ CDpiHelper
{
public:
CDpiHelper();
CResult SetAwareness( EDpiAwareness awareness );
EDpiAwareness GetAwareness() const { return m_eAwareness; }
int GetDpi() const;
int GetScaleFactor() const;
public:
EDpiAwareness m_eAwareness;
int m_nScaleFactor;
};
}
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#include<ctime>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
const int tle = 1e8/40;
LL a[60100],b[120100];
int main() {
int t,n;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
LL ans = 0;
for (int i = 0;i < n; i++) scanf("%I64d",&a[i]);
for (int i = 0;i < n; i++) {
scanf("%I64d",&b[i]);b[i+n] = b[i];
ans += (a[i]-b[i])*(a[i]-b[i]);
}
srand(time(NULL));
int ca = tle/n;
while (ca--) {
int k = rand()%n;
LL sum = 0;
bool pass = true;
for (int i = 0;i < n; i++) {
sum += (a[i]-b[i+k])*(a[i]-b[i+k]);
if (sum > ans) {
pass = false;
break;
}
}
if (pass) ans = sum;
}
printf("%I64d\n",ans);
}
return 0;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/GameModeBase.h"
#include "MemoryMatrixProvaGameModeBase.generated.h"
/**
*
*/
UCLASS()
class MEMORYMATRIXPROVA_API AMemoryMatrixProvaGameModeBase : public AGameModeBase
{
GENERATED_BODY()
public:
AMemoryMatrixProvaGameModeBase();
};
|
#include <LoRaTxRx.h>
/*
資料來源
https://www.youtube.com/watch?v=vTSLijvnVxg
輸出要接在 pin 2
*/
int i = 0; // used if calculations are made
int ax = 0; // hundreds .... sadat
int bx = 0; // tens ... kymmenet
int cx = 0; // ones ... ykköset
int dx = 0;
int ex = 190;
int top = 0;
int mov = 0;
int ix = 0;
int kx = 0;
int red = 20;
int green = 70;
int blue = 0;
float dd = 0.0;
float ee = 0.0;
float ff = 0.0;
float gg = 0.0;
float a = 0.0;
float b = 0.0;
float c = 0.0;
float d = 0.0; // using floats one can have readings with
float e = 0.0; // decimal point such as 65.3 km/h
// with floats a decimal point should be
////////////LoRa
const byte MD0_pin = 8, MD1_pin = 9;
LoRaTxRx myLora(51);//with receive buffer
char bufferSendStr[51];//send buffer
////////////LoRa ^
unsigned long detectionTimes; //from 0 to 4,294,967,295 (2^32 - 1).
float mm = 51308.0; // With 10.525Ghz HB100 and desired km/h
// Value is = 51308.0 .... for Mph value is 31888.0
// Formula for value is 1000000 / Fd without V for exmple 1000000/31.36 = 31888
/*
Frequency Fd (V in Km/hr) Fd (V in mph)
9.35 GHz 17.31V 27.85V
9.9 GHz 18.33V 29.49V
10.525 GHz 19.49V 31.36V
10.587 GHz 19.60V 31.54V
10.687 GHz 19.79V 31.84V
24.125 GHz 44.68V 71.89V
*/
char * floatToString(char * outstr, float value, int places, int minwidth=0, bool rightjustify=false) {
// this is used to write a float value to string, outstr. oustr is also the return value.
int digit;
float tens = 0.1;
int tenscount = 0;
int i;
float tempfloat = value;
int c = 0;
int charcount = 1;
int extra = 0;
// make sure we round properly. this could use pow from <math.h>, but doesn't seem worth the import
// if this rounding step isn't here, the value 54.321 prints as 54.3209
// calculate rounding term d: 0.5/pow(10,places)
float d = 0.5;
if (value < 0)
d *= -1.0;
// divide by ten for each decimal place
for (i = 0; i < places; i++)
d/= 10.0;
// this small addition, combined with truncation will round our values properly
tempfloat += d;
// first get value tens to be the large power of ten less than value
if (value < 0)
tempfloat *= -1.0;
while ((tens * 10.0) <= tempfloat) {
tens *= 10.0;
tenscount += 1;
}
if (tenscount > 0)
charcount += tenscount;
else
charcount += 1;
if (value < 0)
charcount += 1;
charcount += 1 + places;
minwidth += 1; // both count the null final character
if (minwidth > charcount){
extra = minwidth - charcount;
charcount = minwidth;
}
if (extra > 0 and rightjustify) {
for (int i = 0; i< extra; i++) {
outstr[c++] = ' ';
}
}
// write out the negative if needed
if (value < 0)
outstr[c++] = '-';
if (tenscount == 0)
outstr[c++] = '0';
for (i=0; i< tenscount; i++) {
digit = (int) (tempfloat/tens);
itoa(digit, &outstr[c++], 10);
tempfloat = tempfloat - ((float)digit * tens);
tens /= 10.0;
}
// if no places after decimal, stop now and return
// otherwise, write the point and continue on
if (places > 0)
outstr[c++] = '.';
// now write out each decimal place by shifting digits one by one into the ones place and writing the truncated value
for (i = 0; i < places; i++) {
tempfloat *= 10.0;
digit = (int) tempfloat;
itoa(digit, &outstr[c++], 10);
// once written, subtract off that digit
tempfloat = tempfloat - (float) digit;
}
if (extra > 0 and not rightjustify) {
for (int i = 0; i< extra; i++) {
outstr[c++] = ' ';
}
}
outstr[c++] = '\0';
return outstr;
}
void setup()
{
pinMode(2, INPUT);
pinMode(3, OUTPUT);
////////////LoRa
pinMode(MD0_pin, OUTPUT);
pinMode(MD1_pin, OUTPUT);
digitalWrite(MD0_pin, LOW);
digitalWrite(MD1_pin, LOW);
////////////LoRa ^
detectionTimes = 0;
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println ("Connection OK");
}
void loop()
{
//利用脈衝來讀取HB100訊號
while (dd < 4.0){
a = pulseIn(2, HIGH, 50000); // loop here in while-loop
b = pulseIn(2, LOW, 50000); // if no movenment detected
dd = mm/(a+b);
} // go out of while-loop when dd = > 4
//read input 4 times with 50mS delay between reads
a = pulseIn(2, HIGH, 50000); // wait 50000uS for pulse (0,05 sec)
b = pulseIn(2, LOW, 50000); // to complete (over 10Hz needed)
dd = mm/(a+b); // as 0.05 LOW + 0.05 HIGH = 0.1 sec
delay (50);
a = pulseIn(2, HIGH, 50000);
b = pulseIn(2, LOW, 50000);
ee = mm/(a+b);
delay (50);
a = pulseIn(2, HIGH, 50000);
b = pulseIn(2, LOW, 50000);
ff = mm/(a+b);
delay (50);
a = pulseIn(2, HIGH, 50000);
b = pulseIn(2, LOW, 50000);
gg = mm/(a+b);
// Make strange misread values like 4158344 to zeros ( 0 )
if (dd > 255.0) {
dd = 0.0;
}
if (ee > 255.0) {
ee = 0.0;
}
if (ff > 255.0) {
ff = 0.0;
}
if (gg > 255.0) {
gg = 0.0;
}
//**********"BubbleSort" the readings dd highest gg lowest
for (i = 0; i<4; i++) {
if (dd > ee) {
d = dd;
e = ee;
ee = d;
dd = e;
}
if (ee > ff) {
d = ee;
e = ff;
ee = e;
ff = d;
}
if (ff > gg) {
d = ff;
e = gg;
ff = e;
gg = d;
}
}
c = (ee + ff)/2;
// ignore highes and lowest value dd and gg ****************
// and continue with average of ee and ff
if (c > 999.0) { //prints ovf instead of 0 without this
c = 0.0; // not needed when using low limit in next if-sentence
}
if (((ff - ee) > 4.0) || ((ee - ff) > 4.0)) {
c = 0.0; // filter strange things
} // if ff differs from ee more than 4
if ((c > 4.0) && c < (255.0)) { // If reading is over 4 and less than
detectionTimes++;
sprintf(bufferSendStr, "%lu,\t", detectionTimes);
Serial.print(bufferSendStr);
Serial.print(c, 2); //255 then print it to serial
Serial.print(" km/h \r\n");
////////////LoRa
myLora.sendString(bufferSendStr);
// send the same message to others
floatToString(bufferSendStr, c , 2);
myLora.sendString(bufferSendStr);
myLora.sendString(" km/h \r\n");
////////////LoRa ^
}
delay(20);
}
|
//
// Created by manout on 18-3-27.
//
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
int w;
int count_ = 1;
vector<int> snacks;
void bag(int w, int i)
{
//sort(snacks.begin(), snacks.end());
//vector<vector<int>> mat(snacks.size() + 1, vector<int>(w + 1, 0));
if (i < 0)return ;
if (w == 0)
{
++count_;
return;
}
if (snacks[i] > w )
{
bag(w, i - 1);
return ;
}
if (snacks[i] < w)
{
++count_;
bag(w - snacks[i], i - 1);
bag(w, i - 1);
}
}
|
#include "Week.h"
#include <string>
Week::Week(string date) {//might need to check that the substr is correct
this->date = date;
int mon = stoi(date.substr(3, 1));
int daysInMonth = 1;
if (mon == 04 || mon == 06 || mon == 9 || mon == 11) {
daysInMonth = 30;
}
else if (mon == 02) {
int year = stoi(date.substr(6, 3));
if (year % 4 == 0 && year % 100 && year % 400) {
daysInMonth = 29;
}
else {
daysInMonth = 28;
}
}
else {
daysInMonth = 31;
}
for (int i = 0; i < 7; i++) {
int dateOfWeek = (stoi(date.substr(0, 1)) + i);
if (dateOfWeek == daysInMonth) {
dateOfWeek = 1;
int month = stoi(date.substr(2, 2));
int year = stoi(date.substr(5, 4));
if (mon == 12) {//checking that if it's the end of the year
year++;
date = "01/01/" + to_string(year);
}
else {//checks if it's the end of the month
date = "01/" + to_string(month + 1) + to_string(year);
}
}
Day dayx(date);
week.push_back(dayx);
}
}
Week::~Week() {}
Day Week::getDay(string day) {
int startDateOfWeek = stoi(date.substr(0,2));
int theDay = stoi(day.substr(0.2));
int dayOfWeek = startDateOfWeek - theDay;
return week.at(dayOfWeek -1);
}
string Week::toString() {
string result = "";
result = date;
return result;
}
|
#ifndef PAD_H
#define PAD_H
#include "bloco.h"
class Bloco;
class Pad
{
private:
Bloco *pad;
Vertice vertices_elipse[15];
double centro_x, centro_y, raio_x, raio_y, valor_tamanho_profundidade, valor_tamanho_altura, valor_tamanho_base;
int num_segmentos;
void monta_elipses();
public:
/// CONSTRUTOR & DESTRUTOR
Pad(Vertice *vertice_ponto, double valor_tamanho_base, double valor_tamanho_altura, double valor_tamanho_profundidade);
virtual ~Pad();
/// GETTERS
inline Bloco *pega_pad() { monta_elipses(); return pad; }
inline Vertice *pega_Vertices_elipse() { return vertices_elipse; }
inline Bloco *pega_Pad() { return pad; }
inline double pega_Centro_x() const { return centro_x; }
inline double pega_Centro_y() const { return centro_y; }
inline double pega_Raio_x() const { return raio_x; }
inline double pega_Raio_y() const { return raio_y; }
inline int pega_Num_segmentos() const { return num_segmentos; }
inline double pega_Valor_tamanho_profundidade() const { return valor_tamanho_profundidade; }
inline double pega_Valor_tamanho_altura() const { return valor_tamanho_altura; }
inline double pega_Valor_tamanho_base() const { return valor_tamanho_base; }
/// SETTERS
inline void define_pad(Bloco *novo_bloco) { pad = novo_bloco; }
inline void insere_vertice_elipse(int pos, Vertice v1) { vertices_elipse[pos] = v1; }
inline void define_Pad(Bloco *pad) { this->pad = pad; }
inline void define_Centro_x(double centro_x) { this->centro_x = centro_x; }
inline void define_Centro_y(double centro_y) { this->centro_y = centro_y; }
inline void define_Raio_x(double raio_x) { this->raio_x = raio_x; }
inline void define_Raio_y(double raio_y) { this->raio_y = raio_y; }
inline void define_Num_segmentos(int num_segmentos) { this->num_segmentos = num_segmentos; }
inline void define_Valor_tamanho_profundidade(double valor_tamanho_profundidade) { this->valor_tamanho_profundidade = valor_tamanho_profundidade; }
inline void define_Valor_tamanho_altura(double valor_tamanho_altura) { this->valor_tamanho_altura = valor_tamanho_altura; }
inline void define_Valor_tamanho_base(double valor_tamanho_base) { this->valor_tamanho_base = valor_tamanho_base; }
};
#endif // PAD_H
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Triad National Security, LLC. This file is part of the
// Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms
// in the LICENSE file found in the top-level directory of this distribution.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef NOX_THYRA_MODEL_EVALUATOR_TPETRA_DECL_HPP
#define NOX_THYRA_MODEL_EVALUATOR_TPETRA_DECL_HPP
#include <Teuchos_Comm.hpp>
#include <Tpetra_Vector.hpp>
#include <Tpetra_Map_decl.hpp>
#include <Tpetra_Import.hpp>
#include <Tpetra_Export.hpp>
#include <Tpetra_CrsGraph_decl.hpp>
#include <Tpetra_CrsMatrix_decl.hpp>
//teuchos support
#include <Teuchos_RCP.hpp>
//#include <MueLu_HierarchyManager.hpp>
#include <MueLu_TpetraOperator.hpp>
#include "Thyra_StateFuncModelEvaluatorBase.hpp"
#include "Mesh.h"
#include "error_estimator.h"
#include "elem_color.h"
#include "timestep.hpp"
#include "post_process.h"
#include "random_distribution.h"
#include <boost/ptr_container/ptr_vector.hpp>
#if 0
template <typename LocalOrdinal,typename GlobalOrdinal>
class GreedyTieBreak : public Tpetra::Details::TieBreak<LocalOrdinal,GlobalOrdinal>
{
public:
GreedyTieBreak() { }
virtual bool mayHaveSideEffects() const {
return true;
}
virtual std::size_t selectedIndex(GlobalOrdinal /* GID */,
const std::vector<std::pair<int,LocalOrdinal> > & pid_and_lid) const
{
// always choose index of pair with smallest pid
const std::size_t numLids = pid_and_lid.size();
std::size_t idx = 0;
int minpid = pid_and_lid[0].first;
std::size_t minidx = 0;
for (idx = 0; idx < numLids; ++idx) {
if (pid_and_lid[idx].first < minpid) {
minpid = pid_and_lid[idx].first;
minidx = idx;
}
}
return minidx;
}
};
#endif
template<class Scalar> class ModelEvaluatorTPETRA;
template<class Scalar>
Teuchos::RCP<ModelEvaluatorTPETRA<Scalar> >
modelEvaluatorTPETRA( const Teuchos::RCP<const Epetra_Comm>& comm,
Mesh &mesh,
Teuchos::ParameterList plist
);
/// Implentation of timestep with MPI and OpenMP support.
template<class Scalar>
class ModelEvaluatorTPETRA
: public ::timestep<Scalar>, public ::Thyra::StateFuncModelEvaluatorBase<Scalar>
{
public:
/// Constructor
ModelEvaluatorTPETRA( const Teuchos::RCP<const Epetra_Comm>& comm,
Mesh *mesh,
Teuchos::ParameterList plist
);
/// Destructor
~ModelEvaluatorTPETRA(){};
typedef Tpetra::Vector<>::scalar_type scalar_type;
/// Satisfy Thyra::StateFuncModelEvaluatorBase interface
Teuchos::RCP<const ::Thyra::VectorSpaceBase<Scalar> > get_x_space() const{return x_space_;};
/// Satisfy Thyra::StateFuncModelEvaluatorBase interface
Teuchos::RCP<const ::Thyra::VectorSpaceBase<Scalar> > get_f_space() const{return f_space_;};
/// Satisfy Thyra::StateFuncModelEvaluatorBase interface
::Thyra::ModelEvaluatorBase::InArgs<Scalar> createInArgs() const{return prototypeInArgs_;};
/// Satisfy Thyra::StateFuncModelEvaluatorBase interface
::Thyra::ModelEvaluatorBase::InArgs<Scalar> getNominalValues() const{return nominalValues_;};
/// Satisfy Thyra::StateFuncModelEvaluatorBase interface
Teuchos::RCP< ::Thyra::PreconditionerBase< Scalar > > create_W_prec() const;
Teuchos::RCP< ::Thyra::LinearOpBase< Scalar > > create_W_op() const;
void initialize();
void finalize();
double advance();
void write_exodus();
void evalModelImpl(
const ::Thyra::ModelEvaluatorBase::InArgs<Scalar> &inArgs,
const ::Thyra::ModelEvaluatorBase::OutArgs<Scalar> &outArgs
) const;
private:
typedef Tpetra::Vector<>::global_ordinal_type global_ordinal_type;
typedef Tpetra::Vector<>::local_ordinal_type local_ordinal_type;
typedef Tpetra::Vector<>::node_type node_type;
typedef Tpetra::CrsMatrix<scalar_type,local_ordinal_type, global_ordinal_type,
node_type>::crs_graph_type crs_graph_type;
typedef Tpetra::global_size_t global_size_t;
typedef Tpetra::Vector<scalar_type, local_ordinal_type,
global_ordinal_type, node_type> vector_type;
typedef Tpetra::Map<local_ordinal_type, global_ordinal_type, node_type> map_type;
typedef Tpetra::Import<local_ordinal_type, global_ordinal_type,
node_type> import_type;
typedef Tpetra::Export<local_ordinal_type, global_ordinal_type,
node_type> export_type;
typedef Tpetra::CrsMatrix<scalar_type,local_ordinal_type, global_ordinal_type,
node_type> matrix_type;
typedef Tpetra::MultiVector<scalar_type, local_ordinal_type,
global_ordinal_type, node_type> mv_type;
::Thyra::ModelEvaluatorBase::OutArgs<Scalar> createOutArgsImpl() const;
/// Allocates and returns the Jacobian matrix graph.
virtual Teuchos::RCP<crs_graph_type> createGraph();
Teuchos::RCP<crs_graph_type> createOverlapGraph();
Mesh* mesh_;
int update_mesh_data();
void restart(Teuchos::RCP<vector_type> u);//,Teuchos::RCP<vector_type> u_old);
void set_test_case();
double time_;
int ex_id_;
int output_step_;
int numeqs_;
int num_owned_nodes_;
int num_overlap_nodes_;
int numsteps_;
Teuchos::RCP<const Thyra::VectorSpaceBase<Scalar> > x_space_;
Teuchos::RCP<const map_type > x_overlap_map_;
Teuchos::RCP<const map_type > x_owned_map_;
Teuchos::RCP<const map_type > node_overlap_map_;
Teuchos::RCP<const map_type > node_owned_map_;
Teuchos::RCP<const Thyra::VectorSpaceBase<Scalar> > f_space_;
Teuchos::RCP<const import_type > importer_;
Teuchos::RCP<const export_type > exporter_;
Teuchos::RCP<NOX::Solver::Generic> solver_;
Teuchos::RCP<NOX::Solver::Generic> predictor_;
Teuchos::RCP<vector_type> u_old_;
Teuchos::RCP<vector_type> u_old_old_;
Teuchos::RCP<vector_type> u_new_;
Teuchos::RCP<vector_type> pred_temp_;
Teuchos::RCP<vector_type> x_;
Teuchos::RCP<vector_type> y_;
Teuchos::RCP<vector_type> z_;
Teuchos::RCP<mv_type> muelucoords_;
Teuchos::RCP<crs_graph_type> W_graph_;
Teuchos::RCP<crs_graph_type> W_overlap_graph_;
Teuchos::RCP<matrix_type> P_;
Teuchos::RCP<matrix_type> P;
//Teuchos::RCP<MueLu::HierarchyManager<scalar_type,local_ordinal_type, global_ordinal_type, node_type>> mueluFactory_;
Teuchos::RCP<MueLu::TpetraOperator<scalar_type,local_ordinal_type, global_ordinal_type, node_type> > prec_;
int nnewt_;
double dt_;
double dtold_;
double t_theta_;
double t_theta2_;
Teuchos::ParameterList paramList;
Thyra::ModelEvaluatorBase::InArgs<Scalar> nominalValues_;
//Teuchos::RCP< ::Thyra::VectorBase<scalar_type> > x0_;
Teuchos::RCP<vector_type > x0_;
Thyra::ModelEvaluatorBase::InArgs<Scalar> prototypeInArgs_;
Thyra::ModelEvaluatorBase::OutArgs<Scalar> prototypeOutArgs_;
Teuchos::RCP<::Thyra::VectorBase< Scalar > > scaling_;
void update_left_scaling();
void print_norms();
/// Initialize and create the NOX and linear solvers.
void init_nox();
/// Satisfy Thyra::StateFuncModelEvaluatorBase interface
void set_W_factory(const Teuchos::RCP<const ::Thyra::LinearOpWithSolveFactoryBase<Scalar> >& W_factory);
Teuchos::RCP<const ::Thyra::LinearOpWithSolveFactoryBase<Scalar> > W_factory_;
void init(Teuchos::RCP<vector_type> u);
std::vector<std::string> *varnames_;
//do we want to move these typedefs to function_def.hpp? would need to do it for nemesis class as well
//typedef double (*RESFUNC)(const GPUBasis * const * basis,
typedef double (*RESFUNC)(GPUBasis * basis[],
const int &i,
const double &dt_,
const double &dtold_,
const double &t_theta_,
const double &t_theta2_,
const double &time,
const int &eqn_id,
const double &vol,
const double &rand);
std::vector<RESFUNC> *residualfunc_;
typedef double (*PREFUNC)(const GPUBasis *basis,
const int &i,
const int &j,
const double &dt_,
const double &t_theta_,
const int &eqn_id);
std::vector<PREFUNC> *preconfunc_;
typedef double (*DBCFUNC)(const double &x,
const double &y,
const double &z,
const double &t);
std::vector<std::map<int,DBCFUNC>> *dirichletfunc_;
typedef double (*INITFUNC)(const double &x,
const double &y,
const double &z,
const int &eqn_id);
typedef double (*NBCFUNC)(const GPUBasis *basis,
const int &i,
const double &dt_,
const double &dtold_,
const double &t_theta_,
const double &t_theta2_,
const double &time);
std::vector<std::map<int,NBCFUNC>> *neumannfunc_;
std::vector<INITFUNC> *initfunc_;
typedef void (*PARAMFUNC)(Teuchos::ParameterList *plist);
std::vector<PARAMFUNC> paramfunc_;
//PARAMFUNC paramfunc_;
Teuchos::RCP<Teuchos::Time> ts_time_import;
Teuchos::RCP<Teuchos::Time> ts_time_resfill;
Teuchos::RCP<Teuchos::Time> ts_time_precfill;
Teuchos::RCP<Teuchos::Time> ts_time_nsolve;
Teuchos::RCP<Teuchos::Time> ts_time_view;
Teuchos::RCP<Teuchos::Time> ts_time_iowrite;
Teuchos::RCP<Teuchos::Time> ts_time_temperr;
Teuchos::RCP<Teuchos::Time> ts_time_predsolve;
//RCP<Teuchos::Time> ts_time_ioread;
//hacked stuff for elem_color
Teuchos::RCP<elem_color> Elem_col;
Teuchos::RCP<const Epetra_Comm> Comm;
//Kokkos::View<const double*, Kokkos::MemoryTraits<Kokkos::RandomAccess>> x_1dra;
//Kokkos::View<const double*> x_1dra;
//TUSAS_CUDA_CALLABLE_MEMBER void set_basis( GPUBasis &basis, const std::string elem_type) const;
boost::ptr_vector<error_estimator> Error_est;
boost::ptr_vector<post_process> post_proc;
void postprocess();
void predictor();
void initialsolve();
double estimatetimestep();
void temporalpostprocess(boost::ptr_vector<post_process>pp);
boost::ptr_vector<post_process> temporal_est;
boost::ptr_vector<post_process> temporal_norm;
boost::ptr_vector<post_process> temporal_dyn;
void setadaptivetimestep();
void init_P_();
std::string outfilename;
std::vector<int> localprojectionindices_;
Teuchos::RCP<random_distribution> randomdistribution;
bool predictor_step;
bool corrector_step;
};
//==================================================================
#include "ModelEvaluatorTPETRA_def.hpp"
//==================================================================
#endif
|
#pragma once
#include "GameNode.h"
#include "IsoTile.h"
class SubIsoMap : public GameNode
{
private:
bool isDebug;
int currentTile;
RECT rc[TILE_SIZE_X][TILE_SIZE_Y];
int frameX, frameY;
public:
SubIsoMap();
~SubIsoMap();
HRESULT Init();
void Release();
void Update();
void Render(HDC hdc);
};
|
#include "pch.h"
#include "CppUnitTest.h"
#include "../laba6.1.2/Source.cpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Test612
{
TEST_CLASS(Test612)
{
public:
TEST_METHOD(TestMethod1)
{
int c;
int a[20]{ 9,- 20, - 20, 21, 7, - 12, 8, - 18, - 8, 32, 37, 18, - 14, - 12, 28, 32, - 14, 1, - 10, - 2 };
c = Sum(a, 20, 1);
Assert::AreEqual(c, 126);
}
};
}
|
#ifndef ETW_CONFIG_EXPRESSION_INTERFACE_H_
#define ETW_CONFIG_EXPRESSION_INTERFACE_H_
#include "ConfigurationInterface.h"
#include "OptionInterface.h"
namespace etw {
class ExpressionInterface
{
public:
int getResult(ConfigurationInterface *cfg, OptionInterface **op);
};
}
#endif
|
#include <GL/glut.h>
#include "Posizione.h"
Posizione::Posizione() {
}
Posizione::Posizione(double x1, double y1, double z1) {
x = x1;
y = y1;
z = z1;
}
double Posizione::getX() {
return x;
}
double Posizione::getY() {
return y;
}
double Posizione::getZ() {
return z;
}
void Posizione::setX(double x1) {
x = x1;
}
void Posizione::setY(double y1) {
y = y1;
}
void Posizione::setZ(double z1) {
z = z1;
}
|
class Solution {
public:
string removeKdigits(string num, int k) {
int n = num.size();
if( n<= k ) {
return "0";
}
while(k) {
int i = 0;
// for finding the peaks.
while(i+1<n && num[i+1]>=num[i]) i++;
num.erase(i,1);
k--;
}
// for deleting cases for 0 0 2 0 0 or 0 0 0 0 0
int j = 0;
while( j < n && num[j] == '0' ) j++;
num = num.substr(j);
return num=="" ? "0" : num;
}
};
|
/* --- This file is distributed under the MIT Open Source License, as detailed
in "LICENSE.TXT" in the root of this repository --- */
#ifndef HURCHALLA_PROGRAMMING_BY_CONTRACT_H_INCLUDED
#define HURCHALLA_PROGRAMMING_BY_CONTRACT_H_INCLUDED
/*
These are the main contract assertion macros:
HPBC_PRECONDITION(x), HPBC_PRECONDITION2(x), HPBC_PRECONDITION3(x)
HPBC_POSTCONDITION(x), HPBC_POSTCONDITION2(x), HPBC_POSTCONDITION3(x)
HPBC_INVARIANT(x), HPBC_INVARIANT2(x), HPBC_INVARIANT3(x)
HPBC_ASSERT(x), HPBC_ASSERT2(x), HPBC_ASSERT3(x)
They are purposely implemented as macros instead of inline functions, as
described at the end of this section.
Precondition asserts are intended to check that a precondition is satisfied.
Postcondition asserts are intended to check that a postcondition is satisfied.
Invariant asserts are intended to check that invariants are true.
Plain asserts are intended to check that logical assumptions are true.
The number at the end of an assertion macro name specifies the assertion level.
The assertion macros without a number at the end (precondition, postcondition,
invariant, assumption) can be viewed as having an implicit level of 1. For
more detail:
An unnumbered (implicit level 1) assert can be viewed as a "normal" assert
and is the go-to assert level, useful for when you either don't care about
levels at all, or for when an assert is unremarkable in the time it will
take to check while the program is running. [Note that if you are able to
perform a check at compile time, you should always prefer static_assert()
in C++ or _Static_assert() in C, since it is always free of cost and fails
during compilation.]
A level 2 assert is intended for checks that you know will be unusually
expensive to perform.
A level 3 assert is for checks that are incredibly expensive, such as a check
with a larger order of computational complexity than the function that
contains it. It could be considered a "safe mode" assert.
When NDEBUG is defined in a translation unit, all of these asserts will be
replaced with a no-op, regardless of assertion level.
When NDEBUG is undefined, each assert will be replaced with first a call to a
trivial getter function [hpbcGetHandlerAssertLevel()] to determine the
program-wide assert level. Then, this will be followed by a conditional to
skip the assert check if your particular assert's level is greater than the
program-wide assert level. If this occurs and you are using link-time-
optimization, the linker will typically see that the code will always skip the
assert, and it will remove the getter call and the conditional and the assert,
resulting in a no-op. However, the effects of link-time-optimization depend
upon your linker implementation.
For a given compiler, by default NDEBUG is typically defined in release builds
and undefined in debug builds. It's a standard macro (see the C or C++
documentation of assert()) and you can predefine it (or not) for any
compilation project - for example by using -D in gcc or clang, or in MSVC++
via either command line option /D or by UI setting "preprocessor definitions".
Note: the assertions are all purposely implemented as macros instead of inline
functions. Implementing them as functions involves at least two unavoidable
problems, which is very likely the reason the standard assert() from assert.h
is also implemented as a macro. First, the assserts use the C/C++ standard
predefined macros __FILE__ and __LINE_ to show the location of an assertion
failure. If assertions were implemented as functions, this could not work,
since __FILE__ and __LINE_ would provide locations in the called assert
functions rather than the location of the assert in the caller. Second, the
contract assertions are designed to guarantee zero overhead when NDEBUG is
defined in a translation unit. If assertions were implemented as functions,
the argument given to an assert could break that guarantee. For example
consider: assert(isGood()). If isGood() has side effects, the compiler would
always need to call it, even if a hypothetical assert function (instead of
macro) had an empty body. Even if isGood() has no side effects, it's possible
the compiler and linker would miss an optimization we ordinarily would expect
to remove the isGood() call. Missed optimizations might be unlikely, but the
lack of guarantee and the side-effects issue would make the overhead (zero?)
of these contract asserts unpredictable in general. This behavior would also
be inconsistent with the standard library assert() macro defined in assert.h.
Assertions implemented as macros do not have these problems. However, macros
have the problem that they 'pollute' the namespace. If your souce code uses
any names identitical to one of the macro names in this file, then you may
either get errors while compiling, or bugs from the compiler silently
replacing your name with a macro expansion. Consequently, you *must* treat all
the assertion macro names in this file as reserved keywords throughout your
projects. If the given assertion names here are impossible or undesirable for
you to use, you can edit this file to change the macro names. To minimize the
pollution aspect, the current macro names are all-caps and prefixed with
"HPBC". Nevertheless, potential macro name collision is a danger.
*/
/*
Some ideas in this file were inspired by
https://www.youtube.com/watch?v=1QhtXRMp3Hg
http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/
*/
/*
Ordinarily, you shouldn't change anything in this file.
*/
#if defined(NDEBUG)
# if 0
/* HPBC_DO_NOTHING() is written to avoid 'unused variable' warnings during
compilation. Note: for C++ prior to C++20, the line below will not
compile if the arg contains a lambda. Perhaps more importantly, this
version below doesn't seem to achieve the goal of avoiding 'unused
variable' warnings for the Intel C/C++ compiler, or for all the recent
MSVC compilers. The alternative version in the #else seems to be
preferable to this version. */
# define HPBC_DO_NOTHING(...) ((void)sizeof(__VA_ARGS__))
# else
/* Alternative version that will work C++ pre-20 with lambdas in contract
args, and that will work with Intel C/C++ compiler and with MSVC */
# ifdef _MSC_VER
# define HPBC_DO_NOTHING(...) (false ? (void)(__VA_ARGS__) : (void)0)
# else
# define HPBC_DO_NOTHING(...) ((void)(true || (__VA_ARGS__)))
# endif
//# define HPBC_DO_NOTHING(...) (while (false) (void)(__VA_ARGS__))
//# define HPBC_DO_NOTHING(...) do { (void)(__VA_ARGS__); } while (0, 0)
# endif
# define HPBC_PRECONDITION(...) HPBC_DO_NOTHING(__VA_ARGS__)
# define HPBC_PRECONDITION2(...) HPBC_DO_NOTHING(__VA_ARGS__)
# define HPBC_PRECONDITION3(...) HPBC_DO_NOTHING(__VA_ARGS__)
# define HPBC_POSTCONDITION(...) HPBC_DO_NOTHING(__VA_ARGS__)
# define HPBC_POSTCONDITION2(...) HPBC_DO_NOTHING(__VA_ARGS__)
# define HPBC_POSTCONDITION3(...) HPBC_DO_NOTHING(__VA_ARGS__)
# define HPBC_INVARIANT(...) HPBC_DO_NOTHING(__VA_ARGS__)
# define HPBC_INVARIANT2(...) HPBC_DO_NOTHING(__VA_ARGS__)
# define HPBC_INVARIANT3(...) HPBC_DO_NOTHING(__VA_ARGS__)
# define HPBC_ASSERT(...) HPBC_DO_NOTHING(__VA_ARGS__)
# define HPBC_ASSERT2(...) HPBC_DO_NOTHING(__VA_ARGS__)
# define HPBC_ASSERT3(...) HPBC_DO_NOTHING(__VA_ARGS__)
# if defined(__cplusplus)
# define HPBC_FALSE_VALUE (false)
# else
# define HPBC_FALSE_VALUE (0)
# endif
# define HPBC_PRECONDITION_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
# define HPBC_PRECONDITION2_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
# define HPBC_PRECONDITION3_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
# define HPBC_POSTCONDITION_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
# define HPBC_POSTCONDITION2_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
# define HPBC_POSTCONDITION3_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
# define HPBC_INVARIANT_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
# define HPBC_INVARIANT2_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
# define HPBC_INVARIANT3_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
# define HPBC_ASSERT_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
# define HPBC_ASSERT2_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
# define HPBC_ASSERT3_MACRO_IS_ACTIVE HPBC_FALSE_VALUE
#else
# if !defined(HPBC_ENABLE_FULL_FEATURES)
/* wrap the standard library assert */
# if defined(__cplusplus)
# include <cassert>
# else
# include <assert.h>
# endif
# define HPBC_LEVEL_ASSERT(LEVEL, ...) assert(__VA_ARGS__)
# define HPBC_LEVEL_ASSERT_PRE(LEVEL, ...) assert(__VA_ARGS__)
# define HPBC_HANDLER_LEVEL 3
# define HPBC_HANDLER_PRECOND_LEVEL 3
# else /* the normal Programming by Contract features */
# include "hurchalla/util/assert_handler.h"
/* If this is C++, we can (probably) detect if exceptions are enabled by
checking the gcc/clang macro __EXCEPTIONS, msvc's macro _CPPUNWIND, and
the official but not always supported C++98 macro __cpp_exceptions. */
# if defined(__cplusplus) && (defined(__EXCEPTIONS) || defined(_CPPUNWIND) \
|| (defined(__cpp_exceptions) && __cpp_exceptions != 0))
// C++ with exceptions: treat an exception as a failure during assert
# define HPBC_BASIC_ASSERT(...) do { \
bool assertPassed = false; \
try { if (__VA_ARGS__) assertPassed = true; } \
catch (...) {} \
if (!assertPassed) \
hpbcAssertHandler(#__VA_ARGS__, __FILE__, __LINE__);\
} while(0)
# else /* C, or C++ without exceptions */
# define HPBC_BASIC_ASSERT(...) do { if (__VA_ARGS__) {} else { \
hpbcAssertHandler(#__VA_ARGS__, __FILE__, __LINE__); } } while(0)
# endif
# define HPBC_LEVEL_ASSERT(LEVEL, ...) do { \
if (hpbcGetHandlerAssertLevel() >= LEVEL) { \
HPBC_BASIC_ASSERT(__VA_ARGS__); } } while(0)
# define HPBC_LEVEL_ASSERT_PRE(LEVEL, ...) do { \
if (hpbcGetHandlerPreconditionAssertLevel() >= LEVEL) { \
HPBC_BASIC_ASSERT(__VA_ARGS__); } } while(0)
# define HPBC_HANDLER_LEVEL hpbcGetHandlerAssertLevel()
# define HPBC_HANDLER_PRECOND_LEVEL hpbcGetHandlerPreconditionAssertLevel()
# endif
# define HPBC_PRECONDITION(...) HPBC_LEVEL_ASSERT_PRE(1, __VA_ARGS__)
# define HPBC_PRECONDITION2(...) HPBC_LEVEL_ASSERT_PRE(2, __VA_ARGS__)
# define HPBC_PRECONDITION3(...) HPBC_LEVEL_ASSERT_PRE(3, __VA_ARGS__)
# define HPBC_POSTCONDITION(...) HPBC_LEVEL_ASSERT(1, __VA_ARGS__)
# define HPBC_POSTCONDITION2(...) HPBC_LEVEL_ASSERT(2, __VA_ARGS__)
# define HPBC_POSTCONDITION3(...) HPBC_LEVEL_ASSERT(3, __VA_ARGS__)
# define HPBC_INVARIANT(...) HPBC_LEVEL_ASSERT(1, __VA_ARGS__)
# define HPBC_INVARIANT2(...) HPBC_LEVEL_ASSERT(2, __VA_ARGS__)
# define HPBC_INVARIANT3(...) HPBC_LEVEL_ASSERT(3, __VA_ARGS__)
# define HPBC_ASSERT(...) HPBC_LEVEL_ASSERT(1, __VA_ARGS__)
# define HPBC_ASSERT2(...) HPBC_LEVEL_ASSERT(2, __VA_ARGS__)
# define HPBC_ASSERT3(...) HPBC_LEVEL_ASSERT(3, __VA_ARGS__)
# define HPBC_PRECONDITION_MACRO_IS_ACTIVE (HPBC_HANDLER_PRECOND_LEVEL >= 1)
# define HPBC_PRECONDITION2_MACRO_IS_ACTIVE (HPBC_HANDLER_PRECOND_LEVEL >= 2)
# define HPBC_PRECONDITION3_MACRO_IS_ACTIVE (HPBC_HANDLER_PRECOND_LEVEL >= 3)
# define HPBC_POSTCONDITION_MACRO_IS_ACTIVE (HPBC_HANDLER_LEVEL >= 1)
# define HPBC_POSTCONDITION2_MACRO_IS_ACTIVE (HPBC_HANDLER_LEVEL >= 2)
# define HPBC_POSTCONDITION3_MACRO_IS_ACTIVE (HPBC_HANDLER_LEVEL >= 3)
# define HPBC_INVARIANT_MACRO_IS_ACTIVE (HPBC_HANDLER_LEVEL >= 1)
# define HPBC_INVARIANT2_MACRO_IS_ACTIVE (HPBC_HANDLER_LEVEL >= 2)
# define HPBC_INVARIANT3_MACRO_IS_ACTIVE (HPBC_HANDLER_LEVEL >= 3)
# define HPBC_ASSERT_MACRO_IS_ACTIVE (HPBC_HANDLER_LEVEL >= 1)
# define HPBC_ASSERT2_MACRO_IS_ACTIVE (HPBC_HANDLER_LEVEL >= 2)
# define HPBC_ASSERT3_MACRO_IS_ACTIVE (HPBC_HANDLER_LEVEL >= 3)
#endif /* NDEBUG */
/* For postconditions where we need to save a value at the function's start: */
/* C example:
void foo(Widget* p)
{
int origVal;
_Bool origHasValue = 0;
if (HPBC_POSTCONDITION_MACRO_IS_ACTIVE) {
origVal = p->a;
origHasValue = 1;
}
... preconditions ...
... function body ...
changeWidget(p);
... more function body ...
HPBC_POSTCONDITION(origHasValue && origVal < p->a);
}
*/
/* C++ example:
We'll normally want to use std::optional (requires C++17)
or boost::optional (pre C++17):
void bar()
{
std::optional<int> origVal;
if (HPBC_POSTCONDITION_MACRO_IS_ACTIVE)
origVal = getValue();
... preconditions ...
... function body ...
HPBC_POSTCONDITION(origVal.has_value() && origVal < getValue());
}
*/
#if defined(NDEBUG)
# define HPBC_INVARIANTS_CHECK(METHOD_NAME) ((void)0)
#else
# define HPBC_INVARIANTS_CHECK(METHOD_NAME) do { \
if (hpbcGetHandlerAssertLevel() > 0) { \
METHOD_NAME(); \
} } while(0)
#endif
#if defined(__cplusplus)
# if defined(NDEBUG)
# define HPBC_INVARIANTS_GUARD(INVARIANTS_METHOD_NAME) ((void)0)
# else
# define HPBC_INVARIANTS_GUARD(INVARIANTS_METHOD_NAME) \
using OuterClassPtrHpbcInvariantsGuard = decltype(this); \
class HpbcClassInvariantsGuard { \
public: \
explicit \
HpbcClassInvariantsGuard(OuterClassPtrHpbcInvariantsGuard ptr) \
: pOuter(ptr) \
{ \
if (hpbcGetHandlerAssertLevel() > 0) \
pOuter->INVARIANTS_METHOD_NAME(); \
} \
~HpbcClassInvariantsGuard() \
{ \
if (hpbcGetHandlerAssertLevel() > 0) \
pOuter->INVARIANTS_METHOD_NAME(); \
} \
HpbcClassInvariantsGuard(const HpbcClassInvariantsGuard&) = delete;\
HpbcClassInvariantsGuard& operator=(const HpbcClassInvariantsGuard&) = delete; \
private: \
OuterClassPtrHpbcInvariantsGuard pOuter; \
} hpbcClassInvariantsGuardVar(this)
# endif
#endif /* defined(__cplusplus) */
#endif
|
/*
* @Description: 一些文件读写的方法
* @Author: Ren Qian
* @Date: 2020-02-24 20:09:32
*/
#include "lidar_localization/tools/file_manager.hpp"
#include <boost/filesystem.hpp>
#include "glog/logging.h"
namespace lidar_localization {
bool FileManager::CreateFile(std::ofstream& ofs, std::string file_path) {
ofs.close();
boost::filesystem::remove(file_path.c_str());
ofs.open(file_path.c_str(), std::ios::out);
if (!ofs) {
LOG(WARNING) << "无法生成文件: " << std::endl << file_path << std::endl << std::endl;
return false;
}
return true;
}
bool FileManager::InitDirectory(std::string directory_path, std::string use_for) {
if (boost::filesystem::is_directory(directory_path)) {
boost::filesystem::remove_all(directory_path);
}
return CreateDirectory(directory_path, use_for);
}
bool FileManager::CreateDirectory(std::string directory_path, std::string use_for) {
if (!boost::filesystem::is_directory(directory_path)) {
boost::filesystem::create_directory(directory_path);
}
if (!boost::filesystem::is_directory(directory_path)) {
LOG(WARNING) << "无法创建文件夹: " << std::endl << directory_path << std::endl << std::endl;
return false;
}
std::cout << use_for << "存放地址:" << std::endl << directory_path << std::endl << std::endl;
return true;
}
bool FileManager::CreateDirectory(std::string directory_path) {
if (!boost::filesystem::is_directory(directory_path)) {
boost::filesystem::create_directory(directory_path);
}
if (!boost::filesystem::is_directory(directory_path)) {
LOG(WARNING) << "无法创建文件夹: " << std::endl << directory_path << std::endl << std::endl;
return false;
}
return true;
}
}
|
#include <bits/stdc++.h>
using namespace std;
// Complete the counterGame function below.
bool isPowerOfTwo (long x)
{
return x && (!(x&(x-1)));
}
int inverse(int x)
{
if(x==0)
return 1;
else
return 0;
}
long highestPowerof2(long n)
{
long p = (long)log2(n);
return (long)pow(2, p);
}
string counterGame(long n) {
int flag=0;
while(n!=1)
{
if(isPowerOfTwo(n))
{
n=n/2;
flag=inverse(flag);
}
else
{
n=n-highestPowerof2(n);
flag=inverse(flag);
}
}
if(flag)
return "Louise";
else
return "Richard";
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int t_itr = 0; t_itr < t; t_itr++) {
long n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string result = counterGame(n);
fout << result << "\n";
}
fout.close();
return 0;
}
|
//
// nehe30.h
// NeheGL
//
// Created by Andong Li on 10/10/13.
// Copyright (c) 2013 Andong Li. All rights reserved.
//
#ifndef __NeheGL__nehe30__
#define __NeheGL__nehe30__
#include <iostream>
#endif /* defined(__NeheGL__nehe30__) */
|
#include <windows.h>
#include <iostream>
using namespace std;
int main ()
{
SetConsoleTitle("Cit Root Chopper");
string choice;
int x;
int y;
int run;
int done = 0;
start:
cout << "Cit Root Chopper" ;
cout << endl << "Version 1.0" << endl;
cout << endl << "Insert number of roots to chop than press 'enter' to begin... ";
cout << endl << "Note: Each root is approx 8 ressources." << endl;
Sleep(500);
cout << endl << "Number of roots to chop: ";
cin >> run;
cout << endl << "Starting in 3...";
Sleep(1000);
cout << endl << "Starting in 2...";
Sleep(1000);
cout << endl << "Starting in 1...";
Sleep(1000);
cout << endl << "In progress..." << endl;
POINT p;
SetCursorPos(609, 415);
GetCursorPos(&p);
x = p.x;
y = p.y;
while(done < run)
{
HDC hDC = GetDC(NULL);
COLORREF color = GetPixel(hDC, p.x, p.y);
BYTE redValue, greenValue, blueValue;
redValue = GetRValue(color);
greenValue = GetGValue(color);
blueValue = GetBValue(color);
if(redValue >= 109 && redValue <= 119 && greenValue >= 83 && greenValue <= 93 && blueValue >= 52 && blueValue <=62)
{
mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
Sleep(20000);
done++;
}
else
{
Sleep(5000);
}
}
cout << endl << "complete!";
cout << endl << "(y/n) Again: ";
cin >> choice;
if (choice == "y")
{
system("cls");
goto start;
}
return 0;
}
|
//
// Tableau.cpp
// Puissance 4
//
// Created by Glorian on 12/02/2016.
// Copyright (c) 2016 Glorian . All rights reserved.
//
#include "Tableau.h"
using namespace std;
Tableau::Tableau(int taille, int p){
puissance = p;
x = taille;
this->array = new char*[x];
for(int i = 0; i <= x; i++)
array[i] = new char[x];
for (int m = 0; m <= x - 1; m++){
for (int j = 0; j <= x; j++){
this->array[m][j] = ' ';
}
}
}
Tableau::Tableau(){
puissance = 4;
x = 7;
this->array = new char*[x];
for(int i = 0; i <= x; ++i)
array[i] = new char[x];
for (int i = 0; i < x; i++){
for (int j = 0; j < x; j++){
this->array[i][j] = ' ';
}
}
}
Tableau::~Tableau(){
delete [] array;
}
bool Tableau::addPion(Player p, int j){
for (int i = x-1; i >= 0; i--){
if (this->array[i][j] == ' '){
array[i][j] = p.getCouleur();
p.Jouer();
int nbregal = 1;
for (int p = 1; p < puissance && i + p < x; p++){
if (array[i][j] == array[i + p][j])nbregal++;
if (nbregal == puissance)return true;
}
nbregal = 1;
for (int k = 1; k < puissance && j + k < x; k++){
if (array[i][j] == array[i][j + k]){nbregal++;}
else {k = puissance;}
}
for (int m = 1; m < puissance && j - m >= 0; m++){
if (array[i][j] == array[i][j - m]){nbregal++;}
else {m = puissance;}
}
if (nbregal >= puissance)return true;
nbregal = 1;
for (int b = 1; b < puissance && i - b >= 0 && j + b < x; b++){
if (array[i][j] == array[i - b][j + b]){nbregal++;}
else {b = puissance;}
}
for (int c = 1; c < puissance && j - c >= 0 && i + c < x; c++){
if (array[i][j] == array[i + c][j - c]){nbregal++;}
else {c = puissance;}
}
if (nbregal >= puissance)return true;
nbregal = 1;
for (int h = 1; h < puissance && i - h >= 0 && j - h >= 0;h++){
if (array[i][j] == array[i - h][j - h]){nbregal++;}
else {h = puissance;}
}
for (int l = 1; l < puissance && i + l < x && j + l < x; l++){
if (array[i][j] == array[i + l][j + l]){nbregal++;}
else {l = puissance;}
}
if (nbregal >= puissance){return true;}
else {return false;}
}
}
cout << "La colonne est déja remplie" << endl;
return false;
}
void Tableau::afficher(){
cout << " |";
for (int j = 0; j < x; j++){
cout << j << " |";
}
cout << endl;
for (int i = 0; i < x; i++){
cout << i << " |";
for (int j = 0; j < x; j++){
cout << array[i][j] << " |";
}
cout << endl;
}
cout << endl << endl << endl;
}
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
void Init_ListNode(ListNode* head, vector<int> vec)
{
if (vec.size() == 0)
{
head = NULL;
return;
}
ListNode* p;
p = head;
p->val = vec[0];
for (int i = 1; i < vec.size(); i++)
{
ListNode* q = new ListNode(vec[i]);
p->next = q;
p = p->next;
}
}
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
//简化版:单链表操作,链表start1中元素都小于x,链表start2中元素都大于等于x,最后合并两个链表
ListNode* start1=new ListNode(0),*start2=new ListNode(0);
ListNode* p=start1,*q=start2;
while(head)
{
if(head->val<x)
{
p->next=head;
p=p->next;
}
else
{
q->next=head;
q=q->next;
}
head=head->next;
}
p->next=start2->next;
q->next=nullptr;
return start1->next;
}
};
class Solution1 {
public:
ListNode* partition(ListNode* head, int x) {
//基本思想:单链表操作,p指向小于x的右边界节点,q指向大于等于x的右边界节点,cur指向当前节点
//如果当前节点cur小于x,将cur节点插到p的位置
//如果当前节点cur大于等于x,将cur节点插到q的位置
if (head == NULL)
return NULL;
ListNode* p, * q, * cur, * start;
p = new ListNode(0);
start = p;
//找到p节点的位置,p指向小于x的右边界节点
p->next = head;
while (p->next!=NULL && p->next->val < x)
p = p->next;
//如果链表所有节点小于x,不用调整节点,返回
if (p->next == NULL)
return start->next;
//找到p节点的位置,q指向大于等于x的右边界节点
q = p->next;
while (q->next != NULL && q->next->val >= x)
q = q->next;
//如果链表p之后所有节点大于等于x,不用调整节点,返回
if (q->next == NULL)
return start->next;
//遍历q之后所有节点
cur = q->next;
while (cur != NULL)
{
//如果当前节点cur大于等于x,将cur节点插到q的位置
if (cur->val >= x)
{
q = cur;
cur = q->next;
}
//如果当前节点cur小于x,将cur节点插到p的位置
else
{
q->next = cur->next;
cur->next = p->next;
p->next = cur;
p = cur;
cur = q->next;
}
}
return start->next;
}
};
int main()
{
Solution solute;
ListNode* head = new ListNode(0);
vector<int> vec = { 5,1,1,1,1,1 };
//初始化链表
Init_ListNode(head, vec);
ListNode* p;
int x = 3;
p = solute.partition(head, x);
while (p != NULL)
{
cout << p->val << " ";
p = p->next;
}
cout << endl;
return 0;
}
|
#include "deathEvent.h"
deathEvent::deathEvent(GameObject a, GameObject b) {
this->a = a;
this->b = b;
}
GameObject deathEvent::getObjA() {
return a;
}
GameObject deathEvent::getObjB() {
return b;
}
eventType deathEvent::getType()
{
return deathEvent_type;
}
char deathEvent::getKeyPress() {
return NULL;
}
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t,a;
scanf("%d",&t);
while(t--){
scanf("%d",&a);
a=(a*567)/9;
a=(a+7492)*235;
a=(a/47)-498;
a=a%100;
a=a/10;
if(a<0) a=a*-1;
cout<<a<<endl;
}
return 0;
}
|
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
// class for AVL node
class AVL_Node
{
private:
int key;
int bf; // balance factor bf = height(left subtree) – height(right subtree)
AVL_Node *LChild, *RChild;
friend class AVL_Tree;
public:
// parameterized constructor
AVL_Node(int k)
{
key = k;
bf = 0;
LChild = RChild = NULL;
}
// non-parameterized constructor
AVL_Node()
{
bf = 0;
LChild = RChild = NULL;
}
};
class AVL_Tree
{
private:
AVL_Node *root;
int number_of_rotations_during_insertion;
int number_of_rotations_during_deletion;
int number_of_comparisons_during_insertion;
int number_of_comparisons_during_deletion;
AVL_Node *link(int a, AVL_Node *node);
void singleRotation(AVL_Node *&p, AVL_Node *&r, AVL_Node *&s, int a);
void doubleRotation(AVL_Node *&p, AVL_Node *&r, AVL_Node *&s, int a);
void AVL_PrintHelper(const AVL_Node *node, ofstream &fout);
void destructorHelper(AVL_Node *avl_node);
void copyConstructorHelper(const AVL_Node *node);
void RotateR(AVL_Node *&ptr);
void RotateL(AVL_Node *&ptr);
void RotateRL(AVL_Node *&ptr);
void RotateLR(AVL_Node *&ptr);
long int AVL_Average_Height_Of_Nodes_Helper(AVL_Node *node, long int &total_height, double &number_of_nodes);
int AVL_Height_Helper(AVL_Node *node);
public:
AVL_Tree();
AVL_Tree(const AVL_Tree &T);
void AVL_Insert(int k);
void AVL_Delete(int k);
bool AVL_Search(int k);
void AVL_Print(const char *filename);
double AVL_Average_Height_Of_Nodes();
int AVL_Height();
int get_number_of_rotations_during_insertion();
int get_number_of_rotations_during_deletion();
int get_number_of_comparisons_during_insertion();
int get_number_of_comparisons_during_deletion();
~AVL_Tree();
};
//===============================================================================================
// function to handle the LL case in rotation
void AVL_Tree::RotateR(AVL_Node *&ptr) //Right Rotation
{
AVL_Node *subR = ptr;
ptr = subR->LChild;
subR->LChild = ptr->RChild;
ptr->RChild = subR;
ptr->bf = subR->bf = 0;
}
//===============================================================================================
// function to handle the RR case in rotation
void AVL_Tree::RotateL(AVL_Node *&ptr) //Left Rotation
{
AVL_Node *subL = ptr;
ptr = subL->RChild;
subL->RChild = ptr->LChild;
ptr->LChild = subL;
ptr->bf = subL->bf = 0;
}
//===============================================================================================
// function to handle the RL case in rotation
void AVL_Tree::RotateRL(AVL_Node *&ptr) //Rotate right then left
{
AVL_Node *subL = ptr;
AVL_Node *subR = ptr->RChild;
ptr = subR->LChild;
subR->LChild = ptr->RChild;
ptr->RChild = subR;
if (ptr->bf >= 0)
subR->bf = 0;
else
subR->bf = 1;
subL->RChild = ptr->LChild;
ptr->LChild = subL;
if (ptr->bf <= 0)
subL->bf = 0;
else
subL->bf = -1;
ptr->bf = 0;
}
//===============================================================================================
// function to handle the LR case in rotation
void AVL_Tree::RotateLR(AVL_Node *&ptr) //Rotate left then right
{
AVL_Node *subL = ptr->LChild;
AVL_Node *subR = ptr;
ptr = subL->RChild;
subL->RChild = ptr->LChild;
ptr->LChild = subL;
if (ptr->bf <= 0)
subL->bf = 0;
else
subL->bf = -1;
subR->LChild = ptr->RChild;
ptr->RChild = subR;
if (ptr->bf >= 0)
subR->bf = 0;
else
subR->bf = 1;
ptr->bf = 0;
}
//===============================================================================================
// constructor for AVL_Tree class
AVL_Tree::AVL_Tree()
{
number_of_comparisons_during_deletion = 0;
number_of_comparisons_during_insertion = 0;
number_of_rotations_during_deletion = 0;
number_of_rotations_during_insertion = 0;
root = new AVL_Node();
}
//===============================================================================================
// copy constructor for AVL_Tree class
AVL_Tree::AVL_Tree(const AVL_Tree &T)
{
number_of_comparisons_during_deletion = 0;
number_of_comparisons_during_insertion = 0;
number_of_rotations_during_deletion = 0;
number_of_rotations_during_insertion = 0;
root = new AVL_Node();
copyConstructorHelper(T.root->RChild);
}
//===============================================================================================
// helper function to do the traversal of AVL tree
// and copy it in a new object
void AVL_Tree::copyConstructorHelper(const AVL_Node *node)
{
if (!node)
return;
AVL_Insert(node->key);
copyConstructorHelper(node->LChild);
copyConstructorHelper(node->RChild);
}
//===============================================================================================
// function to return the pointer of child whose subtree height is more
AVL_Node *AVL_Tree::link(int a, AVL_Node *node)
{
if (a == -1)
return node->LChild;
return node->RChild;
};
//===============================================================================================
// function to insert a value (k) in the AVL tree
void AVL_Tree::AVL_Insert(int k)
{
AVL_Node *t = root; // pointer to parent of balance point
AVL_Node *s = root->RChild; // pointer to balance point (where imbalance might have occurred)
AVL_Node *p = root->RChild; // pointer to traverse te AVL tree
AVL_Node *q, *r;
AVL_Node *avl_node = new AVL_Node(k); // create new node
if (!p) // if tree is empty
{
root->RChild = avl_node;
return;
}
// traverse the tree to find and insert k
// at its correct position
while (true)
{
number_of_comparisons_during_insertion++;
if (k < p->key) // k should be inserted in left subtree
{
q = p->LChild;
if (!q)
{
q = avl_node;
p->LChild = q;
break;
}
}
else if (k > p->key) // k should be inserted in right subtree
{
q = p->RChild;
if (!q)
{
q = avl_node;
p->RChild = q;
break;
}
}
else
return;
if (q->bf != 0) // if q can be the balance point, update s and t
{
t = p;
s = q;
}
p = q; // go down with p
}
int a = 1;
if (k < s->key)
a = -1;
r = p = link(a, s);
// update bf for all nodes between p and q
while (p != q)
{
if (k < p->key)
{
p->bf = -1;
p = p->LChild;
}
else if (k > p->key)
{
p->bf = 1;
p = p->RChild;
}
}
if (s->bf == 0) // tree has grown higher
{
s->bf = a;
return;
}
if (s->bf == -a) // tree has become more balanced
{
s->bf = 0;
return;
}
// tree has become imbalanced
if (s->bf == a)
{
if (r->bf == a)
{
number_of_rotations_during_insertion++;
singleRotation(p, r, s, a); // Either LL or RR case for a = -1 and a = 1 respectively
}
else if (r->bf == -a)
{
number_of_rotations_during_insertion += 2;
doubleRotation(p, r, s, a); // Either LR or RL case for a = -1 and a = 1 respectively
}
}
// update root if tree is rotated through it
if (s == t->RChild)
t->RChild = p;
else
t->LChild = p;
}
//===============================================================================================
void AVL_Tree::singleRotation(AVL_Node *&p, AVL_Node *&r, AVL_Node *&s, int a)
{
p = r;
if (a == 1) // for RR case
{
s->RChild = r->LChild;
r->LChild = s;
}
else // for LL case
{
s->LChild = r->RChild;
r->RChild = s;
}
s->bf = r->bf = 0;
}
//===============================================================================================
void AVL_Tree::doubleRotation(AVL_Node *&p, AVL_Node *&r, AVL_Node *&s, int a)
{
if (a == -1) // for LR case
{
p = r->RChild;
r->RChild = p->LChild;
p->LChild = r;
s->LChild = p->RChild;
p->RChild = s;
}
else // for RL case
{
p = r->LChild;
r->LChild = p->RChild;
p->RChild = r;
s->RChild = p->LChild;
p->LChild = s;
}
if (p->bf == a)
{
s->bf = -a;
r->bf = 0;
}
else if (p->bf == 0)
{
s->bf = 0;
r->bf = 0;
}
else if (p->bf == -a)
{
s->bf = 0;
r->bf = a;
}
p->bf = 0;
}
//===============================================================================================
// function to print the AVL tree in a png file
void AVL_Tree::AVL_Print(const char *filename)
{
ofstream fout;
string dot_file = "";
dot_file = dot_file + filename + ".dot"; // name of graphviz file
string png_file = "";
png_file = png_file + filename + ".png"; // name of png file
fout.open(dot_file.c_str()); // open dot file for writing
fout << "digraph g {\n";
fout << "node [shape=record, height=0.1];\n";
AVL_PrintHelper(root->RChild, fout);
fout << "}";
fout.close(); // close dot file
string str = "dot -Tpng ";
str = str + dot_file + " -o " + png_file;
const char *command = str.c_str();
system(command); // system call to run the dot file using graphviz
cout << "Tree Printed Successfully! Please check the " << png_file << " file.\n";
}
//===============================================================================================
// helper function to traverse the AVL tree in preorder fashion
// and print the edges in the required format in the dot file
void AVL_Tree::AVL_PrintHelper(const AVL_Node *node, ofstream &fout)
{
if (!node) // if node is NULL
return;
if (node == root->RChild) // add the label and root in the dot file
{
fout << "label = \" rooted at " << node->key << " \";\n";
fout << node->key << " [root = true]\n";
}
fout << node->key << " [label=\"<f0>|<f1>" << node->key << "|<f2> " << -node->bf << " |<f3> \"];\n";
if (node->LChild) // if left child exists
{
fout << node->key << ":f0 -> " << node->LChild->key << ":f1\n"; // write edge in dot file
AVL_PrintHelper(node->LChild, fout); // recurse for left subtree
}
if (node->RChild) // if right child exists
{
fout << node->key << ":f3 -> " << node->RChild->key << ":f1\n"; // write edge in dot file
AVL_PrintHelper(node->RChild, fout); // recurse for right subtree
}
}
//===============================================================================================
// function to search for an element (k) in the
// AVL tree and return a boolean value
bool AVL_Tree::AVL_Search(int k)
{
AVL_Node *avl_node = root->RChild;
while (avl_node) // traverse while cur node is not NULL
{
if (k == avl_node->key) // k is found
return true;
if (k < avl_node->key) // k is in left subtree
avl_node = avl_node->LChild;
else // k is in right subtree
avl_node = avl_node->RChild;
}
// k was not found in the tree
return false;
}
//===============================================================================================
// function to delete an element (k)
// from the AVL tree
void AVL_Tree::AVL_Delete(int k)
{
// if (!AVL_Search(k)) // if k is not present in the tree
// {
// throw "Key does not exist in the tree.";
// }
AVL_Node *pr = NULL;
AVL_Node *p = root->RChild, *q;
stack<AVL_Node *> st;
// traverse the tree to find node with key value k
while (p)
{
number_of_comparisons_during_deletion++;
if (k == p->key) // k is found
break;
pr = p;
st.push(pr);
if (k < p->key) // k is in left subtree
p = p->LChild;
else // k is in right subtree
p = p->RChild;
}
if (!p)
return;
// if p has both children (left and right)
if (p->LChild != NULL && p->RChild != NULL)
{
pr = p;
st.push(pr);
// find the successor of p in q
q = p->RChild;
while (q->LChild != NULL)
{
pr = q;
st.push(pr);
q = q->LChild;
}
p->key = q->key; // copy key value of q to p
p = q;
}
if (p->LChild != NULL) // if p has left child
q = p->LChild;
else // if p has right child
q = p->RChild;
// p deleted node, q deleted child node
if (pr == NULL) // p is the root
root->RChild = q;
else // p is an internal node or a leaf
{
if (p == pr->LChild) // if p is left child of its parent
pr->LChild = q;
else // if p is right child of its parent
pr->RChild = q;
// adjust Balance
while (!st.empty())
{
pr = st.top();
st.pop();
if (p->key < pr->key) // k was deleted from left subtree
pr->bf++;
else
pr->bf--; // k was deleted from right subtree
if (pr->bf == 1 || pr->bf == -1) // whole tree is balanced
break;
if (pr->bf != 0)
{
// let q point to a higher subtree
if (pr->bf < 0)
q = pr->LChild;
else
q = pr->RChild;
if (q->bf == 0)
{
number_of_rotations_during_deletion++;
if (pr->bf < 0) // LL case
{
RotateR(pr);
pr->bf = 1;
pr->RChild->bf = -1;
}
else // RR case
{
RotateL(pr);
pr->bf = -1;
pr->LChild->bf = 1;
}
if (!st.empty())
{
AVL_Node *ppr = st.top();
if (ppr->key < pr->key)
ppr->RChild = pr;
else
ppr->LChild = pr;
}
else
root->RChild = pr;
break;
}
if (pr->bf < 0)
{
if (q->bf < 0) // LL case
{
number_of_rotations_during_deletion++;
RotateR(pr);
}
else
{
number_of_rotations_during_deletion += 2;
RotateLR(pr); // LR case
}
}
else
{
number_of_rotations_during_deletion++;
if (q->bf > 0)
{
RotateL(pr); // RR case
}
else
{
number_of_rotations_during_deletion += 2;
RotateRL(pr); // RL case
}
}
if (!st.empty())
{
AVL_Node *ppr = st.top();
// ppr->key < pr->key ? (ppr->RChild = pr) : (ppr->LChild = pr);
if (ppr->key < pr->key)
ppr->RChild = pr;
else
ppr->LChild = pr;
}
else
root->RChild = pr;
}
q = pr;
} //end while
}
delete p;
}
//===============================================================================================
// destructor
AVL_Tree::~AVL_Tree()
{
destructorHelper(root->RChild); // delete all children
delete (root); // delete root
}
//===============================================================================================
// helper function to traverse the AVL tree in post order
// fashion and delete the nodes one by one
void AVL_Tree::destructorHelper(AVL_Node *avl_node)
{
if (!avl_node) // if node is NULL
return;
if (avl_node->LChild) // node has left child
destructorHelper(avl_node->LChild);
if (avl_node->RChild) // node has right child
destructorHelper(avl_node->RChild);
delete (avl_node); // deallocate memory for node
}
//========================================================================================================================
int AVL_Tree::AVL_Height()
{
return AVL_Height_Helper(root->RChild);
}
//========================================================================================================================
int AVL_Tree::AVL_Height_Helper(AVL_Node *node)
{
if (!node)
return 0;
return 1 + max(AVL_Height_Helper(node->LChild), AVL_Height_Helper(node->RChild));
}
//========================================================================================================================
double AVL_Tree::AVL_Average_Height_Of_Nodes()
{
long int h = 0;
int c = 1;
double number_of_nodes = 0;
AVL_Average_Height_Of_Nodes_Helper(root->RChild, h, number_of_nodes);
return h / number_of_nodes;
}
//========================================================================================================================
long int AVL_Tree::AVL_Average_Height_Of_Nodes_Helper(AVL_Node *node, long int &total_height, double &number_of_nodes)
{
if (!node)
return 0;
++number_of_nodes;
long int lh = AVL_Average_Height_Of_Nodes_Helper(node->LChild, total_height, number_of_nodes);
long int rh = AVL_Average_Height_Of_Nodes_Helper(node->RChild, total_height, number_of_nodes);
int h = max(lh, rh) + 1;
total_height += h;
return h;
}
//========================================================================================================================
int AVL_Tree::get_number_of_rotations_during_insertion() { return number_of_rotations_during_insertion; }
int AVL_Tree::get_number_of_rotations_during_deletion() { return number_of_rotations_during_deletion; }
int AVL_Tree::get_number_of_comparisons_during_insertion() { return number_of_comparisons_during_insertion; }
int AVL_Tree::get_number_of_comparisons_during_deletion() { return number_of_comparisons_during_deletion; }
|
// Created on: 2014-09-01
// Created by: Ivan SAZONOV
// Copyright (c) 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 OpenGl_StructureShadow_Header
#define OpenGl_StructureShadow_Header
#include <OpenGl_Structure.hxx>
//! Dummy structure which just redirects to groups of another structure.
class OpenGl_StructureShadow : public OpenGl_Structure
{
public:
//! Create empty structure
Standard_EXPORT OpenGl_StructureShadow (const Handle(Graphic3d_StructureManager)& theManager,
const Handle(OpenGl_Structure)& theStructure);
public:
//! Raise exception on API misuse.
Standard_EXPORT virtual void Connect (Graphic3d_CStructure& ) Standard_OVERRIDE;
//! Raise exception on API misuse.
Standard_EXPORT virtual void Disconnect (Graphic3d_CStructure& ) Standard_OVERRIDE;
private:
Handle(OpenGl_Structure) myParent;
public:
DEFINE_STANDARD_RTTIEXT(OpenGl_StructureShadow,OpenGl_Structure) // Type definition
};
DEFINE_STANDARD_HANDLE(OpenGl_StructureShadow, OpenGl_Structure)
#endif // OpenGl_StructureShadow_Header
|
#ifndef LOSS_FUNCTION_H_
#define LOSS_FUNCTION_H_
#include "Layer.h"
class Loss_function: public Layer
{
public:
Loss_function();
virtual ~Loss_function();
virtual void forward(MatrixXd act_p, MatrixXd label);
protected:
virtual MatrixXd act_func(MatrixXd stat, MatrixXd label)=0;
virtual MatrixXd act_func_g(MatrixXd stat, MatrixXd label)=0;
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** 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.
**
*/
#ifndef __DESKTOPNOTIFIER_H__
# define __DESKTOPNOTIFIER_H__
class DesktopNotifier;
class OpInputAction;
class DesktopNotifierListener
{
public:
virtual void OnNotifierDeleted(const DesktopNotifier* notifier){}
virtual ~DesktopNotifierListener(){}
};
class DesktopNotifier
{
public:
// Type of notification
enum DesktopNotifierType
{
MAIL_NOTIFICATION,
BLOCKED_POPUP_NOTIFICATION,
TRANSFER_COMPLETE_NOTIFICATION,
WIDGET_NOTIFICATION,
NETWORK_SPEED_NOTIFICATION,
AUTOUPDATE_NOTIFICATION,
EXTENSION_NOTIFICATION,
AUTOUPDATE_NOTIFICATION_EXTENSIONS,
PLUGIN_DOWNLOADED_NOTIFICATION
};
virtual ~DesktopNotifier() {}
static OP_STATUS Create(DesktopNotifier **new_notifier);
virtual OP_STATUS Init(DesktopNotifier::DesktopNotifierType notification_group, const OpStringC& text, const OpStringC8& image, OpInputAction* action, BOOL managed = FALSE, BOOL wrapping = FALSE) = 0;
virtual OP_STATUS Init(DesktopNotifier::DesktopNotifierType notification_group, const OpStringC& title, Image& image, const OpStringC& text, OpInputAction* action, OpInputAction* cancel_action, BOOL managed = FALSE, BOOL wrapping = FALSE) = 0;
/** Adds a button to the notifier below the title
* @param text Text on button
* @param action Action to execute when this button is clicked
*/
virtual OP_STATUS AddButton(const OpStringC& text, OpInputAction* action) = 0;
virtual void StartShow() = 0;
virtual BOOL IsManaged() const = 0;
virtual void AddListener(DesktopNotifierListener* listener) = 0;
virtual void RemoveListener(DesktopNotifierListener* listener) = 0;
virtual void SetReceiveTime(time_t time) = 0;
#ifdef M2_SUPPORT
static bool UsesCombinedMailAndFeedNotifications();
#endif
};
#endif // __DESKTOPNOTIFIER_H__
|
// Created on: 1994-03-18
// Created by: Bruno DUMORTIER
// Copyright (c) 1994-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 _GeomAPI_ExtremaSurfaceSurface_HeaderFile
#define _GeomAPI_ExtremaSurfaceSurface_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Integer.hxx>
#include <Extrema_ExtSS.hxx>
class Geom_Surface;
class gp_Pnt;
//! Describes functions for computing all the extrema
//! between two surfaces.
//! An ExtremaSurfaceSurface algorithm minimizes or
//! maximizes the distance between a point on the first
//! surface and a point on the second surface. Results
//! are start and end points of perpendiculars common to the two surfaces.
//! Solutions consist of pairs of points, and an extremum
//! is considered to be a segment joining the two points of a solution.
//! An ExtremaSurfaceSurface object provides a framework for:
//! - defining the construction of the extrema,
//! - implementing the construction algorithm, and
//! - consulting the results.
//! Warning
//! In some cases, the nearest points between the two
//! surfaces do not correspond to one of the computed
//! extrema. Instead, they may be given by:
//! - a point of a bounding curve of one surface and one of the following:
//! - its orthogonal projection on the other surface,
//! - a point of a bounding curve of the other surface; or
//! - any point on intersection curves between the two surfaces.
class GeomAPI_ExtremaSurfaceSurface
{
public:
DEFINE_STANDARD_ALLOC
//! Constructs an empty algorithm for computing
//! extrema between two surfaces. Use an Init function
//! to define the surfaces on which it is going to work.
Standard_EXPORT GeomAPI_ExtremaSurfaceSurface();
//! Computes the extrema distances between the
//! surfaces <S1> and <S2>
Standard_EXPORT GeomAPI_ExtremaSurfaceSurface(const Handle(Geom_Surface)& S1, const Handle(Geom_Surface)& S2);
//! Computes the extrema distances between
//! the portion of the surface S1 limited by the
//! two values of parameter (U1min,U1max) in
//! the u parametric direction, and by the two
//! values of parameter (V1min,V1max) in the v
//! parametric direction, and
//! - the portion of the surface S2 limited by the
//! two values of parameter (U2min,U2max) in
//! the u parametric direction, and by the two
//! values of parameter (V2min,V2max) in the v
//! parametric direction.
Standard_EXPORT GeomAPI_ExtremaSurfaceSurface(const Handle(Geom_Surface)& S1, const Handle(Geom_Surface)& S2, const Standard_Real U1min, const Standard_Real U1max, const Standard_Real V1min, const Standard_Real V1max, const Standard_Real U2min, const Standard_Real U2max, const Standard_Real V2min, const Standard_Real V2max);
//! Initializes this algorithm with the given arguments
//! and computes the extrema distances between the
//! surfaces <S1> and <S2>
Standard_EXPORT void Init (const Handle(Geom_Surface)& S1, const Handle(Geom_Surface)& S2);
//! Initializes this algorithm with the given arguments
//! and computes the extrema distances between -
//! the portion of the surface S1 limited by the two
//! values of parameter (U1min,U1max) in the u
//! parametric direction, and by the two values of
//! parameter (V1min,V1max) in the v parametric direction, and
//! - the portion of the surface S2 limited by the two
//! values of parameter (U2min,U2max) in the u
//! parametric direction, and by the two values of
//! parameter (V2min,V2max) in the v parametric direction.
Standard_EXPORT void Init (const Handle(Geom_Surface)& S1, const Handle(Geom_Surface)& S2, const Standard_Real U1min, const Standard_Real U1max, const Standard_Real V1min, const Standard_Real V1max, const Standard_Real U2min, const Standard_Real U2max, const Standard_Real V2min, const Standard_Real V2max);
//! Returns the number of extrema computed by this algorithm.
//! Note: if this algorithm fails, NbExtrema returns 0.
Standard_EXPORT Standard_Integer NbExtrema() const;
Standard_EXPORT operator Standard_Integer() const;
//! Returns the points P1 on the first surface and P2 on
//! the second surface, which are the ends of the
//! extremum of index Index computed by this algorithm.
//! Exceptions
//! Standard_OutOfRange if Index is not in the range [
//! 1,NbExtrema ], where NbExtrema is the
//! number of extrema computed by this algorithm.
Standard_EXPORT void Points (const Standard_Integer Index, gp_Pnt& P1, gp_Pnt& P2) const;
//! Returns the parameters (U1,V1) of the point on the
//! first surface, and (U2,V2) of the point on the second
//! surface, which are the ends of the extremum of index
//! Index computed by this algorithm.
//! Exceptions
//! Standard_OutOfRange if Index is not in the range [
//! 1,NbExtrema ], where NbExtrema is the
//! number of extrema computed by this algorithm.
Standard_EXPORT void Parameters (const Standard_Integer Index, Standard_Real& U1, Standard_Real& V1, Standard_Real& U2, Standard_Real& V2) const;
//! Computes the distance between the end points of the
//! extremum of index Index computed by this algorithm.
//! Exceptions
//! Standard_OutOfRange if Index is not in the range [
//! 1,NbExtrema ], where NbExtrema is the
//! number of extrema computed by this algorithm.
Standard_EXPORT Standard_Real Distance (const Standard_Integer Index) const;
//! Returns True if the surfaces are parallel
Standard_Boolean IsParallel() const
{
return myExtSS.IsParallel();
}
//! Returns the points P1 on the first surface and P2 on
//! the second surface, which are the ends of the
//! shortest extremum computed by this algorithm.
//! Exceptions StdFail_NotDone if this algorithm fails.
Standard_EXPORT void NearestPoints (gp_Pnt& P1, gp_Pnt& P2) const;
//! Returns the parameters (U1,V1) of the point on the
//! first surface and (U2,V2) of the point on the second
//! surface, which are the ends of the shortest extremum
//! computed by this algorithm.
//! Exceptions - StdFail_NotDone if this algorithm fails.
Standard_EXPORT void LowerDistanceParameters (Standard_Real& U1, Standard_Real& V1, Standard_Real& U2, Standard_Real& V2) const;
//! Computes the distance between the end points of the
//! shortest extremum computed by this algorithm.
//! Exceptions StdFail_NotDone if this algorithm fails.
Standard_EXPORT Standard_Real LowerDistance() const;
Standard_EXPORT operator Standard_Real() const;
//! return the algorithmic object from Extrema
const Extrema_ExtSS& Extrema() const;
private:
Standard_Boolean myIsDone;
Standard_Integer myIndex;
Extrema_ExtSS myExtSS;
};
#include <GeomAPI_ExtremaSurfaceSurface.lxx>
#endif // _GeomAPI_ExtremaSurfaceSurface_HeaderFile
|
#include <stack>
#include <string>
#include <iostream>
using namespace std;
int operation(string &S, std::stack<int> &nums, string &word, int i){
int top_element;
int num1, num2;
if (i == S.size() || S.at(i) == ' '){
if (word == "DUP"){
// push the top of stack
if (nums.size()>0){
top_element = nums.top();
nums.push(top_element);
}
else{
return -1;
}
}
else if (word == "POP"){
if (nums.size()>0){
nums.pop();
}
else{
return -1;
}
}
else if (word == "+"){
if (nums.size()>1){
num1 = nums.top();
nums.pop();
num2 = nums.top();
nums.pop();
nums.push(num1+num2);
}
else{
return -1;
}
}
else if (word == "-"){
if (nums.size()>1){
num1 = nums.top();
nums.pop();
num2 = nums.top();
nums.pop();
nums.push(num1-num2);
}
else{
return -1;
}
}
else{
nums.push(stoi(word));
}
word = "";
}
else{
word = word+S.at(i);
}
return 0;
}
int solution(string &S) {
int stop;
unsigned i;
string word = "";
std::stack<int> nums;
for(i=0; i<S.length(); i++){
stop = operation(S, nums, word, i);
if (stop == -1){
return stop;
}
}
stop = operation(S, nums, word, i);
if (stop == -1){
return stop;
}
return nums.top();
}
int main()
{
int res;
string s;
s = "13 DUP 4 POP 5 DUP + DUP + -";
res = solution(s);
cout << res;
}
|
#include "AIControoller.h"
|
#include "gtest/gtest.h"
#include "Student.hpp"
constexpr char STUDENT_NAME[] = "Anna";
constexpr char STUDENT_SURNAME[] = "Nowak";
constexpr char STUDENT_ADDRESS[] = "Wroclaw";
constexpr char STUDENT_INDEX_NUMBER[] = "123456";
constexpr char STUDENT_PERSONAL_IDENTITY_NUMBER[] = "95012600149";
constexpr char STUDENT_GENDER[] = "F";
Student student(STUDENT_NAME, STUDENT_SURNAME, STUDENT_ADDRESS, STUDENT_INDEX_NUMBER, STUDENT_PERSONAL_IDENTITY_NUMBER, STUDENT_GENDER);
TEST(StudentGettersTests, getStudentNameByGetterAndShouldBeEqualAnna) {
EXPECT_EQ(student.getName(), STUDENT_NAME);
}
TEST(StudentGettersTests, getStudentSurnameByGetterAndShouldBeEqualNowak) {
EXPECT_EQ(student.getSurname(), STUDENT_SURNAME);
}
TEST(StudentGettersTests, getStudentAddressByGetterAndShouldBeEqualWroclaw) {
EXPECT_EQ(student.getAddress(), STUDENT_ADDRESS);
}
TEST(StudentGettersTests, getStudentIndexNumberByGetterAndShouldBeEqual123456) {
EXPECT_EQ(student.getIndexNumber(), STUDENT_INDEX_NUMBER);
}
TEST(StudentGettersTests, getStudentPersonalIndentityNumberByGetterAndShouldBeEqual95012600149) {
EXPECT_EQ(student.getPersonalIdentityNumber(), STUDENT_PERSONAL_IDENTITY_NUMBER);
}
TEST(StudentGettersTests, getStudentGenderAndShouldBeEqualToF) {
EXPECT_EQ(student.getGender(), STUDENT_GENDER);
}
TEST(StudentOperatorsTests, compareTwoIndexNumberInStudentClass) {
Student student2(STUDENT_NAME, STUDENT_SURNAME, STUDENT_ADDRESS, "123456", STUDENT_PERSONAL_IDENTITY_NUMBER, STUDENT_GENDER);
EXPECT_EQ(student.getIndexNumber(), student2.getIndexNumber());
}
TEST(PersonalIdentityNumberValidation, PersonalIdentityNumberShouldBeElevenCharacters) {
EXPECT_EQ(std::size(student.getPersonalIdentityNumber()), 11);
}
|
#include "logind.hpp"
#include "log.hpp"
#include "utils/service_thread.hpp"
#include "utils/time_utils.hpp"
#include "utils/process_utils.hpp"
#include "config/utils.hpp"
#include "config/options_ptts.hpp"
#include <signal.h>
using namespace nora;
int main(int argc, char **argv) {
srand(time(0));
PTTS_LOAD(options);
auto ptt = PTTS_GET_COPY(options, 1u);
if (ptt.login_info().logind_deamon()) {
deamonize(argv);
}
write_pid_file("logind_pid");
init_log("logind", ptt.level());
PTTS_LOAD(channel_specify);
PTTS_LOAD(serverlist);
PTTS_LOAD(specific_server_list);
PTTS_MVP(options);
PTTS_MVP(channel_specify);
PTTS_MVP(serverlist);
PTTS_MVP(specific_server_list);
auto st = make_shared<service_thread>("main");
clock::instance().start(st);
auto lg = make_shared<login::logind>(st);
st->async_call(
[lg] {
lg->start();
});
LOGIN_ILOG << "start";
st->run();
return 0;
}
|
#pragma once
#include "Behaviour.h"
#include "State.h"
class Transition;
class Condition;
class FiniteStateMachine : public Behaviour
{
public:
FiniteStateMachine() : m_currentState(nullptr) {}
FiniteStateMachine(State* state) : m_currentState(state) {}
virtual ~FiniteStateMachine()
{
for (auto state : m_states)
delete state;
for (auto t : m_transitions)
delete t;
for (auto c : m_conditions)
delete c;
}
//add components, takes ownership
State* addState(State* state)
{
m_states.push_back(state);
return state;
}
Transition* addTransition(Transition* transition)
{
m_transitions.push_back(transition);
return transition;
}
Condition* addCondition(Condition* condition)
{
m_conditions.push_back(condition);
return condition;
}
virtual bool execute(Agent* gameObject, float deltaTime);
virtual vector2 Update(Agent* agent, float deltaTime)
{
execute(agent, deltaTime);
vector2* v = new vector2(0, 0);
return *v;
}
virtual float GetWeight() { return 0; }
void setCurrentState(State* state) { m_currentState = state; }
protected:
std::vector<State*> m_states;
std::vector<Transition*> m_transitions;
std::vector<Condition*> m_conditions;
State* m_currentState;
};
|
/**
Author: Elliott Waterman
Date: 08/01/2019
Description: Program to use an alarm on the RTC module
to wake a sleeping Arduino via an interrupt.
*/
/* INCLUDES */
#include <avr/sleep.h> //AVR library contains methods and sleep modes to control the sleep of an Arduino
#include <SPI.h> //SPI library used for the SD module. Part of the Arduino IDE
#include <SD.h> //SD library used for the SD module. Part of the Arduino IDE
#include <DS3232RTC.h> //RTC library used to control the RTC module
#include <SimpleDHT.h> //DHT22 library used to read from a DHT22 module
/* DEFINES */
#define PIN_WAKE_UP 2 //Interrupt pin (or #3) we are going to use to wake up the Arduino
#define PIN_DHT22 3 //Digital pin connected to the DHT22 module
#define PIN_SD 10 //Digital pin connected to the SD module
#define TIME_INTERVAL 5 //Sets the wakeup intervall in minutes
//#define EXAMPLE 1 //Comment
/* INSTANTIATE LIBRARIES */
SimpleDHT22 DHT22(PIN_DHT22); //Controls the DHT22 module
File storageFile; //Controls writing to the SD card
/* VARIABLES */
float dht22_temperature;
float dht22_humidity;
int dht22_error = SimpleDHTErrSuccess;
void setup() {
Serial.begin(115200); //Start serial communication
pinMode(LED_BUILTIN, OUTPUT); //The built-in LED on pin 13 indicates when the Arduino is asleep
pinMode(PIN_WAKE_UP, INPUT_PULLUP); //Set pin as an input which uses the built-in pullup resistor
digitalWrite(LED_BUILTIN, HIGH); //Turn built-in LED on
// Initialise the alarms to known values, clear the alarm flags, clear the alarm interrupt flags
RTC.setAlarm(ALM1_MATCH_DATE, 0, 0, 0, 1);
RTC.setAlarm(ALM2_MATCH_DATE, 0, 0, 0, 1);
RTC.alarm(ALARM_1);
RTC.alarm(ALARM_2);
RTC.alarmInterrupt(ALARM_1, false);
RTC.alarmInterrupt(ALARM_2, false);
RTC.squareWave(SQWAVE_NONE);
time_t t; //create a temporary time variable so we can set the time and read the time from the RTC
t = RTC.get(); //Gets the current time of the RTC
RTC.setAlarm(ALM1_MATCH_MINUTES , 0, minute(t) + TIME_INTERVAL, 0, 0); // Setting alarm 1 to go off 5 minutes from now
// clear the alarm flag
RTC.alarm(ALARM_1);
// configure the INT/SQW pin for "interrupt" operation (disable square wave output)
RTC.squareWave(SQWAVE_NONE);
// enable interrupt output for Alarm 1
RTC.alarmInterrupt(ALARM_1, true);
/**Initializes the SD breakout board. If it is not ready or not connected correct it writes
an error message to the serial monitor
**/
Serial.print("Initializing SD card...");
if (!SD.begin(chipSelect)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
}
void loop() {
delay(5000);//wait 5 seconds before going to sleep. In real senairio keep this as small as posible
Going_To_Sleep();
//dht22ReadFromSensor();
}
void Going_To_Sleep() {
sleep_enable(); //Enabling sleep mode
attachInterrupt(0, wakeUp, LOW); //attaching an interrupt to pin d2
set_sleep_mode(SLEEP_MODE_PWR_DOWN); //Setting the sleep mode, in our case full sleep
digitalWrite(LED_BUILTIN, LOW); //turning LED off
time_t t; // creates temp time variable
t = RTC.get(); //gets current time from rtc
Serial.println("Sleep Time: " + String(hour(t)) + ":" + String(minute(t)) + ":" + String(second(t)));
delay(1000); //wait a second to allow the led to be turned off before going to sleep
sleep_cpu(); //activating sleep mode
Serial.println("just woke up!"); //next line of code executed after the interrupt
digitalWrite(LED_BUILTIN, HIGH); //turning LED on
t = RTC.get();
Serial.println("WakeUp Time: " + String(hour(t)) + ":" + String(minute(t)) + ":" + String(second(t)));
temp_Humi(); //function that reads the temp and the humidity
//Set New Alarm
RTC.setAlarm(ALM1_MATCH_MINUTES , 0, minute(t) + TIME_INTERVAL, 0, 0);
// clear the alarm flag
RTC.alarm(ALARM_1);
}
void wakeUp() {
Serial.println("Interrrupt Fired");//Print message to serial monitor
sleep_disable();//Disable sleep mode
detachInterrupt(0); //Removes the interrupt from pin 2;
}
/**
* Function to read the temperature and humidity of the DHT22 sensor.
*/
void dht22ReadFromSensor() {
//Read from the DHT22 sensor and assign values into variables, NULL is meant for raw data array.
int function_success = DHT22.read2(&dht22_temperature, &dht22_humidity, NULL);
//Check return value is NOT equal to constant for success
if (function_success != SimpleDHTErrSuccess) {
Serial.print("Read DHT22 failed, err=");
Serial.println(function_success);
//delay(2000);
return;
}
//TODO: Could return success value?
}
/**
the writeData function gets the humidity (h), temperature in celsius (t) and farenheit (f) as input
parameters. It uses the RTC to create a filename using the current date, and writes the temperature
and humidity with a date stamp to this file
*/
void writeData(float h, float t, float f) {
time_t p; //create time object for time and date stamp
p = RTC.get(); //gets the time from RTC
String file_Name = String(day(p)) + monthShortStr(month(p)) + String(year(p)) + ".txt"; //creates the file name we are writing to.
storageFile = SD.open(file_Name, FILE_WRITE);// creates the file object for writing
// if the file opened okay, write to it:
if (storageFile) {
Serial.print("Writing to " + file_Name);
//appends a line to the file with time stamp and humidity and temperature data
storageFile.println(String(hour(p)) + ":" + String(minute(p)) + " Hum: " + String(h) + "% C: " + String(t) + " F: " + String(f));
// close the file:
storageFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening " + file_Name);
}
//opening file for reading and writing content to serial monitor
storageFile = SD.open(file_Name);
if (storageFile) {
Serial.println(file_Name);
// read from the file until there's nothing else in it:
while (storageFile.available()) {
Serial.write(storageFile.read());
}
// close the file:
storageFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening" + file_Name);
}
}
|
#include <iostream>
struct Matrix
{
double matrix[100][100];
int M;
};
void read(Matrix& a)
{
do
{
std::cout << "Enter M: ";
std::cin >> a.M;
if (std::cin)
{
std::cin.clear();
std::cin.ignore(32767, '\n');
}
} while (a.M <= 0 || a.M > 100);
std::cout << "Enter the matrix: \n";
for (int i = 0; i < a.M; ++i)
{
for (int j = 0; j < a.M; ++j)
{
std::cin >> a.matrix[i][j];
}
}
}
void result(Matrix& a)
{
std::cout << "\n\n";
for (int i = 0; i < a.M; ++i)
{
for (int j = 0; j < a.M; ++j)
{
std::cout << a.matrix[a.M - j - 1][i] << ' ';
}
std::cout << '\n';
}
}
int main()
{
Matrix matrix;
read(matrix);
result(matrix);
return 0;
}
|
//Kris Li and William Easterby
/* hashTable.h
Implementation of templated hash table
*/
#ifndef HASH_TABLE_H
#define HASH_TABLE_H
#include <cstdlib>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
template<class ItemType, int TABLESIZE>
class HASH_TABLE {
public:
HASH_TABLE();
~HASH_TABLE();
int getKey(const string &value) const;
void add(int key, const ItemType &item);
//Return true if item is in table
bool inTable(int key, const ItemType &item) const;
//Return all items in a vector in a current key spot
vector<ItemType> getItemsAtKey(int key) const;
//Return number of items at key
int numItemsAtKey(int key) const;
void remove(int key, const ItemType &item);
int getTableSize() const;
private:
static const int tableSize = TABLESIZE;
vector<ItemType> items[TABLESIZE];
};
/*************************************
* Function implementations
*************************************/
template<class ItemType, int TABLESIZE>
HASH_TABLE<ItemType, TABLESIZE>::HASH_TABLE(){
}
template<class ItemType, int TABLESIZE>
HASH_TABLE<ItemType, TABLESIZE>::~HASH_TABLE(){
}
template<class ItemType, int TABLESIZE>
int HASH_TABLE<ItemType, TABLESIZE>::getKey(const string &value) const{
long unsigned int key = 0 ;
int numTimes = (value.length() / 3);
for (int i = 0 ; i < numTimes ; i++) {
key += value[value.length()-(i*3)-1] * pow(37, i) ;
}
return key%tableSize ;
}
template<class ItemType, int TABLESIZE>
void HASH_TABLE<ItemType, TABLESIZE>::add(int key, const ItemType &item){
if((key >= 0) && (key < tableSize))
items[key].push_back(item);
}
template<class ItemType, int TABLESIZE>
bool HASH_TABLE<ItemType, TABLESIZE>::inTable(int key, const ItemType &item) const{
bool result = false;
if((key >= 0) && (key < tableSize)) {
int size = items[key].size();
for(int i = 0; (i < size) && (!result); i++) {
if(items[key].at(i) == item)
result = true;
}
}
return result;
}
template<class ItemType, int TABLESIZE>
vector<ItemType> HASH_TABLE<ItemType, TABLESIZE>::getItemsAtKey(int key) const{
vector<ItemType> result;
if((key >= 0) && (key < tableSize))
result = items[key];
return result;
}
template<class ItemType, int TABLESIZE>
int HASH_TABLE<ItemType, TABLESIZE>::numItemsAtKey(int key) const{
int result = 0;
if((key >= 0 ) && (key < tableSize))
result = items[key].size();
return result;
}
template<class ItemType, int TABLESIZE>
void HASH_TABLE<ItemType, TABLESIZE>::remove(int key, const ItemType &item){
bool found = false;
if((key >= 0) && (key < tableSize)) {
int size = items[key].size();
for(int i = 0; (i < size) && (!found); i++) {
if(items[key].at(i) == item){
found = true;
items[key].erase(items[key].begin() + i);
}
}
}
}
template<class ItemType, int TABLESIZE>
int HASH_TABLE<ItemType, TABLESIZE>::getTableSize() const{
return tableSize;
}
#endif
|
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <type_traits>
#include <limits.h>
#include "Config.hpp"
#if defined(_MSC_VER)
#include <intrin.h>
namespace accel {
//
// Begin ByteSwap
//
template<typename __IntegerType>
__IntegerType ByteSwap(__IntegerType x) noexcept {
static_assert(std::is_integral<__IntegerType>::value,
"ByteSwap failure! Not a integer type.");
if constexpr (sizeof(x) == 2) {
return _byteswap_ushort(static_cast<uint16_t>(x));
} else if constexpr (sizeof(x) == 4) {
return _byteswap_ulong(static_cast<uint32_t>(x));
} else if constexpr (sizeof(x) == 8) {
return _byteswap_uint64(static_cast<uint64_t>(x));
} else {
static_assert(sizeof(__IntegerType) == 2 ||
sizeof(__IntegerType) == 4 ||
sizeof(__IntegerType) == 8,
"ByteSwap failure! Unsupported integer type.");
}
ACCEL_UNREACHABLE();
}
//
// Begin RotateShiftLeft
//
template<typename __IntegerType>
__IntegerType RotateShiftLeft(__IntegerType x, unsigned shift) noexcept {
static_assert(std::is_integral<__IntegerType>::value,
"RotateShiftLeft failure! Not a integer type.");
if constexpr (sizeof(x) == 1) {
return _rotl8(static_cast<uint8_t>(x), shift);
} else if constexpr (sizeof(x) == 2) {
return _rotl16(static_cast<uint16_t>(x), shift);
} else if constexpr (sizeof(x) == 4) {
return _rotl(static_cast<uint32_t>(x), shift);
} else if constexpr (sizeof(x) == 8) {
return _rotl64(static_cast<uint64_t>(x), shift);
} else {
static_assert(sizeof(__IntegerType) == 1 ||
sizeof(__IntegerType) == 2 ||
sizeof(__IntegerType) == 4 ||
sizeof(__IntegerType) == 8,
"RotateShiftLeft failure! Unsupported integer type.");
}
ACCEL_UNREACHABLE();
}
//
// Begin RotateShiftRight
//
template<typename __IntegerType>
__IntegerType RotateShiftRight(__IntegerType x, int shift) noexcept {
static_assert(std::is_integral<__IntegerType>::value,
"RotateShiftRight failure! Not a integer type.");
if constexpr (sizeof(x) == 1) {
return _rotr8(static_cast<uint8_t>(x), shift);
} else if constexpr (sizeof(x) == 2) {
return _rotr16(static_cast<uint16_t>(x), shift);
} else if constexpr (sizeof(x) == 4) {
return _rotr(static_cast<uint32_t>(x), shift);
} else if constexpr (sizeof(x) == 8) {
return _rotr64(static_cast<uint64_t>(x), shift);
} else {
static_assert(sizeof(__IntegerType) == 1 ||
sizeof(__IntegerType) == 2 ||
sizeof(__IntegerType) == 4 ||
sizeof(__IntegerType) == 8,
"RotateShiftRight failure! Unsupported integer type.");
}
ACCEL_UNREACHABLE();
}
}
#elif defined(__GNUC__)
#include <x86intrin.h>
namespace accel {
//
// Begin ByteSwap
//
template<typename __IntegerType>
ACCEL_FORCEINLINE
__IntegerType ByteSwap(__IntegerType x) noexcept {
static_assert(std::is_integral<__IntegerType>::value, "ByteSwap failure! Not a integer type.");
static_assert(sizeof(__IntegerType) == 2 ||
sizeof(__IntegerType) == 4 ||
sizeof(__IntegerType) == 8, "ByteSwap failure! Unsupported integer type.");
if constexpr (sizeof(__IntegerType) == 2) {
return __builtin_bswap16(x);
}
if constexpr (sizeof(__IntegerType) == 4) {
return __builtin_bswap32(x);
}
if constexpr (sizeof(__IntegerType) == 8) {
return __builtin_bswap64(x);
}
ACCEL_UNREACHABLE();
}
//
// Begin RotateShiftLeft
//
// The following code will be optimized by `rol` assembly code
//
template<typename __IntegerType>
ACCEL_FORCEINLINE
__IntegerType RotateShiftLeft(__IntegerType x, unsigned shift) noexcept {
static_assert(std::is_integral<__IntegerType>::value, "RotateShiftLeft failure! Not a integer type.");
shift %= sizeof(__IntegerType) * CHAR_BIT;
if (shift == 0)
return x;
else
return (x << shift) | (x >> (sizeof(__IntegerType) * CHAR_BIT - shift));
}
//
// Begin RotateShiftRight
//
// The following code will be optimized by `ror` assembly code
//
template<typename __IntegerType>
ACCEL_FORCEINLINE
__IntegerType RotateShiftRight(__IntegerType x, unsigned shift) noexcept {
static_assert(std::is_integral<__IntegerType>::value, "RotateShiftRight failure! Not a integer type.");
shift %= sizeof(__IntegerType) * CHAR_BIT;
if (shift == 0)
return x;
else
return (x >> shift) | (x << (sizeof(__IntegerType) * 8 - shift));
}
//
// Begin AddCarry
//
template<typename __IntegerType>
ACCEL_FORCEINLINE
uint8_t AddCarry(uint8_t carry, __IntegerType a, __IntegerType b, __IntegerType* p_c) {
static_assert(std::is_integral<__IntegerType>::value, "AddCarry failure! Not a integer type.");
static_assert(sizeof(__IntegerType) == 4 ||
sizeof(__IntegerType) == 8, "AddCarry failure! Unsupported integer type.");
if (sizeof(__IntegerType) == 4) {
return _addcarry_u32(carry, a, b, p_c);
}
if constexpr (sizeof(__IntegerType) == 8) {
#if defined(_M_X64) || defined(__x86_64__)
return _addcarry_u64(carry, a, b, p_c);
#else
static_assert(sizeof(__IntegerType) != 8, "AddCarry failure! Unsupported integer type.");
#endif
}
ACCEL_UNREACHABLE();
}
//
// Begin SubBorrow
//
template<typename __IntegerType>
ACCEL_FORCEINLINE
uint8_t SubBorrow(uint8_t borrow, __IntegerType a, __IntegerType b, __IntegerType* p_c) {
static_assert(std::is_integral<__IntegerType>::value, "SubBorrow failure! Not a integer type.");
static_assert(sizeof(__IntegerType) == 4 ||
sizeof(__IntegerType) == 8, "SubBorrow failure! Unsupported integer type.");
if (sizeof(__IntegerType) == 4) {
return _subborrow_u32(borrow, a, b, p_c);
}
if constexpr (sizeof(__IntegerType) == 8) {
#if defined(_M_X64) || defined(__x86_64__)
return _subborrow_u64(borrow, a, b, p_c);
#else
static_assert(sizeof(__IntegerType) != 8, "SubBorrow failure! Unsupported integer type.");
#endif
}
ACCEL_UNREACHABLE();
}
}
#else
#error "Unknown compiler"
#endif
|
#pragma once
#include <vector>
#include <string>
#include <memory>
#include "rttr/type.h"
namespace studio
{
class Node;
using NodePtr = std::shared_ptr<Node>;
class Node
{
public:
Node(const std::string &_name, rttr::type t) : name(_name), type(t){}
void addChild(NodePtr node)
{
node->parent = this;
children.push_back(node);
}
bool hasChild() const
{
return !children.empty();
}
size_t childCount() const
{
return children.size();
}
NodePtr at(int n)
{
return children[n];
}
NodePtr get(const std::string &childName)
{
for (auto c : children) { if (c->name == childName)return c; }
return nullptr;
}
NodePtr operator[](int n)
{
return at(n);
}
std::string name;
rttr::type type;
std::vector<NodePtr> children;
Node *parent{nullptr};
};
}
|
#include <bits/stdc++.h>
using namespace std;
struct Dir {
string name;
map<string, Dir *> subDir;
};
void print_directories(Dir *disk, string space_char) {
cout << space_char << disk->name << '\n';
space_char += " ";
for (auto &it : disk->subDir) {
print_directories(it.second, space_char);
}
}
int main() {
int n;
string s, temp;
cin >> n;
Dir *dir = new Dir;
dir->name = "";
for (int i = 1; i <= n; ++i) {
cin >> s;
s += "\\";
temp = "";
Dir *node = dir;
for (char j : s) {
if (j == '\\') {
auto it = node->subDir.find(temp);
if (it == node->subDir.end()) {
auto *new_node = new Dir();
new_node->name = temp;
node->subDir[temp] = new_node;
it = node->subDir.find(temp);
}
node = it->second;
temp = "";
} else {
temp += j;
}
}
}
for (auto &it : dir->subDir) {
print_directories(it.second, "");
}
}
|
#include <iostream>
#include <cstring>
#include "cipher.hpp"
#include "cgilib.hpp"
#include "freqan.hpp"
#include "hypertext.hpp"
void readData();
void errMsg();
int main()
{
char card[257];
std::string cipher, flag, keystr;
readQueryString(card);
std::cout << "Content-Type: text/html; charset=utf-8\n\n";
std::cout << "<!DOCTYPE HTML>\n";
std::cout << "<html>\n";
std::cout << "<head>\n";
std::cout << "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n";
// std::cout << "<link rel=\"stylesheet\" media=\"all\" href=\"/includes/style.css\">\n";
std::cout << "<link rel=\"stylesheet\" media=\"all\" href=\"/includes/gradienttable.css\">\n";
std::cout << "<title>cgi-bin C++ classical ciphers</title>\n";
std::cout << "</head>\n";
std::cout << "<body>\n";
std::cout << "<header><p>cgi-bin C++ classical ciphers</p></header>\n";
std::cout << "<p></p>\n";
std::cout << "<div><a href=\"/index.php\">Home</a> | <a href=\"/cppciphers.html\">Back</a></div>\n";
std::cout << "<p></p>\n";
if (strcmp(card, "step1") == 0) {
std::string formData;
getline(std::cin, formData);
// get cipher
std::string cipher = readFormValue(formData, "cipher");
// get keytype
std::string keytype = readFormValue(formData, "keytype");
// get action
std::string action = readFormValue(formData, "action");
// get keystring
std::string keystring = readFormValue(formData, "keystring");
stripKeyString(keystring);
// get message
std::string message = readFormValue(formData, "message");
// std::cout << "<p>" << message << "<p>\n";
stripMessage(message);
// trap for error and show user usage message
if (cipher != "coltran" && cipher != "keytran" && cipher != "keysub"
&&cipher != "Caesar" && cipher != "Affine" && cipher != "Vigenere"
&& cipher != "Gronsfeld" && cipher != "Porta" && cipher != "Beaufort"
&& cipher != "Variant" && cipher != "SlideI" && cipher != "SlideII"
&& cipher != "SlideIII")
{
errMsg();
printPageBottom();
return 1;
}
if (action != "encrypt" && action != "decrypt") {
errMsg();
printPageBottom();
return 1;
}
// check if user wants auto or progressive key encryption
bool autokey = false, progkey = false;
if (keytype == "auto") autokey = true;
if (keytype == "prog") progkey = true;
// check for empty, or too long, keystring
if (keystring.length() == 0 || keystring.length() > C) {
errMsg();
printPageBottom();
return 1;
}
// ready, steady, go
Cipher machine;
// read stdin to input buffer
machine.readBuf(message);
// process buffer in core
machine.processBuf(cipher, action, keystring, autokey, progkey);
// print html form
std::cout << "<form action='cppciphers.cgi?step1' method ='POST' accept-charset='utf-8'>\n";
// print cipher choice radio buttons
std::cout << "Cipher\n";
printButton("cipher", "coltran", "", true);
printButton("cipher", "keytran", "", false);
printButton("cipher", "Caesar", "", false);
printButton("cipher", "Affine", "", false);
printButton("cipher", "keysub", "", false);
printButton("cipher", "Vigenere", "", false);
printButton("cipher", "Gronsfeld", "", false);
printButton("cipher", "Porta", "", false);
printButton("cipher", "Beaufort", "", false);
printButton("cipher", "Variant", "", false);
printButton("cipher", "SlideI", "", false);
printButton("cipher", "SlideII", "", false);
printButton("cipher", "SlideIII", "", false);
// print key options raio buttons
std::cout << "<div>Key type (Affects only Vigenere, Beaufort and Variant.)</div>\n";
printButton("keytype", "regular", "", true);
printButton("keytype", "auto", "", false);
printButton("keytype", "prog", "", false);
// print encrypt/decrypt action radio buttons
std::cout << "<div>Action</div>\n";
printButton("action", "encrypt", "", true);
printButton("action", "decrypt", "", false);
// print key string textbox
std::cout << "<div>Key: <input type = 'text' name = 'keystring' size='50' value = ''>";
// print form submit button
std::cout << " <input type='submit' value='SUBMIT'></div>\n";
// print message area and message output buffer
std::cout << "<p></p>\n";
std::cout << "<textarea name = \"message\" cols = \"80\" rows = \"12\">\n";
machine.writeBuf();
std::cout << "</textarea>\n";
std::cout << "</form>\n";
// begin frequency analysis
FrequencyAnalyzer freqan;
freqan.cipherReport(machine);
// print bottom of page
printPageBottom();
}
return 0;
}
void readData()
{
std::string data_item;
getline(std::cin, data_item);
}
void errMsg()
{
std::cout << "<p>I'm sorry Dave, I'm afraid I can't do that.</p>\n";
}
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define MOD 1000000007
inline void Add(int& x, int y) {
x = (x + y) % MOD;
}
int main() {
freopen("spiral.in", "r", stdin);
freopen("spiral.out", "w", stdout);
cin >> n >> m;
if (n < m) swap(n, m);
f[0][0] = 1;
for (int i = 1; i <= n; ++i) {
f[i][0] = f[0][i] = i;
for (int j = 1; j <= m; ++j) {
int& ans = f[i][j];
Add(ans, j);
for (int k = 0; k < j; ++i) {
Add(ans, f[i][k]);
}
Add(ans, i);
for (int k = 1; k < i; ++i) {
Add(ans, f[i - 1][k]);
}
Add(ans, j);
for (int k = 1; k < j; ++i) {
Add(ans, f[i - 2][k]);
}
Add(ans, i);
for (int k = 1; k < i; ++i) {
Add(ans, f[i - 1][k]);
}
}
}
cout << f[i][j] << endl;
return 0;
}
|
#ifndef STARTMENUER_H
#define STARTMENUER_H
#include <QObject>
#include <QGraphicsScene>
#include <QPushButton>
#include<QGraphicsView>
#include"score.h"
class StartMenueR : public QObject
{
Q_OBJECT
public:
StartMenueR(QObject *parent=0);
QGraphicsView *v = new QGraphicsView();
Score *score;
private:
//QGraphicsView * view;
QGraphicsScene * scene;
QPushButton *play;
private slots:
void pressedstartkey(bool);
};
#endif // STARTMENUER_H
|
#define _CRT_SECURE_NO_WARNINGS
#include "vector3f.h"
using namespace std;
#define ESCAPE '\033'
#define DELETE '\010'
unsigned char* image1;
int J = 0, JL = 0;
int Width = 700, Height = 700;
double t_min = 1, t_max = 1e+25;
double tetta = 120;
double N = 1;
double Aspect = (double)Width / Height;
double H = N * tan((double)tetta * 3.1415926535897932 / 360.0);
double W = H * Aspect;
int figMenu, mainMenu, lightMenu;
Vector3f O(0, 0, -150);
Vector3f D, pointHit;
int r, c;
int numFigures, numSpheres = 0;
int depth = 1;
vector<int> flagFigures;
vector<int> flagLight{ 1,1,1,1 };
struct Material {
Material(const double& ka, const double& kd, const double& ks, const double& kr, const Vector3f& color, const double& spec) :ka(ka), kd(kd), ks(ks), kr(kr), Color(color), specularExponent(spec) {}
Material() : ka(1), kd(1), ks(0), kr(0), Color(), specularExponent() {}
double ka;// фоновое
double kd;// диффузное
double ks;//блики
double kr;//отражение
Vector3f Color;
double specularExponent;
};
//список материалов
vector<Material> mats{ Material(0.9, 0.7,0.5, 0.5, Vector3f(0.,1.,0.), 50.),Material(0.9, 0.7, 2., 0.5, Vector3f(0.,0.,1.), 50.),Material(0.9, 0.7, 2., 0.5, Vector3f(1.,1.,0.), 50.) };
struct Sphere {
Vector3f center;
double radius;
Material material;
Sphere(Vector3f center, double radius, int numM) :center(center), radius(radius), material(mats[numM]) {}
Sphere() {}
};
struct Tetra {
vector<Vector3f> points{ Vector3f(0,0,0),Vector3f(0,0,0), Vector3f(0,0,0), Vector3f(0,0,0) };
vector<Vector3f> normals{ Vector3f(0,0,0),Vector3f(0,0,0), Vector3f(0,0,0), Vector3f(0,0,0) };
vector<double> di{ 0,0,0,0 };
Material material;
Tetra() {}
};
struct Plane {
Vector3f normal;
double di;
Material material;
Plane(Vector3f normal, double di, Material material) : normal(normal), di(di), material(material) {}
};
struct Light {
Light(const Vector3f& p, const double& i) : position(p), intensity(i) {}
Vector3f position;
double intensity;
};
Vector3f tmpCol;
vector<Sphere> spheres;
vector<Tetra> tetras;
Sphere closestSphere;
Tetra closestTetra;
Plane plane(Vector3f(0., -4, 1.), 30., Material(1., 0.4, 0., 0., Vector3f(0.7, 0.7, 0.7), 0.));
Vector3f nowColor{ 1.,1.,1. };
Vector3f backGroudColor{ 1.,1.,1. };
int closestFlag;//ближайший объект: 0-сфера, 1-тетраэдр
double closestT;
vector<Light> lights{ Light(Vector3f(-25,20,0), 1), Light(Vector3f(130, 0, 10), 0.5) };
//норма вектора
double Norm(Vector3f v1) {
return (double)sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z);
}
//нормализация
Vector3f Normalize(Vector3f v1) {
double norm = Norm(v1);
Vector3f res;
res.x = 0;
res.y = 0;
res.z = 0;
if (norm != 0) {
res.x = v1.x / norm;
res.y = v1.y / norm;
res.z = v1.z / norm;
}
return res;
}
//векторное произведение
Vector3f Vector(Vector3f v1, Vector3f v2) {
Vector3f res;
res.x = v1.y * v2.z - v2.y * v1.z;
res.y = -v1.x * v2.z + v2.x * v1.z;
res.z = v1.x * v2.y - v2.x * v1.y;
return res;
}
//нормаль между двумя векторами
Vector3f Normal(Vector3f v1, Vector3f v2) {
Vector3f res = Vector(v1, v2);
res = Normalize(res);
return res;
}
double dot(Vector3f vec1, Vector3f vec2)
{
return (vec1.x * vec2.x + vec1.y * vec2.y + vec1.z * vec2.z);
}
Vector3f Reflect(Vector3f& L, Vector3f& N) { //отраженный луч h
return L - Vector((Vector(L, N) * 2), N);
}
void ReadFigures() {
ifstream fin("figures.txt");
fin >> numFigures;
flagFigures.resize(numFigures);
fill(flagFigures.begin(), flagFigures.end(), 1);
int type;// 0-сфера,1-пирамида
for (int i = 0; i < numFigures; i++)
{
fin >> type;
if (type == 0) {
int numM;
Sphere sphere;
fin >> sphere.center.x >> sphere.center.y >> sphere.center.z >> sphere.radius >> numM;
sphere.material = mats[numM];
spheres.push_back(sphere);
numSpheres++;
}
else {
int numM;
Tetra tetraedr;
for (int i = 0; i < 4; i++) {
fin >> tetraedr.points[i].x >> tetraedr.points[i].y >> tetraedr.points[i].z;
}
fin >> numM;
//расчет нормалей и di
tetraedr.normals[0] = Normal(tetraedr.points[1] - tetraedr.points[0], tetraedr.points[2] - tetraedr.points[1]);
tetraedr.normals[1] = Normal(tetraedr.points[0] - tetraedr.points[1], tetraedr.points[3] - tetraedr.points[0]);
tetraedr.normals[2] = Normal(tetraedr.points[1] - tetraedr.points[2], tetraedr.points[3] - tetraedr.points[1]);
tetraedr.normals[3] = Normal(tetraedr.points[2] - tetraedr.points[0], tetraedr.points[3] - tetraedr.points[2]);
for (int i = 0; i < 4; i++)
tetraedr.di[i] = dot(tetraedr.points[i], tetraedr.normals[i]);
tetraedr.material = mats[numM];
tetras.push_back(tetraedr);
}
}
fin.close();
}
Vector3f CanvasToViewport() {
double uc = 2. * W * c / Width;
double vr = 2. * H * r / Height;
Vector3f u(1., 0, 0), v(0, 1., 0), w(0, 0, 1.);
Vector3f tmp = u * uc + v * vr + w * N;
return tmp;
}
void IntersectRaySphere(Vector3f orig, Vector3f dir, Sphere sphere, double& t1, double& t2) {
Vector3f C = sphere.center;
double rad = sphere.radius;
Vector3f OC = orig - C;
double k1 = dot(dir, dir);
double k2 = 2 * dot(OC, dir);
double k3 = dot(OC, OC) - rad * rad;
double discriminant = k2 * k2 - 4 * k1 * k3;
if (discriminant < 0)
t1 = t2 = 1e+25;
else
{
t1 = (-k2 + sqrt(discriminant)) / (2 * k1);
t2 = (-k2 - sqrt(discriminant)) / (2 * k1);
}
}
int IntersectRayTetra(Vector3f orig, Vector3f dir, Tetra tetraedr, double& alfa) {
// Пересечение луча и многогранника:
// Вход: Луч из точки O в направлении d (|d| = 1).
// Набор k плоскостей с нормалями ni и параметрами di, i = 1, k.
double fMax = 1;
double bMin = 1e+25;
alfa = 1e+25;
for (int i = 0; i < 4; i++) {
// Пересечение луча и плоскости
double s = dot(dir, tetraedr.normals[i]);
if (s == 0) { // луч и плоскость параллельны
if (dot(orig, tetraedr.normals[i]) > tetraedr.di[i]) {
return 1; // пересечения нет
}
}
// Если непараллельно плоскости
alfa = (tetraedr.di[i] - dot(orig, tetraedr.normals[i])) / s;
if (dot(dir, tetraedr.normals[i]) < 0) { // если пересечение "сверху"
if (alfa > fMax) {
if (alfa > bMin) {
return 1; // пересечения нет
}
fMax = alfa;
}
}
else { // если пересечение "снизу"
if (alfa < bMin) {
if (alfa < 0 || alfa < fMax) {
return 1; // пересечения нет
}
bMin = alfa;
}
}
}
alfa = fMax > 0 ? fMax : bMin;
return 0;
}
int IntersectRayPlane(Vector3f orig, Vector3f dir, Plane plane, double& alfa) {
alfa = 1e+25;
// Вход: Луч из точки p в направлении u (|u| = 1).
// Плоскость с нормалью n и параметром d.
double s = dot(dir, plane.normal);
if (s != 0) { // пересечения нет
double tmp = (plane.di - dot(orig, plane.normal)) / s;
if (tmp >= 0) {
alfa = tmp;
return 0;
}
}
return 1;
}
int FindTetraPlane(Tetra tetraedr, Vector3f toFind) {
//передняя
if (toFind.x >= min(tetraedr.points[0].x, tetraedr.points[1].x) && toFind.x <= max(tetraedr.points[0].x, tetraedr.points[1].x) &&
toFind.z >= min(tetraedr.points[0].z, tetraedr.points[1].z) && toFind.z <= max(tetraedr.points[0].z, tetraedr.points[1].z) &&
toFind.y >= min(tetraedr.points[0].y, tetraedr.points[1].y) && toFind.y <= tetraedr.points[3].y)
return 1;
//правая
if (toFind.x >= min(tetraedr.points[1].x, tetraedr.points[2].x) && toFind.x <= max(tetraedr.points[1].x, tetraedr.points[2].x) &&
toFind.z >= min(tetraedr.points[1].z, tetraedr.points[2].z) && toFind.z <= max(tetraedr.points[1].z, tetraedr.points[2].z) &&
toFind.y >= min(tetraedr.points[1].y, tetraedr.points[2].y) && toFind.y <= tetraedr.points[3].y)
return 2;
//левая
if (toFind.x >= min(tetraedr.points[2].x, tetraedr.points[0].x) && toFind.x <= max(tetraedr.points[2].x, tetraedr.points[0].x) &&
toFind.z >= min(tetraedr.points[2].z, tetraedr.points[0].z) && toFind.z <= max(tetraedr.points[2].z, tetraedr.points[0].z) &&
toFind.y >= min(tetraedr.points[2].y, tetraedr.points[0].y) && toFind.y <= tetraedr.points[3].y)
return 3;
return 0;
}
Vector3f TraceRay(Vector3f& orig, Vector3f& dir, int depth) {
closestFlag = -1;
closestT = 1e+25;
double sphT = 1e+25, pirT = 1e+25, plT = 1e+25;
//Material closestMaterial;
bool flagS = false, flagP = false, flagPl = false;
Vector3f curColor = backGroudColor;
for (int i = 0; i < numSpheres; i++) {
if (flagFigures[i] == 1) {
Sphere sphere = spheres[i];
double t1, t2;
IntersectRaySphere(orig, dir, sphere, t1, t2);
if (t1 > t_min && t1 < t_max && t1 < sphT) {
flagS = true;
sphT = t1;
closestSphere = sphere;
}
if (t2 > t_min && t2 < t_max && t2 < sphT) {
flagS = true;
sphT = t2;
closestSphere = sphere;
}
}
}
for (int i = numSpheres; i < numFigures; i++) {
if (flagFigures[i] == 1) {
Tetra piramid = tetras[i - numSpheres];
double alfa;
if (IntersectRayTetra(orig, dir, piramid, alfa) == 0) {
if (alfa > t_min && alfa < t_max && alfa < pirT) {
flagP = true;
pirT = alfa;
closestTetra = piramid;
}
}
}
}
double alfa;
if (IntersectRayPlane(orig, dir, plane, alfa) == 0) {
if (alfa > t_min && alfa < t_max && alfa < plT) {
flagPl = true;
plT = alfa;
}
}
if (flagPl == true) {//нашли плоскость
if (flagS == true) {//нашли плоскость, сферу и хз
if (flagP == true) {//нашли все 3
if (pirT < sphT) {
if (plT < pirT) {//плоскость ближе
curColor = plane.material.Color;
closestT = plT;
closestFlag = 2;
}
else {//тетраэдр ближе
curColor = closestTetra.material.Color;
closestT = pirT;
closestFlag = 1;
}
}
else {//проверим плоскость и сферу
if (plT < sphT) {//плоскость ближе
curColor = plane.material.Color;
closestT = plT;
closestFlag = 2;
}
else {//сфера ближе
curColor = closestSphere.material.Color;
closestT = sphT;
closestFlag = 0;
}
}
}
else {//нашли сферу и плоскость
if (sphT < plT) {
curColor = closestSphere.material.Color;
closestT = sphT;
closestFlag = 0;
}
else {
curColor = plane.material.Color;
closestT = plT;
closestFlag = 2;
}
}
}
else {//нашли плоскость и пирамиду
if (pirT < plT) {
curColor = closestTetra.material.Color;
closestT = pirT;
closestFlag = 1;
}
else {
curColor = plane.material.Color;
closestT = plT;
closestFlag = 2;
}
}
}
else {
if (flagS == true) {
if (flagP == true) {
if (pirT < sphT) {
curColor = closestTetra.material.Color;
closestT = pirT;
closestFlag = 1;
}
else {
curColor = closestSphere.material.Color;
closestT = sphT;
closestFlag = 0;
}
}
else {//нашли только сферу
curColor = closestSphere.material.Color;
closestT = sphT;
closestFlag = 0;
}
}
else {
if (flagP == true) {//нашли только пирамиду
curColor = closestTetra.material.Color;
closestT = pirT;
closestFlag = 1;
}
}
}
//ЦВЕТА и СВЕТ
double diffuseLightIntensity = 0, specularLightIntensity = 0, ambientLigthIntensity = 0.5;
if (closestFlag == 0) {//свет для сферы
pointHit = orig + dir * closestT;
curColor = closestSphere.material.Color;
//double ka, kd, ks, specExp;
Vector3f ReflectColor = Vector3f(1., 0., 0.);
Vector3f ReflectDir;
Vector3f ReflectOrig;
for (int i = 0; i < lights.size(); i++) {
if (flagLight[i] == 1) {
Vector3f lightDir = Normalize(lights[i].position - pointHit);//падающий луч l
Vector3f PointToCenter = Normalize(pointHit - closestSphere.center); //нормаль в обратную сторону n
ambientLigthIntensity *= closestSphere.material.ka;
diffuseLightIntensity += lights[i].intensity * max(0., dot(lightDir, PointToCenter)) * closestSphere.material.kd;
specularLightIntensity += powf(max(0., (dot(PointToCenter, Reflect(lightDir, PointToCenter)))), closestSphere.material.specularExponent) * lights[i].intensity * closestSphere.material.ks;
}
}
curColor = curColor * ambientLigthIntensity + curColor * diffuseLightIntensity + Vector3f(1., 1., 1.) * specularLightIntensity;
}
else {
if (closestFlag == 1) {//свет для пирамиды
pointHit = orig + dir * closestT;
curColor = closestTetra.material.Color;
for (int i = 0; i < lights.size(); i++) {
if (flagLight[i] == 1) {
Vector3f lightDir = Normalize(lights[i].position - pointHit);
int numNormal = FindTetraPlane(closestTetra, pointHit);
Vector3f PointToCenter = closestTetra.normals[numNormal];
diffuseLightIntensity += lights[i].intensity * max(0., dot(lightDir, PointToCenter));
specularLightIntensity += powf(max(0., (dot(PointToCenter, Reflect(lightDir, PointToCenter)))), closestTetra.material.specularExponent) * lights[i].intensity * closestTetra.material.ks;
}
}
curColor = curColor * ambientLigthIntensity + curColor * diffuseLightIntensity + Vector3f(1., 1., 1.) * specularLightIntensity;
}
else if (closestFlag == 2) {//свет для плоскости
Vector3f ReflectDir, ReflectOrig, ReflectColor;
if (closestFlag == 2) {//свет для плоскости
curColor = plane.material.Color;
pointHit = orig + dir * closestT;
Vector3f PointToCenter = plane.normal * (-1);
for (int i = 0; i < lights.size(); i++) {
if (flagLight[i] == 1) {
Vector3f lightDir = Normalize(lights[i].position - pointHit);
ambientLigthIntensity *= plane.material.ka;
diffuseLightIntensity += lights[i].intensity * max(0., dot(lightDir, PointToCenter)) * plane.material.kd;
specularLightIntensity += powf(max(0., (dot(PointToCenter, Reflect(lightDir, PointToCenter)))), plane.material.specularExponent) * lights[i].intensity * plane.material.ks;
}
}
curColor = curColor * ambientLigthIntensity + curColor * diffuseLightIntensity + Vector3f(1., 1., 1.) * specularLightIntensity;
}
}
}
return curColor;
}
/* Функция вывода на экран */
void Display(void) {
glClearColor(0.5, 0.5, 0.5, 1);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
for (r = -Height / 2; r <= Height / 2; r++) {
for (c = -Width / 2; c < Width / 2; c++) {
if (c == 0 && r == 0)
{
cout << "*";
}
D = CanvasToViewport();//направление
nowColor = TraceRay(O, D, 0);// возвращаем цвет пикселя
glBegin(GL_POINTS);
glColor3f(nowColor.x, nowColor.y, nowColor.z);
glVertex2f(c, r);
glEnd();
}
}
glFinish();
}
/* Функция обработки сообщений от клавиатуры */
void Keyboard(unsigned char key, int x, int y) {
if (key == 'a') { // переходим на свет влево
if (JL > 0)
JL--;
}
if (key == 'd') { // переходим на свет вправо
if (JL < lights.size() - 1)
JL++;
}
if (key == 'w') {
flagLight[JL] = 1; // вкл
glutPostRedisplay();
}
if (key == 's') {
flagLight[JL] = 0; // не вкл
glutPostRedisplay();
}
if (key == '-') { // переходим на фигуру влево
if (J > 0)
J--;
}
if (key == '=') { // переходим на фигуру вправо
if (J < numFigures - 1)
J++;
}
if (key == 'p') {
flagFigures[J] = 1; // рисуем
glutPostRedisplay();
}
if (key == 'o') {
flagFigures[J] = 0; // не рисуем
glutPostRedisplay();
}
}
int menuFlag;
void processMainMenu(int option) {
switch (option) {
case 1:
if (flagFigures[J] == 1)
flagFigures[J] = 0;
else flagFigures[J] = 1;
break;
case 2:
if (flagLight[JL] == 1)
flagLight[JL] = 0;
else flagLight[JL] = 1;
}
glutPostRedisplay();
}
void processFigMenu(int option) {
switch (option) {
case 1:
if (J < numFigures - 1)
J++;
break;
case 2:
if (J > 0)
J--;
break;
}
glutPostRedisplay();
}
void processLightMenu(int option) {
switch (option) {
case 1:
if (JL < lights.size() - 1)
JL++;
break;
case 2:
if (JL > 0)
JL--;
break;
}
glutPostRedisplay();
}
void createPopupMenus() {
figMenu = glutCreateMenu(processFigMenu);
glutAddMenuEntry("Следующая фигура", 1);
glutAddMenuEntry("Предыдущая фигура", 2);
lightMenu = glutCreateMenu(processLightMenu);
glutAddMenuEntry("Следующий источник", 1);
glutAddMenuEntry("Предыдущий источник", 2);
mainMenu = glutCreateMenu(processMainMenu);
glutAddMenuEntry("Включить/Выключить фигуру", 1);
glutAddSubMenu("Переключение фигуры", figMenu);
glutAddMenuEntry("Включить/Выключить свет", 2);
glutAddSubMenu("Переключение света", lightMenu);
// прикрепить меню к правой кнопке мыши
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
/* Функция изменения размеров окна */
void Reshape(GLint w, GLint h) {
Width = w;
Height = h;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-w / 2, w / 2, -h / 2, h / 2, -10000, 10000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/* Головная программа */
void main(int argc, char* argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(Width, Height);
ReadFigures();
glutCreateWindow("RayTracing");
glutKeyboardFunc(Keyboard);
glutDisplayFunc(Display);
glutReshapeFunc(Reshape);
createPopupMenus();
glutMainLoop();
}
|
#include <iostream>
using namespace std;
int main()
{
/*Initialization*/
char type = 0, initial_1 = 0, final_1 = 0;
int initial_2 = 0, final_2 = 0;
cout << "Welcome to Chess Mania!!!!\n\n";
//Taking input from the user
cout << "Enter the type of your piece\n"
<< "Enter P for Pawn, K for King, Q for Queen, B for Bishop, N for Knight\n";
cin >> type;
//initial_1 for the character part & initial_2 for the integer part
cout << "\nEnter the initial Position i.e \"e 6\". Mind the space in between!\n";
cin >> initial_1 >> initial_2;
//final_1 for the character part & final_2 for the integer part
cout << "\nEnter the final Position i.e \"f 7\". Mind the space in between!\n";
cin >> final_1 >> final_2;
//Checking if the user has input the right positions
if ((initial_1 >= 'a' && initial_1 <= 'h') && (final_1 >= 1 && final_2 <= 8))
{
cout << "Initial_1 : " << initial_1 << endl;
cout << "Initial_2 : " << initial_2 << endl;
cout << "Final_1 : " << final_1 << endl;
cout << "Final_2 : " << final_2 << endl;
cout << "Type : " << type << endl << endl;
// For Pawn
if (type == 'P')
{
if (initial_1 == final_1)
{
if ((final_2 > initial_2) && (final_2 - initial_2 == 1))
{
cout << "Good move!\n";
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
// For King
else if (type == 'K')
{
if (initial_1 == final_1)
{
if ((final_2 > initial_2) && (final_2 - initial_2 == 1))
{
cout << "Good move!\n";
}
else if ((final_2 < initial_2) && (initial_2 - final_2 == 1))
{
cout << "Good move!\n";
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
else if ((final_1 - initial_1 == 1) || (initial_1 - final_1 == 1))
{
if ((final_2 > initial_2) && (final_2 - initial_2 == 1))
{
cout << "Good move!\n";
}
else if ((final_2 < initial_2) && (initial_2 - final_2 == 1))
{
cout << "Good move!\n";
}
else if (final_2 == initial_2)
{
cout << "Good move!\n";
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
// For Queen
else if (type == 'Q')
{
if (initial_1 == final_1)
{
if (final_2 != initial_2)
{
cout << "Good move!\n";
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
else if (final_1 > initial_1)
{
if (final_2 == initial_2)
{
cout << "Good move!\n";
}
else if (final_2 > initial_2)
{
for (int j = initial_2 + 1, i = initial_1 + 1; (i <= 'h') && (j <= 8); i++, j++)
{
if ((final_1 == i) && (final_2 == j))
{
cout << "Good move\n";
break;
}
}
}
else if (final_2 < initial_2)
{
for (int j = initial_2 - 1, i = initial_1 + 1; (i <= 'h') && (j >= 1); i++, j--)
{
if ((final_1 == i) && (final_2 == j))
{
cout << "Good move\n";
break;
}
}
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
else if (final_1 < initial_1)
{
if (final_2 == initial_2)
{
cout << "Good move!\n";
}
else if (final_2 > initial_2)
{
for (int j = initial_2 + 1, i = initial_1 - 1; (i >= 'a') && (j <= 8); i--, j++)
{
if ((final_1 == i) && (final_2 == j))
{
cout << "Good move\n";
break;
}
}
}
else if (final_2 < initial_2)
{
for (int j = initial_2 - 1, i = initial_1 - 1; (i >= 'a') && (j >= 1); i--, j--)
{
if ((final_1 == i) && (final_2 == j))
{
cout << "Good move\n";
break;
}
}
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
// For Bishop
else if (type == 'B')
{
if (final_1 > initial_1)
{
if (final_2 > initial_2)
{
for (int j = initial_2 + 1, i = initial_1 + 1; (i <= 'h') && (j <= 8); i++, j++)
{
if ((final_1 == i) && (final_2 == j))
{
cout << "Good move\n";
break;
}
}
}
else if (final_2 < initial_2)
{
for (int j = initial_2 - 1, i = initial_1 + 1; (i <= 'h') && (j >= 1); i++, j--)
{
if ((final_1 == i) && (final_2 == j))
{
cout << "Good move\n";
break;
}
}
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
else if (final_1 < initial_1)
{
if (final_2 > initial_2)
{
for (int j = initial_2 + 1, i = initial_1 - 1; (i >= 'a') && (j <= 8); i--, j++)
{
if ((final_1 == i) && (final_2 == j))
{
cout << "Good move\n";
break;
}
}
}
else if (final_2 < initial_2)
{
for (int j = initial_2 - 1, i = initial_1 - 1; (i >= 'a') && (j >= 1); i--, j--)
{
if ((final_1 == i) && (final_2 == j))
{
cout << "Good move\n";
break;
}
}
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
// For Knight
else if (type == 'N')
{
if (final_1 > initial_1)
{
if ((final_1 - initial_1 == 1) && ((final_2 - initial_2 == 2) || (initial_2 - final_2 == 2)))
{
cout << "Good move!\n";
}
else if ((final_1 - initial_1 == 2) && ((final_2 - initial_2 == 1) || (initial_2 - final_2 == 1)))
{
cout << "Good move!\n";
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
else if (final_1 < initial_1)
{
if ((initial_1 - final_1 == 1) && ((final_2 - initial_2 == 2) || (initial_2 - final_2 == 2)))
{
cout << "Good move!\n";
}
else if ((initial_1 - final_1 == 2) && ((final_2 - initial_2 == 1) || (initial_2 - final_2 == 1)))
{
cout << "Good move!\n";
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
else
{
cout << "Tumharey piece se na ho paye ga";
}
}
else
{
cout << "What type is this? Bhai kidhr se aye ho? Kon si chess he ye!\n";
}
}
else
{
cout << "The details you have entered are incorrect! Kindly enter the correct detail!\n";
}
}
|
#include "engine/GameEngine.hpp"
#include "game/Player.hpp"
#include "game/GameMessage.hpp"
GameEngine::GameEngine(int c_or_s){
camera = new SDL_Rect();
camera->x = 0;
camera->y = 0;
camera->w = CAMERA_WIDTH;
camera->h = CAMERA_HEIGHT;
pauseMode = new PauseMode();
homeMode = new HomeMode() ;
gMode = homeMode;
currMode = HOME_MODE;
if (c_or_s){
clientObj = new ClientNet();
}
else{
serverObj = new ServerNet();
}
// cout<<"in\n";
playMode = new PlayMode(true, clientObj, serverObj);
audioMaster = new AudioMaster();
audioStore = new AudioStore();
}
bool GameEngine::init()
{
audioMaster->init();
audioStore->init();
bgm = audioStore->getSourceFor(AS_BGM);
startbgm();
//Initialization flag
bool success = true;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Set texture filtering to linear
if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
{
printf( "Warning: Linear texture filtering not enabled!" );
}
//Create window
gWindow = SDL_CreateWindow( "Maze Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( gWindow == NULL )
{
printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Create vsynced renderer for window
gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );
if( gRenderer == NULL )
{
printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Initialize renderer color
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) )
{
printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
success = false;
}
if( TTF_Init() == -1 )
{
printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() );
success = false;
}
}
}
}
return success;
}
void GameEngine::checkRoundEnd(){
if (serverObj!=NULL){
if (playMode->canReturnHome){
setGameMode(HOME);
return;
}
if (playMode->roundEndMessageInit){
return;
}
PlayerObj winner;
if (playMode->playerObj == ATTACK){
winner = DEFEND;
}
else{
winner = ATTACK;
}
if(playMode->LoadingComplete && !serverObj->isConnected()){
playMode->setWinner(0);
playMode->gameMessage->resetMessage("ROUND OVER", playMode->RoundEndMessageDuration, DRAW_DISCONNECT, false);
playMode->currentRoundNum = -1;
playMode->roundEndMessageInit = true;
return;
}
if (currMode==PLAY_MODE || currMode==PAUSE_MODE){
if (playMode->player->getHealth()<=0){
if (playMode->playerObj==DEFEND || playMode->bombState==IDLE || playMode->bombState==PLANTING){
playMode->setWinner(winner);
serverObj->SendRoundEndSignal(winner);
playMode->gameMessage->resetMessage("ROUND OVER", playMode->RoundEndMessageDuration, winner,false);
playMode->roundEndMessageInit = true;
}
else{
if(!playMode->player->isDead){
playMode->updatePlayerToDead(0);
serverObj->sendPlayerDead(0);
}
}
}
else if (playMode->otherPlayer->getHealth()<=0){
if (playMode->playerObj==ATTACK || playMode->bombState==IDLE || playMode->bombState==PLANTING){
playMode->setWinner(playMode->playerObj);
serverObj->SendRoundEndSignal(playMode->playerObj);
playMode->gameMessage->resetMessage("ROUND OVER", playMode->RoundEndMessageDuration, playMode->playerObj,false);
playMode->roundEndMessageInit = true;
}
else{
if(!playMode->otherPlayer->isDead){
playMode->updatePlayerToDead(1);
serverObj->sendPlayerDead(1);
}
}
}
if (playMode->clock->timeOver()){
if (playMode->bombState == PLANTED || playMode->bombState == DEFUSING){
playMode->setWinner(ATTACK);
cout << "TIME OVER GAME END" << endl;
serverObj->SendRoundEndSignal(ATTACK);
playMode->gameMessage->resetMessage("ROUND OVER", playMode->RoundEndMessageDuration, ATTACK, true);
playMode->roundEndMessageInit = true;
}
else{
playMode->setWinner(DEFEND);
serverObj->SendRoundEndSignal(DEFEND);
playMode->gameMessage->resetMessage("ROUND OVER", playMode->RoundEndMessageDuration, DEFEND, false);
playMode->roundEndMessageInit = true;
}
}
if (playMode->bombState==DEFUSED){
playMode->setWinner(DEFEND);
// cout<<"IN1\n";
serverObj->SendRoundEndSignal(DEFEND);
playMode->gameMessage->resetMessage("ROUND OVER", playMode->RoundEndMessageDuration, DEFEND,false);
playMode->roundEndMessageInit = true;
}
}
}
else{
if (playMode->canReturnHome){
setGameMode(HOME);
return;
}
if (playMode->roundEndMessageInit){
return;
}
if(playMode->LoadingComplete && !clientObj->isConnected()){
playMode->setWinner(0);
playMode->gameMessage->resetMessage("ROUND OVER", playMode->RoundEndMessageDuration, DRAW_DISCONNECT, false);
playMode->currentRoundNum = -1;
playMode->roundEndMessageInit = true;
return;
}
if (playMode->roundOver){
playMode->gameMessage->resetMessage("ROUND OVER", playMode->RoundEndMessageDuration, playMode->roundWinner, playMode->clock->timeOver() && playMode->bombState == PLANTED);
playMode->roundEndMessageInit = true;
}
}
}
void GameEngine::runLoop(){
SDL_Event e;
homeMode->enterMode();
while( !quit_program )
{
//Handle events on queue
checkRoundEnd();
while( SDL_PollEvent( &e ) != 0 )
{
//User requests quit
if( e.type == SDL_QUIT )
{
quit_program = true;
}
//Handle input for the player
gMode->eventHandler(e);
}
//Clear screen
SDL_SetRenderDrawColor( gEngine->gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
SDL_RenderClear( gEngine->gRenderer );
if (currMode==PAUSE_MODE){
playMode->update(false);
}
SDL_SetRenderDrawColor( gEngine->gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
SDL_RenderClear( gEngine->gRenderer );
gMode->update();
// cout<<currMode<<"\n";
//Update screen
SDL_RenderPresent( gEngine->gRenderer );
// if (currMode == 1)cout<<"in\n";
}
//Free loaded images
// playMode->freePlayMode();
bgm->free();
audioMaster->free();
audioStore->free();
//Destroy window
SDL_DestroyRenderer(gRenderer );
SDL_DestroyWindow(gWindow );
gWindow = NULL;
gRenderer = NULL;
//Quit SDL subsystems
IMG_Quit();
SDL_Quit();
TTF_Quit();
}
void GameEngine::updateOtherPlayer(std::vector<int> &data){
if (currMode==PLAY_MODE || currMode==PAUSE_MODE){
playMode->otherPlayer->setPosVel(data[1], data[2], data[3], data[4]);
playMode->otherPlayer->setRotation(data[5]);
}
}
void GameEngine::addThrowableToVector(std::vector<int> &data){
if (currMode==PLAY_MODE || currMode==PAUSE_MODE){
ThrowableType type;
if (data[5]==0){
type=BULLET;
}
else{
type = KNIFE_SLASH;
}
playMode->spawnThrowable(data[1],data[2],(int)sqrt(data[3]*data[3]+data[4]*data[4]),((double)data[6])/1e8,0, type);
}
}
void GameEngine::damagePlayer(std::vector<int> &data){
if (currMode==PLAY_MODE || currMode==PAUSE_MODE){
if ((playMode->currentRoundNum) ==data[2]){
playMode->player->damage(data[1]);
}
}
}
void GameEngine::updateMapfromServer(vector<int> &map_vec){
playMode->tileMap->initializeMap(LEVEL_HEIGHT/TILE_SIZE, LEVEL_WIDTH/TILE_SIZE);
for (int i=1; i<(int)map_vec.size(); i++){
if (map_vec[i]==1){
playMode->tileMap->setMap((i-1)/20, (i-1)%20, true);
}
else{
playMode->tileMap->setMap((i-1)/20, (i-1)%20, false);
}
}
}
void GameEngine::resetListener(int x,int y){
// cout << "listener at " <<x <<" " << y << endl;
audioMaster->setListenerPosition(x,y,0);
}
void GameEngine::setGameMode(GameModeType a){
switch (a)
{
case QUIT:
quit_program=true;
break;
case PLAY:
gMode = playMode;
currMode = PLAY_MODE;
playMode->Reset();
// if (clientObj!=NULL){
// clientObj->Connect(server_address.c_str(), server_port);
// }
playMode->enterMode();
break;
case RESUME:
stopbgm();
gMode = playMode;
currMode = PLAY_MODE;
playMode->enterMode();
break;
case PAUSE:
startbgm();
gMode = pauseMode;
currMode = PAUSE_MODE;
pauseMode->enterMode();
break;
case HOME:
startbgm();
playMode->freePlayMode();
gMode = homeMode;
currMode = HOME_MODE;
homeMode->enterMode();
if (clientObj!=NULL){
if (clientObj->connected){
clientObj->Disconnect();
}
}
break;
default:
break;
}
}
void GameEngine::startbgm(){
if(bgm->getState()!=AL_PLAYING){
bgm->rewind();
bgm->play(true);
}
}
void GameEngine::stopbgm(){
bgm->rewind();
}
|
#include "triangolo.h"
double triangolo::numeroFisso = 0.289 ;
double triangolo::getfisso() const{
return numeroFisso;
}
/* CALCOLO DISTANZA TRA I PUNTI TRA 1-2 1-3 2-3 */
double triangolo::perimetro() const{
double per = 0 ;
per = per + pt[0]->distanceTwoPoints(*pt[1]) + pt[0]->distanceTwoPoints(*pt[2]) + pt[2]->distanceTwoPoints(*pt[1]) ;
return per;
}
double triangolo::lato() const {
if( ( pt[0]->distanceTwoPoints(*pt[1]) == pt[0]->distanceTwoPoints(*pt[2]) ) == pt[2]->distanceTwoPoints(*pt[1])){
return pt[0]->distanceTwoPoints(*pt[1]);
}
else return 0;
}
double triangolo::area( ) const {
double base = pt[0]->distanceTwoPoints(*pt[1]) ;
double h = retta::rettaFromTwoPoints(*pt[0],*pt[1]).distancePuntoRetta(*pt[2]);
return (base*h)/2;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#include "modules/url/tools/arrays.h"
void
FormatsModule::InitL(const OperaInitInfo& info)
{
#if defined(_ENABLE_AUTHENTICATE)
CONST_ARRAY_INIT_L(HTTP_Authentication_Keywords);
#endif
CONST_ARRAY_INIT_L(HTTPHeaders);
CONST_ARRAY_INIT_L(HTTP_General_Keywords);
CONST_ARRAY_INIT_L(paramsep);
CONST_ARRAY_INIT_L(HTTP_Cookie_Keywords);
#ifdef SUPPORT_AUTO_PROXY_CONFIGURATION
CONST_ARRAY_INIT_L(APC_keywords);
#endif
// Add all other array initializations above
CONST_ARRAY_INIT_L(Keyword_Index_List);
}
void
FormatsModule::Destroy()
{
CONST_ARRAY_SHUTDOWN(Keyword_Index_List);
// Add all array shutowns below
#if defined(_ENABLE_AUTHENTICATE)
CONST_ARRAY_SHUTDOWN(HTTP_Authentication_Keywords);
#endif
CONST_ARRAY_SHUTDOWN(HTTPHeaders);
CONST_ARRAY_SHUTDOWN(HTTP_General_Keywords);
CONST_ARRAY_SHUTDOWN(paramsep);
CONST_ARRAY_SHUTDOWN(HTTP_Cookie_Keywords);
#ifdef SUPPORT_AUTO_PROXY_CONFIGURATION
CONST_ARRAY_SHUTDOWN(APC_keywords);
#endif
}
|
#ifndef MASTERS_PROJECT_BLACKSCHOLESDISCRETEDIVPUT_H
#define MASTERS_PROJECT_BLACKSCHOLESDISCRETEDIVPUT_H
#include "../BlackScholesMertonPut.hpp"
#include "../../binomial_method/method/dividend/Dividend.hpp"
#include "DiscreteDividend.h"
class BlackScholesDiscreteDivPut: public BlackScholesMertonPut {
public:
BlackScholesDiscreteDivPut(double _S0, double _E, double _r, double _sigma, double _T, int dividend_number, Dividend<double> **dividends);
private:
int dividend_number;
Dividend<double> **dividends;
DiscDiv discDiv;
public:
double calculate(const double t) override;
};
#endif //MASTERS_PROJECT_BLACKSCHOLESDISCRETEDIVPUT_H
|
//
// Created by goturak on 21/02/19.
//
#ifndef POO2_MATRIX_H
#define POO2_MATRIX_H
#include <ostream>
#include "Operation.hpp"
class Matrix {
public:
int **getElements() const;
int getWidth() const;
int getHeight() const;
int getModulo() const;
void setElement(int x, int y, int value);
int getElement(int x, int y) const;
void resize(int h, int w);
friend std::ostream &operator<<(std::ostream &os, const Matrix &matrix);
virtual ~Matrix();
Matrix(int height, int width, int modulo);
Matrix(const Matrix &m2);
void addInPlace(Matrix& m2);
Matrix* addPtr(Matrix &m2);
Matrix addValue(Matrix &m2);
void multInPlace(Matrix& m2);
Matrix* multPtr(Matrix &m2);
Matrix multValue(Matrix &m2);
void subInPlace(Matrix& m2);
Matrix* subPtr(Matrix &m2);
Matrix subValue(Matrix &m2);
private:
int width;
int height;
int modulo;
int** elements;
bool sameMod(Matrix& m2);
void compute(Matrix &result,Matrix &m2, Operation *op );
};
#endif //POO2_MATRIX_H
|
//
// Created by sunlin on 2020-10-11
//
#ifndef KALMAN_H_
#define KALMAN_H_
#include "opencv2/video/tracking.hpp"
//#include "opencv2/highgui/highgui.hpp"
//#include <stdio.h>
//#include <stdlib.h>
//#include <string.h>
//#include <iostream>
class Kalman{
private:
const int stateNum=4; //状态值4×1向量(x,y,△x,△y)
const int measureNum=2; //测量值2×1向量(x,y)
cv::KalmanFilter *KF ;
cv::Mat prediction;
cv::Mat measurement ;
cv::Point predict_pt ;
public:
Kalman(){
this->KF=new cv::KalmanFilter(stateNum, measureNum, 0);
this->KF->transitionMatrix = (cv::Mat_<float>(4, 4) <<1,0,1,0,0,1,0,1,0,0,1,0,0,0,0,1); //转移矩阵A
setIdentity(KF->measurementMatrix); //测量矩阵H
setIdentity(KF->processNoiseCov, cv::Scalar::all(1e-5)); //系统噪声方差矩阵Q
setIdentity(KF->measurementNoiseCov, cv::Scalar::all(1e-1)); //测量噪声方差矩阵R
setIdentity(KF->errorCovPost, cv::Scalar::all(1)); //后验错误估计协方差矩阵P
//rng.fill(K input(200,300);ePost,RNG::UNIFORM,0,winHeight>winWidth?winWidth:winHeight); //初始状态值x(0)
randn(KF->statePost, cv::Scalar::all(0), cv::Scalar::all(0.1));
}
cv::Point2d predict(cv::Point input); //卡尔曼滤波预测函数
};
//卡尔曼预测
#endif
|
//__BEGIN_LICENSE__
// Copyright (c) 2017, United States Government, as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All rights reserved.
//
// The GeoRef platform is licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0.
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//__END_LICENSE__
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
/**
Simple tool to determine if an ISS image has a white label tag.
The tags could be on any side of the image and have a black label
on a white background. This tool could get confused on some
images but hopefully will work nearly every time.
*/
// Set up constants
const cv::Vec3b WHITE_VALUE(255, 255, 255);
const int MAX_TAG_HEIGHT = 180; // The narrow direction
const int MIN_TAG_HEIGHT = 30;
// Side codes
const int LEFT = 0;
const int RIGHT = 1;
const int TOP = 2;
const int BOTTOM = 3;
const int NOT_FOUND = -1;
/// Search along a line from the outer edge of the image inwards
/// and record the index of the first drop from pure white to another color
int findLineDrop(const cv::Mat &image, int side, int place)
{
const int height = image.rows;
const int width = image.cols;
int start, stop, inc;
switch(side)
{
case LEFT: start = 0; stop = MAX_TAG_HEIGHT; inc = 1; break;
case RIGHT: start = width-1; stop = width-MAX_TAG_HEIGHT; inc = -1; break;
case TOP: start = 0; stop = MAX_TAG_HEIGHT; inc = 1; break;
default: start = height-1; stop = height-MAX_TAG_HEIGHT; inc = -1; break;
}
if ((side == LEFT) || (side == RIGHT)) {
if (image.at<cv::Vec3b>(place, start) != WHITE_VALUE)
return NOT_FOUND; // No tag if first pixel is not white!
start += inc;
for (int i=start; i!=stop; i+=inc)
{
cv::Vec3b value = image.at<cv::Vec3b>(place, i);
if (value != WHITE_VALUE)
{
//int mean = (value[0] + value[1] + value[2]) / 3.0;
//int diff = 255 - mean;
return i;
}
}
}
else // TOP and BOTTOM
{
if (image.at<cv::Vec3b>(start, place) != WHITE_VALUE)
return NOT_FOUND; // No tag if first pixel is not white!
start += inc;
for (int i=start; i!=stop; i+=inc)
{
cv::Vec3b value = image.at<cv::Vec3b>(i, place);
if (value != WHITE_VALUE)
{
//int mean = (value[0] + value[1] + value[2]) / 3.0;
//int diff = 255 - mean;
return i;
}
}
}
return NOT_FOUND;
}
// TODO: Need a simple histogram here!
// Returns the most likely tag side along with the location and the count
void get_best_count(const cv::Mat &image,
int &bestSide, int &bestCount, int &bestWidth)
{
const int height = image.rows;
const int width = image.cols;
const int lrSize = height + 1; // One extra value to store "NOT_FOUND" results
const int tbSize = width + 1;
// Initialize all of the counts
bestSide = 0;
bestCount = 0;
bestWidth = 0;
std::vector<int> leftCounts(lrSize), rightCounts (lrSize);
std::vector<int> topCounts (tbSize), bottomCounts(tbSize);
for (int r=0; r<lrSize; ++r) { leftCounts[r] = 0; rightCounts [r] = 0; }
for (int c=0; c<tbSize; ++c) { topCounts [c] = 0; bottomCounts[c] = 0; }
// Find all the index hits in each direction
// - Add one to the results to NOT_FOUND(-1) goes into the first spot.
int index;
for (int r=0; r<height; ++r)
{
index = findLineDrop(image, LEFT, r)+1;
leftCounts [index] += 1;
index = findLineDrop(image, RIGHT, r)+1;
rightCounts[index] += 1;
}
for (int c=0; c<width; ++c)
{
index = findLineDrop(image, TOP, c)+1;
topCounts [index] += 1;
index = findLineDrop(image, BOTTOM, c)+1;
bottomCounts[index] += 1;
}
// Find the highest hit total
// - Skip the first entry which is for NOT_FOUND
for (int r=1; r<lrSize; ++r) // Left and right sides
{
if (leftCounts[r] > bestCount) {
bestCount = leftCounts[r];
bestWidth = r;
bestSide = LEFT;
std::cout << r << " L-> " << bestCount << std::endl;
}
if (rightCounts[r] > bestCount) {
bestCount = rightCounts[r];
bestWidth = r;
bestSide = RIGHT;
std::cout << r << " R-> " << bestCount << std::endl;
}
}
for (int c=1; c<tbSize; ++c) // Top and bottom sides
{
if (topCounts[c] > bestCount) {
bestCount = topCounts[c];
bestWidth = c;
bestSide = TOP;
std::cout << c << " T-> " << bestCount << std::endl;
}
if (bottomCounts[c] > bestCount) {
bestCount = bottomCounts[c];
bestWidth = c;
bestSide = BOTTOM;
std::cout << c << " B-> " << bestCount << std::endl;
}
}
return;
}
int main(int argc, char** argv )
{
if (argc != 2)
{
printf("usage: detectImageTag <image path>\n");
return -1;
}
std::string path = argv[1];
const int LOAD_RGB = 1;
// Load the input image
cv::Mat image = cv::imread(path, LOAD_RGB);
if (!image.data)
{
printf("Failed to load image\n");
return -1;
}
// Require that at least 60 of pixels match the tag location.
const double MIN_COUNT_PERCENT = 0.7;
// The target number is larger for the longer edges.
int lowThreshold = floor(MIN_COUNT_PERCENT * static_cast<double>(image.rows));
int highThreshold = floor(MIN_COUNT_PERCENT * static_cast<double>(image.cols));
// Call function to find the side most likely to have a tag
int bestSide, bestCount, bestWidth;
get_best_count(image, bestSide, bestCount, bestWidth);
// Debug info
std::string side;
int threshold;
switch (bestSide)
{
case LEFT: side = "LEFT"; threshold = lowThreshold; break;
case RIGHT: side = "RIGHT"; threshold = lowThreshold; break;
case TOP: side = "TOP"; threshold = highThreshold; break;
default: side = "BOTTOM"; threshold = highThreshold; break;
};
std::cout << "best side = " << side << std::endl;
std::cout << "best count = " << bestCount << std::endl;
std::cout << "best width = " << bestWidth << std::endl;
if (bestCount >= threshold)
std::cout << "LABEL " << side << " " << bestWidth << std::endl;
else
std::cout << "NO_LABEL\n";
return 0;
}
|
#ifndef MarchingCubes_HPP
#define MarchingCubes_HPP
#include "OgreFramework.h"
#include "UberCube.h"
#include "MarchingCubesTable.h"
#include "BooleanVoxel.h"
struct Voxel
{
bool _vertex0;
bool _vertex1;
bool _vertex2;
bool _vertex3;
bool _vertex4;
bool _vertex5;
bool _vertex6;
bool _vertex7;
Voxel(bool vertex0, bool vertex1, bool vertex2, bool vertex3, bool vertex4, bool vertex5, bool vertex6, bool vertex7)
{
_vertex0 = vertex0;
_vertex1 = vertex1;
_vertex2 = vertex2;
_vertex3 = vertex3;
_vertex4 = vertex4;
_vertex5 = vertex5;
_vertex6 = vertex6;
_vertex7 = vertex7;
}
};
class MarchingCubes
{
public:
void Poligonize(UberCube* cube, Ogre::MeshPtr mesh);
void Poligonize(UberCube* cube, Ogre::ManualObject* manualObject);
void Poligonize(UberCube* cube, std::vector<Ogre::Vector3> extraVertex, Ogre::ManualObject* manualObject);
int CreateRawTrianglesVector(UberCube* cube, std::vector<RawTriangle> *trianglesVector, Ogre::Vector3 cubeOffset = Ogre::Vector3::ZERO);
};
#endif
|
/**
* @file sum_of_squares_variable.cc
* @author Gerbrand De Laender
* @date 18/02/2021
* @version 1.0
*
* @brief E091103, Master thesis, HLS testing
*
* @section DESCRIPTION
*
* IP that calculates the sum of the squares of an incoming AXI stream.
*
*/
#include <stdint.h>
#include <hls_stream.h>
#include <ap_axi_sdata.h>
typedef ap_uint<32> T;
typedef ap_axiu<8 * sizeof(T), 1, 1, 1> T_SIDE;
T sum_of_squares_variable(hls::stream<T_SIDE> &in_stream, ap_uint<8> stream_len_min_one)
{
#pragma HLS INTERFACE axis port=in_stream
#pragma HLS INTERFACE s_axilite port=stream_len_min_one bundle=CRTL_BUS
#pragma HLS INTERFACE s_axilite port=return bundle=CRTL_BUS
T_SIDE tmp;
static T res = 0;
#pragma HLS RESET variable=res
for (int i = 0; i < stream_len_min_one + 1; i++) {
#pragma HLS PIPELINE
in_stream >> tmp;
res += (tmp.data * tmp.data);
}
return res;
}
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
void Init_ListNode(ListNode* head, vector<int> vec)
{
if (vec.size() == 0)
{
head = NULL;
return;
}
ListNode* p;
p = head;
p->val = vec[0];
for (int i = 1; i < vec.size(); i++)
{
ListNode* q = new ListNode(vec[i]);
p->next = q;
p = p->next;
}
}
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//基本思想:迭代
ListNode* start = new ListNode(0), * p;
while (head != NULL)
{
p = head;
head = head->next;
p->next = start->next;
start->next = p;
}
return start->next;
}
};
class Solution1 {
public:
ListNode* reverseList(ListNode* head) {
//基本思想:递归
return Recursion(NULL, head);
}
ListNode* Recursion(ListNode* pre, ListNode* cur)
{
if (cur == NULL)
return pre;
ListNode* post = cur->next;
cur->next = pre;
return Recursion(cur, post);
}
};
int main()
{
Solution1 solute;
ListNode* head = new ListNode(0);
vector<int> vec = { 1,2,3,4,5 };
Init_ListNode(head, vec);
ListNode* p;
p = solute.reverseList(head);
while (p != NULL)
{
cout << p->val << " ";
p = p->next;
}
cout << endl;
return 0;
}
|
#ifndef __IM_WINDOW_MANAGER_DX11_H__
#define __IM_WINDOW_MANAGER_DX11_H__
#include "../ImWindow/ImwConfig.h"
#include "../ImWindow/ImwWindowManager.h"
namespace ImWindow
{
class ImwWindowManagerDX11 : public ImwWindowManager
{
public:
ImwWindowManagerDX11();
virtual ~ImwWindowManagerDX11();
protected:
bool CanCreateMultipleWindow() override { return true; }
ImwPlatformWindow* CreatePlatformWindow(EPlatformWindowType eType, ImwPlatformWindow* pParent) override;
ImVec2 GetCursorPos() override;
bool IsLeftClickDown() override;
};
}
#endif //__IM_WINDOW_MANAGER_DX11_H__
|
#include <iostream>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <torch/torch.h>
#include <torch/ordered_dict.h>
#include <torch/nn/modules/conv.h>
#include "Cifar10DataSetParser.hpp"
namespace TDD = torch::data::datasets;
struct ReLu: torch::nn::Module {
ReLu() {}
torch::Tensor forward(torch::Tensor x) {
return torch::relu(x);
}
};
struct MaxPool2d: torch::nn::Module {
MaxPool2d() {}
torch::Tensor forward(torch::Tensor x) {
return torch::max_pool2d(x,{2, 2});
}
void pretty_print(std::ostream& stream) const {
stream << "torch::max_pool2d(x, {2, 2})";
}
};
struct Flatten: torch::nn::Module {
Flatten() {}
torch::Tensor forward(torch::Tensor x) {
return x.view({-1, 64*4*4});
}
};
struct DropOut: torch::nn::Module {
double Rate;
bool IsTrain;
DropOut(double rate, bool train):Rate(rate),IsTrain(train) {}
torch::Tensor forward(torch::Tensor x) {
return torch::dropout(x, Rate, IsTrain);
}
void pretty_print(std::ostream& stream) const {
stream << "torch::nn::Dropout(rate=" << Rate << ")";
}
};
struct LogSoftMax : torch::nn::Module {
LogSoftMax() {}
torch::Tensor forward(torch::Tensor x) {
return torch::log_softmax(x, /*dim=*/1);
}
void pretty_print(std::ostream& stream) const {
stream << "torch::log_softmax(x, dim=1)";
}
};
#if OPENCV_INCLUDED
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
bool Display(const torch::Tensor &imageTensor, const std::string &title)
{
bool retVal(false);
std::vector<uint8_t> tmpVec;
torch::Tensor flattenImg = imageTensor.view({3*32*32});
for(int i =0; i < flattenImg.numel(); i++) {
uint8_t val = static_cast<uint8_t>(flattenImg[i].item().to<float>()*255);
tmpVec.push_back(val);
retVal = true;
}
#if 0
// Merge the color channels appropriately.
cv::Mat outputMat(3, 32*32, CV_8UC1, tmpVec.data());
cv::Mat tmp = outputMat.t();
outputMat = tmp.reshape(3, 32);
cv::cvtColor(outputMat, outputMat, cv::COLOR_RGB2BGR);
cv::imshow("testing", outputMat);
cv::waitKey(0);
#endif
// Merge the color channels appropriately.
cv::Mat outputMat;
cv::Mat channelR(32, 32, CV_8UC1, tmpVec.data());
cv::Mat channelG(32, 32, CV_8UC1, tmpVec.data() + 32 * 32);
cv::Mat channelB(32, 32, CV_8UC1, tmpVec.data() + 2 * 32 * 32);
std::vector<cv::Mat> channels{ channelB, channelG, channelR };
cv::merge(channels, outputMat);
cv::imshow(title.c_str(), outputMat);
cv::waitKey(0);
return retVal;
}
#endif
std::stringstream ReadFile(const std::string &file)
{
std::stringstream buffer;
std::ifstream fileReader(file);
if(fileReader) {
buffer << fileReader.rdbuf();
fileReader.close();
}
return buffer;
}
int main()
{
TDD::CIFAR10::Mode mode = TDD::CIFAR10::Mode::kTrain;
uint32_t batchSize = 64;
auto dataSet = torch::data::datasets::CIFAR10("/opt/pytorch/data/cifar-10-batches-bin/", mode);
auto trainDataLoader = torch::data::make_data_loader(
dataSet.map(torch::data::transforms::Stack<>()),
batchSize);
#if OPENCV_INCLUDED
// Test if the images loaded properly
auto batch = std::begin(*trainDataLoader);
auto images = batch->data;
auto target = batch->target;
std::cout << "images = " << images.sizes() << "\n";
std::cout << "targets = " << target.sizes() << "\n";
std::cout << "single images = " << images[0].sizes() << "\n";
// Test if the images are decoded fine.
for (int i = 0 ; i < images.size(0); i++) {
std::string title = dataSet.GetTarget(target[i].item<int>());
std::cout << "Displaying " << (dataSet.IsTrain() ? " Tain " : " Test ") <<"Image # " << i << " is : " << title.c_str() <<" \n";
Display(images[i], title);
}
cv::destroyAllWindows();
#endif
// Check if GPU is available.
torch::Device device(torch::kCPU);
if (torch::cuda::is_available()) {
std::cout << "CUDA is available! Training on GPU." << std::endl;
device = torch::Device(torch::kCUDA);
}
else {
std::cout << "Training on CPU." << std::endl;
}
torch::nn::Sequential seqConvLayer(torch::nn::Conv2d(torch::nn::Conv2dOptions(3, 16, 3).padding(1)),
ReLu(),
MaxPool2d(),
torch::nn::Conv2d(torch::nn::Conv2dOptions(16, 32, 3).padding(1)),
ReLu(),
MaxPool2d(),
torch::nn::Conv2d(torch::nn::Conv2dOptions(32, 64, 3).padding(1)),
ReLu(),
MaxPool2d(),
Flatten(),
DropOut(0.25, true),
torch::nn::Linear(64 * 4 * 4, 500),
ReLu(),
DropOut(0.25, true),
torch::nn::Linear(500, 10),
LogSoftMax()
);
seqConvLayer->to(device);
std::cout << "Model:\n\n";
std::cout << c10::str(seqConvLayer) << "\n\n";
torch::optim::SGD optimizer(seqConvLayer->parameters(), /*lr=*/0.01);
std::cout << "Training.....\n";
double minVal(10000.991);
for (size_t epoch = 1; epoch <= 2; ++epoch) {
size_t batchIndex = 0;
// keep track of training and validation loss
float train_loss = 0.0;
//float valid_loss = 0.0;
seqConvLayer->train();
for (auto& batch : *trainDataLoader) {
batch.data.to(device);
batch.target.to(device);
// Reset gradients.
optimizer.zero_grad();
// Execute the model on the input data.
auto imgs = batch.data.to(torch::kFloat);
//std::cout << "images = " << imgs.sizes() << "\n";
// forward pass: compute predicted outputs by passing inputs to the model
torch::Tensor prediction = seqConvLayer->forward(imgs);
// calculate the batch loss
auto loss = torch::nll_loss(prediction, batch.target.to(torch::kLong));
// Compute gradients of the loss w.r.t. the parameters of our model.
loss.backward();
// Update the parameters based on the calculated gradients.
optimizer.step();
// update training loss
train_loss += loss.item<float>() * batch.data.size(0);
// Output the loss and checkpoint every 100 batches.
if (++batchIndex % 100 == 0) {
std::cout << "Epoch: " << epoch << " | Batch: " << batchIndex
<< " | Training Loss: " << loss.item<float>() << "\n";
}
if (minVal > loss.item<float>()) {
minVal = loss.item<float>();
std::string model_path = "test_model.pt";
torch::serialize::OutputArchive output_archive;
seqConvLayer->save(output_archive);
output_archive.save_to(model_path);
std::cout << "Saving model with least training error = " << minVal << "\n";
}
}
}
std::cout << "Least training error reached = " << minVal << "\n";
torch::serialize::InputArchive archive;
std::string file("test_model.pt");
archive.load_from(file, device);
torch::nn::Sequential savedSeq;
savedSeq->load(archive);
#if 0
auto parameters = savedSeq->named_parameters();
auto keys = parameters.keys();
auto vals = parameters.values();
for(auto v: keys) {
std::cout << v << "\n";
}
#endif
std::cout << "Saved Model:\n\n";
std::cout << c10::str(savedSeq) << "\n\n";
return 0;
}
|
// Created on: 1995-03-08
// Created by: Laurent BUCHARD
// Copyright (c) 1995-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 _CSLib_Class2d_HeaderFile
#define _CSLib_Class2d_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TColgp_Array1OfPnt2d.hxx>
#include <NCollection_Handle.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <TColgp_SequenceOfPnt2d.hxx>
class gp_Pnt2d;
//! *** Class2d : Low level algorithm for 2d classification
//! this class was moved from package BRepTopAdaptor
class CSLib_Class2d
{
public:
DEFINE_STANDARD_ALLOC
//! Constructs the 2D-polygon.
//! thePnts2d is the set of the vertices (closed polygon
//! will always be created inside of this constructor;
//! consequently, there is no point in repeating first and
//! last point in thePnts2d).
//! theTolu and theTolv are tolerances.
//! theUmin, theVmin, theUmax, theVmax are
//! UV-bounds of the polygon.
Standard_EXPORT CSLib_Class2d(const TColgp_Array1OfPnt2d& thePnts2d,
const Standard_Real theTolU,
const Standard_Real theTolV,
const Standard_Real theUMin,
const Standard_Real theVMin,
const Standard_Real theUMax,
const Standard_Real theVMax);
//! Constructs the 2D-polygon.
//! thePnts2d is the set of the vertices (closed polygon
//! will always be created inside of this constructor;
//! consequently, there is no point in repeating first and
//! last point in thePnts2d).
//! theTolu and theTolv are tolerances.
//! theUmin, theVmin, theUmax, theVmax are
//! UV-bounds of the polygon.
Standard_EXPORT CSLib_Class2d(const TColgp_SequenceOfPnt2d& thePnts2d,
const Standard_Real theTolU,
const Standard_Real theTolV,
const Standard_Real theUMin,
const Standard_Real theVMin,
const Standard_Real theUMax,
const Standard_Real theVMax);
Standard_EXPORT Standard_Integer SiDans (const gp_Pnt2d& P) const;
Standard_EXPORT Standard_Integer SiDans_OnMode (const gp_Pnt2d& P, const Standard_Real Tol) const;
Standard_EXPORT Standard_Integer InternalSiDans (const Standard_Real X, const Standard_Real Y) const;
Standard_EXPORT Standard_Integer InternalSiDansOuOn (const Standard_Real X, const Standard_Real Y) const;
protected:
private:
//! Initializes theObj
template <class TCol_Containers2d>
void Init(const TCol_Containers2d& TP2d,
const Standard_Real aTolu,
const Standard_Real aTolv,
const Standard_Real umin,
const Standard_Real vmin,
const Standard_Real umax,
const Standard_Real vmax);
//! Assign operator is forbidden
const CSLib_Class2d& operator= (const CSLib_Class2d& Other) const;
NCollection_Handle <TColStd_Array1OfReal> MyPnts2dX, MyPnts2dY;
Standard_Real Tolu;
Standard_Real Tolv;
Standard_Integer N;
Standard_Real Umin;
Standard_Real Vmin;
Standard_Real Umax;
Standard_Real Vmax;
};
#endif // _CSLib_Class2d_HeaderFile
|
#include "stdafx.h"
int main() {
srand((unsigned)time(NULL));
removeCursor();
system("mode con cols=56 lines=30");
Tetris *T = new Tetris();
T->title();
while (1) {
for (int i = 0; i < 5; i++) { // 최대 5회의 키 입력
T->keyCheck();
T->drawGameboard();
Sleep(T->getSpeed());
if (T->getEvent(0) && T->checkCollision(T->getPos(0), T->getPos(1), T->getRotation())) Sleep(100); // 블럭 이동이 불가능 하다면 잠시 멈춤
}
T->dropBlock();
T->checkLvUp();
if (T->checkGameOver()) break; // 게임 오버 상태일 경우 게임을 진행하지 않음
if (T->getEvent(1)) T->generateNewBlock(); // 블럭이 놓여진 상태일 때, 새 블럭 생성
}
delete T;
while (1) {
if (_kbhit()) {
int key = _getch();
if (key == 13) break;
}
}
return 0;
}
|
#ifndef TO_LOWER_HPP
#define TO_LOWER_HPP
#include <algorithm>
#include <string>
namespace String
{
static std::string toLower(std::string& str)
{
std::transform(
str.begin(),
str.end(),
str.begin(),
[](unsigned char c)
{
return ::tolower(c);
}
);
return str;
}
}
#endif /* end of include guard : TO_LOWER_HPP */
|
#include "stdafx.h"
#include "StubDataProcessor.h"
#include <iostream>
#include "VehicleData.h"
#include "CppUnitTest.h"
using std::unique_ptr;
using std::shared_ptr;
using std::move;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
StubDataProcessor::StubDataProcessor() {
}
StubDataProcessor::~StubDataProcessor() {
}
void StubDataProcessor::processData(std::vector<std::unique_ptr<VehicleData>> data) {
processDataCalled = true;
Logger::WriteMessage("processDataCalled on IDs: ");
for(unique_ptr<VehicleData> &d : data) {
std::string output = std::to_string(d->getID()) + ", ";
Logger::WriteMessage(output.c_str());
}
inputs.push_back(move(data));
}
bool StubDataProcessor::isProcessDataCalled() {
return processDataCalled;
}
std::vector<std::vector<unique_ptr<VehicleData>>> const& StubDataProcessor::getInputs() {
return inputs;
}
|
#pragma once
#include "core/maths.h"
#include "core/core.h"
class Metaballs
{
public:
struct Ball
{
Point3 m_pos;
float m_radius;
};
Metaballs(const Ball* balls, uint32_t n)
{
m_numBalls = n;
m_balls = new Ball[n];
memcpy(m_balls, balls, sizeof(Ball)*n);
// calculate the sum of the radii used to approximate the distance field
for (uint32_t i=0; i < n; ++i)
{
m_radiiSum += balls[i].m_radius;
}
}
~Metaballs()
{
delete[] m_balls;
}
// evaluate the distance of a point to the iso-surface of the surface (lower-bound)
float Distance(const Point3& p, float threshold)
{
float density = 0.0f;
for (uint32_t i=0; i < m_numBalls; ++i)
{
density += Density(Length(m_balls[i].m_pos-p), m_balls[i].m_radius);
}
return 2.0f/3.0f * m_radiiSum * (threshold - density);
}
private:
float Density(float r, float rmax)
{
if (r > rmax)
return 0.0f;
else
{
float t = (r/rmax);
return 2.0f*(t*t*t) - 3.0f*(t*t) + 1.0f;
}
}
float m_radiiSum;
uint32_t m_numBalls;
Ball* m_balls;
};
|
#include "adaptivecanny.h"
adaptivecanny::adaptivecanny()
{
}
|
#include <bits/stdc++.h>
using namespace std;
using namespace std::chrono;
typedef long long int ll;
using ii= pair<ll,ll>;
#define fr(i,a,b) for(ll i=a;i<b;i++)
#define all(o) (o).begin(),(o).end()
#define F first
#define S second
#define MP make_pair
#define PB push_back
#define ld long double
#define eps 0.00000000001
#define mod 1000000007
class prioritize{
public: bool operator() (ii &p1,ii &p2){
return p1.F<p2.F;
}
};
vector<ll> v[100010];
ll vst[100010]={0};
ll sz[100010]={0};
//vector<bool> ctr(100010);
set<ll> croid;
// croid-> set to store the centroids of the tree
// if n-> odd ->only one centroid possible. if n-> even-> two may be possible
ll dfs(ll node,ll n)
{
vst[node]= 1;
sz[node]= 1;
bool is_ctr= true;
for(auto it:v[node])
{
if(!vst[it])
{
sz[node]+= dfs(it,n);
if(sz[it]>(n)/2) is_ctr= false;
}
}
if(sz[node]<((n+1)/2)) is_ctr= false; // (n+1) important in case of odd number of nodes....
if(is_ctr) croid.insert(node);
return sz[node];
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input1.txt","r", stdin);
freopen("output1.txt","w",stdout);
auto start= high_resolution_clock::now();
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
ll t;
cin>>t;
while(t--)
{
ll n;
cin>>n;
croid.clear();
fr(i,0,n+8) v[i].clear();
fr(i,0,n+8){
vst[i]= 0;
sz[i] = 0;
// ctr[i]= true;
}
fr(i,1,n)
{
ll x,y;
cin>>x>>y;
v[x].PB(y);
v[y].PB(x);
}
ll si=dfs(1,n);
for(auto it:croid) cout<<it<<"*";
cout<<"\n";
cout<<sz[1]<<"->"<<sz[2]<<"->"<<sz[3]<<"\n";
if(croid.size()==1){
auto it= croid.begin();
ll centroid= *it;
ll neigh= v[centroid][0];
cout<<centroid<<" "<<neigh<<"\n";
cout<<centroid<<" "<<neigh<<"\n";
}
else{
auto it= croid.begin();
ll centroid1= *it;
it++;
ll centroid2= *it;
ll other;
set<ll> cr;
for(auto it:v[centroid1]) cr.insert(it);
cr.insert(centroid1);
for(auto it:v[centroid2]){
if(cr.find(it)==cr.end()) other= it;
}
cout<<centroid2<<" "<<other<<"\n";
cout<<centroid1<<" "<<other<<"\n";
}
}
#ifndef ONLINE_JUDGE
auto stop= high_resolution_clock::now();
auto duration= duration_cast<milliseconds>(stop-start);
cout<<"run time: "<<duration.count()<<" ms"<<"\n";
#endif
}
|
/* -*- Mode: c++; tab-width: 4; 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.
*
* @author Adam Minchinton
*/
#include "core/pch.h"
#ifdef USE_COMMON_RESOURCES
#include "adjunct/desktop_util/resources/ResourceUpgrade.h"
#include "adjunct/desktop_util/resources/pi/opdesktopresources.h"
#include "adjunct/desktop_util/resources/ResourceFolders.h"
#include "adjunct/desktop_util/opfile/desktop_opfile.h"
#include "modules/prefsfile/prefsfile.h"
#include "modules/util/opfile/opfile.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OP_STATUS ResourceUpgrade::UpdatePref(const uni_char* old_filename, const uni_char* new_filename, OperaInitInfo *pinfo)
{
OpDesktopResources *dr_temp; // Just for the autopointer
RETURN_IF_ERROR(OpDesktopResources::Create(&dr_temp));
OpAutoPtr<OpDesktopResources> resources(dr_temp);
if(!resources.get())
return OpStatus::ERR_NO_MEMORY;
OpString old_profile_path;
resources->GetOldProfileLocation(old_profile_path);
OpFile newfile, oldfile;
OpString path;
// path.Set(pinfo->default_folders[OPFILE_USERPREFS_FOLDER]);
path.Set(pinfo->default_folders[OPFILE_HOME_FOLDER]);
if (path[path.Length() - 1] != PATHSEPCHAR)
path.Append(PATHSEP);
path.Append(new_filename);
RETURN_IF_ERROR(newfile.Construct(path.CStr(), OPFILE_ABSOLUTE_FOLDER));
BOOL exists;
if (OpStatus::IsError(newfile.Exists(exists)) || exists) {
// Nothing to do
return OpStatus::OK;
}
path.Set(pinfo->default_folders[OPFILE_HOME_FOLDER]);
if (path[path.Length() - 1] != PATHSEPCHAR)
path.Append(PATHSEP);
path.Append(old_profile_path);
path.Append(old_filename);
RETURN_IF_ERROR(oldfile.Construct(path.CStr(), OPFILE_ABSOLUTE_FOLDER));
if (OpStatus::IsError(oldfile.Exists(exists)) || !exists) {
// Nothing to do
return OpStatus::OK;
}
int res_count = (sizeof(mResourceUpgrades)/sizeof(*mResourceUpgrades)) - 1;
if (res_count == 0) {
return newfile.CopyContents(&oldfile, TRUE);
}
OpString filepath;
filepath.Reserve(2048); // FIXME: Proper macro
OpString prefPathFull;
prefPathFull.Reserve(2048); // FIXME: Proper macro
OpString defaultPathFull;
defaultPathFull.Reserve(2048); // FIXME: Proper macro
OpString8 scan;
RETURN_IF_ERROR(oldfile.Open(OPFILE_READ));
RETURN_IF_ERROR(newfile.Open(OPFILE_WRITE));
// g_op_system_info->GetNewlineString()
char section[512];
section[0] = 0;
OpFile logfile;
OpString8 lognote;
path.Set(pinfo->default_folders[OPFILE_LOCAL_HOME_FOLDER]);
if (path[path.Length() - 1] != PATHSEPCHAR)
path.Append(PATHSEP);
path.Append(UNI_L("upgrade.log"));
RETURN_IF_ERROR(logfile.Construct(path.CStr(), OPFILE_ABSOLUTE_FOLDER));
RETURN_IF_ERROR(logfile.Open(OPFILE_APPEND));
lognote.Set("--------");
lognote.Append(NEWLINE);
logfile.Write(lognote.CStr(), lognote.Length());
// time_t now = g_timecache->CurrentTime();
// struct tm *datelocal = localtime(&now);
// lognote.Reserve(200);
// g_oplocale->op_strftime(lognote.CStr(), 199, UNI_L("%Y-%m-%d %H:%M:%S"), datelocal);
while (OpStatus::IsSuccess(oldfile.ReadLine(scan)) && !oldfile.Eof())
{
char key[512], value[2048];
if (scan[0] == '[') {
char* end = strchr(scan.CStr()+1, ']');
if (end && (end-scan.CStr()) <= 512) {
memcpy(section, scan.CStr()+1, end-scan.CStr()-1);
section[end-scan.CStr()-1] = 0;
}
}
else if (scan.Length()) {
char* delim = strchr(scan.CStr(), '=');
if (delim && (delim-scan.CStr()) < 512 && strlen(delim+1)<2048) {
memcpy(key, scan.CStr(), delim-scan.CStr());
key[delim-scan.CStr()] = 0;
delim++;
strcpy(value, delim);
BOOL skip = FALSE;
for (int i = 0; i < res_count; i++) {
if ((mResourceUpgrades[i].section && (op_strcmp(mResourceUpgrades[i].section, section) == 0 || op_strcmp(mResourceUpgrades[i].section, "*") == 0)) &&
(mResourceUpgrades[i].key && (op_strcmp(mResourceUpgrades[i].key, key) == 0 || op_strcmp(mResourceUpgrades[i].key, "*") == 0)))
{
filepath.SetFromUTF8(value);
resources->ExpandSystemVariablesInString(filepath.CStr(), prefPathFull.CStr(), prefPathFull.Capacity());
if (mResourceUpgrades[i].olddefaultparent == OPFILE_SERIALIZED_FOLDER) {
filepath.Set(mResourceUpgrades[i].olddefaultpath);
resources->ExpandSystemVariablesInString(filepath.CStr(), defaultPathFull.CStr(), defaultPathFull.Capacity());
}
else {
ResourceFolders::GetFolder(mResourceUpgrades[i].olddefaultparent, pinfo, defaultPathFull);
#ifdef MSWIN
if (uni_strnicmp(mResourceUpgrades[i].olddefaultpath, UNI_L("mail"), 5) != 0)
#endif
defaultPathFull.Append(old_profile_path);
defaultPathFull.Append(mResourceUpgrades[i].olddefaultpath);
}
OpFile defaultvaluefile;
OpFileInfo::Mode mode;
defaultvaluefile.Construct(defaultPathFull.CStr(), OPFILE_ABSOLUTE_FOLDER);
BOOL identical;
BOOL exists;
if (mResourceUpgrades[i].newpath &&
OpStatus::IsSuccess(defaultvaluefile.Exists(exists)) && exists &&
OpStatus::IsSuccess(defaultvaluefile.GetMode(mode)) && mode==OpFileInfo::DIRECTORY
&& resources->IsSameVolume(prefPathFull.CStr(), defaultPathFull.CStr())) {
#ifdef MSWIN
if (prefPathFull.CompareI(defaultPathFull.CStr(), defaultPathFull.Length()) == 0)
#else
if (prefPathFull.Compare(defaultPathFull.CStr(), defaultPathFull.Length()) == 0)
#endif
{
// The pref points to a file inside inside the old default folder. Change pref to the same filename inside the new folder.
// That file will not exist yet, but it will soon (see ResourceUpgrade::CopyOldResources)
OpString newParent;
OpString8 newParent8;
if (defaultPathFull[defaultPathFull.Length() - 1] != PATHSEPCHAR)
RETURN_IF_ERROR(defaultPathFull.Append(PATHSEP));
if (mResourceUpgrades[i].olddefaultparent == OPFILE_SERIALIZED_FOLDER) {
filepath.Set(mResourceUpgrades[i].newpath);
resources->ExpandSystemVariablesInString(filepath.CStr(), newParent.CStr(), newParent.Capacity());
}
else {
ResourceFolders::GetFolder(mResourceUpgrades[i].newparent, pinfo, newParent);
newParent.Append(mResourceUpgrades[i].newpath);
}
OpFile newfile;
newfile.Construct(newParent.CStr(), OPFILE_ABSOLUTE_FOLDER);
if (OpStatus::IsError(newfile.Exists(exists)) || exists) {
// The new parent already exists, so we wouldn't be able to move the old folder to it -> keep the old value
break;
}
if (newParent[newParent.Length() - 1] != PATHSEPCHAR)
RETURN_IF_ERROR(newParent.Append(PATHSEP));
if (prefPathFull.Length() > defaultPathFull.Length())
newParent.Append(prefPathFull.CStr()+defaultPathFull.Length());
resources->SerializeFileName(newParent.CStr(), prefPathFull.CStr(), prefPathFull.Capacity());
newParent8.SetUTF8FromUTF16(prefPathFull.CStr());
if (OpStatus::IsError(scan.Set(key))) {skip=TRUE;break;}
if (OpStatus::IsError(scan.Append("="))) {skip=TRUE;break;}
if (OpStatus::IsError(scan.Append(newParent8.CStr()))) {skip=TRUE;break;}
// if (OpStatus::IsError(scan.Append(filename8.CStr()))) continue;
lognote.Empty();
lognote.AppendFormat("Pref entry \"%s\" changed from \"%s\" to \"%s\"%s", key, value, newParent8.CStr(), NEWLINE);
logfile.Write(lognote.CStr(), lognote.Length());
}
}
else if (OpStatus::IsSuccess(ResourceFolders::ComparePaths(prefPathFull, defaultPathFull, identical)) && identical
&& resources->IsSameVolume(prefPathFull.CStr(), defaultPathFull.CStr()))
{
lognote.Empty();
lognote.AppendFormat("Pref entry \"%s\", which used to be \"%s\", was removed%s", key, value, NEWLINE);
logfile.Write(lognote.CStr(), lognote.Length());
skip=TRUE;
break; // This is the default pref. Discard.
}
}
}
if (skip)
continue;
}
}
scan.Append(NEWLINE);
newfile.Write(scan.CStr(), scan.Length());
}
newfile.Close();
logfile.Close();
return OpStatus::OK;
}
OP_STATUS ResourceUpgrade::CopyOldResources(OperaInitInfo *pinfo)
{
OpDesktopResources *dr_temp; // Just for the autopointer
RETURN_IF_ERROR(OpDesktopResources::Create(&dr_temp));
OpAutoPtr<OpDesktopResources> resources(dr_temp);
if(!resources.get())
return OpStatus::ERR_NO_MEMORY;
OpString old_profile_path;
resources->GetOldProfileLocation(old_profile_path);
OpFile logfile;
OpString8 lognote;
OpString logpath;
logpath.Set(pinfo->default_folders[OPFILE_LOCAL_HOME_FOLDER]);
if (logpath[logpath.Length() - 1] != PATHSEPCHAR)
logpath.Append(PATHSEP);
logpath.Append(UNI_L("upgrade.log"));
RETURN_IF_ERROR(logfile.Construct(logpath.CStr(), OPFILE_ABSOLUTE_FOLDER));
RETURN_IF_ERROR(logfile.Open(OPFILE_APPEND));
BOOL exists;
OpString filepath;
filepath.Reserve(2048); // FIXME: Proper macro
int len = (sizeof(mResourceUpgrades)/sizeof(*mResourceUpgrades))-1;
OpString defaultPathFull;
defaultPathFull.Reserve(2048); // FIXME: Proper macro
OpString newPathFull;
newPathFull.Reserve(2048); // FIXME: Proper macro
for (int i = 0; i < len; i++)
{
OpFile newfile, oldfile;
if (mResourceUpgrades[i].olddefaultpath && mResourceUpgrades[i].newpath)
{
// Old Resource
if (mResourceUpgrades[i].olddefaultparent == OPFILE_SERIALIZED_FOLDER) {
filepath.Set(mResourceUpgrades[i].olddefaultpath);
resources->ExpandSystemVariablesInString(filepath.CStr(), defaultPathFull.CStr(), defaultPathFull.Capacity());
}
else {
ResourceFolders::GetFolder(mResourceUpgrades[i].olddefaultparent, pinfo, defaultPathFull);
#ifdef MSWIN
if (uni_strnicmp(mResourceUpgrades[i].olddefaultpath, UNI_L("mail"), 5) != 0)
#endif
defaultPathFull.Append(old_profile_path);
defaultPathFull.Append(mResourceUpgrades[i].olddefaultpath);
}
// New Resource
if (mResourceUpgrades[i].newparent == OPFILE_SERIALIZED_FOLDER) {
filepath.Set(mResourceUpgrades[i].newpath);
resources->ExpandSystemVariablesInString(filepath.CStr(), newPathFull.CStr(), newPathFull.Capacity());
}
else {
ResourceFolders::GetFolder(mResourceUpgrades[i].newparent, pinfo, newPathFull);
newPathFull.Append(mResourceUpgrades[i].newpath);
}
RETURN_IF_ERROR(oldfile.Construct(defaultPathFull.CStr(), OPFILE_ABSOLUTE_FOLDER));
RETURN_IF_ERROR(newfile.Construct(newPathFull.CStr(), OPFILE_ABSOLUTE_FOLDER));
if (OpStatus::IsError(newfile.Exists(exists)) || exists) {
// Nothing to do
continue;
}
if (OpStatus::IsError(oldfile.Exists(exists)) || !exists) {
// Nothing to do
continue;
}
if (!resources->IsSameVolume(newPathFull.CStr(), defaultPathFull.CStr()))
{
// Do not update
continue;
}
lognote.Empty();
lognote.AppendFormat("Moving file/folder \"%ls\" to \"%ls\"%s", defaultPathFull.CStr(), newPathFull.CStr(), NEWLINE);
logfile.Write(lognote.CStr(), lognote.Length());
// newfile.CopyContents(&oldfile, TRUE);
DesktopOpFileUtils::Move(&oldfile, &newfile);
}
}
return OpStatus::OK;
}
OP_STATUS ResourceUpgrade::RemoveIncompatibleLanguageFile(PrefsFile *pf)
{
OpString saved_language_file_path;
OP_STATUS err;
// Check we have a prefs file object
if (!pf)
return OpStatus::ERR;
// Create the PI interface object
OpDesktopResources *dr_temp; // Just for the autopointer
RETURN_IF_ERROR(OpDesktopResources::Create(&dr_temp));
OpAutoPtr<OpDesktopResources> desktop_resources(dr_temp);
if(!desktop_resources.get())
return OpStatus::ERR_NO_MEMORY;
TRAP(err, pf->ReadStringL("User Prefs", "Language File", saved_language_file_path));
RETURN_IF_ERROR(err);
// Remove any serialised path from the preference setting
OpString out_path;
out_path.Reserve(MAX_PATH);
RETURN_IF_ERROR(OpStatus::IsSuccess(desktop_resources->ExpandSystemVariablesInString(saved_language_file_path.CStr(), out_path.CStr(), MAX_PATH)));
RETURN_IF_ERROR(saved_language_file_path.Set(out_path.CStr()));
if (!saved_language_file_path.IsEmpty())
{
INT32 version = -1;
OpFile file;
RETURN_IF_ERROR(file.Construct(saved_language_file_path.CStr()));
if (OpStatus::IsSuccess(file.Open(OPFILE_READ)))
{
for( INT32 i=0; i<100; i++ )
{
OpString8 buf;
if (OpStatus::IsError(file.ReadLine(buf)))
break;
buf.Strip(TRUE, FALSE);
if (buf.CStr() && op_strnicmp(buf.CStr(), "DB.version", 10) == 0)
{
for (const char *p = &buf.CStr()[10]; *p; p++)
{
if (op_isdigit(*p))
{
sscanf(p,"%d",&version);
break;
}
}
break;
}
}
}
// If the language file is less than version 811 throw it away!
if (version < 811)
{
TRAP(err, pf->DeleteKeyL("User Prefs", "Language File"));
RETURN_IF_ERROR(err);
TRAP(err, pf->CommitL(TRUE, FALSE)); // Keep data loaded
RETURN_IF_ERROR(err);
}
}
return OpStatus::OK;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif // USE_COMMON_RESOURCES
|
#include <iostream>
#include <string>
using namespace std;
class timeFM
{
};
int main()
{
char done = 'y';
while (done == 'y')
{
try
{
int hours = 0;
string min;
char useless =0;
cout << "Enter time in 24-hour notation:\n";
cin >> hours >> useless >> min;
int newHours = 0;
string newMin;
string time;
if (hours < 0 || hours > 24)
throw timeFM();
if (hours < 13)
{
newHours = hours;
newMin = min;
time = "AM";
}
else
{
newHours = hours - 12;
newMin = min;
time = "PM";
}
cout << "That is the same as\n"
<< newHours << useless << newMin << " " << time
<< endl;
cout << "Again? (y/n)";
cin >> done;
}
catch(timeFM)
{
cout << "Time Format Error\n";
}
}
}
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand (time(NULL));
int x;
x = rand() %7;
cout << x;
x = rand() %5;
cout << x;
x = rand() %7;
cout << x;
x = rand() %5;
cout << x;
x = rand() %7;
cout << x;
x = rand() %5;
cout << x;
x = rand() %7;
cout << x;
x = rand() %5;
cout << x;
x = rand() %7;
cout << x;
return 0;
}
|
#include <iostream>
#include <string>
using namespace std;
int numDivisors(long long n) {
int num = 1;
for (long long i = 2; i <= n; i++) {
if ( n % i == 0 ) {
num++;
}
}
return num;
}
int main() {
long long count = 3;
long long num = 3;
int divs;
bool ex[4] = {false, false, false, false};
while(true) {
divs = numDivisors(num);
if (divs > 500) {
break;
} else if (divs > 400 && !ex[3]) {
cout << num << " has over 400 divisors." << endl;
cout << "count = " << count << endl;
ex[3] = true;
} else if (divs > 300 && !ex[2]) {
cout << num << " has over 300 divisors." << endl;
cout << "count = " << count << endl;
ex[2] = true;
} else if (divs > 200 && !ex[1]) {
cout << num << " has over 200 divisors." << endl;
cout << "count = " << count << endl;
ex[1] = true;
} else if (divs > 100 && !ex[0]) {
cout << num << " has over 100 divisors." << endl;
cout << "count = " << count << endl;
ex[0] = true;
} else {}
num += count;
count++;
}
cout << num << endl;
cout << "Sum of numbers 1 to " << count-1 << " has " << divs << " divisors." << endl;
}
|
#include "Sprite.h"
#include "ImageManager.h"
namespace WGF
{
Sprite::Sprite() :
mFilename("")
{
//ctor
}
Sprite::~Sprite()
{
//dtor
if(mFilename != "")
{
ImageManager::GetSingleton().Unload(mFilename);
}
}
Sprite::Sprite(const std::string& filename, const sf::Vector2f& position, const sf::Vector2f& scale, float rotation, const sf::Color& col):
sf::Sprite(ImageManager::GetSingleton().Load(filename), position, scale, rotation, col),
mFilename(filename)
{
}
}
|
//
// Created by peto184 on 09-Dec-17.
//
#ifndef PPGSO_OBJECT_H
#define PPGSO_OBJECT_H
#include <glm/vec3.hpp>
#include <glm/detail/type_mat.hpp>
#include <glm/detail/type_mat4x4.hpp>
#include "src/playground/constants.h"
class Scene;
class Object {
public:
Object() = default;
glm::vec3 mPosition;
glm::vec3 mRotation;
glm::vec3 mScale;
glm::mat4 mModelMatrix;
virtual bool update(Scene& scene, float dt) = 0;
virtual void render(Scene &scene) = 0;
bool checkCollisionY(Object& o1, Object& o2);
bool checkCollisionX(Object& o1, Object& o2);
const float SPEED = 5.0f;
const float JUMP_STRENGHT = 10.0f;
const float GRAVITY = 15.0f;
float mRotAngle = 0.0f;
glm::vec3 mDirection{0.0,0.0,0.0};
enum Orientation mOrientation = Orientation ::LEFT;
};
#endif //PPGSO_OBJECT_H
|
#include "stdafx.h"
#include "SkinModelDummy.h"
SkinModelDummy::SkinModelDummy()
{
}
SkinModelDummy::~SkinModelDummy()
{
}
bool SkinModelDummy::Start() {
return true;
}
void SkinModelDummy::Update() {
m_model.UpdateWorldMatrix(m_pos, m_rot, CVector3::One());
}
void SkinModelDummy::Render() {
}
void SkinModelDummy::Init(const wchar_t* filepath, EnFbxUpAxis axis) {
m_model.Init(filepath, axis);
}
|
#include <iostream>
#include <string.h>
#include <cjxml/cjson.h>
int main() {
void * writer = json_create_writer();
json_append_double(writer, "key1", 1.425);
json_append_int(writer, "key2", 7);
json_append_string(writer, "key3", "hello world!");
int vals[10];
for(int i = 0; i < 10; i++) vals[i] = i;
json_append_int_array(writer, "key4", vals, 10);
const char * subjson = "{\"key5\":17,\"key6\":18.7}";
json_append_object(writer, "sub", subjson, strlen(subjson));
const char* json = json_dispose_writer(writer);
std::cout << json << std::endl;
for(int i = 0; i < 10; i++) vals[i] = -1;
std::cout << "json has key9? " << json_doc_has_key(json, "key9") << std::endl;
std::cout << "json get double from key1: " << json_doc_get_double(json, "key1") << std::endl;
/*
const char* json = json_dispose_writer(writer);
memset(vals, 0, sizeof(int) * 10);
json_doc_get_int_array(json, "key4", vals, 10);
std::cout << "json get the array of int from key4: " << std::endl;
for (int i = 0; i < 10; i++)
std::cout << vals[i] << std::endl;
*/
}
|
/**
* Unidad 3: LightBuzzer o Buzz Lightyear
*
* Hacemos sonar un altavoz piezoeléctrico (buzzer)
* con un LDR (Light Dependant Resistor) usando
* la configuración de un divisor de tensión.
*/
const byte pinBuzzer = 10;
const byte pinBoton = 2;
void setup() {
pinMode(pinBuzzer, OUTPUT);
pinMode(pinBoton, INPUT_PULLUP);
}
void loop() {
int luz = analogRead(A0);
// Mapeamos los valores obtenidos del sensor a frecuencias
// que el buzzer pueda reproducir
int frec = map(luz, 0, 1023, 1000, 5000);
// Hacemos sonar el buzzer a la frecuencia calculada usando PWM
// cuando esté pulsado el botón
if (digitalRead(pinBoton) == LOW) {
tone(pinBuzzer, frec);
// Dejamos de emitir cuando soltamos el botón
} else {
noTone(pinBuzzer);
}
}
|
#pragma once
#include "datablock.h"
namespace trevi {
class SourceBlock : public trevi::DataBlock
{
public:
// From payload
SourceBlock( uint8_t* payloadBuffer, int payloadSize );
// From Raw Buffer
SourceBlock( int bufferSize, uint8_t* rawBuffer );
virtual ~SourceBlock();
virtual uint16_t payload_size();
virtual void * payload_ptr();
uint32_t get_global_sequence_idx();
void set_global_sequence_idx(uint32_t value);
virtual void * footer_ptr();
void updateCRC();
uint16_t readCRC();
uint16_t computeCRC();
bool isCorrectCRC();
private:
static const int SOURCEBLOCK_HEADER_SIZE = 6;
static const int SOURCEBLOCK_GLOBAL_SEQ_IDX_OFFSET = 2;
static const int SOURCEBLOCK_FOOTER_SIZE = 2;
void setPayloadSize( uint16_t plSize );
protected:
};
}
|
/*
* @author: aaditkamat
* @date: 28/12/2018
*/
#include <iostream>
using namespace std;
bool can_replace_a_character(string str1, string str2) {
if (str1.size() != str2.size()) {
return false;
}
int change = 0;
for (int i = 0; i < str1.size(); i++) {
if (str1[i] != str2[i]) {
change++;
}
}
return change == 1;
}
bool is_a_modified_substring(string str1, string str2) {
if (str1.empty()) {
return true;
}
if (str1[0] != str2[1] && str1[0] != str2[0]) {
return false;
}
int found = str2.find(str1[0]);
if (found == 1) {
return str2.find(str1) != string::npos;
}
int j = 0, ctr = 0;
for (int i = 0; i < str1.size(); j++) {
if (j >= str2.size()) {
return false;
}
if (str1[i] != str2[j] && ctr == 0) {
ctr++;
continue;
}
if (str1[i] != str2[j]) {
return false;
}
i++;
}
return true;
}
bool can_add_a_character(string str1, string str2) {
return str2.size() - str1.size() == 1 && is_a_modified_substring(str1, str2);
}
bool can_delete_a_character(string str1, string str2) {
return str1.size() - str2.size() == 1 && is_a_modified_substring(str2, str1);
}
bool are_one_edit_away(string str1, string str2) {
if (str1 == str2) {
return true;
}
return can_replace_a_character(str1, str2) || can_add_a_character(str1, str2) || can_delete_a_character(str1, str2);
}
int main() {
string str1, str2;
cout << "Enter two strings: " << endl;
getline(cin, str1);
getline(cin, str2);
cout << "Are \"" << str1 << "\" and \"" << str2 << "\" one edit away? " << are_one_edit_away(str1, str2) << endl;
}
|
#include "MappingScreenTapListener.hpp"
#include "LeftMouseButtonEvent.hpp"
using namespace Leap;
void MappingScreenTapListener::onScreenTap(const ScreenTapGesture& screenTap) {
LeftMouseButtonEvent event;
event.trigger();
}
|
#include "GameObject.h"
#include "GameState.h"
#include "sdlwrap.h"
#include <SDL_events.h>
#include <SDL_render.h>
Player::Player(int x, int y)
: _x(x), _y(y)
{
_hp = Player::defaultHp();
_weapons[WEAPON_PISTOL].reset(new Pistol());
_weapons[WEAPON_SHOTGUN].reset(new Shotgun());
_weapons[WEAPON_UZI].reset(new Uzi());
_dmgCd.start();
}
float Player::x() const { return _x; }
float Player::y() const { return _y; }
float Player::angle() const { return _angle; }
float Player::speed() const { return _speed; }
void Player::x(float x) { _x = x; }
void Player::y(float y) { _y = y; }
void Player::angle(float a) { _angle = a; }
void Player::speed(float s) { _speed = s; }
Circle Player::circle() const { return Circle(_x, _y, 30); }
std::string Player::texName() const {
std::string name = "player";
switch(_currentWeap) {
case WEAPON_SHOTGUN:
return name += "_shotgun";
case WEAPON_UZI:
return name += "_uzi";
default:
return name += "_pistol";
}
}
int Player::hp() const { return _hp; }
int Player::defaultHp() const { return 100; }
int Player::dmg() const { return 0; }
bool Player::dead() const {
return _hp <= 0;
}
void Player::damage(int v) {
if(v > 0 && _dmgCd.passed(500)) {
_hp -= v;
_dmgCd.start();
}
}
bool Player::reloading() const {
return _weapons[_currentWeap]->reloading();
}
void Player::handle_events() {
switch(gameEvent().type) {
case SDL_MOUSEWHEEL:
if(gameEvent().wheel.y < 0) {
if(_currentWeap < WEAPON_LAST) ++_currentWeap;
}
else {
if(_currentWeap > WEAPON_FIRST) --_currentWeap;
}
break;
case SDL_MOUSEBUTTONDOWN:
if(gameEvent().button.button == SDL_BUTTON_LEFT) {
_state |= SHOOTS;
}
break;
case SDL_MOUSEBUTTONUP:
if(gameEvent().button.button == SDL_BUTTON_LEFT) {
_state ^= SHOOTS;
}
break;
case SDL_KEYDOWN:
switch(gameEvent().key.keysym.sym) {
case SDLK_w:
_state |= MOVES_UP;
break;
case SDLK_s:
_state |= MOVES_DOWN;
break;
case SDLK_a:
_state |= MOVES_LEFT;
break;
case SDLK_d:
_state |= MOVES_RIGHT;
break;
case SDLK_SPACE:
_state |= SHOOTS;
break;
default:;
}
break;
case SDL_KEYUP:
switch(gameEvent().key.keysym.sym) {
case SDLK_1:
_currentWeap = WEAPON_PISTOL;
break;
case SDLK_2:
_currentWeap = WEAPON_SHOTGUN;
break;
case SDLK_3:
_currentWeap = WEAPON_UZI;
break;
case SDLK_w:
_state ^= MOVES_UP;
break;
case SDLK_s:
_state ^= MOVES_DOWN;
break;
case SDLK_a:
_state ^= MOVES_LEFT;
break;
case SDLK_d:
_state ^= MOVES_RIGHT;
break;
case SDLK_SPACE:
_state ^= SHOOTS;
break;
default:;
}
break;
case SDL_MOUSEMOTION:
_angle = to_deg(get_angle(x(), y(), gameEvent().motion.x, gameEvent().motion.y));
break;
default:;
}
}
void Player::handle_logic() {
int mx, my;
SDL_GetMouseState(&mx, &my);
_angle = to_deg(get_angle(_x, _y, mx, my));
if(_dmgCd.passed(500)) {
_speed = 2.3f;
}
else {
_speed = 1.0f;
}
if(_state & MOVES_DOWN) {
_y = _y + _speed;
}
if(_state & MOVES_UP) {
_y = _y - _speed;
}
if(_state & MOVES_LEFT) {
_x = _x - _speed;
}
if(_state & MOVES_RIGHT) {
_x = _x + _speed;
}
_weapons[_currentWeap]->reload();
if(_state & SHOOTS) {
_weapons[_currentWeap]->shoot(*this);
}
}
void Player::handle_render() {
default_render();
default_render_health(SDL_Color{0, 0x77, 0, 0xFF});
}
|
/*
Name: �������еĵ�nλ��ֵ
Copyright:
Author: Hill bamboo
Date: 2019/8/15 18:26:55
Description: ���
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
scanf("%d", &n);
int k = 0;
int sum;
do {
sum = (k + 1) * k / 2;
++k;
} while (sum < n);
// int ans = 1;
// while (ans * (ans + 1) / 2 < num) ++ans;
// printf("%d\n", ans);
printf("%d\n", k - 1);
return 0;
}
|
// Copyright (c) 2011-2016 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
namespace CryptoNote
{
const static boost::uuids::uuid CRYPTONOTE_NETWORK = { { 0x17, 0x15, 0x62, 0x97, 0x16, 0x74, 0x4f, 0x50, 0x31, 0x30, 0x02, 0x2f, 0x38, 0x1c, 0x05, 0x66 } };
}
|
#include <cmath>
#include <list>
#include <Poco/Exception.h>
#include <Poco/Path.h>
#include <Poco/StringTokenizer.h>
#include <Poco/Dynamic/Var.h>
#include "di/DependencyInjector.h"
#include "math/SimpleCalc.h"
#include "util/ClassInfo.h"
#include "math/LogicalExpression.h"
#include "util/MultiException.h"
#include "util/TimespanParser.h"
using namespace std;
using namespace Poco;
using namespace Poco::Dynamic;
using namespace Poco::Util;
using namespace BeeeOn;
namespace BeeeOn {
class InstanceInfo {
public:
InstanceInfo(const string &name):
m_name(name)
{
}
const string &name() const
{
return m_name;
}
void validate(AutoPtr<AbstractConfiguration> conf) const
{
const string base("instance[@name='" + m_name + "']");
if (!conf->has(base)) {
throw NotFoundException(
"missing instance of name " + m_name);
}
if (!conf->has(base + "[@class]")) {
throw NotFoundException(
"attribute 'class' not specified for instance "
+ m_name);
}
}
string library(AutoPtr<AbstractConfiguration> conf) const
{
const string lib("instance[@name='" + m_name + "'][@library]");
return conf->getString(lib, "");
}
const string resolveAlias(AutoPtr<AbstractConfiguration> conf) const
{
const string ref("alias[@name='" + m_name + "'][@ref]");
const string &value = conf->getString(ref, "");
if (value.compare(m_name) == 0)
throw IllegalStateException("alias " + m_name
+ " refers to itself");
return value;
}
const string resolveClass(AutoPtr<AbstractConfiguration> conf) const
{
string entry("instance[@name='" + m_name + "'][@class]");
return conf->getString(entry);
}
bool testConditions(AutoPtr<AbstractConfiguration> conf,
const string &key) const
{
const string if_yes(key + "[@if-yes]");
/* no such condition */
if (!conf->has(if_yes))
return true;
const string &value = conf->getString(if_yes);
return value == "y" || value == "yes" || value == "true";
}
void resolveKeys(AutoPtr<AbstractConfiguration> conf,
AbstractConfiguration::Keys &keys) const
{
const string base("instance[@name='" + m_name + "']");
AbstractConfiguration::Keys tmp;
conf->keys(base, tmp);
AbstractConfiguration::Keys::const_iterator it;
for (it = tmp.begin(); it != tmp.end(); ++it) {
const string &key = *it;
if (key.find("set") != 0 && key.find("add") != 0)
continue;
if (!testConditions(conf, base + "." + key))
continue;
keys.push_back(base + "." + key);
}
}
private:
string m_name;
};
}
void DependencyInjector::destroyOne(DIWrapper *one) const
{
logger().debug(
"deleting an instance of "
+ ClassInfo(one->type()).name(),
__FILE__, __LINE__);
delete one;
}
void DependencyInjector::cleanup(const WrapperVector vec) const
{
for (auto wrapper : vec) {
if (wrapper->hasHook("cleanup")) {
try {
logger().debug("calling hook 'cleanup' for "
+ ClassInfo(wrapper->type()).name());
wrapper->callHook("cleanup");
}
BEEEON_CATCH_CHAIN(logger())
}
}
}
DependencyInjector::WrapperVector DependencyInjector::tryDestroy(const WrapperVector vec) const
{
WrapperVector alive;
for (auto wrapper : vec) {
const int count = wrapper->referenceCount();
if (count > 1)
alive.emplace_back(wrapper);
else
destroyOne(wrapper);
}
return alive;
}
void DependencyInjector::destroyRest(const WrapperVector vec) const
{
for (auto wrapper : vec) {
const int count = wrapper->referenceCount();
if (count > 1) {
logger().warning(
"an instance of "
+ ClassInfo(wrapper->type()).name()
+ " is still referenced ("
+ to_string(wrapper->referenceCount() - 1)
+ ")",
__FILE__, __LINE__);
}
destroyOne(wrapper);
}
}
DependencyInjector::DependencyInjector(
AutoPtr<AbstractConfiguration> conf,
const vector<string> &paths,
bool avoidEarly):
m_conf(conf),
m_librariesPaths(paths)
{
computeConstants();
if (!avoidEarly) {
try {
createEarly();
}
BEEEON_CATCH_CHAIN_ACTION(logger(),
destroyAll();
throw)
}
}
void DependencyInjector::destroyAll()
{
logger().debug(
"destroying " + to_string(m_free.size()) + " instances",
__FILE__, __LINE__);
m_set.clear();
WrapperVector alive = m_free;
m_free.clear();
cleanup(alive);
while (!alive.empty()) {
const size_t count = alive.size();
logger().trace("try destroy up to " + to_string(count) + " instances",
__FILE__, __LINE__);
alive = tryDestroy(alive);
if (count == alive.size()) {
logger().warning(
"could not delete all instances,"
" there might be a circular dependency",
__FILE__, __LINE__);
break;
}
}
destroyRest(alive);
}
DependencyInjector::~DependencyInjector()
{
destroyAll();
}
void DependencyInjector::computeConstants()
{
AbstractConfiguration::Keys tmp;
m_conf->keys(tmp);
AbstractConfiguration::Keys::const_iterator it;
for (it = tmp.begin(); it != tmp.end(); ++it) {
const string &key = *it;
if (key.find("constant[") == string::npos && key != "constant")
continue;
if (!m_conf->has(key + "[@name]"))
continue;
const string &name = m_conf->getString(key + "[@name]");
string value;
logger().trace("visiting constant " + name, __FILE__, __LINE__);
if (m_conf->has(key + "[@text]")) {
value = m_conf->getString(key + "[@text]");
logger().debug(
"evaluating constant " + name + " value " + value,
__FILE__, __LINE__);
m_conf->setString(name, value);
}
else if (m_conf->has(key + "[@time]")) {
value = m_conf->getString(key + "[@time]");
const auto result = TimespanParser::parse(value);
logger().debug(
"evaluating constant " + name
+ " value " + value
+ " as " + to_string(result.totalMicroseconds()),
__FILE__, __LINE__);
m_conf->setInt64(name, result.totalMicroseconds());
}
else if (m_conf->has(key + "[@number]")) {
value = m_conf->getString(key + "[@number]");
SimpleCalc calc;
const double result = calc.evaluate(value);
logger().debug(
"evaluating constant " + name
+ " value " + value
+ " as " + to_string(result),
__FILE__, __LINE__);
if (::floor(result) == result)
m_conf->setInt64(name, static_cast<Int64>(result));
else
m_conf->setDouble(name, result);
}
else if (m_conf->has(key + "[@yes-when]")) {
value = m_conf->getString(key + "[@yes-when]");
const auto expr = LogicalExpression::parse(value);
logger().debug(
"evaluating constant " + name
+ " value " + value
+ " as " + to_string(expr.result()),
__FILE__, __LINE__);
if (expr.result())
m_conf->setString(name, "yes");
else
m_conf->setString(name, "no");
}
else {
throw NotFoundException("missing attribute text, time or number");
}
}
}
void DependencyInjector::createEarly()
{
AbstractConfiguration::Keys tmp;
m_conf->keys(tmp);
AbstractConfiguration::Keys::const_iterator it;
for (it = tmp.begin(); it != tmp.end(); ++it) {
const string &key = *it;
if (key.find("instance[") == string::npos && key != "instance")
continue;
if (!m_conf->has(key + "[@name]"))
continue;
const string &init = m_conf->getString(
key + "[@init]", "lazy");
if (init.compare("early"))
continue;
const string name = m_conf->getString(key + "[@name]");
(void) createNoAlias(name);
}
}
DIWrapper *DependencyInjector::resolveAndCreate(const string &name, bool disown)
{
InstanceInfo info(name);
const string &ref = info.resolveAlias(m_conf);
if (ref.empty())
return createNoAlias(info, disown);
DIWrapper *existing = find(ref);
if (existing != NULL) {
logger().debug("instance " + name
+ " reused as alias to " + ref,
__FILE__, __LINE__);
return existing;
}
InstanceInfo aliasInfo(ref);
return createNoAlias(aliasInfo, disown);
}
DIWrapper *DependencyInjector::createImpl(const string &name, bool disown)
{
DIWrapper *existing = findImpl(name);
if (existing != NULL) {
logger().debug("instance " + name + " reused",
__FILE__, __LINE__);
return existing;
}
return resolveAndCreate(name, disown);
}
DIWrapper *DependencyInjector::findImpl(const string &name)
{
WrapperMap::const_iterator it = m_set.find(name);
if (it != m_set.end())
return it->second;
return NULL;
}
void DependencyInjector::castImpl(
const type_info &type,
const DIWrapper &wrapper,
void *target)
{
DIWCast *cast = DIWCast::find(type, wrapper);
if (cast == NULL)
throw DIWCastException(wrapper.type(), type);
cast->cast(wrapper.raw(), target);
}
DIWrapper *DependencyInjector::createNoAlias(
const InstanceInfo &info, bool disown)
{
DIWrapper *t = createNew(info);
if (t == NULL)
throw Poco::NullPointerException("failed to create target "
+ info.name());
if (!disown) {
m_set.insert(make_pair(info.name(), t));
m_free.push_back(t);
}
return injectDependencies(info, t);
}
void DependencyInjector::loadLibrary(SharedLibrary &library, const string &name) const
{
MultiException ex("failed to load library " + name);
const string libName = "lib" + name + SharedLibrary::suffix();
const auto paths = m_librariesPaths;
if (paths.empty())
throw LibraryLoadException("no ldpath has been specified");
for (const auto &dir : paths) {
const Path path(dir, libName);
if (logger().debug()) {
logger().debug(
"attempt to load library " + name
+ " from " + path.toString(),
__FILE__, __LINE__);
}
try {
library.load(path.toString(), SharedLibrary::SHLIB_GLOBAL);
}
catch (const LibraryAlreadyLoadedException &) {
break;
}
catch (const LibraryLoadException &e) {
ex.caught(e);
}
}
if (!ex.empty())
throw ex;
}
DIWrapper *DependencyInjector::createNew(const InstanceInfo &info)
{
info.validate(m_conf);
const string lib = info.library(m_conf);
if (!lib.empty()) {
auto &library = m_libraries[lib];
if (!library.isLoaded()) {
logger().notice("loading library " + lib);
loadLibrary(library, lib);
}
}
const string cls = info.resolveClass(m_conf);
logger().debug("creating " + info.name() + " as " + cls);
DIWrapperFactory &factory = DIWrapperFactory::lookupFactory(cls);
return factory.create();
}
void DependencyInjector::createAndInjectRef(
const string &targetName,
DIWrapper *target,
const string &name,
const string &value)
{
logger().debug("injecting " + value + " as " + name
+ " into " + targetName);
DIWrapper *ref = NULL;
try {
ref = createImpl(value, false);
} catch (const Exception &e) {
logger().error("failed to create ref " + value,
__FILE__, __LINE__);
e.rethrow();
}
if (ref == NULL) {
throw NullPointerException(
"failed to create ref " + value);
}
target->injectRef(name, *ref);
}
bool DependencyInjector::tryInjectRef(
const InstanceInfo &info,
DIWrapper *target,
const string &key,
const string &name)
{
if (m_conf->has(key + "[@ref]")) {
const string value = m_conf->getString(key + "[@ref]");
createAndInjectRef(info.name(), target, name, value);
return true;
}
return false;
}
void DependencyInjector::evalAndInjectNumber(
const string &targetName,
DIWrapper *target,
const string &name,
const string &value)
{
SimpleCalc calc;
const double number = calc.evaluate(value);
logger().debug("injecting number " + to_string(number)
+ " as " + name + " into " + targetName);
target->injectNumber(name, number);
}
bool DependencyInjector::tryInjectNumber(
const InstanceInfo &info,
DIWrapper *target,
const string &key,
const string &name)
{
if (m_conf->has(key + "[@number]")) {
const string &tmp = m_conf->getString(key + "[@number]");
evalAndInjectNumber(info.name(), target, name, tmp);
return true;
}
return false;
}
bool DependencyInjector::tryInjectText(
const InstanceInfo &info,
DIWrapper *target,
const string &key,
const string &name)
{
if (m_conf->has(key + "[@text]")) {
const string value = m_conf->getString(key + "[@text]");
logger().debug("injecting " + value + " as " + name
+ " into " + info.name());
target->injectText(name, value);
return true;
}
return false;
}
bool DependencyInjector::tryInjectTime(
const InstanceInfo &info,
DIWrapper *target,
const string &key,
const string &name)
{
if (m_conf->has(key + "[@time]")) {
const string value = m_conf->getString(key + "[@time]");
logger().debug("injecting " + value + " as " + name
+ " into " + info.name());
const Timespan &span = TimespanParser::parse(value);
target->injectTime(name, span);
return true;
}
return false;
}
bool DependencyInjector::tryInjectList(
const InstanceInfo &info,
DIWrapper *target,
const string &key,
const string &name)
{
if (m_conf->has(key + "[@list]")) {
const string value = m_conf->getString(key + "[@list]");
logger().debug("injecting " + value + " as " + name
+ " into " + info.name());
StringTokenizer tokenizer(value, ",;",
StringTokenizer::TOK_TRIM);
list<Var> tmp;
for (const auto &s : tokenizer)
tmp.push_back(s);
target->injectList(name, tmp);
return true;
}
return false;
}
bool DependencyInjector::tryInjectMap(
const InstanceInfo &info,
DIWrapper *target,
const string &key,
const string &name)
{
if (!m_conf->has(key + ".pair") && !m_conf->has(key + ".pair[1]"))
return false;
AbstractConfiguration::Keys keys;
m_conf->keys(key, keys);
map<Var, Var> m;
for (auto &pair : keys) {
if (!m_conf->has(key + "." + pair + "[@key]")) {
logger().warning("missing attribute @key for "
+ key + "." + pair);
continue;
}
if (!m_conf->has(key + "." + pair + "[@text]")) {
logger().error("missing attribute @text for "
+ key + "." + pair);
return false;
}
const string &mapKey = m_conf->getString(
key + "." + pair + "[@key]");
const string &mapText = m_conf->getString(
key + "." + pair + "[@text]");
logger().debug("map pair " + mapKey + " -> " + mapText,
__FILE__, __LINE__);
if (!m.emplace(mapKey, mapText).second) {
throw InvalidArgumentException(
"duplicate map key " + mapKey + " for " + key
+ " when injecting into " + info.name()
);
}
}
logger().debug("injecting map " + name + " into " + info.name(),
__FILE__, __LINE__);
target->injectMap(name, m);
return true;
}
void DependencyInjector::injectValue(
const InstanceInfo &info,
DIWrapper *target,
const string &key,
const string &name)
{
if (tryInjectRef(info, target, key, name))
return;
if (tryInjectNumber(info, target, key, name))
return;
if (tryInjectText(info, target, key, name))
return;
if (tryInjectTime(info, target, key, name))
return;
if (tryInjectList(info, target, key, name))
return;
if (tryInjectMap(info, target, key, name))
return;
logger().error("malformed configuration entry "
+ key + " for " + info.name(),
__FILE__, __LINE__);
}
DIWrapper *DependencyInjector::injectDependencies(
const InstanceInfo &info,
DIWrapper *target)
{
AbstractConfiguration::Keys keys;
info.resolveKeys(m_conf, keys);
AbstractConfiguration::Keys::const_iterator it;
for (it = keys.begin(); it != keys.end(); ++it) {
const string &key = *it;
logger().trace("visiting key " + key);
if (!m_conf->has(key + "[@name]")) {
logger().warning("missing @name for " + key,
__FILE__, __LINE__);
continue;
}
const string name = m_conf->getString(key + "[@name]");
try {
injectValue(info, target, key, name);
} catch (const Poco::Exception &e) {
logger().error("failed inject " + name + " for "
+ info.name(), __FILE__, __LINE__);
e.rethrow();
}
logger().trace("next key after " + key);
}
logger().notice("successfully created " + info.name(),
__FILE__, __LINE__);
try {
if (!target->hasHook("done")) {
logger().debug("no such hook 'done' defined for "
+ ClassInfo(target->type()).name(),
__FILE__, __LINE__);
}
else {
target->callHook("done");
}
} catch (const Exception &e) {
logger().error("hook 'done' failed for " + info.name(),
__FILE__, __LINE__);
e.rethrow();
}
return target;
}
|
#ifndef __SETESTAPP1_H__
#define __SETESTAPP1_H__
#include <se.h>
class SETestApp1 : public SEApplication<GLfloat>
{
public:
SETestApp1();
virtual ~SETestApp1() {}
virtual void init(int argc, char **argv);
virtual void update();
virtual void run();
virtual void quit();
virtual void reshape(int width, int height) {}
virtual void display();
virtual void key(unsigned char key, int x, int y);
virtual void pressFuncKey(int key, int x1, int y1) {}
virtual void releaseFuncKey(int key, int x, int y) {}
virtual void mouseMotion(int x, int y) {}
virtual void mousePassiveMotion(int x, int y) {}
virtual void mouseButton(int button, int state, int x, int y) {}
virtual void idle() {}
private:
int objId;
uint32_t ccId;
int l1Id;
int l2Id;
// uint32_t sphereId;
// uint32_t cubeId;
// uint32_t coneId;
// uint32_t torusId;
// uint32_t teapotId;
SECamera<GLfloat>* c_;
SEOpenGLPrimitive* prim;
SEOpenGLDirectionalLight* l1;
SEOpenGLSpotLight* l2;
SETimer<GLfloat> t_;
GLfloat speedFactor;
GLfloat objSize;
SEVec3<GLfloat> rotAxis;
bool isWireOn;
void switchToSphere();
void switchToCube();
void switchToCone();
void switchToTorus();
void switchToTeapot();
void destroyCurrentObj();
};
#endif // __SETESTAPP1_H__
|
#include "_pch.h"
#include "whPGFileLinkProperty.h"
/// BtnStringEditor
class PGFileLinkEditor : public wxPGTextCtrlEditor
{
public:
DECLARE_DYNAMIC_CLASS(PGFileLinkEditor)
typedef std::function<bool(wxPGProperty*)> OnBtnFunc;
PGFileLinkEditor(){}
virtual ~PGFileLinkEditor() {}
virtual wxPGWindowList CreateControls(wxPropertyGrid* propGrid,
wxPGProperty* property,
const wxPoint& pos,
const wxSize& sz) const override
{
bool is_read_only = property->HasFlag(wxPG_PROP_READONLY) != 0;//(property->GetFlags() & wxPG_PROP_READONLY)!=0;
auto btnprop = dynamic_cast<whPGFileLinkProperty*>(property);
// Create and populate buttons-subwindow
wxPGMultiButton* buttons = new wxPGMultiButton(propGrid, sz);
// Add regular buttons
buttons->Add(wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_MENU));
buttons->Add(wxString("..."));
auto btn0 = buttons->GetButton(0);
auto btn1 = buttons->GetButton(1);
btn0->SetToolTip("Открыть");
btn1->SetToolTip("Выбрать");
if (is_read_only)
btn1->Disable();
// Create the 'primary' editor control (textctrl in this case)
property->ChangeFlag(wxPG_PROP_READONLY, true); // wxPG_EDITABLE_VALUE
wxPGWindowList wndList = wxPGTextCtrlEditor::CreateControls(propGrid, property, pos, buttons->GetPrimarySize());
property->ChangeFlag(wxPG_PROP_READONLY, is_read_only);
// Finally, move buttons-subwindow to correct position and make sure returned wxPGWindowList contains our custom button list.
buttons->Finalize(propGrid, pos);
wndList.SetSecondary(buttons);
return wndList;
}
virtual bool OnEvent(wxPropertyGrid* propGrid,
wxPGProperty* prop,
wxWindow* ctrl,
wxEvent& evt) const override
{
if (evt.GetEventType() == wxEVT_COMMAND_BUTTON_CLICKED)
{
wxPGMultiButton* buttons = (wxPGMultiButton*)propGrid->GetEditorControlSecondary();
whPGFileLinkProperty* bprop = dynamic_cast<whPGFileLinkProperty*>(prop);
if (!buttons || !bprop)
return false;
const std::function<bool(wxPGProperty*)>* func = nullptr;
if (evt.GetId() == buttons->GetButtonId(1))
func = &bprop->GetOpenFunc();
else if (evt.GetId() == buttons->GetButtonId(0))
func = &bprop->GetExecFunc();
if (func && func->operator bool() )
return (*func)(prop);
return false;
}//if (evt.GetEventType() == wxEVT_COMMAND_BUTTON_CLICKED)
return false;
}
};
class whPGFileLinkProperty::LinkImpl
{
public:
std::function<bool(wxPGProperty*)> funcOpen = nullptr;
std::function<bool(wxPGProperty*)> funcExec = nullptr;
};
IMPLEMENT_DYNAMIC_CLASS(PGFileLinkEditor, wxPGTextCtrlEditor)
//-------------------------------------------------------------------------------------------------
PGFileLinkEditor* gPGFileLinkEditor = NULL;
whPGFileLinkProperty::whPGFileLinkProperty(const wxString& label, const wxString& name, const wxString& value)
: wxStringProperty(label, name, value)
{
SetValue(WXVARIANT(value));
mImpl.reset(new LinkImpl);
mImpl->funcOpen = [this](wxPGProperty* prop)->bool
{
wxFileDialog openFileDialog(nullptr);
if (openFileDialog.ShowModal() == wxID_CANCEL)
return false;
prop->SetValueFromString (openFileDialog.GetPath());
return true;
};
mImpl->funcExec = [this](wxPGProperty* prop)->bool
{
auto str = prop->GetValueAsString();
if (str.IsEmpty())
return false;
wxBusyCursor busyCursor;
// win execute
HWND hwnd = nullptr;
LPCWSTR path = str.operator const wchar_t *();
ShellExecuteW(hwnd, L"open", path, L"", NULL, SW_SHOWNORMAL);
//wxWidget
//wxShell(str);
// std
//#include "unistd.h"
//execl(prop->GetValueAsString().c_str(),nullptr);
return true;
};
if (!gPGFileLinkEditor)
{
gPGFileLinkEditor = new PGFileLinkEditor;
wxPropertyGrid::RegisterEditorClass(gPGFileLinkEditor);
}
this->SetEditor("PGFileLinkEditor");
}
//-------------------------------------------------------------------------------------------
whPGFileLinkProperty::~whPGFileLinkProperty()
{
}
//-------------------------------------------------------------------------------------------
void whPGFileLinkProperty::SetOpenFunc(std::function<bool(wxPGProperty*)>& func)
{
mImpl->funcOpen = func;
}
//-------------------------------------------------------------------------------------------
void whPGFileLinkProperty::SetExecFunc(std::function<bool(wxPGProperty*)>& func)
{
mImpl->funcExec = func;
}
//-------------------------------------------------------------------------------------------
const std::function<bool(wxPGProperty*)>& whPGFileLinkProperty::GetOpenFunc()const
{
return mImpl->funcOpen;
}
//-------------------------------------------------------------------------------------------
const std::function<bool(wxPGProperty*)>& whPGFileLinkProperty::GetExecFunc()const
{
return mImpl->funcExec;
}
|
#include <Rigidbody.h>
#include <iostream>
using namespace NoHope;
Rigidbody::Rigidbody(b2World *world, Vec2 position, float angle, Vec2 size, bool fixedRotation, bool staticBody)
:m_world(world)
{
Init(position, angle, size, fixedRotation, staticBody);
}
Rigidbody::~Rigidbody()
{
m_world->DestroyBody(body);
//m_world->DestroyBody(groundBody);
}
void Rigidbody::Init(Vec2 position, float angle, Vec2 size, bool fixedR, bool staticBody)
{
//Player
b2BodyDef BodyDef;
if (!staticBody)
{
BodyDef.type = b2_dynamicBody; //this will be a dynamic body
}
position = position / PIXELS_PER_METER;
size = size / PIXELS_PER_METER;
BodyDef.position.Set(position.x, position.y); //set the starting position
BodyDef.angle = angle; //set the starting angle
body = m_world->CreateBody(&BodyDef);
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox((size.x/2),(size.y/2));
//dynamicBox.SetAsBox(size.x/2,size.y/2);
b2FixtureDef boxFixtureDef;
boxFixtureDef.shape = &dynamicBox;
boxFixtureDef.density = 10;
body->CreateFixture(&boxFixtureDef);
body->SetFixedRotation(fixedR);
//Ground
//b2BodyDef groundBodyDef;
////groundBodyDef.type = b2_staticBody;
//groundBodyDef.position.Set(0.0f, -10.0f);
//
//groundBody = m_world->CreateBody(&groundBodyDef);
//b2PolygonShape groundBox;
//groundBox.SetAsBox(50.0f, 10.0f);
//groundBody->CreateFixture(&groundBox, 0.0f);
}
void Rigidbody::setPosition(Vec2 spos) //Jessen kommentit
{
const b2Vec2 Spos(spos.x/PIXELS_PER_METER , spos.y/PIXELS_PER_METER);
body->SetTransform(Spos,0);
}
Vec2 Rigidbody::getPosition()
{
const b2Vec2 pos = body->GetPosition();
Vec2 retVal = Vec2(pos.x,pos.y);
retVal = retVal * PIXELS_PER_METER;
return retVal;
}
float Rigidbody::getAngle()
{
return body->GetAngle();
}
void Rigidbody::SetLinearVelocity(Vec2 linearV)
{
body->SetLinearVelocity(b2Vec2(linearV.x,linearV.y));
}
void Rigidbody::SetLinearImpulse(Vec2 LinearI)
{
body->ApplyLinearImpulse(b2Vec2(LinearI.x,LinearI.y), b2Vec2(0,1));
}
//
//void BeginContact(b2Contact* contact)
//{
//
// //check if fixture A was a ball
// void* bodyUserData = contact->GetFixtureA()->GetBody()->GetUserData();
// if ( bodyUserData )
// static_cast<Rigidbody*>( bodyUserData )->startContact();
//
// //check if fixture B was a ball
// bodyUserData = contact->GetFixtureB()->GetBody()->GetUserData();
// if ( bodyUserData )
// static_cast<Rigidbody*>( bodyUserData )->startContact();
//
//}
//
//void EndContact(b2Contact* contact)
//{
// //check if fixture A was a ball
// void* bodyUserData = contact->GetFixtureA()->GetBody()->GetUserData();
// if ( bodyUserData )
// static_cast<Rigidbody*>( bodyUserData )->endContact();
//
// //check if fixture B was a ball
// bodyUserData = contact->GetFixtureB()->GetBody()->GetUserData();
// if ( bodyUserData )
// static_cast<Rigidbody*>( bodyUserData )->endContact();
//
//}
|
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
const int maxn = 1e6 + 7;
int id, ch[maxn][30], cnt[maxn];
char str[15];
void Insert(char *s)
{
int rt = 0;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
if(!ch[rt][s[i]-'a'])
{
memset(ch[id], 0, sizeof(ch[id]));
cnt[id] = 0;
ch[rt][s[i]-'a'] = id++;
}
rt = ch[rt][s[i]-'a'];
cnt[rt]++;
}
}
int match(char *s)
{
int rt = 0;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
if(!ch[rt][s[i]-'a'])
return 0;
rt = ch[rt][s[i]-'a'];
}
return cnt[rt];
}
int main()
{
id = 1;
memset(ch[0], 0, sizeof(ch[0]));
while(gets(str))
{
if(!strlen(str)) break;
Insert(str);
}
while(gets(str) != NULL)
printf("%d\n", match(str));
return 0;
}
|
#include <iostream>
#include <vector>
#include "StrongDataTypes.h"
#include "Utils.h"
using namespace std;
using namespace utils;
int main() {
// simple integer container
std::vector<int> nativeTypeCollection {1, 4, 5, 3, 6, 8, 9, 0, 2, 7};
// custom class type container
std::vector<Integer> userDefinedTypeCollection {
Integer{0},
Integer{1},
Integer{2},
Integer{3},
Integer{4},
Integer{5},
Integer{6},
Integer{7},
Integer{8},
Integer{9}
};
cout << "Collection: ";
PrintCollection(nativeTypeCollection);
cout << "Sorted: ";
std::sort(nativeTypeCollection.begin(), nativeTypeCollection.end());
PrintCollection(nativeTypeCollection);
cout << "Collection: ";
PrintCollection(userDefinedTypeCollection);
cout << "Sorted in descending order: ";
std::sort(begin(userDefinedTypeCollection), end(userDefinedTypeCollection), std::greater<>());
PrintCollection(userDefinedTypeCollection);
return 0;
}
|
#pragma once
#include <string>
#include <iostream>
#include <fstream>
#include "json.hpp"
using json = nlohmann::json;
class Configuration
{
public:
Configuration(std::string fname);
~Configuration();
template <class T> T Get(std::string name)
{
return j[name.c_str()];
}
void Reload();
private:
std::ifstream ifs;
std::string jsons;
json j;
};
|
// Helena Ruiz Ramirez (A01282531) , Gilberto Alejandro Castillo Perez (A00821306)
// 12/marzo/2018
// Proyecto 2: Fecha header
#ifndef Fecha_h
#define Fecha_h
using namespace std;
class Fecha{
private:
int dia;
int mes;
int anio;
public:
// Constructores
Fecha();
Fecha(int,int,int);
// Metodos de Modificacion
void setDia(int);
void setMes(int);
void setAnio(int);
// Metodos de Acceso
int getDia();
int getMes();
int getAnio();
void muestra();
// Metodos de sobrecarga
void operator+=(int);
bool operator==(Fecha);
// Metodos de operacion
bool esBisiesto (int);
//////////////////////////////////
};
// Constructores
Fecha::Fecha(){
dia=0;
mes=0;
anio=0;
}
Fecha::Fecha(int dia,int mes,int anio){
this->dia=dia;
this->mes=mes;
this->anio=anio;
}
// Metodos de Modificacion
void Fecha::setDia(int dia){
this->dia=dia;
}
void Fecha::setMes(int mes){
this->mes=mes;
}
void Fecha::setAnio(int anio){
this->anio=anio;
}
// Metodos de Acceso
int Fecha::getDia(){
return dia;
}
int Fecha::getMes(){
return mes;
}
int Fecha::getAnio(){
return anio;
}
// Metodo de Muestra
void Fecha::muestra(){
cout<<dia<<"/"<<mes<<"/"<<anio<<endl;
}
/////////////////////////////////////////////////////////////////////////////
// Metodos de sobrecarga
void Fecha::operator+=(int d){
// le suma una cantidad de dias "int d" a una fecha, checando que la
// suma restante sea una fecha valida en cuanto al numero de dias del
// mes y el año
dia+=d;
if (mes==1||mes==3||mes==5||mes==7||mes==8||mes==10||mes==12){
while (dia>31){
dia-=31;
mes++;
if (mes>12){
mes-=12;
anio++;
}
}
}
else if (mes==4||mes==6||mes==9||mes==11){
while (dia>30){
dia-=30;
mes++;
if (mes>12){
mes-=12;
anio++;
}
}
}
else if (mes==2){
if (esBisiesto(anio)){
while (dia>29){
dia-=29;
mes++;
if (mes>12){
mes-=12;
anio++;
}
}
}
else {
while (dia>28){
dia-=28;
mes++;
if (mes>12){
mes-=12;
anio++;
}
}
}
}
}
bool Fecha::operator== (Fecha f2){
// operador de igualdad para confirmar que dos
// objetos tipo fecha son iguales
if ( (dia==f2.dia) && (mes==f2.mes) && (anio==f2.anio) )
return true;
else
return false;
}
// Metodos de operacion
bool Fecha::esBisiesto(int anio){
// confirma si un año es bisiesto
if (anio%4!=0)
return false;
else
return true;
}
#endif /* Fecha_h */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.