text
stringlengths
8
6.88M
#pragma once #include "GameNode6.h" struct tagTimeLineInfo { int x; int y; }; enum TIME { TIME_SECOND, TIME_MINUTE, TIME_HOUR, TIME_END }; struct tagTimeNameInfo { int time; int x; int y; }; class MainGame7 : public GameNode6 { private: RECT clock; tagTimeLineInfo timeLineInfo[3]; tagTimeNameInfo timeNameInfo[12]; SYSTEMTIME st; public: MainGame7(); ~MainGame7(); HRESULT Init() override; void Release() override; void Update() override; void Render(HDC hdc) override; };
#pragma once #include "stdafx.h" #include "TestBase.h" class Station; class CallsignTests : public TestBase { public: CallsignTests(); virtual ~CallsignTests(); virtual bool Setup(); virtual void Teardown(); virtual bool RunAllTests(); bool TestN0H_BAR(); bool TestVE9AA(); bool TestOM2VL(); private: };
#include <bits/stdc++.h> using namespace std; typedef long long int ll; using ii= pair<ll,ll>; #define all(o) (o).begin(),(o).end() #define F first #define S second #define MP make_pair #define PB push_back //using min_of_3=min({ll a,ll b,ll c}); class prioritize{ public: bool operator() (ii &p1,ii &p2){ return p1.F<p2.F; } }; ll power(ll n,ll y) { if(y==0) return 1; else if (y%2==0) return power(n,y/2)*power(n,y/2); else return n*power(n,y/2)*power(n,y/2); } long long maxPrimeFactors(long long n) { long long maxPrime = -1; while (n % 2 == 0) { maxPrime = 2; n >>= 1; } for (int i = 3; i <= sqrt(n); i += 2) { while (n % i == 0) { maxPrime = i; n = n / i; } } if (n > 2) maxPrime = n; return maxPrime; } ll spf(ll n) { if(n%2==0) return 2; else{ for(ll i=3;i<=sqrt(n);i+=2) { if(n%i==0) return i; } } return n; } bool checker(ll n,ll s) { ll sum=0; ll x = n; while(x) { sum+=(x%10); x = x/10; } if(n-sum>=s) return true; else return false; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL); ll n,s; cin>>n>>s; if(!checker(n,s)) { cout<<0<<"\n"; } else{ ll start = 0; ll mid = 0; ll end = n; ll ans=0; while(start<=end) { mid = start + ((end-start)/2); if(checker(mid,s)) { if(!checker(mid-1,s)) { ans = mid-1; break; } else{ end = mid-1; } } else{ if(checker(mid+1,s)) { ans = mid; break; } else{ start = mid+1; } } } cout<<(n-ans); } }
#include <bits/stdc++.h> using namespace std; int main() { bool marq[1000005]={0}; int n, tot=0, est=0, pt=0, sitio[1000005]; scanf("%d", &n); for(int i=0;i<n;i++) { scanf("%d", &sitio[i]); tot+=sitio[i]; } while(pt>=0 && pt<n) { if(sitio[pt]%2) { if(marq[pt]==false) est++; if(sitio[pt]) { sitio[pt]--; tot--; } marq[pt]=true; pt++; } else { if(marq[pt]==false) est++; if(sitio[pt]) { sitio[pt]--; tot--; } marq[pt]=true; pt--; } } printf("%d %d\n", est, tot); return 0; }
extern "C" { #include <libavcodec/avcodec.h> #include <libavutil/opt.h> #include <libavutil/imgutils.h> #include <libswscale/swscale.h> }; class AvEncoder { public: AvEncoder(); ~AvEncoder(); bool init(char* codec_name, int width, int height); void encode(unsigned char* buffer); private: bool rgba_to_yuv420(AVFrame* frmArgb, AVFrame* frm420p); AVCodec* codec; AVCodecContext* context; AVFrame* frmArgb; AVFrame* frm420p; AVPacket* pkt; };
// Created on: 2002-11-13 // Created by: Galina KULIKOVA // Copyright (c) 2002-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 _ShapeUpgrade_RemoveLocations_HeaderFile #define _ShapeUpgrade_RemoveLocations_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TopAbs_ShapeEnum.hxx> #include <TopoDS_Shape.hxx> #include <TopTools_DataMapOfShapeShape.hxx> #include <Standard_Transient.hxx> class ShapeUpgrade_RemoveLocations; DEFINE_STANDARD_HANDLE(ShapeUpgrade_RemoveLocations, Standard_Transient) //! Removes all locations sub-shapes of specified shape class ShapeUpgrade_RemoveLocations : public Standard_Transient { public: //! Empty constructor Standard_EXPORT ShapeUpgrade_RemoveLocations(); //! Removes all location correspodingly to RemoveLevel. Standard_EXPORT Standard_Boolean Remove (const TopoDS_Shape& theShape); //! Returns shape with removed locations. TopoDS_Shape GetResult() const; //! sets level starting with that location will be removed, //! by default TopAbs_SHAPE. In this case locations will be kept for specified shape //! and if specified shape is TopAbs_COMPOUND for sub-shapes of first level. void SetRemoveLevel (const TopAbs_ShapeEnum theLevel); //! sets level starting with that location will be removed.Value of level can be set to //! TopAbs_SHAPE,TopAbs_COMPOUND,TopAbs_SOLID,TopAbs_SHELL,TopAbs_FACE.By default TopAbs_SHAPE. //! In this case location will be removed for all shape types for exception of compound. TopAbs_ShapeEnum RemoveLevel() const; //! Returns modified shape obtained from initial shape. TopoDS_Shape ModifiedShape (const TopoDS_Shape& theInitShape) const; DEFINE_STANDARD_RTTIEXT(ShapeUpgrade_RemoveLocations,Standard_Transient) protected: private: Standard_EXPORT Standard_Boolean MakeNewShape (const TopoDS_Shape& theShape, const TopoDS_Shape& theAncShape, TopoDS_Shape& theNewShape, const Standard_Boolean theRemoveLoc); TopAbs_ShapeEnum myLevelRemoving; TopoDS_Shape myShape; TopTools_DataMapOfShapeShape myMapNewShapes; }; #include <ShapeUpgrade_RemoveLocations.lxx> #endif // _ShapeUpgrade_RemoveLocations_HeaderFile
// Copyright 2012 Yandex #ifndef LTR_LEARNERS_DECISION_TREE_DECISION_VERTEX_H_ #define LTR_LEARNERS_DECISION_TREE_DECISION_VERTEX_H_ #include <string> #include "ltr/learners/decision_tree/utility/utility.h" #include "ltr/learners/decision_tree/decision_tree.h" namespace ltr { namespace decision_tree { /** * DecisionVertex is a node, which returns value of the child * with the greatest condition */ template <class TValue> class DecisionVertex : public Vertex<TValue> { public: typedef ltr::utility::shared_ptr<DecisionVertex<TValue> > Ptr; DecisionVertex() : Vertex<TValue>() {} explicit DecisionVertex(Condition::Ptr condition) : Vertex<TValue>(condition) {} TValue value(const Object& object) const; string generateCppCode(const string& function_name) const; private: virtual string getDefaultAlias() const; }; template<class TValue> typename DecisionVertex<TValue>::Ptr DecisionVertexPtr() { return typename DecisionVertex<TValue>::Ptr(new DecisionVertex<TValue>()); } template<class TValue> typename DecisionVertex<TValue>::Ptr DecisionVertexPtr(Condition::Ptr condition) { return typename DecisionVertex<TValue>::Ptr( new DecisionVertex<TValue>(condition)); } // template realizations template <class TValue> TValue DecisionVertex<TValue>::value(const Object& object) const { typename Vertex<TValue>::Ptr best_child; double max_value = 0; if (!this->hasChild()) { throw std::logic_error("non list vertex has no children"); } typename Vertex<TValue>::Ptr child = this->firstChild(); while (child != NULL) { double cond_value = child->condition()->value(object); if (best_child == NULL || max_value < cond_value) { best_child = child; max_value = cond_value; } child = child->nextSibling(); } return best_child->value(object); } template <class TValue> string DecisionVertex<TValue>::generateCppCode( const string& function_name) const { string hpp_code; int number_of_childs = 0; typename Vertex<TValue>::Ptr child = this->firstChild(); while (child != NULL) { hpp_code.append(child->condition()->generateCppCode()); hpp_code.append(child->generateCppCode()); child = child->nextSibling(); number_of_childs++; } hpp_code. append("inline "). append(ClassName<TValue>()). append(" "). append(function_name). append("(const std::vector<double>& features) {\n"). append(" typedef "). append(ClassName<TValue>()). append(" (*vertex_function_ptr)"). append("(const std::vector<double>&);\n"). append(" typedef "). append("double (*condition_function_ptr)"). append("(const std::vector<double>&);\n"). append(" condition_function_ptr conditions[] = {"); // Create array of condition functions child = this->firstChild(); if (child != NULL) { INFO("Child is not NULL."); hpp_code.append(child->condition()->getDefaultSerializableObjectName()); child = child->nextSibling(); } while (child != NULL) { hpp_code. append(", "). append(child->condition()->getDefaultSerializableObjectName()); child = child->nextSibling(); } hpp_code.append("};\n vertex_function_ptr children[] = {"); // Create array of children functions child = this->firstChild(); if (child != NULL) { INFO("Child is not NULL."); hpp_code.append(child->getDefaultSerializableObjectName()); child = child->nextSibling(); } while (child != NULL) { hpp_code. append(", "). append(child->getDefaultSerializableObjectName()); child = child->nextSibling(); } hpp_code. append("};\n"). append(" int best_id = -1;\n"). append(" double best_condition = 0;\n"). append(" for (int i = 0; i < "). append(boost::lexical_cast<string>(number_of_childs)). append("; ++i) {\n"). append(" double val = conditions[i](features);\n"). append(" if (best_id == -1 || val > best_condition) {\n"). append(" best_id = i;\n"). append(" best_condition = val;\n"). append(" }\n"). append(" }\n"). append(" return children[best_id](features);\n"). append("}\n"); return hpp_code; } template <class TValue> string DecisionVertex<TValue>::getDefaultAlias() const { return "Decision Vertex"; } }; }; #endif // LTR_LEARNERS_DECISION_TREE_DECISION_VERTEX_H_
// Created on: 1995-01-27 // Created by: Marie Jose MARTZ // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepToIGES_BRWire_HeaderFile #define _BRepToIGES_BRWire_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <BRepToIGES_BREntity.hxx> #include <TopTools_DataMapOfShapeShape.hxx> class IGESData_IGESEntity; class TopoDS_Shape; class TopoDS_Vertex; class TopoDS_Edge; class TopoDS_Face; class Geom_Surface; class TopLoc_Location; class gp_Pnt2d; class TopoDS_Wire; //! This class implements the transfer of Shape Entities //! from Geom To IGES. These can be : //! . Vertex //! . Edge //! . Wire class BRepToIGES_BRWire : public BRepToIGES_BREntity { public: DEFINE_STANDARD_ALLOC Standard_EXPORT BRepToIGES_BRWire(); Standard_EXPORT BRepToIGES_BRWire(const BRepToIGES_BREntity& BR); //! Transfert a Shape entity from TopoDS to IGES //! this entity must be a Vertex or an Edge or a Wire. //! If this Entity could not be converted, //! this member returns a NullEntity. Standard_EXPORT Handle(IGESData_IGESEntity) TransferWire (const TopoDS_Shape& start); //! Transfert a Vertex entity from TopoDS to IGES //! If this Entity could not be converted, //! this member returns a NullEntity. Standard_EXPORT Handle(IGESData_IGESEntity) TransferVertex (const TopoDS_Vertex& myvertex); //! Transfert a Vertex entity on an Edge from TopoDS to IGES //! Returns the parameter of myvertex on myedge. //! If this Entity could not be converted, //! this member returns a NullEntity. Standard_EXPORT Handle(IGESData_IGESEntity) TransferVertex (const TopoDS_Vertex& myvertex, const TopoDS_Edge& myedge, Standard_Real& parameter); //! Transfert a Vertex entity of an edge on a Face //! from TopoDS to IGES //! Returns the parameter of myvertex on the pcurve //! of myedge on myface //! If this Entity could not be converted, //! this member returns a NullEntity. Standard_EXPORT Handle(IGESData_IGESEntity) TransferVertex (const TopoDS_Vertex& myvertex, const TopoDS_Edge& myedge, const TopoDS_Face& myface, Standard_Real& parameter); //! Transfert a Vertex entity of an edge on a Surface //! from TopoDS to IGES //! Returns the parameter of myvertex on the pcurve //! of myedge on mysurface //! If this Entity could not be converted, //! this member returns a NullEntity. Standard_EXPORT Handle(IGESData_IGESEntity) TransferVertex (const TopoDS_Vertex& myvertex, const TopoDS_Edge& myedge, const Handle(Geom_Surface)& mysurface, const TopLoc_Location& myloc, Standard_Real& parameter); //! Transfert a Vertex entity on a Face from TopoDS to IGES //! Returns the parameters of myvertex on myface //! If this Entity could not be converted, //! this member returns a NullEntity. Standard_EXPORT Handle(IGESData_IGESEntity) TransferVertex (const TopoDS_Vertex& myvertex, const TopoDS_Face& myface, gp_Pnt2d& mypoint); //! Transfert an Edge 3d entity from TopoDS to IGES //! If edge is REVERSED and isBRepMode is False 3D edge curve is reversed //! @param[in] theEdge input edge to transfer //! @param[in] theOriginMap shapemap contains the original shapes. Should be empty if face is not reversed //! @param[in] theIsBRepMode indicates if write mode is BRep //! @return Iges entity or null if could not be converted Standard_EXPORT Handle(IGESData_IGESEntity) TransferEdge (const TopoDS_Edge& theEdge, const TopTools_DataMapOfShapeShape& theOriginMap, const Standard_Boolean theIsBRepMode); //! Transfert an Edge 2d entity on a Face from TopoDS to IGES //! @param[in] theEdge input edge to transfer //! @param[in] theFace input face to get the surface and UV coordinates from it //! @param[in] theOriginMap shapemap contains the original shapes. Should be empty if face is not reversed //! @param[in] theLength input surface length //! @param[in] theIsBRepMode indicates if write mode is BRep //! @return Iges entity or null if could not be converted Standard_EXPORT Handle(IGESData_IGESEntity) TransferEdge (const TopoDS_Edge& theEdge, const TopoDS_Face& theFace, const TopTools_DataMapOfShapeShape& theOriginMap, const Standard_Real theLength, const Standard_Boolean theIsBRepMode); //! Transfert a Wire entity from TopoDS to IGES //! If this Entity could not be converted, //! this member returns a NullEntity. Standard_EXPORT Handle(IGESData_IGESEntity) TransferWire (const TopoDS_Wire& mywire); //! Transfert a Wire entity from TopoDS to IGES. //! @param[in] theWire input wire //! @param[in] theFace input face //! @param[in] theOriginMap shapemap contains the original shapes. Should be empty if face is not reversed //! @param[in] theCurve2d input curve 2d //! @param[in] theLength input surface length //! @return Iges entity (the curve associated to mywire in the parametric space of myface) //! or null if could not be converted Standard_EXPORT Handle(IGESData_IGESEntity) TransferWire (const TopoDS_Wire& theWire, const TopoDS_Face& theFace, const TopTools_DataMapOfShapeShape& theOriginMap, Handle(IGESData_IGESEntity)& theCurve2d, const Standard_Real theLength); protected: private: }; #endif // _BRepToIGES_BRWire_HeaderFile
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <string.h> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #define rev for(std::string::reverse_iterator rit=str.rbegin(); rit!=str.rend(); ++rit) {std::cout << *rit;}cout << "\n"; #define ll long long int using namespace std; namespace patch{ template<typename T>std::string to_string(const T& n){ std::ostringstream stm; stm << n; return stm.str(); } } int main(){ int n; cin >> n; while(n != -1){ int ans = 0,sum = 0, temp, arr[n]; for(int i = 0; i < n; i++){ cin >> arr[i]; sum += arr[i]; } temp = sum / n; if(temp * n == sum){ for(int i = 0; i < n; i++){ if(temp > arr[i]){ ans += temp - arr[i]; } } cout << ans << "\n"; }else{ cout << "-1"<<"\n"; } cin >> n; } return 0; }
class Category_605 { duplicate = 487; }; class Category_640 { duplicate = 487; };
#pragma once #include "aePrerequisitesCore.h" #include <aePrerequisitesUtil.h> namespace aeEngineSDK { class AE_CORE_EXPORT aeApplication { protected: virtual AE_RESULT Init(); virtual AE_RESULT StatusUptade(); virtual void Render(); virtual void Logic(); virtual void Destroy(); public: aeApplication(); aeApplication(const aeApplication& A); virtual ~aeApplication(); virtual AE_RESULT Run(); virtual void Resize(uint32 X, uint32 Y); virtual void Stop(); }; }
#include <iberbar/RHI/D3D11/Effect.h> #include <iberbar/RHI/D3D11/ShaderState.h> #include <iberbar/RHI/D3D11/ShaderReflection.h> #include <iberbar/RHI/D3D11/ShaderVariables.h> #include <iberbar/RHI/D3D11/Shader.h> #include <iberbar/RHI/D3D11/Buffer.h> #include <iberbar/RHI/D3D11/Device.h> iberbar::RHI::D3D11::CEffect::CEffect( IShaderState* pShaderState ) : IEffect() , m_pShaderState( nullptr ) , m_UniformMemorys() , m_UniformBuffers() //, m_UniformBuffersDirty() { memset( m_UniformMemorys, 0, sizeof( m_UniformMemorys ) ); memset( m_UniformBuffers, 0, sizeof( m_UniformBuffers ) ); //memset( m_UniformBuffersDirty, 0, sizeof( m_UniformBuffersDirty ) ); CShader* pShader = nullptr; CShaderReflection* pReflection = nullptr; const CShaderReflectionBuffer* pReflectionBuffer = nullptr; int nBufferSizeTotalForShader; for ( int i = 0, s = (int)EShaderType::__Count; i < s; i++ ) { pShader = m_pShaderState->GetShaderInternal( (EShaderType)i ); if ( pShader == nullptr ) continue; pReflection = pShader->GetReflectionInternal(); if ( pShader == nullptr ) continue; nBufferSizeTotalForShader = pReflection->GetBufferSizeTotal(); if ( nBufferSizeTotalForShader > 0 ) { m_UniformMemorys[ i ] = new uint8[ nBufferSizeTotalForShader ]; memset( m_UniformMemorys[ i ], 0, nBufferSizeTotalForShader ); } for ( int nBufferIndex = 0, nBufferCount = pReflection->GetBufferCountInternal(); nBufferIndex < nBufferCount; nBufferIndex++ ) { pReflectionBuffer = pReflection->GetBufferByIndexInternal( nBufferIndex ); if ( pReflectionBuffer == nullptr ) continue; m_UniformBuffers[ i ][ pReflectionBuffer->GetBindPoint() ] = new CUniformBuffer( m_pShaderState->GetDevice(), pReflectionBuffer->GetSize() ); } } } iberbar::RHI::D3D11::CEffect::~CEffect() { UNKNOWN_SAFE_RELEASE_NULL( m_pShaderState ); for ( int i = 0, s = (int)EShaderType::__Count; i < s; i++ ) { SAFE_DELETE_ARRAY( m_UniformMemorys[ i ] ); for ( int j = 0; j < D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT; j++ ) { UNKNOWN_SAFE_RELEASE_NULL( m_UniformBuffers[ i ][ j ] ); } } } void iberbar::RHI::D3D11::CEffect::SetShaderVariables( EShaderType nShaderType, IShaderVariableTable* pShaderVariables ) { if ( m_UniformMemorys[ (int)nShaderType ] == nullptr ) return; CShaderVariableTable* pShaderVariablesInternal = (CShaderVariableTable*)pShaderVariables; assert( pShaderVariablesInternal->GetShaderInternal() == m_pShaderState->GetShaderInternal( nShaderType ) ); assert( pShaderVariablesInternal->GetMemory() ); CShader* pShader = m_pShaderState->GetShaderInternal( nShaderType ); assert( pShader != nullptr ); CShaderReflection* pShaderReflection = pShader->GetReflectionInternal(); assert( pShaderReflection != nullptr ); int nBufferCount = pShaderReflection->GetBufferCountInternal(); assert( nBufferCount > 0 ); int nBufferSizeTotal = pShaderReflection->GetBufferSizeTotal(); assert( nBufferSizeTotal == pShaderVariablesInternal->GetMemorySize() ); const uint8* pShaderVariablesMemory = pShaderVariablesInternal->GetMemory(); if ( memcmp( m_UniformMemorys[ (int)nShaderType ], pShaderVariablesMemory, 0 ) == 0 ) return; CUniformBuffer** pSlots = m_UniformBuffers[ (int)nShaderType ]; CUniformBuffer* pSlotTemp; int nSlotIndex; const CShaderReflectionBuffer* pShaderReflectionBuffer = nullptr; int nBufferMemoryOffset = 0; int nBufferMemorySize = 0; for ( int i = 0, s = nBufferCount; i < s; i++ ) { pShaderReflectionBuffer = pShaderReflection->GetBufferByIndexInternal( i ); nBufferMemoryOffset = pShaderReflectionBuffer->GetOffset(); nBufferMemorySize = pShaderReflectionBuffer->GetSize(); if ( memcmp( m_UniformMemorys[ (int)nShaderType ] + nBufferMemoryOffset, pShaderVariablesMemory + nBufferMemoryOffset, nBufferMemorySize ) == 0 ) continue; nSlotIndex = pShaderReflectionBuffer->GetBindPoint(); pSlotTemp = pSlots[ nSlotIndex ]; if ( pSlotTemp == nullptr ) continue; pSlotTemp->UpdateContents( pShaderVariablesMemory + nBufferMemoryOffset, nBufferMemorySize ); //m_UniformBuffersDirty[ (int)nShaderType ][ nSlotIndex ] = 1; } }
#include <SoftwareSerial.h> SoftwareSerial mySerial(1, 0);//Initialize serial communications on pins 1TX, 0RX void setup(){ mySerial.begin(9600) } void loop(){ }
//果然还是得一段一段来,process注释掉竟然没问题了,就是说process部分竟然能影响输入 //我他妈也是佩服自己了 while里面的3个for循环全是++A_index. 不死循环才怪呢 //你他妈的就不能一开始就检查吗 非得调试半天 还调试 我真是日了狗了 //检查出这个改了以后就能在小黑框里面运行样例成功了 //这次算是用了下hash吧 和原来的比了一下 无论速度还是内存都不如原来的 //原来的那个加速版的还不如不加速版的 不过这一次的代码长度减少不少原来(73)这次(55) //看了下大概懂原来是怎么写的了 现在客观评价的话,还是现在的代码好懂一点 简洁一点 //不过依然是 在同一个复杂度内就不用太纠结了 系数差不太多就不管 //2017-02-26 22:27:21 50分 #include<cstdio> #include<iostream> using namespace std; int main(){ //input int n; fscanf(stdin, "%d", &n); int* A = new int[n+10]; int* B = new int[n+10]; int* C = new int[n+10]; for(int i=0;i<n;++i){ fscanf(stdin,"%d",&(A[i])); } for(int i=0;i<n;++i){ fscanf(stdin,"%d",&(B[i])); } for(int i=0;i<n;++i){ fscanf(stdin,"%d",&(C[i])); } int k; fscanf(stdin,"%d",&k); //process int* hash = new int[n+10]; int A_index=0; int B_index=0; int C_index=0; for(int i=0;i<(n+10);++i){ hash[i] = 0; } int sign = 0; while(sign==0){ for(;hash[(A[A_index])]!=0;++A_index); if(A[A_index]==k){ cout<<"A"; sign = 1; } hash[(A[A_index])]=8; ++A_index; for(;hash[(B[B_index])]!=0;++B_index); if(B[B_index]==k){ cout<<"B"; sign = 1; } hash[(B[B_index])]=8; ++B_index; for(;hash[(C[C_index])]!=0;++C_index); if(C[C_index]==k){ cout<<"C"; sign = 1; } hash[(C[C_index])]=8; ++C_index; } return 0; }
#include <iostream> #include <utility> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/conf.h> #include "CryptoFunctions.h" using namespace std; int main(int argc, char *argv[]) { const char* c_file; const char* sk_file; const char * iv_file; const char* sig_file; const char* p_file; const char* pubk_file; //Argument Parsing for (int i = 1; i < argc; ++i) { string arg = argv[i]; if ((arg == "-c") || (arg == "--ciphertext")) { if (i + 1 < argc) { c_file = argv[i+1]; cout << "ciphertext: " << c_file << "\n"; } } else if ((arg == "-p") || (arg == "--plaintext")) { if (i + 1 < argc) { p_file = argv[i+1]; cout << "Plaintext: " << p_file << "\n"; } } else if ((arg == "-b") || (arg == "--publickey")) { if (i + 1 < argc) { pubk_file = argv[i+1]; cout << "Publickey: " << pubk_file << "\n"; } } else if ((arg == "-k") || (arg == "--sessionkey")) { if (i + 1 < argc) { sk_file = argv[i+1]; cout << "Session Key: " << sk_file << "\n"; } } else if ((arg == "-i") || (arg == "--iv")) { if (i + 1 < argc) { iv_file = argv[i+1]; cout << "IV: " << iv_file << "\n"; } } else if ((arg == "-s") || (arg == "--signature")) { if (i + 1 < argc) { sig_file = argv[i+1]; cout << "Signature: " << sig_file << "\n"; } } } DecryptPlaintext(c_file, sk_file, iv_file); VerifySign(p_file, sig_file, pubk_file); }
// // OpenGLIncludes.h // Crapenstein // // Created by Bruno Caceiro on 23/05/14. // Copyright (c) 2014 Bruno Caceiro. All rights reserved. // #ifndef Crapenstein_OpenGLIncludes_h #define Crapenstein_OpenGLIncludes_h #ifdef __APPLE__ #include <GLUT/glut.h> #include <OpenGL/gl.h> #else #include <GL/gl.h> #include <GL/glu.h> #include <GL/freeglut.h> #endif #include <cmath> #include <vector> #include <iostream> //#include "materiais.h" #define AZUL 0.0, 0.0, 1.0, 1.0 #define BLUE 0.0, 0.0, 1.0, 1.0 #define VERMELHO 1.0, 0.0, 0.0, 1.0 #define RED 1.0, 0.0, 0.0, 1.0 #define VERDE 0.0, 1.0, 0.0, 1.0 #define GREEN 0.0, 1.0, 0.0, 1.0 #define BRANCO 1.0, 1.0, 1.0, 1.0 #define WHITE 1.0, 1.0, 1.0, 1.0 #define YELLOW 1.0, 1.0, 0.0, 1.0 #define ORANGE 1.0, 0.5, 0.1, 1.0 #define BLACK 0.0, 0.0, 0.0, 1.0 #define GRAY 0.9, 0.92, 0.29, 1.0 #define PI 3.14159 using namespace std; #endif
#ifndef WALI_TESTING_KEYS_HPP #define WALI_TESTING_KEYS_HPP #include "wali/Key.hpp" namespace testing { struct Keys { wali::Key st1, st2, st3, st4, st5; wali::Key a, b; Keys(): st1(wali::getKey("state1")), st2(wali::getKey("state2")), st3(wali::getKey("state3")), st4(wali::getKey("state4")), st5(wali::getKey("state5")), a(wali::getKey("a")), b(wali::getKey("b")) {} }; } // Yo emacs! // Local Variables: // c-file-style: "ellemtel" // c-basic-offset: 2 // indent-tabs-mode: nil // End: #endif
#include <vector> #include "Panel.h" #define FONT_LINE_HEIGHT 40.0f / 512.0f Panel::Panel(Scene& scene, Font& font, glm::vec4 transform) : GuiElement(scene, font, transform){ background = new Gui; background->color = Color {0.5f, 0.5f, 0.5f, 1.0f}; text = new GuiText(font); text->borderColor.a = 0.0f; text->centered = true; text->color = Color {1.0f, 1.0f, 1.0f, 1.0f}; text->spacing = 0.55f; text->fontSize = 0.5f; scene.guis->push_back(background); scene.guiTexts->push_back(text); setTransform(transform); setVisible(false); } void Panel::setTransform(glm::vec4 transform) { GuiElement::setTransform(transform); glm::vec4 glTrans = TO_GL_COORDS(transform); background->transform.posx = glTrans.x; background->transform.posy = glTrans.y; background->transform.scalex = glTrans[2]; background->transform.scaley = glTrans[3]; text->position.x = glTrans.x; text->position.y = glTrans.y +FONT_LINE_HEIGHT / 4.0f; text->maxLineWidth = glTrans[2] * 2.0f; text->setText(text->getText()); } void Panel::setBackgroundColor(Color& color) { background->color = color; } void Panel::setBackgroundImage(unsigned int image) { background->texture = image; } void Panel::setFontColor(Color color) { text->color = color; } void Panel::setText(std::string text_) { text->setText(text_); } std::string Panel::getText() { return text->getText(); } void Panel::setFontSize(float fontSize) { text->fontSize = fontSize; text->setText(text->getText()); } void Panel::update() { GuiElement::update(); setTransform(transform); } void Panel::setVisible(bool visible) { GuiElement::setVisible(visible); background->renderMe = visible; text->renderMe = visible; } Panel::~Panel() { delete background; delete text; }
/* * Copyright (C) 2007,2008 Alex Shulgin * * This file is part of png++ the C++ wrapper for libpng. PNG++ is free * software; the exact copying conditions are as follows: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PNGPP_REQUIRE_COLOR_SPACE_HPP_INCLUDED #define PNGPP_REQUIRE_COLOR_SPACE_HPP_INCLUDED #pragma once #include "error.hpp" #include "rgb_pixel.hpp" #include "rgba_pixel.hpp" #include "gray_pixel.hpp" #include "ga_pixel.hpp" #include "index_pixel.hpp" #include "io_base.hpp" namespace png::detail { template<typename pixel> struct wrong_color_space { static inline constexpr const char* error_msg() noexcept; }; template<> inline constexpr const char* wrong_color_space<rgb_pixel>::error_msg() noexcept { return "8-bit RGB color space required"; } template<> inline constexpr const char* wrong_color_space<rgb_pixel_16>::error_msg() noexcept { return "16-bit RGB color space required"; } template<> inline constexpr const char* wrong_color_space<rgba_pixel>::error_msg() noexcept { return "8-bit RGBA color space required"; } template<> inline constexpr const char* wrong_color_space<rgba_pixel_16>::error_msg() noexcept { return "16-bit RGBA color space required"; } template<> inline constexpr const char* wrong_color_space<gray_pixel>::error_msg() noexcept { return "8-bit Grayscale color space required"; } template<> inline constexpr const char* wrong_color_space<gray_pixel_1>::error_msg() noexcept { return "1-bit Grayscale color space required"; } template<> inline constexpr const char* wrong_color_space<gray_pixel_2>::error_msg() noexcept { return "2-bit Grayscale color space required"; } template<> inline constexpr const char* wrong_color_space<gray_pixel_4>::error_msg() noexcept { return "4-bit Grayscale color space required"; } template<> inline constexpr const char* wrong_color_space<gray_pixel_16>::error_msg() noexcept { return "16-bit Grayscale color space required"; } template<> inline constexpr const char* wrong_color_space<ga_pixel>::error_msg() noexcept { return "8-bit Gray+Alpha color space required"; } template<> inline constexpr const char* wrong_color_space<ga_pixel_16>::error_msg() noexcept { return "16-bit Gray+Alpha color space required"; } template<> inline constexpr const char* wrong_color_space<index_pixel>::error_msg() noexcept { return "8-bit Colormap color space required"; } template<> inline constexpr const char* wrong_color_space<index_pixel_1>::error_msg() noexcept { return "1-bit Colormap color space required"; } template<> inline constexpr const char* wrong_color_space<index_pixel_2>::error_msg() noexcept { return "2-bit Colormap color space required"; } template<> inline constexpr const char* wrong_color_space<index_pixel_4>::error_msg() noexcept { return "4-bit Colormap color space required"; } } // end namespace png::detail namespace png { /** * \brief IO transformation class template. Enforces image color space. * * This IO transformation class template used to enforce source image color space. * * \see image, image::read */ template<typename pixel> struct require_color_space { using traits = pixel_traits<pixel>; inline constexpr void operator()(io_base& io) const { if (io.get_color_type() != traits::get_color_type() || io.get_bit_depth() != traits::get_bit_depth()) { throw error(detail::wrong_color_space< pixel >::error_msg()); } } }; } // end namespace png #endif // PNGPP_REQUIRE_COLOR_SPACE_HPP_INCLUDED
/** * @date 04/01/19 * @author SPREEHA DUTTA */ #include <bits/stdc++.h> using namespace std; void calc(string w,int m,int p[]) { int l=0,i=1;p[0]=0; while(i<m) { if(p[i]==p[l]) { l++; p[i]=l; i++; } else { if(l!=0) l=p[l-1]; else { p[i]=l; i++; } } } } int search(string s,string w) { int i=0,j=0;int k=-1; int m=w.length(); int n=s.length(); int arr[m]; calc(w,m,arr); while(i<n) { if(w[j]==s[i]) { j++; i++; } if(j==m) { k=i-j; break; } else if(i<n && w[j]!=s[i]) { if(j!=0) j=arr[j-1]; else i++; } } return k; } int main() { string s,w; getline(cin,s); getline(cin,w); int t=search (w,s); cout<<"\n"<<t<<endl; }
#include <algorithm> #include "Application.h" #include "EverydayTools/Exception/CallAndRethrow.h" #include "EverydayTools/Exception/ThrowIfFailed.h" #include "Keng/Core/ISystem.h" #include "Keng/Core/SystemEvent.h" #include "WinWrappers/WinWrappers.h" #include "WinWrappers/WinWrappers.h" #include "Keng/Core/ISystem.h" #include "GlobalEnvironment.h" namespace keng::core { using SystemCreatorSignature = void(__cdecl*)(void**); void Application::SetVSync(bool value) { m_vSync = value; } Application::Application() { } void Application::LoadModule(std::string_view name) { CallAndRethrowM + [&] { auto module = ModulePtr::MakeInstance(name); if (module->IsGlobalModule()) { GlobalEnvironment::PrivateInstance().RegisterModule(module); } else { m_modules.push_back(ModulePtr::MakeInstance(name)); } }; } void Application::LoadDependencies() { bool addedNewSystem; do { addedNewSystem = false; for (auto& module : m_modules) { auto& system = module->GetSystem(); auto onDependency = [&](const char* dependencyName) { if (FindSystem(dependencyName)) { return false; } LoadModule(dependencyName); return true; }; edt::Delegate<bool(const char*)> delegate; delegate.Bind(onDependency); addedNewSystem = system->ForEachDependency(delegate); if (addedNewSystem) { break; } } } while (addedNewSystem); } void Application::UpdateSystems() { return CallAndRethrowM + [&] { NotifyAll(SystemEvent::Update); }; } void Application::Initialize(const ApplicationStartupParameters& params) { for (auto& moduleToLoad : params.modulesToLoad) { LoadModule(moduleToLoad); } LoadDependencies(); std::vector<ISystemPtr> walkQueue; std::vector<ISystemPtr> systems; for (auto& module : m_modules) { systems.push_back(module->GetSystem()); } auto findSystem = [&systems](std::string_view name) -> ISystemPtr { for (auto& system : systems) { if (system->GetSystemName() == name) { return system; } } auto& gEnv = GlobalEnvironment::PrivateInstance(); auto system = gEnv.TryGetSystem(name); if (system) { return system; } return nullptr; }; std::stable_sort(m_modules.begin(), m_modules.end(), [&](const ModulePtr& ma, const ModulePtr& mb) { walkQueue.clear(); auto a = ma->GetSystem(); auto b = mb->GetSystem(); auto a_name = a->GetSystemName(); bool dependencyFound = false; walkQueue.push_back(b); while (!dependencyFound && !walkQueue.empty()) { auto current = walkQueue.back(); walkQueue.pop_back(); auto onDependency = [&](std::string_view name) { if (a_name == name) { return true; } auto system = findSystem(name); edt::ThrowIfFailed(system != nullptr, "Found dependency that was not registered as system"); walkQueue.push_back(system); return false; }; edt::Delegate<bool(const char*)> delegate; delegate.Bind(onDependency); dependencyFound = current->ForEachDependency(delegate); } return dependencyFound; }); NotifyAll(SystemEvent::Initialize); NotifyAll(SystemEvent::PostInitialize); } void Application::Update() { return CallAndRethrowM + [&] { if (m_vSync) { using namespace std::chrono; auto t0 = high_resolution_clock::now(); UpdateSystems(); auto t1 = high_resolution_clock::now(); auto average = m_fpsCounter.CalcAverageTick(t1 - t0); auto sleep = m_fpsCounter.GetDesiredFrameDuration() - average; if (sleep.count() > 0) { //std::this_thread::sleep_for(sleep); <-- so slow! Sleep(sleep); } } else { UpdateSystems(); } }; } void Application::Run() { CallAndRethrowM + [&] { while (!m_quiting) { Update(); }; FreeModules(); }; } ISystemPtr Application::FindSystem(const char* name) const { std::string_view view(name); for (auto& module : m_modules) { auto& system = module->GetSystem(); if (system->GetSystemName() == view) { return system; } } auto& gEnv = GlobalEnvironment::PrivateInstance(); auto system = gEnv.TryGetSystem(name); if (system) { return system; } return nullptr; } void Application::Shutdown() { m_quiting = true; } void Application::FreeModules() { NotifyAllReversed(SystemEvent::Shutdown); while (!m_modules.empty()) { //assert(m_modules.back()->GetSystem()->GetReferencesCount() == 1); m_modules.pop_back(); } GlobalEnvironment::PrivateInstance().DestroyApplication(this); } void Application::NotifyAll(const SystemEvent& event) { CallAndRethrowM + [&] { IApplicationPtr app(this); for (auto& module : m_modules) { if (auto& system = module->GetSystem()) { system->OnSystemEvent(app, event); } } }; } void Application::NotifyAllReversed(const SystemEvent& event) { CallAndRethrowM + [&] { IApplicationPtr app(this); for (auto iModule = m_modules.rbegin(); iModule != m_modules.rend(); ++iModule) { if (auto& system = (*iModule)->GetSystem()) { system->OnSystemEvent(app, event); } } }; } }
#include <iostream> #include <vector> #include<math.h> using namespace std; #define P 1000000 vector<int> primes; char sieve[P+1]; void getPrimes(); int cut(int n, bool right); int main() { getPrimes(); int sum = 0; for (int p = 0; p < primes.size(); p++) { if (primes[p] < 10) { sieve[primes[p]] = 5; continue; } int left = cut(primes[p], 0); int right = cut(primes[p], 1); if (sieve[left] == 2 || sieve[left] == 5) sieve[primes[p]] += 2; if (sieve[right] == 3 || sieve[right] == 5) sieve[primes[p]] += 3; if (sieve[primes[p]] == 5) sum += primes[p]; } cout << sum << "\n"; } int cut(int n, bool right) { if (right) return n / 10; int place = 1; for (int tempN = n; tempN > 9; tempN /= 10) place *= 10; while (n > place) n -= place; return n; } void getPrimes() { int sievebound = P; int crossbound = sqrt((double)P); for (int j = 4; j <= sievebound; j += 2) sieve[j] = 1; for (int i = 3; i <= crossbound; i++) if (!sieve[i]) for (int j = i*i; j <= sievebound; j += i) sieve[j] = 1; for (int i = 2; i <= sievebound; i++) if (!sieve[i]) primes.push_back(i); }
#include "StdAfx.h" #include "configTreeMng.h" configTreeMng::configTreeMng(void) { } configTreeMng::~configTreeMng(void) { } void configTreeMng::loadDataFromFile() { }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2002 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #ifdef SKIN_SUPPORT #include "modules/skin/IndpWidgetInfo.h" #include "modules/widgets/OpMultiEdit.h" #include "modules/widgets/OpScrollbar.h" #include "modules/widgets/OpButton.h" #include "modules/widgets/OpEdit.h" #include "modules/widgets/OpListBox.h" #include "modules/widgets/OpDropDown.h" #include "modules/widgets/OpResizeCorner.h" #include "modules/pi/OpSystemInfo.h" #include "modules/pi/OpFont.h" #include "modules/skin/OpSkinManager.h" #include "modules/display/vis_dev.h" #include "modules/prefs/prefsmanager/prefstypes.h" void IndpWidgetInfo::GetPreferedSize(OpWidget* widget, OpTypedObject::Type type, INT32* w, INT32* h, INT32 cols, INT32 rows) { #ifdef QUICK if (widget->IsForm()) { OpWidgetInfo::GetPreferedSize(widget, type, w, h, cols, rows); return; } switch(type) { case OpTypedObject::WIDGET_TYPE_RADIOBUTTON: case OpTypedObject::WIDGET_TYPE_CHECKBOX: { OpButton* button = (OpButton*) widget; const char* skin = type == OpTypedObject::WIDGET_TYPE_RADIOBUTTON ? "Checkbox Skin" : "Radio Button Skin"; INT32 image_width; INT32 image_height; widget->GetSkinManager()->GetSize(skin, &image_width, &image_height); image_width += 4; image_height += 2; INT32 text_width = button->string.GetWidth() + 4; INT32 text_height = button->string.GetHeight() + (widget->IsMiniSize() ? 0 : 4); *w = image_width + text_width; *h = image_height; if (text_height > *h) *h = text_height; *h += 1; break; } case OpTypedObject::WIDGET_TYPE_BUTTON: { OpButton* button = (OpButton*) widget; OpButton::ButtonStyle style = button->GetForegroundSkin()->HasContent() ? button->m_button_style : OpButton::STYLE_TEXT; OpSkinElement* element = widget->GetSkinManager()->GetSkinElement(button->GetBorderSkin()->GetImage(), button->GetBorderSkin()->GetType()); BOOL bold = button->packed2.is_bold || (element && element->HasBoldState()); INT32 old_weight = button->font_info.weight; if (bold) { button->font_info.weight = 7; button->string.NeedUpdate(); } INT32 text_width = button->string.GetWidth(); INT32 text_height = button->string.GetHeight(); OpInputAction* action = button->GetAction(); if (action) { BOOL changed = FALSE; OpString original_string; original_string.Set(button->string.Get()); if (original_string.Compare(button->m_text.CStr())) { changed = TRUE; button->string.Set(button->m_text.CStr(), button); INT32 new_text_width = button->string.GetWidth(); INT32 new_text_height = button->string.GetHeight(); if (new_text_width > text_width) { text_width = new_text_width; } if (new_text_height > text_height) { text_height = new_text_height; } } while (action) { if (original_string.Compare(action->GetActionText())) { changed = TRUE; button->string.Set(action->GetActionText(), button); INT32 new_text_width = button->string.GetWidth(); INT32 new_text_height = button->string.GetHeight(); if (new_text_width > text_width) { text_width = new_text_width; } if (new_text_height > text_height) { text_height = new_text_height; } } action = action->GetActionOperator() != OpInputAction::OPERATOR_PLUS ? action->GetNextInputAction() : NULL; } if (changed) { button->string.Set(original_string.CStr(), button); } } if (bold) { button->font_info.weight = old_weight; button->string.NeedUpdate(); } if (text_width == 0 && style != OpButton::STYLE_TEXT) style = OpButton::STYLE_IMAGE; if (button->m_button_type == OpButton::TYPE_PUSH || button->m_button_type == OpButton::TYPE_PUSH_DEFAULT) { text_height += text_height / 4; if (button->font_info.justify == JUSTIFY_CENTER) text_width += text_width * 2 / 5; } else { INT32 extra = -1; button->GetBorderSkin()->GetButtonTextPadding(&extra); if(extra == -1) { extra = button->GetSkinManager()->GetOptionValue("Button Text Padding", 2) * 2; } else { extra *= 2; } text_width += extra; text_height += extra; } INT32 image_width; INT32 image_height; if( button->GetForegroundSkin()->GetRestrictImageSize() ) { OpRect r = button->GetForegroundSkin()->CalculateScaledRect( OpRect(0,0,100,100), 0,0 ); image_width = r.width; image_height = r.height; } else { button->GetForegroundSkin()->GetSize(&image_width, &image_height); } INT32 left, top, right, bottom; button->GetForegroundSkin()->GetMargin(&left, &top, &right, &bottom); if (right < 0 && style != OpButton::STYLE_IMAGE_AND_TEXT_ON_RIGHT) { right = 0; } if (bottom < 0 && style != OpButton::STYLE_IMAGE_AND_TEXT_BELOW) { bottom = 0; } image_width += left + right; image_height += top + bottom; INT32 spacing = 0; button->GetSpacing(&spacing); switch (style) { case OpButton::STYLE_IMAGE_AND_TEXT_ON_LEFT: case OpButton::STYLE_IMAGE_AND_TEXT_CENTER: case OpButton::STYLE_IMAGE_AND_TEXT_ON_RIGHT: { *w = image_width + text_width + spacing; *h = max(image_height, text_height); break; } case OpButton::STYLE_IMAGE: { *w = image_width; *h = image_height; break; } case OpButton::STYLE_IMAGE_AND_TEXT_BELOW: { *w = max(text_width, image_width); *h = image_height + text_height + spacing; break; } case OpButton::STYLE_TEXT: { *w = text_width; *h = text_height; break; } } button->GetPadding(&left, &top, &right, &bottom); if (*w < button->GetMinWidth()) *w = button->GetMinWidth(); if (button->GetMaxWidth() && *w > button->GetMaxWidth()) *w = button->GetMaxWidth(); *w += left + right; *h += top + bottom; if (*w < *h && (style != OpButton::STYLE_IMAGE && (style != OpButton::STYLE_IMAGE && button->GetButtonType() != OpButton::TYPE_CUSTOM))) *w = *h; #ifdef ACTION_SHOW_MENU_SECTION_ENABLED if (button->GetButtonExtra() == OpButton::EXTRA_SUB_MENU) { INT32 sw = 0, sh = 0; if (OpSkinElement* element = widget->GetSkinManager()->GetSkinElement("Menu Right Arrow", SKINTYPE_DEFAULT, SKINSIZE_DEFAULT, TRUE)) element->GetSize(&sw, &sh, 0); *w += sw; } #endif if (button->m_dropdown_image.HasContent()) { INT32 image_width; INT32 image_height; button->m_dropdown_image.GetSize(&image_width, &image_height); INT32 dropdown_left, dropdown_top, dropdown_right, dropdown_bottom; button->m_dropdown_image.GetMargin(&dropdown_left, &dropdown_top, &dropdown_right, &dropdown_bottom); INT32 auto_dropdown_padding = (left + right) / 2; *w += image_width + auto_dropdown_padding + dropdown_left + dropdown_right; } } break; case OpTypedObject::WIDGET_TYPE_DROPDOWN: { OpDropDown* dr = (OpDropDown*) widget; { if (dr->edit || dr->CountItems() == 0) { *w = 150; } else { *w = dr->ih.widest_item + GetDropdownButtonWidth(widget); INT32 left = 0; INT32 top = 0; INT32 right = 0; INT32 bottom = 0; dr->GetPadding(&left, &top, &right, &bottom); *w += left + right; } #if 1 // Part of fix for bug #199381 (UI label text is cut off due to widget padding changes) if (dr->edit) { OP_ASSERT(dr->edit->GetVisualDevice()); // might not get height if vis_dev is not set int text_height = dr->edit->string.GetHeight(); *h = text_height + dr->edit->GetPaddingTop() + dr->edit->GetPaddingBottom() + dr->GetPaddingTop() + dr->GetPaddingBottom(); // The '4' is because of OpWidgetInfo::AddBorder() if (!dr->edit->HasCssBorder()) *h += 4; } else #endif { *h = widget->font_info.size + (widget->IsMiniSize() ? 8 : 12); } if (widget->GetType() == OpTypedObject::WIDGET_TYPE_ZOOM_DROPDOWN) { // Can not use a hardcoded width here. Must take padding, icon and font size // into the equation. We assume "100%" to be the default string we want to show. // save current zoom string OpString org_string; org_string.Set(dr->edit->string.Get()); // set default string, to measure default size dr->edit->string.Set(UNI_L("100%"), dr->edit); // get the require size for the default text INT32 edit_width = dr->edit->string.GetWidth(); // restore original string dr->edit->string.Set(org_string.CStr(), dr->edit); INT32 icon_width = 0; // Compute the width as is done in OpDropDown::OnLayout() if (dr->GetForegroundSkin()->HasContent()) { // We have to fake a little bit here. CalculateScaledRect() will return // an empty rectangle when inner_rect is too small. That will happen when we // use dr->GetBounds() when IndpWidgetInfo::GetPreferedSize() gets called // before layout has been set. OpRect inner_rect(0,0,100,100); OpRect rect = dr->GetForegroundSkin()->CalculateScaledRect(inner_rect, FALSE, TRUE); // 4 is added to the image width in OpDropDown::OnLayout() icon_width = rect.width + 4; } *w = icon_width + edit_width + GetDropdownButtonWidth(widget) + dr->edit->GetPaddingLeft() + dr->edit->GetPaddingRight() + dr->GetPaddingLeft() + dr->GetPaddingRight(); // the '4' is because of OpWidgetInfo::AddBorder() if (!dr->HasCssBorder()) *w += 4; } } } break; case OpTypedObject::WIDGET_TYPE_EDIT: { OP_ASSERT(widget->GetVisualDevice()); INT32 font_height = ((OpEdit*)widget)->string.GetHeight(); *w = 150; *h = font_height + (widget->IsMiniSize() ? 8 : 12); break; } break; /* case OpTypedObject::WIDGET_TYPE_RADIOBUTTON: { OpSkinElement* skin_elm = g_skin_manager->GetSkinElement(UNI_L("Radio Button Skin")); if (skin_elm) { *w = 0; *h = 0; skin_elm->GetSize(w, h, 0); if (*w && *h) break; } OpWidgetInfo::GetPreferedSize(widget, type, w, h, cols, rows); } break; case OpTypedObject::WIDGET_TYPE_CHECKBOX: { OpSkinElement* skin_elm = g_skin_manager->GetSkinElement(UNI_L("Radio Button Skin")); if (skin_elm) { *w = 0; *h = 0; skin_elm->GetSize(w, h, 0); if (*w && *h) break; } OpWidgetInfo::GetPreferedSize(widget, type, w, h, cols, rows); } break; */ default: OpWidgetInfo::GetPreferedSize(widget, type, w, h, cols, rows); break; }; #else OpWidgetInfo::GetPreferedSize(widget, type, w, h, cols, rows); #endif } void IndpWidgetInfo::GetMinimumSize(OpWidget* widget, OpTypedObject::Type type, INT32* minw, INT32* minh) { switch(type) { case OpTypedObject::WIDGET_TYPE_BUTTON: { OpSkinElement* skin_elm = g_skin_manager->GetSkinElement("Push Button Skin"); if (skin_elm) skin_elm->GetMinSize(minw, minh, 0); } break; default: OpWidgetInfo::GetMinimumSize(widget, type, minw, minh); break; } } INT32 IndpWidgetInfo::GetDropdownButtonWidth(OpWidget* widget) { if (widget->IsOfType(OpTypedObject::WIDGET_TYPE_DROPDOWN) && !((OpDropDown*)widget)->m_dropdown_packed.show_button) return 0; OpSkinElement* skin_elm = g_skin_manager->GetSkinElement("Dropdown Button Skin"); if (skin_elm) { INT32 w = 0, h = 0; skin_elm->GetSize(&w, &h, 0); return w; } return OpWidgetInfo::GetDropdownButtonWidth(widget); } INT32 IndpWidgetInfo::GetDropdownLeftButtonWidth(OpWidget* widget) { if (widget->IsOfType(OpTypedObject::WIDGET_TYPE_DROPDOWN) && !((OpDropDown*)widget)->m_dropdown_packed.show_button) return 0; OpSkinElement* skin_elm = g_skin_manager->GetSkinElement("Dropdown Left Button Skin"); if (skin_elm) { INT32 w = 0, h = 0; skin_elm->GetSize(&w, &h, 0); return w; } return OpWidgetInfo::GetDropdownLeftButtonWidth(widget); } void IndpWidgetInfo::GetBorders(OpWidget* widget, INT32& left, INT32& top, INT32& right, INT32& bottom) { if (widget->HasCssBorder() || widget->IsForm() || !widget->GetBorderSkin()->GetImage()) { OpWidgetInfo::GetBorders(widget, left, top, right, bottom); return; } widget->GetBorderSkin()->GetPadding(&left, &top, &right, &bottom); } #endif // SKIN_SUPPORT
#ifndef CRASHEVENT_H #define CRASHEVENT_H #include "Event.h" class Vector; class Object; class PlayerNeo; class Field::CrashEvent : public Field::Event { public: class CrashResult; public: explicit CrashEvent(PlayerNeo*); void exec(void); private: void execFirstCrash(void); void execSecondCrash(void); bool canCrashObjSphere(Object*, Object*); bool canCrashObjSphereAndVrtx(Object*, Vector); int reflectIfCrash(Object*, Object*); bool resolveCaught(Object*, Object*); Vector calcCaughtDist(Object*, Object*); Vector getLineToPolygonPenetration1(Object*, Object*, const Vector&, short, float); Vector getLineToPolygonPenetration2(Object*, Object*, short, short, short); void judgePlgnAndVrtx(Object*, Object*, CrashResult*); void judgeLineAndLine(Object*, Object*, CrashResult*); void reflectPlgnAndVrtx(CrashResult*); void reflectLineAndLine(CrashResult*); void calcRepulsion(Object*, Object*, const Vector&, const Vector&, CrashResult*); PlayerNeo* playerNeo; }; #endif
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; const int INF = 1 << 28; int a[1010][1010]; int use[1010],dis[1010]; int main() { int n,q; while (scanf("%d",&n) != EOF) { for (int i = 1;i <= n; i++) for (int j = 1;j <= n; j++) scanf("%d",&a[i][j]); scanf("%d",&q); for (int i = 1;i <= q; i++) { int x,y; scanf("%d%d",&x,&y); a[x][y] = a[y][x] = 0; } for (int i = 1;i <= n; i++) dis[i] = a[1][i]; memset(use,0,sizeof(use)); use[1] = 1; int ans = 0; for (int i = 1;i < n; i++) { int rec = INF,v = 1; for (int i = 2;i <= n; i++) if (!use[i] && dis[i] < rec) { v = i; rec = dis[i]; } ans += rec; use[v] = 1; for (int i = 2;i <= n; i++) if (!use[i] && a[v][i] < dis[i]) dis[i] = a[v][i]; } printf("%d\n",ans); } return 0; }
// Copyright (C) 2014, 2015, 2016 Alexander Golant // // This file is part of csys project. This project is free // software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> #include <cstdlib> #include <sstream> #include <cmath> #include "commac.h" #include "serial_device.h" #include "logger.h" #include "io.h" using namespace std; using namespace csys; using namespace dev; serialDevice::serialDevice(const char* lbl, const char* port_alias, char addr): device(lbl, time::Sec4), port(*device::serialMap.find(port_alias)->second), msg(*(new message(lbl))), dev_addr(addr) { msg.eot = 0x0D; io_cs.error = err::NOERR; io_cs.command = cmd::NOCMD; io_cs.error = err::NOERR; io_cs.link = true; send = false; receive = false; state = device_state::DISABLED; /* test serialMap.find() return value */ if(device::serialMap.end() == device::serialMap.find(port_alias)) { cout << __func__ << delim << label << ": requested port [" << port_alias << "] not found" << endl; exit(1); } /* match device timeout with serial port */ if(timeout < port.get_timeout() || timeout > port.get_tmlink()) { cout << __func__ << delim << label << ": device timeout is out of range" << endl; exit(1); } io_ps = io_cs; pair<deviceMapIterator, bool> ret; ret = deviceMap.insert (pair<string, device*>(label, this)); if (false == ret.second) { dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << label << delim << __func__ << delim << " already exists" << endl; cout << __func__ << delim << label << " already exists" << endl; exit(1); } request = new(std::nothrow) char[bufferLen]; reply = new(std::nothrow) char[bufferLen]; if(!request || !reply) { dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << delim << __func__ << ": bad alloc" << endl; cout << __func__ << ": bad alloc" << endl; exit(1); } } serialDevice::~serialDevice() { delete[] request; delete[] reply; deviceMapIterator it = deviceMap.find(label); if(it == deviceMap.end()) { dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << label << delim << __func__ << ": device not found" << endl; return; } else { deviceMap.erase(it); } dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << label << delim << __func__ << ": device removed" << endl; } void serialDevice::process(io &sys_io) { emit = false; /* out of use */ if(&sys_io){} if(!init) { init = true; io_cs.command = cmd::INIT; } try_push(); error_handler(); /* frame switcher */ if(time_global - time_redge > timeout) { try_pop(); send = true; receive = true; time_redge = time_global; switch(io_cs.command) { case cmd::NOCMD: break; case cmd::POLL: break; case cmd::INIT: port.init(); io_cs.error = err::NOERR; state = device_state::ENABLED; break; default: break; } /* patch message into port buffer_out */ request_handler(); } sender(); receiver(); /* notify CLIENT that something has changed */ if(rts || io_cs != io_ps || state != state_ps) { rts = false; emit = true; } io_ps = io_cs; state_ps = state; } /***************** internal methods **********************/ void serialDevice::try_push() { if(io_cs.command != io_ps.command) { /* push new request */ reqQue.push(io_cs); dLog.getstream(logLevel::DDEBUG, logType::DEVICE) << label << delim << __func__ << delim << io_cs.command << delim << io_ps.command << delim << "reqQue size: " << reqQue.size() << endl; io_cs = io_ps; } } void serialDevice::try_pop() { /* release request from the queue */ if(!reqQue.empty()) { io_cs = reqQue.front(); reqQue.pop(); dLog.getstream(logLevel::DDEBUG, logType::DEVICE) << label << delim << __func__ << delim << io_cs.command << endl; } } /* TODO unused port separate logic */ void serialDevice::error_handler() { /* copy port state into device */ io_cs.link = port.get_link(); if(norep && port.get_link()) { norep = false; io_cs.error = err::TMERR; state = device_state::CHANGED; dLog.getstream(logLevel::DDEBUG, logType::DEVICE) << label << delim << __func__ << ": no reply " << endl; } if(!port.get_link()) { io_cs.link = false; io_cs.error = err::NOLNK; state = device_state::ALARM; } /* port error_link registration */ if(!port.get_link() && io_cs.link != io_ps.link) { dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << label << delim << __func__ << ": no link" << endl; } /* error_link recovery */ if(port.get_link() && io_cs.link != io_ps.link) { io_cs.link = true; io_cs.error = err::NOERR; state = device_state::ENABLED; dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << label << delim << __func__ << ": link recovery" << endl; } } void serialDevice::sender() { if(send) { send = false; msg.clear(); msg.request = request; msg.command = io_cs.command; port << msg; dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << label << delim << __func__ << delim << msg.request << endl; } } void serialDevice::receiver() { if(receive) { if(port >> msg) { if(0 == msg.response.size()) { norep = true; io_cs.command = cmd::POLL; dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << label << delim << __func__ << ": zero sized message" << endl; return; } receive = false; norep = false; memset(reply, 0, bufferLen); strcpy(reply, msg.response.c_str()); dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << label << delim << __func__ << delim << msg.response << endl; dispatch(); } } } void serialDevice::request_handler() { memset(request, 0x00, bufferLen); switch(io_cs.command) { case cmd::NOCMD: return; case cmd::POLL: strcpy(request, "loopback"); break; case cmd::INIT: strcpy(request, "init"); break; default: return; } patch(); } void serialDevice::patch() { int len = strlen(request); request[len] = msg.eot; } float counter = 0; void serialDevice::dispatch() { switch(io_cs.command) { case cmd::NOCMD: return; case cmd::POLL: io_cs.data = counter++; break; case cmd::INIT: io_cs.data = 0; io_cs.command = cmd::POLL; break; default: return; } dLog.getstream(logLevel::DDEBUG, logType::DEVICE) << label << delim << __func__ << delim << io_cs.data << endl; } void serialDevice::serialize() { os << label << delim << state << delim << io_cs.error << delim << io_cs.command << delim << io_cs.data << delim << io_cs.link << delim; dLog.getstream(logLevel::DDEBUG, logType::DEVICE) << label << delim << __func__ << delim << state << delim << io_cs.error << delim << io_cs.command << delim << io_cs.data << delim << io_cs.link << endl; } void serialDevice::unserialize() { is >> io_cs.command; dLog.getstream(logLevel::DDEBUG, logType::DEVICE) << label << delim << __func__ << delim << io_cs.command << endl; }
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> using namespace std; int main() { //freopen("test1.in", "r", stdin); //freopen("test1.out", "w", stdout); int T; while (~scanf("%d", &T)) { int dp[T + 5]; int data[T + 5]; data[0] = 0; int num = 0; for (int i = 1; i <= T; i++) { cin >> data[i]; dp[i] = 1; } for (int i = 2; i <= T; i++) { for (int j = i - 1; j >= 1; j--) { if (data[i] > data[j]) { dp[i] = max(dp[i], dp[j] + 1); } num = max(num, dp[i]); } } cout << num << endl; } return 0; }
#include<bits/stdc++.h> using namespace std; #define rep(i,b) for(i=0;i<b;i++) #define rep1(i,b) for(i=1;i<=b;i++) #define plln(n) printf("%lld\n",n) #define s3ll(n1,n2,n3) scanf("%lld%lld%lld",&n1,&n2,&n3) #define s2ll(n1,n2) scanf("%lld%lld",&n1,&n2) #define sll(n) scanf("%lld",&n) #define countSetBits(n) __builtin_popcountll(n) typedef long long LL; #define mod 1000000007 #define mx 999999 int main() { LL t,n,i; sll(t); while(t--) { sll(n); LL a[n+5]; LL flag=1; rep1(i,n) { sll(a[i]); } rep1(i,n) { LL cnt=(a[i]-i); if((cnt<=-2)){ flag=0;break; } } if(flag) printf("YES\n"); else printf("NO\n"); } return 0; }
#include <iostream> #include <vector> using namespace std; int find2020(vector<int>& numbers){ for(int i = 0; i < numbers.size(); ++i){ for(int j = i + 1; j < numbers.size(); ++j){ for(int k = j + 1; k < numbers.size(); ++k){ if(numbers[i] + numbers[j] + numbers[k] == 2020){ return numbers[i] * numbers[j] * numbers[k]; } } } } return 0; } int main(){ vector<int> numbers; int number, result; while(cin >> number){ numbers.push_back(number); } cout << find2020(numbers) << endl; return 0; }
// Copyright (c) 2018 Mozart Alexander Louis. All rights reserved. // Includes #include "intro_scene.hxx" IntroScene::IntroScene(const ValueMap& params, BackgroundLayer*) : BaseScene(params, nullptr) {} IntroScene::~IntroScene() = default; ValueMap IntroScene::generateParams() { // Add default params ValueMap params; params.emplace(__SCRIPT__, __INTRO_SCENE__); params.emplace(__NAME__, typeid(IntroScene).name()); // Return default values return params; } void IntroScene::beforeInitialized() { } bool IntroScene::onInitialized() { AudioUtils::getInstance()->playAudioWithParam("event:/Music/Moon Ray", "fullLoop", 1.0f); // Schedule our load function which will orchestrate this intro sequence schedule(schedule_selector(IntroScene::monitor), 0.5f); return true; } void IntroScene::monitor(float dt) { // Getting a reference to all sprite on the layer const auto& probymozart = sprite_manager_->findSprite(__INTRO_ASSET_PROD_BY_MOZART__); const auto& cocos = sprite_manager_->findSprite(__INTRO_ASSET_COCOS__); const auto& firebase = sprite_manager_->findSprite(__INTRO_ASSET_FIREBASE__); const auto& fmod = sprite_manager_->findSprite(__INTRO_ASSET_FMOD__); // Make sure actions are not running on any of the sprites if (ActionUtils::isRunningAction({probymozart, cocos, firebase, fmod})) return; // Remove this function from scheduler. unschedule(schedule_selector(IntroScene::monitor)); // Check to see if the user has completed the tutorial yet. It not, transition to the tutorial scene. if (DataUtils::getOtherData(__KEY_TUTORIAL_COMPLETE__, 0)) SceneUtils::replaceScene(MODES, BackgroundLayer::create()); else SceneUtils::replaceScene(CONTROLS, BackgroundLayer::create()); }
// include the basic windows header file #include <windows.h> #include <windowsx.h> #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "dxgi.lib") #pragma comment(lib, "d3dcompiler.lib") #include <d3d11.h> #include <directxmath.h> #include <d3dcompiler.h> #include <sstream> #include <fstream> #include <tuple> #include <chrono> using namespace DirectX; using namespace std; struct MatrixBufferType { XMMATRIX world; XMMATRIX view; XMMATRIX projection; }; struct MaterialBufferType { XMFLOAT4 materialAmbient; XMFLOAT4 materialDiffuse; XMFLOAT4 materialSpecular; }; struct LightingBufferType { XMFLOAT4 viewPosition; XMFLOAT4 lightDirection; XMFLOAT4 lightAmbient; XMFLOAT4 lightDiffuse; XMFLOAT4 lightSpecular; }; struct VertexColorType { XMFLOAT3 position; XMFLOAT4 color; }; struct VertexTextureType { XMFLOAT3 position; XMFLOAT2 texture; }; struct VertexLitTextureType { XMFLOAT4 position; XMFLOAT4 normal; XMFLOAT2 texture; }; struct TargaHeader { unsigned char data1[12]; unsigned short width; unsigned short height; unsigned char bpp; unsigned char data2; }; LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); // C++11 timestamp as a float chrono::high_resolution_clock::time_point timeStart = chrono::high_resolution_clock::now(); float time() { auto sinceStart = chrono::high_resolution_clock::now() - timeStart; return ((float)sinceStart.count()) * chrono::high_resolution_clock::period::num / chrono::high_resolution_clock::period::den; } // the entry point for any Windows program int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // the handle for the window, filled by a function HWND hWnd; // this struct holds information for the window class WNDCLASSEX wc; // clear out the window class for use ZeroMemory(&wc, sizeof(WNDCLASSEX)); // fill in the struct with the needed information wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.lpszClassName = L"WindowClass1"; // register the window class RegisterClassEx(&wc); bool vsync = false; bool windowed = true; int screenWidth = windowed ? 1000 : GetSystemMetrics(SM_CXSCREEN); int screenHeight = windowed ? 800 : GetSystemMetrics(SM_CYSCREEN); RECT wr = {0, 0, screenWidth, screenHeight}; // set the size, but not the position AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); // adjust the size // create the window and use the result as the handle hWnd = CreateWindowEx(NULL, L"WindowClass1", // name of the window class L"Our First Windowed Program", // title of the window WS_OVERLAPPEDWINDOW, // window style 300, // x-position of the window 300, // y-position of the window wr.right - wr.left, // width of the window wr.bottom - wr.top, // height of the window NULL, // we have no parent window, NULL NULL, // we aren't using menus, NULL hInstance, // application handle NULL); // used with multiple windows, NULL // display the window on the screen ShowWindow(hWnd, nCmdShow); IDXGIFactory* factory; CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); IDXGIAdapter* adapter; factory->EnumAdapters(0, &adapter); IDXGIOutput* adapterOutput; adapter->EnumOutputs(0, &adapterOutput); // DirectX init // initialize the swap chain DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.BufferCount = 1; // single back buffer swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hWnd; // turn multisampling off swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.Windowed = windowed; swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // discard the back buffer contents after presenting swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // don't set the advanced flags swapChainDesc.Flags = 0; // set the refresh rate if (vsync) { // get the refresh rate from the graphics card unsigned numModes; adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); DXGI_MODE_DESC* displayModeList = new DXGI_MODE_DESC[numModes]; adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); for (unsigned i = 0; i < numModes; i++) { if (displayModeList[i].Width == (unsigned)screenWidth && displayModeList[i].Height == (unsigned)screenHeight) { swapChainDesc.BufferDesc.RefreshRate.Numerator = displayModeList[i].RefreshRate.Numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = displayModeList[i].RefreshRate.Denominator; break; } } delete[] displayModeList; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } // find the video memory in megabytes DXGI_ADAPTER_DESC adapterDesc; adapter->GetDesc(&adapterDesc); size_t videoMemoryMb = adapterDesc.DedicatedVideoMemory / 1024 / 1024; // get the video card name char videoCardName[128]; size_t stringLength; wcstombs_s(&stringLength, videoCardName, 128, adapterDesc.Description, 128); adapterOutput->Release(); adapter->Release(); factory->Release(); // create the swap chain, device, context, and rendertargetview IDXGISwapChain* swapChain = nullptr; ID3D11Device* device = nullptr; ID3D11DeviceContext* context = nullptr; D3D_FEATURE_LEVEL featureLevels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1}; unsigned flags = 0; #ifdef _DEBUG flags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, flags, featureLevels, 2, D3D11_SDK_VERSION, &swapChainDesc, &swapChain, &device, NULL, &context); ID3D11Texture2D* backBuffer = 0; swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBuffer); ID3D11RenderTargetView* renderTargetView; device->CreateRenderTargetView(backBuffer, NULL, &renderTargetView); backBuffer->Release(); // create the depth stencil buffer ID3D11Texture2D* depthStencilBuffer = nullptr; D3D11_TEXTURE2D_DESC depthBufferDesc; ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); depthBufferDesc.Width = screenWidth; depthBufferDesc.Height = screenHeight; depthBufferDesc.MipLevels = 1; depthBufferDesc.ArraySize = 1; depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthBufferDesc.SampleDesc.Count = 1; depthBufferDesc.SampleDesc.Quality = 0; depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; depthBufferDesc.MiscFlags = 0; device->CreateTexture2D(&depthBufferDesc, NULL, &depthStencilBuffer); // create the depth stencil state ID3D11DepthStencilState* depthStencilState = nullptr; D3D11_DEPTH_STENCIL_DESC depthStencilDesc; ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; device->CreateDepthStencilState(&depthStencilDesc, &depthStencilState); context->OMSetDepthStencilState(depthStencilState, 1); // make it take effect // create the depth stencil view ID3D11DepthStencilView* depthStencilView = nullptr; D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; device->CreateDepthStencilView(depthStencilBuffer, &depthStencilViewDesc, &depthStencilView); // bind the render target view and depth stencil buffer to the output render pipeline context->OMSetRenderTargets(1, &renderTargetView, depthStencilView); // custom raster options, like draw as wireframe ID3D11RasterizerState* rasterState = nullptr; D3D11_RASTERIZER_DESC rasterDesc; rasterDesc.AntialiasedLineEnable = false; rasterDesc.CullMode = D3D11_CULL_BACK; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = 0.0f; rasterDesc.DepthClipEnable = true; rasterDesc.FillMode = D3D11_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.MultisampleEnable = false; rasterDesc.ScissorEnable = false; rasterDesc.SlopeScaledDepthBias = 0.0f; device->CreateRasterizerState(&rasterDesc, &rasterState); context->RSSetState(rasterState); // set up the viewport D3D11_VIEWPORT viewport; viewport.Width = (float)screenWidth; viewport.Height = (float)screenHeight; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; context->RSSetViewports(1, &viewport); // create the projection matrix float fieldOfView = 3.141592654f / 4.0f; float screenAspect = (float)screenWidth / (float)screenHeight; float screenDepth = 1000.0f; float screenNear = 0.1f; XMMATRIX projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth); // create the world matrix XMMATRIX worldMatrix = XMMatrixIdentity(); // create an orthographic projection matrix for 2D UI rendering. XMMATRIX orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth); // shaders HRESULT result; ID3D10Blob* errorMessage = 0; ID3D10Blob* colorVertexShaderBuffer = 0, *colorPixelShaderBuffer = 0; ID3D10Blob* textureVertexShaderBuffer = 0, *texturePixelShaderBuffer = 0; ID3D10Blob* litTextureVertexShaderBuffer = 0, *litTexturePixelShaderBuffer = 0; // compile the vertex and pixel shaders UINT shaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) shaderFlags |= D3DCOMPILE_DEBUG; #endif typedef tuple <LPCWSTR, char*, char*, ID3D10Blob**> ShaderInfo; for (auto shaderInfo : { ShaderInfo(L"color.vs", "ColorVertexShader", "vs_4_0", &colorVertexShaderBuffer), ShaderInfo(L"color.ps", "ColorPixelShader", "ps_4_0", &colorPixelShaderBuffer), ShaderInfo(L"texture.vs", "TextureVertexShader", "vs_4_0", &textureVertexShaderBuffer), ShaderInfo(L"texture.ps", "TexturePixelShader", "ps_4_0", &texturePixelShaderBuffer), ShaderInfo(L"litTextureVertexShader.fx", "LitTextureVertexShader", "vs_4_0", &litTextureVertexShaderBuffer), ShaderInfo(L"litTexturePixelShader.fx", "LitTexturePixelShader", "ps_4_0", &litTexturePixelShaderBuffer) }) { result = D3DCompileFromFile(get<0>(shaderInfo), NULL, NULL, get<1>(shaderInfo), get<2>(shaderInfo), shaderFlags, 0, get<3>(shaderInfo), &errorMessage); if (FAILED(result)) { if (errorMessage) { // show a message box with the compile errors char* compileErrors = (char*)(errorMessage->GetBufferPointer()); wstringstream msg; for (size_t i = 0; i < errorMessage->GetBufferSize(); i++) msg << compileErrors[i]; errorMessage->Release(); MessageBox(hWnd, msg.str().c_str(), get<0>(shaderInfo), MB_OK); } else { MessageBox(hWnd, get<0>(shaderInfo), L"Missing Shader File", MB_OK); } break; } } // create the color shader ID3D11VertexShader* colorVertexShader = 0; ID3D11PixelShader* colorPixelShader = 0; assert(!FAILED(result = device->CreateVertexShader(colorVertexShaderBuffer->GetBufferPointer(), colorVertexShaderBuffer->GetBufferSize(), NULL, &colorVertexShader))); assert(!FAILED(result = device->CreatePixelShader(colorPixelShaderBuffer->GetBufferPointer(), colorPixelShaderBuffer->GetBufferSize(), NULL, &colorPixelShader))); // this setup needs to match the VertexColorType stucture in the color shader D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "COLOR"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; ID3D11InputLayout* colorShaderInputLayout; assert(!FAILED(result = device->CreateInputLayout(polygonLayout, sizeof(polygonLayout) / sizeof(polygonLayout[0]), colorVertexShaderBuffer->GetBufferPointer(), colorVertexShaderBuffer->GetBufferSize(), &colorShaderInputLayout))); colorVertexShaderBuffer->Release(); colorPixelShaderBuffer->Release(); // create the texture shader ID3D11VertexShader* textureVertexShader = 0; ID3D11PixelShader* texturePixelShader = 0; assert(!FAILED(result = device->CreateVertexShader(textureVertexShaderBuffer->GetBufferPointer(), textureVertexShaderBuffer->GetBufferSize(), NULL, &textureVertexShader))); assert(!FAILED(result = device->CreatePixelShader(texturePixelShaderBuffer->GetBufferPointer(), texturePixelShaderBuffer->GetBufferSize(), NULL, &texturePixelShader))); // this setup needs to match the VertexTextureType stucture in the texture shader polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "TEXCOORD"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; ID3D11InputLayout* textureShaderInputLayout; assert(!FAILED(result = device->CreateInputLayout(polygonLayout, sizeof(polygonLayout) / sizeof(polygonLayout[0]), textureVertexShaderBuffer->GetBufferPointer(), textureVertexShaderBuffer->GetBufferSize(), &textureShaderInputLayout))); textureVertexShaderBuffer->Release(); texturePixelShaderBuffer->Release(); // create the lit texture ID3D11VertexShader* litTextureVertexShader = 0; ID3D11PixelShader* litTexturePixelShader = 0; assert(!FAILED(result = device->CreateVertexShader(litTextureVertexShaderBuffer->GetBufferPointer(), litTextureVertexShaderBuffer->GetBufferSize(), NULL, &litTextureVertexShader))); assert(!FAILED(result = device->CreatePixelShader(litTexturePixelShaderBuffer->GetBufferPointer(), litTexturePixelShaderBuffer->GetBufferSize(), NULL, &litTexturePixelShader))); // this setup needs to match the VertexLitTextureType stucture in the litTexture shader D3D11_INPUT_ELEMENT_DESC textureLitLayout[3]; textureLitLayout[0].SemanticName = "POSITION"; textureLitLayout[0].SemanticIndex = 0; textureLitLayout[0].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; textureLitLayout[0].InputSlot = 0; textureLitLayout[0].AlignedByteOffset = 0; textureLitLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; textureLitLayout[0].InstanceDataStepRate = 0; textureLitLayout[1].SemanticName = "NORMAL"; textureLitLayout[1].SemanticIndex = 0; textureLitLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; textureLitLayout[1].InputSlot = 0; textureLitLayout[1].AlignedByteOffset = 16; //D3D11_APPEND_ALIGNED_ELEMENT; textureLitLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; textureLitLayout[1].InstanceDataStepRate = 0; textureLitLayout[2].SemanticName = "TEXCOORD"; textureLitLayout[2].SemanticIndex = 0; textureLitLayout[2].Format = DXGI_FORMAT_R32G32_FLOAT; textureLitLayout[2].InputSlot = 0; textureLitLayout[2].AlignedByteOffset = 32; //D3D11_APPEND_ALIGNED_ELEMENT; textureLitLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; textureLitLayout[2].InstanceDataStepRate = 0; ID3D11InputLayout* litTextureShaderInputLayout; assert(!FAILED(result = device->CreateInputLayout(textureLitLayout, sizeof(textureLitLayout) / sizeof(textureLitLayout[0]), litTextureVertexShaderBuffer->GetBufferPointer(), litTextureVertexShaderBuffer->GetBufferSize(), &litTextureShaderInputLayout))); litTextureVertexShaderBuffer->Release(); litTexturePixelShaderBuffer->Release(); // create a texture sampler state D3D11_SAMPLER_DESC samplerDesc; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; ID3D11SamplerState* samplerState; result = device->CreateSamplerState(&samplerDesc, &samplerState); // dynamic matrix constant buffer that's in the vertex shaders ID3D11Buffer* matrixBuffer = 0; D3D11_BUFFER_DESC matrixBufferDesc; matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; assert(!FAILED(result = device->CreateBuffer(&matrixBufferDesc, NULL, &matrixBuffer))); // dynamic material constant buffer ID3D11Buffer* materialBuffer = 0; D3D11_BUFFER_DESC materialBufferDesc; materialBufferDesc.Usage = D3D11_USAGE_DYNAMIC; materialBufferDesc.ByteWidth = sizeof(MaterialBufferType); materialBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; materialBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; materialBufferDesc.MiscFlags = 0; materialBufferDesc.StructureByteStride = 0; assert(!FAILED(result = device->CreateBuffer(&materialBufferDesc, NULL, &materialBuffer))); // dynamic lighting constant buffer ID3D11Buffer* lightingBuffer = 0; D3D11_BUFFER_DESC lightingBufferDesc; lightingBufferDesc.Usage = D3D11_USAGE_DYNAMIC; lightingBufferDesc.ByteWidth = sizeof(LightingBufferType); lightingBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; lightingBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; lightingBufferDesc.MiscFlags = 0; lightingBufferDesc.StructureByteStride = 0; assert(!FAILED(result = device->CreateBuffer(&lightingBufferDesc, NULL, &lightingBuffer))); // put all the buffers in an ordered array ID3D11Buffer* constantBuffers[] = {matrixBuffer, materialBuffer, lightingBuffer}; //// make a triangle //unsigned vertexCount = 3; //unsigned indexCount = 3; //VertexTextureType* vertices = new VertexTextureType[vertexCount]; //unsigned long* indices = new unsigned long[indexCount]; //vertices[0].position = XMFLOAT3(-1.0f, -1.0f, 0.0f); // bottom left //vertices[0].texture = XMFLOAT2(0.0f, 1.0f); ////vertices[0].color = XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f); //vertices[1].position = XMFLOAT3(0.0f, 1.0f, 0.0f); // top middle //vertices[1].texture = XMFLOAT2(0.5f, 0.0f); ////vertices[1].color = XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f); //vertices[2].position = XMFLOAT3(1.0f, -1.0f, 0.0f); // bottom right //vertices[2].texture = XMFLOAT2(1.0f, 1.0f); ////vertices[2].color = XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f); //indices[0] = 0; // bottom left //indices[1] = 1; // top middle //indices[2] = 2; // bottom right // make a sphere // note: go to planetpixelemporium for textures const float PI = 3.14159265358979f; const float TWOPI = 2.f * PI; unsigned latitudes = 24; unsigned longitudes = 24; unsigned vertexCount = (latitudes + 1) * (longitudes + 1); unsigned indexCount = (latitudes - 1) * (longitudes + 1) * 2 * 3; VertexLitTextureType* vertices = new VertexLitTextureType[vertexCount]; unsigned long* indices = new unsigned long[indexCount]; const float latStep = PI / latitudes; const float lonStep = TWOPI / longitudes; unsigned v = 0; for (unsigned lat = 0; lat <= latitudes; ++lat) { for (unsigned lon = 0; lon <= longitudes; ++lon) { const float alat = lat * latStep; const float alon = lon * lonStep; vertices[v].position = XMFLOAT4(sin(alat) * cos(alon), cos(alat), sin(alat) * sin(alon), 1.0f); vertices[v].normal = vertices[v].position; vertices[v].normal.w = 0.0f; vertices[v++].texture = XMFLOAT2((float)lon / longitudes, -cos(alat) * 0.5f + 0.5f); } } unsigned index = 0; for (unsigned lat = 0; lat < latitudes; ++lat) { for (unsigned lon = 0; lon < longitudes; ++lon) { if (lat != latitudes - 1) { indices[index++] = lat * (longitudes + 1) + (lon % (longitudes + 1)); indices[index++] = (lat + 1) * (longitudes + 1) + ((lon + 1) % (longitudes + 1)); indices[index++] = (lat + 1) * (longitudes + 1) + (lon % (longitudes + 1)); } if (lat != 0) { indices[index++] = lat * (longitudes + 1) + (lon % (longitudes + 1)); indices[index++] = lat * (longitudes + 1) + ((lon + 1) % (longitudes + 1)); indices[index++] = (lat + 1) * (longitudes + 1) + ((lon + 1) % (longitudes + 1)); } } } // create the vertex and index buffers ID3D11Buffer *vertexBuffer, *indexBuffer; for (auto bufferInfo : { tuple<unsigned, void*, ID3D11Buffer**, unsigned>(sizeof(VertexLitTextureType) * vertexCount, vertices, &vertexBuffer, D3D11_BIND_VERTEX_BUFFER), tuple<unsigned, void*, ID3D11Buffer**, unsigned>(sizeof(unsigned long) * indexCount, indices, &indexBuffer, D3D11_BIND_INDEX_BUFFER) }) { D3D11_BUFFER_DESC bufferDesc; bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.ByteWidth = get<0>(bufferInfo); bufferDesc.BindFlags = get<3>(bufferInfo); bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; bufferDesc.StructureByteStride = 0; // give the subresource structure a pointer to the raw data D3D11_SUBRESOURCE_DATA bufferData; bufferData.pSysMem = get<1>(bufferInfo); bufferData.SysMemPitch = 0; bufferData.SysMemSlicePitch = 0; // create the buffer assert(!FAILED(result = device->CreateBuffer(&bufferDesc, &bufferData, get<2>(bufferInfo)))); } delete[] vertices; delete[] indices; // set up the camera XMFLOAT3 position(0.f, 0.f, -3.f); XMFLOAT3 rotation(0.f, 0.f, 0.f); XMFLOAT3 up(0.f, 1.f, 0.f); XMFLOAT3 forward(0.f, 0.f, 1.f); // texture // read the targa file FILE* filePtr; assert(fopen_s(&filePtr, "earthmap1k.tga", "rb") == 0); TargaHeader targaHeader; assert((unsigned)fread(&targaHeader, sizeof(TargaHeader), 1, filePtr) == 1); assert(targaHeader.bpp == 32 || targaHeader.bpp == 24); unsigned bytespp = targaHeader.bpp / 8; unsigned imageSize = targaHeader.width * targaHeader.height * bytespp; auto targaImage = new unsigned char[imageSize]; assert(targaImage); assert((unsigned)fread(targaImage, 1, imageSize, filePtr) == imageSize); assert(fclose(filePtr) == 0); unsigned i = 0; auto targaData = new unsigned char[imageSize / bytespp * 4]; // targa stores it upside down, so go through the rows backwards for (int r = (int)targaHeader.height - 1; r >= 0; --r) { // signed because it must become -1 for (unsigned j = r * targaHeader.width * bytespp; j < (r + 1) * targaHeader.width * bytespp; j += bytespp) { targaData[i++] = targaImage[j + 2]; // red targaData[i++] = targaImage[j + 1]; // green targaData[i++] = targaImage[j + 0]; // blue targaData[i++] = bytespp == 4 ? targaImage[j + 3] : 0; // alpha } } delete[] targaImage; // create the texture D3D11_TEXTURE2D_DESC textureDesc; textureDesc.Height = targaHeader.height; textureDesc.Width = targaHeader.width; textureDesc.MipLevels = 0; textureDesc.ArraySize = 1; textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS; ID3D11Texture2D* texture; assert(!FAILED(result = device->CreateTexture2D(&textureDesc, NULL, &texture))); // copy the image data into the texture context->UpdateSubresource(texture, 0, NULL, targaData, targaHeader.width * 4 * sizeof(unsigned char), 0); // create the shader resource view so shaders can read from the texture D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = textureDesc.Format; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = -1; ID3D11ShaderResourceView* textureView; assert(!FAILED(result = device->CreateShaderResourceView(texture, &srvDesc, &textureView))); // generate mipmaps context->GenerateMips(textureView); // main loop MSG msg = {0}; unsigned framesDrawn = 0; while (true) { // Check to see if any messages are waiting in the queue if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // translate keystroke messages into the right format TranslateMessage(&msg); // send the message to the WindowProc function DispatchMessage(&msg); // check to see if it's time to quit if (msg.message == WM_QUIT) break; } else { // clear the back buffer with the background color and clear the depth buffer float color[4] = {0.f, 0.f, 0.f, 1.f}; context->ClearRenderTargetView(renderTargetView, color); context->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0); // generate the view matrix based on the camera XMVECTOR upVector = XMLoadFloat3(&up); XMVECTOR lookAtVector = XMLoadFloat3(&forward); XMVECTOR positionVector = XMLoadFloat3(&position); XMMATRIX rotationMatrix = XMMatrixRotationRollPitchYaw(rotation.x, rotation.y, rotation.z); // rotate the forward and up according to the camera rotation lookAtVector = XMVector3TransformCoord(lookAtVector, rotationMatrix); upVector = XMVector3TransformCoord(upVector, rotationMatrix); // move the forward vector to the target position lookAtVector = XMVectorAdd(positionVector, lookAtVector); // create the view matrix XMMATRIX viewMatrix = XMMatrixLookAtLH(positionVector, lookAtVector, upVector); // add rotation to the sphere worldMatrix = XMMatrixRotationY(time() * 0.3f); // stage the triangle's buffers as the ones to use // set the vertex buffer to active in the input assembler unsigned stride = sizeof(VertexLitTextureType); unsigned offset = 0; context->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset); // set the index buffer to active in the input assembler context->IASetIndexBuffer(indexBuffer, DXGI_FORMAT_R32_UINT, 0); // Set the type of primitive that should be rendered from this vertex buffer, in this case triangles. context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // render the model using the lit texture shader // lock the matrixBuffer, set the new matrices inside it, and then unlock it // shaders must receive transposed matrices in DirectX11 D3D11_MAPPED_SUBRESOURCE mappedResource; assert(!FAILED(result = context->Map(matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource))); auto matrixDataPtr = (MatrixBufferType*)mappedResource.pData; matrixDataPtr->world = XMMatrixTranspose(worldMatrix); matrixDataPtr->view = XMMatrixTranspose(viewMatrix); matrixDataPtr->projection = XMMatrixTranspose(projectionMatrix); context->Unmap(matrixBuffer, 0); // set the materialBuffer information assert(SUCCEEDED(result = context->Map(materialBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource))); auto materialDataPtr = (MaterialBufferType*)mappedResource.pData; materialDataPtr->materialAmbient = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); materialDataPtr->materialDiffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); materialDataPtr->materialSpecular = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f); context->Unmap(materialBuffer, 0); // set the lightingBuffer information assert(SUCCEEDED(result = context->Map(lightingBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource))); auto lightingDataPtr = (LightingBufferType*)mappedResource.pData; lightingDataPtr->lightAmbient = XMFLOAT4(0.1f, 0.1f, 0.1f, 1.0f); lightingDataPtr->lightDiffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); lightingDataPtr->lightDirection = XMFLOAT4(0.70710678118f, 0.0f, 0.70710678118f, 0.0f); lightingDataPtr->lightSpecular = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); XMStoreFloat4(&lightingDataPtr->viewPosition, positionVector); context->Unmap(lightingBuffer, 0); // update the vertex and pixel shader constant buffers // they're in the constantBuffers in the order: matrix, material, lighting // the vertex shader needs matrix, material, lighting in its 0, 1, 2 spots // the pixel shader needs just material, lighting in its 0, 1 spots context->VSSetConstantBuffers(0, 3, constantBuffers); context->PSSetConstantBuffers(0, 2, &(constantBuffers[1])); // give the pixel shader the texture context->PSSetShaderResources(0, 1, &textureView); // set the vertex input layout context->IASetInputLayout(litTextureShaderInputLayout); // set the vertex and pixel shaders that will be used to render this triangle context->VSSetShader(litTextureVertexShader, NULL, 0); context->PSSetShader(litTexturePixelShader, NULL, 0); context->PSSetSamplers(0, 1, &samplerState); // render the sphere context->DrawIndexed(indexCount, 0, 0); // Present the back buffer to the screen since rendering is complete. swapChain->Present(vsync ? 1 : 0, 0); ++framesDrawn; } } // clean up if (swapChain && !windowed) swapChain->SetFullscreenState(false, NULL); if (textureView) textureView->Release(); if (texture) texture->Release(); if (targaData) delete[] targaData; if (vertexBuffer) vertexBuffer->Release(); if (indexBuffer) indexBuffer->Release(); if (samplerState) samplerState->Release(); if (lightingBuffer) lightingBuffer->Release(); if (materialBuffer) materialBuffer->Release(); if (matrixBuffer) matrixBuffer->Release(); if (textureShaderInputLayout) textureShaderInputLayout->Release(); if (textureVertexShader) textureVertexShader->Release(); if (texturePixelShader) texturePixelShader->Release(); if (colorShaderInputLayout) colorShaderInputLayout->Release(); if (colorVertexShader) colorVertexShader->Release(); if (rasterState) rasterState->Release(); if (colorPixelShader) colorPixelShader->Release(); if (depthStencilView) depthStencilView->Release(); if (depthStencilState) depthStencilState->Release(); if (depthStencilBuffer) depthStencilBuffer->Release(); if (renderTargetView) renderTargetView->Release(); if (context) context->Release(); if (device) device->Release(); if (swapChain) swapChain->Release(); // return this part of the WM_QUIT message to Windows return msg.wParam; } // this is the main message handler for the program LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { // sort through and find what code to run for the message given switch (message) { // this message is read when the window is closed case WM_DESTROY: { // close the application entirely PostQuitMessage(0); return 0; } break; } // handle any messages that the switch statement didn't return DefWindowProc(hWnd, message, wParam, lParam); }
#include "tabwidget.h" #include "ui_tabwidget.h" #include "cvimagewidget.h" using namespace std; /*----------------------* * * * * * TAB WIDGET * * * * * *----------------------*/ TabWidget::TabWidget(QWidget *parent) : QTabWidget(parent), ui(new Ui::TabWidget) { ui->setupUi(this); setAcceptDrops(true); this->setMovable(true); this->setUsesScrollButtons(true); this->acceptDrops(); this->setTabIcon(0,QIcon(icons_folder+"home.png")); connect(this, SIGNAL(currentChanged(int)), this, SLOT(tabChanged())); } TabWidget::~TabWidget() { delete ui; } View* TabWidget::addNewView(QString title,bool add_to_userinfo){ // actualizar userinfo if(add_to_userinfo){ MGrid* mgrid = new struct MGrid; mgrid->name = title.toStdString(); mgrid->independent = false; mgrid->type = -1; vector<string> cameras_id; for(int i=0;i<182;i++) cameras_id.push_back("0"); mgrid->cameras_id = cameras_id; userinfo.grids.push_back(mgrid); } View* newview = new View(this,title); views_.push_back(newview); return newview; } void TabWidget::changeCurrentTab(string name){ //si es una grilla for(uint i=0;i<views_.size();i++) if(views_[i]->name_.toStdString() == name) setCurrentWidget(views_[i]->view_widget_); //si es un map for(uint i=0;i<maps_.size();i++) if(maps_[i].name_.toStdString() == name) setCurrentWidget(maps_[i].mapwidget_); } void TabWidget::changeCurrentGridName(QString name){ for(uint i=0;i<views_.size();i++) if(views_[i]->view_widget_ == this->currentWidget()) views_[i]->name_ = name; setTabText(currentIndex(),name); } void TabWidget::changeCurrentEmapName(QString name){ for(uint i=0;i<maps_.size();i++) if(maps_[i].mapwidget_ == this->currentWidget()) maps_[i].name_ = name; setTabText(currentIndex(),name); } EMap TabWidget::addNewMap(QString title,bool update_user_info){ QWidget* mapwidget = new QWidget(); MapImage* mapimage = new MapImage(mapwidget); connect(mapimage,SIGNAL(imageChanged(MapImage*)),this,SLOT(imageChanged(MapImage*))); connect(mapimage,SIGNAL(cameraDropped(MapImage*,Camera*)),this,SLOT(cameraDropped(MapImage*,Camera*))); EMap newemap; newemap.name_ = title; newemap.mapwidget_ = mapwidget; newemap.mapimage_ = mapimage; newemap.remove_ = false; addTab(mapwidget,QIcon(icons_folder+"emap.png"),title); maps_.push_back(newemap); // actualizar userinfo if(update_user_info){ MEmap* memap = new struct MEmap; memap->independent=false; memap->name = title.toStdString(); memap->image = mapimage->map_path; vector<string> nullvec; memap->cameras_position = nullvec; memap->cameras_id = nullvec; userinfo.emaps.push_back(memap); bool mongo_connected; vsmongo->updateUserInfoEmaps(mongo_connected); } return newemap; } void TabWidget::imageChanged(MapImage* mimg){ /* std::string image_path = mimg->map_path; string emap_name = mimg for(uint u=0;u<userinfo.emaps.size();u++) if(userinfo.emaps[u]->name == emap_name){ userinfo.emaps[u]->image = mimg->map_path; bool mongo_connected; vsmongo->updateUserInfoEmaps(mongo_connected); } */ //busco el emap al que se corresponde.. for(uint e=0;e<maps_.size();e++) if(maps_[e].mapwidget_ == mimg){ string emap_name = maps_[e].name_.toStdString(); //actualizar userinfo for(uint u=0;u<userinfo.emaps.size();u++) if(userinfo.emaps[u]->name == emap_name){ userinfo.emaps[u]->image = mimg->map_path; bool mongo_connected; vsmongo->updateUserInfoEmaps(mongo_connected); } } } void TabWidget::cameraDropped(MapImage*mimg, Camera*cam){ std::string camera_id; if(cam->is_channel_) camera_id = to_string(cam->channel_)+ "$" +cam->dhdevice_id_; else camera_id = cam->unique_id_; // busco el emap correspondiente string emap_name; bool emap_found = false; for(uint e=0;e<maps_.size();e++) if(maps_[e].mapimage_ == mimg){ emap_found = true; emap_name = maps_[e].name_.toStdString(); } // actualizar userinfo if(emap_found){ for(uint u=0;u<userinfo.emaps.size();u++){ MEmap* thismap = userinfo.emaps[u]; // me paro en el emap de userinfo correspondiente if(thismap->name == emap_name){ bool alredy_mapped = false; string pos_s = mimg->getStringPositionOf(cam); // si ya estaba, reemplazo los valores for(uint f=0;f<thismap->cameras_id.size();f++) if(thismap->cameras_id[f]==camera_id){ alredy_mapped = true; thismap->cameras_id[f] = camera_id; thismap->cameras_position[f] = pos_s; } // si no estaba, agrego un nuevo elemento if(!alredy_mapped){ thismap->cameras_id.push_back(camera_id); thismap->cameras_position.push_back(pos_s); } bool mongo_connected; vsmongo->updateUserInfoEmaps(mongo_connected); } } } } EMap TabWidget::getCurrentEMap(){ QWidget* widget = currentWidget(); for(uint i=0;i<maps_.size();i++) if ( widget == maps_[i].mapwidget_) return maps_[i]; EMap nomap; nomap.name_ = ""; nomap.mapimage_ = NULL; nomap.mapwidget_ = NULL; nomap.remove_ = true; return nomap; } void TabWidget::removeCameraFromMaps(QString camera_name){ for(uint i=0;i<maps_.size();i++) maps_[i].mapimage_->removeCamera(camera_name); } void TabWidget::updateViewsAndMaps(){ for(uint i=0;i<views_.size();i++) views_[i]->updatePositions(); // update maps for(uint i=0;i<maps_.size();i++) maps_[i].mapimage_->setGeometry(0,0,this->width(),this->height()-10); } void TabWidget::tabChanged(){ log("Se cambia la pestaña actual a: "+tabText(currentIndex()).toStdString()); userinfo.tabactual = tabText(currentIndex()).toStdString(); bool mongo_connected; vsmongo->updateUserInfoTabActual(mongo_connected); for(uint i=0;i<views_.size();i++) if(views_[i]->view_widget_ == this->currentWidget()){ // poner todos sus cvwidgets visibles views_[i]->setAllCVWidgetsVisibles(true); }else{ // poner todos sus cvwidgets no visibles views_[i]->setAllCVWidgetsVisibles(false); } } void TabWidget::removeMap(MapImage* map){ for(uint i=0;i<maps_.size();i++) if(map == maps_[i].mapimage_){ map->removeAllDocks(); map->close(); maps_.erase(maps_.begin()+i); break; } } QString TabWidget::getInfo(){ QString res = ""; res += "- Tab widget: "+QString::number(this->width()) + "x" + QString::number(this->height()) + "\n"; for(uint i=0;i<views_.size();i++) res += views_[i]->getInfo(); return res; } void TabWidget::deleteEMap(QWidget* emap_widget){ for(uint i=0;i<maps_.size();i++){ if(maps_[i].mapwidget_ == emap_widget){ EMap emap_to_remove = maps_[i]; emap_to_remove.mapimage_->removeAllDocks(); delete emap_to_remove.mapwidget_; maps_.erase(maps_.begin()+i); break; } } } void TabWidget::deleteView(QWidget* view_widget){ for(uint i=0;i<views_.size();i++){ if(views_[i]->view_widget_ == view_widget){ // encontre la view para eliminar views_[i]->removeAllCVWidgets(); views_[i]->removeButtons(); views_[i]->removeWidget(); delete views_[i]; views_.erase(views_.begin()+i); break; } } } View* TabWidget::takeOutCurrentView(){ View* cur_view; for(uint i=0;i<views_.size();i++){ if(views_[i]->view_widget_ == this->currentWidget()){ cur_view = views_[i]; views_.erase(views_.begin()+i); } } return cur_view; } CVImageWidget* TabWidget::getCurrentViewCVWidget(QPoint globalPos){ //get current view View* cur_view; for(uint i=0;i<views_.size();i++) if(views_[i]->view_widget_ == this->currentWidget()) cur_view = views_[i]; //get current view's selected widget return cur_view->getCVWidgetByGlobalPos(globalPos); } bool TabWidget::isAView(int index){ QWidget* widget = this->widget(index); for(uint i=0;i<views_.size();i++) if ( widget == views_[i]->view_widget_) return true; return false; } bool TabWidget::isAMap(int index){ QWidget* widget = this->widget(index); for(uint i=0;i<maps_.size();i++) if ( widget == maps_[i].mapwidget_) return true; return false; } /*----------------------* * * * * * VIEW * * * * * *----------------------*/ View::View(TabWidget* tab_widget, QString name){ show_ptz_ = false; // inicializar los vectores de camaras guardadas for(uint i=0;i<182;i++) saved_cameras_.push_back(NULL); tab_widget_ = tab_widget; name_ = name; // Crear widget de la tab view_widget_ = new QWidget(); QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); view_widget_->setSizePolicy(sizePolicy); view_widget_->setGeometry(0,0,tab_widget_->width(),tab_widget_->height()); // Agregar botones addButtons(); // Agregar tab tab_widget->addTab(view_widget_,QIcon(icons_folder+"grid.png"),name); // Vista 1x1 por default type = -1; } CVImageWidget* View::getCVWidgetByGlobalPos(QPoint globalPos){ for(uint i=0;i<cv_widgets_.size();i++){ QPoint cv_tl(cv_widgets_[i]->x(),cv_widgets_[i]->y()); QPoint cv_br(cv_widgets_[i]->x()+cv_widgets_[i]->width(),cv_widgets_[i]->y()+cv_widgets_[i]->height()); QPoint global_cv_tl = view_widget_->mapToGlobal(cv_tl); QPoint global_cv_br = view_widget_->mapToGlobal(cv_br); if(globalPos.x() >= global_cv_tl.x() && globalPos.x() < global_cv_br.x() && globalPos.y() >= global_cv_tl.y() && globalPos.y() < global_cv_br.y()) { return cv_widgets_[i]; } } return NULL; } QString View::getInfo(){ QString res = ""; res += "-- view widget " + QString::number(view_widget_->width()) + "x" + QString::number(view_widget_->height()) + "\n"; for(uint i=0;i<cv_widgets_.size();i++){ res += "--- cv widget " + QString::number(cv_widgets_[i]->width()) + "x" + QString::number(cv_widgets_[i]->height()) + "\n"; } return res; } void View::removeAllCVWidgets(){ for(uint i=0;i<cv_widgets_.size();i++){ for(uint j=0;j<cvwidgets.size();j++) if(cvwidgets[j]==cv_widgets_[i]){ cv_widgets_[i]->added_to_rep_list_ = false; cvwidgets.erase(cvwidgets.begin()+j); } delete cv_widgets_[i]; } cv_widgets_.clear(); while ( QWidget* w = findChild<QWidget*>() ) delete w; } void View::removeWidget(){ delete view_widget_; } void View::removeButtons(){ for(uint i=0;i<buttons_.size();i++) delete buttons_[i]; buttons_.clear(); } void View::removeSavedCamera(Camera* to_remove){ for(uint i=0;i<saved_cameras_.size();i++) if(saved_cameras_[i] == to_remove) saved_cameras_[i] = NULL; } QPushButton* View::addButton(int& x_pos,int y_pos, int button_width,int button_height, QIcon icon,QSize icon_size){ QPushButton* nb = new QPushButton(view_widget_); nb->setStyleSheet("border: none"); nb->setGeometry(x_pos,y_pos,button_width,button_height); nb->setIconSize(icon_size); nb->setIcon(icon); x_pos += button_width + 1; buttons_.push_back(nb); return nb; } QPushButton* View::addPtzButton(int& x_pos,int y_pos, int button_width,int button_height, QIcon icon,QSize icon_size){ QPushButton* nb = new QPushButton(view_widget_); nb->setStyleSheet("border: none"); nb->setGeometry(x_pos,y_pos,button_width,button_height); nb->setIconSize(icon_size); nb->setIcon(icon); y_pos += button_height + 1; ptzbuttons_.push_back(nb); nb->show(); return nb; } void View::addButtons(){ int buttons_width = 50; int buttons_height = 25; QSize icons_size(40,20); int x_pos = 5; int y_pos = view_widget_->height()-30; // 1x1 QPushButton* nb0 = addButton(x_pos,y_pos,buttons_width,buttons_height,black_icons[0],icons_size); nb0->setFocusPolicy(Qt::NoFocus); connect(nb0,SIGNAL(clicked(bool)),this,SLOT(changeTo1x1())); // 2x2h QPushButton* nb1 = addButton(x_pos,y_pos,buttons_width,buttons_height,black_icons[1],icons_size); nb1->setFocusPolicy(Qt::NoFocus); connect(nb1,SIGNAL(clicked(bool)),this,SLOT(changeTo2x2())); // 5+1 QPushButton* nb2 = addButton(x_pos,y_pos,buttons_width,buttons_height,black_icons[2],icons_size); nb2->setFocusPolicy(Qt::NoFocus); connect(nb2,SIGNAL(clicked(bool)),this,SLOT(changeTo5_1())); // 3x3 QPushButton* nb3 = addButton(x_pos,y_pos,buttons_width,buttons_height,black_icons[3],icons_size); nb3->setFocusPolicy(Qt::NoFocus); connect(nb3,SIGNAL(clicked(bool)),this,SLOT(changeTo3x3())); // 7+1 QPushButton* nb4 = addButton(x_pos,y_pos,buttons_width,buttons_height,black_icons[4],icons_size); nb4->setFocusPolicy(Qt::NoFocus); connect(nb4,SIGNAL(clicked(bool)),this,SLOT(changeTo7_1())); // 12+1 QPushButton* nb5 = addButton(x_pos,y_pos,buttons_width,buttons_height,black_icons[5],icons_size); nb5->setFocusPolicy(Qt::NoFocus); connect(nb5,SIGNAL(clicked(bool)),this,SLOT(changeTo12_1())); // 4x4 QPushButton* nb6 = addButton(x_pos,y_pos,buttons_width,buttons_height,black_icons[6],icons_size); nb6->setFocusPolicy(Qt::NoFocus); connect(nb6,SIGNAL(clicked(bool)),this,SLOT(changeTo4x4())); // 5x5 QPushButton* nb7 = addButton(x_pos,y_pos,buttons_width,buttons_height,black_icons[7],icons_size); nb7->setFocusPolicy(Qt::NoFocus); connect(nb7,SIGNAL(clicked(bool)),this,SLOT(changeTo5x5())); // 6x6 QPushButton* nb8 = addButton(x_pos,y_pos,buttons_width,buttons_height,black_icons[8],icons_size); nb8->setFocusPolicy(Qt::NoFocus); connect(nb8,SIGNAL(clicked(bool)),this,SLOT(changeTo6x6())); // 8x8 QPushButton* nb9 = addButton(x_pos,y_pos,buttons_width,buttons_height,black_icons[9],icons_size); nb9->setFocusPolicy(Qt::NoFocus); connect(nb9,SIGNAL(clicked(bool)),this,SLOT(changeTo8x8())); } void View::setAllCVWidgetsVisibles(bool visibles){ for(uint i=0;i<cv_widgets_.size();i++) cv_widgets_[i]->visible_ = visibles; } void View::paintCVImagesBlack(){ for(uint i=0;i<cv_widgets_.size();i++) if(!cv_widgets_[i]->added_to_rep_list_) cv_widgets_[i]->showBlack(); } void View::repositionNxN(int N){ if(cv_widgets_.size() == (uint)N*N){ int w; if(show_ptz_) w = ((view_widget_->width()-24)/N)-4; else w = (view_widget_->width()/N)-4; int h = ((view_widget_->height()-40-3*N)/N); for(int row=0;row<N;row++) for(int col=0;col<N;col++) cv_widgets_[row*N+col]->setGeometry(col*w+3*col,row*h+3*row,w,h); } } void View::reposition5_1(){ if(cv_widgets_.size() == 6){ int w; if(show_ptz_) w = ((view_widget_->width()-24)/3)-4; else w = (view_widget_->width()/3)-4; int h = ((view_widget_->height() - 49)/3); cv_widgets_[0]->setGeometry(0,0,w*2+3,h*2+3); cv_widgets_[1]->setGeometry(2*w + 6,0,w,h); cv_widgets_[2]->setGeometry(2*w + 6,h + 3,w,h); cv_widgets_[3]->setGeometry(0,2*h + 6,w,h); cv_widgets_[4]->setGeometry(w+3,2*h + 6,w,h); cv_widgets_[5]->setGeometry(2*w + 6,2*h + 6,w,h); } } void View::reposition7_1(){ if(cv_widgets_.size() == 8){ int w; if(show_ptz_) w = ((view_widget_->width()-24)/4)-4; else w = (view_widget_->width()/4)-4; int h = ((view_widget_->height() - 56)/4); cv_widgets_[0]->setGeometry(0,0,w*3+5,h*3+5); cv_widgets_[1]->setGeometry(3*w + 9,0,w,h); cv_widgets_[2]->setGeometry(3*w + 9,h+3,w,h); cv_widgets_[3]->setGeometry(3*w + 9,2*h + 6,w,h); cv_widgets_[4]->setGeometry(0,3*h + 9,w,h); cv_widgets_[5]->setGeometry(w+3,3*h + 9,w,h); cv_widgets_[6]->setGeometry(2*w + 6,3*h + 9,w,h); cv_widgets_[7]->setGeometry(3*w + 9,3*h + 9,w,h); } } void View::reposition12_1(){ if(cv_widgets_.size() == 13){ int w; if(show_ptz_) w = ((view_widget_->width()-24)/4)-4; else w = (view_widget_->width()/4)-4; int h = ((view_widget_->height() - 56)/4); cv_widgets_[0]->setGeometry(w+3,h+3,w*2+3,h*2+3); cv_widgets_[1]->setGeometry(0,0,w,h); cv_widgets_[2]->setGeometry(w+3,0,w,h); cv_widgets_[3]->setGeometry(2*w + 6,0,w,h); cv_widgets_[4]->setGeometry(3*w + 9,0,w,h); cv_widgets_[5]->setGeometry(0,h+3,w,h); cv_widgets_[6]->setGeometry(3*w + 9,h+3,w,h); cv_widgets_[7]->setGeometry(0,2*h + 6,w,h); cv_widgets_[8]->setGeometry(3*w + 9,2*h + 6,w,h); cv_widgets_[9]->setGeometry(0,3*h + 9,w,h); cv_widgets_[10]->setGeometry(w+3,3*h + 9,w,h); cv_widgets_[11]->setGeometry(2*w + 6,3*h + 9,w,h); cv_widgets_[12]->setGeometry(3*w + 9,3*h + 9,w,h); } } void View::changeButtonColors(int blue_index){ for(uint i=0;i<buttons_.size();i++){ buttons_[i]->setIcon(black_icons[i]); } buttons_[blue_index]->setIcon(blue_icons[blue_index]); } void View::addPtzButtons(){ int buttons_width = 20; int buttons_height = 20; QSize icons_size(19,19); int x_pos = view_widget_->width()-22; int y_pos = 5; //up QPushButton* up = addPtzButton(x_pos,y_pos,buttons_width,buttons_height,QIcon(icons_folder+"ptz_up.png"),icons_size); up->setToolTip("Mover hacia arriba"); up->setFocusPolicy(Qt::NoFocus); connect(up,SIGNAL(clicked(bool)),this,SLOT(ptzUp())); //down QPushButton* down = addPtzButton(x_pos,y_pos,buttons_width,buttons_height,QIcon(icons_folder+"ptz_down.png"),icons_size); down->setToolTip("Mover hacia abajo"); down->setFocusPolicy(Qt::NoFocus); connect(down,SIGNAL(clicked(bool)),this,SLOT(ptzDown())); //left QPushButton* left = addPtzButton(x_pos,y_pos,buttons_width,buttons_height,QIcon(icons_folder+"ptz_left.png"),icons_size); left->setToolTip("Mover hacia la izquierda"); left->setFocusPolicy(Qt::NoFocus); connect(left,SIGNAL(clicked(bool)),this,SLOT(ptzLeft())); //right QPushButton* right = addPtzButton(x_pos,y_pos,buttons_width,buttons_height,QIcon(icons_folder+"ptz_right.png"),icons_size); right->setToolTip("Mover hacia la derecha"); right->setFocusPolicy(Qt::NoFocus); connect(right,SIGNAL(clicked(bool)),this,SLOT(ptzRight())); //zin QPushButton* zin = addPtzButton(x_pos,y_pos,buttons_width,buttons_height,QIcon(icons_folder+"ptz_zoomin.png"),icons_size); zin->setToolTip("Zoom (+)"); zin->setFocusPolicy(Qt::NoFocus); connect(zin,SIGNAL(clicked(bool)),this,SLOT(ptzZoomIn())); //zout QPushButton* zout = addPtzButton(x_pos,y_pos,buttons_width,buttons_height,QIcon(icons_folder+"ptz_zoomout.png"),icons_size); zout->setToolTip("Zoom (-)"); zout->setFocusPolicy(Qt::NoFocus); connect(zout,SIGNAL(clicked(bool)),this,SLOT(ptzZoomOut())); //tour QPushButton* tour = addPtzButton(x_pos,y_pos,buttons_width,buttons_height,QIcon(icons_folder+"ptz_tour.png"),icons_size); tour->setToolTip("Comenzar tour"); tour->setFocusPolicy(Qt::NoFocus); connect(tour,SIGNAL(clicked(bool)),this,SLOT(ptzTour())); //presets QPushButton* presets = addPtzButton(x_pos,y_pos,buttons_width,buttons_height,QIcon(icons_folder+"presets.png"),icons_size); presets->setToolTip("Seleccionar preset"); presets->setFocusPolicy(Qt::NoFocus); presets_menu_ = new QMenu(view_widget_); connect(presets_menu_,SIGNAL(aboutToShow()),this,SLOT(openPresetMenu())); connect(presets_menu_,SIGNAL(triggered(QAction*)),this,SLOT(onPresetSelected(QAction*))); presets->setMenu(presets_menu_); //connect(presets,SIGNAL(clicked(bool)),this,SLOT(ptzTour())); } void View::onPresetSelected(QAction* act){ if(selected_camera != NULL && selected_camera->onvif_config_.active){ if(act->text() == "Recargar presets"){ if(selected_camera != NULL && selected_camera->onvif_config_.active){ log("Se actualizan los presets de la camara seleccionada"); selected_camera->updatePresets(); } return; } if(act->text()=="Guardar preset"){ bool ok; QString text = QInputDialog::getText(view_widget_, tr("Guardar preset"), tr("Nombre:"), QLineEdit::Normal, "", &ok); if (ok && !text.isEmpty()){ // guardar preset PtzMovement pm; pm.ip = selected_camera->onvif_config_.ip; pm.movement = "set"; pm.password = selected_camera->onvif_config_.password; pm.port = selected_camera->onvif_config_.port; pm.user = selected_camera->onvif_config_.user; pm.velocity = selected_camera->onvif_config_.velocity; pm.timeout = selected_camera->onvif_config_.timeout; pm.preset = text.toStdString(); ptz->newPtzAction(pm); } return; } // ir a un preset: // conseguir el indice de preset .. int preset_index = 0; QList<QAction*> actions = presets_menu_->actions(); for(int i=0;i<actions.size();i++) if(actions[i]->text() == act->text()){ preset_index = i; break; } // mover la camara .. log("Movimiento de ptz de la camara seleccionada: preset "+to_string(preset_index)); selected_camera->goToPreset(preset_index); } } void View::openPresetMenu(){ presets_menu_->clear(); // agregar items al menu if(selected_camera != NULL && selected_camera->onvif_config_.active){ for(uint i=0;i<selected_camera->presets_.size();i++){ string preset_s = selected_camera->presets_[i].first + ":" +selected_camera->presets_[i].second; presets_menu_->addAction(QString::fromStdString(preset_s)); } presets_menu_->addSeparator(); presets_menu_->addAction(QIcon(icons_folder+"save.png"),"Guardar preset"); presets_menu_->addAction(QIcon(icons_folder+"loop.png"),"Recargar presets"); } } void View::ptzUp(){ if(selected_camera != NULL && selected_camera->onvif_config_.active){ log("Movimiento de ptz de la camara seleccionada: up"); selected_camera->ptzMove("u"); } } void View::ptzDown(){ if(selected_camera != NULL && selected_camera->onvif_config_.active){ log("Movimiento de ptz de la camara seleccionada: down"); selected_camera->ptzMove("d"); } } void View::ptzLeft(){ if(selected_camera != NULL && selected_camera->onvif_config_.active){ log("Movimiento de ptz de la camara seleccionada: left"); selected_camera->ptzMove("l"); } } void View::ptzRight(){ if(selected_camera != NULL && selected_camera->onvif_config_.active){ log("Movimiento de ptz de la camara seleccionada: right"); selected_camera->ptzMove("r"); } } void View::ptzZoomIn(){ if(selected_camera != NULL && selected_camera->onvif_config_.active){ log("Movimiento de ptz de la camara seleccionada: zoom-in"); selected_camera->ptzMove("+"); } } void View::ptzZoomOut(){ if(selected_camera != NULL && selected_camera->onvif_config_.active){ log("Movimiento de ptz de la camara seleccionada: zoom-out"); selected_camera->ptzMove("-"); } } void View::ptzTour(){ if(selected_camera != NULL && selected_camera->onvif_config_.active){ log("Movimiento de ptz de la camara seleccionada: tour"); selected_camera->startTour(); } } void View::setToShowPtz(){ // crear botones de ptz y conectarlos addPtzButtons(); show_ptz_ = true; } void View::changeTo1x1(){ changeButtonColors(0); if (type != 0){ log("Se cambia la grilla actual al tipo 1x1"); vector<Camera*> active_widgets_cameras; for(uint i=0;i<cv_widgets_.size();i++) if(cv_widgets_[i]->added_to_rep_list_) active_widgets_cameras.push_back(cv_widgets_[i]->camera_); saveCameras(); // actualizar // crear nuevo widget removeAllCVWidgets(); type = 0; addCVWidget(getGridIndex(),0); repositionNxN(1); paintCVImagesBlack(); loadCameras(active_widgets_cameras); // actualizar userinfo for(uint i=0;i<userinfo.grids.size();i++) if(userinfo.grids[i]->name == name_.toStdString()) userinfo.grids[i]->type = type; bool mongo_connected; vsmongo->updateUserInfoGrids(mongo_connected); // } } void View::changeTo2x2(){ changeButtonColors(1); if (type != 1){ log("Se cambia la grilla actual al tipo 2x2"); vector<Camera*> active_widgets_cameras; for(uint i=0;i<cv_widgets_.size();i++) if(cv_widgets_[i]->added_to_rep_list_) active_widgets_cameras.push_back(cv_widgets_[i]->camera_); saveCameras(); //crear nuevos widgets removeAllCVWidgets(); type = 1; for(uint i=0;i<4;i++) addCVWidget(getGridIndex(),getWidgetIndex(i)); repositionNxN(2); paintCVImagesBlack(); loadCameras(active_widgets_cameras); // actualizar userinfo for(uint i=0;i<userinfo.grids.size();i++) if(userinfo.grids[i]->name == name_.toStdString()) userinfo.grids[i]->type = type; bool mongo_connected; vsmongo->updateUserInfoGrids(mongo_connected); // } } void View::saveCameras(){ int start_index=0; switch (type) { case 0: start_index = 0; break; case 1://+1 start_index = 1; break; case 2://+4 start_index = 5; break; case 3://+6 start_index = 11; break; case 4://+9 start_index = 20; break; case 5://+8 start_index = 28; break; case 6://+13 start_index = 41; break; case 7://+16 start_index = 57; break; case 8://+25 start_index = 82; break; case 9://+36 start_index = 118; break; default: break; } for(uint i=0;i<cv_widgets_.size();i++) if(cv_widgets_[i]->added_to_rep_list_) saved_cameras_[start_index+i] = cv_widgets_[i]->camera_; else saved_cameras_[start_index+i] = NULL; } void View::loadCameras(vector<Camera*> last_cameras){ int start_index=0; switch (type) { case 0: start_index = 0; break; case 1://+1 start_index = 1; break; case 2://+4 start_index = 5; break; case 3://+6 start_index = 11; break; case 4://+9 start_index = 20; break; case 5://+8 start_index = 28; break; case 6://+13 start_index = 41; break; case 7://+16 start_index = 57; break; case 8://+25 start_index = 82; break; case 9://+36 start_index = 118; break; default: break; } bool saved = false; for(uint i=0;i<cv_widgets_.size();i++){ if(saved_cameras_[start_index+i]!=NULL){ saved = true; break; } } if(saved){ for(uint i=0;i<cv_widgets_.size();i++) if(saved_cameras_[start_index+i]!=NULL) cv_widgets_[i]->dropCamera(saved_cameras_[start_index+i]); }else{ // no habia nada guardado, copio las camaras que hay ahora int ac_size = last_cameras.size(); int saved_cameras = min((int)cv_widgets_.size(),ac_size); for(int i=0;i<saved_cameras;i++) cv_widgets_[i]->dropCamera(last_cameras[i]); } } void View::changeType(int type){ if(type == 0) changeTo1x1(); if(type == 1) changeTo2x2(); if(type == 2) changeTo5_1(); if(type == 3) changeTo3x3(); if(type == 4) changeTo7_1(); if(type == 5) changeTo12_1(); if(type == 6) changeTo4x4(); if(type == 7) changeTo5x5(); if(type == 8) changeTo6x6(); if(type == 9) changeTo8x8(); } void View::setSavedGrids(vector<Camera*> savedgrids){ if(savedgrids.size()==182) saved_cameras_ = savedgrids; } int View::getGridIndex(){ for(uint i=0;i<userinfo.grids.size();i++) if(userinfo.grids[i]->name == name_.toStdString()) return i; return -1; } int View::getWidgetIndex(int int_index){ int start_index = -1; switch (type) { case 0: start_index = 0; break; case 1://+1 start_index = 1; break; case 2://+4 start_index = 5; break; case 3://+6 start_index = 11; break; case 4://+9 start_index = 20; break; case 5://+8 start_index = 28; break; case 6://+13 start_index = 41; break; case 7://+16 start_index = 57; break; case 8://+25 start_index = 82; break; case 9://+36 start_index = 118; break; default: break; } return start_index+int_index; } void View::changeTo5_1(){ changeButtonColors(2); if(type != 2){ log("Se cambia la grilla actual al tipo 5+1"); vector<Camera*> active_widgets_cameras; for(uint i=0;i<cv_widgets_.size();i++) if(cv_widgets_[i]->added_to_rep_list_) active_widgets_cameras.push_back(cv_widgets_[i]->camera_); saveCameras(); //crear nuevos widgets removeAllCVWidgets(); reposition5_1(); paintCVImagesBlack(); type = 2; for(uint i=0;i<6;i++) addCVWidget(getGridIndex(),getWidgetIndex(i)); loadCameras(active_widgets_cameras); // actualizar userinfo for(uint i=0;i<userinfo.grids.size();i++) if(userinfo.grids[i]->name == name_.toStdString()) userinfo.grids[i]->type = type; bool mongo_connected; vsmongo->updateUserInfoGrids(mongo_connected); // } } void View::changeTo3x3(){ changeButtonColors(3); if(type != 3){ log("Se cambia la grilla actual al tipo 3x3"); vector<Camera*> active_widgets_cameras; for(uint i=0;i<cv_widgets_.size();i++) if(cv_widgets_[i]->added_to_rep_list_) active_widgets_cameras.push_back(cv_widgets_[i]->camera_); saveCameras(); //crear nuevos widgets removeAllCVWidgets(); type = 3; for(uint i=0;i<9;i++) addCVWidget(getGridIndex(),getWidgetIndex(i)); repositionNxN(3); paintCVImagesBlack(); loadCameras(active_widgets_cameras); // actualizar userinfo for(uint i=0;i<userinfo.grids.size();i++) if(userinfo.grids[i]->name == name_.toStdString()) userinfo.grids[i]->type = type; bool mongo_connected; vsmongo->updateUserInfoGrids(mongo_connected); // } } void View::changeTo7_1(){ changeButtonColors(4); if(type != 4){ log("Se cambia la grilla actual al tipo 7+1"); vector<Camera*> active_widgets_cameras; for(uint i=0;i<cv_widgets_.size();i++) if(cv_widgets_[i]->added_to_rep_list_) active_widgets_cameras.push_back(cv_widgets_[i]->camera_); saveCameras(); //crear nuevos widgets removeAllCVWidgets(); type = 4; for(uint i=0;i<8;i++) addCVWidget(getGridIndex(),getWidgetIndex(i)); reposition7_1(); paintCVImagesBlack(); loadCameras(active_widgets_cameras); // actualizar userinfo for(uint i=0;i<userinfo.grids.size();i++) if(userinfo.grids[i]->name == name_.toStdString()) userinfo.grids[i]->type = type; bool mongo_connected; vsmongo->updateUserInfoGrids(mongo_connected); // } } void View::changeTo12_1(){ changeButtonColors(5); if(type != 5){ log("Se cambia la grilla actual al tipo 12+1"); vector<Camera*> active_widgets_cameras; for(uint i=0;i<cv_widgets_.size();i++) if(cv_widgets_[i]->added_to_rep_list_) active_widgets_cameras.push_back(cv_widgets_[i]->camera_); saveCameras(); //crear nuevo widgets removeAllCVWidgets(); type = 5; for(uint i=0;i<13;i++) addCVWidget(getGridIndex(),getWidgetIndex(i)); reposition12_1(); paintCVImagesBlack(); loadCameras(active_widgets_cameras); // actualizar userinfo for(uint i=0;i<userinfo.grids.size();i++) if(userinfo.grids[i]->name == name_.toStdString()) userinfo.grids[i]->type = type; bool mongo_connected; vsmongo->updateUserInfoGrids(mongo_connected); // } } void View::changeTo4x4(){ changeButtonColors(6); if(type != 6){ log("Se cambia la grilla actual al tipo 4x4"); vector<Camera*> active_widgets_cameras; for(uint i=0;i<cv_widgets_.size();i++) if(cv_widgets_[i]->added_to_rep_list_) active_widgets_cameras.push_back(cv_widgets_[i]->camera_); saveCameras(); //crar nuevos widgets removeAllCVWidgets(); type = 6; for(uint i=0;i<16;i++) addCVWidget(getGridIndex(),getWidgetIndex(i)); repositionNxN(4); paintCVImagesBlack(); loadCameras(active_widgets_cameras); // actualizar userinfo for(uint i=0;i<userinfo.grids.size();i++) if(userinfo.grids[i]->name == name_.toStdString()) userinfo.grids[i]->type = type; bool mongo_connected; vsmongo->updateUserInfoGrids(mongo_connected); // } } void View::changeTo5x5(){ changeButtonColors(7); if(type != 7){ log("Se cambia la grilla actual al tipo 5x5"); vector<Camera*> active_widgets_cameras; for(uint i=0;i<cv_widgets_.size();i++) if(cv_widgets_[i]->added_to_rep_list_) active_widgets_cameras.push_back(cv_widgets_[i]->camera_); saveCameras(); //crear nuevos widgets removeAllCVWidgets(); type = 7; for(uint i=0;i<25;i++) addCVWidget(getGridIndex(),getWidgetIndex(i)); repositionNxN(5); paintCVImagesBlack(); loadCameras(active_widgets_cameras); // actualizar userinfo for(uint i=0;i<userinfo.grids.size();i++) if(userinfo.grids[i]->name == name_.toStdString()) userinfo.grids[i]->type = type; bool mongo_connected; vsmongo->updateUserInfoGrids(mongo_connected); // } } void View::changeTo6x6(){ changeButtonColors(8); if(type != 8){ log("Se cambia la grilla actual al tipo 6x6"); vector<Camera*> active_widgets_cameras; for(uint i=0;i<cv_widgets_.size();i++) if(cv_widgets_[i]->added_to_rep_list_) active_widgets_cameras.push_back(cv_widgets_[i]->camera_); saveCameras(); //crear nuevos widgets removeAllCVWidgets(); type = 8; for(uint i=0;i<36;i++) addCVWidget(getGridIndex(),getWidgetIndex(i)); repositionNxN(6); paintCVImagesBlack(); loadCameras(active_widgets_cameras); // actualizar userinfo for(uint i=0;i<userinfo.grids.size();i++) if(userinfo.grids[i]->name == name_.toStdString()) userinfo.grids[i]->type = type; bool mongo_connected; vsmongo->updateUserInfoGrids(mongo_connected); // } } void View::changeTo8x8(){ changeButtonColors(9); if(type != 9){ log("Se cambia la grilla actual al tipo 8x8"); vector<Camera*> active_widgets_cameras; for(uint i=0;i<cv_widgets_.size();i++) if(cv_widgets_[i]->added_to_rep_list_) active_widgets_cameras.push_back(cv_widgets_[i]->camera_); saveCameras(); //crear nuevos widgets removeAllCVWidgets(); type = 9; for(uint i=0;i<64;i++) addCVWidget(getGridIndex(),getWidgetIndex(i)); repositionNxN(8); paintCVImagesBlack(); loadCameras(active_widgets_cameras); // actualizar userinfo for(uint i=0;i<userinfo.grids.size();i++) if(userinfo.grids[i]->name == name_.toStdString()) userinfo.grids[i]->type = type; bool mongo_connected; vsmongo->updateUserInfoGrids(mongo_connected); // } } void View::addCVWidget(int gridindex,int widgetindex){ CVImageWidget* cv_widget = new CVImageWidget(view_widget_); cv_widget->setUserinfoGridsIndex(gridindex,widgetindex); cv_widget->setAcceptDrops(true); cv_widgets_.push_back(cv_widget); cv_widget->show(); } void View::repositionMaximized(int maximized_cvwidget_index){ cv_widgets_[maximized_cvwidget_index]->setGeometry(0,0,view_widget_->width()-4,view_widget_->height()-40); cv_widgets_[maximized_cvwidget_index]->raise(); } void View::updatePositions(){ // reubicar los botones de vistas for(uint i=0;i<buttons_.size();i++) buttons_[i]->setGeometry(10+60*i,view_widget_->height()-30,50,25); // reubicar los botones de ptz si es una ventana independiente if(show_ptz_){ for(uint i=0;i<ptzbuttons_.size();i++){ int x = view_widget_->width()-22; int y = i*22; int w = 20; int h = 20; ptzbuttons_[i]->setGeometry(x,y,w,h); } } // si hay alguno maximizado.. for(uint i=0;i<cv_widgets_.size();i++){ if(cv_widgets_[i]->maximized_){ repositionMaximized(i); return; } } // resizear y reubicar los widgets switch (type) { case 0: repositionNxN(1); break; case 1: repositionNxN(2); break; case 2: reposition5_1(); break; case 3: repositionNxN(3); break; case 4: reposition7_1(); break; case 5: reposition12_1(); break; case 6: repositionNxN(4); break; case 7: repositionNxN(5); break; case 8: repositionNxN(6); break; case 9: repositionNxN(8); break; default: break; } paintCVImagesBlack(); }
#include "compiler.hpp" void modulo() { Identifier a = identifierMap.at(expressionArguments[0]); Identifier b = identifierMap.at(expressionArguments[1]); Identifier aI, bI; if (identifierMap.count(argumentsTabIndex[0]) > 0) aI = identifierMap.at(argumentsTabIndex[0]); if (identifierMap.count(argumentsTabIndex[1]) > 0) bI = identifierMap.at(argumentsTabIndex[1]); if (a.type == "NUM" && stoll(a.name) == 0) { zeroRegister(); } else if (b.type == "NUM" && stoll(b.name) == 0) { zeroRegister(); } else if (a.type == "NUM" && b.type == "NUM") { long long int valM = abs(stoll(a.name)) % abs(stoll(b.name)); long long int valA = stoll(a.name); long long int valB = stoll(b.name); if (valA > 0) { if (valB > 0) setRegister(to_string(valM)); else setRegister(to_string(valM + valB)); } else { if (valB > 0) setRegister(to_string(valB - valM)); else setRegister(to_string(-valM)); } removeIdentifier(a.name); removeIdentifier(b.name); } else { zeroRegister(); registerToMem(7); registerToMem(4); registerToMem(8); registerToMem(13); setToTempMem(a, aI, 5); setToTempMem(b, bI, 6); registerToMem(14); //if (b < 0) b = -b pushCommandOneArg("JNEG", codeVector.size() + 4); pushCommandOneArg("JPOS", codeVector.size() + 10); zeroRegister(); pushCommandOneArg("JUMP", codeVector.size() + 88); pushCommandOneArg("SHIFT", 2); registerToMem(3); memToRegister(6); pushCommandOneArg("SUB", 3); registerToMem(6); memToRegister(2); registerToMem(13); //if (a < 0) a = -a memToRegister(5); pushCommandOneArg("JNEG", codeVector.size() + 4); pushCommandOneArg("JPOS", codeVector.size() + 10); zeroRegister(); pushCommandOneArg("JUMP", codeVector.size() + 76); pushCommandOneArg("SHIFT", 2); registerToMem(3); memToRegister(5); pushCommandOneArg("SUB", 3); registerToMem(5); memToRegister(2); registerToMem(8); //R = a memToRegister(5); registerToMem(10); registerToMem(11); //compute n = #bits of a memToRegister(11); pushCommandOneArg("SHIFT", 9); pushCommandOneArg("JZERO", codeVector.size() + 6); registerToMem(11); memToRegister(4); pushCommand("INC"); registerToMem(4); pushCommandOneArg("JUMP", codeVector.size() - 7); //b = b << n memToRegister(4); pushCommand("INC"); registerToMem(4); memToRegister(6); pushCommandOneArg("SHIFT", 4); registerToMem(11); memToRegister(4); registerToMem(12); //(12) <- -n pushCommandOneArg("SHIFT", 2); registerToMem(3); memToRegister(12); pushCommandOneArg("SUB", 3); registerToMem(12); memToRegister(4); pushCommand("DEC"); // for n-1 .. 0 int stackJ1 = codeVector.size(); pushCommandOneArg("JNEG", codeVector.size() + 23); registerToMem(4); // R = R*2 - D memToRegister(10); pushCommandOneArg("SHIFT", 2); pushCommandOneArg("SUB", 11); registerToMem(10); // if R >= 0 pushCommandOneArg("JNEG", codeVector.size() + 8); memToRegister(7); pushCommandOneArg("SHIFT", 2); pushCommand("INC"); registerToMem(7); memToRegister(4); pushCommand("DEC"); pushCommandOneArg("JUMP", stackJ1); memToRegister(10); pushCommandOneArg("ADD", 11); registerToMem(10); memToRegister(7); pushCommandOneArg("SHIFT", 2); registerToMem(7); memToRegister(4); pushCommand("DEC"); pushCommandOneArg("JUMP", stackJ1); //R = R / 2^(#bits of a) memToRegister(10); pushCommandOneArg("JZERO",codeVector.size() + 19); pushCommandOneArg("SHIFT", 12); registerToMem(10); memToRegister(8); pushCommandOneArg("JZERO",codeVector.size() + 9); // a > 0 memToRegister(13); pushCommandOneArg("JZERO", codeVector.size() + 4); // a < 0 zeroRegister(); // a < 0 b < 0 pushCommandOneArg("SUB", 10); pushCommandOneArg("JUMP",codeVector.size() + 10); memToRegister(14); // a < 0 b > 0 pushCommandOneArg("SUB", 10); pushCommandOneArg("JUMP",codeVector.size() + 7); memToRegister(13); // a > 0 b < 0 pushCommandOneArg("JZERO", codeVector.size() + 4); memToRegister(10); pushCommandOneArg("ADD", 14); pushCommandOneArg("JUMP",codeVector.size() + 2); memToRegister(10); // a > 0 b > 0 } argumentsTabIndex[0] = "null"; argumentsTabIndex[1] = "null"; expressionArguments[0] = "null"; expressionArguments[1] = "null"; } void multiply() { Identifier a = identifierMap.at(expressionArguments[0]); Identifier b = identifierMap.at(expressionArguments[1]); Identifier aI, bI; if (identifierMap.count(argumentsTabIndex[0]) > 0) aI = identifierMap.at(argumentsTabIndex[0]); if (identifierMap.count(argumentsTabIndex[1]) > 0) bI = identifierMap.at(argumentsTabIndex[1]); if (a.type == "NUM" && b.type == "NUM") { long long int val = stoll(a.name) * stoll(b.name); setRegister(to_string(val)); removeIdentifier(a.name); removeIdentifier(b.name); } else if (a.type == "NUM" && isPowerOf2(a.name)) { setRegister(to_string(isPowerOf2(a.name) - 1)); registerToMem(3); setToRegister(b, bI); if (stoll(a.name) < 0) { pushCommandOneArg("SHIFT", 3); pushCommandOneArg("SHIFT", 2); registerToMem(4); setToRegister(b, bI); pushCommandOneArg("SHIFT", 3); pushCommandOneArg("SUB", 4); } else if (stoll(a.name) > 0) { pushCommandOneArg("SHIFT", 3); } else { zeroRegister(); } removeIdentifier(a.name); } else if (b.type == "NUM" && isPowerOf2(b.name)) { setRegister(to_string(isPowerOf2(b.name) - 1)); registerToMem(3); setToRegister(a, aI); if (stoll(b.name) < 0) { pushCommandOneArg("SHIFT", 3); pushCommandOneArg("SHIFT", 2); registerToMem(4); setToRegister(a, aI); pushCommandOneArg("SHIFT", 3); pushCommandOneArg("SUB", 4); } else if (stoll(b.name) > 0) { pushCommandOneArg("SHIFT", 3); } else { zeroRegister(); } removeIdentifier(b.name); } else { zeroRegister(); registerToMem(7); pushCommand("DEC"); registerToMem(8); setToTempMem(a, aI, 5); setToTempMem(b, bI, 6); //if (b < 0) b = -b pushCommandOneArg("JPOS", codeVector.size() + 8); pushCommandOneArg("SHIFT", 2); registerToMem(3); memToRegister(6); pushCommandOneArg("SUB", 3); registerToMem(6); zeroRegister(); registerToMem(8); //if (a < 0) a = -a memToRegister(5); pushCommandOneArg("JPOS", codeVector.size() + 10); pushCommandOneArg("SHIFT", 2); registerToMem(3); memToRegister(5); pushCommandOneArg("SUB", 3); registerToMem(5); memToRegister(8); pushCommand("INC"); registerToMem(8); memToRegister(5); // if a > b swap(a,b) pushCommand("SUB 6"); pushCommandOneArg("JNEG", codeVector.size() + 8); pushCommandOneArg("JZERO", codeVector.size() + 7); memToRegister(6); registerToMem(3); memToRegister(5); registerToMem(6); memToRegister(3); registerToMem(5); memToRegister(5); // a * b int stackJ = codeVector.size(); pushCommandOneArg("JZERO", codeVector.size() + 16); pushCommandOneArg("SHIFT", 9); pushCommandOneArg("SHIFT", 2); pushCommandOneArg("SUB", 5); pushCommandOneArg("JNEG", codeVector.size() + 2); pushCommandOneArg("JUMP", codeVector.size() + 4); memToRegister(7); pushCommandOneArg("ADD", 6); registerToMem(7); memToRegister(6); pushCommandOneArg("SHIFT", 2); registerToMem(6); memToRegister(5); pushCommandOneArg("SHIFT", 9); registerToMem(5); pushCommandOneArg("JUMP", stackJ); //if(a.old * b.old < 0) c = -c memToRegister(8); pushCommandOneArg("JNEG", codeVector.size() + 8); pushCommandOneArg("JPOS", codeVector.size() + 7); memToRegister(7); pushCommandOneArg("SHIFT", 2); registerToMem(3); memToRegister(7); pushCommandOneArg("SUB", 3); pushCommandOneArg("JUMP", codeVector.size() + 2); memToRegister(7); } argumentsTabIndex[0] = "null"; argumentsTabIndex[1] = "null"; expressionArguments[0] = "null"; expressionArguments[1] = "null"; } void divide() { Identifier a = identifierMap.at(expressionArguments[0]); Identifier b = identifierMap.at(expressionArguments[1]); Identifier aI, bI; if (identifierMap.count(argumentsTabIndex[0]) > 0) aI = identifierMap.at(argumentsTabIndex[0]); if (identifierMap.count(argumentsTabIndex[1]) > 0) bI = identifierMap.at(argumentsTabIndex[1]); if (a.type == "NUM" && stoll(a.name) == 0) { zeroRegister(); } else if (b.type == "NUM" && stoll(b.name) == 0) { zeroRegister(); } else if (a.type == "NUM" && b.type == "NUM") { long long int val = stoll(a.name) / stoll(b.name); if(val >= 0 || (val < 0 && stoll(a.name)%stoll(b.name) == 0)) setRegister(to_string(val)); else setRegister(to_string(val - 1)); removeIdentifier(a.name); removeIdentifier(b.name); } else { zeroRegister(); registerToMem(7); registerToMem(4); pushCommand("DEC"); registerToMem(8); setToTempMem(a, aI, 5); setToTempMem(b, bI, 6); //if (b < 0) b = -b pushCommandOneArg("JNEG", codeVector.size() + 4); pushCommandOneArg("JPOS", codeVector.size() + 10); zeroRegister(); int divZeroEnd = codeVector.size(); pushCommand("JUMP"); pushCommandOneArg("SHIFT", 2); registerToMem(3); memToRegister(6); pushCommandOneArg("SUB", 3); registerToMem(6); zeroRegister(); registerToMem(8); //if (a < 0) a = -a memToRegister(5); pushCommandOneArg("JNEG", codeVector.size() + 4); pushCommandOneArg("JPOS", codeVector.size() + 11); zeroRegister(); int divZeroEnd2 = codeVector.size(); pushCommand("JUMP"); pushCommandOneArg("SHIFT", 2); registerToMem(3); memToRegister(5); pushCommandOneArg("SUB", 3); registerToMem(5); memToRegister(8); pushCommand("INC"); registerToMem(8); memToRegister(5); // if(|a| < |b|) pushCommandOneArg("SUB", 6); pushCommandOneArg("JPOS", codeVector.size() + 17); // |a| > |b| pushCommandOneArg("JZERO", codeVector.size() + 8); // |a| = |b| memToRegister(8); // |a| < |b| pushCommandOneArg("JPOS", codeVector.size() + 4); pushCommandOneArg("JNEG", codeVector.size() + 3); pushCommand("DEC"); pushCommandOneArg("JUMP", codeVector.size() + 2); zeroRegister(); pushCommandOneArg("JUMP", codeVector.size() + 66); memToRegister(8); // |a| = |b| pushCommandOneArg("JPOS", codeVector.size() + 4); pushCommandOneArg("JNEG", codeVector.size() + 3); pushCommand("DEC"); pushCommandOneArg("JUMP", codeVector.size() + 3); zeroRegister(); pushCommand("INC"); pushCommandOneArg("JUMP", codeVector.size() + 58); //R = a memToRegister(5); registerToMem(10); registerToMem(11); //compute n = #bits of a memToRegister(11); pushCommandOneArg("SHIFT", 9); pushCommandOneArg("JZERO", codeVector.size() + 6); registerToMem(11); memToRegister(4); pushCommand("INC"); registerToMem(4); pushCommandOneArg("JUMP", codeVector.size() - 7); //b = b << n memToRegister(4); pushCommand("INC"); registerToMem(4); memToRegister(6); pushCommandOneArg("SHIFT", 4); registerToMem(11); memToRegister(4); pushCommand("DEC"); // for n-1 .. 0 int stackJ1 = codeVector.size(); pushCommandOneArg("JNEG", codeVector.size() + 23); registerToMem(4); // R = R*2 - D memToRegister(10); pushCommandOneArg("SHIFT", 2); pushCommandOneArg("SUB", 11); registerToMem(10); // if R >= 0 pushCommandOneArg("JNEG", codeVector.size() + 8); memToRegister(7); pushCommandOneArg("SHIFT", 2); pushCommand("INC"); registerToMem(7); memToRegister(4); pushCommand("DEC"); pushCommandOneArg("JUMP", stackJ1); memToRegister(10); pushCommandOneArg("ADD", 11); registerToMem(10); memToRegister(7); pushCommandOneArg("SHIFT", 2); registerToMem(7); memToRegister(4); pushCommand("DEC"); pushCommandOneArg("JUMP", stackJ1); //if(a.old * b.old < 0) c = -c memToRegister(8); pushCommandOneArg("JNEG", codeVector.size() + 13); // a > 0 and b > 0 pushCommandOneArg("JPOS", codeVector.size() + 12); // a < 0 and b < 0 memToRegister(7); pushCommandOneArg("SHIFT", 2); registerToMem(3); memToRegister(7); pushCommandOneArg("SUB", 3); registerToMem(7); memToRegister(10); pushCommandOneArg("JZERO", codeVector.size() + 4); memToRegister(7); pushCommand("DEC"); pushCommandOneArg("JUMP", codeVector.size() + 2); memToRegister(7); addInt(divZeroEnd, codeVector.size()); addInt(divZeroEnd2, codeVector.size()); } argumentsTabIndex[0] = "null"; argumentsTabIndex[1] = "null"; expressionArguments[0] = "null"; expressionArguments[1] = "null"; } void subtractIdentifires(string a, string b) { expressionArguments[0] = a; expressionArguments[1] = b; subtract(); } void subtract() { Identifier a = identifierMap.at(expressionArguments[0]); Identifier b = identifierMap.at(expressionArguments[1]); expressionArguments[0] = "null"; expressionArguments[1] = "null"; if (a.type != "ARR" && b.type != "ARR") { if (a.type == "NUM" && b.type == "NUM") { long long int val = stoll(a.name) - stoll(b.name); setRegister(to_string(val)); removeIdentifier(a.name); removeIdentifier(b.name); } else if (a.type == "NUM" && b.type == "IDE") { setRegister(a.name); pushCommandOneArg("SUB", b.mem); removeIdentifier(a.name); } else if (a.type == "IDE" && b.type == "NUM") { setRegister(b.name); registerToMem(3); memToRegister(a.mem); pushCommandOneArg("SUB", 3); removeIdentifier(b.name); } else if (a.type == "IDE" && b.type == "IDE") { if (a.name == b.name) { zeroRegister(); } else { memToRegister(a.mem); pushCommandOneArg("SUB", b.mem); } } } else { Identifier aIndex, bIndex; if (identifierMap.count(argumentsTabIndex[0]) > 0) aIndex = identifierMap.at(argumentsTabIndex[0]); if (identifierMap.count(argumentsTabIndex[1]) > 0) bIndex = identifierMap.at(argumentsTabIndex[1]); argumentsTabIndex[0] = "null"; argumentsTabIndex[1] = "null"; if (a.type == "NUM" && b.type == "ARR") { if (bIndex.type == "NUM") { long long int addr = b.mem + (stoll(bIndex.name) - b.begin); setRegister(a.name); pushCommandOneArg("SUB", addr); removeIdentifier(a.name); removeIdentifier(bIndex.name); } else if (bIndex.type == "IDE") { setRegister(to_string(b.mem - b.begin)); pushCommandOneArg("ADD", bIndex.mem); pushCommandOneArg("LOADI", 0); registerToMem(3); setRegister(a.name); pushCommandOneArg("SUB", 3); removeIdentifier(a.name); } } else if (a.type == "ARR" && b.type == "NUM") { if (aIndex.type == "NUM") { long long int addr = a.mem + (stoll(aIndex.name) - a.begin); setRegister(b.name); registerToMem(3); memToRegister(addr); pushCommandOneArg("SUB", 3); removeIdentifier(b.name); removeIdentifier(aIndex.name); } else if (aIndex.type == "IDE") { setRegister(b.name); registerToMem(3); setRegister(to_string((a.mem - a.begin))); pushCommandOneArg("ADD", aIndex.mem); pushCommandOneArg("LOADI", 0); pushCommandOneArg("SUB", 3); removeIdentifier(b.name); } } else if (a.type == "IDE" && b.type == "ARR") { if (bIndex.type == "NUM") { long long int addr = b.mem + (stoll(bIndex.name) - b.begin); memToRegister(a.mem); pushCommandOneArg("SUB", addr); removeIdentifier(bIndex.name); } else if (bIndex.type == "IDE") { setRegister(to_string(b.mem - b.begin)); pushCommandOneArg("ADD", bIndex.mem); pushCommandOneArg("LOADI", 0); registerToMem(3); memToRegister(a.mem); pushCommandOneArg("SUB", 3); } } else if (a.type == "ARR" && b.type == "IDE") { if (aIndex.type == "NUM") { long long int addr = a.mem + (stoll(aIndex.name) - a.begin); memToRegister(addr); pushCommandOneArg("SUB", b.mem); removeIdentifier(aIndex.name); } else if (aIndex.type == "IDE") { setRegister(to_string(a.mem - a.begin)); pushCommandOneArg("ADD", aIndex.mem); pushCommandOneArg("LOADI", 0); pushCommandOneArg("SUB", b.mem); } } else if (a.type == "ARR" && b.type == "ARR") { if (aIndex.type == "NUM" && bIndex.type == "NUM") { long long int addrA = a.mem + (stoll(aIndex.name) - a.begin); long long int addrB = b.mem + (stoll(bIndex.name) - b.begin); if (a.name == b.name && addrA == addrB) zeroRegister(); else { memToRegister(addrA); pushCommandOneArg("SUB", addrB); } removeIdentifier(aIndex.name); removeIdentifier(bIndex.name); } else if (aIndex.type == "NUM" && bIndex.type == "IDE") { long long int addrA = a.mem + (stoll(aIndex.name) - a.begin); setRegister(to_string((b.mem - b.begin))); pushCommandOneArg("ADD", bIndex.mem); pushCommandOneArg("LOADI", 0); registerToMem(3); memToRegister(addrA); pushCommandOneArg("SUB", 3); removeIdentifier(aIndex.name); } else if (aIndex.type == "IDE" && bIndex.type == "NUM") { long long int addrB = b.mem + (stoll(bIndex.name) - b.begin); setRegister(to_string((a.mem - a.begin))); pushCommandOneArg("ADD", aIndex.mem); pushCommandOneArg("LOADI", 0); pushCommandOneArg("SUB", addrB); removeIdentifier(bIndex.name); } else if (aIndex.type == "IDE" && bIndex.type == "IDE") { if (a.name == b.name && aIndex.name == bIndex.name) zeroRegister(); else { setRegister(to_string((b.mem - b.begin))); pushCommandOneArg("ADD", bIndex.mem); pushCommandOneArg("LOADI", 0); registerToMem(3); setRegister(to_string((a.mem - a.begin))); pushCommandOneArg("ADD", aIndex.mem); pushCommandOneArg("LOADI", 0); pushCommandOneArg("SUB", 3); } } } } } void add() { Identifier a = identifierMap.at(expressionArguments[0]); Identifier b = identifierMap.at(expressionArguments[1]); expressionArguments[0] = "null"; expressionArguments[1] = "null"; if (a.type != "ARR" && b.type != "ARR") { if (a.type == "NUM" && b.type == "NUM") { long long int val = stoll(a.name) + stoll(b.name); setRegister(to_string(val)); removeIdentifier(a.name); removeIdentifier(b.name); } else if (a.type == "NUM" && b.type == "IDE") { setRegister(a.name); pushCommandOneArg("ADD", b.mem); removeIdentifier(a.name); } else if (a.type == "IDE" && b.type == "NUM") { setRegister(b.name); pushCommandOneArg("ADD", a.mem); removeIdentifier(b.name); } else if (a.type == "IDE" && b.type == "IDE") { if (a.name == b.name) { memToRegister(a.mem); pushCommand("SHIFT 2"); } else { memToRegister(a.mem); pushCommandOneArg("ADD", b.mem); } } } else { Identifier aIndex, bIndex; if (identifierMap.count(argumentsTabIndex[0]) > 0) aIndex = identifierMap.at(argumentsTabIndex[0]); if (identifierMap.count(argumentsTabIndex[1]) > 0) bIndex = identifierMap.at(argumentsTabIndex[1]); argumentsTabIndex[0] = "null"; argumentsTabIndex[1] = "null"; if (a.type == "NUM" && b.type == "ARR") { if (bIndex.type == "NUM") { long long int addr = b.mem + (stoll(bIndex.name) - b.begin); setRegister(a.name); pushCommandOneArg("ADD", addr); removeIdentifier(a.name); removeIdentifier(bIndex.name); } else if (bIndex.type == "IDE") { setRegister(to_string(b.mem - b.begin)); pushCommandOneArg("ADD", bIndex.mem); pushCommandOneArg("LOADI", 0); registerToMem(3); setRegister(a.name); pushCommandOneArg("ADD", 3); removeIdentifier(a.name); } } else if (a.type == "ARR" && b.type == "NUM") { if (aIndex.type == "NUM") { long long int addr = a.mem + (stoll(aIndex.name) - a.begin); setRegister(b.name); pushCommandOneArg("ADD", addr); removeIdentifier(b.name); removeIdentifier(aIndex.name); } else if (aIndex.type == "IDE") { setRegister(to_string((a.mem - a.begin))); pushCommandOneArg("ADD", aIndex.mem); pushCommandOneArg("LOADI", 0); registerToMem(3); setRegister(b.name); pushCommandOneArg("ADD", 3); removeIdentifier(b.name); } } else if (a.type == "IDE" && b.type == "ARR") { if (bIndex.type == "NUM") { long long int addr = b.mem + (stoll(bIndex.name) - b.begin); memToRegister(a.mem); pushCommandOneArg("ADD", addr); removeIdentifier(bIndex.name); } else if (bIndex.type == "IDE") { setRegister(to_string(b.mem - b.begin)); pushCommandOneArg("ADD", bIndex.mem); pushCommandOneArg("LOADI", 0); pushCommandOneArg("ADD", a.mem); } } else if (a.type == "ARR" && b.type == "IDE") { if (aIndex.type == "NUM") { long long int addr = a.mem + (stoll(aIndex.name) - a.begin); memToRegister(addr); pushCommandOneArg("ADD", b.mem); removeIdentifier(aIndex.name); } else if (aIndex.type == "IDE") { setRegister(to_string(a.mem - a.begin)); pushCommandOneArg("ADD", aIndex.mem); pushCommandOneArg("LOADI", 0); pushCommandOneArg("ADD", b.mem); } } else if (a.type == "ARR" && b.type == "ARR") { if (aIndex.type == "NUM" && bIndex.type == "NUM") { long long int addrA = a.mem + (stoll(aIndex.name) - a.begin); long long int addrB = b.mem + (stoll(bIndex.name) - b.begin); memToRegister(addrA); if (a.name == b.name && addrA == addrB) pushCommand("SHIFT 2"); else pushCommandOneArg("ADD", addrB); removeIdentifier(aIndex.name); removeIdentifier(bIndex.name); } else if (aIndex.type == "NUM" && bIndex.type == "IDE") { long long int addrA = a.mem + (stoll(aIndex.name) - a.begin); setRegister(to_string((b.mem - b.begin))); pushCommandOneArg("ADD", bIndex.mem); pushCommandOneArg("LOADI", 0); pushCommandOneArg("ADD", addrA); removeIdentifier(aIndex.name); } else if (aIndex.type == "IDE" && bIndex.type == "NUM") { long long int addrB = b.mem + (stoll(bIndex.name) - b.begin); setRegister(to_string((a.mem - a.begin))); pushCommandOneArg("ADD", aIndex.mem); pushCommandOneArg("LOADI", 0); pushCommandOneArg("ADD", addrB); removeIdentifier(bIndex.name); } else if (aIndex.type == "IDE" && bIndex.type == "IDE") { if (a.name == b.name && aIndex.name == bIndex.name) { setRegister(to_string((a.mem - a.begin))); pushCommandOneArg("ADD", aIndex.mem); pushCommandOneArg("LOADI", 0); pushCommand("SHIFT 2"); } else { setRegister(to_string((a.mem - a.begin))); pushCommandOneArg("ADD", aIndex.mem); pushCommandOneArg("LOADI", 0); registerToMem(3); setRegister(to_string((b.mem - b.begin))); pushCommandOneArg("ADD", bIndex.mem); pushCommandOneArg("LOADI", 0); pushCommandOneArg("ADD", 3); } } } } }
#include <cstdlib> #include <iostream> #include <vector> using namespace std; main() { vector <int> a; a.push_back(8); a.push_back(7); a.push_back(2); a.push_back(5); a.push_back(3); a.insert(a.begin()+3,10); for(int i = 0; i < a.size(); i++) cout << a[i] << " "; cout<<"El tamano anterior era: "<<a.size()<<endl; a.resize(4); cout<<"El nuevo tamano es: "<<a.size()<<endl; }
#ifndef __SYNAPSE_H__ #define __SYNAPSE_H__ #include "../../qgraph/src/Vertex.h" namespace neurnet { struct Synapse { const graph::Vertex* v; double weight; bool operator<(const Synapse& s) const { return (v < s.v); }; bool operator==(const Synapse& s) const { return (v == s.v); }; }; } #endif // __SYNAPSE_H__
#include "Application.h" #include "components/MeshComponent.h" #include "components/graphics/Camera.h" #include "components/graphics/CameraController.h" #include "components/PhysicsComponent.h" #include "components/TransformComponent.h" //Todo: this could be cleaned up a little bit. using namespace Game; int main() { Application app; auto camera = GameCore::get().addEntity(); camera->addComponent(new Camera()); camera->addComponent(new CameraController()); //Entity 1: auto sampleEntity = GameCore::get().addEntity(); sampleEntity->addComponent(new MeshComponent()); sampleEntity->getComponent<TransformComponent>().setTransform(Transform(glm::vec3(-5,-5,-20))); sampleEntity->getComponent<MeshComponent>().loadMesh("stairs.obj"); sampleEntity->addComponent(new PhysicsComponent()); sampleEntity->getComponent<PhysicsComponent>().setMass(0); sampleEntity->getComponent<PhysicsComponent>().setShape(CollisionShapes::STAIRS); //Entity2 auto sampleEntity2 = GameCore::get().addEntity(); sampleEntity2->addComponent(new MeshComponent()); sampleEntity2->getComponent<TransformComponent>().setTransform(Transform(glm::vec3(0,10,-20))); sampleEntity2->getComponent<MeshComponent>().loadMesh("suzanne.obj"); sampleEntity2->addComponent(new PhysicsComponent()); sampleEntity2->getComponent<PhysicsComponent>().setMass(1); sampleEntity2->getComponent<PhysicsComponent>().setShape(CollisionShapes::RAGDOLL); app.start(); }
/* * @Description: front end 任务管理, 放在类里使代码更清晰 * @Author: Ren Qian * @Date: 2020-02-10 08:31:22 */ #ifndef LIDAR_LOCALIZATION_MAPPING_FRONT_END_FRONT_END_FLOW_HPP_ #define LIDAR_LOCALIZATION_MAPPING_FRONT_END_FRONT_END_FLOW_HPP_ #include <ros/ros.h> #include "lidar_localization/subscriber/cloud_subscriber.hpp" #include "lidar_localization/publisher/odometry_publisher.hpp" #include "lidar_localization/mapping/front_end/front_end.hpp" namespace lidar_localization { class FrontEndFlow { public: FrontEndFlow(ros::NodeHandle& nh, std::string cloud_topic, std::string odom_topic); bool Run(); private: bool ReadData(); bool HasData(); bool ValidData(); bool UpdateLaserOdometry(); bool PublishData(); private: std::shared_ptr<CloudSubscriber> cloud_sub_ptr_; std::shared_ptr<OdometryPublisher> laser_odom_pub_ptr_; std::shared_ptr<FrontEnd> front_end_ptr_; std::deque<CloudData> cloud_data_buff_; CloudData current_cloud_data_; Eigen::Matrix4f laser_odometry_ = Eigen::Matrix4f::Identity(); }; } #endif
#pragma once #include <random> #include <string> #include <map> #include "Tetramino.h" class RandomTetraminoGenerator { std::map<int, Tetramino *> tetraminoes; public: static RandomTetraminoGenerator& Instance(); void RegisterTetramino(const int & id, Tetramino * tetramino); Tetramino * Generate() { int randomId = rand() % tetraminoes.size(); return tetraminoes[randomId]; } };
#include "dbmanager.h" #include <QSqlQuery> #include <QSqlError> #include <QSqlRecord> #include <QDebug> #include <QCoreApplication> DbManager::DbManager(const QString &file) { m_db = QSqlDatabase::addDatabase("QSQLITE", "ball_state_db"); QString path = QCoreApplication::applicationDirPath() + "/" + file; // qDebug() << path; m_db.setDatabaseName(path); if (!m_db.open()) { qDebug() << "Error: connection with database fail"; } else { // qDebug() << "Database: connection ok"; } } DbManager::~DbManager() { if (m_db.isOpen()) { m_db.close(); } QString dbName = m_db.connectionName(); m_db = QSqlDatabase(); m_db.close(); QSqlDatabase::removeDatabase(dbName); } bool DbManager::isOpen() const { return m_db.isOpen(); } bool DbManager::addBallState(const BallState& state) { bool success = false; QSqlQuery query(m_db); query.prepare("INSERT INTO ball_state (x, y, forwardDirection) VALUES (:x, :y, :forwardDirection)"); query.bindValue(":x", state.x); query.bindValue(":y", state.y); query.bindValue(":forwardDirection", state.forwardDirection); if(query.exec()) { success = true; } else { qDebug() << "add ball state to db failed: " << query.lastError(); } return success; } bool DbManager::getLastState(BallState &state){ bool success = false; QSqlQuery query("SELECT * FROM ball_state ORDER BY ids DESC LIMIT 1", m_db); if(query.exec()) { success = true; int idX = query.record().indexOf("x"); int idY = query.record().indexOf("y"); int idD = query.record().indexOf("forwardDirection"); query.first(); state.x = query.value(idX).toInt(); state.y = query.value(idY).toInt(); state.forwardDirection = query.value(idD).toBool(); } else { qDebug() << "get ball state from db failed: " << query.lastError(); } return success; }
/* * File: main.cpp * Author: Daniel * * Created on 21 de agosto de 2014, 07:41 AM */ #include <cstdlib> #include <iostream> using namespace std; /* * */ int sumarVectores(int* arreglo, int pos); int main(int argc, char** argv) { int arr[3] = {3,6,9}; cout<<sumarVectores(arr, 2); return 0; } int sumarVectores(int *arreglo, int pos){ if(pos == 0){ return arreglo[0]; } else{ if(pos == 0){ return arreglo[0]; } else{ return (arreglo[pos]+sumarVectores(arreglo, pos-1)); } } }
#include <bits/stdc++.h> using namespace std; const int maxn = 110; int n, m, cnt; char a[maxn][maxn]; int ans[maxn][maxn]; int main() { cin >> n >> m; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) scanf("%c", &a[i][j]); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) if (a[i][j] == '*') cout << '*'; else { } puts(""); } return 0; }
// Даны два списка чисел, которые могут содержать до 100000 чисел каждый. // Выведите все числа, которые входят как в первый, так и во второй список в порядке возрастания. // Входные данные // Вводится число N - количество элементов первого списка, а затем N чисел первого списка. // Затем вводится число M - количество элементов второго списка, а затем M чисел второго списка. #include <iostream> #include <set> using namespace std; int main() { set<int> s; multiset<int> ms; int n, x; cin >> n; for (int i = 0; i < n; i++) { cin >> x; s.insert(x); } cin >> n; for (int i = 0; i < n; i++) { cin >> x; if (s.find(x) != s.end()) ms.insert(x); } for (auto elm : ms) { cout << elm << " "; } return 0; }
using namespace std; int * construct_array(int); int error_handle(); void print_array(int *, int); int * copy_array(int *, int); void merge(int * arr, int left_index, int middle, int right_index); void merge_sort(int * arr, int left_index, int right_index);
#include<iostream> #include<map> #include<algorithm> #include<set> #include<vector> using namespace std; struct con{ int onof[9]; int ques; int time[9]; }; typedef struct con Con; Con temp={{},9,{}}; vector<int>details(3); int main() { int n,a,b,c,s=0,k; char d; string input,tmp; cin>>n; cin.ignore();cin.ignore(); while(n--) { map<int,Con>m; map<int,Con>::iterator it; while(true) { input.clear(); getline(cin,input); if(input.size()==0)break; tmp.clear();k=0; while(input[k]!=' '){tmp+=input[k];k++;} a=stoi(tmp);k++; tmp.clear(); while(input[k]!=' '){tmp+=input[k];k++;} b=stoi(tmp);k++; tmp.clear(); while(input[k]!=' '){tmp+=input[k];k++;} c=stoi(tmp);k++; d=input[input.size()-1]; it=m.find(a); if(it==m.end()){m[a]=temp;} if(m[a].onof[b-1]!=1) { if(d=='I'){m[a].time[b-1]+=20;} if(d=='C'){m[a].time[b-1]+=c;m[a].ques--;m[a].onof[b-1]=1;} } } if(s)cout<<endl; int Time; set<vector<int>> x; set<vector<int>>::iterator it2; for(it=m.begin();it!=m.end();it++) { Time=0; for(int j=0;j<9;j++) { if((*it).second.onof[j]==1) { Time+=(*it).second.time[j]; } } details[0]=(*it).second.ques; details[1]=Time; details[2]=(*it).first; x.insert(details); } for(it2=x.begin();it2!=x.end();it2++) { cout<<(*it2)[2]<<" "<<9-(*it2)[0]<<" "<<(*it2)[1]<<endl; } s=1; } return 0; }
/* Просто перечисление всех реализованных классов узлов дерева промежуточного представления */ #pragma once namespace IRTree { // Вспомогательные классы class CExpList; class CStmList; // Подклассы IRTree::IExp class CONST; class NAME; class TEMP; class BINOP; class MEM; class CALL; class ESEQ; // Подклассы IRTree::IStm class MOVE; class EXP; class JUMP; class CJUMP; class SEQ; class LABEL; }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "sparse.h" template<typename Scalar> void initSPD(double density, Matrix<Scalar,Dynamic,Dynamic>& refMat, SparseMatrix<Scalar>& sparseMat) { Matrix<Scalar,Dynamic,Dynamic> aux(refMat.rows(),refMat.cols()); initSparse(density,refMat,sparseMat); refMat = refMat * refMat.adjoint(); for (int k=0; k<2; ++k) { initSparse(density,aux,sparseMat,ForceNonZeroDiag); refMat += aux * aux.adjoint(); } sparseMat.setZero(); for (int j=0 ; j<sparseMat.cols(); ++j) for (int i=j ; i<sparseMat.rows(); ++i) if (refMat(i,j)!=Scalar(0)) sparseMat.insert(i,j) = refMat(i,j); sparseMat.finalize(); } template<typename Scalar> void sparse_solvers(int rows, int cols) { double density = std::max(8./(rows*cols), 0.01); typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix; typedef Matrix<Scalar,Dynamic,1> DenseVector; // Scalar eps = 1e-6; DenseVector vec1 = DenseVector::Random(rows); std::vector<Vector2i> zeroCoords; std::vector<Vector2i> nonzeroCoords; // test triangular solver { DenseVector vec2 = vec1, vec3 = vec1; SparseMatrix<Scalar> m2(rows, cols); DenseMatrix refMat2 = DenseMatrix::Zero(rows, cols); // lower - dense initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template triangularView<Lower>().solve(vec2), m2.template triangularView<Lower>().solve(vec3)); // upper - dense initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template triangularView<Upper>().solve(vec2), m2.template triangularView<Upper>().solve(vec3)); // lower - transpose initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.transpose().template triangularView<Upper>().solve(vec2), m2.transpose().template triangularView<Upper>().solve(vec3)); // upper - transpose initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.transpose().template triangularView<Lower>().solve(vec2), m2.transpose().template triangularView<Lower>().solve(vec3)); SparseMatrix<Scalar> matB(rows, rows); DenseMatrix refMatB = DenseMatrix::Zero(rows, rows); // lower - sparse initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular); initSparse<Scalar>(density, refMatB, matB); refMat2.template triangularView<Lower>().solveInPlace(refMatB); m2.template triangularView<Lower>().solveInPlace(matB); VERIFY_IS_APPROX(matB.toDense(), refMatB); // upper - sparse initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular); initSparse<Scalar>(density, refMatB, matB); refMat2.template triangularView<Upper>().solveInPlace(refMatB); m2.template triangularView<Upper>().solveInPlace(matB); VERIFY_IS_APPROX(matB, refMatB); // test deprecated API initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template triangularView<Lower>().solve(vec2), m2.template triangularView<Lower>().solve(vec3)); } } void test_sparse_solvers() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1(sparse_solvers<double>(8, 8) ); int s = ei_random<int>(1,300); CALL_SUBTEST_2(sparse_solvers<std::complex<double> >(s,s) ); CALL_SUBTEST_1(sparse_solvers<double>(s,s) ); } }
#include <iostream> #include <math.h> using namespace std; int main() { int res = 13; double number = 600851475143; // cout<<res<<"\n"; cout<<"Number is "<<number<<". Factors as follows: \n"; //Find factor for (double i = 2; i <= number/71; i++){ if(fmod(number,i)==0){ //number%i == 0){ cout<<"Factor of "<<number<<" is "<<i; //Is factor a prime? for(double j = 2; j < i/2; j++){ if(fmod(i,j)==0){ //i%j==0){ cout<<" - Current Factor "<<i<<" is not a prime";// divisible by "<<j<<"\n"; break; } } cout<<"\n"; } } return 0; }
///////////////////////////////////////////////////////////////////////////// // render.cpp // rendering system implementation // $Id$ // #include "precompiled.h" #include "render/render.h" #include "render/scenegraph.h" namespace render { } using namespace render; SceneGraph::SceneGraph() { tree = new SceneNode(NULL); } SceneGraph::~SceneGraph() { delete tree; } MESHHANDLE SceneGraph::addStaticMesh(Mesh& mesh) { meshes.push_back(&mesh); tree->addStaticMesh(mesh); return (MESHHANDLE)meshes.size(); } MESHHANDLE SceneGraph::addDynamicMesh(Mesh& mesh) { return (MESHHANDLE)meshes.size(); } void SceneGraph::acquire() { tree->acquire(); } void SceneGraph::release() { } void SceneGraph::render() { if (render::use_scenegraph) tree->render(); } void SceneGraph::finalizeStatic() { tree->subdivide(); }
/*============================================================================= /*----------------------------------------------------------------------------- /* [JSONManager.h] JSON管理クラス /* Author:Kousuke,Ohno. /*----------------------------------------------------------------------------- /* 説明:JSON管理クラス =============================================================================*/ #ifndef JSON_MANAGER_H_ #define JSON_MANAGER_H_ /*--- インクルードファイル ---*/ #include "StdAfx.h" /*--- 構造体定義 ---*/ /*--- クラスの前方宣言 ---*/ /*------------------------------------- /* JSON管理クラス -------------------------------------*/ class JSONManager { private: enum class LanguageSetting { None = -1 , Jp , En , Max }; private: JSONManager(void); public: ~JSONManager(void); //ロードとセーブ関係 static bool LoadJSON(const std::string& inFileName, rapidjson::Document& outDoc); static bool LoadData(const std::string& inFileName); static void SaveData(const std::string& inFileName); //プロパティ関係 static void LoadProperties(const rapidjson::Value& inObject); static void SaveProperties(rapidjson::Document::AllocatorType& alloc ,rapidjson::Value& inObject); private: //解析エラーのメッセージ static const char* GetParseErrorMsg(rapidjson::ParseErrorCode inParseErrorCode, const LanguageSetting inSelectLanguage); static const char* GetParseError_Jp(rapidjson::ParseErrorCode inParseErrorCode); }; #endif //JSON_MANAGER_H_ /*============================================================================= /* End of File =============================================================================*/
#include <iostream> #include <vector> #include <map> #include <cmath> #include <queue> #include <algorithm> #include <iomanip> #include <set> using namespace std; /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ #define int long long #define ld long double #define F first #define S second #define P pair <int,int> #define vi vector <int> #define vs vector <string> #define vb vector <bool> #define all(x) x.begin(),x.end() #define REP(i,a,b) for(int i=(int)a;i<=(int)b;i++) #define REV(i,a,b) for(int i=(int)a;i>=(int)b;i--) #define sp(x,y) fixed<<setprecision(y)<<x #define pb push_back #define mod (int)1e9+7 #define endl '\n' /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ const int N = 1e2 + 5; char Graph[N][N]; int dis[N][N]; int n, m; void bfs(int sx, int sy) { queue <P> q; q.push({sx, sy}); dis[sx][sy] = 0; while (!q.empty()) { int cur_x = q.front().F; int cur_y = q.front().S; q.pop(); int u = cur_x; int v = cur_y; while (v <= m && Graph[cur_x][v] != '*') { if (dis[cur_x][v] > dis[cur_x][cur_y] + 1) { dis[cur_x][v] = dis[cur_x][cur_y] + 1; q.push({cur_x, v}); } v++; } v = cur_y; while (v >= 1 && Graph[cur_x][v] != '*') { if (dis[cur_x][v] > dis[cur_x][cur_y] + 1) { dis[cur_x][v] = dis[cur_x][cur_y] + 1; q.push({cur_x, v}); } v--; } while (u <= n && Graph[u][cur_y] != '*') { if (dis[u][cur_y] > dis[cur_x][cur_y] + 1) { dis[u][cur_y] = dis[cur_x][cur_y] + 1; q.push({u, cur_y}); } u++; } u = cur_x; while (u >= 1 && Graph[u][cur_y] != '*') { if (dis[u][cur_y] > dis[cur_x][cur_y] + 1) { dis[u][cur_y] = dis[cur_x][cur_y] + 1; q.push({u, cur_y}); } u--; } } } void solve() { REP(i, 0, N) { REP(j, 0, N) { dis[i][j] = 101; } } cin >> m >> n; vector <P> se; REP(i, 1, n) { REP(j, 1, m) { cin >> Graph[i][j]; if (Graph[i][j] == 'C') se.pb({i, j}); } } int x1 = se[0].F, y1 = se[0].S; int x2 = se[1].F, y2 = se[1].S; //cout << x1 << " " << y1 << endl; //cout << x2 << " " << y2 << endl; bfs(x1, y1); cout << dis[x2][y2] - 1 << endl; return ; } int32_t main() { /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ ios_base:: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ //int t;cin>>t;while(t--) solve(); return 0; }
#ifndef _GetAllUserStatus_H_ #define _GetAllUserStatus_H_ #include "BaseProcess.h" class GetAllUserStatus : public BaseProcess { public: GetAllUserStatus() {}; virtual ~GetAllUserStatus() {}; virtual int doRequest(CDLSocketHandler* CDLSocketHandler, InputPacket* inputPacket, Context* pt); virtual int doResponse(CDLSocketHandler* CDLSocketHandler, InputPacket* inputPacket, Context* pt); private: int sendErrorMsg(CDLSocketHandler* CDLSocketHandler, short errcode, char* errmsg); }; #endif
/************************************************************************************** * File Name : Camera.cpp * Project Name : Keyboard Warriors * Primary Author : JeongHak Kim * Secondary Author : * Copyright Information : * "All content 2019 DigiPen (USA) Corporation, all rights reserved." **************************************************************************************/ #include "Camera.hpp" #include "Transform.hpp" void Camera::ResetUp(vec2<float> camera_up) noexcept { up.x = camera_up.x; up.y = camera_up.y; right = { up.y, -up.x }; } void Camera::MoveUp(float distance) noexcept { center += normalize(up) * distance; } void Camera::MoveRight(float distance) noexcept { center += normalize(right) * distance; } void Camera::Rotate(float angle_radians) noexcept { up = rotate_by(angle_radians, up); right = rotate_by(angle_radians, right); } mat3<float> Camera::CameraToWorld() const noexcept { //return build_translation(center.x, center.y) * transpose(mat3<float>{ // right.x, up.x, 0.f, // right.y, up.y, 0.f, // 0.f, 0.f, 1.f }); mat3<float> inverseTransformMatrix = { up.y, -right.y, (right.y * dot_product(-up, center) - dot_product(-right, center) * up.y), -up.x, right.x, (dot_product(-right, center) * up.x - right.x * dot_product(-up, center)), 0.0f, 0.0f, 1.0f }; return transpose(inverseTransformMatrix); } mat3<float> Camera::WorldToCamera() const noexcept { //return transpose(mat3<float>{ // right.x, right.y, 0.f, // up.x, up.y, 0.f, // 0.f, 0.f, 1.f }) * build_translation(-center.x, -center.y); mat3<float> transformMatrix = { right.x, up.x, 0.0f, right.y, up.y, 0.0f, dot_product(right, center), dot_product(up, center),1.0f }; return transformMatrix; }
#include <QPainter> #include <QApplication> #include "splashscreen.h" #include "clientversion.h" #include "util.h" SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; // define text to place QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QChar(0xA9) + QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers")); QString testnetAddText = QString(tr("[testnet]")); // define text to place as single text object QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if (GetBoolArg("-testnet")) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(100, 100, 100)); // check font size and drawing with pixPaint.setFont(QFont(font, 33 * fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if (titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 33 * fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(newPixmap.width() - titleTextWidth - paddingRight, paddingTop, titleText); pixPaint.setFont(QFont(font, 15 * fontFactor)); // if the version string is to long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if (versionTextWidth > titleTextWidth + paddingRight - 10) { pixPaint.setFont(QFont(font, 10 * fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(newPixmap.width() - titleTextWidth - paddingRight + 2, paddingTop + titleVersionVSpace, versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10 * fontFactor)); pixPaint.drawText(newPixmap.width() - titleTextWidth - paddingRight, paddingTop + titleCopyrightVSpace, copyrightText); // draw testnet string if -testnet is on if (QApplication::applicationName().contains(QString("-testnet"))) { // draw copyright stuff QFont boldFont = QFont(font, 10 * fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int testnetAddTextWidth = fm.width(testnetAddText); pixPaint.drawText(newPixmap.width() - testnetAddTextWidth - 10, 15, testnetAddText); } pixPaint.end(); this->setPixmap(newPixmap); }
//: C08:ConstInitialization.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 // Inicjalizacja stalych w klasach #include <iostream> using namespace std; class Fred { const int size; public: Fred(int sz); void print(); }; Fred::Fred(int sz) : size(sz) {} void Fred::print() { cout << size << endl; } int main() { Fred a(1), b(2), c(3); a.print(), b.print(), c.print(); } ///:~
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- // // Copyright (C) 1995-2008 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // #ifndef UNIX_OPAUTOUPDATE_H #define UNIX_OPAUTOUPDATE_H #ifdef AUTO_UPDATE_SUPPORT #include "adjunct/autoupdate/pi/opautoupdatepi.h" class UnixOpAutoUpdate : public OpAutoUpdatePI { public: ~UnixOpAutoUpdate() {} static OpAutoUpdatePI* Create(); /* * Get OS name * * Name of the operating system as will be passed to the auto update * system. It should be of the form as show on the download page * i.e. http://www.opera.com/download/index.dml?custom=yes * * @param os (in/out) Name of the OS * * Example of values: FreeBSD, Linux, MacOS, Windows * * @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR. */ OP_STATUS GetOSName(OpString& os); /* * Get OS version * * Version of the operating system as will be passed to the auto update system * * @param version (in/out) Name of OS version * * Example of values: 10.2, 10.3, 7, 95 * * @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR. */ OP_STATUS GetOSVersion(OpString& version); /* * Get architecture * * @param arch (in/out) Name of architecture * * Example of values: i386, ppc, sparc, x86-64 * * @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR. */ OP_STATUS GetArchitecture(OpString& arch); /* * Get package type (*nix only) * * @param package (in/out) Name of *nix package * * Example of values: deb, rpm, tar.gz, tar.bz2, tar.Z, pkg.gz, pkg.bz2, pkg.Z * * @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR. * * Platforms other than *nix should set the string to empty and return OpStatus::OK. */ OP_STATUS GetPackageType(OpString& package); /* * Get gcc version (*nix only) * * @param gcc (in/out) GCC version * * Example of values: gcc295, gcc3, gcc4 * * @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR. * * Platforms other than *nix should set the string to empty and return OpStatus::OK. */ OP_STATUS GetGccVersion(OpString& gcc); /* * Get QT version (*nix only) * * @param qt (in/out) QT version * * Example of values: qt3-shared, qt3-static, qt4-unbundled, qt4-bundled * * @return OP_STATUS Returns OpStatus::OK on success, otherwise OpStatus::ERR. * * Platforms other than *nix should set the string to empty and return OpStatus::OK. */ OP_STATUS GetQTVersion(OpString& qt); OP_STATUS ExtractInstallationFiles(uni_char *package) { return OpStatus::OK; } BOOL ExtractionInBackground() { return FALSE; } }; #endif // AUTO_UPDATE_SUPPORT #endif // UNIX_OPAUTOUPDATE_H
#include <iostream> #include <vector> #include <map> #include <string> #include <bitset> #include <queue> #include <algorithm> #include <functional> #include <cmath> #include <cstdio> #include <sstream> using namespace std; #define INF 1000000000 class CountingSeries { public: long long countYnX(long long a,long long b,long long c,long long d,long long u) { long long r = 0; long long y = c; while (y <= u) { bool add = true; if (y >= a) { if ((y-a)%b==0) { add = false; } } r += add ? 1 : 0; y *= d; if (d == 1) { break; } } return r; } long long countX(long long a,long long b,long long u) { if (a <= u) { return 1 + (u-a)/b; } return 0; } long long countThem(long long a, long long b, long long c, long long d, long long upperBound) { long long x = countX(a, b, upperBound); long long y = countYnX(a, b, c, d, upperBound); return x+y; } };
#include "gast_node.h" #include "gast_manager.h" #include <utils.h> #include <core/Array.hpp> #include <core/String.hpp> #include <core/NodePath.hpp> #include <core/Rect2.hpp> #include <core/Transform.hpp> #include <gen/Camera.hpp> #include <gen/Input.hpp> #include <gen/InputEventScreenDrag.hpp> #include <gen/InputEventScreenTouch.hpp> #include <gen/Material.hpp> #include <gen/Mesh.hpp> #include <gen/Node.hpp> #include <gen/QuadMesh.hpp> #include <gen/ArrayMesh.hpp> #include <gen/Resource.hpp> #include <gen/ResourceLoader.hpp> #include <gen/SceneTree.hpp> #include <gen/Shape.hpp> #include <gen/Texture.hpp> #include <gen/Viewport.hpp> namespace gast { namespace { const Vector2 kDefaultSize = Vector2(2.0, 1.125); const int kDefaultSurfaceIndex = 0; const char *kGastEnableBillBoardParamName = "enable_billboard"; const char *kGastTextureParamName = "gast_texture"; const char *kGastGradientHeightRatioParamName = "gradient_height_ratio"; const char *kGastNodeAlphaParamName = "node_alpha"; const float kDefaultAlpha = 1; const Vector2 kInvalidCoordinate = Vector2(-1, -1); const char *kCapturedGastRayCastGroupName = "captured_gast_ray_casts"; const float kCurvedScreenRadius = 6.0f; const size_t kCurvedScreenResolution = 20; const float kEquirectSphereSize = 1.0f; const size_t kEquirectSphereMeshBandCount = 80; const size_t kEquirectSphereMeshSectorCount = 80; const char *kShaderCode = R"GAST_SHADER( shader_type spatial; render_mode unshaded, depth_draw_opaque, specular_disabled, shadows_disabled, ambient_light_disabled; uniform samplerExternalOES gast_texture; uniform bool enable_billboard; uniform float gradient_height_ratio; uniform float node_alpha = 1.0; void vertex() { if (enable_billboard) { MODELVIEW_MATRIX = INV_CAMERA_MATRIX * mat4(CAMERA_MATRIX[0],CAMERA_MATRIX[1],CAMERA_MATRIX[2],WORLD_MATRIX[3]); } } void fragment() { vec4 texture_color = texture(gast_texture, UV); float target_alpha = COLOR.a * texture_color.a * node_alpha; if (gradient_height_ratio >= 0.05) { float gradient_mask = min((1.0 - UV.y) / gradient_height_ratio, 1.0); target_alpha = target_alpha * gradient_mask; } ALPHA = target_alpha; ALBEDO = texture_color.rgb * target_alpha; } )GAST_SHADER"; const char *kDisableDepthTestRenderMode = "render_mode depth_test_disable;"; const char *kCullFrontRenderMode = "render_mode cull_front;"; const char *kShaderCustomDefines = R"GAST_DEFINES( #ifdef ANDROID_ENABLED #extension GL_OES_EGL_image_external : enable #extension GL_OES_EGL_image_external_essl3 : enable #else #define samplerExternalOES sampler2D #endif )GAST_DEFINES"; } GastNode::GastNode() : collidable(kDefaultCollidable), curved(kDefaultCurveValue), gaze_tracking(kDefaultGazeTracking), render_on_top(kDefaultRenderOnTop), alpha(kDefaultAlpha), gradient_height_ratio(kDefaultGradientHeightRatio), mesh_size(kDefaultSize), projection_mesh_type(ProjectionMeshType::RECTANGULAR){} GastNode::~GastNode() = default; void GastNode::_register_methods() { register_method("_enter_tree", &GastNode::_enter_tree); register_method("_exit_tree", &GastNode::_exit_tree); register_method("_input_event", &GastNode::_input_event); register_method("_physics_process", &GastNode::_physics_process); register_method("_process", &GastNode::_process); register_method("_notification", &GastNode::_notification); register_method("set_size", &GastNode::set_size); register_method("get_size", &GastNode::get_size); register_method("set_collidable", &GastNode::set_collidable); register_method("is_collidable", &GastNode::is_collidable); register_method("set_curved", &GastNode::set_curved); register_method("is_curved", &GastNode::is_curved); register_method("set_gaze_tracking", &GastNode::set_gaze_tracking); register_method("is_gaze_tracking", &GastNode::is_gaze_tracking); register_method("set_render_on_top", &GastNode::set_render_on_top); register_method("is_render_on_top", &GastNode::is_render_on_top); register_method("set_gradient_height_ratio", &GastNode::set_gradient_height_ratio); register_method("get_gradient_height_ratio", &GastNode::get_gradient_height_ratio); register_method("get_external_texture_id", &GastNode::get_external_texture_id); register_property<GastNode, bool>("collidable", &GastNode::set_collidable, &GastNode::is_collidable, kDefaultCollidable); register_property<GastNode, bool>("curved", &GastNode::set_curved, &GastNode::is_curved, kDefaultCurveValue); register_property<GastNode, bool>("gaze_tracking", &GastNode::set_gaze_tracking, &GastNode::is_gaze_tracking, kDefaultGazeTracking); register_property<GastNode, bool>("render_on_top", &GastNode::set_render_on_top, &GastNode::is_render_on_top, kDefaultRenderOnTop); register_property<GastNode, Vector2>("size", &GastNode::set_size, &GastNode::get_size, kDefaultSize); register_property<GastNode, float>("gradient_height_ratio", &GastNode::set_gradient_height_ratio, &GastNode::get_gradient_height_ratio, kDefaultGradientHeightRatio); } void GastNode::_init() { ALOGV("Initializing GastNode class."); // Add a CollisionShape to the static body node CollisionShape *collision_shape = CollisionShape::_new(); add_child(collision_shape); // Add a mesh instance to the collision shape node MeshInstance *mesh_instance = MeshInstance::_new(); collision_shape->add_child(mesh_instance); rectangular_surface = QuadMesh::_new(); spherical_surface_array = create_spherical_surface_array( kEquirectSphereSize, kEquirectSphereMeshBandCount, kEquirectSphereMeshSectorCount); } void GastNode::_enter_tree() { ALOGV("Entering tree for %s.", get_node_tag(*this)); // Create the shader object Shader *shader = Shader::_new(); shader->set_custom_defines(kShaderCustomDefines); shader->set_code(generate_shader_code()); // Create the external texture ExternalTexture *external_texture = ExternalTexture::_new(); // Create the shader material. ALOGV("Creating GAST shader material."); ShaderMaterial *shader_material = ShaderMaterial::_new(); shader_material->set_shader(shader); shader_material->set_shader_param(kGastTextureParamName, external_texture); shader_material_ref = Ref<ShaderMaterial>(shader_material); update_mesh_and_collision_shape(); update_render_priority(); } void GastNode::_exit_tree() { ALOGV("Exiting tree."); reset_mesh_and_collision_shape(); } void GastNode::reset_mesh_and_collision_shape() { // Unset the GAST mesh resource MeshInstance *mesh_instance = get_mesh_instance(); if (mesh_instance) { mesh_instance->set_mesh(Ref<Resource>()); } // Unset the box shape resource update_collision_shape(); } void GastNode::update_mesh_dimensions_and_collision_shape() { MeshInstance *mesh_instance = get_mesh_instance(); auto *mesh = get_mesh(); if (!mesh_instance || !mesh) { ALOGE("Unable to access mesh resource for %s", get_node_tag(*this)); return; } Mesh::PrimitiveType primitive; Array mesh_surface_array; if (projection_mesh_type == ProjectionMeshType::RECTANGULAR) { if (is_curved()) { primitive = Mesh::PRIMITIVE_TRIANGLE_STRIP; mesh_surface_array = create_curved_screen_surface_array( mesh_size, kCurvedScreenRadius, kCurvedScreenResolution); } else { primitive = Mesh::PRIMITIVE_TRIANGLES; rectangular_surface->set_size(mesh_size); mesh_surface_array = rectangular_surface->get_mesh_arrays(); } } else if (projection_mesh_type == ProjectionMeshType::EQUIRECTANGULAR) { primitive = Mesh::PRIMITIVE_TRIANGLES; mesh_surface_array = spherical_surface_array; } auto *array_mesh = Object::cast_to<ArrayMesh>(mesh); if (!array_mesh) { ALOGE("Failed to cast mesh to %s.", ArrayMesh::___get_class_name()); return; } for (int i = 0; i < array_mesh->get_surface_count(); i++) { array_mesh->surface_remove(i); } array_mesh->add_surface_from_arrays(primitive, mesh_surface_array); // Generate updated shader code for the type of projection being used. shader_material_ref->get_shader()->set_code(generate_shader_code()); ALOGV("Setting up GAST shader material resource."); mesh_instance->set_surface_material(kDefaultSurfaceIndex, shader_material_ref); update_collision_shape(); } void GastNode::update_mesh_and_collision_shape() { Mesh *mesh = ArrayMesh::_new(); ALOGV("Setting up GAST mesh resource."); MeshInstance *mesh_instance = get_mesh_instance(); if (!mesh_instance || !mesh) { return; } mesh_instance->set_mesh(mesh); ALOGV("Setting up GAST shape resource."); update_mesh_dimensions_and_collision_shape(); } void GastNode::update_render_priority() { ShaderMaterial *shader_material = *shader_material_ref; if (!shader_material) { return; } int render_priority = 0; if (render_on_top) { render_priority++; if (gaze_tracking) { render_priority++; } } shader_material->set_render_priority(render_priority); } Vector2 GastNode::get_size() { return mesh_size; } void GastNode::set_size(Vector2 size) { this->mesh_size = size; update_mesh_dimensions_and_collision_shape(); } void GastNode::update_collision_shape() { CollisionShape *collision_shape = get_collision_shape(); if (!collision_shape) { ALOGW("Unable to retrieve collision shape for %s. Aborting...", get_node_tag(*this)); return; } Mesh *mesh = get_mesh(); if (!is_visible_in_tree() || !collidable || !mesh) { collision_shape->set_shape(Ref<Resource>()); } else { if (is_curved()) { // TODO: Use `create_trimesh_shape()` instead after resolving why the shape doesn't detect collisions. collision_shape->set_shape(mesh->create_convex_shape()); } else { collision_shape->set_shape(mesh->create_convex_shape()); } } } void GastNode::update_shader_params() { ShaderMaterial *shader_material = get_shader_material(); if (!shader_material) { return; } shader_material->set_shader_param(kGastEnableBillBoardParamName, gaze_tracking); shader_material->set_shader_param(kGastGradientHeightRatioParamName, gradient_height_ratio); shader_material->set_shader_param(kGastNodeAlphaParamName, alpha); } int GastNode::get_external_texture_id(int surface_index) { if (surface_index == kInvalidSurfaceIndex) { // Default to the first one surface_index = kDefaultSurfaceIndex; } ExternalTexture *external_texture = get_external_texture(surface_index); int tex_id = external_texture == nullptr ? kInvalidTexId : external_texture->get_external_texture_id(); ALOGV("Retrieved tex id %d", tex_id); return tex_id; } void GastNode::_input_event(const godot::Object *camera, const godot::Ref<godot::InputEvent> event, const godot::Vector3 click_position, const godot::Vector3 click_normal, const int64_t shape_idx) { if (event.is_null()) { return; } String node_path = get_path(); // Calculate the 2D collision point of the raycast on the Gast node. Vector2 relative_collision_point = get_relative_collision_point(click_position); float x_percent = relative_collision_point.x; float y_percent = relative_collision_point.y; // This should only fire for touch screen input events, so we filter for those. if (event->is_class(InputEventScreenTouch::___get_class_name())) { auto *touch_event = Object::cast_to<InputEventScreenTouch>(*event); if (touch_event) { String touch_event_id = InputEventScreenTouch::___get_class_name() + String::num_int64(touch_event->get_index()); if (touch_event->is_pressed()) { GastManager::get_singleton_instance()->on_render_input_press(node_path, touch_event_id, x_percent, y_percent); } else { GastManager::get_singleton_instance()->on_render_input_release(node_path, touch_event_id, x_percent, y_percent); } } } else if (event->is_class(InputEventScreenDrag::___get_class_name())) { auto *drag_event = Object::cast_to<InputEventScreenDrag>(*event); if (drag_event) { String drag_event_id = InputEventScreenDrag::___get_class_name() + String::num_int64(drag_event->get_index()); GastManager::get_singleton_instance()->on_render_input_hover(node_path, drag_event_id, x_percent, y_percent); } } } void GastNode::_notification(const int64_t what) { switch(what) { case NOTIFICATION_VISIBILITY_CHANGED: update_collision_shape(); break; } } void GastNode::_process(const real_t delta) { if (is_gaze_tracking()) { Rect2 gaze_area = get_viewport()->get_visible_rect(); Vector2 gaze_center_point = Vector2(gaze_area.position.x + gaze_area.size.x / 2.0, gaze_area.position.y + gaze_area.size.y / 2.0); // Get the distance between the camera and this node. Camera* camera = get_viewport()->get_camera(); Transform global_transform = get_global_transform(); float distance = camera->get_global_transform().origin.distance_to(global_transform.origin); // Update the node's position to match the center of the gaze area. Vector3 updated_position = camera->project_position(gaze_center_point, distance); global_transform.origin = updated_position; set_global_transform(global_transform); } } void GastNode::_physics_process(const real_t delta) { if (!is_collidable()) { return; } // Get the list of ray casts in the group Array gast_ray_casts = get_tree()->get_nodes_in_group(kGastRayCasterGroupName); if (gast_ray_casts.empty()) { return; } NodePath node_path = get_path(); for (int i = 0; i < gast_ray_casts.size(); i++) { RayCast *ray_cast = get_ray_cast_from_variant(gast_ray_casts[i]); if (!ray_cast || !ray_cast->is_enabled()) { continue; } String ray_cast_path = ray_cast->get_path(); // Check if the raycast has been captured by another node already. if (ray_cast->is_in_group(kCapturedGastRayCastGroupName) && !has_captured_raycast(*ray_cast)) { continue; } // Check if the ray cast collides with this node. bool collides_with_node = false; Vector3 collision_point; Vector3 collision_normal; if (ray_cast->is_colliding()) { Node *collider = Object::cast_to<Node>(ray_cast->get_collider()); if (collider != nullptr && node_path == collider->get_path()) { collides_with_node = true; collision_point = ray_cast->get_collision_point(); collision_normal = ray_cast->get_collision_normal(); } } else if (has_captured_raycast(*ray_cast) && colliding_raycast_paths[ray_cast_path]->press_in_progress) { // A press was in progress when the raycast 'move off' this node. Continue faking the // collision until the press is released. collision_point = colliding_raycast_paths[ray_cast_path]->collision_point; collision_normal = colliding_raycast_paths[ray_cast_path]->collision_normal; // Simulate collision and update collision_point accordingly. // Generate the plane defined by the collision normal and the collision point. auto *collision_plane = new Plane(collision_point, collision_normal); collides_with_node = calculate_raycast_plane_collision(*ray_cast, *collision_plane, &collision_point); } if (collides_with_node) { std::shared_ptr<CollisionInfo> collision_info = has_captured_raycast(*ray_cast) ? colliding_raycast_paths[ray_cast_path] : std::make_shared<CollisionInfo>(); // Calculate the 2D collision point of the raycast on the Gast node. Vector2 relative_collision_point = get_relative_collision_point(collision_point); collision_info->press_in_progress = handle_ray_cast_input(ray_cast_path, relative_collision_point); collision_info->collision_normal = collision_normal; collision_info->collision_point = collision_point; // Add the raycast to the list of colliding raycasts and update its collision info. colliding_raycast_paths[ray_cast_path] = collision_info; // Add the raycast to the captured raycasts group. ray_cast->add_to_group(kCapturedGastRayCastGroupName); continue; } // Cleanup if (has_captured_raycast(*ray_cast)) { // Grab the last coordinates. Vector2 last_coordinate = get_relative_collision_point( colliding_raycast_paths[ray_cast_path]->collision_point); if (colliding_raycast_paths[ray_cast_path]->press_in_progress) { // Fire a release event. GastManager::get_singleton_instance()->on_render_input_release(node_path, ray_cast_path, last_coordinate.x, last_coordinate.y); } else { // Fire a hover exit event. GastManager::get_singleton_instance()->on_render_input_hover(node_path, ray_cast_path, kInvalidCoordinate.x, kInvalidCoordinate.y); } // Remove the raycast from this node. colliding_raycast_paths.erase(ray_cast_path); // Remove the raycast from the captured raycasts group. ray_cast->remove_from_group(kCapturedGastRayCastGroupName); } } } bool GastNode::calculate_raycast_plane_collision(const RayCast &raycast, const Plane &plane, Vector3 *collision_point) { return plane.intersects_ray(raycast.to_global(raycast.get_translation()), raycast.to_global(raycast.get_cast_to()), collision_point); } ExternalTexture *GastNode::get_external_texture(int surface_index) { ShaderMaterial *shader_material = get_shader_material(); if (!shader_material) { return nullptr; } ExternalTexture *external_texture = nullptr; Ref<Texture> texture = shader_material->get_shader_param(kGastTextureParamName); if (texture.is_valid()) { external_texture = Object::cast_to<ExternalTexture>(*texture); } if (external_texture) { ALOGV("Found external GastNode texture for node %s", get_node_tag(*this)); } return external_texture; } bool GastNode::handle_ray_cast_input(const String &ray_cast_path, Vector2 relative_collision_point) { Input *input = Input::get_singleton(); String node_path = get_path(); float x_percent = relative_collision_point.x; float y_percent = relative_collision_point.y; // Check for click actions String ray_cast_click_action = get_click_action_from_node_path(ray_cast_path); const bool press_in_progress = input->is_action_pressed(ray_cast_click_action); if (input->is_action_just_pressed(ray_cast_click_action)) { GastManager::get_singleton_instance()->on_render_input_press(node_path, ray_cast_path, x_percent, y_percent); } else if (input->is_action_just_released(ray_cast_click_action)) { GastManager::get_singleton_instance()->on_render_input_release(node_path, ray_cast_path, x_percent, y_percent); } else { GastManager::get_singleton_instance()->on_render_input_hover(node_path, ray_cast_path, x_percent, y_percent); } // Check for scrolling actions bool did_scroll = false; float horizontal_scroll_delta = 0; float vertical_scroll_delta = 0; // Horizontal scrolls String ray_cast_horizontal_left_scroll_action = get_horizontal_left_scroll_action_from_node_path( ray_cast_path); String ray_cast_horizontal_right_scroll_action = get_horizontal_right_scroll_action_from_node_path( ray_cast_path); if (input->is_action_pressed(ray_cast_horizontal_left_scroll_action)) { did_scroll = true; horizontal_scroll_delta = -input->get_action_strength( ray_cast_horizontal_left_scroll_action); } else if (input->is_action_pressed(ray_cast_horizontal_right_scroll_action)) { did_scroll = true; horizontal_scroll_delta = input->get_action_strength( ray_cast_horizontal_right_scroll_action); } // Vertical scrolls String ray_cast_vertical_down_scroll_action = get_vertical_down_scroll_action_from_node_path( ray_cast_path); String ray_cast_vertical_up_scroll_action = get_vertical_up_scroll_action_from_node_path( ray_cast_path); if (input->is_action_pressed(ray_cast_vertical_down_scroll_action)) { did_scroll = true; vertical_scroll_delta = -input->get_action_strength(ray_cast_vertical_down_scroll_action); } else if (input->is_action_pressed(ray_cast_vertical_up_scroll_action)) { did_scroll = true; vertical_scroll_delta = input->get_action_strength(ray_cast_vertical_up_scroll_action); } if (did_scroll) { GastManager::get_singleton_instance()->on_render_input_scroll(node_path, ray_cast_path, x_percent, y_percent, horizontal_scroll_delta, vertical_scroll_delta); } return press_in_progress; } String GastNode::generate_shader_code() const { String shader_code = kShaderCode; if (render_on_top) { shader_code += kDisableDepthTestRenderMode; } if (projection_mesh_type == ProjectionMeshType::EQUIRECTANGULAR) { shader_code += kCullFrontRenderMode; } return shader_code; } Vector2 GastNode::get_relative_collision_point(Vector3 absolute_collision_point) { Vector2 relative_collision_point = kInvalidCoordinate; // Turn the collision point into local space Vector3 local_point = to_local(absolute_collision_point); // Normalize the collision point. A Gast node is a flat quad so we only worry about // the x,y coordinates Vector2 node_size = get_size(); if (node_size.width > 0 && node_size.height > 0) { float max_x = node_size.width / 2; float min_x = -max_x; float max_y = node_size.height / 2; float min_y = -max_y; relative_collision_point = Vector2((local_point.x - min_x) / node_size.width, (local_point.y - min_y) / node_size.height); // Adjust the y coordinate to match the Android view coordinates system. relative_collision_point.y = 1 - relative_collision_point.y; } return relative_collision_point; } } // namespace gast
const int X_Pin = 0; const int Y_Pin = 1; void setup() { Serial.begin(9600); } int state = 0; void loop() { // put your main code here, to run repeatedly: int x, y; //btnState = digitalRead(btnPin); this is a ok code x = analogRead(X_Pin); y = analogRead(Y_Pin); x = -(((x+128)>>7) - 8); y = (y+128)>>7; byte a = x + (y<<4); /*Serial.print("x: "); Serial.println(x); Serial.print("y: ");*/ //Serial.println(x); Serial.write(a); }
/////////////////////////////////////// // // Computer Graphics TSBK03 // Conrad Wahlén - conwa099 // /////////////////////////////////////// #include "Camera.h" #include "GL_utilities.h" #include "gtc/matrix_transform.hpp" #include <iostream> // // // CAMERA // // Camera::Camera() { isPaused = true; needUpdate = true; rspeed = 0.001f; yvec = glm::vec3(0.0f, 1.0f, 0.0f); cameraTwMembers[0] = { "Cam Pos x", TW_TYPE_FLOAT, offsetof(CameraParam, position.x), " readonly=true group=Info " }; cameraTwMembers[1] = { "Cam Pos y", TW_TYPE_FLOAT, offsetof(CameraParam, position.y), " readonly=true group=Info " }; cameraTwMembers[2] = { "Cam Pos z", TW_TYPE_FLOAT, offsetof(CameraParam, position.z), " readonly=true group=Info " }; cameraTwStruct = TwDefineStruct("Camera", cameraTwMembers, 3, sizeof(CameraParam), NULL, NULL); } bool Camera::Init(GLfloat fovInit, GLint *screenWidth, GLint *screenHeight, GLfloat farInit) { winHeight = screenHeight; winWidth = screenWidth; frustumFar = farInit; fov = fovInit; Resize(); glGenBuffers(1, &cameraBuffer); glBindBufferBase(GL_UNIFORM_BUFFER, CAMERA, cameraBuffer); glBufferData(GL_UNIFORM_BUFFER, sizeof(CameraParam), NULL, GL_STREAM_DRAW); // Set starting WTVmatrix Update(); return true; } void Camera::Reset() { param.position = startPos; } void Camera::Resize() { if(*winWidth > 0 && *winHeight > 0) { param.VTPmatrix = glm::perspectiveFov(glm::radians(fov), (GLfloat)*winWidth, (GLfloat)*winHeight, 1.0f, frustumFar); needUpdate = true; } } void Camera::Update(GLfloat deltaT) { if(needUpdate) { UpdateParams(deltaT); UploadParams(); } needUpdate = false; } void Camera::UploadParams() { glBindBufferBase(GL_UNIFORM_BUFFER, CAMERA, cameraBuffer); glBufferSubData(GL_UNIFORM_BUFFER, NULL, sizeof(CameraParam), &param); } // // // FPCAMERA // // FPCamera::FPCamera() : Camera() { mspeed = 10.0f; phi = 2.0f * (float)M_PI / 2.0f; theta = 2.0f * (float)M_PI / 4.0f; moveVec = glm::vec3(0, 0, 0); } bool FPCamera::Init(glm::vec3 startpos, GLfloat fovInit, GLint *screenWidth, GLint *screenHeight, GLfloat farInit) { startPos = startpos; param.position = startPos; return Camera::Init(fovInit, screenWidth, screenHeight, farInit); } void FPCamera::UpdateParams(GLfloat deltaT) { // Update directions forward = glm::normalize(glm::vec3(-sin(theta) * sin(phi), cos(theta), sin(theta) * cos(phi))); right = glm::normalize(glm::cross(forward, yvec)); up = glm::normalize(glm::cross(right, forward)); // Update camera matrix param.position += moveVec * deltaT; lookp = param.position + forward; param.WTVmatrix = lookAt(param.position, lookp, yvec); moveVec = glm::vec3(0.0f); } void FPCamera::Reset() { Camera::Reset(); phi = 7.0f * (float)M_PI / 4.0f; theta = (float)M_PI / 2.0f; } void FPCamera::MoveForward() { Move(forward); } void FPCamera::MoveBackward() { Move(-forward); } void FPCamera::MoveRight() { Move(right); } void FPCamera::MoveLeft() { Move(-right); } void FPCamera::MoveUp() { Move(up); } void FPCamera::MoveDown() { Move(-up); } void FPCamera::Move(glm::vec3 vec) { if(!isPaused) { moveVec += vec * mspeed; needUpdate = true; } } void FPCamera::Rotate(GLint dx, GLint dy) { Rotate((GLfloat)dx, (GLfloat)dy); } void FPCamera::Rotate(GLfloat dx, GLfloat dy) { if(!isPaused) { float eps = 0.001f; phi += rspeed * dx; theta += rspeed * dy; phi = (float)fmod(phi, 2.0f * (float)M_PI); theta = theta < (float)M_PI - eps ? (theta > eps ? theta : eps) : (float)M_PI - eps; needUpdate = true; } } // // // ORBITCAMERA // // OrbitCamera::OrbitCamera() { startTarget = glm::vec3(0, 0, 0); target = startTarget; distance = 1.0f; } void OrbitCamera::UpdateParams(GLfloat deltaT) { param.position = glm::vec3(sin(polar) * cos(azimuth), cos(polar), sin(polar) * sin(azimuth)); param.position *= distance; param.position += target; lookp = target; param.WTVmatrix = lookAt(param.position, lookp, yvec); } bool OrbitCamera::Init(glm::vec3 initTarget, GLfloat initDistance, GLfloat initPolar, GLfloat initAzimuth, GLfloat fovInit, GLint *screenWidth, GLint *screenHeight, GLfloat farInit) { startTarget = initTarget; target = startTarget; distance = initDistance; polar = initPolar; azimuth = initAzimuth; return Camera::Init(fovInit, screenWidth, screenHeight, farInit); } void OrbitCamera::Reset() { Camera::Reset(); } void OrbitCamera::Rotate(GLint dx, GLint dy) { Rotate((GLfloat)dx, (GLfloat)dy); } void OrbitCamera::Rotate(GLfloat dx, GLfloat dy) { if(!isPaused) { float eps = 0.001f; azimuth -= rspeed * dx; polar += rspeed * dy; azimuth = (float)fmod(azimuth, 2.0f * (float)M_PI); polar = polar < (float)M_PI - eps ? (polar > eps ? polar : eps) : (float)M_PI - eps; needUpdate = true; } } void OrbitCamera::Zoom(GLfloat factor) { if(!isPaused) { distance /= factor; needUpdate = true; } }
/* * velocity_calc.cpp * 4v_2d_magic_numbers * * Created by Niels Otani on 9/7/06. * Copyright 2006 __MyCompanyName__. All rights reserved. * */ #include "velocity_calc.h" void calc_velocity (double *vx, double *vy, double M[4], double *ax, double *ay, double *wavefront_times, int npoints) { /* Calculate the velocity of a wavefront based on the times that the wavefront passees through npoints different gridpoints. vx: on output, contains the x-component of the calculated velocity vy: on output, contains the y-component of the calculated velocity M[4]: (input) the elements of the matrix calculated by setup_variance_matrix ax(npoints), ay(npoints): (input) contains npoints vectors pointing from the gripoint where the velocity is to be calculated to the npoints gridpoints that will participate in the calculation. The first vector should point to the gridpoint where the velocity is calculated itself; thus should have ax(0)=0 and ay(0)=0 on input. wavefront_times(npoints): (input) times at which the wavefront passes through the gridpoints defined by ax and ay relative to the gridpoint at which the calculation is to be performed. Note that the wavefront time at this gridpoint should be in wavefront_time(0) on input. npoints: (input) the number of points that will participate in the calculation. This routine works by minimizing the sum of the squares of (time_difference-a*grad(t_wavefront)) */ double A = M[0], B = M[1], C = M[2], D = M[3]; double b1 = 0.0, b2 = 0.0; int ipoints; for (ipoints=0;ipoints<npoints;ipoints++) { b1 += (wavefront_times[ipoints]-wavefront_times[0])*ax[ipoints]; b2 += (wavefront_times[ipoints]-wavefront_times[0])*ay[ipoints]; } double det = A*D-B*C; double dtdx = (D*b1-B*b2)/det; double dtdy = (-C*b1 + A*b2)/det; double gradtsq = dtdx*dtdx + dtdy*dtdy; *vx = dtdx/gradtsq; *vy = dtdy/gradtsq; return; } void setup_variance_matrix (double M[4], double *ax, double *ay, int npoints) { /* Setup the matrix used to calculate the velocity vector. M[4]: (output) contains the elements of the 2x2 matrix. Supply a matrix of length 4 on input. ax(npoints), ay(npoints): (input) contains npoints vectors pointing from the gripoint where the velocity is to be calculated to the npoints gridpoints that will participate in the calculation. The first vector should point to the gridpoint where the velocity is calculated itself; thus should have ax(0)=0 and ay(0)=0 on input. npoints: (input) the number of points that will participate in the calculation This routine need only be called once before calculations are performed, since it is a constant matrix. */ int k, ipoints; for (k=0;k<4;k++) { M[k] = 0; } for (ipoints=0;ipoints<npoints;ipoints++) { M[0] += ax[ipoints]*ax[ipoints]; M[1] += ax[ipoints]*ay[ipoints]; M[3] += ay[ipoints]*ay[ipoints]; } M[2] = M[1]; return; } int ready_to_calc_velocity (double current_time, double *wavefront_times, int npoints, double time_diff_threshold) { /* Check to see whether all the wavefront times are in place to do the velocity calculation. The calculation will be done when the last wavefront time involved in the calculation has just been updated (so that one of the wavefront_times is the current_time) and all the wavefront_times are less than time_diff_threshold behind the current_time. current_time: (input) the current time in the simulation wavefront_times(npoints): (input) a vector of length npoints containing the last time a wavefront passed each gripoint participating in the calculation. npoints: (input) the number of gridpoints participating in the calculation. time_diff_threshold: (input) all gridpoint wavefront_times must be within this value of the current_time; otherwise, the wavefront times will be assumed to not be from the same wavefront, and the calculation will not be ok'ed by this routine. return value: (output) = 1 if it is time to do the velocity calculation; 0 otherwise. */ int ipoints; // Check to see one of the points has just been updated. // (This prevents the same calculation from being performed over ana over) for (ipoints=0;ipoints<npoints;ipoints++) { if (wavefront_times[ipoints]==current_time) break; } if (ipoints==npoints) return (0); // Check to see that all the points have recently been updated: for (ipoints=0;ipoints<npoints;ipoints++) { if ( !(current_time-wavefront_times[ipoints] < time_diff_threshold ) ) return(2); } return (1); }
#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 <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #include <deque> const long long LINF = (1e15); const int INF = (1<<27); #define EPS 1e-6 const int MOD = 1000000007; using namespace std; typedef pair<int, int> P; class MaxTriangle { public: vector<P> getVector(int x) { vector<P> res; for (int i=0; i*i<=x; ++i) { int y = sqrt(x-i*i); if (x == i*i + y*y) { res.push_back(P(i,y)); res.push_back(P(-i,y)); res.push_back(P(i,-y)); res.push_back(P(-i,-y)); } } return res; } double calculateArea(int A, int B) { vector<P> a(getVector(A)); vector<P> b(getVector(B)); double ans = -1; int N = (int)a.size(); int M = (int)b.size(); for (int i=0; i<N; ++i) { for (int j=0; j<M; ++j) { double x1 = a[i].first; double y1 = a[i].second; double x2 = b[j].first; double y2 = b[j].second; ans = max(ans, 0.5*abs(x1*y2-x2*y1)); } } return ans; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 1; int Arg1 = 1; double Arg2 = 0.5; verify_case(0, Arg2, calculateArea(Arg0, Arg1)); } void test_case_1() { int Arg0 = 3; int Arg1 = 7; double Arg2 = -1.0; verify_case(1, Arg2, calculateArea(Arg0, Arg1)); } void test_case_2() { int Arg0 = 41; int Arg1 = 85; double Arg2 = 29.5; verify_case(2, Arg2, calculateArea(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { MaxTriangle ___test; ___test.run_test(-1); } // END CUT HERE
/****************************************************************************** * * * Copyright 2018 Jan Henrik Weinstock * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * ******************************************************************************/ #include <signal.h> // for SIGTRAP #include "vcml/debugging/gdbserver.h" namespace vcml { namespace debugging { static inline int char2int(char c) { return ((c >= 'a') && (c <= 'f')) ? c - 'a' + 10 : ((c >= 'A') && (c <= 'F')) ? c - 'A' + 10 : ((c >= '0') && (c <= '9')) ? c - '0' : (c == '\0') ? 0 : -1; } static inline u64 str2int(const char* s, int n) { u64 val = 0; for (const char* c = s + n - 1; c >= s; c--) { val <<= 4; val |= char2int(*c); } return val; } static inline u8 char_unescape(const char*& s) { u8 result = *s++; if (result == '}') result = *s++ ^ 0x20; return result; } void gdbserver::update_status(gdb_status status) { if (m_status == status) return; m_status = status; resume(); } bool gdbserver::is_suspend_requested() const { if (!m_sync) return false; return m_status == GDB_STOPPED; } bool gdbserver::access_pmem(bool iswr, u64 addr, u8 buffer[], u64 size) { try { return iswr ? m_stub->async_write_mem(addr, buffer, size) : m_stub->async_read_mem(addr, buffer, size); } catch (report& r) { log_warn("gdb cannot access %lu bytes at address %lx: %s", size, addr, r.message()); return false; } } bool gdbserver::access_vmem(bool iswr, u64 addr, u8 buffer[], u64 size) { u64 page_size = 0; if (!m_stub->async_page_size(page_size)) return access_pmem(iswr, addr, buffer, size); u64 end = addr + size; while (addr < end) { u64 pa = 0; u64 todo = min(end - addr, page_size - (addr % page_size)); if (m_stub->async_virt_to_phys(addr, pa)) { access_pmem(iswr, pa, buffer, todo); } else { memset(buffer, 0xee, todo); } addr += todo; buffer += todo; } return true; } string gdbserver::handle_unknown(const char* command) { return ""; } string gdbserver::handle_step(const char* command) { int signal = 0; update_status(GDB_STEPPING); while (m_status == GDB_STEPPING) { if ((signal = recv_signal(100))) { log_debug("received signal 0x%x", signal); m_status = GDB_STOPPED; m_signal = GDBSIG_TRAP; wait_for_suspend(); } } return mkstr("S%02x", m_signal); } string gdbserver::handle_continue(const char* command) { int signal = 0; update_status(GDB_RUNNING); while (m_status == GDB_RUNNING) { if ((signal = recv_signal(100))) { log_debug("received signal 0x%x", signal); m_status = GDB_STOPPED; m_signal = GDBSIG_TRAP; wait_for_suspend(); } } return mkstr("S%02x", m_signal); } string gdbserver::handle_detach(const char* command) { disconnect(); return ""; } string gdbserver::handle_kill(const char* command) { disconnect(); update_status(GDB_KILLED); sc_stop(); return ""; } string gdbserver::handle_query(const char* command) { if (strncmp(command, "qSupported", strlen("qSupported")) == 0) return mkstr("PacketSize=%zx", PACKET_SIZE); else if (strncmp(command, "qAttached", strlen("qAttached")) == 0) return "1"; else if (strncmp(command, "qOffsets", strlen("qOffsets")) == 0) return "Text=0;Data=0;Bss=0"; else if (strncmp(command, "qRcmd", strlen("qRcmd")) == 0) return handle_rcmd(command); else return handle_unknown(command); } string gdbserver::handle_rcmd(const char* command) { return m_stub->async_handle_rcmd(command); } string gdbserver::handle_reg_read(const char* command) { unsigned int reg; if (sscanf(command, "p%x", &reg) != 1) { log_warn("malformed command '%s'", command); return ERR_COMMAND; } u64 regsz = m_stub->async_register_width(reg); if (regsz == 0) return "xxxxxxxx"; // respond with "contents unknown" u8* buffer = new u8[regsz]; bool ok = m_stub->async_read_reg(reg, buffer, regsz); stringstream ss; ss << std::hex << std::setfill('0'); for (unsigned int byte = 0; byte < regsz; byte++) { if (ok) ss << std::setw(2) << (int)buffer[byte]; else ss << "xx"; } delete [] buffer; return ss.str(); } string gdbserver::handle_reg_write(const char* command) { unsigned int reg; if (sscanf(command, "P%x=", &reg) != 1) { log_warn("malformed command '%s'", command); return ERR_COMMAND; } u64 regsz = m_stub->async_register_width(reg); if (regsz == 0) return "OK"; const char* str = strchr(command, '='); if (str == NULL) { log_warn("malformed command '%s'", command); return ERR_COMMAND; } str++; // step beyond '=' if (strlen(str) != regsz * 2) { // need two hex chars per byte log_warn("malformed command '%s'", command); return ERR_COMMAND; } u8* buffer = new u8[regsz]; for (unsigned int byte = 0; byte < regsz; byte++, str += 2) buffer[byte] = char2int(str[0]) << 4 | char2int(str[1]); bool ok = m_stub->async_write_reg(reg, buffer, regsz); delete [] buffer; if (!ok) { log_warn("gdb cannot write register %u", reg); return ERR_INTERNAL; } return "OK"; } string gdbserver::handle_reg_read_all(const char* command) { u64 nregs = m_stub->async_num_registers(); stringstream ss; ss << std::hex << std::setfill('0'); for (u64 reg = 0; reg < nregs; reg++) { u64 regsz = m_stub->async_register_width(reg); if (regsz == 0) continue; u8* buffer = new u8[regsz]; bool ok = m_stub->async_read_reg(reg, buffer, regsz); for (u64 byte = 0; byte < regsz; byte++) { if (ok) ss << std::setw(2) << (int)buffer[byte]; else ss << "xx"; } delete [] buffer; } return ss.str(); } string gdbserver::handle_reg_write_all(const char* command) { u64 nregs = m_stub->async_num_registers(); u64 bufsz = 0; for (u64 reg = 0; reg < nregs; reg++) bufsz += m_stub->async_register_width(reg) * 2; const char* str = command + 1; if (strlen(str) != bufsz) { log_warn("malformed command '%s'", command); return ERR_COMMAND; } for (u64 reg = 0; reg < nregs; reg++) { u64 regsz = m_stub->async_register_width(reg); if (regsz == 0) continue; u8* buffer = new u8[regsz]; for (u64 byte = 0; byte < regsz; byte++, str += 2) buffer[byte] = char2int(str[0]) << 4 | char2int(str[1]); if (!m_stub->async_write_reg(reg, buffer, regsz)) log_warn("gdb cannot write register %lu", reg); delete [] buffer; } return "OK"; } string gdbserver::handle_mem_read(const char* command) { unsigned long long addr, size; if (sscanf(command, "m%llx,%llx", &addr, &size) != 2) { log_warn("malformed command '%s'", command); return ERR_COMMAND; } if (size > BUFFER_SIZE) { log_warn("too much data requested: %llu bytes", size); return ERR_PARAM; } stringstream ss; ss << std::hex << std::setfill('0'); u8 buffer[BUFFER_SIZE]; if (!access_vmem(false, addr, buffer, size)) return ERR_UNKNOWN; for (unsigned int i = 0; i < size; i++) ss << std::setw(2) << (int)buffer[i]; return ss.str(); } string gdbserver::handle_mem_write(const char* command) { unsigned long long addr, size; if (sscanf(command, "M%llx,%llx", &addr, &size) != 2) { log_warn("malformed command '%s'", command); return ERR_COMMAND; } if (size > BUFFER_SIZE) { log_warn("too much data requested: %llu bytes", size); return ERR_PARAM; } const char* data = strchr(command, ':'); if (data == NULL) { log_warn("malformed command '%s'", command); return ERR_COMMAND; } data++; u8 buffer[BUFFER_SIZE]; for (unsigned int i = 0; i < size; i++) buffer[i] = str2int(data++, 2); if (!access_vmem(true, addr, buffer, size)) return ERR_UNKNOWN; return "OK"; } string gdbserver::handle_mem_write_bin(const char* command) { unsigned long long addr, size; if (sscanf(command, "X%llx,%llx:", &addr, &size) != 2) { log_warn("malformed command '%s'", command); return ERR_COMMAND; } if (size > BUFFER_SIZE) { log_warn("too much data requested: %llu bytes", size); return ERR_PARAM; } if (size == 0) return "OK"; // empty load to test if binary write is supported const char* data = strchr(command, ':'); if (data == NULL) { log_warn("malformed command '%s'", command); return ERR_COMMAND; } data++; u8 buffer[BUFFER_SIZE]; for (unsigned int i = 0; i < size; i++) buffer[i] = char_unescape(data); if (!access_vmem(true, addr, buffer, size)) return ERR_UNKNOWN; return "OK"; } string gdbserver::handle_breakpoint_set(const char* command) { unsigned long long type, addr, length; if (sscanf(command, "Z%llx,%llx,%llx", &type, &addr, &length) != 3) { log_warn("malformed command '%s'", command); return ERR_COMMAND; } const range mem(addr, addr + length - 1); switch (type) { case GDB_BREAKPOINT_SW: case GDB_BREAKPOINT_HW: if (!m_stub->async_insert_breakpoint(addr)) return ERR_INTERNAL; break; case GDB_WATCHPOINT_WRITE: if (!m_stub->async_insert_watchpoint(mem, VCML_ACCESS_WRITE)) return ERR_INTERNAL; break; case GDB_WATCHPOINT_READ: if (!m_stub->async_insert_watchpoint(mem, VCML_ACCESS_READ)) return ERR_INTERNAL; break; case GDB_WATCHPOINT_ACCESS: if (!m_stub->async_insert_watchpoint(mem, VCML_ACCESS_READ_WRITE)) return ERR_INTERNAL; break; default: log_warn("unknown breakpoint type %llu", type); return ERR_COMMAND; } return "OK"; } string gdbserver::handle_breakpoint_delete(const char* command) { unsigned long long type, addr, length; if (sscanf(command, "z%llx,%llx,%llx", &type, &addr, &length) != 3) { log_warn("malformed command '%s'", command); return ERR_COMMAND; } const range mem(addr, addr + length - 1); switch (type) { case GDB_BREAKPOINT_SW: case GDB_BREAKPOINT_HW: if (!m_stub->async_remove_breakpoint(addr)) return ERR_INTERNAL; break; case GDB_WATCHPOINT_WRITE: if (!m_stub->async_remove_watchpoint(mem, VCML_ACCESS_WRITE)) return ERR_INTERNAL; break; case GDB_WATCHPOINT_READ: if (!m_stub->async_remove_watchpoint(mem, VCML_ACCESS_READ)) return ERR_INTERNAL; break; case GDB_WATCHPOINT_ACCESS: if (!m_stub->async_remove_watchpoint(mem, VCML_ACCESS_READ_WRITE)) return ERR_INTERNAL; break; default: log_warn("unknown breakpoint type %llu", type); return ERR_COMMAND; } return "OK"; } string gdbserver::handle_exception(const char* command) { return mkstr("S%02u", SIGTRAP); } string gdbserver::handle_thread(const char* command) { return "OK"; } string gdbserver::handle_vcont(const char* command) { return ""; } gdbserver::gdbserver(u16 port, gdbstub* stub, gdb_status status): rspserver(port), suspender("gdbserver"), m_stub(stub), m_status(status), m_default(status), m_sync(true), m_signal(-1), m_handler() { VCML_ERROR_ON(!stub, "no debug stub given"); m_handler['q'] = &gdbserver::handle_query; m_handler['s'] = &gdbserver::handle_step; m_handler['c'] = &gdbserver::handle_continue; m_handler['D'] = &gdbserver::handle_detach; m_handler['k'] = &gdbserver::handle_kill; m_handler['p'] = &gdbserver::handle_reg_read; m_handler['P'] = &gdbserver::handle_reg_write; m_handler['g'] = &gdbserver::handle_reg_read_all; m_handler['G'] = &gdbserver::handle_reg_write_all; m_handler['m'] = &gdbserver::handle_mem_read; m_handler['M'] = &gdbserver::handle_mem_write; m_handler['X'] = &gdbserver::handle_mem_write_bin; m_handler['Z'] = &gdbserver::handle_breakpoint_set; m_handler['z'] = &gdbserver::handle_breakpoint_delete; m_handler['H'] = &gdbserver::handle_thread; m_handler['v'] = &gdbserver::handle_vcont; m_handler['?'] = &gdbserver::handle_exception; run_async(); } gdbserver::~gdbserver() { /* nothing to do */ } void gdbserver::simulate(unsigned int cycles) { suspender::handle_requests(); switch (m_status) { case GDB_KILLED: return; case GDB_STOPPED: return; case GDB_STEPPING: { m_stub->gdb_simulate(1); notify(GDBSIG_TRAP); return; } case GDB_RUNNING: default: m_stub->gdb_simulate(cycles); return; } } string gdbserver::handle_command(const string& command) { try { handler func = find_handler(command.c_str()); return (this->*func)(command.c_str()); } catch (report& rep) { vcml::logger::log(rep); return ERR_INTERNAL; } catch (std::exception& ex) { log_warn(ex.what()); return ERR_INTERNAL; } } void gdbserver::handle_connect(const char* peer) { log_debug("gdb connected to %s", peer); update_status(GDB_STOPPED); } void gdbserver::handle_disconnect() { log_debug("gdb disconnected"); update_status(m_default); } }}
class Solution { public: bool isAnagram(string s, string t) { if(s.size() != t.size()) return false; vector<int> count(128,0); for(int i=0; i<s.size(); ++i){ count[s[i]]++; } for(int i=0; i<s.size(); ++i){ count[t[i]]--; } for(int i=0; i<128; ++i){ if(count[i] != 0) return false; } return true; } };
#pragma once namespace BroodWar { namespace Api { namespace Enum { [System::Flags] public enum class Targets { None = 0x0, Air = 0x1, Ground = 0x2, Mechanical = 0x4, Organic = 0x8, NonBuilding = 0x10, NonRobotic = 0x20, Terrain = 0x40, OrgOrMech = 0x80, Own = 0x100 }; } } }
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// // Пример использования static для генерации уникальных ID // уничтожения временных переменных // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// #include <iostream> using namespace std; int generateID() { static int s_itemID = 0; return ++s_itemID; } int main() { static int i = 0; while (i < 10) { ++i; cout << generateID() << endl; } return 0; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// // END FILE // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
//============================================================================ // Name : set_exeriments.cpp // Author : Andrzej Pawlowicz // Version : // Copyright : Your copyright notice // Description : Playing with std::set, hash_set, vector //============================================================================ // // Problem: // -> container that quaranties uniquenes of elements // Which solution is the fastest one // // For small number of elements ~100 vector + simple find on insert is faster // For big number of elements unordered_set is better // // #include <iostream> #include <vector> #include <map> #include <set> #include <unordered_set> #include <algorithm> #include <random> #include <chrono> using namespace std; class Timer { public: Timer(): start_(chrono::steady_clock::now()) {} int elapsedUs() const { auto end = chrono::steady_clock::now(); return chrono::duration_cast<chrono::microseconds>(end - start_).count(); } private: chrono::steady_clock::time_point start_; }; void printResult(std::string name, int time, int inputSize, int outputSize) { cout<<"---------------------- " << name <<"-------------------------" << endl; cout<< " test data size : " << inputSize << endl; cout<< " unique elements : " << outputSize << endl; cout<< " time :"<< time << "[us]" << endl; } void std_set_test(std::vector<int> data) { Timer timer; std::set<int> testSet; for (auto val: data) { testSet.insert(val); } printResult("std_set_test", timer.elapsedUs(), data.size(), testSet.size()); } void std_unordered_set_test(std::vector<int> data) { Timer timer; std::unordered_set<int> output; for (auto val: data) { output.insert(val); } printResult("std_unordered_set_test", timer.elapsedUs(), data.size(), output.size()); } void std_vector_made_unique_test(std::vector<int> data) { Timer timer; std::vector<int> output; for (auto val: data) { output.emplace_back(val); } std::sort(output.begin(), output.end()); auto new_end = std::unique(output.begin(), output.end()); output.erase(new_end, output.end()); printResult("std_vector_made_unique_test", timer.elapsedUs(), data.size(), output.size()); } void std_vector_made_unique_test_reserve(std::vector<int> data) { Timer timer; std::vector<int> output; output.reserve(data.size()); for (auto val: data) { output.emplace_back(val); } std::sort(output.begin(), output.end()); auto new_end = std::unique(output.begin(), output.end()); std::vector<int> output2; output2.reserve(std::distance(output.begin(), new_end)); output2.assign(output.begin(), new_end); //output.erase(new_end, output.end()); printResult("std_vector_made_unique_test_reserve", timer.elapsedUs(), data.size(), output2.size()); } void std_vector_with_find_reserve(std::vector<int> data) { Timer timer; std::vector<int> output; output.reserve(data.size()); for (auto val: data) { auto it = std::find(output.begin(), output.end(), val); if (it == output.end()) { output.emplace_back(val); } } printResult("std_vector_with_find_reserve", timer.elapsedUs(), data.size(), output.size()); } void std_vector_with_find(std::vector<int> data) { Timer timer; std::vector<int> output; for (auto val: data) { auto it = std::find(output.begin(), output.end(), val); if (it == output.end()) { output.emplace_back(val); } } printResult("std_vector_with_find", timer.elapsedUs(), data.size(), output.size()); } void std_vector_sorted_insert_reserve(std::vector<int> data) { cout << "not implemented" <<endl; } std::vector<int> prepare_test_data(int size) { std::vector<int> data; data.reserve(size); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, 100); Timer timer; cout << "Generating test data set "; int logStep = size/50; for (int n = 0; n < size; ++n) { data.emplace_back(dis(gen)); if (n%logStep == 0) { cout << "."; } } cout << "done "<< timer.elapsedUs() << " [us]" <<endl; return data; } int main() { cout<<"----------------------------------"<<endl; cout<<" Unique container playground "<<endl; cout<<"----------------------------------"<<endl; { auto testData = prepare_test_data(10000000); std_set_test(testData); std_unordered_set_test(testData); std_vector_made_unique_test(testData); std_vector_made_unique_test_reserve(testData); std_vector_with_find(testData); std_vector_with_find_reserve(testData); std_vector_sorted_insert_reserve(testData); } cout<<"----------------------------------"<<endl; cout<<"**********************************"<<endl; cout<<"----------------------------------"<<endl; { auto testData = prepare_test_data(10000); std_set_test(testData); std_unordered_set_test(testData); std_vector_made_unique_test(testData); std_vector_made_unique_test_reserve(testData); std_vector_with_find(testData); std_vector_with_find_reserve(testData); std_vector_sorted_insert_reserve(testData); } cout<<"----------------------------------"<<endl; cout<<"**********************************"<<endl; cout<<"----------------------------------"<<endl; { auto testData = prepare_test_data(100); std_set_test(testData); std_unordered_set_test(testData); std_vector_made_unique_test(testData); std_vector_made_unique_test_reserve(testData); std_vector_with_find(testData); std_vector_with_find_reserve(testData); std_vector_sorted_insert_reserve(testData); } return 0; }
#ifndef LISP_CMAP_TEST_HPP #define LISP_CMAP_TEST_HPP #include <gtest/gtest.h> #include <cmap.h> #include <hash.h> #include <permutations.h> #include <ops.h> namespace { /** * Function that "hashes" everything to the same value! * (very useful for testing the behavior of hash collisions in a hash table) * @tparam N what to hash elements to * @param key the key to hash (unused) * @param keysize size of the key (unused) * @return the value of N (always!) */ template <unsigned int N> constexpr unsigned int hash_to_n(const void *key UNUSED, size_t keysize UNUSED) { return N; } /** * Function that "hashes" everything to one of two values! * Again, very helpful for testing hash collision behavior, especially with open addressing * @tparam T The type of the key (make sure it supports GTE operator) * @tparam N first value that might be hashed to * @tparam M second value that might be hashed to * @tparam Threshold threshold for key value above which this function returns M rather than N * @param key pointer to the key to hash * @param keysize The size of the key (unused since keysize can be had from T) * @return N if the key is at least the Threshold, otherwise M */ template <typename T, unsigned int N, unsigned int M, T Threshold> unsigned int two_hash(const void *key, size_t keysize UNUSED) { auto tp = static_cast<const T*>(key); return *tp >= Threshold ? N : M; } template <typename K, typename V> class MapTest : public testing::Test { protected: MapTest() : cm(nullptr) { } using Test::SetUp; void SetUp(CMapHashFn hash, CmpFn cmp, unsigned int capacity_hint) { cm = cmap_create(sizeof(K), sizeof(V), hash, cmp, nullptr, nullptr, capacity_hint); ASSERT_NE(cm, nullptr); } void TearDown() { cmap_dispose(cm); } CMap *cm; }; typedef MapTest<int, int> MapIntIntTest; TEST_F(MapIntIntTest, create) { SetUp(hash_to_n<0>, (CmpFn) cmp_int, 0); EXPECT_EQ(cmap_count(cm), 0); } typedef MapTest<int, int> MapIntIntTest; TEST_F(MapIntIntTest, InsertOne) { SetUp(hash_to_n<0>, (CmpFn) cmp_int, 0); int i = 42; cmap_insert(cm, &i, &i); EXPECT_EQ(cmap_count(cm), 1); } TEST_F(MapIntIntTest, Insert10) { SetUp(two_hash<int, 0, 100, 5>, (CmpFn) cmp_int, 0); for (int i = 0; i < 10; ++i) { EXPECT_EQ(cmap_count(cm), i); cmap_insert(cm, &i, &i); } // Make sure they're all in there for (int i = 0; i < 10; ++i) { const void *v = cmap_lookup(cm, &i); ASSERT_TRUE(v != nullptr); int value = *static_cast<const int*>(v); EXPECT_EQ(value, i); } } // test if things are inserted correctly when one collection of elements overlaps with another set TEST_F(MapIntIntTest, InsertOverlap) { constexpr int first_hash = 0; constexpr int second_hash = 10; constexpr int threshold = 1000; SetUp(two_hash<int, first_hash, second_hash, threshold>, (CmpFn) cmp_int, 0); constexpr int N = 2 * second_hash; // how many of each hash to insert const int first_value = 42; const int second_value = 314; // insert elements hashing to first location, enough to cover up the origin of the // next set of elements for (int i = 0; i < N; i++) cmap_insert(cm, &i, &first_value); // these ones will all hash to "second_hash" for (int i = threshold; i < threshold + N; i++) cmap_insert(cm, &i, &second_value); for (int i = N; i < 2 * N; i++) cmap_insert(cm, &i, &first_value); const int *valuep; for (int i = 0; i < 2 * N; i++) { valuep = static_cast<const int *>(cmap_lookup(cm, &i)); ASSERT_TRUE(valuep != nullptr); EXPECT_EQ(*valuep, first_value); } for (int i = threshold; i < threshold + N; i++) { valuep = static_cast<const int *>(cmap_lookup(cm, &i)); ASSERT_TRUE(valuep != nullptr); EXPECT_EQ(*valuep, second_value); } } TEST_F(MapIntIntTest, InsertStaggeredOverlap) { constexpr int first_hash = 0; constexpr int second_hash = 10; constexpr int threshold = 1000; SetUp(two_hash<int, first_hash, second_hash, threshold>, (CmpFn) cmp_int, 0); constexpr int N = 2 * second_hash; // how many of each hash to insert const int first_value = 42; const int second_value = 314; // insert a bunch of elements near each-other until they start overlapping with one another // at which point they will need to stagger for (int i = 0; i < N; i++) { cmap_insert(cm, &i, &first_value); const int second_key = threshold + i; cmap_insert(cm, &second_key, &second_value); } // make sure they're all in there for (int i = 0; i < N; i++) { auto valuep = static_cast<const int *>(cmap_lookup(cm, &i)); ASSERT_NE(valuep, nullptr); EXPECT_EQ(*valuep, first_value); const int second_key = threshold + i; valuep = static_cast<const int *>(cmap_lookup(cm, &second_key)); ASSERT_NE(valuep, nullptr); EXPECT_EQ(*valuep, second_value); } } // Make sure that when you delete an element, its gone. TEST_F(MapIntIntTest, Delete) { SetUp(two_hash<int, 0, 100, 5>, (CmpFn) cmp_int, 0); int i = 42; cmap_insert(cm, &i, &i); cmap_remove(cm, &i); EXPECT_EQ(cmap_lookup(cm, &i), nullptr); } // Make sure that when you delete an element when there was a collision, the other // one is still there TEST_F(MapIntIntTest, DeleteWithCollision) { SetUp(two_hash<int, 0, 100, 5>, (CmpFn) cmp_int, 0); int x = 0; int y = 1; cmap_insert(cm, &x, &x); cmap_insert(cm, &y, &y); cmap_remove(cm, &x); EXPECT_EQ(cmap_lookup(cm, &x), nullptr); auto yp = static_cast<const int*>(cmap_lookup(cm, &y)); EXPECT_EQ(*yp, y); } TEST_F(MapIntIntTest, DeleteSecondWithCollision) { SetUp(two_hash<int, 0, 100, 5>, (CmpFn) cmp_int, 0); int x = 0; int y = 1; cmap_insert(cm, &x, &x); cmap_insert(cm, &y, &y); cmap_remove(cm, &y); EXPECT_EQ(cmap_lookup(cm, &y), nullptr); auto xp = static_cast<const int*>(cmap_lookup(cm, &x)); EXPECT_EQ(*xp, x); } TEST_F(MapIntIntTest, DeleteOverlap) { constexpr int first_hash = 0; constexpr int second_hash = 10; constexpr int threshold = 1000; SetUp(two_hash<int, first_hash, second_hash, threshold>, (CmpFn) cmp_int, 0); constexpr int N = 2 * second_hash; // how many of each hash to insert const int first_value = 42; const int second_value = 314; // insert a bunch of elements near each-other until they start overlapping with one another // at which point they will need to stagger for (int i = 0; i < N; i++) { cmap_insert(cm, &i, &first_value); const int second_key = threshold + i; cmap_insert(cm, &second_key, &second_value); } // delete all the ones from the lower hash value that overlapped into the second hash for (int i = 0; i < N; i++) cmap_remove(cm, &i); // make sure all the higher hash value elements are sill there for (int i = threshold; i < N; i++) { auto vp = static_cast<const int *>(cmap_lookup(cm, &i)); ASSERT_NE(vp, nullptr); EXPECT_EQ(*vp, second_value); } } // the next few tests use the permuter library to insert a whole bunch // of elements. this doesn't test for anything in particular but just // hopefully might catch something wrong that wasn't tested for in other cases class PermutationMapTest : public testing::Test { protected: PermutationMapTest() : p(nullptr), cm(nullptr) { } using Test::SetUp; void SetUp(const char * str, CMapHashFn hash, CmpFn cmp, unsigned int capacity_hint) { cm = cmap_create(sizeof(const char *), sizeof(int), hash, cmp, str_cleanup, nullptr, capacity_hint); ASSERT_NE(cm, nullptr); p = new_cstring_permuter(str); ASSERT_NE(p, nullptr); } // cleans up one of the string keys (which has been malloc'd) static void str_cleanup(void *key) { char *s = *(char **) key; free(s); } void TearDown() { cstring_permuter_dispose(p); cmap_dispose(cm); } permuter *p; CMap *cm; }; TEST_F(PermutationMapTest, Permute1234) { SetUp("1234", string_hash, cmp_cstr, 1024); const void *permutation; for_permutations(p, permutation) { auto str = static_cast<const char *>(permutation); int i = permutation_index(p); char *s = strdup(str); cmap_insert(cm, &s, &i); EXPECT_EQ(cmap_count(cm), i + 1); } reset_permuter(p); // Check to make sure that they're all there for_permutations(p, permutation) { auto str = static_cast<const char *>(permutation); auto valuep = static_cast<int *>(cmap_lookup(cm, &str)); ASSERT_NE(valuep, nullptr); EXPECT_EQ(*valuep, permutation_index(p)); } } } #endif // LISP_CMAP_TEST_HPP
// Created by: Kirill GAVRILOV // Copyright (c) 2019 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 _Media_Frame_HeaderFile #define _Media_Frame_HeaderFile #include <Graphic3d_Vec2.hxx> #include <Image_PixMap.hxx> #include <Standard_Transient.hxx> #include <Standard_Type.hxx> struct AVFrame; //! AVFrame wrapper - the frame (decoded image/audio sample data) holder. class Media_Frame : public Standard_Transient { DEFINE_STANDARD_RTTIEXT(Media_Frame, Standard_Transient) public: //! Convert pixel format from FFmpeg (AVPixelFormat) to OCCT. Standard_EXPORT static Image_Format FormatFFmpeg2Occt (int theFormat); //! Convert pixel format from OCCT to FFmpeg (AVPixelFormat). //! Returns -1 (AV_PIX_FMT_NONE) if undefined. Standard_EXPORT static int FormatOcct2FFmpeg (Image_Format theFormat); //! Swap AVFrame* within two frames. Standard_EXPORT static void Swap (const Handle(Media_Frame)& theFrame1, const Handle(Media_Frame)& theFrame2); public: //! Empty constructor Standard_EXPORT Media_Frame(); //! Destructor Standard_EXPORT virtual ~Media_Frame(); //! Return true if frame does not contain any data. Standard_EXPORT bool IsEmpty() const; //! av_frame_unref() wrapper. Standard_EXPORT void Unref(); //! Return image dimensions. Graphic3d_Vec2i Size() const { return Graphic3d_Vec2i (SizeX(), SizeY()); } //! Return image width. Standard_EXPORT int SizeX() const; //! Return image height. Standard_EXPORT int SizeY() const; //! Return pixel format (AVPixelFormat). Standard_EXPORT int Format() const; //! Return TRUE if YUV range is full. Standard_EXPORT bool IsFullRangeYUV() const; //! Access data plane for specified Id. Standard_EXPORT uint8_t* Plane (int thePlaneId) const; //! @return linesize in bytes for specified data plane Standard_EXPORT int LineSize (int thePlaneId) const; //! @return frame timestamp estimated using various heuristics, in stream time base Standard_EXPORT int64_t BestEffortTimestamp() const; //! Return frame. const AVFrame* Frame() const { return myFrame; } //! Return frame. AVFrame* ChangeFrame() { return myFrame; } //! Return presentation timestamp (PTS). double Pts() const { return myFramePts; } //! Set presentation timestamp (PTS). void SetPts (double thePts) { myFramePts = thePts; } //! Return PAR. float PixelAspectRatio() const { return myPixelRatio; } //! Set PAR. void SetPixelAspectRatio (float theRatio) { myPixelRatio = theRatio; } //! Return locked state. bool IsLocked() const { return myIsLocked; } //! Lock/free frame for edition. void SetLocked (bool theToLock) { myIsLocked = theToLock; } public: //! Wrap allocated image pixmap. Standard_EXPORT bool InitWrapper (const Handle(Image_PixMap)& thePixMap); protected: AVFrame* myFrame; //!< frame double myFramePts; //!< presentation timestamp float myPixelRatio; //!< pixel aspect ratio bool myIsLocked; //!< locked state }; #endif // _Media_Frame_HeaderFile
#include <stdio.h> #include <stdlib.h> int main() { int sayi,i=0,dizi[100],a,toplam = 0; printf("bir sayi giriniz"); scanf("%d",&sayi); a = sayi; while(sayi > 0) { dizi[i]= sayi % 10; sayi = sayi / 10; i = i + 1; } for(i=i-1;i>=0;i--) { toplam = toplam + dizi[i]*dizi[i]*dizi[i]; } if(toplam == a) printf("%d sayisi Armstrong sayidir ",a); else printf("%d sayisi Armstrong sayi degildir",a); return 0; }
// Copyright (c) 2011-2012 Thomas Heller // Copyright (c) 2013-2016 Agustin Berge // // 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) #pragma once #include <pika/config.hpp> #include <pika/assert.hpp> #include <pika/functional/invoke.hpp> #include <pika/functional/traits/get_function_address.hpp> #include <pika/functional/traits/get_function_annotation.hpp> #include <cstddef> #include <type_traits> #include <utility> namespace pika::util::detail { template <typename F> class one_shot_wrapper //-V690 { public: template <typename F_, typename = std::enable_if_t<std::is_constructible_v<F, F_>>> constexpr explicit one_shot_wrapper(F_&& f) : _f(PIKA_FORWARD(F_, f)) #if defined(PIKA_DEBUG) , _called(false) #endif { } constexpr one_shot_wrapper(one_shot_wrapper&& other) : _f(PIKA_MOVE(other._f)) #if defined(PIKA_DEBUG) , _called(other._called) #endif { #if defined(PIKA_DEBUG) other._called = true; #endif } void check_call() { #if defined(PIKA_DEBUG) PIKA_ASSERT(!_called); _called = true; #endif } template <typename... Ts> constexpr PIKA_HOST_DEVICE std::invoke_result_t<F, Ts...> operator()(Ts&&... vs) { check_call(); return PIKA_INVOKE(PIKA_MOVE(_f), PIKA_FORWARD(Ts, vs)...); } constexpr std::size_t get_function_address() const { return pika::detail::get_function_address<F>::call(_f); } constexpr char const* get_function_annotation() const { #if defined(PIKA_HAVE_THREAD_DESCRIPTION) return pika::detail::get_function_annotation<F>::call(_f); #else return nullptr; #endif } #if PIKA_HAVE_ITTNOTIFY != 0 && !defined(PIKA_HAVE_APEX) util::itt::string_handle get_function_annotation_itt() const { # if defined(PIKA_HAVE_THREAD_DESCRIPTION) return pika::detail::get_function_annotation_itt<F>::call(_f); # else static util::itt::string_handle sh("one_shot_wrapper"); return sh; # endif } #endif public: // exposition-only F _f; #if defined(PIKA_DEBUG) bool _called; #endif }; template <typename F> constexpr one_shot_wrapper<std::decay_t<F>> one_shot(F&& f) { using result_type = one_shot_wrapper<std::decay_t<F>>; return result_type(PIKA_FORWARD(F, f)); } } // namespace pika::util::detail namespace pika::detail { #if defined(PIKA_HAVE_THREAD_DESCRIPTION) template <typename F> struct get_function_address<util::detail::one_shot_wrapper<F>> { static constexpr std::size_t call(util::detail::one_shot_wrapper<F> const& f) noexcept { return f.get_function_address(); } }; /////////////////////////////////////////////////////////////////////////// template <typename F> struct get_function_annotation<util::detail::one_shot_wrapper<F>> { static constexpr char const* call(util::detail::one_shot_wrapper<F> const& f) noexcept { return f.get_function_annotation(); } }; # if PIKA_HAVE_ITTNOTIFY != 0 && !defined(PIKA_HAVE_APEX) template <typename F> struct get_function_annotation_itt<util::detail::one_shot_wrapper<F>> { static util::itt::string_handle call(util::detail::one_shot_wrapper<F> const& f) noexcept { return f.get_function_annotation_itt(); } }; # endif #endif } // namespace pika::detail
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef JAYENTROPYDECODER_H #define JAYENTROPYDECODER_H /** Abstract class representing an entropy decoder. Can be either a huffman or * arithmetic decoder. */ class JayEntropyDecoder { public: virtual ~JayEntropyDecoder(){} /** Reset the decoder. Should be done at restart intervalls and new * scans. */ virtual void reset() = 0; /** Read a number of samples. * @param stream the data stream to read from. * @param component the component to read the sample for. * @param numSamples the number of sample to read. * @param samples pointer to the array of output samples. * @returns JAYPEG_ERR_NO_MEMORY if out of memory. * JAYPEG_ERR if an error occured. * JAYPEG_NOT_ENOUGH_DATA if there is not enough data to decode the * samples. * JAYPEG_OK if all went well. */ virtual int readSamples(class JayStream *stream, unsigned int component, unsigned int numSamples, short *samples) = 0; }; #endif
#ifndef Empleado_h #define Empleado_h using namespace std; class Empleado{ protected: // protected ya que es la clase base string nombre,apellidos; int nomina; double sueldoBase; public: Empleado(); Empleado(string,string,int,double); void setNombre(string); void setApellido(string); void setNomina(int); void setSueldoB(double); string getNombre(); string getApellido(); int getNomina(); double getSueldoB(); virtual double CalcularPago()=0; // estos metodos son virtual pure virtual void mostrar()=0; // para que sea una clase abstracta }; // Constructores Empleado::Empleado(){ nombre=""; apellidos=""; nomina=0; sueldoBase=0; } Empleado::Empleado(string nomb,string ape,int nomi,double sBase){ nombre=nomb; apellidos=ape; nomina=nomi; sueldoBase=sBase; } // Metodos set void Empleado::setNombre(string nomb){ nombre=nomb; } void Empleado::setApellido(string ape){ apellidos=ape; } void Empleado::setNomina(int nomi){ nomina=nomi; } void Empleado::setSueldoB(double sBase){ sueldoBase=sBase; } // Metodos get string Empleado::getNombre(){ return nombre; } string Empleado::getApellido(){ return apellidos; } int Empleado::getNomina(){ return nomina; } double Empleado::getSueldoB(){ return sueldoBase; } #endif /* Empleado_h */
#include <iostream> #include <cstdlib> #include "instr.h" #include "prog.h" #include "../grammar.h" #include "../interpreter.h" using namespace std; using namespace rep; Call::Call(LTerm* tree) : Expression(tree) { TTerm* t = dynamic_cast<TTerm*>((*tree)[0]); name = t->getValue(); for(int i = 1; i < tree->size(); i++) { argument.push_back(create_expression((*tree)[i])); } } Call::Call(LTerm* tree, int op) : Expression(tree) { TTerm* t = dynamic_cast<TTerm*>((*tree)[2]); name = t->getValue(); argument.push_back(create_expression((*tree)[1])); for(int i = 3; i < tree->size(); i++) { argument.push_back(create_expression((*tree)[i])); } } int Call::execute(Env* e, Store* s) { this->eval(s,e); return 0; } Val Call::eval(Store* s, Env* e) { function::Function *f = NULL; NFunction *nf = NULL; Val v = e->get(this->name); if(VERBOSE) cout << "call => " << name << endl; if(v.getType() == FUNCTION) { if(v.to_function()->getType() == NATIVE_FUNCTION) { nf = dynamic_cast<NFunction*>(v.to_function()); } else { f = dynamic_cast<function::Function*>(v.to_function()); } } else { f = ::getProgFunction(name); nf = ::getNativeFunction(name); } if(f != NULL) { Env *ne = new Env(f->getNbVar()); if(argument.size() != f->getArity()) { cout << "wrong arity during calling " << name << ", expected " << f->getArity() << ", " << argument.size() << " given " << endl; exit(1); } for(unsigned int i = 0; i < argument.size(); i++) { ne->set(i, argument[i]->eval(s,e), f->getVarName(i)); } f->execute(ne, s); Val v = ne->get(f->getNbVar()); delete ne; return v; } if(nf != NULL) { return nf->eval(s,e,argument, this->line(), this->file()); } cout << "undefined symbol " << name << endl; return Val(); } Assignement::Assignement(LTerm* list) : Expression(list) { TTerm* id = dynamic_cast<TTerm*>( (*list)[1]); this->name = id->getValue(); this->expr = create_expression((*list)[2]); } int Assignement::execute(Env* e, Store* s) { Val v = eval(s,e); if(v.getType() == EMPTY) { return 1; } return 0; } Val Assignement::eval(Store* s, Env* e) { Val v = this->expr->eval(s,e); /*if(v.getType() == REFERENCE) { cout << "référence set" << v.to_s() << endl; }*/ if(e->set(var_ref, v, name)) { cout << "variable hors des bornes de l'env boulet de programmeur " << endl; return Val(); } return v; } string Assignement::getVarName() { return this->name; } void Assignement::setVarRef(int ref) { this->var_ref = ref; } Expression* create_expression(Term* t) { if(t->getType() == get_set_code("int")) { TTerm* tt = dynamic_cast<TTerm*>(t); return new Integer(tt->getValue(), tt); } if(t->getType() == get_set_code("float")) { TTerm* tt = dynamic_cast<TTerm*>(t); return new Real(tt->getValue(), tt); } if(t->getType() == get_set_code("string")) { TTerm* tt = dynamic_cast<TTerm*>(t); return new String(tt->getValue(), tt); } if(t->getType() == get_set_code("Id")) { TTerm* tt = dynamic_cast<TTerm*>(t); return new Id(tt->getValue(), get_var_ref(tt->getValue()), tt); } if(t->getType() == get_set_code("Call")) { LTerm* lt = dynamic_cast<LTerm*>(t); return new Call(lt); } if(t->getType() == get_set_code("Op")) { LTerm* lt = dynamic_cast<LTerm*>(t); return new Call(lt, 0); } if(t->getType() == get_set_code("Assignement")) { LTerm* lt = dynamic_cast<LTerm*>(t); Assignement* ass = new Assignement(lt); ::add_var(ass->getVarName()); ass->setVarRef(get_var_ref(ass->getVarName())); return ass; } return NULL; } Return::Return(LTerm* list) : SNode(list) { this->expr = create_expression((*list)[1]); } int Return::execute(Env* e, Store* s) { //on place la valeur du return dans la dernière case de l'environement e->set(e->getSize() - 1, this->expr->eval(s,e)); return 99; } If::If(LTerm *tree) : SNode(tree) { this->expr = create_expression((*tree)[1]); LTerm *t = dynamic_cast<LTerm*>((*tree)[2]); ::analyse_instr(t, yes); LTerm *tt = dynamic_cast<LTerm*>((*tree)[3]); ::analyse_instr(tt, no); } int If::execute(Env* e, Store* s) { if(expr->eval(s,e).to_b()) { executeList(e,s,yes); } else { executeList(e,s,no); } return 0; } int If::executeList(Env* e, Store* s, std::vector<Instr*>& instr) { for(unsigned int i = 0; i < instr.size(); i++) { int result = instr[i]->execute(e,s); if(result == 99) { return 99; } else if(result) { return result; } } return 0; } While::While(LTerm *tree) : SNode(tree) { this->expr = create_expression((*tree)[1]); LTerm *t = dynamic_cast<LTerm*>((*tree)[2]); ::analyse_instr(t, yes); } int While::execute(Env* e, Store* s) { while(expr->eval(s,e).to_b()) { int result = executeList(e,s,yes); if(result == 99) { return 99; } else if(result) { return result; } } return 0; } int While::executeList(Env* e, Store* s, std::vector<Instr*>& instr) { for(unsigned int i = 0; i < instr.size(); i++) { int result = instr[i]->execute(e,s); if(result == 99) { return 99; } else if(result) { return result; } } return 0; } Skip::Skip(LTerm *tree) : SNode(tree) {} int Skip::execute(Env*, Store*) {return 0;}
#include "Arduino.h" #include "blink.h" blink::blink(int pin_num) { pinMode(pin_num, OUTPUT); pin = pin_num; } void blink::on(int deg) { digitalWrite(pin, HIGH); delay(deg); } void blink::off(int deg) { digitalWrite(pin, LOW); delay(deg); }
#ifndef CPOLYLINE_H #define CPOLYLINE_H // system include #include <vector> // project include #include "CRect.h" // external include #include "xmlParser.h" // forward declarations using namespace std; class CPolyLine : public CShape { public: // interface CPolyLine(); ~CPolyLine(); void Draw() const; void AddPoint( const CPoint& inP ); size_t GetVertexCount() const { return mVertices.size(); } CRect GetBoundingBox() const { return mBoundRect; } static CShape* CreateFromXml(XMLNode& inNode); virtual void SaveXml ( XMLNode& inNode ); private: // implementation vector< CPoint > mVertices; CRect mBoundRect; }; #endif // CPOLYLINE_H
#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++) { if ((i % 2) == 0) { printf("%d\n", i); } } } getchar(); return 0; }
#include<stdio.h> /** * 输出数组 * @param array 待输出的数组 * @param len 待输出数组的长度 * @param state 数组的状态,例如:"排序前"和"排序后" * @return void */ void PrintArray(int array[],int len,char state[]) { int i; printf("%s\n",state); for(i = 0;i < len;i++) { printf("%d ",array[i]); } printf("\n"); } /** * 交换两个整数 * @param a 整数a的地址 * @param b 整数b的地址 * @return void */ void swap(int* a,int* b) { int temp; temp = *a; *a = *b; *b = temp; } /** * 简单选择排序 * @param array 待排序的数组 * @param len 待排序数组的长度 * @return void */ void SimpleSelectSort(int array[],int len) { int i,j; for(i = 0;i < len;i++) { for(j = i + 1;j < len;j++) { if(array[j] < array[i]) swap(&array[i],&array[j]); } } } int main() { int array[] = {10,9,8,7,6,5,4,3,2,1}; int len = sizeof(array) / sizeof(int); PrintArray(array,len,"简单选择排序前:"); SimpleSelectSort(array,len); PrintArray(array,len,"简单选择排序后:"); return 0; }
#pragma once #include "Core/Core.h" #include <yaml-cpp/yaml.h> #include <sstream> namespace Rocket { class ConfigLoader { public: ConfigLoader(const String& path) : m_Path(path) {} ~ConfigLoader() = default; int Initialize() { String config_file; #if defined(PLATFORM_LINUX) config_file = m_Path + "/Config/setting-linux.yaml"; #elif defined(PLATFORM_WINDOWS) config_file = m_Path + "/Config/setting-windows.yaml"; #elif defined(PLATFORM_APPLE) config_file = m_Path + "/Config/setting-mac.yaml"; #else RK_CORE_ASSERT(false, "Unknown Platform"); #endif m_ConfigMap["Path"] = YAML::LoadFile(config_file); config_file = m_Path + "/Config/setting-graphics.yaml"; m_ConfigMap["Graphics"] = YAML::LoadFile(config_file); config_file = m_Path + "/Config/setting-event.yaml"; m_ConfigMap["Event"] = YAML::LoadFile(config_file); return 0; } String GetAssetPath() { return m_ConfigMap["Path"]["asset_path"].as<String>(); } template<typename T> T GetConfigInfo(const String& category, const String& name) { return m_ConfigMap[category][name].as<T>(); } String ToString() const { std::stringstream ss; ss << "Config Path : " << m_Path; return ss.str(); } private: String m_Path; UMap<String, YAML::Node> m_ConfigMap; }; inline std::ostream& operator << (std::ostream &os, const ConfigLoader& c) { os << c.ToString(); return os; } }
// Created: 2001-05-21 // // Copyright (c) 2001-2013 OPEN CASCADE SAS // // This file is part of commercial software by OPEN CASCADE SAS, // furnished in accordance with the terms and conditions of the contract // and with the inclusion of this copyright notice. // This file or any part thereof may not be provided or otherwise // made available to any third party. // // No ownership title to the software is transferred hereby. // // OPEN CASCADE SAS makes no representation or warranties with respect to the // performance of this software, and specifically disclaims any responsibility // for any damages, special or consequential, connected with its use. #ifndef _GeomConvert_CurveToAnaCurve_HeaderFile #define _GeomConvert_CurveToAnaCurve_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Boolean.hxx> #include <Standard_Real.hxx> #include <TColgp_Array1OfPnt.hxx> #include <GeomConvert_ConvType.hxx> #include <GeomAbs_CurveType.hxx> class Geom_Curve; class Geom_Line; class gp_Lin; class gp_Pnt; class gp_Circ; class GeomConvert_CurveToAnaCurve { public: DEFINE_STANDARD_ALLOC Standard_EXPORT GeomConvert_CurveToAnaCurve(); Standard_EXPORT GeomConvert_CurveToAnaCurve(const Handle(Geom_Curve)& C); Standard_EXPORT void Init (const Handle(Geom_Curve)& C); //! Converts me to analytical if possible with given //! tolerance. The new first and last parameters are //! returned to newF, newL Standard_EXPORT Standard_Boolean ConvertToAnalytical (const Standard_Real theTol, Handle(Geom_Curve)& theResultCurve, const Standard_Real F, const Standard_Real L, Standard_Real& newF, Standard_Real& newL); Standard_EXPORT static Handle(Geom_Curve) ComputeCurve (const Handle(Geom_Curve)& curve, const Standard_Real tolerance, const Standard_Real c1, const Standard_Real c2, Standard_Real& cf, Standard_Real& cl, Standard_Real& theGap, const GeomConvert_ConvType theCurvType = GeomConvert_MinGap, const GeomAbs_CurveType theTarget = GeomAbs_Line); //! Tries to convert the given curve to circle with given //! tolerance. Returns NULL curve if conversion is //! not possible. Standard_EXPORT static Handle(Geom_Curve) ComputeCircle (const Handle(Geom_Curve)& curve, const Standard_Real tolerance, const Standard_Real c1, const Standard_Real c2, Standard_Real& cf, Standard_Real& cl, Standard_Real& Deviation); //! Tries to convert the given curve to ellipse with given //! tolerance. Returns NULL curve if conversion is //! not possible. Standard_EXPORT static Handle(Geom_Curve) ComputeEllipse (const Handle(Geom_Curve)& curve, const Standard_Real tolerance, const Standard_Real c1, const Standard_Real c2, Standard_Real& cf, Standard_Real& cl, Standard_Real& Deviation); //! Tries to convert the given curve to line with given //! tolerance. Returns NULL curve if conversion is //! not possible. Standard_EXPORT static Handle(Geom_Line) ComputeLine (const Handle(Geom_Curve)& curve, const Standard_Real tolerance, const Standard_Real c1, const Standard_Real c2, Standard_Real& cf, Standard_Real& cl, Standard_Real& Deviation); //! Returns true if the set of points is linear with given //! tolerance Standard_EXPORT static Standard_Boolean IsLinear (const TColgp_Array1OfPnt& aPoints, const Standard_Real tolerance, Standard_Real& Deviation); //! Creates line on two points. //! Resulting parameters returned Standard_EXPORT static gp_Lin GetLine(const gp_Pnt& P1, const gp_Pnt& P2, Standard_Real& cf, Standard_Real& cl); //! Creates circle on points. Returns true if OK. Standard_EXPORT static Standard_Boolean GetCircle(gp_Circ& Circ, const gp_Pnt& P0, const gp_Pnt& P1, const gp_Pnt& P2); //! Returns maximal deviation of converted surface from the original //! one computed by last call to ConvertToAnalytical Standard_Real Gap() const { return myGap; } //! Returns conversion type GeomConvert_ConvType GetConvType() const { return myConvType; } //! Sets type of convertion void SetConvType(const GeomConvert_ConvType theConvType) { myConvType = theConvType; } //! Returns target curve type GeomAbs_CurveType GetTarget() const { return myTarget; } //! Sets target curve type void SetTarget(const GeomAbs_CurveType theTarget) { myTarget = theTarget; } protected: private: Handle(Geom_Curve) myCurve; Standard_Real myGap; GeomConvert_ConvType myConvType; GeomAbs_CurveType myTarget; }; #endif // _GeomConvert_CurveToAnaCurve_HeaderFile
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end(), greater<int>()); vector<vector<int>> res; vector<int> ve; helper(0, target, res, ve, candidates); return res; } void helper(int pos, int target, vector<vector<int>> &res, vector<int> &ve, vector<int>& cands){ for(int i = pos; i < cands.size(); ++i){ int cand = cands[i]; if(cand > target) continue; ve.push_back(cand); int ans = target - cand; if(ans == 0){ res.push_back(ve); }else{ helper(i, ans, res, ve, cands); } ve.pop_back(); } } };
/* * main.cpp * * Created on: May 10, 2016 * Author: g33z */ #include <iostream> using namespace std; #include <stdio.h> #include <stdlib.h> #include "Point.h" int main(){ double ax,ay, bx,by, cx,cy; cout << "Punkt a.x:" << endl; cin >> ax; cout << "Punkt a.y:" << endl; cin >> ay; Point newXa(ax,ay); cout << "Punkt b.x:" << endl; cin >> bx; cout << "Punkt b.x:" << endl; cin >> by; Point newXb(bx,by); cout << "Punkt c.x:" << endl; cin >> cx; cout << "Punkt c.x:" << endl; cin >> cy; Point newXc(cx,cy); cout << "Computing..." << endl; cout << "Die Fläche des Dreiecks beträgt:" << endl << Point::computeArea(newXa,newXb,newXc); cout << "TEST!" << endl; Point A(ax,ay); Point B(bx,by); Point C = A + B; cout << "C: x = " << C.getX() << " und y = " << C.getY() << endl; return 0; }
#include <bits/stdc++.h> #define map guohezu using namespace std; const int maxn = 100; const int mov[16] = {1, 2, 2, 1, -1, 2, 2, -1, 1, -2, -2, 1, -1, -2, -2, -1}; int n, m, x, y, a, b, ans; int map[maxn][maxn]; int main() { cin >> n >> m >> x >> y; for (int i = 0; i < 8; i++) map[x + mov[2 * i]][y + mov[2 * i + 1]] = -1; if (n == 0 || m == 0) ans = 1; else if (n < 0 || m < 0) ans = 0; else { for (int i = 0; i <= max(n, m); i++) map[0][i] = 1, map[i][0] = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (map[i-1][j] == -1 && map[i][j-1] == -1) map[i][j] = -1; else if (map[i-1][j] == -1) map[i][j] = map[i][j-1]; else if (map[i][j-1] == -1) map[i][j] = map[i-1][j]; else map[i][j] = map[i-1][j] + map[i][j-1]; } } ans = map[n][m]; } cout << ans << endl; return 0; }
/* POJ2396 NetFlow with lower_bound , source-terminal. add fake-source and fake-terminal. possible solution algorithm not maxium one. */ #include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> using namespace std; #define NEWNODE &data[++datap] const int INF=99999999; const int MAXN=500; const int MAXM=500; const int MAXC=MAXN*MAXM*2; int N,M,C; int S,T,tot,Ss,St; struct node { int num,rest; node * next,* back; }; int d[MAXC]; int vd[MAXC]; node head[MAXC]; node data[MAXC*10]; int datap; int Nin[MAXC]; int Nout[MAXC]; int Hto[MAXC]; int Lto[MAXC]; int Cellto[MAXN][MAXM]; int a,b,lim; char c; int hsum[MAXC]; int lsum[MAXC]; node * toe[MAXC]; int tote; node * ans[MAXN][MAXM]; int Cmin[MAXN][MAXM]; int Cmax[MAXN][MAXM]; node * addit(int a,int b,int c) { node * temp=head[a].next; node * p=NEWNODE; head[a].next=p,p->next=temp; p->num=b,p->rest=c; return p; } node * addE(int a,int b,int c,int d)//c上界,d下界 { Nout[a]+=d,Nin[b]+=d; // 对于每个点,记录它的入值和出值 node * p1=addit(a,b,c-d); node * p2=addit(b,a,0); p1->back=p2; p2->back=p1; return p1; } int aug(int num,int rest) { if(num==St) return rest; int toflow=rest; int flowed; for(node * p=head[num].next;p;p=p->next) { if(p->rest) { if(d[p->num]==d[num]-1) { if(toflow<p->rest) flowed=aug(p->num,toflow); else flowed=aug(p->num,p->rest); toflow-=flowed; p->rest-=flowed; p->back->rest+=flowed; if(toflow==0) break; if(d[Ss]>=tot) return rest-toflow; } } } if(toflow==rest) { vd[d[num]]--; if(vd[d[num]]==0) d[Ss]=tot; d[num]++; vd[d[num]]++; } return rest-toflow; } int Sap() { memset(d,0,sizeof(d)); memset(vd,0,sizeof(vd)); int ans=0; vd[0]=tot; while(d[Ss]<tot) ans+=aug(Ss,INF); return ans; } void Maket() { for(int i=1;i<=N;i++) for(int j=1;j<=M;j++) Cmin[i][j]=0,Cmax[i][j]=INF; int p=0; for(int i=1;i<=N;i++) for(int j=1;j<=M;j++) Cellto[i][j]=++p; for(int i=1;i<=N;i++) Hto[i]=++p; for(int i=1;i<=M;i++) Lto[i]=++p; S=0,T=p+1; Ss=T+1,St=T+2; tot=St+1; // 设置基本的点编号 } void init() { memset(Nin,0,sizeof(Nin)); memset(Nout,0,sizeof(Nout)); memset(head,0,sizeof(head)); tote=0; datap=0; scanf("%d%d",&N,&M); Maket(); // 设置基本编号 for(int i=1;i<=N;i++) scanf("%d",&hsum[i]); for(int i=1;i<=M;i++) scanf("%d",&lsum[i]); // 行和与列和 scanf("%d",&C); // 要求 for(int i=1;i<=C;i++) { scanf("%d%d%s%d",&a,&b,&c,&lim); if(a==0&&b==0) { for(int i=1;i<=N;i++) for(int j=1;j<=M;j++) { int &Min=Cmin[i][j]; int &Max=Cmax[i][j]; if(c=='>') Min=max(lim+1,Min); else if(c=='=') Max=min(lim,Max),Min=max(lim,Min); else Max=min(lim-1,Max); } } else if(b==0) { for(int i=1;i<=M;i++) { int &Min=Cmin[a][i]; int &Max=Cmax[a][i]; if(c=='>') Min=max(lim+1,Min); else if(c=='=') Max=min(lim,Max),Min=max(lim,Min); else Max=min(lim-1,Max); } } else if(a==0) { for(int i=1;i<=N;i++) { int &Min=Cmin[i][b]; int &Max=Cmax[i][b]; if(c=='>') Min=max(lim+1,Min); else if(c=='=') Max=min(lim,Max),Min=max(lim,Min); else Max=min(lim-1,Max); } } else { int &Min=Cmin[a][b]; int &Max=Cmax[a][b]; if(c=='>') Min=max(lim+1,Min); else if(c=='=') Max=min(lim,Max),Min=max(lim,Min); else Max=min(lim-1,Max); } } for(int i=1;i<=N;i++) addE(S,Hto[i],hsum[i],hsum[i]); // 每行的要求 for(int i=1;i<=N;i++) for(int j=1;j<=M;j++) addE(Hto[i],Cellto[i][j],INF,0); // 行到点的边 for(int i=1;i<=N;i++) for(int j=1;j<=M;j++) ans[i][j]=addE(Cellto[i][j],Lto[j],Cmax[i][j],Cmin[i][j]); // 点到列的边 for(int i=1;i<=M;i++) addE(Lto[i],T,lsum[i],lsum[i]); // 列到终点的边 addE(T,S,INF,0); // 最后的 } void built() { for(int i=0;i<=T;i++) if(Nin[i]>Nout[i]) addE(Ss,i,Nin[i]-Nout[i],0); // 如果in > out , 连一天条从super source 到它的点 else toe[++tote]=addE(i,St,Nout[i]-Nin[i],0); // 如果小于,它到super terminal 的边 } bool check() { for(node * p=head[Ss].next;p;p=p->next) if(p->rest) return 0; for(int i=1;i<=tote;i++) if(toe[i]->rest) return 0; // super source, terminal都必须是满流边 return 1; } int Q; int main() { cin>>Q; for(int q=1;q<=Q;q++) { init(); built(); Sap(); if(check()) { for(int i=1;i<=N;i++,printf("\n")) { printf("%d",ans[i][1]->back->rest+Cmin[i][1]); for(int j=2;j<=M;j++) printf(" %d",ans[i][j]->back->rest+Cmin[i][j]); } printf("\n"); } else printf("IMPOSSIBLE\n"); } return 0; }
#include <QtWidgets/QApplication> #include <QtWidgets/QWidget> #include <QDebug> #include <QtWidgets/QGridLayout> #include "ui/LoginWidget/loginwidget.h" #include "ui/Viewer/Viewer.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Viewer viewer; viewer.runApp(); return a.exec(); }
#ifndef PIECE_H #define PIECE_H #include <QGraphicsPixmapItem> class Piece : public QGraphicsPixmapItem { public: enum couleurPiece {pieceNeutre=0, pieceRond, pieceCroix}; explicit Piece(); // explicit Piece(couleurPiece couleur, int16_t x, int16_t y); int16_t x; int16_t y; bool estJouable(couleurPiece couleurSelect, couleurPiece couleurJoueur); // revoir protected: // void mousePressEvent(QGraphicsSceneMouseEvent * event); private: std::vector<QPixmap *> pixmapCollection; couleurPiece couleur; }; #endif // PIECE_H
/* ==general== This script uses the non-volatile storage of esp32 to store key value pairs. These can be accessed via BLE-connection (read and/or write). ==BLE== BLE part Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleWrite.cpp Ported to Arduino ESP32 by Evandro Copercini edited by ernst (ernst@teco.edu) ==NVS== ESP32 key value store with Preferences library. uses the Preferences library to store key value pairs in non-volatile storage on ESP32 processor. created for arduino-esp32 09 Jul 2018 by Felix Ernst (ernst(at)teco.edu) namespace limited to 15 chars key name limited to 15 chars ==WATCHDOG== the BLE stack is not stable and stops advertising after a random time between some minutes and some hours the watchdog reboots the ESP if no device reads the sensor values (PM10 values) last edits: 11.11.19 by Arash Torabi & Farima Narimani (torabi@teco.edu) */ #include "src/lib/ArduinoJson/ArduinoJson.h" #include <BLE2902.h> #include <sstream> //c++ libary to use std::string #include <sdkconfig.h> #include <BLEDevice.h> #include <BLEUtils.h> #include <BLEServer.h> #include <BLEDescriptor.h> #include <Preferences.h> #include "Arduino.h" #include "bleobjects.h" #include "nvscallback.h" #include "sensor.h" #include "watchdog.h" #include "datadescription.h" #include "connectCallback.h" #include<U8g2lib.h> U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 15, /* data=*/ 4, /* reset=*/ 16); #define duster1_width 92 #define duster1_height 64 static const unsigned char duster1_bits[] PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x03, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x07, 0x00, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x87, 0xAA, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0xA0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xC0, 0x07, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x3A, 0x00, 0x00, 0x00, 0xE0, 0x00, 0x00, 0xE0, 0x00, 0x00, 0x00, 0x80, 0xC5, 0x05, 0x00, 0x00, 0x70, 0x00, 0x00, 0xC0, 0x07, 0x00, 0x00, 0x80, 0x00, 0x0E, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0x40, 0x11, 0x1D, 0x00, 0x7F, 0x1F, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x80, 0xEF, 0x06, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0xF8, 0x1F, 0xD1, 0xC1, 0xD7, 0x03, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0xAE, 0xFA, 0x02, 0xA2, 0xAB, 0x01, 0x00, 0xE0, 0x20, 0x60, 0x00, 0x00, 0xFF, 0xFF, 0x5F, 0xFD, 0xD7, 0xC1, 0x01, 0xF0, 0x77, 0xE0, 0x00, 0x00, 0xAB, 0xAA, 0x3A, 0xB8, 0xE2, 0x80, 0x00, 0xE0, 0x3F, 0xC0, 0x00, 0xC0, 0x77, 0x77, 0xF7, 0x7D, 0x75, 0xC0, 0x01, 0xE0, 0x3F, 0xC0, 0x01, 0xE0, 0xAA, 0xAA, 0xAA, 0xEE, 0x28, 0xE0, 0x03, 0xE0, 0x1F, 0x80, 0x01, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x35, 0xF0, 0x0F, 0xC0, 0x1F, 0x00, 0x03, 0xE8, 0xAA, 0xAA, 0xAA, 0xAE, 0x38, 0xF8, 0x0A, 0xE0, 0x3F, 0x00, 0x03, 0xFC, 0xDD, 0xDD, 0xDD, 0xFF, 0x1D, 0x78, 0x00, 0xF0, 0x3F, 0x00, 0x07, 0xBE, 0xAA, 0xAA, 0xAA, 0xBA, 0x1A, 0x38, 0x00, 0xF8, 0x3E, 0x00, 0x02, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x1D, 0x7C, 0x00, 0x70, 0x7C, 0x00, 0x06, 0xBA, 0xAA, 0xAA, 0xAA, 0xBA, 0x0A, 0x38, 0x00, 0x00, 0x00, 0x00, 0x06, 0x7F, 0x77, 0x77, 0x77, 0x77, 0x1D, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x06, 0xBE, 0xAA, 0xAA, 0xAA, 0xBA, 0x0C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x0E, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0D, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x04, 0xBE, 0xAA, 0xAA, 0xAA, 0xAA, 0x0C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x0C, 0xFF, 0xDD, 0xDD, 0xDD, 0x5F, 0x0D, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x0C, 0xBF, 0xAA, 0xAA, 0xAA, 0xBA, 0x0E, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x0E, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1D, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x04, 0xBA, 0xAA, 0xAA, 0xAA, 0xBA, 0x0A, 0x3C, 0x00, 0xA0, 0x2F, 0x00, 0x06, 0x7F, 0x77, 0x77, 0x77, 0x77, 0x1D, 0x7C, 0x00, 0xF0, 0x7F, 0x00, 0x06, 0xBE, 0xAA, 0xAA, 0xAA, 0xBE, 0x08, 0x38, 0x00, 0x38, 0xE8, 0x00, 0x06, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1D, 0x7C, 0x00, 0x1C, 0xFF, 0x01, 0x07, 0xAE, 0xAA, 0xAA, 0xAA, 0xAE, 0x18, 0xF8, 0x08, 0x0E, 0xFE, 0x03, 0x02, 0xFC, 0xDD, 0xDD, 0xDD, 0xFD, 0x1D, 0xF8, 0x0F, 0x06, 0x7F, 0x03, 0x03, 0xFC, 0xAA, 0xAA, 0xAA, 0xAA, 0x3A, 0xF0, 0x03, 0x06, 0x7F, 0x83, 0x03, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x75, 0xF0, 0x01, 0x1E, 0xFF, 0xC1, 0x01, 0xB8, 0xAA, 0xAA, 0xAA, 0xBB, 0x62, 0x80, 0x01, 0x38, 0xE8, 0x80, 0x01, 0xF0, 0x77, 0x77, 0xF7, 0xF5, 0xF5, 0x80, 0x01, 0xF8, 0xFF, 0xC0, 0x01, 0xE0, 0xAB, 0xAA, 0x3E, 0xE8, 0xEA, 0x80, 0x00, 0xE0, 0x3F, 0xE0, 0x00, 0x00, 0xFF, 0xFF, 0x17, 0xC7, 0xD7, 0x01, 0x00, 0x00, 0x05, 0x70, 0x00, 0x00, 0xAC, 0xBE, 0x80, 0x80, 0x8F, 0x03, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0xF0, 0x15, 0x71, 0x00, 0x7F, 0x07, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x40, 0x00, 0x38, 0x00, 0x38, 0x0E, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0xC0, 0x55, 0x07, 0x00, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x80, 0xA2, 0x02, 0x00, 0x00, 0x38, 0x00, 0x00, 0x80, 0x03, 0x00, 0x00, 0x00, 0x7F, 0x00, 0x00, 0x00, 0xF0, 0x01, 0x00, 0xF0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x0F, 0x00, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xD5, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE8, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x5F, 0x00, 0x00, 0x00, }; #define duster2_width 93 #define duster2_height 64 static const unsigned char duster2_bits[] PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x00, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8E, 0xBE, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBE, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x40, 0x1F, 0x00, 0xF4, 0x01, 0x00, 0x00, 0x00, 0xFE, 0x03, 0x00, 0x00, 0x80, 0x03, 0x00, 0x80, 0x03, 0x00, 0x00, 0x00, 0xD7, 0x1F, 0x00, 0x00, 0xF0, 0x01, 0x00, 0x00, 0x07, 0x00, 0x00, 0x80, 0x01, 0x3E, 0x00, 0x68, 0x38, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0xC0, 0x01, 0xF0, 0x01, 0xFF, 0x1D, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0xE0, 0x0A, 0xE0, 0x83, 0x8F, 0x0F, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0xF8, 0xFF, 0x81, 0xC7, 0x0F, 0x07, 0x00, 0x40, 0x00, 0x70, 0x00, 0x00, 0x3C, 0xE8, 0x0B, 0xFE, 0x07, 0x03, 0x00, 0xC0, 0xE3, 0xE0, 0x00, 0x00, 0x1E, 0x40, 0x7F, 0xFC, 0xC5, 0x63, 0x00, 0xC0, 0xF7, 0xC1, 0x01, 0x00, 0x02, 0x00, 0xF8, 0xB3, 0x82, 0x61, 0x00, 0xC0, 0xFF, 0x80, 0x03, 0xC0, 0x07, 0x00, 0xC0, 0xFF, 0xC2, 0xF1, 0x00, 0xC0, 0x7F, 0x00, 0x07, 0xE0, 0x03, 0x00, 0x00, 0xBE, 0xE2, 0xF8, 0x00, 0x80, 0x3F, 0x00, 0x02, 0xF0, 0x01, 0x00, 0x00, 0x5C, 0x71, 0xFC, 0x01, 0x80, 0x7F, 0x00, 0x07, 0x98, 0x00, 0x00, 0x00, 0x48, 0x60, 0xE8, 0x03, 0x80, 0x7F, 0x00, 0x0E, 0xDC, 0x01, 0x00, 0x00, 0x5C, 0x71, 0xC0, 0x07, 0xF0, 0x7F, 0x00, 0x0C, 0xCC, 0x00, 0x00, 0x00, 0x28, 0x31, 0x80, 0x03, 0xE0, 0xF8, 0x00, 0x0C, 0xCC, 0x00, 0x00, 0x00, 0x6C, 0x31, 0xC0, 0x07, 0x60, 0x70, 0x00, 0x1C, 0xCE, 0x00, 0x00, 0x00, 0x2C, 0x31, 0x80, 0x07, 0x00, 0x00, 0x00, 0x08, 0x46, 0x00, 0x00, 0x00, 0x64, 0x11, 0x00, 0x07, 0x00, 0x00, 0x00, 0x1C, 0xE6, 0x00, 0x00, 0x00, 0x2E, 0x18, 0x80, 0x0F, 0x00, 0x00, 0x00, 0x08, 0x66, 0x00, 0x00, 0x00, 0x24, 0x19, 0x00, 0x07, 0x00, 0x00, 0x00, 0x1C, 0x66, 0x00, 0x00, 0x00, 0x2E, 0x18, 0x80, 0x0F, 0x00, 0x00, 0x00, 0x08, 0x66, 0x00, 0x00, 0x00, 0x24, 0x19, 0x00, 0x07, 0x00, 0x00, 0x00, 0x1C, 0x66, 0x00, 0x00, 0x00, 0x2E, 0x18, 0x80, 0x0F, 0x00, 0x00, 0x00, 0x08, 0x66, 0x00, 0x00, 0x00, 0x6C, 0x19, 0x00, 0x07, 0x00, 0x04, 0x00, 0x1C, 0x66, 0x00, 0x00, 0x00, 0x2C, 0x39, 0x80, 0x0F, 0x80, 0x3F, 0x00, 0x08, 0x46, 0x00, 0x00, 0x00, 0x6C, 0x31, 0x80, 0x07, 0xF0, 0xFF, 0x01, 0x1C, 0xEE, 0x00, 0x00, 0x00, 0x2C, 0x31, 0x80, 0x07, 0xB8, 0xA0, 0x03, 0x0C, 0xCC, 0x00, 0x00, 0x00, 0x5C, 0x71, 0xC0, 0x07, 0x1C, 0x7C, 0x07, 0x0C, 0xCC, 0x00, 0x00, 0x00, 0x48, 0x20, 0xE8, 0x03, 0x08, 0xFE, 0x06, 0x0E, 0xDC, 0x01, 0x00, 0x00, 0x58, 0x71, 0xF8, 0x03, 0x1C, 0xFE, 0x07, 0x06, 0x98, 0x00, 0x00, 0x00, 0xB8, 0x62, 0xF0, 0x03, 0x08, 0xFE, 0x06, 0x02, 0xD8, 0x01, 0x00, 0x00, 0xFC, 0xC2, 0xF0, 0x01, 0x1C, 0x7C, 0x07, 0x07, 0xB0, 0x03, 0x00, 0x80, 0xBF, 0x82, 0xE0, 0x00, 0x38, 0xA0, 0x03, 0x03, 0xF0, 0x07, 0x00, 0xF0, 0xF7, 0xC5, 0x41, 0x00, 0xF0, 0xFF, 0xC1, 0x01, 0xE0, 0x07, 0x00, 0xFE, 0xF8, 0x85, 0xE3, 0x00, 0x80, 0x3F, 0xC0, 0x00, 0x00, 0x1F, 0xD0, 0x1F, 0xDF, 0x0F, 0x07, 0x00, 0x00, 0x14, 0xC0, 0x01, 0x00, 0xF8, 0xFF, 0x82, 0x83, 0x8F, 0x0F, 0x00, 0x00, 0x00, 0xE0, 0x00, 0x00, 0xF0, 0x5F, 0xF0, 0x01, 0xFF, 0x1D, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x80, 0x01, 0xF8, 0x00, 0xF8, 0x38, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x80, 0x03, 0x7F, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0xAB, 0x0B, 0x00, 0x00, 0xE0, 0x00, 0x00, 0x80, 0x03, 0x00, 0x00, 0x00, 0xFF, 0x01, 0x00, 0x00, 0xC0, 0x07, 0x00, 0xC0, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x80, 0x0E, 0x00, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xD5, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5D, 0x01, 0x00, 0x00, }; #define sad_width 127 #define sad_height 35 static const unsigned char sad_bits[] PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x7F, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x01, 0x00, 0x00, 0xF0, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0x00, 0x00, 0xF8, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x07, 0x00, 0x00, 0xF8, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x07, 0x00, 0x1E, 0xFC, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x0F, 0x1C, 0x3E, 0xFC, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x0F, 0x3E, 0xFF, 0xFE, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x0F, 0x7F, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xDF, 0x7F, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x7F, 0xFE, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x3F, 0xFC, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x1F, 0xF8, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x0F, 0xF0, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x07, 0xC0, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0x03, 0x80, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x7F, 0x00, 0x00, 0xFC, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x1F, 0x00, 0x00, 0xF8, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x0F, 0x00, 0x00, 0xC0, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, }; #define happy_width 127 #define happy_height 39 static const unsigned char happy_bits[] PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x01, 0x00, 0x00, 0xC0, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x03, 0x00, 0x00, 0xE0, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x07, 0x00, 0x00, 0xF8, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x1F, 0x04, 0x00, 0xF8, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x7F, 0x07, 0x20, 0xFC, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0x1F, 0xF8, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0x3F, 0xFC, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0x3F, 0xFE, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0x7F, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0x1F, 0xFE, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0x0F, 0xFC, 0x9F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x01, 0x00, 0xE0, 0x03, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x01, 0x00, 0x00, 0x00, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0xC0, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; void draw_duster(uint8_t bleOn) { if (bleOn) { u8g2.setFont(u8g2_font_9x18B_tf); u8g2.setFontRefHeightExtendedText(); u8g2.setFontPosTop(); u8g2.setFontDirection(0); u8g2.drawStr(20, 25, "CONNECTED"); //u8g2.drawXBMP(10, 0, duster1_width, duster1_height, duster1_bits); //u8g2.drawXBMP(0, 10, happy_width, happy_height, happy_bits); } else { u8g2.setFont(u8g2_font_9x18B_tf); u8g2.setFontRefHeightExtendedText(); u8g2.setFontPosTop(); u8g2.setFontDirection(0); u8g2.drawStr(10, 25, "NOT CONNECTED!"); //u8g2.drawXBMP(10, 0, duster2_width, duster2_height, duster2_bits); //u8g2.drawXBMP(0, 10, sad_width, sad_height, sad_bits); } } /* Setup part */ void setup() { // Display u8g2.begin(); u8g2.firstPage(); do { draw_duster(0); } while ( u8g2.nextPage() ); // make serial monitor printing available Serial.begin(115200); /* BLE */ // initialise with name of ble device BLEDevice::init(DEVICE_NAME); //initialise bleServer pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); // initialise bleService pDustService = pServer->createService(DUST_SERVICE_UUID); pMetadataService = pServer->createService(METADATA_SERVICE_UUID); // initialise bleCharacteristic for config pMetadataCharacteristic = pMetadataService->createCharacteristic( METADATA_CHARACTERISTIC_UUID, // set the properties, only read possible too BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE ); // initialise bleCharacteristic for sds011 sensor pDataCharacteristic = pDustService->createCharacteristic( DATA_CHARACTERISTIC_UUID, // set the properties, only read possible too BLECharacteristic::PROPERTY_READ ); // initialise bleCharacteristic for sds011 sensor pDataDescriptionCharacteristic = pDustService->createCharacteristic( DATADESCRIPTION_CHARACTERISTIC_UUID, // set the properties, only read possible too BLECharacteristic::PROPERTY_READ ); // initialise bleCharacteristic for watchdog pNotifyCharacteristic = pDustService->createCharacteristic( NOTIFY_CHARACTERISTIC_UUID, // set the properties, only read possible too BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY | BLECharacteristic::PROPERTY_INDICATE ); pNotifyDescriptor2902 = new BLE2902(); pNotifyCharacteristic->addDescriptor(pNotifyDescriptor2902); // create JSON for descriptor which contains sensor meta data like units etc // default values, TODO: change that it checks if there is a value, if not use default value // create Json buffer. inside brackets: size of the pool in bytes. // Use arduinojson.org/assistant to compute the capacity. StaticJsonBuffer<1024> jsonBuffer_desc; //TODO set a good buffer size // create json root object JsonObject& description_json = jsonBuffer_desc.createObject(); // create nested objects inside root object JsonObject& pm10_desc = description_json.createNestedObject("PM10"); JsonObject& pm25_desc = description_json.createNestedObject("PM25"); JsonObject& temp_desc = description_json.createNestedObject("TEMP"); JsonObject& hum_desc = description_json.createNestedObject("HUM"); JsonObject& atm_desc = description_json.createNestedObject("ATM"); // add values to nested objects pm10_desc["UNIT"] = pm10_unit; pm25_desc["UNIT"] = pm25_unit; temp_desc["UNIT"] = temp_unit; hum_desc["UNIT"] = hum_unit; atm_desc["UNIT"] = atm_unit; pm10_desc["NAME"] = pm10_name; pm25_desc["NAME"] = pm25_name; temp_desc["NAME"] = temp_name; hum_desc["NAME"] = hum_name; atm_desc["NAME"] = atm_name; char description_json_char[512]; //TODO set maximum size of char here // create a char out of the json object description_json.printTo(description_json_char); pDataDescriptionCharacteristic->setValue(description_json_char); // Serial.println(description_json_char); // initialize characteristics pDataCharacteristic->setValue(String(-1).c_str()); // notify characteristic notifies random values, just used to trigger reading in android app pNotifyCharacteristic->setValue("0"); //callback to do something when a value is written or read //TODO ensure that key is not longer than 14 const char* configkey = "config"; nvsCallback *pMetadataCallback = new nvsCallback(configkey); pMetadataCharacteristic->setCallbacks(pMetadataCallback); watchdogCallback *pwatchdogCallback = new watchdogCallback(); pDataCharacteristic->setCallbacks(pwatchdogCallback); pDustService->start(); pMetadataService->start(); // start advertising, so the device can be found pAdvertising = pServer->getAdvertising(); pAdvertising->start(); //SDS_SERIAL.begin(9600); sds.begin(&SDS_SERIAL, 12, 17); // initialize SDS011 sensor /* watchdog setup hardware timer is set, if timer runs out, reboot is triggered */ if (enable_wd == true) { timer = timerBegin(0, 80, true); //timer 0, div 80, initialise hardware timer timerAttachInterrupt(timer, &resetModule, true); //attach callback timerAlarmWrite(timer, wdtTimeout * 1000, false); //set time in us timerAlarmEnable(timer); } } void loop() { if (!deviceConnected) { u8g2.firstPage(); do { draw_duster(0); } while ( u8g2.nextPage() ); Serial.println("Not Connectet"); delay(100); } else { u8g2.firstPage(); do { draw_duster(1); } while ( u8g2.nextPage() ); Serial.print("Connected"); //delay(10); int sdsError = sdsRead(); if (!sdsError) { // default values, TODO: change that it checks if there is a value, if not use default value float temp = -1000; float hum = -1; float atm = -1; // create Json buffer. inside brackets: size of the pool in bytes. // Use arduinojson.org/assistant to compute the capacity. StaticJsonBuffer<1024> jsonBuffer; //TODO set a good buffer size // create json object JsonObject& data_values = jsonBuffer.createObject(); // add all key-value pairs to json object data_values["PM10"] = pm10; data_values["PM25"] = pm25; data_values["TEMP"] = temp; data_values["HUM"] = hum; data_values["ATM"] = atm; char data_values_char[512]; //TODO set maximum size of char here // create a char out of the json object data_values.printTo(data_values_char); Serial.println(data_values_char); pDataCharacteristic->setValue(data_values_char); // notify characteristic changes value between "0" and "1", only to trigger reading in android app if (pNotifyCharacteristic->getValue() == "0") { pNotifyCharacteristic->setValue("1"); } else { pNotifyCharacteristic->setValue("0"); } pNotifyCharacteristic->notify(); } //delay(10); // 100ms => f = 10/s } }
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int getNum(int have, int m) { if(have <= m) { return 1; } else if(have % m) { return have / m + 1; } else { return have / m; } } int main() { int n = 0; int m = 0; string temp; int numY = 0; int numB = 0; int numG = 0; int res = 0; std::vector<string> stringArr; // input cin>>n>>m; for(int i = 0; i < n; i++) { cin>>temp; stringArr.push_back(temp); } // compute for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(stringArr[i][j] == 'Y') { numY++; } else if(stringArr[i][j] == 'B') { numB++; } else if(stringArr[i][j] == 'G') { numG++; } } } res = max(getNum(numY, m), getNum(numB, m)); res = max(res, numG) + 1; // res += getNum(numY, m); // res += getNum(numB, m); // output cout<<res<<endl; return 0; }
/** * @author shaoDong * @email scut_sd@163.com * @create date 2018-08-27 07:43:16 * @modify date 2018-08-27 07:43:16 * @desc 小红有两个长度为n的排列A和B。每个排列由[1,n]数组成,且里面的数字都是不同的。 现在要找到一个新的序列C,要求这个新序列中任意两个位置(i,j)满足: 如果在A数组中C[i]这个数在C[j]的后面,那么在B数组中需要C[i]这个数在C[j]的前面。 请问C序列的长度最长为多少呢? */ #include <iostream> #include <vector> #include <algorithm> using namespace std; // 判断将a 加入arr 后能否让其中的所有元素对满足条件 bool isFine(vector<int> &arr, int a, vector<int> arrA, vector<int> arrB) { for(vector<int>::iterator it = arr.begin(); it != arr.end(); it++) { // find 方法可以在vector 中找到指定的值 if((find(arrA.begin(), arrA.end(), *it) > find(arrA.begin(), arrA.end(), a) && find(arrB.begin(), arrB.end(), *it) < find(arrB.begin(), arrB.end(), a)) || (find(arrA.begin(), arrA.end(), *it) < find(arrA.begin(), arrA.end(), a) && find(arrB.begin(), arrB.end(), *it) > find(arrB.begin(), arrB.end(), a))) { continue; } else { return false; } } arr.push_back(a); return true; } int printVec(vector<int> arr) { for(vector<int>::iterator it = arr.begin(); it != arr.end(); it++) { cout<<*it<<" "; } cout<<endl; return 0; } int main(int argc, char const *argv[]) { int n, temp, output; vector<int> arrA, arrB, middle, res; // 输入 cin>>n; for(int i = 0; i < n; i++) { cin>>temp; arrA.push_back(temp); } for(int i = 0; i < n; i++) { cin>>temp; arrB.push_back(temp); } // 对于每一个元素,判断是否可以与其他元素共同存在于C 序列中 for(vector<int>::iterator it = arrA.begin(); it != arrA.end(); it++) { middle.push_back(*it); for(vector<int>::iterator it2 = arrA.begin(); it2 != arrA.end(); it2++) { if(it2 != it) { isFine(middle, *it2, arrA, arrB); } } res.push_back(middle.size()); middle.clear(); } // 找到最长序列值 output = res[0]; for(vector<int>::iterator it = res.begin(); it != res.end(); it++) { if(*it > output) { output = *it; } } cout<<output<<endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) Opera Software ASA 2008 * * @author Daniel Spang */ #ifndef ES_BLOCK_H #define ES_BLOCK_H #include "modules/util/simset.h" template <class T> class ES_Block; template <class T> class ES_BlockItemIterator; class ES_Execution_Context; template <class T> class ES_BlockHead : public AutoDeleteHead { friend class ES_BlockItemIterator<T>; public: ES_BlockHead(unsigned initial_capacity, BOOL prefill = FALSE, T prototype = T()); OP_STATUS Initialize(ES_Execution_Context *context); void Reset(); OP_STATUS Allocate(ES_Execution_Context *context, T *&item, unsigned size = 1); OP_STATUS Allocate(ES_Execution_Context *context, BOOL &first_in_block, T *&item, unsigned size, unsigned overlap, unsigned copy); /**< Allocate new items. @param[out] first_in_block is TRUE if allocated in new underlying block. Pass this to Free to make it behave correctly. @param[out] item pointer to the newly allocated block. @param[in] size number of items to allocate. @param[in] overlap how many items this allocation should overlap with previous. @param[in] copy how many items are important for the new block. I.e., if we have to allocate a new block to satisfy the allocation copy this amount of items to the new block. */ void Free(unsigned size = 1); void Free(unsigned size, unsigned overlap, unsigned copy, BOOL first_in_block = FALSE); /**< Free the last allocation of items. Size must match the size of allocation. */ void Shrink(unsigned size); /**< Shrink the current allocation by size. */ void Trim(); /**< Deallocate unused blocks. */ void LastItem(T *&item); T *Limit() { return last_used_block->Storage() + last_used_block->Capacity(); } ES_Block<T> *GetLastUsedBlock() { return last_used_block; } unsigned TotalUsed() { return total_used; } void IncrementTotalUsed(unsigned value) { total_used += value; } void DecrementTotalUsed(unsigned value) { total_used -= value; } protected: ES_BlockHead(); // Prevent usage of default constructor. OP_STATUS AllocateInNextBlock(ES_Execution_Context *context, T *&item, unsigned size, unsigned overlap, unsigned copy); OP_STATUS AllocateBlock(ES_Execution_Context *context, unsigned min_size, ES_Block<T> *follows = NULL); /**< Allocate a new block that is of size min_size large or grow_ratio times bigger than the last allocated block. */ ES_Block<T> *last_used_block; unsigned next_capacity; /**< Size of next allocated block. */ unsigned extra_capacity; /**< Number of extra elements to allocate in each block. */ enum { grow_ratio = 2 }; BOOL prefill; /**< Prefill items with prototype_item if true. */ T prototype_item; unsigned total_used; #ifdef ES_DEBUG_BLOCK_USAGE class DebugItemInfo : public Link { public: DebugItemInfo(unsigned size = 1, unsigned overlap = 0, BOOL first_in_block = TRUE) : size(size), overlap(overlap), first_in_block(first_in_block) {} unsigned size; unsigned overlap; BOOL first_in_block; }; Head debug_stack; #endif // ES_DEBUG_BLOCK_USAGE }; template <class T> class ES_Block : public Link { friend class ES_BlockHead<T>; public: ES_Block(unsigned capacity) : used(0), capacity(capacity) {} OP_STATUS Initialize(ES_Execution_Context *context, unsigned extra_capacity); void Reset(); ~ES_Block(); void Allocate(T *&item, unsigned size); void Free(unsigned size); unsigned Available() { return capacity - used; } unsigned Used() { return used; } unsigned Capacity() { return capacity; } T *Storage() { return storage; } void Populate(T prototype_item); void SetUsed(unsigned new_used) { used = new_used; } private: ES_Execution_Context *context; T *storage; unsigned used; unsigned capacity, total_capacity; }; template <class T> class ES_BlockItemIterator { public: ES_BlockItemIterator(ES_BlockHead<T> *block_head, BOOL set_to_end = TRUE); ES_BlockItemIterator<T> *Prev(); T *GetItem() { return current; } private: T *current; ES_Block<T> *current_block; }; #endif // ES_BLOCK_H
#include "CImg.h" #include "Info.h" #include <map> #include <bitset> #include <vector> using namespace cimg_library; using std::string; std::map<string, string> parseCMD(int argc, char *argv[]); template<typename T> int getKey(CImg<T>& img) { std::bitset<keySpace> bitKey; for (int i = 0; i < keySpace; i++) { bitKey[i] = img.atXYZC(i, 0, 0, 0); } return static_cast<int>(bitKey.to_ulong()); } template<typename T> void rotateDecrypt(CImg<T>& img, int const rotateKey) { std::vector<int> bitDepths = {8, 24, 48}; T secretMask = bitMax(rotateKey); cimg_forXYZC(img, x, y, z, v) { img.atXYZC(x, y, z, v) &= secretMask; } img.normalize(0, bitMax(*std::upper_bound(bitDepths.begin(), bitDepths.end(), rotateKey))); }
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> #include <cassert> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; struct tp { int x, y; } a[155555]; bool bydiff(const tp& a, const tp& b) { return a.x - a.y > b.x - b.y; } bool byX(const tp& a, const tp& b) { return a.x < b.x; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); int T; scanf("%d", &T); while (T--) { int n, k; scanf("%d%d", &n, &k); for (int i = 0; i < n; ++i) { scanf("%d%d", &a[i].x, &a[i].y); } sort(a, a + n, byX); int left = 0; int right = 1e6 + 1; while (left < right) { int center = (left + right + 1) / 2; //cerr << center << endl; vector<LL> f1(n), f2; for (int i = 0; i < n; ++i) f1[i] = a[i].y; for (int it = 1; it <= k; ++it) { f2.assign(n, 1e18); LL mi = 1e18; for (int i = 0; i < n; ++i) { if (i > 0 && f1[i - 1] + center <= a[i - 1].x) mi = min(mi, f1[i - 1]); f2[i] = mi + a[i].y; } f1.swap(f2); } bool fnd = 0; for (int i= 0; i < n; ++i) if (f1[i] + center <= a[i].x) { fnd = 1; break; } if (fnd) left = center;else right = center - 1; } printf("%d\n", left); } return 0; }
#include <iostream> template<typename T> class Matrix; template<typename T> class Vector { T v[4]; public: template<typename U> friend Vector<U> operator*(Matrix<U> const&, Vector<U> const&); }; template<typename T> class Matrix { Vector<T> v[4]; public: template<typename U> friend Vector<U> operator*(Matrix<U> const&, Vector<U> const&); }; template<typename T> Vector<T> operator*(Matrix<T> const& m, Vector<T> const& v) { Vector<T> r; return r; } int main() { }
#include "menu.h" #include "ui_menu.h" menu::menu(QWidget *parent) : QMainWindow(parent), ui(new Ui::menu) { ui->setupUi(this); } menu::~menu() { delete ui; } void menu::on_smasuk_clicked() { sm.resize(1366,768); this->close(); if(QGuiApplication::primaryScreen()->geometry().height() > 768 || QGuiApplication::primaryScreen()->geometry().width() > 1366) sm.show(); else sm.showMaximized(); } void menu::on_skeluar_clicked() { sk.resize(1366,768); this->close(); if(QGuiApplication::primaryScreen()->geometry().height() > 768 || QGuiApplication::primaryScreen()->geometry().width() > 1366) sk.show(); else sk.showMaximized(); }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "Stucchi.h" #include "StucchiGameMode.h" #include "StucchiPawn.h" AStucchiGameMode::AStucchiGameMode(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { // set default pawn class to our character class DefaultPawnClass = AStucchiPawn::StaticClass(); }
#include <iostream> using namespace std; typedef unsigned long ulong; bool IsBouncy (ulong num); int main() { ulong bouncyNumCnt = 0; ulong n; long double ratio = 0; for (n = 99; 100*bouncyNumCnt < 99*n; n++) { if (IsBouncy (n)) bouncyNumCnt++; } cout << n; return 0; } bool IsBouncy (ulong num) { int prevDigit, digit; bool increasing = false, decreasing = false; prevDigit = num%10; while(num /= 10) { digit = num%10; if (digit > prevDigit) decreasing = true; if (digit < prevDigit) increasing = true; if (increasing && decreasing) return true; else prevDigit = digit; } return false; }
class TimeBomb: CA_Magazine { scope = 1; displayName = "$STR_MN_TIME_BOMB"; picture = "\CA\weapons\data\equip\m_satchel_CA.paa"; useAction = 1; useActionTitle = "$STR_ACTION_PUTBOMB"; type = 256; value = 5; ammo = "TimeBomb"; count = 1; initSpeed = 0; maxLeadSpeed = 0; nameSoundWeapon = "satchelcharge"; nameSound = "satchelcharge"; sound[] = {"\ca\Weapons\Data\Sound\gravel_L",0.00031622776,1,10}; descriptionShort = "$STR_DSS_TimeBomb"; }; class Mine: TimeBomb { scope = 2; type = 256; displayName = $STR_MN_MINE; picture = "\CA\weapons\data\equip\m_AT15_ca.paa"; ammo = "Mine"; nameSoundWeapon = "mine"; nameSound = "mine"; descriptionShort = $STR_DSS_MINE; }; class MineE: TimeBomb { scope = 2; type = 256; displayName = $STR_MN_MINE; picture = "\CA\weapons\data\equip\m_TM46_ca.paa"; ammo = "MineE"; nameSoundWeapon = "mine"; descriptionShort = $STR_DSS_MINE_E; }; class PipeBomb: TimeBomb { scope = 2; displayName = $STR_DZ_MAG_SATCHEL_NAME; // Singular "Satchel Charge" for death messages "with a x" descriptionShort = $STR_DSS_Pipe_Bomb; type = 256; picture = "\CA\weapons\data\equip\m_satchel_CA.paa"; model = "\z\addons\dayz_epoch_w\magazine\dze_satchel.p3d"; value = 5; ammo = "PipeBomb"; count = 1; initSpeed = 0; maxLeadSpeed = 0; nameSoundWeapon = "satchelcharge"; nameSound = "satchelcharge"; useAction = 1; useActionTitle = "$STR_ACTION_PUTBOMB"; }; class ItemC4Charge : CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_C4_CHARGE; descriptionShort = $STR_EPOCH_C4_CHARGE_DESC; model = "\ca\weapons\explosive.p3d"; picture = "\z\addons\dayz_communityassets\pictures\carbomb.paa"; }; class ItemCarBomb : CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_ITEM_NAME_equip_carbomb; model = "\ca\weapons\explosive.p3d"; picture = "\z\addons\dayz_communityassets\pictures\carbomb.paa"; descriptionShort = $STR_ITEM_DESC_equip_carbomb; class ItemActions { class Use { text = $STR_ACTIONS_attach_carbomb; script = "spawn player_attach_bomb;"; }; }; };
#include <iostream> #include <iomanip> #include <cmath> using namespace std; long long primes[200000000]; bool isPrime(long long num, int numprimes) { for(int i = 0; i < numprimes; i++) { if (num % primes[i] == 0) { return false; } } return true; } int main() { int numprimes = 1; primes[0] = 2; long long factor = 0; long long num = 600851475143.0; for (double i = 3; i < num; i++) { if (isPrime((long long)i, numprimes)) { primes[numprimes] = i; numprimes++; if (fmod(num, i) == 0) { cout << setprecision(12) << i << endl; factor = i; } } } }
#include "ofSSobj.h" #include "ofMesh.h" GLuint vao_; GLuint vbo_; ofSSobj::ofSSobj(void){ GLfloat saqv[8] = {-1.0f,-1.0f,1.0f,-1.0f,-1.0f,1.0f,1.0f,1.0f}; glEnableClientState(GL_VERTEX_ARRAY); glGenVertexArrays(1, &vao_); glBindVertexArray(vao_); glGenBuffers(1, &vbo_); glBindBuffer(GL_ARRAY_BUFFER, vbo_); glBufferData(GL_ARRAY_BUFFER, 8*sizeof(GLfloat), saqv, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT,GL_FALSE,0,(const GLvoid*)0); //layout 0 glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } ofSSobj::~ofSSobj(void){ //deletion vao and vbo } void ofSSobj::draw(){ glBindVertexArray(vao_); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); }
#include <iostream> #include <vector> using namespace std; class Solution { private: string s, p; int sLen, pLen; vector< vector<bool> > visited, DP; bool isMatch(int sIndex, int pIndex){ // string finished if(sIndex == sLen){ // pattern also finished if(pIndex == pLen) return true; // if a char without a star if((pLen - pIndex) % 2 == 1) return false; // if pattern has also chars with stars left for(int i=pIndex+1;i<pLen;i+=2) if(p[i] != '*') return false; return true; } // pattern finished but str not if(pIndex == pLen) return false; if(visited[sIndex][pIndex]) return DP[sIndex][pIndex]; bool res = false; if(p[pIndex] == '.'){ if(pIndex < pLen -1 && p[pIndex + 1] == '*'){ // use star res |= isMatch(sIndex + 1, pIndex); // do not use star res |= isMatch(sIndex, pIndex + 2); } else res = isMatch(sIndex + 1, pIndex + 1); } // eg: pat : ..a*.. else if(pIndex < pLen - 1 && p[pIndex + 1] == '*'){ // eg: str: ..aaa.. , ..a.. if(s[sIndex] == p[pIndex]) res = isMatch(sIndex + 1, pIndex); // eg: str: bbb res |= isMatch(sIndex, pIndex + 2); } else if(s[sIndex] == p[pIndex]) res = isMatch(sIndex + 1, pIndex + 1); visited[sIndex][pIndex] = true; DP[sIndex][pIndex] = res; return res; } public: bool isMatch(string str, string pattern) { s = str; p = pattern; sLen = s.size(); pLen = p.size(); visited = vector< vector<bool> >(sLen, vector<bool>(pLen, false)); DP = vector< vector<bool> >(sLen, vector<bool>(pLen, false)); return isMatch(0, 0); } }; int main(){ Solution s; cout << s.isMatch("aaa", "a*a") << endl; }