blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35d8200fd16b6bef7e855de843eca8270202bd4b | 56acf1e1c32f41fcda5f11f4322ffa9fbdae2024 | /Kattis/-listgame2.cpp | 11e1d993209ac2827ce9e7b65e4a5b7096d0f974 | [] | no_license | Kelym/ACM_Training_Archive | cfea3606c0e713a88c73690d4fb4f2ce7eda9ecd | 8d6b6f32954e1742b1ed15f982e332a03051042d | refs/heads/master | 2021-01-10T16:44:53.426817 | 2015-11-28T21:20:33 | 2015-11-28T21:20:33 | 43,664,922 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | cpp | -listgame2.cpp | /*
TODO: https://open.kattis.com/problems/listgame2
Given an integer, make it the product of K different positive numbers.
Output the max K.
*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
long long n;
vector<int> p;
cin>>n;
if(n%2==0){
int c=0;
while(n%2==0){c++;n/=2;}
p.push_back(c);
}
long long i=3;
while(i*i<=n){
if(n%i==0){
int c=0;
while(n%i==0){c++;n/=i;}
p.push_back(c);
}
i+=2;
}
if(n%i==0){
int c=0;
while(n%i==0){c++;n/=i;}
p.push_back(c);
}
if(n>1) p.push_back(1);
sort(p.begin(),p.end());
return 0;
}
|
dec4c6716c131a83aae8cfbc168fc7518ec026b7 | 26cc5abd76eab50e0a260200b56247cf3f10e8ee | /app/jni/ik_thread.cpp | c972206b86a350a7be2506a97fa44f86ae02116a | [] | no_license | ihjklj/ikc | 8bfd9ee881fb59452c4851967554b9bf419676a4 | 1a4269f14c98786ce87d9e150b05a7077c706bbc | refs/heads/master | 2020-03-08T08:13:31.171749 | 2018-04-04T09:56:31 | 2018-04-04T09:56:31 | 128,016,737 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 803 | cpp | ik_thread.cpp |
#include "ik_thread.h"
extern JavaVM* gJvm;
CThread::CThread(PTHREAD_ROUTINE func, void *lParm) {
mThreadId = 0L;
mThreadFunc = func;
mParm = lParm;
mExit = false;
if (pthread_create(&mThreadId, NULL, runThreadFunc, this) == 0){
pthread_detach(mThreadId);
//LOGD("run thread:%ld.", mThreadId);
}
else {
LOGD("run thread failed!");
}
}
CThread::~CThread() {
//
}
void* CThread::runThreadFunc(void *data) {
JNIEnv* env = NULL;
if (gJvm != NULL)
gJvm->AttachCurrentThread(&env, NULL);
CThread *threadThis = (CThread *)data;
threadThis->mThreadFunc(threadThis->mParm);
threadThis->mExit = true;
if (env == NULL)
gJvm->AttachCurrentThread(&env, NULL);
if (env != NULL)
gJvm->DetachCurrentThread();
pthread_exit(0);
return NULL;
}
|
b26750bfb1d81175034fa60b7fba6d8dd23f0cde | bb9b83b2526d3ff8a932a1992885a3fac7ee064d | /src/modules/osgVolume/generated_code/PropertyAdjustmentCallback.pypp.cpp | e6208e9868d34c4a9ee90d86b8d871cb59bf215c | [] | no_license | JaneliaSciComp/osgpyplusplus | 4ceb65237772fe6686ddc0805b8c77d7b4b61b40 | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | refs/heads/master | 2021-01-10T19:12:31.756663 | 2015-09-09T19:10:16 | 2015-09-09T19:10:16 | 23,578,052 | 20 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 12,688 | cpp | PropertyAdjustmentCallback.pypp.cpp | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "__call_policies.pypp.hpp"
#include "__convenience.pypp.hpp"
#include "wrap_osgvolume.h"
#include "wrap_referenced.h"
#include "propertyadjustmentcallback.pypp.hpp"
namespace bp = boost::python;
struct PropertyAdjustmentCallback_wrapper : osgVolume::PropertyAdjustmentCallback, bp::wrapper< osgVolume::PropertyAdjustmentCallback > {
PropertyAdjustmentCallback_wrapper( )
: osgVolume::PropertyAdjustmentCallback( )
, bp::wrapper< osgVolume::PropertyAdjustmentCallback >(){
// null constructor
}
virtual char const * className( ) const {
if( bp::override func_className = this->get_override( "className" ) )
return func_className( );
else{
return this->osgVolume::PropertyAdjustmentCallback::className( );
}
}
char const * default_className( ) const {
return osgVolume::PropertyAdjustmentCallback::className( );
}
virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const {
if( bp::override func_clone = this->get_override( "clone" ) )
return func_clone( boost::ref(copyop) );
else{
return this->osgVolume::PropertyAdjustmentCallback::clone( boost::ref(copyop) );
}
}
::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const {
return osgVolume::PropertyAdjustmentCallback::clone( boost::ref(copyop) );
}
virtual ::osg::Object * cloneType( ) const {
if( bp::override func_cloneType = this->get_override( "cloneType" ) )
return func_cloneType( );
else{
return this->osgVolume::PropertyAdjustmentCallback::cloneType( );
}
}
::osg::Object * default_cloneType( ) const {
return osgVolume::PropertyAdjustmentCallback::cloneType( );
}
virtual bool handle( ::osgGA::GUIEventAdapter const & ea, ::osgGA::GUIActionAdapter & arg1, ::osg::Object * object, ::osg::NodeVisitor * arg3 ) {
namespace bpl = boost::python;
if( bpl::override func_handle = this->get_override( "handle" ) ){
bpl::object py_result = bpl::call<bpl::object>( func_handle.ptr(), ea, arg1, object, arg3 );
return bpl::extract< bool >( pyplus_conv::get_out_argument( py_result, 0 ) );
}
else{
return osgVolume::PropertyAdjustmentCallback::handle( boost::ref(ea), boost::ref(arg1), boost::python::ptr(object), boost::python::ptr(arg3) );
}
}
static boost::python::object default_handle( ::osgVolume::PropertyAdjustmentCallback & inst, ::osgGA::GUIEventAdapter & ea, ::osgGA::GUIActionAdapter & arg1, ::osg::Object * object, ::osg::NodeVisitor * arg3 ){
bool result;
if( dynamic_cast< PropertyAdjustmentCallback_wrapper * >( boost::addressof( inst ) ) ){
result = inst.::osgVolume::PropertyAdjustmentCallback::handle(ea, arg1, object, arg3);
}
else{
result = inst.handle(ea, arg1, object, arg3);
}
return bp::object( result );
}
virtual bool isSameKindAs( ::osg::Object const * obj ) const {
if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) )
return func_isSameKindAs( boost::python::ptr(obj) );
else{
return this->osgVolume::PropertyAdjustmentCallback::isSameKindAs( boost::python::ptr(obj) );
}
}
bool default_isSameKindAs( ::osg::Object const * obj ) const {
return osgVolume::PropertyAdjustmentCallback::isSameKindAs( boost::python::ptr(obj) );
}
virtual char const * libraryName( ) const {
if( bp::override func_libraryName = this->get_override( "libraryName" ) )
return func_libraryName( );
else{
return this->osgVolume::PropertyAdjustmentCallback::libraryName( );
}
}
char const * default_libraryName( ) const {
return osgVolume::PropertyAdjustmentCallback::libraryName( );
}
virtual void computeDataVariance( ) {
if( bp::override func_computeDataVariance = this->get_override( "computeDataVariance" ) )
func_computeDataVariance( );
else{
this->osg::Object::computeDataVariance( );
}
}
void default_computeDataVariance( ) {
osg::Object::computeDataVariance( );
}
virtual ::osg::Referenced * getUserData( ) {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced * default_getUserData( ) {
return osg::Object::getUserData( );
}
virtual ::osg::Referenced const * getUserData( ) const {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced const * default_getUserData( ) const {
return osg::Object::getUserData( );
}
virtual void resizeGLObjectBuffers( unsigned int arg0 ) {
if( bp::override func_resizeGLObjectBuffers = this->get_override( "resizeGLObjectBuffers" ) )
func_resizeGLObjectBuffers( arg0 );
else{
this->osg::Object::resizeGLObjectBuffers( arg0 );
}
}
void default_resizeGLObjectBuffers( unsigned int arg0 ) {
osg::Object::resizeGLObjectBuffers( arg0 );
}
virtual void setName( ::std::string const & name ) {
if( bp::override func_setName = this->get_override( "setName" ) )
func_setName( name );
else{
this->osg::Object::setName( name );
}
}
void default_setName( ::std::string const & name ) {
osg::Object::setName( name );
}
virtual void setThreadSafeRefUnref( bool threadSafe ) {
if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
func_setThreadSafeRefUnref( threadSafe );
else{
this->osg::Object::setThreadSafeRefUnref( threadSafe );
}
}
void default_setThreadSafeRefUnref( bool threadSafe ) {
osg::Object::setThreadSafeRefUnref( threadSafe );
}
virtual void setUserData( ::osg::Referenced * obj ) {
if( bp::override func_setUserData = this->get_override( "setUserData" ) )
func_setUserData( boost::python::ptr(obj) );
else{
this->osg::Object::setUserData( boost::python::ptr(obj) );
}
}
void default_setUserData( ::osg::Referenced * obj ) {
osg::Object::setUserData( boost::python::ptr(obj) );
}
};
void register_PropertyAdjustmentCallback_class(){
bp::class_< PropertyAdjustmentCallback_wrapper, bp::bases< ::osg::StateSet::Callback >, osg::ref_ptr< PropertyAdjustmentCallback_wrapper >, boost::noncopyable >( "PropertyAdjustmentCallback", bp::init< >() )
.def(
"className"
, (char const * ( ::osgVolume::PropertyAdjustmentCallback::* )( )const)(&::osgVolume::PropertyAdjustmentCallback::className)
, (char const * ( PropertyAdjustmentCallback_wrapper::* )( )const)(&PropertyAdjustmentCallback_wrapper::default_className) )
.def(
"clone"
, (::osg::Object * ( ::osgVolume::PropertyAdjustmentCallback::* )( ::osg::CopyOp const & )const)(&::osgVolume::PropertyAdjustmentCallback::clone)
, (::osg::Object * ( PropertyAdjustmentCallback_wrapper::* )( ::osg::CopyOp const & )const)(&PropertyAdjustmentCallback_wrapper::default_clone)
, ( bp::arg("copyop") )
, bp::return_value_policy< bp::reference_existing_object >() )
.def(
"cloneType"
, (::osg::Object * ( ::osgVolume::PropertyAdjustmentCallback::* )( )const)(&::osgVolume::PropertyAdjustmentCallback::cloneType)
, (::osg::Object * ( PropertyAdjustmentCallback_wrapper::* )( )const)(&PropertyAdjustmentCallback_wrapper::default_cloneType)
, bp::return_value_policy< bp::reference_existing_object >() )
.def(
"getKeyEventActivatesAlphaFuncAdjustment"
, (int ( ::osgVolume::PropertyAdjustmentCallback::* )( )const)( &::osgVolume::PropertyAdjustmentCallback::getKeyEventActivatesAlphaFuncAdjustment ) )
.def(
"getKeyEventActivatesSampleDensityAdjustment"
, (int ( ::osgVolume::PropertyAdjustmentCallback::* )( )const)( &::osgVolume::PropertyAdjustmentCallback::getKeyEventActivatesSampleDensityAdjustment ) )
.def(
"getKeyEventActivatesTransparencyAdjustment"
, (int ( ::osgVolume::PropertyAdjustmentCallback::* )( )const)( &::osgVolume::PropertyAdjustmentCallback::getKeyEventActivatesTransparencyAdjustment ) )
.def(
"getKeyEventCycleBackward"
, (int ( ::osgVolume::PropertyAdjustmentCallback::* )( )const)( &::osgVolume::PropertyAdjustmentCallback::getKeyEventCycleBackward ) )
.def(
"getKeyEventCycleForward"
, (int ( ::osgVolume::PropertyAdjustmentCallback::* )( )const)( &::osgVolume::PropertyAdjustmentCallback::getKeyEventCycleForward ) )
.def(
"handle"
, (boost::python::object (*)( ::osgVolume::PropertyAdjustmentCallback &,::osgGA::GUIEventAdapter &,::osgGA::GUIActionAdapter &,::osg::Object *,::osg::NodeVisitor * ))( &PropertyAdjustmentCallback_wrapper::default_handle )
, ( bp::arg("inst"), bp::arg("ea"), bp::arg("arg1"), bp::arg("object"), bp::arg("arg3") ) )
.def(
"isSameKindAs"
, (bool ( ::osgVolume::PropertyAdjustmentCallback::* )( ::osg::Object const * )const)(&::osgVolume::PropertyAdjustmentCallback::isSameKindAs)
, (bool ( PropertyAdjustmentCallback_wrapper::* )( ::osg::Object const * )const)(&PropertyAdjustmentCallback_wrapper::default_isSameKindAs)
, ( bp::arg("obj") ) )
.def(
"libraryName"
, (char const * ( ::osgVolume::PropertyAdjustmentCallback::* )( )const)(&::osgVolume::PropertyAdjustmentCallback::libraryName)
, (char const * ( PropertyAdjustmentCallback_wrapper::* )( )const)(&PropertyAdjustmentCallback_wrapper::default_libraryName) )
.def(
"setKeyEventActivatesAlphaFuncAdjustment"
, (void ( ::osgVolume::PropertyAdjustmentCallback::* )( int ))( &::osgVolume::PropertyAdjustmentCallback::setKeyEventActivatesAlphaFuncAdjustment )
, ( bp::arg("key") ) )
.def(
"setKeyEventActivatesSampleDensityAdjustment"
, (void ( ::osgVolume::PropertyAdjustmentCallback::* )( int ))( &::osgVolume::PropertyAdjustmentCallback::setKeyEventActivatesSampleDensityAdjustment )
, ( bp::arg("key") ) )
.def(
"setKeyEventActivatesTransparencyAdjustment"
, (void ( ::osgVolume::PropertyAdjustmentCallback::* )( int ))( &::osgVolume::PropertyAdjustmentCallback::setKeyEventActivatesTransparencyAdjustment )
, ( bp::arg("key") ) )
.def(
"setKeyEventCycleBackward"
, (void ( ::osgVolume::PropertyAdjustmentCallback::* )( int ))( &::osgVolume::PropertyAdjustmentCallback::setKeyEventCycleBackward )
, ( bp::arg("key") ) )
.def(
"setKeyEventCycleForward"
, (void ( ::osgVolume::PropertyAdjustmentCallback::* )( int ))( &::osgVolume::PropertyAdjustmentCallback::setKeyEventCycleForward )
, ( bp::arg("key") ) )
.def_readwrite( "_alphaFuncKey", &osgVolume::PropertyAdjustmentCallback::_alphaFuncKey )
.def_readwrite( "_cyleBackwardKey", &osgVolume::PropertyAdjustmentCallback::_cyleBackwardKey )
.def_readwrite( "_cyleForwardKey", &osgVolume::PropertyAdjustmentCallback::_cyleForwardKey )
.def_readwrite( "_sampleDensityKey", &osgVolume::PropertyAdjustmentCallback::_sampleDensityKey )
.def_readwrite( "_transparencyKey", &osgVolume::PropertyAdjustmentCallback::_transparencyKey )
.def_readwrite( "_updateAlphaCutOff", &osgVolume::PropertyAdjustmentCallback::_updateAlphaCutOff )
.def_readwrite( "_updateSampleDensity", &osgVolume::PropertyAdjustmentCallback::_updateSampleDensity )
.def_readwrite( "_updateTransparency", &osgVolume::PropertyAdjustmentCallback::_updateTransparency );
}
|
bd3c0aac94cb063c996a1761e66bbd37dbe7477e | 568d1d0ec9d42a8a68f03418385fb5ac0ab42e10 | /1.9.0简单调整后的最终版本/test-widgt/debug/moc_loginmainwindow.cpp | aafd7018b101b5514a99fab15237c40cff06bbec | [] | no_license | OneForNothing/NIC | 953126588cb492b60049c0f3ab03e57f76cfcb5b | 1cb5d68ebdb7ab40700a78cfb13a8680e00f1a85 | refs/heads/master | 2020-04-27T16:16:08.614522 | 2019-03-13T06:38:19 | 2019-03-13T06:38:19 | 174,479,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,226 | cpp | moc_loginmainwindow.cpp | /****************************************************************************
** Meta object code from reading C++ file 'loginmainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.2.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../loginmainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'loginmainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.2.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_loginMainWindow_t {
QByteArrayData data[10];
char stringdata[161];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
offsetof(qt_meta_stringdata_loginMainWindow_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData) \
)
static const qt_meta_stringdata_loginMainWindow_t qt_meta_stringdata_loginMainWindow = {
{
QT_MOC_LITERAL(0, 0, 15),
QT_MOC_LITERAL(1, 16, 11),
QT_MOC_LITERAL(2, 28, 0),
QT_MOC_LITERAL(3, 29, 21),
QT_MOC_LITERAL(4, 51, 3),
QT_MOC_LITERAL(5, 55, 13),
QT_MOC_LITERAL(6, 69, 24),
QT_MOC_LITERAL(7, 94, 22),
QT_MOC_LITERAL(8, 117, 20),
QT_MOC_LITERAL(9, 138, 21)
},
"loginMainWindow\0deelMessage\0\0"
"QMap<QString,QString>\0msg\0TypeOfMessage\0"
"on_losePwdButton_clicked\0"
"on_enterButton_clicked\0on_regButton_clicked\0"
"on_pushButton_clicked\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_loginMainWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
5, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 2, 39, 2, 0x08,
6, 0, 44, 2, 0x08,
7, 0, 45, 2, 0x08,
8, 0, 46, 2, 0x08,
9, 0, 47, 2, 0x08,
// slots: parameters
QMetaType::Void, 0x80000000 | 3, QMetaType::QString, 4, 5,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void loginMainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
loginMainWindow *_t = static_cast<loginMainWindow *>(_o);
switch (_id) {
case 0: _t->deelMessage((*reinterpret_cast< QMap<QString,QString>(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break;
case 1: _t->on_losePwdButton_clicked(); break;
case 2: _t->on_enterButton_clicked(); break;
case 3: _t->on_regButton_clicked(); break;
case 4: _t->on_pushButton_clicked(); break;
default: ;
}
}
}
const QMetaObject loginMainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_loginMainWindow.data,
qt_meta_data_loginMainWindow, qt_static_metacall, 0, 0}
};
const QMetaObject *loginMainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *loginMainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_loginMainWindow.stringdata))
return static_cast<void*>(const_cast< loginMainWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int loginMainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 5)
qt_static_metacall(this, _c, _id, _a);
_id -= 5;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 5)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 5;
}
return _id;
}
QT_END_MOC_NAMESPACE
|
141318c08864bba801aa5861b699aa0d32c15e95 | 123712e7a0db5383a5e736a3d1435e33fa30080d | /inc/component/com_network.h | e2b852b598d970316f54c5729e82ed45695b54ac | [
"MIT"
] | permissive | lemontreehuang/dios | f66aed3648f80adab8ccc54e6d4935bdb6593fe2 | ce947382bcc8692ea70533d6def112a2838a9d0e | refs/heads/master | 2021-05-30T17:02:23.630692 | 2015-11-17T12:39:09 | 2015-11-17T12:39:09 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,110 | h | com_network.h | #ifndef _____NET_SERVICE_H_________
#define _____NET_SERVICE_H_________
#include "dios/platform.h"
#include "dios_com/dios_com.h"
namespace dios{
namespace com{
class IConnectorSink;
/*
* 由INetworkContext创建产生
*/
class IConnector : public std::enable_shared_from_this<IConnector>
{
public:
typedef std::shared_ptr<IConnector> Ptr;
typedef std::weak_ptr<IConnector> WeakPtr;
virtual ~IConnector() {}
// 基本操作;
virtual bool Send(const void * buffer, unsigned int size) = 0;
virtual void Shutdown(void) = 0;
/*
* 基本网络信息;
*/
virtual std::string local_ip() = 0;
virtual int local_port() = 0;
virtual std::string remote_ip() = 0;
virtual int remote_port() = 0;
};
/*
* 由INetworkContext创建产生
*/
class IServer : public std::enable_shared_from_this<IServer>
{
public:
typedef std::shared_ptr<IServer> Ptr;
virtual ~IServer() {}
/*
* 关闭服务器;
*/
virtual void Shutdown(void) = 0;
/*
* 基本信息;
*/
virtual std::string local_ip() = 0;
virtual int local_port() = 0;
};
class INetworkContext : public ICom
{
public:
typedef std::shared_ptr<INetworkContext> Ptr;
typedef std::weak_ptr<INetworkContext> WeakPtr;
virtual ~INetworkContext(void) {}
virtual bool Initialize(unsigned int recv_size) = 0;
virtual bool Shutdown(void) = 0;
/*
* 服务端监听,有连接进来时调用AcceptCallback
*/
virtual IServer::Ptr Listen(const char * local_ip, int local_port, IConnectorSink* sink) = 0;
/*
* 客户端连接,连接成功时调用AcceptCallback
*/
virtual IConnector::Ptr Connect(const char * remote_ip, int remote_port, IConnectorSink* sink) = 0;
};
// 事件接收器;
class IConnectorSink
{
public:
virtual void OnConnect(const IConnector::Ptr&) = 0;
virtual void OnRecv(const IConnector::Ptr&, const void* buffer, unsigned int size) = 0;
virtual void OnDisconnect(const IConnector::Ptr&) = 0;
virtual IConnectorSink* Clone() = 0;
virtual void Release() = 0;
};
}
}
#endif
|
f3cf5fd09db6d4b8800039e648bd1d51bbcf8302 | 964743cc9072f09d3d60a88ddd90971e48e8a956 | /NewGeneUI/NewGene/Infrastructure/ModelAction/uimodelactionmanager.cpp | 27d9750624781d6366d7554c1e19c27f78afdb5b | [] | no_license | daniel347x/newgene | f6a7abae718bc4b3813c6adf2c2f991dca535954 | dc0b5ddaeea441d905d627a4145d7a3e2eda78b5 | refs/heads/master | 2022-06-27T17:19:42.205690 | 2022-06-21T21:52:07 | 2022-06-21T21:52:07 | 9,526,888 | 0 | 2 | null | 2022-06-21T21:52:08 | 2013-04-18T16:55:22 | C | UTF-8 | C++ | false | false | 462 | cpp | uimodelactionmanager.cpp | #include "uimodelactionmanager.h"
#include "../../NewGeneBackEnd/Utilities/NewGeneException.h"
UIModelActionManager::UIModelActionManager(QObject * parent, UIMessager & messager)
: QObject(parent)
, UIManager(messager)
{
// *************************************************************************
// All Managers are instantiated AFTER the application event loop is running
// *************************************************************************
}
|
803e3c989005cef757e9be2f75e8f05657286a4e | bcf2018acb5848d8beb4863e1247eb96709800ee | /Ladder/Less1300/141A.cpp | 0733c022d22f8df56d92984311520d8b981fe33e | [] | no_license | filipeherculano/codeforces_deception | 71ac34a59599f3db8b927d0c5084896ee61867c0 | 6b331368a918d9cee379664e2b3c00ababa48e7a | refs/heads/master | 2021-01-11T03:35:35.231606 | 2017-02-04T01:55:03 | 2017-02-04T01:55:03 | 68,941,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 576 | cpp | 141A.cpp | #include <bits/stdc++.h>
#define FOR(i, a, n) for(int i = (int)(a); i < (int)(n); ++i)
#define REP(i, n) FOR(i, 0, n)
#define all(a) a.begin(),a.end()
#define pb push_back
typedef unsigned long long llu;
typedef long long ll;
typedef long double ld;
using namespace std;
int main(){
int v[27] = {0};
string f, s, p;
getline(cin, f);
getline(cin, s);
getline(cin, p);
REP(i, f.size()) v[f[i]-'A']++;
REP(i, s.size()) v[s[i]-'A']++;
REP(i, p.size()) v[p[i]-'A']--;
REP(i, 27){
if(v[i] != 0){
cout << "NO\n";
return 0;
}
}
cout << "YES\n";
return 0;
}
|
2c6d1a069bfcb7dfef2850d1980e5c984e21b624 | 63c21d8f615b43889cb7b247a6f4e108bc8c714c | /infra/include/l0-infra/base/HashMap.h | b1b89b680c162fb975332bddedb386929ac3a5c3 | [] | no_license | liulei2015/perfect-cpp | cba79a82c6bc6e6e56d023057fc7ec589b7a0c1f | 5287e4a5d4aa3a4c87668f5f4be1feb610b4acbe | refs/heads/master | 2021-01-01T16:28:10.131718 | 2017-08-06T13:33:16 | 2017-08-06T13:33:16 | 97,839,632 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,104 | h | HashMap.h | #ifndef INCL_USI_H569AC47A_98D9_42AD_B1C8_4EF1EA3DFAD7
#define INCL_USI_H569AC47A_98D9_42AD_B1C8_4EF1EA3DFAD7
#include "l0-infra/base/SequenceAllocator.h"
#include "l0-infra/base/NullPtr.h"
#include "l0-infra/base/Status.h"
#include "l0-infra/base/Assertions.h"
#include "l0-infra/base/AbstractMap.h"
#include <string.h>
template <typename K, typename V, typename HASH_FUN, typename PRED, WORD32 MAX_SIZE>
struct HashMap
{
HashMap()
{
memset(bucketList, 0, sizeof(bucketList));
}
const V* get(const K& key) const
{
Bucket* bucket = __null_ptr__;
bucket = bucketList[getIndex(key)];
for (WORD32 i = 0; (__null_ptr__ != bucket) && (i < MAX_SIZE); i++)
{
if (pred(key, bucket->pair.key))
{
return &(bucket->pair.value);
}
bucket = bucket->nextPair;
}
return __null_ptr__;
}
bool contains(const K& key)
{
Bucket *bucket = __null_ptr__;
bucket = bucketList[getIndex(key)];
for (WORD32 i = 0; (__null_ptr__ != bucket) && (i < MAX_SIZE) ; i++)
{
if (pred(key, bucket->pair.key))
{
return true;
}
bucket = bucket->nextPair;
}
return false;
}
bool empty() const
{
return bucketAllocator.getFreeNum() == MAX_SIZE;
}
Status put(const K& key, const V& value)
{
if(contains(key))
{
V* lastValue = const_cast<V*>(get(key));
*lastValue = value;
return USI_SUCCESS;
}
Bucket* bucket = __null_ptr__;
bucket = bucketAllocator.alloc();
USI_ASSERT_VALID_PTR(bucket);
bucket->fillPair(key, value);
WORD16 index = getIndex(key);
Bucket* head = bucketList[index];
if(head == __null_ptr__)
{
bucketList[index] = bucket;
return USI_SUCCESS;
}
for (WORD32 i = 0; (head->nextPair != __null_ptr__) && (i < MAX_SIZE); i++)
{
head = head->nextPair;
}
head->nextPair = bucket;
return USI_SUCCESS;
}
void remove(const K& key)
{
USI_ASSERT_TRUE_VOID(contains(key));
WORD16 index = getIndex(key);
Bucket* head = bucketList[index];
if (pred(head->pair.key, key))
{
bucketList[index] = head->nextPair;
bucketAllocator.free(head);
head->nextPair = __null_ptr__;
return;
}
Bucket* preCursor = head;
Bucket* cursor = head->nextPair;
for (WORD32 i = 0; ((cursor != __null_ptr__) && !pred(key, cursor->pair.key)) && (i < MAX_SIZE); i++)
{
preCursor = cursor;
cursor = cursor->nextPair;
}
USI_ASSERT_VALID_PTR_VOID(cursor);
if (pred(key, cursor->pair.key))
{
preCursor->nextPair = cursor->nextPair;
bucketAllocator.free(cursor);
cursor->nextPair = __null_ptr__;
}
}
//important, ahead of dcmng removeBy, please think about performance!!!
void removeBy(const V& value)
{
for(WORD32 i = 0; i < MAX_SIZE; i++)
{
Bucket* cursor = bucketList[i];
while(cursor != __null_ptr__)
{
if(cursor->pair.value == value)
{
Bucket* nextCursor = cursor->nextPair;
remove(cursor->pair.key);
cursor = nextCursor;
continue;
}
cursor = cursor->nextPair;
}
}
}
//important, ahead of dcmng removeBy, please think about performance!!!
void removeOtherKeyExcept(const K& key, const V& value)
{
for(WORD32 i = 0; i < MAX_SIZE; i++)
{
Bucket* cursor = bucketList[i];
while(cursor != __null_ptr__)
{
if(cursor->pair.value == value && cursor->pair.key != key)
{
Bucket* nextCursor = cursor->nextPair;
remove(cursor->pair.key);
cursor = nextCursor;
continue;
}
cursor = cursor->nextPair;
}
}
}
//important, ahead of dcmng removeBy, please think about performance!!!
typedef typename AbstractMap<K, V>::ConstMapVisitor ConstMapVisitor;
void visit(ConstMapVisitor& visitor) const
{
for(WORD32 i = 0; i < MAX_SIZE; i++)
{
Bucket* cursor = bucketList[i];
while(cursor != __null_ptr__)
{
visitor.visit(cursor->pair.key, cursor->pair.value);
cursor = cursor->nextPair;
}
}
}
void dump()
{
printf("\n-----------------------------------------\n");
for(WORD32 i = 0; i < MAX_SIZE; i++)
{
Bucket* cursor = bucketList[i];
printf("bucketList[%lu]: ", i);
while(cursor != __null_ptr__)
{
cursor->dump();
cursor = cursor->nextPair;
}
printf("\n");
}
}
private:
struct HashPair
{
K key;
V value;
};
struct Bucket{
HashPair pair;
Bucket* nextPair;
Bucket() : nextPair(__null_ptr__)
{
}
inline void fillPair(const K& key, const V& value)
{
pair.key = key;
pair.value = value;
}
void dump() const
{
pair.key.dump();
printf(" | %lu ]", (WORD32)pair.value);
const char* format = (nextPair == 0 ? "" : " -> ");
printf(format, nextPair);
}
};
private:
WORD16 getIndex(const K &key) const
{
return hashFunc(key) % MAX_SIZE;
}
private:
Bucket* bucketList[MAX_SIZE];
HASH_FUN hashFunc;
PRED pred;
SequenceAllocator<Bucket, MAX_SIZE> bucketAllocator;
};
//////////////////////////////////////////////////////////////////////////
#define DEF_UE_ID_HASH_MAP(p_name, p_key, p_value, p_hash_func, p_hash_pred, p_size) \
struct p_name \
{ \
typedef HashMap<p_key, p_value, p_hash_func, p_hash_pred, p_size> ThisMap; \
static ThisMap& getInstance() \
{ \
static ThisMap map; \
return map; \
} \
};
#define __DEF_UE_ID_HASH_MAP(p_name, p_key, p_hash_func, p_hash_pred, p_size) \
DEF_UE_ID_HASH_MAP(p_name, p_key, WORD16, p_hash_func, p_hash_pred, p_size)
#endif
|
85a787a7c60fbcd691955801e21d39a427a0ef59 | 9c942fe75218d6018f8390c926f0b693e36ceaad | /cpp/0820_ShortEncodingofWords.cpp | 733bc6d5159befb7aeebafcf6815f1372378fa3c | [] | no_license | joy-yjl/leetcode_yjl | 5878113ae6cb81d1f735fa812b13e7f7b31883f6 | 1def24ac4ef723ecfd1e4dc50ced677809bc942c | refs/heads/master | 2022-07-31T04:42:45.845904 | 2022-07-20T03:35:20 | 2022-07-20T03:35:20 | 206,940,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | cpp | 0820_ShortEncodingofWords.cpp | class Solution {
public:
static bool compare (string& first, string& second) {
return first.size() > second.size();
}
int minimumLengthEncoding(vector<string>& words) {
unordered_map<string, int> mp;
int ans = 0;
sort(words.begin(), words.end(), compare);
for(int i=0; i<words.size(); i++){
mp[words[i]]++;
}
for(int i=0; i<words.size(); i++){
int k = words[i].size();
if(mp[words[i]] >0){
ans += (k+1);
}
for(int j=k-1; j>=0; j--){
string s = words[i].substr(j, k-j);
mp[s] = 0;
}
}
return ans;
}
};
|
48b7ec230d9a9cbb3f61ecb960b36891dde4079a | 9ea575abc4b9641d0deb5285d4e6cb2396e3ac27 | /CodeForces/0732B_Cormen.cpp | c9251767d8ee1c614933d5e25f907ab99234b7c2 | [] | no_license | Ming-J/LeetCode | 65e11cdeb1530ae163fa1fc9851acbcee7f05744 | a69f56a1e92a4cb32a1a16bc3201027910f1a877 | refs/heads/master | 2022-05-08T00:37:01.830067 | 2022-03-06T15:40:43 | 2022-03-06T15:40:43 | 26,152,966 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 700 | cpp | 0732B_Cormen.cpp | #include <iostream>
#include <vector>
using namespace std;
vector<int> calWalk(vector<int> &aff, int walkNeed, int &newWalks){
vector<int> walks(aff.size(),0);
walks[0] = aff[0];
for( int i = 1; i < aff.size(); i++){
int affSum = aff[i] + walks[i-1];
int additional = ( walkNeed - affSum > 0 )? walkNeed - affSum : 0;
newWalks += additional;
walks[i] = aff[i] + additional;
}
return walks;
}
int main(){
int days = 4, walksNeed = 6;
cin >> days >> walksNeed;
vector<int> aff(days,0);
for(int i = 0; i < days; i++){
cin >> aff[i];
}
int sum = 0;
vector<int> dp = calWalk(aff,walksNeed,sum);
cout<<sum<<endl;
for( int i : dp ){
cout<<i<<' ';
}
}
|
fc8c04f65b2323b2bba517fb00c2291bc6a1e04b | 1a525bf9ed3313c8a19c645cfa6cd52ff6d75960 | /get_owners_name.cpp | 254d42829d965607c37c0a2fc665a6eb3d9e1f58 | [] | no_license | chowdhuryRakibul/randomFlatAllotment | acd221e80ce5fdf7be358ec39cec3ff241562946 | a46010563878e8ccd8195210e54457fe3c811283 | refs/heads/main | 2023-04-06T18:46:51.648130 | 2021-04-06T03:20:40 | 2021-04-06T03:20:40 | 358,781,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,416 | cpp | get_owners_name.cpp | #include "get_owners_name.h"
#include "ui_get_owners_name.h"
#include "mainwindow.h"
#include "QFileDialog"
#include "QDebug"
#include "QFile"
#include "QMessageBox"
#include "QTextStream"
#include "main.h"
#include "QRandomGenerator"
#include "QStringList"
extern allInfo myAllInfo;
GET_OWNERS_NAME::GET_OWNERS_NAME(QWidget *parent) :
QDialog(parent),
ui(new Ui::GET_OWNERS_NAME)
{
ui->setupUi(this);
QWidget::showMaximized();
}
GET_OWNERS_NAME::~GET_OWNERS_NAME()
{
delete ui;
}
void GET_OWNERS_NAME::on_pushButton_5_clicked()
{
close();
}
void GET_OWNERS_NAME::on_pushButton_clicked()
{
myAllInfo.ownersName.clear();
ui->textBrowser->clear();
QString fileName;
QMessageBox myMessageBox;
fileName = QFileDialog::getOpenFileName(this,
tr("Open Owners' Name"), "", tr("txt Files (*.txt)"));
if(fileName.size()<=0)
{
return;
}
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly))
{
myMessageBox.setText("Erro Opeing File");
}
QTextStream in(&file);
QStringList actualList;
while(!in.atEnd())
{
QString line = in.readLine();
actualList<<line;
}
file.close();
actualList.sort();
for(int j=0;j<actualList.length();j++)
{
ui->textBrowser->append(actualList.at(j));
}
if(actualList.length()<(myAllInfo.numberOfFloors*myAllInfo.numberOfUnitPerFloor))
{
QMessageBox::warning(this, tr("Pacific Appartments"),
tr("There is less owners than number of flats/garage.\n"
"Please try again"),
QMessageBox::Ok);
return;
}
QList<int> a;
int num;
QString separator(" : ");
while(a.size() != actualList.size())
{
num = QRandomGenerator::global()->generate()%actualList.size();
if(!a.contains(num))
{
a.append(num);
myAllInfo.ownersName<<actualList.at(num);
}
}
for(int i=0;i<myAllInfo.randomizeList.size();i++)
{
myAllInfo.finalList<<myAllInfo.randomizeList.at(i) + separator + myAllInfo.ownersName.at(i);
}
myAllInfo.finalList.sort();
qDebug()<<myAllInfo.finalList;
}
void GET_OWNERS_NAME::on_pushButton_4_clicked()
{
myResultWindow = new resultWindow(this);
this->hide();
myResultWindow->show();
}
|
3c0a3f3a8201bda52efbde355ee98afa0dcc0a9b | e018d8a71360d3a05cba3742b0f21ada405de898 | /VS_UI/src/VS_UI_widget.cpp | 6fb3d3dff590eb975e28cef93eda189da2b2a668 | [] | no_license | opendarkeden/client | 33f2c7e74628a793087a08307e50161ade6f4a51 | 321b680fad81d52baf65ea7eb3beeb91176c15f4 | refs/heads/master | 2022-11-28T08:41:15.782324 | 2022-11-26T13:21:22 | 2022-11-26T13:21:22 | 42,562,963 | 24 | 18 | null | 2022-11-26T13:21:23 | 2015-09-16T03:43:01 | C++ | UHC | C++ | false | false | 4,101 | cpp | VS_UI_widget.cpp | #include "client_PCH.h"
#include <assert.h>
#include "VS_UI_widget.h"
#include "VS_UI_filepath.h"
#ifndef _LIB
Button * gpC_press_button;
#endif
//bool ButtonGroup::press;
//----------------------------------------------------------------------------
// Operations
//----------------------------------------------------------------------------
/*
//-----------------------------------------------------------------------------
// SetPosition
//
//
//-----------------------------------------------------------------------------
void C_VS_UI_BUTTON::SetPosition(int x, int y)
{
m_pC_ani_button->SetPlayPosition(x, y);
}
//-----------------------------------------------------------------------------
// C_VS_UI_BUTTON
//
// set_end는 ani button을 focus rect의 끝 정렬여부를 결정한다.
//-----------------------------------------------------------------------------
C_VS_UI_BUTTON::C_VS_UI_BUTTON(int _x, int _y, int _w, int _h, id_t id, Exec * pC_exec_handler, bool set_end, bool image_show) :
EventButton(_x, _y, _w, _h, id, pC_exec_handler)
{
assert(gpC_global_resource);
assert(gpC_global_resource->m_pC_ao_ani_button);
m_pC_ani_button = new C_ANIMATION(gpC_global_resource->m_pC_ao_ani_button);
m_pC_ani_button->SetSpeed(SPEED_MILLISEC);
int px, py;
if (set_end)
{
px = x+w-gpC_global_resource->m_pC_ao_ani_button->GetWidth(0);
py = y;
}
else
{
px = x;
py = y;
}
m_pC_ani_button->SetPlayPosition(px, py);
m_bl_image_show = image_show;
}
//-----------------------------------------------------------------------------
// ~C_VS_UI_BUTTON
//
//
//-----------------------------------------------------------------------------
C_VS_UI_BUTTON::~C_VS_UI_BUTTON()
{
DeleteNew(m_pC_ani_button);
}
//-----------------------------------------------------------------------------
// Refresh
//
//
//-----------------------------------------------------------------------------
void C_VS_UI_BUTTON::Refresh()
{
InitState();
m_pC_ani_button->Refresh();
}
//-----------------------------------------------------------------------------
// Show
//
// Button을 보인다.
//-----------------------------------------------------------------------------
void C_VS_UI_BUTTON::Show()
{
if (m_bl_image_show)
m_pC_ani_button->Show();
}
//-----------------------------------------------------------------------------
// EventFocusOn
//
//
//-----------------------------------------------------------------------------
void C_VS_UI_BUTTON::EventFocusOn()
{
// animation play
switch (m_pC_ani_button->GetAnimationState())
{
case C_ANIMATION::PLAY_BACK:
m_pC_ani_button->SetNextPlayOrder(C_ANIMATION::PLAY);
break;
case C_ANIMATION::STOP:
m_pC_ani_button->Play();
break;
case C_ANIMATION::PLAY:
m_pC_ani_button->SetNextPlayOrder(C_ANIMATION::STOP);
break;
}
}
//-----------------------------------------------------------------------------
// EventFocusOff
//
//
//-----------------------------------------------------------------------------
void C_VS_UI_BUTTON::EventFocusOff()
{
// animation play back
switch (m_pC_ani_button->GetAnimationState())
{
case C_ANIMATION::PLAY:
m_pC_ani_button->SetNextPlayOrder(C_ANIMATION::PLAY_BACK);
break;
case C_ANIMATION::STOP:
m_pC_ani_button->PlayBack();
break;
case C_ANIMATION::PLAY_BACK:
m_pC_ani_button->SetNextPlayOrder(C_ANIMATION::STOP);
break;
}
}
//-----------------------------------------------------------------------------
// EventPressDown
//
//
//-----------------------------------------------------------------------------
void C_VS_UI_BUTTON::EventPressDown()
{
// m_pC_ani_button->SetPlayPosition(m_x+2, m_y+2);
}
//-----------------------------------------------------------------------------
// UpAction
//
//
//-----------------------------------------------------------------------------
void C_VS_UI_BUTTON::EventPressUp()
{
// m_pC_ani_button->SetPlayPosition(m_x, m_y);
}*/ |
06f073302c2b9dd31efdfc942b22ebec1915b801 | 2ef6a773dd5288e6526b70e484fb0ec0104529f4 | /poj.org/2499/2444004_RE.cc | eb608d21218df77bf8699cca8747fc9e98352272 | [] | no_license | thebeet/online_judge_solution | f09426be6b28f157b1e5fd796c2eef99fb9978d8 | 7e8c25ff2e1f42cc9835e9cc7e25869a9dbbc0a1 | refs/heads/master | 2023-08-31T15:19:26.619898 | 2023-08-28T10:51:24 | 2023-08-28T10:51:24 | 60,448,261 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 468 | cc | 2444004_RE.cc | #include <stdio.h>
void calc(int a, int b, int &l, int &r)
{
if (a == 1)
{
r = b - 1;
return;
}
if (b == 1)
{
l = a - 1;
return;
}
if (a > b)
{
calc(a - b, b, l, r);
++l;
}
else
{
calc(a, b - a, l, r);
++r;
}
}
int main()
{
int ti, tn;
scanf("%d", &tn);
for (ti = 1; ti <= tn; ++ti)
{
int n, m;
int l, r;
l = 0; r = 0;
scanf("%d%d", &n, &m);
calc(n, m, l, r);
printf("Scenario #%d:\n%d %d\n\n", ti, l, r);
}
return 0;
}
|
c927a12321216e7d5370ee3f8c1e1d1cefbbd274 | f79e5d1d3f86469d8b981126c393cd4a4ec87f71 | /src/images/utils/Pixel.cpp | 7390c25bc091a890ad211f9d73d7e899c6533fde | [] | no_license | pitekantropus/images | f3341e0289f8f06ded1cc0465d5c027425dd6ecb | d974ff96288003d091ac5e4f0cea237c89f48146 | refs/heads/master | 2020-06-27T05:04:29.073451 | 2019-08-18T16:10:11 | 2019-08-18T16:10:11 | 199,851,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 969 | cpp | Pixel.cpp | #include "Pixel.hpp"
#include <sstream>
#include <iomanip>
#include <iostream>
std::string Pixel::toString() const
{
std::stringstream stream;
stream << std::setw(3) << (unsigned)red << " "
<< std::setw(3) << (unsigned)green << " "
<< std::setw(3) << (unsigned)blue;
return stream.str();
}
Pixel Pixel::operator*(int d) const
{
Pixel pixel = *this;
pixel.red *= d;
pixel.green *= d;
pixel.blue *= d;
return pixel;
}
Pixel Pixel::operator/(int d) const
{
Pixel pixel = *this;
pixel.red /= d;
pixel.green /= d;
pixel.blue /= d;
return pixel;
}
Pixel Pixel::operator+(const Pixel &rhs)
{
Pixel pixel = *this;
pixel.red += rhs.red;
pixel.green += rhs.green;
pixel.blue += rhs.blue;
return pixel;
}
bool Pixel::operator==(Pixel rhs) const
{
Pixel pixel = std::move(rhs);
return red == pixel.red &&
green == pixel.green &&
blue == pixel.blue;
}
|
a721ddb7e7a4e2b90e8165e8883b973736753f54 | 3a7671cac5e58e6eba34c41367870466c162f815 | /sketches/Lab_5_9_atividade_1/Lab_5_9_atividade_1.ino | fac733e7087c18c11bc6888a7c29aa19a74535e8 | [] | no_license | oturing/arduinando | df2fe77ada142086dd13a1aed74d3e6477a8ddc0 | ca7768c6a304c528ea9063ffef23037a0077226d | refs/heads/master | 2020-05-18T05:30:23.593719 | 2013-09-14T11:22:54 | 2013-09-14T11:22:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 247 | ino | Lab_5_9_atividade_1.ino |
const int led = 13;
const int botao = 2;
int estadoBotao;
void setup() {
pinMode(led, OUTPUT);
pinMode(botao, INPUT);
}
void loop() {
luz = analogRead(LDR);
Serial.print("Luz: ");
Serial.println(luz);
delay(500);
}
|
c536a1a3e768e45277212103f67fc1da90b78918 | a56252fda5c9e42eff04792c6e16e413ad51ba1a | /resources/home/dnanexus/root/include/TPavesText.h | 9639164c7d822d425e7d1cb2942bc1afe637a9a6 | [
"LGPL-2.1-or-later",
"LGPL-2.1-only",
"Apache-2.0"
] | permissive | edawson/parliament2 | 4231e692565dbecf99d09148e75c00750e6797c4 | 2632aa3484ef64c9539c4885026b705b737f6d1e | refs/heads/master | 2021-06-21T23:13:29.482239 | 2020-12-07T21:10:08 | 2020-12-07T21:10:08 | 150,246,745 | 0 | 0 | Apache-2.0 | 2019-09-11T03:22:55 | 2018-09-25T10:21:03 | Python | UTF-8 | C++ | false | false | 1,322 | h | TPavesText.h | // @(#)root/graf:$Id$
// Author: Rene Brun 19/11/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TPavesText
#define ROOT_TPavesText
#include "TPaveText.h"
class TPavesText : public TPaveText {
protected:
Int_t fNpaves; ///< Number of stacked paves
public:
TPavesText();
TPavesText(Double_t x1, Double_t y1,Double_t x2 ,Double_t y2, Int_t npaves=5, Option_t *option="br");
TPavesText(const TPavesText &pavestext);
virtual ~TPavesText();
virtual void Draw(Option_t *option="");
virtual Int_t GetNpaves() {return fNpaves;}
virtual void Paint(Option_t *option="");
virtual void SavePrimitive(std::ostream &out, Option_t *option = "");
virtual void SetNpaves(Int_t npaves=5) {fNpaves=npaves;} // *MENU*
ClassDef(TPavesText,1) //Stacked Paves with text strings
};
#endif
|
031f02b73286104f841cc17770dddd203ddf6bc0 | 76ef8ea5f82410db62b2a0336a4727e11e8d0a84 | /PTIME.cpp | b82f2bdbce57a62aac18cf37d6b999ecd22ab313 | [] | no_license | akulagrawal/Competitive-Coding | 3ece603cb4baeccf3215674d20ff6775ca3e960c | 74885d6dbae3b21fd673d4fdb0497c233bf0c179 | refs/heads/master | 2022-11-11T14:12:06.942130 | 2020-07-07T18:59:20 | 2020-07-07T18:59:20 | 277,892,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 648 | cpp | PTIME.cpp | #include<bits/stdc++.h>
using namespace std;
int a[10004];
vector<int> prime;
int main()
{
int n,p,t,sum,i,j;
scanf("%d",&n);
for(i=2;i*i<=n;i++)
{
if(!a[i])
{
for(j=2*i;j<=n;j+=i)
a[j]=1;
}
}
for(i=2;i<=n;i++)
{
if(!a[i])
prime.push_back(i);
}
for(int i=0;i<prime.size();i++)
{
if(i)
printf(" * ");
sum=0;
p=prime[i];
t=log(n)/log(p);
for(int j=1;j<=t;j++)
sum+=n/pow(p,j);
printf("%d^%d",p,sum);
}
return 0;
}
|
a7e12c3ca004339a1108c9092fcae7473d3fdc22 | d6853d7ae8361e4d7b5b3127044d4d4e2755e8a6 | /img-to-pdf/mainwindow.cpp | f8cc8396cd4707f47cfec3bc6a94a31c6ddb469d | [] | no_license | Mopsik62/img-to-pdf | 7841b13b3d4fd3098bbaba9d9acbeddb547b7227 | 053feac70e25686bcfe945ab549d0cf01500c383 | refs/heads/main | 2023-01-23T16:14:44.160550 | 2020-11-24T16:29:59 | 2020-11-24T16:29:59 | 315,700,833 | 2 | 0 | null | 2020-11-24T17:09:42 | 2020-11-24T17:09:42 | null | UTF-8 | C++ | false | false | 2,255 | cpp | mainwindow.cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->dateEdit->setDate(QDate::currentDate());
QFile f("dir.txt");
if(f.open(QIODevice::ReadOnly))
str = f.readAll();
QFile f1("class.txt");
if(f1.open(QIODevice::ReadOnly))
ui->classText->setText(f1.readAll());
QFile f2("name.txt");
if(f2.open(QIODevice::ReadOnly))
ui->nameText->setText(f2.readAll());
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_dirButton_clicked()
{
QString str1 = QFileDialog::getExistingDirectory(0, "Directory Dialog", "/home/dmitriy");
qDebug() << str1;
QFile f("dir.txt");
if(str1 != "" && f.open(QIODevice::WriteOnly | QIODevice::Truncate))
{
str = str1;
QTextStream out(&f);
out << str;
}
}
void MainWindow::on_startButton_clicked()
{
QFile f2("class.txt");
if(f2.open(QIODevice::ReadWrite | QIODevice::Truncate))
{
QTextStream out(&f2);
out << ui->classText->toPlainText();
}
QFile f1("name.txt");
if(f1.open(QIODevice::ReadWrite | QIODevice::Truncate))
{
QTextStream out(&f1);
out << ui->nameText->toPlainText();
}
QString filename = ui->classText->toPlainText()+"_"+ui->nameText->toPlainText()+"_"+ui->subjBox->currentText()+'_'+ui->dateEdit->date().toString("dd.MM.yyyy")+".pdf";
qDebug() << filename << str;
QPdfWriter pdfWriter(str +'/' + filename);
pdfWriter.setPageSize(QPageSize(QPageSize::A4));
QPainter painter(&pdfWriter);
QDirIterator it(str, QDir::NoFilter);
while (it.hasNext())
{
QFile f(it.next());
if(f.open(QIODevice::ReadOnly))
{
if(imgFormats.indexOf(f.fileName().mid(f.fileName().size() - 3, 3)) != -1
|| imgFormats.indexOf(f.fileName().mid(f.fileName().size() - 4, 4)) != -1)
{
painter.drawImage(QRect(0,0,pdfWriter.logicalDpiX()*8,pdfWriter.logicalDpiY()*11.5), QImage(f.fileName()));
if(it.hasNext())
pdfWriter.newPage();
}
}
}
ui->statusbar->showMessage("Finished");
}
|
b72ebc2cb23700d75b4c678af301d6a69cfa3013 | 51247d7a36526e81d720727d0328ceab2fc4e077 | /RedFogMagic/RedFogMagic/FunctionManager.hpp | c3175a5e5041e9f240d4e9fbb97ddcd50a89fd86 | [] | no_license | RedFog/RedFogMagic | c6b9ca0380c3a5de0389c7c8c74035a1e07ee568 | 7ce40bb4c8ffda7a1345eb52e8b6897ae4628fdf | refs/heads/master | 2021-03-12T20:38:29.546056 | 2014-10-22T13:09:40 | 2014-10-22T13:09:40 | 25,562,253 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 9,021 | hpp | FunctionManager.hpp | #pragma once
#include "Type.hpp"
#include <tuple>
#ifndef normax
#define normax(a,b) (((a)>(b)) ? (a) : (b))
#define normin(a,b) (((a)<(b)) ? (a) : (b))
#endif
namespace Types{
//wrapper
template<typename T>class ObjectWrapper{
T item;
public:
ObjectWrapper(T item) :item(item){};
ObjectWrapper& operator=(T item){
this->item = item;
return *this;
};
operator T()const{
return item;
};
};
template<typename T>class ObjectWrapper<T&&>;
template<typename T>ObjectWrapper<T> wrapper(T item){
return ObjectWrapper<T>(item);
};
//占位符
template<size_t n>struct Args{
static const size_t id = n;
};
//函数式占位符
template<size_t n, typename Func, typename Array>struct FuncArgs;
template<size_t n, typename Func, typename... Args>
struct FuncArgs<n, Func, TypeArray<Args...>>{
Func fun;
FuncArgs(Func const& fun) :fun(fun){};
typedef typename GetFuncInfo<Func>::Ret Ret;
Ret operator()(Args... args)const{
return fun(args...);
};
};
//从参数包内分离第N个参数
template<size_t n>struct ArgsDetacher{
template<typename Head, typename... Args>
static typename SelectTypeInGroup<n, Head, Args...>::Result call
(Head, Args &&... args){
return ArgsDetacher<n - 1>::call(std::forward<Args&&>(args)...);
};
};
template<>struct ArgsDetacher<0>{
template<typename Head>static Head call(Head&& head, ...){
return std::forward<Head&&>(head);
};
};
//特殊tuple
template<typename... Args>std::tuple<ObjectWrapper<Args>...>
make_cache_tuple(Args &&... args){
return std::make_tuple(wrapper<Args>(args)...);
};
template<size_t n, typename... Args>struct PMPArgsHelper{
static const bool check = n < sizeof...(Args);
template<bool check>struct Helper{
typedef typename SelectTypeInGroup<n, Args...>::Result Result;
static Result call(std::tuple<Args...> const& tuple){
return std::get<n>(tuple);
};
};
struct A{
template<typename... W>
A operator()(W...){ return *this; };
};
template<>struct Helper<false>{
typedef A Result;
static Result call(std::tuple<Args...> const& tuple){
return A();
};
};
typedef typename Helper<check>::Result Result;
static Result call(std::tuple<Args...> const& tuple){
return Helper<check>::call(tuple);
};
};
template<size_t n, typename... Args>struct PMPArgsHelper2{
static const bool check = n < sizeof...(Args);
template<bool check>struct Helper{
typedef typename SelectTypeInGroup<n, Args...>::Result Result;
static Result call(Args... tuple){
return ArgsDetacher<n>::call(tuple...);
};
};
struct A{
template<typename... W>
A operator()(W...){ return *this; };
};
template<>struct Helper<false>{
typedef A Result;
static Result call(Args&&... tuple){
return A();
};
};
typedef typename Helper<check>::Result Result;
static Result call(Args... tuple){
return Helper<check>::call(tuple...);
};
};
//tuple里分离出特定参数,位置不存在返回void*(0)
template<size_t n, typename... Args>
typename PMPArgsHelper<n, Args...>::Result
unpack_args(std::tuple<Args...> const& tuple){
return PMPArgsHelper<n, Args...>::call(tuple);
};
//tuple展开成参数~Helper
template<typename Func, typename... Args>
struct TransponderHelper{
typedef typename GetFuncInfo<Func>::Ret Ret;
static Ret unpack(Func const& fun, Args... args, ...){
return fun(args...);
};
static Ret call(Func const& fun, std::tuple<Args...> const& tuple){
#define M(n, data) ,unpack_args<n>(tuple)
return unpack(unpack_args<0>(tuple)
NOB_REPEAT(256,M,~)
);
#undef M
};
};
//tuple展开成参数
template<typename Func, typename... Args>
typename GetFuncInfo<Func>::Ret
transponder(Func const& fun, std::tuple<Args...> const& tuple){
return TransponderHelper<Func, Args...>::call(fun, tuple);
};
//临时lambda
template<typename Ret, typename Args>
struct ArgsCatcher{
ObjectWrapper<Args> item;
ArgsCatcher(Args a) :item(a){};
template<typename... W>
Ret operator()(W &&... args)const{
return item;
};
};
template<typename Ret, size_t n>
struct ArgsCatcher<Ret, Args<n>>{
ArgsCatcher(...) {};
template<typename... W>
Ret operator()(W &&... args)const{
return ArgsDetacher<n - 1>::call(std::forward<W&&>(args)...);
};
};
template<typename Ret, size_t m, typename Func, typename... Array>
struct ArgsCatcher<Ret, FuncArgs<m, Func, TypeArray<Array...>>>{
Func fun;
ArgsCatcher(FuncArgs<m, Func, TypeArray<Array...>> const& w)
:fun(w.fun){};
Ret unpack(Array... arr, ...)const{
return fun(arr...);
};
template<typename... W>
Ret operator()(W &&... args)const{
#define M(n, data) ,(PMPArgsHelper2<m - 1 + n, W...>::call(std::forward<W&&>(args)...))
return unpack(PMPArgsHelper2<m - 1, W...>::call(std::forward<W&&>(args)...)
NOB_REPEAT(256,M,~)
);
#undef M
};
};
//形成参数列表
template<typename, typename>struct ParamListMaker;
template<typename... Args, typename... Param>
struct ParamListMaker<TypeArray<Args...>, TypeArray<Param...>>{
template<size_t n, typename S>struct Sign{
typedef S Type;
static const size_t result = n;
};
template<size_t n, typename T>
struct Enumerator{
typedef Sign<99999, void> Result;
};
template<size_t n, size_t m>
struct Enumerator<n, Types::Args<m>>{
typedef Sign<m, typename SelectTypeInGroup<n, Args...>::Result> Result;
};
template<size_t n, size_t m, typename Func, typename... Arr>
struct Enumerator<n, FuncArgs<m, Func, TypeArray<Arr...>>>{
template<typename Array, size_t w>struct Helper{
typedef typename Array::template shift<Sign<w - 1 + m,
typename SelectTypeInGroup<w - 1, Arr...>::Result>>::Result NewArray;
typedef typename Helper<NewArray, w - 1>::Result Result;
};
template<typename Array>struct Helper<Array, 0>{
typedef Array Result;
};
static const size_t size = sizeof...(Arr);
typedef typename Helper<TypeArray<>, size>::Result Result;
};
typedef typename ArrayMapWithIndex<TypeArray<Param...>, Enumerator>
::Result XOnce;
typedef typename ArrayFlatten<XOnce>::Result Once;
template<typename T>struct Deleter{
static const bool result = T::result == 99999;
};
typedef typename ArrayDeleteIf<Once, Deleter>::Result Twice;
template<typename v1, typename v2>struct Sorter{
static const bool result = (v1::result < v2::result);
};
typedef typename ArraySort<Twice, Sorter>::Result Third;
template<typename v1, typename v2>struct Uniquer{
static const bool result = (v1::result == v2::result);
};
typedef typename ArrayUniqueIf<Third, Uniquer>::Result Fourth;
template<typename T>struct Unpacker{
typedef typename T::Type Result;
};
typedef typename ArrayMap<Fourth, Unpacker>::Result Result;
};
//Bind类
template<typename Func, typename Function, typename Tuple>
class BindFunction;
template<typename Func, typename Ret, typename... XArgs, typename Tuple>
class BindFunction<Func, Ret(XArgs...), Tuple>{
Func fun;
Tuple tuple;
template<typename ArgsList>struct Helper;
template<typename... ArgsList>struct Helper<TypeArray<ArgsList...>>{
static Ret unpack(Func const& fun, ArgsList... args, ...){
return fun(args...);
};
};
Ret call(XArgs... args)const{
#define M(n, data) ,(unpack_args<n>(tuple))(args...)
return Helper<typename GetFuncInfo<Func>::Args>::unpack
(fun, (unpack_args<0>(tuple))(args...)
NOB_REPEAT(256,M,~)
);
#undef M
};
public:
BindFunction(Func const& fun, Tuple const& tuple) :fun(fun), tuple(tuple){};
Ret operator()(XArgs &&... args)const{
return call(args...);
};
};
//bind函数~helper
template<typename List, typename Ret, typename FuncArgs, typename Func,
typename... Params>struct BindHelper;
template<typename... List, typename Ret, typename... FuncArgs, typename Func,
typename... Params>struct BindHelper<TypeArray<List...>, Ret,
TypeArray<FuncArgs...>, Func, Params...>{
typedef std::tuple<ArgsCatcher<FuncArgs, Params>...> Tuple;
typedef BindFunction<Func, Ret(List...), Tuple> Result;
static Result call(Func const& fun, Params &&... param){
auto a = std::make_tuple(ArgsCatcher<FuncArgs, Params>(param)...);
return Result(fun, a);
};
};
//函数转化为占位符
template<size_t n, typename Func>
FuncArgs<n, Func, typename GetFuncInfo<Func>::Args> func(Func const& fun){
return FuncArgs<n, Func, typename GetFuncInfo<Func>::Args>(fun);
};
//bind函数
template<typename Func, typename... Params>
auto bind(Func const& fun, Params &&... param)
->typename BindHelper<typename ParamListMaker<typename GetFuncInfo<Func>::Args,
TypeArray<Params...>>::Result, typename GetFuncInfo<Func>::Ret,
typename GetFuncInfo<Func>::Args, Func, Params...>::Result{
return BindHelper<typename ParamListMaker<typename GetFuncInfo<Func>::Args,
TypeArray<Params...>>::Result, typename GetFuncInfo<Func>::Ret, typename
GetFuncInfo<Func>::Args, Func, Params...>::call
(fun, std::forward<Params&&>(param)...);
};
}; |
d89e28465d97b20f6ee01f9a443866f75dbd50ae | 7dc9aa54cc9b5b9cb63ebb6b26d7e1ad380ed7cd | /SlatebackAppCLI/src/Command.h | 0c8e8eabcca96ec1a2c909fb6701459dbb9952fb | [
"MIT"
] | permissive | filmbrood/Slateback | 7703131cf515e4d93becdc792adbb5469d17b879 | b512df3b3f13ba152bcf0801c2ad36676d57d2e2 | refs/heads/master | 2023-09-02T06:53:46.206035 | 2021-09-18T02:56:18 | 2021-09-18T02:56:18 | 296,993,356 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 673 | h | Command.h | #pragma once
#include <string>
// Abstract class to be inherited by commands for CommandList. Must define OnInit() and OnUpdate() in children.
class Command
{
public:
virtual void OnInit() = 0;
virtual void OnUpdate() = 0;
virtual void SetInput(std::string input); // Sets m_Input string.
virtual void SetDesc(std::string desc); // Sets m_Desc string
virtual std::string GetInput(); // Returns m_Input string
virtual std::string GetDesc(); // Returns m_Desc string
private:
std::string m_Input; // What string the user must enter for this command to execute.
std::string m_Desc; // Description that will show alongside command when 'help' command is inputted.
}; |
6074d3626da8162a0e05185a4d77ab5f7d202636 | 89abf316efbaab7a06d5dd3560dae5751c281a1a | /Week_04/322. 零钱兑换.cpp | 3f8279d592523922104105a4b4ed04692c5675c8 | [] | no_license | runningRun/algorithm012 | 4ed8889b8a157d947a36e4ea92bb73893dc2bc0f | c1f44d599db2bf38bda78bf8c132abfecd119081 | refs/heads/master | 2022-12-17T02:58:11.370961 | 2020-09-20T14:25:11 | 2020-09-20T14:25:11 | 279,012,468 | 0 | 0 | null | 2020-07-12T07:15:07 | 2020-07-12T07:15:06 | null | UTF-8 | C++ | false | false | 5,466 | cpp | 322. 零钱兑换.cpp | class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
// [] 1 返回 -1
// [] 0 返回 0
// [1] 0 返回 0
if (0 == amount )
return 0;
if (coins.empty())
return -1;
sort(coins.begin(), coins.end(), greater<int>()); // 降序
if (amount < coins[coins.size() - 1]) // 比最小的硬币面值还小,肯定不行的嘛
return -1;
int level = 0;
queue<int> intervalResult;
unordered_map<int, bool> visited;
intervalResult.push(amount);
while (!intervalResult.empty()) {
int tmpSize = intervalResult.size();
level += 1;
for (int index = 0; index < tmpSize; ++index) {
int tmpValue = intervalResult.front();
// cout << "tmpValue: " << tmpValue << endl;
intervalResult.pop();
for (int coin : coins) {
int aa = tmpValue - coin;
if (aa < 0 || visited.find(aa) != visited.end())
continue;
if (aa == 0) {
return level;
}
intervalResult.push(aa);
visited.insert(pair<int, bool>(aa, true));
}
}
}
return -1;
}
};
/*
* 使用vector记录解决方案
* 但会超时
*/
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
// [] 1 返回 -1
// [] 0 返回 0
// [1] 0 返回 0
if (0 == amount )
return 0;
if (coins.empty())
return -1;
sort(coins.begin(), coins.end(), greater<int>()); // 降序
if (amount < coins[coins.size() - 1]) // 比最小的硬币面值还小,肯定不行的嘛
return -1;
int level = 0;
// 其实还是填格子,每个面额的硬币对应一个格子,
// 格子里是几,就表示用几枚本种硬币
// 回溯
vector<int> countOfCoint(coins.size(), 0);
vector<vector<int>> result;
backTrace(0, amount, coins, countOfCoint, result);
if (result.empty())
return -1;
int minCoins = INT_MAX;
int tmpCount = 0;
for (vector<int> &vec : result) {
tmpCount = 0;
for (int num : vec) {
// cout << num << " ";
tmpCount += num;
}
minCoins = min(tmpCount, minCoins);
// cout << endl;
}
return minCoins;
}
private:
void backTrace(int index, int amount, vector<int> &coins, vector<int> &countOfCoint, vector<vector<int>> &result) {
// cout << "index: " << index << " amount: " << amount << endl;
// 结束条件
if (0 == amount) {
// 满足条件
// 不需要再进行后续检测
result.push_back(countOfCoint);
}
// 不满足条件,但也已经到结尾了
if (index == coins.size()) {
return;
}
int count = amount / coins[index];
int left = amount % coins[index];
int k = 0;
while (k <= count) {
countOfCoint[index] = count - k;
backTrace(index + 1, left + k * coins[index], coins, countOfCoint, result);
countOfCoint[index] = 0;
k += 1;
}
}
};
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
// [] 1 返回 -1
// [] 0 返回 0
// [1] 0 返回 0
if (0 == amount )
return 0;
if (coins.empty())
return -1;
sort(coins.rbegin(), coins.rend()); // 降序
int level = 0;
int minCoins = INT_MAX;
int tmpCount = 0;
backTrace(0, amount, coins, minCoins, tmpCount);
return minCoins == INT_MAX ? -1 : minCoins;
}
private:
void backTrace(int index, int amount, vector<int> &coins, int &minCoins, int tmpCount) {
// cout << "index: " << index << " amount: " << amount << endl;
// 结束条件
if (0 == amount) {
// 满足条件
// 不需要再进行后续检测
minCoins = min(minCoins, tmpCount);
}
// 不满足条件,但也已经到结尾了
if (index == coins.size()) {
return;
}
int count = amount / coins[index];
/*
* 本方式的精髓在于tmpCount + count < minCoins
* 如果使用count个coins[index]时,硬币的数量已经超过了当前最小结果,count-1个coins[index]就更不用考虑了,
* 因为coins[index+1] < coin[index],少使用一个coins[index]只会增加更多的coins[index+1...n]
*/
while (count >= 0 && tmpCount + count < minCoins) {
backTrace(index + 1, amount - count * coins[index], coins, minCoins, tmpCount + count);
count -= 1;
}
}
};
// [288,160,10,249,40,77,314,429]
// 9208
// [470,35,120,81,121]
// 9825
// [270,373,487,5,62]
// 8121
// [186,419,83,408]
// 6249
// [1,2,5]
// 11
// []
// 1
// []
// 0
// [1]
// 0
// [2]
// 1 |
dbfae460bbc3b50797bf0d9749f9e68ed2f8e0b6 | 692af5a07aa3f7dde83c9c4793a7297a6ea8780b | /Classes/GolfXIMager.cpp | 48928afeb424e9dd32c05b1b4dd663c4469deba8 | [] | no_license | w13315071023/DigitGolf_300 | 5c7886521a83874602a51e9639607df4e2fd98a5 | 1ed5158bb593044eddb312d43497afe45b87ee6f | refs/heads/master | 2020-09-14T11:49:44.549011 | 2016-11-03T06:34:30 | 2016-11-03T06:34:30 | 66,529,287 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,129 | cpp | GolfXIMager.cpp | #include "GolfXIMager.h"
GolfXIMager::GolfXIMager()
{
}
GolfXIMager::~GolfXIMager()
{
}
GolfXIMager* GolfXIMager::m_pInstence = NULL;
bool GolfXIMager::m_IsHitBall = false;
GolfXIMager* GolfXIMager::getInstence()
{
if (m_pInstence == NULL)
{
m_pInstence = new GolfXIMager();
if (!m_pInstence->init())
{
delete m_pInstence;
m_pInstence = NULL;
}
}
return m_pInstence;
}
bool GolfXIMager::init()
{
count = 0;
gsiInstance = 0;
std::string fileName = "GolfSensorInterface_v4_7_0_alpha_1.dll";
if (!OpenGolfSensorInterface(fileName.c_str()))
{
CCLog("无法打开雷达的接口信息!");
return false;
}
//7 Creating a Library Instance
gsiInstance = (GSINewInstance != NULL) ? GSINewInstance((int)this) : NULL;
if (!gsiInstance)
{
CCLog("GSINewInstance:bad\n");
return false;
}
//6 Verifying Library Version
std::string Caption;
Caption = "GolfSensorInterface Tester (DLL " + std::string(GSIFileProductVersion(gsiInstance, fileName.c_str())) + ")";
CCLog(Caption.c_str());
std::string version = std::string(GSIFileProductVersion(gsiInstance, fileName.c_str()));
if (version == "")
{
CCLog("没有找到对应的雷达版本!");
return false;
}
GSISetErrorCallback(gsiInstance, &GSIErrorCallback);
GSISetStatusChangeCallback(gsiInstance, &GSIStatusChangeCallback);
GSISetExtendedStatusCallback(gsiInstance, &GSIExtendedStatusCallback);
GSISetTiltRollCallback(gsiInstance, &GSITiltRollCallback);
GSISetTrackingStatusChangeCallback(gsiInstance, &GSITrackingStatusChangeCallback);
GSISetResultCallback(gsiInstance, &GSIResultCallback);
GSISetRealtimeResultCallback(gsiInstance, &GSIRealtimeResultCallback);
GSISetAVRParamsWrittenCallback(gsiInstance, &GSIAVRParamsWrittenCallback);
GSISetDSPParamsWrittenCallback(gsiInstance, &GSIDSPParamsWrittenCallback);
GSISetSamplesAvailableForDownloadCallback(gsiInstance, &GSISamplesAvailableForDownloadCallback);
GSISetSampleUploadOrDownloadProgressCallback(gsiInstance, &GSISampleUploadOrDownloadProgressCallback);
GSISetSamplesUploadedCallback(gsiInstance, &GSISamplesUploadedCallback);
GSISetSamplesDownloadedAndSavedCallback(gsiInstance, &GSISamplesDownloadedAndSavedCallback);
GSISetUDPDiscoveryStartedCallback(gsiInstance, &GSIUDPDiscoveryStartedCallback);
GSISetUDPDiscoveryServiceFoundCallback(gsiInstance, &GSIUDPDiscoveryServiceFoundCallback);
int deviceCount = -1;
deviceCount = GSIScanForCommsDevices(gsiInstance);
if (deviceCount < 0)
{
return 0;
}
if (GSIOpenTCP(gsiInstance, "192.168.2.1", 5100))
{
Ext_IsGolfXI = true;
}
else
{
Ext_IsGolfXI = false;
}
return true;
}
void GolfXIMager::CloseXI()
{
if (gsiInstance != 0)
{
//7、释放
GSIDisposeInstance(gsiInstance);
gsiInstance = 0;
}
CloseGolfSensorInterface();
}
void GolfXIMager::DeviceUpdate()
{
if (true)
{
MSG msg;
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
//消息处理
if (this->hasCallbackData())
{
std::vector<std::map<std::string, std::string>> list;
this->takeCallbackDataList(list);
//记录雷达输出的必要信息
for (unsigned int i = 0; i < list.size(); i++)
{
//分拣名称
auto it = list[i].find("name");
if (it != list[i].end())
{
//处理击球结果
if (it->second == "hit_ball")
{
for (auto it2 = list[i].begin(); it2 != list[i].end(); it2++)
{
CCLog("-- %s %s\n", it2->first.c_str(), it2->second.c_str());
if (it2->first == "oriented_speed")
{
std::vector<std::string> nameDataList;
split(it2->second, nameDataList, ' ', true);
m_curBallSpeed = atof(nameDataList[0].c_str())*Ext_ToPixels;
m_curHAngle = atof(nameDataList[1].c_str());
m_curVAngle = atof(nameDataList[2].c_str());
m_curBallSpeed = m_curBallSpeed * 3.6;//公里每小时
//球速 velocity = 6.78
printf("球速 = %f\n", m_curBallSpeed);
printf("仰角 = %f\n", m_curVAngle);
printf("偏角 = %f\n", m_curHAngle);
}
if (it2->first == "angular_rpm")
{
std::vector<std::string> nameDataList;
split(it2->second, nameDataList, ' ', true);
m_curBackSpin = atof(nameDataList[1].c_str());
m_curSideSpin = atof(nameDataList[2].c_str());
printf("回旋 = %f\n", m_curBackSpin);
printf("侧旋 = %f\n", m_curSideSpin);
}
if (it2->first == "club_msg")
{
std::vector<std::string> nameDataList;
split(it2->second, nameDataList, ' ', true);
m_curClubYaw = atof(nameDataList[0].c_str())* Ext_ToPixels;
m_curClubSpeed = atof(nameDataList[1].c_str())* Ext_ToPixels;
printf("杆速 = %f\n", m_curClubSpeed);
}
}
m_IsHitBall = true;
}
}
}
}
}
void GolfXIMager::setClubType(int ClubType)
{
if (Ext_IsGolfXI)
{
GSISetClubType(gsiInstance, GSI_CT_IRON);
GSIRelevel(gsiInstance);
}
}
bool GolfXIMager::RelevelXI()
{
count++;
if (count == 3)
{
GSIRelevel(gsiInstance);
}
else if (count == 310)
{
GSISetTargetArmed(gsiInstance, true);
}
else if (count == 420)
{
GSIRelevel(gsiInstance);
}
else if (count == 480)
{
GSISetDetectionMode(gsiInstance, GSI_DM_INDOOR);
}
else if (count > 485)
{
return true;
}
return false;
}
void GolfXIMager::addCallbackData(const std::map<std::string, std::string>& value)
{
_callbackDataList.push_back(value);
_callbackDataUpdated = true;
}
void GolfXIMager::takeCallbackDataList(std::vector< std::map<std::string, std::string> >& dataList)
{
dataList.swap(_callbackDataList);
_callbackDataUpdated = false;
}
void GolfXIMager::clearCallbackData()
{
_callbackDataList.clear();
}
bool GolfXIMager::hasCallbackData() const
{
return _callbackDataUpdated;
}
void GolfXIMager::split(const std::string& src, std::vector<std::string>& slist, char sep, bool ignoreEmpty)
{
if (src.empty()) return;
std::string::size_type start = src.find_first_not_of(sep);
while (start != std::string::npos)
{
std::string::size_type end = src.find_first_of(sep, start);
if (end != std::string::npos)
{
slist.push_back(std::string(src, start, end - start));
if (ignoreEmpty) start = src.find_first_not_of(sep, end);
else start = end + 1;
}
else
{
slist.push_back(std::string(src, start, src.size() - start));
start = end;
}
}
}
void __stdcall GSIErrorCallback(int tag, const char *text)
{
std::cout << "Error text: " << text << std::endl;
std::cout << "" << std::endl;
}
void PrintGolfSensorStatus(std::string &memoLines, TGolfSensorStatus *status, bool finalNewLine)
{
std::cout << "Open: " << BoolToStr(status->Open) << std::endl;
std::cout << "Connected: " << BoolToStr(status->Connected) << std::endl;
std::cout << "Armed: " << BoolToStr(status->Armed) << std::endl;
std::cout << "Sleeping: " << BoolToStr(status->Sleeping) << std::endl;
std::cout << "Leveling: " << BoolToStr(status->Leveling) << std::endl;
if (finalNewLine)
std::cout << " " << std::endl;
}
void __stdcall GSIStatusChangeCallback(int tag, TGolfSensorStatus *status)
{
// Because the first couple of fields of TGolfSensorStatus and TGolfSensorExtendedStatus are identical,
// we simply copy over using a cast trick
//*(TGolfSensorStatus*)(&mainForm->extendedStatus) = *status;
*(TGolfSensorStatus*)(&GolfXIMager::getInstence()->extendedStatus) = *status;
std::string lines;
PrintGolfSensorStatus(lines, status, true);
}
void __stdcall GSIExtendedStatusCallback(int tag, TGolfSensorExtendedStatus *status)
{
GolfXIMager::getInstence()->extendedStatus = *status;
std::string memoLines;
PrintGolfSensorStatus(memoLines, (TGolfSensorStatus*)status, false);
std::cout << "IsOnTCPConnection: " << status->IsOnTCPConnection << std::endl;
std::cout << "FirmwareVersion: " << status->FirmwareVersion << std::endl;
std::cout << "SensorModel: " << status->SensorModel << std::endl;
std::cout << "FirmwareApplication: " << status->FirmwareApplication << std::endl;
std::cout << "HasBattery: " << BoolToStr(status->HasBattery) << std::endl;
std::cout << "BatteryPercentageLevel: " << status->BatteryPercentageLevel << std::endl;
std::cout << "ExternalPowerConnected: " << BoolToStr(status->ExternalPowerConnected) << std::endl;
std::cout << "Charging: " << BoolToStr(status->Charging) << std::endl;
std::cout << "CanSleep: " << BoolToStr(status->CanSleep) << std::endl;
std::cout << "CanSelfLevel: " << BoolToStr(status->CanSelfLevel) << std::endl;
std::cout << "HasCamera: " << BoolToStr(status->HasCamera) << std::endl;
std::cout << "CameraModel: " << status->CameraModel << std::endl;
std::cout << "CameraHFOVDeg: " << status->CameraHFOVDeg << std::endl;
std::cout << "CameraHBoresightDeg: " << status->CameraHBoresightDeg << std::endl;
std::cout << "CameraVFOVDeg: " << status->CameraVFOVDeg << std::endl;
std::cout << "CameraVBoresightDeg: " << status->CameraVBoresightDeg << std::endl;
std::cout << "HardwareID: " << status->HardwareID << std::endl;
std::cout << "DetectionMode: " << status->DetectionMode << std::endl;
std::cout << "TeePosition: "
<< status->TeePosition.X << ", "
<< status->TeePosition.Y << ", "
<< status->TeePosition.Z << std::endl;
std::cout << "TargetArmed: " << BoolToStr(status->TargetArmed) << std::endl;
std::cout << "Altitude: " << status->Altitude << std::endl;
std::cout << "ClubType: " << status->ClubType << std::endl;
std::cout << "" << std::endl;
}
void __stdcall GSITiltRollCallback(int tag, double tilt, double roll)
{
return;
}
void __stdcall GSITrackingStatusChangeCallback(int tag, BOOL tracking, double triggerTime, const char *guid)
{
if (tracking)
{
std::cout << "Tracking: " << tracking << " ("
<< triggerTime << ") - " << guid << std::endl; //tracking, true)
}
else
std::cout << "Tracking: " << tracking << " - " << guid << std::endl;
std::cout << " " << std::endl;
}
void __stdcall GSIRealtimeResultCallback(int tag, TDFlightResults2RH *result, const char *guid)
{
std::cout << "Realtime result: Time = " << result->Time << " s - " << guid << std::endl;
std::cout << "Realtime result: FlightTime = " << result->FlightTime << " s" << std::endl;
//其他信息
std::cout << "Realtime Result: 球速 " << result->LaunchSpeed << std::endl;
std::cout << "Realtime Result: 杆速 " << result->ClubheadSpeed << std::endl;
std::cout << "Realtime Result: 杆角度 " << result->ClubFaceAngleDeg << std::endl;
}
void __stdcall GSIResultCallback(int tag, TDFlightResults2RH *result, const char *guid)
{
std::cout << "Result: Time = " << result->Time << " s - " << guid << std::endl;
std::cout << "Result: FlightTime = " << result->FlightTime << " s" << std::endl;
std::cout << "Result: Carry = " << result->CarryDistance << " m" << std::endl;
g_Carry = result->CarryDistance;
//if(!(result->BackspinRPM) && !(result->SidespinRPM))
{
std::cout << "BackspinRPM is " << result->BackspinRPM << " SidespinRPM is " << result->SidespinRPM << std::endl;
std::cout << "Result: Total spin = " << sqrt((result->BackspinRPM*result->BackspinRPM) + (result->SidespinRPM*result->SidespinRPM))
<< " rpm" << std::endl;
std::cout << "Result: Spin axis = " << RadToDeg(atan2(result->SidespinRPM, result->BackspinRPM))
<< "?);" << std::endl;
}
std::cout << "Result: ClubSpeedPointCount = " << result->ClubSpeedPointCount << std::endl;
std::cout << " " << std::endl;
//其他信息
std::cout << "Result: 球速 " << result->LaunchSpeed << std::endl;
std::cout << "Result: 杆速 " << result->ClubheadSpeed << std::endl;
std::cout << "Result: 杆角度 " << result->ClubFaceAngleDeg << std::endl;
sendHitResultCommand(result);
}
void __stdcall GSIAVRParamsWrittenCallback(int tag, BOOL successful)
{
if (successful)
std::cout << "AVR params successfully written" << std::endl;
else
std::cout << "AVR params write failed" << std::endl;
std::cout << "" << std::endl;
}
void __stdcall GSIDSPParamsWrittenCallback(int tag, BOOL successful)
{
if (successful)
std::cout << "DSP params successfully written" << std::endl;
else
std::cout << "DSP params write failed" << std::endl;
std::cout << "" << std::endl;
}
void __stdcall GSISamplesAvailableForDownloadCallback(int tag, const char *guid)
{
std::cout << "调用 GSISamplesAvailableForDownloadCallback " << std::endl;
}
void __stdcall GSISampleUploadOrDownloadProgressCallback(int tag,
float channelPercentage, int currentChannelIndex, int channelCount, const char *guid)
{
std::cout << "调用 GSISamplesUploadedCallback 刷新? ProgressForm->Hide() " << std::endl;
}
void __stdcall GSISamplesUploadedCallback(int tag, BOOL successful)
{
std::cout << "调用 GSISamplesUploadedCallback 刷新? ProgressForm->Hide() " << std::endl;
}
void __stdcall GSISamplesDownloadedAndSavedCallback(int tag, BOOL successful, const char *guid)
{
std::cout << "调用 GSISamplesDownloadedAndSavedCallback 刷新? ProgressForm->Hide() " << std::endl;
}
void __stdcall GSIUDPDiscoveryStartedCallback(int tag)
{
std::cout << "调用 GSIUDPDiscoveryStartedCallback" << std::endl;
}
void __stdcall GSIUDPDiscoveryServiceFoundCallback(int tag, TGolfSensorDiscoverableServiceInfo *serviceInfo,
const char *discoveryServerIPv4Address)
{
std::cout << "调用 GSIUDPDiscoveryServiceFoundCallback" << std::endl;
}
void sendHitResultCommand(TDFlightResults2RH *result)
{
std::map<std::string, std::string> jsonData;
jsonData["name"] = "hit_ball";
std::stringstream ss;
ss << result->LaunchSpeed << " " << result->LaunchAzimDeg//-inDegrees(r->HorzAngle)
<< " " << result->LaunchElevDeg;//inDegrees(r->VertAngle);
jsonData["oriented_speed"] = ss.str();
ss.str("");
ss << "0.0 " << result->BackspinRPM << " " << result->SidespinRPM;
jsonData["angular_rpm"] = ss.str();
ss.str("");
ss << result->ClubStrikeDirectionDeg << " " << result->ClubheadSpeed << " " << "0.0";
jsonData["club_msg"] = ss.str();
if (GolfXIMager::getInstence())
GolfXIMager::getInstence()->addCallbackData(jsonData);
}
float RadToDeg(float Angle)
{
return (Angle * 180) / PI;
}
std::string BoolToStr(bool boolTag)
{
if (boolTag)
{
return "true";
}
else
{
return "false";
}
}
|
3114583f3ecf86c791a68a97c32f7ecc065b973a | 9efaee6c826cd48473cd6c187b2542b7f8c02e8a | /06-cpp11feature/cpp11feature/functionbind.cpp | 89ac16638b5eeb0043fcedf7f8f3803e94bd4278 | [] | no_license | secondtonone1/cpp-learn | 71fa2a3cfd53a64075421f474ff0a92d6e1e223e | 34dae5bb0fc6cd9b2dc7e567a406ac939a5865f9 | refs/heads/master | 2020-12-14T18:05:04.567665 | 2020-03-11T23:18:04 | 2020-03-11T23:18:04 | 234,833,832 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,853 | cpp | functionbind.cpp | #include "functionbind.h"
#include <utility>
#include <vector>
#include <algorithm>
void fun(int x, int y, int z)
{
cout << x << " " << y << " " << z << endl;
}
void fun_2(int &a, int &b)
{
a++;
b++;
cout << a << " " << b << endl;
}
void use_funcmem() {
//f1的类型为 function<void(int, int, int)>
auto f1 = std::bind(fun, 1, 2, 3); //表示绑定函数 fun 的第一,二,三个参数值为: 1 2 3
f1(); //print:1 2 3
auto f2 = std::bind(fun, placeholders::_1, placeholders::_2, 3);
//表示绑定函数 fun 的第三个参数为 3,而fun 的第一,二个参数分别由调用 f2 的第一,二个参数指定
f2(1, 2);//print:1 2 3
auto f3 = std::bind(fun, placeholders::_2, placeholders::_1, 3);
//表示绑定函数 fun 的第三个参数为 3,而fun 的第一,二个参数分别由调用 f3 的第二,一个参数指定
//注意: f2 和 f3 的区别。
f3(1, 2);//print:2 1 3
int n = 2;
int m = 3;
auto f4 = std::bind(fun_2, n, placeholders::_1); //表示绑定fun_2的第一个参数为n, fun_2的第二个参数由调用f4的第一个参数(_1)指定。
f4(m); //print:3 4
cout << m << endl;//print:4 说明:bind对于不事先绑定的参数,通过std::placeholders传递的参数是通过引用传递的,如m
cout << n << endl;//print:2 说明:bind对于预先绑定的函数参数是通过值传递的,如n
A a;
//f5的类型为 function<void(int, int)>
auto f5 = std::bind(&A::fun_3, a, placeholders::_1, placeholders::_2); //使用auto关键字
f5(10, 20);//调用a.fun_3(10,20),print:10 20
std::function<void(int, int)> fc = std::bind(&A::fun_3, a, std::placeholders::_1, std::placeholders::_2);
fc(10, 20);//调用a.fun_3(10,20) print:10 20
auto f6 = std::bind(&A::fun_4, a, std::placeholders::_1, std::placeholders::_2);
f6("hello ", " world!");
}
|
6fe9e7fa7087b810e34ade4c519a173d21c83649 | 938caa07956634eb9663d775fa5fc55860a1aacf | /src/sdl/sound.h | c69586bbc8571c3129c666a447990d491c3f02d1 | [
"BSD-3-Clause"
] | permissive | lasty/ld30_connectedworlds | 5f657124b4243f5d3e82aa6693b4b3ba0084bf22 | 807b4c5e05d74f4385c2f71590deb6a69e5e5553 | refs/heads/master | 2021-06-02T04:52:40.612406 | 2020-08-10T12:03:32 | 2020-08-10T12:03:32 | 23,244,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | h | sound.h | #ifndef SDL_SOUND_H
#define SDL_SOUND_H
#include <string>
struct Mix_Chunk;
namespace sdl
{
class Sound
{
public:
Sound(const std::string &sound_filename);
~Sound();
//Block copy, implement move
Sound(const Sound ©) = delete;
Sound(Sound &&move);
Sound& operator=(const Sound ©) = delete;
Sound& operator=(Sound &&move);
private:
Mix_Chunk * chunk = nullptr;
public:
Mix_Chunk * GetChunk() const { return chunk; }
};
} // namespace sdl
#endif // SDL_SOUND_H
|
03ed08954fdded5738af88fe5fbab93411ee3a8d | 4e45f4dce1e4a4faf576de9c1bdb0338d44e4d81 | /src/tools.cpp | 64e05fda64839f46991364b49c0d41d3831d5adc | [] | no_license | kswaroop1/CarND-Unscented-Kalman-Filter-Project | da0acbad4d39839cf84177a1a51c55f1df8b35b8 | 0f8db03f0dc128e78601d8d0cbc59351886aa037 | refs/heads/master | 2021-01-20T01:33:46.435219 | 2017-04-30T20:37:46 | 2017-04-30T20:37:46 | 89,296,266 | 0 | 0 | null | 2017-04-29T06:15:17 | 2017-04-24T23:33:21 | C++ | UTF-8 | C++ | false | false | 1,883 | cpp | tools.cpp | #include <sstream>
#include <iostream>
#include <iomanip>
#include <numeric>
#include "tools.h"
using Eigen::Vector2d;
using Eigen::VectorXd;
using Eigen::MatrixXd;
using std::vector;
using std::string;
using std::stringstream;
Tools::Tools() {}
Tools::~Tools() {}
/*static*/ VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) {
auto rmse = VectorXd{ 4 };
rmse << 0.0, 0.0, 0.0, 0.0;
// check the validity of the following inputs:
// * the estimation vector size should not be zero
// * the estimation vector size should equal ground truth vector size
if (estimations.size() != ground_truth.size() || estimations.size() == 0) {
std::cerr << "Invalid estimation or ground_truth data" << std::endl;
return rmse;
}
//accumulate squared residuals
for (unsigned int i = 0; i < estimations.size(); ++i) {
VectorXd residual = estimations[i] - ground_truth[i];
residual = residual.array()*residual.array(); //coefficient-wise multiplication
rmse += residual;
}
rmse = rmse / (double)estimations.size(); //calculate the mean
rmse = rmse.array().sqrt(); //calculate the squared root
return rmse;
}
/* static */ VectorXd Tools::CalculateStdDev(const std::vector<VectorXd>& process_state) {
// standard deviation of population. ref https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
VectorXd retVal;
auto N = process_state.size();
if (N < 1) return retVal;
auto K = process_state[0];
retVal = VectorXd(process_state[0].rows()); retVal.fill(0.0);
auto sum = retVal; auto sum2 = retVal;
for (auto i = 0u; i < N; ++i) {
auto d = process_state[i] - K;
sum += d;
sum2 += d.cwiseProduct(d);
}
retVal = (sum2 - (sum.cwiseProduct(sum) / N)) / N; // (n-1) for sample
retVal = retVal.array().sqrt();
return retVal;
}
|
3edb6bed4632cd4f4b9a5da6a7d760552c1ccd73 | c432cf3a7db8cd558c7d8b66f9a7be62064ae5a8 | /C++/02_leetCode_GfG_Hacker/l025_no_of_connected_components/main.cpp | 21bb01f9fd12e90a5569c95054e138efcdf3bea6 | [] | no_license | babakpst/Learning | 19867acf37145fed8acfd1321ec49b7eba217042 | 945ffb6136b4cb7944810834db1366d8ee5128ad | refs/heads/master | 2023-08-09T06:57:49.476966 | 2023-08-04T13:48:02 | 2023-08-04T13:48:02 | 158,579,987 | 4 | 0 | null | 2020-08-28T21:07:05 | 2018-11-21T16:53:53 | C++ | UTF-8 | C++ | false | false | 1,239 | cpp | main.cpp |
// babak poursartip
// Aug 8, 2022
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <set>
using namespace std;
class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
std::vector<int> root(n);
std::iota(root.begin(), root.end(), 0);
for (int i = 0; i<edges.size(); i++)
{
int p = edges[i][0];
int q = edges[i][1];
int rootp = root[p];
int rootq = root[q];
if (rootp != rootq)
for (auto it = root.begin(); it!=root.end(); it++)
{
if (*it == rootq)
*it = rootp;
}
}
std::set<int> connected;
for (auto it = root.begin(); it!=root.end(); it++)
{
connected.insert(*it);
}
return connected.size();
}
};
int main(int argc, char* argv[])
{
std::cout << " starts ... \n";
//int n = 5;
//std::vector<std::vector<int>> vec{{0,1},{0,2},{0,3},{1,4}};
//int n = 2;
//std::vector<std::vector<int>> vec{{0,1}};
int n = 5;
std::vector<std::vector<int>> vec{{0,1},{1,2},{3,4}};
Solution t;
int out = t.countComponents(n,vec);
std::cout << " answer: "<< out << std::endl;
std::cout << " done. \n";
return 0;
}
|
957a1d4947d57127d17f32ea45de409b67a6f700 | da1500e0d3040497614d5327d2461a22e934b4d8 | /starboard/android/shared/jni_utils.h | 515280154ad72217bb4d12bb44947417f631cf87 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | youtube/cobalt | 34085fc93972ebe05b988b15410e99845efd1968 | acefdaaadd3ef46f10f63d1acae2259e4024d383 | refs/heads/main | 2023-09-01T13:09:47.225174 | 2023-09-01T08:54:54 | 2023-09-01T08:54:54 | 50,049,789 | 169 | 80 | BSD-3-Clause | 2023-09-14T21:50:50 | 2016-01-20T18:11:34 | null | UTF-8 | C++ | false | false | 2,821 | h | jni_utils.h | // Copyright 2017 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef STARBOARD_ANDROID_SHARED_JNI_UTILS_H_
#define STARBOARD_ANDROID_SHARED_JNI_UTILS_H_
#include <jni.h>
#include "starboard/android/shared/jni_env_ext.h"
#include "starboard/common/log.h"
#include "starboard/configuration.h"
#include "starboard/memory.h"
namespace starboard {
namespace android {
namespace shared {
// Wrapper class to manage the lifetime of a local reference to Java type
// |JT|. This is necessary for local references to |JT|s that are obtained in
// native code that was not called into from Java, since they will otherwise
// not be cleaned up.
template <typename JT>
class ScopedLocalJavaRef {
public:
explicit ScopedLocalJavaRef(jobject j_object = NULL)
: jt_(static_cast<JT>(j_object)) {}
~ScopedLocalJavaRef() {
if (jt_) {
JniEnvExt::Get()->DeleteLocalRef(jt_);
jt_ = NULL;
}
}
JT Get() const { return jt_; }
void Reset(jobject j_object) {
if (jt_) {
JniEnvExt::Get()->DeleteLocalRef(jt_);
}
jt_ = static_cast<JT>(j_object);
}
operator bool() const { return jt_; }
private:
JT jt_;
ScopedLocalJavaRef(const ScopedLocalJavaRef&) = delete;
void operator=(const ScopedLocalJavaRef&) = delete;
};
// Convenience class to manage the lifetime of a local Java ByteBuffer
// reference, and provide accessors to its properties.
class ScopedJavaByteBuffer {
public:
explicit ScopedJavaByteBuffer(jobject j_byte_buffer)
: j_byte_buffer_(j_byte_buffer) {}
void* address() const {
return JniEnvExt::Get()->GetDirectBufferAddress(j_byte_buffer_.Get());
}
jint capacity() const {
return JniEnvExt::Get()->GetDirectBufferCapacity(j_byte_buffer_.Get());
}
bool IsNull() const { return !j_byte_buffer_ || !address(); }
void CopyInto(const void* source, jint count) {
SB_DCHECK(!IsNull());
SB_DCHECK(count >= 0 && count <= capacity());
memcpy(address(), source, count);
}
private:
ScopedLocalJavaRef<jobject> j_byte_buffer_;
ScopedJavaByteBuffer(const ScopedJavaByteBuffer&) = delete;
void operator=(const ScopedJavaByteBuffer&) = delete;
};
} // namespace shared
} // namespace android
} // namespace starboard
#endif // STARBOARD_ANDROID_SHARED_JNI_UTILS_H_
|
344f32d58fa199213a7a8c7e7143ad7983c8791b | bab2a50dec758a565b84f6569b3c377a0273741a | /Leetcode_双周赛23_5361_圆和矩形是否有重叠/Leetcode_双周赛23_5361_圆和矩形是否有重叠/main.cpp | 499e5692bf2a842d28efb52cc931d81c002ed0c8 | [] | no_license | chx2502/LeetCode | 734ed70cc7a9c732ca7795c9f1920a6763548fb6 | 9c292b22ba4a3163691f3dfdf11037adbc644c1b | refs/heads/master | 2021-11-27T18:04:25.168830 | 2021-06-25T02:45:15 | 2021-06-25T02:45:15 | 180,375,645 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 475 | cpp | main.cpp | //
// main.cpp
// Leetcode_双周赛23_5361_圆和矩形是否有重叠
//
// Created by chx on 2020/4/4.
// Copyright © 2020 __Ninja__. All rights reserved.
//
#include <iostream>
using namespace std;
class Solution {
public:
bool checkOverlap(int radius, int x_center, int y_center, int x1, int y1, int x2, int y2) {
}
};
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
|
ab8a5b632e753288bc943b6d7d4475504a2a8ded | 026a49bd77f1f9b50d851292ca49d256e322b217 | /lab/00 - Tipos Abstratos de Dados/binary-search-trees/main.cpp | 4570003036ccb3c49d321c4ff67bd89ffd959215 | [] | no_license | gnuns/pds2 | 1994dc5dee1ff628d1b52a7db835b2acd78f3b94 | b8b2a304326f8674ac7f5852cb53b9c7c7553d8d | refs/heads/master | 2020-03-26T16:13:46.482143 | 2018-08-28T21:10:12 | 2018-08-28T21:10:12 | 145,088,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 468 | cpp | main.cpp | #include "BST.hpp"
int main (int argc, char const *argv[]) {
BST tree;
tree.insertNode(480);
tree.insertNode(920);
tree.insertNode(55);
tree.insertNode(99);
tree.insertNode(9);
tree.insertNode(17);
tree.insertNode(18);
tree.insertNode(3);
tree.display();
cout << tree.contains(8) << endl;
cout << tree.contains(18) << endl;
cout << tree.contains(920) << endl;
cout << tree.contains(10) << endl;
cout << "Fim!" << endl;
return 0;
}
|
44ccd32c0316a7044a2aef1d372f5a03bbc56ec0 | 10fce5ba5a40413ab63a0301c2d5bd7a816477d0 | /src/shared/Output.h | 98f730e6e816f1efa3edac60c8335790ff882bf3 | [
"MIT"
] | permissive | RainerBlessing/TheRayTracerChallenge-C- | 425b7ba20e3d34c91ddfd146f4e39863f577d7ec | 22c990201507f46d5bb1604bc1f6ee88e59cef95 | refs/heads/master | 2020-11-29T13:24:08.981512 | 2020-01-11T15:47:12 | 2020-01-11T15:47:12 | 230,123,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 987 | h | Output.h | #ifndef RAY_TRACER_CHALLENGE_OUTPUT_H
#define RAY_TRACER_CHALLENGE_OUTPUT_H
#include <ostream>
#include "Translation.h"
#include "Point.h"
#include "Color.h"
#include "Object.h"
#include "Sphere.h"
#include "Intersection.h"
#include "Position.h"
extern std::ostream& operator << (std::ostream& os, const Translation t);
extern std::ostream& operator << (std::ostream& os, const Tuple t);
extern std::ostream& operator << (std::ostream& os, const Point p);
extern std::ostream& operator << (std::ostream& os, const Vector v);
extern std::ostream& operator << (std::ostream& os, const Matrix m);
extern std::ostream& operator << (std::ostream& os, const Color c);
extern std::ostream& operator << (std::ostream& os, const Object o);
extern std::ostream& operator << (std::ostream& os, const Sphere s);
extern std::ostream& operator << (std::ostream& os, const Intersection i);
extern std::ostream& operator << (std::ostream& os, const Position p);
#endif //RAY_TRACER_CHALLENGE_OUTPUT_H |
c4cae48218f3bc0a1941d77c847bdf239b84ab15 | 5b94b7d1adef2eb65b5d250eb0cb5b381f9d2397 | /main.cpp | 73cd38d15d5eddbd427b65e7dc6cda41b2dcc248 | [
"Apache-2.0"
] | permissive | MoyKarasik/HzChe | 8ec7c6815263cd95bf89a82c460d90f04883dfbe | 830653ee5b8becc0fa3100cfbbb80f7c8b98d693 | refs/heads/master | 2022-12-09T00:21:25.879343 | 2020-06-28T10:50:51 | 2020-06-28T10:50:51 | 275,561,496 | 0 | 2 | Apache-2.0 | 2020-09-08T22:31:03 | 2020-06-28T10:31:38 | C++ | UTF-8 | C++ | false | false | 27 | cpp | main.cpp | gsaocipo[fkgm ;fwe'k[AJEBL
|
2de30afac1da322978f30f18bdad71149cdd99c0 | 69f0ec8835c84208834cca424702881c19c0a3eb | /main.cpp | 84576ee5d2ea52bf4990d9007c4c867df788d4a8 | [] | no_license | slsktnkv/GoogleCity | 6891189f93a6f03aa192fe52867502591b365353 | 2d4d2d5456402b8904ca24307ff70d2c1730efce | refs/heads/master | 2023-03-21T03:13:25.734183 | 2021-03-06T10:58:48 | 2021-03-06T10:58:48 | 342,952,396 | 0 | 0 | null | 2021-03-06T10:58:49 | 2021-02-27T20:31:46 | C++ | UTF-8 | C++ | false | false | 3,091 | cpp | main.cpp | #include <iostream>
#include <fstream>
#include <omp.h>
#include "City.h"
#include "Simulation.h"
#include "Genetics.h"
#include "DummyOptimization.h"
int main(int argc, char** argv)
{
std::string data, solution;
int times;
size_t size;
if (argc == 5) {
data = argv[1];
solution = argv[2];
size = atoi(argv[3]);
times = atoi(argv[4]);
} else {
data = "a.txt";
solution = "answer_a.txt";
size = 8;
times = 20;
}
City city;
std::ifstream in, sch;
in.open(data);
city.LoadCity(in);
in.close();
if (!city.CheckRouts()) {
std::cout << "PROBLEM WITH CARS' ROUTES!" << std::endl;
}
/*
std::vector<Simulation> sims;
sims.emplace_back(city);
sch.open(solution);
sims.front().LoadScheduler(sch);
sch.close();
sims.front().Run();
std::cout << "Initial:\t" << sims.front().Score() << std::endl;
for (int i = 1; i < times; ++i) {
sims.emplace_back(city);
std::cout << "Constructed:" << "\t" << i << std::endl;
}
#pragma omp parallel for
for (int i = 1; i < times; ++i) {
sims[i].SetScheduler(sims.front().Scheduler());
sims[i].Run();
std::cout << i << "\t" << sims[i].Score() << std::endl;
}
*/
/*
size_t elite_size = size;
Genetics::Population world(city, elite_size, 0);
int time = 0;
std::cout << "Generation: " << time;
for (const auto& c : world.GetTop(elite_size * 2)) {
std::cout << "\t" << c->Score();
}
std::cout << std::endl;
for (++time; time < times; time++) {
world.NextGeneration();
std::cout << "Generation: " << time;
for (const auto& c : world.GetTop(elite_size * 2)) {
std::cout << "\t" << c->Score();
}
std::cout << std::endl;
}
*/
Simulation sim(city);
sch.open(solution);
sim.LoadScheduler(sch);
sch.close();
sim.Run();
std::cout << "initial:\t" << sim.Score() << std::endl;
/*
std::cout << "unused:\t" << ReduceUnsed(sim);
sim.Run();
std::cout << "\tscore:\t" << sim.Score() << std::endl;
std::cout << "unused:\t" << ReduceUnsed(sim);
sim.Run();
std::cout << "\tscore:\t" << sim.Score() << std::endl;
sim.RunUniformScheduler();
std::cout << "uniform:\t" << sim.Score() << std::endl;
std::cout << "unused:\t" << ReduceUnsed(sim);
sim.Run();
std::cout << "\tscore:\t" << sim.Score() << std::endl;
sim.RunEmptyScheduler();
std::cout << "empty:\t" << sim.Score() << std::endl;
std::cout << "unused:\t" << ReduceUnsed(sim);
sim.Run();
std::cout << "\tscore:\t" << sim.Score() << std::endl;
*/
std::cout << std::endl;
for (int s = 0; s < times; ++s) {
std::cout << "unused:\t" << ReduceUnsed(sim);
sim.Run();
std::cout << "\tscore:\t" << sim.Score() << std::endl;
std::cout << "increase:\t" << IncreaseStucked(sim);
sim.Run();
std::cout << "\tscore:\t" << sim.Score() << std::endl;
}
return 0;
}
|
6784cfad0c760a61b5ec91650d7a875dd281e167 | caff4200d2933a2bd5bd7f7fda3e4e75641d1740 | /libluaav/av_windows.cpp | 2459fdd27997b8c590b39f491f05d045d65cd662 | [
"MIT"
] | permissive | sidec/libluaav | 6a77c7f6a4e7bf4d68db5659bcd2549ab550375d | 0b53342dfc5778db24c0090d01765c6bef552493 | refs/heads/master | 2021-01-18T06:49:26.461112 | 2014-01-24T23:53:43 | 2014-01-24T23:53:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,427 | cpp | av_windows.cpp |
#include <windows.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#include "av.hpp"
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
#endif
#define AV_PATH_MAX MAX_PATH
#define AV_GETCWD _getcwd
#define AV_SNPRINTF _snprintf
struct timezone {
int tz_minuteswest; /* minutes W of Greenwich */
int tz_dsttime; /* type of dst correction */
};
int gettimeofday(struct timeval *tv, struct timezone *tz) {
FILETIME ft;
unsigned __int64 tmpres = 0;
static int tzflag;
if (NULL != tv)
{
GetSystemTimeAsFileTime(&ft);
tmpres |= ft.dwHighDateTime;
tmpres <<= 32;
tmpres |= ft.dwLowDateTime;
/*converting file time to unix epoch*/
tmpres -= DELTA_EPOCH_IN_MICROSECS;
tmpres /= 10; /*convert into microseconds*/
tv->tv_sec = (long)(tmpres / 1000000UL);
tv->tv_usec = (long)(tmpres % 1000000UL);
}
if (NULL != tz)
{
if (!tzflag)
{
_tzset();
tzflag++;
}
tz->tz_minuteswest = _timezone / 60;
tz->tz_dsttime = _daylight;
}
return 0;
}
AV_EXPORT double av_time() {
timeval t;
gettimeofday(&t, NULL);
return (double)t.tv_sec + (((double)t.tv_usec) * 1.0e-6);
}
AV_EXPORT void av_sleep(double seconds) {
Sleep((DWORD)(seconds * 1.0e3));
}
static HMODULE HIn;
typedef struct av_GLContextW32 {
HDC dc; // Private GDI device context
HGLRC context; // Permanent rendering context
} av_GLContextW32;
typedef struct av_WindowW32 : public av_Window {
HWND hwnd;
av_WindowW32(const char * title, int x, int y, int w, int h) {
this->x = x;
this->y = y;
this->width = w;
this->height = h;
shift = ctrl = alt = cmd = 0;
autoclear = 1;
create_callback = 0;
resize_callback = 0;
draw_callback = 0;
mouse_callback = 0;
key_callback = 0;
modifiers_callback = 0;
isfullscreen = 0;
this->title = (char *)malloc(strlen(title)+1);
strcpy(this->title, title);
hwnd = 0;
}
~av_WindowW32() {
close();
free(this->title);
}
int open() {
hwnd = CreateWindowEx(
0, //WS_EX_APPWINDOW,
"LuaAV",
title,
WS_OVERLAPPEDWINDOW,
x, y, width, height,
NULL, //GetDesktopWindow(), // parent HWND
NULL, // menu
HIn,
this);
if(hwnd==NULL) {
printf("failed to create window\n");
return 1;
} else {
printf("created window\n");
}
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
SetFocus(hwnd);
return 0;
}
int close() {
}
void getMods() {
shift = (GetAsyncKeyState(VK_SHIFT) & (1 << 31));
ctrl = (GetAsyncKeyState(VK_CONTROL) & (1 << 31));
alt = (GetAsyncKeyState(VK_MENU) & (1 << 31));
cmd = ((GetAsyncKeyState(VK_LWIN) | GetAsyncKeyState(VK_RWIN)) & (1 << 31));
}
} av_WindowW32;
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
// not that this will be NULL until the WM_NCCREATE event is posted
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
switch(msg) {
case WM_CREATE:
case WM_NCCREATE: {
LONG_PTR userdata = (LONG_PTR)((LPCREATESTRUCT)lParam)->lpCreateParams;
SetWindowLongPtr(hwnd, GWL_USERDATA, (LONG_PTR)userdata);
break;
}
case WM_SIZE: {
win->width = LOWORD(lParam);
win->height = HIWORD(lParam);
if (win && win->resize_callback) win->resize_callback(win, win->width, win->height);
break;
}
case WM_MOVE: {
win->x = LOWORD(lParam);
win->y = HIWORD(lParam);
if (win && win->resize_callback) win->resize_callback(win, win->width, win->height);
break;
}
case WM_ACTIVATE: {
BOOL focused = LOWORD(wParam) != WA_INACTIVE;
BOOL iconified = HIWORD(wParam) ? TRUE : FALSE;
printf("WM_ACTIVATE\n");
break;
}
//case WM_ACTIVATEAPP:
case WM_SHOWWINDOW: {
BOOL show = wParam ? 1 : 0;
printf("WM_SHOWWINDOW\n");
if (win && win->create_callback) win->create_callback(win);
break;
}
case WM_SYSCOMMAND: {
switch (wParam & 0xfff0) {
case SC_SCREENSAVE:
case SC_MONITORPOWER:
// if we are fullscreen, return 0 to prevent screensaver
case SC_KEYMENU: {
// alt click menu... bypass it
return 0;
}
}
break;
}
case WM_CLOSE: {
printf("WM_CLOSE\n");
break;
}
case WM_DESTROY: {
printf("WM_DESTROY\n");
break;
}
case WM_MOUSELEAVE: {
printf("WM_MOUSELEAVE\n");
break;
}
case WM_PAINT: {
printf("WM_PAINT\n");
// dirty the scene
break;
}
case WM_DEVICECHANGE: {
printf("WM_DEVICECHANGE\n"); // monitor setup?
break;
}
default: {
break;
}
}
//SwapBuffers(window->wgl.dc);
return DefWindowProc(hwnd, msg, wParam, lParam);
}
BOOL Register(HINSTANCE HIn) {
WNDCLASSEX Wc;
Wc.cbSize=sizeof(WNDCLASSEX);
Wc.style=0;
Wc.lpfnWndProc=WndProc;
Wc.cbClsExtra=0;
Wc.cbWndExtra=0;
Wc.hInstance=HIn;
Wc.hIcon=LoadIcon(NULL,IDI_APPLICATION);
Wc.hCursor=LoadCursor(NULL,IDC_ARROW);
Wc.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH);
Wc.lpszMenuName=NULL;
Wc.lpszClassName="LuaAV";
Wc.hIconSm=LoadIcon(NULL,IDI_APPLICATION);
return RegisterClassEx(&Wc);
}
AV_EXPORT int av_init() {
static bool initialized = 0;
if (!initialized) {
initialized = 1;
HIn = GetModuleHandle(NULL);
if (!HIn) {
printf("failed to create HMODULE\n");
return 0;
}
if(!Register(HIn)) {
printf("failed to register HINSTANCE\n");
return 0;
}
}
return 0;
}
AV_EXPORT int av_run() {
return 0;
}
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms646276(v=vs.85).aspx
union keystate {
LPARAM lParam;
struct {
unsigned nRepeatCount : 16;
unsigned nScanCode : 8;
unsigned nExtended : 1;
unsigned nReserved : 4;
unsigned nContext : 1;
unsigned nPrev : 1;
unsigned nTrans : 1;
};
};
AV_EXPORT int av_run_once(int blocking) {
MSG msg;
HWND hWnd = NULL; // get messages for all windows
BOOL todo = false;
if (todo) {
todo = GetMessage(&msg, hWnd, 0, 0);
} else {
todo = PeekMessage(&msg,hWnd, 0,0, PM_REMOVE);
}
while (todo) {
HWND hwnd = msg.hwnd;
UINT message = msg.message;
/*
WPARAM wParam;
LPARAM lParam;
DWORD time;
POINT pt; (long x, y)*/
//printf("%d\n", message);
TranslateMessage(&msg);
switch (msg.message) {
case WM_QUIT: {
PostQuitMessage(0);
break;
}
// consider using RAWMOUSE for mouse handling
// http://stackoverflow.com/questions/14113303/raw-input-device-rawmouse-usage
// (this should give better handling for games etc.)
case WM_LBUTTONDOWN: {
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
win->mouseX = msg.pt.x;
win->mouseY = msg.pt.y;
win->getMods();
win->mouse_callback(win, AV_EVENT_MOUSEDOWN, 0, msg.pt.x, msg.pt.y, 0, 0);
break;
}
case WM_RBUTTONDOWN: {
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
win->mouseX = msg.pt.x;
win->mouseY = msg.pt.y;
win->getMods();
win->mouse_callback(win, AV_EVENT_MOUSEDOWN, 1, msg.pt.x, msg.pt.y, 0, 0);
break;
}
case WM_MBUTTONDOWN: {
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
win->mouseX = msg.pt.x;
win->mouseY = msg.pt.y;
win->getMods();
win->mouse_callback(win, AV_EVENT_MOUSEDOWN, 2, msg.pt.x, msg.pt.y, 0, 0);
break;
}
case WM_LBUTTONUP: {
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
win->mouseX = msg.pt.x;
win->mouseY = msg.pt.y;
win->getMods();
win->mouse_callback(win, AV_EVENT_MOUSEUP, 0, msg.pt.x, msg.pt.y, 0, 0);
break;
}
case WM_RBUTTONUP: {
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
win->mouseX = msg.pt.x;
win->mouseY = msg.pt.y;
win->getMods();
win->mouse_callback(win, AV_EVENT_MOUSEUP, 1, msg.pt.x, msg.pt.y, 0, 0);
break;
}
case WM_MBUTTONUP: {
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
win->mouseX = msg.pt.x;
win->mouseY = msg.pt.y;
win->getMods();
win->mouse_callback(win, AV_EVENT_MOUSEUP, 2, msg.pt.x, msg.pt.y, 0, 0);
break;
}
// TODO: calculate dx, dy (e.g. via global), or remove dx, dy from the mouse handling in LuaAV?
// or just do it all in window.lua instead (useful anyway to have mouse.x, mouseX whatever available)
case WM_MOUSEMOVE: {
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
int dx = msg.pt.x - win->mouseX;
int dy = msg.pt.y - win->mouseY;
win->mouseX = msg.pt.x;
win->mouseY = msg.pt.y;
win->getMods();
if (msg.wParam & MK_LBUTTON) {
win->mouse_callback(win, AV_EVENT_MOUSEDRAG, 0, msg.pt.x, msg.pt.y, dx, dy);
} else if (msg.wParam & MK_RBUTTON) {
win->mouse_callback(win, AV_EVENT_MOUSEDRAG, 1, msg.pt.x, msg.pt.y, dx, dy);
} else if (msg.wParam & MK_MBUTTON) {
win->mouse_callback(win, AV_EVENT_MOUSEDRAG, 2, msg.pt.x, msg.pt.y, dx, dy);
} else {
win->mouse_callback(win, AV_EVENT_MOUSEMOVE, 0, msg.pt.x, msg.pt.y, dx, dy);
}
break;
}
case WM_MOUSEWHEEL: {
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
win->mouse_callback(win, AV_EVENT_MOUSESCROLL, 0, win->mouseX, win->mouseY, 0, (SHORT) HIWORD(msg.wParam) / (double) WHEEL_DELTA);
break;
}
case WM_MOUSEHWHEEL: {
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
win->mouse_callback(win, AV_EVENT_MOUSESCROLL, 0, win->mouseX, win->mouseY, (SHORT) HIWORD(msg.wParam) / (double) WHEEL_DELTA, 0);
break;
}
// TODO: entered, exited
/*
case WM_CHAR: {
// these are the ASCII key codes (not all keys generate them)
keystate * ks = (keystate *)(&msg.lParam);
printf("chardown %d %d\n", msg.wParam, ks->nPrev);
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
win->key_callback(win, AV_EVENT_KEYDOWN, msg.wParam);
break;
}
*/
case WM_SYSKEYDOWN:
case WM_KEYDOWN: {
//wParam has virtual key code http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
win->getMods();
if (msg.wParam == VK_SHIFT) {
win->modifiers_callback(win, AV_EVENT_KEYDOWN, AV_MODIFIERS_SHIFT);
} else if (msg.wParam == VK_CONTROL) {
win->modifiers_callback(win, AV_EVENT_KEYDOWN, AV_MODIFIERS_CTRL);
} else if (msg.wParam == VK_MENU) {
win->modifiers_callback(win, AV_EVENT_KEYDOWN, AV_MODIFIERS_ALT);
} else if (msg.wParam == VK_LWIN || msg.wParam == VK_RWIN) {
win->modifiers_callback(win, AV_EVENT_KEYDOWN, AV_MODIFIERS_CMD);
} else {
win->key_callback(win, AV_EVENT_KEYDOWN, msg.wParam);
}
break;
}
case WM_SYSKEYUP:
case WM_KEYUP: {
//wParam has virtual key code http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
av_WindowW32 * win = (av_WindowW32 *)GetWindowLongPtr(hwnd, GWL_USERDATA);
win->getMods();
if (msg.wParam == VK_SHIFT) {
win->modifiers_callback(win, AV_EVENT_KEYUP, AV_MODIFIERS_SHIFT);
} else if (msg.wParam == VK_CONTROL) {
win->modifiers_callback(win, AV_EVENT_KEYUP, AV_MODIFIERS_CTRL);
} else if (msg.wParam == VK_MENU) {
win->modifiers_callback(win, AV_EVENT_KEYUP, AV_MODIFIERS_ALT);
} else if (msg.wParam == VK_LWIN || msg.wParam == VK_RWIN) {
win->modifiers_callback(win, AV_EVENT_KEYUP, AV_MODIFIERS_CMD);
} else {
win->key_callback(win, AV_EVENT_KEYUP, msg.wParam);
}
break;
}
default: {
//printf("app event\n");
DispatchMessage(&msg);
break;
}
}
// next one:
todo = PeekMessage(&msg,NULL,0,0,PM_REMOVE);
}
return 0;
}
AV_EXPORT av_Window * av_window_create(const char * title, int x, int y, int w, int h) {
if (!title) {
title = "LuaAV";
}
av_WindowW32 * win = new av_WindowW32(title, x, y, w, h);
win->open();
return win;
}
AV_EXPORT int av_window_flush(av_Window * avwindow) {
fprintf(stderr, "NYI\n");
return 0;
}
AV_EXPORT int av_window_sync(av_Window * avwindow, int enable) {
fprintf(stderr, "NYI\n");
return 0;
}
AV_EXPORT int av_window_cursor(av_Window * avwindow, int enable) {
if (enable) {
SetCursor(NULL);
} else {
SetCursor(LoadCursor(NULL, IDC_ARROW));
}
return 0;
}
AV_EXPORT int av_window_fullscreen(av_Window * avwindow, int enable) {
fprintf(stderr, "NYI\n");
return 0;
}
AV_EXPORT int av_window_destroy(av_Window * window) {
fprintf(stderr, "NYI\n");
return 0;
}
// see http://msdn.microsoft.com/en-us/library/dd144901.aspx
AV_EXPORT int av_screens_count() {
fprintf(stderr, "NYI\n");
return 1;
}
AV_EXPORT av_PixelRect av_screens_main() {
LPRECT lpRect;
GetWindowRect(GetDesktopWindow(), lpRect);
av_PixelRect result;
result.x = lpRect->left;
result.y = lpRect->top;
result.width = lpRect->right - lpRect->left;
result.height = lpRect->bottom - lpRect->top; // or the other way?
return result;
}
AV_EXPORT av_PixelRect av_screens_deepest();
AV_EXPORT av_PixelRect av_screens_index(int idx); |
51249a2f367b7c33f65f822b0c517025b1fd4768 | 94edd6be1b8f4a90266a88b90d3dac38e24ab62b | /Parser/Animation.h | 2a99da0456b4d65a250d2b1bf9db64aa7593c7b3 | [] | no_license | Sidnioulz/soda-cd | b06aa2e0339e799024e77e9dabeb18840168c97d | 2aa011ef311ea01bafc6453b657554e20e2d356f | refs/heads/master | 2020-05-17T14:45:08.887722 | 2012-08-27T09:09:00 | 2012-08-27T09:09:00 | 183,770,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,651 | h | Animation.h | #ifndef ACTION_ELEMENT_H
#define ACTION_ELEMENT_H
#include <QtCore>
#include "Action.h"
// ------------------------------------------------- //
/** \brief Classe de gestion d'une animation
* \author Q. Avril, IRISA-INSA de Rennes */
// ------------------------------------------------- //
class Animation : public QObject
{
public:
/** Definit une Animation. */
Animation();
virtual ~Animation();
/** Identifiant de l'action utilisee dans le stockage XML. */
QString getId() const;
/** Identifiantde l'action utilisee dans le stockage XML. */
void setId(QString id);
/** Nom de l'action affichee dans la bibliotheque. */
QString getName() const;
/** Definit le nom de l'action a afficher dans la bibliotheque. */
void setName(QString name);
/** Recuperation de la liste d'actions a effectuer */
std::vector<Action*> getActionList();
/** Ajoute une action a la liste*/
void addActionList(Action* newAction);
/** Numero de la frame courante*/
int getCurrentFrame();
/** Retourne l'action courante*/
Action* getCurrentAction();
/** Numero de la derniere frame de l'action courante */
int getFrameEnd();
/** Remise a 0 des actions */
void resetActions();
/** Incremente les frames de l'animation, true si on change d'action, false sinon */
bool incFrame();
bool incAction(); //incremente les actions de l'animation, si l'on depasse le nombre total d'action, renvoie false et effectue un reset, true sinon
bool incFrame(int n); //incremente l'action courante de n frame a condition que n soit inferieur ou egale a la frame de fin de l'action courante.
/** Retourne le numero de l'action courante */
int getNumCurrentAction();
/** Charge les attributs de l'animation a partir de la source XML. */
void load(QXmlStreamReader* reader);
/** Copy dans this les parametres de anim*/
void clone(Animation * anim);
protected:
void readId(QXmlStreamReader* reader);
void readName(QXmlStreamReader* reader);
void readActionList(QXmlStreamReader* reader);
void readUnknownElement(QXmlStreamReader* reader);
private:
QString m_id; //!< Identifiant de la serie d'action utilise dans le stockage XML
QString m_name; //!< Nom de la liste d'action affiche dans la bibliotheque.
std::vector<Action*> m_listAction; //!< Liste des actions composants l'animation
int m_currentFrame; //!< Numero de la frame courante
size_t m_currentAction; //!< Numero de l'action courante dans m_listAction (dans un soucis de simplification des calculs)
int m_FrameEnd; //!< Numero de la derniere frame de l'action courante. (dans un soucis de simplifications des calculs)
};
/** @} */
#endif |
486a1f794d43e0ea01d39efa7c8c684cb3e554e9 | 963dc5ce2ff5c1e9f3dbc6b674c06f76c2f78b86 | /C++/EVA1_13_OPERACIONES_EN_FRACCIONES_18550725.cpp | 2441f291002db3e872aa058fa41a0e0340f4e5fe | [] | no_license | CarlosRivera07/EVA1 | 312a5dc141053818da63ea097ef46049a183d276 | d331bd2d3b05f43f634f1df39d0c1608c3eeed1c | refs/heads/master | 2020-03-29T17:53:28.094370 | 2018-09-25T00:14:44 | 2018-09-25T00:14:44 | 149,787,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,215 | cpp | EVA1_13_OPERACIONES_EN_FRACCIONES_18550725.cpp | #include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
using namespace std;
// Headers
string toString (double);
int toInt (string);
double toDouble (string);
int main() {
cout << "Introduce el valor del numerador de la fracción 1:" << endl;
int iFN1;
cin >> iFN1;
cout << "Introduce el valor del denominador de la fraccion 1: " << endl;
int iFD1;
cin >> iFD1;
cout << "Introduce el valor del numerador de la fracción 2: " << endl;
int iFN2;
cin >> iFN2;
cout << "Introduce el valor del denominador de la fracción 2: " << endl;
int iFD2;
cin >> iFD2;
cout << "Tus operaciones son: " << endl;
cout << iFN1 << "/" << iFD1 << " + " << iFN2 << "/" << iFD2 << endl;
cout << iFN1 << "/" << iFD1 << " - " << iFN2 << "/" << iFD2 << endl;
cout << iFN1 << "/" << iFD1 << " * " << iFN2 << "/" << iFD2 << endl;
cout << iFN1 << "/" << iFD1 << " / " << iFN2 << "/" << iFD2 << endl;
int iSuma1;
iSuma1 = iFN1 * iFD2 + iFD1 * iFD2;
int iSuma2;
iSuma2 = iFD1 * iFD2;
cout << "El resultado de la suma es : " << endl;
cout << iSuma1 << "/" << iSuma2 << endl;
int iResta1;
iResta1 = iFN1 * iFD2 - iFD1 * iFD2;
int iResta2;
iResta2 = iFD1 * iFD2;
cout << "El resultado de la resta es : " << endl;
cout << iResta1 << "/" << iResta2 << endl;
int iMultiplicacion1;
iMultiplicacion1 = iFN1 * iFN2;
int iMultiplicacion2;
iMultiplicacion2 = iFD1 * iFD2;
cout << "El resultado de la multiplicación es : " << endl;
cout << iMultiplicacion1 << "/" << iMultiplicacion2 << endl;
int iDivision1;
iDivision1 = iFN1 * iFD2;
int iDivision2;
iDivision2 = iFD1 * iFN2;
cout << "El resultado de la división es : " << endl;
cout << iDivision1 << "/" << iDivision2 << endl;
return 0;
}
// The following implements type conversion functions.
string toString (double value) { //int also
stringstream temp;
temp << value;
return temp.str();
}
int toInt (string text) {
return atoi(text.c_str());
}
double toDouble (string text) {
return atof(text.c_str());
}
|
0207f756c45701d3624891a0ffa1ecd7182d33f4 | f136fe7c0ee4afcb441de3f963a2f53b4c28bbdd | /UBrotEngineX/header/graphics/model.h | 5bb33e8be3e021109c243123dc17d44300fb7c45 | [] | no_license | rwarnking/UBrotEngineX | 0066ed00f63f3901430256122e2081e360aba04d | 0fa5bb85d973f599a010a4542c875f88e4426bd9 | refs/heads/master | 2020-03-25T09:08:30.930453 | 2018-08-12T14:01:28 | 2018-08-12T14:01:28 | 143,649,680 | 1 | 0 | null | 2018-08-12T14:01:29 | 2018-08-05T21:41:54 | C++ | UTF-8 | C++ | false | false | 1,359 | h | model.h | ///////////////////////////////////////////////////////////////////////////////////////////////////
// Filename: model.h
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef _MODEL_H_
#define _MODEL_H_
//////////////
// INCLUDES //
//////////////
#include <fstream>
#include <memory>
#include <wrl\client.h>
///////////////////////
// MY CLASS INCLUDES //
///////////////////////
#include "direct3d.h"
#include "vertextypes.h"
namespace ubrot
{
namespace graphics
{
///////////////////////////////////////////////////////////////////////////////////////////////////
// Class name: Model
/// The model class stores all relevant information related to an 3D entity, like the
/// mesh and possible transformation-information.
/// TODO: rename to entity (!NO!) and make data-oriented
///////////////////////////////////////////////////////////////////////////////////////////////////
class Model
{
public:
/**
* A constructor where all the member pointers are initialised to null
*/
Model();
/**
* Copy contructor
* @param other to copy
*/
Model(const Model& other);
~Model();
/**
* @return m_indexCount
*/
int GetIndexCount();
Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexBuffer;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_indexBuffer;
int m_vertexCount, m_indexCount;
};
};
};
#endif |
7b8f6ba27304ec180c2da3d050ffbcb8f6aa4194 | 37a372c78efcdb4f90f143aa67e6d436f8f240e5 | /MobileServer/include/Serial/AtCommand.h | 812ca42201a08d2487b1c9e53e7979d1acc40c28 | [] | no_license | hfz-Halley/hfz-4 | dbd01c7b12f7459a709a9da8576c38c74a4449eb | 11bf0dc7fe941df926e77517da88526b9ef7934c | refs/heads/master | 2021-06-02T10:30:54.747498 | 2020-04-09T09:14:58 | 2020-04-09T09:14:58 | 254,324,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,393 | h | AtCommand.h | #ifndef _ATcommand_H
#define _ATcommand_H
#include "SerialPort.h"
#include <iconv.h>
using Poco::Timespan;
#define rssisize 128
namespace Poco
{
namespace Serial
{
class ATcommand
{
public:
enum signaLevel
{
UNKNOWN = 0, //无信号
POOR,
MODERATE,
GOOD,
GREAT //满格
};
ATcommand();
~ATcommand();
bool AT_SendCmd(char *cmd);
bool AT_Send(char *cmd, char *buffer, int size);
bool AT_ComClose();
bool AT_RecvData(char *rdata, int rsize);
bool Setecho(bool enable);
//RSSI
bool GetRssidata();
int GetCurSignalStrenght();
bool getcpsi();
bool set_cnsmod();
bool setKeepalive();
bool simDetectd();
//check Network registration status
int getSIMStatus();
int getNetworkMode();
int getNetAttachStatus();
//text meassage
bool SetMsmformat();
bool SetCharacter();
bool setphonenum(char *phonenum);
bool sendTextmessage(char *msg);
//PDU meassage
bool SetPDUmode();
bool phonenum_parity_exchange(char *indata, char *outdata);
bool get_sms_center(char *sms_center);
bool get_sms_dest(char *phonenum, char *dest);
bool ConverToUnicode(std::string utf8String, char *outdata);
bool sendPduMessage(std::string phonenum, std::string utf8Msg);
private:
SerialPort *com;
Timespan recvTimeout;
char RssiBuffer[rssisize];
};
} // namespace Serial
} // namespace Poco
#endif
|
5d1ef19992a9859001a3ef11e6a30937eed214d7 | 49775280c31c8dc97907cf1762cb28db107c2887 | /editor/widgets/FileBrowser.h | 691284bf1b9c8a6bf1c80bde454d20e013531937 | [
"MIT"
] | permissive | gan74/Yave | 7e8fe3f9fd530f892a4185fc67109f0426955c2b | acb75c47b8a8e317ef38232173553a4dcb334b3b | refs/heads/master | 2023-08-31T15:27:12.871118 | 2023-08-29T23:03:31 | 2023-08-29T23:03:31 | 59,200,808 | 464 | 27 | MIT | 2021-02-28T13:10:06 | 2016-05-19T11:39:10 | C++ | UTF-8 | C++ | false | false | 3,302 | h | FileBrowser.h | /*******************************
Copyright (c) 2016-2023 Grégoire Angerand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**********************************/
#ifndef EDITOR_WIDGETS_FILEBROWSER_H
#define EDITOR_WIDGETS_FILEBROWSER_H
#include "FileSystemView.h"
#include <functional>
namespace editor {
class FileBrowser final : public FileSystemView {
public:
enum class FilterFlags : u32 {
None = 0x00,
IncludeDirs = 0x01,
AllowNewFiles = 0x02,
};
FileBrowser(const FileSystemModel* filesystem = nullptr);
template<typename F>
void set_selected_callback(F&& func) {
_callbacks.selected = y_fwd(func);
}
template<typename F>
void set_canceled_callback(F&& func) {
_callbacks.canceled = y_fwd(func);
}
void set_selection_filter(std::string_view exts = "", FilterFlags flags = FilterFlags::None);
protected:
void on_gui() override;
void path_changed() override;
core::Result<core::String> entry_icon(const core::String &name, EntryType type) const override;
void entry_clicked(const Entry& entry) override;
private:
bool has_valid_extension(std::string_view filename) const;
bool done(const core::String& filename);
void cancel();
core::String full_path() const;
const FileSystemModel* _filesystem = nullptr;
bool _dirs = false;
bool _allow_new = false;
core::Vector<core::String> _extensions;
core::String _path_buffer;
core::String _name_buffer;
struct {
std::function<bool(const core::String&)> selected = [](const auto&) { return false; };
std::function<bool()> canceled = [] { return true; };
} _callbacks;
};
inline constexpr FileBrowser::FilterFlags operator|(FileBrowser::FilterFlags l, FileBrowser::FilterFlags r) {
return FileBrowser::FilterFlags(u32(l) | u32(r));
}
inline constexpr FileBrowser::FilterFlags operator&(FileBrowser::FilterFlags l, FileBrowser::FilterFlags r) {
return FileBrowser::FilterFlags(u32(l) & u32(r));
}
}
#endif // EDITOR_WIDGETS_FILEBROWSER_H
|
5644a7f12bb8257b586d2fcefcce7ad05a56e763 | 02e07149af0dff9796c2cc8af56a0730d5f4861f | /src/PluginsInspector/PluginsInspectorModel.cpp | 2a09b41bc9c1015cd60ce1419fa83234e51c93f2 | [
"BSD-3-Clause"
] | permissive | loganek/gstcreator | b5817acc271b00d52aaed491f96ab1b03a03ea92 | 619f1a6f1ee39c7c5b883c0a676cd490f59ac81b | refs/heads/master | 2021-01-10T22:14:08.257537 | 2014-07-31T18:14:40 | 2014-07-31T18:14:45 | 15,843,428 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,678 | cpp | PluginsInspectorModel.cpp | /*
* gstcreator
* PluginsInspectorModel.cpp
*
* Created on: 12 sty 2014
* Author: Marcin Kolny <marcin.kolny@gmail.com>
*/
#include "PluginsInspectorModel.h"
#include "Utils/StringUtils.h"
using Glib::RefPtr;
using namespace Gst;
using namespace std;
PluginsInspectorModel::PluginsInspectorModel(FillInspectorMethod method, QObject* parent)
: QAbstractItemModel(parent)
{
root_item = new PluginsInspectorItem(false, string());
RefPtr<Registry> registry = Registry::get();
for (RefPtr<Plugin> plugin : registry->get_plugin_list())
{
if (method == FillInspectorMethod::BY_KLASS)
fill_inspector_by_klass(plugin);
else
fill_inspector_by_plugin(plugin);
}
}
PluginsInspectorModel::~PluginsInspectorModel()
{
delete root_item;
}
PluginsInspectorItem* PluginsInspectorModel::find_parent(PluginsInspectorItem* current_item,
const vector<string>& klasses, size_t klass_it)
{
for (int i = 0; i < current_item->child_count(); i++)
{
if (current_item->child(i)->get_name() == klasses[klass_it])
{
return (klass_it == klasses.size() - 1) ?
current_item->child(i) :
find_parent(current_item->child(i), klasses, klass_it + 1);
}
}
PluginsInspectorItem* ret_item;
for (size_t i = klass_it; i < klasses.size(); i++)
{
current_item->append_child(ret_item = new PluginsInspectorItem(false, klasses[i], current_item));
current_item = ret_item;
}
return ret_item;
}
void PluginsInspectorModel::fill_inspector_by_klass(const RefPtr<Plugin>& plugin)
{
for (auto feature : Registry::get()->get_feature_list(plugin->get_name()))
if (feature && GST_IS_ELEMENT_FACTORY (feature->gobj()))
{
RefPtr<ElementFactory> factory = factory.cast_static(feature);
vector<Glib::ustring> metadata = factory->get_metadata_keys();
if (find(metadata.begin(), metadata.end(), "klass") == metadata.end())
continue;
vector<string> klasses =
StringUtils::split(factory->get_metadata("klass").c_str(), "/");
PluginsInspectorItem* parent = find_parent(root_item, klasses, 0);
parent->append_child(new PluginsInspectorItem(true, factory->get_name(), parent));
}
}
void PluginsInspectorModel::fill_inspector_by_plugin(const RefPtr<Plugin>& plugin)
{
auto plugin_item = new PluginsInspectorItem(false, plugin->get_name().c_str(), root_item);
root_item->append_child(plugin_item);
for (auto feature : Registry::get()->get_feature_list(plugin->get_name()))
if (feature && GST_IS_ELEMENT_FACTORY (feature->gobj()))
plugin_item->append_child(new PluginsInspectorItem(true, feature->get_name().c_str(), plugin_item));
}
int PluginsInspectorModel::columnCount(const QModelIndex& parent) const
{
return 1;
}
QVariant PluginsInspectorModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid() || role != Qt::DisplayRole)
return QVariant();
PluginsInspectorItem *item = static_cast<PluginsInspectorItem*>(index.internalPointer());
return QVariant(item->get_name().c_str());
}
Qt::ItemFlags PluginsInspectorModel::flags(const QModelIndex &index) const
{
PluginsInspectorItem* item = static_cast<PluginsInspectorItem*>(index.internalPointer());
if (!item->is_factory())
return 0;
if (!index.isValid())
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | QAbstractItemModel::flags(index);
}
QVariant PluginsInspectorModel::headerData(int section,
Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return QVariant("Factory name");
return QVariant();
}
QModelIndex PluginsInspectorModel::index(int row, int column, const QModelIndex& parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
PluginsInspectorItem* parent_item;
parent_item = (parent.isValid()) ?
static_cast<PluginsInspectorItem*>(parent.internalPointer()):
root_item;
PluginsInspectorItem *child_item = parent_item->child(row);
return (child_item) ? createIndex(row, column, child_item) :
QModelIndex();
}
QModelIndex PluginsInspectorModel::parent(const QModelIndex& index) const
{
if (!index.isValid())
return QModelIndex();
auto child_item = static_cast<PluginsInspectorItem*>(index.internalPointer());
PluginsInspectorItem* parent_item = child_item->parent();
return (parent_item == root_item) ?
QModelIndex() :
createIndex(parent_item->row(), 0, parent_item);
}
int PluginsInspectorModel::rowCount(const QModelIndex& parent) const
{
if (parent.column() > 0)
return 0;
auto parent_item = (parent.isValid()) ?
static_cast<PluginsInspectorItem*>(parent.internalPointer()) :
root_item;
return parent_item->child_count();
}
|
680aa9d5bcbc58079970fdb0ab28e8e4ae7ccf2a | 7575692fd3800ec48e7c941cdd40210d02ca96d0 | /advanced-cpp-pa3/advanced-cpp-pa3/memPool_t.cpp | 2dc82286c148a12ca3fe9065ce8dbcbdf2371f13 | [] | no_license | husamMaruf/advanced-programming-2011 | bf577a8cc51d53599ed032c22ae31fc15db217fb | db285ae560495bd051400f0e372a2eec2434afe1 | refs/heads/master | 2021-01-10T10:12:46.760433 | 2011-05-21T17:00:12 | 2011-05-21T17:00:12 | 36,380,809 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,433 | cpp | memPool_t.cpp | #include "memPool_t.h"
memPool_t::~memPool_t() {
list<memPage_t*>::iterator it = pages.begin();
while(it != pages.end()) {
delete *it;
it++;
}
pages.clear();
}
int memPool_t::defaultPageSize = 32;
const memPage_t* memPool_t::getLastPage() const {
list<memPage_t*>::const_iterator result = pages.end();
result--;
return *result;
}
void memPool_t::setDefaultPageSize(int pageSize) {
if (pageSize < 1) {
throw ILLEGAL_PAGE_SIZE;
}
defaultPageSize = pageSize;
}
void memPool_t::createPages(int amount) throw(int) {
if (amount < 1) {
throw ILLEGAL_NUMBER_OF_PAGES;
}
for (int i=0; i<amount; i++) {
memPage_t* newPage = new memPage_t(getDefaultPageSize());
pages.push_back(newPage);
if (getNumOfPages() == 1) {
currentPageIter = pages.begin();
}
}
capacity += amount * getDefaultPageSize();
}
void memPool_t::setCurrentPosition(int position) throw(int) {
if (position < 0 || position > actualSize) {
throw ILLEGAL_POSITION;
}
list<memPage_t*>::iterator iter = pages.begin();
memPage_t* currentPage = *iter;
for (currentPosition = 0; currentPosition + currentPage->getPageCapacity() <= position;
currentPosition += currentPage->getPageCapacity(), currentPage = *(++iter));
currentPageIter = iter;
if (currentPageIter != pages.end()) {
currentPage->setPosition(position-currentPosition);
}
currentPosition = position;
} |
d40eeb14a8f959e61ce909f1a1686c6ecd551dba | 57d1d62e1a10282e8d4faa42e937c486102ebf04 | /judges/codeforces/done/486d.cpp | 3bf777d646d066475ffe5bcc0b6861f5433162c7 | [] | no_license | diegoximenes/icpc | 91a32a599824241247a8cc57a2618563f433d6ea | 8c7ee69cc4a1f3514dddc0e7ae37e9fba0be8401 | refs/heads/master | 2022-10-12T11:47:10.706794 | 2022-09-24T04:03:31 | 2022-09-24T04:03:31 | 178,573,955 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 771 | cpp | 486d.cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
#define MAX 2005
#define MOD 1000000007
ll cnt[MAX];
int a[MAX], d, n;
vector<int> g[MAX];
int dfs(int u, int dadu, int root)
{
ll cnt = 1;
for(int i=0; i<(int)g[u].size(); ++i)
{
int v = g[u][i];
if(v == dadu) continue;
if(a[v] == a[root] && v > root) continue;
if(a[v] >= a[root] && a[v]-a[root] <= d) cnt = (cnt * (dfs(v, u, root) + 1))%MOD;
}
return cnt%MOD;
}
int main()
{
scanf("%d %d", &d, &n);
for(int i=0; i<n; ++i) scanf("%d", &a[i]);
for(int i=0; i<n-1; ++i)
{
int u, v; scanf("%d %d", &u, &v);
--u; --v;
g[v].pb(u); g[u].pb(v);
}
int sol = 0;
for(int u=0; u<n; ++u) sol = (sol + dfs(u, -1, u))%MOD;
printf("%d\n", sol);
return 0;
}
|
73131b386cb74f4b01fd3a13ddcef800736ebeeb | c1c90b8747fec449dd625f59d2ab2912153157b8 | /code/win32_game.cpp | 4da86a645171b926c94baa23ce96fb2f1ab7f251 | [] | no_license | nowrie141/game | e070137f902d3748ce308de9b8482f9a594be382 | f135068335ada9066fc7a26a49195f255c1e775b | refs/heads/master | 2022-06-27T08:00:28.396508 | 2020-05-13T17:33:34 | 2020-05-13T17:33:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 275 | cpp | win32_game.cpp | #include <windows.h> //WinMain, MessageBox, ...
//Main
int CALLBACK WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd
){
MessageBox(0, "This is the start game", "Start Game", MB_OK|MB_ICONINFORMATION);
return 0;
} |
5a085d41c4a3f9abe2414e233d197e3887951b17 | 669789a63bd5c01df2e68efa7931e74eb52c1742 | /DDZ_AI/Farmer2PlayerStrategy.h | 9678111831e582cf18f8b4733c8367bfdb11309a | [] | no_license | qq717337/ddzai | d47d4ab3c280a3832abbfd31cf26f8766b812c22 | 9e59e23a6e967ae3a91fb5d234d2bc782ea24eec | refs/heads/master | 2020-03-21T02:26:56.805637 | 2018-03-26T13:39:47 | 2018-03-26T13:39:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,035 | h | Farmer2PlayerStrategy.h | #ifndef _FARMER2PLAYERSTRATEGY_H_
#define _FARMER2PLAYERSTRATEGY_H_
#include "PlayStrategyBase.h"
class Farmer2PlayerStrategy :
public PlayStrategyBase
{
private:
CardStyle takeLord(const CardStyle & lastStyle);
CardStyle takeFarmer(const CardStyle & lastStyle);
public:
~Farmer2PlayerStrategy();
Farmer2PlayerStrategy(const CardVector & cardsValue, GameTable* table);
Farmer2PlayerStrategy(const std::set<uint8_t, CardSetCompare>& cardsValue, GameTable* table);
virtual CardStyle Play() override;
virtual CardStyle Take(EIdentity::EIdentity_ lastIdentity, const CardStyle & lastStyle)override;
virtual bool OtherCanTake(const CardStyle& style)const override;
virtual uint8_t OtherBiggestCardValue(int compareCount)const override;
virtual bool IsSafeSituation(ESituationSafeLevel::ESituationSafeLevel_ level, int param1, void* param2 = nullptr) const override;
virtual std::vector<ECardStyle::ECardStyle_> AvoidPlayStyle();
virtual EIdentity::EIdentity_ Identity()const override;
virtual void Init()override;
};
#endif
|
fcfc1a5d7a63b44749a41f90876d59dd245e0ccd | 69cb5b4448c999899a4fed2dc62fc36c304ed1ba | /Задание 2(стек, множество)/ClassSteck/ClassSteck/main.cpp | 7fdc278ef76d675e57dde3a5fea4d8ed3d78bfee | [] | no_license | Segrey1989/C_STEP_tasks | f49b4074ee0bd9cef68d2b5e5c588c55aa64b755 | 29522e836731c6aae4c3dc275988cb273c3717a5 | refs/heads/master | 2020-03-31T03:55:20.833671 | 2018-10-07T08:22:15 | 2018-10-07T08:22:15 | 151,884,311 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | cpp | main.cpp | #include "Header.h"
int main() {
Steck a(2);
Steck c;
// a.push(10);
// a.push(4);
// std::cout << a.pop() << "\n";
c = a; // присвоили c размер и содержимое a
// дополнили c
c.push(5);
c.push(6);
c.push(7);
//дополнили a
a.push(5);
// инициализировали стек b через конструктор копирования
Steck b(a);
std::cout <<"Значение top стека с: "<< c.Get_top() << " \n";
std::cout <<"Извлекли из с: " <<c.pop() << " \n";
std::cout <<"Значение top стека с: "<< c.Get_top() << " \n\n";
std::cout <<"Значение top стека a: "<< a.Get_top() << " \n";
std::cout <<"Значение top стека b: "<< b.Get_top() << " \n\n";
//std::cout << a.Get_size() << "\n";
return 0;
}
|
c245a0e6e1012f2bf0e27e085ee43277ab839eb2 | 75634c83b641f2b3c99a7cdf5d96f12232f4ffee | /NetTeam4/NetTeam4/src/Math/Math.h | c5cc4574bb2562d59376fbf9309957575c73d3d7 | [] | no_license | molvin/NetworkTeam4 | ee60d56a6081b918ab40df832176a53bb72bace8 | 5c6b0a888ed5c78ae0df60622b01b51e581c2318 | refs/heads/master | 2022-03-30T22:47:34.992606 | 2020-02-05T13:22:15 | 2020-02-05T13:22:15 | 233,609,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,850 | h | Math.h | #pragma once
#include <cmath>
struct Vector2
{
float X;
float Y;
Vector2() : X(0.0f), Y(0.0f) { }
Vector2(float x, float y) : X(x), Y(y) { }
Vector2(float value) : X(value), Y(value) { }
Vector2 operator+(Vector2 otherVec) const
{
return Vector2(X + otherVec.X, Y + otherVec.Y);
}
Vector2 operator-(Vector2 otherVec) const
{
return Vector2(X - otherVec.X, Y - otherVec.Y);
}
Vector2 operator*(float scalar) const
{
return Vector2(X * scalar, Y * scalar);
}
Vector2 operator/(float scalar) const
{
return Vector2(X / scalar, Y / scalar);
}
Vector2& operator+=(const Vector2& otherVec)
{
*this = *this + otherVec;
return *this;
}
Vector2& operator-=(const Vector2& otherVec)
{
*this = *this - otherVec;
return *this;
}
Vector2& operator*=(float scalar)
{
*this = *this * scalar;
return *this;
}
Vector2& operator/=(float scalar)
{
*this = *this / scalar;
return *this;
}
float magnitude()
{
return std::sqrt(X * X + Y * Y);
}
void Normalize()
{
Vector2 vec = *this / magnitude();
X = vec.X;
Y = vec.Y;
}
Vector2 Normalized()
{
return *this / magnitude();
}
static float Dot(const Vector2& lhs, const Vector2& rhs)
{
return lhs.X * rhs.X + lhs.Y * rhs.Y;
}
static Vector2 Zero;
static Vector2 Right;
static Vector2 Up;
static Vector2 One;
};
namespace mathHelper
{
inline float clamp(float value, float min, float max)
{
return value < min ? min : value > max ? max : value;
}
inline float lerp(float min, float max, float value)
{
return (max - min) * value + min;
}
inline float abs(float value)
{
return value < 0.0f ? -value : value;
}
inline Vector2 lerp(Vector2 min, Vector2 max, float value)
{
return Vector2(lerp(min.X, max.X, value), lerp(min.Y, max.Y, value));
}
inline int sign(float value)
{
return value < 0.0f ? -1 : 1;
}
}
|
3369b188678256e75e796d0d8d436a442b17deb1 | 872a54da02329a4286f5ad13a6ee5489d46d2ea8 | /SnowFall/Include/Math/Rectangle.h | 0feb12cb1d6b3ee8c50b2d85910d19bd7fc1dcc9 | [] | no_license | James-Emmett/DirectVolumeRenderer | 3e729dabecf9261e725e7b1976b39ab105923e7f | ebe91035644191bfc3c8e39ea7092d77a3d64459 | refs/heads/master | 2023-01-02T05:00:01.210496 | 2020-10-29T16:44:04 | 2020-10-29T16:44:04 | 291,761,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 758 | h | Rectangle.h | #pragma once
#include "Vector2.h"
template<typename T>
class Rect
{
public:
T X, Y, Width, Height;
public:
Rect(T x, T y, T width, T height)
{
X = x; Y = y;
Width = width; Height = height;
}
T Top()const
{
return Y + Height;
}
T Bottom()const
{
return Y;
}
T Left()const
{
return X;
}
T Right()const
{
return X + Width;
}
bool Intersects(const Rect<T>& other)const
{
if (other.Right() < Left() || other.Left() > Right()) { return false; }
if (other.Top() < Bottom() || other.Bottom() > Top()) { return false; }
return true;
}
bool Contains(Vector2 point)const
{
if (point.x < Left() || point.x > Right()) { return false; }
if (point.y < Bottom() || Bottom() > point.y) { return false; }
return true;
}
}; |
a4e699f11a042c0ef926496382a30adc31bd47bc | 120a14ffaff6544f2144f2de1895ac4a114a4107 | /src/framework/blockinggridrule.hpp | f036104bf13608b70adae2e9373170c699fb20ad | [] | no_license | xill/engine | fd40152fd4370c84d46e7e2dc299c929d714e4b3 | 0e0e4cab1ed92c313cc7b9f0934409668699543a | refs/heads/master | 2016-09-05T17:49:37.628602 | 2012-04-22T20:02:36 | 2012-04-22T20:02:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 864 | hpp | blockinggridrule.hpp | #ifndef BLOCK_GRID_RULE_H
#define BLOCK_GRID_RULE_H
#include "gridrule.h"
class BlockingGridRule : public GridRule
{
private:
public:
/**
* Returns true if all grid access should be denied.
*/
bool ignoreAll();
/**
* Returns true projectiles are allowed access.
*
* This rule is superceded by ignoreAll -funtion.
*/
bool allowProjectile();
/**
* Returns true grid objects are allowed access.
*
* This rule is superceded by ignoreAll -funtion.
*/
bool allowObject();
/**
* Return true if given object id is black listed.
*/
bool isBlackListed(const int objectid);
/**
* Blacklist the object id. Will result in isBlackListed
* returning true for the same id.
*/
void blackListId(const int objectid);
/**
* Remove object id blacklisting.
*/
void deListId(const int objectid);
};
#endif // BLOCK_GRID_RULE_H
|
0c74003bcd2d43dc7392f39fb3a63283d507f6e7 | ecc7a6e4f1f0847d74aa719480ec5402c65f5109 | /MiAPR_SelfLearning/ChooseVectorsCountDialog.h | 300f3a1f41ce2625fe1fe0594c73ed52b0cf94fc | [] | no_license | VladimirZhdan/MiAPR_SelfLearning | 2060730b7ec40d8f46c25a9a07a417664bf892c1 | fd41e4433f7f9bcf7968000b6a45623bd7c479b6 | refs/heads/master | 2021-01-11T14:24:26.066707 | 2017-02-08T22:11:05 | 2017-02-08T22:11:05 | 81,381,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 327 | h | ChooseVectorsCountDialog.h | #pragma once
#include "Dialog.h"
#include "resource.h"
#include <CommCtrl.h>
class ChooseVectorsCountDialog : public Dialog
{
public:
ChooseVectorsCountDialog(HWND hWndParent);
~ChooseVectorsCountDialog();
private:
static INT_PTR CALLBACK ChooseVectorsCountProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
};
|
c3281a731c83376b60dea5d9bca973e5f68c0dd9 | 8467ccd8da6f120d2cd9ad00e8352b359b10fb7d | /UThread.h | fc26173ac4e4ea2437520269f440513e62ad18a7 | [] | no_license | matan188/OS_ex2 | 6420475df06d2d30fd463ca1a158bb6910d8cb8e | 810e55c837addd81f1c5c57a709866ccdcd1006f | refs/heads/master | 2021-04-28T23:04:52.117364 | 2017-01-03T14:22:05 | 2017-01-03T14:22:05 | 77,740,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 983 | h | UThread.h |
#ifndef UThread_h
#define UThread_h
#include <setjmp.h>
#include <stdio.h>
#include "uthreads.h"
#include <signal.h>
/* States for defining a thread's state */
enum state {ready, sleeping, running, blocked};
/**
* Class for threads objects
*/
class UThread {
public:
UThread();
UThread(int tid, void (*f)(void));
int getQuantumsUntilWakeup() { return _quantumsUntilWakeup; };
void setQuantumsUntilWakeup(int sleepingTime) { _quantumsUntilWakeup =
sleepingTime; };
long unsigned getQuantumsCount() { return _quantumsCount; };
void updateQuantumCount() { _quantumsCount++; };
sigjmp_buf * getEnvPtr(){ return &_env; };
void setState(state s) { _state = s; };
state getState() { return _state; };
private:
sigjmp_buf _env;
char _stack[STACK_SIZE];
int _tid;
state _state;
int _quantumsUntilWakeup;
long unsigned _quantumsCount;
};
#endif /* UThread_h */
|
acf8ddb255280813074a82fbf72f6a0916eb5e75 | e7846c059bda90df06ea217aa48c56934ff4550a | /componentmanager.hpp | d27a64ba58f24206e4067d7182d627e21a3399d8 | [] | no_license | LeVirus/Entity-Component-System-LV | 35485a15d9a014dc401fec92acd9194716973126 | c28ea48e251e4235140e352e1d02d10bd1d87ea4 | refs/heads/master | 2020-06-04T05:00:22.495115 | 2019-07-19T16:46:46 | 2019-07-19T16:46:46 | 27,675,207 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,585 | hpp | componentmanager.hpp | #ifndef COMPONENTMANAGER_H
#define COMPONENTMANAGER_H
#include "component.hpp"
#include <vector>
#include <memory>
namespace ecs
{
class Engine;
/**
* @brief La classe ComponentManager gère tous les composants.
* Les composants de toutes les entités sont stockés dans un tableau.
* Leurs emplacements sont déterminés par le numéro de leur entité associée ainsi que par leurs type(associé à une énumération).
*/
class ComponentManager
{
private:
Engine *mptrEngine = nullptr;
std::vector<std::unique_ptr<Component>> mVectComponent;
static unsigned int muiNumberComponent;
public:
ComponentManager();
void updateComponentFromEntity();
void linkEngineToComponentManager(Engine *ptrEngine);
bool bVerifComponentInstanciate(unsigned int uiNumEntity, unsigned int uiTypeComponent);
void addEmplacementsForExternComponent(unsigned int uiNumberExternalComponent);
void instanciateExternComponent(unsigned int uiNumEntity, std::unique_ptr<Component> ptrComp);
static unsigned int getNumberComponent();
/**
* @brief ComponentManager::searchComponentByType
* Fonction renvoyant la référence du contenant recherché.
* Une vérification est effectué avant l'envoie:
* -Les paramètres renvoie bien a une case du tableau(pas de dépassement de mémoire).
* -Le paramètre renvoie bien à une case contenant un composant instancié.
* La fonction renvoie le composant avec un static_cast.
* @param uiNumEntity le numéro de l'entité à qui appartient le composant recherché.
* @param uiTypeComponent le type de composant a rechercher.
* @return Un pointeur vers le composant demandé, NULL en cas de paramètre invalide ou
* si le composant demandé n'est pas instancié.
*/
template < typename componentTemplate >
componentTemplate * searchComponentByType(unsigned int uiNumEntity, unsigned int uiTypeComponent)
{
if((uiNumEntity * ComponentManager::getNumberComponent() + uiTypeComponent) >= mVectComponent.size() ||
! mVectComponent[uiNumEntity * ComponentManager::getNumberComponent() + uiTypeComponent])return nullptr;
static_assert(std::is_base_of< Component, componentTemplate >(), "componentTemplate n'est pas un composant");
//récupérer un pointeur vers l'objet contenu dans le unique_ptr
return static_cast<componentTemplate*>(mVectComponent[uiNumEntity * ComponentManager::getNumberComponent()
+ uiTypeComponent].get());
}
};
}//fin namespace
#endif // COMPONENTMANAGER_H
|
69de7e60dba0398e92c5b893bc5e180157ef215b | 9f6de4fbcac0548ccc8a72af54c08a2d0012b067 | /cpp/openFrameworks/openFrameworksExamples/windows/ofxMaximExampleVS2010-OF0072/src/testApp.cpp | d1d2e833cc58d5ac9da01719fc78a8cf905da3d7 | [
"MIT"
] | permissive | micknoise/Maximilian | a1aa5aafe9f3ab307b7c133f1051baf800bb6a4c | 6bad5f5945497f07946af6d4b31f3fbc7bfc694c | refs/heads/master | 2023-08-26T20:01:25.604464 | 2023-05-24T09:57:09 | 2023-05-24T09:57:09 | 2,254,934 | 1,412 | 287 | MIT | 2023-05-24T09:57:10 | 2011-08-23T12:22:17 | C++ | UTF-8 | C++ | false | false | 1,884 | cpp | testApp.cpp | #include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
maxiSettings::setup(44100, 2, 512);
ofSoundStreamSetup(maxiSettings::channels,0,this,maxiSettings::sampleRate, maxiSettings::bufferSize, 4);
ofSoundStreamStart();
}
//--------------------------------------------------------------
void testApp::update(){
}
//--------------------------------------------------------------
void testApp::draw(){
}
void testApp::audioRequested( float * output, int bufferSize, int nChannels ){
for(int i=0; i < bufferSize; i+=2) {
float sawFreq = maxiMap::linexp(mouseX,0, ofGetWidth(), 20, 20000);
float w = sawOsc.saw(sawFreq);
w = dist.atanDist(w, 10);
float filtFreq = maxiMap::linexp(mouseY,0, ofGetHeight(), 20, 20000);
w = filt.hires(w, filtFreq, 0.4);
output[i] = output[i+1] = w;
}
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){
} |
5a6e512cf94cc702c29ff4a6c901ab0ffb358dce | 6d0a2194bfb230c3333329be0779382a358934f1 | /Programmers/level1/level1_1(완주하지_못한_선수).cpp | 0983e7486afc6a349819c5b71dc224e60d81208b | [] | no_license | hsh07260/Algoritm_study | e275463437f4d627c62ab1c231472ba9add3f3ba | f9d31d4036c314af8cca4ddc5663203c91077c09 | refs/heads/master | 2020-08-06T22:04:02.320857 | 2020-04-04T11:11:46 | 2020-04-04T11:11:46 | 213,173,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,827 | cpp | level1_1(완주하지_못한_선수).cpp | //Programers 완주하지 못한 선수 문항.
//해시 관련 문제
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
string solution_2(vector<string> participant, vector<string> completion) {
//3개의 테스트케이스 모두 통과후 정확성,효율성 통과
int participant_sz = participant.size();
int completion_sz = completion.size();
string answer = "";
//완주자가 (참가자-1)이기때문에 sorting하여 비교하면 될 것으로 판단.
//vector를 sorting 후 안맞는 이름을 바로 출력
//원본 데이터의 손상없이 결과얻기 가능
sort(participant.begin(), participant.end());
sort(completion.begin(), completion.end());
for (int i = 0; i < completion_sz; i++) {
if (participant[i] != completion[i]) {
answer = participant[i];
return answer;
}
}
answer = participant[participant_sz-1];
return answer;
}
string solution_1(vector<string> participant, vector<string> completion) {
//3개의 테스트 케이스는 통과하지만, 효율성에서 탈락.
//직관적으로 바로 비교하여 참가자와 완주자가 같으면 완주자 목록에서 제외
//참가자가 남거나 일치하는 완주자가없으면 결과로 출력
//(vector).erase로 인해 원본 데이터 손상생김
int participant_sz = participant.size();
string answer = "";
//for 문을 통해 참가자 한명씩 비교
for (int i = 0; i < participant_sz; i++) {
//완주자가 남고 비교할 참가자가 남은경우에 비교
int completion_sz = completion.size();
for (int j = 0; j < completion_sz; j++) {
if (participant[i] == completion[j]) {
completion.erase(completion.begin() + j);
break;
}
if (j == completion_sz - 1) {
answer = participant[i];
}
}
}
return answer;
}
|
480731c5a1af989894c78dd3bac0b948607a9fad | 6d389e502e9448de5eb6f8ae590a3d98886ddb4c | /V1.0_water_saver/V1.0_water_saver.ino | 4e45884b39cf1a8d1db0fef48be9988f6624e3ad | [] | no_license | Raaghav932/arduino_projects | b1cccb0e09e41728a84f844e5154447bfcf02cac | 254f116597293022c954fdbaa193d7ff38ec54dd | refs/heads/master | 2022-04-24T16:00:43.594133 | 2020-04-12T02:56:36 | 2020-04-12T02:56:36 | 254,986,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,900 | ino | V1.0_water_saver.ino | const int RED_PIN = 6;
const int GREEN_PIN = 5;
const int BLUE_PIN = 3;
int BUTTON_ONE = 13;
int BUTTON_TWO = 12;
int SPEAKER = 9;
int TEMP = A0;
int TURNTABLE = A4;
int delay2 = 30;
int brightness = 0;
int fadeAmount = 5;
float turnValue = 0;
float turnValue2 = 0;
int BUTTON_TWO_STATE = 1;
float voltage, degreesC, degreesF;
int c = 6;
void setup()
{
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
pinMode(BUTTON_ONE, INPUT);
pinMode(BUTTON_TWO, INPUT);
pinMode(SPEAKER, OUTPUT);
pinMode(TEMP, INPUT);
pinMode(TURNTABLE, INPUT);
Serial.begin(9600);
State_1(9);
}
void loop()
{
}
int State_1 (int ignore)
{
//turnValue = analogRead(TURNTABLE);
int button1State = digitalRead(BUTTON_ONE);
if(button1State == HIGH)
{
digitalWrite(RED_PIN, HIGH);
State_2(9);
}
while(button1State == HIGH)
{
/*digitalWrite(RED_PIN, HIGH);
analogWrite(GREEN_PIN, brightness);
brightness = brightness + fadeAmount;
if(brightness < 0 || brightness >= 255)
{
fadeAmount = -fadeAmount;
}*/
}
}
int State_2(int ignnore)
{
//Serial.write("in s 2");
turnValue = analogRead(TURNTABLE);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(RED_PIN, LOW);
digitalWrite(BLUE_PIN, HIGH);
digitalWrite(RED_PIN, LOW);
if (c==6)
{
voltage = getVoltage(TEMP);
degreesC = (voltage - 0.5) * 100.0;
degreesF = degreesC * (9.0/5.0) + 32.0;
//Serial.println(degreesF); 69
turnValue = analogRead(TURNTABLE * 0.0);
turnValue = turnValue * 0.093;
turnValue2 = turnValue + 5;
//Serial.println(turnValue);
digitalWrite(RED_PIN,LOW);
digitalWrite(BLUE_PIN,LOW);
digitalWrite(GREEN_PIN,HIGH);
delay(1000);
//Serial.print("done");
if(degreesF >= turnValue && degreesF <= turnValue2)
{
digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN,LOW);
State_3(9);
//Serial.print("done");
}
}
}
int State_3(int ignnnore)
{
if(ignnnore == 9)
{
digitalWrite(GREEN_PIN,LOW);
digitalWrite(RED_PIN,HIGH);
digitalWrite(BLUE_PIN,LOW);
//Serial.println("State_3");
ignnnore = 10;
}
while (ignnnore==10)
{
tone(9,2000,2500);
tone(9,4000,2500);
delay(10000);
digitalWrite(GREEN_PIN,HIGH);
while(true)
{
digitalWrite(GREEN_PIN,LOW);
}
}
if(BUTTON_TWO_STATE == LOW)
{
State_4(9);
digitalWrite(GREEN_PIN,LOW);
digitalWrite(BLUE_PIN,LOW);
digitalWrite(RED_PIN,LOW);
}
}
int State_4(int ignnnnore)
{
if(true)
{
digitalWrite(GREEN_PIN,LOW);
digitalWrite(BLUE_PIN,LOW);
Serial.println("done");
digitalWrite(RED_PIN,LOW);
}
}
float getVoltage(int pin)
{
return (analogRead(A4) * 0.004882814);
}
|
1f0090db7c48274a313734ab23b842833e653d13 | 6f224b734744e38062a100c42d737b433292fb47 | /libc/src/string/memory_utils/inline_memmove.h | c520b6f4de0cdff4295026b4b6221ee900315f08 | [
"NCSA",
"Apache-2.0",
"LLVM-exception"
] | permissive | smeenai/llvm-project | 1af036024dcc175c29c9bd2901358ad9b0e6610e | 764287f1ad69469cc264bb094e8fcdcfdd0fcdfb | refs/heads/main | 2023-09-01T04:26:38.516584 | 2023-08-29T21:11:41 | 2023-08-31T22:16:12 | 216,062,316 | 0 | 0 | Apache-2.0 | 2019-10-18T16:12:03 | 2019-10-18T16:12:03 | null | UTF-8 | C++ | false | false | 1,626 | h | inline_memmove.h | //===-- Memmove implementation ----------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_MEMMOVE_H
#define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_MEMMOVE_H
#include <stddef.h> // size_t, ptrdiff_t
#if defined(LIBC_TARGET_ARCH_IS_X86)
#include "src/string/memory_utils/x86_64/inline_memmove.h"
#define LIBC_SRC_STRING_MEMORY_UTILS_MEMMOVE inline_memmove_x86
#elif defined(LIBC_TARGET_ARCH_IS_AARCH64)
#include "src/string/memory_utils/aarch64/inline_memmove.h"
#define LIBC_SRC_STRING_MEMORY_UTILS_MEMMOVE inline_memmove_aarch64
#elif defined(LIBC_TARGET_ARCH_IS_ANY_RISCV)
#include "src/string/memory_utils/riscv/inline_memmove.h"
#define LIBC_SRC_STRING_MEMORY_UTILS_MEMMOVE inline_memmove_riscv
#elif defined(LIBC_TARGET_ARCH_IS_ARM) || defined(LIBC_TARGET_ARCH_IS_GPU)
#include "src/string/memory_utils/generic/byte_per_byte.h"
#define LIBC_SRC_STRING_MEMORY_UTILS_MEMMOVE inline_memmove_byte_per_byte
#else
#error "Unsupported architecture"
#endif
namespace __llvm_libc {
LIBC_INLINE void inline_memmove(void *dst, const void *src, size_t count) {
LIBC_SRC_STRING_MEMORY_UTILS_MEMMOVE(reinterpret_cast<Ptr>(dst),
reinterpret_cast<CPtr>(src), count);
}
} // namespace __llvm_libc
#endif /* LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_MEMMOVE_H */
|
fcf8356e4c0b37e09f9399da4089018b0fd48b06 | 75471b94fc26505298c2a862c8ab68db020f2c7b | /atoi.cpp | 50eab6221bb631c8e423269c096cb0c4a0ee771a | [] | no_license | meichy/xd | 8f1190f8c36ae001a0690c34e4ebcbca60e9245e | a301194bec3adfb6e7f498a3af632d61c37d3a24 | refs/heads/main | 2023-08-30T05:34:14.204500 | 2021-10-30T07:15:53 | 2021-10-30T07:15:53 | 422,811,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | cpp | atoi.cpp | #include <ctype.h>
#include <stdio.h>
int atoi(char s[])
{
int i,n,sign;
for(i=0;isspace(s[i]);i++)
;
sign=(s[i]=='-')?-1:1;
if(s[i]=='+'||s[i]=='-')
i++;
for(n=0;isdigit(s[i]);i++)
n=10*n+(s[i]-'0');
return sign*n;
}
int main()
{
char a[999];
scanf("%s",&a);
printf("integer=%d",atoi(a));
} |
8ce260d65246d35b250c0e142ddf614ed8b6c35e | 6325638953353358c7243c6f292bbc55f6427d8d | /CodeChef/Beginner/JAG.cpp | 97511c510689bbcc7e1ce42db1cd4d66b9eab86a | [] | no_license | bashu22tiwari/BashuTiwari-CP | 60fc93488569c4e0cbc217f53aecd1bf38cc486f | 99c1d9ea4ce7cb6114508683635d62f04dbd64b8 | refs/heads/main | 2023-08-13T04:43:24.578329 | 2021-09-27T20:37:53 | 2021-09-27T20:37:53 | 340,102,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 712 | cpp | JAG.cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int tt;
cin >> tt;
while(tt--){
long long int n;
cin >> n;
long long int i=0;
unordered_map<long long int,long long int> mp;
for(long long int j=0 ; j<n ; j++){
long long temp;
cin >> temp;
temp -=i ;
i++;
if(mp.find(temp)==mp.end()){
mp[temp]=1;
}
else{
mp[temp]++;
}
}
if(mp.size()==1){
cout << n << "\n";
}
else{
cout << "1\n";
}
}
} |
72e5b2a3795f7277f0cce5a9cee0f7d9ff5cedf9 | c89fc569241ea9598d6fd009db484074fc466ee4 | /src/apps/qutils/canvas.cpp | 2815c75cca5bca527d0b78aa770b0e2ec8254462 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | namica/vizzu-lib | abcfc05eecd9bf95d0e90bab832a3371eecf0cc0 | 4d9473147ff0082e811234ad4c17c95e2eb0bdd7 | refs/heads/main | 2023-08-28T12:07:30.170977 | 2021-10-24T11:59:03 | 2021-10-24T11:59:03 | 418,309,880 | 0 | 0 | Apache-2.0 | 2021-10-18T02:00:55 | 2021-10-18T02:00:55 | null | UTF-8 | C++ | false | false | 8,395 | cpp | canvas.cpp | #include "canvas.h"
#include <QDebug>
#include <QFontMetrics>
#include <QGuiApplication>
#include <QLinearGradient>
#include <QScreen>
using namespace Vizzu;
class PixmapCanvas : public Canvas {
public:
PixmapCanvas(int width, int height)
: pixmap(width, height)
{
pixmap.fill(Qt::transparent);
init(&pixmap);
}
~PixmapCanvas()
{
if (painter.isActive()) painter.end();
}
const QPixmap &getPixmap() const { return pixmap; }
private:
QPixmap pixmap;
};
static void initFont(QFont &font)
{
font.setHintingPreference(QFont::PreferFullHinting);
font.setStyleStrategy(QFont::PreferAntialias);
}
QColor toQColor(const Gfx::Color &color) {
return QColor(color.getRedByte(),
color.getGreenByte(),
color.getBlueByte(),
color.getAlphaByte());
}
QPointF toQPoint(const Geom::Point &point)
{
return QPointF(point.x, point.y);
}
QPoint toQPointInt(const Geom::Point &point)
{
return QPoint((int)point.x, (int)point.y);
}
Geom::Point fromQPointF(const QPointF &point)
{
return Geom::Point(point.x(), point.y());
}
QLineF toQLine(const Geom::Line &line)
{
return QLineF(toQPoint(line.begin), toQPoint(line.end));
}
QSizeF toQSize(const Geom::Size &size)
{
return QSizeF(size.x, size.y);
}
QSize toQSizeInt(const Geom::Size &size)
{
return QSize((int)size.x, (int)size.y);
}
Geom::Size fromQSizeF(const QSizeF &size)
{
return Geom::Size(size.width(), size.height());
}
QRectF toQRect(const Geom::Rect &rect)
{
return QRectF(toQPoint(rect.pos), toQSize(rect.size));
}
QRect toQRectInt(const Geom::Rect &rect)
{
return QRect(toQPointInt(rect.pos), toQSizeInt(rect.size));
}
Geom::Rect fromQRectF(const QRectF &rect)
{
return Geom::Rect(fromQPointF(rect.topLeft()), fromQSizeF(rect.size()));
}
BaseCanvas::BaseCanvas(QPaintDevice *device)
{
if (device) init(device);
}
BaseCanvas::~BaseCanvas()
{
if (painter.isActive()) painter.end();
}
void BaseCanvas::init(QPaintDevice *device)
{
if(!painter.isActive()) painter.begin(device);
painter.setRenderHint(QPainter::Antialiasing);
painter.setRenderHint(QPainter::TextAntialiasing);
font = painter.font();
initFont(font);
painter.setFont(font);
auto pen = painter.pen();
pen.setWidth(0);
painter.setPen(pen);
}
std::shared_ptr<Gfx::ICanvas> BaseCanvas::createCanvas(int width,
int height)
{
return std::make_shared<PixmapCanvas>(width, height);
}
void BaseCanvas::setBrushColor(const Gfx::Color &color)
{
brush = QBrush(toQColor(color));
painter.setBrush(brush);
}
void BaseCanvas::setLineColor(const Gfx::Color &color)
{
linePen = colorToPen(color);
painter.setPen(linePen);
}
void BaseCanvas::setLineWidth(double width)
{
linePen.setWidthF(width);
painter.setPen(linePen);
}
void BaseCanvas::beginPolygon()
{
painter.setPen(linePen);
polygon = QPainterPath();
}
void BaseCanvas::addPoint(const Geom::Point &point)
{
if (polygon.elementCount() == 0)
polygon.moveTo(toQPoint(point));
else
polygon.lineTo(toQPoint(point));
}
void BaseCanvas::addBezier(const Geom::Point &control0,
const Geom::Point &control1,
const Geom::Point &endPoint)
{
polygon.cubicTo(toQPoint(control0),
toQPoint(control1),
toQPoint(endPoint));
}
void BaseCanvas::endPolygon()
{
painter.drawPath(polygon);
polygon = QPainterPath();
}
Geom::Rect BaseCanvas::getClipRect() const
{
if (painter.hasClipping())
return fromQRectF(painter.clipBoundingRect());
else
return Geom::Rect(Geom::Point(),
Geom::Size(painter.device()->width(),
painter.device()->height()));
}
void BaseCanvas::setClipRect(const Geom::Rect &rect)
{
painter.setClipping(true);
painter.setClipRect(toQRect(rect));
}
void BaseCanvas::setClipCircle(const Geom::Circle &circle)
{
QPainterPath path;
path.addEllipse(toQRect(circle.boundary()));
painter.setClipPath(path);
}
void BaseCanvas::setClipPolygon() {
painter.setClipping(true);
painter.setClipPath(polygon);
polygon = QPainterPath();
}
void BaseCanvas::setFont(const Gfx::Font &newFont)
{
auto font = painter.font();
font.setPixelSize((int)newFont.size);
if (!newFont.family.empty())
font.setFamily(QString::fromStdString(newFont.family));
font.setWeight(
newFont.weight == Gfx::Font::Weight::Bold() ? QFont::Bold :
newFont.weight == Gfx::Font::Weight::Normal() ? QFont::Normal :
(int)newFont.weight / 10);
font.setStyle(
newFont.style == Gfx::Font::Style::italic ? QFont::StyleItalic :
newFont.style == Gfx::Font::Style::oblique ? QFont::StyleOblique :
QFont::StyleNormal);
painter.setFont(font);
}
void BaseCanvas::setTextColor(const Gfx::Color &color)
{
textPen = colorToPen(color);
painter.setPen(textPen);
}
void BaseCanvas::beginDropShadow() {
}
void BaseCanvas::setDropShadowBlur(uint64_t) {
}
void BaseCanvas::setDropShadowColor(const Gfx::Color &) {
}
void BaseCanvas::setDropShadowOffset(const Geom::Point &) {
}
void BaseCanvas::endDropShadow() {
}
void BaseCanvas::circle(const Geom::Circle &circle)
{
painter.setPen(linePen);
painter.drawEllipse(toQPoint(circle.center),
circle.radius,
circle.radius);
}
void BaseCanvas::line(const Geom::Line &line)
{
painter.drawLine(toQLine(line));
}
void BaseCanvas::rectangle(const Geom::Rect &rect)
{
painter.setPen(linePen);
painter.drawRect(toQRect(rect));
}
void BaseCanvas::text(const Geom::Rect &rect,
const std::string &text)
{
painter.setPen(textPen);
painter.drawText(toQRect(rect), Qt::AlignLeft, QString::fromStdString(text));
}
void BaseCanvas::setBrushGradient(const Geom::Line &line, const Gfx::ColorGradient &gradient)
{
QLinearGradient qGradient(toQPoint(line.begin), toQPoint(line.end));
for (auto stop: gradient.stops) {
qGradient.setColorAt(stop.pos, toQColor(stop.value));
}
painter.setBrush(QBrush(qGradient));
}
int BaseCanvas::loadSvgImage(const Gfx::Svg &/*svg*/)
{
return 0;
}
int BaseCanvas::loadPixMapImage(const Gfx::PixMapView &/*pixmap*/)
{
return 0;
}
void BaseCanvas::dropImage(int /*imageId*/)
{}
void BaseCanvas::drawImage(int /*imageId*/, const Geom::Rect &/*boundary*/, double /*opacity*/)
{
// todo: separated image loading and drawing through ICanvas interface
// The imageId parameter comes from the further ImageLoader component.
// The loading phase must be implemeted there, the drawing part remains
// in this function.
/*QImage image;
if (pixMap.grayscale)
{
image = QImage(pixMap.size.x, pixMap.size.y,
QImage::Format_ARGB32);
for (auto y = 0u; y < pixMap.size.y; y++) {
auto *in = (uint16_t*)pixMap.scanLine(y);
auto *out = (QRgb*)image.scanLine(y);
for (auto x = 0u; x < pixMap.size.x; x++)
{
uint8_t value = in[x];
uint8_t alpha = in[x] >> 8;
out[x] = qRgba(value, value, value, alpha);
}
}
}
else
{
image = QImage((unsigned char*)pixMap.data,
(int)pixMap.size.x, (int)pixMap.size.y,
QImage::Format_RGBA8888);
}
auto qpixmap = QPixmap::fromImage(image);
if (opacity < 1.0) painter.setOpacity(opacity);
if ((rotateQuadrantCW % 4) == 0)
{
painter.drawPixmap(toQRectInt(boundary), qpixmap);
}
else
{
QTransform transform;
transform.rotate(90 * rotateQuadrantCW);
painter.drawPixmap(toQRectInt(boundary),
qpixmap.transformed(transform));
}
if (opacity < 1.0) painter.setOpacity(1.0);*/
}
void BaseCanvas::drawCanvas(const Geom::Rect &boundary, const Gfx::ICanvas &canvas)
{
const PixmapCanvas *pixmap = dynamic_cast<const PixmapCanvas*>(&canvas);
if (!pixmap) throw std::logic_error("cannot recover pixmap canvas");
painter.drawPixmap(toQRectInt(boundary), pixmap->getPixmap());
}
QPen BaseCanvas::colorToPen(const Gfx::Color &color)
{
return brushToPen(QBrush(toQColor(color)));
}
QPen BaseCanvas::brushToPen(const QBrush &brush)
{
auto pen = painter.pen();
pen.setBrush(brush);
return pen;
}
Geom::Size BaseCanvas::textBoundary(const std::string &text)
{
QFontMetrics metrics(painter.font());
auto res = metrics.boundingRect(QRect(0, 0, 0, 0),
Qt::AlignLeft,
QString::fromStdString(text));
return Geom::Size(res.width(), res.height());
}
void BaseCanvas::transform(const Geom::AffineTransform &transform) {
painter.translate(transform.offset.x, transform.offset.y);
painter.rotate(180.0 * transform.rotate / M_PI);
painter.scale(transform.scale, transform.scale);
}
void BaseCanvas::save() {
painter.save();
}
void BaseCanvas::restore() {
painter.restore();
} |
3b403c09e602d41000dc4a56816f2476047f7dcc | 423d69af20dc5ef3bda2fbee54141c7218be9537 | /Homework/HW5/WordSearch.cpp | 72df2b91522ebab9fd41af1e45a1387654a90c52 | [] | no_license | dyl10s/DataStructuresAndAlgorithms | e76dbbfcd74a0a923fb3ed0e025aa29ef96dc1aa | e43ec7ac1aca0b687c5be777ea450c75e1290e35 | refs/heads/master | 2020-03-27T15:59:31.826913 | 2018-11-01T00:34:43 | 2018-11-01T00:34:43 | 146,752,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,049 | cpp | WordSearch.cpp | //
// WordSearch.cpp
// CS263-HW4
//
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm> // needed for transform()
#include <exception>
#include <regex>
#include "WordSearch.h"
WordSearch::WordSearch() {
/* default constructor requires no additional code */
}
WordSearch::WordSearch(const string& topdir, const string& ignore_file) {
load_ignored_words(ignore_file);
/* filter the directory only for files ending with "txt" */
gvsu::FileSystem dir (topdir, regex{"txt$"});
for (auto entry : dir) {
cout << "Reading words from " << entry.second << endl;
read_words (entry.first + "/" + entry.second);
}
}
void WordSearch::load_ignored_words(const string& fname) {
ifstream ign_file (fname);
if (!ign_file.is_open()) {
throw ios_base::failure {"Unable to load ignored.txt"};
}
string word;
while (getline(ign_file, word))
ignored_words.insert(word);
ign_file.close();
}
void WordSearch::read_words(const string &file_name)
{
/* a word is THREE OR MORE alphabetical characters (lowercase) */
const regex word_re {"[a-z]{3,}"};
/* Alternate declaration of the above regular expr
const regex word_re {"[[:alpha:]]{3,}"};
*/
ifstream txt (file_name); /* file is aumatically open */
string one_line;
int line = 1;
string prev = "";
while (getline(txt, one_line)) {
/* change to lowercase */
transform(one_line.begin(), one_line.end(), one_line.begin(), ::tolower);
/* iterate over the string using a regular expression */
auto re_begin = sregex_iterator {one_line.begin(),one_line.end(), word_re};
auto re_end = sregex_iterator{};
for (auto word = re_begin; word != re_end; ++word) {
/* if the word is in the ignored list, don't print it */
if (ignored_words.find(word->str()) == ignored_words.end()) {
words[word->str()] = words[word->str()] + 1;
if (prev != "") {
wordsAfter[prev][word->str()] = wordsAfter[prev][word->str()] + 1;
}
prev = word->str();
}
}
line++;
}
wordsAfter[prev][""] = wordsAfter[prev][""] + 1;
txt.close(); /* close the file */
}
unsigned long WordSearch::word_count() const {
/* TODO complete this function */
int count = 0;
for(auto w : words){
count += w.second;
}
return count;
}
set<string> WordSearch::words_of_length (int L) const {
/* TODO complete this function */
set<string> wordsOfLength;
for(auto w : words){
if(w.first.length() == L)
wordsOfLength.insert(w.first);
}
return wordsOfLength; /* return an empty set */
}
pair<unsigned int,set<string>> WordSearch::most_frequent_words() const
#ifndef _WIN32
throw (length_error)
#endif
{
if(words.size() == 0)
throw length_error{"There are no words"};
set<string> freqWords;
int highScore = 0;
/* TODO complete this function */
for(auto w : words){
if(w.second > highScore){
highScore = w.second;
freqWords.clear();
freqWords.insert(w.first);
}else if(w.second == highScore){
freqWords.insert(w.first);
}
}
return make_pair(highScore, freqWords);
}
set<string> WordSearch::least_frequent_words(int count) const {
if(words.size() == 0)
throw length_error{"There are no words"};
set<string> freqWords;
for(auto w : words){
if(w.second <= count){
freqWords.insert(w.first);
}
}
return freqWords;
}
string WordSearch::most_probable_word_after(const string& word) const {
if(words.size() == 0)
throw length_error{"There are no words"};
int highScore = 0;
string data;
for(auto const &n : wordsAfter.at(word)){
if(n.second >= highScore){
highScore = n.second;
data = n.first;
}
}
return data;
} |
08600511f087ed30a2c071b4fdaffdb739053cee | 8bb81fa2f1785f4bec5bfe1c5e2f4f72fd57f51b | /Team11/Code11/src/spa/src/ProcedureAnalyser.h | c70dc95173d66a8054d4a2ab5d80a37ac1efa971 | [] | no_license | LZYAndy/nus-cs3203 | 3e33721f8a76127b44c74c0535d84a036e0bb4b0 | 4c5d5b4116ea562f19caf530c840d661c29a9422 | refs/heads/master | 2020-12-30T06:41:18.378094 | 2019-11-09T12:25:35 | 2019-11-09T12:25:35 | 238,891,825 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,136 | h | ProcedureAnalyser.h | #ifndef AUTOTESTER_PROCEDUREANALYSER_H
#define AUTOTESTER_PROCEDUREANALYSER_H
#include <string>
#include <regex>
#include "Procedure.h"
#include "StringUtil.h"
#include "StatementListParser.h"
#include "ErrorMessages.h"
class ProcedureAnalyser
{
private:
std::string raw_data;
public:
/**
* The constructor of the ProcedureAnalyser.
* @param raw The raw string to be parsed into procedures.
*/
ProcedureAnalyser(std::string raw);
/**
* Parse the raw data, find all the procedures and return as a vector of procedures.
* @return a vector of procedures.
*/
std::vector<Procedure> analyse();
/**
* The find the closing brackets of the opening brackets which is the first non-space character of the string.
* @param src the source string.
* @param opening the opening bracket, which is also the first non-space character.
* @param closing the closing bracket to be found.
* @return the index of the closing bracket.
*/
static int find_bracket(std::string src, std::string opening, std::string closing);
};
#endif //AUTOTESTER_PROCEDUREANALYSER_H
|
3c84895e3c6c38ced141f54c864489fe8d647fab | fb4bc3b6e2dd10b0cca4c9d89ae2875160256ee3 | /reactor/s13/test12.cc | 928cb742706edc09acee8e4a68a2fa2f77b5184b | [] | no_license | sunqk13022/simple_reactor | 165fa42e0e6dc0d942b924b352aac84bbea993e7 | b338f788de0ae9b75d95ed7d0a4f63d526ec9c33 | refs/heads/master | 2021-01-10T03:06:12.273219 | 2016-04-07T02:04:27 | 2016-04-07T02:04:27 | 52,213,673 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | cc | test12.cc | #include <stdio.h>
#include <iostream>
#include <sys/timerfd.h>
#include <boost/bind.hpp>
#include <thread/thread.h>
#include <logging/logging.h>
#include "event_loop.h"
#include "event_loop_thread.h"
#include "channel.h"
#include "acceptor.h"
#include "socket_fun.h"
#include "inet_address.h"
#include "tcp_server.h"
#include "connector.h"
using namespace simple_reactor;
EventLoop* g_loop;
void connectCallback(int sockfd) {
printf("connected.\n");
g_loop->Quit();
}
int main(int argc, char* argv[]) {
printf("main():pid = %d, tid=%d \n", getpid(), CurrentThread::Tid());
InetAddress listen_addr("127.0.0.1", 12820);
EventLoop loop;
g_loop = &loop;
ConnectorPtr connector(new Connector(&loop, listen_addr));
connector->SetNewConnectionCallback(connectCallback);
connector->Start();
loop.Loop();
printf("exit main().\n");
}
|
e10dd63af3ca54fcee2b4189cc55351c95db5cc6 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /extensions/browser/sandboxed_unpacker_unittest.cc | 04b97810d8a5e7cba57d10376faa24ab6bdbfc6c | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 22,899 | cc | sandboxed_unpacker_unittest.cc | // Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/browser/sandboxed_unpacker.h"
#include "build/build_config.h"
#include <memory>
#include <tuple>
#include "base/base64.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/rust_buildflags.h"
#include "base/strings/pattern.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/threading/thread.h"
#include "base/values.h"
#include "components/crx_file/id_util.h"
#include "components/services/unzip/content/unzip_service.h"
#include "components/services/unzip/in_process_unzipper.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/extensions_test.h"
#include "extensions/browser/install/crx_install_error.h"
#include "extensions/browser/install/sandboxed_unpacker_failure_reason.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_paths.h"
#include "extensions/common/file_util.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/switches.h"
#include "extensions/common/verifier_formats.h"
#include "extensions/strings/grit/extensions_strings.h"
#include "extensions/test/test_extensions_client.h"
#include "services/data_decoder/public/cpp/test_support/in_process_data_decoder.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/zlib/google/zip.h"
#include "ui/base/l10n/l10n_util.h"
namespace extensions {
namespace {
// Inserts an illegal path into the browser images returned by
// TestExtensionsClient for any extension.
class IllegalImagePathInserter
: public TestExtensionsClient::BrowserImagePathsFilter {
public:
IllegalImagePathInserter(TestExtensionsClient* client) : client_(client) {
client_->AddBrowserImagePathsFilter(this);
}
virtual ~IllegalImagePathInserter() {
client_->RemoveBrowserImagePathsFilter(this);
}
void Filter(const Extension* extension,
std::set<base::FilePath>* paths) override {
base::FilePath illegal_path =
base::FilePath(base::FilePath::kParentDirectory)
.AppendASCII(kTempExtensionName)
.AppendASCII("product_logo_128.png");
paths->insert(illegal_path);
}
private:
raw_ptr<TestExtensionsClient> client_;
};
} // namespace
class MockSandboxedUnpackerClient : public SandboxedUnpackerClient {
public:
explicit MockSandboxedUnpackerClient(
scoped_refptr<base::SequencedTaskRunner> callback_runner)
: callback_runner_(callback_runner) {}
base::FilePath temp_dir() const { return temp_dir_; }
std::u16string unpack_error_message() const {
if (error_)
return error_->message();
return std::u16string();
}
CrxInstallErrorType unpack_error_type() const {
if (error_)
return error_->type();
return CrxInstallErrorType::NONE;
}
int unpack_error_detail() const {
if (error_) {
return error_->type() == CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE
? static_cast<int>(error_->sandbox_failure_detail())
: static_cast<int>(error_->detail());
}
return 0;
}
void set_deleted_tracker(bool* deleted_tracker) {
deleted_tracker_ = deleted_tracker;
}
void set_should_compute_hashes(bool should_compute_hashes) {
should_compute_hashes_ = should_compute_hashes;
}
void SetQuitClosure(base::OnceClosure quit_closure) {
quit_closure_ = std::move(quit_closure);
}
private:
~MockSandboxedUnpackerClient() override {
if (deleted_tracker_)
*deleted_tracker_ = true;
if (quit_closure_)
std::move(quit_closure_).Run();
}
void ShouldComputeHashesForOffWebstoreExtension(
scoped_refptr<const Extension> extension,
base::OnceCallback<void(bool)> callback) override {
std::move(callback).Run(should_compute_hashes_);
}
void OnUnpackSuccess(const base::FilePath& temp_dir,
const base::FilePath& extension_root,
std::unique_ptr<base::Value::Dict> original_manifest,
const Extension* extension,
const SkBitmap& install_icon,
declarative_net_request::RulesetInstallPrefs
ruleset_install_prefs) override {
temp_dir_ = temp_dir;
callback_runner_->PostTask(FROM_HERE, std::move(quit_closure_));
}
void OnUnpackFailure(const CrxInstallError& error) override {
error_ = error;
callback_runner_->PostTask(FROM_HERE, std::move(quit_closure_));
}
scoped_refptr<base::SequencedTaskRunner> callback_runner_;
absl::optional<CrxInstallError> error_;
base::OnceClosure quit_closure_;
base::FilePath temp_dir_;
raw_ptr<bool> deleted_tracker_ = nullptr;
bool should_compute_hashes_ = false;
};
class SandboxedUnpackerTest : public ExtensionsTest {
public:
SandboxedUnpackerTest()
: ExtensionsTest(content::BrowserTaskEnvironment::IO_MAINLOOP),
unpacker_thread_("Unpacker Thread") {}
void SetUp() override {
ExtensionsTest::SetUp();
unpacker_thread_.Start();
unpacker_task_runner_ = unpacker_thread_.task_runner();
ASSERT_TRUE(extensions_dir_.CreateUniqueTempDir());
in_process_utility_thread_helper_ =
std::make_unique<content::InProcessUtilityThreadHelper>();
// It will delete itself.
client_ = new MockSandboxedUnpackerClient(
task_environment()->GetMainThreadTaskRunner());
InitSandboxedUnpacker();
// By default, we host an in-process UnzipperImpl to support any service
// clients. Tests may explicitly override the launch callback to prevent
// this.
unzip::SetUnzipperLaunchOverrideForTesting(
base::BindRepeating(&unzip::LaunchInProcessUnzipper));
}
void InitSandboxedUnpacker() {
sandboxed_unpacker_ = new SandboxedUnpacker(
mojom::ManifestLocation::kInternal, Extension::NO_FLAGS,
extensions_dir_.GetPath(), unpacker_task_runner_, client_);
}
void TearDown() override {
unzip::SetUnzipperLaunchOverrideForTesting(base::NullCallback());
// Need to destruct SandboxedUnpacker before the message loop since
// it posts a task to it.
sandboxed_unpacker_ = nullptr;
base::RunLoop().RunUntilIdle();
ExtensionsTest::TearDown();
in_process_utility_thread_helper_.reset();
unpacker_thread_.Stop();
}
base::FilePath GetCrxFullPath(const std::string& crx_name) {
base::FilePath full_path;
EXPECT_TRUE(base::PathService::Get(extensions::DIR_TEST_DATA, &full_path));
full_path = full_path.AppendASCII("unpacker").AppendASCII(crx_name);
EXPECT_TRUE(base::PathExists(full_path)) << full_path.value();
return full_path;
}
void SetupUnpacker(const std::string& crx_name,
const std::string& package_hash) {
base::FilePath crx_path = GetCrxFullPath(crx_name);
extensions::CRXFileInfo crx_info(crx_path, GetTestVerifierFormat());
crx_info.expected_hash = package_hash;
base::RunLoop run_loop;
client_->SetQuitClosure(run_loop.QuitClosure());
unpacker_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&SandboxedUnpacker::StartWithCrx,
sandboxed_unpacker_, crx_info));
// Wait for unpack
run_loop.Run();
}
void SetupUnpackerWithDirectory(const std::string& crx_name) {
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
base::FilePath crx_path = GetCrxFullPath(crx_name);
ASSERT_TRUE(zip::Unzip(crx_path, temp_dir.GetPath()));
std::string fake_id = crx_file::id_util::GenerateId(crx_name);
std::string fake_public_key;
base::Base64Encode(std::string(2048, 'k'), &fake_public_key);
base::RunLoop run_loop;
client_->SetQuitClosure(run_loop.QuitClosure());
unpacker_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&SandboxedUnpacker::StartWithDirectory,
sandboxed_unpacker_, fake_id, fake_public_key,
temp_dir.Take()));
// Wait for unpack
run_loop.Run();
}
bool InstallSucceeded() const { return !client_->temp_dir().empty(); }
base::FilePath GetInstallPath() const {
return client_->temp_dir().AppendASCII(kTempExtensionName);
}
std::u16string GetInstallErrorMessage() const {
return client_->unpack_error_message();
}
CrxInstallErrorType GetInstallErrorType() const {
return client_->unpack_error_type();
}
int GetInstallErrorDetail() const { return client_->unpack_error_detail(); }
void ExpectInstallErrorContains(const std::string& error) {
std::string full_error = base::UTF16ToUTF8(client_->unpack_error_message());
EXPECT_TRUE(full_error.find(error) != std::string::npos)
<< "Error message " << full_error << " does not contain " << error;
}
// Unpacks the package |package_name| and checks that |sandboxed_unpacker_|
// gets deleted.
void TestSandboxedUnpackerDeleted(const std::string& package_name,
bool expect_success) {
bool client_deleted = false;
client_->set_deleted_tracker(&client_deleted);
SetupUnpacker(package_name, "");
EXPECT_EQ(GetInstallErrorMessage().empty(), expect_success);
base::RunLoop run_loop;
client_->SetQuitClosure(run_loop.QuitClosure());
// Remove our reference to |sandboxed_unpacker_|, it should get deleted
// since/ it's the last reference.
sandboxed_unpacker_ = nullptr;
// Wait for |client_| dtor.
run_loop.Run();
// The SandboxedUnpacker should have been deleted and deleted the client.
EXPECT_TRUE(client_deleted);
}
void SetPublicKey(const std::string& key) {
sandboxed_unpacker_->public_key_ = key;
}
void SetExtensionRoot(const base::FilePath& path) {
sandboxed_unpacker_->extension_root_ = path;
}
absl::optional<base::Value::Dict> RewriteManifestFile(
const base::Value::Dict& manifest) {
return sandboxed_unpacker_->RewriteManifestFile(manifest);
}
data_decoder::test::InProcessDataDecoder& in_process_data_decoder() {
return in_process_data_decoder_;
}
protected:
base::ScopedTempDir extensions_dir_;
raw_ptr<MockSandboxedUnpackerClient, AcrossTasksDanglingUntriaged> client_;
scoped_refptr<SandboxedUnpacker> sandboxed_unpacker_;
std::unique_ptr<content::InProcessUtilityThreadHelper>
in_process_utility_thread_helper_;
data_decoder::test::InProcessDataDecoder in_process_data_decoder_;
private:
// The thread where the sandboxed unpacker runs. This provides test coverage
// in an environment similar to what we use in production.
base::Thread unpacker_thread_;
scoped_refptr<base::SequencedTaskRunner> unpacker_task_runner_;
};
TEST_F(SandboxedUnpackerTest, EmptyDefaultLocale) {
SetupUnpacker("empty_default_locale.crx", "");
ExpectInstallErrorContains(manifest_errors::kInvalidDefaultLocale);
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(
static_cast<int>(SandboxedUnpackerFailureReason::UNPACKER_CLIENT_FAILED),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, HasDefaultLocaleMissingLocalesFolder) {
SetupUnpacker("has_default_missing_locales.crx", "");
ExpectInstallErrorContains(manifest_errors::kLocalesTreeMissing);
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(
static_cast<int>(SandboxedUnpackerFailureReason::UNPACKER_CLIENT_FAILED),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, InvalidDefaultLocale) {
SetupUnpacker("invalid_default_locale.crx", "");
ExpectInstallErrorContains(manifest_errors::kInvalidDefaultLocale);
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(
static_cast<int>(SandboxedUnpackerFailureReason::UNPACKER_CLIENT_FAILED),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, MissingDefaultData) {
SetupUnpacker("missing_default_data.crx", "");
ExpectInstallErrorContains(manifest_errors::kLocalesNoDefaultMessages);
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(
static_cast<int>(SandboxedUnpackerFailureReason::UNPACKER_CLIENT_FAILED),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, MissingDefaultLocaleHasLocalesFolder) {
SetupUnpacker("missing_default_has_locales.crx", "");
ExpectInstallErrorContains(l10n_util::GetStringUTF8(
IDS_EXTENSION_LOCALES_NO_DEFAULT_LOCALE_SPECIFIED));
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(
static_cast<int>(SandboxedUnpackerFailureReason::UNPACKER_CLIENT_FAILED),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, MissingMessagesFile) {
SetupUnpacker("missing_messages_file.crx", "");
EXPECT_TRUE(base::MatchPattern(
GetInstallErrorMessage(),
u"*" + std::u16string(manifest_errors::kLocalesMessagesFileMissing) +
u"*_locales?en_US?messages.json'."))
<< GetInstallErrorMessage();
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(
static_cast<int>(SandboxedUnpackerFailureReason::UNPACKER_CLIENT_FAILED),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, NoLocaleData) {
SetupUnpacker("no_locale_data.crx", "");
ExpectInstallErrorContains(manifest_errors::kLocalesNoDefaultMessages);
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(
static_cast<int>(SandboxedUnpackerFailureReason::UNPACKER_CLIENT_FAILED),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, ImageDecodingError) {
const char16_t kExpected[] = u"Could not decode image: ";
SetupUnpacker("bad_image.crx", "");
EXPECT_TRUE(base::StartsWith(GetInstallErrorMessage(), kExpected,
base::CompareCase::INSENSITIVE_ASCII))
<< "Expected prefix: \"" << kExpected << "\", actual error: \""
<< GetInstallErrorMessage() << "\"";
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(
static_cast<int>(SandboxedUnpackerFailureReason::UNPACKER_CLIENT_FAILED),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, BadPathError) {
IllegalImagePathInserter inserter(
static_cast<TestExtensionsClient*>(ExtensionsClient::Get()));
SetupUnpacker("good_package.crx", "");
// Install should have failed with an error.
EXPECT_FALSE(InstallSucceeded());
EXPECT_FALSE(GetInstallErrorMessage().empty());
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(static_cast<int>(
SandboxedUnpackerFailureReason::INVALID_PATH_FOR_BROWSER_IMAGE),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, NoCatalogsSuccess) {
SetupUnpacker("no_l10n.crx", "");
// Check that there is no _locales folder.
base::FilePath install_path = GetInstallPath().Append(kLocaleFolder);
EXPECT_FALSE(base::PathExists(install_path));
EXPECT_EQ(CrxInstallErrorType::NONE, GetInstallErrorType());
}
TEST_F(SandboxedUnpackerTest, FromDirNoCatalogsSuccess) {
SetupUnpackerWithDirectory("no_l10n.crx");
// Check that there is no _locales folder.
base::FilePath install_path = GetInstallPath().Append(kLocaleFolder);
EXPECT_FALSE(base::PathExists(install_path));
EXPECT_EQ(CrxInstallErrorType::NONE, GetInstallErrorType());
}
TEST_F(SandboxedUnpackerTest, WithCatalogsSuccess) {
SetupUnpacker("good_l10n.crx", "");
// Check that there is _locales folder.
base::FilePath install_path = GetInstallPath().Append(kLocaleFolder);
EXPECT_TRUE(base::PathExists(install_path));
EXPECT_EQ(CrxInstallErrorType::NONE, GetInstallErrorType());
}
TEST_F(SandboxedUnpackerTest, FromDirWithCatalogsSuccess) {
SetupUnpackerWithDirectory("good_l10n.crx");
// Check that there is _locales folder.
base::FilePath install_path = GetInstallPath().Append(kLocaleFolder);
EXPECT_TRUE(base::PathExists(install_path));
EXPECT_EQ(CrxInstallErrorType::NONE, GetInstallErrorType());
}
TEST_F(SandboxedUnpackerTest, FailHashCheck) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
extensions::switches::kEnableCrxHashCheck);
SetupUnpacker("good_l10n.crx", std::string(64, '0'));
// Check that there is an error message.
EXPECT_FALSE(GetInstallErrorMessage().empty());
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(static_cast<int>(
SandboxedUnpackerFailureReason::CRX_HASH_VERIFICATION_FAILED),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, TestRewriteManifestInjections) {
constexpr char kTestKey[] = "test_key";
constexpr char kTestVersion[] = "1.2.3";
constexpr char kVersionStr[] = "version";
SetPublicKey(kTestKey);
SetExtensionRoot(extensions_dir_.GetPath());
std::string fingerprint = "1.0123456789abcdef";
base::WriteFile(extensions_dir_.GetPath().Append(
FILE_PATH_LITERAL("manifest.fingerprint")),
fingerprint);
absl::optional<base::Value::Dict> manifest(
RewriteManifestFile(base::Value::Dict().Set(kVersionStr, kTestVersion)));
auto* key = manifest->FindString("key");
auto* version = manifest->FindString(kVersionStr);
auto* differential_fingerprint =
manifest->FindString("differential_fingerprint");
ASSERT_NE(nullptr, key);
ASSERT_NE(nullptr, version);
ASSERT_NE(nullptr, differential_fingerprint);
EXPECT_EQ(kTestKey, *key);
EXPECT_EQ(kTestVersion, *version);
EXPECT_EQ(fingerprint, *differential_fingerprint);
}
TEST_F(SandboxedUnpackerTest, InvalidMessagesFile) {
SetupUnpackerWithDirectory("invalid_messages_file.crx");
// Check that there is no _locales folder.
base::FilePath install_path = GetInstallPath().Append(kLocaleFolder);
EXPECT_FALSE(base::PathExists(install_path));
#if BUILDFLAG(BUILD_RUST_JSON_READER)
EXPECT_TRUE(base::MatchPattern(
GetInstallErrorMessage(),
u"*_locales?en_US?messages.json': EOF while parsing a string at line 4*"))
#else // BUILDFLAG(BUILD_RUST_JSON_READER)
EXPECT_TRUE(base::MatchPattern(
GetInstallErrorMessage(),
u"*_locales?en_US?messages.json': Line: 4, column: 1,*"))
#endif // BUILDFLAG(BUILD_RUST_JSON_READER)
<< GetInstallErrorMessage();
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(static_cast<int>(
SandboxedUnpackerFailureReason::COULD_NOT_LOCALIZE_EXTENSION),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, PassHashCheck) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
extensions::switches::kEnableCrxHashCheck);
SetupUnpacker(
"good_l10n.crx",
"614AE3D608F4C2185E9173293AB3F93EE7C7C79C9A2C3CF71F633386A3296A6C");
// Check that there is no error message.
EXPECT_THAT(GetInstallErrorMessage(), testing::IsEmpty());
EXPECT_EQ(CrxInstallErrorType::NONE, GetInstallErrorType());
}
TEST_F(SandboxedUnpackerTest, SkipHashCheck) {
SetupUnpacker("good_l10n.crx", "badhash");
// Check that there is no error message.
EXPECT_THAT(GetInstallErrorMessage(), testing::IsEmpty());
EXPECT_EQ(CrxInstallErrorType::NONE, GetInstallErrorType());
}
// The following tests simulate the utility services failling.
TEST_F(SandboxedUnpackerTest, UnzipperServiceFails) {
// We override the Unzipper's launching behavior to drop the interface
// receiver, effectively simulating a crashy service process.
unzip::SetUnzipperLaunchOverrideForTesting(base::BindRepeating([]() -> auto {
mojo::PendingRemote<unzip::mojom::Unzipper> remote;
std::ignore = remote.InitWithNewPipeAndPassReceiver();
return remote;
}));
InitSandboxedUnpacker();
SetupUnpacker("good_package.crx", "");
EXPECT_FALSE(InstallSucceeded());
EXPECT_FALSE(GetInstallErrorMessage().empty());
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(static_cast<int>(SandboxedUnpackerFailureReason::UNZIP_FAILED),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, JsonParserFails) {
in_process_data_decoder().service().SimulateJsonParserCrashForTesting(true);
InitSandboxedUnpacker();
SetupUnpacker("good_package.crx", "");
EXPECT_FALSE(InstallSucceeded());
EXPECT_FALSE(GetInstallErrorMessage().empty());
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
}
TEST_F(SandboxedUnpackerTest, ImageDecoderFails) {
in_process_data_decoder().service().SimulateImageDecoderCrashForTesting(true);
InitSandboxedUnpacker();
SetupUnpacker("good_package.crx", "");
EXPECT_FALSE(InstallSucceeded());
EXPECT_FALSE(GetInstallErrorMessage().empty());
ASSERT_EQ(CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE,
GetInstallErrorType());
EXPECT_EQ(
static_cast<int>(SandboxedUnpackerFailureReason::UNPACKER_CLIENT_FAILED),
GetInstallErrorDetail());
}
TEST_F(SandboxedUnpackerTest, NoComputeHashes) {
client_->set_should_compute_hashes(false);
SetupUnpacker("good_package.crx", "");
EXPECT_TRUE(InstallSucceeded());
EXPECT_TRUE(GetInstallErrorMessage().empty());
EXPECT_FALSE(
base::PathExists(file_util::GetComputedHashesPath(GetInstallPath())));
}
TEST_F(SandboxedUnpackerTest, ComputeHashes) {
client_->set_should_compute_hashes(true);
SetupUnpacker("good_package.crx", "");
EXPECT_TRUE(InstallSucceeded());
EXPECT_TRUE(GetInstallErrorMessage().empty());
EXPECT_TRUE(
base::PathExists(file_util::GetComputedHashesPath(GetInstallPath())));
}
// SandboxedUnpacker is ref counted and is reference by callbacks and
// InterfacePtrs. This tests that it gets deleted as expected (so that no extra
// refs are left).
TEST_F(SandboxedUnpackerTest, DeletedOnSuccess) {
TestSandboxedUnpackerDeleted("good_l10n.crx", /*expect_success=*/true);
}
TEST_F(SandboxedUnpackerTest, DeletedOnFailure) {
TestSandboxedUnpackerDeleted("bad_image.crx", /*expect_success=*/false);
}
} // namespace extensions
|
a2237756c1bc2541e24687aee9c0eb0610f75aa2 | 0576db21df4cdd32ca448055d7fd7c07912f8fff | /天数差.cpp | 8482811d7d2fb993763b9491a559fef2d466d8ef | [] | no_license | lov1ballad/now-coder | 29b97f05635dcb472b82c2ea2cdb2c67b9af83bc | 1bacfbe1c8ae6fb0d7b1a9498b283962b7dd8085 | refs/heads/main | 2023-07-17T17:07:18.336925 | 2021-08-22T15:47:35 | 2021-08-22T15:47:35 | 348,896,513 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | cpp | 天数差.cpp | #define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
int Month[12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
int day(int year, int month, int day)
{
int year_day = year * 365 + year / 4 - year / 100 + year / 400;
int month_day = Month[month - 1];
if ((month % 4 == 0 && month % 100 != 0) || month % 400 == 0)
month_day += 1;
return year_day + month_day + day;
}
int main()
{
int d1_year=0, d1_month=0, d1_day=0, d2_year=0, d2_month=0, d2_day=0;
scanf("%4d%2d%2d\n", &d1_year, &d1_month, &d1_day);
int d1days = day(d1_year, d1_month, d1_day);
scanf("%4d%2d%2d", &d2_year, &d2_month, &d2_day);
int d2days = day(d2_year, d2_month, d2_day);
printf("%d", abs(d1days - d2days));
return 0;
} |
e6cbefed4bfdb16c80e89c7dfa2b681284bfe273 | ae8c95c0cdedc695ba4f5b1bd09a18878fa02019 | /EAPI_Test/UnitTestingTestCase/UnitTesting_TestCase_EApiBoardGetStringA.cpp | a2af5a294283991303dd19b58861ad9f102d1e7c | [] | no_license | locke12456/EAPI_Test | 7bbfc5b5e6cb3adbbf5d1978d74c191a50b1de68 | 307469decc2c84c616ca1984e607beeeb00309a1 | refs/heads/master | 2019-01-19T10:04:18.079883 | 2013-11-06T03:31:22 | 2013-11-06T03:31:22 | 13,027,428 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,414 | cpp | UnitTesting_TestCase_EApiBoardGetStringA.cpp |
#include "UnitTesting_EApiBoardGetStringA.h"
using namespace testing;
TEST_F(UnitTesting_EApiBoardGetStringA , EApiBoardGetStringA_ID_BoardManufacturer)
{
EXPECT_PRED_FORMAT1(AssertEApiBoardGetStringA,EAPI_ID_BOARD_MANUFACTURER_STR);
}
TEST_F(UnitTesting_EApiBoardGetStringA , EApiBoardGetStringA_ID_BoardName)
{
EXPECT_PRED_FORMAT1(AssertEApiBoardGetStringA,EAPI_ID_BOARD_NAME_STR);
}
TEST_F(UnitTesting_EApiBoardGetStringA , EApiBoardGetStringA_ID_BoardSerial)
{
EXPECT_PRED_FORMAT1(AssertEApiBoardGetStringA,EAPI_ID_BOARD_SERIAL_STR);
}
TEST_F(UnitTesting_EApiBoardGetStringA , EApiBoardGetStringA_ID_BoardRevision)
{
EXPECT_PRED_FORMAT1(AssertEApiBoardGetStringA,EAPI_ID_BOARD_BIOS_REVISION_STR);
}
TEST_F(UnitTesting_EApiBoardGetStringA , EApiBoardGetStringA_ID_BoardPlatformType)
{
EXPECT_PRED_FORMAT1(AssertEApiBoardGetStringA,EAPI_ID_BOARD_PLATFORM_TYPE_STR);
}
TEST_P(UnitTesting_EApiBoardGetStringA, EApiBoardGetStringA_ID_All)
{
uint32_t n = GetParam();
EXPECT_PRED_FORMAT1( AssertEApiBoardGetStringA , n );
}
INSTANTIATE_TEST_CASE_P( EAPI_Unit_testing , UnitTesting_EApiBoardGetStringA , testing::Values(
EAPI_ID_BOARD_MANUFACTURER_STR , EAPI_ID_BOARD_NAME_STR ,
EAPI_ID_BOARD_SERIAL_STR , EAPI_ID_BOARD_BIOS_REVISION_STR ,
EAPI_ID_BOARD_PLATFORM_TYPE_STR
) ); |
fa8788bd8956c45155afe4182939545eb490e0f0 | b0c66358ae5c0386db5887e2609929e753c38d18 | /arch/cf/463/TaskD.cpp | e3e0269e3715775238750e30a077b39c18bfd8af | [] | no_license | michalsvagerka/competitive | e7683133ee5f108429135a3a19b3bbaa6732ea9f | 07f084dff6c1ba6f151c93bf78405574456100e4 | refs/heads/master | 2021-06-07T14:54:35.516490 | 2020-07-07T08:17:56 | 2020-07-07T08:19:09 | 113,440,107 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,634 | cpp | TaskD.cpp | #include "../../../l/lib.h"
// #include "../l/mod.h"
class TaskD {
public:
void solve(istream& cin, ostream& cout) {
int Q, t, last = 0;
ll p,q;
cin >> Q;
vector<vector<pair<int,ll>>> E{{}};
vector<int> W{0};
while (Q--) {
cin >> t >> p >> q;
p ^= last;
q ^= last;
p--;
if (t == 1) {
W.push_back(int(q));
for (int z = 20; z >= 0; --z) {
if (z < E[p].size() && W[E[p][z].x] < q) {
p = E[p][z].x;
}
}
if (W[p] < q && !E[p].empty()) {
p = E[p][0].x;
}
E.emplace_back();
if (W[p] >= q) {
E.back().emplace_back(p,q);
ll r = q;
for (int i = 0; i < E[p].size() ;++i) {
E.back().emplace_back(E[p][i].x, r + E[p][i].y);
r += E[p][i].y;
p = E[p][i].x;
}
}
} else if (t == 2) {
last = 0;
for (int z = 20; z >= 0; --z) {
if (z < E[p].size() && E[p][z].y <= q) {
q -= E[p][z].y;
p = E[p][z].x;
last += 1<<z;
}
}
if (W[p] <= q) {
q -= W[p];
last++;
}
cout << last << "\n";
}
}
}
};
|
266f15f6d84c2cecda66ac8baebd80f73f88d82a | c19c56317ffc4e90d43b7020813eff339c0afef9 | /functions/tests/test_addition.cpp | af051033de537cc2031518f4ef0b8ae21389adc3 | [
"MIT"
] | permissive | GuylainGreer/manifolds | 8bb33ad11a3cb2700a0c71645f69cfcff75ee754 | 96f996f67fc523c726f2edbc9705125c212bedae | refs/heads/master | 2021-01-21T02:27:11.854036 | 2015-04-02T12:02:37 | 2015-04-02T12:02:37 | 20,369,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 881 | cpp | test_addition.cpp | #include <boost/test/unit_test.hpp>
#include "functions/addition.hh"
#include "functions/variables.hh"
#include "functions/full_function_defs.hh"
#include "functions/std_functions.hh"
#include "functions/polynomial.hh"
#include "functions/operators.hh"
#include <iostream>
#include "functions/streaming.hh"
BOOST_AUTO_TEST_CASE(addition_test) {
using namespace manifolds;
Variable<1> b1;
Variable<2> b2;
Variable<4> b3;
Variable<6> m1;
Variable<7> m2;
Variable<8> m3;
auto c33 = b1 + m1 * t;
auto c22 = b2 + m2 * t;
auto c11 = b3 + m3 * t;
auto part1 = 4_c * c22 * c22 * c11 * c33;
/*CustomVariableNamer
vnamer{ std::make_pair(1, "b1"), std::make_pair(2, "b2"),
std::make_pair(4, "b3"), std::make_pair(6, "m1"),
std::make_pair(7, "m2"), std::make_pair(8, "m3"), };*/
// Stream2(std::cout, part1, vnamer) << "\n\n";
(void)part1;
}
|
cf34b6c4e6fc9ded909d2fe12165c171f5ae8a51 | ab18394336a408a95fec282cb4ff756733ee9d7c | /util/persist_test.cc | f9333088f6163425006cc674dfed0aa98b2fbb47 | [
"BSD-3-Clause"
] | permissive | wzharies/SLM-DB | defa22643bd07f087898e1c7167e25c977933342 | 6c54d4beeceea8fb0bb34f0213c30d183ac47fc7 | refs/heads/master | 2023-08-08T00:14:10.710414 | 2023-08-06T12:46:28 | 2023-08-06T12:46:28 | 675,229,507 | 0 | 0 | BSD-3-Clause | 2023-08-06T08:09:41 | 2023-08-06T08:09:39 | null | UTF-8 | C++ | false | false | 1,114 | cc | persist_test.cc | #include <libvmem.h>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <cstring>
#include <cstdint>
constexpr uint64_t POOL_SIZE = 2<<30;
constexpr uint64_t OBJ_SIZE = 1<<27;
void random_str(char* str, uint length) {
for (uint i = 0; i < length; i++) {
char ascii_code = rand() % 95 + 33;
str[i] = ascii_code;
}
}
int main(int argc, char* argv[]) {
VMEM* vmp;
if ((vmp = vmem_create("/mnt/mem/vmem_test", POOL_SIZE)) == NULL) {
perror("vmem_create");
exit(1);
}
std::vector<char*> objs;
for (int i = 0; i < POOL_SIZE/OBJ_SIZE; i++) {
char* ptr = new char[OBJ_SIZE];
random_str(ptr, OBJ_SIZE);
objs.push_back(ptr);
}
clock_t begin = clock();
for (const auto& obj : objs) {
char* ptr;
if ((ptr = (char*) vmem_malloc(vmp, OBJ_SIZE)) == NULL) {
perror("vmem_malloc");
exit(1);
}
memcpy(ptr, obj, OBJ_SIZE);
}
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
double bd = static_cast<double>(POOL_SIZE) / elapsed_secs;
fprintf(stdout, "Bandwidth %fGB/s \n", bd);
} |
bea17864ab27a92283a9d8116301efa5733c3d33 | 75f94687e9df7bde68f4b41b0b0143c1a59d420e | /src/angle/DPN.cc | 437380e32f39b4f8ce28e62ad7735d6282f5d570 | [
"MIT"
] | permissive | Relzohery/libdetran | d2a7a5604b97303d27c06cfd4e811a57f277fc55 | 77637c788823e0a14aae7e40e476a291f6f3184b | refs/heads/master | 2023-02-06T10:32:34.242165 | 2013-11-11T15:56:52 | 2013-11-11T15:56:52 | 242,563,346 | 0 | 0 | MIT | 2020-10-13T23:18:47 | 2020-02-23T17:50:00 | null | UTF-8 | C++ | false | false | 1,151 | cc | DPN.cc | //----------------------------------*-C++-*----------------------------------//
/**
* @file DPN.cc
* @author robertsj
* @date Oct 10, 2012
* @brief DPN class definition.
*/
//---------------------------------------------------------------------------//
#include "DPN.hh"
#include "GenerateGaussLegendre.hh"
namespace detran_angle
{
//---------------------------------------------------------------------------//
DPN::DPN(const size_t number_polar_octant)
: Quadrature(1, 2*number_polar_octant, "DPN")
{
// generate the parameters on-the-fly.
vec_dbl tmp_mu(d_number_angles_octant, 0.0);
vec_dbl tmp_wt(d_number_angles_octant, 0.0);
generate_gl_parameters(d_number_angles_octant, tmp_mu, tmp_wt);
for (size_t i = 0; i < d_number_angles_octant; ++i)
{
// Shift the mu to [0, 1] from [-1, 1]
d_mu[i] = 0.5*tmp_mu[i] + 0.5;
d_weight[i] = 0.5*tmp_wt[i];
}
}
//---------------------------------------------------------------------------//
DPN::SP_quadrature
DPN::Create(const size_t number_polar_octant)
{
SP_quadrature p(new DPN(number_polar_octant));
return p;
}
} // end namespace detran_angle
|
943d0f211ec976ad0fee07f4bae5e8bcb1edbad8 | c6ef31569a31e0da96008865eccbbb7be67313f2 | /cocosProject/Game/Managers/SoundsManager.cpp | eafcc3ddff6092861ce2f16a9499623ea178ec10 | [] | no_license | jonyrock/FoxyBird | ee3fb1732be9a2349d03c86c0893a2c956037387 | e4221134f8e0f6540e8ae6817dd68761f6ec4d14 | refs/heads/master | 2021-01-10T09:59:00.616567 | 2016-02-09T16:15:55 | 2016-02-09T16:15:55 | 51,378,657 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,890 | cpp | SoundsManager.cpp | #include "Managers/SoundsManager.h"
#include "Managers/DataManager.h"
#include "Managers/SettingsManager.h"
#include "Managers/LocalizationManager.h"
#include <SimpleAudioEngine.h>
#include <cocos2d.h>
#include <string>
using namespace std;
using namespace cocos2d;
SoundsManager* SoundsManager::getInstance() {
static SoundsManager instance;
return &instance;
}
SoundsManager::SoundsManager() {
}
bool SoundsManager::init() {
CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sounds/background.mp3");
return true;
}
void SoundsManager::playMusic(bool startAgain) {
_musicTime = true;
if(!SettingsManager::getInstance()->getIsMusicOn()) return;
if(startAgain || !_musicInited) {
CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("sounds/background.mp3", true);
_musicInited = true;
} else {
CocosDenshion::SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
}
void SoundsManager::stopMusic() {
_musicTime = false;
CocosDenshion::SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
void SoundsManager::playJumpEffect() {
if(!SettingsManager::getInstance()->getIsSoundEffectsOn()) return;
CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(
"sounds/jump.wav"
);
}
void SoundsManager::playGameOverEffect() {
if(!SettingsManager::getInstance()->getIsSoundEffectsOn() &&
!SettingsManager::getInstance()->getIsMusicOn()) return;
CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(
"sounds/game_over.mp3"
);
}
void SoundsManager::playErrorEffect() {
if(!SettingsManager::getInstance()->getIsSoundEffectsOn()) return;
CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(
"sounds/wrong_ice.wav"
);
}
void SoundsManager::playNextStageEffect() {
if(!SettingsManager::getInstance()->getIsSoundEffectsOn()) return;
CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(
"sounds/new_stage.wav"
);
}
void SoundsManager::playButtonEffect() {
if(!SettingsManager::getInstance()->getIsSoundEffectsOn()) return;
CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(
"sounds/button.wav"
);
}
void SoundsManager::playNewRecord() {
if(!SettingsManager::getInstance()->getIsSoundEffectsOn()) return;
CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(
"sounds/new_record.mp3"
);
}
void SoundsManager::onAppPause() {
CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic();
_musicInited = false;
}
void SoundsManager::onAppResume() {
if(!_musicTime)
stopMusic();
}
void SoundsManager::onMusicSettingsChange(bool enabled) {
if(!_musicTime) return;
if(enabled) {
playMusic(false);
} else {
CocosDenshion::SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
}
|
7821dda9e2ca58a15849d24668c864ef0faa1035 | 9331ef4baa70500771f7e54fa4edbb24fe4ce099 | /ast/Astnode.cpp | 90db2308b48aa495bb2731fb0b2b7d399bd12a50 | [] | no_license | alexbprr/CsmallCompiler | 9ee8c34056fc4ffcd7fef60762cd357c46a8a0de | c41026cf0c161c664e09268fb67cef6a999fd863 | refs/heads/master | 2022-03-14T04:28:56.923746 | 2019-11-08T00:31:16 | 2019-11-08T00:31:16 | 179,382,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,001 | cpp | Astnode.cpp | using namespace std;
#include "Astnode.h"
ofstream *Astnode::ast_file;
ofstream *Astnode::tac_file;
ofstream *Astnode::pythonfile;
ofstream *Astnode::dotfile;
Astnode:: Astnode(){ }
Astnode:: Astnode(string name)
{
this->name = name;
}
vector<Astnode*>* Astnode::getChildren()
{
return &(this->children);
}
string Astnode::getName()
{
return name;
}
float Astnode::getValue()
{
return this->value;
}
Operand* Astnode::getAddress()
{
return this->address;
}
Label* Astnode::getNextLabel()
{
return this->next;
}
Label* Astnode::getTrueLabel()
{
return this->true_label;
}
Label* Astnode::getFalseLabel()
{
return this->false_label;
}
void Astnode::setChildren(vector<Astnode*> children)
{
this->children = children;
}
void Astnode::setName(string name)
{
this->name = name;
}
void Astnode::setIntValue(int value)
{
this->intValue = value;
}
void Astnode::setFloatValue(float value)
{
this->value = value;
}
void Astnode::setAddress(Operand* o)
{
this->address = o;
}
void Astnode::setTacFile(ofstream *tac_file)
{
Astnode::tac_file = tac_file;
}
void Astnode::setAstFile(ofstream *ast_file)
{
Astnode::ast_file = ast_file;
}
void Astnode::setPythonFile(ofstream *pythonfile)
{
Astnode::pythonfile = pythonfile;
}
void Astnode::setDotFile(ofstream *dotfile)
{
Astnode::dotfile = dotfile;
}
void Astnode::addChild(Astnode* node)
{
if (node == NULL)
cerr << "{Astnode::addChild}: Tentativa de adicionar um filho nulo." << endl;
else
this->children.push_back(node);
}
string Astnode::tabs(int level)
{
string deslocamento = "";
while (level!=0)
{
level = level - 1;
deslocamento += " ";
}
return deslocamento;
}
//if ((*it)->tableEntryRef != NULL)
//ss << (*it)->name << level << *cont << "_" << (*it)->tableEntryRef->getLexema();
//ss << (*it)->name << level << *cont << "[shape=circle,label=\"Id("<< (*it)->tableEntryRef->getLexema()<< ")\"]";
// if ((*it)->op.length() > 0)
// {
// ss << (*it)->name << level << *cont << "\"" << (*it)->op << "\"";// << "[shape=circle,label=\""<< (*it)->name << "(" << (*it)->op<< ")\"]";
// (*it)->dotname = ss.str();
// ss.str("");
// }
// else
// ss << (*it)->name << level << *cont << "[shape=circle,label=\""<< (*it)->name << "\"]";
//printf("Dot name: %s\n", (*it)->dotname.c_str());
void Astnode::generateDot(int level, int *cont)
{
std::stringstream ss;
if (level == 0)
{
ss << this->name;
this->dotname = ss.str();
ss.str("");
}
(*cont)++;
if (this->children.size() > 0)
{
if (this->op.length() > 0)
ss << this->name << level << *cont << "[shape=circle,label=\""<< this->name << "("<< this->op <<")\"];"<<endl;
else
ss << this->name << level << *cont << "[shape=circle,label=\""<< this->name << "\"];"<< endl;
(*Astnode::dotfile) << ss.str();
ss.str("");
ss << this->name << level << *cont;
this->dotname = ss.str();
ss.str("");
for(vector<Astnode*>::iterator it = this->children.begin(); it != this->children.end(); ++it)
{
if ((*it) != NULL)
{
if ((*it)->dotname.length() == 0)
{
ss << (*it)->name << level << *cont;
(*it)->dotname = ss.str();
ss.str("");
}
(*it)->generateDot(level + 1, cont);
(*Astnode::dotfile) << this->dotname << " -> " << (*it)->dotname << ";" << endl;
}
}
}
else
{
if (this->getName() == "Id")
{
ss << this->name << level << *cont << "[shape=circle,label=\"Id("<< this->lexema << ")\"];"<< endl;
}
else {
if (this->type == 0)
ss << this->name << level << *cont << "[shape=circle,label=\"Integer("<< this->intValue << ")\"];"<< endl;
else
ss << this->name << level << *cont << "[shape=circle,label=\"Integer("<< this->value << ")\"];"<< endl;
}
(*Astnode::dotfile) << ss.str();
ss.str("");
ss << this->name << level << *cont;
this->dotname = ss.str();
ss.str("");
}
}
void Astnode::printNode(int level)
{
string deslocamento = this->tabs(level);
cout << deslocamento << "<" << this->name << ">" << endl;
(*Astnode::ast_file) << deslocamento << "<" << this->name << ">" << endl;
if (this->children.size() > 0)
{
for(vector<Astnode*>::iterator it = this->children.begin(); it != this->children.end(); ++it)
{
if ((*it) != NULL)
(*it)->printNode(level+1);
}
}
cout << deslocamento << "</" << this->name << ">" << endl;
(*Astnode::ast_file) << deslocamento << "</" << this->name << ">" << endl;
}
float Astnode::evaluate()
{
if (this->children.size() > 0)
{
for(vector<Astnode*>::iterator it = this->children.begin(); it != this->children.end(); ++it)
if ((*it) != NULL)
(*it)->evaluate();
}
}
void Astnode::generateCode()
{
if (this->children.size() > 0)
{
for(vector<Astnode*>::iterator it = this->children.begin(); it != this->children.end(); ++it)
{
if ((*it) != NULL)
(*it)->generateCode();
}
}
}
void Astnode::generateBranchCode(){}
void Astnode::generateRValueCode(){}
string Astnode::pythonTab(int level)
{
string deslocamento = "";
while (level!=0)
{
level = level - 1;
deslocamento += " ";
}
return deslocamento;
}
void Astnode::generatePythonCode(int level)
{
if (this->children.size() > 0)
{
for(vector<Astnode*>::iterator it = this->children.begin(); it != this->children.end(); ++it)
{
if ((*it) != NULL)
(*it)->generatePythonCode(level);
}
}
}
|
134217b2b11591060c2faa4108ca0ca53ec73416 | fcfb8ef8f325eca5df9c750cd5d14417c7505486 | /100/102.cpp | 135619a5dc2f504edaa78a858908313cb58b72ac | [] | no_license | ijliao/uva | c83547d042521a488380f03144cf2ce5bdd46bb8 | c7b6b34dee4c5399dd68932920adb8fc2f1d84c9 | refs/heads/master | 2016-09-06T05:53:03.002135 | 2013-06-05T03:22:47 | 2013-06-05T03:22:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | 102.cpp | #include <iostream>
using namespace std;
int bin[3][3];
void pack(void)
{
char res[] = " ";
int max = 0;
for (int B = 0; B < 3; B++) {
for (int C = 0; C < 3; C++) {
if (B == C)
continue;
int G = 3 - B - C;
int tmp = bin[B][0] + bin[G][1] + bin[C][2];
if (tmp > max) {
max = tmp;
res[B] = 'B';
res[G] = 'G';
res[C] = 'C';
}
}
}
int sum = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
sum += bin[i][j];
cout << res << ' ' << sum - max << endl;
}
int main(void)
{
while (true) {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
cin >> bin[i][j];
if (cin.eof())
break;
pack();
}
return 0;
}
|
1118a01ed28b53a06b9c15d2b1969d32c4cad02a | ee6a981f31d86e32cb5459d435fd8ebc14361461 | /src/compiler/lib/Grid.hpp | c418faf0aba8e3a68bd05296310f122ceeee2f98 | [
"MIT"
] | permissive | silvercreekpk/yask | 40e21dd79f2fa94e197de961f902c9556114a18a | 7a5ffd73b98dbb945f3e70e7cec2ea50e15a56c9 | refs/heads/master | 2020-03-28T09:01:05.297700 | 2018-08-28T15:27:52 | 2018-08-28T15:27:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,030 | hpp | Grid.hpp | /*****************************************************************************
YASK: Yet Another Stencil Kernel
Copyright (c) 2014-2018, Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*****************************************************************************/
///////// Classes for Grids and Eqs ////////////
#ifndef GRID_HPP
#define GRID_HPP
#include "Expr.hpp"
using namespace std;
namespace yask {
// Fwd decl.
struct Dimensions;
// A class for a Grid.
// This is a generic container for all variables to be accessed
// from the kernel. A 0-D grid is a scalar, a 1-D grid is an array, etc.
// Dims can be the step dim, a domain dim, or anything else.
class Grid : public virtual yc_grid {
protected:
string _name; // name of this grid.
IndexExprPtrVec _dims; // dimensions of this grid.
bool _isScratch = false; // true if a temp grid.
// Ptr to solution that this grid belongs to (its parent).
StencilSolution* _soln = 0;
// How many dims are foldable.
int _numFoldableDims = -1; // -1 => unknown.
// Whether this grid can be vector-folded.
bool _isFoldable = false;
// Values below are computed based on equations.
// Min and max const indices that are used to access each dim.
IntTuple _minIndices, _maxIndices;
// Max abs-value of domain-index halos required by all eqs at
// various step-index values.
// bool key: true=left, false=right.
// int key: step-dim offset or 0 if no step-dim.
// TODO: keep separate halos for each equation bundle.
map<bool, map<int, IntTuple>> _halos;
public:
// Ctors.
Grid(string name,
bool isScratch,
StencilSolution* soln,
const IndexExprPtrVec& dims);
Grid(string name,
bool isScratch,
StencilSolution* soln,
IndexExprPtr dim1 = nullptr,
IndexExprPtr dim2 = nullptr,
IndexExprPtr dim3 = nullptr,
IndexExprPtr dim4 = nullptr,
IndexExprPtr dim5 = nullptr,
IndexExprPtr dim6 = nullptr);
// Dtor.
virtual ~Grid() { }
// Name accessors.
const string& getName() const { return _name; }
void setName(const string& name) { _name = name; }
string getDescr() const;
// Access dims.
virtual const IndexExprPtrVec& getDims() const { return _dims; }
// Step dim or null if none.
virtual const IndexExprPtr getStepDim() const {
for (auto d : _dims)
if (d->getType() == STEP_INDEX)
return d;
return nullptr;
}
// Temp grid?
virtual bool isScratch() const { return _isScratch; }
// Access to solution.
virtual StencilSolution* getSoln() { return _soln; }
virtual void setSoln(StencilSolution* soln) { _soln = soln; }
// Get foldablity.
virtual int getNumFoldableDims() const {
assert(_numFoldableDims >= 0);
return _numFoldableDims;
}
virtual bool isFoldable() const {
assert(_numFoldableDims >= 0);
return _isFoldable;
}
// Get min and max observed indices.
virtual const IntTuple& getMinIndices() const { return _minIndices; }
virtual const IntTuple& getMaxIndices() const { return _maxIndices; }
// Get the max sizes of halo across all steps.
virtual IntTuple getHaloSizes(bool left) const {
IntTuple halo;
if (_halos.count(left)) {
for (auto i : _halos.at(left)) {
auto& right = i.second; // halo at step-val 'i'.
halo = halo.makeUnionWith(right);
halo = halo.maxElements(right, false);
}
}
return halo;
}
// Get the max size in 'dim' of halo across all steps.
virtual int getHaloSize(const string& dim, bool left) const {
int h = 0;
if (_halos.count(left)) {
for (auto i : _halos.at(left)) {
auto& hs = i.second; // halo at step-val 'i'.
auto* p = hs.lookup(dim);
if (p)
h = std::max(h, *p);
}
}
return h;
}
// Determine whether dims are same.
virtual bool areDimsSame(const Grid& other) const {
if (_dims.size() != other._dims.size())
return false;
size_t i = 0;
for (auto& dim : _dims) {
auto d2 = other._dims[i].get();
if (!dim->isSame(d2))
return false;
i++;
}
return true;
}
// Determine how many values in step-dim are needed.
virtual int getStepDimSize() const;
// Determine whether grid can be folded.
virtual void setFolding(const Dimensions& dims);
// Determine whether halo sizes are equal.
virtual bool isHaloSame(const Grid& other) const;
// Update halos based on halo in 'other' grid.
virtual void updateHalo(const Grid& other);
// Update halos based on each value in 'offsets'.
virtual void updateHalo(const IntTuple& offsets);
// Update const indices based on 'indices'.
virtual void updateConstIndices(const IntTuple& indices);
// Create an expression to a specific point in this grid.
// Note that this doesn't actually 'read' or 'write' a value;
// it's just a node in an expression.
virtual GridPointPtr makePoint(const NumExprPtrVec& args);
virtual GridPointPtr makePoint() {
NumExprPtrVec args;
return makePoint(args);
}
// Convenience functions for zero dimensions (scalar).
virtual operator NumExprPtr() { // implicit conversion.
return makePoint();
}
virtual operator GridPointPtr() { // implicit conversion.
return makePoint();
}
virtual GridPointPtr operator()() {
return makePoint();
}
// Convenience functions for one dimension (array).
virtual GridPointPtr operator[](const NumExprArg i1) {
NumExprPtrVec args;
args.push_back(i1);
return makePoint(args);
}
virtual GridPointPtr operator()(const NumExprArg i1) {
return operator[](i1);
}
// Convenience functions for more dimensions.
virtual GridPointPtr operator()(const NumExprArg i1, const NumExprArg i2) {
NumExprPtrVec args;
args.push_back(i1);
args.push_back(i2);
return makePoint(args);
}
virtual GridPointPtr operator()(const NumExprArg i1, const NumExprArg i2,
const NumExprArg i3) {
NumExprPtrVec args;
args.push_back(i1);
args.push_back(i2);
args.push_back(i3);
return makePoint(args);
}
virtual GridPointPtr operator()(const NumExprArg i1, const NumExprArg i2,
const NumExprArg i3, const NumExprArg i4) {
NumExprPtrVec args;
args.push_back(i1);
args.push_back(i2);
args.push_back(i3);
args.push_back(i4);
return makePoint(args);
}
virtual GridPointPtr operator()(const NumExprArg i1, const NumExprArg i2,
const NumExprArg i3, const NumExprArg i4,
const NumExprArg i5) {
NumExprPtrVec args;
args.push_back(i1);
args.push_back(i2);
args.push_back(i3);
args.push_back(i4);
args.push_back(i5);
return makePoint(args);
}
virtual GridPointPtr operator()(const NumExprArg i1, const NumExprArg i2,
const NumExprArg i3, const NumExprArg i4,
const NumExprArg i5, const NumExprArg i6) {
NumExprPtrVec args;
args.push_back(i1);
args.push_back(i2);
args.push_back(i3);
args.push_back(i4);
args.push_back(i5);
args.push_back(i6);
return makePoint(args);
}
// APIs.
virtual const string& get_name() const {
return _name;
}
virtual int get_num_dims() const {
return int(_dims.size());
}
virtual const string& get_dim_name(int n) const {
assert(n >= 0);
assert(n < get_num_dims());
auto dp = _dims.at(n);
assert(dp);
return dp->getName();
}
virtual std::vector<std::string> get_dim_names() const;
virtual yc_grid_point_node_ptr
new_grid_point(const std::vector<yc_number_node_ptr>& index_exprs);
virtual yc_grid_point_node_ptr
new_grid_point(const std::initializer_list<yc_number_node_ptr>& index_exprs) {
std::vector<yc_number_node_ptr> idx_expr_vec(index_exprs);
return new_grid_point(idx_expr_vec);
}
virtual yc_grid_point_node_ptr
new_relative_grid_point(const std::vector<int>& dim_offsets);
virtual yc_grid_point_node_ptr
new_relative_grid_point(const std::initializer_list<int>& dim_offsets) {
std::vector<int> dim_ofs_vec(dim_offsets);
return new_relative_grid_point(dim_ofs_vec);
}
};
// A list of grids. This holds pointers to grids defined by the stencil
// class in the order in which they are added via the INIT_GRID_* macros.
class Grids : public vector_set<Grid*> {
public:
Grids() {}
virtual ~Grids() {}
// Copy ctor.
// Copies list of grid pointers, but not grids (shallow copy).
Grids(const Grids& src) : vector_set<Grid*>(src) {}
// Determine whether each grid can be folded.
virtual void setFolding(const Dimensions& dims) {
for (auto gp : *this)
gp->setFolding(dims);
}
};
// Settings for the compiler.
// May be provided via cmd-line or API.
class CompilerSettings {
public:
int _elem_bytes = 4; // bytes in an FP element.
IntTuple _foldOptions; // vector fold.
IntTuple _clusterOptions; // cluster multipliers.
bool _firstInner = true; // first dimension of fold is unit step.
string _eq_bundle_basename_default = "stencil_bundle";
bool _allowUnalignedLoads = false;
bool _bundleScratch = true;
int _haloSize = 0; // 0 => calculate each halo separately and automatically.
int _stepAlloc = 0; // 0 => calculate step allocation automatically.
int _maxExprSize = 50;
int _minExprSize = 2;
bool _doCse = true; // do common-subexpr elim.
bool _doComb = true; // combine commutative operations.
bool _doOptCluster = true; // apply optimizations also to cluster.
string _eqBundleTargets; // how to bundle equations.
string _gridRegex; // grids to update.
bool _findDeps = true;
};
// Stencil dimensions.
struct Dimensions {
string _stepDim; // step dimension, usually time.
IntTuple _domainDims; // domain dims, usually spatial (with zero value).
IntTuple _stencilDims; // both step and domain dims.
string _innerDim; // domain dim that will be used in the inner loop.
IntTuple _miscDims; // misc dims that are not the step or domain.
// Following contain only domain dims.
IntTuple _scalar; // points in scalar (value 1 in each).
IntTuple _fold; // points in fold.
IntTuple _foldGT1; // subset of _fold w/values >1.
IntTuple _clusterPts; // cluster size in points.
IntTuple _clusterMults; // cluster size in vectors.
// Direction of stepping.
int _stepDir = 0; // 0: undetermined, +1: forward, -1: backward.
Dimensions() {}
virtual ~Dimensions() {}
// Find the dimensions to be used.
void setDims(Grids& grids,
CompilerSettings& settings,
int vlen,
bool is_folding_efficient,
ostream& os);
// Make string like "+(4/VLEN_X)" or "-(2/VLEN_Y)"
// given signed offset and direction.
string makeNormStr(int offset, string dim) const;
// Make string like "t+1" or "t-1".
string makeStepStr(int offset) const;
};
} // namespace yask.
#endif
|
3f1156507f2599c9155ff2156af912137dad2c55 | e74690d56751ee3bba016c7f4447ccbd4aa6301d | /build/classes/URI/CPP/I am Toorg.cpp | 52c9a5a9c3bff00bded574a4cb1f1cf587739e50 | [] | no_license | RedwanSharafatKabir/Online_judge_problem_solve | e9ce789cea79fdf4b6a52cf3e2a3c16a3cbfa1ed | 4eeed84b9e816e2d95b69b10ca9577ca7a430b8a | refs/heads/master | 2021-08-16T20:00:45.876217 | 2020-06-20T19:12:35 | 2020-06-20T19:12:35 | 195,096,415 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 224 | cpp | I am Toorg.cpp | #include <iostream>
using namespace std;
int main()
{
string s;
int n,i;
cin>>n;
for(i=0;i<=n;i++)
{
getline(cin,s);
if(i!=0)
cout<<"I am Toorg!"<<endl;
}
return 0;
}
|
80a1d605886b5af760d12a0066d72f65dd62b096 | 79656f11fe06b2bc6f791d21bbdd449c218efdf0 | /Leetcode/53. Maximum Subarray.cpp | 8fbd72e73fb3bc6a353b2ddbcde20594a5817f4a | [] | no_license | yuzhengang/algorithm | e3696e8e0ac4fbc994bc7db6a1bdedaa8ec3b6b7 | 525e48ec4cfe3447b6d557553805c4e3e1808bf2 | refs/heads/master | 2022-03-25T04:53:44.766099 | 2019-12-31T02:26:44 | 2019-12-31T02:26:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 507 | cpp | 53. Maximum Subarray.cpp | /*Maximum Subarray:Find the contiguous subarray within an array (containing at least one number) which has the largest sum.*/
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if(nums.size() == 0) return 0;
int sum = nums[0];
int result = sum;
for(int i = 1; i < nums.size(); ++i){
if(sum > 0){
sum += nums[i];
}else{
sum = nums[i];
}
result = max(sum, result);
}
return result;
}
}; |
3505de89b5a5ad922c114674a6b1dc25b1acec76 | d170a79fb89f635849389afedbba87baa39baad1 | /Data Structures and Libraries/Non-Linear Data Structures with Built-in Libraries/C++ STL set/11849.cpp | 7f4cc6fc580c74c5073809e8fdefed9f3f6af65d | [] | no_license | hvk3/UVa-submissions | 699283ac3fe315059a0f3e1390777a809e7c6ef6 | b0ca87a08b12f22cd29ec2d80a82d3c78592a0f7 | refs/heads/master | 2020-06-12T14:31:00.747385 | 2019-06-28T20:30:23 | 2019-06-28T20:30:23 | 194,330,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 443 | cpp | 11849.cpp | #include <bits/stdc++.h>
#define ll long long
#define ld long double
#define mod 1000000007
using namespace std;
int main()
{
ios::sync_with_stdio(0);
int i, m, n, x;
while (true)
{
cin >> n >> m;
if (!n && !m)
break;
set<int> s;
int cnt = 0;
for (i = 0; i < n; i++)
{
cin >> x;
s.insert(x);
}
for (i = 0; i < m; i++)
{
cin >> x;
cnt += (s.find(x) != s.end());
}
cout << cnt << '\n';
}
return 0;
} |
46339aa206d14cfc09aa11cfeddff9d6515c3757 | 2c5957a2c68bad3085ce511e1ea73e9d7ff9449c | /others/zad10.cpp | 158d676c725e1fe45c175d31ef41edee0640742f | [] | no_license | AlexMaz99/WDI | 2f3d36501bf1691a35e4de0697c3b974145a0e72 | 1234ddd568bd2961c6f7650c64de8377273886ec | refs/heads/master | 2022-11-26T20:38:43.650632 | 2020-08-05T10:36:53 | 2020-08-05T10:36:53 | 281,486,251 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 970 | cpp | zad10.cpp | #include <iostream>
using namespace std;
const int N = 1000;
int odd_palindrome(int tab[], int n) {
int i = 0, j;
int max_length = 0;
int a, b;
bool is_palindrome;
while (i < n) {
if (tab[i] % 2 == 1 && max_length < 1) max_length = 1;
j = i + 1;
while (tab[i] % 2 == 1 && tab[j] % 2 == 1) //Sprawdza czy granice podciagu sa liczbami nieparzystymi
{
a = i;
b = j;
is_palindrome = true;
while (a <= b && is_palindrome)//Sprawdza czy dany podciag jest palindromem
{
if (tab[a] != tab[b]) is_palindrome = false;
a++;
b--;
}
if (is_palindrome && max_length < j - i + 1) max_length = j - i + 1;
j++;
}
i++;
}
return max_length;
}
int main() {
int tab[N] = {1, 532, 7, 1, 3, 5, 7, 5, 3, 1, 7, 8, 11, 1515, 1};
cout << sprPali(tab, N);//9
} |
e42bb391dea2a5421a65e6d2ee6906b8282cf556 | d64737d31ae9caba2820ea1048be3f9bce708b42 | /cpp/combination-sum-ii.cpp | f4f8db322ed828ed1991946a612b9706cca5dd17 | [] | no_license | ldcduc/leetcode-training | 2453ec13e69160bc29e8e516e19544c2b25bf945 | 40db37375372f14dd45d0a069c8b86fe36221f09 | refs/heads/master | 2023-08-05T01:46:52.993542 | 2021-09-18T16:47:54 | 2021-09-18T16:47:54 | 271,736,046 | 9 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,114 | cpp | combination-sum-ii.cpp | /* Problem url: https://leetcode.com/problems/combination-sum-ii
* Code by: ldcduc
* */
/* Begin of Solution */
class Solution {
public:
set<vector<int>> setResult;
void recursion(int index, vector<int>& candidates, vector<int> &tmp, int remain) {
if (remain <= 0) {
if (remain == 0) {
setResult.insert(tmp);
}
return;
}
if (index < candidates.size()) {
tmp.push_back(candidates[index]);
recursion(index + 1, candidates, tmp, remain - candidates[index]);
tmp.pop_back();
recursion(index + 1, candidates, tmp, remain);
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int> tmp;
recursion(0, candidates, tmp, target);
vector<vector<int>> result;
for (auto item : setResult) {
result.push_back(item);
}
return result;
}
};
/* End of Solution */
/*
* Comment by ldcduc
* Suggested tags: recursion
*
* */
|
01a5c9789f818ad0fc3d4c0283290676498acd44 | 31de33c8ef4722fdea966ea9fc8ab938df1ed16e | /Day26.cpp | 2b7012467f9696f34f0bd7fa4252eca069859465 | [] | no_license | arunmsharma/October-Leetcoding-Challenge | 4b8203fa54eb0ace8c417f671357f9b5a14b49e2 | e22e7ceebeb7ac0c8efa9ba88332b423da9a8332 | refs/heads/main | 2023-01-03T13:52:52.434811 | 2020-11-01T01:34:03 | 2020-11-01T01:34:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | cpp | Day26.cpp | //Day 26
class Solution {
public:
double champagneTower(int poured, int query_row, int query_glass) {
double mat[101][101];
for(int i=0;i<101;i++){
for(int j=0;j<101;j++){
mat[i][j]=0.0;
}
}
mat[0][0]=poured;
for(int row=0;row<=query_row;row++){
for(int col=0;col<=row;col++){
double quant = (mat[row][col]-1.0)/2.0;
if(quant>0){
mat[row+1][col]+=quant;
mat[row+1][col+1]+=quant;
}
}
}
if(mat[query_row][query_glass]>1.0){
return 1.0;
}
else{
return mat[query_row][query_glass];
}
}
};
|
6ffd5d3eb2a8835f1db06c29b2abe932f95be476 | f9109a07bc6ec0a6c6849a187676ec43d31e44de | /source/hdk2/hdk2/bin/unittest/tests-gen/complex/expected_client_inline.cpp | 74e167f2eece5432fd585103ca8c3e643a14ca08 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | rdkcmf/rdkb-Utopia | 1f65d785e5c5f9aaad92185d619482621ee5eac9 | 5765878d1990b050af80ea109ae556fc7b0c27ae | refs/heads/rdk-next | 2023-01-27T11:07:08.540498 | 2022-09-27T11:58:42 | 2023-01-25T09:49:12 | 57,202,219 | 6 | 8 | NOASSERTION | 2023-01-25T17:15:47 | 2016-04-27T09:42:30 | C | UTF-8 | C++ | false | false | 58,878 | cpp | expected_client_inline.cpp | /*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2015 RDK Management
*
* 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.
*/
/**********************************************************************
Copyright [2014] [Cisco Systems, Inc.]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********************************************************************/
// actual_client_inline.cpp - [Generated by hdkcli_cpp]
// Local header.
#include "actual_client_inline.h"
using namespace HDK;
bool HDK::InitializeClient() throw()
{
return !!HDK_CLI_Init();
}
void HDK::UninitializeClient() throw()
{
HDK_CLI_Cleanup();
}
HDK::ClientError Cisco_HNAP::GetServiceInfo
(
HDK::ITarget* pTarget,
const Cisco_HNAP::GetServiceInfoStruct & input,
Cisco_HNAP::GetServiceInfoResponseStruct & output,
enum Cisco_HNAP::GetServiceInfoResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_GetServiceInfo,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_GetServiceInfo);
// Get the result value.
enum Cisco_HNAP::GetServiceInfoResult result = output.get_GetServiceInfoResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Cisco_HNAP::GetServices
(
HDK::ITarget* pTarget,
Cisco_HNAP::GetServicesResponseStruct & output,
enum Cisco_HNAP::GetServicesResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Cisco_HNAP::GetServicesStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_GetServices,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_GetServices);
// Get the result value.
enum Cisco_HNAP::GetServicesResult result = output.get_GetServicesResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::AddPortMapping
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::AddPortMappingStruct & input,
enum Purenetworks_HNAP1::AddPortMappingResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::AddPortMappingResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_AddPortMapping,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_AddPortMapping);
// Get the result value.
enum Purenetworks_HNAP1::AddPortMappingResult result = output.get_AddPortMappingResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::DeletePortMapping
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::DeletePortMappingStruct & input,
enum Purenetworks_HNAP1::DeletePortMappingResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::DeletePortMappingResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_DeletePortMapping,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_DeletePortMapping);
// Get the result value.
enum Purenetworks_HNAP1::DeletePortMappingResult result = output.get_DeletePortMappingResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::DownloadSpeedTest
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::DownloadSpeedTestStruct & input,
Purenetworks_HNAP1::DownloadSpeedTestResponseStruct & output,
enum Purenetworks_HNAP1::DownloadSpeedTestResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_DownloadSpeedTest,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_DownloadSpeedTest);
// Get the result value.
enum Purenetworks_HNAP1::DownloadSpeedTestResult result = output.get_DownloadSpeedTestResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::FirmwareUpload
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::FirmwareUploadStruct & input,
enum Purenetworks_HNAP1::FirmwareUploadResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::FirmwareUploadResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_FirmwareUpload,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_FirmwareUpload);
// Get the result value.
enum Purenetworks_HNAP1::FirmwareUploadResult result = output.get_FirmwareUploadResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetClientStats
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetClientStatsResponseStruct & output,
enum Purenetworks_HNAP1::GetClientStatsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetClientStatsStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetClientStats,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetClientStats);
// Get the result value.
enum Purenetworks_HNAP1::GetClientStatsResult result = output.get_GetClientStatsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetConfigBlob
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetConfigBlobResponseStruct & output,
enum Purenetworks_HNAP1::GetConfigBlobResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetConfigBlobStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetConfigBlob,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetConfigBlob);
// Get the result value.
enum Purenetworks_HNAP1::GetConfigBlobResult result = output.get_GetConfigBlobResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetConnectedDevices
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetConnectedDevicesResponseStruct & output,
enum Purenetworks_HNAP1::GetConnectedDevicesResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetConnectedDevicesStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetConnectedDevices,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetConnectedDevices);
// Get the result value.
enum Purenetworks_HNAP1::GetConnectedDevicesResult result = output.get_GetConnectedDevicesResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetDeviceSettings
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetDeviceSettingsResponseStruct & output,
enum Purenetworks_HNAP1::GetDeviceSettingsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetDeviceSettingsStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetDeviceSettings,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetDeviceSettings);
// Get the result value.
enum Purenetworks_HNAP1::GetDeviceSettingsResult result = output.get_GetDeviceSettingsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetDeviceSettings_GET
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetDeviceSettingsResponseStruct & output,
enum Purenetworks_HNAP1::GetDeviceSettingsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetDeviceSettingsStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_GET_PN_GetDeviceSettings,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_GET_PN_GetDeviceSettings);
// Get the result value.
enum Purenetworks_HNAP1::GetDeviceSettingsResult result = output.get_GetDeviceSettingsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetDeviceSettings2
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetDeviceSettings2ResponseStruct & output,
enum Purenetworks_HNAP1::GetDeviceSettings2Result* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetDeviceSettings2Struct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetDeviceSettings2,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetDeviceSettings2);
// Get the result value.
enum Purenetworks_HNAP1::GetDeviceSettings2Result result = output.get_GetDeviceSettings2Result();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetFirmwareSettings
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetFirmwareSettingsResponseStruct & output,
enum Purenetworks_HNAP1::GetFirmwareSettingsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetFirmwareSettingsStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetFirmwareSettings,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetFirmwareSettings);
// Get the result value.
enum Purenetworks_HNAP1::GetFirmwareSettingsResult result = output.get_GetFirmwareSettingsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetMACFilters2
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetMACFilters2ResponseStruct & output,
enum Purenetworks_HNAP1::GetMACFilters2Result* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetMACFilters2Struct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetMACFilters2,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetMACFilters2);
// Get the result value.
enum Purenetworks_HNAP1::GetMACFilters2Result result = output.get_GetMACFilters2Result();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetNetworkStats
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetNetworkStatsResponseStruct & output,
enum Purenetworks_HNAP1::GetNetworkStatsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetNetworkStatsStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetNetworkStats,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetNetworkStats);
// Get the result value.
enum Purenetworks_HNAP1::GetNetworkStatsResult result = output.get_GetNetworkStatsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetPortMappings
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetPortMappingsResponseStruct & output,
enum Purenetworks_HNAP1::GetPortMappingsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetPortMappingsStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetPortMappings,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetPortMappings);
// Get the result value.
enum Purenetworks_HNAP1::GetPortMappingsResult result = output.get_GetPortMappingsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetRouterLanSettings2
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetRouterLanSettings2ResponseStruct & output,
enum Purenetworks_HNAP1::GetRouterLanSettings2Result* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetRouterLanSettings2Struct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetRouterLanSettings2,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetRouterLanSettings2);
// Get the result value.
enum Purenetworks_HNAP1::GetRouterLanSettings2Result result = output.get_GetRouterLanSettings2Result();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetRouterSettings
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetRouterSettingsResponseStruct & output,
enum Purenetworks_HNAP1::GetRouterSettingsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetRouterSettingsStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetRouterSettings,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetRouterSettings);
// Get the result value.
enum Purenetworks_HNAP1::GetRouterSettingsResult result = output.get_GetRouterSettingsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetWLanRadioFrequencies
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetWLanRadioFrequenciesResponseStruct & output,
enum Purenetworks_HNAP1::GetWLanRadioFrequenciesResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetWLanRadioFrequenciesStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWLanRadioFrequencies,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWLanRadioFrequencies);
// Get the result value.
enum Purenetworks_HNAP1::GetWLanRadioFrequenciesResult result = output.get_GetWLanRadioFrequenciesResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetWLanRadioSecurity
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::GetWLanRadioSecurityStruct & input,
Purenetworks_HNAP1::GetWLanRadioSecurityResponseStruct & output,
enum Purenetworks_HNAP1::GetWLanRadioSecurityResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWLanRadioSecurity,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWLanRadioSecurity);
// Get the result value.
enum Purenetworks_HNAP1::GetWLanRadioSecurityResult result = output.get_GetWLanRadioSecurityResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetWLanRadioSettings
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::GetWLanRadioSettingsStruct & input,
Purenetworks_HNAP1::GetWLanRadioSettingsResponseStruct & output,
enum Purenetworks_HNAP1::GetWLanRadioSettingsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWLanRadioSettings,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWLanRadioSettings);
// Get the result value.
enum Purenetworks_HNAP1::GetWLanRadioSettingsResult result = output.get_GetWLanRadioSettingsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetWLanRadios
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetWLanRadiosResponseStruct & output,
enum Purenetworks_HNAP1::GetWLanRadiosResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetWLanRadiosStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWLanRadios,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWLanRadios);
// Get the result value.
enum Purenetworks_HNAP1::GetWLanRadiosResult result = output.get_GetWLanRadiosResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetWanInfo
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetWanInfoResponseStruct & output,
enum Purenetworks_HNAP1::GetWanInfoResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetWanInfoStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWanInfo,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWanInfo);
// Get the result value.
enum Purenetworks_HNAP1::GetWanInfoResult result = output.get_GetWanInfoResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::GetWanSettings
(
HDK::ITarget* pTarget,
Purenetworks_HNAP1::GetWanSettingsResponseStruct & output,
enum Purenetworks_HNAP1::GetWanSettingsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::GetWanSettingsStruct input;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWanSettings,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_GetWanSettings);
// Get the result value.
enum Purenetworks_HNAP1::GetWanSettingsResult result = output.get_GetWanSettingsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::IsDeviceReady
(
HDK::ITarget* pTarget,
enum Purenetworks_HNAP1::IsDeviceReadyResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::IsDeviceReadyStruct input;
Purenetworks_HNAP1::IsDeviceReadyResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_IsDeviceReady,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_IsDeviceReady);
// Get the result value.
enum Purenetworks_HNAP1::IsDeviceReadyResult result = output.get_IsDeviceReadyResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::Reboot
(
HDK::ITarget* pTarget,
enum Purenetworks_HNAP1::RebootResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::RebootStruct input;
Purenetworks_HNAP1::RebootResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_Reboot,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_Reboot);
// Get the result value.
enum Purenetworks_HNAP1::RebootResult result = output.get_RebootResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::RenewWanConnection
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::RenewWanConnectionStruct & input,
enum Purenetworks_HNAP1::RenewWanConnectionResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::RenewWanConnectionResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_RenewWanConnection,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_RenewWanConnection);
// Get the result value.
enum Purenetworks_HNAP1::RenewWanConnectionResult result = output.get_RenewWanConnectionResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::RestoreFactoryDefaults
(
HDK::ITarget* pTarget,
enum Purenetworks_HNAP1::RestoreFactoryDefaultsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::RestoreFactoryDefaultsStruct input;
Purenetworks_HNAP1::RestoreFactoryDefaultsResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_RestoreFactoryDefaults,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_RestoreFactoryDefaults);
// Get the result value.
enum Purenetworks_HNAP1::RestoreFactoryDefaultsResult result = output.get_RestoreFactoryDefaultsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::SetAccessPointMode
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::SetAccessPointModeStruct & input,
Purenetworks_HNAP1::SetAccessPointModeResponseStruct & output,
enum Purenetworks_HNAP1::SetAccessPointModeResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_SetAccessPointMode,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_SetAccessPointMode);
// Get the result value.
enum Purenetworks_HNAP1::SetAccessPointModeResult result = output.get_SetAccessPointModeResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::SetConfigBlob
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::SetConfigBlobStruct & input,
enum Purenetworks_HNAP1::SetConfigBlobResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::SetConfigBlobResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_SetConfigBlob,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_SetConfigBlob);
// Get the result value.
enum Purenetworks_HNAP1::SetConfigBlobResult result = output.get_SetConfigBlobResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::SetDeviceSettings
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::SetDeviceSettingsStruct & input,
enum Purenetworks_HNAP1::SetDeviceSettingsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::SetDeviceSettingsResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_SetDeviceSettings,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_SetDeviceSettings);
// Get the result value.
enum Purenetworks_HNAP1::SetDeviceSettingsResult result = output.get_SetDeviceSettingsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::SetDeviceSettings2
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::SetDeviceSettings2Struct & input,
enum Purenetworks_HNAP1::SetDeviceSettings2Result* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::SetDeviceSettings2ResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_SetDeviceSettings2,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_SetDeviceSettings2);
// Get the result value.
enum Purenetworks_HNAP1::SetDeviceSettings2Result result = output.get_SetDeviceSettings2Result();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::SetMACFilters2
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::SetMACFilters2Struct & input,
enum Purenetworks_HNAP1::SetMACFilters2Result* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::SetMACFilters2ResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_SetMACFilters2,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_SetMACFilters2);
// Get the result value.
enum Purenetworks_HNAP1::SetMACFilters2Result result = output.get_SetMACFilters2Result();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::SetRouterLanSettings2
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::SetRouterLanSettings2Struct & input,
enum Purenetworks_HNAP1::SetRouterLanSettings2Result* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::SetRouterLanSettings2ResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_SetRouterLanSettings2,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_SetRouterLanSettings2);
// Get the result value.
enum Purenetworks_HNAP1::SetRouterLanSettings2Result result = output.get_SetRouterLanSettings2Result();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::SetRouterSettings
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::SetRouterSettingsStruct & input,
enum Purenetworks_HNAP1::SetRouterSettingsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::SetRouterSettingsResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_SetRouterSettings,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_SetRouterSettings);
// Get the result value.
enum Purenetworks_HNAP1::SetRouterSettingsResult result = output.get_SetRouterSettingsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::SetWLanRadioFrequency
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::SetWLanRadioFrequencyStruct & input,
enum Purenetworks_HNAP1::SetWLanRadioFrequencyResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::SetWLanRadioFrequencyResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_SetWLanRadioFrequency,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_SetWLanRadioFrequency);
// Get the result value.
enum Purenetworks_HNAP1::SetWLanRadioFrequencyResult result = output.get_SetWLanRadioFrequencyResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::SetWLanRadioSecurity
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::SetWLanRadioSecurityStruct & input,
enum Purenetworks_HNAP1::SetWLanRadioSecurityResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::SetWLanRadioSecurityResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_SetWLanRadioSecurity,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_SetWLanRadioSecurity);
// Get the result value.
enum Purenetworks_HNAP1::SetWLanRadioSecurityResult result = output.get_SetWLanRadioSecurityResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::SetWLanRadioSettings
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::SetWLanRadioSettingsStruct & input,
enum Purenetworks_HNAP1::SetWLanRadioSettingsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::SetWLanRadioSettingsResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_SetWLanRadioSettings,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_SetWLanRadioSettings);
// Get the result value.
enum Purenetworks_HNAP1::SetWLanRadioSettingsResult result = output.get_SetWLanRadioSettingsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
HDK::ClientError Purenetworks_HNAP1::SetWanSettings
(
HDK::ITarget* pTarget,
const Purenetworks_HNAP1::SetWanSettingsStruct & input,
enum Purenetworks_HNAP1::SetWanSettingsResult* presult /* = NULL */,
unsigned int timeoutSecs /* = 0 */
) throw()
{
if (!pTarget)
{
return ClientError_InvalidArg;
}
Purenetworks_HNAP1::SetWanSettingsResponseStruct output;
ClientError error = pTarget->Request(timeoutSecs,
ACTUAL_CLIENT_MOD_Module(),
ACTUAL_CLIENT_MOD_MethodEnum_PN_SetWanSettings,
input,
&output);
const HDK_MOD_Method* pMethod = HDK_MOD_GetMethod(ACTUAL_CLIENT_MOD_Module(), ACTUAL_CLIENT_MOD_MethodEnum_PN_SetWanSettings);
// Get the result value.
enum Purenetworks_HNAP1::SetWanSettingsResult result = output.get_SetWanSettingsResult();
if (NULL != presult)
{
*presult = result;
}
// Determine if there was an HNAP-result, and whether it was an error or not.
if ((ClientError_OK == error) && (HDK_XML_BuiltinElement_Unknown != pMethod->hnapResultElement))
{
if ((pMethod->hnapResultOK != (int)result) && (pMethod->hnapResultREBOOT != (int)result))
{
// An HNAP error response.
error = HDK::ClientError_HnapMethod;
}
}
return error;
}
|
0093a28a846eb1c1c1d7898d3601f771d4322a38 | e3b67db8b0ea9af2ba890dc4e119ff22876a2232 | /extensions/jni/jvm/JniLogger.cpp | ae3985d9d4f8f8c9bef7aa22d7ccb2304ac9993e | [
"MPL-2.0",
"Apache-2.0",
"BSD-3-Clause",
"curl",
"OpenSSL",
"libtiff",
"bzip2-1.0.6",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"MIT-0",
"Beerware",
"Zlib",
"NCSA",
"ISC",
"CC0-1.0",
"LicenseRef-scancode-object-form-exception-to-mit",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-protobuf",
"Libpng",
"LicenseRef-scancode-mit-old-style",
"JSON",
"BSD-1-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"LicenseRef-scancode-bsd-unchanged"
] | permissive | apache/nifi-minifi-cpp | 90919e880bf7ac1ce51b8ad0f173cc4e3aded7fe | 9b55dc0c0f17a190f3e9ade87070a28faf542c25 | refs/heads/main | 2023-08-29T22:29:02.420503 | 2023-08-25T17:21:53 | 2023-08-25T17:21:53 | 56,750,161 | 131 | 114 | Apache-2.0 | 2023-09-14T05:53:30 | 2016-04-21T07:00:06 | C++ | UTF-8 | C++ | false | false | 4,547 | cpp | JniLogger.cpp | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "JniLogger.h"
#include <string>
#include <memory>
#include <algorithm>
#include <iterator>
#include <set>
#include "core/Property.h"
#include "io/validation.h"
#include "utils/StringUtils.h"
#include "utils/file/FileUtils.h"
#include "properties/Configure.h"
#include "JVMLoader.h"
#include "core/Processor.h"
#include "JniFlowFile.h"
#include "../JavaException.h"
#include "core/logging/Logger.h"
#include "../JNIUtil.h"
#ifdef __cplusplus
extern "C" {
#endif
namespace minifi = org::apache::nifi::minifi;
JNIEXPORT jboolean JNICALL Java_org_apache_nifi_processor_JniLogger_isWarnEnabled(JNIEnv *env, jobject obj) {
minifi::jni::JniLogger *logger_ref = minifi::jni::JVMLoader::getPtr<minifi::jni::JniLogger>(env, obj);
return logger_ref->logger_reference_->should_log(minifi::core::logging::LOG_LEVEL::warn);
}
JNIEXPORT jboolean JNICALL Java_org_apache_nifi_processor_JniLogger_isTraceEnabled(JNIEnv *env, jobject obj) {
minifi::jni::JniLogger *logger_ref = minifi::jni::JVMLoader::getPtr<minifi::jni::JniLogger>(env, obj);
return logger_ref->logger_reference_->should_log(minifi::core::logging::LOG_LEVEL::trace);
}
JNIEXPORT jboolean JNICALL Java_org_apache_nifi_processor_JniLogger_isInfoEnabled(JNIEnv *env, jobject obj) {
minifi::jni::JniLogger *logger_ref = minifi::jni::JVMLoader::getPtr<minifi::jni::JniLogger>(env, obj);
return logger_ref->logger_reference_->should_log(minifi::core::logging::LOG_LEVEL::info);
}
JNIEXPORT jboolean JNICALL Java_org_apache_nifi_processor_JniLogger_isErrorEnabled(JNIEnv *env, jobject obj) {
minifi::jni::JniLogger *logger_ref = minifi::jni::JVMLoader::getPtr<minifi::jni::JniLogger>(env, obj);
return logger_ref->logger_reference_->should_log(minifi::core::logging::LOG_LEVEL::err);
}
JNIEXPORT jboolean JNICALL Java_org_apache_nifi_processor_JniLogger_isDebugEnabled(JNIEnv *env, jobject obj) {
minifi::jni::JniLogger *logger_ref = minifi::jni::JVMLoader::getPtr<minifi::jni::JniLogger>(env, obj);
return logger_ref->logger_reference_->should_log(minifi::core::logging::LOG_LEVEL::debug);
}
JNIEXPORT void JNICALL Java_org_apache_nifi_processor_JniLogger_warn(JNIEnv *env, jobject obj, jstring msg) {
minifi::jni::JniLogger *logger_ref = minifi::jni::JVMLoader::getPtr<minifi::jni::JniLogger>(env, obj);
if (!logger_ref)
return;
logger_ref->logger_reference_->log_warn(JniStringToUTF(env, msg).c_str());
}
JNIEXPORT void JNICALL Java_org_apache_nifi_processor_JniLogger_error(JNIEnv *env, jobject obj, jstring msg) {
minifi::jni::JniLogger *logger_ref = minifi::jni::JVMLoader::getPtr<minifi::jni::JniLogger>(env, obj);
if (!logger_ref)
return;
logger_ref->logger_reference_->log_error(JniStringToUTF(env, msg).c_str());
}
JNIEXPORT void JNICALL Java_org_apache_nifi_processor_JniLogger_info(JNIEnv *env, jobject obj, jstring msg) {
minifi::jni::JniLogger *logger_ref = minifi::jni::JVMLoader::getPtr<minifi::jni::JniLogger>(env, obj);
if (!logger_ref)
return;
logger_ref->logger_reference_->log_info(JniStringToUTF(env, msg).c_str());
}
JNIEXPORT void JNICALL Java_org_apache_nifi_processor_JniLogger_debug(JNIEnv *env, jobject obj, jstring msg) {
minifi::jni::JniLogger *logger_ref = minifi::jni::JVMLoader::getPtr<minifi::jni::JniLogger>(env, obj);
if (!logger_ref)
return;
logger_ref->logger_reference_->log_debug(JniStringToUTF(env, msg).c_str());
}
JNIEXPORT void JNICALL Java_org_apache_nifi_processor_JniLogger_trace(JNIEnv *env, jobject obj, jstring msg) {
minifi::jni::JniLogger *logger_ref = minifi::jni::JVMLoader::getPtr<minifi::jni::JniLogger>(env, obj);
if (!logger_ref)
return;
logger_ref->logger_reference_->log_trace(JniStringToUTF(env, msg).c_str());
}
#ifdef __cplusplus
}
#endif
|
295bf6b6001c97eaee75ea120fda8ae8d14ef7aa | 5a25b69e4424e13ab170cd3166e88b1f47465cf6 | /Calculate/calculate.cpp | ba370c84db29bda12fe1be7930feb76bb22fd132 | [] | no_license | PinkLilLi/FirstResponsitory | d63d698785f744f2c44535a6b848a9e4fe729226 | e787d65bb4c393f803ad219dd2bc2a8ebb29b5ec | refs/heads/master | 2021-01-21T07:07:15.675546 | 2017-02-27T14:20:01 | 2017-02-27T14:20:01 | 83,317,866 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 206 | cpp | calculate.cpp | #include<iostream>
#include"Add.h"
#include"Subtraction.h"
using namespace std;
void main() {
int a = 1;
int b = 2;
int c, d;
c = Add(a, b);
d = Subtraction(a, b);
cout << c << endl << d << endl;
}
|
0bcc0eada37fb52903f860180e3b51da59ba2367 | c80c197274f25f1008aef127eca7c7824461baec | /src/simulation/ecosystem/iteration/Iteration.h | 130ede33e3ff1c188d9834d579a673b3c004ac67 | [] | no_license | LiamEverton/CS-3210-Project-Assignment | b8fde18b7c85ca47a5d23f927a8e4f0da371c5d0 | c07274d2b765c31ff2996e1bcec93fba8d932a7d | refs/heads/master | 2020-05-07T15:18:37.699587 | 2019-05-04T19:26:39 | 2019-05-04T19:26:39 | 180,631,270 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 665 | h | Iteration.h | #ifndef CS_3210_PROJECT_ASSIGNMENT_ITERATION_H
#define CS_3210_PROJECT_ASSIGNMENT_ITERATION_H
class EcoSystem;
/**
* Iteration, representing the single 'iteration' simulation of a EcoSystem.
*/
class Iteration {
//The owning EcoSystem.
EcoSystem *ecosystem;
public:
/**
* Constructs a new Iteration.
*
* @param ecosystem - the owning EcoSystem.
*/
Iteration(EcoSystem *ecosystem);
/**
* Runs this iteration.
*/
void run();
/**
* Gets the owning EcoSystem.
*
* @return the owning EcoSystem.
*/
EcoSystem *getEcoSystem();
};
#endif //CS_3210_PROJECT_ASSIGNMENT_ITERATION_H
|
82337e53659e9e207f965cc9e219366209972793 | 94c68d17a0559e9ad1ed9bc85d9f22fd857b70f8 | /Mail Delivery.cpp | a310667cde3d55247f1370b6984fe375e224e6aa | [] | no_license | ShreyanshMehta/CSES-Problemset---Graph-Algorithms | 7d8c96eb586e3f3301e3050ea13420784b60976b | 70750bdc7bfaf9728be74ad48f0c1cfd738908bf | refs/heads/main | 2023-01-20T04:06:28.318919 | 2020-12-03T19:05:34 | 2020-12-03T19:05:34 | 306,842,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,517 | cpp | Mail Delivery.cpp | #include<bits/stdc++.h>
using namespace std;
#define fi(a,b) for(int i=a;i<b;i++)
#define fj(a,b) for(int j=a;j<b;j++)
#define ff first
#define ss second
#define ll long long
#define ld long double
#define ull unsigned long long
#define bp(x) __builtin_popcount(x)
#define pr(x) for(auto it: x) cout<<it<<" "; cout<<endl;
#define getMax(x) max_element(x.begin(),x.end())
#define getMin(x) min_element(x.begin(),x.end())
#define endl "\n"
typedef vector<int> vi;
typedef vector< pair<int,int> > vii;
typedef vector<long long> vl;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector< pair<ll,ll> > vll;
//int dx[]={1,0,-1,0};
//int dy[]={0,1,0,-1};
//int dx[]={-1,0,1,1,1,0,-1,-1};
//int dy[]={-1,-1,-1,0,1,1,1,0};
struct eulerGraph{
int n, m, odd = 0;
vector<bool>vis;
vector<set<int>>adj;
vi ans;
//n--Vertices m--Edges
eulerGraph(int n, int m){
this->n = n;
this->m = m;
adj.assign(n, set<int>({}));
vis.assign(n, 0);
}
void addEdge(int u, int v){
adj[u].insert(v);
adj[v].insert(u);
}
void findPath(int start_node){
int node = start_node;
stack<int>st;
while(!st.empty() or adj[node].size()){
if(adj[node].size()==0){
ans.push_back(node);
node = st.top();
st.pop();
}
else{
int u = *adj[node].begin();
adj[node].erase(adj[node].begin());
adj[u].erase(adj[u].find(node));
st.push(node);
node = u;
}
}
if(odd==0)
ans.push_back(start_node);
}
bool getAns(int start_node){
fi(0, n){
if(adj[i].size()%2) odd++;
}
findPath(start_node);
if(ans.size()!=m+1 or odd>2) return 0;
else return 1;
}
};
void nikal_pehli_fursat_mai(){
int n, m;
cin>>n>>m;
eulerGraph G(n, m);
fi(0, m){
int u, v;
cin>>u>>v;
u--; v--;
G.addEdge(u, v);
}
if(G.getAns(0)){
for(auto i: G.ans)
cout<<i+1<<" ";
}
else{
cout<<"IMPOSSIBLE"<<endl;
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios::sync_with_stdio(0);
cin.tie(0);
int tc=1;
// cin>>tc;
while(tc--){
nikal_pehli_fursat_mai();
}
}
|
61046b59e3b14fbb1f3e0848314f042ab239b261 | 16bfa77ab105896cf044b8f6c8e15f75e3a8c8e8 | /Latest/MorphingClock/Digit.h | ede50576b9373f0e72d108f6df1c3b0c4a4b0a89 | [] | no_license | PeterTeunissen/HariFun_166_Morphing_Clock | e59d2fb717851f6864cb0a6fda21af546bdd4402 | 087128207d3dd86aa604c7be60310980117619b4 | refs/heads/master | 2020-04-18T04:15:24.798464 | 2019-02-01T14:25:05 | 2019-02-01T14:25:05 | 167,231,805 | 1 | 0 | null | 2019-01-23T18:20:37 | 2019-01-23T18:20:37 | null | UTF-8 | C++ | false | false | 1,216 | h | Digit.h | #ifndef DIGIT_H
#define DIGIT_H
#include <Arduino.h>
#include <PxMatrix.h> // https://github.com/2dom/PxMatrix
class Digit {
public:
Digit(PxMATRIX* d, byte value, uint16_t xo, uint16_t yo, uint16_t color);
void Draw(byte value);
void Morph(byte newValue);
byte Value();
void DrawColon(uint16_t c);
void setSize(int sz);
void setColonLeft(bool b);
void setX(uint16_t x);
uint16_t getX();
void setY(uint16_t y);
uint16_t getY();
void setColor(uint16_t color);
void hide();
private:
PxMATRIX* _display;
byte _value;
uint16_t _color;
uint16_t xOffset;
uint16_t yOffset;
int animSpeed = 30;
int segHeight = 6;
int segWidth = segHeight;
bool colonLeft = true;
void drawPixel(uint16_t x, uint16_t y, uint16_t c);
void drawFillRect(uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t c);
void drawLine(uint16_t x, uint16_t y, uint16_t x2, uint16_t y2, uint16_t c);
void drawSeg(byte seg);
void Morph2();
void Morph3();
void Morph4();
void Morph5();
void Morph6();
void Morph7();
void Morph8();
void Morph9();
void Morph0();
void Morph1();
};
#endif
|
e7a1975866d254449f03b91577f6c9f1b6e7c077 | 2e2eb7e00899bd75ce9a6f6bf81267dde31e0e69 | /조재휘/07-07-2020/12790.cpp | d5f0131e098502b11d0f40bb7563b1aa70069510 | [] | no_license | wogus3602/study | 3f8e47bbcf7a45aa1ba0781f50140a6f9be89764 | cba81bec9a7044567627d197ae9c8620d4fb8729 | refs/heads/master | 2022-11-18T23:32:50.632074 | 2020-07-10T04:02:42 | 2020-07-10T04:02:42 | 273,912,878 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 526 | cpp | 12790.cpp | #include <iostream>
using namespace std;
int main() {
int n;
int HP, MP, ATK, DEF;
int HP_item, MP_item, ATK_item, DEF_item;
int CP;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> HP >> MP >> ATK >> DEF;
cin >> HP_item >> MP_item >> ATK_item >> DEF_item;
HP += HP_item;
MP += MP_item;
ATK += ATK_item;
DEF += DEF_item;
if (HP < 1) HP = 1;
if (MP < 1) MP = 1;
if (ATK < 0) ATK = 0;
CP = HP + (5 * MP) + 2 * (ATK + DEF);
cout << CP << endl;
}
return 0;
}
|
4f99a971d81bda771f4f9d8b84701d3838b577f6 | 020fa5a092920d757fd9a301ead15b3591c07be9 | /src/nn/NeuronFunction.cpp | c5e5478a24980ee88cd412233b9f1cbcf49bbec5 | [] | no_license | DolotovEvgeniy/Artifical-life | ad554030386fde2ef7849319f9ce6cf802dd722d | b188ad3b1dc1c700ebbd46ae61caacaf37dbbf75 | refs/heads/master | 2021-01-20T07:15:24.982465 | 2014-06-09T19:53:02 | 2014-06-09T19:53:02 | 20,656,749 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | cpp | NeuronFunction.cpp | #include <vector>
#include <math.h>
#include <iostream>
using namespace std;
double linear(double value, std::vector<double> params)
{
double a = params[0];
double b = params[1];
return (a * value) + b;
}
double sign(double value, std::vector<double> params)
{
double a = params[0];
if (value > a)
{
return 1;
}
else
{
return 0;
}
}
double sigma (double value, std::vector<double> params)
{
double a = params[0];
double b = params[1];
double c = params[2];
return a / (b + exp(-value * c) + 1);
}
|
24176939ef29f9e4ab2bfb018df4060e31d6b336 | c3c3b97e824370642f20a0cb408bb054c7b6049c | /BOJ/스택/스택/main.cpp | 54ec58ef6c90223cd70de8e5ef99bab8ff150a99 | [] | no_license | chrisais9/algorithm | 00333c0f731ffd5971bf20871e622b48d22617c2 | 2a4fdf8e3f5d3da0b88cd2832d74e8e1dcbe09e9 | refs/heads/master | 2022-06-13T04:57:32.181733 | 2022-06-03T08:35:36 | 2022-06-03T08:35:36 | 136,615,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | cpp | main.cpp | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int tb[100010],n;
vector<int> v;
vector<string> way;
int main()
{
ios::sync_with_stdio(false);
int i,an=0;
cin>>n;
for(i=0;i<n;i++)cin>>tb[i];
for(i=1;i<=n;i++)
{
v.push_back(i);
way.push_back("+");
while(!v.empty())
{
if(v.back()!=tb[an])break;
an++;
v.pop_back();
way.push_back("-");
}
}
if(!v.empty())cout<<"NO"<<endl;
else for(i=0;i<way.size();i++)cout<<way[i]<<endl;
}
|
b39f2cef4cbfb3482817961e92931123706abd02 | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/libs/extension/examples/multiple_inheritance/computer.cpp | af79271d0aebd7909d0447e13fda76696696c9e0 | [] | no_license | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 1,107 | cpp | computer.cpp | /*
* Boost.Extension / multiple inheritance example (computer)
*
* (C) Copyright Jeremy Pack 2007
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org/ for latest version.
*/
/* The following lines are only necessary because when
are linking to this dll at compile time with another
dll on Windows. As such, standard __declspec stuff
is required.
This example is something of a special case - normally
these types of macros are not necessary for classes
- see the FAQ.
*/
#include <boost/extension/extension.hpp>
#define BOOST_EXTENSION_COMPUTER_DECL BOOST_EXTENSION_EXPORT_DECL
#include "computer.hpp"
#include <boost/extension/type_map.hpp>
#include <boost/extension/factory.hpp>
std::string computer::list_capabilities()
{
return "\nIt computes.";
}
using boost::extensions::factory;
BOOST_EXTENSION_TYPE_MAP_FUNCTION {
types.get<std::map<std::string, factory<computer> > >()
["\nA computer exported as a computer"].set<computer>();
}
|
821b010f0b6074a32c9dd26f93a0f3d843388fb0 | 4043f78994d68efc7d0fe9805cd91ec46a4d16f4 | /src/Eigen/src/Core/arch/AltiVec/MatrixProductCommon.h | 33d543494b26769c51a7783f67f9cbab9c4e1bef | [
"Apache-2.0"
] | permissive | fanvanzh/3dtiles | d08d30956e790e451beab79c82acddc42a051e02 | a7c3000c794f5fbcf0defe72cabd0465dbf9df6e | refs/heads/master | 2023-09-03T14:08:09.905715 | 2023-08-30T02:30:02 | 2023-08-30T02:30:02 | 120,919,743 | 1,713 | 555 | Apache-2.0 | 2023-08-30T02:30:03 | 2018-02-09T15:07:43 | C++ | UTF-8 | C++ | false | false | 9,490 | h | MatrixProductCommon.h | //#define EIGEN_POWER_USE_PREFETCH // Use prefetching in gemm routines
#ifdef EIGEN_POWER_USE_PREFETCH
#define EIGEN_POWER_PREFETCH(p) prefetch(p)
#else
#define EIGEN_POWER_PREFETCH(p)
#endif
namespace Eigen {
namespace internal {
template<typename Scalar, typename Packet, typename DataMapper, typename Index, const Index accRows>
EIGEN_STRONG_INLINE void gemm_extra_col(
const DataMapper& res,
const Scalar* lhs_base,
const Scalar* rhs_base,
Index depth,
Index strideA,
Index offsetA,
Index row,
Index col,
Index remaining_rows,
Index remaining_cols,
const Packet& pAlpha);
template<typename Scalar, typename Packet, typename DataMapper, typename Index, const Index accRows, const Index accCols>
EIGEN_STRONG_INLINE void gemm_extra_row(
const DataMapper& res,
const Scalar* lhs_base,
const Scalar* rhs_base,
Index depth,
Index strideA,
Index offsetA,
Index row,
Index col,
Index rows,
Index cols,
Index remaining_rows,
const Packet& pAlpha,
const Packet& pMask);
template<typename Scalar, typename Packet, typename DataMapper, typename Index, const Index accCols>
EIGEN_STRONG_INLINE void gemm_unrolled_col(
const DataMapper& res,
const Scalar* lhs_base,
const Scalar* rhs_base,
Index depth,
Index strideA,
Index offsetA,
Index& row,
Index rows,
Index col,
Index remaining_cols,
const Packet& pAlpha);
template<typename Packet>
EIGEN_ALWAYS_INLINE Packet bmask(const int remaining_rows);
template<typename Scalar, typename Packet, typename Packetc, typename DataMapper, typename Index, const Index accRows, const Index accCols, bool ConjugateLhs, bool ConjugateRhs, bool LhsIsReal, bool RhsIsReal>
EIGEN_STRONG_INLINE void gemm_complex_extra_col(
const DataMapper& res,
const Scalar* lhs_base,
const Scalar* rhs_base,
Index depth,
Index strideA,
Index offsetA,
Index strideB,
Index row,
Index col,
Index remaining_rows,
Index remaining_cols,
const Packet& pAlphaReal,
const Packet& pAlphaImag);
template<typename Scalar, typename Packet, typename Packetc, typename DataMapper, typename Index, const Index accRows, const Index accCols, bool ConjugateLhs, bool ConjugateRhs, bool LhsIsReal, bool RhsIsReal>
EIGEN_STRONG_INLINE void gemm_complex_extra_row(
const DataMapper& res,
const Scalar* lhs_base,
const Scalar* rhs_base,
Index depth,
Index strideA,
Index offsetA,
Index strideB,
Index row,
Index col,
Index rows,
Index cols,
Index remaining_rows,
const Packet& pAlphaReal,
const Packet& pAlphaImag,
const Packet& pMask);
template<typename Scalar, typename Packet, typename Packetc, typename DataMapper, typename Index, const Index accCols, bool ConjugateLhs, bool ConjugateRhs, bool LhsIsReal, bool RhsIsReal>
EIGEN_STRONG_INLINE void gemm_complex_unrolled_col(
const DataMapper& res,
const Scalar* lhs_base,
const Scalar* rhs_base,
Index depth,
Index strideA,
Index offsetA,
Index strideB,
Index& row,
Index rows,
Index col,
Index remaining_cols,
const Packet& pAlphaReal,
const Packet& pAlphaImag);
template<typename Scalar, typename Packet>
EIGEN_ALWAYS_INLINE Packet ploadLhs(const Scalar* lhs);
template<typename DataMapper, typename Packet, typename Index, const Index accCols, int N, int StorageOrder>
EIGEN_ALWAYS_INLINE void bload(PacketBlock<Packet,4>& acc, const DataMapper& res, Index row, Index col);
template<typename DataMapper, typename Packet, typename Index, const Index accCols, int N, int StorageOrder>
EIGEN_ALWAYS_INLINE void bload(PacketBlock<Packet,8>& acc, const DataMapper& res, Index row, Index col);
template<typename Packet>
EIGEN_ALWAYS_INLINE void bscale(PacketBlock<Packet,4>& acc, PacketBlock<Packet,4>& accZ, const Packet& pAlpha);
template<typename Packet, int N>
EIGEN_ALWAYS_INLINE void bscalec(PacketBlock<Packet,N>& aReal, PacketBlock<Packet,N>& aImag, const Packet& bReal, const Packet& bImag, PacketBlock<Packet,N>& cReal, PacketBlock<Packet,N>& cImag);
const static Packet16uc p16uc_SETCOMPLEX32_FIRST = { 0, 1, 2, 3,
16, 17, 18, 19,
4, 5, 6, 7,
20, 21, 22, 23};
const static Packet16uc p16uc_SETCOMPLEX32_SECOND = { 8, 9, 10, 11,
24, 25, 26, 27,
12, 13, 14, 15,
28, 29, 30, 31};
//[a,b],[ai,bi] = [a,ai] - This is equivalent to p16uc_GETREAL64
const static Packet16uc p16uc_SETCOMPLEX64_FIRST = { 0, 1, 2, 3, 4, 5, 6, 7,
16, 17, 18, 19, 20, 21, 22, 23};
//[a,b],[ai,bi] = [b,bi] - This is equivalent to p16uc_GETIMAG64
const static Packet16uc p16uc_SETCOMPLEX64_SECOND = { 8, 9, 10, 11, 12, 13, 14, 15,
24, 25, 26, 27, 28, 29, 30, 31};
// Grab two decouples real/imaginary PacketBlocks and return two coupled (real/imaginary pairs) PacketBlocks.
template<typename Packet, typename Packetc>
EIGEN_ALWAYS_INLINE void bcouple_common(PacketBlock<Packet,4>& taccReal, PacketBlock<Packet,4>& taccImag, PacketBlock<Packetc, 4>& acc1, PacketBlock<Packetc, 4>& acc2)
{
acc1.packet[0].v = vec_perm(taccReal.packet[0], taccImag.packet[0], p16uc_SETCOMPLEX32_FIRST);
acc1.packet[1].v = vec_perm(taccReal.packet[1], taccImag.packet[1], p16uc_SETCOMPLEX32_FIRST);
acc1.packet[2].v = vec_perm(taccReal.packet[2], taccImag.packet[2], p16uc_SETCOMPLEX32_FIRST);
acc1.packet[3].v = vec_perm(taccReal.packet[3], taccImag.packet[3], p16uc_SETCOMPLEX32_FIRST);
acc2.packet[0].v = vec_perm(taccReal.packet[0], taccImag.packet[0], p16uc_SETCOMPLEX32_SECOND);
acc2.packet[1].v = vec_perm(taccReal.packet[1], taccImag.packet[1], p16uc_SETCOMPLEX32_SECOND);
acc2.packet[2].v = vec_perm(taccReal.packet[2], taccImag.packet[2], p16uc_SETCOMPLEX32_SECOND);
acc2.packet[3].v = vec_perm(taccReal.packet[3], taccImag.packet[3], p16uc_SETCOMPLEX32_SECOND);
}
template<typename Packet, typename Packetc>
EIGEN_ALWAYS_INLINE void bcouple(PacketBlock<Packet,4>& taccReal, PacketBlock<Packet,4>& taccImag, PacketBlock<Packetc,8>& tRes, PacketBlock<Packetc, 4>& acc1, PacketBlock<Packetc, 4>& acc2)
{
bcouple_common<Packet, Packetc>(taccReal, taccImag, acc1, acc2);
acc1.packet[0] = padd<Packetc>(tRes.packet[0], acc1.packet[0]);
acc1.packet[1] = padd<Packetc>(tRes.packet[1], acc1.packet[1]);
acc1.packet[2] = padd<Packetc>(tRes.packet[2], acc1.packet[2]);
acc1.packet[3] = padd<Packetc>(tRes.packet[3], acc1.packet[3]);
acc2.packet[0] = padd<Packetc>(tRes.packet[4], acc2.packet[0]);
acc2.packet[1] = padd<Packetc>(tRes.packet[5], acc2.packet[1]);
acc2.packet[2] = padd<Packetc>(tRes.packet[6], acc2.packet[2]);
acc2.packet[3] = padd<Packetc>(tRes.packet[7], acc2.packet[3]);
}
template<typename Packet, typename Packetc>
EIGEN_ALWAYS_INLINE void bcouple_common(PacketBlock<Packet,1>& taccReal, PacketBlock<Packet,1>& taccImag, PacketBlock<Packetc, 1>& acc1, PacketBlock<Packetc, 1>& acc2)
{
acc1.packet[0].v = vec_perm(taccReal.packet[0], taccImag.packet[0], p16uc_SETCOMPLEX32_FIRST);
acc2.packet[0].v = vec_perm(taccReal.packet[0], taccImag.packet[0], p16uc_SETCOMPLEX32_SECOND);
}
template<typename Packet, typename Packetc>
EIGEN_ALWAYS_INLINE void bcouple(PacketBlock<Packet,1>& taccReal, PacketBlock<Packet,1>& taccImag, PacketBlock<Packetc,2>& tRes, PacketBlock<Packetc, 1>& acc1, PacketBlock<Packetc, 1>& acc2)
{
bcouple_common<Packet, Packetc>(taccReal, taccImag, acc1, acc2);
acc1.packet[0] = padd<Packetc>(tRes.packet[0], acc1.packet[0]);
acc2.packet[0] = padd<Packetc>(tRes.packet[1], acc2.packet[0]);
}
template<>
EIGEN_ALWAYS_INLINE void bcouple_common<Packet2d, Packet1cd>(PacketBlock<Packet2d,4>& taccReal, PacketBlock<Packet2d,4>& taccImag, PacketBlock<Packet1cd, 4>& acc1, PacketBlock<Packet1cd, 4>& acc2)
{
acc1.packet[0].v = vec_perm(taccReal.packet[0], taccImag.packet[0], p16uc_SETCOMPLEX64_FIRST);
acc1.packet[1].v = vec_perm(taccReal.packet[1], taccImag.packet[1], p16uc_SETCOMPLEX64_FIRST);
acc1.packet[2].v = vec_perm(taccReal.packet[2], taccImag.packet[2], p16uc_SETCOMPLEX64_FIRST);
acc1.packet[3].v = vec_perm(taccReal.packet[3], taccImag.packet[3], p16uc_SETCOMPLEX64_FIRST);
acc2.packet[0].v = vec_perm(taccReal.packet[0], taccImag.packet[0], p16uc_SETCOMPLEX64_SECOND);
acc2.packet[1].v = vec_perm(taccReal.packet[1], taccImag.packet[1], p16uc_SETCOMPLEX64_SECOND);
acc2.packet[2].v = vec_perm(taccReal.packet[2], taccImag.packet[2], p16uc_SETCOMPLEX64_SECOND);
acc2.packet[3].v = vec_perm(taccReal.packet[3], taccImag.packet[3], p16uc_SETCOMPLEX64_SECOND);
}
template<>
EIGEN_ALWAYS_INLINE void bcouple_common<Packet2d, Packet1cd>(PacketBlock<Packet2d,1>& taccReal, PacketBlock<Packet2d,1>& taccImag, PacketBlock<Packet1cd, 1>& acc1, PacketBlock<Packet1cd, 1>& acc2)
{
acc1.packet[0].v = vec_perm(taccReal.packet[0], taccImag.packet[0], p16uc_SETCOMPLEX64_FIRST);
acc2.packet[0].v = vec_perm(taccReal.packet[0], taccImag.packet[0], p16uc_SETCOMPLEX64_SECOND);
}
// This is necessary because ploadRhs for double returns a pair of vectors when MMA is enabled.
template<typename Scalar, typename Packet>
EIGEN_ALWAYS_INLINE Packet ploadRhs(const Scalar* rhs)
{
return ploadu<Packet>(rhs);
}
} // end namespace internal
} // end namespace Eigen
|
c39a70bdbfd1e98073a227c57c05a30fa38813b9 | dfb0952ea11066b76aa8e808f9e2a15be426ecf8 | /prj/gml/Algorithms/KMeans/dllmain.cpp | 20291fd31ddeaf57f144b3bc98b7700e4aaa7ab5 | [] | no_license | berendeanicolae/gml | 10070aefc778245304401bf58cd68b1e7b9b17b1 | 556cf8008d12e58077c346c72d70932ca58b316c | refs/heads/master | 2021-01-10T14:07:05.168676 | 2017-08-09T10:40:08 | 2017-08-09T10:40:08 | 36,880,125 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 72 | cpp | dllmain.cpp | #include "KMeans.h"
LIB_INTERFACE(KMeans,"GDT",1,"KMeans algorithm"); |
78300c7c3f297272a70baf66fd65bff1cc8dee5d | ac445eca22bffadae4bb46f926cfabd97e540319 | /examples/HK/HonFlx11UpMu.cc | 918ff75482354a7353c5938c75a9356a874659f5 | [] | no_license | hyperk/NGen | d7bf63d856441cff187dbee470ad93c3b938c793 | 5dc15ba196b03884da0bcb4ee8b3ca0ae3faf578 | refs/heads/master | 2020-03-30T16:43:09.530285 | 2015-04-24T07:14:47 | 2015-04-24T07:14:47 | 30,894,834 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cc | HonFlx11UpMu.cc | #include "HonFlx11UpMu.h"
double HonFlx11UpMu::GetFlux(float E,NEUTRINO::FLAVOR nuFlav, Time_Struct t)
{
if(nuFlav!=NEUTRINO::MU and nuFlav!=NEUTRINO::MU_BAR)
{
return 0;
}
return HonFlx11::GetFlux(E,nuFlav,t);
}
double HonFlx11UpMu::GetFlux(float phi,float cosZ, float E,NEUTRINO::FLAVOR nuFlav,Time_Struct t)
{
if(nuFlav!=NEUTRINO::MU and nuFlav!=NEUTRINO::MU_BAR)
{
return 0;
}
return HonFlx11::GetFlux(phi,cosZ,E,NEUTRINO::MU_BAR,t);
}
|
5ab3d84769de524abd695470dd2fe719dc144571 | 0ac7388d092db127a5f34952a985ee3cfb3ca028 | /deps/libgdal/gdal/ogr/ogrsf_frmts/flatgeobuf/ogrflatgeobuflayer.cpp | 654f1d5616215a4ea766bf8bec17335a5db0ca10 | [
"LicenseRef-scancode-warranty-disclaimer",
"SunPro",
"LicenseRef-scancode-info-zip-2005-02",
"BSD-3-Clause",
"MIT",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | mmomtchev/node-gdal-async | 49161ab6864341b1f0dd8b656c74290c63061c77 | 5c75d3d98989c4c246e54bb7ccff3a00d5cc3417 | refs/heads/main | 2023-08-07T11:44:44.011002 | 2023-07-30T17:41:18 | 2023-07-30T17:41:18 | 300,949,372 | 96 | 18 | Apache-2.0 | 2023-09-13T17:43:40 | 2020-10-03T18:28:43 | C++ | UTF-8 | C++ | false | false | 90,349 | cpp | ogrflatgeobuflayer.cpp | /******************************************************************************
*
* Project: FlatGeobuf driver
* Purpose: Implements OGRFlatGeobufLayer class.
* Author: Björn Harrtell <bjorn at wololo dot org>
*
******************************************************************************
* Copyright (c) 2018-2020, Björn Harrtell <bjorn at wololo dot org>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "ogrsf_frmts.h"
#include "cpl_vsi_virtual.h"
#include "cpl_conv.h"
#include "cpl_json.h"
#include "cpl_http.h"
#include "cpl_time.h"
#include "ogr_p.h"
#include "ograrrowarrayhelper.h"
#include "ogr_recordbatch.h"
#include "ogr_flatgeobuf.h"
#include "cplerrors.h"
#include "geometryreader.h"
#include "geometrywriter.h"
#include <algorithm>
#include <limits>
#include <new>
#include <stdexcept>
using namespace flatbuffers;
using namespace FlatGeobuf;
using namespace ogr_flatgeobuf;
static OGRErr CPLErrorMemoryAllocation(const char *message)
{
CPLError(CE_Failure, CPLE_AppDefined, "Could not allocate memory: %s",
message);
return OGRERR_NOT_ENOUGH_MEMORY;
}
static OGRErr CPLErrorIO(const char *message)
{
CPLError(CE_Failure, CPLE_AppDefined, "Unexpected I/O failure: %s",
message);
return OGRERR_FAILURE;
}
OGRFlatGeobufLayer::OGRFlatGeobufLayer(const Header *poHeader, GByte *headerBuf,
const char *pszFilename, VSILFILE *poFp,
uint64_t offset)
{
m_poHeader = poHeader;
CPLAssert(poHeader);
m_headerBuf = headerBuf;
CPLAssert(pszFilename);
if (pszFilename)
m_osFilename = pszFilename;
m_poFp = poFp;
m_offsetFeatures = offset;
m_offset = offset;
m_create = false;
m_featuresCount = m_poHeader->features_count();
m_geometryType = m_poHeader->geometry_type();
m_indexNodeSize = m_poHeader->index_node_size();
m_hasZ = m_poHeader->has_z();
m_hasM = m_poHeader->has_m();
m_hasT = m_poHeader->has_t();
const auto envelope = m_poHeader->envelope();
if (envelope && envelope->size() == 4)
{
m_sExtent.MinX = (*envelope)[0];
m_sExtent.MinY = (*envelope)[1];
m_sExtent.MaxX = (*envelope)[2];
m_sExtent.MaxY = (*envelope)[3];
}
CPLDebugOnly("FlatGeobuf", "geometryType: %d, hasZ: %d, hasM: %d, hasT: %d",
(int)m_geometryType, m_hasZ, m_hasM, m_hasT);
const auto crs = m_poHeader->crs();
if (crs != nullptr)
{
m_poSRS = new OGRSpatialReference();
m_poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
const auto org = crs->org();
const auto code = crs->code();
const auto crs_wkt = crs->wkt();
CPLString wkt = crs_wkt ? crs_wkt->c_str() : "";
double dfCoordEpoch = 0;
if (STARTS_WITH_CI(wkt.c_str(), "COORDINATEMETADATA["))
{
size_t nPos = std::string::npos;
// We don't want to match FRAMEEPOCH[
for (const char *pszEpoch :
{",EPOCH[", " EPOCH[", "\tEPOCH[", "\nEPOCH[", "\rEPOCH["})
{
nPos = wkt.ifind(pszEpoch);
if (nPos != std::string::npos)
break;
}
if (nPos != std::string::npos)
{
dfCoordEpoch = CPLAtof(wkt.c_str() + nPos + strlen(",EPOCH["));
wkt.resize(nPos);
wkt = wkt.substr(strlen("COORDINATEMETADATA["));
}
}
if ((org == nullptr || EQUAL(org->c_str(), "EPSG")) && code != 0)
{
m_poSRS->importFromEPSG(code);
}
else if (org && code != 0)
{
CPLString osCode;
osCode.Printf("%s:%d", org->c_str(), code);
if (m_poSRS->SetFromUserInput(
osCode.c_str(),
OGRSpatialReference::
SET_FROM_USER_INPUT_LIMITATIONS_get()) != OGRERR_NONE &&
!wkt.empty())
{
m_poSRS->importFromWkt(wkt.c_str());
}
}
else if (!wkt.empty())
{
m_poSRS->importFromWkt(wkt.c_str());
}
if (dfCoordEpoch > 0)
m_poSRS->SetCoordinateEpoch(dfCoordEpoch);
}
m_eGType = getOGRwkbGeometryType();
const char *pszName =
m_poHeader->name() ? m_poHeader->name()->c_str() : "unknown";
m_poFeatureDefn = new OGRFeatureDefn(pszName);
SetDescription(m_poFeatureDefn->GetName());
m_poFeatureDefn->SetGeomType(wkbNone);
auto poGeomFieldDefn =
cpl::make_unique<OGRGeomFieldDefn>(nullptr, m_eGType);
if (m_poSRS != nullptr)
poGeomFieldDefn->SetSpatialRef(m_poSRS);
m_poFeatureDefn->AddGeomFieldDefn(std::move(poGeomFieldDefn));
readColumns();
m_poFeatureDefn->Reference();
}
OGRFlatGeobufLayer::OGRFlatGeobufLayer(const char *pszLayerName,
const char *pszFilename,
OGRSpatialReference *poSpatialRef,
OGRwkbGeometryType eGType,
bool bCreateSpatialIndexAtClose,
VSILFILE *poFpWrite,
std::string &osTempFile)
: m_eGType(eGType),
m_bCreateSpatialIndexAtClose(bCreateSpatialIndexAtClose),
m_poFpWrite(poFpWrite), m_osTempFile(osTempFile)
{
m_create = true;
if (pszLayerName)
m_osLayerName = pszLayerName;
if (pszFilename)
m_osFilename = pszFilename;
m_geometryType = GeometryWriter::translateOGRwkbGeometryType(eGType);
if wkbHasZ (eGType)
m_hasZ = true;
if wkbHasM (eGType)
m_hasM = true;
if (poSpatialRef)
m_poSRS = poSpatialRef->Clone();
CPLDebugOnly("FlatGeobuf", "geometryType: %d, hasZ: %d, hasM: %d, hasT: %d",
(int)m_geometryType, m_hasZ, m_hasM, m_hasT);
SetMetadataItem(OLMD_FID64, "YES");
m_poFeatureDefn = new OGRFeatureDefn(pszLayerName);
SetDescription(m_poFeatureDefn->GetName());
m_poFeatureDefn->SetGeomType(eGType);
m_poFeatureDefn->Reference();
}
OGRwkbGeometryType OGRFlatGeobufLayer::getOGRwkbGeometryType()
{
OGRwkbGeometryType ogrType = OGRwkbGeometryType::wkbUnknown;
if (static_cast<int>(m_geometryType) <= 17)
ogrType = (OGRwkbGeometryType)m_geometryType;
if (m_hasZ)
ogrType = wkbSetZ(ogrType);
if (m_hasM)
ogrType = wkbSetM(ogrType);
return ogrType;
}
static ColumnType toColumnType(OGRFieldType type, OGRFieldSubType subType)
{
switch (type)
{
case OGRFieldType::OFTInteger:
return subType == OFSTBoolean ? ColumnType::Bool
: subType == OFSTInt16 ? ColumnType::Short
: ColumnType::Int;
case OGRFieldType::OFTInteger64:
return ColumnType::Long;
case OGRFieldType::OFTReal:
return subType == OFSTFloat32 ? ColumnType::Float
: ColumnType::Double;
case OGRFieldType::OFTString:
return ColumnType::String;
case OGRFieldType::OFTDate:
return ColumnType::DateTime;
case OGRFieldType::OFTTime:
return ColumnType::DateTime;
case OGRFieldType::OFTDateTime:
return ColumnType::DateTime;
case OGRFieldType::OFTBinary:
return ColumnType::Binary;
default:
CPLError(CE_Failure, CPLE_AppDefined,
"toColumnType: Unknown OGRFieldType %d", type);
}
return ColumnType::String;
}
static OGRFieldType toOGRFieldType(ColumnType type, OGRFieldSubType &eSubType)
{
eSubType = OFSTNone;
switch (type)
{
case ColumnType::Byte:
return OGRFieldType::OFTInteger;
case ColumnType::UByte:
return OGRFieldType::OFTInteger;
case ColumnType::Bool:
eSubType = OFSTBoolean;
return OGRFieldType::OFTInteger;
case ColumnType::Short:
eSubType = OFSTInt16;
return OGRFieldType::OFTInteger;
case ColumnType::UShort:
return OGRFieldType::OFTInteger;
case ColumnType::Int:
return OGRFieldType::OFTInteger;
case ColumnType::UInt:
return OGRFieldType::OFTInteger64;
case ColumnType::Long:
return OGRFieldType::OFTInteger64;
case ColumnType::ULong:
return OGRFieldType::OFTReal;
case ColumnType::Float:
eSubType = OFSTFloat32;
return OGRFieldType::OFTReal;
case ColumnType::Double:
return OGRFieldType::OFTReal;
case ColumnType::String:
return OGRFieldType::OFTString;
case ColumnType::Json:
return OGRFieldType::OFTString;
case ColumnType::DateTime:
return OGRFieldType::OFTDateTime;
case ColumnType::Binary:
return OGRFieldType::OFTBinary;
}
return OGRFieldType::OFTString;
}
const std::vector<Offset<Column>>
OGRFlatGeobufLayer::writeColumns(FlatBufferBuilder &fbb)
{
std::vector<Offset<Column>> columns;
for (int i = 0; i < m_poFeatureDefn->GetFieldCount(); i++)
{
const auto field = m_poFeatureDefn->GetFieldDefn(i);
const auto name = field->GetNameRef();
const auto columnType =
toColumnType(field->GetType(), field->GetSubType());
auto title = field->GetAlternativeNameRef();
if (EQUAL(title, ""))
title = nullptr;
const std::string &osComment = field->GetComment();
const char *description =
!osComment.empty() ? osComment.c_str() : nullptr;
auto width = -1;
auto precision = -1;
auto scale = field->GetPrecision();
if (scale == 0)
scale = -1;
if (columnType == ColumnType::Float || columnType == ColumnType::Double)
precision = field->GetWidth();
else
width = field->GetWidth();
auto nullable = CPL_TO_BOOL(field->IsNullable());
auto unique = CPL_TO_BOOL(field->IsUnique());
auto primaryKey = false;
// CPLDebugOnly("FlatGeobuf", "Create column %s (index %d)", name, i);
const auto column =
CreateColumnDirect(fbb, name, columnType, title, description, width,
precision, scale, nullable, unique, primaryKey);
columns.push_back(column);
// CPLDebugOnly("FlatGeobuf", "DEBUG writeColumns: Created column %s
// added as index %d", name, i);
}
CPLDebugOnly("FlatGeobuf", "Created %lu columns for writing",
static_cast<long unsigned int>(columns.size()));
return columns;
}
void OGRFlatGeobufLayer::readColumns()
{
const auto columns = m_poHeader->columns();
if (columns == nullptr)
return;
for (uint32_t i = 0; i < columns->size(); i++)
{
const auto column = columns->Get(i);
const auto type = column->type();
const auto name = column->name()->c_str();
const auto title =
column->title() != nullptr ? column->title()->c_str() : nullptr;
const auto width = column->width();
const auto precision = column->precision();
const auto scale = column->scale();
const auto nullable = column->nullable();
const auto unique = column->unique();
OGRFieldSubType eSubType = OFSTNone;
const auto ogrType = toOGRFieldType(column->type(), eSubType);
OGRFieldDefn field(name, ogrType);
field.SetSubType(eSubType);
field.SetAlternativeName(title);
if (column->description())
field.SetComment(column->description()->str());
if (width != -1 && type != ColumnType::Float &&
type != ColumnType::Double)
field.SetWidth(width);
if (precision != -1)
field.SetWidth(precision);
field.SetPrecision(scale != -1 ? scale : 0);
field.SetNullable(nullable);
field.SetUnique(unique);
m_poFeatureDefn->AddFieldDefn(&field);
// CPLDebugOnly("FlatGeobuf", "DEBUG readColumns: Read column %s added
// as index %d", name, i);
}
CPLDebugOnly("FlatGeobuf",
"Read %lu columns and added to feature definition",
static_cast<long unsigned int>(columns->size()));
}
void OGRFlatGeobufLayer::writeHeader(VSILFILE *poFp, uint64_t featuresCount,
std::vector<double> *extentVector)
{
size_t c;
c = VSIFWriteL(&magicbytes, sizeof(magicbytes), 1, poFp);
CPLDebugOnly("FlatGeobuf", "Wrote magicbytes (%lu bytes)",
static_cast<long unsigned int>(c * sizeof(magicbytes)));
m_writeOffset += sizeof(magicbytes);
FlatBufferBuilder fbb;
fbb.TrackMinAlign(8);
auto columns = writeColumns(fbb);
flatbuffers::Offset<Crs> crs = 0;
if (m_poSRS)
{
int nAuthorityCode = 0;
const char *pszAuthorityName = m_poSRS->GetAuthorityName(nullptr);
if (pszAuthorityName == nullptr || strlen(pszAuthorityName) == 0)
{
// Try to force identify an EPSG code.
m_poSRS->AutoIdentifyEPSG();
pszAuthorityName = m_poSRS->GetAuthorityName(nullptr);
if (pszAuthorityName != nullptr && EQUAL(pszAuthorityName, "EPSG"))
{
const char *pszAuthorityCode =
m_poSRS->GetAuthorityCode(nullptr);
if (pszAuthorityCode != nullptr && strlen(pszAuthorityCode) > 0)
{
/* Import 'clean' SRS */
m_poSRS->importFromEPSG(atoi(pszAuthorityCode));
pszAuthorityName = m_poSRS->GetAuthorityName(nullptr);
}
}
}
if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0)
{
// For the root authority name 'EPSG', the authority code
// should always be integral
nAuthorityCode = atoi(m_poSRS->GetAuthorityCode(nullptr));
}
// Translate SRS to WKT.
char *pszWKT = nullptr;
const char *const apszOptionsWkt[] = {"FORMAT=WKT2_2019", nullptr};
m_poSRS->exportToWkt(&pszWKT, apszOptionsWkt);
if (pszWKT && pszWKT[0] == '\0')
{
CPLFree(pszWKT);
pszWKT = nullptr;
}
if (pszWKT && m_poSRS->GetCoordinateEpoch() > 0)
{
std::string osCoordinateEpoch =
CPLSPrintf("%f", m_poSRS->GetCoordinateEpoch());
if (osCoordinateEpoch.find('.') != std::string::npos)
{
while (osCoordinateEpoch.back() == '0')
osCoordinateEpoch.resize(osCoordinateEpoch.size() - 1);
}
std::string osWKT("COORDINATEMETADATA[");
osWKT += pszWKT;
osWKT += ",EPOCH[";
osWKT += osCoordinateEpoch;
osWKT += "]]";
CPLFree(pszWKT);
pszWKT = CPLStrdup(osWKT.c_str());
}
if (pszWKT && !CPLIsUTF8(pszWKT, -1))
{
char *pszWKTtmp = CPLForceToASCII(pszWKT, -1, '?');
CPLFree(pszWKT);
pszWKT = pszWKTtmp;
}
crs = CreateCrsDirect(fbb, pszAuthorityName, nAuthorityCode,
m_poSRS->GetName(), nullptr, pszWKT);
CPLFree(pszWKT);
}
const auto header = CreateHeaderDirect(
fbb, m_osLayerName.c_str(), extentVector, m_geometryType, m_hasZ,
m_hasM, m_hasT, m_hasTM, &columns, featuresCount, m_indexNodeSize, crs);
fbb.FinishSizePrefixed(header);
c = VSIFWriteL(fbb.GetBufferPointer(), 1, fbb.GetSize(), poFp);
CPLDebugOnly("FlatGeobuf", "Wrote header (%lu bytes)",
static_cast<long unsigned int>(c));
m_writeOffset += c;
}
static bool SupportsSeekWhileWriting(const std::string &osFilename)
{
return (!STARTS_WITH(osFilename.c_str(), "/vsi")) ||
STARTS_WITH(osFilename.c_str(), "/vsimem/");
}
bool OGRFlatGeobufLayer::CreateFinalFile()
{
// no spatial index requested, we are (almost) done
if (!m_bCreateSpatialIndexAtClose)
{
if (m_poFpWrite == nullptr || m_featuresCount == 0 ||
!SupportsSeekWhileWriting(m_osFilename))
{
return true;
}
// Rewrite header
VSIFSeekL(m_poFpWrite, 0, SEEK_SET);
m_writeOffset = 0;
std::vector<double> extentVector;
extentVector.push_back(m_sExtent.MinX);
extentVector.push_back(m_sExtent.MinY);
extentVector.push_back(m_sExtent.MaxX);
extentVector.push_back(m_sExtent.MaxY);
writeHeader(m_poFpWrite, m_featuresCount, &extentVector);
// Sanity check to verify that the dummy header and the real header
// have the same size.
CPLAssert(m_writeOffset == m_offsetAfterHeader);
CPL_IGNORE_RET_VAL(m_writeOffset); // otherwise checkers might tell the
// member is not used
return true;
}
m_poFp = VSIFOpenL(m_osFilename.c_str(), "wb");
if (m_poFp == nullptr)
{
CPLError(CE_Failure, CPLE_OpenFailed, "Failed to create %s:\n%s",
m_osFilename.c_str(), VSIStrerror(errno));
return false;
}
// check if something has been written, if not write empty layer and bail
if (m_writeOffset == 0 || m_featuresCount == 0)
{
CPLDebugOnly("FlatGeobuf", "Writing empty layer");
writeHeader(m_poFp, 0, nullptr);
return true;
}
CPLDebugOnly("FlatGeobuf", "Writing second pass sorted by spatial index");
const uint64_t nTempFileSize = m_writeOffset;
m_writeOffset = 0;
m_indexNodeSize = 16;
size_t c;
if (m_featuresCount >= std::numeric_limits<size_t>::max() / 8)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Too many features for this architecture");
return false;
}
NodeItem extent = calcExtent(m_featureItems);
auto extentVector = extent.toVector();
writeHeader(m_poFp, m_featuresCount, &extentVector);
CPLDebugOnly("FlatGeobuf", "Sorting items for Packed R-tree");
hilbertSort(m_featureItems);
CPLDebugOnly("FlatGeobuf", "Calc new feature offsets");
uint64_t featureOffset = 0;
for (auto &item : m_featureItems)
{
item.nodeItem.offset = featureOffset;
featureOffset += item.size;
}
CPLDebugOnly("FlatGeobuf", "Creating Packed R-tree");
c = 0;
try
{
const auto fillNodeItems = [this](NodeItem *dest)
{
size_t i = 0;
for (const auto &featureItem : m_featureItems)
{
dest[i] = featureItem.nodeItem;
++i;
}
};
PackedRTree tree(fillNodeItems, m_featureItems.size(), extent);
CPLDebugOnly("FlatGeobuf", "PackedRTree extent %f, %f, %f, %f",
extentVector[0], extentVector[1], extentVector[2],
extentVector[3]);
tree.streamWrite([this, &c](uint8_t *data, size_t size)
{ c += VSIFWriteL(data, 1, size, m_poFp); });
}
catch (const std::exception &e)
{
CPLError(CE_Failure, CPLE_AppDefined, "Create: %s", e.what());
return false;
}
CPLDebugOnly("FlatGeobuf", "Wrote tree (%lu bytes)",
static_cast<long unsigned int>(c));
m_writeOffset += c;
CPLDebugOnly("FlatGeobuf", "Writing feature buffers at offset %lu",
static_cast<long unsigned int>(m_writeOffset));
c = 0;
// For temporary files not in memory, we use a batch strategy to write the
// final file. That is to say we try to separate reads in the source
// temporary file and writes in the target file as much as possible, and by
// reading source features in increasing offset within a batch.
const bool bUseBatchStrategy =
!STARTS_WITH(m_osTempFile.c_str(), "/vsimem/");
if (bUseBatchStrategy)
{
const uint32_t nMaxBufferSize = std::max(
m_maxFeatureSize,
static_cast<uint32_t>(std::min(
static_cast<uint64_t>(100 * 1024 * 1024), nTempFileSize)));
if (ensureFeatureBuf(nMaxBufferSize) != OGRERR_NONE)
return false;
uint32_t offsetInBuffer = 0;
struct BatchItem
{
size_t featureIdx; // index of m_featureItems[]
uint32_t offsetInBuffer;
};
std::vector<BatchItem> batch;
const auto flushBatch = [this, &batch, &offsetInBuffer]()
{
// Sort by increasing source offset
std::sort(batch.begin(), batch.end(),
[this](const BatchItem &a, const BatchItem &b)
{
return m_featureItems[a.featureIdx].offset <
m_featureItems[b.featureIdx].offset;
});
// Read source features
for (const auto &batchItem : batch)
{
const auto &item = m_featureItems[batchItem.featureIdx];
if (VSIFSeekL(m_poFpWrite, item.offset, SEEK_SET) == -1)
{
CPLErrorIO("seeking to temp feature location");
return false;
}
if (VSIFReadL(m_featureBuf + batchItem.offsetInBuffer, 1,
item.size, m_poFpWrite) != item.size)
{
CPLErrorIO("reading temp feature");
return false;
}
}
// Write target features
if (offsetInBuffer > 0 &&
VSIFWriteL(m_featureBuf, 1, offsetInBuffer, m_poFp) !=
offsetInBuffer)
{
CPLErrorIO("writing feature");
return false;
}
batch.clear();
offsetInBuffer = 0;
return true;
};
for (size_t i = 0; i < m_featuresCount; i++)
{
const auto &featureItem = m_featureItems[i];
const auto featureSize = featureItem.size;
if (offsetInBuffer + featureSize > m_featureBufSize)
{
if (!flushBatch())
{
return false;
}
}
BatchItem bachItem;
bachItem.offsetInBuffer = offsetInBuffer;
bachItem.featureIdx = i;
batch.emplace_back(bachItem);
offsetInBuffer += featureSize;
c += featureSize;
}
if (!flushBatch())
{
return false;
}
}
else
{
const auto err = ensureFeatureBuf(m_maxFeatureSize);
if (err != OGRERR_NONE)
return false;
for (const auto &featureItem : m_featureItems)
{
const auto featureSize = featureItem.size;
// CPLDebugOnly("FlatGeobuf", "featureItem.offset: %lu",
// static_cast<long unsigned int>(featureItem.offset));
// CPLDebugOnly("FlatGeobuf", "featureSize: %d", featureSize);
if (VSIFSeekL(m_poFpWrite, featureItem.offset, SEEK_SET) == -1)
{
CPLErrorIO("seeking to temp feature location");
return false;
}
if (VSIFReadL(m_featureBuf, 1, featureSize, m_poFpWrite) !=
featureSize)
{
CPLErrorIO("reading temp feature");
return false;
}
if (VSIFWriteL(m_featureBuf, 1, featureSize, m_poFp) != featureSize)
{
CPLErrorIO("writing feature");
return false;
}
c += featureSize;
}
}
CPLDebugOnly("FlatGeobuf", "Wrote feature buffers (%lu bytes)",
static_cast<long unsigned int>(c));
m_writeOffset += c;
CPLDebugOnly("FlatGeobuf", "Now at offset %lu",
static_cast<long unsigned int>(m_writeOffset));
return true;
}
OGRFlatGeobufLayer::~OGRFlatGeobufLayer()
{
OGRFlatGeobufLayer::Close();
if (m_poFeatureDefn)
m_poFeatureDefn->Release();
if (m_poSRS)
m_poSRS->Release();
if (m_featureBuf)
VSIFree(m_featureBuf);
if (m_headerBuf)
VSIFree(m_headerBuf);
}
CPLErr OGRFlatGeobufLayer::Close()
{
CPLErr eErr = CE_None;
if (m_create)
{
if (!CreateFinalFile())
eErr = CE_Failure;
m_create = false;
}
if (m_poFp)
{
if (VSIFCloseL(m_poFp) != 0)
eErr = CE_Failure;
m_poFp = nullptr;
}
if (m_poFpWrite)
{
if (VSIFCloseL(m_poFpWrite) != 0)
eErr = CE_Failure;
m_poFpWrite = nullptr;
}
if (!m_osTempFile.empty())
{
VSIUnlink(m_osTempFile.c_str());
m_osTempFile.clear();
}
return eErr;
}
OGRErr OGRFlatGeobufLayer::readFeatureOffset(uint64_t index,
uint64_t &featureOffset)
{
try
{
const auto treeSize =
PackedRTree::size(m_featuresCount, m_indexNodeSize);
const auto levelBounds =
PackedRTree::generateLevelBounds(m_featuresCount, m_indexNodeSize);
const auto bottomLevelOffset =
m_offset - treeSize +
(levelBounds.front().first * sizeof(NodeItem));
const auto nodeItemOffset =
bottomLevelOffset + (index * sizeof(NodeItem));
const auto featureOffsetOffset = nodeItemOffset + (sizeof(double) * 4);
if (VSIFSeekL(m_poFp, featureOffsetOffset, SEEK_SET) == -1)
return CPLErrorIO("seeking feature offset");
if (VSIFReadL(&featureOffset, sizeof(uint64_t), 1, m_poFp) != 1)
return CPLErrorIO("reading feature offset");
#if !CPL_IS_LSB
CPL_LSBPTR64(&featureOffset);
#endif
return OGRERR_NONE;
}
catch (const std::exception &e)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to calculate tree size: %s", e.what());
return OGRERR_FAILURE;
}
}
OGRFeature *OGRFlatGeobufLayer::GetFeature(GIntBig nFeatureId)
{
if (m_indexNodeSize == 0)
{
return OGRLayer::GetFeature(nFeatureId);
}
else
{
if (static_cast<uint64_t>(nFeatureId) >= m_featuresCount)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Requested feature id is out of bounds");
return nullptr;
}
ResetReading();
m_ignoreSpatialFilter = true;
m_ignoreAttributeFilter = true;
uint64_t featureOffset;
const auto err = readFeatureOffset(nFeatureId, featureOffset);
if (err != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Unexpected error reading feature offset from id");
return nullptr;
}
m_offset = m_offsetFeatures + featureOffset;
OGRFeature *poFeature = GetNextFeature();
if (poFeature != nullptr)
poFeature->SetFID(nFeatureId);
ResetReading();
return poFeature;
}
}
OGRErr OGRFlatGeobufLayer::readIndex()
{
if (m_queriedSpatialIndex || !m_poFilterGeom)
return OGRERR_NONE;
if (m_sFilterEnvelope.IsInit() && m_sExtent.IsInit() &&
m_sFilterEnvelope.MinX <= m_sExtent.MinX &&
m_sFilterEnvelope.MinY <= m_sExtent.MinY &&
m_sFilterEnvelope.MaxX >= m_sExtent.MaxX &&
m_sFilterEnvelope.MaxY >= m_sExtent.MaxY)
return OGRERR_NONE;
const auto indexNodeSize = m_poHeader->index_node_size();
if (indexNodeSize == 0)
return OGRERR_NONE;
const auto featuresCount = m_poHeader->features_count();
if (featuresCount == 0)
return OGRERR_NONE;
if (VSIFSeekL(m_poFp, sizeof(magicbytes), SEEK_SET) ==
-1) // skip magic bytes
return CPLErrorIO("seeking past magic bytes");
uoffset_t headerSize;
if (VSIFReadL(&headerSize, sizeof(uoffset_t), 1, m_poFp) != 1)
return CPLErrorIO("reading header size");
CPL_LSBPTR32(&headerSize);
try
{
const auto treeSize =
indexNodeSize > 0 ? PackedRTree::size(featuresCount) : 0;
if (treeSize > 0 && m_poFilterGeom && !m_ignoreSpatialFilter)
{
CPLDebugOnly("FlatGeobuf", "Attempting spatial index query");
OGREnvelope env;
m_poFilterGeom->getEnvelope(&env);
NodeItem n{env.MinX, env.MinY, env.MaxX, env.MaxY, 0};
CPLDebugOnly("FlatGeobuf", "Spatial index search on %f,%f,%f,%f",
env.MinX, env.MinY, env.MaxX, env.MaxY);
const auto treeOffset =
sizeof(magicbytes) + sizeof(uoffset_t) + headerSize;
const auto readNode =
[this, treeOffset](uint8_t *buf, size_t i, size_t s)
{
if (VSIFSeekL(m_poFp, treeOffset + i, SEEK_SET) == -1)
throw std::runtime_error("I/O seek failure");
if (VSIFReadL(buf, 1, s, m_poFp) != s)
throw std::runtime_error("I/O read file");
};
m_foundItems = PackedRTree::streamSearch(
featuresCount, indexNodeSize, n, readNode);
m_featuresCount = m_foundItems.size();
CPLDebugOnly("FlatGeobuf",
"%lu features found in spatial index search",
static_cast<long unsigned int>(m_featuresCount));
m_queriedSpatialIndex = true;
}
}
catch (const std::exception &e)
{
CPLError(CE_Failure, CPLE_AppDefined,
"readIndex: Unexpected failure: %s", e.what());
return OGRERR_FAILURE;
}
return OGRERR_NONE;
}
GIntBig OGRFlatGeobufLayer::GetFeatureCount(int bForce)
{
if (m_poFilterGeom != nullptr || m_poAttrQuery != nullptr ||
m_featuresCount == 0)
return OGRLayer::GetFeatureCount(bForce);
else
return m_featuresCount;
}
/************************************************************************/
/* ParseDateTime() */
/************************************************************************/
static inline bool ParseDateTime(const char *pszInput, size_t nLen,
OGRField *psField)
{
return OGRParseDateTimeYYYYMMDDTHHMMSSZ(pszInput, nLen, psField) ||
OGRParseDateTimeYYYYMMDDTHHMMSSsssZ(pszInput, nLen, psField);
}
OGRFeature *OGRFlatGeobufLayer::GetNextFeature()
{
if (m_create)
return nullptr;
while (true)
{
if (m_featuresCount > 0 && m_featuresPos >= m_featuresCount)
{
CPLDebugOnly("FlatGeobuf", "GetNextFeature: iteration end at %lu",
static_cast<long unsigned int>(m_featuresPos));
return nullptr;
}
if (readIndex() != OGRERR_NONE)
{
return nullptr;
}
if (m_queriedSpatialIndex && m_featuresCount == 0)
{
CPLDebugOnly("FlatGeobuf", "GetNextFeature: no features found");
return nullptr;
}
auto poFeature = cpl::make_unique<OGRFeature>(m_poFeatureDefn);
if (parseFeature(poFeature.get()) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Fatal error parsing feature");
return nullptr;
}
if (VSIFEofL(m_poFp))
{
CPLDebug("FlatGeobuf", "GetNextFeature: iteration end due to EOF");
return nullptr;
}
m_featuresPos++;
if ((m_poFilterGeom == nullptr || m_ignoreSpatialFilter ||
FilterGeometry(poFeature->GetGeometryRef())) &&
(m_poAttrQuery == nullptr || m_ignoreAttributeFilter ||
m_poAttrQuery->Evaluate(poFeature.get())))
return poFeature.release();
}
}
OGRErr OGRFlatGeobufLayer::ensureFeatureBuf(uint32_t featureSize)
{
if (m_featureBufSize == 0)
{
const auto newBufSize = std::max(1024U * 32U, featureSize);
CPLDebugOnly("FlatGeobuf", "ensureFeatureBuf: newBufSize: %d",
newBufSize);
m_featureBuf = static_cast<GByte *>(VSIMalloc(newBufSize));
if (m_featureBuf == nullptr)
return CPLErrorMemoryAllocation("initial feature buffer");
m_featureBufSize = newBufSize;
}
else if (m_featureBufSize < featureSize)
{
// Do not increase this x2 factor without modifying
// feature_max_buffer_size
const auto newBufSize = std::max(m_featureBufSize * 2, featureSize);
CPLDebugOnly("FlatGeobuf", "ensureFeatureBuf: newBufSize: %d",
newBufSize);
const auto featureBuf =
static_cast<GByte *>(VSIRealloc(m_featureBuf, newBufSize));
if (featureBuf == nullptr)
return CPLErrorMemoryAllocation("feature buffer resize");
m_featureBuf = featureBuf;
m_featureBufSize = newBufSize;
}
return OGRERR_NONE;
}
OGRErr OGRFlatGeobufLayer::parseFeature(OGRFeature *poFeature)
{
GIntBig fid;
auto seek = false;
if (m_queriedSpatialIndex && !m_ignoreSpatialFilter)
{
const auto item = m_foundItems[m_featuresPos];
m_offset = m_offsetFeatures + item.offset;
fid = item.index;
seek = true;
}
else
{
fid = m_featuresPos;
}
poFeature->SetFID(fid);
// CPLDebugOnly("FlatGeobuf", "m_featuresPos: %lu", static_cast<long
// unsigned int>(m_featuresPos));
if (m_featuresPos == 0)
seek = true;
if (seek && VSIFSeekL(m_poFp, m_offset, SEEK_SET) == -1)
{
if (VSIFEofL(m_poFp))
return OGRERR_NONE;
return CPLErrorIO("seeking to feature location");
}
uint32_t featureSize;
if (VSIFReadL(&featureSize, sizeof(featureSize), 1, m_poFp) != 1)
{
if (VSIFEofL(m_poFp))
return OGRERR_NONE;
return CPLErrorIO("reading feature size");
}
CPL_LSBPTR32(&featureSize);
// Sanity check to avoid allocated huge amount of memory on corrupted
// feature
if (featureSize > 100 * 1024 * 1024)
{
if (featureSize > feature_max_buffer_size)
return CPLErrorInvalidSize("feature");
if (m_nFileSize == 0)
{
VSIStatBufL sStatBuf;
if (VSIStatL(m_osFilename.c_str(), &sStatBuf) == 0)
{
m_nFileSize = sStatBuf.st_size;
}
}
if (m_offset + featureSize > m_nFileSize)
{
return CPLErrorIO("reading feature size");
}
}
const auto err = ensureFeatureBuf(featureSize);
if (err != OGRERR_NONE)
return err;
if (VSIFReadL(m_featureBuf, 1, featureSize, m_poFp) != featureSize)
return CPLErrorIO("reading feature");
m_offset += featureSize + sizeof(featureSize);
if (m_bVerifyBuffers)
{
Verifier v(m_featureBuf, featureSize);
const auto ok = VerifyFeatureBuffer(v);
if (!ok)
{
CPLError(CE_Failure, CPLE_AppDefined, "Buffer verification failed");
CPLDebugOnly("FlatGeobuf", "m_offset: %lu",
static_cast<long unsigned int>(m_offset));
CPLDebugOnly("FlatGeobuf", "m_featuresPos: %lu",
static_cast<long unsigned int>(m_featuresPos));
CPLDebugOnly("FlatGeobuf", "featureSize: %d", featureSize);
return OGRERR_CORRUPT_DATA;
}
}
const auto feature = GetRoot<Feature>(m_featureBuf);
const auto geometry = feature->geometry();
if (!m_poFeatureDefn->IsGeometryIgnored() && geometry != nullptr)
{
auto geometryType = m_geometryType;
if (geometryType == GeometryType::Unknown)
geometryType = geometry->type();
OGRGeometry *poOGRGeometry =
GeometryReader(geometry, geometryType, m_hasZ, m_hasM).read();
if (poOGRGeometry == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined, "Failed to read geometry");
return OGRERR_CORRUPT_DATA;
}
// #ifdef DEBUG
// char *wkt;
// poOGRGeometry->exportToWkt(&wkt);
// CPLDebugOnly("FlatGeobuf", "readGeometry as wkt: %s",
// wkt);
// #endif
if (m_poSRS != nullptr)
poOGRGeometry->assignSpatialReference(m_poSRS);
poFeature->SetGeometryDirectly(poOGRGeometry);
}
const auto properties = feature->properties();
if (properties != nullptr)
{
const auto data = properties->data();
const auto size = properties->size();
// CPLDebugOnly("FlatGeobuf", "DEBUG parseFeature: size: %lu",
// static_cast<long unsigned int>(size));
// CPLDebugOnly("FlatGeobuf", "properties->size: %d", size);
uoffset_t offset = 0;
// size must be at least large enough to contain
// a single column index and smallest value type
if (size > 0 && size < (sizeof(uint16_t) + sizeof(uint8_t)))
return CPLErrorInvalidSize("property value");
while (offset + 1 < size)
{
if (offset + sizeof(uint16_t) > size)
return CPLErrorInvalidSize("property value");
uint16_t i = *((uint16_t *)(data + offset));
CPL_LSBPTR16(&i);
// CPLDebugOnly("FlatGeobuf", "DEBUG parseFeature: i: %hu", i);
offset += sizeof(uint16_t);
// CPLDebugOnly("FlatGeobuf", "DEBUG parseFeature: offset: %du",
// offset);
// TODO: use columns from feature if defined
const auto columns = m_poHeader->columns();
if (columns == nullptr)
{
CPLErrorInvalidPointer("columns");
return OGRERR_CORRUPT_DATA;
}
if (i >= columns->size())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Column index %hu out of range", i);
return OGRERR_CORRUPT_DATA;
}
const auto column = columns->Get(i);
const auto type = column->type();
const auto isIgnored = poFeature->GetFieldDefnRef(i)->IsIgnored();
const auto ogrField = poFeature->GetRawFieldRef(i);
if (!OGR_RawField_IsUnset(ogrField))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Field %d set more than once", i);
return OGRERR_CORRUPT_DATA;
}
switch (type)
{
case ColumnType::Bool:
if (offset + sizeof(unsigned char) > size)
return CPLErrorInvalidSize("bool value");
if (!isIgnored)
{
ogrField->Integer = *(data + offset);
}
offset += sizeof(unsigned char);
break;
case ColumnType::Byte:
if (offset + sizeof(signed char) > size)
return CPLErrorInvalidSize("byte value");
if (!isIgnored)
{
ogrField->Integer =
*reinterpret_cast<const signed char *>(data +
offset);
}
offset += sizeof(signed char);
break;
case ColumnType::UByte:
if (offset + sizeof(unsigned char) > size)
return CPLErrorInvalidSize("ubyte value");
if (!isIgnored)
{
ogrField->Integer =
*reinterpret_cast<const unsigned char *>(data +
offset);
}
offset += sizeof(unsigned char);
break;
case ColumnType::Short:
if (offset + sizeof(int16_t) > size)
return CPLErrorInvalidSize("short value");
if (!isIgnored)
{
short s;
memcpy(&s, data + offset, sizeof(int16_t));
CPL_LSBPTR16(&s);
ogrField->Integer = s;
}
offset += sizeof(int16_t);
break;
case ColumnType::UShort:
if (offset + sizeof(uint16_t) > size)
return CPLErrorInvalidSize("ushort value");
if (!isIgnored)
{
uint16_t s;
memcpy(&s, data + offset, sizeof(uint16_t));
CPL_LSBPTR16(&s);
ogrField->Integer = s;
}
offset += sizeof(uint16_t);
break;
case ColumnType::Int:
if (offset + sizeof(int32_t) > size)
return CPLErrorInvalidSize("int32 value");
if (!isIgnored)
{
memcpy(&ogrField->Integer, data + offset,
sizeof(int32_t));
CPL_LSBPTR32(&ogrField->Integer);
}
offset += sizeof(int32_t);
break;
case ColumnType::UInt:
if (offset + sizeof(uint32_t) > size)
return CPLErrorInvalidSize("uint value");
if (!isIgnored)
{
uint32_t v;
memcpy(&v, data + offset, sizeof(int32_t));
CPL_LSBPTR32(&v);
ogrField->Integer64 = v;
}
offset += sizeof(int32_t);
break;
case ColumnType::Long:
if (offset + sizeof(int64_t) > size)
return CPLErrorInvalidSize("int64 value");
if (!isIgnored)
{
memcpy(&ogrField->Integer64, data + offset,
sizeof(int64_t));
CPL_LSBPTR64(&ogrField->Integer64);
}
offset += sizeof(int64_t);
break;
case ColumnType::ULong:
if (offset + sizeof(uint64_t) > size)
return CPLErrorInvalidSize("uint64 value");
if (!isIgnored)
{
uint64_t v;
memcpy(&v, data + offset, sizeof(v));
CPL_LSBPTR64(&v);
ogrField->Real = static_cast<double>(v);
}
offset += sizeof(int64_t);
break;
case ColumnType::Float:
if (offset + sizeof(float) > size)
return CPLErrorInvalidSize("float value");
if (!isIgnored)
{
float f;
memcpy(&f, data + offset, sizeof(float));
CPL_LSBPTR32(&f);
ogrField->Real = f;
}
offset += sizeof(float);
break;
case ColumnType::Double:
if (offset + sizeof(double) > size)
return CPLErrorInvalidSize("double value");
if (!isIgnored)
{
memcpy(&ogrField->Real, data + offset, sizeof(double));
CPL_LSBPTR64(&ogrField->Real);
}
offset += sizeof(double);
break;
case ColumnType::String:
case ColumnType::Json:
{
if (offset + sizeof(uint32_t) > size)
return CPLErrorInvalidSize("string length");
uint32_t len;
memcpy(&len, data + offset, sizeof(int32_t));
CPL_LSBPTR32(&len);
offset += sizeof(uint32_t);
if (len > size - offset)
return CPLErrorInvalidSize("string value");
if (!isIgnored)
{
char *str =
static_cast<char *>(VSI_MALLOC_VERBOSE(len + 1));
if (str == nullptr)
return CPLErrorMemoryAllocation("string value");
memcpy(str, data + offset, len);
str[len] = '\0';
ogrField->String = str;
}
offset += len;
break;
}
case ColumnType::DateTime:
{
if (offset + sizeof(uint32_t) > size)
return CPLErrorInvalidSize("datetime length ");
uint32_t len;
memcpy(&len, data + offset, sizeof(int32_t));
CPL_LSBPTR32(&len);
offset += sizeof(uint32_t);
if (len > size - offset || len > 32)
return CPLErrorInvalidSize("datetime value");
if (!isIgnored)
{
if (!ParseDateTime(
reinterpret_cast<const char *>(data + offset),
len, ogrField))
{
char str[32 + 1];
memcpy(str, data + offset, len);
str[len] = '\0';
if (!OGRParseDate(str, ogrField, 0))
{
OGR_RawField_SetUnset(ogrField);
}
}
}
offset += len;
break;
}
case ColumnType::Binary:
{
if (offset + sizeof(uint32_t) > size)
return CPLErrorInvalidSize("binary length");
uint32_t len;
memcpy(&len, data + offset, sizeof(int32_t));
CPL_LSBPTR32(&len);
offset += sizeof(uint32_t);
if (len > static_cast<uint32_t>(INT_MAX) ||
len > size - offset)
return CPLErrorInvalidSize("binary value");
if (!isIgnored)
{
GByte *binary = static_cast<GByte *>(
VSI_MALLOC_VERBOSE(len ? len : 1));
if (binary == nullptr)
return CPLErrorMemoryAllocation("string value");
memcpy(binary, data + offset, len);
ogrField->Binary.nCount = static_cast<int>(len);
ogrField->Binary.paData = binary;
}
offset += len;
break;
}
}
}
}
return OGRERR_NONE;
}
/************************************************************************/
/* GetNextArrowArray() */
/************************************************************************/
int OGRFlatGeobufLayer::GetNextArrowArray(struct ArrowArrayStream *stream,
struct ArrowArray *out_array)
{
if (m_poAttrQuery != nullptr ||
(m_poFilterGeom != nullptr &&
!(m_poHeader != nullptr && m_poHeader->index_node_size() > 0)) ||
CPLTestBool(
CPLGetConfigOption("OGR_FLATGEOBUF_STREAM_BASE_IMPL", "NO")))
{
return OGRLayer::GetNextArrowArray(stream, out_array);
}
int errorErrno = EIO;
memset(out_array, 0, sizeof(*out_array));
if (m_create)
return EINVAL;
if (m_bEOF || (m_featuresCount > 0 && m_featuresPos >= m_featuresCount))
{
return 0;
}
if (readIndex() != OGRERR_NONE)
return EIO;
OGRArrowArrayHelper sHelper(
nullptr, // dataset pointer. only used for field domains (not used by
// FlatGeobuf)
m_poFeatureDefn, m_aosArrowArrayStreamOptions, out_array);
if (out_array->release == nullptr)
{
return ENOMEM;
}
std::vector<bool> abSetFields(sHelper.nFieldCount);
struct tm brokenDown;
memset(&brokenDown, 0, sizeof(brokenDown));
int iFeat = 0;
bool bEOFOrError = true;
if (m_queriedSpatialIndex && m_featuresCount == 0)
{
CPLDebugOnly("FlatGeobuf", "GetNextFeature: no features found");
sHelper.nMaxBatchSize = 0;
}
for (; iFeat < sHelper.nMaxBatchSize; iFeat++)
{
bEOFOrError = true;
if (m_featuresCount > 0 && m_featuresPos >= m_featuresCount)
{
CPLDebugOnly("FlatGeobuf", "GetNextFeature: iteration end at %lu",
static_cast<long unsigned int>(m_featuresPos));
break;
}
GIntBig fid;
auto seek = false;
if (m_queriedSpatialIndex && !m_ignoreSpatialFilter)
{
const auto item = m_foundItems[m_featuresPos];
m_offset = m_offsetFeatures + item.offset;
fid = item.index;
seek = true;
}
else
{
fid = m_featuresPos;
}
if (sHelper.panFIDValues)
sHelper.panFIDValues[iFeat] = fid;
if (m_featuresPos == 0)
seek = true;
if (seek && VSIFSeekL(m_poFp, m_offset, SEEK_SET) == -1)
{
break;
}
uint32_t featureSize;
if (VSIFReadL(&featureSize, sizeof(featureSize), 1, m_poFp) != 1)
{
if (VSIFEofL(m_poFp))
break;
CPLErrorIO("reading feature size");
goto error;
}
CPL_LSBPTR32(&featureSize);
// Sanity check to avoid allocated huge amount of memory on corrupted
// feature
if (featureSize > 100 * 1024 * 1024)
{
if (featureSize > feature_max_buffer_size)
{
CPLErrorInvalidSize("feature");
goto error;
}
if (m_nFileSize == 0)
{
VSIStatBufL sStatBuf;
if (VSIStatL(m_osFilename.c_str(), &sStatBuf) == 0)
{
m_nFileSize = sStatBuf.st_size;
}
}
if (m_offset + featureSize > m_nFileSize)
{
CPLErrorIO("reading feature size");
goto error;
}
}
const auto err = ensureFeatureBuf(featureSize);
if (err != OGRERR_NONE)
goto error;
if (VSIFReadL(m_featureBuf, 1, featureSize, m_poFp) != featureSize)
{
CPLErrorIO("reading feature");
goto error;
}
m_offset += featureSize + sizeof(featureSize);
if (m_bVerifyBuffers)
{
Verifier v(m_featureBuf, featureSize);
const auto ok = VerifyFeatureBuffer(v);
if (!ok)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Buffer verification failed");
CPLDebugOnly("FlatGeobuf", "m_offset: %lu",
static_cast<long unsigned int>(m_offset));
CPLDebugOnly("FlatGeobuf", "m_featuresPos: %lu",
static_cast<long unsigned int>(m_featuresPos));
CPLDebugOnly("FlatGeobuf", "featureSize: %d", featureSize);
goto error;
}
}
const auto feature = GetRoot<Feature>(m_featureBuf);
const auto geometry = feature->geometry();
if (!m_poFeatureDefn->IsGeometryIgnored() && geometry != nullptr)
{
auto geometryType = m_geometryType;
if (geometryType == GeometryType::Unknown)
geometryType = geometry->type();
auto poOGRGeometry = std::unique_ptr<OGRGeometry>(
GeometryReader(geometry, geometryType, m_hasZ, m_hasM).read());
if (poOGRGeometry == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to read geometry");
goto error;
}
const int iArrowField = sHelper.mapOGRGeomFieldToArrowField[0];
const size_t nWKBSize = poOGRGeometry->WkbSize();
GByte *outPtr =
sHelper.GetPtrForStringOrBinary(iArrowField, iFeat, nWKBSize);
if (outPtr == nullptr)
{
errorErrno = ENOMEM;
goto error;
}
poOGRGeometry->exportToWkb(wkbNDR, outPtr, wkbVariantIso);
}
abSetFields.clear();
abSetFields.resize(sHelper.nFieldCount);
const auto properties = feature->properties();
if (properties != nullptr)
{
const auto data = properties->data();
const auto size = properties->size();
uoffset_t offset = 0;
// size must be at least large enough to contain
// a single column index and smallest value type
if (size > 0 && size < (sizeof(uint16_t) + sizeof(uint8_t)))
{
CPLErrorInvalidSize("property value");
goto error;
}
while (offset + 1 < size)
{
if (offset + sizeof(uint16_t) > size)
{
CPLErrorInvalidSize("property value");
goto error;
}
uint16_t i = *((uint16_t *)(data + offset));
CPL_LSBPTR16(&i);
offset += sizeof(uint16_t);
// TODO: use columns from feature if defined
const auto columns = m_poHeader->columns();
if (columns == nullptr)
{
CPLErrorInvalidPointer("columns");
goto error;
}
if (i >= columns->size())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Column index %hu out of range", i);
goto error;
}
abSetFields[i] = true;
const auto column = columns->Get(i);
const auto type = column->type();
const int iArrowField = sHelper.mapOGRFieldToArrowField[i];
const bool isIgnored = iArrowField < 0;
auto psArray =
isIgnored ? nullptr : out_array->children[iArrowField];
switch (type)
{
case ColumnType::Bool:
if (offset + sizeof(unsigned char) > size)
{
CPLErrorInvalidSize("bool value");
goto error;
}
if (!isIgnored)
{
if (*(data + offset))
{
sHelper.SetBoolOn(psArray, iFeat);
}
}
offset += sizeof(unsigned char);
break;
case ColumnType::Byte:
if (offset + sizeof(signed char) > size)
{
CPLErrorInvalidSize("byte value");
goto error;
}
if (!isIgnored)
{
sHelper.SetInt8(psArray, iFeat,
*reinterpret_cast<const int8_t *>(
data + offset));
}
offset += sizeof(signed char);
break;
case ColumnType::UByte:
if (offset + sizeof(unsigned char) > size)
{
CPLErrorInvalidSize("ubyte value");
goto error;
}
if (!isIgnored)
{
sHelper.SetUInt8(psArray, iFeat,
*reinterpret_cast<const uint8_t *>(
data + offset));
}
offset += sizeof(unsigned char);
break;
case ColumnType::Short:
if (offset + sizeof(int16_t) > size)
{
CPLErrorInvalidSize("short value");
goto error;
}
if (!isIgnored)
{
short s;
memcpy(&s, data + offset, sizeof(int16_t));
CPL_LSBPTR16(&s);
sHelper.SetInt16(psArray, iFeat, s);
}
offset += sizeof(int16_t);
break;
case ColumnType::UShort:
if (offset + sizeof(uint16_t) > size)
{
CPLErrorInvalidSize("ushort value");
goto error;
}
if (!isIgnored)
{
uint16_t s;
memcpy(&s, data + offset, sizeof(uint16_t));
CPL_LSBPTR16(&s);
sHelper.SetInt32(psArray, iFeat, s);
}
offset += sizeof(uint16_t);
break;
case ColumnType::Int:
if (offset + sizeof(int32_t) > size)
{
CPLErrorInvalidSize("int32 value");
goto error;
}
if (!isIgnored)
{
int32_t nVal;
memcpy(&nVal, data + offset, sizeof(int32_t));
CPL_LSBPTR32(&nVal);
sHelper.SetInt32(psArray, iFeat, nVal);
}
offset += sizeof(int32_t);
break;
case ColumnType::UInt:
if (offset + sizeof(uint32_t) > size)
{
CPLErrorInvalidSize("uint value");
goto error;
}
if (!isIgnored)
{
uint32_t v;
memcpy(&v, data + offset, sizeof(int32_t));
CPL_LSBPTR32(&v);
sHelper.SetInt64(psArray, iFeat, v);
}
offset += sizeof(int32_t);
break;
case ColumnType::Long:
if (offset + sizeof(int64_t) > size)
{
CPLErrorInvalidSize("int64 value");
goto error;
}
if (!isIgnored)
{
int64_t v;
memcpy(&v, data + offset, sizeof(int64_t));
CPL_LSBPTR64(&v);
sHelper.SetInt64(psArray, iFeat, v);
}
offset += sizeof(int64_t);
break;
case ColumnType::ULong:
if (offset + sizeof(uint64_t) > size)
{
CPLErrorInvalidSize("uint64 value");
goto error;
}
if (!isIgnored)
{
uint64_t v;
memcpy(&v, data + offset, sizeof(v));
CPL_LSBPTR64(&v);
sHelper.SetDouble(psArray, iFeat,
static_cast<double>(v));
}
offset += sizeof(int64_t);
break;
case ColumnType::Float:
if (offset + sizeof(float) > size)
{
CPLErrorInvalidSize("float value");
goto error;
}
if (!isIgnored)
{
float f;
memcpy(&f, data + offset, sizeof(float));
CPL_LSBPTR32(&f);
sHelper.SetFloat(psArray, iFeat, f);
}
offset += sizeof(float);
break;
case ColumnType::Double:
if (offset + sizeof(double) > size)
{
CPLErrorInvalidSize("double value");
goto error;
}
if (!isIgnored)
{
double v;
memcpy(&v, data + offset, sizeof(double));
CPL_LSBPTR64(&v);
sHelper.SetDouble(psArray, iFeat, v);
}
offset += sizeof(double);
break;
case ColumnType::String:
case ColumnType::Json:
case ColumnType::Binary:
{
if (offset + sizeof(uint32_t) > size)
{
CPLErrorInvalidSize("string length");
goto error;
}
uint32_t len;
memcpy(&len, data + offset, sizeof(int32_t));
CPL_LSBPTR32(&len);
offset += sizeof(uint32_t);
if (len > size - offset)
{
CPLErrorInvalidSize("string value");
goto error;
}
if (!isIgnored)
{
GByte *outPtr = sHelper.GetPtrForStringOrBinary(
iArrowField, iFeat, len);
if (outPtr == nullptr)
{
errorErrno = ENOMEM;
goto error;
}
memcpy(outPtr, data + offset, len);
}
offset += len;
break;
}
case ColumnType::DateTime:
{
if (offset + sizeof(uint32_t) > size)
{
CPLErrorInvalidSize("datetime length ");
goto error;
}
uint32_t len;
memcpy(&len, data + offset, sizeof(int32_t));
CPL_LSBPTR32(&len);
offset += sizeof(uint32_t);
if (len > size - offset || len > 32)
{
CPLErrorInvalidSize("datetime value");
goto error;
}
if (!isIgnored)
{
OGRField ogrField;
if (ParseDateTime(reinterpret_cast<const char *>(
data + offset),
len, &ogrField))
{
sHelper.SetDateTime(psArray, iFeat, brokenDown,
ogrField);
}
else
{
char str[32 + 1];
memcpy(str, data + offset, len);
str[len] = '\0';
if (OGRParseDate(str, &ogrField, 0))
{
sHelper.SetDateTime(psArray, iFeat,
brokenDown, ogrField);
}
}
}
offset += len;
break;
}
}
}
}
// Mark null fields
for (int i = 0; i < sHelper.nFieldCount; i++)
{
if (!abSetFields[i] && sHelper.abNullableFields[i])
{
const int iArrowField = sHelper.mapOGRFieldToArrowField[i];
if (iArrowField >= 0)
{
sHelper.SetNull(iArrowField, iFeat);
}
}
}
if (VSIFEofL(m_poFp))
{
CPLDebug("FlatGeobuf", "GetNextFeature: iteration end due to EOF");
break;
}
m_featuresPos++;
bEOFOrError = false;
}
if (bEOFOrError && m_featuresCount > 0)
m_bEOF = true;
sHelper.Shrink(iFeat);
return 0;
error:
sHelper.ClearArray();
return errorErrno;
}
OGRErr OGRFlatGeobufLayer::CreateField(OGRFieldDefn *poField,
int /* bApproxOK */)
{
// CPLDebugOnly("FlatGeobuf", "CreateField %s %s", poField->GetNameRef(),
// poField->GetFieldTypeName(poField->GetType()));
if (!TestCapability(OLCCreateField))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Unable to create new fields after first feature written.");
return OGRERR_FAILURE;
}
if (m_poFeatureDefn->GetFieldCount() > std::numeric_limits<uint16_t>::max())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot create features with more than 65536 columns");
return OGRERR_FAILURE;
}
m_poFeatureDefn->AddFieldDefn(poField);
return OGRERR_NONE;
}
OGRErr OGRFlatGeobufLayer::ICreateFeature(OGRFeature *poNewFeature)
{
if (!m_create)
{
CPLError(CE_Failure, CPLE_AppDefined,
"CreateFeature() not supported on read-only layer");
return OGRERR_FAILURE;
}
const auto fieldCount = m_poFeatureDefn->GetFieldCount();
std::vector<uint8_t> properties;
properties.reserve(1024 * 4);
FlatBufferBuilder fbb;
fbb.TrackMinAlign(8);
for (int i = 0; i < fieldCount; i++)
{
const auto fieldDef = m_poFeatureDefn->GetFieldDefn(i);
if (!poNewFeature->IsFieldSetAndNotNull(i))
continue;
uint16_t column_index_le = static_cast<uint16_t>(i);
CPL_LSBPTR16(&column_index_le);
// CPLDebugOnly("FlatGeobuf", "DEBUG ICreateFeature: column_index_le:
// %hu", column_index_le);
std::copy(reinterpret_cast<const uint8_t *>(&column_index_le),
reinterpret_cast<const uint8_t *>(&column_index_le + 1),
std::back_inserter(properties));
const auto fieldType = fieldDef->GetType();
const auto fieldSubType = fieldDef->GetSubType();
const auto field = poNewFeature->GetRawFieldRef(i);
switch (fieldType)
{
case OGRFieldType::OFTInteger:
{
int nVal = field->Integer;
if (fieldSubType == OFSTBoolean)
{
GByte byVal = static_cast<GByte>(nVal);
std::copy(reinterpret_cast<const uint8_t *>(&byVal),
reinterpret_cast<const uint8_t *>(&byVal + 1),
std::back_inserter(properties));
}
else if (fieldSubType == OFSTInt16)
{
short sVal = static_cast<short>(nVal);
CPL_LSBPTR16(&sVal);
std::copy(reinterpret_cast<const uint8_t *>(&sVal),
reinterpret_cast<const uint8_t *>(&sVal + 1),
std::back_inserter(properties));
}
else
{
CPL_LSBPTR32(&nVal);
std::copy(reinterpret_cast<const uint8_t *>(&nVal),
reinterpret_cast<const uint8_t *>(&nVal + 1),
std::back_inserter(properties));
}
break;
}
case OGRFieldType::OFTInteger64:
{
GIntBig nVal = field->Integer64;
CPL_LSBPTR64(&nVal);
std::copy(reinterpret_cast<const uint8_t *>(&nVal),
reinterpret_cast<const uint8_t *>(&nVal + 1),
std::back_inserter(properties));
break;
}
case OGRFieldType::OFTReal:
{
double dfVal = field->Real;
if (fieldSubType == OFSTFloat32)
{
float fVal = static_cast<float>(dfVal);
CPL_LSBPTR32(&fVal);
std::copy(reinterpret_cast<const uint8_t *>(&fVal),
reinterpret_cast<const uint8_t *>(&fVal + 1),
std::back_inserter(properties));
}
else
{
CPL_LSBPTR64(&dfVal);
std::copy(reinterpret_cast<const uint8_t *>(&dfVal),
reinterpret_cast<const uint8_t *>(&dfVal + 1),
std::back_inserter(properties));
}
break;
}
case OGRFieldType::OFTDate:
case OGRFieldType::OFTTime:
case OGRFieldType::OFTDateTime:
{
char szBuffer[OGR_SIZEOF_ISO8601_DATETIME_BUFFER];
const size_t len =
OGRGetISO8601DateTime(field, false, szBuffer);
uint32_t l_le = static_cast<uint32_t>(len);
CPL_LSBPTR32(&l_le);
std::copy(reinterpret_cast<const uint8_t *>(&l_le),
reinterpret_cast<const uint8_t *>(&l_le + 1),
std::back_inserter(properties));
std::copy(szBuffer, szBuffer + len,
std::back_inserter(properties));
break;
}
case OGRFieldType::OFTString:
{
const size_t len = strlen(field->String);
if (len >= feature_max_buffer_size ||
properties.size() > feature_max_buffer_size - len)
{
CPLError(CE_Failure, CPLE_AppDefined,
"ICreateFeature: String too long");
return OGRERR_FAILURE;
}
// Valid cast since feature_max_buffer_size is 2 GB
uint32_t l_le = static_cast<uint32_t>(len);
CPL_LSBPTR32(&l_le);
std::copy(reinterpret_cast<const uint8_t *>(&l_le),
reinterpret_cast<const uint8_t *>(&l_le + 1),
std::back_inserter(properties));
try
{
// to avoid coverity scan warning: "To avoid a quadratic
// time penalty when using reserve(), always increase the
// capacity
/// by a multiple of its current value"
if (properties.size() + len > properties.capacity() &&
properties.size() <
std::numeric_limits<size_t>::max() / 2)
{
properties.reserve(std::max(2 * properties.size(),
properties.size() + len));
}
}
catch (const std::bad_alloc &)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"ICreateFeature: String too long");
return OGRERR_FAILURE;
}
std::copy(field->String, field->String + len,
std::back_inserter(properties));
break;
}
case OGRFieldType::OFTBinary:
{
const size_t len = field->Binary.nCount;
if (len >= feature_max_buffer_size ||
properties.size() > feature_max_buffer_size - len)
{
CPLError(CE_Failure, CPLE_AppDefined,
"ICreateFeature: Binary too long");
return OGRERR_FAILURE;
}
uint32_t l_le = static_cast<uint32_t>(len);
CPL_LSBPTR32(&l_le);
std::copy(reinterpret_cast<const uint8_t *>(&l_le),
reinterpret_cast<const uint8_t *>(&l_le + 1),
std::back_inserter(properties));
try
{
// to avoid coverity scan warning: "To avoid a quadratic
// time penalty when using reserve(), always increase the
// capacity
/// by a multiple of its current value"
if (properties.size() + len > properties.capacity() &&
properties.size() <
std::numeric_limits<size_t>::max() / 2)
{
properties.reserve(std::max(2 * properties.size(),
properties.size() + len));
}
}
catch (const std::bad_alloc &)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"ICreateFeature: Binary too long");
return OGRERR_FAILURE;
}
std::copy(field->Binary.paData, field->Binary.paData + len,
std::back_inserter(properties));
break;
}
default:
CPLError(CE_Failure, CPLE_AppDefined,
"ICreateFeature: Missing implementation for "
"OGRFieldType %d",
fieldType);
return OGRERR_FAILURE;
}
}
// CPLDebugOnly("FlatGeobuf", "DEBUG ICreateFeature: properties.size():
// %lu", static_cast<long unsigned int>(properties.size()));
const auto ogrGeometry = poNewFeature->GetGeometryRef();
#ifdef DEBUG
// char *wkt;
// ogrGeometry->exportToWkt(&wkt);
// CPLDebugOnly("FlatGeobuf", "poNewFeature as wkt: %s", wkt);
#endif
if (m_bCreateSpatialIndexAtClose &&
(ogrGeometry == nullptr || ogrGeometry->IsEmpty()))
{
CPLError(
CE_Failure, CPLE_AppDefined,
"ICreateFeature: NULL geometry not supported with spatial index");
return OGRERR_FAILURE;
}
if (ogrGeometry != nullptr && m_geometryType != GeometryType::Unknown &&
ogrGeometry->getGeometryType() != m_eGType)
{
CPLError(CE_Failure, CPLE_AppDefined,
"ICreateFeature: Mismatched geometry type");
return OGRERR_FAILURE;
}
try
{
// FlatBuffer serialization will crash/assert if the vectors go
// beyond FLATBUFFERS_MAX_BUFFER_SIZE. We cannot easily anticipate
// the size of the FlatBuffer, but WKB might be a good approximation.
// Takes an extra security margin of 10%
flatbuffers::Offset<FlatGeobuf::Geometry> geometryOffset = 0;
if (ogrGeometry != nullptr)
{
const auto nWKBSize = ogrGeometry->WkbSize();
if (nWKBSize > feature_max_buffer_size - nWKBSize / 10)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"ICreateFeature: Too big geometry");
return OGRERR_FAILURE;
}
GeometryWriter writer{fbb, ogrGeometry, m_geometryType, m_hasZ,
m_hasM};
geometryOffset = writer.write(0);
}
const auto pProperties = properties.empty() ? nullptr : &properties;
if (properties.size() > feature_max_buffer_size - geometryOffset.o)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"ICreateFeature: Too big feature");
return OGRERR_FAILURE;
}
// TODO: write columns if mixed schema in collection
const auto feature =
CreateFeatureDirect(fbb, geometryOffset, pProperties);
fbb.FinishSizePrefixed(feature);
OGREnvelope psEnvelope;
if (ogrGeometry != nullptr)
{
ogrGeometry->getEnvelope(&psEnvelope);
if (m_sExtent.IsInit())
m_sExtent.Merge(psEnvelope);
else
m_sExtent = psEnvelope;
}
if (m_featuresCount == 0)
{
if (m_poFpWrite == nullptr)
{
CPLErrorInvalidPointer("output file handler");
return OGRERR_FAILURE;
}
if (!SupportsSeekWhileWriting(m_osFilename))
{
writeHeader(m_poFpWrite, 0, nullptr);
}
else
{
std::vector<double> dummyExtent(
4, std::numeric_limits<double>::quiet_NaN());
const uint64_t dummyFeatureCount =
0xDEADBEEF; // write non-zero value, otherwise the reserved
// size is not OK
writeHeader(m_poFpWrite, dummyFeatureCount,
&dummyExtent); // we will update it later
m_offsetAfterHeader = m_writeOffset;
}
CPLDebugOnly("FlatGeobuf", "Writing first feature at offset: %lu",
static_cast<long unsigned int>(m_writeOffset));
}
m_maxFeatureSize =
std::max(m_maxFeatureSize, static_cast<uint32_t>(fbb.GetSize()));
size_t c =
VSIFWriteL(fbb.GetBufferPointer(), 1, fbb.GetSize(), m_poFpWrite);
if (c == 0)
return CPLErrorIO("writing feature");
if (m_bCreateSpatialIndexAtClose)
{
FeatureItem item;
item.size = static_cast<uint32_t>(fbb.GetSize());
item.offset = m_writeOffset;
item.nodeItem = {psEnvelope.MinX, psEnvelope.MinY, psEnvelope.MaxX,
psEnvelope.MaxY, 0};
m_featureItems.emplace_back(std::move(item));
}
m_writeOffset += c;
m_featuresCount++;
return OGRERR_NONE;
}
catch (const std::bad_alloc &)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"ICreateFeature: Memory allocation failure");
return OGRERR_FAILURE;
}
}
OGRErr OGRFlatGeobufLayer::GetExtent(OGREnvelope *psExtent, int bForce)
{
if (m_sExtent.IsInit())
{
*psExtent = m_sExtent;
return OGRERR_NONE;
}
return OGRLayer::GetExtent(psExtent, bForce);
}
int OGRFlatGeobufLayer::TestCapability(const char *pszCap)
{
if (EQUAL(pszCap, OLCCreateField))
return m_create;
else if (EQUAL(pszCap, OLCSequentialWrite))
return m_create;
else if (EQUAL(pszCap, OLCRandomRead))
return m_poHeader != nullptr && m_poHeader->index_node_size() > 0;
else if (EQUAL(pszCap, OLCIgnoreFields))
return true;
else if (EQUAL(pszCap, OLCMeasuredGeometries))
return true;
else if (EQUAL(pszCap, OLCCurveGeometries))
return true;
else if (EQUAL(pszCap, OLCZGeometries))
return true;
else if (EQUAL(pszCap, OLCFastFeatureCount))
return m_poFilterGeom == nullptr && m_poAttrQuery == nullptr &&
m_featuresCount > 0;
else if (EQUAL(pszCap, OLCFastGetExtent))
return m_sExtent.IsInit();
else if (EQUAL(pszCap, OLCFastSpatialFilter))
return m_poHeader != nullptr && m_poHeader->index_node_size() > 0;
else if (EQUAL(pszCap, OLCStringsAsUTF8))
return true;
else if (EQUAL(pszCap, OLCFastGetArrowStream) && m_poAttrQuery == nullptr &&
m_poFilterGeom == nullptr)
return true;
else
return false;
}
void OGRFlatGeobufLayer::ResetReading()
{
CPLDebugOnly("FlatGeobuf", "ResetReading");
m_offset = m_offsetFeatures;
m_bEOF = false;
m_featuresPos = 0;
m_foundItems.clear();
m_featuresCount = m_poHeader ? m_poHeader->features_count() : 0;
m_queriedSpatialIndex = false;
m_ignoreSpatialFilter = false;
m_ignoreAttributeFilter = false;
return;
}
std::string OGRFlatGeobufLayer::GetTempFilePath(const CPLString &fileName,
CSLConstList papszOptions)
{
const CPLString osDirname(CPLGetPath(fileName.c_str()));
const CPLString osBasename(CPLGetBasename(fileName.c_str()));
const char *pszTempDir = CSLFetchNameValue(papszOptions, "TEMPORARY_DIR");
std::string osTempFile =
pszTempDir ? CPLFormFilename(pszTempDir, osBasename, nullptr)
: (STARTS_WITH(fileName, "/vsi") && !STARTS_WITH(fileName, "/vsimem/"))
? CPLGenerateTempFilename(osBasename)
: CPLFormFilename(osDirname, osBasename, nullptr);
osTempFile += "_temp.fgb";
return osTempFile;
}
VSILFILE *OGRFlatGeobufLayer::CreateOutputFile(const CPLString &osFilename,
CSLConstList papszOptions,
bool isTemp)
{
std::string osTempFile;
VSILFILE *poFpWrite;
int savedErrno;
if (isTemp)
{
CPLDebug("FlatGeobuf", "Spatial index requested will write to temp "
"file and do second pass on close");
osTempFile = GetTempFilePath(osFilename, papszOptions);
poFpWrite = VSIFOpenL(osTempFile.c_str(), "w+b");
savedErrno = errno;
// Unlink it now to avoid stale temporary file if killing the process
// (only works on Unix)
VSIUnlink(osTempFile.c_str());
}
else
{
CPLDebug("FlatGeobuf",
"No spatial index will write directly to output");
if (!SupportsSeekWhileWriting(osFilename))
poFpWrite = VSIFOpenL(osFilename, "wb");
else
poFpWrite = VSIFOpenL(osFilename, "w+b");
savedErrno = errno;
}
if (poFpWrite == nullptr)
{
CPLError(CE_Failure, CPLE_OpenFailed, "Failed to create %s:\n%s",
osFilename.c_str(), VSIStrerror(savedErrno));
return nullptr;
}
return poFpWrite;
}
OGRFlatGeobufLayer *
OGRFlatGeobufLayer::Create(const char *pszLayerName, const char *pszFilename,
OGRSpatialReference *poSpatialRef,
OGRwkbGeometryType eGType,
bool bCreateSpatialIndexAtClose, char **papszOptions)
{
std::string osTempFile = GetTempFilePath(pszFilename, papszOptions);
VSILFILE *poFpWrite =
CreateOutputFile(pszFilename, papszOptions, bCreateSpatialIndexAtClose);
if (poFpWrite == nullptr)
return nullptr;
OGRFlatGeobufLayer *layer = new OGRFlatGeobufLayer(
pszLayerName, pszFilename, poSpatialRef, eGType,
bCreateSpatialIndexAtClose, poFpWrite, osTempFile);
return layer;
}
OGRFlatGeobufLayer *OGRFlatGeobufLayer::Open(const Header *poHeader,
GByte *headerBuf,
const char *pszFilename,
VSILFILE *poFp, uint64_t offset)
{
OGRFlatGeobufLayer *layer =
new OGRFlatGeobufLayer(poHeader, headerBuf, pszFilename, poFp, offset);
return layer;
}
OGRFlatGeobufLayer *OGRFlatGeobufLayer::Open(const char *pszFilename,
VSILFILE *fp, bool bVerifyBuffers)
{
uint64_t offset = sizeof(magicbytes);
CPLDebugOnly("FlatGeobuf", "Start at offset: %lu",
static_cast<long unsigned int>(offset));
if (VSIFSeekL(fp, offset, SEEK_SET) == -1)
{
CPLError(CE_Failure, CPLE_AppDefined, "Unable to get seek in file");
return nullptr;
}
uint32_t headerSize;
if (VSIFReadL(&headerSize, 4, 1, fp) != 1)
{
CPLError(CE_Failure, CPLE_AppDefined, "Failed to read header size");
return nullptr;
}
CPL_LSBPTR32(&headerSize);
CPLDebugOnly("FlatGeobuf", "headerSize: %d", headerSize);
if (headerSize > header_max_buffer_size)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Header size too large (> 10 MB)");
return nullptr;
}
std::unique_ptr<GByte, CPLFreeReleaser> buf(
static_cast<GByte *>(VSIMalloc(headerSize)));
if (buf == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to allocate memory for header");
return nullptr;
}
if (VSIFReadL(buf.get(), 1, headerSize, fp) != headerSize)
{
CPLError(CE_Failure, CPLE_AppDefined, "Failed to read header");
return nullptr;
}
if (bVerifyBuffers)
{
Verifier v(buf.get(), headerSize, 64U, 1000000U, false);
const auto ok = VerifyHeaderBuffer(v);
if (!ok)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Header failed consistency verification");
return nullptr;
}
}
const auto header = GetHeader(buf.get());
offset += 4 + headerSize;
CPLDebugOnly("FlatGeobuf", "Add header size + length prefix to offset (%d)",
4 + headerSize);
const auto featuresCount = header->features_count();
if (featuresCount >
std::min(static_cast<uint64_t>(std::numeric_limits<size_t>::max() / 8),
static_cast<uint64_t>(100) * 1000 * 1000 * 1000))
{
CPLError(CE_Failure, CPLE_AppDefined, "Too many features");
return nullptr;
}
const auto index_node_size = header->index_node_size();
if (index_node_size > 0)
{
try
{
const auto treeSize = PackedRTree::size(featuresCount);
CPLDebugOnly("FlatGeobuf", "Tree start at offset (%lu)",
static_cast<long unsigned int>(offset));
offset += treeSize;
CPLDebugOnly("FlatGeobuf", "Add tree size to offset (%lu)",
static_cast<long unsigned int>(treeSize));
}
catch (const std::exception &e)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to calculate tree size: %s", e.what());
return nullptr;
}
}
CPLDebugOnly("FlatGeobuf", "Features start at offset (%lu)",
static_cast<long unsigned int>(offset));
CPLDebugOnly("FlatGeobuf", "Opening OGRFlatGeobufLayer");
auto poLayer = OGRFlatGeobufLayer::Open(header, buf.release(), pszFilename,
fp, offset);
poLayer->VerifyBuffers(bVerifyBuffers);
return poLayer;
}
OGRFlatGeobufBaseLayerInterface::~OGRFlatGeobufBaseLayerInterface() = default; |
fb5817cb838c7bb7dbf8911d47ee0886b10d2a32 | 6685563f47afd43c49a7bcf1edc054b100f72695 | /potyczki algorytmiczne/2020/kol.cpp | ff26cdfb614c4e5eb6a9786c993c5bc806778fd1 | [] | no_license | Noxitu/contests | e6c7841897f981e43429043390b9fb14603939d2 | c8b1502a21e150fd60b8450d15598d49b89f45f6 | refs/heads/master | 2021-06-23T16:00:39.576815 | 2020-12-10T21:16:17 | 2020-12-10T21:16:17 | 29,066,178 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,343 | cpp | kol.cpp | #include <bits/stdc++.h>
// #define MULTIPLE_TESTS
// #define ENDLESS_TESTS
#define TIME_LIMIT 1
#define MEMORY_LIMIT 128
using namespace std;
void test()
{
int n, m;
cin >> n >> m;
vector<pair<int, int>> changes;
changes.reserve(2*m);
while (m --> 0)
{
int l, r, k;
cin >> l >> r >> k;
changes.emplace_back(l, k);
changes.emplace_back(r+1, -k);
}
sort(changes.begin(), changes.end());
array<int, 4> status = {};
int answer = 0;
constexpr int NOT_OK = -1;
int ok_since = NOT_OK;
for (const auto &change : changes)
{
if (ok_since != NOT_OK)
{
answer += change.first - ok_since;
}
const int step = (change.second > 0 ? 1 : -1);
const int color = abs(change.second);
status[color] += step;
const bool ok = (status[1] > 0 && status[2] > 0 && status[3] == 0);
ok_since = (ok ? change.first : NOT_OK);
}
cout << answer << '\n';
}
int main()
{
#ifndef CONTEST_WORKSPACE
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
#endif
#ifdef ENDLESS_TESTS
while(!(cin >> std::ws).eof())
test();
#else
int T = 0;
#ifdef MULTIPLE_TESTS
cin >> T;
#else
T = 1;
#endif
while (T --> 0)
test();
#endif
return 0;
} |
822e0d1bc0d70cc69cc78563376f70b2f49a9959 | 0dd13f79b99a6689fd3dde921d259273d0e9cc6e | /tabview.cpp | 371888cc74d29862cfde31fe35edb42334580936 | [] | no_license | ThomasWzorek/MaxNet | 221054820c21fd2d063f583fa93887149c3f7d9b | 2af1ce457d219cc8ab3f085924aff2cb59d8e322 | refs/heads/master | 2020-04-07T18:57:40.615132 | 2012-05-09T13:01:05 | 2012-05-09T13:01:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,161 | cpp | tabview.cpp | #include "tabview.h"
#include "ui_tabview.h"
#include <QtWebKit/QWebView>
#include <cstdio>
TabView::TabView(QWidget *parent) :
QWidget(parent),
ui(new Ui::TabView)
{
ui->setupUi(this);
Title = "This is my title";
ui->TabMainView->load(QUrl(HOMEPAGE));
ui->TabMainView->show();
Title = ui->TabMainView->title();
}
TabView::~TabView()
{
delete ui;
}
QString TabView::GetTitle()
{
return Title;
}
void TabView::SendSignal(FLAGS flags)
{
if(flags.refresh == true){
printf("Refreshing is buggy. Do not use!\n");
} else if(flags.Stop == true){
ui->TabMainView->stop();
} else if(flags.GoHome == true){
ui->Address_Bar->setText(HOMEPAGE);
ui->TabMainView->load(QUrl(HOMEPAGE));
}
}
void TabView::on_BackButton_clicked()
{
ui->TabMainView->back();
ui->Address_Bar->setText(ui->TabMainView->url().toString());
}
void TabView::on_Forward_Button_clicked()
{
ui->TabMainView->forward();
ui->Address_Bar->setText(ui->TabMainView->url().toString());
}
void TabView::on_Go_Button_clicked()
{
if(ui->Address_Bar->text().contains("http://")){
ui->TabMainView->load(QUrl(ui->Address_Bar->text()));
ui->Address_Bar->setText(ui->TabMainView->url().toString());
} else if(ui->Address_Bar->text().contains("https://")) {
ui->TabMainView->load(QUrl(ui->Address_Bar->text()));
ui->Address_Bar->setText(ui->TabMainView->url().toString());
} else if(ui->Address_Bar->text().contains("ftp://")){
ui->TabMainView->load(QUrl(ui->Address_Bar->text()));
ui->Address_Bar->setText(ui->TabMainView->url().toString());
} else if(ui->Address_Bar->text().contains("file://")){
ui->TabMainView->load(QUrl(ui->Address_Bar->text()));
ui->Address_Bar->setText(ui->TabMainView->url().toString());
} else {
ui->TabMainView->load(QUrl(QString("http://") +
ui->Address_Bar->text()));
ui->Address_Bar->setText(ui->TabMainView->url().toString());
}
}
void TabView::on_TabMainView_urlChanged(const QUrl &arg1)
{
ui->Address_Bar->setText(arg1.toString());
}
|
11f81f6a3f783770f7e5c8bb987069bf30108806 | 9eb9796d34f587b02672d98a9e9dbda1cd7af3e6 | /CS/2/DataStructure/04stack/02linkStack/linkStack_test.h | 7248ee10ce443046312828a3bfbd68d49d7d9b06 | [] | no_license | eternity6666/university | ef0b902158917d7c70287eaa1207ee28d9d98c20 | 953188832fd174270c43c584fc8c4beda297d95d | refs/heads/master | 2021-07-15T04:16:50.128943 | 2020-05-15T02:34:17 | 2020-05-15T02:34:17 | 141,017,995 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 972 | h | linkStack_test.h | #ifndef LINKSTACK_TEST_H
#define LINKSTACK_TEST_H
#include "linkStack.h"
template <typename elemtype>
void display(linkStack<elemtype> a)
{
int n = a.getLength();
if(n)
{
// cout << 1 << endl;
for(int i = 0; i < n; i++)
{
elemtype e;
a.pop(e);
cout.width(5);
cout.fill(' ');
cout << e;
if(i + 1 != n)
cout << "→";
}
cout << endl;
cout << " ↑" << endl;
cout << " top" << endl;
}
else
return ;
}
template <typename elemtype>
void getByRand(linkStack<elemtype> &a, int display = 0)
{
a.clear();
int n = rand() % 8;
int array[10];
for(int i = 0; i < n; i++)
{
array[i] = rand() % 100;
cout.width(5);
cout.fill(' ');
if(display)
cout << array[i];
a.push(array[i]);
}
if(display)
cout << endl;
}
#endif
|
edc0a98cb3732691a33aeae32dd29743fd52c22b | e25d29a4230d298dff22f76412fa30b34fad98bd | /Language programm/labFour/codeFour.cpp | ee9d66d553acb0af3cc7bed308afcfc206a4c10f | [] | no_license | Zerp2808/program-language | 4becab08c4a2bbd746b4ad10515eaada652ab721 | 5b73f486e73b237f4abd76a8547f7615dbf4e06f | refs/heads/master | 2020-06-15T20:12:41.166728 | 2019-07-12T06:52:49 | 2019-07-12T06:52:49 | 195,382,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,660 | cpp | codeFour.cpp | #include <iostream>
#include <string>
using namespace std;
class String
{
char * value;
int len;
public:
String():value(new char[1] {}),len(0) {}; // конструктор по умолчанию
String(const String& s);
// конструктор копирования
String(const char * s);
// конструктор инициализации Си-строкой
~String();
String(int size):value(new char[size+1]), len(size){};
String operator-() const;
String& operator=(const String& other);
friend ostream& operator<<(ostream& o, const String & s);
friend istream& operator>>(istream& o, String & s);
// деструктор
};
String String::operator-() const
{
String ret(len);
//временный объект с буфером нужного размера
for (int i=0; i<len; i++) {
//копируем в обратном порядке
ret.value[i] = value[len-i-1];
}
ret.value[len] = 0;
//нулевое окончание строки
return ret;
//возвращаем временный объект
}
String& String::operator=(const String& other)
{
if (this != &other) {
// игнорировать присваивания вида a = a
delete[] value;
// удаляем старое значение
len=other.len;
// длина строки
value = new char[len+1];
// выделить память под новый буфер
for (int i=0; i<=len; i++) { // скопировать строку в новый буфер
value[i]=other.value[i];
}
}
return *this;
}
ostream& operator<<(ostream& outputStream, const String & s)
{
return outputStream << s.value;
}
String::~String()
{
delete[] value;
}
String::String(const String& s)
{
len=s.len;
value = new char[len+1];
for (int i=0; i<=len; i++)
value[i]=s.value[i];
}
String::String(const char *s)
{
int i=0;
len=0;
while(s[i]!='\0') {
len++;
i++;
}
value = new char[len];
for(int i=0; i<len; i++) {
value[i]=s[i];
}
value[len]=0;
}
istream& operator>>(istream& inputStream, String & s)
{
int dl=0;
char temp[90];
inputStream >> s.value;
for(int i=0; s.value[i]!=0; i++) {
temp[i]=s.value[i];
dl=dl+1;
}
delete[] s.value;
s.len=dl;
s.value=new char[s.len+1];
for(int i=0; i<s.len; i++) {
s.value[i]=temp[i];
}
s.value[s.len]=0;
}
int main(int argc, char **argv)
{
String s;
cin>>s;
String s1("hello");
String s2(s1);
String s3=-s;
cout<<s2<<" "<<-s1<<" "<<s<<" "<<s3<<endl;
return 0;
}
|
dbc29bba9858ccb792a0d156c040063fa16f43e8 | e59127606facf962d559e869ccb65be488cb93e8 | /ProjectData/GameSources/Player.cpp | 47b03c595562e778879384a35a4261a24ca27361 | [] | no_license | OkabeTatsuya/TGS_TeamJ_WaveProject | 084f8c1a3bb713dc7421af7f47300d9c2e9462a9 | 8e7b51403255fff4d854e917542657bc6a140cf0 | refs/heads/master | 2021-01-26T10:48:27.596231 | 2020-06-24T23:02:26 | 2020-06-24T23:02:26 | 243,408,631 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 36,697 | cpp | Player.cpp | /*!
@file Player.cpp
@brief プレイヤーなど実体
*/
#include "stdafx.h"
#include "Project.h"
namespace basecross {
Player::Player(const shared_ptr<Stage>& stage,
Vec3& rotation,
Vec3& scale,
Vec3& position,
int& layer) :
ObjectBase(stage,
rotation, scale, position, layer
)
{
m_jumpActionDif = 0.8f;
m_isFirstJump = false;
m_currentFlightTime = 0;
m_maxFlightTime = 0.5f;
m_currentAnimationKeyCount = 0;
m_isWaveTouch = false;
m_jumpActionTime = 0.5f;
m_highJumpMoveY = 7.5f;
m_midJumpMoveY = 5.5f;
m_lowJumpMoveY = 4.0f;
m_maxSpeed = 6.0f;
m_minSpeed = 3.0f;
GameManager::GetInstance().SetGameSpeed((m_maxSpeed - m_minSpeed) / 3 + m_minSpeed);
m_jumpGradeSpeedMagnification = 1.5;
m_jumpGradeScoreMagnification = 2.0f;
m_jumpGradeTime = 0.0f;
m_jumpGradeTimeJudge = 0.8f;
m_isTopJumpAction = false;
m_isBottomJumpAction = false;
m_isLeftJumpAction = false;
m_isRightJumpAction = false;
m_isJump = false;
m_isJumpAction = false;
m_rot = m_rotation;
m_currentJumpActionTime = 0;
m_jumpActionLimitTime = 0.3;
m_upSpeedValue = 0.5f;
m_jumpMissDownSpeedValue = 0.5f;
m_groundWaveDownSpeedValue = 0.1f;
m_currentLandingTime = 0;
m_maxLandingTime = 0.2;
m_isLanding = false;
m_currentInvincibleTime = 0;
m_invincibleFlashSpeed = 0.25f;
m_maxInvincibleTime = 1.0f;
m_isInvincible = false;
m_maxSpeedScoreMagnification = 1.5f;
m_currentSpeedScoreMagnification = 0;
m_comboMagnification = 0.1f;
m_combo = 0;
m_greatJumpMagnification = 1.5;
m_maxAnimationTime = 0.1f;
m_currentAnimationTime = 0.0f;
m_isWaitingAnimation = true;
m_isJumpActionZAnimation = false;
m_isFinishJumpFinishAnimation = false;
m_isFinishJumpStartAnimation = false;
m_isJumpFinishAnimation = false;
m_isJumpStartAnimation = false;
m_currentSpecialJumpCount = 0;
m_specialJumpCount = 3;
m_specialJumpActionMaxCount = 2;
m_knockBackValue = 0.5f;
m_playerVoiceStr = { L"Voice2_1.wav", L"Voice2_3.wav", L"Voice2_4.wav"};
m_playerSpecialVoiceStr = { L"Voice2_6.wav", L"Voice2_10.wav"};
}
void Player::OnCreate() {
DrawingImage(L"Wait_1.png");
InitAnimation();
auto transPtr = AddComponent<Transform>();
transPtr->SetPosition(m_position);
transPtr->SetScale(m_scale);
transPtr->SetRotation(m_rotation);
PsBoxParam param(transPtr->GetWorldMatrix(), 1.0f, false, PsMotionType::MotionTypeActive);
AddComponent<RigidbodyBox>(param);
auto colPtr = AddComponent<CollisionObb>();
colPtr->SetMakedSize(Vec3(1.4f, 1.0f, 1.0f));
m_scoreUpUI = GetStage()->AddGameObject<ScoreUIPanel>(Vec3(0.0f), Vec3(30.0f, 20.0f, 1.0f), Vec2(0.0f), float(7.0f), L"Number.png", 4, true);
GameManager::GetInstance().SetScoreUpUIPanel(m_scoreUpUI);
AddTag(L"Player");
m_effectObj = GetStage()->AddGameObject<EffectObject>();
m_effectObj->GetComponent<Transform>()->SetPosition(Vec3(0.0f));
m_judgJumpUI = GetStage()->AddGameObject<JudgJumpUI>(Vec3(0.0f), Vec3(256.0f, 128.0f, 1.0f), Vec2(0.0f), float(7.0f), L"Perfect.png");
}
void Player::InitAnimation() {
wstring wait = L"Wait_";
wstring jumpX = L"JumpX_";
wstring jumpY = L"JumpY_";
wstring jumpZ = L"JumpZ";
wstring jumpStart = L"JumpStart_";
wstring jumpFinish = L"JumpFinish_";
wstring number;
wstring png = L".png";
for (int i = 0; i < m_waitingAnimationKeyCount; i++) {
number = to_wstring(i + 1);
m_waitingAnimationKeys[i] = wait + number + png;
}
for (int i = 0; i < m_jumpActionAnimationZKeyCount; i++) {
number = to_wstring(i + 1);
m_jumpActionAnimationZKeys[i] = jumpZ + png;
}
for (int i = 0; i < m_jumpStartAnimationKeyCount; i++) {
number = to_wstring(i + 4);
m_jumpStartAnimationKeys[i] = jumpStart + number + png;
}
for (int i = 0; i < m_jumpFinishAnimationKeyCount; i++) {
number = to_wstring(i + 1);
m_jumpFinishAnimationKeys[i] = jumpFinish + number + png;
}
for (int i = 0; i < m_jumpActionAnimationXKeyCount; i++) {
number = to_wstring(i + 1);
m_jumpActionAnimationXKeys[i] = jumpX + number + png;
}
for (int i = 0; i < m_jumpActionAnimationYKeyCount; i++) {
number = to_wstring(i + 1);
m_jumpActionAnimationYKeys[i] = jumpY + number + png;
}
}
void Player::OnUpdate() {
InvincibleAnimation();
WaitingAnimation();
JumpActionXAnimation();
JumpActionYAnimation();
JumpActionZAnimation();
JumpStartAnimation();
JumpFinishAnimation();
JudgeJumpAction();
SpecialJumpAction();
FlightAction();
Invincible();
SpeedScoreMagnification();
GravityControl();
KnockBack();
m_scoreUpUI->AdjustPosition(GetComponent<Transform>()->GetPosition());
m_judgJumpUI->SetingPos(GetComponent<Transform>()->GetPosition());
FollowEffect();
SpecialCheck();
PushAButton();
}
void Player::OnUpdate2() {
JumpAction();
}
//滞空アニメーション
void Player::JumpActionXAnimation() {
if (m_isJumpActionXAnimation) {
JumpAcionEffect(EN_EffectName::en_GoodEffect, L"se_maoudamashii_onepoint16.wav");
m_animeTimeCounter += App::GetApp()->GetElapsedTime();
m_currentAnimationTime += App::GetApp()->GetElapsedTime();
if (m_currentAnimationTime >= m_maxAnimationTime) {
DrawingImage(m_jumpActionAnimationXKeys[m_currentAnimationKeyCount]);
m_currentAnimationKeyCount++;
if (m_currentAnimationKeyCount >= m_jumpActionAnimationXKeyCount) {
m_animeTimeCounter = 0;
m_currentAnimationKeyCount = 0;
m_isJumpActionXAnimation = false;
if (m_isSpecialJumpAction) {
m_currentSpecialJumpActionCount++;
}
}
m_currentAnimationTime = 0;
}
}
}
//ジャンプアクションアニメーション(Y軸)
void Player::JumpActionYAnimation() {
if (m_isJumpActionYAnimation) {
JumpAcionEffect(EN_EffectName::en_GoodEffect, L"se_maoudamashii_onepoint16.wav");
m_animeTimeCounter += App::GetApp()->GetElapsedTime();
m_currentAnimationTime += App::GetApp()->GetElapsedTime();
if (m_currentAnimationTime >= m_maxAnimationTime) {
DrawingImage(m_jumpActionAnimationYKeys[m_currentAnimationKeyCount]);
m_currentAnimationKeyCount++;
if (m_currentAnimationKeyCount >= m_jumpActionAnimationYKeyCount) {
m_isJumpActionYAnimation = false;
m_animeTimeCounter = 0;
m_currentAnimationKeyCount = 0;
GameManager::GetInstance().AddActionScore(m_currentSpeedScoreMagnification, m_combo * m_comboMagnification, JumpActionType::en_ActionY);
if (m_isSpecialJumpAction) {
m_currentSpecialJumpActionCount++;
}
}
m_currentAnimationTime = 0;
}
}
}
//ジャンプアクションアニメーション(Z軸)
void Player::JumpActionZAnimation() {
if (m_isJumpActionZAnimation) {
JumpAcionEffect(EN_EffectName::en_GoodEffect, L"se_maoudamashii_onepoint16.wav");
m_animeTimeCounter += App::GetApp()->GetElapsedTime();
m_currentAnimationTime += App::GetApp()->GetElapsedTime();
if (m_isInvincible) {
m_isJumpStartAnimation = false;
m_isJumpFinishAnimation = true;
m_isWaitingAnimation = false;
m_isJumpActionXAnimation = false;
m_isJumpActionYAnimation = false;
m_isJumpActionZAnimation = false;
}
if (m_currentAnimationTime >= m_maxAnimationTime) {
DrawingImage(m_jumpActionAnimationZKeys[m_currentAnimationKeyCount]);
m_currentAnimationKeyCount++;
if (m_currentAnimationKeyCount >= m_jumpActionAnimationZKeyCount) {
m_isJumpActionZAnimation = false;
m_currentAnimationKeyCount = 0;
}
m_currentAnimationTime = 0;
}
}
}
//待機アニメーション
void Player::WaitingAnimation() {
if (m_isWaitingAnimation) {
m_currentAnimationTime += App::GetApp()->GetElapsedTime();
if (m_currentAnimationKeyCount >= m_waitingAnimationKeyCount) {
m_currentAnimationKeyCount = 0;
}
if (m_currentAnimationTime >= m_maxAnimationTime) {
DrawingImage(m_waitingAnimationKeys[m_currentAnimationKeyCount]);
m_currentAnimationKeyCount++;
m_currentAnimationTime = 0;
}
}
}
//踏切アニメーション
void Player::JumpStartAnimation() {
float jumpStartAnimationFrameTime = 0.03f;
if (m_isJumpStartAnimation) {
m_currentAnimationTime += App::GetApp()->GetElapsedTime();
if (m_currentAnimationKeyCount >= m_jumpStartAnimationKeyCount) {
m_isJumpStartAnimation = false;
DrawingImage(m_jumpStartAnimationKeys[m_currentAnimationKeyCount]);
m_currentAnimationKeyCount = 0;
}
if (m_currentAnimationTime >= jumpStartAnimationFrameTime) {
DrawingImage(m_jumpStartAnimationKeys[m_currentAnimationKeyCount]);
m_currentAnimationKeyCount++;
m_currentAnimationTime = 0;
}
}
}
//着地アニメーション
void Player::JumpFinishAnimation() {
float jumpFinishAnimationFrameTime = 0.05f;
if (m_isJumpFinishAnimation) {
m_currentAnimationTime += App::GetApp()->GetElapsedTime();
if (m_currentAnimationKeyCount >= m_jumpFinishAnimationKeyCount) {
m_isFinishJumpStartAnimation = false;
m_isFinishJumpFinishAnimation = true;
m_isJumpStartAnimation = false;
m_isJumpFinishAnimation = false;
m_isWaitingAnimation = true;
m_isJumpActionXAnimation = false;
m_isJumpActionYAnimation = false;
m_isJumpActionZAnimation = false;
m_currentAnimationKeyCount = 0;
}
if (m_currentAnimationTime >= jumpFinishAnimationFrameTime) {
DrawingImage(m_jumpFinishAnimationKeys[m_currentAnimationKeyCount]);
m_currentAnimationKeyCount++;
m_currentAnimationTime = 0;
}
}
}
//無敵アニメーション
void Player::InvincibleAnimation() {
if (m_isInvincible) {
auto drawPtr = GetComponent<PCTStaticDraw>();
auto color = drawPtr->GetDiffuse();
float flashSpeed = m_currentInvincibleTime / m_invincibleFlashSpeed;
if (flashSpeed <= 0.3f || flashSpeed>=XM_PI) {
flashSpeed = 0.3f;
}
color.w = sinf(flashSpeed);
drawPtr->SetDiffuse(color);
}
else {
auto drawPtr = GetComponent<PCTStaticDraw>();
auto color = drawPtr->GetDiffuse();
color.w = 1.0f;
drawPtr->SetDiffuse(color);
}
}
//重力制御
void Player::GravityControl()
{
if (GameManager::GetInstance().GetIsSpecialTime() && GetComponent<RigidbodyBox>()->GetLinearVelocity().y<0 && !m_isTouchSea && m_isBigWaveJump){
GetComponent<RigidbodyBox>()->SetAutoGravity(false);
auto gravity = GetComponent<RigidbodyBox>()->GetLinearVelocity();
gravity.y -= 3.0f * App::GetApp()->GetElapsedTime();
GetComponent<RigidbodyBox>()->SetLinearVelocity(gravity);
}
}
//スピード依存のスコア倍率計算処理
void Player::SpeedScoreMagnification() {
auto diff = m_maxSpeed - m_minSpeed;
auto currentDiff = GameManager::GetInstance().GetGameSpeed() - m_minSpeed;
auto currentSpeedPersentage = currentDiff / diff;
if (diff != currentDiff)
m_currentSpeedScoreMagnification = 1.0f + 0.5f*currentSpeedPersentage;
else
m_currentSpeedScoreMagnification = 1.0f;
}
//スピードの上限下限処理
void Player::AdjustSpeed() {
auto &gm = GameManager::GetInstance();
if (gm.GetGameSpeed() > m_maxSpeed) {
gm.SetGameSpeed(m_maxSpeed);
}
if (gm.GetGameSpeed() < m_minSpeed) {
gm.SetGameSpeed(m_minSpeed);
}
}
//スピードアップ処理
void Player::SpeedUp(float upSpeedValue) {
auto &gm = GameManager::GetInstance();
auto currentSpeed = gm.GetGameSpeed();
currentSpeed += upSpeedValue;
gm.SetGameSpeed(currentSpeed);
AdjustSpeed();
}
//ジャンプミスのスピードダウン処理
void Player::JumpMissSpeedDown() {
auto &gm = GameManager::GetInstance();
auto currentSpeed = gm.GetGameSpeed();
currentSpeed -= m_jumpMissDownSpeedValue;
gm.SetGameSpeed(currentSpeed);
AdjustSpeed();
}
//継続スピードダウン処理
void Player::GroundWaveSpeedDown() {
if (m_isLanding) {
m_currentLandingTime += App::GetApp()->GetElapsedTime();
if (m_currentLandingTime >= m_maxLandingTime) {
m_currentLandingTime = 0;
m_isLanding = false;
}
}
else {
auto &gm = GameManager::GetInstance();
auto currentSpeed = gm.GetGameSpeed();
currentSpeed -= m_groundWaveDownSpeedValue * App::GetApp()->GetElapsedTime();
gm.SetGameSpeed(currentSpeed);
AdjustSpeed();
}
}
//スペシャルジャンプアクション
void Player::SpecialJumpAction() {
if (m_isSpecialJumpAction&&m_currentSpecialJumpActionCount<m_specialJumpActionMaxCount) {
switch (0) {
case 0:
m_isJumpAction = true;
break;
case 1:
m_isFlightAction = true;
break;
case 2:
m_isJumpActionYAnimation = true;
break;
default:
break;
}
}
}
//ジャンプアクションの入力判定
void Player::JudgeJumpAction() {
auto controller = App::GetApp()->GetInputDevice().GetControlerVec()[0];
if (m_isJump && Vec2(controller.fThumbLX, controller.fThumbLY).length() >= 1.0f) {
m_currentJumpActionTime += App::GetApp()->GetElapsedTime();
}
if (m_isJump && !m_isJumpAction && m_currentJumpActionTime <= m_jumpActionLimitTime) {
if (controller.fThumbLY >= m_jumpActionDif) {
m_isTopJumpAction = true;
}
if (controller.fThumbLY <= -m_jumpActionDif) {
m_isBottomJumpAction = true;
}
if (controller.fThumbLX <= -m_jumpActionDif) {
m_isLeftJumpAction = true;
}
if (controller.fThumbLX >= m_jumpActionDif) {
m_isRightJumpAction = true;
}
}
else {
m_isTopJumpAction = false;
m_isBottomJumpAction = false;
m_isLeftJumpAction = false;
m_isRightJumpAction = false;
m_currentJumpActionTime = 0;
}
if (m_isTopJumpAction && m_isBottomJumpAction && m_isLeftJumpAction && m_isRightJumpAction && !m_isJumpAction) {
m_isTopJumpAction = false;
m_isBottomJumpAction = false;
m_isLeftJumpAction = false;
m_isRightJumpAction = false;
m_isJumpAction = true;
m_currentAnimationKeyCount = 0;
}
if (m_isJump && m_isLeftJumpAction&&m_isRightJumpAction && !m_isTopJumpAction && !m_isBottomJumpAction) {
m_isLeftJumpAction = false;
m_isRightJumpAction = false;
m_isJumpStartAnimation = false;
m_isJumpFinishAnimation = false;
m_isWaitingAnimation = false;
m_isJumpActionXAnimation = false;
m_isJumpActionYAnimation = true;
m_isJumpActionZAnimation = false;
}
}
//滞空アクション処理
void Player::FlightAction() {
auto controller = App::GetApp()->GetInputDevice().GetControlerVec()[0];
if (m_isJump && controller.wPressedButtons & XINPUT_GAMEPAD_LEFT_THUMB && m_isEnableFlightAction && GetComponent<RigidbodyBox>()->GetLinearVelocity().y <=0) {
m_isFlightAction = true;
GetComponent<RigidbodyBox>()->SetAutoGravity(false);
}
if (m_isFlightAction && !m_isTouchSea) {
m_isJumpStartAnimation = false;
m_isJumpFinishAnimation = false;
m_isWaitingAnimation = false;
m_isJumpActionXAnimation = true;
m_isJumpActionYAnimation = false;
m_isJumpActionZAnimation = false;
m_currentFlightTime += App::GetApp()->GetElapsedTime();
GetComponent<RigidbodyBox>()->SetLinearVelocity(Vec3(0.0f,-0.2f,0.0f));
if (m_currentFlightTime >= m_maxFlightTime) {
m_isFlightAction = false;
m_isEnableFlightAction = false;
m_currentFlightTime = 0.0f;
GameManager::GetInstance().AddActionScore(m_currentSpeedScoreMagnification, m_combo * m_comboMagnification, JumpActionType::en_ActionX);
GetComponent<RigidbodyBox>()->SetAutoGravity(true);
}
}
}
//ジャンプアクション処理
void Player::JumpAction() {
if (m_isSpecialJumpAction) {
if (m_isJumpAction && GetComponent<RigidbodyBox>()->GetLinearVelocity().y <= 0) {
if (!m_isInvincible) {
m_isJumpStartAnimation = false;
m_isJumpFinishAnimation = false;
m_isWaitingAnimation = false;
m_isJumpActionXAnimation = false;
m_isJumpActionYAnimation = false;
m_isJumpActionZAnimation = true;
}
m_rot.z += XM_2PI * App::GetApp()->GetElapsedTime() / m_jumpActionTime;
GetComponent<Transform>()->SetRotation(m_rot);
if (m_rot.z >= XM_2PI) {
m_rot.z = 0;
m_isJumpAction = false;
m_isInvincible = false;
m_animeTimeCounter = 0;
GameManager::GetInstance().AddActionScore(m_currentSpeedScoreMagnification, m_combo * m_comboMagnification, JumpActionType::en_ActionZ);
GameManager::GetInstance().SetIsSpecialJump(true);
}
m_currentSpecialJumpActionCount++;
}
}
else {
if (m_isJumpAction) {
if (!m_isInvincible) {
m_isJumpStartAnimation = false;
m_isJumpFinishAnimation = false;
m_isWaitingAnimation = false;
m_isJumpActionXAnimation = false;
m_isJumpActionYAnimation = false;
m_isJumpActionZAnimation = true;
}
m_rot.z += XM_2PI * App::GetApp()->GetElapsedTime() / m_jumpActionTime;
GetComponent<Transform>()->SetRotation(m_rot);
if (m_rot.z >= XM_2PI) {
m_rot.z = 0;
m_isJumpAction = false;
m_isInvincible = false;
m_animeTimeCounter = 0;
GameManager::GetInstance().AddActionScore(m_currentSpeedScoreMagnification, m_combo * m_comboMagnification, JumpActionType::en_ActionZ);
}
}
}
}
//大波のジャンプ処理
void Player::BigWaveJump() {
bool isGreatJump = false;
auto controller = App::GetApp()->GetInputDevice().GetControlerVec()[0];
auto &gm = GameManager::GetInstance();
m_currentJumpGradeTime += App::GetApp()->GetElapsedTime();
if (m_jumpGradeTime <= m_currentJumpGradeTime) {
isGreatJump = true;
}
if (gm.GetIsSpecialTime() && controller.wPressedButtons & XINPUT_GAMEPAD_A && !m_isJump) {
m_isBigWaveJump = true;
m_isTouchSea = false;
m_isWaveTouch = false;
m_currentSpecialJumpCount++;
if (m_currentSpecialJumpCount > m_specialJumpCount) {
m_isSpecialJump = false;
m_managerniaruyatu = false;
m_currentSpecialJumpCount = 0;
}
m_isJumpStartAnimation = true;
m_isJumpFinishAnimation = false;
m_isWaitingAnimation = false;
m_isJumpActionXAnimation = false;
m_isJumpActionYAnimation = false;
m_isJumpActionZAnimation = false;
m_currentAnimationKeyCount = 0;
if (isGreatJump) {
m_knockBackMagnification = 4.0f;
InitKnockBack(m_knockBackMagnification);
SpeedUp(m_upSpeedValue * m_jumpGradeSpeedMagnification);
HighJump(m_greatJumpMagnification);
JumpEffect(EN_EffectName::en_GoodEffect, L"se_maoudamashii_onepoint16.wav");
gm.AddJumpScore(m_currentSpeedScoreMagnification, m_combo*m_comboMagnification, true);
Vec3 pos = GetComponent<Transform>()->GetPosition();
m_judgJumpUI->VisibleUI(L"Perfect.png", pos);
}
else {
SpeedUp(m_upSpeedValue);
HighJump(1.0f);
JumpEffect(EN_EffectName::en_GoodEffect, L"se_maoudamashii_onepoint17.wav");
gm.AddJumpScore(m_currentSpeedScoreMagnification, m_combo*m_comboMagnification, false);
Vec3 pos = GetComponent<Transform>()->GetPosition();
m_judgJumpUI->VisibleUI(L"Good.png", pos);
}
m_currentJumpGradeTime = 0;
m_combo++;
gm.SetIsJumpBigWave(true);
}
}
//中波のジャンプ処理
void Player::MidWaveJump() {
bool isGreatJump = false;
auto controller = App::GetApp()->GetInputDevice().GetControlerVec()[0];
auto &gm = GameManager::GetInstance();
m_currentJumpGradeTime += App::GetApp()->GetElapsedTime();
if (m_jumpGradeTime <= m_currentJumpGradeTime) {
isGreatJump = true;
}
if (controller.wPressedButtons & XINPUT_GAMEPAD_A && !m_isJump) {
m_isTouchSea = false;
m_isWaveTouch = false;
m_isJumpStartAnimation = true;
m_isJumpFinishAnimation = false;
m_isWaitingAnimation = false;
m_isJumpActionXAnimation = false;
m_isJumpActionYAnimation = false;
m_isJumpActionZAnimation = false;
m_currentAnimationKeyCount = 0;
if (isGreatJump) {
m_knockBackMagnification = 2.0f;
InitKnockBack(m_knockBackMagnification);
SpeedUp(m_upSpeedValue * m_jumpGradeSpeedMagnification);
MidJump(m_greatJumpMagnification);
JumpEffect(EN_EffectName::en_GoodEffect, L"se_maoudamashii_onepoint16.wav");
gm.AddJumpScore(m_currentSpeedScoreMagnification, m_combo*m_comboMagnification, true);
Vec3 pos = GetComponent<Transform>()->GetPosition();
m_judgJumpUI->VisibleUI(L"Perfect.png", pos);
}
else {
SpeedUp(m_upSpeedValue);
MidJump(1.0f);
JumpEffect(EN_EffectName::en_GoodEffect, L"se_maoudamashii_onepoint17.wav");
gm.AddJumpScore(m_currentSpeedScoreMagnification, m_combo*m_comboMagnification, false);
Vec3 pos = GetComponent<Transform>()->GetPosition();
m_judgJumpUI->VisibleUI(L"Good.png", pos);
}
m_currentJumpGradeTime = 0;
m_combo++;
}
}
//小波のジャンプ処理
void Player::SmallWaveJump() {
bool isGreatJump = false;
auto controller = App::GetApp()->GetInputDevice().GetControlerVec()[0];
auto &gm = GameManager::GetInstance();
m_currentJumpGradeTime += App::GetApp()->GetElapsedTime();
if (m_jumpGradeTime <= m_currentJumpGradeTime) {
isGreatJump = true;
}
if (controller.wPressedButtons & XINPUT_GAMEPAD_A && !m_isJump) {
m_isTouchSea = false;
m_isWaveTouch = false;
m_isJumpStartAnimation = true;
m_isJumpFinishAnimation = false;
m_isWaitingAnimation = false;
m_isJumpActionXAnimation = false;
m_isJumpActionYAnimation = false;
m_isJumpActionZAnimation = false;
m_currentAnimationKeyCount = 0;
if (isGreatJump) {
m_knockBackMagnification = 1.0f;
InitKnockBack(m_knockBackMagnification);
SpeedUp(m_upSpeedValue * m_jumpGradeSpeedMagnification);
LowJump(m_greatJumpMagnification);
JumpEffect(EN_EffectName::en_GoodEffect, L"se_maoudamashii_onepoint16.wav");
gm.AddJumpScore(m_currentSpeedScoreMagnification, m_combo*m_comboMagnification, true);
Vec3 pos = GetComponent<Transform>()->GetPosition();
m_judgJumpUI->VisibleUI(L"Perfect.png", pos);
}
else {
SpeedUp(m_upSpeedValue);
LowJump(1.0f);
JumpEffect(EN_EffectName::en_GoodEffect, L"se_maoudamashii_onepoint17.wav");
gm.AddJumpScore(m_currentSpeedScoreMagnification, m_combo*m_comboMagnification, false);
Vec3 pos = GetComponent<Transform>()->GetPosition();
m_judgJumpUI->VisibleUI(L"Good.png", pos);
}
m_currentJumpGradeTime = 0;
m_combo++;
}
}
//ハイジャンプ
void Player::HighJump(float jumpMag) {
m_isJump = true;
GetComponent<RigidbodyBox>()->SetAutoGravity(true);
GetComponent<RigidbodyBox>()->SetLinearVelocity(Vec3(0, m_highJumpMoveY * jumpMag, 0));
}
//ミドルジャンプ
void Player::MidJump(float jumpMag) {
m_isJump = true;
GetComponent<RigidbodyBox>()->SetAutoGravity(true);
GetComponent<RigidbodyBox>()->SetLinearVelocity(Vec3(0, m_midJumpMoveY * jumpMag, 0));
}
//ロージャンプ
void Player::LowJump(float jumpMag) {
m_isJump = true;
GetComponent<RigidbodyBox>()->SetAutoGravity(true);
GetComponent<RigidbodyBox>()->SetLinearVelocity(Vec3(0, m_lowJumpMoveY * jumpMag, 0));
}
//無敵
void Player::Invincible() {
if (m_isInvincible) {
m_currentInvincibleTime += App::GetApp()->GetElapsedTime();
if (m_currentInvincibleTime >= m_maxInvincibleTime) {
m_currentInvincibleTime = 0;
m_isInvincible = false;
}
}
else {
m_currentInvincibleTime = 0;
}
}
//ノックバック処理初期化
void Player::InitKnockBack(float mag) {
if (m_isTouchSea) {
m_knockBackPos = GetComponent<Transform>()->GetPosition().x - mag * m_knockBackValue;
m_isKnockBack = true;
}
else {
m_knockBackPos = GetComponent<Transform>()->GetPosition().x + mag * m_knockBackValue;
if (m_knockBackPos >= -2.0f)
m_knockBackPos = -2.0f;
else
m_isKnockUp = true;
}
}
//ノックバック処理
void Player::KnockBack() {
if (m_isKnockBack) {
auto linerVel = GetComponent<RigidbodyBox>()->GetLinearVelocity();
linerVel.x = -3.0f;
GetComponent<RigidbodyBox>()->SetLinearVelocity(linerVel);
if (GetComponent<Transform>()->GetPosition().x <= m_knockBackPos) {
m_isKnockBack = false;
}
}
if (m_isKnockUp && m_isTouchSea) {
auto linerVel = GetComponent<RigidbodyBox>()->GetLinearVelocity();
linerVel.x = +1.0f;
GetComponent<RigidbodyBox>()->SetLinearVelocity(linerVel);
if (GetComponent<Transform>()->GetPosition().x >= m_knockBackPos) {
linerVel.x = 0.0f;
GetComponent<RigidbodyBox>()->SetLinearVelocity(linerVel);
m_isKnockUp = false;
}
}
}
void Player::SpecialCheck() {
if (m_isTouchSea) {
auto& gameManager = GameManager::GetInstance();
gameManager.SpecialCheck();
if (gameManager.GetIsSpecialTime()) {
gameManager.SetIsSpecialJump(false);
}
if (gameManager.GetIsJumpBigWave()) {
gameManager.SetIsSpecialTime(false);
gameManager.SetIsJumpBigWave(false);
}
}
}
//効果音
void Player::ActiveSE(wstring se) {
float pitch = m_combo == 0.0f ? 1.0f : m_combo / 10.0f + 1.0f;
auto XAPtr = App::GetApp()->GetXAudio2Manager();
m_SE = XAPtr->MyStart(se, 0, 0.5f, pitch);
}
void Player::PlayVoiceSE(float vol) {
auto XAPtr = App::GetApp()->GetXAudio2Manager();
auto &gameManager = GameManager::GetInstance();
std::random_device rando;
std::mt19937 mt(rando());
int voiceItr = mt() % m_playerSpecialVoiceStr.size();
int spVoiceItr = mt() % m_playerVoiceStr.size();
bool JumpAcionFlag = (m_isJumpActionXAnimation || m_isJumpActionYAnimation || m_isJumpActionZAnimation);
if (!JumpAcionFlag) {
if (gameManager.GetIsSpecialTime()) {
m_voiceSE = XAPtr->Start(m_playerSpecialVoiceStr[voiceItr], 0, vol);
}
else
{
m_voiceSE = XAPtr->Start(m_playerVoiceStr[spVoiceItr], 0, vol);
}
}
}
//エフェクトの再生
void Player::JumpEffect(EN_EffectName effectName, wstring seName) {
auto pos = GetComponent<Transform>()->GetPosition();
m_effectObj->PlayEffect(EN_EffectName::en_GoodEffect, EffectType::en_Jump, Vec3(pos.x, pos.y, -10.0f));
ActiveSE(seName);
PlayVoiceSE(0.5f);
}
void Player::JumpAcionEffect(EN_EffectName effectName, wstring seName) {
bool JumpAcionFlag = (m_isJumpActionXAnimation || m_isJumpActionYAnimation || m_isJumpActionZAnimation);
if (JumpAcionFlag && m_animeTimeCounter == 0) {
JumpEffect(effectName, seName);
}
};
void Player::SetUpSpecialJumpFlag() {
bool isSpecialTime = GameManager::GetInstance().GetIsSpecialTime();
if (isSpecialTime) {
GameManager::GetInstance().SetIsSpecialJump(true);
}
}
void Player::FollowEffect() {
if (m_effectObj) {
auto pos = GetComponent<Transform>()->GetPosition();
auto efkPlay = m_effectObj->GetEfkPlay(EffectType::en_Jump);
if (efkPlay != NULL) {
efkPlay->SetPosition(Vec3(pos.x, pos.y, -10.0f));
m_effectObj->SetEfkPlay(efkPlay, EffectType::en_Jump);
}
}
};
//コリジョンの最初に当たった瞬間1回のみの処理
void Player::OnCollisionEnter(shared_ptr<GameObject>& other) {
if (other->FindTag(L"Sea")) {
m_isTouchSea = true;
if (m_isSpecialJumpAction) {
m_isSpecialJumpAction = false;
m_currentSpecialJumpActionCount = 0;
}
m_currentAnimationKeyCount = 0;
m_isEnableFlightAction = true;
m_isJump=false;
m_isFreeJump = false;
m_isLanding = true;
if (m_isFirstJump) {
m_isJumpStartAnimation = false;
m_isJumpFinishAnimation = true;
m_isWaitingAnimation = false;
m_isJumpActionXAnimation = false;
m_isJumpActionYAnimation = false;
m_isJumpActionZAnimation = false;
}
if (m_rot.z!=0) {
m_knockBackMagnification = 0.5f;
InitKnockBack(m_knockBackMagnification);
JumpMissSpeedDown();
m_isInvincible = true;
}
if (m_isFlightAction) {
m_isFlightAction = false;
//m_currentFlightTime = m_maxFlightTime;
}
GetComponent<RigidbodyBox>()->SetAutoGravity(false);
}
if ((other->FindTag(L"SmallWave") || other->FindTag(L"MidWave") || other->FindTag(L"BigWave"))) {
m_isFirstJump = true;
auto colPtr = GetComponent<CollisionObb>();
float playerColSize = colPtr->GetMakedSize().x;
float inSpeed = GameManager::GetInstance().GetGameSpeed();
float stayTime = playerColSize / inSpeed;
float outSpeed = inSpeed + m_groundWaveDownSpeedValue * stayTime;
float averageSpeed = (inSpeed + outSpeed) / 2.8f;
stayTime = playerColSize / averageSpeed;
m_jumpGradeTime = stayTime * m_jumpGradeTimeJudge;
}
if (other->FindTag(L"BigWave")) {
m_isWaveTouch = true;
}
if (other->FindTag(L"MidWave")) {
m_isWaveTouch = true;
}
if (other->FindTag(L"SmallWave")) {
m_isWaveTouch = true;
}
}
//コリジョンに当たり続けているときの処理
void Player::OnCollisionExcute(shared_ptr<GameObject>& other) {
if (other->FindTag(L"BigWave")) {
BigWaveJump();
}
if (other->FindTag(L"MidWave")) {
MidWaveJump();
}
if (other->FindTag(L"SmallWave")) {
SmallWaveJump();
}
//落下防止処理
if (other->FindTag(L"Sea") && !m_isJump && !m_isFreeJump) {
GetComponent<RigidbodyBox>()->SetLinearVelocity(Vec3(0, 0, 0));
GetComponent<RigidbodyBox>()->SetAutoGravity(false);
if (m_isBigWaveJump) {
m_isBigWaveJump = false;
}
if (!m_isInvincible && !m_isWaveTouch&&m_isFirstJump) {
m_isTouchSea = true;
GroundWaveSpeedDown();
}
bool JumpAcionFlag = (m_isJumpActionXAnimation || m_isJumpActionYAnimation || m_isJumpActionZAnimation);
if (JumpAcionFlag) {
m_combo = 0;
}
}
}
//コリジョンから抜けた瞬間1回のみの処理
void Player::OnCollisionExit(shared_ptr<GameObject>&other) {
if (other->FindTag(L"BigWave")&&m_isTouchSea) {
if (!m_isInvincible&&m_isFirstJump) {
m_knockBackMagnification = 4.0f;
InitKnockBack(m_knockBackMagnification);
JumpMissSpeedDown();
GameManager::GetInstance().SetIsSpecialTime(false);
m_isInvincible = true;
}
m_currentJumpGradeTime = 0;
m_combo = 0;
m_isWaveTouch = false;
}
if (other->FindTag(L"MidWave") && m_isTouchSea) {
if (!m_isInvincible&&m_isFirstJump) {
m_knockBackMagnification = 2.0f;
InitKnockBack(m_knockBackMagnification);
JumpMissSpeedDown();
m_isInvincible = true;
}
m_currentJumpGradeTime = 0;
m_combo = 0;
m_isWaveTouch = false;
}
if (other->FindTag(L"SmallWave")&&m_isTouchSea) {
if (!m_isInvincible&&m_isFirstJump) {
m_knockBackMagnification = 1.0f;
InitKnockBack(m_knockBackMagnification);
JumpMissSpeedDown();
m_isInvincible = true;
}
m_currentJumpGradeTime = 0;
m_combo = 0;
m_isWaveTouch = false;
}
}
void Player::PushAButton() {
auto controller = App::GetApp()->GetInputDevice().GetControlerVec()[0];
if (controller.wPressedButtons & XINPUT_GAMEPAD_A && !m_isFreeJump && !m_isJump && !m_isWaveTouch) {
GetComponent<RigidbodyBox>()->SetAutoGravity(true);
GetComponent<RigidbodyBox>()->SetLinearVelocity(Vec3(0, m_midJumpMoveY * 0.5f, 0));
m_isFreeJump = true;
}
}
}
//end basecross
|
4f972806bc6c46dbbaca56dff9f9620cf4332200 | 997b0ac548c08f8ea3c57be423c946f946ecff40 | /Nutcracker/src/Nutcracker/Core/Input.h | 5c388484d2c51cd5af33fc1fe374403f832d4ac6 | [
"Apache-2.0"
] | permissive | DevShag/Nutcracker | 883e4158bcba847c8ef88f486e127d92dd1825ee | a5d90233b4b308db58872288a7d1637bf22e3050 | refs/heads/main | 2023-07-15T05:48:37.533974 | 2021-08-23T06:40:50 | 2021-08-23T06:40:50 | 318,091,266 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 882 | h | Input.h | #pragma once
#include "Nutcracker/Core/Core.h"
namespace Nutcracker {
class NUTCRACKER_API Input {
public:
inline static bool IsKeyPressed(int keycode) { return s_Instance->IsKeyPressedImpl(keycode); }
inline static bool IsMouseButtonPressed(int button) { return s_Instance->IsMouseButtonPressedImp(button); }
inline static std::pair<float, float> GetMousePosition() { return s_Instance->GetMousePositionImp(); }
inline static float GetMouseX() { return s_Instance->GetMouseX(); }
inline static float GetMouseY() { return s_Instance->GetMouseY(); }
protected:
virtual bool IsKeyPressedImpl(int keycode) = 0;
virtual bool IsMouseButtonPressedImp(int button) = 0;
virtual std::pair<float, float> GetMousePositionImp() = 0;
virtual float GetMouseX(int keycode) = 0;
virtual float GetMouseY(int keycode) = 0;
private:
static Input* s_Instance;
};
}
|
d59021254292ce14136d8b78cff9950ca284685d | 78d02c8034b83bdfbe0cdb747bef318bab744e1e | /proyFinal/alarm.cpp | be794190084d2de8c2ebf519b1ea854efc3ac8bc | [] | no_license | cesaravila22/embebidosTEC | 3cdf50aafd4719cbbe05029e051caeeb463174f9 | 06b67e81f8c54aeeec4b741ddfd4c646b7cf7d23 | refs/heads/master | 2020-04-08T22:07:12.316968 | 2013-11-18T21:19:46 | 2013-11-18T21:19:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,948 | cpp | alarm.cpp | #include <cv.h>
#include <highgui.h>
#include <iostream>
#include <time.h>
using namespace std;
using namespace cv;
int main (int argc, char * const argv[]){
const int DELAY = 100; // mseconds
// create all necessary instances
CvCapture * camera = cvCaptureFromCAM(0);
Mat next_frame_color = cvQueryFrame(camera);
Mat current_frame_color = cvQueryFrame(camera);
Mat current_frame, next_frame;
cvtColor(current_frame_color, current_frame, CV_RGB2GRAY);
cvtColor(next_frame_color, next_frame, CV_RGB2GRAY);
imshow("Motion1", current_frame);
Mat d1, d2, result;
int window = 200;
bool movement;
while (true){
//imshow("Motion1", current_frame);
//imshow("Motion2", next_frame);
movement = false;
imshow("Motion1", next_frame);
absdiff(next_frame, current_frame, d1);
absdiff(current_frame, current_frame, d2);
bitwise_xor(d1, d2, result);
int middle_y = result.rows/2;
int middle_x = result.cols/2;
// Center window
threshold(result, result, 140, 255, CV_THRESH_BINARY);
for(int i = middle_x-window; i < middle_x+window; i++)
for(int j = middle_y-window; j < middle_y+window; j++)
if(result.at<int>(j,i)>0)
{
movement = true;
break;
}
if(movement==true){
cout<<"Movement!\n";
}
//imshow("Motion", result);
next_frame.copyTo(current_frame);
// semi delay and quit when press Q/q
int key = cvWaitKey (DELAY);
if (key == 'q' || key == 'Q')
break;
//cvReleaseCapture(&camera);
//camera = cvCaptureFromCAM(0);
// get image from webcam
next_frame_color = cvQueryFrame(camera);
cvtColor(next_frame_color, next_frame, CV_RGB2GRAY);
}
return 0;
}
|
2b0abb4696e00521faf0910fa3ba10048b4ad1ac | 9261b7f586f6c7386ba77a2bd63518facf93fd3b | /setting.cpp | 822db4cc9274d62a4e3fea46e0c0796bcf39f8da | [] | no_license | Hans0706/Forum-for-Learning-C- | aa22b4ba9d8093c95ebcb0144199b3c29a6ad7fc | 819fee6a8701930a7f86b3dfee59cb07ef957abd | refs/heads/master | 2020-06-08T13:41:56.981292 | 2020-01-07T16:07:21 | 2020-01-07T16:07:21 | 193,237,387 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 52 | cpp | setting.cpp | #include "setting.h"
setting::setting()
{
}
|
08cffb91127f6aa9d79c88d7eb41cfce14f88bf2 | 4b65ffcb1df3db08e0d7cf6073d74d6bd4fac39f | /cf/1208/E.cpp~ | cd6eb64445c801e1458951d037301606e1477dd0 | [] | no_license | xLLLxLLLx/Averyta | 0b8540ba39da8bd7067504e85b3bd6533e84e281 | 487c58f4d4e55aa4291e1ccd7765bdbce2aaf6e7 | refs/heads/master | 2020-07-17T12:04:05.269971 | 2019-09-20T13:03:23 | 2019-09-20T13:03:23 | 206,016,559 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | E.cpp~ | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
struct data {
int w, id;
} a[N];
int b[N];
bool cmp(data A, data B) {
return A.w > B.w;
}
int main() {
int n;
scanf("%d", &n);
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i].w);
a[i].id = i;
}
sort(a + 1, a + 1 + n, cmp);
for(int i = 1; i < n; ++i) {
printf("%d %d\n", a[i].id * 2, a[i + 1].id * 2);
}
for(int i = 1; i <= n; ++i) {
b[i] = a[i].id * 2;
}
int ed = n;
for(int i = 1; i <= n; ++i) {
int pos = i + a[i].w - 1;
printf("%d %d\n", b[pos], a[i].id * 2 - 1);
if(pos == ed) b[++ed] = a[i].id * 2 - 1;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.