text
stringlengths
8
6.88M
#ifndef TP_PPROJECT_GUESTOPTIONS_H #define TP_PPROJECT_GUESTOPTIONS_H #include <iostream> #include <memory> #include "BaseUserOptions.h" class GuestOptions : public BaseUserOptions { public: ~GuestOptions() override = default; // Send message in select chat void sendMessage(const Message& message, int globalId, const std::shared_ptr<BaseCallback> callback, std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override; // Update select chat void chatUpdate(const ChatUpdates& chatUpdates, int globalId, const std::shared_ptr<BaseCallback> callback, std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override; // Get list of chats void getListChats(const ListChats& listChats, int globalId, const std::shared_ptr<BaseCallback> callback, std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override; // Get select chat room void getChatRoom(const ChatRoom& chatRoom, int globalId, const std::shared_ptr<BaseCallback> callback, std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override; // Get messages in select chat void getChatMessages(const ChatUpdates& chatUpdates, int globalId, const std::shared_ptr<BaseCallback> callback, std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override; // Get last message in chat void getLastMessage(const Message& message, int globalId, const std::shared_ptr<BaseCallback> callback, std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override; // Get user void getUser(const UserPreview& user, int globalId, const std::shared_ptr<BaseCallback> callback, std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override; // Set chat observer void setChatObserver(int chatId, const std::shared_ptr<BaseCallback> callback, std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override; // Get log void getLog(const LogUpdates& logUpdates, int globalId, const std::shared_ptr<BaseCallback> callback, std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override; // Send chat command void sendChatCommand(const Message& message, int globalId, std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override; // Registration new user void registration(const UserInfo& authInfo, int globalId, const std::shared_ptr<BaseCallback> callback, std::shared_ptr<BaseClient> client, std::shared_ptr<CallbacksHolder> callbackHolder) override; }; #endif
#ifndef MARKS_HPP_INCLUDED #define MARKS_HPP_INCLUDED #include <regex> namespace bbplus { struct mark { mark(std::string n, std::string i, std::string r) { name = n; input_regex = std::regex(i, std::regex::icase); replace_pattern = r; } std::string name; std::regex input_regex; std::string replace_pattern; }; const int_fast8_t MARKS_NB = 4; const mark MARKS[MARKS_NB] = { mark( "bold", "\\[b\\](.*?)\\[\\/b\\]", "<strong class=\"bb bb-bold\">$1</strong>" ), mark( "italic", "\\[i\\](.*?)\\[\\/i\\]", "<em class=\"bb bb-italic\">$1</em>" ), mark( "link", "\\[url\\]([^\\s+|\"]*?)\\[\\/url\\]", "<a href=\"$1\" class=\"bb bb-link\">$1</a>" ), mark( "labelled_link", "\\[url=\\\"([^\\s+|\"]*?)\\\"\\](.*?)\\[\\/url\\]", "<a href=\"$1\" class=\"bb bb-labelled-link\">$2</a>" ) }; } #endif
/* * File: MRAC.cpp * Author: Corrado Pezzato, TU Delft, DCSC * * Created on April 14th, 2019 * * Class to perform active inference control of the 7DOF Franka Emika Panda robot. * Definition of the methods contained in MRAC.h * */ #include "MRAC.h" // Constructor which takes as argument the publishers and initialises the private ones in the class MRAC::MRAC(){ // Initialize the variables for thr MRAC MRAC::initVariables(); } MRAC::~MRAC(){} void MRAC::initVariables(){ // Initialize publishers on the topics /panda_joint*_controller/command for the joint efforts tauPub1 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint1_controller/command", 20); tauPub2 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint2_controller/command", 20); tauPub3 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint3_controller/command", 20); tauPub4 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint4_controller/command", 20); tauPub5 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint5_controller/command", 20); tauPub6 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint6_controller/command", 20); tauPub7 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint7_controller/command", 20); // Subscribers for proprioceptive sensors (i.e. from joint:states) and camera position (i.e. aruco_single/pose) sensorSub = nh.subscribe("/robot1/joint_states", 1, &MRAC::jointStatesCallback, this); // Set goal for velocity (always zero), the goal for the position is set by the main node MRAC_controller_node dqr << 0, 0, 0, 0, 0, 0, 0; // Set initial conditions for the states for the integrals x_qe << 0, 0, 0, 0, 0, 0, 0; X_qr << Eigen::Matrix<double, 7, 7>::Zero(); X_dqr << Eigen::Matrix<double, 7, 7>::Zero(); X_q << Eigen::Matrix<double, 7, 7>::Zero(); X_dq << Eigen::Matrix<double, 7, 7>::Zero(); // Support variable dataReceived = 0; // Integration step h = 0.001; // MRAC Variables omega << 2, 2, 2, 2, 2, 2, 2; // Damping zeta << 1, 1, 1, 1, 1, 1, 1; // Controller parameters alpha1 << 40, 200, 40, 200, 200, 200, 40; alpha2 << 4, 4, 4, 4, 4, 4, 4; alpha3 << 0, 0, 0, 0, 0, 0, 0; e01 << 20, 40, 20, 40, 20, 40, 20; e02 << 2, 4, 2, 4, 2, 4, 2; e03 << 0, 0, 0, 0, 0, 0, 0; e11 << 10, 20, 10, 20, 10, 20, 10; e12 << 1, 2, 1, 2, 1, 2, 1; e13 << 0, 0, 0, 0, 0, 0, 0; f01 << 10, 10, 10, 10, 50, 50, 50; f02 << 1, 1, 1, 1, 1, 1, 1; f03 << 0, 0, 0, 0, 0, 0, 0; // Not used for constant ref f11 << 1, 1, 1, 1, 1, 1, 1; f12 << 1, 1, 1, 1, 10, 10, 10; f13 << 0, 0, 0, 0, 0, 0, 0; //////////////////////////// l1 << 1, 1, 1, 1, 1, 1, 1; l2 << 1, 1, 1, 1, 1, 1, 1; // From here on a normal user should not modify p2 << l1[0]/(2*omega[0]*omega[0]), l1[1]/(2*omega[1]*omega[1]), l1[2]/(2*omega[2]*omega[2]), l1[3]/(2*omega[3]*omega[3]), l1[4]/(2*omega[4]*omega[4]), l1[5]/(2*omega[5]*omega[5]), l1[6]/(2*omega[6]*omega[6]); p3 << l2[0]/(4*zeta[0]*omega[0])+l1[0]/(4*zeta[0]*pow(omega[0],3)), l2[1]/(4*zeta[1]*omega[1])+l1[1]/(4*zeta[1]*pow(omega[1],3)), l2[2]/(4*zeta[2]*omega[2])+l1[2]/(4*zeta[2]*pow(omega[2],3)), l2[3]/(4*zeta[3]*omega[3])+l1[3]/(4*zeta[3]*pow(omega[3],3)), l2[4]/(4*zeta[4]*omega[4])+l1[4]/(4*zeta[4]*pow(omega[4],3)), l2[5]/(4*zeta[5]*omega[5])+l1[5]/(4*zeta[5]*pow(omega[5],3)), l2[6]/(4*zeta[6]*omega[6])+l1[6]/(4*zeta[6]*pow(omega[6],3)); // Initial adaptive gains and constant matrices K0_hat = Eigen::Matrix<double, 7, 7>::Zero(); K1_hat = Eigen::Matrix<double, 7, 7>::Zero(); Q0_hat = Eigen::Matrix<double, 7, 7>::Zero(); Q1_hat = Eigen::Matrix<double, 7, 7>::Zero(); // Controller parameters ALPHA1 = Eigen::Matrix<double, 7, 7>::Zero(); ALPHA2 = Eigen::Matrix<double, 7, 7>::Zero(); ALPHA3 = Eigen::Matrix<double, 7, 7>::Zero(); E01 = Eigen::Matrix<double, 7, 7>::Zero(); E02 = Eigen::Matrix<double, 7, 7>::Zero(); E03 = Eigen::Matrix<double, 7, 7>::Zero(); E11 = Eigen::Matrix<double, 7, 7>::Zero(); E12 = Eigen::Matrix<double, 7, 7>::Zero(); E13 = Eigen::Matrix<double, 7, 7>::Zero(); F01 = Eigen::Matrix<double, 7, 7>::Zero(); F02 = Eigen::Matrix<double, 7, 7>::Zero(); F03 = Eigen::Matrix<double, 7, 7>::Zero(); F11 = Eigen::Matrix<double, 7, 7>::Zero(); F12 = Eigen::Matrix<double, 7, 7>::Zero(); F13 = Eigen::Matrix<double, 7, 7>::Zero(); P2 = Eigen::Matrix<double, 7, 7>::Zero(); P3 = Eigen::Matrix<double, 7, 7>::Zero(); for( int i = 0; i < P2.rows(); i = i + 1 ) { ALPHA1(i,i) = alpha1(i); ALPHA2(i,i) = alpha2(i); ALPHA3(i,i) = alpha3(i); E01(i,i) = e01(i); E02(i,i) = e02(i); E03(i,i) = e03(i); E11(i,i) = e11(i); E12(i,i) = e12(i); E13(i,i) = e13(i); F01(i,i) = f01(i); F02(i,i) = f02(i); F03(i,i) = f03(i); F11(i,i) = f11(i); F12(i,i) = f12(i); F13(i,i) = f13(i); P2(i,i) = p2(i); P3(i,i) = p3(i); } } void MRAC::jointStatesCallback(const sensor_msgs::JointState::ConstPtr& msg) { // Save joint values for( int i = 0; i < 7; i++ ) { jointPos(i) = msg->position[i]; jointVel(i) = msg->velocity[i]; } // If this is the first time we read the joint states then we set the current beliefs if (dataReceived == 0){ // Track the fact that the encoders published dataReceived = 1; } // std::cout << jointPos << '\n'; } void MRAC::setGoal(std::vector<double> desiredPos){ for(int i=0; i<desiredPos.size(); i++){ qr(i) = desiredPos[i]; } } int MRAC::dataReady(){ // Method to control if the joint states have been received already, used in the main function if(dataReceived==1) return 1; else return 0; } void MRAC::computeControlInput(){ // Definition of the modified joint angle error qe = P2*(qr-jointPos)+P3*(dqr-jointVel); // Feed-forward term f // Integral of qe using first order system as integrator qe_integral = x_qe; x_qe = x_qe + h*qe; f = ALPHA1*qe + ALPHA2*qe_integral; // Adaptive gain K0 qe_q_integral = X_q; X_q = X_q + qe*jointPos.transpose(); K0 = K0_hat + E01*(qe*jointPos.transpose()) + E02*qe_q_integral; // Adaptive gain K1 qe_dq_integral = X_q; X_dq = X_dq + qe*jointVel.transpose(); K1 = K1_hat + E11*(qe*jointVel.transpose()) + E12*qe_dq_integral; // Adaptive gain Q0 qe_qr_integral = X_qr; X_qr = X_qr + qe*qr.transpose(); Q0 = Q0_hat + F01*(qe*qr.transpose()) + F02*qe_qr_integral; // Adaptive gain K1 qe_dqr_integral = X_dqr; X_dqr = X_dqr + qe*dqr.transpose(); Q1 = Q1_hat + F11*(qe*dqr.transpose()) + F12*qe_dqr_integral; // std::cout << Q1 << '\n'; // Torque to the robot arm u = (K0*jointPos + K1*jointVel + Q0*qr + Q1*dqr + f); // std::cout << "Start" << '\n'; // std::cout << u << '\n'; // Build and send command messages // Set the toques from u and publish tau1.data = u(0); tau2.data = u(1); tau3.data = u(2); tau4.data = u(3); tau5.data = u(4); tau6.data = u(5); tau7.data = u(6); // Publishing tauPub1.publish(tau1); tauPub2.publish(tau2); tauPub3.publish(tau3); tauPub4.publish(tau4); tauPub5.publish(tau5); tauPub6.publish(tau6); tauPub7.publish(tau7); }
#define LOGURU_IMPLEMENTATION 1 #define LOG_WITH_STREAMS 1 #include "loguru.hpp"
// ********************************************************************** // // Copyright (c) 2003-2006 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** // Ice version 3.1.1 // Generated from file `Transfer.ice' #include <Transfer.h> #include <Ice/LocalException.h> #include <Ice/ObjectFactory.h> #include <Ice/BasicStream.h> #include <Ice/Object.h> #include <IceUtil/Iterator.h> #ifndef ICE_IGNORE_VERSION # if ICE_INT_VERSION / 100 != 301 # error Ice version mismatch! # endif # if ICE_INT_VERSION % 100 < 1 # error Ice patch level mismatch! # endif #endif static const ::std::string __fktest__Transfer__send_name = "send"; static const ::std::string __fktest__Transfer__sendsn_name = "sendsn"; void IceInternal::incRef(::fktest::Transfer* p) { p->__incRef(); } void IceInternal::decRef(::fktest::Transfer* p) { p->__decRef(); } void IceInternal::incRef(::IceProxy::fktest::Transfer* p) { p->__incRef(); } void IceInternal::decRef(::IceProxy::fktest::Transfer* p) { p->__decRef(); } void fktest::__write(::IceInternal::BasicStream* __os, const ::fktest::TransferPrx& v) { __os->write(::Ice::ObjectPrx(v)); } void fktest::__read(::IceInternal::BasicStream* __is, ::fktest::TransferPrx& v) { ::Ice::ObjectPrx proxy; __is->read(proxy); if(!proxy) { v = 0; } else { v = new ::IceProxy::fktest::Transfer; v->__copyFrom(proxy); } } void fktest::__write(::IceInternal::BasicStream* __os, const ::fktest::TransferPtr& v) { __os->write(::Ice::ObjectPtr(v)); } ::Ice::Int IceProxy::fktest::Transfer::send(const ::fktest::ByteSeq& bytes, ::Ice::Int id, const ::Ice::Context& __ctx) { int __cnt = 0; while(true) { try { __checkTwowayOnly(__fktest__Transfer__send_name); ::IceInternal::Handle< ::IceDelegate::Ice::Object> __delBase = __getDelegate(); ::IceDelegate::fktest::Transfer* __del = dynamic_cast< ::IceDelegate::fktest::Transfer*>(__delBase.get()); return __del->send(bytes, id, __ctx); } catch(const ::IceInternal::LocalExceptionWrapper& __ex) { __handleExceptionWrapper(__ex); } catch(const ::Ice::LocalException& __ex) { __handleException(__ex, __cnt); } } } ::Ice::Int IceProxy::fktest::Transfer::sendsn(::Ice::Int sn, ::Ice::Int id, const ::Ice::Context& __ctx) { int __cnt = 0; while(true) { try { __checkTwowayOnly(__fktest__Transfer__sendsn_name); ::IceInternal::Handle< ::IceDelegate::Ice::Object> __delBase = __getDelegate(); ::IceDelegate::fktest::Transfer* __del = dynamic_cast< ::IceDelegate::fktest::Transfer*>(__delBase.get()); return __del->sendsn(sn, id, __ctx); } catch(const ::IceInternal::LocalExceptionWrapper& __ex) { __handleExceptionWrapper(__ex); } catch(const ::Ice::LocalException& __ex) { __handleException(__ex, __cnt); } } } const ::std::string& IceProxy::fktest::Transfer::ice_staticId() { return ::fktest::Transfer::ice_staticId(); } ::IceInternal::Handle< ::IceDelegateM::Ice::Object> IceProxy::fktest::Transfer::__createDelegateM() { return ::IceInternal::Handle< ::IceDelegateM::Ice::Object>(new ::IceDelegateM::fktest::Transfer); } ::IceInternal::Handle< ::IceDelegateD::Ice::Object> IceProxy::fktest::Transfer::__createDelegateD() { return ::IceInternal::Handle< ::IceDelegateD::Ice::Object>(new ::IceDelegateD::fktest::Transfer); } bool IceProxy::fktest::operator==(const ::IceProxy::fktest::Transfer& l, const ::IceProxy::fktest::Transfer& r) { return static_cast<const ::IceProxy::Ice::Object&>(l) == static_cast<const ::IceProxy::Ice::Object&>(r); } bool IceProxy::fktest::operator!=(const ::IceProxy::fktest::Transfer& l, const ::IceProxy::fktest::Transfer& r) { return static_cast<const ::IceProxy::Ice::Object&>(l) != static_cast<const ::IceProxy::Ice::Object&>(r); } bool IceProxy::fktest::operator<(const ::IceProxy::fktest::Transfer& l, const ::IceProxy::fktest::Transfer& r) { return static_cast<const ::IceProxy::Ice::Object&>(l) < static_cast<const ::IceProxy::Ice::Object&>(r); } bool IceProxy::fktest::operator<=(const ::IceProxy::fktest::Transfer& l, const ::IceProxy::fktest::Transfer& r) { return l < r || l == r; } bool IceProxy::fktest::operator>(const ::IceProxy::fktest::Transfer& l, const ::IceProxy::fktest::Transfer& r) { return !(l < r) && !(l == r); } bool IceProxy::fktest::operator>=(const ::IceProxy::fktest::Transfer& l, const ::IceProxy::fktest::Transfer& r) { return !(l < r); } ::Ice::Int IceDelegateM::fktest::Transfer::send(const ::fktest::ByteSeq& bytes, ::Ice::Int id, const ::Ice::Context& __context) { ::IceInternal::Outgoing __og(__connection.get(), __reference.get(), __fktest__Transfer__send_name, ::Ice::Normal, __context, __compress); try { ::IceInternal::BasicStream* __os = __og.os(); if(bytes.size() == 0) { __os->writeSize(0); } else { __os->write(&bytes[0], &bytes[0] + bytes.size()); } __os->write(id); } catch(const ::Ice::LocalException& __ex) { __og.abort(__ex); } bool __ok = __og.invoke(); try { ::IceInternal::BasicStream* __is = __og.is(); if(!__ok) { try { __is->throwException(); } catch(const ::Ice::UserException& __ex) { throw ::Ice::UnknownUserException(__FILE__, __LINE__, __ex.ice_name()); } } ::Ice::Int __ret; __is->read(__ret); return __ret; } catch(const ::Ice::LocalException& __ex) { throw ::IceInternal::LocalExceptionWrapper(__ex, false); } } ::Ice::Int IceDelegateM::fktest::Transfer::sendsn(::Ice::Int sn, ::Ice::Int id, const ::Ice::Context& __context) { ::IceInternal::Outgoing __og(__connection.get(), __reference.get(), __fktest__Transfer__sendsn_name, ::Ice::Normal, __context, __compress); try { ::IceInternal::BasicStream* __os = __og.os(); __os->write(sn); __os->write(id); } catch(const ::Ice::LocalException& __ex) { __og.abort(__ex); } bool __ok = __og.invoke(); try { ::IceInternal::BasicStream* __is = __og.is(); if(!__ok) { try { __is->throwException(); } catch(const ::Ice::UserException& __ex) { throw ::Ice::UnknownUserException(__FILE__, __LINE__, __ex.ice_name()); } } ::Ice::Int __ret; __is->read(__ret); return __ret; } catch(const ::Ice::LocalException& __ex) { throw ::IceInternal::LocalExceptionWrapper(__ex, false); } } ::Ice::Int IceDelegateD::fktest::Transfer::send(const ::fktest::ByteSeq& bytes, ::Ice::Int id, const ::Ice::Context& __context) { ::Ice::Current __current; __initCurrent(__current, __fktest__Transfer__send_name, ::Ice::Normal, __context); while(true) { ::IceInternal::Direct __direct(__current); ::fktest::Transfer* __servant = dynamic_cast< ::fktest::Transfer*>(__direct.servant().get()); if(!__servant) { ::Ice::OperationNotExistException __opEx(__FILE__, __LINE__); __opEx.id = __current.id; __opEx.facet = __current.facet; __opEx.operation = __current.operation; throw __opEx; } try { return __servant->send(bytes, id, __current); } catch(const ::Ice::LocalException& __ex) { throw ::IceInternal::LocalExceptionWrapper(__ex, false); } } } ::Ice::Int IceDelegateD::fktest::Transfer::sendsn(::Ice::Int sn, ::Ice::Int id, const ::Ice::Context& __context) { ::Ice::Current __current; __initCurrent(__current, __fktest__Transfer__sendsn_name, ::Ice::Normal, __context); while(true) { ::IceInternal::Direct __direct(__current); ::fktest::Transfer* __servant = dynamic_cast< ::fktest::Transfer*>(__direct.servant().get()); if(!__servant) { ::Ice::OperationNotExistException __opEx(__FILE__, __LINE__); __opEx.id = __current.id; __opEx.facet = __current.facet; __opEx.operation = __current.operation; throw __opEx; } try { return __servant->sendsn(sn, id, __current); } catch(const ::Ice::LocalException& __ex) { throw ::IceInternal::LocalExceptionWrapper(__ex, false); } } } ::Ice::ObjectPtr fktest::Transfer::ice_clone() const { throw ::Ice::CloneNotImplementedException(__FILE__, __LINE__); return 0; // to avoid a warning with some compilers } static const ::std::string __fktest__Transfer_ids[2] = { "::Ice::Object", "::fktest::Transfer" }; bool fktest::Transfer::ice_isA(const ::std::string& _s, const ::Ice::Current&) const { return ::std::binary_search(__fktest__Transfer_ids, __fktest__Transfer_ids + 2, _s); } ::std::vector< ::std::string> fktest::Transfer::ice_ids(const ::Ice::Current&) const { return ::std::vector< ::std::string>(&__fktest__Transfer_ids[0], &__fktest__Transfer_ids[2]); } const ::std::string& fktest::Transfer::ice_id(const ::Ice::Current&) const { return __fktest__Transfer_ids[1]; } const ::std::string& fktest::Transfer::ice_staticId() { return __fktest__Transfer_ids[1]; } ::IceInternal::DispatchStatus fktest::Transfer::___send(::IceInternal::Incoming&__inS, const ::Ice::Current& __current) { __checkMode(::Ice::Normal, __current.mode); ::IceInternal::BasicStream* __is = __inS.is(); ::IceInternal::BasicStream* __os = __inS.os(); ::fktest::ByteSeq bytes; ::Ice::Int id; ::std::pair<const ::Ice::Byte*, const ::Ice::Byte*> ___bytes; __is->read(___bytes); ::std::vector< ::Ice::Byte>(___bytes.first, ___bytes.second).swap(bytes); __is->read(id); ::Ice::Int __ret = send(bytes, id, __current); __os->write(__ret); return ::IceInternal::DispatchOK; } ::IceInternal::DispatchStatus fktest::Transfer::___sendsn(::IceInternal::Incoming&__inS, const ::Ice::Current& __current) { __checkMode(::Ice::Normal, __current.mode); ::IceInternal::BasicStream* __is = __inS.is(); ::IceInternal::BasicStream* __os = __inS.os(); ::Ice::Int sn; ::Ice::Int id; __is->read(sn); __is->read(id); ::Ice::Int __ret = sendsn(sn, id, __current); __os->write(__ret); return ::IceInternal::DispatchOK; } static ::std::string __fktest__Transfer_all[] = { "ice_id", "ice_ids", "ice_isA", "ice_ping", "send", "sendsn" }; ::IceInternal::DispatchStatus fktest::Transfer::__dispatch(::IceInternal::Incoming& in, const ::Ice::Current& current) { ::std::pair< ::std::string*, ::std::string*> r = ::std::equal_range(__fktest__Transfer_all, __fktest__Transfer_all + 6, current.operation); if(r.first == r.second) { return ::IceInternal::DispatchOperationNotExist; } switch(r.first - __fktest__Transfer_all) { case 0: { return ___ice_id(in, current); } case 1: { return ___ice_ids(in, current); } case 2: { return ___ice_isA(in, current); } case 3: { return ___ice_ping(in, current); } case 4: { return ___send(in, current); } case 5: { return ___sendsn(in, current); } } assert(false); return ::IceInternal::DispatchOperationNotExist; } void fktest::Transfer::__write(::IceInternal::BasicStream* __os) const { __os->writeTypeId(ice_staticId()); __os->startWriteSlice(); __os->endWriteSlice(); #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug Object::__write(__os); #else ::Ice::Object::__write(__os); #endif } void fktest::Transfer::__read(::IceInternal::BasicStream* __is, bool __rid) { if(__rid) { ::std::string myId; __is->readTypeId(myId); } __is->startReadSlice(); __is->endReadSlice(); #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug Object::__read(__is, true); #else ::Ice::Object::__read(__is, true); #endif } void fktest::Transfer::__write(const ::Ice::OutputStreamPtr&) const { Ice::MarshalException ex(__FILE__, __LINE__); ex.reason = "type fktest::Transfer was not generated with stream support"; throw ex; } void fktest::Transfer::__read(const ::Ice::InputStreamPtr&, bool) { Ice::MarshalException ex(__FILE__, __LINE__); ex.reason = "type fktest::Transfer was not generated with stream support"; throw ex; } void fktest::__patch__TransferPtr(void* __addr, ::Ice::ObjectPtr& v) { ::fktest::TransferPtr* p = static_cast< ::fktest::TransferPtr*>(__addr); assert(p); *p = ::fktest::TransferPtr::dynamicCast(v); if(v && !*p) { ::Ice::NoObjectFactoryException e(__FILE__, __LINE__); e.type = ::fktest::Transfer::ice_staticId(); throw e; } } bool fktest::operator==(const ::fktest::Transfer& l, const ::fktest::Transfer& r) { return static_cast<const ::Ice::Object&>(l) == static_cast<const ::Ice::Object&>(r); } bool fktest::operator!=(const ::fktest::Transfer& l, const ::fktest::Transfer& r) { return static_cast<const ::Ice::Object&>(l) != static_cast<const ::Ice::Object&>(r); } bool fktest::operator<(const ::fktest::Transfer& l, const ::fktest::Transfer& r) { return static_cast<const ::Ice::Object&>(l) < static_cast<const ::Ice::Object&>(r); } bool fktest::operator<=(const ::fktest::Transfer& l, const ::fktest::Transfer& r) { return l < r || l == r; } bool fktest::operator>(const ::fktest::Transfer& l, const ::fktest::Transfer& r) { return !(l < r) && !(l == r); } bool fktest::operator>=(const ::fktest::Transfer& l, const ::fktest::Transfer& r) { return !(l < r); }
#include <iostream> #include "Bureaucrat.hpp" #include "PresidentialPardonForm.hpp" #include "RobotomyRequestForm.hpp" #include "ShrubberyCreationForm.hpp" #include "Form.hpp" #include <cstdlib> #include <ctime> int main(void) { Bureaucrat b("PPPPP", Bureaucrat::maxGrade); Bureaucrat bo("LALALA", Bureaucrat::minGrade); Form *form1 = new PresidentialPardonForm("AAA"); Form *form2 = new RobotomyRequestForm("SSS"); Form *form3 = new ShrubberyCreationForm("VVV"); std::cout << std::endl; bo.executeForm(*form1); std::cout << std::endl; bo.signForm(*form1); std::cout << std::endl; b.executeForm(*form1); std::cout << std::endl; bo.executeForm(*form1); std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; srand(time(NULL)); bo.executeForm(*form2); std::cout << std::endl; bo.signForm(*form2); std::cout << std::endl; b.executeForm(*form2); std::cout << std::endl; bo.executeForm(*form2); bo.executeForm(*form2); bo.executeForm(*form2); std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; bo.executeForm(*form3); std::cout << std::endl; bo.signForm(*form3); std::cout << std::endl; b.executeForm(*form3); std::cout << std::endl; bo.executeForm(*form3); std::cout << std::endl; delete form1; delete form2; delete form3; return (0); }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- // // Copyright (C) 1995-2006 Opera Software ASA. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // Adam Minchinton and Karianne Ekern // #ifndef __SYNCSHUTDOWNPROGRESSDIALOG_H__ #define __SYNCSHUTDOWNPROGRESSDIALOG_H__ #ifdef SUPPORT_DATA_SYNC #include "adjunct/quick/managers/SyncManager.h" #include "adjunct/quick_toolkit/widgets/Dialog.h" #include "modules/sync/sync_coordinator.h" class SyncShutdownProgressDialog : public Dialog, #ifdef SY_CAP_SYNCLISTENER_CHANGED public OpSyncUIListener #else public OpSyncListener #endif { public: SyncShutdownProgressDialog(); ~SyncShutdownProgressDialog(); virtual void OnInit(); virtual BOOL GetModality() { return TRUE; } virtual BOOL GetIsBlocking() { return FALSE; } virtual Type GetType() {return DIALOG_TYPE_SYNC_SHUTDOWN_PROGRESS;} virtual const char* GetWindowName() {return "Sync Shutdown Progress Dialog";} virtual DialogType GetDialogType() {return TYPE_OK;} virtual void OnClose(BOOL user_initiated); virtual const uni_char* GetOkText() { return m_ok_text.CStr();} #ifdef SY_CAP_SYNCLISTENER_CHANGED // OpSyncUIListener virtual void OnSyncFinished(OpSyncState& sync_state) {} virtual void OnSyncError(OpSyncError error, const OpStringC& error_msg); virtual void OnSyncStarted(BOOL items_sent) {} virtual void OnSyncReencryptEncryptionKeyFailed(ReencryptEncryptionKeyContext* context) { /* Empty. */ } virtual void OnSyncReencryptEncryptionKeyCancel(ReencryptEncryptionKeyContext* context) { /* Empty. */ } #else // OpSyncListener void OnSyncError(OpSyncError error, OpString& error_msg); void OnSyncStarted(BOOL items_sending) {} void OnSyncCompleted(OpSyncCollection *new_items, OpSyncState& sync_state, OpSyncServerInformation& server_info) {} void OnSyncItemAdded() {} #endif private: OpString m_ok_text; BOOL m_dont_exit; }; #endif // SUPPORT_DATA_SYNC #endif // __SYNCSHUTDOWNPROGRESSDIALOG_H__
#ifndef TOOLS_SHELL_DBCLIENTPROXY #define TOOLS_SHELL_DBCLIENTPROXY #include <vector> #include <map> #include <string> #include <boost/utility.hpp> #include <boost/shared_ptr.hpp> #include "DB.h" /* * class DBClientProxy maintains: * 1. a connection to rocksdb service * 2. a map from db names to opened db handles * * it's client codes' responsibility to catch all possible exceptions. */ namespace rocksdb { class DBClientProxy : private boost::noncopyable { public: // connect to host_:port_ void connect(void); // return true on success, false otherwise bool get(const std::string & db, const std::string & key, std::string & value); // return true on success, false otherwise bool put(const std::string & db, const std::string & key, const std::string & value); // return true on success, false otherwise bool scan(const std::string & db, const std::string & start_key, const std::string & end_key, const std::string & limit, std::vector<std::pair<std::string, std::string> > & kvs); // return true on success, false otherwise bool create(const std::string & db); DBClientProxy(const std::string & host, int port); ~DBClientProxy(); private: // some internal help functions void cleanUp(void); void open(const std::string & db); std::map<std::string, Trocksdb::DBHandle>::iterator getHandle(const std::string & db); const std::string host_; const int port_; std::map<std::string, Trocksdb::DBHandle> dbToHandle_; boost::shared_ptr<Trocksdb::DBClient> dbClient_; }; } // namespace #endif
#ifndef GAME_H #define GAME_H #include <allegro5\allegro.h> class Game { public: static int gameState; // 0 = menu, 1 == game; }; #endif
#include "SIdict.h" #include <string> #include <iostream> // Conner Zeigman and Daniel Kramer // I pledge on my honor that I have abided by the Stevens Honor System Dict::Dict(){ first = NULL; } struct Dict::DictNode{ string key; int value; DictNode* next; }; int Dict::hasKey(string key){ DictNode* current = first; while (current != NULL){ if ((current -> key).compare(key) == 0){ return 1; } current = current -> next; } return 0; } int Dict::addOrUpdate(string key, int value){ DictNode* current = first; if (hasKey(key) == 1){ while (current != NULL){ if((current -> key).compare(key) == 0){ current -> value = value; } current = current -> next; } return 1; } else { if (current != NULL){ while ((current -> next) != NULL){ current = current -> next; } DictNode* newNode1 = new DictNode(); current -> next = newNode1; newNode1 -> next = NULL; newNode1 -> value = value; newNode1 -> key = key; } else { DictNode* newNode = new DictNode(); current = newNode; first = newNode; newNode -> value = value; newNode -> key = key; newNode -> next = NULL; } return 0; } } int Dict::lookup(string key){ if (hasKey(key)){ DictNode* current = first; while ((current -> key).compare(key) != 0){ current = current -> next; } return current -> value; } else { return -1; } } int Dict::remKey(string key){ if (hasKey(key) == 1){ if(first == NULL){ return -1; } DictNode* current = first; if ((current -> key).compare(key) == 0){ first = current -> next; delete current; return 1; } DictNode* prev = current; current = current -> next; while ((current -> next) != NULL && (current -> key).compare(key) != 0){ prev = current; current = current -> next; } prev -> next = current -> next; delete current; return 1; } return -2; }
#ifndef ExternDot_HPP #define ExternDot_HPP #include <QObject> // Object source includes externally generated .moc file class ExternDot : public QObject { Q_OBJECT public: ExternDot(); ~ExternDot(); }; #endif
#pragma once #include "singletonBase.h" #include "image.h" enum ITEMKIND{ NONE, LEVLEUPITEM, ULTIMATEITEM }; struct tagItem { image* img; int _count; int _index; float x; float y; float angle; RECT rc; bool isActive; int width; int height; float speed; int time; }; class itemManager : public singletonBase<itemManager> { private: enum{MAXITEM = 10}; vector<tagItem> v_levelItem; vector<tagItem> v_ultiItem; public: HRESULT init(); void release(); void update(); void render(HDC hdc); void itemMove(); void anim(); void active(float x, float y, float angle , ITEMKIND kind); pair<bool, ITEMKIND> collision(RECT p_rc); void itemOut(); itemManager() {} ~itemManager() {} };
#pragma once #include "../../Engine/graphics/animation/AnimationClip.h" #include "../Monster.h" class TestMons :public Monster { public: TestMons(); //bool Start() override; //void Update() override; private: AnimationClip m_animclip[3]; };
// // Created on 04/01/19. // #pragma once #include <map> #include <array> #include <armadillo> // Conversion from C# summary: // - int ==> uint64_t // - Dictionary<TKey, TVavlue> ==> std::map<TKey, TValue> // - List<T> ==> std::vector<T> // - List<T> where T : const K ==> std::array<T> // - double[,] ==> arma::mat namespace Algorithms { class ST_MVL { private: const std::string techFolder = "_technical/ST-MVL/"; const std::string equationFile = techFolder + "stmvl_equation.txt"; const std::string trainingFolder = techFolder + "TrainingFolder/"; private: uint64_t rowCount; uint64_t columnCount; double alpha; double gamma; uint64_t windowSize; const double default_missing = std::numeric_limits<double>::quiet_NaN(); //const double default_missing = 0.010101010101010101; arma::mat &missingMatrix; arma::mat predictMatrix; arma::mat temporaryMatrix; std::map<std::pair<uint64_t, uint64_t>, double> distanceDic; std::map<uint64_t, std::vector<uint64_t>> stationDic; const uint64_t temporal_threshold = 5; const static uint64_t viewCount = 4; public: // aux inline double ComputeSpatialWeight(double dis); inline double ComputeTemporalWeight(uint64_t timespan); // construct explicit ST_MVL(arma::mat &_missing, const std::string &latlong, double _alpha, double _gamma, uint64_t _windowSize); void Run(bool isBlockMissing); void doSTMVL(); void InitializeMissing(); void GlobalViewCombine(uint64_t i, uint64_t j); void MVL(uint64_t i, uint64_t j, arma::mat &equation); double UCF(uint64_t ti, uint64_t tj, arma::mat &dataMatrix); double calUserEuclideanSim(uint64_t tj, uint64_t jj, uint64_t ti, arma::mat &dataMatrix); double ICF(uint64_t ti, uint64_t tj, arma::mat &dataMatrix); double calItemEuclideanSim(uint64_t ti, uint64_t ii, uint64_t tj, arma::mat &dataMatrix); double SES(uint64_t ti, uint64_t tj, arma::mat &dataMatrix); double IDW(uint64_t ti, uint64_t tj, arma::mat &dataMatrix); void GenerateTrainingCase(); uint64_t checkContextData(uint64_t ti, uint64_t tj); void outputCase(uint64_t i, uint64_t j, std::ofstream &swTrain); void FourView(uint64_t sensorCount); void sqt2(const arma::mat &x, const arma::vec &y, std::array<double, viewCount + 1> &a, std::array<double, 4> &dt, std::array<double, viewCount> &v); int chlk(arma::vec &a, uint64_t n, uint64_t m, std::array<double, viewCount + 1> &d); inline bool ismissing(double val); double GeoDistance(double lat1, double lng1, double lat2, double lng2); inline double RadToDeg(double d); }; // Auxiliary } // namespace Algorithms
#include "ros/ros.h" #include "std_msgs/String.h" #include "std_msgs/Float32.h" //not sure how to check if the header file is present // or not #include <sstream> #include "beginner_tutorials/Num.h" #include "beginner_tutorials/driveCmd.h" #include "beginner_tutorials/Num.h" #include "custom_messages/driveMessage.h" #include <iostream> int main(int argc, char **argv) { ros::init(argc, argv, "driveControl"); ros::NodeHandle n; ros::Publisher drive_publisher = n.advertise<beginner_tutorials::driveCmd>("drive_cmd_channel",1000); beginner_tutorials::Num currentDrive_cmd; beginner_tutorials::driveCmd DRIVE_FEED; // currentDrive_cmd.x = 0; //This is manually set right now, will be mapped to a 16bit register(PWM) // currentDrive_cmd.y = 0; //This is manually set right now, will be mapped to a 16bit register(PWM) DRIVE_FEED.throttle = 0.5; DRIVE_FEED.steering = 0.8; ros::Rate loop_rate(10); //10 times a second - publish @ while(ros::ok()) { ROS_INFO("Drive Command Sent. iThrottle =: %f",DRIVE_FEED.throttle); // std::cout<<currentDrive_cmd.data<<"\n"; drive_publisher.publish(DRIVE_FEED); loop_rate.sleep(); } }
#include <ros/ros.h> #include <ros/package.h> #include <memory> #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <exception> #include <io_lib/io_utils.h> #include <io_lib/file_io.h> #include <gmp_lib/GMP/GMPo.h> #include <gmp_test/utils.h> using namespace as64_; #define TEST_ORIENT_GMP_ typedef void (*sim_fun_ptr)(std::shared_ptr<gmp_::GMPo> &, const arma::vec &, const arma::vec &, double , double , arma::rowvec &, arma::mat &, arma::mat &, arma::mat &); void loadParams(); std::string path; std::string train_data_file; std::string sim_data_file; std::string train_method; unsigned N_kernels; double D; double K; double kernels_std_scaling; double ks; double kt; sim_fun_ptr simulateGMPo; int main(int argc, char** argv) { #ifdef TEST_ORIENT_GMP_ try{ #endif // =========== Initialize the ROS node =============== ros::init(argc, argv, "Test_orient_GMP_node"); loadParams(); // =========== Load training data =============== std::ifstream in(train_data_file, std::ios::in | std::ios::binary); if (!in) throw std::runtime_error("Failed to open file \"" + train_data_file + "\"..."); arma::rowvec Timed; arma::mat Qd_data; arma::mat vRotd_data; arma::mat dvRotd_data; io_::read_mat(Timed, in, true); io_::read_mat(Qd_data, in, true); io_::read_mat(vRotd_data, in, true); io_::read_mat(dvRotd_data, in, true); in.close(); double Ts = Timed(1)-Timed(0); // =========== initialize gmp =============== std::shared_ptr<gmp_::GMPo> gmp( new gmp_::GMPo(arma::uvec({N_kernels}), arma::vec({D}), arma::vec({K}), kernels_std_scaling) ); arma::wall_clock timer; timer.tic(); std::cout << "GMPo training...\n"; arma::vec offline_train_mse; int i_end = Timed.size()-1; gmp->train(train_method, Timed, Qd_data, &offline_train_mse); std::cout << "offline_train_mse = \n" << offline_train_mse << "\n"; std::cout << "Elapsed time: " << timer.toc() << " sec\n"; gmp->exportToFile(path+"/gmp_o_model.bin"); gmp = gmp_::GMPo::importFromFile(path+"/gmp_o_model.bin"); // std::shared_ptr<gmp_::GMPo> gmp = gmp_::GMPo::importFromFile(path+"/gmp_o_model.bin"); // =========== gmp update and simulation =============== arma::vec Q0d = Qd_data.col(0); arma::vec Qgd = Qd_data.col(i_end); arma::vec Q0 = Q0d; arma::vec e0 = ks*gmp_::quatLog( gmp_::quatProd( Qgd, gmp_::quatInv(Q0d) ) ); arma::vec Qg = gmp_::quatProd(gmp_::quatExp(e0), Q0); double T = kt*Timed(i_end); double dt = Timed(1) - Timed(0); arma::rowvec Time; arma::mat Q_data; arma::mat vRot_data; arma::mat dvRot_data; simulateGMPo(gmp, Q0, Qg, T, dt, Time, Q_data, vRot_data, dvRot_data); // =========== write results =============== io_::FileIO out(sim_data_file, io_::FileIO::out | io_::FileIO::trunc); out.write("Timed", Timed); out.write("Qd_data", Qd_data); out.write("vRotd_data", vRotd_data); out.write("dvRotd_data", dvRotd_data); out.write("Time", Time); out.write("Q_data", Q_data); out.write("vRot_data", vRot_data); out.write("dvRot_data", dvRot_data); out.write("ks", ks); out.write("kt", kt); // =========== Shutdown ROS node ================== ros::shutdown(); return 0; #ifdef TEST_ORIENT_GMP_ }catch(std::exception &e) { throw std::runtime_error(std::string("[main]: ") + e.what()); } #endif } void loadParams() { #ifdef TEST_ORIENT_GMP_ try{ #endif ros::NodeHandle nh_("~"); // =========== Read params =============== path = ros::package::getPath("gmp_test") + "/matlab/data/"; if (!nh_.getParam("train_data_file", train_data_file)) train_data_file = "gmp_train_data.bin"; if (!nh_.getParam("sim_data_file", sim_data_file)) sim_data_file = "gmp_update_sim_data.bin"; if (!nh_.getParam("train_method", train_method)) train_method = "LWR"; int n_ker; if (!nh_.getParam("N_kernels", n_ker)) n_ker = 30; N_kernels = n_ker; if (!nh_.getParam("D", D)) D = 50; if (!nh_.getParam("K", K)) K = 250; if (!nh_.getParam("kernels_std_scaling", kernels_std_scaling)) kernels_std_scaling = 2; if (!nh_.getParam("ks", ks)) ks = 1.0; if (!nh_.getParam("kt", kt)) kt = 1.0; std::string sim_fun; if (!nh_.getParam("sim_fun", sim_fun)) sim_fun = "log"; if (sim_fun.compare("log")==0) simulateGMPo = &simulateGMPo_in_log_space; else if (sim_fun.compare("quat")==0) simulateGMPo = &simulateGMPo_in_quat_space; else std::runtime_error("Unsupported simulation function: \"" + sim_fun + "\"..."); train_data_file = path + train_data_file; sim_data_file = path + sim_data_file; #ifdef TEST_ORIENT_GMP_ }catch(std::exception &e) { throw std::runtime_error(std::string("[loadParams]: ") + e.what()); } #endif }
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <map> typedef long long LL; typedef unsigned long long ULL; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; #define N 333333 int n, p[N], le[N], ri[N], pos[N]; int main() { freopen(".in", "r", stdin); freopen(".out", "w", stdout); scanf("%d", &n); for (int i = 0; i< n; i++) { scanf("%d", &p[i]); pos[p[i]] = i; if (i > 0 && p[i-1] + 1 == p[i]) { le[i] = le[i-1] + 1; } else le[i] = 1; } for (int i = n-1; i >= 0;i--) { if (i < n - 1 && p[i + 1] - 1 == p[i]) { ri[i] = ri[i+1] + 1; } else ri[i] = 1; } LL ans = 0; for (int i = 0; i < n; i++) { if (pos[p[i] + 1] > i) { if (pos[p[i] + 1] == i + 1) { ans += le[i]; } else ans += (LL)le[i] * ri[pos[p[i] + 1]]; } } cout << ans << endl; return 0; }
#pragma once #include <iterator> #include <vector> #include <algorithm> #include <functional> #include <assert.h> template <typename T> struct TreeNode { TreeNode(const T& data, TreeNode* left, TreeNode* right) : _data(data), _left(left), _right(right), _parent(nullptr) { } T _data; TreeNode* _left; TreeNode* _right; TreeNode* _parent; }; template<typename T> class BinaryTree { private: TreeNode<T>* _root; public: BinaryTree() : _root(nullptr) {} void MideOrderOneNode(TreeNode<T>* node, const std::function<void(T)>& fun) { if (node == nullptr) { return; } MideOrderOneNode(node->_left, fun); fun(node->_data); MideOrderOneNode(node->_right, fun); } void MideOrder(const std::function<void(T)>& fun) { MideOrderOneNode(_root, fun); } void PreOrderOneNode(TreeNode<T>* node, const std::function<void(T)>& fun) { if (node == nullptr) { return; } fun(node->_data); PreOrderOneNode(node->_left, fun); PreOrderOneNode(node->_right, fun); } void PreOrder(const std::function<void(T)>& fun) { PreOrderOneNode(_root, fun); } void BackOrderOneNode(TreeNode<T>* node, const std::function<void(T)>& fun) { if (node == nullptr) { return; } BackOrderOneNode(node->_left, fun); BackOrderOneNode(node->_right, fun); fun(node->_data); } void BackOrder(const std::function<void(T)>& fun) { BackOrderOneNode(_root, fun); } template<typename Iter> void Create(Iter begin, Iter end) { if (_root != nullptr) { return; } for (auto iter = begin; iter != end; iter++) { _root = Insert(_root, *iter); } } TreeNode<T>* Insert(TreeNode<T>* node, const T& data) { if (node == nullptr) { node = new TreeNode<T>(data, nullptr, nullptr); return node; } if (node->_data > data) { node->_left = Insert(node->_left, data); node->_left->_parent = node; } else if (node->_data < data) { node->_right = Insert(node->_right, data); node->_right->_parent = node; } return node; } TreeNode<T>* Find(TreeNode<T>* node, const T& data) { if (node == nullptr) { return node; } if (node->_data == data) { return node; } else if (node->_data > data) { return Find(node->_left, data); } else { return Find(node->_right, data); } return nullptr; } TreeNode<T>* Find(const T& data) { return Find(_root, data); } void RemoveAll(TreeNode<T>* node) { if (node == nullptr) { return; } RemoveAll(node->_left); RemoveAll(node->_right); delete node; } void Remove(const T& data) { TreeNode<T>* removeNode = Find(_root, data); if (removeNode == nullptr) { return; } /* ่ฏฅ่Š‚็‚นๆœ‰ไธคไธชๅญฉๅญ, ๆ‰พๅˆฐ่ฏฅ่Š‚็‚น็š„ๅŽ็ปง่Š‚็‚น(ๆฏ”่ฏฅ่Š‚็‚นๅคง็š„ๆœ€ๅฐๅ€ผ), ็”ฑไบŽๅŽ็ปง่Š‚็‚น่‚ฏๅฎšๆฒกๆœ‰ๅทฆๅญๆ ‘, ๅŽ้ข็š„ๅˆ ้™ค้€ป่พ‘็ปŸไธ€ๅค„็† */ if (removeNode->_left != nullptr && removeNode->_right != nullptr) { TreeNode<T>* nextNode = GetNext(removeNode); assert(nextNode != nullptr); removeNode->_data = nextNode->_data; removeNode = nextNode; } /* ๆ— ๅญฉๅญๅ’Œๅชๆœ‰1ไธชๅญฉๅญ่Š‚็‚น็š„ๆƒ…ๅ†ต, ็›ดๆŽฅๅˆ ้™ค่Š‚็‚น, ๅฆ‚ๆžœ่ฏฅ่Š‚็‚นๆ˜ฏๅทฆๅญฉๅญ, ็ˆถ่Š‚็‚น็š„ๅทฆๅญฉๅญ่ฎพ็ฝฎไธบ่ฏฅ่Š‚็‚น็š„ไธ€ไธชๅญฉๅญ, ๅฆ‚ๆžœ่ฏฅ่Š‚็‚นๆ˜ฏๅณๅญฉๅญ, ็ˆถ่Š‚็‚น็š„ๅณๅญฉๅญ่ฎพ็ฝฎไธบ่ฏฅ่Š‚็‚น็š„ไธ€ไธชๅญฉๅญ */ TreeNode<T>* child = removeNode->_left ? removeNode->_left : removeNode->_right; if (removeNode->_parent != nullptr) { if (removeNode->_parent->_left == removeNode) { removeNode->_parent->_left = child; } else if (removeNode->_parent->_right == removeNode) { removeNode->_parent->_right = child; } if (child != nullptr) { child->_parent = removeNode->_parent; } } else { _root = child; if (child != nullptr) { child->_parent = removeNode->_parent; } } delete removeNode; } //่Žทๅ–ๅŽ้ฉฑ่Š‚็‚น TreeNode<T>* GetNext(TreeNode<T>* node) { //ๅฆ‚ๆžœๆœ‰ๆœ‰ๅณ่Š‚็‚น TreeNode<T>* next; if (node->_right != nullptr) { next = node->_right; while (next && next->_left) { next = next->_left; } return next; } //ๅฆ‚ๆžœๆฒกๆœ‰ๅณ่Š‚็‚น ๅˆคๆ–ญ็ˆถ่Š‚็š„ๅทฆๅญฉๅญๆ˜ฏไธๆ˜ฏ่ฏฅ่Š‚็‚น while (node->_parent) { if (node->_parent->_left == node) { return node->_parent; } node = node->_parent; } return nullptr; } };
#include "firewarning.h" //ๅ‘็Žฐ็ซ่ญฆๆ—ถๅค„็† void dealfire(string firecity,string filename) { string firemes=firecity+"ๆœ‰็ซ่ญฆ,่ฏทๆŸฅ็œ‹ ็ซ่ญฆๆ–‡ไปถไธบ: "+filename; cout<<"\n "<<firemes<<endl; cout<<"ๆญฃๅœจๅ‘้€็Ÿญไฟก... "; if(sendmes(firemes,"13663880026,13698835392") ) cout<<"็Ÿญไฟกๅทฒๅ‘ๅ‡บ"<<endl; else cout<<"ๅ‘้€ๅคฑ่ดฅ"<<endl; tdquit=0;//ๅ…จๅฑ€char ๆŽงๅˆถ็บฟ็จ‹ๅ…ณ้—ญ CWinThread * hthread = AfxBeginThread(MyThreadProc,NULL); cout<<"\n ๆŒ‰ไปปๆ„้”ฎ็„ถๅŽๅ›ž่ฝฆๅณๅฏๅœๆญขๅฃฐ้Ÿณ... "; WaitForSingleObject(hMutex,INFINITE); cin>>tdquit; ReleaseMutex(hMutex); WaitForSingleObject(hthread->m_hThread,INFINITE);//็ญ‰ๅพ…็บฟ็จ‹็ป“ๆŸ } bool dealfile(CFtpFileFind & finder, CFtpConnection* pConnect, CTime & lastTime, CTime & nowTime) { LYname lynames; CString curdirname, warnline; CTime tempTime; if (finder.GetLastWriteTime(tempTime))//ๅฏไปฅ่ฎฟ้—ฎไฟฎๆ”นๆ—ถ้—ด { if(tempTime>lastTime) { //ๆ–ฐๆ–‡ไปถ ๅšๅค„็† if(tempTime>nowTime) nowTime=tempTime; char * filename = finder.GetFileName().GetBuffer(); cout<<"ๅ‘็Žฐๆ–ฐๆ–‡ไปถ"<<filename<<" ๆญฃๅœจๆŸฅ็œ‹ๆด›้˜ณๅœฐๅŒบๆ˜ฏๅฆๆœ‰็ซ่ญฆ......"<<endl; CInternetFile *ftpFile=pConnect->OpenFile(filename ); while(ftpFile->ReadString(warnline)) { for(size_t i=0;i<lynames.a.size();i++) { string firecity=lynames.a[i]; if(warnline.Find(firecity.c_str() ) > -1) { dealfire(firecity,filename); } } } ftpFile->Close(); } else { return false; } } else { return false; } return true;//ๅ‘็Žฐๆ–ฐๆ–‡ไปถๅนถๅšๅค„็† }
// // CryptClient.cpp for cpp_spider in sources/client // // Made by Benoit Hamon // Login <benoit.hamon@epitech.eu> // // Started on Sun Oct 08 17:50:33 2017 Benoit Hamon // Last update Sun Oct 29 12:09:47 2017 Benoit Hamon // #include <boost/filesystem.hpp> #include "ssl/Base64.hpp" #include "CryptClient.hpp" #include <iostream> void CryptClient::init() { if (!boost::filesystem::exists("./keys/aesiv.key") || !boost::filesystem::exists("./keys/aeskey.key")) { this->_rsaClient.genKey(); this->_rsaServer.setKeyFromFile(ICryptAlgo::KeyType::RSA_PUB, "./keys/serverPubKey.key"); this->_current = &this->_rsaServer; this->_currentType = "RSA"; boost::property_tree::ptree ptree; ptree.add("type", "PublicKey"); std::string key; this->_rsaClient.getKey(ICryptAlgo::KeyType::RSA_PUB, key); ptree.add("key", Base64::encrypt(key)); this->_moduleCommunication->send(ptree); } else { this->_aes.setKeyFromFile(ICryptAlgo::KeyType::AES_KEY, "./keys/aeskey.key"); this->_aes.setKeyFromFile(ICryptAlgo::KeyType::AES_IV, "./keys/aesiv.key"); this->_current = &this->_aes; this->_currentType = "AES"; } } void CryptClient::init(std::string const &aes_key, std::string const &aes_iv) { this->_aes.setKey(ICryptAlgo::KeyType::AES_KEY, Base64::decrypt(aes_key)); this->_aes.setKey(ICryptAlgo::KeyType::AES_IV, Base64::decrypt(aes_iv)); this->_aes.saveKeyInFile(ICryptAlgo::KeyType::AES_KEY, "./keys/aeskey.key"); this->_aes.saveKeyInFile(ICryptAlgo::KeyType::AES_IV, "./keys/aesiv.key"); this->_current = &this->_aes; this->_currentType = "AES"; } void CryptClient::addModuleCommunication(IModuleCommunication *moduleCommunication) { this->_moduleCommunication = moduleCommunication; } void CryptClient::encrypt(Packet &packet) { std::string data = packet.get<Packet::Field::DATA, std::string>(); std::cout << packet << std::endl; if (!data.empty()) { std::string res; this->_current->encrypt(data, res); packet.set(Packet::Field::DATA, Base64::encrypt(res)); packet.set(Packet::Field::CRYPT, this->_currentType); } } std::string CryptClient::encryptMethod(Packet &packet) { return this->_currentType; } void CryptClient::decrypt(Packet &packet) { std::string data = packet.get<Packet::Field::DATA, std::string>(); std::string crypt = packet.get<Packet::Field::CRYPT, std::string>(); std::string res; std::cout << packet << std::endl; if (!data.empty()) { if (crypt == "AES") this->_aes.decrypt(Base64::decrypt(data), res); else if (crypt == "RSA") { this->_rsaClient.decrypt(Base64::decrypt(data), res); } else res = data; packet.set(Packet::Field::DATA, res); } }
/* Copyright (c) 2018-2019, tevador <tevador@gmail.com> Copyright (c) 2019 SChernykh <https://github.com/SChernykh> 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 copyright holder 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 HOLDER 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 "crypto/randomx/soft_aes.h" alignas(64) uint32_t lutEnc0[256]; alignas(64) uint32_t lutEnc1[256]; alignas(64) uint32_t lutEnc2[256]; alignas(64) uint32_t lutEnc3[256]; alignas(64) uint32_t lutDec0[256]; alignas(64) uint32_t lutDec1[256]; alignas(64) uint32_t lutDec2[256]; alignas(64) uint32_t lutDec3[256]; static uint32_t mul_gf2(uint32_t b, uint32_t c) { uint32_t s = 0; for (uint32_t i = b, j = c, k = 1; (k < 0x100) && j; k <<= 1) { if (j & k) { s ^= i; j ^= k; } i <<= 1; if (i & 0x100) i ^= (1 << 8) | (1 << 4) | (1 << 3) | (1 << 1) | (1 << 0); } return s; } #define ROTL8(x,shift) ((uint8_t) ((x) << (shift)) | ((x) >> (8 - (shift)))) static struct SAESInitializer { SAESInitializer() { static uint8_t sbox[256]; static uint8_t sbox_reverse[256]; uint8_t p = 1, q = 1; do { p = p ^ (p << 1) ^ (p & 0x80 ? 0x1B : 0); q ^= q << 1; q ^= q << 2; q ^= q << 4; q ^= (q & 0x80) ? 0x09 : 0; const uint8_t value = q ^ ROTL8(q, 1) ^ ROTL8(q, 2) ^ ROTL8(q, 3) ^ ROTL8(q, 4) ^ 0x63; sbox[p] = value; sbox_reverse[value] = p; } while (p != 1); sbox[0] = 0x63; sbox_reverse[0x63] = 0; for (uint32_t i = 0; i < 0x100; ++i) { union { uint32_t w; uint8_t p[4]; }; uint32_t s = sbox[i]; p[0] = mul_gf2(s, 2); p[1] = s; p[2] = s; p[3] = mul_gf2(s, 3); lutEnc0[i] = w; w = (w << 8) | (w >> 24); lutEnc1[i] = w; w = (w << 8) | (w >> 24); lutEnc2[i] = w; w = (w << 8) | (w >> 24); lutEnc3[i] = w; s = sbox_reverse[i]; p[0] = mul_gf2(s, 0xe); p[1] = mul_gf2(s, 0x9); p[2] = mul_gf2(s, 0xd); p[3] = mul_gf2(s, 0xb); lutDec0[i] = w; w = (w << 8) | (w >> 24); lutDec1[i] = w; w = (w << 8) | (w >> 24); lutDec2[i] = w; w = (w << 8) | (w >> 24); lutDec3[i] = w; } } } aes_initializer;
#include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <queue> #include <unordered_set> #include <unordered_map> #include <stack> #include <cstdio> #include <cmath> #include <cstring> #include <complex> using namespace std; #define INT_MIN (1<<31) #define INT_MAX (~INT_MIN) #define UNREACHABLE (INT_MAX>>2) #define INF (1e300) #define eps (1e-9) #define MODULO 1000000007 ifstream fin("12879_input.txt"); #define cin fin #define MAXM 200001 typedef complex<double> T; typedef vector<T> VT; const double PI = 4*atan(1); void FFT(VT &a, bool invert) { size_t n = a.size(); for (int i=1, j=0; i<n; ++i) { int bit = n >> 1; for (; j>=bit; bit>>=1) j -= bit; j += bit; if (i < j) swap(a[i], a[j]); } for (int len=2; len<=n; len<<=1) { double ang = 2*PI/len * (invert ? -1 : 1); T wlen (cos(ang), sin(ang)); for (int i=0; i<n; i+=len) { T w(1); for (int j=0; j<len/2; ++j) { T u = a[i+j], v = a[i+j+len/2] * w; a[i+j] = u + v; a[i+j+len/2] = u - v; w *= wlen; } } } if(invert) for (int i=0; i<n; ++i) a[i] /= n; } // END int main() { int n, m; vector<int> tk(MAXM, 0); vector<int> td(MAXM, 0); int case_count = 0; while (cin >> n) { case_count++; int max_num = -1; for (int i = 0; i < n; i++) { cin >> tk[i]; max_num = max(max_num, tk[i]); } cin >> m; for (int i = 0; i < m; i++) { cin >> td[i]; max_num = max(max_num, td[i]); } int len = 1; while (len < max_num) len <<= 1; len <<= 1; VT k(len, T(0, 0)); VT h(len, T(0, 0)); vector<bool> d(len, false); k[0] = 1; for (int i = 0; i < n; i++) { k[tk[i]] = 1; } for (int i = 0; i < m; i++) { d[td[i]] = true; } FFT(k, false); for (int i = 0; i < k.size(); i++) h[i] = k[i] * k[i]; FFT(h, true); int result = 0; for (int i = 0; i < d.size(); i++) if (d[i] && h[i].real() > 0.5) result++; cout << result << endl; // if (case_count == 61) { // cout << n << endl; // for (int i = 0; i < n; i++) // cout << tk[i] << ' '; // cout << endl; // cout << m << endl; // for (int i = 0; i < m; i++) // cout << td[i] << ' '; // cout << endl; // for (int i = 0; i < len; i++) // if (h[i].real() < 0.5) // cout << 0 << endl; // else cout << h[i].real() << endl; // } } }
// // Created by manout on 17-3-28. // #include "common_use.h" /* * You are given an n * n 2D matrix representing an image * Rotate the image by 90 degrees (clockwise) * note: do it in place * ๅˆ†ๆž๏ผšใ€€ๅฏไปฅๆ นๆฎๅฎšไน‰้กบๆ—ถ้’ˆๆ“็บตๆฏไธชๅ…ƒ็ด ๆ—‹่ฝฌ๏ผ™๏ผๅบฆ๏ผŒไฝ†ๆ˜ฏๅคชๆ…ขไบ†๏ผŒๅฎž่ทต่ตทๆฅไนŸ้บป็ƒฆ * ๅฏไปฅๅ…ˆๆฒฟๅ‰ฏๅฏน่ง’็บฟ็ฟปๆŠ˜๏ผŒ็„ถๅŽๅ†ไธŠไธ‹็ฟปๆŠ˜ */ void rotate_image(vector<vector<int>> &matrix) { const int n = matrix.size(); //ๅ…ˆๆฒฟๅ‰ฏๅฏน่ง’็บฟ็ฟปๆŠ˜ for (int i = 0; i < n; ++i) { for (int j = 0; j < n - i; ++j) { swap(matrix[i][j], matrix[n - i - 1][n - j - 1]); } } //ๅ†ไธŠไธ‹็ฟปๆŠ˜ for (int i = 0; i < n / 2; ++i) { for (int j = 0; j < n; ++j) { swap(matrix[i][j], matrix[n - i - 1][j]); } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef QUICK_BINDER_DROP_DOWN_H #define QUICK_BINDER_DROP_DOWN_H #include "adjunct/quick_toolkit/bindings/QuickBinder.h" #include "modules/widgets/OpWidget.h" class QuickDropDown; namespace PrefUtils { class IntegerAccessor; } /** * A base class for (potentially) bidirectional bindings for the selection in * a QuickDropDown. * * @author Wojciech Dzierzanowski (wdzierzanowski) */ class QuickBinder::QuickDropDownSelectionBinding : public QuickBinder::Binding , public OpWidgetListener { public: // Binding virtual const QuickWidget* GetBoundWidget() const; // OpWidgetListener virtual void OnChange(OpWidget* widget, BOOL by_mouse = FALSE); protected: QuickDropDownSelectionBinding(); virtual ~QuickDropDownSelectionBinding(); OP_STATUS Init(QuickDropDown& drop_down); void ToWidget(INT32 new_value); virtual OP_STATUS FromWidget(INT32 new_value) = 0; private: QuickDropDown* m_drop_down; }; /** * A bidirectional property binding for the selection in a QuickDropDown. * * The user data of the selected item is bound to an integer OpProperty. * * @author Wojciech Dzierzanowski (wdzierzanowski) */ class QuickBinder::QuickDropDownSelectionPropertyBinding : public QuickDropDownSelectionBinding { public: QuickDropDownSelectionPropertyBinding(); virtual ~QuickDropDownSelectionPropertyBinding(); OP_STATUS Init(QuickDropDown& drop_down, OpProperty<INT32>& property); void OnPropertyChanged(INT32 new_value) { ToWidget(new_value); } protected: // QuickDropDownSelectionBinding virtual OP_STATUS FromWidget(INT32 new_value); private: OpProperty<INT32>* m_property; }; /** * A unidirectional preference binding for the selection in a QuickDropDown. * * The user data of the selected item is automatically written to an integer * preference. * * @author Wojciech Dzierzanowski (wdzierzanowski) */ class QuickBinder::QuickDropDownSelectionPreferenceBinding : public QuickDropDownSelectionBinding { public: QuickDropDownSelectionPreferenceBinding(); virtual ~QuickDropDownSelectionPreferenceBinding(); OP_STATUS Init(QuickDropDown& drop_down, PrefUtils::IntegerAccessor* accessor); protected: // QuickDropDownSelectionBinding virtual OP_STATUS FromWidget(INT32 new_value); private: PrefUtils::IntegerAccessor* m_accessor; }; #endif // QUICK_BINDER_DROP_DOWN_H
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> const long long LINF = (1e11); const int INF = (1<<30); #define EPS 1e-6 const int MOD = 10007; using namespace std; class Pillars { public: double getExpectedLength(int w, int x, int y) { int mn = min(x,y); int mx = max(x,y); vector<int> cnt(mx,0); vector<double> l(mx); cnt[0] = min(x,y); l[0] = w; double sqw = w*w; for (long long i=1; i<mx; ++i) { l[i] = sqrt(sqw+i*i); } for (int i=1; i<mn; ++i) { cnt[i] += (mn-i)*2; } for (int i=1; i<mx; ++i) { cnt[i] += min(min(mn,mx-mn), min(mx - i, i)); } double num = (double)x*y; double sum = 0; for (int i=0; i<mx; ++i) { sum += l[i]*(double)cnt[i]; } return sum/num; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 1; int Arg1 = 1; int Arg2 = 1; double Arg3 = 1.0; verify_case(0, Arg3, getExpectedLength(Arg0, Arg1, Arg2)); } void test_case_1() { int Arg0 = 1; int Arg1 = 5; int Arg2 = 1; double Arg3 = 2.387132965131785; verify_case(1, Arg3, getExpectedLength(Arg0, Arg1, Arg2)); } void test_case_2() { int Arg0 = 2; int Arg1 = 3; int Arg2 = 15; double Arg3 = 6.737191281760445; verify_case(2, Arg3, getExpectedLength(Arg0, Arg1, Arg2)); } void test_case_3() { int Arg0 = 1000; int Arg1 = 100000; int Arg2 = 100000; double Arg3 = 33381.38304701605; verify_case(3, Arg3, getExpectedLength(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { Pillars ___test; ___test.run_test(3); } // END CUT HERE
// // Created by manout on 17-3-22. // #include "common_use.h" /* * Given a triangle, find the minimum path sum from top to bottom. Each step you may * move to adjacent numbers on the below. * ๅˆ†ๆž๏ผš * ่ฎพ็Šถๆ€ไธบf(i, j)๏ผŒ่กจ็คบไปŽไฝ็ฝฎ(i, j)ๅ‡บๅ‘๏ผŒ่ทฏๅพ„็š„ๆœ€ๅฐๅ’Œ๏ผŒๅˆ™็Šถๆ€่ฝฌ็งปๆ–น็จ‹ไธบ๏ผš * f(i, j) = min{f(i + 1๏ผŒ j), f(i + 1, j + 1)} + (i, j) * ็ฎ—ๆณ•ๆ˜ฏไปŽไธ‰่ง’ๅž‹ๅบ•้ƒจๅ‘ไธŠ่ตฐไฝฟ็”จ้€’ๆŽจๅ…ฌๅผ๏ผŒๅ›žๆบฏๅˆฐไธ‰่ง’ๅฝข้กถ้ƒจๆ—ถไพฟๅทฒๆฑ‚ๅ‡บๆœ€ๅฐ่ทฏๅพ„ๅ’Œ */ //ๆ—ถ้—ดๅคๆ‚ๅบฆ O(n ^ 2) ็ฉบ้—ดๅคๆ‚ๅบฆO(1) int triangle(vector<vector<int>> &triangle) { for (int i = triangle.size() - 2; i >= 0; ++i) { //ๅ› ไธบ่ฟ™ๆ˜ฏไธชไธ‰่ง’ๅฝขๅ‘้‡๏ผŒๆ‰€ไปฅ็ฌฌ i ่กŒๆœ‰ i ไธชๅ…ƒ็ด  for (int j = 0; j < i; ++j) { triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]); } } return triangle[0][0]; }
#include "EdlProviderServerThread.h" using namespace edlprovider::soap; EdlProviderServerThread::EdlProviderServerThread() { }
#ifndef SPECEX_IMAGE_DATA_BASE__H #define SPECEX_IMAGE_DATA_BASE__H // Base image class for specex adapted from the HARP package developed // by Ted Kisner, see https://github.com/tskisner/HARP #include <specex_unbls.h> class image_data_base { public : image_data_base ( ); virtual ~image_data_base ( ); virtual size_t n_rows ( ) const; virtual size_t n_cols ( ) const; virtual void values ( unbls::vector_double & data ) const; virtual void inv_variance ( unbls::vector_double & invvar ) const; virtual void mask ( unbls::vector_mask & msk ) const; void values ( unbls::matrix_double & data ) const; void inv_variance ( unbls::matrix_double & invvar ) const; void mask ( unbls::matrix_mask & msk ) const; private : std::string type_; }; #endif
#include "GameObject.h" class Monster : public GameObject { public: void load(int x, int y, int width, int height, std::string texturID); void draw(SDL_Renderer* pRenderer); virtual void update(); void clean(); int g=0; };
#include <bits/stdc++.h> using namespace std; #define int long long #define PI 3.141592653589 #define MOD 1000000007 #define FAST_IO ios_base::sync_with_stdio(false), cin.tie(0) #define deb(x) cout<<"[ "<<#x<<" = "<<x<<"] " void solve(){ int ans=0; int n;cin>>n; for(int i=0;i<n;i++) { int temp;cin>>temp; if(temp!=2) { ans++; } } cout<<ans<<"\n"; } signed main(){ FAST_IO; int t=1; cin>>t; while(t--) solve(); return 0; }
#include<iostream> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<set> #include<map> #include<bits/stdc++.h> #include<queue> #define FOR0(i,n) for(i=0;i<n;i++) #define FOR(i,j,n) for(i=j;i<n;i++) #define FORD(i,j,k) for(i=j;i>=k;i--) inline long long MAX2(long long a, long long int b){return (a)>(b)?(a):(b);} inline long long MAX3(long long a, long long b,long long c){return (a)>(b)?((a)>(c)?(a):(c)):((b)>(c)?(b):(c));} inline long long MIN2(long long a, long long b){return (a)<(b)?(a):(b);} inline long long MIN3(long long a, long long b, long long c){return (a)<(b)?((a)<(c)?(a):(c)):((b)<(c)?(b):(c));} using namespace std; typedef pair<int,int> ii; typedef vector<int> vi; typedef vector< pair<int,int> > vii; typedef long long ll; vector < vi > graph(305); int color[305]; int dfs(int i) { int j; int ans=1; FOR0(j,graph[i].size()) { if(color[graph[i][j]]==-1) { color[graph[i][j]]=1-color[i]; ans=dfs(graph[i][j]); if(ans==0)break; } else if(color[graph[i][j]]!=1-color[i]) { ans=0;break; } } return ans; } int main() { int v,i,a,b,ans; while(1) { cin>>v; if(!v)break; FOR0(i,v+1) { color[i]=-1; graph[i].clear(); } while(1) { cin>>a>>b; if(!a)break; graph[a].push_back(b); graph[b].push_back(a); } color[1]=1; ans=dfs(1); if(ans==1) cout<<"YES\n"; else cout<<"NO\n"; } }
#include "child_merger.hpp" #include "prepare.hpp" #include "utils/log.hpp" #include "utils/assert.hpp" namespace nora { void child_merger::start() { ASSERT(st_); st_->async_call( [this] { ILOG << "merge child begin"; load_mgr(); }); } void child_merger::load_mgr() { ASSERT(st_->check_in_thread()); auto from_db_msg = make_shared<db::message>("get_child_mgr", db::message::req_type::rt_select, [this] (const auto& msg) { ASSERT(msg->results().size() == 1); from_child_mgr_ = make_unique<pd::child_mgr>(); from_child_mgr_->ParseFromString(boost::any_cast<string>(msg->results()[0][0])); if (to_child_mgr_) { this->merge_mgr(); } }); from_db_->push_message(from_db_msg, st_); auto to_db_msg = make_shared<db::message>("get_child_mgr", db::message::req_type::rt_select, [this] (const auto& msg) { ASSERT(msg->results().size() == 1); to_child_mgr_ = make_unique<pd::child_mgr>(); to_child_mgr_->ParseFromString(boost::any_cast<string>(msg->results()[0][0])); if (from_child_mgr_) { this->merge_mgr(); } }); to_db_->push_message(to_db_msg, st_); } void child_merger::merge_mgr() { ASSERT(st_->check_in_thread()); for (const auto& i : from_child_mgr_->owners().owners()) { *to_child_mgr_->mutable_owners()->add_owners() = i; } auto db_msg = make_shared<db::message>("save_child_mgr", db::message::req_type::rt_update, [this] (const auto& msg) { this->load_next_page(); }); string data_str; to_child_mgr_->SerializeToString(&data_str); db_msg->push_param(data_str); to_db_->push_message(db_msg, st_); } void child_merger::load_next_page() { ASSERT(st_->check_in_thread()); auto db_msg = make_shared<db::message>("get_children", db::message::req_type::rt_select, [this] (const auto& msg) { this->on_db_get_children_done(msg); }); db_msg->push_param(cur_page_ * page_size_); db_msg->push_param(page_size_); from_db_->push_message(db_msg, st_); cur_page_ += 1; } void child_merger::on_db_get_children_done(const shared_ptr<db::message>& msg) { ASSERT(st_->check_in_thread()); if (msg->results().empty()) { ILOG << "merge children done"; if (done_cb_) { done_cb_(); } return; } for (const auto& i : msg->results()) { ASSERT(i.size() == 2); adding_count_ += 1; auto db_msg = make_shared<db::message>("add_child", db::message::req_type::rt_insert, [this] (const auto& msg) { adding_count_ -= 1; if (adding_count_ == 0) { this->load_next_page(); } }); auto gid = boost::any_cast<uint64_t>(i[0]); ILOG << "process child " << gid; db_msg->push_param(gid); db_msg->push_param(boost::any_cast<string>(i[1])); to_db_->push_message(db_msg, st_); } } }
#include "DynamicObjectMagicRayLogicCalculator.h" void DynamicObjectMagicRayLogicCalculator::init(LevelModel* levelModel, DynamicObjectModel* dynamicObjectModel) { m_dynamicObjectModel = dynamicObjectModel; m_levelModel = levelModel; m_referencePosition = Vector4(0,0,0); } void DynamicObjectMagicRayLogicCalculator::computeLogic() { if(m_dynamicObjectModel->getState()!= DynamicObjectModel::DYNAMIC_OBJECT_STATE_VANISHING) { if(m_dynamicObjectModel->getState()== DynamicObjectModel::DYNAMIC_OBJECT_STATE_IMPACTING) { m_dynamicObjectModel->setAction(DynamicObjectModel::DYNAMIC_OBJECT_ACTION_IMPACT); return; } else if(rayHasTravelledTooFar()) { m_dynamicObjectModel->setAction(DynamicObjectModel::DYNAMIC_OBJECT_ACTION_VANISH); return; } else if(checkIfMagicRayCollidesWithWalls() || checkIfMagicRayCollidesWithEnemiesAndUpdateEnemies()) { m_dynamicObjectModel->setAction(DynamicObjectModel::DYNAMIC_OBJECT_ACTION_IMPACT); return; } else { //nothing } } } bool DynamicObjectMagicRayLogicCalculator::checkIfMagicRayCollidesWithWalls() { return (collidesOnLeft() || collidesOnRight() || collidesOnCeiling() ||collidesOnFloor()); } bool DynamicObjectMagicRayLogicCalculator::checkIfMagicRayCollidesWithEnemiesAndUpdateEnemies() { bool isColliding = false; std::map<int, AvatarModel*>::iterator enemiesIt = m_levelModel->getEnemyModels().begin(); while(enemiesIt != m_levelModel->getEnemyModels().end()) { if(collides(enemiesIt->second->getRect())) { if(!isColliding) isColliding = true; enemiesIt->second->setLifePoints(enemiesIt->second->getLifePoints()- m_dynamicObjectModel->getDamagePoints()); } enemiesIt++; } return isColliding; } bool DynamicObjectMagicRayLogicCalculator::rayHasTravelledTooFar() { if(m_referencePosition[0] == 0 && m_referencePosition[1] == 0) { //we just started flying set current position as reference position m_referencePosition[0] = m_dynamicObjectModel->getTerrainPosition()[0]; m_referencePosition[1] = m_dynamicObjectModel->getTerrainPosition()[1]; return false; } else { //TO_DO define the distance of 40 somewhere return ( std::sqrtf( (m_referencePosition[0] - m_dynamicObjectModel->getTerrainPosition()[0]) * (m_referencePosition[0] - m_dynamicObjectModel->getTerrainPosition()[0])+ (m_referencePosition[1] - m_dynamicObjectModel->getTerrainPosition()[1])* (m_referencePosition[1] - m_dynamicObjectModel->getTerrainPosition()[1]) ) > 40 ); } }
//=========================================================================== //! @file task_manager.cpp //! @brief ใ‚ฟใ‚นใ‚ฏ็ฎก็† //=========================================================================== //--------------------------------------------------------------------------- //! ๅˆๆœŸๅŒ– //--------------------------------------------------------------------------- bool TaskManager::initialize() { return true; } //--------------------------------------------------------------------------- //! ๆ›ดๆ–ฐ //--------------------------------------------------------------------------- void TaskManager::update() { // obๆ›ดๆ–ฐ for(auto& object : objects_) { if(object) { object->update(); } } } //--------------------------------------------------------------------------- //! ๆ็”ป //--------------------------------------------------------------------------- void TaskManager::render(RenderMode renderMode) { for(auto& object : objects_) { if(object) { object->render(renderMode); } } } //--------------------------------------------------------------------------- //! ่งฃๆ”พ ( !!ใ‚ทใƒผใƒณใฎ้–‹ๆ”พใ‚ˆใ‚Šๅ…ˆใซๅ‘ผใถใ“ใจ๏ผ! ) //--------------------------------------------------------------------------- void TaskManager::cleanup() { for(auto& object : objects_) { if(object) { object->cleanup(); } } objects_.clear(); } //--------------------------------------------------------------------------- //! ่งฃๆ”พ(ImGuiใงใƒชใ‚ปใƒƒใƒˆใƒœใ‚ฟใƒณๆŠผใ•ใ‚ŒใŸใจใ) //--------------------------------------------------------------------------- void TaskManager::resetButtonCleanup() { std::vector<ObjectBaseModel*> tmp; for(auto& object : objects_) { if(object) { if(!object->isButtonReset()) { tmp.emplace_back(object.release()); continue; } object->cleanup(); } } objects_.clear(); for(auto& object : tmp) { object->initialize(); objects_.emplace_back(object); } } //--------------------------------------------------------------------------- //! ImGui //--------------------------------------------------------------------------- void TaskManager::showImGuiWindow() { // ImGui::Begin("Object"); if(ImGui::TreeNode("Models")) { s32 i = 0; for(auto& object : objects_) { if(!object->isImGui()) continue; std::string s = "Model [" + std::to_string(i) + "]"; if(ImGui::TreeNode(s.c_str())) { object->showImGuiWindow(); ImGui::TreePop(); } ++i; } // ่ฟฝๅŠ  if(ImGui::Button("Add")) { if(objects_.size() < MODEL_MAX_COUNT) { std::unique_ptr<ObjectBaseModel> object(new ObjectBaseModel()); object->initialize("shape/box.fbx", +1.0f); object->setPosition({ +0.0f, +3.0f, +0.0f }); this->addObject(object.release()); } } if(ImGui::Button("AllRemove")) { this->resetButtonCleanup(); } ImGui::TreePop(); } ImGui::End(); } //--------------------------------------------------------------------------- //! ใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆ่ฟฝๅŠ  //--------------------------------------------------------------------------- void TaskManager::addObject(ObjectBaseModel* object) { objects_.emplace_back(object); } //--------------------------------------------------------------------------- //! ใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆ้…ๅˆ—ใ‚ตใ‚คใ‚บๅ–ๅพ— //--------------------------------------------------------------------------- u32 TaskManager::getObjectCount() const { return u32(objects_.size()); }
#ifndef DEFAULT_SWIPE_LISTENER_HPP #define DEFAULT_SWIPE_LISTENER_HPP #include <iostream> #include "BaseSwipeListener.hpp" /* * Prints Swipe events to standard output. * @author: Grzegorz Mirek */ class DefaultSwipeListener : public BaseSwipeListener { protected: void onLeftSwipe(const Leap::SwipeGesture& screenTap) override; void onRightSwipe(const Leap::SwipeGesture& screenTap) override; void onUpSwipe(const Leap::SwipeGesture& screenTap) override; void onDownSwipe(const Leap::SwipeGesture& screenTap) override; }; #endif
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. #include "core/pch.h" #ifdef M2_SUPPORT #include "modules/encodings/detector/charsetdetector.h" #include "modules/xmlutils/xmldocumentinfo.h" #include "xmlparser_tracker.h" #include "adjunct/m2/src/engine/engine.h" #include "adjunct/m2/src/util/misc.h" #include "adjunct/m2/src/util/str/strutil.h" #include "adjunct/desktop_util/adt/hashiterator.h" using namespace M2XMLUtils; //**************************************************************************** // // XMLAttributeQN // //**************************************************************************** XMLAttributeQN::XMLAttributeQN() {} XMLAttributeQN::~XMLAttributeQN() {} OP_STATUS XMLAttributeQN::Init ( const OpStringC& namespace_uri, const OpStringC& local_name, const OpStringC& qualified_name, const OpStringC& value ) { RETURN_IF_ERROR ( m_namespace_uri.Set ( namespace_uri ) ); RETURN_IF_ERROR ( m_local_name.Set ( local_name ) ); RETURN_IF_ERROR ( m_qualified_name.Set ( qualified_name ) ); RETURN_IF_ERROR ( m_value.Set ( value ) ); return OpStatus::OK; } //**************************************************************************** // // XMLElement // //**************************************************************************** XMLElement::XMLElement ( XMLParserTracker& owner ) : m_owner ( owner ) {} XMLElement::~XMLElement() {} OP_STATUS XMLElement::Init ( const OpStringC& namespace_uri, const OpStringC& local_name, const XMLToken::Attribute* attributes, UINT attributes_count ) { RETURN_IF_ERROR ( m_namespace_uri.Set ( namespace_uri ) ); RETURN_IF_ERROR ( m_local_name.Set ( local_name ) ); RETURN_IF_ERROR ( m_owner.QualifiedName ( m_qualified_name, m_namespace_uri, m_local_name ) ); // Loop the passed attributes and create new XMLAttributeQN objects // from them. for ( UINT index = 0; index < attributes_count; ++index ) { const XMLCompleteNameN& attrname = attributes[index].GetName(); OpString namespace_uri; OpString attribute_name; OpString attribute_value; RETURN_IF_ERROR ( namespace_uri.Set ( attrname.GetUri(), attrname.GetUriLength() ) ); RETURN_IF_ERROR ( attribute_name.Set ( attrname.GetLocalPart(), attrname.GetLocalPartLength() ) ); RETURN_IF_ERROR ( attribute_value.Set ( attributes[index].GetValue(), attributes[index].GetValueLength() ) ); if ( attrname.GetNsIndex() == NS_IDX_XMLNS ) { if ( !m_owner.HasNamespacePrefix ( attribute_value ) ) { // The user have not set a specific prefix for this uri, so we use // the prefix the xml creator desired. RETURN_IF_ERROR ( m_owner.AddNamespacePrefix ( attribute_name, attribute_value ) ); } } OpAutoPtr<XMLAttributeQN> attribute_qn ( OP_NEW(XMLAttributeQN, ()) ); if ( attribute_qn.get() == 0 ) return OpStatus::ERR_NO_MEMORY; OpString qualified_name; RETURN_IF_ERROR ( m_owner.QualifiedName ( qualified_name, namespace_uri, attribute_name ) ); RETURN_IF_ERROR ( attribute_qn->Init ( namespace_uri, attribute_name, qualified_name, attribute_value ) ); RETURN_IF_ERROR ( m_attributes.Add ( attribute_qn->QualifiedName().CStr(), attribute_qn.get() ) ); attribute_qn.release(); } // Check for xml:base attribute. if ( m_attributes.Contains ( UNI_L ( "xml:base" ) ) ) { XMLAttributeQN* attribute = 0; RETURN_IF_ERROR ( m_attributes.GetData ( UNI_L ( "xml:base" ), &attribute ) ); OP_ASSERT ( attribute != 0 ); const OpStringC& value = attribute->Value(); // Convert the value into an absolute uri. OpString base_uri; RETURN_IF_ERROR ( m_owner.BaseURI ( base_uri ) ); if ( base_uri.HasContent() ) RETURN_IF_ERROR ( OpMisc::RelativeURItoAbsoluteURI ( m_base_uri, value, base_uri ) ); else RETURN_IF_ERROR ( m_base_uri.Set ( value ) ); } return OpStatus::OK; } //**************************************************************************** // // XMLNamespacePrefix // //**************************************************************************** XMLNamespacePrefix::XMLNamespacePrefix() {} XMLNamespacePrefix::~XMLNamespacePrefix() {} OP_STATUS XMLNamespacePrefix::Init ( const OpStringC& prefix, const OpStringC& uri ) { RETURN_IF_ERROR ( m_prefix.Set ( prefix ) ); RETURN_IF_ERROR ( m_uri.Set ( uri ) ); return OpStatus::OK; } //**************************************************************************** // // XMLParserTracker // //**************************************************************************** BOOL XMLParserTracker::HasNamespacePrefix ( const OpStringC& uri ) const { XMLParserTracker* non_const_this = ( XMLParserTracker * ) ( this ); return non_const_this->m_namespace_prefixes.Contains ( uri.CStr() ); } OP_STATUS XMLParserTracker::AddNamespacePrefix ( const OpStringC& prefix, const OpStringC& uri ) { OP_ASSERT ( !HasNamespacePrefix ( uri ) ); OpAutoPtr<XMLNamespacePrefix> namespace_prefix ( OP_NEW(XMLNamespacePrefix, ()) ); if ( namespace_prefix.get() == 0 ) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR ( namespace_prefix->Init ( prefix, uri ) ); RETURN_IF_ERROR ( m_namespace_prefixes.Add ( namespace_prefix->URI().CStr(), namespace_prefix.get() ) ); namespace_prefix.release(); return OpStatus::OK; } OP_STATUS XMLParserTracker::NamespacePrefix ( OpString& prefix, const OpStringC& uri ) const { XMLParserTracker* non_const_this = ( XMLParserTracker * ) ( this ); XMLNamespacePrefix* namespace_prefix = 0; non_const_this->m_namespace_prefixes.GetData ( uri.CStr(), &namespace_prefix ); if ( namespace_prefix != 0 ) RETURN_IF_ERROR ( prefix.Set ( namespace_prefix->Prefix() ) ); return OpStatus::OK; } OP_STATUS XMLParserTracker::QualifiedName ( OpString& qualified_name, const OpStringC& namespace_uri, const OpStringC& local_name ) const { if ( namespace_uri.HasContent() ) { OpString prefix; RETURN_IF_ERROR ( NamespacePrefix ( prefix, namespace_uri ) ); if ( prefix.HasContent() ) { qualified_name.Empty(); RETURN_IF_ERROR ( qualified_name.AppendFormat ( UNI_L ( "%s:%s" ), prefix.CStr(), local_name.CStr() ) ); } } if ( qualified_name.IsEmpty() ) RETURN_IF_ERROR ( qualified_name.Set ( local_name ) ); return OpStatus::OK; } OP_STATUS XMLParserTracker::Parse ( const char* buffer, UINT buffer_length, BOOL is_final ) { OpString8 encoding; // Detect the encoding used if this is the first parse attempt. if ( m_xml_parser.get() == 0 ) { RETURN_IF_ERROR ( encoding.Set ( CharsetDetector::GetXMLEncoding ( buffer, buffer_length ) ) ); if ( encoding.IsEmpty() ) RETURN_IF_ERROR ( encoding.Set ( "utf-8" ) ); // Check if we have a BOM (Byte-order-mark) at the start of utf-8. This has no influence, // but is allowed at the start of a UTF-8 file if (!encoding.Compare("utf-8") && buffer_length >= 3 && !op_strncmp(buffer, "\xef\xbb\xbf", 3)) { buffer += 3; buffer_length -= 3; } } else RETURN_IF_ERROR ( Encoding ( encoding ) ); // Convert the data to utf16. // This is broken in so many ways, but try to work around most of it by // passing the buffer size directly (compare DSK-270822). OpStringC8 input_buffer(buffer); OpString utf16_buffer; RETURN_IF_ERROR ( MessageEngine::GetInstance()->GetInputConverter().ConvertToChar16 ( encoding, input_buffer, utf16_buffer, TRUE, FALSE, buffer_length ) ); // Parse it as utf16. RETURN_IF_ERROR ( Parse ( utf16_buffer.CStr(), utf16_buffer.Length(), is_final ) ); return OpStatus::OK; } OP_STATUS XMLParserTracker::Parse ( const uni_char *buffer, UINT buffer_length, BOOL is_final ) { if ( m_xml_parser.get() == 0 ) RETURN_IF_ERROR ( ResetParser() ); const OP_STATUS parse_status = m_xml_parser->Parse ( buffer, buffer_length, !is_final ); if ( OpStatus::IsError ( parse_status ) || is_final || m_xml_parser->IsFailed() ) { RETURN_IF_ERROR ( ResetParser() ); } RETURN_IF_ERROR ( parse_status ); return OpStatus::OK; } const OpStringC& XMLParserTracker::ParentName() const { OP_ASSERT ( HasParent() ); return m_element_stack.Get ( 1 )->QualifiedName(); } const OpStringC& XMLParserTracker::GrandparentName() const { OP_ASSERT ( HasGrandparent() ); return m_element_stack.Get ( 2 )->QualifiedName(); } BOOL XMLParserTracker::IsChildOf ( const OpStringC& parent_name ) const { BOOL is_child = FALSE; if ( HasParent() ) { if ( ParentName().Compare ( parent_name ) == 0 ) is_child = TRUE; } return is_child; } BOOL XMLParserTracker::IsGrandchildOf ( const OpStringC& grandparent_name ) const { BOOL is_grandchild = FALSE; if ( HasGrandparent() ) { if ( GrandparentName().Compare ( grandparent_name ) == 0 ) is_grandchild = TRUE; } return is_grandchild; } BOOL XMLParserTracker::IsDescendantOf ( const OpStringC& descendant_name ) const { BOOL is_descendant = FALSE; const UINT stack_size = m_element_stack.GetCount(); for ( UINT index = 1; index < stack_size; ++index ) { if ( m_element_stack.Get ( index )->QualifiedName().Compare ( descendant_name ) == 0 ) { is_descendant = TRUE; break; } } return is_descendant; } OP_STATUS XMLParserTracker::BaseURI ( OpString& base_uri, const OpStringC& document_uri ) const { for ( UINT index = 0, stack_size = m_element_stack.GetCount(); index < stack_size; ++index ) { XMLElement* current_element = m_element_stack.Get ( index ); OP_ASSERT ( current_element != 0 ); if ( current_element->HasBaseURI() ) { RETURN_IF_ERROR ( base_uri.Set ( current_element->BaseURI() ) ); break; } } if ( base_uri.IsEmpty() && document_uri.HasContent() ) RETURN_IF_ERROR ( base_uri.Set ( document_uri ) ); return OpStatus::OK; } OP_STATUS XMLParserTracker::Version ( OpString8& version ) const { if ( m_xml_parser.get() == 0 ) return OpStatus::ERR_NULL_POINTER; const XMLDocumentInformation& xmldocinfo = m_xml_parser->GetDocumentInformation(); if ( xmldocinfo.GetXMLDeclarationPresent() ) { if ( xmldocinfo.GetVersion() == XMLVERSION_1_0 ) RETURN_IF_ERROR ( version.Set ( "1.0" ) ); else if ( xmldocinfo.GetVersion() == XMLVERSION_1_1 ) RETURN_IF_ERROR ( version.Set ( "1.1" ) ); } if ( version.IsEmpty() ) RETURN_IF_ERROR ( version.Set ( "1.0" ) ); return OpStatus::OK; } OP_STATUS XMLParserTracker::Encoding ( OpString8& encoding ) const { if ( m_xml_parser.get() == 0 ) return OpStatus::ERR_NULL_POINTER; const XMLDocumentInformation& xmldocinfo = m_xml_parser->GetDocumentInformation(); if ( xmldocinfo.GetXMLDeclarationPresent() ) RETURN_IF_ERROR ( encoding.Set ( xmldocinfo.GetEncoding() ) ); if ( encoding.IsEmpty() ) RETURN_IF_ERROR ( encoding.Set ( "utf-8" ) ); return OpStatus::OK; } OP_STATUS XMLParserTracker::SetKeepTags ( const OpStringC& namespace_uri, const OpStringC& local_name, BOOL ignore_first_tag ) { OP_ASSERT ( !IsKeepingTags() ); if ( IsKeepingTags() ) return OpStatus::ERR; m_keep_tags = OP_NEW(KeepTags, ( ignore_first_tag )); if ( m_keep_tags.get() == 0 ) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR ( m_keep_tags->Init ( namespace_uri, local_name ) ); return OpStatus::OK; } XMLParserTracker::XMLParserTracker() : m_xml_parser ( 0 ) { m_content_string.SetExpansionPolicy ( TempBuffer::AGGRESSIVE ); m_content_string.SetCachedLengthPolicy ( TempBuffer::TRUSTED ); } XMLParserTracker::~XMLParserTracker() {} OP_STATUS XMLParserTracker::Init() { // The xml namespace does not need to be declared before use; thus we add // it to our internal namespace list here. RETURN_IF_ERROR ( AddNamespacePrefix ( UNI_L ( "xml" ), UNI_L ( "http://www.w3.org/XML/1998/namespace" ) ) ); return OpStatus::OK; } XMLTokenHandler::Result XMLParserTracker::HandleToken ( XMLToken &token ) { OP_STATUS status = OpStatus::OK; switch ( token.GetType() ) { case XMLToken::TYPE_CDATA : { status = HandleCDATAToken ( token ); break; } case XMLToken::TYPE_Text : { status = HandleTextToken ( token ); break; } case XMLToken::TYPE_STag : { status = HandleStartTagToken ( token ); break; } case XMLToken::TYPE_ETag : { status = HandleEndTagToken ( token ); break; } case XMLToken::TYPE_EmptyElemTag : { status = HandleStartTagToken ( token ); if ( OpStatus::IsSuccess ( status ) ) status = HandleEndTagToken ( token ); break; } } if ( OpStatus::IsMemoryError ( status ) ) return XMLTokenHandler::RESULT_OOM; else if ( OpStatus::IsError ( status ) ) return XMLTokenHandler::RESULT_ERROR; return XMLTokenHandler::RESULT_OK; } OP_STATUS XMLParserTracker::HandleStartTagToken ( const XMLToken& token ) { // Fetch information about the element. const XMLCompleteNameN &elemname = token.GetName(); OpString namespace_uri; OpString element_name; RETURN_IF_ERROR ( namespace_uri.Set ( elemname.GetUri(), elemname.GetUriLength() ) ); RETURN_IF_ERROR ( element_name.Set ( elemname.GetLocalPart(), elemname.GetLocalPartLength() ) ); // Process the element. OpAutoPtr<XMLElement> element ( OP_NEW(XMLElement, ( *this )) ); if ( element.get() == 0 ) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR ( element->Init ( namespace_uri, element_name, token.GetAttributes(), token.GetAttributesCount() ) ); if ( IsKeepingTags() ) { if ( m_keep_tags->KeepThisTag() ) { // Create a string with the attributes. OpString attribute_string; for (StringHashIterator<XMLAttributeQN> it(element->Attributes()); it; it++) { XMLAttributeQN* attribute = it.GetData(); OP_ASSERT ( attribute != 0 ); RETURN_IF_ERROR ( attribute_string.AppendFormat ( UNI_L ( "%s=\"%s\" " ), attribute->QualifiedName().CStr(), attribute->Value().CStr() ) ); } attribute_string.Strip(); if ( attribute_string.HasContent() ) { RETURN_IF_ERROR ( m_content_string.Append ( UNI_L ( "<" ) ) ); RETURN_IF_ERROR ( m_content_string.Append ( element_name.CStr() ) ); RETURN_IF_ERROR ( m_content_string.Append ( UNI_L ( " " ) ) ); RETURN_IF_ERROR ( m_content_string.Append ( attribute_string.CStr() ) ); RETURN_IF_ERROR ( m_content_string.Append ( UNI_L ( ">" ) ) ); } else { RETURN_IF_ERROR ( m_content_string.Append ( UNI_L ( "<" ) ) ); RETURN_IF_ERROR ( m_content_string.Append ( element_name.CStr() ) ); RETURN_IF_ERROR ( m_content_string.Append ( UNI_L ( ">" ) ) ); } } m_keep_tags->IncTagDepth(); } else { RETURN_IF_ERROR ( PushElementStack ( element.get() ) ); const OP_STATUS status = OnStartElement ( element->NamespaceURI(), element->LocalName(), element->QualifiedName(), element->Attributes() ); element.release(); m_content_string.Clear(); m_content_string.SetExpansionPolicy ( TempBuffer::AGGRESSIVE ); m_content_string.SetCachedLengthPolicy ( TempBuffer::TRUSTED ); RETURN_IF_ERROR ( status ); } return OpStatus::OK; } OP_STATUS XMLParserTracker::HandleEndTagToken ( const XMLToken& token ) { // Fetch information about the element. const XMLCompleteNameN &elemname = token.GetName(); OpString namespace_uri; OpString element_name; RETURN_IF_ERROR ( namespace_uri.Set ( elemname.GetUri(), elemname.GetUriLength() ) ); RETURN_IF_ERROR ( element_name.Set ( elemname.GetLocalPart(), elemname.GetLocalPartLength() ) ); // Process the element. if ( IsKeepingTags() ) { if ( m_keep_tags->IsEndTag ( namespace_uri, element_name ) ) { RETURN_IF_ERROR ( OnCharacterData ( m_content_string.GetStorage() ) ); m_keep_tags = 0; } else { m_keep_tags->DecTagDepth(); if ( m_keep_tags->KeepThisTag() ) { if ( token.GetType() == XMLToken::TYPE_EmptyElemTag ) { m_content_string.GetStorage() [m_content_string.Length() - 1] = 0x2f; // '/' RETURN_IF_ERROR ( m_content_string.Append ( 0x3e ) ); // '>' } else { RETURN_IF_ERROR ( m_content_string.Append ( UNI_L ( "</" ) ) ); RETURN_IF_ERROR ( m_content_string.Append ( element_name.CStr() ) ); RETURN_IF_ERROR ( m_content_string.Append ( UNI_L ( ">" ) ) ); } } } } if ( !IsKeepingTags() ) { ElementStackPopper stack_popper ( *this ); // Pop stack at the end. XMLElement* element = 0; RETURN_IF_ERROR ( TopElementStack ( element ) ); RETURN_IF_ERROR ( OnEndElement ( element->NamespaceURI(), element->LocalName(), element->QualifiedName() , element->Attributes()) ); } return OpStatus::OK; } OP_STATUS XMLParserTracker::HandleTextToken ( const XMLToken& token ) { uni_char* allocated_value = token.GetLiteralAllocatedValue(); if ( allocated_value == 0 ) return OpStatus::ERR_NO_MEMORY; ANCHOR_ARRAY ( uni_char, allocated_value ); if ( IsKeepingTags() && token.GetType() != XMLToken::TYPE_CDATA ) { // When we are keeping the tags we want content containing '&', '<' // and '>' to be escaped. // Walk through string, find occurrences of characters we want to replace uni_char* start_scan = allocated_value; uni_char* scanner = allocated_value; while ( *scanner ) { switch ( *scanner ) { case 0x26: // '&' RETURN_IF_ERROR ( m_content_string.Append ( start_scan, scanner - start_scan ) ); RETURN_IF_ERROR ( m_content_string.Append ( UNI_L ( "&amp;" ) ) ); start_scan = scanner + 1; break; case 0x3c: // '<' RETURN_IF_ERROR ( m_content_string.Append ( start_scan, scanner - start_scan ) ); RETURN_IF_ERROR ( m_content_string.Append ( UNI_L ( "&lt;" ) ) ); start_scan = scanner + 1; break; case 0x3e: // '>' RETURN_IF_ERROR ( m_content_string.Append ( start_scan, scanner - start_scan ) ); RETURN_IF_ERROR ( m_content_string.Append ( UNI_L ( "&gt;" ) ) ); start_scan = scanner + 1; break; } scanner++; } RETURN_IF_ERROR ( m_content_string.Append ( start_scan, scanner - start_scan ) ); } else { RETURN_IF_ERROR ( m_content_string.Append ( allocated_value ) ); RETURN_IF_ERROR ( OnCharacterData ( allocated_value ) ); } return OpStatus::OK; } OP_STATUS XMLParserTracker::HandleCDATAToken ( const XMLToken& token ) { if ( IsKeepingTags() ) { RETURN_IF_ERROR ( m_content_string.Append ( "<![CDATA[" ) ); RETURN_IF_ERROR ( OnCharacterData ( UNI_L ( "<![CDATA[" ) ) ); RETURN_IF_ERROR ( HandleTextToken ( token ) ); RETURN_IF_ERROR ( m_content_string.Append ( "]]>" ) ); RETURN_IF_ERROR ( OnCharacterData ( UNI_L ( "]]>" ) ) ); } else { RETURN_IF_ERROR ( OnStartCDATASection() ); RETURN_IF_ERROR ( HandleTextToken ( token ) ); RETURN_IF_ERROR ( OnEndCDATASection() ); } return OpStatus::OK; } OP_STATUS XMLParserTracker::ResetParser() { // Recreate / initialize the xml parser. if ( m_xml_parser.get() != 0 ) m_xml_parser = 0; { URL empty_url; XMLParser* new_xml_parser = 0; RETURN_IF_ERROR ( XMLParser::Make ( new_xml_parser, 0, g_main_message_handler, this, empty_url ) ); m_xml_parser = new_xml_parser; } XMLParser::Configuration configuration; configuration.load_external_entities = XMLParser::LOADEXTERNALENTITIES_NO; configuration.max_tokens_per_call = 4096; m_xml_parser->SetConfiguration ( configuration ); // Clear / reset the internal variables. m_element_stack.DeleteAll(); m_content_string.Clear(); m_content_string.SetExpansionPolicy ( TempBuffer::AGGRESSIVE ); m_content_string.SetCachedLengthPolicy ( TempBuffer::TRUSTED ); m_keep_tags = 0; return OpStatus::OK; } OP_STATUS XMLParserTracker::PushElementStack ( XMLElement* element ) { OP_ASSERT ( element != 0 ); RETURN_IF_ERROR ( m_element_stack.Insert ( 0, element ) ); return OpStatus::OK; } OP_STATUS XMLParserTracker::PopElementStack() { OP_ASSERT ( ElementStackHasContent() ); if ( !ElementStackHasContent() ) return OpStatus::ERR; m_element_stack.Delete ( 0, 1 ); return OpStatus::OK; } OP_STATUS XMLParserTracker::TopElementStack ( XMLElement*& element ) const { OP_ASSERT ( ElementStackHasContent() ); if ( !ElementStackHasContent() ) return OpStatus::ERR; element = m_element_stack.Get ( 0 ); return OpStatus::OK; } //**************************************************************************** // // XMLParserTracker::KeepTags // //**************************************************************************** XMLParserTracker::KeepTags::KeepTags ( BOOL ignore_first_tag ) : m_tag_depth ( 0 ), m_ignore_first_tag ( ignore_first_tag ) {} OP_STATUS XMLParserTracker::KeepTags::Init ( const OpStringC& namespace_uri, const OpStringC& local_name ) { RETURN_IF_ERROR ( m_namespace_uri.Set ( namespace_uri ) ); RETURN_IF_ERROR ( m_local_name.Set ( local_name ) ); return OpStatus::OK; } BOOL XMLParserTracker::KeepTags::IsEndTag ( const OpStringC& namespace_uri, const OpStringC& local_name ) const { return ( m_tag_depth == 0 ) && ( m_namespace_uri == namespace_uri ) && ( m_local_name == local_name ); } UINT XMLParserTracker::KeepTags::DecTagDepth() { OP_ASSERT ( m_tag_depth > 0 ); if ( m_tag_depth > 0 ) --m_tag_depth; return m_tag_depth; } #endif //M2_SUPPORT
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <sstream> #include <string.h> #include <queue> #include <vector> #include <set> #include <map> typedef long long LL; typedef unsigned long long ULL; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int field[3][3], myId, px[9] = {2, 0, 0, 2, 2, 0, 1, 1, 1}, py[9] = {2, 0, 2, 0, 1, 1, 0, 2, 1}; bool Check(int id) { for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (field[i][j] != id) break; if (j == 2) return true; } } for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (field[j][i] != id) break; if (j == 2) return true; } } if (field[0][0] == id && field[1][1] == id && field[2][2] == id) return true; if (field[2][0] == id && field[1][1] == id && field[0][2] == id) return true; return false; } int Win(int id) { if (Check(id)) return 1; if (Check(3 - id)) return -1; int maxWin = -1, fr = 0; for (int i = 0; i < 9; ++i) { if (field[px[i]][py[i]] != -1) continue; ++fr; field[px[i]][py[i]] = 3 - id; maxWin = max(maxWin, Win(3 - id)); field[px[i]][py[i]] = -1; } if (fr == 0) return 0; return -maxWin; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); cin >> myId; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { cin >> field[i][j]; } } for (int i = 0; i < 9; ++i) { if (px[i] < 0 || py[i] < 0 || px[i] > 2 || py[i] > 2) throw 1; for (int j = i + 1; j < 9; ++j) { if (px[i] == px[j] && py[i] == py[j]) { throw 2; } } } for (int it = 1; ; --it) for (int i = 0; i < 9; ++i) { if (field[px[i]][py[i]] != -1) continue; field[px[i]][py[i]] = myId; if (Win(myId) == it) { cout << px[i] << " " << py[i] << endl; return 0; } field[px[i]][py[i]] = -1; } throw 3; return 0; }
#include "GamePch.h" #include "AI_LaserBurnStationary.h" #include "Laser.h" #include "Common.h" void AI_LaserBurnStationary::LoadFromXML( tinyxml2::XMLElement* data ) { m_Duration = 20.0f; data->QueryFloatAttribute( "duration", &m_Duration ); } void AI_LaserBurnStationary::Init( Hourglass::Entity * entity ) { hg::Entity* laserEnt = hg::Entity::FindByName( SID( LaserEmissionPoint ) ); laserEnt->GetComponent<Laser>()->SetEnabled( true ); laserEnt->GetComponent<hg::MeshRenderer>()->SetEnabled( true ); m_Laser = laserEnt->GetTransform(); m_Timer = 0.0f; const float max_length = 100.0f; Vector3 startPos = m_Laser->GetWorldPosition(); hg::Ray ray( startPos, m_Laser->Forward(), max_length ); Vector3 hitPos; if (hg::g_Physics.RayCast( ray, nullptr, &hitPos, nullptr, COLLISION_BULLET_HIT_MASK )) { m_FxLaserBurn = hg::Entity::Assemble( SID(FxLaserBurn) ); m_FxLaserBurn->GetTransform()->SetPosition(hitPos); } } Hourglass::IBehavior::Result AI_LaserBurnStationary::Update( Hourglass::Entity* entity ) { m_Timer += hg::g_Time.Delta(); if (m_Timer >= m_Duration) { m_FxLaserBurn->Destroy(); return IBehavior::kSUCCESS; } else return IBehavior::kRUNNING; } Hourglass::IBehavior* AI_LaserBurnStationary::MakeCopy() const { AI_LaserBurnStationary* copy = (AI_LaserBurnStationary*)IBehavior::Create( SID(AI_LaserBurnStationary) ); copy->m_Duration = m_Duration; return copy; }
#include "stdafx.h" #include "DateToken.h" DateToken::DateToken() : QsoTokenType("date") { } DateToken::~DateToken() { } bool DateToken::Parse(const string& token) { m_token = token; return true; }
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/icon.Qrcode.g.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Animations.IResize.h> #include <Fuse.Binding.h> #include <Fuse.Controls.Image.h> #include <Fuse.IActualPlacement.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.ITemplateSource.h> #include <Fuse.Node.h> #include <Fuse.Scripting.IScriptObject.h> #include <Fuse.Triggers.Actions.ICollapse.h> #include <Fuse.Triggers.Actions.IHide.h> #include <Fuse.Triggers.Actions.IShow.h> #include <Fuse.Visual.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.UX.IPropertyListener.h> namespace g{namespace icon{struct Qrcode;}} namespace g{ namespace icon{ // public partial sealed class Qrcode :4 // { ::g::Fuse::Controls::Control_type* Qrcode_typeof(); void Qrcode__ctor_7_fn(Qrcode* __this); void Qrcode__InitializeUX_fn(Qrcode* __this); void Qrcode__New4_fn(Qrcode** __retval); struct Qrcode : ::g::Fuse::Controls::Image { void ctor_7(); void InitializeUX(); static Qrcode* New4(); }; // } }} // ::g::icon
/*********************************************************************/ /* File: myFESpace.cpp */ /* Author: Joachim Schoeberl */ /* Date: 26. Apr. 2009 */ /*********************************************************************/ /* My own FESpace for linear and quadratic triangular elements. A fe-space provides the connection between the local reference element, and the global mesh. */ #include <comp.hpp> // provides FESpace, ... #include <h1lofe.hpp> #include <regex> #include <python_ngstd.hpp> #include "myElement.hpp" #include "myFESpace.hpp" namespace ngcomp { MyFESpace ::MyFESpace(shared_ptr<MeshAccess> ama, const Flags &flags) : FESpace(ama, flags) { cout << "Constructor of MyFESpace" << endl; cout << "Flags = " << flags << endl; order = flags.GetNumFlag("order", 1); cout << "You have chosen element order " << order << endl; // needed for symbolic integrators and to draw solution evaluator[VOL] = make_shared<T_DifferentialOperator<DiffOpId<2>>>(); flux_evaluator[VOL] = make_shared<T_DifferentialOperator<DiffOpGradient<2>>>(); evaluator[BND] = make_shared<T_DifferentialOperator<DiffOpIdBoundary<2>>>(); // (still) needed to draw solution integrator[VOL] = GetIntegrators().CreateBFI("mass", ma->GetDimension(), make_shared<ConstantCoefficientFunction>(1)); } DocInfo MyFESpace ::GetDocu() { auto docu = FESpace::GetDocu(); docu.Arg("order") = "int = 1\n" "order of basis functions"; return docu; } void MyFESpace ::Update(LocalHeap &lh) { // some global update: cout << "Update MyFESpace, #vert = " << ma->GetNV() << ", #edge = " << ma->GetNEdges() << endl; // number of vertices nvert = ma->GetNV(); // number of dofs: ndof = nvert; switch (order) { case 1: ndof = ma->GetNV(); break; case 2: ndof = ma->GetNV() + ma->GetNEdges(); break; case 3: ndof = ma->GetNV() + 2 * ma->GetNEdges() + ma->GetNE(); break; } } void MyFESpace ::GetDofNrs(ElementId ei, Array<DofId> &dnums) const { // returns dofs of element ei // may be a volume triangle or boundary segment dnums.SetSize(0); auto element = ma->GetElement(ei); switch (order) { case 1: for (auto vertex : element.Vertices()) { dnums.Append(vertex); } break; case 2: for (auto vertex : element.Vertices()) { dnums.Append(vertex); } for (auto edge : element.Edges()) { dnums.Append(ma->GetNV() + edge); } break; case 3: for (auto vertex : element.Vertices()) { dnums.Append(vertex); } Array<int> edgeElements; for (auto edge : element.Edges()) { ma->GetEdgeElements(edge, edgeElements); if (edgeElements.Size() == 1 || ei.Nr() <= edgeElements[0] && ei.Nr() <= edgeElements[1]) { dnums.Append(ma->GetNV() + 2 * edge); dnums.Append(ma->GetNV() + 2 * edge + 1); } else { dnums.Append(ma->GetNV() + 2 * edge + 1); dnums.Append(ma->GetNV() + 2 * edge); } } if (ei.IsVolume()) { dnums.Append(ma->GetNV() + ma->GetNEdges() * 2 + ei.Nr()); } break; } } FiniteElement &MyFESpace ::GetFE(ElementId ei, Allocator &alloc) const { if (ei.IsVolume()) { switch (order) { case 1: switch (ma->GetElVertices(ei).Size()) { case 3: return *new (alloc) MyLinearTrig; case 4: return *new (alloc) BilinearQuadElement; } break; case 2: return *new (alloc) MyQuadraticTrig; case 3: return *new (alloc) ThirdOrderTriangleElement; } } else { switch (order) { case 1: return *new (alloc) FE_Segm1; case 2: return *new (alloc) FE_Segm2; case 3: return *new (alloc) ThirdOrderLineSegment; } } throw "could not determine a finite element"; } /* register fe-spaces Object of type MyFESpace can be defined in the pde-file via "define fespace v -type=myfespace" */ static RegisterFESpace<MyFESpace> initifes("myfespace"); } // namespace ngcomp void ExportMyFESpace(py::module m) { using namespace ngcomp; /* We just export the class here and use the FESpace constructor to create our space. This has the advantage, that we do not need to specify all the flags to parse (like dirichlet, definedon,...), but we can still append new functions only for that space. */ auto docu = MyFESpace::GetDocu(); auto myfes = py::class_<MyFESpace, shared_ptr<MyFESpace>, FESpace>(m, "MyFESpace", (docu.short_docu + "\n\n" + docu.long_docu).c_str()); myfes /* this is optional, if you don't write an init function, you can create your fespace with FESpace("myfes",mesh,...), but it's nicer to write MyFESpace(mesh,...) ;) */ .def(py::init([myfes](shared_ptr<MeshAccess> ma, py::kwargs kwa) { py::list info; info.append(ma); auto flags = CreateFlagsFromKwArgs(myfes, kwa, info); auto fes = make_shared<MyFESpace>(ma, flags); LocalHeap glh(100000000, "init-fes-lh"); fes->Update(glh); fes->FinalizeUpdate(glh); return fes; }), py::arg("mesh")) /* this is, so that we do not get an 'undocumented flag' warning */ .def_static("__flags_doc__", [docu]() { auto doc = py::cast<py::dict>(py::module::import("ngsolve").attr("FESpace").attr("__flags_doc__")()); for (auto &flagdoc : docu.arguments) doc[get<0>(flagdoc).c_str()] = get<1>(flagdoc); return doc; }) .def("GetNVert", &MyFESpace::GetNVert); }
#include "WinWrappers/WinWrappers.h" #include "EverydayTools/Array/ArrayView.h" #include "EverydayTools/Array/ArrayViewVector.h" #include "EverydayTools/UnusedVar.h" #include "EverydayTools/Exception/CallAndRethrow.h" #include "EverydayTools/Exception/ThrowIfFailed.h" #include "EverydayTools/Exception/CheckedCast.h" #include <algorithm> #include <string_view> #include <string> #include <sstream> #include <vector> #include <thread> #include <future> #include "Keng/Core/IApplication.h" #include "Keng/Core/CreateApplication.h" namespace { template<typename T> class LocalFreeDeleter { public: void operator()(T* ptr) { if (ptr) { LocalFree(ptr); } } }; std::string ConvertString(const std::wstring& wide) { std::string result; result.reserve(wide.size()); std::transform(wide.begin(), wide.end(), std::back_inserter(result), edt::CheckedCast<char, wchar_t>); return result; } template<typename T> using WinLocalPtr = std::unique_ptr<T, LocalFreeDeleter<T>>; int main() { try { using WA = WinAPI<wchar_t>; return CallAndRethrowM + [&] { auto cmdLine = GetCommandLineW(); int nArguments; WinLocalPtr<LPWSTR> argumentsPtr(CommandLineToArgvW(cmdLine, &nArguments)); edt::DenseArrayView<LPWSTR> arguments(argumentsPtr.get(), nArguments); std::wstring libraryName; if (nArguments > 1) { libraryName = arguments[1]; } else { const char* filters[]{ "DLL", "*.dll", nullptr, nullptr }; wchar_t szFile[MAX_PATH]; // open a file name OpenFileName<wchar_t> ofn; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; ofn.lpstrFile = szFile; ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = sizeof(szFile); ofn.lpstrFilter = L"DLL\0*.dll\0"; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; edt::ThrowIfFailed(WA::GetOpenFileName_(&ofn), "You have to select library to load!"); libraryName = ofn.lpstrFile; } auto module = WA::LoadLibrary_(L"KengCore"); edt::ThrowIfFailed(module != nullptr, L"Failed to load library!"); auto app = keng::core::CreateApplication(module); std::string modulesToLoad[1]; modulesToLoad[0] = ConvertString(libraryName); std::vector<const char*> rawNames; for (auto& str : modulesToLoad) { rawNames.push_back(str.data()); } keng::core::ApplicationStartupParameters params; params.modulesToLoad = edt::MakeArrayView(rawNames); app->Initialize(params); app->Run(); return 0; }; } catch (const std::exception& ex) { using WA = WinAPI<char>; std::stringstream sstream; PrintException(sstream, ex); WA::MessageBox_(nullptr, sstream.str().c_str(), "Error", MB_ICONERROR); } catch (...) { using WA = WinAPI<char>; WA::MessageBox_(nullptr, "Unexpected error!", "Error", MB_ICONERROR); } return 1; } } INT WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow) { UnusedVar(hInstance, hPrevInstance, lpCmdLine, nCmdShow); //std::future<int> a = std::async(std::launch::async, main); //std::future<int> b = std::async(std::launch::async, main); // //auto result_a = a.get(); //auto result_b = b.get(); // //return result_a + result_b; return main(); }
#ifndef TTDTable_H #define TTDTable_H /* Class designed to store TTD lookup table and perform lookup up conversion to distance given time (and slope) */ #include <iostream> #include "TMath.h" using namespace std; class TTDTable { public: TTDTable(std::vector<Double_t> Table, double LowVal, int nbins, double *apars, double *aparsext): LTable(Table), Low(LowVal), NBins(nbins), par(apars), parExt(aparsext), BExtPars(true) {}; TTDTable(std::vector<Double_t> Table, double LowVal, int nbins): LTable(Table), Low(LowVal), NBins(nbins), par(NULL), parExt(NULL) {}; double Convert(double dtime); double ConvertAngleCorr(double dtime, double tantheta); void PrintParams(); private: std::vector<double> LTable; // lookup table const double * par; // parameters for angle correction const double invTanTheta0 = 1.4; // central value of inverse tan theta (inverse of slope) const double Low; // value of lowest time const int NBins; // number of entries in Lookup table const double bin_res = 0.5e-9; const double * parExt; // parameters for times outside normal range Bool_t BExtPars = false; // bool to keep track if ext parametershave been intialised }; #endif
//leftover.cpp--overloading the left() function #include<iostream> unsigned long left(unsigned long num,unsigned ct); char * left(const char * str,int n=1); int main() { using namespace std; char * trip="Hawaii!!";//test value unsigned long n=12345678;//test value int i; char * temp; for(i=1;i<10;i++) { cout<<left(n,i)<<endl; temp=left(trip,i); cout<<temp<<endl; delete [] temp;//point to temporary storage } return 0; } //this function returns the first ct digits of the number num. unsigned long left(unsigned long num,unsigned ct) { unsigned digits=1; unsigned long n=num; if(ct==0||num==0) return 0;//return 0 if no digits while(n/=10) digits++; if(digits>ct) { ct=digits-ct;//้œ€่ฆๅˆ ้™ค็š„ไฝๆ•ฐ,ๅณๆ€ปไฝๆ•ฐๅ‡ๅŽป่ฆ่Žทๅพ—็š„ไฝๆ•ฐ while(ct--) num/=10; return num;//return left ct digits } else //if ct>=number of digits return num;//return the whole number } //this function returns a pointer to a new string //consisting of the first n characters in the str string char * left(const char * str,int n) { if(n<0) n=0; char *p=new char[n+1]; int i; for(i=0;i<n&&str[i];i++) p[i]=str[i];//copy characters while(i<=n) p[i++]='\0';//set rest of string to '\0' return p; }
#ifndef VULKANLAB_MESH_COMPONENT_H #define VULKANLAB_MESH_COMPONENT_H #include "../ECS.h" ECS_TYPE_IMPLEMENTATION; using namespace ECS; struct MeshComponent { ECS_DECLARE_TYPE; MeshComponent() {} Mesh* mesh; }; ECS_DEFINE_TYPE(MeshComponent); #endif //VULKANLAB_MESH_COMPONENT_H
#include <iostream> #include <string> #include "cmsys/FStream.hxx" #ifdef _WIN32 # include "cmsys/ConsoleBuf.hxx" #endif #ifdef _WIN32 void setEncoding(cmsys::ConsoleBuf::Manager& buf, UINT codepage) { cmsys::ConsoleBuf* cb = buf.GetConsoleBuf(); if (cb) { cb->input_pipe_codepage = codepage; cb->output_pipe_codepage = codepage; cb->input_file_codepage = codepage; cb->output_file_codepage = codepage; cb->activateCodepageChange(); } } #endif int main(int argc, char* argv[]) { #ifdef _WIN32 cmsys::ConsoleBuf::Manager consoleOut(std::cout); #endif if (argc <= 2) { std::cout << "Usage: testEncoding <encoding> <file>" << std::endl; return 1; } const std::string encoding(argv[1]); #ifdef _WIN32 if ((encoding == "UTF8") || (encoding == "UTF-8")) { setEncoding(consoleOut, CP_UTF8); } else if (encoding == "ANSI") { setEncoding(consoleOut, CP_ACP); } else if (encoding == "OEM") { setEncoding(consoleOut, CP_OEMCP); } // else AUTO #endif cmsys::ifstream file(argv[2]); if (!file.is_open()) { std::cout << "Failed to open file: " << argv[2] << std::endl; return 2; } std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); std::cout << text; return 0; }
#include "StdAfx.h" #include "MapManager.h" MapManager::MapManager(void) { } MapManager::~MapManager(void) { } MapManager* MapManager::getInstance(void) { static MapManager instance; return &instance; } void MapManager::startUp(void) { log = LogManager::getInstance(); activeMaps = new LinkedList<Map>(); registeredForInput = new LinkedList<Map>(); allMaps = new LinkedList<Map>(); log->writeLog("MapManager: Started Up"); } void MapManager::shutDown(void) { allMaps->freeAll(); log->writeLog("MapManager: Shut Down"); } void MapManager::activateMap(Map* in) { activeMaps->insert(in); } void MapManager::deactivateMap(Map* in) { activeMaps->remove(in); } void MapManager::registerForInput(Map* in) { registeredForInput->insert(in); } void MapManager::deregFromInput(Map* in) { registeredForInput->remove(in); } void MapManager::introduceMap(Map* in) { allMaps->insert(in); } void MapManager::terminateMap(Map* in) { allMaps->remove(in); } void MapManager::sendInput(char in) { forEach(Map, ptr, registeredForInput->getFirst()) { ptr->first->takeInput(in); } } void MapManager::advanceActiveMaps(void) { forEach(Map, ptr, activeMaps->getFirst()) { ptr->first->step(); } }
/** * An Mirf example which copies back the data it recives. * * Pins: * Hardware SPI: * MISO -> 12 * MOSI -> 11 * SCK -> 13 * * Configurable: * CE -> 8 * CSN -> 7 * */ #include <SPI.h> #include <Mirf.h> #include <nRF24L01.h> #include <MirfHardwareSpiDriver.h> int flip =5; int flop =6; int mailStat = 0; void setup(){ Serial.begin(9600); pinMode(flip,OUTPUT); // pin A declared as OUTPUT pinMode(flop,OUTPUT); // pin B declared as OUTPUT /* * Set the SPI Driver. */ Mirf.spi = &MirfHardwareSpi; /* * Setup pins / SPI. */ Mirf.init(); /* * Configure reciving address. */ Mirf.setRADDR((byte *)"serv1"); /* * Set the payload length to sizeof(unsigned long) the * return type of millis(). * * NB: payload on client and server must be the same. */ Mirf.payload = sizeof(unsigned long); /* * Write channel and payload config then power up reciver. */ Mirf.config(); Serial.println("Listening..."); } void loop(){ if(mailStat ==1){ digitalWrite(flip,HIGH); // dot direction one pin switched to HIGH (+5V) digitalWrite(flop,LOW); // dot direction two pin switched to LOW (GND) delay(10); digitalWrite(flip,LOW); // dot direction one pin switched to LOW (GND) delay(10); }else if(mailStat ==0){ digitalWrite(flip,LOW); // dot direction one pin switched to HIGH (GND) digitalWrite(flop,HIGH); // dot direction two pin switched to LOW (+5V) delay(10); digitalWrite(flop,LOW); // dot direction two pin switched to LOW (GND) delay(10); } while(!Mirf.dataReady()){ } Mirf.getData((byte *) &mailStat); Serial.println("MailStat: "); Serial.println(mailStat); delay(10); }
// Created on: 1996-02-28 // Created by: Philippe MANGIN // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _math_NewtonMinimum_HeaderFile #define _math_NewtonMinimum_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Precision.hxx> #include <math_Status.hxx> #include <math_Vector.hxx> #include <math_Matrix.hxx> #include <Standard_Integer.hxx> #include <Standard_OStream.hxx> class math_MultipleVarFunctionWithHessian; class math_NewtonMinimum { public: DEFINE_STANDARD_ALLOC //! The tolerance required on the solution is given by Tolerance. //! Iteration are stopped if (!WithSingularity) and H(F(Xi)) is not definite //! positive (if the smaller eigenvalue of H < Convexity) //! or IsConverged() returns True for 2 successives Iterations. //! Warning: This constructor does not perform computation. Standard_EXPORT math_NewtonMinimum(const math_MultipleVarFunctionWithHessian& theFunction, const Standard_Real theTolerance = Precision::Confusion(), const Standard_Integer theNbIterations = 40, const Standard_Real theConvexity = 1.0e-6, const Standard_Boolean theWithSingularity = Standard_True); //! Search the solution. Standard_EXPORT void Perform (math_MultipleVarFunctionWithHessian& theFunction, const math_Vector& theStartingPoint); //! Destructor Standard_EXPORT virtual ~math_NewtonMinimum(); //! This method is called at the end of each iteration to check the convergence: //! || Xi+1 - Xi || < Tolerance or || F(Xi+1) - F(Xi)|| < Tolerance * || F(Xi) || //! It can be redefined in a sub-class to implement a specific test. virtual Standard_Boolean IsConverged() const; //! Tests if an error has occurred. Standard_Boolean IsDone() const; //! Tests if the Function is convexe during optimization. Standard_Boolean IsConvex() const; //! returns the location vector of the minimum. //! Exception NotDone is raised if an error has occurred. const math_Vector& Location() const; //! outputs the location vector of the minimum in Loc. //! Exception NotDone is raised if an error has occurred. //! Exception DimensionError is raised if the range of Loc is not //! equal to the range of the StartingPoint. void Location (math_Vector& Loc) const; //! Set boundaries. Standard_EXPORT void SetBoundary (const math_Vector& theLeftBorder, const math_Vector& theRightBorder); //! returns the value of the minimum. //! Exception NotDone is raised if the minimum was not found. Standard_Real Minimum() const; //! returns the gradient vector at the minimum. //! Exception NotDone is raised if an error has occurred. //! The minimum was not found. const math_Vector& Gradient() const; //! outputs the gradient vector at the minimum in Grad. //! Exception NotDone is raised if the minimum was not found. //! Exception DimensionError is raised if the range of Grad is not //! equal to the range of the StartingPoint. void Gradient (math_Vector& Grad) const; //! returns the number of iterations really done in the //! calculation of the minimum. //! The exception NotDone is raised if an error has occurred. Standard_Integer NbIterations() const; //! Returns the Status of computation. //! The exception NotDone is raised if an error has occurred. math_Status GetStatus() const; //! Prints on the stream o information on the current state //! of the object. //! Is used to redefine the operator <<. Standard_EXPORT void Dump (Standard_OStream& o) const; protected: math_Status TheStatus; math_Vector TheLocation; math_Vector TheGradient; math_Vector TheStep; math_Matrix TheHessian; Standard_Real PreviousMinimum; Standard_Real TheMinimum; Standard_Real MinEigenValue; Standard_Real XTol; Standard_Real CTol; Standard_Integer nbiter; Standard_Boolean NoConvexTreatement; Standard_Boolean Convex; Standard_Boolean myIsBoundsDefined; math_Vector myLeft; math_Vector myRight; private: Standard_Boolean Done; Standard_Integer Itermax; }; #include <math_NewtonMinimum.lxx> #endif // _math_NewtonMinimum_HeaderFile
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "memory_block_interface.hpp" #include "table_data.hpp" using orkhestrafs::core_interfaces::MemoryBlockInterface; using orkhestrafs::core_interfaces::table_data::ColumnDataType; namespace orkhestrafs::dbmstodspi { class CSVReaderInterface { public: virtual ~CSVReaderInterface() = default; virtual auto ReadTableData(const std::string& filename, char separator, int& rows_already_read) -> std::vector<std::vector<std::string>> = 0; virtual auto WriteTableFromFileToMemory( const std::string& filename, char separator, const std::vector<std::pair<ColumnDataType, int>>& column_defs_vector, MemoryBlockInterface* memory_device) -> int = 0; }; } // namespace orkhestrafs::dbmstodspi
#include "f3lib/logic/Object.h"
#ifndef Conjugate_h #define Conjugate_h #include "Matrix.h" #include <vector> class Conjugate { private: Matrix<vector<vector<double> > > p; double alpha; double beta; public: void Set_p_Matrix(int rows_,int columns_) { p.SetMatrix(rows_,columns_); } void Setp(Matrix<vector<vector<double> > > p_) { p=p_; } void Setalpha(double alpha_) { alpha=alpha_; } void Setbeta(double beta_) { beta=beta_; } Matrix<vector<vector<double> > > Getp() { return p; } double Getalpha() { return alpha; } double Getbeta() { return beta; } void algorithm(Matrix<vector<vector<double> > > s,Matrix<vector<vector<double> > > Q,Matrix<vector<vector<double> > >& x); }; #endif
/*-------------------------------------------------------------------- Bellevue Class: PROG 111 Term/Date: Fall 11/21/2013 Instructor: Robert Main Project #: 8 File Name: main.cpp Programmer: Kathryn Brusewitz Uses stats class to retrieve and analyze data for a years worth of rainfall. Reports total rainfall, average rainfall, and months with the most and least rainfall. --------------------------------------------------------------------*/ #include <iostream> // Defines objects and classes used for stream I/O #include "Stats.h" // Class Definition header file #include <iomanip> // For manipulating input/output stream #include <windows.h> // For setting cursor positions #include <string> const int NUM_MONTHS = 12; void placeCursor(HANDLE, int, int); int main() { std::string month[NUM_MONTHS] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; int highestMonth; int lowestMonth; double userInput; Stats rainfallStats; // Create handle to the standard output screen HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE); std::cout << "This program analyzes a year's worth of rainfall data.\n\n"; std::cout << "Enter the amount of rainfall for the month in inches: \n\n"; // Print Form (Months) for (int i = 0; i < NUM_MONTHS; i++) std::cout << month[i] << ":" << std::endl; // User Input for (int i = 0; i < NUM_MONTHS; i++) { placeCursor(screen, (4 + i), 12); std::cin >> userInput; if(!rainfallStats.storeValue(userInput)) std::cout << "Error: Can't add more values" << std::endl; } // Find months with most and least rainfall highestMonth = rainfallStats.highest(); lowestMonth = rainfallStats.lowest(); // Display Report std::cout << "\n Rain Report for the Year"; std::cout << std::fixed << std::setprecision(2) << std::endl << std::endl; std::cout << "Total rainfall: " << rainfallStats.total() << " inches" << std::endl; std::cout << "Average rainfall: " << rainfallStats.average() << " inches" << std::endl; std::cout << "The most rain fell in " << month[highestMonth] << " with "; std::cout << rainfallStats.getValue(highestMonth) << " inches." << std::endl; std::cout << "The least rain fell in " << month[lowestMonth] << " with "; std::cout << rainfallStats.getValue(lowestMonth) << " inches." << std::endl; // Prevent the Console Window from closing during debug mode std::cin.ignore(std::cin.rdbuf()->in_avail()); std::cout << "\nPress only the 'Enter' key to exit program: "; std::cin.get(); return 0; } void placeCursor(HANDLE screen, int row, int col) { COORD position; position.Y = row; position.X = col; SetConsoleCursorPosition(screen, position); }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef BASEMATRIXTYPE_H_ #define BASEMATRIXTYPE_H_ #include <boost/numeric/ublas/matrix.hpp> #include "Point.h" namespace Geometry { /** * Matrix type optimised to use with OpenGL. * \ingroup Geometry */ /* * Tu jest podany parametr szablonowy column_major, ktรณry mรณwi o ustawieniu * elementรณw w pamiฤ™ci (kolumnami, czy wierszami). */ namespace { typedef boost::numeric::ublas::matrix <float, boost::numeric::ublas::column_major> BaseMatrixType_T; } class BaseMatrixType : public BaseMatrixType_T { public: BaseMatrixType () : BaseMatrixType_T (4, 4) { resetIdentity (); } BaseMatrixType (const BaseMatrixType &m) : BaseMatrixType_T (m) {} template<class AE> BaseMatrixType (const boost::numeric::ublas::matrix_expression<AE> &ae) : BaseMatrixType_T (ae) {} /*--------------------------------------------------------------------------*/ void resetIdentity (); void invert (); BaseMatrixType getInversed () const; /*------apply-transformation------------------------------------------------*/ void transform (Point *) const; Point getTransformed (const Point &) const; private: bool invertMatrix (const float m[16], float invOut[16]); }; } #endif /* BASEMATRIXTYPE_H_ */
#include "MyStrategy.h" #define _USE_MATH_DEFINES #include <cmath> #include <vector> #include <algorithm> using namespace std; using namespace model; typedef vector<Tank> TVTanks; const double MIN_ANGLE = M_PI / 90.0; // ัƒะณะพะป ะฒ ะพะดะธะฝ ะณั€ะฐะดัƒั //const double MIN_ANGLE_B = M_PI / 30.0; // ัƒะณะพะป ะฒ ะพะดะธะฝ ะณั€ะฐะดัƒั const double PI_D_2 = M_PI / 2; static double ls = 1.0; static double rs = 1.0; static long long g_need_id = 0; static long long g_lock_id = 0; static const int init_ticks = 100; static int g_num_enemies = 0; static const double g_crit_health_treshold = 0.66; bool EnemyDead(Tank * pEnemy) { if (!pEnemy) return true; return pEnemy->crew_health() == 0 || pEnemy->hull_durability() == 0; } bool HealthIsCritical(Tank & self) { return ( (double)self.crew_health()/(double)self.crew_max_health() ) < g_crit_health_treshold; } bool HullIsCritical(Tank & self) { return ( (double)self.hull_durability() /(double)self.hull_max_durability() ) < g_crit_health_treshold; } BonusType what_i_need(Tank & me) { if ( ( (double)me.crew_health()/(double)me.crew_max_health() ) < 0.9) { return MEDIKIT; } if ( ( (double)me.hull_durability()/(double)me.hull_max_durability() ) < 0.9 ) { return REPAIR_KIT; } if (!me.premium_shell_count()) { return AMMO_CRATE; } return UNKNOWN_BONUS; } template <typename TUnit> TUnit * get_need_id(long long need_id, vector<TUnit> & v) { for (int i = 0; i < v.size(); ++i) { if (need_id == v[i].id()) { return &v[i]; } } return 0; } static int stuck_tick = 0; static double min_stuck_speed = 0.1; static const int stuck_period = 20; class SpeedStat { public: SpeedStat(double sx, double sy) : m_sx( sx ) , m_sy( sy) {} double m_sx, m_sy; }; static vector<SpeedStat> speed_stat; bool IsStuck( Tank & self ) { double sx = fabs( self.speed_x() ); double sy = fabs( self.speed_y() ); speed_stat.push_back( SpeedStat(sx, sy) ); if (speed_stat.size() > 50) { speed_stat.erase( speed_stat.begin() ); } else { return false; } double avg_x = 0.0, avg_y = 0.0; for (int i = 0; i < speed_stat.size(); ++i) { avg_x += speed_stat[i].m_sx; avg_y += speed_stat[i].m_sy; } avg_x = avg_x / speed_stat.size(); avg_y = avg_y / speed_stat.size(); if (avg_x < min_stuck_speed && avg_y < min_stuck_speed) { stuck_tick = stuck_period; return true; } return false; } void GoToUnit( Unit * pBonus, Tank & self, model::Move & move ) { double orig_angle = self.GetAngleTo(*pBonus); double angle = orig_angle; double fangle = fabs(orig_angle); double dist = self.GetDistanceTo( *pBonus ); double MIN_ANGLE_B = dist*0.0005; double direction = 1.0; if (orig_angle > PI_D_2) { angle = M_PI - fangle; direction = -1.0; } if (orig_angle < -PI_D_2) { angle = fangle - M_PI; direction = -1.0; } if (fangle > PI_D_2) { if ( angle > MIN_ANGLE_B ) { move.set_left_track_power(-self.engine_power()); move.set_right_track_power( self.engine_power() - self.engine_rear_power_factor() ); //(.75); } else if ( angle < -MIN_ANGLE_B ) { move.set_left_track_power(self.engine_power() - self.engine_rear_power_factor() );//(.75); move.set_right_track_power(-self.engine_power()); } else { move.set_left_track_power(direction*1); move.set_right_track_power(direction*1); } } else { if ( angle > MIN_ANGLE_B ) { move.set_left_track_power(self.engine_power() - self.engine_rear_power_factor() );//(.75); move.set_right_track_power(-self.engine_power()); } else if ( angle < -MIN_ANGLE_B ) { move.set_left_track_power(-self.engine_power()); move.set_right_track_power( self.engine_power() - self.engine_rear_power_factor() ); //(.75); } else { move.set_left_track_power(direction*1); move.set_right_track_power(direction*1); } } } /* enum BonusType { UNKNOWN_BONUS = -1, MEDIKIT = 0, REPAIR_KIT = 1, AMMO_CRATE = 2 }; */ static int piStdBonusPriority[] = { 1, 2, 0 }; // { 1, 0, 2 }; AMMO_CRATE >= MEDIKIT >= REPAIR_KIT static int piHealthBonusPriory[] = { 0, 2, 1 }; // { 2, 0, 1 }; MEDIKIT => AMMO_CRATE => REPAIR_KIT static int piHullBonusPriory[] = { 2, 0, 1 }; //{ 0, 2, 1 }; REPAIR_KIT => AMMO_CRATE => MEDIKIT Bonus * GetNeededBonus( Tank & self, vector<Bonus> & b ) { int * pCurPriStrategy = piStdBonusPriority; BonusType cur_priority = REPAIR_KIT; if (HealthIsCritical(self)) { pCurPriStrategy = piHealthBonusPriory; } else if (HullIsCritical(self)) { pCurPriStrategy = piHullBonusPriory; cur_priority = MEDIKIT; } double min_distance = 1E20; Bonus * pBonus = 0; for (int i = 0; i < b.size(); ++i) { int iType = b[i].type(); if (pCurPriStrategy[ iType ] < pCurPriStrategy[cur_priority]) { min_distance = fabs( self.GetDistanceTo(b[i]) ); cur_priority = b[i].type(); pBonus = &b[i]; } else if ( pCurPriStrategy[ iType ] == pCurPriStrategy[cur_priority] ) { double cur_distance = fabs( self.GetDistanceTo(b[i]) ); if (cur_distance < min_distance) { min_distance = cur_distance; pBonus = &b[i]; } } } if (pBonus) { g_need_id = pBonus->id(); } return pBonus; } bool EnemyIsWalkingDead(Tank * pEnemy) { if ( ( (double)pEnemy->crew_health()/(double)pEnemy->crew_max_health() ) < 0.5 || ( (double)pEnemy->hull_durability()/(double)pEnemy->hull_max_durability() ) < 0.5 ) { return true; } return false; } bool EnemyBlocked( Tank * pEnemy, Tank & self, vector<Tank> & t ) { double my_angle = self.GetAngleTo( *pEnemy ); double my_dist = self.GetDistanceTo( *pEnemy ); for (int i = 0; i < t.size(); ++i) { if (t[i].id() == pEnemy->id() || t[i].id() == self.id()) { continue; } double max_wh = std::max( t[i].width(), t[i].height() ); double alpha = fabs( self.GetAngleTo(t[i]) - my_angle ); double his_dist = self.GetDistanceTo( t[i] ); if (alpha > M_PI / 4) { continue; } double d_size = sin(alpha) * my_dist; if ( d_size <= max_wh/2 && his_dist < my_dist ) { return true; } } return false; } Tank * get_best_enemy( Tank & self, vector<Tank> & t ) { int selected_tank = -1; double min_angle_to_enemy = 1E20; g_num_enemies = 0; for(size_t i = 0; i < t.size(); ++i) { /* select not our teammate and not dead enemy and not blocked */ if ( !t[i].teammate() && !EnemyDead(&t[i]) && !EnemyBlocked( &t[i], self, t ) ) { ++g_num_enemies; /* best if it's almoust dead */ if ( EnemyIsWalkingDead( &t[i] ) ) { g_lock_id = t[i].id(); /* lock ont enemy */ return &t[i]; } /* okay, just select enemy with minimum turret turn */ double angle_to_enemy = fabs(self.GetTurretAngleTo(t[i])); if (angle_to_enemy < min_angle_to_enemy) { min_angle_to_enemy = angle_to_enemy; selected_tank = i; } } } if (selected_tank < 0) return 0; g_lock_id = t[selected_tank].id(); /* lock ont enemy */ return &t[selected_tank]; } bool MoveTurretOrShoot( Tank * pEnemy, Tank & self, World & world, model::Move& move, double offset ) { double angle_to_enemy = self.GetTurretAngleTo(*pEnemy); if (angle_to_enemy + offset > ( MIN_ANGLE) ) { move.set_turret_turn(1.0); } else if (angle_to_enemy + offset < ( -MIN_ANGLE ) ) { move.set_turret_turn(-1.0); } else { //vector<Tank> t = world.tanks(); //if ( ! EnemyBlocked(pEnemy, self, t) ) /* decide to shoot here, path may block */ //{ /* burst if we almoust alone */ if ( EnemyIsWalkingDead( pEnemy ) || self.premium_shell_count() > 3 ) { move.set_fire_type(PREMIUM_PREFERRED); } else { move.set_fire_type(REGULAR_FIRE); } return true; //} } return false; } bool TimeToHide(Tank & self, World & world, model::Move& move) { if ( HealthIsCritical(self) || HullIsCritical(self) ) { return false; } vector<Tank> t = world.tanks(); int enemies_left = 0; for (int i = 0; i < t.size(); ++i) { if (!t[i].teammate() && !EnemyDead(&t[i])) enemies_left++; } return enemies_left > 4 || world.tick() <= 500; } enum CornerType { LEFT_UP, RIGHT_UP, RIGHT_DOWN, LEFT_DOWN, MAX_CORNER, }; class Corner : public Unit { public: double dist; CornerType id; double m_weight; Corner(double cx, double cy, double weight) : Unit( 0.0, 0.0, 0.0, cx, cy, 0.0, 0.0, 0.0, 0.0 ) , dist(0.0) , id( LEFT_UP ) , m_weight(weight) { } Corner(Tank & self, double cx, double cy, CornerType cid) : Unit( 0.0, 0.0, 0.0, cx, cy, 0.0, 0.0, 0.0, 0.0 ) , dist( self.GetDistanceTo(cx, cy) ) , id( cid ) { } }; struct CornerComparator { bool operator()(const Corner & c1, const Corner & c2) { return c1.dist < c2.dist; } }; Corner * GetNearestCorner(Tank & self, World & world) { std::vector< Corner > d; CornerComparator cdp; d.push_back( Corner(self, 0.0, world.height(), LEFT_DOWN) ); d.push_back( Corner(self, world.width(), 0.0, RIGHT_UP) ); d.push_back( Corner(self, world.width(), world.height(), RIGHT_DOWN) ); d.push_back( Corner(self, 0.0, 0.0, LEFT_UP) ); std::sort( d.begin(), d.end(), cdp ); return new Corner( d[0] ); } void MoveAlgo(Bonus * pBonus, Tank & self, World & world, model::Move& move) { if (pBonus) { return; } Corner * pNearestCorner = GetNearestCorner(self, world); GoToUnit( pNearestCorner, self, move ); delete pNearestCorner; } void Move1(Tank self, World world, model::Move& move) { Bonus * pBonus = 0; if ( !TimeToHide( self, world, move ) ) { vector<Bonus> b = world.bonuses(); /* am i going to get any bonus */ pBonus = get_need_id(g_need_id, b); if (!pBonus || ( pBonus->type() != MEDIKIT && HealthIsCritical(self) ) ) { pBonus = GetNeededBonus( self, b ); } if (pBonus) { GoToUnit( pBonus, self, move ); } } // Shoot( self, world, move ); MoveAlgo( pBonus, self, world, move ); } void ForceModify(Tank & self, Unit & u, double & xForce, double & yForce, double neg_c) { //double absBearing = fabs( u.angle() ); double absBearing = self.GetAngleTo( u ); /* from 0 to 2*PI */ double distance = self.GetDistanceTo( u ); xForce += neg_c * ( sin(absBearing) / (distance * distance) ); yForce += neg_c * ( cos(absBearing) / (distance * distance) ); } static vector<Corner> c; void FirstTick( Tank & self, World & world ) { for (double i = 0.0; i <= world.height(); i += self.height()) { for (double j = 0.0; i <= world.width(); i += self.width()) { c.push_back( Corner( i, j, -1.0) ); } } c.push_back( Corner( 0.0, world.height(), 3 ) ) ; c.push_back( Corner( world.width(), 0.0, 3) ); c.push_back( Corner( world.width(), world.height(), 3) ); c.push_back( Corner( 0.0, 0.0, 3) ); } class WaveBullet { public: double startX, startY, startBearing, m_power; long fireTime; int direction; vector<double> * m_returnSegment; class PlayerShadow : public Unit { public: PlayerShadow( double x, double y, double angle ) : Unit( 0.0, 0.0, 0.0, x, y, 0.0, 0.0, angle, 0.0 ) {} }; WaveBullet(double x, double y, double angle, double bearing, double power, int direction, long time, vector<double> * returnSegment ) : startX( x ) , startY( y ) , startBearing( bearing ) , m_power( power ) , direction( direction ) , fireTime( time ) , m_returnSegment( returnSegment ) , m_shadow( x, y, angle ) { } double getBulletSpeed() { return (20 - (3 * m_power)); } double maxEscapeAngle() { return asin(8/getBulletSpeed()); } static double rollingAvg(double value, double newEntry, double n, double weighting ) { return (value * n + newEntry * weighting)/(n + weighting); } bool checkHit(Tank & self, Tank * pEnemy, long currentTime) { static int readings = 0; // if the distance from the wave origin to our enemy has passed // the distance the bullet would have traveled... if (pEnemy->GetDistanceTo( startX, startY ) <= (currentTime - fireTime) * m_power ) { //double desiredDirection = atan2(pEnemy->x() - startX, pEnemy->y() - startY); //double desiredDirection = pEnemy->GetAngleTo( startX, startY ); //double desiredDirection = self.GetAngleTo(*pEnemy); double desiredDirection = m_shadow.GetAngleTo(*pEnemy); double angleOffset = desiredDirection - startBearing; double guessFactor = std::max(-1.0, std::min(1.0, angleOffset / maxEscapeAngle())) * direction; int index = (int)floor( ((double)m_returnSegment->size() - 1) /2 * (guessFactor + 1)); m_returnSegment->at(index) = rollingAvg(m_returnSegment->at(index), 1, std::min(readings++, 200), 1); for (int i = 0; i < m_returnSegment->size(); ++i) { m_returnSegment->at(i) = 1 / pow(abs(i - index) + 1, 2.0); /* if (i != index) { m_returnSegment->at(index) = rollingAvg(m_returnSegment->at(index), 0, std::min(readings++, 200), 1); } */ } //m_returnSegment->at(index)++; return true; } m_power -= .2; return false; } PlayerShadow m_shadow; }; static std::vector<WaveBullet> waves; static vector<double> stats(30); double direction = 1; void Shoot(Tank & self, World & world, model::Move& move) { vector<Tank> t = world.tanks(); /* always keep tower to some enemy */ Tank * pEnemy = get_need_id(g_lock_id, t); if ( EnemyDead(pEnemy) ) { pEnemy = 0; } /* not locked to anyone, select some, or change target every 300 tick */ if (!pEnemy || world.tick() % 300 == 0) { Tank * pOldEnemy = pEnemy; pEnemy = get_best_enemy(self, t); if (pEnemy != pOldEnemy) { waves.clear(); stats.clear(); stats.resize(30); } } /* still bad luck ? */ if (!pEnemy) { /* MoveAlgo */ return; } double absBearing = self.GetAngleTo(*pEnemy); for (int i=0; i < waves.size(); i++) { if (waves[i].checkHit(self, pEnemy, world.tick())) { waves.erase(waves.begin() + i ); i--; } } double power = 16.7; double e_velocity = sqrt( pEnemy->speed_x()*pEnemy->speed_x() + pEnemy->speed_y()*pEnemy->speed_y() ); WaveBullet newWave( self.x(), self.y(), self.angle(), absBearing, power, direction, world.tick(), &stats ); int bestindex = 15; for (int i=0; i<30; ++i) { if (stats[bestindex] < stats[i]) { bestindex = i; } } double guessfactor = ( bestindex - ( (double)stats.size() - 1 )/2 ) / ( ( (double)stats.size() - 1) / 2) ; if (e_velocity > 0.01) { if ( sin( pEnemy->angle() - self.angle() ) < 0 ) { direction = -1; } else { direction = 1; } } double angleOffset = direction * guessfactor * newWave.maxEscapeAngle(); /* got lock? move turret! */ MoveTurretOrShoot( pEnemy, self, world, move, 0.0 ); waves.push_back(newWave); } void MyStrategy::Move(Tank self, World world, model::Move& move) { if (world.tick() == 1) { FirstTick(self, world); } vector<Tank> t = world.tanks(); vector<Shell> s = world.shells(); vector<Bonus> b = world.bonuses(); double xForce = 0 , yForce = 0 ; for (int i = 0; i < t.size(); ++i) { if (self.id() == t[i].id()) continue; if (EnemyDead(&t[i])) continue; ForceModify( self, t[i], xForce, yForce, -1.0 ); } Bonus * pBonus = 0; if ( !TimeToHide( self, world, move ) ) { pBonus = get_need_id(g_need_id, b); //pBonus = GetNeededBonus( self, b ); if (!pBonus || ( pBonus->type() != MEDIKIT && HealthIsCritical(self) ) ) { pBonus = GetNeededBonus( self, b ); } } for (int i = 0; i < b.size(); ++i) { double bonusPower = 1.0; if (pBonus && b[i].id() == pBonus->id()) { bonusPower = 10000.0; } ForceModify( self, b[i], xForce, yForce, bonusPower ); } /* for (int i = 0; i < s.size(); ++i) { if (self.player_name() != s[i].player_name()) { ForceModify( self, s[i], xForce, yForce, -100000.0 ); } } */ double orig_angle = atan2(xForce, yForce); double angle = orig_angle; double fangle = fabs(angle); double MIN_ANGLE_B = M_PI/30.0; double dir = 1.0; double s_angle = self.angle(); if (orig_angle > PI_D_2) { angle = M_PI - fangle; dir = -1.0; } if (orig_angle < -PI_D_2) { angle = fangle - M_PI; dir = -1.0; } if (fangle > PI_D_2) { if ( angle > MIN_ANGLE_B ) { move.set_left_track_power(-1.0); move.set_right_track_power( .75 ); //(.75); } else if ( angle < -MIN_ANGLE_B ) { move.set_left_track_power(.75 );//(.75); move.set_right_track_power(-1.0); } else { move.set_left_track_power(dir*1); move.set_right_track_power(dir*1); } } else { if ( angle > MIN_ANGLE_B ) { move.set_left_track_power(.75 );//(.75); move.set_right_track_power(-1.0); } else if ( angle < -MIN_ANGLE_B ) { move.set_left_track_power(-1.0); move.set_right_track_power( .75 ); //(.75); } else { move.set_left_track_power(dir*1); move.set_right_track_power(dir*1); } } //move.set_left_track_power(0); //move.set_right_track_power(0); Shoot( self, world, move ); } TankType MyStrategy::SelectTank(int tank_index, int team_size) { return MEDIUM; }
๏ปฟ#include <iostream> #include <vector> #include "include/AppContext.h" #include "include/LRAnalyze.h" using namespace std; int main(int argc, char *argv[]) { cout << "LR Grammatical analysis by Kyle Derrick ^_^" << endl; cout << "-------------------------------------------" << endl; //่Žทๅ–้…็ฝฎๆ–‡ไปถ่ทฏๅพ„ string fpath; if (argc > 1) { fpath = argv[1]; } else { cout << "่พ“ๅ…ฅLR้…็ฝฎๆ–‡ไปถ่ทฏๅพ„:\n> "; cin >> fpath; } //่งฃๆž้…็ฝฎๆ–‡ไปถ AppContext context = AppContext::init(fpath); //context.testPrint(); LRAnalyze lr = LRAnalyze(context); string instr; while (true) { cout << "\n่พ“ๅ…ฅๅฅๅญ:\n> "; cin >> instr; if (instr == "exit") { break; } try { lr.init(instr); lr.analyze(); } catch (const string& estr) { cerr << estr << endl; } } system("pause"); }
// Created on: 2016-04-19 // Copyright (c) 2016 OPEN CASCADE SAS // Created by: Oleg AGASHIN // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IMeshTools_ModelAlgo_HeaderFile #define _IMeshTools_ModelAlgo_HeaderFile #include <Standard_Transient.hxx> #include <Message_ProgressRange.hxx> class IMeshData_Model; struct IMeshTools_Parameters; //! Interface class providing API for algorithms intended to update or modify discrete model. class IMeshTools_ModelAlgo : public Standard_Transient { public: //! Destructor. virtual ~IMeshTools_ModelAlgo() { } //! Exceptions protected processing of the given model. Standard_Boolean Perform ( const Handle (IMeshData_Model)& theModel, const IMeshTools_Parameters& theParameters, const Message_ProgressRange& theRange) { try { OCC_CATCH_SIGNALS return performInternal (theModel, theParameters, theRange); } catch (Standard_Failure const&) { return Standard_False; } } DEFINE_STANDARD_RTTIEXT(IMeshTools_ModelAlgo, Standard_Transient) protected: //! Constructor. IMeshTools_ModelAlgo() { } //! Performs processing of the given model. Standard_EXPORT virtual Standard_Boolean performInternal ( const Handle (IMeshData_Model)& theModel, const IMeshTools_Parameters& theParameters, const Message_ProgressRange& theRange) = 0; }; #endif
#ifndef _GUARD_PROFILE_ARGS_H #define _GUARD_PROFILE_ARGS_H #include <cstdlib> #include <cstring> #include <initializer_list> #include <stdexcept> #include <unordered_set> #include <vector> #include <iostream> #include "profile_util.h" struct VariantOptionBase { std::vector<char const *>::size_type choice_index(char const *choice) const { for (auto i = 0u; i < _choices.size(); ++i) { if (strcmp(_choices[i], choice) == 0) return i; } throw std::invalid_argument("invalid parameter choice"); } std::vector<char const *> _choices; }; class VariantOption : private VariantOptionBase { public: VariantOption(std::initializer_list<char const *> choices) { _choices.emplace_back("unset"); _choices.insert(_choices.end(), choices.begin(), choices.end()); _current_choice = 0u; } void set(char const *choice) { _current_choice = choice_index(choice); } char const *get() const { return _choices[_current_choice]; } bool is_set() const { return _current_choice != 0u; } bool is(char const *choice) const { return _current_choice == choice_index(choice); } private: std::vector<char const *>::size_type _current_choice; }; class VariantOptionSet : private VariantOptionBase { public: VariantOptionSet(std::initializer_list<char const *> choices) { _choices.emplace_back("unset"); _choices.insert(_choices.end(), choices.begin(), choices.end()); } void set(char const *choice) { if (!is_set(choice)) _selected.insert(choice_index(choice)); } void unset(char const *choice) { _selected.erase(choice_index(choice)); } std::vector<char const *> get() const { std::vector<char const *> res; for (auto i : _selected) res.push_back(_choices[i]); return res; } bool is_set(char const *choice) const { return _selected.find(choice_index(choice)) != _selected.end(); } private: std::unordered_set<std::vector<char const *>::size_type> _selected; }; #define CHECK_OPTION(cond, msg) \ if (!(cond)) { \ usage(std::cerr); \ error(msg); \ return EXIT_FAILURE; \ } #define CHECK_ARGUMENT(arg) \ if (optind == argc) { \ usage(std::cerr); \ error(arg, "argument is mandatory"); \ return EXIT_FAILURE; \ } #define OPEN_STREAM(var, arg) \ try { \ var.open(arg); \ } catch (std::runtime_error const &e) { \ error(e.what(), ":", arg); \ return EXIT_FAILURE; \ } #endif // _GUARD_PROFILE_ARGS_H
class GetUglyNumber { public: int min(int a, int b, int c) { int res = (a > b ? b : a); return (res > c ? c : res); } int GetUglyNumber_Solution(int index) { if (index < 1) return 0; vector<int> ugly_nums(index, 0); ugly_nums[0] = 1; int nextIdx = 1; int X2_min = -1; int X3_min = -1; int X5_min = -1; int idx = 0; while (nextIdx < index) { for (idx = 0; idx < nextIdx && 2 * ugly_nums[idx] <= ugly_nums[nextIdx - 1]; ++idx); X2_min = 2 * ugly_nums[idx]; for (idx = 0; idx < nextIdx && 3 * ugly_nums[idx] <= ugly_nums[nextIdx - 1]; ++idx); X3_min = 3 * ugly_nums[idx]; for (idx = 0; idx < nextIdx && 5 * ugly_nums[idx] <= ugly_nums[nextIdx - 1]; ++idx); X5_min = 5 * ugly_nums[idx]; ugly_nums[nextIdx++] = min(X2_min, X3_min, X5_min); } return ugly_nums.back(); } void test() { vector<int> test_cases = { -1, 1, 3, 7, 8, 50, 1000, 3000 }; for (auto& i : test_cases) { cout << i << " ==> " << GetUglyNumber_Solution(i) << endl; } } };
#pragma once #include "Behaviour.h" #include "Decision.h" class DecisionBehaviour : public Behaviour { public: virtual vector2 Update(Agent* agent, float deltaTime) //each frame update your decision { m_decision->makeDecision(agent, deltaTime); return vector2(0, 0); } virtual float GetWeight() { return 0; } void addDecision(Decision* d) //adds 1 decision which is at the top of the decision tree { m_decision = d; }; private: Decision* m_decision; };
#include <vector> #include <set> #include "opennwa/query/returns.hpp" #include "opennwa/query/calls.hpp" #include "opennwa/query/internals.hpp" #include "wali/TotalOrderWorklist.hpp" #include "wali/wfa/WFA.hpp" #include "wali/wfa/State.hpp" #include "opennwa/Nwa.hpp" #include "opennwa/query/language.hpp" #include "opennwa/nwa_pds/conversions.hpp" #include "wali/wpds/WPDS.hpp" #include "opennwa/ClientInfo.hpp" #include "wali/witness/WitnessWrapper.hpp" #include "wali/witness/WitnessLengthWorklist.hpp" #include "opennwa/query/PathVisitor.hpp" #include "opennwa/query/ShortWitnessVisitor.hpp" using namespace wali; namespace opennwa { namespace query { NestedWordRefPtr getSomeAcceptedWordInternal(Nwa const & nwa, WeightGen const & wg); NestedWordRefPtr getSomeAcceptedWord(Nwa const & nwa) { ReachGen wg; return getSomeAcceptedWordInternal(nwa, wg); } NestedWordRefPtr getSomeShortestAcceptedWord(Nwa const & nwa) { ShortestWordGen wg; return getSomeAcceptedWordInternal(nwa, wg); } NestedWordRefPtr getSomeAcceptedWordWithWeights(Nwa const & nwa, WeightGen const & wg) { return getSomeAcceptedWordInternal(nwa, wg); } sem_elem_t getWitnessForSomeAcceptedWordWithWeights(Nwa const & nwa, WeightGen const & wg) { if (nwa.sizeInitialStates() == 0 || nwa.sizeFinalStates() == 0) { return sem_elem_t(); } ref_ptr<wpds::Wrapper> wrapper = new witness::WitnessWrapper(); wpds::WPDS conv = nwa_pds::NwaToWpdsCalls(nwa, wg, wrapper); // Set the worklist to determine the order of poststar traversal. conv.setWorklist(new witness::WitnessLengthWorklist()); Key state = nwa_pds::getProgramControlLocation(); Key accept = getKey("__accept"); // Construct the poststar query automaton to get all // configurations reachable from the initial state. wfa::WFA query; query.addState(state, wg.getOne()->zero()); query.setInitialState(state); query.addState(accept, wg.getOne()->zero()); query.addFinalState(accept); for( Nwa::StateIterator initial = nwa.beginInitialStates(); initial != nwa.endInitialStates(); initial++ ) { query.addTrans(state, *initial, accept, wg.getOne()); query.addTrans(accept, *initial, accept, wg.getOne()); // Accept pending returns } // Execute the post* query. wfa::WFA path = conv.poststar(query); // Prune unreachable states. path.prune(); // Intersect path with a new 2-state WFA with a transitioning edge // for each final NWA state, and a self-loop from the WFA final // state on each non-final NWA state. wfa::WFA fa; Key init = getKey("__init"); fa.addState(init, wg.getOne()->zero()); fa.setInitialState(init); Key fin = getKey("__final"); fa.addState(fin, wg.getOne()->zero()); fa.addFinalState(fin); for( Nwa::StateIterator fit = nwa.beginFinalStates(); fit != nwa.endFinalStates(); fit++) { fa.addTrans(init, *fit, fin, wg.getOne()); } for( Nwa::StateIterator sit = nwa.beginStates(); sit != nwa.endStates(); sit++ ) { fa.addTrans(fin, *sit, fin, wg.getOne()); } wfa::KeepLeft wmaker; wfa::WFA ipath; path.intersect(wmaker, fa, ipath); // Intersect may prune all final states. if (ipath.getFinalStates().size() == 0) { return sem_elem_t(); } ipath.path_summary_iterative_wpds(wfa::WFA::ComputeInitialState); return ipath.getState(ipath.getInitialState())->weight(); } NestedWordRefPtr getSomeAcceptedWordInternal(Nwa const & nwa, WeightGen const & wg) { sem_elem_t se = getWitnessForSomeAcceptedWordWithWeights(nwa, wg); if (se.is_empty()) return NULL; witness::Witness *wit = dynamic_cast<witness::Witness*>(se.get_ptr()); assert(wit); if (!wit->isZero()) { // Find a shortest single-path witness. ShortWitnessVisitor swv; wit->accept(swv, false); witness::Witness *pathWit = swv.answer().get_ptr(); assert(pathWit); //std::cerr << "##### PATHWIT LENGTH: " << pathWit->getLength() << std::endl; //pathWit->reset_marks(); // Generate a NestedWord from the single-path witness. PathVisitor pv(nwa); pathWit->accept(pv, false); NestedWord *nw = new NestedWord(pv.getPath()); return NestedWordRefPtr(nw); } // No word was found. return NULL; } } // namespace query } // Yo, Emacs! // Local Variables: // c-file-style: "ellemtel" // c-basic-offset: 2 // End:
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "adjunct/desktop_util/prefs/PrefsUtils.h" #include "adjunct/desktop_util/prefs/PropertyPrefs.h" namespace PrefsUtils { OP_STATUS ReadPrefsString(PrefsFile* prefs_file, const OpStringC8& section, const OpStringC8& key, const OpStringC& def_value, OpProperty<OpString>& result) { OpString value; RETURN_IF_ERROR(ReadPrefsString(prefs_file, section, key, def_value, value)); result.Set(value); return OpStatus::OK; } OP_STATUS ReadPrefsString(PrefsFile* prefs_file, const OpStringC8& section, const OpStringC8& key, OpProperty<OpString>& result) { return ReadPrefsString(prefs_file, section, key, NULL, result); } }
// // sudokuSolver.hpp // // // Created by Juha Kreula on 22/01/2020. // #ifndef sudokuSolver_hpp #define sudokuSolver_hpp #include "sudokuGrid.hpp" class Solver { public: // Constructor explicit Solver(Grid & gridToBeSolved) : grid(gridToBeSolved), cycles(0) { } // Destructor ~Solver () {} bool slotIsEmpty(int & row, int & col) const { return (grid[row][col] == EMPTY); } bool findEmptySlotInGrid(int & row, int & col) const; bool numberFoundInRow(int & row, int & number) const; bool numberFoundInColumn(int & col, int & number) const; bool numberFoundInRegion(int & regionBeginRow, int & regionBeginCol, int & number) const; bool legalAssignmentToSlot(int & row, int & col, int & number) const; bool solveBacktracking(); Grid & getGrid() { return grid; } int getCycles() const { return cycles; } // Return the number of backtracking cycles private: Grid grid; // Sudoku Grid object holding the numbers int cycles; // Number of backtracking cycles static const int EMPTY = 0; // variable to indicate an empty cell in the grid }; #endif /* sudokuSolver_hpp */
#include "tokenizer.hh" #include "statistics.hh" #include "../v0/dictionary.hh" #include "../string_view.hh" #include <iostream> #include <fstream> #include <vector> #include <string> #include <locale> #include <algorithm> std::vector<std::string> load_dictionary(const char* path) { std::vector<std::string> out; std::ifstream input(path); std::string line; while(std::getline(input, line)) { out.push_back(line); } return out; } int main(int argc, char** argv) { if (argc < 3) throw std::runtime_error("Usage: spellchecker DICTIONARY INPUT"); // Load dictionary std::vector<std::string> words = load_dictionary(argv[1]); v0::Dictionary dict(words); Statistics stats; // Parse input file std::ifstream input(argv[2]); std::string line; std::string lower; while(std::getline(input, line)) { auto tokenizer = Tokenizer{line.data(), line.data() + line.size()}; for(string_view word = tokenizer.get_next(); !word.empty(); word = tokenizer.get_next()) { if (!dict.in_dictionary(word)) { // convert to lower-case and re-check lower.resize(word.size()); std::transform(word.begin(), word.end(), lower.begin(), [](char c) { return std::tolower(c); }); if (!dict.in_dictionary(lower)) { stats.add_error(word); } } } } stats.print_stats(); }
#include <dmp_lib/KalmanFilter/DMPpEKFa.h> #include <dmp_lib/math/quaternions.h> namespace as64_ { namespace dmp_ { DMPpEKFa::DMPpEKFa(std::shared_ptr<dmp_::DMP_pos> dmp, double Ts) { this->Ts = Ts; this->dmp = dmp; this->Az = arma::diagmat( arma::vec( {dmp->dmp[0]->a_z, dmp->dmp[1]->a_z, dmp->dmp[2]->a_z} ) ); this->Bz = arma::diagmat( arma::vec( {dmp->dmp[0]->b_z, dmp->dmp[1]->b_z, dmp->dmp[2]->b_z} ) ); int N_params = 10; int N_msr = 6; this->theta = arma::vec().zeros(N_params); this->P = arma::mat().zeros(N_params,N_params); this->setProcessNoiseCov(arma::mat().eye(N_params,N_params)*1e-5); this->setMeasureNoiseCov(arma::mat().eye(N_msr,N_msr)*0.05); this->setFadingMemoryCoeff(1.0); this->enableParamsContraints(false); this->setParamsConstraints(arma::mat().zeros(1,N_params),arma::vec().zeros(1)); this->setPartDerivStep(0.001); H_k = arma::join_horiz( arma::mat().eye(6,6), arma::mat().zeros(6,4) ); // this->stateTransFun_ptr = std::bind(&DMPpEKFa::stateTransFun, *this, std::placeholders::_1, std::placeholders::_2); // this->msrFun_ptr = std::bind(&DMPpEKFa::msrFun, *this, std::placeholders::_1, std::placeholders::_2); // this->stateTransFunJacob_ptr = std::bind(&DMPpEKFa::stateTransFunJacob, *this, std::placeholders::_1, std::placeholders::_2); // this->msrFunJacob_ptr = std::bind(&DMPpEKFa::msrFunJacob, *this, std::placeholders::_1, std::placeholders::_2); } void DMPpEKFa::setFadingMemoryCoeff(double a_p) { this->a_p = a_p; } void DMPpEKFa::enableParamsContraints(bool enable_contraints) { this->enable_constraints = enable_contraints; } void DMPpEKFa::setParamsConstraints(const arma::mat &A_c, const arma::vec &b_c) { this->A_c = A_c; this->b_c = b_c; } void DMPpEKFa::setProcessNoiseCov(const arma::mat &Qn) { this->Qn = Qn; } void DMPpEKFa::setMeasureNoiseCov(const arma::mat &Rn) { this->Rn = Rn; } void DMPpEKFa::setPartDerivStep(double dtheta) { this->dtheta = arma::vec().ones(this->theta.size())*dtheta; } void DMPpEKFa::setPartDerivStep(const arma::vec &dtheta) { this->dtheta = dtheta; } void DMPpEKFa::predict(void *cookie) { F_k = stateTransFunJacob(theta, cookie); theta = stateTransFun(theta, cookie); arma::mat FP = P; FP.rows(0,2) = F_k.rows(0,2)*P; FP.rows(3,5) = FP.rows(3,5) + P.rows(0,2)*Ts; P = std::pow(a_p,2)*FP*F_k.t() + Qn; } void DMPpEKFa::correct(const arma::vec &z, void *cookie) { // ===== Retrive the measurement function Jacobian ===== // this->H_k = msrFunJacob(theta, cookie); // ===== Correction estimates ===== arma::vec z_hat = msrFun(this->theta, cookie); // arma::mat K_kf = arma::solve((P.submat(0,0,5,5) + Rn).t(), H_k*P.t(), arma::solve_opts::fast).t(); // this->theta = this->theta + K_kf * (z - z_hat); // // ===== Apply projection if enabled ===== // arma::mat D; // active contraints // arma::vec d; // bool proj_flag = false; // if ( this->enable_constraints & ~b_c.is_empty() ) // { // arma::uvec ind = arma::find(A_c*theta > b_c); // if (~ind.is_empty()) // { // proj_flag = true; // D = A_c.rows(ind); // d = b_c.elem(ind); // } // } // // int N_params = theta.size(); // arma::mat I = arma::mat().eye(N_params, N_params); // // if (proj_flag) // { // K_kf = ( I - D.t()*arma::inv_sympd(D*D.t())*D ) * K_kf; // this->theta = theta - D.t()*arma::inv_sympd(D*D.t())*(D*theta-d); // } // ===== Calculate new covariance ===== // this->P = (I - K_kf*H_k) * P * (I - K_kf*H_k).t() + K_kf*Rn*K_kf.t(); // K = arma::solve((P.submat(0,0,5,5) + Rn).t(), H_k*P.t(), arma::solve_opts::fast).t(); K = arma::solve((P.submat(0,0,5,5) + Rn), P.rows(0,5), arma::solve_opts::fast+arma::solve_opts::likely_sympd).t(); // Eigen::Map<Eigen::Matrix<double,10,6>> K_map(K.memptr()); // Eigen::Map<Eigen::Matrix<double,10,10>> P_map(P.memptr()); // Eigen::Map<Eigen::Matrix<double,6,6>> R_map(Rn.memptr()); // Eigen::Matrix<double,6,6> cPc_R = P_map.block(0,0,6,6) + R_map; // Eigen::LLT<Eigen::Matrix<double,6,6>> llt(cPc_R); // K_map = (llt.solve(P_map.block(0,0,6,10))).transpose(); theta += K*(z - z_hat); P += -K*P.rows(0,5); //this->K = K_kf; } arma::vec DMPpEKFa::msrFun(const arma::vec &theta, void *cookie) { return theta.subvec(0,5); } arma::vec DMPpEKFa::stateTransFun(const arma::vec &theta, void *cookie) { arma::vec p_dot = theta.subvec(0,2); arma::vec p = theta.subvec(3,5); arma::vec pg = theta.subvec(6,8); double tau = theta(9); double x = static_cast<StateTransCookie *>(cookie)->t/tau; double tau0 = dmp->getTau(); dmp->setTau(tau); arma::vec p_ddot = dmp->calcYddot(x, p, p_dot, pg); dmp->setTau(tau0); arma::vec theta_next(10); theta_next.subvec(0,2) = p_dot + p_ddot*Ts; theta_next.subvec(3,5) = p + p_dot*Ts; theta_next.subvec(6,9) = theta.subvec(6,9); return theta_next; } arma::mat DMPpEKFa::msrFunJacob(const arma::vec &theta, void *cookie) { return arma::join_horiz( arma::mat().eye(6,6), arma::mat().zeros(6,4) ); } arma::mat DMPpEKFa::stateTransFunJacob(const arma::vec &theta, void *cookie) { double t = static_cast<StateTransCookie *>(cookie)->t; arma::vec p0 = static_cast<StateTransCookie *>(cookie)->p0; arma::vec p_dot = theta.subvec(0,2); arma::vec p = theta.subvec(3,5); arma::vec pg = theta.subvec(6,8); double tau = theta(9); double x = t/tau; arma::mat I3 = arma::mat().eye(3,3); arma::mat F = arma::mat().eye(10,10); F.submat(0,0,2,2) = I3 - Az*Ts/tau; F.submat(0,3,2,5) = -Az*Bz*Ts/std::pow(tau,2); F.submat(0,6,2,9) = dmp->getAcellPartDev_g_tau(t, p, p_dot, p0, x, pg, tau)*Ts; F.submat(3,0,5,2) = I3*Ts; return F; } } // namespace dmp_ } // namespace as64_
#include "Font.h" #include "Texture.h" #include "Exception.h" #include "Core.h" void Font::Load(std::string _path) { //renderFont = core->GetContext()->createFont(); //long size; //std::vector<unsigned char> fontBuffer; //FILE* fontFile = fopen(_path.c_str(), "rb"); //fseek(fontFile, 0, SEEK_END); //size = ftell(fontFile); /* how long is the file ? */ //fseek(fontFile, 0, SEEK_SET); /* reset */ //fontBuffer.resize(size); //fread(&fontBuffer.at(0), size, 1, fontFile); //renderFont->initFont(fontBuffer); //fclose(fontFile); } void Font::DrawFont(std::string _text, glm::vec2 position) { }
#pragma once class Patch { public: struct Vertex { glm::vec3 pos; glm::vec3 normal; glm::vec2 uv; }; struct Triangle { GLuint v1, v2, v3; }; Patch(); ~Patch(); // N - vertices count in grid side // step - cell length in world coords void init(int N, const glm::vec3& origin, GLfloat step); std::vector<Vertex>& getVertices() {return vertices_;} std::vector<GLuint>& getIndices() {return indices_;} int getTrianglesCount() const; Triangle getTriangle(int i) const; void animate(double time); private: int N_; glm::vec3 origin_; GLfloat step_; std::vector<Vertex> vertices_; std::vector<GLuint> indices_; void createVertices(); void createIndices(); };
// // main.cpp // 1015 // // Created by Pedro Neves Alvarez on 7/8/17. // Copyright ยฉ 2017 Pedro Neves Alvarez. All rights reserved. // #include <iostream> #include <cmath> using namespace std; typedef struct point{ double x; double y; } Point; int main(int argc, const char * argv[]) { Point p1,p2; cout << "Enter the first" << endl; cin >> p1.x >> p1.y; cout << endl << "Enter the second" << endl; cin >> p2.x >> p2.y; double dist = sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y)); printf("%.4f\n", dist); return 0; }
#pragma once #include "GuiManager.h" #include "OgreTerrain.h" #include "OgreTerrainGroup.h" #include "OgreTerrainQuadTreeNode.h" #include "OgreTerrainMaterialGeneratorA.h" #include "OgreTerrainPaging.h" #include "Controls/RollupCtrl.h" #include "EditTool.h" #include "DatabaseDialog.h" #include "ParticleDialog.h" #include "StatusDialog.h" #include "smartptr.h" #include "EntityManager.h" #include "PhysicsManager.h" enum E_ROLLUP_CTRLS { E_OBJECT_CTRL, E_TERRAIN_CTRL, E_DISPLAY_CTRL, E_LAYER_CTRL, E_ROLLUP_CTRL_NUM }; /** Possible types of editor tools enumeration */ enum EDITORTOOLS { TOOL_SELECT = 0, /** Selection mode, allowing for selection of object(s) */ TOOL_MOVE, /** Displacement mode, allowing for moving object(s) */ TOOL_ROTATE, /** Rotation mode, allowing for changing object(s) orientation */ TOOL_SCALE /** Scale mode, allowing for scaling of object(s) */ }; enum E_NOTIFY_EVENTS { NE_EDITTOOL_CHANGED, NE_TOOLMODE_CHANGED }; #define TERRAIN_FILE_PREFIX String("ogreTerrain") #define TERRAIN_FILE_SUFFIX String("dat") #define TERRAIN_WORLD_SIZE 12000.0f #define TERRAIN_SIZE 513 class IEditorEventListener { public: virtual void Notify( E_NOTIFY_EVENTS event, UINT nflag = 0 ) = 0; }; class CEditor:public Ogre::FrameListener, public Ogre::WindowEventListener, public OgreBites::GuiManagerListener { public: CEditor(); ~CEditor(); void Create( HWND hWnd,int width,int height ); void locateResources(); void loadResources(); void PreLoadResources(); //void SetupInput(); void UpDate(); void Destroy(); void Resize(int width,int height); void CreateHydrax(); void CreateLevel(); BOOL Load(LPCTSTR lpszPathName); void SaveLevel(); void DefineTerrain(long x, long y, bool flat = false); void GetTerrainImage(bool flipX, bool flipY, Ogre::Image& img); /*----------------------------------------------------------------------------- | Processes frame started events. -----------------------------------------------------------------------------*/ virtual bool frameStarted(const Ogre::FrameEvent& evt) { // manually call sample callback to ensure correct order return true; } /*----------------------------------------------------------------------------- | Processes rendering queued events. -----------------------------------------------------------------------------*/ virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt); /*----------------------------------------------------------------------------- | Processes frame ended events. -----------------------------------------------------------------------------*/ virtual bool frameEnded(const Ogre::FrameEvent& evt) { // quit if window was closed if (mRenderWindow->isClosed()) return false; return true; } void OnLButtonDown(UINT nFlags, CPoint point); void OnLButtonUp(UINT nFlags, CPoint point); void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags); void OnMouseMove(UINT nFlags, CPoint point); void OnRButtonDown(UINT nFlags, CPoint point); void OnRButtonUp(UINT nFlags, CPoint point); BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); Ogre::SceneManager* GetSceneManager() { return mSceneManager; } Ogre::RenderWindow* GetRenderWindow() { return mRenderWindow; } Ogre::Camera* GetCamera() { return mCamera; } Ogre::Viewport* GetViewport() { return mViewport; } Ogre::TerrainGroup* GetTerrainGroup() { return mTerrainGroup; } Ogre::TerrainGlobalOptions* GetTerrainGlobalOptions() { return mTerrainGlobals; } bool IsLevelLoaded() { return mHaveLevel; } Ogre::Ray getCameraToViewportRay( CPoint& point ) { Ogre::Ray ray; Ogre::Vector2 fPt = Ogre::Vector2(point.x, point.y); ray = mCamera->getCameraToViewportRay(fPt.x/mRenderWindow->getWidth(), fPt.y/mRenderWindow->getHeight()); return ray; } Ogre::TerrainGroup::RayResult TerrainHitTest( CPoint& point ) { Ogre::Ray ray; Ogre::Vector2 fPt = Ogre::Vector2(point.x, point.y); ray = mCamera->getCameraToViewportRay(fPt.x/mRenderWindow->getWidth(), fPt.y/mRenderWindow->getHeight()); return mTerrainGroup->rayIntersects(ray); } void SetToolMode( EDITORTOOLS toolMode ) { mToolMode = toolMode; Notify( NE_TOOLMODE_CHANGED ); } EDITORTOOLS GetToolMode() { return mToolMode; } void RegisterEditorListener( IEditorEventListener* listener ); void unRegisterEditorListener( IEditorEventListener* listener ); void SetEditTool( CEditTool* pTool ); CEditTool* GetCurrentEditTool(); void SetStatusText( CString& test ); void Notify( E_NOTIFY_EVENTS event, UINT nflag = 0 ); void RestoreCurrentDirectory(); void ShowDatabaseDialog( bool bShow ); void DestroyDatabaseDialog() { if ( mpDatabaseDialog ) { mpDatabaseDialog = NULL; } } void ShowParticleDialog( bool bShow ); void DestroyParticleDialog() { if ( mpParticleDialog ) { mpParticleDialog = NULL; } } void SetRollupCtrl( E_ROLLUP_CTRLS id, CRollupCtrl* pCtrl ) { m_pRollupCtrl[id] = pCtrl; } CRollupCtrl* GetRollupCtrl( E_ROLLUP_CTRLS id ) { return m_pRollupCtrl[id]; } void SetStatusDialog( CStatusDialog* pDialog ) { mpStatusDialog = pDialog; } CDialog* GetStatusDialog() const { return mpStatusDialog; } void SetEditPos( Ogre::Vector3& pos ) { return mpStatusDialog->SetEditPos(pos); } void SetLogWindow(CEdit* pEdit); void Log( CString& log ); void SetTopSpeed( Ogre::Real speed ) { mTopSpeed = speed; } protected: Ogre::Root* mRoot; Ogre::RenderWindow* mRenderWindow; Ogre::SceneManager* mSceneManager; Ogre::SceneNode* mBaseSceneNode; Ogre::SceneNode* mStaticSceneNode; Ogre::Camera* mCamera; Ogre::Viewport* mViewport; OgreBites::GuiManager* mGuiMgr; CPoint mRButtonDownPos; HWND mhWnd; CEntityManager* mpEntityMgr; CPhysicsManager* mpPhysicsMgr; Ogre::TerrainGlobalOptions* mTerrainGlobals; Ogre::TerrainGroup* mTerrainGroup; Ogre::Light* mTerrainLight; Ogre::Vector3 mTerrainPos; bool mTerrainsImported; Ogre::Real mTopSpeed; Ogre::Vector3 mVelocity; bool mGoingForward; bool mGoingBack; bool mGoingLeft; bool mGoingRight; bool mGoingUp; bool mGoingDown; bool mHaveLevel; _smart_ptr<CEditTool> mpEditTool; EDITORTOOLS mToolMode; std::list<IEditorEventListener*> mEditorListenerList; char mCurDir[MAX_PATH]; CDatabaseDialog* mpDatabaseDialog; CParticleDialog* mpParticleDialog; CStatusDialog* mpStatusDialog; CRollupCtrl* m_pRollupCtrl[E_ROLLUP_CTRL_NUM]; CString mLogTest; CEdit* mpLogEdit; }; CEditor* GetEditor();
/***************************************************** * No. : JobDu 1179 * Date : 2015/12/22 * Author : HillBamboo * Source : http://ac.jobdu.com/problem.php?pid=1179 * Summary: long long for big data * Remarkr: ้ข˜็›ฎ่กจ่ฟฐไธๆธ… *****************************************************/ #include <iostream> #include <stdio.h> using namespace std; long long int fac(long long int a) { long long int res = 1; for (long long int i = 2; i <= a; ++i) res *= i; return res; } long long int facEven(long long int n) { long long int res = 0; for (long long int i = 2; i <= n; i += 2) { res += fac(i); } return res; } long long int facodd(long long int n) { long long int res = 0; for (long long int i = 1; i <= n; i += 2) { res += fac(i); } return res; } int main(int argc, char const *argv[]) { long long int n; while(scanf("%lld",&n) != EOF) { printf("%lld %lld", facodd(n), facEven(n)); } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef CORS_SUPPORT #include "modules/security_manager/include/security_manager.h" #include "modules/security_manager/src/cors/cors_request.h" #include "modules/security_manager/src/cors/cors_manager.h" #include "modules/security_manager/src/cors/cors_loader.h" #include "modules/security_manager/src/cors/cors_preflight.h" #include "modules/security_manager/src/cors/cors_utilities.h" #include "modules/dom/domutils.h" #include "modules/url/url2.h" #include "modules/url/tools/url_util.h" #include "modules/formats/hdsplit.h" #include "modules/util/tempbuf.h" /* static */ OP_STATUS OpCrossOrigin_Request::Make(OpCrossOrigin_Request *&result, const URL &origin_url, const URL &request_url, const uni_char *method, BOOL with_credentials, BOOL is_anon) { OpCrossOrigin_Request *request = OP_NEW(OpCrossOrigin_Request, (request_url, with_credentials)); OpAutoPtr<OpCrossOrigin_Request> anchor_request(request); RETURN_OOM_IF_NULL(request); RETURN_IF_ERROR(request->method.Set(method)); if (is_anon) RETURN_IF_ERROR(request->origin.Set(UNI_L("null"))); else RETURN_IF_ERROR(OpCrossOrigin_Request::ToOriginString(request->origin, origin_url)); request->is_anonymous = is_anon; request->SetIsSimple(OpCrossOrigin_Utilities::IsSimpleMethod(method)); result = anchor_request.release(); request->origin_url = origin_url; return OpStatus::OK; } OpCrossOrigin_Request::~OpCrossOrigin_Request() { for (unsigned i = 0; i < headers.GetCount(); i++) OP_DELETEA(headers.Get(i)); headers.Clear(); for (unsigned i = 0; i < exposed_headers.GetCount(); i++) OP_DELETEA(exposed_headers.Get(i)); exposed_headers.Clear(); if (loader) loader->DetachRequest(); Out(); } /* static */ OP_STATUS OpCrossOrigin_Request::ToOriginString(OpString &result, const URL &origin_url) { TempBuffer buf; RETURN_IF_ERROR(DOM_Utils::GetSerializedOrigin(origin_url, buf)); RETURN_IF_ERROR(result.Append(buf.GetStorage())); return OpStatus::OK; } OP_STATUS OpCrossOrigin_Request::ToOriginString(OpString &result) { if (is_anonymous) return result.Set(UNI_L("null")); OpString original_url_origin; URL original_url = redirects.GetCount() ? *redirects.Get(0) : url; RETURN_IF_ERROR(OpCrossOrigin_Request::ToOriginString(original_url_origin, original_url)); OpString request_url_origin; RETURN_IF_ERROR(OpCrossOrigin_Request::ToOriginString(request_url_origin, url)); if (original_url_origin.Compare(request_url_origin) != 0) return result.Set("null"); return result.Set(origin); } OP_STATUS OpCrossOrigin_Request::SetMethod(const uni_char *new_method) { RETURN_IF_ERROR(method.Set(new_method)); SetIsSimple(OpCrossOrigin_Utilities::IsSimpleMethod(new_method)); return OpStatus::OK; } OP_STATUS OpCrossOrigin_Request::AddHeader(const char *name, const char *value) { OP_ASSERT(name); uni_char *name_str = NULL; RETURN_IF_ERROR(SetStr(name_str, name)); OpAutoArray<uni_char> anchor_name(name_str); BOOL inserted = FALSE; for (unsigned i = 0; i < headers.GetCount(); i++) { int result = OpCrossOrigin_Utilities::CompareASCIICaseInsensitive(headers.Get(i), name_str, UINT_MAX, TRUE); if (result == 0) return OpStatus::OK; else if (result > 0) { RETURN_IF_ERROR(headers.Insert(i, name_str)); inserted = TRUE; break; } } if (!inserted) RETURN_IF_ERROR(headers.Add(name_str)); anchor_name.release(); if (IsSimple() && !OpCrossOrigin_Utilities::IsSimpleRequestHeader(name_str, value, FALSE)) { if (uni_stri_eq(name_str, "Content-Type")) SetHasNonSimpleContentType(TRUE); SetIsSimple(FALSE); } return OpStatus::OK; } #ifdef SELFTEST void OpCrossOrigin_Request::ClearHeaders() { for (unsigned i = 0; i < headers.GetCount(); i++) OP_DELETEA(headers.Get(i)); headers.Clear(); } #endif // SELFTEST BOOL OpCrossOrigin_Request::CheckRedirect(const URL &moved_to_url) { for (unsigned i = 0; i < redirects.GetCount(); i++) if (*redirects.Get(i) == moved_to_url) return FALSE; return TRUE; } void OpCrossOrigin_Request::SetNetworkError() { status = ErrorNetwork; Out(); } OP_STATUS OpCrossOrigin_Request::AddRedirect(const URL &moved_to_url) { URL *next = OP_NEW(URL, ()); RETURN_OOM_IF_NULL(next); *next = this->url; RETURN_IF_ERROR(redirects.Add(next)); this->url = moved_to_url; return OpStatus::OK; } BOOL OpCrossOrigin_Request::CanExposeResponseHeader(const uni_char *name, unsigned length) { if (length == UINT_MAX) length = uni_strlen(name); /* [CORS: simple response headers] */ if (uni_strnicmp("Cache-Control", name, length) == 0|| uni_strnicmp("Content-Language", name, length) == 0 || uni_strnicmp("Content-Type", name, length) == 0 || uni_strnicmp("Expires", name, length) == 0 || uni_strnicmp("Last-Modified", name, length) == 0|| uni_strnicmp("Pragma", name, length) == 0) return TRUE; for (unsigned i = 0; i < exposed_headers.GetCount(); i++) { int result = OpCrossOrigin_Utilities::CompareASCIICaseInsensitive(exposed_headers.Get(i), name, length, FALSE); if (result == 0) return TRUE; } return FALSE; } OP_STATUS OpCrossOrigin_Request::AddResponseHeader(const uni_char *name, BOOL copy) { OP_ASSERT(name); uni_char *name_str = copy ? UniSetNewStr(name) : const_cast<uni_char *>(name); RETURN_OOM_IF_NULL(name_str); OpAutoArray<uni_char> anchor_name(name_str); if (!copy) anchor_name.release(); BOOL inserted = FALSE; for (unsigned i = 0; i < exposed_headers.GetCount(); i++) { int result = OpCrossOrigin_Utilities::CompareASCIICaseInsensitive(exposed_headers.Get(i), name, UINT_MAX, TRUE); if (result == 0) return OpStatus::OK; else if (result > 0) { RETURN_IF_ERROR(exposed_headers.Insert(i, name_str)); inserted = TRUE; break; } } if (!inserted) RETURN_IF_ERROR(exposed_headers.Add(name_str)); if (copy) anchor_name.release(); return OpStatus::OK; } OP_STATUS OpCrossOrigin_Request::PrepareRequestURL(URL *request_url) { if (request_url) RETURN_IF_ERROR(request_url->SetAttribute(URL::KFollowCORSRedirectRules, URL::CORSRedirectVerify)); else RETURN_IF_ERROR(url.SetAttribute(URL::KFollowCORSRedirectRules, URL::CORSRedirectVerify)); URL_Custom_Header header_item; RETURN_IF_ERROR(header_item.name.Set("Origin")); OpString origin_str; RETURN_IF_ERROR(ToOriginString(origin_str)); RETURN_IF_ERROR(header_item.value.Set(origin_str)); if (request_url) RETURN_IF_ERROR(request_url->SetAttribute(URL::KAddHTTPHeader, &header_item)); else RETURN_IF_ERROR(url.SetAttribute(URL::KAddHTTPHeader, &header_item)); return OpStatus::OK; } /* static */ BOOL OpCrossOrigin_Request::IsSimpleMethod(const uni_char *method) { return OpCrossOrigin_Utilities::IsSimpleMethod(method); } /* static */ BOOL OpCrossOrigin_Request::IsSimpleHeader(const char *name, const char *value) { OpString name_str; RETURN_VALUE_IF_ERROR(name_str.Set(name), FALSE); return OpCrossOrigin_Utilities::IsSimpleRequestHeader(name_str.CStr(), value, FALSE); } #endif // CORS_SUPPORT
#define WIN32_LEAN_AND_MEAN #include "Mutex.h" #include "Semaphore.h" #include "Thread.h" #include "ThreadPoolExecutor.h" // ๆต‹่ฏ•็บฟ็จ‹ๆ•ฐ #define TEST_TREAD_COUNT 20 // ๆฏไธชๆต‹่ฏ•็บฟ็จ‹ๆ•ฐๆทปๅŠ ็š„ไปปๅŠกๆ•ฐ #define TASK_COUNT 100 static int g_totalcount = 0; static int g_seq = 0; // ไฟๅญ˜g_seq CRITICAL_SECTION g_csThreadCode; // ไฟๆŠคๅ…ฑไบซ่ต„ๆบ Mutex g_runmutex; // ่ฟ™้‡Œ็š„ไฝœ็”จ๏ผš้€€ๅ‡บๅพช็Žฏ๏ผŒ็›ธๅฝ“ไบŽไปฅไธชๅ…จๅฑ€ๅธƒๅฐ”ๅ˜้‡ Semaphore g_semFinishFlag; class R :public Runnable { public: ~R() { } void Run() { EnterCriticalSection(&g_csThreadCode); g_seq ++; Sleep(0); printf("Hello World is: %d\n",g_seq); LeaveCriticalSection(&g_csThreadCode); } protected: private: }; DWORD __stdcall WapperFun1(void* arg) { CThreadPoolExecutor* poolmanager = (CThreadPoolExecutor*)arg; if (poolmanager == NULL) return 0; for (int i=0;i<TASK_COUNT;++i) { R* r= new R; g_runmutex.enter(); while(!poolmanager->Execute(r)) { Sleep(100); // ไปปๅŠกๆทปๅŠ ๅคฑ่ดฅ๏ผŒ็ป™็บฟ็จ‹่ฟ่กŒๆ—ถ้—ด๏ผŒ็จๅŽ็ปง็ปญๆทปๅŠ  } g_totalcount++; g_runmutex.leave(); } if (g_totalcount >= TEST_TREAD_COUNT*TASK_COUNT) { g_semFinishFlag.post(); } return 0; } int main() { // ๅˆ›ๅปบ็บฟ็จ‹ๆฑ ๏ผŒๅนถๅˆๅง‹ๅŒ–10ไธชๅทฅไฝœ็บฟ็จ‹ CThreadPoolExecutor* pExecutor = new CThreadPoolExecutor(); pExecutor->Init(10,64,100); InitializeCriticalSection(&g_csThreadCode); // ๆทปๅŠ 20ไธช็บฟ็จ‹ไปปๅŠก HANDLE m_threadId[TEST_TREAD_COUNT] = {0}; for (int cow =0;cow < TEST_TREAD_COUNT;cow ++) { m_threadId[cow] = CreateThread(NULL,0,WapperFun1,pExecutor,0,NULL); } // ๆฏ100ๆฏซ็ง’ๅˆคๆ–ญไธ‹ไปปๅŠกๆ˜ฏๅฆๆ‰ง่กŒๅฎŒๆฏ•ไบ† while(1) { if (g_semFinishFlag.pend(100) <0) { Sleep(10); continue; } else break; } pExecutor->Terminate(); delete pExecutor; DeleteCriticalSection(&g_csThreadCode); getchar(); return 0; }
#include<bits/stdc++.h> using namespace std; typedef long long ll; //dp[i][j] is the min cost to reach ith station from 0th station within time j. vector<vector<ll>> dp(100,vector<ll>(251,-1)); vector<vector<ll>> ti(100,vector<ll>(100,-1)); vector<vector<ll>> risk(100,vector<ll>(100,-1)); ll n; ll dp_rec(ll nn,ll t){ if(t<0) return INT_MAX; if(dp[nn][t]!=-1) return dp[nn][t]; dp[nn][t] = dp_rec(nn,t-1); for(ll i=0;i<n;i++){ if(t-ti[i][nn]>=0){ dp[nn][t] = min(dp[nn][t], dp_rec(i,t-ti[i][nn]) + risk[i][nn]); } } return dp[nn][t]; } int main(){ ll k; cin>>k; while(k--){ ll t; cin>>n>>t; for(ll i=0;i<n;i++){ for(ll j=0;j<n;j++){ cin>>ti[i][j]; } } for(ll i=0;i<n;i++){ for(ll j=0;j<n;j++){ cin>>risk[i][j]; } } //resetting dp after each iteration for(ll i=0;i<100;i++){ for(ll j=0;j<251;j++){ dp[i][j] = -1; } } //A base case. for(ll i=0;i<251;i++){ dp[0][i] = 0; } ll ans = dp_rec(n-1,t); if(ans==INT_MAX){ cout<<"-1"<<endl; continue; } ll ans2=0; for(ll i=0;i<=t;i++){ if(dp[n-1][i]==ans){ ans2=i; break; } } cout<<ans<<" "<<ans2<<endl; } }
#include "particle.h" #include "../utils/timer.h" #include "../camera/raw_camera.h" bool sloth::Particle::update(const RawCamera &camera) { float deltaTime = static_cast<float>(Timer::deltaFrameTime); m_Velocity.y += PLAYER_GRAVITY * m_GravityEffect * deltaTime; m_Position += m_Velocity * deltaTime; m_ElapsedTime += deltaTime; m_Distance = glm::length(camera.getPosition() - m_Position); updateTextureCoordInfo(); return m_ElapsedTime < m_LifeLength; } void sloth::Particle::updateTextureCoordInfo() { float lifeFactor = m_ElapsedTime / m_LifeLength; unsigned int stageCount = m_Texture.getNumberOfRows() * m_Texture.getNumberOfRows(); // ่Žทๅ–ๆ‰€ๆœ‰็บน็†้›†็š„ไธชๆ•ฐ float atlasProgression = lifeFactor * stageCount; // ๅฝ“ๅ‰ๅค„็†็š„็บน็†ๅบๅท unsigned int indexNow = static_cast<unsigned int>(glm::floor(atlasProgression)); unsigned int indexNext = indexNow < stageCount - 1 ? indexNow + 1 : indexNow; m_BlendFactor = std::fmodf(atlasProgression, 1.0f); // ๆ นๆฎๆ—ถ้—ดๅ†ไธคไธช็Šถๆ€้—ด่ฟ›่กŒๆ’ๅ€ผ setTextureOffset(m_TexOffsetNow, indexNow); setTextureOffset(m_TexOffsetNext, indexNext); } void sloth::Particle::setTextureOffset(glm::vec2 & offset, unsigned int index) { unsigned int column = index % m_Texture.getNumberOfRows(); unsigned int row = index / m_Texture.getNumberOfRows(); offset.x = static_cast<float>(column) / m_Texture.getNumberOfRows(); offset.y = static_cast<float>(row) / m_Texture.getNumberOfRows(); }
/* BEGIN LICENSE */ /***************************************************************************** * SKFind : the SK search engine * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: hiliter.cpp,v 1.15.4.7 2005/02/21 14:22:44 krys Exp $ * * Authors: Mathieu Poumeyrol <poumeyrol @at@ idm .dot. fr> * Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr> * * 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #include <skfind/skfind.h> #include "hiliter.h" SK_REFCOUNT_IMPL_DEFAULT(SKHiliter) SKERR SKHiliter::SetValues(const PRUint32* pValues, PRUint32 lValuesCount) { if(m_pValues) delete[] m_pValues; if((m_lValuesCount = lValuesCount)) { m_pValues = new PRUint32[m_lValuesCount]; if(m_pValues && pValues) memcpy(m_pValues, pValues, m_lValuesCount * sizeof(PRUint32)); else return SKError(err_failure, "[SKHiliter::SetValues] Invalid arguments."); } return noErr; } SKHiliter::~SKHiliter() { if(m_pValues) delete[] m_pValues; if(m_pszStartFrom) PL_strfree(m_pszStartFrom); if(m_pszStartTo) PL_strfree(m_pszStartTo); if(m_pszStopFrom) PL_strfree(m_pszStopFrom); if(m_pszStopTo) PL_strfree(m_pszStopTo); } SKERR SKHiliter::SetStartStrings(const char* pszStartFrom, const char* pszStartTo, PRInt32 iStartOccPos) { if(m_pszStartFrom) PL_strfree(m_pszStartFrom); if(m_pszStartTo) PL_strfree(m_pszStartTo); m_pszStartFrom = PL_strdup(pszStartFrom); m_pszStartTo = PL_strdup(pszStartTo); m_lStartFromLen = PL_strlen(pszStartFrom); m_lStartToLen = PL_strlen(pszStartTo); if(iStartOccPos <= (PRInt32)m_lStartToLen) m_iStartOccPos = iStartOccPos; else m_iStartOccPos = -1; return (m_pszStartFrom && m_pszStartTo) ? noErr : err_failure; } SKERR SKHiliter::SetStopStrings(const char* pszStopFrom, const char* pszStopTo, PRInt32 iStopOccPos) { if(m_pszStopFrom) PL_strfree(m_pszStopFrom); if(m_pszStopTo) PL_strfree(m_pszStopTo); m_pszStopFrom = PL_strdup(pszStopFrom); m_pszStopTo = PL_strdup(pszStopTo); m_lStopFromLen = PL_strlen(pszStopFrom); m_lStopToLen = PL_strlen(pszStopTo); if(iStopOccPos <= (PRInt32)m_lStopToLen) m_iStopOccPos = iStopOccPos; else m_iStopOccPos = -1; return (m_pszStopFrom && m_pszStopTo) ? noErr : err_failure; } SKERR SKHiliter::FilterData(const void* pData, PRUint32 lSize) { if( !m_pszStartFrom || !m_pszStartFrom || !m_pszStopTo || !m_pszStopFrom || (((char*)pData)[lSize - 1] != '\0') || (PL_strlen((char*)pData) + 1 != lSize)) { return err_failure; } PRInt32 lDiff = 0; if((m_lStartToLen - m_lStartFromLen) > 0) lDiff += m_lStartToLen - m_lStartFromLen; if((m_lStopToLen - m_lStopFromLen) > 0) lDiff += m_lStopToLen - m_lStopFromLen; if(m_iStartOccPos >= 0) lDiff += 10; if(m_iStopOccPos >= 0) lDiff += 10; SKERR err; if(lDiff > 0) err = Realloc(lSize + lDiff * m_lValuesCount); else err = Realloc(lSize); if(err != noErr) return err; m_lSize = 0; char* pszFrom = (char*)pData; char* pszTo = (char*)m_pData; char* psz = PL_strstr(pszFrom, m_pszStartFrom); PRUint32 i = 0, lPos = 0; while(psz) { // Copy the string before PRUint32 len = psz - pszFrom; PL_strncpy(pszTo, pszFrom, len); pszTo += len; pszFrom = psz + m_lStartFromLen; m_lSize += len; // Copy m_pszStartTo if needed if((i < m_lValuesCount) && (lPos == m_pValues[i])) { if(m_iStartOccPos >= 0) { SK_ASSERT(m_iStartOccPos <= (PRInt32)m_lStartToLen); PL_strncpy(pszTo, m_pszStartTo, m_iStartOccPos); pszTo += m_iStartOccPos; len = sprintf(pszTo, "%u", lPos); pszTo += len; PL_strncpy(pszTo, m_pszStartTo + m_iStartOccPos, m_lStartToLen - m_iStartOccPos); pszTo += m_lStartToLen - m_iStartOccPos; m_lSize += len + m_lStartToLen; } else { PL_strncpy(pszTo, m_pszStartTo, m_lStartToLen); pszTo += m_lStartToLen; m_lSize += m_lStartToLen; } } // Find m_pszStopFrom psz = PL_strstr(psz, m_pszStopFrom); if(!psz) break; // Copy the content len = psz - pszFrom; PL_strncpy(pszTo, pszFrom, len); pszTo += len; pszFrom = psz + m_lStopFromLen; m_lSize += len; // Copy m_pszStopTo if needed if((i < m_lValuesCount) && (lPos == m_pValues[i])) { if(m_iStopOccPos >= 0) { SK_ASSERT(m_iStopOccPos <= (PRInt32)m_lStopToLen); PL_strncpy(pszTo, m_pszStopTo, m_iStopOccPos); pszTo += m_iStopOccPos; len = sprintf(pszTo, "%u", lPos); pszTo += len; PL_strncpy(pszTo, m_pszStopTo + m_iStopOccPos, m_lStopToLen - m_iStopOccPos); pszTo += m_lStopToLen - m_iStopOccPos; m_lSize += len + m_lStopToLen; } else { PL_strncpy(pszTo, m_pszStopTo, m_lStopToLen); pszTo += m_lStopToLen; m_lSize += m_lStopToLen; } ++i; } // Find m_pszStartFrom psz = PL_strstr(psz, m_pszStartFrom); ++lPos; } PRUint32 len = lSize - (pszFrom - (char*)pData); SK_ASSERT(pszFrom[len - 1] == '\0'); PL_strncpy(pszTo, pszFrom, len); m_lSize += len; return (i == m_lValuesCount) ? noErr : err_failure; } SKERR skFilterHilite(SKBinary *pContent, SKCursor *pPositions, const char *pcszStartTag, const char *pcszStopTag, SKBinary **ppTo) { if( pContent == NULL || pPositions == NULL || ppTo == NULL ) return err_invalid; PRUint32 iCount; SKERR err = pPositions->GetCount(&iCount); if( err != noErr ) return err; SKHiliter* pHlt = sk_CreateInstance(SKHiliter)(); if( pHlt == NULL ) return err_invalid; // Get the strings right char* pcStartTag = PR_smprintf("<a name=\"skhlt_\"></a>%s", pcszStartTag); pHlt->SetStartStrings("<?SK W?>", pcStartTag, 15); PR_smprintf_free(pcStartTag); pHlt->SetStopStrings("<?SK /W?>", pcszStopTag, -1); err = pHlt->SetValues( pPositions->GetSharedCursorDataRead(), iCount ); if( err != noErr ) { sk_DeleteInstance( pHlt ); return err; } // pass the data to the hiliter if( ((char *)pContent->GetSharedData())[pContent->GetSize() - 1] == '\0' ) { err = pHlt->FilterData( pContent->GetSharedData(), pContent->GetSize() ); } else { char *pBinData = (char *)PR_Malloc( (pContent->GetSize() + 1) * sizeof(char) ); if( pBinData != NULL ) { memcpy(pBinData, pContent->GetSharedData(), pContent->GetSize() * sizeof(char)); pBinData[pContent->GetSize()] = '\0'; err = pHlt->FilterData(pBinData, pContent->GetSize() + 1); PR_Free(pBinData); } else err = err_memory; } if( err != noErr ) { sk_DeleteInstance( pHlt ); return err; } // create a new binary to return (I know this copy could be avoided) //*ppTo = sk_CreateInstance(SKBinary)(hlt); *ppTo = pHlt; return noErr; }
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; int main(){ int r,d,x; cin >> r >> d >> x; vector<int>A(10); A[0] = x; for(int i = 1; i <= 10; i++){ A[i] = A[i-1] * r - d; cout << A[i] << endl; } return 0; }
#include <vector> #include <cmath> #include "tgaimage.h" #include "geometry.h" #include "line.h" #include "model.h" #include "triangle.h" #include "colors.h" Model *model = NULL; const int width = 800; const int height = 800; int main(int argc, char** argv) { TGAImage image(width, height, TGAImage::RGB); Vec2i t0[3] = {Vec2i(10, 70), Vec2i(50,160), Vec2i(70, 80)}; Vec2i t1[3] = {Vec2i(180, 50), Vec2i(150,1), Vec2i(70, 180)}; Vec2i t2[3] = {Vec2i(180, 150), Vec2i(120,160), Vec2i(130, 180)}; Vec2i t3[3] = {Vec2i(180, 150), Vec2i(100,80), Vec2i(100, 90)}; triangle(t0[0], t0[1], t0[2], image, red); triangle(t1[0], t1[1], t1[2], image, white); triangle(t2[0], t2[1], t2[2], image, green); triangle(t3[0], t3[1], t3[2], image, blue); image.flip_vertically(); // i want to have the origin at the left bottom corner of the image image.write_tga_file("output.tga"); return 0; }
#ifndef __LMENGINE__ #define __LMENGINE__ #include <Windows.h> #include <Leap.h> #include "..\EngineLib\LMEngineDevice.h" #include "..\EngineLib\EngineCommon.h" class LMENGINE : public LMENGINEDEVICE { private: HWND hwnd; Leap::Controller ctrl; unsigned char init=0; GLVECTOR2 start; GLVECTOR2 last; bool first = true; public: LMENGINE(HWND hwnd) : ctrl() { this->hwnd = hwnd; last.x = 0; last.y = 0; } virtual unsigned char LMRefresh(); virtual void Reset(); virtual GLVECTOR2 LMGetVector(); virtual bool initLM(); ~LMENGINE(); }; #endif
// Created on: 1993-03-10 // Created by: JCV // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Geom_CartesianPoint_HeaderFile #define _Geom_CartesianPoint_HeaderFile #include <Standard.hxx> #include <gp_Pnt.hxx> #include <Geom_Point.hxx> #include <Standard_Real.hxx> class gp_Trsf; class Geom_Geometry; class Geom_CartesianPoint; DEFINE_STANDARD_HANDLE(Geom_CartesianPoint, Geom_Point) //! Describes a point in 3D space. A //! Geom_CartesianPoint is defined by a gp_Pnt point, //! with its three Cartesian coordinates X, Y and Z. class Geom_CartesianPoint : public Geom_Point { public: //! Returns a transient copy of P. Standard_EXPORT Geom_CartesianPoint(const gp_Pnt& P); //! Constructs a point defined by its three Cartesian coordinates X, Y and Z. Standard_EXPORT Geom_CartesianPoint(const Standard_Real X, const Standard_Real Y, const Standard_Real Z); //! Assigns the coordinates X, Y and Z to this point. Standard_EXPORT void SetCoord (const Standard_Real X, const Standard_Real Y, const Standard_Real Z); //! Set <me> to P.X(), P.Y(), P.Z() coordinates. Standard_EXPORT void SetPnt (const gp_Pnt& P); //! Changes the X coordinate of me. Standard_EXPORT void SetX (const Standard_Real X); //! Changes the Y coordinate of me. Standard_EXPORT void SetY (const Standard_Real Y); //! Changes the Z coordinate of me. Standard_EXPORT void SetZ (const Standard_Real Z); //! Returns the coordinates of <me>. Standard_EXPORT void Coord (Standard_Real& X, Standard_Real& Y, Standard_Real& Z) const Standard_OVERRIDE; //! Returns a non transient cartesian point with //! the same coordinates as <me>. Standard_EXPORT gp_Pnt Pnt() const Standard_OVERRIDE; //! Returns the X coordinate of <me>. Standard_EXPORT Standard_Real X() const Standard_OVERRIDE; //! Returns the Y coordinate of <me>. Standard_EXPORT Standard_Real Y() const Standard_OVERRIDE; //! Returns the Z coordinate of <me>. Standard_EXPORT Standard_Real Z() const Standard_OVERRIDE; //! Applies the transformation T to this point. Standard_EXPORT void Transform (const gp_Trsf& T) Standard_OVERRIDE; //! Creates a new object which is a copy of this point. Standard_EXPORT Handle(Geom_Geometry) Copy() const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(Geom_CartesianPoint,Geom_Point) protected: private: gp_Pnt gpPnt; }; #endif // _Geom_CartesianPoint_HeaderFile
#include "nftcenter.hpp" void nftcenter::cancelauc(name seller, uint64_t order_id) { require_auth(seller); chis_table chistable(_code, _code.value); auto iterator = chistable.find(seller.value); if (iterator == chistable.end()) { chistable.emplace(seller, [&](auto& row) { row.seller = seller; row.order_id = order_id; }); } else { std::string changes; chistable.modify(iterator, seller, [&](auto& row) { row.seller = seller; row.order_id = order_id; }); } // eosio_assert(false, "welcome to nft center : cancelauc"); } EOSIO_DISPATCH( nftcenter, (cancelauc))
#pragma once #include <vector> #include "ref_count.h" #include "bitmap.h" #include "sprite.h" class SpritePool; class SpriteResource; class SpriteProperty; class CartFile; class Buffer; class Animation { public: Animation(); ~Animation(); /* Draw the current sprite frame on a surface */ bool Draw(BitmapSurface& surface, int to_x, int to_y, int from_x, int from_y); bool DrawDC(HDC hdc, int to_x, int to_y, int from_x, int from_y); bool DrawSelection(BitmapSurface& surface, int x, int y); void SetFrame(UINT nFrame); bool NextFrame(); bool Load(Buffer& src_buf, SpritePool& sprites, UINT anim_id, UINT pal_id); bool LoadStatic(Buffer& src_buf, SpritePool& sprites, UINT sprite_id, UINT pal_id); /* Load an animation from a sprite graphics */ bool LoadFromProperty(Buffer& src_buf, SpritePool& sprites, SpriteProperty& prop); Ref<SpriteResource> GetCurrentSprite(); virtual bool IntersectBox(RECT& box); virtual bool IntersectPoint(POINT& pt); const RECT& GetBoundingBox() const; private: bool flip_horz_; bool flip_vert_; /* Calculates the frame count */ void UpdateFrameCount(); void IncreaseFrame(); UINT anim_id_; /* Current sprite index to display */ UINT frame_index_; UINT counter_; /* Count of frames */ UINT frame_count_; typedef struct { UINT duration; // Duration of this frame Ref<SpriteResource> sprite; // Sprite to display } Frame; RECT base_; Frame& GetCurrentFrame(); std::vector<Frame> frames_; }; class AnimationRef : public Animation, public RefCount { public: }; class AnimationPool : ResourcePool<AnimationRef> { public: AnimationPool(CartFile& cart, SpritePool& sprites); virtual bool OnResourceAlloc(DWORD id, AnimationRef* resource); private: CartFile& cart_; SpritePool& sprites_; };
// // Ripple.cpp // w07_h01_ripple // // Created by Kris Li on 10/17/16. // // #include "Ripple.hpp" Ripple::Ripple(){ init(ofPoint(100,100)); num = 20; radius = 0; opacity = 100; theta = 0; } void Ripple::init(ofPoint _pos){ pos.set(_pos.x, _pos.y); } void Ripple::update(vector<Ripple> *ripples, float _wave){ pos += vel; vel += acc; radius++; if(radius > 400){ opacity --; } theta += PI/_wave; // if(pos.x + radius > ) // opacity = collide(ripples); } void Ripple::addForce(ofPoint _acc){ vel += _acc; } float Ripple::collide(vector<Ripple> *ripples){ for(int i =0; i<ripples->size(); i++){ if(&(*ripples)[i] ==this){ continue; } float dist = ofDist(pos.x, pos.y, (*ripples)[i].pos.x,(*ripples)[i].pos.y); float waveRadius = radius + (*ripples)[i].radius; float overlap = waveRadius - dist; if(overlap>0 && overlap<200){ float opacity_collide = ofMap(overlap, 0, 200, 100, 0); return opacity_collide; } else { continue; } } } void Ripple::draw(int _rippleM){ ofNoFill(); ofSetLineWidth(2); ofSetColor(172, 240, 242,opacity); for(int i =0; i<num; i++){ pos.z = sin(theta*i)*5; size =i*i*i/_rippleM+radius; ofDrawEllipse(pos.x, pos.y,pos.z,size,size); } }
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; // Author: Tatparya Shankar int main() { int n; cin >> n; // Get fractions int element; int neg = 0; int pos = 0; int zero = 0; for( int i = 0; i < n; i ++ ) { cin >> element; if( element < 0 ) { neg++; } else if( element == 0 ) { zero++; } else { pos++; } } // Get fractions printf( "%0.3f\n%0.3f\n%0.3f\n", (float) pos / n, (float) neg / n, (float) zero / n ); }
#include <iostream> #include <vector> #include <unistd.h> #include <sys/wait.h> #include <stdlib.h> #include "eNFA-to-NFA.h" #include "NFA-to-DFA.h" int main(){ int states, transitions; std::cout << "Enter No of States: "; std::cin >> states; std::cout << "Enter No of Transitions: "; std::cin >> transitions; eNFAtoNFA n1(states, transitions); std::cout << "Enter Transition Matrix: "; n1.setENFA(); n1.getENFA(); std::cout << "Enter Final States: "; n1.setFinalStates(); std::cout << "-------------------" << std::endl; n1.getStates(); n1.getTransition(); std::cout << "NFA: " << std::endl; n1.convert(); n1.printNFA(); NFAtoDFA d1(states, transitions); d1.convert(n1.getTransitionsMatrix(), n1.getMapToTransitions(), n1.getNFA()); std::cout << "\nDFA" << std::endl; d1.getDFA(); d1.writeToDotFile(n1.getFinalStates()); if (!fork()){ execlp("dot", "dot", "-Tpng", "tests/fa.dot", "-o", "tests/dp.png", (char *)NULL); exit(0); } return 0; }
#ifndef _ANIMAL_H_ #define _ANIMAL_H_ #include <iostream> //std class Animal{ public: Animal(); Animal(std::string name, char mark, int* pattern, int size, int position); ~Animal(); void setPatternAndLength(int* pattern, int size); void setMark(char mark); void setName(std::string name); void setPosition(int position); int* getPattern() const; int getPatternLength() const; int getPosition() const; std::string getName() const; void move(); char getMark() const; virtual void showExcitement() const; private: int patternLength;// length of race is constant. int* pattern; int position; char mark; std:: string name; }; #endif
//Paul Schakel //Variable LED Blinker //This code makes an LED blink at a rate starting at once every 4 seconds and decreasing in an increment //of .2 seconds each time until it reaches .2 seconds between each blink. // A variable is a sort of container for a value. //You can use variables in a loop to plug different values into the same block of code int ledPin1 = 13; int ledPin2 = 12; int delayVar1 = 2000; int delayVar2; void setup() { // Code inside the setup function runs once. Serial.begin(9600); pinMode(ledPin1, OUTPUT); pinMode(ledPin2, OUTPUT); } void loop() { // code inside the loop function runs forever, repeatedly while (true){ digitalWrite(ledPin1, HIGH); delay(delayVar1); digitalWrite(ledPin1, LOW); delay(delayVar1); Serial.println(delayVar1); delayVar1 -= 200; if (delayVar1 <= 200){ delayVar2 = 200; break; } } while (true){ digitalWrite(ledPin2, HIGH); delay(delayVar2); digitalWrite(ledPin2, LOW); delay(delayVar2); Serial.println(delayVar2); delayVar2 += 200; if (delayVar2 >= 2000){ delayVar1 = 2000; break; } } }
/****************************************************************************** * * * Copyright 2018 Jan Henrik Weinstock * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * ******************************************************************************/ #ifndef VCML_STUBS_H #define VCML_STUBS_H #include "vcml/common/types.h" #include "vcml/common/report.h" #include "vcml/common/systemc.h" namespace vcml { class initiator_stub: public sc_module { private: initiator_stub(); initiator_stub(const initiator_stub&); void invalidate_direct_mem_ptr(sc_dt::uint64 start, sc_dt::uint64 end); public: simple_initiator_socket<initiator_stub> OUT; initiator_stub(const sc_module_name&); virtual ~initiator_stub(); VCML_KIND(initiator_stub); }; class target_stub: public sc_module { private: target_stub(); target_stub(const target_stub&); void b_transport(tlm_generic_payload&, sc_time&); unsigned int transport_dbg(tlm_generic_payload&); public: simple_target_socket<target_stub> IN; target_stub(const sc_module_name&); virtual ~target_stub(); VCML_KIND(target_stub); }; } #endif
#pragma once #include "AllowWindowsPlatformTypes.h" #include <strsafe.h> #include <thread> #include <mutex> #include <condition_variable> #include <queue> #include <algorithm> #include "HideWindowsPlatformTypes.h" //template<typename Data> class ThreadSafeQueue { private: //std::queue<Data> queue; //std::condition_variable conditionVariable; mutable std::mutex mutex; char* data = 0; int bytesLeft = 0; public: void enqueue(const char* newData, const int byteCount) { std::unique_lock < std::mutex > lock(mutex); int newSize = byteCount + bytesLeft; data = (char*)realloc(data, newSize); memcpy(data + bytesLeft, newData, byteCount); //remember to free newData in the calling function bytesLeft += byteCount; } bool empty() const { std::unique_lock < std::mutex > lock(mutex); return bytesLeft == 0; //return queue.empty(); } /* void waitForData() { if (!empty()) return; std::unique_lock < std::mutex > lock(mutex); conditionVariable.wait(lock, [this] { return bytesLeft != 0; }); } */ int dequeue(int byteCount, char** chunk) { std::unique_lock < std::mutex > lock(mutex); if (byteCount == 0 || bytesLeft == 0) { return 0; } int bytesToCopy = std::min(bytesLeft, byteCount); *chunk = new char[bytesToCopy]; memcpy(*chunk, data, bytesToCopy); char* newPos = data + bytesToCopy; bytesLeft -= bytesToCopy; memcpy(data, newPos, bytesLeft); data = (char*)realloc(data, bytesLeft); return bytesToCopy; } };
//--------------------------------------------------------------------------- #ifndef DLaboralesH #define DLaboralesH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <ComCtrls.hpp> //--------------------------------------------------------------------------- class TForm3 : public TForm { __published: // IDE-managed Components TLabel *Label1; TComboBox *ComboBox1; TLabel *Label2; TEdit *Edit1; TLabel *Label3; TEdit *Edit2; TLabel *Label4; TMemo *Memo1; TLabel *Label5; TMemo *Memo2; TLabel *Label6; TLabel *Label7; TDateTimePicker *DateTimePicker1; TEdit *Edit3; TButton *Button2; void __fastcall Button2Click(TObject *Sender); private: // User declarations public: // User declarations __fastcall TForm3(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TForm3 *Form3; //--------------------------------------------------------------------------- #endif
#include "scriptObject.h" scriptObject::scriptObject() {} int scriptObject::GetR() { return m_r; } int scriptObject::GetG() { return m_g; } int scriptObject::GetB() { return m_b; } float scriptObject::GetLenght() { return m_length; } float scriptObject::GetWidth() { return m_width; } void scriptObject::SetR(int val) { this->m_r = val; } void scriptObject::SetG(int val) { this->m_g = val; } void scriptObject::SetB(int val) { this->m_b = val; } void scriptObject::SetLength(float val) { this->m_length = val; } void scriptObject::SetWidth(float val) { this->m_width = val; }
#pragma once #include <memory> #include <vector> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <list> #include <string> #include <queue> #include <array> namespace Rocket { template <typename Base, typename T> static bool InstanceOf (const T *) { return std::is_base_of<Base, T>::value; } template <typename T> //using Scope = std::unique_ptr<T, std::function<void(T*)>>; using Scope = std::unique_ptr<T>; template <typename T> using Ref = std::shared_ptr<T>; template <typename T> using StoreRef = std::weak_ptr<T>; template <typename T, typename... Arguments> constexpr Ref<T> CreateRef(Arguments ... args) { Ref<T> ptr = Ref<T>( new T(args...) //new (RK_ALLOCATE_CLASS(T)) T(args...)//, [](T* ptr) { RK_DELETE(T, ptr); } ); return std::move(ptr); } template <typename T, typename... Arguments> constexpr Scope<T> CreateScope(Arguments ... args) { Scope<T> ptr = Scope<T>( new T(args...) //new (RK_ALLOCATE_CLASS(T)) T(args...)//, [](T* ptr) { RK_DELETE(T, ptr); } ); return std::move(ptr); } template <typename T> using Vec = std::vector<T>; template <typename T1, typename T2> using Map = std::map<T1, T2>; template <typename T1, typename T2> using UMap = std::unordered_map<T1, T2>; template <typename T1, auto T2> using Array = std::array<T1, T2>; template <typename T> using List = std::list<T>; template <typename T> using Queue = std::queue<T>; template <typename T> using Set = std::set<T>; template <typename T> using USet = std::unordered_set<T>; using String = std::string; } // namespace Rocket
// // Copyright (c) 2011 Bryce Lelbach // Copyright (c) 2011-2012 Hartmut Kaiser // Copyright (c) 2010 Artyom Beilis (Tonkikh) // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include <pika/config.hpp> #include <cstddef> #include <iosfwd> #include <string> #include <vector> /////////////////////////////////////////////////////////////////////////////// namespace pika::debug::detail { namespace stack_trace { PIKA_EXPORT std::size_t trace(void** addresses, std::size_t size); PIKA_EXPORT void write_symbols(void* const* addresses, std::size_t size, std::ostream&); PIKA_EXPORT std::string get_symbol(void* address); PIKA_EXPORT std::string get_symbols(void* const* address, std::size_t size); } // namespace stack_trace class backtrace { public: explicit backtrace(std::size_t frames_no = PIKA_HAVE_THREAD_BACKTRACE_DEPTH) { if (frames_no == 0) return; frames_no += 2; // we omit two frames from printing frames_.resize(frames_no, nullptr); std::size_t size = stack_trace::trace(&frames_.front(), frames_no); if (size != 0) frames_.resize(size); } virtual ~backtrace() noexcept {} std::size_t stack_size() const { return frames_.size(); } void* return_address(std::size_t frame_no) const { if (frame_no < stack_size()) return frames_[frame_no]; return nullptr; } void trace_line(std::size_t frame_no, std::ostream& out) const { if (frame_no < frames_.size()) stack_trace::write_symbols(&frames_[frame_no], 1, out); } std::string trace_line(std::size_t frame_no) const { if (frame_no < frames_.size()) return stack_trace::get_symbol(frames_[frame_no]); return std::string(); } std::string trace() const { if (frames_.empty()) return std::string(); return stack_trace::get_symbols(&frames_.front(), frames_.size()); } void trace(std::ostream& out) const { if (frames_.empty()) return; stack_trace::write_symbols(&frames_.front(), frames_.size(), out); } private: std::vector<void*> frames_; }; class trace_manip { public: trace_manip(backtrace const* tr) : tr_(tr) { } std::ostream& write(std::ostream& out) const { if (tr_) tr_->trace(out); return out; } private: backtrace const* tr_; }; inline std::ostream& operator<<(std::ostream& out, trace_manip const& t) { return t.write(out); } template <typename E> inline trace_manip trace(E const& e) { backtrace const* tr = dynamic_cast<backtrace const*>(&e); return trace_manip(tr); } inline std::string trace(std::size_t frames_no = PIKA_HAVE_THREAD_BACKTRACE_DEPTH) //-V659 { return backtrace(frames_no).trace(); } } // namespace pika::debug::detail
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPushButton> #include <QLineEdit> #include "quitwindow.h" #include "datewindow.h" #include "directorywindow.h" #include "helpwindow.h" #include "pcbwindow.h" #include "processschedulers.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void quitClicked(); void dateClicked(); void helpClicked(); void directoryClicked(); void pcbToolsClicked(); private: Ui::MainWindow *ui; QPushButton *dateDisplayButton, *directoryDisplayButton, *helpButton, *quitButton, *pcbToolButton; QLineEdit *helpLineEdit; quitWindow exitWindow; dateWindow dateShower; directoryWindow directoryShower; //helpWindow helpShower; pcbWindow pcbTools; }; #endif // MAINWINDOW_H
#include <iostream> using namespace std; int mdc(int , int); int main() { int a, b, divisor; cin >> a >> b; int menor = ( a<b ? a : b ); int maior = ( a>b ? a : b ); divisor = mdc(maior,menor); cout << divisor << endl; return 0; } int mdc(int maior, int menor) { if (menor == 0) return maior; else return mdc(menor, maior%menor); }
/** * Copyright (C) Omar Thor, Aurora Hernandez - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * * Written by * Omar Thor <omar@thorigin.com>, 2018 * Aurora Hernandez <aurora@aurorahernandez.com>, 2018 */ #ifndef DMTK_ALGORITHM_HMM_MODEL_DETAIL_MODEL_HPP #define DMTK_ALGORITHM_HMM_MODEL_DETAIL_MODEL_HPP #include <unordered_map> #include <algorithm> #include <cmath> #include <functional> DMTK_DETAIL_NAMESPACE_BEGIN /** * \brief Convert probability map to log2 based */ template<typename State, typename Emission, typename Prob> void hmm_probability_map_to_log2(std::unordered_map<State, std::unordered_map<Emission, Prob>>& probs) { for(auto& v : probs) { std::for_each(v.second.begin(), v.second.end(), [](auto& pair) { pair.second = std::log2(pair.second); }); } } /** * \brief Convert transition map to log2 based */ template<typename TransititionMap> void hmm_transition_map_to_log2(TransititionMap& trans) { std::for_each(trans.begin(), trans.end(), [](auto& pair) { pair.second = std::log2(pair.second); }); } /** * \brief Convert transition map to log2 based */ template<typename StartingProbs> void hmm_starting_probs_to_log2(StartingProbs& starting) { std::for_each(starting.begin(), starting.end(), [](auto& pair) { pair.second = std::log2(pair.second); }); } /** * Construct the default starting probabilities vector */ template<typename State, typename Emission, typename Prob = double> std::unordered_map<State, Prob> hmm_default_starting_probs(std::unordered_map<State, std::unordered_map<Emission, Prob>> emission_probs) { const auto states_count = emission_probs.size(); std::unordered_map<State, Prob> start_probs(emission_probs.size()); for(auto& p : emission_probs) { start_probs.emplace(p.first, 1.0f / states_count); } return start_probs; } /** * Provides way to make pluggable log(p(x)) calculations */ template<bool Logarithmic> struct hmm_probability_scale; /** * \brief Partial specialization of hmm_probability_scale which defaults to * default numeric scale */ template<> struct hmm_probability_scale<false> { template<typename ProbabilityMap, typename TransitionMap, typename StartingProbs> hmm_probability_scale(ProbabilityMap&, TransitionMap&, StartingProbs&) {} template<typename LHS, typename RHS> inline auto mul(const LHS& lhs, const RHS& rhs) { return lhs * rhs; } template<typename T> inline auto p_of(const T& value) { return value; } }; /** * \brief Partial specialization of hmm_probability_scale which treats * multiplication as additions */ template<> struct hmm_probability_scale<true> { template<typename ProbabilityMap, typename TransitionMap, typename StartingProbs> hmm_probability_scale(ProbabilityMap& pm, TransitionMap& tm, StartingProbs& sp) { hmm_probability_map_to_log2(pm); hmm_transition_map_to_log2(tm); hmm_starting_probs_to_log2(sp); } template<typename LHS, typename RHS> auto mul(const LHS& lhs, const RHS& rhs) { return lhs + rhs; } template<typename T> auto p_of(const T& value) { return value; } }; /** * \brief Validates the size and shapes of parameters of hmm functions * */ template<typename EmissionProbMap, typename TransitionProbMap, typename Starting> void hmm_validate_parameters( EmissionProbMap& emission_probs, TransitionProbMap& transmissin_probs, Starting& starting_probs) { const auto nr_of_states = emission_probs.size(); const auto nr_of_transitions = transmissin_probs.size(); auto nr_of_emission_probs = 0; for(auto& kv : emission_probs) { nr_of_emission_probs += kv.second.size(); } const auto nr_of_starting = starting_probs.size(); BOOST_ASSERT_MSG(nr_of_emission_probs > 0, "Emission observations probability map input must not be empty"); BOOST_ASSERT_MSG(nr_of_transitions > 0, "Transition probability map input must not be empty"); BOOST_ASSERT_MSG(nr_of_starting > 0, "Starting probability vector input must not be empty"); BOOST_ASSERT_MSG(nr_of_emission_probs > 0, "Emission probability map input must not be empty"); BOOST_ASSERT_MSG( nr_of_states == nr_of_starting, "Number of starting possibilities is equal to the number of states" ); } DMTK_DETAIL_NAMESPACE_END #endif /* DMTK_ALGORITHM_HMM_MODEL_DETAIL_MODEL_HPP */
/* * (C) Copyright 2016-2018 Ben Karsin, Nodari Sitchinava * * 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. * */ /* This file is where you define the datatype and comparison operator to sort the given input data. */ #define DATATYPE int // Datatype to sort #define CASTTYPE int // Datatype to cast key to in order to use __shfl() // Define MAX_INT and MIN_INT as maximum and minimum key values // FOR INTEGERS #define MAXVAL 2147483647 #define MINVAL -2147483647 // FOR LONGS //#define MAXVAL 0x0000ffff00000001 //#define MINVAL 0x000000010000ffff // Define abstract format of comparison function typedef int(*fptr_t)(DATATYPE, DATATYPE); // Comparison function used to sort by. // Edit this to be whatever comparison function is needed. template<typename T> __forceinline__ __device__ int cmp(T a, T b) { return a < b; // Basic less than comparison // L1-norm (manhattan distance) // return ((((int)a)+(int)(a>>32)) < (((int)b)+(int)(b>>32))); // L1-norm (manhattan distance) // Comparison of fractional values without loss of precision // return (((int)(a>>32)*(int)b) < (((int)(b>>32))*(int)a)); } // Host comparison function to check correctness when debugging template<typename T> __forceinline__ int host_cmp(T a, T b) { return a < b; } /******************************************************************* * Example structure for key/value pair sorting *******************************************************************/ /* struct testType { volatile int key; // Keys by which to compare objects // Pointer to the objects to be sorted (defined as index within an array). Because GPU memory is limited, 32-bit integer index suffices to cover address space volatile int val; // Casting functions to enable use of a single __shfl operation __forceinline__ __device__ operator CASTTYPE() { return ((long)key + ((long)((long)val << 32)));} __forceinline__ __device__ testType& operator =(long &newVal) { key = (int)newVal; val = (int)((long)newVal >> 32); return *this;} __forceinline__ __device__ testType& operator =(const long &newVal) { key = (int)newVal; val = (int)((long)newVal >> 32); return *this;} __forceinline__ __device__ testType& operator =(const int &newVal) { key = newVal; val = newVal; return *this;} }; */ // Variable used for debugging and performance counting __device__ int tot_cmp;
#pragma once #include "vlc/vlc.h" #include <string> #pragma comment(lib, "libvlc.lib") #pragma comment(lib, "libvlccore.lib") using namespace std; class VLCPlayer { libvlc_instance_t *vlcInstance; libvlc_media_player_t *vlcMediaPlayer; libvlc_media_t *vlcMedia; int volume; public: VLCPlayer(); ~VLCPlayer(); void OpenMedia(const char* mediaPath); libvlc_time_t GetPlayTime(); libvlc_time_t GetLength(); void Play(); void Pause(); void Stop(); void SetVolume(int vol); void SetTime(libvlc_time_t newTime); };
#pragma once #include "ARPG.h" #include "Components/SphereComponent.h" #include "InteractableAreaComponent.generated.h" DECLARE_MULTICAST_DELEGATE_OneParam(FInteractEvent, class UInteractableAreaComponent *) UCLASS() class ARPG_API UInteractableAreaComponent : public USphereComponent { GENERATED_BODY() public : // ์ƒํ˜ธ์ž‘์šฉ์ด ์‹œ์ž‘๋˜์—ˆ์„ ๋•Œ ํ˜ธ์ถœ๋˜๋Š” ๋Œ€๋ฆฌ์ž FInteractEvent OnInteractionStarted; public : virtual void BeginPlay() override; public : // ์ƒํ˜ธ์ž‘์šฉ์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค. void StartInteraction(); private : UFUNCTION() void OnPlayerCharacterDetected( UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); UFUNCTION() void OnPlayerCharacterLost( UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex); };
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> #include <QDateTime> #include <QFile> static QFile outFile; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); outFile.setFileName("short.log"); //"C:/Qt/build-LightingSensor-Desktop_Qt_5_11_1_MinGW_32bit-Debug/short.log" } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_lineEdit_returnPressed() { QString qsTemp = ui->lineEdit->text(); ui->plainTextEdit->appendPlainText(qsTemp); ui->lineEdit->clear(); readFromFile(qsTemp); } void MainWindow::on_pushButton_pressed() { on_lineEdit_returnPressed(); } static int countLighting = 0; static double sum = 0.0; static int count = 0; static double average = 0.0; void MainWindow::readFromFile(QString fileName) { QFile inputFile(fileName); if (!inputFile.open(QIODevice::ReadOnly | QIODevice::Text)){ qDebug() << "Can't open file" ; } while (!inputFile.atEnd()) { QString line; int i=0; while(!inputFile.atEnd()){ line = inputFile.readLine(); line = line.trimmed(); process_line(line); i++; } } } void MainWindow::process_line(QString input) { QStringList qsl = input.split(','); if(qsl.size()==3){ double lux = qsl.at(0).toDouble(); QString qsTemp = QString::number(lux,'f',6); qsl[0]=qsTemp; qint64 unixTimeMilSec = static_cast<qint64>(qsl.at(1).toLongLong()); QDateTime dt =QDateTime::fromMSecsSinceEpoch(unixTimeMilSec); qsTemp = dt.toString(); if (dt.time().hour() == countLighting){ sum += lux; count++; } else { average = sum/count; countLighting = dt.time().hour(); count = 0; sum = 0.0; qDebug() << "Average lighting level: " << average << "lux at " << dt.time().hour() << " o'clock on date:" + qsTemp; qsl.append(qsTemp); QString outStr = qsl.join(';'); //outStr.append("\n"); outFile.write(qPrintable(outStr)); ui->plainTextEdit->appendPlainText(outStr); } } }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef pair<int, int> P; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} void fds(vector<ll> &s, int keta, string tmp){ if (tmp.size() == keta){ s.push_back(stoll(tmp)); return; } if (tmp == ""){ for (int i = 1; i <= 9; i++) { fds(s, keta, to_string(i)); } return; } int num = tmp[tmp.size()-1] - '0'; if (num!=0) fds(s, keta, tmp+to_string(num-1)); fds(s, keta, tmp+to_string(num)); if (num!=9) fds(s, keta, tmp+to_string(num+1)); return; } int main(){ int k; cin >> k; vector<ll> s; rep(i, 10){ fds(s, i+1, ""); } sort(s.begin(), s.end()); cout << s[k-1] << endl; }