text
stringlengths 8
6.88M
|
|---|
#include <iostream>
using namespace std;
int findfirstoccurence(int arr[],int n,int x);
int findlastoccurence(int arr[],int n,int x);
int main() {
//code
int T;
int n,x;
cin>>T;
for(int i=0;i<T;i++){
cin>>n>>x;
int arr[n];
for(int j=0;j<n;j++){
cin>>arr[j];
}
if(findfirstoccurence(arr,n,x)==-1)
{
cout<<findfirstoccurence(arr,n,x)<<endl;
}
else{
cout<<findfirstoccurence(arr,n,x)<<" ";
cout<<findlastoccurence(arr,n,x)<<endl;
}
}
return 0;
}
int findfirstoccurence(int arr[],int n,int x){
int l=0,h=n-1,m;
while(l<=h){
m=l+(h-l)/2;
if(arr[m]<x){
l=m+1;
}
else if(arr[m]>x){
h=m-1;
}
else{
if(m>0){
if(arr[m]==arr[m-1]){
h=m-1;
}
else{
return m;
}
}
else{
return 0;
}
}
}
return -1;
}
int findlastoccurence(int arr[],int n,int x){
int l=0,h=n-1,m;
while(l<=h){
m=l+(h-l)/2;
if(arr[m]<x){
l=m+1;
}
else if(arr[m]>x){
h=m-1;
}
else{
if(m==n-1){
return m;
}
else{
if(arr[m]==arr[m+1]){
l=m+1;
}
else{
return m;
}
}
}
}
return -1;
}
|
//
// Created by griha on 09.12.17.
//
#include "misc/logger.hpp"
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include "misc/filesystem.hpp"
namespace griha { namespace hsm {
namespace log = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
namespace trivial = boost::log::trivial;
const size_t MAX_LINE = 255;
struct StandardLog::Impl {
src::severity_logger< trivial::severity_level > lg;
Impl(const std::string &name, bool debug) {
log::add_file_log(
keywords::file_name = "hsm_remote_%4N.log",
keywords::rotation_size = 10 * 1024 * 1024, // 10 MByte
keywords::target = from_wstr(get_executable_path() + L"\\logs"),
keywords::max_files = 10,
keywords::scan_method = sinks::file::scan_matching,
keywords::auto_flush = true,
keywords::open_mode = std::ios_base::app | std::ios_base::out,
keywords::format = "[%TimeStamp%]: %Message%"
);
log::add_common_attributes();
}
void debug(bool value) {
}
void write(LogType type, const std::string &str) {
switch (type) {
case LogType::Information:
BOOST_LOG_SEV(lg, trivial::info) << str;
break;
case LogType::Warning:
BOOST_LOG_SEV(lg, trivial::warning) << "(warning) " << str;
break;
case LogType::Error:
BOOST_LOG_SEV(lg, trivial::error) << "(error) " << str;
break;
case LogType::Critical:
BOOST_LOG_SEV(lg, trivial::fatal) << "(fatal) " << str;
break;
case LogType::Debug:
BOOST_LOG_SEV(lg, trivial::debug) << "(debug) " << str;
break;
}
}
};
StandardLog::StandardLog( const std::string& name, bool debug )
: _pimpl( new StandardLog::Impl( name, debug ) ), _debug( debug ) {
}
StandardLog::~StandardLog() {
delete _pimpl;
}
void StandardLog::write( LogType type, const std::string& str ) {
_pimpl->write(type, str);
}
void StandardLog::debug( bool value ) {
_pimpl->debug(value);
_debug = value;
}
}} // namespace griha::hsm
|
// Created on: 1993-05-14
// Created by: Bruno DUMORTIER
// 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 _GeomAdaptor_Surface_HeaderFile
#define _GeomAdaptor_Surface_HeaderFile
#include <Adaptor3d_Surface.hxx>
#include <BSplSLib_Cache.hxx>
#include <GeomAbs_Shape.hxx>
#include <GeomEvaluator_Surface.hxx>
#include <Geom_Surface.hxx>
#include <Standard_NullObject.hxx>
#include <TColStd_Array1OfReal.hxx>
DEFINE_STANDARD_HANDLE(GeomAdaptor_Surface, Adaptor3d_Surface)
//! An interface between the services provided by any
//! surface from the package Geom and those required
//! of the surface by algorithms which use it.
//! Creation of the loaded surface the surface is C1 by piece
//!
//! Polynomial coefficients of BSpline surfaces used for their evaluation are
//! cached for better performance. Therefore these evaluations are not
//! thread-safe and parallel evaluations need to be prevented.
class GeomAdaptor_Surface : public Adaptor3d_Surface
{
DEFINE_STANDARD_RTTIEXT(GeomAdaptor_Surface, Adaptor3d_Surface)
public:
GeomAdaptor_Surface()
: myUFirst(0.), myULast(0.),
myVFirst(0.), myVLast (0.),
myTolU(0.), myTolV(0.),
mySurfaceType (GeomAbs_OtherSurface) {}
GeomAdaptor_Surface(const Handle(Geom_Surface)& theSurf)
: myTolU(0.), myTolV(0.)
{
Load (theSurf);
}
//! Standard_ConstructionError is raised if UFirst>ULast or VFirst>VLast
GeomAdaptor_Surface (const Handle(Geom_Surface)& theSurf,
const Standard_Real theUFirst, const Standard_Real theULast,
const Standard_Real theVFirst, const Standard_Real theVLast,
const Standard_Real theTolU = 0.0, const Standard_Real theTolV = 0.0)
{
Load (theSurf, theUFirst, theULast, theVFirst, theVLast, theTolU, theTolV);
}
//! Shallow copy of adaptor
Standard_EXPORT virtual Handle(Adaptor3d_Surface) ShallowCopy() const Standard_OVERRIDE;
void Load (const Handle(Geom_Surface)& theSurf)
{
if (theSurf.IsNull()) { throw Standard_NullObject("GeomAdaptor_Surface::Load"); }
Standard_Real aU1, aU2, aV1, aV2;
theSurf->Bounds (aU1, aU2, aV1, aV2);
load (theSurf, aU1, aU2, aV1, aV2);
}
//! Standard_ConstructionError is raised if theUFirst>theULast or theVFirst>theVLast
void Load (const Handle(Geom_Surface)& theSurf,
const Standard_Real theUFirst, const Standard_Real theULast,
const Standard_Real theVFirst, const Standard_Real theVLast,
const Standard_Real theTolU = 0.0, const Standard_Real theTolV = 0.0)
{
if (theSurf.IsNull()) { throw Standard_NullObject("GeomAdaptor_Surface::Load"); }
if (theUFirst > theULast || theVFirst > theVLast) { throw Standard_ConstructionError("GeomAdaptor_Surface::Load"); }
load (theSurf, theUFirst, theULast, theVFirst, theVLast, theTolU, theTolV);
}
const Handle(Geom_Surface)& Surface() const { return mySurface; }
virtual Standard_Real FirstUParameter() const Standard_OVERRIDE { return myUFirst; }
virtual Standard_Real LastUParameter() const Standard_OVERRIDE { return myULast; }
virtual Standard_Real FirstVParameter() const Standard_OVERRIDE { return myVFirst; }
virtual Standard_Real LastVParameter() const Standard_OVERRIDE { return myVLast; }
Standard_EXPORT GeomAbs_Shape UContinuity() const Standard_OVERRIDE;
Standard_EXPORT GeomAbs_Shape VContinuity() const Standard_OVERRIDE;
//! Returns the number of U intervals for continuity
//! <S>. May be one if UContinuity(me) >= <S>
Standard_EXPORT Standard_Integer NbUIntervals (const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Returns the number of V intervals for continuity
//! <S>. May be one if VContinuity(me) >= <S>
Standard_EXPORT Standard_Integer NbVIntervals (const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Returns the intervals with the requested continuity
//! in the U direction.
Standard_EXPORT void UIntervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Returns the intervals with the requested continuity
//! in the V direction.
Standard_EXPORT void VIntervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Returns a surface trimmed in the U direction
//! equivalent of <me> between
//! parameters <First> and <Last>. <Tol> is used to
//! test for 3d points confusion.
//! If <First> >= <Last>
Standard_EXPORT Handle(Adaptor3d_Surface) UTrim (const Standard_Real First, const Standard_Real Last, const Standard_Real Tol) const Standard_OVERRIDE;
//! Returns a surface trimmed in the V direction between
//! parameters <First> and <Last>. <Tol> is used to
//! test for 3d points confusion.
//! If <First> >= <Last>
Standard_EXPORT Handle(Adaptor3d_Surface) VTrim (const Standard_Real First, const Standard_Real Last, const Standard_Real Tol) const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsUClosed() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsVClosed() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsUPeriodic() const Standard_OVERRIDE;
Standard_EXPORT Standard_Real UPeriod() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsVPeriodic() const Standard_OVERRIDE;
Standard_EXPORT Standard_Real VPeriod() const Standard_OVERRIDE;
//! Computes the point of parameters U,V on the surface.
Standard_EXPORT gp_Pnt Value (const Standard_Real U, const Standard_Real V) const Standard_OVERRIDE;
//! Computes the point of parameters U,V on the surface.
Standard_EXPORT void D0 (const Standard_Real U, const Standard_Real V, gp_Pnt& P) const Standard_OVERRIDE;
//! Computes the point and the first derivatives on
//! the surface.
//!
//! Warning : On the specific case of BSplineSurface:
//! if the surface is cut in interval of continuity at least C1,
//! the derivatives are computed on the current interval.
//! else the derivatives are computed on the basis surface.
Standard_EXPORT void D1 (const Standard_Real U, const Standard_Real V, gp_Pnt& P, gp_Vec& D1U, gp_Vec& D1V) const Standard_OVERRIDE;
//! Computes the point, the first and second
//! derivatives on the surface.
//!
//! Warning : On the specific case of BSplineSurface:
//! if the surface is cut in interval of continuity at least C2,
//! the derivatives are computed on the current interval.
//! else the derivatives are computed on the basis surface.
Standard_EXPORT void D2 (const Standard_Real U, const Standard_Real V, gp_Pnt& P, gp_Vec& D1U, gp_Vec& D1V, gp_Vec& D2U, gp_Vec& D2V, gp_Vec& D2UV) const Standard_OVERRIDE;
//! Computes the point, the first, second and third
//! derivatives on the surface.
//!
//! Warning : On the specific case of BSplineSurface:
//! if the surface is cut in interval of continuity at least C3,
//! the derivatives are computed on the current interval.
//! else the derivatives are computed on the basis surface.
Standard_EXPORT void D3 (const Standard_Real U, const Standard_Real V, gp_Pnt& P, gp_Vec& D1U, gp_Vec& D1V, gp_Vec& D2U, gp_Vec& D2V, gp_Vec& D2UV, gp_Vec& D3U, gp_Vec& D3V, gp_Vec& D3UUV, gp_Vec& D3UVV) const Standard_OVERRIDE;
//! Computes the derivative of order Nu in the
//! direction U and Nv in the direction V at the point P(U, V).
//!
//! Warning : On the specific case of BSplineSurface:
//! if the surface is cut in interval of continuity CN,
//! the derivatives are computed on the current interval.
//! else the derivatives are computed on the basis surface.
//! Raised if Nu + Nv < 1 or Nu < 0 or Nv < 0.
Standard_EXPORT gp_Vec DN (const Standard_Real U, const Standard_Real V, const Standard_Integer Nu, const Standard_Integer Nv) const Standard_OVERRIDE;
//! Returns the parametric U resolution corresponding
//! to the real space resolution <R3d>.
Standard_EXPORT Standard_Real UResolution (const Standard_Real R3d) const Standard_OVERRIDE;
//! Returns the parametric V resolution corresponding
//! to the real space resolution <R3d>.
Standard_EXPORT Standard_Real VResolution (const Standard_Real R3d) const Standard_OVERRIDE;
//! Returns the type of the surface : Plane, Cylinder,
//! Cone, Sphere, Torus, BezierSurface,
//! BSplineSurface, SurfaceOfRevolution,
//! SurfaceOfExtrusion, OtherSurface
virtual GeomAbs_SurfaceType GetType() const Standard_OVERRIDE { return mySurfaceType; }
Standard_EXPORT gp_Pln Plane() const Standard_OVERRIDE;
Standard_EXPORT gp_Cylinder Cylinder() const Standard_OVERRIDE;
Standard_EXPORT gp_Cone Cone() const Standard_OVERRIDE;
Standard_EXPORT gp_Sphere Sphere() const Standard_OVERRIDE;
Standard_EXPORT gp_Torus Torus() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer UDegree() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbUPoles() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer VDegree() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbVPoles() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbUKnots() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbVKnots() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsURational() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsVRational() const Standard_OVERRIDE;
//! This will NOT make a copy of the
//! Bezier Surface : If you want to modify
//! the Surface please make a copy yourself
//! Also it will NOT trim the surface to
//! myU/VFirst/Last.
Standard_EXPORT Handle(Geom_BezierSurface) Bezier() const Standard_OVERRIDE;
//! This will NOT make a copy of the
//! BSpline Surface : If you want to modify
//! the Surface please make a copy yourself
//! Also it will NOT trim the surface to
//! myU/VFirst/Last.
Standard_EXPORT Handle(Geom_BSplineSurface) BSpline() const Standard_OVERRIDE;
Standard_EXPORT gp_Ax1 AxeOfRevolution() const Standard_OVERRIDE;
Standard_EXPORT gp_Dir Direction() const Standard_OVERRIDE;
Standard_EXPORT Handle(Adaptor3d_Curve) BasisCurve() const Standard_OVERRIDE;
Standard_EXPORT Handle(Adaptor3d_Surface) BasisSurface() const Standard_OVERRIDE;
Standard_EXPORT Standard_Real OffsetValue() const Standard_OVERRIDE;
private:
Standard_EXPORT void Span (const Standard_Integer Side, const Standard_Integer Ideb, const Standard_Integer Ifin, Standard_Integer& OutIdeb, Standard_Integer& OutIfin, const Standard_Integer FKIndx, const Standard_Integer LKIndx) const;
Standard_EXPORT Standard_Boolean IfUVBound (const Standard_Real U, const Standard_Real V, Standard_Integer& Ideb, Standard_Integer& Ifin, Standard_Integer& IVdeb, Standard_Integer& IVfin, const Standard_Integer USide, const Standard_Integer VSide) const;
Standard_EXPORT void load (const Handle(Geom_Surface)& S, const Standard_Real UFirst, const Standard_Real ULast, const Standard_Real VFirst, const Standard_Real VLast, const Standard_Real TolU = 0.0, const Standard_Real TolV = 0.0);
//! Rebuilds B-spline cache
//! \param theU first parameter to identify the span for caching
//! \param theV second parameter to identify the span for caching
Standard_EXPORT void RebuildCache (const Standard_Real theU, const Standard_Real theV) const;
protected:
Handle(Geom_Surface) mySurface;
Standard_Real myUFirst;
Standard_Real myULast;
Standard_Real myVFirst;
Standard_Real myVLast;
Standard_Real myTolU;
Standard_Real myTolV;
Handle(Geom_BSplineSurface) myBSplineSurface; ///< B-spline representation to prevent downcasts
mutable Handle(BSplSLib_Cache) mySurfaceCache; ///< Cached data for B-spline or Bezier surface
GeomAbs_SurfaceType mySurfaceType;
Handle(GeomEvaluator_Surface) myNestedEvaluator; ///< Calculates values of nested complex surfaces (offset surface, surface of extrusion or revolution)
};
#endif // _GeomAdaptor_Surface_HeaderFile
|
//============================================================================
// Name : Writer.h
// Author : kdjie
// Version : 1.0
// Copyright : @2015
// Description : 14166097@qq.com
//============================================================================
#pragma once
#include "EVComm.h"
namespace evwork
{
class CWriter
: public IWriter
{
public:
CWriter();
virtual ~CWriter();
virtual void send(const std::string& strIp, uint16_t uPort, const char* pData, size_t uSize);
virtual void flush() {}
};
}
|
//By SCJ
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define maxn 1005
struct P{
int t,x,y;
}p[maxn];
int n,my[maxn];
vector<int> G[maxn];
bool used[maxn];
bool dfs(int v)
{
for(int u:G[v])
{
if(used[u]) continue;
used[u]=1;
if(my[u]==-1||dfs(my[u]))
{
my[u]=v;return true;
}
}
return false;
}
int max_match()
{
memset(my,-1,sizeof(my));
int res=0;
for(int i=1;i<=n;++i)
{
memset(used,0,sizeof(used));
if(dfs(i)) res++;
}
return res;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int T;cin>>T;
while(T--)
{
cin>>n;
for(int i=0;i<maxn;++i) G[i].clear();
for(int i=1;i<=n;++i)
cin>>p[i].t>>p[i].x>>p[i].y;
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
if(i!=j&&abs(p[i].x-p[j].x)+abs(p[i].y-p[j].y)+p[i].t<=p[j].t) G[i].push_back(j);
cout<<n-max_match()<<endl;
}
}
|
#include "Map.h"
Map::Map()
{
}
Map::~Map()
{
}
void Map::addSnake(Snake snk)
{
snakes.push_back(snk);
}
void Map::addApple(Apple apl)
{
std::cout<<"adding apl"<<std::endl;
apples.push_back(apl);
}
void Map::refreshMap()
{
for(int i = 0; i < (int)snakes.size(); i++)
{
snakes[i].move();
}
for(int i = 0; i < (int)apples.size(); i++)
{
int eat = whoEatApple(apples[i]);
if(eat != -1)
{
snakes[eat].grow();
}
}
drawMap();
}
int Map::whoEatApple(Apple& apl)
{
for(int i = 0; i < (int)snakes.size(); i++)
{
if(snakes[i].getHead() == apl.getCoordinates())
{
return i;
}
}
return -1;
}
void Map::refreshApple(Apple& apl, std::pair<int, int> cor)
{
apl.setCoordinates(cor);
}
Apple& Map::getApple(int index)
{
return apples[index];
}
Snake& Map::getSnake(int index)
{
return snakes[index];
}
void Map::clearScreen()
{
#if defined _WIN32
system("cls");
//clrscr(); // including header file : conio.h
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
system("clear");
//std::cout<< u8"\033[2J\033[1;1H"; //Using ANSI Escape Sequences
#elif defined (__APPLE__)
system("clear");
#endif
}
void Map::drawMap()
{
for (size_t y = 0; y < MAP_SIZE; y++)
{
for (size_t x = 0; x < MAP_SIZE; x++)
{
map[x][y] = BACKGROUND_CHAR;
}
}
for (size_t i = 0; i < (size_t)snakes.size(); i++)
{
for (size_t j = 0; j < (size_t)snakes[i].getSize(); j++)
{
std::pair<int, int> piece = snakes[i].getPiece(j);
map[piece.first][piece.second] = SNAKE_CHAR;
}
}
for (size_t i = 0; i < (size_t)apples.size(); i++)
{
std::pair<int, int> appCor = apples[i].getCoordinates();
map[appCor.first][appCor.second] = APPLE_CHAR;
}
//-------------------------------------------------------------------
//clearScreen();
for (size_t i = 0; i < MAP_SIZE + 2; i++)
{
std::cout<<"-";
}
std::cout<<"\n";
for (size_t y = 0; y < MAP_SIZE; y++)
{
std::cout<<"|";
for (size_t x = 0; x < MAP_SIZE; x++)
{
std::cout<<map[x][y];
}
std::cout<<"|\n";
}
for (size_t i = 0; i < MAP_SIZE + 2; i++)
{
std::cout<<"-";
}
std::cout<<"\n";
}
|
//
// BitStream.h
// superasteroids
//
// Created by Cristian Marastoni on 31/05/14.
//
//
#pragma once
#include <string.h>
#include "NetTypes.h"
#include <string>
class BitStream {
public:
BitStream();
BitStream(uint8 *data, size_t size, bool read=false);
BitStream(const uint8 *data, size_t size);
virtual ~BitStream();
const uint8 *buffer() const;
const uint8 *read_ptr() const;
uint32 size() const;
void seek(int32 nbits) const;
void skip(uint32 nbits) const;
void skip_bytes(uint32 nbytes) const;
uint32 bitpos() const;
uint32 bytepos() const;
uint32 remaining_bytes() const;
bool eof() const;
void flush();
void setData(uint8 *data, size_t size);
void setData(uint8 const *data, size_t size);
void subStream(uint32 bitPos, uint32 size, BitStream &out) const;
void copyData(uint32 bytePos, uint32 size, void *out) const;
BitStream &pack_s8(char data);
BitStream &pack_s16(int16 data);
BitStream &pack_s32(int32 data);
BitStream &pack8(uint8 data);
BitStream &pack16(uint16 data);
BitStream &pack32(uint32 data);
BitStream &pack64(uint64 data);
BitStream &packFloat(float data);
BitStream &packString(const char *str);
BitStream &packString(std::string const &str);
BitStream &packData(void const *data, size_t size);
//Attention! data must be byte aligned to append the content (for both performance and correctness)
BitStream &append(void const *data, size_t size);
BitStream &align();
BitStream const &align() const;
BitStream const &unpack8(uint8 &data) const;
BitStream const &unpack16(uint16 &data) const;
BitStream const &unpack32(uint32 &data) const;
BitStream const &unpack64(uint64 &data) const;
BitStream const &unpackFloat(float &data) const;
BitStream const &unpack_s8(char &data) const;
BitStream const &unpack_s16(int16 &data) const;
BitStream const &unpack_s32(int32 &data) const;
BitStream const &unpackString(char *buffer, uint32 bufferSize) const;
BitStream const &unpackString(std::string &str) const;
uint32 unpackData(uint8 *buffer, uint32 bufferSize) const;
private:
BitStream &packBits(unsigned int data, int nBits);
uint32 unpackBits(int nBits) const ;
void writeToBuffer(uint32 bits);
void readFromBuffer(uint32 *bits) const;
void cacheBits(uint32 *bits) const;
private:
union {
uint8 *mWriteBuffer;
uint8 const *mReadBuffer;
};
uint32 mBufferSize;
uint32 mBitCount;
mutable uint32 mBitPos;
mutable uint32 mBitLeft;
mutable uint32 mBitBuf;
};
template<int SIZE>
class NetStackData : public BitStream {
public:
NetStackData() : BitStream(mBuffer, SIZE) {
}
uint32 capacity() const {
return SIZE;
}
private:
uint8 mBuffer[SIZE];
};
|
#include "stdafx.h"
#include "ProtoBufTest.h"
#include <fstream>
#include "acctest.pb.h"
#include "person.pb.h"
using namespace std;
using namespace myPbMsg;
//#ifdef NDEBUG
//#pragma comment(lib, "../google/bin/Release64/libprotobuf.lib") //x64版本
//#else
//#pragma comment(lib, "../google/bin/Debug64/libprotobufd.lib")
//#endif
CProtoBufTest::CProtoBufTest()
{
person_serialize();
person_unSerialize();
}
CProtoBufTest::~CProtoBufTest()
{
}
//Person序列化
void person_serialize()
{
Person person;
person.set_name("Mike Jordon");
person.set_id(1001);
person.set_email("MikeJD@email.com");
Person_PhoneNumber *pPhone = person.add_phone();
pPhone->set_type(Person_PhoneType::Person_PhoneType_MOBILE);
pPhone->set_number("13800138000");
fstream output("myfile.serial", ios::out | ios::binary);
person.SerializeToOstream(&output);
}
//Person反序列化
void person_unSerialize()
{
fstream input("myfile.serial", ios::in | ios::binary);
Person person;
person.ParseFromIstream(&input);
cout << "ID: " << person.id() << endl;
cout << "Name: " << person.name() << endl;
cout << "E-mail: " << person.email() << endl;
if (person.phone().size()) cout << "Phone: " << person.phone().at(0).number() << endl;
}
int testProtoBuf()
{
IM::Account account1;
account1.set_id(1);
account1.set_name("windsun");
account1.set_password("123456");
string serializeToStr;
account1.SerializeToString(&serializeToStr);
cout << "序列化后的字节:" << serializeToStr << endl;
IM::Account account2;
if (!account2.ParseFromString(serializeToStr))
{
cerr << "failed to parse student." << endl;
return -1;
}
cout << "反序列化:" << endl;
cout << account2.id() << endl;
cout << account2.name() << endl;
cout << account2.password() << endl;
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
|
// ==========================================================================
// Wrapper code to interface g_Element
// ==========================================================================
// (C)opyright:
//
// Jochen Lang
// SITE, University of Ottawa
// 800 King Edward Ave.
// Ottawa, On., K1N 6N5
// Canada.
// http://www.site.uottawa.ca
//
// Creator: Jochen Lang
// Email: jlang@site.uottawa.ca
// ==========================================================================
// $Rev: 3834 $
// $LastChangedBy: jlang $
// $LastChangedDate: 2013-04-11 16:03:39 -0400 (Thu, 11 Apr 2013) $
// ==========================================================================
#ifndef WRAPPER_G_ELEMENT_H
#define WRAPPER_G_ELEMENT_H
#include "g_Container.h"
class g_Node;
class g_PEdge;
class g_Part;
typedef g_Container<g_PEdge *> g_PEdgeContainer;
typedef g_Container<g_Node *> g_NodeContainer;
// Should use a namespace
class g_Element {
protected:
g_Part* d_part;
int d_id; // -1
g_NodeContainer d_nodes;
friend class g_Part;
friend class g_Node;
public:
g_Element() : d_id(-1), d_part(0) {}
void node( g_Node* );
// g_Node* nodes();
int id() const;
g_NodeContainer nodes() const;
g_PEdgeContainer pEdges() const;
void emptyNodeList();
void replaceNodeAt( int&, g_Node*& );
};
typedef g_Container<g_Element *> g_ElementContainer;
#endif
|
/*
* Name - Erin Coots
* Date - November 4th, 2016
* File - Test.cpp
* Description - LinkedListOfInts tests
*/
#include <iostream>
#include <string>
#include "Test.h"
using namespace std;
Test::Test(){}
void Test::runTests(){
cout << "\n-------------------\n";
cout << " RUNNING TESTS ";
cout << "\n-------------------\n";
Test1a();
Test1b();
Test2a();
Test2b();
Test2c();
Test2d();
Test2e();
Test2f();
Test2g();
Test3a();
Test3b();
Test3c();
Test4();
Test5();
Test6a();
Test6b();
Test7a();
Test7b();
cout << "\n-------------------\n";
cout << " TEST COMPLETE ";
cout << "\n-------------------\n";
}
void Test::printMessage(string test, int num, string description, bool passOrFail){
if(num != 0){
if(num == 1){
cout << "\n" << test << ":\n";
}
cout << "\t" << num << ": ";
cout << description << ": ";
if(passOrFail == true){
cout << "Passed\n";
}
else{
cout << "Failed\n";
}
}
else{
cout << "\n" << test << ": ";
cout << description << ": ";
if(passOrFail == true){
cout << "Passed\n";
}
else{
cout << "Failed\n";
}
}
}
//true for empty list
void Test::Test1a(){
LinkedListOfInts list;
bool verdict = false;
verdict = list.isEmpty();
printMessage("isEmpty", 1 ,"list registers as empty", verdict);
}
//false for occupied list
void Test::Test1b(){
LinkedListOfInts list;
bool verdict = false;
verdict = list.isEmpty() ? false : true;
printMessage("isEmpty", 2 ,"list registers as occupied", verdict);
}
//size of empty list
void Test::Test2a(){
LinkedListOfInts list;
bool verdict = false;
if(list.size() == 0)
verdict = true;
printMessage("size", 1 ,"size of empty list", verdict);
}
//size of list after addFront
void Test::Test2b(){
LinkedListOfInts list;
bool verdict = false;
list.addFront(0);
if(list.size() == 1)
verdict = true;
printMessage("size", 2 ,"size of list after 1 addFront", verdict);
}
//size of list after addBack
void Test::Test2c(){
LinkedListOfInts list;
bool verdict = false;
list.addBack(0);
if(list.size() == 1)
verdict = true;
printMessage("size", 3 ,"size of list after 1 addBack", verdict);
}
//size of list after 2+ addFront
void Test::Test2d(){
LinkedListOfInts list;
bool verdict = false;
for(int i = 0; i < 10;i++){
list.addFront(i);
}
if(list.size() == 10)
verdict = true;
printMessage("size", 4 ,"size of list after 2+ addFront", verdict);
}
//size of list after 2+ addBack
void Test::Test2e(){
LinkedListOfInts list;
bool verdict = false;
for(int i = 0; i < 10;i++){
list.addBack(i);
}
if(list.size() == 10)
verdict = true;
printMessage("size", 5 ,"size of list after 2+ addBack", verdict);
}
//size of occupied list after removeFront
void Test::Test2f(){
LinkedListOfInts list;
bool verdict = false;
for(int i = 0; i < 10;i++){
list.addFront(i);
}
list.removeFront();
if(list.size() == 9)
verdict = true;
printMessage("size", 6 ,"size of occupied list after removeFront", verdict);
}
//size of occupied list after removeBack
void Test::Test2g(){
LinkedListOfInts list;
bool verdict = false;
for(int i = 0; i < 10;i++){
list.addFront(i);
}
list.removeBack();
if(list.size() == 9)
verdict = true;
printMessage("size", 7 ,"size of occupied list after removeBack", verdict);
}
//search of empty list
void Test::Test3a(){
LinkedListOfInts list;
bool verdict = false;
verdict = list.search(1) ? false : true;
printMessage("search", 1 ,"search of empty list", verdict);
}
//search of list without value
void Test::Test3b(){
LinkedListOfInts list;
bool verdict = false;
for(int i = 0; i < 10;i++){
list.addFront(i);
}
verdict = list.search(11) ? false : true;
printMessage("search", 2 ,"search of list without value", verdict);
}
//search of list with value
void Test::Test3c(){
LinkedListOfInts list;
bool verdict = false;
for(int i = 0; i < 10;i++){
list.addFront(i);
}
verdict = list.search(1);
printMessage("search", 3 ,"search of list with value", verdict);
}
//value added to end of list
void Test::Test4(){
LinkedListOfInts list;
bool verdict = false;
for(int i = 0; i < 10;i++){
list.addFront(i);
}
list.addFront(20);
list.removeBack();
verdict = list.search(20) ? false : true;
printMessage("addBack", 0 ,"value added to end of list", verdict);
}
//value added to end of list
void Test::Test5(){
LinkedListOfInts list;
bool verdict = false;
for(int i = 0; i < 10;i++){
list.addFront(i);
}
list.addBack(20);
list.removeFront();
verdict = list.search(20) ? false : true;
printMessage("addFront", 0 ,"value added to front of list", verdict);
}
//false for empty list
void Test::Test6a(){
LinkedListOfInts list;
bool verdict = false;
verdict = list.removeBack() ? false : true;
printMessage("removeBack", 1 ,"returns false for empty list", verdict);
}
//value removed from end of list
void Test::Test6b(){
LinkedListOfInts list;
bool verdict = false;
for(int i = 0; i < 10;i++){
list.addFront(i);
}
list.removeFront();
verdict = list.search(9) ? false : true;
printMessage("removeBack", 2 ,"value removed from end of list", verdict);
}
//false for empty list
void Test::Test7a(){
LinkedListOfInts list;
bool verdict = false;
verdict = list.removeFront() ? false : true;
printMessage("removeFront", 1 ,"returns false for empty list", verdict);
}
//value removed from front of list
void Test::Test7b(){
LinkedListOfInts list;
bool verdict = false;
for(int i = 0; i < 10;i++){
list.addFront(i);
}
list.removeBack();
verdict = list.search(0) ? false : true;
printMessage("removeFront", 2 ,"value removed from front of list", verdict);
}
|
#include <EEPROMString.h>
#include <EEPROM.h>
EEPROMString::EEPROMString(int start, int size, int qty) {
_start = start;
_size = size;
_qty = qty;
}
void EEPROMString::begin() {
_eeprom_size = _size * _qty;
EEPROM.begin(_eeprom_size);
}
void EEPROMString::save(int index, String value) {
int start = _start + _size * index;
for (int i=0; i<_size; i++) {
EEPROM.write(start + i, 0);
}
for (int i=0; i<value.length(); i++) {
EEPROM.write(start + i, value[i]);
}
if (EEPROM.commit()) {
Serial.print("save successfully ");
} else {
Serial.print("save failed ");
}
}
String EEPROMString::read(int index) {
int start = _start + _size * index;
char value[_size];
for (int i=0; i<_size; i++) {
value[i] = EEPROM.read(start + i);
}
return String(value);
}
void EEPROMString::remove(int index) {
int start = _start + _size * index;
for (int i=0; i<_size; i++) {
EEPROM.write(start + i, 0);
}
if (EEPROM.commit()) {
Serial.print("remove successfully ");
} else {
Serial.print("remove failed ");
}
}
|
#ifndef MAC_WIDGET_INFO_H
#define MAC_WIDGET_INFO_H
#include "modules/skin/IndpWidgetInfo.h"
typedef enum {
kOperaScrollbarStyleFull,
kOperaScrollbarStyleSimplified
} OperaScrollbarStyle;
class MacWidgetInfo : public IndpWidgetInfo
{
public:
/** Se OpWidget.h for parameter details. */
virtual void GetPreferedSize(OpWidget* widget, OpTypedObject::Type type, INT32* w, INT32* h, INT32 cols, INT32 rows);
/** Shrinks the rect with the border size */
virtual void AddBorder(OpWidget* widget, OpRect *rect);
virtual void GetItemMargin(INT32 &left, INT32 &top, INT32 &right, INT32 &bottom);
virtual INT32 GetDropdownButtonWidth(OpWidget* widget);
virtual INT32 GetScrollbarFirstButtonSize();
virtual INT32 GetScrollbarSecondButtonSize();
virtual SCROLLBAR_ARROWS_TYPE GetScrollbarArrowStyle();
virtual UINT32 GetSystemColor(OP_SYSTEM_COLOR color);
/**
Return which direction a scrollbar button points to. Could be used to make scrollbars with f.eks. no button in
the top and 2 at the bottom.
pos is the mousepos relative to the buttons x position (for a horizontal scrollbar) or y position (for a vertical).
Return values should be: 0 for UP (or LEFT),
1 for DOWN (or RIGHT)
*/
virtual BOOL GetScrollbarButtonDirection(BOOL first_button, BOOL horizontal, INT32 pos);
virtual BOOL GetScrollbarPartHitBy(OpWidget *widget, const OpPoint &pt, SCROLLBAR_PART_CODE &hitPart);
};
#endif // MAC_WIDGET_INFO_H
|
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define FOR(i, n) for (ll i = 0; i < n; i++)
#define FOR1(i, n) for (ll i = 1; i < n; i++)
#define FORn1(i, n) for (ll i = 1; i <= n; i++)
#define FORmap(i, mp) for (auto i = mp.begin(); i != mp.end(); i++)
#define vll vector<ll>
#define vs vector<string>
#define pb(x) push_back(x)
#define fast \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
#define mod 1000000007
using namespace std;
int main()
{
// your code goes here
fast;
ll t;
cin >> t;
while (t--)
{
unordered_map<int, vector<int>> v;
int n, res = 0;
cin >> n;
int x;
FOR(i, n)
{
cin >> x;
int tmp=v[x].size();
res=max(res,tmp);
//cout<<tmp<<" ";
for (int j = 1; j <= sqrt(x); j++)
{
if (x % j == 0)
{
if (x / j == j)
{
v[j].pb(x);
}
else
{
v[j].pb(x);
v[x/j].pb(x);
}
}
}
}
cout << res << endl;
}
return 0;
}
|
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
class Point {
private:
friend std::ostream& operator<<(std::ostream& os, const Point& point) {
return os << "x: " << point.x << " y: " << point.y;
}
friend class PointFactory;
// Use a factory as constructor is private!
Point(double x, double y) : x(x), y(y) {}
double x, y;
};
class PointFactory {
public:
static Point NewCartesian(double x, double y) { return Point{x, y}; }
static Point NewPolar(double r, double theta) {
return Point{r * cos(theta), r * sin(theta)};
}
};
int main() {
auto cartesianPoint = PointFactory::NewCartesian(1.1, 2.2);
auto polarPoint = PointFactory::NewPolar(2.0, M_PI_4);
std::cout << cartesianPoint << std::endl;
std::cout << polarPoint << std::endl;
return 0;
}
|
#ifndef COMMON_THREADING_THREAD_H_
#define COMMON_THREADING_THREAD_H_
#include <functional>
#include <pthread.h>
#include "common/base/nocopy.h"
namespace common {
typedef pthread_t ThreadId;
typedef pthread_attr_t ThreadAttr;
typedef std::function<void()> Functor;
// thread in toft is quite fussy
class Thread {
NOCOPY_CLASS(Thread);
public:
Thread();
explicit Thread(Functor&& functor);
explicit Thread(const Functor& functor);
virtual ~Thread();
// call this before starting it
void SetStackSize(uint32_t size);
void Start(Functor&& functor);
void Start(const Functor& functor);
bool Join();
// you cannot control the thread detached
bool Detach();
void Cancel();
bool IsJoinable();
bool IsRunning();
ThreadId thread_id() const {
return thread_id_;
}
private:
void Init();
void Destroy();
void Run();
static void* ThreadEntry(void* self);
ThreadId thread_id_;
ThreadAttr thread_attr_;
Functor functor_;
};
}
using common::Thread;
#endif
|
// Created on: 2016-02-04
// Created by: Anastasia BORISOVA
// Copyright (c) 2016 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 _Prs3d_ToolQuadric_HeaderFile
#define _Prs3d_ToolQuadric_HeaderFile
#include <Graphic3d_ArrayOfTriangles.hxx>
#include <Poly_Triangulation.hxx>
//! Base class to build 3D surfaces presentation of quadric surfaces.
class Prs3d_ToolQuadric
{
public:
DEFINE_STANDARD_ALLOC
//! Return number of triangles for presentation with the given params.
static Standard_Integer TrianglesNb (const Standard_Integer theSlicesNb,
const Standard_Integer theStacksNb)
{
return theSlicesNb * theStacksNb * 2;
}
//! Return number of vertices for presentation with the given params.
static Standard_Integer VerticesNb (const Standard_Integer theSlicesNb,
const Standard_Integer theStacksNb,
const Standard_Boolean theIsIndexed = Standard_True)
{
return theIsIndexed
? (theSlicesNb + 1) * (theStacksNb + 1)
: TrianglesNb (theSlicesNb, theStacksNb) * 3;
}
public:
//! Generate primitives for 3D quadric surface presentation.
//! @param theTrsf [in] optional transformation to apply
//! @return generated triangulation
Standard_EXPORT Handle(Graphic3d_ArrayOfTriangles) CreateTriangulation (const gp_Trsf& theTrsf) const;
//! Generate primitives for 3D quadric surface presentation.
//! @param theTrsf [in] optional transformation to apply
//! @return generated triangulation
Standard_EXPORT Handle(Poly_Triangulation) CreatePolyTriangulation (const gp_Trsf& theTrsf) const;
//! Generate primitives for 3D quadric surface and fill the given array.
//! @param theArray [in][out] the array of vertices;
//! when NULL, function will create an indexed array;
//! when not NULL, triangles will be appended to the end of array
//! (will raise an exception if reserved array size is not large enough)
//! @param theTrsf [in] optional transformation to apply
Standard_EXPORT void FillArray (Handle(Graphic3d_ArrayOfTriangles)& theArray,
const gp_Trsf& theTrsf) const;
//! Return number of triangles in generated presentation.
Standard_Integer TrianglesNb() const { return mySlicesNb * myStacksNb * 2; }
//! Return number of vertices in generated presentation.
Standard_Integer VerticesNb (bool theIsIndexed = true) const
{
return theIsIndexed
? (mySlicesNb + 1) * (myStacksNb + 1)
: TrianglesNb() * 3;
}
public:
//! Generate primitives for 3D quadric surface presentation.
//! @param theArray [out] generated array of triangles
//! @param theTriangulation [out] generated triangulation
//! @param theTrsf [in] optional transformation to apply
Standard_DEPRECATED("Deprecated method, CreateTriangulation() and CreatePolyTriangulation() should be used instead")
Standard_EXPORT void FillArray (Handle(Graphic3d_ArrayOfTriangles)& theArray,
Handle(Poly_Triangulation)& theTriangulation,
const gp_Trsf& theTrsf) const;
protected:
//! Redefine this method to generate vertex at given parameters.
virtual gp_Pnt Vertex (const Standard_Real theU, const Standard_Real theV) const = 0;
//! Redefine this method to generate normal at given parameters.
virtual gp_Dir Normal (const Standard_Real theU, const Standard_Real theV) const = 0;
protected:
Standard_Integer mySlicesNb; //!< number of slices within U parameter
Standard_Integer myStacksNb; //!< number of stacks within V parameter
};
#endif // _Prs3d_ToolQuadric_HeaderFile
|
/*! @file LogVol_GammaSourceCasing.hh
@brief Defines mandatory user class LogVol_GammaSourceCasing.
@date August, 2012
@author Flechas (D. C. Flechas dcflechasg@unal.edu.co)
@version 1.9
In this header file, the 'physical' setup is defined: materials, geometries and positions.
This class defines the experimental hall used in the toolkit.
*/
/* no-geant4 classes*/
#include "LogVol_GammaSourceCasing.hh"
/* units and constants */
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
#include "G4PhysicalConstants.hh"
/* geometric objects */
#include "G4Tubs.hh"
#include "G4Orb.hh"
/* logic and physical volume */
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
/* geant4 materials */
#include "G4NistManager.hh"
/* visualization */
#include "G4VisAttributes.hh"
LogVol_GammaSourceCasing:: LogVol_GammaSourceCasing(G4String fname, G4double frad, G4double fhei):
G4LogicalVolume(new G4Tubs(fname+"_Sol",0.0*cm, 1.0*cm, 0.3*cm/2.0,0.*rad,2*M_PI*rad),(G4NistManager::Instance())->FindOrBuildMaterial("G4_POLYACRYLONITRILE"),fname,0,0,0)
{
/* set variables */
SetName(fname);
SetRadius(frad);
SetHeight(fhei);
/* Construct solid volume */
ConstructLogVol_GammaSourceCasing();
/* Visualization */
G4VisAttributes* red_vis
= new G4VisAttributes(true,G4Colour::Red());
red_vis->SetForceWireframe(false);
red_vis->SetForceSolid(false);
this->SetVisAttributes(red_vis);
}
LogVol_GammaSourceCasing::~LogVol_GammaSourceCasing()
{}
void LogVol_GammaSourceCasing::ConstructLogVol_GammaSourceCasing(void)
{
GammaSourceCasing_solid = new G4Tubs(Name+"_Sol",0.0*cm, Radius, Height/2.0,
0.*rad,2*M_PI*rad);
/*** Main trick here: Set the new solid volume ***/
SetSolidVol_GammaSourceCasing();
///////////////////////////////
/// **** Source volume **** ///
///////////////////////////////
G4double source_r = 1.2*mm/2.0;
G4Orb* source_sol = new G4Orb(Name+"_source_Sol",source_r);
//Alternatively:: G4Sphere* source_sol = new G4Box("source_Sol",0.0, source_r,0.*rad,2*M_PI*rad,0.*rad,M_PI*rad);
G4LogicalVolume* source_log= new G4LogicalVolume(source_sol,(G4NistManager::Instance())->FindOrBuildMaterial("G4_Na"),Name+"_source_Log",0,0,0);
G4VisAttributes* blue_vis
= new G4VisAttributes(true,G4Colour::Blue());
source_log->SetVisAttributes(blue_vis);
G4VPhysicalVolume* source_phy;
source_phy = new G4PVPlacement(0, // no rotation
G4ThreeVector(),
source_log, // its logical volume
Name+"_source_phy", // its name
this,
false, // no boolean operations
0,
true);
}
void LogVol_GammaSourceCasing::SetSolidVol_GammaSourceCasing(void)
{
/*** Main trick here: Set the new solid volume ***/
if(GammaSourceCasing_solid)
this->SetSolid(GammaSourceCasing_solid);
}
|
#include <SoftwareSerial.h>
#include <Sprite.h>
#include <Matrix.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C mylcd(0x27,16,2);
SoftwareSerial mySerial(10, 11); // RX, TX
//libraries http://duinoedu.com/dl/lib/dupont/sprite/
//libraries http://duinoedu.com/dl/lib/dupont/matrix/
Matrix mesLeds367 = Matrix(3,6,7,1);
int X[] = {
0,7,6,5,4,3,2,1};
int Y[] = {
7,6,5,4,3,2,1,0};
int botton=8;
int mine, yours;
void setup()
{
Serial.begin(9600);
mySerial.begin(9600);
mesLeds367.clear();
mylcd.init();
mylcd.backlight();
mylcd.clear();
pinMode(botton, INPUT);
mine=1;
yours=1;
}
void stone(){
mesLeds367.clear();
for(int i=2; i<=5; i++){
for(int j=2; j<=5; j++){
mesLeds367.write(X[i],Y[j],HIGH);
}
}
}
void scissor(){
mesLeds367.clear();
for(int i=2; i<=7; i++){
for(int j=0; j<=7;j++){
if(i==j||i+j==7){
mesLeds367.write(X[i],Y[j],HIGH);
}
}
}
for(int i=0; i<=2; i++){
for(int j=0; j<=2; j++){
if(i==0||i==2||j==0||j==2){
mesLeds367.write(X[i],Y[j],HIGH);
}
}
}
for(int i=0; i<=2; i++){
for(int j=5; j<=7; j++){
if(i==0||i==2||j==5||j==7){
mesLeds367.write(X[i],Y[j],HIGH);
}
}
}
}
void pack(){
mesLeds367.clear();
for(int i=0; i<=7; i++){
for(int j=0; j<=7; j++){
if(i==0||j==0||i==7||j==7){
mesLeds367.write(X[i],Y[j],HIGH);
}
}
}
}
void showmine(int mine){
switch(mine){
case 1:
stone();
break;
case 2:
scissor();
break;
case 3:
pack();
break;
}
}
void compete(int mine, int yours){
mylcd.clear();
mylcd.setCursor(0, 0);
if(yours - mine == 1|| mine-yours ==2){
mylcd.print("I win!");
}
else if(mine - yours == 1|| yours-mine ==2){
mylcd.print("You win!");
}
else if(mine==yours){
mylcd.print("Same!");
}
else {
mylcd.print("Pass");
}
}
void loop()
{
byte rev;
if (mySerial.available())
{
rev = mySerial.read();
Serial.println(rev);
yours = rev-48;
}
//Serial.println(digitalRead(8));
if (digitalRead(8) == HIGH) {
while (digitalRead(8) == HIGH) {
delay(10);
}
mine = random(1, 4);
showmine(mine);
compete( mine, yours);
}
}
|
#include <boost/math/special_functions/next.hpp>
#include <boost/random.hpp>
#include <limits>
#include "caffe/common.hpp"
#include "caffe/SpeedUp/math_functions_sparse.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/rng.hpp"
#include "caffe/util/benchmark.hpp"
namespace caffe {
template <typename Dtype>
void DisplayMatrix(const Dtype *A, const int m, const int n){
if( m*n >= 100 ){
LOG(INFO) << "Too Many to display.";
return;
}
for (int index = 0; index < m; ++index){
std::ostringstream buffer;
for(int jj = 0; jj < n; ++jj){
int x = A[index*n+jj] * 100;
buffer << std::setfill(' ') << std::setw(6) << x/100.f;
}
LOG(INFO) << buffer.str();
}
}
template void DisplayMatrix<float>(const float *A, const int m, const int n);
template void DisplayMatrix<int>(const int *A, const int m, const int n);
template void DisplayMatrix<double>(const double *A, const int m, const int n);
int GetRandomMatrix(float *A, const int m, const int n, const int seed = 0,const double zero_ratio = 0){
caffe::rng_t RD(seed);
int count_nozeros = m * n;
for (int index = 0; index < m*n; ++index){
A[index] = (RD()%5000+1) / 1000.;
if( RD()%1000 < zero_ratio*1000 ) A[index] = 0;
if( A[index] == 0 ) count_nozeros --;
}
return count_nozeros;
}
int Sparse_Matrix::Convert(float *A, const int m, const int n, float *acsr, int *columns, int *rowIndex ){
#ifdef USE_MKL
int job[] = { 0 , //If job(1)=0, the rectangular matrix A is converted to the CSR format;
//if job(1)=1, the rectangular matrix A is restored from the CSR format.
0 , //If job(2)=0, zero-based indexing for the rectangular matrix A is used;
//if job(2)=1, one-based indexing for the rectangular matrix A is used.
0 , //If job(3)=0, zero-based indexing for the matrix in CSR format is used;
//if job(3)=1, one-based indexing for the matrix in CSR format is used.
2 , //If job(4)=0, adns is a lower triangular part of matrix A;
//If job(4)=1, adns is an upper triangular part of matrix A;
m*n, //If job(4)=2, adns is a whole matrix A.
//job(5)=nzmax - maximum number of the non-zero elements allowed if job(1)=0.
1 };//job(6) - job indicator for conversion to CSR format.
//If job(6)=0, only array ia is generated for the output storage.
//If job(6)>0, arrays acsr, ia, ja are generated for the output storage.
int lda = n, info = -1;
mkl_sdnscsr(job, &m, &n, A, &lda, acsr, columns, rowIndex, &info);
return info;
#else
LOG(FATAL) << "This func requires MKL; compile with BLAS: mkl.";
return -1;
#endif
}
#ifdef USE_MKL
void Sparse_Matrix::TestConvert(){
float A[] = { 1, -1, 0, -3, 0,
-2, 5, 0, 0, 0,
0, 0, 4, 6, 4,
-4, 0, 2, 7, 0,
0, 8, 0, 0, -5}; // 5 * 5 matrix
const float values[] = {1, -1, -3, -2, 5, 4, 6, 4, -4, 2, 7, 8, -5};
const int columns[] = {0, 1, 3, 0, 1, 2, 3, 4, 0, 2, 3, 1, 4};
const int rowIndex[] = {0, 3, 5, 8, 11, 13};
//void mkl_sdnscsr(int *job, int *m, int *n, float *adns, int *lda, float *acsr, int *ja, int *ia, int *info);
const int m = 5; // INTEGER. Number of rows of the matrix A.
const int n = 5; // INTEGER. Number of columns of the matrix A.
//float adns[20] ; //(input/output) Array containing non-zero elements of the matrix A.
//int lda = m; //(input/output)INTEGER. Specifies the first dimension of adns as declared in the calling (sub)program, must be at least max(1, m).
float acsr[20] ; // Array containing non-zero elements of the matrix A. Its length is equal to the number of non-zero elements in the matrix A. Refer to values array description in Sparse Matrix Storage Formats for more details.
int ja[20] ; //(input/output)INTEGER. Array containing the column indices for each non-zero element of the matrix A.
//Its length is equal to the length of the array acsr. Refer to columns array description in Sparse Matrix Storage Formats for more details.
int ia[20] ; //(input/output)INTEGER. Array of length m + 1, containing indices of elements in the array acsr, such that ia(I) is the index in the array acsr of the first non-zero element from the row I. The value of the last element ia(m + 1) is equal to the number of non-zeros plus one. Refer to rowIndex array description in Sparse Matrix Storage Formats for more details.
int info = -1; //INTEGER. Integer info indicator only for restoring the matrix A from the CSR format.
//If info=0, the execution is successful.
//If info=i, the routine is interrupted processing the i-th row because there is no space in the arrays adns and ja according to the value nzmax.
double Average_time = 0;
const int LOOP = 50, gap = 10;
LOG(INFO) << "Matrix A is :";
DisplayMatrix(A , m , n );
for (int index = 0; index < LOOP; index+=gap){
caffe::Timer _time;
_time.Start();
//mkl_sdnscsr(job, &m, &n, A, &lda, acsr, ja, ia, &info);
for (int j = 0 ; j < gap; ++j)
info = Convert(A, m, n, acsr, ja, ia);
Average_time += _time.MicroSeconds();
LOG(INFO) << "Iteration " << index << " Convert in " << _time.MicroSeconds()/float(gap) << "us";
}
LOG(INFO) << "Average Time for Convert is " << Average_time / LOOP << "us";
std::ostringstream buffer;
buffer << "Acsr (" << ia[m] << ") : ";
const int no_zeros = sizeof(values) / sizeof(values[0]);
CHECK_EQ( no_zeros, ia[m] );
for (int i = 0; i < ia[m]; ++i){
buffer << " " << acsr[i];
CHECK_EQ( acsr[i] , values[i] );
}
LOG(INFO) << buffer.str(); buffer.str("");
buffer << "rowIndex (" << m << "+1) : ";
for(int i = 0; i <= m ; ++i){
CHECK_EQ( rowIndex[i] , ia[i] );
buffer << " " << ia[i];
}
LOG(INFO) << buffer.str(); buffer.str("");
buffer << "columns (" << ia[m] << ") : ";
for(int i = 0; i < ia[m] ; ++i){
CHECK_EQ( columns[i] , ja[i] );
buffer << " " << ja[i];
}
LOG(INFO) << buffer.str(); buffer.str("");
if(info==0) buffer << "convert is successful ";
else buffer << "routine is interrupted processing the " << info << "-th row";
LOG(INFO) << buffer.str();
}
#else
void Sparse_Matrix::TestConvert(){
LOG(FATAL) << "This func requires MKL; compile with BLAS: mkl.";
}
#endif
#ifdef USE_MKL
void Sparse_Matrix::TestMVProduct(const int m,const int n,const double zero_ratio){
/*
// m -> rows , n -> cols
The mkl_?csrmv routine performs a matrix-vector operation defined as
y := alpha*A*x + beta*y or y := alpha*A'*x + beta*y,
where:
alpha and beta are scalars,
x and y are vectors,
A is an m-by-k sparse matrix in the CSR format, A' is the transpose of A.
*/
CHECK( zero_ratio >= 0 && zero_ratio <= 1 );
CHECK( m > 0 && n > 0 );
float *A = new float[m*n];
const int count_nozeros = GetRandomMatrix(A , m , n , 0 , zero_ratio);
/*
int count_nozeros = m*n;
for (int index = 0; index < m*n; ++index){
A[index] = (RD()%5000) / 1000.;
if( RD()%1000 < zero_ratio*1000 ) A[index] = 0;
//if( A[index] == 0 ) count_nozeros --;
if( std::abs(A[index])<1e-8 ) count_nozeros --;
}*/
LOG(INFO) << "Random Set Matrix A (" << m << " , " << n << ") : " << count_nozeros*1.0/(m*n) << " (force) no-zeros elements" ;
DisplayMatrix(A, m , n );
//void mkl_scsrmv(char *transa, int *m, int *k, float *alpha, char *matdescra, float *val, int *indx, int *pntrb, int *pntre, float *x, float *beta, float *y);
const char transa = 'N'; // If transa = 'N' or 'n', then y := alpha*A*x + beta*y
// If transa = 'T' or 't' or 'C' or 'c', then y := alpha*A'*x + beta*y,
// m INTEGER. Number of rows of the matrix A.
const int k = n; //INTEGER. Number of columns of the matrix A.
const float alpha = 2.0; // REAL for mkl_scsrmv.
const char matdescra[6] = {'G','L','N','C','\0','\0'}; //CHARACTER. Array of six elements, specifies properties of the matrix used for operation.
float *val = new float[count_nozeros]; // Array containing non-zero elements of the matrix A.
int *indx = new int[count_nozeros]; // INTEGER. Array containing the column indices for each non-zero element of the matrix A.Its length is equal to length of the val array.
int *rowIndex = new int[m+1];
LOG(INFO) << "Start Convert [MV-Product]";
caffe::Timer _time;
double matrix_time = 0;
for (int loop = 0; loop < 10 ; loop++ ){
_time.Start();
int info = Convert(A, m, k, val, indx, rowIndex);
matrix_time = _time.MicroSeconds();
if(info==0) LOG(INFO) << "Convert is successful [MV-Product] , " << matrix_time << " us";
else LOG(INFO) << "Routine is interrupted processing the " << info << "-th row [MV-Product]";
}
int *pntrb = new int[m];
int *pntre = new int[m];
memcpy(pntrb, rowIndex, sizeof(int)*m);
LOG(INFO) << "Prointer B OK ";
memcpy(pntre, rowIndex+1, sizeof(int)*m);
LOG(INFO) << "Prointer E OK ";
for (int i = 0; i < m; i++){
CHECK_EQ( pntrb[i] , rowIndex[i] );
CHECK_EQ( pntre[i] , rowIndex[i+1] );
}
float *x = new float[k]; // Array, DIMENSION at least k if transa = 'N' or 'n' and at least m otherwise. On entry, the array x must contain the vector x.
const float beta = 1.7; // Specifies the scalar beta.
float *y = new float[m];
/*
for (int index = 0; index < k; ++index){
x[index] = (RD()%5000) / 1000.;
}
for (int index = 0; index < m; ++index){
y[index] = (RD()%5000) / 1000.;
}*/
const int x_nz = GetRandomMatrix(x , k , 1 , 101);
const int y_nz = GetRandomMatrix(y , 1 , m , 209);
LOG(INFO) << "Transa : " << transa << " :: X(" << x_nz << ") Y(" << y_nz << ")";
LOG(INFO) << "m : " << m << " , k : " << k;
LOG(INFO) << "alpha : " << alpha << " , beta : " << beta;
LOG(INFO) << "Val : ";
DisplayMatrix(val, 1, count_nozeros );
LOG(INFO) << "Index : ";
DisplayMatrix(indx, 1, count_nozeros );
LOG(INFO) << "PointerB : ";
DisplayMatrix(pntrb, 1, m );
LOG(INFO) << "PointerE : ";
DisplayMatrix(pntre, 1, m );
LOG(INFO) << "[MV-Product] Data Prepare Done, Matrix Convert Cost " << matrix_time << " us";
const int LOOP = 30;
float *temp = new float[m];
float *XX = new float[k];
float *YY = new float[m];
memcpy(XX,x,sizeof(float)*k);
memcpy(YY,y,sizeof(float)*m);
vector<double> DenseAVE;
for (int loop = 0; loop < LOOP; ++loop){
// Force to calculate Y
_time.Start();
for (int j = 0; j < m; ++j){
temp[j] = beta * y[j];
for (int i = 0; i < k; ++i){
temp[j] += alpha * A[j*k+i] * x[i];
}
}
//LOG(INFO) << "[Sparse] Loop " << loop << " Done in " << _time.MicroSeconds() << " us";
double force_time = _time.MicroSeconds();
_time.Start();
mkl_scsrmv(&transa, &m, &k, &alpha, matdescra, val, indx, pntrb, pntre, x, &beta, y);
double sparse_time = _time.MicroSeconds();
_time.Start();
caffe_cpu_gemv(CblasNoTrans, m, n, alpha, A, XX, beta, YY);
double dense_time = _time.MicroSeconds();
DenseAVE.push_back( dense_time );
//LOG(INFO) << "[Dense] Loop " << loop << " Done in " << _time.MicroSeconds() << " us";
LOG(INFO) << "Loop " << loop << " [Force : " << std::setfill(' ') << std::setw(5) << force_time << "] [Sparse : " << std::setfill(' ') << std::setw(5) << sparse_time << "] [Dense : " << std::setfill(' ') << std::setw(5) << dense_time << "] us";
for (int j = 0; j < m; ++j){
//printf("Temp: %.8f \n, Y : %.8f\n",temp[j],y[j]);
//CHECK( std::abs(temp[j]-y[j]) <= 1e-5*std::abs(y[j]) ) << j << "-th value of [Sparse] Y is wrong. " << temp[j] << " vs " << y[j];
float Sparse_Error = std::max( std::abs(temp[j]-y[j]) / std::abs(y[j]) , std::abs(temp[j]-y[j]) / std::abs(temp[j]) ) ;
if( Sparse_Error > 3e-5 ) LOG(WARNING) << j << "-th value of [Sparse] Y is wrong. By " << Sparse_Error << " deviation";
//printf("Temp: %.8f \n, Y : %.8f\n",temp[j],y[j]);
//CHECK( std::abs(temp[j]-YY[j]) <= 1e-5*std::abs(YY[j]) ) << j << "-th value of [Dense] Y is wrong. " << temp[j] << " vs " << YY[j];
Sparse_Error = std::max( std::abs(temp[j]-YY[j]) / std::abs(YY[j]) , std::abs(temp[j]-YY[j]) / std::abs(temp[j]) ) ;
if( Sparse_Error > 3e-5 ) LOG(WARNING) << j << "-th value of [Dense] Y is wrong. By " << Sparse_Error << " deviation";
}
}
sort(DenseAVE.begin(), DenseAVE.end());
double ave = 0 ;
int num = 0;
for (int i = 4; i < LOOP - 4 ; i ++ ){
ave += DenseAVE[i];
num ++;
}
LOG(INFO) << "[MV] Dense Average Time: " << ave/num << " us";
delete []XX;
delete []YY;
delete []A;
delete []val;
delete []indx;
delete []rowIndex;
delete []pntrb;
delete []pntre;
delete []x;
delete []y;
delete []temp;
}
#else
void Sparse_Matrix::TestMVProduct(const int m, const int n, const double zero_ratio){
/*
The since mkl cannot be used, this will only test dense matrix test mv product
y := alpha*A*x + beta*y or y := alpha*A'*x + beta*y,
where:
alpha and beta are scalars,
x and y are vectors,
A is an m-by-k sparse matrix in the CSR format, A' is the transpose of A.
*/
CHECK( zero_ratio >= 0 && zero_ratio <= 1 );
CHECK( m > 0 && n > 0 );
float *A = new float[m*n];
const int count_nozeros = GetRandomMatrix(A , m , n , 0 , zero_ratio);
LOG(INFO) << "Random Set Matrix A (" << m << " , " << n << ") : " << count_nozeros*1.0/(m*n) << " (force) no-zeros elements" ;
DisplayMatrix(A, m , n );
const int k = n;
const float alpha = 3.9; // Specifies the scalar beta.
float *x = new float[k]; // Array, DIMENSION at least k if transa = 'N' or 'n' and at least m otherwise. On entry, the array x must contain the vector x.
const float beta = 1.7; // Specifies the scalar beta.
float *y = new float[m];
GetRandomMatrix(x , k , 1 , 101);
GetRandomMatrix(y , 1 , m , 209);
LOG(INFO) << "m : " << m << " , k : " << k;
LOG(INFO) << "alpha : " << alpha << " , beta : " << beta;
LOG(INFO) << "[MV-Product] Data Prepare Done,.";
const int LOOP = 30;
vector<double> DenseAVE;
caffe::Timer _time;
for (int loop = 0; loop < LOOP; ++loop){
// Force to calculate Y
_time.Start();
caffe_cpu_gemv(CblasNoTrans, m, n, alpha, A, x, beta, y);
double dense_time = _time.MicroSeconds();
DenseAVE.push_back( dense_time );
LOG(INFO) << "Loop " << loop << "Dense : " << std::setfill(' ') << std::setw(5) << dense_time << "] us";
}
sort(DenseAVE.begin(), DenseAVE.end());
double ave = 0 ;
int num = 0;
for (int i = 4; i < LOOP - 4 ; i ++ ){
ave += DenseAVE[i];
num ++;
}
LOG(INFO) << "[MV] Dense Average Time: " << ave/num << " us";
delete []A;
delete []x;
delete []y;
}
#endif
#ifdef USE_MKL
MM_Time Sparse_Matrix::TestMMProduct(const int m, const int k, const int n ,const double zero_ratio){
/*
The mkl_?csrmm routine performs a matrix-vector operation defined as
C := alpha*A*B + beta*C or C := alpha*A'*B + beta*C,
where:
alpha and beta are scalars,
B and C are dense matrices ,
A is an m-by-k sparse matrix in the CSR format, A' is the transpose of A.
*/
CHECK( zero_ratio >= 0 && zero_ratio <= 1 );
//const int m = k + 10;
CHECK( m > 0 && k > 0 );
float *A = new float[m*k];
const int count_nozeros = GetRandomMatrix(A , m , k , 0 , zero_ratio);
/*
int count_nozeros = m*n;
for (int index = 0; index < m*n; ++index){
A[index] = (RD()%5000) / 1000.;
if( RD()%1000 < zero_ratio*1000 ) A[index] = 0;
//if( A[index] == 0 ) count_nozeros --;
if( std::abs(A[index])<1e-8 ) count_nozeros --;
}*/
LOG(INFO) << "Random Set Matrix A (" << m << " , " << k << ") : " << count_nozeros*1.0/(m*k) << " (force) no-zeros elements" ;
DisplayMatrix(A, m , k );
//void mkl_scsrmv(char *transa, int *m, int *k, float *alpha, char *matdescra, float *val, int *indx, int *pntrb, int *pntre, float *x, float *beta, float *y);
const char transa = 'N'; // If transa = 'N' or 'n', then y := alpha*A*x + beta*y
// If transa = 'T' or 't' or 'C' or 'c', then y := alpha*A'*x + beta*y,
// m INTEGER. Number of rows of the matrix A.
//const int k = n; //INTEGER. Number of columns of the matrix A.
const float alpha = 2.0; // REAL for mkl_scsrmv.
const char matdescra[6] = {'G','L','N','C','\0','\0'}; //CHARACTER. Array of six elements, specifies properties of the matrix used for operation.
float *val = new float[count_nozeros]; // Array containing non-zero elements of the matrix A.
int *indx = new int[count_nozeros]; // INTEGER. Array containing the column indices for each non-zero element of the matrix A.Its length is equal to length of the val array.
int *rowIndex = new int[m+1];
LOG(INFO) << "Start Convert [MV-Product]";
caffe::Timer _time;
double matrix_time = 0;
for (int loop = 0; loop < 10 ; loop++ ){
_time.Start();
int info = Convert(A, m, k, val, indx, rowIndex);
matrix_time = _time.MicroSeconds();
if(info==0) LOG(INFO) << "Convert is successful [MV-Product] , " << matrix_time << " us";
else LOG(INFO) << "Routine is interrupted processing the " << info << "-th row [MV-Product]";
}
int *pntrb = new int[m];
int *pntre = new int[m];
memcpy(pntrb, rowIndex, sizeof(int)*m);
LOG(INFO) << "Prointer B OK ";
memcpy(pntre, rowIndex+1, sizeof(int)*m);
LOG(INFO) << "Prointer E OK ";
for (int i = 0; i < m; i++){
CHECK_EQ( pntrb[i] , rowIndex[i] );
CHECK_EQ( pntre[i] , rowIndex[i+1] );
}
//const int n = k + 1;
float *B = new float[k*n]; // Array, DIMENSION at least k if transa = 'N' or 'n' and at least m otherwise. On entry, the array x must contain the vector x.
const float beta = 1.7; // Specifies the scalar beta.
float *C = new float[m*n];
const int x_nz = GetRandomMatrix(B , k , n , 121);
const int y_nz = GetRandomMatrix(C , m , n , 207);
LOG(INFO) << "Transa : " << transa << " :: X(" << x_nz << ") Y(" << y_nz << ")";
LOG(INFO) << "m : " << m << " , k : " << k;
LOG(INFO) << "alpha : " << alpha << " , beta : " << beta;
LOG(INFO) << "Val : ";
DisplayMatrix(val, 1, count_nozeros );
LOG(INFO) << "Index : ";
DisplayMatrix(indx, 1, count_nozeros );
LOG(INFO) << "PointerB : ";
DisplayMatrix(pntrb, 1, m );
LOG(INFO) << "PointerE : ";
DisplayMatrix(pntre, 1, m );
LOG(INFO) << "[MV-Product] Data Prepare Done, Matrix Convert Cost " << matrix_time << " us";
const int LOOP = 30;
const int ldb = n;
const int ldc = n;
float *XX = new float[k*n];
float *YY = new float[m*n];
memcpy(XX,B,sizeof(float)*k*n);
memcpy(YY,C,sizeof(float)*m*n);
vector<double> DenseAVE;
for (int loop = 0; loop < LOOP; ++loop){
// Force to calculate Y
_time.Start();
mkl_scsrmm(&transa, &m, &n, &k, &alpha, matdescra, val, indx, pntrb, pntre, B, &ldb, &beta, C, &ldc);
//double sparse_time = _time.MicroSeconds();
_time.Start();
caffe_cpu_gemm(CblasNoTrans, CblasNoTrans, m, n, k, alpha, A, XX, beta, YY);
double dense_time = _time.MicroSeconds();
//LOG(INFO) << "Loop " << loop << " [Sparse : " << std::setfill(' ') << std::setw(5) << sparse_time << "] [Dense : " << std::setfill(' ') << std::setw(5) << dense_time << "] us";
DenseAVE.push_back(dense_time);
for (int j = 0; j < m*n; ++j){
double Sparse_Error = std::max( std::abs(C[j]-YY[j]) / std::abs(YY[j]) , std::abs(C[j]-YY[j]) / std::abs(C[j]) ) ;
if( Sparse_Error > 3e-5 ) LOG(WARNING) << j << "-th value of [Dense] vs [Sparse] is wrong. By " << Sparse_Error << " deviation";
}
}
sort(DenseAVE.begin(), DenseAVE.end());
double ave = 0 ;
int num = 0;
for (int i = 4; i < LOOP - 4 ; i ++ ){
ave += DenseAVE[i];
num ++;
}
LOG(INFO) << "Dense Average Time: " << ave/num << " us";
delete []XX;
delete []YY;
delete []A;
delete []val;
delete []indx;
delete []rowIndex;
delete []pntrb;
delete []pntre;
delete []B;
delete []C;
return MM_Time(m, n, k, ave/num);
}
#else
MM_Time Sparse_Matrix::TestMMProduct(const int m, const int k, const int n ,const double zero_ratio){
/*
The since mkl cannot be used, this will only test dense matrix test mm product
C := alpha*A*B + beta*C or C := alpha*A'*B + beta*C,
where:
alpha and beta are scalars,
B and C are dense matrices ,
A is an m-by-k sparse matrix in the CSR format, A' is the transpose of A.
*/
CHECK( zero_ratio >= 0 && zero_ratio <= 1 ) << " not " << zero_ratio;
//const int m = k + 10;
CHECK( m > 0 && k > 0 );
float *A = new float[m*k];
const int count_nozeros = GetRandomMatrix(A , m , k , 0 , zero_ratio);
LOG(INFO) << "Random Set Matrix A (" << m << " , " << k << ") : " << count_nozeros*1.0/(m*k) << " (force) no-zeros elements" ;
DisplayMatrix(A, m , k );
//void mkl_scsrmv(char *transa, int *m, int *k, float *alpha, char *matdescra, float *val, int *indx, int *pntrb, int *pntre, float *x, float *beta, float *y);
//const int k = n; //INTEGER. Number of columns of the matrix A.
const float alpha = 2.0; // REAL for mkl_scsrmv.
//const int n = k + 1;
float *B = new float[k*n]; // Array, DIMENSION at least k if transa = 'N' or 'n' and at least m otherwise. On entry, the array x must contain the vector x.
const float beta = 1.7; // Specifies the scalar beta.
float *C = new float[m*n];
GetRandomMatrix(B , k , n , 121);
GetRandomMatrix(C , m , n , 207);
LOG(INFO) << "m : " << m << " , k : " << k << " , n : " << n;
LOG(INFO) << "alpha : " << alpha << " , beta : " << beta;
//LOG(INFO) << "[MV-Product] Data Prepare Done";
const int LOOP = 30;
vector<double> DenseAVE;
caffe::Timer _time;
for (int loop = 0; loop < LOOP; ++loop){
// Force to calculate Y
_time.Start();
caffe_cpu_gemm(CblasNoTrans, CblasNoTrans, m, n, k, alpha, A, B, beta, C);
double dense_time = _time.MicroSeconds();
//LOG(INFO) << "Loop " << loop << "[Dense : " << std::setfill(' ') << std::setw(5) << dense_time << "] us";
DenseAVE.push_back(dense_time);
}
sort(DenseAVE.begin(), DenseAVE.end());
LOG(INFO) << "FOR CHECK >>>> m : " << m << " n : " << n << " k : " << k;
double ave = 0 ;
int num = 0;
for (int i = 4; i < LOOP - 4 ; i ++ ){
ave += DenseAVE[i];
num ++;
}
LOG(INFO) << "Dense Average Time: " << ave/num << " us";
delete []A;
delete []B;
delete []C;
return MM_Time(m, n, k, ave/num);
}
#endif
} // namespace caffe
|
;
#include <iostream>
#include <conio.h>
using namespace std;
int ShowMatrix()
{
int row=2, column=2;
int matrix[2][2] = { {8, -4} , {-6, 2} };
cout<<"The matrix is:"<<endl;
for(int i=0; i<row; ++i) {
for(int j=0; j<column; ++j)
cout<<matrix[i][j]<<" ";
cout<<endl;
}
}
int showTranspose ( )
{
int transpose[2][2], row=2, column=2, i, j;
int matrix[2][2] = { {8, -4} , {-6, 2} };
cout<<endl;
for(i=0; i<row; ++i)
for(j=0; j<column; ++j) {
transpose[j][i] = matrix[i][j];
}
cout<<"The transpose of the matrix is:"<<endl;
for(i=0; i<column; ++i) {
for(j=0; j<row; ++j)
cout<<transpose[i][j]<<" ";
cout<<endl;
}
}
int calculateDeterminant()
{
int determMatrix[2][2], determinant;
int matrix[2][2] = { {8, -4} , {-6, 2} };
determinant = ((matrix[0][0] * matrix[1][1]) -
(matrix[0][1] * matrix[1][0]));
cout << "\nThe Determinant of 2 * 2 Matrix = " << determinant;
}
int showAdjoint()
{
int ch,A2[2][2] = {{8,-4},{-6,2}},AD2[2][2],C2[2][2];
//Calculating co-factors of matrix of order 2x2
C2[0][0]=A2[1][1]; C2[0][1]=-A2[1][0]; C2[1][0]=-A2[0][1]; C2[1][1]=A2[0][0];
//calculating ad-joint of matrix of order 2x2
AD2[0][0]=C2[0][0]; AD2[0][1]=C2[1][0]; AD2[1][0]=C2[0][1]; AD2[1][1]=C2[1][1];
cout<<"\n\nAdjoint of A is :- \n\n";
cout<<"|\t"<<AD2[0][0]<<"\t"<<AD2[0][1]<<"\t|\n|\t"<<AD2[1][0]<<"\t"<<AD2[1][1]<<"\t|\n";
}
int main()
{
int choice = 0;
cout<<" ||---Enter your choice---||"<<endl;
cout<<""<<endl;
cout<<"---Press 1 to display the matrix and its transpose---"<<endl;
cout<<"---Press 2 to find adjoint and determinant of the matrix---"<<endl;
cout<<""<<endl;
cout<<"Press any other key to exit.";
cout<<""<<endl;
cin>>choice;
if (choice ==1)
{
ShowMatrix();
showTranspose ( );
}
else if (choice == 2)
{
showAdjoint();
calculateDeterminant();
}
else
system("pause");
}
|
#include <iostream>
#include <cppunit/extensions/HelperMacros.h>
#include <Poco/AutoPtr.h>
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/Document.h>
#include "util/SecureXmlParser.h"
#include "cppunit/BetterAssert.h"
using namespace std;
using namespace Poco;
using namespace Poco::XML;
namespace BeeeOn {
class SecureXmlParserTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(SecureXmlParserTest);
CPPUNIT_TEST(testGenericEntityExpansionVulnerable);
CPPUNIT_TEST(testGenericEntityExpansionSecured);
CPPUNIT_TEST(testRecursiveEntityExpansionVulnerable);
CPPUNIT_TEST(testRecursiveEntityExpansionSecured);
CPPUNIT_TEST_SUITE_END();
public:
void testGenericEntityExpansionVulnerable();
void testGenericEntityExpansionSecured();
void testRecursiveEntityExpansionVulnerable();
void testRecursiveEntityExpansionSecured();
};
CPPUNIT_TEST_SUITE_REGISTRATION(SecureXmlParserTest);
static const string GENERIC_ENTITY_EXPANSION_ATTACK =
"<!DOCTYPE s ["
"<!ENTITY x \"VERY LONG CONTENT\">"
"]>"
"<test>&x;&x;&x;</test>";
/**
* Test the parser is vulnerable to generic entity expansion.
*/
void SecureXmlParserTest::testGenericEntityExpansionVulnerable()
{
DOMParser parser;
const AutoPtr<Document> doc = parser.parseString(
GENERIC_ENTITY_EXPANSION_ATTACK);
const Element *root = doc->documentElement();
const string &value = root->innerText();
const string expect = "VERY LONG CONTENT"
"VERY LONG CONTENT" "VERY LONG CONTENT";
CPPUNIT_ASSERT_EQUAL(expect, value);
}
void SecureXmlParserTest::testGenericEntityExpansionSecured()
{
SecureXmlParser parser;
CPPUNIT_ASSERT_THROW(parser.parse(
GENERIC_ENTITY_EXPANSION_ATTACK),
InvalidArgumentException);
}
static const string RECURSIVE_ENTITY_EXPANSION_ATTACK =
"<!DOCTYPE s ["
"<!ENTITY x0 \":)\">"
"<!ENTITY x1 \"&x0;&x0;\">"
"<!ENTITY x2 \"&x1;&x1;\">"
"]>"
"<test>&x2;</test>";
/**
* Test the parser is vulnerable to recursive entity expansion.
*/
void SecureXmlParserTest::testRecursiveEntityExpansionVulnerable()
{
DOMParser parser;
const AutoPtr<Document> doc = parser.parseString(
RECURSIVE_ENTITY_EXPANSION_ATTACK);
const Element *root = doc->documentElement();
const string &value = root->innerText();
const string expect = ":):):):)";
CPPUNIT_ASSERT_EQUAL(expect, value);
}
void SecureXmlParserTest::testRecursiveEntityExpansionSecured()
{
SecureXmlParser parser;
CPPUNIT_ASSERT_THROW(parser.parse(
RECURSIVE_ENTITY_EXPANSION_ATTACK),
InvalidArgumentException);
}
}
|
#ifndef _CONFIGURE_H_
#define _CONFIGURE_H_
#include <time.h>
#include <unistd.h>
#include <string>
#include "Typedef.h"
#include "Game/GameConfig.h"
class Configure :public GameConfig
{
Singleton(Configure);
public:
bool LoadGameConfig();
public:
UINT16 m_robotId; //第几个机器人服务器
//连接大厅的ip和端口
std::string m_hallIp;
short m_hallPort;
//头像链接
std::string m_headLink;
int baseMoney1;
int baseMoney2;
int baseMoney3;
int baseMoney4;
int randMoney1;
int randMoney2;
int randMoney3;
int randMoney4;
int swtichWin1;
int swtichWin2;
int swtichWin3;
int swtichWin4;
std::string serverxml;
};
#endif
|
/**
BasicHTTPClient.ino
Created on: 24.05.2015
*/
#include <Arduino.h>
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
//for input-output
SoftwareSerial NodeMCU(D2,D3);
//SoftwareSerial NodeMCU(D3,D2);
/*
* HTTP Client POST Request
* Copyright (c) 2018, circuits4you.com
* All rights reserved.
* https://circuits4you.com
* Connects to WiFi HotSpot. */
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
/* Set these to your desired credentials. */
//char* ssid = "AndroidAP";
//const char* password = "olrv4095";
char* ssid = "Ess";
const char* password = "0524600066";
//char* ssid = "Student";
//const char* password = "Aa123456";
//Web/Server address to read/write from
const char *host = "10.100.102.131"; //https://circuits4you.com website or IP address of server
//=======================================================================
// Power on setup
//=======================================================================
void setup() {
delay(1000);
Serial.begin(9600);
//for connect with arduino
NodeMCU.begin(4800);
pinMode(D2,INPUT);
pinMode(D3,OUTPUT);
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi hotspot
WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.println("");
Serial.print("Connecting");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
}
//=======================================================================
// Main Program Loop
//=======================================================================
void loop() {
//receiving a value from the arduino
while(NodeMCU.available()>0){
int val = NodeMCU.read();
Serial.println("the wifi receive from the arduino val is: ");
Serial.println(val);
if(val == 1){
HTTPClient http; //Declare object of class HTTPClient
String ADCData, station, postData;
//int adcvalue=analogRead(A0); //Read Analog value of LDR
//ADCData = String(adcvalue); //String to interger conversion
station = "A";
//Post Data
postData = "{\"usr\":\"asaf\",\"sig\":1}" ;
http.begin("http://10.100.102.13:3000/api/pluse"); //Specify request destination
http.addHeader("Content-Type", "application/json"); //Specify content-type header
int httpCode = http.POST(postData); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end(); //Close connection
delay(500); //Post Data at every 5 seconds
}
else{
Serial.println("no cigares for today - well done ! :)"); }
}
}
|
#ifndef _PLATE_1D_ADAMSBASHFORTH_
#define _PLATE_1D_ADAMSBASHFORTH_ 1
#include "plate_var_types.h"
#include <vector>
#include <iostream>
#include <fstream>
#include <complex>
using std::vector;
using std::cout;
using std::endl;
using std::ofstream;
using std::complex;
class ABPrevPhis
{
public:
ABPrevPhis();
~ABPrevPhis();
vector<PL_NUM> F_1; //Function Phi of the system for basis vector of the -1 spatial step
vector<PL_NUM> F_2; //Function Phi of the system for basis vector of the -2 spatial step
vector<PL_NUM> F_3; //Function Phi of the system for basis vector of the -3 spatial step
vector<PL_NUM> F; //Function Phi of the system for basis vector of the current spatial step
};
class AdamsBashforth
{
public:
AdamsBashforth();
~AdamsBashforth();
vector<ABPrevPhis> prevPhis; //sets of 4 previous functions of the system for each of basis vectors
void calc( const vector<PL_NUM>& A, const vector<PL_NUM>& f, PL_NUM dx, int n, int hom, vector<PL_NUM>* x ); //hom == 0 if homogeneous
void setEqNum( int _eq_num );
private:
int eq_num;
};
#endif
|
#include <SmartDB.h>
namespace qy {
SmartDB::SmartDB()
: dbHandle_(NULL)
, connected_(false)
, code_(0)
{};
SmartDB::SmartDB(const std::string& filename) {
Open(filename);
};
bool SmartDB::Open(const std::string& filename) {
code_ = sqlite3_open(filename.data(), &dbHandle_);
if (SQLITE_OK == code_)
{
connected_ = true;
}
return connected_;
};
SmartDB::~SmartDB() {
Close();
};
bool SmartDB::Close() {
code_ = sqlite3_close(dbHandle_);
return code_ == SQLITE_OK;
};
bool SmartDB::Execute(const std::string& sqlStr) {
code_ = sqlite3_exec(dbHandle_, sqlStr.data(), nullptr, nullptr, nullptr);
return SQLITE_OK == code_;
};
bool SmartDB::Begin() {
return Execute(BEGIN);
};
bool SmartDB::RollBack() {
return Execute(ROLLBACK);
};
bool SmartDB::Commit() {
return Execute(COMMIT);
};
bool SmartDB::Prepare(const std::string &sqlStr) {
code_ = sqlite3_prepare_v2(dbHandle_, sqlStr.data(), -1, &state_, nullptr);
if (code_ == SQLITE_OK) {
return true;
} else {
std::cout << "prepared error " << sqlite3_errmsg(dbHandle_) << std::endl;
return false;
}
};
const std::string SmartDB::BEGIN = "BEGIN";
const std::string SmartDB::ROLLBACK = "ROLLBACK";
const std::string SmartDB::COMMIT = "COMMIT";
}
|
#ifndef AWEAPON_HPP
# define AWEAPON_HPP
#include <iostream>
class AWeapon
{
private:
AWeapon(void);
std::string name;
int shoot_cost;
int damage_hit;
public:
AWeapon(std::string const & name, int apcost, int damage);
AWeapon(AWeapon const & src);
virtual ~AWeapon();
std::string virtual getName() const;
int getAPCost() const;
int getDamage() const;
void setName(std::string name);
void setAPCost(int apcost);
void setDamage(int dmg);
virtual void attack() const = 0;
AWeapon & operator=(AWeapon const & rhs);
};
#endif
|
#pragma once
#include "bricks/java/jobject.h"
#include "bricks/java/jmethoddelegate.h"
#include "bricks/collections/array.h"
namespace Bricks { namespace Java { namespace Internal {
template<typename T> struct JArrayTypeConversion;
#define BRICKS_JAVA_JARRAYTYPECONVERSION(T, JT) \
template<> struct JArrayTypeConversion<T> { typedef JT##Array Type; }
BRICKS_JAVA_TYPES_CONVERSION(BRICKS_JAVA_JARRAYTYPECONVERSION);
#undef BRICKS_JAVA_JARRAYTYPECONVERSION
template<typename T> struct JArrayValueTypeConversion;
#define BRICKS_JAVA_JARRAYVALUETYPECONVERSION(T, JT) \
template<> struct JArrayValueTypeConversion<T> { typedef JT Type; }
BRICKS_JAVA_TYPES_CONVERSION(BRICKS_JAVA_JARRAYVALUETYPECONVERSION);
#undef BRICKS_JAVA_JARRAYTYPECONVERSION
template<typename T> struct JArrayType;
#define BRICKS_JAVA_JARRAYTYPE(T, name) \
template<> struct JArrayType<T> \
{ \
typedef JArrayTypeConversion<T>::Type JType; \
typedef JArrayValueTypeConversion<T>::Type Type; \
static jsize GetLength(JVM* vm, JType array) { return vm->GetEnv()->GetArrayLength(array); } \
static JType CreateArray(JVM* vm, jsize length) { return vm->GetEnv()->New##name##Array(length); } \
static Type* GetItems(JVM* vm, JType array) { return vm->GetEnv()->Get##name##ArrayElements(array, NULL); } \
static void ReleaseItems(JVM* vm, JType array, Type* items) { vm->GetEnv()->Release##name##ArrayElements(array, items, 0); } \
static void GetItems(JVM* vm, JType array, Type* buffer, jsize offset, jsize length) { vm->GetEnv()->Get##name##ArrayRegion(array, offset, length, buffer); } \
static void SetItems(JVM* vm, JType array, const Type* buffer, jsize offset, jsize length) { vm->GetEnv()->Set##name##ArrayRegion(array, offset, length, buffer); } \
}
BRICKS_JAVA_TYPES(BRICKS_JAVA_JARRAYTYPE);
#undef BRICKS_JAVA_JARRAYTYPE
} } }
namespace Bricks { namespace Java { namespace Lang {
template<typename T, typename E = void> class Array : public JObject
{
public:
typedef typename Internal::JArrayType<T>::JType JType;
typedef typename Internal::JArrayType<T>::Type Type;
protected:
void CreateArray(const T* data, int length)
{
reference = Internal::JArrayType<T>::CreateArray(vm, length);
if (data)
SetItems(data, 0, length);
clazz = autonew JClass(vm, reference);
}
void CreateArray(const Collections::List<T>* array)
{
CreateArray(NULL, array->GetCount());
Type* items = Internal::JArrayType<T>::GetItems(vm, GetJArray());
Type* itemsIter = items;
BRICKS_FOR_EACH (const T item, array)
*(itemsIter++) = item;
Internal::JArrayType<T>::ReleaseItems(vm, GetJArray(), items);
}
public:
Array(JVM* vm, const T* data, int length) :
JObject(vm, NULL)
{
CreateArray(data, length);
}
Array(const T* data, int length) :
JObject(JVM::GetCurrentVM(), NULL)
{
CreateArray(data, length);
}
Array(JVM* vm, int length) :
JObject(vm, NULL)
{
CreateArray(NULL, length);
}
Array(int length) :
JObject(JVM::GetCurrentVM(), NULL)
{
CreateArray(NULL, length);
}
Array(JVM* vm, const Collections::List<T>* array) :
JObject(vm, NULL)
{
CreateArray(array);
}
Array(const Collections::List<T>* array) :
JObject(JVM::GetCurrentVM(), NULL)
{
CreateArray(array);
}
Array(JClass* clazz, jobject object, bool global = false) :
JObject(clazz, object, global)
{
}
Array(JVM* vm, jobject object, bool global = false) :
JObject(vm, object, global)
{
}
Array(JReference* reference) :
JObject(reference)
{
}
JType GetJArray() const { return (JType)GetObject(); }
ReturnPointer<Collections::Array<T> > GetArray() const;
int GetCount()
{
return Internal::JArrayType<T>::GetLength(vm, GetJArray());
}
T GetItem(int index)
{
Type ret;
Internal::JArrayType<T>::GetItems(vm, GetJArray(), &ret, index, 1);
return ret;
}
void SetItem(int index, T value)
{
Internal::JArrayType<T>::SetItems(vm, GetJArray() &value, index, 1);
}
void GetItems(T* buffer, int offset, int length)
{
Internal::JArrayType<T>::GetItems(vm, GetJArray(), buffer, offset, length);
}
void SetItems(const T* buffer, int offset, int length)
{
Internal::JArrayType<T>::SetItems(vm, GetJArray(), buffer, offset, length);
}
};
template<typename T> class Array<T, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<JObject, T>::Value>::Type> : public JObject
{
public:
typedef jobjectArray JType;
protected:
template<typename U>
void CreateArray(int length, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<Internal::JQualifiedObjectBase, U>::Value, JClass>::Type* dummy = NULL)
{
reference = vm->GetEnv()->NewObjectArray(length, T::Class::GetClass(vm), NULL);
clazz = autonew JClass(vm, reference);
}
void CreateArray(int length, JClass* clazz)
{
reference = vm->GetEnv()->NewObjectArray(length, clazz->GetClass(), NULL);
clazz = autonew JClass(vm, reference);
}
template<typename U>
void CreateArray(const Collections::List<U>* array, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<JReference, U>::Value>::Type* dummy = NULL)
{
int index = 0;
BRICKS_FOR_EACH (const U& item, array)
vm->GetEnv()->SetObjectArrayElement(GetJArray(), index++, item->GetReference());
}
template<typename U>
void CreateArray(const Collections::List<U*>* array, typename SFINAE::EnableIf<SFINAE::IsCompatibleType<JReference, U>::Value>::Type* dummy = NULL)
{
int index = 0;
BRICKS_FOR_EACH (const U* item, array)
vm->GetEnv()->SetObjectArrayElement(GetJArray(), index++, item->GetReference());
}
public:
Array(JVM* vm, int length) : JObject(vm, NULL) { CreateArray<T>(length); }
Array(int length) : JObject(JVM::GetCurrentVM(), NULL) { CreateArray<T>(length); }
template<typename U>
Array(JVM* vm, const Collections::List<U>* array) : JObject(vm, NULL) { CreateArray<T>(array->GetCount()); CreateArray(array); }
template<typename U>
Array(const Collections::List<U>* array) : JObject(JVM::GetCurrentVM(), NULL) { CreateArray<T>(array->GetCount()); CreateArray(array); }
Array(JVM* vm, JClass* clazz, int length) : JObject(vm, NULL) { CreateArray(length, clazz); }
Array(JClass* clazz, int length) : JObject(JVM::GetCurrentVM(), NULL) { CreateArray(length, clazz); }
template<typename U>
Array(JVM* vm, JClass* clazz, const Collections::List<U>* array) : JObject(vm, NULL) { CreateArray(array->GetCount(), clazz); CreateArray(array); }
template<typename U>
Array(JClass* clazz, const Collections::List<U>* array) : JObject(JVM::GetCurrentVM(), NULL) { CreateArray(array->GetCount(), clazz); CreateArray(array); }
Array(JClass* clazz, jobject object, bool global = false) : JObject(clazz, object, global) { }
Array(JVM* vm, jobject object, bool global = false) : JObject(vm, object, global) { }
Array(JReference* reference) : JObject(reference) { }
JType GetJArray() const { return (JType)GetObject(); }
ReturnPointer<Collections::Array<T> > GetArray() const;
int GetCount()
{
return Internal::JArrayType<T>::GetLength(vm, GetJArray());
}
T GetItem(int index)
{
return Internal::TypeConversion<T>::Convert(vm->GetEnv()->GetObjectArrayElement(GetJArray(), index));
}
void SetItem(int index, T value)
{
vm->GetEnv()->SetObjectArrayElement(GetJArray(), index, Internal::TypeConversion<T>::trevnoC(value));
}
};
} } }
namespace Bricks { namespace Java { namespace Internal {
template<typename T> struct JSignature<Lang::Array<T> > { static String Signature() { return "[" + JSignature<T>::Signature(); } };
template<typename T> struct JSignature<Collections::Array<T> > { static String Signature() { return JSignature<Lang::Array<T> >::Signature(); } };
template<typename T> struct TypeConversion<Collections::Array<T> >
{
typedef ReturnPointer<Collections::Array<T> > Type;
static Type Convert(JReference* value)
{
return Lang::Array<T>(value).GetArray();
}
static jobject trevnoC(const Collections::Array<T>* value)
{
return Lang::Array<T>(value).GetReference();
}
};
} } }
|
//
// Created by 송지원 on 2020/07/17.
//
#include <iostream>
using namespace std;
int N, R, C;
void func(int r, int c, int n, int CNT) {
if (n == 1) {
for (int i=0; i<2; i++) {
for (int j=0; j<2; j++) {
if (r+i == R && c+j == C) cout << CNT + 2*i + j;
// cout <<"("<<r+i<<", "<<c+j<<") :"<<CNT + 2*i + j<<endl;
}
}
// return CNxT + 4;
return;
}
int m = n-1;
int nm = 1<<m;
func(r, c, m, CNT);
func(r, c + nm, m, CNT + nm*nm);
func(r + nm, c, m, CNT + 2*nm*nm);
func(r + nm, c + nm, m, CNT + 3*nm*nm);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> R >> C;
func(0, 0, N, 0);
}
|
#include<iostream>
#include<deque>
using namespace std;
void DFS(int v);
int visited[5]= {0};
int arc[5][5]= {
{0,0,1,1,0},
{0,0,1,0,0},
{1,1,0,1,0},
{1,0,1,0,1},
{0,0,0,1,0}
};
int main() {
DFS(4);
}
void DFS(int v) {
visited[v]=1;
cout<<(v+1);
for(int i=0; i<5; ++i) {
if(arc[v][i]==1) {
if(visited[i]!=1) {
DFS(i);
}
}
}
}
void BFS(int v) {
deque<int> Q;
visited[v]=1;
cout<<(v+1);
Q.push_back(v);
while(!Q.empty()) {
Q.pop_front()
}
for(int i=0; i<5; i++) {
if(arc[v][i]==1) {
if(visited[i]!=1) {
Q.pop_front();
}
}
}
}
|
//#include <SFML/Graphics.hpp>
//#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
#include <conio.h>
#include "Game.h"
#include <fstream>
string Path = "D:\\Ali\\Repos\\Quest\\Quest\\Quest\\";
//---------------------------------------------------------------------------------------
bool loadTextureFromFile(Texture &T, string Path)
{
bool ret = T.loadFromFile(Path);
ifstream t(Path);
if (t.bad())
ret = false;
int size = 7298;
char *s = new char[size];
t.read(s, size);
ret = T.loadFromMemory(s, size);
delete[] s;
return ret;
}
//---------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
/*
char P[256];
strcpy_s(P, argv[0]);
*strrchr(P, '\\') = '\0';
Path = P;
Path += "\\";
*/
std::FILE* m_file = std::fopen((Path + "Textures\\Jake_Shine.png").c_str(), "rb");
ifstream map(Path + "Map\\map.txt");
// ifstream map("Textures\\Jake_Shine.png");
for (int i = 0; i < height; i++)
{
string buffer;
getline(map, buffer);
// for (int j = 0; j < width; j++)
{
// if (buffer[j] == ' ')
//field[i][j] = 0;
// else
// field[i][j] = buffer[j];
}
}
map.close();
Texture mapTexture;
Texture heroTexture;
Texture DinoTexture;
Sprite mapSprite;
Sprite heroSprite;
Sprite DinoSprite;
if (!loadTextureFromFile(heroTexture, Path + "j.png"))
return 1;
if (!loadTextureFromFile(DinoTexture, Path + "d.png"))
return 1;
if (!loadTextureFromFile(mapTexture, Path + "c.png"))
return 1;
int key = 0;
noCursor(false);
srand(time(NULL));
Clock clock;
if (!getMySFML().LoadTextures())
{
return 1;
}
//Game::get().getPlayer()->Draw();
//Game::get().drawSkelet();
//while (true)
while (getMySFML().getWindow().isOpen())
{
float time = clock.getElapsedTime().asMicroseconds();
clock.restart();
time = time / 800;
Event event;
while (getMySFML().getWindow().pollEvent(event))
{
if (event.type == Event::Closed)
getMySFML().getWindow().close();
if (event.type == Event::KeyPressed)
{
if (event.key.code == Keyboard::W)
Game::get().getPlayer()->move(Up);
else if (event.key.code == Keyboard::S)
Game::get().getPlayer()->move(Down);
else if (event.key.code == Keyboard::A)
Game::get().getPlayer()->move(Left);
else if (event.key.code == Keyboard::D)
Game::get().getPlayer()->move(Right);
}
}
//if (_kbhit())
//{
// key = _getch();
// Direction dir = GetDirection(key);
// Game::get().getPlayer()->move(dir);
//}
//if (key == AttackDefence::AttackKey)
//{
// Game::get().getPlayer()->attack();
//}
//else
getMySFML().getWindow().clear();
// Game::get().Draw();
getMySFML().getWindow().draw(getMySFML().getSpriteHero());
getMySFML().getWindow().draw(getMySFML().getSpriteDino());
getMySFML().getWindow().display();
Sleep(100);
//Game::get().skeletMove();
//Sleep(100);
//SetCoord({0, 32});
//cout << " ";
//SetCoord({0, 32 });
//cout << Game::get().getPlayer()->getHp();
//if (Game::get().getPlayer()->getHp() == 0)
// break;
}
//SetCoord({ 0, 34 });
//cout << "Game Over!" << endl;
//system("pause");
return 0;
}
//---------------------------------------------------------------------------------------
//int main()
//{
// sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
// sf::CircleShape shape(100.f);
// shape.setFillColor(sf::Color::Green);
//
// while (window.isOpen())
// {
// sf::Event event;
// while (window.pollEvent(event))
// {
// if (event.type == sf::Event::Closed)
// window.close();
// }
//
// window.clear();
// window.draw(shape);
// window.display();
// }
//
// return 0;
//}
//---------------------------------------------------------------------------------------
//#include <SFML/Graphics.hpp>
//#include <windows.h>
//#include <iostream>
//#include <time.h>
//
//using namespace sf;
//
//enum Cell { EMPTY, WALL };
//
//void print(Cell arr[10][10])
//{
// system("cls");
// for (int i = 0; i < 10; i++)
// {
// for (int j = 0; j < 10; j++)
// {
// std::cout << arr[i][j];
// }
// std::cout << std::endl;
// }
//}
//
//int main()
//{
// srand(time(0));
// RenderWindow window(VideoMode(500, 500), "Hello!");
// Cell arr[10][10] = {};
//
// for (int i = 0; i < 20; i++)
// {
// arr[rand() % 10][rand() % 10] = WALL;
// }
//
// Texture grasst;
// grasst.loadFromFile("Textures/floor.png");
// Texture wallt;
// wallt.loadFromFile("wall.png");
// RectangleShape empty(Vector2f(50, 50));
// empty.setTexture(&grasst);
// RectangleShape wall(Vector2f(50, 50));
// wall.setTexture(&wallt);
//
// CircleShape circle(25);
// circle.setFillColor(Color::Blue);
//
// while (window.isOpen())
// {
// Event event;
// while (window.pollEvent(event))
// {
// if (event.type == sf::Event::Closed)
// window.close();
//
// if (event.type == Event::KeyPressed)
// {
// if (event.key.code == Keyboard::Up)
// circle.move(0, -10);
// else if (event.key.code == Keyboard::Down)
// circle.move(0, +10);
// else if (event.key.code == Keyboard::Left)
// circle.move(-10, 0);
// else if (event.key.code == Keyboard::Right)
// circle.move(+10, 0);
// }
// }
//
// //Keyboard::isKeyPressed(Keyboard::A)
//
// window.clear();
// for (int i = 0; i < 10; i++)
// {
// for (int j = 0; j < 10; j++)
// {
// if (arr[i][j] == EMPTY)
// {
// empty.setPosition(j * 50, i * 50);
// window.draw(empty);
// }
// else if (arr[i][j] == WALL)
// {
// wall.setPosition(j * 50, i * 50);
// window.draw(wall);
// }
// }
//
// }
// window.draw(circle);
// window.display();
// //print(arr);
// }
//
// return 0;
//}
//--------------------------------------------------------------------------------------------
|
#ifndef __VIVADO_SYNTH__
#include <fstream>
using namespace std;
// Debug utility
ofstream* global_debug_handle;
#endif //__VIVADO_SYNTH__
#include "sbl_ur_2_opt_compute_units.h"
#include "hw_classes.h"
struct img_img_update_0_write0_merged_banks_12_cache {
// RAM Box: {[-2, 1920], [-1, 1080]}
// Capacity: 1926
// # of read delays: 6
hw_uint<16> f0;
hw_uint<16> f2;
fifo<hw_uint<16>, 960> f3;
hw_uint<16> f4;
hw_uint<16> f6;
fifo<hw_uint<16>, 960> f7;
hw_uint<16> f8;
hw_uint<16> f10;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline hw_uint<16> peek_961() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_962() {
return f4;
}
inline hw_uint<16> peek_963() {
return f6;
}
inline hw_uint<16> peek_1923() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f7.back();
}
inline hw_uint<16> peek_1924() {
return f8;
}
inline hw_uint<16> peek_1925() {
return f10;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f10 = f8;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 960
f8 = f7.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 960 reading from capacity: 1
f7.push(f6);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f6 = f4;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 960
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 960 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct img_img_update_0_write1_merged_banks_12_cache {
// RAM Box: {[-1, 1921], [-1, 1080]}
// Capacity: 1927
// # of read delays: 7
hw_uint<16> f0;
hw_uint<16> f2;
hw_uint<16> f4;
fifo<hw_uint<16>, 960> f5;
hw_uint<16> f6;
hw_uint<16> f8;
fifo<hw_uint<16>, 960> f9;
hw_uint<16> f10;
hw_uint<16> f12;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline hw_uint<16> peek_2() {
return f4;
}
inline hw_uint<16> peek_962() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f5.back();
}
inline hw_uint<16> peek_963() {
return f6;
}
inline hw_uint<16> peek_964() {
return f8;
}
inline hw_uint<16> peek_1924() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f9.back();
}
inline hw_uint<16> peek_1925() {
return f10;
}
inline hw_uint<16> peek_1926() {
return f12;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f12 = f10;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 960
f10 = f9.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 960 reading from capacity: 1
f9.push(f8);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f8 = f6;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 960
f6 = f5.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 960 reading from capacity: 1
f5.push(f4);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f4 = f2;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct img_cache {
img_img_update_0_write0_merged_banks_12_cache img_img_update_0_write0_merged_banks_12;
img_img_update_0_write1_merged_banks_12_cache img_img_update_0_write1_merged_banks_12;
};
inline void img_img_update_0_write0_write(hw_uint<16>& img_img_update_0_write0, img_cache& img, int d0, int d1) {
img.img_img_update_0_write0_merged_banks_12.push(img_img_update_0_write0);
}
inline void img_img_update_0_write1_write(hw_uint<16>& img_img_update_0_write1, img_cache& img, int d0, int d1) {
img.img_img_update_0_write1_merged_banks_12.push(img_img_update_0_write1);
}
inline hw_uint<16> mag_x_rd0_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd0 read pattern: { mag_x_update_0[d0, d1] -> img[-1 + 2d0, -1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_x_update_0[d0, d1] -> 1926 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_1926();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_x_rd1_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd1 read pattern: { mag_x_update_0[d0, d1] -> img[-1 + 2d0, d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_x_update_0[d0, d1] -> 964 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_964();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_x_rd10_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd10 read pattern: { mag_x_update_0[d0, d1] -> img[2 + 2d0, d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_x_update_0[d0, d1] -> 962 : 0 <= d0 <= 958 and 0 <= d1 <= 1079; mag_x_update_0[d0, d1] -> (3 + d0) : d0 = 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_962();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_x_rd11_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd11 read pattern: { mag_x_update_0[d0, d1] -> img[2 + 2d0, 1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_0();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_x_rd2_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd2 read pattern: { mag_x_update_0[d0, d1] -> img[-1 + 2d0, 1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_x_update_0[d0, d1] -> 2 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_2();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_x_rd3_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd3 read pattern: { mag_x_update_0[d0, d1] -> img[1 + 2d0, -1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_x_update_0[d0, d1] -> 1925 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_1925();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_x_rd4_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd4 read pattern: { mag_x_update_0[d0, d1] -> img[1 + 2d0, d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_x_update_0[d0, d1] -> 963 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_963();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_x_rd5_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd5 read pattern: { mag_x_update_0[d0, d1] -> img[1 + 2d0, 1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_x_update_0[d0, d1] -> 1 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_1();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_x_rd6_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd6 read pattern: { mag_x_update_0[d0, d1] -> img[2d0, -1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_x_update_0[d0, d1] -> 1925 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_1925();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_x_rd7_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd7 read pattern: { mag_x_update_0[d0, d1] -> img[2d0, d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_x_update_0[d0, d1] -> 963 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_963();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_x_rd8_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd8 read pattern: { mag_x_update_0[d0, d1] -> img[2d0, 1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_x_update_0[d0, d1] -> 1 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_1();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_x_rd9_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_x_rd9 read pattern: { mag_x_update_0[d0, d1] -> img[2 + 2d0, -1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_x_update_0[d0, d1] -> 1924 : 0 <= d0 <= 958 and 0 <= d1 <= 1079; mag_x_update_0[d0, d1] -> (965 + d0) : d0 = 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_1924();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd0_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd0 read pattern: { mag_y_update_0[d0, d1] -> img[-1 + 2d0, -1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_y_update_0[d0, d1] -> 1926 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_1926();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd1_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd1 read pattern: { mag_y_update_0[d0, d1] -> img[-1 + 2d0, 1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_y_update_0[d0, d1] -> 2 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_2();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd10_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd10 read pattern: { mag_y_update_0[d0, d1] -> img[2 + 2d0, -1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_y_update_0[d0, d1] -> 1924 : 0 <= d0 <= 958 and 0 <= d1 <= 1079; mag_y_update_0[d0, d1] -> (965 + d0) : d0 = 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_1924();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd11_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd11 read pattern: { mag_y_update_0[d0, d1] -> img[2 + 2d0, 1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_0();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd2_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd2 read pattern: { mag_y_update_0[d0, d1] -> img[2d0, -1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_y_update_0[d0, d1] -> 1925 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_1925();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd3_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd3 read pattern: { mag_y_update_0[d0, d1] -> img[2d0, 1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_y_update_0[d0, d1] -> 1 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_1();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd4_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd4 read pattern: { mag_y_update_0[d0, d1] -> img[1 + 2d0, -1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_y_update_0[d0, d1] -> 1925 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_1925();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd5_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd5 read pattern: { mag_y_update_0[d0, d1] -> img[1 + 2d0, 1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_y_update_0[d0, d1] -> 1 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_1();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd6_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd6 read pattern: { mag_y_update_0[d0, d1] -> img[2d0, -1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_y_update_0[d0, d1] -> 1925 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_1925();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd7_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd7 read pattern: { mag_y_update_0[d0, d1] -> img[2d0, 1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_y_update_0[d0, d1] -> 1 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write0 = img.img_img_update_0_write0_merged_banks_12.peek_1();
return value_img_img_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd8_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd8 read pattern: { mag_y_update_0[d0, d1] -> img[1 + 2d0, -1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_y_update_0[d0, d1] -> 1925 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_1925();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> mag_y_rd9_select(img_cache& img, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// mag_y_rd9 read pattern: { mag_y_update_0[d0, d1] -> img[1 + 2d0, 1 + d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { img_update_0[d0, d1] -> [d1, d0, 1] : -1 <= d0 <= 960 and -1 <= d1 <= 1080 }
// DD fold: { mag_y_update_0[d0, d1] -> 1 : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
auto value_img_img_update_0_write1 = img.img_img_update_0_write1_merged_banks_12.peek_1();
return value_img_img_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 3
// img_update_0_write
// img_img_update_0_write0
// img_img_update_0_write1
inline void img_img_update_0_write_bundle_write(hw_uint<32>& img_update_0_write, img_cache& img, int d0, int d1) {
hw_uint<16> img_img_update_0_write0_res = img_update_0_write.extract<0, 15>();
img_img_update_0_write0_write(img_img_update_0_write0_res, img, d0, d1);
hw_uint<16> img_img_update_0_write1_res = img_update_0_write.extract<16, 31>();
img_img_update_0_write1_write(img_img_update_0_write1_res, img, d0, d1);
}
// mag_x_update_0_read
// mag_x_rd0
// mag_x_rd1
// mag_x_rd2
// mag_x_rd3
// mag_x_rd4
// mag_x_rd5
// mag_x_rd6
// mag_x_rd7
// mag_x_rd8
// mag_x_rd9
// mag_x_rd10
// mag_x_rd11
inline hw_uint<192> img_mag_x_update_0_read_bundle_read(img_cache& img, int d0, int d1) {
// # of ports in bundle: 12
// mag_x_rd0
// mag_x_rd1
// mag_x_rd2
// mag_x_rd3
// mag_x_rd4
// mag_x_rd5
// mag_x_rd6
// mag_x_rd7
// mag_x_rd8
// mag_x_rd9
// mag_x_rd10
// mag_x_rd11
hw_uint<192> result;
hw_uint<16> mag_x_rd0_res = mag_x_rd0_select(img, d0, d1);
set_at<0, 192>(result, mag_x_rd0_res);
hw_uint<16> mag_x_rd1_res = mag_x_rd1_select(img, d0, d1);
set_at<16, 192>(result, mag_x_rd1_res);
hw_uint<16> mag_x_rd2_res = mag_x_rd2_select(img, d0, d1);
set_at<32, 192>(result, mag_x_rd2_res);
hw_uint<16> mag_x_rd3_res = mag_x_rd3_select(img, d0, d1);
set_at<48, 192>(result, mag_x_rd3_res);
hw_uint<16> mag_x_rd4_res = mag_x_rd4_select(img, d0, d1);
set_at<64, 192>(result, mag_x_rd4_res);
hw_uint<16> mag_x_rd5_res = mag_x_rd5_select(img, d0, d1);
set_at<80, 192>(result, mag_x_rd5_res);
hw_uint<16> mag_x_rd6_res = mag_x_rd6_select(img, d0, d1);
set_at<96, 192>(result, mag_x_rd6_res);
hw_uint<16> mag_x_rd7_res = mag_x_rd7_select(img, d0, d1);
set_at<112, 192>(result, mag_x_rd7_res);
hw_uint<16> mag_x_rd8_res = mag_x_rd8_select(img, d0, d1);
set_at<128, 192>(result, mag_x_rd8_res);
hw_uint<16> mag_x_rd9_res = mag_x_rd9_select(img, d0, d1);
set_at<144, 192>(result, mag_x_rd9_res);
hw_uint<16> mag_x_rd10_res = mag_x_rd10_select(img, d0, d1);
set_at<160, 192>(result, mag_x_rd10_res);
hw_uint<16> mag_x_rd11_res = mag_x_rd11_select(img, d0, d1);
set_at<176, 192>(result, mag_x_rd11_res);
return result;
}
// mag_y_update_0_read
// mag_y_rd0
// mag_y_rd1
// mag_y_rd2
// mag_y_rd3
// mag_y_rd4
// mag_y_rd5
// mag_y_rd6
// mag_y_rd7
// mag_y_rd8
// mag_y_rd9
// mag_y_rd10
// mag_y_rd11
inline hw_uint<192> img_mag_y_update_0_read_bundle_read(img_cache& img, int d0, int d1) {
// # of ports in bundle: 12
// mag_y_rd0
// mag_y_rd1
// mag_y_rd2
// mag_y_rd3
// mag_y_rd4
// mag_y_rd5
// mag_y_rd6
// mag_y_rd7
// mag_y_rd8
// mag_y_rd9
// mag_y_rd10
// mag_y_rd11
hw_uint<192> result;
hw_uint<16> mag_y_rd0_res = mag_y_rd0_select(img, d0, d1);
set_at<0, 192>(result, mag_y_rd0_res);
hw_uint<16> mag_y_rd1_res = mag_y_rd1_select(img, d0, d1);
set_at<16, 192>(result, mag_y_rd1_res);
hw_uint<16> mag_y_rd2_res = mag_y_rd2_select(img, d0, d1);
set_at<32, 192>(result, mag_y_rd2_res);
hw_uint<16> mag_y_rd3_res = mag_y_rd3_select(img, d0, d1);
set_at<48, 192>(result, mag_y_rd3_res);
hw_uint<16> mag_y_rd4_res = mag_y_rd4_select(img, d0, d1);
set_at<64, 192>(result, mag_y_rd4_res);
hw_uint<16> mag_y_rd5_res = mag_y_rd5_select(img, d0, d1);
set_at<80, 192>(result, mag_y_rd5_res);
hw_uint<16> mag_y_rd6_res = mag_y_rd6_select(img, d0, d1);
set_at<96, 192>(result, mag_y_rd6_res);
hw_uint<16> mag_y_rd7_res = mag_y_rd7_select(img, d0, d1);
set_at<112, 192>(result, mag_y_rd7_res);
hw_uint<16> mag_y_rd8_res = mag_y_rd8_select(img, d0, d1);
set_at<128, 192>(result, mag_y_rd8_res);
hw_uint<16> mag_y_rd9_res = mag_y_rd9_select(img, d0, d1);
set_at<144, 192>(result, mag_y_rd9_res);
hw_uint<16> mag_y_rd10_res = mag_y_rd10_select(img, d0, d1);
set_at<160, 192>(result, mag_y_rd10_res);
hw_uint<16> mag_y_rd11_res = mag_y_rd11_select(img, d0, d1);
set_at<176, 192>(result, mag_y_rd11_res);
return result;
}
#include "hw_classes.h"
struct mag_x_mag_x_update_0_write0_merged_banks_1_cache {
// RAM Box: {[0, 1918], [0, 1079]}
// Capacity: 1
// # of read delays: 1
fifo<hw_uint<16>, 1> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(0 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct mag_x_mag_x_update_0_write1_merged_banks_1_cache {
// RAM Box: {[1, 1919], [0, 1079]}
// Capacity: 1
// # of read delays: 1
fifo<hw_uint<16>, 1> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(0 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct mag_x_cache {
mag_x_mag_x_update_0_write0_merged_banks_1_cache mag_x_mag_x_update_0_write0_merged_banks_1;
mag_x_mag_x_update_0_write1_merged_banks_1_cache mag_x_mag_x_update_0_write1_merged_banks_1;
};
inline void mag_x_mag_x_update_0_write0_write(hw_uint<16>& mag_x_mag_x_update_0_write0, mag_x_cache& mag_x, int d0, int d1) {
mag_x.mag_x_mag_x_update_0_write0_merged_banks_1.push(mag_x_mag_x_update_0_write0);
}
inline void mag_x_mag_x_update_0_write1_write(hw_uint<16>& mag_x_mag_x_update_0_write1, mag_x_cache& mag_x, int d0, int d1) {
mag_x.mag_x_mag_x_update_0_write1_merged_banks_1.push(mag_x_mag_x_update_0_write1);
}
inline hw_uint<16> sbl_ur_2_rd0_select(mag_x_cache& mag_x, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// sbl_ur_2_rd0 read pattern: { sbl_ur_2_update_0[d0, d1] -> mag_x[2d0, d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { sbl_ur_2_update_0[d0, d1] -> [1 + d1, 1 + d0, 4] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// DD fold: { }
auto value_mag_x_mag_x_update_0_write0 = mag_x.mag_x_mag_x_update_0_write0_merged_banks_1.peek(/* one reader or all rams */ 0);
return value_mag_x_mag_x_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> sbl_ur_2_rd1_select(mag_x_cache& mag_x, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// sbl_ur_2_rd1 read pattern: { sbl_ur_2_update_0[d0, d1] -> mag_x[1 + 2d0, d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { sbl_ur_2_update_0[d0, d1] -> [1 + d1, 1 + d0, 4] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { mag_x_update_0[d0, d1] -> [1 + d1, 1 + d0, 3] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// DD fold: { }
auto value_mag_x_mag_x_update_0_write1 = mag_x.mag_x_mag_x_update_0_write1_merged_banks_1.peek(/* one reader or all rams */ 0);
return value_mag_x_mag_x_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// mag_x_update_0_write
// mag_x_mag_x_update_0_write0
// mag_x_mag_x_update_0_write1
inline void mag_x_mag_x_update_0_write_bundle_write(hw_uint<32>& mag_x_update_0_write, mag_x_cache& mag_x, int d0, int d1) {
hw_uint<16> mag_x_mag_x_update_0_write0_res = mag_x_update_0_write.extract<0, 15>();
mag_x_mag_x_update_0_write0_write(mag_x_mag_x_update_0_write0_res, mag_x, d0, d1);
hw_uint<16> mag_x_mag_x_update_0_write1_res = mag_x_update_0_write.extract<16, 31>();
mag_x_mag_x_update_0_write1_write(mag_x_mag_x_update_0_write1_res, mag_x, d0, d1);
}
// sbl_ur_2_update_0_read
// sbl_ur_2_rd0
// sbl_ur_2_rd1
inline hw_uint<32> mag_x_sbl_ur_2_update_0_read_bundle_read(mag_x_cache& mag_x, int d0, int d1) {
// # of ports in bundle: 2
// sbl_ur_2_rd0
// sbl_ur_2_rd1
hw_uint<32> result;
hw_uint<16> sbl_ur_2_rd0_res = sbl_ur_2_rd0_select(mag_x, d0, d1);
set_at<0, 32>(result, sbl_ur_2_rd0_res);
hw_uint<16> sbl_ur_2_rd1_res = sbl_ur_2_rd1_select(mag_x, d0, d1);
set_at<16, 32>(result, sbl_ur_2_rd1_res);
return result;
}
#include "hw_classes.h"
struct mag_y_mag_y_update_0_write0_merged_banks_1_cache {
// RAM Box: {[0, 1918], [0, 1079]}
// Capacity: 1
// # of read delays: 1
fifo<hw_uint<16>, 1> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(0 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct mag_y_mag_y_update_0_write1_merged_banks_1_cache {
// RAM Box: {[1, 1919], [0, 1079]}
// Capacity: 1
// # of read delays: 1
fifo<hw_uint<16>, 1> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(0 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct mag_y_cache {
mag_y_mag_y_update_0_write0_merged_banks_1_cache mag_y_mag_y_update_0_write0_merged_banks_1;
mag_y_mag_y_update_0_write1_merged_banks_1_cache mag_y_mag_y_update_0_write1_merged_banks_1;
};
inline void mag_y_mag_y_update_0_write0_write(hw_uint<16>& mag_y_mag_y_update_0_write0, mag_y_cache& mag_y, int d0, int d1) {
mag_y.mag_y_mag_y_update_0_write0_merged_banks_1.push(mag_y_mag_y_update_0_write0);
}
inline void mag_y_mag_y_update_0_write1_write(hw_uint<16>& mag_y_mag_y_update_0_write1, mag_y_cache& mag_y, int d0, int d1) {
mag_y.mag_y_mag_y_update_0_write1_merged_banks_1.push(mag_y_mag_y_update_0_write1);
}
inline hw_uint<16> sbl_ur_2_rd0_select(mag_y_cache& mag_y, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// sbl_ur_2_rd0 read pattern: { sbl_ur_2_update_0[d0, d1] -> mag_y[2d0, d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { sbl_ur_2_update_0[d0, d1] -> [1 + d1, 1 + d0, 4] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// DD fold: { }
auto value_mag_y_mag_y_update_0_write0 = mag_y.mag_y_mag_y_update_0_write0_merged_banks_1.peek(/* one reader or all rams */ 0);
return value_mag_y_mag_y_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> sbl_ur_2_rd1_select(mag_y_cache& mag_y, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// sbl_ur_2_rd1 read pattern: { sbl_ur_2_update_0[d0, d1] -> mag_y[1 + 2d0, d1] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Read schedule : { sbl_ur_2_update_0[d0, d1] -> [1 + d1, 1 + d0, 4] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// Write schedule: { mag_y_update_0[d0, d1] -> [1 + d1, 1 + d0, 2] : 0 <= d0 <= 959 and 0 <= d1 <= 1079 }
// DD fold: { }
auto value_mag_y_mag_y_update_0_write1 = mag_y.mag_y_mag_y_update_0_write1_merged_banks_1.peek(/* one reader or all rams */ 0);
return value_mag_y_mag_y_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// mag_y_update_0_write
// mag_y_mag_y_update_0_write0
// mag_y_mag_y_update_0_write1
inline void mag_y_mag_y_update_0_write_bundle_write(hw_uint<32>& mag_y_update_0_write, mag_y_cache& mag_y, int d0, int d1) {
hw_uint<16> mag_y_mag_y_update_0_write0_res = mag_y_update_0_write.extract<0, 15>();
mag_y_mag_y_update_0_write0_write(mag_y_mag_y_update_0_write0_res, mag_y, d0, d1);
hw_uint<16> mag_y_mag_y_update_0_write1_res = mag_y_update_0_write.extract<16, 31>();
mag_y_mag_y_update_0_write1_write(mag_y_mag_y_update_0_write1_res, mag_y, d0, d1);
}
// sbl_ur_2_update_0_read
// sbl_ur_2_rd0
// sbl_ur_2_rd1
inline hw_uint<32> mag_y_sbl_ur_2_update_0_read_bundle_read(mag_y_cache& mag_y, int d0, int d1) {
// # of ports in bundle: 2
// sbl_ur_2_rd0
// sbl_ur_2_rd1
hw_uint<32> result;
hw_uint<16> sbl_ur_2_rd0_res = sbl_ur_2_rd0_select(mag_y, d0, d1);
set_at<0, 32>(result, sbl_ur_2_rd0_res);
hw_uint<16> sbl_ur_2_rd1_res = sbl_ur_2_rd1_select(mag_y, d0, d1);
set_at<16, 32>(result, sbl_ur_2_rd1_res);
return result;
}
// Operation logic
inline void mag_y_update_0(img_cache& img, mag_y_cache& mag_y, int d0, int d1) {
// Consume: img
auto img_0_c__0_value = img_mag_y_update_0_read_bundle_read(img/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
*global_debug_handle << "mag_y_update_0_img," << d0<< "," << d1<< "," << img_0_c__0_value << endl;
#endif //__VIVADO_SYNTH__
auto compute_result = mag_y_generated_compute_unrolled_2(img_0_c__0_value);
// Produce: mag_y
mag_y_mag_y_update_0_write_bundle_write(compute_result, mag_y, d0, d1);
#ifndef __VIVADO_SYNTH__
hw_uint<32> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
hw_uint<16> debug_compute_result_lane_1;
set_at<0, 16, 16>(debug_compute_result_lane_1, debug_compute_result.extract<16, 31>());
*global_debug_handle << "mag_y_update_0," << (2*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
*global_debug_handle << "mag_y_update_0," << (2*d0 + 1) << ", " << d1<< "," << debug_compute_result_lane_1 << endl;
#endif //__VIVADO_SYNTH__
}
inline void mag_x_update_0(img_cache& img, mag_x_cache& mag_x, int d0, int d1) {
// Consume: img
auto img_0_c__0_value = img_mag_x_update_0_read_bundle_read(img/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
*global_debug_handle << "mag_x_update_0_img," << d0<< "," << d1<< "," << img_0_c__0_value << endl;
#endif //__VIVADO_SYNTH__
auto compute_result = mag_x_generated_compute_unrolled_2(img_0_c__0_value);
// Produce: mag_x
mag_x_mag_x_update_0_write_bundle_write(compute_result, mag_x, d0, d1);
#ifndef __VIVADO_SYNTH__
hw_uint<32> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
hw_uint<16> debug_compute_result_lane_1;
set_at<0, 16, 16>(debug_compute_result_lane_1, debug_compute_result.extract<16, 31>());
*global_debug_handle << "mag_x_update_0," << (2*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
*global_debug_handle << "mag_x_update_0," << (2*d0 + 1) << ", " << d1<< "," << debug_compute_result_lane_1 << endl;
#endif //__VIVADO_SYNTH__
}
inline void sbl_ur_2_update_0(mag_x_cache& mag_x, mag_y_cache& mag_y, HWStream<hw_uint<32> >& /* buffer_args num ports = 2 */sbl_ur_2, int d0, int d1) {
// Consume: mag_x
auto mag_x_0_c__0_value = mag_x_sbl_ur_2_update_0_read_bundle_read(mag_x/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
*global_debug_handle << "sbl_ur_2_update_0_mag_x," << d0<< "," << d1<< "," << mag_x_0_c__0_value << endl;
#endif //__VIVADO_SYNTH__
// Consume: mag_y
auto mag_y_0_c__0_value = mag_y_sbl_ur_2_update_0_read_bundle_read(mag_y/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
*global_debug_handle << "sbl_ur_2_update_0_mag_y," << d0<< "," << d1<< "," << mag_y_0_c__0_value << endl;
#endif //__VIVADO_SYNTH__
auto compute_result = sbl_ur_2_generated_compute_unrolled_2(mag_x_0_c__0_value, mag_y_0_c__0_value);
// Produce: sbl_ur_2
sbl_ur_2.write(compute_result);
#ifndef __VIVADO_SYNTH__
hw_uint<32> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
hw_uint<16> debug_compute_result_lane_1;
set_at<0, 16, 16>(debug_compute_result_lane_1, debug_compute_result.extract<16, 31>());
*global_debug_handle << "sbl_ur_2_update_0," << (2*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
*global_debug_handle << "sbl_ur_2_update_0," << (2*d0 + 1) << ", " << d1<< "," << debug_compute_result_lane_1 << endl;
#endif //__VIVADO_SYNTH__
}
inline void img_update_0(HWStream<hw_uint<32> >& /* buffer_args num ports = 2 */off_chip_img, img_cache& img, int d0, int d1) {
// Consume: off_chip_img
auto off_chip_img_0_c__0_value = off_chip_img.read();
auto compute_result = img_generated_compute_unrolled_2(off_chip_img_0_c__0_value);
// Produce: img
img_img_update_0_write_bundle_write(compute_result, img, d0, d1);
#ifndef __VIVADO_SYNTH__
hw_uint<32> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
hw_uint<16> debug_compute_result_lane_1;
set_at<0, 16, 16>(debug_compute_result_lane_1, debug_compute_result.extract<16, 31>());
*global_debug_handle << "img_update_0," << (2*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
*global_debug_handle << "img_update_0," << (2*d0 + 1) << ", " << d1<< "," << debug_compute_result_lane_1 << endl;
#endif //__VIVADO_SYNTH__
}
// Driver function
void sbl_ur_2_opt(HWStream<hw_uint<32> >& /* get_args num ports = 2 */off_chip_img, HWStream<hw_uint<32> >& /* get_args num ports = 2 */sbl_ur_2, uint64_t num_epochs) {
#ifndef __VIVADO_SYNTH__
ofstream debug_file("sbl_ur_2_opt_debug.csv");
global_debug_handle = &debug_file;
#endif //__VIVADO_SYNTH__
img_cache img;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
mag_x_cache mag_x;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
mag_y_cache mag_y;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
#ifdef __VIVADO_SYNTH__
#pragma HLS inline recursive
#endif // __VIVADO_SYNTH__
for (uint64_t epoch = 0; epoch < num_epochs; epoch++) {
#ifdef __VIVADO_SYNTH__
#pragma HLS inline recursive
#endif // __VIVADO_SYNTH__
for (int c0 = -1; c0 <= 1080; c0++) {
for (int c1 = -1; c1 <= 960; c1++) {
#ifdef __VIVADO_SYNTH__
#pragma HLS pipeline II=1
#endif // __VIVADO_SYNTH__
if ((-1 <= c1 && c1 <= 960) && ((c1 - 0) % 1 == 0) && (-1 <= c0 && c0 <= 1080) && ((c0 - 0) % 1 == 0)) {
img_update_0(off_chip_img, img, (c1 - 0) / 1, (c0 - 0) / 1);
}
if ((1 <= c1 && c1 <= 960) && ((c1 - 1) % 1 == 0) && (1 <= c0 && c0 <= 1080) && ((c0 - 1) % 1 == 0)) {
mag_y_update_0(img, mag_y, (c1 - 1) / 1, (c0 - 1) / 1);
}
if ((1 <= c1 && c1 <= 960) && ((c1 - 1) % 1 == 0) && (1 <= c0 && c0 <= 1080) && ((c0 - 1) % 1 == 0)) {
mag_x_update_0(img, mag_x, (c1 - 1) / 1, (c0 - 1) / 1);
}
if ((1 <= c1 && c1 <= 960) && ((c1 - 1) % 1 == 0) && (1 <= c0 && c0 <= 1080) && ((c0 - 1) % 1 == 0)) {
sbl_ur_2_update_0(mag_x, mag_y, sbl_ur_2, (c1 - 1) / 1, (c0 - 1) / 1);
}
}
}
}
#ifndef __VIVADO_SYNTH__
debug_file.close();
#endif //__VIVADO_SYNTH__
}
void sbl_ur_2_opt(HWStream<hw_uint<32> >& /* get_args num ports = 2 */off_chip_img, HWStream<hw_uint<32> >& /* get_args num ports = 2 */sbl_ur_2) {
sbl_ur_2_opt(off_chip_img, sbl_ur_2, 1);
}
#ifdef __VIVADO_SYNTH__
#include "sbl_ur_2_opt.h"
#define INPUT_SIZE 1040884
#define OUTPUT_SIZE 1036800
extern "C" {
static void read_input(hw_uint<32>* input, HWStream<hw_uint<32> >& v, const uint64_t size) {
hw_uint<32> burst_reg;
for (int i = 0; i < INPUT_SIZE*size; i++) {
#pragma HLS pipeline II=1
burst_reg = input[i];
v.write(burst_reg);
}
}
static void write_output(hw_uint<32>* output, HWStream<hw_uint<32> >& v, const uint64_t size) {
hw_uint<32> burst_reg;
for (int i = 0; i < OUTPUT_SIZE*size; i++) {
#pragma HLS pipeline II=1
burst_reg = v.read();
output[i] = burst_reg;
}
}
void sbl_ur_2_opt_accel(hw_uint<32>* img_update_0_read, hw_uint<32>* sbl_ur_2_update_0_write, const uint64_t size) {
#pragma HLS dataflow
#pragma HLS INTERFACE m_axi port = img_update_0_read offset = slave depth = 65536 bundle = gmem0
#pragma HLS INTERFACE m_axi port = sbl_ur_2_update_0_write offset = slave depth = 65536 bundle = gmem1
#pragma HLS INTERFACE s_axilite port = img_update_0_read bundle = control
#pragma HLS INTERFACE s_axilite port = sbl_ur_2_update_0_write bundle = control
#pragma HLS INTERFACE s_axilite port = size bundle = control
#pragma HLS INTERFACE s_axilite port = return bundle = control
static HWStream<hw_uint<32> > img_update_0_read_channel;
static HWStream<hw_uint<32> > sbl_ur_2_update_0_write_channel;
read_input(img_update_0_read, img_update_0_read_channel, size);
sbl_ur_2_opt(img_update_0_read_channel, sbl_ur_2_update_0_write_channel, size);
write_output(sbl_ur_2_update_0_write, sbl_ur_2_update_0_write_channel, size);
}
}
#endif //__VIVADO_SYNTH__
|
#include "basedataview.h"
#include "qcustomplot.h"
#include "statdatatool.h"
#include <QComboBox>
CBaseDataView::CBaseDataView(QWidget *parent)
: CStatViewBase(parent)
{
// m_mapFileName["frequency.dat"] = StatItemInfo("频率", "Hz");
// m_mapFileName["rms_vol.dat"] = StatItemInfo("电压有效值", "V");
// m_mapFileName["rms_cur.dat"] = StatItemInfo("电流有效值", "A");
// m_mapFileName["ang_vol.dat"] = StatItemInfo("电压相位角", "°");
// m_mapFileName["ang_cur.dat"] = StatItemInfo("电流相位角", "°");
// QMap<QString, StatItemInfo>::iterator ite = m_mapFileName.begin();
// for (; ite != m_mapFileName.end(); ++ite) {
// m_pCombDataSel->addItem(ite.value().chinese);
// }
// m_pCombDataSel->setCurrentIndex(0);
m_mapFileName.insert("frequency.dat",StatItemInfo("频率", "Hz"));
m_mapFileName.insert("rms_vol.dat",StatItemInfo("电压有效值", "V"));
m_mapFileName.insert("rms_cur.dat",StatItemInfo("电流有效值", "A"));
m_mapFileName.insert("ang_vol.dat",StatItemInfo("电压相位角", "°"));
m_mapFileName.insert("ang_cur.dat",StatItemInfo("电流相位角", "°"));
m_vecBoxName.append("频率");
m_vecBoxName.append("电压有效值");
m_vecBoxName.append("电流有效值");
m_vecBoxName.append("电压相位角");
m_vecBoxName.append("电流相位角");
for(int i=0;i<m_vecBoxName.size();i++)
{
m_pCombDataSel->addItem(m_vecBoxName.at(i));
}
m_pCombDataSel->setCurrentIndex(0);
}
CBaseDataView::~CBaseDataView()
{
}
//bool CBaseDataView::_getStatDataFromFile(QString statFilePath, StatDataPoints *points)
//{
// // 从统计文件中读取所有统计数据
// CStatDataTool tool;
// StatRecordInfo info;
// int idx = statFilePath.lastIndexOf('/');
// QString infoFilePath = statFilePath.left(idx + 1) + "stat.info";
// for (int i = 0; i != 4; i++)
// points[i].clear();
// // 先读取统计配置信息,获取起始时间以及统计数据数量
// if (!tool.ReadInfoFromFile(infoFilePath.toStdString(), info))
// return false;
// if (!tool.InitReadFile(statFilePath.toStdString(), _getStatPhaseCount(statFilePath)))
// return false;
// // 转化为显示的统计数据缓存起来
// StatDatas dats;
// if (!tool.ReadDataFromFile(0, info.statTotalCnt - 1, dats))
// return false;
// qDebug()<<"info.meaCfg.pt="<<info.meaCfg.pt;
// float params = 1;
// if (statFilePath.contains("rms_vol"))
// params = info.meaCfg.pt/1000;
// else if (statFilePath.contains("rms_cur"))
// params = 1;//info.meaCfg.ct;
// for (int i = 0; i != (int)dats.size(); i++) {
// UtcTime curTime = info.firstTime.toUtcTime();
// curTime.tv_sec += i * info.statCycle;
// DateTime curDate = curTime.toDateTime();
// QDateTime tmp(QDate(curDate.year, curDate.month, curDate.day),
// QTime(curDate.hour, curDate.minute, curDate.second, curDate.ms));
// StatOnePoint point[4];
// for (int j = 0; j != (int)dats.at(i).max_val.size(); j++)
// point[0].y.push_back(dats.at(i).max_val.at(j) * params);
// for (int j = 0; j != (int)dats.at(i).min_val.size(); j++)
// point[1].y.push_back(dats.at(i).min_val.at(j) * params);
// for (int j = 0; j != (int)dats.at(i).avg_val.size(); j++)
// point[2].y.push_back(dats.at(i).avg_val.at(j) * params);
// for (int j = 0; j != (int)dats.at(i).cp95_val.size(); j++)
// point[3].y.push_back(dats.at(i).cp95_val.at(j) * params);
// for (int j = 0; j != 4; j++) {
// point[j].x = tmp.toTime_t();
// points[j].push_back(point[j]);
// }
// }
// return true;
//}
|
/*
Copyright (c) 2014 Mircea Daniel Ispas
This file is part of "Push Game Engine" released under zlib license
For conditions of distribution and use, see copyright notice in Push.hpp
*/
#pragma once
#include "Math/Math.hpp"
#include "Serialization/Serialize.hpp"
#include <cmath>
namespace Push
{
struct Vector
{
Vector();
Vector(float xx, float yy);
Vector& operator+=(const Vector& rhs);
Vector& operator-=(const Vector& rhs);
Vector& operator*=(float rhs);
Vector& operator/=(float rhs);
float x;
float y;
template<typename Serializer>
void Serialize(Serializer& serializer);
};
template<typename Serializer>
void Vector::Serialize(Serializer& serializer)
{
Push::Serialize(serializer, "x", x);
Push::Serialize(serializer, "y", y);
}
inline Vector::Vector()
: x(0.f)
, y(0.f)
{
}
inline Vector::Vector(float xx, float yy)
: x(xx)
, y(yy)
{
}
inline Vector& Vector::operator+=(const Vector& rhs)
{
x += rhs.x;
y += rhs.y;
return *this;
}
inline Vector& Vector::operator-=(const Vector& rhs)
{
x -= rhs.x;
y -= rhs.y;
return *this;
}
inline Vector& Vector::operator*=(float rhs)
{
x *= rhs;
y *= rhs;
return *this;
}
inline Vector& Vector::operator/=(float rhs)
{
x /= rhs;
y /= rhs;
return *this;
}
inline Vector operator-(const Vector& vec)
{
return Vector(-vec.x, -vec.y);
}
inline Vector operator+(const Vector& left, const Vector& right)
{
return Vector(left.x + right.x, left.y + right.y);
}
inline Vector operator+(const Vector& left, float right)
{
return Vector(left.x + right, left.y + right);
}
inline Vector operator+(float left, const Vector& right)
{
return Vector(left + right.x, left + right.y);
}
inline Vector operator-(const Vector& left, const Vector& right)
{
return Vector(left.x - right.x, left.y - right.y);
}
inline Vector operator-(const Vector& left, float right)
{
return Vector(left.x - right, left.y - right);
}
inline Vector operator-(float left, const Vector& right)
{
return Vector(left - right.x, left - right.y);
}
inline Vector operator*(const Vector& left, float right)
{
return Vector(left.x * right, left.y * right);
}
inline Vector operator*(float left, const Vector& right)
{
return Vector(left * right.x, left * right.y);
}
inline Vector operator/(const Vector& left, float right)
{
return Vector(left.x / right, left.y / right);
}
inline Vector operator/(float left, const Vector& right)
{
return Vector(left / right.x, left / right.y);
}
inline float Length(const Vector& vec)
{
return std::sqrtf(vec.x * vec.x + vec.y * vec.y);
}
inline void Normalize(Vector& vec)
{
const float oneOverLength = 1.f / Length(vec);
vec.x *= oneOverLength;
vec.y *= oneOverLength;
}
}
|
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <algorithm>
#include <memory.h>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <string>
#include <string.h>
#include <vector>
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const ld PI = acos(-1.);
using namespace std;
const int N = 1000111;
int a[N];
int f[N][11];
int n;
void relax(int& x, int y) {
if (x > y) x = y;
}
int main() {
//freopen("in", "r", stdin);
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", a + i);
}
memset(f, 63, sizeof(f));
f[0][5 + a[0]] = 0;
for (int i = 0; i + 1 < n; ++i) {
for (int j = 0; j <= 10; ++j) {
int w = j - 5;
if (w == 0) {
if (a[i + 1] >= 0) {
relax(f[i + 1][ a[i + 1] + 5 ], f[i][j]);
}
} else {
int cnt = 0;
int pos = 5 + a[i + 1];
while (pos >= 0 && pos <= 10) {
if (pos >= j) {
relax(f[i + 1][pos], f[i][j] + cnt);
}
pos += w;
++cnt;
}
}
}
}
/*
for (int i = 0; i < n; ++i)
for (int j = 0; j <= 10; ++j)
if (f[i][j] < 1000)
printf("%d %d: %d\n", i, j - 5, f[i][j]);
*/
int ans = f[n - 1][0];
for (int i = 0; i <= 10; ++i) {
ans = min(ans, f[n - 1][i]);
}
if (ans > 1e9) {
puts("BRAK");
return 0;
}
cout << ans << endl;
return 0;
}
|
#include <Adafruit_NeoPixel.h>
#include "Words.h"
const int8_t PROGMEM
fireBears[] = {
1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1,
1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,
1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1,
1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1,
1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1};
Words::Words(void) { }
void Words::reset(variables_t *vars) {
}
void Words::loop(variables_t *vars) {
int prog = (millis()/500)%6;
if(prog >= 5) {
vars->toQuit = 1;
return;
}
int i, j;
for (i = 0; i < 30; i++) {//draw
if(fireBears[i+(30*prog)]) {
vars->color[i]=Animation::getColor(i,1, vars->isCopper);
}else{
vars->color[i]=Adafruit_NeoPixel::Color(0,0,0);
}
}
// delay(5);
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e10
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define MAX 100
#define MUL 10e9
ll mul = MUL + 7;
ll N;
std::vector<ll> data;
int main() {
cin >> N;
rep(i,N) {
ll a;
scanf("%lld", &a);
data.push_back(a);
}
int bucket[N];
rep(i,N) bucket[i] = 0;
bool flag = false;
for (auto itr = data.begin(); itr != data.end(); ++itr) {
bucket[*itr]++;
if (*itr != 0) {
if (bucket[*itr] > 2) {
flag = true;
}
} else {
if (bucket[*itr] > 1) {
flag = true;
}
}
if (flag) {
cout << 0 << endl;
return 0;
}
}
ll bin = data.size() / 2;
ll ans = 1;
rep(i,bin) {
ans *= 2;
}
cout << ans % mul << endl;
}
|
/**
* heap.h
* Heap class -- implements a min heap with ability to change a weight already in the heap.
*
* Entries in the heap are keyed by a unique string so the weight can subsequently be changed
* and so when the min weight is dequeued it can also be identified by its key for use by the client.
*
* Min heap. Elements are key:weight pairs. Operations are:
1. construct from set of key:weight pairs, Θ(n)
2. enqueue a new or existing key with its current weight, Θ(log n) worst case
3. dequeue the key with the minimum weight, Θ(log n)
4. empty tells if the heap is empty, Θ(1)
*
* @author Kevin Lundeen, Seattle University
* @see CPSC5031, Winter 2018, HW #8
*/
#pragma once
#include <string>
#include <vector>
#include <map>
class Heap {
public:
typedef int Weight;
typedef std::string Key;
typedef std::vector<Key> HeapArray;
typedef std::map<Key, Weight> WeightMap;
/**
* Data structure used to return a key:weight pair.
*/
struct KeyWeight {
Key key;
Weight weight;
KeyWeight() : key(""), weight(0) {}
KeyWeight(Key k, Weight w) : key(k), weight(w) {}
};
Heap() {}
~Heap() {}
/**
* Construct a heap from the given initial list, Θ(n) time.
* @param initial start with these keys and their weights
*/
Heap(const WeightMap& initial);
/**
* Check if there are more key:weight pairs in the heap.
* @return True if no more items in the heap.
*/
bool empty() const;
/**
* Put key into heap with given weight. If key is already present, this will change the weight and repair
* the heap as necessary.
* @param key key which is to be added or modified
* @param weight desired weight for given key
*/
void enqueue(Key key, int weight);
/**
* Remove minimum element and return its key and weight.
* @return the key:weight of the minimum weight in the heap.
*/
KeyWeight dequeue();
/**
* Get a list of all the key:weight pairs currently in the heap.
* @return list of key:weight pairs (arbitrary order)
*/
const WeightMap& weightMap() const;
private:
typedef std::map<Key, int> PlaceMap;
HeapArray heap;
WeightMap weights;
PlaceMap place;
int last() const;
int parent(int i) const;
int leftChild(int p) const;
int rightChild(int p) const;
Weight weight(int i) const;
void swapUp(int i);
void swapDown(int p);
void heapConstruct();
};
|
#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <type_traits>
#include <unistd.h>
#include <unordered_set>
#include <string>
#include <vector>
unsigned in_row = 0;
void row_check()
{
in_row++;
// TODO: Make this dynamic
if(in_row >= 8)
{
std::cout << std::endl;
in_row = 0;
}
}
void print_sgr_str(std::string const& value_str)
{
std::cout << std::setw(4) << value_str << ": \e[" << value_str << "m" << "test" << "\e[m";
row_check();
}
void print_sgr(int value)
{
print_sgr_str(std::to_string(value));
}
// r,g,b in range 0-255
struct ColorRGB
{
float r = 0, g = 0, b = 0;
ColorRGB() = default;
ColorRGB(float r_, float g_, float b_)
: r(r_), g(g_), b(b_) {}
};
// h in range 0-360, s,v in range 0-1
struct ColorHSV
{
float h, s, v;
};
// https://www.rapidtables.com/convert/color/hsv-to-rgb.html
ColorRGB hsv_to_rgb(ColorHSV const& in)
{
assert(in.h >= 0 && in.h <= 360);
assert(in.s >= 0 && in.s <= 1);
assert(in.v >= 0 && in.v <= 1);
float C = in.v * in.s;
float Hp = static_cast<int>(in.h) / 60.f;
float X = C * (1 - std::abs(std::fmod(Hp, 2.f) - 1));
ColorRGB rgb_p;
if(Hp >= 0 && Hp <= 1)
rgb_p = ColorRGB(C, X, 0);
else if(Hp > 1 && Hp <= 2)
rgb_p = ColorRGB(X, C, 0);
else if(Hp > 2 && Hp <= 3)
rgb_p = ColorRGB(0, C, X);
else if(Hp > 3 && Hp <= 4)
rgb_p = ColorRGB(0, X, C);
else if(Hp > 4 && Hp <= 5)
rgb_p = ColorRGB(X, 0, C);
else if(Hp > 5 && Hp <= 6)
rgb_p = ColorRGB(C, 0, X);
float m = in.v - C;
return ColorRGB((rgb_p.r + m) * 255, (rgb_p.g + m) * 255, (rgb_p.b + m) * 255);
}
std::string sgr_rgb_from_color(ColorRGB const& in)
{
return "2;" + std::to_string(static_cast<int>(in.r)) + ";" + std::to_string(static_cast<int>(in.g)) + ";" + std::to_string(static_cast<int>(in.b));
}
void wrap()
{
std::cout << std::endl;
in_row = 0;
}
void print_label(std::string const& value)
{
std::cout << std::endl << std::endl << "\e[m" << value << std::endl << std::endl;
in_row = 0;
}
class TestRunner
{
public:
TestRunner(std::unordered_set<std::string> const& input_types)
: m_types(resolve_types(input_types)) {}
template<class Callback>
void test(std::string const& label, std::string const& type, Callback&& callback) const
{
if(m_types.count(type))
{
print_label(label + " (" + type + ")");
callback();
}
}
private:
std::unordered_set<std::string> m_types;
static std::unordered_set<std::string> resolve_types(std::unordered_set<std::string> const& type_names);
};
#define CONTINUE_IF_TRUE(...) if(__VA_ARGS__) continue;
std::unordered_set<std::string> TestRunner::resolve_types(std::unordered_set<std::string> const& type_names)
{
std::unordered_set<std::string> output;
auto expand_types = [&output](std::string const& type, std::string const& input, std::unordered_set<std::string> const& expand) {
if(type == input)
{
auto sub_types = resolve_types(expand);
output.insert(sub_types.begin(), sub_types.end());
return true;
}
return false;
};
for(auto& type: type_names)
{
CONTINUE_IF_TRUE(expand_types(type, "sgr_standard", {"sgr_fg", "sgr_bg"}));
CONTINUE_IF_TRUE(expand_types(type, "sgr_color", {"sgr_standard", "sgr_256", "sgr_rgb"}));
CONTINUE_IF_TRUE(expand_types(type, "sgr", {"sgr_basic", "sgr_color"}));
CONTINUE_IF_TRUE(expand_types(type, "all", {"sgr"}));
output.insert(type);
}
return output;
}
int main(int argc, char** argv)
{
if(!isatty(1))
{
std::cerr << "This program must run in a TTY." << std::endl;
return 0;
}
std::string tests_string;
if(argc == 1)
tests_string = "all";
else if(argc == 2)
{
tests_string = argv[1];
if(tests_string == "--help")
{
std::cerr << "Usage: " << argv[0] << " [<tests>|--help]" << std::endl;
std::cerr << "------------------------------------------" << std::endl;
std::cerr << "type: Tests to run (comma-separated):" << std::endl;
std::cerr << " - sgr_basic: SGR basic" << std::endl;
std::cerr << " - sgr_fg: SGR foreground" << std::endl;
std::cerr << " - sgr_bg: SGR foreground" << std::endl;
std::cerr << " - sgr_256: SGR 256-color" << std::endl;
std::cerr << " - sgr_rgb: SGR RGB" << std::endl;
std::cerr << "------------------------------------------" << std::endl;
std::cerr << " - sgr_standard = sgr_fg, sgr_bg" << std::endl;
std::cerr << " - sgr_color = sgr_standard, sgr_256, sgr_rgb" << std::endl;
std::cerr << " - sgr = sgr_basic, sgr_color" << std::endl;
std::cerr << " - all = sgr" << std::endl;
std::cerr << "------------------------------------------" << std::endl;
return 1;
}
}
auto runner = TestRunner([&tests_string]() {
std::unordered_set<std::string> out;
std::istringstream iss(tests_string);
while(!iss.eof())
{
std::string test;
while(true)
{
char c = iss.peek();
if(iss.peek() == ',' || iss.eof())
break;
test += c;
iss.ignore(1);
}
out.insert(test);
}
return out;
}());
runner.test("SGR: Basic", "sgr_basic", []() {
for(int i = 1; i <= 29; i++)
print_sgr(i);
wrap();
for(int i = 50; i <= 75; i++)
print_sgr(i);
});
runner.test("SGR: Foreground", "sgr_fg", []() {
for(int i = 30; i <= 37; i++)
print_sgr(i);
print_sgr(39);
wrap();
for(int i = 90; i <= 97; i++)
print_sgr(i);
print_sgr(99);
});
runner.test("SGR: Background", "sgr_bg", []() {
for(int i = 40; i <= 47; i++)
print_sgr(i);
print_sgr(49);
wrap();
for(int i = 100; i <= 107; i++)
print_sgr(i);
print_sgr(109);
});
runner.test("SGR: 256-Color", "sgr_256", []() {
std::cout << "Std ";
for(size_t s = 0; s < 16; s++)
{
std::cout << "\e[48;5;" << s << "m ";
}
std::cout << "\e[m" << std::endl;
for(size_t s = 0; s < 6; s++)
{
std::cout << std::left << std::setw(5) << s * 36;
for(size_t t = 0; t < 36; t++)
{
std::cout << "\e[48;5;" << 16 + s * 36 + t << "m ";
}
std::cout << "\e[m" << std::endl;
}
std::cout << "Gray ";
for(size_t s = 232; s < 256; s++)
{
std::cout << "\e[48;5;" << s << "m ";
}
std::cout << "\e[m";
});
runner.test("SGR: RGB Color", "sgr_rgb", []() {
for(float h = 0; h < 16; h++)
{
float h1 = (h * 2) * 360 / 32;
float h2 = (h * 2 + 1) * 360 / 32;
std::cout << " h=" << std::setw(3) << static_cast<int>(h1) << " | ";
for(float v = 0; v < 32; v++)
{
std::cout << "\e[38;" << sgr_rgb_from_color(hsv_to_rgb(ColorHSV{h1, v / 32.f, 1})) << "m"
<< "\e[48;" << sgr_rgb_from_color(hsv_to_rgb(ColorHSV{h2, v / 32.f, 1})) << "m"
<< "▀";
}
std::cout << "\e[0m" << std::endl;
}
});
std::cout << std::endl;
return 0;
}
|
// Include necessary modules for Adafruit motor shield
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"
#define A_pin 2
#define B_pin 3
#define num_ticks 1440
// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *panMotor = AFMS.getMotor(2);
int motorspeed = 0;
float angle;
volatile int counter;
volatile int counterA;
volatile int counterB;
volatile int counterC;
double time;
double ptime;
float kp = 2;
float ki = 0.005;
float target_angle = 90;
void setup() {
Serial.begin(9600);
pinMode(A_pin, INPUT);
pinMode(B_pin, INPUT);
// enable internal pullup resistors
digitalWrite(A_pin, 1);
digitalWrite(B_pin, 1);
// using encoders
attachInterrupt(0, ISRchanA, CHANGE);
attachInterrupt(1, ISRchanB, CHANGE);
// Start motor shield
AFMS.begin();
//tell PySerial you're ready to go
Serial.print("Initialized!");
}
void loop() {
angle = (counter % num_ticks) / 4.;
panMotor->run(BACKWARD);
panMotor->setSpeed(100);
time = millis();
if (time - ptime > 500) {
Serial.println(counter);
Serial.println(counterA);
Serial.println(counterB);
Serial.println(counterC);
Serial.println("");
ptime = time;
}
}
void ISRchanA()
{
if (digitalRead(A_pin) == digitalRead(B_pin)) {
counter++;
} else {
counterA--;
}
}
void ISRchanB()
{
if (digitalRead(A_pin) == digitalRead(B_pin)) {
counterB--;
} else {
counterC++;
}
}
|
#include <SoftwareWire.h>
#include "ssd1306_lib.h"
SSD1306 screen;
void setup() {
// put your setup code here, to run once:
SSD1306_Init(&screen, 2, 3);
while(SSD1306_Loop(&screen)) delayMicroseconds(100);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
SSD1306_Display(&screen);
while(SSD1306_Loop(&screen)) delayMicroseconds(100);
Serial.println("done");
while(1) {}
}
|
#include "globals.h"
#include "physics.h"
#include "game.h"
#include "math_extra.h"
#include <math.h>
/**
* Allocate and initialize a new Goal object.
*
*
* @param[in] x The x location of the goal
* @param[in] y The y location of the goal
* @return The newly initialized goal.
*/
Goal* create_goal(int x, int y) {
Goal* goal = (Goal*) malloc(sizeof(Goal));
goal->type = GOAL;
goal->x = x;
goal->y = y;
goal->radius = 6;
return goal;
}
/**
* Computes the physics update for a goal.
*
* @param[out] phys The result physics update. Assumed valid at function start.
* @param[in] ball The ball to update
* @param[in] goal The goal to that is interacting
*/
int do_goal(Physics* next, const Physics* curr, Goal* goal)
{
double xdist = (double)(curr->px)-(goal->x);
double ydist = (double)(curr->py)-(goal->y);
double dist = pow(pow(ydist,2.0)+pow(xdist,2.0),0.5);
if (dist < 5.0) {
return 1;
}
return 0;
}
/**
* Draws a given goal to the screen.
*
* @param[in] goal The goal to draw
*/
void draw_goal(Goal* goal)
{
uLCD.filled_circle(goal->x,goal->y,goal->radius,WHITE);
}
|
/****************************************************************
File Name: phase4.C
Author: Tian Zhang, CS Dept., Univ. of Wisconsin-Madison, 1995
Copyright(c) 1995 by Tian Zhang
All Rights Reserved
Permission to use, copy and modify this software must be granted
by the author and provided that the above copyright notice appear
in all relevant copies and that both that copyright notice and this
permission notice appear in all relevant supporting documentations.
Comments and additions may be sent the author at zhang@cs.wisc.edu.
******************************************************************/
#include "global.h"
#include "util.h"
#include "timeutil.h"
#include "vector.h"
#include "rectangle.h"
#include "cfentry.h"
#include "cutil.h"
#include "parameter.h"
#include "status.h"
#include "phase4.h"
extern Para* Paras;
static int ClosestNorm(double tmpnorm,double *norms,int start,int end)
{
if (end-start==1) {
if (tmpnorm>norms[end]) return end;
if (tmpnorm<norms[start]) return start;
if (tmpnorm-norms[start]<norms[end]-tmpnorm)
return start;
else return end;
}
int median=(start+end)/2;
if (tmpnorm>norms[median])
return ClosestNorm(tmpnorm,norms,median,end);
else return ClosestNorm(tmpnorm,norms,start,median);
}
static int MinLargerThan(double tmpnorm,double *norms,int start,int end)
{
int median;
if (start>=end) return start;
median=(start+end)/2;
if (tmpnorm>norms[median])
return MinLargerThan(tmpnorm,norms,median+1,end);
else return MinLargerThan(tmpnorm,norms,start,median);
}
static int MaxSmallerThan(double tmpnorm,double *norms,int start,int end)
{
int median;
if (start>=end) return start;
median=(start+end+1)/2;
if (tmpnorm<norms[median])
return MaxSmallerThan(tmpnorm,norms,start,median-1);
else return MaxSmallerThan(tmpnorm,norms,median,end);
}
static int ClosestCenter(int &i, double &idist, const Vector &v,
const Vector *centers, int imin, int imax,
const double *matrix, int n)
{
int k,count=0;
double d;
k=imin;
while (k<=imax) {
if (k<i && matrix[k*n-k*(k+1)/2+i-k-1]<=4*idist) {
d=v||centers[k]; count++;
if (d<idist) {idist=d;i=k;}
}
else if (k>i && matrix[i*n-i*(i+1)/2+k-i-1]<=4*idist) {
d=v||centers[k]; count++;
if (d<idist) {idist=d;i=k;}
}
k++;
}
return count;
}
static void ClosestCenter(int &imin, double &dmin, const Vector &v,
const Vector *centers, int num)
{
double d;
imin=0; dmin = v||centers[0];
for (int i=1; i<num; i++) {
d = v||centers[i];
if (d<dmin) {imin=i; dmin=d;}
}
}
static void Swap(Vector *centers, double *norms, int i, int j)
{
Vector tmpcenter;
tmpcenter.Init(centers[0].dim);
double tmpnorm;
tmpcenter=centers[i];
tmpnorm=norms[i];
centers[i]=centers[j];
norms[i]=norms[j];
centers[j]=tmpcenter;
norms[j]=tmpnorm;
}
/** Relevant to QuickSort: which is not critical because
it is only run once for each scan of the whole dataset. */
static void Swap(Vector *centers, double *norms, double *radii, int i, int j)
{
Vector tmpcenter;
tmpcenter.Init(centers[0].dim);
double tmpnorm;
double tmpradius;
tmpcenter=centers[i];
tmpnorm=norms[i];
tmpradius=radii[i];
centers[i]=centers[j];
norms[i]=norms[j];
radii[i]=radii[j];
centers[j]=tmpcenter;
norms[j]=tmpnorm;
radii[j]=tmpradius;
}
static int Split(Vector *centers, double *norms, int start, int end)
{
int median=(start+end)/2;
Swap(centers,norms,start,median);
int i=start+1;
int j=end;
while (i<=j) {
if (norms[i]<=norms[start]) i++;
else {Swap(centers,norms,i,j); j--;}
}
Swap(centers,norms,start,j);
return j;
}
static int Split(Vector *centers, double *norms, double *radii, int start, int end)
{
int median=(start+end)/2;
Swap(centers,norms,radii,start,median);
int i=start+1;
int j=end;
while (i<=j) {
if (norms[i]<=norms[start]) i++;
else {Swap(centers,norms,radii,i,j); j--;}
}
Swap(centers,norms,radii,start,j);
return j;
}
static void QuickSort(Vector *centers, double *norms, int start, int end)
{
int SplitPoint;
if (start<end) {SplitPoint=Split(centers,norms,start,end);
QuickSort(centers,norms,start,SplitPoint-1);
QuickSort(centers,norms,SplitPoint+1,end);
}
}
static void QuickSort(Vector *centers, double *norms, double *radii, int start, int end)
{
int SplitPoint;
if (start<end) {SplitPoint=Split(centers,norms,radii,start,end);
QuickSort(centers,norms,radii,start,SplitPoint-1);
QuickSort(centers,norms,radii,SplitPoint+1,end);
}
}
static int MaxRefinePass(Stat **Stats)
{
int maxpass=0;
for (int i=0; i<Paras->ntrees; i++)
if (Stats[i]->MaxRPass>maxpass) maxpass=Stats[i]->MaxRPass;
return maxpass;
}
static int RedistributeA(Stat* Stats,Vector* centers,double *radii,const Vector& tmpv)
{
int i;
double idist;
ClosestCenter(i,idist,tmpv,centers,Stats->CurrEntryCnt);
if (Stats->NoiseFlag==1 && idist>4*radii[i]) {
Stats->NoiseCnt++;
return -1;
}
else {
Stats->Entries[i].n += 1;
Stats->Entries[i].sx += tmpv;
Stats->Entries[i].sxx += (tmpv&&tmpv);
return i;
}
}
static void UpdateMatrix(int n, Vector *centers, double *matrix)
{
int i,j;
for (i=0;i<n-1;i++)
for (j=i+1;j<n;j++)
matrix[i*n-i*(i+1)/2+j-i-1]=centers[i]||centers[j];
}
static int RedistributeB(Stat* Stats,Vector* centers,double *norms,double *radii,double *matrix,const Vector& tmpv)
{
int imin,imax,i,k,n,start,end,median;
double d,tmpnorm,idist,tmpdist;
n=Stats->CurrEntryCnt;
tmpnorm=sqrt(tmpv&&tmpv);
// i=ClosestNorm(tmpnorm,norms,0,n-1);
// for efficiency, replace recursion by iteration
start=0;
end=n-1;
while(start<end) {
if (end-start==1) {
if (tmpnorm>norms[end]) i=start=end;
else if (tmpnorm<norms[start]) i=end=start;
else if (tmpnorm-norms[start]<norms[end]-tmpnorm)
i=end=start;
else i=start=end;
}
else {
median=(start+end)/2;
if (tmpnorm>norms[median]) start=median;
else end=median;
}
}
idist=tmpv||centers[i];
// imin=MinLargerThan(tmpnorm-sqrt(idist),norms,0,n-1);
// imax=MaxSmallerThan(tmpnorm+sqrt(idist),norms,0,n-1);
// for efficiency, replace recursion by iteration
tmpdist=tmpnorm-sqrt(idist);
start=0;
end=n-1;
while (start<end) {
median=(start+end)/2;
if (tmpdist>norms[median]) start=median+1;
else end=median;
}
imin=start;
tmpdist=tmpnorm+sqrt(idist);
start=0;
end=n-1;
while(start<end) {
median=(start+end+1)/2;
if (tmpdist<norms[median]) end=median-1;
else start=median;
}
imax=start;
// ClosestCenter(i,idist,tmpv,centers,imin,imax,matrix,n);
// for efficiency, replace procedure by inline
k=imin;
while (k<=imax) {
if (k<i && matrix[k*n-k*(k+1)/2+i-k-1]<=4*idist) {
d=tmpv||centers[k];
if (d<idist) {idist=d;i=k;}
}
else if (k>i && matrix[i*n-i*(i+1)/2+k-i-1]<=4*idist) {
d=tmpv||centers[k];
if (d<idist) {idist=d;i=k;}
}
k++;
}
if (Stats->NoiseFlag==1 && idist>4*radii[i]) {
Stats->NoiseCnt++;
return -1;
}
else {
Stats->Entries[i].n += 1;
Stats->Entries[i].sx += tmpv;
Stats->Entries[i].sxx += (tmpv&&tmpv);
return i;
}
}
void BirchPhase4(Stat **Stats)
{
std::ofstream tmpfile;
char tmpname[MAX_NAME];
int i, j, k, maxk, clusteri;
// 1. allocate space
Vector **centers = new Vector*[Paras->ntrees];
double **norms = new double*[Paras->ntrees];
double **radii = new double*[Paras->ntrees];
double **matrix = new double*[Paras->ntrees];
#ifdef LABEL
ofstream *labfiles=new ofstream[Paras->ntrees];
#endif LABEL
#ifdef FILTER
ofstream **filterfiles=new ofstream*[Paras->ntrees];
#endif FILTER
#ifdef SUMMARY
int **n = new int*[Paras->ntrees];
Vector **sx = new Vector*[Paras->ntrees];
Vector **sxx = new Vector*[Paras->ntrees];
#endif SUMMARY
for (i=0; i<Paras->ntrees; i++) {
centers[i]=new Vector[Stats[i]->CurrEntryCnt];
for (j=0;j<Stats[i]->CurrEntryCnt;j++)
centers[i][j].Init(Stats[i]->Dimension);
norms[i]=new double[Stats[i]->CurrEntryCnt];
radii[i]=new double[Stats[i]->CurrEntryCnt];
matrix[i]=new double[Stats[i]->CurrEntryCnt*(Stats[i]->CurrEntryCnt-1)/2];
#ifdef LABEL
sprintf(tmpname,"%s-label",Stats[i]->name);
labfiles[i].open(tmpname);
#endif LABEL
#ifdef FILTER
filterfiles[i]=new ofstream[Stats[i]->CurrEntryCnt];
for (j=0;j<Stats[i]->CurrEntryCnt;j++) {
sprintf(tmpname,"%s-dat-%d",Stats[i]->name,j);
filterfiles[i][j].open(tmpname);
}
#endif FILTER
#ifdef SUMMARY
n[i]=new int[Stats[i]->CurrEntryCnt];
sx[i]=new Vector[Stats[i]->CurrEntryCnt];
sxx[i]=new Vector[Stats[i]->CurrEntryCnt];
for (j=0;j<Stats[i]->CurrEntryCnt;j++) {
n[i][j]=0;
sx[i][j].Init(Paras->attrcnt);
sxx[i][j].Init(Paras->attrcnt);
}
#endif SUMMARY
}
// 2. prepare to read data
RecId recid1,recidi;
DevStatus dstat;
Paras->attrproj->FirstRecId(recid1);
Vector vector;
vector.Init(Paras->attrcnt);
VectorArray *vectors;
Paras->attrproj->CreateRecordList(vectors);
Vector *tmpvecs=new Vector[Paras->ntrees];
for (i=0;i<Paras->ntrees;i++)
tmpvecs[i].Init(Stats[i]->Dimension);
for (i=0;i<Paras->ntrees;i++) {
Stats[i]->Phase=4;
Stats[i]->Passi=0;
}
maxk=MaxRefinePass(Stats);
// 2.1 as long as there is one tree needed to refine
for (k=0; k<maxk; k++) {
// 1. find initial centers, radii, norms, matrix
for (i=0; i<Paras->ntrees; i++)
if (k<Stats[i]->MaxRPass) {
Stats[i]->Passi=k;
Stats[i]->NoiseCnt=0;
for (j=0; j<Stats[i]->CurrEntryCnt; j++) {
centers[i][j].Div(Stats[i]->Entries[j].sx,
Stats[i]->Entries[j].n);
radii[i][j]=Stats[i]->Entries[j].Radius();
Stats[i]->Entries[j]=0;
}
if (Stats[i]->RefineAlg==1) {
for (j=0; j<Stats[i]->CurrEntryCnt; j++)
norms[i][j]=sqrt(centers[i][j]&¢ers[i][j]);
QuickSort(centers[i],norms[i],radii[i],0,Stats[i]->CurrEntryCnt-1);
UpdateMatrix(Stats[i]->CurrEntryCnt,centers[i],matrix[i]);
}
}
// 2. scan data
for (recidi=recid1; ; recidi++) {
#ifdef FILTER
dstat=Paras->attrproj->ReadWholeRec(recidi,vector);
if (dstat!=StatusOk) break;
#endif FILTER
#ifdef SUMMARY
dstat=Paras->attrproj->ReadWholeRec(recidi,vector);
if (dstat!=StatusOk) break;
#endif SUMMARY
dstat=Paras->attrproj->ReadRec(recidi,*vectors);
if (dstat!=StatusOk) break;
for (i=0; i<Paras->ntrees; i++) {
if (k<Stats[i]->MaxRPass) {
tmpvecs[i]=*(vectors->GetVector(i));
if (Stats[i]->WMflag)
tmpvecs[i].Transform(Stats[i]->W,Stats[i]->M);
switch (Stats[i]->RefineAlg) {
case 0: clusteri=RedistributeA(Stats[i],centers[i],radii[i],tmpvecs[i]);
break;
case 1: clusteri=RedistributeB(Stats[i],centers[i],norms[i],radii[i],matrix[i],tmpvecs[i]);
break;
default: print_error("BirchPhase4","Invalid refine method");
break;
}
#ifdef LABEL
labfiles[i]<<clusteri<<std::endl;
#endif LABEL
#ifdef FILTER
filterfiles[i][clusteri]<<vector<<std::endl;
#endif FILTER
#ifdef SUMMARY
if (clusteri>=0) {
n[i][clusteri]++;
sx[i][clusteri]+=vector;
sxx[i][clusteri].AddSqr(vector);
}
#endif SUMMARY
}
}
}
}
delete vectors;
delete [] tmpvecs;
// 3 output results
for (i=0; i<Paras->ntrees; i++) {
delete [] centers[i];
delete [] norms[i];
delete [] radii[i];
delete [] matrix[i];
if (Stats[i]->MaxRPass>0) {
// quality and output
sprintf(tmpname,"%s-refcluster",Stats[i]->name);
tmpfile.open(tmpname);
Paras->logfile<<Stats[i]->name<<":"
<<"Quality of Phase4 "
<<Quality(Stats[i]->Qtype,
Stats[i]->CurrEntryCnt,
Stats[i]->Entries)
<<std::endl;
for (j=0;j<Stats[i]->CurrEntryCnt;j++)
tmpfile<<Stats[i]->Entries[j]<<std::endl;
tmpfile.close();
#ifdef LABEL
labfiles[i].close();
#endif LABEL
#ifdef FILTER
for (j=0;j<Stats[i]->CurrEntryCnt;j++)
filterfiles[i][j].close();
delete [] filterfiles[i];
#endif FILTER
#ifdef SUMMARY
sprintf(tmpname,"%s-summary",Stats[i]->name);
tmpfile.open(tmpname);
for (j=0;j<Stats[i]->CurrEntryCnt;j++)
tmpfile<<n[i][j]<<" "
<<sx[i][j]
<<sxx[i][j]
<<std::endl;
delete [] n[i];
delete [] sx[i];
delete [] sxx[i];
tmpfile.close();
#endif SUMMARY
}
}
delete [] centers;
delete [] norms;
delete [] radii;
delete [] matrix;
#ifdef LABEL
delete [] labfiles;
#endif LABEL
#ifdef FILTER
delete [] filterfiles;
#endif FILTER
#ifdef SUMMARY
delete [] n;
delete [] sx;
delete [] sxx;
#endif SUMMARY
}
|
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
vector<vector<int>> ans;
sort(arr.begin(), arr.end());
int min_diff = abs(arr[1]-arr[0]);
for(int i=0;i<arr.size()-1;i++)
{
int diff=0;
diff=abs(arr[i+1]-arr[i]);
min_diff=min(min_diff,diff);
}
for(int i=0;i<arr.size()-1;i++)
{
int diff=abs(arr[i+1]-arr[i]);
if(diff==min_diff)
{
vector<int>temp;
temp.push_back(arr[i]);
temp.push_back(arr[i+1]);
ans.push_back(temp);
}
}
return ans;
}
};
|
#ifndef EXTENSION_SUPERSONIC_H
#define EXTENSION_SUPERSONIC_H
namespace extension_supersonic {
int SampleMethod(int inputValue);
}
#endif
|
#include "time.h"
#include <iostream>
#include <sdl/SDL.h>
double time::_time_prev = 0;
double time::_time_fps_prev = 0;
uint time::_fps = 0;
float time::_dt = 0;
double time::get_time()
{
return SDL_GetPerformanceCounter() * 1000 / (double)SDL_GetPerformanceFrequency();
}
float time::get_delta_time()
{
return _dt;
}
void time::update()
{
double time_current = get_time();
_dt = time_current - _time_prev;
_time_prev = time_current;
if(get_time() - _time_fps_prev >= 1000)
{
std::cout << _fps <<std::endl;
_fps=0;
_time_fps_prev = get_time();
}
_fps++;
}
|
#pragma once
#include "Parametrizable.h"
class ExampleWidget : public QWidget, public Parametrizable
{
Q_OBJECT
public:
ExampleWidget(QWidget * parent = nullptr);
};
|
#pragma once
#include "../../Toolbox/Types.h"
#include "../Dependencies/OpenGL.h"
namespace ae
{
/// \ingroup graphics
/// <summary>When the texture will be sampled, determine how to chose the pixel color.</summary>
/// <remarks>https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexParameter.xhtml</remarks>
enum class TextureFilterMode : Int32
{
/// <summary>Nearest pixel ( Manhattan distance ).</summary>
Nearest = GL_NEAREST,
/// <summary>Average of the four neighboor ( more smooth ).</summary>
Linear = GL_LINEAR,
/// <summary>Chooses the mipmap that most closely matches the size of the pixel being textured and uses the GL_NEAREST criterion.</summary>
Nearest_MipMap_Nearest = GL_NEAREST_MIPMAP_NEAREST,
/// <summary>Chooses the two mipmaps that most closely match the size of the pixel being textured and uses the GL_NEAREST criterion.</summary>
Nearest_MipMap_Linear = GL_NEAREST_MIPMAP_LINEAR,
/// <summary>Chooses the mipmap that most closely matches the size of the pixel being textured and uses the GL_LINEAR criterion.</summary>
Linear_MipMap_Nearest = GL_LINEAR_MIPMAP_NEAREST,
/// <summary>Chooses the two mipmaps that most closely match the size of the pixel being textured and uses the GL_LINEAR criterion.</summary>
Linear_MipMap_Linear = GL_LINEAR_MIPMAP_LINEAR
};
}
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n, m, ans, f[maxn];
int main() {
scanf("%d%d", &n, &m);
int x, y;
for (int i = 1; i <= m; i++) {
scanf("%d", &x);
if (x == 0) {
scanf("%d%d", &x, &y);
for (int i = x; i <= y; i++)
f[i] ^= 1;
} else {
scanf("%d%d", &x, &y);
ans = 0;
for (int i = x; i <= y; i++)
if (f[i]) ans++;
printf("%d\n", ans);
}
}
return 0;
}
|
// Longest Increasing Sequence
#include <bits/stdc++.h>
using namespace std;
#define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll long long
int n;
vector<int> v,dp;
void solve(){
cin>>n;
v.resize(n);
dp.resize(n);
for(int i=0;i<n;i++){
cin>>v[i];
}
int best=0;
dp[0]=1;
for(int i=1;i<n;i++){
dp[i]=1;
for(int j=i-1;j>=0;j--){
if(v[j]<=v[i]) dp[i]=max(dp[i],dp[j]+1);
}
best=max(best,dp[i]);
}
cout<<best<<'\n';
}
int main(){
IOS;
solve();
return 0;
}
|
// Copyright (c) 1991-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 _gp_Lin_HeaderFile
#define _gp_Lin_HeaderFile
#include <gp_Ax1.hxx>
#include <gp_Ax2.hxx>
#include <gp_Dir.hxx>
#include <gp_Pnt.hxx>
#include <gp_Trsf.hxx>
#include <gp_Vec.hxx>
//! Describes a line in 3D space.
//! A line is positioned in space with an axis (a gp_Ax1
//! object) which gives it an origin and a unit vector.
//! A line and an axis are similar objects, thus, we can
//! convert one into the other. A line provides direct access
//! to the majority of the edit and query functions available
//! on its positioning axis. In addition, however, a line has
//! specific functions for computing distances and positions.
//! See Also
//! gce_MakeLin which provides functions for more complex
//! line constructions
//! Geom_Line which provides additional functions for
//! constructing lines and works, in particular, with the
//! parametric equations of lines
class gp_Lin
{
public:
DEFINE_STANDARD_ALLOC
//! Creates a Line corresponding to Z axis of the
//! reference coordinate system.
gp_Lin() {}
//! Creates a line defined by axis theA1.
gp_Lin (const gp_Ax1& theA1)
: pos (theA1)
{}
//! Creates a line passing through point theP and parallel to
//! vector theV (theP and theV are, respectively, the origin and
//! the unit vector of the positioning axis of the line).
gp_Lin (const gp_Pnt& theP, const gp_Dir& theV)
: pos (theP, theV)
{}
void Reverse()
{
pos.Reverse();
}
//! Reverses the direction of the line.
//! Note:
//! - Reverse assigns the result to this line, while
//! - Reversed creates a new one.
Standard_NODISCARD gp_Lin Reversed() const
{
gp_Lin aL = *this;
aL.pos.Reverse();
return aL;
}
//! Changes the direction of the line.
void SetDirection (const gp_Dir& theV) { pos.SetDirection (theV); }
//! Changes the location point (origin) of the line.
void SetLocation (const gp_Pnt& theP) { pos.SetLocation (theP); }
//! Complete redefinition of the line.
//! The "Location" point of <theA1> is the origin of the line.
//! The "Direction" of <theA1> is the direction of the line.
void SetPosition (const gp_Ax1& theA1) { pos = theA1; }
//! Returns the direction of the line.
const gp_Dir& Direction() const { return pos.Direction(); }
//! Returns the location point (origin) of the line.
const gp_Pnt& Location() const { return pos.Location(); }
//! Returns the axis placement one axis with the same
//! location and direction as <me>.
const gp_Ax1& Position() const { return pos; }
//! Computes the angle between two lines in radians.
Standard_Real Angle (const gp_Lin& theOther) const
{
return pos.Direction().Angle (theOther.pos.Direction());
}
//! Returns true if this line contains the point theP, that is, if the
//! distance between point theP and this line is less than or
//! equal to theLinearTolerance..
Standard_Boolean Contains (const gp_Pnt& theP, const Standard_Real theLinearTolerance) const
{
return Distance (theP) <= theLinearTolerance;
}
//! Computes the distance between <me> and the point theP.
Standard_Real Distance (const gp_Pnt& theP) const;
//! Computes the distance between two lines.
Standard_EXPORT Standard_Real Distance (const gp_Lin& theOther) const;
//! Computes the square distance between <me> and the point theP.
Standard_Real SquareDistance (const gp_Pnt& theP) const;
//! Computes the square distance between two lines.
Standard_Real SquareDistance (const gp_Lin& theOther) const
{
Standard_Real aD = Distance (theOther);
return aD * aD;
}
//! Computes the line normal to the direction of <me>, passing
//! through the point theP. Raises ConstructionError
//! if the distance between <me> and the point theP is lower
//! or equal to Resolution from gp because there is an infinity of
//! solutions in 3D space.
gp_Lin Normal (const gp_Pnt& theP) const;
Standard_EXPORT void Mirror (const gp_Pnt& theP);
//! Performs the symmetrical transformation of a line
//! with respect to the point theP which is the center of
//! the symmetry.
Standard_NODISCARD Standard_EXPORT gp_Lin Mirrored (const gp_Pnt& theP) const;
Standard_EXPORT void Mirror (const gp_Ax1& theA1);
//! Performs the symmetrical transformation of a line
//! with respect to an axis placement which is the axis
//! of the symmetry.
Standard_NODISCARD Standard_EXPORT gp_Lin Mirrored (const gp_Ax1& theA1) const;
Standard_EXPORT void Mirror (const gp_Ax2& theA2);
//! Performs the symmetrical transformation of a line
//! with respect to a plane. The axis placement <theA2>
//! locates the plane of the symmetry :
//! (Location, XDirection, YDirection).
Standard_NODISCARD Standard_EXPORT gp_Lin Mirrored (const gp_Ax2& theA2) const;
void Rotate (const gp_Ax1& theA1, const Standard_Real theAng) { pos.Rotate (theA1, theAng); }
//! Rotates a line. A1 is the axis of the rotation.
//! Ang is the angular value of the rotation in radians.
Standard_NODISCARD gp_Lin Rotated (const gp_Ax1& theA1, const Standard_Real theAng) const
{
gp_Lin aL = *this;
aL.pos.Rotate (theA1, theAng);
return aL;
}
void Scale (const gp_Pnt& theP, const Standard_Real theS) { pos.Scale (theP, theS); }
//! Scales a line. theS is the scaling value.
//! The "Location" point (origin) of the line is modified.
//! The "Direction" is reversed if the scale is negative.
Standard_NODISCARD gp_Lin Scaled (const gp_Pnt& theP, const Standard_Real theS) const
{
gp_Lin aL = *this;
aL.pos.Scale (theP, theS);
return aL;
}
void Transform (const gp_Trsf& theT) { pos.Transform (theT); }
//! Transforms a line with the transformation theT from class Trsf.
Standard_NODISCARD gp_Lin Transformed (const gp_Trsf& theT) const
{
gp_Lin aL = *this;
aL.pos.Transform (theT);
return aL;
}
void Translate (const gp_Vec& theV) { pos.Translate (theV); }
//! Translates a line in the direction of the vector theV.
//! The magnitude of the translation is the vector's magnitude.
Standard_NODISCARD gp_Lin Translated (const gp_Vec& theV) const
{
gp_Lin aL = *this;
aL.pos.Translate (theV);
return aL;
}
void Translate (const gp_Pnt& theP1, const gp_Pnt& theP2) { pos.Translate (theP1, theP2); }
//! Translates a line from the point theP1 to the point theP2.
Standard_NODISCARD gp_Lin Translated (const gp_Pnt& theP1, const gp_Pnt& theP2) const
{
gp_Lin aL = *this;
aL.pos.Translate (gp_Vec(theP1, theP2));
return aL;
}
private:
gp_Ax1 pos;
};
//=======================================================================
//function : Distance
// purpose :
//=======================================================================
inline Standard_Real gp_Lin::Distance (const gp_Pnt& theP) const
{
gp_XYZ aCoord = theP.XYZ();
aCoord.Subtract ((pos.Location()).XYZ());
aCoord.Cross ((pos.Direction()).XYZ());
return aCoord.Modulus();
}
//=======================================================================
//function : SquareDistance
// purpose :
//=======================================================================
inline Standard_Real gp_Lin::SquareDistance(const gp_Pnt& theP) const
{
const gp_Pnt& aLoc = pos.Location();
gp_Vec aV (theP.X() - aLoc.X(),
theP.Y() - aLoc.Y(),
theP.Z() - aLoc.Z());
aV.Cross (pos.Direction());
return aV.SquareMagnitude();
}
//=======================================================================
//function : Normal
// purpose :
//=======================================================================
inline gp_Lin gp_Lin::Normal(const gp_Pnt& theP) const
{
const gp_Pnt& aLoc = pos.Location();
gp_Dir aV (theP.X() - aLoc.X(),
theP.Y() - aLoc.Y(),
theP.Z() - aLoc.Z());
aV = pos.Direction().CrossCrossed (aV, pos.Direction());
return gp_Lin(theP, aV);
}
#endif // _gp_Lin_HeaderFile
|
#pragma once
class RotatingRoom;
class ShiftingPlatform : public hg::IComponent
{
public:
virtual int GetTypeID() const { return s_TypeID; }
static uint32_t s_TypeID;
void LoadFromXML( tinyxml2::XMLElement* data );
void Start();
void Update();
void OnEvent(const StrID& eventName);
void Extend();
void Retract();
bool IsExtending() { return m_ShiftActivated != 0 && m_Extended == 0; }
bool IsRetracting() { return m_ShiftActivated != 0 && m_Extended != 0; }
hg::IComponent* MakeCopyDerived() const;
private:
uint32_t m_Extended : 1;
uint32_t m_ShiftActivated : 1;
uint32_t m_WaitForExtend : 1;
Vector3 m_ExtendVector;
Vector3 m_ShiftStart;
Vector3 m_ShiftEnd;
RotatingRoom* m_RotRoom;
float m_ShiftLength;
float m_ShiftLengthInv;
float m_Timer;
};
|
#pragma once
class CommunityLayer
{
public:
CommunityLayer();
~CommunityLayer();
};
|
/*
Name: 链式 a + b
Copyright:
Author: Hill Bamboo
Date: 2019/9/9 15:45:23
Description:
归并排序 + 处理最后的carry
*/
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int v) : val(v), next(nullptr){
}
};
void printList(ListNode* list) {
ListNode* ph = list;
cout << "{";
while (ph != nullptr) {
cout << (ph->val) << " ";
ph = ph->next;
}
cout << "}";
}
class Plus {
public:
ListNode* plusAB(ListNode* a, ListNode* b) {
if (a == nullptr) return b;
if (b == nullptr) return a;
int carry = 0;
ListNode* pa = a;
ListNode* pb = b;
int sum = (pa->val + pb->val) % 10;
carry = (pa->val + pb->val) / 10;
ListNode* res = new ListNode(sum);
ListNode* head = res;
pa = pa->next;
pb = pb->next;
while (pa != nullptr && pb != nullptr) {
sum = (pa->val + pb->val + carry) % 10;
carry = (pa->val + pb->val + carry) / 10;
res->next = new ListNode(sum);
res = res->next;
pa = pa->next;
pb = pb->next;
}
while (pa != nullptr) {
sum = (pa->val + carry) % 10;
carry = (pa->val + carry) / 10;
res->next = new ListNode(sum);
res = res->next;
pa = pa->next;
}
while (pb != nullptr) {
sum = (pb->val + carry) % 10;
carry = (pb->val + carry) / 10;
res->next = new ListNode(sum);
res = res->next;
pb = pb->next;
}
if (carry > 0) res->next = new ListNode(carry);
return head;
}
};
class Plus2 {
public:
ListNode* plusAB(ListNode* a, ListNode* b) {
ListNode *pa = a, *pb = b;
ListNode* head = new ListNode(-1);
ListNode* res = head;
int sum = 0, carry = 0;
while (pa != nullptr || pb != nullptr || carry != 0) {
int v1 = (pa == nullptr ? 0 : pa->val);
int v2 = (pb == nullptr ? 0 : pb->val);
sum = (v1 + v2 + carry) % 10;
carry = (v1 + v2 + carry) / 10;
res->next = new ListNode(sum);
res = res->next;
pa = (pa == nullptr ? nullptr : pa->next);
pb = (pb == nullptr ? nullptr : pb->next);
}
return head->next;
}
};
int main() {
auto a = new ListNode(0);
auto pa = a;
for (int i : {1, 1}) {
pa->next = new ListNode(i);
pa = pa->next;
}
auto b = new ListNode(0);
auto pb = b;
auto res = Plus2().plusAB(a, b);
printList(res);
return 0;
}
|
#include "producteur.h"
/// @brief Le constructeur par défaut attribue les valeurs passée en paramètre.
///
/// Constructeur de la classe Producteur
///
/// @param n nom de l'utilisateur
/// @param pren prenom de l'utilisateur
/// @param pc @ref PointDeCollecte à associé à ce compte
Producteur::Producteur(std::string n, std::string pren, std::vector<PointDeCollecte> pc, Application app) : Utilisateur(n, pren, pc, app)
{
produitsFournis = GestionnaireProduits();
}
/// @brief Fonction qui reponds si le producteur est d'accord d'etre fournisseur
///
/// @param m Message le message a supprimer
///
///@return true si il accepte false sinon
void Producteur::repondreMessage(Message m, bool accept) {
if (accept) {
PointDeCollecte pc = goodBasket->getPC(m.getLieu());
pcFournis.push_back(pc);
}
removeMessage(m);
}
Producteur::~Producteur() {
pcFournis.clear();
delete &produitsFournis;
}
|
#if !defined (_8259_H_)
#define _8259_H_
#include <stddef.h>
#include <stdint.h>
#define PIC1 0x20 /* IO base address for leader PIC */
#define PIC2 0xA0 /* IO base address for follower PIC */
#define PIC1_COMMAND PIC1
#define PIC1_DATA (PIC1+1)
#define PIC2_COMMAND PIC2
#define PIC2_DATA (PIC2+1)
#define ICW1_ICW4 0x01 /* ICW4 (not) needed */
#define ICW1_SINGLE 0x02 /* Single (cascade) mode */
#define ICW1_INTERVAL4 0x04 /* Call address interval 4 (8) */
#define ICW1_LEVEL 0x08 /* Level triggered (edge) mode */
#define ICW1_INIT 0x10 /* Initialization - required! */
#define ICW4_8086 0x01 /* 8086/88 (MCS-80/85) mode */
#define ICW4_AUTO 0x02 /* Auto (normal) EOI */
#define ICW4_BUF_FOLLOWER 0x08 /* Buffered mode/follower */
#define ICW4_BUF_LEADER 0x0C /* Buffered mode/leader */
#define ICW4_SFNM 0x10 /* Special fully nested (not) */
#define PIC_READ_IRR 0x0a /* OCW3 irq ready next CMD read */
#define PIC_READ_ISR 0x0b /* OCW3 irq service next CMD read */
#define PIC_EOI 0x20
#define MAX_IRQ 16
#define LEADER_PIC_REMAP 0x30
#define FOLLOWER_PIC_REMAP 0x38
class G2PIC {
public:
G2PIC(uint8_t leaderOffset, uint8_t followerOffset);
void EOI(uint8_t irq);
void setMask(uint8_t line);
void clearMask(uint8_t line);
uint16_t getISR(void);
uint16_t getIRR(void);
void maskAll(void);
};
#endif
|
#include "regex.h"
Automaton autoOr(Automaton A, Automaton B) {
A.s->addTrans(0, B.s);
B.t->addTrans(0, A.t);
return A;
}
Automaton autoSeq(Automaton A, Automaton B) {
A.t->addTrans(0, B.s);
A.t = B.t;
return A;
}
Automaton autoStar(Automaton A) {
A.s->addTrans(0, A.t);
A.t->addTrans(0, A.s);
return A;
}
Automaton autoChar(char c) {
State *s = State::make();
State *t = State::make();
s->addTrans(c, t);
return Automaton(s, t);
}
vector<char> regex;
vector<bool> ctrl;
bool isOpen (int i) { return ctrl[i] && regex[i] == '('; }
bool isClose(int i) { return ctrl[i] && regex[i] == ')'; }
bool isStar (int i) { return ctrl[i] && regex[i] == '*'; }
bool isOr (int i) { return ctrl[i] && regex[i] == '|'; }
Automaton build(int lo, int hi) {
int firstClose = -1;
int level = 0;
for (int i = lo; i <= hi; ++i) {
if (isOpen(i)) ++level;
if (isClose(i)) --level;
if (isClose(i) && firstClose == -1 && level == 0) firstClose = i;
if (isOr(i) && level == 0)
return autoOr(build(lo, i - 1), build(i + 1, hi));
}
int mid = lo+1;
if (isOpen(lo)) mid = firstClose + 1;
bool star = false;
if (mid <= hi && isStar(mid)) {
++mid;
star = true;
}
Automaton A = isOpen(lo) ? build(lo + 1, firstClose - 1) : autoChar(regex[lo]);
if (star) A = autoStar(A);
if (mid > hi) return A;
return autoSeq(A, build(mid, hi));
}
Automaton regexAutomaton(string str) {
regex.clear();
ctrl.clear();
bool esc = false;
for (string::iterator it = str.begin(); it != str.end(); ++it) {
if (esc) {
if (*it == '_') regex.push_back(' ');
else if (*it == 'n') regex.push_back('\n');
else if (*it == 't') regex.push_back('\t');
else regex.push_back(*it);
ctrl.push_back(false);
esc = false;
} else if (*it == '\\') {
esc = true;
} else {
regex.push_back(*it == '$' ? 0 : *it);
ctrl.push_back(*it == '(' || *it == ')' || *it == '*' || *it == '|');
}
}
return build(0, regex.size()-1);
}
|
#include <iostream>
#include <vector>
#include "KDTree.h"
const static float pointList[7][2] = {
{3, 4},
{5, 6},
{9, 1},
{1, 6},
{20, 5},
{7, 300},
{9, 8}
};
int main()
{
auto v = PointList();
for (int i = 0; i < 7; ++i)
{
auto a = glm::vec3( pointList[i][0], pointList[i][1], 0 );
v.push_back(a);
}
auto kdtree = KDTree::build(v);
Point p = glm::vec3(3.5, 7.6, 0);
kdtree->contains(p);
std::cout << "Hello World!" << std::endl;
std::cout << kdtree->contains(p) << std::endl;
return 0;
}
|
#ifndef HEADER_CURL_MULTIIF_H
#define HEADER_CURL_MULTIIF_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* Prototypes for library-wide functions provided by multi.c
*/
namespace youmecommon
{
void Curl_expire(struct SessionHandle *data, long milli);
void Curl_expire_latest(struct SessionHandle *data, long milli);
bool Curl_multi_pipeline_enabled(const struct Curl_multi* multi);
void Curl_multi_handlePipeBreak(struct SessionHandle *data);
/* Internal version of curl_multi_init() accepts size parameters for the
socket and connection hashes */
struct Curl_multi *Curl_multi_handle(int hashsize, int chashsize);
/* the write bits start at bit 16 for the *getsock() bitmap */
#define GETSOCK_WRITEBITSTART 16
#define GETSOCK_BLANK 0 /* no bits set */
/* set the bit for the given sock number to make the bitmap for writable */
#define GETSOCK_WRITESOCK(x) (1 << (GETSOCK_WRITEBITSTART + (x)))
/* set the bit for the given sock number to make the bitmap for readable */
#define GETSOCK_READSOCK(x) (1 << (x))
#ifdef DEBUGBUILD
/*
* Curl_multi_dump is not a stable public function, this is only meant to
* allow easier tracking of the internal handle's state and what sockets
* they use. Only for research and development DEBUGBUILD enabled builds.
*/
void Curl_multi_dump(const struct Curl_multi *multi_handle);
#endif
void Curl_multi_process_pending_handles(struct Curl_multi *multi);
/* Return the value of the CURLMOPT_MAX_HOST_CONNECTIONS option */
size_t Curl_multi_max_host_connections(struct Curl_multi *multi);
/* Return the value of the CURLMOPT_MAX_PIPELINE_LENGTH option */
size_t Curl_multi_max_pipeline_length(struct Curl_multi *multi);
/* Return the value of the CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE option */
curl_off_t Curl_multi_content_length_penalty_size(struct Curl_multi *multi);
/* Return the value of the CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE option */
curl_off_t Curl_multi_chunk_length_penalty_size(struct Curl_multi *multi);
/* Return the value of the CURLMOPT_PIPELINING_SITE_BL option */
struct curl_llist *Curl_multi_pipelining_site_bl(struct Curl_multi *multi);
/* Return the value of the CURLMOPT_PIPELINING_SERVER_BL option */
struct curl_llist *Curl_multi_pipelining_server_bl(struct Curl_multi *multi);
/* Return the value of the CURLMOPT_MAX_TOTAL_CONNECTIONS option */
size_t Curl_multi_max_total_connections(struct Curl_multi *multi);
/*
* Curl_multi_closed()
*
* Used by the connect code to tell the multi_socket code that one of the
* sockets we were using is about to be closed. This function will then
* remove it from the sockethash for this handle to make the multi_socket API
* behave properly, especially for the case when libcurl will create another
* socket again and it gets the same file descriptor number.
*/
void Curl_multi_closed(struct connectdata *conn, curl_socket_t s);
}
#endif /* HEADER_CURL_MULTIIF_H */
|
// Copyright (c) 2020 albestro
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/init.hpp>
#include <pika/testing.hpp>
#include <atomic>
#include <string>
#include <vector>
std::atomic<bool> main_executed(false);
int pika_main()
{
main_executed = true;
return pika::finalize();
}
int main(int argc, char** argv)
{
std::vector<std::string> cfg = {"--pika:help"};
pika::init_params init_args;
init_args.cfg = cfg;
PIKA_TEST_EQ(pika::init(pika_main, argc, argv, init_args), 0);
PIKA_TEST(!main_executed);
return 0;
}
|
#include <ros/ros.h>
#include <ros/package.h>
#include <memory>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <exception>
#include <io_lib/io_utils.h>
#include <dmp_lib/DMP/DMP_eo.h>
#include <kf_lib/EKF.h>
#include <math_lib/quaternions.h>
#include <dmp_kf_test/utils.h>
using namespace as64_;
struct OrientStateTransCookie
{
arma::vec vRot;
double Ts;
OrientStateTransCookie(const arma::vec &vRot, double Ts)
{
this->vRot = vRot;
this->Ts = Ts;
}
};
struct OrientMsrCookie
{
std::shared_ptr<dmp_::DMP_eo> dmp_o;
double t;
arma::vec Q;
arma::vec vRot;
OrientMsrCookie(std::shared_ptr<dmp_::DMP_eo> dmp_o, double t, const arma::vec &Q, const arma::vec &vRot)
{
this->dmp_o = dmp_o;
this->t = t;
this->Q = Q;
this->vRot = vRot;
}
};
arma::vec oStateTransFun(const arma::vec &theta, void *cookie)
{
OrientStateTransCookie *ck = static_cast<OrientStateTransCookie *>(cookie);
arma::vec theta_next(theta.size());
arma::vec eo = theta.subvec(0,2);
arma::vec Qe = math_::quatExp(eo);
arma::vec rotVel = ck->vRot;
arma::vec deo = dmp_::DMP_eo::rotVel2deo(rotVel, Qe);
theta_next.subvec(0,2) = eo + deo*ck->Ts;
theta_next(3) = theta(3);
return theta_next;
}
arma::vec oMsrFun(const arma::vec &theta, void *cookie)
{
OrientMsrCookie *ck = static_cast<OrientMsrCookie *>(cookie);
arma::vec Q = ck->Q;
arma::vec eo_hat = theta.subvec(0,2);
arma::vec Qg_hat = math_::quatProd( math_::quatExp(eo_hat), Q);
double tau_hat = theta(3);
double x_hat = ck->t / tau_hat;
double tau0 = ck->dmp_o->getTau();
ck->dmp_o->setTau(tau_hat);
arma::vec Y_out = ck->dmp_o->calcRotAccel(x_hat, Q, ck->vRot, Qg_hat);
ck->dmp_o->setTau(tau0); // restore previous tau
return Y_out;
}
double dt;
arma::vec q0_offset;
arma::vec qg_offset;
double time_offset;
double tau_low_lim;
double tau_up_lim;
arma::vec process_noise;
double msr_noise;
double msr_noise_hat;
arma::vec init_params_variance;
double a_p;
arma::vec num_diff_step;
bool enable_constraints;
arma::mat M_r;
void loadParams()
{
ros::NodeHandle nh_("~");
if (!nh_.getParam("dt",dt)) throw std::runtime_error("Failed to load param \"dt\"...");
std::vector<double> temp;
if (!nh_.getParam("q0_offset",temp)) throw std::runtime_error("Failed to load param \"q0_offset\"...");
q0_offset = arma::vec(temp);
if (!nh_.getParam("qg_offset",temp)) throw std::runtime_error("Failed to load param \"qg_offset\"...");
qg_offset = arma::vec(temp);
if (!nh_.getParam("time_offset",time_offset)) throw std::runtime_error("Failed to load param \"time_offset\"...");
if (!nh_.getParam("tau_low_lim",tau_low_lim)) throw std::runtime_error("Failed to load param \"tau_low_lim\"...");
if (!nh_.getParam("tau_up_lim",tau_up_lim)) throw std::runtime_error("Failed to load param \"tau_up_lim\"...");
if (!nh_.getParam("process_noise",temp)) throw std::runtime_error("Failed to load param \"process_noise\"...");
process_noise = arma::vec(temp);
if (!nh_.getParam("msr_noise",msr_noise)) throw std::runtime_error("Failed to load param \"msr_noise\"...");
if (!nh_.getParam("msr_noise_hat",msr_noise_hat)) throw std::runtime_error("Failed to load param \"msr_noise_hat\"...");
if (!nh_.getParam("init_params_variance",temp)) throw std::runtime_error("Failed to load param \"init_params_variance\"...");
init_params_variance = arma::vec(temp);
if (!nh_.getParam("a_p",a_p)) throw std::runtime_error("Failed to load param \"a_p\"...");
if (!nh_.getParam("enable_constraints",enable_constraints)) throw std::runtime_error("Failed to load param \"enable_constraints\"...");
if (!nh_.getParam("num_diff_step",temp)) throw std::runtime_error("Failed to load param \"num_diff_step\"...");
num_diff_step = arma::vec(temp);
if (!nh_.getParam("M_r",temp)) throw std::runtime_error("Failed to load param \"M_r\"...");
M_r = arma::diagmat(arma::vec(temp));
}
int main(int argc, char** argv)
{
// =========== Initialize the ROS node ===============
ros::init(argc, argv, "dmp_ekf_orient_test_node");
ros::NodeHandle nh_("~");
std::string path = ros::package::getPath("dmp_kf_test");
loadParams();
int N_params = 4;
arma::mat A_c = arma::join_vert(arma::rowvec({0,0,0,-1}), arma::rowvec({0,0,0,1}));
arma::vec b_c = arma::vec({-tau_low_lim, tau_up_lim});
// =========== load DMP data ===============
std::string dmp_data_file = path + "/matlab/data/model/dmp_eo_data.bin";
std::ifstream in(dmp_data_file, std::ios::in | std::ios::binary);
if (!in) throw std::runtime_error("Failed to open file \"" + dmp_data_file + "\"...");
std::shared_ptr<dmp_::DMP_eo> dmp_o;
arma::vec Qg0;
arma::vec Q0d;
double tau0;
dmp_o = dmp_::DMP_eo::importFromFile(in);
io_::read_mat(Qg0, in);
io_::read_mat(Q0d, in);
io_::read_scalar(tau0, in);
in.close();
// ===========================================
std::shared_ptr<dmp_::CanonicalClock> can_clock_ptr = dmp_o->can_clock_ptr;
can_clock_ptr->setTau(tau0);
// DMP simulation
// set initial values
int Dim = 3;
double t = 0.0;
double x = 0.0;
double dx = 0.0;
arma::vec Q0 = math_::quatProd(math_::quatExp(q0_offset), Q0d);
arma::vec Q = Q0;
arma::vec vRot = arma::vec().zeros(Dim);
arma::vec dvRot = arma::vec().zeros(Dim);
arma::vec F_ext = arma::vec().zeros(Dim);
arma::rowvec Time;
arma::mat Q_data;
arma::mat vRot_data;
arma::mat dvRot_data;
arma::rowvec x_data;
arma::mat Qg_data;
arma::rowvec tau_data;
arma::mat F_data;
arma::mat Sigma_theta_data;
arma::vec Qg = math_::quatProd(math_::quatExp(qg_offset), Qg0);
double t_end = tau0 + time_offset;
double tau = t_end;
can_clock_ptr->setTau(tau);
double tau_hat = tau0;
arma::vec Qg_hat = Qg0;
arma::vec eo_hat = dmp_::DMP_eo::quat2eo(Q, Qg_hat);
double x_hat = t/tau_hat;
int N_out = vRot.size();
arma::vec Y_out_hat = arma::vec().zeros(N_out);
arma::vec Y_out = arma::vec().zeros(N_out);
arma::vec theta = arma::join_vert(eo_hat, arma::vec({tau_hat}));
arma::mat P_theta = arma::diagmat(init_params_variance);
arma::mat Rn_hat = arma::mat().eye(N_out,N_out) * msr_noise_hat;
arma::mat Qn = arma::diagmat(process_noise);
arma::arma_rng::set_seed(0);
arma::mat Rn = arma::mat().eye(N_out,N_out) * msr_noise;
arma::mat Sigma_vn = arma::sqrtmat_sympd(Rn);
// Set up EKF object
kf_::EKF ekf(theta, P_theta, N_out, &oStateTransFun, &oMsrFun);
ekf.setProcessNoiseCov(Qn);
ekf.setMeasureNoiseCov(Rn_hat);
// a_p = exp(a_pc*dt);
ekf.setFadingMemoryCoeff(a_p);
ekf.enableParamsContraints(enable_constraints);
ekf.setParamsConstraints(A_c, b_c);
ekf.setPartDerivStep(num_diff_step);
dmp_o->setQ0(Q0);
std::cout << "DMP-EKF (discrete) Orient simulation...\n";
arma::wall_clock timer;
timer.tic();
while (true)
{
// data logging
Time = arma::join_horiz(Time, arma::vec({t}));
Q_data = arma::join_horiz(Q_data, Q);
vRot_data = arma::join_horiz(vRot_data, vRot);
dvRot_data = arma::join_horiz(dvRot_data, dvRot);
Qg_data = arma::join_horiz(Qg_data, Qg_hat);
tau_data = arma::join_horiz(tau_data, arma::vec({tau_hat}));
x_data = arma::join_horiz(x_data, arma::vec({x}));
F_data = arma::join_horiz(F_data, F_ext);
Sigma_theta_data = arma::join_horiz(Sigma_theta_data, arma::sqrt(arma::vectorise(P_theta)));
// DMP simulation
dmp_o->setTau(tau_hat);
arma::vec dvRot_hat = dmp_o->calcRotAccel(x_hat, Q, vRot, Qg_hat);
dmp_o->setTau(tau);
dvRot = dmp_o->calcRotAccel(x, Q, vRot, Qg) + Sigma_vn*arma::vec().randn(N_out);
F_ext = M_r * (dvRot - dvRot_hat);
Y_out = dvRot;
// Y_out_hat = dvRot_hat;
// Update phase variable
dx = can_clock_ptr->getPhaseDot(x);
// Stopping criteria
double err_o = arma::norm( math_::quatLog( math_::quatProd(Qg,math_::quatInv(Q)) ) );
if (err_o <= 0.5e-2 & t>=t_end) break;
if (t>=t_end)
{
std::cerr << "Time limit reached. Stopping simulation...\n";
break;
}
// ======== KF measurement update ========
OrientMsrCookie msr_cookie(dmp_o, t, Q, vRot);
ekf.correct(Y_out, static_cast<void *>(&msr_cookie));
// ======== KF time update ========
OrientStateTransCookie state_cookie(vRot, dt);
ekf.predict(static_cast<void *>(&state_cookie));
theta = ekf.theta;
P_theta = ekf.P;
// Numerical integration
t = t + dt;
x = x + dx*dt;
Q = math_::quatProd( math_::quatExp(vRot*dt), Q );
vRot = vRot + dvRot*dt;
eo_hat = theta.subvec(0,2);
Qg_hat = math_::quatProd( math_::quatExp(eo_hat), Q);
tau_hat = theta(3);
x_hat = t/tau_hat;
}
std::cout << "Elapsed time: " << timer.toc() << " sec\n";
// =========== write results ===============
std::string sim_data_file = path + "/matlab/data/sim/sim_DMPeoEKFc_results.bin";
std::ofstream out(sim_data_file, std::ios::out | std::ios::binary);
if (!out) throw std::runtime_error("Failed to create file \"" + sim_data_file + "\"...");
io_::write_mat(Time, out);
io_::write_mat(Qg, out);
io_::write_mat(Qg_data, out);
io_::write_scalar(tau, out);
io_::write_mat(tau_data, out);
io_::write_mat(Sigma_theta_data, out);
io_::write_mat(F_data, out);
io_::write_mat(Q_data, out);
io_::write_mat(vRot_data, out);
out.close();
// =========== Shutdown ROS node ==================
ros::shutdown();
return 0;
}
|
#include "Renderer.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, -3.0f);
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);
Renderer::Renderer(Model* model, Shader* shader) :
m_model(model),
m_shader(shader)
{
}
void Renderer::render(RenderingEngine* renderingEngine)
{
glm::mat4 model;
model = glm::translate(model, getTransform().getPos());
model = glm::rotate(model, (float)glfwGetTime() * getTransform().getPos().x, glm::vec3(1.0f, 1.0f, 1.0f));
model = glm::scale(model, getTransform().getScale());
m_shader->bind();
//m_shader->setUniform("model", model);
//m_shader->setUniform("view", view);
m_shader->updateUniforms(getTransform(), *m_model, renderingEngine);
m_model->getMesh()->draw();
}
|
// Created on: 1992-09-28
// Created by: Remi GILET
// 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 _GC_MakeTrimmedCylinder_HeaderFile
#define _GC_MakeTrimmedCylinder_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <GC_Root.hxx>
#include <Geom_RectangularTrimmedSurface.hxx>
class gp_Pnt;
class gp_Circ;
class gp_Ax1;
//! Implements construction algorithms for a trimmed
//! cylinder limited by two planes orthogonal to its axis.
//! The result is a Geom_RectangularTrimmedSurface surface.
//! A MakeTrimmedCylinder provides a framework for:
//! - defining the construction of the trimmed cylinder,
//! - implementing the construction algorithm, and
//! - consulting the results. In particular, the Value
//! function returns the constructed trimmed cylinder.
class GC_MakeTrimmedCylinder : public GC_Root
{
public:
DEFINE_STANDARD_ALLOC
//! Make a cylindricalSurface <Cyl> from Geom
//! Its axis is <P1P2> and its radius is the distance
//! between <P3> and <P1P2>.
//! The height is the distance between P1 and P2.
Standard_EXPORT GC_MakeTrimmedCylinder(const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3);
//! Make a cylindricalSurface <Cyl> from gp by its base <Circ>.
//! Its axis is the normal to the plane defined bi <Circ>.
//! <Height> can be greater than zero or lower than zero.
//! In the first case the V parametric direction of the
//! result has the same orientation as the normal to <Circ>.
//! In the other case it has the opposite orientation.
Standard_EXPORT GC_MakeTrimmedCylinder(const gp_Circ& Circ, const Standard_Real Height);
//! Make a cylindricalSurface <Cyl> from gp by its
//! axis <A1> and its radius <Radius>.
//! It returns NullObject if <Radius> is lower than zero.
//! <Height> can be greater than zero or lower than zero.
//! In the first case the V parametric direction of the
//! result has the same orientation as <A1>.
//! In the other case it has the opposite orientation.
Standard_EXPORT GC_MakeTrimmedCylinder(const gp_Ax1& A1, const Standard_Real Radius, const Standard_Real Height);
//! Returns the constructed trimmed cylinder.
//! Exceptions
//! StdFail_NotDone if no trimmed cylinder is constructed.
Standard_EXPORT const Handle(Geom_RectangularTrimmedSurface)& Value() const;
operator const Handle(Geom_RectangularTrimmedSurface)& () const { return Value(); }
private:
Handle(Geom_RectangularTrimmedSurface) TheCyl;
};
#endif // _GC_MakeTrimmedCylinder_HeaderFile
|
/**********************************************************************************
General Neck Header file
Has overall class definition and private and public functions.
This class will change if a new neck mechanism is implemented (recommended).
Edited by Ethan Lauer on 4/8/21
*********************************************************************************/
#include<Arduino.h>
class Neck {
private:
// SERVO PINS
int rightServoPin;
int leftServoPin;
int rotServoPin;
int servoType;
// SENSOR PINS
const int neckPotPinR = A13;
const int neckPotPinL = A12;
const int neckPotPinRot = A1;
// MOVING VARIABLES
boolean initRunSide = true;
boolean initRunRot = true;
int cmdServo = 0;
int cmdServoR = 0; // stores the command that was sent to the right servo
int cmdServoL = 0;// stores the command that was sent to the left servo
int cmdServoRot = 0;// stores the command that was sent to the rotational servo
int state = 0; // state machine variable
int stateTest = 0;
const int tol = 2; // tolerance for feedback and movements
int nodCount = 0; // keeps track of the number of times nodded
int tiltCount = 0; // keeps track of the number of times tilted
// TIMING VARIABLES
const int moveTime = 20; // time delay before incrementing to the next degree
unsigned long timeNow = 0; //time variable for moving motors without delays
const int neckMotorCmdPause = 10;
const int normTimeBtwnNod = 250;
// SERVO POSITIONS
const int rotCenterPos = 35;
const int nodBackMax = 50;
const int nodFwdMax = 150;
const int tiltRightMax = 50; // servo position for tilting to the right
const int tiltLeftMax = 160;// servo position for tilting to the left
const int neutralPos = 100; // neutral position for left and right servos.
// Calibration values
const int minDeg = 0;
const int midDeg = 135;
const int maxDeg = 270;
int minFeedback = 335; // found thorugh calibration testing
int minFBs[2];
int maxFeedback = 1023; // found thorugh calibration testing
int maxFBs[2];
public:
const int rotLeftMax = 80;
const int rotRightMin = 0;
//********************************************************* SETUP AND INITIALIZE*********************
Neck() { // pass in pin numbers here and servo types
}
void setUp() {
// initialize and define servo pins
rightServoPin = rightTiltPin;
leftServoPin = leftTiltPin;
rotServoPin = rotPin;
servoType = datan;
// SENSOR PINS Analog pot pins for neck control
pinMode(neckPotPinR, INPUT);
pinMode(neckPotPinL, INPUT);
pinMode(neckPotPinRot, INPUT);
neutral();
Serial.println("Initializing Neck");
}
//**************************************************************CONVERSIONS**********************************************
/*
feedbackToDeg- converstion from the raw feedback into degrees of the servo
integer rawFB - the raw data from the servo feedback potentiometer pins.
return a double of the degrees
*/
double feedbackToDeg(int rawFB) {
double result = abs(map(rawFB, minFeedback, maxFeedback, minDeg, maxDeg));
return result;
}
/*
rDegToLDeg - convert the right servo degree to left and return
integer deg - degree for the right servo to move
note - offset with 90 was added because the left servo was not cooperating - unknown why
*/
int rDegToLDeg(int deg) {
int result = abs(maxDeg - deg - 60);
return result;
}
//*******************************************************************MOVING FUNCTIONS********************************************************
//******************************************************************Basics******************************
/*
moveRightServo - Move right servo to a certainn degree
integer Deg - the goal degree you want to move to.
*/
void moveRightServo(int deg) {
driveServo(rightServoPin, deg, datan);
}
/*
moveLeftServo - Move left servo to a certainn degree
integer Deg - the goal degree you want to move to.
*/
void moveLeftServo(int deg) {
driveServo(leftServoPin, deg, datan);
}
/*
moveRotServo - rotate the head to a certainn degree
integer Deg - the goal degree you want the head to turn to.
*/
void moveRotServo(int deg) {
driveServo(rotServoPin, deg, datan);
}
//***********************************************************************Combined******************************
/*
rotToDeg - rotate servo to a set point and ensure it made it there using a boolean.
can be used to move from any location.
integer goalDeg - the goal position of rotation servo
int degChange - how much you want the servo to move by (speed)
return true if it successfully moved to that degree
*/
boolean rotToDeg(int goalDeg,int degChange) {
boolean result = false;
int currPosRot;
int errRot;
if (initRunRot) {
currPosRot = (int)feedbackToDeg(analogRead(neckPotPinRot));
Serial.print("Rotational Reading = "); Serial.println(currPosRot);
cmdServoRot = currPosRot;
initRunRot = false;
}
errRot = goalDeg - cmdServoRot;
// Serial.print(" Rotation ERR = "); Serial.println(errRot);
moveRotServo(cmdServoRot);
// if engough time has passed for the servos to move
// check the errors to determine which direcetion the servos should move and if they need to move more at all
if (millis() > timeNow + moveTime) {
if (errRot >= tol) {
cmdServoRot += degChange;
} else if (errRot <= -tol) {
cmdServoRot -= degChange;
}
timeNow = millis();
}
// if you are within the tolerance, then return true
if (errRot < tol && errRot > -tol) {
result = true;
initRunRot = true;
// Serial.print("result = "); Serial.println(result);
// delay(2000);
}
return result;
}
/*
moveToDeg - move the left and right servos to a set point and ensure it made it there using a boolean.
can be used to move from any location.
integer goalDeg - the goal position based on the right servo ( convertes to left servo goal in the fnction)
boolean moveTogether - true if you want the servos to line up with each other whereever they are, false if you want them opposite.
int degChange - how much you want the servos to move by (speed)
return true if it successfully moved to that degree
*/
boolean moveToDeg(int goalDeg, boolean moveTogether, int degChange) {
boolean result = false; // initialize result to return false
int leftGoalDeg;
if (moveTogether) { // if you want the servos to line up with one another
leftGoalDeg = rDegToLDeg(goalDeg); // calculate the left goal
} else {
leftGoalDeg = goalDeg;
}
// initialize varibles fro the current positions and errors
int currPosR;
int currPosL;
int errR;
int errL;
// if it is the initial run , find out where the servos are currently and set that to the current cmd
if (initRunSide) {
currPosR = (int)feedbackToDeg(analogRead(neckPotPinR));
currPosL = (int)feedbackToDeg(analogRead(neckPotPinL));
Serial.print("Right Reading = "); Serial.println(currPosR);
Serial.print("LEft Reading = "); Serial.println(currPosL);
cmdServoR = currPosR;
cmdServoL = currPosL;
initRunSide = false;
}
// Calculate the error between the goal degree and the command number
errR = goalDeg - cmdServoR;
errL = leftGoalDeg - cmdServoL;
// Serial.print(" Right ERR = "); Serial.println(errR);
// Serial.print(" LEft ERR = "); Serial.println(errL);
// move both the servos
moveRightServo(cmdServoR);
moveLeftServo(cmdServoL);
// if engough time has passed for the servos to move
// check the errors to determine which direcetion the servos should move and if they need to move more at all
if (millis() > timeNow + moveTime) {
if (errR >= tol) {
cmdServoR += degChange;
} else if (errR <= -tol) {
cmdServoR -= degChange;
}
if (errL >= tol) {
cmdServoL += degChange;
} else if (errL <= -tol) {
cmdServoL -= degChange;
}
timeNow = millis();
}
// if you are within the tolerance, then return true and set initial run back to true
if (errR < tol && errR > -tol && errL < tol && errL > -tol) {
result = true;
// initRunSide = true;
// Serial.print("result = "); Serial.println(result);
}
return result;
}
/*
moveBtwnPts - have the neck move betweentwo points based on time
int startPos - the starting position you want the nod to start at (one of the setpoints you want move between)
int goalDeg - other setpoint you want to
boolean moveTogether - true for together
return boolean - true if it completed one round (ie. moved to startPos and goalDeg)
*/
boolean moveBtwnPts(int startPos, int goalDeg, boolean moveTogether) {
int result = false;
switch (state) {
case 0:
if (moveToDeg(startPos, moveTogether,2)) {
state = 1;
}
break;
case 1:
if (moveToDeg(goalDeg, moveTogether,2)) {
state = 0;
result = true;
}
break;
}
return result;
}
/*
rotBtwnPts - have the neck rotate between two points based on time
int startPos - the starting position you want the nod to start at (one of the setpoints you want move between)
int goalDeg - other setpoint you want to
return boolean - true if it completed one round (ie. moved to startPos and goalDeg)
*/
boolean rotBtwnPts(int startPos, int goalDeg) {
int result = false;
switch (state) {
case 0:
if (rotToDeg(startPos,2)) {
state = 1;
}
break;
case 1:
if (rotToDeg(goalDeg,2)) {
state = 0;
result = true;
}
break;
}
return result;
}
//******************************************************************************Complex***************************************
/*
neutral - move neck to neutral position
*/
boolean neutral() {
boolean result = false;
boolean sideResult = false;
boolean rotResult = false;
sideResult = moveToDeg (neutralPos, true,2);
rotResult = rotToDeg(rotCenterPos,2);
result = sideResult && rotResult;
return result;
}
/*
nod - generic nod to a back and forth with no end until function is not called (place inside a loop).
*/
void nod() {
// boolean result;
moveBtwnPts(nodFwdMax, nodBackMax, true);
}
/*
tilt - tilt head left and right with no end until function is not calle (place this inside a loop)
*/
void tilt() {
moveBtwnPts(tiltLeftMax, tiltRightMax, false);
}
/*
wince - have the neck wince/bend toward one of the given sides and rotate away from that side
boolean isLeft - true if wincing/tilting towards the left, false if towards the right
*/
boolean wince(boolean isLeft) {
boolean result;
if (isLeft) {
result = moveToDeg(tiltLeftMax, false,5);
} else {
result = moveToDeg(tiltRightMax, false,5);
}
rotToDeg(rotCenterPos,2);
return result;
}
/*
nodTimes - have the neck nod a forward and back at a certain speed for a given number of times
moving to the maximum locations
int numNods - the number of times the neck should be nodding
int timeBtwnNod - how long between the fwd and back
return boolean - true if finished nodding
*/
boolean nodTimes(int numNods, int timeBtwnNod) {
boolean result = false;
if (nodCount < numNods) {
boolean oneCycle = moveBtwnPts(nodFwdMax, nodBackMax, true);
if (oneCycle) {
nodCount++;
delay(timeBtwnNod);
}
} else {
nodCount = 0;
Serial.print("FINISHED NODDING "); Serial.print(numNods); Serial.println(" Times");
result = true;
delay(2000); /// remove eventually
}
return result;
}
/*
tiltTimes - have the neck tilte a left and right at a certain speed for a given number of times
moving to the maximum locations
int numTilts - the number of times the neck should be tilting
int timeBtwnTilt - how long between the left and right
return boolean - true if finished nodding
*/
boolean tiltTimes(int numTilts, int timeBtwnTilt) {
boolean result = false;
if (tiltCount < numTilts) {
boolean oneCycle = moveBtwnPts(tiltRightMax, tiltLeftMax, false);
if (oneCycle) {
tiltCount++;
delay(timeBtwnTilt);
}
} else {
tiltCount = 0;
Serial.print("FINISHED TILTING "); Serial.print(numTilts); Serial.println(" Times");
result = true;
delay(2000); /// remove eventually
}
return result;
}
/*
neckTest - have neck nod back, forward, tilt right, left
test moving to multiple setpoints to see the range of motion
*/
void neckTest() {
switch (stateTest) {
case 0:
if (moveToDeg(nodBackMax, true,2)) { // nodded back
stateTest = 1;
delay(1000);
}
break;
case 1:
if (moveToDeg(nodFwdMax, true,2)) { // nodded forward
stateTest = 2;
delay(1000);
}
break;
case 2:
if (moveToDeg(tiltRightMax, false,2)) { // tilted right
stateTest = 3;
delay(1000);
}
break;
case 3:
if (moveToDeg(tiltLeftMax, false,2)) { // tilted left
stateTest = 4;
delay(1000);
}
break;
case 4:
if (moveToDeg(neutralPos, true,2)) { // move to neutral position
stateTest = 0;
delay(1000);
}
break;
}
}
//****************************************OLDER FUNCTIONS***************************************
//***************************************************************************************************
/*
driveRandL - function to move both servos and print any feedback
int rightPos - right servo desired position
boolean moveTogether - true if you want to move the servos together , false if they are opposite
*/
void driveRandL(int rightPos, boolean moveTogether) {
int currPosL;
if (moveTogether) {
currPosL = rDegToLDeg(rightPos);
} else {
currPosL = rightPos;
}
Serial.print(" Left POSITION = "); Serial.println(currPosL);
moveRightServo(rightPos);
moveLeftServo(currPosL); // drive the servo
Serial.print("Rotating to "); Serial.println(rightPos);
}
/*
moveRandL - use for loops to move left and right servos together either forward or back
int startPos - starting position of the servos
int goalDeg - goal degree to move too
boolean moveTogether - true if the servos should move together (nod), false if opposite (tilt)
*/
boolean moveRandL(int startPos, int goalDeg, boolean moveTogether) {
// current feedback/reading
int currPos;
moveRightServo(startPos);
moveLeftServo(rDegToLDeg(startPos));
if (startPos < goalDeg) {
for (currPos = startPos; currPos < goalDeg; currPos++) {
driveRandL(currPos, moveTogether);
}
} else if (startPos > goalDeg) {
for (currPos = startPos; currPos >= goalDeg; currPos--) {
driveRandL(currPos, moveTogether);
}
}
return true;
}
/*
rotAndTilt - rotate the head and tilt the head to a certain set point for each
int startRotPos - starting servo position for the rotation servo
int goalRotDeg - goal degree position for the servo to rotate to
int startSidePos - starting servo position for the right servo left servo is calculated afterwards)
int goalSidePos - end servo position for the right servo left servo is calculated afterwards)
boolean moveTogether - true if the left and right servos shoudl move together(nod), false if they are opposite (tilt)
*/
void rotAndTilt(int startRotPos, int goalRotDeg, int startSidePos, int goalSidePos, boolean moveTogether) {
int currPosRot = startRotPos;
int currPosSide = startSidePos;
moveRightServo(startSidePos);
moveLeftServo(rDegToLDeg(startSidePos));
moveRotServo(startRotPos);
// calculate which difference is bigger, the rotation or the tilt diff
int rotDiff = abs(goalRotDeg - startRotPos);
int sideDiff = abs(goalSidePos - startSidePos);
if (sideDiff > rotDiff) {// SIDE MOVES MORE THAN ROT
Serial.println("SIDE MOVES MORE THAN ROT");
if (startRotPos < goalRotDeg && startSidePos < goalSidePos) { // if both SIDE and rot servos need to increment
Serial.println("side AND rot servos are = INCREASING .......bigger SIDE diff");
for (currPosSide = startSidePos; currPosSide < goalSidePos; currPosSide++) {
driveRandL(currPosSide, moveTogether);
if (currPosRot >= goalRotDeg) { // if it went too high past the goal, stay at the goal
moveRotServo(goalRotDeg);
} else {
moveRotServo(currPosRot); // otherwise go up to the goal
currPosRot++;
}
// delay(neckMotorCmdPause);
}
} else if (startRotPos > goalRotDeg && startSidePos > goalSidePos) { // if both right and rot servos need to decrement
Serial.println("side AND rot servos are = DECREASING .......bigger SIDE diff");
for (currPosSide = startSidePos; currPosSide > goalSidePos; currPosSide--) {
driveRandL(currPosSide, moveTogether);
if (currPosRot <= goalRotDeg) { // if it went too low past the goal, stay at the goal
moveRotServo(goalRotDeg);
} else {
moveRotServo(currPosRot);// otherwise go down to the goal
currPosRot--;
}
// delay(neckMotorCmdPause);
}
} else if (startRotPos > goalRotDeg && startSidePos < goalSidePos) { // rot servo needs to decrement, side servos increment
Serial.println("side servos = INCREASING !!!!! ROT servos = DECREASING !!...bigger SIDE diff");
for (currPosSide = startSidePos; currPosSide < goalSidePos; currPosSide++) {
driveRandL(currPosSide, moveTogether);
if (currPosRot <= goalRotDeg) { // if it went too low past the goal, stay at the goal
moveRotServo(goalRotDeg);
} else {
moveRotServo(currPosRot);// otherwise go down to the goal
currPosRot--;
}
// delay(neckMotorCmdPause);
}
} else if (startRotPos < goalRotDeg && startSidePos > goalSidePos) { // rot servo needs to increment, side servos decrement
Serial.println("side servos = DECREASING !!!!! ROT servos = INCCREASING !!...bigger SIDE diff");
for (currPosSide = startSidePos; currPosSide > goalSidePos; currPosSide--) {
driveRandL(currPosSide, moveTogether);
if (currPosRot >= goalRotDeg) { // if it went too high past the goal, stay at the goal
moveRotServo(goalRotDeg);
} else {
moveRotServo(currPosRot); // otherwise go up to the goal
currPosRot++;
}
// delay(neckMotorCmdPause);
}
}
}
else if (sideDiff <= rotDiff) {// ROT MOVES MORE THAN SIDE
Serial.println("ROT MOVES MORE THAN SIDE");
if (startRotPos < goalRotDeg && startSidePos < goalSidePos) { // if both right and rot servos need to increment
Serial.println("side AND rot servos are = INCREASING .......bigger ROT diff");
for (currPosRot = startRotPos; currPosRot < goalRotDeg; currPosRot++) {
moveRotServo(currPosRot);
if (currPosSide >= goalSidePos) { // if you went too high past the goal, then stay at the goal
driveRandL(goalSidePos, moveTogether);
} else {
driveRandL(currPosSide, moveTogether);// otherwise go up to the goal
currPosSide++;
}
// delay(neckMotorCmdPause);
}
} else if (startRotPos > goalRotDeg && startSidePos > goalSidePos) { // if both right and rot servos need to decrement
Serial.println("side AND rot servos are = DECREASING .......bigger ROT diff");
for (currPosRot = startRotPos; currPosRot > goalRotDeg; currPosRot--) {
moveRotServo(currPosRot);
if (currPosSide <= goalSidePos) { // if you went too low past the goal, then stay at the goal
driveRandL(goalSidePos, moveTogether);
} else {
driveRandL(currPosSide, moveTogether);// otherwise go down to the goal
currPosSide--;
}
// delay(neckMotorCmdPause);
}
} else if (startRotPos > goalRotDeg && startSidePos < goalSidePos) { // rot servo needs to decrement, side servos increment
Serial.println("side servos = INCREASING !!!!! ROT servos = DECREASING !!...bigger ROT diff");
for (currPosRot = startRotPos; currPosRot > goalRotDeg; currPosRot--) {
moveRotServo(currPosRot);
if (currPosSide >= goalSidePos) { // if you went too high past the goal, stay at the goal
driveRandL(goalSidePos, moveTogether);
} else {
driveRandL(currPosSide, moveTogether); // otherwise, go up to the goal
currPosSide++;
}
// delay(neckMotorCmdPause);
}
} else if (startRotPos < goalRotDeg && startSidePos > goalSidePos) { // rot servo needs to increment, side servos decrement
Serial.println("side servos = DECREASING !!!!! ROT servos = INCCREASING !!...bigger ROT diff");
for (currPosRot = startRotPos; currPosRot < goalRotDeg; currPosRot++) {
moveRotServo(currPosRot);
if (currPosSide <= goalSidePos) { // if you went too low past the goal, stay at the goal
driveRandL(goalSidePos, moveTogether);
} else {
driveRandL(currPosSide, moveTogether);// otherwise, go down to the goal
currPosSide--;
}
// delay(neckMotorCmdPause);
}
}
}
}
//**************************************************************TESTING and BIG MOVEMENTS******************************************************
// /*
// neckTest - nod back, forward, tilt right, left
// */
// void neckTest() {
// switch (stateTest) {
// case 0:
// if (moveRandL(nodFwdMax, nodBackMax, true)) {
// stateTest = 1;
// delay(1000);
// }
// break;
// case 1:
// if (moveRandL( nodBackMax, nodFwdMax, true)) {
// stateTest = 2;
// delay(1000);
// }
// break;
//
// case 2:
// if (moveRandL(tiltRightMax, tiltLeftMax, false)) {
// stateTest = 3;
// delay(1000);
// }
// break;
// case 3:
// if (moveRandL(tiltLeftMax, tiltRightMax, false)) {
// stateTest = 4;
// delay(1000);
// }
// break;
// case 4:
// if (moveRandL(tiltRightMax, neutralPos, false)) {
// stateTest = 0;
// delay(1000);
// }
// break;
// }
// }
/*
nod - have the neck nod a forward and back at a certain speed for a given number of times
int numNods - the number of times the neck should be nodding
int timeBtweenNod - how long between the fwd and back
*/
// void nod(int numNods, int timeBtwnNod) {
// boolean isDone;
// for (int i = 0; i < numNods * 2; i++) {
// moveRotServo(rotCenterPos);
// switch (stateTest) {
// case 0:
// Serial.println("Nodding Forward");
// isDone = moveRandL(tiltLeftMax, tiltRightMax, true);
// if (isDone) {
// isDone = false;
// stateTest = 1;
// delay(timeBtwnNod);
// }
//
// break;
// case 1:
// Serial.println("Nodding Backward");
//
// isDone = moveRandL(tiltRightMax, tiltLeftMax, true);
// if (isDone) {
// isDone = false;
// stateTest = 0;
// delay(timeBtwnNod);
// }
// break;
// }
// }
// Serial.print("FINISHED NODDING "); Serial.print(numNods); Serial.println(" Times");
// delay(5000); /// remove eventually
// }
/*
tilt - have the neck tilte a left and right at a certain speed for a given number of times
int numTilts - the number of times the neck should be tilting
int timeBtwnTilt - how long between the left and right
*/
// void tilt(int numTilts, int timeBtwnTilt) {
// boolean isDone;
// for (int i = 0; i < numTilts * 2; i++) {
// moveRotServo(rotCenterPos);
// switch (stateTest) {
// case 0:
// isDone = moveRandL(nodBackMax, nodFwdMax, false);
// if (isDone) {
// isDone = false;
// stateTest = 1;
// delay(timeBtwnTilt);
// }
// break;
// case 1:
// isDone = moveRandL(nodFwdMax, nodBackMax, false);
// if (isDone) {
// isDone = false;
// stateTest = 0;
// delay(timeBtwnTilt);
// }
// break;
// }
// }
// Serial.print("FINISHED Tilting "); Serial.print(numTilts); Serial.println(" Times");
// delay(5000); /// remove eventually - just there for testing purposes
// }
//******************************************************************************CALIBRATION****************************************************************
/*
step servo to the maximum position in a degree incrementation
*/
void stepToMax() {
for (int currPos = minDeg; currPos < maxDeg; currPos += 2) {
moveRightServo(currPos);
moveLeftServo(currPos); // drive the servo
// moveRotServo(currPos);
Serial.print("Rotating to "); Serial.println(currPos);
delay(neckMotorCmdPause);
uint16_t val = analogRead(neckPotPinR);
Serial.print("Pos = "); Serial.print(val); Serial.println("Deg");
}
}
/*
step servo to the minimum position in a degree incrementation
*/
void stepToMin() {
for (int currPos = maxDeg; currPos >= minDeg; currPos -= 2) {
moveRightServo(currPos); // tell servo to go to position in variable 'pos'
moveLeftServo(currPos); // drive the servo
// moveRotServo(currPos);
Serial.print("Rotating to "); Serial.println(currPos);
delay(neckMotorCmdPause);
uint16_t val = analogRead(neckPotPinR);
Serial.print("Pos = "); Serial.print(val); Serial.println("Deg");
}
}
/*
calibration of the sensor
integer minPos: minimum deg position to move to
integer maxPos: max deg position to move to
integer analogPin: servo pin to read
*/
void calibration(int minPos, int maxPos, int analogPin)
{
int i;
for (i = 0; i < 3; i++) {
// Move to the minimum position and record the feedback value
stepToMin();
delay(2000); // make sure it has time to get there and settle
minFeedback = analogRead(analogPin);
Serial.println("Cal Min");
Serial.print("Min Reading = "); Serial.println(minFeedback);
delay(1000);
// Move to the maximum position and record the feedback value
stepToMax();
delay(2000); // make sure it has time to get there and settle
maxFeedback = analogRead(analogPin);
Serial.println("Cal Max");
Serial.print("Max Reading = "); Serial.println(maxFeedback);
delay(1000);
minFBs[i] = minFeedback;
maxFBs[i] = maxFeedback;
}
// calculate and print all of the min and max values, and the average of each respectively
Serial.print("Min = "); Serial.print(minFBs[0]); Serial.print(", "); Serial.print(minFBs[1]); Serial.print(", "); Serial.println(minFBs[2]);
double aveMin = (minFBs[0] + minFBs[1] + minFBs[2]) / 3;
Serial.print("aveerage MIN ="); Serial.println(aveMin);
Serial.print("Max = "); Serial.print(maxFBs[0]); Serial.print(", "); Serial.print(maxFBs[1]); Serial.print(", "); Serial.println(maxFBs[2]);
double aveMax = (maxFBs[0] + maxFBs[1] + maxFBs[2]) / 3;
Serial.print("aveerage MAX ="); Serial.println(aveMax);
delay(5000);
//calculate and print all of the converted min and max values
i = 0;
Serial.print("Min converted = ");
for (i = 0; i < 3; i++) {
double deg = feedbackToDeg(minFBs[i]);
Serial.print(deg); Serial.print(", ");
}
Serial.println(" done");
Serial.print("Max converted = ");
int j;
for (j = 0; j < 3; j++) {
double deg = feedbackToDeg(maxFBs[j]);
Serial.print(deg); Serial.print(", ");
}
Serial.println(" done 2");
delay(10000);
}
};
|
#pragma once
#include <memory>
#include <type_traits>
#include "EverydayTools/Array/ArrayView.h"
#include "EverydayTools/Exception/CallAndRethrow.h"
#include "EverydayTools/Exception/ThrowIfFailed.h"
#include "RangedFunction.h"
#include "WaveBuffer.h"
template
<
typename T, bool interpolate,
typename = std::enable_if_t<std::is_floating_point_v<T>>
>
class WaveRangedFunction : public RangedFunction<T>
{
private:
using Converter = T(*)(const uint8_t& sampleRef);
public:
WaveRangedFunction(T argumentMin, T argumentMax, std::shared_ptr<const WaveBuffer> waveBuffer) :
m_waveBuffer(waveBuffer),
m_minimalArgument(argumentMin),
m_argumentRange(argumentMax - argumentMin)
{
CallAndRethrowM + [&] {
edt::ThrowIfFailed(m_waveBuffer != nullptr, "Wave buffer is null");
edt::ThrowIfFailed(m_argumentRange > 0, "Invalid argument range");
const auto bytesView = m_waveBuffer->GetData();
const auto sampleSize = waveBuffer->GetBitsPerSample() / 8;
edt::ThrowIfFailed((bytesView.GetSize() % sampleSize) == 0, "Invalid wave buffer");
const auto samplesCount = bytesView.GetSize() / sampleSize;
edt::ThrowIfFailed(samplesCount > 0, "Sound buffer is empty");
m_samples = edt::SparseArrayView<const uint8_t>(bytesView.GetData(), samplesCount, sampleSize);
switch (sampleSize)
{
case 1:
m_converter = GenericConverter<int8_t>;
break;
case 2:
m_converter = GenericConverter<int16_t>;
break;
case 4:
m_converter = GenericConverter<int32_t>;
break;
default:
edt::ThrowIfFailed(false, "Unexpected sample size: ", sampleSize * 8, " bit");
}
};
}
virtual T Compute(T argument) const override final {
return CallAndRethrowM + [&] {
const T deltaArgument = argument - m_minimalArgument;
edt::ThrowIfFailed((argument >= m_minimalArgument) && (deltaArgument <= m_argumentRange), "Invalid argument");
const T parameter = deltaArgument / m_argumentRange;
const size_t samplesCount = m_samples.GetSize();
const size_t maxIndex = samplesCount - 1;
const T floatIndex = samplesCount * parameter;
const size_t index = std::min(static_cast<size_t>(floatIndex), maxIndex);
const T sample = m_converter(m_samples[index]);
if constexpr (!interpolate) {
return static_cast<T>(sample);
}
const size_t nextIndex = std::min(index + 1, maxIndex);
const T nextSample = m_converter(m_samples[nextIndex]);
const T deltaSample = nextSample - sample;
const T deltaIndex = floatIndex - std::floor(floatIndex);
const T interpolatedSample = sample + deltaIndex * deltaSample;
return static_cast<T>(interpolatedSample);
};
}
virtual T GetMinArgument() const override final {
return m_minimalArgument;
}
virtual T GetMaxArgument() const override final {
return m_minimalArgument + m_argumentRange;
}
T operator()(T argument) const {
return Compute(argument);
}
size_t GetSamplesCount() const
{
return m_samples.GetSize();
}
const WaveBuffer& GetWaveBuffer() const {
return *m_waveBuffer;
}
private:
template<typename Sample>
static T GenericConverter(const uint8_t& sample) {
return static_cast<T>(reinterpret_cast<const Sample&>(sample));
}
private:
T m_minimalArgument;
T m_argumentRange;
edt::SparseArrayView<const uint8_t> m_samples;
std::shared_ptr<const WaveBuffer> m_waveBuffer;
Converter m_converter = nullptr;
};
|
// Generated from Expr.g4 by ANTLR 4.8
#pragma once
#include "antlr4-runtime.h"
#include "ExprVisitor.h"
/**
* This class provides an empty implementation of ExprVisitor, which can be
* extended to create a visitor which only needs to handle a subset of the available methods.
*/
class ExprBaseVisitor : public ExprVisitor {
public:
virtual antlrcpp::Any visitProg(ExprParser::ProgContext *ctx) override {
return visitChildren(ctx);
}
virtual antlrcpp::Any visitStatExpr(ExprParser::StatExprContext *ctx) override {
return visitChildren(ctx);
}
virtual antlrcpp::Any visitStatAssignExpr(ExprParser::StatAssignExprContext *ctx) override {
return visitChildren(ctx);
}
virtual antlrcpp::Any visitStatNewLine(ExprParser::StatNewLineContext *ctx) override {
return visitChildren(ctx);
}
virtual antlrcpp::Any visitExprINT(ExprParser::ExprINTContext *ctx) override {
return visitChildren(ctx);
}
virtual antlrcpp::Any visitExprAddSub(ExprParser::ExprAddSubContext *ctx) override {
return visitChildren(ctx);
}
virtual antlrcpp::Any visitExprID(ExprParser::ExprIDContext *ctx) override {
return visitChildren(ctx);
}
virtual antlrcpp::Any visitExprParenthesis(ExprParser::ExprParenthesisContext *ctx) override {
return visitChildren(ctx);
}
virtual antlrcpp::Any visitExprMulDiv(ExprParser::ExprMulDivContext *ctx) override {
return visitChildren(ctx);
}
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2012 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#if defined(VEGA_USE_ASM) && defined(ARCHITECTURE_IA32)
#include "modules/libvega/src/vegapixelformat.h"
#include "modules/libvega/src/x86/vegacommon_x86.h"
static op_force_inline __m128i Lerp(__m128i a, __m128i b, __m128i t)
{
__m128i ba = _mm_sub_epi16(b, a);
__m128i t_ba = _mm_srli_epi16(_mm_mullo_epi16(ba, t), 8);
return _mm_add_epi8(a, t_ba);
}
// This function is a lot more complicated than one would hope for
// since we needs to cater for the cases where fx == 0 or fy == 0
// could lead to accesses outside the source if dual-pixel access are
// done in all cases (VEGAImage generates that kind of requests).
static op_force_inline __m128i LerpRows(const UINT32* data, unsigned dataPixelStride,
INT32 frac_x, INT32 frac_y)
{
const __m128i zeros = _mm_setzero_si128();
// This branch structure was chosen because it seemed to reduce
// the impact of it being there at all - so if changing it verify
// that there are no adverse effects.
if (frac_y)
{
__m128i row0, row1;
if (frac_x)
{
// Load row-samples and expand components to 16-bit.
row0 = _mm_loadl_epi64((__m128i*)data);
row1 = _mm_loadl_epi64((__m128i*)(data + dataPixelStride));
}
else
{
// Load row-samples and expand components to 16-bit.
row0 = _mm_cvtsi32_si128(*data);
row1 = _mm_cvtsi32_si128(*(data + dataPixelStride));
}
row0 = _mm_unpacklo_epi8(row0, zeros);
row1 = _mm_unpacklo_epi8(row1, zeros);
// Linearly interpolate between the two row-samples.
return Lerp(row0, row1, _mm_set1_epi16(frac_y));
}
else
{
__m128i row0;
if (frac_x)
row0 = _mm_loadl_epi64((__m128i*)data);
else
row0 = _mm_cvtsi32_si128(*data);
return _mm_unpacklo_epi8(row0, zeros);
}
}
static op_force_inline __m128i Bilerp2(const UINT32* data, unsigned dataPixelStride,
INT32& csx, INT32& csy, INT32 cdx, INT32 cdy)
{
const UINT32* s0addr = data + VEGA_SAMPLE_INT(csy) * dataPixelStride + VEGA_SAMPLE_INT(csx);
int s0_fx = VEGA_SAMPLE_FRAC(csx);
__m128i s0 = LerpRows(s0addr, dataPixelStride, s0_fx, VEGA_SAMPLE_FRAC(csy));
csx += cdx;
csy += cdy;
const UINT32* s1addr = data + VEGA_SAMPLE_INT(csy) * dataPixelStride + VEGA_SAMPLE_INT(csx);
int s1_fx = VEGA_SAMPLE_FRAC(csx);
__m128i s1 = LerpRows(s1addr, dataPixelStride, s1_fx, VEGA_SAMPLE_FRAC(csy));
csx += cdx;
csy += cdy;
// Interleave samples 0 and 1.
__m128i r0 = _mm_unpacklo_epi64(s0, s1);
__m128i r1 = _mm_unpackhi_epi64(s0, s1);
// Setup x-weights.
__m128i vfx = _mm_unpacklo_epi64(_mm_shufflelo_epi16(_mm_cvtsi32_si128(s0_fx),
_MM_SHUFFLE(0, 0, 0, 0)),
_mm_shufflelo_epi16(_mm_cvtsi32_si128(s1_fx),
_MM_SHUFFLE(0, 0, 0, 0)));
// Interpolate between "column" samples.
return Lerp(r0, r1, vfx);
}
static op_force_inline __m128i Bilerp1(const UINT32* data, unsigned dataPixelStride,
INT32 csx, INT32 csy)
{
const UINT32* s0addr = data + VEGA_SAMPLE_INT(csy) * dataPixelStride + VEGA_SAMPLE_INT(csx);
int s0_fx = VEGA_SAMPLE_FRAC(csx);
__m128i s0 = LerpRows(s0addr, dataPixelStride, s0_fx, VEGA_SAMPLE_FRAC(csy));
// Deinterleave
const __m128i zeros = _mm_setzero_si128();
__m128i r0 = _mm_unpacklo_epi64(s0, zeros);
__m128i r1 = _mm_unpackhi_epi64(s0, zeros);
// Setup x-weights.
__m128i vfx = _mm_shufflelo_epi16(_mm_cvtsi32_si128(s0_fx),
_MM_SHUFFLE(0, 0, 0, 0));
// Interpolate between "column" samples.
return Lerp(r0, r1, vfx);
}
extern "C" void Sampler_LerpXY_Opaque_SSE2(UINT32* color, const UINT32* data,
unsigned cnt, unsigned dataPixelStride,
INT32 csx, INT32 cdx, INT32 csy, INT32 cdy)
{
unsigned cnt2 = cnt / 2;
while (cnt2)
{
__m128i s01 = Bilerp2(data, dataPixelStride, csx, csy, cdx, cdy);
_mm_storel_epi64((__m128i*)color,
_mm_packus_epi16(s01, _mm_setzero_si128()));
color += 2;
cnt2--;
}
if (cnt & 1)
{
__m128i s0 = Bilerp1(data, dataPixelStride, csx, csy);
*color = _mm_cvtsi128_si32(_mm_packus_epi16(s0, _mm_setzero_si128()));
}
}
// Perform (dst.rgba * (256 - src.a) on two pixels (word components).
static op_force_inline __m128i CompOverW_SSE2(__m128i src, __m128i dst)
{
// Broadcast the alpha channel to all the words.
__m128i alpha = _mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3));
alpha = _mm_shufflehi_epi16(alpha, _MM_SHUFFLE(3, 3, 3, 3));
// Subtract each component from 256.
__m128i res = _mm_subs_epu16(g_xmm_constants._256, alpha);
// Multiply [dst0][dst1] with one minus src alpha.
// Then shift down the result to bytes again.
return MulW(dst, res);
}
static op_force_inline __m128i CompOver2_SSE2(__m128i src, __m128i dst)
{
const __m128i zeros = _mm_setzero_si128();
dst = _mm_unpacklo_epi8(dst, zeros);
// d' = d * (256 - sa)
dst = CompOverW_SSE2(src, dst);
// d = d' + s
dst = _mm_adds_epu8(dst, src);
return _mm_packus_epi16(dst, zeros);
}
extern "C" void Sampler_LerpXY_CompOver_SSE2(UINT32* color, const UINT32* data,
unsigned cnt, unsigned dataPixelStride,
INT32 csx, INT32 cdx, INT32 csy, INT32 cdy)
{
unsigned cnt2 = cnt / 2;
while (cnt2)
{
__m128i s01 = Bilerp2(data, dataPixelStride, csx, csy, cdx, cdy);
__m128i dst = _mm_loadl_epi64((__m128i*)color);
dst = CompOver2_SSE2(s01, dst);
_mm_storel_epi64((__m128i*)color, dst);
color += 2;
cnt2--;
}
if (cnt & 1)
{
__m128i s0 = Bilerp1(data, dataPixelStride, csx, csy);
__m128i dst = _mm_cvtsi32_si128(*color);
dst = CompOver2_SSE2(s0, dst);
*color = _mm_cvtsi128_si32(dst);
}
}
extern "C" void Sampler_LerpXY_CompOverMask_SSE2(UINT32* color, const UINT32* data, const UINT8* mask,
unsigned cnt, unsigned dataPixelStride,
INT32 csx, INT32 cdx, INT32 csy, INT32 cdy)
{
unsigned cnt2 = cnt / 2;
while (cnt2)
{
int a0 = *mask++;
int a1 = *mask++;
if (a0 || a1)
{
__m128i s01 = Bilerp2(data, dataPixelStride, csx, csy, cdx, cdy);
// Modulate with mask.
__m128i a_0 = _mm_cvtsi32_si128(a0 + 1);
a_0 = _mm_shufflelo_epi16(a_0, _MM_SHUFFLE(0, 0, 0, 0));
__m128i a_1 = _mm_cvtsi32_si128(a1 + 1);
a_1 = _mm_shufflelo_epi16(a_1, _MM_SHUFFLE(0, 0, 0, 0));
__m128i a_01 = _mm_unpacklo_epi64(a_0, a_1);
s01 = MulW(s01, a_01);
// Composite
__m128i dst = _mm_loadl_epi64((__m128i*)color);
dst = CompOver2_SSE2(s01, dst);
_mm_storel_epi64((__m128i*)color, dst);
}
else
{
csx += 2 * cdx;
csy += 2 * cdy;
}
color += 2;
cnt2--;
}
if ((cnt & 1) && *mask)
{
__m128i s0 = Bilerp1(data, dataPixelStride, csx, csy);
// Modulate with mask.
__m128i a8 = _mm_cvtsi32_si128(*mask + 1);
a8 = _mm_shufflelo_epi16(a8, _MM_SHUFFLE(0, 0, 0, 0));
s0 = MulW(s0, a8);
// Composite
__m128i dst = _mm_cvtsi32_si128(*color);
dst = CompOver2_SSE2(s0, dst);
*color = _mm_cvtsi128_si32(dst);
}
}
#endif // defined(VEGA_USE_ASM) && defined(ARCHITECTURE_IA32)
|
#ifndef SDAIHEADER_SECTION_SCHEMA_SCHEMA_CC
#define SDAIHEADER_SECTION_SCHEMA_SCHEMA_CC
// This file was generated by fedex_plus. You probably don't want to edit
// it since your modifications will be lost if fedex_plus is used to
// regenerate it.
#include <SdaiSchemaInit.h>
#include "scl_memmgr.h"
void HeaderSchemaInit( Registry & reg ) {
HeaderInitSchemasAndEnts( reg );
SdaiHEADER_SECTION_SCHEMAInit( reg );
reg.SetCompCollect( 0 );
}
#endif
|
#pragma once
#include <functional>
#include <Poco/AutoPtr.h>
#include <Poco/Util/TimerTask.h>
namespace BeeeOn {
class LambdaTimerTask : public Poco::Util::TimerTask {
public:
typedef std::function<void(void)> TaskCall;
typedef Poco::AutoPtr<LambdaTimerTask> Ptr;
LambdaTimerTask(TaskCall call);
void run() override;
private:
TaskCall m_taskCall;
};
}
|
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <iostream>
#include <queue>
#include <set>
#include <vector>
#include <fstream>
#include <string>
int min(int x, int y) {
if (x <= y)
return x;
return y;
}
using namespace std;
deque<int> runningValues(0);
const int SECONDS = 1;
const int SAMPLES_PER_SEC = 400;
const int WINDOW_SIZE = 100; // SECONDS * SAMPLES_PER_SEC;
const int THRESHOLD_PERCENT = 24;
const int THRESHOLD_ABS = 100;
int runningSum = 0;
bool calibrated = false;
deque<bool> wasAnomalyMeasured;
int anomalousCount = 0;
double averageWindow = 0;
// needs to called at every time instant
bool isAnomaly(int value) {
double maxLimit = THRESHOLD_ABS + averageWindow,
minLimit = -THRESHOLD_ABS + averageWindow;
return (value >= maxLimit || value <= minLimit);
}
void takeInput(int value) {
while ((int)(runningValues.size()) >= WINDOW_SIZE) {
runningSum -= runningValues.front();
anomalousCount -= wasAnomalyMeasured.front();
wasAnomalyMeasured.pop_front();
runningValues.pop_front();
}
runningSum += value;
runningValues.push_back(value);
averageWindow = runningSum / (double)WINDOW_SIZE;
if (calibrated) {
bool x = isAnomaly(value);
wasAnomalyMeasured.push_back(x);
} else
wasAnomalyMeasured.push_back(false);
anomalousCount += wasAnomalyMeasured.back();
}
int counter = 0;
void sendResponse() {
int lim = min((int)wasAnomalyMeasured.size(), WINDOW_SIZE);
double percentage = anomalousCount * 100 / (double)lim;
cout << (percentage >= THRESHOLD_PERCENT ? 1 : 0);
}
int main() {
int val;
string fileName = "data";
ifstream inp;
inp.open(fileName);
if (inp) {
while (inp >> val) {
if (val == -1)
break;
runningValues.push_back(val);
runningSum += val;
wasAnomalyMeasured.push_back(0);
}
while (runningValues.size() >= WINDOW_SIZE) {
runningSum -= runningValues[0];
wasAnomalyMeasured.pop_front();
runningValues.pop_front();
}
inp.close();
}
while(true){
string s;
cin >> s;
if(s.size() % 3 != 0) {
cerr << -3;
return 1;
}
for(int i = 0, len = s.size(); i < len; i+=3){
int val = (s[i]-'0')*100 + (s[i+1]-'0')*10 + (s[i+2]-'0');
val *= 10;
takeInput(val);
sendResponse();
counter++;
if (counter > WINDOW_SIZE)
calibrated = true;
}
int val;
cin >> val;
ofstream oft;
oft.open(fileName, ios::trunc);
if (val == -1) {
cout << endl;
fflush(stdout);
for (auto d : runningValues) {
oft << d << " ";
}
oft << -1 << endl;
exit(0);
}else{
oft << -2 << endl;
}
}
}
|
/*
Name: 走方格
Copyright:
Author: Hill Bamboo
Date: 2019/9/9 16:34:52
Description:
*/
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100;
int ans[maxn][maxn];
class Robot {
public:
// int countWays(int x, int y) {
// ans[1][1] = 1;
// return walk(x, y);
// }
// dp method
int countWays(int x, int y) {
int dp[15][15] = {0};
for (int i = 1; i < 15; ++i) dp[i][1] = 1;
for (int j = 1; j < 15; ++j) dp[1][j] = 1;
for (int i = 2; i <= x; ++i) {
for (int j = 2; j <= y; ++j) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
return dp[x][y];
}
// 记忆化搜索
int walk(int i, int j) {
if (ans[i][j] != 0) return ans[i][j];
return ans[i][j] = (j == 1 ? 0 : walk(i, j - 1)) + (i == 1 ? 0 : walk(i - 1, j));
}
};
int main() {
cout << Robot().countWays(10, 2) << endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef MODULES_SCOPE_SCOPE_INTERNAL_PROXY_H
#define MODULES_SCOPE_SCOPE_INTERNAL_PROXY_H
#if defined(SCOPE_SUPPORT) && defined(SCOPE_ACCEPT_CONNECTIONS)
/**
* Public API for the internal proxy in the scope module.
*/
class OpScopeProxy
{
public:
#ifdef SCOPE_MESSAGE_TRANSCODING
enum TranscodingFormat
{
Format_None = 0
, Format_ProtocolBuffer = 1
, Format_JSON = 2
, Format_XML = 3
};
/**
* Changes the current format used for transcoding in the proxy.
* Can be called at any time.
*
* @note Only available for testing purposes.
* @see OpScopeSocketHostConnection::InitiateTranscoding
*/
static OP_STATUS SetTranscodingFormat(TranscodingFormat format);
static void GetTranscodingStats(unsigned &client_to_host, unsigned &host_to_client);
#endif // SCOPE_MESSAGE_TRANSCODING
};
#endif // SCOPE_SUPPORT && SCOPE_ACCEPT_CONNECTIONS
#endif // !MODULES_SCOPE_SCOPE_INTERNAL_PROXY_H
|
/*
* Copyright (c) 2011 Pierre-Etienne Bougué <pe.bougue(a)gmail.com>
* Copyright (c) 2011 Florian Colin <florian.colin28(a)gmail.com>
* Copyright (c) 2011 Kamal Fadlaoui <kamal.fadlaoui(a)gmail.com>
* Copyright (c) 2011 Quentin Lequy <quentin.lequy(a)gmail.com>
* Copyright (c) 2011 Guillaume Pinot <guillaume.pinot(a)tremplin-utc.net>
* Copyright (c) 2011 Cédric Royer <cedroyer(a)gmail.com>
* Copyright (c) 2011 Guillaume Turri <guillaume.turri(a)gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#ifndef CHECKER_HH
#define CHECKER_HH
#include <vector>
#include <stdint.h>
using namespace std;
class ContextALG;
class ContextBO;
class MachineBO;
class RessourceBO;
/**
* Fonctions s'appuyant sur la classe #Checker, permettant de s'evitant la creation d'instances temporaires
*/
bool check(ContextALG const * pContextALG_p);
bool check(ContextBO const * pContextBO_p);
class Checker {
public:
Checker(ContextALG const * pContextALG_p);
Checker(ContextBO const * pContextBO_p, const vector<int>& sol_p);
/**
* /!\ Ne pas utiliser /!\
* Defini uniquement afin d'eviter d'en avoir une implantation par defaut.
* (afin d'eviter d'avoir a perdre du cpu a gerer a vouloir eviter les
* double delete et/ou fuites, alors qu'on n'a de toute facon pas besoin de ce ctr
*/
Checker(const Checker& checker_p);
~Checker();
void setContextALG(ContextALG const * pContextALG_p);
bool isValid();
/**
* Calcule le score en supposant que l'instance est valide.
* Dans le cas contrainte, le comportement est indetermine
*/
uint64_t computeScore();
/**
* Methodes permettant de ne checker que quelques contraintes
*/
bool checkCapaIncludingTransient();
bool checkConflict();
bool checkSpread();
bool checkDependances();
/**
* Methodes permettant de ne calculer que certains couts
*/
uint64_t computeLoadCost();
uint64_t computeLoadCost(int idxRess_p);
uint64_t computeLoadCost(int idxRess_p, int idxMachine_p);
uint64_t computeBalanceCost();
uint64_t computeBalanceCost(int idxMachine_p);
uint64_t computeBalanceCost(int idxMachine_p, int idxBalanceCost_p);
uint64_t computePMC();
uint64_t computeSMC();
uint64_t computeMMC();
private:
bool checkCapaIncludingTransient(RessourceBO const * pRess_p);
/**
* Permet de construire un ContextALG customise, et const
*/
ContextALG const * buildMyContextALG(ContextBO const * pContextBO, const vector<int> sol_p);
/**
* Le const permet surtout a la classe cliente de s'assurer qu'on ne pourri
* pas son contexte. Ceci dit, si le client peut eventuellement la modifier
* donc attention : il n'est pas possible de cacher quoique se soit !
*/
ContextALG const * pContextALG_m;
/**
* Si le context a ete cree sur mesure par le checker, il faut le deleter nous meme
*/
bool contextToDelete_m;
};
#endif
|
/****************************************************************
* TianGong RenderLab *
* Copyright (c) Gaiyitp9. All rights reserved. *
* This code is licensed under the MIT License (MIT). *
*****************************************************************/
#pragma once
#include "Window/WindowHelper.hpp"
#include <optional>
namespace TG
{
// WIN32窗口基类
class Window
{
public:
Window(int x, int y, int width, int height, HWND parent);
Window(const Window&) = delete;
Window& operator=(const Window&) = delete;
virtual ~Window() = default;
static std::optional<int> ProcessMessage(); // 处理所有窗口的消息
[[nodiscard]] HWND Hwnd() const noexcept { return m_hwnd; } // 窗口句柄
[[nodiscard]] HWND ParentHwnd() const noexcept { return m_parent; } // 返回父母窗口
[[nodiscard]] int Width() const noexcept { return m_width; } // 获取窗口宽和高
[[nodiscard]] int Height() const noexcept { return m_height; }
[[nodiscard]] bool Destroy() const noexcept { return m_destroy; } // 是否销毁窗口
void SpyMessage(bool enable) noexcept { m_spyMessage = enable; } // 捕捉窗口消息
virtual LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM) = 0; // 消息处理函数
protected:
HWND m_hwnd;
HWND m_parent;
int m_posX, m_posY;
int m_width, m_height;
bool m_destroy = false; // 是否销毁窗口
bool m_spyMessage = false; // 是否监控窗口消息
};
}
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2009-2011.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#include <fwDataTools/Image.hpp>
#include <itkIO/itk.hpp>
namespace fwItkIO
{
namespace ut
{
template< class TYPE>
void ImageConversionTest::stressTestForAType()
{
for(unsigned char k=0; k<5; k++)
{
::fwData::Image::NewSptr image;
::fwDataTools::Image::generateRandomImage(image, ::fwTools::Type::create<TYPE>());
typedef itk::Image< TYPE , 3 > ImageType;
typename ImageType::Pointer itkImage = ::itkIO::itkImageFactory<ImageType>( image );
::fwData::Image::NewSptr image2;
bool image2ManagesHisBuffer = false;
::itkIO::dataImageFactory< ImageType >( itkImage, image2, image2ManagesHisBuffer );
CPPUNIT_ASSERT(::fwDataTools::Image::compareImage(image, image2));
bool image3ManagesHisBuffer = false;
::fwData::Image::sptr image3 = ::itkIO::dataImageFactory< ImageType >( itkImage, image3ManagesHisBuffer );
CPPUNIT_ASSERT(::fwDataTools::Image::compareImage(image, image3));
}
}
} //namespace ut
} //namespace fwItkIO
|
#include "Real.h"
Real::Real(){
}
string Real::toString(){
return "";
}
|
#include "ArrivalEvent.h"
#include "..\Rest\Restaurant.h"
ArrivalEvent::ArrivalEvent(int eTime, int oID, ORD_TYPE oType):Event(eTime, oID)
{
OrdType = oType;
}
ArrivalEvent::ArrivalEvent(int eTime, int oID, char ty, int size, double money):Event(eTime, oID)
{
OrdMoney = money > 0 ? money : 0;
order_size = size > 0 ? size : 0;
switch (ty)
{
case 'N':
OrdType = TYPE_NRM;
break;
case'G':
OrdType = TYPE_VGAN;
break;
case 'V':
OrdType = TYPE_VIP;
break;
}
}
void ArrivalEvent::Execute(Restaurant* pRest)
{
Order* new_order = new Order(OrdType, EventTime, OrderID,order_size,OrdMoney);
pRest->AddtoORDERsLISTS(new_order);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2006 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef FORMRADIOGROUPS_H
#define FORMRADIOGROUPS_H
#include "modules/util/adt/opvector.h"
#include "modules/util/OpHashTable.h"
class HTML_Element;
class FramesDocument;
/**
* A radio button must be able to find all its friends. It does so by asking the Form for a named group.
*/
class FormRadioGroup
{
OpString m_name; // Used as key in the hash table in FormRadioGroups
OpVector<HTML_Element> m_radio_buttons;
BOOL m_might_have_several_checked;
BOOL m_has_any_checked;
/**
* Until some radio button in a group has been explicitly changed,
* setting the checked attribute will affect checked state. So
* to know when to stop, we have to keep track of whether
* something was explicitly checked or not.
*
* Explicitly set means set by the user of by the checked property in
* scripts.
*/
BOOL m_has_been_explicitly_checked;
public:
FormRadioGroup() : m_might_have_several_checked(FALSE), m_has_any_checked(FALSE), m_has_been_explicitly_checked(FALSE) {}
OP_STATUS Init(const uni_char* name) { OP_ASSERT(name); return m_name.Set(name); }
const uni_char* GetName() { OP_ASSERT(m_name.CStr()); return m_name.CStr(); }
/**
* Uncheck other buttons in the group and sets the "is_in_checked_group" flag to TRUE.
*/
void UncheckOthers(FramesDocument* frames_doc, HTML_Element *radio_button);
/**
* Returns TRUE if any of the buttons beside |radio_button| is checked.
*/
BOOL HasOtherChecked(HTML_Element* radio_button) const;
/**
* Returns TRUE if any of the buttons are checked (uses cached value).
*/
BOOL HasAnyChecked() const { return m_has_any_checked; }
/**
* Set or clear the flag that says that this is in an checked
* group. Will/might change the :indeterminate class so this is
* potentially a very expensive method that should be
* avoided if possible.
*
* @param frames_doc the document. Use NULL if pseudo classes shouldn't be recalculated.
* @param checked What the flag should be set to.
*/
void SetIsInCheckedGroup(FramesDocument* frames_doc, BOOL checked);
/**
* Returns the group of the button. NULL if out of memory.
*/
OP_STATUS RegisterRadioButton(HTML_Element* radio_button, BOOL might_be_registered_already, BOOL will_uncheck_afterwards);
void UnregisterRadioButton(HTML_Element* radio_button);
void UnregisterThoseWithFormAttr();
/**
* At some time or other a radio button in the control
* was implicitly checked if this returns TRUE.
*/
BOOL HasBeenExplicitlyChecked() { return m_has_been_explicitly_checked; }
/**
* Until some radio button in a group has been explicitly changed,
* setting the checked attribute will affect checked state. So
* to know when to stop, we have to keep track of whether
* something was explicitly checked or not.
*
* Explicitly set means set by the user of by the checked property in
* scripts.
*/
void SetHasBeenExplicitlyChecked() { m_has_been_explicitly_checked = TRUE; }
};
class FormRadioGroups
{
OpAutoStringHashTable<FormRadioGroup> m_radio_groups;
public:
/**
* Get the group with the given name. The name will be normalized.
* @param create TRUE if the group should be created if it doesn't exist.
* @return NULL if OOM when create is set.
*/
FormRadioGroup* Get(const uni_char* name, BOOL create);
/**
* To be called when an attribute changes.
*/
void UnregisterAllRadioButtonsConnectedByName();
};
class DocumentRadioGroups
{
private:
OpHashTable m_formradiogroups;
/** If there are radio buttons with non-functional form attributes. */
BOOL m_may_have_orphans;
public:
DocumentRadioGroups() : m_may_have_orphans(TRUE) {}
~DocumentRadioGroups();
/**
* If it returns NULL and create was TRUE, then it is an OOM.
*/
FormRadioGroups* GetFormRadioGroupsForRadioButton(FramesDocument* frames_doc, HTML_Element* radio_elm, BOOL create);
/**
* Returns OpStatus::OK or OpStatus::ERR_NO_MEMORY.
*/
OP_STATUS RegisterRadioAndUncheckOthers(FramesDocument* frames_doc, HTML_Element* form_elm, HTML_Element* radio_button);
OP_STATUS RegisterRadio(HTML_Element* form_elm, HTML_Element* radio_button);
OP_STATUS RegisterNewRadioButtons(FramesDocument* frames_doc, HTML_Element* form_element);
void UnregisterAllRadioButtonsConnectedByName(HTML_Element* form);
void UnregisterAllRadioButtonsInTree(FramesDocument* frames_doc, HTML_Element* tree);
void UnregisterFromRadioGroup(FramesDocument* frames_doc, HTML_Element* radio_button);
/**
* A late form element might take ownership of existing elements if those existing
* elements have the form attribute pointing to the late form element.
*
* Call this for a form element to move all necessary radio buttons to their right
* place.
*
* @param[in] frames_doc The document owning the form element.
* @param[in] form_element The HE_FORM element.
*
* @returns OpStatus::OK or OpStatus::ERR_NO_MEMORY.
*/
OP_STATUS AdoptOrphanedRadioButtons(FramesDocument* frames_doc, HTML_Element* form_element);
private:
void operator=(const DocumentRadioGroups& other);
DocumentRadioGroups(const DocumentRadioGroups& other);
/**
* If it returns NULL and create was TRUE, then it is an OOM.
*/
FormRadioGroups* GetFormRadioGroupsForForm(HTML_Element* form, BOOL create);
BOOL MayHaveOrphans() { return m_may_have_orphans; }
void SetHasOrphan() { m_may_have_orphans = TRUE; }
};
#endif // FORMRADIOGROUPS_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2009 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* Morten Rolland, mortenro@opera.com
*/
#ifndef MEMORY_GROUP_H
#define MEMORY_GROUP_H
class OpMemGroup
{
public:
OpMemGroup(void);
~OpMemGroup(void);
void* NewGRO(size_t size);
void* NewGRO(size_t size, const char* file, int line, const char* obj);
void* NewGRO_L(size_t size);
void* NewGRO_L(size_t size, const char* file, int line, const char* obj);
void ReleaseAll(void);
private:
void Reset(void)
{
all = 0;
primary_ptr = 0;
secondary_ptr = 0;
primary_size = 0;
secondary_size = 0;
}
void* all; ///< All allocations in this group chained together
char* primary_ptr; ///< Primary next allocation address
char* secondary_ptr; ///< Secondary next allocation address
unsigned int primary_size; ///< Free bytes in primary allocation segment
unsigned int secondary_size; ///< Free bytes in secondary allocations segment
};
#endif // MEMORY_GROUP_H
|
//: C14:Inheritance.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Proste dziedziczenie
#include "Useful.h"
#include <iostream>
using namespace std;
class Y : public X {
int i; // Inne niz i klasy X
public:
Y() { i = 0; }
int change() {
i = permute(); // Wywolanie funkcji o innej nazwie
return i;
}
void set(int ii) {
i = ii;
X::set(ii); // Wywolanie funkcji o tej samej nazwie
}
};
int main() {
cout << "sizeof(X) = " << sizeof(X) << endl;
cout << "sizeof(Y) = "
<< sizeof(Y) << endl;
Y D;
D.change();
// Wykorzystanie funkcji interfejsu klasy X:
D.read();
D.permute();
// Zdefiniowane ponownie funkcje zaslaniaja
// funkcje klasy podstawowej:
D.set(12);
} ///:~
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
using namespace std;
int main()
{
int a, b;
scanf("%d %d", &a, &b);
if (a>= 0 && a <= b && b <= 100) {
for (int i = a; i <= b; i++) {
printf("%d\n", i);
}
}
getchar();
return 0;
}
|
#include "node.h"
#include "codegen.h"
#include "parser.hpp"
using namespace std;
Value *CodeGenBlock::findLocal(std::string name) {
if (locals.find(name) == locals.end()) {
return parent ? parent->findLocal(name) : nullptr;
} else {
return locals[name];
}
}
/* Compile the AST into a module */
void CodeGenContext::generateCode(NBlock& root)
{
std::cout << "Generating code...\n";
/* Create the top level interpreter function to call as entry */
vector<Type*> argTypes;
FunctionType *ftype = FunctionType::get(Type::getVoidTy(getGlobalContext()), makeArrayRef(argTypes), false);
mainFunction = Function::Create(ftype, GlobalValue::InternalLinkage, "main", module);
BasicBlock *bblock = BasicBlock::Create(getGlobalContext(), "entry", mainFunction, 0);
/* Push a new variable/block context */
pushBlock(bblock);
root.codeGen(*this); /* emit bytecode for the toplevel block */
ReturnInst::Create(getGlobalContext(), bblock);
popBlock();
/* Print the bytecode in a human-readable format
to see if our program compiled properly
*/
std::cout << "Code is generated.\n";
PassManager pm;
pm.add(createPrintModulePass(outs()));
pm.run(*module);
}
void CodeGenContext::pushBlock(BasicBlock *block) {
CodeGenBlock *child = new CodeGenBlock();
child->block = block;
if (!blocks.empty()) {
child->parent = blocks.top();
}
blocks.push(child);
builder.SetInsertPoint(blocks.top()->block);
}
void CodeGenContext::popBlock() {
CodeGenBlock *top = blocks.top();
blocks.pop();
delete top;
if (!blocks.empty()) {
builder.SetInsertPoint(blocks.top()->block);
}
}
/* Executes the AST by running the main function */
GenericValue CodeGenContext::runCode() {
std::cout << "Running code...\n";
ExecutionEngine *ee = EngineBuilder(module).create();
vector<GenericValue> noargs;
GenericValue v = ee->runFunction(mainFunction, noargs);
std::cout << "Code was run.\n";
return v;
}
/* Returns an LLVM type based on the identifier */
static Type *typeOf(const NIdentifier& type)
{
if (type.name.compare("int") == 0) {
return Type::getInt64Ty(getGlobalContext());
}
else if (type.name.compare("double") == 0) {
return Type::getDoubleTy(getGlobalContext());
}
else if (type.name.compare("bool") == 0) {
return Type::getInt1Ty(getGlobalContext());
}
else if (type.name.compare("void") == 0) {
return Type::getVoidTy(getGlobalContext());
}
return Type::getVoidTy(getGlobalContext());
}
/* -- Code Generation -- */
Value* NInteger::codeGen(CodeGenContext& context)
{
std::cout << "Creating integer: " << value << endl;
return ConstantInt::get(Type::getInt64Ty(getGlobalContext()), value, true);
}
Value* NDouble::codeGen(CodeGenContext& context)
{
std::cout << "Creating double: " << value << endl;
return ConstantFP::get(Type::getDoubleTy(getGlobalContext()), value);
}
Value* NBoolean::codeGen(CodeGenContext& context)
{
std::cout << "Creating boolean: " << value << endl;
return ConstantInt::get(Type::getInt1Ty(getGlobalContext()), value);
}
Value* NIdentifier::codeGen(CodeGenContext& context)
{
std::cout << "Creating identifier reference: " << name << endl;
Value *var = context.findLocal(name);
if (!var) {
std::cerr << "undeclared variable " << name << endl;
return nullptr;
}
return context.builder.CreateLoad(var);
}
Value* NMethodCall::codeGen(CodeGenContext& context)
{
Function *function = context.module->getFunction(id.name.c_str());
if (!function) {
std::cerr << "no such function " << id.name << endl;
}
std::vector<Value*> args;
ExpressionList::const_iterator it;
for (it = arguments.begin(); it != arguments.end(); it++) {
args.push_back((**it).codeGen(context));
}
std::cout << "Creating method call: " << id.name << endl;
return context.builder.CreateCall(function, makeArrayRef(args));
}
Value* NBinaryOperator::codeGen(CodeGenContext& context)
{
std::cout << "Creating binary operation " << op << endl;
Value* left = lhs.codeGen(context);
Value* right= rhs.codeGen(context);
switch (op) {
case TPLUS:
return context.builder.CreateAdd(left, right);
case TMINUS:
return context.builder.CreateSub(left, right);
case TMUL:
return context.builder.CreateMul(left, right);
case TDIV:
return context.builder.CreateSDiv(left, right);
case TCEQ:
return context.builder.CreateICmpEQ(left, right);
case TCNE:
return context.builder.CreateICmpNE(left, right);
case TCLT:
return context.builder.CreateICmpSLT(left, right);
case TCLE:
return context.builder.CreateICmpSLE(left, right);
case TCGT:
return context.builder.CreateICmpSGT(left, right);
case TCGE:
return context.builder.CreateICmpSGE(left, right);
default:
return nullptr;
}
}
Value* NAssignment::codeGen(CodeGenContext& context)
{
std::cout << "Creating assignment for " << lhs.name << endl;
Value* var = context.findLocal(lhs.name);
if (var) {
Value* val = rhs.codeGen(context);
return context.builder.CreateStore(val, var);
} else {
std::cerr << "undeclared variable " << lhs.name << endl;
return nullptr;
}
}
Value* NBlock::codeGen(CodeGenContext& context)
{
StatementList::const_iterator it;
Value *last = nullptr;
for (it = statements.begin(); it != statements.end(); it++) {
std::cout << "Generating code for " << typeid(**it).name() << endl;
last = (**it).codeGen(context);
}
std::cout << "Creating block" << endl;
return last;
}
Value* NExpressionStatement::codeGen(CodeGenContext& context)
{
std::cout << "Generating code for " << typeid(expression).name() << endl;
return expression.codeGen(context);
}
Value* NReturnStatement::codeGen(CodeGenContext& context)
{
std::cout << "Generating return code for " << typeid(expression).name() << endl;
if (expression) {
Value *returnValue = expression->codeGen(context);
context.setCurrentReturnValue(returnValue);
return returnValue;
} else {
return nullptr;
}
}
Value* NVariableDeclaration::codeGen(CodeGenContext& context)
{
std::cout << "Creating variable declaration " << type.name << " " << id.name << endl;
Value* var = nullptr;
if (context.isGlobalContext()) {
var = new GlobalVariable(*(context.module), typeOf(type), false, GlobalValue::PrivateLinkage,
Constant::getNullValue(typeOf(type)), id.name.c_str());
} else {
var = context.builder.CreateAlloca(typeOf(type));
}
context.locals()[id.name] = var;
if (assignmentExpr) {
NAssignment assn(id, *assignmentExpr);
assn.codeGen(context);
}
return var;
}
Value* NExternDeclaration::codeGen(CodeGenContext& context)
{
vector<Type*> argTypes;
VariableList::const_iterator it;
for (it = arguments.begin(); it != arguments.end(); it++) {
argTypes.push_back(typeOf((**it).type));
}
FunctionType *ftype = FunctionType::get(typeOf(type), makeArrayRef(argTypes), false);
Function *function = Function::Create(ftype, GlobalValue::ExternalLinkage, id.name.c_str(), context.module);
return function;
}
Value* NFunctionDeclaration::codeGen(CodeGenContext& context)
{
vector<Type*> argTypes;
VariableList::const_iterator it;
for (it = arguments.begin(); it != arguments.end(); it++) {
argTypes.push_back(typeOf((**it).type));
}
FunctionType *ftype = FunctionType::get(typeOf(type), makeArrayRef(argTypes), false);
Function *function = Function::Create(ftype, GlobalValue::InternalLinkage, id.name.c_str(), context.module);
BasicBlock *bblock = BasicBlock::Create(getGlobalContext(), "entry", function, 0);
context.pushBlock(bblock);
Function::arg_iterator argsValues = function->arg_begin();
Value* argumentValue;
for (it = arguments.begin(); it != arguments.end(); it++) {
(**it).codeGen(context);
argumentValue = argsValues++;
argumentValue->setName((*it)->id.name.c_str());
context.builder.CreateStore(argumentValue, context.findLocal((*it)->id.name));
}
block.codeGen(context);
ReturnInst::Create(getGlobalContext(), context.getCurrentReturnValue(), bblock);
context.popBlock();
std::cout << "Creating function: " << id.name << endl;
return function;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; 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 __FL_TEMP_H__
#define __FL_TEMP_H__
// records stored without Tags and payload length
// Bigendian storage
class DataStream_BaseRecord;
class DataStream_ByteArray;
#include "modules/datastream/fl_ref.h"
#include "modules/datastream/fl_int.h"
#include "modules/datastream/fl_tint.h"
#include "modules/datastream/fl_bytes.h"
#include "modules/datastream/fl_buffer.h"
#ifdef DATASTREAM_UINT_ENABLED
typedef DataStream_Reference<DataStream_UIntBase> DataStream_UIntReference;
#ifdef DATASTREAM_USE_INTEGRALTYPE_TEMPLATE
typedef DataStream_IntegralType<uint8, 1> DataStream_UInt8;
typedef DataStream_IntegralType<uint8, 1> DataStream_Octet;
typedef DataStream_IntegralType<uint16, 2> DataStream_UInt16;
typedef DataStream_IntegralType<uint32, 4> DataStream_UInt32;
#endif // DATASTREAM_USE_INTEGRALTYPE_TEMPLATE
#endif // DATASTREAM_UINT_ENABLED
#endif // __FL_TEMP_H__
|
#include <iostream>
using namespace std;
int main()
{
int n, a[100], required, cur, i;
bool success;
cin >> n;
for(int i = 0; i < n; i++)
cin >> a[i];
for(cur = 0; cur <= 100; cur++)
{
success = true;
//subtract first one
required = a[0] - cur;
for( i = 1; i < n; i++)
{
if(a[i] - cur == required|| a[i] + cur == required || a[i] == required)
continue;
success = false;
break;
}
if(success == true)
break;
//add to first one
success = true;
required = a[0] + cur;
for(i = 1; i < n; i++)
{
if(a[i] - cur == required|| a[i] + cur == required || a[i] == required)
continue;
success = false;
break;
}
if(success == true)
break;
}
if(success)
cout << cur << endl;
else
cout << -1 << endl;
}
|
#ifndef PPJ_PARSE_H
#define PPJ_PARSE_H
#include <string>
#include <vector>
using namespace std;
bool parseInt(string s, int &res);
bool parseChar(string s, int &res);
bool parseString(string s, vector<int> &res);
#endif
|
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
int findMin(vector<int>& nums) {
//基本思想:二分查找
int left=0,right=nums.size()-1;
while(left<right)
{
int mid=(left+right)/2;
if(nums[right]==nums[mid])
right--;
else if(nums[right]<nums[mid])
left=mid+1;
else
right=mid;
}
return nums[left];
}
};
int main()
{
Solution solute;
vector<int> nums = { 3,3,1,3 };
cout << solute.findMin(nums) << endl;
return 0;
}
|
#include<iostream>
#include"../game/game.h"
Game::Game()
{
std::cout << "constructor\n";
}
void Game::init_all()
{
std::cout << "initializing\n";
}
void Game::start()
{
std::cout << "Start!\n";
}
|
//#include "stdafx.h" //CRITICAL header information
#include "data_both.h"
#include "define_host.h"
#include "function_host.h"
#include "function_both.h" // remove this if logadd is not needed
// b111 build tiles
void cleararea(int x, int y, int lengthx, int lengthy);
void buildwall(int x, int y, int length, int buildtype, int wallstyle, int floorstyle);
void buildfloor(int x, int y, int lengthx, int lengthy, int floorstyle);
void buildwallrect(int x, int y, int lengthx, int lengthy, int buildtype, int wallstyle, int floorstyle);
void buildwallrect(int x, int y, int lengthx, int lengthy, int buildtype, int wallstyle, int floorstyle, int skipsideoption);
void buildwall2(int x, int y, int length, int buildtype, int wallstyle, int floorstyle, int begintileoption, int endtileoption);
void buildwallrect2(int x, int y, int lengthx, int lengthy, int buildtype, int wallstyle, int floorstyle, int skipsideoption);
// b111 build objects
//void buildwallobj(int x, int y, int length, int buildtype, int wallstyle, int floorstyle, int begintileoption, int endtileoption);
void buildwallobj(int x, int y, int length, int buildtype, int objnum, int begintileoption, int endtileoption);
void buildwallrectobj(int x, int y, int lengthx, int lengthy, int buildtype, int objnum, int skipsideoption);
void buildarch(int x, int y, int length, int buildtype, int archstart, int archlength, int wallstyle, int begintileoption, int endtileoption);
object* builddoor(int x, int y, int type, int doorstyle, int wallstyle, int floorstyle);
object* buildlever(int x, int y, object* door);
void buildstorage(int x, int y, int lengthx, int lengthy, int storagetype);
//void buildwallh(int x, int y, int length, int walltype, int wallstyle, int floorstyle);
//void buildwallv(int x, int y, int length, int walltype, int wallstyle, int floorstyle);
void house(){
static object *myobj=OBJnew(),*myobj2=OBJnew(),*myobj3=OBJnew(),*myobj4=OBJnew();
static long i=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0;
static long x=0,x2=0,x3=0,x4=0,x5=0,x6=0,x7=0,x8=0,x9=0;
static long y=0,y2=0,y3=0,y4=0,y5=0,y6=0,y7=0,y8=0,y9=0;
static long z=0,z2=0,z3=0,z4=0,z5=0,z6=0,z7=0,z8=0,z9=0;
static double d=0,d2=0,d3=0,d4=0,d5=0,d6=0,d7=0,d8=0,d9=0;
static unsigned char b=0,b2=0,b3=0,b4=0,b5=0,b6=0,b7=0,b8=0,b9=0;
static float f=0,f2=0,f3=0,f4=0,f5=0,f6=0,f7=0,f8=0,f9=0;
//init. house arrays
ZeroMemory(&housex1,sizeof(housex1)); ZeroMemory(&housey1,sizeof(housey1));
ZeroMemory(&housex2,sizeof(housex2)); ZeroMemory(&housey2,sizeof(housey2));
ZeroMemory(&housepnext,sizeof(housepnext));
ZeroMemory(&housepx,sizeof(housepx)); ZeroMemory(&housepy,sizeof(housepy));
ZeroMemory(&housecost,sizeof(housecost));
ZeroMemory(&houseinitialcost,sizeof(houseinitialcost));
ZeroMemory(&housestoragenext,sizeof(housestoragenext));
ZeroMemory(&housestoragex,sizeof(housestoragex)); ZeroMemory(&housestoragey,sizeof(housestoragey));
/* TODO/FIXME!
* the inefficient way of calling BTset (not in a loop etc) in the patches,
* causes a huge delay when optimizing house.cpp, and even when optimizing for size,
* still makes more than 1 MB of obj file. I think this contributes most to the size
* of the host/both versions. Speed is not needed here as it is a one time process.
* Consider patching basetiles file directly, or at least read in the patches at runtime and
* parse them, so we don't have an object file full of placing things on the stack,
* calling a function, rinse, repeat.
*/
// t111
int basex=0;
int basey=0;
int basecx = 0;
int basecy = 0;
int houseid;
int arenaid;
// init locations
hlocx[BUILD_HOUSEID_MANOR1][BUILD_SECTIONID_BASE] = 377;
hlocy[BUILD_HOUSEID_MANOR1][BUILD_SECTIONID_BASE] = 384-3;
#include "map_patches/house1.txt"
#include "map_patches/house2.txt"
#include "map_patches/house3.txt"
#include "map_patches/castlerooms.txt"
#include "map_patches/castlenonhousetiles.txt"
#include "map_patches/castlehousetiles.txt"
#include "map_patches/castlehousepatch.txt"
#include "map_patches/guardianguild.txt"
#include "map_patches/ragnor.txt"
#include "map_patches/katish.txt"
#include "map_patches/mose.txt"
#include "map_patches/bryan.txt"
#include "map_patches/darrell.txt"
#include "map_patches/notir.txt"
//#include "map_patches/toth.txt" //a house floating in the void with respawning staff. A BIG NO NO
#include "map_patches/forestfix.txt"
#include "map_patches/farm.txt"
#include "map_patches/spiritwood.txt"
#include "map_patches/steel.txt"
#include "map_patches/misc.txt"
#include "map_patches/shop.txt"
//#include "map_patches/dungeontest.txt"
/*
if (easymodehostn1) {
#include "map_patches/newhouse01.txt"
#include "map_patches/newhouse02.txt"
#include "map_patches/newhouse03.txt"
}
*/
// s111 check house storage slots used/placed and show warning on host if it is exceeded. Items may/will be lost.
int housenumnew = 0;
int storageusednew = 0;
for (int i=0; i < HOUSEMAX; i++) {
if (housecost[i] > 0) {
if (housestoragenext[i] > storageusednew) {
storageusednew = housestoragenext[i];
housenumnew = i;
}
}
}
//if (TRUE) {
//if (storageusednew >= 240) {
if (storageusednew >= HOUSESTORAGESLOTMAX - 30) {
txt *t2=txtnew();
txt *t3=txtnew();
txtset(t2, "--- WARNING!!! ---> One or more house has exceeded (or almost exceeded) the house storage slots limit! ITEMS may/will be LOST!");
LOGadd(t2);
txtset(t2, "--- Recommended action ---> Shutdown the server, backup saves, and fix the problem.");
LOGadd(t2);
txtset(t2, "storage used = housestoragenext = ");
txtnumint(t3, storageusednew);
txtadd(t2, t3);
LOGadd(t2);
txtset(t2, "storage max = HOUSESTORAGESLOTMAX = ");
txtnumint(t3, HOUSESTORAGESLOTMAX);
txtadd(t2, t3);
LOGadd(t2);
txtset(t2, "house number affected = ");
txtnumint(t3, housenumnew);
txtadd(t2, t3);
LOGadd(t2);
}
}//house
// b111 building stuff
void cleararea(int x, int y, int lengthx, int lengthy) {
int xi, yi;
object* obj;
for (yi = y; yi < y + lengthy; yi++) {
for (xi = x; xi < x + lengthx; xi++) {
obj = OBJfindlast(xi, yi);
if (obj)
OBJremove(obj);
}
}
}
void buildwallh(int x, int y, int length, int walltype, int wallstyle, int floorstyle) {
int lefttile, midtile, righttile;
int i;
if (wallstyle == 1) {
if (walltype == WALL_NORTH) {
// top
lefttile = 146;
midtile = 144;
if (floorstyle == 1)
righttile = 152;
else if (floorstyle == 2)
righttile = 147;
} else if (walltype == WALL_SOUTH) {
// bottom
righttile = 149;
midtile = 144;
if (floorstyle == 1)
lefttile = 153;
else if (floorstyle == 2)
lefttile = 148;
} else if (walltype == 3) {
// mid
lefttile = 144;
midtile = 144;
if (floorstyle == 1)
righttile = 150;
else if (floorstyle == 2)
righttile = 150;
}
} else if (wallstyle == 2) {
}
BTset(x, y, lefttile);
BTset(x + length - 1, y, righttile);
for (i = x + 1; i < x + length - 1; i++)
BTset(i, y, midtile);
}
void buildwallv(int x, int y, int length, int walltype, int wallstyle, int floorstyle) {
int begintile, endtile, tile;
int i;
if (wallstyle == 1) {
if (walltype == WALL_WEST) {
// top
begintile = 145;
tile = 145;
if (floorstyle == 1)
endtile = 145;
else if (floorstyle == 2)
endtile = 145;
} else if (walltype == WALL_EAST) {
// bottom
endtile = 145;
tile = 145;
if (floorstyle == 1)
begintile = 145;
else if (floorstyle == 2)
begintile = 145;
} else if (walltype == 3) {
// mid
begintile = 145;
tile = 145;
if (floorstyle == 1)
endtile = 145;
else if (floorstyle == 2)
endtile = 145;
}
} else if (wallstyle == 2) {
}
BTset(x, y, begintile);
BTset(x, y + length - 1, endtile);
for (i = y + 1; i < y + length - 1; i++)
BTset(x, i, tile);
}
void buildwall(int x, int y, int length, int buildtype, int wallstyle, int floorstyle) {
int begintile, tile, endtile;
int buildtype1;
int i;
if (wallstyle == 1) {
if (buildtype == WALL_NORTH) {
// north
buildtype1 = BUILD_TYPE_HORIZONTAL;
begintile = 146;
tile = 144;
if (floorstyle == 1)
endtile = 152;
else if (floorstyle == 2)
endtile = 147;
} else if (buildtype == WALL_SOUTH) {
// south
buildtype1 = BUILD_TYPE_HORIZONTAL;
endtile = 149;
tile = 144;
if (floorstyle == 1)
begintile = 153;
else if (floorstyle == 2)
begintile = 148;
} else if (buildtype == BUILD_TYPE_HORIZONTAL) {
// mid
buildtype1 = BUILD_TYPE_HORIZONTAL;
begintile = 144;
tile = 144;
if (floorstyle == 1)
endtile = 150;
else if (floorstyle == 2)
endtile = 150;
} else if (buildtype == WALL_WEST) {
// west
buildtype1 = BUILD_TYPE_VERTICAL;
begintile = 145;
tile = 145;
if (floorstyle == 1)
endtile = 145;
else if (floorstyle == 2)
endtile = 145;
} else if (buildtype == WALL_EAST) {
// east
buildtype1 = BUILD_TYPE_VERTICAL;
endtile = 145;
tile = 145;
if (floorstyle == 1)
begintile = 145;
else if (floorstyle == 2)
begintile = 145;
} else if (buildtype == BUILD_TYPE_VERTICAL) {
// mid
buildtype1 = BUILD_TYPE_VERTICAL;
begintile = 145;
tile = 145;
if (floorstyle == 1)
endtile = 145;
else if (floorstyle == 2)
endtile = 145;
}
} else if (wallstyle == 2) {
}
if (buildtype1 == BUILD_TYPE_HORIZONTAL) {
BTset(x, y, begintile);
BTset(x + length - 1, y, endtile);
for (i = x + 1; i < x + length - 1; i++)
BTset(i, y, tile);
} else if (buildtype1 == BUILD_TYPE_VERTICAL) {
BTset(x, y, begintile);
BTset(x, y + length - 1, endtile);
for (i = y + 1; i < y + length - 1; i++)
BTset(x, i, tile);
}
}
int getwalltile(int floorstyle, int wallstyle, int tileoption) {
int tile = 0;
if (wallstyle == BUILD_WALLSTYLE_STONE1) {
if (tileoption == BUILD_TILEOPTION_H) {
tile = 144;
} else if (tileoption == BUILD_TILEOPTION_V) {
tile = 145;
} else if (tileoption == BUILD_TILEOPTION_NW) {
tile = 146;
} else if (tileoption == BUILD_TILEOPTION_NE) {
if ((floorstyle == BUILD_FLOORSTYLE_BLUE1) || (floorstyle == BUILD_FLOORSTYLE_BLUE2)) {
tile = 147;
}
} else if (tileoption == BUILD_TILEOPTION_SW) {
if ((floorstyle == BUILD_FLOORSTYLE_BLUE1) || (floorstyle == BUILD_FLOORSTYLE_BLUE2)) {
tile = 148;
}
} else if (tileoption == BUILD_TILEOPTION_SE) {
tile = 149;
}
}
return tile;
}
void buildwall2(int x, int y, int length, int buildtype, int wallstyle, int floorstyle, int begintileoption, int endtileoption) {
int begintile, tile, endtile;
//int buildtype1;
int i;
/*
if (wallstyle == 1) {
if (begintileoption == BUILD_TILEOPTION_NW)
begintile = 146;
else if (begintileoption == BUILD_TILEOPTION_NE)
if (buildtype == WALL_NORTH) {
// north
buildtype1 = BUILD_TYPE_HORIZONTAL;
begintile = 146;
tile = 144;
if (floorstyle == 1)
endtile = 152;
else if (floorstyle == 2)
endtile = 147;
} else if (buildtype == WALL_SOUTH) {
// south
buildtype1 = BUILD_TYPE_HORIZONTAL;
endtile = 149;
tile = 144;
if (floorstyle == 1)
begintile = 153;
else if (floorstyle == 2)
begintile = 148;
} else if (buildtype == BUILD_TYPE_HORIZONTAL) {
// mid
buildtype1 = BUILD_TYPE_HORIZONTAL;
begintile = 144;
tile = 144;
if (floorstyle == 1)
endtile = 150;
else if (floorstyle == 2)
endtile = 150;
} else if (buildtype == WALL_WEST) {
// west
buildtype1 = BUILD_TYPE_VERTICAL;
begintile = 145;
tile = 145;
if (floorstyle == 1)
endtile = 145;
else if (floorstyle == 2)
endtile = 145;
} else if (buildtype == WALL_EAST) {
// east
buildtype1 = BUILD_TYPE_VERTICAL;
endtile = 145;
tile = 145;
if (floorstyle == 1)
begintile = 145;
else if (floorstyle == 2)
begintile = 145;
} else if (buildtype == BUILD_TYPE_VERTICAL) {
// mid
buildtype1 = BUILD_TYPE_VERTICAL;
begintile = 145;
tile = 145;
if (floorstyle == 1)
endtile = 145;
else if (floorstyle == 2)
endtile = 145;
}
} else if (wallstyle == 2) {
}
*/
begintile = getwalltile(floorstyle, wallstyle, begintileoption);
endtile = getwalltile(floorstyle, wallstyle, endtileoption);
if (buildtype == BUILD_TYPE_HORIZONTAL) {
tile = getwalltile(floorstyle, wallstyle, BUILD_TILEOPTION_H);
if (length > 0)
BTset(x, y, begintile);
if (length > 1)
BTset(x + length - 1, y, endtile);
for (i = x + 1; i < x + length - 1; i++)
BTset(i, y, tile);
} else if (buildtype == BUILD_TYPE_VERTICAL) {
tile = getwalltile(floorstyle, wallstyle, BUILD_TILEOPTION_V);
if (length > 0)
BTset(x, y, begintile);
if (length > 1)
BTset(x, y + length - 1, endtile);
for (i = y + 1; i < y + length - 1; i++)
BTset(x, i, tile);
}
}
void buildwallrect(int x, int y, int lengthx, int lengthy, int buildtype, int wallstyle, int floorstyle, int skipsideoption) {
/*
bool skipnorth = FALSE;
bool skipsouth = FALSE;
bool skipeast = FALSE;
bool skipwest = FALSE;
int xadj = 0, yadj = 0;
int lengthxadj = 0, lengthyadj = 0;
if (skipsideoption - BUILD_SKIPSIDE_WEST >= 0) {
skipwest = TRUE;
skipsideoption -= BUILD_SKIPSIDE_WEST;
}
if (skipsideoption - BUILD_SKIPSIDE_EAST >= 0) {
skipeast = TRUE;
skipsideoption -= BUILD_SKIPSIDE_EAST;
}
if (skipsideoption - BUILD_SKIPSIDE_SOUTH >= 0) {
skipsouth = TRUE;
skipsideoption -= BUILD_SKIPSIDE_SOUTH;
}
if (skipsideoption - BUILD_SKIPSIDE_NORTH >= 0) {
skipnorth = TRUE;
skipsideoption -= BUILD_SKIPSIDE_NORTH;
}
if (skipnorth) {
yadj--;
lengthyadj++;
}
if (skipsouth) {
// yadj--;
lengthyadj++;
}
if (skipeast) {
xadj--;
lengthxadj++;
}
if (skipwest) {
// yadj--;
lengthxadj++;
}
*/
buildwall(x, y, lengthx, WALL_NORTH, wallstyle, floorstyle);
buildwall(x, y + lengthy - 1, lengthx, WALL_SOUTH, wallstyle, floorstyle);
buildwall(x, y + 1, lengthy - 2, WALL_WEST, wallstyle, floorstyle);
buildwall(x + lengthx - 1, y + 1, lengthy - 2, WALL_EAST, wallstyle, floorstyle);
buildfloor(x + 1, y + 1, lengthx - 2, lengthy - 2, floorstyle);
}
void buildwallrect2(int x, int y, int lengthx, int lengthy, int buildtype, int wallstyle, int floorstyle, int skipsideoption) {
/*
buildwall2(x, y, lengthx, BUILD_TYPE_H, wallstyle, floorstyle, BUILD_TILEOPTION_NW, BUILD_TILEOPTION_NE);
buildwall2(x, y + lengthy - 1, lengthx, BUILD_TYPE_H, wallstyle, floorstyle, BUILD_TILEOPTION_SW, BUILD_TILEOPTION_SE);
buildwall2(x, y + 1, lengthy - 2, BUILD_TYPE_V, wallstyle, floorstyle, BUILD_TILEOPTION_V, BUILD_TILEOPTION_V);
buildwall2(x + lengthx - 1, y + 1, lengthy - 2, BUILD_TYPE_V, wallstyle, floorstyle, BUILD_TILEOPTION_V, BUILD_TILEOPTION_V);
buildfloor(x + 1, y + 1, lengthx - 2, lengthy - 2, floorstyle);
*/
bool skipnorth = FALSE;
bool skipsouth = FALSE;
bool skipwest = FALSE;
bool skipeast = FALSE;
int xadj = 1;
int yadj = 1;
int lengthxadj = -2;
int lengthyadj = -2;
int begintileoption1 = BUILD_TILEOPTION_NW;
int endtileoption1 = BUILD_TILEOPTION_NE;
int begintileoption2 = BUILD_TILEOPTION_SW;
int endtileoption2 = BUILD_TILEOPTION_SE;
int begintileoption3 = BUILD_TILEOPTION_V;
int endtileoption3 = BUILD_TILEOPTION_V;
int begintileoption4 = BUILD_TILEOPTION_V;
int endtileoption4 = BUILD_TILEOPTION_V;
//begintileoption = BUILD_TILEOPTION_H;
//endtileoption = BUILD_TILEOPTION_H;
if (skipsideoption - BUILD_SKIPSIDE_EAST >= 0) {
skipeast = TRUE;
skipsideoption -= BUILD_SKIPSIDE_EAST;
}
if (skipsideoption - BUILD_SKIPSIDE_WEST >= 0) {
skipwest = TRUE;
skipsideoption -= BUILD_SKIPSIDE_WEST;
}
if (skipsideoption - BUILD_SKIPSIDE_SOUTH >= 0) {
skipsouth = TRUE;
skipsideoption -= BUILD_SKIPSIDE_SOUTH;
}
if (skipsideoption - BUILD_SKIPSIDE_NORTH >= 0) {
skipnorth = TRUE;
skipsideoption -= BUILD_SKIPSIDE_NORTH;
}
if (skipnorth) {
yadj--;
lengthyadj++;
}
if (skipsouth) {
// yadj--;
lengthyadj++;
}
if (skipwest) {
xadj--;
lengthxadj++;
begintileoption1 = BUILD_TILEOPTION_H;
begintileoption2 = BUILD_TILEOPTION_H;
}
if (skipeast) {
lengthxadj++;
endtileoption1 = BUILD_TILEOPTION_H;
endtileoption2 = BUILD_TILEOPTION_H;
}
/*
if (skipnorth) {
begintileoption3 = BUILD_TILEOPTION_NW;
begintileoption4 = BUILD_TILEOPTION_NE;
}
if (skipsouth) {
endtileoption3 = BUILD_TILEOPTION_SW;
endtileoption4 = BUILD_TILEOPTION_SE;
}
*/
if (!skipnorth)
buildwall2(x, y, lengthx, BUILD_TYPE_H, wallstyle, floorstyle, begintileoption1, endtileoption1);
if (!skipsouth)
buildwall2(x, y + lengthy - 1, lengthx, BUILD_TYPE_H, wallstyle, floorstyle, begintileoption2, endtileoption2);
if (!skipwest)
buildwall2(x, y + yadj, lengthy + lengthyadj, BUILD_TYPE_V, wallstyle, floorstyle, begintileoption3, endtileoption3);
if (!skipeast)
buildwall2(x + lengthx - 1, y + yadj, lengthy + lengthyadj, BUILD_TYPE_V, wallstyle, floorstyle, begintileoption4, endtileoption4);
buildfloor(x + xadj, y + yadj, lengthx + lengthxadj, lengthy + lengthyadj, floorstyle);
}
void buildwallrect(int x, int y, int lengthx, int lengthy, int buildtype, int wallstyle, int floorstyle) {
buildwallrect(x, y, lengthx, lengthy, buildtype, wallstyle, floorstyle, BUILD_SKIPSIDE_NONE);
}
void buildfloor(int x, int y, int lengthx, int lengthy, int floorstyle) {
int lefttile, midtile, righttile;
int xi, yi;
if (floorstyle == 1) {
midtile = 214;
} else if (floorstyle == 2) {
midtile = 213;
} else if (floorstyle == BUILD_FLOORSTYLE_BLUE1) {
midtile = 213;
} else if (floorstyle == BUILD_FLOORSTYLE_BLUE2) {
midtile = 214;
//midtile = 214;
/*
if (floorstyle == WALL_NORTH) {
// top
lefttile = 146;
midtile = 144;
if (floorstyle == 1)
righttile = 152;
else if (floorstyle == 2)
righttile = 147;
} else if (floorstyle == WALL_SOUTH) {
// bottom
righttile = 149;
midtile = 144;
if (floorstyle == 1)
lefttile = 153;
else if (floorstyle == 2)
lefttile = 148;
} else if (floorstyle == 3) {
// mid
lefttile = 144;
midtile = 144;
if (floorstyle == 1)
righttile = 150;
else if (floorstyle == 2)
righttile = 150;
}
*/
}
//BTset(x, y, lefttile);
//BTset(x + length - 1, y, righttile);
for (yi = y; yi < y + lengthy; yi++) {
for (xi = x; xi < x + lengthx; xi++) {
BTset(xi, yi, midtile);
}
}
}
int getwallobj(int objnum, int tileoption) {
int tile = 0;
if (objnum == OBJ_TABLE) {
if (tileoption == BUILD_TILEOPTION_H) {
tile = OBJ_TABLE + 1024 * 4;
}
else if (tileoption == BUILD_TILEOPTION_V) {
tile = OBJ_TABLE + 1024 * 1;
}
else if (tileoption == BUILD_TILEOPTION_NW) {
tile = OBJ_TABLE + 1024 * 7;
}
else if (tileoption == BUILD_TILEOPTION_NE) {
tile = OBJ_TABLE + 1024 * 8;
}
else if (tileoption == BUILD_TILEOPTION_SW) {
tile = OBJ_TABLE + 1024 * 9; //
}
else if (tileoption == BUILD_TILEOPTION_SE) {
tile = OBJ_TABLE + 1024 * 10; //
}
else if (tileoption == BUILD_TILEOPTION_N) {
tile = OBJ_TABLE + 1024 * 0;
}
else if (tileoption == BUILD_TILEOPTION_S) {
tile = OBJ_TABLE + 1024 * 2;
}
else if (tileoption == BUILD_TILEOPTION_W) {
tile = OBJ_TABLE + 1024 * 3;
}
else if (tileoption == BUILD_TILEOPTION_E) {
tile = OBJ_TABLE + 1024 * 5;
}
} else if (objnum == OBJ_FENCE) {
if (tileoption == BUILD_TILEOPTION_H) {
tile = OBJ_FENCE + 1024 * 0;
}
else if (tileoption == BUILD_TILEOPTION_V) {
tile = OBJ_FENCE + 1024 * 1;
}
else if (tileoption == BUILD_TILEOPTION_NW) {
tile = OBJ_FENCE + 1024 * 2;
}
else if (tileoption == BUILD_TILEOPTION_NE) {
tile = OBJ_FENCE + 1024 * 3;
}
else if (tileoption == BUILD_TILEOPTION_SW) {
tile = OBJ_FENCE + 1024 * 5;
}
else if (tileoption == BUILD_TILEOPTION_SE) {
tile = OBJ_FENCE + 1024 * 4;
}
} else if (objnum == OBJ_ARCHWAY) {
if (tileoption == BUILD_TILEOPTION_H) {
tile = OBJ_ARCHWAY + 1024 * 0;
} else if (tileoption == BUILD_TILEOPTION_V) {
tile = OBJ_ARCHWAY + 1024 * 2;
} else if (tileoption == BUILD_TILEOPTION_N) {
//tile = OBJ_ARCHWAY + 1024 * 10;
tile = OBJ_DOORWAY + 1024 * 2;
} else if (tileoption == BUILD_TILEOPTION_S) {
tile = OBJ_ARCHWAY + 1024 * 3;
} else if (tileoption == BUILD_TILEOPTION_W) {
//tile = OBJ_ARCHWAY + 1024 * 11;
tile = OBJ_DOORWAY + 1024 * 0;
} else if (tileoption == BUILD_TILEOPTION_E) {
tile = OBJ_ARCHWAY + 1024 * 1;
}
} else if (objnum == OBJ_DOORWAY) {
if (tileoption == BUILD_TILEOPTION_H) {
//tile = OBJ_DOORWAY + 1024 * 0;
} else if (tileoption == BUILD_TILEOPTION_V) {
//tile = OBJ_DOORWAY + 1024 * 2;
} else if (tileoption == BUILD_TILEOPTION_N) {
tile = OBJ_DOORWAY + 1024 * 2;
} else if (tileoption == BUILD_TILEOPTION_S) {
tile = OBJ_DOORWAY + 1024 * 3;
} else if (tileoption == BUILD_TILEOPTION_W) {
tile = OBJ_DOORWAY + 1024 * 0;
} else if (tileoption == BUILD_TILEOPTION_E) {
tile = OBJ_DOORWAY + 1024 * 1;
}
} else {
tile = objnum + 1024 * 0;
}
return tile;
}
void buildwallobj(int x, int y, int length, int buildtype, int objnum, int begintileoption, int endtileoption) {
int begintile, tile, endtile;
int somenumber = 0;
int i, x2, y2;
bool storageobj = FALSE;
begintile = getwallobj(objnum, begintileoption);
endtile = getwallobj(objnum, endtileoption);
if (objnum == OBJ_TABLE) {
storageobj = TRUE;
somenumber = 5;
}
if (buildtype == BUILD_TYPE_HORIZONTAL) {
tile = getwallobj(objnum, BUILD_TILEOPTION_H);
//OBJaddnew(x, y, tile, 0, 5);
if (length > 0) {
x2 = x;
y2 = y;
//OBJaddnew(x, y, begintile, 0, somenumber);
OBJaddnew(x2, y2, begintile, 0, somenumber);
if (storageobj) {
if (buildtablewithstorage == BUILD_TABLEWITHSTORAGE_YES) {
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + x2;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + y2;
housestoragenext[basehousenumber + 0]++;
}
}
}
if (length > 1) {
x2 = x + length - 1;
y2 = y;
//OBJaddnew(x + length - 1, y, endtile, 0, somenumber);
OBJaddnew(x2, y2, endtile, 0, somenumber);
if (storageobj) {
if (buildtablewithstorage == BUILD_TABLEWITHSTORAGE_YES) {
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + x2;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + y2;
housestoragenext[basehousenumber + 0]++;
}
}
}
y2 = y;
for (i = x + 1; i < x + length - 1; i++) {
x2 = i;
//OBJaddnew(i, y, tile, 0, somenumber);
OBJaddnew(x2, y2, tile, 0, somenumber);
if (storageobj) {
if (buildtablewithstorage == BUILD_TABLEWITHSTORAGE_YES) {
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + x2;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + y2;
housestoragenext[basehousenumber + 0]++;
}
}
}
} else if (buildtype == BUILD_TYPE_VERTICAL) {
tile = getwallobj(objnum, BUILD_TILEOPTION_V);
if (length > 0) {
x2 = x;
y2 = y;
//OBJaddnew(x, y, begintile, 0, somenumber);
OBJaddnew(x2, y2, begintile, 0, somenumber);
if (storageobj) {
if (buildtablewithstorage == BUILD_TABLEWITHSTORAGE_YES) {
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + x2;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + y2;
housestoragenext[basehousenumber + 0]++;
}
}
}
if (length > 1) {
x2 = x;
y2 = y + length - 1;
//OBJaddnew(x, y + length - 1, endtile, 0, somenumber);
OBJaddnew(x2, y2, endtile, 0, somenumber);
if (storageobj) {
if (buildtablewithstorage == BUILD_TABLEWITHSTORAGE_YES) {
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + x2;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + y2;
housestoragenext[basehousenumber + 0]++;
}
}
}
x2 = x;
for (i = y + 1; i < y + length - 1; i++) {
y2 = i;
//OBJaddnew(x, i, tile, 0, somenumber);
OBJaddnew(x2, y2, tile, 0, somenumber);
if (storageobj) {
if (buildtablewithstorage == BUILD_TABLEWITHSTORAGE_YES) {
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + x2;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + y2;
housestoragenext[basehousenumber + 0]++;
}
}
}
}
}
void buildarch(int x, int y, int length, int buildtype, int archstart, int archlength, int wallstyle, int begintileoption, int endtileoption) {
int floorstyle = BUILD_FLOORSTYLE_BLUE2;
if (buildtype == BUILD_TYPE_HORIZONTAL) {
if (archstart > 0)
buildwall2(x, y, archstart, buildtype, wallstyle, floorstyle, begintileoption, BUILD_TILEOPTION_H);
//for (i = x; i < x + archstart; i++)
// BTset(i, y, tile);
if (archstart + archlength < length)
buildwall2(x + archstart + archlength, y, length - archstart - archlength, buildtype, wallstyle, floorstyle, BUILD_TILEOPTION_H, endtileoption);
//for (i = x + archstart + archlength; i < x + length; i++)
//BTset(i, y, tile);
buildfloor(x + archstart, y, archlength, 1, floorstyle);
buildwallobj(x + archstart, y, archlength, buildtype, OBJ_ARCHWAY, BUILD_TILEOPTION_W, BUILD_TILEOPTION_E);
} else if (buildtype == BUILD_TYPE_VERTICAL) {
if (archstart > 0)
buildwall2(x, y, archstart, buildtype, wallstyle, floorstyle, begintileoption, BUILD_TILEOPTION_V);
if (archstart + archlength < length)
buildwall2(x, y + archstart + archlength, length - archstart - archlength, buildtype, wallstyle, floorstyle, BUILD_TILEOPTION_V, endtileoption);
buildfloor(x, y + archstart, 1, archlength, floorstyle);
buildwallobj(x, y + archstart, archlength, buildtype, OBJ_ARCHWAY, BUILD_TILEOPTION_N, BUILD_TILEOPTION_S);
}
}
void buildwallrectobj(int x, int y, int lengthx, int lengthy, int buildtype, int objnum, int skipsideoption) {
bool skipnorth = FALSE;
bool skipsouth = FALSE;
bool skipwest = FALSE;
bool skipeast = FALSE;
bool endpoints = FALSE;
int xadj = 1;
int yadj = 1;
int lengthxadj = -2;
int lengthyadj = -2;
int begintileoption1 = BUILD_TILEOPTION_NW;
int endtileoption1 = BUILD_TILEOPTION_NE;
int begintileoption2 = BUILD_TILEOPTION_SW;
int endtileoption2 = BUILD_TILEOPTION_SE;
int begintileoption3 = BUILD_TILEOPTION_V;
int endtileoption3 = BUILD_TILEOPTION_V;
int begintileoption4 = BUILD_TILEOPTION_V;
int endtileoption4 = BUILD_TILEOPTION_V;
//begintileoption = BUILD_TILEOPTION_H;
//endtileoption = BUILD_TILEOPTION_H;
if (skipsideoption - BUILD_SKIPSIDE_ENDPOINTS >= 0) {
endpoints = TRUE;
skipsideoption -= BUILD_SKIPSIDE_ENDPOINTS;
}
if (skipsideoption - BUILD_SKIPSIDE_EAST >= 0) {
skipeast = TRUE;
skipsideoption -= BUILD_SKIPSIDE_EAST;
}
if (skipsideoption - BUILD_SKIPSIDE_WEST >= 0) {
skipwest = TRUE;
skipsideoption -= BUILD_SKIPSIDE_WEST;
}
if (skipsideoption - BUILD_SKIPSIDE_SOUTH >= 0) {
skipsouth = TRUE;
skipsideoption -= BUILD_SKIPSIDE_SOUTH;
}
if (skipsideoption - BUILD_SKIPSIDE_NORTH >= 0) {
skipnorth = TRUE;
skipsideoption -= BUILD_SKIPSIDE_NORTH;
}
if (skipnorth) {
yadj--;
lengthyadj++;
if (endpoints) {
begintileoption3 = BUILD_TILEOPTION_N;
begintileoption4 = BUILD_TILEOPTION_N;
}
}
if (skipsouth) {
// yadj--;
lengthyadj++;
if (endpoints) {
endtileoption3 = BUILD_TILEOPTION_S;
endtileoption4 = BUILD_TILEOPTION_S;
}
}
if (skipwest) {
xadj--;
lengthxadj++;
begintileoption1 = BUILD_TILEOPTION_H;
begintileoption2 = BUILD_TILEOPTION_H;
if (endpoints) {
begintileoption1 = BUILD_TILEOPTION_W;
begintileoption2 = BUILD_TILEOPTION_W;
}
}
if (skipeast) {
lengthxadj++;
endtileoption1 = BUILD_TILEOPTION_H;
endtileoption2 = BUILD_TILEOPTION_H;
if (endpoints) {
endtileoption1 = BUILD_TILEOPTION_E;
endtileoption2 = BUILD_TILEOPTION_E;
}
}
/*
if (skipnorth) {
begintileoption3 = BUILD_TILEOPTION_NW;
begintileoption4 = BUILD_TILEOPTION_NE;
}
if (skipsouth) {
endtileoption3 = BUILD_TILEOPTION_SW;
endtileoption4 = BUILD_TILEOPTION_SE;
}
*/
if (!skipnorth)
buildwallobj(x, y, lengthx, BUILD_TYPE_H, objnum, begintileoption1, endtileoption1);
if (!skipsouth)
buildwallobj(x, y + lengthy - 1, lengthx, BUILD_TYPE_H, objnum, begintileoption2, endtileoption2);
if (!skipwest)
buildwallobj(x, y + yadj, lengthy + lengthyadj, BUILD_TYPE_V, objnum, begintileoption3, endtileoption3);
if (!skipeast)
buildwallobj(x + lengthx - 1, y + yadj, lengthy + lengthyadj, BUILD_TYPE_V, objnum, begintileoption4, endtileoption4);
}
object* builddoor(int x, int y, int type, int doorstyle, int wallstyle, int floorstyle) {
int begintile, endtile, floortile;
int i;
int doorframe1, doorframe2;
int door1, door2;
object* door = NULL;
if (floorstyle == 1) {
} else if (floorstyle == 2) {
floortile = 214;
}
if (type == BUILD_TYPE_HORIZONTAL) {
if (doorstyle == 1) {
door1 = OBJ_PORTCULLIS + 1024 * 0;
door2 = OBJ_PORTCULLIS + 1024 * 1;
} else if (doorstyle == 2) {
}
if (wallstyle == 1) {
doorframe1 = OBJ_DOORWAY + 1024 * 0;
doorframe2 = OBJ_DOORWAY + 1024 * 1;
} else if (wallstyle == 2) {
}
BTset(x - 1, y, floortile);
BTset(x, y, floortile);
OBJaddnew(x - 1, y, doorframe1, 0, 0);
OBJaddnew(x, y, doorframe2, 0, 0);
//myobj=OBJaddnew(hx,hy,OBJ_STEEL_DOOR+1024*6,0,170);//matched door pair
//myobj->more=(object*)OBJaddnew(hx,hy+1,OBJ_STEEL_DOOR+1024*7,0,(unsigned long)myobj);//matched door pair
door = OBJaddnew(x - 1, y, door1, 0, 0);
object* item102 = OBJaddnew(x, y, door2, 0, 0);
door->more = item102;
} else if (type == BUILD_TYPE_VERTICAL) {
if (doorstyle == 1) {
door1 = OBJ_PORTCULLIS + 1024 * 2;
door2 = OBJ_PORTCULLIS + 1024 * 3;
} else if (doorstyle == 2) {
}
if (wallstyle == 1) {
doorframe1 = OBJ_DOORWAY + 1024 * 2;
doorframe2 = OBJ_DOORWAY + 1024 * 3;
} else if (wallstyle == 2) {
}
BTset(x, y - 1, floortile);
BTset(x, y, floortile);
OBJaddnew(x, y - 1, doorframe1, 0, 0);
OBJaddnew(x, y, doorframe2, 0, 0);
//myobj=OBJaddnew(hx,hy,OBJ_STEEL_DOOR+1024*6,0,170);//matched door pair
//myobj->more=(object*)OBJaddnew(hx,hy+1,OBJ_STEEL_DOOR+1024*7,0,(unsigned long)myobj);//matched door pair
door = OBJaddnew(x, y - 1, door1, 0, 0);
object* item102 = OBJaddnew(x, y, door2, 0, 0);
door->more = item102;
}
return door;
}
object* buildlever(int x, int y, object* door) {
object* lever = OBJaddnew(x, y, OBJ_LEVER + 1024 * 0, 0, 0);
lever->more = door;
return lever;
}
void buildstorage(int x, int y, int lengthx, int lengthy, int storagetype) {
// right of arena
// row 1 (starting from top row) storage
//basecx = basex - 2;
//basecy = basey;
int basecx, basecy;
int hx, hy, hi;
basecx = x - 20;
basecy = y - 1;
hx = basecx + 20; hy = basecy + 1;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 3, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 27; hy = basecy + 1;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 5, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 21; hy = basecy + 1;
for (hx = basecx + 21; hx < basecx + 27; hx++) {
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 4, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
}
// row 2 storage
hx = basecx + 20; hy = basecy + 2;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 3, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 27; hy = basecy + 2;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 5, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 21; hy = basecy + 2;
for (hx = basecx + 21; hx < basecx + 27; hx++) {
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 4, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
}
// row 3 storage
hx = basecx + 20; hy = basecy + 4;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 3, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 27; hy = basecy + 4;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 5, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 21; hy = basecy + 4;
for (hx = basecx + 21; hx < basecx + 27; hx++) {
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 4, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
}
// row 4 storage
hx = basecx + 20; hy = basecy + 5;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 3, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 27; hy = basecy + 5;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 5, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 21; hy = basecy + 5;
for (hx = basecx + 21; hx < basecx + 27; hx++) {
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 4, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
}
// row 5 storage
hx = basecx + 20; hy = basecy + 7;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 3, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 27; hy = basecy + 7;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 5, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 21; hy = basecy + 7;
for (hx = basecx + 21; hx < basecx + 27; hx++) {
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 4, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
}
// row 6 storage
hx = basecx + 20; hy = basecy + 8;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 3, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 27; hy = basecy + 8;
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 5, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
hx = basecx + 21; hy = basecy + 8;
for (hx = basecx + 21; hx < basecx + 27; hx++) {
OBJaddnew(hx, hy, OBJ_TABLE + 1024 * 4, 0, 5);
housestoragex[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchx + hx;
housestoragey[basehousenumber + 0][housestoragenext[basehousenumber + 0]] = patchy + hy;
housestoragenext[basehousenumber + 0]++;
}
}
|
#include "RogueAttack.h"
RogueAttack::RogueAttack(Unit* instance): Attack(instance) {}
void RogueAttack::attack(Unit* enemy) {
enemy->takeDamage(this->instance->getDmg());
}
|
#include<bits/stdc++.h>
#define MAX 10
using namespace std;
int a[100];
int n;
void input(){
cin >> n;
for(int i = 0; i < n; i++)
cin >> a[i];
}
int main(){
freopen("XYZ.inp", "r", stdin);
freopen("XYZ.out", "w", stdout);
input();
int s = 0;
bitset<MAX> myBit[100];
for (int i = 0; i < n; ++i) {
myBit[i] = bitset<MAX>(a[i]);
}
for (int i = 0; i < n; ++i) {
for (int j = i+1; j < n; ++j) {
int bit = static_cast<int>((myBit[i] ^ myBit[j]).to_ullong());
s+=bit;
}
}
cout << s;
return 0;
}
|
////////////////////////////////////////////////////////////////////////////////
#include "extrude_mesh.h"
#include <polyfem/MeshUtils.hpp>
#include <igl/all_edges.h>
#include <igl/boundary_loop.h>
#include <igl/bfs_orient.h>
#include <igl/orient_outward.h>
#include <igl/triangle/triangulate.h>
#include <igl/copyleft/tetgen/tetrahedralize.h>
////////////////////////////////////////////////////////////////////////////////
namespace cellogram {
// -----------------------------------------------------------------------------
void extrude_mesh(const Eigen::MatrixXd &V1, const Eigen::MatrixXi &F1, double thickness, Eigen::MatrixXd &VT, Eigen::MatrixXi &FT, Eigen::MatrixXi &TT) {
// 1. Create box vertices
const int n = V1.rows();
double z0 = (V1.cols() < 3 ? 0 : V1.col(2).mean());
Eigen::RowVector2d minV = V1.colwise().minCoeff().head<2>();
Eigen::RowVector2d maxV = V1.colwise().maxCoeff().head<2>();
Eigen::MatrixXd V2(V1.rows() + 4, 3);
V2.topLeftCorner(V1.rows(), V1.cols()) = V1;
V2.col(2).setConstant(z0);
V2.bottomRows(4) <<
minV(0), minV(1), z0 + thickness,
maxV(0), minV(1), z0 + thickness,
maxV(0), maxV(1), z0 + thickness,
minV(0), maxV(1), z0 + thickness;
Eigen::MatrixXi F2 = F1;
// 2. Project coordinate of boundary points of input surface to lie exactly on the bbox boundary
Eigen::MatrixXi E;
igl::all_edges(F1, E);
std::vector<bool> boundary_vertex(V2.rows(), false);
double eps = 1e-9 * (maxV - minV).sum();
for (int e = 0; e < E.rows(); ++e) {
for (int lv = 0; lv < 2; ++lv) {
boundary_vertex[E(e, lv)] = true;
for (int d : {0, 1}) {
double &x = V2(E(e, lv), d);
if (std::abs(x - minV(d)) < eps) {
x = minV(d);
} else if (std::abs(x - maxV(d)) < eps) {
x = maxV(d);
}
}
}
}
for (int i = 0; i < 4; ++i) {
boundary_vertex.rbegin()[i] = true;
}
// 3. Trivial triangulation of boundary vertices
std::cout << "n = " << n << std::endl;
for (int d = 0; d < 2; ++d) {
for (double coord : {minV(d), maxV(d)}) {
std::vector<std::pair<double, int>> top;
std::vector<std::pair<double, int>> bottom;
for (int v = 0; v < V2.rows(); ++v) {
if (boundary_vertex[v] && V2(v, d) == coord) {
if (v < n) {
top.emplace_back(V2(v, 1 - d), v);
} else {
bottom.emplace_back(V2(v, 1 - d), v);
}
}
}
cel_assert(bottom.size() == 2);
std::sort(top.begin(), top.end());
std::sort(bottom.begin(), bottom.end());
const int f0 = F2.rows();
F2.conservativeResize(F2.rows() + top.size(), F2.cols());
for (size_t i = 0; i < top.size(); ++i) {
F2.row(f0 + i) << bottom.front().second, top[i].second, (i + 1 == top.size() ? bottom.back().second : top[i + 1].second);
}
}
}
// 4. Trivial trangulation of bottom side
const int f0 = F2.rows();
F2.conservativeResize(F2.rows() + 2, F2.cols());
F2.row(f0+0) << n+0, n+1, n+2;
F2.row(f0+1) << n+2, n+0, n+3;
// 5. Orient facets and tetrahedralize
Eigen::VectorXi C;
igl::bfs_orient(F2, F2, C);
igl::copyleft::tetgen::tetrahedralize(V2, F2, "Qq1.414", VT, TT, FT);
polyfem::orient_closed_surface(VT, FT);
}
void extrude_mesh_old(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, double thickness, Eigen::MatrixXd &VT, Eigen::MatrixXi &FT, Eigen::MatrixXi &TT) {
// Extract boundary loop
Eigen::VectorXi L;
igl::boundary_loop(F, L);
// Extract boundary edge-graph
int n = L.size();
Eigen::MatrixXd VC(n, 2);
Eigen::MatrixXi EC(n, 2);
for (int i = 0; i < n; ++i) {
VC.row(i) = V.row(L(i)).head<2>();
EC.row(i) << i, (i+1)%n;
}
// Triangulate outer-face
Eigen::MatrixXd V2;
Eigen::MatrixXi F2;
igl::triangle::triangulate(VC, EC, Eigen::MatrixXd(0, 2), "QqY", V2, F2);
// Sanity check
Eigen::VectorXi L2;
igl::boundary_loop(F2, L2);
cel_assert(L2.size() == n);
cel_assert(L2.maxCoeff() + 1 == L2.size()); // boundary vertices should be the first indices
// Stitch both sides
Eigen::MatrixXd VS(V.rows() + V2.rows(), 3);
VS.topLeftCorner(V.rows(), 2) = V.leftCols<2>();
VS.topRightCorner(V.rows(), 1).setZero();
VS.bottomLeftCorner(V2.rows(), 2) = V2;
VS.bottomRightCorner(V2.rows(), 1).setConstant(thickness);
Eigen::MatrixXi FS(F.rows() + F2.rows() + 2 * L.size(), 3);
FS.topRows(F.rows()) = F;
FS.middleRows(F.rows(), F2.rows()) = F2.array() + V.rows();
for (int vo = V.rows(), fo = F.rows() + F2.rows(), i = 0; i < n; ++i) {
cel_assert(L2(i) == i);
FS.row(fo + 2*i + 0) << L(i), L((i+1)%n), L2(i)+vo;
FS.row(fo + 2*i + 1) << L2(i)+vo, L2((i+1)%n)+vo, L((i+1)%n);
}
// Orient faces coherently
Eigen::VectorXi C;
igl::bfs_orient(FS, FS, C);
// Mesh volume
igl::copyleft::tetgen::tetrahedralize(VS, FS, "Qq1.414", VT, TT, FT);
polyfem::orient_closed_surface(VT, FT);
}
// -----------------------------------------------------------------------------
} // namespace cellogram
|
#include "Matrix.hpp"
using namespace cv;
using namespace uipf;
// get content (returns a cloned version of Mat by default)
// this is due to prevent overwriting accidentally
Mat Matrix::getContent(bool bAutoClone /*= true*/) const{
if (bAutoClone)
return matrix_.clone();
else
return matrix_;
}
// sets the content of the matrix
/*
m new matrix content
*/
void Matrix::setContent(Mat& m){
matrix_ = m;
}
// returns the data type of this data object: in this case: MATRIX
Type Matrix::getType() const {
return MATRIX;
}
|
#pragma once
#include "proto/data_base.pb.h"
#include "proto/data_event.pb.h"
#include "proto/config_shop.pb.h"
using namespace std;
namespace pd = proto::data;
namespace pc = proto::config;
namespace nora {
namespace scene {
class role;
pd::result mys_shop_free_refresh_goods(uint32_t pttid, pd::event_res *event_res, role& role);
pd::result mys_shop_refresh_goods(uint32_t pttid, pd::event_res *event_res, role& role);
pd::result mys_shop_check_buy(uint32_t pttid, uint32_t good_id, const role& role);
pd::event_res mys_shop_buy(uint32_t pttid, uint32_t good_id, role& role);
pd::result shop_check_buy(uint32_t shop, uint32_t good_id, const role& role);
pd::event_res shop_buy(uint32_t shop, uint32_t good_id, role& role, pd::event_res *merge_res, bool send_bi);
}
}
|
#include <iostream>
void reverseString(std::string& str, int size) {
char* ptr1 = nullptr;
char* ptr2 = nullptr;
for (int i = 0; i < size / 2; ++i) {
ptr1 = &str[i];
ptr2 = &str[size - i - 1];
char tmp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = tmp;
}
}
int main() {
std::string str;
std::cout << "Enter any string: ";
getline(std::cin, str);
int size = str.size();
reverseString(str, size);
std::cout << "Reverse: " << str << std::endl;
return 0;
}
|
#include<iostream>
using namespace std;
int main(){
//input
int *hash = new int[1005];
for(int i=0;i<1005;++i){
hash[i] = 0;
}
int n;
cin>>n;
for(int i=0;i<n;++i){
int number;
cin>>number;
for(int j=0;j<number;++j){
int temp;
cin>>temp;
++hash[temp];
}
}
int result_sign = -1;
int max_time = 0;
for(int i=1;i<1001;++i){
if(hash[i]>=max_time){
max_time = hash[i];
result_sign = i;
}
}
cout<<result_sign<<' '<<max_time;
return 0;
}
|
#include <iostream>
#include <vector>
typedef long long ll;
int n;
ll table[21][21];
ll Combination(ll n, ll r)
{
if(n == r || r == 0)
{
return 1;
}
if(table[n][r] > 0)
{
return table[n][r];
}
return table[n][r] = Combination(n - 1, r - 1) + Combination(n - 1, r);
}
ll factorial(ll n)
{
ll ret = 1;
for(int i = 2; i <= n; i++)
{
ret *= i;
}
return ret;
}
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
ll ans = 0;
std::cin >> n;
ans = Combination(n - 1, n / 2 - 1) * factorial(n / 2 - 1) * factorial(n / 2 - 1);
std::cout << ans << '\n';
return 0;
}
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <stdio.h>
#include <string.h>
#include <time.h>
using namespace std;
#define MAX_N 55
#define MOD 1000000007
int X,Y;
bool used[MAX_N][MAX_N];
vector<string> f;
typedef pair<int, int> P;
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
class GooseInZooDivOne {
public:
bool
bfs(int x,int y,int D)
{
queue<P> q;
q.push(P(x,y));
int c = 1;
while (!q.empty()) {
P p = q.front(); q.pop();
for (int cx = p.first-D; cx <= p.first+D; ++cx) {
for (int cy = p.second-D; cy <= p.second+D; ++cy) {
if (abs(p.first-cx)+abs(p.second-cy) <= D && 0 <= cx && cx < X && 0 <= cy && cy < Y && f[cy][cx] == 'v' && !used[cy][cx]) {
q.push(P(cx,cy));
used[cy][cx] = true;
++c;
}
}
}
}
return c&1;
}
long long
modPow(long long x,long long n,long long m)
{
if (n == 0) return 1;
long long res = modPow((x*x)%m, n/2, m);
if (n&1) res = (res*x)%m;
return res;
}
long long
inv(long long x)
{
return modPow(x, MOD-2, MOD);
}
long long
factorial(int a)
{
long long res = 1;
for (int i=a; i>1; --i) {
res *= i%MOD;
res = res%MOD;
}
return res;
}
int
count(vector <string> field, int dist)
{
memset(used, false, sizeof(used));
f = field;
Y = (int)field.size() , X = (int)field[0].size();
int odd = 0 , even = 0;
for (int y=0; y<Y; ++y) {
for (int x=0; x<X; ++x) {
if (field[y][x] == 'v' && !used[y][x]) {
used[y][x] = true;
if(bfs(x, y, dist))
++odd;
else
++even;
}
}
}
long long e = modPow(2, even, MOD);
long long o = 1;
for (int r = 2; r <= odd; r += 2) {
o += (factorial(odd) * inv((factorial(r)*factorial(odd-r))%MOD))%MOD;
o = o%MOD;
}
long long ans = (e*o)%MOD;
return ans = (ans-1+MOD)%MOD;
}
// BEGIN CUT HERE
public:
void run_test(int Case) {
if ((Case == -1) || (Case == 0)) test_case_0();
if ((Case == -1) || (Case == 1)) test_case_1();
if ((Case == -1) || (Case == 2)) test_case_2();
if ((Case == -1) || (Case == 3)) test_case_3();
if ((Case == -1) || (Case == 4)) test_case_4();
if ((Case == -1) || (Case == 5)) test_case_5();
}
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"vvv"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; int Arg2 = 3; verify_case(0, Arg2, count(Arg0, Arg1)); }
void test_case_1() { string Arr0[] = {"."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 100; int Arg2 = 0; verify_case(1, Arg2, count(Arg0, Arg1)); }
void test_case_2() { string Arr0[] = {"vvv"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 0; verify_case(2, Arg2, count(Arg0, Arg1)); }
void test_case_3() {
string Arr0[] =
{"v.v..................v............................"
,".v......v..................v.....................v"
,"..v.....v....v.........v...............v......v..."
,".........vvv...vv.v.........v.v..................v"
,".....v..........v......v..v...v.......v..........."
,"...................vv...............v.v..v.v..v..."
,".v.vv.................v..............v............"
,"..vv.......v...vv.v............vv.....v.....v....."
,"....v..........v....v........v.......v.v.v........"
,".v.......v.............v.v..........vv......v....."
,"....v.v.......v........v.....v.................v.."
,"....v..v..v.v..............v.v.v....v..........v.."
,"..........v...v...................v..............v"
,"..v........v..........................v....v..v..."
,"....................v..v.........vv........v......"
,"..v......v...............................v.v......"
,"..v.v..............v........v...............vv.vv."
,"...vv......v...............v.v..............v....."
,"............................v..v.................v"
,".v.............v.......v.........................."
,"......v...v........................v.............."
,".........v.....v..............vv.................."
,"................v..v..v.........v....v.......v...."
,"........v.....v.............v......v.v............"
,"...........v....................v.v....v.v.v...v.."
,"...........v......................v...v..........."
,"..........vv...........v.v.....................v.."
,".....................v......v............v...v...."
,".....vv..........................vv.v.....v.v....."
,".vv.......v...............v.......v..v.....v......"
,"............v................v..........v....v...."
,"................vv...v............................"
,"................v...........v........v...v....v..."
,"..v...v...v.............v...v........v....v..v...."
,"......v..v.......v........v..v....vv.............."
,"...........v..........v........v.v................"
,"v.v......v................v....................v.."
,".v........v................................v......"
,"............................v...v.......v........."
,"........................vv.v..............v...vv.."
,".......................vv........v.............v.."
,"...v.............v.........................v......"
,"....v......vv...........................v........."
,"....vv....v................v...vv..............v.."
,".................................................."
,"vv........v...v..v.....v..v..................v...."
,".........v..............v.vv.v.............v......"
,".......v.....v......v...............v............."
,"..v..................v................v....v......"
,".....v.....v.....................v.v......v......."};
vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; int Arg2 = 898961330; verify_case(3, Arg2, count(Arg0, Arg1));
}
void test_case_4() {
string Arr0[] =
{".v..."
, "v.v.v", ".....", "....."};vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 1; verify_case(4, Arg2, count(Arg0, Arg1));
}
void test_case_5() {
string Arr0[] =
{".vv..v.........v....", "....v.......vv...vvv", "...vv.v....v..vv....", "v......v....vv...v..", "..v..v..vv.v..vv....", "..v....v.v.....v...v", ".v......v..vv...v...", "vv..............v...", "..v..v.....vv.v.v..v", "v.........vv...v....", "......v..v.v.....v..", ".....v.....v....v..v", "..v.v....v.v.....v..", "..v.......vvv.....v.", "....v....v.vv.....v.", ".v...v.............v", "..vv.....v.........v", "..v.................", "v.........v.........", "v...........v....v..", "v.......v..........."};vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; int Arg2 = 280261901; verify_case(5, Arg2, count(Arg0, Arg1));
}
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
GooseInZooDivOne ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#ifndef ADD_CONNECTOR_H
#define ADD_CONNECTOR_H
#include "Action.h"
#include "..\Statements\Connector.h"
//Add Connector Action
//This class is responsible for
// 1 - Getting the first stat. coordinates from the user
// 2 - Getting the second stat. coordinates from the user
// 3 - Creating an object of Connector class and fill it parameters
// 4 - Adding the created object to the list of connectors
class AddConnector : public Action
{
private:
Point Position; //Position where the user clicks to add the stat.
Point Start; //The start point of the connector
Point End; //The end point of the connector
Statement *SrcStat; //the source statement of the connector
Statement *DstStat; //the destination statement of the connector
int ConnType;
public:
AddConnector(ApplicationManager *pAppManager);
//Read Connector parameters
virtual void ReadActionParameters();
//Create and add an connector to the list of connector
virtual void Execute() ;
};
#endif
|
#pragma once
#include <iterator>
void QuickSort(size_t low, size_t high, std::vector<int>& data)
{
if (data.empty() || data.size() == 1 || low >= high)
{
return;
}
int base = data[low];
size_t lowTemp = low;
size_t highTemp = high;
while (lowTemp < highTemp)
{
while (data[highTemp] >= base&& highTemp > lowTemp)
{
--highTemp;
}
while (data[lowTemp] <= base&& highTemp > lowTemp)
{
++lowTemp;
}
if (lowTemp < highTemp)
{
std::swap(data[highTemp], data[lowTemp]);
}
}
data[low] = data[lowTemp];
data[lowTemp] = base;
if (lowTemp == low)
{
QuickSort(lowTemp + 1, high, data);
}
else if (lowTemp == high)
{
QuickSort(low, lowTemp - 1, data);
}
else
{
QuickSort(low, lowTemp - 1, data);
QuickSort(lowTemp + 1, high, data);
}
}
|
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Audio/Music.hpp>
#include "GlobalniePer.h"
#include "Racket.h"
#include "Ball.h"
#include <string>
#include <time.h> //!
#include <Windows.h> //!
Racket left(1);
Racket right(0);
Ball ball;
float speed = 0; //!
void menu(sf::RenderWindow &window) {
sf::Texture Backgr;
Backgr.loadFromFile("images/back.jpg");
sf::Sprite backgr(Backgr);
backgr.setPosition(0, 0);
sf::Texture Menu1, Menu2, Menu3, About, Pong;
Menu1.loadFromFile("images/play.png");
Menu2.loadFromFile("images/about.png");
Menu3.loadFromFile("images/exit.png");
About.loadFromFile("images/Programmer.png");
Pong.loadFromFile("images/Pong.png");
sf::Sprite menu1(Menu1), menu2(Menu2), menu3(Menu3), about(About), pong(Pong);
bool isMenu = 1;
int menunum = 0;
menu1.setPosition(495, 280);
menu2.setPosition(495, 360);
menu3.setPosition(495, 420);
pong.setPosition(495, 180);
about.setPosition(0, 0);
while (isMenu)
{
menu1.setColor(sf::Color::White);
menu2.setColor(sf::Color::White);
menu3.setColor(sf::Color::White);
menunum = 0;
window.clear();
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
if (sf::IntRect(475, 340, 300, 50).contains(sf::Mouse::getPosition(window))) {
menu1.setColor(sf::Color::Black); menunum = 1;
}
if (sf::IntRect(475, 420, 300, 50).contains(sf::Mouse::getPosition(window))) {
menu2.setColor(sf::Color::Black); menunum = 2;
}
if (sf::IntRect(475, 480, 300, 50).contains(sf::Mouse::getPosition(window))) {
menu3.setColor(sf::Color::Black); menunum = 3;
}
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
if (menunum == 1) isMenu = false;
if (menunum == 2) {
window.draw(backgr);
window.draw(about);
window.display();
while (!sf::Keyboard::isKeyPressed(sf::Keyboard::Escape));
}
if (menunum == 3) {
window.close();
isMenu = false;
}
}
window.draw(backgr);
window.draw(pong);
window.draw(menu1);
window.draw(menu2);
window.draw(menu3);
window.display();
}
}
int Player1_ = 0;
int Player2_ = 0;
void Collision()
{
if ((ball.pos.y < left.pos.y + 40) && (ball.pos.y > left.pos.y - 40) && (ball.pos.x < 20))
{
ball.dir.x *= -1;
ball.pos.x = 20; //!
}
if ((ball.pos.y < right.pos.y + 40) && (ball.pos.y > right.pos.y - 40) && (ball.pos.x > 1250))
{
ball.dir.x *= -1;
ball.pos.x = 1250; //!
}
if (ball.pos.x < 0)
{
ball.pos = { width / 2,height / 2 };
left.pos = { 10, height / 2 };
right.pos = { width - 20,height / 2 };
speed = 0; //!
Player1_++;
}
if (ball.pos.x > 1265)
{
ball.pos = { width / 2,height / 2 };
left.pos = { 10, height / 2 };
right.pos = { width - 20,height / 2 };
speed = 0; //!
Player2_++;
}
}
void main()
{
sf::Music sound;
sound.openFromFile("music.ogg");
sound.setVolume(10.f);
sound.play();
sound.setLoop(true);
long long unsigned int tick = 0; //!
long long unsigned int frame_period = 0; //!
int delta_tick = 0; //!
setlocale(LC_ALL, "Russian");
sf::RenderWindow window(sf::VideoMode(width, height), "Pong by Student from KFU");
sf::Texture Backgr;
Backgr.loadFromFile("images/back1.jpg");
sf::Sprite backgr(Backgr);
backgr.setPosition(0, 0);
back:
menu(window);
sf::Text Player1;
sf::Text Player2;
sf::Text Name1;
sf::Text Name2;
sf::Font Cyrilica;
Cyrilica.loadFromFile("CyrilicOld.TTF");
Player1.setFont(Cyrilica);
Player1.setCharacterSize(30);
Player1.setFillColor(sf::Color::Color(255, 255, 255));
Player1.setPosition(width / 2 + 80, 40);
Player2.setFont(Cyrilica);
Player2.setCharacterSize(30);
Player2.setFillColor(sf::Color::Color(255, 255, 255));
Player2.setPosition(width / 2 - 120, 40);
Name1.setFont(Cyrilica);
Name1.setCharacterSize(30);
Name1.setFillColor(sf::Color::Color(255, 255, 255));
Name1.setPosition(width / 2 + 50, 0);
Name2.setFont(Cyrilica);
Name2.setCharacterSize(30);
Name2.setFillColor(sf::Color::Color(255,255,255));
Name2.setPosition(width / 2 - 150, 0);
while (window.isOpen())
{
delta_tick = clock() - tick;
tick = clock();
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) speed = 1.5;
Sleep(1);
Collision();
left.move(1, delta_tick * speed);
right.move(0, delta_tick * speed);
ball.move(delta_tick * speed);
;
Name1.setString("Игрок 2");
Name2.setString("Игрок 1");
Player1.setString(std::to_string(Player1_));
Player2.setString(std::to_string(Player2_));
if (clock() - frame_period > 60 / CLOCKS_PER_SEC) //!
{
frame_period = clock();
window.clear();
window.draw(backgr);
left.drawTo(window);
right.drawTo(window);
ball.drawTo(window);
window.draw(Name1);
window.draw(Name2);
window.draw(Player1);
window.draw(Player2);
window.display();
}
if (Player1_ == 10 || Player2_ == 10)
{
Player1_ = 0; //!
Player2_ = 0; //!
speed = 0; //!
ball.pos = { width / 2,height / 2 };
left.pos = { 10, height / 2 };
right.pos = { width - 20,height / 2 };
goto back;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
Player1_ = 0;
Player2_ = 0;
speed = 0;
ball.pos = { width / 2,height / 2 };
left.pos = { 10, height / 2 };
right.pos = { width - 20,height / 2 };
goto back;
}
}
}
|
#ifndef FORMAVERAGEDEVIATION_H
#define FORMAVERAGEDEVIATION_H
#include <QWidget>
#include <QComboBox>
#include <QDoubleSpinBox>
namespace Ui {
class FormAverageDeviation;
}
class FormAverageDeviation : public QWidget
{
Q_OBJECT
public:
explicit FormAverageDeviation(QWidget *parent = 0);
~FormAverageDeviation();
private:
Ui::FormAverageDeviation *ui;
signals:
void tendencyMeasureChanged(QString);
void scalingFactorChanged(double);
void roundingValueChanged(QString);
protected slots:
void tendencyChanged(QString val);
};
#endif // FORMAVERAGEDEVIATION_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.