text
stringlengths
8
6.88M
#include <vector> #include "kontynent.hpp" class Kraj {}; class Planeta { private: const std::vector<Kontynent> kontynenty; std::vector<Kraj> kraje; static int ile; public: Planeta(std::vector<Kontynent> kontynenty); ~Planeta(); static int get_ile(); };
// Created on: 1996-11-25 // Created by: Christophe LEYNADIER // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Storage_BaseDriver_HeaderFile #define _Storage_BaseDriver_HeaderFile #include <Storage_OpenMode.hxx> #include <Storage_Data.hxx> #include <Storage_Position.hxx> #include <TCollection_AsciiString.hxx> #include <TColStd_SequenceOfAsciiString.hxx> #include <TColStd_SequenceOfExtendedString.hxx> class TCollection_ExtendedString; DEFINE_STANDARD_HANDLE(Storage_BaseDriver,Standard_Transient) //! Root class for drivers. A driver assigns a physical container //! to data to be stored or retrieved, for instance a file. //! The FSD package provides two derived concrete classes : //! - FSD_File is a general driver which defines a //! file as the container of data. class Storage_BaseDriver : public Standard_Transient { public: DEFINE_STANDARD_RTTIEXT(Storage_BaseDriver,Standard_Transient) public: Standard_EXPORT virtual ~Storage_BaseDriver(); TCollection_AsciiString Name() const { return myName; } Storage_OpenMode OpenMode() const { return myOpenMode; } Standard_EXPORT static TCollection_AsciiString ReadMagicNumber(Standard_IStream& theIStream); public: //!@name Virtual methods, to be provided by descendants Standard_EXPORT virtual Storage_Error Open (const TCollection_AsciiString& aName, const Storage_OpenMode aMode) = 0; //! returns True if we are at end of the stream Standard_EXPORT virtual Standard_Boolean IsEnd() = 0; //! return position in the file. Return -1 upon error. Standard_EXPORT virtual Storage_Position Tell() = 0; Standard_EXPORT virtual Storage_Error BeginWriteInfoSection() = 0; Standard_EXPORT virtual void WriteInfo (const Standard_Integer nbObj, const TCollection_AsciiString& dbVersion, const TCollection_AsciiString& date, const TCollection_AsciiString& schemaName, const TCollection_AsciiString& schemaVersion, const TCollection_ExtendedString& appName, const TCollection_AsciiString& appVersion, const TCollection_ExtendedString& objectType, const TColStd_SequenceOfAsciiString& userInfo) = 0; Standard_EXPORT virtual Storage_Error EndWriteInfoSection() = 0; Standard_EXPORT virtual Storage_Error BeginReadInfoSection() = 0; Standard_EXPORT virtual void ReadInfo (Standard_Integer& nbObj, TCollection_AsciiString& dbVersion, TCollection_AsciiString& date, TCollection_AsciiString& schemaName, TCollection_AsciiString& schemaVersion, TCollection_ExtendedString& appName, TCollection_AsciiString& appVersion, TCollection_ExtendedString& objectType, TColStd_SequenceOfAsciiString& userInfo) = 0; Standard_EXPORT virtual void ReadCompleteInfo (Standard_IStream& theIStream, Handle(Storage_Data)& theData) = 0; Standard_EXPORT virtual Storage_Error EndReadInfoSection() = 0; Standard_EXPORT virtual Storage_Error BeginWriteCommentSection() = 0; Standard_EXPORT virtual void WriteComment (const TColStd_SequenceOfExtendedString& userComments) = 0; Standard_EXPORT virtual Storage_Error EndWriteCommentSection() = 0; Standard_EXPORT virtual Storage_Error BeginReadCommentSection() = 0; Standard_EXPORT virtual void ReadComment (TColStd_SequenceOfExtendedString& userComments) = 0; Standard_EXPORT virtual Storage_Error EndReadCommentSection() = 0; Standard_EXPORT virtual Storage_Error BeginWriteTypeSection() = 0; Standard_EXPORT virtual void SetTypeSectionSize (const Standard_Integer aSize) = 0; Standard_EXPORT virtual void WriteTypeInformations (const Standard_Integer typeNum, const TCollection_AsciiString& typeName) = 0; Standard_EXPORT virtual Storage_Error EndWriteTypeSection() = 0; Standard_EXPORT virtual Storage_Error BeginReadTypeSection() = 0; Standard_EXPORT virtual Standard_Integer TypeSectionSize() = 0; Standard_EXPORT virtual void ReadTypeInformations (Standard_Integer& typeNum, TCollection_AsciiString& typeName) = 0; Standard_EXPORT virtual Storage_Error EndReadTypeSection() = 0; Standard_EXPORT virtual Storage_Error BeginWriteRootSection() = 0; Standard_EXPORT virtual void SetRootSectionSize (const Standard_Integer aSize) = 0; Standard_EXPORT virtual void WriteRoot (const TCollection_AsciiString& rootName, const Standard_Integer aRef, const TCollection_AsciiString& aType) = 0; Standard_EXPORT virtual Storage_Error EndWriteRootSection() = 0; Standard_EXPORT virtual Storage_Error BeginReadRootSection() = 0; Standard_EXPORT virtual Standard_Integer RootSectionSize() = 0; Standard_EXPORT virtual void ReadRoot (TCollection_AsciiString& rootName, Standard_Integer& aRef, TCollection_AsciiString& aType) = 0; Standard_EXPORT virtual Storage_Error EndReadRootSection() = 0; Standard_EXPORT virtual Storage_Error BeginWriteRefSection() = 0; Standard_EXPORT virtual void SetRefSectionSize (const Standard_Integer aSize) = 0; Standard_EXPORT virtual void WriteReferenceType (const Standard_Integer reference, const Standard_Integer typeNum) = 0; Standard_EXPORT virtual Storage_Error EndWriteRefSection() = 0; Standard_EXPORT virtual Storage_Error BeginReadRefSection() = 0; Standard_EXPORT virtual Standard_Integer RefSectionSize() = 0; Standard_EXPORT virtual void ReadReferenceType (Standard_Integer& reference, Standard_Integer& typeNum) = 0; Standard_EXPORT virtual Storage_Error EndReadRefSection() = 0; Standard_EXPORT virtual Storage_Error BeginWriteDataSection() = 0; Standard_EXPORT virtual void WritePersistentObjectHeader (const Standard_Integer aRef, const Standard_Integer aType) = 0; Standard_EXPORT virtual void BeginWritePersistentObjectData() = 0; Standard_EXPORT virtual void BeginWriteObjectData() = 0; Standard_EXPORT virtual void EndWriteObjectData() = 0; Standard_EXPORT virtual void EndWritePersistentObjectData() = 0; Standard_EXPORT virtual Storage_Error EndWriteDataSection() = 0; Standard_EXPORT virtual Storage_Error BeginReadDataSection() = 0; Standard_EXPORT virtual void ReadPersistentObjectHeader (Standard_Integer& aRef, Standard_Integer& aType) = 0; Standard_EXPORT virtual void BeginReadPersistentObjectData() = 0; Standard_EXPORT virtual void BeginReadObjectData() = 0; Standard_EXPORT virtual void EndReadObjectData() = 0; Standard_EXPORT virtual void EndReadPersistentObjectData() = 0; Standard_EXPORT virtual Storage_Error EndReadDataSection() = 0; Standard_EXPORT virtual void SkipObject() = 0; Standard_EXPORT virtual Storage_Error Close() = 0; public: //!@name Output methods Standard_EXPORT virtual Storage_BaseDriver& PutReference (const Standard_Integer aValue) = 0; Standard_EXPORT virtual Storage_BaseDriver& PutCharacter (const Standard_Character aValue) = 0; Storage_BaseDriver& operator << (const Standard_Character aValue) { return PutCharacter(aValue); } Standard_EXPORT virtual Storage_BaseDriver& PutExtCharacter(const Standard_ExtCharacter aValue) = 0; Storage_BaseDriver& operator << (const Standard_ExtCharacter aValue) { return PutExtCharacter(aValue); } Standard_EXPORT virtual Storage_BaseDriver& PutInteger(const Standard_Integer aValue) = 0; Storage_BaseDriver& operator << (const Standard_Integer aValue) { return PutInteger(aValue); } Standard_EXPORT virtual Storage_BaseDriver& PutBoolean(const Standard_Boolean aValue) = 0; Storage_BaseDriver& operator << (const Standard_Boolean aValue) { return PutBoolean(aValue); } Standard_EXPORT virtual Storage_BaseDriver& PutReal(const Standard_Real aValue) = 0; Storage_BaseDriver& operator << (const Standard_Real aValue) { return PutReal(aValue); } Standard_EXPORT virtual Storage_BaseDriver& PutShortReal(const Standard_ShortReal aValue) = 0; Storage_BaseDriver& operator << (const Standard_ShortReal aValue) { return PutShortReal(aValue); } public: //!@name Input methods Standard_EXPORT virtual Storage_BaseDriver& GetReference (Standard_Integer& aValue) = 0; Standard_EXPORT virtual Storage_BaseDriver& GetCharacter (Standard_Character& aValue) = 0; Storage_BaseDriver& operator >> (Standard_Character& aValue) { return GetCharacter(aValue); } Standard_EXPORT virtual Storage_BaseDriver& GetExtCharacter(Standard_ExtCharacter& aValue) = 0; Storage_BaseDriver& operator >> (Standard_ExtCharacter& aValue) { return GetExtCharacter(aValue); } Standard_EXPORT virtual Storage_BaseDriver& GetInteger(Standard_Integer& aValue) = 0; Storage_BaseDriver& operator >> (Standard_Integer& aValue) { return GetInteger(aValue); } Standard_EXPORT virtual Storage_BaseDriver& GetBoolean(Standard_Boolean& aValue) = 0; Storage_BaseDriver& operator >> (Standard_Boolean& aValue) { return GetBoolean(aValue); } Standard_EXPORT virtual Storage_BaseDriver& GetReal(Standard_Real& aValue) = 0; Storage_BaseDriver& operator >> (Standard_Real& aValue) { return GetReal(aValue); } Standard_EXPORT virtual Storage_BaseDriver& GetShortReal(Standard_ShortReal& aValue) = 0; Storage_BaseDriver& operator >> (Standard_ShortReal& aValue) { return GetShortReal(aValue); } protected: Standard_EXPORT Storage_BaseDriver(); void SetName(const TCollection_AsciiString& aName) { myName = aName; } void SetOpenMode(const Storage_OpenMode aMode) { myOpenMode = aMode; } private: Storage_OpenMode myOpenMode; TCollection_AsciiString myName; }; #endif // _Storage_BaseDriver_HeaderFile
#include <iostream> #include <math.h> bool prime(int num) { for( int i = 2; i <= sqrt(num); i++) { if( num % i == 0) { return false; } } return true; } int main() { int num; std::cout << "Input a number: "; std::cin >> num; std::cout << "Prime divisors : " << std::endl; for( int i = 1; i <= num; ++i ) { if(num % i == 0 && prime(i)) { std::cout << " " << i << std::endl; } } return 0; }
#ifndef PORT_H #define PORT_H //#include <QObject> class IPort //: public QObject { // Q_OBJECT public: virtual ~IPort(); virtual int openPort()=0; virtual int closePort()=0; virtual int readData(char* rxBuffer, int bytes)=0; virtual int writeData(char* txBuffer, int bytes)=0; // virtual void Package(char* data)=0; // virtual void unPackage(void)=0; }; //IPort::~IPort() //{} #endif // PORT_H
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "10106" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif string one,two; int table[1000]; int tmp_a,tmp_b,i,j; while( cin >> one >> two ){ if( one == "0" || two == "0" ){ printf("0\n"); continue; } memset(table,0,sizeof(table)); tmp_a = one.size(); tmp_b = two.size(); for( i = tmp_a-1 ; i >= 0 ; i-- ) for( j = tmp_b-1 ; j >= 0 ; j-- ) table[i+j+1] = table[i+j+1] + (one[i]-'0')*(two[j]-'0'); for( i = tmp_a+tmp_b-1 ; i > 0 ; i-- ){ if( table[i] > 9 ){ j = table[i] - table[i]%10; j = j/10; table[i] = table[i]%10; table[i-1] = table[i-1] + j; } } if( table[0] != 0 ) printf("%d",table[0] ); for( i = 1 ; i < tmp_a+tmp_b ; i++ ) printf("%d",table[i] ); printf("\n"); } return 0; }
#include "MinMaxHierarchy.h" #include "gtest/gtest.h" #include <iostream> using namespace std; // contains depths32x32 #include "TestImages.h" class MinMaxTest : public ::testing::Test { protected: MinMaxTest() : img(8, 8, 1), img32(32, 32, 1) { img.setAll(vector<float>{ 0.0, 0.5, 0.2, 0.7, 0.1, 0.2, 0.3, 0.4, 0.9, 0.0, 0.0, 0.1, 1.0, 0.2, 0.3, 0.4, 0.0, 0.5, 0.2, 0.7, 0.1, 0.2, 0.3, 0.4, 0.0, 0.0, 1.0, 0.7, 0.1, 0.0, 0.2, 0.4, 0.0, 0.5, 1.0, 0.7, 0.1, 0.0, 0.2, 0.4, 0.0, 0.5, 0.2, 0.7, 0.1, 0.0, 0.2, 0.4, 0.0, 0.0, 0.2, 0.7, 0.1, 0.0, 0.2, 0.4, 0.0, 0.5, 1.0, 0.7, 0.1, 0.0, 0.2, 1.0}); img32.setAll(getDepths32x32()); } virtual ~MinMaxTest() { } virtual void SetUp() { } virtual void TearDown() { } protected: ImageF img; ImageF img32; }; TEST_F(MinMaxTest, get) { MinMaxHierarchy mm(img); ASSERT_EQ(4, mm.getNumLevels()); ASSERT_EQ(0.0f, mm.getMin(0, 0, 0)); ASSERT_EQ(0.0f, mm.getMax(0, 0, 0)); ASSERT_EQ(0.0f, mm.getMin(1, 0, 0)); ASSERT_EQ(0.9f, mm.getMax(1, 0, 0)); ASSERT_EQ(0.0f, mm.getMin(1, 0, 0)); ASSERT_EQ(1.0f, mm.getMax(2, 0, 0)); ASSERT_EQ(1.0f, mm.getMax(3, 0, 0)); ASSERT_EQ(0.0f, mm.getMin(3, 0, 0)); } TEST_F(MinMaxTest, create4x4) { ImageF img4x4(4, 4, 1); img4x4.setAll(std::vector<float>{ 0.0, 0.0, 1, 1, 0.0, 0.0, 1, 1, 0.75, 0.75, 0.25, 0.25, 0.6, 0.8, 0.1, 0.3 }); MinMaxHierarchy mm(img4x4); ASSERT_EQ(0.0, mm.getMin(1, 0, 0)); ASSERT_EQ(0.0, mm.getMax(1, 0, 0)); ASSERT_EQ(1.0, mm.getMax(1, 1, 0)); } bool cmpFloats(float x, float y) { return abs(x - y) < 1e-6f; } TEST_F(MinMaxTest, test32x32) { MinMaxHierarchy mm(img32); ASSERT_EQ(6, mm.getNumLevels()); // test min values of level 4 ASSERT_TRUE(cmpFloats(0.673203, mm.getMin(4, 0, 1))); ASSERT_TRUE(cmpFloats(0.63008, mm.getMin(4, 0, 0))); ASSERT_TRUE(cmpFloats(0.63008, mm.getMin(4, 1, 0))); ASSERT_TRUE(cmpFloats(0.700469, mm.getMin(4, 1, 1))); // test min values of level 2, i.e. size 8 ASSERT_TRUE(cmpFloats(0.63008, mm.getMin(2, 1, 1))); }
#include<stdio.h> int countSort(int a[], int n) { int maxLen = n + 1; int b[maxLen]; int index = 0; for (int i = 0; i < n; i ++) { if (!b[a[i]]) { b[a[i]] = 0; } b[a[i]] ++; } for (int j = 0; j < maxLen; j ++) { while (b[j] > 0) { a[index ++] = j; b[j] --; } } return *a; } int main() { int a[10] = {15,7,45,96,1,52,6,3,0,78}; countSort(a, 10); for (int i = 0; i < 10; i ++) { printf("%d ", a[i]); } printf("\n"); }
#include <iostream> #include <iomanip> int main() { double TotalCost; double CashReceived; double Change; int Cents; int ChangeBills; int NumTwenties; int ChangeAfterTwenties; //Amount of change remaining after twenties int NumTens; int ChangeAfterTens; int NumFives; int ChangeAfterFives; int NumOnes; int ChangeAfterOnes; int NumQuarters; int ChangeAfterQ; //This is the amount of change remaining after quarters int NumDimes; int ChangeAfterD; //Amount of change remaining after dimes int NumNickels; int ChangeAfterN; //Amount of change remaining after nickels int NumPennies; bool BillChange = false; int ChangeVar; std::cout << "What is the total cost?" << std::endl; std::cin >> TotalCost; std::cout << "How much cash was received?" << std::endl; std::cin >> CashReceived; Change = CashReceived - TotalCost; std::cout << std::setprecision(2) << std::fixed; std::cout << "You should give $" << Change << " in change." << std::endl; if (Change > 1) { ChangeBills = Change; NumTwenties = ChangeBills / 20; ChangeAfterTwenties = ChangeBills % 20; NumTens = ChangeAfterTwenties / 10; ChangeAfterTens = ChangeAfterTwenties % 10; NumFives = ChangeAfterTens / 5; ChangeAfterFives = ChangeAfterTens % 5; NumOnes = ChangeAfterFives; ChangeVar = 100 * Change; Cents = ChangeVar % 100; BillChange = true; } if (Change < 1) { Cents = static_cast<int>(Change) * 100; } NumQuarters = Cents / 25; ChangeAfterQ = Cents % 25; NumDimes = ChangeAfterQ / 10; ChangeAfterD = ChangeAfterQ % 10; NumNickels = ChangeAfterD / 5; ChangeAfterN = ChangeAfterD % 5; NumPennies = ChangeAfterN; if (BillChange) { std::cout << "The change is " << NumTwenties << " twenties, " << NumTens << " tens, " << NumFives << " fives, and " << NumOnes << " ones, " << NumQuarters << " quarters, " << NumDimes << " dimes, " << NumNickels << " nickels, and " << NumPennies << " pennies." << std::endl; } if (!BillChange) { std::cout << "This would be best given by giving " << NumQuarters << " quarters, " << NumDimes << " dimes, " << NumNickels << " nickels, and " << NumPennies << " pennies." << std::endl; } }
#ifndef __USERBOT_H__ #define __USERBOT_H__ #include "Building.h" #include "Move.h" class UserBot { public: void MakeMoves(Building BuildingPlan,Move moves[],int size); }; #endif // __USERBOT_H__
/**************************************************************************** * Copyright (c) 2006 GeoMind Srl. www.geomind.it * All rights reserved. * *--------------------------------------------------------------------------- * This software is part of the GMCommonUtility PROJECT by GeoMind Srl; * it is not allowed to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of software in parts or as a whole, * in source and binary forms, without a written permission of GeoMind Srl. * ****************************************************************************/ // System includes //#include "precompiled.h" // #ifdef _WIN32 // #include <Windows.h> // #endif #include "pthread.h" #include <stdio.h> #include <errno.h> // Project includes // Local includes #include "CSem.h" // Forward References // Extern definitions namespace gmcu { #if defined( __APPLE__ ) pthread_mutex_t CSem::sNameMutex; int CSem::sNameMutexInitRetval = pthread_mutex_init(&sNameMutex, 0); unsigned CSem::sNameCount = 0; #endif // -------------------------------------------------------------------------- // CSem // -------------------------------------------------------------------------- /** * \brief Constructor **/ CSem::CSem() : mMySem( 0 ) { } // -------------------------------------------------------------------------- // ~CSem // -------------------------------------------------------------------------- /** * \brief Destructor **/ CSem::~CSem() { Destroy(); } // -------------------------------------------------------------------------- // Init // -------------------------------------------------------------------------- /** * \brief Create and initialize the semaphore **/ int CSem::Init( unsigned int inValue /*, const std::string& inName = ""*/ ) { #if defined( WIN32 ) || defined( __linux__ ) mMySem = new sem_t; int retval = sem_init( mMySem, 0, inValue ); if( retval != 0 ) { delete mMySem; mMySem = 0; } return retval; #elif defined( __APPLE__ ) //# undef max static const int kMaxAttempt = 5; for( int i =0; i< kMaxAttempt; ++i ) { std::string semName = GenSemName(); if( semName == "" ) return -1; mMySem = sem_open( semName.c_str(), O_CREAT | O_EXCL, 0, inValue ); // \todo to be verified: permission can be 0. try 0006 if( mMySem != SEM_FAILED ) { if( 0 != sem_unlink(semName.c_str()) ) { mMySem = 0; return -1; } else return 0; } else if( errno != EEXIST ) { mMySem = 0; //return -1; } } return -1; #endif } // -------------------------------------------------------------------------- // Destroy // -------------------------------------------------------------------------- /** * \brief **/ int CSem::Destroy() { int retval = -1; errno = EINVAL; #if defined( WIN32 ) || defined( __linux__ ) if( mMySem ) { retval = sem_destroy( mMySem ); delete mMySem; } #elif defined( __APPLE__ ) if( mMySem ) retval = sem_close( mMySem ); #endif mMySem = 0; return retval; } // -------------------------------------------------------------------------- // Wait // -------------------------------------------------------------------------- /** * \brief **/ bool CSem::Wait( unsigned int inTimeWait/*=0*/ ) { if( !mMySem ) return false; if( 0==inTimeWait ) return 0==sem_wait( mMySem ); else #ifdef __APPLE__ return false; #else { timespec theTime; theTime.tv_sec = (long) time( NULL ) + inTimeWait /1000; theTime.tv_nsec = ( inTimeWait % 1000 ) *1000000; return 0==sem_timedwait( mMySem, &theTime ); } #endif } // -------------------------------------------------------------------------- // TryWait // -------------------------------------------------------------------------- /** * \brief **/ bool CSem::TryWait() { if( mMySem ) return 0==sem_trywait( mMySem ); else return false; } // -------------------------------------------------------------------------- // Post // -------------------------------------------------------------------------- /** * \brief **/ bool CSem::Post() { if( mMySem ) return 0==sem_post( mMySem ); else return false; } // -------------------------------------------------------------------------- // GetValue // -------------------------------------------------------------------------- /** * \brief **/ int CSem::GetValue() { int outVal=-1; if( mMySem ) outVal = sem_getvalue( mMySem, &outVal ); return outVal; } // -------------------------------------------------------------------------- // GenSemName // -------------------------------------------------------------------------- /** * \brief **/ #if defined( __APPLE__ ) std::string CSem::GenSemName() { if( sNameMutexInitRetval != 0 ) return ""; if( 0 != pthread_mutex_lock( &sNameMutex ) ) return ""; // try tmpnam static const int kNameSize = std::max( L_tmpnam, 1024 ); char fileName[kNameSize]; char* tmpnamRetval = tmpnam(fileName); if( tmpnamRetval ) { pthread_mutex_unlock( &sNameMutex ); return fileName; } // try thread id plus counter sprintf( fileName, "gmcu_sem_%d_%d", int(getpid()), sNameCount ); ++sNameCount; pthread_mutex_unlock( &sNameMutex ); return fileName; } #endif } // namespace gmcu
#pragma once #include <stdexcept> #include "SDL.h" #include "cow_resource.hpp" #include "Renderer.hpp" namespace SDL { // C++ wrapper around SDL_Window* using RAII ref counting. struct Window { Window() {} explicit Window(SDL_Window* w) : res(w) {} Window(Window&& w) : res(std::move(w.res)) {} Window& operator=(Window&& o) { res = std::move(o.res); return *this; } // Accessors SDL_Window* get() { return res.get(); } SDL_Window* release() { return res.release(); } // Object-based interface inline Renderer CreateRenderer(int index, uint32_t flags) { SDL_Renderer* rend = SDL_CreateRenderer(res.get(), index, flags); if (!rend) throw std::runtime_error(std::string("Could not create window: ") + SDL_GetError()); SDL_RenderClear(rend); return Renderer(rend); } private: struct DestroyWindow { inline void operator()(SDL_Window* w) { SDL_DestroyWindow(w); } }; std::unique_ptr<SDL_Window, DestroyWindow> res; }; inline Window CreateWindow(const char* title, int x, int y, int w, int h, uint32_t flags) { SDL_Window* win = SDL_CreateWindow(title, x, y, w, h, flags); if (!win) throw std::runtime_error(std::string("Could not create window: ") + SDL_GetError()); return Window(win); } }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- // // Copyright (C) 1995-2007 Opera Software ASA. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // Patricia Aas // #ifndef __DOWNLOAD_MANAGER_H__ #define __DOWNLOAD_MANAGER_H__ #include "modules/pi/OpBitmap.h" #include "modules/pi/OpWindow.h" #include "modules/skin/OpWidgetImage.h" #include "modules/viewers/viewers.h" #include "modules/url/url2.h" #include "modules/util/OpTypedObject.h" typedef enum { HANDLER_MODE_EXTERNAL, HANDLER_MODE_PASS_URL, HANDLER_MODE_INTERNAL, HANDLER_MODE_PLUGIN, HANDLER_MODE_SAVE, HANDLER_MODE_UNKNOWN } HandlerMode; typedef enum { CONTAINER_TYPE_FILE = 0, CONTAINER_TYPE_HANDLER = 1, CONTAINER_TYPE_MIMETYPE = 2, CONTAINER_TYPE_PLUGIN = 3, CONTAINER_TYPE_SERVER = 4 } ContainerType; class DownloadManager { public: // ------------------------- // Public member classes: // ------------------------- class Container { public: // ------------------------- // Public member functions: // ------------------------- virtual ~Container() {} INT32 GetID() { return m_id; } virtual ContainerType GetType() = 0; const OpStringC & GetName() { return m_name; } const OpWidgetImage& GetWidgetImageIcon(UINT32 pixel_width = 16, UINT32 pixel_height = 16) { return m_widget_image; } Image GetImageIcon(UINT32 pixel_width = 16, UINT32 pixel_height = 16) { return m_image; } BOOL IsInitialized() { return m_initialized; } protected: // ------------------------ // Protected member functions: // ------------------------- Container() { m_id = OpTypedObject::GetUniqueID(); m_initialized = FALSE; } Container(OpString * item_name, OpBitmap * item_icon) { m_id = OpTypedObject::GetUniqueID(); InitContainer(item_name, item_icon); } Container(OpString * item_name, Image &item_icon) { m_id = OpTypedObject::GetUniqueID(); InitContainer(item_name, item_icon); } Container(const OpStringC & item_name, const OpStringC8 & item_icon) { m_id = OpTypedObject::GetUniqueID(); InitContainer(item_name, item_icon); } void InitContainer(OpString * item_name, OpBitmap * item_icon) { SetName(item_name); SetIcon(item_icon); m_initialized = TRUE; } void InitContainer(OpString * item_name, Image &item_icon) { SetName(item_name); SetIcon(item_icon); m_initialized = TRUE; } void InitContainer(const OpStringC & item_name, const OpStringC8 & item_icon) { SetName(&item_name); m_widget_image.SetImage(item_icon.CStr()); m_initialized = TRUE; } void SetName(const OpStringC * item_name){ if(item_name) m_name.Set(item_name->CStr());} void SetIcon(OpBitmap * item_icon) { //Make the icon from the bitmap : if(item_icon) { m_image = imgManager->GetImage(item_icon); } m_widget_image.SetBitmapImage( m_image, FALSE ); } void SetIcon(Image &item_icon) { m_image = item_icon; m_widget_image.SetBitmapImage( m_image, FALSE ); } void EmptyContainer() { m_initialized = FALSE; m_name.Empty(); m_widget_image.Empty(); m_image.Empty(); } // ------------------------- // Protected member variables: // ------------------------- OpString m_name; OpWidgetImage m_widget_image; Image m_image; BOOL m_initialized; INT32 m_id; }; public: // ------------------------- // Public member functions: // ------------------------- /** Get method for singleton class DownloadManager @return pointer to the instance of class DownloadManager */ static DownloadManager* GetManager(); static void DestroyManager(); /** @param @param @return */ BOOL HasSystemRegisteredHandler( const Viewer& viewer, const OpStringC& mime_type ); /** @param @return */ BOOL HasApplicationHandler( const Viewer& viewer ); /** @param @return */ BOOL HasPluginHandler( Viewer& viewer ); /** @param @param @return */ OP_STATUS GetSuggestedExtension(URL & url, OpString & extension); /** @param @param @return */ OP_STATUS GetHostName(URL & url, OpString & host_name); /** @param @param @return */ OP_STATUS GetFilePathName(URL & url, OpString & file_path); /** @param @param @return */ OP_STATUS GetServerName(URL & url, ServerName *& servername); /** @param @param @param @return */ OP_STATUS GetSuggestedFilename(URL & url, OpString & file_name, const OpStringC & extension); /** @param @param @return */ void MakeDefaultFilename(OpString & filename, const OpStringC & extension); /** @param @param @return */ OP_STATUS MakeSaveTemporaryFilename(const OpStringC & source_file_name, OpString & file_name); /** @param @param @return */ OP_STATUS MakeSavePermanentFilename(const OpStringC & source_file_name, OpString & file_name); /** @param @return */ BOOL ExtensionExists(const OpStringC & extension); /** @return */ BOOL AllowExecuteDownloadedContent(); private: // ------------------------ // Private member functions: // ------------------------- ~DownloadManager(){} DownloadManager(){} // ------------------------- // Private member variables: // ------------------------- static DownloadManager* m_manager; }; #endif //__DOWNLOAD_MANAGER_H__
//#define F_CPU 1000000UL #define CS PB4 #define CLK PB2 #define MOSI PB0 typedef uint8_t u8; typedef uint32_t u32; void out(u8 pin, u8 init) { pinMode(pin, OUTPUT); digitalWrite(pin, init); } void setup_spi() { out(CS, HIGH); out(CLK, LOW); out(MOSI, LOW); } void pause(int n = 10) { delayMicroseconds(n); } void mosi(u8* tfr, u8 pin) { u8 hi = (*tfr) & (1<<7) ? 1 : 0; digitalWrite(MOSI, hi); pause(); *tfr <<= 1; } void spi_transfer(u8 val) { u8 tfr = val; mosi(&tfr, CS); for(int i=0; i<8; i++) { digitalWrite(CLK, HIGH); pause(); digitalWrite(CLK, LOW); mosi(&tfr, CLK); } pause(); } /** Transfers data to a MAX7219/MAX7221 register. @param address The register to load data into @param value Value to store in the register */ void transfer_7219(uint8_t address, uint8_t value) { digitalWrite(CS, LOW); spi_transfer(address); spi_transfer(value); digitalWrite(CS, HIGH); } void setup() { setup_spi(); transfer_7219(0x0F, 0x00); transfer_7219(0x09, 0xFF); // Enable mode B transfer_7219(0x0A, 0x0F); // set intensity (page 9) transfer_7219(0x0B, 0x07); // use all pins transfer_7219(0x0C, 0x01); // Turn on chip } void loop() { static u32 cnt = 0; u32 num = cnt; for (uint8_t i = 0; i < 8; ++i) { u32 val = num % 10; //val = 7; transfer_7219(i+1, val); num = num/10; delay(1); } delay(1000); cnt++; }
#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 <thread> 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; string s[111]; vector<int> g[33]; int was[33]; char ans[33]; int an = 0; void ERR() { cout << "Impossible\n"; exit(0); } void dfs(int x) { if (was[x]) { if (was[x] == 2) ERR(); return; } was[x] = 2; for (int i = 0; i < g[x].size(); ++i) dfs(g[x][i]); was[x] = 1; ans[an++] = x + 'a'; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); int n; cin >> n; for (int i =0; i < n;++i) { cin >> s[i]; } for (int i = 1; i < n; ++i) { int j = 0; while (j < s[i - 1].length() && j < s[i].length() && s[i - 1][j] == s[i][j]) ++j; if (j == s[i - 1].length()) continue; if (j == s[i].length()) { ERR(); } g[s[i][j] - 'a'].push_back(s[i - 1][j] - 'a'); // cerr << s[i - 1][j] << " " << s[i][j] << endl; } for (int i = 0; i < 26; ++i) if (!was[i]) { dfs(i); } cout << ans << endl; return 0; }
#include "GnGamePCH.h" #include "GStateUILayer.h" #include "GStateUnitUpgrade.h"
#include "BubbleSort.h" void BubbleSort::sort(Container * c){ for(int i = 0; i < c->size() - 1; ++i){ for(int j = 0; j < c->size() - i - 1; ++j){ if(c->at(j)->evaluate() > c->at(j+1)->evaluate()) { c->swap(j,j+1); } } } }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/Expected.h> #include <folly/Optional.h> #include <folly/String.h> #include <folly/io/Cursor.h> #include <folly/lang/Bits.h> #include <quic/QuicException.h> #include <quic/common/BufUtil.h> namespace quic { constexpr uint64_t kOneByteLimit = 0x3F; constexpr uint64_t kTwoByteLimit = 0x3FFF; constexpr uint64_t kFourByteLimit = 0x3FFFFFFF; constexpr uint64_t kEightByteLimit = 0x3FFFFFFFFFFFFFFF; namespace { template <typename BufOp> inline uint8_t encodeOneByte(BufOp bufop, uint64_t value) { auto modified = static_cast<uint8_t>(value); bufop(modified); return sizeof(modified); } template <typename BufOp> inline uint16_t encodeTwoBytes(BufOp bufop, uint64_t value) { auto reduced = static_cast<uint16_t>(value); uint16_t modified = reduced | 0x4000; bufop(modified); return sizeof(modified); } template <typename BufOp> inline uint32_t encodeFourBytes(BufOp bufop, uint64_t value) { auto reduced = static_cast<uint32_t>(value); uint32_t modified = reduced | 0x80000000; bufop(modified); return sizeof(modified); } template <typename BufOp> inline uint64_t encodeEightBytes(BufOp bufop, uint64_t value) { uint64_t modified = value | 0xC000000000000000; bufop(modified); return sizeof(modified); } } // namespace /** * Encodes the integer and writes it out to appender. Returns the number of * bytes written, or an error if value is too large to be represented with the * variable length encoding. */ template <typename BufOp> folly::Expected<size_t, TransportErrorCode> encodeQuicInteger( uint64_t value, BufOp bufop) { if (value <= kOneByteLimit) { return encodeOneByte(std::move(bufop), value); } else if (value <= kTwoByteLimit) { return encodeTwoBytes(std::move(bufop), value); } else if (value <= kFourByteLimit) { return encodeFourBytes(std::move(bufop), value); } else if (value <= kEightByteLimit) { return encodeEightBytes(std::move(bufop), value); } return folly::makeUnexpected(TransportErrorCode::INTERNAL_ERROR); } template <typename BufOp> folly::Expected<size_t, TransportErrorCode> encodeQuicInteger(uint64_t value, BufOp bufop, int outputSize) { switch (outputSize) { case 1: CHECK(value <= kOneByteLimit); return encodeOneByte(std::move(bufop), value); case 2: CHECK(value <= kTwoByteLimit); return encodeTwoBytes(std::move(bufop), value); case 4: CHECK(value <= kFourByteLimit); return encodeFourBytes(std::move(bufop), value); case 8: CHECK(value <= kEightByteLimit); return encodeEightBytes(std::move(bufop), value); } return folly::makeUnexpected(TransportErrorCode::INTERNAL_ERROR); } /** * Reads an integer out of the cursor and returns a pair with the integer and * the numbers of bytes read, or folly::none if there are not enough bytes to * read the int. It only advances the cursor in case of success. */ folly::Optional<std::pair<uint64_t, size_t>> decodeQuicInteger( folly::io::Cursor& cursor, uint64_t atMost = sizeof(uint64_t)); /** * Returns the length of a quic integer given the first byte */ uint8_t decodeQuicIntegerLength(uint8_t firstByte); /** * Returns number of bytes needed to encode value as a QUIC integer, or an error * if value is too large to be represented with the variable * length encoding */ folly::Expected<size_t, TransportErrorCode> getQuicIntegerSize(uint64_t value); /** * Returns number of bytes needed to encode value as a QUIC integer, or throws * an exception if value is too large to be represented with the variable * length encoding */ size_t getQuicIntegerSizeThrows(uint64_t value); /** * A better API for dealing with QUIC integers for encoding. */ class QuicInteger { public: explicit QuicInteger(uint64_t value); /** * Encodes a QUIC integer to the appender. */ template <typename BufOp> size_t encode(BufOp appender) const { auto size = encodeQuicInteger(value_, std::move(appender)); if (size.hasError()) { LOG(ERROR) << "Value too large value=" << value_; throw QuicTransportException( folly::to<std::string>("Value too large ", value_), size.error()); } return size.value(); } template <typename BufOp> size_t encode(BufOp appender, int outputSize) const { auto size = encodeQuicInteger(value_, std::move(appender), outputSize); if (size.hasError()) { LOG(ERROR) << "Value too large value=" << value_; throw QuicTransportException( folly::to<std::string>("Value too large ", value_), size.error()); } return size.value(); } /** * Returns the number of bytes needed to represent the QUIC integer in * its encoded form. **/ size_t getSize() const; /** * Returns the real value of the QUIC integer that it was instantiated with. * This should normally never be used. */ uint64_t getValue() const; private: uint64_t value_; }; } // namespace quic
#include<iostream> #include<unistd.h> using namespace std; int countOut(int count) { sleep(1); cout << ". Execution" << endl; if (count > 1) { countOut(-- count); } cout << "Release" << endl; } int main() { countOut(4); return 0; }
#pragma once #include "../system.hpp" #include "CollisionResults/collisionresult.h" #include <memory> #include <map> namespace sbg { struct ResultData; struct CollisionTester; struct CollisionHandler; struct CollisionEntity; struct Group; struct CollisionBody { CollisionBody() = default; CollisionBody(const CollisionBody&) = delete; CollisionBody(CollisionBody&& other); virtual ~CollisionBody() = default; CollisionBody& operator=(CollisionBody&& other); CollisionBody& operator=(const CollisionBody&) = delete; CollisionResult testObject(std::shared_ptr<const Entity> other, Time time, Group* test) const; void setCollisionEntity(Group* group, std::shared_ptr<CollisionEntity> entity); std::shared_ptr<CollisionEntity> getCollisionEntity(Group* group); const std::shared_ptr<const CollisionEntity> getCollisionEntity(Group* group) const; void addCollisionHandler(Group* group, std::unique_ptr<CollisionHandler> collisionHandler); void removeCollisionHandler(Group* group); void setCollisionTester(Group* group, std::unique_ptr<CollisionTester> collisionTester); void removeCollisionTester(Group* group); void trigger(std::shared_ptr<Entity> self, CollisionResult result, Group* test); void setMaterial(Material material); Material getMaterial() const; private: Material _material; std::multimap<Group*, std::unique_ptr<CollisionHandler>> _collisionhandlers; std::map<Group*, std::shared_ptr<CollisionEntity>> _collisionEntities; std::map<Group*, std::unique_ptr<CollisionTester>> _collisionTesters; }; }
#pragma once #ifndef __SOCKETHELPER_H__ #define __SOCKETHELPER_H__ class CTcpSocketHandler { public: CTcpSocketHandler(); ~CTcpSocketHandler(); public: #if 0 static CTcpSocketHandler& GetInstance() { static CTcpSocketHandler instance; return instance; } #endif int Init(const char *cServerAddr, int nServerPort, bool bAutoReConnect = false); static void RecvDataFromApp(void * p); int StartRecvDataThread(); int RequestCommand(const char * pCommand, int nCommandLength); //std::wstring GetWebUrl(char * pUrl, std::wstring & wstrNickName); int Exit(); void SetRecvFlag(bool bRecvFlag) { m_bRecvFlag = bRecvFlag; } bool GetRecvFlag() { return m_bRecvFlag; } void SetClientSocket(SOCKET s) { m_clientSocket = s; } SOCKET GetClientSocket() { return m_clientSocket; } void SetServerAddr(std::string strServerAddr) { m_strServerAddr = strServerAddr; } std::string GetServerAddr() { return m_strServerAddr; } void SetServerPort(int nServerPort) { m_nServerPort = nServerPort; } int GetServerPort() { return m_nServerPort; } void SetAutoReConnect(bool bAutoReConnect) { m_bAutoReConnect = bAutoReConnect; } bool GetAutoReConnect() { return m_bAutoReConnect; } void SetReConnecting(bool bReConnecting) { m_bReConnecting = bReConnecting; } bool GetReConnecting() { return m_bReConnecting; } struct sockaddr_in m_serverSockAddrIn; void ClientSockInitialize();//初始化 void ClientSetSockOptions();//设置选项 void ClientSetSockAddrsIn();//设置参数 void ClientExecuteConnect();//执行连接 private: void ClientInit(); std::string m_strServerAddr; int m_nServerPort; SOCKET m_clientSocket; SOCKET m_clientReConnectSocket; bool m_bRecvFlag;//false-关闭,true-运行 bool m_bAutoReConnect;//是否自动重连,true-自动重连,false-不自动重连 bool m_bReConnecting;//是否正在重连,true-是,false-否 }; class CUdpSocketHandler{ public: typedef struct tagSocketPacket{ int ssize;//结构体大小 SOCKET s; struct sockaddr_in si;//接入的连接信息 int port;//端口 void * data;//数据指针 int size;//数据大小 }SOCKETPACKET, *PSOCKETPACKET; SOCKET udp_start(int nPort); void udp_setsockaddrsin()//设置参数 { } static DWORD WINAPI udp_recvdata_thread(void *p); static DWORD WINAPI udp_senddata_thread(void *p); }; #endif // __SOCKETHELPER_H__
= イベントのコンセプト 技術書界隈を盛り上げる会 connpassページより抜粋した、イベントの説明がこちらです。 == イベントの説明 技術書典や技書博など、技術書を書く・発行することを応援するイベントです。 YoutubeLive + Twitterを通して、技術書典や技書博で頒布されている書籍の紹介や、著者とお話をしたりなど、技術書の魅力を伝える様々な活動を行っていきます。 このイベントは以下のような方にお勧めです。 * 技術書が好きな人 * 技術書を書いてみたい人 * 技術書を書いている人(著者の人) * 技術書界隈って何?知りたい!という人 収録はZoomで行いますが、YoutubeLiveへは10秒~30秒程度の遅延でライブ配信されます。 Twitterでのコメントや、YoutubeLiveのコメントを拾いながら進めていきますので、どちらもお楽しみに! == イベントのデザイン このイベントは、参加者・ゲスト双方が参加しやすいような雰囲気を作り出すようにデザインしています。 参加者に向けては、「気軽に参加できる」「興味がある人を増やす」というコンセプトです。 イベント開始初期はZoomとYouTubeLiveとでどちらに参加しても大丈夫、という風に作っていたのですが、はじめての人がZoomに入るのって意外と勇気がいると思います。そのため、Zoomはパーソナリティとゲストのみに限定して、参加者はYouTubeLiveのみにする。視聴すればいいだけだし、いつでも離脱できる。アーカイブが残っているので、途中から見直すこともできる。そして、Twitterでの実況という形でイベントに参加してもらい、パーソナリティがその実況を拾うことで、参加者もより楽しめる。そういう風にデザインしました。 ゲストに向けては、「気軽に参加できる」「話したいことが話せる」というコンセプトです。 基本的に、ゲストをこちらからお願いすることは稀です。「喋りたいなー」と呟いていた人や、参加者から「この人の話を聞きたい」というような要望が出た場合を除き、基本的には「喋りたい人に喋ってもらう」というコンセプトでイベントを開催しています。 講演・イベントによっては、相手から依頼された内容に沿うように、色々と内容を整理して、新しく資料を作って、という風に発表者側に負担がかかってしまうことが多々ありますが、このイベントでは「資料なしでも全く問題なし」「無理のない範囲で、用意したい分だけ用意する」という風にお願いしています。誰でも気軽に、話してみよう、という空気を作り出すために、ゲスト側の負担がかからないような仕組みづくりを心掛けています。
/* * Copyright 2019 LogMeIn * * 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. * * SPDX-License-Identifier: Apache-2.0 */ #include "ExecutorMetrics.h" #include <iterator> namespace asyncly { namespace { // creates buckets from 1us to 4s with exponential bucket sizes inline std::vector<double> createDurationBuckets() { const std::size_t size = 23; // Max bucket = 4s std::vector<double> result; result.reserve(size); double start = 500; std::generate_n(std::back_inserter(result), size, [&start] { start = 2.0 * start; return start; }); return result; } } ProcessedTasksMetrics::ProcessedTasksMetrics( prometheus::Registry& registry, const std::string& executorLabel) : family_{ prometheus::BuildCounter() .Name("processed_tasks_total") .Help("Number of tasks pulled out of the queue and run " "by this executor.") .Register(registry) } , immediate_{ family_.Add({ { "executor", executorLabel }, { "type", "immediate" } }) } , timed_{ family_.Add({ { "executor", executorLabel }, { "type", "timed" } }) } { } EnqueuedTasksMetrics::EnqueuedTasksMetrics( prometheus::Registry& registry, const std::string& executorLabel) : family_{ prometheus::BuildGauge() .Name("currently_enqueued_tasks_total") .Help("Number of tasks currently residing in the executors " "task queue and waiting to be executed.") .Register(registry) } , immediate_{ family_.Add({ { "executor", executorLabel }, { "type", "immediate" } }) } , timed_{ family_.Add({ { "executor", executorLabel }, { "type", "timed" } }) } { } TaskExecutionDurationMetrics::TaskExecutionDurationMetrics( prometheus::Registry& registry, const std::string& executorLabel) : family_{ prometheus::BuildHistogram() .Name("task_execution_duration_ns") .Help("Histogram of time taken for tasks to run once they " "have been taken out of the queue and started.") .Register(registry) } , immediate_{ family_.Add( { { "executor", executorLabel }, { "type", "immediate" } }, createDurationBuckets()) } , timed_{ family_.Add( { { "executor", executorLabel }, { "type", "timed" } }, createDurationBuckets()) } { } TaskQueueingDelayMetrics::TaskQueueingDelayMetrics( prometheus::Registry& registry, const std::string& executorLabel) : family_{ prometheus::BuildHistogram() .Name("task_queueing_delay_ns") .Help("Histogram of the queuing time of tasks, i.e., the time it takes from " "their creation to their execution.") .Register(registry) } , immediate_{ family_.Add( { { "executor", executorLabel }, { "type", "immediate" } }, createDurationBuckets()) } , timed_{ family_.Add( { { "executor", executorLabel }, { "type", "timed" } }, createDurationBuckets()) } { } ExecutorMetrics::ExecutorMetrics(const std::string& executorLabel) : processedTasks{ registry_, executorLabel } , queuedTasks{ registry_, executorLabel } , taskExecution{ registry_, executorLabel } , taskDelay{ registry_, executorLabel } { } }
/* * levelset.cpp * deflektor-ds * * Created by Hugh Cole-Baker on 4/1/09. * */ #include <nds.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <fat.h> #include <sys/dir.h> #include <string.h> #include <errno.h> #include "levelset.h" #include "level.h" #include "settings.h" #include "sprite.h" #include "gameover.h" #include "bar.h" void timerHandler(void) { //this does nothing } void LevelSet::fadeToBlack() { REG_BLDCNT = (1 << BEAMBG_IDX) | (1 << GAMEBG_IDX) | (1 << MIRRORSBG_IDX) | (1 << DECORBG_IDX) | (1 << 4) | //sprite layer (3 << 6); for(int blend = 0; blend <= 16; ++blend) { swiWaitForVBlank(); REG_BLDY = blend; swiWaitForVBlank(); } } void LevelSet::fadeFromBlack() { REG_BLDCNT = (1 << BEAMBG_IDX) | (1 << GAMEBG_IDX) | (1 << MIRRORSBG_IDX) | (1 << DECORBG_IDX) | (1 << 4) | //sprite layer (3 << 6); for(int blend = 16; blend >= 0; --blend) { swiWaitForVBlank(); REG_BLDY = blend; swiWaitForVBlank(); } } void LevelSet::blackScreen() { REG_BLDCNT = (1 << BEAMBG_IDX) | (1 << GAMEBG_IDX) | (1 << MIRRORSBG_IDX) | (1 << DECORBG_IDX) | (1 << 4) | //sprite layer (3 << 6); REG_BLDY = 16; } void LevelSet::blackScreenSub() { REG_BLDCNT_SUB = (1 << BMPBG_IDX) | (1 << CONSOLEBG_IDX) | (3 << 6); REG_BLDY_SUB = 16; } void LevelSet::fadeToBlackSub() { REG_BLDCNT_SUB = (1 << BMPBG_IDX) | (1 << CONSOLEBG_IDX) | (3 << 6); for(int blend = 0; blend <= 16; ++blend) { swiWaitForVBlank(); REG_BLDY_SUB = blend; swiWaitForVBlank(); } } void LevelSet::disableFade() { REG_BLDCNT = 0; REG_BLDY = 0; } void LevelSet::disableFadeSub() { REG_BLDCNT_SUB = 0; REG_BLDY_SUB = 0; } void LevelSet::captureScreen(int bank) { REG_DISPCAPCNT = DCAP_ENABLE | DCAP_MODE(0) | DCAP_SRC(0) | DCAP_SIZE(3) | DCAP_OFFSET(0) | DCAP_BANK(bank); while(REG_DISPCAPCNT & DCAP_ENABLE); } void LevelSet::blurScreen(int iters, int bank, bool fadeSub) { if(fadeSub) REG_BLDCNT_SUB = (1 << BMPBG_IDX) | (1 << CONSOLEBG_IDX) | (3 << 6); u16* vramBank = ((u16*)(0x6800000 + bank*0x20000)); for(int times = 0; times < iters; ++times) { swiWaitForVBlank(); if(fadeSub) REG_BLDY_SUB = times; /*int bAvg = ((vramBank[0] & 0x7c00) + (vramBank[1] & 0x7c00) + (vramBank[256] & 0x7c00) + (vramBank[257] & 0x7c00)) >> 10; int gAvg = ((vramBank[0] & 0x3e0) + (vramBank[1] & 0x3e0) + (vramBank[256] & 0x3e0) + (vramBank[257] & 0x3e0)) >> 5; int rAvg = ((vramBank[0] & 0x1f) + (vramBank[1] & 0x1f) + (vramBank[256] & 0x1f) + (vramBank[257] & 0x1f)); for(int i=0; i < 48896; ++i) { vramBank[i] = ARGB16(1,(rAvg >> 2) & 0x1f,(gAvg >> 2) & 0x1f,(bAvg >> 2) & 0x1f); bAvg += (((vramBank[i+1] & 0x7c00) + (vramBank[i+257] & 0x7c00)) >> 10); bAvg -= (((vramBank[i] & 0x7c00) + (vramBank[i+256] & 0x7c00)) >> 10); gAvg += (((vramBank[i+1] & 0x3e0) + (vramBank[i+257] & 0x3e0)) >> 5); gAvg -= (((vramBank[i] & 0x3e0) + (vramBank[i+256] & 0x3e0)) >> 5); rAvg += ((vramBank[i+1] & 0x1f) + (vramBank[i+257] & 0x1f)); rAvg -= ((vramBank[i] & 0x1f) + (vramBank[i+256] & 0x1f)); } for(int i=48896; i < 49152; ++i) { vramBank[i] = ARGB16(1,rAvg >> 2,gAvg >> 2,bAvg >> 2); bAvg += (((vramBank[i+1] & 0x7c00) + (vramBank[i-255] & 0x7c00)) >> 10); bAvg -= (((vramBank[i] & 0x7c00) + (vramBank[i-256] & 0x7c00)) >> 10); gAvg += (((vramBank[i+1] & 0x3e0) + (vramBank[i-255] & 0x3e0)) >> 5); gAvg -= (((vramBank[i] & 0x3e0) + (vramBank[i-256] & 0x3e0)) >> 5); rAvg += ((vramBank[i+1] & 0x1f) + (vramBank[i-255] & 0x1f)); rAvg -= ((vramBank[i] & 0x1f) + (vramBank[i-256] & 0x1f)); } */ vramBank[0] = 0x8000 |(0x1f & (((0x1f & vramBank[0]) + (0x1f & vramBank[1]) + (0x1f & vramBank[256]) + (0x1f & vramBank[257])) >> 2)) | (0x3e0 & (((0x3e0 & vramBank[9]) + (0x3e0 & vramBank[1]) + (0x3e0 & vramBank[256]) + (0x3e0 & vramBank[257]))>> 2)) | (0x7c00 & (((0x7c00 & vramBank[9]) + (0x7c00 & vramBank[1]) + (0x7c00 & vramBank[256]) + (0x7c00 & vramBank[257]))>> 2)); for(int i = 1; i < 256; ++i) { vramBank[i] = 0x8000 |(0x1f & (((0x1f & vramBank[i-1]) + (0x1f & vramBank[i+1]) + (0x1f & vramBank[i]) + (0x1f & vramBank[i+256])) >> 2)) | (0x3e0 & (((0x3e0 & vramBank[i-1]) + (0x3e0 & vramBank[i+1]) + (0x3e0 & vramBank[i]) + (0x3e0 & vramBank[i+256]))>> 2)) | (0x7c00 & (((0x7c00 & vramBank[i-1]) + (0x7c00 & vramBank[i+1]) + (0x7c00 & vramBank[i]) + (0x7c00 & vramBank[i+256]))>> 2)); } for(int i = 256; i < 48896; ++i) { vramBank[i] = 0x8000 |(0x1f & (((0x1f & vramBank[i-1]) + (0x1f & vramBank[i+1]) + (0x1f & vramBank[i-256]) + (0x1f & vramBank[i+256])) >> 2)) | (0x3e0 & (((0x3e0 & vramBank[i-1]) + (0x3e0 & vramBank[i+1]) + (0x3e0 & vramBank[i-256]) + (0x3e0 & vramBank[i+256]))>> 2)) | (0x7c00 & (((0x7c00 & vramBank[i-1]) + (0x7c00 & vramBank[i+1]) + (0x7c00 & vramBank[i-256]) + (0x7c00 & vramBank[i+256]))>> 2)); } for(int i = 48896; i < 49152; ++i) { vramBank[i] = 0x8000 |(0x1f & (((0x1f & vramBank[i-1]) + (0x1f & vramBank[i+1]) + (0x1f & vramBank[i-256]) + (0x1f & vramBank[i])) >> 2)) | (0x3e0 & (((0x3e0 & vramBank[i-1]) + (0x3e0 & vramBank[i+1]) + (0x3e0 & vramBank[i-256]) + (0x3e0 & vramBank[i]))>> 2)) | (0x7c00 & (((0x7c00 & vramBank[i-1]) + (0x7c00 & vramBank[i+1]) + (0x7c00 & vramBank[i-256]) + (0x7c00 & vramBank[i]))>> 2)); } } } void LevelSet::gameOver(Level* ended) { vramSetBankD(VRAM_D_LCD); captureScreen(3); delete ended; videoSetMode(MODE_FB3); blurScreen(5,3,false); swiWaitForVBlank(); Settings::get().getEnergyBar()->hide(); Settings::get().getOverloadBar()->hide(); vramSetBankD(VRAM_D_MAIN_BG); videoSetMode(MODE_3_2D | DISPLAY_SPR_1D | DISPLAY_SPR_1D_SIZE_64); oamEnable(&oamMain); bgInit(BEAMBG_IDX, BgType_Bmp16, BgSize_B16_256x256, 24, 0); BgHandles& handles = Settings::get().getBgHandles(); int curPalIdx = Settings::get().getPalIdx(); bgSetScroll(handles.beamBg,0,0); bgHide(handles.gameBg); bgHide(handles.mirrorsBg); bgHide(handles.decorBg); bgUpdate(); int * velocity = new int[8]; int * position = new int[8]; Sprite* sprites[] = { new Sprite(true, coord(56,-16), 0, curPalIdx, SpriteSize_16x16, SpriteColorFormat_16Color, false, false, false, false , 1, true), new Sprite(true, coord(72,-16), 0, curPalIdx, SpriteSize_16x16, SpriteColorFormat_16Color, false, false, false, false , 1, true), new Sprite(true, coord(88,-16), 0, curPalIdx, SpriteSize_16x16, SpriteColorFormat_16Color, false, false, false, false , 1, true), new Sprite(true, coord(104,-16), 0, curPalIdx, SpriteSize_16x16, SpriteColorFormat_16Color, false, false, false, false , 1, true), new Sprite(true, coord(136,-16), 0, curPalIdx, SpriteSize_16x16, SpriteColorFormat_16Color, false, false, false, false , 1, true), new Sprite(true, coord(152,-16), 0, curPalIdx, SpriteSize_16x16, SpriteColorFormat_16Color, false, false, false, false , 1, true), new Sprite(true, coord(168,-16), 0, curPalIdx, SpriteSize_16x16, SpriteColorFormat_16Color, false, false, false, false , 1, false), new Sprite(true, coord(184,-16), 0, curPalIdx, SpriteSize_16x16, SpriteColorFormat_16Color, false, false, false, false , 1, true) }; //copy Game Over gfx dmaCopy(&gameoverTiles, sprites[0]->getGfxPtrs()[0], 128); dmaCopy(128+((char*)&gameoverTiles), sprites[1]->getGfxPtrs()[0], 128); dmaCopy(256+((char*)&gameoverTiles), sprites[2]->getGfxPtrs()[0], 128); dmaCopy(384+((char*)&gameoverTiles), sprites[3]->getGfxPtrs()[0], 128); dmaCopy(512+((char*)&gameoverTiles), sprites[4]->getGfxPtrs()[0], 128); dmaCopy(640+((char*)&gameoverTiles), sprites[5]->getGfxPtrs()[0], 128); sprites[6]->setGfxPtrs(sprites[3]->getGfxPtrs()); dmaCopy(768+((char*)&gameoverTiles), sprites[7]->getGfxPtrs()[0], 128); oamUpdate(&oamMain); for(int i=0; i<8; ++i) { velocity[i] = 0; position[i] = -16; } velocity[0] = 1; bool stopped = false; while(!stopped) { for(int i=0; i<8; ++i) { position[i] = position[i] + velocity[i]; if(position[i] > -16 && position[i] < 70) { velocity[i] += 1; } if(position[i] >= 70 && velocity[i] > 0) { velocity[i] = -(velocity[i]) + 3 + (rand() & 3); position[i] = 70; if(velocity[i] >= 0) { //come to rest velocity[i] = 0; position[i] = 70; } if(i < 7 && position[i+1] == -16) { velocity[i+1] = 1; position[i+1] = -15; } } sprites[i]->setYPos(position[i]); } swiWaitForVBlank(); oamUpdate(&oamMain); stopped = true; for(int i=0; i<8; ++i) { stopped = stopped && velocity[i] == 0 && position[i] == 70; if(!stopped) break; } } delete [] velocity; delete [] position; timerStart(0, ClockDivider_1024, 1, timerHandler); for(int i=0; i<2; ++i) { swiIntrWait(1, IRQ_TIMER0); } //disable timer TIMER_CR(0) = 0; vramSetBankB(VRAM_B_LCD); captureScreen(1); videoSetMode(MODE_FB1); blurScreen(16,1, true); videoSetMode(MODE_3_2D | DISPLAY_SPR_1D | DISPLAY_SPR_1D_SIZE_64); //clear bank B DMA_FILL(3) = (vuint32)0; DMA_SRC(3) = (uint32)&DMA_FILL(3); DMA_DEST(3) = (uint32)VRAM_B; DMA_CR(3) = DMA_SRC_FIX | DMA_COPY_WORDS | ((SCREEN_WIDTH*192)>>1); //hide gameover sprites for(int i=0; i < 8; ++i) { delete sprites[i]; } oamEnable(&oamMain); bgInit(BEAMBG_IDX, BgType_Bmp16, BgSize_B16_256x256, 3, 0); bgSetScroll(handles.beamBg,1-XOFS,1-YOFS); bgShow(handles.gameBg); bgShow(handles.mirrorsBg); bgShow(handles.decorBg); disableFadeSub(); bgUpdate(); oamUpdate(&oamMain); } LevelSet::LevelSet(char* dir) : currentScore(0), currentLives(3), currentLevel(0), dirLen(strlen(dir) + 1) { memset(filename, 0, MAXPATHLEN); strncpy(filename, dir, MAXPATHLEN); filename[dirLen-1] = '/'; } void LevelSet::playLevelSet() { strcpy(filename+dirLen, "filelist.txt"); FILE *flist = fopen(filename,"r"); if(flist != NULL) { char line[128]; while(fgets(line, sizeof line, flist) != NULL) { if (line[strlen(line) - 1] == '\n') { line[strlen(line) - 1] = '\0'; } strcpy(filename+dirLen, line); currentLevel++; while(!playLevel(filename)) { currentLives--; iprintf("lives:%d\n",currentLives); if(currentLives < 0) { fclose(flist); return; } } } swiWaitForVBlank(); Settings::get().getEnergyBar()->hide(); Settings::get().getOverloadBar()->hide(); oamUpdate(&oamMain); fclose(flist); } else { iprintf("Can't open %s\n",filename); } return; } bool LevelSet::playLevel(char* levelfile) { BgHandles& handles = Settings::get().getBgHandles(); Level* tempLevel = new Level(levelfile, handles.gameBg, handles.mirrorsBg, handles.beamBg, Settings::get().getLevelParams()); disableFade(); snprintf(levelStr, 11, "LEVEL: %03d",currentLevel); tempLevel->printSub(11, 12, handles.gamedisplayBg, 0, levelStr); snprintf(livesStr, 9, "LIVES: %d",currentLives); tempLevel->printSub(12, 17, handles.gamedisplayBg, 2, livesStr); int newScore = tempLevel->playLevel(currentScore); if(newScore >= 0) { currentScore = newScore; fadeToBlack(); delete tempLevel; return true; } else if(newScore == -1) { if(currentLives > 0) { fadeToBlack(); delete tempLevel; } else { gameOver(tempLevel); bgHide(handles.decorBg); bgUpdate(); } return false; } else// if(newScore == -2) { currentLives = 0; fadeToBlack(); delete tempLevel; bgHide(handles.decorBg); bgUpdate(); Settings::get().getEnergyBar()->hide(); Settings::get().getOverloadBar()->hide(); oamUpdate(&oamMain); return false; } }
#include<map> #include<iostream> #define MAX 20 using namespace std; typedef char vextype; const int inf = 0x3f3f3f3f; typedef int costtype; struct edge { int begin, end; costtype cost; edge(int begin, int end, int cost) :begin(begin), end(end), cost(cost) { } }; int n, m, p[MAX][MAX]; costtype dist[MAX]; edge **q; map<vextype, int> mm; vextype *_mm; void createvex(vextype x) { static int i = 1; if (mm[x]) return; mm[x] = i; _mm[i] = x; ++i; } void input() { vextype x, y; costtype z; cin >> n >> m; _mm = new vextype[n + 1]; q = new edge*[m]; for (int i = 0; i < m; i++) { cin >> x >> y >> z; createvex(x); createvex(y); q[i] = new edge(mm[x],mm[y],z); } } bool bf(int A) { memset(p, -1, sizeof(p)); memset(dist, 0x3f, sizeof(dist)); dist[A] = 0; for (int i = 0; i < m; i++) if (q[i]->begin == A) dist[q[i]->end] = q[i]->cost; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { int u = q[j]->begin, v = q[j]->end, c = q[j]->cost; if (dist[v] > dist[u] + c) { dist[v] = dist[u] + c; if (u != A) p[A][v] = u; if (i == n-1) return 0; } } } return 1; } void printway(int x, int y) { if (p[x][y] == -1) cout << "->" << _mm[y]; else { printway(x, p[x][y]); printway(p[x][y], y); } } void test() { vextype x, y; cout << "input A,B: "; cin >> x >> y; if (bf(mm[x])) { cout << "bellman_ford: " << dist[mm[y]] << '\n' << x; printway(mm[x], mm[y]); } else cout << "Negative loop exist\n"; } void main() { input(); test(); system("pause"); }
#pragma once #include "utils/ptts.hpp" #include "proto/config_drop.pb.h" using namespace std; namespace nora { namespace config { using drop_ptts = ptts<proto::config::drop>; drop_ptts& drop_ptts_instance(); void drop_ptts_set_funcs(); } }
const int button = 5; int buttonState = 0; int lastButtonState = 0; void setup() { pinMode(button, INPUT); Serial.begin(9600); } void loop() { buttonState = digitalRead(button); if (buttonState == HIGH) { Serial.println("1"); delay(100); } else if(buttonState == LOW) { Serial.println("0"); delay(100); } lastButtonState = buttonState; }
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int utopian(int n){ return ~(~1<<(n>>1)) << n%2; } int main() { int t, s; cin >>t; while(t--){ cin >> s; cout << utopian(s)<<endl; } }
#include<bits/stdc++.h> using namespace std; using ll=long long; int n; vector<pair<int,int> > v; int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>n; int _,__; for(int i=0;i<n;i++){ cin>>_>>__; v.emplace_back(_,__); } sort(v.begin(),v.end()); int ans=-1; for(int i=0;i<n;i++){ if(v[i].second>=ans){ ans=v[i].second; } else ans=v[i].first; } cout<<ans<<endl; return 0; }
#ifndef WALLS_H #define WALLS_H #include<QObject> class Walls :public QObject { Q_OBJECT public: Walls(); public slots: virtual void move()=0; }; #endif // WALLS_H
#ifndef __PCF8574_H__ #define __PCF8574_H__ // // // template <typename ChannelInBufferType, typename ChannelOutBufferType, uint8_t address> class PCF8574 { public: PCF8574(ChannelInBufferType& _inChannel, ChannelOutBufferType& _outChannel) : inChannel(_inChannel), outChannel(_outChannel) { } void SetOutputs( uint8_t bits ) { } private: ChannelInBufferType& inChannel; ChannelOutBufferType& outChannel; }; #endif
/******************************************** * Titre: Travail pratique #5 - GestionnaireUsagers.h * Date: 9 mars 2018 * Auteur: Ryan Hardie *******************************************/ #pragma once #include "ProduitAuxEncheres.h" #include "Client.h" #include "Foncteur.h" #include "GestionnaireGenerique.h" // TODO : Créer la classe GestionnaireUsager class GestionnaireUsager : public GestionnaireGenerique<AjouterUsager, set<Usager*>,Usager*, SupprimerUsager<Usager*>> { public: double obtenirChiffreAffaires() const; void encherir(Client *client, ProduitAuxEncheres *produit, double montant) const; void reinitialiser(); void afficherProfils() const; }; // TODO : La classe ressemble beaucoup à la classe Gestionnaire /* Les méthodes retrouvées de la classe Gestionnaire sont : - double obtenirChiffreAffaires() const; - void encherir(Client *client, ProduitAuxEncheres *produit, double montant) const; - void reinitialiser(); - void afficherProfils() const; */
/* * dataSmoother.cpp * moviePlayerExample * * Created by William Hooke on 10/12/2011. * Copyright 2011 Wieden + Kennedy. All rights reserved. * */ #include "ofMain.h" #include "testApp.h" #include "dataSmoother.h" #include "ofxXmlSettings.h" void dataSmoother::drawGui() { ofPushMatrix(); ofTranslate(600, 600); ofSetColor(0); ofDrawBitmapString("press l to toggle shape lock: " + ofToString(shapeLocked) ,0,0); ofDrawBitmapString("point 1 smoothing (1 / q) : " + ofToString(pt1SmoothVal),0,20); ofDrawBitmapString("point 2 smoothing (2 / w) : " + ofToString(pt2SmoothVal),0,40); ofDrawBitmapString("point 3 smoothing (3 / e) : " + ofToString(pt3SmoothVal),0,60); ofDrawBitmapString("hit 'r' to reset",0,80); ofDrawBitmapString("hit 'x' to save new xml files",0,100); ofPopMatrix(); } void dataSmoother::loadXML() { //ofDirectory choirFaceDir; //vector<ofFile> faceDataFiles; string filename = "xml/orig/boy 6 - row 1.xml"; origXml.loadFile(filename); origXml.pushTag("CHOIRFACE"); totalFrames = origXml.getNumTags("FRAME"); printf("total frame tags found %i", totalFrames); //vector<frameTriangle> origFrameTris; // Pt1x[totalFrames]; // Pt1y[totalFrames]; // // Pt2x[totalFrames]; // Pt2y[totalFrames]; // // Pt3x[totalFrames]; // Pt3y[totalFrames]; // // FrameNum[totalFrames]; // load all the frame coords into a vector for (int i = 0; i < totalFrames; ++i) { origXml.pushTag("FRAME", i); Pt1x[i] = (origXml.getValue("POINT1:X", 0.0f)) - 472; // printf("point 1x: %f \n", origXml.getValue("POINT1:X", 0.0f)); // Pt1y[i] = (origXml.getValue("POINT1:Y", 0.0f)) - 192; // printf("point 1y: %f \n", origXml.getValue("POINT1:Y", 0.0f)); // Pt2x[i] = (origXml.getValue("POINT2:X", 0.0f)) - 472; // printf("point 2x: %f \n", origXml.getValue("POINT2:X", 0.0f)); // Pt2y[i] = (origXml.getValue("POINT2:Y", 0.0f)) - 192; // printf("point 2y: %f \n", origXml.getValue("POINT2:Y", 0.0f)); // Pt3x[i] = (origXml.getValue("POINT3:X", 0.0f)) - 472; // printf("point 3x: %f \n", origXml.getValue("POINT3:X", 0.0f)); // Pt3y[i] = (origXml.getValue("POINT3:Y", 0.0f)) - 192; // printf("point 3y: %f \n", origXml.getValue("POINT3:Y", 0.0f)); //Pt3y[i] = origXml.getValue("POINT3:Y", 0); //FrameNum[i] = i; //origFrameTris.push_back(curPt1x, curPt1y, curPt2x, curPt2y, curPt3x, curPt3y, curFrameNum); origXml.popTag(); } //printf("xml loaded in %i %f", FrameNum[10], Pt1x[10]); printf("triangle x1: %f y1: %f x2: %f y2: %f x3: %f y3: %f", Pt1x[0], Pt1y[0], Pt2y[0], Pt2y[0], Pt3x[0], Pt3y[0]); //then make a copy of the vector. we will smooth the values in the copy, using the original as for reference /* string filename = "myfile.xml"; ofxXmlSettings xml; xml.loadFile(fileName); interactionLevel = (int)xml.getAttribute(ofToString("CHOIRFACE"), ofToString("interactionLevel"), 0, 0); xml.pushTag("CHOIRFACE"); for (int i = 0; i < xml.getNumTags("FRAME"); ++i) { xml.pushTag("FRAME", i); ofVec2f pt1(xml.getValue("POINT1:X", 0) + CROP_SHIFT.x, xml.getValue("POINT1:Y", 0) + CROP_SHIFT.y); ofVec2f pt2(xml.getValue("POINT2:X", 0) + CROP_SHIFT.x, xml.getValue("POINT2:Y", 0) + CROP_SHIFT.y); ofVec2f pt3(xml.getValue("POINT3:X", 0) + CROP_SHIFT.x, xml.getValue("POINT3:Y", 0) + CROP_SHIFT.y); frames.push_back(Frame(pt1, pt2, pt3)); xml.popTag(); } */ } void dataSmoother::drawTriangles(int curFrame) { // draw the triangles if data loaded //ofPushMatrix(); //curFrame = fingerMovie.getCurrentFrame(); ofSetColor(255,0,0); ofNoFill(); ofRect(200, 200, 100, 100); ofLine(10, 30, 150, 60); //ofLine(frames[frameNum].p1, frames[frameNum].p2); //ofTriangle( Pt1x[curFrame], Pt1y[curFrame], Pt2y[curFrame], Pt2y[curFrame], Pt3x[curFrame], Pt3y[curFrame]); ofEnableSmoothing(); ofLine(Pt1x[curFrame], Pt1y[curFrame], Pt2y[curFrame], Pt2y[curFrame]); ofLine(Pt2y[curFrame], Pt2y[curFrame], Pt3x[curFrame], Pt3y[curFrame]); ofLine(Pt3x[curFrame], Pt3y[curFrame], Pt1x[curFrame], Pt1y[curFrame]); ofDisableSmoothing(); //printf("triangle x1:%f y1:%f x2:%f y2:%f x3:%f y3:%f", Pt1x[curFrame], Pt1y[curFrame], Pt2y[curFrame], Pt2y[curFrame], Pt3x[curFrame], Pt3y[curFrame]); //ofLine(frames[frameNum].p2, frames[frameNum].p3); //ofLine(frames[frameNum].p3, frames[frameNum].p1); //ofPopMatrix(); } void dataSmoother::updateValues() { // if the slider value has changed, smooth values // slider values vary number of mean average sample values either side the frame for smoothing. } void dataSmoother::saveXML() { // once happy with the smoothing, write out 25 new xml files in a new folder }
#ifndef __CHATTY_LOGGER_H__ #define __CHATTY_LOGGER_H__ #include <string.h> #include <iostream> namespace chatty { #define LOGERROR \ std::cerr << "ERROR | " << __FILE__ << " | "<< __LINE__ << " | " << strerror(errno) #define LOGDEBUG std::cerr << "DEBUG | " << __FILE__ << " | "<< __LINE__ << " | " } // namespace chatty #endif // __CHATTY_LOGGER_H__
#include <SPI.h> int SERcounter; int SERcounter1; int _OEcounter; int RCLKcounter; int SRCLKcounter; int _SRCLRcounter; int SER = 8; int _OE = 7; int RCLK = 6; int SRCLK = 5; int _SRCLR = 4; int testpin = A0; int RCLKprev; int SRCLKprev; int _SRCLRprev; float testvalue; void setup() { pinMode(SER, OUTPUT); pinMode(_OE, OUTPUT); pinMode(RCLK, OUTPUT); pinMode(SRCLK, OUTPUT); pinMode(_SRCLR, OUTPUT); pinMode(testpin, INPUT); Serial.begin(9600); digitalWrite(_SRCLR, LOW); //Clear serial registers digitalWrite(_OE, HIGH); //Disable Output } void loop() { if (millis() - SRCLKcounter > 30) { digitalWrite(SRCLK, SRCLKprev); SRCLKcounter = millis(); } if (millis() - SERcounter > 1000) { // Need two loops to send a pulse of length x every y seconds while (SERcounter1 < 100) { digitalWrite(SER, HIGH); SERcounter1++; } digitalWrite(SER, LOW); SERcounter = millis(); SERcounter1 = 0; } if (millis() - RCLKcounter > 30) { digitalWrite(RCLK, RCLKprev); RCLKcounter = millis(); RCLKprev = !RCLKprev; } // if (millis() - _SRCLRcounter > 10) { digitalWrite(_SRCLR, HIGH); // _SRCLRcounter = millis(); // } // if (millis() - _OEcounter > 10) { digitalWrite(_OE, LOW); // _OEcounter = millis(); // } if (analogRead(testpin) != 0) { Serial.print("Pin analog voltage: "); Serial.println(analogRead(testpin)*5.000/1024, 4); } }
#include<iostream> using namespace std; typedef long long int ll; const ll max1=922337203685477580; const ll min1=-922337203685477580; int main(){ ll k,max=min1,min=max1; while(cin>>k){ if(k>max) max=k; if(k<min) min=k; } cout<<min<<"\n"<<max<<"\n"<<max+min; return 0; }
#ifndef IP_ADDRESS_HPP #define IP_ADDRESS_HPP #include <iostream> #include <string> #include <vector> class IpAddress { public: unsigned m_part1; unsigned m_part2; unsigned m_part3; unsigned m_part4; unsigned m_port; IpAddress(); IpAddress(unsigned part1, unsigned part2, unsigned part3, unsigned part4, unsigned port); IpAddress(const std::string& ipStr); std::string str() const; friend bool operator==(const IpAddress& rhs, const IpAddress& lhs); friend bool operator>(const IpAddress& rhs, const IpAddress& lhs); friend bool operator<(const IpAddress& rhs, const IpAddress& lhs); friend std::ostream& operator<<(std::ostream& out, const IpAddress& ip) { out << ip.str(); return out; } }; #endif // !IP_ADDRESS_HPP
/** * @file bluetooth_reciever.cpp * @author your name (you@domain.com) * @brief * @version 0.1 * @date 2021-08-16 * * @copyright Copyright (c) 2021 * */ #include "bluetooth_reciever.h" #include "BluetoothSerial.h" #include "printer.h" void BlueToothRetriever::setupRetriever(){ PRINT("Starting Bluetooth\n"); BlueToothRetriever::SerialBT = BluetoothSerial(); SerialBT.begin(); PRINT("Bluetooth started\n"); } void BlueToothRetriever::updateRetriever(){ // PRINT("Running Update BT\n"); if(BlueToothRetriever::SerialBT.available()){ Message * messageBuffer = this->getMessageBuffer(); SerialBT.readBytesUntil(Utils::LEDSerial::finalSerialByte, (uint8_t *)( messageBuffer->begin()), MAX_MESSAGE_LENGTH); // hack lmfao this->enqueue_message(messageBuffer); } }
#include <iostream> #include <cmath> #include <cstring> #define LL long long using namespace std; const double eps = 1e-7; int main() { char s[30]; while (cin >> s && strcmp(s, "0e0") != 0) { LL A = s[0] - '0', B = 0; for (int i = 2; i < 17; i++) A = A * 10 + s[i] - '0'; for (int i = 18; i < strlen(s); i++) B = B * 10 + s[i] - '0'; double t = log10(A) + B - 15; bool flag = false; for (int i = 0; i < 10; i++) { for (int j = 1; j <= 30; j++) { double X = 1 - pow(2, -1 - i), Y = pow(2, j) - 1; double ans = log10(X) + Y * log10(2); if (fabs(ans - t) < eps) { flag = true; cout << i << ' ' << j << endl; break; } } if (flag) break; } } return 0; }
#include <maya/MGlobal.h> #include <maya/MPxCommand.h> #include <maya/MSyntax.h> #include <maya/MStatus.h> #include <maya/MArgList.h> #include <maya/MArgDatabase.h> #include <maya/MDagPath.h> #include <maya/MSelectionList.h> #include <maya/MFnTransform.h> #include <maya/MItSelectionList.h> #include <maya/MFn.h> #include <maya/MEulerRotation.h> #include <maya/MVector.h> #include <maya/MFnPlugin.h> #include <maya/MObject.h> const char *timeFlag = "-t", *timeLongFlag = "-time"; const double TWOPI = 3.1415926 * 2; const char *cmdName = "clock"; class ClockCmd : public MPxCommand { public: virtual MStatus doIt(const MArgList &args); virtual MStatus undoIt(); virtual MStatus redoIt(); virtual bool isUndoable(); static void * creator() { return new ClockCmd; } static MSyntax newSyntax(); private: bool isQuery; int prevTime, newTime; MDagPath hourHandPath, minuteHandPath; int getTime(); void setTime(const int time); }; MStatus ClockCmd::doIt(const MArgList & args) { MStatus stat; MArgDatabase argData(syntax(), args, &stat); if (!stat) { return stat; } isQuery = argData.isQuery(); if (argData.isFlagSet(timeFlag) && !isQuery) { argData.getFlagArgument(timeFlag, 0, newTime); } // get a list of currently selected objects MSelectionList selection; MGlobal::getActiveSelectionList(selection); MDagPath dagPath; MFnTransform transformFn; MString name; // Iterate over the transforms MItSelectionList iter(selection, MFn::kTransform); for (; !iter.isDone(); iter.next()) { iter.getDagPath(dagPath); transformFn.setObject(dagPath); name = transformFn.name(); if (name == MString("hour_hand")) { hourHandPath = dagPath; } else { if (name == MString("minute_hand")) { minuteHandPath = dagPath; } } } // Neither hour nor minute hand selected if (!hourHandPath.isValid() || !minuteHandPath.isValid()) { MGlobal::displayError("Select hour and minute hands"); return MS::kFailure; } prevTime = getTime(); if (isQuery) { setResult(prevTime); return MS::kSuccess; } // if edit mode return redoIt(); } MStatus ClockCmd::undoIt() { //return MStatus(); setTime(prevTime); return MS::kSuccess; } MStatus ClockCmd::redoIt() { //return MStatus(); setTime(newTime); return MS::kSuccess; } bool ClockCmd::isUndoable() { //return true; return isQuery ? false : true; } MSyntax ClockCmd::newSyntax() { MSyntax syntax; syntax.addFlag(timeFlag, timeLongFlag, MSyntax::kLong); syntax.enableQuery(true); syntax.enableEdit(true); return syntax; } int ClockCmd::getTime() { // Get the time from the rotation MFnTransform transformFn; transformFn.setObject(hourHandPath); MEulerRotation rot; transformFn.getRotation(rot); // Determine the time and format it int a = int( -rot.y * (1200.0 / TWOPI)); int time = (a / 100 * 100) + int(floor((a % 100) * (6.0 / 10.0) + 0.5)); ; return time; } void ClockCmd::setTime(const int time) { MFnTransform transformFn; // Calculate the hour and minutes int hour = (time / 100) % 12; int minutes = time % 100; // Rotate the hour hand by the required amount transformFn.setObject(hourHandPath); transformFn.setRotation(MEulerRotation(MVector(0.0, hour * (-TWOPI / 12) + minutes * (-TWOPI / 720.0), 0))); // Rotate the minute hand by the required amount transformFn.setObject(minuteHandPath); transformFn.setRotation(MEulerRotation(MVector(0.0, minutes * (-TWOPI / 60.0), 0))); } MStatus initializePlugin(MObject obj) { MFnPlugin pluginFn(obj, "jason.li", "0.1"); MStatus stat; stat = pluginFn.registerCommand(cmdName, ClockCmd::creator, ClockCmd::newSyntax); if (!stat) { stat.perror("registerCommand failed."); } return stat; } MStatus uninitializePlugin(MObject obj) { MFnPlugin pluginFn(obj); MStatus stat; stat = pluginFn.deregisterCommand(cmdName); if (!stat) { stat.perror("deregisterCommand failed."); } return stat; }
#include "person.h" Person::Person() { name_ = "undefine"; age_ = 0; } Person::Person(string name, unsigned age) { name_ = name; age_ = age; } Person::~Person() { } ostream &operator<<(ostream &os, const Person &item) { os << item.name_ << "\t" << item.age_; return os; }
#include "rdtsc_benchmark.h" #include "ut.hpp" #include <random> #include <algorithm> #include <math.h> #include <functional> #include <vector> #include "linalg.h" using namespace boost::ut; // provides `expect`, `""_test`, etc using namespace boost::ut::bdd; // provides `given`, `when`, `then` __m256d data_loader( __m256d a, __m256d b, __m256d c ) { return a; } __m256d mmadd_2x2_reg( __m256d a, __m256d b, __m256d c ) { double A[4] __attribute__ ((aligned(32))); double B[4] __attribute__ ((aligned(32))); double C[4] __attribute__ ((aligned(32))); _mm256_store_pd(A, a); _mm256_store_pd(B, b); _mm256_store_pd(C, c); mmadd_2x2(A, B, C); return a; //dummy } int main() { // Test: double A[4] __attribute__ ((aligned(32))) = {0., 1., 2., 3.}; double B[4] __attribute__ ((aligned(32))) = {1., 2., 3., 4.}; double C[4] __attribute__ ((aligned(32))) = {8., 9., 16., 21.}; __m256d const a = _mm256_load_pd( A ); __m256d const b = _mm256_load_pd( B ); __m256d const c = _mm256_load_pd( C ); Benchmark<decltype(&_mmadd_2x2_avx_v2)> bench("mmadd_2x2 benchmark"); bench.data_loader = data_loader; bench.add_function(&mmadd_2x2_reg, "base", 0.0); bench.funcFlops[0] = mmadd_2x2_flops(A, B, C); bench.funcBytes[0] = 8*mmadd_2x2_memory(A, B, C); bench.add_function(&_mmadd_2x2_avx_v2, "avx_v2", 0.0); bench.funcFlops[1] = mmadd_2x2_flops(A, B, C); bench.funcBytes[1] = 8*mmadd_2x2_memory(A, B, C); bench.run_benchmark(a, b, c); return 0; }
#include <iostream> using namespace std; int main() { int i = 1; while(i <= 12) { cout << "2 x " << i << " = " << (2*i) << endl; i++; } return 0; }
#ifndef PLAYER #define CAMERA #include "GameInfo.h" #include <math.h> #include "KeyPressed.h" #include "MouseClicked.h" class Player { private: const int width = 16 * 50; const int height = 9 * 50; float pitch = 0.0, yaw = 0.0; float camX = 0.0, camZ = 0.0, camY = 30.0; bool isShot = false; float shotPower = 0.0; public: float PlayerPitch = 0.0, PlayerYaw = 0.0; static Player* Instance(); void PlayerCtrl(); void moveCtrl(); void drawPlayer(); KeyPressed* getKey() { return KeyPressed::Instance(); }; MouseClicked* getmouse() { return MouseClicked::Instance(); }; private: Player() { } virtual ~Player() { } }; #endif
// // Created by griha on 01.12.17. // #pragma once #ifndef MIKRONSST_HSM_IDECRYPTER_H #define MIKRONSST_HSM_IDECRYPTER_H #include <windows.h> #include <wincrypt.h> #include <unknwn.h> #include "error.hpp" #include "crypto_context.hpp" #include "input_output.hpp" namespace griha { namespace hsm { enum class KeyParam : DWORD { Mode = KP_MODE, Padding = KP_PADDING }; enum class CipherMode : DWORD { ECB = CRYPT_MODE_ECB, CBC = CRYPT_MODE_CBC, CFB = CRYPT_MODE_CFB, OFB = CRYPT_MODE_OFB, CTS = CRYPT_MODE_CTS }; enum class Padding : DWORD { Pkcs5 = PKCS5_PADDING, Random = RANDOM_PADDING, Zero = ZERO_PADDING }; static const GUID IID_ICipher = { 0x2465d915, 0xd66a, 0x497d, {0xb9, 0x0e, 0xc2, 0xae, 0xc2, 0xfb, 0x77, 0x4b} }; struct ICipher : public IUnknown { virtual HRESULT STDMETHODCALLTYPE Decrypt(IInput *in, IOutput *out, IError *error_sink) = 0; virtual HRESULT STDMETHODCALLTYPE Encrypt(IInput *in, IOutput *out, IError *error_sink) = 0; }; static const GUID IID_IRsaCipher = { 0x1a20e261, 0x1b77, 0x45de, {0xa4, 0xf6, 0x34, 0x62, 0x5a, 0x5b, 0xcb, 0x67} }; struct IRsaCipher : public ICipher { virtual HRESULT STDMETHODCALLTYPE TrapdoorPub(IInput *in, IOutput *out, IError *err_sink) = 0; virtual HRESULT STDMETHODCALLTYPE TrapdoorPri(IInput *in, IOutput *out, IError *err_sink) = 0; }; }} // namespace griha::hsm #endif //MIKRONSST_HSM_IDECRYPTER_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "modules/widgets/OpMultiEdit.h" #include "adjunct/quick/widgets/OpPrivateBrowsingBar.h" #include "adjunct/quick_toolkit/widgets/OpGroup.h" #include "adjunct/quick_toolkit/widgets/OpLabel.h" #include "modules/widgets/OpButton.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" DEFINE_CONSTRUCT(OpPrivateBrowsingBar) OpPrivateBrowsingBar::OpPrivateBrowsingBar() { m_checkbox = NULL; // OpBar has to have a name to perform actions! what? SetName("Private Mode Bar"); if(OpStatus::IsSuccess(OpMultilineEdit::Construct(&m_text))) { m_text->SetLabelMode(); AddChild(m_text); //m_text->SetText(UNI_L("Private browsing is enabled in this tab. Opera will forget everything you did when you close the tab.")); } if(OpStatus::IsSuccess(OpButton::Construct(&m_close))) { OpInputAction* close = OP_NEW(OpInputAction, (OpInputAction::ACTION_SET_ALIGNMENT, ALIGNMENT_OFF, 0, 0, 0, Str::NOT_A_STRING, "Caption Close")); m_close->SetAction(close); m_close->GetForegroundSkin()->SetImage("Caption Close"); m_close->SetButtonStyle(OpButton::STYLE_IMAGE); AddChild(m_close); } if(OpStatus::IsSuccess(OpButton::Construct(&m_more_info))) { OpInputAction* close = OP_NEW(OpInputAction,(OpInputAction::ACTION_SET_ALIGNMENT, ALIGNMENT_OFF)); OpInputAction* go_to_privacy_page = OP_NEW(OpInputAction,(OpInputAction::ACTION_GO_TO_PRIVACY_INTRO_PAGE)); close->SetActionOperator(OpInputAction::OPERATOR_AND); close->SetNextInputAction(go_to_privacy_page); m_more_info->SetAction(close); m_more_info->SetText(UNI_L("More information")); AddChild(m_more_info); } if (OpStatus::IsSuccess(OpButton::Construct(&m_checkbox))) { m_checkbox->SetButtonType(OpButton::TYPE_CHECKBOX); m_checkbox->SetFixedTypeAndStyle(TRUE); m_checkbox->SetText(UNI_L("Do not show this again")); AddChild(m_checkbox); } SetAlignment(OpBar::ALIGNMENT_OFF); GetBorderSkin()->SetImage("Content Block Toolbar Skin"); } void OpPrivateBrowsingBar::OnChange(OpWidget *widget, BOOL changed_by_mouse) { if(widget == m_checkbox) { #ifdef PREFS_CAP_SHOW_PRIVATE_BROWSING_BAR TRAPD(err,g_pcui->WriteIntegerL(PrefsCollectionUI::ShowPrivateBrowsingBar, !widget->GetValue())); #endif } } void OpPrivateBrowsingBar::OnLayout(BOOL compute_size_only, INT32 available_width, INT32 available_height, INT32& used_width, INT32& used_height) { m_text->SetText(UNI_L("Private browsing is enabled in this tab. Opera will forget everything you did when you close the tab.")); // calculate the room for text INT32 close_width, close_height, more_info_width, more_info_height, check_box_width, check_box_height, height,offset_y = 0, padding_top, padding_bottom, padding_left, padding_right, padding_vertical, padding_horizontal, dummy; GetPadding(&padding_left, &padding_top, &padding_right, &padding_bottom); padding_vertical = padding_top + padding_bottom; padding_horizontal = padding_left + padding_right; padding_top += 2; m_close->GetPreferedSize(&close_width, &close_height, 0, 0); m_more_info->GetPreferedSize(&more_info_width, &more_info_height, 0, 0); m_checkbox->GetPreferedSize(&check_box_width, &check_box_height, 0, 0); height = MAX(check_box_height,MAX(close_height,more_info_height)) + 2; used_height = height*2 + padding_bottom + padding_top; used_width = available_width; // animation if(IsAnimating()) { double p = m_animation_in ? m_animation_progress : 1.0 - m_animation_progress; offset_y = used_height*(p-1); used_height *= p; } if(!compute_size_only) { INT32 label_2row_height; m_text->GetPreferedSize(&dummy, &label_2row_height, 1, 2); INT32 text_width = available_width - MAX(check_box_width, (close_width + more_info_width)) - padding_horizontal; if(text_width <= 0) { m_text->SetVisibility(FALSE); } else { //m_text->SetWrap(TRUE); m_text->SetRect(OpRect(padding_left, padding_top + offset_y, text_width,label_2row_height)); m_text->SetVisibility(TRUE); } // Buttons m_more_info->SetRect(OpRect(available_width - close_width - more_info_width - padding_right, padding_top + offset_y, more_info_width, more_info_height)); m_close->SetRect (OpRect(available_width - close_width - padding_right, padding_top + offset_y, close_width, close_height)); m_checkbox->SetRect (OpRect(available_width - check_box_width - padding_right, height + padding_top + offset_y, check_box_width, check_box_height)); } }
#ifndef PRAC4_H #define PRAC4_H #include <QDialog> namespace Ui { class prac4; } class prac4 : public QDialog { Q_OBJECT public: explicit prac4(QWidget *parent = 0); ~prac4(); private slots: void on_pushButton_clicked(); private: Ui::prac4 *ui; }; #endif // PRAC4_H
#include <bits/stdc++.h> using namespace std; void solve () { long long x, y; long long a, b; cin >> x >> y; cin >> a >> b; long long sumA = 0, sumB = 0; sumA = b * min(x, y) + a * abs(x - y); sumB = a * (x + y); // cout << sumA << " " << sumB << endl; cout << min(sumA, sumB) << endl; } int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; while (n--) { solve(); } return 0; }
// // Created by 钟奇龙 on 2019-05-03. // #include <iostream> #include <map> #include <set> using namespace std; class Node{ public: int data; Node *left; Node *right; Node(int x):data(x),left(NULL),right(NULL){} }; //普通解法 Node* getCommonAncestor(Node *root,Node *node1,Node *node2){ if(!root || root == node1 || root == node2) return root; Node *left = getCommonAncestor(root->left,node1,node2); Node *right = getCommonAncestor(root->right,node1,node2); if(left && right){ return root; } return left == NULL ? right:left; } //哈希表解法 map<Node*,Node*> ancestor_map; void setNodeMap(Node *root){ if(!root) return; if(root->left){ ancestor_map[root->left] = root; } if(root->right){ ancestor_map[root->right] = root; } setNodeMap(root->left); setNodeMap(root->right); } Node* query(Node* node1,Node* node2){ set<Node*> ancestor_set; while(ancestor_map.find(node1) != ancestor_map.end()){ ancestor_set.insert(ancestor_map[node1]); node1 = ancestor_map[node1]; } while(ancestor_set.find(node2) == ancestor_set.end()){ node2 = ancestor_map[node2]; } return node2; }
#pragma once #include "DrawGraph.h" class DrawTriangle : public DrawGraph { public: DrawTriangle() { } virtual void drawGraph() override; ~DrawTriangle() { } virtual void initBuffer() override; private: // 定义顶点数据 把它作为输入发送给顶点着色器 float vertices[9] = { // 这里是三角形的3个点的坐标,因为绘制的是二维的,所以z轴是0 z轴也是所谓的深度 比如被遮挡了,就是z轴在之后,这个在渲染中是会被丢弃的 -0.5f, -0.5f, 0.0f, 0.5f, -0.5f , 0.0f, 0.0f, 0.5f, 0.0f }; };
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "SMITElabs/Public/SLGod.h" #include "SMITElabs/Public/SLAgni.h" #include "SLAgniRainFire.generated.h" class ASLGod; class ASLAgni; UCLASS() class SMITELABS_API ASLAgniRainFire : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ASLAgniRainFire(); void SetOrigin(ASLGod* Val); void SetDamage(float Val); void SetScaling(float Val); void SetBHasCombustion(bool Val); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Scene") USceneComponent* SceneComponent; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Mesh") UStaticMeshComponent* MeteorComponent; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Mesh") UStaticMeshComponent* DamageAreaComponent; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Material") UMaterial* MRainFireExplosion; ASLGod* Origin; FTimerHandle MeteorMovementTimerHandle; FVector StartingLocation; TArray<ASLGod*> HitGods; bool bHasCombustion; float Damage; float Scaling; float DirectionalMultiplier{ 1 }; void AdjustMeteor(); public: // Called every frame virtual void Tick(float DeltaTime) override; };
//扩展欧几里得算法 long long exgcd(long long a,long long b,long long &x,long long &y) { if (b==0) { x=1,y=0; return a; } long long d=exgcd(b,a%b,x,y); long long tmp=x; x=y; y=tmp-a/b*y; return d; }#include <bits/stdc++.h> using namespace std; #define Int register int #define mod 998244353ll #define int long long int inv2 = 499122177ll,inv6 = 166374059ll; struct Ans{int f,g,h;}; Ans Solve (int a,int b,int c,int n) { if (!a) { int f = (n + 1) * (b / c) % mod; int g = (n + 1) * (b / c) % mod * (b / c) % mod; int h = n * (n + 1) % mod * inv2 % mod * (b / c) % mod; return Ans {f % mod,g % mod,h % mod}; } else if (a >= c || b >= c) { Ans fucker = Solve (a % c,b % c,c,n); int F = fucker.f + n * (n + 1) / 2 % mod * (a / c) % mod + (n + 1) * (b / c) % mod; int G = fucker.g + 2 * (a / c) % mod * fucker.h % mod + 2 * (b / c) % mod * fucker.f + n % mod * (n + 1) % mod * (2 * n % mod + 1) % mod * inv6 % mod * (a / c) % mod * (a / c) % mod + n % mod * (n + 1) % mod * (a / c) % mod * (b / c) % mod + (n + 1) * (b / c) % mod * (b / c) % mod; int H = fucker.h + n % mod * (n + 1) % mod * (2 * n + 1) % mod * inv6 % mod * (a / c) % mod + n % mod * (n + 1) % mod * inv2 % mod * (b / c) % mod; return Ans {F % mod,G % mod,H % mod}; } else { int M = (a * n + b) / c; Ans fucker = Solve (c,c - b - 1,a,M - 1); int F = n * M % mod - fucker.f; int G = n * M % mod * (M + 1) % mod - 2 * fucker.h % mod + mod - 2 * fucker.f % mod + mod - F % mod; int H = (M * n % mod * (n + 1) % mod - fucker.g + mod - fucker.f) % mod * inv2 % mod; return Ans {F % mod,G % mod,H % mod}; } } int read () { int x = 0;char c = getchar();int f = 1; while (c < '0' || c > '9'){if (c == '-') f = -f;c = getchar();} while (c >= '0' && c <= '9'){x = (x << 3) + (x << 1) + c - '0';c = getchar();} return x * f; } void write (int x) { if (x < 0){x = -x;putchar ('-');if (x > 9) write (x / 10); putchar (x % 10 + '0'); } signed main() { int times = read (); while (times --) { int n = read (),a = read (),b = read (),c = read (); Ans Putout = Solve (a,b,c,n); write ((Putout.f + mod) % mod),putchar (' '),write ((Putout.g + mod) % mod),putchar (' '),write ((Putout.h + mod) % mod),putchar ('\n'); } return 0; } //类欧几里得算法 /* sum_{i=0}^n floor((a*i+b)/c) sum_{i=0}^n (floor((a*i+b)/c))^2 sum_{i=0}^n (floor((a*i+b)/c)*i) */ #include <bits/stdc++.h> using namespace std; #define Int register int #define mod 998244353ll #define int long long int inv2 = 499122177ll,inv6 = 166374059ll; struct Ans{int f,g,h;}; Ans Solve (int a,int b,int c,int n) { if (!a) { int f = (n + 1) * (b / c) % mod; int g = (n + 1) * (b / c) % mod * (b / c) % mod; int h = n * (n + 1) % mod * inv2 % mod * (b / c) % mod; return Ans {f % mod,g % mod,h % mod}; } else if (a >= c || b >= c) { Ans fucker = Solve (a % c,b % c,c,n); int F = fucker.f + n * (n + 1) / 2 % mod * (a / c) % mod + (n + 1) * (b / c) % mod; int G = fucker.g + 2 * (a / c) % mod * fucker.h % mod + 2 * (b / c) % mod * fucker.f + n % mod * (n + 1) % mod * (2 * n % mod + 1) % mod * inv6 % mod * (a / c) % mod * (a / c) % mod + n % mod * (n + 1) % mod * (a / c) % mod * (b / c) % mod + (n + 1) * (b / c) % mod * (b / c) % mod; int H = fucker.h + n % mod * (n + 1) % mod * (2 * n + 1) % mod * inv6 % mod * (a / c) % mod + n % mod * (n + 1) % mod * inv2 % mod * (b / c) % mod; return Ans {F % mod,G % mod,H % mod}; } else { int M = (a * n + b) / c; Ans fucker = Solve (c,c - b - 1,a,M - 1); int F = n * M % mod - fucker.f; int G = n * M % mod * (M + 1) % mod - 2 * fucker.h % mod + mod - 2 * fucker.f % mod + mod - F % mod; int H = (M * n % mod * (n + 1) % mod - fucker.g + mod - fucker.f) % mod * inv2 % mod; return Ans {F % mod,G % mod,H % mod}; } } int read () { int x = 0;char c = getchar();int f = 1; while (c < '0' || c > '9'){if (c == '-') f = -f;c = getchar();} while (c >= '0' && c <= '9'){x = (x << 3) + (x << 1) + c - '0';c = getchar();} return x * f; } void write (int x) { if (x < 0){x = -x;putchar ('-');} if (x > 9) write (x / 10); putchar (x % 10 + '0'); } signed main() { int times = read (); while (times --) { int n = read (),a = read (),b = read (),c = read (); Ans Putout = Solve (a,b,c,n); write ((Putout.f + mod) % mod),putchar (' '),write ((Putout.g + mod) % mod),putchar (' '),write ((Putout.h + mod) % mod),putchar ('\n'); } return 0; } //更一般的情况#include <iostream> #include <stdio.h> #include <math.h> #include <string.h> #include <time.h> #include <stdlib.h> #include <string> #include <bitset> #include <vector> #include <set> #include <map> #include <queue> #include <algorithm> #include <sstream> #include <stack> #include <iomanip> using namespace std; #define pb push_back #define mp make_pair typedef pair<int,int> pii; typedef long long ll; typedef double ld; typedef vector<int> vi; #define fi first #define se second #define fe first #define FO(x) {freopen(#x".in","r",stdin);freopen(#x".out","w",stdout);} #define Edg int M=0,fst[SZ],vb[SZ],nxt[SZ];void ad_de(int a,int b){++M;nxt[M]=fst[a];fst[a]=M;vb[M]=b;}void adde(int a,int b){ad_de(a,b);ad_de(b,a);} #define Edgc int M=0,fst[SZ],vb[SZ],nxt[SZ],vc[SZ];void ad_de(int a,int b,int c){++M;nxt[M]=fst[a];fst[a]=M;vb[M]=b;vc[M]=c;}void adde(int a,int b,int c){ad_de(a,b,c);ad_de(b,a,c);} #define es(x,e) (int e=fst[x];e;e=nxt[e]) #define esb(x,e,b) (int e=fst[x],b=vb[e];e;e=nxt[e],b=vb[e]) typedef long long ll; const int MOD=1e9+7; inline ll qp(ll a,ll b) { ll x=1; a%=MOD; while(b) { if(b&1) x=x*a%MOD; a=a*a%MOD; b>>=1; } return x; } namespace Lagrange { ll x[23333],y[23333],a[23333],g[23333],h[23333],p[23333]; int N; void work() { for(int i=0;i<N;++i) a[i]=0; g[0]=1; for(int i=0;i<N;++i) { for(int _=0;_<=i;++_) h[_+1]=g[_]; h[0]=0; for(int _=0;_<=i;++_) h[_]=(h[_]-g[_]*(ll)x[i])%MOD; for(int _=0;_<=i+1;++_) g[_]=h[_]; } for(int i=0;i<N;++i) { for(int j=0;j<=N;++j) p[j]=g[j]; for(int j=N;j;--j) p[j-1]=(p[j-1]+p[j]*(ll)x[i])%MOD; ll s=1; for(int j=0;j<N;++j) if(i!=j) s=s*(x[i]-x[j])%MOD; s=y[i]*qp(s,MOD-2)%MOD; for(int _=0;_<N;++_) a[_]=(a[_]+p[_+1]*s)%MOD; } } vector<int> feed(vector<int> v) { N=v.size(); for(int i=0;i<N;++i) x[i]=i,y[i]=v[i]; work(); v.clear(); for(int i=0;i<N;++i) v.pb(a[i]); while(v.size()&&!v.back()) v.pop_back(); return v; } ll calc(vector<int>&v,ll xx) { ll s=0,gg=1; xx%=MOD; for(int i=0;i<N;++i) s=(s+gg*v[i])%MOD,gg=gg*xx%MOD; return s; } } using Lagrange::feed; using Lagrange::calc; //ps[k]=\sum_{i=0}^x i^k vector<int> ps[2333]; //rs[k]=\sum_{i=0}^x ((i+1)^k-i^k) vector<int> rs[2333]; struct arr{ll p[11][11];}; ll C[233][233]; arr calc(ll a,ll b,ll c,ll n) { arr w; if(n==0) a=0; if(a==0||a*n+b<c) { for(int i=0;i<=10;++i) { ll t=calc(ps[i],n),s=b/c; for(int j=0;i+j<=10;++j) w.p[i][j]=t,t=t*s%MOD; } return w; } for(int i=0;i<=10;++i) w.p[i][0]=calc(ps[i],n); if(a>=c||b>=c) { arr t=calc(a%c,b%c,c,n); ll p=a/c,q=b/c; for(int i=0;i<=10;++i) for(int j=1;i+j<=10;++j) { ll s=0,px=1; for(int x=0;x<=j;++x,px=px*p%MOD) { ll qy=1; for(int y=0;x+y<=j;++y,qy=qy*q%MOD) { //x^(i) (px)^x q^y ??^(j-x-y) s+=px*qy%MOD*C[j][x]%MOD*C[j-x][y] %MOD*t.p[i+x][j-x-y]; s%=MOD; } } w.p[i][j]=s; } return w; } ll m=(a*n+b)/c; arr t=calc(c,c-b-1,a,m-1); for(int i=0;i<=10;++i) for(int j=1;i+j<=10;++j) { ll s=calc(rs[j],m-1)*calc(ps[i],n)%MOD; for(int p=0;p<j;++p) { for(unsigned q=0;q<ps[i].size();++q) { ll v=C[j][p]*ps[i][q]%MOD; //v*t^p*((tc+c-b-1)/a)^q s-=t.p[p][q]*v; s%=MOD; } } w.p[i][j]=s%MOD; } return w; } int T,n,a,b,c,k1,k2; int main() { for(int i=0;i<=230;++i) { C[i][0]=1; for(int j=1;j<=i;++j) C[i][j]=(C[i-1][j-1]+C[i-1][j])%MOD; } for(int i=0;i<=10;++i) { ll sp=0,sr=0; vector<int> p,r; for(int j=0;j<=20;++j) sp+=qp(j,i),sr+=qp(j+1,i)-qp(j,i), sp%=MOD,sr%=MOD,p.pb(sp),r.pb(sr); ps[i]=feed(p); rs[i]=feed(r); } scanf("%d",&T); while(T--) { scanf("%d%d%d%d%d%d", &n,&a,&b,&c,&k1,&k2); arr s=calc(a,b,c,n); int p=s.p[k1][k2]; p=(p%MOD+MOD)%MOD; printf("%d\n",p); } }
#include "Type.h" #include "Value.h" #include "String.h" #include "Array.h" #include "Map.h" #include "GC.h" #include "CFunc.h" #include "Object.h" #include "VM.h" #include <unistd.h> Types::Types(VM *vm) : stringType(new StringType(this, vm->gc)), arrayType(new ArrayType(this, vm->gc)), mapType(new MapType(this, vm->gc)), functionType(new FunctionType(this, vm)), defaultType(new Type(this)) { } Types::~Types() { delete stringType; delete arrayType; delete mapType; delete functionType; delete defaultType; } Type *Types::type(Value v) { assert(!IS_NIL(v)); if (IS_STRING(v)) { return stringType; } else if (IS_ARRAY(v)) { return arrayType; } else if (IS_MAP(v)) { return mapType; } else if (IS_FUNC(v) || IS_CFUNC(v) || IS_CF(v)) { return functionType; } else { return defaultType; } } // -- String -- StringType::StringType(Types *types, GC *gc) : Type(types), stringSuper(Map::makeMap(gc, "find", CFunc::value(gc, String::findField), NULL)) { gc->addRoot(GET_OBJ(stringSuper)); } Value StringType::indexGet(Value self, Value key) { return key == STR("super") ? stringSuper : String::indexGet(self, key); } // -- Arrray -- ArrayType::ArrayType(Types *types, GC *gc) : Type(types), arraySuper(Map::makeMap(gc, "size", CFunc::value(gc, Array::sizeField), NULL)) { gc->addRoot(GET_OBJ(arraySuper)); } Value ArrayType::indexGet(Value self, Value key) { return key == STR("super") ? arraySuper : ARRAY(self)->indexGet(key); } bool ArrayType::indexSet(Value self, Value key, Value v) { return ARRAY(self)->indexSet(key, v); } // -- Map -- MapType::MapType(Types *types, GC *gc) : Type(types) { } Value MapType::indexGet(Value self, Value key) { return MAP(self)->indexGet(key); } bool MapType::indexSet(Value self, Value key, Value v) { return MAP(self)->indexSet(key, v); } // -- FunctionType -- FunctionType::FunctionType(Types *types, VM *vm) : Type(types), vm(vm) { } Value FunctionType::call(Value self, int nArgs, Value *args) { return vm->run(self, nArgs, args); } // -- Type -- Type::Type(Types *types) : types(types) { } Type *Type::type(Value v) { return types->type(v); } Type::~Type() { } bool Type::hasIndexSet() { return false; } bool Type::hasRemove() { return hasIndexSet(); } bool Type::hasIndexGet() { return hasIndexSet(); } bool Type::hasFieldSet() { return hasIndexSet(); } bool Type::hasFieldGet() { return hasIndexGet(); } bool Type::hasCall() { return false; } Value Type::call(Value self, int nArgs, Value *args) { return VERR; } Value Type::indexGet(Value self, Value key) { // if (key == STATIC_STRING("super")) { return super; } return VERR; } bool Type::indexSet(Value self, Value key, Value v) { return IS_NIL(v) ? remove(self, key) : false; } bool Type::remove(Value self, Value key) { return false; } bool Type::isProperty(Value v) { return !IS_NIL(v) && types->type(v)->indexGet(v, VAL_NUM(0)) == STR("_prop"); } // get without invoking the eventual property.get Value Type::auxFieldGet(Value self, Value key) { Value v = indexGet(self, key); if (IS_NIL(v) && (v=indexGet(self, STR("super")), !IS_NIL(v))) { v = type(v)->fieldGet(v, key); } return v; } Value Type::fieldGet(Value self, Value key) { Value v = auxFieldGet(self, key); if (isProperty(v)) { Value get = type(v)->indexGet(v, VAL_NUM(1)); Type *p = type(get); if (p->hasCall()) { Value args[] = {self, key, v}; v = p->call(get, 3, args); } } return v; } bool Type::fieldSet(Value self, Value key, Value v) { Value old = auxFieldGet(self, key); if (isProperty(old)) { Value set = type(old)->indexGet(old, VAL_NUM(2)); Type *p = type(set); if (p->hasCall()) { Value args[] = {self, key, v, old}; v = p->call(set, 4, args); return true; } return false; } else { return indexSet(self, key, v); } }
/* * Assignennt 2, COMP 5421, summer 2016 * Federico O'Reilly Regueiro 40012304 * Concordia University * * Command header file */ #ifndef LED_COMMAND #define LED_COMMAND #include <iostream> #include <string> #include <cstddef> #include <sstream> using namespace std; /** * Command class used by LED for parsing user input. * Contains members and methods for parsing and validating user input. */ class Command{ public: /** * enum listing all valid commands accepted by the line editor. * Used to pass the command type (in more of a human-readable fashion) * to the caller. */ enum CommandType { insert = 'i', append = 'a', remove = 'r', print = 'p', numberPrint = 'n', change = 'c', up = 'u', down = 'd', write = 'w', printCurrLine = '=', quit = 'q', open = 'o', help = 'h', notRecognized = 'z' }; /** * enum listing the validity status of parsed commands. * Used to pass the important information to the caller which can, in turn, * either execute a valid command or inform the user regarding errors. */ enum CommandStatus { validCommand = 0, invalidChars, invalidSyntax, invalidRange }; /** * An address range structure containing a start end end line address. * Used to pass command-addressing information to the caller. */ struct AddressRange { size_t start; /**<range-start*/ size_t end; /**<range-end*/ /** * Default constructor with an optional parameter. * @param s is both the starting and ending line-addresses. * s defaults to 0 */ AddressRange(const size_t& s = 0) : start(s) , end(s) { } /** * Constructor with both a start and end parameters. * @param s is the start line-address of the specified range. * @param e is the end line-address of the specified range. */ AddressRange(const size_t& s, const size_t& e) : start(s) , end(e) { } /** * Overloaded assignment operator. * Useful when address range is not specified in the command as * the received currentLine is assigned to both start and end. */ AddressRange& operator=(const AddressRange& ar); /** * Explicit request for a default destructor */ virtual ~AddressRange()=default; }; private: static const bool VALID = true; /**<makes reading exit points clearer*/ static const bool INVALID = false; /**<makes reading exit points clearer*/ // static const strings need to be defined outside of the class // see implementation file // The definition of these strings makes changing commands a bit easier // as well as reading the code a bit clearer (I hope) static const string VALID_COMMAND_CHAR; /**<Chars used in valid commands*/ static const string VALID_ADDR_CHAR;/**<Chars used for address ranges*/ static const char DOT; /**<Char used to represent current address */ static const char END; /**<Char used to represent the last buffer line*/ static const string SPECIAL_ADDR_CHAR;/**<Chars that expand to addresses*/ static const string SEPARATOR;/**<The character used as a s,e separator*/ static const string VALID_CHAR;/**<All of the characters that can be used*/ CommandType ct{notRecognized}; /**<used for passing CommandType to caller*/ AddressRange ar; /**<Used for passing the range for the next command*/ // until shown otherwise, initialize as valid CommandStatus cs{validCommand}; /**<Command validation information*/ /** * Function for stripping commands from any whitespace. * @param s is a reference to the string to be pruned from ws. */ void removeWhiteSpace(string& s); public: /** * Explicit request for a default constructor. */ Command()=default; /** * Explicit request for a default destructor */ virtual ~Command()=default; /** * Parse and validate command strings given by the caller. * @param commandBuffer is a string containing the command to be parsed. * @param currentLine is a reference to the current line in the buffer. * It is used as a default address if the address is not specified. * @param totalLines indicates the size of the buffer (in lines). */ bool parse(string& commandBuffer, const size_t& currentLine, const size_t& totalLines); /** * Returns an address range extracted from the last parsed command. */ const AddressRange& getAddressRange() const; /** * Returns the type of command, extracted from the last parsed command. */ const CommandType& getCommandType() const; /** * Returns validation information resulting from the last parsed command. */ const CommandStatus& getCommandStatus() const; }; #endif
#include "Statistics.h" const unsigned int Statistics::repeat_ini; Statistics::Statistics(){ } Statistics::Statistics(Simulator *sim, float sampling) : generator((std::random_device())()) { assert(sim != NULL); assert(sampling >= 0.0); assert(sampling <= 1.0); // cout << "Statistics - Start\n"; pool = sim->getPool(); profile = sim->getProfile(); // cout << "Statistics - Preparing mutations table\n"; mutation_table['A'] = {'C', 'G', 'T'}; mutation_table['C'] = {'A', 'G', 'T'}; mutation_table['G'] = {'A', 'C', 'T'}; mutation_table['T'] = {'A', 'C', 'G'}; // Preparo tablas y cualquier otro dato necesario alleles_tables.resize(profile->getNumMarkers()); alleles_mutations_tables.resize(profile->getNumMarkers()); alleles_ms_tables.resize(profile->getNumMarkers()); alleles_repeats_tables.resize(profile->getNumMarkers()); Population summary(0, profile, pool, generator); vector<string> pop_names = sim->getPopulationNames(); cout << "Statistics - Processing " << pop_names.size() << " populations\n"; for(string name : pop_names){ cout << "Statistics - Population " << name << "\n"; Population *pop = sim->getPopulation(name); processStatistics(pop, name, sampling); cout << "Statistics - Adding individuals to summary\n"; for(unsigned int i = 0; i < pop->size(); ++i){ summary.add( pop->get(i) ); } } cout << "Statistics - Processing the combined population\n"; processStatistics(&summary, "summary", sampling); // cout << "Statistics - End\n"; } Statistics::~Statistics(){ } // Procesa todos los estadisticos y los agrega a statistics[name][stat] void Statistics::processStatistics(Population *pop, string name, float sampling){ cout << "Statistics::processStatistics - Start (population " << name << ", size " << pop->size() << ", sampling " << sampling << ")\n"; unsigned int n_inds = pop->size() * sampling; if(n_inds < min_sampling){ n_inds = min_sampling; } if(n_inds > pop->size()){ n_inds = pop->size(); } // Necesito un shuffle de la poblacion // Para simularlo, puedo desordenar las posiciones cout << "Statistics::processStatistics - Preparing selected individuals (n_inds: " << n_inds << ")\n"; vector<unsigned int> inds_usados; for(unsigned int i = 0; i < pop->size(); ++i){ inds_usados.push_back(i); } shuffle(inds_usados.begin(), inds_usados.end(), generator); // Para esta poblacion: // Iterar por los marcadores // Para cada marcador, calcular SU mapa de estadisticos y agregarlo vector<map<string, double>> stats_vector; cout << "Statistics::processStatistics - Processing " << profile->getNumMarkers() << " markers\n"; for(unsigned int pos_marker = 0; pos_marker < profile->getNumMarkers(); ++pos_marker){ map<string, double> stats; ProfileMarker marker = profile->getMarker(pos_marker); // Lo que sigue depende del tipo de marcador if( marker.getType() == MARKER_SEQUENCE ){ vector<string> alleles; vector< map<unsigned int, char> > alleles_mutations; if( profile->getPloidy() == 1 ){ for(unsigned int ind = 0; ind < n_inds; ++ind){ unsigned int pos_ind = inds_usados[ind]; unsigned int id_allele = pop->get(pos_ind).getAllele(pos_marker); alleles.push_back( getAllele(pos_marker, id_allele, marker) ); alleles_mutations.push_back( alleles_mutations_tables[pos_marker][id_allele] ); } } else{ cerr << "Statistics::processStatistics - Error, Ploidy not supported (" << profile->getPloidy() << ")\n"; } NanoTimer timer; double num_haplotypes = statNumHaplotypes(alleles); stats["num-haplotypes"] = num_haplotypes; timer.reset(); double num_segregating_sites = statNumSegregatingSites(alleles); stats["num-segregating-sites"] = num_segregating_sites; // vector<unsigned int> pairwise_differences = statPairwiseDifferences(alleles); vector<unsigned int> pairwise_differences = statPairwiseDifferencesMutations(alleles_mutations); double mean_pairwise_diff = statMeanPairwiseDifferences(pairwise_differences); stats["mean-pairwise-diff"] = mean_pairwise_diff; double var_pairwise_diff = statVariancePairwiseDifferences(pairwise_differences, mean_pairwise_diff); stats["var-pairwise-diff"] = var_pairwise_diff; double tajima_d = statTajimaD(alleles, num_segregating_sites, mean_pairwise_diff); stats["tajima-d"] = tajima_d; } else if( marker.getType() == MARKER_MS ){ cout << "Statistics::processStatistics - Preparando Data de microsatellites...\n"; vector<string> alleles; if( profile->getPloidy() == 2 ){ unsigned int min_id = 0xffffffff; unsigned int max_id = 0; unsigned int pos_ind = 0; unsigned int id_allele = 0; // Primero busco min y max para determinar limites al string for(unsigned int ind = 0; ind < n_inds; ++ind){ pos_ind = inds_usados[ind]; id_allele = pop->get(pos_ind).getAllele(pos_marker, 0); if( id_allele < min_id ){ min_id = id_allele; } if( id_allele > max_id ){ max_id = id_allele; } id_allele = pop->get(pos_ind).getAllele(pos_marker, 1); if( id_allele < min_id ){ min_id = id_allele; } if( id_allele > max_id ){ max_id = id_allele; } } string str_base = std::to_string( 1 + max_id - min_id ); unsigned int str_len = str_base.length(); if( str_len < 3 ){ str_len = 3; } cout << "Statistics::processStatistics - min_id: " << min_id << ", max_id: " << max_id << ", str_base: \"" << str_base << "\", str_len: " << str_len << "\n"; for(unsigned int ind = 0; ind < n_inds; ++ind){ pos_ind = inds_usados[ind]; id_allele = pop->get(pos_ind).getAllele(pos_marker, 0); string str_part = std::to_string( 1 + id_allele - min_id ); while( str_part.length() < str_len ){ str_part = "0" + str_part; } string str_allele = str_part; id_allele = pop->get(pos_ind).getAllele(pos_marker, 1); str_part = std::to_string( 1 + id_allele - min_id ); while( str_part.length() < str_len ){ str_part = "0" + str_part; } str_allele += str_part; // cout << "Statistics::processStatistics - str_allele: \"" << str_allele << "\"\n"; alleles.push_back(str_allele); } } else{ cerr << "Statistics::processStatistics - Error, Ploidy not supported (" << profile->getPloidy() << ")\n"; } cout << "Statistics::processStatistics - Preparando statistics de microsatellites...\n"; map<unsigned int, unsigned int> ids = statAllelesData(alleles); double num_alleles = ids.size(); stats["num-alleles"] = num_alleles; double heterozygosity = statHeterozygosity(ids); stats["heterozygosity"] = heterozygosity; double effective_num_alleles = statEffectiveNumAlleles(heterozygosity); stats["effective-num-alleles"] = effective_num_alleles; } else{ cerr << "Statistics::processStatistics - Error, Genetic Marker not supperted.\n"; } stats_vector.push_back(stats); } statistics[name] = stats_vector; cout << "Statistics::processStatistics - End (statistics[" << name << "]: " << stats_vector.size() << " stats)\n"; } // Procesa todos los estadisticos de un genepop y los agrega a statistics[name][stat] // Si summary_alleles es diferente de NULL, se agregan los de esta poblacion para generar los stats de Summary void Statistics::processStatistics(string filename, string name, Profile *external_profile, vector<vector<string>> *summary_alleles){ cout << "Statistics::processStatistics - Start (filename " << filename << ", pop_name: " << name << ")\n"; unsigned int n_markers = external_profile->getNumMarkers(); // Leer y parsear el genepop // Notar que lo ideal seria dejarlo esto a un objeto lecto de genepop // En esta version se llena el vector de alelos directamente con strings // vector<string> alleles; // cout << "Statistics::processStatistics - Preparando allele_markers\n"; vector<vector<string>> alleles_marker; alleles_marker.resize(n_markers); // Primero la lectura directa del archivo que tenemos, despues cambio esto a una lectura generica en un GenepopReader // cout << "Statistics::processStatistics - Preparando Lector\n"; ifstream lector(filename, ifstream::in); if( ! lector.is_open() ){ cerr << "Statistics::processStatistics - Can't open file \"" << filename << "\"\n"; return; } // cout << "Statistics::processStatistics - Preparando Buffer\n"; unsigned int buff_size = 1024*1024*10; char *buff = new char[buff_size + 1]; memset(buff, 0, buff_size + 1); // cout << "Statistics::processStatistics - Iniciando Lectura\n"; // Titulo lector.getline(buff, buff_size); // cout << "Statistics::processStatistics - Title: " << buff << "\n"; while( lector.good() ){ lector.getline(buff, buff_size); if( lector.gcount() >= 3 && toupper(buff[0]) == 'P' && toupper(buff[1]) == 'O' && toupper(buff[2]) == 'P' ){ break; } // cout << "Statistics::processStatistics - Loci: " << buff << "\n"; } // // Pop // cout << "Statistics::processStatistics - Pop: " << buff << "\n"; // Inicio de datos while( lector.good() ){ lector.getline(buff, buff_size); unsigned int lectura = lector.gcount(); // Cada linea debe tener al menos id + , + data if( !lector.good() || lectura < 3 ){ break; } string line(buff); replace(line.begin(), line.end(), ',', ' '); replace(line.begin(), line.end(), ';', ' '); // cout << "Statistics::processStatistics - line: " << line << "\n"; stringstream toks(line); string id = ""; string separator = ""; string data = ""; toks >> id; // cout << "Statistics::processStatistics - id: \"" << id << "\"\n"; for( unsigned int i = 0; i < n_markers; ++i ){ toks >> data; // cout << "Statistics::processStatistics - data : \"" << data << "\"\n"; alleles_marker[i].push_back(data); } } delete [] buff; if(summary_alleles != NULL){ // cout << "Statistics::processStatistics - Adding alleles to summary\n"; if( summary_alleles->size() != n_markers ){ summary_alleles->resize(n_markers); } for( unsigned int i = 0; i < n_markers; ++i ){ summary_alleles->at(i).insert( summary_alleles->at(i).begin(), alleles_marker[i].begin(), alleles_marker[i].end() ); } } processStatistics(name, external_profile, &alleles_marker); } // Procesa los stats directamente de una muestra de alelos como string y los asocia a la poblacion "name" void Statistics::processStatistics(string name, Profile *external_profile, vector<vector<string>> *alleles_marker){ unsigned int n_markers = external_profile->getNumMarkers(); assert(n_markers == alleles_marker->size()); cout << "Statistics::processStatistics - Start Internal for pop_name: \"" << name << "\"\n"; vector<map<string, double>> stats_vector; // cout << "Statistics::processStatistics - Processing " << profile->getNumMarkers() << " markers\n"; for(unsigned int pos_marker = 0; pos_marker < n_markers; ++pos_marker){ map<string, double> stats; vector<string> alleles = alleles_marker->at(pos_marker); ProfileMarker marker = external_profile->getMarker(pos_marker); if( marker.getType() == MARKER_SEQUENCE ){ double num_haplotypes = statNumHaplotypes(alleles); stats["num-haplotypes"] = num_haplotypes; double num_segregating_sites = statNumSegregatingSites(alleles); stats["num-segregating-sites"] = num_segregating_sites; vector<unsigned int> pairwise_differences = statPairwiseDifferences(alleles); double mean_pairwise_diff = statMeanPairwiseDifferences(pairwise_differences); stats["mean-pairwise-diff"] = mean_pairwise_diff; double var_pairwise_diff = statVariancePairwiseDifferences(pairwise_differences, mean_pairwise_diff); stats["var-pairwise-diff"] = var_pairwise_diff; double tajima_d = statTajimaD(alleles, num_segregating_sites, mean_pairwise_diff); stats["tajima-d"] = tajima_d; } else if( marker.getType() == MARKER_MS ){ cout << "Statistics::processStatistics - Preparando statistics de microsatellites...\n"; map<unsigned int, unsigned int> ids = statAllelesData(alleles); double num_alleles = ids.size(); stats["num-alleles"] = num_alleles; double heterozygosity = statHeterozygosity(ids); stats["heterozygosity"] = heterozygosity; double effective_num_alleles = statEffectiveNumAlleles(heterozygosity); stats["effective-num-alleles"] = effective_num_alleles; } else{ cerr << "Statistics::processStatistics - Error, Genetic Marker not supperted.\n"; } stats_vector.push_back(stats); } statistics[name] = stats_vector; } // Busca el alelo en la tabla, lo genere recursivamente si no lo encuentra string &Statistics::getAllele(unsigned int marker_pos, unsigned int id, ProfileMarker &marker){ // cout << "Statistics::getAllele - Start (marker_pos: " << marker_pos << ", allele " << id << ", alleles_tables.size " << alleles_tables.size() << ")\n"; map<unsigned int, string>::iterator it = alleles_tables[marker_pos].find(id); if( it != alleles_tables[marker_pos].end() ){ // cout << "Statistics::getAllele - Case 1\n"; return it->second; } else if( id == 0 ){ // cout << "Statistics::getAllele - Case 2 (Creating Origin)\n"; string seq = generateAllele(marker_pos, marker); alleles_tables[marker_pos][id] = seq; if( marker.getType() == MARKER_SEQUENCE ){ map<unsigned int, char> mutations_map; alleles_mutations_tables[marker_pos][id] = mutations_map; } else if( marker.getType() == MARKER_MS ){ alleles_ms_tables[marker_pos][seq] = repeat_ini; alleles_repeats_tables[marker_pos][repeat_ini] = seq; } else{ cerr << "Statistics::getAllele - Error, Genetic Marker not supperted.\n"; } return alleles_tables[marker_pos][id]; } else{ // cout << "Statistics::getAllele - Case 3\n"; // Tomar el allelo padre, y aplicar mutacion // Notar que en la practica, esto depende del tipo de marcador unsigned int parent_id = pool->getParent(marker_pos, id); string parent = getAllele(marker_pos, parent_id, marker); if( marker.getType() == MARKER_SEQUENCE && marker.getMutationType() == MUTATION_BASIC ){ // Aqui ya puedo tomar el mapa de mutaciones del padre porque se genero en getParen // TODO: este mapa solo es valido para datos de tipo secuencia map<unsigned int, char> mutations_map; map<unsigned int, char> mutations_map_parent = alleles_mutations_tables[marker_pos][parent_id]; mutations_map.insert(mutations_map_parent.begin(), mutations_map_parent.end()); uniform_int_distribution<> pos_dist(0, marker.getLength() - 1); unsigned int pos = pos_dist(generator); uniform_int_distribution<> mut_dist(0, 2); unsigned int mut = mut_dist(generator); char new_value = mutation_table[ parent[pos] ][mut]; // cout << "Statistics::getAllele - Marker " << marker_pos // << ", allele " << id // << ", mutation \'" << parent[pos] // << "\' -> \'" << new_value // << "\' in position " << pos << "\n"; mutations_map[pos] = new_value; // En forma especial borro la mutacion si regreso al valor original del primer ancestro // El id del primero (la raiz del arbol) esta fijo en 0 if( alleles_tables[marker_pos][0][pos] == new_value ){ mutations_map.erase(pos); } alleles_mutations_tables[marker_pos][id] = mutations_map; parent[pos] = new_value; } else if( marker.getType() == MARKER_MS && marker.getMutationType() == MUTATION_BASIC ){ cout << "Statistics::getAllele - parent id: " << parent << " (" << std::stoi(parent) << ")\n"; } else{ cerr << "Statistics::getAllele - Error, Mutation model not implemented.\n"; } alleles_tables[marker_pos][id] = parent; return alleles_tables[marker_pos][id]; } } string Statistics::generateAllele(unsigned int marker_pos, ProfileMarker &marker){ // cout << "Statistics::generateAllele - Start\n"; string s; // Generar el string considerando profile // Esto tambien depende del tipo de marcador if( marker.getType() == MARKER_SEQUENCE ){ unsigned int nucleo = 0; uniform_int_distribution<> nucleo_dist(0, 3); for(unsigned int i = 0; i < marker.getLength(); ++i){ nucleo = nucleo_dist(generator); if( nucleo == 0 ){ s.push_back('A'); } else if( nucleo == 1 ){ s.push_back('C'); } else if( nucleo == 2 ){ s.push_back('G'); } else{ s.push_back('T'); } } } else if( marker.getType() == MARKER_MS ){ s = "001"; } else{ // cerr << "Statistics::generateAllele - Sequence model not implemented.\n"; } // cout << "Statistics::generateAllele - End (" << s << ", " << s.length() << ")\n"; return s; } double Statistics::statNumHaplotypes(vector<string> &alleles){ // cout << "Statistics::statNumHaplotypes - Inicio\n"; // NanoTimer timer; if(alleles.size() <= 1){ return 0.0; } map<string, unsigned int> haplotypes; for( string &allele : alleles ){ if( haplotypes.find(allele) == haplotypes.end() ){ haplotypes[allele] = 1; } else{ ++haplotypes[allele]; } } double sum = 0.0; double N = alleles.size(); for( auto& par : haplotypes ){ double f = (double)(par.second); f /= N; sum += (f*f); } double res = ((N/(N-1.0))*(1.0-sum)); // cout << "Statistics::statNumHaplotypes - Fin ("<<timer.getMilisec()<<" ms)\n"; return res; } double Statistics::statNumSegregatingSites(vector<string> &alleles){ // cout << "Statistics::statNumSegregatingSites - Inicio\n"; // NanoTimer timer; if(alleles.size() <= 1){ return 0.0; } // for( string allele : alleles ){ // cout << "Statistics::statNumSegregatingSites - \"" << allele << "\"\n"; // } double res = 0; string ref = alleles[0]; for(unsigned int i = 0; i < ref.length(); i++){ for(unsigned int j = 1; j < alleles.size(); j++){ if( ref.at(i) != alleles[j].at(i) ){ ++res; break; } } } // cout << "Statistics::statNumSegregatingSites - Fin\n"; return res; } vector<unsigned int> Statistics::statPairwiseDifferences(vector<string> &alleles){ // cout << "Statistics::statMeanPairwiseDifferences - Inicio\n"; // NanoTimer timer; vector<unsigned int> pairwise_differences; for(unsigned int i = 0; i < alleles.size(); ++i){ for(unsigned int j = i+1; j < alleles.size(); ++j){ unsigned int diff = 0; for(unsigned int k = 0; k < alleles[i].length(); ++k){ if( alleles[i][k] != alleles[j][k] ){ ++diff; } } pairwise_differences.push_back(diff); } } // cout << "Sample::pairwise_statistics - Fin ("<<timer.getMilisec()<<" ms)\n"; return pairwise_differences; } vector<unsigned int> Statistics::statPairwiseDifferencesMutations(vector< map<unsigned int, char> > &alleles){ // cout << "Statistics::statMeanPairwiseDifferences - Inicio\n"; // NanoTimer timer; vector<unsigned int> pairwise_differences; for(unsigned int i = 0; i < alleles.size(); ++i){ for(unsigned int j = i+1; j < alleles.size(); ++j){ unsigned int diff = 0; // Una forma mas rapida deberia ser usando una diferencia simetrica lineal // Se sacan las posiciones replicadas a posteriori vector< pair<unsigned int, char> > res; std::set_symmetric_difference(alleles[i].begin(), alleles[i].end(), alleles[j].begin(), alleles[j].end(), back_inserter(res)); unsigned int last = 0xffffffff; for( pair<unsigned int, char> it : res ){ if( it.first != last ){ ++diff; last = it.first; } } pairwise_differences.push_back(diff); } } // cout << "Sample::pairwise_statistics - Fin ("<<timer.getMilisec()<<" ms)\n"; return pairwise_differences; } double Statistics::statMeanPairwiseDifferences(vector<unsigned int> &differences){ if(differences.size() <= 1){ return 0.0; } double mean = 0.0; for(unsigned int diff : differences){ mean += diff; } mean /= double(differences.size()); return mean; } double Statistics::statVariancePairwiseDifferences(vector<unsigned int> &differences, double mean){ if(differences.size() <= 1){ return 0.0; } double variance = 0.0; for(unsigned int diff : differences){ variance += (diff-mean) * (diff-mean); } variance /= (double)(differences.size()); return variance; } double Statistics::statTajimaD(vector<string> &alleles, double num_segregating_sites, double mean_pairwise_diff){ // return 0.0; double n = alleles.size(); double ss = num_segregating_sites; double mpd = mean_pairwise_diff; if( n <= 1 || ss == 0 || mpd <= 0){ return 0.0; } double a1 = 0.0; double a2 = 0.0; for(unsigned int k = 1; k < (unsigned int)n; ++k){ a1 += 1.0 / (double)k; a2 += 1.0 / (double)(k*k); } double b1 = (n + 1.0) / ( 3.0 * (n - 1.0) ); double b2 = (2.0 * (n*n + n + 3.0)) / ( (9.0 * n) * (n - 1.0) ); double c1 = b1 - (1.0 / a1); double c2 = b2 + ((n + 2.0) / (a1 * n)) + a2 / (a1 * a1); double e1 = c1 / a1; double e2 = c2 / (a1*a1 + a2); double res = ( (mpd - (ss / a1)) / sqrt(e1*ss + e2*ss*(ss - 1.0)) ); return res; } map<unsigned int, unsigned int> Statistics::statAllelesData(vector<string> &alleles){ map<unsigned int, unsigned int> ids; // Verificacion de seguridad if( alleles.size() < 1 ){ return ids; } // Asumo que el largo es igual, par y fijo for( string allelle : alleles ){ // cout << "Statistics::statAllelesData - allelle: \"" << allelle << "\"\n"; unsigned int len = allelle.length(); if( (len & 0x1) != 0 ){ cerr << "Statistics::statAllelesData - Error,length is NOT even (" << len << ")\n"; continue; } len /= 2; string str1 = allelle.substr(0, len); string str2 = allelle.substr(len, len); unsigned int id1 = std::stoi( str1 ); unsigned int id2 = std::stoi( str2 ); if( id1 != 0 ){ ids[id1]++; } if( id2 != 0 ){ ids[id2]++; } } // for( auto par : ids ){ // cout << "Statistics::statAllelesData - allele[" << par.first << "]: " << par.second<< "\n"; // } return ids; } double Statistics::statHeterozygosity(map<unsigned int, unsigned int> &allele_data){ double sum = 0.0; unsigned int total = 0; for( auto it : allele_data ){ total += it.second; } for( auto it : allele_data ){ sum += pow(((double)it.second)/total, 2.0); } return (1.0 - sum); } double Statistics::statEffectiveNumAlleles(double h){ return (1.0/(1.0-h)); }
#include "aeMath.h" namespace aeEngineSDK { /*************************************************************************************************/ /* Constructors /*************************************************************************************************/ aeVector3::aeVector3() { } aeVector3::~aeVector3() { } aeVector3::aeVector3(const aeVector3 & V) { *this = V; } aeVector3::aeVector3(float X, float Y, float Z) : x(X), y(Y), z(Z) { } /*************************************************************************************************/ /* Functions implementation /*************************************************************************************************/ float aeVector3::AngleBetweenVectors(const aeVector3 & V) const { if (*this == V) return 0; return aeMath::ArcCos((*this|V) / (~(*this) * ~(V))); } void aeVector3::OrthoNormalize(aeVector3 & V) { aeVector3 normal = *this; *this = Normalized(); aeVector3 proj = *this * (V | *this); V -= proj; V = V.Normalized(); } }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int maxn = 1e6 + 100; char st[maxn]; int loc[maxn]; int main() { int t; scanf("%d",&t); for (int ca = 1;ca <= t;ca++) { scanf("%s",st); int cou = 0,n = strlen(st); for (int i = 0;i < n; i++) { if (st[i] == 'c') { loc[cou] = i; if (cou > 0 && loc[cou] - loc[cou-1] < 3) {cou = - 1;break;} cou++; } if (st[i] != 'c' && st[i] != 'f') { cou = -1; break; } } if (cou == 0) cou = (n+1)/2; else if (cou == 1) {cou = (n <= 2)?-1:cou;} else if (cou > 1) {if (n-loc[cou-1] + loc[0] <= 2) cou = -1;} printf("Case #%d: %d\n",ca,cou); } return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #include "GridContainer.h" #include "Unit.h" // Sets default values AGridContainer::AGridContainer() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; units = TMap<int, AUnit*>(); building = nullptr; building_state = ContainerBuilding_enum::empty; pos_index = 0; } void AGridContainer::Init_GridCcontainer(int _pos_index) { pos_index = _pos_index; } TEnumAsByte<PlayerGroup_enum> AGridContainer::Get_player_group() { return player_group; } TEnumAsByte<ContainerBuilding_enum> AGridContainer::Get_building_state() { return building_state; } int AGridContainer::Get_pos_index() { return pos_index; } bool AGridContainer::Add_to_container(AUnit* _building) { building = _building; building_state = _building->building_state; return true; } bool AGridContainer::Erase_building() { building_state = ContainerBuilding_enum::empty; building = nullptr; return false; } bool AGridContainer::IsBuildable(TEnumAsByte<PlayerGroup_enum> _player_group) { return (player_group == _player_group) && building_state == ContainerBuilding_enum::empty; } // Called when the game starts or when spawned void AGridContainer::BeginPlay() { Super::BeginPlay(); } // Called every frame void AGridContainer::Tick(float DeltaTime) { Super::Tick(DeltaTime); }
/* Copyright (c) 2016-7 Seth Pendergrass. See LICENSE. */ #pragma once #include <magma_v2.h> #include <vector> namespace ssvd { class Ssvd { public: virtual ~Ssvd(){}; virtual int Run(const float *x, int x_n, bool stream, float *sigma, float *v, double *elapsed = nullptr) = 0; }; class SsvdCpu : public Ssvd { public: SsvdCpu(int m, int n, int k); virtual ~SsvdCpu(){}; virtual int Run(const float *x, int n, bool stream, float *sigma, float *v, double *elapsed = nullptr) override; const float *GetXX() const { return xx.data(); } protected: int m, n, k; std::vector<float> xx, xx_temp, sigma; std::vector<int> isuppz; }; class SsvdMagma : public Ssvd { public: SsvdMagma(int m, int n, int k, int n_full = 0); virtual ~SsvdMagma(); //HACK sigma must be n length, not k virtual int Run(const float *x, int n, bool stream, float *sigma, float *v, double *elapsed = nullptr) override; magma_queue_t GetQueue() const { return queue; } magmaFloat_ptr GetDX() const { return dX; } magmaFloat_ptr GetDXX() const { return dXX; } protected: int m, n, k, n_full; magma_queue_t queue; magmaFloat_ptr dX, dXX, dXX_dV; std::vector<float> wA, work; std::vector<int> iwork; }; }
#ifndef TRANSFORM_H #define TRANSFORM_H #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/vec4.hpp> #include "object.h" class transform: public object { public: glm::vec3 position; glm::vec3 size; glm::quat rotation; transform(); json serialize(); void deserialize(json& serialized); glm::mat4 get_model_matrix(); glm::vec3 get_forward(); glm::vec3 get_up(); }; #endif //!TRANSFORM_H
// -*- C++ -*- /*! * @file PSGamepad.cpp * @brief Playstation Gamepad class * $Date$ * * $Id$ */ #include "PSGamepad.h" #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } LPDIRECTINPUT8 g_pDI = NULL; LPDIRECTINPUTDEVICE8 g_pJoystick = NULL; PSGamepad::PSGamepad() { } PSGamepad::~PSGamepad() { } //----------------------------------------------------------------------------- // Name: InitDirectInput() // Desc: Initialize the DirectInput variables. //----------------------------------------------------------------------------- HRESULT PSGamepad::InitDirectInput(int max, int min, int threshold) { HRESULT hr; // Register with the DirectInput subsystem and get a pointer // to a IDirectInput interface we can use. // Create a DInput object if FAILED( hr = DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&g_pDI, NULL ) ) { cout << "Create a DInput object failed. return value: " << hr << endl; return hr; } DIJOYCONFIG PreferredJoyCfg = {0}; DI_ENUM_CONTEXT enumContext; enumContext.pPreferredJoyCfg = &PreferredJoyCfg; enumContext.bPreferredJoyCfgValid = false; IDirectInputJoyConfig8* pJoyConfig = NULL; if( FAILED( hr = g_pDI->QueryInterface( IID_IDirectInputJoyConfig8, (void **) &pJoyConfig ) ) ) { cout << "Error QueryInterface." << endl; return hr; } PreferredJoyCfg.dwSize = sizeof(PreferredJoyCfg); if( SUCCEEDED( pJoyConfig->GetConfig(0, &PreferredJoyCfg, DIJC_GUIDINSTANCE ) ) ) // This function is expected to fail if no joystick is attached enumContext.bPreferredJoyCfgValid = true; SAFE_RELEASE( pJoyConfig ); // Look for a simple joystick we can use for this sample program. if( FAILED( hr = g_pDI->EnumDevices( DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback, &enumContext, DIEDFL_ATTACHEDONLY ) ) ) { cout << "Look for a simple joystick failed." << endl; return hr; } // Set the data format to "simple joystick" - a predefined data format // // A data format specifies which controls on a device we are interested in, // and how they should be reported. This tells DInput that we will be // passing a DIJOYSTATE2 structure to IDirectInputDevice::GetDeviceState(). if( FAILED( hr = g_pJoystick->SetDataFormat( &c_dfDIJoystick2 ) ) ) { cout << "SetDataFormat failed." << endl; return hr; } HRESULT res; DIPROPDWORD pw; DIPROPRANGE pr; pw.diph.dwSize = sizeof(DIPROPDWORD); /* $B%8%g%$%9%F%#%C%/@_Dj(B */ pr.diph.dwSize = sizeof(DIPROPRANGE); pw.diph.dwHeaderSize = pr.diph.dwHeaderSize = sizeof(DIPROPHEADER); pw.diph.dwHow = pr.diph.dwHow = DIPH_BYOFFSET; pw.dwData = threshold; /* $BF~NO$7$-$$CM(B (0-10000: $BF~NOCMHO0O$N(B10%$B$KAjEv(B) */ pr.lMin = min; /* $BF~NOCMHO0O(B */ pr.lMax = max; /* $B#X<4$N@_Dj(B */ pw.diph.dwObj = pr.diph.dwObj = DIJOFS_X; res = g_pJoystick->SetProperty(DIPROP_RANGE, &pr.diph); res |= g_pJoystick->SetProperty(DIPROP_DEADZONE, &pw.diph); /* $B#Y<4$N@_Dj(B */ pw.diph.dwObj = pr.diph.dwObj = DIJOFS_Y; res |= g_pJoystick->SetProperty(DIPROP_RANGE, &pr.diph); res |= g_pJoystick->SetProperty(DIPROP_DEADZONE, &pw.diph); if (res != DI_OK) { cout << "Error: SetProperty." << endl; g_pJoystick->Release(); g_pJoystick = NULL; return DIENUM_CONTINUE; } return S_OK; } //----------------------------------------------------------------------------- // Name: UpdateInputState(RTC::TimedFloatSeq& data) // Desc: Get the input device's state and display it. //----------------------------------------------------------------------------- HRESULT PSGamepad::UpdateInputState(std::vector<float>& data, const std::vector<float>& rate) { HRESULT hr; TCHAR strText[512] = {0}; // Device state text DIJOYSTATE2 js; // DInput joystick state if( NULL == g_pJoystick ) return S_OK; // Poll the device to read the current state hr = g_pJoystick->Poll(); if( FAILED(hr) ) { // DInput is telling us that the input stream has been // interrupted. We aren't tracking any state between polls, so // we don't have any special reset that needs to be done. We // just re-acquire and try again. hr = g_pJoystick->Acquire(); while( hr == DIERR_INPUTLOST ) hr = g_pJoystick->Acquire(); // hr may be DIERR_OTHERAPPHASPRIO or other errors. This // may occur when the app is minimized or in the process of // switching, so just try again later return S_OK; } // Get the input's device state if( FAILED( hr = g_pJoystick->GetDeviceState( sizeof(DIJOYSTATE2), &js ) ) ) { cout << "Error: GetDeviceState" << endl; return hr; // The device should have been acquired during the Poll() } // Points of view for (int i = 0; i < 4; i++ ) cout << "js.rgdwPOV[" << i << "]: " << js.rgdwPOV[i] << endl; // Fill up text with which buttons are pressed for( int i = 0; i < 128; i++ ) { if ( js.rgbButtons[i] & 0x80 ) { cout << "js.rgbButtons[" << i << "]: " << i << endl; } } data[0] = js.lX * rate[0]; data[1] = js.lY * rate[1]; data[2] = js.lZ * rate[2]; for( int i = 3; i < 15; i++ ) { if ( js.rgbButtons[i-3] & 0x80 ) { data[i] = 1.0; } else { data[i] = 0.0; } } return S_OK; } //----------------------------------------------------------------------------- // Name: FreeDirectInput() // Desc: Initialize the DirectInput variables. //----------------------------------------------------------------------------- VOID PSGamepad::FreeDirectInput() { // Unacquire the device one last time just in case // the app tried to exit while the device is still acquired. if( g_pJoystick ) g_pJoystick->Unacquire(); // Release any DirectInput objects. SAFE_RELEASE( g_pJoystick ); SAFE_RELEASE( g_pDI ); } extern "C" { //----------------------------------------------------------------------------- // Name: EnumJoysticksCallback() // Desc: Called once for each enumerated joystick. If we find one, create a // device interface on it so we can play with it. //----------------------------------------------------------------------------- BOOL CALLBACK EnumJoysticksCallback( const DIDEVICEINSTANCE* pdidInstance, VOID* pContext ) { HRESULT hr; // Obtain an interface to the enumerated joystick. hr = g_pDI->CreateDevice( pdidInstance->guidInstance, &g_pJoystick, NULL ); // If it failed, then we can't use this joystick. (Maybe the user unplugged // it while we were in the middle of enumerating it.) if( FAILED(hr) ) return DIENUM_CONTINUE; // Stop enumeration. Note: we're just taking the first joystick we get. You // could store all the enumerated joysticks and let the user pick. return DIENUM_STOP; } };
// Talk2MeDlg.h // #pragma once #include"SetServerIpPort.h" #include"Signup.h" #include"Login.h" #include"ChatRoom.h" #include "afxcmn.h" #include"Friends.h" #include"ChatroomIn.h" #include"FileRecv.h" #include"Progress.h" #define DEBUG #undef DEBUG // CTalk2MeDlg 对话框 class CTalk2MeDlg : public CDialogEx { public: CTalk2MeDlg(CWnd* pParent = NULL); // 标准构造函数 map<int, CConversation*> m_id2Conversation;//存储121对话 map<int, CChatRoom*> m_id2Chatroom;//存储聊天室 vector<USER_LOGIN> m_onlineFriends;//注册用户 map <CString, CString> m_File2FileName; //原始名字对现在的名字 map<CString, CProgress*> m_File2ProgressBar;//文件名对进度条 map<CString, CFileRecv*> m_file2SaveDlg;//文件名对保存对话框 CSetServerIpPort m_serverSet;//设置服务器对话框 CSignup m_signup;//注册对话框 CLogin m_login;//登陆对话框 CFriends m_friendTab;//注册好友tab CChatroomIn m_chatRoomTab;//聊天室tab // 对话框数据 enum { IDD = IDD_TALK2ME_DIALOG }; SOCKET m_ClientSocket; int m_fileConversationId;//121文件传输,用于文件线程的发送,作为参数传到 int m_fileChatRoomId;//聊天室文件传输 WSADATA wsaData; int iLen; // 客户地址长度 int iSend; // 发送数据的长度 int iRecv; // 接收数据的长度 struct sockaddr_in m_myAddr,m_serverAddr; // 本地地址和客户地址 MSG0 m_sendMsg , m_recvMsg; int m_wantToTalkId; int m_myOwnId;//当前用户的id char m_username[DB_LENGTH]; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: HICON m_hIcon; // 生成的消息映射函数 virtual BOOL OnInitDialog(); virtual void OnClose(); virtual BOOL PreTranslateMessage(MSG* pMsg); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: BOOL m_IsConnected; void GetMembersFromTheChatRoom(int cid);//获得当前用户参与的聊天室的所有成员情况 afx_msg void OnBnClickedStarttalkButton(); afx_msg void OnBnClickedLoginbtn(); afx_msg void OnBnClickedSetbtn(); afx_msg LRESULT OnRecvFileSave(WPARAM wParam, LPARAM lParam);//接收文件提示框 afx_msg LRESULT OnSendFile(WPARAM wParam, LPARAM lParam);//发送121文件 afx_msg LRESULT OnSendMsg(WPARAM wParam, LPARAM lParam);//发送121消息 afx_msg LRESULT OnRecvChatMsg(WPARAM wParam, LPARAM lParam);//接收聊天室消息 afx_msg LRESULT OnRecvMsg(WPARAM wParam, LPARAM lParam);//接收121消息 afx_msg LRESULT OnCloseMsg(WPARAM wParam, LPARAM lParam);//关闭对话框 afx_msg LRESULT OnSignUp(WPARAM wParam, LPARAM lParam);//注册 afx_msg LRESULT OnAddOne(WPARAM wParam, LPARAM lParam);//增加聊天室成员 afx_msg LRESULT OnDelOne(WPARAM wParam, LPARAM lParam);//删除聊天室成员 afx_msg LRESULT OnSendChatMsg(WPARAM wParam, LPARAM lParam);//发送聊天室消息 afx_msg LRESULT OnSendChatFile(WPARAM wParam, LPARAM lParam);//发送群发文件 afx_msg LRESULT OnRecvFile(WPARAM wParam, LPARAM lParam);//接收文件 afx_msg LRESULT OnCancelFile(WPARAM wParam, LPARAM lParam);//取消文件 afx_msg void OnBnClickedSignupbtn(); afx_msg void OnBnClickedChatroomBtn(); afx_msg void OnBnClickedLogoutbtn(); void OnBnClickedGetroombtn();//获得用户参与的所有的聊天室 void OnBnClickedRefreshButton();//获得好友列表 CTabCtrl m_tabCtrl; afx_msg void OnTcnSelchangeTab1(NMHDR *pNMHDR, LRESULT *pResult); };
/* * File: main.cpp * Author: Elijah De Vera * Created on January 26, 2021, 12:36 AM * Purpose: Menu for all assignments in assignment 5 */ //System Libraries #include <iostream> //I/O Library #include <iomanip> #include <math.h> using namespace std; //Function Prototypes void minmax(int, int, int, int&, int& );//Function to find the min and max int fctrl(int);//Function to write for this problem bool isPrime(int);//Determine if the input number is prime. int collatz(int);//3n+1 sequence int collatz1(int);//3n+1 sequence void getTime( int&, char, int&, bool& ); // input for time void convert( int&, int&, char&); // converting time void output( int&, int&, int&, char); // outputting time float psntVal( float, float, int ); // receiving present value for the price void getScre(int &,int &,int &,int &,int &); // receiving score float calcAvg(int,int,int,int,int); //calculating averages of score int fndLwst(int,int,int,int,int); // finding the lowest score int main(int argc, char** argv) { string choice; cout<<"Type 1 for min max program"<<endl; cout<<"Type 2 for factorial program"<<endl; cout<<"Type 3 for prime program"<<endl; cout<<"Type 4 for collatz sequence"<<endl; cout<<"Type 5 for collatz sequence with output"<<endl; cout<<"Type 6 for the 12 hour notation program"<<endl; cout<<"Type 7 for the time converter program"<<end; cout<<"Type 8 for the present value calculator program"<<endl; cout<<"Type 9 for the average program"<<end; cin>>choice; if ( choice == "1" ) { //Declare Variables int inp1, inp2, inp3, min, max; //Initialize Variables cout<<"Input 3 numbers"<<endl; cin>>inp1; cin>>inp2; cin>>inp3; min = max = inp1; //Output data minmax( inp1, inp2, inp3, min, max); } if ( choice == "2" ) { //Program TItle cout<<"This program calculates the factorial using a function prototype " "found in the template for this problem."<<endl; //Declare Variables int inp; //Initialize Variables cout<<"Input the number for the function."<<endl; cin>>inp; //Output data cout<<inp<<"! = "<<fctrl(inp); } if ( choice == "3" ) { //Declare Variables int inp; //Initialize Variables cout<<"Input a number to test if Prime."<<endl; cin>>inp; //Output data cout<<inp; if ( isPrime(inp) == true ) { cout<<" is prime."; } else { cout<<" is not prime."; } } if ( choice == "4" ) { //Declare Variables int n; //Initialize Variables cout<<"Collatz Conjecture Test"<<endl; cout<<"Input a sequence start"<<endl; cin>>n; //Process/Map inputs to outputs cout<<"Sequence start of "<<n<<" cycles to 1 in "<< collatz(n)<<" steps"; } if ( choice == "5" ) { //Declare Variables int n,ns; //Initialize Variables cout<<"Collatz Conjecture Test"<<endl; cout<<"Input a sequence start"<<endl; cin>>n; //Process/Map inputs to outputs ns=collatz1(n); //Output data cout<<"Sequence start of "<<n<<" cycles to 1 in "<< ns<<" steps"; } if ( choice == "6" ) { //Declare Variables int hour, min, wTime, fHour, fMin, mHolder, hHolder; string iampm, fampm, inp; //Initialize or input i.e. set variable value //Map inputs -> outputs do { cout<<"Enter hour:"<<endl<<endl; cin>>hour; fHour=hour; cout<<"Enter minutes:"<<endl<<endl; cin>>min; fMin=min; cout<<"Enter A for AM, P for PM:"<<endl<<endl; cin>>iampm; cout<<"Enter waiting time:"<<endl<<endl; cin>>wTime; if ( iampm == "A" ) { iampm = "AM"; } else if ( iampm == "P" ) { iampm = "PM"; } // adding minutes to the time if ( wTime+min > 60 ) { hHolder=(wTime/60); fHour+=hHolder; mHolder=wTime-(hHolder*60); if ( fMin+mHolder > 60 ) { fHour++; fMin+=mHolder-60; } else { fMin+=mHolder; } } // adjusting to 12 hour notation if ( fHour > 12 ) { fHour-=12; if ( iampm == "AM" ) { fampm = "PM"; } else if ( iampm == "PM" ) { fampm = "AM"; } } else { if ( iampm == "AM" ) { fampm = "AM"; } else { fampm = "PM"; } } cout<<setfill('0')<<setw(2)<<fixed; cout<<"Current time = " <<setfill('0')<<setw(2)<<hour<<":"<<setfill('0')<<setw(2)<<min<<" "<<iampm<<endl; cout<<"Time after waiting period = "<<setfill('0')<<setw(2)<<fHour<<":"<<setfill('0')<<setw(2)<<fMin<< " "<<fampm<<endl<<endl; cout<<"Again:"<<endl; cin>>inp; if ( inp == "y" ) { cout<<endl; } }while ( inp == "y" ); } if ( choice == "7" ) { //Declare Variables int mTime, sTime, min; char c=':', inp, day; bool valid; //Project title cout<<"Military Time Converter to Standard Time"<<endl; cout<<"Input Military Time hh:mm"<<endl; //Process/Map inputs to outputs do { getTime(mTime,c,min,valid); if ( valid == true ) { convert(mTime,sTime,day); output(mTime,min,sTime,day); } cout<<"Would you like to convert another time (y/n)"<<endl; cin>>inp; }while ( inp == 'y' || inp == 'Y' ); } if ( choice == "8" ) { //Declare Variables float ftrVal, intRate; int years; //Project title cout<<"This is a Present Value Computation"<<endl; //Initialize Variables cout<<"Input the Future Value in Dollars"<<endl; cin>>ftrVal; cout<<"Input the Number of Years"<<endl; cin>>years; cout<<"Input the Interest Rate %/yr"<<endl; cin>>intRate; //Output data cout<<setprecision(2)<<fixed<<"The Present Value = $" <<psntVal(ftrVal,intRate,years); } if ( choice == "9" ) { //Declare Variables int s1, s2, s3, s4, s5; //Project title cout<<setprecision(1)<<fixed; cout<<"Find the Average of Test Scores"<<endl; cout<<"by removing the lowest value."<<endl; //Initialize Variables getScre(s1,s2,s3,s4,s5); cout<<"The average test score = "<<calcAvg(s1,s2,s3,s4,s5); } return 0; } void minmax( int inp1, int inp2, int inp3, int& min, int& max) { if ( inp1 > inp2 && inp1 > inp3 ) { max = inp1; if ( inp2 > inp3 ) { min = inp3; } else { min = inp2; } } if ( inp2 > inp1 && inp2 > inp3 ) { max = inp2; if ( inp1 > inp3 ) { min = inp3; } else { min = inp1; } } if ( inp3 > inp1 && inp3 > inp2 ) { max = inp3; if ( inp1 > inp2 ) { min = inp2; } else { min = inp1; } } cout<<"Min = "<<min<<endl; cout<<"Max = "<<max; } int fctrl( int inp ) { int sltn = 1; for ( int i = 1; i <= inp; i++ ) { sltn*=i; } return sltn; } bool isPrime( int inp ) { int counter = 0; for ( int i = 2; i < inp; i++ ) { if ( inp % i == 0 ) { counter++; } } if ( counter > 0 ) { return false; } else { return true; } } int collatz( int n ) { int steps = 1; while ( n != 1 ) { if ( n % 2 == 0 ) { n /= 2; steps++; } else { n = ( n * 3 + 1 ); steps++; } } return steps; } int collatz1( int n ) { int steps = 1; while ( n != 1 ) { if ( n % 2 == 0 ) { cout<<n<<", "; n /= 2; steps++; } else { cout<<n<<", "; n = ( n * 3 + 1 ); steps++; } } cout<<n<<endl; return steps; } float psntVal( float ftrVal, float intRate, int years ) { float pValue; pValue = ftrVal/(pow(1+(intRate/100),years)); return pValue; } //get score Function void getScre(int & s1,int &s2,int &s3,int &s4,int &s5) { cout<<"Input the 5 test scores."<<endl; cin>>s1; cin>>s2; cin>>s3; cin>>s4; cin>>s5; if ( s2 > 100 || s2 < 0 ){ cout<<"INVALID"; } if ( s1 > 100 || s1 < 0 ){ cout<<"INVALID"; } if ( s3 > 100 || s3 < 0 ){ cout<<"INVALID"; } if ( s4 > 100 || s4 < 0 ){ cout<<"INVALID"; } if ( s5 > 100 || s5 < 0 ){ cout<<"INVALID"; } } //average function float calcAvg(int test1, int test2, int test3, int test4, int test5) { int average=0; average = ((test1+test2+test3+test4+test5)-fndLwst(test1, test2, test3, test4, test5))/4.0; return average; } //finding lowest number function int fndLwst(int score1, int score2, int score3, int score4, int score5) { if(score1 < score2 && score1 < score3 && score1 < score4 && score1 < score5) return score1; else if(score2 < score1 && score2 < score3 && score2 < score4 && score2 < score5) return score2; else if(score3 < score1 && score3 < score2 && score3 < score4 && score3 < score5) return score3; else if(score4 < score1 && score4 < score2 && score4 < score3 && score4 < score5) return score4; else if(score5 < score1 && score5 < score2 && score5 < score3 && score5 < score4) return score5; }
#ifndef M2_SERVER_DATABASE_H #define M2_SERVER_DATABASE_H #include "Data.hpp" namespace m2 { namespace server { class Database { public: Database(const std::string& rootDir); public: bool CreateUser(uuids::uuid Uid, const std::string& PublicKey); bool CreateUser(uuids::uuid Uid, std::string&& PublicKey); bool IsClienExists(uuids::uuid Uid); public: std::string getUserPublicKey(uuids::uuid Uid); std::string getPublicServerKey(); std::string getPrivateServerKey(); //WTF??? protected: data::AUsers Users; data::ADialogs Dialogs; }; }} #endif //M2_SERVER_DATABASE_H
#pragma once #ifndef HEXADECIMAL_HPP #define HEXADECIMAL_HPP #include <sstream> #include <iomanip> namespace griha { namespace tools { template<typename InputIterator, typename CharT = char> auto as_hex( InputIterator first, InputIterator last, std::basic_string<CharT> delim = "" ) -> std::basic_string<CharT> { using namespace std; basic_ostringstream<CharT> os; os << hex << setfill( os.widen( '0' ) ) << uppercase; for ( ; first != last; ++first ) os << setw( 2 ) << static_cast<int>( *first ) << delim; return os.str(); } template<typename InputIterator, typename CharT = char> auto as_hex_n( InputIterator first, typename std::iterator_traits<InputIterator>::difference_type n, std::basic_string<CharT> delim = "" ) -> std::basic_string<CharT> { InputIterator last = first; std::advance( last, n ); return as_hex(first, last, delim); } }} // namespace griha::tools #endif //HEXADECIMAL_HPP
#include <Application.hpp> #include <Util.hpp> int WINAPI wWinMain(HINSTANCE instance, HINSTANCE prevInstance, WCHAR* cmdLine, int cmdShow) { CoInitialize(NULL); try { Application app(instance); app.run(); } catch (Exception& ex) { MessageBox(NULL, ex.message().c_str(), L"Error", MB_OK | MB_ICONERROR); return 1; } return 0; }
/* Assuming the ocean's level is currently rising at about 1.5 millimeters per year, write a program that displays the number of mm higher than the current level that the ocean's level will be in 5, 7, and 10 years. Author: Aaron Maynard */ #include <iostream> using namespace std; int main() { //Declare variables double currentLevel = 0.00; // The current level risen will start at zero double risingLevel = 1.5; // 15 millimiters per year // Display levels on screen cout << "In 5 years, the ocean's level will be " << risingLevel * 5 << " mm higher " << "than the current level \n"; cout << "In 7 years, the ocean's level will be " << risingLevel * 7 << " mm higher " << "than the current level \n"; cout << "In 10 years, the ocean's level will be " << risingLevel * 10 << " mm higher " << "than the current level \n\n"; system("pause"); return 0; }
#include "gtest/gtest.h" #include "../../../../options/Option.hpp" #include "../../../../options/OptionPut.hpp" #include "../../../../binomial_method/case/Case.hpp" #include "../../../../binomial_method/case/Wilmott2Case.hpp" #include "../../../../binomial_method/method/regular/euro/EuroBinomialMethod.hpp" double regular_euro_put_Wilmott2(int iT, int M) { double r = 0.06; double s0 = 5; double E = 10; double T[] = {0.25, 0.5, 0.75, 1.0}; double sigma = 0.3; OptionPut<double> aOption(T[iT], s0, r, sigma, E); Wilmott2Case<double> aCase(&aOption, M); EuroBinomialMethod<double> method(&aCase); method.solve(); double result = method.getResult(); return result; } TEST(RegularEuroPutWillmot2, test16_025) { double result = regular_euro_put_Wilmott2(0, 16); EXPECT_NEAR(result, 4.8511, 0.0001); } TEST(RegularEuroPutWillmot2, test32_025) { double result = regular_euro_put_Wilmott2(0, 32); EXPECT_NEAR(result, 4.8511, 0.0001); } TEST(RegularEuroPutWillmot2, test64_025) { double result = regular_euro_put_Wilmott2(0, 64); EXPECT_NEAR(result, 4.8511, 0.0001); } TEST(RegularEuroPutWillmot2, test128_025) { double result = regular_euro_put_Wilmott2(0, 128); EXPECT_NEAR(result, 4.8511, 0.0001); } TEST(RegularEuroPutWillmot2, test256_025) { double result = regular_euro_put_Wilmott2(0, 256); EXPECT_NEAR(result, 4.8511, 0.0001); } TEST(RegularEuroPutWillmot2, test16_050) { double result = regular_euro_put_Wilmott2(1, 16); EXPECT_NEAR(result, 4.7046, 0.0001); } TEST(RegularEuroPutWillmot2, test32_050) { double result = regular_euro_put_Wilmott2(1, 32); EXPECT_NEAR(result, 4.7047, 0.0001); } TEST(RegularEuroPutWillmot2, test64_050) { double result = regular_euro_put_Wilmott2(1, 64); EXPECT_NEAR(result, 4.7047, 0.0001); } TEST(RegularEuroPutWillmot2, test128_050) { double result = regular_euro_put_Wilmott2(1, 128); EXPECT_NEAR(result, 4.7048, 0.0001); } TEST(RegularEuroPutWillmot2, test256_050) { double result = regular_euro_put_Wilmott2(1, 256); EXPECT_NEAR(result, 4.7048, 0.0001); } TEST(RegularEuroPutWillmot2, test16_075) { double result = regular_euro_put_Wilmott2(2, 16); EXPECT_NEAR(result, 4.5625, 0.0001); } TEST(RegularEuroPutWillmot2, test32_075) { double result = regular_euro_put_Wilmott2(2, 32); EXPECT_NEAR(result, 4.5632, 0.0001); } TEST(RegularEuroPutWillmot2, test64_075) { double result = regular_euro_put_Wilmott2(2, 64); EXPECT_NEAR(result, 4.5634, 0.0001); } TEST(RegularEuroPutWillmot2, test128_075) { double result = regular_euro_put_Wilmott2(2, 128); EXPECT_NEAR(result, 4.5635, 0.0001); } TEST(RegularEuroPutWillmot2, test256_075) { double result = regular_euro_put_Wilmott2(2, 256); EXPECT_NEAR(result, 4.5635, 0.0001); } TEST(RegularEuroPutWillmot2, test16_010) { double result = regular_euro_put_Wilmott2(3, 16); EXPECT_NEAR(result, 4.4293, 0.0001); } TEST(RegularEuroPutWillmot2, test32_010) { double result = regular_euro_put_Wilmott2(3, 32); EXPECT_NEAR(result, 4.4298, 0.0001); } TEST(RegularEuroPutWillmot2, test64_010) { double result = regular_euro_put_Wilmott2(3, 64); EXPECT_NEAR(result, 4.4296, 0.0001); } TEST(RegularEuroPutWillmot2, test128_010) { double result = regular_euro_put_Wilmott2(3, 128); EXPECT_NEAR(result, 4.4302, 0.0001); } TEST(RegularEuroPutWillmot2, test256_010) { double result = regular_euro_put_Wilmott2(3, 256); EXPECT_NEAR(result, 4.4303, 0.0001); } TEST(RegularEuroPutWillmot2, test150_010) { double result = regular_euro_put_Wilmott2(3, 150); EXPECT_NEAR(result, 4.4301, 0.00015); }
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 10000 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 typedef long long LL; bool slove[MAXN+10][5]; vector <int> ans[5]; int main(int argc, char const *argv[]) { int kase; scanf("%d",&kase); int num,tmp; for(int K = 1 ; K <= kase ; K++ ){ memset(slove,0,sizeof(slove)); for(int i = 1 ; i <= 3 ; i++ ){ ans[i].clear(); scanf("%d",&num); for(int j = 0 ; j < num ; j++ ){ scanf("%d",&tmp); slove[tmp][i] = true; } } for(int i = 0 ; i < MAXN+5 ; i++ ){ if( slove[i][1] && !slove[i][2] && !slove[i][3] ) ans[1].push_back(i); if( !slove[i][1] && slove[i][2] && !slove[i][3] ) ans[2].push_back(i); if( !slove[i][1] && !slove[i][2] && slove[i][3] ) ans[3].push_back(i); } int S = max(ans[1].size(),max(ans[2].size(),ans[3].size())); printf("Case #%d:\n",K); for(int i = 1 ; i <= 3 ; i++ ){ if( ans[i].size() == S ){ printf("%d %d",i,S); for(int j = 0 ; j < S ; j++ ) printf(" %d",ans[i][j]); printf("\n"); } } } return 0; }
#include "stdafx.h" #include "View.h" #include "Interface.h" namespace RLGM { View::View() { } View::View(HWND HWnd, RLGM::Interface* Owner, double heightAboveSea, double longitude, double latitude) { hWnd = HWnd; owner = Owner; RECT rc; GetClientRect(hWnd, &rc); width = rc.right - rc.left; height = rc.bottom - rc.top; aspectRatio = height / (double)width; geoPosition.Longitude = longitude; geoPosition.Latitude = latitude; geoPosition.HUnderSee = heightAboveSea; geoPosition.Azimuth = 0; InitializeGraphics(); } //Инициализация Графики void View::InitializeGraphics() { HRESULT hr = S_OK; // Obtain DXGI factory from device (since we used nullptr for pAdapter above) IDXGIFactory* dxgiFactory = nullptr; { IDXGIDevice* dxgiDevice = nullptr; hr = owner->g_pd3dDevice->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice)); if (SUCCEEDED(hr)) { IDXGIAdapter* adapter = nullptr; hr = dxgiDevice->GetAdapter(&adapter); if (SUCCEEDED(hr)) { hr = adapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgiFactory)); adapter->Release(); } dxgiDevice->Release(); } } if (FAILED(hr)) return;// hr; // Create swap chain IDXGIFactory2* dxgiFactory2 = nullptr; hr = dxgiFactory->QueryInterface(__uuidof(IDXGIFactory2), reinterpret_cast<void**>(&dxgiFactory2)); if (dxgiFactory2) { DXGI_SWAP_CHAIN_DESC1 sd; ZeroMemory(&sd, sizeof(sd)); sd.Width = width; sd.Height = height; sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; hr = dxgiFactory2->CreateSwapChainForHwnd(owner->g_pd3dDevice, hWnd, &sd, nullptr, nullptr, &g_pSwapChain1); if (SUCCEEDED(hr)) { hr = g_pSwapChain1->QueryInterface(__uuidof(IDXGISwapChain), reinterpret_cast<void**>(&g_pSwapChain)); } dxgiFactory2->Release(); } else { // DirectX 11.0 systems DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = width; sd.BufferDesc.Height = height; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; hr = dxgiFactory->CreateSwapChain(owner->g_pd3dDevice, &sd, &g_pSwapChain); } // Note this tutorial doesn't handle full-screen swapchains so we block the ALT+ENTER shortcut dxgiFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER); dxgiFactory->Release(); if (FAILED(hr)) return;// hr; // Create a render target view hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&g_pBackBuffer)); if (FAILED(hr)) return;// hr; hr = owner->g_pd3dDevice->CreateRenderTargetView(g_pBackBuffer, nullptr, &g_pRenderTargetView); g_pBackBuffer->Release(); if (FAILED(hr)) return;// hr; //Create textures for radar ID3D11Texture2D* pTexture; ID3D11RenderTargetView* pRenderTargetView; ID3D11ShaderResourceView* pShaderResourceView; D3D11_TEXTURE2D_DESC textureDesc; D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc; D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc; // ---> Create texture for final 8bit layer ZeroMemory(&textureDesc, sizeof(textureDesc)); textureDesc.Width = extensionCoef * width; textureDesc.Height = extensionCoef * height; textureDesc.MipLevels = 1; 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_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; hr = owner->g_pd3dDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture); if (FAILED(hr)) return;// hr; ZeroMemory(&renderTargetViewDesc, sizeof(renderTargetViewDesc)); renderTargetViewDesc.Format = textureDesc.Format; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; renderTargetViewDesc.Texture2D.MipSlice = 0; hr = owner->g_pd3dDevice->CreateRenderTargetView(pTexture, &renderTargetViewDesc, &pRenderTargetView); if (FAILED(hr)) return;// hr; ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc)); shaderResourceViewDesc.Format = textureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = 1; hr = owner->g_pd3dDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pShaderResourceView); if (FAILED(hr)) return;// hr; textureFinal8bit = RLGM::Texture{ pTexture, pRenderTargetView, pShaderResourceView }; // <--- Create texture for final 8bit layer // ---> Create texture for final 2bit layer ZeroMemory(&textureDesc, sizeof(textureDesc)); textureDesc.Width = extensionCoef * width; textureDesc.Height = extensionCoef * height; textureDesc.MipLevels = 1; 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_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; hr = owner->g_pd3dDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture); if (FAILED(hr)) return;// hr; ZeroMemory(&renderTargetViewDesc, sizeof(renderTargetViewDesc)); renderTargetViewDesc.Format = textureDesc.Format; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; renderTargetViewDesc.Texture2D.MipSlice = 0; hr = owner->g_pd3dDevice->CreateRenderTargetView(pTexture, &renderTargetViewDesc, &pRenderTargetView); if (FAILED(hr)) return;// hr; ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc)); shaderResourceViewDesc.Format = textureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = 1; hr = owner->g_pd3dDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pShaderResourceView); if (FAILED(hr)) return;// hr; textureFinal2bit = RLGM::Texture{ pTexture, pRenderTargetView, pShaderResourceView }; // <--- Create texture for final 2bit layer // ---> Create texture for final tail layer ZeroMemory(&textureDesc, sizeof(textureDesc)); textureDesc.Width = extensionCoef * width; textureDesc.Height = extensionCoef * height; textureDesc.MipLevels = 1; 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_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; hr = owner->g_pd3dDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture); if (FAILED(hr)) return;// hr; ZeroMemory(&renderTargetViewDesc, sizeof(renderTargetViewDesc)); renderTargetViewDesc.Format = textureDesc.Format; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; renderTargetViewDesc.Texture2D.MipSlice = 0; hr = owner->g_pd3dDevice->CreateRenderTargetView(pTexture, &renderTargetViewDesc, &pRenderTargetView); if (FAILED(hr)) return;// hr; ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc)); shaderResourceViewDesc.Format = textureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = 1; hr = owner->g_pd3dDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pShaderResourceView); if (FAILED(hr)) return;// hr; textureFinalTail = RLGM::Texture{ pTexture, pRenderTargetView, pShaderResourceView }; // <--- Create texture for final tail layer // ---> Create texture for final layer without color correction ZeroMemory(&textureDesc, sizeof(textureDesc)); textureDesc.Width = extensionCoef * width; textureDesc.Height = extensionCoef * height; textureDesc.MipLevels = 1; textureDesc.ArraySize = 1; textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; hr = owner->g_pd3dDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture); if (FAILED(hr)) return;// hr; ZeroMemory(&renderTargetViewDesc, sizeof(renderTargetViewDesc)); renderTargetViewDesc.Format = textureDesc.Format; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; renderTargetViewDesc.Texture2D.MipSlice = 0; hr = owner->g_pd3dDevice->CreateRenderTargetView(pTexture, &renderTargetViewDesc, &pRenderTargetView); if (FAILED(hr)) return;// hr; ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc)); shaderResourceViewDesc.Format = textureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = 1; hr = owner->g_pd3dDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pShaderResourceView); if (FAILED(hr)) return;// hr; textureFinalWithoutColorCorrection = RLGM::Texture{ pTexture, pRenderTargetView, pShaderResourceView }; hr = owner->g_pd3dDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture); if (FAILED(hr)) return;// hr; hr = owner->g_pd3dDevice->CreateRenderTargetView(pTexture, &renderTargetViewDesc, &pRenderTargetView); if (FAILED(hr)) return;// hr; hr = owner->g_pd3dDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pShaderResourceView); if (FAILED(hr)) return;// hr; textureFinalWithoutColorCorrectionHelp1 = RLGM::Texture{ pTexture, pRenderTargetView, pShaderResourceView }; hr = owner->g_pd3dDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture); if (FAILED(hr)) return;// hr; hr = owner->g_pd3dDevice->CreateRenderTargetView(pTexture, &renderTargetViewDesc, &pRenderTargetView); if (FAILED(hr)) return;// hr; hr = owner->g_pd3dDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pShaderResourceView); if (FAILED(hr)) return;// hr; textureFinalWithoutColorCorrectionHelp2 = RLGM::Texture{ pTexture, pRenderTargetView, pShaderResourceView }; //<--- Create texture for final layer without color correction //---> Create 8bit color correction texture for radar ZeroMemory(&textureDesc, sizeof(textureDesc)); textureDesc.Width = 256; //??? textureDesc.Height = 256; textureDesc.MipLevels = 1; 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; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; hr = owner->g_pd3dDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture); if (FAILED(hr)) return;// hr; ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc)); shaderResourceViewDesc.Format = textureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = textureDesc.MipLevels; hr = owner->g_pd3dDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pShaderResourceView); if (FAILED(hr)) return;// hr; colorCorrection8bitTexture = RLGM::Texture{ pTexture, nullptr, pShaderResourceView }; //<--- Create 8bit color correction texture for radar //---> Create 2bit color correction texture for radar ZeroMemory(&textureDesc, sizeof(textureDesc)); textureDesc.Width = 256; //??? textureDesc.Height = 256; textureDesc.MipLevels = 1; 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; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; hr = owner->g_pd3dDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture); if (FAILED(hr)) return;// hr; ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc)); shaderResourceViewDesc.Format = textureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = textureDesc.MipLevels; hr = owner->g_pd3dDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pShaderResourceView); if (FAILED(hr)) return;// hr; colorCorrection2bitTexture = RLGM::Texture{ pTexture, nullptr, pShaderResourceView }; //<--- Create 2bit color correction texture for radar //---> Create tail color correction texture for radar ZeroMemory(&textureDesc, sizeof(textureDesc)); textureDesc.Width = 256; //??? textureDesc.Height = 256; textureDesc.MipLevels = 1; 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; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; hr = owner->g_pd3dDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture); if (FAILED(hr)) return;// hr; ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc)); shaderResourceViewDesc.Format = textureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = textureDesc.MipLevels; hr = owner->g_pd3dDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pShaderResourceView); if (FAILED(hr)) return;// hr; colorCorrectionTailTexture = RLGM::Texture{ pTexture, nullptr, pShaderResourceView }; //<--- Create tail color correction texture for radar //---> Create Map layer for (int i = 0; i < 2; i++) { ZeroMemory(&textureDesc, sizeof(textureDesc)); textureDesc.Width = width; textureDesc.Height = height; textureDesc.MipLevels = 1; textureDesc.ArraySize = 1; textureDesc.Format = DXGI_FORMAT_B8G8R8A8_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_GDI_COMPATIBLE; hr = owner->g_pd3dDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture); if (FAILED(hr)) return;// hr; ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc)); shaderResourceViewDesc.Format = textureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = textureDesc.MipLevels; hr = owner->g_pd3dDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pShaderResourceView); if (FAILED(hr)) return;// hr; layerMap[i] = RLGM::Texture{ pTexture, nullptr, pShaderResourceView }; } //<--- Create Map layer } void View::AddRadar(int nRadarId) { show8bit[nRadarId] = true; show2bit[nRadarId] = true; showTails[nRadarId] = true; geoms[nRadarId] = RLGM::RadarPositioning{ 0,0,1,0 }; //Create textures for radar ID3D11Texture2D* pTexture; ID3D11RenderTargetView* pRenderTargetView; ID3D11ShaderResourceView* pShaderResourceView; D3D11_TEXTURE2D_DESC textureDesc; D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc; D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc; HRESULT hr; // ---> Create texture for drawing each radar on its own layer ZeroMemory(&textureDesc, sizeof(textureDesc)); textureDesc.Width = extensionCoef * width; textureDesc.Height = extensionCoef * height; textureDesc.MipLevels = 1; textureDesc.ArraySize = 1; textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; hr = owner->g_pd3dDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture); if (FAILED(hr)) return;// hr; ZeroMemory(&renderTargetViewDesc, sizeof(renderTargetViewDesc)); renderTargetViewDesc.Format = textureDesc.Format; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; renderTargetViewDesc.Texture2D.MipSlice = 0; hr = owner->g_pd3dDevice->CreateRenderTargetView(pTexture, &renderTargetViewDesc, &pRenderTargetView); if (FAILED(hr)) return;// hr; ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc)); shaderResourceViewDesc.Format = textureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = 1; hr = owner->g_pd3dDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pShaderResourceView); if (FAILED(hr)) return;// hr; textureRadarCurrent.push_back({ pTexture, pRenderTargetView, pShaderResourceView }); // <--- Create texture for drawing each radar on its own layer } void View::RemoveRadar(int id) { show8bit.erase(id); geoms.erase(id); } RLGM::GeoCoord View::xyToGeo(int x, int y) { double X = 2 * -x * scale / height; double Y = 2 * -y * scale / height; double Z = std::sqrt(6371000.0 * 6371000.0 - X * X - Y * Y); DirectX::XMMATRIX vect; vect.r[0].m128_f32[0] = X; vect.r[0].m128_f32[1] = Y; vect.r[0].m128_f32[2] = Z; vect.r[0].m128_f32[3] = 1; vect *= DirectX::XMMatrixRotationZ((float)(-geoPosition.Azimuth * (RLGM::M_PI / 180))) * DirectX::XMMatrixRotationX((float)(geoPosition.Latitude * (RLGM::M_PI / 180))) * DirectX::XMMatrixRotationY((float)(geoPosition.Longitude * (RLGM::M_PI / 180))); auto coord = GeoCoord(); coord.HUnderSee = 0; coord.Longitude = std::atan2(vect.r[0].m128_f32[0], vect.r[0].m128_f32[2]) / (RLGM::M_PI / 180); coord.Latitude = -std::atan(vect.r[0].m128_f32[1] / std::sqrt(vect.r[0].m128_f32[0] * vect.r[0].m128_f32[0] + vect.r[0].m128_f32[2] * vect.r[0].m128_f32[2])) / (RLGM::M_PI / 180); coord.Azimuth = geoPosition.Azimuth; return coord; } void View::AddPixelOffset(int nX, int nY) { geoPosition = xyToGeo(nX, nY); } //позиционирование Радара: центр, масштаб, поворот void View::SetRadarPosition(int id, int nX, int nY) { float x = 2 * nX / (float)width - 1; float y = 1 - 2 * nY / (float)height; for (auto& var : geoms) if ((var.first == id) || (id == -1)) { geoms[var.first].centerX = x; geoms[var.first].centerY = y; } } std::pair<int, int> View::GetRadarPosition(int id) { return std::pair<int, int> { (int)((geoms[id].centerX + 1) * width / 2), (int)((1 - geoms[id].centerY) * height / 2) }; } void View::AddRadarPosition(int id, int nDX, int nDY) { float dx = 2 * nDX / (float)width; float dy = -2 * nDY / (float)height; for (auto& var : geoms) if ((var.first == id) || (id == -1)) { geoms[var.first].centerX += dx; geoms[var.first].centerY += dy; } } void View::SetDPP(int id, float dDPP) { for (auto& var : geoms) if ((var.first == id) || (id == -1)) geoms[var.first].radius = (2 * owner->radars[var.first].numSamples / dDPP) / height; } float View::GetDPP(int id) { return (2 * owner->radars[id].numSamples) / (geoms[id].radius * height); } void View::MultiplyDPP(int id, float value) { for (auto& var : geoms) if ((var.first == id) || (id == -1)) geoms[var.first].radius *= value; } void View::MultiplyDPPCenter(int id, float value) { for (auto& var : geoms) if ((var.first == id) || (id == -1)) { geoms[var.first].radius *= value; geoms[var.first].centerX *= value; geoms[var.first].centerY *= value; } } void View::SetRotation(int id, float rot) { for (auto& var : geoms) if ((var.first == id) || (id == -1)) geoms[var.first].rotation = rot; } void View::AddRotation(int id, float rot) { for (auto& var : geoms) if ((var.first == id) || (id == -1)) geoms[var.first].rotation += rot; } void View::SetShow8bit(int nRadarId, bool value) { for (auto& var : show8bit) if ((var.first == nRadarId) || (nRadarId == -1)) show8bit[var.first] = value; } bool View::GetShow8bit(int nRadarId) { return show8bit[nRadarId]; } void View::SetShow2bit(int nRadarId, bool value) { for (auto& var : show2bit) if ((var.first == nRadarId) || (nRadarId == -1)) show2bit[var.first] = value; } bool View::GetShow2bit(int nRadarId) { return show2bit[nRadarId]; } void View::SetShowTails(int nRadarId, bool value) { for (auto& var : showTails) if ((var.first == nRadarId) || (nRadarId == -1)) showTails[var.first] = value; } bool View::GetShowTails(int nRadarId) { return showTails[nRadarId]; } void View::SetColorCorrection8bit(int nRadarId, int nCount, uint32_t* value) { D3D11_BOX region; region.left = 0; region.right = 256;//??? region.top = nRadarId; region.bottom = nRadarId + 1; region.front = 0; region.back = 1; owner->g_pImmediateContext->UpdateSubresource(colorCorrection8bitTexture.m_Texture, 0, &region, value, 256, 256); } void View::SetColorCorrection2bit(int nRadarId, int nCount, uint32_t* value) { D3D11_BOX region; region.left = 0; region.right = 256;//??? region.top = nRadarId; region.bottom = nRadarId + 1; region.front = 0; region.back = 1; owner->g_pImmediateContext->UpdateSubresource(colorCorrection2bitTexture.m_Texture, 0, &region, value, 256, 256); } void View::SetColorCorrectionTails(int nRadarId, int nCount, uint32_t* value) { D3D11_BOX region; region.left = 0; region.right = 256;//??? region.top = nRadarId; region.bottom = nRadarId + 1; region.front = 0; region.back = 1; owner->g_pImmediateContext->UpdateSubresource(colorCorrectionTailTexture.m_Texture, 0, &region, value, 256, 256); } //отрисовать Окно RLGM::ReturnCode View::Draw() { ID3D11ShaderResourceView* pNullSRV = NULL; UINT stride = sizeof(RLGM::PositionedTexturedVertex); UINT offset = 0; RLGM::ConstantBuffer1 cb1; RLGM::ConstantBuffer4 cb4; cb1.mViewWorldProjection = DirectX::XMMatrixIdentity(); float black[4]{ 0,0,0,0 }; // Disable alpha blending UINT sampleMask = 0xffffffff; owner->g_pImmediateContext->OMSetBlendState(owner->g_pBlendStateNoBlend, nullptr, sampleMask); // Set the viewport D3D11_VIEWPORT vp1{ 0, 0, extensionCoef * width, extensionCoef * height, 0, 1 }; owner->g_pImmediateContext->RSSetViewports(1, &vp1); //---> Forming final 2bit layer (3 steps) //if (draw2bit) //should be drawn because unified 2bit info is used for tails unification { int num_radars = 0; //number of actually drawn 2bits //---> 1. Drawing 2bit of each radar into separate layers for (auto& var : owner->radars) { int radar_id = var.first; if (!show2bit[radar_id]) continue; owner->g_pImmediateContext->OMSetRenderTargets(1, &textureRadarCurrent[num_radars].m_renderTargetView, nullptr); owner->g_pImmediateContext->ClearRenderTargetView(textureRadarCurrent[num_radars].m_renderTargetView, black); owner->radars[radar_id].Draw2bit(geoPosition, aspectRatio, scale, owner->psShaders[L"shader2bit.cso"], owner->vsShaders[L"vs_shader1.cso"], owner->samplerPoint/*, radarDrawMode*/); num_radars++; } //<--- Drawing 2bit of each radar into separate layers //---> 2. Unification of 2bit layers owner->g_pImmediateContext->OMSetRenderTargets(1, &textureFinalWithoutColorCorrectionHelp1.m_renderTargetView, nullptr); owner->g_pImmediateContext->PSSetShader(owner->psShaders[L"shader2bit_unify.cso"], nullptr, 0); cb4 = RLGM::ConstantBuffer4{ num_radars, (int)unification2bitRule }; owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer4, 0, nullptr, &cb4, 0, 0); owner->g_pImmediateContext->PSSetConstantBuffers(0, 1, &owner->constantBuffer4); owner->g_pImmediateContext->PSSetSamplers(0, 1, &owner->samplerPoint); for (int k = 0; k < num_radars; k++) owner->g_pImmediateContext->PSSetShaderResources(k, 1, &textureRadarCurrent[k].m_shaderResourceView); owner->g_pImmediateContext->VSSetShader(owner->vsShaders[L"vs_shader1.cso"], nullptr, 0); owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer1, 0, nullptr, &cb1, 0, 0); owner->g_pImmediateContext->VSSetConstantBuffers(0, 1, &owner->constantBuffer1); owner->g_pImmediateContext->IASetVertexBuffers(0, 1, &owner->vbQuadScreen, &stride, &offset); owner->g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); owner->g_pImmediateContext->Draw(6, 0); for (int k = 0; k < num_radars; k++) owner->g_pImmediateContext->PSSetShaderResources(k, 1, &pNullSRV); //<--- 2. Unification of 2bit layers //---> 3. Applying color correction owner->g_pImmediateContext->OMSetRenderTargets(1, &textureFinal2bit.m_renderTargetView, nullptr); owner->g_pImmediateContext->PSSetShader(owner->psShaders[L"shader2bit_colorcorrection.cso"], nullptr, 0); owner->g_pImmediateContext->PSSetShaderResources(0, 1, &textureFinalWithoutColorCorrectionHelp1.m_shaderResourceView); owner->g_pImmediateContext->PSSetSamplers(0, 1, &owner->samplerPoint); owner->g_pImmediateContext->PSSetShaderResources(1, 1, &colorCorrection2bitTexture.m_shaderResourceView); owner->g_pImmediateContext->IASetVertexBuffers(0, 1, &owner->vbQuadScreen, &stride, &offset); owner->g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); owner->g_pImmediateContext->Draw(6, 0); //<--- 3. Applying color correction } //---> Forming final Tails layer (5 steps) if (drawTails) { //---> 1. Drawing tail 2bit of each radar into separate layers int num_radars = 0; //number of actually drawn tail 2bits for (auto& var : owner->radars) { int radar_id = var.first; if (!showTails[radar_id]) continue; owner->g_pImmediateContext->OMSetRenderTargets(1, &textureRadarCurrent[num_radars].m_renderTargetView, nullptr); owner->g_pImmediateContext->ClearRenderTargetView(textureRadarCurrent[num_radars].m_renderTargetView, black); owner->radars[radar_id].Draw2bitTail(geoPosition, aspectRatio, scale, owner->psShaders[L"shader2bit.cso"], owner->vsShaders[L"vs_shader1.cso"], owner->samplerPoint/*, radarDrawMode*/); num_radars++; } //<--- 1. Drawing tail 2bit of each radar into separate layers //---> 2. Unification of tail 2bit layers owner->g_pImmediateContext->OMSetRenderTargets(1, &textureFinalWithoutColorCorrectionHelp2.m_renderTargetView, nullptr); owner->g_pImmediateContext->PSSetShader(owner->psShaders[L"shader2bit_unify.cso"], nullptr, 0); cb4 = RLGM::ConstantBuffer4{ num_radars, (int)unification2bitRule }; owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer4, 0, nullptr, &cb4, 0, 0); owner->g_pImmediateContext->PSSetConstantBuffers(0, 1, &owner->constantBuffer4); owner->g_pImmediateContext->PSSetSamplers(0, 1, &owner->samplerPoint); for (int k = 0; k < num_radars; k++) owner->g_pImmediateContext->PSSetShaderResources(k, 1, &textureRadarCurrent[k].m_shaderResourceView); owner->g_pImmediateContext->VSSetShader(owner->vsShaders[L"vs_shader1.cso"], nullptr, 0); owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer1, 0, nullptr, &cb1, 0, 0); owner->g_pImmediateContext->VSSetConstantBuffers(0, 1, &owner->constantBuffer1); owner->g_pImmediateContext->IASetVertexBuffers(0, 1, &owner->vbQuadScreen, &stride, &offset); owner->g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); owner->g_pImmediateContext->Draw(6, 0); for (int k = 0; k < num_radars; k++) owner->g_pImmediateContext->PSSetShaderResources(k, 1, &pNullSRV); //<--- 2. Unification of tail 2bit layers //---> 3. Drawing tail of each radar into separate layers num_radars = 0; //number of actually drawn tails for (auto& var : owner->radars) { int radar_id = var.first; if (!showTails[radar_id]) continue; owner->g_pImmediateContext->OMSetRenderTargets(1, &textureRadarCurrent[num_radars].m_renderTargetView, nullptr); owner->g_pImmediateContext->ClearRenderTargetView(textureRadarCurrent[num_radars].m_renderTargetView, black); owner->radars[radar_id].DrawTail(geoPosition, aspectRatio, scale, owner->psShaders[L"shaderTail.cso"], owner->vsShaders[L"vs_shader1.cso"], owner->samplerPoint);//, radarDrawMode); num_radars++; } //<--- 3. Drawing tail of each radar into separate layers //---> 4. Unification of tail layers owner->g_pImmediateContext->OMSetRenderTargets(1, &textureFinalWithoutColorCorrection.m_renderTargetView, nullptr); owner->g_pImmediateContext->PSSetShader(owner->psShaders[L"shaderTail_unify.cso"], nullptr, 0); cb4 = RLGM::ConstantBuffer4{ num_radars, owner->thr2bitForTails }; owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer4, 0, nullptr, &cb4, 0, 0); owner->g_pImmediateContext->PSSetConstantBuffers(0, 1, &owner->constantBuffer4); owner->g_pImmediateContext->PSSetSamplers(0, 1, &owner->samplerPoint); owner->g_pImmediateContext->PSSetShaderResources(0, 1, &textureFinalWithoutColorCorrectionHelp2.m_shaderResourceView); owner->g_pImmediateContext->PSSetShaderResources(1, 1, &textureFinalWithoutColorCorrectionHelp1.m_shaderResourceView); for (int k = 0; k < num_radars; k++) owner->g_pImmediateContext->PSSetShaderResources(k + 2, 1, &textureRadarCurrent[k].m_shaderResourceView); owner->g_pImmediateContext->VSSetShader(owner->vsShaders[L"vs_shader1.cso"], nullptr, 0); cb1.mViewWorldProjection = DirectX::XMMatrixIdentity(); owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer1, 0, nullptr, &cb1, 0, 0); owner->g_pImmediateContext->VSSetConstantBuffers(0, 1, &owner->constantBuffer1); stride = sizeof(RLGM::PositionedTexturedVertex); offset = 0; owner->g_pImmediateContext->IASetVertexBuffers(0, 1, &owner->vbQuadScreen, &stride, &offset); owner->g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); owner->g_pImmediateContext->Draw(6, 0); for (int k = 0; k < num_radars; k++) owner->g_pImmediateContext->PSSetShaderResources(k + 2, 1, &pNullSRV); //<--- 4. Unification of tail layers //---> 5. Applying color correction owner->g_pImmediateContext->OMSetRenderTargets(1, &textureFinalTail.m_renderTargetView, nullptr); owner->g_pImmediateContext->PSSetShader(owner->psShaders[L"shaderTail_colorcorrection.cso"], nullptr, 0); owner->g_pImmediateContext->PSSetShaderResources(0, 1, &textureFinalWithoutColorCorrection.m_shaderResourceView); owner->g_pImmediateContext->PSSetSamplers(0, 1, &owner->samplerPoint); owner->g_pImmediateContext->PSSetShaderResources(1, 1, &colorCorrectionTailTexture.m_shaderResourceView); owner->g_pImmediateContext->IASetVertexBuffers(0, 1, &owner->vbQuadScreen, &stride, &offset); owner->g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); owner->g_pImmediateContext->Draw(6, 0); //<--- 5. Applying color correction } //---> Forming final 8bit layer (3 steps) if (draw8bit) { int num_radars = 0; //number of actually drawn 8bits //---> 1. Drawing 8bit of each radar into separate layers for (auto& var : owner->radars) { int radar_id = var.first; if (!show8bit[radar_id]) continue; owner->g_pImmediateContext->OMSetRenderTargets(1, &textureRadarCurrent[num_radars].m_renderTargetView, nullptr); owner->g_pImmediateContext->ClearRenderTargetView(textureRadarCurrent[num_radars].m_renderTargetView, black); ID3D11SamplerState* txSampler = (m_8bitTexture_SamplerType == RLGM::TextureSamplerType::POINT) ? owner->samplerPoint : owner->samplerLinear; //owner->radars[radar_id].Draw8bit(geoms[radar_id], aspectRatio, owner->psShaders[L"shader8bit.cso"], owner->vsShaders[L"vs_shader1.cso"], txSampler/*, radarDrawMode*/); owner->radars[radar_id].Draw8bit(geoPosition, aspectRatio, scale, owner->psShaders[L"shader8bit.cso"], owner->vsShaders[L"vs_shader1.cso"], txSampler/*, radarDrawMode*/); num_radars++; } //<--- 1. Drawing 8bit of each radar into separate layers //---> 2. Unification of 8bit layers owner->g_pImmediateContext->OMSetRenderTargets(1, &textureFinalWithoutColorCorrection.m_renderTargetView, nullptr); owner->g_pImmediateContext->PSSetShader(owner->psShaders[L"shader8bit_unify.cso"], nullptr, 0); cb4 = RLGM::ConstantBuffer4{ num_radars, (int)unification8bitRule }; owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer4, 0, nullptr, &cb4, 0, 0); owner->g_pImmediateContext->PSSetConstantBuffers(0, 1, &owner->constantBuffer4); owner->g_pImmediateContext->PSSetSamplers(0, 1, &owner->samplerPoint); for (int k = 0; k < num_radars; k++) owner->g_pImmediateContext->PSSetShaderResources(k, 1, &textureRadarCurrent[k].m_shaderResourceView); owner->g_pImmediateContext->VSSetShader(owner->vsShaders[L"vs_shader1.cso"], nullptr, 0); owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer1, 0, nullptr, &cb1, 0, 0); owner->g_pImmediateContext->VSSetConstantBuffers(0, 1, &owner->constantBuffer1); owner->g_pImmediateContext->IASetVertexBuffers(0, 1, &owner->vbQuadScreen, &stride, &offset); owner->g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); owner->g_pImmediateContext->Draw(6, 0); for (int k = 0; k < num_radars; k++) owner->g_pImmediateContext->PSSetShaderResources(k, 1, &pNullSRV); //<--- 2. Unification of 8bit layers //---> 3. Applying color correction owner->g_pImmediateContext->OMSetRenderTargets(1, &textureFinal8bit.m_renderTargetView, nullptr); owner->g_pImmediateContext->PSSetShader(owner->psShaders[L"shader8bit_colorcorrection.cso"], nullptr, 0); owner->g_pImmediateContext->PSSetShaderResources(0, 1, &textureFinalWithoutColorCorrection.m_shaderResourceView); owner->g_pImmediateContext->PSSetSamplers(0, 1, &owner->samplerPoint); owner->g_pImmediateContext->PSSetShaderResources(1, 1, &colorCorrection8bitTexture.m_shaderResourceView); owner->g_pImmediateContext->IASetVertexBuffers(0, 1, &owner->vbQuadScreen, &stride, &offset); owner->g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); owner->g_pImmediateContext->Draw(6, 0); //<--- 3. Applying color correction } // Clear the back buffer owner->g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, nullptr); owner->g_pImmediateContext->ClearRenderTargetView(g_pRenderTargetView, DirectX::Colors::Black); // Set the viewport D3D11_VIEWPORT vp2{ 0, 0, width, height, 0, 1 }; owner->g_pImmediateContext->RSSetViewports(1, &vp2); if (drawMap) { owner->g_pImmediateContext->PSSetShader(owner->psShaders[L"shaderMap.cso"], nullptr, 0); owner->g_pImmediateContext->PSSetShaderResources(0, 1, &layerMap[layerMapIndexToDraw].m_shaderResourceView); owner->g_pImmediateContext->PSSetSamplers(0, 1, &owner->samplerPoint); RLGM::ConstantBuffer1 cb1; cb1.mViewWorldProjection = DirectX::XMMatrixRotationZ(-mapGeom.rotation * ((float)RLGM::M_PI / 180)) * DirectX::XMMatrixScaling(mapGeom.radius, mapGeom.radius, 1) * DirectX::XMMatrixTranslation(mapGeom.centerX, mapGeom.centerY, 0); owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer1, 0, nullptr, &cb1, 0, 0); owner->g_pImmediateContext->IASetVertexBuffers(0, 1, &owner->vbQuadScreen, &stride, &offset); owner->g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); owner->g_pImmediateContext->Draw(6, 0); } if (draw8bit) { // enable alpha blending if map is drawn if (drawMap) { sampleMask = 0xffffffff; owner->g_pImmediateContext->OMSetBlendState(owner->g_pBlendStateBlend, nullptr, sampleMask); } owner->g_pImmediateContext->PSSetShader(owner->psShaders[L"shader8bit_final.cso"], nullptr, 0); owner->g_pImmediateContext->PSSetShaderResources(0, 1, &textureFinal8bit.m_shaderResourceView); owner->g_pImmediateContext->PSSetSamplers(0, 1, &owner->samplerPoint); owner->g_pImmediateContext->VSSetShader(owner->vsShaders[L"vs_shader1.cso"], nullptr, 0); owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer1, 0, nullptr, &cb1, 0, 0); owner->g_pImmediateContext->VSSetConstantBuffers(0, 1, &owner->constantBuffer1); owner->g_pImmediateContext->IASetVertexBuffers(0, 1, &owner->vbQuadScreen, &stride, &offset); owner->g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); owner->g_pImmediateContext->Draw(6, 0); } // enable alpha blending sampleMask = 0xffffffff; owner->g_pImmediateContext->OMSetBlendState(owner->g_pBlendStateBlend, nullptr, sampleMask); if (drawTails) { owner->g_pImmediateContext->PSSetShader(owner->psShaders.at(L"shaderTail_final.cso"), nullptr, 0); owner->g_pImmediateContext->PSSetShaderResources(0, 1, &textureFinalTail.m_shaderResourceView); owner->g_pImmediateContext->PSSetSamplers(0, 1, &owner->samplerPoint); owner->g_pImmediateContext->VSSetShader(owner->vsShaders.at(L"vs_shader1.cso"), nullptr, 0); owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer1, 0, nullptr, &cb1, 0, 0); owner->g_pImmediateContext->VSSetConstantBuffers(0, 1, &owner->constantBuffer1); owner->g_pImmediateContext->IASetVertexBuffers(0, 1, &owner->vbQuadScreen, &stride, &offset); owner->g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); owner->g_pImmediateContext->Draw(6, 0); } if (draw2bit) { owner->g_pImmediateContext->PSSetShader(owner->psShaders[L"shader2bit_final.cso"], nullptr, 0); owner->g_pImmediateContext->PSSetShaderResources(0, 1, &textureFinal2bit.m_shaderResourceView); owner->g_pImmediateContext->PSSetSamplers(0, 1, &owner->samplerPoint); owner->g_pImmediateContext->VSSetShader(owner->vsShaders[L"vs_shader1.cso"], nullptr, 0); owner->g_pImmediateContext->UpdateSubresource(owner->constantBuffer1, 0, nullptr, &cb1, 0, 0); owner->g_pImmediateContext->VSSetConstantBuffers(0, 1, &owner->constantBuffer1); owner->g_pImmediateContext->IASetVertexBuffers(0, 1, &owner->vbQuadScreen, &stride, &offset); owner->g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); owner->g_pImmediateContext->Draw(6, 0); } // Present the information rendered to the back buffer to the front buffer (the screen) g_pSwapChain->Present(0, 0); return RLGM::ReturnCode::Success; } //возврат Картографического слоя ID3D11Texture2D* View::GetMapLayer() { return layerMap[1 - layerMapIndexToDraw].m_Texture; } void View::ReleaseMapLayer() { layerMapIndexToDraw = 1 - layerMapIndexToDraw; } //позиционирование нерадарных слоёв void View::SetSurfacesShift(int nx, int ny) { float x = 2 * nx / (float)width - 1; float y = 1 - 2 * ny / (float)height; mapGeom.centerX = x; mapGeom.centerY = y; } void View::AddSurfacesShift(int nDX, int nDY) { float dx = 2 * nDX / (float)width; float dy = -2 * nDY / (float)height; mapGeom.centerX += dx; mapGeom.centerY += dy; } void View::MultiplySurfacesDPP(float value) { mapGeom.radius *= value; } void View::MultiplySurfacesDPPCenter(float value) { mapGeom.radius *= value; mapGeom.centerX *= value; mapGeom.centerY *= value; } View::~View() { } };
#ifndef __QUEUE_H_ #define __QUEUE_H_ // define to use printing, uncommennt to debug //#define DEBUG // Queue node daat type typedef unsigned int xQueueData; // definition of queue struct queueNode { xQueueData data; queueNode *tail; }; // another names for queue and queue pointers typedef queueNode xQueue; typedef xQueue * xQueuePointer; // API class for Queue class _Queue { // private functions private: // create node xQueuePointer createNode ( xQueueData data ); // check empty condition of queue bool isEmpty ( xQueuePointer headPointer ); // public functions of Queue public: _Queue(void); // constructor ~_Queue(void); // deconstructor // create queue xQueuePointer createQueue ( unsigned int length ); // send data to queue, always send at tail position void sendToQueue ( xQueuePointer *headPointer, xQueuePointer *tailPointer, xQueueData data ); // receive data from queue, always from front position xQueueData receiveFromQueue ( xQueuePointer *headPointer, xQueuePointer *tailPointer ); // fetch peek value unsigned int getPeek ( xQueuePointer *headPointer, xQueuePointer *tailPointer ); // display queue contents void display ( xQueuePointer *headPointer ); // make all data fields to NULL void reset ( xQueuePointer *headPointer, xQueuePointer *tailPointer ); // delete queue, deconstructor can also be used void deleteQueue ( xQueuePointer *headPointer, xQueuePointer *tailPointer ); };// class Queue ends #endif /* Queue.h */
#include "..\..\01-Shared\Elysium.Graphics\GameWindow.hpp" Elysium::Graphics::Platform::GameWindow::GameWindow() : Elysium::Core::Object(), Elysium::Graphics::Platform::IGameCanvas() { // prepare the window information const char* const Myclass = "GameWindow"; WNDCLASSEX WindowInformation = { sizeof(WNDCLASSEX), CS_DBLCLKS, (WNDPROC)WindowCallbackProcedure, 0, 0, GetModuleHandle(0), LoadIcon(0, IDI_APPLICATION), LoadCursor(0, IDC_ARROW), HBRUSH(COLOR_WINDOW + 1), 0, (LPCTSTR)Myclass, LoadIcon(0, IDI_APPLICATION) }; // register the window information RegisterClassEx(&WindowInformation); // create the window _Window = CreateWindowEx(0, (LPCTSTR)Myclass, // name of the window class L"Elysium - Canvas", // title of the window WS_OVERLAPPEDWINDOW, // window style //CS_HREDRAW | CS_VREDRAW, // window style 100, // x-position 100, // y-position 840, // width 600, // height nullptr, // parent window nullptr, // menu GetModuleHandle(0), // application handle nullptr // do we use multiple windows? ); // save the address of the class as the window's USERDATA // this is required so we can cast to GameWindow* in WindowCallbackProcedure(...) SetWindowLong(_Window, GWLP_USERDATA, (long)this); } Elysium::Graphics::Platform::GameWindow::~GameWindow() { Close(); } HWND Elysium::Graphics::Platform::GameWindow::GetHWND() { return _Window; } void Elysium::Graphics::Platform::GameWindow::Show() { // display the window ShowWindow(_Window, SW_SHOWDEFAULT); } void Elysium::Graphics::Platform::GameWindow::Close() { if (_Window != nullptr) { DestroyWindow(_Window); _Window = nullptr; } } void Elysium::Graphics::Platform::GameWindow::ProcessInput() { MSG Message; GetMessage(&Message, 0, 0, 0); TranslateMessage(&Message); DispatchMessage(&Message); /* MSG Message; while (GetMessage(&Message, 0, 0, 0)) { // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // http://www.directxtutorial.com/Lesson.aspx?lessonid=11-1-5 // translate keystroke messages into the right format TranslateMessage(&Message); // send the message to the WindowProc function DispatchMessage(&Message); } */ } #include <iostream> LRESULT Elysium::Graphics::Platform::GameWindow::WindowCallbackProcedure(HWND WindowHandle, unsigned int Message, WPARAM wParam, LPARAM lParam) { GameWindow *Canvas = (GameWindow*)GetWindowLong(WindowHandle, GWLP_USERDATA); if (Canvas == nullptr) { return DefWindowProc(WindowHandle, Message, wParam, lParam); } return Canvas->Process(WindowHandle, Message, wParam, lParam); } int Elysium::Graphics::Platform::GameWindow::Process(HWND WindowHandle, unsigned int Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_CREATE: std::cout << "creating window" << std::endl; break; case WM_COMMAND: std::cout << "???" << std::endl; break; case WM_LBUTTONDOWN: std::cout << "mouse left button down at (" << LOWORD(lParam) << ',' << HIWORD(lParam) << ")" << std::endl; break; /* case WM_CLOSE: std::cout << "closing window" << std::endl; break; */ case WM_DESTROY: _ShouldExit = true; PostQuitMessage(0); break; default: return DefWindowProc(WindowHandle, Message, wParam, lParam); } return 0; }
#include <iostream> #include <vector> #include <list> #include <algorithm> #include <deque> #include <set> #include <sequtils.h> using namespace std; int main(int argc, char *argv[]) { set<int, greater<int> > col1; deque<int> col2; set<int> st; vector<int> v; populate_lseq(col1, 9); print_seq(col1); transform(col1.begin(), col1.end(), back_inserter(col2), bind2nd(multiplies<int>(), 10)); print_seq(col2); transform(col2.begin(), col2.end(), col2.begin(), col2.begin(), multiplies<int>()); print_seq(col2, "sq:"); transform(col2.begin(), col2.end(), back_inserter(v), [](int x) { return x * x; }); col2.erase(col2.begin(), col2.end()); populate_lseq(col2, 24, 60); print_seq(col2, "col2"); replace_if (col2.begin(), col2.end(), bind2nd(equal_to<int>(), 50), 42); print_seq(col2, "rpl"); col2.erase(remove_if(col2.begin(), col2.end(), bind2nd(less<int>(), 50)), col2.end()); print_seq(col2, "rm"); return 0; }
#pragma once #pragma once //------------------------------------------------------------------------- #ifndef H_unit //if not define #define H_unit //------------------------------------------------------------------------- #include <iostream> #include <string> using namespace std; //------------------------------------------------------------------------- /** * @class unit * @brief manages all and data from sensor read from file in program * * */ class unit { /** * @brief overload input and output to show, store all sensor data info */ friend ostream& operator << (ostream&, const unit&); friend istream& operator >> (istream&, unit&); public: bool operator < (unit& rhs)const; bool operator == (unit& rhs)const; unit& operator = (const int rhs); /** * @brief set default value for all sensor data */ unit(); /** * set wind speed, solar radiation, air temperature * @param sp - wind speed, sr - solar radiation, airtemp - air temperature */ unit(float sp, float sr, float airtemp); ~unit(); //destructor //setters /** * @brief store sensor data for program * @param sp - wind speed, sr - solar radiation, airtemp - air temperature */ void setUnit(float sp, float sr, float airtemp); /** * @brief store speed for program * @param sp - speed */ void setSpeed(float sp); /** * @brief store solar radtiation for program * @param sr - solar radiation */ void setSolarRad(float sr); /** * @brief store air temperature for program * @param airtemp - air temperature */ void setAirTemp(float airtemp); //getter /* *@brief extract all sensor data from program to terminal */ void print(); /** * @brief extract speed from program * @return int */ float getSpeed() const; /** * @brief extract solar radtiation from program * @return float */ float getSolarRad() const; /** * @brief extract air temperature from program * @return float */ float getAirTemp() const; private: ///wind speed in data float speed; ///solar radiation in data float solar_radiation; /// air temperature in data float air_temperature; }; #endif // !H_unit
#include <iostream> #include <Windows.h> #include "Board.h" using namespace std; #define COL GetStdHandle(STD_OUTPUT_HANDLE) #define ORIGINAL SetConsoleTextAttribute(COL,0x0007); Board::Board() { int i, j; for (i = 0; i < 10; i++) for (j = 0; j < 20; j++) board_[i][j] = EMPTY; } int Board::GetState(cursur_point pos) { return board_[pos.GetX()][pos.GetY()]; } void Board::SetState(cursur_point pos,int state) { board_[pos.GetX()][pos.GetY()] = state; } int Board::CheckLineFull(cursur_point reference_pos) { int count = 0; int check = 0; for (int val = 0; val < 19; val++) { for (int y = 0; y < 20; y++) { for (int x = 0; x < 10; x++) if (board_[x][y] == EMPTY) { check++; break; } if (check == 0) { count++; for (int j = y + 1; j < 19; j++) { for (int i = 0; i < 10; i++) { cursur_point::GotoXY(2 * (i + reference_pos.GetX()) + 2, 21 - j); cout << " "; board_[i][j - 1] = board_[i][j]; } for (int i = 0; i < 10; i++) board_[i][j - 1] = board_[i][j]; } for (int i = 0; i < 10; i++) board_[i][19] = EMPTY; for (int j = 0; j < 20; j++) { for (int i = 0; i < 10; i++) { if (board_[i][j] != EMPTY) { cursur_point::GotoXY(2 * (i + reference_pos.GetX()) + 2, 20 - j); ORIGINAL cout << "กแ"; } else { cursur_point::GotoXY(2 * (i + reference_pos.GetX()) + 2, 20 - j); cout << " "; } } } } check = 0; } } return count; }
/* Based on UserCode/Futyan/macros/WenuTemplateFit.cc See WCharge/scripts/genTemplates.py for an example of how to run the code. */ #include "AsymTemplateHistos.hh" #include "KinSuite.hh" #include <fstream> using namespace std; //using namespace Event; AsymTemplateHistos::AsymTemplateHistos(const std::string & folderName, Utils::ParameterSet &pset ): mFolderName(folderName) { elecET = pset.Get<double>("ElecET"); chChk = pset.Get<bool>("ChCheck"); lepPtVeto = pset.Get<double>("ElePtVeto"); convChk = pset.Get<bool>("ConvCheck"); lepVeto = pset.Get<bool>("EleVeto"); wp = pset.Get<int>("WorkingPoint"); scEta = pset.Get<bool>("UseSCEta"); scEnergy = pset.Get<bool>("UseSCEnergy"); CorVersion = pset.Get<int>("CorVersion"); //(0=95%,1=90%,2=85%,3=80%,4=70%,5=60%) ieff=-1; if (wp==95) ieff=0; if (wp==90) ieff=1; if (wp==85) ieff=2; if (wp==80) ieff=3; if (wp==70) ieff=4; if (wp==60) ieff=5; if (ieff<0){ cout<<"Working point "<<wp<<" unknown"<<endl <<"Working points accepted are 60,70,80,85,90,95"<<endl <<"Job is going to stop"<<endl; assert(0); } //mMissingHits=0; //mDCot=0.02; //mDist=0.02; } void AsymTemplateHistos::Start(Event::Data & ev) { initDir(ev.OutputFile(), mFolderName.c_str()); BookHistos(); } AsymTemplateHistos::~AsymTemplateHistos() { } /* ~~~BOOK HISTOS~~~ */ void AsymTemplateHistos::BookHistos() { int nBins = 100; for (int ih=0;ih<EtaChBins_;ih++){ for (int ipt=0; ipt<PtBins; ipt++) { TString sel = "h_pfMET"+etabin[ih]+ptbin[ipt]; TString antisel = "h_anti_pfMET"+etabin[ih]+ptbin[ipt]; TString selcor = "h_pfMETcor"+etabin[ih]+ptbin[ipt]; TString antiselcor = "h_anti_pfMETcor"+etabin[ih]+ptbin[ipt]; h_sel[ih][ipt] = new TH1F(sel,sel,nBins,0,100.); h_antisel[ih][ipt] = new TH1F(antisel,antisel,nBins,0,100.); h_selcor[ih][ipt] = new TH1F(selcor ,selcor ,nBins,0,100.); h_antiselcor[ih][ipt]= new TH1F(antiselcor,antiselcor,nBins,0,100.); } } for (int ih=0;ih<WptChBins_;ih++){ for (int ipt=0; ipt<PtBins; ipt++) { TString sel= "h_wpt_pfMET"+wptbin[ih]+ptbin[ipt]; TString antisel= "h_wpt_anti_pfMET"+wptbin[ih]+ptbin[ipt]; h_wpt_sel[ih][ipt] = new TH1F(sel,sel,nBins,0,100.); h_wpt_antisel[ih][ipt]= new TH1F(antisel,antisel,nBins,0,100.); //TODO add corrected ET wpt histograms } } } /* ~~~PROCESS~~~ */ bool AsymTemplateHistos::Process(Event::Data & ev) { w=ev.GetEventWeight(); double met = ev.PFMET().Pt(); double met_phi = ev.PFMET().Phi(); //ONLY 1 GOOD ELECTRON && VETO ON THE SECOND // int nSel=0; int nSelVeto=0; int nSelVetoCor=0; // std::vector<Lepton const *>::const_iterator goodLep; //ANTI EVENT SELECTION int nSel[PtBins]={0,0,0}; int nSelCor[PtBins]={0,0,0}; //int nVetoSel[PtBins]={0,0,0}; int nAntiSel[PtBins]={0,0,0}; int nAntiSelCor[PtBins]={0,0,0}; // std::vector<Lepton const *>::const_iterator dfiLep[AntiEvBins]; // std::vector<Lepton const *>::const_iterator dhiLep[AntiEvBins]; std::vector<Lepton const *>::const_iterator goodLepCor[PtBins]; std::vector<Lepton const *>::const_iterator goodLep[PtBins]; std::vector<Lepton const *>::const_iterator antiLepCor[PtBins]; std::vector<Lepton const *>::const_iterator antiLep[PtBins]; for (std::vector<Lepton const *>::const_iterator lep=ev.LD_CommonElectrons().accepted.begin(); lep != ev.LD_CommonElectrons().accepted.end(); ++lep) { //Selection int i = (*lep)->GetIndex(); double eta = (scEta) ? ev.GetElectronESuperClusterEta(i) : (*lep)->Eta(); //double Et = (scEnergy) ? ev.GetElectronESuperClusterOverP(i)*ev.GetElectronTrkPt(i) : (*lep)->Et(); double Et = (scEnergy) ? ev.GetElectronEcalEnergy(i)/cosh(eta) : (*lep)->Et(); double corEt = cor(Et,eta,ev.RunNumber()); if (!fid(eta)) continue; bool chargeOk = (chChk) ? (((*lep)->GetCharge()==ev.GetElectronSCCharge(i)) && ((*lep)->GetCharge()==ev.GetElectronKFCharge(i))) : true; bool convOk = (convChk) ? (passConv(ev.GetElectronGsfTrackTrackerExpectedHitsInner(i) , ev.GetElectronDCot(i), ev.GetElectronDist(i), ieff) ) : true; bool iso = passIsolation((*lep)->GetTrkIsolation()/(*lep)->Pt(), (*lep)->GetEcalIsolation()/(*lep)->Pt(), (*lep)->GetHcalIsolation()/(*lep)->Pt(),eta,ieff); bool id = passID(ev.GetElectronSigmaIetaIeta(i), ev.GetElectronDeltaPhiAtVtx(i), ev.GetElectronDeltaEtaAtVtx(i), ev.GetElectronHoE(i),eta,ieff); bool veto_convOk = (convChk) ? (passConv(ev.GetElectronGsfTrackTrackerExpectedHitsInner(i) , ev.GetElectronDCot(i), ev.GetElectronDist(i), 0) ) : true; bool veto_iso = passIsolation((*lep)->GetTrkIsolation()/(*lep)->Pt(), (*lep)->GetEcalIsolation()/(*lep)->Pt(), (*lep)->GetHcalIsolation()/(*lep)->Pt(),eta,0); bool veto_id = passID(ev.GetElectronSigmaIetaIeta(i), ev.GetElectronDeltaPhiAtVtx(i), ev.GetElectronDeltaEtaAtVtx(i), ev.GetElectronHoE(i),eta,0); if (iso && id && chargeOk && convOk){ for (int ipt=0;ipt<PtBins;ipt++){ if (Et>ptcut[ipt]){ nSel[ipt]++; goodLep[ipt]=lep; } if (corEt>ptcut[ipt]){ nSelCor[ipt]++; goodLepCor[ipt]=lep; } } } if (veto_iso && veto_id && veto_convOk){ if (Et >lepPtVeto) nSelVeto++; if (corEt>lepPtVeto) nSelVetoCor++; } // David's anti-selection // Pass WP80 : // no Conversion rejection // All Isolation cuts // Electron ID (only H/E cut) // Anti WP90/85 (Deta/Dphi) // Deta > 0.007/0.009 (EB/EE) // Dphi > 0.06/0.04 (EB/EE) bool AS_convOk = true;//(convChk) ? (passConv(ev.GetElectronGsfTrackTrackerExpectedHitsInner(i) , ev.GetElectronDCot(i), ev.GetElectronDist(i), 0) ) : true; //Removed cut bool AS_iso = passIsolation((*lep)->GetTrkIsolation()/(*lep)->Pt(), (*lep)->GetEcalIsolation()/(*lep)->Pt(), (*lep)->GetHcalIsolation()/(*lep)->Pt(),eta,3);//3 = WP80 bool AS_id = passID(0., 0., 0., ev.GetElectronHoE(i),eta,3);//3 = WP80 //only HoE bool pass_dfi = passID_AS (ev.GetElectronDeltaPhiAtVtx(i), 0., eta ,as_dphi); bool pass_dhi = passID_AS (0., ev.GetElectronDeltaEtaAtVtx(i), eta ,as_deta); for (int ipt=0;ipt<PtBins;ipt++){ if (Et>ptcut[ipt]){ if (AS_convOk && AS_iso && AS_id && (!pass_dfi) && (!pass_dhi)){ nAntiSel[ipt]++; antiLep[ipt]=lep; } } if (corEt>ptcut[ipt]){ if (AS_convOk && AS_iso && AS_id && (!pass_dfi) && (!pass_dhi)){ nAntiSelCor[ipt]++; antiLepCor[ipt]=lep; } } } } //TDirectory *currentDirectory= ev.OutputFile()->GetDirectory(mFolderName.c_str()); for (int ipt=0;ipt<PtBins;ipt++){ //Loop over Pt Bins //Uncorrected if ((nSel[ipt]==1)&&(nSelVeto==1)){ int ih = getEta(goodLep[ipt]); int iwpt = getWpt(goodLep[ipt],met,met_phi); h_sel[0][ipt]->Fill(met,w); if (ih>0) h_sel[ih][ipt]->Fill(met,w); if (iwpt>0) h_wpt_sel[iwpt][ipt]->Fill(met,w); } if (nAntiSel[ipt]==1){ int ih = getEta(antiLep[ipt]); int iwpt = getWpt(antiLep[ipt],met,met_phi); h_antisel[0][ipt]->Fill(met,w); if (ih>0) h_antisel[ih][ipt]->Fill(met,w); if (iwpt>0) h_wpt_antisel[iwpt][ipt]->Fill(met,w); } //Corrected //TODO add corrected ET wpt histograms if ((nSelCor[ipt]==1)&&(nSelVetoCor==1)){ int ih = getEta(goodLepCor[ipt]); int iwpt = getWpt(goodLepCor[ipt],met,met_phi); if (ipt == 0) { cout<<"RUN= "<<ev.RunNumber()<<" LUMIS= "<<ev.LumiSection()<<" EVENT= "<<ev.EventNumber()<<endl;} h_selcor[0][ipt]->Fill(met,w); if (ih>0) h_selcor[ih][ipt]->Fill(met,w); //if (iwpt>0) h_wpt_sel[iwpt][ipt]->Fill(met,w); } if (nAntiSelCor[ipt]==1){ int ih = getEta(antiLepCor[ipt]); int iwpt = getWpt(antiLepCor[ipt],met,met_phi); h_antiselcor[0][ipt]->Fill(met,w); if (ih>0) h_antiselcor[ih][ipt]->Fill(met,w); //if (iwpt>0) h_wpt_antisel[iwpt][ipt]->Fill(met,w); } } return true; } // end of Process method std::ostream& AsymTemplateHistos::Description(std::ostream &ostrm) { ostrm << "AsymTemplateHistos plots made here: (histograms in "; ostrm << mFolderName << ")"; return ostrm; } bool AsymTemplateHistos::passIsolation (double track, double ecal, double hcal, double eta, int ieff) { return CheckCuts(track, ecal, hcal, 0., 0., 0., 0., eta, ieff ); } bool AsymTemplateHistos::passID (double sihih, double dfi, double dhi,double hoe, double eta, int ieff) { return CheckCuts(0., 0., 0., sihih, dfi, dhi, hoe, eta, ieff ); } bool AsymTemplateHistos::passConv (int v_missHits, double v_DCot, double v_Dist, int ieff) { if ((v_missHits <= MissHits_[ieff]) && (fabs(v_DCot) > DCot_[ieff] || fabs(v_Dist) > Dist_[ieff]) ) return true; return false; } bool AsymTemplateHistos::passID_AS(double v_dfi, double v_dhi, double eta, int ieff){ if (fabs(eta)< 1.479) { if ( fabs(v_dfi) < Dphi_[ieff] && fabs(v_dhi) < Deta_[ieff] ) return true; } else { if (fabs(v_dfi) < Dphi_ee_[ieff] && fabs(v_dhi) < Deta_ee_[ieff] ) return true; } return false; } bool AsymTemplateHistos::fid(double eta) { return (fabs(eta)<2.4 && ( fabs(eta) < 1.4 || fabs(eta) > 1.6 ));//( fabs(eta) < 1.4442 || fabs(eta) > 1.56 )); } int AsymTemplateHistos::getEta(std::vector<Lepton const *>::const_iterator lep){ //cout<<"test1"<<endl; double eta= (*lep)->Eta(); double charge = (*lep)->GetCharge(); //double pt= (*lep)->Pt(); bool acc= (((fabs(eta)<1.6)&&(fabs(eta)>1.4))|| (fabs(eta)>2.4)); bool cha = (charge==0); //cout<<"test2"<<endl; int ih = -1; for (int ieta=0;ieta<EtaBins;ieta++){ if (fabs(eta)<etabinup[ieta]){ ih = ieta+1; // bin 0 is inclusive bin break; } } //cout<<"test3"<<endl; if (ih < 0) return -1; // no eta bin found if (cha) return -1; if (acc) return -1; if (charge<0) ih+=EtaBins; // positive bins go 1,2,3,4,5,6, negative go 7,8,9,10,11,12 //cout<<"test4"<<endl; return ih; } int AsymTemplateHistos::getWpt(std::vector<Lepton const *>::const_iterator lep, double met, double met_phi){ double charge = (*lep)->GetCharge(); double pt= (*lep)->Pt(); int wpt = -1; for (int iwpt=0;iwpt<WptBins;iwpt++){ double measured_Wpt = sqrt(met*met+pt*pt+pt*met*cos(met_phi-(*lep)->Phi())); if (measured_Wpt>wptbinlow[iwpt]){ wpt = iwpt; // note: no +1 since we do not have an inclusive bin here //note : no break since these are the lower bin edges } } if (wpt < 0) return -1; // no wpt bin found (should be impossible) if (charge<0) wpt+=WptBins; // positive bins go 0,1,2,3,4, negative go 5,6,7,8,9 return wpt; } double AsymTemplateHistos::cor(double et,double eta,int runNumber){ int ih = -1; for (int ieta=0;ieta<EtaBins;ieta++){ if (fabs(eta)<etabinup[ieta]){ ih = ieta; break; } } if (CorVersion == 0) return et*Sca_38_[ih]; else if (CorVersion == 1 && runNumber<148000) return et*Sca_39_p1_[ih]; else if (CorVersion == 1 && runNumber>=148000) return et*Sca_39_p2_[ih]; else return et; } bool AsymTemplateHistos::CheckCuts(double v_trk, double v_ecal, double v_hcal, double v_sihih, double v_dfi, double v_dhi, double v_hoe, double eta, int ieff){ if (fabs(eta)< 1.479) { if ( v_trk < Trk_[ieff] && v_ecal < Ecal_[ieff] && v_hcal < Hcal_[ieff] && v_sihih < sihih_[ieff] && fabs(v_dfi) < Dphi_[ieff] && fabs(v_dhi) < Deta_[ieff] && fabs(v_hoe)< HoE_[ieff] ) return true; } else { if (v_trk < Trk_ee_[ieff] && v_ecal < Ecal_ee_[ieff] && v_hcal < Hcal_ee_[ieff] && v_sihih <sihih_ee_[ieff] && fabs(v_dfi) <Dphi_ee_[ieff] && //MICHELE DA SCOMMENTARE fabs(v_dhi) <Deta_ee_[ieff] && fabs(v_hoe)< HoE_ee_[ieff] ) return true; } return false; }
#include <iostream> #include <cmath> #include <ctime> #include <vector> #include <array> #include <algorithm> #include <set> #include <string> #include <sstream> #include <map> #include <future> #include <thread> using namespace std; map<string, set<int>> keyResults; vector<int> list; vector<string> listString; int solve(int seats); int solveq(int seats); int solve(vector<bool> &, bool); class Solution { public: explicit Solution(int seatsArg) : seats(seatsArg), factorials((seatsArg%2 == 0 ? seatsArg/2 + 1: seatsArg/2 + 2)), powers(seatsArg/3 + 1), factorialInverses((seatsArg% 2 == 0 ? seatsArg / 2 : seatsArg / 2 + 1)) { } int solve(); private: static const long long MOD = 100000007; int seats; void fillFactorials(); void fillPowers(); void fillFactorialInverses(); long long evenTypeOne(); long long evenTypeTwo(); long long evenTypeThree(); long long evenTypeFour(); long long oddTypeOne(); long long oddTypeTwo(); long long oddTypeThree(); long long oddTypeFour(); vector<long long> factorials; vector<long long> powers; vector<long long> factorialInverses; }; int main() { clock_t start = clock(); int result = Solution(1000000).solve(); clock_t end = clock(); cout << result << ' ' << (static_cast<double>(end) - start) / CLOCKS_PER_SEC << endl; system("PAUSE"); } int Solution::solve() { auto futureResult1 = async(launch::async, &Solution::fillFactorials, this); fillPowers(); futureResult1.get(); fillFactorialInverses(); long long sum = 0; if (seats%2 == 0) { auto futureResult2 = async(launch::async, &Solution::evenTypeOne, this); auto futureResult3 = async(launch::async, &Solution::evenTypeTwo, this); auto futureResult4 = async(launch::async, &Solution::evenTypeThree, this); sum += evenTypeFour(); sum += futureResult2.get(); sum += futureResult3.get(); sum += futureResult4.get(); sum %= MOD; } else { auto futureResult2 = async(launch::async, &Solution::oddTypeOne, this); auto futureResult3 = async(launch::async, &Solution::oddTypeTwo, this); auto futureResult4 = async(launch::async, &Solution::oddTypeThree, this); sum += oddTypeFour(); sum += futureResult2.get(); sum += futureResult3.get(); sum += futureResult4.get(); sum %= MOD; } //cout << maxFactorial << ' ' << maxPower << ' ' << maxInverseFactorial << endl; return static_cast<int>(sum); } void Solution::fillFactorials() { factorials[0] = 1; for (size_t i = 1; i < factorials.size(); ++i) { factorials[i] = factorials[i - 1] * i; factorials[i] %= MOD; } } void Solution::fillPowers() { powers[0] = 1; for (size_t i = 1; i < powers.size(); ++i) { powers[i] = 2 * powers[i - 1]; powers[i] %= MOD; } } void Solution::fillFactorialInverses() { factorialInverses[0] = 1; factorialInverses[1] = 1; for (size_t i = 2; i < factorialInverses.size(); ++i) { long long x = 1; long long y = factorials[i]; x *= y; x %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; y *= y; y %= MOD; y *= y; y %= MOD; x *= y; x %= MOD; factorialInverses[i] = x; } } long long Solution::evenTypeOne() { long long sum = 0; //start with zero, end with 10 for (int tens = (seats - 4) / 2, hundreds = 1; 1 <= tens; tens -= 3, hundreds += 2) { long long result = factorials[tens + hundreds] * factorials[tens - 1 + hundreds]; result %= MOD; result *= factorialInverses[hundreds]; result %= MOD; result *= factorialInverses[tens - 1]; result %= MOD; result *= powers[hundreds]; result %= MOD; result *= factorials[hundreds]; result %= MOD; result *= (hundreds + 1); result %= MOD; result *= (hundreds + 2); result %= MOD; result *= factorials[hundreds + tens - 1]; result %= MOD; sum += result; } sum %= MOD; return sum; } long long Solution::evenTypeTwo() { long long sum = 0; //start with zero, end with 1 for (int tens = (seats - 2) / 2, hundreds = 0; 0 <= tens; tens -= 3, hundreds += 2) { long long result = factorials[tens + hundreds + 1] * factorials[tens + hundreds]; result %= MOD; result *= factorialInverses[hundreds]; result %= MOD; result *= factorialInverses[tens]; result %= MOD; result *= powers[hundreds]; result %= MOD; result *= factorials[hundreds]; result %= MOD; result *= (hundreds + 1); result %= MOD; result *= factorials[hundreds + tens]; result %= MOD; sum += result; } sum %= MOD; return sum; } long long Solution::evenTypeThree() { long long sum = 0; //starts with any ends with 10 for (int tens = seats / 2, hundreds = 0; 1 <= tens; tens -= 3, hundreds += 2) { long long result = factorials[tens + hundreds] * factorials[tens - 1 + hundreds]; result %= MOD; result *= factorialInverses[hundreds]; result %= MOD; result *= factorialInverses[tens - 1]; result %= MOD; result *= powers[hundreds]; result %= MOD; result *= factorials[hundreds]; result %= MOD; result *= (hundreds + 1); result %= MOD; result *= factorials[hundreds + tens - 1]; result %= MOD; sum += result; } sum %= MOD; return sum; } long long Solution::evenTypeFour() { long long sum = 0; for (int tens = (seats - 4) / 2, hundreds = 1; 0 <= tens; tens -= 3, hundreds += 2) { long long result = factorials[tens + hundreds + 1] * factorials[tens + hundreds]; result %= MOD; result *= factorialInverses[hundreds]; result %= MOD; result *= factorialInverses[tens]; result %= MOD; result *= powers[hundreds]; result %= MOD; result *= factorials[hundreds]; result %= MOD; result *= factorials[hundreds + tens]; result %= MOD; sum += result; sum %= MOD; } return sum; } long long Solution::oddTypeOne() { long long sum = 0; //start with zero, end with 10 for (int tens = (seats - 1) / 2, hundreds = 0; 1 <= tens; tens -= 3, hundreds += 2) { long long result = factorials[tens + hundreds] * factorials[tens - 1 + hundreds]; result %= MOD; result *= factorialInverses[hundreds]; result %= MOD; result *= factorialInverses[tens - 1]; result %= MOD; result *= powers[hundreds]; result %= MOD; result *= factorials[hundreds]; result %= MOD; result *= (hundreds + 1); result %= MOD; result *= (hundreds + 2); result %= MOD; result *= factorials[hundreds + tens - 1]; result %= MOD; sum += result; } return sum; } long long Solution::oddTypeTwo() { long long sum = 0; //start with zero, end with 1 for (int tens = (seats - 5) / 2, hundreds = 1; 0 <= tens; tens -= 3, hundreds += 2) { long long result = factorials[tens + hundreds + 1] * factorials[tens + hundreds]; result %= MOD; result *= factorialInverses[hundreds]; result %= MOD; result *= factorialInverses[tens]; result %= MOD; result *= powers[hundreds]; result %= MOD; result *= factorials[hundreds]; result %= MOD; result *= (hundreds + 1); result %= MOD; result *= factorials[hundreds + tens]; result %= MOD; sum += result; } return sum; } long long Solution::oddTypeThree() { long long sum = 0; //starts with any ends with 10 for (int tens = (seats - 3) / 2, hundreds = 1; 1 <= tens; tens -= 3, hundreds += 2) { long long result = factorials[tens + hundreds] * factorials[tens - 1 + hundreds]; result %= MOD; result *= factorialInverses[hundreds]; result %= MOD; result *= factorialInverses[tens - 1]; result %= MOD; result *= powers[hundreds]; result %= MOD; result *= factorials[hundreds]; result %= MOD; result *= (hundreds + 1); result %= MOD; result *= factorials[hundreds + tens - 1]; result %= MOD; sum += result; } return sum; } long long Solution::oddTypeFour() { long long sum = 0; for (int tens = (seats - 1) / 2, hundreds = 0; 0 <= tens; tens -= 3, hundreds += 2) { long long result = factorials[tens + hundreds + 1] * factorials[tens + hundreds]; result %= MOD; result *= factorialInverses[hundreds]; result %= MOD; result *= factorialInverses[tens]; result %= MOD; result *= powers[hundreds]; result %= MOD; result *= factorials[hundreds]; result %= MOD; result *= factorials[hundreds + tens]; result %= MOD; sum += result; sum %= MOD; } return sum; } int solve(int seats) { cout << boolalpha; vector<bool> vect(seats); int sum = 0; for (size_t i = 0; i < vect.size(); ++i) { vect[i] = true; int result = solve(vect, true); sum += result; vect[i] = false; cout << i << " = " << result << endl; } //sort(list.begin(), list.end()); /*int prev = list[0]; int count = 1; for (int i = 1; i < list.size(); ++i) { if (list[i] != prev) { cout << prev << ' ' << count << endl; count = 0; } prev = list[i]; count++; } cout << prev << ' ' << count << endl;*/ sort(listString.begin(), listString.end()); string & prev = listString[0]; int count = 1; for (size_t i = 1; i < listString.size(); ++i) { if (listString[i] != prev) { cout << prev << ' ' << count << endl; count = 0; } prev = listString[i]; count++; } cout << prev << ' ' << count << endl; for (auto item : keyResults) { cout << item.first << " = "; for (int results : item.second) { cout << results << ", "; } cout << "\b\b " << endl; } return sum; } int solve(vector<bool> &seats, bool show) { bool found = false; int result = 0; for (size_t i = 0; i < seats.size(); ++i) { if (!seats[i]) { int count = 0; if (i != 0) { if (seats[i - 1]) { count++; } } if (i != seats.size() - 1) { if (seats[i + 1]) { count++; } } if (count == 0) { show = false; found = true; seats[i] = true; result += solve(seats, true); seats[i] = false; } } } if (!found) { for (size_t i = 0; i < seats.size(); ++i) { if (!seats[i]) { int count = 0; if (i != 0) { if (seats[i - 1]) { count++; } } if (i != seats.size() - 1) { if (seats[i + 1]) { count++; } } if (count == 1) { found = true; seats[i] = true; result += solve(seats, false); seats[i] = false; } } } } if (!found) { for (size_t i = 0; i < seats.size(); ++i) { if (!seats[i]) { found = true; seats[i] = true; result += solve(seats, false); seats[i] = false; } } } if (show) { array<int, 3> types = { 0 }; vector<int> vect; int number = (seats[0] ? 1 : 0); for (size_t i = 1; i < seats.size(); ++i) { if (seats[i]) { vect.push_back(number); number = 1; //cout << '1'; types[0]++; } else { number *= 10; int count = 0; if (i != 0) { if (seats[i - 1]) { count++; } } if (i != seats.size() - 1) { if (seats[i + 1]) { count++; } } types[count]++; //cout << '0'; } } if (number != 0) { vect.push_back(number); } //cout << endl; //cout << types[0] << ' ' << types[1] << ' ' << types[2] << endl; sort(vect.begin(), vect.end()); ostringstream output; for (int a : vect) { output << a; } string key = output.str(); //cout << key; listString.push_back(key); keyResults.insert(make_pair(key, set<int>())); keyResults[key].insert(result); //cout << result << endl; //system("PAUSE"); } if (found) { return result; } else { return 1; } }
#ifndef FIGHTER_H #define FIGHTER_H #include "Entity.h" #include <SFML\Graphics.hpp> class Fighter: public Entity { public: Fighter(); ~Fighter(); void dir(int hitwall); virtual int checkColl(int x, int y); int Destroy(int x, int y); bool dead = false; void randomnspawnerEnemies(); // Randomspawner for enemies private: int hitwall = 0; }; #endif
#include<iostream> using std::cin; using std::cout; using std::endl; float GetPosAmount() { float temp; cout<<"Enter a positive value:"; cin>>temp; while(temp<0.0) { cout<<"**Negative value,enter a positive value:"<<endl; cin>>temp; } return (temp); } main() { GetPosAmount(); }
//: C15:Instrument4.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 // Mozliwosc rozszerzania programow w programowaniu obiektowym #include <iostream> using namespace std; enum note { middleC, Csharp, Cflat }; // Itd. class Instrument { public: virtual void play(note) const { cout << "Instrument::play" << endl; } virtual char* what() const { return "Instrument"; } // Zakladamy, ze funkcja modyfikuje obiekt: virtual void adjust(int) {} }; class Wind : public Instrument { public: void play(note) const { cout << "Wind::play" << endl; } char* what() const { return "Wind"; } void adjust(int) {} }; class Percussion : public Instrument { public: void play(note) const { cout << "Percussion::play" << endl; } char* what() const { return "Percussion"; } void adjust(int) {} }; class Stringed : public Instrument { public: void play(note) const { cout << "Stringed::play" << endl; } char* what() const { return "Stringed"; } void adjust(int) {} }; class Brass : public Wind { public: void play(note) const { cout << "Brass::play" << endl; } char* what() const { return "Brass"; } }; class Woodwind : public Wind { public: void play(note) const { cout << "Woodwind::play" << endl; } char* what() const { return "Woodwind"; } }; // Funkcja taka sama, jak poprzednio: void tune(Instrument& i) { // ... i.play(middleC); } // Nowa funkcja: void f(Instrument& i) { i.adjust(1); } // Rzutowanie w gore podczas inicjalizacji tablicy: Instrument* A[] = { new Wind, new Percussion, new Stringed, new Brass, }; int main() { Wind flute; Percussion drum; Stringed violin; Brass flugelhorn; Woodwind recorder; tune(flute); tune(drum); tune(violin); tune(flugelhorn); tune(recorder); f(flugelhorn); } ///:~
// // main.cpp // ListasEjercicio1 // // Created by Daniel on 16/10/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #include <iostream> #include "Cola.h" #include "Pila.h" #include <string> #define N 4 int main(int argc, const char * argv[]) { srand((int)time(NULL)); int temp; Cola<int> * cola = new Cola<int>; Pila<int> * p = new Pila<int>; std::cout<<"---------- Invertir cola -------"<<std::endl; for (int i = 0; i < N; ++i){ temp = rand()%100; cola->enQue(temp); } std::cout<<*cola<<std::endl; for (int j = 0; j< N; ++j){ p->push(cola->deQue()->getInfo()); } for (int z = 0; z<N; z++){ cola->enQue(p->pop()->getInfo()); } std::cout<<*cola; delete p; delete cola; std::cout<<"-------- Ejercicio 2 --------"<<std::endl; std::string linea; std::string palabra; Pila<std::string> * palabras = new Pila<std::string>; std::cout<<"Escriba una frase: "<<std::endl; getline(std::cin, linea); for (int i = 0; i < linea.length(); ++i){ palabra = linea[i]; while (linea[i+1] != ' ' && i < linea.length()-1) { ++i; palabra += linea[i]; } palabras->push(palabra); } palabra = ""; int t = palabras->size(); for (int k = 0; k < t; ++k){ palabra += palabras->pop()->getInfo(); palabra += " "; } std::cout<<palabra<<std::endl; delete palabras; return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int MAXN = 100000; int arv[MAXN + 3]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; for(int i = 0; i < n; i++) cin >> arv[i]; sort(arv, arv + n); int jud[MAXN + 3], len = 0; jud[len++] = arv[0]; for(int i = 1; i < n; i++) if(arv[i] != arv[i - 1]) jud[len++] = arv[i]; if(len == 1 || len == 2 || (len == 3 && jud[2] + jud[0] == jud[1] * 2) ) cout << "YES"; else cout << "NO"; return 0; }
#include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <queue> #include <unordered_set> #include <unordered_map> #include <stack> #include <cstdio> #define INT_MIN (1<<31) #define INT_MAX (~INT_MIN) #define UNREACHABLE (INT_MAX>>2) #define INF (1e300) using namespace std; ifstream fin("11858_input.txt"); #define cin fin long long merge(vector<int> & v, int left, int right) { int mid = (right - left) / 2 + left; vector<int> f(right - left, 0); int lp, rp; lp = left; rp = mid; int count = 0; long long result = 0; while (lp < mid && rp < right) { if (v[lp] < v[rp]) f[count++] = v[lp++]; else { result += mid - lp; f[count++] = v[rp++]; } } while (lp < mid) f[count++] = v[lp++]; while (rp < right) f[count++] = v[rp++]; count = 0; while (count < (int)f.size()) { v[left + count] = f[count]; count++; } return result; } long long get_inversion_num(vector<int> & v, int left, int right) { if (right - left <= 1) return 0; int mid = (right - left) / 2 + left; long long result = get_inversion_num(v, left, mid); result += get_inversion_num(v, mid, right); result += merge(v, left, right); return result; } int main() { int n; while (cin >> n) { vector<int> v(n, 0); for (int i = 0; i < n; i++) cin >> v[i]; cout << get_inversion_num(v, 0, v.size()) << endl; } }
#ifndef MODELFITTING_H #define MODELFITTING_H #include <QWidget> #include "facialmesh.h" namespace Ui { class ModelFitting; } class ModelFitting : public QWidget { Q_OBJECT public: explicit ModelFitting(QWidget *parent = nullptr); ~ModelFitting(); void init(void); void conectar(void); void desconectar(void); facialmesh *candide; cv::Mat kf_image; bool keyframe = false; public slots: void actualizar_posicion(); void actualizar_animation(); void actualizar_animation_slider(); void actualizar_shape(); void actualizar_shape_slider(); private slots: void on_boton_reset_clicked(); void on_animation_back_pressed(); void on_animation_next_pressed(); void on_shape_back_pressed(); void on_shape_next_pressed(); void on_tabWidget_currentChanged(int index); void on_render_model_clicked(); void on_save_model_clicked(); void on_load_model_clicked(); void on_key_frame_ready_clicked(); void resizeEvent(QResizeEvent *event); signals: void keyframe_ready(); private: Ui::ModelFitting *ui; }; #endif // MODELFITTING_H
#include "TextArea.h" #include "../__trash.h" #include "../src/IMAGELoad.h" TextArea::TextArea(Pos p, Font* f) : _f{f} { w = 800; h = 600; g = 6; fg = g*2.0/(GLfloat)w; _pos.x = p.x + fg; _pos.y = p.y - fg; _pos.h = p.h - 2*fg - f->fFH; _pos.w = p.w - 2*fg; bottom = _pos.y - _pos.h; left = _pos.x; symPerStr = (w - 2*g)/_f->fW; numStrings = (h/2 - g)/(g + _f->fH); /// Buffer char* str = "Test string.\n123\n"; int len = strlen(str); _szBuf = len; memcpy(_buf, str, len); printf("****************char %c\n", 0x30); fillvv(); } void TextArea::appendBuffer(char* p, int len) { if (_szBuf + len + 1 < TA_MAX_BUF) { memcpy(_buf + _szBuf, p, len); _buf[_szBuf + len] = '\n'; _szBuf = _szBuf + len + 1; fillvv(); } else { char* pStart = _buf; char* pEnd = _buf + _szBuf - 1; char* pBufEnd = _buf + TA_MAX_BUF - 1; int free = TA_MAX_BUF - _szBuf; int toCopy = _szBuf - (len + 1 - free); memcpy(pStart, pStart + (len + 1 - free), toCopy); memcpy(pStart + toCopy, p, len); _buf[TA_MAX_BUF-1] = '\n'; _szBuf = TA_MAX_BUF; fillvv(); } }; void TextArea::uv(int i) { int sIndex = convert(_buf[i]); _uv.push_back(_f->symbols[sIndex].uv[0]); _uv.push_back(_f->symbols[sIndex].uv[1]); _uv.push_back(_f->symbols[sIndex].uv[3]); _uv.push_back(_f->symbols[sIndex].uv[2]); } void TextArea::ss(int strNum, int xpos) { GLfloat bottomLine = bottom + fg; GLfloat leftLine = _pos.x; int n2 = strNum; GLfloat b = bottomLine + (fg + n2*_f->fFH + n2*fg); GLfloat t = bottomLine + (fg + (n2+1)*_f->fFH + n2*fg); GLfloat l = leftLine + (fg + xpos*_f->fFW); GLfloat r = leftLine + (fg + (xpos+1)*_f->fFW); _v.push_back({l, b, 0.0f}); _v.push_back({r, b, 0.0f}); _v.push_back({r, t, 0.0f}); _v.push_back({l, t, 0.0f}); } void TextArea::fillvv() { _v.clear(); _uv.clear(); unsigned char* pEnd = _buf + _szBuf - 1; unsigned char* pStart = _buf; int curStr = 0; unsigned char* p = pEnd; while (p >= pStart) { unsigned char* sEnd = p; do { p--; } while ((*p != '\n') && (p >= pStart)); int i = 0; for (unsigned char* tPtr = p + 1; tPtr != sEnd; tPtr++) { ss(curStr, i); uv(tPtr - pStart); i++; } curStr++; } glGenBuffers(1, &_vbo); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, _v.size()*sizeof(vec3), &(_v[0]), GL_DYNAMIC_DRAW); glGenBuffers(1, &_uvbo); glBindBuffer(GL_ARRAY_BUFFER, _uvbo); glBufferData(GL_ARRAY_BUFFER, _uv.size()*sizeof(vec2), &(_uv[0]), GL_DYNAMIC_DRAW); } void TextArea::render(GLuint sp) { GLuint TextureID = glGetUniformLocation(sp, "texSampler"); glActiveTexture(_f->tex); glBindTexture(GL_TEXTURE_2D,_f->tex); glUniform1i(TextureID, 0); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 ); glBindBuffer(GL_ARRAY_BUFFER, _uvbo); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0 ); glDrawArrays(GL_QUADS, 0, _v.size()); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); } TextArea::~TextArea() { //dtor }
/* -*- Mode: c++; tab-width: 4; 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. * * Arjan van Leeuwen (arjanl) */ #include "core/pch.h" #ifdef M2_SUPPORT #include "adjunct/m2/src/backend/imap/commands/MessageSet.h" // Max size of a positive INT32 string #define UINT_STRING_SIZE 10 /*********************************************************************************** ** Constructor ** ** ImapCommands::MessageSet::MessageSet ***********************************************************************************/ ImapCommands::MessageSet::MessageSet(UINT32 start, UINT32 end) : m_count(0) { OP_ASSERT(start == 0 || end == 0 || start <= end); if (start > 0) OpStatus::Ignore(InsertRange(start, end)); }; /*********************************************************************************** ** Get the sequence as a string that conforms to the IMAP spec ** ** ImapCommands::MessageSet::GetString ** @param string Output string ***********************************************************************************/ OP_STATUS ImapCommands::MessageSet::GetString(OpString8& string) { // Length of string: a range is max two positive integers and two characters size_t string_length = (UINT_STRING_SIZE * 2 + 2) * m_ranges.GetCount(); // Reserve the space for the string char* string_ptr = string.Reserve(string_length + 1); RETURN_OOM_IF_NULL(string_ptr); // Create the string for (unsigned i = 0; i < m_ranges.GetCount(); i++) { Range* range = m_ranges.GetByIndex(i); if (range->end == 0) sprintf(string_ptr, "%s%u:*", i != 0 ? "," : "", range->start); else if (range->end == range->start) sprintf(string_ptr, "%s%u", i != 0 ? "," : "", range->start); else sprintf(string_ptr, "%s%u:%u", i != 0 ? "," : "", range->start, range->end); string_ptr += strlen(string_ptr); if (string_ptr - string.CStr() > (ptrdiff_t)string_length) { OP_ASSERT(!"This can't be happening!"); } } return OpStatus::OK; } /*********************************************************************************** ** Add all the message ids in this sequence to vector, won't add if sequence ** contains infinite set ** ** ImapCommands::MessageSet::ToVector ** @param vector Vector to add message ids to ***********************************************************************************/ OP_STATUS ImapCommands::MessageSet::ToVector(OpINT32Vector & vector) const { for (unsigned i = 0; i < m_ranges.GetCount(); i++) { Range* range = m_ranges.GetByIndex(i); if (range->end == 0) return OpStatus::OK; for (unsigned j = range->start; j <= range->end; j++) RETURN_IF_ERROR(vector.Add(j)); } return OpStatus::OK; } /*********************************************************************************** ** Insert range [start .. end] into this sequence ** ** ImapCommands::MessageSet::InsertRange ** ***********************************************************************************/ OP_STATUS ImapCommands::MessageSet::InsertRange(UINT32 start, UINT32 end) { // Check for invalid range if (start == 0 || (end > 0 && start > end)) return OpStatus::ERR; OpAutoPtr<Range> range (OP_NEW(Range, (start, end))); if (!range.get()) return OpStatus::ERR_NO_MEMORY; // Find the nearest range INT32 nearest = m_ranges.FindInsertPosition(range.get()); // Only add the range if extending existing ranges fails if (!Extend(nearest , start, end) && !Extend(nearest - 1, start, end)) { // Couldn't extend existing ranges, insert the range RETURN_IF_ERROR(m_ranges.Insert(range.get())); if (end > 0) m_count += end - start + 1; range.release(); } return OpStatus::OK; } /*********************************************************************************** ** Copy ** ** ImapCommands::MessageSet::Copy ***********************************************************************************/ OP_STATUS ImapCommands::MessageSet::Copy(const MessageSet& copy_from) { for (unsigned i = 0; i < copy_from.m_ranges.GetCount(); i++) { OpAutoPtr<Range> range (OP_NEW(Range, (*copy_from.m_ranges.GetByIndex(i)))); if (!range.get()) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR(m_ranges.Insert(range.get())); range.release(); } m_count += copy_from.Count(); return OpStatus::OK; } /*********************************************************************************** ** Merge with another message set ** ** ImapCommands::MessageSet::Merge ***********************************************************************************/ OP_STATUS ImapCommands::MessageSet::Merge(const MessageSet& merge_from) { for (unsigned i = 0; i < merge_from.m_ranges.GetCount(); i++) { Range* range = merge_from.m_ranges.GetByIndex(i); RETURN_IF_ERROR(InsertRange(range->start, range->end)); } return OpStatus::OK; } /*********************************************************************************** ** Insert a sequence specified as integer vector ** ** ImapCommands::MessageSet::InsertSequence ** @param sequence Sequence to insert into this sequence ***********************************************************************************/ OP_STATUS ImapCommands::MessageSet::InsertSequence(const OpINT32Vector& sequence) { for (UINT32 i = 0; i < sequence.GetCount(); i++) { RETURN_IF_ERROR(InsertRange(sequence.Get(i), sequence.Get(i))); } return OpStatus::OK; } /*********************************************************************************** ** Checks whether this sequence contains a certain id ** ** ImapCommands::MessageSet::Contains ** @param id The ID to check for ** @return Whether this sequence contains id ***********************************************************************************/ BOOL ImapCommands::MessageSet::Contains(UINT32 id) const { // Try to find the closest range Range range(id, id); int index = m_ranges.FindInsertPosition(&range); for (unsigned i = max(0, index - 1); (int)i <= index && i < m_ranges.GetCount(); i++) { Range* found_range = m_ranges.GetByIndex(i); if (id >= found_range->start && (id <= found_range->end || found_range->end == 0)) return TRUE; } return FALSE; } /*********************************************************************************** ** Checks whether this sequence contains all messages ** ** ImapCommands::MessageSet::ContainsAll ***********************************************************************************/ BOOL ImapCommands::MessageSet::ContainsAll() const { // Contains all messages if the only range is 1:0 (1:*) return m_ranges.GetCount() > 0 && m_ranges.GetByIndex(0)->start == 1 && m_ranges.GetByIndex(0)->end == 0; } /*********************************************************************************** ** Split off a number of ids in this sequence and give the remainder ** ** ImapCommands::MessageSet::SplitOff ** @param to_split_off Number of ids to split off ** @param remainder Where to put the remainder after splitting off to_split_off ids ** @return Whether any messages were actually split off ***********************************************************************************/ OP_STATUS ImapCommands::MessageSet::SplitOff(unsigned to_split_off, ImapCommands::MessageSet& remainder) { unsigned count = 0; unsigned index = 0; Range* range = NULL; // Find the range where the split should happen for (; index < m_ranges.GetCount(); index++) { range = m_ranges.GetByIndex(index); // Can't split infinite ranges if (range->end == 0) return OpStatus::OK; // Check if this is the range that should split if (count + 1 + (range->end - range->start) > to_split_off) break; count += range->end + 1 - range->start; } // Check if we found a range to split if (!range) return OpStatus::OK; // Check if the range itself should be split if (to_split_off - count > 0) { // Split the range that we found RETURN_IF_ERROR(remainder.InsertRange(range->start + (to_split_off - count), range->end)); range->end = range->start + (to_split_off - count) - 1; index++; } // Add the remaining ranges ( [index .. m_ranges.GetCount()) ) to the remainder RETURN_IF_ERROR(SplitOffRanges(index, remainder)); m_count = to_split_off; return OpStatus::OK; } /*********************************************************************************** ** Split off a number of ranges in this sequence and give the remainder ** ** ImapCommands::MessageSet::SplitOffRanges ** @param to_split_off Number of ranges to split off ** @param remainder Remainder after splitting off to_split_off ranges ***********************************************************************************/ OP_STATUS ImapCommands::MessageSet::SplitOffRanges(unsigned to_split_off, ImapCommands::MessageSet& remainder) { // Add the remaining ranges ( [to_split_off .. m_ranges.GetCount()) ) to the remainder for (unsigned i = to_split_off; i < m_ranges.GetCount(); i++) { RETURN_IF_ERROR(remainder.InsertRange(m_ranges.GetByIndex(i)->start, m_ranges.GetByIndex(i)->end)); OP_DELETE(m_ranges.GetByIndex(i)); } // Remove the remaining ranges from this set m_ranges.RemoveByIndex(to_split_off, m_ranges.GetCount() - to_split_off); return OpStatus::OK; } /*********************************************************************************** ** Expunge an id from this sequence ** ** ImapCommands::MessageSet::Expunge ** @param id id to expunge ** ***********************************************************************************/ OP_STATUS ImapCommands::MessageSet::Expunge(UINT32 id) { // Remove from relevant ranges Range range(id, id); int bottom = max(0, (int)m_ranges.FindInsertPosition(&range) - 1); for (int i = m_ranges.GetCount() - 1; i >= bottom; i--) { Range* found_range = m_ranges.GetByIndex(i); if (found_range->start <= id && found_range->end >= id) m_count--; // Decrease the start of the range when a server ID is expunged // We don't decrease if start == id, since we'd now want the next element as the start if (found_range->start > id) found_range->start--; // We decrease the end even if it's equal to the id, since we don't want that id anymore // in the range if (found_range->end >= id) { found_range->end--; // If the range is now invalid, remove it if (found_range->end < found_range->start) m_ranges.Delete(found_range); } } return OpStatus::OK; } /*********************************************************************************** ** Extend a range ** ** ImapCommands::MessageSet::Extend ** @param merge Whether to try to merge the extended range with other ranges ** @return Whether the range at index could be extended with [start .. end] ***********************************************************************************/ BOOL ImapCommands::MessageSet::Extend(INT32 index, UINT32 start, UINT32 end, BOOL merge) { if (index < 0 || index >= (int)m_ranges.GetCount()) return FALSE; Range* range = m_ranges.GetByIndex(index); // 'range' is extendable with values in extension if and only if // (range->start - 1 <= end || end == 0) && (start <= range->end + 1 || range->end == 0) if ((range->start - 1 > end && end > 0) || (start > range->end + 1 && range->end > 0)) return FALSE; // We can extend this range. Extend start or end? if (start < range->start) { m_count += range->start - start; range->start = start; if (merge) MergeDown(index); } if (end > range->end && range->end > 0) { m_count += end - range->end; range->end = end; if (merge) MergeUp(index); } return TRUE; } /*********************************************************************************** ** Try to merge ranges down from index ** ** ImapCommands::MessageSet::Merge ***********************************************************************************/ void ImapCommands::MessageSet::MergeDown(INT32 index) { for (INT32 merge_index = index - 1; merge_index >= 0; merge_index--) { // Check if ranges can be merged with the range at 'index' Range* range = m_ranges.GetByIndex(merge_index); if (!Extend(index, range->start, range->end, FALSE)) break; m_count -= range->end - range->start + 1; // Range was merged, remove OP_DELETE(m_ranges.RemoveByIndex(merge_index)); index--; } } /*********************************************************************************** ** Try to merge ranges up from index ** ** ImapCommands::MessageSet::MergeUp ***********************************************************************************/ void ImapCommands::MessageSet::MergeUp(INT32 index) { while (index + 1 < (int)m_ranges.GetCount()) { // Check if ranges can be merged with the range at 'index' Range* range = m_ranges.GetByIndex(index + 1); if (!Extend(index, range->start, range->end, FALSE)) break; m_count -= range->end - range->start + 1; // Range was merged, remove OP_DELETE(m_ranges.RemoveByIndex(index + 1)); } } #endif // M2_SUPPORT
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #include<ctime> using namespace std; int a[10][10]; int main() { srand(time(NULL)); int n = rand()%6 + 3,m = 0; for (int i = 1;i < n; i++) for (int j = i+1;j <= n; j++) { if (rand()%2) { printf("%d %d\n",i,j); m++; } } printf("%d %d\n",n,m); return 0; }
#include <iostream> #include <math.h> using namespace std; int countDigits(int n) { int count_digits = 0; int x = n; while (x) { x = x/10; count_digits++; } return count_digits; } int checkDisarium(int n) { int count_digits = countDigits(n); int sum = 0; int x = n; int rem; while (x!=0) { rem = x%10; sum = sum + pow(rem, count_digits--); x = x/10; } return (sum == n); }
#include "TTH/MEAnalysis/interface/EventShapeVariables.h" namespace { namespace { std::vector<TLorentzVector> _TTHMEAnalysis_i1; } }
#ifndef CABAL_WARNING_H #define CABAL_WARNING_H #include <string> class Warning { private: std::string warning; public: explicit Warning(std::string warning) : warning(std::move(warning)) {}; const std::string getWarning() const { return this->warning; }; }; #endif //CABAL_WARNING_H
/**************************************************************************** ** ** Copyright (C) 2010 Instituto Nokia de Tecnologia (INdT) ** ** This file is part of the Rask Browser project. ** ** This file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact ** the openBossa stream from INdT <renato.chencarek@openbossa.org>. ** ****************************************************************************/ #ifndef PIXMAPITEM_H #define PIXMAPITEM_H #include <QPixmap> #include <QDeclarativeItem> class PixmapItem : public QDeclarativeItem { Q_OBJECT Q_PROPERTY(bool smooth READ smooth WRITE setSmooth NOTIFY smoothChanged); Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap NOTIFY pixmapChanged); public: PixmapItem(QDeclarativeItem *parent = 0); virtual ~PixmapItem(); bool smooth() const; void setSmooth(bool enabled); QPixmap pixmap() const; void setPixmap(const QPixmap &pixmap); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); signals: void smoothChanged(); void pixmapChanged(); private: bool m_smooth; QPixmap m_pixmap; }; QML_DECLARE_TYPE(PixmapItem); #endif
#include <iostream> #include <vector> #include <queue> #include <utility> using namespace std; class Solution { public: vector<vector<int>> getSkyline(vector<vector<int>>& buildings) { if(buildings.empty()){ return buildings; } size_t size = buildings.size(); int cur = 0; int cur_X, cur_H; priority_queue<pair<int, int>> liveBuildings; // pair(H, R) vector<vector<int>> ans; while(cur < size || !liveBuildings.empty()){ cur_X = liveBuildings.empty() ? buildings[cur][0] : liveBuildings.top().second; if(cur < size && (liveBuildings.empty() || cur_X >= buildings[cur][0])){ cur_X = buildings[cur][0]; while(cur < size && cur_X == buildings[cur][0]){ liveBuildings.push(make_pair(buildings[cur][2], buildings[cur][1])); cur++; } }else{ while(!liveBuildings.empty() && liveBuildings.top().second <= cur_X){ liveBuildings.pop(); } } cur_H = liveBuildings.empty() ? 0 : liveBuildings.top().first; if(ans.empty() || cur_H != ans.back()[1]){ ans.push_back(vector<int>({cur_X, cur_H})); } } return ans; } }; int main(void){ return 0; }
#define CATCH_CONFIG_MAIN #include "../catch/catch.hpp" #include <vector> #include <tuple> template <typename T> struct Maybe { Maybe(bool hasValue, T v) : has_value{ hasValue }, value{ v } { } operator bool() const { return has_value; } T& operator *() const { return &value; } private: bool has_value; T value; }; struct GI { uint32_t generation; size_t index; }; template <typename T> struct GIItem { uint32_t generation; bool has_value; T value; }; template <typename T> class GenerationVector { public: GenerationVector() : next{ 0 } { } GI push_back(const T& value) { auto itemsSize = items.size(); while ((next < itemsSize) && items[next].has_value) ++next; if (next >= itemsSize) { next = itemsSize; items.push_back({ 0, false, {} }); } auto& item = items[next]; ++item.generation; item.has_value = true; item.value = value; return { item.generation, next }; } void erase(GI& i) { auto itemsSize = items.size(); if (i.index >= itemsSize) { return; } auto& item = items[i.index]; ++item.generation; item.has_value = false; next = i.index; } Maybe<T*> operator[] (GI& i) { if (i.index >= items.size()) return { false, nullptr }; auto& item = items[i.index]; if(!item.has_value || item.generation != i.generation) return { false, nullptr }; return { true, &item.value }; } Maybe<std::tuple<GI, T*>> operator[] (size_t i) { if (i >= items.size()) return { false, std::make_tuple<GI,T*>({}, nullptr) }; auto& item = items[i]; if (item.has_value) return { false, std::make_tuple<GI,T*>({}, nullptr) }; return { true, std::make_tuple<GI,T*>({item.generation, i}, &item.value) }; } private: std::vector<GIItem<T>> items; size_t next; }; struct PlayerPosition { float x; float y; float z; }; template <typename T> class IsSomeMatcher : public Catch::MatcherBase<Maybe<T>> { public: bool match(Maybe<T> const& m) const override { return m; } virtual std::string describe() const override { std::ostringstream ss; ss << "must have value"; return ss.str(); } }; template <typename T> class IsNoneMatcher : public Catch::MatcherBase<Maybe<T>> { public: bool match(Maybe<T> const& m) const override { return !m; } virtual std::string describe() const override { std::ostringstream ss; ss << "must be empty"; return ss.str(); } }; template <typename T> IsSomeMatcher<T> isSome(Maybe<T> m) { return {}; } template <typename T> IsNoneMatcher<T> isNone(Maybe<T> m) { return {}; } TEST_CASE("Fake.Test.Will Pass", "[ok]") { auto vec = GenerationVector<PlayerPosition>{}; auto i1 = vec.push_back({ 1,0,0 }); vec.push_back({ 2,0,0 }); vec.push_back({ 3,0,0 }); { auto x = vec[i1]; REQUIRE_THAT(x, isSome(x)); } { vec.erase(i1); auto x = vec[i1]; REQUIRE_THAT(x, isNone(x)); } { i1 = vec.push_back({ 1,0,0 }); auto x = vec[i1]; REQUIRE_THAT(x, isSome(x)); } { vec.erase(i1); vec.push_back({ 1,0,0 }); auto x = vec[i1]; REQUIRE_THAT(x, isNone(x)); } { auto i2 = vec.push_back({ 1,0,0 }); auto x1 = vec[i2.index]; REQUIRE_THAT(x1, isNone(x1)); vec.erase(i2); auto x2 = vec[i2.index]; REQUIRE_THAT(x2, isSome(x2)); } }
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDir> #include <QJsonArray> #include <QJsonObject> #include <QFileDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_sender = new QUdpSocket(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_buttonBox_accepted() { QJsonObject srcObject; srcObject.insert("srcExcelPath", ui->srcExcelPath->text()); srcObject.insert("srcSheetName", ui->srcSheet->text()); srcObject.insert("srcColumn1", ui->srcColumn1->text()); srcObject.insert("dstColumn1", ui->dstColumn1->text()); srcObject.insert("strContext", ui->srcModuleIndex->text()); QJsonObject dstObject; dstObject.insert("dstExcelPath", ui->dstExcelPath->text()); dstObject.insert("dstSheetName", ui->dstSheet->text()); dstObject.insert("srcColumn2", ui->srcColumn2->text()); dstObject.insert("dstColumn2", ui->dstColumn2->text()); dstObject.insert("strContext", ui->dstModuleIndex->text()); QJsonObject jsonData; jsonData.insert("srcJson", QJsonValue(srcObject)); jsonData.insert("dstJson", QJsonValue(dstObject)); // 构建 Json 文档 QJsonDocument document; document.setObject(jsonData); QByteArray byteArray = document.toJson(QJsonDocument::Compact); QString strJson(byteArray); qDebug() << strJson; //UDP广播 m_sender->writeDatagram(byteArray.data(),byteArray.size(),QHostAddress::Broadcast,6665); // //向特定IP发送 // QHostAddress serverAddress = QHostAddress("10.21.11.66"); // sender->writeDatagram(datagram.data(), datagram.size(),serverAddress, 6665); } void MainWindow::on_buttonBox_rejected() { } void MainWindow::on_srcBrowserBtn_clicked() { QString strPath = QFileDialog::getOpenFileName(this, tr("Source Excel file"), ".", tr("Excel Files(*.xlsx)")); ui->srcExcelPath->setText(strPath); } void MainWindow::on_dstBrowserBtn_clicked() { QString strPath = QFileDialog::getOpenFileName(this, tr("Dist Excel file"), ".", tr("Excel Files(*.xlsx)")); ui->dstExcelPath->setText(strPath); }
#include <algorithm> #include <csignal> #include <functional> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cm/memory> #include "cm_uv.h" #include "cmGetPipes.h" #include "cmUVHandlePtr.h" #include "cmUVProcessChain.h" #include "cmUVStreambuf.h" struct ExpectedStatus { bool Finished; bool MatchExitStatus; bool MatchTermSignal; cmUVProcessChain::Status Status; }; static const std::vector<ExpectedStatus> status1 = { { false, false, false, { 0, 0 } }, { false, false, false, { 0, 0 } }, { false, false, false, { 0, 0 } }, }; static const std::vector<ExpectedStatus> status2 = { { true, true, true, { 0, 0 } }, { false, false, false, { 0, 0 } }, { false, false, false, { 0, 0 } }, }; static const std::vector<ExpectedStatus> status3 = { { true, true, true, { 0, 0 } }, { true, true, true, { 1, 0 } }, #ifdef _WIN32 { true, true, true, { 2, 0 } }, #else { true, false, true, { 0, SIGABRT } }, #endif }; bool operator==(const cmUVProcessChain::Status* actual, const ExpectedStatus& expected) { if (!expected.Finished) { return !actual; } else if (!actual) { return false; } if (expected.MatchExitStatus && expected.Status.ExitStatus != actual->ExitStatus) { return false; } if (expected.MatchTermSignal && expected.Status.TermSignal != actual->TermSignal) { return false; } return true; } bool resultsMatch(const std::vector<const cmUVProcessChain::Status*>& actual, const std::vector<ExpectedStatus>& expected) { return actual.size() == expected.size() && std::equal(actual.begin(), actual.end(), expected.begin()); } std::string getInput(std::istream& input) { char buffer[1024]; std::ostringstream str; do { input.read(buffer, 1024); str.write(buffer, input.gcount()); } while (input.gcount() > 0); return str.str(); } template <typename T> std::function<std::ostream&(std::ostream&)> printExpected(bool match, const T& value) { return [match, value](std::ostream& stream) -> std::ostream& { if (match) { stream << value; } else { stream << "*"; } return stream; }; } std::ostream& operator<<( std::ostream& stream, const std::function<std::ostream&(std::ostream&)>& func) { return func(stream); } void printResults(const std::vector<const cmUVProcessChain::Status*>& actual, const std::vector<ExpectedStatus>& expected) { std::cout << "Expected: " << std::endl; for (auto const& e : expected) { if (e.Finished) { std::cout << " ExitStatus: " << printExpected(e.MatchExitStatus, e.Status.ExitStatus) << ", TermSignal: " << printExpected(e.MatchTermSignal, e.Status.TermSignal) << std::endl; } else { std::cout << " null" << std::endl; } } std::cout << "Actual:" << std::endl; for (auto const& a : actual) { if (a) { std::cout << " ExitStatus: " << a->ExitStatus << ", TermSignal: " << a->TermSignal << std::endl; } else { std::cout << " null" << std::endl; } } } bool checkExecution(cmUVProcessChainBuilder& builder, std::unique_ptr<cmUVProcessChain>& chain) { std::vector<const cmUVProcessChain::Status*> status; chain = cm::make_unique<cmUVProcessChain>(builder.Start()); if (!chain->Valid()) { std::cout << "Valid() returned false, should be true" << std::endl; return false; } status = chain->GetStatus(); if (!resultsMatch(status, status1)) { std::cout << "GetStatus() did not produce expected output" << std::endl; printResults(status, status1); return false; } if (chain->Wait(6000)) { std::cout << "Wait() returned true, should be false" << std::endl; return false; } status = chain->GetStatus(); if (!resultsMatch(status, status2)) { std::cout << "GetStatus() did not produce expected output" << std::endl; printResults(status, status2); return false; } if (!chain->Wait()) { std::cout << "Wait() returned false, should be true" << std::endl; return false; } status = chain->GetStatus(); if (!resultsMatch(status, status3)) { std::cout << "GetStatus() did not produce expected output" << std::endl; printResults(status, status3); return false; } return true; } bool checkOutput(std::istream& outputStream, std::istream& errorStream) { std::string output = getInput(outputStream); if (output != "HELO WRD!") { std::cout << "Output was \"" << output << "\", expected \"HELO WRD!\"" << std::endl; return false; } std::string error = getInput(errorStream); if (error.length() != 3 || error.find('1') == std::string::npos || error.find('2') == std::string::npos || error.find('3') == std::string::npos) { std::cout << "Error was \"" << error << "\", expected \"123\"" << std::endl; return false; } return true; } bool testUVProcessChainBuiltin(const char* helperCommand) { cmUVProcessChainBuilder builder; std::unique_ptr<cmUVProcessChain> chain; builder.AddCommand({ helperCommand, "echo" }) .AddCommand({ helperCommand, "capitalize" }) .AddCommand({ helperCommand, "dedup" }) .SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT) .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR); if (!checkExecution(builder, chain)) { return false; } if (!chain->OutputStream()) { std::cout << "OutputStream() was null, expecting not null" << std::endl; return false; } if (!chain->ErrorStream()) { std::cout << "ErrorStream() was null, expecting not null" << std::endl; return false; } if (!checkOutput(*chain->OutputStream(), *chain->ErrorStream())) { return false; } return true; } bool testUVProcessChainExternal(const char* helperCommand) { cmUVProcessChainBuilder builder; std::unique_ptr<cmUVProcessChain> chain; int outputPipe[2], errorPipe[2]; cm::uv_pipe_ptr outputInPipe, outputOutPipe, errorInPipe, errorOutPipe; if (cmGetPipes(outputPipe) < 0) { std::cout << "Error creating pipes" << std::endl; return false; } if (cmGetPipes(errorPipe) < 0) { std::cout << "Error creating pipes" << std::endl; return false; } builder.AddCommand({ helperCommand, "echo" }) .AddCommand({ helperCommand, "capitalize" }) .AddCommand({ helperCommand, "dedup" }) .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT, outputPipe[1]) .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR, errorPipe[1]); if (!checkExecution(builder, chain)) { return false; } if (chain->OutputStream()) { std::cout << "OutputStream() was not null, expecting null" << std::endl; return false; } if (chain->ErrorStream()) { std::cout << "ErrorStream() was not null, expecting null" << std::endl; return false; } outputOutPipe.init(chain->GetLoop(), 0); uv_pipe_open(outputOutPipe, outputPipe[1]); outputOutPipe.reset(); errorOutPipe.init(chain->GetLoop(), 0); uv_pipe_open(errorOutPipe, errorPipe[1]); errorOutPipe.reset(); outputInPipe.init(chain->GetLoop(), 0); uv_pipe_open(outputInPipe, outputPipe[0]); cmUVStreambuf outputBuf; outputBuf.open(outputInPipe); std::istream outputStream(&outputBuf); errorInPipe.init(chain->GetLoop(), 0); uv_pipe_open(errorInPipe, errorPipe[0]); cmUVStreambuf errorBuf; errorBuf.open(errorInPipe); std::istream errorStream(&errorBuf); if (!checkOutput(outputStream, errorStream)) { return false; } return true; } bool testUVProcessChainNone(const char* helperCommand) { cmUVProcessChainBuilder builder; std::unique_ptr<cmUVProcessChain> chain; builder.AddCommand({ helperCommand, "echo" }) .AddCommand({ helperCommand, "capitalize" }) .AddCommand({ helperCommand, "dedup" }); if (!checkExecution(builder, chain)) { return false; } if (chain->OutputStream()) { std::cout << "OutputStream() was not null, expecting null" << std::endl; return false; } if (chain->ErrorStream()) { std::cout << "ErrorStream() was not null, expecting null" << std::endl; return false; } return true; } int testUVProcessChain(int argc, char** const argv) { if (argc < 2) { std::cout << "Invalid arguments.\n"; return -1; } if (!testUVProcessChainBuiltin(argv[1])) { std::cout << "While executing testUVProcessChainBuiltin().\n"; return -1; } if (!testUVProcessChainExternal(argv[1])) { std::cout << "While executing testUVProcessChainExternal().\n"; return -1; } if (!testUVProcessChainNone(argv[1])) { std::cout << "While executing testUVProcessChainNone().\n"; return -1; } return 0; }
#include <iostream> #include <fstream> #include "VirtualMachine.h" /*constructor*/ VirtualMachine::VirtualMachine(string cfg_fp,string * pfiles,int pcount,int iterations){ //initialize performance array performance = new double[pcount]; for(int i =0;i<pcount;i++){ //loop through all the iterations char in[256]; int lc = 0; ifstream prog_fp; //open up the file prog_fp.open(pfiles[i].c_str(),ifstream::in); //count lines that are not commented (don't begin with #) while(prog_fp.getline(in,256)){ if(in[0] != '#'){ lc++; } } //rewind config file prog_fp.clear(); prog_fp.seekg(0,ios::beg); //allocate program space string * program = new string[lc]; //load the program lc=0; while(prog_fp.getline(in,256)){ if(in[0] != '#'){ //trimming string s = in; s=s.substr(0,s.find_last_not_of(' ')+1); program[lc]=s; lc++; } } //cleanup prog_fp.close(); //create thread double average = 0; double single_run; //run through according to #of iterations for(int i=0;i<iterations;i++){ //create a parser and initialize it //sum the total of %completes Parser p(program,lc,cfg_fp); single_run = p.parse(); average += single_run; cout << "run: " << i << " compeleted " << single_run <<"%\n"; } //complete the average calculation average = average / iterations; cout << "average performance: " << average << "%\n"; } } /*destructor*/ VirtualMachine::~VirtualMachine(){ delete[] performance; } int main(int argc, char**argv){ if(argc < 2){ cout << "Needs # of iterations\n"; return 0; } else{ string * pfiles = new string[1]; pfiles[0] = string("first_try.mss"); VirtualMachine vm("actions.cfg",pfiles,1,atoi(argv[1])); } }
// // Pantalla.cpp // Tarea4Ejercicio4 // // Created by Daniel on 18/10/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #include "Pantalla.h" bool Pantalla::curses_ON = false; void Pantalla::print(ListaDoblementeEnlazada<ListaDoblementeEnlazada<char> *> *texto){ std::cout<<"------------- Editor de Texto ------------\n"; for (int i = 0; i < texto->size(); ++i){ std::cout<<*(texto->At(i)->getInfo()); std::cout<<std::endl; } } void Pantalla::printMenu(){ std::cout<<"------------- Editor de Texto ------------\n"; std::cout<<"Menu: "<<std::endl; std::cout<<"Para abrir el menu de ocpiones una vez ingresado al editor presione ESC"<<std::endl; std::cout<<"1) Nuevo Documento\n2) Abrir Documento\n0) Salir"<<std::endl; } void Pantalla::printOpciones(){ std::cout<<"Opciones:\n1) Salvar el documento\n2) Cerrar documento\n"; } ListaDoblementeEnlazada<ListaDoblementeEnlazada<char> *> * Pantalla::editor(ListaDoblementeEnlazada<ListaDoblementeEnlazada<char> *> * texto){ int row, col; row = 0; col = 0; bool activo = true; if(texto->size() == 1 && texto->At(0)->getInfo()->size() == 0){ row = 0; col = 0; } else{ row = texto->size() -1; col = texto->At(row-1)->getInfo()->size(); } startCurses(); for (int i = 0; i< texto->size(); ++i){ for (int j = 0; j < texto->At(i)->getInfo()->size(); ++j){ addch(texto->At(i)->getInfo()->At(j)->getInfo()); } addch('\n'); } move(row, col); while (activo) { // getyx(stdscr, row, col); int ch = getch(); switch (ch) { case ESC: activo = false; break; case '\n': addch(ch); texto->insertAt(nuevaLinea(texto->At(row)->getInfo(), col), row+1); clear(); return editor(texto); break; case BACKSPACE: if (col > 0) { texto->At(row)->getInfo()->deleteAt(col-1); col--; move(row, col); for (int i = col; i < texto->At(row)->getInfo()->size(); ++i){ addch(texto->At(row)->getInfo()->At(i)->getInfo()); } addch(' '); move(row, col); } else{ for (int j = 0; j < texto->At(row)->getInfo()->size(); ++j) { texto->At(row-1)->getInfo()->insertBack(texto->At(row)->getInfo()->deleteAt(j)->getInfo()); } texto->deleteAt(row); return editor(texto); } break; case LEFT: if (col >0) { col--; move(row, col); } break; case RIGHT: if(col < texto->At(row)->getInfo()->size()){ col++; move(row, col); } break; case UP: if (row > 0) { row--; move(row, col); } break; case DOWN: if(row < texto->size()-1){ row++; move(row, col); } break; default: addch(ch); texto->At(row)->getInfo()->insertAt(ch, col); col++; break; } } endCurses(); return texto; } void Pantalla::endCurses(){ if (curses_ON && !isendwin()) clear(); endwin(); } void Pantalla::startCurses(){ if (curses_ON) { refresh(); } else { initscr(); cbreak(); noecho(); intrflush(stdscr, false); keypad(stdscr, true); atexit(endCurses); curses_ON = true; } } ListaDoblementeEnlazada<char> * Pantalla::nuevaLinea(ListaDoblementeEnlazada<char> * vieja, int c){ ListaDoblementeEnlazada<char> * nueva = new ListaDoblementeEnlazada<char>; if(c != vieja->size()){ for (int i = c-1; i < vieja->size(); ++i) { nueva->insertBack(vieja->deleteAt(c)->getInfo()); } } return nueva; }
#ifndef STARTDIALOG_H #define STARTDIALOG_H #include "gamewindow.hh" #include <QDialog> namespace Ui { class startDialog; } class startDialog : public QDialog { Q_OBJECT public: explicit startDialog(QWidget *parent = 0); ~startDialog(); int numberOfPawns; public slots: // void startGameWindow(); private slots: void on_exitButton_clicked(); void on_startButton_clicked(); private: Ui::startDialog *ui; gameWindow *newGameWindow; }; #endif // STARTDIALOG_H
/**************************************************************************** ** ** Copyright (C) 2010 Instituto Nokia de Tecnologia (INdT) ** ** This file is part of the Rask Browser project. ** ** This file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact ** the openBossa stream from INdT <renato.chencarek@openbossa.org>. ** ****************************************************************************/ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QDeclarativeItem> #include <QDeclarativeView> class MainWindow : public QDeclarativeView { Q_OBJECT public: MainWindow(); protected: void setupWebSettings(); void resizeEvent(QResizeEvent * event); private: QDeclarativeItem *rootItem; }; #endif
#ifndef _MSG_0X17_SPAWNOBJECT_STC_H_ #define _MSG_0X17_SPAWNOBJECT_STC_H_ #include "mcprotocol_base.h" #include "objectdata.h" namespace MC { namespace Protocol { namespace Msg { class SpawnObject : public BaseMessage { public: SpawnObject(); SpawnObject(int32_t _entityId, int8_t _type, int32_t _x, int32_t _y, int32_t _z, int8_t _pitch, int8_t _yaw); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); int32_t getEntityId() const; int8_t getType() const; int32_t getX() const; int32_t getY() const; int32_t getZ() const; int8_t getPitch() const; int8_t getYaw() const; void setEntityId(int32_t _val); void setType(int8_t _val); void setX(int32_t _val); void setY(int32_t _val); void setZ(int32_t _val); void setPitch(int8_t _val); void setYaw(int8_t _val); private: int32_t _pf_entityId; int8_t _pf_type; int32_t _pf_x; int32_t _pf_y; int32_t _pf_z; int8_t _pf_pitch; int8_t _pf_yaw; ObjectData _pf_objectData; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0X17_SPAWNOBJECT_STC_H_
/* * * * * * search.cxx * Search function ** MiniMax + Alpha Beta Pruning * White selects highest scoring moves * Black selects lowest scoring moves * Alpha is the minimum score accepted by white parent nodes * Beta is the maximum score accepted by black parent nodes * When Beta is less than Alpha no new nodes examined will be accepted by * parent nodes and search terminates on that node * ** Search Function * The search function is a special case of MiniMax that keeps track of * which possible move scores the highest * */ #include "search.hxx" #include "movegen.hxx" #include "eval.hxx" signed int MiniMax( Position& pos, bool IsMaximiser, signed int alpha = NEG_INFINITE, signed int beta = INFINITE, int depth = 0 ) { int moves = 0; signed int eval, best; MoveNode* movelist = GenMoves( pos ); MoveNode* p = movelist; Position testpos = pos; while( p != NULL ) { p = p->nxt; moves++; } if( ( depth == 0 ) || ( moves == 0 ) ) { DeleteMoveList( movelist ); return Evaluate( pos ); } p = movelist; if( IsMaximiser ) { best = NEG_INFINITE; while( ( beta > alpha ) && ( moves > 0 ) ) { MakeMove( testpos, p->move ); eval = MiniMax( testpos, false, alpha, beta, depth - 1 ); if( eval > best ) { best = eval; if( eval > alpha ) alpha = eval; } p = p->nxt; moves--; testpos = pos; } } else { best = INFINITE; while( ( beta > alpha ) && ( moves > 0 ) ) { MakeMove( testpos, p->move ); eval = MiniMax( testpos, true, alpha, beta, depth - 1 ); if( eval < best ) { best = eval; if( eval < beta ) beta = eval; } p = p->nxt; moves--; testpos = pos; } } DeleteMoveList( movelist ); return best; } MoveRep Search( Position& pos, int depth ) { MoveNode* movelist = GenMoves( pos ); MoveNode* bestmove; MoveNode* p; int moves = 0; signed int eval, best; signed int alpha = NEG_INFINITE; signed int beta = INFINITE; Position testpos = pos; MoveRep ret; p = movelist; if( movelist == NULL ) { return 0x0000; } while( p != NULL ) { p = p->nxt; moves++; } p = movelist; if( pos.flags & WHITE_TO_MOVE ) { best = alpha; while( ( beta > alpha ) && ( moves > 0 ) ) { MakeMove( testpos, p->move ); eval = MiniMax( testpos, false, alpha, beta, depth - 1 ); if( eval > best ) { best = eval; bestmove = p; if( eval > alpha ) alpha = eval; } p = p->nxt; moves--; testpos = pos; } } else { best = beta; while( ( beta > alpha ) && ( moves > 0 ) ) { MakeMove( testpos, p->move ); eval = MiniMax( testpos, true, alpha, beta, depth - 1 ); if( eval < best ) { best = eval; bestmove = p; if( eval < beta ) beta = eval; } p = p->nxt; moves--; testpos = pos; } } ret = bestmove->move; DeleteMoveList( movelist ); return ret; }