text
stringlengths
8
6.88M
#include <stdio.h> #include <string> #include <stdlib.h> #include <iostream> using namespace std; int k; string array[15]; string save[1<<16]; string merge(string a,string b) { int sa = a.size(); int sb = b.size(); int check; int check2=1; for(int i=0;i<sa;i++) { if(a[i]==b[0]) { check=0; int j; for(j=i+1;j<sa;j++) { if(j-i>=sb) break; if(a[j]!=b[j-i]) { check=1; } } if(check==0) { check2=0; b=b.substr(j-i); a = a+b; } } } if(check2==1) { a = a+b; } return a; } int min(int a,int b) { if(a<b) return a; else return b; } string func(string input,int bit) { string tempstr; string result; int temp; int max=9999999; int check=0; if(save[bit]!="-") return save[bit]; for(int i=0;i<k;i++) { if((bit&(1<<i))==0) check=1; } if(check==0) { return input; } for(int i=0;i<k;i++) { if((bit&(1<<i))==0) { tempstr = func(merge(input,array[i]),bit|(1<<i)); temp = tempstr.size(); if(temp<max) { max = temp; result = tempstr; } } } save[bit]=result; return result; } int main() { int c; scanf("%d",&c); while(c--) { scanf("%d",&k); for(int i=0;i<k;i++) { cin>>array[i]; } for(int i=0;i<(1<<16);i++) { save[i]="-"; } cout << func("",0)+"\n"; } }
/*! *@FileName: KaiXinApp_UserInfoDetail.h *@Author: pengzhixiong@GoZone *@Date: 2010-10-7 *@Log: Author Date Description * *@section Copyright * =======================================================================<br> * Copyright ? 2010-2012 GOZONE <br> * All Rights Reserved.<br> * The file is generated by Kaixin_Component Wizard for Tranzda Mobile Platform <br> * =======================================================================<br> */ #ifndef __KAIXINAPI_USERINFODETAIL_H__ #define __KAIXINAPI_USERINFODETAIL_H__ #include "KaiXinAPI.h" class TUserInfoDetailForm : public TWindow { public: TUserInfoDetailForm(TApplication* pApp); virtual ~TUserInfoDetailForm(void); virtual Boolean EventHandler(TApplication * appP, EventType * eventP); private: Boolean _OnWinInitEvent(TApplication * pApp, EventType * pEvent); Boolean _OnWinClose(TApplication * pApp, EventType * pEvent); Boolean _OnCtrlSelectEvent(TApplication * pApp, EventType * pEvent); void _SetDataToCtrls(TApplication* pApp); Int32 _SetCoolBarList(TApplication* pApp); private: tResponseGetUserInfos* Response; //Óû§Í¼±ê TBitmap* pPhotoBmp; Int32 m_BackBtn; }; #endif
// ============================================================================= // Copyright 2012. // Scott Alexander Holm. // All Rights Reserved. // ============================================================================= #ifndef PLAY_H #define PLAY_H #include "player.h" #include "card.h" #include "constants.h" // Crib play class Play { protected: // array of cards thus played. Card played[8]; // index into play array short int played_index; // a players go bool go[2]; // whos turn it is bool turn; // players of the game Player *p[2]; // the running count short unsigned int count; // the state of points after the last card was played bool fifteen; bool thirtyone; bool quadruple; bool triple; bool pair; short unsigned int run; bool last; // points earned from last play short unsigned int earned; public: //Play (void); Play (void); Play (Player *contestant[], bool dealer); Play (Player *contestant[], short unsigned int new_count, Card *new_played, short int new_played_index); // reset the gos and count and played card array void resetPlay(void); // nuke the scored states void resetScored(void); // return any points earned by discard virtual short unsigned int playCard (Card discard); // the state of points after the last card was played bool fifteenScored(void); bool thirtyoneScored(void); bool quadrupleScored(void); bool tripleScored(void); bool pairScored(void); short unsigned int runScored(void); bool lastScored(void); // the points earned from the last play short unsigned int pointsEarned (void); // get the running count short unsigned int getCount (void); // set the running count void setCount (short unsigned int new_count); // get the last discarded Card getDiscard(); // deal with the go bool isGo(); void setGo(short unsigned int turn); // true when both players have said 'go' bool countReached(void); // true when one player has said go and the other hasn't but doesn't have // any cards that can be played bool isLast(void); // set the 'last' variable to true bool setLast(void); // return play when both players are out of cards bool playOver(void); // announce any points gained during play virtual void announcePlay(void); // make it the next players turn void endTurn(void); // get who's turn it is bool getTurn(void); // play up to 31 or we run out of cards bool playSet(void); // play as many times as we can up to 31 or we run out of cards virtual bool playAllSets(void); // The main routine //bool play(Player *p[]); // get the seed value from the current players points values virtual short unsigned int getCurrentPlayerPointsSeed(void); virtual short unsigned int getOpponentPlayerPointsSeed(void); }; #endif
#include <queue> #include "log.h" #include "statemachine.h" #include "utils.h" using namespace std; pthread_mutex_t CStateMachine::sm_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t CStateMachine::event_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t CStateMachine::event_mutex_cond = PTHREAD_COND_INITIALIZER; //! \brief Initialize this singleton object. This has to be called once only. CStateMachine* CStateMachine::Initialize() { if ( !pInstance ) { pInstance = new CStateMachine; // pthread_mutex_init( &sm_mutex, NULL ); // pthread_mutex_init( &event_mutex, NULL ); // pthread_cond_init( &event_mutex_cond, NULL); } return pInstance; } //! \brief Intialize the states of the state machibe. This should be called once only. void CStateMachine::InitializeStates() { cState[ STARTUP ] = new CStartup; cState[ PRE_MAINTENANCE ] = new CPreMaintenance; cState[ MAINTENANCE ] = new CMaintenance; cState[ PRE_STANDBY ] = new CPreStandby; cState[ STANDBY ] = new CStandby; cState[ PRE_ACTIVE ] = new CPreActive; cState[ ACTIVE ] = new CActive; m_current_state = STARTUP; m_current_event = NONE; m_previous_state = STARTUP; m_previous_event = NONE; m_ssh_keys_generated = false; } //! \brief Set the application paramters. This will allow this object to access the CParam object. //void CStateMachine::SetParameters(const CParams param) //{ // cp = param; //} //! \brief Returns the current state of the state machine object. DR_STATES CStateMachine::CurrentState( DR_STATES curstate ) { pthread_mutex_lock ( &sm_mutex ); m_current_state = curstate; pthread_mutex_unlock ( &sm_mutex ); return m_current_state; } //! \brief Returns the current event of the state machine object. void CStateMachine::CurrentEvent( DR_EVENTS curevent ) { m_current_event = curevent; } //! \brief Returns the current event of the state machine object. void CStateMachine::PreviousEvent( DR_EVENTS prevevent ) { m_previous_event = prevevent; } //! \brief This is the main function that will process all the events. //! Events will be read from an event queue. void CStateMachine::ProcessEvents() { //m_current_state = STARTUP; if ( m_current_state != m_previous_state ) m_previous_state = m_current_state; if ( m_current_event != m_previous_event ){ if ( m_current_event != NONE ) m_previous_event = m_current_event; } //else printf("Current State: %s, CurrentEvent: %s\n", CurrentStateStr(), CurrentEventStr() ); LogInfo("Current State: %s, CurrentEvent: %s\n", CurrentStateStr(), CurrentEventStr() ); switch( m_current_state ) { case STARTUP: break; case PRE_MAINTENANCE: break; case MAINTENANCE: break; case PRE_STANDBY: break; case STANDBY: break; case PRE_ACTIVE: break; case ACTIVE: break; } // Run the Handler on the current state cState[ m_current_state ]->Handler( m_current_event ); if ( m_previous_state != m_current_state ) { UpdateLocalStatus( m_current_state ); } } //! \brief Get and instance of CStateMachine object. Note: CStateMachine::Initialize() must be called before using this function. CStateMachine* CStateMachine::GetInstance() { return pInstance; } //! \brief Returns the string value of the current state. This is an overloaded function. If 'previous' is set to true, //! then this function will the return the previous state rather than the current. Note: 'previous' is set to false by default. const char* CStateMachine::CurrentStateStr( const bool previous ) { return StateStr( previous ? m_previous_state : m_current_state ); } //! \brief Returns the string value of the current event. This is an overloaded function. If 'previous' is set to true, //! then this function will the return the previous event rather than the current. Note: 'previous' is set to false by default. const char* CStateMachine::CurrentEventStr( const bool previous ) { return EventStr( previous ? m_previous_event : m_current_event ); } //! \brief Returns the string value of the previous state. const char* CStateMachine::PreviousStateStr() { return CurrentStateStr( true ); } //! \brief Returns the string value of the previous event. const char* CStateMachine::PreviousEventStr() { return CurrentEventStr( true ); } //! \brief Return a string represting the event const char* CStateMachine::EventStr( DR_EVENTS ev ) { const char *str; switch( ev ) { case MAINT: str = "MAINT"; break; case MAINT_END: str = "MAINT_END"; break; case MATCH_PUBIP: str = "MATCH_PUBIP"; break; case NO_MATCH_PUBIP: str = "NO_MATCH_PUBIP"; break; case C_PUBIP: str = "C_PUBIP"; break; case NO_DNS: str = "NO_DNS"; break; case REPL_OK: str = "REPL_OK"; break; case REPL_FAIL: str = "REPL_FAIL"; break; case REPL_STOP: str = "REPL_STOP"; break; case PUBKEY_OK: str = "PUBKEY_OK"; break; case ACTIVE_READY: str = "ACTIVE_READY"; break; case NONE: str = "NONE"; break; default: str = "UNKNOWN"; } return str; } //! \brief Return a string represting the state const char* CStateMachine::StateStr( DR_STATES state ) { const char *str; switch( state ) { case STARTUP: str = "STARTUP"; break; case PRE_MAINTENANCE: str = "PRE_MAINTENANCE"; break; case MAINTENANCE: str = "MAINTENANCE"; break; case PRE_STANDBY: str = "PRE_STANDBY"; break; case STANDBY: str = "STANDBY"; break; case PRE_ACTIVE: str = "PRE_ACTIVE"; break; case ACTIVE: str = "ACTIVE"; break; default: str = "UNKNOWN"; } return str; } //! \brief Process the events received from the event queue. int CStateMachine::EventHandler() { DR_EVENTS event; while(1){ printf("waiting for event...\n"); pthread_mutex_lock ( &event_mutex ); while( event_queue.empty() ) pthread_cond_wait( &event_mutex_cond, &event_mutex); if ( event_queue.empty() ) { printf("Q is empty...\n"); pthread_mutex_unlock ( &event_mutex ); continue; } event = event_queue.front(); event_queue.pop(); pthread_mutex_unlock ( &event_mutex ); printf("Event: %s\n", EventStr( event )); CurrentEvent( event ); ProcessEvents(); } return 1; } //! \brief Push DR Events to Queue. Note: this can be called from multiple thread. void CStateMachine::PushEventToQueue(DR_EVENTS ev) { pthread_mutex_lock( &event_mutex ); event_queue.push( ev ); pthread_cond_signal( &event_mutex_cond ); pthread_mutex_unlock( &event_mutex ); } bool CStateMachine::UpdateLocalStatus( DR_STATES drstate ) { FILE *fp; LogInfo("Updating status to [%s]\n", StateStr( drstate ) ); if ( !lockfile(DR_STATUS_LOCK, 3 )) { // try to acquire lock and set timeout to 3 seconds. /// timeout occur.. LogError("Unable to acquire lock on DR_STATUS_LOCK!"); return false; } if ( (fp = fopen(DR_STATUS, "w")) == NULL ) { LogError("failed to update %s", DR_STATUS); return false; } fprintf(fp, "DR_STATE=%s\n", StateStr( drstate ) ); fflush(fp); fclose(fp); if ( !unlockfile(DR_STATUS_LOCK ) ) { // try to acquire lock and set timeout to 3 seconds. LogError("failed to unlock DR_STATUS_LOCK!"); return false; } return true; } void CStateMachine::SSHKeyGenerated( bool tf ) { m_ssh_keys_generated = tf; }
/* blah_test.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 30 Mar 2014 FreeBSD-style copyright and disclaimer apply Blah */ #define REFLECT_USE_EXCEPTIONS 1 #include "reflect.h" #include "dsl/all.h" #include "types/primitives.h" #include "types/std/string.h" #include <iostream> using namespace reflect; struct Bar {}; struct Foo { operator Bar() const { return Bar(); } }; struct Baz : public Bar {}; void value(Bar) {} void lRef(Bar&) {} void constLRef(const Bar&) {} void rRef(Bar&&) {} Foo g; Foo retValue() { return {}; } Foo& retLRef() { return g; } const Foo& retConstLRef() { return g; } struct NoCons { NoCons(const NoCons&) = default; NoCons& operator=(const NoCons&) = default; NoCons(NoCons&&) = default; NoCons& operator=(NoCons&&) = default; NoCons() = delete; }; struct NoCopy { NoCopy() = default; NoCopy(NoCopy&&) = default; NoCopy& operator=(NoCopy&&) = default; NoCopy(const NoCopy&) = delete; NoCopy& operator=(const NoCopy&) = delete; }; struct NoMove { NoMove() = default; NoMove(const NoMove&) = default; NoMove& operator=(const NoMove&) = default; NoMove(NoMove&&) = delete; NoMove& operator=(NoMove&&) = delete; }; template<typename T> void bleh() { std::cerr << "def cons: " << std::is_default_constructible<T>() << std::endl; std::cerr << "copy cons: " << std::is_copy_constructible<T>() << std::endl; std::cerr << "copy assg: " << std::is_copy_assignable<T>() << std::endl; std::cerr << "move cons: " << std::is_move_constructible<T>() << std::endl; std::cerr << "move assg: " << std::is_move_assignable<T>() << std::endl; } void ptr(int const*) {} struct Foo2 { int bar(int a, int b) const { return a + b; } int baz; }; reflectType(Foo2) { reflectPlumbing(); reflectField(baz); reflectFn(bar); } int main(int, char**) { std::cerr << type("Foo2")->print() << std::endl; std::cerr << type("Foo2")->call<std::string>("baz_desc") << std::endl; printf("\ncopy:\n"); bleh<typename CleanType<int>::type>(); printf("\nlref:\n"); bleh<typename CleanType<int&>::type>(); printf("\ncref:\n"); bleh<typename CleanType<const int&>::type>(); printf("\nrref:\n"); bleh<typename CleanType<int&&>::type>(); std::cerr << std::endl; std::cerr << "copy: " << std::is_pointer<int*>::value << std::endl; std::cerr << "lref: " << std::is_pointer<int*&>::value << std::endl; std::cerr << "rref: " << std::is_pointer<int*&&>::value << std::endl; std::cerr << "cref: " << std::is_pointer<int* const &>::value << std::endl; std::cerr << std::endl; { Baz baz; constLRef(baz); } { Foo foo; value(foo); // lRef(foo); constLRef(foo); rRef(foo); } { const Foo foo; value(foo); // lRef(foo); constLRef(foo); rRef(foo); } { value(Foo()); // lRef(Foo()); constLRef(Foo()); rRef(Foo()); } { (Bar) retValue(); const Bar& bar = retLRef(); (void) bar; (const Bar&) retConstLRef(); } }
/* * Copyright 2017 Roman Katuntsev <sbkarr@stappler.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EXEC_SEXPR_H_ #define EXEC_SEXPR_H_ #include "wasm/Utils.h" namespace sexpr { using StringView = wasm::StringView; template <typename T> using Vector = wasm::Vector<T>; struct Token { enum Kind { Word, List }; Token() = default; explicit Token(StringView t) : kind(Word), token(t) { } explicit Token(Kind k) : kind(k) { } Kind kind = Word; StringView token; Vector<Token> vec; }; Vector<Token> parse(StringView); void print(std::ostream &, const Token &); void print(std::ostream &, const Vector<Token> &); } #endif /* EXEC_SEXPR_H_ */
#include<bits/stdc++.h> using namespace std; int n; long long aux,lst; set<long long>s; int main(){ cin >> n; for(int i=0;i<n;i++){ cin >> aux; s.insert(aux); } while(1){ set<long long>::iterator it=s.end(); it--; aux=*it; if(aux==1) break; lst=aux/2; while(s.find(lst)!=s.end()&&lst>1) lst/=2; if(s.find(lst)!=s.end()) break; s.erase(it); s.insert(lst); } for(set<long long>::iterator it=s.begin();it!=s.end();it++) cout << (*it) <<" "; cout << endl; }
class Solution { public: void moveZeroes(vector<int>& nums) { int numbersOfZeros = 0; int tmpIndex = 0; int n = nums.size(); int i = 0; for(; i < n; i++) { if(nums[i] == 0) { numbersOfZeros++; continue; } else { nums[tmpIndex] = nums[i]; tmpIndex++; } } for(i = n - numbersOfZeros; i < n; i++) nums[i] = 0; } };
#pragma once #include "Mesh.h" class Model { public: std::vector<Mesh> meshes; Model(std::vector<Mesh> meshes); };
/* * Copyright (C) 2007-2015 Frank Mertens. * * Use of this source is governed by a BSD-style license that can be * found in the LICENSE file. * */ #include <flux/Format> #include <flux/meta/YasonWriter> namespace flux { namespace meta { Ref<YasonWriter> YasonWriter::create(Format format, String indent) { return new YasonWriter(format, indent); } YasonWriter::YasonWriter(Format format, String indent): format_(format), indent_(indent) {} void YasonWriter::write(Variant value) { writeValue(value, 0); format_ << nl; } void YasonWriter::writeValue(Variant value, int depth) { if ( type(value) == Variant::IntType || type(value) == Variant::BoolType || type(value) == Variant::FloatType ) { format_ << value; } else if (type(value) == Variant::StringType) { String s = value; if (s->contains("\"")) s = s->replace("\"", "\\\""); s = s->escape(); format_ << "\"" << s << "\""; } else if (type(value) == Variant::ListType) { writeList(value, depth); } else if (type(value) == Variant::ObjectType) { writeObject(value, depth); } } void YasonWriter::writeList(Variant value, int depth) { if (itemType(value) == Variant::IntType) writeTypedList<int>(value, depth); else if (itemType(value) == Variant::BoolType) writeTypedList<bool>(value, depth); else if (itemType(value) == Variant::FloatType) writeTypedList<float>(value, depth); else if (itemType(value) == Variant::StringType) writeTypedList<String>(value, depth); else writeTypedList<Variant>(value, depth); } bool YasonWriter::isIdentifier(String name) const { for (int i = 0, n = name->count(); i < n; ++i) { char ch = name->at(i); if (!( (('a' <= ch) && (ch <= 'z')) || (('A' <= ch) && (ch <= 'Z')) || (ch == '_') || (ch == '-') || (('0' <= ch) && (ch <= '9')) )) return false; } return true; } void YasonWriter::writeObject(Variant value, int depth) { Ref<MetaObject> object = cast<MetaObject>(value); if (!object) { format_ << "null"; return; } if (object->className() != "") { format_ << object->className(); format_ << " "; } if (object->count() == 0 && !object->hasChildren()) { format_ << "{}"; return; } format_ << "{\n"; writeIndent(depth + 1); // FIXME: having an "IndentStream" would be nice for (int i = 0; i < object->count(); ++i) { String memberName = object->keyAt(i); Variant memberValue = object->valueAt(i); if (isIdentifier(memberName)) format_ << memberName << ": "; else format_ << "\"" << memberName << "\": "; writeValue(memberValue, depth + 1); format_ << "\n"; if (i < object->count() - 1) writeIndent(depth + 1); } if (object->hasChildren()) { if (object->count() > 0) writeIndent(depth + 1); MetaObjectList *children = object->children(); for (int i = 0; i < children->count(); ++i) { writeObject(children->at(i), depth + 1); format_ << "\n"; if (i < children->count() -1) writeIndent(depth + 1); } } writeIndent(depth); format_ << "}"; } void YasonWriter::writeIndent(int depth) { for (int i = 0; i < depth; ++i) format_ << indent_; } template<class T> void YasonWriter::writeTypedList(Variant value, int depth) { List<T> *list = cast< List<T> >(value); if (list->count() == 0) { format_ << "[]"; return; } format_ << "[ "; for (int i = 0; i < list->count(); ++i) { writeValue(list->at(i), depth); if (i < list->count() - 1) format_ << ", "; } format_ << " ]"; } }} // namespace flux::meta
#pragma once #include <cstdint> #include <landstalker-lib/tools/json.hpp> class ItemDistribution { private: uint16_t _quantity = 0; public: ItemDistribution() = default; explicit ItemDistribution(uint16_t quantity) : _quantity (quantity) {} [[nodiscard]] uint16_t quantity() const { return _quantity; } void quantity(uint16_t value) { _quantity = value; } void add(uint8_t quantity) { _quantity += quantity; } void remove(uint8_t quantity) { if(_quantity <= quantity) _quantity = 0; else _quantity -= quantity; } [[nodiscard]] Json to_json() const { return { {"quantity", _quantity} }; } static ItemDistribution* from_json(const Json& json) { uint16_t quantity = json.value("quantity", 0); return new (quantity); } };
//#include <cstdio> #include <cstdlib> #include <iostream> #include <time.h> #include "tools.h" #include "gauss.h" int main(int argc, char** argv){ double* a; double* b; int initID = 0; int n=0; int m=0; int res; char* name; clock_t t; double time=0.; FILE* input; if (argc==3){ if ( !(n = atoi(argv[1])) || !(m = atoi(argv[2]))){ printf("This is not a moon!\n"); return -4; } //n = atoi(argv[1]); //m = atoi(argv[2]); a = new double[n*n]; if (a==NULL){ printf("Failed to allocate memory for matrix A\n"); return -2; } defineMatrixWithFunction(a, n); initID=1; } else if (argc==4){ if ( !(n = atoi(argv[1])) || !(m = atoi(argv[2]))){ printf("This is not a moon!\n"); return -4; } name = argv[1]; //n = atoi(argv[2]); //m = atoi(argv[3]); printf("n=%d m=%d\n", n, m); int size = n*n; a = new double[size]; if (a==NULL){ printf("Failed to allocate memory for matrix A\n"); return -2; } input = fopen(name, "r"); readMatrixFromFile(input, a, n); fclose(input); initID=2; } else{ printf("Usage:\n %s n m\n %s file_name n m\n", argv[0], argv[0]); return -1; } if (initID==0){ printf("Failed to initialize matrix\n"); delete[] a; return -1; } b = new double[n*n]; if (b==NULL){ printf("Failed to allocate memory for matrix B\n"); delete[] a; return -2; } makeBlockMatrix(a, n, m); printUpperLeftBlock(a, n, m); idMatrix(b, n); makeBlockMatrix(b, n, m); t = clock(); res = gaussInvert(a, b, n ,m); if (res!=0){ printf("Method failed!\n"); } time = (clock()-t)*1./CLOCKS_PER_SEC; printf("and here we have a record: %.2lf\n", time); printUpperLeftBlock(b, n, m); if (res==0){ if (initID==2){ input = fopen(argv[1], "r"); readMatrixFromFile(input, a, n); fclose(input); } else if (initID==1){ defineMatrixWithFunction(a, n); } calculationDeviation(b, a, n, m); } delete[] a; delete[] b; return 0; }
#include <iostream> #include <vector> #include <algorithm> using namespace std; /*concept1 문제랑은 다르게 고려해야 할 요소가 4개나 있으니 단순히 pair나 map을 이용해서 풀기 힘들다. 그럴 경우 class를 이용하여 안의 속성들을 정렬하는 방식으로 푼다.*/ class Student { public: string name; int kor, eng, math; Student(string name, int kor, int eng, int math){ this->name = name; this->kor = kor; this->eng = eng; this->math = math; } /*이 메소드를 기억해 두자. 객체 끼리 비교할 수 있는 기준을 세워 주는 메소드다.*/ bool operator <(Student &other){ if(this->kor == other.kor){ if(this->eng == other.eng){ if(this->math == other.math){ return this->name < other.name; }else{ return this->math > other.math; } }else{ return this->eng < other.eng; } }else{ return this->kor > other.kor; } } }; int main(){ int n; string name; int kor, eng, math; vector<Student> scores; cin >> n; for(int a = 0; a < n; a++){ cin >> name >> kor >> eng >> math; /*이름과 점수들을 입력 받을 때 마다 객체를 생성자를 통해 생성하여 scores 벡터 안에 넣어준다.*/ scores.push_back(Student(name, kor, eng, math)); } /*sort 함수에 따라 정렬을 수행하면 operator 메소드의 정렬 방식에 따라 정렬이 수행된다.*/ sort(scores.begin(), scores.end()); for(int b = 0; b < n; b++){ cout << scores[b].name << endl; } return 0; }
#include <iostream> #include "logging.hpp" INITIALIZE_EASYLOGGINGPP // Program entry point. int main(int argc, char** argv) { START_EASYLOGGINGPP(argc, argv); CXL_LOG(INFO) << "Hello, useful utils =)"; return 0; }
// // https://open.kattis.com/problems/r2 // // Created by Sofian Hadianto on 23/12/18. // Copyright © 2018 Sofian Hadianto. All rights reserved. // #include <bits/stdc++.h> using namespace std; typedef long long ll; int main(int argc, const char * argv[]) { ios::sync_with_stdio(false); cin.tie(NULL); ll R1,R2; ll S; cin >> R1 >> S; R2 = (2 * S) - R1; cout << R2 << endl; return 0; }
#ifndef __ZU_STACK_ALLOCATOR_H__ #define __ZU_STACK_ALLOCATOR_H__ #include <string> #include <iostream> #include <cdk/symbol_table.h> #include <cdk/ast/basic_node.h> #include "targets/symbol.h" #include "targets/basic_ast_visitor.h" namespace zu { class stack_allocator: public basic_ast_visitor { cdk::symbol_table<zu::symbol> &_symtab; int _alloc = 0; public: stack_allocator(std::shared_ptr<cdk::compiler> compiler, cdk::symbol_table<zu::symbol> &symtab) : basic_ast_visitor(compiler), _symtab(symtab) { } public: ~stack_allocator() {} public: int memory() const { return _alloc; } public: void do_sequence_node(cdk::sequence_node * const node, int lvl); public: void do_integer_node(cdk::integer_node * const node, int lvl); void do_double_node(cdk::double_node * const node, int lvl); void do_string_node(cdk::string_node * const node, int lvl); public: void do_neg_node(cdk::neg_node * const node, int lvl); void do_not_node(zu::not_node * const node, int lvl); void do_identity_node(zu::identity_node * const node, int lvl); void do_position_node(zu::position_node * const node, int lvl); public: void do_and_node(zu::and_node * const node, int lvl); void do_or_node(zu::or_node * const node, int lvl); void do_allocation_node(zu::allocation_node * const node, int lvl); void do_index_node(zu::index_node * const node, int lvl); void do_id_node(zu::id_node * const node, int lvl); void do_variable_node(zu::variable_node * const node, int lvl); void do_lvalue_node(zu::lvalue_node * const node, int lvl); public: void do_add_node(cdk::add_node * const node, int lvl); void do_sub_node(cdk::sub_node * const node, int lvl); void do_mul_node(cdk::mul_node * const node, int lvl); void do_div_node(cdk::div_node * const node, int lvl); void do_mod_node(cdk::mod_node * const node, int lvl); void do_lt_node(cdk::lt_node * const node, int lvl); void do_le_node(cdk::le_node * const node, int lvl); void do_ge_node(cdk::ge_node * const node, int lvl); void do_gt_node(cdk::gt_node * const node, int lvl); void do_ne_node(cdk::ne_node * const node, int lvl); void do_eq_node(cdk::eq_node * const node, int lvl); public: void do_function_declaration_node(zu::function_declaration_node * const node, int lvl); void do_function_body_node(zu::function_body_node * const node, int lvl); void do_function_call_node(zu::function_call_node * const node, int lvl); void do_block_node(zu::block_node * const node, int lvl); void do_evaluation_node(zu::evaluation_node * const node, int lvl); void do_print_node(zu::print_node * const node, int lvl); void do_read_node(zu::read_node * const node, int lvl); void do_assignment_node(zu::assignment_node * const node, int lvl); public: void do_for_node(zu::for_node * const node, int lvl); void do_if_node(zu::if_node * const node, int lvl); void do_if_else_node(zu::if_else_node * const node, int lvl); void do_break_node(zu::break_node * const node, int lvl); void do_continue_node(zu::continue_node * const node, int lvl); void do_return_node(zu::return_node * const node, int lvl); }; } // zu #define COUNT_STACK_SPACE(compiler, symtab, node, size) { \ zu::stack_allocator sa(compiler, symtab); \ (node)->accept(&sa, 0); \ size = sa.memory(); \ } #endif
#include <iostream> using namespace std; int main(){ int outputs; int outputf = 0; int remainder; int n; int s; cin>>n; cin>>s; remainder = s; for (int i = n ; i>0 ; --i){ if (i<=remainder){ outputs = remainder/i; outputf += outputs; remainder -= i*outputs; } else{} } cout<<outputf; }
#include <bits/stdc++.h> using namespace std; int main() { int N; while (cin >> N, N) { priority_queue<int, vector<int>, greater<int>> fila; for (int i = 0; i < N; ++i) { int a; cin >> a; fila.push(a); } int cost = 0; while (fila.size() > 1) { int a = fila.top(); fila.pop(); int b = fila.top(); fila.pop(); cost += a + b; fila.push(a + b); } cout << cost << endl; } return 0; }
#include<stdio.h> #include<stdlib.h> void countSort(int arr[],int size,int max) { int count[max+1],output[size],i; for(i=0;i<=max;i++) count[i]=0; for(i=0;i<size;i++) //frequency of elements count[arr[i]]++; for(i=1;i<=max;i++) //giving index in sorted array count[i]=count[i]+count[i-1]; for(i=size-1;i>=0;i--) //starting loop from back for stability { //int x=count[arr[i]]-1; //giving index(x) of arr[i] in sorted array //output[x]=arr[i]; output[--count[arr[i]]] =arr[i]; } for(i=0;i<size;i++) arr[i]=output[i]; } int main() { int arr[]={-4,4,-2,1,2,-1,4,1,-9,6,-3,4},max=0,i,flag,min; for(i=0;i<=11;i++) { if(arr[i]<0) min=arr[i]; //finding first negative element flag=1; break; } if(flag==1) //finding largest negative { for(int j=i;j<=11;j++) if(min>arr[j]) min=arr[j]; } printf("\n min element is %d",min); min=(-min); printf("\n min after sign change is %d",min); //adding min to every element for(i=0;i<=11;i++) { arr[i]=arr[i]+min; } for(i=0;i<=11;i++) { if(arr[i]>max) max=arr[i]; } printf("\n intermediate array:"); for(i=0;i<11;i++) printf("\n%d",arr[i]); printf("\n max element is %d",max); countSort(arr,11,max); for(i=0;i<=11;i++) { arr[i]=arr[i]-min; } printf("\narray after sorting:"); for(i=0;i<11;i++) printf("\n%d",arr[i]); }
#include <cstdio> #include <iostream> #include <map> #include <vector> #include <queue> #include <stack> #include <algorithm> #include <cstring> #include <set> #include <iterator> using namespace std; vector<string>node; map<string,int>seen; map<string,int>indegree; vector<string>result; map<string,vector<string> >v; int main() { int n,m,no=1; while(cin>>n) { string x,y; for(int i=0;i<n;i++){ cin>>x; node.push_back(x); } cin>>m; for(int i=0;i<m;i++){ cin>>x>>y; v[x].push_back(y); indegree[y]++; } for(int i=0;i<n;i++){ for(int j=0;j<n;j++) { if(indegree[node[j]]==0 && seen[node[j]]==0) { result.push_back(node[j]); for(int k=0;k<v[node[j]].size();k++)indegree[v[node[j]][k]]--; seen[node[j]]=1; break; } } } //cout<<"size "<<result.size()<<endl; bool ck=false; cout<<"Case #"<<no<<": "; cout<<"Dilbert should drink beverages in this order: "; for(int i=0;i<result.size();i++){ if(ck==true)cout<<" "; ck=true; cout<<result[i]; } cout<<"."; cout<<endl<<endl; no++; seen.clear(); node.clear(); v.clear(); result.clear(); indegree.clear(); } return 0; }
#ifndef STMT_INFO_COLLECT_H #define STMT_INFO_COLLECT_H #include "AstInterface.h" #include "SinglyLinkedList.h" #include "ProcessAstTree.h" #include "AnalysisInterface.h" #include "union_find.h" #include <map> #include <sstream> class StmtInfoCollect : public ProcessAstTreeBase { protected: struct ModRecord{ AstNodePtr rhs; bool readlhs; ModRecord() : readlhs(false) {} ModRecord( const AstNodePtr& _rhs, bool _readlhs) : rhs(_rhs), readlhs(_readlhs) {} }; typedef std::map<AstNodePtr, ModRecord, std::less<AstNodePtr> > ModMap; struct ModStackEntry { AstNodePtr root; ModMap modmap; ModStackEntry(const AstNodePtr& r) : root(r) {} }; std::list<ModStackEntry> modstack; AstNodePtr curstmt; protected: virtual void AppendModLoc( AstInterface& fa, const AstNodePtr& mod, const AstNodePtr& rhs = AstNodePtr()) = 0; virtual void AppendReadLoc( AstInterface& fa, const AstNodePtr& read) = 0; virtual void AppendFuncCall( AstInterface& fa, const AstNodePtr& fc) = 0; void AppendFuncCallArguments( AstInterface& fa, const AstNodePtr& fc) ; void AppendFuncCallWrite( AstInterface& fa, const AstNodePtr& fc) ; virtual bool ProcessTree( AstInterface &_fa, const AstNodePtr& s, AstInterface::TraversalVisitType t); public: void operator()( AstInterface& fa, const AstNodePtr& h) ; }; class FunctionSideEffectInterface; class StmtSideEffectCollect : public StmtInfoCollect, public SideEffectAnalysisInterface { private: bool modunknown, readunknown; FunctionSideEffectInterface* funcanal; CollectObject< std::pair<AstNodePtr,AstNodePtr> > *modcollect, *readcollect, *killcollect; virtual void AppendModLoc( AstInterface& fa, const AstNodePtr& mod, const AstNodePtr& rhs = AstNodePtr()) ; virtual void AppendReadLoc( AstInterface& fa, const AstNodePtr& read) ; virtual void AppendFuncCall( AstInterface& fa, const AstNodePtr& fc); public: StmtSideEffectCollect( FunctionSideEffectInterface* a=0) : modunknown(false), readunknown(false),funcanal(a), modcollect(0), readcollect(0), killcollect(0) {} bool get_side_effect(AstInterface& fa, const AstNodePtr& h, CollectObject<std::pair<AstNodePtr,AstNodePtr> >* collectmod, CollectObject<std::pair<AstNodePtr,AstNodePtr> >* collectread = 0, CollectObject<std::pair<AstNodePtr,AstNodePtr> >* collectkill = 0) { return operator()( fa, h, collectmod, collectread, collectkill); } bool operator()( AstInterface& fa, const AstNodePtr& h, CollectObject< std::pair<AstNodePtr,AstNodePtr> >* mod, CollectObject< std::pair<AstNodePtr,AstNodePtr> >* read=0, CollectObject< std::pair<AstNodePtr,AstNodePtr> >* kill = 0) { modcollect = mod; readcollect = read; killcollect = kill; modunknown = readunknown = false; StmtInfoCollect::operator()(fa, h); return !modunknown && !readunknown; } }; class Ast2StringMap { typedef std::map<AstNodePtr, std::string, std::less<AstNodePtr> > MapType; MapType astmap; int cur; public: Ast2StringMap() : cur(0) {} std::string get_string( const AstNodePtr& s); std::string get_string( const AstNodePtr& s) const; std::string lookup_string( const AstNodePtr& s) const; }; class InterProcVariableUniqueRepr { static Ast2StringMap astmap; public: static std:: string // get name for the ith parameter of function get_unique_name(const std::string& fname, int i) { std::stringstream out; out << i; std::string res = fname + "-" + out.str(); return res; } static std:: string get_unique_name(const std::string& fname, const AstNodePtr& scope, const std::string& varname) { return fname + "-" + (scope==0? "" : astmap.get_string(scope)) + "-" + varname; } static std:: string get_unique_name(AstInterface& fa, const AstNodePtr& exp); static std:: string get_unique_name(AstInterface& fa, const AstNodePtr& scope, const std::string& varname); }; class FunctionAliasInterface; // flow insensitive alias analysis for named variables only class StmtVarAliasCollect : public StmtInfoCollect, public AliasAnalysisInterface { public: class VarAliasMap { std::map<std::string, UF_elem*, std::less<std::string> > aliasmap; Ast2StringMap scopemap; public: ~VarAliasMap() { for (std::map<std::string, UF_elem*, std::less<std::string> >:: const_iterator p = aliasmap.begin(); p != aliasmap.end(); ++p) { delete (*p).second; } } UF_elem* get_alias_map( const std::string& varname, const AstNodePtr& scope); }; private: FunctionAliasInterface* funcanal; VarAliasMap aliasmap; bool hasunknown, hasresult; UF_elem* get_alias_map( const std::string& varname, const AstNodePtr& scope); virtual void AppendModLoc( AstInterface& fa, const AstNodePtr& mod, const AstNodePtr& rhs = AstNodePtr()); virtual void AppendFuncCall( AstInterface& fa, const AstNodePtr& fc); virtual void AppendReadLoc( AstInterface& fa, const AstNodePtr& read) {} public: StmtVarAliasCollect( FunctionAliasInterface* a = 0) : funcanal(a), hasunknown(false), hasresult(false) {} void operator()( AstInterface& fa, const AstNodePtr& funcdefinition); bool may_alias(AstInterface& fa, const AstNodePtr& r1, const AstNodePtr& r2); }; template <class Select> class ModifyVariableMap : public CollectObject<std::pair<AstNodePtr,AstNodePtr> >, public StmtSideEffectCollect { AstInterface& ai; class VarModSet : public std::set<AstNodePtr> {}; typedef std::map <std::string, VarModSet, std::less<std::string> > VarModInfo; VarModInfo varmodInfo; Select sel; bool operator()(const std::pair<AstNodePtr,AstNodePtr>& cur) { std::string varname; if (ai.IsVarRef(cur.first,0, &varname)) { AstNodePtr l = ai.GetParent(cur.first); VarModSet& cur = varmodInfo[varname]; for ( ; l != AST_NULL; l = ai.GetParent(l)) { if (sel(ai,l)) cur.insert(l); } } return true; } public: AstInterface& get_astInterface() { return ai; } ModifyVariableMap(AstInterface& _ai, Select _sel, FunctionSideEffectInterface* a=0) : StmtSideEffectCollect(a), ai(_ai), sel(_sel) {} void Collect(const AstNodePtr& root) { StmtSideEffectCollect::get_side_effect(ai, root, this); } bool Modify( const AstNodePtr& l, const std::string& varname) const { typename VarModInfo::const_iterator p = varmodInfo.find(varname); if (p != varmodInfo.end()) { if (l == AST_NULL) return true; const VarModSet& cur = (*p).second; return cur.find(l) != cur.end(); } else return false; } }; #endif
/* Author: Градобоева Елизавета Group: СБС-001-о-01 Task#: 1.11 */ #include <iostream> #include <cmath> using namespace std; int main() { cout << "The program calculates the square root of a complex number." << endl; const double PI = 3.1416; double x, y, z, iph, X1, Y1, X, Y; cout << "Enter the variable X ="; while (!(cin >> x)) { cin.clear(); while (cin.get() != '\n'); cout << "Error! A letter is entered, repeat the input" << endl; cout << "Enter the variable X ="; } cout << "Enter the variable Y ="; while (!(cin >> y)) { cin.clear(); while (cin.get() != '\n'); cout << "Error!A letter is entered, repeat the input" << endl; cout << "Enter the variable Y ="; } iph = atan2(y, x) * 180 / PI; z = sqrt(x * y + y * y); X = sqrt(z) * cos((iph + 2 * PI) / 2); Y = sqrt(z) * sin((iph + 2 * PI) / 2); cout << "X =" << X << "\t" "Y =" << Y << endl; X1 = sqrt(z) * cos(iph / 2); Y1 = sqrt(z) * sin(iph / 2); cout << "X1 =" << X1 << "\t" "Y1 =" << Y1 << endl; system("pause"); return 0; }
/*********************************************************************** created: Sun Jan 11 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/RendererModules/OpenGLES/Renderer.h" #include "CEGUI/RendererModules/OpenGLES/Texture.h" #include "CEGUI/Exceptions.h" #include "CEGUI/EventArgs.h" #include "CEGUI/ImageCodec.h" #include "CEGUI/DynamicModule.h" #include "CEGUI/RendererModules/OpenGLES/ViewportTarget.h" #include "CEGUI/RendererModules/OpenGLES/GeometryBuffer.h" #include "CEGUI/RendererModules/OpenGLES/FBOTextureTarget.h" #include "CEGUI/Logger.h" #include "CEGUI/System.h" #include "CEGUI/DefaultResourceProvider.h" #include <sstream> #include <algorithm> #include <string.h> #include "CEGUI/RendererModules/OpenGLES/FBOTextureTarget.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// // The following are some GL extension / version dependant related items. // This is all done totally internally here; no need for external interface // to show any of this. //----------------------------------------------------------------------------// // we only really need this with MSVC / Windows(?) and by now it should already // be defined on that platform, so we just define it as empty macro so the // compile does not break on other systems. #ifndef APIENTRY # define APIENTRY #endif //! Dummy function for if real ones are not present (saves testing each render) void APIENTRY activeTextureDummy(GLenum) {} //----------------------------------------------------------------------------// // // Here we have an internal class that allows us to implement a factory template // for creating / destroying any type of TextureTarget. The code that detects // the computer's abilities will generate an appropriate factory for a // TextureTarget based on what the host system can provide - or use the default // 'null' factory if no suitable TextureTargets are available. // // base factory class - mainly used as a polymorphic interface class OGLTextureTargetFactory { public: OGLTextureTargetFactory() {} virtual ~OGLTextureTargetFactory() {} virtual TextureTarget* create(OpenGLESRenderer&) const { return 0; } virtual void destory(TextureTarget* target) const { delete target; } }; // template specialised class that does the real work for us template<typename T> class OGLTemplateTargetFactory : public OGLTextureTargetFactory { virtual TextureTarget* create(OpenGLESRenderer& r) const { return new T(r); } }; //----------------------------------------------------------------------------// String OpenGLESRenderer::d_rendererID( "CEGUI::OpenGLESRenderer - Official OpenGLES based 2nd generation renderer module."); //----------------------------------------------------------------------------// OpenGLESRenderer& OpenGLESRenderer::bootstrapSystem( const TextureTargetType tt_type, const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); if (System::getSingletonPtr()) throw InvalidRequestException( "CEGUI::System object is already initialised."); OpenGLESRenderer& renderer(create(tt_type)); DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); System::create(renderer, rp); return renderer; } //----------------------------------------------------------------------------// OpenGLESRenderer& OpenGLESRenderer::bootstrapSystem( const Sizef& display_size, const TextureTargetType tt_type, const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); if (System::getSingletonPtr()) throw InvalidRequestException( "CEGUI::System object is already initialised."); OpenGLESRenderer& renderer(create(display_size, tt_type)); DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); System::create(renderer, rp); return renderer; } //----------------------------------------------------------------------------// void OpenGLESRenderer::destroySystem() { System* sys; if (!(sys = System::getSingletonPtr())) throw InvalidRequestException( "CEGUI::System object is not created or was already destroyed."); OpenGLESRenderer* renderer = static_cast<OpenGLESRenderer*>(sys->getRenderer()); DefaultResourceProvider* rp = static_cast<DefaultResourceProvider*>(sys->getResourceProvider()); System::destroy(); delete rp; destroy(*renderer); } //----------------------------------------------------------------------------// OpenGLESRenderer& OpenGLESRenderer::create(const TextureTargetType tt_type, const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); return *new OpenGLESRenderer(tt_type); } //----------------------------------------------------------------------------// OpenGLESRenderer& OpenGLESRenderer::create(const Sizef& display_size, const TextureTargetType tt_type, const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); return *new OpenGLESRenderer(display_size, tt_type); } //----------------------------------------------------------------------------// void OpenGLESRenderer::destroy(OpenGLESRenderer& renderer) { delete &renderer; } //----------------------------------------------------------------------------// bool OpenGLESRenderer::isGLExtensionSupported( const char* extension ) { const GLubyte *extensions = NULL; const GLubyte *start; GLubyte *where, *terminator; /* Extension names should not have spaces. */ where = (GLubyte *) strchr(extension, ' '); if (where || *extension == '\0') return 0; extensions = glGetString(GL_EXTENSIONS); start = extensions; for (;;) { where = (GLubyte *) strstr((const char *) start, extension); if (!where) break; terminator = where + strlen(extension); if (where == start || *(where - 1) == ' ') if (*terminator == ' ' || *terminator == '\0') return true; start = terminator; } return false; } //----------------------------------------------------------------------------// OpenGLESRenderer::OpenGLESRenderer(const TextureTargetType tt_type) : d_initExtraStates(false) { // get rough max texture size GLint max_tex_size; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size); d_maxTextureSize = max_tex_size; // initialise display size GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); d_displaySize = Sizef(static_cast<float>(vp[2]), static_cast<float>(vp[3])); initialiseTextureTargetFactory(tt_type); d_defaultTarget = new OpenGLESViewportTarget(*this); } //----------------------------------------------------------------------------// OpenGLESRenderer::OpenGLESRenderer(const Sizef& display_size, const TextureTargetType tt_type) : d_displaySize(display_size), d_initExtraStates(false) { // get rough max texture size GLint max_tex_size; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size); d_maxTextureSize = max_tex_size; initialiseTextureTargetFactory(tt_type); d_defaultTarget = new OpenGLESViewportTarget(*this); } //----------------------------------------------------------------------------// OpenGLESRenderer::~OpenGLESRenderer() { destroyAllGeometryBuffers(); destroyAllTextureTargets(); destroyAllTextures(); delete d_defaultTarget; delete d_textureTargetFactory; } //----------------------------------------------------------------------------// RenderTarget& OpenGLESRenderer::getDefaultRenderTarget() { return *d_defaultTarget; } //----------------------------------------------------------------------------// GeometryBuffer& OpenGLESRenderer::createGeometryBuffer() { OpenGLESGeometryBuffer* b= new OpenGLESGeometryBuffer; d_geometryBuffers.push_back(b); return *b; } //----------------------------------------------------------------------------// void OpenGLESRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer) { GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), d_geometryBuffers.end(), &buffer); if (d_geometryBuffers.end() != i) { d_geometryBuffers.erase(i); delete &buffer; } } //----------------------------------------------------------------------------// void OpenGLESRenderer::destroyAllGeometryBuffers() { while (!d_geometryBuffers.empty()) destroyGeometryBuffer(**d_geometryBuffers.begin()); } //----------------------------------------------------------------------------// TextureTarget* OpenGLESRenderer::createTextureTarget(bool addStencilBuffer) { TextureTarget* t = d_textureTargetFactory->create(*this, addStencilBuffer); d_textureTargets.push_back(t); return t; } //----------------------------------------------------------------------------// void OpenGLESRenderer::destroyTextureTarget(TextureTarget* target) { TextureTargetList::iterator i = std::find(d_textureTargets.begin(), d_textureTargets.end(), target); if (d_textureTargets.end() != i) { d_textureTargets.erase(i); d_textureTargetFactory->destory(target); } } //----------------------------------------------------------------------------// void OpenGLESRenderer::destroyAllTextureTargets() { while (!d_textureTargets.empty()) destroyTextureTarget(*d_textureTargets.begin()); } //----------------------------------------------------------------------------// Texture& OpenGLESRenderer::createTexture(const String& name) { OpenGLESTexture* tex = new OpenGLESTexture(*this, name); d_textures[name] = tex; return *tex; } //----------------------------------------------------------------------------// Texture& OpenGLESRenderer::createTexture(const String& name, const String& filename, const String& resourceGroup) { OpenGLESTexture* tex = new OpenGLESTexture(*this, name, filename, resourceGroup); d_textures[name] = tex; return *tex; } //----------------------------------------------------------------------------// Texture& OpenGLESRenderer::createTexture(const String& name, const Sizef& size) { OpenGLESTexture* tex = new OpenGLESTexture(*this, name, size); d_textures[name] = tex; return *tex; } //----------------------------------------------------------------------------// void OpenGLESRenderer::destroyTexture(const String& name) { TextureMap::iterator i = d_textures.find(name); if (d_textures.end() != i) { logTextureDestruction(name); delete i->second; d_textures.erase(i); } } //----------------------------------------------------------------------------// void OpenGLESRenderer::logTextureDestruction(const String& name) { Logger* logger = Logger::getSingletonPtr(); if (logger) logger->logEvent("[OpenGLESRenderer] Destroyed texture: " + name); } //----------------------------------------------------------------------------// void OpenGLESRenderer::destroyTexture(Texture& texture) { destroyTexture(texture.getName()); } //----------------------------------------------------------------------------// void OpenGLESRenderer::destroyAllTextures() { while (!d_textures.empty()) destroyTexture(d_textures.begin()->first); } //----------------------------------------------------------------------------// Texture& OpenGLESRenderer::getTexture(const String& name) const { TextureMap::const_iterator i = d_textures.find(name); if (i == d_textures.end()) throw UnknownObjectException( "No texture named '" + name + "' is available."); return *i->second; } //----------------------------------------------------------------------------// bool OpenGLESRenderer::isTextureDefined(const String& name) const { return d_textures.find(name) != d_textures.end(); } //----------------------------------------------------------------------------// void OpenGLESRenderer::beginRendering() { //save current attributes // Unsupported by OpenGL ES //glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS); //glPushAttrib(GL_ALL_ATTRIB_BITS); // save current matrices //glMatrixMode(GL_PROJECTION); //glPushMatrix(); -- causes gl stack overflow error glMatrixMode(GL_MODELVIEW); glPushMatrix(); // Save at least something glPreRenderStates.glScissorTest = glIsEnabled(GL_SCISSOR_TEST); glPreRenderStates.texturing = glIsEnabled(GL_TEXTURE_2D); glPreRenderStates.blend = glIsEnabled(GL_BLEND); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &glPreRenderStates.arrayBuffer); glGetIntegerv(GL_TEXTURE_BINDING_2D, &glPreRenderStates.texture); glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &glPreRenderStates.texEnvParam); // do required set-up. yes, it really is this minimal ;) glEnable(GL_SCISSOR_TEST); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindBuffer(GL_ARRAY_BUFFER, 0); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // enable arrays that we'll be using in the batches glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); // if enabled, restores a subset of the GL state back to default values. if (d_initExtraStates) setupExtraStates(); } //----------------------------------------------------------------------------// void OpenGLESRenderer::endRendering() { if (d_initExtraStates) cleanupExtraStates(); // restore former matrices // FIXME: If the push ops failed, the following could mess things up! //glMatrixMode(GL_PROJECTION); //glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); if (!glPreRenderStates.glScissorTest) glDisable(GL_SCISSOR_TEST); if (!glPreRenderStates.texturing) glDisable(GL_TEXTURE_2D); if (!glPreRenderStates.blend) glDisable(GL_BLEND); if (glPreRenderStates.arrayBuffer) glBindBuffer(GL_ARRAY_BUFFER, glPreRenderStates.arrayBuffer); glBindTexture(GL_TEXTURE_2D, glPreRenderStates.texture); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, glPreRenderStates.texEnvParam); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); //restore former attributes //still unsupported //glPopAttrib(); //glPopClientAttrib(); } //----------------------------------------------------------------------------// const Sizef& OpenGLESRenderer::getDisplaySize() const { return d_displaySize; } //----------------------------------------------------------------------------// unsigned int OpenGLESRenderer::getMaxTextureSize() const { return d_maxTextureSize; } //----------------------------------------------------------------------------// const String& OpenGLESRenderer::getIdentifierString() const { return d_rendererID; } //----------------------------------------------------------------------------// Texture& OpenGLESRenderer::createTexture(const String& name, GLuint tex, const Sizef& sz) { OpenGLESTexture* t = new OpenGLESTexture(*this, name, tex, sz); d_textures[name] = t; return *t; } //----------------------------------------------------------------------------// void OpenGLESRenderer::setDisplaySize(const Sizef& sz) { if (sz != d_displaySize) { d_displaySize = sz; // update the default target's area Rectf area(d_defaultTarget->getArea()); area.setSize(sz); d_defaultTarget->setArea(area); } } //----------------------------------------------------------------------------// void OpenGLESRenderer::enableExtraStateSettings(bool setting) { d_initExtraStates = setting; } //----------------------------------------------------------------------------// void OpenGLESRenderer::setupExtraStates() { glMatrixMode(GL_TEXTURE); glPushMatrix(); glLoadIdentity(); glActiveTexture(GL_TEXTURE0); glClientActiveTexture(GL_TEXTURE0); //glPolygonMode(GL_FRONT, GL_FILL); //glPolygonMode(GL_BACK, GL_FILL); glDisable(GL_LIGHTING); glDisable(GL_FOG); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); //glDisable(GL_TEXTURE_GEN_S); //glDisable(GL_TEXTURE_GEN_T); //glDisable(GL_TEXTURE_GEN_R); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); } //----------------------------------------------------------------------------// void OpenGLESRenderer::cleanupExtraStates() { glMatrixMode(GL_TEXTURE); glPopMatrix(); } //----------------------------------------------------------------------------// void OpenGLESRenderer::grabTextures() { for(TextureMap::iterator i = d_textures.begin(); i != d_textures.end(); ++i) i->second->grabTexture(); } //----------------------------------------------------------------------------// void OpenGLESRenderer::restoreTextures() { for(TextureMap::iterator i = d_textures.begin(); i != d_textures.end(); ++i) i->second->restoreTexture(); } //----------------------------------------------------------------------------// void OpenGLESRenderer::initialiseTextureTargetFactory( const TextureTargetType tt_type) { if (isGLExtensionSupported("GL_OES_framebuffer_object")) { d_rendererID += " TextureTarget support enabled via" "GL_OES_framebuffer_object extension."; OpenGLESFBOTextureTarget::initializedFBOExtension(); d_textureTargetFactory = new OGLTemplateTargetFactory<OpenGLESFBOTextureTarget>; } else { d_rendererID += " TextureTarget support is not available :("; d_textureTargetFactory = new OGLTextureTargetFactory; } } //----------------------------------------------------------------------------// Sizef OpenGLESRenderer::getAdjustedTextureSize(const Sizef& sz) const { Sizef out(sz); out.d_width = getNextPOTSize(out.d_width); out.d_height = getNextPOTSize(out.d_height); return out; } //----------------------------------------------------------------------------// float OpenGLESRenderer::getNextPOTSize(const float f) { unsigned int size = static_cast<unsigned int>(f); // if not power of 2 if ((size & (size - 1)) || !size) { int log = 0; // get integer log of 'size' to base 2 while (size >>= 1) ++log; // use log to calculate value to use as size. size = (2 << log); } return static_cast<float>(size); } //----------------------------------------------------------------------------// bool OpenGLESRenderer::isTexCoordSystemFlipped() const { return true; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
#include <iostream> #include <algorithm> #include <queue> using namespace std; int num[100]; int n; class treenode { public: int data; treenode *lch; treenode *rch; treenode(int s) { data=s; lch=NULL; rch=NULL; } }; void destroy(treenode *node) { if(node->lch!=NULL) destroy(node->lch); if(node->rch!=NULL) destroy(node->rch); delete []node; } int main() { cin>>n; for(int k=0;k<n;k++) scanf("%d",&num[k]); sort(num,num+n); treenode *treenode1=new treenode(num[0]); treenode *treenode2=new treenode(num[1]); treenode *node=new treenode(num[0]+num[1]); node->lch=treenode1; node->rch=treenode2; for(int k=2;k<n;k++) { treenode *temp=node; treenode *t=new treenode(num[k]); node=new treenode(num[k]+node->data); if(node->data>num[k]) { node->rch=temp; node->lch=t; } if(node->data>num[k]) { node->lch=temp; node->rch=t; } } queue<treenode*> q; q.push(node); while(!q.empty()) { treenode *temp=q.front(); if(temp->lch!=NULL) q.push(temp->lch); if(temp->rch!=NULL) q.push(temp->rch); if(temp->lch==NULL&&temp->rch==NULL) printf("%d",temp->data); q.pop(); } }
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; for(int i=0; i<=n; i++) { for(int j=0; j<n-i; j++) cout<<" "; for(int j=0; j<2*i; j++) { if(j<=i) cout<<j<<" "; else cout<<2*i-j<<" "; } cout<<0<<endl; } for(int i=n-1; i>=0; i--) { for(int j=0; j<n-i; j++) cout<<" "; for(int j=0; j<2*i; j++) { if(j<=i) cout<<j<<" "; else cout<<2*i-j<<" "; } cout<<0<<endl; } }
#ifndef TempPeripheral_h #define TempPeripheral_h #include <Arduino.h> #include <ESP8266WebServer.h> #include <PubSubClient.h> #include <ESP_MQTTLogger.h> #include <OneWire.h> #include <DallasTemperature.h> #include "peripherals.h" class TempPeripheral : public Peripheral { public: TempPeripheral(); void begin(ESP_MQTTLogger& l); void publish_data(); private: bool _got_temp = false; OneWire * _one_wire; DallasTemperature * _DS18B20; }; #endif
#include "stdafx.h" #include "ErrorLogger.h" void ErrorLogger::Log(string message) { string error_message = "Error: " + message; MessageBoxA(NULL, error_message.c_str(), "Error", MB_ICONERROR); } void ErrorLogger::Log(HRESULT hr, string message) { _com_error error(hr); wstring error_message = L"Error: " + StringConverter::StringToWide(message) + L"\n" + error.ErrorMessage(); MessageBoxW(NULL, error_message.c_str(), L"Error", MB_ICONERROR); }
#include<Windows.h> #include"CView.h" extern CView app; LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) { int i = 0; while (CView::messageMap[i].iMsg != 0) { if (iMsg == CView::messageMap[i].iMsg) { fpCViewGlobal = CView::messageMap[i].fp; (app.*fpCViewGlobal)(wParam,lParam); return 0; }//if ++i; }//while return DefWindowProc(hwnd, iMsg, wParam, lParam); }//WndProc int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { app.InitInstance(hInstance, szCmdLine, iCmdShow); app.Run(); return app.ExitInstance(); }//WinMain
#include "../include/mathGL_graphics.h" #include <cmath> #include <list> #include <string> /** * * Example of plotting two arguments function f(x,t) = cos(x) - t, * using syntax parser * */ int main() { MathGLGraphics gr; TwoArgumentsFunction_Surf_SyntaxParser obj("cos(x) - y"); gr.parametres()->setRanges(-10, 10, -5, 5,-7,7); gr.parametres()->setRotation(70,45); gr.link(&obj); gr.plotQT("cos(x) - t"); return 0; }
#include<algorithm> #include<bitset> #include<cmath> #include<cstdio> #include<cstdlib> #include<cstring> #include<deque> #include<functional> #include<iostream> #include<limits> #include<map> #include<queue> #include<set> #include<stack> #include<string> #include<vector> #include<numeric> #include<ext/numeric> // iota //#include<ext/hash_set> //#include<ext/hash_map> using namespace std; using namespace __gnu_cxx; // Pour utiliser les ext/... typedef long long ll; typedef unsigned long long ull; typedef vector<int> vi; typedef pair<int, int> pii; //typedef int int128 __attribute__ ((mode(TI))); //typedef unsigned int uint128 __attribute__ ((mode(TI))); int infty = numeric_limits<int>::max();
#include "StdAfx.h" #include "QueryProcessConnect.h" #include "CommonFunc.h" CQueryProcessConnect::CQueryProcessConnect(void) { } CQueryProcessConnect::~CQueryProcessConnect(void) { } long CQueryProcessConnect::Init() { long long_ret = 0; QuerySYSResult = NULL; QuerySYSTypeCount = NULL; QuerySYSTypeCountParam=NULL; QuerySYSResultParam = NULL; QuerySYSEnd = NULL; QuerySYSEndParam = NULL; ::InitializeCriticalSection(&cs_InfoLock); return long_ret; } long CQueryProcessConnect::GetSYSInfo(void* param) { long long_ret = 0; if (param == NULL) { long_ret = -1; return long_ret; } SYSItems* p_query = NULL; p_query = (SYSItems*)param; if (long_ret == 0) { QuerySYSResult = p_query->p_func_query_sys_result; QuerySYSResultParam = p_query->p_func_query_sys_result_param; QuerySYSTypeCount = p_query->p_func_query_sys_type_count; QuerySYSTypeCountParam = p_query->p_func_query_collect_sys_type_param; QuerySYSEnd = p_query->p_func_query_sys_end; QuerySYSEndParam = p_query->p_func_query_sys_end_param; } //调试时候可能出现多线程问题 EnterCriticalSection(&cs_InfoLock); if(GetProcessConnectInfo()) { DWORD dw_vectorNum = m_vProcessNet.size(); QuerySYSTypeCount(dw_vectorNum,SYS_PROCESS_CONNECT,QuerySYSTypeCountParam); for(int i = 0 ; i< dw_vectorNum;i++) { QuerySYSResult(&m_vProcessNet[i],QuerySYSResultParam); //上传 } QuerySYSEnd(QuerySYSEndParam); } LeaveCriticalSection(&cs_InfoLock); return long_ret; } /*------------------------------- CONNECTTION INFORMATION -----------------------------*/ /* 获取进程连接信息调用 */ long CQueryProcessConnect::GetProcessConnectInfo() { //定义进程信息结构 PROCESSENTRY32 pe32; pe32.dwSize = sizeof(PROCESSENTRY32); MapPID2APP mappid2app; m_vProcessNet.clear(); EnableDebugPrivilege(); HANDLE hProcessShot; hProcessShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); //获取进程列表,最后一个参数是0 if (hProcessShot == INVALID_HANDLE_VALUE) { return 0; } // 创建系统当前进程快照 if (Process32First(hProcessShot,&pe32))//获取下一个进程快照 { for (int i = 0;Process32Next(hProcessShot, &pe32);i++) { //char mmk[MAX_PATH] = {0}; //char mm[MAX_PATH] = {0}; //sprintf(mm,"%d",pe32.th32ProcessID); //OutputDebugStringA(mm); mappid2app[pe32.th32ProcessID] = pe32.szExeFile; } } //遍历进程快照 GetConnectInfo(mappid2app); CloseHandle(hProcessShot); return 1; } BOOL CQueryProcessConnect::GetPortInfoVista(VPortInfoVista &v, MapPID2APP &mapPID2App) { WSADATA WSAData; WSAStartup(MAKEWORD(1, 1), &WSAData ); HMODULE hDll = LoadLibraryA("iphlpapi.dll"); if (NULL == hDll) return false; typedef int (WINAPI *PGetExtendedTcpTable)(MIB_TCPTABLE_OWNER_PID *ptr,PDWORD pdwSize, BOOL bOrder, ULONG ulAf, TCP_TABLE_CLASS TableClass, ULONG Reserved); // typedef DWORD (*PGetExtendedTcpTable)( PVOID pTcpTable, PDWORD pdwSize, BOOL bOrder, ULONG ulAf, TCP_TABLE_CLASS TableClass, ULONG Reserved ); PGetExtendedTcpTable pGetExtendedTcpTable = (PGetExtendedTcpTable)GetProcAddress(hDll, "GetExtendedTcpTable"); typedef int (WINAPI *PGetExtendedUdpTable)(MIB_UDPTABLE_OWNER_PID *ptr,PDWORD pdwSize, BOOL bOrder, ULONG ulAf, UDP_TABLE_CLASS TableClass, ULONG Reserved); PGetExtendedUdpTable pGetExtendedUdpTable = (PGetExtendedUdpTable)GetProcAddress(hDll, "GetExtendedUdpTable"); if (!pGetExtendedTcpTable || !pGetExtendedUdpTable) return false; MIB_TCPTABLE_OWNER_PID tcpx; PMIB_TCPTABLE_OWNER_PID TcpPtr=NULL; DWORD dwSize=0; // ULONG Reserved; int ret = pGetExtendedTcpTable(&tcpx,&dwSize,FALSE,AF_INET,TCP_TABLE_OWNER_PID_ALL,0); if(ERROR_INVALID_PARAMETER == ret ) { OutputDebugStringA("获取失败"); return false; } if(ERROR_INSUFFICIENT_BUFFER == ret) { int nSize = dwSize/sizeof(MIB_TCPTABLE_OWNER_PID); TcpPtr = new MIB_TCPTABLE_OWNER_PID[nSize+1]; ZeroMemory(TcpPtr, nSize*sizeof(MIB_TCPTABLE_OWNER_PID)); if(pGetExtendedTcpTable(TcpPtr, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) == NO_ERROR) { for (DWORD i = 0;i < TcpPtr->dwNumEntries; i ++) { PortInfoVista vPortBuffer; DWORD dwPID = TcpPtr->table[i].dwOwningPid; vPortBuffer.dwLocalIp = TcpPtr->table[i].dwLocalAddr; vPortBuffer.dwLocalPort = ntohs((USHORT)TcpPtr->table[i].dwLocalPort); vPortBuffer.dwProcessID = dwPID; vPortBuffer.dwStatus = TcpPtr->table[i].dwState; if (MIB_TCP_STATE_LISTEN ==vPortBuffer.dwStatus ) { vPortBuffer.dwRemoteIp = 0; vPortBuffer.dwRemotePort = 0; } else { vPortBuffer.dwRemoteIp = TcpPtr->table[i].dwRemoteAddr; vPortBuffer.dwRemotePort = ntohs((USHORT)TcpPtr->table[i].dwRemotePort); } vPortBuffer.dwType = TCP; vPortBuffer.sFileName = mapPID2App[dwPID]; //TcpPtr->table[i].OwningModuleInfo v.push_back(vPortBuffer); } } delete []TcpPtr; } PMIB_UDPTABLE_OWNER_PID UdpPtr = NULL; dwSize = 0; ret = pGetExtendedUdpTable(UdpPtr,&dwSize,NULL,AF_INET,UDP_TABLE_OWNER_PID,0); if(ERROR_INVALID_PARAMETER == ret ) { OutputDebugStringA("获取失败"); return false; } if(ERROR_INSUFFICIENT_BUFFER == ret) { UdpPtr =new MIB_UDPTABLE_OWNER_PID[dwSize/sizeof(MIB_UDPTABLE_OWNER_PID)]; if(pGetExtendedUdpTable(UdpPtr,&dwSize,NULL,AF_INET,UDP_TABLE_OWNER_PID,0) == NO_ERROR) { for (DWORD i = 0;i < UdpPtr->dwNumEntries; i ++) { PortInfoVista vPortBuffer; DWORD dwPID = UdpPtr->table[i].dwOwningPid; vPortBuffer.dwLocalIp = UdpPtr->table[i].dwLocalAddr; vPortBuffer.dwLocalPort = ntohs((USHORT)UdpPtr->table[i].dwLocalPort); vPortBuffer.dwProcessID = dwPID; vPortBuffer.dwStatus = 0; vPortBuffer.dwRemoteIp = 0; vPortBuffer.dwRemotePort = 0; vPortBuffer.dwType = UDP; vPortBuffer.sFileName = mapPID2App[dwPID]; v.push_back(vPortBuffer); } } delete [] UdpPtr; } return true; } /* *函数:GetConnectInfo *参数1:map *返回值:BOOL *作用: 获取信息保存在Vector */ BOOL CQueryProcessConnect::GetConnectInfo(MapPID2APP MapPid) { VPortInfoVista vInfosvista; CString strTmpName; DWORD nTmpPid =0; if (GetPortInfoVista(vInfosvista, MapPid)) { for (VPortInfoVista::iterator it = vInfosvista.begin(); it != vInfosvista.end(); it ++) { CString sLocalIP(inet_ntoa(*(struct in_addr*)&it->dwLocalIp)); CString sRemoteIP(inet_ntoa(*(struct in_addr*)&it->dwRemoteIp)); CString sLocal, sRemote, sProtocol; sLocal.Format(_T("%s:%d"), sLocalIP, it->dwLocalPort); sRemote.Format(_T("%s:%d"), sRemoteIP, it->dwRemotePort); /* FILE* newfile = fopen("new.txt","a+"); char mm[255] = {0}; sprintf(mm,"%d",it->dwRemoteIp); fputs(SystemUnicodeToAnsi(it->sFileName),newfile); fputs(mm,newfile); fputs(SystemUnicodeToAnsi(sRemoteIP),newfile); fputs("\n",newfile); //fputs(SystemUnicodeToAnsi(sRemote),newfile); fclose(newfile); */ if (it->dwRemoteIp != 0) //远程IP不为空 { ProcessConncectResult tmp_net ; memset(&tmp_net,0,sizeof(ProcessConncectResult)); if (it->dwProcessID == 0) { tmp_net.Pid = nTmpPid; } else { tmp_net.Pid = it->dwProcessID; nTmpPid = it->dwProcessID; } if (it->sFileName.GetLength() == 0) { //tmp_net.ProcessName = strTmpName; strcpy(tmp_net.szProcessName,strTmpName.GetBuffer(strTmpName.GetLength())); } else { //tmp_net.ProcessName = it->sFileName; strcpy(tmp_net.szProcessName, it->sFileName.GetBuffer(it->sFileName.GetLength())); strTmpName = it->sFileName; } if (it->dwType == 1) { //tmp_net.strTpye.Format(_T("TCP")); strcpy(tmp_net.szTpye,_T("TCP")); } else if (it->dwType == 2) { strcpy(tmp_net.szTpye,_T("UDP")); } //tmp_net.dwStatus = it->dwStatus; strcpy(tmp_net.szLocal,sLocal.GetBuffer(sLocal.GetLength())); strcpy(tmp_net.szRemote,sRemote.GetBuffer(sRemote.GetLength())); SwitchStatus(it->dwStatus,tmp_net.szStatus); m_vProcessNet.push_back(tmp_net); } } } return TRUE; } /* *函数:SwitchStatus *参数1:输入获取的Status号 *参数2:状态赋值 *返回值:void *作用: 给获取的链接状态 赋值 */ void CQueryProcessConnect::SwitchStatus(DWORD dwStatus,char* szStatus) { switch (dwStatus) { case MIB_TCP_STATE_CLOSED: _tcscpy(szStatus,_T("CLOSED")); break; case MIB_TCP_STATE_LISTEN: _tcscpy(szStatus,_T("LISTENING")); break; case MIB_TCP_STATE_SYN_SENT: _tcscpy(szStatus,_T("SYN_SENT")); break; case MIB_TCP_STATE_SYN_RCVD: _tcscpy(szStatus,_T("SYN_RCVD")); break; case MIB_TCP_STATE_ESTAB: _tcscpy(szStatus,_T("ESTABLISHED")); break; case MIB_TCP_STATE_FIN_WAIT1: _tcscpy(szStatus,_T("FIN_WAIT_1")); break; case MIB_TCP_STATE_FIN_WAIT2: _tcscpy(szStatus,_T("FIN_WAIT_2")); break; case MIB_TCP_STATE_CLOSE_WAIT: _tcscpy(szStatus,_T("CLOSE_WAIT")); break; case MIB_TCP_STATE_CLOSING: _tcscpy(szStatus,_T("CLOSING")); break; case MIB_TCP_STATE_LAST_ACK: _tcscpy(szStatus,_T("LAST_ACK")); break; case MIB_TCP_STATE_TIME_WAIT: _tcscpy(szStatus,_T("TIME_WAIT")); break; case MIB_TCP_STATE_DELETE_TCB: _tcscpy(szStatus,_T("DELETE_TCB")); break; } }
#pragma once #include <opencv2/core.hpp> class CurveCompare { public: static void curveCompareNormalizedArea(cv::Mat &input, cv::Mat &teacher, double &area, double &completeness) { int numPixels = 0; int nt = 0; int ni = 0; for (int i = 0; i < teacher.cols; ++i) { for (int j = 0; j < teacher.rows; ++j) { if (teacher.at<uchar>(j, i) > 0) { ++nt; for (int k = 0; k < input.rows; ++k) { if (input.at<uchar>(k, i) > 0) { ++ni; numPixels += abs(k - j); break; } } break; } } } area = double(numPixels) / double(teacher.cols*teacher.rows); completeness = (double(ni) / double(nt)); } static void curveComparePixelDeviation(cv::Mat &input, cv::Mat &teacher, double &area, double &completeness) { int numPixels = 0; int nt = 0; int ni = 0; for (int i = 0; i < teacher.cols; ++i) { for (int j = 0; j < teacher.rows; ++j) { if (teacher.at<uchar>(j, i) > 0) { ++nt; for (int k = 0; k < input.rows; ++k) { if (input.at<uchar>(k, i) > 0) { ++ni; numPixels += abs(k - j); break; } } break; } } } area = double(numPixels) / double(nt); completeness = (double(ni) / double(nt)); } static void curveComparePixelDeviation(cv::Mat &input, std::vector<cv::Point> &teacher, double &area, double &completeness) { int numPixels = 0; int nt = (int) teacher.size(); int ni = 0; for (cv::Point t : teacher) { for (int k = 0; k < input.rows; ++k) { if (input.at<uchar>(k, t.x) > 0) { ++ni; numPixels += abs(k - t.y); break; } } break; } area = double(numPixels) / double(nt); completeness = (double(ni) / double(nt)); } };
#include<iostream> #include<set> #include<algorithm> using namespace std; const int MAX_NUM=100000; set<long long>s; int tmpArray[MAX_NUM int n,k; int process() { int ans=0; int start,end; cin >>n>>k; s.clear(); for(int i=0;i<n;i++) { long long tmpI; cin >>tmpI; s.insert(tmpI); } start=0;end=s.size()-1; while(true) { if(start>=end)break; long long tmp=s.+s[start]; if(tmp==k) { ans++; start++; end--; continue; } if(tmp<k) { start++; continue; } if(tmp>k) { end--; continue; } } ans*=2; if(start==end && s[end]+s[start]==k)ans++; return ans; } int main() { int t; cin >>t; for(int j=0;j<t;j++) { cout <<process()<<endl; } return 0; }
#ifndef _CAMERA_H_ #define _CAMERA_H_ #include <stdio.h> #include <iostream> #include <map> #include <string> #include <vector> #include "CGFcamera.h" #include "CGFscene.h" using namespace std; class Camera: public CGFcamera { protected: bool enabled; string camera_id; float near; float far; public: Camera(string camera_id, float near, float far); bool getEnabled(); void setEnabled(bool enable); virtual int getCameraType(); string getId(); virtual void applyView(); virtual void updateProjectionMatrix(int width, int height); }; class Perspective: public Camera { protected: float angle; public: Perspective(string camera_id, float near, float far, float * pos, float * target); int getCameraType(); void changeView(); void applyView(); void updateProjectionMatrix(int width, int height); }; class Ortho: public Camera{ protected: float left; float right; float top; float bottom; string direction; public: Ortho(string camera_id, string direction, float near, float far, float left, float right, float top, float bottom); int getCameraType(); void changeView(); void applyView(); void updateProjectionMatrix(int width, int height); }; #endif
/********************************************************************** Filename : LobbyDataProvider.h Content : The Lobby application controller Created : 7/31/2009 Authors : Prasad Silva Copyright : (c) 2009 Scaleform Corp. All Rights Reserved. This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR ANY PURPOSE. **********************************************************************/ #ifndef INC_LobbyController_H #define INC_LobbyController_H #include "GRefCount.h" #include "FxGameDelegate.h" #include "LobbyDataProvider.h" #include "LobbyProfileManager.h" // This is the main lobby application. It interfaces with both the UI and // the data stores (online and offline). ////////////////////////////////////////////////////////////////////////// // Localization interface for the lobby application // class LobbyLocalizer { public: virtual const char* GetCurrentLanguage() = 0; virtual void ApplyLanguage(const char* lang) = 0; }; ////////////////////////////////////////////////////////////////////////// // The lobby application controller // class LobbyController : public FxDelegateHandler, public LDPResultListener { public: LobbyController(GFxMovieView* pmovie, FxDelegate* pdg, LobbyLocalizer* ploc); virtual ~LobbyController(); // FxDelegate callback installer void Accept(FxDelegateHandler::CallbackProcessor* cp); // DataProvider listener for results void OnDataProviderResult(LDPResult* r); // Login panel callbacks static void OnProfilesListRequestLength(const FxDelegateArgs& params); static void OnProfilesListRequestItemRange(const FxDelegateArgs& params); static void OnProfilesListRequestItemAt(const FxDelegateArgs& params); static void OnLogin(const FxDelegateArgs& params); static void OnLogout(const FxDelegateArgs& params); static void OnCreateProfile(const FxDelegateArgs& params); static void OnDeleteProfile(const FxDelegateArgs& params); static void OnGetRemLastAccount(const FxDelegateArgs& params); static void OnSetRemLastAccount(const FxDelegateArgs& params); // Language panel callbacks static void OnGetCurrentLanguage(const FxDelegateArgs& params); static void OnApplyLanguage(const FxDelegateArgs& params); // Buddy panel callbacks static void OnBuddyPanelStateChange(const FxDelegateArgs& params); static void OnBuddyListRequestLength(const FxDelegateArgs& params); static void OnBuddyListRequestItemRange(const FxDelegateArgs& params); static void OnBuddyListRequestItemAt(const FxDelegateArgs& params); static void OnSelectChatLog(const FxDelegateArgs& params); static void OnSubmitChat(const FxDelegateArgs& params); static void OnAddBuddy(const FxDelegateArgs& params); static void OnRemoveSelectedBuddy(const FxDelegateArgs& params); static void OnGetBuddyRequestsCount(const FxDelegateArgs& params); static void OnProcessBuddyRequest(const FxDelegateArgs& params); static void OnAcceptBuddyRequest(const FxDelegateArgs& params); // Browser panel callbacks static void OnServerBrowserPanelStateChange(const FxDelegateArgs& params); static void OnServerListRequestLength(const FxDelegateArgs& params); static void OnServerListRequestItemRange(const FxDelegateArgs& params); static void OnPopulateServers(const FxDelegateArgs& params); static void OnPollServerList(const FxDelegateArgs& params); static void OnSortServerList(const FxDelegateArgs& params); static void OnRefreshServer(const FxDelegateArgs& params); static void OnSpectateServer(const FxDelegateArgs& params); static void OnJoinServer(const FxDelegateArgs& params); static void OnConnect(const FxDelegateArgs& params); static void OnGetServerFilter(const FxDelegateArgs& params); static void OnSetServerFilter(const FxDelegateArgs& params); static void OnSetInitialServerSort(const FxDelegateArgs& params); static void OnServersScrolled(const FxDelegateArgs& params); // Players panel callbacks static void OnPlayersListRequestLength(const FxDelegateArgs& params); static void OnPlayersListRequestItemAt(const FxDelegateArgs& params); static void OnPlayersListRequestItemRange(const FxDelegateArgs& params); static void OnSortPlayerLists(const FxDelegateArgs& params); static void OnSetInitialPlayersSort(const FxDelegateArgs& params); // Callback to change data provider static void OnModeChange(const FxDelegateArgs& params); static void OnHasOnlineMode(const FxDelegateArgs& params); static void OnGetMode(const FxDelegateArgs& params); // Process pending tasks that may be queued up and require synchronous // execution with the main thread void ProcessTasks(); GINLINE bool IsOfflineMode() { return bOfflineMode; } private: // If true, then the current data provider is an offline data provider bool bOfflineMode; // GFx specific references GFxMovieView* pMovie; FxDelegate* pDelegate; // *** Login panel specific members // The current data provider GPtr<LobbyDataProvider> pDataProvider; GPtr<LobbyProfileManager> pProfileMgr; // A lobby localizer to retrieve localization specific information LobbyLocalizer* pLocalizer; // The current login profile GPtr<LobbyProfile> pLoginProfile; // *** Buddy panel specific members GArray< GPtr<LobbyBuddy> > BuddyList; // If true, then the buddy panel UI is available bool bBuddyPanelActive; int SelectedBuddyIndex; // List of buddy requests from remote users GArray< LobbyBuddyRequest > PendingBuddyRequests; // *** Server/Player panel specific members // Total list of servers retrieved from the data provider GArray< GPtr<LobbyServer> > UnfilteredServerList; // List of servers filtered from the unfiltered list (via the server filter) GArray< LobbyServer* > FilteredServerList; // Temporary storage for incoming servers. They must be processed when the // UI requests to refresh the view GArray< GPtr<LobbyServer> > UnprocessedServers; // If true, then the server panel UI is available bool bServerBrowserPanelActive; // Current network type LobbyServer::NetworkType ActiveServerListNetwork; // Comparator for the server list LobbyServerLess ServerComparator; // Currently selected server (can be set by both application and UI) int SelectedServerIndex; LobbyServerFilter ServerFilter; // Comparator for the player lists LobbyPlayerLess PlayerComparator; // Index of the top most server in the server list view (set by the UI) int TopServerIndex; // Temporary buffer used to compile a chat log before sending it // to the UI GStringBuffer CompiledMessage; // Initialize and startup the dataprovider void BootDataProvider(); // Clear all local server/player data void ClearData(); // Generate a formatted chat message (timestamp, html, etc.) void GenerateChatMessage(LobbyBuddy* pbuddy, const LobbyBuddyMessage& msg, LobbyBuddyMessage::Direction dir); LobbyBuddy* GetSelectedBuddy(); // Helper to notify the UI to refresh its buddy list view void RefreshBuddyList(); // Process the unprocessed server list void FlushUnprocessedServers(); LobbyServer* GetSelectedServer(); void ClearServerStorage(); void RefreshServerList(LobbyServer::NetworkType network); void ApplyServerFilter(); void NotifyPlayerListsClear(); LobbyServer* GetTopServer(); }; #endif // INC_LobbyController_H
template <typename T> class DataTypeFor { public: static H5::DataType value; }; template <typename T> typename std::enable_if<is_tt<std::complex, T>::value, void>::type get_hdf5(T * l, H5::H5File * file, char * name) { H5::DataSet dataset = H5::DataSet(file->openDataSet(name)); H5::CompType complex_data_type(sizeof(l[0])); typedef typename extract_value_type<T>::value_type value_type; complex_data_type.insertMember("r", 0, DataTypeFor<value_type>::value); complex_data_type.insertMember( "i", sizeof(value_type), DataTypeFor<value_type>::value); dataset.read(l, complex_data_type); }; template <typename T> typename std::enable_if<!is_tt<std::complex, T>::value, void>::type get_hdf5(T * l, H5::H5File * file, char * name) { H5::DataSet dataset = H5::DataSet(file->openDataSet(name)); dataset.read(l, DataTypeFor<T>::value); }; template <typename T> typename std::enable_if<is_tt<std::complex, T>::value, void>::type get_hdf5(T * l, H5::H5File * file, std::string & name) { H5::DataSet dataset = H5::DataSet(file->openDataSet(name)); H5::CompType complex_data_type(sizeof(l[0])); typedef typename extract_value_type<T>::value_type value_type; complex_data_type.insertMember("r", 0, DataTypeFor<value_type>::value); complex_data_type.insertMember( "i", sizeof(value_type), DataTypeFor<value_type>::value); dataset.read(l, complex_data_type); }; template <typename T> typename std::enable_if<!is_tt<std::complex, T>::value, void>::type get_hdf5(T * l, H5::H5File * file, std::string & name) { H5::DataSet dataset = H5::DataSet(file->openDataSet(name)); dataset.read(l, DataTypeFor<T>::value); }; /* template <typename T> typename std::enable_if< is_tt<std::complex, T>::value, void>::type get_hdf5(T *, H5::H5File *, char *); template <typename T> typename std::enable_if<!is_tt<std::complex, T>::value, void>::type get_hdf5(T *, H5::H5File *, char *); template <typename T> typename std::enable_if< is_tt<std::complex, T>::value, void>::type get_hdf5(T *, H5::H5File *, std::string &); template <typename T> typename std::enable_if<!is_tt<std::complex, T>::value, void>::type get_hdf5(T *, H5::H5File *, std::string &); */ template <typename T> typename std::enable_if<!is_tt<std::complex, T>::value, void>::type write_hdf5(const Eigen::Array<T, -1, -1 > & ,H5::H5File *, const std::string); template <typename T> typename std::enable_if<is_tt<std::complex, T>::value, void>::type write_hdf5(const Eigen::Array<T, -1, -1 > &, H5::H5File *, const std::string); template <typename T> typename std::enable_if<!is_tt<std::complex, T>::value, void>::type write_hdf5(T*, H5::H5File *, const std::string); template <typename T> typename std::enable_if<is_tt<std::complex, T>::value, void>::type write_hdf5(T*, H5::H5File *, const std::string); template <typename T> struct instantiateHDF { void write_hdf5A(const Eigen::Array<T, -1, -1 > &, H5::H5File *, const std::string); void write_hdf5A(T *, H5::H5File *, const std::string); void get_hdf5A(T *, H5::H5File *, std::string &); void get_hdf5A(T *, H5::H5File *, char *); };
/*************************************************************************** propiedades.h - description ------------------- begin : jue abr 24 2003 copyright : (C) 2003 by Oscar G. Duarte V. email : ogduarte@ing.unal.edu.co ***************************************************************************/ /*************************************************************************** * * * Este programa ha sido diseñado por Oscar G. Duarte V. por encargo del * * Departamento de Ciencias de la Computación e Inteligencia * * Artificial de la Universidad de Granada. * * * ***************************************************************************/ #ifndef PROPIEDADES_H #define PROPIEDADES_H #include <wx/wx.h> #include "mi_fstream.h" /** *Implementa parejas de cadenas de caracteres, para ser usados como propiedaes genéricas de Casos y/o Estrategias * ATENCION : Falta documentar * ATENCION : Falta manejo de archivos. */ class Propiedades { public: Propiedades(); ~Propiedades(); void adicionarPropiedad(const wxString &cad,int loc=-1); void eliminarPropiedad(int loc); void modificarValor(const wxString cad,int loc); void modificarValor(const wxString cad, const wxString prop); void modificarNombre(const wxString cad,int loc); void modificarNombre(const wxString cad, const wxString prop); wxString nombre(int loc); wxString valor(wxString pr); wxString valor(int loc); int tamano(); void limpiarPropiedades(); wxArrayString listaNombres(); wxArrayString listaValores(); void write(Mi_ofpstream &str); void read(Mi_ifpstream &str); void operator=(Propiedades& other); protected: wxArrayString NombresPropiedad; wxArrayString ValoresPropiedad; }; #endif
#include "expressions/subtraction_expression.hpp" #include "expressions/expression.hpp" #include "expressions/binary_expression.hpp" #include "expressions/operator.hpp" #include "expressions/scope.hpp" namespace flow { SubtractionExpression::SubtractionExpression(ExpressionPtr left, ExpressionPtr right) : BinaryExpression(OperatorID::E_SUB, left, right) { } gcc_jit_rvalue* SubtractionExpression::jit(gcc_jit_context *context, Scope &scope) { gcc_jit_rvalue *left_rval = m_left_child->jit(context, scope); gcc_jit_rvalue *right_rval = m_right_child->jit(context, scope); gcc_jit_type *result_type = gcc_jit_context_get_type(context, GCC_JIT_TYPE_LONG_LONG); gcc_jit_location *location = nullptr; gcc_jit_rvalue *result = gcc_jit_context_new_binary_op(context, location, GCC_JIT_BINARY_OP_MINUS, result_type, left_rval, right_rval); return result; } Result SubtractionExpression::eval(std::int64_t opt_arg) { Result left_result = m_left_child->eval(opt_arg); Result right_result = m_right_child->eval(opt_arg); Result r; r.type = ResultType::INT64; r.value.int64_value = left_result.value.int64_value - right_result.value.int64_value; return r; } }
#ifndef __MODULE_RENDER_3D_H__ #define __MODULE_RENDER_3D_H__ #include "Module.h" #include "Globals.h" #include "glmath.h" #include "Light.h" #include "RenderTexture.h" #define MAX_LIGHTS 8 struct SDL_Window; struct ImVec2; class ModuleRenderer3D : public Module { private: bool depth_test = false; bool cull_face = false; bool lighting = false; bool color_material = false; bool texture_2d = false; public: ModuleRenderer3D(const char* name, bool start_enabled = true); ~ModuleRenderer3D(); bool Init(JSONFile * module_file); void UpdateProjectionMatrix(); bool Start(JSONFile * module_file) override; update_status PreUpdate() override; update_status PostUpdate() override; bool CleanUp(); bool SaveConfiguration(JSONFile * module_file); bool LoadConfiguration(JSONFile * module_file); void OnResize(int width, int height); void DrawConfigurationUi(); public: Light lights[MAX_LIGHTS]; RenderTexture scene_fbo; RenderTexture game_fbo; friend class PanelConfiguration; }; #endif
#include <iostream> #include "simulation.h" #include "TCanvas.h" #include "TGraph.h" #include <vector> #include <cmath> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_airy.h> #include <gsl/gsl_sf_elementary.h> #include <gsl/gsl_sf_exp.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_trig.h> #include <gsl/gsl_sf_bessel.h> int main(int argc, char** argv){ //simulation exp; int N = 3; //int N = 50000; double diameter = 0.75e-5; double lambda = 500e-9; double c = 1; double i = 0; int k = 0; double* x_axis = new double[30]; double* y_axis = new double[30]; simulation exp(N,c,lambda,diameter); while(i<N){ y_axis[k]=exp.diffraction_fun(i); x_axis[k]=i; i +=0.1; k+=1; } TCanvas* c1 = new TCanvas("c","c",700,700); TGraph * g = new TGraph(30,x_axis,y_axis); g->Draw("APC"); c1->Draw(); c1->Print("./try.pdf","pdf"); return 0; }
#include "naive.h" //naive alogrithms // 遇到不匹配时,i ,j都回溯;j回溯至0,i回溯至 i-j+1 int NaiveMatch(const string &s, const string &t) { int i(0),j(0);//字符下标均从0开始 while( i<s.length() && j<t.length()) { if(s[i]==t[j])//两字符相等则继续匹配 { i++; j++; } else { // 若有模式串与主串遇到不匹配元素时,i , j需要都回溯 i = i-j+1; //i 退回至开始匹配的下一位置 j = 0; //j 退回首位 } } if(j>=t.length()) //匹配时,j最终为 t.length()-1) + 1 return i-j+1; else return 0; }
/* * Helloworld.cpp * * Created on: Nov 8, 2018 * Author: Akash Lohani */ #include <iostream> using namespace std; int main() { cout << "Hello, World!"; return 0; }
#include<bits/stdc++.h> using namespace std; int sqrtN; struct Query{ int s,e,idx; bool operator<(const Query& o) const { if(s/sqrtN == o.s/sqrtN) return e < o.e; return s/sqrtN < o.s/sqrtN; } }; int st[100010]; int n,k,a[100010]; long long ans=0; int get(int x){ int ret = 0; while(x > 0){ ret += st[x]; x -= (x & -x); } return ret; } void update(int x, int diff){ while(x <= 100000){ st[x] += diff; x += (x & -x); } } void add(int i){ ans += get( min(100000, a[i]+k) ); if(a[i]-k-1>0) ans -= get(a[i]-k-1); update(a[i], 1); } void del(int i){ update(a[i],-1); ans -= get( min(100000, a[i]+k) ); if(a[i]-k-1>0) ans += get(a[i]-k-1); } long long res[100010]; int main(){ scanf("%d %d",&n,&k); sqrtN = sqrt(n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); int m; scanf("%d",&m); vector<Query> Q(m); for(int i=0;i<m;i++){ int s,e; scanf("%d %d",&s,&e); Q[i] = {s,e,i}; } sort(Q.begin(),Q.end()); //for(int i=0;i<m;i++) printf("%d %d %d\n",Q[i].idx,Q[i].s,Q[i].e); int s = Q[0].s, e = Q[0].e; for(int i=s;i<=e;i++) add(i); res[Q[0].idx] = ans; for(int i=1;i<m;i++){ while(Q[i].s<s) add(--s); while(e<Q[i].e) add(++e); while(s<Q[i].s) del(s++); while(Q[i].e<e) del(e--); res[Q[i].idx] = ans; } for(int i=0;i<m;i++) printf("%lld\n",res[i]); }
// // TextureSheet.cpp // cheetah // // Copyright (c) 2013 cafaxo. All rights reserved. // #include "BufferManager.h" #include "TextureSheet.h" TextureSheet::TextureSheet(BufferManager &bufferManager, const std::string &fileName, const std::string &indexFileName) : Texture(bufferManager, fileName) { std::stringstream parsableData(Utils::readFile(indexFileName)); std::string line; while (std::getline(parsableData, line, '\n')) { std::stringstream parsableLine(line); std::string name; int x, y, width, height; parsableLine >> name >> x >> y >> width >> height; const float textureX = static_cast<float>(x) / mWidth; const float textureY = static_cast<float>(y) / mHeight; const float textureWidth = static_cast<float>(width) / mWidth; const float textureHeight = static_cast<float>(height) / mHeight; Buffer coordinates = bufferManager.create(16); coordinates.setData({ 0.f, 0.f, static_cast<float>(width), 0.f, static_cast<float>(width), static_cast<float>(height), 0.f, static_cast<float>(height), textureX, textureY, textureX + textureWidth, textureY, textureX + textureWidth, textureY + textureHeight, textureX, textureY + textureHeight }); coordinates.refresh(); mTextures.emplace(name, mId, static_cast<unsigned int>(width), static_cast<unsigned int>(height), coordinates); } }
//! @file ai.h //! @brief AIcontrolクラスの宣言 /** * LynxOPS * * Copyright (c) 2015 Nilpaca * * Licensed under the MIT License. * https://github.com/Nilpaca/LynxOPS/blob/master/LICENSE */ //-------------------------------------------------------------------------------- // // OpenXOPS // Copyright (c) 2014-2015, OpenXOPS Project / [-_-;](mikan) All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the OpenXOPS Project nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL OpenXOPS Project BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //-------------------------------------------------------------------------------- #ifndef AI_H #define AI_H #define AI_TOTALHUMAN_SCALE (MAX_HUMAN/24) //!< 24人あたりの最大人数の倍率 #define AI_ADDTURNRAD DegreeToRadian(0.8f) //!< AIの旋回(回転)能力 #define AI_SEARCH_RX DegreeToRadian(110) //!< 敵を発見する横軸角度 #define AI_SEARCH_RY DegreeToRadian(60) //!< 敵を発見する縦軸角度 #define AI_ARRIVALDIST_PATH 5.0f //!< パスに到達したと判定する距離 #define AI_ARRIVALDIST_TRACKING 18.0f //!< 追尾対象に到達したと判定する距離 #define AI_ARRIVALDIST_WALKTRACKING 24.0f //!< 追尾対象へ(走らずに)歩いて近づく距離 #define AI_CHECKJUMP_HEIGHT 0.3f //!< 前にブロックが無いか判定する高さ #define AI_CHECKJUMP_DIST 2.0f //!< 前にブロックが無いか判定する距離 #define AI_CHECKJUMP2_DIST 10.0f //!< 前にブロックが無いか判定する距離(優先的な走り) #define AI_CHECKBULLET 20.0f //!< 弾が近くを通ったと判定する距離 #ifndef H_LAYERLEVEL #define H_LAYERLEVEL 3 //!< Select include file. #endif #include "main.h" //! @brief AI制御を行うクラス //! @details パスによる移動、視野にいる敵への認識や攻撃、武器の使い分け などのAIの制御全般を行います class AIcontrol { class ObjectManager *ObjMgr; //!< ObjectManagerクラスのポインタ class BlockDataInterface *blocks; //!< ブロックデータを管理するクラスへのポインタ class PointDataInterface *Points; //!< ポイントデータを管理するクラスへのポインタ class ParameterInfo *Param; //!< 設定値を管理するクラスへのポインタ class Collision *CollD; //!< 当たり判定を管理するクラスへのポインタ class SoundManager *GameSound; //!< ゲーム効果音再生クラスへのポインタ int AIlevel; //!< AIレベル int battlemode; //!< 戦闘モード int movemode; //!< 移動モード bool hold; //!< 移動パスを読まない bool NoFight; //!< 非戦闘化フラグ float posx; //!< X座標 float posy; //!< Y座標 float posz; //!< Z座標 float rx; //!< X軸回転角度 float ry; //!< Y軸回転角度 float addrx; //!< X軸回転角加速度 float addry; //!< Y軸回転角加速度 int target_pointid; //!< パス系 ターゲットのデータ番号 float target_posx; //!< パス系 ターゲットのX座標 float target_posz; //!< パス系 ターゲットのZ座標 float target_rx; //!< パス系 ターゲットの水平角度 float total_move; //!< 合計移動量 int waitcnt; //!< 時間待ちカウント int movejumpcnt; //!< ジャンプ判定カウント int gotocnt; //!< 移動カウント int moveturn_mode; //!< 移動方向や回転方向のフラグ int cautioncnt; //!< 警戒中カウント int actioncnt; //!< 攻撃中カウント bool longattack; //!< 近距離・遠距離フラグ AIParameter *LevelParam; //!< AIの性能値 int SearchHumanPos(signed char in_p4, float *out_x, float *out_z); bool CheckTargetPos(); bool SearchTarget(bool next); void MoveTarget(); void MoveTarget2(); void MoveRandom(); void TurnSeen(); bool StopSeen(); bool MoveJump(); void Action(); bool ActionCancel(); int HaveWeapon(); void CancelMoveTurn(); void ControlMoveTurn(); int ControlWeapon(); int ThrowGrenade(); void ArmAngle(); int SearchEnemy(); int SearchShortEnemy(); bool CheckLookEnemy(int id, float search_rx, float search_ry, float maxDist, float *out_minDist); bool CheckLookEnemy(class human *thuman, float search_rx, float search_ry, float maxDist, float *out_minDist); bool CheckCorpse(int id); void MovePath(); bool ActionMain(); bool CautionMain(); bool NormalMain(); int ctrlid; //!< 自分自身(制御対象)の人番号 class human *ctrlhuman; //!< 自分自身(制御対象)のhumanクラス class human *enemyhuman; //!< 攻撃対象のhumanクラス public: AIcontrol(class ObjectManager *in_ObjMgr = NULL, int in_ctrlid = -1, class BlockDataInterface *in_blocks = NULL, class PointDataInterface *in_Points = NULL, class ParameterInfo *in_Param = NULL, class Collision *in_CollD = NULL, class SoundManager *in_GameSound = NULL); ~AIcontrol(); void SetClass(class ObjectManager *in_ObjMgr, int in_ctrlid, class BlockDataInterface *in_blocks, class PointDataInterface *in_Points, class ParameterInfo *in_Param, class Collision *in_CollD, class SoundManager *in_GameSound); void Init(); void SetHoldWait(float px, float pz, float rx); void SetHoldTracking(int id); void SetCautionMode(); void SetNoFightFlag(bool flag); void Process(); }; //! AIの制御モードを表す定数 enum AImode { AI_DEAD = 0, //!< 死亡している人 AI_ACTION, //!< 戦闘中の人 AI_CAUTION, //!< 警戒中の人 AI_NORMAL, //!< 通常のモード AI_WALK, //!< 移動パスによって歩いている人 AI_RUN, //!< 移動パスによって走っている人 AI_WAIT, //!< パスによって待機している人 AI_STOP, //!< パスによって時間待ちをしている人 AI_TRACKING, //!< 特定の人を追尾する AI_GRENADE, //!< 手榴弾を投げる AI_RUN2, //!< 優先的な走り AI_RANDOM, //!< ランダムパス処理中 AI_NULL //!< パスなし }; //! AIの操作モードを表す定数 enum AIcontrolFlag { AI_CTRL_MOVEFORWARD = 0x0001, AI_CTRL_MOVEBACKWARD = 0x0002, AI_CTRL_MOVELEFT = 0x0004, AI_CTRL_MOVERIGHT = 0x0008, AI_CTRL_MOVEWALK = 0x0010, AI_CTRL_TURNUP = 0x0100, AI_CTRL_TURNDOWN = 0x0200, AI_CTRL_TURNLEFT = 0x0400, AI_CTRL_TURNRIGHT = 0x0800 }; #endif
/* * Copyright (C) 2015 The Android Open Source Project * * 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. */ #define LOG_NDEBUG 0 #define LOG_TAG "IFingerprintDaemonCallback" #include <stdint.h> #include <sys/types.h> #include <utils/Log.h> #include <binder/Parcel.h> #include "IFingerprintDaemonCallback.h" namespace android { status_t BnFingerprintDaemonCallback::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch (code) { case ON_ENROLL_RESULT: { CHECK_INTERFACE(IFingerprintDaemonCallback, data, reply); int64_t devId = data.readInt64(); int32_t fpId = data.readInt32(); int32_t gpId = data.readInt32(); int32_t rem = data.readInt32(); onEnrollResult(devId, fpId, gpId, rem); return NO_ERROR; } case ON_ACQUIRED: { CHECK_INTERFACE(IFingerprintDaemonCallback, data, reply); int64_t devId = data.readInt64(); int32_t acquiredInfo = data.readInt32(); onAcquired(devId, acquiredInfo); return NO_ERROR; } case ON_AUTHENTICATED: { CHECK_INTERFACE(IFingerprintDaemonCallback, data, reply); int64_t devId = data.readInt64(); int32_t fpId = data.readInt32(); int32_t gpId = data.readInt32(); onAuthenticated(devId, fpId, gpId); return NO_ERROR; } case ON_ERROR: { CHECK_INTERFACE(IFingerprintDaemonCallback, data, reply); int64_t devId = data.readInt64(); int32_t error = data.readInt32(); onError(devId, error); return NO_ERROR; } case ON_REMOVED: { CHECK_INTERFACE(IFingerprintDaemonCallback, data, reply); int64_t devId = data.readInt64(); int32_t fpId = data.readInt32(); int32_t gpId = data.readInt32(); onRemoved(devId, fpId, gpId); return NO_ERROR; } case ON_ENUMERATE: { CHECK_INTERFACE(IFingerprintDaemonCallback, data, reply); int64_t devId = data.readInt64(); int32_t fpId = data.readInt32(); int32_t gpId = data.readInt32(); int32_t rem = data.readInt32(); onEnumerate(devId, fpId, gpId, rem); return NO_ERROR; } default: return BBinder::onTransact(code, data, reply, flags); } } class BpFingerprintDaemonCallback : public BpInterface<IFingerprintDaemonCallback> { public: BpFingerprintDaemonCallback(const sp<IBinder>& impl) : BpInterface<IFingerprintDaemonCallback>(impl) { } virtual status_t onEnrollResult(int64_t devId, int32_t fpId, int32_t gpId, int32_t rem) { Parcel data, reply; data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor()); data.writeInt64(devId); data.writeInt32(fpId); data.writeInt32(gpId); data.writeInt32(rem); return remote()->transact(ON_ENROLL_RESULT, data, &reply, IBinder::FLAG_ONEWAY); } virtual status_t onAcquired(int64_t devId, int32_t acquiredInfo) { Parcel data, reply; data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor()); data.writeInt64(devId); data.writeInt32(acquiredInfo); return remote()->transact(ON_ACQUIRED, data, &reply, IBinder::FLAG_ONEWAY); } virtual status_t onAuthenticated(int64_t devId, int32_t fpId, int32_t gpId) { Parcel data, reply; data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor()); data.writeInt64(devId); data.writeInt32(fpId); data.writeInt32(gpId); return remote()->transact(ON_AUTHENTICATED, data, &reply, IBinder::FLAG_ONEWAY); } virtual status_t onError(int64_t devId, int32_t error) { Parcel data, reply; data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor()); data.writeInt64(devId); data.writeInt32(error); return remote()->transact(ON_ERROR, data, &reply, IBinder::FLAG_ONEWAY); } virtual status_t onRemoved(int64_t devId, int32_t fpId, int32_t gpId) { Parcel data, reply; data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor()); data.writeInt64(devId); data.writeInt32(fpId); data.writeInt32(gpId); return remote()->transact(ON_REMOVED, data, &reply, IBinder::FLAG_ONEWAY); } virtual status_t onEnumerate(int64_t devId, int32_t fpId, int32_t gpId, int32_t rem) { Parcel data, reply; data.writeInterfaceToken(IFingerprintDaemonCallback::getInterfaceDescriptor()); data.writeInt64(devId); data.writeInt32(fpId); data.writeInt32(gpId); data.writeInt32(rem); return remote()->transact(ON_ENUMERATE, data, &reply, IBinder::FLAG_ONEWAY); } }; IMPLEMENT_META_INTERFACE(FingerprintDaemonCallback, "android.hardware.fingerprint.IFingerprintDaemonCallback"); }; // namespace android
#include<bits/stdc++.h> using namespace std; int solve1(int* arr,int n,int k) { if(k==0) { return 0; } if(k < 0) { return -1; } int max_ = INT_MIN; for(int i=0;i<n;i++) { int temp = solve1(arr,n,k-arr[i]); if(temp==-1) { continue; } max_ = max(max_,temp+1); } return max_; } // iterative o(n*n) int solve(int* arr,int n,int k) { vector<int> dp(k+1,-1); dp[0]=0; for(int i=1;i<=k;i++) { for(int j=0;j<n;j++) { int temp = i - arr[j]; if(temp >=0 ) { if(dp[temp]==-1) { continue;//invalid cut } dp[i]=max(dp[i],dp[temp]+1); } } } return dp[k]; } int main() { int n; cin >> n; int k; cin >> k; int min_value = INT_MAX; int* arr = new int[n]; for(int i=0;i<n;i++) { cin >> arr[i]; min_value = min(min_value,arr[i]); } cout << solve1(arr,n,k) << endl; cout << solve(arr,n,k) << endl; return 0; }
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package #ifndef JACTORIO_INCLUDE_GAME_WORLD_CHUNK_H #define JACTORIO_INCLUDE_GAME_WORLD_CHUNK_H #pragma once #include <array> #include <limits> #include <vector> #include "jactorio.h" #include "data/cereal/serialize.h" #include "game/world/chunk_tile.h" #include "game/world/overlay_element.h" #include "game/world/tile_layer.h" #include <cereal/types/array.hpp> #include <cereal/types/vector.hpp> namespace jactorio::game { /// A chunk within the game /// /// Made up of tiles and objects: /// tiles: Has 32 x 32, fixed grid location /// overlays: Has no set amount, can exist anywhere on chunk class Chunk { public: using OverlayContainerT = std::vector<OverlayElement>; using LogicGroupContainerT = std::vector<ChunkTile*>; static constexpr uint8_t kChunkWidth = 32; static constexpr uint16_t kChunkArea = static_cast<uint16_t>(kChunkWidth) * kChunkWidth; private: using TileArrayT = std::array<ChunkTile, kChunkArea>; using OverlayArrayT = std::array<OverlayContainerT, kOverlayLayerCount>; public: /// \remark For cereal deserialization only Chunk() = default; /// Default initialization of chunk tiles explicit Chunk(const ChunkCoord& c_coord) : position_(c_coord) {} J_NODISCARD static ChunkTileCoordAxis WorldCToChunkTileC(WorldCoordAxis coord); J_NODISCARD static ChunkTileCoord WorldCToChunkTileC(const WorldCoord& coord); J_NODISCARD ChunkCoord GetPosition() const { return position_; } /// Tiles at provided tlayer J_NODISCARD TileArrayT& Tiles(TileLayer tlayer) noexcept; J_NODISCARD const TileArrayT& Tiles(TileLayer tlayer) const noexcept; /// Gets tile at x, y offset from top left of chunk J_NODISCARD ChunkTile& GetCTile(const ChunkTileCoord& coord, TileLayer tlayer) noexcept; J_NODISCARD const ChunkTile& GetCTile(const ChunkTileCoord& coord, TileLayer tlayer) const noexcept; // Overlays - Rendered without being fixed to a tile position OverlayContainerT& GetOverlay(OverlayLayer layer); J_NODISCARD const OverlayContainerT& GetOverlay(OverlayLayer layer) const; CEREAL_SERIALIZE(archive) { archive(position_, layers_); } OverlayArrayT overlays; private: ChunkCoord position_; std::array<TileArrayT, kTileLayerCount> layers_; }; } // namespace jactorio::game #endif // JACTORIO_INCLUDE_GAME_WORLD_CHUNK_H
#include "flipLogic.h" #include <iostream> #include <string> #include <cassert> #include <climits> void test_basic1(); void test_basic2(); void test_basic3(); void test_cannot_flip(); using namespace std; int main() { test_basic1(); test_basic2(); test_basic3(); test_cannot_flip(); } static void test_template(string logicStr, int min_num) { TreeNode* root = construct_logicTree(logicStr); int actual_num = root -> flipLogic(); cout << "Expected flip times: " << min_num << endl; cout << "Actual flip times: " << actual_num << endl; delete root; assert(min_num == actual_num); cout << "PASS" << endl; } void test_basic1() { test_template("|| && True False || True False", 1); } void test_basic2() { test_template("&& && True False && False False", 2); } void test_basic3() { test_template("&& || && True False False && False False", 2); } void test_cannot_flip() { test_template("&& || && False False False && False False", INT_MAX); }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.Perception.Spatial.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_cdb5efb3_5788_509d_9be1_71ccb8a3362a #define WINRT_GENERIC_cdb5efb3_5788_509d_9be1_71ccb8a3362a template <> struct __declspec(uuid("cdb5efb3-5788-509d-9be1-71ccb8a3362a")) __declspec(novtable) IAsyncOperation<bool> : impl_IAsyncOperation<bool> {}; #endif #ifndef WINRT_GENERIC_c50898f6_c536_5f47_8583_8b2c2438a13b #define WINRT_GENERIC_c50898f6_c536_5f47_8583_8b2c2438a13b template <> struct __declspec(uuid("c50898f6-c536-5f47-8583-8b2c2438a13b")) __declspec(novtable) EventHandler<Windows::Foundation::IInspectable> : impl_EventHandler<Windows::Foundation::IInspectable> {}; #endif #ifndef WINRT_GENERIC_2f2d6c29_5473_5f3e_92e7_96572bb990e2 #define WINRT_GENERIC_2f2d6c29_5473_5f3e_92e7_96572bb990e2 template <> struct __declspec(uuid("2f2d6c29-5473-5f3e-92e7-96572bb990e2")) __declspec(novtable) IReference<double> : impl_IReference<double> {}; #endif #ifndef WINRT_GENERIC_dacbffdc_68ef_5fd0_b657_782d0ac9807e #define WINRT_GENERIC_dacbffdc_68ef_5fd0_b657_782d0ac9807e template <> struct __declspec(uuid("dacbffdc-68ef-5fd0-b657-782d0ac9807e")) __declspec(novtable) IReference<Windows::Foundation::Numerics::float4x4> : impl_IReference<Windows::Foundation::Numerics::float4x4> {}; #endif #ifndef WINRT_GENERIC_fa43f9e4_3558_59c8_9a77_6e8b765adcc8 #define WINRT_GENERIC_fa43f9e4_3558_59c8_9a77_6e8b765adcc8 template <> struct __declspec(uuid("fa43f9e4-3558-59c8-9a77-6e8b765adcc8")) __declspec(novtable) TypedEventHandler<Windows::Perception::Spatial::SpatialAnchor, Windows::Perception::Spatial::SpatialAnchorRawCoordinateSystemAdjustedEventArgs> : impl_TypedEventHandler<Windows::Perception::Spatial::SpatialAnchor, Windows::Perception::Spatial::SpatialAnchorRawCoordinateSystemAdjustedEventArgs> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_2d344564_21b1_5470_b013_488cdde45c48 #define WINRT_GENERIC_2d344564_21b1_5470_b013_488cdde45c48 template <> struct __declspec(uuid("2d344564-21b1-5470-b013-488cdde45c48")) __declspec(novtable) IMapView<hstring, Windows::Perception::Spatial::SpatialAnchor> : impl_IMapView<hstring, Windows::Perception::Spatial::SpatialAnchor> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_1cd05e51_1457_5023_8f5d_fe5e5a953423 #define WINRT_GENERIC_1cd05e51_1457_5023_8f5d_fe5e5a953423 template <> struct __declspec(uuid("1cd05e51-1457-5023-8f5d-fe5e5a953423")) __declspec(novtable) IAsyncOperation<Windows::Perception::Spatial::SpatialAnchorStore> : impl_IAsyncOperation<Windows::Perception::Spatial::SpatialAnchorStore> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_627298e7_068d_53f6_9154_d7d8d8091463 #define WINRT_GENERIC_627298e7_068d_53f6_9154_d7d8d8091463 template <> struct __declspec(uuid("627298e7-068d-53f6-9154-d7d8d8091463")) __declspec(novtable) IKeyValuePair<hstring, Windows::Perception::Spatial::SpatialAnchor> : impl_IKeyValuePair<hstring, Windows::Perception::Spatial::SpatialAnchor> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_b425d126_1069_563f_a863_44a30a8f071d #define WINRT_GENERIC_b425d126_1069_563f_a863_44a30a8f071d template <> struct __declspec(uuid("b425d126-1069-563f-a863-44a30a8f071d")) __declspec(novtable) IAsyncOperation<winrt::Windows::Perception::Spatial::SpatialPerceptionAccessStatus> : impl_IAsyncOperation<winrt::Windows::Perception::Spatial::SpatialPerceptionAccessStatus> {}; #endif #ifndef WINRT_GENERIC_dbb08ab5_6b40_55fb_83d3_50d5373a3b20 #define WINRT_GENERIC_dbb08ab5_6b40_55fb_83d3_50d5373a3b20 template <> struct __declspec(uuid("dbb08ab5-6b40-55fb-83d3-50d5373a3b20")) __declspec(novtable) TypedEventHandler<Windows::Perception::Spatial::SpatialLocator, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Perception::Spatial::SpatialLocator, Windows::Foundation::IInspectable> {}; #endif #ifndef WINRT_GENERIC_34bf236c_e5d6_501f_8693_bc1d8d431d7e #define WINRT_GENERIC_34bf236c_e5d6_501f_8693_bc1d8d431d7e template <> struct __declspec(uuid("34bf236c-e5d6-501f-8693-bc1d8d431d7e")) __declspec(novtable) TypedEventHandler<Windows::Perception::Spatial::SpatialLocator, Windows::Perception::Spatial::SpatialLocatorPositionalTrackingDeactivatingEventArgs> : impl_TypedEventHandler<Windows::Perception::Spatial::SpatialLocator, Windows::Perception::Spatial::SpatialLocatorPositionalTrackingDeactivatingEventArgs> {}; #endif #ifndef WINRT_GENERIC_b4d8b1bf_1d66_5458_a5df_3f4f6c366c58 #define WINRT_GENERIC_b4d8b1bf_1d66_5458_a5df_3f4f6c366c58 template <> struct __declspec(uuid("b4d8b1bf-1d66-5458-a5df-3f4f6c366c58")) __declspec(novtable) IAsyncOperation<Windows::Perception::Spatial::SpatialStageFrameOfReference> : impl_IAsyncOperation<Windows::Perception::Spatial::SpatialStageFrameOfReference> {}; #endif #ifndef WINRT_GENERIC_f8edae01_6a30_52cc_b543_8abdb26529b4 #define WINRT_GENERIC_f8edae01_6a30_52cc_b543_8abdb26529b4 template <> struct __declspec(uuid("f8edae01-6a30-52cc-b543-8abdb26529b4")) __declspec(novtable) TypedEventHandler<Windows::Perception::Spatial::SpatialEntityWatcher, Windows::Perception::Spatial::SpatialEntityAddedEventArgs> : impl_TypedEventHandler<Windows::Perception::Spatial::SpatialEntityWatcher, Windows::Perception::Spatial::SpatialEntityAddedEventArgs> {}; #endif #ifndef WINRT_GENERIC_a15fd0c0_8a0a_5a7d_897a_f206cc509190 #define WINRT_GENERIC_a15fd0c0_8a0a_5a7d_897a_f206cc509190 template <> struct __declspec(uuid("a15fd0c0-8a0a-5a7d-897a-f206cc509190")) __declspec(novtable) TypedEventHandler<Windows::Perception::Spatial::SpatialEntityWatcher, Windows::Perception::Spatial::SpatialEntityUpdatedEventArgs> : impl_TypedEventHandler<Windows::Perception::Spatial::SpatialEntityWatcher, Windows::Perception::Spatial::SpatialEntityUpdatedEventArgs> {}; #endif #ifndef WINRT_GENERIC_36f982ad_eaa2_5263_861e_2acf030c9e17 #define WINRT_GENERIC_36f982ad_eaa2_5263_861e_2acf030c9e17 template <> struct __declspec(uuid("36f982ad-eaa2-5263-861e-2acf030c9e17")) __declspec(novtable) TypedEventHandler<Windows::Perception::Spatial::SpatialEntityWatcher, Windows::Perception::Spatial::SpatialEntityRemovedEventArgs> : impl_TypedEventHandler<Windows::Perception::Spatial::SpatialEntityWatcher, Windows::Perception::Spatial::SpatialEntityRemovedEventArgs> {}; #endif #ifndef WINRT_GENERIC_50171823_30a9_5938_9f3b_358d86169f2e #define WINRT_GENERIC_50171823_30a9_5938_9f3b_358d86169f2e template <> struct __declspec(uuid("50171823-30a9-5938-9f3b-358d86169f2e")) __declspec(novtable) TypedEventHandler<Windows::Perception::Spatial::SpatialEntityWatcher, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Perception::Spatial::SpatialEntityWatcher, Windows::Foundation::IInspectable> {}; #endif #ifndef WINRT_GENERIC_c1d3d1a2_ae17_5a5f_b5a2_bdcc8844889a #define WINRT_GENERIC_c1d3d1a2_ae17_5a5f_b5a2_bdcc8844889a template <> struct __declspec(uuid("c1d3d1a2-ae17-5a5f-b5a2-bdcc8844889a")) __declspec(novtable) AsyncOperationCompletedHandler<bool> : impl_AsyncOperationCompletedHandler<bool> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_25298593_9baf_5a73_a1b6_cd5e40a5e834 #define WINRT_GENERIC_25298593_9baf_5a73_a1b6_cd5e40a5e834 template <> struct __declspec(uuid("25298593-9baf-5a73-a1b6-cd5e40a5e834")) __declspec(novtable) IMap<hstring, Windows::Perception::Spatial::SpatialAnchor> : impl_IMap<hstring, Windows::Perception::Spatial::SpatialAnchor> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_84c21a3a_037a_503f_8006_ab577b7f6f66 #define WINRT_GENERIC_84c21a3a_037a_503f_8006_ab577b7f6f66 template <> struct __declspec(uuid("84c21a3a-037a-503f-8006-ab577b7f6f66")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Perception::Spatial::SpatialAnchorStore> : impl_AsyncOperationCompletedHandler<Windows::Perception::Spatial::SpatialAnchorStore> {}; #endif #ifndef WINRT_GENERIC_6ced54c8_7689_525a_80e1_956a9d85cd83 #define WINRT_GENERIC_6ced54c8_7689_525a_80e1_956a9d85cd83 template <> struct __declspec(uuid("6ced54c8-7689-525a-80e1-956a9d85cd83")) __declspec(novtable) AsyncOperationCompletedHandler<winrt::Windows::Perception::Spatial::SpatialPerceptionAccessStatus> : impl_AsyncOperationCompletedHandler<winrt::Windows::Perception::Spatial::SpatialPerceptionAccessStatus> {}; #endif #ifndef WINRT_GENERIC_fbb7e9fb_e49a_54e1_8c83_d1a87e4d2304 #define WINRT_GENERIC_fbb7e9fb_e49a_54e1_8c83_d1a87e4d2304 template <> struct __declspec(uuid("fbb7e9fb-e49a-54e1-8c83-d1a87e4d2304")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Perception::Spatial::SpatialStageFrameOfReference> : impl_AsyncOperationCompletedHandler<Windows::Perception::Spatial::SpatialStageFrameOfReference> {}; #endif #ifndef WINRT_GENERIC_bbe07728_da33_52c5_aae0_a5e74cdf0471 #define WINRT_GENERIC_bbe07728_da33_52c5_aae0_a5e74cdf0471 template <> struct __declspec(uuid("bbe07728-da33-52c5-aae0-a5e74cdf0471")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IMapView<hstring, Windows::Perception::Spatial::SpatialAnchor>> : impl_IAsyncOperation<Windows::Foundation::Collections::IMapView<hstring, Windows::Perception::Spatial::SpatialAnchor>> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_55f0fa8a_afd4_5541_a1c3_36f12147d606 #define WINRT_GENERIC_55f0fa8a_afd4_5541_a1c3_36f12147d606 template <> struct __declspec(uuid("55f0fa8a-afd4-5541-a1c3-36f12147d606")) __declspec(novtable) IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Perception::Spatial::SpatialAnchor>> : impl_IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Perception::Spatial::SpatialAnchor>> {}; #endif #ifndef WINRT_GENERIC_67a5f318_0232_5900_ac7e_5c647d731cbc #define WINRT_GENERIC_67a5f318_0232_5900_ac7e_5c647d731cbc template <> struct __declspec(uuid("67a5f318-0232-5900-ac7e-5c647d731cbc")) __declspec(novtable) IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Perception::Spatial::SpatialAnchor>> : impl_IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Perception::Spatial::SpatialAnchor>> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_3a950aa3_9c65_586e_af75_1acf07190e90 #define WINRT_GENERIC_3a950aa3_9c65_586e_af75_1acf07190e90 template <> struct __declspec(uuid("3a950aa3-9c65-586e-af75-1acf07190e90")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IMapView<hstring, Windows::Perception::Spatial::SpatialAnchor>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IMapView<hstring, Windows::Perception::Spatial::SpatialAnchor>> {}; #endif } namespace Windows::Perception::Spatial { struct ISpatialAnchor : Windows::Foundation::IInspectable, impl::consume<ISpatialAnchor> { ISpatialAnchor(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialAnchor2 : Windows::Foundation::IInspectable, impl::consume<ISpatialAnchor2> { ISpatialAnchor2(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialAnchorManagerStatics : Windows::Foundation::IInspectable, impl::consume<ISpatialAnchorManagerStatics> { ISpatialAnchorManagerStatics(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialAnchorRawCoordinateSystemAdjustedEventArgs : Windows::Foundation::IInspectable, impl::consume<ISpatialAnchorRawCoordinateSystemAdjustedEventArgs> { ISpatialAnchorRawCoordinateSystemAdjustedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialAnchorStatics : Windows::Foundation::IInspectable, impl::consume<ISpatialAnchorStatics> { ISpatialAnchorStatics(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialAnchorStore : Windows::Foundation::IInspectable, impl::consume<ISpatialAnchorStore> { ISpatialAnchorStore(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialAnchorTransferManagerStatics : Windows::Foundation::IInspectable, impl::consume<ISpatialAnchorTransferManagerStatics> { ISpatialAnchorTransferManagerStatics(std::nullptr_t = nullptr) noexcept {} }; struct [[deprecated("Use SpatialEntityStore instead of SpatialAnchorTransferManager. For more info, see MSDN.")]] ISpatialAnchorTransferManagerStatics; struct ISpatialBoundingVolume : Windows::Foundation::IInspectable, impl::consume<ISpatialBoundingVolume> { ISpatialBoundingVolume(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialBoundingVolumeStatics : Windows::Foundation::IInspectable, impl::consume<ISpatialBoundingVolumeStatics> { ISpatialBoundingVolumeStatics(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialCoordinateSystem : Windows::Foundation::IInspectable, impl::consume<ISpatialCoordinateSystem> { ISpatialCoordinateSystem(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialEntity : Windows::Foundation::IInspectable, impl::consume<ISpatialEntity> { ISpatialEntity(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialEntityAddedEventArgs : Windows::Foundation::IInspectable, impl::consume<ISpatialEntityAddedEventArgs> { ISpatialEntityAddedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialEntityFactory : Windows::Foundation::IInspectable, impl::consume<ISpatialEntityFactory> { ISpatialEntityFactory(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialEntityRemovedEventArgs : Windows::Foundation::IInspectable, impl::consume<ISpatialEntityRemovedEventArgs> { ISpatialEntityRemovedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialEntityStore : Windows::Foundation::IInspectable, impl::consume<ISpatialEntityStore> { ISpatialEntityStore(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialEntityStoreStatics : Windows::Foundation::IInspectable, impl::consume<ISpatialEntityStoreStatics> { ISpatialEntityStoreStatics(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialEntityUpdatedEventArgs : Windows::Foundation::IInspectable, impl::consume<ISpatialEntityUpdatedEventArgs> { ISpatialEntityUpdatedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialEntityWatcher : Windows::Foundation::IInspectable, impl::consume<ISpatialEntityWatcher> { ISpatialEntityWatcher(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialLocation : Windows::Foundation::IInspectable, impl::consume<ISpatialLocation> { ISpatialLocation(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialLocator : Windows::Foundation::IInspectable, impl::consume<ISpatialLocator> { ISpatialLocator(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialLocatorAttachedFrameOfReference : Windows::Foundation::IInspectable, impl::consume<ISpatialLocatorAttachedFrameOfReference> { ISpatialLocatorAttachedFrameOfReference(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialLocatorPositionalTrackingDeactivatingEventArgs : Windows::Foundation::IInspectable, impl::consume<ISpatialLocatorPositionalTrackingDeactivatingEventArgs> { ISpatialLocatorPositionalTrackingDeactivatingEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialLocatorStatics : Windows::Foundation::IInspectable, impl::consume<ISpatialLocatorStatics> { ISpatialLocatorStatics(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialStageFrameOfReference : Windows::Foundation::IInspectable, impl::consume<ISpatialStageFrameOfReference> { ISpatialStageFrameOfReference(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialStageFrameOfReferenceStatics : Windows::Foundation::IInspectable, impl::consume<ISpatialStageFrameOfReferenceStatics> { ISpatialStageFrameOfReferenceStatics(std::nullptr_t = nullptr) noexcept {} }; struct ISpatialStationaryFrameOfReference : Windows::Foundation::IInspectable, impl::consume<ISpatialStationaryFrameOfReference> { ISpatialStationaryFrameOfReference(std::nullptr_t = nullptr) noexcept {} }; } }
#include "Player.h" Player::Player(const LoaderParams* pParams) : SDLGameObject(pParams) {} void Player::draw() { m_currentFrame = 0; //m_currentFrame = int(((SDL_GetTicks() / 100) % 5)); if (m_velocity.getX() < 0) { TextureManager::Instance()->drawFrame(m_textureID, (Uint32)m_position.getX(), (Uint32)m_position.getY(), m_width, m_height, m_currentRow, m_currentFrame, TheGame::Instance()->getRenderer(), SDL_FLIP_HORIZONTAL); } else { TextureManager::Instance()->drawFrame(m_textureID, (Uint32)m_position.getX(), (Uint32)m_position.getY(), m_width, m_height, m_currentRow, m_currentFrame, TheGame::Instance()->getRenderer()); } } void Player::Walk() { //if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RIGHT)) { // m_velocity.setX(4); // m_currentFrame = int((SDL_GetTicks() / 100) % 9); //} //if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LEFT)) { // m_velocity.setX(-4); // m_currentFrame = int((SDL_GetTicks() / 100) % 9); //} ///*if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_UP)) { // m_velocity.setY(-2); //}*/ ///*if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_DOWN)) { // m_velocity.setY(2); //}*/ } void Player::Jump() { //if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_UP) && jumpKeyDown == false) { // m_position.setY(m_position.getY() - 180); // //m_acceleration.setY(-1); // jumpKeyDown = true; //} //if (!TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_UP)) //{ // jumpKeyDown = false; //} } void Player::clean() { } void Player::clear() { } void Player::update() { }
#include "SDLSoundAPI.h" #include <string> #include <iostream> SDLSoundAPI::SDLSoundAPI() { Mix_Init(0); if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096)) { std::cout << Mix_GetError(); } loadMap(); } SDLSoundAPI::~SDLSoundAPI() { stopMusic(); Mix_Quit(); } void SDLSoundAPI::loadMap() { soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::INCREASE_SIZE, "INCREASE_SIZE.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::DECREASE_SIZE, "DECREASE_SIZE.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::BOUNCE, "BOUNCE.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::BOUNCE2, "BOUNCE2.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::NEW_BALL, "NEW_BALL.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::RED_BALL, "RED_BALL.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::KILLER_BALL, "KILLER_BALL.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::DEATH, "DEATH.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::MOVEMENT, "MOVEMENT.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::PLAYER, "PLAYER.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::NEW_GAME, "NEW_GAME.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::HIGH_SCORE, "HIGH_SCORE.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::HIGH_SCORE, "HIGH_SCORE.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::MUSIC, "MUSIC_01.wav")); soundMap.insert(std::pair<SOUND_TYPE, string>(SOUND_TYPE::GAME_MUSIC, "GAME_MUSIC.wav")); } void SDLSoundAPI::playSound(ISoundAPI::SOUND_TYPE sound) { string soundFile = "../sound/" + soundMap.at(sound); Mix_Chunk * soundEffect = Mix_LoadWAV(soundFile.c_str()); if (soundEffect == NULL) throw std::runtime_error("could not load " + soundFile); Mix_PlayChannel(-1, soundEffect, 0); } void SDLSoundAPI::startMusic(SOUND_TYPE music) { if (Mix_PlayingMusic() == 0) { string soundFile = "../sound/" + soundMap.at(music); Mix_Music * musicToPlay = Mix_LoadMUS(soundFile.c_str()); if (musicToPlay == NULL) throw std::runtime_error("could not load " + soundFile); Mix_PlayMusic(musicToPlay, -1); } } void SDLSoundAPI::stopMusic() { Mix_HaltMusic(); }
#include <iostream> #include <omp.h> #include <Eigen/Dense> #include <H5Cpp.h> #include <H5Group.h> #include <chrono> #include "general.hpp" #include "kpm_vector.hpp" #include "aux.hpp" #include "hamiltonian.hpp" #include "cheb.hpp" #include "ComplexTraits.hpp" #include "myHDF5.hpp" #define NUM_MOMENTS 2000 int main(){ unsigned nx, ny, n_threads; nx = NX_T; ny = NY_T; n_threads = nx*ny; unsigned Norb = 2; omp_set_num_threads(n_threads); // (in order) upper left (ul), upper right (ur), down left (dl), down right (dr) // (in order) left, right, up, down T ***corners; Eigen::Array<T, -1, -1> ***sides; corners = new T**[n_threads]; sides = new Eigen::Array<T, -1, -1>**[n_threads]; for(unsigned t = 0; t < n_threads; t++){ corners[t] = new T*[Norb]; sides[t] = new Eigen::Array<T, -1, -1>*[Norb]; for(unsigned orb = 0; orb < Norb; orb++){ corners[t][orb] = new T[4]; sides[t][orb] = new Eigen::Array<T, -1, -1>[4]; } } Eigen::Array<TR, -1, -1> MU; MU = Eigen::Array<TR, -1, -1>::Zero(NUM_MOMENTS, 1); #pragma omp parallel shared(corners, sides, MU) { unsigned id = omp_get_thread_num(); unsigned Lx, Ly; unsigned mult; mult = 1; Lx = 15; Ly = 17; unsigned size_y = Ly/double(ny) + 0.9; unsigned size_x = Lx/double(nx) + 0.9; unsigned lx, ly, Norb; unsigned tx, ty; Norb = 2; tx = id%nx; ty = id/nx; ly = std::min(size_y, Ly - ty*size_y); lx = std::min(size_x, Lx - tx*size_x); //#pragma omp barrier //#pragma omp critical //{ //std::cout << "sizes: " << size_x << " " << size_y << "\n" << std::flush; //std::cout << "lx,ly: " << lx << " " << ly << "\n" << std::flush; //std::cout << "id:" << id << " tx,ty:" << tx << " " << ty << "\n" << std::flush; //} #pragma omp barrier Eigen::Matrix<int, 2, 2> gauge_matrix; int min_flux; int M12, M21; extended_euclidean(Lx, Ly, &M12, &M21, &min_flux); gauge_matrix(0,0) = 0; gauge_matrix(1,1) = 0; gauge_matrix(0,1) = -M12*mult; gauge_matrix(1,0) = M21*mult; //#pragma omp barrier //#pragma omp critical //{ //std::cout << min_flux << " \n" << gauge_matrix << "\n\n"<< std::flush; //} //#pragma omp barrier hamiltonian H; double W = 0.0; H.set_geometry(lx, ly); H.Lattice_Lx = Lx; H.Lattice_Ly = Ly; H.N_threads_x = nx; H.N_threads_y = ny; H.set_regular_hoppings(); H.set_anderson_W(W); H.set_anderson(); H.set_peierls(gauge_matrix); chebinator C; C.n_threads_x = NX_T; C.n_threads_y = NY_T; C.corners = corners; C.sides = sides; C.set_hamiltonian(&H); // There two are not required for the computation, but are used // to obtain output information about the program C.set_seed(1*n_threads + id); C.set_mult(1); C.cheb_iteration(NUM_MOMENTS, 1, 1); #pragma omp barrier #pragma omp critical { MU += C.mu.real()/n_threads; } #pragma omp barrier } Eigen::Array<TR, -1, -1> dos_list; Eigen::Array<TR, -1, -1> energies; //std::cout << "MU:\n" << MU << "\n"; double lim = 0.99; unsigned N_Energies = 5000; energies = Eigen::Array<TR, -1, 1>::LinSpaced(N_Energies, -lim, lim); dos_list = calc_dos(MU, energies, "jackson"); std::cout << "##################\n"; for(unsigned i = 0; i < N_Energies; i++){ std::cout << energies(i)*SCALE << " " << dos_list(i) << "\n"; } for(unsigned t = 0; t < n_threads; t++){ for(unsigned orb = 0; orb < Norb; orb++){ delete []corners[t][orb]; delete []sides[t][orb]; } delete []corners[t]; delete []sides[t]; } delete []corners; delete []sides; return 0; }
// github.com/andy489 #include<bits/stdc++.h> using namespace std; stack <int> s; stack <string> history; int main(){ int n, query, k; string elem, S; cin >> n; while(n--){ cin >> query; if (query == 1){ // append string w to S cin >> elem; history.push(S); S = S.append(elem); } else if (query == 2){ // erase last k characters from S cin >> k; history.push(S); S = S.substr(0,S.size() - k); } else if (query == 3){ // returns the kth character cin >> k; cout << S[k - 1] << endl; } else if (query == 4){ // undo the last operation of type [1,2] S = history.top(); history.pop(); } } return 0; }
#ifndef LSIMBDD3_H #define LSIMBDD3_H /// @file LsimBdd3.h /// @brief LsimBdd3 のヘッダファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2005-2011 Yusuke Matsunaga /// All rights reserved. #include "Lsim.h" #include "YmLogic/Bdd.h" #include "YmLogic/BddMgr.h" BEGIN_NAMESPACE_YM ////////////////////////////////////////////////////////////////////// /// @class LsimBdd3 LsimBdd3.h "LsimBdd3.h" /// @brief BDD を用いた Lsim の実装 ////////////////////////////////////////////////////////////////////// class LsimBdd3 : public Lsim { public: /// @brief コンストラクタ LsimBdd3(); /// @brief デストラクタ virtual ~LsimBdd3(); public: ////////////////////////////////////////////////////////////////////// // Lsim の仮想関数 ////////////////////////////////////////////////////////////////////// /// @brief ネットワークをセットする. /// @param[in] bdn 対象のネットワーク /// @param[in] order_map 順序マップ virtual void set_network(const BdnMgr& bdn, const unordered_map<string, ymuint>& order_map); /// @brief 論理シミュレーションを行う. /// @param[in] iv 入力ベクタ /// @param[out] ov 出力ベクタ virtual void eval(const vector<ymuint64>& iv, vector<ymuint64>& ov); private: ////////////////////////////////////////////////////////////////////// // 内部で用いられる関数 ////////////////////////////////////////////////////////////////////// /// @brief 1つの出力に対する評価を行う. ymuint64 eval_lut(ymuint addr0, const vector<ymuint64>& iv); private: ////////////////////////////////////////////////////////////////////// // データメンバ ////////////////////////////////////////////////////////////////////// // BDD の管理用オブジェクト BddMgr mBddMgr; // 巨大な Look-Up Table ymuint32* mLUT; // 出力の LUT のエントリポイント vector<ymuint32> mOutputList; }; END_NAMESPACE_YM #endif // LSIMBDD3_H
#include <stdio.h> // used for printf #include <unistd.h> // used for fork(), usleep; #include <stdlib.h> // used for exit(); #include <sys/wait.h> // used for wait(); WEXITSTATUS int main() { pid_t childpid; // variable to store the child’s pid childpid = fork(); int status; if (childpid == 0) { printf("CHILD: %d\n", getpid()); usleep(1000000); printf("CHILD: %d terminates\n", getpid()); exit(13); } else if (childpid > 0) { pid_t childpid1 = fork(); if (childpid1 == 0) { exit(12); } else { printf("PARENT\n"); waitpid(childpid, &status, 0); printf("PARENT: my child terminated with status %d\n", WEXITSTATUS(status)); exit(0); } } }
#include<iostream> #include<string> #include<algorithm> using namespace std; int main(){ string str ="narendiran"; for(int i=0;i<str.length();i++){ if(str[i]>='a' && str[i]<='z') str[i]-=32; } cout<<str<<endl; for(int i=0;i<str.length();i++){ if(str[i]>='A' && str[i]<='Z') str[i]+=32; } cout<<str<<endl; transform(str.begin(),str.end(),str.begin(),::toupper); cout<<str<<endl; transform(str.begin(),str.end(),str.begin(),::tolower); cout<<str<<endl; }
#include "WblsDaqEvent.h" #include <TFile.h> #include <TTree.h> #include <TChain.h> #include <iostream> using namespace std; void WblsDaq::set_branch_address(TTree* tree, WblsDaq::Event* obj) { tree->SetBranchAddress("EventNumber",&obj->count); tree->SetBranchAddress("TriggerTimeFromRunStart",&obj->time); tree->SetBranchAddress("Channel0",&obj->ch0); tree->SetBranchAddress("Channel1",&obj->ch1); tree->SetBranchAddress("Channel2",&obj->ch2); tree->SetBranchAddress("Channel3",&obj->ch3); tree->SetBranchAddress("TriggerCountFromRunStart", &obj->time_count); } void WblsDaq::set_branch_address(TTree* tree, WblsDaq::Header* obj) { tree->SetBranchAddress("RunNumber", &obj->run_number); tree->SetBranchAddress("RunStartTime", &obj->runstart); tree->SetBranchAddress("IsThisDataFile", &obj->isdata); tree->SetBranchAddress("is12or14bit", &obj->nbits); tree->SetBranchAddress("frequency", &obj->freqtype); tree->SetBranchAddress("runtype", &obj->runtype); tree->SetBranchAddress("sampletype", &obj->sampletype); tree->SetBranchAddress("Channel0Gain", &obj->ch0_gain); tree->SetBranchAddress("Channel1Gain", &obj->ch1_gain); tree->SetBranchAddress("Channel2Gain", &obj->ch2_gain); tree->SetBranchAddress("Channel3Gain", &obj->ch3_gain); tree->SetBranchAddress("Channel0device", &obj->ch0_device); tree->SetBranchAddress("Channel1device", &obj->ch1_device); tree->SetBranchAddress("Channel2device", &obj->ch2_device); tree->SetBranchAddress("Channel3device", &obj->ch3_device); tree->SetBranchAddress("PedestalSubstructedAtRun", &obj->pedestal); tree->SetBranchAddress("PerformanceFrequency", &obj->perform_freq); } void WblsDaq::set_branch_address(TTree* tree, WblsDaq::Footer* obj) { tree->SetBranchAddress("TotalEventsNumber", &obj->nevents); tree->SetBranchAddress("RunStopTime", &obj->runstop); } WblsDaq::Spinner::~Spinner() { if (m_event) delete m_event; if (m_head) delete m_head; if (m_foot) delete m_foot; } WblsDaq::Spinner::Spinner(std::string filename) { TFile* fp = TFile::Open(filename.c_str()); // intentional leak m_event_tree = dynamic_cast<TTree*>(fp->Get("FADCData")); m_event = new WblsDaq::Event(); set_branch_address(m_event_tree, m_event); m_head_tree = dynamic_cast<TTree*>(fp->Get("Header")); m_head = new WblsDaq::Header(); set_branch_address(m_head_tree, m_head); m_foot_tree = dynamic_cast<TTree*>(fp->Get("Footer")); m_foot = new WblsDaq::Footer(); set_branch_address(m_foot_tree, m_foot); } WblsDaq::Spinner::Spinner(const std::vector<std::string>& filenames) { TChain* chain = new TChain("FADCData","WbLS DAQ Triggers"); m_event_tree = chain; m_event = new WblsDaq::Event(); set_branch_address(m_event_tree, m_event); m_head = 0; m_foot = 0; for (size_t ind=0; ind< filenames.size(); ++ind) { chain->Add(filenames[ind].c_str()); bool leak = false; TFile* fp = TFile::Open(filenames[ind].c_str()); if (!m_head) { TTree* t = dynamic_cast<TTree*>(fp->Get("Header")); if (t) { m_head = new WblsDaq::Header(); set_branch_address(t, m_head); leak = true; } } if (!m_foot) { TTree* t = dynamic_cast<TTree*>(fp->Get("Footer")); if (t) { m_foot = new WblsDaq::Footer(); set_branch_address(t, m_foot); leak = true; } } // Fixme: best to not leak, but no real harm is done if (leak) { continue; } delete fp; fp = 0; } } int WblsDaq::Spinner::entries() { if (!m_event_tree) return 0; return m_event_tree->GetEntries(); } int WblsDaq::Spinner::load(int entry) { if (!m_event_tree) return 0; return m_event_tree->GetEntry(entry); } WblsDaq::Event* WblsDaq::Spinner::event(int entry) { if (!m_event_tree) return 0; if (entry >= 0) { this->load(entry); } return m_event; } WblsDaq::Header* WblsDaq::Spinner::header() { m_head_tree->GetEntry(0); return m_head; } WblsDaq::Footer* WblsDaq::Spinner::footer() { m_foot_tree->GetEntry(0); return m_foot; } void WblsDaq::Spinner::PrintRunInfo() { WblsDaq::Header* h = header(); WblsDaq::Footer* f = footer(); cout << " run_number:" << h->run_number << endl; cout << " runstart:" << h->runstart << endl; cout << " isdata:" << h->isdata << endl; cout << " nbits:" << h->nbits << endl; cout << " freqtype:" << h->freqtype << endl; cout << " runtype:" << h->runtype << endl; cout << " sampletype:" << h->sampletype << endl; cout << " ch0_gain:" << h->ch0_gain << endl; cout << " ch1_gain:" << h->ch1_gain << endl; cout << " ch2_gain:" << h->ch2_gain << endl; cout << " ch3_gain:" << h->ch3_gain << endl; cout << " ch0_device:" << h->ch0_device << endl; cout << " ch1_device:" << h->ch1_device << endl; cout << " ch2_device:" << h->ch2_device << endl; cout << " ch3_device:" << h->ch3_device << endl; cout << " pedestal:" << h->pedestal << endl; cout << " pedestal:" << h->pedestal << endl; cout << "perform_freq:" << h->perform_freq << endl; cout << " runstop:" << f->runstop << endl; cout << " nevents:" << f->nevents << endl; }
/* * * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ * */ // $Id: QTAtom_stsz.h,v 1.9 2003/08/15 23:53:14 sbasu Exp $ // // QTAtom_stsz: // The 'stsz' QTAtom class. #ifndef QTAtom_stsz_H #define QTAtom_stsz_H // // Includes #include "QTFile.h" #include "QTAtom.h" // // QTAtom class class QTAtom_stsz : public QTAtom { public: // // Constructors and destructor. QTAtom_stsz(QTFile * File, QTFile::AtomTOCEntry * Atom, Bool16 Debug = false, Bool16 DeepDebug = false); virtual ~QTAtom_stsz(void); // // Initialization functions. virtual Bool16 Initialize(void); // // Accessors. inline Bool16 SampleSize(UInt32 SampleNumber, UInt32 *Size = NULL) \ { if(fCommonSampleSize) { \ if( Size != NULL ) \ *Size = fCommonSampleSize; \ return true; \ } else if(SampleNumber && (SampleNumber<=fNumEntries)) { \ if( Size != NULL ) \ *Size = ntohl(fTable[SampleNumber-1]); \ return true; \ } else \ return false; \ }; Bool16 SampleRangeSize(UInt32 firstSampleNumber, UInt32 lastSampleNumber, UInt32 *sizePtr); // // Debugging functions. virtual void DumpAtom(void); virtual void DumpTable(void); inline UInt32 GetNumEntries() {return fNumEntries;} inline UInt32 GetCommonSampleSize() {return fCommonSampleSize;} protected: // // Protected member variables. UInt8 fVersion; UInt32 fFlags; // 24 bits in the low 3 bytes UInt32 fCommonSampleSize; UInt32 fNumEntries; char *fSampleSizeTable; UInt32 *fTable; // longword-aligned version of the above }; #endif // QTAtom_stsz_H
#include <iostream> #include <cmath> using namespace std; /** * Escreva um programa que imprima o quadrado dos numeros inteiros, * no intervalo fechado de 1 a 20. */ int main () { // imprime o quadrado dos numeros inteiros de 1 a 20 for (int i=1; i<=20; i++) cout<<pow (i,2)<<" "; cout<<endl; return 0; }
#include <typeinfo> // For std::bad_cast #include <iostream> // For std::cout, std::err, std::endl etc. class A { public: // Since RTTI is included in the virtual method table there should be at least one virtual function. virtual ~A() { }; void methodSpecificToA() { std::cout << "Method specific for A was invoked" << std::endl; }; }; class B : public A { public: void methodSpecificToB() { std::cout << "Method specific for B was invoked" << std::endl; }; virtual ~B() { }; }; void my_function(A& my_a) { try { B& my_b = dynamic_cast<B&>(my_a); // cast will be successful only for B type objects. my_b.methodSpecificToB(); } catch (const std::bad_cast& e) { std::cerr << " Exception " << e.what() << " thrown." << std::endl; std::cerr << " Object is not of type B" << std::endl; } } int main() { A *arrayOfA[3]; // Array of pointers to base class (A) arrayOfA[0] = new B(); // Pointer to B object arrayOfA[1] = new B(); // Pointer to B object arrayOfA[2] = new A(); // Pointer to A object for (int i = 0; i < 3; i++) { my_function(*arrayOfA[i]); delete arrayOfA[i]; // delete object to prevent memory leak } return 0; }
/* * Copyright (c) 2009-2012 André Tupinambá (andrelrt@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ //----------------------------------------------------------------------------- #ifndef _DCL_REMOTE_PROGRAM_H_ #define _DCL_REMOTE_PROGRAM_H_ #if (defined _MSC_VER) && (_MSC_VER >= 1200) #pragma once #endif #include "distributedcl_internal.h" #include "remote_object.h" #include "remote_context.h" #include "info/program_info.h" //----------------------------------------------------------------------------- namespace dcl { namespace remote { //----------------------------------------------------------------------------- class remote_program : public dcl::info::generic_program, public remote_object< remote_program, dcl::network::message::msgReleaseProgram > { public: remote_program( const remote_context& context_ref, const std::string& source_code ) : dcl::info::generic_program( source_code ), remote_object< remote_program, dcl::network::message::msgReleaseProgram >( context_ref.get_session() ), context_( context_ref ){} remote_program( const remote_context& context_ref, const dcl::devices_t& devices, const size_t* lengths, const unsigned char** binaries ) : dcl::info::generic_program( devices, lengths, binaries ), remote_object< remote_program, dcl::network::message::msgReleaseProgram >( context_ref.get_session() ), context_( context_ref ){} ~remote_program(){} virtual void build( const std::string& build_options, cl_bool blocking = CL_TRUE ); virtual void build( const devices_t& devices, const std::string& build_options, cl_bool blocking = CL_TRUE ); virtual dcl::info::generic_kernel* create_kernel( const std::string& kernel_name ); virtual cl_build_status get_build_status( const dcl::info::generic_device* device_ptr ) const; virtual void get_build_log( const dcl::info::generic_device* device_ptr, std::string& build_log ) const; private: const remote_context& context_; }; //----------------------------------------------------------------------------- }} // namespace dcl::remote //----------------------------------------------------------------------------- #endif // _DCL_REMOTE_PROGRAM_H_
//TabKey.cpp #include "TabKey.h" #include "OtherNoteForm.h" TabKey::TabKey(Form *form) :KeyAction(form) { } TabKey::TabKey(const TabKey& source) : KeyAction(source) { } TabKey::~TabKey() { } TabKey& TabKey::operator=(const TabKey& source) { KeyAction::operator=(source); return *this; } #include "MemoForm.h" #include "Caret.h" #include "Memo.h" #include "Line.h" #include "CharacterFaces.h" #include "SelectedBuffer.h" void TabKey::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { if (dynamic_cast<MemoForm*>(this->form)) { Memo *memo = static_cast<Memo*>(this->form->GetContents()); Line *line = memo->GetLine(memo->GetRow()); CharacterFaces *characterFaces = CharacterFaces::Instance(0); Long tabWidth = characterFaces->GetCharacterSize(32).GetWidth() * 8; Caret *caret = dynamic_cast<MemoForm*>(this->form)->GetCaret(); Long xPosition = caret->GetXPosition() - static_cast<MemoForm*>(this->form)->GetMarginWidth(); Long height = caret->GetYPosition(); Long width = tabWidth - (xPosition%tabWidth); line->Write('\t', width, height); caret->UpdateCaret(); static_cast<MemoForm*>(this->form)->GetSelectedBuffer()->SetIsSelecting(false); static_cast<MemoForm*>(this->form)->ReSizeWindow(); static_cast<MemoForm*>(this->form)->RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_ERASE); } }
#include "object.hpp" Object::Object(int c, sf::String file_name, sf::String name) { this->cost_ = c; this->image_file_name_ = file_name; this->name_ = name; image_.loadFromFile(PATH_TO_PICTURES + image_file_name_ + PICTURES_FORMAT); texture_.loadFromImage(image_); sprite_.setTexture(texture_); } Object::Object(const Object &o) { this->cost_ = o.get_cost(); this->image_file_name_ = o.get_file_name(); this->name_ = o.get_name(); image_.loadFromFile(PATH_TO_PICTURES + o.get_file_name() + PICTURES_FORMAT); texture_.loadFromImage(image_); sprite_.setTexture(texture_); sprite_.setTextureRect(o.get_sprite().getTextureRect()); sprite_.setPosition(o.get_sprite().getPosition().x, o.get_sprite().getPosition().y); } void Object::set_base_texture_rect(sf::IntRect rect) { sprite_.setTextureRect(rect); } // get int Object::get_cost() const { return cost_; } sf::String Object::get_file_name() const { return image_file_name_; } sf::String Object::get_name() const { return name_; } sf::Image Object::get_image() const { return image_; } sf::Texture Object::get_texture() const { return texture_; } sf::Sprite Object::get_sprite() const { return sprite_; } // set void Object::set_cost(int cost) { this->cost_ = cost; } void Object::set_file_name(sf::String file_name) { this->image_file_name_ = file_name; } void Object::set_name(sf::String name) { this->name_ = name; } void Object::set_image(sf::Image image) { this->image_ = image; texture_.loadFromImage(image); sprite_.setTexture(texture_); } void Object::set_base_position(std::pair<float, float> coordinate) { sprite_.setPosition(coordinate.first, coordinate.second); }
#ifndef _GLX_MATH_VEC4_H_ #define _GLX_MATH_VEC4_H_ namespace glx { template<class T> class vec4 { public: T x, y, z, w; public: vec4() {}; vec4(const T*); vec4(const vec3<T>& xyz, T w); vec4(T x, T y, T z, T w); // casting operator float* (); operator const float* () const; // assignment operators vec4<T>& operator += (const vec4<T>&); vec4<T>& operator -= (const vec4<T>&); vec4<T>& operator *= (T); vec4<T>& operator /= (T); vec4<T>& operator = (const vec4<T>&); // unary operators vec4<T> operator + () const; vec4<T> operator - () const; // binary operators vec4<T> operator + (const vec4<T>&) const; vec4<T> operator - (const vec4<T>&) const; vec4<T> operator * (T) const; vec4<T> operator / (T) const; friend vec4<T> operator * (T, const vec4<T>&); bool operator == (const vec4<T>&) const; bool operator != (const vec4<T>&) const; //Resets to 0,0,0,0 void Clear(); }; } #include "GLXVec4.inl" #endif
#include "poly.h" bool Poly::is_neighbor(int idx) const { for(int i = 0; i < neighbors.size(); ++i) { if(idx == neighbors[i]) { return true; } } return false; } void Poly::clear() { center = QPointF(0, 0); points.clear(); indices.clear(); neighbors.clear(); }
#include "schokoprod.h" /******************************************************** *********** DEFINITION DER HILFSFUNKTIONEN ************** *********************************************************/ // Fordert Nutzer auf Enter zu drücken void press_enter() { cout << "\nEnter drücken um fortzufahren."; cin.ignore(); return; } // Hilfe & Credits void help() { cout << "\n-- Hilfe\n"; cout << "Das Programm gibt Auskunft über Kosten und Preise einer Schokoladenproduktion.\n"; cout << "Notwendig für die Berechnung sind zwei Dateien: zutaten.txt (beeinhaltet Zutaten\n"; cout << "und deren Preise pro 100g und schoki.txt (beeinhaltet Name der Praline, Gewicht,\n"; cout << "Anzahl an Zutaten sowie eine Auflistung der einzelnen Zutaten und deren Prozentanteil\n"; cout << "am Gesamtrezept). Bei Anpassungen in den .txt Datein bitte das Format beibehalten\n"; cout << "und die entsprechenden Konstanten im Quelltext verändern.\n"; press_enter(); return; } // Rückgabe eines positiven Integerwertes int get_uint() { while (true) { string input; int temp; getline(cin, input); stringstream inputStream(input); if (inputStream >> temp) { if (temp >= 0) { return temp; } } cout << "Ungültiger Wert, bitte erneut versuchen: "; } } // Auflisten aller Zutaten und ihrem Preisen pro 100g void print_zutaten(zutat_t *array) { cout << "\n-- Zutaten\n"; cout << "Folgende " << ANZAHL_ZUTATEN << " Zutaten stehen zur Verfügung:\n"; for (int i = 0; i < ANZAHL_ZUTATEN; i++) { cout << "\t- " << array[i].name << " (" << array[i].preis_pro_100gramm << "€/100g)\n"; } cout << endl; press_enter(); return; } // Auflisten aller Schokoladenrezepte void print_pralinen(schokolade_t *praline, zutat_t *zutaten) { cout << "\n-- Rezepte\n"; cout << "Folgende Pralinen können produziert werden:\n"; for (int i = 0; i < ANZAHL_PRALINEN; i++) { cout << (i + 1) << ": " << praline[i].name << " (" << praline[i].gewicht << "g)" << endl; for (int j = 0; j < ANZAHL_ZUTATEN_PRO_PRALINE; j++) { if (praline[i].zutat[j].id != -1) { cout << "\t- "<< praline[i].zutat[j].menge_in_prozent << "% " << zutaten[praline[i].zutat[j].id].name << endl; } } cout << endl; } press_enter(); return; } /******************************************************** ************ BERECHNUNG DER ROHSTOFFKOSTEN ************** *********************************************************/ // Berechnung der allgemeinen Rohstoffkosten & befüllen der structs. Diese Funktion muss in main aufgerufen werden! void berechnung_rohstoff(schokolade_t *praline, zutat_t *zutaten) { // Hier werden die individuellen Rohstoffkosten jeder Zutat, sowie die Rohstoffkosten der gesamten Praline ermittelt for (int i = 0; i < ANZAHL_PRALINEN; i++) { double sum = 0; // Wenn nicht alle Zutaten vorkommen, setze restliche id's auf 0 for (int j = 0; j < ANZAHL_ZUTATEN_PRO_PRALINE; j++) { if (praline[i].zutat[j].id == -1) { praline[i].zutat[j].rohstoffkosten = 0; } else { // Bsp: 34% Anteil Kakao je 0.82€/100g; 150g Schokolade = 34 * (150 * 0.82 / 100) / 100; praline[i].zutat[j].rohstoffkosten = (praline[i].zutat[j].menge_in_prozent * ((praline[i].gewicht * zutaten[praline[i].zutat[j].id].preis_pro_100gramm) / 100) /100); } sum += praline[i].zutat[j].rohstoffkosten; } praline[i].kosten.rohstoff_einheit = sum; // Dieses Element ist abhänging von der zu produzierenden Anzahl und wird später nach der Nutzereingabe definiert praline[i].kosten.rohstoff_gesamt = 0; } } // Berechnung der Rohstoffkosten für x-Tafeln void berechnung_rohstoff_pro_tafel(schokolade_t *praline, zutat_t *zutaten) { // Speichert die Anzahl der zu produzierenden Tafeln für jede Praline int n_schoko[ANZAHL_PRALINEN]; cout << "\n-- Berechnung der Rohstoffkosten\n"; // Gibt die Zutaten und deren Rohstoffkosten für eine Tafel Schokolade aus cout << "Folgende Pralinen können produziert werden:\n"; for (int i = 0; i < ANZAHL_PRALINEN; i++) { cout << "\n" << (i + 1) << ": " << praline[i].name << " (" << praline[i].gewicht << "g)" << endl; for (int j = 0; j < ANZAHL_ZUTATEN_PRO_PRALINE; j++) { if (praline[i].zutat[j].id != -1) { cout << "\t- "<< praline[i].zutat[j].menge_in_prozent << "% " << zutaten[praline[i].zutat[j].id].name; cout << " (" << zutaten[praline[i].zutat[j].id].preis_pro_100gramm << "€/100g) \t-> " << praline[i].zutat[j].rohstoffkosten << "€\n"; } } cout << "\tRohstoffkosten pro Einheit:\t--> " << praline[i].kosten.rohstoff_einheit << "€\n"; } cout << "\nWie viele Einheiten sollen produziert werden?\n> "; for (int i = 0; i < ANZAHL_PRALINEN; i++) { cout << praline[i].name << ": "; n_schoko[i] = get_uint(); } // Gibt die Gesamtkosten der einzelnen Rohstoffe und die Gesamtrohstoffkosten der Schokolade aus for (int i = 0; i < ANZAHL_PRALINEN; i++) { double sum = 0; cout << "\n" << n_schoko[i] << "x " << praline[i].name << " (insg. " << (praline[i].gewicht * n_schoko[i]) << "g)" << endl; for (int j = 0; j < ANZAHL_ZUTATEN_PRO_PRALINE; j++) { if (praline[i].zutat[j].id != -1) { cout << "\t- "<< praline[i].zutat[j].menge_in_prozent << "% " << zutaten[praline[i].zutat[j].id].name; cout << " (" << zutaten[praline[i].zutat[j].id].preis_pro_100gramm << "€/100g) \t-> " << (praline[i].zutat[j].rohstoffkosten * n_schoko[i]) << "€\n"; sum += praline[i].zutat[j].rohstoffkosten * n_schoko[i]; } } praline[i].kosten.rohstoff_gesamt = sum; cout << "\tGesamte Rohstoffkosten:\t\t--> " << (praline[i].kosten.rohstoff_gesamt) << "€\n"; } press_enter(); return; } /******************************************************** ********************* PREISMATRIX *********************** *********************************************************/ void berechnung_preis(schokolade_t *praline, zutat_t *zutaten) { // Variablen für Preisberechnung string choice, choice_format, choice_produkt; int prozent_gewinn, start_prozent_gewinn, end_prozent_gewinn, schritt_prozent_gewinn; int produkt = 0; int anzahl, start_anzahl, end_anzahl, schritt_anzahl; double gewinn, vpreis_gesamt, vpreis_einheit, vpreis_format; // Abfrage des Produktes cout << "\nFür welches Produkt soll der Verkaufspreis berechnet werden?\n"; for (int i = 0; i < ANZAHL_PRALINEN; i++) { cout << (i + 1) << ": " << praline[i].name << endl; } cout<< "\n0 - Zurück zum Hauptmenü\n"; // Interne Auswahl des Produkts while(true) { cout << "\nBitte Nummer eingeben:\n> "; getline(cin, choice_produkt); // Umwandlung vom string input in integer stringstream strToInt(choice_produkt); if (strToInt >> produkt) { // Lässt nur Zahlen zwischen 0 und max. Anzahl der Pralinen zu if (produkt > 0 && produkt <= ANZAHL_PRALINEN) { produkt -= 1; break; } else if (produkt == 0) { return; } } cout << "Falsche Eingabe.\n"; } // Abfrage der Werte cout << "\n-- Berechnung des Verkaufspreises\n"; cout << "Bitte auswählen:\n"; cout << "1 - Standardwerte\n"; cout << "2 - Benutzerdefinierte Werte\n"; cout << "\n0 - Zurück zum Hauptmenü\n> "; getline(cin, choice); // Standardwerte nach Aufgabenstellung if (choice == "1") { praline[produkt].kosten.personal = 42800; praline[produkt].kosten.betrieb = 19200; praline[produkt].kosten.sonstige = 13500; praline[produkt].kosten.rohstoff_gesamt = 0; start_anzahl = 10000; end_anzahl = 250000; schritt_anzahl = 10000; start_prozent_gewinn = 1; end_prozent_gewinn = 10; schritt_prozent_gewinn = 1; cout << "\n-- Standardwerte\n"; cout << "\t- Personalkosten:\t42 800€\n"; cout << "\t- Betriebskosten:\t19 200€\n"; cout << "\t- Sonstige Kosten:\t13 500€\n"; cout << "\t- Stückzahl:\t10 000 - 250 000 (+10 000/Zeile)\n"; cout << "\t- Gewinnspanne:\t1% - 10% (+1%/Spalte)\n"; } // Benutzerdefinierte Werte else if (choice == "2") { cout << "\n-- Benutzerdefinierte Werte\n"; cout << "- Produkt: " << praline[produkt].name << endl; praline[produkt].kosten.rohstoff_gesamt = 0; cout << "- Personalkosten: "; praline[produkt].kosten.personal = get_uint(); cout << "- Betriebskosten: "; praline[produkt].kosten.betrieb = get_uint(); cout << "- Sonstige Kosten: "; praline[produkt].kosten.sonstige = get_uint(); cout << "- Zu produzierende Stückzahl (Start): "; start_anzahl = get_uint(); while (true) { cout << "- Zu produzierende Stückzahl (Ende): "; end_anzahl = get_uint(); if (end_anzahl >= start_anzahl) { break; } cout << "Ungültiger Wert."; } while (true) { cout << "- Wachstum der Stückzahl pro Zeile: "; schritt_anzahl = get_uint(); if (schritt_anzahl <= end_anzahl) { break; } cout << "Ungültiger Wert."; } cout << "- Gewinnspanne in % (Start): "; start_prozent_gewinn = get_uint(); while (true) { cout << "- Gewinnspanne in % (Ende): "; end_prozent_gewinn = get_uint(); if (end_prozent_gewinn >= start_prozent_gewinn) { break; } cout << "Ungültiger Wert."; } while (true) { cout << "- Wachstum der Gewinnspanne pro Spalte: "; schritt_prozent_gewinn = get_uint(); if (schritt_prozent_gewinn <= end_prozent_gewinn) { break; } cout << "Ungültiger Wert."; } cout << "\nFolgende Werte wurden eingegeben:\n"; cout << "\t- Personalkosten:\t" << praline[produkt].kosten.personal << "€" << endl; cout << "\t- Betriebskosten:\t" << praline[produkt].kosten.betrieb << "€" << endl; cout << "\t- Sonstige Kosten:\t" << praline[produkt].kosten.sonstige << "€" << endl; cout << "\t- Stückzahl:\t" << start_anzahl << " - " << end_anzahl << " (+" << schritt_anzahl << "/Zeile)\n"; cout << "\t- Gewinnspanne in %:\t" << start_prozent_gewinn << "% - " << end_prozent_gewinn << "% (+" << schritt_prozent_gewinn << "%/Spalte)\n"; press_enter(); } // Zurück zum Hauptmenü else if (choice == "0") { return; } else { cout << "Falsche Eingabe."; press_enter(); return; } // Ausgabe des Preises cout << "\nAusgabeformat des Verkaufspreises:\n"; cout << "1 - Verkaufspreis pro Tafel\n"; cout << "2 - Verkaufspreis gesamt\n"; cout << "\n0 - Zurück zum Hauptmenü\n"; cout << "\nBitte Nummer eingeben:\n> "; getline(cin, choice_format); // Ausgabe pro Tafel if (choice_format == "1") { vpreis_format = 1; } // Ausgabe gesamt else if (choice_format == "2") { vpreis_format = 2; } // Zurück zum Hauptmenü else if (choice_format == "0") { return; } else { cout << "Falsche Eingabe."; press_enter(); return; } // Legende & Beginn der Matrix cout << "\n-- Legende\nZeilen:\t\tStückzahl n an zu produzierenden Pralinen\n"; cout << "Spalten:\tGewinn p in %\n"; cout << "Felder:\t\tVerkaufspreis pro Tafel in €\n"; // Kopf der Matrix cout << "\nn\t"; for (int p = start_prozent_gewinn; p <= end_prozent_gewinn; p = p + schritt_prozent_gewinn) { cout << "p = " << p << "%\t"; } cout << endl; // Y-Achse: Stückzahl an Tafeln steigt um 10 000 von 10 000 auf 250 000 for (anzahl = start_anzahl; anzahl <= end_anzahl; anzahl = anzahl + schritt_anzahl) { cout << anzahl << "\t"; praline[produkt].kosten.rohstoff_gesamt = anzahl * praline[produkt].kosten.rohstoff_einheit; // X-Achse: Gewinn steigt um 1% von 1% bis 10% for (prozent_gewinn = start_prozent_gewinn; prozent_gewinn <= end_prozent_gewinn; prozent_gewinn = prozent_gewinn + schritt_prozent_gewinn) { praline[produkt].kosten.gesamt = praline[produkt].kosten.personal + praline[produkt].kosten.betrieb + praline[produkt].kosten.sonstige + praline[produkt].kosten.rohstoff_gesamt; gewinn = (prozent_gewinn * praline[produkt].kosten.gesamt) / 100; vpreis_gesamt = praline[produkt].kosten.gesamt + gewinn; vpreis_einheit = vpreis_gesamt / anzahl; if (vpreis_format == 1) { cout << setprecision(5) <<vpreis_einheit << "\t"; } else { cout << vpreis_gesamt << "\t"; } } cout << endl; } press_enter(); return; }
// // Time.cpp // ReserveSystem // // Created by HeeCheol Kim on 27/11/2018. // Copyright © 2018 HeeCheol Kim. All rights reserved. // #include "Time.h" char* Time::getCurrentTimeYYMMDD() { time(&(this->rawtime)); this->timeInfo = localtime(&(this->rawtime)); strftime(this->buffer, 80, "%Y%m%d", this->timeInfo); return buffer; } char* Time::getCurrentTimeYYMMDDHHMMSS() { strftime(this->buffer, 80, "%Y%m%d%H%M%S", this->timeInfo); return buffer; } char* Time::getCurrentTimeBeautify() { strftime(this->buffer, 80, "%Y-%m-%d %H:%M:%S", this->timeInfo); return buffer; } void Time::setTimeInfo() { time(&(this->rawtime)); this->timeInfo = localtime(&(this->rawtime)); }
#include "iter.h" ContOctree::Iter::Iter(ContOctree& oc) : mem(oc.mem), at_node(true), top_level(oc.top_level), level(oc.top_level), null_leaf(oc.null_leaf), null_leaf_len(oc.null_leaf_len) { pos() = 0; length() = mem.length(); FORI(3) loc[i] = 0; }
#ifndef CLAP_TRAP_H # define CLAP_TRAP_H # include <iostream> class ClapTrap { protected: int _hitPoints; int _maxHitPoints; int _energyPoints; int _maxEnergyPoints; int _level; std::string _name; int _meleeDamage; int _rangeDamage; int _armor; public: ClapTrap(void); ClapTrap(const ClapTrap & src); ClapTrap(std::string const name); ~ClapTrap(void); ClapTrap & operator=(const ClapTrap & rhs); void rangedAttack(std::string const & target); void meleeAttack(std::string const & target); void takeDamage(unsigned int amount); void beRepaired(unsigned int amount); int getHitPoints(void) const; int getMaxHitPoints(void) const; int getEnergyPoints(void) const; int getMaxEnergyPoints(void) const; int getLevel(void) const; std::string getName(void) const; int getMeleeDamage(void) const; int getRangeDamage(void) const; int getArmor(void) const; }; #endif
// slinked_list.h // implements a templated singly linked list // based on Professor Morrison's singly linked list from class #ifndef SLINKED_H #define SLINKED_H #include <cstddef> template<class T> class slinked_list { private: // list node data and pointer to next node // plus constructors and operators struct node { // data and next T data; node* next; // default constructor // up to user not to use this when they shouldn't node() : data() , next(NULL) {} // data input constructor node(T indata) : data(indata) , next(NULL) {} // copy constructor node(const node& copy) { data = copy.data; next = copy.next; } // node destructor // recursively deletes nodes down the list ~node() { delete next; } // operators // reference operator= node& operator=(const node& assign) { // if this and assign aren't the same, copy over the values if (this != &assign) { this->data = assign.data; this->next = assign.next; } return *this; } // pointer operator= node* operator=(const node* assign) { // if this and assign aren't the same, copy values if (this != (void*)&assign) { this->data = assign->data; this->next = assign->next; } return *this; } // pointer operator!= bool operator!=(const node* right) { return this != (void*)&right; } }; // also need a head pointer for the whole list node* head; public: // linked list default constructor slinked_list() : head(NULL) {} // linked list copy constructor slinked_list(const slinked_list<T>& copy) : head(NULL) { // get head node* curr = copy.head; // iterate through and assign data and pointers while (NULL != curr) { insert(curr->data); curr = curr->next; } } // linked list destructor ~slinked_list() { delete head; // recursive node deletion } // assignment operator slinked_list<T>& operator=(const slinked_list<T>& assign) { // is this me check if (this != &assign) { node* prev = NULL; node* curr = NULL; // iterate through, inserting while (NULL != curr) { this->insert(curr->data); // update pointers prev = curr; curr = curr->next; } } return *this; } // helper and other functions // insert item at end of list void insert(T value) { node* temp = new node(value); if (is_empty()) { head = temp; } else { node* prev = NULL; node* curr = head; // find end of list while (NULL != curr) { prev = curr; curr = curr->next; } // insert node prev->next = temp; } } // push item onto front of list void push_front(T value) { node* temp = new node(value); // set up pointers temp->next = head; head = temp; } // delete target data (first instance, specifically - do a contains check afterwards if you want all) bool del(T target) { node* temp = new node(); node* prev = new node(); node* curr = new node(); if (is_empty()) { return false; } // handle first in list else if (target == head->data) { temp = head; head = head->next; delete (temp); return true; } // handle other options by traversing else { prev = head; curr = head->next; // traversal while ((NULL != curr) && (curr->data != target)) { prev = curr; curr = curr->next; } if (NULL != curr) { // delete node with target value temp = curr; prev->next = curr->next; delete (temp); return true; } else { // not in list, so false return false; } } } // pop front element from list bool pop_front() { // check if empty if (is_empty()) { return false; } // otherwise pop else { // node* temp = head; head = head->next; // delete(temp); return true; } } // get what's in front T front() const { return head->data; } // check if empty bool is_empty() const { return NULL == head; } // check if element is contained in list bool contains(const T& target) const { // emptiness check if (is_empty()) { return false; } else { node* prev = NULL; node* curr = head; // traverse while ((NULL != curr) && (curr->data != target)) { prev = curr; curr = curr->next; } return NULL != curr; } } }; #endif
#include "Run_time_Framework.h" GLvoid CRun_time_Framework::background(float r, float g, float b) { glClearColor(r, g, b, 1.0f); // 바탕색을 'blue' 로 지정 glClear(GL_COLOR_BUFFER_BIT); // 설정된 색으로 전체를 칠하기 } GLvoid CRun_time_Framework::Draw_Ball() { GLfloat a[] = { 0.2,0.2,0.2,1.0 }; GLfloat d[] = { 0.8,0.8,0.8,1.0 }; glPushMatrix(); glTranslatef(100 * sin(moon_degree / 180.0*PI), 0, -100 * cos(moon_degree / 180.0*PI)); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, a); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, d); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, WhiteLight); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 80.0f); glutSolidSphere(50, 30, 30); glPopMatrix(); } GLvoid CRun_time_Framework::Draw_Cone() { //glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glPushMatrix(); glColor3f(0, 1, 0); glTranslatef(light[0].position[0], light[0].position[1], light[0].position[2]); glRotatef(180 - light[0].degree, 0, 1, 0); gluCylinder(qobj, 20, 0.0, 20, 20, 8); glPopMatrix(); glPushMatrix(); glColor3f(1, 0, 0); glTranslatef(light[1].position[0], light[1].position[1], light[1].position[2]); glRotatef(180 - light[1].degree, 0, 1, 0); gluCylinder(qobj, 20, 0.0, 20, 20, 8); glPopMatrix(); glDisable(GL_COLOR_MATERIAL); } GLvoid CRun_time_Framework::Init_Light() { light[0].degree = 90.0; light[0].AmbientColor[1] = 0.2; light[0].DiffuseColor[1] = 0.8; light[1].degree = 270.0; light[1].AmbientColor[0] = 0.2; light[1].DiffuseColor[0] = 0.8; return GLvoid(); } GLvoid CRun_time_Framework::UpdateLight() { light[0].position[0] = 300.0*sin(light[0].degree / 180.0*PI); light[0].position[2] = -300.0*cos(light[0].degree / 180.0*PI); light[1].position[0] = 300.0*sin(light[1].degree / 180.0*PI); light[1].position[2] = -300.0*cos(light[1].degree / 180.0*PI); return GLvoid(); } GLvoid CRun_time_Framework::Draw_Ground() { glPushMatrix(); glBindTexture(GL_TEXTURE_2D, texture[0]); glTranslatef(0, -300, 0); for (int i = 0; i < 50; ++i) { for (int j = 0; j < 50; ++j) { glBegin(GL_QUADS); glTexCoord2f(j*(1.0 / 50.0), i*(1.0 / 50.0)); glVertex3f(ground[i][j].left, 0, ground[i][j].top); glTexCoord2f((j + 1)*(1.0 / 50.0), i*(1.0 / 50.0)); glVertex3f(ground[i][j].right, 0, ground[i][j].top); glTexCoord2f((j + 1)*(1.0 / 50.0), (i + 1)*(1.0 / 50.0)); glVertex3f(ground[i][j].right, 0, ground[i][j].bottom); glTexCoord2f(j*(1.0 / 50.0), (i + 1)*(1.0 / 50.0)); glVertex3f(ground[i][j].left, 0, ground[i][j].bottom); glEnd(); } } glPopMatrix(); } GLvoid CRun_time_Framework::Draw_Piramid() { GLfloat a[] = { 0.2,0.2,0.2,1.0 }; GLfloat d[] = { 0.8,0.8,0.8,1.0 }; glPushMatrix(); glBindTexture(GL_TEXTURE_2D, texture[1]); glMaterialfv(GL_FRONT, GL_AMBIENT, a); glMaterialfv(GL_FRONT, GL_DIFFUSE, d); glMaterialfv(GL_FRONT, GL_SPECULAR, WhiteLight); glTranslatef(0, -300, 0); glColor3f(1, 1, 1); //왼쪽위 { glBegin(GL_POLYGON); if (normal) glNormal3f(0.0, 0.0, 1.0); glTexCoord2f(0.5, 0); glVertex3f(-360, 40, -360); glTexCoord2f(0, 1); glVertex3f(ground[4][4].right, 0, ground[4][4].bottom); glTexCoord2f(1, 1); glVertex3f(ground[4][0].left, 0, ground[4][0].bottom); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(-1.0, 0.0, 0.0); glTexCoord2f(0.5, 0); glVertex3f(-360, 40, -360); glTexCoord2f(0, 1); glVertex3f(ground[4][0].left, 0, ground[4][0].bottom); glTexCoord2f(1, 1); glVertex3f(ground[0][0].left, 0, ground[0][0].top); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(0.0, 0.0, -1.0); glTexCoord2f(0.5, 0); glVertex3f(-360, 40, -360); glTexCoord2f(0, 1); glVertex3f(ground[0][0].left, 0, ground[0][0].top); glTexCoord2f(1, 1); glVertex3f(ground[0][4].right, 0, ground[0][4].top); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(1.0, 0.0, 0.0); glTexCoord2f(0.5, 0); glVertex3f(-360, 40, -360); glTexCoord2f(0, 1); glVertex3f(ground[0][4].right, 0, ground[0][4].top); glTexCoord2f(1, 1); glVertex3f(ground[4][4].right, 0, ground[4][4].bottom); glEnd(); } //오른쪽위 { glBegin(GL_POLYGON); if (normal) glNormal3f(0.0, 0.0, 1.0); glTexCoord2f(0.5, 0); glVertex3f(360, 40, -360); glTexCoord2f(0, 1); glVertex3f(ground[4][49].right, 0, ground[4][49].bottom); glTexCoord2f(1, 1); glVertex3f(ground[4][45].left, 0, ground[4][45].bottom); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(-1.0, 0.0, 0.0); glTexCoord2f(0.5, 0); glVertex3f(360, 40, -360); glTexCoord2f(0, 1); glVertex3f(ground[4][45].left, 0, ground[4][45].bottom); glTexCoord2f(1, 1); glVertex3f(ground[0][45].left, 0, ground[0][45].top); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(0.0, 0.0, -1.0); glTexCoord2f(0.5, 0); glVertex3f(360, 40, -360); glTexCoord2f(0, 1); glVertex3f(ground[0][45].left, 0, ground[0][45].top); glTexCoord2f(1, 1); glVertex3f(ground[0][49].right, 0, ground[0][49].top); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(1.0, 0.0, 0.0); glTexCoord2f(0.5, 0); glVertex3f(360, 40, -360); glTexCoord2f(0, 1); glVertex3f(ground[0][49].right, 0, ground[0][49].top); glTexCoord2f(1, 1); glVertex3f(ground[4][49].right, 0, ground[4][49].bottom); glEnd(); } //왼쪽아래 { glBegin(GL_POLYGON); if (normal) glNormal3f(0.0, 0.0, 1.0); glTexCoord2f(0.5, 0); glVertex3f(-360, 40, 360); glTexCoord2f(0, 1); glVertex3f(ground[49][4].right, 0, ground[49][4].bottom); glTexCoord2f(1, 1); glVertex3f(ground[49][0].left, 0, ground[49][0].bottom); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(-1.0, 0.0, 0.0); glTexCoord2f(0.5, 0); glVertex3f(-360, 40, 360); glTexCoord2f(0, 1); glVertex3f(ground[49][0].left, 0, ground[49][0].bottom); glTexCoord2f(1, 1); glVertex3f(ground[45][0].left, 0, ground[45][0].top); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(0.0, 0.0, -1.0); glTexCoord2f(0.5, 0); glVertex3f(-360, 40, 360); glTexCoord2f(0, 1); glVertex3f(ground[45][0].left, 0, ground[45][0].top); glTexCoord2f(1, 1); glVertex3f(ground[45][4].right, 0, ground[45][4].top); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(1.0, 0.0, 0.0); glTexCoord2f(0.5, 0); glVertex3f(-360, 40, 360); glTexCoord2f(0, 1); glVertex3f(ground[45][4].right, 0, ground[45][4].top); glTexCoord2f(1, 1); glVertex3f(ground[49][4].right, 0, ground[49][4].bottom); glEnd(); } //오른쪽아래 { glBegin(GL_POLYGON); if (normal) glNormal3f(0.0, 0.0, 1.0); glTexCoord2f(0.5, 0); glVertex3f(360, 40, 360); glTexCoord2f(0, 1); glVertex3f(ground[49][49].right, 0, ground[49][49].bottom); glTexCoord2f(1, 1); glVertex3f(ground[49][45].left, 0, ground[49][45].bottom); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(-1.0, 0.0, 0.0); glTexCoord2f(0.5, 0); glVertex3f(360, 40, 360); glTexCoord2f(0, 1); glVertex3f(ground[49][45].left, 0, ground[49][45].bottom); glTexCoord2f(1, 1); glVertex3f(ground[45][45].left, 0, ground[45][45].top); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(0.0, 0.0, -1.0); glTexCoord2f(0.5, 0); glVertex3f(360, 40, 360); glTexCoord2f(0, 1); glVertex3f(ground[45][45].left, 0, ground[45][45].top); glTexCoord2f(1, 1); glVertex3f(ground[45][49].right, 0, ground[45][49].top); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(1.0, 0.0, 0.0); glTexCoord2f(0.5, 0); glVertex3f(360, 40, 360); glTexCoord2f(0, 1); glVertex3f(ground[45][49].right, 0, ground[45][49].top); glTexCoord2f(1, 1); glVertex3f(ground[49][49].right, 0, ground[49][49].bottom); glEnd(); } //가운데 { glBegin(GL_POLYGON); if (normal) glNormal3f(0.0, 0.0, 1.0); glTexCoord2f(0.5, 0); glVertex3f(0, 200, 0); glTexCoord2f(0, 1); glVertex3f(ground[29][29].right, 0, ground[29][29].bottom); glTexCoord2f(1, 1); glVertex3f(ground[29][20].left, 0, ground[29][20].bottom); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(-1.0, 0.0, 0.0); glTexCoord2f(0.5, 0); glVertex3f(0, 200, 0); glTexCoord2f(0, 1); glVertex3f(ground[29][20].left, 0, ground[29][20].bottom); glTexCoord2f(1, 1); glVertex3f(ground[20][20].left, 0, ground[20][20].top); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(0.0, 0.0, -1.0); glTexCoord2f(0.5, 0); glVertex3f(0, 200, 0); glTexCoord2f(0, 1); glVertex3f(ground[20][20].left, 0, ground[20][20].top); glTexCoord2f(1, 1); glVertex3f(ground[20][29].right, 0, ground[20][29].top); glEnd(); glBegin(GL_POLYGON); if (normal) glNormal3f(1.0, 0.0, 0.0); glTexCoord2f(0.5, 0); glVertex3f(0, 200, 0); glTexCoord2f(0, 1); glVertex3f(ground[20][29].right, 0, ground[20][29].top); glTexCoord2f(1, 1); glVertex3f(ground[29][29].right, 0, ground[29][29].bottom); glEnd(); } glPopMatrix(); } GLubyte * CRun_time_Framework::LoadDIBitmap(const char *filename, BITMAPINFO ** info) { FILE *fp; GLubyte *bits; int bitsize, infosize; BITMAPFILEHEADER header; // 바이너리 읽기 모드로 파일을 연다 if ((fp = fopen(filename, "rb")) == NULL) return NULL; // 비트맵 파일 헤더를 읽는다. if (fread(&header, sizeof(BITMAPFILEHEADER), 1, fp) < 1) { fclose(fp); return NULL; } // 파일이 BMP 파일인지 확인한다. if (header.bfType != 'MB') { fclose(fp); return NULL; } // BITMAPINFOHEADER 위치로 간다. infosize = header.bfOffBits - sizeof(BITMAPFILEHEADER); // 비트맵 이미지 데이터를 넣을 메모리 할당을 한다. if ((*info = (BITMAPINFO *)malloc(infosize)) == NULL) { fclose(fp); exit(0); return NULL; } // 비트맵 인포 헤더를 읽는다. if (fread(*info, 1, infosize, fp) < (unsigned int)infosize) { free(*info); fclose(fp); return NULL; } // 비트맵의 크기 설정 if ((bitsize = (*info)->bmiHeader.biSizeImage) == 0) bitsize = ((*info)->bmiHeader.biWidth*(*info)->bmiHeader.biBitCount + 7) / 8.0 * abs((*info)->bmiHeader.biHeight); // 비트맵의 크기만큼 메모리를 할당한다. if ((bits = (unsigned char *)malloc(bitsize)) == NULL) { free(*info); fclose(fp); return NULL; } // 비트맵 데이터를 bit(GLubyte 타입)에 저장한다. if (fread(bits, 1, bitsize, fp) < (unsigned int)bitsize) { free(*info); free(bits); fclose(fp); return NULL; } fclose(fp); return bits; } GLvoid CRun_time_Framework::set_texture(int n) { // n개의 이미지 텍스처 매핑을 한다. glGenTextures(n, texture); //텍스처와 객체를 결합한다. --- (1) glBindTexture(GL_TEXTURE_2D, texture[0]); //이미지 로딩을 한다. --- (2) pBytes = LoadDIBitmap("ground.bmp", &info); //텍스처 설정 정의를 한다. --- (3) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, info->bmiHeader.biWidth, info->bmiHeader.biHeight, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, pBytes); //텍스처 파라미터 설정 --- (4) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // 텍스처 모드 설정 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // 나머지 n-1개의 텍스처에도 (1) ~ (4)까지의 과정을 진행하여 텍스처를 설정한다. glBindTexture(GL_TEXTURE_2D, texture[1]); pBytes = LoadDIBitmap("piramid.bmp", &info); glTexImage2D(GL_TEXTURE_2D, 0, 3, info->bmiHeader.biWidth, info->bmiHeader.biHeight, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, pBytes); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); return GLvoid(); }
#ifndef CONTROLLER_H #define CONTROLLER_H #include <QObject> #include <QGraphicsScene> #include <QTimer> #include <QGraphicsRectItem> #include "Zombie.h" #include "Score.h" #include "Sun.h" #include "GroundRect.h" #include "Nut.h" #include "ShooterIcon.h" #include "NutIcon.h" #include "SunFlower.h" #include "SunFlowerIcon.h" #include "CherryBomb.h" #include "CherryIcon.h" #include "ShovelIcon.h" class Controller : public QObject { Q_OBJECT friend class View; friend class Zombie; private: QGraphicsScene *scene; QTimer *ctimer; QGraphicsRectItem *holder; QList<Zombie *> zombieList; QList<Sun *> sunList; QList<GroundRect *> groundList; QGraphicsPixmapItem *scoreBoard; Score *controllerScore; ShooterIcon * shooterIcon; NutIcon * nutIcon; SunFlowerIcon * sunFlowerIcon; CherryIcon* cherryIcon; ShovelIcon * shovelIcon; int season; int number; bool isLevelSix; public: explicit Controller(int season,QObject *parent =nullptr); ~Controller(); void addZombie(const int& velocity, const int & lives , bool isLord,int row); void addSun(); void addNuts(int velocity); bool boolGameOver(); void checkLives(); void addGround(const int & season); void checkShooterIcon(); void planting(int s); void checkNutIcon(); void checkSunFlowerIcon(); void checkCherryIcon(); void checkShovelIcon(); signals: }; #endif // CONTROLLER_H
#include "Global.h" #include "IpmtConfiguration.h" /* * Configuração para a função getopt_long. * Adaptado de * http://www.gnu.org/software/libc/manual/html_node/Getopt-Long-Option-Example.html */ IpmtConfiguration config; #define COMPRESSION 1 #define INDEXTYPE 2 #define LZ77_BUFFER 3 #define LZ77_LOOKA 4 #define DOT_FILE 5 #define COMPRESSION_LEVEL 6 struct option options[] = { {"count", no_argument, &config.countFlag, 'c'}, {"help", no_argument, &config.helpFlag, 'h'}, {"compression", required_argument, 0, COMPRESSION}, {"indextype", required_argument, 0, INDEXTYPE}, {"wb", required_argument, 0, LZ77_BUFFER}, {"wl", required_argument, 0, LZ77_LOOKA}, {"pattern", required_argument, 0, 'p'}, {"interrupt", required_argument, 0, 'i'}, {"dotfile", required_argument, 0, DOT_FILE}, {"level", required_argument, 0, COMPRESSION_LEVEL}, {0, 0, 0, 0} }; /* * Análise dos parâmetros do programa (preenchimento dos campos de 'config') * Adaptado de * * http://www.gnu.org/software/libc/manual/html_node/Getopt-Long-Option-Example.html */ IpmtConfiguration& parseOptions(int argc, char* argv[]) { while(true){ int c = getopt_long (argc, argv, "cp:i:h", options, NULL); if(c == -1) break; if(c == COMPRESSION_LEVEL) { config.compressionLevel = atoi(optarg); config.isCompressionLevelSet = true; } else if(c == 'i') { config.interrupt = atoi(optarg); } else if(c == DOT_FILE) { config.dotFile = optarg; } else if(c == LZ77_BUFFER) { config.wb = atoi(optarg); } else if(c == LZ77_LOOKA) { config.wl = atoi(optarg); } else if(c == COMPRESSION) { config.compression = optarg; } else if(c == INDEXTYPE) { config.indexType = optarg; } else if(c == 'p') { config.patternFileName = optarg; } else if(c == 'c') { config.countFlag = 1; } else if(c == 'h') { config.helpFlag = 1; return config;//O usuário quer ajuda! } } //parâmetros sem opções. São esperados aqui o modo de operação, o arquivo de padrões, o arquivo de texto e o arquivo de índice. if (optind < argc) { //Modo de operação if(optind < argc) config.mode = argv[optind++]; if(config.mode == "index") { //o proximo valor deve ser o nome do arquivo de texto if(optind < argc) config.textFileName = argv[optind++]; } else if(config.mode == "search") { //Usuário não informou uma fonte de padrões. //Então a próxima string é um padrão. if(config.patternFileName == "" && optind < argc){ config.patterns.push_back(argv[optind++]); } if(optind < argc) config.indexFileName = argv[optind++]; } } return config; } void printHelpMessage() { printf("###############################################################################\n"); printf(" FUNCIONALIDADES BÁSICAS\n"); printf(" \n"); printf("Construção de um índice:\n"); printf(" iptm index arquivo_de_texto.txt\n"); printf("essa opção gera o arquivo de índice: arquivo_de_texto.txt.idx\n"); printf("\n"); printf("Busca de padrões em um índice:\n"); printf(" ipmt search padrao arquivo_de_indice\n"); printf(" ou\n"); printf(" iptm search -p arquivo_de_padroes arquivo_de_indice\n"); printf("###############################################################################\n"); printf(" OPÇÕES DISPONÍVEIS\n"); printf("\n"); printf("Para a construção de índice:\n"); printf(" --indextype Define o tipo de índice a ser criado. Os \n"); printf(" valores possíveis são: \n"); printf(" suffixtree (padrão), suffixtree2 e suffixarray\n"); printf("\n"); printf(" --compression Define o algoritmo de compressão utilizado.\n"); printf(" Os valores possíveis são:\n"); printf(" lz77, lz78, lzw (padrão) e none\n"); printf("\n"); printf(" --wl Define o tamanho da janela de lookahead\n"); printf(" do algoritmo lz77. Valor padrão: 1024\n"); printf("\n"); printf(" --wb Define o tamanho da janela de buffer\n"); printf(" do algoritmo lz77. Valor padrão: 16\n"); printf("\n"); printf(" --level Define a qualidade da compressão dos \n"); printf(" algoritmos lz78 e lzw. Os valores possíveis\n"); printf(" são:\n"); printf(" 0 -> compressão mais rápida\n"); printf(" 1 (padrão)\n"); printf(" 2 -> melhor compressão \n"); printf("\n"); printf(" --dotfile Arquivo onde serão salvos as etapas\n"); printf(" intermediárias da construção da árvore de\n"); printf(" sufixos em formato dot.\n"); printf("\n"); printf("Para a busca de padrões:\n"); printf("\n"); printf(" -c, --count A ferramenta apenas reporta a quantidade de \n"); printf(" ocorrências encontradas. Essa flag é desligada\n"); printf(" por padrão, ou seja, a ferramenta imprime\n"); printf(" as linhas das ocorrências por padrão.\n"); printf("\n"); printf(" -p, --pattern Define um arquivo fonte de padrões, um em cada\n"); printf(" linha.\n"); printf("Geral:\n"); printf(" -h, --help Exibe uma mensagem de ajuda\n"); }
#include "protein_translation.h" namespace protein_translation { std::vector<std::string> proteins(std::string code) { std::vector<std::string> result; int codNum = code.size() / 3; for (int i = 0; i < codNum; ++i) { std::string subCode = code.substr(i * 3, 3); if (subCode == "AUG") result.push_back("Methionine"); else if (subCode == "UUU" || subCode == "UUC") result.push_back("Phenylalanine"); else if (subCode == "UUA" || subCode == "UUG") result.push_back("Leucine"); else if (subCode == "UCU" || subCode == "UCC" || subCode == "UCA" || subCode == "UCG") result.push_back("Serine"); else if (subCode == "UAU" || subCode == "UAC") result.push_back("Tyrosine"); else if (subCode == "UGU" || subCode == "UGC") result.push_back("Cysteine"); else if (subCode == "UGG") result.push_back("Tryptophan"); else if (subCode == "UAA" || subCode == "UAG" || subCode == "UGA") break; } return result; } } // namespace protein_translation
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.Devices.Bluetooth.GenericAttributeProfile.1.h" #include "Windows.Foundation.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_e5198cc8_2873_55f5_b0a1_84ff9e4aad62 #define WINRT_GENERIC_e5198cc8_2873_55f5_b0a1_84ff9e4aad62 template <> struct __declspec(uuid("e5198cc8-2873-55f5-b0a1-84ff9e4aad62")) __declspec(novtable) IReference<uint8_t> : impl_IReference<uint8_t> {}; #endif #ifndef WINRT_GENERIC_c00bc2f2_a7f8_5f3f_80d1_2808ef6bca10 #define WINRT_GENERIC_c00bc2f2_a7f8_5f3f_80d1_2808ef6bca10 template <> struct __declspec(uuid("c00bc2f2-a7f8-5f3f-80d1-2808ef6bca10")) __declspec(novtable) IAsyncOperation<winrt::Windows::Devices::Enumeration::DeviceAccessStatus> : impl_IAsyncOperation<winrt::Windows::Devices::Enumeration::DeviceAccessStatus> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_7c8e7fdd_a1a1_528a_81d1_296769227a08 #define WINRT_GENERIC_7c8e7fdd_a1a1_528a_81d1_296769227a08 template <> struct __declspec(uuid("7c8e7fdd-a1a1-528a-81d1-296769227a08")) __declspec(novtable) IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> : impl_IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_e7c667f6_e874_500f_86ff_760ca6f07a58 #define WINRT_GENERIC_e7c667f6_e874_500f_86ff_760ca6f07a58 template <> struct __declspec(uuid("e7c667f6-e874-500f-86ff-760ca6f07a58")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceServicesResult> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceServicesResult> {}; #endif #ifndef WINRT_GENERIC_6d40b467_46b9_516f_8208_db23b786ea48 #define WINRT_GENERIC_6d40b467_46b9_516f_8208_db23b786ea48 template <> struct __declspec(uuid("6d40b467-46b9-516f-8208-db23b786ea48")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSession> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSession> {}; #endif #ifndef WINRT_GENERIC_6c7ec2ec_9f00_5ea0_9a08_60e5070bcf03 #define WINRT_GENERIC_6c7ec2ec_9f00_5ea0_9a08_60e5070bcf03 template <> struct __declspec(uuid("6c7ec2ec-9f00-5ea0-9a08-60e5070bcf03")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSession, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSession, Windows::Foundation::IInspectable> {}; #endif #ifndef WINRT_GENERIC_0e1210f2_7b6f_543e_8adb_a61d34ab535d #define WINRT_GENERIC_0e1210f2_7b6f_543e_8adb_a61d34ab535d template <> struct __declspec(uuid("0e1210f2-7b6f-543e-8adb-a61d34ab535d")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSession, Windows::Devices::Bluetooth::GenericAttributeProfile::GattSessionStatusChangedEventArgs> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSession, Windows::Devices::Bluetooth::GenericAttributeProfile::GattSessionStatusChangedEventArgs> {}; #endif #ifndef WINRT_GENERIC_e5e90272_408f_5055_9bd3_88408982d301 #define WINRT_GENERIC_e5e90272_408f_5055_9bd3_88408982d301 template <> struct __declspec(uuid("e5e90272-408f-5055-9bd3-88408982d301")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_cb3ab3ae_b561_504f_a808_599deceb2df4 #define WINRT_GENERIC_cb3ab3ae_b561_504f_a808_599deceb2df4 template <> struct __declspec(uuid("cb3ab3ae-b561-504f-a808-599deceb2df4")) __declspec(novtable) IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic> : impl_IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_983201ac_8777_53e8_86e0_63fa684be1bd #define WINRT_GENERIC_983201ac_8777_53e8_86e0_63fa684be1bd template <> struct __declspec(uuid("983201ac-8777-53e8-86e0-63fa684be1bd")) __declspec(novtable) IAsyncOperation<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattOpenStatus> : impl_IAsyncOperation<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattOpenStatus> {}; #endif #ifndef WINRT_GENERIC_0972194a_ac1c_5536_9886_27e58a18f273 #define WINRT_GENERIC_0972194a_ac1c_5536_9886_27e58a18f273 template <> struct __declspec(uuid("0972194a-ac1c-5536-9886-27e58a18f273")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristicsResult> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristicsResult> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_19605ea8_73d6_5760_849b_fe5f8a2bd05c #define WINRT_GENERIC_19605ea8_73d6_5760_849b_fe5f8a2bd05c template <> struct __declspec(uuid("19605ea8-73d6-5760-849b-fe5f8a2bd05c")) __declspec(novtable) IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptor> : impl_IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptor> {}; #endif #ifndef WINRT_GENERIC_0ea2c154_22b8_5c8e_925d_d47e1aad31bb #define WINRT_GENERIC_0ea2c154_22b8_5c8e_925d_d47e1aad31bb template <> struct __declspec(uuid("0ea2c154-22b8-5c8e-925d-d47e1aad31bb")) __declspec(novtable) IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattPresentationFormat> : impl_IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattPresentationFormat> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_d40432a8_1e14_51d0_b49b_ae2ce1aa05e5 #define WINRT_GENERIC_d40432a8_1e14_51d0_b49b_ae2ce1aa05e5 template <> struct __declspec(uuid("d40432a8-1e14-51d0-b49b-ae2ce1aa05e5")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadResult> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadResult> {}; #endif #ifndef WINRT_GENERIC_3ff69516_1bfb_52e9_9ee6_e5cdb78e1683 #define WINRT_GENERIC_3ff69516_1bfb_52e9_9ee6_e5cdb78e1683 template <> struct __declspec(uuid("3ff69516-1bfb-52e9-9ee6-e5cdb78e1683")) __declspec(novtable) IAsyncOperation<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCommunicationStatus> : impl_IAsyncOperation<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCommunicationStatus> {}; #endif #ifndef WINRT_GENERIC_cf4444cc_4077_5719_8366_46e86b983685 #define WINRT_GENERIC_cf4444cc_4077_5719_8366_46e86b983685 template <> struct __declspec(uuid("cf4444cc-4077-5719-8366-46e86b983685")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadClientCharacteristicConfigurationDescriptorResult> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadClientCharacteristicConfigurationDescriptorResult> {}; #endif #ifndef WINRT_GENERIC_c1f420f6_6292_5760_a2c9_9ddf98683cfc #define WINRT_GENERIC_c1f420f6_6292_5760_a2c9_9ddf98683cfc template <> struct __declspec(uuid("c1f420f6-6292-5760-a2c9-9ddf98683cfc")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic, Windows::Devices::Bluetooth::GenericAttributeProfile::GattValueChangedEventArgs> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic, Windows::Devices::Bluetooth::GenericAttributeProfile::GattValueChangedEventArgs> {}; #endif #ifndef WINRT_GENERIC_ceaf40c7_be37_52a5_9a1b_63398513e597 #define WINRT_GENERIC_ceaf40c7_be37_52a5_9a1b_63398513e597 template <> struct __declspec(uuid("ceaf40c7-be37-52a5-9a1b-63398513e597")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptorsResult> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptorsResult> {}; #endif #ifndef WINRT_GENERIC_e83b4534_bd14_5a9b_a53b_17cc02a2a8a8 #define WINRT_GENERIC_e83b4534_bd14_5a9b_a53b_17cc02a2a8a8 template <> struct __declspec(uuid("e83b4534-bd14-5a9b-a53b-17cc02a2a8a8")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteResult> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteResult> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_cba635ef_1c70_5412_8ede_7316276b9ee4 #define WINRT_GENERIC_cba635ef_1c70_5412_8ede_7316276b9ee4 template <> struct __declspec(uuid("cba635ef-1c70-5412-8ede-7316276b9ee4")) __declspec(novtable) IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattPresentationFormat> : impl_IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattPresentationFormat> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_21781028_f5a2_5d99_a5ab_bce6554fbc02 #define WINRT_GENERIC_21781028_f5a2_5d99_a5ab_bce6554fbc02 template <> struct __declspec(uuid("21781028-f5a2-5d99-a5ab-bce6554fbc02")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattServiceProviderResult> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattServiceProviderResult> {}; #endif #ifndef WINRT_GENERIC_56ce41b0_2570_50d3_a1b1_7e4167e1fde7 #define WINRT_GENERIC_56ce41b0_2570_50d3_a1b1_7e4167e1fde7 template <> struct __declspec(uuid("56ce41b0-2570-50d3-a1b1-7e4167e1fde7")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattServiceProvider, Windows::Devices::Bluetooth::GenericAttributeProfile::GattServiceProviderAdvertisementStatusChangedEventArgs> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattServiceProvider, Windows::Devices::Bluetooth::GenericAttributeProfile::GattServiceProviderAdvertisementStatusChangedEventArgs> {}; #endif #ifndef WINRT_GENERIC_1f97164e_88d5_567d_90f9_75d4f6455274 #define WINRT_GENERIC_1f97164e_88d5_567d_90f9_75d4f6455274 template <> struct __declspec(uuid("1f97164e-88d5-567d-90f9-75d4f6455274")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristicResult> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristicResult> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_e4865eba_6de3_5a99_9a75_7efd8e3cb096 #define WINRT_GENERIC_e4865eba_6de3_5a99_9a75_7efd8e3cb096 template <> struct __declspec(uuid("e4865eba-6de3-5a99-9a75-7efd8e3cb096")) __declspec(novtable) IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic> : impl_IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_3ef6d808_754f_5040_97ac_0703309c574f #define WINRT_GENERIC_3ef6d808_754f_5040_97ac_0703309c574f template <> struct __declspec(uuid("3ef6d808-754f-5040-97ac-0703309c574f")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptorResult> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptorResult> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_7f4688cc_0bbc_5070_8974_19fcb1acbf6c #define WINRT_GENERIC_7f4688cc_0bbc_5070_8974_19fcb1acbf6c template <> struct __declspec(uuid("7f4688cc-0bbc-5070-8974-19fcb1acbf6c")) __declspec(novtable) IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor> : impl_IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor> {}; #endif #ifndef WINRT_GENERIC_63391d79_4ba7_5f45_9681_3a683089353b #define WINRT_GENERIC_63391d79_4ba7_5f45_9681_3a683089353b template <> struct __declspec(uuid("63391d79-4ba7-5f45-9681-3a683089353b")) __declspec(novtable) IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSubscribedClient> : impl_IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSubscribedClient> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_8087acd6_aed7_53eb_9b23_4808bb910c17 #define WINRT_GENERIC_8087acd6_aed7_53eb_9b23_4808bb910c17 template <> struct __declspec(uuid("8087acd6-aed7-53eb-9b23-4808bb910c17")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic, Windows::Foundation::IInspectable> {}; #endif #ifndef WINRT_GENERIC_218a3e4a_aa9d_500e_bca7_047751bb10a3 #define WINRT_GENERIC_218a3e4a_aa9d_500e_bca7_047751bb10a3 template <> struct __declspec(uuid("218a3e4a-aa9d-500e-bca7-047751bb10a3")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic, Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadRequestedEventArgs> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic, Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadRequestedEventArgs> {}; #endif #ifndef WINRT_GENERIC_ed61a2fb_7d2a_5ba3_8ebf_8ad878e539a9 #define WINRT_GENERIC_ed61a2fb_7d2a_5ba3_8ebf_8ad878e539a9 template <> struct __declspec(uuid("ed61a2fb-7d2a-5ba3-8ebf-8ad878e539a9")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic, Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequestedEventArgs> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic, Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequestedEventArgs> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_c886eb62_ec71_586b_a158_66dc62a378b7 #define WINRT_GENERIC_c886eb62_ec71_586b_a158_66dc62a378b7 template <> struct __declspec(uuid("c886eb62-ec71-586b-a158-66dc62a378b7")) __declspec(novtable) IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> : impl_IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_de27c5cf_6227_5829_b997_88e575ad0680 #define WINRT_GENERIC_de27c5cf_6227_5829_b997_88e575ad0680 template <> struct __declspec(uuid("de27c5cf-6227-5829-b997-88e575ad0680")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> {}; #endif #ifndef WINRT_GENERIC_9c17a110_806d_594b_b33d_ed280bbf27e5 #define WINRT_GENERIC_9c17a110_806d_594b_b33d_ed280bbf27e5 template <> struct __declspec(uuid("9c17a110-806d-594b-b33d-ed280bbf27e5")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSubscribedClient, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSubscribedClient, Windows::Foundation::IInspectable> {}; #endif #ifndef WINRT_GENERIC_252dca5c_86e7_5be1_aeed_f78c6ed466ab #define WINRT_GENERIC_252dca5c_86e7_5be1_aeed_f78c6ed466ab template <> struct __declspec(uuid("252dca5c-86e7-5be1-aeed-f78c6ed466ab")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor, Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadRequestedEventArgs> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor, Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadRequestedEventArgs> {}; #endif #ifndef WINRT_GENERIC_6cf5b169_3731_591b_ae7c_d939faaa8a71 #define WINRT_GENERIC_6cf5b169_3731_591b_ae7c_d939faaa8a71 template <> struct __declspec(uuid("6cf5b169-3731-591b-ae7c-d939faaa8a71")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor, Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequestedEventArgs> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor, Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequestedEventArgs> {}; #endif #ifndef WINRT_GENERIC_0246e199_5199_5bdb_919d_8544ce30fd71 #define WINRT_GENERIC_0246e199_5199_5bdb_919d_8544ce30fd71 template <> struct __declspec(uuid("0246e199-5199-5bdb-919d-8544ce30fd71")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadRequest, Windows::Devices::Bluetooth::GenericAttributeProfile::GattRequestStateChangedEventArgs> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadRequest, Windows::Devices::Bluetooth::GenericAttributeProfile::GattRequestStateChangedEventArgs> {}; #endif #ifndef WINRT_GENERIC_7744c6bc_cdcd_5283_9e4f_2e21b49a2ef2 #define WINRT_GENERIC_7744c6bc_cdcd_5283_9e4f_2e21b49a2ef2 template <> struct __declspec(uuid("7744c6bc-cdcd-5283-9e4f-2e21b49a2ef2")) __declspec(novtable) TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequest, Windows::Devices::Bluetooth::GenericAttributeProfile::GattRequestStateChangedEventArgs> : impl_TypedEventHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequest, Windows::Devices::Bluetooth::GenericAttributeProfile::GattRequestStateChangedEventArgs> {}; #endif #ifndef WINRT_GENERIC_4732cec2_d943_5ceb_8281_8d54a21b9a45 #define WINRT_GENERIC_4732cec2_d943_5ceb_8281_8d54a21b9a45 template <> struct __declspec(uuid("4732cec2-d943-5ceb-8281-8d54a21b9a45")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadRequest> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadRequest> {}; #endif #ifndef WINRT_GENERIC_fb8b3c18_2f60_5b43_b773_146045816e03 #define WINRT_GENERIC_fb8b3c18_2f60_5b43_b773_146045816e03 template <> struct __declspec(uuid("fb8b3c18-2f60-5b43-b773-146045816e03")) __declspec(novtable) IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequest> : impl_IAsyncOperation<Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequest> {}; #endif #ifndef WINRT_GENERIC_ee154d83_805b_53e8_8469_90715036d013 #define WINRT_GENERIC_ee154d83_805b_53e8_8469_90715036d013 template <> struct __declspec(uuid("ee154d83-805b-53e8-8469-90715036d013")) __declspec(novtable) AsyncOperationCompletedHandler<winrt::Windows::Devices::Enumeration::DeviceAccessStatus> : impl_AsyncOperationCompletedHandler<winrt::Windows::Devices::Enumeration::DeviceAccessStatus> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_534cdf69_a258_5232_8dd3_ce94d8c256b0 #define WINRT_GENERIC_534cdf69_a258_5232_8dd3_ce94d8c256b0 template <> struct __declspec(uuid("534cdf69-a258-5232-8dd3-ce94d8c256b0")) __declspec(novtable) IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> : impl_IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> {}; #endif #ifndef WINRT_GENERIC_8beb3a26_73ca_50f3_a1d3_418c60a9f3b2 #define WINRT_GENERIC_8beb3a26_73ca_50f3_a1d3_418c60a9f3b2 template <> struct __declspec(uuid("8beb3a26-73ca-50f3-a1d3-418c60a9f3b2")) __declspec(novtable) IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> : impl_IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> {}; #endif #ifndef WINRT_GENERIC_4b192e23_4893_56b2_8eff_439c3ab7fd1f #define WINRT_GENERIC_4b192e23_4893_56b2_8eff_439c3ab7fd1f template <> struct __declspec(uuid("4b192e23-4893-56b2-8eff-439c3ab7fd1f")) __declspec(novtable) IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> : impl_IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_74ab0892_a631_5d6c_b1b4_bd2e1a741a9b #define WINRT_GENERIC_74ab0892_a631_5d6c_b1b4_bd2e1a741a9b template <> struct __declspec(uuid("74ab0892-a631-5d6c-b1b4-bd2e1a741a9b")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceServicesResult> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceServicesResult> {}; #endif #ifndef WINRT_GENERIC_cae01a28_fd33_542e_a5ad_3d878f73db90 #define WINRT_GENERIC_cae01a28_fd33_542e_a5ad_3d878f73db90 template <> struct __declspec(uuid("cae01a28-fd33-542e-a5ad-3d878f73db90")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSession> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSession> {}; #endif #ifndef WINRT_GENERIC_2dbcf64a_262b_5708_adb1_c3b8750bd680 #define WINRT_GENERIC_2dbcf64a_262b_5708_adb1_c3b8750bd680 template <> struct __declspec(uuid("2dbcf64a-262b-5708-adb1-c3b8750bd680")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_693c8447_2b8e_5e3c_8749_a4de166e1070 #define WINRT_GENERIC_693c8447_2b8e_5e3c_8749_a4de166e1070 template <> struct __declspec(uuid("693c8447-2b8e-5e3c-8749-a4de166e1070")) __declspec(novtable) IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic> : impl_IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic> {}; #endif #ifndef WINRT_GENERIC_1ffc4777_4346_5564_b7a5_59eae385f4f6 #define WINRT_GENERIC_1ffc4777_4346_5564_b7a5_59eae385f4f6 template <> struct __declspec(uuid("1ffc4777-4346-5564-b7a5-59eae385f4f6")) __declspec(novtable) IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic> : impl_IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic> {}; #endif #ifndef WINRT_GENERIC_e3c56728_7f2d_5a0d_ad38_030d39c60f9f #define WINRT_GENERIC_e3c56728_7f2d_5a0d_ad38_030d39c60f9f template <> struct __declspec(uuid("e3c56728-7f2d-5a0d-ad38-030d39c60f9f")) __declspec(novtable) IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic> : impl_IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_548b3cd0_dce8_5d3d_98ab_6948dd7f90b8 #define WINRT_GENERIC_548b3cd0_dce8_5d3d_98ab_6948dd7f90b8 template <> struct __declspec(uuid("548b3cd0-dce8-5d3d-98ab-6948dd7f90b8")) __declspec(novtable) AsyncOperationCompletedHandler<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattOpenStatus> : impl_AsyncOperationCompletedHandler<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattOpenStatus> {}; #endif #ifndef WINRT_GENERIC_d6a15475_1e72_5c56_98e8_88f4bc3e0313 #define WINRT_GENERIC_d6a15475_1e72_5c56_98e8_88f4bc3e0313 template <> struct __declspec(uuid("d6a15475-1e72-5c56-98e8-88f4bc3e0313")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristicsResult> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristicsResult> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_f8aca3dd_66b1_5fa6_a586_35ae7121f676 #define WINRT_GENERIC_f8aca3dd_66b1_5fa6_a586_35ae7121f676 template <> struct __declspec(uuid("f8aca3dd-66b1-5fa6-a586-35ae7121f676")) __declspec(novtable) IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptor> : impl_IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptor> {}; #endif #ifndef WINRT_GENERIC_3d8df436_cefb_5ffb_858c_4882ce1da079 #define WINRT_GENERIC_3d8df436_cefb_5ffb_858c_4882ce1da079 template <> struct __declspec(uuid("3d8df436-cefb-5ffb-858c-4882ce1da079")) __declspec(novtable) IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptor> : impl_IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptor> {}; #endif #ifndef WINRT_GENERIC_30e2ffc4_3aa3_5219_9a18_ca2d0b6562e8 #define WINRT_GENERIC_30e2ffc4_3aa3_5219_9a18_ca2d0b6562e8 template <> struct __declspec(uuid("30e2ffc4-3aa3-5219-9a18-ca2d0b6562e8")) __declspec(novtable) IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptor> : impl_IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptor> {}; #endif #ifndef WINRT_GENERIC_20006c53_5dda_5319_91b1_c6f28fe65933 #define WINRT_GENERIC_20006c53_5dda_5319_91b1_c6f28fe65933 template <> struct __declspec(uuid("20006c53-5dda-5319-91b1-c6f28fe65933")) __declspec(novtable) IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattPresentationFormat> : impl_IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattPresentationFormat> {}; #endif #ifndef WINRT_GENERIC_d75fcef1_c10e_5b7b_b130_f5a00314d35d #define WINRT_GENERIC_d75fcef1_c10e_5b7b_b130_f5a00314d35d template <> struct __declspec(uuid("d75fcef1-c10e-5b7b-b130-f5a00314d35d")) __declspec(novtable) IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattPresentationFormat> : impl_IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattPresentationFormat> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_d8992aa0_eac2_55b7_92c5_894886beb0ca #define WINRT_GENERIC_d8992aa0_eac2_55b7_92c5_894886beb0ca template <> struct __declspec(uuid("d8992aa0-eac2-55b7-92c5-894886beb0ca")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadResult> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadResult> {}; #endif #ifndef WINRT_GENERIC_2154117a_978d_59db_99cf_6b690cb3389b #define WINRT_GENERIC_2154117a_978d_59db_99cf_6b690cb3389b template <> struct __declspec(uuid("2154117a-978d-59db-99cf-6b690cb3389b")) __declspec(novtable) AsyncOperationCompletedHandler<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCommunicationStatus> : impl_AsyncOperationCompletedHandler<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCommunicationStatus> {}; #endif #ifndef WINRT_GENERIC_98f9a6f3_4d29_5351_8b12_751dc977a331 #define WINRT_GENERIC_98f9a6f3_4d29_5351_8b12_751dc977a331 template <> struct __declspec(uuid("98f9a6f3-4d29-5351-8b12-751dc977a331")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadClientCharacteristicConfigurationDescriptorResult> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadClientCharacteristicConfigurationDescriptorResult> {}; #endif #ifndef WINRT_GENERIC_df09ae77_f606_53e4_8ba6_799f5992c85e #define WINRT_GENERIC_df09ae77_f606_53e4_8ba6_799f5992c85e template <> struct __declspec(uuid("df09ae77-f606-53e4-8ba6-799f5992c85e")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptorsResult> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptorsResult> {}; #endif #ifndef WINRT_GENERIC_6fa8c9c3_ff7e_5fa1_a2f3_2714cf04b899 #define WINRT_GENERIC_6fa8c9c3_ff7e_5fa1_a2f3_2714cf04b899 template <> struct __declspec(uuid("6fa8c9c3-ff7e-5fa1-a2f3-2714cf04b899")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteResult> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteResult> {}; #endif #ifndef WINRT_GENERIC_f992789a_e981_597a_9197_1fbd986f74c7 #define WINRT_GENERIC_f992789a_e981_597a_9197_1fbd986f74c7 template <> struct __declspec(uuid("f992789a-e981-597a-9197-1fbd986f74c7")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattServiceProviderResult> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattServiceProviderResult> {}; #endif #ifndef WINRT_GENERIC_85c70edd_d815_5284_8c84_58a8f769e388 #define WINRT_GENERIC_85c70edd_d815_5284_8c84_58a8f769e388 template <> struct __declspec(uuid("85c70edd-d815-5284-8c84-58a8f769e388")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristicResult> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristicResult> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_66175161_4cfb_5ae5_aaff_48368b1a3a29 #define WINRT_GENERIC_66175161_4cfb_5ae5_aaff_48368b1a3a29 template <> struct __declspec(uuid("66175161-4cfb-5ae5-aaff-48368b1a3a29")) __declspec(novtable) IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic> : impl_IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic> {}; #endif #ifndef WINRT_GENERIC_edd74875_8e85_546f_83b8_1e00aa896419 #define WINRT_GENERIC_edd74875_8e85_546f_83b8_1e00aa896419 template <> struct __declspec(uuid("edd74875-8e85-546f-83b8-1e00aa896419")) __declspec(novtable) IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic> : impl_IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic> {}; #endif #ifndef WINRT_GENERIC_7082ed53_37f6_5262_8d09_939bea9edbd5 #define WINRT_GENERIC_7082ed53_37f6_5262_8d09_939bea9edbd5 template <> struct __declspec(uuid("7082ed53-37f6-5262-8d09-939bea9edbd5")) __declspec(novtable) IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic> : impl_IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_f2927eec_47d9_5338_9ba5_5be8461ad410 #define WINRT_GENERIC_f2927eec_47d9_5338_9ba5_5be8461ad410 template <> struct __declspec(uuid("f2927eec-47d9-5338-9ba5-5be8461ad410")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptorResult> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptorResult> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_78050e16_af8d_518a_a880_4885ccbdd62a #define WINRT_GENERIC_78050e16_af8d_518a_a880_4885ccbdd62a template <> struct __declspec(uuid("78050e16-af8d-518a-a880-4885ccbdd62a")) __declspec(novtable) IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor> : impl_IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor> {}; #endif #ifndef WINRT_GENERIC_08023045_5f5c_59cc_abd3_bbcfe6fa7030 #define WINRT_GENERIC_08023045_5f5c_59cc_abd3_bbcfe6fa7030 template <> struct __declspec(uuid("08023045-5f5c-59cc-abd3-bbcfe6fa7030")) __declspec(novtable) IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor> : impl_IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor> {}; #endif #ifndef WINRT_GENERIC_9016e9a2_c9f7_5d09_b0ae_552fa67796ae #define WINRT_GENERIC_9016e9a2_c9f7_5d09_b0ae_552fa67796ae template <> struct __declspec(uuid("9016e9a2-c9f7-5d09-b0ae-552fa67796ae")) __declspec(novtable) IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor> : impl_IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalDescriptor> {}; #endif #ifndef WINRT_GENERIC_354149d6_9889_5697_9659_66e6c88bee43 #define WINRT_GENERIC_354149d6_9889_5697_9659_66e6c88bee43 template <> struct __declspec(uuid("354149d6-9889-5697-9659-66e6c88bee43")) __declspec(novtable) IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSubscribedClient> : impl_IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSubscribedClient> {}; #endif #ifndef WINRT_GENERIC_df039115_a5ff_5d5a_b07b_20b42e078765 #define WINRT_GENERIC_df039115_a5ff_5d5a_b07b_20b42e078765 template <> struct __declspec(uuid("df039115-a5ff-5d5a-b07b-20b42e078765")) __declspec(novtable) IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSubscribedClient> : impl_IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSubscribedClient> {}; #endif #ifndef WINRT_GENERIC_b19864e4_f2b1_50de_8c11_fff9eca934e9 #define WINRT_GENERIC_b19864e4_f2b1_50de_8c11_fff9eca934e9 template <> struct __declspec(uuid("b19864e4-f2b1-50de-8c11-fff9eca934e9")) __declspec(novtable) IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSubscribedClient> : impl_IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattSubscribedClient> {}; #endif #ifndef WINRT_GENERIC_9263ccb7_c34e_59f7_aedf_5ac4b57c98ca #define WINRT_GENERIC_9263ccb7_c34e_59f7_aedf_5ac4b57c98ca template <> struct __declspec(uuid("9263ccb7-c34e-59f7-aedf-5ac4b57c98ca")) __declspec(novtable) IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> : impl_IVector<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> {}; #endif #ifndef WINRT_GENERIC_fca87386_a3ab_55e2_a83e_21f5bfab4049 #define WINRT_GENERIC_fca87386_a3ab_55e2_a83e_21f5bfab4049 template <> struct __declspec(uuid("fca87386-a3ab-55e2-a83e-21f5bfab4049")) __declspec(novtable) IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> : impl_IIterator<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> {}; #endif #ifndef WINRT_GENERIC_d3f4b8ad_251f_5bbb_ada2_ea47434e74d6 #define WINRT_GENERIC_d3f4b8ad_251f_5bbb_ada2_ea47434e74d6 template <> struct __declspec(uuid("d3f4b8ad-251f-5bbb-ada2-ea47434e74d6")) __declspec(novtable) IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> : impl_IIterable<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_9783fef1_1b62_5418_9898_933138c2bd14 #define WINRT_GENERIC_9783fef1_1b62_5418_9898_933138c2bd14 template <> struct __declspec(uuid("9783fef1-1b62-5418-9898-933138c2bd14")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult> {}; #endif #ifndef WINRT_GENERIC_31823848_3ab2_547a_8303_964dcc377c9c #define WINRT_GENERIC_31823848_3ab2_547a_8303_964dcc377c9c template <> struct __declspec(uuid("31823848-3ab2-547a-8303-964dcc377c9c")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadRequest> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadRequest> {}; #endif #ifndef WINRT_GENERIC_25b737f6_30ff_558e_ba16_b564c45fdc06 #define WINRT_GENERIC_25b737f6_30ff_558e_ba16_b564c45fdc06 template <> struct __declspec(uuid("25b737f6-30ff-558e-ba16-b564c45fdc06")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequest> : impl_AsyncOperationCompletedHandler<Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequest> {}; #endif #ifndef WINRT_GENERIC_b6fa5848_accd_536b_a37e_2444d86f2c1f #define WINRT_GENERIC_b6fa5848_accd_536b_a37e_2444d86f2c1f template <> struct __declspec(uuid("b6fa5848-accd-536b-a37e-2444d86f2c1f")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult>> : impl_IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult>> {}; #endif #ifndef WINRT_GENERIC_2f6c4343_667f_5d74_8ee7_b39de335a960 #define WINRT_GENERIC_2f6c4343_667f_5d74_8ee7_b39de335a960 template <> struct __declspec(uuid("2f6c4343-667f-5d74-8ee7-b39de335a960")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Devices::Bluetooth::GenericAttributeProfile::GattClientNotificationResult>> {}; #endif } namespace Windows::Devices::Bluetooth::GenericAttributeProfile { struct IGattCharacteristic : Windows::Foundation::IInspectable, impl::consume<IGattCharacteristic> { IGattCharacteristic(std::nullptr_t = nullptr) noexcept {} }; struct IGattCharacteristic2 : Windows::Foundation::IInspectable, impl::consume<IGattCharacteristic2>, impl::require<IGattCharacteristic2, Windows::Devices::Bluetooth::GenericAttributeProfile::IGattCharacteristic> { IGattCharacteristic2(std::nullptr_t = nullptr) noexcept {} }; struct IGattCharacteristic3 : Windows::Foundation::IInspectable, impl::consume<IGattCharacteristic3> { IGattCharacteristic3(std::nullptr_t = nullptr) noexcept {} }; struct IGattCharacteristicStatics : Windows::Foundation::IInspectable, impl::consume<IGattCharacteristicStatics> { IGattCharacteristicStatics(std::nullptr_t = nullptr) noexcept {} }; struct IGattCharacteristicUuidsStatics : Windows::Foundation::IInspectable, impl::consume<IGattCharacteristicUuidsStatics> { IGattCharacteristicUuidsStatics(std::nullptr_t = nullptr) noexcept {} }; struct IGattCharacteristicUuidsStatics2 : Windows::Foundation::IInspectable, impl::consume<IGattCharacteristicUuidsStatics2> { IGattCharacteristicUuidsStatics2(std::nullptr_t = nullptr) noexcept {} }; struct IGattCharacteristicsResult : Windows::Foundation::IInspectable, impl::consume<IGattCharacteristicsResult> { IGattCharacteristicsResult(std::nullptr_t = nullptr) noexcept {} }; struct IGattClientNotificationResult : Windows::Foundation::IInspectable, impl::consume<IGattClientNotificationResult> { IGattClientNotificationResult(std::nullptr_t = nullptr) noexcept {} }; struct IGattDescriptor : Windows::Foundation::IInspectable, impl::consume<IGattDescriptor> { IGattDescriptor(std::nullptr_t = nullptr) noexcept {} }; struct IGattDescriptor2 : Windows::Foundation::IInspectable, impl::consume<IGattDescriptor2> { IGattDescriptor2(std::nullptr_t = nullptr) noexcept {} }; struct IGattDescriptorStatics : Windows::Foundation::IInspectable, impl::consume<IGattDescriptorStatics> { IGattDescriptorStatics(std::nullptr_t = nullptr) noexcept {} }; struct IGattDescriptorUuidsStatics : Windows::Foundation::IInspectable, impl::consume<IGattDescriptorUuidsStatics> { IGattDescriptorUuidsStatics(std::nullptr_t = nullptr) noexcept {} }; struct IGattDescriptorsResult : Windows::Foundation::IInspectable, impl::consume<IGattDescriptorsResult> { IGattDescriptorsResult(std::nullptr_t = nullptr) noexcept {} }; struct IGattDeviceService : Windows::Foundation::IInspectable, impl::consume<IGattDeviceService>, impl::require<IGattDeviceService, Windows::Foundation::IClosable> { IGattDeviceService(std::nullptr_t = nullptr) noexcept {} }; struct IGattDeviceService2 : Windows::Foundation::IInspectable, impl::consume<IGattDeviceService2>, impl::require<IGattDeviceService2, Windows::Devices::Bluetooth::GenericAttributeProfile::IGattDeviceService, Windows::Foundation::IClosable> { IGattDeviceService2(std::nullptr_t = nullptr) noexcept {} }; struct IGattDeviceService3 : Windows::Foundation::IInspectable, impl::consume<IGattDeviceService3> { IGattDeviceService3(std::nullptr_t = nullptr) noexcept {} }; struct IGattDeviceServiceStatics : Windows::Foundation::IInspectable, impl::consume<IGattDeviceServiceStatics> { IGattDeviceServiceStatics(std::nullptr_t = nullptr) noexcept {} }; struct IGattDeviceServiceStatics2 : Windows::Foundation::IInspectable, impl::consume<IGattDeviceServiceStatics2> { IGattDeviceServiceStatics2(std::nullptr_t = nullptr) noexcept {} }; struct IGattDeviceServicesResult : Windows::Foundation::IInspectable, impl::consume<IGattDeviceServicesResult> { IGattDeviceServicesResult(std::nullptr_t = nullptr) noexcept {} }; struct IGattLocalCharacteristic : Windows::Foundation::IInspectable, impl::consume<IGattLocalCharacteristic> { IGattLocalCharacteristic(std::nullptr_t = nullptr) noexcept {} }; struct IGattLocalCharacteristicParameters : Windows::Foundation::IInspectable, impl::consume<IGattLocalCharacteristicParameters> { IGattLocalCharacteristicParameters(std::nullptr_t = nullptr) noexcept {} }; struct IGattLocalCharacteristicResult : Windows::Foundation::IInspectable, impl::consume<IGattLocalCharacteristicResult> { IGattLocalCharacteristicResult(std::nullptr_t = nullptr) noexcept {} }; struct IGattLocalDescriptor : Windows::Foundation::IInspectable, impl::consume<IGattLocalDescriptor> { IGattLocalDescriptor(std::nullptr_t = nullptr) noexcept {} }; struct IGattLocalDescriptorParameters : Windows::Foundation::IInspectable, impl::consume<IGattLocalDescriptorParameters> { IGattLocalDescriptorParameters(std::nullptr_t = nullptr) noexcept {} }; struct IGattLocalDescriptorResult : Windows::Foundation::IInspectable, impl::consume<IGattLocalDescriptorResult> { IGattLocalDescriptorResult(std::nullptr_t = nullptr) noexcept {} }; struct IGattLocalService : Windows::Foundation::IInspectable, impl::consume<IGattLocalService> { IGattLocalService(std::nullptr_t = nullptr) noexcept {} }; struct IGattPresentationFormat : Windows::Foundation::IInspectable, impl::consume<IGattPresentationFormat> { IGattPresentationFormat(std::nullptr_t = nullptr) noexcept {} }; struct IGattPresentationFormatStatics : Windows::Foundation::IInspectable, impl::consume<IGattPresentationFormatStatics> { IGattPresentationFormatStatics(std::nullptr_t = nullptr) noexcept {} }; struct IGattPresentationFormatStatics2 : Windows::Foundation::IInspectable, impl::consume<IGattPresentationFormatStatics2>, impl::require<IGattPresentationFormatStatics2, Windows::Devices::Bluetooth::GenericAttributeProfile::IGattPresentationFormatStatics> { IGattPresentationFormatStatics2(std::nullptr_t = nullptr) noexcept {} }; struct IGattPresentationFormatTypesStatics : Windows::Foundation::IInspectable, impl::consume<IGattPresentationFormatTypesStatics> { IGattPresentationFormatTypesStatics(std::nullptr_t = nullptr) noexcept {} }; struct IGattProtocolErrorStatics : Windows::Foundation::IInspectable, impl::consume<IGattProtocolErrorStatics> { IGattProtocolErrorStatics(std::nullptr_t = nullptr) noexcept {} }; struct IGattReadClientCharacteristicConfigurationDescriptorResult : Windows::Foundation::IInspectable, impl::consume<IGattReadClientCharacteristicConfigurationDescriptorResult> { IGattReadClientCharacteristicConfigurationDescriptorResult(std::nullptr_t = nullptr) noexcept {} }; struct IGattReadClientCharacteristicConfigurationDescriptorResult2 : Windows::Foundation::IInspectable, impl::consume<IGattReadClientCharacteristicConfigurationDescriptorResult2> { IGattReadClientCharacteristicConfigurationDescriptorResult2(std::nullptr_t = nullptr) noexcept {} }; struct IGattReadRequest : Windows::Foundation::IInspectable, impl::consume<IGattReadRequest> { IGattReadRequest(std::nullptr_t = nullptr) noexcept {} }; struct IGattReadRequestedEventArgs : Windows::Foundation::IInspectable, impl::consume<IGattReadRequestedEventArgs> { IGattReadRequestedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct IGattReadResult : Windows::Foundation::IInspectable, impl::consume<IGattReadResult> { IGattReadResult(std::nullptr_t = nullptr) noexcept {} }; struct IGattReadResult2 : Windows::Foundation::IInspectable, impl::consume<IGattReadResult2> { IGattReadResult2(std::nullptr_t = nullptr) noexcept {} }; struct IGattReliableWriteTransaction : Windows::Foundation::IInspectable, impl::consume<IGattReliableWriteTransaction> { IGattReliableWriteTransaction(std::nullptr_t = nullptr) noexcept {} }; struct IGattReliableWriteTransaction2 : Windows::Foundation::IInspectable, impl::consume<IGattReliableWriteTransaction2> { IGattReliableWriteTransaction2(std::nullptr_t = nullptr) noexcept {} }; struct IGattRequestStateChangedEventArgs : Windows::Foundation::IInspectable, impl::consume<IGattRequestStateChangedEventArgs> { IGattRequestStateChangedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct IGattServiceProvider : Windows::Foundation::IInspectable, impl::consume<IGattServiceProvider> { IGattServiceProvider(std::nullptr_t = nullptr) noexcept {} }; struct IGattServiceProviderAdvertisementStatusChangedEventArgs : Windows::Foundation::IInspectable, impl::consume<IGattServiceProviderAdvertisementStatusChangedEventArgs> { IGattServiceProviderAdvertisementStatusChangedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct IGattServiceProviderAdvertisingParameters : Windows::Foundation::IInspectable, impl::consume<IGattServiceProviderAdvertisingParameters> { IGattServiceProviderAdvertisingParameters(std::nullptr_t = nullptr) noexcept {} }; struct IGattServiceProviderResult : Windows::Foundation::IInspectable, impl::consume<IGattServiceProviderResult> { IGattServiceProviderResult(std::nullptr_t = nullptr) noexcept {} }; struct IGattServiceProviderStatics : Windows::Foundation::IInspectable, impl::consume<IGattServiceProviderStatics> { IGattServiceProviderStatics(std::nullptr_t = nullptr) noexcept {} }; struct IGattServiceUuidsStatics : Windows::Foundation::IInspectable, impl::consume<IGattServiceUuidsStatics> { IGattServiceUuidsStatics(std::nullptr_t = nullptr) noexcept {} }; struct IGattServiceUuidsStatics2 : Windows::Foundation::IInspectable, impl::consume<IGattServiceUuidsStatics2> { IGattServiceUuidsStatics2(std::nullptr_t = nullptr) noexcept {} }; struct IGattSession : Windows::Foundation::IInspectable, impl::consume<IGattSession> { IGattSession(std::nullptr_t = nullptr) noexcept {} }; struct IGattSessionStatics : Windows::Foundation::IInspectable, impl::consume<IGattSessionStatics> { IGattSessionStatics(std::nullptr_t = nullptr) noexcept {} }; struct IGattSessionStatusChangedEventArgs : Windows::Foundation::IInspectable, impl::consume<IGattSessionStatusChangedEventArgs> { IGattSessionStatusChangedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct IGattSubscribedClient : Windows::Foundation::IInspectable, impl::consume<IGattSubscribedClient> { IGattSubscribedClient(std::nullptr_t = nullptr) noexcept {} }; struct IGattValueChangedEventArgs : Windows::Foundation::IInspectable, impl::consume<IGattValueChangedEventArgs> { IGattValueChangedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct IGattWriteRequest : Windows::Foundation::IInspectable, impl::consume<IGattWriteRequest> { IGattWriteRequest(std::nullptr_t = nullptr) noexcept {} }; struct IGattWriteRequestedEventArgs : Windows::Foundation::IInspectable, impl::consume<IGattWriteRequestedEventArgs> { IGattWriteRequestedEventArgs(std::nullptr_t = nullptr) noexcept {} }; struct IGattWriteResult : Windows::Foundation::IInspectable, impl::consume<IGattWriteResult> { IGattWriteResult(std::nullptr_t = nullptr) noexcept {} }; } }
#ifndef STRPAIRARR_H #define STRPAIRARR_H #include "pair.h" template <typename Key, typename Value> class StrPairArr { public: StrPairArr(); private: }; #endif // STRPAIRARR_H
/*************************************************************************** dialogonumeromostrar.cpp - description ------------------- begin : jue abr 8 2004 copyright : (C) 2004 by Oscar G. Duarte email : ogduarte@ing.unal.edu.co ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "dialogonumeromostrar.h" BEGIN_EVENT_TABLE(DialogoNumeroMostrar, wxDialog) EVT_PAINT(DialogoNumeroMostrar::OnPaint) EVT_BUTTON(DLG_NUMERO_MOSTRAR_BTN_OK, DialogoNumeroMostrar::cerrarOk) EVT_BUTTON(DLG_NUMERO_MOSTRAR_BTN_CANCEL, DialogoNumeroMostrar::cancelar) EVT_BUTTON(DLG_NUMERO_MOSTRAR_BTN_AYUDA, DialogoNumeroMostrar::ayuda) EVT_LISTBOX(DLG_NUMERO_MOSTRAR_LISTBOX_ETIQUETAS,DialogoNumeroMostrar::seleccionarEtiqueta) END_EVENT_TABLE() DialogoNumeroMostrar::DialogoNumeroMostrar(VariableLinguistica *var, NumeroDifuso *num,wxWindow *parent,const wxString& title, wxHtmlHelpController *ayuda) :wxDialog(parent,-1,title) { Var=var; Num=num; Ayuda=ayuda; SetTitle(wxT("Número Difuso Calculado")); ButtonOK =new wxButton(this,DLG_NUMERO_MOSTRAR_BTN_OK, wxT("OK")); ButtonCancelar =new wxButton(this,DLG_NUMERO_MOSTRAR_BTN_CANCEL, wxT("Cancelar")); ButtonAyuda =new wxButton (this,DLG_NUMERO_MOSTRAR_BTN_AYUDA, wxT("Ayuda")); StaticNombre =new wxStaticText(this,DLG_NUMERO_MOSTRAR_STATIC_NOMBRE, wxT("Nombre")); StaticMinimo =new wxStaticText(this,DLG_NUMERO_MOSTRAR_STATIC_MINIMO, wxT("Mínimo")); StaticMaximo =new wxStaticText(this,DLG_NUMERO_MOSTRAR_STATIC_MAXIMO, wxT("Máximo")); StaticUnidades =new wxStaticText(this,DLG_NUMERO_MOSTRAR_STATIC_UNIDADES, wxT("Unidades")); StaticEtiquetas =new wxStaticText(this,DLG_NUMERO_MOSTRAR_STATIC_ETIQUETAS, wxT("Etiquetas")); StaticValorCalculado =new wxStaticText(this,DLG_NUMERO_MOSTRAR_STATIC_VALORCALCULADO, wxT("El Valor es...")); TextNombre =new wxTextCtrl(this,DLG_NUMERO_MOSTRAR_TEXT_NOMBRE,wxT(""),wxDefaultPosition,wxDefaultSize,wxTE_READONLY); TextMinimo =new wxTextCtrl(this,DLG_NUMERO_MOSTRAR_TEXT_MINIMO,wxT(""),wxDefaultPosition,wxDefaultSize,wxTE_READONLY); TextMaximo =new wxTextCtrl(this,DLG_NUMERO_MOSTRAR_TEXT_MAXIMO,wxT(""),wxDefaultPosition,wxDefaultSize,wxTE_READONLY); TextUnidades =new wxTextCtrl(this,DLG_NUMERO_MOSTRAR_TEXT_UNIDADES,wxT(""),wxDefaultPosition,wxDefaultSize,wxTE_READONLY); ListBoxEtiquetas =new wxListBox(this,DLG_NUMERO_MOSTRAR_LISTBOX_ETIQUETAS,wxPoint(0,0),wxSize(150, 80), 0, 0, wxLB_SINGLE|wxLB_ALWAYS_SB); /* ButtonOK ->SetSize(80,20); ButtonCancelar ->SetSize(80,20); ButtonAyuda ->SetSize(80,20);*/ StaticValorCalculado ->SetMinSize(wxSize(180,20)); TextNombre ->SetMinSize(wxSize(300,20)); TextMinimo ->SetMinSize(wxSize(40,20)); TextMaximo ->SetMinSize(wxSize(40,20)); TextUnidades ->SetMinSize(wxSize(40,20)); ListBoxEtiquetas ->SetMinSize(wxSize(100,80)); SizerDibujo=new wxBoxSizer(wxHORIZONTAL); SizerDibujo->Add(200,80, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5); wxBoxSizer *sizerNombre = new wxBoxSizer(wxHORIZONTAL); sizerNombre->Add(StaticNombre, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5); sizerNombre->Add(TextNombre, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5); wxBoxSizer *sizerMinMax = new wxBoxSizer(wxHORIZONTAL); sizerMinMax->Add(StaticMinimo, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5); sizerMinMax->Add(TextMinimo, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5); sizerMinMax->Add(StaticMaximo, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5); sizerMinMax->Add(TextMaximo, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5); sizerMinMax->Add(StaticUnidades, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5); sizerMinMax->Add(TextUnidades, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5); wxBoxSizer *sizerEtiDib = new wxBoxSizer(wxVERTICAL); sizerEtiDib->Add(StaticEtiquetas, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5); sizerEtiDib->Add(SizerDibujo, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5); wxBoxSizer *sizerEtiqueta = new wxBoxSizer(wxHORIZONTAL); sizerEtiqueta->Add(sizerEtiDib, 0, wxALIGN_BOTTOM | wxLEFT |wxRIGHT, 5); sizerEtiqueta->Add(ListBoxEtiquetas, 0, wxALIGN_BOTTOM | wxLEFT |wxRIGHT, 5); wxBoxSizer *sizerValCombo = new wxBoxSizer(wxVERTICAL); sizerValCombo->Add(StaticValorCalculado, 0, wxALIGN_LEFT | wxLEFT |wxRIGHT, 5); wxBoxSizer *sizerValor = new wxBoxSizer(wxHORIZONTAL); sizerValor->Add(sizerValCombo, 0, wxALIGN_BOTTOM | wxLEFT |wxRIGHT, 5); wxBoxSizer *sizerButInf = new wxBoxSizer(wxHORIZONTAL); sizerButInf->Add(ButtonOK, 0, wxALIGN_CENTER | wxALL, 5); sizerButInf->Add(ButtonCancelar, 0, wxALIGN_CENTER | wxALL, 5); sizerButInf->Add(ButtonAyuda, 0, wxALIGN_CENTER | wxALL, 5); wxBoxSizer *sizerTotal = new wxBoxSizer(wxVERTICAL); sizerTotal->Add(sizerNombre, 0, wxALIGN_CENTER | wxALL, 5); sizerTotal->Add(sizerMinMax, 0, wxALIGN_CENTER | wxALL, 5); sizerTotal->Add(sizerEtiqueta, 0, wxALIGN_CENTER | wxALL, 5); sizerTotal->Add(sizerValor, 0, wxALIGN_CENTER | wxALL, 5); sizerTotal->Add(sizerButInf, 0, wxALIGN_CENTER | wxALL, 5); SetAutoLayout(TRUE); SetSizer(sizerTotal); sizerTotal->SetSizeHints(this); sizerTotal->Fit(this); llenarCuadro(); } DialogoNumeroMostrar::~DialogoNumeroMostrar() { } void DialogoNumeroMostrar::llenarCuadro() { wxString cad; cad=wxT(""); cad << Var->Nombre;TextNombre->SetValue(cad); cad=wxT(""); cad << Var->Minimo;TextMinimo->SetValue(cad); cad=wxT(""); cad << Var->Maximo;TextMaximo->SetValue(cad); cad=wxT(""); cad << Var->Unidades;TextUnidades->SetValue(cad); int i,tam; ListBoxEtiquetas->Clear(); tam=Var->Etiquetas.GetCount(); for(i=0;i<tam;i++) { cad=wxT(""); cad << Var->Etiquetas.Item(i).Label; ListBoxEtiquetas->Append(cad); } ListBoxEtiquetas->SetSelection(0); Refresh(); // cad=Var->strEntrada(); cad = wxT("Valor: "); cad << Num->valorRepresentativo(0.5,1); cad << wxT(" / "); cad << Num->ambiguedad(); StaticValorCalculado->SetLabel(cad); } void DialogoNumeroMostrar::OnPaint(wxPaintEvent&) { wxPaintDC dc(this); // PrepareDC(dc); pintar(dc); } void DialogoNumeroMostrar::pintar(wxPaintDC &dc) { // wxPaintDC dc(this); wxPoint Origen; wxSize Tamano; Origen=SizerDibujo->GetPosition(); Tamano=SizerDibujo->GetSize(); dc.SetPen(* wxBLACK_PEN); // dc.DrawRectangle(Origen.x,Origen.y,Tamano.GetWidth(),Tamano.GetHeight()); dc.DrawRectangle(Origen,Tamano); // un pequeño offset Origen.x+=5; Origen.y+=5; Tamano.SetWidth(Tamano.GetWidth()-10); Tamano.SetHeight(Tamano.GetHeight()-5); int i,tam; tam=Var->Etiquetas.GetCount(); for(i=0;i<tam;i++) { if (i == ListBoxEtiquetas->GetSelection()) { dc.SetPen(* wxRED_PEN); }else { dc.SetPen(* wxBLUE_PEN); } NumeroDifuso *n; n=Var->Etiquetas.Item(i).ND; int j,tam2; tam2=n->Tamano; float xLo,xLf,xRo,xRf,yo,yf; for(j=0;j<tam2-1;j++) { yo=j*n->intervalo(); yf=(j+1)*n->intervalo(); xLo=n->L[j]; xLf=n->L[j+1]; xRo=n->R[j]; xRf=n->R[j+1]; xLo = Origen.x + (xLo - Var->Minimo)*(Tamano.GetWidth())/(Var->Maximo-Var->Minimo); xLf = Origen.x + (xLf - Var->Minimo)*(Tamano.GetWidth())/(Var->Maximo-Var->Minimo); xRo = Origen.x + (xRo - Var->Minimo)*(Tamano.GetWidth())/(Var->Maximo-Var->Minimo); xRf = Origen.x + (xRf - Var->Minimo)*(Tamano.GetWidth())/(Var->Maximo-Var->Minimo); // y aumenta hacia abajo !!! yo = Origen.y + Tamano.GetHeight() - (yo - 0.0)*(Tamano.GetHeight())/(1.0-0.0); yf = Origen.y + Tamano.GetHeight() - (yf - 0.0)*(Tamano.GetHeight())/(1.0-0.0); dc.DrawLine(xLo,yo,xLf,yf); dc.DrawLine(xRo,yo,xRf,yf); } dc.DrawLine(xLf,yf,xRf,yf); } // if(CheckValor->GetValue()) { dc.SetPen(* wxBLACK_PEN); NumeroDifuso *n; // n=Var->valor(); n=Num; int j,tam2; tam2=n->Tamano; float xLo,xLf,xRo,xRf,yo,yf; for(j=0;j<tam2-1;j++) { yo=j*n->intervalo(); yf=(j+1)*n->intervalo(); xLo=n->L[j]; xLf=n->L[j+1]; xRo=n->R[j]; xRf=n->R[j+1]; xLo = Origen.x + (xLo - Var->Minimo)*(Tamano.GetWidth())/(Var->Maximo-Var->Minimo); xLf = Origen.x + (xLf - Var->Minimo)*(Tamano.GetWidth())/(Var->Maximo-Var->Minimo); xRo = Origen.x + (xRo - Var->Minimo)*(Tamano.GetWidth())/(Var->Maximo-Var->Minimo); xRf = Origen.x + (xRf - Var->Minimo)*(Tamano.GetWidth())/(Var->Maximo-Var->Minimo); // y aumenta hacia abajo !!! yo = Origen.y + Tamano.GetHeight() - (yo - 0.0)*(Tamano.GetHeight())/(1.0-0.0); yf = Origen.y + Tamano.GetHeight() - (yf - 0.0)*(Tamano.GetHeight())/(1.0-0.0); dc.DrawLine(xLo,yo,xLf,yf); dc.DrawLine(xRo,yo,xRf,yf); } dc.DrawLine(xLf,yf,xRf,yf); } } void DialogoNumeroMostrar::seleccionarEtiqueta(wxCommandEvent&) { if(Var->TipoDeValor==4) { Var->EtiquetaSeleccionada=ListBoxEtiquetas->GetSelection(); llenarCuadro(); ListBoxEtiquetas->SetSelection(Var->EtiquetaSeleccionada); }else { Refresh(); } } void DialogoNumeroMostrar::cerrarOk(wxCommandEvent&) { Close(); } void DialogoNumeroMostrar::cancelar(wxCommandEvent&) { Close(); } void DialogoNumeroMostrar::ayuda(wxCommandEvent&) { Ayuda->Display(wxT("Presentación de Números Difusos")); }
/* * Copyright 2021 Stylianos Piperakis, Foundation for Research and Technology Hellas (FORTH) * License: BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Foundation for Research and Technology Hellas (FORTH) * nor the names of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <apollo_lidar/apollo_lidar_ros.h> #include <math.h> void apollo_lidar_ros::processLaserScan(const sensor_msgs::LaserScan::ConstPtr& msg0, const sensor_msgs::LaserScan::ConstPtr& msg1) { sensor_msgs::LaserScan scan_in0 = *msg0; sensor_msgs::LaserScan scan_in1 = *msg1; sensor_msgs::LaserScan scan_out; scan_out.header.frame_id = "laser"; scan_out.header.stamp = ros::Time::now(); scan_out.angle_min = fmin(scan_in0.angle_min,scan_in1.angle_min); scan_out.angle_max = fmax(scan_in0.angle_max,scan_in1.angle_max); scan_out.angle_increment = fmax(scan_in0.angle_increment,scan_in1.angle_increment); scan_out.time_increment = fmax(scan_in0.time_increment,scan_in1.time_increment); scan_out.scan_time = fmax(scan_in0.scan_time,scan_in1.scan_time); scan_out.range_min = fmin(scan_in0.range_min,scan_in1.range_min); scan_out.range_max = fmax(scan_in0.range_max,scan_in1.range_max); int j = 0; scan_out.ranges.resize(scan_in0.ranges.size()+scan_in1.ranges.size()); for(unsigned int i = 0; i < scan_in0.ranges.size(); ++i) { //if( (scan_in.ranges[i] == scan_in.ranges[i]) && !isinf(scan_in.ranges[i]) ) //{ scan_out.ranges[j] = scan_in0.ranges[i]; j++; //} } for(unsigned int i = 0; i < scan_in1.ranges.size(); ++i) { scan_out.ranges[j] = scan_in1.ranges[i]; j++; } pub.publish(scan_out); } void apollo_lidar_ros::init(ros::NodeHandle node_handle_) { nh = node_handle_; ros::NodeHandle n_p("~"); n_p.param<std::string>("scan_topic0", scan_topic0, "/inter/scan"); n_p.param<std::string>("scan_topic1", scan_topic1, "/scan"); laser_sub0 = new message_filters::Subscriber<sensor_msgs::LaserScan>(nh, scan_topic0, 1); laser_sub1 = new message_filters::Subscriber<sensor_msgs::LaserScan>(nh, scan_topic1, 1); pub = nh.advertise<sensor_msgs::LaserScan>("apollo/scan",10); } void apollo_lidar_ros::run() { message_filters::Synchronizer<MySyncPolicy> sync(MySyncPolicy(10), *laser_sub0, *laser_sub1); sync.registerCallback(boost::bind(&apollo_lidar_ros::processLaserScan, this, _1, _2)); ros::spin(); }
#include "stdafx.h" #include<sstream> #include<fstream> #include<iostream> #include<algorithm> #include<string> #include<list> #include<map> using namespace std; typedef map<char, int> CharMap; void insertDuCharHelper(CharMap charmap, string prefix, int remaining, list<string> &allStrings){ //Base Case. Permutation has been completed. if (remaining == 0){ allStrings.push_back(prefix); return; } //Use each letter as the prefix and update the remaining and charmap. for (CharMap::iterator i = charmap.begin(); i != charmap.end(); ++i){ if (i->second > 0){ i->second--; insertDuCharHelper(charmap, prefix + i->first, remaining - 1, allStrings); //Recover the hash table to other cases. i->second++; } } } list<string> insertDuChar(string ori){ list<string> allStrings; //case 1. If ori is NULL if (ori.length() == 0){ allStrings.push_back(""); return allStrings; } //generate a hash map; CharMap charMap; for (auto &s : ori){ charMap[s]++; } string prefix = ""; int remaining = ori.length(); insertDuCharHelper(charMap, prefix, remaining, allStrings); return allStrings; } int main(){ string test = "abab"; list<string> allStrings; allStrings = insertDuChar(test); for (auto &c : allStrings){ cout << c << endl; } system("pause"); return 0; }
#ifndef _escenaH_ #define _escenaH_ #include "PLY2.h" #include "cuadro.h" //Esta clase va a servir para dibujar las distintas escenas requeridas en la práctica 4 using namespace std; class escena{ GLuint ID_text; PLY lata_tapa; PLY lata_tronco; PLY lata_culo; PLY peon1; PLY peon2; PLY peon3; PLY bet1; PLY bet2; PLY bet3; PLY bet4; PLY bet5; PLY bet6; int figuraSeleccionada; figura3D esfera; bool esferaTextura; cuadro cuad; bool instancia; int dibujo; GLUquadric *esfer; public: escena(); bool instanciado(); void cambiarTexturaEsfera(); void instanciar(int lados, char eje); void cambiarEscena(); void seleccionarFigura(int i); void draw(char mode); _vertex3f centroGiro(); }; #endif
/* * Copyright 2016-2017 Flatiron Institute, Simons Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mvcontrolpanel2.h" //#include "qAccordion/qaccordion.h" #include "toolbox.h" #include <QHBoxLayout> #include <QPushButton> //#include "mlcommon.h" #include "mvmainwindow.h" class MVControlPanel2Private { public: MVControlPanel2* q; ToolBox* m_accordion; QList<MVAbstractControl*> m_controls; MVAbstractContext* m_context; MVMainWindow* m_main_window; }; MVControlPanel2::MVControlPanel2(MVAbstractContext* context, MVMainWindow* mw) { d = new MVControlPanel2Private; d->q = this; d->m_context = context; d->m_main_window = mw; QHBoxLayout* top_layout = new QHBoxLayout; top_layout->setSpacing(20); top_layout->setMargin(20); { QPushButton* B = new QPushButton("Recalc Visible"); top_layout->addWidget(B); QObject::connect(B, SIGNAL(clicked(bool)), this, SLOT(slot_recalc_visible())); } { QPushButton* B = new QPushButton("Recalc All"); top_layout->addWidget(B); QObject::connect(B, SIGNAL(clicked(bool)), this, SLOT(slot_recalc_all())); } d->m_accordion = new ToolBox; // d->m_accordion->setMultiActive(true); // QScrollArea* SA = new QScrollArea; // SA->setWidget(d->m_accordion); // SA->setWidgetResizable(true); QVBoxLayout* vlayout = new QVBoxLayout; vlayout->setSpacing(0); vlayout->setMargin(0); vlayout->addLayout(top_layout); vlayout->addWidget(d->m_accordion); this->setLayout(vlayout); } MVControlPanel2::~MVControlPanel2() { delete d; } void MVControlPanel2::insertControl(int position, MVAbstractControl* mvcontrol, bool start_open) { if (position < 0) d->m_controls << mvcontrol; else d->m_controls.insert(position, mvcontrol); // QFrame* frame = new QFrame; // QHBoxLayout* frame_layout = new QHBoxLayout; // frame_layout->addWidget(mvcontrol); // frame->setLayout(frame_layout); // ContentPane* CP = new ContentPane(mvcontrol->title(), frame); // CP->setMaximumHeight(1000); if (position < 0) { d->m_accordion->addWidget(mvcontrol, mvcontrol->title()); } else d->m_accordion->insertWidget(position, mvcontrol, mvcontrol->title()); if (start_open) { d->m_accordion->open(d->m_accordion->indexOf(mvcontrol)); //CP->openContentPane(); } mvcontrol->updateControls(); mvcontrol->updateContext(); //do this so the default values get passed on to the context } void MVControlPanel2::addControl(MVAbstractControl* mvcontrol, bool start_open) { insertControl(-1, mvcontrol, start_open); } void MVControlPanel2::slot_recalc_visible() { d->m_main_window->recalculateViews(MVMainWindow::SuggestedVisible); } void MVControlPanel2::slot_recalc_all() { d->m_main_window->recalculateViews(MVMainWindow::Suggested); }
#ifndef CONTROLS_H #define CONTROLS_H #include <FastCG/World/Behaviour.h> using namespace FastCG; class Controls : public Behaviour { FASTCG_DECLARE_COMPONENT(Controls, Behaviour); protected: void OnUpdate(float time, float deltaTime) override; private: uint8_t mPressedKeyMask{0}; }; #endif
// github.com/andy489 // https://www.hackerrank.com/contests/practice-4-sda/challenges/truck-ordering/ #include <iostream> #include <vector> #include <stack> using namespace std; typedef vector<int> vi; #define F(i, k, n) for(int i=k;i<n;++i) bool fmiTrucks() { int n, truck, cnt(1); cin >> n; stack<int> aux, final; F(i, 0, n) { cin >> truck; if (truck == cnt) final.push(truck),++cnt; else aux.push(truck); } while (!aux.empty()) { if (aux.top() != cnt) return false; else final.push(aux.top()), aux.pop(),++cnt; } return true; } int main() { int T; cin >> T; F(i, 0, T) fmiTrucks() ? cout << "yes\n" : cout << "no\n"; return 0; }
#include <cassert> #include <iostream> using namespace std; #include "cpp_algs.hpp" int main() { ds::SinglyLinkedList<int> sing = ds::SinglyLinkedList<int>(); sing.insertNode(10); sing.insertNode(20); sing.print(); ds::SinglyLinkedList<string> s = ds::SinglyLinkedList<string>(); s.insertNode("hello"); s.insertNode(", "); s.insertNode("world"); s.insertNode("!"); s.print(); int *arr = new int[5]{43, 44, 45, 46, 47}; sing.insertArray(arr, 5); sing.print(); cout << "Verified installation of library!" << '\n'; // cleanup delete[] arr; return 0; }
// // Copyright Jason Rice 2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef NBDL_BINDER_HASH_HPP #define NBDL_BINDER_HASH_HPP #include <nbdl/bind_map.hpp> #include <nbdl/bind_sequence.hpp> #include <nbdl/bind_variant.hpp> #include <nbdl/concept/BindableMap.hpp> #include <nbdl/concept/BindableSequence.hpp> #include <nbdl/concept/BindableVariant.hpp> #include <nbdl/concept/Container.hpp> #include <nbdl/detail/hash_combine.hpp> #include <functional> namespace nbdl::binder { namespace hash_detail { struct writer { std::size_t digest; writer() : digest(0) { } template <BindableSequence T> void bind(T const& t) { nbdl::bind_sequence(t, [&](auto const& ...xs) { hana::for_each(hana::make_tuple(std::cref(xs)...), [&](auto const& x) { bind(x.get()); }); }); } template <BindableVariant T> void bind(T const& t) { nbdl::bind_variant(t, [&](auto const& type_id, auto const& value) { bind(type_id); bind(value); }); } template <Container T> void bind(T const& t) { for (auto const& x : t) { nbdl::detail::hash_combine(digest, x); } } template <typename T> void bind(T const& t) { nbdl::detail::hash_combine(digest, t); } }; } struct hash_fn { template <typename T> std::size_t operator()(T const& t) const { hash_detail::writer binder{}; binder.bind(t); return binder.digest; } }; constexpr hash_fn hash{}; } #endif
#include <bits/stdc++.h> #define ull unsigned long long #define ll long long #define il inline #define ls rt << 1 #define rs rt << 1 | 1 #define pb push_back #define mp make_pair #define pii pair<int, int> #define X first #define Y second #define pcc pair<char, char> #define vi vector<int> #define vl vector<ll> #define rep(i, x, y) for(int i = x; i <= y; i ++) #define rrep(i, x, y) for(int i = x; i >= y; i --) #define rep0(i, n) for(int i = 0; i < (n); i ++) #define per0(i, n) for(int i = (n) - 1; i >= 0; i --) #define INF 0x3f3f3f3f #define sz(x) (int)(x).size() #define ALL(x) (x).begin(), (x).end() using namespace std; #define ld long double static char ibuf[1 << 20]; char *fis = ibuf, *fit = ibuf; inline char readChar() { return fis == fit && (fit = (fis = ibuf) + fread(ibuf, 1, 1 << 20, stdin), fis == fit) ? EOF : *fis++; } inline int read() { char c; int x; for (c = readChar(); !isdigit(c); c = readChar()); for (x = 0; isdigit(c); c = readChar()) { x = x * 10 + c - '0'; } return x; } static char ostc[100], obuf[1 << 20]; int ol = 0; char *fos = obuf, *fot = obuf + (1 << 20) - 1; inline void writeChar(char c) { *fos++ = c; if (fos == fot) { fwrite(obuf, 1, fos - obuf, stdout); fos = obuf; } } inline void write(int n, char c) { if (!n) { writeChar('0'); } else { while (n) { ostc[++ol] = n % 10 + 48, n /= 10; } } for (; ol; ol--) { writeChar(ostc[ol]); } writeChar(c); } const long double eps = 1e-9; const int N = 1e5 + 10; vector<pii> G[N]; int dp[N][2][5]; void dfs(int x, int fa, int len) { int ndp[2][5]; dp[x][0][0] = 0; for(auto pp : G[x]) { int to = pp.X; int val = pp.Y; if(to == fa) continue; dfs(to, x, val); rep0(i, 2) rep0(j, 5) ndp[i][j] = INF; rep0(i, 2) rep0(j, 5) rep0(ii, 2) rep0(jj, 5) if(j + jj <= 4) ndp[i ^ ii][j + jj] = min(ndp[i ^ ii][j + jj], dp[x][i][j] + dp[to][ii][jj]); rep0(i, 2) rep0(j, 5) dp[x][i][j] = ndp[i][j]; } rep0(i, 2) rep0(j, 5) ndp[i][j] = INF; rep0(i, 2) rep0(j, 5) rep(use, 1, 2) { int nn = (i + use) % 2; int nc = j + nn; if(nc > 4) continue; int nt = dp[x][i][j] + (use == 2 ? len : 0); ndp[use & 1][nc] = min(ndp[use & 1][nc], nt); } rep0(i, 2) rep0(j, 5) dp[x][i][j] = ndp[i][j]; } int main() { int n = read(); int ans = 0; memset(dp, INF, sizeof(dp)); rep(i, 1, n - 1) { int x, y, z; x = read(); y = read(); z = read(); G[x].pb({y, z}); G[y].pb({x, z}); ans += z; } dfs(1, 0, 0); int res = INF; rep0(i, 5) res = min(res, dp[1][0][i]); printf("%d\n", ans + res); }
// // MockEntityModel.h // MyGame // // Created by Ariant Uka on 2015-03-03. // // #ifndef __MyGame__MockEntityModel__ #define __MyGame__MockEntityModel__ #include "IEntityModel.h" class MockEntityModel: public IEntityModel { public: MockEntityModel(); std::shared_ptr<Entity> findEntityById(int entityId); }; #endif /* defined(__MyGame__MockEntityModel__) */
#ifndef MENUSYSTEM_H #define MENUSYSTEM_H enum menuID{ MAIN=1, WEAKLY, CARD, CONNECT }; class MenuSystem { private: public: MenuSystem(); void mainMenu(); void weaklyMenu(); void menuCard(); void connections(); }; #endif // MENUSYSTEM_H
#include "audio\Singularity.Audio.h" /* * AdaptiveMusicManager.h * * Handles all adaptive music. Loads in a given file and plays music based upon the information given by the AdaptiveMusicUpdater(s). * * Author: Sela Davis * * Created: March 15, 2010 (03/15/10) * Last modified: March 15, 2010 (03/15/10) */ namespace Singularity { namespace Audio { class AdaptiveMusicManager { private: #pragma region Static Variables // The single instance of the AudioManager. static AdaptiveMusicManager* g_pInstance; #pragma endregion #pragma region Variables bool m_bIsPlaying; // A list of AdaptiveEnvironments. DynamicList<AdaptiveEnvironment*> m_pEnvironments; // we only keep a list so that we don't lose any that we want to keep loaded in // A list of Cues. DynamicList<Cue*> m_pCuesToPlay; // This just happens to be the best place to keep track of them. // The current environment to play. AdaptiveEnvironment* m_pCurrentEnvironment; #pragma endregion public: #pragma region Constructors and Finalizers // Constructor. AdaptiveMusicManager(); // Destructor. ~AdaptiveMusicManager(); #pragma endregion #pragma region Methods // Registers an AudioEmitter. void AddEnvironment(AdaptiveEnvironment* envir); // Unregisters an AudioEmitter. //void RemoveEnvironment(AdaptiveEnvironment* envir); void SetCurrentEnvironment(String name); // Pauses/unpauses the engine. (Manual.) void Play(); // Stops all cues that are currently playing. void StopAll(); bool Get_IsPlaying(); DynamicList<Cue*> GetCuesToPlay(); void ClearCues(); void SetVariable(String variable, float value); #pragma endregion #pragma region Static Methods // Returns the single instance of the AudioManager. static AdaptiveMusicManager* Instantiate(); #pragma endregion #pragma region Properties #pragma endregion }; } }
#include <iostream> #include <fstream> #include <sstream> #include <string> #include "header.h" using namespace std; int main() { ifstream stream; string fileName; cout << "Please enter a file name." << endl; cin >> fileName; while(stream.fail()) { //if stream fails ask for appropriate name cout << "Unable to open file " << fileName << endl; cout << "Please enter a different file name." << endl; cin >> fileName; } stream.open(fileName.c_str()); cout << "Successfully opened file " << fileName << endl << endl; cout << "######## TOPOLOGY ########" << endl << endl; string house, neighbor, line; linkedList GOT; while(getline(stream,line)) { istringstream iss(line); iss >> house >> neighbor; //taking house and neigbor names as string w/ iss cout << "Processing " << house << ", " << neighbor << endl; if(GOT.nnExists(house,neighbor) && GOT.nnExists(neighbor,house)) cout << "Redundant information! An entry with " << house << " and " << neighbor <<" is already processed." << endl << endl; else cout << "Topology information successfully added." << endl << endl; if(!GOT.hnExists(house)) //there is no house name GOT.addHouseNode(house); if(!GOT.hnExists(neighbor)) //there is no neighbor name GOT.addHouseNode(neighbor); if(!GOT.nnExists(house,neighbor)) //there is house name but not neighbor GOT.addNeighborNode(house,neighbor); if(GOT.nnExists(house,neighbor)) //there is house name and neighbor name, it makes neigbor and house neighbors as well. GOT.addNeighborNode(neighbor,house); } cout << endl << "######## MAP ########" << endl << endl ; GOT.printAll(); //print function of map stream.close(); int action = 0; while(action != 3) { //this will make the game continue until user enters 3 cout << endl << endl << "Please select an option [1-2-3]." << endl << "1. Annexation! War for the iron throne continues..." << endl ; cout << "2. Tyrion must travel, do a path check for the famous imp." << endl << "3. Exit" << endl ; cin >> action; if(action == 1) { //if user enters 1 the game will continue with this part cout << "Please enter two houses first the annexer and the annexed. (ex: Tyrell Stark)." << endl; string attack,winner,loser; cin.ignore(); getline(cin,attack,'\n'); istringstream vs(attack); vs >> winner >> loser; //taking conquerer and conquered name as string w/ iss if(!GOT.hnExists(winner)) //if first input doesnt exist cout << winner << " does not exist!" << endl << "Update failed." << endl ; else if(!GOT.hnExists(loser)) // if second input doesnt exist cout << loser << " does not exist!" << endl << "Update failed." << endl ; else if(winner == loser) //if inputs are the same cout << "A House cannot conquer itself!" << endl << "Update failed." << endl; else if(!GOT.nnExists(winner,loser)) //if inputs are not neighbor cout << "A house can only conquer a neighboring house! " << loser << " is not a neighbor of " << winner << "." << endl << "Update failed." << endl; else if(GOT.nnExists(winner,loser)) { //if inputs are available for conquering GOT.conquerIt(winner,loser); //this function transfers the neighbors of loser to the winner GOT.deleteLoser(loser); //this function deletes the loser house GOT.neighborDeleter(winner,loser); //this function deletes loser from the other neighbors lists cout << winner << " conquered " << loser << "!" << endl; cout << "######## MAP ########" << endl; GOT.printAll(); } } else if(action == 2) { //if user enters 2 the game will continue with this part cout << "Please enter a path. (ex: Tyrell Martell Tully)" << endl; string path, prevHouse, nextHouse, next; cin.ignore(); getline(cin,path,'\n'); istringstream control(path) ; control >> prevHouse >> nextHouse; //taking house names as string to create path w/ iss bool check = true; bool test = true; if(prevHouse == nextHouse) // if house names are same cout << "You are already in " << prevHouse << endl; if(!GOT.hnExists(prevHouse)) { //if input is not propriet cout << prevHouse << " does not exist in the map." << endl; test = false; check = false; } else if(!GOT.hnExists(nextHouse)) { cout << nextHouse << " does not exist in the map." << endl; test = false; check = false; } if(GOT.nnExists(prevHouse,nextHouse) && test) //if inputs are neighbor cout << "Path found between " << prevHouse << " and " << nextHouse << endl; else if(!GOT.nnExists(prevHouse,nextHouse) && test && prevHouse != nextHouse) { //if inputs are not neighbor cout << prevHouse << " is not a neighbor of " << nextHouse << endl; check = false; } while (control >> next) { prevHouse = nextHouse; nextHouse = next; if(!GOT.hnExists(nextHouse)) { cout << nextHouse << " does not exist in the map." << endl; test = false; } else if(!GOT.hnExists(prevHouse)) { cout << prevHouse << " does not exist in the map." << endl; test = false; } if (GOT.nnExists(nextHouse,prevHouse)) cout << "Path found between " << nextHouse << " and " << prevHouse << endl; else if(!GOT.nnExists(nextHouse,prevHouse) && nextHouse != prevHouse && test) { cout << nextHouse << " is not a neighbor of " << prevHouse << endl; check = false; } } if(nextHouse == prevHouse) check = true; if(check && test) cout << "Path search succeeded." << endl; else if(!check || !test) cout << "Path search failed!" << endl; } else if(action > 3 || action < 0) // if input is not 1,2 or 3 cout << "Invalid option please select from the menu." << endl; } //if user enters 3 GOT.deleteAll(); cout << "List deleted and program ended." << endl; cin.get(); cin.ignore(); return 0; }
#ifndef OBJECT_H #define OBJECT_H #include <QOpenGLShaderProgram> #include <vector> #include <array> #include "objectmodel.h" struct Vertex { std::array<GLfloat , 3> vertex; std::array<GLfloat , 3> normal; std::array<GLfloat , 2> texCoord; }; class Object { public: Object(); void setObject(const std::vector<GLfloat>& vert ,const std::vector<GLfloat>& norms,const std::vector<GLfloat>& texCoord ); std::vector<Vertex> vertexs; }; #endif // OBJECT_H
// // Created by mattia on 25/06/19. // #ifndef GCC_INSTRUMENTATION_TEST_TEST_CLASS_H #define GCC_INSTRUMENTATION_TEST_TEST_CLASS_H #include <time.h> class falco_engine{ private: struct timespec ts; public: explicit falco_engine(long nsec); void process_sinsp_event(); ~falco_engine() = default; }; #endif //GCC_INSTRUMENTATION_TEST_TEST_CLASS_H
#ifndef IMPLISTREC2_H #define IMPLISTREC2_H /// @file ImpListRec2.h /// @brief ImpListRec2 のヘッダファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2005-2012 Yusuke Matsunaga /// All rights reserved. #include "ImpRec.h" #include "ImpVal.h" BEGIN_NAMESPACE_YM_NETWORKS ////////////////////////////////////////////////////////////////////// /// @class ImpListRec ImpListRec.h "ImpListRec.h" /// @brief 結果を imp_list の配列に格納する ImpRec ////////////////////////////////////////////////////////////////////// class ImpListRec2 : public ImpRec { public: /// @brief コンストラクタ /// @param[in] imp_list_array 含意結果を格納するリストの配列 ImpListRec2(vector<vector<ImpVal> >& imp_list_array); /// @brief デストラクタ virtual ~ImpListRec2(); public: /// @brief 含意結果を記録する仮想関数 /// @param[in] src_node 含意元のノード /// @param[in] src_val 含意元の値 /// @param[in] dst_node 含意先のノード /// @param[in[ dst_val 含意先の値 virtual void record(ImpNode* src_node, ymuint src_val, ImpNode* dst_node, ymuint dst_val); private: ////////////////////////////////////////////////////////////////////// // データメンバ ////////////////////////////////////////////////////////////////////// // 含意結果を格納するリストの配列 vector<vector<ImpVal> >& mImpListArray; }; END_NAMESPACE_YM_NETWORKS #endif // IMPLISTREC2_H
#include "GamingLayer.h" #include "ScoreLayer.h" #include "TimeLayer.h" #include "PauseLayer.h" GamingLayer::GamingLayer() { } GamingLayer::~GamingLayer() { } bool GamingLayer::init() { bool s=false; do { CC_BREAK_IF(!BasicLayer::init()); SetView(); s=true; } while (0); return s; } void GamingLayer::SetView() { auto sp0=Sprite::create("bg01.jpg"); auto sp1=Sprite::create("bg01.jpg"); sp0->setAnchorPoint(Point(0,0)); sp1->setAnchorPoint(Point(0,0)); sp0->setPosition(Point(0,0)); sp1->setPosition(Point(0,576)); this->addChild(sp0,0,10); this->addChild(sp1,0,11); //背景滚动的schedule方法 this->schedule(schedule_selector(GamingLayer::Background_scroll_logic),0.01f); //加入分数布景 auto score_layer=ScoreLayer::create(); score_layer->setAnchorPoint(Point(0,1)); score_layer->setPosition(Point(10,getwinsize().height-20)); addChild(score_layer); //加入时间布景 auto time_layer=TimeLayer::create(); time_layer->setAnchorPoint(Point(0,1)); time_layer->setPosition(Point(getwinsize().width-time_layer->getContentSize().width/4-10,getwinsize().height-20)); addChild(time_layer); //加入暂停按钮 auto pause_item=MenuItemImage::create("pause.png","pause.png",CC_CALLBACK_1(GamingLayer::Pause_down,this)); pause_item->setAnchorPoint(Point(1,0)); pause_item->setPosition(VisibleRect::rightBottom()); auto menu=Menu::create(pause_item,NULL); menu->setPosition(VisibleRect::leftBottom()); addChild(menu,1,156); //加入PauseLayer并把它设置成隐藏的 auto pPause=PauseLayer::create(); pPause->setVisible(false); this->addChild(pPause,10,99); //加入飞机 m_warriorLayer=WarriorLayer::create(); addChild(m_warriorLayer); ////加入子弹 m_heroBulletManager=HeroBulletManager::create(); addChild(m_heroBulletManager,1); //移动英雄子弹的schedule this->schedule(schedule_selector(GamingLayer::warrior_add_new_bullet),0.15f); //加入敌机 //无法显示的另外一种可能,就是位置未在屏幕内 m_enemyManager=EnemyManager::create(); this->addChild(m_enemyManager); // } void GamingLayer::Pause_down(Ref* sender) { //1、显示这个PauseLayer this->getChildByTag(99)->setVisible(true); //2、调用Director的pause函数 Director::getInstance()->pause(); //3、设定Menu的Enabled为false auto menu=(Menu*)this->getChildByTag(156); menu->setEnabled(false); //4、背景音乐的控制 if (SimpleAudioEngine::getInstance()->isBackgroundMusicPlaying()) { SimpleAudioEngine::getInstance()->stopBackgroundMusic(); } } void GamingLayer::Background_scroll_logic(float t) { auto sp0=(Sprite*)this->getChildByTag(10); auto sp1=(Sprite*)this->getChildByTag(11); sp0->setPositionY(sp0->getPositionY()-5); sp1->setPositionY(sp0->getPositionY()+576); if(sp1->getPositionY()<=0) sp0->setPositionY(0); } Scene* GamingLayer::scene() { Scene*sc=NULL; do { sc=Scene::create(); CC_BREAK_IF(!sc); auto layer=GamingLayer::create(); CC_BREAK_IF(!layer); sc->addChild(layer); } while (0); return sc; } void GamingLayer::warrior_add_new_bullet(float t) { m_heroBulletManager->addNewBullet(m_warriorLayer->getWarriorPosition(),m_warriorLayer->getWarriorSize()); }
#ifndef GAME_HPP #define GAME_HPP #include <SFML/Graphics.hpp> #include "Constants.hpp" #include "World.hpp" /** * Contains all in game components needed to * run the game. */ class Game { public: Game(); void run(); void handleEvents(); private: sf::RenderWindow m_window; sf::Event m_event; sf::Clock m_clock; sf::Time m_timeSinceUpdate; World m_world; }; #endif //GAME_HPP
#include "fuzzy.h" Fuzzy::Fuzzy() : MD_WIN_WIDTH(100), MD_WIN_HEIGHT(100), MD_THRESHOLD_PERCENT(10), MD_HISTORY_SIZE(30), MD_OFFSET(382), //FIXME base on config limits TAG_HISTORY_SIZE(6), TAG_LENGTH(12), OLD_TAG(40), VERY_OLD_TAG(80), VALID_TAG_REPEATS(3), TAG_ACTIVE_FOR(10) { assert(TAG_HISTORY_SIZE >= VALID_TAG_REPEATS); debug = false; d_videodebug = false; md_lastframe = NULL; md_frame_deltas = new int[MD_HISTORY_SIZE]; for( int i = 0; i < MD_HISTORY_SIZE; i++) md_frame_deltas[i] = 0; tag_backstore = new int[TAG_LENGTH* TAG_HISTORY_SIZE]; for( int i = 0; i < TAG_LENGTH* TAG_HISTORY_SIZE; i++) tag_backstore[i] = -1; md_win_x1 = 0; md_win_x2 = 0; md_win_y1 = 0; md_win_y2 = 0; md_index = 0; tag_index = 0; valid_for = -1; //skip first valid md_pixel_threshold = 0; real_frame_count = 0; used_frame_count = -1; } Fuzzy::~Fuzzy() { if(md_lastframe!=NULL) delete [] md_lastframe; if(md_frame_deltas!=NULL) delete [] md_frame_deltas; if(tag_backstore!=NULL) delete [] tag_backstore; } void Fuzzy::setDebug(bool _debug) { debug = _debug; } bool Fuzzy::selectFrame(int skip_frames) { // if(valid_for >= 1) valid_for++; if(real_frame_count++ % skip_frames == 0) { used_frame_count++; return true; } return false; } /* bool Fuzzy::trackFrame() //DEL { if(valid_for>=1) return true; return false; } void Fuzzy::countFrame() //DEL { frame_count++; //only if last one was a valid frame if(valid_for >= 1) valid_for++; } */ bool Fuzzy::motionDetect(unsigned char *frame_data, int frame_width, int frame_height) { checkFrameStores(frame_width, frame_height); int d = computeDelta(frame_data, frame_width, frame_height); if( d > md_pixel_threshold ){ //exceeds max threshold frame to frame if(debug) printf( "Fuzzy::motionDetect [%ld] d=%d > t=%d Exit\n", used_frame_count, d, md_pixel_threshold ); return true; }else{ //or exceeds average delta of the last few frames int sum = 0; for(int i=0; i<MD_HISTORY_SIZE; i++) sum+=md_frame_deltas[i]; if(d > 2*(sum/MD_HISTORY_SIZE) ) { if(debug) printf("Fuzzy::motionDetect [%ld] d=%d a=%d Exit\n", used_frame_count, d, sum/MD_HISTORY_SIZE); return true; } } return false; } void Fuzzy::checkFrameStores(int frame_width, int frame_height) { if( frame_width == last_frame_width && frame_height == last_frame_height ) return; //relocate the md sub window calculateMDWindow(frame_width, frame_height); //allocate first time or reallocate new size frame if( md_lastframe == NULL ){ /*md_lastframe = new bool[(md_win_x2-md_win_x1) * (md_win_y2-md_win_y1)]; for(int i=0; i< (md_win_x2-md_win_x1) * (md_win_y2-md_win_y1) ; i++) md_lastframe[i] = false;*/ //FIXME use smaller storage as above and change indexing in computeDelta() md_lastframe = new bool[frame_width*frame_height]; for(int i=0; i< frame_width*frame_height; i++) md_lastframe[i] = false; }else{ delete [] md_lastframe; md_lastframe = NULL; } md_pixel_threshold = ( (md_win_x2-md_win_x1) * (md_win_y2-md_win_y1) ) * MD_THRESHOLD_PERCENT / 100; last_frame_width = frame_width; last_frame_height = frame_height; } int Fuzzy::computeDelta(unsigned char *frame_data, int frame_width, int frame_height) { int i = 0; RGBBYTE *rgb; bool pixel = false; int delta = 0; for(int y = md_win_y1; y < md_win_y2; y++){ for(int x = md_win_x1; x < md_win_x2; x++){ i = ((frame_height-y) *frame_width) + x; rgb = (RGBBYTE*) frame_data + i; pixel = (rgb->R + rgb->G + rgb->B) > MD_OFFSET ? true : false ; if(used_frame_count) if(md_lastframe[i] != pixel) delta++; //not first frame md_lastframe[i] = pixel; //FIXME change indexing if(d_videodebug) { if(pixel){ rgb->R = 255; rgb->G = 255; rgb->B = 255; }else{ rgb->R = 0; rgb->G = 0; rgb->B = 0; } } } } md_frame_deltas[used_frame_count % MD_HISTORY_SIZE] = delta; //not first frame return delta; } bool Fuzzy::tagIsActive() { if(valid_for >= 1 && valid_for <= TAG_ACTIVE_FOR) return true; return false; } void Fuzzy::calculateMDWindow(int width, int height) { //define centered subwindow MD_WIN_WIDTH * MD_WIN_HEIGHT //adjusts subwindow size if frame is smaller than subwindow if( width > MD_WIN_WIDTH ) { md_win_x1 = (width/2) - (MD_WIN_WIDTH/2); md_win_x2 = (width/2) + (MD_WIN_WIDTH/2); }else{ md_win_x1 = 0; md_win_x2 = width; } if( height > MD_WIN_HEIGHT ) { md_win_y1 = (height/2) - (MD_WIN_HEIGHT/2); md_win_y2 = (height/2) + (MD_WIN_HEIGHT/2); }else{ md_win_y1 = 0; md_win_y2 = height; } } bool Fuzzy::tagIsBrandNew() { if(valid_for == 1) return true; return false; } bool Fuzzy::tagIsNew() { if(valid_for < OLD_TAG) return true; return false; } bool Fuzzy::tagIsOld() { if(valid_for >= OLD_TAG) return true; return false; } bool Fuzzy::tagIsVeryOld() { if(valid_for > VERY_OLD_TAG) return true; return false; } bool Fuzzy::validateTag(int *tag) { storeTag(tag); bool result = allValidTag(tag); if(result) { printf("checking tag valid_for = %d\n", valid_for ); for(int i=0; i<VALID_TAG_REPEATS; i++){ //TODO now storing skipped tags, optimize with separate counter if(!equalTag(tag, i)) result = false; } } if(result) valid_for++; else valid_for=0; //else if(valid_for >= 0) valid_for=0; d_printTagStore(); return result; } void Fuzzy::storeTag(int *tag) { int index = (used_frame_count % TAG_HISTORY_SIZE)*TAG_LENGTH; for(int i = 0; i < TAG_LENGTH; i++) tag_backstore[index+i] = tag[i]; } bool Fuzzy::equalTag(int *tag, int backindex) { /*assert(tagindex <= TAG_HISTORY_SIZE); int storeindex = tagindex-- > 0 ? tagindex : TAG_HISTORY_SIZE + tagindex + 1; int index = storeindex * TAG_LENGTH; */ assert(backindex <= TAG_HISTORY_SIZE); int index = ( (used_frame_count-backindex) % TAG_HISTORY_SIZE)*TAG_LENGTH; printf("%d -> %d (%d) : ", backindex, index , used_frame_count); for(int i = 0; i < TAG_LENGTH; i++) { printf("%d=%d ", tag_backstore[index+i], tag[i]); if(tag_backstore[index+i] != tag[i]) { printf(" != \n"); d_printTagStore(); return false; } } printf(" == \n"); return true; } bool Fuzzy::equalTag(int backindex1, int backindex2) { assert(backindex1 <= TAG_HISTORY_SIZE); assert(backindex2 <= TAG_HISTORY_SIZE); int index1 = (used_frame_count-backindex1 % TAG_HISTORY_SIZE)*TAG_LENGTH; int index2 = (used_frame_count-backindex2 % TAG_HISTORY_SIZE)*TAG_LENGTH; for(int i = 0; i < TAG_LENGTH; i++) { if(tag_backstore[index1+i] != tag_backstore[index2+i] ) return false; } return true; } bool Fuzzy::allValidTag(int *tag) //Truth Degree 1.0 (12) { int valid = 0; for(int i=0; i<TAG_LENGTH; i++) { if(tag[i] >= 0) valid++; } if(valid == TAG_LENGTH) return true; return false; } bool Fuzzy::closeToValidTag(int *tag)//Truth Degree 0.9 (11) { int valid = 0; for(int i=0; i<TAG_LENGTH; i++) { if(tag[i] >= 0) valid++; } if(valid == TAG_LENGTH-1) return true; return false; } bool Fuzzy::barelyValidTag(int *tag) //Truth Degree 0.7-0.8 (6-10) { int valid = 0; for(int i=0; i<TAG_LENGTH; i++) { if(tag[i] >= 0) valid++; } if(valid > (TAG_LENGTH/2)+1 || valid < TAG_LENGTH-1) return true; return false; } bool Fuzzy::inValidTag(int *tag) //Truth Degree 0.1-0.6 (1-5) { int valid = 0; for(int i=0; i<TAG_LENGTH; i++) { if(tag[i] >= 0) valid++; } if(valid > 0 && valid <= (TAG_LENGTH/2)) return true; return false; } bool Fuzzy::allInValidTag(int *tag) //Truth Degree 0.0 (0) { int valid = 0; for(int i=0; i<TAG_LENGTH; i++) { if(tag[i] >= 0) valid++; } if(valid == 0) return true; return false; } //fuzzy sizing of the video source to ideal window width range //with priority given to squares of 2 sizing if possible //result sizes will be rounded to next multiple of two //very large sized video sources will be just scaled to fit void Fuzzy::sizeFrame(int *resx, int* resy, int wx, int wy, int vx, int vy, int mode) { if(debug) printf("v %d,%d -> w %d,%d ", vx, vy, wx, wy); int w = vx > vy ? wx : wy; int v = vx > vy ? vx : vy; if( v <= w ) { *resx = wx; *resy = wy; if(debug) printf(" = %d,%d (mode=%d)\n", *resx, *resy, mode); return; } if(mode = 0){ if(v/2 >= w) { *resx = vx/2; *resy = vy/2; if(debug) printf(" = %d,%d (mode=%d)\n", *resx, *resy, mode); return; } } int f = (int)((float)v/(float)w); if(f > 8) { //too big if(f%2) f++; }else{ f = 16; while(v/f < w) f = f/2; } // f2 larger bigger than w size of v // f1 smaller smaller than w size of v // f2 is preffered, // unless f1 is closer to w than half of f2 closeness to w int d1 = vx > vy ? vx/f : vy/f ; int d2 = vx > vy ? vx/(f*2) : vy/(f*2) ; f = abs(w-d2) < (abs(w-d1)/2) ? f*2 : f; *resx = vx/f; *resy = vy/f; if(*resx%2) *resx = (*resx)+1; if(*resy%2) *resy = (*resy)+1; if(debug) printf(" = %d,%d (mode=%d)\n", *resx, *resy, mode); } void Fuzzy::d_printTagStore() { //if(!debug) return; int top = (used_frame_count % TAG_HISTORY_SIZE)*TAG_LENGTH; int index = 0; printf("[------- %d -------\n", used_frame_count); for(int i=0; i< TAG_HISTORY_SIZE; i++){ printf("%d ", i); for(int j = 0; j< TAG_LENGTH; j++) printf("%d", tag_backstore[index++]); if(i*TAG_LENGTH == top) printf(" *"); printf("\n"); } printf("------- %d -------]\n", used_frame_count); }
//************************************************************************** //** //** See jlquake.txt for copyright info. //** //** This program is free software; you can redistribute it and/or //** modify it under the terms of the GNU General Public License //** as published by the Free Software Foundation; either version 3 //** of the License, or (at your option) any later version. //** //** This program is distributed in the hope that it will be useful, //** but WITHOUT ANY WARRANTY; without even the implied warranty of //** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //** included (gnu.txt) GNU General Public License for more details. //** //************************************************************************** #include "commands.h" #include "main.h" #include "backend.h" #include "cvars.h" #include "state.h" #include "driver.h" #include "scene.h" #include "../../common/Common.h" #include "../../common/common_defs.h" #include "../../common/strings.h" void R_InitCommandBuffers() { glConfig.smpActive = false; if ( ( GGameType & GAME_Tech3 ) && r_smp->integer ) { common->Printf( "Trying SMP acceleration...\n" ); if ( GLimp_SpawnRenderThread( RB_RenderThread ) ) { common->Printf( "...succeeded.\n" ); glConfig.smpActive = true; } else { common->Printf( "...failed.\n" ); } } } void R_ShutdownCommandBuffers() { // kill the rendering thread if ( glConfig.smpActive ) { GLimp_WakeRenderer( NULL ); glConfig.smpActive = false; } } static void R_PerformanceCounters() { if ( !r_speeds->integer ) { // clear the counters even if we aren't printing Com_Memset( &tr.pc, 0, sizeof ( tr.pc ) ); Com_Memset( &backEnd.pc, 0, sizeof ( backEnd.pc ) ); return; } if ( r_speeds->integer == 1 ) { common->Printf( "%i/%i shaders/surfs %i leafs %i verts %i/%i tris %.2f mtex %.2f dc\n", backEnd.pc.c_shaders, backEnd.pc.c_surfaces, tr.pc.c_leafs, backEnd.pc.c_vertexes, backEnd.pc.c_indexes / 3, backEnd.pc.c_totalIndexes / 3, R_SumOfUsedImages() / 1000000.0f, backEnd.pc.c_overDraw / ( float )( glConfig.vidWidth * glConfig.vidHeight ) ); } else if ( r_speeds->integer == 2 ) { common->Printf( "(patch) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", tr.pc.c_sphere_cull_patch_in, tr.pc.c_sphere_cull_patch_clip, tr.pc.c_sphere_cull_patch_out, tr.pc.c_box_cull_patch_in, tr.pc.c_box_cull_patch_clip, tr.pc.c_box_cull_patch_out ); common->Printf( "(md3) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", tr.pc.c_sphere_cull_md3_in, tr.pc.c_sphere_cull_md3_clip, tr.pc.c_sphere_cull_md3_out, tr.pc.c_box_cull_md3_in, tr.pc.c_box_cull_md3_clip, tr.pc.c_box_cull_md3_out ); common->Printf( "(gen) %i sin %i sout %i pin %i pout\n", tr.pc.c_sphere_cull_in, tr.pc.c_sphere_cull_out, tr.pc.c_plane_cull_in, tr.pc.c_plane_cull_out ); } else if ( r_speeds->integer == 3 ) { common->Printf( "viewcluster: %i\n", tr.viewCluster ); } else if ( r_speeds->integer == 4 ) { if ( backEnd.pc.c_dlightVertexes ) { common->Printf( "dlight srf:%i culled:%i verts:%i tris:%i\n", tr.pc.c_dlightSurfaces, tr.pc.c_dlightSurfacesCulled, backEnd.pc.c_dlightVertexes, backEnd.pc.c_dlightIndexes / 3 ); } } else if ( r_speeds->integer == 5 ) { common->Printf( "zFar: %.0f\n", tr.viewParms.zFar ); } else if ( r_speeds->integer == 6 ) { common->Printf( "flare adds:%i tests:%i renders:%i\n", backEnd.pc.c_flareAdds, backEnd.pc.c_flareTests, backEnd.pc.c_flareRenders ); } else if ( r_speeds->integer == 7 ) { common->Printf( "decal projectors: %d test surfs: %d clip surfs: %d decal surfs: %d created: %d\n", tr.pc.c_decalProjectors, tr.pc.c_decalTestSurfaces, tr.pc.c_decalClipSurfaces, tr.pc.c_decalSurfaces, tr.pc.c_decalSurfacesCreated ); } Com_Memset( &tr.pc, 0, sizeof ( tr.pc ) ); Com_Memset( &backEnd.pc, 0, sizeof ( backEnd.pc ) ); } void R_IssueRenderCommands( bool runPerformanceCounters ) { renderCommandList_t* cmdList = &backEndData[ tr.smpFrame ]->commands; assert( cmdList ); // bk001205 // add an end-of-list command *( int* )( cmdList->cmds + cmdList->used ) = RC_END_OF_LIST; // clear it out, in case this is a sync and not a buffer flip cmdList->used = 0; if ( glConfig.smpActive ) { // if the render thread is not idle, wait for it if ( renderThreadActive ) { if ( r_showSmp->integer ) { common->Printf( "R" ); } } else { if ( r_showSmp->integer ) { common->Printf( "." ); } } // sleep until the renderer has completed GLimp_FrontEndSleep(); } // at this point, the back end thread is idle, so it is ok // to look at it's performance counters if ( runPerformanceCounters ) { R_PerformanceCounters(); } // actually start the commands going if ( !r_skipBackEnd->integer ) { // let it start on the new batch if ( !glConfig.smpActive ) { RB_ExecuteRenderCommands( cmdList->cmds ); } else { GLimp_WakeRenderer( cmdList ); } } } // Issue any pending commands and wait for them to complete. After exiting, // the render thread will have completed its work and will remain idle and // the main thread is free to issue OpenGL calls until R_IssueRenderCommands // is called. void R_SyncRenderThread() { if ( !tr.registered ) { return; } R_IssueRenderCommands( false ); if ( !glConfig.smpActive ) { return; } GLimp_FrontEndSleep(); } // make sure there is enough command space, waiting on the render thread if needed. void* R_GetCommandBuffer( int bytes ) { renderCommandList_t* cmdList = &backEndData[ tr.smpFrame ]->commands; // always leave room for the swap buffers and end of list commands if ( cmdList->used + bytes + sizeof ( swapBuffersCommand_t ) + 4 > MAX_RENDER_COMMANDS ) { if ( bytes > MAX_RENDER_COMMANDS - ( int )sizeof ( swapBuffersCommand_t ) - 4 ) { common->FatalError( "R_GetCommandBuffer: bad size %i", bytes ); } // if we run out of room, just start dropping commands return NULL; } cmdList->used += bytes; return cmdList->cmds + cmdList->used - bytes; } void R_AddDrawSurfCmd( drawSurf_t* drawSurfs, int numDrawSurfs ) { drawSurfsCommand_t* cmd = ( drawSurfsCommand_t* )R_GetCommandBuffer( sizeof ( *cmd ) ); if ( !cmd ) { return; } cmd->commandId = RC_DRAW_SURFS; cmd->drawSurfs = drawSurfs; cmd->numDrawSurfs = numDrawSurfs; cmd->refdef = tr.refdef; cmd->viewParms = tr.viewParms; } // Passing NULL will set the color to white void R_SetColor( const float* rgba ) { if ( !tr.registered ) { return; } setColorCommand_t* cmd = ( setColorCommand_t* )R_GetCommandBuffer( sizeof ( *cmd ) ); if ( !cmd ) { return; } cmd->commandId = RC_SET_COLOR; if ( !rgba ) { static float colorWhite[ 4 ] = { 1, 1, 1, 1 }; rgba = colorWhite; } cmd->color[ 0 ] = rgba[ 0 ]; cmd->color[ 1 ] = rgba[ 1 ]; cmd->color[ 2 ] = rgba[ 2 ]; cmd->color[ 3 ] = rgba[ 3 ]; } void R_StretchPic( float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader ) { if ( !tr.registered ) { return; } stretchPicCommand_t* cmd = ( stretchPicCommand_t* )R_GetCommandBuffer( sizeof ( *cmd ) ); if ( !cmd ) { return; } cmd->commandId = RC_STRETCH_PIC; cmd->shader = R_GetShaderByHandle( hShader ); cmd->x = x; cmd->y = y; cmd->w = w; cmd->h = h; cmd->s1 = s1; cmd->t1 = t1; cmd->s2 = s2; cmd->t2 = t2; } void R_StretchPicGradient( float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader, const float* gradientColor, int gradientType ) { if ( !tr.registered ) { return; } stretchPicCommand_t* cmd = ( stretchPicCommand_t* )R_GetCommandBuffer( sizeof ( *cmd ) ); if ( !cmd ) { return; } cmd->commandId = RC_STRETCH_PIC_GRADIENT; cmd->shader = R_GetShaderByHandle( hShader ); cmd->x = x; cmd->y = y; cmd->w = w; cmd->h = h; cmd->s1 = s1; cmd->t1 = t1; cmd->s2 = s2; cmd->t2 = t2; if ( !gradientColor ) { static float colorWhite[ 4 ] = { 1, 1, 1, 1 }; gradientColor = colorWhite; } cmd->gradientColor[ 0 ] = gradientColor[ 0 ] * 255; cmd->gradientColor[ 1 ] = gradientColor[ 1 ] * 255; cmd->gradientColor[ 2 ] = gradientColor[ 2 ] * 255; cmd->gradientColor[ 3 ] = gradientColor[ 3 ] * 255; cmd->gradientType = gradientType; } void R_RotatedPic( float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader, float angle ) { if ( !tr.registered ) { return; } stretchPicCommand_t* cmd = ( stretchPicCommand_t* )R_GetCommandBuffer( sizeof ( *cmd ) ); if ( !cmd ) { return; } cmd->commandId = RC_ROTATED_PIC; cmd->shader = R_GetShaderByHandle( hShader ); cmd->x = x; cmd->y = y; cmd->w = w; cmd->h = h; // fixup cmd->w /= 2; cmd->h /= 2; cmd->x += cmd->w; cmd->y += cmd->h; cmd->w = sqrt( ( cmd->w * cmd->w ) + ( cmd->h * cmd->h ) ); cmd->h = cmd->w; cmd->angle = angle; cmd->s1 = s1; cmd->t1 = t1; cmd->s2 = s2; cmd->t2 = t2; } void R_2DPolyies( polyVert_t* verts, int numverts, qhandle_t hShader ) { if ( !tr.registered ) { return; } if ( r_numpolyverts + numverts > max_polyverts ) { return; } poly2dCommand_t* cmd = ( poly2dCommand_t* )R_GetCommandBuffer( sizeof ( *cmd ) ); if ( !cmd ) { return; } cmd->commandId = RC_2DPOLYS; cmd->verts = &backEndData[ tr.smpFrame ]->polyVerts[ r_numpolyverts ]; cmd->numverts = numverts; memcpy( cmd->verts, verts, sizeof ( polyVert_t ) * numverts ); cmd->shader = R_GetShaderByHandle( hShader ); r_numpolyverts += numverts; } // If running in stereo, RE_BeginFrame will be called twice // for each R_EndFrame void R_BeginFrame( stereoFrame_t stereoFrame ) { if ( !tr.registered ) { return; } glState.finishCalled = false; tr.frameCount++; tr.frameSceneNum = 0; // // do overdraw measurement // if ( r_measureOverdraw->integer ) { if ( glConfig.stencilBits < 4 ) { common->Printf( "Warning: not enough stencil bits to measure overdraw: %d\n", glConfig.stencilBits ); Cvar_Set( "r_measureOverdraw", "0" ); r_measureOverdraw->modified = false; } else if ( r_shadows->integer == 2 ) { common->Printf( "Warning: stencil shadows and overdraw measurement are mutually exclusive\n" ); Cvar_Set( "r_measureOverdraw", "0" ); r_measureOverdraw->modified = false; } else { R_SyncRenderThread(); qglEnable( GL_STENCIL_TEST ); qglStencilMask( ~0U ); qglClearStencil( 0U ); qglStencilFunc( GL_ALWAYS, 0U, ~0U ); qglStencilOp( GL_KEEP, GL_INCR, GL_INCR ); } r_measureOverdraw->modified = false; } else { // this is only reached if it was on and is now off if ( r_measureOverdraw->modified ) { R_SyncRenderThread(); qglDisable( GL_STENCIL_TEST ); } r_measureOverdraw->modified = false; } // // texturemode stuff // if ( r_textureMode->modified ) { R_SyncRenderThread(); GL_TextureMode( r_textureMode->string ); r_textureMode->modified = false; } // // anisotropic filtering stuff // if ( r_textureAnisotropy->modified ) { R_SyncRenderThread(); GL_TextureAnisotropy( r_textureAnisotropy->value ); r_textureAnisotropy->modified = false; } // // ATI stuff // // TRUFORM if ( qglPNTrianglesiATI ) { // tess if ( r_ati_truform_tess->modified ) { r_ati_truform_tess->modified = false; // cap if necessary if ( r_ati_truform_tess->value > glConfig.ATIMaxTruformTess ) { Cvar_Set( "r_ati_truform_tess", va( "%d", glConfig.ATIMaxTruformTess ) ); } qglPNTrianglesiATI( GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI, r_ati_truform_tess->value ); } // point mode if ( r_ati_truform_pointmode->modified ) { r_ati_truform_pointmode->modified = false; // GR - shorten the mode name if ( !String::ICmp( r_ati_truform_pointmode->string, "LINEAR" ) ) { glConfig.ATIPointMode = ( int )GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI; // GR - fix point mode change } else if ( !String::ICmp( r_ati_truform_pointmode->string, "CUBIC" ) ) { glConfig.ATIPointMode = ( int )GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI; } else { // bogus value, set to valid glConfig.ATIPointMode = ( int )GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI; Cvar_Set( "r_ati_truform_pointmode", "LINEAR" ); } qglPNTrianglesiATI( GL_PN_TRIANGLES_POINT_MODE_ATI, glConfig.ATIPointMode ); } // normal mode if ( r_ati_truform_normalmode->modified ) { r_ati_truform_normalmode->modified = false; // GR - shorten the mode name if ( !String::ICmp( r_ati_truform_normalmode->string, "LINEAR" ) ) { glConfig.ATINormalMode = ( int )GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI; // GR - fix normal mode change } else if ( !String::ICmp( r_ati_truform_normalmode->string, "QUADRATIC" ) ) { glConfig.ATINormalMode = ( int )GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI; } else { // bogus value, set to valid glConfig.ATINormalMode = ( int )GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI; Cvar_Set( "r_ati_truform_normalmode", "LINEAR" ); } qglPNTrianglesiATI( GL_PN_TRIANGLES_NORMAL_MODE_ATI, glConfig.ATINormalMode ); } } // // NVidia stuff // // fog control if ( glConfig.NVFogAvailable && r_nv_fogdist_mode->modified ) { r_nv_fogdist_mode->modified = false; if ( !String::ICmp( r_nv_fogdist_mode->string, "GL_EYE_PLANE_ABSOLUTE_NV" ) ) { glConfig.NVFogMode = ( int )GL_EYE_PLANE_ABSOLUTE_NV; } else if ( !String::ICmp( r_nv_fogdist_mode->string, "GL_EYE_PLANE" ) ) { glConfig.NVFogMode = ( int )GL_EYE_PLANE; } else if ( !String::ICmp( r_nv_fogdist_mode->string, "GL_EYE_RADIAL_NV" ) ) { glConfig.NVFogMode = ( int )GL_EYE_RADIAL_NV; } else { // in case this was really 'else', store a valid value for next time glConfig.NVFogMode = ( int )GL_EYE_RADIAL_NV; Cvar_Set( "r_nv_fogdist_mode", "GL_EYE_RADIAL_NV" ); } } // // gamma stuff // if ( r_gamma->modified ) { r_gamma->modified = false; R_SyncRenderThread(); R_SetColorMappings(); } // check for errors if ( !r_ignoreGLErrors->integer ) { R_SyncRenderThread(); int err = qglGetError(); if ( err != GL_NO_ERROR ) { common->FatalError( "RE_BeginFrame() - glGetError() failed (0x%x)!\n", err ); } } // // draw buffer stuff // drawBufferCommand_t* cmd = ( drawBufferCommand_t* )R_GetCommandBuffer( sizeof ( *cmd ) ); if ( !cmd ) { return; } cmd->commandId = RC_DRAW_BUFFER; if ( glConfig.stereoEnabled ) { if ( stereoFrame == STEREO_LEFT ) { cmd->buffer = ( int )GL_BACK_LEFT; } else if ( stereoFrame == STEREO_RIGHT ) { cmd->buffer = ( int )GL_BACK_RIGHT; } else { common->FatalError( "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame ); } } else { if ( stereoFrame != STEREO_CENTER ) { common->FatalError( "R_BeginFrame: Stereo is disabled, but stereoFrame was %i", stereoFrame ); } if ( !String::ICmp( r_drawBuffer->string, "GL_FRONT" ) ) { cmd->buffer = ( int )GL_FRONT; } else { cmd->buffer = ( int )GL_BACK; } } } // Returns the number of msec spent in the back end void R_EndFrame( int* frontEndMsec, int* backEndMsec ) { if ( !tr.registered ) { return; } if ( GGameType & GAME_ET ) { // Needs to use reserved space, so no R_GetCommandBuffer. renderCommandList_t* cmdList = &backEndData[ tr.smpFrame ]->commands; assert( cmdList ); // add swap-buffers command *( int* )( cmdList->cmds + cmdList->used ) = RC_SWAP_BUFFERS; cmdList->used += sizeof ( swapBuffersCommand_t ); } else { swapBuffersCommand_t* cmd = ( swapBuffersCommand_t* )R_GetCommandBuffer( sizeof ( *cmd ) ); if ( !cmd ) { return; } cmd->commandId = RC_SWAP_BUFFERS; } R_IssueRenderCommands( true ); // use the other buffers next frame, because another CPU // may still be rendering into the current ones R_ToggleSmpFrame(); if ( frontEndMsec ) { *frontEndMsec = tr.frontEndMsec; } tr.frontEndMsec = 0; if ( backEndMsec ) { *backEndMsec = backEnd.pc.msec; } backEnd.pc.msec = 0; } void R_RenderToTexture( qhandle_t textureid, int x, int y, int w, int h ) { if ( !tr.registered ) { return; } if ( textureid > tr.numImages || textureid < 0 ) { common->Printf( "Warning: trap_R_RenderToTexture textureid %d out of range.\n", textureid ); return; } renderToTextureCommand_t* cmd = ( renderToTextureCommand_t* )R_GetCommandBuffer( sizeof ( *cmd ) ); if ( !cmd ) { return; } cmd->commandId = RC_RENDERTOTEXTURE; cmd->image = tr.images[ textureid ]; cmd->x = x; cmd->y = y; cmd->w = w; cmd->h = h; } void R_Finish() { if ( !tr.registered ) { return; } common->Printf( "R_Finish\n" ); renderFinishCommand_t* cmd = ( renderFinishCommand_t* )R_GetCommandBuffer( sizeof ( *cmd ) ); if ( !cmd ) { return; } cmd->commandId = RC_FINISH; }
#include "frame.h" // Initialize a superwindow frame::frame(int nr_rows, int nr_cols, int row_0, int col_0) { _has_super = FALSE; _super = NULL; _w = newwin(nr_rows, nr_cols, row_0, col_0); _height = nr_rows; _width = nr_cols; _row = row_0; _col = col_0; } // Initialize a subwindow with a parent frame::frame(frame &parent, int nr_rows, int nr_cols, int row_0, int col_0) { _has_super = TRUE; _super = parent.win(); _w = derwin(parent.win(), nr_rows, nr_cols, row_0, col_0); _height = nr_rows; _width = nr_cols; _row = row_0; _col = col_0; } frame::~frame() { delwin(_w); } // Place an actor in a window void frame::add(actor &x) { mvwaddch(_w, x.row(), x.col(), x.symbol()); } // Define the "erase" character, to clean up the path of actors void frame::erase(actor &x) { mvwaddch(_w, x.row(), x.col(), '.'); } // Add an actor at a specific position to the window void frame::add(actor &x, int row_0, int col_0) { if ((row_0 >= 0 && row_0 < _height) && (col_0 >= 0 && col_0 < _width)) { erase(x); mvwaddch(_w, row_0, col_0, x.symbol()); x.position(row_0, col_0); } } // Center the viewport around an actor void frame::center(actor &x) { if (_has_super) { int row = _row, col = _col, hh, ww; int _r = x.row() - _height/2; int _c = x.col() - _width/2; getmaxyx(_super, hh, ww); if (_c + _width >= ww) { int delta = ww - (_c + _width); col = _c + delta; } else col = _c; if (_r + _height >= hh) { int delta = hh - (_r + _height); row = _r + delta; } else row = _r; if (_r < 0) row = 0; if (_c < 0) col = 0; move(row, col); } } // Refresh the window void frame::refresh() { if(_has_super) touchwin(_super); wrefresh(_w); } // Move a window to a new position (row, col) void frame::move(int row, int col) { if (_super) { mvderwin(_w, row, col); _row = row; _col = col; refresh(); } } // Get the window WINDOW* frame::win() { return _w; } // Get the parent window WINDOW* frame::super() { return _super; } // Return true if this window is a subwindow bool frame::has_super() { return _has_super; } // Get the dimensions of the window int frame::height() { return _height; } int frame::width() { return _width; } // Get the position of the window int frame::row() { return _row; } int frame::col() { return _col; } // Fill a map with "0" and "#" XXX // Simple terrain for debugging purposes void frame::fill_map() { // Fill the inner region with "." for (int y = 0; y < _height; ++y) { for (int x = 0; x < _width; ++x) mvwaddch(_w, y, x, '0'); } // Fill the borders with "#" for (int y = 0; y < _height; ++y) { mvwaddch(_w, y, 0, '#'); mvwaddch(_w, y, _width - 1, '#'); } for (int x = 0; x < _width; ++x) { mvwaddch(_w, 0, x, '#'); mvwaddch(_w, _height - 1, x, '#'); } } void frame::print(std::string message, int row, int col) { std::string str = message; const char * msg = str.c_str(); mvwaddnstr(_w, row, col, msg, -1); }
#pragma once #include <SFML/Graphics.hpp> #include "MASimQt.h" #include "qwidget.h" #include "QTimer" class QMASim : public QWidget, public MASimQt { public : QMASim(QWidget* Parent, const QPoint& Position, const QSize& Size, unsigned int FrameTime = 0); virtual ~QMASim(); private : virtual void OnInit(); virtual void OnUpdate(); virtual QPaintEngine* paintEngine() const; virtual void showEvent(QShowEvent*); virtual void paintEvent(QPaintEvent*); QTimer myTimer; bool myInitialized; sf::Vector2u size; };