text
stringlengths 8
6.88M
|
|---|
// Created on: 1998-05-05
// Created by: Stepan MISHIN
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Geom_OsculatingSurface_HeaderFile
#define _Geom_OsculatingSurface_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Real.hxx>
#include <Geom_HSequenceOfBSplineSurface.hxx>
#include <TColStd_HSequenceOfInteger.hxx>
#include <TColStd_Array1OfBoolean.hxx>
#include <Standard_Integer.hxx>
#include <GeomAbs_IsoType.hxx>
#include <Geom_SequenceOfBSplineSurface.hxx>
class Geom_Surface;
class Geom_BSplineSurface;
class Geom_OsculatingSurface;
DEFINE_STANDARD_HANDLE(Geom_OsculatingSurface, Standard_Transient)
class Geom_OsculatingSurface : public Standard_Transient
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT Geom_OsculatingSurface();
//! detects if the surface has punctual U or V
//! isoparametric curve along on the bounds of the surface
//! relatively to the tolerance Tol and Builds the corresponding
//! osculating surfaces.
Standard_EXPORT Geom_OsculatingSurface(const Handle(Geom_Surface)& BS, const Standard_Real Tol);
Standard_EXPORT void Init (const Handle(Geom_Surface)& BS, const Standard_Real Tol);
Standard_EXPORT Handle(Geom_Surface) BasisSurface() const;
Standard_EXPORT Standard_Real Tolerance() const;
//! if Standard_True, L is the local osculating surface
//! along U at the point U,V.
Standard_EXPORT Standard_Boolean UOscSurf (const Standard_Real U, const Standard_Real V, Standard_Boolean& t, Handle(Geom_BSplineSurface)& L) const;
//! if Standard_True, L is the local osculating surface
//! along V at the point U,V.
Standard_EXPORT Standard_Boolean VOscSurf (const Standard_Real U, const Standard_Real V, Standard_Boolean& t, Handle(Geom_BSplineSurface)& L) const;
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const;
DEFINE_STANDARD_RTTIEXT(Geom_OsculatingSurface,Standard_Transient)
protected:
private:
//! returns False if the osculating surface can't be built
Standard_EXPORT Standard_Boolean BuildOsculatingSurface (const Standard_Real Param, const Standard_Integer UKnot, const Standard_Integer VKnot, const Handle(Geom_BSplineSurface)& BS, Handle(Geom_BSplineSurface)& L) const;
//! returns True if the isoparametric is
//! quasi-punctual
Standard_EXPORT Standard_Boolean IsQPunctual (const Handle(Geom_Surface)& S, const Standard_Real Param, const GeomAbs_IsoType IT, const Standard_Real TolMin, const Standard_Real TolMax) const;
Standard_EXPORT Standard_Boolean HasOscSurf() const;
Standard_EXPORT Standard_Boolean IsAlongU() const;
Standard_EXPORT Standard_Boolean IsAlongV() const;
Standard_EXPORT void ClearOsculFlags();
Standard_EXPORT const Geom_SequenceOfBSplineSurface& GetSeqOfL1() const;
Standard_EXPORT const Geom_SequenceOfBSplineSurface& GetSeqOfL2() const;
Handle(Geom_Surface) myBasisSurf;
Standard_Real myTol;
Handle(Geom_HSequenceOfBSplineSurface) myOsculSurf1;
Handle(Geom_HSequenceOfBSplineSurface) myOsculSurf2;
Handle(TColStd_HSequenceOfInteger) myKdeg;
TColStd_Array1OfBoolean myAlong;
};
#endif // _Geom_OsculatingSurface_HeaderFile
|
#include <iostream>
using namespace std;
int main(){
int sum = 0, n;
cin >> n;
for (int i=1; i<n; i++){
for (int j=1; j<=i; j++)
sum += j;
}
cout << sum;
return 0;
}
|
#include <QtTest>
#include "test_entity_code.h"
#include "test_data_facade.h"
using namespace qi::config::qt;
using namespace qi;
const QString CICI::FILENAME = "cici";
const QString TestDB::FOLDERNAME="qi/app/im";
const QString TestDB::FILENAME = "test_db";
const QString CICI::FOLDERNAME="qi/app/im";
class core : public QObject
{
Q_OBJECT
public:
core();
~core();
private slots:
void initTestCase();
void cleanupTestCase();
void entity_code();
void data_facade();
};
core::core()
{
}
core::~core()
{
}
void core::initTestCase()
{
}
void core::cleanupTestCase()
{
}
void core::entity_code()
{
test_entity_code();
}
void core::data_facade()
{
test_data_facade<CICI>();
}
QTEST_APPLESS_MAIN(core)
#include "tst_core.moc"
|
#pragma once
#include "bricks/core/object.h"
#include "bricks/core/returnpointer.h"
#include "bricks/core/exception.h"
namespace Bricks {
template<typename T> class Delegate;
}
namespace Bricks { namespace Collections {
namespace Internal {
class IteratorBase { };
class IterableBase { };
class IterableFastBase { };
}
class InvalidIteratorException : public Exception
{
public:
InvalidIteratorException(const String& message = String::Empty) : Exception(message) { }
};
template<typename T> class Collection;
template<typename T>
class Iterator : public Object, public Internal::IteratorBase
{
public:
typedef T IteratorType;
virtual T& GetCurrent() const = 0;
virtual bool MoveNext() = 0;
virtual ReturnPointer< Collection< T > > GetAllObjects() { BRICKS_FEATURE_THROW(NotImplementedException()); };
};
template<typename T>
class Iterable : public Internal::IterableBase
{
public:
typedef T IteratorType;
virtual ReturnPointer< Iterator< IteratorType > > GetIterator() const = 0;
void Iterate(const Delegate<bool(IteratorType&)>& delegate) const;
void Iterate(const Delegate<void(IteratorType&)>& delegate) const;
};
template<typename T>
class IterableFast : public Internal::IterableFastBase
{
public:
typedef T IteratorFastType;
virtual T GetIteratorFast() const = 0;
};
} }
namespace Bricks { namespace Collections { namespace Internal {
template<typename T>
struct IteratorType
{
template<typename U> IteratorType(const U& list, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableBase, U>::Value>::Type* dummy = NULL) : state(true), iter(list.GetIterator()) { }
template<typename U> IteratorType(const U* list, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableBase, U>::Value>::Type* dummy = NULL) : state(true), iter(list->GetIterator()) { }
template<typename U> IteratorType(const Pointer<U>& list, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableBase, U>::Value>::Type* dummy = NULL) : state(true), iter(list->GetIterator()) { }
template<typename U> IteratorType(const U& iter, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IteratorBase, U>::Value>::Type* dummy = NULL) : state(true), iter(&iter) { }
template<typename U> IteratorType(const U* iter, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IteratorBase, U>::Value>::Type* dummy = NULL) : state(true), iter(iter) { }
template<typename U> IteratorType(const Pointer<U>& iter, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IteratorBase, U>::Value>::Type* dummy = NULL) : state(true), iter(iter) { }
bool state;
AutoPointer<Iterator<T> > iter;
inline bool MoveNext() const { return iter->MoveNext(); }
inline T& GetCurrent() const { return iter->GetCurrent(); }
};
template<typename T>
struct IteratorFastType
{
template<typename U> IteratorFastType(const U& list, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableFastBase, U>::Value>::Type* dummy = NULL) : state(true), iter(list.GetIteratorFast()) { }
template<typename U> IteratorFastType(const U* list, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableFastBase, U>::Value>::Type* dummy = NULL) : state(true), iter(list->GetIteratorFast()) { }
template<typename U> IteratorFastType(const Pointer<U>& list, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableFastBase, U>::Value>::Type* dummy = NULL) : state(true), iter(list->GetIteratorFast()) { }
template<typename U> IteratorFastType(const U& iter, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IteratorBase, U>::Value>::Type* dummy = NULL) : state(true), iter(iter) { }
template<typename U> IteratorFastType(const U* iter, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IteratorBase, U>::Value>::Type* dummy = NULL) : state(true), iter(*iter) { }
template<typename U> IteratorFastType(const Pointer<U>& iter, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IteratorBase, U>::Value>::Type* dummy = NULL) : state(true), iter(*iter) { }
bool state;
T iter;
inline bool MoveNext() const { return const_cast<T&>(iter).MoveNext(); }
inline typename T::IteratorType& GetCurrent() const { return iter.GetCurrent(); }
};
template<typename T> static typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableBase, T>::Value && !SFINAE::IsCompatibleType<IterableFastBase, T>::Value, IteratorType<typename T::IteratorType> >::Type IteratorContainerType(const T& t);
template<typename T> static typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableBase, T>::Value && !SFINAE::IsCompatibleType<IterableFastBase, T>::Value, IteratorType<typename T::IteratorType> >::Type IteratorContainerType(const T* t);
template<typename T> static typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableBase, T>::Value && !SFINAE::IsCompatibleType<IterableFastBase, T>::Value, IteratorType<typename T::IteratorType> >::Type IteratorContainerType(const Pointer<T>& t);
template<typename T> static typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IteratorBase, T>::Value && SFINAE::IsSameType<Iterator<typename T::IteratorType>, T>::Value, IteratorType<T> >::Type IteratorContainerType(const T& t);
template<typename T> static typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IteratorBase, T>::Value && !SFINAE::IsSameType<Iterator<typename T::IteratorType>, T>::Value, IteratorFastType<T> >::Type IteratorContainerType(const T& t);
template<typename T> static typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IteratorBase, T>::Value, IteratorType<typename T::IteratorType> >::Type IteratorContainerType(const T* t);
template<typename T> static typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IteratorBase, T>::Value, IteratorType<typename T::IteratorType> >::Type IteratorContainerType(const Pointer<T>& t);
template<typename T> static typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableFastBase, T>::Value, IteratorFastType<typename T::IteratorFastType> >::Type IteratorContainerType(const T& t);
template<typename T> static typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableFastBase, T>::Value, IteratorFastType<typename T::IteratorFastType> >::Type IteratorContainerType(const T* t);
template<typename T> static typename SFINAE::EnableIf<SFINAE::IsCompatibleType<IterableFastBase, T>::Value, IteratorFastType<typename T::IteratorFastType> >::Type IteratorContainerType(const Pointer<T>& t);
} } }
#define BRICKS_FOR_EACH(val, list) for (typeof(Bricks::Collections::Internal::IteratorContainerType(list)) __bricks_iter(list); __bricks_iter.MoveNext() && __bricks_iter.state;) if (!(__bricks_iter.state = false)) for (val = __bricks_iter.GetCurrent(); !__bricks_iter.state; __bricks_iter.state = true)
namespace Bricks { namespace Collections {
template<typename T> inline void Iterable<T>::Iterate(const Delegate<bool(Iterable<T>::IteratorType&)>& delegate) const {
BRICKS_FOR_EACH (IteratorType& t, *this) {
if (!delegate.Call(t))
break;
}
}
template<typename T> inline void Iterable<T>::Iterate(const Delegate<void(Iterable<T>::IteratorType&)>& delegate) const {
BRICKS_FOR_EACH (IteratorType& t, *this)
delegate.Call(t);
}
} }
#define foreach BRICKS_FOR_EACH
|
#include "Instructions.h"
#include "llvm/ADT/Twine.h"
#include "InstrTypes.h"
#include "Instruction.h"
#include "llvm/ADT/ArrayRef.h"
#include "CallingConv.h"
#include "Attributes.h"
#include "llvm/ADT/SmallVector.h"
#include "Type.h"
#include "Value.h"
#include "Instruction.h"
#include "BasicBlock.h"
#include "DerivedTypes.h"
#include "LLVMContext.h"
#include "Constant.h"
#include "Function.h"
#include "Attributes.h"
#include "Use.h"
#include "Constants.h"
#include "Instructions.h"
#include <msclr/marshal.h>
#include "utils.h"
using namespace LLVM;
AllocaInst::AllocaInst(llvm::AllocaInst *base)
: base(base)
, UnaryInstruction(base)
, constructed(false)
{
}
inline AllocaInst ^AllocaInst::_wrap(llvm::AllocaInst *base)
{
return base ? gcnew AllocaInst(base) : nullptr;
}
AllocaInst::!AllocaInst()
{
if (constructed)
{
delete base;
}
}
AllocaInst::~AllocaInst()
{
this->!AllocaInst();
}
AllocaInst::AllocaInst(Type ^Ty)
: base(new llvm::AllocaInst(Ty->base))
, UnaryInstruction(base)
, constructed(true)
{
}
AllocaInst::AllocaInst(Type ^Ty, Value ^ArraySize)
: base(new llvm::AllocaInst(Ty->base, ArraySize->base))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::AllocaInst *AllocaInst::_construct(Type ^Ty, Value ^ArraySize, System::String ^Name)
{
msclr::interop::marshal_context ctx;
return new llvm::AllocaInst(Ty->base, ArraySize->base, ctx.marshal_as<const char *>(Name));
}
AllocaInst::AllocaInst(Type ^Ty, Value ^ArraySize, System::String ^Name)
: base(_construct(Ty, ArraySize, Name))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::AllocaInst *AllocaInst::_construct(Type ^Ty, Value ^ArraySize, System::String ^Name, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::AllocaInst(Ty->base, ArraySize->base, ctx.marshal_as<const char *>(Name), InsertBefore->base);
}
AllocaInst::AllocaInst(Type ^Ty, Value ^ArraySize, System::String ^Name, Instruction ^InsertBefore)
: base(_construct(Ty, ArraySize, Name, InsertBefore))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::AllocaInst *AllocaInst::_construct(Type ^Ty, Value ^ArraySize, System::String ^Name, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::AllocaInst(Ty->base, ArraySize->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base);
}
AllocaInst::AllocaInst(Type ^Ty, Value ^ArraySize, System::String ^Name, BasicBlock ^InsertAtEnd)
: base(_construct(Ty, ArraySize, Name, InsertAtEnd))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::AllocaInst *AllocaInst::_construct(Type ^Ty, System::String ^Name)
{
msclr::interop::marshal_context ctx;
return new llvm::AllocaInst(Ty->base, ctx.marshal_as<const char *>(Name));
}
AllocaInst::AllocaInst(Type ^Ty, System::String ^Name)
: base(_construct(Ty, Name))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::AllocaInst *AllocaInst::_construct(Type ^Ty, System::String ^Name, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::AllocaInst(Ty->base, ctx.marshal_as<const char *>(Name), InsertBefore->base);
}
AllocaInst::AllocaInst(Type ^Ty, System::String ^Name, Instruction ^InsertBefore)
: base(_construct(Ty, Name, InsertBefore))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::AllocaInst *AllocaInst::_construct(Type ^Ty, System::String ^Name, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::AllocaInst(Ty->base, ctx.marshal_as<const char *>(Name), InsertAtEnd->base);
}
AllocaInst::AllocaInst(Type ^Ty, System::String ^Name, BasicBlock ^InsertAtEnd)
: base(_construct(Ty, Name, InsertAtEnd))
, UnaryInstruction(base)
, constructed(true)
{
}
AllocaInst::AllocaInst(Type ^Ty, Value ^ArraySize, unsigned Align)
: base(new llvm::AllocaInst(Ty->base, ArraySize->base, Align))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::AllocaInst *AllocaInst::_construct(Type ^Ty, Value ^ArraySize, unsigned Align, System::String ^Name)
{
msclr::interop::marshal_context ctx;
return new llvm::AllocaInst(Ty->base, ArraySize->base, Align, ctx.marshal_as<const char *>(Name));
}
AllocaInst::AllocaInst(Type ^Ty, Value ^ArraySize, unsigned Align, System::String ^Name)
: base(_construct(Ty, ArraySize, Align, Name))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::AllocaInst *AllocaInst::_construct(Type ^Ty, Value ^ArraySize, unsigned Align, System::String ^Name, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::AllocaInst(Ty->base, ArraySize->base, Align, ctx.marshal_as<const char *>(Name), InsertBefore->base);
}
AllocaInst::AllocaInst(Type ^Ty, Value ^ArraySize, unsigned Align, System::String ^Name, Instruction ^InsertBefore)
: base(_construct(Ty, ArraySize, Align, Name, InsertBefore))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::AllocaInst *AllocaInst::_construct(Type ^Ty, Value ^ArraySize, unsigned Align, System::String ^Name, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::AllocaInst(Ty->base, ArraySize->base, Align, ctx.marshal_as<const char *>(Name), InsertAtEnd->base);
}
AllocaInst::AllocaInst(Type ^Ty, Value ^ArraySize, unsigned Align, System::String ^Name, BasicBlock ^InsertAtEnd)
: base(_construct(Ty, ArraySize, Align, Name, InsertAtEnd))
, UnaryInstruction(base)
, constructed(true)
{
}
bool AllocaInst::isArrayAllocation()
{
return base->isArrayAllocation();
}
Value ^AllocaInst::getArraySize()
{
return Value::_wrap(base->getArraySize());
}
PointerType ^AllocaInst::getType()
{
return PointerType::_wrap(base->getType());
}
Type ^AllocaInst::getAllocatedType()
{
return Type::_wrap(base->getAllocatedType());
}
unsigned AllocaInst::getAlignment()
{
return base->getAlignment();
}
void AllocaInst::setAlignment(unsigned Align)
{
base->setAlignment(Align);
}
bool AllocaInst::isStaticAlloca()
{
return base->isStaticAlloca();
}
inline bool AllocaInst::classof(Instruction ^I)
{
return llvm::AllocaInst::classof(I->base);
}
inline bool AllocaInst::classof(Value ^V)
{
return llvm::AllocaInst::classof(V->base);
}
LoadInst::LoadInst(llvm::LoadInst *base)
: base(base)
, UnaryInstruction(base)
, constructed(false)
{
}
inline LoadInst ^LoadInst::_wrap(llvm::LoadInst *base)
{
return base ? gcnew LoadInst(base) : nullptr;
}
LoadInst::!LoadInst()
{
if (constructed)
{
delete base;
}
}
LoadInst::~LoadInst()
{
this->!LoadInst();
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(Ptr, NameStr, InsertBefore))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(Ptr, NameStr, InsertAtEnd))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr));
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr)
: base(_construct(Ptr, NameStr))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, bool isVolatile)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), isVolatile);
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, bool isVolatile)
: base(_construct(Ptr, NameStr, isVolatile))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, bool isVolatile, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), isVolatile, InsertBefore->base);
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, bool isVolatile, Instruction ^InsertBefore)
: base(_construct(Ptr, NameStr, isVolatile, InsertBefore))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, bool isVolatile, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), isVolatile, InsertAtEnd->base);
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, bool isVolatile, BasicBlock ^InsertAtEnd)
: base(_construct(Ptr, NameStr, isVolatile, InsertAtEnd))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), isVolatile, Align);
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align)
: base(_construct(Ptr, NameStr, isVolatile, Align))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), isVolatile, Align, InsertBefore->base);
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, Instruction ^InsertBefore)
: base(_construct(Ptr, NameStr, isVolatile, Align, InsertBefore))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), isVolatile, Align, InsertAtEnd->base);
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, BasicBlock ^InsertAtEnd)
: base(_construct(Ptr, NameStr, isVolatile, Align, InsertAtEnd))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, AtomicOrdering Order)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), isVolatile, Align, safe_cast<llvm::AtomicOrdering>(Order));
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, AtomicOrdering Order)
: base(_construct(Ptr, NameStr, isVolatile, Align, Order))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), isVolatile, Align, safe_cast<llvm::AtomicOrdering>(Order), safe_cast<llvm::SynchronizationScope>(SynchScope));
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope)
: base(_construct(Ptr, NameStr, isVolatile, Align, Order, SynchScope))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), isVolatile, Align, safe_cast<llvm::AtomicOrdering>(Order), safe_cast<llvm::SynchronizationScope>(SynchScope), InsertBefore->base);
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope, Instruction ^InsertBefore)
: base(_construct(Ptr, NameStr, isVolatile, Align, Order, SynchScope, InsertBefore))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::LoadInst *LoadInst::_construct(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::LoadInst(Ptr->base, ctx.marshal_as<const char *>(NameStr), isVolatile, Align, safe_cast<llvm::AtomicOrdering>(Order), safe_cast<llvm::SynchronizationScope>(SynchScope), InsertAtEnd->base);
}
LoadInst::LoadInst(Value ^Ptr, System::String ^NameStr, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope, BasicBlock ^InsertAtEnd)
: base(_construct(Ptr, NameStr, isVolatile, Align, Order, SynchScope, InsertAtEnd))
, UnaryInstruction(base)
, constructed(true)
{
}
LoadInst::LoadInst(Value ^Ptr)
: base(new llvm::LoadInst(Ptr->base))
, UnaryInstruction(base)
, constructed(true)
{
}
bool LoadInst::isVolatile()
{
return base->isVolatile();
}
void LoadInst::setVolatile(bool V)
{
base->setVolatile(V);
}
unsigned LoadInst::getAlignment()
{
return base->getAlignment();
}
void LoadInst::setAlignment(unsigned Align)
{
base->setAlignment(Align);
}
AtomicOrdering LoadInst::getOrdering()
{
return safe_cast<AtomicOrdering>(base->getOrdering());
}
void LoadInst::setOrdering(AtomicOrdering Ordering)
{
base->setOrdering(safe_cast<llvm::AtomicOrdering>(Ordering));
}
SynchronizationScope LoadInst::getSynchScope()
{
return safe_cast<SynchronizationScope>(base->getSynchScope());
}
void LoadInst::setSynchScope(SynchronizationScope xthread)
{
base->setSynchScope(safe_cast<llvm::SynchronizationScope>(xthread));
}
bool LoadInst::isAtomic()
{
return base->isAtomic();
}
void LoadInst::setAtomic(AtomicOrdering Ordering)
{
base->setAtomic(safe_cast<llvm::AtomicOrdering>(Ordering));
}
void LoadInst::setAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope)
{
base->setAtomic(safe_cast<llvm::AtomicOrdering>(Ordering), safe_cast<llvm::SynchronizationScope>(SynchScope));
}
bool LoadInst::isSimple()
{
return base->isSimple();
}
bool LoadInst::isUnordered()
{
return base->isUnordered();
}
Value ^LoadInst::getPointerOperand()
{
return Value::_wrap(base->getPointerOperand());
}
unsigned LoadInst::getPointerOperandIndex()
{
return llvm::LoadInst::getPointerOperandIndex();
}
unsigned LoadInst::getPointerAddressSpace()
{
return base->getPointerAddressSpace();
}
inline bool LoadInst::classof(Instruction ^I)
{
return llvm::LoadInst::classof(I->base);
}
inline bool LoadInst::classof(Value ^V)
{
return llvm::LoadInst::classof(V->base);
}
StoreInst::StoreInst(llvm::StoreInst *base)
: base(base)
, Instruction(base)
, constructed(false)
{
}
inline StoreInst ^StoreInst::_wrap(llvm::StoreInst *base)
{
return base ? gcnew StoreInst(base) : nullptr;
}
StoreInst::!StoreInst()
{
if (constructed)
{
delete base;
}
}
StoreInst::~StoreInst()
{
this->!StoreInst();
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, Instruction ^InsertBefore)
: base(new llvm::StoreInst(Val->base, Ptr->base, InsertBefore->base))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, BasicBlock ^InsertAtEnd)
: base(new llvm::StoreInst(Val->base, Ptr->base, InsertAtEnd->base))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr)
: base(new llvm::StoreInst(Val->base, Ptr->base))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, bool isVolatile)
: base(new llvm::StoreInst(Val->base, Ptr->base, isVolatile))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, bool isVolatile, Instruction ^InsertBefore)
: base(new llvm::StoreInst(Val->base, Ptr->base, isVolatile, InsertBefore->base))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, bool isVolatile, BasicBlock ^InsertAtEnd)
: base(new llvm::StoreInst(Val->base, Ptr->base, isVolatile, InsertAtEnd->base))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, bool isVolatile, unsigned Align)
: base(new llvm::StoreInst(Val->base, Ptr->base, isVolatile, Align))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, bool isVolatile, unsigned Align, Instruction ^InsertBefore)
: base(new llvm::StoreInst(Val->base, Ptr->base, isVolatile, Align, InsertBefore->base))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, bool isVolatile, unsigned Align, BasicBlock ^InsertAtEnd)
: base(new llvm::StoreInst(Val->base, Ptr->base, isVolatile, Align, InsertAtEnd->base))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, bool isVolatile, unsigned Align, AtomicOrdering Order)
: base(new llvm::StoreInst(Val->base, Ptr->base, isVolatile, Align, safe_cast<llvm::AtomicOrdering>(Order)))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope)
: base(new llvm::StoreInst(Val->base, Ptr->base, isVolatile, Align, safe_cast<llvm::AtomicOrdering>(Order), safe_cast<llvm::SynchronizationScope>(SynchScope)))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope, Instruction ^InsertBefore)
: base(new llvm::StoreInst(Val->base, Ptr->base, isVolatile, Align, safe_cast<llvm::AtomicOrdering>(Order), safe_cast<llvm::SynchronizationScope>(SynchScope), InsertBefore->base))
, Instruction(base)
, constructed(true)
{
}
StoreInst::StoreInst(Value ^Val, Value ^Ptr, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope, BasicBlock ^InsertAtEnd)
: base(new llvm::StoreInst(Val->base, Ptr->base, isVolatile, Align, safe_cast<llvm::AtomicOrdering>(Order), safe_cast<llvm::SynchronizationScope>(SynchScope), InsertAtEnd->base))
, Instruction(base)
, constructed(true)
{
}
bool StoreInst::isVolatile()
{
return base->isVolatile();
}
void StoreInst::setVolatile(bool V)
{
base->setVolatile(V);
}
unsigned StoreInst::getAlignment()
{
return base->getAlignment();
}
void StoreInst::setAlignment(unsigned Align)
{
base->setAlignment(Align);
}
AtomicOrdering StoreInst::getOrdering()
{
return safe_cast<AtomicOrdering>(base->getOrdering());
}
void StoreInst::setOrdering(AtomicOrdering Ordering)
{
base->setOrdering(safe_cast<llvm::AtomicOrdering>(Ordering));
}
SynchronizationScope StoreInst::getSynchScope()
{
return safe_cast<SynchronizationScope>(base->getSynchScope());
}
void StoreInst::setSynchScope(SynchronizationScope xthread)
{
base->setSynchScope(safe_cast<llvm::SynchronizationScope>(xthread));
}
bool StoreInst::isAtomic()
{
return base->isAtomic();
}
void StoreInst::setAtomic(AtomicOrdering Ordering)
{
base->setAtomic(safe_cast<llvm::AtomicOrdering>(Ordering));
}
void StoreInst::setAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope)
{
base->setAtomic(safe_cast<llvm::AtomicOrdering>(Ordering), safe_cast<llvm::SynchronizationScope>(SynchScope));
}
bool StoreInst::isSimple()
{
return base->isSimple();
}
bool StoreInst::isUnordered()
{
return base->isUnordered();
}
Value ^StoreInst::getValueOperand()
{
return Value::_wrap(base->getValueOperand());
}
Value ^StoreInst::getPointerOperand()
{
return Value::_wrap(base->getPointerOperand());
}
unsigned StoreInst::getPointerOperandIndex()
{
return llvm::StoreInst::getPointerOperandIndex();
}
unsigned StoreInst::getPointerAddressSpace()
{
return base->getPointerAddressSpace();
}
inline bool StoreInst::classof(Instruction ^I)
{
return llvm::StoreInst::classof(I->base);
}
inline bool StoreInst::classof(Value ^V)
{
return llvm::StoreInst::classof(V->base);
}
FenceInst::FenceInst(llvm::FenceInst *base)
: base(base)
, Instruction(base)
, constructed(false)
{
}
inline FenceInst ^FenceInst::_wrap(llvm::FenceInst *base)
{
return base ? gcnew FenceInst(base) : nullptr;
}
FenceInst::!FenceInst()
{
if (constructed)
{
delete base;
}
}
FenceInst::~FenceInst()
{
this->!FenceInst();
}
FenceInst::FenceInst(LLVMContext ^C, AtomicOrdering Ordering)
: base(new llvm::FenceInst(*C->base, safe_cast<llvm::AtomicOrdering>(Ordering)))
, Instruction(base)
, constructed(true)
{
}
FenceInst::FenceInst(LLVMContext ^C, AtomicOrdering Ordering, SynchronizationScope SynchScope)
: base(new llvm::FenceInst(*C->base, safe_cast<llvm::AtomicOrdering>(Ordering), safe_cast<llvm::SynchronizationScope>(SynchScope)))
, Instruction(base)
, constructed(true)
{
}
FenceInst::FenceInst(LLVMContext ^C, AtomicOrdering Ordering, SynchronizationScope SynchScope, Instruction ^InsertBefore)
: base(new llvm::FenceInst(*C->base, safe_cast<llvm::AtomicOrdering>(Ordering), safe_cast<llvm::SynchronizationScope>(SynchScope), InsertBefore->base))
, Instruction(base)
, constructed(true)
{
}
FenceInst::FenceInst(LLVMContext ^C, AtomicOrdering Ordering, SynchronizationScope SynchScope, BasicBlock ^InsertAtEnd)
: base(new llvm::FenceInst(*C->base, safe_cast<llvm::AtomicOrdering>(Ordering), safe_cast<llvm::SynchronizationScope>(SynchScope), InsertAtEnd->base))
, Instruction(base)
, constructed(true)
{
}
AtomicOrdering FenceInst::getOrdering()
{
return safe_cast<AtomicOrdering>(base->getOrdering());
}
void FenceInst::setOrdering(AtomicOrdering Ordering)
{
base->setOrdering(safe_cast<llvm::AtomicOrdering>(Ordering));
}
SynchronizationScope FenceInst::getSynchScope()
{
return safe_cast<SynchronizationScope>(base->getSynchScope());
}
void FenceInst::setSynchScope(SynchronizationScope xthread)
{
base->setSynchScope(safe_cast<llvm::SynchronizationScope>(xthread));
}
inline bool FenceInst::classof(Instruction ^I)
{
return llvm::FenceInst::classof(I->base);
}
inline bool FenceInst::classof(Value ^V)
{
return llvm::FenceInst::classof(V->base);
}
AtomicCmpXchgInst::AtomicCmpXchgInst(llvm::AtomicCmpXchgInst *base)
: base(base)
, Instruction(base)
, constructed(false)
{
}
inline AtomicCmpXchgInst ^AtomicCmpXchgInst::_wrap(llvm::AtomicCmpXchgInst *base)
{
return base ? gcnew AtomicCmpXchgInst(base) : nullptr;
}
AtomicCmpXchgInst::!AtomicCmpXchgInst()
{
if (constructed)
{
delete base;
}
}
AtomicCmpXchgInst::~AtomicCmpXchgInst()
{
this->!AtomicCmpXchgInst();
}
AtomicCmpXchgInst::AtomicCmpXchgInst(Value ^Ptr, Value ^Cmp, Value ^NewVal, AtomicOrdering Ordering, SynchronizationScope SynchScope)
: base(new llvm::AtomicCmpXchgInst(Ptr->base, Cmp->base, NewVal->base, safe_cast<llvm::AtomicOrdering>(Ordering), safe_cast<llvm::SynchronizationScope>(SynchScope)))
, Instruction(base)
, constructed(true)
{
}
AtomicCmpXchgInst::AtomicCmpXchgInst(Value ^Ptr, Value ^Cmp, Value ^NewVal, AtomicOrdering Ordering, SynchronizationScope SynchScope, Instruction ^InsertBefore)
: base(new llvm::AtomicCmpXchgInst(Ptr->base, Cmp->base, NewVal->base, safe_cast<llvm::AtomicOrdering>(Ordering), safe_cast<llvm::SynchronizationScope>(SynchScope), InsertBefore->base))
, Instruction(base)
, constructed(true)
{
}
AtomicCmpXchgInst::AtomicCmpXchgInst(Value ^Ptr, Value ^Cmp, Value ^NewVal, AtomicOrdering Ordering, SynchronizationScope SynchScope, BasicBlock ^InsertAtEnd)
: base(new llvm::AtomicCmpXchgInst(Ptr->base, Cmp->base, NewVal->base, safe_cast<llvm::AtomicOrdering>(Ordering), safe_cast<llvm::SynchronizationScope>(SynchScope), InsertAtEnd->base))
, Instruction(base)
, constructed(true)
{
}
bool AtomicCmpXchgInst::isVolatile()
{
return base->isVolatile();
}
void AtomicCmpXchgInst::setVolatile(bool V)
{
base->setVolatile(V);
}
void AtomicCmpXchgInst::setOrdering(AtomicOrdering Ordering)
{
base->setOrdering(safe_cast<llvm::AtomicOrdering>(Ordering));
}
void AtomicCmpXchgInst::setSynchScope(SynchronizationScope SynchScope)
{
base->setSynchScope(safe_cast<llvm::SynchronizationScope>(SynchScope));
}
AtomicOrdering AtomicCmpXchgInst::getOrdering()
{
return safe_cast<AtomicOrdering>(base->getOrdering());
}
SynchronizationScope AtomicCmpXchgInst::getSynchScope()
{
return safe_cast<SynchronizationScope>(base->getSynchScope());
}
Value ^AtomicCmpXchgInst::getPointerOperand()
{
return Value::_wrap(base->getPointerOperand());
}
unsigned AtomicCmpXchgInst::getPointerOperandIndex()
{
return llvm::AtomicCmpXchgInst::getPointerOperandIndex();
}
Value ^AtomicCmpXchgInst::getCompareOperand()
{
return Value::_wrap(base->getCompareOperand());
}
Value ^AtomicCmpXchgInst::getNewValOperand()
{
return Value::_wrap(base->getNewValOperand());
}
unsigned AtomicCmpXchgInst::getPointerAddressSpace()
{
return base->getPointerAddressSpace();
}
inline bool AtomicCmpXchgInst::classof(Instruction ^I)
{
return llvm::AtomicCmpXchgInst::classof(I->base);
}
inline bool AtomicCmpXchgInst::classof(Value ^V)
{
return llvm::AtomicCmpXchgInst::classof(V->base);
}
AtomicRMWInst::AtomicRMWInst(llvm::AtomicRMWInst *base)
: base(base)
, Instruction(base)
, constructed(false)
{
}
inline AtomicRMWInst ^AtomicRMWInst::_wrap(llvm::AtomicRMWInst *base)
{
return base ? gcnew AtomicRMWInst(base) : nullptr;
}
AtomicRMWInst::!AtomicRMWInst()
{
if (constructed)
{
delete base;
}
}
AtomicRMWInst::~AtomicRMWInst()
{
this->!AtomicRMWInst();
}
AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value ^Ptr, Value ^Val, AtomicOrdering Ordering, SynchronizationScope SynchScope)
: base(new llvm::AtomicRMWInst(safe_cast<llvm::AtomicRMWInst::BinOp>(Operation), Ptr->base, Val->base, safe_cast<llvm::AtomicOrdering>(Ordering), safe_cast<llvm::SynchronizationScope>(SynchScope)))
, Instruction(base)
, constructed(true)
{
}
AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value ^Ptr, Value ^Val, AtomicOrdering Ordering, SynchronizationScope SynchScope, Instruction ^InsertBefore)
: base(new llvm::AtomicRMWInst(safe_cast<llvm::AtomicRMWInst::BinOp>(Operation), Ptr->base, Val->base, safe_cast<llvm::AtomicOrdering>(Ordering), safe_cast<llvm::SynchronizationScope>(SynchScope), InsertBefore->base))
, Instruction(base)
, constructed(true)
{
}
AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value ^Ptr, Value ^Val, AtomicOrdering Ordering, SynchronizationScope SynchScope, BasicBlock ^InsertAtEnd)
: base(new llvm::AtomicRMWInst(safe_cast<llvm::AtomicRMWInst::BinOp>(Operation), Ptr->base, Val->base, safe_cast<llvm::AtomicOrdering>(Ordering), safe_cast<llvm::SynchronizationScope>(SynchScope), InsertAtEnd->base))
, Instruction(base)
, constructed(true)
{
}
AtomicRMWInst::BinOp AtomicRMWInst::getOperation()
{
return safe_cast<AtomicRMWInst::BinOp>(base->getOperation());
}
void AtomicRMWInst::setOperation(BinOp Operation)
{
base->setOperation(safe_cast<llvm::AtomicRMWInst::BinOp>(Operation));
}
bool AtomicRMWInst::isVolatile()
{
return base->isVolatile();
}
void AtomicRMWInst::setVolatile(bool V)
{
base->setVolatile(V);
}
void AtomicRMWInst::setOrdering(AtomicOrdering Ordering)
{
base->setOrdering(safe_cast<llvm::AtomicOrdering>(Ordering));
}
void AtomicRMWInst::setSynchScope(SynchronizationScope SynchScope)
{
base->setSynchScope(safe_cast<llvm::SynchronizationScope>(SynchScope));
}
AtomicOrdering AtomicRMWInst::getOrdering()
{
return safe_cast<AtomicOrdering>(base->getOrdering());
}
SynchronizationScope AtomicRMWInst::getSynchScope()
{
return safe_cast<SynchronizationScope>(base->getSynchScope());
}
Value ^AtomicRMWInst::getPointerOperand()
{
return Value::_wrap(base->getPointerOperand());
}
unsigned AtomicRMWInst::getPointerOperandIndex()
{
return llvm::AtomicRMWInst::getPointerOperandIndex();
}
Value ^AtomicRMWInst::getValOperand()
{
return Value::_wrap(base->getValOperand());
}
unsigned AtomicRMWInst::getPointerAddressSpace()
{
return base->getPointerAddressSpace();
}
inline bool AtomicRMWInst::classof(Instruction ^I)
{
return llvm::AtomicRMWInst::classof(I->base);
}
inline bool AtomicRMWInst::classof(Value ^V)
{
return llvm::AtomicRMWInst::classof(V->base);
}
GetElementPtrInst::GetElementPtrInst(llvm::GetElementPtrInst *base)
: base(base)
, Instruction(base)
{
}
inline GetElementPtrInst ^GetElementPtrInst::_wrap(llvm::GetElementPtrInst *base)
{
return base ? gcnew GetElementPtrInst(base) : nullptr;
}
GetElementPtrInst::!GetElementPtrInst()
{
}
GetElementPtrInst::~GetElementPtrInst()
{
this->!GetElementPtrInst();
}
GetElementPtrInst ^GetElementPtrInst::Create(Value ^Ptr, array<Value ^> ^IdxList)
{
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = GetElementPtrInst::_wrap(llvm::GetElementPtrInst::Create(Ptr->base, brr));
delete b;
return r;
}
GetElementPtrInst ^GetElementPtrInst::Create(Value ^Ptr, array<Value ^> ^IdxList, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = GetElementPtrInst::_wrap(llvm::GetElementPtrInst::Create(Ptr->base, brr, ctx.marshal_as<const char *>(NameStr)));
delete b;
return r;
}
GetElementPtrInst ^GetElementPtrInst::Create(Value ^Ptr, array<Value ^> ^IdxList, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = GetElementPtrInst::_wrap(llvm::GetElementPtrInst::Create(Ptr->base, brr, ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
delete b;
return r;
}
GetElementPtrInst ^GetElementPtrInst::Create(Value ^Ptr, array<Value ^> ^IdxList, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = GetElementPtrInst::_wrap(llvm::GetElementPtrInst::Create(Ptr->base, brr, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
delete b;
return r;
}
GetElementPtrInst ^GetElementPtrInst::CreateInBounds(Value ^Ptr, array<Value ^> ^IdxList)
{
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = GetElementPtrInst::_wrap(llvm::GetElementPtrInst::CreateInBounds(Ptr->base, brr));
delete b;
return r;
}
GetElementPtrInst ^GetElementPtrInst::CreateInBounds(Value ^Ptr, array<Value ^> ^IdxList, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = GetElementPtrInst::_wrap(llvm::GetElementPtrInst::CreateInBounds(Ptr->base, brr, ctx.marshal_as<const char *>(NameStr)));
delete b;
return r;
}
GetElementPtrInst ^GetElementPtrInst::CreateInBounds(Value ^Ptr, array<Value ^> ^IdxList, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = GetElementPtrInst::_wrap(llvm::GetElementPtrInst::CreateInBounds(Ptr->base, brr, ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
delete b;
return r;
}
GetElementPtrInst ^GetElementPtrInst::CreateInBounds(Value ^Ptr, array<Value ^> ^IdxList, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = GetElementPtrInst::_wrap(llvm::GetElementPtrInst::CreateInBounds(Ptr->base, brr, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
delete b;
return r;
}
SequentialType ^GetElementPtrInst::getType()
{
return SequentialType::_wrap(base->getType());
}
unsigned GetElementPtrInst::getAddressSpace()
{
return base->getAddressSpace();
}
Type ^GetElementPtrInst::getIndexedType(Type ^Ptr, array<Value ^> ^IdxList)
{
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = Type::_wrap(llvm::GetElementPtrInst::getIndexedType(Ptr->base, brr));
delete b;
return r;
}
Type ^GetElementPtrInst::getIndexedType(Type ^Ptr, array<Constant ^> ^IdxList)
{
llvm::Constant **b = new llvm::Constant*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, IdxList->Length);
auto r = Type::_wrap(llvm::GetElementPtrInst::getIndexedType(Ptr->base, brr));
delete b;
return r;
}
Type ^GetElementPtrInst::getIndexedType(Type ^Ptr, array<uint64_t> ^IdxList)
{
auto r = Type::_wrap(llvm::GetElementPtrInst::getIndexedType(Ptr->base, utils::unmanage_array(IdxList)));
return r;
}
Value ^GetElementPtrInst::getPointerOperand()
{
return Value::_wrap(base->getPointerOperand());
}
unsigned GetElementPtrInst::getPointerOperandIndex()
{
return llvm::GetElementPtrInst::getPointerOperandIndex();
}
Type ^GetElementPtrInst::getPointerOperandType()
{
return Type::_wrap(base->getPointerOperandType());
}
unsigned GetElementPtrInst::getPointerAddressSpace()
{
return base->getPointerAddressSpace();
}
Type ^GetElementPtrInst::getGEPReturnType(Value ^Ptr, array<Value ^> ^IdxList)
{
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = Type::_wrap(llvm::GetElementPtrInst::getGEPReturnType(Ptr->base, brr));
delete b;
return r;
}
unsigned GetElementPtrInst::getNumIndices()
{
return base->getNumIndices();
}
bool GetElementPtrInst::hasIndices()
{
return base->hasIndices();
}
bool GetElementPtrInst::hasAllZeroIndices()
{
return base->hasAllZeroIndices();
}
bool GetElementPtrInst::hasAllConstantIndices()
{
return base->hasAllConstantIndices();
}
void GetElementPtrInst::setIsInBounds()
{
base->setIsInBounds();
}
void GetElementPtrInst::setIsInBounds(bool b)
{
base->setIsInBounds(b);
}
bool GetElementPtrInst::isInBounds()
{
return base->isInBounds();
}
inline bool GetElementPtrInst::classof(Instruction ^I)
{
return llvm::GetElementPtrInst::classof(I->base);
}
inline bool GetElementPtrInst::classof(Value ^V)
{
return llvm::GetElementPtrInst::classof(V->base);
}
ICmpInst::ICmpInst(llvm::ICmpInst *base)
: base(base)
, CmpInst(base)
, constructed(false)
{
}
inline ICmpInst ^ICmpInst::_wrap(llvm::ICmpInst *base)
{
return base ? gcnew ICmpInst(base) : nullptr;
}
ICmpInst::!ICmpInst()
{
if (constructed)
{
delete base;
}
}
ICmpInst::~ICmpInst()
{
this->!ICmpInst();
}
ICmpInst::ICmpInst(Instruction ^InsertBefore, Predicate pred, Value ^LHS, Value ^RHS)
: base(new llvm::ICmpInst(InsertBefore->base, safe_cast<llvm::ICmpInst::Predicate>(pred), LHS->base, RHS->base))
, CmpInst(base)
, constructed(true)
{
}
llvm::ICmpInst *ICmpInst::_construct(Instruction ^InsertBefore, Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::ICmpInst(InsertBefore->base, safe_cast<llvm::ICmpInst::Predicate>(pred), LHS->base, RHS->base, ctx.marshal_as<const char *>(NameStr));
}
ICmpInst::ICmpInst(Instruction ^InsertBefore, Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
: base(_construct(InsertBefore, pred, LHS, RHS, NameStr))
, CmpInst(base)
, constructed(true)
{
}
ICmpInst::ICmpInst(BasicBlock ^InsertAtEnd, Predicate pred, Value ^LHS, Value ^RHS)
: base(new llvm::ICmpInst(*InsertAtEnd->base, safe_cast<llvm::ICmpInst::Predicate>(pred), LHS->base, RHS->base))
, CmpInst(base)
, constructed(true)
{
}
llvm::ICmpInst *ICmpInst::_construct(BasicBlock ^InsertAtEnd, Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::ICmpInst(*InsertAtEnd->base, safe_cast<llvm::ICmpInst::Predicate>(pred), LHS->base, RHS->base, ctx.marshal_as<const char *>(NameStr));
}
ICmpInst::ICmpInst(BasicBlock ^InsertAtEnd, Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
: base(_construct(InsertAtEnd, pred, LHS, RHS, NameStr))
, CmpInst(base)
, constructed(true)
{
}
ICmpInst::ICmpInst(Predicate pred, Value ^LHS, Value ^RHS)
: base(new llvm::ICmpInst(safe_cast<llvm::ICmpInst::Predicate>(pred), LHS->base, RHS->base))
, CmpInst(base)
, constructed(true)
{
}
llvm::ICmpInst *ICmpInst::_construct(Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::ICmpInst(safe_cast<llvm::ICmpInst::Predicate>(pred), LHS->base, RHS->base, ctx.marshal_as<const char *>(NameStr));
}
ICmpInst::ICmpInst(Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
: base(_construct(pred, LHS, RHS, NameStr))
, CmpInst(base)
, constructed(true)
{
}
CmpInst::Predicate ICmpInst::getSignedPredicate()
{
return safe_cast<CmpInst::Predicate>(base->getSignedPredicate());
}
CmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred)
{
return safe_cast<CmpInst::Predicate>(llvm::ICmpInst::getSignedPredicate(safe_cast<llvm::ICmpInst::Predicate>(pred)));
}
CmpInst::Predicate ICmpInst::getUnsignedPredicate()
{
return safe_cast<CmpInst::Predicate>(base->getUnsignedPredicate());
}
CmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred)
{
return safe_cast<CmpInst::Predicate>(llvm::ICmpInst::getUnsignedPredicate(safe_cast<llvm::ICmpInst::Predicate>(pred)));
}
bool ICmpInst::isEquality(Predicate P)
{
return llvm::ICmpInst::isEquality(safe_cast<llvm::ICmpInst::Predicate>(P));
}
bool ICmpInst::isEquality()
{
return base->isEquality();
}
bool ICmpInst::isCommutative()
{
return base->isCommutative();
}
bool ICmpInst::isRelational()
{
return base->isRelational();
}
bool ICmpInst::isRelational(Predicate P)
{
return llvm::ICmpInst::isRelational(safe_cast<llvm::ICmpInst::Predicate>(P));
}
void ICmpInst::swapOperands()
{
base->swapOperands();
}
inline bool ICmpInst::classof(Instruction ^I)
{
return llvm::ICmpInst::classof(I->base);
}
inline bool ICmpInst::classof(Value ^V)
{
return llvm::ICmpInst::classof(V->base);
}
FCmpInst::FCmpInst(llvm::FCmpInst *base)
: base(base)
, CmpInst(base)
, constructed(false)
{
}
inline FCmpInst ^FCmpInst::_wrap(llvm::FCmpInst *base)
{
return base ? gcnew FCmpInst(base) : nullptr;
}
FCmpInst::!FCmpInst()
{
if (constructed)
{
delete base;
}
}
FCmpInst::~FCmpInst()
{
this->!FCmpInst();
}
FCmpInst::FCmpInst(Instruction ^InsertBefore, Predicate pred, Value ^LHS, Value ^RHS)
: base(new llvm::FCmpInst(InsertBefore->base, safe_cast<llvm::FCmpInst::Predicate>(pred), LHS->base, RHS->base))
, CmpInst(base)
, constructed(true)
{
}
llvm::FCmpInst *FCmpInst::_construct(Instruction ^InsertBefore, Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::FCmpInst(InsertBefore->base, safe_cast<llvm::FCmpInst::Predicate>(pred), LHS->base, RHS->base, ctx.marshal_as<const char *>(NameStr));
}
FCmpInst::FCmpInst(Instruction ^InsertBefore, Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
: base(_construct(InsertBefore, pred, LHS, RHS, NameStr))
, CmpInst(base)
, constructed(true)
{
}
FCmpInst::FCmpInst(BasicBlock ^InsertAtEnd, Predicate pred, Value ^LHS, Value ^RHS)
: base(new llvm::FCmpInst(*InsertAtEnd->base, safe_cast<llvm::FCmpInst::Predicate>(pred), LHS->base, RHS->base))
, CmpInst(base)
, constructed(true)
{
}
llvm::FCmpInst *FCmpInst::_construct(BasicBlock ^InsertAtEnd, Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::FCmpInst(*InsertAtEnd->base, safe_cast<llvm::FCmpInst::Predicate>(pred), LHS->base, RHS->base, ctx.marshal_as<const char *>(NameStr));
}
FCmpInst::FCmpInst(BasicBlock ^InsertAtEnd, Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
: base(_construct(InsertAtEnd, pred, LHS, RHS, NameStr))
, CmpInst(base)
, constructed(true)
{
}
FCmpInst::FCmpInst(Predicate pred, Value ^LHS, Value ^RHS)
: base(new llvm::FCmpInst(safe_cast<llvm::FCmpInst::Predicate>(pred), LHS->base, RHS->base))
, CmpInst(base)
, constructed(true)
{
}
llvm::FCmpInst *FCmpInst::_construct(Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::FCmpInst(safe_cast<llvm::FCmpInst::Predicate>(pred), LHS->base, RHS->base, ctx.marshal_as<const char *>(NameStr));
}
FCmpInst::FCmpInst(Predicate pred, Value ^LHS, Value ^RHS, System::String ^NameStr)
: base(_construct(pred, LHS, RHS, NameStr))
, CmpInst(base)
, constructed(true)
{
}
bool FCmpInst::isEquality()
{
return base->isEquality();
}
bool FCmpInst::isCommutative()
{
return base->isCommutative();
}
bool FCmpInst::isRelational()
{
return base->isRelational();
}
void FCmpInst::swapOperands()
{
base->swapOperands();
}
inline bool FCmpInst::classof(Instruction ^I)
{
return llvm::FCmpInst::classof(I->base);
}
inline bool FCmpInst::classof(Value ^V)
{
return llvm::FCmpInst::classof(V->base);
}
CallInst::CallInst(llvm::CallInst *base)
: base(base)
, Instruction(base)
{
}
inline CallInst ^CallInst::_wrap(llvm::CallInst *base)
{
return base ? gcnew CallInst(base) : nullptr;
}
CallInst::!CallInst()
{
}
CallInst::~CallInst()
{
this->!CallInst();
}
CallInst ^CallInst::Create(Value ^Func, array<Value ^> ^Args)
{
llvm::Value **b = new llvm::Value*[Args->Length];
for (int i = 0; i < Args->Length; i++)
b[i] = Args[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, Args->Length);
auto r = CallInst::_wrap(llvm::CallInst::Create(Func->base, brr));
delete b;
return r;
}
CallInst ^CallInst::Create(Value ^Func, array<Value ^> ^Args, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[Args->Length];
for (int i = 0; i < Args->Length; i++)
b[i] = Args[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, Args->Length);
auto r = CallInst::_wrap(llvm::CallInst::Create(Func->base, brr, ctx.marshal_as<const char *>(NameStr)));
delete b;
return r;
}
CallInst ^CallInst::Create(Value ^Func, array<Value ^> ^Args, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[Args->Length];
for (int i = 0; i < Args->Length; i++)
b[i] = Args[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, Args->Length);
auto r = CallInst::_wrap(llvm::CallInst::Create(Func->base, brr, ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
delete b;
return r;
}
CallInst ^CallInst::Create(Value ^Func, array<Value ^> ^Args, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[Args->Length];
for (int i = 0; i < Args->Length; i++)
b[i] = Args[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, Args->Length);
auto r = CallInst::_wrap(llvm::CallInst::Create(Func->base, brr, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
delete b;
return r;
}
CallInst ^CallInst::Create(Value ^F)
{
return CallInst::_wrap(llvm::CallInst::Create(F->base));
}
CallInst ^CallInst::Create(Value ^F, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return CallInst::_wrap(llvm::CallInst::Create(F->base, ctx.marshal_as<const char *>(NameStr)));
}
CallInst ^CallInst::Create(Value ^F, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return CallInst::_wrap(llvm::CallInst::Create(F->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
}
CallInst ^CallInst::Create(Value ^F, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return CallInst::_wrap(llvm::CallInst::Create(F->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
}
Instruction ^CallInst::CreateMalloc(Instruction ^InsertBefore, Type ^IntPtrTy, Type ^AllocTy, Value ^AllocSize)
{
return Instruction::_wrap(llvm::CallInst::CreateMalloc(InsertBefore->base, IntPtrTy->base, AllocTy->base, AllocSize->base));
}
Instruction ^CallInst::CreateMalloc(Instruction ^InsertBefore, Type ^IntPtrTy, Type ^AllocTy, Value ^AllocSize, Value ^ArraySize)
{
return Instruction::_wrap(llvm::CallInst::CreateMalloc(InsertBefore->base, IntPtrTy->base, AllocTy->base, AllocSize->base, ArraySize->base));
}
Instruction ^CallInst::CreateMalloc(Instruction ^InsertBefore, Type ^IntPtrTy, Type ^AllocTy, Value ^AllocSize, Value ^ArraySize, Function ^MallocF)
{
return Instruction::_wrap(llvm::CallInst::CreateMalloc(InsertBefore->base, IntPtrTy->base, AllocTy->base, AllocSize->base, ArraySize->base, MallocF->base));
}
Instruction ^CallInst::CreateMalloc(Instruction ^InsertBefore, Type ^IntPtrTy, Type ^AllocTy, Value ^AllocSize, Value ^ArraySize, Function ^MallocF, System::String ^Name)
{
msclr::interop::marshal_context ctx;
return Instruction::_wrap(llvm::CallInst::CreateMalloc(InsertBefore->base, IntPtrTy->base, AllocTy->base, AllocSize->base, ArraySize->base, MallocF->base, ctx.marshal_as<const char *>(Name)));
}
Instruction ^CallInst::CreateMalloc(BasicBlock ^InsertAtEnd, Type ^IntPtrTy, Type ^AllocTy, Value ^AllocSize)
{
return Instruction::_wrap(llvm::CallInst::CreateMalloc(InsertAtEnd->base, IntPtrTy->base, AllocTy->base, AllocSize->base));
}
Instruction ^CallInst::CreateMalloc(BasicBlock ^InsertAtEnd, Type ^IntPtrTy, Type ^AllocTy, Value ^AllocSize, Value ^ArraySize)
{
return Instruction::_wrap(llvm::CallInst::CreateMalloc(InsertAtEnd->base, IntPtrTy->base, AllocTy->base, AllocSize->base, ArraySize->base));
}
Instruction ^CallInst::CreateMalloc(BasicBlock ^InsertAtEnd, Type ^IntPtrTy, Type ^AllocTy, Value ^AllocSize, Value ^ArraySize, Function ^MallocF)
{
return Instruction::_wrap(llvm::CallInst::CreateMalloc(InsertAtEnd->base, IntPtrTy->base, AllocTy->base, AllocSize->base, ArraySize->base, MallocF->base));
}
Instruction ^CallInst::CreateMalloc(BasicBlock ^InsertAtEnd, Type ^IntPtrTy, Type ^AllocTy, Value ^AllocSize, Value ^ArraySize, Function ^MallocF, System::String ^Name)
{
msclr::interop::marshal_context ctx;
return Instruction::_wrap(llvm::CallInst::CreateMalloc(InsertAtEnd->base, IntPtrTy->base, AllocTy->base, AllocSize->base, ArraySize->base, MallocF->base, ctx.marshal_as<const char *>(Name)));
}
Instruction ^CallInst::CreateFree(Value ^Source, Instruction ^InsertBefore)
{
return Instruction::_wrap(llvm::CallInst::CreateFree(Source->base, InsertBefore->base));
}
Instruction ^CallInst::CreateFree(Value ^Source, BasicBlock ^InsertAtEnd)
{
return Instruction::_wrap(llvm::CallInst::CreateFree(Source->base, InsertAtEnd->base));
}
bool CallInst::isTailCall()
{
return base->isTailCall();
}
void CallInst::setTailCall()
{
base->setTailCall();
}
void CallInst::setTailCall(bool isTC)
{
base->setTailCall(isTC);
}
unsigned CallInst::getNumArgOperands()
{
return base->getNumArgOperands();
}
Value ^CallInst::getArgOperand(unsigned i)
{
return Value::_wrap(base->getArgOperand(i));
}
void CallInst::setArgOperand(unsigned i, Value ^v)
{
base->setArgOperand(i, v->base);
}
CallingConv::ID CallInst::getCallingConv()
{
return safe_cast<CallingConv::ID>(base->getCallingConv());
}
void CallInst::setCallingConv(CallingConv::ID CC)
{
base->setCallingConv(safe_cast<llvm::CallingConv::ID>(CC));
}
void CallInst::setAttributes(AttributeSet ^Attrs)
{
base->setAttributes(*Attrs->base);
}
void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr)
{
base->addAttribute(i, safe_cast<llvm::Attribute::AttrKind>(attr));
}
void CallInst::removeAttribute(unsigned i, Attribute ^attr)
{
base->removeAttribute(i, *attr->base);
}
bool CallInst::hasFnAttr(Attribute::AttrKind A)
{
return base->hasFnAttr(safe_cast<llvm::Attribute::AttrKind>(A));
}
bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A)
{
return base->paramHasAttr(i, safe_cast<llvm::Attribute::AttrKind>(A));
}
unsigned CallInst::getParamAlignment(unsigned i)
{
return base->getParamAlignment(i);
}
bool CallInst::isNoInline()
{
return base->isNoInline();
}
void CallInst::setIsNoInline()
{
base->setIsNoInline();
}
bool CallInst::canReturnTwice()
{
return base->canReturnTwice();
}
void CallInst::setCanReturnTwice()
{
base->setCanReturnTwice();
}
bool CallInst::doesNotAccessMemory()
{
return base->doesNotAccessMemory();
}
void CallInst::setDoesNotAccessMemory()
{
base->setDoesNotAccessMemory();
}
bool CallInst::onlyReadsMemory()
{
return base->onlyReadsMemory();
}
void CallInst::setOnlyReadsMemory()
{
base->setOnlyReadsMemory();
}
bool CallInst::doesNotReturn()
{
return base->doesNotReturn();
}
void CallInst::setDoesNotReturn()
{
base->setDoesNotReturn();
}
bool CallInst::doesNotThrow()
{
return base->doesNotThrow();
}
void CallInst::setDoesNotThrow()
{
base->setDoesNotThrow();
}
bool CallInst::cannotDuplicate()
{
return base->cannotDuplicate();
}
void CallInst::setCannotDuplicate()
{
base->setCannotDuplicate();
}
bool CallInst::hasStructRetAttr()
{
return base->hasStructRetAttr();
}
bool CallInst::hasByValArgument()
{
return base->hasByValArgument();
}
Function ^CallInst::getCalledFunction()
{
return Function::_wrap(base->getCalledFunction());
}
Value ^CallInst::getCalledValue()
{
return Value::_wrap(base->getCalledValue());
}
void CallInst::setCalledFunction(Value ^Fn)
{
base->setCalledFunction(Fn->base);
}
bool CallInst::isInlineAsm()
{
return base->isInlineAsm();
}
inline bool CallInst::classof(Instruction ^I)
{
return llvm::CallInst::classof(I->base);
}
inline bool CallInst::classof(Value ^V)
{
return llvm::CallInst::classof(V->base);
}
SelectInst::SelectInst(llvm::SelectInst *base)
: base(base)
, Instruction(base)
{
}
inline SelectInst ^SelectInst::_wrap(llvm::SelectInst *base)
{
return base ? gcnew SelectInst(base) : nullptr;
}
SelectInst::!SelectInst()
{
}
SelectInst::~SelectInst()
{
this->!SelectInst();
}
SelectInst ^SelectInst::Create(Value ^C, Value ^S1, Value ^S2)
{
return SelectInst::_wrap(llvm::SelectInst::Create(C->base, S1->base, S2->base));
}
SelectInst ^SelectInst::Create(Value ^C, Value ^S1, Value ^S2, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return SelectInst::_wrap(llvm::SelectInst::Create(C->base, S1->base, S2->base, ctx.marshal_as<const char *>(NameStr)));
}
SelectInst ^SelectInst::Create(Value ^C, Value ^S1, Value ^S2, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return SelectInst::_wrap(llvm::SelectInst::Create(C->base, S1->base, S2->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
}
SelectInst ^SelectInst::Create(Value ^C, Value ^S1, Value ^S2, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return SelectInst::_wrap(llvm::SelectInst::Create(C->base, S1->base, S2->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
}
Value ^SelectInst::getCondition()
{
return Value::_wrap(base->getCondition());
}
Value ^SelectInst::getTrueValue()
{
return Value::_wrap(base->getTrueValue());
}
Value ^SelectInst::getFalseValue()
{
return Value::_wrap(base->getFalseValue());
}
System::String ^SelectInst::areInvalidOperands(Value ^Cond, Value ^True, Value ^False)
{
return utils::manage_str(llvm::SelectInst::areInvalidOperands(Cond->base, True->base, False->base));
}
Instruction::OtherOps SelectInst::getOpcode()
{
return safe_cast<Instruction::OtherOps>(base->getOpcode());
}
inline bool SelectInst::classof(Instruction ^I)
{
return llvm::SelectInst::classof(I->base);
}
inline bool SelectInst::classof(Value ^V)
{
return llvm::SelectInst::classof(V->base);
}
VAArgInst::VAArgInst(llvm::VAArgInst *base)
: base(base)
, UnaryInstruction(base)
, constructed(false)
{
}
inline VAArgInst ^VAArgInst::_wrap(llvm::VAArgInst *base)
{
return base ? gcnew VAArgInst(base) : nullptr;
}
VAArgInst::!VAArgInst()
{
if (constructed)
{
delete base;
}
}
VAArgInst::~VAArgInst()
{
this->!VAArgInst();
}
VAArgInst::VAArgInst(Value ^List, Type ^Ty)
: base(new llvm::VAArgInst(List->base, Ty->base))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::VAArgInst *VAArgInst::_construct(Value ^List, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::VAArgInst(List->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
VAArgInst::VAArgInst(Value ^List, Type ^Ty, System::String ^NameStr)
: base(_construct(List, Ty, NameStr))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::VAArgInst *VAArgInst::_construct(Value ^List, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::VAArgInst(List->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
VAArgInst::VAArgInst(Value ^List, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(List, Ty, NameStr, InsertBefore))
, UnaryInstruction(base)
, constructed(true)
{
}
llvm::VAArgInst *VAArgInst::_construct(Value ^List, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::VAArgInst(List->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
VAArgInst::VAArgInst(Value ^List, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(List, Ty, NameStr, InsertAtEnd))
, UnaryInstruction(base)
, constructed(true)
{
}
Value ^VAArgInst::getPointerOperand()
{
return Value::_wrap(base->getPointerOperand());
}
unsigned VAArgInst::getPointerOperandIndex()
{
return llvm::VAArgInst::getPointerOperandIndex();
}
inline bool VAArgInst::classof(Instruction ^I)
{
return llvm::VAArgInst::classof(I->base);
}
inline bool VAArgInst::classof(Value ^V)
{
return llvm::VAArgInst::classof(V->base);
}
ExtractElementInst::ExtractElementInst(llvm::ExtractElementInst *base)
: base(base)
, Instruction(base)
{
}
inline ExtractElementInst ^ExtractElementInst::_wrap(llvm::ExtractElementInst *base)
{
return base ? gcnew ExtractElementInst(base) : nullptr;
}
ExtractElementInst::!ExtractElementInst()
{
}
ExtractElementInst::~ExtractElementInst()
{
this->!ExtractElementInst();
}
ExtractElementInst ^ExtractElementInst::Create(Value ^Vec, Value ^Idx)
{
return ExtractElementInst::_wrap(llvm::ExtractElementInst::Create(Vec->base, Idx->base));
}
ExtractElementInst ^ExtractElementInst::Create(Value ^Vec, Value ^Idx, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return ExtractElementInst::_wrap(llvm::ExtractElementInst::Create(Vec->base, Idx->base, ctx.marshal_as<const char *>(NameStr)));
}
ExtractElementInst ^ExtractElementInst::Create(Value ^Vec, Value ^Idx, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return ExtractElementInst::_wrap(llvm::ExtractElementInst::Create(Vec->base, Idx->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
}
ExtractElementInst ^ExtractElementInst::Create(Value ^Vec, Value ^Idx, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return ExtractElementInst::_wrap(llvm::ExtractElementInst::Create(Vec->base, Idx->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
}
bool ExtractElementInst::isValidOperands(Value ^Vec, Value ^Idx)
{
return llvm::ExtractElementInst::isValidOperands(Vec->base, Idx->base);
}
Value ^ExtractElementInst::getVectorOperand()
{
return Value::_wrap(base->getVectorOperand());
}
Value ^ExtractElementInst::getIndexOperand()
{
return Value::_wrap(base->getIndexOperand());
}
VectorType ^ExtractElementInst::getVectorOperandType()
{
return VectorType::_wrap(base->getVectorOperandType());
}
inline bool ExtractElementInst::classof(Instruction ^I)
{
return llvm::ExtractElementInst::classof(I->base);
}
inline bool ExtractElementInst::classof(Value ^V)
{
return llvm::ExtractElementInst::classof(V->base);
}
InsertElementInst::InsertElementInst(llvm::InsertElementInst *base)
: base(base)
, Instruction(base)
{
}
inline InsertElementInst ^InsertElementInst::_wrap(llvm::InsertElementInst *base)
{
return base ? gcnew InsertElementInst(base) : nullptr;
}
InsertElementInst::!InsertElementInst()
{
}
InsertElementInst::~InsertElementInst()
{
this->!InsertElementInst();
}
InsertElementInst ^InsertElementInst::Create(Value ^Vec, Value ^NewElt, Value ^Idx)
{
return InsertElementInst::_wrap(llvm::InsertElementInst::Create(Vec->base, NewElt->base, Idx->base));
}
InsertElementInst ^InsertElementInst::Create(Value ^Vec, Value ^NewElt, Value ^Idx, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return InsertElementInst::_wrap(llvm::InsertElementInst::Create(Vec->base, NewElt->base, Idx->base, ctx.marshal_as<const char *>(NameStr)));
}
InsertElementInst ^InsertElementInst::Create(Value ^Vec, Value ^NewElt, Value ^Idx, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return InsertElementInst::_wrap(llvm::InsertElementInst::Create(Vec->base, NewElt->base, Idx->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
}
InsertElementInst ^InsertElementInst::Create(Value ^Vec, Value ^NewElt, Value ^Idx, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return InsertElementInst::_wrap(llvm::InsertElementInst::Create(Vec->base, NewElt->base, Idx->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
}
bool InsertElementInst::isValidOperands(Value ^Vec, Value ^NewElt, Value ^Idx)
{
return llvm::InsertElementInst::isValidOperands(Vec->base, NewElt->base, Idx->base);
}
VectorType ^InsertElementInst::getType()
{
return VectorType::_wrap(base->getType());
}
inline bool InsertElementInst::classof(Instruction ^I)
{
return llvm::InsertElementInst::classof(I->base);
}
inline bool InsertElementInst::classof(Value ^V)
{
return llvm::InsertElementInst::classof(V->base);
}
ShuffleVectorInst::ShuffleVectorInst(llvm::ShuffleVectorInst *base)
: base(base)
, Instruction(base)
, constructed(false)
{
}
inline ShuffleVectorInst ^ShuffleVectorInst::_wrap(llvm::ShuffleVectorInst *base)
{
return base ? gcnew ShuffleVectorInst(base) : nullptr;
}
ShuffleVectorInst::!ShuffleVectorInst()
{
if (constructed)
{
delete base;
}
}
ShuffleVectorInst::~ShuffleVectorInst()
{
this->!ShuffleVectorInst();
}
ShuffleVectorInst::ShuffleVectorInst(Value ^V1, Value ^V2, Value ^Mask)
: base(new llvm::ShuffleVectorInst(V1->base, V2->base, Mask->base))
, Instruction(base)
, constructed(true)
{
}
llvm::ShuffleVectorInst *ShuffleVectorInst::_construct(Value ^V1, Value ^V2, Value ^Mask, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::ShuffleVectorInst(V1->base, V2->base, Mask->base, ctx.marshal_as<const char *>(NameStr));
}
ShuffleVectorInst::ShuffleVectorInst(Value ^V1, Value ^V2, Value ^Mask, System::String ^NameStr)
: base(_construct(V1, V2, Mask, NameStr))
, Instruction(base)
, constructed(true)
{
}
llvm::ShuffleVectorInst *ShuffleVectorInst::_construct(Value ^V1, Value ^V2, Value ^Mask, System::String ^NameStr, Instruction ^InsertBefor)
{
msclr::interop::marshal_context ctx;
return new llvm::ShuffleVectorInst(V1->base, V2->base, Mask->base, ctx.marshal_as<const char *>(NameStr), InsertBefor->base);
}
ShuffleVectorInst::ShuffleVectorInst(Value ^V1, Value ^V2, Value ^Mask, System::String ^NameStr, Instruction ^InsertBefor)
: base(_construct(V1, V2, Mask, NameStr, InsertBefor))
, Instruction(base)
, constructed(true)
{
}
llvm::ShuffleVectorInst *ShuffleVectorInst::_construct(Value ^V1, Value ^V2, Value ^Mask, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::ShuffleVectorInst(V1->base, V2->base, Mask->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
ShuffleVectorInst::ShuffleVectorInst(Value ^V1, Value ^V2, Value ^Mask, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(V1, V2, Mask, NameStr, InsertAtEnd))
, Instruction(base)
, constructed(true)
{
}
bool ShuffleVectorInst::isValidOperands(Value ^V1, Value ^V2, Value ^Mask)
{
return llvm::ShuffleVectorInst::isValidOperands(V1->base, V2->base, Mask->base);
}
VectorType ^ShuffleVectorInst::getType()
{
return VectorType::_wrap(base->getType());
}
Constant ^ShuffleVectorInst::getMask()
{
return Constant::_wrap(base->getMask());
}
int ShuffleVectorInst::getMaskValue(Constant ^Mask, unsigned i)
{
return llvm::ShuffleVectorInst::getMaskValue(Mask->base, i);
}
int ShuffleVectorInst::getMaskValue(unsigned i)
{
return base->getMaskValue(i);
}
array<int> ^ShuffleVectorInst::getShuffleMaskArray(Constant ^Mask)
{
llvm::SmallVector<int, 8> r;
llvm::ShuffleVectorInst::getShuffleMask(Mask->base, r);
array<int> ^s = gcnew array<int>(r.size());
for (int i = 0; i < s->Length; i++)
s[i] = r[i];
return s;
}
array<int> ^ShuffleVectorInst::getShuffleMaskArray()
{
llvm::SmallVector<int, 8> r;
base->getShuffleMask(r);
array<int> ^s = gcnew array<int>(r.size());
for (int i = 0; i < s->Length; i++)
s[i] = r[i];
return s;
}
inline bool ShuffleVectorInst::classof(Instruction ^I)
{
return llvm::ShuffleVectorInst::classof(I->base);
}
inline bool ShuffleVectorInst::classof(Value ^V)
{
return llvm::ShuffleVectorInst::classof(V->base);
}
ExtractValueInst::ExtractValueInst(llvm::ExtractValueInst *base)
: base(base)
, UnaryInstruction(base)
{
}
inline ExtractValueInst ^ExtractValueInst::_wrap(llvm::ExtractValueInst *base)
{
return base ? gcnew ExtractValueInst(base) : nullptr;
}
ExtractValueInst::!ExtractValueInst()
{
}
ExtractValueInst::~ExtractValueInst()
{
this->!ExtractValueInst();
}
ExtractValueInst ^ExtractValueInst::Create(Value ^Agg, array<unsigned> ^Idxs)
{
auto r = ExtractValueInst::_wrap(llvm::ExtractValueInst::Create(Agg->base, utils::unmanage_array(Idxs)));
return r;
}
ExtractValueInst ^ExtractValueInst::Create(Value ^Agg, array<unsigned> ^Idxs, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
auto r = ExtractValueInst::_wrap(llvm::ExtractValueInst::Create(Agg->base, utils::unmanage_array(Idxs), ctx.marshal_as<const char *>(NameStr)));
return r;
}
ExtractValueInst ^ExtractValueInst::Create(Value ^Agg, array<unsigned> ^Idxs, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
auto r = ExtractValueInst::_wrap(llvm::ExtractValueInst::Create(Agg->base, utils::unmanage_array(Idxs), ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
return r;
}
ExtractValueInst ^ExtractValueInst::Create(Value ^Agg, array<unsigned> ^Idxs, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
auto r = ExtractValueInst::_wrap(llvm::ExtractValueInst::Create(Agg->base, utils::unmanage_array(Idxs), ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
return r;
}
Type ^ExtractValueInst::getIndexedType(Type ^Agg, array<unsigned> ^Idxs)
{
auto r = Type::_wrap(llvm::ExtractValueInst::getIndexedType(Agg->base, utils::unmanage_array(Idxs)));
return r;
}
Value ^ExtractValueInst::getAggregateOperand()
{
return Value::_wrap(base->getAggregateOperand());
}
unsigned ExtractValueInst::getAggregateOperandIndex()
{
return llvm::ExtractValueInst::getAggregateOperandIndex();
}
array<unsigned> ^ExtractValueInst::getIndices()
{
auto r = base->getIndices();
array<unsigned> ^s = gcnew array<unsigned>(r.size());
for (int i = 0; i < s->Length; i++)
s[i] = r[i];
return s;
}
unsigned ExtractValueInst::getNumIndices()
{
return base->getNumIndices();
}
bool ExtractValueInst::hasIndices()
{
return base->hasIndices();
}
inline bool ExtractValueInst::classof(Instruction ^I)
{
return llvm::ExtractValueInst::classof(I->base);
}
inline bool ExtractValueInst::classof(Value ^V)
{
return llvm::ExtractValueInst::classof(V->base);
}
InsertValueInst::InsertValueInst(llvm::InsertValueInst *base)
: base(base)
, Instruction(base)
{
}
inline InsertValueInst ^InsertValueInst::_wrap(llvm::InsertValueInst *base)
{
return base ? gcnew InsertValueInst(base) : nullptr;
}
InsertValueInst::!InsertValueInst()
{
}
InsertValueInst::~InsertValueInst()
{
this->!InsertValueInst();
}
InsertValueInst ^InsertValueInst::Create(Value ^Agg, Value ^Val, array<unsigned> ^Idxs)
{
auto r = InsertValueInst::_wrap(llvm::InsertValueInst::Create(Agg->base, Val->base, utils::unmanage_array(Idxs)));
return r;
}
InsertValueInst ^InsertValueInst::Create(Value ^Agg, Value ^Val, array<unsigned> ^Idxs, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
auto r = InsertValueInst::_wrap(llvm::InsertValueInst::Create(Agg->base, Val->base, utils::unmanage_array(Idxs), ctx.marshal_as<const char *>(NameStr)));
return r;
}
InsertValueInst ^InsertValueInst::Create(Value ^Agg, Value ^Val, array<unsigned> ^Idxs, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
auto r = InsertValueInst::_wrap(llvm::InsertValueInst::Create(Agg->base, Val->base, utils::unmanage_array(Idxs), ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
return r;
}
InsertValueInst ^InsertValueInst::Create(Value ^Agg, Value ^Val, array<unsigned> ^Idxs, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
auto r = InsertValueInst::_wrap(llvm::InsertValueInst::Create(Agg->base, Val->base, utils::unmanage_array(Idxs), ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
return r;
}
Value ^InsertValueInst::getAggregateOperand()
{
return Value::_wrap(base->getAggregateOperand());
}
unsigned InsertValueInst::getAggregateOperandIndex()
{
return llvm::InsertValueInst::getAggregateOperandIndex();
}
Value ^InsertValueInst::getInsertedValueOperand()
{
return Value::_wrap(base->getInsertedValueOperand());
}
unsigned InsertValueInst::getInsertedValueOperandIndex()
{
return llvm::InsertValueInst::getInsertedValueOperandIndex();
}
array<unsigned> ^InsertValueInst::getIndices()
{
auto r = base->getIndices();
array<unsigned> ^s = gcnew array<unsigned>(r.size());
for (int i = 0; i < s->Length; i++)
s[i] = r[i];
return s;
}
unsigned InsertValueInst::getNumIndices()
{
return base->getNumIndices();
}
bool InsertValueInst::hasIndices()
{
return base->hasIndices();
}
inline bool InsertValueInst::classof(Instruction ^I)
{
return llvm::InsertValueInst::classof(I->base);
}
inline bool InsertValueInst::classof(Value ^V)
{
return llvm::InsertValueInst::classof(V->base);
}
PHINode::PHINode(llvm::PHINode *base)
: base(base)
, Instruction(base)
{
}
inline PHINode ^PHINode::_wrap(llvm::PHINode *base)
{
return base ? gcnew PHINode(base) : nullptr;
}
PHINode::!PHINode()
{
}
PHINode::~PHINode()
{
this->!PHINode();
}
PHINode ^PHINode::Create(Type ^Ty, unsigned NumReservedValues)
{
return PHINode::_wrap(llvm::PHINode::Create(Ty->base, NumReservedValues));
}
PHINode ^PHINode::Create(Type ^Ty, unsigned NumReservedValues, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return PHINode::_wrap(llvm::PHINode::Create(Ty->base, NumReservedValues, ctx.marshal_as<const char *>(NameStr)));
}
PHINode ^PHINode::Create(Type ^Ty, unsigned NumReservedValues, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return PHINode::_wrap(llvm::PHINode::Create(Ty->base, NumReservedValues, ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
}
PHINode ^PHINode::Create(Type ^Ty, unsigned NumReservedValues, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return PHINode::_wrap(llvm::PHINode::Create(Ty->base, NumReservedValues, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
}
unsigned PHINode::getNumIncomingValues()
{
return base->getNumIncomingValues();
}
Value ^PHINode::getIncomingValue(unsigned i)
{
return Value::_wrap(base->getIncomingValue(i));
}
void PHINode::setIncomingValue(unsigned i, Value ^V)
{
base->setIncomingValue(i, V->base);
}
unsigned PHINode::getOperandNumForIncomingValue(unsigned i)
{
return llvm::PHINode::getOperandNumForIncomingValue(i);
}
unsigned PHINode::getIncomingValueNumForOperand(unsigned i)
{
return llvm::PHINode::getIncomingValueNumForOperand(i);
}
BasicBlock ^PHINode::getIncomingBlock(unsigned i)
{
return BasicBlock::_wrap(base->getIncomingBlock(i));
}
BasicBlock ^PHINode::getIncomingBlock(Use ^U)
{
return BasicBlock::_wrap(base->getIncomingBlock(*U->base));
}
void PHINode::setIncomingBlock(unsigned i, BasicBlock ^BB)
{
base->setIncomingBlock(i, BB->base);
}
void PHINode::addIncoming(Value ^V, BasicBlock ^BB)
{
base->addIncoming(V->base, BB->base);
}
Value ^PHINode::removeIncomingValue(unsigned Idx)
{
return Value::_wrap(base->removeIncomingValue(Idx));
}
Value ^PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty)
{
return Value::_wrap(base->removeIncomingValue(Idx, DeletePHIIfEmpty));
}
Value ^PHINode::removeIncomingValue(BasicBlock ^BB)
{
return Value::_wrap(base->removeIncomingValue(BB->base));
}
Value ^PHINode::removeIncomingValue(BasicBlock ^BB, bool DeletePHIIfEmpty)
{
return Value::_wrap(base->removeIncomingValue(BB->base, DeletePHIIfEmpty));
}
int PHINode::getBasicBlockIndex(BasicBlock ^BB)
{
return base->getBasicBlockIndex(BB->base);
}
Value ^PHINode::getIncomingValueForBlock(BasicBlock ^BB)
{
return Value::_wrap(base->getIncomingValueForBlock(BB->base));
}
Value ^PHINode::hasConstantValue()
{
return Value::_wrap(base->hasConstantValue());
}
inline bool PHINode::classof(Instruction ^I)
{
return llvm::PHINode::classof(I->base);
}
inline bool PHINode::classof(Value ^V)
{
return llvm::PHINode::classof(V->base);
}
LandingPadInst::LandingPadInst(llvm::LandingPadInst *base)
: base(base)
, Instruction(base)
{
}
inline LandingPadInst ^LandingPadInst::_wrap(llvm::LandingPadInst *base)
{
return base ? gcnew LandingPadInst(base) : nullptr;
}
LandingPadInst::!LandingPadInst()
{
}
LandingPadInst::~LandingPadInst()
{
this->!LandingPadInst();
}
LandingPadInst ^LandingPadInst::Create(Type ^RetTy, Value ^PersonalityFn, unsigned NumReservedClauses)
{
return LandingPadInst::_wrap(llvm::LandingPadInst::Create(RetTy->base, PersonalityFn->base, NumReservedClauses));
}
LandingPadInst ^LandingPadInst::Create(Type ^RetTy, Value ^PersonalityFn, unsigned NumReservedClauses, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return LandingPadInst::_wrap(llvm::LandingPadInst::Create(RetTy->base, PersonalityFn->base, NumReservedClauses, ctx.marshal_as<const char *>(NameStr)));
}
LandingPadInst ^LandingPadInst::Create(Type ^RetTy, Value ^PersonalityFn, unsigned NumReservedClauses, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return LandingPadInst::_wrap(llvm::LandingPadInst::Create(RetTy->base, PersonalityFn->base, NumReservedClauses, ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
}
LandingPadInst ^LandingPadInst::Create(Type ^RetTy, Value ^PersonalityFn, unsigned NumReservedClauses, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return LandingPadInst::_wrap(llvm::LandingPadInst::Create(RetTy->base, PersonalityFn->base, NumReservedClauses, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
}
Value ^LandingPadInst::getPersonalityFn()
{
return Value::_wrap(base->getPersonalityFn());
}
bool LandingPadInst::isCleanup()
{
return base->isCleanup();
}
void LandingPadInst::setCleanup(bool V)
{
base->setCleanup(V);
}
void LandingPadInst::addClause(Value ^ClauseVal)
{
base->addClause(ClauseVal->base);
}
Value ^LandingPadInst::getClause(unsigned Idx)
{
return Value::_wrap(base->getClause(Idx));
}
bool LandingPadInst::isCatch(unsigned Idx)
{
return base->isCatch(Idx);
}
bool LandingPadInst::isFilter(unsigned Idx)
{
return base->isFilter(Idx);
}
unsigned LandingPadInst::getNumClauses()
{
return base->getNumClauses();
}
void LandingPadInst::reserveClauses(unsigned Size)
{
base->reserveClauses(Size);
}
inline bool LandingPadInst::classof(Instruction ^I)
{
return llvm::LandingPadInst::classof(I->base);
}
inline bool LandingPadInst::classof(Value ^V)
{
return llvm::LandingPadInst::classof(V->base);
}
ReturnInst::ReturnInst(llvm::ReturnInst *base)
: base(base)
, TerminatorInst(base)
{
}
inline ReturnInst ^ReturnInst::_wrap(llvm::ReturnInst *base)
{
return base ? gcnew ReturnInst(base) : nullptr;
}
ReturnInst::!ReturnInst()
{
}
ReturnInst::~ReturnInst()
{
this->!ReturnInst();
}
ReturnInst ^ReturnInst::Create(LLVMContext ^C)
{
return ReturnInst::_wrap(llvm::ReturnInst::Create(*C->base));
}
ReturnInst ^ReturnInst::Create(LLVMContext ^C, Value ^retVal)
{
return ReturnInst::_wrap(llvm::ReturnInst::Create(*C->base, retVal->base));
}
ReturnInst ^ReturnInst::Create(LLVMContext ^C, Value ^retVal, Instruction ^InsertBefore)
{
return ReturnInst::_wrap(llvm::ReturnInst::Create(*C->base, retVal->base, InsertBefore->base));
}
ReturnInst ^ReturnInst::Create(LLVMContext ^C, Value ^retVal, BasicBlock ^InsertAtEnd)
{
return ReturnInst::_wrap(llvm::ReturnInst::Create(*C->base, retVal->base, InsertAtEnd->base));
}
ReturnInst ^ReturnInst::Create(LLVMContext ^C, BasicBlock ^InsertAtEnd)
{
return ReturnInst::_wrap(llvm::ReturnInst::Create(*C->base, InsertAtEnd->base));
}
Value ^ReturnInst::getReturnValue()
{
return Value::_wrap(base->getReturnValue());
}
unsigned ReturnInst::getNumSuccessors()
{
return base->getNumSuccessors();
}
inline bool ReturnInst::classof(Instruction ^I)
{
return llvm::ReturnInst::classof(I->base);
}
inline bool ReturnInst::classof(Value ^V)
{
return llvm::ReturnInst::classof(V->base);
}
BranchInst::BranchInst(llvm::BranchInst *base)
: base(base)
, TerminatorInst(base)
{
}
inline BranchInst ^BranchInst::_wrap(llvm::BranchInst *base)
{
return base ? gcnew BranchInst(base) : nullptr;
}
BranchInst::!BranchInst()
{
}
BranchInst::~BranchInst()
{
this->!BranchInst();
}
BranchInst ^BranchInst::Create(BasicBlock ^IfTrue)
{
return BranchInst::_wrap(llvm::BranchInst::Create(IfTrue->base));
}
BranchInst ^BranchInst::Create(BasicBlock ^IfTrue, Instruction ^InsertBefore)
{
return BranchInst::_wrap(llvm::BranchInst::Create(IfTrue->base, InsertBefore->base));
}
BranchInst ^BranchInst::Create(BasicBlock ^IfTrue, BasicBlock ^IfFalse, Value ^Cond)
{
return BranchInst::_wrap(llvm::BranchInst::Create(IfTrue->base, IfFalse->base, Cond->base));
}
BranchInst ^BranchInst::Create(BasicBlock ^IfTrue, BasicBlock ^IfFalse, Value ^Cond, Instruction ^InsertBefore)
{
return BranchInst::_wrap(llvm::BranchInst::Create(IfTrue->base, IfFalse->base, Cond->base, InsertBefore->base));
}
BranchInst ^BranchInst::Create(BasicBlock ^IfTrue, BasicBlock ^InsertAtEnd)
{
return BranchInst::_wrap(llvm::BranchInst::Create(IfTrue->base, InsertAtEnd->base));
}
BranchInst ^BranchInst::Create(BasicBlock ^IfTrue, BasicBlock ^IfFalse, Value ^Cond, BasicBlock ^InsertAtEnd)
{
return BranchInst::_wrap(llvm::BranchInst::Create(IfTrue->base, IfFalse->base, Cond->base, InsertAtEnd->base));
}
bool BranchInst::isUnconditional()
{
return base->isUnconditional();
}
bool BranchInst::isConditional()
{
return base->isConditional();
}
Value ^BranchInst::getCondition()
{
return Value::_wrap(base->getCondition());
}
void BranchInst::setCondition(Value ^V)
{
base->setCondition(V->base);
}
unsigned BranchInst::getNumSuccessors()
{
return base->getNumSuccessors();
}
BasicBlock ^BranchInst::getSuccessor(unsigned i)
{
return BasicBlock::_wrap(base->getSuccessor(i));
}
void BranchInst::setSuccessor(unsigned idx, BasicBlock ^NewSucc)
{
base->setSuccessor(idx, NewSucc->base);
}
void BranchInst::swapSuccessors()
{
base->swapSuccessors();
}
inline bool BranchInst::classof(Instruction ^I)
{
return llvm::BranchInst::classof(I->base);
}
inline bool BranchInst::classof(Value ^V)
{
return llvm::BranchInst::classof(V->base);
}
SwitchInst::SwitchInst(llvm::SwitchInst *base)
: base(base)
, TerminatorInst(base)
{
}
inline SwitchInst ^SwitchInst::_wrap(llvm::SwitchInst *base)
{
return base ? gcnew SwitchInst(base) : nullptr;
}
SwitchInst::!SwitchInst()
{
}
SwitchInst::~SwitchInst()
{
this->!SwitchInst();
}
SwitchInst ^SwitchInst::Create(Value ^Value, BasicBlock ^Default, unsigned NumCases)
{
return SwitchInst::_wrap(llvm::SwitchInst::Create(Value->base, Default->base, NumCases));
}
SwitchInst ^SwitchInst::Create(Value ^Value, BasicBlock ^Default, unsigned NumCases, Instruction ^InsertBefore)
{
return SwitchInst::_wrap(llvm::SwitchInst::Create(Value->base, Default->base, NumCases, InsertBefore->base));
}
SwitchInst ^SwitchInst::Create(Value ^Value, BasicBlock ^Default, unsigned NumCases, BasicBlock ^InsertAtEnd)
{
return SwitchInst::_wrap(llvm::SwitchInst::Create(Value->base, Default->base, NumCases, InsertAtEnd->base));
}
Value ^SwitchInst::getCondition()
{
return Value::_wrap(base->getCondition());
}
void SwitchInst::setCondition(Value ^V)
{
base->setCondition(V->base);
}
BasicBlock ^SwitchInst::getDefaultDest()
{
return BasicBlock::_wrap(base->getDefaultDest());
}
void SwitchInst::setDefaultDest(BasicBlock ^DefaultCase)
{
base->setDefaultDest(DefaultCase->base);
}
unsigned SwitchInst::getNumCases()
{
return base->getNumCases();
}
ConstantInt ^SwitchInst::findCaseDest(BasicBlock ^BB)
{
return ConstantInt::_wrap(base->findCaseDest(BB->base));
}
void SwitchInst::addCase(ConstantInt ^OnVal, BasicBlock ^Dest)
{
base->addCase(OnVal->base, Dest->base);
}
unsigned SwitchInst::getNumSuccessors()
{
return base->getNumSuccessors();
}
BasicBlock ^SwitchInst::getSuccessor(unsigned idx)
{
return BasicBlock::_wrap(base->getSuccessor(idx));
}
void SwitchInst::setSuccessor(unsigned idx, BasicBlock ^NewSucc)
{
base->setSuccessor(idx, NewSucc->base);
}
uint16_t SwitchInst::hash()
{
return base->hash();
}
inline bool SwitchInst::classof(Instruction ^I)
{
return llvm::SwitchInst::classof(I->base);
}
inline bool SwitchInst::classof(Value ^V)
{
return llvm::SwitchInst::classof(V->base);
}
IndirectBrInst::IndirectBrInst(llvm::IndirectBrInst *base)
: base(base)
, TerminatorInst(base)
{
}
inline IndirectBrInst ^IndirectBrInst::_wrap(llvm::IndirectBrInst *base)
{
return base ? gcnew IndirectBrInst(base) : nullptr;
}
IndirectBrInst::!IndirectBrInst()
{
}
IndirectBrInst::~IndirectBrInst()
{
this->!IndirectBrInst();
}
IndirectBrInst ^IndirectBrInst::Create(Value ^Address, unsigned NumDests)
{
return IndirectBrInst::_wrap(llvm::IndirectBrInst::Create(Address->base, NumDests));
}
IndirectBrInst ^IndirectBrInst::Create(Value ^Address, unsigned NumDests, Instruction ^InsertBefore)
{
return IndirectBrInst::_wrap(llvm::IndirectBrInst::Create(Address->base, NumDests, InsertBefore->base));
}
IndirectBrInst ^IndirectBrInst::Create(Value ^Address, unsigned NumDests, BasicBlock ^InsertAtEnd)
{
return IndirectBrInst::_wrap(llvm::IndirectBrInst::Create(Address->base, NumDests, InsertAtEnd->base));
}
Value ^IndirectBrInst::getAddress()
{
return Value::_wrap(base->getAddress());
}
void IndirectBrInst::setAddress(Value ^V)
{
base->setAddress(V->base);
}
unsigned IndirectBrInst::getNumDestinations()
{
return base->getNumDestinations();
}
BasicBlock ^IndirectBrInst::getDestination(unsigned i)
{
return BasicBlock::_wrap(base->getDestination(i));
}
void IndirectBrInst::addDestination(BasicBlock ^Dest)
{
base->addDestination(Dest->base);
}
void IndirectBrInst::removeDestination(unsigned i)
{
base->removeDestination(i);
}
unsigned IndirectBrInst::getNumSuccessors()
{
return base->getNumSuccessors();
}
BasicBlock ^IndirectBrInst::getSuccessor(unsigned i)
{
return BasicBlock::_wrap(base->getSuccessor(i));
}
void IndirectBrInst::setSuccessor(unsigned i, BasicBlock ^NewSucc)
{
base->setSuccessor(i, NewSucc->base);
}
inline bool IndirectBrInst::classof(Instruction ^I)
{
return llvm::IndirectBrInst::classof(I->base);
}
inline bool IndirectBrInst::classof(Value ^V)
{
return llvm::IndirectBrInst::classof(V->base);
}
InvokeInst::InvokeInst(llvm::InvokeInst *base)
: base(base)
, TerminatorInst(base)
{
}
inline InvokeInst ^InvokeInst::_wrap(llvm::InvokeInst *base)
{
return base ? gcnew InvokeInst(base) : nullptr;
}
InvokeInst::!InvokeInst()
{
}
InvokeInst::~InvokeInst()
{
this->!InvokeInst();
}
InvokeInst ^InvokeInst::Create(Value ^Func, BasicBlock ^IfNormal, BasicBlock ^IfException, array<Value ^> ^Args)
{
llvm::Value **b = new llvm::Value*[Args->Length];
for (int i = 0; i < Args->Length; i++)
b[i] = Args[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, Args->Length);
auto r = InvokeInst::_wrap(llvm::InvokeInst::Create(Func->base, IfNormal->base, IfException->base, brr));
delete b;
return r;
}
InvokeInst ^InvokeInst::Create(Value ^Func, BasicBlock ^IfNormal, BasicBlock ^IfException, array<Value ^> ^Args, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[Args->Length];
for (int i = 0; i < Args->Length; i++)
b[i] = Args[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, Args->Length);
auto r = InvokeInst::_wrap(llvm::InvokeInst::Create(Func->base, IfNormal->base, IfException->base, brr, ctx.marshal_as<const char *>(NameStr)));
delete b;
return r;
}
InvokeInst ^InvokeInst::Create(Value ^Func, BasicBlock ^IfNormal, BasicBlock ^IfException, array<Value ^> ^Args, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[Args->Length];
for (int i = 0; i < Args->Length; i++)
b[i] = Args[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, Args->Length);
auto r = InvokeInst::_wrap(llvm::InvokeInst::Create(Func->base, IfNormal->base, IfException->base, brr, ctx.marshal_as<const char *>(NameStr), InsertBefore->base));
delete b;
return r;
}
InvokeInst ^InvokeInst::Create(Value ^Func, BasicBlock ^IfNormal, BasicBlock ^IfException, array<Value ^> ^Args, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
llvm::Value **b = new llvm::Value*[Args->Length];
for (int i = 0; i < Args->Length; i++)
b[i] = Args[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, Args->Length);
auto r = InvokeInst::_wrap(llvm::InvokeInst::Create(Func->base, IfNormal->base, IfException->base, brr, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base));
delete b;
return r;
}
unsigned InvokeInst::getNumArgOperands()
{
return base->getNumArgOperands();
}
Value ^InvokeInst::getArgOperand(unsigned i)
{
return Value::_wrap(base->getArgOperand(i));
}
void InvokeInst::setArgOperand(unsigned i, Value ^v)
{
base->setArgOperand(i, v->base);
}
CallingConv::ID InvokeInst::getCallingConv()
{
return safe_cast<CallingConv::ID>(base->getCallingConv());
}
void InvokeInst::setCallingConv(CallingConv::ID CC)
{
base->setCallingConv(safe_cast<llvm::CallingConv::ID>(CC));
}
void InvokeInst::setAttributes(AttributeSet ^Attrs)
{
base->setAttributes(*Attrs->base);
}
void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr)
{
base->addAttribute(i, safe_cast<llvm::Attribute::AttrKind>(attr));
}
void InvokeInst::removeAttribute(unsigned i, Attribute ^attr)
{
base->removeAttribute(i, *attr->base);
}
bool InvokeInst::hasFnAttr(Attribute::AttrKind A)
{
return base->hasFnAttr(safe_cast<llvm::Attribute::AttrKind>(A));
}
bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A)
{
return base->paramHasAttr(i, safe_cast<llvm::Attribute::AttrKind>(A));
}
unsigned InvokeInst::getParamAlignment(unsigned i)
{
return base->getParamAlignment(i);
}
bool InvokeInst::isNoInline()
{
return base->isNoInline();
}
void InvokeInst::setIsNoInline()
{
base->setIsNoInline();
}
bool InvokeInst::doesNotAccessMemory()
{
return base->doesNotAccessMemory();
}
void InvokeInst::setDoesNotAccessMemory()
{
base->setDoesNotAccessMemory();
}
bool InvokeInst::onlyReadsMemory()
{
return base->onlyReadsMemory();
}
void InvokeInst::setOnlyReadsMemory()
{
base->setOnlyReadsMemory();
}
bool InvokeInst::doesNotReturn()
{
return base->doesNotReturn();
}
void InvokeInst::setDoesNotReturn()
{
base->setDoesNotReturn();
}
bool InvokeInst::doesNotThrow()
{
return base->doesNotThrow();
}
void InvokeInst::setDoesNotThrow()
{
base->setDoesNotThrow();
}
bool InvokeInst::hasStructRetAttr()
{
return base->hasStructRetAttr();
}
bool InvokeInst::hasByValArgument()
{
return base->hasByValArgument();
}
Function ^InvokeInst::getCalledFunction()
{
return Function::_wrap(base->getCalledFunction());
}
Value ^InvokeInst::getCalledValue()
{
return Value::_wrap(base->getCalledValue());
}
void InvokeInst::setCalledFunction(Value ^Fn)
{
base->setCalledFunction(Fn->base);
}
BasicBlock ^InvokeInst::getNormalDest()
{
return BasicBlock::_wrap(base->getNormalDest());
}
BasicBlock ^InvokeInst::getUnwindDest()
{
return BasicBlock::_wrap(base->getUnwindDest());
}
void InvokeInst::setNormalDest(BasicBlock ^B)
{
base->setNormalDest(B->base);
}
void InvokeInst::setUnwindDest(BasicBlock ^B)
{
base->setUnwindDest(B->base);
}
LandingPadInst ^InvokeInst::getLandingPadInst()
{
return LandingPadInst::_wrap(base->getLandingPadInst());
}
BasicBlock ^InvokeInst::getSuccessor(unsigned i)
{
return BasicBlock::_wrap(base->getSuccessor(i));
}
void InvokeInst::setSuccessor(unsigned idx, BasicBlock ^NewSucc)
{
base->setSuccessor(idx, NewSucc->base);
}
unsigned InvokeInst::getNumSuccessors()
{
return base->getNumSuccessors();
}
inline bool InvokeInst::classof(Instruction ^I)
{
return llvm::InvokeInst::classof(I->base);
}
inline bool InvokeInst::classof(Value ^V)
{
return llvm::InvokeInst::classof(V->base);
}
ResumeInst::ResumeInst(llvm::ResumeInst *base)
: base(base)
, TerminatorInst(base)
{
}
inline ResumeInst ^ResumeInst::_wrap(llvm::ResumeInst *base)
{
return base ? gcnew ResumeInst(base) : nullptr;
}
ResumeInst::!ResumeInst()
{
}
ResumeInst::~ResumeInst()
{
this->!ResumeInst();
}
ResumeInst ^ResumeInst::Create(Value ^Exn)
{
return ResumeInst::_wrap(llvm::ResumeInst::Create(Exn->base));
}
ResumeInst ^ResumeInst::Create(Value ^Exn, Instruction ^InsertBefore)
{
return ResumeInst::_wrap(llvm::ResumeInst::Create(Exn->base, InsertBefore->base));
}
ResumeInst ^ResumeInst::Create(Value ^Exn, BasicBlock ^InsertAtEnd)
{
return ResumeInst::_wrap(llvm::ResumeInst::Create(Exn->base, InsertAtEnd->base));
}
Value ^ResumeInst::getValue()
{
return Value::_wrap(base->getValue());
}
unsigned ResumeInst::getNumSuccessors()
{
return base->getNumSuccessors();
}
inline bool ResumeInst::classof(Instruction ^I)
{
return llvm::ResumeInst::classof(I->base);
}
inline bool ResumeInst::classof(Value ^V)
{
return llvm::ResumeInst::classof(V->base);
}
UnreachableInst::UnreachableInst(llvm::UnreachableInst *base)
: base(base)
, TerminatorInst(base)
, constructed(false)
{
}
inline UnreachableInst ^UnreachableInst::_wrap(llvm::UnreachableInst *base)
{
return base ? gcnew UnreachableInst(base) : nullptr;
}
UnreachableInst::!UnreachableInst()
{
if (constructed)
{
delete base;
}
}
UnreachableInst::~UnreachableInst()
{
this->!UnreachableInst();
}
UnreachableInst::UnreachableInst(LLVMContext ^C)
: base(new llvm::UnreachableInst(*C->base))
, TerminatorInst(base)
, constructed(true)
{
}
UnreachableInst::UnreachableInst(LLVMContext ^C, Instruction ^InsertBefore)
: base(new llvm::UnreachableInst(*C->base, InsertBefore->base))
, TerminatorInst(base)
, constructed(true)
{
}
UnreachableInst::UnreachableInst(LLVMContext ^C, BasicBlock ^InsertAtEnd)
: base(new llvm::UnreachableInst(*C->base, InsertAtEnd->base))
, TerminatorInst(base)
, constructed(true)
{
}
unsigned UnreachableInst::getNumSuccessors()
{
return base->getNumSuccessors();
}
inline bool UnreachableInst::classof(Instruction ^I)
{
return llvm::UnreachableInst::classof(I->base);
}
inline bool UnreachableInst::classof(Value ^V)
{
return llvm::UnreachableInst::classof(V->base);
}
TruncInst::TruncInst(llvm::TruncInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline TruncInst ^TruncInst::_wrap(llvm::TruncInst *base)
{
return base ? gcnew TruncInst(base) : nullptr;
}
TruncInst::!TruncInst()
{
if (constructed)
{
delete base;
}
}
TruncInst::~TruncInst()
{
this->!TruncInst();
}
TruncInst::TruncInst(Value ^S, Type ^Ty)
: base(new llvm::TruncInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::TruncInst *TruncInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::TruncInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
TruncInst::TruncInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::TruncInst *TruncInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::TruncInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
TruncInst::TruncInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::TruncInst *TruncInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::TruncInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
TruncInst::TruncInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
inline bool TruncInst::classof(Instruction ^I)
{
return llvm::TruncInst::classof(I->base);
}
inline bool TruncInst::classof(Value ^V)
{
return llvm::TruncInst::classof(V->base);
}
ZExtInst::ZExtInst(llvm::ZExtInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline ZExtInst ^ZExtInst::_wrap(llvm::ZExtInst *base)
{
return base ? gcnew ZExtInst(base) : nullptr;
}
ZExtInst::!ZExtInst()
{
if (constructed)
{
delete base;
}
}
ZExtInst::~ZExtInst()
{
this->!ZExtInst();
}
ZExtInst::ZExtInst(Value ^S, Type ^Ty)
: base(new llvm::ZExtInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::ZExtInst *ZExtInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::ZExtInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
ZExtInst::ZExtInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::ZExtInst *ZExtInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::ZExtInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
ZExtInst::ZExtInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::ZExtInst *ZExtInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::ZExtInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
ZExtInst::ZExtInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
inline bool ZExtInst::classof(Instruction ^I)
{
return llvm::ZExtInst::classof(I->base);
}
inline bool ZExtInst::classof(Value ^V)
{
return llvm::ZExtInst::classof(V->base);
}
SExtInst::SExtInst(llvm::SExtInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline SExtInst ^SExtInst::_wrap(llvm::SExtInst *base)
{
return base ? gcnew SExtInst(base) : nullptr;
}
SExtInst::!SExtInst()
{
if (constructed)
{
delete base;
}
}
SExtInst::~SExtInst()
{
this->!SExtInst();
}
SExtInst::SExtInst(Value ^S, Type ^Ty)
: base(new llvm::SExtInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::SExtInst *SExtInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::SExtInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
SExtInst::SExtInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::SExtInst *SExtInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::SExtInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
SExtInst::SExtInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::SExtInst *SExtInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::SExtInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
SExtInst::SExtInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
inline bool SExtInst::classof(Instruction ^I)
{
return llvm::SExtInst::classof(I->base);
}
inline bool SExtInst::classof(Value ^V)
{
return llvm::SExtInst::classof(V->base);
}
FPTruncInst::FPTruncInst(llvm::FPTruncInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline FPTruncInst ^FPTruncInst::_wrap(llvm::FPTruncInst *base)
{
return base ? gcnew FPTruncInst(base) : nullptr;
}
FPTruncInst::!FPTruncInst()
{
if (constructed)
{
delete base;
}
}
FPTruncInst::~FPTruncInst()
{
this->!FPTruncInst();
}
FPTruncInst::FPTruncInst(Value ^S, Type ^Ty)
: base(new llvm::FPTruncInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::FPTruncInst *FPTruncInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::FPTruncInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
FPTruncInst::FPTruncInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::FPTruncInst *FPTruncInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::FPTruncInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
FPTruncInst::FPTruncInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::FPTruncInst *FPTruncInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::FPTruncInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
FPTruncInst::FPTruncInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
inline bool FPTruncInst::classof(Instruction ^I)
{
return llvm::FPTruncInst::classof(I->base);
}
inline bool FPTruncInst::classof(Value ^V)
{
return llvm::FPTruncInst::classof(V->base);
}
FPExtInst::FPExtInst(llvm::FPExtInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline FPExtInst ^FPExtInst::_wrap(llvm::FPExtInst *base)
{
return base ? gcnew FPExtInst(base) : nullptr;
}
FPExtInst::!FPExtInst()
{
if (constructed)
{
delete base;
}
}
FPExtInst::~FPExtInst()
{
this->!FPExtInst();
}
FPExtInst::FPExtInst(Value ^S, Type ^Ty)
: base(new llvm::FPExtInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::FPExtInst *FPExtInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::FPExtInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
FPExtInst::FPExtInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::FPExtInst *FPExtInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::FPExtInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
FPExtInst::FPExtInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::FPExtInst *FPExtInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::FPExtInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
FPExtInst::FPExtInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
inline bool FPExtInst::classof(Instruction ^I)
{
return llvm::FPExtInst::classof(I->base);
}
inline bool FPExtInst::classof(Value ^V)
{
return llvm::FPExtInst::classof(V->base);
}
UIToFPInst::UIToFPInst(llvm::UIToFPInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline UIToFPInst ^UIToFPInst::_wrap(llvm::UIToFPInst *base)
{
return base ? gcnew UIToFPInst(base) : nullptr;
}
UIToFPInst::!UIToFPInst()
{
if (constructed)
{
delete base;
}
}
UIToFPInst::~UIToFPInst()
{
this->!UIToFPInst();
}
UIToFPInst::UIToFPInst(Value ^S, Type ^Ty)
: base(new llvm::UIToFPInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::UIToFPInst *UIToFPInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::UIToFPInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
UIToFPInst::UIToFPInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::UIToFPInst *UIToFPInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::UIToFPInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
UIToFPInst::UIToFPInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::UIToFPInst *UIToFPInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::UIToFPInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
UIToFPInst::UIToFPInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
inline bool UIToFPInst::classof(Instruction ^I)
{
return llvm::UIToFPInst::classof(I->base);
}
inline bool UIToFPInst::classof(Value ^V)
{
return llvm::UIToFPInst::classof(V->base);
}
SIToFPInst::SIToFPInst(llvm::SIToFPInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline SIToFPInst ^SIToFPInst::_wrap(llvm::SIToFPInst *base)
{
return base ? gcnew SIToFPInst(base) : nullptr;
}
SIToFPInst::!SIToFPInst()
{
if (constructed)
{
delete base;
}
}
SIToFPInst::~SIToFPInst()
{
this->!SIToFPInst();
}
SIToFPInst::SIToFPInst(Value ^S, Type ^Ty)
: base(new llvm::SIToFPInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::SIToFPInst *SIToFPInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::SIToFPInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
SIToFPInst::SIToFPInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::SIToFPInst *SIToFPInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::SIToFPInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
SIToFPInst::SIToFPInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::SIToFPInst *SIToFPInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::SIToFPInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
SIToFPInst::SIToFPInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
inline bool SIToFPInst::classof(Instruction ^I)
{
return llvm::SIToFPInst::classof(I->base);
}
inline bool SIToFPInst::classof(Value ^V)
{
return llvm::SIToFPInst::classof(V->base);
}
FPToUIInst::FPToUIInst(llvm::FPToUIInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline FPToUIInst ^FPToUIInst::_wrap(llvm::FPToUIInst *base)
{
return base ? gcnew FPToUIInst(base) : nullptr;
}
FPToUIInst::!FPToUIInst()
{
if (constructed)
{
delete base;
}
}
FPToUIInst::~FPToUIInst()
{
this->!FPToUIInst();
}
FPToUIInst::FPToUIInst(Value ^S, Type ^Ty)
: base(new llvm::FPToUIInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::FPToUIInst *FPToUIInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::FPToUIInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
FPToUIInst::FPToUIInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::FPToUIInst *FPToUIInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::FPToUIInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
FPToUIInst::FPToUIInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::FPToUIInst *FPToUIInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::FPToUIInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
FPToUIInst::FPToUIInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
inline bool FPToUIInst::classof(Instruction ^I)
{
return llvm::FPToUIInst::classof(I->base);
}
inline bool FPToUIInst::classof(Value ^V)
{
return llvm::FPToUIInst::classof(V->base);
}
FPToSIInst::FPToSIInst(llvm::FPToSIInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline FPToSIInst ^FPToSIInst::_wrap(llvm::FPToSIInst *base)
{
return base ? gcnew FPToSIInst(base) : nullptr;
}
FPToSIInst::!FPToSIInst()
{
if (constructed)
{
delete base;
}
}
FPToSIInst::~FPToSIInst()
{
this->!FPToSIInst();
}
FPToSIInst::FPToSIInst(Value ^S, Type ^Ty)
: base(new llvm::FPToSIInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::FPToSIInst *FPToSIInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::FPToSIInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
FPToSIInst::FPToSIInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::FPToSIInst *FPToSIInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::FPToSIInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
FPToSIInst::FPToSIInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::FPToSIInst *FPToSIInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::FPToSIInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
FPToSIInst::FPToSIInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
inline bool FPToSIInst::classof(Instruction ^I)
{
return llvm::FPToSIInst::classof(I->base);
}
inline bool FPToSIInst::classof(Value ^V)
{
return llvm::FPToSIInst::classof(V->base);
}
IntToPtrInst::IntToPtrInst(llvm::IntToPtrInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline IntToPtrInst ^IntToPtrInst::_wrap(llvm::IntToPtrInst *base)
{
return base ? gcnew IntToPtrInst(base) : nullptr;
}
IntToPtrInst::!IntToPtrInst()
{
if (constructed)
{
delete base;
}
}
IntToPtrInst::~IntToPtrInst()
{
this->!IntToPtrInst();
}
IntToPtrInst::IntToPtrInst(Value ^S, Type ^Ty)
: base(new llvm::IntToPtrInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::IntToPtrInst *IntToPtrInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::IntToPtrInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
IntToPtrInst::IntToPtrInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::IntToPtrInst *IntToPtrInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::IntToPtrInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
IntToPtrInst::IntToPtrInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::IntToPtrInst *IntToPtrInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::IntToPtrInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
IntToPtrInst::IntToPtrInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
IntToPtrInst ^IntToPtrInst::clone_impl()
{
return IntToPtrInst::_wrap(base->clone_impl());
}
unsigned IntToPtrInst::getAddressSpace()
{
return base->getAddressSpace();
}
inline bool IntToPtrInst::classof(Instruction ^I)
{
return llvm::IntToPtrInst::classof(I->base);
}
inline bool IntToPtrInst::classof(Value ^V)
{
return llvm::IntToPtrInst::classof(V->base);
}
PtrToIntInst::PtrToIntInst(llvm::PtrToIntInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline PtrToIntInst ^PtrToIntInst::_wrap(llvm::PtrToIntInst *base)
{
return base ? gcnew PtrToIntInst(base) : nullptr;
}
PtrToIntInst::!PtrToIntInst()
{
if (constructed)
{
delete base;
}
}
PtrToIntInst::~PtrToIntInst()
{
this->!PtrToIntInst();
}
PtrToIntInst::PtrToIntInst(Value ^S, Type ^Ty)
: base(new llvm::PtrToIntInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::PtrToIntInst *PtrToIntInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::PtrToIntInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
PtrToIntInst::PtrToIntInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::PtrToIntInst *PtrToIntInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::PtrToIntInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
PtrToIntInst::PtrToIntInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::PtrToIntInst *PtrToIntInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::PtrToIntInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
PtrToIntInst::PtrToIntInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
Value ^PtrToIntInst::getPointerOperand()
{
return Value::_wrap(base->getPointerOperand());
}
unsigned PtrToIntInst::getPointerOperandIndex()
{
return llvm::PtrToIntInst::getPointerOperandIndex();
}
unsigned PtrToIntInst::getPointerAddressSpace()
{
return base->getPointerAddressSpace();
}
inline bool PtrToIntInst::classof(Instruction ^I)
{
return llvm::PtrToIntInst::classof(I->base);
}
inline bool PtrToIntInst::classof(Value ^V)
{
return llvm::PtrToIntInst::classof(V->base);
}
BitCastInst::BitCastInst(llvm::BitCastInst *base)
: base(base)
, CastInst(base)
, constructed(false)
{
}
inline BitCastInst ^BitCastInst::_wrap(llvm::BitCastInst *base)
{
return base ? gcnew BitCastInst(base) : nullptr;
}
BitCastInst::!BitCastInst()
{
if (constructed)
{
delete base;
}
}
BitCastInst::~BitCastInst()
{
this->!BitCastInst();
}
BitCastInst::BitCastInst(Value ^S, Type ^Ty)
: base(new llvm::BitCastInst(S->base, Ty->base))
, CastInst(base)
, constructed(true)
{
}
llvm::BitCastInst *BitCastInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr)
{
msclr::interop::marshal_context ctx;
return new llvm::BitCastInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr));
}
BitCastInst::BitCastInst(Value ^S, Type ^Ty, System::String ^NameStr)
: base(_construct(S, Ty, NameStr))
, CastInst(base)
, constructed(true)
{
}
llvm::BitCastInst *BitCastInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
{
msclr::interop::marshal_context ctx;
return new llvm::BitCastInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertBefore->base);
}
BitCastInst::BitCastInst(Value ^S, Type ^Ty, System::String ^NameStr, Instruction ^InsertBefore)
: base(_construct(S, Ty, NameStr, InsertBefore))
, CastInst(base)
, constructed(true)
{
}
llvm::BitCastInst *BitCastInst::_construct(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
{
msclr::interop::marshal_context ctx;
return new llvm::BitCastInst(S->base, Ty->base, ctx.marshal_as<const char *>(NameStr), InsertAtEnd->base);
}
BitCastInst::BitCastInst(Value ^S, Type ^Ty, System::String ^NameStr, BasicBlock ^InsertAtEnd)
: base(_construct(S, Ty, NameStr, InsertAtEnd))
, CastInst(base)
, constructed(true)
{
}
inline bool BitCastInst::classof(Instruction ^I)
{
return llvm::BitCastInst::classof(I->base);
}
inline bool BitCastInst::classof(Value ^V)
{
return llvm::BitCastInst::classof(V->base);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser.
** It may not be distributed under any circumstances.
**
** Yngve Pettersen
*/
#ifndef LIBSSL_CHCIPHER_H
#define LIBSSL_CHCIPHER_H
#if defined _NATIVE_SSL_SUPPORT_
class SSL_ChangeCipherSpec_st: public LoadAndWritableList
{
public:
SSL_ChangeCipherSpec_st();
virtual void PerformActionL(DataStream::DatastreamAction action, uint32 arg1=0, uint32 arg2=0);
#ifdef _DATASTREAM_DEBUG_
protected:
virtual const char *Debug_ClassName(){return "SSL_ChangeCipherSpec_st";}
#endif
};
#endif
#endif // LIBSSL_CHCIPHER_H
|
// Programmable-Air
// Author: tinkrmind
// https://github.com/orgs/Programmable-Air
//
// Factory Image
//
// PCB v1.0
#define BOARD_VER 6
#include "programmable_air.h"
#include <Adafruit_NeoPixel.h>
#include "EEPROMAnything.h"
Adafruit_NeoPixel paPixels(3, 12, NEO_GRB + NEO_KHZ800);
#define DEBUG 1
int state = UN_KNOWN;
#define MOTORS_ON 6
#define MOTORS_OFF 7
int calibratedPressure = 0;
const char helpText[] PROGMEM =
"\t\t\tWelcome to the Programmable - Air kit! \n\n"
" _______________________________________|--|________________________________\n"
" /__ RED BTN BLUE BTN POWER | |__| | NEOPIXELS (PIN 12) __\\ \n"
" | | (PIN3) (PIN2) + 12V | | | | \n"
" | | __ | | __ | | \n"
" | | | N | | | \n"
" | | / \\ | A | / \\ | | \n"
" | | PUMP 1 | N | PUMP 2 | | \n"
" |___| | (PIN 10) | | O | | (PIN 11) | |___| \n"
" | SUCK | | BLOW | \n"
" | \\ / | | \\ / | \n"
" | __ | | __ | \n"
" | _____________ | \n"
" \\ / \n"
" ---------------------------------------------------------------------------- \n"
" / \\ \n"
" | PRESSURE SENSOR(A3) | \n"
" | ___ ___ ___ | \n"
" | | \n"
" | / \\ / \\ / \\ | \n"
" | | VALVE 1 | | VALVE 2 | | VALVE 3 | | \n"
" | | (PIN 6) | | (PIN 5) | | (PIN 4) | | \n"
" | \\ VENT / \\ BLOW / \\ SUCK / | \n"
" | ___ ___ ___ | \n"
" | YELLOW BTN GREEN BTN WHITE BTN | \n"
" \\ ________________________________________________________________________ / \n\n"
"\tI hope you're ready to experiment with air, because Programmable-Air is! \n\n"
"Here's how to get started: \n"
"\t * Right now, the vent valve(next to YELLOW button) is switched on, \n"
"\t and the output tube can freely exchange air with the atmosphere. \n"
"\t * Press the RED button to blow air out of the output tube. \n"
"\t * Press the BLUE button to suck air into the output tube. \n"
"\t * Press both RED and BLUE buttons together to switch the motors on or off. \n"
"\t * When the motors are ON, all the valves will switch off by default. \n"
"\t You can now press the WHITE, GREEN, and YELLOW buttons \n"
"\t to suck air in, blow air out, and vent air to the atmosphere respectively. \n"
"\t * All this while, the pressure is being reported on the neopixel; \n"
"\t bright cyan is low pressure and bright purple is high pressure. \n"
"\t * If the neopixels are dim or off, pressure is close to the atmospheric pressure. \n"
"\t (Atleast in Manhattan on Saturday Oct 26th around 6pm, when I calibrated this board!) \n"
"\t * The pressure is also being reported in the Serial port as numbers \n"
"\t (which is why you had to scroll so much to see this message :P ) \n"
"\t * To test the device block the output tube and send 'test' over serial. \n"
"\t * Try sending 'music' or 'help' over serial :)\n\n"
"\t\t\t\tHappy hacking!\n"
"\t\t\t\t\t\t\t\t\t-tinkrmind \n"
"------------------------------------------------------------------------------------ \n";
void setup() {
initializePins();
pixels.begin();
pixels.show();
paPixels.begin();
paPixels.show();
if (readBtn(BLUE) && readBtn(RED)) {
testMode();
}
printHelpText();
}
void loop() {
if (Serial.available()) {
String data = Serial.readString();
if (data == "test" || data == "test\n" || data == "test\r\n" || data == "test\r") {
testMode();
}
if (data == "help" || data == "help\n" || data == "help\r\n" || data == "help\r") {
printHelpText();
}
if (data == "music" || data == "music\n" || data == "music\r\n" || data == "music\r") {
playMusic();
}
if (data == "allGood" || data == "allGood\n" || data == "allGood\r\n" || data == "allGood\r") {
allGood();
}
if (data == "allBad" || data == "allBad\n" || data == "allBad\r\n" || data == "allBad\r") {
allBad();
}
}
showPressure();
if (readBtn(BLUE) && readBtn(RED)) {
if (state == MOTORS_ON) {
switchOffPumps();
closeAllValves();
state = MOTORS_OFF;
}
else {
switchOnPumps(100);
closeAllValves();
state = MOTORS_ON;
}
while (readBtn(BLUE) && readBtn(RED));
delay(50);
}
// If blue button is pressed start sucking
if (readBtn(BLUE) && state != SUCKING) {
// switch on pumps to 50% power
switchOnPump(1, 100);
switchOffPump(2);
suck();
state = SUCKING;
}
// if red button is pressed, start blowing
else if (readBtn(RED) && state != BLOWING) {
// switch on pumps to 50% power
switchOnPump(2, 100);
switchOffPump(1);
blow();
state = BLOWING;
}
// if nither button is pressed, vent (but blow for a bit to let go of the object)
else if (!readBtn(BLUE) && !readBtn(RED) && state != VENTING && state != MOTORS_ON) {
// switchOnPump(1, 100);
// blow();
// delayWhileReadingPressure(250);
switchOffPumps();
vent();
state = VENTING;
}
delayWhileReadingPressure(200);
}
void testMode() {
for (int i = 0; i < 3; i++) {
paPixels.setPixelColor(i, paPixels.Color(0, 0, 100));
}
paPixels.show();
// check that pressure sensor is working
vent();
delay(1000);
int calibratedPressure = readPressure(1, 10);
Serial.print("Calibrated Pressure : ");
Serial.println(calibratedPressure);
if (calibratedPressure < 450 || calibratedPressure > 575) {
error();
}
EEPROM_writeAnything(0, calibratedPressure);
// check that high pressure is being generated
closeAllValves();
switchOffPumps();
delay(100);
switchOnPump(2);
blow();
delay(1000);
int highPressure = readPressure(1, 10);
Serial.print("High Pressure : ");
Serial.println(highPressure);
EEPROM_writeAnything(4, highPressure);
if (highPressure < 750) {
error();
}
// check that low pressure is generated
closeAllValves();
switchOffPumps();
delay(1000);
switchOnPump(1);
suck();
delay(1000);
int lowPressure = readPressure(1, 10);
Serial.print("Low Pressure : ");
Serial.println(lowPressure);
EEPROM_writeAnything(8, lowPressure);
if (lowPressure > 225) {
error();
}
// check that pressure is held
closeAllValves();
switchOffPumps();
delay(1000);
int heldPressure = readPressure(1, 10);
Serial.print("Held Pressure : ");
Serial.println(heldPressure);
EEPROM_writeAnything(12, heldPressure);
if (abs(lowPressure - heldPressure) > 10) {
error();
}
// check that venting works
closeAllValves();
switchOffPumps();
vent();
delay(1000);
int ventPressure = readPressure(1, 10);
Serial.print("Vent Pressure : ");
Serial.println(ventPressure);
EEPROM_writeAnything(16, ventPressure);
if (abs(ventPressure - calibratedPressure) > 10) {
error();
}
// Test if blow/suck valves leak
switchOnPumps();
delay(5000);
int witheldPressure = readPressure(1, 10);
Serial.print("witheldPressure Pressure : ");
Serial.println(witheldPressure);
EEPROM_writeAnything(16, witheldPressure);
if (abs(witheldPressure - calibratedPressure) > 10) {
error();
}
Serial.println("TESTED OK");
for (int i = 0; i < 3; i++) {
paPixels.setPixelColor(i, paPixels.Color(0, 100, 0));
}
paPixels.show();
allGood();
delay(1000);
}
void error() {
Serial.println("ERROR");
for (int i = 0; i < 3; i++) {
paPixels.setPixelColor(i, paPixels.Color(100, 0, 0));
}
paPixels.show();
allBad();
switchOffPumps();
closeAllValves();
while (1);
}
void printHelpText() {
char myChar;
for (int k = 0; k < strlen_P(helpText); k++) {
myChar = pgm_read_byte_near(helpText + k);
Serial.print(myChar);
}
}
void playMusic() {
int notes[] = {
70, 80, 100, 90,
70, 80, 100, 90,
70, 80, 100, 90,
70, 70, 90, 100,
80, 80, 100, 90,
80, 80, 100, 90,
70, 80, 100, 90,
70, 80, 100, 90,
70, 70, 90, 100,
50, 60, 70, 80
};
int actionDelay = 80;
int offTimeDelay = 105;
int sizeOfNotes = sizeof(notes) / sizeof(notes[0]);
int increaseSpeedPoint = 13;
Serial.println("Music sequence playing");
for (int i = 0; i <= sizeOfNotes - 1; i++) {
switchOnPump(1, notes[i]);
suck();
delay(actionDelay);
switchOffPumps();
delay(offTimeDelay);
switchOnPump(1, notes[i]);
blow();
delay(actionDelay);
switchOffPumps();
vent();
delay(actionDelay);
switchOffPumps();
delay(offTimeDelay);
if (i >= sizeOfNotes - increaseSpeedPoint) {
offTimeDelay = offTimeDelay * .8;
actionDelay = offTimeDelay * .8;
}
}
}
void allGood() {
int notes[] = {70, 80, 100};
int actionDelay = 300;
int sizeOfNotes = sizeof(notes) / sizeof(notes[0]);
Serial.println("Everything is good! :) ");
for (int i = 0; i <= sizeOfNotes - 1; i++) {
switchOnPump(1, notes[i]);
suck();
delay(actionDelay);
switchOffPumps();
}
}
void allBad() {
int notes[] = {100, 80, 70};
int actionDelay = 420;
int sizeOfNotes = sizeof(notes) / sizeof(notes[0]);
Serial.println("Err, something went wrong :( ");
for (int i = 0; i <= sizeOfNotes - 1; i++) {
if (i == sizeOfNotes - 1) {
actionDelay = 600;
}
switchOnPump(1, notes[i]);
suck();
delay(actionDelay);
switchOffPumps();
Serial.print("i: ");
Serial.println(i);
}
}
|
#pragma once
#include <YouMeCommon/CrossPlatformDefine/PlatformDef.h>
#include <memory>
#include <YouMeCommon/XAny.h>
#include <YouMeCommon/XSharedArray.h>
namespace youmecommon {
enum VariantType
{
VariantType_Unknow,
VariantType_String,
VariantType_Byte,
VariantType_INT16,
VariantType_INT32,
VariantType_INT64,
VariantType_Float,
VariantType_Double,
VariantType_Bool,
VariantType_Array,
VariantType_Dict,
VariantType_Buffer,
};
class CXVariant
{
public:
CXVariant(void);
~CXVariant(void);
void Clear();
//各种构造函数
CXVariant (const XCHAR* value);
CXVariant (const XString& value);
CXVariant(byte value);
CXVariant(short value);
CXVariant(int value);
CXVariant(XINT64 value);
CXVariant(float value);
CXVariant(double value);
//主要是为了避免 char 和 wchar 的混用,强制不能隐式转换成bool 类型
explicit CXVariant(bool value);
CXVariant(const std::map<std::string,CXVariant >& value);
CXVariant(const std::vector<CXVariant >& value);
void SetBuffer(const byte* value,int iSize);
//针对变体的操作
void Add( const std::string& key,const CXVariant& value);
void Add( const CXVariant& value);
//返回的数据里面各种int和int64 混合,为了方便提供一个函数
XINT64 ToInt() const;
XString ToString() const;
//提供一些get 函数
template <typename T>
T Get() const
{
return ::youmecommon::CXAny::XAny_Cast<T>(m_any);
}
template <typename T>
T* GetP() const
{
return ::youmecommon::CXAny::XAny_Cast<T>(&m_any);
}
//对string 做特化处理
XString Get() const
{
std::shared_ptr<XString>* pPtr = ::youmecommon::CXAny::XAny_Cast<std::shared_ptr<XString> >(&m_any);
if (NULL != pPtr)
{
return *(pPtr->get());
}
return __XT("");
}
//把自身的内容给对方,直接使用swap,否则可能会释放两次
void Detach(CXVariant* value);
//数据类型
VariantType m_vType;
//保留的变量,用来补充各种数据类型的,比如缓存的大小
int m_iUnUsed;
//使用any 来代表任意值
::youmecommon::CXAny m_any;
};
}
|
#include "Camera.h"
#include <cmath>
using Mat4D::CVector4D;
using Mat4D::CMatrix4D;
Camera::Camera() :
m_fPitch{ 0 },
m_fYaw{ 0 },
m_fRoll{ 0 },
m_fOffset{ 1000.f },
m_fUpLock{ 3.141592f * 0.35f },
m_fDownLock{ -3.141592f * 0.35f }
{
}
Camera::Camera( const CVector4D & Position, const CVector4D & Up, float fPitch, float fYaw, float fRoll ) :
m_position{ Position },
m_up{ Up },
m_fPitch{ fPitch },
m_fYaw{ fYaw },
m_fRoll{ fRoll },
m_fOffset{ 1000.f },
m_fUpLock{ 3.141592f * 0.35f },
m_fDownLock{ -3.141592f * 0.35f }
{
}
void Camera::CreateProjection( float fFOV, float fAspect, float fNearPlane, float fFarPlane )
{
m_info.x = fNearPlane;
m_info.y = fFarPlane;
m_info.z = fFOV;
m_info.w = 1.f;
m_projection = Mat4PerspectiveFov( fFOV, fAspect, fNearPlane, fFarPlane );
}
void Camera::CreateProjOrtho( float w, float h, float nearPlane, float farPlane )
{
m_projection.Identity();
m_info.x = nearPlane;
m_info.y = farPlane;
m_info.z = 1.f;
m_info.w = 1.f;
m_projection.m[0][0] = 2.0f / w;
m_projection.m[1][1] = 2.0f / h;
m_projection.m[2][2] = 1.0f / ( nearPlane - farPlane );
m_projection.m[3][2] = nearPlane / ( nearPlane - farPlane );
}
void Camera::SetPosition( const CVector4D & Position )
{
m_position = Position;
}
CVector4D Camera::GetPosition()
{
return m_position;
}
Mat4D::CVector4D Camera::GetInfo()
{
return m_info;
}
CVector4D Camera::GetDirection()
{
return CVector4D
{
cosf( m_fPitch ) * sinf( m_fYaw ),
sinf( m_fPitch ),
cosf( m_fPitch ) * cosf( m_fYaw ), 0.f
}.Normalize();
}
CVector4D Camera::GetRightVector()
{
return GetDirection().Cross( m_up ).Normalize();
}
Mat4D::CMatrix4D Camera::GetView()
{
return Mat4LookAt( m_position, m_position + GetDirection() * m_fOffset, m_up );
}
void Camera::SetScale( const CVector4D & scale )
{
m_scale = Mat4D::Scale( scale.x, scale.y, scale.z );
}
void Camera::SetUp( const CVector4D & up )
{
m_up = up;
}
void Camera::SetOffset( float fOffset )
{
m_fOffset = fOffset;
}
void Camera::Move( const CVector4D & Distance )
{
m_position += Distance;
}
void Camera::MoveForward( float fDistance )
{
m_position += GetDirection() * fDistance;
}
void Camera::MoveBackward( float fDistance )
{
m_position -= GetDirection() * fDistance;
}
void Camera::MoveLeft( float fDistance )
{
m_position -= GetRightVector() * fDistance;
}
void Camera::MoveRight( float fDistance )
{
m_position += GetRightVector() * fDistance;
}
void Camera::MoveUp( float fDistance )
{
m_position.y += fDistance;
}
void Camera::MoveDown( float fDistance )
{
m_position.y -= fDistance;
}
void Camera::MovePitch( float fDistance )
{
m_fPitch = fmaxf(m_fDownLock, fminf(m_fUpLock, m_fPitch + fDistance));
}
void Camera::SetPicth( float fPitch )
{
m_fPitch = fPitch;
}
void Camera::MoveYaw( float fDistance )
{
m_fYaw += fDistance;
}
void Camera::SetYaw( float fYaw )
{
m_fYaw = fYaw;
}
void Camera::SetLocks( float fUp, float fDown )
{
m_fUpLock = fUp;
m_fDownLock = fDown;
}
CMatrix4D Camera::GetVP()
{
CMatrix4D vp;
vp = GetView() * m_projection;
return vp;
}
|
#include <ionir/passes/pass.h>
namespace ionir {
StoreInst::StoreInst(const StoreInstOpts &opts) :
Inst(opts.parent, InstKind::Store),
value(opts.value),
target(opts.target) {
//
}
void StoreInst::accept(Pass &visitor) {
visitor.visitStoreInst(this->dynamicCast<StoreInst>());
}
Ast StoreInst::getChildrenNodes() {
return {
this->value,
this->target
};
}
}
|
#ifndef SHADER_H
#define SHADER_H
#include <Common.h>
class CShader
{
public:
CShader(GLenum type, const std::string &source);
~CShader();
GLuint getId() const
{
return _id;
}
private:
GLuint _id;
void compile(const std::string &source);
void check(GLenum status);
};
#endif // SHADER_H
|
#include <iostream>
#include <algorithm>
#include <fstream>
using namespace std;
const int mmax = 256;
ifstream fi("INPUT.INP");
ofstream fo("OUTPUT.OUT");
int n, m;
int dd[mmax];
void set(){
fi >> n >> m;
int x, i;
for(i = 0; i < n; i++){
fi >> x;
dd[x]++;
}
for(i = 0; i < m; i++){
fi >> x;
dd[x]++;
}
}
void solve(){
int i;
sort(dd+0, dd+mmax, greater<int>());
int d = 0;
for(i = 0; i < mmax; i++){
d = d + dd[i];
if(d > n) break;
}
if(d - dd[i] == n) fo << i;
else fo << i + 1;
}
int main(){
set();
solve();
fi.close();
fo.close();
return 0;
}
|
#include <iostream>
// sse vec
#include <xmmintrin.h>
constexpr int size = 4 * 1000 * 1000 * 100;
void simple_loop(float *arr, float a, float b) {
std::cout << "simple" << std::endl;
for (int i=0; i<size; i++)
arr[i] = arr[i] * a + b;
}
void simple_loop_with_intrinsics(float *arr, float a, float b) {
std::cout << "with intrinsics" << std::endl;
__m128 a_sse = _mm_load1_ps(&a);
__m128 b_sse = _mm_load1_ps(&b);
for (int i=0; i<size; i+=4) {
__m128 arr_sse = _mm_load_ps(&arr[i]);
}
}
int main() {
float *arr = new float[size];
float a = 2;
float b = 4;
#ifdef SIMPLE
simple_loop(arr, a, b);
#elif INTRINSICS
simple_loop_with_intrinsics(arr, a, b);
#endif
return 0;
}
|
#include "stdafx.h"
#include <string>
#include "../ToAiEditModeButton.h"
#include "DungeonGame.h"
#include "DungeonSelect.h"
#include "../Title/ModeSelect.h"
#include "../Fade/Fade.h"
#include "../GameData.h"
#include "../GameCursor.h"
#include "../Title/SuperMonsterSelect.h"
#include "../StageSetup/StageSetup.h"
#include "../Game.h"
#include "../SaveLoad/PythonFileLoad.h"
#include "../StageSetup/StageSelect.h"
#include "../Title/ModeSelect.h"
#include "../Title/PMMonster.h"
#include "DungeonAISelect.h"
#include "DungeonTransition.h"
#include "..//Title/AIeditModeSelect.h"
#include "../ReturnButton/ReturnButton.h"
#include "../Title/MonAIPreset/MonAIPresetOpenSuper.h"
#include "../Title/MonAIPreset/MonAIPresetSaveOpen.h"
#include "../Title/MonAIPreset/MonAIPresetLoadOpen.h"
#include "../Title/GObutton.h"
#include "../Title/MonsterSelectBack.h"
DungeonAISelect::DungeonAISelect()
{
}
DungeonAISelect::~DungeonAISelect()
{
}
void DungeonAISelect::OnDestroy()
{
DeleteGO(m_dunSp);
DeleteGO(m_font);
DeleteGO(m_cursor);
for (auto go : m_pmms)
{
DeleteGO(go);
}
//DeleteGO(m_GO);
DeleteGO(m_backSp);
DeleteGO(m_returnButton);
DeleteGO(m_msp);
DeleteGO(m_mlp);
DeleteGO(m_GOb);
DeleteGO(m_back);
DeleteGO(m_aiButton);
}
bool DungeonAISelect::Start() {
auto m_BGM = FindGO<Sound>("BGM");
if (m_BGM == nullptr)
{
m_BGM = NewGO<Sound>(0, "BGM");
m_BGM->Init(L"Assets/sound/BGM/PerituneMaterial_Strategy5_loop.wav", true);
m_BGM->Play();
}
//m_backSp->Init(L"Assets/Sprite/dungeonAiSelectWallpaper.dds", 1280.f, 720.f, false);
//m_backSp = NewGO<SpriteRender>(0, "sp");
//m_backSp->Init(L"Assets/sprite/monsel_back.dds", 1280, 720);
m_back = NewGO<MonsterSelectBack>(0, "msb");
m_fade = FindGO<Fade>("fade");
m_fade->FadeIn();
m_files = PythonFileLoad::FilesLoad();
m_enemyFiles = PythonFileLoad::FilesLoadEnemy();
m_cursor = NewGO<GameCursor>(0, "cursor");
CVector3 pos = { -320,0,0 };
for (int i = 0; i < m_numPmm; i++) {
m_pmms.push_back(NewGO<PMMonster>(0, "pmm"));
m_pmms[i]->init(i, pos);
pos.x += 240.f;
if (g_AIset[i].AImode == 0) //AImode Python
{
std::wstring ws = std::wstring(m_files[g_AIset[i].AInum].begin(), m_files[g_AIset[i].AInum].end());
m_pmms[i]->SetPython(ws.c_str(), g_AIset[i].AInum, g_AIset[i].AImode);
}
else //AImode VisualAI
{
wchar_t ws[3];
swprintf_s(ws, L"%d", g_AIset[i].AInum);
m_pmms[i]->SetPython(ws, g_AIset[i].AInum, g_AIset[i].AImode);
}
}
/*m_GO = NewGO<SpriteRender>(1, "sp");
m_GO->Init(L"Assets/sprite/GO.dds", 193, 93, true);
m_GO->SetPosition({ 400,-160,0 });*/
m_dunSp = NewGO<SpriteRender>(1, "dunSp");
m_dunSp->Init(L"Assets/Sprite/DadandanBk.dds", 350.f, 70.f);
m_dunSp->SetPosition({ 0.f,300.f,0.f });
m_font = NewGO<FontRender>(1, "font");
m_font->SetTextType(CFont::en_Japanese);
wchar_t dungeon[256];
swprintf_s(dungeon, L"ダンジョン%d\n", m_dunNum + 1);
m_font->Init(dungeon, { -140.f, 320.f }, 0.f, CVector4::White, 1.f, { 0.f,0.f });
m_returnButton = NewGO<ReturnButton>(1, "rb");
m_returnButton->init(this, "pvp", m_cursor);
// 紅組用のチームを保存するやつ
m_msp = NewGO<MonAIPresetSaveOpen>(0, "mapso");
m_msp->init(this, m_cursor, L"チームを保存", { 410,130,0 }, 0);
// 紅組用のチームを開くやつ
m_mlp = NewGO<MonAIPresetLoadOpen>(0, "maplo");
m_mlp->init(this, m_cursor, L"チームを開く", { 410,60,0 }, 0);
m_GOb = NewGO<GObutton>(0, "gb");
m_GOb->init(m_cursor, { 400,-160,0 });
m_aiButton = NewGO< ToAiEditModeButton>(0);
m_aiButton->SetCurrentScene(this);
return true;
}
void DungeonAISelect::Update() {
if (m_isfade && m_fade->isFadeStop()) {
auto dun = NewGO<DungeonGame>(0, "DungeonGame");
int i = 0;
for (auto p : m_pmms) {
aimode[i] = p->GetAImode();
i++;
}
dun->SetGameData(m_files, m_enemyFiles, monai, moid, m_dunNum, aimode);
OutputDebugStringA("AI Selected!! Start Transation!\n");
dun->StartTransition();
DeleteGO(this);
}
if (m_isfade)
return;
bool ismonsel = false;
int count = 0;
bool ispmm = false;
if (!m_isfade) {
for (auto pmm : m_pmms)
{
ispmm = pmm->isOpen();
if (ispmm)
break;
}
if (ispmm)
return;
if (m_aiButton->isFading())
return;
/*for (auto pmm : m_pmms)
{
if (pmm->isClick())
{
pmm->Open();
}
}*/
/*for (auto pmm : m_pmms)
{
ismonsel = pmm->isMonSel();
if (ismonsel || pmm->isSelect())
{
break;
}
count++;
}*/
}
if (ismonsel)
return;
if (!(m_msp->IsOpen() || m_mlp->IsOpen()))
{
m_msp->UpdateEx();
m_mlp->UpdateEx();
if (m_msp->IsClick())
{
m_msp->Open();
}
else if (m_mlp->IsClick())
{
m_mlp->Open();
}
for (auto pmm : m_pmms)
{
pmm->UpdateEX();
}
/*m_GO->SetCollisionTarget(m_cursor->GetCursor());
if (m_GO->isCollidingTarget())
{
if (Mouse::isTrigger(enLeftClick))
{
for (int i = 0; i < m_numPmm; i++)
{
moid[i] = static_cast<MonsterID>(m_pmms[i]->GetMonsterID());
monai[i] = m_pmms[i]->GetAI();
}
m_fade->FadeOut();
m_isfade = true;
auto se = NewGO<Sound>(0);
se->Init(L"Assets/sound/se/button.wav", false);
se->Play();
}
}*/
m_GOb->UpdateEx();
if (m_GOb->isClick())
{
for (int i = 0; i < m_numPmm; i++)
{
moid[i] = static_cast<MonsterID>(m_pmms[i]->GetMonsterID());
monai[i] = m_pmms[i]->GetAI();
}
m_fade->FadeOut();
m_isfade = true;
auto se = NewGO<Sound>(0);
se->Init(L"Assets/sound/se/button.wav", false);
se->Play();
}
// m_backSp->SetCollisionTarget(m_cursor->GetCursor());
//// if (g_pad[0].IsTrigger(enButtonA)) {
// if(m_backSp->isCollidingTarget() && Mouse::isTrigger(enLeftClick)){
// m_fade->FadeOut();
// isfade = true;
// }
}
if (isfade && m_fade->isFadeStop()) {
NewGO<DungeonSelect>(0, "DungeonSelect");
auto dgame = FindGO<DungeonGame>("DungeonGame");
DeleteGO(this);
DeleteGO(dgame);
}
if(!isfade and !m_isfade)
m_returnButton->UpdateEx<DungeonSelect>();
m_aiButton->SetTarget(m_cursor->GetCursor());
}
void DungeonAISelect::LoadFiles() {
HANDLE hfind;
WIN32_FIND_DATA win32d;
std::vector<std::string> filenames;
char c[255];
std::string cd;
GetCurrentDirectory(255, c);
cd = c;
std::string key = cd + "/PythonAIs/*.py";
hfind = FindFirstFile(key.c_str(), &win32d);
do
{
if (win32d.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
}
else
{
std::string p = win32d.cFileName;
p.resize(p.length() - 3);
m_files.push_back(p);
}
} while (FindNextFile(hfind, &win32d));
FindClose(hfind);
}
std::vector<std::string> DungeonAISelect::GetFiles() {
return m_files;
}
|
#include <QApplication>
#include "game.h"
#include "mainmenu.h"
#include "loginscreen.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
LoginScreen* l = new LoginScreen;
l->show();
return a.exec();
}
|
#ifndef GAMECONTROLLER_H
#define GAMECONTROLLER_H
#include <QGraphicsPixmapItem>
#include <QObject>
#include <QGraphicsItem>
#include<QTimer>
#include<QGraphicsView>
#include"Endmenu.h"
#include"Play.h"
#include "startmenuer.h"
#include <QMediaPlayer>
class Gamecontroller : public QObject
{
Q_OBJECT
public:
Gamecontroller ();
void startgame();
void endgamemedium();
void endgameeasy();
void playagain();
QMediaPlayer * gameover;
//void newgame();
// QTimer * timer;
// Endmenu *end;
// Startmenu *start;
// Play *play;
public slots:
//->using in startmenu connect ??
};
#endif // GAMECONTROLLER_H
|
#include <iostream>
#include "lexer.h"
#include "tests.h"
int main () {
unit_test_1();
unit_test_2();
unit_test_3();
unit_test_4();
unit_test_5();
unit_test_6();
unit_test_8();
unit_test_9();
unit_test_10();
//unit_test_7();
test();
return 0;
}
|
#pragma once
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
#include<string>
using namespace cv;
using namespace std;
//@breif generate code
//@author shitaotao
class QRCodeDrawer
{
private:
string data;
int currentX;//当前所需绘制矩形左上角的x坐标
int currentY;//当前所需绘制矩形左上角的y坐标
int code_pixel_col;//二维码横向像素数
int code_pixel_row;//二维码纵向像素数
int all_code_pixel_col;//整个图像的横向像素数
int all_code_pixel_row;//整个图像的纵向像素数
int code_col;//二维码列数
int code_row;//二维码行数
int frame_wid;//边框宽度
int rect_len;//二维码中单位正方形的边长
int code_num;//根据信息长度所需二维码数量
long int data_index;
int num_row;//用于存放二维码序号的行数
int outer_frame_width;//最外围宽边框的像素宽度
void draw_frame();
void set_code_num();
void draw_code(int count);
void initial();
public:
Mat code;
QRCodeDrawer();
void set_data(string data);
void generate_code(string file_path);
int getCode_num();
};
|
#ifndef COMLIB_H
#define COMLIB_H
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <Windows.h>
enum MSG_TYPE { NORMAL, DUMMY};
enum TYPE { PRODUCER, CONSUMER };
struct Header
{
MSG_TYPE type;
size_t length;
};
class ComLib
{
private:
HANDLE hFileMap;
void* mData;
bool exists = false;
unsigned int mSize = 1 << 20;
TYPE userType;
char* base;
size_t* head;
size_t* tail;
char* memStart;
size_t bufferSize;
size_t getFreeMem(size_t tempTail);
public:
ComLib(const std::string& secret, const size_t& buffSize, TYPE type);
bool send(const void*msg, const size_t length);
bool recv(char* msg, size_t &length);
char* recvBuffer;
size_t sizeOfRecvBuffer = 4;
size_t nextSize();
~ComLib();
};
#endif
|
#include<bits/stdc++.h>
#define mod 1000000007
typedef long long ll;
using namespace std;
struct matrix{
ll a[2][2];
matrix(){
memset(a,0,sizeof(a));
}
matrix(int x){
memset(a,0,sizeof(a));
for(int i=0;i<2;i++)
a[i][i]=1;
}
ll sum(){
ll ret=0;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
ret+=a[i][j];
return ret%mod;
}
matrix operator+(const matrix&other){
matrix ret;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
ret.a[i][j]=(ret.a[i][j]+a[i][j]+other.a[i][j])%mod;
return ret;
}
matrix operator*(const matrix&other){
matrix ret;
int i,j,k;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
for(k=0;k<2;k++)
ret.a[i][j]+=a[i][k]*other.a[k][j],
ret.a[i][j]%=mod;
return ret;
}
matrix&operator*=(const matrix&other){*this=*this*other;
return*this;
}
matrix operator^(ll index){
matrix ret(1);
matrix base(*this);
while(index){
if(index&1)
ret*=base;
base*=base;
index>>=1;
}
return ret;
}
};
int main() {
ll x, u, v, k;
for(ll x, u, v, k; ~scanf("%lld %lld %lld %lld", &x, &u, &v, &k); ) {
matrix mm;
mm.a[0][0] = v, mm.a[0][1] = u, mm.a[1][0] = 1, mm.a[1][1] = 0;
ll a1 = x%mod, a2 = x*x%mod;
matrix res = mm^(k-2);
ll ans = (res.a[0][0]*a2%mod + res.a[0][1]*a1%mod) % mod;
printf("%lld\n", ans);
}
return 0;
}
|
/*----------------------------------------------------------------------------*
** sets.cpp : class definitions for set operations using bit representations.
**
** Stephen R. Schmitt
** Nettoyage et mis en c++ pure : Thibault Francois
*/
#include "sets.h"
#include <string>
#include <iostream>
#include <cstdio>
#include <sstream>
using namespace std;
/*----------------------------------------------------------------------------*
** "sets()" default constructor, initializes elements of the set to zero.
**
** returns: nothing
*/
sets::sets() {
clear(); // initialize to empty
}
/*----------------------------------------------------------------------------*
** "sets()" copy constructor, initializes elements of the set to be
** equal to the values of the argument set.
**
** returns: nothing
*/
sets::sets(const sets &rhs) { // the set to copy
for( int i = 0; i < MAX_WORDS; i++ ) // copy into new set
set[i] = rhs.set[i];
}
/*----------------------------------------------------------------------------*
** "item()" checks for existence of an item in the set.
**
** returns: 1 if item present, 0 if not, -1 on range error
*/
int sets::item( int bit ) { // index of the item
if( bit <= 0 || bit > MAX_WORDS * WORD_SIZE ) // in range?
return -1;
int i = bit / WORD_SIZE;
bit -= i * WORD_SIZE;
return set[i] & 1 << ( bit - 1 ); // binary AND
}
/*----------------------------------------------------------------------------*
** "insert()" puts an item into the set. Range errors are ignored.
**
** returns: nothing
*/
void sets::insert( int bit ) { // index of the item
if( bit <= 0 || bit > MAX_WORDS * WORD_SIZE ) // in range?
return;
int i = bit / WORD_SIZE;
bit -= i * WORD_SIZE;
set[i] |= 1 << ( bit - 1 ); // binary OR
}
/*----------------------------------------------------------------------------*
** "remove()" takes an item out of the set. Range errors are ignored.
**
** returns: nothing
*/
void sets::remove( int bit ) { // index of the item
if( bit <= 0 || bit > MAX_WORDS * WORD_SIZE ) // in range?
return;
int i = bit / WORD_SIZE;
bit -= i * WORD_SIZE;
set[i] &= ~( 1 << ( bit - 1 ) ); // binary AND
}
/*----------------------------------------------------------------------------*
** "clear()" removes all items from the set..
**
** returns: nothing
*/
void sets::clear() {
for( int i = 0; i < MAX_WORDS; i++ ) // all words in set
set[i] = 0;
}
/*----------------------------------------------------------------------------*
** "define()" initializes elements of the set using an enumerated input
** string (numbers separated by spaces).
**
** NOTE: Values of set elements that are too large are ignored.
**
** returns: nothing
*/
void sets::define( string input ) { // string of numbers
int length = input.size(); // of input buffer
int pos = 0; // current character
clear(); // initialize to empty
while( pos < length ) { // more input
int bit = 0; // init bit to set
while( isdigit( input[pos] ) ) {
bit *= 10; // compute bit to set
bit += input[pos] - '0';
pos++; // advance
}
if( bit ) // zero means no bit
insert( bit );
pos++; // advance
}
}
/*----------------------------------------------------------------------------*
** "binary()" prints binary representation of set to stdout.
**
** returns: nothing
*/
void sets::binary() {
for( int j = 0; j < MAX_WORDS; j++ ) { // do all words
unsigned long mask = 1; // start at low bit
for( int i = 0; i < WORD_SIZE; i++ ) { // every bit in word
if( i % 4 == 0 ) // add space
putchar( ' ' );
set[j] & mask ? putchar( '1' ) : putchar( '0' );
mask <<= 1; // next higher bit
}
}
}
/*----------------------------------------------------------------------------*
** "cardinality()" counts items in the set.
**
** returns: total items
*/
int sets::cardinality() {
int count = 0; // init counter
for( int j = 0; j < MAX_WORDS; j++ ) { // do all words
unsigned long mask = 1; // start at low bit
for( int i = 0; i < WORD_SIZE; i++ ) { // every bit in word
count += set[j] & mask ? 1 : 0;
mask <<= 1; // next higher bit
}
}
return count;
}
/*----------------------------------------------------------------------------*
** "print()" displays set to stdout as a list of integers.
**
** returns: nothing
*/
void sets::print() {
cout << "{ " ;
for( int j = 0; j < MAX_WORDS; j++ ) { // do all words
unsigned long mask = 1; // start at low bit
for( int i = 1; i <= WORD_SIZE; i++ ) {
if( set[j] & mask ) // check bit
cout << ( WORD_SIZE * j + i ) << " ";
mask <<= 1; // next higher bit
}
}
cout << "}" << endl;
}
string sets::to_s() {
ostringstream out;
out << "{ " ;
for( int j = 0; j < MAX_WORDS; j++ ) { // do all words
unsigned long mask = 1; // start at low bit
for( int i = 1; i <= WORD_SIZE; i++ ) {
if( set[j] & mask ) // check bit
out << ( WORD_SIZE * j + i ) << " ";
mask <<= 1; // next higher bit
}
}
out << "}";
return out.str();
}
/*----------------------------------------------------------------------------*
** "operator = " assigns the right hand side to this set.
**
** returns: nothing
*/
const sets &sets::operator = ( const sets &rhs ) {
if( &rhs != this ) { // avoid self assignment
for( int i = 0; i < MAX_WORDS; i++ ) // copy into this set
set[i] = rhs.set[i];
}
return *this; // enable x = y = z;
}
/*----------------------------------------------------------------------------*
** "operator ~ " performs set complement operation (not).
**
** returns: pointer to set
*/
sets sets::operator ~ () const {
sets rv;
for( int i = 0; i < MAX_WORDS; i++ )
rv.set[i] = ~set[i]; // bitwise complement
return rv;
}
/*----------------------------------------------------------------------------*
** "operator + " performs set union operation (or).
**
** returns: pointer to set
*/
sets sets::operator + ( const sets &rhs ) {
sets rv;
for( int i = 0; i < MAX_WORDS; i++ )
rv.set[i] = set[i] | rhs.set[i]; // bitwise OR
return rv;
}
/*----------------------------------------------------------------------------*
** "operator * " performs set intersection operation (and).
**
** returns: pointer to set
*/
sets sets::operator * ( const sets &rhs ) {
sets rv;
for( int i = 0; i < MAX_WORDS; i++ )
rv.set[i] = set[i] & rhs.set[i]; // bitwise AND
return rv;
}
/*----------------------------------------------------------------------------*
** "operator - " performs set difference operation.
**
** returns: pointer to set
*/
sets sets::operator - ( const sets &rhs ) {
sets rv;
for( int i = 0; i < MAX_WORDS; i++ )
rv.set[i] = set[i] & ( ~rhs.set[i] ); // bitwise a AND ~b
return rv;
}
/*----------------------------------------------------------------------------*
** "operator ^ " performs set symmetric difference operation (xor).
**
** returns: pointer to set
*/
sets sets::operator ^ ( const sets &rhs ) {
sets rv;
for( int i = 0; i < MAX_WORDS; i++ )
rv.set[i] = set[i] ^ rhs.set[i]; // bitwise XOR
return rv;
}
|
auto& pc = Serial; // the USB
auto& xdev = Serial2; // external device
#if 1
#define BAUD 115200
#else
#define BAUD 9600
#endif
void setup() {
pc.begin(BAUD);
xdev.begin(BAUD);
}
void loop() {
if(pc.available()) { xdev.print((char) pc.read()); }
if(xdev.available()) { pc.print((char) xdev.read()); }
}
|
#ifndef CUSTOMIZECORE_H
#define CUSTOMIZECORE_H
#include <QObject>
#include <QString>
#include <QStringList>
#include "appconfig.h"
#include "models/currency.h"
#include "models/user.h"
/**
* @brief The CustomizeCore class
*
* Provides functionality for customization state
*/
class CustomizeCore : public QObject
{
Q_OBJECT
Q_PROPERTY(QString username READ getUsername WRITE setUsername NOTIFY propChanged)
Q_PROPERTY(QString email READ getEmail WRITE setEmail NOTIFY propChanged)
Q_PROPERTY(QString firstName READ getFirstName WRITE setFirstName NOTIFY propChanged)
Q_PROPERTY(QString lastName READ getLastName WRITE setLastName NOTIFY propChanged)
Q_PROPERTY(Currency* currency READ getCurrency WRITE setCurrency NOTIFY propChanged)
Q_PROPERTY(User* user READ getUser WRITE setUser NOTIFY propChanged)
AppConfig *config;
QString _username;
QString _email;
QString _firstName;
QString _lastName;
User *_user;
Currency *_currency;
QStringList _categoryList;
QStringList _accountList;
public:
explicit CustomizeCore(QObject *parent = 0);
QString getUsername() const;
void setUsername(const QString &value);
QString getEmail() const;
void setEmail(const QString &value);
QString getFirstName() const;
void setFirstName(const QString &value);
QString getLastName() const;
void setLastName(const QString &value);
Currency *getCurrency() const;
void setCurrency(Currency *value);
AppConfig *getConfig() const;
void setConfig(AppConfig *value);
User *getUser() const;
void setUser(User *user);
signals:
void propChanged();
public slots:
QStringList getCategoryList() const;
QStringList getAccountList() const;
QList<QObject *> getCurrencyList();
void setCategoryList(const QStringList &value);
void setAccountList(const QStringList &value);
void addCategory(const QString &value);
};
#endif // CUSTOMIZECORE_H
|
#ifndef _TESTE_
#define _TESTE_
template <typename FP>
class Teste
{
public:
void bla(FP x);
void bla2(FP x);
protected:
private:
};
#endif
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
char buf1[11111], buf2[1111];
int ans[1111111];
int n;
int s(int x) {
int ss = 0;
while (x) {
ss += x % 10;
x /= 10;
}
return ss;
}
bool ByMagic(int x,int y) {
if (s(x) < s(y)) return true;
if (s(x) > s(y)) return false;
sprintf(buf1, "%d", x);
sprintf(buf2, "%d", y);
return string(buf1) < string(buf2);
}
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
cin >> n;
for (int i = 1; i <= n; ++i) ans[i] = i;
sort(ans + 1, ans + n + 1, ByMagic);
for (int i = 1; i <= n; ++i)
cout << i << ": " << ans[i] << endl;
return 0;
}
|
#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <set>
using namespace std;
/*ϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕ*/
#define int long long
#define ld long double
#define F first
#define S second
#define P pair <int,int>
#define vi vector <int>
#define vs vector <string>
#define vb vector <bool>
#define all(x) x.begin(),x.end()
#define sz(x) (int)x.size()
#define REP(i,a,b) for(int i=(int)a;i<=(int)b;i++)
#define REV(i,a,b) for(int i=(int)a;i>=(int)b;i--)
#define sp(x,y) fixed<<setprecision(y)<<x
#define pb push_back
#define endl '\n'
const int mod = 1e9 + 7;
/*ϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕ*/
const int N = 1e5 + 5;
vi gr[N];
vi vis;
int n, m;
void dfs(int src) {
vis[src] = 1;
for (int to : gr[src]) {
if (!vis[to]) {
dfs(to);
}
}
}
void solve() {
vis.assign(N, 0);
cin >> n >> m;
REP(i, 0, n)
gr[i].clear();
while (m--) {
int u, v; cin >> u >> v;
gr[u].pb(v);
gr[v].pb(u);
}
int ans = 0;
REP(i, 0, n - 1) {
if (!vis[i]) {
dfs(i);
ans++;
}
}
cout << ans << endl;
return ;
}
int32_t main() {
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
int t; cin >> t; while (t--)
solve();
return 0;
}
|
#include "NameIndex.h"
NameIndex::NameIndex() : numCollisions(0),size(0),rehash(0),c(1024),maxProbe(0){
buckets.resize(c);
status.resize(c);
}
NameIndex::~NameIndex() {}
void NameIndex::expandAndRehash(){
c = 2*c;
vector<string> biggerBuckets(c);
vector<BucketStatus> biggerStatus(c);
biggerBuckets.swap(buckets);
biggerStatus.swap(status);
size =0;
for(int i =0; i<biggerStatus.size(); i++){
if(biggerStatus.at(i) == OCCUPIED){
insert(biggerBuckets.at(i));
}
}
}
//elfhash, key is concate the feature name and state alpha
unsigned int NameIndex::hash(const string& key) const{
unsigned int hash =0;
unsigned int x = 0;
unsigned int i = 0;
unsigned int len = key.length();
for(i =0; i <len; i++){
hash = (hash << 4) + (key[i]);
if((x=hash & 0xF0000000L) != 0){
hash ^= (x >> 24);
}
hash &= ~x;
}
return hash;
}
unsigned int NameIndex::insert( const string& key) {
if(isFull()){
expandAndRehash();
rehash++;
}
unsigned int h = hash(key) % c;
unsigned int i = 0;
unsigned int hi = h;
unsigned int probe;
while (status[hi] == OCCUPIED) {
if (buckets[hi].compare(key))
return -1; // Key already exists
numCollisions++;
++i;
probe = (i*i + i)/2;
if(probe > maxProbe){
maxProbe = probe;
}
hi = (hi + probe) % c;
}
status[hi] = OCCUPIED;
buckets[hi] = key;
size++;
return hi; // Key inserted successfully
}
unsigned int NameIndex::search(string key){
unsigned int h = hash(key) % c;
unsigned int i = 0;
unsigned int hi = h;
while (status[hi] != EMPTY) {
if (status[hi] == OCCUPIED && buckets[hi].compare(key)) {
// Key found
return hi;
}
numCollisions++;
++i;
hi = ((int)pow(hi,2)+hi)/2 % c;
}
// Key not found. Hit an empty bucket.
return -1;
}
|
#include <ros/ros.h>
#include <stdio.h>
#include <stdlib.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/tracking.hpp>
#include <PerFoRoControl/SelectTarget.h>
using namespace cv;
using namespace std;
static const std::string OPENCV_WINDOW = "Select Target Person";
static void onMouse(int event, int x, int y, int, void* );
class SelectTarget
{
public:
SelectTarget();
~SelectTarget() {cv::destroyWindow(OPENCV_WINDOW);}
void SelectObject(int event, int x, int y);
protected:
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle nh_;
image_transport::ImageTransport it_;
image_transport::Subscriber image_sub_;
ros::Subscriber target_sub_;
ros::Publisher target_shirt_pub_;
ros::Publisher target_pant_pub_;
ros::Publisher target_dock_pub_;
PerFoRoControl::SelectTarget select_target_shirt_msg;
PerFoRoControl::SelectTarget select_target_pant_msg;
PerFoRoControl::SelectTarget select_target_dock_msg;
bool IMSHOW;
Rect selection;
bool selectObject;
Mat frame;
Point origin;
void ImageCallback(const sensor_msgs::ImageConstPtr& msg);
void SelectTargetCallback(const PerFoRoControl::SelectTarget msg);
};
namespace st
{
SelectTarget *ST = NULL;
}
|
/*
Copyright 2021 University of Manchester
Licensed under the Apache License, Version 2.0(the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http: // www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "table_manager.hpp"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "mock_data_manager.hpp"
#include "virtual_memory_block.hpp"
using orkhestrafs::dbmstodspi::TableManager;
using orkhestrafs::dbmstodspi::VirtualMemoryBlock;
namespace {
class TableManagerTest : public ::testing::Test {
protected:
TableData test_table_;
std::vector<std::pair<ColumnDataType, int>> test_column_defs_vector_ = {
{ColumnDataType::kDecimal, 2},
{ColumnDataType::kDate, 4},
{ColumnDataType::kDecimal, 1}};
std::vector<uint32_t> test_data_vector_ = {0, 1, 2, 3, 4, 5, 6};
void SetUp() override {
test_table_.table_column_label_vector = test_column_defs_vector_;
test_table_.table_data_vector = test_data_vector_;
}
MockDataManager mock_data_manager_;
std::vector<int> any_vector_;
std::string any_filename_;
std::unique_ptr<MemoryBlockInterface> memory_device_ =
std::make_unique<VirtualMemoryBlock>();
};
TEST_F(TableManagerTest, RecordSizeFromTableIsCorrect) {
ASSERT_EQ(7, TableManager::GetRecordSizeFromTable(test_table_));
}
TEST_F(TableManagerTest, GetColumnDefsVectorReturnsExpectedVector) {
std::vector<std::pair<ColumnDataType, int>> expected_column_defs_vector = {
{ColumnDataType::kDecimal, 2},
{ColumnDataType::kDate, 4},
{ColumnDataType::kDecimal, 1}};
std::vector<int> column_types = {3, 4, 3};
std::vector<ColumnDataType> expected_column_types = {
ColumnDataType::kDecimal, ColumnDataType::kDate,
ColumnDataType::kDecimal};
std::vector<int> column_widths = {4, 2, 2};
int stream_index = 1;
std::vector<std::vector<int>> stream_specification = {
any_vector_, any_vector_, any_vector_, any_vector_,
any_vector_, column_types, column_widths, any_vector_};
EXPECT_CALL(mock_data_manager_,
GetHeaderColumnVector(expected_column_types, column_widths))
.WillOnce(testing::Return(expected_column_defs_vector));
auto resuling_column_defs = TableManager::GetColumnDefsVector(
&mock_data_manager_, stream_specification, stream_index);
ASSERT_EQ(expected_column_defs_vector.at(0), resuling_column_defs.at(0));
ASSERT_EQ(expected_column_defs_vector.at(1), resuling_column_defs.at(1));
ASSERT_EQ(expected_column_defs_vector.at(2), resuling_column_defs.at(2));
}
TEST_F(TableManagerTest, WriteDataToMemoryReturnsCorrectRecordData) {
std::vector<std::pair<ColumnDataType, int>> expected_column_defs_vector;
int stream_index = 0;
std::vector<std::vector<int>> stream_specification = {{}, {}, {}, {}};
int expected_record_count = 123;
std::pair<int, int> expected_record_data = {0, expected_record_count};
EXPECT_CALL(
mock_data_manager_,
WriteDataFromCSVToMemory(any_filename_, expected_column_defs_vector,
memory_device_.get()))
.WillOnce(testing::Return(expected_record_count));
ASSERT_EQ(expected_record_data,
TableManager::WriteDataToMemory(
&mock_data_manager_, stream_specification, stream_index,
memory_device_.get(), any_filename_));
}
} // namespace
|
#ifndef PLOTVIEW_H
#define PLOTVIEW_H
#include "viewwidget.h"
#include "qcustomplot.h"
class PlotView : public ViewWidget
{
public:
/// Constructor
PlotView(Manager*,QWidget* =0);
~PlotView();
protected:
/// Initialise the GL scene
void initializeGL();
/// Paint the GL scene
void paintGL();
/// Resize the GL scene
void resizeGL(int width, int height);
private:
};
#endif // PLOTVIEW_H
|
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MockIOUtils.h"
#include <string>
#include <vector>
using std::string;
using std::vector;
using ::testing::Return;
using ::testing::Invoke;
using ::testing::ElementsAre;
using ::testing::UnorderedElementsAre;
using ::testing::NiceMock;
using ::testing::StrictMock;
TEST(CallStudy, CallReturnsWithoutExpectCall) {
NiceMock<MockIOUtils> mockIOUtils;
// When no expect setup is there, default return value is provided by the framework.
EXPECT_EQ("", mockIOUtils.tempDirectoryPath(nullptr));
vector<string> expected;
string doesNotMatter("");
EXPECT_EQ(mockIOUtils.list(doesNotMatter, doesNotMatter), expected);
}
TEST(CallStudy, CallReturnCount) {
StrictMock<MockIOUtils> mockIOUtils;
EXPECT_CALL(mockIOUtils, tempDirectoryPath("random"))
.WillOnce(Return("Invalid platform. How about linux?"))
.WillOnce(Return("Linux it is."))
.WillRepeatedly(Return("Great news. You don't have to run this test again. You're fired!"));
EXPECT_EQ(mockIOUtils.tempDirectoryPath("random"),
"Invalid platform. How about linux?");
EXPECT_EQ(mockIOUtils.tempDirectoryPath("random"),
"Linux it is.");
for (int i = 0; i < 10; ++i) {
EXPECT_EQ(mockIOUtils.tempDirectoryPath("random"),
"Great news. You don't have to run this test again. You're fired!");
}
}
TEST(CallStudy, RetiresOnSaturation) {
StrictMock<MockIOUtils> mockIOUtils;
// ordering should be in reverse
for (int i = 2; i >= 0; --i) {
string msg;
if (i == 0) {
msg = "1st message";
} else if (i == 1) {
msg = "2nd message";
} else if (i == 2) {
msg = "3rd message";
}
EXPECT_CALL(mockIOUtils, tempDirectoryPath("random"))
.WillOnce(Return(msg))
.RetiresOnSaturation();
}
EXPECT_EQ(mockIOUtils.tempDirectoryPath("random"), "1st message");
EXPECT_EQ(mockIOUtils.tempDirectoryPath("random"), "2nd message");
EXPECT_EQ(mockIOUtils.tempDirectoryPath("random"), "3rd message");
}
|
//
// Created by arnoul_r on 21/01/17.
//
#ifndef GGJ17_PHYSICSENGINE_HH
#define GGJ17_PHYSICSENGINE_HH
static const float SCALE = 30.f;
#include <Box2D/Box2D.h>
#include <vector>
class PhysicsEngine {
public:
b2World *world;
float refreshFrequency;
public:
PhysicsEngine(float, float);
~PhysicsEngine();
public:
b2Body* createRectangle(int, int, int, int, double, bool = true);
void Step();
};
#endif //GGJ17_PHYSICSENGINE_HH
|
//
// Created by arnito on 21/04/17.
//
#ifndef BEAT_THE_BEAT_GAMEOBJECT_H
#define BEAT_THE_BEAT_GAMEOBJECT_H
#include "Utils.h"
#include "Inputs.h"
class GameObject : public sf::Drawable {
virtual void event(const sf::Event& event);
virtual void update(const sf::Time& deltatime);
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
virtual void onKeyPressed(Inputs::Key key, int player);
virtual void onKeyReleased(Inputs::Key key, int player);
};
#endif //BEAT_THE_BEAT_GAMEOBJECT_H
|
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void Generate_Letter(string letter[],int num_lines,string thisname)
{
unsigned long max,pos;
max=letter[0].max_size();
for(int n=0;n<num_lines;n++)
{
if((pos=letter[n].find("CUSTOMER",0))<max)
{
letter[n].replace(pos,8,"");
letter[n].insert(pos,thisname);
}
cout<<letter[n]<<endl;
}
}
int main()
{
string letter[100];
string title,lastname,customer;
int number_lines,number_customers;
ifstream letter_in;
ifstream customer_in;
letter_in.open("letter.txt");
customer_in.open("customer.txt");
number_lines=0;
while(getline(letter_in,letter[number_lines]))
number_lines++;
number_customers=0;
while(customer_in>>title)
{
customer_in>>lastname;
customer=title+" "+lastname;
Generate_Letter(letter,number_lines,customer);
number_customers++;
}
}
|
#ifndef ACOROSS_RPC_SOCKET_H_
#define ACOROSS_RPC_SOCKET_H_
#include <SDKDDKVer.h>
#include <boost/asio.hpp>
#include <memory>
#include <deque>
#include <atomic>
#include "rpc_packet.h"
namespace acoross {
namespace rpc {
using boost::asio::ip::tcp;
class RpcSocket
: public std::enable_shared_from_this<RpcSocket>
{
public:
RpcSocket(::boost::asio::io_service& io_service, tcp::socket&& socket,
std::function<void(boost::system::error_code ec)> end_handler = std::function<void(boost::system::error_code ec)>())
: io_service_(io_service)
, socket_(std::move(socket))
, write_strand_(io_service)
, end_handler_(end_handler)
{
}
virtual ~RpcSocket()
{
size_t cnt = 0;
cnt += write_msgs_.size();
RpcSocket::pending_write().fetch_sub(my_pending_write_.load());
auto cnt2 = RpcSocket::pending_write_cnt().load();
cnt2++;
}
void start()
{
do_read_header();
started_.store(true);
}
void end(boost::system::error_code ec)
{
//_ASSERT(0);
if (end_handler_)
{
end_handler_(ec);
}
}
void send(std::shared_ptr<RpcPacket> new_msg);
static std::atomic<size_t>& pending_write()
{
static std::atomic<size_t> pending_write_ = 0;
return pending_write_;
}
static std::atomic<size_t>& pending_write_cnt()
{
static std::atomic<size_t> pending_write_cnt = 0;
return pending_write_cnt;
}
protected:
virtual bool process_msg(RpcPacket& msg) = 0;
private:
void do_write();
void do_read_header();
void do_read_body();
private:
::boost::asio::io_service& io_service_;
tcp::socket socket_; //rpc Àü¿ë ¼ÒÄÏ
RpcPacket read_msg_;
std::function<void(boost::system::error_code ec)> end_handler_;
//
::boost::asio::strand write_strand_;
std::deque<std::shared_ptr<RpcPacket>> write_msgs_;
std::atomic<size_t> my_pending_write_{ 0 };
//
std::atomic<bool> started_{ false };
};
}
}
#include "rpc_socket.ipp"
#endif
|
// Copyright 2011 Yandex
#ifndef LTR_DATA_UTILITY_PARSERS_PARSE_ARFF_H_
#define LTR_DATA_UTILITY_PARSERS_PARSE_ARFF_H_
#include <boost/spirit/include/classic_parser.hpp>
#include <vector>
#include <map>
#include <string>
#include <set>
#include "ltr/data/utility/parsers/parser.h"
using boost::spirit::classic::parser;
using std::vector;
using std::set;
namespace ltr {
namespace io_utility {
class ARFFParser : public Parser {
private:
void init(std::istream* in);
public:
virtual void parseRawObject(string line, RawObject* result);
void makeString(const Object& obj, std::string* result);
PairwiseDataSet buildPairwiseDataSet(const std::vector<Object>& objects,
const FeatureInfo& info);
ListwiseDataSet buildListwiseDataSet(const std::vector<Object>& objects,
const FeatureInfo& info);
private:
int current_id_;
double current_relevance_;
map<int, string> features_;
map<string, double> classes_;
map<string, string> meta_features_;
/**
* @class NextFeatureParser
* This class is used only by ARFF Parser. It is functor,
* which is used in callbacks from boost::spirit
*/
class NextFeatureParser {
public:
/**
* Function inits NextFatureParser.
*/
void init(ARFFParser* parser);
/**
* This operator is called by boost::spirit.
* It processes features and saves it in the map in the parser,
* given in init.
*/
void operator()(const char* feature,
const char* it) const;
/**
* Function prepares NextFeatureParser to process the next object.
*/
void reset();
private:
ARFFParser* parser_;
} parseNextFeature;
friend class NextFeatureParser;
};
};
};
#endif // LTR_DATA_UTILITY_PARSERS_PARSE_ARFF_H_
|
String AT_Command;
String Esp_SSID = "Nucleo_ArGe"; //Enter SSID
String Esp_Password = "NucleoArGe123654"; //Enter Password
String Esp_Mode="1";
String TCP_USP_ID=""; //
//
int initial()
{
Test_Module();
delay(500);
Restart_Module();
delay(500);
// Firmware_Version();
// Deep_Sleep();
// Control_Echo();
// Set_Mode();
// Check_Mode();
// Connect_AP();
// Esp_Ping();
// List_Available_Wifi();
// Disconnect_AP();
// List_Connected_Clients();
// Set_DHCP();
// Get_MAC_Adress_Station();
// Set_MAC_Adress_AP();
// Check_IP_Station();
// Set_IP_Adress_AP();
// Get_IP_Adress_AP();
// Check_Connection();
// List_Command_Variation();
// Send_Data();
// Close_TCPUDP_Connection_Single();
}
void setup()
{
Serial.begin(115200);
initial();
Restore();
delay(500);
}
void loop()
{
delay(2000);
}
//cihaza bağlanılıp bağlanılmadığını kontrol eden fonksiyon
void Is_Ready()
{
for(int i=0;i<5;i++)
{
if(!Serial.find("OK"))
Serial.println("NOT OK");
else{
Serial.println("OK");
break;
}
}
}
//Yapılacak işleme göre belirlenen komutun seri kanl aracılığıyla esp8266'ya gönderilmesi için kullanılır.
void Send_Command()
{
Serial.println(AT_Command);
}
void Response()
{
for(int x;x<5;x++){
Serial.println(Serial.readString());
delay(500);
Serial.println(x);
delay(500);
}
}
//Cihaza güç verildiğinde AT komutlarının çalışıp çalışmadığını test etmek adına AT komutu yollanır.Bu fonksiyon AT komutunun gönderilmesini sağlar.
//Cevap:OK
void Test_Module()
{
AT_Command="AT";
Send_Command();
Is_Ready();
}
//Sensörü yeniden başlatmak için kullanılır.
//Cevap:OK
void Restart_Module()
{
AT_Command="AT+RST";
Send_Command();
Is_Ready();
}
//Cihazın yazılım versiyonunu öğrenmek için gönderilir. Cihaz yazılımlarına göre bazı AT komutlarına başka cevaplar gözlenebilir.
//Cevap= AT version:1.2.0.0(Jul 1 2016 20:04:45)
// SDK version:1.5.4.1(39cb9a32)
// Ai-Thinker Technology Co. Ltd.
// Dec 2 2016 14:21:16
// OK
void Firmware_Version()
{
AT_Command="AT+GMR";
Send_Command();
Response();
}
//Cihazı time değişkeninde saklanan zaman zarfında uykuya geçirmek için kullanılır .
//Cevap==>time,OK: 1500\n OK
//Uyarı: Yükselen kenar tetiği ile cihaz uyandırılabilir.
//Cevap kontrol edilmiyor çünkü cevabın bozuk geldiği gözlenmiştir.
void Deep_Sleep()
{
String Sleep_Time="1500";
AT_Command="AT+GLSP="+String(Sleep_Time);
Send_Command();
Response();
Is_Ready();
}
//Cihaza gönderilen mesajın tekrar geri basılması ya da basılmaması adına ayarları yapmak için kullanılır.
//0-->Geri basma kapatıldı.
//Cevap= OK
//1-->Geri basma açıldı.
//Cevap= OK
void Control_Echo()
{
String identifier="1";
AT_Command="ATE"+String(identifier);
Send_Command();
Is_Ready();
}
//Cihazda tanımlanabilecek 3 adet mod vardır.Bunları ayarlamak ve cihaza göndermek için
//kullanılır.Cihaza bir defa göndermek yeterlidir.
//Mod1=Station Mode
//Mode2=AP mode Host
//Mode3=AP+Station mode
//Cevap= OK
void Set_Mode()
{
AT_Command="AT+CWMODE="+String(Esp_Mode);
Send_Command();
Is_Ready();
}
//Cihazda tanımlanmış modu okuma işlemi için kullanılır.
//Cevap= CWMODE:(1:3)
void Check_Mode()
{
AT_Command="AT+CWMODE?";
Send_Command();
Esp_Mode=Serial.parseInt();
Serial.print("Wi-Fi mode is=");
Serial.println(Esp_Mode);
}
//wifi bağlantısı
//Cevap= WIFI DISCONNECTED
// WIFI CONNECTED
// WIFI GOT IP
// OK
void Connect_AP()
{
AT_Command="AT+CWJAP=\""+Esp_SSID+"\",\""+Esp_Password+"\"";
Send_Command();
Response();
}
//bağlantı kontrolü için www.google.com adresine ping atılır.
//Cevap: 22
void Esp_Ping()
{
String IP="172.217.169.100";
AT_Command="AT+PING=\""+IP+"\"";
Send_Command();
Response();
}
//Cihazın gördüğü ağların listesini çıkarmak için kullanılan fonksiyondur.
//Cevap= CWLAP:ecn,ssid,rssi,mac
// OK
void List_Available_Wifi()
{
AT_Command="AT+CWLAP";
Send_Command();
Response();
Is_Ready();
}
//Bağlantıda olunan ağdan kopmaya yarar.
//Cevap= DISCONNECT
// OK
void Disconnect_AP()
{
String SAP_SSID="ESP8266";
String SAP_Password="123456";
String SAP_Channel="2"; //cause unknown problem
String SAP_Enc="1"; //OPEN, 2 WPA_PSK, 3 WPA2_PSK, 4 WPA_WPA2_PSK
AT_Command="AT+CWSAP="+SAP_SSID+","+SAP_Password+","+SAP_Channel+","+SAP_Enc;
Send_Command();
Is_Ready();
}
//Bu komut kullanıldığında erişim noktasına bağlı olan cihazların bilgileri görüntülenir.
//Cevap=
void List_Connected_Clients()
{
AT_Command="AT+CWLIF";
Send_Command();
Response();
Is_Ready();
}
//Cihazın istasyon olarak mı yoksa erişim noktası olarak mı yoksa iki modu beraber mi kullanacağını belirler.
//Aynı zamanda DHCP aktif ya da deaktif hale getirebilir.
//(Dynamic Host Configuration Protocol)
//Cevap=
void Set_DHCP()
{
String DHCP_Mode="";
String DHCP_En="";
AT_Command="AT+CWDHCP_DEF="+DHCP_Mode+","+DHCP_En;
Send_Command();
Is_Ready();
}
//MAC adresini döndürür.
//Cevap= "dc:4f:22:51:2d:ec"
void Get_MAC_Adress_Station()
{
AT_Command="AT+CIPSTAMAC?";
Send_Command();
Response();
}
//Cihazın MAC adresini ayarlamak için kullanılır.
//Cevap= WIFI DISCONNECTED
// WIFI CONNECTED
// WIFI GOT IP
// OK
void Set_MAC_Adress_AP()
{
String MAC_Adress="dc:4f:22:51:2d:ec";
AT_Command="AT+CIPAPMAC_CUR="+MAC_Adress;
Send_Command();
Response();
Is_Ready();
}
//Cihazın MAC adresini ayarlamak için kullanılır.
//Cevap= WIFI DISCONNECTED
// WIFI CONNECTED
// WIFI GOT IP
// OK
void Set_MAC_Adress_AP()
{
String MAC_Adress="dc:4f:22:51:2d:ec";
AT_Command="AT+CIPAPMAC_DEF="+MAC_Adress;
Send_Command();
Response();
Is_Ready();
}
//Cihazın IPsini döndürür.
//Cevap=
void Check_IP_Station()
{
AT_Command="AT+CIPSTA";
Send_Command();
Response();
}
//Cihazın IP adresini ayarlamak için kullanılır.
//Cevap=
void Set_IP_Adress_AP()
{
String IP_Adress="";
AT_Command="AT+CIPSTA_CUR="+IP_Adress;
Send_Command();
Response();
}
//Cihazın IP adresini ayarlamak için kullanılır.
//Cevap=
void Set_IP_Adress_AP()
{
String IP_Adress="";
AT_Command="AT+CIPSTA_DEF="+IP_Adress;
Send_Command();
Response();
}
//IP adresini döndürür.
//Cevap= ip:"0.0.0.0"
// gateway:"0.0.0.0"
// netmask:"0.0.0.0"
// OK
void Get_IP_Adress_AP()
{
AT_Command="AT+CIPAP?";
Send_Command();
Response();
Is_Ready();
}
//Bağlantı durumunu öğrenmek için kullanılır
//Cevap= STATUS:2
void Check_Connection()
{
AT_Command="AT+CIPSTATUS";
Send_Command();
Response();
}
//Tekli TCP ve UDP bağlantı kurmak için kullanılır.
//Giriş id==> Type: "TCP" ya da "UDP"(String)
//Addr: Uzaktaki IP(String)
//Port: Uzaktaki Port(String)
void Establish_TCP_UDP_Connection_Single()
{
String Type="";
String Addr="";
String Port="";
AT_Command="AT+CIPSTART="+Type+","+Addr+","+Port;
Send_Command();
Response();
}
//Olası komutları sıralar
//Cevap=
void List_Command_Variation()
{
AT_Command="AT+CIPSTART?";
Send_Command();
Response();
}
//TCP veya UDp bağlantısında gönderilecek olan datanın uzunluğunu ayarlamak için kullanılır.
//Cevap=
void Set_TCPUP_Data_Single()
{
String Single_Length="";
AT_Command="AT+CIPSEND="+Single_Length;
Send_Command();
Response();
}
//TCP veya UDp bağlantısında bağlantı numarasına göre gönderilecek olan datanın uzunluğunu ayarlamak için kullanılır.
//Cevap=
void Set_TCPUP_Data_Multiple()
{
String Multiple_Length="";
AT_Command="AT+CIPSEND="+TCP_USP_ID+","+Multiple_Length;
Send_Command();
Response();
}
//TCP veya UDP bağlantısında bağlanmışken veri gönderme görevini yapar.
//Komut işlendikten sonra ">" işareti görünür ve data göndermeye başlanır.
//Gönderilecek olan verinin uzunluğu ayarlanan veri uzunluğundan daha büyükse
//cihaz busy cevabını verecektir.
//20msde aralıklar her paket gönderilir. Paket büyüklüğü maksimum 2048 bytedır.
//Paket içeriği +++ ile sonladnığında komut moduna geri döner.
//Cevap=
void Send_Data()
{
AT_Command="AT+CIPSEND";
Send_Command();
Response();
}
//TCP veya UDP için bağlantıyı kapatır.
//Cevap=
void Close_TCPUDP_Connection_Single()
{
AT_Command="AT+CIPCLOSE";
Send_Command();
Response();
}
//TCP veya UDP için ilgili ID deki bağlantıyı kapatır.
//Cevap=
void Close_TCPUDP_Connection_Multiple()
{
AT_Command="AT+CIPCLOSE="+TCP_USP_ID;
Send_Command();
Response();
}
//Cihaza IP adresinin sorulduğu fonksiyondur.
//Cevap -->CIFSR:STAIP=""
void Check_IP()
{
AT_Command="AT+CIFSR";
Send_Command();
Response();
}
//Cihaza IP adresinin sorulduğu fonksiyondur.
//Cevap -->CIFSR:STAIP=""
// -->CIFSR:STAMAC=""
void Check_IP_Existince()
{
AT_Command="AT+CIFSR?";
Send_Command();
Response();
}
//Çoklu bağlantının aktif olup olmadığını öğrenmek için kullanılır.
//Cevap==> 1:Tekli bağlantı
// 2:Çoklu bağlantı(maksimum 4)
void Check_Multiple_Connections()
{
AT_Command="AT+CIPMUX?";
Send_Command();
Response();
}
//Çoklu bağlantının aktif olup olmadığını öğrenmek için kullanılır.
//Cevap==> 1:Tekli bağlantı
// 2:Çoklu bağlantı(maksimum 4)
//Uyarı: Bu ayar yalnızca tüm bağlantılar iptal edildikten sonra güncellenebilir.
void Set_Multiple_Connections()
{
String CIPMUX_Mode="";
AT_Command="AT+CIPMUX="+CIPMUX_Mode;
Send_Command();
Response();
}
//ESP'yi server olarak ayarlamak için kullanılır.
//Giriş==> Mode: 0 ise serverı isler(bu komuttan sonra restart atılmalıdır.
// 1 ise server yaratır.
// Port: Bağlanılacak portun ayarlanması için kullanılır. Ayar yapılmadığı
//zaman 333'tür.
void Set_ESP_Server()
{
String CIPSERVER_Mode="";
String CIPSERVER_Port="";
AT_Command="AT+CIPSERVER="+CIPSERVER_Mode+","+CIPSERVER_Port;
Send_Command();
Response();
}
//Bu fonksiyon yardımıyla transfer modu öğrenilebilir.
//Cevap==> 0: normal mode
// 1: transparent mode
void Check_Transfer_Mode()
{
AT_Command="AT+CIPMODE?";
Send_Command();
Response();
}
//Bu fonksiyon yardımıyla transfer modu öğrenilebilir.
//Giriş==> 0: normal mode
// 1: transparent mode
void Set_Transfer_Mode()
{
String CIP_Mode="";
AT_Command="AT+CIPMODE?";
Send_Command();
Response();
}
//Cihazın server olarak ayarlandığında zamanaşımını öğrenmek için kullanılır.
//Cevap==> time:0-7200 saniye
void Check_Server_Timeout()
{
AT_Command="AT+CIPSTO?";
Send_Command();
Response();
}
//Bu fonksiyon yardımıyla transfer modu öğrenilebilir.
//Giriş==> 0: normal mode
// 1: transparent mode
void Set_Serve_Timeout()
{
String Timeout="";
AT_Command="AT+CIPSTO="+Timeout;
Send_Command();
Response();
}
//Modülün varsayılan fabrika ayarlarını geri yükler
void Restore()
{
AT_Command="AT+RESTORE";
Send_Command();
Response();
}
|
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <ctime>
#include <iostream>
#include <utility>
// #define DUMP_ONLY
#include <chuffed/branching/branching.h>
#include <chuffed/core/engine.h>
#include <chuffed/core/propagator.h>
#include <chuffed/globals/mddglobals.h>
#include <chuffed/support/ParseUtils.h>
#include <chuffed/vars/modelling.h>
// #include <globals/circglobals.h>
#include <chuffed/mdd/circ_fns.h>
#define HORIZON 28
template <class T>
T circ_gcc(T fff, vec<vec<T> >& xs, CardOp rel, const vec<int>& cards) {
assert(cards.size() > 0);
vec<vec<T> > vals(cards.size());
for (int ii = 0; ii < xs.size(); ii++) {
assert(xs[ii].size() == cards.size());
for (int jj = 0; jj < cards.size(); jj++) {
vals[jj].push(xs[ii][jj]);
}
}
T ret = card(fff, vals[0], rel, cards[0]);
for (int jj = 1; jj < cards.size(); jj++) {
assert(vals[jj].size() == xs.size());
ret = ret & (card(fff, vals[jj], rel, cards[jj]));
}
return ret;
}
void mdd_gcc(vec<IntVar*>& vs, CardOp op, const vec<int>& cards) {
MDDTable tab(vs.size());
vec<vec<MDD> > vars;
for (int ii = 0; ii < vs.size(); ii++) {
vars.push();
for (int jj = 0; jj < cards.size(); jj++) {
vars.last().push(tab.vareq(ii, jj));
}
}
MDD ret(circ_gcc(tab.fff(), vars, op, cards));
MDDOpts opts;
addMDD(vs, ret, opts);
}
MDD multi_sequence(MDDTable& tab, int nDays, vec<int>& bmin, vec<int>& bmax, vec<int>& bsz) {
MDD seq = tab.ttt();
for (int ii = 0; ii < bsz.size(); ii++) {
vec<MDD> terms;
for (int jj = 0; jj < nDays; jj++) {
terms.push(tab.vareq(jj, ii));
}
seq = seq & (sequence(tab.fff(), terms, bmin[ii], bmax[ii], bsz[ii]));
}
return seq;
}
const char* shift_str[] = {"m", "a", "n", "r"};
class NurseSeq : public Problem {
public:
class Opts {
public:
Opts() : model(1), gcard(0) {}
int model;
int gcard;
};
NurseSeq(Opts& opts) {
FILE* out = stdout;
gzFile file(gzdopen(0, "rb"));
Parse::StreamBuffer in(file);
Parse::skipWhitespace(in);
while (*in == '#') {
Parse::skipLine(in);
}
nNurses = Parse::parseInt(in);
nDays = Parse::parseInt(in);
nShifts = Parse::parseInt(in);
assert(nShifts == 4);
nDays = nDays > HORIZON ? HORIZON : nDays;
vec<vec<int> > coverage;
int maxcov = 0;
for (int j = 0; j < nDays; j++) {
int cov = 0;
coverage.push();
for (int i = 0; i < nShifts; i++) {
coverage.last().push(parseInt(in));
cov += coverage.last().last();
}
if (cov > maxcov) {
maxcov = cov;
}
}
nNurses = 1.5 * maxcov;
// Structure:
// Shifts: n1 n2 n3 ... nN n1 n2 ... nN
// [ Day 1 ][ .... ]
createVars(xs, nNurses * nDays, 0, nShifts - 1, true); // Eager literals
assert(xs.size() == nNurses * nDays);
// for(int xi = 0; xi < xs.size(); xi++)
// fprintf(out, "var x%d %d %d\n", xs[xi]->var_id, xs[xi]->getMin(), xs[xi]->getMax());
// FIXME: Check search strategy
// sat_sets_mid_order(&S,nNurses*nDays,nShifts,tempvars,false);
//
// Coverage
vec<int> cov_props; // Coverage propagator ids.
for (int j = 0; j < nDays; j++) {
if (opts.gcard == 0) {
for (int i = 0; i < nShifts; i++) {
// Required coverage for the day.
int req = coverage[j][i];
if (req == 0) {
continue;
}
vec<BoolView> rostered;
for (int k = 0; k < nNurses; k++) {
rostered.push(xs[(nNurses * j) + k]->getLit(i, LR_EQ)); // [[ nurse_shift = i ]]
}
bool_linear_decomp(rostered, IRT_GE, req);
#if 0
fprintf(out, "bool_linear_ge([");
bool first = true;
for(int xi = 0; xi < nNurses; xi++)
{
fprintf(out, "%sx%d=%d", first ? "" : ", ", xs[nNurses*j + xi]->var_id, i);
first = false;
}
fprintf(out, "], %d)\n", req);
#endif
}
} else {
vec<int> lbs;
for (int i = 0; i < nShifts; i++) {
lbs.push(coverage[j][i]);
}
// Allocation for the current shift.
vec<IntVar*> sv;
for (int ww = 0; ww < nNurses; ww++) {
sv.push(xs[nNurses * j + ww]);
}
mdd_gcc(sv, CARD_GE, lbs);
}
}
vec<int> bmin;
vec<int> bmax;
vec<int> bsz;
vec<int> domvec;
for (int i = 0; i < nDays; i++) {
domvec.push(nShifts);
}
// Spacing
/*
vec<dfa_trans> spaceDFA;
// dfa_trans : { src, value, dest }
static const dfa_trans nurseSpace[] =
{ {0,0,0},
{0,1,1},
{0,2,2},
{0,3,0},
{1,0,3},
{1,1,1},
{1,2,2},
{1,3,0},
{2,0,3},
{2,1,3},
{2,2,2},
{2,3,0} };
for( unsigned int i = 0; i < (sizeof(nurseSpace)/sizeof(dfa_trans)); i++ )
spaceDFA.push(nurseSpace[i]);
*/
vec<vec<int> > trans;
trans.push();
trans.last().push(1);
trans.last().push(2);
trans.last().push(3);
trans.last().push(1);
trans.push();
trans.last().push(0);
trans.last().push(2);
trans.last().push(3);
trans.last().push(1);
trans.push();
trans.last().push(0);
trans.last().push(0);
trans.last().push(3);
trans.last().push(1);
trans.push();
trans.last().push(0);
trans.last().push(0);
trans.last().push(0);
trans.last().push(0);
vec<int> accepts;
accepts.push(1);
accepts.push(2);
accepts.push(3);
int nStates = 4;
int q0 = 1;
MDDTable tab(nDays);
MDDNodeInt _spacing = fd_regular(tab, nDays, nStates, trans, q0, accepts, false);
MDD spacing(&tab, _spacing);
/* /
MDD spacing = tab.ttt();
/ */
if (opts.model == 1) {
// Model 1
// Day
bmin.push(1);
bmax.push(5);
bsz.push(7);
// Evening
bmin.push(1);
bmax.push(2);
bsz.push(7);
// Night
bmin.push(1);
bmax.push(2);
bsz.push(7);
// Off
bmin.push(2);
bmax.push(5);
bsz.push(7);
} else {
// Model 2
// Day
bmin.push(0);
bmax.push(7);
bsz.push(7);
// Evening
bmin.push(0);
bmax.push(7);
bsz.push(7);
// Night
bmin.push(1);
bmax.push(2);
bsz.push(7);
// Off
bmin.push(1);
bmax.push(2);
bsz.push(5);
}
MDD seq(multi_sequence(tab, nDays, bmin, bmax, bsz));
MDD seqprop(seq & spacing);
// MDD seqprop(spacing);
MDDOpts mopts;
vec<IntVar*> inst;
for (int i = 0; i < nNurses; i++) {
// Multi-sequence constraint
inst.clear();
for (int j = 0; j < nDays; j++) {
inst.push(xs[j * nNurses + i]);
}
addMDD(inst, seqprop, mopts);
}
fprintf(out, "satisfy\n");
}
void print(std::ostream& os) override {
for (int ii = 0; ii < nDays; ii++) {
bool first = true;
os << "[";
for (int jj = 0; jj < nNurses; jj++) {
os << (first ? "" : ", ");
os << shift_str[xs[ii * nNurses + jj]->getVal()];
first = false;
}
os << "]\n";
}
}
protected:
int nNurses;
int nDays; // Horizon
int nShifts; // Shifts per day
// Variables
vec<IntVar*> xs;
};
static char* hasPrefix(char* str, const char* prefix) {
int len = strlen(prefix);
if (strncmp(str, prefix, len) == 0) {
return str + len;
}
return nullptr;
}
int main(int argc, char** argv) {
NurseSeq::Opts opts;
// Problem-specific options
int i;
int j;
const char* value;
for (i = j = 0; i < argc; i++) {
value = hasPrefix(argv[i], "-model=");
if (value != nullptr) {
opts.model = atoi(value);
} else if (strcmp(argv[i], "-gcc") == 0) {
opts.gcard = 1;
} else {
argv[j++] = argv[i];
}
}
argc = j;
parseOptions(argc, argv);
Problem* p = new NurseSeq(opts);
#ifdef DUMP_ONLY
return 0;
#endif
engine.solve(p);
return 0;
}
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
//
// You have a deck that contains R red and B black cards.
//
//
//
// You are playing the following game: You shuffle the deck,
// and then begin dealing the cards one by one.
// For each red card you flip you get a dollar, and for each
// black card you flip you have to pay a dollar.
// At any moment (including the beginning of the game) you
// are allowed to stop and keep the money you have.
//
//
//
// Write a method that will take the ints R and B, and return
// the expected amount you will
// gain if you play this game optimally.
//
//
// DEFINITION
// Class:RedIsGood
// Method:getProfit
// Parameters:int, int
// Returns:double
// Method signature:double getProfit(int R, int B)
//
//
// NOTES
// -During the game, your balance may be negative.
// -We assume that each permutation of the cards in the deck
// is equally likely.
// -Your return value must have a relative or absolute error
// less than 1e-9.
//
//
// CONSTRAINTS
// -R will be between 0 and 5,000, inclusive.
// -B will be between 0 and 5,000, inclusive.
//
//
// EXAMPLES
//
// 0)
// 0
// 7
//
// Returns: 0.0
//
// If all cards are black, the best strategy is not to play
// at all.
//
// 1)
// 4
// 0
//
// Returns: 4.0
//
// If all cards are red, the best strategy is to flip them all.
//
// 2)
// 5
// 1
//
// Returns: 4.166666666666667
//
// The strategy "flip all cards" is guaranteed to earn $4.
// However, we can do better. If we flipped 5 cards and all
// of them are red, it makes no sense to flip the final,
// black card. Therefore if we play optimally the expected
// gain is more than $4.
//
// 3)
// 2
// 2
//
// Returns: 0.6666666666666666
//
// An optimal strategy for this case: Flip the first card. If
// it is red, stop. If it is black, flip the second and the
// third card. If both are red, stop, otherwise flip the
// fourth card.
//
// 4)
// 12
// 4
//
// Returns: 8.324175824175823
//
// This is a game I would surely like to play often.
//
// 5)
// 11
// 12
//
// Returns: 1.075642825339958
//
// Surprisingly, sometimes there is a good strategy even if
// the number of red cards is smaller than the number of
// black cards.
//
// END CUT HERE
#line 105 "RedIsGood.cc"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
double pr[5001];
double cur[5001];
class RedIsGood
{
public:
double getProfit(int R, int B)
{
fi(B+1){
pr[i] = 0.0;
cur[i] = 0.0;
}
f(i, 1, R + 1) {
cur[0] = i;
f(j, 1, B + 1) {
double p1 = pr[j] + 1;
double p2 = cur[j-1] - 1;
double tot = i + j;
double e = i / tot * p1 + j / tot * p2;
e >?= 0.0;
cur[j] = e;
}
memcpy(pr, cur, sizeof(cur));
}
return cur[B];
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 0; int Arg1 = 7; double Arg2 = 0.0; verify_case(0, Arg2, getProfit(Arg0, Arg1)); }
void test_case_1() { int Arg0 = 4; int Arg1 = 0; double Arg2 = 4.0; verify_case(1, Arg2, getProfit(Arg0, Arg1)); }
void test_case_2() { int Arg0 = 5; int Arg1 = 1; double Arg2 = 4.166666666666667; verify_case(2, Arg2, getProfit(Arg0, Arg1)); }
void test_case_3() { int Arg0 = 2; int Arg1 = 2; double Arg2 = 0.6666666666666666; verify_case(3, Arg2, getProfit(Arg0, Arg1)); }
void test_case_4() { int Arg0 = 12; int Arg1 = 4; double Arg2 = 8.324175824175823; verify_case(4, Arg2, getProfit(Arg0, Arg1)); }
void test_case_5() { int Arg0 = 11; int Arg1 = 12; double Arg2 = 1.075642825339958; verify_case(5, Arg2, getProfit(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
RedIsGood ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#ifndef CIRCULARLIST_H
#define CIRCULARLIST_H
#define NULL 0
#include "textdisp.h"
//Basic List Node Class
template <typename T>
class CDLLNode
{
T m_nodeData;
CDLLNode<T>* m_prevNode;
CDLLNode<T>* m_nextNode;
public:
CDLLNode(T nodeData) :
m_nodeData(nodeData),
m_prevNode(NULL),
m_nextNode(NULL)
{
}
CDLLNode(T nodeData, CDLLNode<T>* prevNode, CDLLNode<T>* nextNode) : m_nodeData(nodeData), m_prevNode(prevNode), m_nextNode(nextNode)
{
}
T GetNodeData() { return m_nodeData; }
void SetNodeData(T nodeData) { m_nodeData = nodeData; }
void SetNextNode(CDLLNode<T>* nextNode) { m_nextNode = nextNode; }
void SetPrevNode(CDLLNode<T>* prevNode) { m_prevNode = prevNode; }
CDLLNode<T>* GetPrevNode() { return m_prevNode; }
CDLLNode<T>* GetNextNode() { return m_nextNode; }
};
//Circular Doubly Linked List
template <typename T>
class CDLCList
{
protected:
CDLLNode<T>* m_headNode;
int m_listSize;
void CreateInitialList(T nodeData)
{
m_headNode = new CDLLNode<T>(nodeData);
m_headNode->SetPrevNode(m_headNode);
m_headNode->SetNextNode(m_headNode);
m_listSize = 1;
}
public:
CDLCList() : m_headNode(NULL), m_listSize(0) {}
~CDLCList()
{
CDLLNode<T>* temp;
while(m_headNode != NULL && m_listSize > 0)
{
temp = m_headNode;
m_headNode = m_headNode->GetNextNode();
delete temp;
temp = NULL;
--m_listSize;
}
}
void InsertAfter(CDLLNode<T>* indexNode, T nodeData)
{
CDLLNode<T>* newNode = new CDLLNode<T>(nodeData);
newNode->SetPrevNode(indexNode);
newNode->SetNextNode(indexNode->GetNextNode());
indexNode->SetNextNode(newNode);
newNode->GetNextNode()->SetPrevNode(newNode);
++m_listSize;
}
void InsertBefore(CDLLNode<T>* indexNode, T nodeData)
{
InsertAfter(indexNode->GetPrevNode(), nodeData);
}
void PushFront(T nodeData)
{
if(!m_headNode) CreateInitialList(nodeData);
else InsertAfter(m_headNode, nodeData);
}
void PushBack(T nodeData)
{
if(!m_headNode) CreateInitialList(nodeData);
else InsertBefore(m_headNode, nodeData);
}
void SetHeadNode(CDLLNode<T>* node)
{
m_headNode = node;
}
CDLLNode<T>* GetHeadNode()
{
return m_headNode;
}
int GetListSize() { return m_listSize; }
};
#endif
|
#include "mainwindow.h"
#include "init.h"
#include "ui_mainwindow.h"
#include <QCoreApplication>
#include <QScrollArea>
#include <QMessageBox>
#include <QString>
#include <QSpacerItem>
#include <qdebug>
#include <iostream>
using namespace std;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Creation de la carte et incorporation dans l'interface
// map = new Carte(ui->centralWidget);
// map->setObjectName(QString::fromUtf8("Map"));
// map->setPixmap(QPixmap(QString::fromUtf8(":/images/carte_small1.png")));
// map->setGeometry(0,0, 800, 400);
// map->setScaledContents(true);
// ui->verticalLayout_4->addWidget(map);
viewer_video = new QmlApplicationViewer;
viewer_video->setMainQmlFile(QLatin1String("qml/Tablette-v6/BOURGET.qml"));
ui->verticalLayout_4->addWidget(viewer_video);
ui->radioButton_Bourget->setAutoFillBackground(false);
// Initialisation du point d'arrivée: le départ est initialisé dans le constructeur de "carte" dans carte.cpp
//map->setArrival(Carte::NewYork);
//On initialise les valeurs min, max et current du slider (valeurs de départ = valeurs pour le printemps)
//Ainsi que l'image du dirigeable et la charge totale
ui->horizontalSlider->setRange(160,200);
ui->horizontalSlider->setValue(180);
ui->lcdNumber_charge->display(ui->horizontalSlider->value());
ui->label_dirigeable->setPixmap(QPixmap(QString::fromUtf8(":/images/images/blimp-moyen.png")));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_DimManu_clicked()
{
nextlayer2->showMaximized();
hide();
}
void MainWindow::on_pushButton_DimAuto_clicked()
{
connexion();
envoipropriete();
nextlayer1->showMaximized();
hide();
}
void MainWindow::on_pushButton_Retour_clicked()
{
previouslayer->showMaximized();
hide();
}
void MainWindow::connexion()
{
ClientAuto.start("192.168.173.1",9001);
}
void MainWindow:: envoipropriete()
{
QByteArray buffer ="";
QString propriete;
propriete += getDepart()+"\\"+getArrivee()+"\\"+getSaison()+"\\"+getCharge()+"\\"+"2";
qDebug() << "propriete : "<<propriete;
buffer.append(propriete);
qDebug() << "buffer : "<<buffer<<endl;
ClientAuto.envoieparametre(buffer);
}
QString MainWindow::getDepart()
{
// depart=ui->comboBox->currentText();
return depart;
}
QString MainWindow::getArrivee()
{
// arrivee=ui->comboBox_2->currentText();
return arrivee;
}
QString MainWindow::getSaison()
{
// saison=ui->comboBox_3->currentText();
return saison;
}
QString MainWindow::getCharge()
{
charge = ui->horizontalSlider->value();
return charge;
}
void MainWindow::on_radioButton_Printemps_clicked(bool)
{
ui->horizontalSlider->setRange(160,200); //On change l'intervale de valeurs
ui->horizontalSlider->setValue(180);// On met le slide à la valeur intermédiaire par défaut
ui->label_saison->setPixmap(QPixmap(QString::fromUtf8(":/images/images/printemps.png")));
}
void MainWindow::on_radioButton_Ete_clicked(bool)
{
ui->horizontalSlider->setRange(120,160);
ui->horizontalSlider->setValue(140);
ui->label_saison->setPixmap(QPixmap(QString::fromUtf8(":/images/images/ete.png")));
}
void MainWindow::on_radioButton_Automne_clicked(bool)
{
ui->horizontalSlider->setRange(80,120);
ui->horizontalSlider->setValue(100);
ui->label_saison->setPixmap(QPixmap(QString::fromUtf8(":/images/images/automne.png")));
}
void MainWindow::on_radioButton_Hiver_clicked(bool)
{
ui->horizontalSlider->setRange(40,80);
ui->horizontalSlider->setValue(60);
ui->label_saison->setPixmap(QPixmap(QString::fromUtf8(":/images/images/hiver.png")));
}
void MainWindow::on_radioButton_Bourget_clicked(bool)
{
viewer_video->setMainQmlFile(QLatin1String("qml/Tablette-v6/BOURGET.qml"));
viewer_video->showExpanded();
ui->verticalLayout_4->addWidget(viewer_video);
}
void MainWindow::on_radioButton_NY_clicked(bool)
{
// map->setArrival(Carte::NewYork);
// map->updateValuesToPoint(Carte::NewYork);
// map->paintEvent(0);
// map->update();
viewer_video->setMainQmlFile(QLatin1String("qml/Tablette-v6/NY.qml"));
viewer_video->showExpanded();
ui->verticalLayout_4->addWidget(viewer_video);
}
void MainWindow::on_radioButton_Vladivostock_clicked(bool)
{
// map->setArrival(Carte::Vladivostok);
// map->updateValuesToPoint(Carte::Vladivostok);
// map->paintEvent(0);
// map->update();
viewer_video->setMainQmlFile(QLatin1String("qml/Tablette-v6/VLA.qml"));
viewer_video->showExpanded();
ui->verticalLayout_4->addWidget(viewer_video);
}
void MainWindow::setNextLayers(QWidget* w1,QWidget* w2){
nextlayer1 = w1;
nextlayer2 = w2;
}
void MainWindow::setPreviousLayer(QWidget* w){
previouslayer = w;
}
void MainWindow::on_horizontalSlider_valueChanged()
{
int v = ui->horizontalSlider->value();
int max = ui->horizontalSlider->maximum();
int min = ui->horizontalSlider->minimum();
if (v == max || v == min || v == min+20)
{
ui->lcdNumber_charge->display(ui->horizontalSlider->value());
setDronepicture(max,min,v);
}
}
void MainWindow::on_horizontalSlider_sliderReleased()
{
int v = ui->horizontalSlider->value();
int max = ui->horizontalSlider->maximum();
int min = ui->horizontalSlider->minimum();
if(v <= min +10) ui->horizontalSlider->setValue(min);
else if(min+10 < v && v <= min+30) ui->horizontalSlider->setValue(min+20);
else ui->horizontalSlider->setValue(max);
ui->lcdNumber_charge->display(ui->horizontalSlider->value());
setDronepicture(max,min,v);
}
void MainWindow::setDronepicture(int max, int min, int v)
{
if (v == max)
ui->label_dirigeable->setPixmap(QPixmap(QString::fromUtf8(":/images/images/blimp-grand.png")));
else if(v == min +20)
ui->label_dirigeable->setPixmap(QPixmap(QString::fromUtf8(":/images/images/blimp-moyen.png")));
else if(v == min)
ui->label_dirigeable->setPixmap(QPixmap(QString::fromUtf8(":/images/images/blimp-petit.png")));
}
|
#pragma once
#include "llvm/GVMaterializer.h"
namespace LLVM
{
ref class GlobalValue;
ref class Module;
public ref class GVMaterializer
{
internal:
llvm::GVMaterializer *base;
protected:
GVMaterializer(llvm::GVMaterializer *base);
internal:
static inline GVMaterializer ^_wrap(llvm::GVMaterializer *base);
public:
!GVMaterializer();
virtual ~GVMaterializer();
// virtual ~GVMaterializer();
// virtual bool isMaterializable(const GlobalValue *GV) const = 0;
// virtual bool isDematerializable(const GlobalValue *GV) const = 0;
virtual bool Materialize(GlobalValue ^GV);
virtual void Dematerialize(GlobalValue ^value);
virtual bool MaterializeModule(Module ^M);
};
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#ifndef __SSLALERT_BASE_H
#define __SSLALERT_BASE_H
#ifdef _NATIVE_SSL_SUPPORT_
#include "modules/datastream/fl_tint.h"
#include "modules/locale/locale-enum.h"
class SSL_Alert_Base{
protected:
DataStream_IntegralType<SSL_AlertLevel,1> level;
DataStream_IntegralType<SSL_AlertDescription,1> description;
OpString reason;
public:
SSL_Alert_Base(){description = SSL_No_Description; level = SSL_NoError;}
SSL_Alert_Base(SSL_AlertLevel lev,SSL_AlertDescription des){Set(lev,des);}
SSL_Alert_Base(const SSL_Alert_Base &old){description = old.description; level = old.level;};
void Get(SSL_AlertLevel &lev,SSL_AlertDescription &des)const {lev=static_cast<SSL_AlertLevel>(level);des=static_cast<SSL_AlertDescription>(description);};
SSL_AlertLevel GetLevel() const{return level;};
SSL_AlertDescription GetDescription() const{return description;};
void Set(SSL_AlertLevel,SSL_AlertDescription);
void Set(OP_STATUS op_err);
void SetLevel(SSL_AlertLevel);
void SetDescription(SSL_AlertDescription);
OP_STATUS SetReason(const OpStringC &text){return reason.Set(text);}
OP_STATUS SetReason(Str::LocaleString str){return SetLangString(str, reason);}
const OpStringC &GetReason() const{return reason;};
SSL_Alert_Base &operator =(const SSL_Alert_Base &other);
};
#endif
#endif
|
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <algorithm>
using namespace std;
//Structure required for sorting according to the first element in the lines.
//Gives the comparison rule for the std::sort algorithm.
struct FirstColumnCmp
{
bool operator()(const vector<double>& lhs,\
const vector<double>& rhs) const
{
return lhs[0] < rhs[0];
}
};
int main(int argc, char* argv[])
{
string filename_in, filename_out;
if (argc == 3) {
filename_in = argv[1];
filename_out = argv[2];
} else if (argc == 2) {
filename_in = argv[1];
filename_out = filename_in;
} else {
cout << "Not the right number of arguments in SortFiles." << endl;
}
vector<vector<double>> file_contents;
ifstream inFile(filename_in);
string line;
while (getline(inFile, line))
{
istringstream iss(line);
int l;
double Fl, cond_n;
// This tests whether the line contains exactly 3 elements.
// It only reads the data if it does, ie. ignoring empty lines.
if ((iss >> l >> Fl >> cond_n))
{
vector<double> row;
row.push_back(l);
row.push_back(Fl);
row.push_back(cond_n);
file_contents.push_back(row);
}
}
inFile.close();
//Sorting by std::sort in <algorithm>
sort(file_contents.begin(), file_contents.end(), FirstColumnCmp());
ofstream outFile(filename_out);
for (int i = 0; i < file_contents.size(); i++)
{
outFile << file_contents[i][0] << " " <<\
file_contents[i][1] << " " <<\
file_contents[i][2] << endl;
}
outFile.close();
return 0;
}
|
;*******************************************************************************
; Filename: PrtTab.asm
; Description: This runtine is involved by lsACPI.asm
; Print RSDP, RSDT ... tables.
;*******************************************************************************
assume cs:code
code segment
;*******************************************************************************
; Procedure: PrintDebugCode
;
; Description: Print Debug_Code.
;
; Input: None.
;
; Output: None.
;
; Change: .
;
;*******************************************************************************
PrintDebugCode proc near
push bx
push dx
call PrintEnter
mov bl, ds:Debug_Code
call PrintBLByBit
call PrintEnter
mov dx, offset ds:Debug_Code_BIT0
call PrintString
mov dx, offset ds:Debug_Code_BIT1
call PrintString
mov dx, offset ds:Debug_Code_BIT2
call PrintString
pop dx
pop bx
ret
PrintDebugCode endp
;===============================================================================
;/*
; * Debug, set a break,
; * press ESC to quit of the routine,
; * press enter to jmp to the routine
; */
;debug proc near
; int key;
; while(1)
; {
; key = bioskey(0);
; if(key==0x011b)
; exit(0);
; else if(key==0x1c0d)
; break;
; else
; continue;
; }
;debug endp
code ends
|
//
// Test.h
// zone/ambientLightInheritence
//
// Created by Nissim Hadar on 2 Nov 2017.
// Copyright 2013 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#ifndef hifi_test_h
#define hifi_test_h
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMessageBox>
#include <QtCore/QRegularExpression>
#include "ImageComparer.h"
#include "ui/MismatchWindow.h"
class Test {
public:
Test();
void evaluateTests();
void evaluateTestsRecursively();
void createRecursiveScript();
void createTest();
QStringList createListOfAllJPEGimagesInDirectory(QString pathToImageDirectory);
bool isInSnapshotFilenameFormat(QString filename);
bool isInExpectedImageFilenameFormat(QString filename);
void importTest(QTextStream& textStream, const QString& testPathname, int testNumber);
private:
const QString testFilename{ "test.js" };
QMessageBox messageBox;
QDir imageDirectory;
QRegularExpression snapshotFilenameFormat;
QRegularExpression expectedImageFilenameFormat;
MismatchWindow mismatchWindow;
ImageComparer imageComparer;
bool compareImageLists(QStringList expectedImages, QStringList resultImages);
};
#endif // hifi_test_h
|
// kumaran_14
// #include <boost/multiprecision/cpp_int.hpp>
// using boost::multiprecision::cpp_int;
#include <bits/stdc++.h>
using namespace std;
// ¯\_(ツ)_/¯
#define f first
#define s second
#define p push
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define foi(i, a, n) for (i = (a); i < (n); ++i)
#define foii(i, a, n) for (i = (a); i <= (n); ++i)
#define fod(i, a, n) for (i = (a); i > (n); --i)
#define fodd(i, a, n) for (i = (a); i >= (n); --i)
#define debug(x) cout << '>' << #x << ':' << x << endl;
#define all(v) v.begin(), v.end()
#define sz(x) ((int)(x).size())
#define endl " \n"
#define newl cout<<"\n"
#define MAXN 100005
#define MOD 1000000007LL
#define EPS 1e-13
#define INFI 1000000000 // 10^9
#define INFLL 1000000000000000000ll //10^18
// ¯\_(ツ)_/¯
#define l long int
#define d double
#define ll long long int
#define ld long double
#define vi vector<int>
#define vll vector<long long>
#define vvi vector<vector<int>>
#define vvll vector<vll>
//vector<vector<int>> v(10, vector<int>(20,500)); 2d vector initialization. of 10 rows and 20 columns, with value 500.
#define mii map<int, int>
#define mll map<long long, long long>
#define pii pair<int, int>
#define pll pair<long long, long long>
#define fast_io() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
ll tc, n, m, k;
// ll ans = 0, c = 0;
ll i, j;
// ll a, b;
// ll x, y;
ll lcmArray(vll arr) {
auto n = sz(arr);
ll ans = arr[0];
rep(i, 1, n) {
ans = ((ans * arr[i] )/( __gcd(ans , arr[i])));
}
return ans;
}
int main()
{
fast_io();
// freopen("../input.txt", "r", stdin);
// freopen("../output.txt", "w", stdout);
// SPOJ EASYMATH
cin>>tc;
while(tc--) {
ll a, b;
cin>>n>>m>>a>>b;
ll ans = 0;
ll arr[] = {a, a+b, a+2*b, a+3*b, a+4*b};
ll ans1 = n-1, ans2 = m;
ll sign = 1;
ll range = 2<<5;
rep(bitmask, 1, range) {
auto num = __builtin_popcount(bitmask);
if(num%2) sign = -1;
else sign = 1;
vll lcmarr;
ll j = 0;
ll bit = bitmask;
while(bit > 0) {
if(bit&1 == 1) {
lcmarr.pb(arr[j]);
}
j++;
bit = bit >> 1;
}
ans1 += sign * ((n-1)/lcmArray((lcmarr)));
ans2 += sign * (m/lcmArray((lcmarr)));
}
ans = ans2 - ans1;
cout<<ans<<endl;
}
return 0;
}
|
// a1_q1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
// Assignment 1 : Question 1
// Weight types: 125 lb, 75 lb, 42 lb, 15 lb, and 1 lb
// Base Object Weight : 2048 lb
// First find the quotient of the object weight divided by the largest weight type. Take this quotient and store it.
// Then take the remainder of the object weight when divided by the weight type and store that as the object_weight, since that is still unbalanced
/*Values used to test the program include 2048, the values of each weight separately,
and numbers like 200, 117, 57, 16 since those would require different pairs of the weights.*/
/*The range of values for which this program will work correctly is : 0 to 2,147,483,647 for the object weight
(since that is the largest number an int can store) */
/*The output of the code is as follows for the base case:
Enter the weight of the object : 2048
The number of weights of each type needed are as follows :
16 of the 125 lb weights are needed.
0 of the 75 lb weights are needed.
1 of the 42 lb weights are needed.
0 of the 15 lb weights are needed.
6 of the 1 lb weights are needed. */
#include <iostream>
using namespace std;
void maximize_largest_weights() {
// function to output how many of each weight type are needed to balance the inputted object weight by maximizing the usage of the heaviest weight type
// decalare and initialize variable for the weight of the object
int object_weight; // weight of the object to be balanced
// declare and initialize variables to store the number of each weight needed
// each weight type weighs the amount of the number used in the variable
int weight_125, weight_75, weight_42, weight_15, weight_1;
// ask for user input of the object weight
cout << "Enter the weight of the object: ";
cin >> object_weight;
cout << "The number of weights of each type needed are as follows:\n";
// compute the number of weights that are needed for each weight type
// computing the number of 125 lb weights needed
if (object_weight >= 125) { // condition to check if the object weight is above the weight type that is being worked with
weight_125 = object_weight / 125; // calculating the max number of weights of the weight type that can help balance the object
object_weight = object_weight % 125; // computing and storing the weight that remains unbalanced
}
else {
weight_125 = 0; // in the case that the weight of the object is less than 125
}
cout << weight_125 << " of the 125 lb weights are needed."; // outputting the max number of weights of this type that are needed.
// computing the number of 75 lb weights needed
if (object_weight >= 75) {
weight_75 = object_weight / 75;
object_weight = object_weight % 75;
}
else {
weight_75 = 0;
}
cout << "\n" << weight_75 << " of the 75 lb weights are needed.";
// computing the number of 42 lb weights needed
if (object_weight >= 42) {
weight_42 = object_weight / 42;
object_weight = object_weight % 42;
}
else {
weight_42 = 0;
}
cout << "\n" << weight_42 << " of the 42 lb weights are needed.";
// computing the number of 15 lb weights needed
if (object_weight >= 15) {
weight_15 = object_weight / 15;
object_weight = object_weight % 15;
}
else {
weight_15 = 0;
}
cout << "\n" << weight_15 << " of the 15 lb weights are needed.";
// computing the number of 1 lb weights needed
if (object_weight >= 1) {
weight_1 = object_weight / 1;
object_weight = object_weight % 1;
}
else {
weight_1 = 0;
}
cout << "\n" << weight_1 << " of the 1 lb weights are needed.";
}
int main() {
// function to output how many of each weight type are needed to balance the inputted object weight by maximizing the usage of the heaviest weight type
maximize_largest_weights();
}
|
/*
Author: Manish Kumar
Username: manicodebits
*/
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define PI 3.141592653589
#define MOD 1000000007
#define FAST_IO ios_base::sync_with_stdio(false), cin.tie(0)
#define deb(x) cout<<"[ "<<#x<<" = "<<x<<"] "
void solve(){
int n;cin>>n;
vector<int> v(n);
for(int i=0;i<n;i++)
cin>>v[i];
int ans=0;
map<int,int> mp;
for(int i=0;i<n;i++)
{
mp[v[i]]++;
ans=max(ans,mp[v[i]]);
}
cout<<ans<<"\n";
}
signed main(){
FAST_IO;
int t=1;
cin>>t;
while(t--)
solve();
return 0;
}
|
#pragma once
#include <dijkstrasSearch.h>
Pathfinding::Node* FindClosestNode(float posX, float posY, std::vector<Pathfinding::Node*> _map);
|
/********************************************************************************
** Form generated from reading UI file 'firstlevel.ui'
**
** Created by: Qt User Interface Compiler version 5.13.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_FIRSTLEVEL_H
#define UI_FIRSTLEVEL_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QLabel>
#include <QtWidgets/QWidget>
#include <mywidget.h>
#include "drawline.h"
QT_BEGIN_NAMESPACE
class Ui_firstLevel
{
public:
QLabel *oldMan;
QLabel *firstMap;
QLabel *currentMoney;
QLabel *goalMoney;
QLabel *lastingtime;
QLabel *firstLevel_2;
drawline *invisibleListWidget;
myWidget *youwangWidget;
QLabel *bigGold;
QLabel *showCurrentMoney;
QLabel *remainingTime;
QLabel *addNumber;
QLabel *fail;
QLabel *smallGold1;
QLabel *smallGold2;
QLabel *bigGold2;
QLabel *stone1;
QLabel *stone2;
QLabel *smallGold3;
QLabel *stone3;
QLabel *luckBag1;
QLabel *currentBomb;
QLabel *bomb;
void setupUi(QWidget *firstLevel)
{
if (firstLevel->objectName().isEmpty())
firstLevel->setObjectName(QString::fromUtf8("firstLevel"));
firstLevel->resize(1200, 800);
oldMan = new QLabel(firstLevel);
oldMan->setObjectName(QString::fromUtf8("oldMan"));
oldMan->setGeometry(QRect(480, 0, 250, 150));
oldMan->setStyleSheet(QString::fromUtf8("border-image: url(:/oldMan/photo/oldMan.png);"));
firstMap = new QLabel(firstLevel);
firstMap->setObjectName(QString::fromUtf8("firstMap"));
firstMap->setGeometry(QRect(0, 150, 1200, 650));
firstMap->setStyleSheet(QString::fromUtf8("border-image: url(:/new/firstLevel/photo/playingBackground.png);"));
currentMoney = new QLabel(firstLevel);
currentMoney->setObjectName(QString::fromUtf8("currentMoney"));
currentMoney->setGeometry(QRect(10, 10, 150, 50));
QFont font;
font.setFamily(QString::fromUtf8("\351\273\221\344\275\223"));
font.setPointSize(16);
currentMoney->setFont(font);
currentMoney->setAlignment(Qt::AlignCenter);
goalMoney = new QLabel(firstLevel);
goalMoney->setObjectName(QString::fromUtf8("goalMoney"));
goalMoney->setGeometry(QRect(0, 80, 250, 50));
QFont font1;
font1.setPointSize(19);
goalMoney->setFont(font1);
goalMoney->setAlignment(Qt::AlignCenter);
lastingtime = new QLabel(firstLevel);
lastingtime->setObjectName(QString::fromUtf8("lastingtime"));
lastingtime->setGeometry(QRect(950, 20, 150, 50));
lastingtime->setFont(font);
lastingtime->setAlignment(Qt::AlignCenter);
firstLevel_2 = new QLabel(firstLevel);
firstLevel_2->setObjectName(QString::fromUtf8("firstLevel_2"));
firstLevel_2->setGeometry(QRect(950, 90, 250, 50));
firstLevel_2->setFont(font1);
firstLevel_2->setAlignment(Qt::AlignCenter);
invisibleListWidget = new drawline(firstLevel);
invisibleListWidget->setObjectName(QString::fromUtf8("invisibleListWidget"));
invisibleListWidget->setGeometry(QRect(0, 100, 1200, 700));
invisibleListWidget->setStyleSheet(QString::fromUtf8("background-color:transparent;"));
youwangWidget = new myWidget(firstLevel);
youwangWidget->setObjectName(QString::fromUtf8("youwangWidget"));
youwangWidget->setGeometry(QRect(507, 108, 146, 91));
bigGold = new QLabel(firstLevel);
bigGold->setObjectName(QString::fromUtf8("bigGold"));
bigGold->setGeometry(QRect(210, 470, 130, 130));
bigGold->setStyleSheet(QString::fromUtf8("border-image: url(:/golds/photo/bigGold.png);"));
showCurrentMoney = new QLabel(firstLevel);
showCurrentMoney->setObjectName(QString::fromUtf8("showCurrentMoney"));
showCurrentMoney->setGeometry(QRect(160, 10, 121, 50));
QFont font2;
font2.setPointSize(20);
showCurrentMoney->setFont(font2);
showCurrentMoney->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 255, 0);"));
remainingTime = new QLabel(firstLevel);
remainingTime->setObjectName(QString::fromUtf8("remainingTime"));
remainingTime->setGeometry(QRect(1090, 20, 60, 50));
remainingTime->setFont(font2);
remainingTime->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 255, 0);"));
addNumber = new QLabel(firstLevel);
addNumber->setObjectName(QString::fromUtf8("addNumber"));
addNumber->setGeometry(QRect(350, 50, 161, 61));
addNumber->setFont(font2);
addNumber->setStyleSheet(QString::fromUtf8("color: rgb(55, 158, 54);"));
fail = new QLabel(firstLevel);
fail->setObjectName(QString::fromUtf8("fail"));
fail->setGeometry(QRect(360, 60, 72, 15));
smallGold1 = new QLabel(firstLevel);
smallGold1->setObjectName(QString::fromUtf8("smallGold1"));
smallGold1->setGeometry(QRect(490, 570, 70, 70));
smallGold1->setStyleSheet(QString::fromUtf8("border-image: url(:/golds/photo/smallGold.png);"));
smallGold2 = new QLabel(firstLevel);
smallGold2->setObjectName(QString::fromUtf8("smallGold2"));
smallGold2->setGeometry(QRect(850, 560, 70, 70));
smallGold2->setStyleSheet(QString::fromUtf8("border-image: url(:/golds/photo/smallGold.png);"));
bigGold2 = new QLabel(firstLevel);
bigGold2->setObjectName(QString::fromUtf8("bigGold2"));
bigGold2->setGeometry(QRect(990, 410, 130, 130));
bigGold2->setStyleSheet(QString::fromUtf8("border-image: url(:/golds/photo/bigGold.png);"));
stone1 = new QLabel(firstLevel);
stone1->setObjectName(QString::fromUtf8("stone1"));
stone1->setGeometry(QRect(950, 300, 70, 70));
stone1->setStyleSheet(QString::fromUtf8("border-image: url(:/stone/photo/stones.png);"));
stone2 = new QLabel(firstLevel);
stone2->setObjectName(QString::fromUtf8("stone2"));
stone2->setGeometry(QRect(720, 460, 70, 70));
stone2->setStyleSheet(QString::fromUtf8("border-image: url(:/stone/photo/stones.png);"));
smallGold3 = new QLabel(firstLevel);
smallGold3->setObjectName(QString::fromUtf8("smallGold3"));
smallGold3->setGeometry(QRect(410, 390, 70, 70));
smallGold3->setStyleSheet(QString::fromUtf8("border-image: url(:/golds/photo/smallGold.png);"));
stone3 = new QLabel(firstLevel);
stone3->setObjectName(QString::fromUtf8("stone3"));
stone3->setGeometry(QRect(180, 330, 70, 70));
stone3->setStyleSheet(QString::fromUtf8("border-image: url(:/stone/photo/stones.png);"));
luckBag1 = new QLabel(firstLevel);
luckBag1->setObjectName(QString::fromUtf8("luckBag1"));
luckBag1->setGeometry(QRect(640, 560, 70, 80));
luckBag1->setStyleSheet(QString::fromUtf8("border-image: url(:/luckyBag/photo/luckyBag.png);"));
currentBomb = new QLabel(firstLevel);
currentBomb->setObjectName(QString::fromUtf8("currentBomb"));
currentBomb->setGeometry(QRect(650, 40, 121, 50));
currentBomb->setFont(font);
currentBomb->setAlignment(Qt::AlignCenter);
bomb = new QLabel(firstLevel);
bomb->setObjectName(QString::fromUtf8("bomb"));
bomb->setGeometry(QRect(760, 40, 60, 50));
bomb->setFont(font2);
bomb->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 255, 0);"));
oldMan->raise();
firstMap->raise();
currentMoney->raise();
goalMoney->raise();
lastingtime->raise();
firstLevel_2->raise();
bigGold->raise();
showCurrentMoney->raise();
remainingTime->raise();
addNumber->raise();
smallGold1->raise();
smallGold2->raise();
bigGold2->raise();
stone1->raise();
stone2->raise();
smallGold3->raise();
stone3->raise();
invisibleListWidget->raise();
luckBag1->raise();
youwangWidget->raise();
currentBomb->raise();
bomb->raise();
fail->raise();
retranslateUi(firstLevel);
QMetaObject::connectSlotsByName(firstLevel);
} // setupUi
void retranslateUi(QWidget *firstLevel)
{
firstLevel->setWindowTitle(QCoreApplication::translate("firstLevel", "\351\273\204\351\207\221\347\237\277\345\267\245", nullptr));
oldMan->setText(QString());
firstMap->setText(QString());
currentMoney->setText(QCoreApplication::translate("firstLevel", "\345\275\223\345\211\215\351\207\221\351\242\235\357\274\232", nullptr));
goalMoney->setText(QCoreApplication::translate("firstLevel", "\347\233\256\346\240\207\351\207\221\351\242\235\357\274\232$650", nullptr));
lastingtime->setText(QCoreApplication::translate("firstLevel", "\345\211\251\344\275\231\346\227\266\351\227\264\357\274\232", nullptr));
firstLevel_2->setText(QCoreApplication::translate("firstLevel", "\347\254\2541\345\205\263", nullptr));
bigGold->setText(QString());
showCurrentMoney->setText(QCoreApplication::translate("firstLevel", "$0", nullptr));
remainingTime->setText(QCoreApplication::translate("firstLevel", "60", nullptr));
addNumber->setText(QString());
fail->setText(QString());
smallGold1->setText(QString());
smallGold2->setText(QString());
bigGold2->setText(QString());
stone1->setText(QString());
stone2->setText(QString());
smallGold3->setText(QString());
stone3->setText(QString());
luckBag1->setText(QString());
currentBomb->setText(QCoreApplication::translate("firstLevel", "\347\202\270\345\274\271\346\225\260\357\274\232", nullptr));
bomb->setText(QCoreApplication::translate("firstLevel", "0", nullptr));
} // retranslateUi
};
namespace Ui {
class firstLevel: public Ui_firstLevel {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_FIRSTLEVEL_H
|
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int beautifulDays(int i, int j, int k) {
int reminder,rev,temp,val,c=0;
//printf("%d %d %d\n",i,j,k);
for(val=i;val<=j;val++)
{
rev=0;
temp=val;
while(temp > 0)
{
reminder=temp % 10;
rev=rev * 10+ reminder;
temp/=10;
}
int result=abs(rev-val);
double ans= result/(k*1.0);
int ans1=ans;
double result1=ans-ans1;
if(result1==0)
{
c++;
}
}
return c;
}
int main() {
int i;
int j;
int k;
scanf("%i %i %i", &i, &j, &k);
int result = beautifulDays(i, j, k);
printf("%d\n", result);
return 0;
}
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
UGV TRACKING AND FOLLOWING MANEUVER
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//HEADER FILES
#include "maneuvers/ugv_follow_maneuver.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using namespace std;
using namespace Eigen;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CONSTRUCTOR
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ugv_follow::ugv_follow(const ros::NodeHandle& nh): nh_(nh)
{
//Current position of the quadrotor
mavPos_ << 0.0, 0.0, 0.0;
//Current velocity of the quadrotor
mavVel_ << 0.0, 0.0, 0.0;
//Current position of the UGV obtained from the Kalman Filter
ugv_position << 0.0, 0.0, 0.0;
//Current velocity of the UGV obtained from the Kalman Filter
ugv_velocity << 0.0, 0.0, 0.0;
//Current acceleration of the UGV obtained from the Kalman Filter
ugv_acceleration << 0.0, 0.0, 0.0;
//Current orientation of the UGV obtained from the Kalman Filter
ugv_attitude << 1.0, 0.0, 0.0, 0.0;
//Variable to store the position of the UGV at some time in future
ugvpos_future << 0.0, 0.0, 0.0;
//Variable to store the velocity of the UGV at some time on future
ugvvel_future << 0.0, 0.0, 0.0;
//Yaw orientation fof the UGV
ugv_yaw = 0.0;
elasped_time = 0.0;
//Tracking and following of the UGV is carried out in two phases. The manuever starts with the quadrotor trying
//to catch up with the UGV. This becomes phase 1. In the next phase the quadrotor tries to closely follow the
//UGV at a given height by making use of onboard camera to detect the UGV
phase = 1;
//Acceleration due to gravity in NED frame
g_ << 0.0, 0.0, 9.81;
//The mean velocity at which the quadrotor is assumed to follow the ugv. This parameter is used for determining
//the point and time of intersection. Altering the parameter in the parameter file can speed up or slow down
//the quadrotor approach maneuver.
nh_.param<double>("/trajectory_generator/ugv_follow_velocity", ugv_follow_velocity, 5.0);
//Height above the UGV at which the quadrotor tracks the UGV
nh_.param<double>("/trajectory_generator/hover_height", hover_height, 1.0);
//To initiate the landing procedure. If this variable is 0 then quadrotor does not land on ugv.
//Only if this variable is 1 landing is initiated
nh_.param<int>("/trajectory_generator/ugv_land_init", ugv_land_init, 0);
//Subscriber to obtain the current position, velocity, acceleration and attitude of the UGV from a Kalman Filter
vehicle_posSub_ = nh_.subscribe("/odometry/filtered", 50, &ugv_follow::ugv_state_sub, this,ros::TransportHints().tcpNoDelay());
//Subscriber to obtain the current acceleration of the UGV from the Kalman Filter
accelSub_ = nh_.subscribe("/accel/filtered", 30, &ugv_follow::ugv_accel_sub, this,ros::TransportHints().tcpNoDelay());
//Subscriber to obtain the current position and attitude of the quadrotor
mavPoseSub_ = nh_.subscribe("/mavros/local_position/pose", 50, &ugv_follow::mav_pose_sub, this,ros::TransportHints().tcpNoDelay());
//Subscriber to obtain the current velocity of the quadrotor
mavtwistSub_ = nh_.subscribe("/mavros/local_position/velocity_local", 50, &ugv_follow::mavtwistCallback, this,ros::TransportHints().tcpNoDelay());
}
ugv_follow::~ugv_follow() {
//Destructor
}
double ugv_follow::maneuver_init(double trigger_time)
{
//Distance between the UGV and quadrotor along the XY plane
dist_to_ugv = planar_distance_calculator(mavPos_, ugv_position);
//If the above calculated distance is less than 0.2m then phase 2 of UGV tracking is initiated
if(dist_to_ugv < 0.2)
{
//Getting the start time of the landing maneuver(phase 2).
if(phase == 1)
start_time = ros::Time::now();
phase = 2;
time_to_intersection = 0.1;
}
else
{
phase = 1;
time_to_intersection = dist_to_ugv/ugv_follow_velocity;
}
//Intersection trajectory recalculation happens only when there is significant variation in the
//predicted intersection point over successive iterations
if(future_state_predict() && phase == 1)
{
elasped_time = trigger_time;
//Setting the desired z axis position of the quadrotor to be the hover height
ugvpos_future[2] = hover_height;
//Number of dimensions that need to be considered for each waypoint e.g. Dimension of 3 requires the definition
//of the waypoint derivatives along X, Y and Z.
const int dimension = 3;
//Trajectory generation is carried out using the mav_trajectory_generation package
mav_trajectory_generation::Vertex::Vector vertices;
//Defintion of two waypoints. The first waypoint is the current position of the quadrotor and the next
//waypoint is the future position of the UGV at the assumed point of intersection between the UGV
//and the quadrotor
mav_trajectory_generation::Vertex start(dimension), end(dimension);
//Generated trajectory has to be a velocity minimal trajectory for quick approach
const int derivative_to_optimize = mav_trajectory_generation::derivative_order::VELOCITY;
//The starting point of the trajectory. This is the current position of the quadrotor
start.makeStartOrEnd(mavPos_, derivative_to_optimize);
start.addConstraint(mav_trajectory_generation::derivative_order::VELOCITY, mavVel_);
vertices.push_back(start);
//The ending point of the trajectory is the future position and velocity of the UGV at the
//calculated point of intersection between the UGV and the quadrotor
end.makeStartOrEnd(ugvpos_future, derivative_to_optimize);
end.addConstraint(mav_trajectory_generation::derivative_order::VELOCITY, ugvvel_future);
vertices.push_back(end);
//Calculation of the velocity continous optimal trajectory that passes through the given vertices.
//Using the generated trajectory object, the desired position, velocity, accelration and jerk along
//the trajectory can be convienently calculated. Desired angular velocity can also be determined
//taking into consideration the differenetial flatnees nature of the quadrotor. Yaw planning is not
//coupled with trajectory design
//Time to intersection is assigned as the segment time
std::vector<double> segment_times;
segment_times.push_back(time_to_intersection);
//Total time for traversing the trajectory
eth_trajectory_init(vertices, segment_times, derivative_to_optimize);
}
//Return a large value for return time to ensure tracking of the UGV by the quadrotor is not stopped
//abruptly in the trajectoryPublisher.cpp code
return 1000.0;
}
void ugv_follow::trajectory_generator(double time)
{
//Recalculate the interception trajectory with the UGV
maneuver_init(time);
//Resetting the time to 0 after a new trajectory has been calculated from the above function call.
//When a new trajectory is calculated by the mav_trajectory_generation package the position, velocity
//and acceleration along that trajectory are calculated from time 0. So the trigger time obtained
//from trajectoryPublisher.cpp has to be re intialised to 0 after every new interception trajectory
//determination
time -= elasped_time;
//Phase 1 corresponds to high speed approach maneuver towards the UGV
if(phase == 1)
{
//Target position obtained from the generated trajectory object using the mav_trajectory_generation package
target_position = eth_trajectory_pos(time);
//Target velocity obtained from the generated trajectory object using the mav_trajectory_generation package
target_velocity = eth_trajectory_vel(time);
//Target acceleration obtained from the generated trajectory object using the mav_trajectory_generation package
target_acceleration = eth_trajectory_acc(time);
//Target jerk obtained from the generated trajectory object using the mav_trajectory_generation package
target_jerk = eth_trajectory_jerk(time);
//Target jerk obtained from the generated trajectory object using the mav_trajectory_generation package
target_angvel = calculate_trajectory_angvel();
//This parameter decides the mode of operation of the controller. The controller can work in 5 modes
//MODE 0 - IGNORE ALL TRAJECTORY TARGET INPUTS (POSITION, VELOCITY, ACCELERATION, ANGULAR VELOCITY, YAW)
//MODE 1 - ACCEPT ALL TRAJECTORY TARGET INPUTS FOR CONTROL OUTPUT CALCULATION
//MODE 2 - IGNORE ONLY POSITION FOR CONTROL OUTPUT CALCULATION (ERROR IS TAKEN AS 0)
//MODE 3 - IGNORE ONLY VELOCITY FOR CONTROL OUTPUT CALCULATION (ERROR IS TAKEN AS 0)
//MODE 4 - IGNORE POSITION AND VELOCITY FOR CONTROL OUTPUT CALCULATION (ERROR IS TAKEN AS 0)
//MODE 5 - SWITCH OFF TRAJECTORY PUBLISHER
type = 1;
}
//Phase 2 corresponds to close tracking of the UGV at a given hover height or landing on the UGV
//whichever out of the two has been commanded by the user by the ugv_land_init variable
else if(phase == 2)
{
//Target position obtained from the generated trajectory object using the mav_trajectory_generation package
target_position = ugvpos_future;
//Target acceleration obtained from the generated trajectory object using the mav_trajectory_generation package
target_acceleration = ugv_acceleration;
//If landing is commanded by the user then the height of the quadrotor is linearly reduced
if(ugv_land_init)
{
target_position[2] = hover_height - (hover_height - ugv_position[2])*(ros::Time::now() - start_time).toSec()/10.0;
if((ros::Time::now() - start_time).toSec() > 10.0)
{
ROS_INFO("LANDED");
type = 5;
//The motors need to stop when the quadrotor reaches a certain height over the UGV. For this
//a negative accelaration is given(has to be greater than g) which will saturate the motor
//in its lower limit and stop the motors. CAN BE IMPROVED
target_acceleration << 0.0, 0.0, -10.0;
}
}
else
{
target_position[2] = hover_height;
type = 1;
}
//Target velocity obtained from the generated trajectory object using the mav_trajectory_generation package
target_velocity = ugvvel_future;
//Target jerk obtained from the generated trajectory object using the mav_trajectory_generation package
target_jerk << 0.0, 0.0, 0.0;
//Target jerk obtained from the generated trajectory object using the mav_trajectory_generation package
target_angvel << 0.0, 0.0, 0.0;
}
//Target Yaw is taken to be 0.0
target_yaw = ugv_yaw;
}
Eigen::Vector3d ugv_follow::calculate_trajectory_angvel()
{
Eigen::Vector3d acc, jerk, h, zb, w, xc, yb, xb;
float m = 0.95;
Eigen::Vector3d g;
g << 0, 0, 9.8;
acc = target_acceleration + g;
jerk = target_jerk;
double u = acc.norm();
zb = acc/u;
xc << cos(target_yaw),sin(target_yaw),0;
yb = zb.cross(xc) / (zb.cross(xc)).norm();
xb = yb.cross(zb) / (yb.cross(zb)).norm();
h = (m/u)*(jerk - (zb.dot(jerk))*zb);
w(0) = -h.dot(yb);
w(1) = h.dot(xb);
w(2) = 0;
return w;
}
Eigen::Vector3d ugv_follow::get_target_pos()
{
//Return the desired position
return target_position;
}
Eigen::Vector3d ugv_follow::get_target_vel()
{
//Return the desired velocity
return target_velocity;
}
Eigen::Vector3d ugv_follow::get_target_acc()
{
//Return the desired acceleration
return target_acceleration;
}
Eigen::Vector3d ugv_follow::get_target_angvel()
{
//Return the desired angular velocity
return target_angvel;
}
Eigen::Vector3d ugv_follow::get_target_jerk()
{
//Return the desired jerk
return target_jerk;
}
double ugv_follow::get_target_yaw()
{
//Return the desired yaw
return target_yaw;
}
int ugv_follow::get_type()
{
//Return the desired mode of operation of the controller
return type;
}
//Function to subscribe to the current acceleration of the UGV
void ugv_follow::ugv_accel_sub(const geometry_msgs::AccelWithCovarianceStamped& msg){
ugv_acceleration << msg.accel.accel.linear.x, msg.accel.accel.linear.y, msg.accel.accel.linear.z;
}
//Function to subscribe to the current position, velocity and attitude of the UGV
void ugv_follow::ugv_state_sub(const nav_msgs::Odometry& msg)
{
//Current UGV position
ugv_position << msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z;
//Current UGV velocity
ugv_velocity << msg.twist.twist.linear.x, msg.twist.twist.linear.y, msg.twist.twist.linear.z;
//Current UGV attitude
ugv_attitude << msg.pose.pose.orientation.w, msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z;
//Current UGV Yaw calculated from the attitude
ugv_yaw = atan2(2 * (ugv_attitude(0) * ugv_attitude(3) + ugv_attitude(1) * ugv_attitude(2)), 1 - 2 * (ugv_attitude(2) * ugv_attitude(2) + ugv_attitude(3) * ugv_attitude(3)));
//Velocity transformation is required for aligning the direction of velocity published from the
//Kalman filter with the axes direction used in the program
Eigen::Matrix3d R;
R << cos(ugv_yaw), -sin(ugv_yaw), 0,
sin(ugv_yaw), cos(ugv_yaw), 0,
0 , 0 , 1;
ugv_velocity = R*ugv_velocity;
}
//Function to subscribe to the current position of the quadrotor
void ugv_follow::mav_pose_sub(const geometry_msgs::PoseStamped& msg){
mavPos_ << msg.pose.position.x, msg.pose.position.y, msg.pose.position.z;
}
//Function to subscribe to the current velocity of the quadrotor
void ugv_follow::mavtwistCallback(const geometry_msgs::TwistStamped& msg){
mavVel_ << msg.twist.linear.x, msg.twist.linear.y, msg.twist.linear.z;
}
//Function to determine the future position and velocity of the UGV based on its current position,
//velocity and acceleration. The predicted data is then used for predicting interception trajectories
//with the quadrotor. The future states are predicted using a linear motion model
bool ugv_follow::future_state_predict()
{
Eigen::Vector3d dummy_pos;
double dummy_error;
ugvvel_future = ugv_velocity + ugv_acceleration*time_to_intersection;
dummy_pos = ugv_position + ugvvel_future*time_to_intersection;
//The error between the previously predicted future UGV position and the future UGV position
//calculated now. The approach trajectory is recalculted only if the variation between the
//two is significant
dummy_error = planar_distance_calculator(dummy_pos, ugvpos_future);
ugvpos_future = dummy_pos;
if(dummy_error > 0.2)
return 1;
else
return 0;
}
//Function to calculate the distance along the XY plane for two given vectors
double ugv_follow::planar_distance_calculator(Eigen::Vector3d& v1, Eigen::Vector3d& v2)
{
return pow(((v1[0]-v2[0])*(v1[0]-v2[0]) + (v1[1]-v2[1])*(v1[1]-v2[1])),0.5);
}
|
#include "Firebase_Client_Version.h"
#if !FIREBASE_CLIENT_VERSION_CHECK(40319)
#error "Mixed versions compilation."
#endif
/**
* Firebase TCP Client v1.2.7
*
* Created July 10, 2023
*
* The MIT License (MIT)
* Copyright (c) 2023 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning 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 FB_TCP_Client_CPP
#define FB_TCP_Client_CPP
#include <Arduino.h>
#include "mbfs/MB_MCU.h"
#if (defined(ESP8266) || defined(MB_ARDUINO_PICO)) && !defined(FB_ENABLE_EXTERNAL_CLIENT)
#include "FB_TCP_Client.h"
FB_TCP_Client::FB_TCP_Client(bool initSSLClient)
{
if (!wcs && initSSLClient)
{
wcs = std::unique_ptr<FB_ESP_SSL_CLIENT>(new FB_ESP_SSL_CLIENT());
client = wcs.get();
}
}
FB_TCP_Client::~FB_TCP_Client()
{
release();
}
void FB_TCP_Client::setInsecure()
{
if (!wcs)
return;
wcs->setInsecure();
}
void FB_TCP_Client::setCACert(const char *caCert)
{
release();
wcs = std::unique_ptr<FB_ESP_SSL_CLIENT>(new FB_ESP_SSL_CLIENT());
client = wcs.get();
if (caCert)
{
x509 = new X509List(caCert);
wcs->setTrustAnchors(x509);
baseSetCertType(fb_cert_type_data);
}
else
{
wcs->setInsecure();
baseSetCertType(fb_cert_type_none);
}
wcs->setBufferSizes(bsslRxSize, bsslTxSize);
}
bool FB_TCP_Client::setCertFile(const char *caCertFile, mb_fs_mem_storage_type storageType)
{
if (!wcs)
return false;
if (clockReady && strlen(caCertFile) > 0)
{
MB_String filename = caCertFile;
if (filename.length() > 0)
{
if (filename[0] != '/')
filename.prepend('/');
}
int len = mbfs->open(filename, storageType, mb_fs_open_mode_read);
if (len > -1)
{
uint8_t *der = MemoryHelper::createBuffer<uint8_t *>(mbfs, len);
if (mbfs->available(storageType))
mbfs->read(storageType, der, len);
mbfs->close(storageType);
wcs->setTrustAnchors(new X509List(der, len));
MemoryHelper::freeBuffer(mbfs, der);
baseSetCertType(fb_cert_type_file);
}
}
wcs->setBufferSizes(bsslRxSize, bsslTxSize);
return getCertType() == fb_cert_type_file;
}
void FB_TCP_Client::setBufferSizes(int recv, int xmit)
{
bsslRxSize = recv;
bsslTxSize = xmit;
}
bool FB_TCP_Client::networkReady()
{
return (WiFi.status() == WL_CONNECTED && validIP(WiFi.localIP())) || ethLinkUp();
}
void FB_TCP_Client::networkReconnect()
{
#if defined(ESP8266)
WiFi.reconnect();
#else
#endif
}
void FB_TCP_Client::networkDisconnect()
{
WiFi.disconnect();
}
fb_tcp_client_type FB_TCP_Client::type()
{
return fb_tcp_client_type_internal;
}
bool FB_TCP_Client::isInitialized() { return true; }
int FB_TCP_Client::hostByName(const char *name, IPAddress &ip)
{
return WiFi.hostByName(name, ip);
}
// override the base connect
bool FB_TCP_Client::connect()
{
if (!wcs)
return false;
if (connected())
{
flush();
return true;
}
client = wcs.get();
lastConnMillis = millis();
if (!client->connect(host.c_str(), port))
return setError(FIREBASE_ERROR_TCP_ERROR_CONNECTION_REFUSED);
wcs->setTimeout(timeoutMs);
// For TCP keepalive should work in ESP8266 core > 3.1.2.
// https://github.com/esp8266/Arduino/pull/8940
// Not currently supported by WiFiClientSecure in Arduino Pico core
#if defined(ESP8266) && defined(USE_CONNECTION_KEEP_ALIVE_MODE) // Use TCP KeepAlive (interval connection probing) together with HTTP connection Keep-Alive
if (isKeepAliveSet())
{
if (tcpKeepIdleSeconds == 0 || tcpKeepIntervalSeconds == 0 || tcpKeepCount == 0)
wcs->disableKeepAlive();
else
wcs->keepAlive(tcpKeepIdleSeconds, tcpKeepIntervalSeconds, tcpKeepCount);
}
#endif
return connected();
}
void FB_TCP_Client::setTimeout(uint32_t timeoutmSec)
{
if (wcs)
wcs->setTimeout(timeoutmSec);
baseSetTimeout(timeoutmSec / 1000);
}
bool FB_TCP_Client::begin(const char *host, uint16_t port, int *response_code)
{
if (!wcs)
return false;
this->host = host;
this->port = port;
this->response_code = response_code;
ethDNSWorkAround();
wcs->setBufferSizes(bsslRxSize, bsslTxSize);
return true;
}
int FB_TCP_Client::beginUpdate(int len, bool verify)
{
if (!wcs)
return FIREBASE_ERROR_FW_UPDATE_BEGIN_FAILED;
int code = 0;
#if defined(ESP8266)
if (len > (int)ESP.getFreeSketchSpace())
{
code = FIREBASE_ERROR_FW_UPDATE_TOO_LOW_FREE_SKETCH_SPACE;
}
else if (verify)
{
uint8_t buf[4];
if (wcs->peekBytes(&buf[0], 4) != 4)
code = FIREBASE_ERROR_FW_UPDATE_INVALID_FIRMWARE;
else
{
// check for valid first magic byte
if (buf[0] != 0xE9 && buf[0] != 0x1f)
{
code = FIREBASE_ERROR_FW_UPDATE_INVALID_FIRMWARE;
}
else if (buf[0] == 0xe9)
{
uint32_t bin_flash_size = ESP.magicFlashChipSize((buf[3] & 0xf0) >> 4);
// check if new bin fits to SPI flash
if (bin_flash_size > ESP.getFlashChipRealSize())
{
code = FIREBASE_ERROR_FW_UPDATE_BIN_SIZE_NOT_MATCH_SPI_FLASH_SPACE;
}
}
}
}
if (code == 0)
{
if (!Update.begin(len, 0, -1, 0))
{
code = FIREBASE_ERROR_FW_UPDATE_BEGIN_FAILED;
}
}
#elif defined(MB_ARDUINO_PICO)
if (!Update.begin(len))
code = FIREBASE_ERROR_FW_UPDATE_BEGIN_FAILED;
#endif
return code;
}
bool FB_TCP_Client::ethLinkUp()
{
if (!eth && config)
eth = &(config->spi_ethernet_module);
if (!eth)
return false;
bool ret = false;
#if defined(ESP8266) && defined(ESP8266_CORE_SDK_V3_X_X)
#if defined(INC_ENC28J60_LWIP)
if (eth->enc28j60)
{
ret = eth->enc28j60->status() == WL_CONNECTED;
goto ex;
}
#endif
#if defined(INC_W5100_LWIP)
if (eth->w5100)
{
ret = eth->w5100->status() == WL_CONNECTED;
goto ex;
}
#endif
#if defined(INC_W5500_LWIP)
if (eth->w5500)
{
ret = eth->w5500->status() == WL_CONNECTED;
goto ex;
}
#endif
#elif defined(MB_ARDUINO_PICO)
#endif
return ret;
#if defined(INC_ENC28J60_LWIP) || defined(INC_W5100_LWIP) || defined(INC_W5500_LWIP)
ex:
#endif
// workaround for ESP8266 Ethernet
delayMicroseconds(0);
return ret;
}
bool FB_TCP_Client::validIP(IPAddress ip)
{
return strcmp(ip.toString().c_str(), "0.0.0.0") != 0;
}
void FB_TCP_Client::ethDNSWorkAround()
{
if (!eth)
return;
#if defined(ESP8266) && defined(ESP8266_CORE_SDK_V3_X_X)
#if defined(INC_ENC28J60_LWIP)
if (eth->enc28j60)
goto ex;
#endif
#if defined(INC_W5100_LWIP)
if (eth->w5100)
goto ex;
#endif
#if defined(INC_W5500_LWIP)
if (eth->w5500)
goto ex;
#endif
#elif defined(MB_ARDUINO_PICO)
#endif
return;
#if defined(INC_ENC28J60_LWIP) || defined(INC_W5100_LWIP) || defined(INC_W5500_LWIP)
ex:
WiFiClient _client;
_client.connect(host.c_str(), port);
_client.stop();
#endif
}
void FB_TCP_Client::release()
{
if (wcs)
{
wcs->stop();
wcs.reset(nullptr);
wcs.release();
if (x509)
delete x509;
baseSetCertType(fb_cert_type_undefined);
}
client = nullptr;
}
#endif /* ESP8266 */
#endif /* FB_TCP_Client_CPP */
|
//
// Created by cirkul on 27.11.2020.
//
#include "Herbivorous.h"
Animal *Herbivorous::spawn(Playground &pg, int i, int j) {
Herbivorous *newAnimal = new Herbivorous(pg, i, j);
++newAnimal->home->creatureCount;
newAnimal->pg->newCreatures[newAnimal] = 1;
newAnimal->pg->allAnimals.push_back(newAnimal);
newAnimal->home->animals.push_back(newAnimal);
return newAnimal;
}
void Herbivorous::eat() {
if (this->satietyInd == this->maxSatisfaction)
return;
Plant *food = this->home->plant;
if (food == nullptr || !food->isAlive)
return;
if (this->satietyInd == this->maxSatisfaction)
return;
if (food->hp > this->maxSatisfaction - this->satietyInd) {
food->hp -= this->maxSatisfaction - this->satietyInd;
this->satietyInd = maxSatisfaction;
} else {
this->satietyInd += food->hp;
food->isAlive = false;
}
}
bool Herbivorous::escape() { return rand() % 100 + 1 < this->escChance; }
|
#include <cassert>
/// In "frontend/util/"
#include <std_code.h>
#include <namespace.h>
#include <frontend/langapi/language_util.h>
#include "expression.h"
const std::string Type::id_string() const
{ return _type.id_string();}
bool Type::is_boolean_number() const
{ return _type.id()==ID_bool;}
bool Type::is_integral_number() const
{ return is_signed() || is_unsigned();}
size_t Type::get_bit_width() const
{
assert(is_integral_number());
return _type.get_int(ID_width);
}
bool Type::is_signed() const
{ return _type.id()==ID_signedbv;}
bool Type::is_unsigned() const
{ return _type.id()==ID_unsignedbv;}
bool Type::is_floating_number() const
{ return _type.id()==ID_floatbv;}
bool Type::is_pointer() const
{ return _type.id()==ID_pointer;}
bool Type::is_array() const
{ return _type.id()==ID_array;}
bool Type::is_array_incomplete() const
{ return get_array_bound().is_nil();}
Expression Type::get_array_bound() const
{
const exprt& e = static_cast<const exprt &>( _type.find(ID_size) );
return Expression(e, _ns);
}
bool Type::is_struct() const
{ return _type.id()==ID_struct;}
bool Type::is_union() const
{ return _type.id()==ID_union;}
Expression::Expression(const exprt& e, const namespacet& ns)
:_expr(e), _ns(ns), _type(ns.follow(e.type()), ns){}
Expression::Expression(const Expression& ex)
:_expr(ex._expr), _ns(ex._ns), _type(ex._type){}
const std::string Expression::id_string() const
{ return _expr.id_string();}
const std::string Expression::location_string() const
{ return _expr.find_location().as_string();}
const Type& Expression::type() const
{ return _type;}
bool Expression::is_nil() const
{ return _expr.is_nil();}
bool Expression::is_expr_lvalue() const
{
return(is_identifier()
|| is_op_index()
|| is_op_member()
|| is_op_dereference())
&&(_type.is_integral_number()
|| _type.is_floating_number()
|| _type.is_array()
|| _type.is_pointer()
|| _type.is_struct()
|| _type.is_union());
}
bool Expression::is_expr_primary() const
{
return
is_constant()
|| is_string_literal()
|| is_identifier();
}
bool Expression::is_constant() const
{ return _expr.id()==ID_constant;}
std::string Expression::get_value() const
{
assert( this->is_constant() );
return from_expr(_expr);
}
bool Expression::is_null_pointer() const
{
if(_expr.get(ID_value) != ID_NULL)
return false;
assert(_type.is_pointer());
return true;
}
bool Expression::is_string_literal() const
{ return _expr.id()==ID_string_constant;}
bool Expression::is_identifier() const
{ return _expr.id()==ID_symbol;}
const std::string& Expression::get_identifier() const
{ return _expr.get(ID_identifier).as_string();}
bool Expression::is_expr_postfix() const
{
return
is_op_index()
|| is_op_member()
|| is_compound_literal();
}
bool Expression::is_op_index() const
{ return _expr.id()==ID_index;}
Expression Expression::operand_base() const
{
assert(is_op_index());
return operand_left();
}
Expression Expression::operand_offset() const
{
assert(is_op_index());
return operand_right();
}
bool Expression::is_op_member() const
{ return _expr.id()==ID_member;}
const std::string& Expression::get_member_name() const
{ return _expr.get_string(ID_component_name);}
bool Expression::is_compound_literal() const
{
return
is_unnamed_struct()
|| is_unnamed_array();
}
bool Expression::is_unnamed_struct() const
{ return _expr.id()==ID_struct;}
bool Expression::is_unnamed_array() const
{ return _expr.id()==ID_array;}
size_t Expression::get_array_size() const
{
assert( is_unnamed_array() );
return _expr.operands().size();
}
Expression Expression::get_array_element(const size_t& index) const
{
assert( is_unnamed_array() );
assert( index < get_array_size() );
return Expression(_expr.operands().at(index), _ns);
}
bool Expression::is_expr_unary() const
{
/// Note: No access operators
if(is_op_unary_plus()
|| is_op_unary_minus()
|| is_op_logical_not()
|| is_op_bitwise_not()
|| is_op_address_of()
|| is_op_dereference())
{
assert(_expr.operands().size()==1);
return true;
}
return false;
}
Expression Expression::operand() const
{ return Expression(_expr.op0(), _ns);}
bool Expression::is_op_unary_plus() const
{ return _expr.id()==ID_unary_plus;}
bool Expression::is_op_unary_minus() const
{ return _expr.id()==ID_unary_minus;}
bool Expression::is_op_logical_not() const
{ return _expr.id()==ID_not;}
bool Expression::is_op_bitwise_not() const
{ return _expr.id()==ID_bitnot;}
bool Expression::is_op_address_of() const
{ return _expr.id()==ID_address_of;}
bool Expression::is_op_dereference() const
{ return _expr.id()==ID_dereference;}
bool Expression::is_expr_cast() const
{
if(_expr.id()==ID_typecast)
{
assert(_expr.operands().size()==1);
return true;
}
return false;
}
bool Expression::is_expr_binary() const
{
if(is_expr_multiplicative()
|| is_expr_additive()
|| is_expr_shift()
|| is_expr_comparison()
|| is_expr_bin_bitwise()
|| is_expr_bin_logical())
{
if(_expr.operands().size()!=2)
return false;
return true;
}
return false;
}
Expression Expression::operand_left() const
{ return Expression(_expr.op0(), _ns);}
Expression Expression::operand_right() const
{ return Expression(_expr.op1(), _ns);}
bool Expression::is_expr_multiplicative() const
{
return
is_op_mult()
|| is_op_div()
|| is_op_mod();
}
bool Expression::is_expr_additive() const
{ return is_op_add() || is_op_sub();}
bool Expression::is_op_add() const
{ return _expr.id()==ID_plus;}
bool Expression::is_op_sub() const
{ return _expr.id()==ID_minus;}
bool Expression::is_op_mult() const
{ return _expr.id()==ID_mult;}
bool Expression::is_op_div() const
{ return _expr.id()==ID_div;}
bool Expression::is_op_mod() const
{ return _expr.id()==ID_mod;}
bool Expression::is_expr_shift() const
{ return is_op_shift_left() || is_op_shift_right();}
bool Expression::is_op_shift_left() const
{ return _expr.id()==ID_shl;}
bool Expression::is_op_shift_right() const
{ return _expr.id()==ID_shr;}
bool Expression::is_expr_comparison() const
{
return
is_op_equal()
|| is_op_unequal()
|| is_op_greater()
|| is_op_less()
|| is_op_greater_or_equal()
|| is_op_less_or_equal();
}
bool Expression::is_op_equal() const
{ return _expr.id()==ID_equal;}
bool Expression::is_op_unequal() const
{ return _expr.id()==ID_notequal;}
bool Expression::is_op_greater() const
{ return _expr.id()==ID_gt;}
bool Expression::is_op_less() const
{ return _expr.id()==ID_lt;}
bool Expression::is_op_greater_or_equal() const
{ return _expr.id()==ID_ge;}
bool Expression::is_op_less_or_equal() const
{ return _expr.id()==ID_le;}
bool Expression::is_expr_bin_bitwise() const
{
return
is_op_bitwise_and()
|| is_op_bitwise_or()
|| is_op_bitwise_xor();
}
bool Expression::is_op_bitwise_and() const
{ return _expr.id()==ID_bitand;}
bool Expression::is_op_bitwise_or() const
{ return _expr.id()==ID_bitor;}
bool Expression::is_op_bitwise_xor() const
{ return _expr.id()==ID_bitxor;}
bool Expression::is_expr_bin_logical() const
{ return is_op_logical_and() || is_op_logical_or();}
bool Expression::is_op_logical_and() const
{ return _expr.id()==ID_and;}
bool Expression::is_op_logical_or() const
{ return _expr.id()==ID_or;}
bool Expression::is_expr_ternary() const
{
if(_expr.id()==ID_if)
{
assert(_expr.operands().size() == 3);
return true;
}
return false;
}
Expression Expression::operand_guard() const
{ return Expression(_expr.op0(), _ns);}
Expression Expression::operand_true() const
{ return Expression(_expr.op1(), _ns);}
Expression Expression::operand_false() const
{ return Expression(_expr.op2(), _ns);}
bool Expression::is_expr_side_effect() const
{ return _expr.id()==ID_sideeffect;}
|
#include <iostream>
class Cuenta
{
public:
void setX(int valor)
{
x = valor;
}
void imprimir()
{
std::cout << x << std::endl;
}
private:
int x;
};
int main()
{
Cuenta contador;
Cuenta *contadorPtr = &contador;
Cuenta &contadorRef = contador;
std::cout << "Establecer x en 1 e imprimir usando el nombre del objeto";
contador.setX(1);
contador.imprimir();
std::cout << "Establecer x en 2 e imprimir usando referencia a objeto";
contadorRef.setX(2);
contador.imprimir();
std::cout << "Establecer x en 1 e imprimir usando el nombre del objeto";
contador.setX(1);
contador.imprimir();
std::cout<<contadorPtr<<std::endl;
std::cout<<&contadorRef<<std::endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MEDIA_TIME_RANGES_H
#define MEDIA_TIME_RANGES_H
#include "modules/pi/OpMediaPlayer.h"
/** Contains a list of time ranges.
*
* This class is useful if we need to maintain a copy of the time ranges
* provided by the platform interface.
*/
class MediaTimeRanges
: public OpMediaTimeRanges
{
public:
MediaTimeRanges();
virtual ~MediaTimeRanges();
/** Copy the specified ranges into this object.
*
* @param ranges The ranges to copy.
* @return OpStatus::OK, or OpStatus::ERR_NO_MEMORY.
*/
OP_STATUS SetRanges(const OpMediaTimeRanges* ranges);
/** Check if the collection of time ranges is normalized.
*
* A normalized MediaTimeRanges is one where no ranges overlap,
* start < end for each range, and where the start times are
* sorted by increasing order.
*
* @return true if normalized, false if not.
*/
bool IsNormalized();
void Normalize();
/** Add a time range, while keeping the ranges normalized.
*
* If the current ranges are not normalized, they are
* normalized before the new range is added.
*
* @param start Start of time range.
* @param end End of time range.
* @return OpStatus::OK, or OpStatus::ERR_NO_MEMORY.
*/
OP_STATUS AddRange(double start, double end);
// OpMediaTimeRanges
virtual UINT32 Length() const;
virtual double Start(UINT32 idx) const;
virtual double End(UINT32 idx) const;
private:
/** Represents a time range (in seconds), where @c start <= @c end. */
struct Range
{
double start;
double end;
bool IsEmpty() { return start >= end; }
};
/** Merge overlapping intervals, assuming start times are already sorted. */
void Merge();
Range* m_ranges;
UINT32 m_allocated;
UINT32 m_used;
};
#endif // MEDIA_TIME_RANGES_H
|
#include "lights.h"
|
// **************************************
// File: KFontManager.h
// Copyright: Copyright(C) 2013-2017 Wuhan KOTEI Informatics Co., Ltd. All rights reserved.
// Website: http://www.nuiengine.com
// Description: This code is part of NUI Engine (NUI Graphics Lib)
// Comments:
// Rev: 2
// Created: 2017/4/12
// Last edit: 2017/4/28
// Author: Chen Zhi
// E-mail: cz_666@qq.com
// License: APACHE V2.0 (see license file)
// ***************************************
#ifndef K_FONT_MANAGER_H
#define K_FONT_MANAGER_H
#include "boost/unordered_map.hpp"
#include "KTextDrawable.h"
//#define FontProperty boost::unordered_map<string,kn_string>
#define mapFontNameMap boost::unordered_map<string, RETypeface*>
#define mapFontFileMap boost::unordered_map<kn_string, RETypeface*>
typedef struct FontPropertyStruct{
kn_string strFileSize;
kn_string strFontFilePath;
kn_string strStyle;
kn_string strUniqueIdentifier;
kn_string strGlyphCount;
kn_string strUnitsPerEm;
kn_string strSmallestRectPixel;
kn_string strTypoAscender;
kn_string strTypoDescender;
kn_string strLineGap;
kn_string strMaxWidth;
kn_string strPlatform;
kn_string strEncoding;
kn_string strLanguage;
kn_string strEnglishName;
kn_string strEnglishSampleText;
kn_string strEnglishCopyright;
kn_string strEnglishTrademark;
kn_string strVersion;
kn_string strChineseName;
kn_string strChineseSampleText;
kn_string strChineseCopyright;
kn_string strChineseTrademark;
}stFontProperty;
#define mapFontPropMap boost::unordered_map<kn_string, stFontProperty*>
class NUI_API KFontManager
{
private:
// boost::unordered_map<string, RETypeface*> m_FontNameMap;
// boost::unordered_map<kn_string, RETypeface*> m_FontFileMap;
mapFontNameMap m_FontNameMap;
mapFontNameMap m_FontBoldNameMap; //粗体和非粗体需要区分
mapFontFileMap m_FontFileMap;
mapFontPropMap m_FontPropMap;
std::vector<RETypeface*> m_FontVector;
public:
KFontManager();
~KFontManager();
RETypeface* GetFontFromName( char* szName, SkTypeface::Style s = RETypeface::kNormal);
RETypeface* GetFontFromFile(kn_string strFilePath);
RETypeface* GetFontByID(int nFontID);
stFontProperty* GetFontPropFromFile(kn_string strFilePath);
int AddFont(RETypeface* pTypeface);
};
extern KFontManager* GetFontManagerSingleton();
extern void DeleteFontManagerSingleton();
#endif
|
// Created on: 1992-10-14
// Created by: Christophe MARION
// Copyright (c) 1992-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _HLRBRep_TheIntPCurvePCurveOfCInter_HeaderFile
#define _HLRBRep_TheIntPCurvePCurveOfCInter_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <IntRes2d_Domain.hxx>
#include <IntRes2d_Intersection.hxx>
#include <Standard_Integer.hxx>
class HLRBRep_CurveTool;
class HLRBRep_TheProjPCurOfCInter;
class HLRBRep_ThePolygon2dOfTheIntPCurvePCurveOfCInter;
class HLRBRep_TheDistBetweenPCurvesOfTheIntPCurvePCurveOfCInter;
class HLRBRep_ExactIntersectionPointOfTheIntPCurvePCurveOfCInter;
class IntRes2d_Domain;
class HLRBRep_TheIntPCurvePCurveOfCInter : public IntRes2d_Intersection
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT HLRBRep_TheIntPCurvePCurveOfCInter();
Standard_EXPORT void Perform (const Standard_Address& Curve1, const IntRes2d_Domain& Domain1, const Standard_Address& Curve2, const IntRes2d_Domain& Domain2, const Standard_Real TolConf, const Standard_Real Tol);
Standard_EXPORT void Perform (const Standard_Address& Curve1, const IntRes2d_Domain& Domain1, const Standard_Real TolConf, const Standard_Real Tol);
//! Set / get minimum number of points in polygon for intersection.
Standard_EXPORT void SetMinNbSamples (const Standard_Integer theMinNbSamples);
Standard_EXPORT Standard_Integer GetMinNbSamples () const;
protected:
Standard_EXPORT void Perform (const Standard_Address& Curve1, const IntRes2d_Domain& Domain1, const Standard_Address& Curve2, const IntRes2d_Domain& Domain2, const Standard_Real TolConf, const Standard_Real Tol, const Standard_Integer NbIter, const Standard_Real DeltaU, const Standard_Real DeltaV);
Standard_EXPORT void Perform (const Standard_Address& Curve1, const IntRes2d_Domain& Domain1, const Standard_Real TolConf, const Standard_Real Tol, const Standard_Integer NbIter, const Standard_Real DeltaU, const Standard_Real DeltaV);
private:
//! Method to find intersection between two curves
//! : returns false for case when some points of polygon
//! : were replaced on line and exact point of intersection was not found
//! : for case when point of intersection was found
//! : during prelimanary search for line (case of bad paramerization of Bspline for example).
Standard_EXPORT Standard_Boolean findIntersect (const Standard_Address& Curve1, const IntRes2d_Domain& Domain1, const Standard_Address& Curve2, const IntRes2d_Domain& Domain2, const Standard_Real TolConf, const Standard_Real Tol, const Standard_Integer NbIter, const Standard_Real DeltaU, const Standard_Real DeltaV, const HLRBRep_ThePolygon2dOfTheIntPCurvePCurveOfCInter& thePoly1, const HLRBRep_ThePolygon2dOfTheIntPCurvePCurveOfCInter& thePoly2, const Standard_Boolean isFullRepresentation);
IntRes2d_Domain DomainOnCurve1;
IntRes2d_Domain DomainOnCurve2;
//! Minimal number of sample points
Standard_Integer myMinPntNb;
};
#endif // _HLRBRep_TheIntPCurvePCurveOfCInter_HeaderFile
|
//Convert a region structure to string
string region_to_str(Region region)
{
//Initialize the output string
string str = "";
//Add the chromosome
str = str + region.chromosome + ":";
//Add the start and end positions
str = str + to_string(region.start) + "-" + to_string(region.end);
//Return the string
return str;
}
//Convert a tabulated string to a region structure
Region tab_to_region(string str)
{
//Initialize the new region
Region region;
//Generate the new array string
string arr[10];
//Split the region
int total = str_split(str, arr, 10, "\t");
//Check the total length
if(total < 4)
{
//Display error
cerr << "Invalid regions object" << endl;
//Exit with error
exit(EXIT_FAILURE);
}
//Save the chromosome name
region.chromosome = arr[0];
//Save the start position
region.start = stoi(arr[1]);
//Save the end position
region.end = stoi(arr[2]);
//Save the name
region.name = arr[3];
//Calculate the region length
region.length = abs(region.end - region.start) + 1;
//Return the new region
return region;
}
|
// Created on: 1993-04-30
// Created by: Yves FRICAUD
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _MAT_Node_HeaderFile
#define _MAT_Node_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Integer.hxx>
#include <Standard_Address.hxx>
#include <Standard_Real.hxx>
#include <Standard_Transient.hxx>
#include <MAT_SequenceOfArc.hxx>
#include <MAT_SequenceOfBasicElt.hxx>
class MAT_Arc;
class MAT_Node;
DEFINE_STANDARD_HANDLE(MAT_Node, Standard_Transient)
//! Node of Graph.
class MAT_Node : public Standard_Transient
{
public:
Standard_EXPORT MAT_Node(const Standard_Integer GeomIndex, const Handle(MAT_Arc)& LinkedArc, const Standard_Real Distance);
//! Returns the index associated of the geometric
//! representation of <me>.
Standard_EXPORT Standard_Integer GeomIndex() const;
//! Returns the index associated of the node
Standard_EXPORT Standard_Integer Index() const;
//! Returns in <S> the Arcs linked to <me>.
Standard_EXPORT void LinkedArcs (MAT_SequenceOfArc& S) const;
//! Returns in <S> the BasicElts equidistant
//! to <me>.
Standard_EXPORT void NearElts (MAT_SequenceOfBasicElt& S) const;
Standard_EXPORT Standard_Real Distance() const;
//! Returns True if <me> is a pending Node.
//! (ie : the number of Arc Linked = 1)
Standard_EXPORT Standard_Boolean PendingNode() const;
//! Returns True if <me> belongs to the figure.
Standard_EXPORT Standard_Boolean OnBasicElt() const;
//! Returns True if the distance of <me> is Infinite
Standard_EXPORT Standard_Boolean Infinite() const;
//! Set the index associated of the node
Standard_EXPORT void SetIndex (const Standard_Integer anIndex);
Standard_EXPORT void SetLinkedArc (const Handle(MAT_Arc)& anArc);
DEFINE_STANDARD_RTTIEXT(MAT_Node,Standard_Transient)
protected:
private:
Standard_Integer nodeIndex;
Standard_Integer geomIndex;
Standard_Address aLinkedArc;
Standard_Real distance;
};
#endif // _MAT_Node_HeaderFile
|
/*
* Copyright 2020 OmniSci, 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.
*/
/*
TODO(Misiu): A lot of methods here can be made asyncronous. It may be worth an
investigation to determine if it's worth adding async versions of them for performance
reasons.
*/
#include "ForeignStorageCache.h"
#include "Shared/measure.h"
namespace foreign_storage {
using read_lock = mapd_shared_lock<mapd_shared_mutex>;
using write_lock = mapd_unique_lock<mapd_shared_mutex>;
template <typename Func, typename T>
static void iterateOverMatchingPrefix(Func func,
T& chunk_collection,
const ChunkKey& chunk_prefix) {
ChunkKey upper_prefix(chunk_prefix);
upper_prefix.push_back(std::numeric_limits<int>::max());
auto end_it = chunk_collection.upper_bound(static_cast<const ChunkKey>(upper_prefix));
for (auto chunk_it = chunk_collection.lower_bound(chunk_prefix); chunk_it != end_it;
++chunk_it) {
func(*chunk_it);
}
}
ForeignStorageCache::ForeignStorageCache(const std::string& cache_dir,
const size_t num_reader_threads,
const size_t limit)
: entry_limit_(limit) {
validatePath(cache_dir);
global_file_mgr_ =
std::make_unique<File_Namespace::GlobalFileMgr>(0, cache_dir, num_reader_threads);
}
void ForeignStorageCache::cacheTableChunks(const std::vector<ChunkKey>& chunk_keys) {
auto timer = DEBUG_TIMER(__func__);
write_lock lock(chunks_mutex_);
CHECK(!chunk_keys.empty());
auto db_id = chunk_keys[0][CHUNK_KEY_DB_IDX];
auto table_id = chunk_keys[0][CHUNK_KEY_TABLE_IDX];
for (const auto& chunk_key : chunk_keys) {
CHECK_EQ(db_id, chunk_key[CHUNK_KEY_DB_IDX]);
CHECK_EQ(table_id, chunk_key[CHUNK_KEY_TABLE_IDX]);
CHECK(global_file_mgr_->isBufferOnDevice(chunk_key));
if (isCacheFull()) {
evictChunkByAlg();
}
eviction_alg_->touchChunk(chunk_key);
cached_chunks_.emplace(chunk_key);
}
global_file_mgr_->checkpoint(db_id, table_id);
}
AbstractBuffer* ForeignStorageCache::getCachedChunkIfExists(const ChunkKey& chunk_key) {
auto timer = DEBUG_TIMER(__func__);
{
read_lock lock(chunks_mutex_);
if (cached_chunks_.find(chunk_key) == cached_chunks_.end()) {
return nullptr;
}
}
write_lock lock(chunks_mutex_);
eviction_alg_->touchChunk(chunk_key);
return global_file_mgr_->getBuffer(chunk_key);
}
bool ForeignStorageCache::isMetadataCached(const ChunkKey& chunk_key) {
auto timer = DEBUG_TIMER(__func__);
read_lock lock(metadata_mutex_);
return (cached_metadata_.find(chunk_key) != cached_metadata_.end());
}
bool ForeignStorageCache::recoverCacheForTable(ChunkMetadataVector& meta_vec,
const ChunkKey& table_key) {
CHECK(meta_vec.size() == 0);
CHECK(isTableKey(table_key));
global_file_mgr_->getChunkMetadataVecForKeyPrefix(meta_vec, table_key);
for (auto& [chunk_key, metadata] : meta_vec) {
cached_metadata_.emplace(chunk_key);
// If a filebuffer has no pages, then it only has cached metadata and no cached chunk.
if (global_file_mgr_->getBuffer(chunk_key)->pageCount() > 0) {
cached_chunks_.emplace(chunk_key);
}
}
return (meta_vec.size() > 0);
}
static void setMetadataForBuffer(AbstractBuffer* buffer, ChunkMetadata* meta) {
buffer->initEncoder(meta->sqlType);
buffer->setSize(meta->numBytes);
buffer->encoder->setNumElems(meta->numElements);
buffer->encoder->resetChunkStats(meta->chunkStats);
buffer->setUpdated();
}
void ForeignStorageCache::evictThenEraseChunk(const ChunkKey& chunk_key) {
eviction_alg_->removeChunk(chunk_key);
eraseChunk(chunk_key);
}
void ForeignStorageCache::cacheMetadataVec(const ChunkMetadataVector& metadata_vec) {
auto timer = DEBUG_TIMER(__func__);
write_lock meta_lock(metadata_mutex_);
write_lock chunk_lock(chunks_mutex_);
for (auto& [chunk_key, metadata] : metadata_vec) {
cached_metadata_.emplace(chunk_key);
AbstractBuffer* buf;
AbstractBuffer* index_buffer = nullptr;
ChunkKey index_chunk_key;
if (isVarLenKey(chunk_key)) {
// For variable length chunks, metadata is associated with the data chunk
CHECK(isVarLenDataKey(chunk_key));
index_chunk_key = {chunk_key[CHUNK_KEY_DB_IDX],
chunk_key[CHUNK_KEY_TABLE_IDX],
chunk_key[CHUNK_KEY_COLUMN_IDX],
chunk_key[CHUNK_KEY_FRAGMENT_IDX],
2};
}
if (!global_file_mgr_->isBufferOnDevice(chunk_key)) {
buf = global_file_mgr_->createBuffer(chunk_key);
if (!index_chunk_key.empty()) {
CHECK(!global_file_mgr_->isBufferOnDevice(index_chunk_key));
index_buffer = global_file_mgr_->createBuffer(index_chunk_key);
CHECK(index_buffer);
}
} else {
buf = global_file_mgr_->getBuffer(chunk_key);
if (!index_chunk_key.empty()) {
CHECK(global_file_mgr_->isBufferOnDevice(index_chunk_key));
index_buffer = global_file_mgr_->getBuffer(chunk_key);
CHECK(index_buffer);
}
}
setMetadataForBuffer(buf, metadata.get());
evictThenEraseChunk(chunk_key);
if (!index_chunk_key.empty()) {
CHECK(index_buffer);
index_buffer->isUpdated();
evictThenEraseChunk(index_chunk_key);
}
}
global_file_mgr_->checkpoint();
}
void ForeignStorageCache::getCachedMetadataVecForKeyPrefix(
ChunkMetadataVector& metadata_vec,
const ChunkKey& chunk_prefix) {
auto timer = DEBUG_TIMER(__func__);
read_lock r_lock(metadata_mutex_);
iterateOverMatchingPrefix(
[&metadata_vec, this](auto chunk) {
std::shared_ptr<ChunkMetadata> buf_metadata = std::make_shared<ChunkMetadata>();
global_file_mgr_->getBuffer(chunk)->encoder->getMetadata(buf_metadata);
metadata_vec.push_back(std::make_pair(chunk, buf_metadata));
},
cached_metadata_,
chunk_prefix);
}
bool ForeignStorageCache::hasCachedMetadataForKeyPrefix(const ChunkKey& chunk_prefix) {
auto timer = DEBUG_TIMER(__func__);
read_lock lock(metadata_mutex_);
// We don't use iterateOvermatchingPrefix() here because we want to exit early if
// possible.
ChunkKey upper_prefix(chunk_prefix);
upper_prefix.push_back(std::numeric_limits<int>::max());
auto end_it = cached_metadata_.upper_bound(static_cast<const ChunkKey>(upper_prefix));
for (auto meta_it = cached_metadata_.lower_bound(chunk_prefix); meta_it != end_it;
++meta_it) {
return true;
}
return false;
}
void ForeignStorageCache::clearForTablePrefix(const ChunkKey& chunk_prefix) {
CHECK(isTableKey(chunk_prefix));
auto timer = DEBUG_TIMER(__func__);
ChunkKey upper_prefix(chunk_prefix);
upper_prefix.push_back(std::numeric_limits<int>::max());
{
write_lock w_lock(chunks_mutex_);
// Delete chunks for prefix
// We won't delete the buffers here because metadata delete will do that for us later.
auto end_it = cached_chunks_.upper_bound(static_cast<const ChunkKey>(upper_prefix));
for (auto chunk_it = cached_chunks_.lower_bound(chunk_prefix); chunk_it != end_it;) {
eviction_alg_->removeChunk(*chunk_it);
chunk_it = cached_chunks_.erase(chunk_it);
}
}
{
write_lock w_lock(metadata_mutex_);
// Delete metadata for prefix
auto end_it = cached_metadata_.upper_bound(static_cast<const ChunkKey>(upper_prefix));
for (auto meta_it = cached_metadata_.lower_bound(chunk_prefix); meta_it != end_it;) {
meta_it = cached_metadata_.erase(meta_it);
}
}
global_file_mgr_->removeTableRelatedDS(chunk_prefix[0], chunk_prefix[1]);
}
void ForeignStorageCache::clear() {
auto timer = DEBUG_TIMER(__func__);
std::set<ChunkKey> table_keys;
{
write_lock w_lock(chunks_mutex_);
for (auto chunk_it = cached_chunks_.begin(); chunk_it != cached_chunks_.end();) {
eviction_alg_->removeChunk(*chunk_it);
chunk_it = cached_chunks_.erase(chunk_it);
}
}
{
write_lock w_lock(metadata_mutex_);
for (auto meta_it = cached_metadata_.begin(); meta_it != cached_metadata_.end();) {
table_keys.emplace(ChunkKey{(*meta_it)[0], (*meta_it)[1]});
meta_it = cached_metadata_.erase(meta_it);
}
}
for (const auto& table_key : table_keys) {
global_file_mgr_->removeTableRelatedDS(table_key[0], table_key[1]);
}
}
void ForeignStorageCache::setLimit(size_t limit) {
auto timer = DEBUG_TIMER(__func__);
write_lock w_lock(chunks_mutex_);
entry_limit_ = limit;
// Need to make sure cache doesn't have more entries than the limit
// in case the limit was lowered.
while (cached_chunks_.size() > entry_limit_) {
evictChunkByAlg();
}
global_file_mgr_->checkpoint();
}
std::vector<ChunkKey> ForeignStorageCache::getCachedChunksForKeyPrefix(
const ChunkKey& chunk_prefix) {
read_lock r_lock(chunks_mutex_);
std::vector<ChunkKey> ret_vec;
iterateOverMatchingPrefix(
[&ret_vec](auto chunk) { ret_vec.push_back(chunk); }, cached_chunks_, chunk_prefix);
return ret_vec;
}
std::map<ChunkKey, AbstractBuffer*> ForeignStorageCache::getChunkBuffersForCaching(
const std::vector<ChunkKey>& chunk_keys) {
auto timer = DEBUG_TIMER(__func__);
std::map<ChunkKey, AbstractBuffer*> chunk_buffer_map;
read_lock lock(chunks_mutex_);
for (const auto& chunk_key : chunk_keys) {
CHECK(cached_chunks_.find(chunk_key) == cached_chunks_.end());
CHECK(global_file_mgr_->isBufferOnDevice(chunk_key));
chunk_buffer_map[chunk_key] = global_file_mgr_->getBuffer(chunk_key);
CHECK_EQ(chunk_buffer_map[chunk_key]->pageCount(), static_cast<size_t>(0));
// Clear all buffer metadata
chunk_buffer_map[chunk_key]->encoder = nullptr;
chunk_buffer_map[chunk_key]->has_encoder = false;
chunk_buffer_map[chunk_key]->setSize(0);
}
return chunk_buffer_map;
}
// Private functions. Locks should be acquired in the public interface before calling
// these functions.
// This function assumes the chunk has been erased from the eviction algorithm already.
void ForeignStorageCache::eraseChunk(const ChunkKey& chunk_key) {
auto timer = DEBUG_TIMER(__func__);
File_Namespace::FileBuffer* file_buffer =
static_cast<File_Namespace::FileBuffer*>(global_file_mgr_->getBuffer(chunk_key));
file_buffer->freeChunkPages();
cached_chunks_.erase(chunk_key);
}
void ForeignStorageCache::evictChunkByAlg() {
auto timer = DEBUG_TIMER(__func__);
eraseChunk(eviction_alg_->evictNextChunk());
}
bool ForeignStorageCache::isCacheFull() const {
auto timer = DEBUG_TIMER(__func__);
return (cached_chunks_.size() >= entry_limit_);
}
std::string ForeignStorageCache::dumpCachedChunkEntries() const {
auto timer = DEBUG_TIMER(__func__);
std::string ret_string = "Cached chunks:\n";
for (const auto& chunk_key : cached_chunks_) {
ret_string += " " + showChunk(chunk_key) + "\n";
}
return ret_string;
}
std::string ForeignStorageCache::dumpCachedMetadataEntries() const {
auto timer = DEBUG_TIMER(__func__);
std::string ret_string = "Cached ChunkMetadata:\n";
for (const auto& meta_key : cached_metadata_) {
ret_string += " " + showChunk(meta_key) + "\n";
}
return ret_string;
}
std::string ForeignStorageCache::dumpEvictionQueue() const {
return ((LRUEvictionAlgorithm*)eviction_alg_.get())->dumpEvictionQueue();
}
void ForeignStorageCache::validatePath(const std::string& base_path) {
// check if base_path already exists, and if not create one
boost::filesystem::path path(base_path);
if (boost::filesystem::exists(path)) {
if (!boost::filesystem::is_directory(path)) {
throw std::runtime_error{
"cache path \"" + base_path +
"\" is not a directory. Please specify a valid directory "
"with --disk_cache_path=<path>, or use the default location."};
}
} else { // data directory does not exist
if (!boost::filesystem::create_directory(path)) {
throw std::runtime_error{
"could not create directory at cache path \"" + base_path +
"\". Please specify a valid directory location "
"with --disk_cache_path=<path> or use the default location."};
}
}
}
} // namespace foreign_storage
|
/* XMRig
* Copyright (c) 2014-2019 heapwolf <https://github.com/heapwolf>
* Copyright (c) 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef XMRIG_HTTPSCLIENT_H
#define XMRIG_HTTPSCLIENT_H
using BIO = struct bio_st;
using SSL_CTX = struct ssl_ctx_st;
using SSL = struct ssl_st;
using X509 = struct x509_st;
#include "base/net/http/HttpClient.h"
#include "base/tools/String.h"
namespace xmrig {
class HttpsClient : public HttpClient
{
public:
XMRIG_DISABLE_COPY_MOVE_DEFAULT(HttpsClient)
HttpsClient(const char *tag, FetchRequest &&req, const std::weak_ptr<IHttpListener> &listener);
~HttpsClient() override;
const char *tlsFingerprint() const override;
const char *tlsVersion() const override;
protected:
void handshake() override;
void read(const char *data, size_t size) override;
private:
void write(std::string &&data, bool close) override;
bool verify(X509 *cert);
bool verifyFingerprint(X509 *cert);
void flush(bool close);
BIO *m_read = nullptr;
BIO *m_write = nullptr;
bool m_ready = false;
char m_fingerprint[32 * 2 + 8]{};
SSL *m_ssl = nullptr;
SSL_CTX *m_ctx = nullptr;
};
} // namespace xmrig
#endif // XMRIG_HTTPSCLIENT_H
|
//
// $Id$
//
// Copyright (C) 1995-2002 Opera Software AS. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
#ifndef AUTODELETE_H
#define AUTODELETE_H
#include "adjunct/m2/src/glue/mh.h"
#include "adjunct/desktop_util/adt/opqueue.h"
#ifdef _DEBUG
# define autodelete(object) MessageEngine::GetInstance()->GetAutoDelete()->DeleteDbg(object, __FILE__, __LINE__)
#else
#define autodelete(object) MessageEngine::GetInstance()->GetAutoDelete()->Delete(object)
#endif
/**
* Implements a delayed delete of any kind of object.
*
* An important advantage here is that you can actually delete
* an object in a callback function coming from that very
* same instance. Example:
*
* Object::Close()
* {
* Cleanup();
* m_observer->Finished(this);
* }
*
* Observer::Finished(Object *object)
* {
* autodelete(object);
* m_object = NULL;
* }
*
* Attention: All objects to be deleted with autodelete must
* inherit from base classes that implement the Autodeletable
* interface (with a public destructor).
*
* If the AutoDelete object is deleted, any remaining
* objects in the delete queue will also be deleted.
* Normally, objects in the delete queue will be deleted
* during the next round of the message loop.
*
* @author Johan Borg, johan@opera.com
*/
class Autodeletable : public OpQueueItem<Autodeletable>
{
public:
Autodeletable() {
#ifdef _DEBUG
m_ok_to_delete = TRUE;
#endif
}
virtual ~Autodeletable() {
#ifdef _DEBUG
OP_ASSERT(m_ok_to_delete);
#endif
};
#ifdef _DEBUG
BOOL m_ok_to_delete;
OpString8 m_autodelete_file;
int m_autodelete_line;
#endif
};
class AutoDelete : public MessageLoop::Target
{
public:
AutoDelete();
virtual ~AutoDelete();
/** Delete all messages waiting in the queue
* also performed in the destructor
*/
void FlushQueue();
/** Put an object in the queue for future deletion
*/
#ifdef _DEBUG
void DeleteDbg(Autodeletable *object, const OpStringC8& autodelete_file, int autodelete_line);
#else
void Delete(Autodeletable *object);
#endif
// From Target:
OP_STATUS Receive(OpMessage message);
private:
MessageLoop *m_loop;
OpQueue<Autodeletable> m_queue;
};
#endif // AUTODELETE_H
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1000;
int G[maxn][maxn];
int d[maxn];
int n;
int dp(int i) {
if (d[i] > 0) return d[i];
d[i] = 1;
for (int j = 1; j <= n; ++j) if (G[i][j]) {
d[i] = max(d[i], dp[j] + 1);
}
return d[i];
}
void print_ans(int i) {
printf("%d ", i);
for (int j = 1; j <= n; ++j) if (G[i][j] && d[i] == d[j] + 1) {
print_ans(j);
break;
}
}
int main() {
n = 10;
int ans = -1;
int idx = 0;
for (int i = 1; i <= n; ++i) {
if (dp(i) > ans) {
idx = i;
ans = dp(i);
}
}
print_ans(idx); printf("\n");
return 0;
}
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<stdlib.h>
using namespace std;
class Date
{
public:
Date(int year = 2018, int month = 06, int day = 11)
:_year(year)
, _month(month)
, _day(day)
{}
Date(const Date& d)
:_year(d._year)
, _month(d._month)
, _day(d._day)
{}
//调整日期
Date& AdjustDate(Date& d);
//调整日期(减法)
Date& AdjustDateSub(Date& d);
//调整日期(加法)
Date& AdjustDateAdd(Date& d);
//当前日期x天之后是什么日期
Date operator+(int days);
//当前日期x天前是什么日期
Date operator-(int days);
//两个日期之间相差多少天
Date operator-(const Date& d);
//比较两个日期大小
bool operator>(const Date& d);
bool operator<(const Date& d);
bool operator==(const Date& d);
bool operator!=(const Date& d);
//重载赋值
Date& operator=(const Date& d);
//重载取地址符号
Date* operator&();
//前置++/--
Date& operator++();
Date& operator--();
//后置++/--
Date operator++(int);
Date operator--(int);
//打印日期
void PrintDate();
private:
int _year;
int _month;
int _day;
};
void TestDate();
|
/*
* Copyright (c) 2017-2021 Morwenn
* SPDX-License-Identifier: MIT
*/
// Copyright (c) 2009 Alexander Stepanov and Paul McJones
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without
// fee, provided that the above copyright notice appear in all copies
// and that both that copyright notice and this permission notice
// appear in supporting documentation. The authors make no
// representations about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
// Algorithms from
// Elements of Programming
// by Alexander Stepanov and Paul McJones
// Addison-Wesley Professional, 2009
#ifndef CPPSORT_DETAIL_RECMERGE_FORWARD_H_
#define CPPSORT_DETAIL_RECMERGE_FORWARD_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <iterator>
#include <memory>
#include <utility>
#include <cpp-sort/utility/as_function.h>
#include <cpp-sort/utility/iter_move.h>
#include "buffered_inplace_merge.h"
#include "iterator_traits.h"
#include "lower_bound.h"
#include "memory.h"
#include "move.h"
#include "rotate.h"
#include "type_traits.h"
#include "upper_bound.h"
namespace cppsort
{
namespace detail
{
////////////////////////////////////////////////////////////
// recmerge for forward iterators
template<typename ForwardIterator, typename Compare, typename Projection>
auto merge_n_step_0(ForwardIterator f0, difference_type_t<ForwardIterator> n0,
ForwardIterator f1, difference_type_t<ForwardIterator> n1,
Compare compare, Projection projection,
ForwardIterator& f0_0, difference_type_t<ForwardIterator>& n0_0,
ForwardIterator& f0_1, difference_type_t<ForwardIterator>& n0_1,
ForwardIterator& f1_0, difference_type_t<ForwardIterator>& n1_0,
ForwardIterator& f1_1, difference_type_t<ForwardIterator>& n1_1)
-> void
{
auto&& proj = utility::as_function(projection);
f0_0 = std::move(f0);
n0_0 = n0 / 2;
f0_1 = std::next(f0_0, n0_0);
f1_1 = lower_bound_n(f1, n1, proj(*f0_1), std::move(compare), std::move(projection));
f1_0 = detail::rotate(f0_1, std::move(f1), f1_1);
n0_1 = std::distance(f0_1, f1_0);
++f1_0;
n1_0 = n0 - n0_0 - 1;
n1_1 = n1 - n0_1;
}
template<typename ForwardIterator, typename Compare, typename Projection>
auto merge_n_step_1(ForwardIterator f0, difference_type_t<ForwardIterator> n0,
ForwardIterator f1, difference_type_t<ForwardIterator> n1,
Compare compare, Projection projection,
ForwardIterator& f0_0, difference_type_t<ForwardIterator>& n0_0,
ForwardIterator& f0_1, difference_type_t<ForwardIterator>& n0_1,
ForwardIterator& f1_0, difference_type_t<ForwardIterator>& n1_0,
ForwardIterator& f1_1, difference_type_t<ForwardIterator>& n1_1)
-> void
{
auto&& proj = utility::as_function(projection);
f0_0 = f0;
n0_1 = n1 / 2;
f1_1 = std::next(f1, n0_1);
f0_1 = upper_bound_n(f0, n0, proj(*f1_1), std::move(compare), std::move(projection));
++f1_1;
f1_0 = detail::rotate(f0_1, std::move(f1), f1_1);
n0_0 = std::distance(f0_0, f0_1);
n1_0 = n0 - n0_0;
n1_1 = n1 - n0_1 - 1;
}
template<typename ForwardIterator, typename RandomAccessIterator,
typename Compare, typename Projection>
auto recmerge(ForwardIterator f0, difference_type_t<ForwardIterator> n0,
ForwardIterator f1, difference_type_t<ForwardIterator> n1,
RandomAccessIterator buffer, std::ptrdiff_t buff_size,
Compare compare, Projection projection,
std::forward_iterator_tag tag)
-> void
{
using rvalue_type = rvalue_type_t<ForwardIterator>;
using difference_type = difference_type_t<ForwardIterator>;
if (n0 == 0 || n1 == 0) return;
if (n0 <= buff_size) {
destruct_n<rvalue_type> d(0);
std::unique_ptr<
rvalue_type,
destruct_n<rvalue_type>&
> h2(buffer, d);
auto buff_ptr = uninitialized_move(f0, f1, buffer, d);
half_inplace_merge(
buffer, buff_ptr, f1, std::next(f1, n1), f0,
n0, std::move(compare), std::move(projection)
);
return;
}
ForwardIterator f0_0, f0_1, f1_0, f1_1;
difference_type n0_0, n0_1, n1_0, n1_1;
if (n0 < n1) {
merge_n_step_0(
std::move(f0), n0, std::move(f1), n1,
compare, projection,
f0_0, n0_0, f0_1, n0_1,
f1_0, n1_0, f1_1, n1_1
);
} else {
merge_n_step_1(
std::move(f0), n0, std::move(f1), n1,
compare, projection,
f0_0, n0_0, f0_1, n0_1,
f1_0, n1_0, f1_1, n1_1
);
}
recmerge(f0_0, n0_0, f0_1, n0_1, buffer, buff_size,
compare, projection, tag);
recmerge(f1_0, n1_0, f1_1, n1_1, buffer, buff_size,
std::move(compare), std::move(projection), tag);
}
}}
#endif // CPPSORT_DETAIL_RECMERGE_FORWARD_H_
|
#ifndef BST_HPP
#define BST_HPP
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
// node structure for tree
template<typename T>
struct node {
// key data and other node pointers
T data;
node * parent, * left_child, * right_child;
// default constructor, inits all pointers as NULL
node(){
parent = left_child = right_child = NULL;
}
// inits pointers as NULL and assigns data member to input arg
node(T data_in){
data = data_in;
parent = left_child = right_child = NULL;
}
// assigns args to internal data members
node(T data_in, node * parent_in){
data = data_in;
parent = parent_in;
left_child = NULL;
right_child = NULL;
}
// sets pointers to input arguments
node(node * parent_in, node * left_child_in, node * right_child_in){
parent = parent_in;
left_child = left_child_in;
right_child = right_child_in;
}
// delete allocated memory
~node(){
if(left_child != NULL){
delete left_child;
}
if(right_child != NULL){
delete right_child;
}
}
};
template<typename T>
class BST {
private:
node<T> root;
public:
BST();
BST(T data_in); // inits root's data
~BST(){} // deletes node data
void addNode(T data_in); // adds new node in right spot
void deleteNode(T key); // deletes node with data matching key
node<T> * search(T key); // returns node * with data mathing key
void print(); // prints tree
void addNodes(std::vector<T> input); // add nodes for elements in vector
// internal function to add nodes recursively
void recursiveAddNodes( std::vector<T> input_data,
int start,
int end);
// return tree size
int size();
// returns kth smallest data
T kthSmallest(int k);
// prints tree starting from current
void recursivePrint(node<T> * current);
};
#include "BST.cpp"
#endif // BST_HPP
|
#include "shadow_mapping_entity_renderer.h"
#include "shadow_mapping_shader.h"
#include <terrain/terrain.h>
#include <entities/entity.h>
#include <utils/maths.h>
namespace sloth {
void ShadowMapEntityRenderer::render(const MapedEntities & entities, const MapedEntities & normalMappingEntities, const std::list<std::shared_ptr<Terrain>> &terrains)
{
ShadowMappingShader::inst()->enable();
for (auto it = entities.begin(); it != entities.end(); ++it) {
glBindVertexArray(it->first.getRawModel().getVaoID());
glBindTexture(GL_TEXTURE_2D, it->first.getTexture().getID());
for (auto &entity : it->second) {
prepareInstance(*entity);
glDrawElements(GL_TRIANGLES, it->first.getRawModel().getVertexCount(), GL_UNSIGNED_INT, nullptr);
}
}
for (auto it = normalMappingEntities.begin(); it != normalMappingEntities.end(); ++it) {
glBindVertexArray(it->first.getRawModel().getVaoID());
glBindTexture(GL_TEXTURE_2D, it->first.getTexture().getID());
for (auto &entity : it->second) {
prepareInstance(*entity);
glDrawElements(GL_TRIANGLES, it->first.getRawModel().getVertexCount(), GL_UNSIGNED_INT, nullptr);
}
}
for (auto it = terrains.begin(); it != terrains.end(); ++it) {
glBindVertexArray((*it)->getModel().getVaoID());
prepareTerrain(**it);
glDrawElements(GL_TRIANGLES, (*it)->getModel().getVertexCount(), GL_UNSIGNED_INT, nullptr);
}
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindVertexArray(0);
ShadowMappingShader::inst()->disable();
}
void ShadowMapEntityRenderer::prepareInstance(const Entity & entity)
{
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glm::mat4 model = Maths::createModelMatrix(
entity.getPosition(), entity.getRotX(), entity.getRotY(), entity.getRotZ(), entity.getScale()
);
ShadowMappingShader::inst()->m_Model.loadMatrix4(model);
}
void ShadowMapEntityRenderer::prepareTerrain(const Terrain & terrain)
{
glEnableVertexAttribArray(0);
glm::mat4 model = Maths::createModelMatrix(glm::vec3(terrain.getX(), 0, terrain.getZ()), 0.0f, 0.0f, 0.0f, 1.0f);
ShadowMappingShader::inst()->m_Model.loadMatrix4(model);
}
}
|
#include "ofApp.h"
// ---------------------------------------------------------------------------------------------------------------------------------------------------
//
void ofApp::setup()
{
isServer = false;
fontSmall.loadFont("Fonts/DIN.otf", 8 );
ofSeedRandom();
int uniqueID = ofRandom( 999999999 ); // Yeah this is bogus I know. Good enough for our purposes.
server = NULL;
client = NULL;
if( ofFile( ofToDataPath("Settings/IsServer.txt")).exists() )
{
server = new ofxServerOscManager();
server->init( "Settings/ServerSettings.xml" );
isServer = server->isInitialised();
ofAddListener( server->newDataEvent, this, &ofApp::newData );
cout<<"Starting Server"<<endl;
}
else
{
ofxXmlSettings XML;
bool loadedFile = XML.loadFile( "Settings/ClientSettings.xml" );
if( loadedFile )
{
screenIndex = XML.getValue("Settings:ScreenIndex", 0);
displayWidth = XML.getValue("Settings:DisplayWidth", 5120);
displayHeight = XML.getValue("Settings:DisplayHeight", 2880);
viewWidth = XML.getValue("Settings:ViewWidth", ofGetWidth());
viewHeight = XML.getValue("Settings:ViewHeight", ofGetHeight());
screenOffsetX = viewWidth*screenIndex;
}
client = new ofxClientOSCManager();
client->init( screenIndex );
commonTimeOsc = client->getCommonTimeOscObj();
commonTimeOsc->setEaseOffset( true );
ofAddListener( client->newDataEvent, this, &ofApp::newData );
}
// Read the screen index from a file
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------
//
void ofApp::update()
{
currTime = 0.0f;
if( isServer ) { currTime = ofGetElapsedTimef(); } else { currTime = commonTimeOsc->getTimeSecs(); }
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------
//
void ofApp::draw()
{
float currTime = 0.0f;
if( isServer ) { currTime = ofGetElapsedTimef(); } else { currTime = commonTimeOsc->getTimeSecs(); }
// Set a color that pulsates based on the time we get
ofColor bgColor;
bgColor.setHsb( ((cosf(currTime/10.0f)+1.0f)/2.0f) * 255, 180, ((cosf(currTime*1.4f)+1.0f)/2.0f) * 255 );
ofSetColor(bgColor);
ofRect(0,0,ofGetWidth(), ofGetHeight() );
// Rotate a circle
ofColor circleColor = bgColor.getInverted();
ofSetColor(circleColor);
ofPushMatrix();
ofTranslate(ofGetWidth() * 0.5f, ofGetHeight() * 0.5f );
ofRotate( currTime * 50.0f );
ofTranslate( ofGetHeight() * 0.45f, 0 );
ofCircle( 0, 0, 40 );
ofPopMatrix();
ofSetColor(255);
if( isServer )
{
fontSmall.drawString( "Server", 300, 85 );
}
else
{
fontSmall.drawString( "Offset: " + ofToString(commonTimeOsc->offsetMillis) + " OffsetTarget: " + ofToString(commonTimeOsc->offsetMillisTarget), 300, 80 );
}
ofSetColor(255, 255, 255);
fontSmall.drawString( "Screen: " + ofToString(screenIndex) + " Time: " + ofToString( currTime, 2), 300, 45 );
}
void ofApp::newData( DataPacket& _packet )
{
if(!isServer){
cout<<"new data"<<endl;
for(int i = 0; i < _packet.valuesFloat.size(); i++){
cout<<_packet.valuesFloat[i]<<endl;
}
for(int i = 0; i < _packet.valuesInt.size(); i++){
cout<<_packet.valuesInt[i]<<endl;
}
for(int i = 0; i < _packet.valuesString.size(); i++){
cout<<_packet.valuesString[i]<<endl;
}
}
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------
//
void ofApp::keyPressed(int key)
{
if(isServer){
DataPacket data;
int client;
string command;
float value;
if(key == '1'){
client = 0;
command = "play";
value = 100.00;
}
if(key == '2'){
client = 1;
command = "play";
value = 50.00;
}
if(key == '3'){
client = 2;
command = "play";
value = 25.00;
}
if(key == '4'){
client = 3;
command = "play";
value = 15.00;
}
if(key == '5'){
client = 4;
command = "play";
value = 5.00;
}
if(key == '6'){
client = 5;
command = "play";
value = 2.50;
}
data.valuesFloat.push_back(value);
data.valuesInt.push_back(client);
data.valuesString.push_back(command);
server->sendData(data.valuesString, data.valuesInt, data.valuesFloat);
}
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------
//
void ofApp::keyReleased(int key)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------
//
void ofApp::mouseMoved(int x, int y )
{
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------
//
void ofApp::mouseDragged(int x, int y, int button)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------
//
void ofApp::mousePressed(int x, int y, int button)
{
if(!isServer){
DataPacket packet;
packet.valuesString.push_back("mouseClicked");
client->sendData(packet);
}
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------
//
void ofApp::mouseReleased(int x, int y, int button)
{
}
|
#include<iostream>
#include<stdlib.h>
using namespace std;
class stack
{
public:
int stk[20],rear,tos,size;
stack()
{
tos=-1;
rear=-1;
cout<<"Enter size\n";
cin>>size;
}
void enque(int x)
{
if(tos==size-1)
{
cout<<"Queue overflow\n";
}
else if(tos==-1)
{
stk[++tos]=x;
cout<<"Inserted "<<x<<endl;
reverse(stk,tos);
}
else if(tos!=-1)
{
reverse(stk,tos);
stk[++tos]=x;
cout<<"Inserted "<<x<<endl<<tos<<endl;
rear++;
reverse(stk,tos);
}
return;
}
void deque()
{
if(tos==-1)
cout<<"Queue empty\n";
else
{
cout<<"Deleted "<<stk[tos--]<<endl;
}
return;
}
void display()
{
cout<<endl;
if(tos==-1)
cout<<"Queue empty\n";
else
{
for(int i=tos;i>=0;i--)
cout<<stk[i]<<" ";
}
return;
}
void reverse(int stk[],int tos)
{
int i,j,k,temp;
j=tos;
for(i=0;i<((tos+1)/2);i++)
{
temp=stk[i];
stk[i]=stk[j];
stk[j]=temp;
j--;
}
temp=tos;
tos=rear;
rear=temp;
return;
}
};
int main()
{
stack s;
int c;
while(1)
{
cout<<"Enter operation\n";
cout<<"1.Enqueue 2.Dequeue 3.Display 4.Exit\n";
cin>>c;
switch(c)
{
case 1:cout<<"enter element\n";
cin>>c;
s.enque(c);
break;
case 2:s.deque();break;
case 3:s.display();break;
default:exit(0);
}
}
}
|
// Created on: 1996-12-05
// Created by: Jean-Pierre COMBE/Odile Olivier
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _PrsDim_ParallelRelation_HeaderFile
#define _PrsDim_ParallelRelation_HeaderFile
#include <PrsDim_Relation.hxx>
#include <DsgPrs_ArrowSide.hxx>
DEFINE_STANDARD_HANDLE(PrsDim_ParallelRelation, PrsDim_Relation)
//! A framework to display constraints of parallelism
//! between two or more Interactive Objects. These
//! entities can be faces or edges.
class PrsDim_ParallelRelation : public PrsDim_Relation
{
DEFINE_STANDARD_RTTIEXT(PrsDim_ParallelRelation, PrsDim_Relation)
public:
//! Constructs an object to display parallel constraints.
//! This object is defined by the first shape aFShape and
//! the second shape aSShape and the plane aPlane.
Standard_EXPORT PrsDim_ParallelRelation(const TopoDS_Shape& aFShape, const TopoDS_Shape& aSShape, const Handle(Geom_Plane)& aPlane);
//! Constructs an object to display parallel constraints.
//! This object is defined by the first shape aFShape and
//! the second shape aSShape the plane aPlane, the
//! position aPosition, the type of arrow, aSymbolPrs and
//! its size anArrowSize.
Standard_EXPORT PrsDim_ParallelRelation(const TopoDS_Shape& aFShape, const TopoDS_Shape& aSShape, const Handle(Geom_Plane)& aPlane, const gp_Pnt& aPosition, const DsgPrs_ArrowSide aSymbolPrs, const Standard_Real anArrowSize = 0.01);
//! Returns true if the parallelism is movable.
virtual Standard_Boolean IsMovable() const Standard_OVERRIDE { return Standard_True; }
private:
Standard_EXPORT virtual void Compute (const Handle(PrsMgr_PresentationManager)& thePrsMgr,
const Handle(Prs3d_Presentation)& thePrs,
const Standard_Integer theMode) Standard_OVERRIDE;
Standard_EXPORT virtual void ComputeSelection (const Handle(SelectMgr_Selection)& theSel,
const Standard_Integer theMode) Standard_OVERRIDE;
Standard_EXPORT void ComputeTwoFacesParallel (const Handle(Prs3d_Presentation)& aPresentation);
Standard_EXPORT void ComputeTwoEdgesParallel (const Handle(Prs3d_Presentation)& aPresentation);
private:
gp_Pnt myFAttach;
gp_Pnt mySAttach;
gp_Dir myDirAttach;
};
#endif // _PrsDim_ParallelRelation_HeaderFile
|
#pragma once
#include "GlobalHeader.h" // fa::String, fa::OStream
#include <boost/operators.hpp> // boost::totally_ordered
#include "Utils.h" // fa::Id
namespace fa {
class NoteImpl final : private boost::totally_ordered<NoteImpl> {
public:
using this_type = NoteImpl;
using value_type = String;
NoteImpl();
explicit NoteImpl(value_type);
value_type getText() const;
void setText(value_type const &text);
void setText(value_type &&text);
Id getId() const;
friend OStream &operator<<(OStream &, this_type const &);
friend bool operator==(this_type const &, this_type const &);
friend bool operator<(this_type const &, this_type const &);
private:
value_type text_;
Id const id_;
}; // END of class NoteImpl
} // END of namespace fa
|
/*
* @Description:
* @Author: Ren Qian
* @Date: 2020-03-01 18:07:42
*/
#include "lidar_localization/models/graph_optimizer/g2o/g2o_graph_optimizer.hpp"
#include "glog/logging.h"
#include "lidar_localization/tools/tic_toc.hpp"
namespace lidar_localization {
G2oGraphOptimizer::G2oGraphOptimizer(const std::string &solver_type) {
graph_ptr_.reset(new g2o::SparseOptimizer());
g2o::OptimizationAlgorithmFactory *solver_factory = g2o::OptimizationAlgorithmFactory::instance();
g2o::OptimizationAlgorithmProperty solver_property;
g2o::OptimizationAlgorithm *solver = solver_factory->construct(solver_type, solver_property);
graph_ptr_->setAlgorithm(solver);
if (!graph_ptr_->solver()) {
LOG(ERROR) << "G2O 优化器创建失败!";
}
robust_kernel_factory_ = g2o::RobustKernelFactory::instance();
}
bool G2oGraphOptimizer::Optimize() {
static int optimize_cnt = 0;
if(graph_ptr_->edges().size() < 1) {
return false;
}
TicToc optimize_time;
graph_ptr_->initializeOptimization();
graph_ptr_->computeInitialGuess();
graph_ptr_->computeActiveErrors();
graph_ptr_->setVerbose(false);
double chi2 = graph_ptr_->chi2();
int iterations = graph_ptr_->optimize(max_iterations_num_);
LOG(INFO) << std::endl << "------ 完成第 " << ++optimize_cnt << " 次后端优化 -------" << std::endl
<< "顶点数:" << graph_ptr_->vertices().size() << ", 边数: " << graph_ptr_->edges().size() << std::endl
<< "迭代次数: " << iterations << "/" << max_iterations_num_ << std::endl
<< "用时:" << optimize_time.toc() << std::endl
<< "优化前后误差变化:" << chi2 << "--->" << graph_ptr_->chi2()
<< std::endl << std::endl;
return true;
}
bool G2oGraphOptimizer::GetOptimizedPose(std::deque<Eigen::Matrix4f>& optimized_pose) {
optimized_pose.clear();
int vertex_num = graph_ptr_->vertices().size();
for (int i = 0; i < vertex_num; i++) {
g2o::VertexSE3* v = dynamic_cast<g2o::VertexSE3*>(graph_ptr_->vertex(i));
Eigen::Isometry3d pose = v->estimate();
optimized_pose.push_back(pose.matrix().cast<float>());
}
return true;
}
int G2oGraphOptimizer::GetNodeNum() {
return graph_ptr_->vertices().size();
}
void G2oGraphOptimizer::AddSe3Node(const Eigen::Isometry3d &pose, bool need_fix) {
g2o::VertexSE3 *vertex(new g2o::VertexSE3());
vertex->setId(graph_ptr_->vertices().size());
vertex->setEstimate(pose);
if (need_fix) {
vertex->setFixed(true);
}
graph_ptr_->addVertex(vertex);
}
void G2oGraphOptimizer::SetEdgeRobustKernel(std::string robust_kernel_name,
double robust_kernel_size) {
robust_kernel_name_ = robust_kernel_name;
robust_kernel_size_ = robust_kernel_size;
need_robust_kernel_ = true;
}
void G2oGraphOptimizer::AddSe3Edge(int vertex_index1,
int vertex_index2,
const Eigen::Isometry3d &relative_pose,
const Eigen::VectorXd noise) {
Eigen::MatrixXd information_matrix = CalculateSe3EdgeInformationMatrix(noise);
g2o::VertexSE3* v1 = dynamic_cast<g2o::VertexSE3*>(graph_ptr_->vertex(vertex_index1));
g2o::VertexSE3* v2 = dynamic_cast<g2o::VertexSE3*>(graph_ptr_->vertex(vertex_index2));
g2o::EdgeSE3 *edge(new g2o::EdgeSE3());
edge->setMeasurement(relative_pose);
edge->setInformation(information_matrix);
edge->vertices()[0] = v1;
edge->vertices()[1] = v2;
graph_ptr_->addEdge(edge);
if (need_robust_kernel_) {
AddRobustKernel(edge, robust_kernel_name_, robust_kernel_size_);
}
}
Eigen::MatrixXd G2oGraphOptimizer::CalculateSe3EdgeInformationMatrix(Eigen::VectorXd noise) {
Eigen::MatrixXd information_matrix = Eigen::MatrixXd::Identity(6, 6);
information_matrix = CalculateDiagMatrix(noise);
return information_matrix;
}
void G2oGraphOptimizer::AddRobustKernel(g2o::OptimizableGraph::Edge *edge, const std::string &kernel_type, double kernel_size) {
if (kernel_type == "NONE") {
return;
}
g2o::RobustKernel *kernel = robust_kernel_factory_->construct(kernel_type);
if (kernel == nullptr) {
std::cerr << "warning : invalid robust kernel type: " << kernel_type << std::endl;
return;
}
kernel->setDelta(kernel_size);
edge->setRobustKernel(kernel);
}
Eigen::MatrixXd G2oGraphOptimizer::CalculateDiagMatrix(Eigen::VectorXd noise) {
Eigen::MatrixXd information_matrix = Eigen::MatrixXd::Identity(noise.rows(), noise.rows());
for (int i = 0; i < noise.rows(); i++) {
information_matrix(i, i) /= noise(i);
}
return information_matrix;
}
void G2oGraphOptimizer::AddSe3PriorXYZEdge(int se3_vertex_index,
const Eigen::Vector3d &xyz,
Eigen::VectorXd noise) {
Eigen::MatrixXd information_matrix = CalculateDiagMatrix(noise);
g2o::VertexSE3 *v_se3 = dynamic_cast<g2o::VertexSE3 *>(graph_ptr_->vertex(se3_vertex_index));
g2o::EdgeSE3PriorXYZ *edge(new g2o::EdgeSE3PriorXYZ());
edge->setMeasurement(xyz);
edge->setInformation(information_matrix);
edge->vertices()[0] = v_se3;
graph_ptr_->addEdge(edge);
}
void G2oGraphOptimizer::AddSe3PriorQuaternionEdge(int se3_vertex_index,
const Eigen::Quaterniond &quat,
Eigen::VectorXd noise) {
Eigen::MatrixXd information_matrix = CalculateSe3PriorQuaternionEdgeInformationMatrix(noise);
g2o::VertexSE3 *v_se3 = dynamic_cast<g2o::VertexSE3 *>(graph_ptr_->vertex(se3_vertex_index));
g2o::EdgeSE3PriorQuat *edge(new g2o::EdgeSE3PriorQuat());
edge->setMeasurement(quat);
edge->setInformation(information_matrix);
edge->vertices()[0] = v_se3;
graph_ptr_->addEdge(edge);
}
// TODO: 姿态观测的信息矩阵尚未添加
// 备注:各位使用时可只用位置观测,而不用姿态观测,影响不大
// 我自己在别的地方尝试过增加姿态观测,但效果反而变差,如果感兴趣,可自己编写此处的信息矩阵,并在后端优化中添加相应的边进行验证
Eigen::MatrixXd G2oGraphOptimizer::CalculateSe3PriorQuaternionEdgeInformationMatrix(Eigen::VectorXd noise) {
Eigen::MatrixXd information_matrix;
return information_matrix;
}
} // namespace graph_ptr_optimization
|
/*
* doChuChu.cpp
*
* Created on: Feb 7, 2014
* Author: Pooja
*/
#include<iostream>
int main () {
std::cout<<"hello";
//return 0;
}
|
#include "Debug.h"
#include "SpriteEntity.h"
#include "Graphics.h"
#include "Util.h"
#include <vector>
using namespace NoHope;
SpriteEntity::SpriteEntity(int x, int y, int width, int height, Texture* texture, Shader *shader):
_shader(shader),
_texture(texture)
{
init(x, y, width, height, Color(1.0f, 1.0f, 1.0f, 1.0f));
}
SpriteEntity::SpriteEntity(int x, int y, int width, int height, const Color& color, Shader *shader):
_shader(shader),
_texture(0)
{
init(x, y, width, height, color);
}
SpriteEntity::~SpriteEntity()
{
delete _texture;
delete _vertexData;
}
void SpriteEntity::init(int x, int y, int width, int height, const Color& color)
{
setPosition(Vec2(x, y));
std::vector<GLfloat> data(32);
data[0] = -width / 2.0f; data[1] = height / 2.0f;
data[8] = data[0]; data[9] = data[1] - height;
data[16] = data[0] + width; data[17] = data[1];
data[24] = data[0] + width; data[25] = data[1] - height;
for(int i = 2; i < 32; i += 8)
{
data[i] = color.red;
data[i+1] = color.green;
data[i+2] = color.blue;
data[i+3] = 1.0f;
}
data[6] = 0.0f; data[7] = 1.0f;
data[14] = 0.0f; data[15] = 0.0f;
data[22] = 1.0f; data[23] = 1.0f;
data[30] = 1.0f; data[31] = 0.0f;
_vertexData = new VertexData(data);
const GLushort iData[] = { 0, 1, 2, 2, 1, 3 };
std::vector<GLushort> indexData(iData, iData+6);
_indexData = new IndexData(indexData);
}
void SpriteEntity::setColor(const Color& color)
{
GLfloat colors[] = { color.red, color.green, color.blue, color.alpha };
for(int i = 2; i < 32; i += 8)
{
_vertexData->setData(GL_ARRAY_BUFFER, sizeof(GLfloat)*i, sizeof(GLfloat)*4, colors);
}
}
void SpriteEntity::draw(Camera &_camera)
{
glUseProgram(_shader->program());
if (_texture)
_texture->bind(_shader);
_shader->setUniform("projection", _projectionMatrix.data());
_shader->setUniform("view",_camera.cameraViewMatrix().data());
_shader->setUniform("model", getMatrix().data());
static const int stride = sizeof(GLfloat)*8;
_vertexData->bindBuffers();
_indexData->bindBuffers();
_vertexData->setAttribute(glGetAttribLocation(_shader->program(), "position"), 2, stride, 0); //vertex positions
_vertexData->setAttribute(glGetAttribLocation(_shader->program(), "color"), 4, stride, sizeof(GLfloat)*2); //color
_vertexData->setAttribute(glGetAttribLocation(_shader->program(), "texCoords"), 2, stride, sizeof(GLfloat)*6); //texture coordinates
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
//glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
checkGlError("glDrawElements");
}
void SpriteEntity::update(float dt)
{
}
|
#include "utils.hpp"
#include "spine_ptts.hpp"
namespace nora {
namespace config {
spine_limit_ptts& spine_limit_ptts_instance() {
static spine_limit_ptts inst;
return inst;
}
void spine_limit_ptts_set_funcs() {
}
hongmo_ptts& hongmo_ptts_instance() {
static hongmo_ptts inst;
return inst;
}
void hongmo_ptts_set_funcs() {
}
yanjing_ptts& yanjing_ptts_instance() {
static yanjing_ptts inst;
return inst;
}
void yanjing_ptts_set_funcs() {
}
yanshenguang_ptts& yanshenguang_ptts_instance() {
static yanshenguang_ptts inst;
return inst;
}
void yanshenguang_ptts_set_funcs() {
}
saihong_ptts& saihong_ptts_instance() {
static saihong_ptts inst;
return inst;
}
void saihong_ptts_set_funcs() {
}
meimao_ptts& meimao_ptts_instance() {
static meimao_ptts inst;
return inst;
}
void meimao_ptts_set_funcs() {
}
yanzhuang_ptts& yanzhuang_ptts_instance() {
static yanzhuang_ptts inst;
return inst;
}
void yanzhuang_ptts_set_funcs() {
}
chuncai_ptts& chuncai_ptts_instance() {
static chuncai_ptts inst;
return inst;
}
void chuncai_ptts_set_funcs() {
}
zui_ptts& zui_ptts_instance() {
static zui_ptts inst;
return inst;
}
void zui_ptts_set_funcs() {
}
huzi_ptts& huzi_ptts_instance() {
static huzi_ptts inst;
return inst;
}
void huzi_ptts_set_funcs() {
}
lian_ptts& lian_ptts_instance() {
static lian_ptts inst;
return inst;
}
void lian_ptts_set_funcs() {
}
tiehua_ptts& tiehua_ptts_instance() {
static tiehua_ptts inst;
return inst;
}
void tiehua_ptts_set_funcs() {
}
lianxing_ptts& lianxing_ptts_instance() {
static lianxing_ptts inst;
return inst;
}
void lianxing_ptts_set_funcs() {
}
spine_deform_face_ptts& spine_deform_face_ptts_instance() {
static spine_deform_face_ptts inst;
return inst;
}
void spine_deform_face_ptts_set_funcs() {
}
spine_deform_head_ptts& spine_deform_head_ptts_instance() {
static spine_deform_head_ptts inst;
return inst;
}
void spine_deform_head_ptts_set_funcs() {
}
spine_pool_ptts& spine_pool_ptts_instance() {
static spine_pool_ptts inst;
return inst;
}
void spine_pool_ptts_set_funcs() {
spine_pool_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (auto i = 0; i < ptt.npc_spines_size(); ++i) {
const auto& spines = ptt.npc_spines(i);
for (const auto& j : spines.selection()) {
if (!SPINE_PTTS_HAS(j.part(),j.pttid())) {
CONFIG_ELOG << ptt.id() << " spine not exist " << pd::spine_part_Name(j.part()) << " " << j.pttid();
}
}
}
};
}
spine_model_ptts& spine_model_ptts_instance() {
static spine_model_ptts inst;
return inst;
}
void spine_model_ptts_set_funcs() {
spine_model_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (const auto& i : ptt.selection()) {
if (!SPINE_PTTS_HAS(i.part(), i.pttid())) {
CONFIG_ELOG << ptt.id() << " " << pd::spine_part_Name(i.part()) << " not exist " << i.pttid();
}
}
};
}
}
}
|
#define ANKERL_NANOBENCH_IMPLEMENT
#include "nanobench.h"
#include "ut.hpp"
#if defined(__MACH__)
#include <stdlib.h>
#else
#include <malloc.h>
#endif
#include <random>
#include <iostream>
using namespace boost::ut;
void create_array(int n, double& d) {
double nums[n];
d = nums[n-1];
}
void create_array_2(int n, double& d) {
double *nums = (double *) malloc(n * sizeof(double));
d = nums[n-1];
free(nums);
}
int main(int argc, char* argv[]) {
"VLA vs malloc"_test = [] {
int n = rand()%1000 + 1;
auto bench = ankerl::nanobench::Bench();
bench.minEpochIterations(300);
double sum = 0;
bench.run("dynamic size", [&] {
double d;
create_array(n, d);
sum += d;
}
).doNotOptimizeAway(sum);
bench.run("malloc", [&] {
double d;
create_array_2(n, d);
sum += d;
}
).doNotOptimizeAway(sum);
};
}
|
#include <iostream>
#include <stdlib.h>
#include <conio.h>
#include <string>
#include <vector>
#include <TxCoord.h>
#include <time.h>
#include <windows.h>
using namespace std;
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD Written;
class Snake {
int snakeSize ;
vector <COORD> position;
public:
Snake()
{
COORD p;
snakeSize = 3;
p.X = 20;
p.Y = 20;
position.push_back(p);
}
void grow()
{
snakeSize++;
}
void draw()
{
for (int i =0; i<position.size()-1;i++)
{
if(i>=0 && position[i].Y==position[i+1].Y )//i-1 for more realistic commands
FillConsoleOutputCharacter(hOut,'-',1,position[i],&Written);
/*else if(i==0 && position[i].Y==position[i+1].Y)//unnecessary with position[i+1]
FillConsoleOutputCharacter(hOut, '-', 1, position[i], &Written);*/
else
FillConsoleOutputCharacter(hOut, '|', 1, position[i], &Written);
}
}
void setPosition(int x,int y)
{
COORD p;
p.X = position[position.size()-1].X+x;
p.Y = position[position.size() - 1].Y + y;
position.push_back(p);
modifyPosition();
}
void modifyPosition()
{
if (position.size() > snakeSize)
{
for (int i =1; i <position.size() - snakeSize; i++)
{
position.erase(position.begin());
}
}
}
COORD getPosition()
{
return position[position.size()-1];
}
COORD getCertainPosition(int i)//not actually needed but wutevs might need it later
{
return position[i];//need to set max size limit
}
int getPositionSize()
{
return position.size();
}
int getSnakeSize()
{
return snakeSize;
}
bool checkCollision()
{
COORD currentPosition;
currentPosition = position[position.size() - 1];
for (int i = 0; i < position.size() - 1; i++)
{
if (currentPosition.X == position[i].X && currentPosition.Y == position[i].Y)
return 0;
}
return 1;
}
bool checkSnakeOverOutOfBounds()
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
int columns, rows;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
if (position[position.size()-1].X<0 || position[position.size() - 1].Y<0 || position[position.size() - 1].X>columns || position[position.size() - 1].Y>rows)
return 0;
else
return 1;
}
};
class Dot {
CONSOLE_SCREEN_BUFFER_INFO csbi;
int columns, rows;
COORD dotPosition;
public:
void determinePosition()
{
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
dotPosition.X = rand() % (columns-1);
dotPosition.Y = rand() % (rows-1);
}
COORD getDotPosition()
{
return dotPosition;
}
void draw()
{
FillConsoleOutputCharacter(hOut, '*', 1, dotPosition, &Written);
}
};
void comparePositions(Dot& ,Snake&);
bool disallowOverlap(Dot&, Snake&);
void setCourse(char,Snake&);
int main(void)
{
bool flagGame = 1,flagGameCollision=1;
Snake s;
Dot d;
srand(time(NULL));
char c;
char lastPosition='r';//used to maintain course,also to make starting course right
d.determinePosition();
d.draw();
while (1)
{
if (_kbhit())
{
c = _getch();
if ((c == 75 && lastPosition == 'r') || (c == 77 && lastPosition == 'l') || (c == 72 && lastPosition == 'd') || (c == 80 && lastPosition == 'u'))
setCourse(lastPosition, s);
else
{
switch (c)
{
case 75://left
s.setPosition(-1, 0);
lastPosition = 'l';
break;
case 77://right
s.setPosition(1, 0);
lastPosition = 'r';
break;
case 72://up
s.setPosition(0, -1);
lastPosition = 'u';
break;
case 80://down
s.setPosition(0, 1);
lastPosition = 'd';
break;
default:continue;
}
}
}
else
setCourse(lastPosition, s);
flagGameCollision = s.checkCollision();
if (flagGameCollision == 0)
break;
flagGame = s.checkSnakeOverOutOfBounds();
if (flagGame == 0)
break;
system("cls");
comparePositions(d, s);
d.draw();
s.draw();
Sleep(100);
}
cout << "\n\n\n\n\n\t\t\t\tGAME OVER!\n\t\t\t Your score is:"<<s.getSnakeSize()-3<<"\n\t\t\t Press any key to exit." << endl;
_getch();
return 0;
}
void comparePositions(Dot& d, Snake& s)
{
bool flag=0;
COORD dotCoord, snakeCoord;
dotCoord = d.getDotPosition();
snakeCoord = s.getPosition();
if (snakeCoord.X == dotCoord.X && snakeCoord.Y == dotCoord.Y)
{
s.grow();
d.determinePosition();
while(flag==0)
{
d.determinePosition();
flag = disallowOverlap(d,s);
}
d.draw();
}
}
bool disallowOverlap(Dot& d,Snake& s)
{
COORD dotCoord = d.getDotPosition();
for (int i = 0; i < s.getSnakeSize(); i++)
{
COORD snakeCoord = s.getCertainPosition(i);
if (snakeCoord.X == dotCoord.X && snakeCoord.Y == dotCoord.Y)
return 0;
}
return 1;
}
void setCourse(char c,Snake &s)
{
switch (c)
{
case 'l':
s.setPosition( -1, 0);
break;
case 'r':
s.setPosition(1, 0);
break;
case 'u':
s.setPosition(0, -1);
break;
case 'd':
s.setPosition(0, 1);
break;
}
}
/*switch (c) //backup just in case
{
case 75://left
if (lastPosition != 'r')//maintaining course,if lastPosition=r
{ //it means you were going right,so pressing left doesnt affect course
s.setPosition(-1, 0);
lastPosition = 'l';
break;
}
case 77://right
if (lastPosition != 'l')
{
s.setPosition(1, 0);
lastPosition = 'r';
break;
}
case 72://up
if (lastPosition != 'd')
{
s.setPosition(0, -1);
lastPosition = 'u';
break;
}
case 80://down
if (lastPosition != 'u')
{
s.setPosition(0, 1);
lastPosition = 'd';
break;
}
default:continue;
}*/
|
#include <queue>
#include <set>
using namespace std;
template <class T>
void time_leak::ElementUniqueFifo<T>::Push(T t)
{
if (this->Set.find(t) == this->Set.end())
{
this->Queue.push(t);
this->Set.insert(t);
}
}
template <class T>
T time_leak::ElementUniqueFifo<T>::Pop()
{
T t = this->Queue.front();
this->Queue.pop();
return t;
}
template <class T>
int time_leak::ElementUniqueFifo<T>::Size()
{
return this->Queue.size();
}
template <class T>
T time_leak::ElementUniqueFifo<T>::Front()
{
return this->Queue.front();
}
template <class T>
void time_leak::ElementUniqueFifo<T>::Shift()
{
T t = this->Pop();
this->Queue.push(t);
}
template <class T>
void time_leak::ElementUniqueFifo<T>::Clear()
{
this->Queue.empty();
this->Set.clear();
}
template <class T, class T2>
bool time_leak::ForwardQueue(T &queue1, T2 &queue2, bool direction)
{
bool changesMade = false;
if (queue1.Size() > 0)
{
if (queue1.Front()->AllDirectionsAnalyzed(direction))
{
auto element = queue1.Pop();
changesMade = element->Analyze();
time_leak::Traverse(element->GetElementsBasedOnDirection(direction), queue2);
}
else
{
auto element = queue1.Front();
auto elements = element->GetElementsBasedOnDirection(!direction);
for (auto iterator = elements.begin(); iterator != elements.end(); ++iterator)
{
if (!iterator->second->WasAnalyzed())
{
iterator->second->Analyze();
break;
}
}
queue1.Shift();
}
}
return changesMade;
}
template <class T>
void time_leak::Traverse(std::map<std::string, T *> elements, time_leak::ElementUniqueFifo<T *> &queue)
{
typename std::map<std::string, T *>::iterator iterator;
for (iterator = elements.begin(); iterator != elements.end(); ++iterator)
{
queue.Push(iterator->second);
}
}
|
#include "stdafx.h"
#include "GetConsoleInput.h"
using namespace std;
std::string pure::getConsoleInputstr(const std::string & message)
{
string response;
cout << message << ": ";
cin >> response;
return response;
}
bool pure::getConsoleInputb(const std::string & message, const std::string & errorMessage)
{
string response = "";
string responseCpy = "";
while (true)
{
cout << message << " (y/n): ";
cin >> response;
cout << endl;
responseCpy = response;
if (responseCpy.compare("yes") != 0 &&
responseCpy.compare("no") != 0 &&
responseCpy.compare("n") != 0 &&
responseCpy.compare("y") != 0)
{
if (errorMessage.size() != 0)
cout << errorMessage << endl;
}
else
{
break;
}
}
if (response.compare("yes") == 0 || response.compare("y") == 0)
return true;
return false;
}
int pure::getConsoleInputi(const std::string & message, const std::string & errorMessage)
{
string response = "";
bool bGoodParse = true;
int result = 0;
do
{
cout << message << ": ";
cin >> response;
cout << endl;
try
{
result = std::stoi(response);
bGoodParse = true;
}
catch (...)
{
bGoodParse = false;
if (errorMessage.size() != 0)
cout << errorMessage << endl;
}
} while (!bGoodParse);
return result;
}
long pure::getConsoleInputl(const std::string & message, const std::string & errorMessage)
{
string response = "";
bool bGoodParse = true;
long result = 0;
do
{
cout << message << ": ";
cin >> response;
cout << endl;
try
{
result = std::stol(response);
bGoodParse = true;
}
catch (...)
{
bGoodParse = false;
if (errorMessage.size() != 0)
cout << errorMessage << endl;
}
} while (!bGoodParse);
return result;
}
long long pure::getConsoleInputll(const std::string & message, const std::string & errorMessage)
{
string response = "";
bool bGoodParse = true;
long long result = 0;
do
{
cout << message << ": ";
cin >> response;
cout << endl;
try
{
result = std::stoll(response);
bGoodParse = true;
}
catch (...)
{
bGoodParse = false;
if (errorMessage.size() != 0)
cout << errorMessage << endl;
}
} while (!bGoodParse);
return result;
}
|
#include "OpenGL/OpenGLVertexArray.h"
#include <glad/glad.h>
using namespace Rocket;
static GLenum ShaderDataTypeToOpenGLBaseType(ShaderDataType type)
{
switch (type)
{
case ShaderDataType::Float: return GL_FLOAT;
case ShaderDataType::Vec2f: return GL_FLOAT;
case ShaderDataType::Vec3f: return GL_FLOAT;
case ShaderDataType::Vec4f: return GL_FLOAT;
case ShaderDataType::Mat2f: return GL_FLOAT;
case ShaderDataType::Mat3f: return GL_FLOAT;
case ShaderDataType::Mat4f: return GL_FLOAT;
case ShaderDataType::Int: return GL_INT;
case ShaderDataType::Vec2i: return GL_INT;
case ShaderDataType::Vec3i: return GL_INT;
case ShaderDataType::Vec4i: return GL_INT;
case ShaderDataType::Bool: return GL_BOOL;
default: RK_CORE_ASSERT(false, "Unknown ShaderDataType!"); return 0;
}
}
OpenGLVertexArray::OpenGLVertexArray()
{
glGenVertexArrays(1, &m_RendererID);
}
OpenGLVertexArray::~OpenGLVertexArray()
{
glDeleteVertexArrays(1, &m_RendererID);
}
inline void OpenGLVertexArray::Bind() const
{
glBindVertexArray(m_RendererID);
}
inline void OpenGLVertexArray::Unbind() const
{
glBindVertexArray(0);
}
inline void OpenGLVertexArray::AddVertexBuffer(const Ref<VertexBuffer>& vertexBuffer)
{
RK_GRAPHICS_ASSERT(vertexBuffer->GetLayout().GetElements().size(), "Vertex Buffer has no layout!");
glBindVertexArray(m_RendererID);
vertexBuffer->Bind();
const auto& layout = vertexBuffer->GetLayout();
for (const auto& element : layout)
{
switch (element.Type)
{
case ShaderDataType::Float:
case ShaderDataType::Vec2f:
case ShaderDataType::Vec3f:
case ShaderDataType::Vec4f:
case ShaderDataType::Int:
case ShaderDataType::Vec2i:
case ShaderDataType::Vec3i:
case ShaderDataType::Vec4i:
case ShaderDataType::Bool:
{
glEnableVertexAttribArray(m_VertexBufferIndex);
glVertexAttribPointer(m_VertexBufferIndex,
element.GetComponentCount(),
ShaderDataTypeToOpenGLBaseType(element.Type),
element.Normalized ? GL_TRUE : GL_FALSE,
layout.GetStride(),
(const void*)element.Offset);
m_VertexBufferIndex++;
break;
}
case ShaderDataType::Mat2f:
case ShaderDataType::Mat3f:
case ShaderDataType::Mat4f:
{
uint8_t count = element.GetComponentCount();
for (uint8_t i = 0; i < count; i++)
{
glEnableVertexAttribArray(m_VertexBufferIndex);
glVertexAttribPointer(m_VertexBufferIndex,
count,
ShaderDataTypeToOpenGLBaseType(element.Type),
element.Normalized ? GL_TRUE : GL_FALSE,
layout.GetStride(),
(const void*)(element.Offset + sizeof(float) * count * i));
glVertexAttribDivisor(m_VertexBufferIndex, 1);
m_VertexBufferIndex++;
}
break;
}
default:
RK_CORE_ASSERT(false, "Unknown ShaderDataType!");
}
}
m_VertexBuffers.push_back(vertexBuffer);
glBindVertexArray(0);
}
inline void OpenGLVertexArray::SetIndexBuffer(const Ref<IndexBuffer>& indexBuffer)
{
glBindVertexArray(m_RendererID);
indexBuffer->Bind();
m_IndexBuffer = indexBuffer;
glBindVertexArray(0);
}
|
//////////////////////////////////////////////////////////////////////////////////////////////////////
///////// //////// ///////// //////// // // ////////// //// // ///////
// // // // // // // // // // // // // // \\
// ///////// //////// // // // // // // // // // \\
// // // // // // // // // // // // // \\ //
///////// // // // // //////// /////// ////////// // //// ///////
//////////////////////////////////////////////////////////////////////////////////////////////////////
/* Code by Dhiraj Jadhao
for more details on how to setup arduino board to control it wirelessly with iArduino App
and how to get started visit Official Website:
http://i-arduino.blogspot.com
This code is for use with iArduino App and is based on RN171XVW WiFly Module.
all rights reserved please contact on following mail id for details:
dhirajjadhao@gmail.com
*/
#include <SPI.h> // for Arduino later than ver 0018
#include <Servo.h>
char str[10];
// Define Servo pins
Servo relay2,relay3,relay4,relay5,relay6,relay7,relay8,relay9,relay44,relay45,relay46;
////
void setup()
{
Serial.begin(9600);
//Define servo pins to attach
relay2.attach(2);
relay3.attach(3);
relay4.attach(4);
relay5.attach(5);
relay6.attach(6);
relay7.attach(7);
relay8.attach(8);
relay9.attach(9);
relay44.attach(44);
relay45.attach(45);
relay46.attach(46);
}
void loop()
{
// Integer that will hold our PWM values for later use //
int relay2pwmVal;
int relay3pwmVal;
int relay4pwmVal;
int relay5pwmVal;
int relay6pwmVal;
int relay7pwmVal;
int relay8pwmVal;
int relay9pwmVal;
int relay44pwmVal;
int relay45pwmVal;
int relay46pwmVal;
if(Serial.available() > 0)
{
int packetSize = Serial.available();
for (byte i=0; i< packetSize; i++)
{
str[i] = Serial.read();
}
///////////////////////// PWM Value Formatting //////////////////////////////////
relay2pwmVal = (str[3] - '0')*100 + (str[4] - '0')*10 + (str[5] - '0');
relay3pwmVal = (str[3] - '0')*100 + (str[4] - '0')*10 + (str[5] - '0');
relay4pwmVal = (str[3] - '0')*100 + (str[4] - '0')*10 + (str[5] - '0');
relay5pwmVal = (str[3] - '0')*100 + (str[4] - '0')*10 + (str[5] - '0');
relay6pwmVal = (str[3] - '0')*100 + (str[4] - '0')*10 + (str[5] - '0');
relay7pwmVal = (str[3] - '0')*100 + (str[4] - '0')*10 + (str[5] - '0');
relay8pwmVal = (str[3] - '0')*100 + (str[4] - '0')*10 + (str[5] - '0');
relay9pwmVal = (str[3] - '0')*100 + (str[4] - '0')*10 + (str[5] - '0');
relay44pwmVal = (str[4] - '0')*100 + (str[5] - '0')*10 + (str[6] - '0');
relay45pwmVal = (str[4] - '0')*100 + (str[5] - '0')*10 + (str[6] - '0');
relay46pwmVal = (str[4] - '0')*100 + (str[5] - '0')*10 + (str[6] - '0');
//////////////////////// Pin 2 (relay2) /////////////////////////////////////
if (str[0] == 'P' && str[1]=='2' && str[2]=='M')
{
relay2.write(relay2pwmVal); //Set relay2 to PWM Value
Serial.println(relay2pwmVal); //Write notification
}
//////////////////////// Pin 3 (relay3) /////////////////////////////////////
else if (str[0] == 'P' && str[1]=='3' && str[2]=='M')
{
relay3.write(relay3pwmVal); //Set relay3 to PWM Value
Serial.println(relay3pwmVal); //Write notification
}
//////////////////////// Pin 4 (relay4) /////////////////////////////////////
else if (str[0] == 'P' && str[1]=='4' && str[2]=='M')
{
relay4.write(relay4pwmVal); //Set relay4 to PWM Value
Serial.println(relay4pwmVal); //Write notification
}
//////////////////////// Pin 5 (relay5) /////////////////////////////////////
else if (str[0] == 'P' && str[1]=='5' && str[2]=='M')
{
relay5.write(relay5pwmVal); //Set relay5 to PWM Value
Serial.println(relay5pwmVal); //Write notification
}
//////////////////////// Pin 6 (relay6) /////////////////////////////////////
else if (str[0] == 'P' && str[1]=='6' && str[2]=='M')
{
relay6.write(relay6pwmVal); //Set relay6 to PWM Value
Serial.println(relay6pwmVal); //Write notification
}
//////////////////////// Pin 7 (relay7) /////////////////////////////////////
else if (str[0] == 'P' && str[1]=='7' && str[2]=='M')
{
relay7.write(relay7pwmVal); //Set relay7 to PWM Value
Serial.println(relay7pwmVal); //Write notification
}
//////////////////////// Pin 8 (relay8) /////////////////////////////////////
else if (str[0] == 'P' && str[1]=='8' && str[2]=='M')
{
relay8.write(relay8pwmVal); //Set relay8 to PWM Value
Serial.println(relay8pwmVal); //Write notification
}
//////////////////////// Pin 9 (relay9) /////////////////////////////////////
else if (str[0] == 'P' && str[1]=='9' && str[2]=='M')
{
relay9.write(relay9pwmVal); //Set relay9 to PWM Value
Serial.println(relay9pwmVal); //Write notification
}
//////////////////////// Pin 44 (relay44) /////////////////////////////////////
else if (str[0] == 'P' && str[1]=='4' && str[2]=='4' && str[2]=='M')
{
relay44.write(relay44pwmVal); //Set relay44 to PWM Value
Serial.println(relay44pwmVal); //Write notification
}
//////////////////////// Pin 45 (relay45) /////////////////////////////////////
else if (str[0] == 'P' && str[1]=='4' && str[2]=='5' && str[2]=='M')
{
relay45.write(relay45pwmVal); //Set relay45 to PWM Value
Serial.println(relay45pwmVal); //Write notification
}
//////////////////////// Pin 46 (relay46) /////////////////////////////////////
else if (str[0] == 'P' && str[1]=='4' && str[2]=='6' && str[2]=='M')
{
relay46.write(relay46pwmVal); //Set relay45 to PWM Value
Serial.println(relay46pwmVal); //Write notification
}
}
delay(20);
Serial.flush();
}
|
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
bool visited[100001];
int trace[100001];
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
std::memset(trace, -1, sizeof(trace));
int n, k;
std::queue<std::pair<int, int>> q;
std::cin >> n >> k;
q.push({n, 0});
visited[n] = 1;
while(!q.empty())
{
auto [now, time] = q.front();
q.pop();
if(now == k)
{
std::cout << time << '\n';
break;
}
int next[3] = {now - 1, now + 1, now + now};
for(int i = 0; i < 3; i++)
{
if(next[i] >= 0 && next[i] <= 100000 && !visited[next[i]])
{
q.push({next[i], time + 1});
visited[next[i]] = 1;
trace[next[i]] = now;
}
}
}
std::vector<int> ans;
int tracing = k;
while(tracing >= 0)
{
ans.push_back(tracing);
tracing = trace[tracing];
}
for(auto x = ans.rbegin(); x != ans.rend(); x++)
{
std::cout << *x << ' ';
}
return 0;
}
|
#include "SnakeGame.h"
int main()
{
snake.Print();
system("cls");
snake.load();
snake.length=5;
head.x=25;
head.y=20;
head.direction=RIGHT;
snake.Boarder();
snake.Food(); //to generate food coordinates initially
snake.life=3; //number of extra lives
bend[0]= head;
snake.Move(); //initialing initial bend coordinate
return 0;
}
|
// 阴阳师合成高星式神
#include <iostream>
using namespace std;
unsigned long long int getNum(unsigned long int num) {
unsigned long long int sum = 0;
if (num == 2) {
return 1;
} else {
return sum + num * getNum(num - 1);
}
}
unsigned long long int getRes (unsigned long int num) {
unsigned long long int res = 1;
if (num == 2) {
return 1;
} else {
for (num; num > 2; num--) {
res *= num;
}
}
return res;
}
int main() {
unsigned long int num = 0;
cin>>num;
unsigned long long int res = getRes(num);
cout<<res<<endl;
return 0;
}
|
#ifndef GEOMETRY_HPP
#define GEOMETRY_HPP
#include <QJsonDocument>
#include <string>
#include <vector>
enum Type {sphere, plane, none};
struct Point
{
double x;
double y;
double z;
};
double dotProduct(Point p1, Point p2);
Point subPts(Point p1, Point p2);
Point multPt(Point p, double factor);
Point addPts(Point p1, Point p2);
double dist(Point p1, Point p2);
bool solveQuadratic(double a, double b, double c, double& t1, double& t2);
struct Vec3d
{
Point startpt;
Point dirpt;
double magnitude()
{
Point zero;
zero.x = 0;
zero.y = 0;
zero.z = 0;
return dist(zero, dirpt);
}
void normalize()
{
double mag = magnitude();
if (mag != 0)
{
dirpt = multPt(dirpt, 1/mag);
}
}
};
struct Light
{
Point location;
double intensity;
};
struct Shape
{
Type type;
Point center;
Point normal;
double radius;
int r;
int g;
int b;
double lambert;
bool intersect(Point start, Point direction, double tLimit, double& t)
{
if (type == sphere)
{
double t1, t2;
Point pt = subPts(start, center);
double a = dotProduct(direction, direction);
double b = 2 * dotProduct(direction, pt);
double c = dotProduct(pt, pt) - (radius * radius);
if (!solveQuadratic(a, b, c, t1, t2))
{
return false;
}
if (t1 > t2)
{
double temp = t1;
t1 = t2;
t2 = temp;
}
if (t1 < tLimit)
{
t1 = t2;
if (t1 < tLimit)
{
return false;
}
}
Vec3d testtemp;
testtemp.dirpt = multPt(direction, t1);
if (testtemp.magnitude() > 0.0001)
{
t = t1;
return true;
}
return false;
}
else if (type == plane)
{
double denominator = dotProduct(normal,direction);
if (denominator > 1e-6 || denominator < -1e-6)
{
Point centerstart = subPts(center, start);
t = dotProduct(centerstart, normal) / denominator;
return (t >= tLimit);
}
return false;
}
else
{
return false;
}
}
};
struct Camera
{
Point center;
Point normal;
double focus;
double sizeX;
double sizeY;
double resX;
double resY;
};
class Geometry
{
public:
Geometry(std::string filetext);
~Geometry();
//put publicly accessable environment here
std::vector<Light> lights;
std::vector<Shape> shapes;
Camera camera;
private:
};
void validate(QJsonDocument& env);
bool isValidCoord(QJsonValue val);
bool isValidRadius(QJsonValue val);
bool isValidIntensity(QJsonValue val);
bool isValidLambert(QJsonValue val);
bool isValidColor(QJsonValue val);
bool isValidSize(QJsonValue val);
bool isValidRes(QJsonValue val);
#endif
|
#include<stdio.h>
#include<stdlib.h>
//这里创建一个结构体用来表示链表的结点类型
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head, *p, *q, *t;
int i, n ,a;
scanf("%d", &n);
head = NULL; //头指针初始为空
for(i = 1; i <= n; i++)
{
scanf("%d", &a);
//动态申请一个空间,用来存放一个结点,并用临时指针p指向这个结点
p = (struct node *)malloc(sizeof(struct node));
p->data = a; //将数据存储到当前结点的data域中
p->next = NULL; //设置当前结点的后继指针为空,即当前结点的下一个结点为空
if(head == NULL)
head = p; //如果这是第一个创建的结点,则将头指针指向这个结点
else
q->next = p; //如果这不是第一个创建的结点,则将上一个结点的后继指针指向当前结点
q = p;
}
scanf("%d", &a);
t = head; //从链表的头部开始遍历
while(t!=NULL) //当前没有到达链表尾部的时候循环
{
if(t->next == NULL||t->next->data > a)
{
p = (struct node *)malloc(sizeof(struct node)); // 动态申请一个空间,用来存放新增结点
p->data = a;
p->next = t->next; //新增结点的后继指针指向当前结点的后继指针所指向的结点
t->next = p; //当前结点的后继指针指向新增结点
break; //插入完毕后退出循环
}
t = t->next; //继续下一个结点
}
t = head;
while(t!=NULL)
{
printf("%d ", t->data);
t = t->next;
}
getchar();
return 0;
}
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2012-2013.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#ifndef _GDCMIO_DICOMCODEDATTRIBUTE_HPP_
#define _GDCMIO_DICOMCODEDATTRIBUTE_HPP_
#include <string>
#include "gdcmIO/config.hpp"
namespace gdcmIO
{
/**
* @brief Structure for basic coded entry.
*
* It defines the identification of a coded content.
*
* @see DICOM PS 3.3 Table 8.8-1
*
* @class DicomCodedAttribute.
* @author IRCAD (Research and Development Team).
* @date 2011.
*/
struct DicomCodedAttribute
{
GDCMIO_API DicomCodedAttribute():
CV(""),
CSD(""),
CSV(""),
CM("")
{
}
GDCMIO_API DicomCodedAttribute(const char * a_CV,
const char * a_CSD,
const char * a_CM,
const char * a_CSV = ""):
CV(a_CV),
CSD(a_CSD),
CSV(a_CSV),
CM(a_CM)
{
}
GDCMIO_API ~DicomCodedAttribute()
{
}
std::string CV; ///< Code Value (see : Tag(0008,0100) )
std::string CSD; ///< Code Scheme Designator (see : Tag(0008,0102) )
std::string CSV; ///< Code Scheme Version (see : Tag(0008,0103) )
std::string CM; ///< Code Meaning (see : Tag(0008,0104) )
};
}
#endif /* _GDCMIO_DICOMCODEDATTRIBUTE_HPP_ */
|
#include "Input.h"
#include "Map.h"
#include "CoinManager.h"
#include "Player.h"
#include <time.h>
#include <stdlib.h>
#include <iostream>
int main(void) {
srand(time(nullptr));
int difficulty;
int scoreToWin = 80;
clock_t start;
do {
std::cout << " ---------------" << std::endl;
std::cout << " || COIN RACE ||" << std::endl;
std::cout << " ---------------" << std::endl << std::endl;
std::cout << "Select difficulty |1, 2, 3|" << std::endl;
std::cin >> difficulty;
start = clock();
} while(difficulty < 1 || difficulty > 3);
Map mapa1(difficulty);
CoinManager manejador(mapa1);
Player senyor(mapa1, manejador);
mapa1.printer();
while(senyor.puntuacio < scoreToWin) {
if (senyor.movement()) {
senyor.scoreCounter();
mapa1.cellModify(senyor.x, senyor.y, '@');
mapa1.printer();
std::cout << std::endl << std::endl;
std::cout << senyor.puntuacio << "/" << scoreToWin << std::endl;
}
};
std::cout << "Congrats!, you have taken " << (clock() - start)/1000 << " seconds and earn " << scoreToWin << " points"; //entre 1000 per pasar-ho a segons.
}
|
// Created on: 1997-08-01
// Created by: Jean-Louis Frenkel
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _PCDM_ReaderStatus_HeaderFile
#define _PCDM_ReaderStatus_HeaderFile
//! Status of reading of a document.
//! The following values are accessible:
//! - PCDM_RS_OK: the document was successfully read;
//! - PCDM_RS_NoDriver: driver is not found for the defined file format;
//! - PCDM_RS_UnknownFileDriver: check of the file failed (file doesn't exist, for example);
//! - PCDM_RS_OpenError: attempt to open the file failed;
//! - PCDM_RS_NoVersion: document version of the file is out of scope;
//! - PCDM_RS_NoSchema: NOT USED;
//! - PCDM_RS_NoDocument: document is empty (failed to be read correctly);
//! - PCDM_RS_ExtensionFailure: NOT USED;
//! - PCDM_RS_WrongStreamMode: file is not open for reading (a mistaken mode);
//! - PCDM_RS_FormatFailure: mistake in document data structure;
//! - PCDM_RS_TypeFailure: data type is unknown;
//! - PCDM_RS_TypeNotFoundInSchema: data type is not found in schema (STD file format);
//! - PCDM_RS_UnrecognizedFileFormat: document data structure is wrong (binary file format);
//! - PCDM_RS_MakeFailure: conversion of data from persistent to transient attributes failed (XML file format);
//! - PCDM_RS_PermissionDenied: file can't be opened because permission is denied;
//! - PCDM_RS_DriverFailure: something went wrong (a general mistake of reading of a document);
//! - PCDM_RS_AlreadyRetrievedAndModified: document is already retrieved and modified in current session;
//! - PCDM_RS_AlreadyRetrieved: document is already in current session (already retrieved);
//! - PCDM_RS_UnknownDocument: file doesn't exist on disk;
//! - PCDM_RS_WrongResource: wrong resource file (.RetrievalPlugin);
//! - PCDM_RS_ReaderException: no shape section in the document file (binary file format);
//! - PCDM_RS_NoModel: NOT USED;
//! - PCDM_RS_UserBreak: user stopped reading of the document;
enum PCDM_ReaderStatus
{
PCDM_RS_OK, //!< Success
PCDM_RS_NoDriver, //!< No driver for file format
PCDM_RS_UnknownFileDriver, //!< File is bad
PCDM_RS_OpenError, //!< Can't open file
PCDM_RS_NoVersion, //!< Unknown document version
PCDM_RS_NoSchema, //!< NOT USED
PCDM_RS_NoDocument, //!< Document is empty
PCDM_RS_ExtensionFailure, //!< NOT USED
PCDM_RS_WrongStreamMode, //!< Open mode is mistaken
PCDM_RS_FormatFailure, //!< Document data structure is wrong
PCDM_RS_TypeFailure, //!< Data type is unknown
PCDM_RS_TypeNotFoundInSchema, //!< Data type is not found in schema
PCDM_RS_UnrecognizedFileFormat, //!< Document data structure is wrong
PCDM_RS_MakeFailure, //!< Conversion of data failed
PCDM_RS_PermissionDenied, //!< Permission denied to open file
PCDM_RS_DriverFailure, //!< General mistake of reading
PCDM_RS_AlreadyRetrievedAndModified, //!< Document is already retrieved and modified
PCDM_RS_AlreadyRetrieved, //!< Document is already retrieved
PCDM_RS_UnknownDocument, //!< File doesn't exist
PCDM_RS_WrongResource, //!< Wrong resource file
PCDM_RS_ReaderException, //!< Wrong data structure
PCDM_RS_NoModel, //!< NOT USED
PCDM_RS_UserBreak //!< User interrupted reading
};
#endif // _PCDM_ReaderStatus_HeaderFile
|
#include<iostream>
//#include<stdio.h>
using namespace std;
class A
{
public:
int a;
static int x;
// void show()
// {
// cout<<"a= "<<a<<endl;
// cout<<"x= "<<x<<endl;
// }
};
int A::x=1;
int main()
{
int i=10,j=20;
int &r=i;
int *ptr=&i;
cout<<"r= "<<r;
cout<<"\n&r= "<<&r;
cout<<"\n&i= "<<&i;
cout<<"\nptr= "<<ptr;
cout<<"\n&ptr= "<<&ptr;
r++;
(*ptr)++;
cout<<"\nr++= "<<r;
cout<<"\n*ptr= "<<*ptr;
cout<<"\ni= "<<i;
r=j;
cout<<"\n&r++= "<<r;
cout<<"\n*ptr= "<<*ptr;
cout<<"\ni= "<<i;
// printf("j=%d\n",j);
}
|
#include<cstdio>
#include<iostream>
using namespace std;
int n;
int b[1000];//储存每个字母的数组位置
struct node
{
char data;//数据
char lc,rc;//儿子
}a[30];
void q(int i)
{
if(a[i].data && i<=n)//不为空
{
printf("%c",a[i].data);//先输出根
if(a[i].lc!='*')//若他有左儿子
q(b[a[i].lc]);//继续前序遍历
if(a[i].rc!='*')//右儿子,同上
q(b[a[i].rc]);
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
cin>>a[i].data>>a[i].lc>>a[i].rc;
b[a[i].data]=i;//记录数组位置
}
q(1);
return 0;
}
|
/*
Dispenser
This sketch controls the dispensers in Robie's vending machine.
Author: Andy Tracy <adtme11@gmail.com>
*/
const int d1p_pin = 2; // Dispenser 1 positive
const int d1n_pin = 3; // Dispenser 1 negative
const int d2p_pin = 4; // Dispenser 2 positive
const int d2n_pin = 5; // Dispenser 2 negative
void setup()
{
// Start up the serial connection
Serial.begin ( 9600 );
// Motor control pins
pinMode ( d1p_pin, OUTPUT );
pinMode ( d1n_pin, OUTPUT );
pinMode ( d2p_pin, OUTPUT );
pinMode ( d2n_pin, OUTPUT );
digitalWrite ( d1p_pin, LOW );
digitalWrite ( d1n_pin, LOW );
digitalWrite ( d2p_pin, LOW );
digitalWrite ( d2n_pin, LOW );
}
void dispense ( int slot, int quant )
{
// Convert quant to time
unsigned long time = quant * 10000;
// Run the motor for that amount of time
digitalWrite ( slot, HIGH );
delay ( time );
digitalWrite ( slot, LOW );
}
void loop()
{
// Check for serial input
if ( Serial.available() > 0 ) {
// Read in the directive byte
char directive = Serial.read();
if ( directive == 'd' ) { // dispense
// Send ACK
Serial.write ( 'a' );
// Read the two data bytes
while ( Serial.available() < 2 ) {}
int slot = Serial.read();
int quant = Serial.read();
// Dispense based on input
if ( slot == 1 ) slot = d1n_pin;
else if ( slot == 0 ) slot = d2n_pin;
else return;
dispense ( slot, quant );
// Send another signal to indicate dispense is complete
Serial.write ( 'a' );
} else {
// Send NACK
Serial.write ( 'n' );
}
}
}
|
#include <iostream>
#include "maze.hpp"
using namespace std;
int main() {
vector<vector<int>> maze = mkMaze(10);
for (auto x : maze) {
for (auto y : x) {
cout << (y == 1? " " : (y == 3? "==" : "██")); // esto -> ██ deben ser bloques
}
cout << endl;
}
// you should see a beautiful maze
return 0;
}
|
int segmentid, i, j;
cv::Mat labels;
seeds->getLabels(labels);
cv::Mat segment[seeds->getNumberOfSuperpixels()];
for (i = 0; i < seeds->getNumberOfSuperpixels(); i++) {
segment[i] = cv::Mat::zeros(height, width, cv_left_ptr->image.type());
}
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
segmentid = labels.at<int>(i, j);
segment[segmentid].at<uchar>(i, j) = result.at<uchar>(i, j);
}
}
for (i = 0; i < seeds->getNumberOfSuperpixels(); i++) {
ROS_INFO("showing segment %d\n", i);
cv::imshow("window_name", segment[i]);
cv::waitKey(0);
}
|
#include <DigitalPin.h> // from BasicLibrary
DigitalPin forward(13, true);
DigitalPin backward(12, true);
DigitalPin right(7, true);
DigitalPin left(8, true);
void setup(){
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
int val = int(Serial.read()) - int('0');
if (val == 0) {
backward.off();
right.off();
forward.on();
left.on();
} else if(val == 1){
backward.off();
right.off();
left.off();
forward.on();
} else if(val == 2) {
backward.off();
left.off();
right.on();
forward.on();
} else if (val == 3) {
right.off();
forward.off();
backward.on();
left.on();
} else if(val == 4){
right.off();
left.off();
forward.off();
backward.on();
} else if(val == 5) {
left.off();
forward.off();
backward.on();
right.on();
} else if(val == 6) {
left.off();
forward.off();
backward.off();
right.off();
}
Serial.flush();
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#include "core/pch.h"
#include "modules/util/opfile/opfile.h"
#include "modules/url/url2.h"
#include "modules/url/url_man.h"
#include "modules/url/url_rep.h"
#include "modules/cache/url_cs.h"
#include "modules/cache/cache_debug.h"
#include "modules/cache/cache_int.h"
#include "modules/cache/cache_common.h"
#include "modules/cache/cache_ctxman_disk.h"
#include "modules/url/url_ds.h"
#include "modules/olddebug/timing.h"
#ifdef _DEBUG
#ifdef YNP_WORK
#include "modules/olddebug/tstdump.h"
#define _DEBUG_DD
#define _DEBUG_DD1
#include "modules/url/tools/url_debug.h"
#endif
#endif
unsigned long GetFileError(OP_STATUS op_err, URL_Rep *url, const uni_char *operation);
#ifdef UNUSED_CODE
File_Storage::File_Storage(Cache_Storage *source, URLCacheType ctyp, BOOL frc_save, BOOL kp_open_file)
:Cache_Storage(source)
{
cachetype = ctyp;
cache_file = NULL;
info.force_save = frc_save;
info.keep_open_file = kp_open_file;
info.dual = FALSE;
info.completed = FALSE;
info.computed = FALSE;
#ifdef SEARCH_ENGINE_CACHE
info.modified = FALSE;
#endif
file = NULL;
file_count = 0;
folder = OPFILE_ABSOLUTE_FOLDER;
#ifdef URL_ENABLE_ASSOCIATED_FILES
purge_assoc_files = 0;
#endif
}
#endif
File_Storage::File_Storage(URL_Rep *url_rep, URLCacheType ctyp, BOOL frc_save, BOOL kp_open_file)
:Cache_Storage(url_rep)
{
cachetype = ctyp;
cache_file = NULL;
file_count = 0;
info.force_save = frc_save;
info.keep_open_file = kp_open_file;
info.dual = FALSE;
info.memory_only_storage = FALSE;
#ifdef SEARCH_ENGINE_CACHE
info.modified = FALSE;
#endif
folder = OPFILE_ABSOLUTE_FOLDER;
info.completed = FALSE;
info.computed = FALSE;
content_size = 0;
stored_size = 0;
#ifdef URL_ENABLE_ASSOCIATED_FILES
purge_assoc_files = 0;
#endif
}
File_Storage::~File_Storage()
{
Purge();
}
OP_STATUS File_Storage::Construct(Cache_Storage *source, const OpStringC &target)
{
OP_ASSERT(source);
RETURN_IF_ERROR(filename.Set(target));
if(GetCacheType() == URL_CACHE_DISK || GetCacheType() == URL_CACHE_TEMP )
{
#if defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_OPERATOR_CACHE_MANAGEMENT
if(url->GetAttribute(URL::KNeverFlush))
folder = OPFILE_OCACHE_FOLDER;
else
#endif
folder = OPFILE_CACHE_FOLDER;
}
else
folder = OPFILE_ABSOLUTE_FOLDER;
BOOL source_finished = source->GetFinished();
source->SetFinished();
if(filename.HasContent() || info.force_save)
{
OP_ASSERT(cache_content.GetLength() || filename.HasContent());
if(cache_content.GetLength())
RETURN_IF_ERROR(CheckFilename());
if(filename.HasContent())
{
OpFileFolder folder1 = OPFILE_ABSOLUTE_FOLDER;
OpStringC src_name(source->FileName(folder1));
if(src_name.HasContent())
{
#ifndef RAMCACHE_ONLY
OP_STATUS op_err = CopyCacheFile(src_name, folder1, NULL, OPFILE_ABSOLUTE_FOLDER, TRUE, FALSE, FILE_LENGTH_NONE);
if(OpStatus::IsError(op_err))
#endif
SetFinished();
}
if(cache_content.GetLength() != 0)
{
info.dual = TRUE;
if(Head::Empty())
{
info.dual = FALSE;
FlushMemory();
}
}
}
OP_DELETE(source);
}
if(source_finished)
SetFinished();
return OpStatus::OK;
}
OP_STATUS File_Storage::Construct(const OpStringC &file_name, FileName_Store *filenames, OpFileFolder afolder, OpFileLength file_len)
{
RETURN_IF_ERROR(filename.Set(file_name));
if(GetCacheType() == URL_CACHE_DISK || GetCacheType() == URL_CACHE_TEMP )
{
folder = afolder;
}
else
folder = OPFILE_ABSOLUTE_FOLDER;
info.completed = (filename.HasContent() ? TRUE : FALSE);
#if !defined(RAMCACHE_ONLY) && !defined(SEARCH_ENGINE_CACHE)
if(HasContentBeenSavedToDisk() && IsDiskContentAvailable())
{
if(!content_size)
content_size=file_len;
if(!content_size && filenames && filename.HasContent())
{
#ifndef CACHE_MULTIPLE_FOLDERS
FileNameElement *elm = filenames->RetrieveFileName(filename, NULL);
if(elm)
content_size = elm->GetFileSize();
// else
// return OpStatus::ERR_NO_MEMORY;
#endif
}
if(!content_size)
content_size = FileLength();
OP_NEW_DBG("File_Storage::Construct(OpStringC, FileName_Store, OpFileFolder, OpFileLength)", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - ctx id: %d - read_only: %d - dual: %d\n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, url->GetContextId(), read_only, info.dual));
OP_ASSERT(!IsRAMContentComplete());
AddToCacheUsage(url, FALSE, TRUE, TRUE);
#if defined STRICT_CACHE_LIMIT2
GetContextManager()->AddToPredictedCacheSize(content_size, url);
#endif
}
#endif // !RAMCACHE_ONLY && !SEARCH_ENGINE_CACHE
#ifdef SEARCH_ENGINE_CACHE
if(info.completed && (GetCacheType() == URL_CACHE_DISK || GetCacheType() == URL_CACHE_TEMP ))
{
OpFile temp_file;
BOOL exists;
if(OpStatus::IsSuccess(temp_file.Construct(filename, folder)))
{
temp_file.GetFileLength(content_size);
if(temp_file.Exists(exists) == OpStatus::OK)
if(exists)
SetCacheType(URL_CACHE_DISK);
}
}
#endif
return OpStatus::OK;
}
OP_STATUS File_Storage::CheckFilename()
{
if(filename.HasContent())
return OpStatus::OK;
OpString ext;
OP_STATUS op_err = OpStatus::OK;
TRAP(op_err, url->GetAttributeL(URL::KSuggestedFileNameExtension_L, ext));
if(OpStatus::IsSuccess(op_err))
{
BOOL session_only=!IsPersistent() || GetCacheType() == URL_CACHE_TEMP;
op_err = urlManager->GetNewFileNameCopy(filename, (ext.HasContent() ? ext.CStr() : UNI_L("tmp")), folder, session_only
#if defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_OPERATOR_CACHE_MANAGEMENT
, !!url->GetAttribute(URL::KNeverFlush)
#endif
, url->GetContextId());
// Fix a bug that when [Disk Cache]Cache Other==0 prevented session files from being deleted
if(session_only && GetCacheType()==URL_CACHE_DISK)
SetCacheType(URL_CACHE_TEMP);
OP_NEW_DBG("File_Storage::CheckFilename()", "cache.name");
OP_DBG((UNI_L("New cache file name:%s [%d] - Session only: %d - URL: %s\n"), filename.CStr(), GetFolder(), !IsPersistent() || GetCacheType() == URL_CACHE_TEMP, url->GetAttribute(URL::KUniName).CStr()));
}
if(OpStatus::IsMemoryError(op_err))
g_memory_manager->RaiseCondition(op_err);
OP_ASSERT(OpStatus::IsError(op_err) || filename.HasContent());
return op_err;
}
#ifdef UNUSED_CODE
File_Storage* File_Storage::Create(Cache_Storage *source, const OpStringC &target, URLCacheType ctyp, BOOL frc_save, BOOL kp_open_file)
{
File_Storage* fs = OP_NEW(File_Storage, (source, ctyp, frc_save, kp_open_file));
if(!fs)
return NULL;
if(OpStatus::IsError(fs->Construct(source, target)))
{
OP_DELETE(fs);
return NULL;
}
return fs;
}
#endif
#ifdef CACHE_FILE_STORAGE_CREATE
File_Storage* File_Storage::Create(URL_Rep *url_rep, const OpStringC &file_name, FileName_Store *filenames, OpFileFolder folder, URLCacheType ctyp, BOOL frc_save, BOOL kp_open_file)
{
File_Storage* fs = OP_NEW(File_Storage, (url_rep, ctyp, frc_save, kp_open_file));
if(!fs)
return NULL;
if(OpStatus::IsError(fs->Construct(file_name,filenames, folder)))
{
OP_DELETE(fs);
return NULL;
}
return fs;
}
#endif
void File_Storage::SetCacheType(URLCacheType ct)
{
#ifdef SEARCH_ENGINE_CACHE
if((folder == OPFILE_CACHE_FOLDER
#if defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_OPERATOR_CACHE_MANAGEMENT
|| folder == OPFILE_OCACHE_FOLDER
#endif
) && cachetype == URL_CACHE_DISK && ct != URL_CACHE_DISK)
{
urlManager->MakeFileTemporary(url);
}
#endif
cachetype = ct;
}
const OpStringC File_Storage::FileName(OpFileFolder &fldr, BOOL get_original_body) const
{
fldr = folder;
return filename;
}
void File_Storage::SetFinished(BOOL force)
{
OP_NEW_DBG("File_Storage::SetFinished()", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - read_only: %d - info.completed: %d ==> TRUE - IsDiskContentAvailable(): %d \n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, (UINT32) cache_content.GetLength(), url->GetContextId(), read_only, info.completed, IsDiskContentAvailable()));
if(cache_file)
{
OP_DELETE(cache_file);
cache_file = NULL;
if(file_count > 1)
{
OP_STATUS op_err = OpStatus::OK;
cache_file = OpenFile(OPFILE_READ, op_err);
if(OpStatus::IsError(op_err))
url->HandleError(GetFileError(op_err, url,UNI_L("write")));
}
DecFileCount();
}
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - read_only: %d - info.completed: %d - IsDiskContentAvailable(): %d \n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, (UINT32) cache_content.GetLength(), url->GetContextId(), read_only, info.completed, IsDiskContentAvailable()));
Cache_Storage::SetFinished();
#ifdef SUPPORT_RIM_MDS_CACHE_INFO
if( !info.completed )
urlManager->ReportCacheItem(url,TRUE);
#endif // SUPPORT_RIM_MDS_CACHE_INFO
info.completed = TRUE;
}
BOOL File_Storage::IsDiskContentAvailable()
{
return filename.HasContent()
#ifdef SEARCH_ENGINE_CACHE
&& !info.modified
#endif
&& (GetCacheType() == URL_CACHE_DISK || GetCacheType() == URL_CACHE_TEMP);
}
void File_Storage::UnsetFinished()
{
OP_NEW_DBG("File_Storage::UnsetFinished()", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - GetDiskContentComputed(): %d - read_only: %d - info.completed: %d ==> FALSE - IsDiskContentAvailable(): %d \n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, (UINT32) cache_content.GetLength(), url->GetContextId(), GetDiskContentComputed(), read_only, info.completed, IsDiskContentAvailable()));
Cache_Storage::UnsetFinished();
if(GetDiskContentComputed())
SubFromDiskOrOEMSize(0, url, FALSE); // Removes the estimated URL size
if(cache_file)
{
OpFileLength pos = 0;
// TODO: Multimedia: Read Pos
if(OpStatus::IsError(cache_file->GetFilePos(pos)))
pos = 0;
OP_DELETE(cache_file);
OP_STATUS op_err = OpStatus::OK;
cache_file = OpenFile((OpFileOpenMode) (OPFILE_APPEND| OPFILE_READ), op_err);
OpStatus::Ignore(op_err);
if(cache_file && pos)
cache_file->SetFilePos(pos);
}
info.completed = FALSE;
}
void File_Storage::ResetForLoading()
{
OP_NEW_DBG("File_Storage::ResetForLoading", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - read_only: %d - dual: %d\n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, cache_content.GetLength(), url->GetContextId(), read_only, info.dual));
Cache_Storage::ResetForLoading();
info.completed = FALSE;
}
void File_Storage::DecFileCount()
{
if(cache_file)
{
if(file_count > 0)
file_count --;
else
file_count = 0;
if(file_count==0 && cache_file)
{
OP_DELETE(cache_file);
cache_file = NULL;
}
}
else
file_count = 0;
}
OP_STATUS File_Storage::StoreData(const unsigned char *buffer, unsigned long buf_len, OpFileLength start_position)
{
if(!buffer)
{
OP_ASSERT(!buf_len);
return buf_len ? OpStatus::ERR_NULL_POINTER : OpStatus::OK;
}
if(GetFinished())
return OpStatus::OK;
OP_NEW_DBG("File_Storage::StoreData()", "cache.storage");
OP_DBG((UNI_L("URL: %s - %x - bytes stored: %d - URL points to me: %d - dual: %d - completed: %d\n"), url->GetAttribute(URL::KUniName).CStr(), url, buf_len, url->GetDataStorage() && url->GetDataStorage()->GetCacheStorage()==this, info.dual, info.completed));
#ifdef _DEBUG_DD1
OpFileLength temp_len = ContentLoaded();
#endif
urlManager->SetLRU_Item(url);
if(info.dual || !info.force_save)
{
RETURN_IF_ERROR(Cache_Storage::StoreData(buffer, buf_len));
#ifdef _DEBUG_DD1
PrintfTofile("urldd1.txt","\nFS Store Data- %s - Stored to memory ( %lu:%lu)\n",
DebugGetURLstring(url), buf_len, (unsigned long) ContentLoaded()
);
#endif
}
if((filename.HasContent()
#ifdef SEARCH_ENGINE_CACHE
&& !info.modified
#endif
) || info.force_save ||
(cache_content.GetLength() >= MIN_FORCE_DISK_STORAGE && !GetMemoryOnlyStorage()
#ifdef NEED_URL_CACHE_TRIPLE_LIMIT_FORCE_DISK
&& (Cardinal() == 0 || cache_content.GetLength() >= (3*MAX_MEMORY_CONTENT_SIZE)) // EPOC only: Don't force to disk, unless larger than 768KB
#endif
))
{
OP_MEMORY_VAR BOOL saved = FALSE;
if(filename.IsEmpty())
{
RETURN_IF_ERROR(CheckFilename());
if(cache_content.GetLength())
{
#ifndef RAMCACHE_ONLY
if(OpStatus::IsError(CopyCacheFile(NULL, OPFILE_ABSOLUTE_FOLDER, NULL, OPFILE_ABSOLUTE_FOLDER, TRUE, FALSE, start_position)))
#endif
SetFinished();
#ifdef _DEBUG_DD1
PrintfTofile("urldd1.txt","\nFS Store Data- %s - Saved to File (%lu)\n",
DebugGetURLstring(url), (unsigned long) ContentLoaded()
);
#endif
saved = TRUE;
info.dual = TRUE;
}
if(!info.dual && Cardinal() == 0 && !info.force_save)
{
#ifdef _DEBUG_DD1
PrintfTofile("urldd1.txt","\nFS Store Data- %s - Flushing Directly to File (%lu)\n",
DebugGetURLstring(url), (unsigned long) ContentLoaded()
);
#endif
FlushMemory();
info.force_save = TRUE;
}
}
BOOL orig_dual = info.dual;
if(info.dual && cache_content.GetLength() > MAX_MEMORY_CONTENT_SIZE)
{
#ifdef _DEBUG_DD1
PrintfTofile("urldd1.txt","\nFS Store Data- %s - Flushing to File %lu\n",
DebugGetURLstring(url), (unsigned long) ContentLoaded()
);
#endif
OP_NEW_DBG("File_Storage::StoreData - cache_content exceeded MAX_MEMORY_CONTENT_SIZE", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - read_only: %d - dual: %d ==> FALSE\n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, cache_content.GetLength(), url->GetContextId(), read_only, info.dual));
// If it's being flushed to disk we need to update the used cache size.
OP_ASSERT(IsDiskContentAvailable());
if(IsDiskContentAvailable())
AddToDiskOrOEMSize(cache_content.GetLength(), url, FALSE);
FlushMemory(TRUE);
info.dual = FALSE;
info.force_save = TRUE;
info.keep_open_file = TRUE;
}
if(!saved)
{
OP_STATUS op_err = OpStatus::OK;
if(!cache_file)
{
cache_file = OpenFile((OpFileOpenMode) (OPFILE_APPEND | OPFILE_READ), op_err);
if(cache_file)
file_count ++;
}
if(cache_file)
{
__DO_START_TIMING(TIMING_FILE_OPERATION);
// TODO: Multimedia: Where to get the position in the content? Pos?
if(start_position != FILE_LENGTH_NONE)
op_err=SetWritePosition(cache_file, start_position);
if(OpStatus::IsSuccess(op_err))
{
if(OpStatus::IsSuccess(op_err = cache_file->Write(buffer, buf_len)))
{
// if info.dual was set, the content is both kept on RAM and saved on the disk
if(!orig_dual && IsDiskContentAvailable())
AddToDiskOrOEMSize(buf_len, url, FALSE);
}
}
if(op_err == OpStatus::ERR_NOT_SUPPORTED) // We are trying to write content already saved...
{
// To simplify things, a successful operation is simulated, but NOTHING is written on disk
#ifdef SELFTEST
OP_ASSERT(bypass_asserts || (FALSE && "Operation not supported and probably wasted bandwidth"));
#endif
op_err=OpStatus::OK;
}
if(OpStatus::IsError(op_err))
{
__DO_STOP_TIMING(TIMING_FILE_OPERATION);
url->HandleError(GetFileError(op_err, url,UNI_L("write")));
OP_DELETE(cache_file);
cache_file = NULL;
SetFinished(TRUE); // Make sure it doesn't try to flush
return op_err;
}
// else cache_file->Flush();
#ifdef _DEBUG_DD1
PrintfTofile("urldd1.txt","\nFS Store Data- %s - Stored to file ( %lu:%lu)\n",
DebugGetURLstring(url), buf_len, (unsigned long) ContentLoaded()
);
#endif
if(!orig_dual && filename.IsEmpty())
{
content_size += buf_len;
stored_size -= buf_len; // Count only once
}
if(!info.keep_open_file)
{
DecFileCount();
}
__DO_ADD_TIMING_PROCESSED(TIMING_FILE_OPERATION,buf_len);
__DO_STOP_TIMING(TIMING_FILE_OPERATION);
}
}
}
#ifdef _DEBUG_DD1
PrintfTofile("urldd1.txt","\nFS Store Data- %s - Added content %lu:%lu (%lu)\n",
DebugGetURLstring(url), buf_len, (unsigned long) ContentLoaded(), temp_len+buf_len
);
//if(temp_len+buf_len != ContentLoaded())
// int test = 1;
#endif
return OpStatus::OK;
}
OpFileLength File_Storage::EstimateContentAvailable()
{
OpFileLength file_len=0;
if(OpStatus::IsSuccess(cache_file->GetFileLength(file_len)))
return file_len;
return 0;
}
unsigned long File_Storage::RetrieveData(URL_DataDescriptor *desc,BOOL &more)
{
OP_NEW_DBG("File_Storage::RetrieveData()", "cache.storage");
OP_DBG((UNI_L("URL: %s"), url->GetAttribute(URL::KUniName).CStr()));
#ifdef SELFTEST
num_disk_read++;
#endif
if(desc == NULL)
return 0;
//info.force_save = FALSE;
more = FALSE;
#ifdef CACHE_STATS
retrieved_from_disk=FALSE;
#endif // CACHE_STATS
urlManager->SetLRU_Item(url);
if(!info.dual && filename.HasContent()
#ifdef SEARCH_ENGINE_CACHE
&& !info.modified
#endif
)
{
Context_Manager *ctx=GetContextManager();
unsigned long ret;
OP_STATUS ops;
OP_ASSERT(ctx);
/// Retrieve from Containers, for example
if(ctx->BypassStorageRetrieveData(this, desc, more, ret, ops))
{
if(OpStatus::IsSuccess(ops)) // Retrieved
{
// FIXME: check if the file can be read in a single operation...
info.completed=TRUE; /// Warning: thread safe?
#ifdef CACHE_STATS
retrieved_from_disk=TRUE;
#endif
}
else // Not retrieved
{
#ifdef CACHE_STATS
retrieved_from_disk=FALSE;
#endif
if(filename.CStr())
filename.CStr()[0]=0;
}
OP_NEW_DBG("File_Storage::RetrieveData()", "cache.storage");
OP_DBG((UNI_L("(bypassed --> containers) URL: %s - more: %d from %s\n"), url->GetAttribute(URL::KUniName).CStr(), more, filename.CStr()));
return ret;
}
// Load the content from the file
if(!cache_file)
{
OP_STATUS op_err = OpStatus::OK;
cache_file = OpenFile(info.completed ? OPFILE_READ : (OpFileOpenMode) (OPFILE_APPEND | OPFILE_READ), op_err);
}
more = FALSE;
if(!cache_file)
{
OP_NEW_DBG("File_Storage::RetrieveData()", "cache.storage");
OP_DBG((UNI_L("URL: %s - File NOT opened!\n"), url->GetAttribute(URL::KUniName).CStr()));
return desc->GetBufSize();
}
if(!desc->GetUsingFile())
{
file_count ++;
desc->SetUsingFile(TRUE);
}
OpFileLength len_estimation = 0;
if(!content_size)
len_estimation=EstimateContentAvailable();
OP_MEMORY_VAR OpFileLength bread=desc->AddContentL(cache_file, content_size ? content_size : len_estimation, more);
if(!more)
{
// TODO: Multimedia: check if real EOF or if related to the segment
if(cache_file && !cache_file->Eof())
{
if(bread != 0 || (!GetFinished() && (URLStatus) url->GetAttribute(URL::KLoadStatus) == URL_LOADING))
more = TRUE;
if(!desc->PostedMessage() && (bread != 0 || (URLStatus) url->GetAttribute(URL::KLoadStatus) != URL_LOADING))
desc->PostMessage(MSG_URL_DATA_LOADED, url->GetID(), 0);
}
else if(!GetFinished() && (URLStatus) url->GetAttribute(URL::KLoadStatus) == URL_LOADING && desc->HasMessageHandler())
more = TRUE;
}
else if(!desc->PostedMessage())
desc->PostMessage(MSG_URL_DATA_LOADED, url->GetID(), 0);
OP_NEW_DBG("File_Storage::RetrieveData()", "cache.storage");
#if CACHE_CONTAINERS_ENTRIES>0
OP_DBG((UNI_L("URL: %s - more: %d from %s - Container id: %d - URL ID: %p - Position: %d - Descriptor address: %p - Bytes read: %d"), url->GetAttribute(URL::KUniName).CStr(), more, filename.CStr(), container_id, url->GetID(), (int)desc->GetPosition(), desc, (int)bread));
#else
OP_DBG((UNI_L("URL: %s - more: %d from %s - Container DISABLED - URL ID: %p - Position: %d - Descriptor address: %p - Bytes read: %d"), url->GetAttribute(URL::KUniName).CStr(), more, filename.CStr(), url->GetID(), (int)desc->GetPosition(), desc, (int)bread));
#endif
#ifdef DEBUGGING
DEBUG_CODE_BEGIN("cache.storage")
OpStringC8 mime=url->GetAttribute(URL::KMIME_Type);
OpString mime16;
URL moved_to = url->GetAttribute(URL::KMovedToURL, URL::KFollowRedirect);
mime16.Set(mime.CStr());
OP_DBG((UNI_L("MIME Type: %s - Moved to: %s"), mime16.CStr(), moved_to.GetAttribute(URL::KUniName).CStr()));
if(desc->GetBufSize()>=10)
OP_DBG((UNI_L("Buf size: %d - content: %d %d %d %d %d %d %d %d %d %d"), desc->GetBufSize(), desc->GetBuffer()[0], desc->GetBuffer()[1], desc->GetBuffer()[2], desc->GetBuffer()[3], desc->GetBuffer()[4], desc->GetBuffer()[5], desc->GetBuffer()[6], desc->GetBuffer()[7], desc->GetBuffer()[8], desc->GetBuffer()[9]));
DEBUG_CODE_END
#endif
#ifdef CACHE_STATS
retrieved_from_disk=TRUE;
#endif
#ifdef _DEBUG_DD1
PrintfTofile("urldd1.txt","\nFS Retrieve Data- %s - %u %s - %s - %s\n",
DebugGetURLstring(url),
desc->GetPosition(),
(url->GetAttribute(URL::KLoadStatus) == URL_LOADING ? "Not Loaded" : "Loaded"),
(GetFinished() ? "Finished" : "Not Finished"),
(desc->HasMessageHandler() ? "MH" : "not MH")
);
#endif
return desc->GetBufSize();
}
#ifdef _DEBUG_DD1
PrintfTofile("urldd1.txt","\nFS Retrieve Data- %s - from memory\n", DebugGetURLstring(url));
#endif
return Cache_Storage::RetrieveData(desc, more);
}
#ifdef CACHE_RESOURCE_USED
OpFileLength File_Storage::ResourcesUsed(ResourceID resource)
{
if(resource == MEMORY_RESOURCE)
return Cache_Storage::ResourcesUsed(resource);
return 0;
}
#endif
OpFileLength File_Storage::FileLength()
{
if(cache_file)
{
OpFileLength length;
// TODO: Multimedia: Real length? Content length? Segment length?
cache_file->GetFileLength(length);
return length;
}
if(filename.HasContent()
#ifdef SEARCH_ENGINE_CACHE
&& !info.modified
#endif
)
{
OpFileLength file_size = 0;
OpFile temp_file;
if(OpStatus::IsSuccess(temp_file.Construct(filename.CStr(), folder, OPFILE_FLAGS_NONE)))
{
temp_file.GetFileLength(file_size);
content_size = file_size;
}
}
return content_size;
}
BOOL File_Storage::DataPresent()
{
#if CACHE_CONTAINERS_ENTRIES>0
if(container_id)
// FIXME: cast is bad! Expose a function on Context_manager
return ((Context_Manager_Disk *)GetContextManager())->IsContainerPresent(this); // Container file deleted
#endif
if(!info.dual && filename.HasContent())
{
#if CACHE_CONTAINERS_ENTRIES>0
if(container_id != 0)
return TRUE;
#endif //CACHE_CONTAINERS_ENTRIES>0
BOOL exists = FALSE;
if(cache_file)
{
cache_file->Exists(exists);
return exists;
}
OpFile temp_file;
if(OpStatus::IsSuccess(temp_file.Construct(filename.CStr(), folder)))
temp_file.Exists(exists);
return exists;
}
return Cache_Storage::DataPresent();
}
void File_Storage::CloseFile()
{
OP_DELETE(cache_file);
cache_file = NULL;
file_count=0;
}
#ifdef URL_ENABLE_ASSOCIATED_FILES
OP_STATUS File_Storage::AssocFileName(OpString &fname, URL::AssociatedFileType type, OpFileFolder &folder_assoc, BOOL allow_storage_change)
{
int dot;
int bit;
if(allow_storage_change)
{
if(IsEmbedded())
RollBackEmbedding();
OP_ASSERT(!IsEmbedded());
#if (CACHE_SMALL_FILES_SIZE>0 || CACHE_CONTAINERS_ENTRIES>0)
if(!IsEmbedded() && !GetContainerID())
plain_file=TRUE; // URL with associated files are not supposed to join container or being embedded
#endif // (CACHE_SMALL_FILES_SIZE>0 || CACHE_CONTAINERS_ENTRIES>0)
if(!filename.HasContent() && GetCacheType() == URL_CACHE_DISK)
{
RETURN_IF_ERROR(Flush());
}
}
if(!filename.HasContent() || folder==OPFILE_ABSOLUTE_FOLDER) // Local file storage are special...
{
// Switch to temporary cache files
Context_Manager *man=GetContextManager();
OP_ASSERT(man);
if(man)
{
OpString *file_name;
RETURN_IF_ERROR(man->CreateTempAssociatedFileName(url, type, file_name, TRUE));
if(file_name)
{
fname.Set(file_name->CStr());
folder_assoc = man->GetCacheLocationForFiles();
return OpStatus::OK;
}
}
return OpStatus::ERR_NOT_SUPPORTED;
}
//#ifndef SEARCH_ENGINE_CACHE
// RETURN_IF_ERROR(fname.Set(filename));
// if((dot = fname.FindLastOf('.')) != -1)
// fname.Delete(dot);
//#else
RETURN_IF_ERROR(fname.Set("assoc"));
bit = 0;
while ((type & 1) == 0)
{
++bit;
type = (URL::AssociatedFileType)((UINT32)type >> 1);
}
// Filenames are like: "assoc000/g_0001/opr00001.000"
// Format: assocTT0/g_GGGG/oprXXXXX.CCC:
// TTT: Type of the associated file (AssociatedFileType: Thumbnail, CompiledECMAScript... maximum allowed: 12 types...)
// GGGG: cache generation (the same as the main cache file)
// XXXXX: cache file name (the same as the main cache file)
// CCC: container ID (this should be enough to cover containers with till 4K of URLs)
RETURN_IF_ERROR(fname.AppendFormat(UNI_L("%.03X%c%s"), bit, PATHSEPCHAR, filename.CStr()));
if((dot = fname.FindLastOf('.')) > 9) // 9 == "assocXXX/"
fname.Delete(dot);
RETURN_IF_ERROR(fname.AppendFormat(UNI_L(".%03X"), GetContainerID()));
//#endif
folder_assoc = folder;
return OpStatus::OK;
}
#endif // URL_ENABLE_ASSOCIATED_FILES
BOOL File_Storage::Flush()
{
OP_ASSERT(urlManager);
OP_ASSERT(url);
#ifdef CACHE_STATS
stats_flushed++;
#endif
if(!GetFinished())
return FALSE;
#if CACHE_SMALL_FILES_SIZE>0
// If possible, add it to the index
if(!plain_file && ManageEmbedding())
return TRUE;
#endif
if((filename.IsEmpty()
#ifdef SEARCH_ENGINE_CACHE
|| info.modified
#endif
) && !info.dual && info.completed && cache_content.GetLength() && !GetMemoryOnlyStorage())
{
Context_Manager *ctx=GetContextManager();
if(ctx && !ctx->BypassStorageFlush(this))
{
#ifdef SEARCH_ENGINE_CACHE
if(!info.modified)
RETURN_VALUE_IF_ERROR(CheckFilename(), FALSE);
else
info.modified = FALSE;
#else // SEARCH_ENGINE_CACHE
RETURN_VALUE_IF_ERROR(CheckFilename(), FALSE);
#endif // SEARCH_ENGINE_CACHE
// Will save it with the filename contained in this->filename
if(Cache_Storage::SaveToFile(NULL) != 0 )
return FALSE;
}
FlushMemory();
info.dual = FALSE;
info.force_save = TRUE; // FROM_EPOC
urlManager->SetLRU_Item(url);
return TRUE;
}
else if(cache_content.GetLength() && !GetMemoryOnlyStorage())
{
FlushMemory();
info.dual = FALSE;
urlManager->SetLRU_Item(url);
return TRUE;
}
// Return FALSE if we didn't do anything, unless we already have
// done something. Previously this returned TRUE but then the error
// was lost if neither of the previous branches were taken.
// lth / 2002-01-28 - peter / 2002-02-21
return filename.HasContent() ? TRUE : FALSE;
}
#if defined(_DEBUG) && defined(SEARCH_ENGINE_CACHE) && !defined(_NO_GLOBALS_)
#include "modules/cache/CacheIndex.h"
extern CacheIndex *g_disk_index;
#endif
BOOL File_Storage::Purge()
{
OP_NEW_DBG("File_Storage::Purge", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - read_only: %d - dual: %d - info.completed: %d - IsDiskContentAvailable(): %d \n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, cache_content.GetLength(), url->GetContextId(), read_only, info.dual, info.completed, IsDiskContentAvailable()));
OP_DELETE(cache_file);
cache_file = NULL;
#if defined(_DEBUG) && defined(SEARCH_ENGINE_CACHE) && !defined(_NO_GLOBALS_)
OpString tmp_storage;
const uni_char * dbg_cache_folder = g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_CACHE_FOLDER, tmp_storage);
if(g_disk_index != NULL && filename.HasContent() &&
uni_strncmp(filename, dbg_cache_folder, uni_strlen(dbg_cache_folder)) == 0 &&
BlockStorage::FileExists(filename, OPFILE_CACHE_FOLDER) == OpBoolean::IS_TRUE)
{
if(!g_disk_index->SearchFile(filename))
{
OpString8 ufname;
const char *cufname;
ufname.SetUTF8FromUTF16(filename);
cufname = ufname.CStr();
file = NULL;
}
}
#endif
if(cachetype != URL_CACHE_DISK && cachetype != URL_CACHE_USERFILE)
{
if(filename.HasContent())
{
if(GetCacheType() == URL_CACHE_TEMP)
SubFromCacheUsage(url, FALSE, IsDiskContentAvailable() && HasContentBeenSavedToDisk()); // Cache_Storage::Purge() only subtract the ram usage
#if CACHE_CONTAINERS_ENTRIES>0
if(!prevent_delete) // Delete the file, unless it is in a container already deleted
#endif
{
OpFile f;
if(OpStatus::IsSuccess(f.Construct(filename.CStr(), folder)))
{
#if defined(_DEBUG) && defined(SEARCH_ENGINE_CACHE) && !defined(_NO_GLOBALS_)
if(g_disk_index != NULL && folder == OPFILE_CACHE_FOLDER)
{
OP_ASSERT(!g_disk_index->SearchFile(filename));
}
#endif
// Containers (or future special cases) marked for delete
Context_Manager *ctx=GetContextManager();
if(!ctx->BypassStorageTruncateAndReset(this))
{
#if defined(_DEBUG) && CACHE_CONTAINERS_ENTRIES>0
OP_NEW_DBG("File_Storage::Purge", "cache.del");
if(container_id)
OP_DBG((UNI_L("*** Cache File cont id %d in %s deleted directly (strange... it should not happen...)"), container_id, filename.CStr() ));
#endif
#if defined(USE_ASYNC_FILEMAN) && defined(UTIL_ASYNC_FILE_OP)
f.DeleteAsync();
#else
f.Delete(FALSE);
#endif
}
#ifdef SUPPORT_RIM_MDS_CACHE_INFO
urlManager->ReportCacheItem(url,FALSE);
#endif // SUPPORT_RIM_MDS_CACHE_INFO
}
}
#ifdef URL_ENABLE_ASSOCIATED_FILES
if(purge_assoc_files) // // Delete associated files
OpStatus::Ignore(PurgeAssociatedFiles(TRUE));
#endif // URL_ENABLE_ASSOCIATED_FILES
}
#ifdef URL_ENABLE_ASSOCIATED_FILES
else // No file name: only temporary associated files are possible
{
if(purge_assoc_files) // // Delete associated files
OpStatus::Ignore(PurgeTemporaryAssociatedFiles());
}
#endif // URL_ENABLE_ASSOCIATED_FILES
}
else
{
SubFromCacheUsage(url, FALSE, IsDiskContentAvailable() && HasContentBeenSavedToDisk()); // Cache_Storage::Purge() only subtract the ram usage
Flush();
#ifdef URL_ENABLE_ASSOCIATED_FILES
if(purge_assoc_files) // // Delete associated files
OpStatus::Ignore(PurgeTemporaryAssociatedFiles());
#endif // URL_ENABLE_ASSOCIATED_FILES
}
#if defined(_DEBUG) && defined(SEARCH_ENGINE_CACHE) && !defined(_NO_GLOBALS_)
// disabled because it would also trigger on any CreateNewCache or whatever the method is called
/*
OpString tmp_storage;
const uni_char * dbg_cache_folder = g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_CACHE_FOLDER, tmp_storage);
if(g_disk_index != NULL && filename.HasContent() &&
uni_strncmp(filename, dbg_cache_folder, uni_strlen(dbg_cache_folder)) == 0 &&
BlockStorage::FileExists(filename, OPFILE_CACHE_FOLDER) == OpBoolean::IS_TRUE)
{
OP_ASSERT(g_disk_index->SearchFile(filename));
}*/
#endif
filename.Empty();
// WOFF fonts (that use associated files) can detach the cache storage from the cache, with the result that
// FlushMemory() does not execute because it checks that the storage is inside a list.
// Probably other operations, like view source, can end-up in the same situation.
// In this case VerifyURLSizeNotCounted() cannot be called to verify the imbalance, as it is imbalanced by definition.
if(Cache_Storage::Purge())
{
#ifdef SELFTEST
Cache_Storage *cs=(url && url->GetDataStorage() && url->GetDataStorage()->GetCacheStorage()) ? url->GetDataStorage()->GetCacheStorage() : NULL;
// In some cases, for example during Download_Storage::SetFinished(), a temporary cache storage is deleted,
// and this check is not valid, as the URL has already been associated to a different storage
if(!cs || cs==this)
GetContextManager()->VerifyURLSizeNotCounted(url, TRUE, TRUE);
#endif // SELFTEST
}
OP_ASSERT(stored_size == 0);
return TRUE;
}
#ifdef URL_ENABLE_ASSOCIATED_FILES
OP_STATUS File_Storage::PurgeAssociatedFiles(BOOL also_temporary)
{
UINT32 i;
OpString afname;
OpFile f;
OP_STATUS ops=OpStatus::OK;
OP_STATUS ops_t=OpStatus::OK;
for (i = 1; i != 0; i <<= 1)
{
if(OpStatus::IsSuccess(ops) && !OpStatus::IsSuccess(ops_t))
ops=ops_t;
ops_t=OpStatus::OK;
if(i & purge_assoc_files) // Select only the files to purge
{
OpFileFolder folder_assoc;
if(!OpStatus::IsSuccess(ops_t=AssocFileName(afname, (URL::AssociatedFileType)i, folder_assoc, FALSE)))
continue;
if(OpStatus::IsSuccess(ops_t=f.Construct(afname, folder_assoc)))
{
OP_NEW_DBG("File_Storage::Purge", "cache.del");
OP_DBG((UNI_L("*** Cache Associated File %s deleted"), afname.CStr() ));
#if defined(USE_ASYNC_FILEMAN) && defined(UTIL_ASYNC_FILE_OP)
f.DeleteAsync();
#else
f.Delete(FALSE);
#endif
#ifdef SUPPORT_RIM_MDS_CACHE_INFO
urlManager->ReportCacheItem(url,FALSE);
#endif // SUPPORT_RIM_MDS_CACHE_INFO
}
}
}
if(also_temporary)
ops_t=PurgeTemporaryAssociatedFiles();
if(OpStatus::IsSuccess(ops) && !OpStatus::IsSuccess(ops_t))
ops=ops_t;
return ops;
}
OP_STATUS File_Storage::PurgeTemporaryAssociatedFiles()
{
if(!purge_assoc_files)
return OpStatus::OK;
UINT32 i;
OpString afname;
OpFile f;
OP_STATUS ops=OpStatus::OK;
OP_STATUS ops_t=OpStatus::OK;
Context_Manager *man=GetContextManager();
OP_ASSERT(man);
if(!man)
return OpStatus::ERR_NULL_POINTER;
OpFileFolder folder_assoc = man->GetCacheLocationForFiles();
for (i = 1; i != 0; i <<= 1)
{
if(OpStatus::IsSuccess(ops) && !OpStatus::IsSuccess(ops_t))
ops=ops_t;
if(i & purge_assoc_files) // Select only the files to purge
{
OpString *name=man->GetTempAssociatedFileName(url, (URL::AssociatedFileType)i);
if(name) // Temporary file actually existing
{
OpFile f;
if(OpStatus::IsSuccess(ops_t=f.Construct(name->CStr(), folder_assoc)))
{
#if defined(USE_ASYNC_FILEMAN) && defined(UTIL_ASYNC_FILE_OP)
f.DeleteAsync();
#else
f.Delete(FALSE);
#endif
#ifdef SUPPORT_RIM_MDS_CACHE_INFO
urlManager->ReportCacheItem(url,FALSE);
#endif // SUPPORT_RIM_MDS_CACHE_INFO
}
}
}
}
return ops;
}
#endif // URL_ENABLE_ASSOCIATED_FILES
void File_Storage::TruncateAndReset()
{
OP_NEW_DBG("File_Storage::TruncateAndReset", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - read_only: %d - dual: %d - completed: %d\n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, cache_content.GetLength(), url->GetContextId(), read_only, info.dual, info.completed));
OP_DELETE(cache_file);
cache_file = NULL;
if(filename.HasContent())
{
if(GetCacheType() == URL_CACHE_DISK || GetCacheType() == URL_CACHE_TEMP)
{
//PrintfTofile("cs.txt", "[%s]\tpurge\t%d\t", filename, info.unsetsize);
if(!content_size)
content_size = FileLength();
}
Context_Manager *ctx=GetContextManager();
if(!ctx->BypassStorageTruncateAndReset(this))
{
OpFile f;
if(OpStatus::IsSuccess(f.Construct(filename.CStr(), folder) ))
{
OP_NEW_DBG("File_Storage::TruncateAndReset()", "cache.del");
OP_DBG((UNI_L("*** Cache File %s deleted - Folder id: %d - Context id: %d"), filename.CStr(), folder, Url()->GetContextId() ));
f.Delete(FALSE);
#ifdef SUPPORT_RIM_MDS_CACHE_INFO
urlManager->ReportCacheItem(url,FALSE);
#endif // SUPPORT_RIM_MDS_CACHE_INFO
}
}
}
Cache_Storage::TruncateAndReset();
ResetForLoading();
content_size = 0;
OP_ASSERT(stored_size==0);
stored_size = 0;
}
OpFileLength File_Storage::ContentLoaded(BOOL force /*=FALSE*/)
{
if(!force && (info.dual || filename.IsEmpty() || content_size))
{
if(content_size && !info.dual)
return content_size;
else
return cache_content.GetLength();
}
else
return FileLength();
}
void File_Storage::SetMemoryOnlyStorage(BOOL flag)
{
info.memory_only_storage = (flag ? TRUE : FALSE);
}
BOOL File_Storage::GetMemoryOnlyStorage()
{
return (BOOL) info.memory_only_storage;
}
/*
BOOL File_Storage::CacheFile()
{
// true if this is a part of the cache ; Default FALSE
return FALSE;
}
BOOL File_Storage::Persistent()
{
// Only used by cache files. True if it is to be preserved for the next session; DEFAULT TRUE
return TRUE;
}
*/
#ifdef _OPERA_DEBUG_DOC_
void File_Storage::GetMemUsed(DebugUrlMemory &debug)
{
debug.memory_loaded += sizeof(*this) - sizeof(Cache_Storage);
debug.memory_loaded += UNICODE_SIZE(filename.Length()+1);
Cache_Storage::GetMemUsed(debug);
}
#endif
#ifdef CACHE_FAST_INDEX
SimpleStreamReader *File_Storage::CreateStreamReader()
{
SimpleStreamReader *reader=Cache_Storage::CreateStreamReader();
if(NULL!=reader)
return reader;
// StreamBuffer from the file
SimpleFileReader *sfr=OP_NEW(SimpleFileReader, ());
if(!sfr)
return NULL;
if(OpStatus::IsError(sfr->Construct(filename.CStr(), folder)))
{
OP_DELETE(sfr);
return NULL;
}
#if CACHE_CONTAINERS_ENTRIES>0
if(container_id)
{
// TODO: It would be very nice to instruct the stream to give an error after the known size (size)
// Get the beginning of the file
UINT32 ch=sfr->Read8();
if(ch==CACHE_CONTAINERS_BYTE_SIGN) // Opera container file: reads the header
{
UINT32 num=sfr->Read8(); // Number of containers
UINT32 offset=0;
#ifdef DEBUG_ENABLE_OPASSERT
UINT32 size=0;
#endif
BOOL found=FALSE;
for(UINT32 i=0; i<num; i++) // Read the entries
{
UINT32 cnt_id=sfr->Read8();
UINT32 cnt_size=sfr->Read16();
if(cnt_id==container_id)
{
OP_ASSERT(!size);
found=TRUE;
#ifdef DEBUG_ENABLE_OPASSERT
size=cnt_size;
#endif
}
else if(!found)
offset+=cnt_size;
}
if(!offset || OpStatus::IsSuccess(sfr->Skip(offset))) // Position the stream on the correct point
return sfr;
}
OP_DELETE(sfr);
return NULL;
}
#endif
return sfr;
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.