text
stringlengths
8
6.88M
#include "Linklist.h" template<class T> Linklist<T>::Linklist(){ head = NULL; tail = NULL; count = 0; } template<class T> Linklist<T>::~Linklist(){ Node<T> *temp; temp = head; while(head != NULL){ head = head->getNext(); delete temp; temp = head; } } template<class T> bool Linklist<T>::isEmpty(){ return (head == NULL && tail==NULL); } template<class T> int Linklist<T>::size(){ return count; } template<class T> void Linklist<T>::AddBegin(T data){ Node<T> *temp = new Node<T>; if(isEmpty()){ temp->setNext(NULL); temp->setPrev(NULL); temp->setData(data); head = temp; tail = temp; }else{ temp->setNext(head); temp->setPrev(NULL); temp->setData(data); head->setPrev(temp); head = temp; } count++; } template<class T> void Linklist<T>::AddEnd(T data){ Node<T> *temp = new Node<T>; if(isEmpty()){ temp->setNext(NULL); temp->setPrev(NULL); temp->setData(data); head = temp; tail = temp; }else{ tail->setNext(temp); temp->setNext(NULL); temp->setPrev(tail); temp->setData(data); tail = temp; } count++; } template<class T> void Linklist<T>::DeleteBegin(){ Node<T> *temp = new Node<T>; if(isEmpty()){ cout<<"\nList is Empty...\n"; }else{ temp = head; head = head->getNext(); head->setPrev(NULL); } delete temp; count--; } template<class T> void Linklist<T>::DeleteEnd(){ Node<T> *n = new Node<T>; if(isEmpty()){ cout<<"\nList is Empty...\n"; }else{ n = tail; tail = tail->getPrev(); tail->setNext(NULL); delete n; } count--; } template<class T> void Linklist<T>::Display(){ Node<T> *temp = new Node<T>; if(isEmpty()){ cout<<"\nList is Empty."; }else{ temp = head; while(temp != NULL){ cout<<"\n"<<temp->getData(); temp = temp->getNext(); } } cout<<"\n"; } template<class T> void Linklist<T>::AddAtPos(int pos,T data){ Node<T> *temp = new Node<T>; Node<T> *p = new Node<T>; Node<T> *n = new Node<T>; if(pos >= count+2){ cout<<"\nWrong"; }else{ n = head; while(pos >= 2){ p = n; n = n->getNext(); pos--; } temp->setData(data); temp->setNext(n); temp->setPrev(p); p->setNext(temp); n->setPrev(temp); } count++; } template<class T> void Linklist<T>::DeleteAtPos(int pos){ Node<T> *p = new Node<T>; Node<T> *n = new Node<T>; Node<T> *temp = new Node<T>; if(pos > count){ cout<<"\nWrong"; }else{ n = head; while(pos > 1){ p = n; n = n->getNext(); pos--; } temp = n->getNext(); p->setNext(temp); temp->setPrev(p); delete n; } count--; } template class Linklist<int>;
#include <iostream> #include <sstream> #include <algorithm> #include <cstring> #include <string> #include <queue> #include <deque> #include <vector> #include <regex> #define MAX 1005 #define INF 987654321 using namespace std; typedef pair<int, int> pii; typedef long long ll; //97, 122 // regex reg1("^([a-z]{3})([a-z]{0,3})([1-9]{1}[0-9]{0,5})*$"); // if(regex_match(registered_list[i], reg1)) // { // // } string solution(vector<string> registered_list, string new_id) { string answer = new_id; while (1) { bool find = true; for(int i = 0; i < registered_list.size(); i++) { if(registered_list[i] == answer) { find = false; break; } } if(find == false) { int i; string num = ""; for(i = 0; i < answer.size(); i++) { if(48 <= answer[i] && answer[i] <= 57) { num = answer.substr(i, answer.size()-1); break; } } if(num == "") { answer += '1'; } else { int tmp = atoi(num.c_str()) + 1; string str = to_string(tmp); answer.replace(i, i+str.size(), str); } cout << answer << endl; } else { break; } } return answer; } int main() { ios::sync_with_stdio(0); cin.tie(0); solution({"bird99", "bird98", "bird101", "gotoxy"}, "bird98"); return 0; }
// // Created by Jared on 5/27/2015. // #ifndef PIXXY_TOOLS_H #define PIXXY_TOOLS_H #include <main.h> #include <stdio.h> static int exec(const char* buffer) { #if OS == OS_NIX char buff[BUFSIZ]; FILE *fp = popen(buffer, "r"); while ( fgets( buff, BUFSIZ, fp ) != NULL ) { printf(buff); } pclose(fp); #elif OS == OS_WIN system(buffer); #endif return 0; } static const char* date() { time_t now = time(0); char* dt = ctime(&now); dt[strlen(dt)-1] = 0; return dt; } static void log(const std::string fmt, ...) { int final_n, n = ((int)fmt.size()) * 2; /* Reserve two times as much as the length of the fmt_str */ std::string str; std::unique_ptr<char[]> formatted; va_list ap; while(1) { formatted.reset(new char[n]); /* Wrap the plain char array into the unique_ptr */ strcpy(&formatted[0], fmt.c_str()); va_start(ap, fmt); final_n = vsnprintf(&formatted[0], n, fmt.c_str(), ap); va_end(ap); if (final_n < 0 || final_n >= n) n += abs(final_n - n + 1); else break; } std::cout << "[" << date() << "] " << formatted.get() << "\n"; } /// <summary> /// Various operations for interacting with files. /// </summary> class File { public: /// <summary> /// Initializes a new instance of the <see cref="File"/> class. /// </summary> /// <param name="file">The file.</param> File(std::string file){ this->file = file; fStream.open(this->file, std::ios::in | std::ios::out | std::ios::binary); } /// <summary> /// Finalizes an instance of the <see cref="File"/> class. /// </summary> ~File(){ fStream.close(); } /// <summary> /// Checks if the file exists. /// </summary> /// <returns>True if it does, otherwise false.</returns> bool exists(){ return exists(file); } /// <summary> /// Checks if the file exists. /// </summary> /// <returns>True if it does, otherwise false.</returns> static bool exists(std::string f){ if (FILE *file = fopen(f.c_str(), "r")) { fclose(file); return true; } else { return false; } } /// <summary> /// Reads the contents of the file. /// </summary> /// <returns>The file contents</returns> std::string read(){ std::string data; if (fStream.is_open()) { std::string tmp; while (std::getline(fStream, tmp)) data.append(tmp + "\n"); } return data; } /// <summary> /// Writes the specified data. /// </summary> /// <param name="data">The data.</param> /// <param name="size">The size.</param> /// <returns></returns> size_t write(void* data, size_t size){ if (fStream.is_open()){ fStream << data; } return size; } size_t length() { std::streampos fsize = 0; std::ifstream file( this->file, std::ios::binary ); fsize = file.tellg(); file.seekg( 0, std::ios::end ); fsize = file.tellg() - fsize; file.close(); return (size_t) fsize; } std::string file; private: std::fstream fStream; }; #endif //PIXXY_TOOLS_H
#include <bits/stdc++.h> #define rep(i,n) for (int i = 0; i < (n); ++i) #define ok() puts(ok?"Yes":"No"); using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<vi> vvi; typedef vector<ii> vii; typedef vector<bool> vb; typedef vector<vb> vvb; typedef set<int> si; typedef map<string, int> msi; typedef greater<int> gt; typedef priority_queue<int, vector<int>, gt> minq; typedef long long ll; const ll LINF = 1e18L + 1; const int INF = 1e9 + 1; //clang++ -std=c++11 -stdlib=libc++ int main() { ll N; cin>>N; vector<ll> A(N); rep(i,N) cin >> A[i]; vector<ll> ord(A); sort(ord.begin(), ord.end(), [](ll a, ll b) {return a>b;}); ll left = 0, right=N-1; ll ans =0; rep(i, ord.size()) { bool pending = false; rep(j, N) { if (A[j] == ord[i]) { if ((j-left) == (right -j)) { ans += (j-left) * A[j]; pending = true; continue; } if ((j-left) > (right-j)) { if (pending) right--; ans += (j-left)*A[j]; left++; } else { if (pending) left++; ans += (right-j) * A[j]; right--; } } } } printf("%lld\n", ans); return 0; }
#include "mbed.h" #include "math.h" #include "../MPU6050/MPU6050.h" #include "../MPU6050/Kalman.h" #include "../HMC5883L/HMC5883L.h" DigitalOut myled(LED1); Serial pc(USBTX, USBRX); namespace Peripherals { MPU6050 mpu; HMC5883L comp; } int main() { /* Debugging Values */ float x, y, z; float gx, gy, gz; /* Showing it got into main */ myled = 1; /* Initializing Accelerometer and Gyroscope */ /* - Sends the appropriate commands to the IC2 Line */ Peripherals::mpu.InitializeEverything(); /* Make sure I2C Object are assigned */ Peripherals::comp.AssignI2CObject(Peripherals::mpu.getI2C()); /* Set Up Compass*/ Peripherals::comp.SetupHMC5883LDevice(); /* Loop To Initialize to Fetch Data and Apply Corresponding Filters */ while(1) { /* Sample Filter */ Peripherals::comp.FetchData(); Peripherals::comp.FillAxis(x, y, z); /* Accelerometer and Gyro Update */ Peripherals::mpu.Update(); Peripherals::mpu.ReturnGyroscope(gx,gy,gz); float Pitch = Peripherals::mpu.GetPitch(); float Roll = Peripherals::mpu.GetRoll(); /* Compass Update and Magnetic North Fetching */ float MagneticNorth = Peripherals::comp.MagneticNorthCalculations(Pitch, Roll); //float Yaw = Peripherals::mpu.GetYaw(MagneticNorth); //pc.printf("Pitch: %f; Roll: %f; Yaw: %f; Cx: %f; Cy: %f, Cz: %f; \n\r", Pitch, Roll, MagneticNorth, x,y,z); pc.printf("Pitch: %f; Roll: %f; Yaw: %f;\n\r",Pitch, Roll, MagneticNorth); } }
#pragma once #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN 1 #include <windows.h> #endif #include <cstdint> #include <vector> #include <iostream> #include <fstream> #include <string> #include <iterator> #include <regex>
#define ASIO_STANDALONE #include "hermes_detail/NetworkSocket.hh" #include <iostream> #include "hermes_detail/NetworkIO.hh" using asio::ip::tcp; hermes::NetworkSocket::NetworkSocket(NetworkIO io, asio::ip::tcp::resolver::iterator endpoint) : m_io(io), m_socket(m_io.internals->io_service), m_read_loop_started(false), m_callbacks_running(0), m_writer_running(false), m_unacknowledged_messages(0) { CallbackCounter counter(this); asio::async_connect(m_socket, endpoint, [this,counter](asio::error_code ec, tcp::resolver::iterator) { if (!ec) { start_read_loop(); } }); } hermes::NetworkSocket::NetworkSocket(NetworkIO io, asio::ip::tcp::socket socket) : m_io(io), m_socket(std::move(socket)), m_read_loop_started(false), m_callbacks_running(0), m_writer_running(false), m_unacknowledged_messages(0) { CallbackCounter counter(this); m_io.internals->io_service.post( [this,counter]() { start_read_loop(); }); } hermes::NetworkSocket::~NetworkSocket() { std::unique_lock<std::mutex> lock(m_unacknowledged_mutex); m_all_messages_acknowledged.wait_for( lock, std::chrono::seconds(5), [this](){ return !m_socket.is_open() || m_unacknowledged_messages == 0; }); close_socket(); std::unique_lock<std::mutex> lock_all_finished(m_all_callbacks_finished_mutex); m_all_callbacks_finished.wait(lock_all_finished, [this] () { return m_callbacks_running==0; } ); } void hermes::NetworkSocket::close_socket() { std::unique_lock<std::mutex> lock(m_close_mutex); if(m_socket.is_open()) { asio::error_code ec; m_socket.shutdown(asio::ip::tcp::socket::shutdown_both,ec); try { m_socket.close(); } catch (std::system_error&) { } } m_socket_closed.notify_all(); m_received_message.notify_all(); } void hermes::NetworkSocket::WaitForClose() { std::unique_lock<std::mutex> lock(m_close_mutex); m_socket_closed.wait(lock, [this](){ return !m_socket.is_open(); }); } void hermes::NetworkSocket::start_read_loop() { std::unique_lock<std::mutex> lock(m_open_mutex); m_read_loop_started = true; m_can_write.notify_all(); asio::socket_base::linger option(true,1000); m_socket.set_option(option); do_read_header(); } void hermes::NetworkSocket::do_read_header() { CallbackCounter counter(this); asio::async_read(m_socket, asio::buffer(m_current_read.header.arr, header_size), [this,counter](asio::error_code ec, std::size_t /*length*/) { if (!ec) { if (m_current_read.header.packed.acknowledge==0) { do_read_body(); } else { m_unacknowledged_messages--; if(m_unacknowledged_messages == 0) { m_all_messages_acknowledged.notify_one(); } do_read_header(); } } else if (ec != asio::error::operation_aborted){ close_socket(); } }); } void hermes::NetworkSocket::do_read_body() { m_current_read.body = std::string(); // In case it is a moved-from value m_current_read.body.resize(m_current_read.header.packed.size, '\0'); CallbackCounter counter(this); asio::async_read(m_socket, asio::buffer(&m_current_read.body[0], m_current_read.body.size()), [this,counter](asio::error_code ec, std::size_t /*length*/) { if (!ec) { write_acknowledge(m_current_read.header); unpack_message(); do_read_header(); } else if (ec != asio::error::operation_aborted){ close_socket(); } }); } void hermes::NetworkSocket::unpack_message() { auto& unpacker = m_io.internals->message_templates.get_by_id(m_current_read.header.packed.id); auto unpacked = unpacker.unpack(m_current_read.body); m_current_read.body = std::string(); std::lock_guard<std::mutex> lock_callbacks(m_callback_mutex); for(auto& callback : m_callbacks) { bool res = callback->apply_on(*unpacked); if(res) { return; } } std::lock_guard<std::mutex> lock(m_read_lock); m_read_messages.push_back(std::move(unpacked)); m_received_message.notify_one(); } void hermes::NetworkSocket::write_direct(Message message) { { std::unique_lock<std::mutex> lock(m_open_mutex); m_can_write.wait_for(lock, std::chrono::seconds(1), [this]() { return bool(m_read_loop_started); }); } if (message.header.packed.size != message.body.size()) { throw std::runtime_error("Incorrect message header"); } if (message.header.packed.size > max_message_size) { throw std::runtime_error("Message size exceeds maximum"); } { std::lock_guard<std::mutex> lock(m_write_lock); m_write_messages.push_back(std::move(message)); } // Start the writing m_unacknowledged_messages++; start_writer(); } void hermes::NetworkSocket::start_writer() { CallbackCounter counter(this); m_io.internals->io_service.post( [this,counter]() { if (!m_writer_running) { m_writer_running = true; do_write_header(); } }); } void hermes::NetworkSocket::write_acknowledge(network_header header) { header.packed.acknowledge = 1; Message message; message.header = header; { std::lock_guard<std::mutex> lock(m_write_lock); m_write_messages.push_back(message); } start_writer(); } void hermes::NetworkSocket::do_write_header() { { std::lock_guard<std::mutex> lock(m_write_lock); if(m_write_messages.size()) { m_current_write = std::move(m_write_messages.front()); m_write_messages.pop_front(); } else { m_writer_running = false; return; } } // Write the buffer to the socket. CallbackCounter counter(this); asio::async_write(m_socket, asio::buffer(m_current_write.header.arr, header_size), [this,counter](asio::error_code ec, std::size_t /*length*/) { if (!ec) { if(m_current_write.header.packed.acknowledge == 0) { do_write_body(); } else { do_write_header(); } } else if (ec != asio::error::operation_aborted){ close_socket(); } }); } void hermes::NetworkSocket::do_write_body() { CallbackCounter counter(this); asio::async_write(m_socket, asio::buffer(m_current_write.body.c_str(), m_current_write.body.size()), [this,counter](asio::error_code ec, std::size_t /*length*/) { if(!ec) { do_write_header(); } else if (ec != asio::error::operation_aborted){ close_socket(); } }); } bool hermes::NetworkSocket::HasNewMessage() { std::lock_guard<std::mutex> lock(m_read_lock); return m_read_messages.size(); } int hermes::NetworkSocket::WriteMessagesQueued() { std::lock_guard<std::mutex> lock(m_write_lock); return m_write_messages.size(); } bool hermes::NetworkSocket::IsOpen() { return m_socket.is_open(); } std::unique_ptr<hermes::UnpackedMessage> hermes::NetworkSocket::GetMessage() { std::lock_guard<std::mutex> lock(m_read_lock); return pop_if_available(); } std::unique_ptr<hermes::UnpackedMessage> hermes::NetworkSocket::WaitForMessage() { std::unique_lock<std::mutex> lock(m_read_lock); m_received_message.wait(lock, [this]() { return m_read_messages.size() || !IsOpen(); } ); return pop_if_available(); } std::unique_ptr<hermes::UnpackedMessage> hermes::NetworkSocket::WaitForMessage(std::chrono::duration<double> duration) { std::unique_lock<std::mutex> lock(m_read_lock); m_received_message.wait_for(lock, duration, [this]() { return m_read_messages.size() || !IsOpen(); } ); return pop_if_available(); } std::unique_ptr<hermes::UnpackedMessage> hermes::NetworkSocket::pop_if_available() { if(m_read_messages.size()) { auto output = std::move(m_read_messages.front()); m_read_messages.pop_front(); return output; } else { return nullptr; } } void hermes::NetworkSocket::initialize_callback() { std::unique_ptr<MessageCallback> new_callback = nullptr; { std::lock_guard<std::mutex> lock(m_new_callback_mutex); new_callback = std::move(m_new_callbacks.front()); m_new_callbacks.pop_front(); } std::lock_guard<std::mutex> lock_callbacks(m_callback_mutex); std::lock_guard<std::mutex> lock_messages(m_read_lock); // Try callback on all messages, remove any that return true. m_read_messages.erase(std::remove_if(m_read_messages.begin(), m_read_messages.end(), [&](std::unique_ptr<UnpackedMessage>& msg) { return new_callback->apply_on(*msg); }), m_read_messages.end()); m_callbacks.push_back(std::move(new_callback)); }
#ifndef Mission_hpp #define Mission_hpp #include <string> #include "Robot.hpp" class Mission { public: virtual void run() = 0; protected: Mission(Robot * robot_ptr); std::string mission_name; Robot *robot; }; #endif // Mission_hpp
#include "ClockAPI.h" //#include "TimeUtils.h" //#include "PathUtils.h" // -- MAIN LOGIC BEGIN //RTC_Interface rtcClock_; //BoardPathMapper pathMapper_; //HourPosMapper hourPosMapper_; Gantry gantry_; HourHand hourHand_; void setup() { initClockPins(); // rtcClock_.init(globTime_); //Serial.begin(9600); gantry_.init(); hourHand_.init(); pinMode(13, OUTPUT); } uint32_t prev_sync_micros{0}, cur_micros{0}; constexpr uint32_t sync_duration_micros = 60 * 1000000; void loop() { // time from boot measured in micros // update glob time once per minute, where the minute is tracked with Point<pos_t> start_pt{10,10}; Point<pos_t> start_pt1{50,10}; Point<pos_t> dest_pt{100,100}; bool at_dest = false; while (!gantry_.chase_point(start_pt, micros())); { } while (!gantry_.chase_point(start_pt1, micros())); { } while (!gantry_.chase_point(dest_pt, micros())); { } while (!gantry_.chase_point(start_pt1, micros())); { } delay(1000); //while (true) {} //while (!gantry_.chase_point(dest_pt, micros())); //{ } // if (cur_micros - prev_sync_micros > sync_duration_micros) // { // globTime_.sync(globTime_,dt); // } // if (lastTime == 0) lastTime = time; // unsigned dt = time - lastTime; // lastTime = time; // // globTime_.addMillis(dt); // rtcClock_.sync(globTime_, dt); //auto gpos = pathMapper_.getPos(globTime_); //auto hpos = hourPosMapper_.getPos(globTime_); //gantry_.moveTo(gpos); //hourHand_.moveTo(hpos); }
/* * Copyright (C) 2007-2015 Frank Mertens. * * Use of this source is governed by a BSD-style license that can be * found in the LICENSE file. * */ #ifndef FLUXSTREAM_LOOKAHEADSTREAM_H #define FLUXSTREAM_LOOKAHEADSTREAM_H #include <flux/Stream> namespace flux { namespace stream { /** \brief Look-a-head stream buffer */ class LookAheadStream: public Stream { public: static Ref<LookAheadStream> open(Stream *source, int windowSize); virtual bool readyRead(double interval) const; virtual int read(ByteArray *data); virtual off_t transfer(off_t count = -1, Stream *sink = 0, ByteArray *buf = 0); void replay(); void done(); private: LookAheadStream(Stream *source, int windowSize); Ref<Stream> source_; Ref<ByteArray> window_; const int w_; // window size int m_; // window fill int i_; // read offset bool done_; }; }} // namespace flux::stream #endif // FLUXSTREAM_LOOKAHEADSTREAM_H
/* * JointTask.h * * This class creates a joint controller for a robotic manipulator using dynamic decoupling and an underlying PID compensator. * It requires a robot model parsed from a urdf file to a Sai2Model object. * * Author: Mikael Jorda */ #ifndef SAI2_PRIMITIVES_JOINT_TASK_H_ #define SAI2_PRIMITIVES_JOINT_TASK_H_ #include "Sai2Model.h" #include "TemplateTask.h" #include <Eigen/Dense> #include <string> #include <chrono> namespace Sai2Primitives { class JointTask : public TemplateTask { public: /** * @brief Constructor * * @param robot A pointer to a Sai2Model object for the robot that is * to be controlled */ JointTask(Sai2Model::Sai2Model* robot); /** * @brief update the task model (only _N_prec for a joint task) * * @param N_prec The nullspace matrix of all the higher priority * tasks. If this is the highest priority task, use * identity of size n*n where n in the number of DoF of * the robot. */ virtual void updateTaskModel(const Eigen::MatrixXd N_prec); /** * @brief Computes the torques associated with this task. * @details Computes the torques taking into account the last model * update and updated values for the robot joint * positions/velocities assumes the desired position and * velocity has been updated * * @param task_joint_torques the vector to be filled with the new * joint torques to apply for the task */ virtual void computeTorques(Eigen::VectorXd& task_joint_torques); /** * @brief reinitializes the desired state to the current robot * configuration as well as the integrator terms */ void reInitializeTask(); Eigen::VectorXd _current_position; Eigen::VectorXd _desired_position; Eigen::VectorXd _goal_position; Eigen::VectorXd _current_velocity; Eigen::VectorXd _desired_velocity; double _max_velocity; double _kp; double _kv; double _ki; Eigen::VectorXd _integrated_position_error; }; } /* namespace Sai2Primitives */ /* SAI2_PRIMITIVES_JOINT_TASK_H_ */ #endif
#include<cstdio> #include<algorithm> #include<iostream> #include<string.h> #include<cmath> using namespace std; struct nodes { long long value;//面额 long long num; //个数 }node[25]; long long res; bool cmp(struct nodes a,struct nodes b) { return a.value>b.value; } int main() { int n,c; scanf("%d",&n); scanf("%d",&c); memset(node,0,sizeof(node)); for (int i = 0; i < n; i++) { scanf("%lld",&node[i].value); scanf("%lld",&node[i].num); } sort(node,node+n,cmp); // cout<<endl; // for(int i=0;i<n;i++) // { // cout<<node[i].value<<" "<<node[i].num<<endl; // } //将大于c的统计发完 int id; //下一个要考虑的硬币编号 for(id=0;id<n;id++) { if(node[id].value<c) break; //大的全部发完了 res+=node[id].num; } if(id==n) //判断是否搞完 { printf("%d",res); } else //小的硬币凑在一起 { int temp;//当前可以凑成的硬币 while(true) { temp=0; //从大到小凑接近c for(int j=id;j<n;j++) { while(node[j].num&&temp+node[j].value<c) { temp+=node[j].value; node[j].num--; } } //从小到大来凑接近c for(int j=n-1;j>=id;j--) { while(node[j].num&&temp<c) { temp+=node[j].value; node[j].num--; } } if(temp<c) //凑不齐了,该停止了 break; //凑齐了 res++; } printf("%d\n",res); } return 0; } /* #include <iostream> #include <cstdio> #include <algorithm> using namespace std; int N, C; struct node { int d, c; }; node a[25]; bool cmp(const node & a, const node & b) { return a.d > b.d; } int main() { cin >> N >> C; for (int i = 0; i < N; i++) { scanf("%d %d", &a[i].d, &a[i].c); } sort(a, a + N, cmp); int cnt = 0; int j = 0; for (; j < N; j++) { if (a[j].d < C) break; } for (int i = 0; i < j; i++) { cnt += (a[i].d / C) * a[i].c; } while (true) { int now = 0; for (int i = j; i < N; i++) { while (a[i].c && now + a[i].d <= C) { now += a[i].d; a[i].c--; } } for (int i = N - 1; i >= j; i--) { while (a[i].c && now < C) { now += a[i].d; a[i].c--; } } if (now < C) break; cnt++; } cout << cnt << endl; return 0; } */
#include "content\Singularity.Content.h" namespace Singularity { namespace Content { class ContentManager { private: public: }; } }
#include "setup.h" SETUP::SETUP(std::ifstream *inputCine, const CINEFILEHEADER &cineheader) { bitreader br(inputCine); br.seekToByte(cineheader.getOffSetup()); //Look for "ST" mark, marking start of non obsolete setup int count = 0; BYTE first, second; first = br.readBYTE(); second = br.readBYTE(); while (true) { if (first == 83 && second == 84) { break; } first = second; second = br.readBYTE(); count = count + 1; if (count > 4096) throw(exceptionMarkNotFound()); } Length = br.readWORD(); Binning = br.readWORD(); SigOption = br.readWORD(); BinChannels = br.readSHORT(); SamplesPerImage = br.readBYTE(); for(int k = 0; k < 8; k++) { BinName[k] = br.readLengthNSTRING(11); } AnaOption = br.readWORD(); AnaChannels = br.readSHORT(); Res6 = br.readBYTE(); AnaBoard = br.readBYTE(); for (int k = 0; k < 8; k++) { ChOption[k] = br.readSHORT(); } for (int k = 0; k < 8; k++) { AnaGain[k] = br.readFLOAT(); } for(int k = 0; k < 8; k++) { AnaUnit[k] = br.readLengthNSTRING(6); } for (int k = 0; k< 8; k++) { AnaName[k] = br.readLengthNSTRING(11); } IFirstImage = br.readLONG(); dwImageCount = br.readDWORD(); nQFactor = br.readSHORT(); wCineFileType = br.readWORD(); for (int k = 0; k < 4; k++) { szCinePath[k] = br.readLengthNSTRING(65); } bMainsFreq = br.readWORD(); bTimeCode = br.readBYTE(); bPriority = br.readBYTE(); wLeapSecDY = br.readWORD(); dDelayTC = br.readDOUBLE(); dDelayPPS = br.readDOUBLE(); GenBits = br.readWORD(); Res1 = br.readINT(); Res2 = br.readINT(); Res3 = br.readINT(); ImWidth = br.readWORD(); ImHeight = br.readWORD(); EDRShutter16 = br.readWORD(); Serial = br.readUINT(); Saturation = br.readINT(); Res5 = br.readBYTE(); AutoExposure = br.readUINT(); bFlipH = br.readBOOL(); bFlipV = br.readBOOL(); Grid = br.readUINT(); FrameRate = br.readUINT(); Shutter = br.readUINT(); EDRShutter = br.readUINT(); PostTrigger = br.readUINT(); FrameDelay = br.readUINT(); bEnableColor = br.readBOOL(); CameraVersion = br.readUINT(); FirmwareVersion = br.readUINT(); SoftwareVersion = br.readUINT(); RecordingTimeZone = br.readINT(); CFA = br.readUINT(); Bright = br.readINT(); Contrast = br.readINT(); Gamma = br.readINT(); Reserved1 = br.readUINT(); AutoExpLevel = br.readUINT(); AutoExpSpeed = br.readUINT(); for (int k = 0; k < 4; k++) AutoExpRect[k] = br.readDWORD(); for (int k = 0; k < 4; k++) WBGain[k] = br.readWBGAIN(); Rotate = br.readINT(); WBView = br.readWBGAIN(); RealBPP = br.readUINT(); Conv8Min = br.readUINT(); Conv8Max = br.readUINT(); FilterCode = br.readINT(); FilterParam = br.readINT(); UF = br.readIMFILTER(); BlackCalSVer = br.readUINT(); WhiteCalSVer = br.readUINT(); GrayCalSVer = br.readUINT(); bStampTime = br.readBOOL(); SoundDest = br.readUINT(); FRPSteps = br.readUINT(); for (int k = 0; k < 16; k++) FRPImgNr[k] = br.readINT(); for (int k = 0; k < 16; k++) FRPRate[k] = br.readUINT(); for (int k = 0; k < 16; k++) FRPExp[k] = br.readUINT(); MCCnt = br.readINT(); for (int k = 0; k < 64; k++) MCPercent[k] = br.readFLOAT(); CICalib = br.readUINT(); CalibWidth = br.readUINT(); CalibHeight = br.readUINT(); CalibRate = br.readUINT(); CalibExp = br.readUINT(); CalibEDR = br.readUINT(); CalibTemp = br.readUINT(); for (int k = 0; k < 4; k++) HeadSerial[k] = br.readUINT(); RangeCode = br.readUINT(); RangeSize = br.readUINT(); Decimation = br.readUINT(); MasterSerial = br.readUINT(); Sensor = br.readUINT(); ShutterNs = br.readUINT(); EDRShutterNs = br.readUINT(); FrameDelayNs = br.readUINT(); ImPosXAcq = br.readUINT(); ImPosYAcq = br.readUINT(); ImWidthAcq = br.readUINT(); ImHeightAcq = br.readUINT(); Description = br.readLengthNSTRING(4096); RisingEdge = br.readBOOL(); FilterTime = br.readDWORD(); LongReady = br.readBOOL(); ShutterOff = br.readBOOL(); for (int k = 0; k < 16; k++) Res4[k] = br.readBYTE(); bMetaWB = br.readBOOL(); Hue = br.readDWORD(); BlackLevel = br.readINT(); WhiteLevel = br.readINT(); LensDescription = br.readLengthNSTRING(256); LensAperture = br.readFLOAT(); LensFocusDistance = br.readFLOAT(); LensFocalLength = br.readFLOAT(); fOffset = br.readFLOAT(); fGain = br.readFLOAT(); fSaturation = br.readFLOAT(); fHue = br.readFLOAT(); fGamma = br.readFLOAT(); fGammaR = br.readFLOAT(); fGammaB = br.readFLOAT(); fFlare = br.readFLOAT(); fPedestalR = br.readFLOAT(); fPedestalG = br.readFLOAT(); fPedestalB = br.readFLOAT(); fChroma = br.readFLOAT(); } // Prints out all non obsolete values std::ostream& operator<<(std::ostream& os, const SETUP & setupheader) { os << "Setup Length: " << setupheader.getLength() << std::endl; os << "Global Signal Options: " << setupheader.getSigOption() << std::endl; os << "Number of Binary Channels read from SAM: " << setupheader.getBinChannels() << std::endl; os << "Samples per Image: " << static_cast<unsigned>(setupheader.getSamplesPerImage()) << std::endl; os << " Binary Signal Names: " << std::endl; for (int k = 0; k < 8; k++) os << "\t" << setupheader.getBinName(k) << std::endl; os << "Global Analog Option: " << setupheader.getAnaOption() << std::endl; os << "Number of Analog Channels: " << setupheader.getAnaChannels() << std::endl; os << "Analog Board Type: " << setupheader.getAnaBoard() << std::endl; os << "Per Channel Analog Options: " << std::endl; for (int k = 0; k < 8; k++) os << "\t" << setupheader.getChOption(k) << std::endl; os << "Per Channel Gain: " << std::endl; for (int k = 0; k < 8; k++) os << "\t" << setupheader.getAnaGain(k) << std::endl; os << "Per Channel Measurement Unit: " << std::endl; for (int k = 0; k < 8; k++) os << "\t" << setupheader.getAnaUnit(k) << std::endl; os << "Channel Name: " << std::endl; for (int k = 0; k < 8; k++) os << "\t" << setupheader.getAnaName(k) << std::endl; os << "First Image in Range: " << setupheader.getIFirstImage() << std::endl; os << "Image Count in Range: " << setupheader.getdwImageCount() << std::endl; os << "Quality (Compressed Files): " << setupheader.getnQFactor() << std::endl; os << "Cine File Type: " << setupheader.getwCineFileType() << std::endl; os << "Cine File Save Paths: " << std::endl; for (int k = 0; k < 4; k++) os << "\t" << setupheader.getszCinePath(k) << std::endl; os << "Image Width: " << setupheader.getImWidth() << std::endl; os << "Image Height: " << setupheader.getImHeight() << std::endl; os << "Camera Serial: " << setupheader.getSerial() << std::endl; os << "Saturation: " << setupheader.getSaturation() << std::endl; os << "Auto Exposure: " << setupheader.getAutoExposure() << std::endl; os << "Flipped Horizontally: " << setupheader.getbFlipH() << std::endl; os << "Flipped Vertically: " << setupheader.getbFlipV() << std::endl; os << "Grid: " << setupheader.getGrid() << std::endl; os << "Frame Rate: " << setupheader.getFrameRate() << std::endl; os << "Number of Post Trigger Frames: " << setupheader.getPostTrigger() << std::endl; os << "Color Enabled: " << setupheader.getbEnableColor() << std::endl; os << "Camera Version: " << setupheader.getCameraVersion() << std::endl; os << "Firmware Version: " << setupheader.getFirmwareVersion() << std::endl; os << "Software Version: " << setupheader.getSoftwareVersion() << std::endl; os << "Recording Time Zone: " << setupheader.getRecordingTimeZone() << std::endl; os << "Color Filter Array Type: " << setupheader.getCFA() << std::endl; os << "Brightness: " << setupheader.getBright() << std::endl; os << "Contrast: " << setupheader.getContrast() << std::endl; os << "Gamma: " << setupheader.getGamma() << std::endl; os << "Auto Exposure Level: " << setupheader.getAutoExpLevel() << std::endl; os << "Auto Exposure Speed: " << setupheader.getAutoExpSpeed() << std::endl; os << "White Balance Gain: " << std::endl; for (int k = 0; k < 4; k++) os << "\t(" << setupheader.getWBGain(k).R << "," << setupheader.getWBGain(k).B << ")\n"; os << "Rotate: " << setupheader.getRotate() << std::endl; os << "Bits Per Pixel: " << setupheader.getRealBPP() << std::endl; os << "Minimum Value When Converting to 8 Bits: " << setupheader.getConv8Min() << std::endl; os << "Maximum Value When Converting to 8 Bits: " << setupheader.getConv8Max() << std::endl; os << "Filter Code: " << setupheader.getFilterCode() << std::endl; os << "Filter Param: " << setupheader.getFilterParam() << std::endl; os << "Software Version for Black Reference: " << setupheader.getBlackCalSVer() << std::endl; os << "Software Version for White Reference: " << setupheader.getWhiteCalSVer() << std::endl; os << "Software Version for Gray Reference: " << setupheader.getGrayCalSVer() << std::endl; os << "Stamp Time: " << setupheader.getbStampTime() << std::endl; os << "Sound Destination: " << setupheader.getSoundDest() << std::endl; // Skipped stuff about changing frames (FRPSteps) os << "Calibration Width: " << setupheader.getCalibWidth() << std::endl; os << "Calibration Height: " << setupheader.getCalibHeight() << std::endl; os << "Calibration Exposure: " << setupheader.getCalibExp() << std::endl; os << "Calibration EDR: " << setupheader.getCalibEDR() << std::endl; os << "Calibration Temperature: " << setupheader.getCalibTemp() << std::endl; os << "Range Code: " << setupheader.getRangeCode() << std::endl; os << "Range Size: " << setupheader.getRangeSize() << std::endl; os << "Decimation: " << setupheader.getDecimation() << std::endl; os << "Master Serial: " << setupheader.getMasterSerial() << std::endl; os << "Sensor: " << setupheader.getSensor() << std::endl; os << "Shutter (ns): " << setupheader.getShutterNs() << std::endl; os << "EDR Shutter (ns): " << setupheader.getEDRShutterNs() << std::endl; os << "Frame Delay (ns): " << setupheader.getFrameDelayNs() << std::endl; os << "Description: " << setupheader.getDescription() << std::endl; os << "Rising Edge: " << setupheader.getRisingEdge() << std::endl; os << "Filter Time: " << setupheader.getFilterTime() << std::endl; os << "Long Ready: " << setupheader.getLongReady() << std::endl; os << "Shutter Off: " << setupheader.getShutterOff() << std::endl; os << "Meta White Balance: " << setupheader.getbMetaWB() << std::endl; os << "Hue: " << setupheader.getHue() << std::endl; os << "Black Level: " << setupheader.getBlackLevel() << std::endl; os << "White Level: " << setupheader.getWhiteLevel() << std::endl; os << "Lens Description: " << setupheader.getLensDescription() << std::endl; os << "Lens Aperture: " << setupheader.getLensAperture() << std::endl; os << "Lens Focus Distance: " << setupheader.getLensFocusDistance() << std::endl; os << "Lens Focal Length: " << setupheader.getLensFocalLength() << std::endl; os << "Offset: " << setupheader.getfOffset() << std::endl; os << "Gain: "<< setupheader.getfGain() << std::endl; os << "Saturation: " << setupheader.getfSaturation() << std::endl; os << "Hue: " << setupheader.getfHue() << std::endl; os << "Gamma: " << setupheader.getfGamma() << std::endl; os << "Gamma Red: " << setupheader.getfGammaR() << std::endl; os << "Gamma Blue: " << setupheader.getfGammaB() << std::endl; os << "Flare: " << setupheader.getfFlare() << std::endl; os << "Pedestal Red: " << setupheader.getfPedestalR() << std::endl; os << "Pedestal Green: " << setupheader.getfPedestalG() << std::endl; os << "Pedestal Blue: " << setupheader.getfPedestalB() << std::endl; os << "Chroma: " << setupheader.getfChroma() << std::endl; return os; }
// Fill out your copyright notice in the Description page of Project Settings. #include "./UI_CrossHair.h" #include "Components/CanvasPanelSlot.h" #include "Components/Image.h" void UUI_CrossHair::NativeTick(const FGeometry& MyGeometry, float InDeltaTime) { // Set Color TopCH->SetBrushTintColor(CrossHairColor); BottomCH->SetBrushTintColor(CrossHairColor); LeftCH->SetBrushTintColor(CrossHairColor); RightCH->SetBrushTintColor(CrossHairColor); CenterDot->SetBrushTintColor(CrossHairColor); // Set Center Dot CenterDot->SetOpacity(CircleOpacity); auto conCenterDot = Cast<UCanvasPanelSlot>(CenterDot->Slot); const float centerDotPosition = -CircleRadius / 2.0f; conCenterDot->SetSize(FVector2D(CircleRadius, CircleRadius)); conCenterDot->SetPosition(FVector2D(centerDotPosition, centerDotPosition)); // Line Opacity TopCH->SetOpacity(LineOpacity); BottomCH->SetOpacity(LineOpacity); LeftCH->SetOpacity(LineOpacity); RightCH->SetOpacity(LineOpacity); // Line Size and Position auto topLine = Cast<UCanvasPanelSlot>(TopCH->Slot); auto bottomLine = Cast<UCanvasPanelSlot>(BottomCH->Slot); auto leftLine = Cast<UCanvasPanelSlot>(LeftCH->Slot); auto rightLine = Cast<UCanvasPanelSlot>(RightCH->Slot); // Size topLine->SetSize(FVector2D(LineLength, LineThickness)); bottomLine->SetSize(FVector2D(LineLength, LineThickness)); leftLine->SetSize(FVector2D(LineThickness, LineLength)); rightLine->SetSize(FVector2D(LineThickness, LineLength)); // Position const float modifiedThickness = -(LineLength / 2.0f); topLine->SetPosition(FVector2D(modifiedThickness, -(LineThickness + LineOffset))); bottomLine->SetPosition(FVector2D(modifiedThickness, LineOffset)); leftLine->SetPosition(FVector2D(-(LineThickness + LineOffset), modifiedThickness)); rightLine->SetPosition(FVector2D(LineOffset, modifiedThickness)); }
/* EMRAH YILDIRIM 111044056 */ #ifndef SORTED_CONTAINER_H #define SORTED_CONTAINER_H #include<iostream> #include"Container.cpp" using namespace std; namespace HW08 { template<class T> class SortedContainer : public Container<T> { public: SortedContainer(); virtual ~SortedContainer(); virtual int size() const { return this->cont.size(); } virtual int capacity() const { return this->cont.capacity(); } virtual void empty() { this->cont.clear(); } //delete all elements virtual bool add(const T& element) throw (bad_alloc); //add element throw exc virtual void remove(int index); //remove element throw exc virtual bool search(const T& element) const; //search element, throw exc virtual int find(const T& element) const; virtual const T& first() throw(int); //return first element virtual const T& next() throw(int); //returns the next element of the Container since the last //call to the function next. If function //first is called before this function, it returns the second element. void sort(); }; } #endif
#ifndef ADMINWINDOW_H #define ADMINWINDOW_H #include <QObject> #include <QWidget> #include <QtWidgets> #include <QtSql> #include <QBoxLayout> #include <QGroupBox> class AdminWindow : public QMainWindow { Q_OBJECT public: AdminWindow(QString admin_id); private: QWidget *area; QLabel *login; QPushButton *exit; QBoxLayout *layout1; QScrollBar *scroll; QLabel *nametable; QTableView *table; QSqlRelationalTableModel *model; QPushButton *otchet; QListWidget *films; QVBoxLayout *filmsLayout; QVBoxLayout *history; QHBoxLayout *layout2; QMenuBar *menubar; void CreateMenuBar(); QVBoxLayout *mainlayout; QSqlDatabase db; QSqlQuery query1; }; #endif // ADMINWINDOW_H
/* printer_test.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 23 Apr 2015 FreeBSD-style copyright and disclaimer apply */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #define REFLECT_USE_EXCEPTIONS 1 #include "printer_utils.h" #include "reflect.h" #include "utils/json.h" #include <boost/test/unit_test.hpp> #include <fstream> using namespace reflect; using namespace reflect::json; /******************************************************************************/ /* OBJECT */ /******************************************************************************/ template<typename... T> std::vector<std::string> keys(T... keys) { return { keys... }; } void print(Writer& writer) { auto onLeafObject = [&] (const std::string& key) { if (key == "3") printInt(writer, 4); else reflectError("unknown key %s", key); }; auto onLeafArray = [&] (size_t i) { if (i == 0) printInt(writer, 2); else reflectError("unknown index %d", i); }; auto onObject = [&] (const std::string& key) { if (key == "a") printInt(writer, 1); else if (key == "b") printArray(writer, 1, onLeafArray); else if (key == "c") printObject(writer, keys("3"), onLeafObject); else reflectError("unknown key %s", key); }; auto onArray = [&] (size_t i) { if (i == 0) printInt(writer, 1); else if (i == 1) printArray(writer, 1, onLeafArray); else if (i == 2) printObject(writer, keys("3"), onLeafObject); else reflectError("unknown index %d", i); }; auto onField = [&] (const std::string& key) { if (key == "null") printNull(writer); else if (key == "bool") printBool(writer, true); else if (key == "int") printInt(writer, 123); else if (key == "float") printFloat(writer, 123.321); else if (key == "string") printString(writer, "abc"); else if (key == "array") printArray(writer, 3, onArray); else if (key == "object") printObject(writer, keys("a", "b", "c"), onObject); else reflectError("unknown key <%s>", key); }; printObject( writer, keys("null", "bool", "int", "float", "string", "array", "object"), onField); BOOST_CHECK(!writer.error()); if (writer.error()) std::cerr << "ERROR: " << writer.error().what() << std::endl; } /******************************************************************************/ /* PRINTERS */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(test_compact) { std::stringstream ss; Writer writer(ss); print(writer); checkFile("generic.json", ss.str(), true); } BOOST_AUTO_TEST_CASE(test_pretty) { std::stringstream ss; Writer writer(ss, Writer::Pretty); print(writer); checkFile("generic.json", ss.str()); }
#ifndef GALES_PRINT_TOOLS_HPP #define GALES_PRINT_TOOLS_HPP #include <iostream> #include <iomanip> #include <vector> #include <iterator> #include <sstream> #include <fstream> #include <mpi.h> #include <initializer_list> namespace GALES{ ///----------------------------------------------------------------------------------------- /// This is to simply place an empty line. void print() { std::cerr<<std::endl; } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data value. template<typename data_type> void print(const data_type& data) { std::cerr<<data<<std::endl; } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data name and its value. template<typename data_type> void print(std::string varname, const data_type& data) { std::cerr<<varname<<" = "<< data<<std::endl; } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print std vector. template<typename T> void print(const std::vector<T>& v) { std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<T>(ss, " ")); print(ss.str()); } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print std vector with std::cout or std::cerr. template<typename E, typename T, typename data_type> std::basic_ostream<E, T> &operator << (std::basic_ostream<E,T>& os, const std::vector<data_type>& v) { std::size_t size = v.size(); std::basic_ostringstream<E, T, std::allocator<E>> s; s.flags(os.flags()); s.imbue(os.getloc()); s.precision(os.precision()); s << "[" << size << "]("; if(size > 0) s << v[0]; for(std::size_t i=1; i<size; i++) s << ", " << v[i]; s << ")"; return os << s.str().c_str(); } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data value on process 0 only. template<typename data_type> void print0(const data_type& data) { const int rank = get_rank(); if(rank==0) print(data); } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data name and value on process 0 only. template<typename data_type> void print0(std::string varname, const data_type& data) { const int rank = get_rank(); if(rank==0) print(varname, data); } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print std vector on process 0 only. template<typename T> void print0(const std::vector<T>& v) { const int rank = get_rank(); if(rank==0) { std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<T>(ss, " ")); print(ss.str()); } } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to for debugging purpose. template<typename data_type> void debug(const data_type& d) { const int rank = get_rank(); const int size = get_size(); for(int pid=0; pid<size; pid++) if(rank==pid) { std::stringstream ss; ss <<"debug_time_"<<time::get().t()<<"_pid_"<<pid<<std::flush; std::ofstream os(ss.str(), std::ios::app); os<< d <<std::endl; os.close(); } } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data value in file on specified process. template<typename data_type> void print_in_file(int pid, std::string f, const data_type& d) { const int rank = get_rank(); if(rank==pid) { std::stringstream ss; ss << f <<"_time_"<<time::get().t()<<"_pid_"<<pid<<std::flush; std::ofstream os(ss.str(), std::ios::app); os<< d <<std::endl; os.close(); } } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print std vector in file on specified process. template<typename T> void print_in_file(int pid, std::string f, const std::vector<T>& v) { const int rank = get_rank(); if(rank==pid) { std::stringstream ss; ss << f <<"_time_"<<time::get().t()<<"_pid_"<<pid<<std::flush; std::ofstream os(ss.str(), std::ios::app); std::stringstream ss1; copy(v.begin(), v.end(), std::ostream_iterator<T>(ss1, " ")); os<< ss1.str() <<std::endl; os.close(); } } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data name and value in file on specified process. template<typename data_type> void print_in_file(int pid, std::string f, std::string d_name, const data_type& d) { const int rank = get_rank(); if(rank==pid) { std::stringstream ss; ss << f <<"_time_"<<time::get().t()<<"_pid_"<<pid<<std::flush; std::ofstream os(ss.str(), std::ios::app); os<< d_name <<" = "<< d <<std::endl; os.close(); } } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data value in file on specified process for non linear iteration(it_num). template<typename data_type> void print_in_file(int pid, std::string f, int it_num, const data_type& d) { const int rank = get_rank(); if(rank==pid) { std::stringstream ss; ss << f <<"_time_"<<time::get().t()<<"_pid_"<<pid<<"_it_"<<it_num<<std::flush; std::ofstream os(ss.str(), std::ios::app); os<< d <<std::endl; os.close(); } } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data name and value in file on specified process for non linear iteration(it_num). template<typename data_type> void print_in_file(int pid, std::string f, int it_num, std::string d_name, const data_type& d) { const int rank = get_rank(); if(rank==pid) { std::stringstream ss; ss << f<<"_time_"<<time::get().t()<<"_pid_"<<pid<<"_it_"<<it_num<<std::flush; std::ofstream os(ss.str(), std::ios::app); os<< d_name <<" = "<< d <<std::endl; os.close(); } } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data value in file on all processes. template<typename data_type> void print_in_file(std::string f, const data_type& d) { const int size = get_size(); for(int pid=0; pid<size; pid++) print_in_file(pid, f, d); } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data name and value in file on all processes. template<typename data_type> void print_in_file(std::string f, std::string d_name, const data_type& d) { const int size = get_size(); for(int pid=0; pid<size; pid++) print_in_file(pid, f, d_name, d); } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print std vector in file on all processes. template<typename T> void print_in_file(std::string f, const std::vector<T>& v) { const int size = get_size(); for(int pid=0; pid<size; pid++) print_in_file(pid, f, v); } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data value in file on all processes for non linear iteration(it_num). template<typename data_type> void print_in_file(std::string f, int it_num, const data_type& d) { const int size = get_size(); for(int pid=0; pid<size; pid++) print_in_file(pid, f, it_num, d); } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /// This is to print data name and value in file on all processes for non linear iteration(it_num). template<typename data_type> void print_in_file(std::string f, int it_num, std::string d_name, const data_type& d) { const int size = get_size(); for(int pid=0; pid<size; pid++) print_in_file(pid, f, it_num, d_name, d); } ///----------------------------------------------------------------------------------------- ///----------------------------------------------------------------------------------------- /** This class uses the << operator on a given object only for the process specified by the template, while the others do nothing. It is not meant to be used directly but by the means of ad hoc operator <<. */ template<int pid_id=0> struct print_only_pid { print_only_pid(std::ostream& o):stream_m(o){} template<typename s_type> void operator()(const s_type& s) { const int rank = get_rank(); if (rank==pid_id) { stream_m.flush(); stream_m<<s; stream_m.flush(); } } std::ostream& stream_m; }; /// The operator to be actually used by the user. For example: print_only_pid<1>(std::cerr)<<"error!!! \n"; template<typename d_type, int PID_ID> inline print_only_pid<PID_ID> operator<<(print_only_pid<PID_ID> p, d_type const & s) { p(s); return p; } ///----------------------------------------------------------------------------------------- } #endif
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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. */ #ifndef TESTCELLCYCLEMODELODESOLVER_HPP_ #define TESTCELLCYCLEMODELODESOLVER_HPP_ #include <cxxtest/TestSuite.h> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/shared_ptr.hpp> #include <cmath> #include "CellCycleModelOdeSolver.hpp" #include "TysonNovakCellCycleModel.hpp" #include "Alarcon2004OxygenBasedCellCycleModel.hpp" #include "OutputFileHandler.hpp" #include "RungeKutta4IvpOdeSolver.hpp" #include "BackwardEulerIvpOdeSolver.hpp" #include "CvodeAdaptor.hpp" #include "OdeSystemInformation.hpp" #include "AbstractCellBasedTestSuite.hpp" //This test is always run sequentially (never in parallel) #include "FakePetscSetup.hpp" /** * Simple ODE system for use in the test suite. Defines the * IVP dy/dt = 1, y(0) = 0. */ class SimpleOde : public AbstractOdeSystem { public: SimpleOde() : AbstractOdeSystem(1) // 1 here is the number of variables { mpSystemInfo = OdeSystemInformation<SimpleOde>::Instance(); ResetToInitialConditions(); } void EvaluateYDerivatives(double time, const std::vector<double>& rY, std::vector<double>& rDY) { rDY[0] = 1.0; } }; template<> void OdeSystemInformation<SimpleOde>::Initialise() { this->mVariableNames.push_back("Variable_1"); this->mVariableUnits.push_back("Units_1"); this->mInitialConditions.push_back(0.0); this->mInitialised = true; } /** * Simple ODE system with stopping event for use in the test suite. * Defines the IVP dx/dt = y, dy/dt = -x, x(0) = 1, y(0) = 0. * Solutions to this system form circles about the origin. The * stopping event is x(0) < 0, which should first occur at time * t = pi/2. */ class OdeSecondOrderWithEvents : public AbstractOdeSystem { public: OdeSecondOrderWithEvents() : AbstractOdeSystem(2) { mpSystemInfo = OdeSystemInformation<OdeSecondOrderWithEvents>::Instance(); } void EvaluateYDerivatives(double time, const std::vector<double>& rY, std::vector<double>& rDY) { rDY[0] = rY[1]; rDY[1] = -rY[0]; } bool CalculateStoppingEvent(double time, const std::vector<double>& rY) { return (rY[0] < 0); } }; template<> void OdeSystemInformation<OdeSecondOrderWithEvents>::Initialise() { this->mVariableNames.push_back("Variable_1"); this->mVariableUnits.push_back("dimensionless"); this->mInitialConditions.push_back(1.0); this->mVariableNames.push_back("Variable_2"); this->mVariableUnits.push_back("dimensionless"); this->mInitialConditions.push_back(0.0); this->mInitialised = true; } class TestCellCycleModelOdeSolver : public AbstractCellBasedTestSuite { public: void TestMethods() { typedef CellCycleModelOdeSolver<TysonNovakCellCycleModel,RungeKutta4IvpOdeSolver> RkSolver; // Check we can create an instance boost::shared_ptr<RkSolver> p_solver = RkSolver::Instance(); TS_ASSERT(p_solver.get() != NULL); // Check singleton-ness boost::shared_ptr<RkSolver> p_solver2 = RkSolver::Instance(); TS_ASSERT_EQUALS(p_solver, p_solver2); // Coverage TS_ASSERT_THROWS_NOTHING(p_solver->Reset()); p_solver->Initialise(); // Check the solver can be called for a simple ODE system SimpleOde ode; double last_time = 0.0; double current_time = 2; double dt = 1e-5; ode.SetStateVariables(ode.GetInitialConditions()); p_solver->SolveAndUpdateStateVariable(&ode, last_time, current_time, dt); // No stopping event is specified, so check the solver did not stop TS_ASSERT_EQUALS(p_solver->StoppingEventOccurred(), false); // Check the solver can be called for another ODE system, this time with a stopping event OdeSecondOrderWithEvents ode_with_events; ode_with_events.SetStateVariables(ode_with_events.GetInitialConditions()); p_solver->SolveAndUpdateStateVariable(&ode_with_events, last_time, current_time, dt); // Check the solver stopped at the correct time TS_ASSERT_EQUALS(p_solver->StoppingEventOccurred(), true); TS_ASSERT_DELTA(p_solver->GetStoppingTime(), M_PI_2, 1e-4); } void TestWithBackwardEulerIvpOdeSolver() { typedef CellCycleModelOdeSolver<TysonNovakCellCycleModel, BackwardEulerIvpOdeSolver> EulerSolver; // Check we can create an instance boost::shared_ptr<EulerSolver> p_solver = EulerSolver::Instance(); TS_ASSERT(p_solver.get() != NULL); // Check singleton-ness boost::shared_ptr<EulerSolver> p_solver2 = EulerSolver::Instance(); TS_ASSERT_EQUALS(p_solver, p_solver2); TS_ASSERT_THROWS_THIS(p_solver->Initialise(), "SetSizeOfOdeSystem() must be called before calling Initialise()"); p_solver->SetSizeOfOdeSystem(1); p_solver->Initialise(); // Check the solver can be called for a simple ODE system SimpleOde ode; double last_time = 0.0; double current_time = 2; double dt = 1e-4; ode.SetStateVariables(ode.GetInitialConditions()); p_solver->SolveAndUpdateStateVariable(&ode, last_time, current_time, dt); // No stopping event is specified, so check the solver did not stop TS_ASSERT_EQUALS(p_solver->StoppingEventOccurred(), false); p_solver->Reset(); p_solver->SetSizeOfOdeSystem(2); p_solver->Initialise(); TS_ASSERT_EQUALS(p_solver->GetSizeOfOdeSystem(), 2u); // Check the solver can be called for another ODE system, this time with a stopping event OdeSecondOrderWithEvents ode_with_events; ode_with_events.SetStateVariables(ode_with_events.GetInitialConditions()); p_solver->SolveAndUpdateStateVariable(&ode_with_events, last_time, current_time, dt); // Check the solver stopped at the correct time TS_ASSERT_EQUALS(p_solver->StoppingEventOccurred(), true); TS_ASSERT_DELTA(p_solver->GetStoppingTime(), M_PI_2, 1e-2); } void TestWithCvodeAdaptor() { #ifdef CHASTE_CVODE typedef CellCycleModelOdeSolver<TysonNovakCellCycleModel, CvodeAdaptor> CvodeSolver; // Check we can create an instance boost::shared_ptr<CvodeSolver> p_solver = CvodeSolver::Instance(); TS_ASSERT(p_solver.get() != NULL); // Check singleton-ness boost::shared_ptr<CvodeSolver> p_solver2 = CvodeSolver::Instance(); TS_ASSERT_EQUALS(p_solver, p_solver2); p_solver->Initialise(); TS_ASSERT_THROWS_NOTHING(p_solver->CheckForStoppingEvents()); TS_ASSERT_THROWS_NOTHING(p_solver->SetMaxSteps(1000)); TS_ASSERT_THROWS_NOTHING(p_solver->SetTolerances(1e-5, 1e-5)); #else std::cout << "CVODE is not enabled. " << std::endl; std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl; #endif //CHASTE_CVODE } void TestArchiving() { OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "ode_solver.arch"; typedef CellCycleModelOdeSolver<Alarcon2004OxygenBasedCellCycleModel, BackwardEulerIvpOdeSolver> EulerSolver; // Create an output archive { boost::shared_ptr<EulerSolver> p_solver = EulerSolver::Instance(); p_solver->SetSizeOfOdeSystem(4); p_solver->Initialise(); std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); output_arch << p_solver; TS_ASSERT_EQUALS(p_solver->GetSizeOfOdeSystem(), 4u); p_solver->Reset(); TS_ASSERT_EQUALS(p_solver->GetSizeOfOdeSystem(), UNSIGNED_UNSET); } { boost::shared_ptr<EulerSolver> p_solver = EulerSolver::Instance(); TS_ASSERT_EQUALS(p_solver->GetSizeOfOdeSystem(), UNSIGNED_UNSET); // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_solver; TS_ASSERT_EQUALS(p_solver->GetSizeOfOdeSystem(), 4u); } } }; #endif /*TESTCELLCYCLEMODELODESOLVER_HPP_*/
#include "stock.h" #include "coach.h" #include<iostream> Coach::Coach(){ Stock(28000); _art = { // Coach " ", " ______________", " | [] [] [] []|", " | ", "='OO--------OO'", "###############", }; }; void Coach::add_passengers(int passengers){_passengers=passengers;} double Coach::weight(){return Stock::weight()+_passengers*60;}
/*Given a chess board of order N x M and source points (s1, s2) and destination points (d1, d2). The task to find minimum number of moves required by the Knight to go to the destination cell. Input: The first line of input contains an integer T denoting the number of testcases. Then T test cases follow. Each test case contains two lines. The first line of each testcase contains two space separated integers N and M. Then in the next line are four space separated values s1, s2 and d1, d2. Output: For each testcase in a new line print the minimum number of moves required by the knight to go to the destination from the source. If no such move is possible print -1.*/ #include <bits/stdc++.h> using namespace std; int n, m, d1, d2; int bfs(int s1, int s2) { int cs1, cs2, minv = INT16_MAX; vector<vector<int>> v(n+1, vector<int>(m+1, INT16_MAX)); queue<pair<int, int>> q; int a[8][2] = {{1, 2}, {1, -2},{-1,2},{-1,-2} ,{2, 1}, {2, -1}, {-2, 1}, {-2, -1}}; pair<int, int> c; v[s1][s2]=0; q.push(make_pair(s1, s2)); while (!q.empty()) { c = q.front(); q.pop(); // cout<<c.first<<" "<<c.second<<" "<<v[c.first][c.second]<<".."<<minv<<"//"; if (c.first == d1 && c.second == d2) return v[c.first][c.second]; for (int i = 0; i < 8; ++i) { cs1 = c.first + a[i][0]; cs2 = c.second + a[i][1]; if (cs1 > 0 && cs2 > 0 && cs1 <= n && cs2 <= m && v[cs1][cs2] > v [c.first][c.second] + 1) { // cout<<cs1<<" "<<cs2<<"//"; q.push(make_pair(cs1, cs2)); v[cs1][cs2] = v[c.first][c.second] + 1; } } } return -1; } int dfs(int s1, int s2) { int cs1, cs2, minv = INT16_MAX; vector<vector<int>> v(n+1, vector<int>(m+1, INT16_MAX)); stack<pair<int, int>> s; int a[8][2] = {{1, 2}, {1, -2},{-1,2},{-1,-2} ,{2, 1}, {2, -1}, {-2, 1}, {-2, -1}}; pair<int, int> c; v[s1][s2]=0; s.push(make_pair(s1, s2)); while (!s.empty()) { c = s.top(); s.pop(); // cout<<c.first<<" "<<c.second<<" "<<v[c.first][c.second]<<".."<<minv<<"//"; if (c.first == d1 && c.second == d2) minv = min(minv, v[c.first][c.second]); for (int i = 0; i < 8; ++i) { cs1 = c.first + a[i][0]; cs2 = c.second + a[i][1]; if (cs1 > 0 && cs2 > 0 && cs1 <= n && cs2 <= m && v[cs1][cs2] > v [c.first][c.second] + 1) { // cout<<cs1<<" "<<cs2<<"//"; s.push(make_pair(cs1, cs2)); v[cs1][cs2] = v[c.first][c.second] + 1; } } } if(minv==INT16_MAX) minv=-1; return minv; } int main() { int t, s1, s2; cin >> t; while (t--) { cin >> n >> m >> s1 >> s2 >> d1 >> d2; bool v[25][25]; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) v[i][j] = false; //cout << dfs(s1, s2) << "\n"; cout << bfs(s1, s2) << "\n"; } return 0; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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. */ #ifndef TESTOFFLATTICESIMULATIONWITHNODEBASEDCELLPOPULATION_HPP_ #define TESTOFFLATTICESIMULATIONWITHNODEBASEDCELLPOPULATION_HPP_ #include <cxxtest/TestSuite.h> // Must be included before other cell_based headers #include "CellBasedSimulationArchiver.hpp" #include "AbstractCellBasedWithTimingsTestSuite.hpp" #include "CellVolumesWriter.hpp" #include "CellsGenerator.hpp" #include "Cylindrical2dNodesOnlyMesh.hpp" #include "FileComparison.hpp" #include "FixedG1GenerationalCellCycleModel.hpp" #include "ForwardEulerNumericalMethod.hpp" #include "GeneralisedLinearSpringForce.hpp" #include "HoneycombMeshGenerator.hpp" #include "LogFile.hpp" #include "NodeBasedCellPopulation.hpp" #include "OffLatticeSimulation.hpp" #include "PeriodicNodesOnlyMesh.hpp" #include "PlaneBasedCellKiller.hpp" #include "PlaneBoundaryCondition.hpp" #include "RandomCellKiller.hpp" #include "SmartPointers.hpp" #include "WildTypeCellMutationState.hpp" // Cell population writers #include "CellDivisionLocationsWriter.hpp" #include "CellMutationStatesCountWriter.hpp" #include "CellPopulationAreaWriter.hpp" #include "CellProliferativePhasesCountWriter.hpp" #include "CellProliferativeTypesCountWriter.hpp" #include "CellRemovalLocationsWriter.hpp" #include "NodeVelocityWriter.hpp" #include "PetscSetupAndFinalize.hpp" class TestOffLatticeSimulationWithNodeBasedCellPopulation : public AbstractCellBasedWithTimingsTestSuite { private: /** * Helper method to generate a simple mesh that works in parallel * @param nx number of nodes in the x direction * @param ny number of nodes in the y direction * @return the nodes for the nodes only mesh */ std::vector<Node<2>*> GenerateMesh(unsigned nx, unsigned ny) { std::vector<Node<2>*> nodes(nx*ny); for ( unsigned j = 0; j < ny; j++ ) { for ( unsigned i = 0; i < nx; i++ ) { double x = (double)i + 0.5*(double)(j % 2); double y = (double)j * std::sqrt(3.0)/2.0; nodes[j*nx+i] = new Node<2>(j*nx+i, false, x, y ); } } return nodes; } public: /** * Create a simulation of a NodeBasedCellPopulation with a simple force law. * Test that no exceptions are thrown, and write the results to file. */ void TestSimpleMonolayer() { EXIT_IF_PARALLEL; // Cant access cells with index loop on multiple processors. // Create a simple mesh unsigned num_cells_depth = 5; unsigned num_cells_width = 5; std::vector<Node<2>*> nodes = GenerateMesh(num_cells_width,num_cells_depth); // Convert this to a NodesOnlyMesh NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(nodes, 1.5); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithNodeBasedCellPopulation"); // Test that the member mDt has been initialised correctly TS_ASSERT_DELTA(simulator.GetDt(), 1.0/120.0, 1e-6); // No need to go for long, don't want any birth or regular grid will be disrupted. simulator.SetEndTime(0.5); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); simulator.Solve(); // Check that nothing's gone badly wrong by testing that nodes aren't too close together double min_distance_between_cells = 1.0; for (unsigned i=0; i<simulator.rGetCellPopulation().GetNumNodes(); i++) { for (unsigned j=i+1; j<simulator.rGetCellPopulation().GetNumNodes(); j++) { double distance = norm_2(simulator.rGetCellPopulation().GetNode(i)->rGetLocation()-simulator.rGetCellPopulation().GetNode(j)->rGetLocation()); if (distance < min_distance_between_cells) { min_distance_between_cells = distance; } } } TS_ASSERT(min_distance_between_cells > 0.999); // Tidy up for (unsigned i=0; i<nodes.size(); i++) { delete nodes[i]; } } void TestBoxSizeWithSimpleMonolayer() { // Create a simple mesh unsigned num_cells_depth = 5; unsigned num_cells_width = 5; std::vector<Node<2>*> nodes = GenerateMesh(num_cells_width,num_cells_depth); // Create the mesh NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(nodes,1.5); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithNodeBasedCellPopulation"); // Run for long enough to see the periodic bounday influencing the cells simulator.SetEndTime(10.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); simulator.Solve(); // Now run the simulation again with a different box size // First reset the singletons SimulationTime::Instance()->Destroy(); SimulationTime::Instance()->SetStartTime(0.0); RandomNumberGenerator::Instance()->Reseed(0); // Create the mesh NodesOnlyMesh<2> mesh_2; mesh_2.ConstructNodesWithoutMesh(nodes, 2.0); // Create cells std::vector<CellPtr> cells_2; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator_2; cells_generator_2.GenerateBasicRandom(cells_2, mesh_2.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population_2(mesh_2, cells_2); // Set up cell-based simulation OffLatticeSimulation<2> simulator_2(node_based_cell_population_2); simulator_2.SetOutputDirectory("TestOffLatticeSimulationWith2ndNodeBasedCellPopulation"); // Run for long enough to see the periodic boundary influencing the cells simulator_2.SetEndTime(10.0); // Pass the same force law to the simulation simulator_2.AddForce(p_linear_force); simulator_2.Solve(); // Tidy up for (unsigned i=0; i<nodes.size(); i++) { delete nodes[i]; } } /** * Create a simulation of a NodeBasedCellPopulation with a Cylindrical2dNodesOnlyMesh * to test periodicity. */ void TestSimplePeriodicMonolayer() { EXIT_IF_PARALLEL; // HoneycombMeshGenereator does not work in parallel. // Create a simple periodic mesh unsigned num_cells_depth = 3; unsigned num_cells_width = 3; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 0); TetrahedralMesh<2,2>* p_generating_mesh = generator.GetMesh(); // Convert this to a Cylindrical2dNodesOnlyMesh double periodic_width = 6.0; Cylindrical2dNodesOnlyMesh mesh(periodic_width); mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithPeriodicNodeBasedCellPopulation"); // Run for long enough to see the periodic bounday influencing the cells simulator.SetEndTime(10.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); simulator.Solve(); // Check that nothing's gone badly wrong by testing that nodes aren't outside the domain for (unsigned i=0; i<simulator.rGetCellPopulation().GetNumNodes(); i++) { TS_ASSERT_LESS_THAN_EQUALS(0,simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[0]); TS_ASSERT_LESS_THAN_EQUALS(simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[0],periodic_width); } // Now run the simulation again with the periodic boundary in a different place and check its the same // First reset the singletons SimulationTime::Instance()->Destroy(); SimulationTime::Instance()->SetStartTime(0.0); RandomNumberGenerator::Instance()->Reseed(0); // Convert this to a Cylindrical2dNodesOnlyMesh Cylindrical2dNodesOnlyMesh mesh_2(periodic_width); mesh_2.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Add an offset double x_offset = periodic_width/2.0; mesh_2.Translate(-x_offset,0.0); // Create cells std::vector<CellPtr> cells_2; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator_2; cells_generator_2.GenerateBasicRandom(cells_2, mesh_2.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population_2(mesh_2, cells_2); // Set up cell-based simulation OffLatticeSimulation<2> simulator_2(node_based_cell_population_2); simulator_2.SetOutputDirectory("TestOffLatticeSimulationWith2ndPeriodicNodeBasedCellPopulation"); // Run for long enough to see the periodic boundary influencing the cells simulator_2.SetEndTime(10.0); // Pass the same force law to the simulation simulator_2.AddForce(p_linear_force); simulator_2.Solve(); // Check with a different interaction distance // First reset the singletons SimulationTime::Instance()->Destroy(); SimulationTime::Instance()->SetStartTime(0.0); RandomNumberGenerator::Instance()->Reseed(0); // Convert this to a Cylindrical2dNodesOnlyMesh Cylindrical2dNodesOnlyMesh mesh_3(periodic_width); mesh_3.ConstructNodesWithoutMesh(*p_generating_mesh, 2.0); // Create cells std::vector<CellPtr> cells_3; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator_3; cells_generator_3.GenerateBasicRandom(cells_3, mesh_3.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population_3(mesh_3, cells_3); // Set up cell-based simulation OffLatticeSimulation<2> simulator_3(node_based_cell_population_3); simulator_3.SetOutputDirectory("TestOffLatticeSimulationWith3rdPeriodicNodeBasedCellPopulation"); // Run for long enough to see the periodic boundary influencing the cells simulator_3.SetEndTime(10.0); // Pass the same force law to the simulation simulator_3.AddForce(p_linear_force); simulator_3.Solve(); // Check that nothing's gone badly wrong by testing that nodes aren't outside the domain for (unsigned i=0; i<simulator.rGetCellPopulation().GetNumNodes(); i++) { double x_1 = simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[0]; double x_2 = simulator_2.rGetCellPopulation().GetNode(i)->rGetLocation()[0]; double x_3 = simulator_3.rGetCellPopulation().GetNode(i)->rGetLocation()[0]; if (x_1 < x_offset) { TS_ASSERT_DELTA(x_1+x_offset, x_2, 1e-6) } else { TS_ASSERT_DELTA(x_1-x_offset, x_2, 1e-6) } TS_ASSERT_DELTA(x_1,x_3,1e-6); TS_ASSERT_DELTA(simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[1],simulator_2.rGetCellPopulation().GetNode(i)->rGetLocation()[1],1e-6); TS_ASSERT_DELTA(simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[1],simulator_3.rGetCellPopulation().GetNode(i)->rGetLocation()[1],1e-6); } } /** * Create a simulation of a NodeBasedCellPopulation with a PeriodicNodesOnlyMesh * to test periodicity. */ void TestSimpleYPeriodicMonolayer() { EXIT_IF_PARALLEL; // HoneycombMeshGenereator does not work in parallel. // Create a simple periodic mesh unsigned num_cells_depth = 3; unsigned num_cells_width = 3; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 0); TetrahedralMesh<2,2>* p_generating_mesh = generator.GetMesh(); // Convert this to a PeriodicdNodesOnlyMesh c_vector<double,2> periodic_width = zero_vector<double>(2); periodic_width[1] = 6.0; PeriodicNodesOnlyMesh<2> mesh(periodic_width); mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithYPeriodicNodeBasedCellPopulation"); // Run for long enough to see the periodic bounday influencing the cells simulator.SetEndTime(10.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); simulator.Solve(); // Check that nothing's gone badly wrong by testing that nodes aren't outside the domain for (unsigned i=0; i<simulator.rGetCellPopulation().GetNumNodes(); i++) { TS_ASSERT_LESS_THAN_EQUALS(0,simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[1]); TS_ASSERT_LESS_THAN_EQUALS(simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[1],periodic_width[1]); } // Now run the simulation again with the periodic boundary in a different place and check its the same // First reset the singletons SimulationTime::Instance()->Destroy(); SimulationTime::Instance()->SetStartTime(0.0); RandomNumberGenerator::Instance()->Reseed(0); // Convert this to a PeriodicdNodesOnlyMesh PeriodicNodesOnlyMesh<2> mesh_2(periodic_width); mesh_2.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Add an offset double y_offset = periodic_width[0]/2.0; mesh_2.Translate(0.0,-y_offset); // Create cells std::vector<CellPtr> cells_2; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator_2; cells_generator_2.GenerateBasicRandom(cells_2, mesh_2.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population_2(mesh_2, cells_2); // Set up cell-based simulation OffLatticeSimulation<2> simulator_2(node_based_cell_population_2); simulator_2.SetOutputDirectory("TestOffLatticeSimulationWith2ndYPeriodicNodeBasedCellPopulation"); // Run for long enough to see the periodic boundary influencing the cells simulator_2.SetEndTime(10.0); // Pass the same force law to the simulation simulator_2.AddForce(p_linear_force); simulator_2.Solve(); // Check with a different interaction distance // First reset the singletons SimulationTime::Instance()->Destroy(); SimulationTime::Instance()->SetStartTime(0.0); RandomNumberGenerator::Instance()->Reseed(0); // Convert this to a PeriodicdNodesOnlyMesh PeriodicNodesOnlyMesh<2> mesh_3(periodic_width); mesh_3.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Create cells std::vector<CellPtr> cells_3; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator_3; cells_generator_3.GenerateBasicRandom(cells_3, mesh_3.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population_3(mesh_3, cells_3); // Set up cell-based simulation OffLatticeSimulation<2> simulator_3(node_based_cell_population_3); simulator_3.SetOutputDirectory("TestOffLatticeSimulationWith3rdYPeriodicNodeBasedCellPopulation"); // Run for long enough to see the periodic boundary influencing the cells simulator_3.SetEndTime(10.0); // Pass the same force law to the simulation simulator_3.AddForce(p_linear_force); simulator_3.Solve(); // Check that nothing's gone badly wrong by testing that nodes aren't outside the domain for (unsigned i=0; i<simulator.rGetCellPopulation().GetNumNodes(); i++) { double y_1 = simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[1]; double y_2 = simulator_2.rGetCellPopulation().GetNode(i)->rGetLocation()[1]; double y_3 = simulator_3.rGetCellPopulation().GetNode(i)->rGetLocation()[1]; if (y_1 < y_offset) { TS_ASSERT_DELTA(y_1+y_offset, y_2, 1e-6) } else { TS_ASSERT_DELTA(y_1-y_offset, y_2, 1e-6) } TS_ASSERT_DELTA(y_1,y_3,1e-6); TS_ASSERT_DELTA(simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[0],simulator_2.rGetCellPopulation().GetNode(i)->rGetLocation()[0],1e-6); TS_ASSERT_DELTA(simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[0],simulator_3.rGetCellPopulation().GetNode(i)->rGetLocation()[0],1e-6); } } /** * Create a simulation of a NodeBasedCellPopulation with a PeriodicNodesOnlyMesh * to test periodicity. */ void TestSimpleXYPeriodicMonolayer() { EXIT_IF_PARALLEL; // HoneycombMeshGenereator does not work in parallel. // Create a simple periodic mesh unsigned num_cells_depth = 3; unsigned num_cells_width = 3; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 0); TetrahedralMesh<2,2>* p_generating_mesh = generator.GetMesh(); // Convert this to a PeriodicdNodesOnlyMesh c_vector<double,2> periodic_width = zero_vector<double>(2); periodic_width[0] = 6.0; periodic_width[1] = 6.0; PeriodicNodesOnlyMesh<2> mesh(periodic_width); mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithXYPeriodicNodeBasedCellPopulation"); // Run for long enough to see the periodic bounday influencing the cells simulator.SetEndTime(10.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); simulator.Solve(); // Check that nothing's gone badly wrong by testing that nodes aren't outside the domain for (unsigned i=0; i<simulator.rGetCellPopulation().GetNumNodes(); i++) { TS_ASSERT_LESS_THAN_EQUALS(0,simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[1]); TS_ASSERT_LESS_THAN_EQUALS(simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[1],periodic_width[0]); } // Now run the simulation again with the periodic boundary in a different place and check its the same // First reset the singletons SimulationTime::Instance()->Destroy(); SimulationTime::Instance()->SetStartTime(0.0); RandomNumberGenerator::Instance()->Reseed(0); // Convert this to a PeriodicdNodesOnlyMesh PeriodicNodesOnlyMesh<2> mesh_2(periodic_width); mesh_2.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Add an offset double offset = periodic_width[0]/2.0; mesh_2.Translate(-offset,-offset); // Create cells std::vector<CellPtr> cells_2; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator_2; cells_generator_2.GenerateBasicRandom(cells_2, mesh_2.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population_2(mesh_2, cells_2); // Set up cell-based simulation OffLatticeSimulation<2> simulator_2(node_based_cell_population_2); simulator_2.SetOutputDirectory("TestOffLatticeSimulationWith2ndXYPeriodicNodeBasedCellPopulation"); // Run for long enough to see the periodic boundary influencing the cells simulator_2.SetEndTime(10.0); // Pass the same force law to the simulation simulator_2.AddForce(p_linear_force); simulator_2.Solve(); // Check with a different interaction distance // First reset the singletons SimulationTime::Instance()->Destroy(); SimulationTime::Instance()->SetStartTime(0.0); RandomNumberGenerator::Instance()->Reseed(0); // Check that nothing's gone badly wrong by testing that nodes aren't outside the domain for (unsigned i=0; i<simulator.rGetCellPopulation().GetNumNodes(); i++) { double x_1 = simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[0]; double x_2 = simulator_2.rGetCellPopulation().GetNode(i)->rGetLocation()[0]; double y_1 = simulator.rGetCellPopulation().GetNode(i)->rGetLocation()[1]; double y_2 = simulator_2.rGetCellPopulation().GetNode(i)->rGetLocation()[1]; if (x_1 < offset) { TS_ASSERT_DELTA(x_1+offset, x_2, 1e-6) } else { TS_ASSERT_DELTA(x_1-offset, x_2, 1e-6) } if (y_1 < offset) { TS_ASSERT_DELTA(y_1+offset, y_2, 1e-6) } else { TS_ASSERT_DELTA(y_1-offset, y_2, 1e-6) } } } /** * Create a simulation of a NodeBasedCellPopulation with different cell radii. */ void TestSimpleMonolayerWithDifferentRadii() { // Creates nodes and mesh std::vector<Node<2>*> nodes; nodes.push_back(new Node<2>(0, false, 0.0, 0.0)); nodes.push_back(new Node<2>(1, false, 1.0, 0.0)); NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(nodes, 5.0); // Large cut off as larger cells. // Modify the radii of the cells if (PetscTools::AmMaster()) { mesh.GetNode(0)->SetRadius(1.0); mesh.GetNode(PetscTools::GetNumProcs())->SetRadius(2.0); } // Create cells std::vector<CellPtr> cells; MAKE_PTR(TransitCellProliferativeType, p_transit_type); CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes(), p_transit_type); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); node_based_cell_population.AddCellWriter<CellVolumesWriter>(); node_based_cell_population.Update(); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithNodeBasedCellPopulationAndDifferentRadi"); simulator.SetSamplingTimestepMultiple(12); simulator.SetEndTime(12.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(5.0); // Different as bigger cells simulator.AddForce(p_linear_force); simulator.Solve(); // Check that the radii of all the cells are correct // (cell 0 divided into 0 and 3 and cell 1 divided into 1 and 2) if (PetscTools::AmMaster()) { TS_ASSERT_DELTA(mesh.GetNode(0)->GetRadius(), 1.0, 1e-6); TS_ASSERT_DELTA(mesh.GetNode(PetscTools::GetNumProcs())->GetRadius(), 2.0, 1e-6); TS_ASSERT_DELTA(mesh.GetNode(2*PetscTools::GetNumProcs())->GetRadius(), 2.0, 1e-6); TS_ASSERT_DELTA(mesh.GetNode(3*PetscTools::GetNumProcs())->GetRadius(), 1.0, 1e-6); // Check the separation of some node pairs TS_ASSERT_DELTA(norm_2(simulator.rGetCellPopulation().GetNode(0)->rGetLocation()-simulator.rGetCellPopulation().GetNode(PetscTools::GetNumProcs())->rGetLocation()), 2.9710, 1e-1); TS_ASSERT_DELTA(norm_2(simulator.rGetCellPopulation().GetNode(0)->rGetLocation()-simulator.rGetCellPopulation().GetNode(2*PetscTools::GetNumProcs())->rGetLocation()), 4.7067, 1e-1); TS_ASSERT_DELTA(norm_2(simulator.rGetCellPopulation().GetNode(0)->rGetLocation()-simulator.rGetCellPopulation().GetNode(3*PetscTools::GetNumProcs())->rGetLocation()), 2.0, 1e-1); } // Clean up memory for (unsigned i=0; i<nodes.size(); i++) { delete nodes[i]; } } /** * Create a simulation of a NodeBasedCellPopulation with variable cell radii. */ void TestSimpleMonolayerWithVariableRadii() { // Creates nodes and mesh std::vector<Node<2>*> nodes; nodes.push_back(new Node<2>(0, false, 0.0, 0.0)); nodes.push_back(new Node<2>(1, false, 1.0, 0.0)); NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(nodes, 5.0); // Larger cut off as bigger cells. // Create cells std::vector<CellPtr> cells; MAKE_PTR(TransitCellProliferativeType, p_transit_type); CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes(), p_transit_type); // Store the radius of the cells in Cell Data if (PetscTools::AmMaster()) { cells[0]->GetCellData()->SetItem("Radius", 1.0); cells[1]->GetCellData()->SetItem("Radius", 2.0); } // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); node_based_cell_population.SetUseVariableRadii(true); node_based_cell_population.AddCellWriter<CellVolumesWriter>(); node_based_cell_population.Update(); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithNodeBasedCellPopulationAndVariableRadii"); simulator.SetSamplingTimestepMultiple(12); simulator.SetEndTime(10.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(5.0); // Different as bigger cells simulator.AddForce(p_linear_force); simulator.Solve(); // Check the radii of all the cells are correct; cell 0 divided into 0 and 3 and cell 1 divided into 1 and 2. // This testing is designed for sequential code. if (PetscTools::IsSequential()) { TS_ASSERT_DELTA(mesh.GetNode(0)->GetRadius(), 1.0, 1e-6); TS_ASSERT_DELTA(mesh.GetNode(1)->GetRadius(), 2.0, 1e-6); TS_ASSERT_DELTA(mesh.GetNode(2)->GetRadius(), 2.0, 1e-6); TS_ASSERT_DELTA(mesh.GetNode(3)->GetRadius(), 1.0, 1e-6); // Check the separation of some node pairs TS_ASSERT_DELTA(norm_2(simulator.rGetCellPopulation().GetNode(0)->rGetLocation()-simulator.rGetCellPopulation().GetNode(1)->rGetLocation()), 3.0, 1e-1); TS_ASSERT_DELTA(norm_2(simulator.rGetCellPopulation().GetNode(0)->rGetLocation()-simulator.rGetCellPopulation().GetNode(2)->rGetLocation()), 4.70670, 1e-1); TS_ASSERT_DELTA(norm_2(simulator.rGetCellPopulation().GetNode(0)->rGetLocation()-simulator.rGetCellPopulation().GetNode(3)->rGetLocation()), 2.0, 1e-1); // Now set all the Radii to 2.0 Note this could be done inside a cell cycle model. for (AbstractCellPopulation<2>::Iterator cell_iter = simulator.rGetCellPopulation().Begin(); cell_iter != simulator.rGetCellPopulation().End(); ++cell_iter) { cell_iter->GetCellData()->SetItem("Radius",2.0); } simulator.SetEndTime(12.0); simulator.Solve(); for (unsigned i=0; i<simulator.rGetCellPopulation().GetNumNodes(); i++) { TS_ASSERT_DELTA(mesh.GetNode(i)->GetRadius(), 2.0, 1e-6); } // Check the separation of some node pairs TS_ASSERT_DELTA(norm_2(simulator.rGetCellPopulation().GetNode(0)->rGetLocation()-simulator.rGetCellPopulation().GetNode(1)->rGetLocation()), 4.0, 1e-3); TS_ASSERT_DELTA(norm_2(simulator.rGetCellPopulation().GetNode(0)->rGetLocation()-simulator.rGetCellPopulation().GetNode(2)->rGetLocation()), 6.9282, 1e-3); TS_ASSERT_DELTA(norm_2(simulator.rGetCellPopulation().GetNode(0)->rGetLocation()-simulator.rGetCellPopulation().GetNode(3)->rGetLocation()), 4.0, 1e-3); } // Clean up memory for (unsigned i=0; i<nodes.size(); i++) { delete nodes[i]; } } void TestSimulationWithBoxes() { EXIT_IF_PARALLEL; // HoneycombMeshGenereator does not work in parallel. // Create a simple mesh int num_cells_depth = 5; int num_cells_width = 5; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 0); TetrahedralMesh<2,2>* p_generating_mesh = generator.GetMesh(); // Convert this to a NodesOnlyMesh NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); // Create a node-based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithNodeBasedCellPopulation"); simulator.SetEndTime(1.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); TS_ASSERT_THROWS_NOTHING(simulator.Solve()); // Check that nothing's gone badly wrong by testing that nodes aren't too close together double min_distance_between_cells = 1.0; for (unsigned i=0; i<simulator.rGetCellPopulation().GetNumNodes(); i++) { for (unsigned j=i+1; j<simulator.rGetCellPopulation().GetNumNodes(); j++) { double distance = norm_2(simulator.rGetCellPopulation().GetNode(i)->rGetLocation()-simulator.rGetCellPopulation().GetNode(j)->rGetLocation()); if (distance < min_distance_between_cells) { min_distance_between_cells = distance; } } } TS_ASSERT(min_distance_between_cells > 1e-3); } /** * Create a simulation of a NodeBasedCellPopulation with a NodeBasedCellPopulationMechanicsSystem * and a CellKiller. Test that no exceptions are thrown, and write the results to file. */ void TestCellDeath() { EXIT_IF_PARALLEL; // HoneycombMeshGenereator does not work in parallel. // Create a simple mesh int num_cells_depth = 5; int num_cells_width = 5; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 0); TetrahedralMesh<2,2>* p_generating_mesh = generator.GetMesh(); // Convert this to a NodesOnlyMesh NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); // Create a node based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithNodeBasedCellPopulationCellPtrDeath"); simulator.SetEndTime(0.5); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); // Add cell killer MAKE_PTR_ARGS(RandomCellKiller<2>, p_killer, (&node_based_cell_population, 0.997877574)); simulator.AddCellKiller(p_killer); // Solve simulator.Solve(); // Check some results TS_ASSERT_EQUALS(simulator.GetNumBirths(), 0u); TS_ASSERT_EQUALS(simulator.GetNumDeaths(), 20u); std::vector<double> node_8_location = simulator.GetNodeLocation(8); TS_ASSERT_DELTA(node_8_location[0], 3.4729, 1e-4); TS_ASSERT_DELTA(node_8_location[1], 1.0051, 1e-4); std::vector<double> node_3_location = simulator.GetNodeLocation(3); TS_ASSERT_DELTA(node_3_location[0], 2.9895, 1e-4); TS_ASSERT_DELTA(node_3_location[1], 0.3105, 1e-4); // Test the results are written correctly FileFinder generated_type_file("TestOffLatticeSimulationWithNodeBasedCellPopulationCellPtrDeath/results_from_time_0/results.vizcelltypes", RelativeTo::ChasteTestOutput); FileFinder generated_node_file("TestOffLatticeSimulationWithNodeBasedCellPopulationCellPtrDeath/results_from_time_0/results.viznodes", RelativeTo::ChasteTestOutput); FileFinder reference_type_file("cell_based/test/data/TestOffLatticeSimulationWithNodeBasedCellPopulationCellPtrDeath/results.vizcelltypes",RelativeTo::ChasteSourceRoot); FileFinder reference_node_file("cell_based/test/data/TestOffLatticeSimulationWithNodeBasedCellPopulationCellPtrDeath/results.viznodes",RelativeTo::ChasteSourceRoot); FileComparison type_files(generated_type_file, reference_type_file); FileComparison node_files(generated_node_file, reference_node_file); TS_ASSERT(type_files.CompareFiles()); TS_ASSERT(node_files.CompareFiles()); } /** * Create a simulation of a NodeBasedCellPopulation with a NodeBasedCellPopulationMechanicsSystem * CellProliferation and a CellKiller. Test that no exceptions are thrown, and write the results to file. */ void TestRecordingCellBirthDeath() { EXIT_IF_PARALLEL; // HoneycombMeshGenerator does not work in parallel. // Create a simple mesh int num_cells_depth = 5; int num_cells_width = 5; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 0); TetrahedralMesh<2, 2>* p_generating_mesh = generator.GetMesh(); // Convert this to a NodesOnlyMesh NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Create cells std::vector<CellPtr> cells; MAKE_PTR(TransitCellProliferativeType, p_transit_type); CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes(), p_transit_type); // Create a node based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); //Add a cell removal writer to output cell deaths node_based_cell_population.AddCellPopulationEventWriter<CellDivisionLocationsWriter>(); node_based_cell_population.AddCellPopulationEventWriter<CellRemovalLocationsWriter>(); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithNodeBasedCellPopulationOutputs"); simulator.SetEndTime(1.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); // Add cell killer c_vector<double, 2> normal = zero_vector<double>(2); normal[1] = 1.0; c_vector<double, 2> point = zero_vector<double>(2); point[1] = 3.5; MAKE_PTR_ARGS(PlaneBasedCellKiller<2>, p_killer, (&node_based_cell_population, point, normal)); // y>3.5 simulator.AddCellKiller(p_killer); // Solve simulator.Solve(); // Check some results TS_ASSERT_EQUALS(simulator.GetNumBirths(), 1u); TS_ASSERT_EQUALS(simulator.GetNumDeaths(), 1u); // Test the results are written correctly FileFinder generated_node_file("TestOffLatticeSimulationWithNodeBasedCellPopulationOutputs/results_from_time_0/results.viznodes", RelativeTo::ChasteTestOutput); FileFinder generated_division_file("TestOffLatticeSimulationWithNodeBasedCellPopulationOutputs/results_from_time_0/divisions.dat", RelativeTo::ChasteTestOutput); FileFinder generated_removal_file("TestOffLatticeSimulationWithNodeBasedCellPopulationOutputs/results_from_time_0/removals.dat", RelativeTo::ChasteTestOutput); FileFinder reference_node_file("cell_based/test/data/TestOffLatticeSimulationWithNodeBasedCellPopulationOutputs/results.viznodes", RelativeTo::ChasteSourceRoot); FileFinder reference_division_file("cell_based/test/data/TestOffLatticeSimulationWithNodeBasedCellPopulationOutputs/divisions.dat", RelativeTo::ChasteSourceRoot); FileFinder reference_removal_file("cell_based/test/data/TestOffLatticeSimulationWithNodeBasedCellPopulationOutputs/removals.dat", RelativeTo::ChasteSourceRoot); FileComparison node_files(generated_node_file, reference_node_file); FileComparison division_files(generated_division_file, reference_division_file); FileComparison removal_files(generated_removal_file, reference_removal_file); TS_ASSERT(node_files.CompareFiles()); TS_ASSERT(division_files.CompareFiles()); TS_ASSERT(removal_files.CompareFiles()); } double mNode3x, mNode4x, mNode3y, mNode4y; // To preserve locations between the below test and test load. void TestStandardResultForArchivingTestsBelow() { EXIT_IF_PARALLEL; // HoneycombMeshGenereator does not work in parallel. // Create a simple mesh int num_cells_depth = 5; int num_cells_width = 5; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 0); TetrahedralMesh<2,2>* p_generating_mesh = generator.GetMesh(); // Convert this to a NodesOnlyMesh NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); // Create a node based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithNodeBasedCellPopulationStandardResult"); simulator.SetEndTime(2.5); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); // Create some boundary conditions and pass them to the simulation c_vector<double,2> normal = zero_vector<double>(2); normal(1) =-1.0; MAKE_PTR_ARGS(PlaneBoundaryCondition<2>, p_bc, (&node_based_cell_population, zero_vector<double>(2), normal)); // y>0 simulator.AddCellPopulationBoundaryCondition(p_bc); // Solve simulator.Solve(); // Check some results mNode3x = 3.0408; mNode3y = 0.0000; mNode4x = 4.0423; mNode4y = 0.0116; std::vector<double> node_3_location = simulator.GetNodeLocation(3); TS_ASSERT_DELTA(node_3_location[0], mNode3x, 1e-4); TS_ASSERT_DELTA(node_3_location[1], mNode3y, 1e-4); std::vector<double> node_4_location = simulator.GetNodeLocation(4); TS_ASSERT_DELTA(node_4_location[0], mNode4x, 1e-4); TS_ASSERT_DELTA(node_4_location[1], mNode4y, 1e-4); } // Testing Save() void TestSave() { EXIT_IF_PARALLEL; // HoneycombMeshGenereator does not work in parallel // Create a simple mesh unsigned num_cells_depth = 5; unsigned num_cells_width = 5; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 0); TetrahedralMesh<2,2>* p_generating_mesh = generator.GetMesh(); // Convert this to a NodesOnlyMesh NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); // Create a node based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithNodeBasedCellPopulationSaveAndLoad"); simulator.SetEndTime(0.1); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); // Create some boundary conditions and pass them to the simulation c_vector<double,2> normal = zero_vector<double>(2); normal(1) =-1.0; MAKE_PTR_ARGS(PlaneBoundaryCondition<2>, p_bc, (&node_based_cell_population, zero_vector<double>(2), normal)); // y>0 simulator.AddCellPopulationBoundaryCondition(p_bc); /* * For more thorough testing of serialization, we 'turn on' adaptivity. * Note that this has no effect on the numerical results, since the * conditions under which the time step would be adapted are not invoked * in this example. */ boost::shared_ptr<AbstractNumericalMethod<2,2> > p_method(new ForwardEulerNumericalMethod<2,2>()); p_method->SetUseAdaptiveTimestep(true); simulator.SetNumericalMethod(p_method); // Solve simulator.Solve(); // Save the results CellBasedSimulationArchiver<2, OffLatticeSimulation<2> >::Save(&simulator); } // Testing Load() (based on previous two tests) void TestLoad() { EXIT_IF_PARALLEL; // Cell based archiving doesn't work in parallel. // Load the simulation from the TestSave method above and // run it from 0.1 to 1.0 OffLatticeSimulation<2>* p_simulator1; p_simulator1 = CellBasedSimulationArchiver<2, OffLatticeSimulation<2> >::Load("TestOffLatticeSimulationWithNodeBasedCellPopulationSaveAndLoad", 0.1); // Test that the numerical method was archived correctly boost::shared_ptr<AbstractNumericalMethod<2, 2> > p_method = p_simulator1->GetNumericalMethod(); TS_ASSERT_EQUALS(p_method->HasAdaptiveTimestep(), true); p_simulator1->SetEndTime(1.0); p_simulator1->Solve(); // Save, then reload and run from 1.0 to 2.5 CellBasedSimulationArchiver<2, OffLatticeSimulation<2> >::Save(p_simulator1); OffLatticeSimulation<2>* p_simulator2 = CellBasedSimulationArchiver<2, OffLatticeSimulation<2> >::Load("TestOffLatticeSimulationWithNodeBasedCellPopulationSaveAndLoad", 1.0); p_simulator2->SetEndTime(2.5); p_simulator2->Solve(); // These results are from time 2.5 in TestStandardResultForArchivingTestBelow() (above!) std::vector<double> node_3_location = p_simulator2->GetNodeLocation(3); TS_ASSERT_DELTA(node_3_location[0], mNode3x, 1e-4); TS_ASSERT_DELTA(node_3_location[1], mNode3y, 1e-4); std::vector<double> node_4_location = p_simulator2->GetNodeLocation(4); TS_ASSERT_DELTA(node_4_location[0], mNode4x, 1e-4); TS_ASSERT_DELTA(node_4_location[1], mNode4y, 1e-4); // Tidy up delete p_simulator1; delete p_simulator2; } /** * Create a simulation of a NodeBasedCellPopulation to test movement threshold. */ void TestMovementThreshold() { EXIT_IF_PARALLEL; // This test doesn't work in parallel because only one process will throw. // Creates nodes and mesh std::vector<Node<2>*> nodes; nodes.push_back(new Node<2>(0, false, 0.0, 0.0)); nodes.push_back(new Node<2>(0, false, 0.0, 0.3)); NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(nodes, 1.5); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); // Create a node based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); node_based_cell_population.SetAbsoluteMovementThreshold(1e-6); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetEndTime(0.1); simulator.SetOutputDirectory("TestOffLatticeSimulationWithNodeBasedCellPopulationThreshold"); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); // Solve TS_ASSERT_THROWS_CONTAINS(simulator.Solve(), "which is more than the AbsoluteMovementThreshold:"); // Avoid memory leak delete nodes[0]; delete nodes[1]; } void TestUpdateCellLocationsAndTopologyWithNoForce() { // Creates nodes and mesh std::vector<Node<2>*> nodes; nodes.push_back(new Node<2>(0, false, 0.0, 0.0)); nodes.push_back(new Node<2>(0, false, 0.0, 0.3)); NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(nodes, 1.5); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); // Create a node based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); node_based_cell_population.SetAbsoluteMovementThreshold(1e-6); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetEndTime(0.1); simulator.SetOutputDirectory("TestOffLatticeSimulationUpdateCellLocationsAndTopologyWithNoForce"); simulator.SetupSolve(); simulator.UpdateCellLocationsAndTopology(); if (PetscTools::AmMaster()) { for (AbstractMesh<2,2>::NodeIterator node_iter = mesh.GetNodeIteratorBegin(); node_iter != mesh.GetNodeIteratorEnd(); ++node_iter) { for (unsigned d=0; d<2; d++) { TS_ASSERT_DELTA(node_iter->rGetAppliedForce()[d], 0.0, 1e-15); } } } // Avoid memory leak delete nodes[0]; delete nodes[1]; } /** * Create a simulation of a NodeBasedCellPopulation with a NodeBasedCellPopulationMechanicsSystem * and a CellKiller. Test that the simulation can be archived and loaded after cells have been killed. */ void TestCellDeathWithArchiving() { EXIT_IF_PARALLEL; // HoneycombMeshGenereator and archiving do not work in parallel { // Create a simple mesh unsigned num_cells_depth = 3; unsigned num_cells_width = 3; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 0); TetrahedralMesh<2, 2> *p_generating_mesh = generator.GetMesh(); // Convert this to a NodesOnlyMesh NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); TS_ASSERT_EQUALS(mesh.GetMaximumNodeIndex(), 9u); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, mesh.GetNumNodes()); for (unsigned i=0; i<cells.size(); i++) { cells[i]->SetBirthTime(-23.49999); // These cells divide every 24 hours so here we set them to divide just after the archive/restore } // Create a node based cell population NodeBasedCellPopulation<2> node_based_cell_population(mesh, cells); // Set up cell-based simulation OffLatticeSimulation<2> simulator(node_based_cell_population); simulator.SetOutputDirectory("TestOffLatticeSimulationWithNodeBasedCellPopulationDeathArchiving"); simulator.SetEndTime(0.5); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(1.5); simulator.AddForce(p_linear_force); // Add cell killer MAKE_PTR_ARGS(RandomCellKiller<2>, p_killer, (&node_based_cell_population, 0.9)); //Probability of death in one hour simulator.AddCellKiller(p_killer); // Solve simulator.Solve(); // Check some results TS_ASSERT_EQUALS(simulator.GetNumBirths(), 0u); TS_ASSERT_EQUALS(simulator.GetNumDeaths(), 4u); CellBasedSimulationArchiver<2, OffLatticeSimulation<2> >::Save(&simulator); } { OffLatticeSimulation<2>* p_simulator1; p_simulator1 = CellBasedSimulationArchiver<2, OffLatticeSimulation<2> >::Load("TestOffLatticeSimulationWithNodeBasedCellPopulationDeathArchiving", 0.5); p_simulator1->SetEndTime(1.0); NodesOnlyMesh<2>* p_mesh = static_cast<NodesOnlyMesh<2>*>(&(p_simulator1->rGetCellPopulation().rGetMesh())); TS_ASSERT_EQUALS(p_mesh->GetNumNodes(), 5u); // 9 (original) - 4 TS_ASSERT_EQUALS(p_mesh->GetMaximumNodeIndex(), 9u); p_simulator1->Solve(); TS_ASSERT_EQUALS(p_simulator1->GetNumBirths(), 2u); TS_ASSERT_EQUALS(p_simulator1->GetNumDeaths(), 8u); // Including previous 4 TS_ASSERT_EQUALS(p_mesh->GetNumNodes(), 3u); // 9 - 8 + 2 TS_ASSERT_EQUALS(p_mesh->GetMaximumNodeIndex(), 9u + 2u); // New births should get fresh indices regardless of gaps caused by deletion. delete p_simulator1; } } }; #endif /*TESTOFFLATTICESIMULATIONWITHNODEBASEDCELLPOPULATION_HPP_*/
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <ATen/ATen.h> #include <ATen/core/op_registration/op_registration.h> #include <fbgemm_gpu/sparse_ops.h> #include <torch/library.h> #include "fbgemm/QuantUtils.h" #include "fbgemm_gpu/sparse_ops_utils.h" using Tensor = at::Tensor; namespace fbgemm_gpu { template <typename input_t> Tensor& _float_to_fused8bitrowwise_cpu_out_t( Tensor& output, const Tensor& input) { TENSOR_ON_CPU(input); TORCH_CHECK( input.dim() >= 2, "Tensor 'input' must have >= 2 dimension(s). Found ", input.ndimension()); const auto input_sizes = input.sizes(); const auto last_dim = input_sizes.size() - 1; const int64_t nrows = c10::size_to_dim_(last_dim, input_sizes); const int32_t ncols = input_sizes[last_dim]; // Output scale and bias are always of type float. const int32_t output_columns = ncols + 2 * sizeof(float); auto output_dims = input_sizes.vec(); output_dims[last_dim] = output_columns; at::native::resize_(output, output_dims, c10::nullopt); const auto input_data = (input_t*)input.data_ptr(); // input.data_ptr<input_t>(); -> Yields // unresolved data_ptr symbol. fbgemm::FloatOrHalfToFused8BitRowwiseQuantizedSBFloat<input_t>( input_data, nrows, ncols, output.data_ptr<uint8_t>()); return output; } template <typename output_t> Tensor& _fused8bitrowwise_to_float_cpu_out_t( Tensor& output, const Tensor& input) { TENSOR_ON_CPU(input); TORCH_CHECK( input.dim() >= 2, "Tensor 'input' must have >= 2 dimension(s). Found ", input.ndimension()); const auto input_sizes = input.sizes(); const auto last_dim = input_sizes.size() - 1; const int64_t nrows = c10::size_to_dim_(last_dim, input_sizes); const int32_t ncols = input_sizes[last_dim]; const int32_t output_columns = ncols - 2 * sizeof(float); auto output_dims = input_sizes.vec(); output_dims[last_dim] = output_columns; at::native::resize_(output, output_dims, c10::nullopt); auto output_data = (output_t*)output.data_ptr(); // output.data_ptr<output_t>(); -> Yields // unresolved data_ptr symbol. fbgemm::Fused8BitRowwiseQuantizedSBFloatToFloatOrHalf<output_t>( input.data_ptr<uint8_t>(), nrows, ncols, output_data); return output; } template <typename input_t> Tensor _float_to_fusednbitrowwise_cpu( const Tensor& input, const int64_t bit_rate) { TENSOR_ON_CPU(input); TENSOR_NDIM_EQUALS(input, 2); const auto input_sizes = input.sizes(); const int64_t nrows = input_sizes[0]; const int32_t ncols = input_sizes[1]; const int32_t num_elem_per_byte = 8 / bit_rate; TORCH_CHECK( ncols % (2 * num_elem_per_byte) == 0, "ncols needs to be multiple of 2 Bytes (half type size) to make the address aligned"); const int64_t output_columns = (ncols + num_elem_per_byte - 1) / num_elem_per_byte + 2 * sizeof(at::Half); auto output = at::empty( {nrows, output_columns}, input.options().dtype(at::kByte)); // at::kBytes for uint8_t const auto input_data = (input_t*)input.data_ptr(); // input.data_ptr<input_t>(); -> Yields // unresolved data_ptr symbol. fbgemm::FloatOrHalfToFusedNBitRowwiseQuantizedSBHalf<input_t>( bit_rate, input_data, nrows, ncols, output.data_ptr<uint8_t>()); return output; } template <typename output_t> Tensor _fusednbitrowwise_to_float_cpu( const Tensor& input, const int64_t bit_rate) { TENSOR_ON_CPU(input); TENSOR_NDIM_EQUALS(input, 2); const auto input_sizes = input.sizes(); const int64_t nrows = input_sizes[0]; const int32_t ncols = input_sizes[1]; const int32_t num_elem_per_byte = 8 / bit_rate; const int32_t output_columns = (ncols - 2 * sizeof(at::Half)) * num_elem_per_byte; Tensor output; if (std::is_same<output_t, float>::value) { output = at::empty( {nrows, output_columns}, // 4 = sizeof(float) input.options().dtype(at::kFloat)); } else { // T = at::Half output = at::empty( {nrows, output_columns}, // 4 = sizeof(float) input.options().dtype(at::kHalf)); } auto output_data = (output_t*)output.data_ptr(); // output.data_ptr<output_t>(); -> Yields // unresolved data_ptr symbol. fbgemm::FusedNBitRowwiseQuantizedSBHalfToFloatOrHalf<output_t>( bit_rate, input.data_ptr<uint8_t>(), nrows, ncols, output_data); return output; } Tensor& _fused8bitrowwise_to_float_cpu_out( Tensor& output, const Tensor& input) { return _fused8bitrowwise_to_float_cpu_out_t<float>(output, input); } Tensor& _float_to_fused8bitrowwise_cpu_out( Tensor& output, const Tensor& input) { return _float_to_fused8bitrowwise_cpu_out_t<float>(output, input); } Tensor& fused8bitrowwise_to_half_cpu_out(Tensor& output, const Tensor& input) { return _fused8bitrowwise_to_float_cpu_out_t<fbgemm::float16>(output, input); } Tensor& half_to_fused8bitrowwise_cpu_out(Tensor& output, const Tensor& input) { return _float_to_fused8bitrowwise_cpu_out_t<fbgemm::float16>(output, input); } Tensor float_to_fused8bitrowwise_cpu(const Tensor& input) { auto output = at::empty( {0}, input.options().dtype(at::kByte)); // at::kBytes for uint8_t return _float_to_fused8bitrowwise_cpu_out(output, input); } Tensor half_to_fused8bitrowwise_cpu(const Tensor& input) { auto output = at::empty( {0}, input.options().dtype(at::kByte)); // at::kBytes for uint8_t return half_to_fused8bitrowwise_cpu_out(output, input); } Tensor fused8bitrowwise_to_float_cpu(const Tensor& input) { auto output = at::empty( {0}, input.options().dtype(at::kFloat)); // at::kBytes for uint8_t return _fused8bitrowwise_to_float_cpu_out(output, input); } Tensor fused8bitrowwise_to_half_cpu(const Tensor& input) { auto output = at::empty( {0}, input.options().dtype(at::kHalf)); // at::kBytes for uint8_t return fused8bitrowwise_to_half_cpu_out(output, input); } Tensor fusednbitrowwise_to_float_cpu( const Tensor& input, const int64_t bit_rate) { return _fusednbitrowwise_to_float_cpu<float>(input, bit_rate); } Tensor fusednbitrowwise_to_half_cpu( const Tensor& input, const int64_t bit_rate) { return _fusednbitrowwise_to_float_cpu<fbgemm::float16>(input, bit_rate); } Tensor float_to_fusednbitrowwise_cpu( const Tensor& input, const int64_t bit_rate) { return _float_to_fusednbitrowwise_cpu<float>(input, bit_rate); } Tensor half_to_fusednbitrowwise_cpu( const Tensor& input, const int64_t bit_rate) { return _float_to_fusednbitrowwise_cpu<fbgemm::float16>(input, bit_rate); } } // namespace fbgemm_gpu TORCH_LIBRARY_FRAGMENT(fbgemm, m) { m.def("FloatToFused8BitRowwiseQuantized(Tensor t) -> Tensor"); m.def( "FloatToFused8BitRowwiseQuantizedOut(Tensor output, Tensor input) -> Tensor"); m.def("HalfToFused8BitRowwiseQuantized(Tensor t) -> Tensor"); m.def("Fused8BitRowwiseQuantizedToFloat(Tensor input) -> Tensor"); m.def("Fused8BitRowwiseQuantizedToHalf(Tensor input) -> Tensor"); m.def( "Fused8BitRowwiseQuantizedToFloatOut(Tensor output, Tensor input) -> Tensor"); m.def( "Fused8BitRowwiseQuantizedToFloatMixedDim(Tensor input, Tensor D_offsets, int output_dtype) -> Tensor"); m.def( "FloatToFusedNBitRowwiseQuantizedSBHalf(Tensor input, int bit_rate) -> Tensor"); m.def( "HalfToFusedNBitRowwiseQuantizedSBHalf(Tensor input, int bit_rate) -> Tensor"); m.def( "FusedNBitRowwiseQuantizedSBHalfToFloat(Tensor input, int bit_rate) -> Tensor"); m.def( "FusedNBitRowwiseQuantizedSBHalfToHalf(Tensor input, int bit_rate) -> Tensor"); } TORCH_LIBRARY_IMPL(fbgemm, CPU, m) { m.impl( "FloatToFused8BitRowwiseQuantized", fbgemm_gpu::float_to_fused8bitrowwise_cpu); m.impl( "HalfToFused8BitRowwiseQuantized", fbgemm_gpu::half_to_fused8bitrowwise_cpu); m.impl( "FloatToFused8BitRowwiseQuantizedOut", fbgemm_gpu::_float_to_fused8bitrowwise_cpu_out); m.impl( "Fused8BitRowwiseQuantizedToFloat", fbgemm_gpu::fused8bitrowwise_to_float_cpu); m.impl( "Fused8BitRowwiseQuantizedToFloatOut", fbgemm_gpu::_fused8bitrowwise_to_float_cpu_out); m.impl( "Fused8BitRowwiseQuantizedToHalf", fbgemm_gpu::fused8bitrowwise_to_half_cpu); m.impl( "FloatToFusedNBitRowwiseQuantizedSBHalf", fbgemm_gpu::float_to_fusednbitrowwise_cpu); m.impl( "FusedNBitRowwiseQuantizedSBHalfToFloat", fbgemm_gpu::fusednbitrowwise_to_float_cpu); m.impl( "FusedNBitRowwiseQuantizedSBHalfToHalf", fbgemm_gpu::fusednbitrowwise_to_half_cpu); m.impl( "HalfToFusedNBitRowwiseQuantizedSBHalf", fbgemm_gpu::half_to_fusednbitrowwise_cpu); }
//비트와이즈 연산 -> 비트를 기준으로 연산 -> 기계의 근본에 해당하는 연산(가장 빠르다) // Bitwise or -> | // Bitwise and -> & // Shift -> <<, >> //연산 속도 (빠른순으로) : 더하기 + 빼기 - 곱하기 * 나누기 / // : 정수연산 실수연산 #include <cstdio> void exam1(int params) { int category1 = 1; // 1 int category2 = 1 << 1; // 2 int category3 = 1 << 2; // 4 if ((category1 & params) != 0) { printf("카테고리 1에 포함\n"); } if ((category2 & params) != 0) { printf("카테고리 2에 포함\n"); } if ((category3 & params) != 0) { printf("카테고리 3에 포함\n"); } } int main() { int v1 = 1; // 0001 int v2 = 3; // 0011 int bitwise_or = v1 | v2; printf("bitwise_or : %d\n", bitwise_or); int bitwise_and = v1 & v2; printf("bitwise_and : %d\n", bitwise_and); int shift_left = v2 << 1; // 0110 printf("shift_left : %d\n", shift_left); int shift_right = v2 >> 1; // 0001 printf("shift_right : %d\n", shift_right); int mario_category = 8 + 4 + 2 + 1; int enemy_category = 0 + 4 + 2 + 1; int turtle_category = 0 + 0 + 2 + 1; int feature_category = 0 + 4 + 0 + 0; exam1(1 | 2 | 4); exam1(1 | 4); return 0; }
#include "../commonunion.h" #include <iostream> COMMONUNION(FooUnion,,foo,bar,baz) struct A { int i; constexpr A(int initi) : i(initi) {} constexpr int foo(int a) const { return i+a; } constexpr int bar() const { return i*2; } void baz() const { std::cout << bar() << std::endl; } }; struct B { int i; constexpr B(int initi) : i(initi) {} constexpr int foo(int a) const { return i*a; } constexpr int bar() const { return i*i; } void baz() const { std::cout << bar() << std::endl; } }; struct C { int i,j; constexpr C(int initi, int initj) : i(initi), j(initj) {} constexpr int foo(int a) const { return (i+(j*a))/j; } constexpr int bar() const { return 2*i/j; } void baz() const { std::cout << bar() << std::endl; } }; template<typename T> struct base { constexpr const T &getbase() const { return static_cast<const T &>(*this); } T &getbase() { return static_cast<const T &>(*this); } constexpr int doublefoo(int a) const { return 2*getbase().foo(a); } }; struct Aplusbyte { A a; //unsigned char b; uint_least8_t b; }; struct ABplusbyte { union { A a; B b; }; //unsigned char i; uint_least8_t i; }; template<std::size_t N> struct Nbytes { unsigned char a[N]; }; COMMONUNION(Foo2Union,public base<cu_impl<Ts...>>,foo,bar,baz) using namespace std; int main(int argc, char **argv) { constexpr FooUnion<A,B> AorB{B{1}}; constexpr FooUnion<C,A> CorA{C{3,2}}; constexpr FooUnion<B,C,A> anyABC{C{7,2}}; constexpr int res1 = AorB.foo(5); constexpr int res2 = CorA.foo(5); constexpr int res3 = anyABC.foo(5); cout << "5: " << res1 << endl; cout << "6: " << res2 << endl; cout << "8: " << res3 << endl; FooUnion<A,B,C> anyABC2{AorB}; cout << "1: " << anyABC2.bar() << endl; anyABC2 = anyABC; cout << "7: " << anyABC2.bar() << endl; anyABC2 = CorA; cout << "3: " << anyABC2.bar() << endl; constexpr Foo2Union<A,B,C> u2(C{3,2}); constexpr int res4 = u2.doublefoo(5); cout << "12: " << res4 << endl; cout << "--------------" << endl; cout << "A sz: " << sizeof(A) << endl; cout << "B sz: " << sizeof(B) << endl; cout << "C sz: " << sizeof(C) << endl; cout << "A+1 sz: " << sizeof(Aplusbyte) << endl; cout << "A/B+1 sz: " << sizeof(ABplusbyte) << endl; cout << "A/B sz: " << sizeof(FooUnion<A,B>) << endl; cout << "A/B/C sz: " << sizeof(FooUnion<A,B,C>) << endl; cout << "B/A/B sz: " << sizeof(FooUnion<B,A,B>) << endl; cout << "--------------" << endl; cout << "2 sz: " << sizeof(Nbytes<2>) << endl; cout << "3 sz: " << sizeof(Nbytes<3>) << endl; cout << "4 sz: " << sizeof(Nbytes<4>) << endl; cout << "5 sz: " << sizeof(Nbytes<5>) << endl; cout << "2/2 sz: " << sizeof(FooUnion<Nbytes<2>,Nbytes<2>>) << endl; cout << "2/3 sz: " << sizeof(FooUnion<Nbytes<2>,Nbytes<3>>) << endl; cout << "2/3/4 sz: " << sizeof(FooUnion<Nbytes<2>,Nbytes<3>,Nbytes<4>>) << endl; cout << "2/3/4/5 sz: " << sizeof(FooUnion<Nbytes<2>,Nbytes<3>,Nbytes<4>,Nbytes<5>>) << endl; cout << "--------------" << endl; cout << "3: "; u2.baz(); }
#include "osp_process.hpp" // set/get params code for class OspProcess /** * @brief Updates parameters * Called by OspParse. * @param group The group (beamforming, freping, etc) that has updates * @param channels 0=left, 1=right, 2=both * @return string "success" or "FAILED" */ std::string OspProcess::set_params(PGroupType group, int channels) { // cout << "Group: " << group << " Chan: " << channels << endl; for (int ch = 0; ch < 2; ch++) { if (channels == 0 && ch == 1) continue; if (channels == 1 && ch == 0) continue; switch (group) { case kCommon: // Common (or global) parameters. Not part of any algorithm. break; case kBf: // send_param to beamformer bf->set_params(params::bf_mu, params::bf_rho, params::bf_delta, params::bf_alpha, params::bf_beta, params::bf_p, params::bf_c, params::bf_type); bf->set_bf_params(params::bf, params::bf_nc_on_off, params::bf_amc_on_off, params::nc_thr, params::amc_thr, params::amc_forgetting_factor); break; case kFp: { // we reduce the gain temporarily to eliminate pops float saved_gain = params::gain_[ch]; params::gain_[ch] = 1e-50; for (int band = 0; band < params::num_bands; band++) fp_[ch][band]->set_params(params::freping_alpha[ch][band], params::freping[ch]); usleep(20000); params::gain_[ch] = saved_gain; } break; case kAudio: if (params::audio_filename.length() == 0) { std::cout << "Error: empty audio filename" << std::endl; break; } fplay.set_params(params::audio_filename, params::audio_reset, params::audio_repeat, params::audio_play); params::audio_play = 0; params::audio_reset = 0; break; case kSpeech: for (int band = 0; band < params::num_bands; band++) noiseMangement[ch][band]->set_param(params::noise_estimation_type[ch], params::spectral_type[ch], params::spectral_subtraction[ch]); break; case kWdrc: { float global_mpo_attack = 0; float global_mpo_release = 0; for (int band = 0; band < params::num_bands; band++) { global_mpo_attack += params::attack[ch][band]; global_mpo_release += params::release[ch][band]; } global_mpo_attack /= params::num_bands; global_mpo_release /= params::num_bands; if (params::num_bands == 10) filterbank[ch]->set(params::aligned[ch]); pd_global_mpo[ch]->set_param(global_mpo_attack, global_mpo_release); global_mpo[ch]->set_param(1.0, 1.0, 0.0, params::global_mpo[ch]); for (int band = 0; band < params::num_bands; band++) { peakDetect[ch][band]->set_param(params::attack[ch][band], params::release[ch][band]); wdrcs[ch][band]->set_param(params::g50[ch][band], params::g80[ch][band], params::knee_low[ch][band], params::mpo_band[ch][band]); } } break; case kAfc: { if (params::afc_reset[ch]) { params::afc_reset[ch] = 0; afcs_[ch]->reset(afc_init_filter, AFC_INIT_FILTER_SIZE); } size_t afc_delay_in_samples = static_cast<size_t>(32.0f * params::afc_delay[ch]); afcs_[ch]->set_delay(afc_delay_in_samples); afcs_[ch]->set_afc_on_off(params::afc[ch]); // set underlying adaptive filter parameters afcs_[ch]->set_params(params::afc_mu[ch], params::afc_rho[ch], defaults::afc_delta, defaults::afc_alpha, defaults::afc_beta, defaults::afc_p, defaults::afc_c, params::afc_type[ch]); } break; default: break; } } return "success"; } /** * @brief Get the parameters from each module * * The values are cached in params::, so the main * reason to do this is to verify that the values * were actually set. */ void OspProcess::get_params() { float t1, t2, t3; float delta, alpha, beta, p, c; size_t delay_len; bf->get_params(params::bf_mu, params::bf_rho, params::bf_delta, params::bf_alpha, params::bf_beta, params::bf_p, params::bf_c, params::bf_type); bf->get_bf_params(params::bf, params::bf_nc_on_off, params::bf_amc_on_off, params::nc_thr, params::amc_thr, params::amc_forgetting_factor); int finished; fplay.get_params(finished); params::audio_playing = finished ? 0 : 1; for (int ch = 0; ch < 2; ch++) { global_mpo[ch]->get_param(t1, t2, t3, params::global_mpo[ch]); afcs_[ch]->get_delay(delay_len); params::afc_delay[ch] = (float)delay_len / 32.0; afcs_[ch]->get_afc_on_off(params::afc[ch]); afcs_[ch]->get_params(params::afc_mu[ch], params::afc_rho[ch], delta, alpha, beta, p, c, params::afc_type[ch]); if (params::num_bands == 10) { bool temp; filterbank[ch]->get(temp); if (temp) params::aligned[ch] = 1; else params::aligned[ch] = 0; } for (int band = 0; band < params::num_bands; band++) { fp_[ch][band]->get_params(params::freping_alpha[ch][band], params::freping[ch]); noiseMangement[ch][band]->get_param(params::noise_estimation_type[ch], params::spectral_type[ch], params::spectral_subtraction[ch]); peakDetect[ch][band]->get_param(params::attack[ch][band], params::release[ch][band]); wdrcs[ch][band]->get_param(params::g50[ch][band], params::g80[ch][band], params::knee_low[ch][band], params::mpo_band[ch][band]); } } }
#ifndef __COMMON_H__ #define __COMMON_H__ #include <cassert> #include <iostream> #include <cudnn.h> #include <cstring> #include <cuda_runtime.h> #define CHECK(status) \ { \ if (status != 0) \ { \ std::cout << "Cuda failure: " << cudaGetErrorString(status) \ << " at line " << __LINE__ \ << std::endl; \ abort(); \ } \ } #endif
#ifndef __MSJEXHND_H__ #define __MSJEXHND_H__ #pragma warning(disable : 4786) #include <stack> #include <CString> //using namespace std; class GlobalExceptionHandler { public: GlobalExceptionHandler( ); ~GlobalExceptionHandler( ); static void push(CString functionName); static void pop(); protected: static LONG WINAPI UnhandledExceptionFilter( PEXCEPTION_POINTERS pExceptionInfo ); static void GenerateExceptionReport( PEXCEPTION_POINTERS pExceptionInfo ); static LPTSTR GetExceptionString( DWORD dwCode ); static BOOL GetLogicalAddress(PVOID addr, PTSTR szModule, DWORD len, DWORD& section, DWORD& offset ); static int write(const char * format, ...); static std::stack<CString> s_functionStack; static char s_szLogFileName[MAX_PATH]; static LPTOP_LEVEL_EXCEPTION_FILTER s_previousFilter; static FILE *s_stream; }; #endif
#include "stdafx.h" #include "Utilities.h" void Utilities::readDataFile(string fileName, vector<Point2D> * data) { ifstream fin(fileName); while (!fin.eof()) { Point2D p; fin >> p.position[0] >> p.position[1]; data->push_back(p); } } void Utilities::getPoints(GLGeometryViewer * viewer, vector<Point2D> * points) { int numPoints = viewer->getNumberOfPoints(); for (int i = 0; i < numPoints; i++) { points->push_back(viewer->getPoint(i)); } } void Utilities::plotPoints(GLGeometryViewer * viewer, vector<Point2D> data) { long numDataPoints = data.size(); for (int i = 0; i < numDataPoints; i++) { viewer->addPoint(data[i]); } viewer->refresh(); } void Utilities::drawCurve(GLGeometryViewer * viewer, vector<Point2D> points, Vector4f color) { Point2D prevPoint = points.at(0); Point2D nextPoint; int numPoints = points.size(); for (int i = 1; i < numPoints; i++) { nextPoint = points.at(i); viewer->addLine(prevPoint.position, nextPoint.position, color); prevPoint = nextPoint; } viewer->refresh(); } void Utilities::drawCurve(GLGeometryViewer * viewer, float points[][2], int numPoints) { Point2D prevPoint(points[0][0], points[0][1]); Point2D nextPoint; for (int i = 1; i < numPoints; i++) { nextPoint.position[0] = points[i][0]; nextPoint.position[1] = points[i][1]; viewer->addLine(prevPoint.position, nextPoint.position); prevPoint = nextPoint; } viewer->refresh(); } Vector3f Utilities::crossProduct(Vector3f v1, Vector3f v2) { Vector3f normal; normal[0] = (v1[1] * v2[2]) - (v1[2] * v2[1]); normal[1] = (v1[2] * v2[0]) - (v1[0] * v2[2]); normal[2] = (v1[0] * v2[1]) - (v1[1] * v2[0]); return normal; }
#include<iostream> using namespace std; int location_of_zero = 6; void swap_with_zero(int* array, int len, int n){ swap(array[n],array[location_of_zero]); location_of_zero = n; } class Solution { public: /** * 调用方法swap_with_zero来对array进行排序 */ void sort(int* array, int len) { for(int i=0;i<len;i++){ int max = len-i-1; for(int j=i;j<len;j++){ if (array[j] == max && j!=i){ swap_with_zero(array,len,i); swap_with_zero(array,len,j); break; } } } } }; int main(){ int array[] = {6,2,1,4,3,5,0}; Solution solute; solute.sort(array,7); for(int i=0;i<7;i++) cout<<" "<<array[i]; return 0; }
#pragma once #include "AsmOperand.h" #include "AsmOperandParser.h" #include "AsmLexicalParser.h" using namespace std; unordered_map<string, OperandParser::OperandGenerator> OperandParser::generators; void OperandParser::PrepareGeneratorsTable() { generators["r"] = [](TokenReadStream tokens)->Operand{ return Operand(tokens[1].data.registerId,Operand::Type::AddressValue); }; generators["i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.registerId, Operand::Type::AddressValue); }; generators["v"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.varTableIndex, Operand::Type::AddressValue); }; generators["r+i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.registerId, tokens[3].data.value); }; generators["r-i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.registerId, tokens[3].data.value*-1); }; generators["r+v"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.registerId, tokens[3].data.varTableIndex); }; generators["r+r"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.registerId, tokens[3].data.registerId,1); }; generators["r+r*i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.registerId, tokens[3].data.registerId, tokens[5].data.value); }; generators["i+r"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[3].data.registerId, tokens[1].data.value); }; generators["r*i+i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.registerId, tokens[3].data.value, tokens[5].data.value); }; generators["i*r+i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[3].data.registerId, tokens[1].data.value, tokens[5].data.value); }; generators["i+i*r"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[5].data.registerId, tokens[3].data.value, tokens[1].data.value); }; generators["i+r*i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[3].data.registerId, tokens[5].data.value, tokens[1].data.value); }; generators["i+r*i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[3].data.registerId, tokens[5].data.value, tokens[1].data.value); }; generators["r+r*i+i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.registerId, tokens[3].data.registerId, tokens[5].data.value, tokens[7].data.value); }; generators["r+i*r+i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.registerId, tokens[5].data.registerId, tokens[3].data.value, tokens[7].data.value); }; generators["r+i+r*i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.registerId, tokens[5].data.registerId, tokens[7].data.value, tokens[3].data.value); }; generators["r+i+i*r"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[1].data.registerId, tokens[7].data.registerId, tokens[5].data.value, tokens[3].data.value); }; generators["r*i+r+i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[5].data.registerId, tokens[1].data.registerId, tokens[3].data.value, tokens[7].data.value); }; generators["i*r+r+i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[5].data.registerId, tokens[3].data.registerId, tokens[1].data.value, tokens[7].data.value); }; generators["r*i+i+r"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[7].data.registerId, tokens[1].data.registerId, tokens[3].data.value, tokens[5].data.value); }; generators["i*r+i+r"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[7].data.registerId, tokens[3].data.registerId, tokens[1].data.value, tokens[5].data.value); }; generators["i+r*i+r"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[7].data.registerId, tokens[3].data.registerId, tokens[5].data.value, tokens[1].data.value); }; generators["i+i*r+r"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[7].data.registerId, tokens[5].data.registerId, tokens[3].data.value, tokens[1].data.value); }; generators["i+r+r*i"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[3].data.registerId, tokens[5].data.registerId, tokens[7].data.value, tokens[1].data.value); }; generators["i+r+i*r"] = [](TokenReadStream tokens)->Operand { return Operand(tokens[3].data.registerId, tokens[7].data.registerId, tokens[5].data.value, tokens[1].data.value); }; } void OperandParser::Init() { PrepareGeneratorsTable(); } Operand OperandParser::MemoryReferenceExpression(TokenReadStream tokens) { string str; vector<Register::Id> regs; vector<int> values; for (auto it = tokens.begin() + 1; it != tokens.end() - 1; ++it) { switch (it->type) { case Token::Type::RegisterName: str.append("r"); break; case Token::Type::IntegralValue: str.append("i"); break; case Token::Type::VariableName: str.append("v"); break; case Token::Type::Add: str.append("+"); break; case Token::Type::Neg: str.append("-"); break; case Token::Type::Mult: str.append("*"); break; } } return generators[str](tokens); } Operand OperandParser::Parse(TokenStream::const_iterator itStart,TokenStream::const_iterator itEnd) { vector<Token> tokens{ itStart,itEnd }; switch (tokens.front().type) { case Token::Type::LSqrBracket: if (tokens.back().type != Token::Type::RSqrBracket) { throw OperandExpressionParserError(); } return MemoryReferenceExpression(tokens); break; case Token::Type::RegisterName: return Operand(tokens.front().data.registerId,Operand::Type::RegisterValue); break; case Token::Type::VariableName: return Operand(tokens.front().data.varTableIndex, Operand::Type::VariableName); break; case Token::Type::IntegralValue: return Operand(tokens.front().data.value, Operand::Type::ImmediateValue); break; } return Operand(); }
#pragma once #include "../EngineLayer/IScan.h" #include <string> #include <unordered_map> #include <vector> #include <limits> #include <optional> using namespace EngineLayer; using namespace EngineLayer::FdrAnalysis; using namespace EngineLayer::ModificationAnalysis; using namespace MassSpectrometry; using namespace NUnit::Framework; using namespace Proteomics; using namespace Proteomics::Fragmentation; using namespace Proteomics::ProteolyticDigestion; namespace Test { //C# TO C++ CONVERTER NOTE: The following .NET attribute has no direct equivalent in native C++: //ORIGINAL LINE: [TestFixture] public static class ModificationAnalysisTest class ModificationAnalysisTest final { public: //C# TO C++ CONVERTER NOTE: The following .NET attribute has no direct equivalent in native C++: //ORIGINAL LINE: [Test] public static void TestModificationAnalysis() static void TestModificationAnalysis(); //C# TO C++ CONVERTER NOTE: The following .NET attribute has no direct equivalent in native C++: //ORIGINAL LINE: [Test] public static void TestModificationAnalysisWithNonLocalizedPtms() static void TestModificationAnalysisWithNonLocalizedPtms(); }; class ThisTestScan : public IScan { public: std::wstring getFullFilePath() const override; int getOneBasedScanNumber() const override; std::optional<int> getOneBasedPrecursorScanNumber() const override; double getRetentionTime() const override; int getNumPeaks() const override; double getTotalIonCurrent() const override; int getPrecursorCharge() const override; double getPrecursorMonoisotopicPeakMz() const override; double getPrecursorMass() const override; }; }
#ifndef BSCHEDULER_PPL_PARALLEL_PIPELINE_HH #define BSCHEDULER_PPL_PARALLEL_PIPELINE_HH #include "basic_pipeline.hh" namespace bsc { template<class T> class parallel_pipeline: public basic_pipeline<T> { public: typedef basic_pipeline<T> base_pipeline; using typename base_pipeline::kernel_type; using typename base_pipeline::lock_type; using typename base_pipeline::traits_type; inline parallel_pipeline(parallel_pipeline&& rhs) noexcept: base_pipeline(std::move(rhs)) {} inline parallel_pipeline() noexcept: parallel_pipeline(1u) {} inline explicit parallel_pipeline(unsigned concurrency) noexcept: base_pipeline(concurrency) {} parallel_pipeline(const parallel_pipeline&) = delete; parallel_pipeline& operator=(const parallel_pipeline&) = delete; ~parallel_pipeline() = default; protected: void do_run() override; }; } #endif // vim:filetype=cpp
#include "test_util.h" void TEST_RM_14(const string &tableName, vector<RID> &rids) { // Functions Tested // 1. reorganize page // 2. delete tuples // 3. delete table cout << "****In Test case 14****" << endl; int numTuples = 2000; readRIDsFromDisk(rids, numTuples); RC rc; rc = rm->reorganizePage(tableName, rids[1000].pageNum); assert(rc == success); rc = rm->deleteTuples(tableName); assert(rc == success); rc = rm->deleteTable(tableName); assert(rc == success); cout << "****Test case 14 passed****" << endl << endl; } int main(int argc, char* argv[]) { (void)argv; if(argc > 1) { cout << "Attach debugger and press enter to continue.\n"; getchar(); } cout << endl << "Test Delete Tuples and Delete Table .." << endl; vector<RID> rids; // DeleteTuples/Table TEST_RM_14("tbl_employee4", rids); return 0; }
//~ author : Sumit Prajapati #include <bits/stdc++.h> using namespace std; #define ull unsigned long long #define ll long long // #define int long long #define pii pair<int, int> #define pll pair<ll, ll> #define pb push_back #define mk make_pair #define ff first #define ss second #define all(a) a.begin(),a.end() #define trav(x,v) for(auto &x:v) #define rep(i,n) for(int i=0;i<n;i++) #define repe(i,n) for(int i=1;i<=n;i++) #define read(a,n) rep(i,n)cin>>a[i] #define reade(a,n) repe(i,n)cin>>a[i] #define FOR(i,a,b) for(int i=a;i<=b;i++) #define printar(a,s,e) FOR(i,s,e)cout<<a[i]<<" ";cout<<'\n' #define curtime chrono::high_resolution_clock::now() #define timedif(start,end) chrono::duration_cast<chrono::nanoseconds>(end - start).count() auto time0 = curtime; const int MD = 1e9 + 7; const int MDL = 998244353; const int INF = 1e9; const int MX = 3e5 + 5; const int B = 600; struct query { int idx, l, r, k; } Q[MX]; int n, q, segm[4 * MX], a[MX], ans[MX]; int query(int cur, int start, int end,int k) { if(segm[cur]<=k) return -1; while(start<=end){ if(start==end) return start; if(segm[2*cur]>k){ cur<<=1; end=(start+end)/2; } else{ cur=(2*cur+1); start=(start+end)/2; start++; } } assert(false); return 0; } void update(int cur, int start, int end, int ind, int val) { if (start == ind && start == end) { //DO UPDATE segm[cur]+=val; return; } if (start > ind || end < ind) return; //OUT OF RANGE int mid = (start + end) >> 1; update(cur << 1, start, mid, ind, val); update((cur << 1) ^ 1, mid + 1, end, ind, val); //MERGING STEP segm[cur]=max(segm[2*cur],segm[2*cur+1]); } void add_element(int x){ update(1,1,n,a[x],1); } void remove_element(int x){ update(1,1,n,a[x],-1); } void MO_S() { for (int L = 1, R = 0, i = 1; i <= q; i++) { while(R<Q[i].r) add_element(++R); while(L>Q[i].l) add_element(--L); while(R>Q[i].r) remove_element(R--); while(L<Q[i].l) remove_element(L++); int k=(Q[i].r-Q[i].l+1)/Q[i].k; // repe(i,16) // cout<<segm[i]<<" "; // cout<<'\n'; // cout<<Q[i].l<<" "<<Q[i].r<<" "<<k<<'\n'; ans[Q[i].idx]=query(1,1,n,k); } } void solve() { // NO MOs(TLE) Needed,Divid and Conquer Instead. cin >> n >> q; repe(i, n) cin >> a[i]; repe(i, q) cin >> Q[i].l >> Q[i].r >> Q[i].k, Q[i].idx = i; sort(Q + 1, Q + q + 1, [&](auto p, auto q) { if (p.l / B == q.l / B) return p.r < q.r; return p.l < q.l; }); MO_S(); repe(i, q) cout << ans[i] << "\n"; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); time0 = curtime; srand(time(NULL)); int t = 1; // cin >> t; repe(tt, t) { // cout<<"Case #"<<tt<<": "; solve(); } // cerr<<"Execution Time: "<<timedif(time0,curtime)*1e-9<<" sec\n"; return 0; }
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package #include "proto/recipe_group.h" #include "proto/sprite.h" using namespace jactorio; proto::RecipeGroup* proto::RecipeGroup::SetSprite(Sprite* sprite) { this->sprite = sprite; return this; } void proto::RecipeGroup::PostLoadValidate(const data::PrototypeManager&) const { J_PROTO_ASSERT(sprite != nullptr, "RecipeGroup sprite was not specified"); J_PROTO_ASSERT(sprite->group == Sprite::SpriteGroup::gui, "RecipeGroup sprite must be in group GUI"); }
/* ID: zrh331 PROG: humble LANG: C++ */ #include <iostream> #include <stdio.h> #include <map> #include <set> #include <string.h> #include <algorithm> #include <assert.h> using namespace std; #define maxint 2147400000 int n, k, a[110], cnt=-1, r; set<long long int> f; int main () { freopen ("humble.in", "r", stdin); freopen ("humble.out", "w", stdout); cin >> n >> k; for (int i=1; i<=n; i++) cin >> a[i]; if (n<50) r = 2147483647; else r = 300000; f.insert (1); for (set<long long int>::iterator i=f.begin(); i!=f.end(); i++) { cnt++; for (int j=1; j<=n; j++) { if (a[j]*(*i)<r) f.insert (a[j]*(*i)); } if (cnt == k) { cout << *i << endl; return 0; } } return 0; }
#include <glut/glut.h> class Camera { Vector position; Vector lookAt; Vector up; Vector dir; public: Vector get_position() { return position; } Vector get_lookAt() { return lookAt; } Vector get_up() { return up; } Vector get_dir() { return dir; } void set_position(Vector); void set_lookAt(Vector); void set_up(Vector); void set_dir(Vector); } ; void Camera::set_position(Vector a) { position = a; } void Camera::set_lookAt(Vector a) { lookAt = a; } void Camera::set_up(Vector a) { up = a; } void Camera::set_dir(Vector a) { dir = a; }
/* NO WARRANTY * * BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO * WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE * LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS * AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT * WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO * THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD * THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL * NECESSARY SERVICING, REPAIR OR CORRECTION. * * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN * WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY * AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES, * INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL * DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM * (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING * RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES * OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER * PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGES. */ #include "stdafx.h" #include "ElectricNodeContextJK_R_T.h" #include "Application\Debug\LogManager.h" ////////////////////////////////////////////////////////////////////// // Konstruktion/Destruktion ////////////////////////////////////////////////////////////////////// IMPLEMENT_REGISTER(CElectricNodeContextJK_R_T); //----------------------------------------------------------------------------- CElectricNodeContextJK_R_T::CElectricNodeContextJK_R_T(){ //----------------------------------------------------------------------------- PROC_TRACE; } //---------------------------------------------------------------------------- void CElectricNodeContextJK_R_T::InitInputPorts(CElectricNode::CElectricNodeDokument& data){ //---------------------------------------------------------------------------- PROC_TRACE; // call the base class // CElectricNodeContext::InitInputPorts(data); // and invert the Reset input // assert(data.inPorts.GetSize()>=4); data.inPorts[3]->SetInverter(true); } //----------------------------------------------------------------------------- void CElectricNodeContextJK_R_T::InitOutputPorts(CElectricNode::CElectricNodeDokument& data){ //----------------------------------------------------------------------------- PROC_TRACE; // call the base class // inherited::InitOutputPorts(data); // and invert the Reset input // assert(data.outPorts.GetSize()>=2); data.outPorts[1]->SetInverter(true); } //----------------------------------------------------------------------------- void CElectricNodeContextJK_R_T::LayoutInput(CElectricNode::CElectricNodeDokument& data){ //----------------------------------------------------------------------------- PROC_TRACE; inherited::LayoutInput(data); assert(data.inPorts.GetSize()>=4); assert(data.icons.GetSize()>=1); CPoint topLeft = data.icons[0]->GetBoundingRect().TopLeft(); long xPos = topLeft.x; long yPos = topLeft.y + data.icons[0]->GetBoundingRect().Height() +16; data.inPorts[3]->SetSpotLocation(DragDropObject::spotRightCenter,xPos,yPos); } //----------------------------------------------------------------------------- void CElectricNodeContextJK_R_T::LayoutOutput(CElectricNode::CElectricNodeDokument& data){ //----------------------------------------------------------------------------- PROC_TRACE; assert(data.icons.GetSize()>=1); long elements_in = data.inPorts.GetSize(); long elements = data.outPorts.GetSize(); CPoint topRight = data.icons[0]->GetBoundingRect().TopLeft() + CPoint( data.icons[0]->GetBoundingRect().Width(),0); float yOffset = data.icons[0]->GetBoundingRect().Height() / (float)(elements_in+1); int xPos = topRight.x; int yPos = (int)(topRight.y + yOffset); data.outPorts[0]->SetSpotLocation(DragDropObject::spotLeftCenter,xPos,yPos); yPos = (int)(topRight.y+(yOffset*3)); data.outPorts[1]->SetSpotLocation(DragDropObject::spotLeftCenter,xPos,yPos); } //----------------------------------------------------------------------------- void CElectricNodeContextJK_R_T::DoCalculate(CElectricNode::CElectricNodeDokument& data){ //----------------------------------------------------------------------------- PROC_TRACE; assert(data.inPorts.GetSize()>=4); assert(data.outPorts.GetSize()>=2); if(data.inPorts[3]->IsHigh()) { // Reset data.outPorts[0]->SetValue(CLogicValue::High); data.outPorts[1]->SetValue(CLogicValue::High); // Note: is an inverter port } else { // normal DoCalculate if(data.inPorts[1]->IsHigh() && data.inPorts[1]->HasValueChanged() ){ if(data.inPorts[0]->IsLow() && data.inPorts[2]->IsHigh()){ data.outPorts[0]->SetValue(CLogicValue::Low); } else if(data.inPorts[0]->IsHigh() && data.inPorts[2]->IsLow()){ data.outPorts[0]->SetValue(CLogicValue::High); } else if(data.inPorts[0]->IsHigh() && data.inPorts[2]->IsHigh()){ data.outPorts[0]->ToggleValue(); } } data.outPorts[1]->SetValue(data.outPorts[0]->GetValue()); // Note: is an inverter port } }
#include "system/pr2-system.h" #include <stdio.h> #include <boost/preprocessor/iteration/local.hpp> extern "C" { #include "pr2MPC.h" pr2MPC_FLOAT **H, **f, **lb, **ub, **z, *c, *A, *b; } const int T = TIMESTEPS; const double INFTY = 1e10; namespace cfg { const double alpha_init = .01; // .01 const double alpha_gain = 3; // 3 const double alpha_epsilon = .1; // .1 const double alpha_max_increases = 5; // 5 const double Xeps_initial = .1; // .1 const double Ueps_initial = .1; // .1 const double improve_ratio_threshold = 1e-1; // .1 const double min_approx_improve = 1e-1; // 1 const double min_trust_box_size = .1; // .1 const double trust_shrink_ratio = .75; // .5 const double trust_expand_ratio = 1.25; // 1.5 } void setup_mpc_vars(pr2MPC_params& problem, pr2MPC_output& output) { // inputs H = new pr2MPC_FLOAT*[T]; f = new pr2MPC_FLOAT*[T]; lb = new pr2MPC_FLOAT*[T]; ub = new pr2MPC_FLOAT*[T]; c = problem.c1; A = problem.A5; // TODO: hard-coded b = problem.b5; // output z = new pr2MPC_FLOAT*[T]; #define SET_VARS(n) \ H[ BOOST_PP_SUB(n,1) ] = problem.H##n ; \ f[ BOOST_PP_SUB(n,1) ] = problem.f##n ; \ lb[ BOOST_PP_SUB(n,1) ] = problem.lb##n ; \ ub[ BOOST_PP_SUB(n,1) ] = problem.ub##n ; \ z[ BOOST_PP_SUB(n,1) ] = output.z##n ; #define BOOST_PP_LOCAL_MACRO(n) SET_VARS(n) #define BOOST_PP_LOCAL_LIMITS (1, TIMESTEPS) #include BOOST_PP_LOCAL_ITERATE() for(int i=0; i < J_DIM; ++i) { c[i] = INFTY; } for(int i=0; i < (2*G_DIM)*J_DIM; ++i) { A[i] = INFTY; } for(int i=0; i < (2*G_DIM); ++i) { b[i] = INFTY; } for(int t=0; t < T-1; ++t) { for(int i=0; i < (J_DIM+U_DIM); ++i) { H[t][i] = INFTY; } for(int i=0; i < (J_DIM+U_DIM); ++i) { f[t][i] = INFTY; } for(int i=0; i < (J_DIM+U_DIM); ++i) { lb[t][i] = INFTY; } for(int i=0; i < (J_DIM+U_DIM); ++i) { ub[t][i] = INFTY; } for(int i=0; i < (J_DIM+U_DIM); ++i) { z[t][i] = INFTY; } } for(int i=0; i < J_DIM; ++i) { H[T-1][i] = INFTY; } for(int i=0; i < J_DIM; ++i) { f[T-1][i] = INFTY; } for(int i=0; i < J_DIM; ++i) { lb[T-1][i] = INFTY; } for(int i=0; i < J_DIM; ++i) { ub[T-1][i] = INFTY; } for(int i=0; i < J_DIM; ++i) { z[T-1][i] = INFTY; } } void cleanup_mpc_vars() { delete[] H; delete[] f; delete[] lb; delete[] ub; delete[] z; delete c; delete A; delete b; } template<typename Derived> inline void fill_col_major(double *X, const MatrixBase<Derived>& M) { int index = 0; for(int j=0; j < M.cols(); ++j) { for(int i=0; i < M.rows(); ++i) { X[index++] = M(i,j); } } } bool is_valid_inputs() { // for(int t = 0; t < T-1; ++t) { // std::cout << "\n\nt: " << t << "\n"; // // if (t == 0) { // std::cout << "\nc[0]:\n"; // for(int i=0; i < (J_DIM); ++i) { // std::cout << c[i] << " "; // } // } // // std::cout << "\nH[" << t << "]: "; // for(int i=0; i < (J_DIM+U_DIM); ++i) { // std::cout << H[t][i] << " "; // } // // std::cout << "\nf[" << t << "]: "; // for(int i=0; i < (J_DIM+U_DIM); ++i) { // std::cout << f[t][i] << " "; // } // // std::cout << "\nlb[" << t << "]: "; // for(int i=0; i < (J_DIM+U_DIM); ++i) { // std::cout << lb[t][i] << " "; // } // // std::cout << "\nub[" << t << "]: "; // for(int i=0; i < (J_DIM+U_DIM); ++i) { // std::cout << ub[t][i] << " "; // } // } // std::cout << "\n\nt: " << T-1 << "\n"; // // std::cout << "\nH[" << T-1 << "]: "; // for(int i=0; i < (J_DIM); ++i) { // std::cout << H[T-1][i] << " "; // } // // std::cout << "\nf[" << T-1 << "]: "; // for(int i=0; i < (J_DIM); ++i) { // std::cout << f[T-1][i] << " "; // } // // std::cout << "\nlb[" << T-1 << "]: "; // for(int i=0; i < (J_DIM); ++i) { // std::cout << lb[T-1][i] << " "; // } // // std::cout << "\nub[" << T-1 << "]: "; // for(int i=0; i < (J_DIM); ++i) { // std::cout << ub[T-1][i] << " "; // } // // std::cout << "\nA[" << T-1 << "]:\n"; // for(int i=0; i < 2*G_DIM; ++i) { // for(int j=0; j < J_DIM; ++j) { // std::cout << A[i+j*(2*G_DIM)] << " "; // } // std::cout << "\n"; // } // std::cout << "\n"; // // std::cout << "b[" << T-1 << "]: "; // for(int i=0; i < 2*G_DIM; ++i) { // std::cout << b[i] << " "; // } // // std::cout << "\n\n"; for(int i=0; i < (J_DIM); ++i) { if (c[i] > INFTY/2) { LOG_ERROR("isValid0"); return false; } } for(int i=0; i < (J_DIM); ++i) { if (c[i] < lb[0][i]) { LOG_ERROR("isValid1"); return false; } } for(int i=0; i < (J_DIM); ++i) { if (c[i] > ub[0][i]) { LOG_ERROR("isValid2"); return false; } } for(int i=0; i < (2*G_DIM)*J_DIM; ++i) { if (A[i] > INFTY/2) { LOG_ERROR("isValid3"); return false; } } for(int i=0; i < (2*G_DIM); ++i) { if (b[i] > INFTY/2) { LOG_ERROR("isValid4"); return false; } } for(int t = 0; t < T-1; ++t) { for(int i=0; i < (J_DIM+U_DIM); ++i) { if (H[t][i] > INFTY/2) { LOG_ERROR("isValid5"); return false; } } for(int i=0; i < (J_DIM+U_DIM); ++i) { if (f[t][i] > INFTY/2) { LOG_ERROR("isValid6"); return false; } } for(int i=0; i < (J_DIM+U_DIM); ++i) { if (lb[t][i] > INFTY/2) { LOG_ERROR("isValid7"); return false; } } for(int i=0; i < (J_DIM+U_DIM); ++i) {if (ub[t][i] > INFTY/2) { LOG_ERROR("isValid8"); return false; } } for(int i=0; i < (J_DIM+U_DIM); ++i) {if (ub[t][i] < lb[t][i]) { LOG_ERROR("isValid9"); return false; } } } for(int i=0; i < (J_DIM); ++i) { if (H[T-1][i] > INFTY/2) { LOG_ERROR("isValid10"); return false; } } for(int i=0; i < (J_DIM); ++i) { if (f[T-1][i] > INFTY/2) { LOG_ERROR("isValid11"); return false; } } for(int i=0; i < (J_DIM); ++i) { if (lb[T-1][i] > INFTY/2) { LOG_ERROR("isValid12"); return false; } } for(int i=0; i < (J_DIM); ++i) { if (ub[T-1][i] > INFTY/2) { LOG_ERROR("isValid13"); return false; } } for(int i=0; i < (J_DIM); ++i) {if (ub[T-1][i] < lb[T-1][i]) { LOG_ERROR("isValid14"); return false; } } return true; } void L_BFGS(const StdVectorJ& J, const StdVectorU& U, const VectorTOTAL &grad, const StdVectorJ &Jopt, const StdVectorU &Uopt, const VectorTOTAL &gradopt, MatrixTOTAL &hess) { VectorTOTAL s = VectorTOTAL::Zero(); int index = 0; for(int t=0; t < T-1; ++t) { s.segment<J_DIM>(index) = Jopt[t] - J[t]; index += J_DIM; s.segment<U_DIM>(index) = Uopt[t] - U[t]; index += U_DIM; } s.segment<J_DIM>(index) = Jopt[T-1] - J[T-1]; VectorTOTAL y = gradopt - grad; double theta; VectorTOTAL hess_s = hess*s; bool decision = s.dot(y) >= .2*s.dot(hess_s); if (decision) { theta = 1; } else { theta = (.8*s.dot(hess_s))/(s.dot(hess_s) - s.dot(y)); } VectorTOTAL r = theta*y + (1-theta)*hess_s; hess = hess - (hess_s*hess_s.transpose())/(s.dot(hess_s)) + (r*r.transpose())/s.dot(r); } double pr2_approximate_collocation(StdVectorJ& J, StdVectorU& U, const MatrixJ& j_sigma0, const std::vector<ParticleGaussian>& particle_gmm, const double alpha, PR2System& sys, pr2MPC_params &problem, pr2MPC_output &output, pr2MPC_info &info) { int max_iter = 100; double Xeps = cfg::Xeps_initial; double Ueps = cfg::Ueps_initial; double merit = 0, meritopt = 0; double constant_cost, hessian_constant, jac_constant; VectorTOTAL grad = VectorTOTAL::Zero(); MatrixTOTAL hess = MatrixTOTAL::Identity(); StdVectorJ Jopt(T, VectorJ::Zero()); StdVectorU Uopt(T-1, VectorU::Zero()); VectorTOTAL gradopt = VectorTOTAL::Zero(); double optcost, model_merit, new_merit; double approx_merit_improve, exact_merit_improve, merit_improve_ratio; LOG_DEBUG("Initial trajectory cost: %4.10f", sys.cost_gmm(J, j_sigma0, U, particle_gmm, alpha)); int index = 0; bool solution_accepted = true; for(int it=0; it < max_iter; ++it) { LOG_DEBUG(" "); LOG_DEBUG(" "); LOG_DEBUG("Iter: %d", it); // only compute gradient/hessian if P/U has been changed if (solution_accepted) { if (it == 0) { merit = sys.cost_gmm(J, j_sigma0, U, particle_gmm, alpha); grad = sys.cost_gmm_grad_ripped(J, j_sigma0, U, particle_gmm, alpha); } else { merit = meritopt; // since L-BFGS calculation required it grad = gradopt; } std::cout << "gradient:\n" << grad << "\n"; VectorTOTAL diaghess = hess.diagonal(); constant_cost = 0; hessian_constant = 0; jac_constant = 0; // fill in Hessian first so we can force it to be PSD index = 0; for(int t=0; t < T-1; ++t) { for(int i=0; i < (J_DIM+U_DIM); ++i) { double val = diaghess(index++); H[t][i] = (val < 0) ? 0 : val; } } for(int i=0; i < J_DIM; ++i) { double val = diaghess(index++); H[T-1][i] = (val < 0) ? 0 : val; } // fill in gradient index = 0; for(int t=0; t < T-1; ++t) { Matrix<double,(J_DIM+U_DIM),1> zbar; zbar.segment<J_DIM>(0) = J[t]; zbar.segment<U_DIM>(J_DIM) = U[t]; for(int i=0; i < (J_DIM+U_DIM); ++i) { hessian_constant += H[t][i]*zbar(i)*zbar(i); jac_constant -= grad(index)*zbar(i); f[t][i] = grad(index) - H[t][i]*zbar(i); index++; } } VectorJ zbar = J[T-1]; for(int i=0; i < J_DIM; ++i) { hessian_constant += H[T-1][i]*zbar(i)*zbar(i); jac_constant -= grad(index)*zbar(i); f[T-1][i] = grad(index) - H[T-1][i]*zbar(i); index++; } for(int i=0; i < J_DIM; ++i) { c[i] = J[0](i); } constant_cost = 0.5*hessian_constant + jac_constant + merit; } VectorJ j_min, j_max; VectorU u_min, u_max; sys.get_limits(j_min, j_max, u_min, u_max); // set trust region bounds based on current trust region size for(int t=0; t < T; ++t) { index = 0; for(int i=0; i < J_DIM; ++i) { lb[t][index] = std::max(j_min(i), J[t](i) - Xeps); ub[t][index] = std::min(j_max(i), J[t](i) + Xeps); if (ub[t][index] < lb[t][index]) { ub[t][index] = lb[t][index] + epsilon; } index++; } if (t < T-1) { // set each input lower/upper bound for(int i=0; i < U_DIM; ++i) { lb[t][index] = std::max(u_min(i), U[t](i) - Ueps); ub[t][index] = std::min(u_max(i), U[t](i) + Ueps); if (ub[t][index] < lb[t][index]) { ub[t][index] = lb[t][index] + epsilon; } index++; } } } // end goal constraint on end effector Arm* arm = sys.get_arm(); Vector3d goal_pos = arm->get_position(J.back());//particle_gmm[0].mean; double goal_delta = .1; Vector3d arm_pos = arm->get_position(J.back()); MatrixJac arm_pos_jac = arm->get_position_jacobian(J.back()); Matrix<double,2*G_DIM,J_DIM> Amat; Amat.block<G_DIM,J_DIM>(0,0) = arm_pos_jac; Amat.block<G_DIM,J_DIM>(G_DIM,0) = -arm_pos_jac; Amat.setZero(); // TODO: tmp fill_col_major(A, Amat); Matrix<double,2*G_DIM,1> bVec; bVec.segment<G_DIM>(0) = goal_pos - arm_pos + arm_pos_jac*J.back() + goal_delta*Matrix<double,G_DIM,1>::Ones(); bVec.segment<G_DIM>(G_DIM) = -goal_pos + arm_pos - arm_pos_jac*J.back() + goal_delta*Matrix<double,G_DIM,1>::Ones(); bVec.setZero(); // TODO: tmp fill_col_major(b, bVec); // Verify problem inputs if (!is_valid_inputs()) { LOG_ERROR("Inputs are not valid!"); exit(0); } // call FORCES int exitflag = pr2MPC_solve(&problem, &output, &info); if (exitflag == 1) { optcost = info.pobj; for(int t=0; t < T; ++t) { index = 0; for(int i=0; i < J_DIM; ++i) { Jopt[t](i) = z[t][index++]; } if (t < T-1) { for(int i=0; i < U_DIM; ++i) { Uopt[t](i) = z[t][index++]; } } } } else { LOG_FATAL("Some problem in solver"); LOG_FATAL("Continuing"); return INFINITY; } // LOG_DEBUG("Displaying Jopt"); // sys.display(Jopt, particle_gmm); model_merit = optcost + constant_cost; // need to add constant terms that were dropped new_merit = sys.cost_gmm(Jopt, j_sigma0, Uopt, particle_gmm, alpha); LOG_DEBUG("merit: %f", merit); LOG_DEBUG("model_merit: %f", model_merit); LOG_DEBUG("new_merit: %f", new_merit); LOG_DEBUG("constant cost term: %f", constant_cost); approx_merit_improve = merit - model_merit; exact_merit_improve = merit - new_merit; merit_improve_ratio = exact_merit_improve / approx_merit_improve; LOG_DEBUG("approx_merit_improve: %f", approx_merit_improve); LOG_DEBUG("exact_merit_improve: %f", exact_merit_improve); LOG_DEBUG("merit_improve_ratio: %f", merit_improve_ratio); if (approx_merit_improve < -1) { LOG_ERROR("Approximate merit function got worse: %f", approx_merit_improve); LOG_DEBUG("Shrinking trust region"); Xeps *= cfg::trust_shrink_ratio; Ueps *= cfg::trust_shrink_ratio; solution_accepted = false; // return INFTY; } else if (approx_merit_improve < cfg::min_approx_improve) { LOG_DEBUG("Converged: improvement small enough"); J = Jopt; U = Uopt; solution_accepted = true; return sys.cost_gmm(J, j_sigma0, U, particle_gmm, alpha); } else if ((exact_merit_improve < 0) || (merit_improve_ratio < cfg::improve_ratio_threshold)) { Xeps *= cfg::trust_shrink_ratio; Ueps *= cfg::trust_shrink_ratio; LOG_DEBUG("Shrinking trust region size to: %2.6f %2.6f", Xeps, Ueps); solution_accepted = false; } else { // expand Xeps and Ueps Xeps *= cfg::trust_expand_ratio; Ueps *= cfg::trust_expand_ratio; LOG_DEBUG("Accepted, Increasing trust region size to: %2.6f %2.6f", Xeps, Ueps); meritopt = sys.cost_gmm(Jopt, j_sigma0, Uopt, particle_gmm, alpha); gradopt = sys.cost_gmm_grad_ripped(Jopt, j_sigma0, Uopt, particle_gmm, alpha); L_BFGS(J, U, grad, Jopt, Uopt, gradopt, hess); J = Jopt; U = Uopt; solution_accepted = true; } } return sys.cost_gmm(J, j_sigma0, U, particle_gmm, alpha); } double pr2_collocation(StdVectorJ& J, StdVectorU& U, const MatrixJ& j_sigma0, const std::vector<ParticleGaussian>& particle_gmm, PR2System& sys, pr2MPC_params &problem, pr2MPC_output &output, pr2MPC_info &info) { double alpha = cfg::alpha_init; double cost = INFINITY; for(int num_alpha_increases=0; num_alpha_increases < cfg::alpha_max_increases; ++num_alpha_increases) { LOG_DEBUG("Calling approximate collocation with alpha = %4.2f", alpha); cost = pr2_approximate_collocation(J, U, j_sigma0, particle_gmm, alpha, sys, problem, output, info); LOG_DEBUG("Reintegrating trajectory"); for(int t=0; t < T-1; ++t) { J[t+1] = sys.dynfunc(J[t], U[t], VectorQ::Zero()); } // double max_delta_diff = -INFINITY; // for(int t=0; t < T; ++t) { // double delta_alpha = sys.delta_matrix(J[t], particle_gmm[0].mean, alpha, particle_gmm[0].ODF)(J_DIM,J_DIM); // double delta_inf = sys.delta_matrix(J[t], particle_gmm[0].mean, INFTY, particle_gmm[0].ODF)(J_DIM,J_DIM); // max_delta_diff = std::max(max_delta_diff, fabs(delta_alpha - delta_inf)); // } // // LOG_DEBUG(" "); // LOG_DEBUG("Max delta difference: %4.2f", max_delta_diff); // if (max_delta_diff < cfg::alpha_epsilon) { // LOG_DEBUG("Max delta difference < %4.10f, exiting minimize merit", cfg::alpha_epsilon); // break; // } LOG_DEBUG("Increasing alpha by gain %4.5f", cfg::alpha_gain); alpha *= cfg::alpha_gain; } return cost; } void init_collocation(const VectorJ& j0, const MatrixP& P, PR2System& sys, StdVectorJ& J, StdVectorU& U, std::vector<ParticleGaussian>& particle_gmm) { // re-initialize GMM from PF sys.fit_gaussians_to_pf(P, particle_gmm); // only take max gaussian particle_gmm = std::vector<ParticleGaussian>(1, particle_gmm[0]); for(int i=0; i < particle_gmm.size(); ++i) { // particle_gmm[i].cov *= 1000; // 5000 std::cout << particle_gmm[i].pct << "\n"; std::cout << particle_gmm[i].cov << "\n\n"; particle_gmm[i].ODF = sys.get_ODF(particle_gmm[i].mean); } Arm* arm = sys.get_arm(); VectorJ j = j0; arm->ik(.99*arm->get_position(j0) + .01*particle_gmm[0].mean, j); // TODO: try a non-zero initialization VectorU uinit = VectorU::Zero(); // VectorU uinit = (j - j0) / (DT*(TIMESTEPS-1)); // integrate trajectory J[0] = j0; for(int t=0; t < T-1; ++t) { U[t] = uinit; J[t+1] = sys.dynfunc(J[t], U[t], VectorQ::Zero()); } } MatrixP init_particles(rave::EnvironmentBasePtr env) { rave::KinBodyPtr table = env->GetKinBody("table"); rave::KinBody::LinkPtr base = table->GetLink("base"); rave::Vector extents = base->GetGeometry(0)->GetBoxExtents(); rave::Vector table_pos = table->GetTransform().trans; double x_min, x_max, y_min, y_max, z_min, z_max; // x_min = table_pos.x - extents.x; // x_max = table_pos.x + extents.x; // y_min = table_pos.y - extents.y; // y_max = table_pos.y + extents.y; // z_min = table_pos.z + extents.z; // z_max = table_pos.z + extents.z + .2; // x_min = table_pos.x - extents.x; // x_max = table_pos.x + extents.x; // y_min = table_pos.y - extents.y; // y_max = table_pos.y;// + extents.y; // z_min = table_pos.z + extents.z - .1; // z_max = table_pos.z + extents.z - .2;// + .2; x_min = table_pos.x - extents.x; x_max = table_pos.x + extents.x; y_min = table_pos.y;// - extents.y; y_max = table_pos.y + extents.y; z_min = table_pos.z + extents.z - .1; z_max = table_pos.z + extents.z + .2; MatrixP P; // uniform for(int m=0; m < M_DIM; ++m) { P(0,m) = pr2_utils::uniform(x_min, x_max); P(1,m) = pr2_utils::uniform(y_min, y_max); P(2,m) = pr2_utils::uniform(z_min, z_max); } // two clumps // for(int m=0; m < M_DIM; ++m) { // if (m < M_DIM/2) { // P(0,m) = mm_utils::uniform(x_min, .7*x_min + .3*x_max); // P(1,m) = mm_utils::uniform(y_min, y_max); // P(2,m) = mm_utils::uniform(z_min, z_max); // } else { // P(0,m) = mm_utils::uniform(.3*x_min + .7*x_max, x_max); // P(1,m) = mm_utils::uniform(y_min, y_max); // P(2,m) = mm_utils::uniform(z_min, z_max); // } // } return P; } int main(int argc, char* argv[]) { // Vector3d object(3.35, -1.11, 0.8); Vector3d object = Vector3d(3.5+0, -1.2+.5, .74+.05); // Vector3d object = Vector3d(3.5+.1, -1.2-.1, .74-.1); Arm::ArmType arm_type = Arm::ArmType::right; bool view = true; PR2System sys(object, arm_type, view); PR2* brett = sys.get_brett(); rave::EnvironmentBasePtr env = brett->get_env(); Camera* cam = sys.get_camera(); Arm* arm = sys.get_arm(); arm->set_posture(Arm::Posture::mantis); // initialize starting state, belief, and pf VectorJ j_t, j_t_real, j_tp1, j_tp1_real; j_t = arm->get_joint_values(); j_t_real = j_t; // TODO: have them be different MatrixJ j_sigma0 = .2*MatrixJ::Identity(); // TODO: never actually update it in MPC MatrixP P_t, P_tp1; P_t = init_particles(env); std::vector<ParticleGaussian> particle_gmm; // initialize state and controls StdVectorU U(T-1, VectorU::Zero()); StdVectorJ J(T); // initialize FORCES pr2MPC_params problem; pr2MPC_output output; pr2MPC_info info; setup_mpc_vars(problem, output); util::Timer forces_timer; bool stop_condition = false; for(int iter=0; !stop_condition; iter++) { arm->set_joint_values(j_t); LOG_INFO("Updating internal TSDF and kinfu\n"); StdVector3d pc = cam->get_pc(j_t_real); Matrix<double,HEIGHT_FULL,WIDTH_FULL> full_zbuffer = cam->get_full_zbuffer(j_t_real, pc); Matrix4d cam_pose = cam->get_pose(j_t_real); sys.update(pc, full_zbuffer, cam_pose); LOG_INFO("MPC iteration: %d",iter); init_collocation(j_t, P_t, sys, J, U, particle_gmm); LOG_INFO("Current state"); sys.display(j_t, particle_gmm); LOG_INFO("Initialized trajectory"); sys.display(J, particle_gmm); // optimize util::Timer_tic(&forces_timer); double cost = pr2_collocation(J, U, j_sigma0, particle_gmm, sys, problem, output, info); double forces_time = util::Timer_toc(&forces_timer); LOG_INFO("Optimized cost: %4.5f", cost); LOG_INFO("Solve time: %5.3f ms", forces_time*1000); for(int t=0; t < T-1; ++t) { J[t+1] = sys.dynfunc(J[t], U[t], VectorQ::Zero()); } LOG_INFO("Post-optimization"); sys.display(J, particle_gmm); sys.execute_control_step(j_t_real, j_t, U[0], P_t, particle_gmm[0].ODF, j_tp1_real, j_tp1, P_tp1); // TODO: stop condition j_t_real = j_tp1_real; j_t = j_tp1; P_t = P_tp1; } return 0; }
#ifndef LOGIC_HPP #define LOGIC_HPP #include <iostream> #include "user_interface.hpp" #include "imagem_ppm.hpp" #include "imagem_pgm.hpp" #include "imagem.hpp" class Logic : public UserInterface { private: int desejaContinuarInt=1; int desejaSairInt = 0; public: Logic(); ~Logic(); void aplicacaoPGM(); void aplicacaoPPM(); void menu(); string pegarCaminhoDaImagem(); void aplicacao(); void desejaContinuar(); void setDesejaContinuar(int desejaContinuar); void setDesejaSair(); }; #endif
#ifndef OPTICALFLOW_SLAM_ALGORITHM_BASE_COMPONENT_CAMERA_CONFIG_H_ #define OPTICALFLOW_SLAM_ALGORITHM_BASE_COMPONENT_CAMERA_CONFIG_H_ #include "algorithm/common_include.h" namespace OpticalFlow_SLAM_algorithm_opticalflow_slam { /** * @brief Camera config params * @author snowden * @date 2021-07-16 * @version 1.0 */ struct CameraConfig { EIGEN_MAKE_ALIGNED_OPERATOR_NEW; public: ~CameraConfig() {}; void show_camera_config_info(); static std::shared_ptr<CameraConfig> getCameraConfig(); double_t fx_left { 0.0 }; double_t fy_left { 0.0 }; double_t cx_left { 0.0 }; double_t cy_left { 0.0 }; double_t r1_left { 0.0 }; double_t r2_left { 0.0 }; double_t r3_left { 0.0 }; double_t p1_left { 0.0 }; double_t p2_left { 0.0 }; double_t fx_right { 0.0 }; double_t fy_right { 0.0 }; double_t cx_right { 0.0 }; double_t cy_right { 0.0 }; double_t r1_right { 0.0 }; double_t r2_right { 0.0 }; double_t r3_right { 0.0 }; double_t p1_right { 0.0 }; double_t p2_right { 0.0 }; //TODO(snowden) : K_left and K_right will be accessed by mutil thread, so need be set private and set lock; Mat33 K_left; Mat33 K_right; /** * @warning: base_line may be negative number, not absolute distance; */ Vec3 base_line; Mat44 T_left; Mat44 T_right; private: //TODO(snowden): need add synchronized operate for mulit thread; static std::shared_ptr<CameraConfig> camera_config ; CameraConfig() {}; }; //CameraConfig } //namespace OpticalFlow_SLAM_algorithm_opticalflow_slam #endif //OPTICALFLOW_SLAM_ALGORITHM_BASE_COMPONENT_CAMERA_CONFIG_H_
#pragma once #include <string> class Zombie { private: int health = 100; int attack = 20; public: std::string name; void takeDamage(int damage); void fight(); int getHealth(); int getDamage(); bool canHit(); };
#include <QApplication> #include <QMainWindow> #include <iostream> #include "mainwindow.h" int main(int argc, char *argv[]){ QApplication a (argc, argv); MainWindow gui; gui.show(); return a.exec(); }
#ifndef _JERARQUIA #define _JERARQUIA #include "3Dmodel.h" class Jerarquia : public Modelo{ private: vector <Modelo> figuras; int numero_figuras; double angle_munieca = 0; double angle_dedos = 0; double angle_brazo = 0; double angle_dedosb = 0; double trans = 0; double tipo = 0; double control[5]; public: Jerarquia(); Jerarquia(vector <Modelo> figuras); void dibujar(int j = 0); void aniade_figura(Modelo figura); void girar_munieca(int i =4); void saludar(int i =4); void indice(int i = 4); void senialar(int i = 4); }; #endif
/* ***************************************************************************** * ___ _ _ _ _ * / _ \ __ _| |_| |__(_) |_ ___ * | (_) / _` | / / '_ \ | _(_-< * \___/\__,_|_\_\_.__/_|\__/__/ * Copyright (c) 2013 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *****************************************************************************/ /** * @author R. Picard * @date 2013/07/01 * *****************************************************************************/ #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" #include "SliceFreeProbe.h" #include "ExeContext.h" extern "C" { void g_slice_free1(gsize block_size, gpointer mem_block) { mock().actualCall("g_slice_free1") .withParameter("block_size", (int)block_size) .withParameter("mem_block", mem_block); } void xunit_slice_free(gsize block_size, gpointer mem_block) { mock().actualCall("xunit_slice_free") .withParameter("block_size", (int)block_size) .withParameter("mem_block", mem_block); } } TEST_GROUP(SliceFreeTestGroup) { void teardown() { mock().clear(); } }; TEST(SliceFreeTestGroup, Build) { GLib::SliceFreeProbe Probe; GLib::SliceFreeProbe *p_Probe; p_Probe = new(std::nothrow) GLib::SliceFreeProbe(); CHECK(p_Probe != NULL); delete p_Probe; } TEST(SliceFreeTestGroup, FreeOK) { CallStack Callers; ExeContext *Context = ExeContext::Get(Callers); int AllocSize = 31; /* Add an entry in the heap and context lists */ CHECK(Context != NULL); Context->UpdateMemory(AllocSize); HeapEntry *Entry = new (std::nothrow) HeapEntry(AllocSize, Context); CHECK(Entry != NULL); MemHeap *Heap = MemHeap::Instantiate(); CHECK(Heap != NULL); Heap->GetEntryList()->AppendItem(Entry); mock().expectOneCall("rtsym_resolve") .withParameter("Symbol", "g_slice_free1") .andReturnValue((void*)g_slice_free1); mock().expectOneCall("g_slice_free1") .withParameter("block_size", (int)(AllocSize+sizeof(HeapEntry))) .withParameter("mem_block", Entry); /* Free the entry */ GLib::SliceFreeProbe Probe; Probe.InitCheck(); uint8_t *Data = (uint8_t*)Entry; Probe.Free(AllocSize, Data+sizeof(HeapEntry)); CHECK_EQUAL(0, (int)Context->GetMemory() ); mock().checkExpectations(); ExeContext::Reset(); delete Entry; } TEST(SliceFreeTestGroup, FreeNullFunc) { GLib::SliceFreeProbe Probe; Probe.Free(31, NULL); mock().checkExpectations(); } TEST(SliceFreeTestGroup, FreeNull) { int AllocSize = 31; mock().expectOneCall("rtsym_resolve") .withParameter("Symbol", "g_slice_free1") .andReturnValue((void*)g_slice_free1); mock().expectOneCall("g_slice_free1") .withParameter("block_size", AllocSize) .withParameter("mem_block", (void*)NULL); /* Free the entry */ GLib::SliceFreeProbe Probe; Probe.InitCheck(); Probe.Free(AllocSize, NULL); mock().checkExpectations(); } TEST(SliceFreeTestGroup, FreeHeapLocked) { CallStack Callers; ExeContext *Context = ExeContext::Get(Callers); int AllocSize = 31; /* Add an entry in the heap and context lists */ CHECK(Context != NULL); Context->UpdateMemory(AllocSize); HeapEntry *Entry = new (std::nothrow) HeapEntry(AllocSize, Context); CHECK(Entry != NULL); MemHeap *Heap = MemHeap::Instantiate(); CHECK(Heap != NULL); Heap->Lock(); Heap->GetEntryList()->AppendItem(Entry); mock().expectOneCall("rtsym_resolve") .withParameter("Symbol", "g_slice_free1") .andReturnValue((void*)g_slice_free1); mock().expectOneCall("g_slice_free1") .withParameter("block_size", AllocSize) .withParameter("mem_block", Entry); /* Free the entry */ GLib::SliceFreeProbe Probe; Probe.InitCheck(); Probe.Free(AllocSize, Entry); CHECK_EQUAL(AllocSize, (int)Context->GetMemory() ); mock().checkExpectations(); ExeContext::Reset(); MemHeap::Instantiate()->Reset(); delete Entry; Heap->Unlock(); } /* Passthrough without free function as parameter */ TEST(SliceFreeTestGroup, Passthrough1) { int AllocSize = 31; int Data; mock().expectOneCall("rtsym_resolve") .withParameter("Symbol", "g_slice_free1") .andReturnValue((void*)g_slice_free1); mock().expectOneCall("g_slice_free1") .withParameter("block_size", AllocSize) .withParameter("mem_block", (void*)&Data); /* Free the entry */ GLib::SliceFreeProbe Probe; Probe.PassThrough(AllocSize, &Data); mock().checkExpectations(); } /* Passthrough without free function as parameter and rtsym_resolve returning * NULL */ TEST(SliceFreeTestGroup, Passthrough2) { int AllocSize = 31; int Data; mock().expectOneCall("rtsym_resolve") .withParameter("Symbol", "g_slice_free1") .andReturnValue((void*)NULL); /* Free the entry */ GLib::SliceFreeProbe Probe; Probe.PassThrough(AllocSize, &Data); mock().checkExpectations(); } /* Passthrough with free function as parameter */ TEST(SliceFreeTestGroup, Passthrough3) { int AllocSize = 31; int Data; mock().expectOneCall("rtsym_resolve") .withParameter("Symbol", "xunit_slice_free") .andReturnValue((void*)xunit_slice_free); mock().expectOneCall("xunit_slice_free") .withParameter("block_size", AllocSize) .withParameter("mem_block", (void*)&Data); /* Free the entry */ GLib::SliceFreeProbe Probe; Probe.PassThrough(AllocSize, &Data, "xunit_slice_free"); mock().checkExpectations(); } /* Passthrough with free function as parameter and rtsym_resolve returning * NULL */ TEST(SliceFreeTestGroup, Passthrough4) { int AllocSize = 31; int Data; mock().expectOneCall("rtsym_resolve") .withParameter("Symbol", "xunit_slice_free") .andReturnValue((void*)NULL); /* Free the entry */ GLib::SliceFreeProbe Probe; Probe.PassThrough(AllocSize, &Data, "xunit_slice_free"); mock().checkExpectations(); }
/* * main.cpp * * Created on: Feb 3, 2017 * Author: kushn_du3a95r */ //============================================================================ // Name : sudoku.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include "sudoku.h" #include "cell.h" #include "row.h" #include "sudokuinit.h" int main(int argc, char **argv) { SudokuCallback sudokuCallback; Sudoku sudoku(sudokuCallback); if (SudokuInit::debugBoard()) cout << "main: init" << endl; sudoku.init(argc, argv); /* * algorithm: * - take the starting board * - pick the empty cell with the fewest possible values -- many ties * - for its row, column, and box, add the total of filled cells * to break the ties * - for each possibility of the empty cell, create a new board * with that value filled in, and put it in a queue ordered by * the total number of cells filled in * - take the next board off the queue, and process as above if * the board is not complete. */ if (SudokuInit::debugBoard()) cout << "main: process" << endl; sudoku.process(); return 0; }
#include "NodoBinario.h" template< class T > NodoBinario<T>::NodoBinario() { this->hijoIzq = NULL; this->hijoDer = NULL; } template< class T > NodoBinario<T>::NodoBinario(T val) { this->hijoIzq = NULL; this->hijoDer = NULL; this->dato = val; } template< class T > NodoBinario<T>::~NodoBinario() { if (this->hijoIzq != NULL) { delete this->hijoIzq; this->hijoIzq = NULL; } if (this->hijoDer != NULL) { delete this->hijoDer; this->hijoDer = NULL; } } template< class T > T NodoBinario<T>::obtenerDato() { return this->dato; } template< class T > void NodoBinario<T>::fijarDato(T val) { this->dato = val; } template< class T > NodoBinario<T>* NodoBinario<T>::obtenerHijoIzq() { return this->hijoIzq; } template< class T > NodoBinario<T>* NodoBinario<T>::obtenerHijoDer() { return this->hijoDer; } template< class T > void NodoBinario<T>::fijarHijoIzq(NodoBinario<T>* izq) { this->hijoIzq = izq; } template< class T > void NodoBinario<T>::fijarHijoDer(NodoBinario<T>* der) { this->hijoDer = der; } template< class T > bool NodoBinario<T>::esHoja() { return (this->hijoIzq == NULL && this->hijoDer == NULL); } template< class T > int NodoBinario<T>::altura() { int valt; if (this->esHoja()) { valt = 0; } else { int valt_izq = -1; int valt_der = -1; if (this->hijoIzq != NULL) valt_izq = (this->hijoIzq)->altura(); if (this->hijoDer != NULL) valt_der = (this->hijoDer)->altura(); if (valt_izq > valt_der) valt = valt_izq + 1; else valt = valt_der + 1; } return valt; } template< class T > void NodoBinario<T>::inOrden() { if (this->hijoIzq != NULL) (this->hijoIzq)->inOrden(); std::cout << this->dato << " "; if (this->hijoDer != NULL) (this->hijoDer)->inOrden(); } template< class T > void NodoBinario<T>::preOrden() { std::cout << this->dato << " "; if (this->hijoIzq != NULL) (this->hijoIzq)->preOrden(); if (this->hijoDer != NULL) (this->hijoDer)->preOrden(); } template< class T > void NodoBinario<T>::posOrden() { if (this->hijoIzq != NULL) (this->hijoIzq)->posOrden(); if (this->hijoDer != NULL) (this->hijoDer)->posOrden(); std::cout << this->dato << " "; }
#include "Utilities/Definitions.h" #include "Utilities/CodeTimer.h" #include "Utilities/SpaceMappedDataPersistenceHandler.h" #include "Utilities/MappedFileDataPersistenceHandler.h" #include "MagneticFieldComponents/MagneticFieldFactory.h" #include <boost/filesystem.hpp> using storage = Utilities::_storage3D<float>; using volume = CoordinateComponents::CartesianVolumeRef<float>; int main() { std::shared_ptr<Utilities::IDataPersistenceHandler<storage>> handlerIn(new Utilities::MappedFileDataPersistenceHandler<storage>()); boost::filesystem::path tempPath = boost::filesystem::temp_directory_path(); // Total space is 64x64x64 divided into blocks of 16x16x16 Utilities::Space calculationSpace(64, 4, 64, 4, 64, 4); Utilities::SpaceMappedDataPersistenceHandler<float> dataHandler(calculationSpace, handlerIn, tempPath.string()); for(size_t z = 0; z < calculationSpace.blockDimZ(); ++z) for(size_t x = 0; x < calculationSpace.blockDimX(); ++x) for(size_t y = 0; y < calculationSpace.blockDimY(); ++y) { storage* data = dataHandler.GetBlockData(x,y,z); volume convertedVolume; float mag = MagneticFieldUtilities::MagneticFieldFactory::GenerateRingCartesianVolumeField<float>(convertedVolume,.1, 10); dataHandler.PutBlockData(data); } return 1; }
/* * Copyright (C) 2012 Marcin Kościelnicki <koriakin@0x04.net> * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "hwtest.h" #include "nva.h" #include <unistd.h> #include <stdio.h> #include <pciaccess.h> int hwtest_root_prep(struct hwtest_ctx *ctx) { return HWTEST_RES_PASS; } HWTEST_DEF_GROUP(hwtest_root, HWTEST_GROUP(nv01_pgraph), HWTEST_GROUP(nv03_pgraph), HWTEST_GROUP(nv04_pgraph), HWTEST_GROUP(nv10_tile), HWTEST_GROUP(mpeg_crypt), HWTEST_GROUP(nv50_ptherm), HWTEST_GROUP(nv84_ptherm), HWTEST_GROUP(vp2_macro), HWTEST_GROUP(pvcomp_isa), HWTEST_GROUP(vp1), HWTEST_GROUP(g80_int), HWTEST_GROUP(g80_fp), HWTEST_GROUP(g80_sfu), HWTEST_GROUP(g80_fp64), HWTEST_GROUP(g80_atom32), HWTEST_GROUP(g80_atom64), ) int main(int argc, char **argv) { struct hwtest_ctx sctx; struct hwtest_ctx *ctx = &sctx; if (nva_init()) { fprintf (stderr, "PCI init failure!\n"); return 1; } int c, force = 0; ctx->cnum = 0; ctx->colors = 1; ctx->noslow = 0; ctx->indent = 0; ctx->rand48[0] = 0xdead; ctx->rand48[1] = 0xbeef; ctx->rand48[2] = 0xcafe; while ((c = getopt (argc, argv, "c:nsf")) != -1) switch (c) { case 'c': sscanf(optarg, "%d", &ctx->cnum); break; case 'n': ctx->colors = 0; break; case 's': ctx->noslow = 1; break; case 'f': force = 1; break; } if (ctx->cnum >= nva_cardsnum) { if (nva_cardsnum) fprintf (stderr, "No such card.\n"); else fprintf (stderr, "No cards found.\n"); return 1; } ctx->chipset = nva_cards[ctx->cnum]->chipset; if (nva_cards[ctx->cnum]->bus_type == NVA_BUS_PCI && pci_device_has_kernel_driver(nva_cards[ctx->cnum]->bus.pci)) { if (force) { fprintf(stderr, "WARNING: Kernel driver in use.\n"); } else { fprintf(stderr, "ERROR: Kernel driver in use. If you know what you are doing, use -f option.\n"); return 1; } } int worst = 0; if (optind == argc) { printf("Running all tests...\n"); worst = hwtest_run_group(ctx, &hwtest_root_group, 0); } else while (optind < argc) { int res = hwtest_run_group(ctx, &hwtest_root_group, argv[optind++]); if (res > worst) worst = res; } if (worst == HWTEST_RES_PASS) return 0; else return worst + 1; }
// // c2_anagram: combine part // bruk: # ./sign < words.txt | sort | ./combine #include <iostream> #include <sstream> using namespace std; int main() { string line; string prev_sign; int linenum = 0; // For å ikke printe første blank line while ( getline(cin, line)) // Les inn en linje med to ord { // Split linjen inn i to ord istringstream iss(line); string sign, word; iss >> sign; iss >> word; // if ( (sign != prev_sign) && linenum > 0 ) { cout << endl; } cout << word << " "; prev_sign = sign; linenum++; } cout << endl; }
#ifndef _HS_SFM_SFM_FILE_IO_TRACKS_LOADER_HPP_ #define _HS_SFM_SFM_FILE_IO_TRACKS_LOADER_HPP_ #include <string> #include <map> #include <fstream> #include "hs_sfm/sfm_utility/match_type.hpp" namespace hs { namespace sfm { namespace fileio { struct TracksLoader { typedef hs::sfm::TrackContainer TrackContainer; typedef hs::sfm::ViewInfoIndexer ViewInfoIndexer; typedef hs::sfm::ViewInfo ViewInfo; typedef int Err; Err operator() (const std::string& tracks_path, TrackContainer& tracks, ViewInfoIndexer& view_info_indexer) const { std::ifstream tracks_file(tracks_path.c_str(), std::ios::in); if (!tracks_file.is_open()) { return -1; } size_t number_of_tracks; tracks_file>>number_of_tracks; tracks.resize(number_of_tracks); std::map<std::pair<size_t, size_t>, int> flags; for (size_t i = 0; i < number_of_tracks; i++) { size_t number_of_views; tracks_file>>number_of_views; tracks[i].resize(number_of_views); for (size_t j = 0; j < number_of_views; j++) { size_t image_id, key_id; int flag; tracks_file>>image_id>>key_id>>flag; tracks[i][j].first = image_id; tracks[i][j].second = key_id; flags[std::make_pair(i, image_id)] = flag; } } view_info_indexer.SetViewInfoByTracks(tracks); auto itr_flag = flags.begin(); auto itr_flag_end = flags.end(); for (; itr_flag != itr_flag_end; ++itr_flag) { size_t track_id = itr_flag->first.first; size_t image_id = itr_flag->first.second; int flag = itr_flag->second; ViewInfo* view_info = view_info_indexer.GetViewInfoByTrackImage(track_id, image_id); view_info->is_blunder = (flag == 1); } return 0; } }; } } } #endif
/* * mallocTest.cpp * * Created on: March 20, 2016 * Author: myan */ #include <stdlib.h> #include <string.h> #include <list> #include <iostream> int main(int argc, char** argv) { //allocate small blocks const int nblks = 10; char* pa[nblks]; for (int i = 0; i < nblks; i++) { pa[i] = (char*)malloc(i << 2); } //allocate bigger blocsk (> threshold 256KB) const int nregions = 5; void* mpa[nregions]; const size_t sz = 256 * 1024; for (int i = 0; i < nregions; i++) { mpa[i] = malloc(sz + i * 4096); } //check fast bins std::list<void*> blklist; std::list<int> blksz; for (int sz = 1; sz < 160; sz += 16) { void *p = malloc(sz); memset(p, sz, sz); blklist.push_back(p); blksz.push_back(sz); } std::cout << "The following block should be in free state" << std::endl; std::list<void*>::iterator itr; std::list<int>::iterator itr2; for (itr = blklist.begin(), itr2 = blksz.begin(); itr != blklist.end() && itr2 != blksz.end(); itr++, itr2++) { void* p = *itr; free(p); int sz = *itr2; std::cout << "0x" << std::hex << p << " size=" << std::dec << sz << std::endl; } ::abort(); }
#ifndef MODEL_H #define MODEL_H #include <cstdlib> #include <ctime> #include <string> #include "state.h" #include "utils_vector.h" #include "utils_linked.h" #include "utils_strandsort.h" class logic_model { public: logic_model(); void Clear(); void SetArr(); void SetLinked(); void Generate(int count = 15, int maxnum = 100); void Sort(); void SortStep(); std::string ToString(); bool busy; state current; }; #endif // MODEL_H
/* Name: Mohit Kishorbhai Sheladiya Student ID: 117979203 Student Email: mksheladiya@myseneca.ca Date: 25/04/01 */ // I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. #ifndef SDDS_SEARCHNLIST_H_ #define SDDS_SEARCHNLIST_H_ #include <iostream> #include "Collection.h" #include "Car.h" #include "Employee.h" #include "Student.h" #include "ReadWrite.h" using namespace std; namespace sdds { template<typename Temp, typename A> bool search(Collection<Temp>& obj, Temp list[], int num, A key) { bool flag = false; for (int i = 0; i < num; i++) if (list[i] == key) { obj.add(list[i]); flag = true; } return flag; } template<typename Temp> void listArrayElements(const char* head, const Temp obj[], int num) { cout << head; cout << endl; for (int i = 0; i < num; i++) cout << i + 1 << ": " << obj[i] << endl; } } #endif
/* SjASMPlus Z80 Cross Compiler - modified - error/warning module Copyright (c) 2006 Sjoerd Mastijn (original SW) Copyright (c) 2020 Peter Ped Helcmanovsky (error/warning module) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ // io_err.cpp #include "sjdefs.h" #include <vector> #include <unordered_map> #include <algorithm> #include <cassert> static bool IsSkipErrors = false; static char ErrorLine[LINEMAX2], ErrorLine2[LINEMAX2]; static aint PreviousErrorLine = -1L; static const char AnsiErrorBeg[] = "\033[31m"; static const char AnsiWarningBeg[] = "\033[33m"; static const char AnsiEnd[] = "\033[m"; static void initErrorLine() { // adds filename + line of definition if possible *ErrorLine = 0; *ErrorLine2 = 0; // when OpenFile is reporting error, the filename is still nullptr, but pass==1 already if (pass < 1 || LASTPASS < pass || nullptr == CurSourcePos.filename) return; // during assembling, show also file+line info TextFilePos errorPos = DefinitionPos.line ? DefinitionPos : CurSourcePos; bool isEmittedMsgEnabled = true; #ifdef USE_LUA lua_Debug ar; // must be in this scope, as some memory is reused by errorPos if (LuaStartPos.line) { errorPos = LuaStartPos; // find either top level of lua stack, or standalone file, otherwise it's impossible // to precisely report location of error (ASM can have 2+ LUA blocks defining functions) int level = 1; // level 0 is "C" space, ignore that always // suppress "is emitted here" when directly inlined in current code isEmittedMsgEnabled = (0 < listmacro); while (true) { if (!lua_getstack(LUA, level, &ar)) break; // no more lua stack levels if (!lua_getinfo(LUA, "Sl", &ar)) break; // no more info about current level if (strcmp("[string \"script\"]", ar.short_src)) { // standalone definition in external file found, pinpoint it precisely errorPos.filename = ar.short_src; errorPos.line = ar.currentline; isEmittedMsgEnabled = true; // and add "emitted here" in any case break; // no more lua-stack traversing, stop here } // if source was inlined script, update the possible source line errorPos.line = LuaStartPos.line + ar.currentline; // and keep traversing stack until top level is found (to make the line meaningful) ++level; } } #endif //USE_LUA SPRINTF2(ErrorLine, LINEMAX2, "%s(%d): ", errorPos.filename, errorPos.line); // if the error filename:line is not identical with current source line, add ErrorLine2 about emit if (isEmittedMsgEnabled && (strcmp(errorPos.filename, CurSourcePos.filename) || errorPos.line != CurSourcePos.line)) { SPRINTF2(ErrorLine2, LINEMAX2, "%s(%d): ^ emitted from here\n", CurSourcePos.filename, CurSourcePos.line); } } static void trimAndAddEol(char* lineBuffer) { if (!lineBuffer[0]) return; // ignore empty line buffer char* lastChar = lineBuffer + strlen(lineBuffer) - 1; while (lineBuffer < lastChar && (' ' == *lastChar || '\t' == *lastChar)) --lastChar; // trim ending whitespace if ('\n' != *lastChar) lastChar[1] = '\n', lastChar[2] = 0; // add EOL character if not present } static void outputErrorLine(const EOutputVerbosity errorLevel) { auto lstFile = GetListingFile(); if (!lstFile && errorLevel < Options::OutputVerbosity) return; // no output required // trim end of error/warning line and add EOL char if needed trimAndAddEol(ErrorLine); trimAndAddEol(ErrorLine2); // always print the message into listing file (the OutputVerbosity does not apply to listing) if (lstFile) { fputs(ErrorLine, lstFile); if (*ErrorLine2) fputs(ErrorLine2, lstFile); } // print the error into stderr if OutputVerbosity allows this type of message if (Options::OutputVerbosity <= errorLevel) { if (OV_ERROR == errorLevel && Options::HasAnsiColours) _CERR AnsiErrorBeg _END; if (OV_WARNING == errorLevel && Options::HasAnsiColours) _CERR AnsiWarningBeg _END; _CERR ErrorLine _END; if (*ErrorLine2) _CERR ErrorLine2 _END; if (Options::HasAnsiColours) _CERR AnsiEnd _END; } } void Error(const char* message, const char* badValueMessage, EStatus type) { // check if it is correct pass by the type of error if (type == EARLY && LASTPASS <= pass) return; if ((type == SUPPRESS || type == IF_FIRST || type == PASS3) && pass < LASTPASS) return; // check if this one should be skipped due to type constraints and current-error-state if (FATAL != type && PreviousErrorLine == CompiledCurrentLine) { // non-fatal error, on the same line as previous, maybe skip? if (IsSkipErrors || IF_FIRST == type) return; } // update current-error-state (reset "skip" on new parsed-line, set "skip" by SUPPRESS type) IsSkipErrors = (IsSkipErrors && (PreviousErrorLine == CompiledCurrentLine)) || (SUPPRESS == type); PreviousErrorLine = CompiledCurrentLine; ++ErrorCount; // number of non-skipped (!) errors DefineTable.Replace("__ERRORS__", ErrorCount); initErrorLine(); STRCAT(ErrorLine, LINEMAX2-1, "error: "); #ifdef USE_LUA if (LuaStartPos.line) STRCAT(ErrorLine, LINEMAX2-1, "[LUA] "); #endif STRCAT(ErrorLine, LINEMAX2-1, message); if (badValueMessage) { STRCAT(ErrorLine, LINEMAX2-1, ": "); STRCAT(ErrorLine, LINEMAX2-1, badValueMessage); } outputErrorLine(OV_ERROR); // terminate whole assembler in case of fatal error if (type == FATAL) { ExitASM(1); } } void ErrorInt(const char* message, aint badValue, EStatus type) { char numBuf[24]; SPRINTF1(numBuf, 24, "%d", badValue); Error(message, numBuf, type); } void ErrorOOM() { // out of memory Error("Not enough memory!", nullptr, FATAL); } static void WarningImpl(const char* id, const char* message, const char* badValueMessage, EWStatus type) { // turn the warning into error if "Warnings as errors" is switched on if (Options::syx.WarningsAsErrors) switch (type) { case W_EARLY: Error(message, badValueMessage, EARLY); return; case W_PASS3: Error(message, badValueMessage, PASS3); return; case W_ALL: Error(message, badValueMessage, ALL); return; } ++WarningCount; DefineTable.Replace("__WARNINGS__", WarningCount); initErrorLine(); if (id) { STRCAT(ErrorLine, LINEMAX2-1, "warning["); STRCAT(ErrorLine, LINEMAX2-1, id); STRCAT(ErrorLine, LINEMAX2-1, "]: "); } else { STRCAT(ErrorLine, LINEMAX2-1, "warning: "); } #ifdef USE_LUA if (LuaStartPos.line) STRCAT(ErrorLine, LINEMAX2-1, "[LUA] "); #endif STRCAT(ErrorLine, LINEMAX2-1, message); if (badValueMessage) { STRCAT(ErrorLine, LINEMAX2-1, ": "); STRCAT(ErrorLine, LINEMAX2-1, badValueMessage); } outputErrorLine(OV_WARNING); } struct WarningEntry { bool enabled; const char* txt; const char* help; }; typedef std::unordered_map<const char*, WarningEntry> messages_map; const char* W_ABS_LABEL = "abs"; const char* W_NEXT_RAMTOP = "zxnramtop"; const char* W_NOSLOT_RAMTOP = "noslotramtop"; const char* W_DEV_RAMTOP = "devramtop"; const char* W_DISPLACED_ORG = "displacedorg"; const char* W_ORG_PAGE = "orgpage"; const char* W_FWD_REF = "fwdref"; const char* W_LUA_MC_PASS = "luamc"; const char* W_NEX_STACK = "nexstack"; const char* W_SNA_48 = "sna48"; const char* W_SNA_128 = "sna128"; const char* W_TRD_EXT_INVALID = "trdext"; const char* W_TRD_EXT_3 = "trdext3"; const char* W_TRD_EXT_B = "trdextb"; const char* W_TRD_DUPLICATE = "trddup"; const char* W_RELOCATABLE_ALIGN = "relalign"; const char* W_READ_LOW_MEM = "rdlow"; const char* W_REL_DIVERTS = "reldiverts"; const char* W_REL_UNSTABLE = "relunstable"; const char* W_DISP_MEM_PAGE = "dispmempage"; const char* W_BP_FILE = "bpfile"; const char* W_OUT0 = "out0"; const char* W_BACKSLASH = "backslash"; const char* W_OPKEYWORD = "opkeyword"; const char* W_BE_HOST = "behost"; static messages_map w_texts = { { W_ABS_LABEL, { true, "the `abs` is now absolute value operator, if you are using it as label, please rename", "Warn about parsing error of new abs operator (v1.18.0)." } }, { W_NEXT_RAMTOP, { true, "ZXN device doesn't init memory in any way (RAMTOP is ignored)", "Warn when <ramtop> argument is used with ZXSPECTRUMNEXT." } }, { W_NOSLOT_RAMTOP, { true, "NoSlot64k device doesn't init memory in any way (RAMTOP is ignored)", "Warn when <ramtop> argument is used with NOSLOT64K." } }, { W_DEV_RAMTOP, { true, "[DEVICE] this device was already opened with different RAMTOP value", "Warn when different <ramtop> is used for same device." } }, { W_DISPLACED_ORG, { true, "ORG-address set inside displaced block, the physical address is not modified, only displacement address", "Warn about ORG-address used inside DISP block." } }, { W_ORG_PAGE, { true, "[ORG] page argument affects current slot while address is outside", "Warn about ORG address vs page argument mismatch." } }, { W_FWD_REF, { true, "forward reference of symbol", "Warn about using undefined symbol in risky way." } }, { W_LUA_MC_PASS, { true, "When lua script emits machine code bytes, use \"ALLPASS\" modifier", "Warn when lua script is not ALLPASS, but emits bytes." } }, { W_NEX_STACK, { true, "[SAVENEX] non-zero data are in stackAddress area, may get overwritten by NEXLOAD", "Warn when NEX stack points into non-empty memory." } }, { W_SNA_48, { true, "[SAVESNA] RAM <0x4000-0x4001> will be overwritten due to 48k snapshot imperfect format.", "Warn when 48k SNA does use screen for stack." } }, { W_SNA_128, { true, "only 128kb will be written to snapshot", "Warn when saving snapshot from 256+ki device." } }, { W_TRD_EXT_INVALID, { true, "invalid file extension, TRDOS official extensions are B, C, D and #.", "Warn when TRD file uses unofficial/invalid extension." } }, { W_TRD_EXT_3, { true, "3-letter extension of TRDOS file (unofficial extension)", "Warn when TRD file does use 3-letter extension." } }, { W_TRD_EXT_B, { true, "the \"B\" extension is always single letter", "Warn when long extension starts with letter B (can not)." } }, { W_TRD_DUPLICATE, { true, "TRD file already exists, creating one more!", "Warn when second file with same name is added to disk." } }, { W_RELOCATABLE_ALIGN, { true, "[ALIGN] inside relocation block: may become misaligned when relocated", "Warn when align is used inside relocatable code." } }, { W_READ_LOW_MEM, { true, "Reading memory at low address", "Warn when reading memory from addresses 0..255." } }, { W_REL_DIVERTS, { true, "Expression can't be relocated by simple \"+offset\" mechanics, value diverts differently.", "Warn when relocated expression differs non-trivially." } }, { W_REL_UNSTABLE, { true, "Relocation makes one of the expressions unstable, resulting machine code is not relocatable", "Warn when expression result can't be relocated." } }, { W_DISP_MEM_PAGE, { true, "DISP memory page differs from current mapping", "Warn when DISP page differs from current mapping." } }, { W_BP_FILE, { true, "breakpoints file was not specified", "Warn when SETBREAKPOINT is used without breakpoint file." } }, { W_OUT0, { true, "'out (c),0' is unstable, on CMOS based chips it does `out (c),255`", "Warn when instruction `out (c),0` is used." } }, { W_BACKSLASH, { true, "File name contains \\, use / instead (\\ fails on most of the supported platforms)", "Warn when file name contains backslash." } }, { W_OPKEYWORD, { true, "Label collides with one of the operator keywords, try capitalizing it or other name", "Warn when symbol name collides with operator keyword." } }, { W_BE_HOST, { true, "Big-endian host detected: support is experimental, please report any issues", "Warn when big-endian host runs sjasmplus (experimental)." } }, }; static messages_map::iterator findWarningByIdText(const char* id) { return std::find_if(w_texts.begin(), w_texts.end(), [id](const auto& v){ return !strcmp(id, v.first); } ); } //TODO deprecated, add single-warning around mid 2021, remove ~1y later (replaced by warning-id system) // checks for "ok" (or also "fake") in EOL comment // "ok" must follow the comment start, "fake" can be anywhere inside bool warningNotSuppressed(bool alsoFake) { if (nullptr == eolComment) return true; char* comment = eolComment; while (';' == *comment || '/' == *comment) ++comment; while (' ' == *comment || '\t' == *comment) ++comment; // check if "ok" is first word if ('o' == comment[0] && 'k' == comment[1] && !isalnum((byte)comment[2])) return false; return alsoFake ? (nullptr == strstr(eolComment, "fake")) : true; } bool suppressedById(const char* id) { assert(id); if (nullptr == eolComment) return false; const size_t idLength = strlen(id); assert(0 < idLength); const char* commentToCheck = eolComment; while (const char* idPos = strstr(commentToCheck, id)) { commentToCheck = idPos + idLength; if ('-' == commentToCheck[0] && 'o' == commentToCheck[1] && 'k' == commentToCheck[2]) { return true; } } return false; } static bool isInactiveTypeInCurrentPass(EWStatus type) { if (type == W_EARLY && LASTPASS <= pass) return true; // "early" is inactive during pass3+ if (type == W_PASS3 && pass < LASTPASS) return true; // "pass3" is inactive during 0..2 pass return false; } void Warning(const char* message, const char* badValueMessage, EWStatus type) { if (isInactiveTypeInCurrentPass(type)) return; WarningImpl(nullptr, message, badValueMessage, type); } void WarningById(const char* id, const char* badValueMessage, EWStatus type) { if (isInactiveTypeInCurrentPass(type)) return; // id-warnings could be suppressed by "id-ok" anywhere in eol comment if (suppressedById(id)) return; const messages_map::const_iterator idMessage = w_texts.find(id); // searching by id POINTER! assert(idMessage != w_texts.end()); if (!idMessage->second.enabled) return; WarningImpl(id, idMessage->second.txt, badValueMessage, type); } void WarningById(const char* id, int badValue, EWStatus type) { char buf[32]; SPRINTF1(buf, 32, "%d", badValue); WarningById(id, buf, type); } void CliWoption(const char* option) { if (!option[0]) { // from command line pass == 0, from source by OPT the pass is above zero Error("no argument after -W", (0 == pass) ? nullptr : bp, (0 == pass) ? EARLY : PASS3); return; } // check for specific id, with possible "no-" prefix ("-Wabs" vs "-Wno-abs") const bool enable = strncmp("no-", option, 3); const char* id = enable ? option : option + 3; auto warning_it = findWarningByIdText(id); if (w_texts.end() != warning_it) warning_it->second.enabled = enable; else Warning("unknown warning id in -W option", id, (0 == pass) ? W_EARLY : W_PASS3); } static const char* spaceFiller = " "; void PrintHelpWarnings() { _COUT "The following options control compiler warning messages:" _ENDL; std::vector<const char*> ids; ids.reserve(w_texts.size()); for (const auto& w_text : w_texts) ids.push_back(w_text.first); std::sort(ids.begin(), ids.end(), [](const char* a, const char* b) -> bool { return (strcmp(a,b) < 0); } ); for (const auto& id : ids) { assert(strlen(id) < strlen(spaceFiller)); _COUT " -W" _CMDL id _CMDL spaceFiller+strlen(id) _CMDL w_texts[id].help _ENDL; } _COUT " Use -Wno- prefix to disable specific warning, example: -Wno-abs" _ENDL; _COUT " Use -ok suffix in comment to suppress it per line, example: jr abs ; abs-ok" _ENDL; } //eof io_err.cpp
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); ++i) using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<vi> vvi; typedef vector<ii> vii; typedef set<int> si; typedef map<string, int> msi; typedef long long ll; const ll INF = 1e18L + 1; double p[3100]; double dp[3100][3100]; int main() { int n; scanf("%d", &n); rep(i, n) scanf("%lf", p + i + 1); // p[i] <- ith coin dp[0][0] = 1; for (int i = 1; i <= n; i++) { // dp[i][0] = dp[i - 1][0] * (1 - p[i]); for (int j = 0; j <= i; j++) { if (j - 1 >= 0) dp[i][j] += dp[i - 1][j - 1] * (p[i]); dp[i][j] += dp[i - 1][j] * (1 - p[i]); // dp[i][j+1] = dp[i-1][j] } } double ans = 0; for (int i = n / 2 + 1; i <= n; i++) ans += dp[n][i]; printf("%.12f\n", ans); return 0; }
#include <bits/stdc++.h> using namespace std; #define REP(i, init, n) for(int i = (int)(init); i < (int)(n); i++) #define vi vector<int> #define vl vector<long> #define vvi vector<vector<int>> #define vvl vector<vector<long>> #define pint pair<int, int> #define plong pair<long, long> int main() { int N, count = 0; cin >> N; vvi S(N); vector<vector<int>> Least(N); REP(i, 0, N){ string s; cin >> s; int best = 0, least = 0; int counter = 0; REP(j, 0, s.size()){ if(s[j] == '('){ count++; counter++; best = max(counter, best); }else{ count--; counter--; least = min(counter, least); } } Least[i] = {counter, least, best}; } if(count != 0){ cout << "No" << endl; return 0; } sort(Least.rbegin(), Least.rend()); /* REP(i, 0, N){ cout << Least[i][0] << " " << Least[i][1] << " " << Least[i][2] << endl; }*/ count = 0; REP(i, 0, N){ if(count + Least[i][1] < 0){ cout << "No" << endl; return 0; } else{ count += Least[i][0]; } } cout << "Yes" << endl; }
#include <iostream> #include <fstream> #include <cstring> #include <string> #include <iomanip> using namespace std; struct PERSON { char name[20]; float balance; }; int getN(); void readingFile(int N, PERSON P[]); void displayArray(int N, PERSON P[]); void findRichest(int N, PERSON P[]); void deposit(string custName, int N, PERSON P[]); void newCopy(string s, int N, PERSON P[]); int main() { int N; string custName; N = getN(); PERSON P[N]; readingFile(N, P); displayArray(N, P); findRichest(N, P); cout << "Enter the full name of who you want to deposit money to: "; getline(cin, custName); deposit(custName, N, P); displayArray(N, P); string fileName = "data.txt"; newCopy(fileName, N, P); return 0; } int getN() { int num = 0; string temp; ifstream inFile; inFile.open("data.txt"); while (!inFile.eof()) { getline(inFile, temp); num++; } num--; inFile.close(); return num; } void readingFile(int N, PERSON P[]) { ifstream inFile; string str1; string str2; string temp; float pay; int num = N; inFile.open("data.txt"); for (int i = 0; i < N; i++) { inFile >> str1; inFile >> str2; inFile >> pay; getline(inFile, temp); string name = str1 + " " + str2; strcpy (P[i].name, name.c_str()); P[i].balance = pay; } inFile.close(); } void displayArray(int N, PERSON P[]) { cout << " NAME PAY" << endl << "-----------------------------------------" << endl; for (int i = 0; i < N; i++) { cout << " " << P[i].name << " " << fixed << setprecision(2) << P[i].balance << endl; } } void findRichest(int N, PERSON P[]) { int temp = 0; int richest = 0; for (int i = 0; i < N; i++) { if (P[i].balance > temp) { temp = P[i].balance; richest = i; } } cout <<"The person with the most money is " << P[richest].name << " and has $" << P[richest].balance << endl; } void deposit(string custName, int N, PERSON P[]) { int i = 0; float deposit; while (custName != P[i].name) { i++; } cout << "The person you inputted was " << P[i].name << endl; cout << "How much would you like to deposit? "; cin >> deposit; P[i].balance = P[i].balance + deposit; cout << "Your new balance is now: " << P[i].balance << endl; } void newCopy(string s, int N, PERSON P[]) { ofstream outFile; outFile.open("data.txt"); for (int i = 0; i < N; i++) { outFile << P[i].name << " " << P[i].balance << endl; } outFile.close(); }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "base.h" WINRT_WARNING_PUSH #include "internal/Windows.Foundation.3.h" #include "internal/Windows.Graphics.Display.3.h" #include "internal/Windows.Foundation.Collections.3.h" #include "internal/Windows.Devices.Sensors.3.h" #include "Windows.Devices.h" #include "Windows.Foundation.h" WINRT_EXPORT namespace winrt { namespace impl { template <typename D> struct produce<D, Windows::Devices::Sensors::IAccelerometer> : produce_base<D, Windows::Devices::Sensors::IAccelerometer> { HRESULT __stdcall abi_GetCurrentReading(impl::abi_arg_out<Windows::Devices::Sensors::IAccelerometerReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentReading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MinimumReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinimumReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_ReportInterval(uint32_t value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReportInterval(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Accelerometer, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Accelerometer, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_Shaken(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Accelerometer, Windows::Devices::Sensors::AccelerometerShakenEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().Shaken(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Accelerometer, Windows::Devices::Sensors::AccelerometerShakenEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_Shaken(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Shaken(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAccelerometer2> : produce_base<D, Windows::Devices::Sensors::IAccelerometer2> { HRESULT __stdcall put_ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingTransform(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReadingTransform(Windows::Graphics::Display::DisplayOrientations * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReadingTransform()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAccelerometer3> : produce_base<D, Windows::Devices::Sensors::IAccelerometer3> { HRESULT __stdcall put_ReportLatency(uint32_t value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReportLatency(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReportLatency(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReportLatency()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_MaxBatchSize(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MaxBatchSize()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAccelerometer4> : produce_base<D, Windows::Devices::Sensors::IAccelerometer4> { HRESULT __stdcall get_ReadingType(Windows::Devices::Sensors::AccelerometerReadingType * type) noexcept override { try { typename D::abi_guard guard(this->shim()); *type = detach_abi(this->shim().ReadingType()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAccelerometerDeviceId> : produce_base<D, Windows::Devices::Sensors::IAccelerometerDeviceId> { HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAccelerometerReading> : produce_base<D, Windows::Devices::Sensors::IAccelerometerReading> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_AccelerationX(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AccelerationX()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_AccelerationY(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AccelerationY()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_AccelerationZ(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AccelerationZ()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAccelerometerReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::IAccelerometerReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::IAccelerometerReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAccelerometerShakenEventArgs> : produce_base<D, Windows::Devices::Sensors::IAccelerometerShakenEventArgs> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAccelerometerStatics> : produce_base<D, Windows::Devices::Sensors::IAccelerometerStatics> { HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Devices::Sensors::IAccelerometer> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAccelerometerStatics2> : produce_base<D, Windows::Devices::Sensors::IAccelerometerStatics2> { HRESULT __stdcall abi_GetDefaultWithAccelerometerReadingType(Windows::Devices::Sensors::AccelerometerReadingType readingType, impl::abi_arg_out<Windows::Devices::Sensors::IAccelerometer> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault(readingType)); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IActivitySensor> : produce_base<D, Windows::Devices::Sensors::IActivitySensor> { HRESULT __stdcall abi_GetCurrentReadingAsync(impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::ActivitySensorReading>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetCurrentReadingAsync()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_SubscribedActivities(impl::abi_arg_out<Windows::Foundation::Collections::IVector<winrt::Windows::Devices::Sensors::ActivityType>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().SubscribedActivities()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_PowerInMilliwatts(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PowerInMilliwatts()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_SupportedActivities(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<winrt::Windows::Devices::Sensors::ActivityType>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().SupportedActivities()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MinimumReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinimumReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::ActivitySensor, Windows::Devices::Sensors::ActivitySensorReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::ActivitySensor, Windows::Devices::Sensors::ActivitySensorReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IActivitySensorReading> : produce_base<D, Windows::Devices::Sensors::IActivitySensorReading> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Activity(Windows::Devices::Sensors::ActivityType * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Activity()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Confidence(Windows::Devices::Sensors::ActivitySensorReadingConfidence * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Confidence()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IActivitySensorReadingChangeReport> : produce_base<D, Windows::Devices::Sensors::IActivitySensorReadingChangeReport> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::IActivitySensorReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IActivitySensorReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::IActivitySensorReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::IActivitySensorReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IActivitySensorStatics> : produce_base<D, Windows::Devices::Sensors::IActivitySensorStatics> { HRESULT __stdcall abi_GetDefaultAsync(impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::ActivitySensor>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefaultAsync()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetDeviceSelector(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetDeviceSelector()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_FromIdAsync(impl::abi_arg_in<hstring> deviceId, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::ActivitySensor>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().FromIdAsync(*reinterpret_cast<const hstring *>(&deviceId))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetSystemHistoryAsync(impl::abi_arg_in<Windows::Foundation::DateTime> fromTime, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ActivitySensorReading>>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetSystemHistoryAsync(*reinterpret_cast<const Windows::Foundation::DateTime *>(&fromTime))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetSystemHistoryWithDurationAsync(impl::abi_arg_in<Windows::Foundation::DateTime> fromTime, impl::abi_arg_in<Windows::Foundation::TimeSpan> duration, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ActivitySensorReading>>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetSystemHistoryAsync(*reinterpret_cast<const Windows::Foundation::DateTime *>(&fromTime), *reinterpret_cast<const Windows::Foundation::TimeSpan *>(&duration))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IActivitySensorTriggerDetails> : produce_base<D, Windows::Devices::Sensors::IActivitySensorTriggerDetails> { HRESULT __stdcall abi_ReadReports(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ActivitySensorReadingChangeReport>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReadReports()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAltimeter> : produce_base<D, Windows::Devices::Sensors::IAltimeter> { HRESULT __stdcall abi_GetCurrentReading(impl::abi_arg_out<Windows::Devices::Sensors::IAltimeterReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentReading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MinimumReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinimumReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_ReportInterval(uint32_t value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReportInterval(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Altimeter, Windows::Devices::Sensors::AltimeterReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Altimeter, Windows::Devices::Sensors::AltimeterReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAltimeterReading> : produce_base<D, Windows::Devices::Sensors::IAltimeterReading> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_AltitudeChangeInMeters(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AltitudeChangeInMeters()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAltimeterReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::IAltimeterReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::IAltimeterReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IAltimeterStatics> : produce_base<D, Windows::Devices::Sensors::IAltimeterStatics> { HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Devices::Sensors::IAltimeter> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IBarometer> : produce_base<D, Windows::Devices::Sensors::IBarometer> { HRESULT __stdcall abi_GetCurrentReading(impl::abi_arg_out<Windows::Devices::Sensors::IBarometerReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentReading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MinimumReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinimumReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_ReportInterval(uint32_t value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReportInterval(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Barometer, Windows::Devices::Sensors::BarometerReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Barometer, Windows::Devices::Sensors::BarometerReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IBarometerReading> : produce_base<D, Windows::Devices::Sensors::IBarometerReading> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_StationPressureInHectopascals(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StationPressureInHectopascals()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IBarometerReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::IBarometerReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::IBarometerReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IBarometerStatics> : produce_base<D, Windows::Devices::Sensors::IBarometerStatics> { HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Devices::Sensors::IBarometer> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ICompass> : produce_base<D, Windows::Devices::Sensors::ICompass> { HRESULT __stdcall abi_GetCurrentReading(impl::abi_arg_out<Windows::Devices::Sensors::ICompassReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentReading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MinimumReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinimumReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_ReportInterval(uint32_t value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReportInterval(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Compass, Windows::Devices::Sensors::CompassReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Compass, Windows::Devices::Sensors::CompassReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ICompass2> : produce_base<D, Windows::Devices::Sensors::ICompass2> { HRESULT __stdcall put_ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingTransform(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReadingTransform(Windows::Graphics::Display::DisplayOrientations * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReadingTransform()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ICompassDeviceId> : produce_base<D, Windows::Devices::Sensors::ICompassDeviceId> { HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ICompassReading> : produce_base<D, Windows::Devices::Sensors::ICompassReading> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_HeadingMagneticNorth(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().HeadingMagneticNorth()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_HeadingTrueNorth(impl::abi_arg_out<Windows::Foundation::IReference<double>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().HeadingTrueNorth()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ICompassReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::ICompassReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::ICompassReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ICompassReadingHeadingAccuracy> : produce_base<D, Windows::Devices::Sensors::ICompassReadingHeadingAccuracy> { HRESULT __stdcall get_HeadingAccuracy(Windows::Devices::Sensors::MagnetometerAccuracy * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().HeadingAccuracy()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ICompassStatics> : produce_base<D, Windows::Devices::Sensors::ICompassStatics> { HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Devices::Sensors::ICompass> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IGyrometer> : produce_base<D, Windows::Devices::Sensors::IGyrometer> { HRESULT __stdcall abi_GetCurrentReading(impl::abi_arg_out<Windows::Devices::Sensors::IGyrometerReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentReading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MinimumReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinimumReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_ReportInterval(uint32_t value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReportInterval(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Gyrometer, Windows::Devices::Sensors::GyrometerReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Gyrometer, Windows::Devices::Sensors::GyrometerReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IGyrometer2> : produce_base<D, Windows::Devices::Sensors::IGyrometer2> { HRESULT __stdcall put_ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingTransform(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReadingTransform(Windows::Graphics::Display::DisplayOrientations * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReadingTransform()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IGyrometerDeviceId> : produce_base<D, Windows::Devices::Sensors::IGyrometerDeviceId> { HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IGyrometerReading> : produce_base<D, Windows::Devices::Sensors::IGyrometerReading> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_AngularVelocityX(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AngularVelocityX()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_AngularVelocityY(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AngularVelocityY()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_AngularVelocityZ(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AngularVelocityZ()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IGyrometerReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::IGyrometerReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::IGyrometerReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IGyrometerStatics> : produce_base<D, Windows::Devices::Sensors::IGyrometerStatics> { HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Devices::Sensors::IGyrometer> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IInclinometer> : produce_base<D, Windows::Devices::Sensors::IInclinometer> { HRESULT __stdcall abi_GetCurrentReading(impl::abi_arg_out<Windows::Devices::Sensors::IInclinometerReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentReading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MinimumReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinimumReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_ReportInterval(uint32_t value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReportInterval(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Inclinometer, Windows::Devices::Sensors::InclinometerReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Inclinometer, Windows::Devices::Sensors::InclinometerReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IInclinometer2> : produce_base<D, Windows::Devices::Sensors::IInclinometer2> { HRESULT __stdcall put_ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingTransform(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReadingTransform(Windows::Graphics::Display::DisplayOrientations * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReadingTransform()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReadingType(Windows::Devices::Sensors::SensorReadingType * type) noexcept override { try { typename D::abi_guard guard(this->shim()); *type = detach_abi(this->shim().ReadingType()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IInclinometerDeviceId> : produce_base<D, Windows::Devices::Sensors::IInclinometerDeviceId> { HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IInclinometerReading> : produce_base<D, Windows::Devices::Sensors::IInclinometerReading> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_PitchDegrees(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PitchDegrees()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_RollDegrees(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().RollDegrees()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_YawDegrees(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().YawDegrees()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IInclinometerReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::IInclinometerReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::IInclinometerReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IInclinometerReadingYawAccuracy> : produce_base<D, Windows::Devices::Sensors::IInclinometerReadingYawAccuracy> { HRESULT __stdcall get_YawAccuracy(Windows::Devices::Sensors::MagnetometerAccuracy * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().YawAccuracy()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IInclinometerStatics> : produce_base<D, Windows::Devices::Sensors::IInclinometerStatics> { HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Devices::Sensors::IInclinometer> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IInclinometerStatics2> : produce_base<D, Windows::Devices::Sensors::IInclinometerStatics2> { HRESULT __stdcall abi_GetDefaultForRelativeReadings(impl::abi_arg_out<Windows::Devices::Sensors::IInclinometer> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefaultForRelativeReadings()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IInclinometerStatics3> : produce_base<D, Windows::Devices::Sensors::IInclinometerStatics3> { HRESULT __stdcall abi_GetDefaultWithSensorReadingType(Windows::Devices::Sensors::SensorReadingType sensorReadingtype, impl::abi_arg_out<Windows::Devices::Sensors::IInclinometer> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault(sensorReadingtype)); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ILightSensor> : produce_base<D, Windows::Devices::Sensors::ILightSensor> { HRESULT __stdcall abi_GetCurrentReading(impl::abi_arg_out<Windows::Devices::Sensors::ILightSensorReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentReading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MinimumReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinimumReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_ReportInterval(uint32_t value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReportInterval(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::LightSensor, Windows::Devices::Sensors::LightSensorReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::LightSensor, Windows::Devices::Sensors::LightSensorReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ILightSensorDeviceId> : produce_base<D, Windows::Devices::Sensors::ILightSensorDeviceId> { HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ILightSensorReading> : produce_base<D, Windows::Devices::Sensors::ILightSensorReading> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_IlluminanceInLux(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().IlluminanceInLux()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ILightSensorReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::ILightSensorReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::ILightSensorReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ILightSensorStatics> : produce_base<D, Windows::Devices::Sensors::ILightSensorStatics> { HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Devices::Sensors::ILightSensor> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IMagnetometer> : produce_base<D, Windows::Devices::Sensors::IMagnetometer> { HRESULT __stdcall abi_GetCurrentReading(impl::abi_arg_out<Windows::Devices::Sensors::IMagnetometerReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentReading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MinimumReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinimumReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_ReportInterval(uint32_t value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReportInterval(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Magnetometer, Windows::Devices::Sensors::MagnetometerReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Magnetometer, Windows::Devices::Sensors::MagnetometerReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IMagnetometer2> : produce_base<D, Windows::Devices::Sensors::IMagnetometer2> { HRESULT __stdcall put_ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingTransform(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReadingTransform(Windows::Graphics::Display::DisplayOrientations * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReadingTransform()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IMagnetometerDeviceId> : produce_base<D, Windows::Devices::Sensors::IMagnetometerDeviceId> { HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IMagnetometerReading> : produce_base<D, Windows::Devices::Sensors::IMagnetometerReading> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_MagneticFieldX(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MagneticFieldX()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_MagneticFieldY(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MagneticFieldY()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_MagneticFieldZ(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MagneticFieldZ()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_DirectionalAccuracy(Windows::Devices::Sensors::MagnetometerAccuracy * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DirectionalAccuracy()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IMagnetometerReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::IMagnetometerReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::IMagnetometerReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IMagnetometerStatics> : produce_base<D, Windows::Devices::Sensors::IMagnetometerStatics> { HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Devices::Sensors::IMagnetometer> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IOrientationSensor> : produce_base<D, Windows::Devices::Sensors::IOrientationSensor> { HRESULT __stdcall abi_GetCurrentReading(impl::abi_arg_out<Windows::Devices::Sensors::IOrientationSensorReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentReading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MinimumReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinimumReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_ReportInterval(uint32_t value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReportInterval(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::OrientationSensor, Windows::Devices::Sensors::OrientationSensorReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::OrientationSensor, Windows::Devices::Sensors::OrientationSensorReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IOrientationSensor2> : produce_base<D, Windows::Devices::Sensors::IOrientationSensor2> { HRESULT __stdcall put_ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingTransform(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReadingTransform(Windows::Graphics::Display::DisplayOrientations * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReadingTransform()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReadingType(Windows::Devices::Sensors::SensorReadingType * type) noexcept override { try { typename D::abi_guard guard(this->shim()); *type = detach_abi(this->shim().ReadingType()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IOrientationSensorDeviceId> : produce_base<D, Windows::Devices::Sensors::IOrientationSensorDeviceId> { HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IOrientationSensorReading> : produce_base<D, Windows::Devices::Sensors::IOrientationSensorReading> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_RotationMatrix(impl::abi_arg_out<Windows::Devices::Sensors::ISensorRotationMatrix> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().RotationMatrix()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Quaternion(impl::abi_arg_out<Windows::Devices::Sensors::ISensorQuaternion> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Quaternion()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IOrientationSensorReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::IOrientationSensorReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::IOrientationSensorReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IOrientationSensorReadingYawAccuracy> : produce_base<D, Windows::Devices::Sensors::IOrientationSensorReadingYawAccuracy> { HRESULT __stdcall get_YawAccuracy(Windows::Devices::Sensors::MagnetometerAccuracy * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().YawAccuracy()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IOrientationSensorStatics> : produce_base<D, Windows::Devices::Sensors::IOrientationSensorStatics> { HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Devices::Sensors::IOrientationSensor> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IOrientationSensorStatics2> : produce_base<D, Windows::Devices::Sensors::IOrientationSensorStatics2> { HRESULT __stdcall abi_GetDefaultForRelativeReadings(impl::abi_arg_out<Windows::Devices::Sensors::IOrientationSensor> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefaultForRelativeReadings()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IOrientationSensorStatics3> : produce_base<D, Windows::Devices::Sensors::IOrientationSensorStatics3> { HRESULT __stdcall abi_GetDefaultWithSensorReadingType(Windows::Devices::Sensors::SensorReadingType sensorReadingtype, impl::abi_arg_out<Windows::Devices::Sensors::IOrientationSensor> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault(sensorReadingtype)); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetDefaultWithSensorReadingTypeAndSensorOptimizationGoal(Windows::Devices::Sensors::SensorReadingType sensorReadingType, Windows::Devices::Sensors::SensorOptimizationGoal optimizationGoal, impl::abi_arg_out<Windows::Devices::Sensors::IOrientationSensor> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault(sensorReadingType, optimizationGoal)); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IPedometer> : produce_base<D, Windows::Devices::Sensors::IPedometer> { HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_PowerInMilliwatts(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PowerInMilliwatts()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_MinimumReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinimumReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_ReportInterval(uint32_t value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReportInterval(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReportInterval(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReportInterval()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Pedometer, Windows::Devices::Sensors::PedometerReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Pedometer, Windows::Devices::Sensors::PedometerReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IPedometer2> : produce_base<D, Windows::Devices::Sensors::IPedometer2> { HRESULT __stdcall abi_GetCurrentReadings(impl::abi_arg_out<Windows::Foundation::Collections::IMapView<winrt::Windows::Devices::Sensors::PedometerStepKind, Windows::Devices::Sensors::PedometerReading>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentReadings()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IPedometerDataThresholdFactory> : produce_base<D, Windows::Devices::Sensors::IPedometerDataThresholdFactory> { HRESULT __stdcall abi_Create(impl::abi_arg_in<Windows::Devices::Sensors::IPedometer> sensor, int32_t stepGoal, impl::abi_arg_out<Windows::Devices::Sensors::ISensorDataThreshold> threshold) noexcept override { try { typename D::abi_guard guard(this->shim()); *threshold = detach_abi(this->shim().Create(*reinterpret_cast<const Windows::Devices::Sensors::Pedometer *>(&sensor), stepGoal)); return S_OK; } catch (...) { *threshold = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IPedometerReading> : produce_base<D, Windows::Devices::Sensors::IPedometerReading> { HRESULT __stdcall get_StepKind(Windows::Devices::Sensors::PedometerStepKind * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StepKind()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_CumulativeSteps(int32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().CumulativeSteps()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_CumulativeStepsDuration(impl::abi_arg_out<Windows::Foundation::TimeSpan> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().CumulativeStepsDuration()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IPedometerReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::IPedometerReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::IPedometerReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IPedometerStatics> : produce_base<D, Windows::Devices::Sensors::IPedometerStatics> { HRESULT __stdcall abi_FromIdAsync(impl::abi_arg_in<hstring> deviceId, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::Pedometer>> operation) noexcept override { try { typename D::abi_guard guard(this->shim()); *operation = detach_abi(this->shim().FromIdAsync(*reinterpret_cast<const hstring *>(&deviceId))); return S_OK; } catch (...) { *operation = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetDefaultAsync(impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::Pedometer>> operation) noexcept override { try { typename D::abi_guard guard(this->shim()); *operation = detach_abi(this->shim().GetDefaultAsync()); return S_OK; } catch (...) { *operation = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetDeviceSelector(impl::abi_arg_out<hstring> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDeviceSelector()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetSystemHistoryAsync(impl::abi_arg_in<Windows::Foundation::DateTime> fromTime, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading>>> operation) noexcept override { try { typename D::abi_guard guard(this->shim()); *operation = detach_abi(this->shim().GetSystemHistoryAsync(*reinterpret_cast<const Windows::Foundation::DateTime *>(&fromTime))); return S_OK; } catch (...) { *operation = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetSystemHistoryWithDurationAsync(impl::abi_arg_in<Windows::Foundation::DateTime> fromTime, impl::abi_arg_in<Windows::Foundation::TimeSpan> duration, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading>>> operation) noexcept override { try { typename D::abi_guard guard(this->shim()); *operation = detach_abi(this->shim().GetSystemHistoryAsync(*reinterpret_cast<const Windows::Foundation::DateTime *>(&fromTime), *reinterpret_cast<const Windows::Foundation::TimeSpan *>(&duration))); return S_OK; } catch (...) { *operation = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IPedometerStatics2> : produce_base<D, Windows::Devices::Sensors::IPedometerStatics2> { HRESULT __stdcall abi_GetReadingsFromTriggerDetails(impl::abi_arg_in<Windows::Devices::Sensors::ISensorDataThresholdTriggerDetails> triggerDetails, impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetReadingsFromTriggerDetails(*reinterpret_cast<const Windows::Devices::Sensors::SensorDataThresholdTriggerDetails *>(&triggerDetails))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IProximitySensor> : produce_base<D, Windows::Devices::Sensors::IProximitySensor> { HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MaxDistanceInMillimeters(impl::abi_arg_out<Windows::Foundation::IReference<uint32_t>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MaxDistanceInMillimeters()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MinDistanceInMillimeters(impl::abi_arg_out<Windows::Foundation::IReference<uint32_t>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MinDistanceInMillimeters()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetCurrentReading(impl::abi_arg_out<Windows::Devices::Sensors::IProximitySensorReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentReading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall add_ReadingChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::ProximitySensor, Windows::Devices::Sensors::ProximitySensorReadingChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ReadingChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::ProximitySensor, Windows::Devices::Sensors::ProximitySensorReadingChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ReadingChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_CreateDisplayOnOffController(impl::abi_arg_out<Windows::Foundation::IClosable> controller) noexcept override { try { typename D::abi_guard guard(this->shim()); *controller = detach_abi(this->shim().CreateDisplayOnOffController()); return S_OK; } catch (...) { *controller = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IProximitySensorDataThresholdFactory> : produce_base<D, Windows::Devices::Sensors::IProximitySensorDataThresholdFactory> { HRESULT __stdcall abi_Create(impl::abi_arg_in<Windows::Devices::Sensors::IProximitySensor> sensor, impl::abi_arg_out<Windows::Devices::Sensors::ISensorDataThreshold> threshold) noexcept override { try { typename D::abi_guard guard(this->shim()); *threshold = detach_abi(this->shim().Create(*reinterpret_cast<const Windows::Devices::Sensors::ProximitySensor *>(&sensor))); return S_OK; } catch (...) { *threshold = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IProximitySensorReading> : produce_base<D, Windows::Devices::Sensors::IProximitySensorReading> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_IsDetected(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().IsDetected()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_DistanceInMillimeters(impl::abi_arg_out<Windows::Foundation::IReference<uint32_t>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DistanceInMillimeters()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IProximitySensorReadingChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::IProximitySensorReadingChangedEventArgs> { HRESULT __stdcall get_Reading(impl::abi_arg_out<Windows::Devices::Sensors::IProximitySensorReading> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Reading()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IProximitySensorStatics> : produce_base<D, Windows::Devices::Sensors::IProximitySensorStatics> { HRESULT __stdcall abi_GetDeviceSelector(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetDeviceSelector()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_FromId(impl::abi_arg_in<hstring> sensorId, impl::abi_arg_out<Windows::Devices::Sensors::IProximitySensor> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().FromId(*reinterpret_cast<const hstring *>(&sensorId))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::IProximitySensorStatics2> : produce_base<D, Windows::Devices::Sensors::IProximitySensorStatics2> { HRESULT __stdcall abi_GetReadingsFromTriggerDetails(impl::abi_arg_in<Windows::Devices::Sensors::ISensorDataThresholdTriggerDetails> triggerDetails, impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ProximitySensorReading>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetReadingsFromTriggerDetails(*reinterpret_cast<const Windows::Devices::Sensors::SensorDataThresholdTriggerDetails *>(&triggerDetails))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ISensorDataThreshold> : produce_base<D, Windows::Devices::Sensors::ISensorDataThreshold> {}; template <typename D> struct produce<D, Windows::Devices::Sensors::ISensorDataThresholdTriggerDetails> : produce_base<D, Windows::Devices::Sensors::ISensorDataThresholdTriggerDetails> { HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_SensorType(Windows::Devices::Sensors::SensorType * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().SensorType()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ISensorQuaternion> : produce_base<D, Windows::Devices::Sensors::ISensorQuaternion> { HRESULT __stdcall get_W(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().W()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_X(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().X()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Y(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Y()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Z(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Z()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ISensorRotationMatrix> : produce_base<D, Windows::Devices::Sensors::ISensorRotationMatrix> { HRESULT __stdcall get_M11(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().M11()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_M12(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().M12()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_M13(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().M13()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_M21(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().M21()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_M22(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().M22()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_M23(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().M23()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_M31(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().M31()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_M32(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().M32()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_M33(float * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().M33()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ISimpleOrientationSensor> : produce_base<D, Windows::Devices::Sensors::ISimpleOrientationSensor> { HRESULT __stdcall abi_GetCurrentOrientation(Windows::Devices::Sensors::SimpleOrientation * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetCurrentOrientation()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_OrientationChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::SimpleOrientationSensor, Windows::Devices::Sensors::SimpleOrientationSensorOrientationChangedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().OrientationChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::SimpleOrientationSensor, Windows::Devices::Sensors::SimpleOrientationSensorOrientationChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_OrientationChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().OrientationChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ISimpleOrientationSensor2> : produce_base<D, Windows::Devices::Sensors::ISimpleOrientationSensor2> { HRESULT __stdcall put_ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ReadingTransform(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ReadingTransform(Windows::Graphics::Display::DisplayOrientations * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReadingTransform()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ISimpleOrientationSensorDeviceId> : produce_base<D, Windows::Devices::Sensors::ISimpleOrientationSensorDeviceId> { HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ISimpleOrientationSensorOrientationChangedEventArgs> : produce_base<D, Windows::Devices::Sensors::ISimpleOrientationSensorOrientationChangedEventArgs> { HRESULT __stdcall get_Timestamp(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Timestamp()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Orientation(Windows::Devices::Sensors::SimpleOrientation * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Orientation()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Sensors::ISimpleOrientationSensorStatics> : produce_base<D, Windows::Devices::Sensors::ISimpleOrientationSensorStatics> { HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Devices::Sensors::ISimpleOrientationSensor> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; } namespace Windows::Devices::Sensors { template <typename D> hstring impl_ISensorDataThresholdTriggerDetails<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(ISensorDataThresholdTriggerDetails)->get_DeviceId(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::SensorType impl_ISensorDataThresholdTriggerDetails<D>::SensorType() const { Windows::Devices::Sensors::SensorType value {}; check_hresult(WINRT_SHIM(ISensorDataThresholdTriggerDetails)->get_SensorType(&value)); return value; } template <typename D> hstring impl_IAccelerometerDeviceId<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(IAccelerometerDeviceId)->get_DeviceId(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::Accelerometer impl_IAccelerometerStatics<D>::GetDefault() const { Windows::Devices::Sensors::Accelerometer result { nullptr }; check_hresult(WINRT_SHIM(IAccelerometerStatics)->abi_GetDefault(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::Accelerometer impl_IAccelerometerStatics2<D>::GetDefault(Windows::Devices::Sensors::AccelerometerReadingType readingType) const { Windows::Devices::Sensors::Accelerometer result { nullptr }; check_hresult(WINRT_SHIM(IAccelerometerStatics2)->abi_GetDefaultWithAccelerometerReadingType(readingType, put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::AccelerometerReading impl_IAccelerometer<D>::GetCurrentReading() const { Windows::Devices::Sensors::AccelerometerReading value { nullptr }; check_hresult(WINRT_SHIM(IAccelerometer)->abi_GetCurrentReading(put_abi(value))); return value; } template <typename D> uint32_t impl_IAccelerometer<D>::MinimumReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IAccelerometer)->get_MinimumReportInterval(&value)); return value; } template <typename D> void impl_IAccelerometer<D>::ReportInterval(uint32_t value) const { check_hresult(WINRT_SHIM(IAccelerometer)->put_ReportInterval(value)); } template <typename D> uint32_t impl_IAccelerometer<D>::ReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IAccelerometer)->get_ReportInterval(&value)); return value; } template <typename D> event_token impl_IAccelerometer<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Accelerometer, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IAccelerometer)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IAccelerometer> impl_IAccelerometer<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Accelerometer, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, IAccelerometer>(this, &ABI::Windows::Devices::Sensors::IAccelerometer::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_IAccelerometer<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(IAccelerometer)->remove_ReadingChanged(token)); } template <typename D> event_token impl_IAccelerometer<D>::Shaken(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Accelerometer, Windows::Devices::Sensors::AccelerometerShakenEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IAccelerometer)->add_Shaken(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IAccelerometer> impl_IAccelerometer<D>::Shaken(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Accelerometer, Windows::Devices::Sensors::AccelerometerShakenEventArgs> & handler) const { return impl::make_event_revoker<D, IAccelerometer>(this, &ABI::Windows::Devices::Sensors::IAccelerometer::remove_Shaken, Shaken(handler)); } template <typename D> void impl_IAccelerometer<D>::Shaken(event_token token) const { check_hresult(WINRT_SHIM(IAccelerometer)->remove_Shaken(token)); } template <typename D> void impl_IAccelerometer2<D>::ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) const { check_hresult(WINRT_SHIM(IAccelerometer2)->put_ReadingTransform(value)); } template <typename D> Windows::Graphics::Display::DisplayOrientations impl_IAccelerometer2<D>::ReadingTransform() const { Windows::Graphics::Display::DisplayOrientations value {}; check_hresult(WINRT_SHIM(IAccelerometer2)->get_ReadingTransform(&value)); return value; } template <typename D> void impl_IAccelerometer3<D>::ReportLatency(uint32_t value) const { check_hresult(WINRT_SHIM(IAccelerometer3)->put_ReportLatency(value)); } template <typename D> uint32_t impl_IAccelerometer3<D>::ReportLatency() const { uint32_t value {}; check_hresult(WINRT_SHIM(IAccelerometer3)->get_ReportLatency(&value)); return value; } template <typename D> uint32_t impl_IAccelerometer3<D>::MaxBatchSize() const { uint32_t value {}; check_hresult(WINRT_SHIM(IAccelerometer3)->get_MaxBatchSize(&value)); return value; } template <typename D> Windows::Devices::Sensors::AccelerometerReadingType impl_IAccelerometer4<D>::ReadingType() const { Windows::Devices::Sensors::AccelerometerReadingType type {}; check_hresult(WINRT_SHIM(IAccelerometer4)->get_ReadingType(&type)); return type; } template <typename D> Windows::Foundation::DateTime impl_IAccelerometerReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IAccelerometerReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> double impl_IAccelerometerReading<D>::AccelerationX() const { double value {}; check_hresult(WINRT_SHIM(IAccelerometerReading)->get_AccelerationX(&value)); return value; } template <typename D> double impl_IAccelerometerReading<D>::AccelerationY() const { double value {}; check_hresult(WINRT_SHIM(IAccelerometerReading)->get_AccelerationY(&value)); return value; } template <typename D> double impl_IAccelerometerReading<D>::AccelerationZ() const { double value {}; check_hresult(WINRT_SHIM(IAccelerometerReading)->get_AccelerationZ(&value)); return value; } template <typename D> Windows::Devices::Sensors::AccelerometerReading impl_IAccelerometerReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::AccelerometerReading value { nullptr }; check_hresult(WINRT_SHIM(IAccelerometerReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } template <typename D> Windows::Foundation::DateTime impl_IAccelerometerShakenEventArgs<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IAccelerometerShakenEventArgs)->get_Timestamp(put_abi(value))); return value; } template <typename D> hstring impl_IInclinometerDeviceId<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(IInclinometerDeviceId)->get_DeviceId(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::Inclinometer impl_IInclinometerStatics<D>::GetDefault() const { Windows::Devices::Sensors::Inclinometer result { nullptr }; check_hresult(WINRT_SHIM(IInclinometerStatics)->abi_GetDefault(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::Inclinometer impl_IInclinometerStatics2<D>::GetDefaultForRelativeReadings() const { Windows::Devices::Sensors::Inclinometer result { nullptr }; check_hresult(WINRT_SHIM(IInclinometerStatics2)->abi_GetDefaultForRelativeReadings(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::Inclinometer impl_IInclinometerStatics3<D>::GetDefault(Windows::Devices::Sensors::SensorReadingType sensorReadingtype) const { Windows::Devices::Sensors::Inclinometer result { nullptr }; check_hresult(WINRT_SHIM(IInclinometerStatics3)->abi_GetDefaultWithSensorReadingType(sensorReadingtype, put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::InclinometerReading impl_IInclinometer<D>::GetCurrentReading() const { Windows::Devices::Sensors::InclinometerReading value { nullptr }; check_hresult(WINRT_SHIM(IInclinometer)->abi_GetCurrentReading(put_abi(value))); return value; } template <typename D> uint32_t impl_IInclinometer<D>::MinimumReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IInclinometer)->get_MinimumReportInterval(&value)); return value; } template <typename D> void impl_IInclinometer<D>::ReportInterval(uint32_t value) const { check_hresult(WINRT_SHIM(IInclinometer)->put_ReportInterval(value)); } template <typename D> uint32_t impl_IInclinometer<D>::ReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IInclinometer)->get_ReportInterval(&value)); return value; } template <typename D> event_token impl_IInclinometer<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Inclinometer, Windows::Devices::Sensors::InclinometerReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IInclinometer)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IInclinometer> impl_IInclinometer<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Inclinometer, Windows::Devices::Sensors::InclinometerReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, IInclinometer>(this, &ABI::Windows::Devices::Sensors::IInclinometer::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_IInclinometer<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(IInclinometer)->remove_ReadingChanged(token)); } template <typename D> void impl_IInclinometer2<D>::ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) const { check_hresult(WINRT_SHIM(IInclinometer2)->put_ReadingTransform(value)); } template <typename D> Windows::Graphics::Display::DisplayOrientations impl_IInclinometer2<D>::ReadingTransform() const { Windows::Graphics::Display::DisplayOrientations value {}; check_hresult(WINRT_SHIM(IInclinometer2)->get_ReadingTransform(&value)); return value; } template <typename D> Windows::Devices::Sensors::SensorReadingType impl_IInclinometer2<D>::ReadingType() const { Windows::Devices::Sensors::SensorReadingType type {}; check_hresult(WINRT_SHIM(IInclinometer2)->get_ReadingType(&type)); return type; } template <typename D> Windows::Foundation::DateTime impl_IInclinometerReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IInclinometerReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> float impl_IInclinometerReading<D>::PitchDegrees() const { float value {}; check_hresult(WINRT_SHIM(IInclinometerReading)->get_PitchDegrees(&value)); return value; } template <typename D> float impl_IInclinometerReading<D>::RollDegrees() const { float value {}; check_hresult(WINRT_SHIM(IInclinometerReading)->get_RollDegrees(&value)); return value; } template <typename D> float impl_IInclinometerReading<D>::YawDegrees() const { float value {}; check_hresult(WINRT_SHIM(IInclinometerReading)->get_YawDegrees(&value)); return value; } template <typename D> Windows::Devices::Sensors::MagnetometerAccuracy impl_IInclinometerReadingYawAccuracy<D>::YawAccuracy() const { Windows::Devices::Sensors::MagnetometerAccuracy value {}; check_hresult(WINRT_SHIM(IInclinometerReadingYawAccuracy)->get_YawAccuracy(&value)); return value; } template <typename D> Windows::Devices::Sensors::InclinometerReading impl_IInclinometerReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::InclinometerReading value { nullptr }; check_hresult(WINRT_SHIM(IInclinometerReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } template <typename D> hstring impl_IGyrometerDeviceId<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(IGyrometerDeviceId)->get_DeviceId(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::Gyrometer impl_IGyrometerStatics<D>::GetDefault() const { Windows::Devices::Sensors::Gyrometer result { nullptr }; check_hresult(WINRT_SHIM(IGyrometerStatics)->abi_GetDefault(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::GyrometerReading impl_IGyrometer<D>::GetCurrentReading() const { Windows::Devices::Sensors::GyrometerReading value { nullptr }; check_hresult(WINRT_SHIM(IGyrometer)->abi_GetCurrentReading(put_abi(value))); return value; } template <typename D> uint32_t impl_IGyrometer<D>::MinimumReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IGyrometer)->get_MinimumReportInterval(&value)); return value; } template <typename D> void impl_IGyrometer<D>::ReportInterval(uint32_t value) const { check_hresult(WINRT_SHIM(IGyrometer)->put_ReportInterval(value)); } template <typename D> uint32_t impl_IGyrometer<D>::ReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IGyrometer)->get_ReportInterval(&value)); return value; } template <typename D> event_token impl_IGyrometer<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Gyrometer, Windows::Devices::Sensors::GyrometerReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IGyrometer)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IGyrometer> impl_IGyrometer<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Gyrometer, Windows::Devices::Sensors::GyrometerReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, IGyrometer>(this, &ABI::Windows::Devices::Sensors::IGyrometer::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_IGyrometer<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(IGyrometer)->remove_ReadingChanged(token)); } template <typename D> void impl_IGyrometer2<D>::ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) const { check_hresult(WINRT_SHIM(IGyrometer2)->put_ReadingTransform(value)); } template <typename D> Windows::Graphics::Display::DisplayOrientations impl_IGyrometer2<D>::ReadingTransform() const { Windows::Graphics::Display::DisplayOrientations value {}; check_hresult(WINRT_SHIM(IGyrometer2)->get_ReadingTransform(&value)); return value; } template <typename D> Windows::Foundation::DateTime impl_IGyrometerReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IGyrometerReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> double impl_IGyrometerReading<D>::AngularVelocityX() const { double value {}; check_hresult(WINRT_SHIM(IGyrometerReading)->get_AngularVelocityX(&value)); return value; } template <typename D> double impl_IGyrometerReading<D>::AngularVelocityY() const { double value {}; check_hresult(WINRT_SHIM(IGyrometerReading)->get_AngularVelocityY(&value)); return value; } template <typename D> double impl_IGyrometerReading<D>::AngularVelocityZ() const { double value {}; check_hresult(WINRT_SHIM(IGyrometerReading)->get_AngularVelocityZ(&value)); return value; } template <typename D> Windows::Devices::Sensors::GyrometerReading impl_IGyrometerReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::GyrometerReading value { nullptr }; check_hresult(WINRT_SHIM(IGyrometerReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } template <typename D> hstring impl_ICompassDeviceId<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(ICompassDeviceId)->get_DeviceId(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::Compass impl_ICompassStatics<D>::GetDefault() const { Windows::Devices::Sensors::Compass result { nullptr }; check_hresult(WINRT_SHIM(ICompassStatics)->abi_GetDefault(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::CompassReading impl_ICompass<D>::GetCurrentReading() const { Windows::Devices::Sensors::CompassReading value { nullptr }; check_hresult(WINRT_SHIM(ICompass)->abi_GetCurrentReading(put_abi(value))); return value; } template <typename D> uint32_t impl_ICompass<D>::MinimumReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(ICompass)->get_MinimumReportInterval(&value)); return value; } template <typename D> void impl_ICompass<D>::ReportInterval(uint32_t value) const { check_hresult(WINRT_SHIM(ICompass)->put_ReportInterval(value)); } template <typename D> uint32_t impl_ICompass<D>::ReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(ICompass)->get_ReportInterval(&value)); return value; } template <typename D> event_token impl_ICompass<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Compass, Windows::Devices::Sensors::CompassReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(ICompass)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<ICompass> impl_ICompass<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Compass, Windows::Devices::Sensors::CompassReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, ICompass>(this, &ABI::Windows::Devices::Sensors::ICompass::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_ICompass<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(ICompass)->remove_ReadingChanged(token)); } template <typename D> void impl_ICompass2<D>::ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) const { check_hresult(WINRT_SHIM(ICompass2)->put_ReadingTransform(value)); } template <typename D> Windows::Graphics::Display::DisplayOrientations impl_ICompass2<D>::ReadingTransform() const { Windows::Graphics::Display::DisplayOrientations value {}; check_hresult(WINRT_SHIM(ICompass2)->get_ReadingTransform(&value)); return value; } template <typename D> Windows::Foundation::DateTime impl_ICompassReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(ICompassReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> double impl_ICompassReading<D>::HeadingMagneticNorth() const { double value {}; check_hresult(WINRT_SHIM(ICompassReading)->get_HeadingMagneticNorth(&value)); return value; } template <typename D> Windows::Foundation::IReference<double> impl_ICompassReading<D>::HeadingTrueNorth() const { Windows::Foundation::IReference<double> value; check_hresult(WINRT_SHIM(ICompassReading)->get_HeadingTrueNorth(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::MagnetometerAccuracy impl_ICompassReadingHeadingAccuracy<D>::HeadingAccuracy() const { Windows::Devices::Sensors::MagnetometerAccuracy value {}; check_hresult(WINRT_SHIM(ICompassReadingHeadingAccuracy)->get_HeadingAccuracy(&value)); return value; } template <typename D> Windows::Devices::Sensors::CompassReading impl_ICompassReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::CompassReading value { nullptr }; check_hresult(WINRT_SHIM(ICompassReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } template <typename D> hstring impl_ILightSensorDeviceId<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(ILightSensorDeviceId)->get_DeviceId(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::LightSensor impl_ILightSensorStatics<D>::GetDefault() const { Windows::Devices::Sensors::LightSensor result { nullptr }; check_hresult(WINRT_SHIM(ILightSensorStatics)->abi_GetDefault(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::LightSensorReading impl_ILightSensor<D>::GetCurrentReading() const { Windows::Devices::Sensors::LightSensorReading value { nullptr }; check_hresult(WINRT_SHIM(ILightSensor)->abi_GetCurrentReading(put_abi(value))); return value; } template <typename D> uint32_t impl_ILightSensor<D>::MinimumReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(ILightSensor)->get_MinimumReportInterval(&value)); return value; } template <typename D> void impl_ILightSensor<D>::ReportInterval(uint32_t value) const { check_hresult(WINRT_SHIM(ILightSensor)->put_ReportInterval(value)); } template <typename D> uint32_t impl_ILightSensor<D>::ReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(ILightSensor)->get_ReportInterval(&value)); return value; } template <typename D> event_token impl_ILightSensor<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::LightSensor, Windows::Devices::Sensors::LightSensorReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(ILightSensor)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<ILightSensor> impl_ILightSensor<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::LightSensor, Windows::Devices::Sensors::LightSensorReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, ILightSensor>(this, &ABI::Windows::Devices::Sensors::ILightSensor::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_ILightSensor<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(ILightSensor)->remove_ReadingChanged(token)); } template <typename D> Windows::Foundation::DateTime impl_ILightSensorReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(ILightSensorReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> float impl_ILightSensorReading<D>::IlluminanceInLux() const { float value {}; check_hresult(WINRT_SHIM(ILightSensorReading)->get_IlluminanceInLux(&value)); return value; } template <typename D> Windows::Devices::Sensors::LightSensorReading impl_ILightSensorReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::LightSensorReading value { nullptr }; check_hresult(WINRT_SHIM(ILightSensorReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } template <typename D> float impl_ISensorRotationMatrix<D>::M11() const { float value {}; check_hresult(WINRT_SHIM(ISensorRotationMatrix)->get_M11(&value)); return value; } template <typename D> float impl_ISensorRotationMatrix<D>::M12() const { float value {}; check_hresult(WINRT_SHIM(ISensorRotationMatrix)->get_M12(&value)); return value; } template <typename D> float impl_ISensorRotationMatrix<D>::M13() const { float value {}; check_hresult(WINRT_SHIM(ISensorRotationMatrix)->get_M13(&value)); return value; } template <typename D> float impl_ISensorRotationMatrix<D>::M21() const { float value {}; check_hresult(WINRT_SHIM(ISensorRotationMatrix)->get_M21(&value)); return value; } template <typename D> float impl_ISensorRotationMatrix<D>::M22() const { float value {}; check_hresult(WINRT_SHIM(ISensorRotationMatrix)->get_M22(&value)); return value; } template <typename D> float impl_ISensorRotationMatrix<D>::M23() const { float value {}; check_hresult(WINRT_SHIM(ISensorRotationMatrix)->get_M23(&value)); return value; } template <typename D> float impl_ISensorRotationMatrix<D>::M31() const { float value {}; check_hresult(WINRT_SHIM(ISensorRotationMatrix)->get_M31(&value)); return value; } template <typename D> float impl_ISensorRotationMatrix<D>::M32() const { float value {}; check_hresult(WINRT_SHIM(ISensorRotationMatrix)->get_M32(&value)); return value; } template <typename D> float impl_ISensorRotationMatrix<D>::M33() const { float value {}; check_hresult(WINRT_SHIM(ISensorRotationMatrix)->get_M33(&value)); return value; } template <typename D> float impl_ISensorQuaternion<D>::W() const { float value {}; check_hresult(WINRT_SHIM(ISensorQuaternion)->get_W(&value)); return value; } template <typename D> float impl_ISensorQuaternion<D>::X() const { float value {}; check_hresult(WINRT_SHIM(ISensorQuaternion)->get_X(&value)); return value; } template <typename D> float impl_ISensorQuaternion<D>::Y() const { float value {}; check_hresult(WINRT_SHIM(ISensorQuaternion)->get_Y(&value)); return value; } template <typename D> float impl_ISensorQuaternion<D>::Z() const { float value {}; check_hresult(WINRT_SHIM(ISensorQuaternion)->get_Z(&value)); return value; } template <typename D> hstring impl_IOrientationSensorDeviceId<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(IOrientationSensorDeviceId)->get_DeviceId(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::OrientationSensor impl_IOrientationSensorStatics<D>::GetDefault() const { Windows::Devices::Sensors::OrientationSensor result { nullptr }; check_hresult(WINRT_SHIM(IOrientationSensorStatics)->abi_GetDefault(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::OrientationSensor impl_IOrientationSensorStatics2<D>::GetDefaultForRelativeReadings() const { Windows::Devices::Sensors::OrientationSensor result { nullptr }; check_hresult(WINRT_SHIM(IOrientationSensorStatics2)->abi_GetDefaultForRelativeReadings(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::OrientationSensor impl_IOrientationSensorStatics3<D>::GetDefault(Windows::Devices::Sensors::SensorReadingType sensorReadingtype) const { Windows::Devices::Sensors::OrientationSensor result { nullptr }; check_hresult(WINRT_SHIM(IOrientationSensorStatics3)->abi_GetDefaultWithSensorReadingType(sensorReadingtype, put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::OrientationSensor impl_IOrientationSensorStatics3<D>::GetDefault(Windows::Devices::Sensors::SensorReadingType sensorReadingType, Windows::Devices::Sensors::SensorOptimizationGoal optimizationGoal) const { Windows::Devices::Sensors::OrientationSensor result { nullptr }; check_hresult(WINRT_SHIM(IOrientationSensorStatics3)->abi_GetDefaultWithSensorReadingTypeAndSensorOptimizationGoal(sensorReadingType, optimizationGoal, put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::OrientationSensorReading impl_IOrientationSensor<D>::GetCurrentReading() const { Windows::Devices::Sensors::OrientationSensorReading value { nullptr }; check_hresult(WINRT_SHIM(IOrientationSensor)->abi_GetCurrentReading(put_abi(value))); return value; } template <typename D> uint32_t impl_IOrientationSensor<D>::MinimumReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IOrientationSensor)->get_MinimumReportInterval(&value)); return value; } template <typename D> void impl_IOrientationSensor<D>::ReportInterval(uint32_t value) const { check_hresult(WINRT_SHIM(IOrientationSensor)->put_ReportInterval(value)); } template <typename D> uint32_t impl_IOrientationSensor<D>::ReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IOrientationSensor)->get_ReportInterval(&value)); return value; } template <typename D> event_token impl_IOrientationSensor<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::OrientationSensor, Windows::Devices::Sensors::OrientationSensorReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IOrientationSensor)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IOrientationSensor> impl_IOrientationSensor<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::OrientationSensor, Windows::Devices::Sensors::OrientationSensorReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, IOrientationSensor>(this, &ABI::Windows::Devices::Sensors::IOrientationSensor::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_IOrientationSensor<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(IOrientationSensor)->remove_ReadingChanged(token)); } template <typename D> void impl_IOrientationSensor2<D>::ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) const { check_hresult(WINRT_SHIM(IOrientationSensor2)->put_ReadingTransform(value)); } template <typename D> Windows::Graphics::Display::DisplayOrientations impl_IOrientationSensor2<D>::ReadingTransform() const { Windows::Graphics::Display::DisplayOrientations value {}; check_hresult(WINRT_SHIM(IOrientationSensor2)->get_ReadingTransform(&value)); return value; } template <typename D> Windows::Devices::Sensors::SensorReadingType impl_IOrientationSensor2<D>::ReadingType() const { Windows::Devices::Sensors::SensorReadingType type {}; check_hresult(WINRT_SHIM(IOrientationSensor2)->get_ReadingType(&type)); return type; } template <typename D> Windows::Foundation::DateTime impl_IOrientationSensorReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IOrientationSensorReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::SensorRotationMatrix impl_IOrientationSensorReading<D>::RotationMatrix() const { Windows::Devices::Sensors::SensorRotationMatrix value { nullptr }; check_hresult(WINRT_SHIM(IOrientationSensorReading)->get_RotationMatrix(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::SensorQuaternion impl_IOrientationSensorReading<D>::Quaternion() const { Windows::Devices::Sensors::SensorQuaternion value { nullptr }; check_hresult(WINRT_SHIM(IOrientationSensorReading)->get_Quaternion(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::MagnetometerAccuracy impl_IOrientationSensorReadingYawAccuracy<D>::YawAccuracy() const { Windows::Devices::Sensors::MagnetometerAccuracy value {}; check_hresult(WINRT_SHIM(IOrientationSensorReadingYawAccuracy)->get_YawAccuracy(&value)); return value; } template <typename D> Windows::Devices::Sensors::OrientationSensorReading impl_IOrientationSensorReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::OrientationSensorReading value { nullptr }; check_hresult(WINRT_SHIM(IOrientationSensorReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } template <typename D> hstring impl_ISimpleOrientationSensorDeviceId<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(ISimpleOrientationSensorDeviceId)->get_DeviceId(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::SimpleOrientationSensor impl_ISimpleOrientationSensorStatics<D>::GetDefault() const { Windows::Devices::Sensors::SimpleOrientationSensor result { nullptr }; check_hresult(WINRT_SHIM(ISimpleOrientationSensorStatics)->abi_GetDefault(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::SimpleOrientation impl_ISimpleOrientationSensor<D>::GetCurrentOrientation() const { Windows::Devices::Sensors::SimpleOrientation value {}; check_hresult(WINRT_SHIM(ISimpleOrientationSensor)->abi_GetCurrentOrientation(&value)); return value; } template <typename D> event_token impl_ISimpleOrientationSensor<D>::OrientationChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::SimpleOrientationSensor, Windows::Devices::Sensors::SimpleOrientationSensorOrientationChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(ISimpleOrientationSensor)->add_OrientationChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<ISimpleOrientationSensor> impl_ISimpleOrientationSensor<D>::OrientationChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::SimpleOrientationSensor, Windows::Devices::Sensors::SimpleOrientationSensorOrientationChangedEventArgs> & handler) const { return impl::make_event_revoker<D, ISimpleOrientationSensor>(this, &ABI::Windows::Devices::Sensors::ISimpleOrientationSensor::remove_OrientationChanged, OrientationChanged(handler)); } template <typename D> void impl_ISimpleOrientationSensor<D>::OrientationChanged(event_token token) const { check_hresult(WINRT_SHIM(ISimpleOrientationSensor)->remove_OrientationChanged(token)); } template <typename D> void impl_ISimpleOrientationSensor2<D>::ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) const { check_hresult(WINRT_SHIM(ISimpleOrientationSensor2)->put_ReadingTransform(value)); } template <typename D> Windows::Graphics::Display::DisplayOrientations impl_ISimpleOrientationSensor2<D>::ReadingTransform() const { Windows::Graphics::Display::DisplayOrientations value {}; check_hresult(WINRT_SHIM(ISimpleOrientationSensor2)->get_ReadingTransform(&value)); return value; } template <typename D> Windows::Foundation::DateTime impl_ISimpleOrientationSensorOrientationChangedEventArgs<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(ISimpleOrientationSensorOrientationChangedEventArgs)->get_Timestamp(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::SimpleOrientation impl_ISimpleOrientationSensorOrientationChangedEventArgs<D>::Orientation() const { Windows::Devices::Sensors::SimpleOrientation value {}; check_hresult(WINRT_SHIM(ISimpleOrientationSensorOrientationChangedEventArgs)->get_Orientation(&value)); return value; } template <typename D> hstring impl_IMagnetometerDeviceId<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(IMagnetometerDeviceId)->get_DeviceId(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::Magnetometer impl_IMagnetometerStatics<D>::GetDefault() const { Windows::Devices::Sensors::Magnetometer result { nullptr }; check_hresult(WINRT_SHIM(IMagnetometerStatics)->abi_GetDefault(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::MagnetometerReading impl_IMagnetometer<D>::GetCurrentReading() const { Windows::Devices::Sensors::MagnetometerReading value { nullptr }; check_hresult(WINRT_SHIM(IMagnetometer)->abi_GetCurrentReading(put_abi(value))); return value; } template <typename D> uint32_t impl_IMagnetometer<D>::MinimumReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IMagnetometer)->get_MinimumReportInterval(&value)); return value; } template <typename D> void impl_IMagnetometer<D>::ReportInterval(uint32_t value) const { check_hresult(WINRT_SHIM(IMagnetometer)->put_ReportInterval(value)); } template <typename D> uint32_t impl_IMagnetometer<D>::ReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IMagnetometer)->get_ReportInterval(&value)); return value; } template <typename D> event_token impl_IMagnetometer<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Magnetometer, Windows::Devices::Sensors::MagnetometerReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IMagnetometer)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IMagnetometer> impl_IMagnetometer<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Magnetometer, Windows::Devices::Sensors::MagnetometerReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, IMagnetometer>(this, &ABI::Windows::Devices::Sensors::IMagnetometer::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_IMagnetometer<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(IMagnetometer)->remove_ReadingChanged(token)); } template <typename D> void impl_IMagnetometer2<D>::ReadingTransform(Windows::Graphics::Display::DisplayOrientations value) const { check_hresult(WINRT_SHIM(IMagnetometer2)->put_ReadingTransform(value)); } template <typename D> Windows::Graphics::Display::DisplayOrientations impl_IMagnetometer2<D>::ReadingTransform() const { Windows::Graphics::Display::DisplayOrientations value {}; check_hresult(WINRT_SHIM(IMagnetometer2)->get_ReadingTransform(&value)); return value; } template <typename D> Windows::Foundation::DateTime impl_IMagnetometerReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IMagnetometerReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> float impl_IMagnetometerReading<D>::MagneticFieldX() const { float value {}; check_hresult(WINRT_SHIM(IMagnetometerReading)->get_MagneticFieldX(&value)); return value; } template <typename D> float impl_IMagnetometerReading<D>::MagneticFieldY() const { float value {}; check_hresult(WINRT_SHIM(IMagnetometerReading)->get_MagneticFieldY(&value)); return value; } template <typename D> float impl_IMagnetometerReading<D>::MagneticFieldZ() const { float value {}; check_hresult(WINRT_SHIM(IMagnetometerReading)->get_MagneticFieldZ(&value)); return value; } template <typename D> Windows::Devices::Sensors::MagnetometerAccuracy impl_IMagnetometerReading<D>::DirectionalAccuracy() const { Windows::Devices::Sensors::MagnetometerAccuracy value {}; check_hresult(WINRT_SHIM(IMagnetometerReading)->get_DirectionalAccuracy(&value)); return value; } template <typename D> Windows::Devices::Sensors::MagnetometerReading impl_IMagnetometerReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::MagnetometerReading value { nullptr }; check_hresult(WINRT_SHIM(IMagnetometerReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::ActivitySensor> impl_IActivitySensorStatics<D>::GetDefaultAsync() const { Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::ActivitySensor> result; check_hresult(WINRT_SHIM(IActivitySensorStatics)->abi_GetDefaultAsync(put_abi(result))); return result; } template <typename D> hstring impl_IActivitySensorStatics<D>::GetDeviceSelector() const { hstring value; check_hresult(WINRT_SHIM(IActivitySensorStatics)->abi_GetDeviceSelector(put_abi(value))); return value; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::ActivitySensor> impl_IActivitySensorStatics<D>::FromIdAsync(hstring_view deviceId) const { Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::ActivitySensor> result; check_hresult(WINRT_SHIM(IActivitySensorStatics)->abi_FromIdAsync(get_abi(deviceId), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ActivitySensorReading>> impl_IActivitySensorStatics<D>::GetSystemHistoryAsync(const Windows::Foundation::DateTime & fromTime) const { Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ActivitySensorReading>> result; check_hresult(WINRT_SHIM(IActivitySensorStatics)->abi_GetSystemHistoryAsync(get_abi(fromTime), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ActivitySensorReading>> impl_IActivitySensorStatics<D>::GetSystemHistoryAsync(const Windows::Foundation::DateTime & fromTime, const Windows::Foundation::TimeSpan & duration) const { Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ActivitySensorReading>> result; check_hresult(WINRT_SHIM(IActivitySensorStatics)->abi_GetSystemHistoryWithDurationAsync(get_abi(fromTime), get_abi(duration), put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::ActivitySensorReading> impl_IActivitySensor<D>::GetCurrentReadingAsync() const { Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::ActivitySensorReading> result; check_hresult(WINRT_SHIM(IActivitySensor)->abi_GetCurrentReadingAsync(put_abi(result))); return result; } template <typename D> Windows::Foundation::Collections::IVector<winrt::Windows::Devices::Sensors::ActivityType> impl_IActivitySensor<D>::SubscribedActivities() const { Windows::Foundation::Collections::IVector<winrt::Windows::Devices::Sensors::ActivityType> value; check_hresult(WINRT_SHIM(IActivitySensor)->get_SubscribedActivities(put_abi(value))); return value; } template <typename D> double impl_IActivitySensor<D>::PowerInMilliwatts() const { double value {}; check_hresult(WINRT_SHIM(IActivitySensor)->get_PowerInMilliwatts(&value)); return value; } template <typename D> hstring impl_IActivitySensor<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(IActivitySensor)->get_DeviceId(put_abi(value))); return value; } template <typename D> Windows::Foundation::Collections::IVectorView<winrt::Windows::Devices::Sensors::ActivityType> impl_IActivitySensor<D>::SupportedActivities() const { Windows::Foundation::Collections::IVectorView<winrt::Windows::Devices::Sensors::ActivityType> value; check_hresult(WINRT_SHIM(IActivitySensor)->get_SupportedActivities(put_abi(value))); return value; } template <typename D> uint32_t impl_IActivitySensor<D>::MinimumReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IActivitySensor)->get_MinimumReportInterval(&value)); return value; } template <typename D> event_token impl_IActivitySensor<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::ActivitySensor, Windows::Devices::Sensors::ActivitySensorReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IActivitySensor)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IActivitySensor> impl_IActivitySensor<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::ActivitySensor, Windows::Devices::Sensors::ActivitySensorReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, IActivitySensor>(this, &ABI::Windows::Devices::Sensors::IActivitySensor::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_IActivitySensor<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(IActivitySensor)->remove_ReadingChanged(token)); } template <typename D> Windows::Foundation::DateTime impl_IActivitySensorReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IActivitySensorReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::ActivityType impl_IActivitySensorReading<D>::Activity() const { Windows::Devices::Sensors::ActivityType value {}; check_hresult(WINRT_SHIM(IActivitySensorReading)->get_Activity(&value)); return value; } template <typename D> Windows::Devices::Sensors::ActivitySensorReadingConfidence impl_IActivitySensorReading<D>::Confidence() const { Windows::Devices::Sensors::ActivitySensorReadingConfidence value {}; check_hresult(WINRT_SHIM(IActivitySensorReading)->get_Confidence(&value)); return value; } template <typename D> Windows::Devices::Sensors::ActivitySensorReading impl_IActivitySensorReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::ActivitySensorReading value { nullptr }; check_hresult(WINRT_SHIM(IActivitySensorReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::ActivitySensorReading impl_IActivitySensorReadingChangeReport<D>::Reading() const { Windows::Devices::Sensors::ActivitySensorReading value { nullptr }; check_hresult(WINRT_SHIM(IActivitySensorReadingChangeReport)->get_Reading(put_abi(value))); return value; } template <typename D> Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ActivitySensorReadingChangeReport> impl_IActivitySensorTriggerDetails<D>::ReadReports() const { Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ActivitySensorReadingChangeReport> value; check_hresult(WINRT_SHIM(IActivitySensorTriggerDetails)->abi_ReadReports(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::Barometer impl_IBarometerStatics<D>::GetDefault() const { Windows::Devices::Sensors::Barometer result { nullptr }; check_hresult(WINRT_SHIM(IBarometerStatics)->abi_GetDefault(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::BarometerReading impl_IBarometer<D>::GetCurrentReading() const { Windows::Devices::Sensors::BarometerReading value { nullptr }; check_hresult(WINRT_SHIM(IBarometer)->abi_GetCurrentReading(put_abi(value))); return value; } template <typename D> hstring impl_IBarometer<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(IBarometer)->get_DeviceId(put_abi(value))); return value; } template <typename D> uint32_t impl_IBarometer<D>::MinimumReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IBarometer)->get_MinimumReportInterval(&value)); return value; } template <typename D> void impl_IBarometer<D>::ReportInterval(uint32_t value) const { check_hresult(WINRT_SHIM(IBarometer)->put_ReportInterval(value)); } template <typename D> uint32_t impl_IBarometer<D>::ReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IBarometer)->get_ReportInterval(&value)); return value; } template <typename D> event_token impl_IBarometer<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Barometer, Windows::Devices::Sensors::BarometerReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IBarometer)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IBarometer> impl_IBarometer<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Barometer, Windows::Devices::Sensors::BarometerReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, IBarometer>(this, &ABI::Windows::Devices::Sensors::IBarometer::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_IBarometer<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(IBarometer)->remove_ReadingChanged(token)); } template <typename D> Windows::Foundation::DateTime impl_IBarometerReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IBarometerReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> double impl_IBarometerReading<D>::StationPressureInHectopascals() const { double value {}; check_hresult(WINRT_SHIM(IBarometerReading)->get_StationPressureInHectopascals(&value)); return value; } template <typename D> Windows::Devices::Sensors::BarometerReading impl_IBarometerReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::BarometerReading value { nullptr }; check_hresult(WINRT_SHIM(IBarometerReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::PedometerStepKind impl_IPedometerReading<D>::StepKind() const { Windows::Devices::Sensors::PedometerStepKind value {}; check_hresult(WINRT_SHIM(IPedometerReading)->get_StepKind(&value)); return value; } template <typename D> int32_t impl_IPedometerReading<D>::CumulativeSteps() const { int32_t value {}; check_hresult(WINRT_SHIM(IPedometerReading)->get_CumulativeSteps(&value)); return value; } template <typename D> Windows::Foundation::DateTime impl_IPedometerReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IPedometerReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> Windows::Foundation::TimeSpan impl_IPedometerReading<D>::CumulativeStepsDuration() const { Windows::Foundation::TimeSpan value {}; check_hresult(WINRT_SHIM(IPedometerReading)->get_CumulativeStepsDuration(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::PedometerReading impl_IPedometerReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::PedometerReading value { nullptr }; check_hresult(WINRT_SHIM(IPedometerReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::Pedometer> impl_IPedometerStatics<D>::FromIdAsync(hstring_view deviceId) const { Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::Pedometer> operation; check_hresult(WINRT_SHIM(IPedometerStatics)->abi_FromIdAsync(get_abi(deviceId), put_abi(operation))); return operation; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::Pedometer> impl_IPedometerStatics<D>::GetDefaultAsync() const { Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::Pedometer> operation; check_hresult(WINRT_SHIM(IPedometerStatics)->abi_GetDefaultAsync(put_abi(operation))); return operation; } template <typename D> hstring impl_IPedometerStatics<D>::GetDeviceSelector() const { hstring result; check_hresult(WINRT_SHIM(IPedometerStatics)->abi_GetDeviceSelector(put_abi(result))); return result; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading>> impl_IPedometerStatics<D>::GetSystemHistoryAsync(const Windows::Foundation::DateTime & fromTime) const { Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading>> operation; check_hresult(WINRT_SHIM(IPedometerStatics)->abi_GetSystemHistoryAsync(get_abi(fromTime), put_abi(operation))); return operation; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading>> impl_IPedometerStatics<D>::GetSystemHistoryAsync(const Windows::Foundation::DateTime & fromTime, const Windows::Foundation::TimeSpan & duration) const { Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading>> operation; check_hresult(WINRT_SHIM(IPedometerStatics)->abi_GetSystemHistoryWithDurationAsync(get_abi(fromTime), get_abi(duration), put_abi(operation))); return operation; } template <typename D> Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading> impl_IPedometerStatics2<D>::GetReadingsFromTriggerDetails(const Windows::Devices::Sensors::SensorDataThresholdTriggerDetails & triggerDetails) const { Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading> result; check_hresult(WINRT_SHIM(IPedometerStatics2)->abi_GetReadingsFromTriggerDetails(get_abi(triggerDetails), put_abi(result))); return result; } template <typename D> Windows::Foundation::Collections::IMapView<winrt::Windows::Devices::Sensors::PedometerStepKind, Windows::Devices::Sensors::PedometerReading> impl_IPedometer2<D>::GetCurrentReadings() const { Windows::Foundation::Collections::IMapView<winrt::Windows::Devices::Sensors::PedometerStepKind, Windows::Devices::Sensors::PedometerReading> value; check_hresult(WINRT_SHIM(IPedometer2)->abi_GetCurrentReadings(put_abi(value))); return value; } template <typename D> hstring impl_IPedometer<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(IPedometer)->get_DeviceId(put_abi(value))); return value; } template <typename D> double impl_IPedometer<D>::PowerInMilliwatts() const { double value {}; check_hresult(WINRT_SHIM(IPedometer)->get_PowerInMilliwatts(&value)); return value; } template <typename D> uint32_t impl_IPedometer<D>::MinimumReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IPedometer)->get_MinimumReportInterval(&value)); return value; } template <typename D> void impl_IPedometer<D>::ReportInterval(uint32_t value) const { check_hresult(WINRT_SHIM(IPedometer)->put_ReportInterval(value)); } template <typename D> uint32_t impl_IPedometer<D>::ReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IPedometer)->get_ReportInterval(&value)); return value; } template <typename D> event_token impl_IPedometer<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Pedometer, Windows::Devices::Sensors::PedometerReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IPedometer)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IPedometer> impl_IPedometer<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Pedometer, Windows::Devices::Sensors::PedometerReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, IPedometer>(this, &ABI::Windows::Devices::Sensors::IPedometer::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_IPedometer<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(IPedometer)->remove_ReadingChanged(token)); } template <typename D> Windows::Devices::Sensors::PedometerDataThreshold impl_IPedometerDataThresholdFactory<D>::Create(const Windows::Devices::Sensors::Pedometer & sensor, int32_t stepGoal) const { Windows::Devices::Sensors::PedometerDataThreshold threshold { nullptr }; check_hresult(WINRT_SHIM(IPedometerDataThresholdFactory)->abi_Create(get_abi(sensor), stepGoal, put_abi(threshold))); return threshold; } template <typename D> hstring impl_IProximitySensorStatics<D>::GetDeviceSelector() const { hstring value; check_hresult(WINRT_SHIM(IProximitySensorStatics)->abi_GetDeviceSelector(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::ProximitySensor impl_IProximitySensorStatics<D>::FromId(hstring_view sensorId) const { Windows::Devices::Sensors::ProximitySensor result { nullptr }; check_hresult(WINRT_SHIM(IProximitySensorStatics)->abi_FromId(get_abi(sensorId), put_abi(result))); return result; } template <typename D> hstring impl_IProximitySensor<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(IProximitySensor)->get_DeviceId(put_abi(value))); return value; } template <typename D> Windows::Foundation::IReference<uint32_t> impl_IProximitySensor<D>::MaxDistanceInMillimeters() const { Windows::Foundation::IReference<uint32_t> value; check_hresult(WINRT_SHIM(IProximitySensor)->get_MaxDistanceInMillimeters(put_abi(value))); return value; } template <typename D> Windows::Foundation::IReference<uint32_t> impl_IProximitySensor<D>::MinDistanceInMillimeters() const { Windows::Foundation::IReference<uint32_t> value; check_hresult(WINRT_SHIM(IProximitySensor)->get_MinDistanceInMillimeters(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::ProximitySensorReading impl_IProximitySensor<D>::GetCurrentReading() const { Windows::Devices::Sensors::ProximitySensorReading value { nullptr }; check_hresult(WINRT_SHIM(IProximitySensor)->abi_GetCurrentReading(put_abi(value))); return value; } template <typename D> event_token impl_IProximitySensor<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::ProximitySensor, Windows::Devices::Sensors::ProximitySensorReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IProximitySensor)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IProximitySensor> impl_IProximitySensor<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::ProximitySensor, Windows::Devices::Sensors::ProximitySensorReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, IProximitySensor>(this, &ABI::Windows::Devices::Sensors::IProximitySensor::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_IProximitySensor<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(IProximitySensor)->remove_ReadingChanged(token)); } template <typename D> Windows::Devices::Sensors::ProximitySensorDisplayOnOffController impl_IProximitySensor<D>::CreateDisplayOnOffController() const { Windows::Devices::Sensors::ProximitySensorDisplayOnOffController controller { nullptr }; check_hresult(WINRT_SHIM(IProximitySensor)->abi_CreateDisplayOnOffController(put_abi(controller))); return controller; } template <typename D> Windows::Devices::Sensors::ProximitySensorReading impl_IProximitySensorReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::ProximitySensorReading value { nullptr }; check_hresult(WINRT_SHIM(IProximitySensorReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } template <typename D> Windows::Foundation::DateTime impl_IProximitySensorReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IProximitySensorReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> bool impl_IProximitySensorReading<D>::IsDetected() const { bool value {}; check_hresult(WINRT_SHIM(IProximitySensorReading)->get_IsDetected(&value)); return value; } template <typename D> Windows::Foundation::IReference<uint32_t> impl_IProximitySensorReading<D>::DistanceInMillimeters() const { Windows::Foundation::IReference<uint32_t> value; check_hresult(WINRT_SHIM(IProximitySensorReading)->get_DistanceInMillimeters(put_abi(value))); return value; } template <typename D> Windows::Devices::Sensors::ProximitySensorDataThreshold impl_IProximitySensorDataThresholdFactory<D>::Create(const Windows::Devices::Sensors::ProximitySensor & sensor) const { Windows::Devices::Sensors::ProximitySensorDataThreshold threshold { nullptr }; check_hresult(WINRT_SHIM(IProximitySensorDataThresholdFactory)->abi_Create(get_abi(sensor), put_abi(threshold))); return threshold; } template <typename D> Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ProximitySensorReading> impl_IProximitySensorStatics2<D>::GetReadingsFromTriggerDetails(const Windows::Devices::Sensors::SensorDataThresholdTriggerDetails & triggerDetails) const { Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ProximitySensorReading> result; check_hresult(WINRT_SHIM(IProximitySensorStatics2)->abi_GetReadingsFromTriggerDetails(get_abi(triggerDetails), put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::Altimeter impl_IAltimeterStatics<D>::GetDefault() const { Windows::Devices::Sensors::Altimeter result { nullptr }; check_hresult(WINRT_SHIM(IAltimeterStatics)->abi_GetDefault(put_abi(result))); return result; } template <typename D> Windows::Devices::Sensors::AltimeterReading impl_IAltimeter<D>::GetCurrentReading() const { Windows::Devices::Sensors::AltimeterReading value { nullptr }; check_hresult(WINRT_SHIM(IAltimeter)->abi_GetCurrentReading(put_abi(value))); return value; } template <typename D> hstring impl_IAltimeter<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(IAltimeter)->get_DeviceId(put_abi(value))); return value; } template <typename D> uint32_t impl_IAltimeter<D>::MinimumReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IAltimeter)->get_MinimumReportInterval(&value)); return value; } template <typename D> void impl_IAltimeter<D>::ReportInterval(uint32_t value) const { check_hresult(WINRT_SHIM(IAltimeter)->put_ReportInterval(value)); } template <typename D> uint32_t impl_IAltimeter<D>::ReportInterval() const { uint32_t value {}; check_hresult(WINRT_SHIM(IAltimeter)->get_ReportInterval(&value)); return value; } template <typename D> event_token impl_IAltimeter<D>::ReadingChanged(const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Altimeter, Windows::Devices::Sensors::AltimeterReadingChangedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IAltimeter)->add_ReadingChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IAltimeter> impl_IAltimeter<D>::ReadingChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Altimeter, Windows::Devices::Sensors::AltimeterReadingChangedEventArgs> & handler) const { return impl::make_event_revoker<D, IAltimeter>(this, &ABI::Windows::Devices::Sensors::IAltimeter::remove_ReadingChanged, ReadingChanged(handler)); } template <typename D> void impl_IAltimeter<D>::ReadingChanged(event_token token) const { check_hresult(WINRT_SHIM(IAltimeter)->remove_ReadingChanged(token)); } template <typename D> Windows::Foundation::DateTime impl_IAltimeterReading<D>::Timestamp() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IAltimeterReading)->get_Timestamp(put_abi(value))); return value; } template <typename D> double impl_IAltimeterReading<D>::AltitudeChangeInMeters() const { double value {}; check_hresult(WINRT_SHIM(IAltimeterReading)->get_AltitudeChangeInMeters(&value)); return value; } template <typename D> Windows::Devices::Sensors::AltimeterReading impl_IAltimeterReadingChangedEventArgs<D>::Reading() const { Windows::Devices::Sensors::AltimeterReading value { nullptr }; check_hresult(WINRT_SHIM(IAltimeterReadingChangedEventArgs)->get_Reading(put_abi(value))); return value; } inline Windows::Devices::Sensors::Accelerometer Accelerometer::GetDefault() { return get_activation_factory<Accelerometer, IAccelerometerStatics>().GetDefault(); } inline Windows::Devices::Sensors::Accelerometer Accelerometer::GetDefault(Windows::Devices::Sensors::AccelerometerReadingType readingType) { return get_activation_factory<Accelerometer, IAccelerometerStatics2>().GetDefault(readingType); } inline Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::ActivitySensor> ActivitySensor::GetDefaultAsync() { return get_activation_factory<ActivitySensor, IActivitySensorStatics>().GetDefaultAsync(); } inline hstring ActivitySensor::GetDeviceSelector() { return get_activation_factory<ActivitySensor, IActivitySensorStatics>().GetDeviceSelector(); } inline Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::ActivitySensor> ActivitySensor::FromIdAsync(hstring_view deviceId) { return get_activation_factory<ActivitySensor, IActivitySensorStatics>().FromIdAsync(deviceId); } inline Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ActivitySensorReading>> ActivitySensor::GetSystemHistoryAsync(const Windows::Foundation::DateTime & fromTime) { return get_activation_factory<ActivitySensor, IActivitySensorStatics>().GetSystemHistoryAsync(fromTime); } inline Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ActivitySensorReading>> ActivitySensor::GetSystemHistoryAsync(const Windows::Foundation::DateTime & fromTime, const Windows::Foundation::TimeSpan & duration) { return get_activation_factory<ActivitySensor, IActivitySensorStatics>().GetSystemHistoryAsync(fromTime, duration); } inline Windows::Devices::Sensors::Altimeter Altimeter::GetDefault() { return get_activation_factory<Altimeter, IAltimeterStatics>().GetDefault(); } inline Windows::Devices::Sensors::Barometer Barometer::GetDefault() { return get_activation_factory<Barometer, IBarometerStatics>().GetDefault(); } inline Windows::Devices::Sensors::Compass Compass::GetDefault() { return get_activation_factory<Compass, ICompassStatics>().GetDefault(); } inline Windows::Devices::Sensors::Gyrometer Gyrometer::GetDefault() { return get_activation_factory<Gyrometer, IGyrometerStatics>().GetDefault(); } inline Windows::Devices::Sensors::Inclinometer Inclinometer::GetDefault() { return get_activation_factory<Inclinometer, IInclinometerStatics>().GetDefault(); } inline Windows::Devices::Sensors::Inclinometer Inclinometer::GetDefaultForRelativeReadings() { return get_activation_factory<Inclinometer, IInclinometerStatics2>().GetDefaultForRelativeReadings(); } inline Windows::Devices::Sensors::Inclinometer Inclinometer::GetDefault(Windows::Devices::Sensors::SensorReadingType sensorReadingtype) { return get_activation_factory<Inclinometer, IInclinometerStatics3>().GetDefault(sensorReadingtype); } inline Windows::Devices::Sensors::LightSensor LightSensor::GetDefault() { return get_activation_factory<LightSensor, ILightSensorStatics>().GetDefault(); } inline Windows::Devices::Sensors::Magnetometer Magnetometer::GetDefault() { return get_activation_factory<Magnetometer, IMagnetometerStatics>().GetDefault(); } inline Windows::Devices::Sensors::OrientationSensor OrientationSensor::GetDefault() { return get_activation_factory<OrientationSensor, IOrientationSensorStatics>().GetDefault(); } inline Windows::Devices::Sensors::OrientationSensor OrientationSensor::GetDefaultForRelativeReadings() { return get_activation_factory<OrientationSensor, IOrientationSensorStatics2>().GetDefaultForRelativeReadings(); } inline Windows::Devices::Sensors::OrientationSensor OrientationSensor::GetDefault(Windows::Devices::Sensors::SensorReadingType sensorReadingtype) { return get_activation_factory<OrientationSensor, IOrientationSensorStatics3>().GetDefault(sensorReadingtype); } inline Windows::Devices::Sensors::OrientationSensor OrientationSensor::GetDefault(Windows::Devices::Sensors::SensorReadingType sensorReadingType, Windows::Devices::Sensors::SensorOptimizationGoal optimizationGoal) { return get_activation_factory<OrientationSensor, IOrientationSensorStatics3>().GetDefault(sensorReadingType, optimizationGoal); } inline Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::Pedometer> Pedometer::FromIdAsync(hstring_view deviceId) { return get_activation_factory<Pedometer, IPedometerStatics>().FromIdAsync(deviceId); } inline Windows::Foundation::IAsyncOperation<Windows::Devices::Sensors::Pedometer> Pedometer::GetDefaultAsync() { return get_activation_factory<Pedometer, IPedometerStatics>().GetDefaultAsync(); } inline hstring Pedometer::GetDeviceSelector() { return get_activation_factory<Pedometer, IPedometerStatics>().GetDeviceSelector(); } inline Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading>> Pedometer::GetSystemHistoryAsync(const Windows::Foundation::DateTime & fromTime) { return get_activation_factory<Pedometer, IPedometerStatics>().GetSystemHistoryAsync(fromTime); } inline Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading>> Pedometer::GetSystemHistoryAsync(const Windows::Foundation::DateTime & fromTime, const Windows::Foundation::TimeSpan & duration) { return get_activation_factory<Pedometer, IPedometerStatics>().GetSystemHistoryAsync(fromTime, duration); } inline Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::PedometerReading> Pedometer::GetReadingsFromTriggerDetails(const Windows::Devices::Sensors::SensorDataThresholdTriggerDetails & triggerDetails) { return get_activation_factory<Pedometer, IPedometerStatics2>().GetReadingsFromTriggerDetails(triggerDetails); } inline PedometerDataThreshold::PedometerDataThreshold(const Windows::Devices::Sensors::Pedometer & sensor, int32_t stepGoal) : PedometerDataThreshold(get_activation_factory<PedometerDataThreshold, IPedometerDataThresholdFactory>().Create(sensor, stepGoal)) {} inline hstring ProximitySensor::GetDeviceSelector() { return get_activation_factory<ProximitySensor, IProximitySensorStatics>().GetDeviceSelector(); } inline Windows::Devices::Sensors::ProximitySensor ProximitySensor::FromId(hstring_view sensorId) { return get_activation_factory<ProximitySensor, IProximitySensorStatics>().FromId(sensorId); } inline Windows::Foundation::Collections::IVectorView<Windows::Devices::Sensors::ProximitySensorReading> ProximitySensor::GetReadingsFromTriggerDetails(const Windows::Devices::Sensors::SensorDataThresholdTriggerDetails & triggerDetails) { return get_activation_factory<ProximitySensor, IProximitySensorStatics2>().GetReadingsFromTriggerDetails(triggerDetails); } inline ProximitySensorDataThreshold::ProximitySensorDataThreshold(const Windows::Devices::Sensors::ProximitySensor & sensor) : ProximitySensorDataThreshold(get_activation_factory<ProximitySensorDataThreshold, IProximitySensorDataThresholdFactory>().Create(sensor)) {} inline Windows::Devices::Sensors::SimpleOrientationSensor SimpleOrientationSensor::GetDefault() { return get_activation_factory<SimpleOrientationSensor, ISimpleOrientationSensorStatics>().GetDefault(); } } } template<> struct std::hash<winrt::Windows::Devices::Sensors::IAccelerometer> { size_t operator()(const winrt::Windows::Devices::Sensors::IAccelerometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAccelerometer2> { size_t operator()(const winrt::Windows::Devices::Sensors::IAccelerometer2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAccelerometer3> { size_t operator()(const winrt::Windows::Devices::Sensors::IAccelerometer3 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAccelerometer4> { size_t operator()(const winrt::Windows::Devices::Sensors::IAccelerometer4 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAccelerometerDeviceId> { size_t operator()(const winrt::Windows::Devices::Sensors::IAccelerometerDeviceId & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAccelerometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::IAccelerometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAccelerometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::IAccelerometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAccelerometerShakenEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::IAccelerometerShakenEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAccelerometerStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::IAccelerometerStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAccelerometerStatics2> { size_t operator()(const winrt::Windows::Devices::Sensors::IAccelerometerStatics2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IActivitySensor> { size_t operator()(const winrt::Windows::Devices::Sensors::IActivitySensor & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IActivitySensorReading> { size_t operator()(const winrt::Windows::Devices::Sensors::IActivitySensorReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IActivitySensorReadingChangeReport> { size_t operator()(const winrt::Windows::Devices::Sensors::IActivitySensorReadingChangeReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IActivitySensorReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::IActivitySensorReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IActivitySensorStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::IActivitySensorStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IActivitySensorTriggerDetails> { size_t operator()(const winrt::Windows::Devices::Sensors::IActivitySensorTriggerDetails & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAltimeter> { size_t operator()(const winrt::Windows::Devices::Sensors::IAltimeter & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAltimeterReading> { size_t operator()(const winrt::Windows::Devices::Sensors::IAltimeterReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAltimeterReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::IAltimeterReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IAltimeterStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::IAltimeterStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IBarometer> { size_t operator()(const winrt::Windows::Devices::Sensors::IBarometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IBarometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::IBarometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IBarometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::IBarometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IBarometerStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::IBarometerStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ICompass> { size_t operator()(const winrt::Windows::Devices::Sensors::ICompass & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ICompass2> { size_t operator()(const winrt::Windows::Devices::Sensors::ICompass2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ICompassDeviceId> { size_t operator()(const winrt::Windows::Devices::Sensors::ICompassDeviceId & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ICompassReading> { size_t operator()(const winrt::Windows::Devices::Sensors::ICompassReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ICompassReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::ICompassReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ICompassReadingHeadingAccuracy> { size_t operator()(const winrt::Windows::Devices::Sensors::ICompassReadingHeadingAccuracy & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ICompassStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::ICompassStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IGyrometer> { size_t operator()(const winrt::Windows::Devices::Sensors::IGyrometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IGyrometer2> { size_t operator()(const winrt::Windows::Devices::Sensors::IGyrometer2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IGyrometerDeviceId> { size_t operator()(const winrt::Windows::Devices::Sensors::IGyrometerDeviceId & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IGyrometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::IGyrometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IGyrometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::IGyrometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IGyrometerStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::IGyrometerStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IInclinometer> { size_t operator()(const winrt::Windows::Devices::Sensors::IInclinometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IInclinometer2> { size_t operator()(const winrt::Windows::Devices::Sensors::IInclinometer2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IInclinometerDeviceId> { size_t operator()(const winrt::Windows::Devices::Sensors::IInclinometerDeviceId & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IInclinometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::IInclinometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IInclinometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::IInclinometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IInclinometerReadingYawAccuracy> { size_t operator()(const winrt::Windows::Devices::Sensors::IInclinometerReadingYawAccuracy & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IInclinometerStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::IInclinometerStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IInclinometerStatics2> { size_t operator()(const winrt::Windows::Devices::Sensors::IInclinometerStatics2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IInclinometerStatics3> { size_t operator()(const winrt::Windows::Devices::Sensors::IInclinometerStatics3 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ILightSensor> { size_t operator()(const winrt::Windows::Devices::Sensors::ILightSensor & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ILightSensorDeviceId> { size_t operator()(const winrt::Windows::Devices::Sensors::ILightSensorDeviceId & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ILightSensorReading> { size_t operator()(const winrt::Windows::Devices::Sensors::ILightSensorReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ILightSensorReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::ILightSensorReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ILightSensorStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::ILightSensorStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IMagnetometer> { size_t operator()(const winrt::Windows::Devices::Sensors::IMagnetometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IMagnetometer2> { size_t operator()(const winrt::Windows::Devices::Sensors::IMagnetometer2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IMagnetometerDeviceId> { size_t operator()(const winrt::Windows::Devices::Sensors::IMagnetometerDeviceId & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IMagnetometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::IMagnetometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IMagnetometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::IMagnetometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IMagnetometerStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::IMagnetometerStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IOrientationSensor> { size_t operator()(const winrt::Windows::Devices::Sensors::IOrientationSensor & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IOrientationSensor2> { size_t operator()(const winrt::Windows::Devices::Sensors::IOrientationSensor2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IOrientationSensorDeviceId> { size_t operator()(const winrt::Windows::Devices::Sensors::IOrientationSensorDeviceId & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IOrientationSensorReading> { size_t operator()(const winrt::Windows::Devices::Sensors::IOrientationSensorReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IOrientationSensorReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::IOrientationSensorReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IOrientationSensorReadingYawAccuracy> { size_t operator()(const winrt::Windows::Devices::Sensors::IOrientationSensorReadingYawAccuracy & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IOrientationSensorStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::IOrientationSensorStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IOrientationSensorStatics2> { size_t operator()(const winrt::Windows::Devices::Sensors::IOrientationSensorStatics2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IOrientationSensorStatics3> { size_t operator()(const winrt::Windows::Devices::Sensors::IOrientationSensorStatics3 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IPedometer> { size_t operator()(const winrt::Windows::Devices::Sensors::IPedometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IPedometer2> { size_t operator()(const winrt::Windows::Devices::Sensors::IPedometer2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IPedometerDataThresholdFactory> { size_t operator()(const winrt::Windows::Devices::Sensors::IPedometerDataThresholdFactory & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IPedometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::IPedometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IPedometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::IPedometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IPedometerStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::IPedometerStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IPedometerStatics2> { size_t operator()(const winrt::Windows::Devices::Sensors::IPedometerStatics2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IProximitySensor> { size_t operator()(const winrt::Windows::Devices::Sensors::IProximitySensor & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IProximitySensorDataThresholdFactory> { size_t operator()(const winrt::Windows::Devices::Sensors::IProximitySensorDataThresholdFactory & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IProximitySensorReading> { size_t operator()(const winrt::Windows::Devices::Sensors::IProximitySensorReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IProximitySensorReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::IProximitySensorReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IProximitySensorStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::IProximitySensorStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::IProximitySensorStatics2> { size_t operator()(const winrt::Windows::Devices::Sensors::IProximitySensorStatics2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ISensorDataThreshold> { size_t operator()(const winrt::Windows::Devices::Sensors::ISensorDataThreshold & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ISensorDataThresholdTriggerDetails> { size_t operator()(const winrt::Windows::Devices::Sensors::ISensorDataThresholdTriggerDetails & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ISensorQuaternion> { size_t operator()(const winrt::Windows::Devices::Sensors::ISensorQuaternion & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ISensorRotationMatrix> { size_t operator()(const winrt::Windows::Devices::Sensors::ISensorRotationMatrix & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ISimpleOrientationSensor> { size_t operator()(const winrt::Windows::Devices::Sensors::ISimpleOrientationSensor & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ISimpleOrientationSensor2> { size_t operator()(const winrt::Windows::Devices::Sensors::ISimpleOrientationSensor2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ISimpleOrientationSensorDeviceId> { size_t operator()(const winrt::Windows::Devices::Sensors::ISimpleOrientationSensorDeviceId & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ISimpleOrientationSensorOrientationChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::ISimpleOrientationSensorOrientationChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ISimpleOrientationSensorStatics> { size_t operator()(const winrt::Windows::Devices::Sensors::ISimpleOrientationSensorStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::Accelerometer> { size_t operator()(const winrt::Windows::Devices::Sensors::Accelerometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::AccelerometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::AccelerometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::AccelerometerShakenEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::AccelerometerShakenEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ActivitySensor> { size_t operator()(const winrt::Windows::Devices::Sensors::ActivitySensor & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ActivitySensorReading> { size_t operator()(const winrt::Windows::Devices::Sensors::ActivitySensorReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ActivitySensorReadingChangeReport> { size_t operator()(const winrt::Windows::Devices::Sensors::ActivitySensorReadingChangeReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ActivitySensorReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::ActivitySensorReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ActivitySensorTriggerDetails> { size_t operator()(const winrt::Windows::Devices::Sensors::ActivitySensorTriggerDetails & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::Altimeter> { size_t operator()(const winrt::Windows::Devices::Sensors::Altimeter & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::AltimeterReading> { size_t operator()(const winrt::Windows::Devices::Sensors::AltimeterReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::AltimeterReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::AltimeterReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::Barometer> { size_t operator()(const winrt::Windows::Devices::Sensors::Barometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::BarometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::BarometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::BarometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::BarometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::Compass> { size_t operator()(const winrt::Windows::Devices::Sensors::Compass & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::CompassReading> { size_t operator()(const winrt::Windows::Devices::Sensors::CompassReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::CompassReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::CompassReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::Gyrometer> { size_t operator()(const winrt::Windows::Devices::Sensors::Gyrometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::GyrometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::GyrometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::GyrometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::GyrometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::Inclinometer> { size_t operator()(const winrt::Windows::Devices::Sensors::Inclinometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::InclinometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::InclinometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::InclinometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::InclinometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::LightSensor> { size_t operator()(const winrt::Windows::Devices::Sensors::LightSensor & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::LightSensorReading> { size_t operator()(const winrt::Windows::Devices::Sensors::LightSensorReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::LightSensorReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::LightSensorReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::Magnetometer> { size_t operator()(const winrt::Windows::Devices::Sensors::Magnetometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::MagnetometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::MagnetometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::MagnetometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::MagnetometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::OrientationSensor> { size_t operator()(const winrt::Windows::Devices::Sensors::OrientationSensor & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::OrientationSensorReading> { size_t operator()(const winrt::Windows::Devices::Sensors::OrientationSensorReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::OrientationSensorReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::OrientationSensorReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::Pedometer> { size_t operator()(const winrt::Windows::Devices::Sensors::Pedometer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::PedometerDataThreshold> { size_t operator()(const winrt::Windows::Devices::Sensors::PedometerDataThreshold & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::PedometerReading> { size_t operator()(const winrt::Windows::Devices::Sensors::PedometerReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::PedometerReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::PedometerReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ProximitySensor> { size_t operator()(const winrt::Windows::Devices::Sensors::ProximitySensor & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ProximitySensorDataThreshold> { size_t operator()(const winrt::Windows::Devices::Sensors::ProximitySensorDataThreshold & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ProximitySensorDisplayOnOffController> { size_t operator()(const winrt::Windows::Devices::Sensors::ProximitySensorDisplayOnOffController & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ProximitySensorReading> { size_t operator()(const winrt::Windows::Devices::Sensors::ProximitySensorReading & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::ProximitySensorReadingChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::ProximitySensorReadingChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::SensorDataThresholdTriggerDetails> { size_t operator()(const winrt::Windows::Devices::Sensors::SensorDataThresholdTriggerDetails & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::SensorQuaternion> { size_t operator()(const winrt::Windows::Devices::Sensors::SensorQuaternion & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::SensorRotationMatrix> { size_t operator()(const winrt::Windows::Devices::Sensors::SensorRotationMatrix & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::SimpleOrientationSensor> { size_t operator()(const winrt::Windows::Devices::Sensors::SimpleOrientationSensor & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Devices::Sensors::SimpleOrientationSensorOrientationChangedEventArgs> { size_t operator()(const winrt::Windows::Devices::Sensors::SimpleOrientationSensorOrientationChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; WINRT_WARNING_POP
#include "HashFactory.h" void HashFactory::addInfo(string _info) { info.push_back(_info); return ; } void HashFactory::printInfo() { int start = 1; for(auto i : info) { cout<<start++<<".Using "<<i<<" to ensure the value of hash."<<endl; } } unsigned long HashFactory::ChoseHash(char *tok[], int Ntoken) { switch(numHash) { case 1: hash1(tok, Ntoken); break; case 2: hash2(tok, Ntoken); break; case 3: hash3(tok, Ntoken); break; default: cout<<"Don't have this number, please try again."<<endl; int num = 0; cin>>num; set_numHash(num); ChoseHash(tok, Ntoken); break; } } unsigned long HashFactory::hash1(char *tok[], int Ntoken) { unsigned long h; unsigned char *s; int i; h = 0; for (i=0; i < Ntoken; i++) for (s = (unsigned char*)tok[i]; *s; s++) h = h*31 + *s; return h; } unsigned long HashFactory::hash2(char *tok[], int Ntoken) { int p = 16777619; int hash = (int)2166136261L; unsigned char *s; for(int i = 0;i < Ntoken; i++) for(s = (unsigned char*)tok[i]; *s; s++) hash = (hash ^ *s) * p; hash += hash << 13; hash ^= hash >> 7; hash += hash << 3; hash ^= hash >> 17; hash += hash << 5; return hash; } unsigned long HashFactory::hash3(char *tok[], int Ntoken) { unsigned long hash = 0; unsigned char *s; for(int i = 0;i < Ntoken; i++) for(s = (unsigned char*)tok[i]; *s; s++) hash = *s + (hash << 6) + (hash << 16) - hash; return hash; }
/* * Copyright: * Daniel D. Neilson (ddneilson@ieee.org) * University of Saskatchewan * All rights reserved * * Permission granted to use for use in assignments and * projects for CMPT 485 & CMPT 829 at the University * of Saskatchewan. */ /* * Class definition for a Shader * * This is the base class of all Shaders that you will define. */ #pragma once #ifndef __INC_SHADER_H__ #define __INC_SHADER_H__ #include <GL/gl.h> #include "glprogram.h" namespace Shader { class Shader { protected: // Handle for the GLSL program GLProgram m_program; // true iff the GLSL program has been compiled & linked without // error bool m_isReady; // Get the handle to one of the shader uniform variables. inline GLint getUniformLoc(UniformVars var) { return m_program.getUniformID(var); } public: Shader(); virtual ~Shader(); inline bool getIsReady() const { return m_isReady; } inline GLuint getID() const { return m_program.getID(); } // Bind/unbind the GLSL program for this shader virtual void bindGL() const; virtual void unbindGL() const; // Set the uniforms for the shader. // Assumes that the shader has already been bound. // Returns true iff successful virtual bool setUniforms(const GLProgUniforms &uniforms) const; }; } // namespace #endif
#ifndef _GOLDBOARD_H_ #define _GOLDBOARD_H_ #include "i2c_device.h" #include "pcf8574.h" extern "C"{ #include "pwm.h" } #include "uart.h" class goldboard{ public: goldboard(struct avr_t* avr); ~goldboard(); void add_i2c_device(i2c_device &device); int run(int ms); void set_state(Json &data); Json get_state(); private: //interface function int get_led_status(int id); double get_motor_speed(int id); double get_power_pin(int id); std::string get_serial_data(); int get_time(); void set_pin_state(int id, int state); void set_analog_state(int id, int state); void set_button_status(int id, int state); struct avr_t* avr; pwm_info_t motor_pwm[4]; pwm_info_t power_pwm[2]; uart uart_obj; pcf8574 pcf_motor; pcf8574 pcf_digital; int button_state[2]; }; #endif
/* * */ #ifndef __PLAYER_H #define __PLAYER_H #include "object.h" #include "terrain.h" #include "audio.h" #include "h.h" class Player: public Object { private: // CAudioSystem *audioSys; // CAudio *rocketSound; // void SetAudioSystem(CAudioSystem *aSys) { audioSys = aSys; } void emit_rocket(); public: Player(Terrain * terrain); virtual ~Player(); void update_input(float second); virtual void v_collision(Object *object) final; virtual void v_draw(float second) final; // bool player_go_forward_; // bool player_go_back_; // bool player_go_left_; // bool player_go_right_; // bool player_jump_; // bool player_turn_left_; // bool player_turn_right_; // bool player_go_upper_; // bool player_go_lower_; // int mouse_move_x_; int rocket_to_emit_; int emited_rocket_; }; #endif
#ifndef __PlayerObject_H__ #define __PlayerObject_H__ const float PLAYER_DEFAULT_FORWARD_SPEED = 20.0f; const float PLAYER_DEFAULT_BACKWARD_SPEED = -10.0f; const float PLAYER_DEFAULT_UP_SPEED = 30.0f; const int PLAYER_DEFAULT_HEALTH = 100; const unsigned int PLAYER_DEFAULT_NUMBER_PROJECTILES = 20; const int PLAYER_COLLISION_DAMAGE = 5; class Projectile; class PlayerObject : public LivingObject { protected: Pool<Projectile> m_poolProjectiles; Sound* m_playerHurtSound; Sound* m_playerFireSound; public: PlayerObject(int maxHealth,Scene* pScene, std::string name, Vector3 pos, Vector3 rot, Vector3 scale, Mesh* pMesh, ShaderProgram* pShader, GLuint texture); virtual ~PlayerObject(); virtual void Update(double TimePassed); bool HandleInput(InputEvent& aInputevent, double aDelta); virtual void ApplyDamage(int damage); void FireProjectile(); void Reset(); }; #endif //__PlayerObject_H__
#pragma once #include <DirectXCollision.h> #include <vector> namespace GraphicsEngine { class Ray { public: Ray(DirectX::FXMVECTOR origin, DirectX::FXMVECTOR direction); Ray(const DirectX::XMFLOAT3& origin, const DirectX::XMFLOAT3& direction); template<typename VertexType, typename IndexType> bool IntersectsTriangleMesh(const std::vector<VertexType>& vertices, const std::vector<IndexType>& indices, float& distance) { using namespace DirectX; // For each triangle: for(size_t i = 0; i < indices.size(); i += 3) { auto v0 = XMLoadFloat3(&vertices[indices[i + 0]].Position); auto v1 = XMLoadFloat3(&vertices[indices[i + 1]].Position); auto v2 = XMLoadFloat3(&vertices[indices[i + 2]].Position); // Test if (TriangleTests::Intersects(m_origin, m_direction, v0, v1, v2, distance)) return true; } return false; } DirectX::XMVECTOR CalculatePoint(float distance) const; private: DirectX::XMVECTOR m_origin; DirectX::XMVECTOR m_direction; }; }
#include "lib_oc.h" #include <algorithm> #include <fstream> #include <random> #include <cmath> #define _USE_MATH_DEFINES double magnitude_vector(const std::vector<double> vector) { double res = 0.0; for(auto v: vector) { res += pow(v,2); } return sqrt(res); } double sigmoid(const double x) { return 1.0/(1.0+exp(-x)); } Features::Features(const std::array<double, 8> &_hist, const double _circularity, const double _roundness, const double _aspect_ratio, const double _solidity) { hist = _hist; circularity = _circularity; roundness = _roundness; aspect_ratio = _aspect_ratio; solidity = _solidity; } Features::Features(const std::vector<cv::Point>& contour) { std::vector<unsigned char> chaincode = chain(contour); std::fill(std::begin(hist), std::end(hist), 0); for (auto vec : chaincode) { hist[vec]++; } if(chaincode.size() > 0) { for(size_t i = 0; i < hist.size(); i++) { hist[i] /= chaincode.size(); } } std::vector<cv::Point> hull; cv::convexHull(contour, hull); auto rbb = cv::fitEllipse(contour); double area = cv::contourArea(contour), perimeter = cv::arcLength(contour, true), major_axis = std::max(rbb.size.width, rbb.size.height), minor_axis = std::min(rbb.size.width, rbb.size.height); circularity = (4.0*M_PI*area)/pow(perimeter, 2); roundness = (4.0*area)/(M_PI*pow(major_axis,2)); aspect_ratio = major_axis / minor_axis; solidity = area / cv::contourArea(hull); } double Features::distance(const Features& other, const unsigned int d) const { auto array0 = get_features(), array1 = other.get_features(); double distance = 0; //Chebyshev distance if(d == 0) { double max = 0; for(size_t i = 0; i < array0.size(); i++) { double t = fabs(array0[i] - array1[i]); if(t < max) { max = t; } } distance = max; } else { double sum = 0.0; for(size_t i = 0; i < array0.size(); i++) { sum += pow(array0[i] - array1[i], d); } distance = pow(sum, 1.0/d); } return distance; } std::vector<double> Features::get_features() const { std::vector<double> res; res.push_back(1.0); for(auto h: hist) { res.push_back(h); } res.push_back(circularity); res.push_back(roundness); res.push_back(aspect_ratio); res.push_back(solidity); return res; } std::array<double, 8> Features::get_histogram() const { return hist; } double Features::get_circularity() const { return circularity; } double Features::get_roundness() const { return roundness; } double Features::get_aspect_ratio() const { return aspect_ratio; } double Features::get_solidity() const { return solidity; } std::ostream& operator<<(std::ostream &strm, const Features &o) { strm << "{'circularity':"<<o.circularity<<",'roundness':"<<o.roundness<< ",'aspect_ratio':"<<o.aspect_ratio<<",'solidity':"<<o.solidity<<",'h':["; for(size_t i = 0; i < o.hist.size(); ++i) { strm << std::fixed << std:: setprecision(2) << o.hist[i]; if (i != o.hist.size() - 1) { strm << ", "; } } strm << "]}"; return strm; } ML& ML::load(const std::string& path) { std::ifstream i(path); json j; i >> j; std::string model = j["model"]; if(model.compare("lr") == 0) { return LR::load(j); } else { return KNN::load(j); } } KNN::KNN(const unsigned int _k, const unsigned int _d) { k = _k; d = _d; } KNN::KNN(const unsigned int _k, const unsigned int _d, const std::vector<std::pair<std::string, Features>> &_instances){ k = _k; d = _d; instances = _instances; } void KNN::learn(const std::vector<std::pair<std::string, Features>> &inst) { for(auto i: inst) { instances.push_back(i); } } std::ostream& operator<<(std::ostream &strm, const KNN &o) { strm << "KNN: {'k':"<<o.k<<", 'd':"<<o.d<<", instances:['"<<std::endl; for(size_t i = 0; i < o.instances.size() - 1; i++) { strm << "{'label':"<<o.instances[i].first<<",'features':"<<o.instances[i].second<<"},"<<std::endl; } strm << "{'label':"<<o.instances[o.instances.size() - 1].first<<",'features':"<<o.instances[o.instances.size() - 1].second<<"}"<<std::endl; strm << "]}"; return strm; } std::string most_frequent(const std::vector<std::string> &votes) { // Insert all elements in hash. std::unordered_map<std::string, unsigned int> hash; for (size_t i = 0; i < votes.size(); i++) { hash[votes[i]]++; } // find the max frequency unsigned int max_count = 0; std::string rv = votes[0]; for (auto i : hash) { if (max_count < i.second) { rv = i.first; max_count = i.second; } } return rv; } std::string KNN::predict(const Object &object) const { std::vector<std::string> votes; std::vector<std::pair<double, std::string>> distances; auto feature = Features(object.get_contour()); for(unsigned int i = 0; i < instances.size(); i++){ distances.push_back(std::pair(feature.distance(instances[i].second, d), instances[i].first)); } sort(distances.begin(), distances.end()); for(unsigned int i = 0; i < k; i++) { votes.push_back(distances[i].second); } return most_frequent(votes); } void KNN::store(const std::string &path) const { json j; j["model"] = "knn"; j["k"] = k; j["d"] = d; json inst; for(auto i: instances) { json instance; instance["label"] = i.first; instance["circularity"] = i.second.get_circularity(); instance["roundness"] = i.second.get_roundness(); instance["aspect_ratio"] = i.second.get_aspect_ratio(); instance["solidity"] = i.second.get_solidity(); json histogram; for(auto h: i.second.get_histogram()) { histogram.push_back(h); } instance["histogram"] = histogram; inst.push_back(instance); } j["instances"] = inst; std::ofstream o(path); o << std::setw(2) << j << std::endl; } KNN& KNN::load(const json& j) { std::vector<std::pair<std::string, Features>> instances; for(auto i: j["instances"]) { std::array<double, 8> hist; double circularity = i["circularity"]; double roundness = i["roundness"]; double aspect_ratio = i["aspect_ratio"]; double solidity = i["solidity"]; for(size_t k = 0; k < i["histogram"].size(); k++) { hist[k] = i["histogram"][k]; } auto features = Features(hist, circularity, roundness, aspect_ratio, solidity); instances.push_back(std::pair(i["label"], features)); } static KNN knn = KNN(j["k"], j["d"], instances); return knn; } LR::LR() { } LR::LR(const std::vector<double> _parameters){ parameters = _parameters; } std::ostream& operator<<(std::ostream &strm, const LR &o) { strm << "LR: {'weights':["; for(size_t i = 0; i < o.parameters.size() - 1; i++) { strm << o.parameters[i] <<", "; } strm << o.parameters[o.parameters.size() - 1]; strm << "]}"; return strm; } std::vector<double> compute_gradient(const std::vector<double> &parameters, const std::vector<std::vector<double>> &features, const std::vector<double> &labels, const size_t m, const double beta) { std::vector<double> predictions, errors; for(size_t i = 0; i < features.size(); i++) { // compute the prediction double p = 0.0; for(unsigned int j = 0; j < parameters.size(); j++) { p += features[i][j] * parameters[j]; } double pred = sigmoid(p); predictions.push_back(pred); // compute the error errors.push_back(pred - labels[i]); } // init the gradient std::vector<double> gradient; for(unsigned int i = 0; i < m; i++) { gradient.push_back(0); } // compute the gradient for(unsigned int i = 0; i < m; i++) { for(unsigned int j = 0; j < errors.size(); j++) { gradient[i] += errors[j] * features[j][i]; } gradient[i] = (gradient[i]/m) + (beta/m)*gradient[i]; } return gradient; } void LR::learn(const std::vector<std::pair<std::string, Features>> &inst) { std::vector<double> labels; std::vector<std::vector<double>> features; for(size_t i = 0; i < inst.size(); i++) { if (inst[i].first.compare("bad") == 0) { labels.push_back(0); } else { labels.push_back(1); } auto feature = inst[i].second.get_features(); features.push_back(feature); } size_t m = features[0].size(); std::vector<double> m_t, v_t, m_cap, v_cap; for(unsigned int i = 0; i < m; i++) { parameters.push_back(0); m_t.push_back(0); v_t.push_back(0); m_cap.push_back(0); v_cap.push_back(0); } const double alpha=0.01, beta=0.1, eps=1e-8, beta1=0.9, beta2=0.999; double magnitude = 1.0; size_t it = 0; while(magnitude > 0.001) { it++; std::vector gradient = compute_gradient(parameters, features, labels, m, beta); for(size_t i = 0; i < gradient.size(); i++) { m_t[i] = beta1 * m_t[i] + (1.0 - beta1) * gradient[i]; v_t[i] = beta2 * v_t[i] + (1.0 - beta2) * pow(gradient[i], 2); m_cap[i] = m_t[i] / (1.0 - pow(beta1, it)); v_cap[i] = v_t[i] / (1.0 - pow(beta2, it)); } for(size_t i = 0; i < parameters.size(); i++) { parameters[i] = parameters[i] - ((alpha * m_cap[i])/(sqrt(v_cap[i]) + eps)); //parameters[i] = parameters[i] - (alpha * gradient[i]); } magnitude = magnitude_vector(gradient); } } std::string LR::predict(const Object &object) const { auto features = Features(object.get_contour()).get_features(); double p = 0.0; for(unsigned int j = 0; j < parameters.size(); j++) { p += features[j] * parameters[j]; } double pred = sigmoid(p); if(pred > 0.5) { pred = 1.0; } else { pred = 0.0; } if(pred == 0.0) { return "bad"; } else { return "good"; } } void LR::store(const std::string &path) const { json j; json jpar; for(auto p: parameters) { jpar.push_back(p); } j["model"] = "lr"; j["parameters"] = jpar; std::ofstream o(path); o << std::setw(2) << j << std::endl; } LR& LR::load(const json& j) { std::vector<double> parameters; for(auto p: j["parameters"]) { parameters.push_back(p); } static LR lr = LR(parameters); return lr; }
#ifndef PIEZA_H #define PIEZA_H #include <string> #include <sstream> #include <graphics.h> //Para determinar una pieza se necesitan solo dos numero enteros que sean de 1 a 6, y van a ser guardados en idColor y en idFigura. //La variable auxColor es la que le da el color a la figura y se define automaticamente segun el valor de idColor. using namespace std; class Pieza { private: int idColor, idFigura, auxColor; string color; public: Pieza(); Pieza(int, int); //Recibe los parametros idColor y idFigura, tambien llama el metodo setColor. int getFigura(); void setColor(); //Define auxColor. string getColor(); int getIdColor(); int getAux(); void DibujarPieza(int, int); //Recibe dos coordenadas, X y Y, y llama un metodo de figura segun sea su idFigura. //Los siguientes metodos dibujan la figura que esta escrita en su titulo del metodo, y reciben dos enteros que definen la posicion de la figura. void Cuadrado(int, int); void Circulo(int, int); void Equis(int, int); void Trebol(int, int); void Estrella(int, int); void Rombo(int, int); string toString(); }; #endif
// This file has been generated by Py++. #ifndef ScrolledItemListBase_hpp__pyplusplus_wrapper #define ScrolledItemListBase_hpp__pyplusplus_wrapper void register_ScrolledItemListBase_class(); #endif//ScrolledItemListBase_hpp__pyplusplus_wrapper
/** * @file NfcEmuFileDevice.cpp * @author Lukas Schuller * @date Thu Oct 24 09:37:08 2013 * * @brief * */ #include "NfcEmuFileDevice.h" #include "Util.h" #include <vector> #include "Debug.h" using namespace std; using namespace boost::asio; namespace NfcEmu { FileDevice::FileDevice(boost::asio::io_service & io, boost::filesystem::path const & inFilename, boost::filesystem::path const & outFilename) : Device(io) { Open(inFilename, outFilename); } FileDevice::~FileDevice() { Close(); } bool FileDevice::Open(boost::filesystem::path const & inFilename, boost::filesystem::path const & outFilename) { inFile.open(inFilename.native()); if(inFile.bad()) { Error("Failed to open input file"); return false; } outFile.open(outFilename.native()); if(outFile.bad()) { Error("Failed to open output file"); return false; } string line; getline(inFile, line); while(inFile.good()) { getline(inFile, line); cout << line << endl; auto v = Util::DecodeHex(line); copy(v.begin(), v.end(), back_inserter(mFileBuf)); } inFile.close(); return true; } bool FileDevice::Close() { outFile.close(); return true; } size_t FileDevice::Read(boost::asio::mutable_buffer buf) { auto pBuf = boost::asio::buffer_cast<unsigned char*>(buf); size_t n = std::min(boost::asio::buffer_size(buf), mFileBuf.size()); copy_n(mFileBuf.begin(), n, pBuf); for(size_t i = 0; i < n; ++i) mFileBuf.pop_front(); return n; } void FileDevice::StartAsyncRead() { vector<unsigned char> readBuf; readBuf.resize(1<<7); readBuf.resize(Read(boost::asio::buffer(readBuf))); copy(readBuf.begin(), readBuf.end(), back_inserter(mPacketBuf)); mIoService.dispatch(std::bind(&FileDevice::OnRx, this)); } void FileDevice::Write(boost::asio::const_buffer buf) { auto pBuf = boost::asio::buffer_cast<unsigned char const*>(buf); size_t len = boost::asio::buffer_size(buf); if(inFile.bad()) throw Exception("Error in file write"); outFile << std::hex; std::copy(pBuf, pBuf+len, std::ostream_iterator<int>(outFile, " ")); outFile << std::endl; } void FileDevice::Accept(DeviceVisitor & visitor) { visitor.Visit(*this); } }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Fixed.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: eyohn <sopka13@mail.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/26 12:07:55 by eyohn #+# #+# */ /* Updated: 2021/06/27 01:07:39 by eyohn ### ########.fr */ /* */ /* ************************************************************************** */ #pragma once #ifndef _FIXED_H_ #define _FIXED_H_ #include <iostream> #include <cmath> class Fixed { int fixed_point_value; static const int s_number_of_fract = 8; public: Fixed(); //default constructor Fixed(const int new_fixed_point_value); //constructor with int value Fixed(const float new_fixed_point_value); //constructor with float value ~Fixed(); //destructor Fixed(const Fixed &other); //copy constructor Fixed &operator = (const Fixed &fixed); //overload to the = operator int getRawBits(void) const; //return point_value void setRawBits(int const raw); //set point_value with raw float toFloat(void) const; //convert point_value to float int toInt(void) const; //convert point_value to int }; std::ostream &operator<< (std::ostream &out, const Fixed &fixed); //overload to the << operator #endif
// // Created by Administrator on 2020/7/5. // #include <vector> #include <list> using namespace std; enum class myType { _today, _tomorrow }; int main() { vector<list<int> > hello; //int x = myType::_today; //98标准是准许的,11标准是不准许的。 //myType y = 1; //98标准是准许的,11标准是不准许的。 myType z = myType::_tomorrow; //98标准不准许,11标注准许 return 0; }
#pragma once void mainpart(void);
#include<stdio.h> #include<stdlib.h> #include<limits.h> int rodCutting(int [],int); int max(int ,int); int main(void){ int arr[]={1, 5, 6, 7, 3, 16, 16}; int size=sizeof(arr)/sizeof(arr[0]); printf("%d",rodCutting(arr,size)); return 0; } int rodCutting(int price[],int n){ int val[n+1]; val[0]=0; int i,j; for(i=1;i<=n;i++){ int max_val=-1; for(j=0;j<i;j++) max_val=max(max_val,price[j]+val[i-j-1]); val[i]=max_val; } return val[n]; } int max(int a,int b){ return (a>b)?a:b; }
#ifndef __IPARSOR_H_ #define __IPARSOR_H_ #include "CommonHeader.h" class CUser; /* parsor클래스 패킷 파싱과 처리를 담당하는 클래스는 이 클래스를 상속받는다. 예) 존 클래스 */ class IParsor { public : IParsor() = default; virtual ~IParsor() = default; public: virtual void ParsingProcess(PACKET* _packet, CUser* _user) = 0; }; /* 파서클래스를 가지고 있는 클래스 세션 클래스가 이걸 가진다. 작동 방식은 존같이 파싱처리를 담당하는 클래스에 들어가면 Add한다. 스택구조로 이루어져있어서 맨 나중에 들어온것이만 처리한다. 해당 존에서 나가고 다른 존으로 들어가면 지우되, pvp존 이런거 들어가면 쌓는다. 아예 게임 종료할떄는 delete-> delete 뭐 이런식으로 진행되면 될거 같다. 현재 게임에선 필요 없는클래스인거 같지만 추후 확장성을 위해 만들어 둠. */ class IParsorHandler { private: vector<IParsor*> m_parsorBuffer; IParsor* m_parsor; public: IParsorHandler() = default; ~IParsorHandler() = default; public: void Start(void); void AddParsor(IParsor* _parsor); void DeleteParsor(void); IParsor* GetParsor(void); }; #endif // ! __IPARSOR_H_
#include <bits/stdc++.h> #define ll long long using namespace std; int main() { int t;cin>>t; for(int a=1;a<=t;a++) { string x;cin>>x; int len=x.size(); ll ara[len+2];memset(ara,0,sizeof(ara)); for(ll i=1;i<=8;i++) { cin>>x; for(ll j=1;j<len-1;j++) { ll ogo=0; if(x[j]=='\\')ogo=1; if(ogo)ara[j]+=(1ll<<(i-1)); } } cin>>x; for(ll i=1;i<len-1;i++){ cout<<(char)ara[i]; } cout<<endl; } return 0; }
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; for(int k = 1; k <= t; k++){ int n; cin >> n; int a[n][n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cin >> a[i][j]; } } int trace = 0, row = 0, col = 0; for(int i = 0; i < n; i++){ trace += a[i][i]; } bool rows[n + 1]; for(int i = 0; i < n; i++){ memset(rows, false, sizeof(rows)); for(int j = 0; j < n; j++){ rows[a[i][j]] = true; } for(int j = 1; j <= n; j++){ if(rows[j] == false){ row ++; break; } } } bool cols[n + 1]; for(int i = 0; i < n; i++){ memset(cols, false, sizeof(cols)); for(int j = 0; j < n; j++){ cols[a[j][i]] = true; } for(int j = 1; j <= n; j++){ if(cols[j] == false){ col ++; break; } } } printf("Case #%d: %d %d %d\n",k, trace, row, col); } return 0; }
#include "ClassicSearchEngine.h" #include "../PrecursorSearchModes/MassDiffAcceptor.h" #include "../PeptideSpectralMatch.h" #include "../Ms2ScanWithSpecificMass.h" #include "../CommonParameters.h" #include "../MetaMorpheusEngineResults.h" #include "../ScanWithIndexAndNotchInfo.h" #include "../GlobalVariables.h" #include "Search.h" using namespace MassSpectrometry; using namespace MzLibUtil; using namespace Proteomics; using namespace Proteomics::Fragmentation; using namespace Proteomics::ProteolyticDigestion; namespace EngineLayer { namespace ClassicSearch { ClassicSearchEngine::ClassicSearchEngine(std::vector<PeptideSpectralMatch*> &globalPsms, std::vector<Ms2ScanWithSpecificMass*> &arrayOfSortedMS2Scans, std::vector<Modification*> &variableModifications, std::vector<Modification*> &fixedModifications, std::vector<Protein*> &proteinList, MassDiffAcceptor *searchMode, CommonParameters *commonParameters, std::vector<std::string> nestedIds, int verbosityLevel) : MetaMorpheusEngine(commonParameters, nestedIds, verbosityLevel ), SearchMode(searchMode), Proteins(proteinList), FixedModifications(fixedModifications), VariableModifications(variableModifications), PeptideSpectralMatches(globalPsms), ArrayOfSortedMS2Scans(arrayOfSortedMS2Scans) { #ifdef ORIG MyScanPrecursorMasses = arrayOfSortedMS2Scans.Select([&] (std::any b){ b::PrecursorMass; })->ToArray(); #endif for ( auto b: arrayOfSortedMS2Scans ) { MyScanPrecursorMasses.push_back(b->getPrecursorMass() ) ; } } MetaMorpheusEngineResults *ClassicSearchEngine::RunSpecific() { Status("Getting ms2 scans..."); double proteinsSearched = 0; int oldPercentProgress = 0; // one lock for each MS2 scan; a scan can only be accessed by one thread at a time auto myLocks = std::vector<std::any>(PeptideSpectralMatches.size()); for (int i = 0; i < (int)myLocks.size(); i++) { myLocks[i] = std::any(); } Status("Performing classic search..."); if (!Proteins.empty()) { #ifdef ORIG //ParallelOptions *tempVar = new ParallelOptions(); //tempVar->MaxDegreeOfParallelism = commonParameters->getMaxThreadsToUsePerFile(); //Parallel::ForEach(Partitioner::Create(0, Proteins.size()), tempVar, [&] (partitionRange, loopState) { // for (int i = partitionRange::Item1; i < partitionRange::Item2; i++) #endif for (int i = 0; i < (int)Proteins.size(); i++) { // Stop loop if canceled if (GlobalVariables::getStopLoops()) { //loopState::Stop(); //return; break; } int jj=0; // digest each protein into peptides and search for each peptide in all spectra within precursor mass tolerance for (PeptideWithSetModifications *peptide : Proteins[i]->Digest(commonParameters->getDigestionParams(), const_cast<std::vector<Proteomics::Modification*>&>(FixedModifications), const_cast<std::vector<Proteomics::Modification*>&>(VariableModifications))) { std::vector<Product*> peptideTheorProducts = peptide->Fragment(commonParameters->getDissociationType(), commonParameters->getDigestionParams()->getFragmentationTerminus()); for (auto scan : GetAcceptableScans(peptide->getMonoisotopicMass(), SearchMode)) { std::vector<MatchedFragmentIon*> matchedIons = MatchFragmentIons(scan->TheScan, peptideTheorProducts, commonParameters); double thisScore = CalculatePeptideScore(scan->TheScan->getTheScan(), matchedIons, 0); bool meetsScoreCutoff = thisScore >= commonParameters->getScoreCutoff(); // this is thread-safe because even if the score improves from another thread writing to this PSM, // the lock combined with AddOrReplace method will ensure thread safety if (meetsScoreCutoff || commonParameters->getCalculateEValue()) { { // valid hit (met the cutoff score); lock the scan to prevent other threads from accessing it //std::lock_guard<std::mutex> lock(myLocks[scan->ScanIndex]); bool scoreImprovement = PeptideSpectralMatches[scan->ScanIndex] == nullptr || (thisScore - PeptideSpectralMatches[scan->ScanIndex]->getRunnerUpScore()) > -PeptideSpectralMatch::ToleranceForScoreDifferentiation; if (scoreImprovement) { if (PeptideSpectralMatches[scan->ScanIndex] == nullptr) { PeptideSpectralMatches[scan->ScanIndex] = new PeptideSpectralMatch(peptide, scan->Notch, thisScore, scan->ScanIndex, scan->TheScan, commonParameters->getDigestionParams(), matchedIons); } else { PeptideSpectralMatches[scan->ScanIndex]->AddOrReplace(peptide, thisScore, scan->Notch, commonParameters->getReportAllAmbiguity(), matchedIons); } } if (commonParameters->getCalculateEValue()) { PeptideSpectralMatches[scan->ScanIndex]->getAllScores().push_back(thisScore); } } } } jj++; } // report search progress (proteins searched so far out of total proteins in database) proteinsSearched++; auto percentProgress = static_cast<int>((proteinsSearched / Proteins.size()) * 100); if (percentProgress > oldPercentProgress) { oldPercentProgress = percentProgress; ProgressEventArgs tempVar2(percentProgress, "Performing classic search... ", const_cast<std::vector<std::string>&>(nestedIds)); ReportProgress(&tempVar2); } } } // remove peptides below the score cutoff that were stored to calculate expectation values if (commonParameters->getCalculateEValue()) { for (int i = 0; i < (int)PeptideSpectralMatches.size(); i++) { if (PeptideSpectralMatches[i] != nullptr && PeptideSpectralMatches[i]->getScore() < commonParameters->getScoreCutoff()) { PeptideSpectralMatches[i] = nullptr; } } } #ifdef ORIG for (PeptideSpectralMatch *psm : PeptideSpectralMatches.Where([&] (std::any p){ return p != nullptr; })) { psm->ResolveAllAmbiguities(); } #endif for (PeptideSpectralMatch *psm : PeptideSpectralMatches ){ if ( psm != nullptr ) { psm->ResolveAllAmbiguities(); } } return new MetaMorpheusEngineResults(this); } std::vector<ScanWithIndexAndNotchInfo*> ClassicSearchEngine::GetAcceptableScans(double peptideMonoisotopicMass, MassDiffAcceptor *searchMode) { std::vector<ScanWithIndexAndNotchInfo*> v; for (auto allowedIntervalWithNotch : searchMode->GetAllowedPrecursorMassIntervalsFromTheoreticalMass(peptideMonoisotopicMass) ) { DoubleRange *allowedInterval = allowedIntervalWithNotch->AllowedInterval; int scanIndex = GetFirstScanWithMassOverOrEqual(allowedInterval->getMinimum()); if (scanIndex < (int)ArrayOfSortedMS2Scans.size()) { auto scanMass = MyScanPrecursorMasses[scanIndex]; while (scanMass <= allowedInterval->getMaximum()) { auto scan = ArrayOfSortedMS2Scans[scanIndex]; //C# TO C++ CONVERTER TODO TASK: C++ does not have an equivalent to the C# 'yield' keyword: //yield return new ScanWithIndexAndNotchInfo(scan, allowedIntervalWithNotch->getNotch(), scanIndex); ScanWithIndexAndNotchInfo *e = new ScanWithIndexAndNotchInfo(scan, allowedIntervalWithNotch->getNotch(), scanIndex); v.push_back(e); scanIndex++; if (scanIndex == (int)ArrayOfSortedMS2Scans.size()) { break; } scanMass = MyScanPrecursorMasses[scanIndex]; } } } return v; } int ClassicSearchEngine::GetFirstScanWithMassOverOrEqual(double minimum) { //int index = Array::BinarySearch(MyScanPrecursorMasses, minimum); int index = BinarySearch(MyScanPrecursorMasses, minimum); if (index < 0) { index = ~index; } // index of the first element that is larger than value return index; } } }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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. */ #ifndef ABSTRACTCABASEDDIVISIONRULE_HPP_ #define ABSTRACTCABASEDDIVISIONRULE_HPP_ #include "CaBasedCellPopulation.hpp" #include "ChasteSerialization.hpp" #include "ClassIsAbstract.hpp" // Forward declaration prevents circular include chain template<unsigned SPACE_DIM> class CaBasedCellPopulation; /** * An abstract cell division rule for use in CA-based simulations. * * The purpose of this class is to define how cells are added to the mesh * * i.e it allows you to move cells out of the way if necessary */ template<unsigned SPACE_DIM> class AbstractCaBasedDivisionRule : public Identifiable { private: friend class boost::serialization::access; /** * Serialize the object and its member variables. * * @param archive the archive * @param version the current version of this class */ template<class Archive> void serialize(Archive & archive, const unsigned int version) { } protected: /** * Output any parameters associated with the division rule. * Currently empty since this class has no member variables. Should * be overridden by any child classes that have parameters. * * @param rParamsFile The stream of the parameter file */ virtual void OutputCellCaBasedDivisionRuleParameters(out_stream& rParamsFile); public: /** * Default constructor. */ AbstractCaBasedDivisionRule(); /** * Empty destructor. */ virtual ~AbstractCaBasedDivisionRule(); /** * Return whether there is room to divide at all. * * As this method is pure virtual, it must be overridden * in subclasses. * * @param pParentCell The cell to divide * @param rCellPopulation The CA-based cell population * @return if the site is available. */ virtual bool IsRoomToDivide(CellPtr pParentCell, CaBasedCellPopulation<SPACE_DIM>& rCellPopulation)=0; /** * Return the index for the Daughter node. * This method can be used to move cells out of the way as necessary. * * As this method is pure virtual, it must be overridden * in subclasses. * * @param pNewCell The cell to new cell * @param pParentCell The parent cell * @param rCellPopulation The CA-based cell population * @return the node index for the daughter cell. */ virtual unsigned CalculateDaughterNodeIndex(CellPtr pNewCell, CellPtr pParentCell, CaBasedCellPopulation<SPACE_DIM>& rCellPopulation)=0; /** * Output the name of the concrete class and call OutputCellCaBasedDivisionRuleParameters(). * * @param rParamsFile The stream of the parameter file */ void OutputCellCaBasedDivisionRuleInfo(out_stream& rParamsFile); }; TEMPLATED_CLASS_IS_ABSTRACT_1_UNSIGNED(AbstractCaBasedDivisionRule) #endif /*ABSTRACTCaBASEDDIVISIONRULE_HPP_*/
#include "stdafx.h" #include "WSquare.h" IMPLEMENT_SERIAL(WSquare, CObject, 1)//实现类WSquare的序列化,指定版本为1 WSquare::WSquare() { Type = (ElementType)0;//图元类型 Width = 100;//默认图形宽度为100 } WSquare::WSquare(int x, int y, int w) { Type = (ElementType)0;//图元类型 OrgX = x; OrgY = y; Width = w; } void WSquare::Draw(CDC* pDC) { //创建画笔及用来保存原画笔的指针 CPen pen, *pOldPen; pen.CreatePen(BoderType, BoderWidth, BoderColor); pOldPen = (CPen*)pDC->SelectObject(&pen); //创建刷子及用来保存原刷子的指针 CBrush brush, *pOldBrush; brush.CreateHatchBrush(FillType, FillColor); pOldBrush = (CBrush*)pDC->SelectObject(&brush); //绘制图形 pDC->Rectangle(OrgX - Width / 2, OrgY + Width / 2, OrgX + Width / 2, OrgY - Width / 2); //使用当前画笔和刷子 pDC->SelectObject(pOldPen); pDC->SelectObject(pOldBrush); } bool WSquare::IsMatched(CPoint pnt) { if (((OrgX - Width / 2) <= pnt.x) && (pnt.x <= (OrgX + Width / 2)) && ((OrgY - Width / 2) <= pnt.y) && (pnt.y <= (OrgY + Width / 2))) return true; else return false; } void WSquare::Serialize(CArchive& ar) { if (ar.IsStoring()) { //保存文件 ar << (WORD)Type; ar << OrgX << OrgY; ar << BoderColor << BoderType << BoderWidth; ar << FillColor << FillType; ar << Width; } else { //读取文件 WORD w; ar >> w; Type = (ElementType)w; ar >> OrgX >> OrgY; ar >> BoderColor >> BoderType >> BoderWidth; ar >> FillColor >> FillType; ar >> Width; } } void WSquare::SetAttribute(int nX, int nY, COLORREF nBoderColor, int nBoderType, int nBoderWidth, COLORREF nFillColor, int nFillType) { OrgX = nX; OrgY = nY; BoderColor = nBoderColor; BoderType = nBoderType; BoderWidth = nBoderWidth; FillColor = nFillColor; FillType = nFillType; } WSquare::~WSquare() { }
#include<iostream> #include<cstdio> #include<string.h> #include<algorithm> using namespace std; int gcd(int a,int b) { if(b==0) return a; else return gcd(b, a%b); } void rotate(int arr[],int n,int k) { for(int i=0;i<gcd(n,k);i++) { int s=i,ni; int temp=arr[s]; while(1) { //cout<<"here"; if(s+k<n) ni=s+k; else ni=s+k-n; int l=arr[ni]; arr[ni]=temp; temp=l; s=ni; if(s==i) break; } } } int main() { int arr[]= {1,2,3,4}; int n=sizeof(arr)/sizeof(int); int k=2; //rotate(arr,n,k); for(int i=0;i<n;i++) cout<<arr[i]<<" "; cout<<endl; cout<<f(NULL); //sort(arr,arr+3,greater<int>()); return 0; }
/************************************************************* * > File Name : P6187.cpp * > Author : Tony * > Created Time : 2020/04/24 22:36:14 * > Algorithm : greedy **************************************************************/ #include <bits/stdc++.h> using namespace std; typedef long long LL; inline LL read() { LL x = 0; LL f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 200010; int n, m; LL a[maxn], vis[maxn], ans; LL gcd(LL a, LL b) { return b == 0 ? a : gcd(b, a % b); } int main() { n = read(); m = read(); for (int i = 1; i <= n; ++i) a[i] = read(); sort(a + 1, a + 1 + n); for (int _ = 1; _ <= m; ++_) { int k = read(); ans = 0; int num = gcd(n, k); int per = n / num; if (k == 0) { for (int i = 1; i <= n; ++i) ans += a[i] * a[i]; printf("%lld\n", ans); continue; } if (vis[num]) { printf("%lld\n", vis[num]); continue; } for (int i = 1; i <= n; i += per) { for (int j = 0; j < per - 2; ++j) { ans += a[i + j] * a[i + j + 2]; } ans += a[i] * a[i + 1]; ans += a[i + per - 2] * a[i + per - 1]; } printf("%lld\n", vis[num] = ans); } return 0; }
#pragma once #include <QThread> #include <QObject> class SaveDataThread :public QThread { Q_OBJECT public: SaveDataThread(); SaveDataThread(QString &toDir, QStringList &headerList, QStringList &dataList, QObject *parent = 0); ~SaveDataThread(); virtual void run(); void setDataString(QString &toDir, QStringList &headerList, QStringList &dataList); signals: void processProgress(int maxValue, int progress); private: QStringList headerList; QStringList dataList; QString toDir; };
/*---------------------------------------------------------------- Copyright (c) 2014 Author: Jagadeesh Vasudevamurthy file: util.h -----------------------------------------------------------------*/ /*---------------------------------------------------------------- include this file for all the programs -----------------------------------------------------------------*/ #ifndef UTIL_H #define UTIL_H /*---------------------------------------------------------------- Basic include files -----------------------------------------------------------------*/ #include <iostream> #include <fstream> #include <iomanip> // std::setprecision using namespace std; #ifdef _WIN32 #include <cassert> #include <ctime> //#include "vld.h" //Comment this line, if you have NOT installed Visual leak detector #else #include <assert.h> #include <time.h> #include <math.h> //required for log2 #include <string.h> //for strlen,strcat and strcpy on linux #endif //'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead.To disable deprecation, //use _CRT_SECURE_NO_WARNINGS //To overcome above warning #ifdef _MSC_VER #pragma warning(disable: 4996) /* Disable deprecation */ #endif /*-------------------------------------------------------- class random number generator ----------------------------------------------------------*/ class Random { public: Random() { srand((unsigned)time(0)); } int get_random_number(int a = 0, int b = 10000) const { int upper_bound, lower_bound; if (a < b) { upper_bound = b - a; lower_bound = a; } else if (a >= b) { upper_bound = a - b; lower_bound = b; } return(lower_bound + rand() % upper_bound); } /* no body can copy random or equal random */ Random(const Random& x) = delete; Random& operator=(const Random& x) = delete; private: }; /*---------------------------------------------------------------- STL -----------------------------------------------------------------*/ #include <stdexcept> //Without this catch will NOT work on Linux #include <vector> #include <string> /*---------------------------------------------------------------- All external here -----------------------------------------------------------------*/ extern int Strcmp(const char* s1, const char* s2); extern void Strcpy(char* s1, const char* s2); extern void print_integer(const int& x); extern void print_integer(const int*& x); extern void print_integer(int& x); extern void print_integer(int*& x); extern int int_ascending_order(const int& c1, const int& c2); extern int int_ascending_order(int* const& c1, int* const& c2); extern int int_descending_order(const int& c1, const int& c2); extern int int_descending_order(int* const& c1, int* const& c2); extern void delete_int(int*& c); extern void delete_charstar(char*& c); extern int charcompare(const char& c1, const char& c2); extern void print_char(char& c); extern void print_string(char*& c); extern void free_string(char*& c); extern int string_descending_order(char* const& c1, char* const& c2); extern int string_ascending_order(char* const& c1, char* const& c2); #endif //EOF
/* * Mechanism.h * * Created on: 26 Apr 2013 * Author: william */ #include "pb_consts.h" #include "pb_process.h" #ifndef MECHANISM_H_ #define MECHANISM_H_ namespace Popbal { class Mechanism { public: Mechanism(); virtual ~Mechanism(); //! Add a process to the mechanism void AddProcess(Processes::Process *p); void CalculateDerivatives(double t, dvec &y, dvec &ydot) const; private: //! The list of particle processes in the mechanism Processes::ProcessPtrs mProcesses; }; } /* namespace Popbal */ #endif /* MECHANISM_H_ */
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * 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 video_sink_wayland_h #define video_sink_wayland_h #include "multimedia/mmmsgthread.h" #include "video_sink.h" #include <wayland-client.h> #include <wayland-drm-client-protocol.h> #include <scaler-client-protocol.h> #include <map> // #include "mm_surface_compat.h" #define MAX_COMMIT_BUF_COUNT 4 namespace YUNOS_MM { class WlDisplayType; class VideoSinkWayland : public VideoSink { public: VideoSinkWayland(); virtual mm_status_t setParameter(const MediaMetaSP & meta); typedef struct { struct wl_buffer *wlBuffer; MediaBufferSP mediaBuffer; } BufferMap; protected: virtual ~VideoSinkWayland(); virtual const char * name() const; private: virtual mm_status_t initCanvas(); virtual mm_status_t drawCanvas(MediaBufferSP buffer); virtual mm_status_t flushCanvas(); virtual mm_status_t uninitCanvas(); struct wl_buffer* createWlBuffer(WlDisplayType *wlDisplay, MediaBufferSP mediaBuffer); int postWlBuffer(struct wl_buffer *wlBuf, MediaBufferSP mediaBuf); // wayland callback must run inside the life cycle of VideoSinkWayland friend void frame_callback(void *data, struct wl_callback *callback, uint32_t time); friend void buffer_release_callback (void *data, struct wl_buffer *wlBuffer); private: WlDisplayType* mDisplay; Lock mLock; Condition mCond; /* usually weston may hold up to 3 wl_buffer submit from client. * one is using by composition, another one is in the wait list for next composition. * and possible the 3rd one just commited (then the one in wait list will be released/replaced soon) */ BufferMap mWlBufMediaBufMap[MAX_COMMIT_BUF_COUNT]; std::map<uint32_t, void*> mDrmWlBufMap; // debug use only uint32_t mInBufferCount; uint32_t mPostBufferCount; };//VideoSinkWayland }// end of namespace YUNOS_MM #endif//video_sink_wayland_h
/* ****************************************************************** * *** Este programa simula uma rede de polímeros. *** * *** *** * ****** ****** * *** Referencia base: Arquivo-fonte sim.cpp fornecido *** * *** por Ronaldo Junio e fornecido por Vitor Barbante *** * *** Pereira Leite. *** * ****** ****** * *** Ultima revisao em: *** * *** Desenvolvedor: Tiago Tambonis *** * *** email: tambonis@yahoo.com.br *** * *** msn e ymessenger: ttambonis@hotmail.com *** * ****** ****** * *** ARQUIVOS DE ENTRADA E SAIDA MENCIONADOS NO PROGRAMA: *** * *** parametros.dat -> Paramentros de entrada *** * *** caixamc.dat-> rede gerada com a persistência indicada *** * *** *** * *** redesimulada.dat-> Arq de saida com a rede simulada final *** * *** *** * *** OS ARQUIVOS DE LEITURA E SAIDA DEVEM ESTAR NO *** * *** DIRETORIO CORRENTE *** * ****************************************************************** * * Este programa e software livre; voce pode redistribui-lo e/ou * * * modifica-lo sob os termos da Licenca Publica Geral GNU, con- * * * forme publicada pela Free Software Foundation tanto a versao 2 * * * da Licenca como qualquer versao mais nova. * * * * * * Este programa e distribuido na expectativa de ser util, mas * * * SEM QUALQUER GARANTIA, sem mesmo a garantia implicita de * * * COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM * * * PARTICULAR. Consulte a Licenca Publica Geral GNU para obter * * * mais detalhes. * * * * * * Voce deve ter recebido uma copia da Licenca Publica Geral GNU * * * junto com este programa; se nao, escreva para a Free Software * * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * * * 02111-1307, USA. * * ****************************************************************** * * *** * *****************************************************************/ #include <iostream> // Fluxo de I/O por monitor, teclado... #include <fstream> /* i/ofstream | fstream é um manipulador de fluxos de dados de arquivos de computador especializado para o tipo de dado nativo char. Ele permite ler e escrever em modo de texto (utiliza-se os operadores de deslocamento de bits, << e >>) ou binário (utiliza-se os métodos read e write para buffers de dado). Fluxo de Arquivos*/ //#include <cmath> #include <cmath> #include <stdlib.h> #include "MersenneTwister.h" // members of class TRandomMersenne #include <cstdlib> using namespace std; //Atenção com o controle da variável bead. class simulacaopolimero : private MTRand { private: static const short int kxrede=100, kyrede=100, kzrede=100, seed=1234; //rede short int xrec[100][2668],yrec[100][2668],zrec[100][2668],caixa[kxrede][kyrede][kzrede]; short int ncadeias,cadeia,mono,torsoes,eg,x[100], y[100], z[100], xt[100], yt[100], zt[100]; short int sorteiocadeia[100], maxligacoes; int ncorridas,ncorridastotal; float beads, A, energia_cadeia[100],temperatura,aresta, txreptation; double energia_velha, energia_nova; bool xestouro, yestouro, zestouro, xdirecao, ydirecao,zdirecao; public: simulacaopolimero(int seed=2697) : MTRand(seed){}; ~simulacaopolimero(){}; double randon() { return (MTRand::rand()); }; void recuperacadeias(), zeracaixa(), limpatela(), zerapolimero(); void zera_sorteio_cadeia(),imprime(); void recupera_parametros_sim(), sobreposicao(), transformacao(); void destransformacao(short int[], short int[], short int[]); void calc_ligacoes (short int[], short int[], short int[], int[]); void calc_ligacoes_totais(int [], int[]); void zera_ligacoes_totais(int[]); int inicializa_simulacao(),corridas(),metropolis(), vol_exluido(); int passacadeia(); int end_move (short int, short int[], short int[], short int[], bool); int corner_move (short int, short int[], short int[], short int[], bool); int reptation_move(short int, short int[], short int[], short int[]); int crankshaft_move (short int, short int[], short int[], short int[],bool); double calc_energia_torsoes (short int[], short int[], short int[]); double calc_energia_vizinhos (void); }; int main() { simulacaopolimero simulacao; simulacao.corridas(); return 0; } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: Gerenciar as corridas e obter dados apropriados. ** Modificacoes: ** OK. *********************************************************************/ int simulacaopolimero::corridas() { /*O número máximo de ligacoes pi é definido no escopo de declaração acima. * Número máximo de monomeros 100, 0 a 99. * * Aresta máxima 0 79 -> 80. */ this->recupera_parametros_sim(); //recupera os parametros da simulação this->inicializa_simulacao(); return(0); } /********************************************************************* ** ** Autor: Tiago Tambonis. ** Propositos: gerenciar passos adequados. ** Modificacoes: muitas... ** *********************************************************************/ int simulacaopolimero::inicializa_simulacao() { //beads=40, cuidado com isso. //ncadeias fica setado a partir da rotina recuperacadeias(); static short int xtent[100], ytent[100], ztent[100]; bool flag_end=1, flag_metropolis,flag_corner, flag_crankshaft=1; bool executado, flag_transf, flag_reptation; short int scadeia; int t,cont, ligacoes[maxligacoes], ligacoestotais[maxligacoes]; float k; MTRand mtrand1; //declaração MersenneTwister.h. mtrand1.seed(seed); //semente. ofstream ienergia; ienergia.open("energias.dat"); t=0; /* flags: * 0: aceito; * 1: recusado. */ this -> recuperacadeias(); /*recuperar as cadeias do arquivo caixamc.dat geradas pelo gcadeia.cpp.*/ imprime(); //imprime a cadeia gerada pelo gcadeia.cpp. zera_ligacoes_totais(ligacoestotais); /*zera o vetor que armazena o numero total de ligações * torsões*/ for (cadeia=0;cadeia<=(ncadeias-1);cadeia++) /* cálculo da energia antiga e das ligações iniciais*/ { flag_transf=this->passacadeia(); //passa a cadeia setada no for. if (flag_transf!=0) this->transformacao(); calc_ligacoes(x,y,z,ligacoes); calc_ligacoes_totais(ligacoes,ligacoestotais); energia_velha = energia_velha + this->calc_energia_torsoes(x,y,z); if (flag_transf!=0) this->destransformacao(x,y,z); energia_velha = energia_velha - this->calc_energia_vizinhos(); } cout<<"Energia inicial: "<<energia_velha<<endl; cout<<"Ligações totais iniciais: "<<endl; for (short int a=0;a<=maxligacoes;a++) { cout<<a<<" "<<ligacoestotais[a]<<endl; } cout<<"Operando..."<<endl; ienergia<<t<<" "<<energia_velha<<endl; getchar(); cont=10000; cout<<endl; for (ncorridas=1;ncorridas<=ncorridastotal;ncorridas++) { if (ncorridas%cont==1) { cout<<"Corrida "<<ncorridas<<endl; cont=cont+10000; imprime(); } zera_sorteio_cadeia(); for (short int controlador_cadeia=0; controlador_cadeia<=(ncadeias-1); controlador_cadeia++) { start: scadeia=mtrand1.randInt(ncadeias-1); if (sorteiocadeia[scadeia]==1) goto start; else /*cadeia ainda não utilizada, é possível então realizar os movimentos nesta cadeia. */ { sorteiocadeia[scadeia]=1; executado=0; mono=mtrand1.randInt(beads-1); //---------------------------------------------------------------------- //End move if (mono==0 || mono==(beads-1)) { k = this->randon(); if (k>=txreptation) //end move. { executado=1; cadeia=scadeia; flag_transf=this->passacadeia(); //passando a cadeia sorteada para a x,y,z da rotina end_move. if (flag_transf!=0) this->transformacao(); flag_end=this->end_move(mono,xtent,ytent,ztent,flag_transf); if (!flag_end)//movimento aceito. { for (short int a=0;a<=(beads-1);++a) { xt[a]=xrec[scadeia][a]; yt[a]=yrec[scadeia][a]; zt[a]=zrec[scadeia][a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=0; //desocupo as posições que a cadeia antiga ocupava na caixa temporariamente. } for (short int a=0;a<=(beads-1);++a) { xrec[scadeia][a]=xtent[a]; yrec[scadeia][a]=ytent[a]; zrec[scadeia][a]=ztent[a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=1; //ocupo as posições que a cadeia nova ocupará na caixa. } energia_nova=0.0; for (cadeia=0;cadeia<=(ncadeias-1);cadeia++) //cálculo da energia nova. { flag_transf=this->passacadeia(); if (flag_transf!=0) this->transformacao(); energia_nova = energia_nova + this->calc_energia_torsoes(x,y,z); if (flag_transf!=0) this -> destransformacao(x,y,z); energia_nova = energia_nova - this->calc_energia_vizinhos(); } flag_metropolis=this->metropolis(); if (!flag_metropolis) //aceito a energia e a caixa permanece como está após a modificação da inserção da nova cadeia. { energia_velha=energia_nova; t=t+1; ienergia<<t<<" "<<energia_nova<<endl; } else { energia_nova=energia_velha; t=t+1; ienergia<<t<<" "<<energia_nova<<endl; for (short int a=0;a<=(beads-1);++a) // retornando a configuração da cadeia antiga. { caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=0; //desocupo as posições que a cadeia nova ocupava na caixa. } for (short int a=0;a<=(beads-1);++a) { xrec[scadeia][a]=xt[a]; yrec[scadeia][a]=yt[a]; zrec[scadeia][a]=zt[a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=1;//ocupo as posições que a cadeia antiga ocupava na caixa. } } } } //fim do end move if (k<txreptation) //reptation. { executado=1; cadeia=scadeia; flag_transf=this->passacadeia(); //passando a cadeia sorteada para a x,y,z da rotina end_move. if (flag_transf!=0) this->transformacao(); flag_reptation=this->reptation_move(mono,xtent,ytent,ztent); if (!flag_reptation)//movimento aceito. { getchar(); for (short int a=0;a<=(beads-1);++a) { xt[a]=xrec[scadeia][a]; yt[a]=yrec[scadeia][a]; zt[a]=zrec[scadeia][a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=0; //desocupo as posições que a cadeia antiga ocupava na caixa temporariamente. } for (short int a=0;a<=(beads-1);++a) { xrec[scadeia][a]=xtent[a]; yrec[scadeia][a]=ytent[a]; zrec[scadeia][a]=ztent[a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=1; //ocupo as posições que a cadeia nova ocupará na caixa. } energia_nova=0.0; for (cadeia=0;cadeia<=(ncadeias-1);cadeia++) //cálculo da energia nova. { flag_transf=this->passacadeia(); if (flag_transf!=0) this->transformacao(); energia_nova = energia_nova + this->calc_energia_torsoes(x,y,z); if (flag_transf!=0) this -> destransformacao(x,y,z); energia_nova = energia_nova - this->calc_energia_vizinhos(); } flag_metropolis=this->metropolis(); if (!flag_metropolis) //aceito a energia e a caixa permanece como está após a modificação da inserção da nova cadeia. { energia_velha=energia_nova; t=t+1; ienergia<<t<<" "<<energia_nova<<endl; } else { energia_nova=energia_velha; t=t+1; ienergia<<t<<" "<<energia_nova<<endl; for (short int a=0;a<=(beads-1);++a) // retornando a configuração da cadeia antiga. { caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=0; //desocupo as posições que a cadeia nova ocupava na caixa. } for (short int a=0;a<=(beads-1);++a) { xrec[scadeia][a]=xt[a]; yrec[scadeia][a]=yt[a]; zrec[scadeia][a]=zt[a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=1;//ocupo as posições que a cadeia antiga ocupava na caixa. } } } } } //Fim do end move. //---------------------------------------------------------------------- //---------------------------------------------------------------------- //Corner move if (executado==0) { cadeia=scadeia; flag_transf=this->passacadeia(); /*passando a cadeia sorteada para a x,y,z da rotina end_move. */ if (flag_transf!=0) this->transformacao(); flag_corner=this->corner_move(mono,xtent,ytent,ztent,flag_transf); if (!flag_corner) //movimento aceito { executado=1; for (short int a=0;a<=(beads-1);++a) { xt[a]=xrec[scadeia][a]; yt[a]=yrec[scadeia][a]; zt[a]=zrec[scadeia][a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=0; //desocupo as posições que a cadeia antiga ocupava na caixa. } for (short int a=0;a<=(beads-1);++a) { xrec[scadeia][a]=xtent[a]; yrec[scadeia][a]=ytent[a]; zrec[scadeia][a]=ztent[a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=1; //ocupo as posições que a cadeia nova ocupará na caixa. } energia_nova=0.0; for (cadeia=0;cadeia<=(ncadeias-1);cadeia++) //cálculo da energia nova. { flag_transf=this->passacadeia(); if (flag_transf!=0) this->transformacao(); energia_nova = energia_nova + this->calc_energia_torsoes(x,y,z); if (flag_transf!=0) this -> destransformacao(x,y,z); energia_nova = energia_nova - this->calc_energia_vizinhos(); } flag_metropolis=this->metropolis(); if (!flag_metropolis) //aceito a energia e a caixa permanece como está após a modificação da inserção da nova cadeia. { energia_velha=energia_nova; t=t+1; ienergia<<t<<" "<<energia_nova<<endl; } else { energia_nova=energia_velha; t=t+1; ienergia<<t<<" "<<energia_nova<<endl; for (short int a=0;a<=(beads-1);++a) // retornando a configuração da cadeia antiga. { caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=0; //desocupo as posições que a cadeia nova ocupava na caixa. } for (short int a=0;a<=(beads-1);++a) { xrec[scadeia][a]=xt[a]; yrec[scadeia][a]=yt[a]; zrec[scadeia][a]=zt[a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=1;//ocupo as posições que a cadeia antiga ocupava na caixa. } } } } //Fim do corner move. //---------------------------------------------------------------------- //---------------------------------------------------------------------- //Crankshat move. if (executado==0) { cadeia=scadeia; flag_transf=this->passacadeia(); /*passando a cadeia sorteada para a x,y,z da rotina end_move.*/ if (flag_transf!=0) this->transformacao(); flag_crankshaft=this->crankshaft_move(mono,xtent,ytent,ztent,flag_transf); if (!flag_crankshaft) { executado=1; for (short int a=0;a<=(beads-1);++a) { xt[a]=xrec[scadeia][a]; yt[a]=yrec[scadeia][a]; zt[a]=zrec[scadeia][a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=0; //desocupo as posições que a cadeia antiga ocupava na caixa. } for (short int a=0;a<=(beads-1);++a) { xrec[scadeia][a]=xtent[a]; yrec[scadeia][a]=ytent[a]; zrec[scadeia][a]=ztent[a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=1; //ocupo as posições que a cadeia nova ocupará na caixa. } energia_nova=0.0; for (cadeia=0;cadeia<=(ncadeias-1);cadeia++) //cálculo da energia nova. { flag_transf=this->passacadeia(); if (flag_transf!=0) this->transformacao(); energia_nova = energia_nova + this->calc_energia_torsoes(x,y,z); if (flag_transf!=0) this -> destransformacao(x,y,z); energia_nova = energia_nova - this->calc_energia_vizinhos(); } flag_metropolis=this->metropolis(); if (!flag_metropolis) //aceito a energia e a caixa permanece como está após a modificação da inserção da nova cadeia. { energia_velha=energia_nova; t=t+1; ienergia<<t<<" "<<energia_nova<<endl; } else { energia_nova=energia_velha; t=t+1; ienergia<<t<<" "<<energia_nova<<endl; for (short int a=0;a<=(beads-1);++a) // retornando a configuração da cadeia antiga. { caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=0; //desocupo as posições que a cadeia nova ocupava na caixa. } for (short int a=0;a<=(beads-1);++a) { xrec[scadeia][a]=xt[a]; yrec[scadeia][a]=yt[a]; zrec[scadeia][a]=zt[a]; caixa[xrec[scadeia][a]][yrec[scadeia][a]][zrec[scadeia][a]]=1;//ocupo as posições que a cadeia antiga ocupava na caixa. } } } } }//fim do for do sorteio da cadeia. }// fim do controlador da cadeia. }// fim do for que controla o número de corridas. cout<<"Energia final: "<<energia_nova<<endl; //---------------------------------------------------------------------- //Calculo das ligações e torções. zera_ligacoes_totais(ligacoestotais); for (cadeia=0;cadeia<=(ncadeias-1);cadeia++) { flag_transf=this->passacadeia(); if (flag_transf!=0) this->transformacao(); calc_ligacoes(x,y,z,ligacoes); calc_ligacoes_totais(ligacoes,ligacoestotais); } cout<<"Ligações finais: "<<endl; for (short int a=0;a<=maxligacoes;a++) { cout<<a<<" "<<ligacoestotais[a]<<endl; } //---------------------------------------------------------------------- ienergia.close(); sobreposicao();//analisa se houve sobreposição. imprime();//imprime a última cadeia devido ao simulacao.cpp. cout<<"OK."; return 0; }// fim da função inicializa_simulacao(). /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: zerar as variaveis que guardam as coordenadas e as * posições dos monomeros das redes. ** Modificacoes: ** OK. *********************************************************************/ void simulacaopolimero::zerapolimero() { for (short int a=0;a<=(ncadeias-1);a++) { for (short int b=0;b<=(beads-1);b++) { xrec[a][b]=0.0; } } } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: Limpar a tela. ** Modificacoes: ** OK. *********************************************************************/ void simulacaopolimero::limpatela() { cout<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl; cout<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl; } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: zerar a caixa principal. ** Modificacoes: ** OK. *********************************************************************/ void simulacaopolimero::zeracaixa() { for (short int a=0;a<=(kxrede-1);a++) { for (short int b=0;b<=(kyrede-1);b++) { for (short int c=0;c<=(kzrede-1);c++) { caixa[a][b][c]=0.0; } } } } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: Recuperar a cadeia gerada no arquivo caixamc.dat, * atribuindo tais valores as matrizes caixa (que vai ser considerada * como a caixa que conterá as configurações aceitas) e a matriz caixat * que conterá a configuração de teste no critério de metrópolis. ** Modificacoes: ** OK. *********************************************************************/ void simulacaopolimero::recuperacadeias() { short int monomeros; ifstream caixamc; // cria o objeto cadeias. caixamc.open("caixamc.dat"); //abre o arquivo caixamc.dat, que deve estar no diretório corrente. ifstream parametros; // cria o objeto leitura. parametros.open("parametros.txt"); //abre o arquivo parametros.txt, que deve estar no diretório corrente. //------------------------------------------------------------------------------------------------------------------------------------ // Leitura das propriedades do polímero. parametros.width(3); parametros>>beads; //necessidade pela compilação, não sei porque. parametros.width(3); parametros>>beads; parametros.close(); //fecha o arquivo setado pelo objeto desenvolvimento. //------------------------------------------------------------------------------------------------------------------------------------- // Recuperação das cadeias geradas no arquivo caixamc.dat ncadeias=0; monomeros=0; this-> zeracaixa(); this-> zerapolimero(); while (caixamc.eof()==0.0) { caixamc.width(3); caixamc>>xrec[ncadeias][monomeros]; caixamc.width(3); caixamc>>yrec[ncadeias][monomeros]; caixamc.width(3); caixamc>>zrec[ncadeias][monomeros]; caixa[xrec[ncadeias][monomeros]][yrec[ncadeias][monomeros]][zrec[ncadeias][monomeros]]=1; monomeros++; if (beads==monomeros) /*Se a cadeia já foi preenchida com todos os beads uma nova deve-se iniciar.*/ { ncadeias++; monomeros=0; } } caixamc.close(); //Fim da recuperação das cadeias. //---------------------------------------------------------------------------------------------------------------------------------- } /********************************************************************* ** ** Autor: Ronaldo Jnio de Oliveira ** Propositos: Testar/realizar o movimento de end_move ** Modificacoes: 12/04/11, Tiago Tambonis. ** OK. *********************************************************************/ int simulacaopolimero::end_move(short int mono, short int xtent[], short int ytent[], short int ztent[],bool flag_transf) { short int aleat; aleat=(int)(this->randon()*4); if(mono==0){ //�o 1o monomero if(x[mono]==x[mono+1] && z[mono]==z[mono+1]) // esta no eixo y switch (aleat){ cout<<1; case 0: xtent[mono]=x[mono+1]+1; ytent[mono]=y[mono+1]; ztent[mono]=z[mono+1]; break; case 1: xtent[mono]=x[mono+1]-1; ytent[mono]=y[mono+1]; ztent[mono]=z[mono+1]; break; case 2: xtent[mono]=x[mono+1]; ytent[mono]=y[mono+1]; ztent[mono]=z[mono+1]+1; break; case 3: xtent[mono]=x[mono+1]; ytent[mono]=y[mono+1]; ztent[mono]=z[mono+1]-1; break; } else if(x[mono]==x[mono+1] && y[mono]==y[mono+1]) // esta no eixo z switch (aleat){ case 0: xtent[mono]=x[mono+1]+1; ytent[mono]=y[mono+1]; ztent[mono]=z[mono+1]; break; case 1: xtent[mono]=x[mono+1]-1; ytent[mono]=y[mono+1]; ztent[mono]=z[mono+1]; break; case 2: xtent[mono]=x[mono+1]; ytent[mono]=y[mono+1]+1; ztent[mono]=z[mono+1]; break; case 3: xtent[mono]=x[mono+1]; ytent[mono]=y[mono+1]-1; ztent[mono]=z[mono+1]; break; } else if(y[mono]==y[mono+1] && z[mono]==z[mono+1]) // esta no eixo x switch (aleat){cout<<3; case 0: xtent[mono]=x[mono+1]; ytent[mono]=y[mono+1]+1; ztent[mono]=z[mono+1]; break; case 1: xtent[mono]=x[mono+1]; ytent[mono]=y[mono+1]-1; ztent[mono]=z[mono+1]; break; case 2: xtent[mono]=x[mono+1]; ytent[mono]=y[mono+1]; ztent[mono]=z[mono+1]+1; break; case 3: xtent[mono]=x[mono+1]; ytent[mono]=y[mono+1]; ztent[mono]=z[mono+1]-1; break; } } else if(mono==(beads-1)){ //�o ultimo monomero if(x[mono]==x[mono-1] && z[mono]==z[mono-1]) // esta no eixo y"; switch (aleat){cout<<4; case 0: xtent[mono]=x[mono-1]+1; ytent[mono]=y[mono-1]; ztent[mono]=z[mono-1]; break; case 1: xtent[mono]=x[mono-1]-1; ytent[mono]=y[mono-1]; ztent[mono]=z[mono-1]; break; case 2: xtent[mono]=x[mono-1]; ytent[mono]=y[mono-1]; ztent[mono]=z[mono-1]+1; break; case 3: xtent[mono]=x[mono-1]; ytent[mono]=y[mono-1]; ztent[mono]=z[mono-1]-1; break; } else if(x[mono]==x[mono-1] && y[mono]==y[mono-1]) // esta no eixo z"; switch (aleat){cout<<5; case 0: xtent[mono]=x[mono-1]+1; ytent[mono]=y[mono-1]; ztent[mono]=z[mono-1]; break; case 1: xtent[mono]=x[mono-1]-1; ytent[mono]=y[mono-1]; ztent[mono]=z[mono-1]; break; case 2: xtent[mono]=x[mono-1]; ytent[mono]=y[mono-1]+1; ztent[mono]=z[mono-1]; break; case 3: xtent[mono]=x[mono-1]; ytent[mono]=y[mono-1]-1; ztent[mono]=z[mono-1]; break; } else if(y[mono]==y[mono-1] && z[mono]==z[mono-1]) // esta no eixo x"; switch (aleat){cout<<6; case 0: xtent[mono]=x[mono-1]; ytent[mono]=y[mono-1]+1; ztent[mono]=z[mono-1]; break; case 1: xtent[mono]=x[mono-1]; ytent[mono]=y[mono-1]-1; ztent[mono]=z[mono-1]; break; case 2: xtent[mono]=x[mono-1]; ytent[mono]=y[mono-1]; ztent[mono]=z[mono-1]+1; break; case 3: xtent[mono]=x[mono-1]; ytent[mono]=y[mono-1]; ztent[mono]=z[mono-1]-1; break; } } else { cout << "\nTemos Problemas, end move"; getchar(); } if (flag_transf!=0 ) { if ( xtent[mono]>(aresta-1) ) xtent[mono] = xtent[mono] - aresta; if ( xtent[mono]<0 ) xtent[mono] = xtent[mono] + aresta; if ( ytent[mono]>(aresta-1) ) ytent[mono] = ytent[mono] - aresta; if ( ytent[mono]<0 ) ytent[mono] = ytent[mono] + aresta; if ( ztent[mono]>(aresta-1) ) ztent[mono] = ztent[mono] - aresta; if ( ztent[mono]<0 ) ztent[mono] = ztent[mono] + aresta; } if(!caixa[xtent[mono]][ytent[mono]][ztent[mono]]) //movimento possivel { for (int i=0; i<=(beads-1); ++i) { if(i!=mono) { xtent[i]=x[i]; ytent[i]=y[i]; ztent[i]=z[i]; } } if (flag_transf!=0 ) { for (short int a=0;a<=(beads-1);a++) if (a!=mono) { if ( xtent[a]>(aresta-1) ) xtent[a] = xtent[a] - aresta; if ( xtent[a]<0 ) xtent[a] = xtent[a] + aresta; if ( ytent[a]>(aresta-1) ) ytent[a] = ytent[a] - aresta; if ( ytent[a]<0 ) ytent[a] = ytent[a] + aresta; if ( ztent[a]>(aresta-1) ) ztent[a] = ztent[a] - aresta; if ( ztent[a]<0 ) ztent[a] = ztent[a] + aresta; } } return(0); } else return(1); } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: Calcular a energia das torsões. ** Modificacoes: 10/04/11 ** OK. *********************************************************************/ double simulacaopolimero::calc_energia_torsoes (short int xlin[], short int ylin[], short int zlin[]) { double energia; torsoes=0; // é necessário zerar a var. "torsoes" por cadeia pois ela calculará o n.º torções por cadeia. for (short int a=0;a<=(beads-1);a++) { if (a>=3) { if (xlin[a]==xlin[a-1]) // eixo x { if ( (ylin[a]==ylin[a-1]) && (ylin[a]!=ylin[a-2]) ) { torsoes=torsoes+1; } // posso usar else futuramente para calcular o número de ligações pi. if ( (zlin[a]==zlin[a-1]) && (zlin[a]!=zlin[a-2]) ) { torsoes=torsoes+1; } } if (ylin[a]==ylin[a-1]) // eixo y { if ( (zlin[a]==zlin[a-1]) && (zlin[a]!=zlin[a-2]) ) { torsoes=torsoes+1; } if ( (xlin[a]==xlin[a-1]) && xlin[a]!=xlin[a-2] ) { torsoes=torsoes+1; } } if (zlin[a]==zlin[a-1]) // eixo z { if ( (ylin[a]==ylin[a-1]) && (ylin[a]!=ylin[a-2]) ) { torsoes=torsoes+1; } if ( (xlin[a]==xlin[a-1]) && (xlin[a]!=xlin[a-2]) ) { torsoes=torsoes+1; } } } } energia=eg*torsoes; return (energia); } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: Calcular a energia das torsões. ** Modificacoes: 10/04/11 ** Ok. *********************************************************************/ double simulacaopolimero::calc_energia_vizinhos() { int sv; double energia; sv = 0; for (short int a=0;a<=(beads-1);a++) { sv = sv + caixa[xrec[cadeia][a]][yrec[cadeia][a]][zrec[cadeia][a]+1] + caixa[xrec[cadeia][a]][yrec[cadeia][a]][zrec[cadeia][a]-1]+ caixa[xrec[cadeia][a]][yrec[cadeia][a]+1][zrec[cadeia][a]] + caixa[xrec[cadeia][a]][yrec[cadeia][a]-1][zrec[cadeia][a]]+ caixa[xrec[cadeia][a]+1][yrec[cadeia][a]][zrec[cadeia][a]] + caixa[xrec[cadeia][a]-1][yrec[cadeia][a]][zrec[cadeia][a]]; } energia=A*sv; return (energia); } /********************************************************************* ** ** Autor: Ronaldo Jnio de Oliveira ** Propositos: Testar/realizar o movimento de "corner". ** Modificacoes: 12/04/11, Tiago Tambonis. ** *********************************************************************/ int simulacaopolimero::corner_move(short int mono, short int xtent[], short int ytent[], short int ztent[], bool flag_transf){ short int xs, ys, zs; short int determinante = ((x[mono]*y[mono-1]*z[mono+1] + x[mono+1]*y[mono]*z[mono-1] + x[mono-1]*y[mono+1]*z[mono])- (x[mono+1]*y[mono-1]*z[mono] + x[mono]*y[mono+1]*z[mono-1] + x[mono-1]*y[mono]*z[mono+1])); if (determinante) { xs = x[mono-1] - x[mono] + x[mono+1]; ys = y[mono-1] - y[mono] + y[mono+1]; zs = z[mono-1] - z[mono] + z[mono+1]; if (flag_transf!=0) { if ( xs>(aresta-1) ) xs = xs - aresta; if ( xs<0 ) xs = xs + aresta; if ( ys>(aresta-1) ) ys = ys - aresta; if ( ys<0 ) ys = ys + aresta; if ( zs>(aresta-1) ) zs = zs - aresta; if ( zs<0 ) zs = zs + aresta; } if (!caixa[xs][ys][zs]) //movimento permitido { xtent[mono] = xs; ytent[mono] = ys; ztent[mono] = zs; for (int i=0; i<=(beads-1); ++i) if (i!=mono) { xtent[i] = x[i]; ytent[i] = y[i]; ztent[i] = z[i]; } if (flag_transf!=0) { for (short int a=0;a<=(beads-1);a++) if (a!=mono) { if ( xtent[a]>(aresta-1) ) xtent[a] = xtent[a] - aresta; if ( xtent[a]<0 ) xtent[a] = xtent[a] + aresta; if ( ytent[a]>(aresta-1) ) ytent[a] = ytent[a] - aresta; if ( ytent[a]<0 ) ytent[a] = ytent[a] + aresta; if ( ztent[a]>(aresta-1) ) ztent[a] = ztent[a] - aresta; if ( ztent[a]<0 ) ztent[a] = ztent[a] + aresta; } } return (0); } else return (1); } else { return (1); cout<<"Problemas, corner move."<<endl; getchar(); } } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: uso do critério de metropolis. ** Modificacoes: ** OK. *********************************************************************/ int simulacaopolimero::metropolis() { float delta,fb; delta=energia_nova - energia_velha; if (delta<=0.0)//aceito a nova energia. { return(0); } else { fb = exp(-delta/temperatura); if (this->randon()<=fb)//aceito a nova energia { return(0); } else { return(1); //não aceito a nova enegia. } } } /********************************************************************* ** ** Autor: Ronaldo Jnio de Oliveira ** Propositos: Testar/realizar o movimento de "crankshaft". ** Modificacoes: 12/04/11, Tiago Tambonis. ** OK. *********************************************************************/ int simulacaopolimero::crankshaft_move (short int mono, short int xtent[], short int ytent[], short int ztent[], bool flag_transf){ short int xs, ys, zs; short int determinante; // #Observacoes ao calculo do determinante // Referencia: Introducao a geometria analitica, Paulo Boulos e // Ivan Camargo, Makron Books, 1997 / Cap7, pag. 72. // // #Considerando v e u vetores e p uma grandeza angular // ||v|| ||u|| sen p = det -> u ^ v =0 <=> u//v if(mono!=0 || mono!=(beads-1)){ determinante = ((x[mono]*y[mono-1]*z[mono+1] + x[mono+1]*y[mono]*z[mono-1] + x[mono-1]*y[mono+1]*z[mono])- (x[mono+1]*y[mono-1]*z[mono] + x[mono]*y[mono+1]*z[mono-1] + x[mono-1]*y[mono]*z[mono+1])); if(determinante){ xs = x[mono-1] - x[mono] + x[mono+1]; ys = y[mono-1] - y[mono] + y[mono+1]; zs = z[mono-1] - z[mono] + z[mono+1]; if(xs==x[mono+2] && ys==y[mono+2] && zs==z[mono+2]){ //�possivel //o crankshaft move //olhar em que eixo esta [mono-1] e [mono+2] if(abs(x[mono-1]-x[mono+2])==1){ //esta no eixo x //exprimindo variacoes de y e z if(!(y[mono]-y[mono-1])) //testar eixo z if((z[mono]-z[mono-1])>0){ //z so pode diminuir ztent[mono] = z[mono]-1; ztent[mono+1] = z[mono+1]-1; xtent[mono] = x[mono-1]; xtent[mono+1] = x[mono+2]; //sorteio uma direcao para y if(this->randon()<0.5){ ytent[mono] = y[mono]+1; ytent[mono+1] = y[mono+1]+1; } else{ ytent[mono] = y[mono]-1; ytent[mono+1] = y[mono+1]-1; } } else{ //lembrando ser impossivel variacao de z=0 //z so pode aumentar ztent[mono] = z[mono]+1; ztent[mono+1] = z[mono+1]+1; xtent[mono] = x[mono-1]; xtent[mono+1] = x[mono+2]; //sorteio uma direcao para y if(this->randon()<0.5){ ytent[mono] = y[mono]+1; ytent[mono+1] = y[mono+1]+1; } else{ ytent[mono] = y[mono]-1; ytent[mono+1] = y[mono+1]-1; } } else if((y[mono]-y[mono-1])<0){ //y so pode aumentar ytent[mono] = y[mono]+1; ytent[mono+1] = y[mono+1]+1; xtent[mono] = x[mono-1]; xtent[mono+1] = x[mono+2]; //sorteio uma direcao para z if(this->randon()<0.5){ ztent[mono] = z[mono]+1; ztent[mono+1] = z[mono+1]+1; } else{ ztent[mono] = z[mono]-1; ztent[mono+1] = z[mono+1]-1; } } else if((y[mono]-y[mono-1]>0)){ //y so pode diminuir ytent[mono] = y[mono]-1; ytent[mono+1] = y[mono+1]-1; xtent[mono] = x[mono-1]; xtent[mono+1] = x[mono+2]; //sorteio uma direcao para z if(this->randon()<0.5){ ztent[mono] = z[mono]+1; ztent[mono+1] = z[mono+1]+1; } else{ ztent[mono] = z[mono]-1; ztent[mono+1] = z[mono+1]-1; } } } else if(abs(y[mono-1]-y[mono+2])==1){ //esta no eixo y //exprimindo variacoes de x e z if(!(x[mono]-x[mono-1])) //testar eixo z if((z[mono]-z[mono-1])>0){ //z so pode diminuir ztent[mono] = z[mono]-1; ztent[mono+1] = z[mono+1]-1; ytent[mono] = y[mono-1]; ytent[mono+1] = y[mono+2]; //sorteio uma direcao para x if(this->randon()<0.5){ xtent[mono] = x[mono]+1; xtent[mono+1] = x[mono+1]+1; } else{ xtent[mono] = x[mono]-1; xtent[mono+1] = x[mono+1]-1; } } else{ //z so pode aumentar ztent[mono] = z[mono]+1; ztent[mono+1] = z[mono+1]+1; ytent[mono] = y[mono-1]; ytent[mono+1] = y[mono+2]; //sorteio uma direcao para x if(this->randon()<0.5){ xtent[mono] = x[mono]+1; xtent[mono+1] = x[mono+1]+1; } else{ xtent[mono] = x[mono]-1; xtent[mono+1] = x[mono+1]-1; } } else if((x[mono]-x[mono-1])<0){ //x so pode aumentar xtent[mono] = x[mono]+1; xtent[mono+1] = x[mono+1]+1; ytent[mono] = y[mono-1]; ytent[mono+1] = y[mono+2]; //sorteio uma direcao para z if(this->randon()<0.5){ ztent[mono] = z[mono]+1; ztent[mono+1] = z[mono+1]+1; } else{ ztent[mono] = z[mono]-1; ztent[mono+1] = z[mono+1]-1; } } else if((x[mono]-x[mono-1])>0){ //x so pode diminuir xtent[mono] = x[mono]-1; xtent[mono+1] = x[mono+1]-1; ytent[mono] = y[mono-1]; ytent[mono+1] = y[mono+2]; //sorteio uma direcao para z if(this->randon()<0.5){ ztent[mono] = z[mono]+1; ztent[mono+1] = z[mono+1]+1; } else{ ztent[mono] = z[mono]-1; ztent[mono+1] = z[mono+1]-1; } } } else if (abs(z[mono-1]-z[mono+2])==1){ //esta no eixo z //exprimindo variacoes de x e y if(!(x[mono]-x[mono-1])) //devo testar no eixo y if((y[mono]-y[mono-1])>0){ //y so pode diminuir ytent[mono] = y[mono]-1; ytent[mono+1] = y[mono+1]-1; ztent[mono] = z[mono-1]; ztent[mono+1] = z[mono+2]; //sorteio uma direcao para x if(this->randon()<0.5){ xtent[mono] = x[mono]+1; xtent[mono+1] = x[mono+1]+1; } else{ xtent[mono] = x[mono]-1; xtent[mono+1] = x[mono+1]-1; } } else{ //y so pode aumentar ytent[mono] = y[mono]+1; ytent[mono+1] = y[mono+1]+1; ztent[mono] = z[mono-1]; ztent[mono+1] = z[mono+2]; //sorteio uma direcao para x if(this->randon()<0.5){ xtent[mono] = x[mono]+1; xtent[mono+1] = x[mono+1]+1; } else{ xtent[mono] = x[mono]-1; xtent[mono+1] = x[mono+1]-1; } } else if((x[mono]-x[mono-1])<0){ //x so pode aumentar xtent[mono] = x[mono]+1; xtent[mono+1] = x[mono+1]+1; ztent[mono] = z[mono-1]; ztent[mono+1] = z[mono+2]; //sorteio uma direcao para y if(this->randon()<0.5){ ytent[mono] = y[mono]+1; ytent[mono+1] = y[mono+1]+1; } else{ ytent[mono] = y[mono]-1; ytent[mono+1] = y[mono+1]-1; } } else if((x[mono]-x[mono-1])>0){ //x so pode diminuir xtent[mono] = x[mono]-1; xtent[mono+1] = x[mono+1]-1; ztent[mono] = z[mono-1]; ztent[mono+1] = z[mono+2]; //sorteio uma direcao para y if(this->randon()<0.5){ ytent[mono] = y[mono]+1; ytent[mono+1] = y[mono+1]+1; } else{ ytent[mono] = y[mono]-1; ytent[mono+1] = y[mono+1]-1; } } }//else if else cout << "\nProblemas"; //testando a nova ocupacao if (flag_transf!=0) { if ( xtent[mono]>(aresta-1) ) xtent[mono] = xtent[mono] - aresta; if ( xtent[mono]<0 ) xtent[mono] = xtent[mono] + aresta; if ( ytent[mono]>(aresta-1) ) ytent[mono] = ytent[mono] - aresta; if ( ytent[mono]<0 ) ytent[mono] = ytent[mono] + aresta; if ( ztent[mono]>(aresta-1) ) ztent[mono] = ztent[mono] - aresta; if ( ztent[mono]<0 ) ztent[mono] = ztent[mono] + aresta; if ( xtent[mono+1]>(aresta-1) ) xtent[mono+1] = xtent[mono+1] - aresta; if ( xtent[mono+1]<0 ) xtent[mono+1] = xtent[mono+1] + aresta; if ( ytent[mono+1]>(aresta-1) ) ytent[mono+1] = ytent[mono+1] - aresta; if ( ytent[mono+1]<0 ) ytent[mono+1] = ytent[mono+1] + aresta; if ( ztent[mono+1]>(aresta-1) ) ztent[mono+1] = ztent[mono+1] - aresta; if ( ztent[mono+1]<0 ) ztent[mono+1] = ztent[mono+1] + aresta; } if(!(caixa[xtent[mono]][ytent[mono]][ztent[mono]]) && !(caixa[xtent[mono+1]][ytent[mono+1]][ztent[mono+1]])){ //movimento possivel for(int i=0; i<beads; ++i) if (i!=mono && i!=(mono+1)) { xtent[i] = x[i]; ytent[i] = y[i]; ztent[i] = z[i]; } if (flag_transf!=0 ) { for (short int a=0;a<=(beads-1);a++) if (a!=mono and a!=(mono+1)) { if ( xtent[a]>(aresta-1) ) xtent[a] = xtent[a] - aresta; if ( xtent[a]<0 ) xtent[a] = xtent[a] + (aresta); if ( ytent[a]>(aresta-1) ) ytent[a] = ytent[a] - aresta; if ( ytent[a]<0 ) ytent[a] = ytent[a] + (aresta); if ( ztent[a]>(aresta-1) ) ztent[a] = ztent[a] - aresta; if ( ztent[a]<0 ) ztent[a] = ztent[a] + (aresta); } } return(0); } else return(1); }//�possivel crankshaft else return(1); }//determinante==0 else return(1); }//mono!=1 e mono!=26 else return(1); }//metodo /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: simplesmente passar os valores da cadeia indicada * pelo sorteio da cadeia e do mono para as variáveis usadas nas rotinas * do Ronaldo. ** Modificacoes: 21/02/2011. ** OK. *********************************************************************/ int simulacaopolimero::passacadeia() { xestouro=yestouro=zestouro=0; for (short int a=0;a<=(beads-1);a++) { x[a]=xrec[cadeia][a]; y[a]=yrec[cadeia][a]; z[a]=zrec[cadeia][a]; if (xestouro==0) /*se não houve estouro continua-se a verificar por estouros nas fronteiras */ { if (xrec[cadeia][a]==0 && xrec[cadeia][a+1]==(aresta-1.0)) { xdirecao=0; xestouro=1; } if (xrec[cadeia][a]==(aresta-1.0) && xrec[cadeia][a+1]==0) { xdirecao=1; xestouro=1; } } if (yestouro==0) { if (yrec[cadeia][a]==0 && yrec[cadeia][a+1]==(aresta-1.0)) { ydirecao=0; yestouro=1; } if (yrec[cadeia][a]==(aresta-1.0) && yrec[cadeia][a+1]==0) { ydirecao=1; yestouro=1; } } if (zestouro==0) { if (zrec[cadeia][a]==0 && zrec[cadeia][a+1]==(aresta-1.0)) { zdirecao=0; zestouro=1; } if (zrec[cadeia][a]==(aresta-1.0) && zrec[cadeia][a+1]==0) { zdirecao=1; zestouro=1; } } } if (xestouro==0 and yestouro==0 and zestouro==0) return (0); else return (1); } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: zerar o vetor que controlará as cadeias que podem ser * usadas no sorteio de cadeia. ** Modificacoes: ** OK. *********************************************************************/ void simulacaopolimero::zera_sorteio_cadeia() { for (short int a=0;a<=99;a++) { sorteiocadeia[a]=0; } } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: imprimir caixa principal. ** Modificacoes: ** OK. *********************************************************************/ void simulacaopolimero::imprime() { bool flag_transf; ofstream impressao; // cria o objeto impressao. impressao.open("caixasimulacao.dat"); //abre o arquivo caixasimulacao, que deve estar no diretório corrente. impressao<<"X"; impressao.width(3); impressao<<"Y"; impressao.width(3); impressao<<"Z"<<endl; for(cadeia=0; cadeia<=(ncadeias-1);cadeia++) { flag_transf=this->passacadeia(); if (flag_transf!=0) this->transformacao(); for (short int b=0;b<=(beads-1);b++) { impressao<<x[b]; impressao.width(3); impressao<<y[b]; impressao.width(3); impressao<<z[b]; impressao<<endl; } impressao<<endl<<endl<<endl; } impressao.close(); } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: recuperar as informações usadas na simulação. ** Modificacoes: ** OK. *********************************************************************/ void simulacaopolimero::recupera_parametros_sim() { float const_atracao; ifstream parametrosim; // cria o objeto paramesim. parametrosim.open("parametrosim.txt"); //abre o arquivo parametrosim.dat, que deve estar no diretório corrente. parametrosim.width(3); parametrosim>>eg; parametrosim.width(3); parametrosim>>const_atracao; parametrosim.width(3); parametrosim>>temperatura; parametrosim.width(9); parametrosim>>ncorridastotal; parametrosim.width(3); parametrosim>>aresta; parametrosim.width(3); parametrosim>>maxligacoes; parametrosim.width(3); parametrosim>>txreptation; parametrosim.close(); A=eg/const_atracao; } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: verificar a existência de sobreposições. ** Modificacoes: ** OK. *********************************************************************/ void simulacaopolimero::sobreposicao() { int posicoes[30000], c=0,d; short int x,y,z; //---------------------------------------------------------------------- //Preencher o vetor que conterá todas as coordenadas. for (short int a=0;a<=(ncadeias-1);a++) { for (short int b=0;b<=(beads-1);b++) { posicoes[c]=xrec[a][b]; c=c+1; posicoes[c]=yrec[a][b]; c=c+1; posicoes[c]=zrec[a][b]; c=c+1; } } //---------------------------------------------------------------------- //Procurar sobreposições. for(c=0;c<=((beads*ncadeias)-1);c=c+3) { x=posicoes[c]; y=posicoes[c+1]; z=posicoes[c+2]; for(d=c+3;d<=((beads*ncadeias)-1);d=d+3) { if (x==posicoes[d]) { if (y==posicoes[d+1]) { if (z==posicoes[d+2]) { cout<<x<<" "<<y<<" "<<z<<endl; cout<<"PROBLEMA DOS GRANDES!"<<endl; getchar(); } } } } } } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: adequar as coordenadas das cadeias que necessitam aos * padrões exigidos pelas rotinas dos movimentos. ** Modificacoes: ** OK. *********************************************************************/ void simulacaopolimero::transformacao(void) { float d; //---------------------------------------------------------------------- //Para as coordenadas x /* direções: * 0: esquerda; * 1: direita. */ if ( xestouro==1 ) { x[0]=xrec[cadeia][0]; for (short int a=1;a<=(beads-1);a++) { if ( abs(xrec[cadeia][a]-xrec[cadeia][a-1])!=1.0 and (xrec[cadeia][a]-xrec[cadeia][a-1])!=0) { d = (xrec[cadeia][a-1] - xrec[cadeia][a])/aresta; if (d<0) d=floor(d); if (d>0) d= ceil(d); x[a] = x[a-1] + d; } else { if ( (xrec[cadeia][a]-xrec[cadeia][a-1])==0 ) x[a]=x[a-1]; else { d = (xrec[cadeia][a] - xrec[cadeia][a-1])/aresta; if (d<0) d=floor(d); if (d>0) d= ceil(d); x[a] = x[a-1] + d; } } } } //---------------------------------------------------------------------- // Para as coordenadas y if ( yestouro==1 ) { y[0]=yrec[cadeia][0]; for (short int a=1;a<=(beads-1);a++) { if ( abs(yrec[cadeia][a]-yrec[cadeia][a-1])!=1.0 and (yrec[cadeia][a]-yrec[cadeia][a-1])!=0) { d = (yrec[cadeia][a-1] - yrec[cadeia][a])/aresta; if (d<0) d=floor(d); if (d>0) d= ceil(d); y[a] = y[a-1] + d; } else { if ( (yrec[cadeia][a]-yrec[cadeia][a-1])==0 ) y[a]=y[a-1]; else { d = (yrec[cadeia][a] - yrec[cadeia][a-1])/aresta; if (d<0) d=floor(d); if (d>0) d= ceil(d); y[a] = y[a-1] + d; } } } } //---------------------------------------------------------------------- //Para as coordenadas z if ( zestouro==1 ) { z[0]=zrec[cadeia][0]; for (short int a=1;a<=(beads-1);a++) { if ( abs(zrec[cadeia][a]-zrec[cadeia][a-1])!=1.0 and (zrec[cadeia][a]-zrec[cadeia][a-1])!=0) { d = (zrec[cadeia][a-1] - zrec[cadeia][a])/aresta; if (d<0) d=floor(d); if (d>0) d= ceil(d); z[a] = z[a-1] + d; } else { if ( (zrec[cadeia][a]-zrec[cadeia][a-1])==0 ) z[a]=z[a-1]; else { d = (zrec[cadeia][a] - zrec[cadeia][a-1])/aresta; if (d<0) d=floor(d); if (d>0) d= ceil(d); z[a] = z[a-1] + d; } } } } //---------------------------------------------------------------------- } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: verificar volume excluido. ** Modificacoes: ** OK. *********************************************************************/ int simulacaopolimero::vol_exluido() { return (0); for (short int a=0;a<=(beads-1);a++) { if (caixa[x[a]][y[a]][z[a]]!=1) { return (1); break; } } } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: adequar as coordenadas às condições de contorno. ** Modificacoes: ** OK. *********************************************************************/ void simulacaopolimero::destransformacao(short int xtent[], short int ytent[], short int ztent[]) { for (short int a=0;a<=(beads-1);a++) { if ( xtent[a]>(aresta-1) ) xtent[a] = xtent[a] - aresta; if ( xtent[a]<0 ) xtent[a] = xtent[a] + aresta; if ( ytent[a]>(aresta-1) ) ytent[a] = ytent[a] - aresta; if ( ytent[a]<0 ) ytent[a] = ytent[a] + aresta; if ( ztent[a]>(aresta-1) ) ztent[a] = ztent[a] - aresta; if ( ztent[a]<0 ) ztent[a] = ztent[a] + aresta; } } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: Calcular a energia das torsões. ** Modificacoes: ** *********************************************************************/ void simulacaopolimero::calc_ligacoes(short int xlin[], short int ylin[], short int zlin[], int ligacoes[]) { short int nligacoes, escalar; for (short int a=0;a<=maxligacoes;a++) { ligacoes[a]=0; } nligacoes=0; for (short int a=1;a<=(beads-1);a++) { escalar = ( (x[a]-x[a-1])*(x[a]-x[a+1]) + (y[a]-y[a-1])*(y[a]-y[a+1]) + (z[a]-z[a-1])*(z[a]-z[a+1]) ); if (abs(escalar)==1) nligacoes++; if (escalar==0) { if (nligacoes!=0) ligacoes[nligacoes+1]++; nligacoes=0; ligacoes[nligacoes+1]++; } } if (nligacoes!=0) ligacoes[nligacoes+1]++; } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: zerar o vetor que guardará o número total de ligações e * torções. ** Modificacoes: ** *********************************************************************/ void simulacaopolimero::zera_ligacoes_totais(int ligacoes_totais[]) { for (short int a=0;a<=maxligacoes;a++) { ligacoes_totais[a]=0; } } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: Calcular o número total de ligações e torções. ** Modificacoes: ** *********************************************************************/ void simulacaopolimero::calc_ligacoes_totais(int ligacoes[], int ligacoes_totais[]) { for (short int a=0;a<=maxligacoes;a++) { ligacoes_totais[a]=ligacoes_totais[a]+ligacoes[a]; } } /********************************************************************* ** ** Autor: Tiago Tambonis ** Propositos: Testar/realizar o movimento de "reptation". ** Modificacoes: ** *********************************************************************/ int simulacaopolimero::reptation_move (short int mono, short int xtent[], short int ytent[], short int ztent[]) { bool ocupada=0; float r; r = this->randon(); for (short int a=0;a<=(beads-1);a++) { xtent[a]=x[a]; ytent[a]=y[a]; ztent[a]=z[a]; } /* Movimento */ if (mono==0) { if ( r<=1/3.0 && ztent[mono]==ztent[mono+1] && xtent[mono]==xtent[mono+1]) //espaço para crescer y. { for (short int a=0;a<=(beads-1);a++) { ytent[a]=ytent[a]-1; } } if ( (r>1/3.0 && r<=2/3.0) && ztent[mono]==ztent[mono+1] && ytent[mono]==ytent[mono+1]) //espaço para crescer x. { for (short int a=0;a<=(beads-1);a++) { xtent[a]=xtent[a]-1; } } if ( r>2/3.0 && r<=1.0 && xtent[mono]==xtent[mono+1] && ytent[mono]==ytent[mono+1]) //espaço para crescer z. { for (short int a=0;a<=(beads-1);a++) { ztent[a]=ztent[a]-1; } } } if (mono==(beads-1)) //último monômero. { if ( r<=1/3.0 && ztent[mono]==ztent[mono-1] && xtent[mono]==xtent[mono-1]) //espaço para crescer y. { for (short int a=0;a<=(beads-1);a++) { ytent[a]=ytent[a] + 1; } } if ( (r>1/3.0 && r<=2/3.0) && ztent[mono]==ztent[mono-1] && ytent[mono]==ytent[mono-1]) //espaço para crescer x. { for (short int a=0;a<=(beads-1);a++) { xtent[a]=xtent[a] + 1; } } if ( r>2/3.0 && r<=1.0 && xtent[mono]==xtent[mono-1] && ytent[mono]==ytent[mono-1]) //espaço para crescer z. { for (short int a=0;a<=(beads-1);a++) { ztent[a]=ztent[a] + 1; } } } /*Adequação às condições periódicas de contorno*/ for (short int a=0;a<=(beads-1);a++) { if ( xtent[a]>(aresta-1) ) xtent[a] = xtent[a] - aresta; if ( xtent[a]<0 ) xtent[a] = xtent[a] + aresta; if ( ytent[a]>(aresta-1) ) ytent[a] = ytent[a] - aresta; if ( ytent[a]<0 ) ytent[a] = ytent[a] + aresta; if ( ztent[a]>(aresta-1) ) ztent[a] = ztent[a] - aresta; if ( ztent[a]<0 ) ztent[a] = ztent[a] + aresta; } for (short int a=0;a<=(beads-1);a++) { if (caixa[xtent[a]][ytent[a]][ztent[a]]==1) ocupada=1; } if (ocupada==1) return (1); else return (0); }
#ifndef CSUFFIX_H #define CSUFFIX_H #include <QString> #include <QChar> #include <QList> #include <QMap> class CSuffix { protected: QString m_key; int m_frequency; int m_count; public: CSuffix(QString ssWord); CSuffix(CSuffix&); public: //Accessors QString get_key() const {return m_key;} QString GetSuffix() const { return m_key; } int GetFrequency() { return m_frequency; } void SetFrequency(int frequency) { m_frequency = frequency; } int get_count() const { return m_count;} int increment_count() { m_count+= 1; return m_count;} }; class CPrefix { protected: QString m_key; int m_frequency; int m_count; public: CPrefix(QString ssWord); CPrefix(CPrefix&); public: //Accessors QString get_key() const { return m_key;} QString GetPrefix() const { return m_key; } int GetFrequency() { return m_frequency; } void SetFrequency(int frequency) { m_frequency = frequency; } int get_count() const { return m_count;} int increment_count() { m_count+= 1; return m_count;} }; #endif // CSUFFIX_H
// // ViewAxis.hpp // alfrid // // Created by Yi-Wen Lin on 2016/5/29. // // #ifndef ViewAxis_hpp #define ViewAxis_hpp #include <stdio.h> #include "View.hpp" using namespace alfrid; namespace alfrid { class ViewAxis : public View { public: ViewAxis(); void render(); private: void _init(); }; } #endif /* ViewAxis_hpp */
// Copyright 2020-2021 Russ 'trdwll' Treadwell <trdwll.com>. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Steam.h" #include "SteamEnums.h" #include "SteamStructs.h" #include "UObject/NoExportTypes.h" #include "SteamGameServerStats.generated.h" DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnGSStatsReceivedDelegate, ESteamResult, Result, FSteamID, SteamIDUser); DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnGSStatsStoredDelegate, ESteamResult, Result, FSteamID, SteamIDUser); DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnGSStatsUnloadedDelegate, FSteamID, SteamIDUser); /** * Functions to allow game servers to set stats and achievements on players. * https://partner.steamgames.com/doc/api/ISteamGameServerStatsStats */ UCLASS() class STEAMBRIDGE_API USteamGameServerStats final : public UObject { GENERATED_BODY() public: USteamGameServerStats(); ~USteamGameServerStats(); UFUNCTION(BlueprintPure, Category = "SteamBridgeCore", meta = (DisplayName = "Steam Game Server Stats", CompactNodeTitle = "SteamGameServerStats")) static USteamGameServerStats* GetSteamGameServerStats() { return USteamGameServerStats::StaticClass()->GetDefaultObject<USteamGameServerStats>(); } /** * Resets the unlock status of an achievement for the specified user. * This is primarily only ever used for testing. * You must have called RequestUserStats and it needs to return successfully via its callback prior to calling this! * This call only modifies Steam's in-memory state and is very cheap. To submit the stats to the server you must call StoreUserStats. * NOTE: This will work only on achievements that game servers are allowed to set. If the "Set By" field for this achievement is "Official GS" then only game servers that have been declared as officially - * controlled by you will be able to set it. To do this you must set the IP range of your official servers in the Dedicated Servers section of App Admin. * * @param FSteamID SteamIDUser - The Steam ID of the user to clear the achievement for. * @param const FString & Name - The 'API Name' of the Achievement to reset. * @return bool - This function returns true upon success if all of the following conditions are met; otherwise, false. * The specified achievement "API Name" exists in App Admin on the Steamworks website, and the changes are published. * RequestUserStats has completed and successfully returned its callback for the specified user. * The stat must be allowed to be set by game server. */ UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|GameServerStats") bool ClearUserAchievement(FSteamID SteamIDUser, const FString& Name) const { return SteamGameServerStats()->ClearUserAchievement(SteamIDUser, TCHAR_TO_UTF8(*Name)); } /** * Gets the unlock status of the Achievement. * * @param FSteamID SteamIDUser - The Steam ID of the user to get the achievement for. * @param const FString & Name - The 'API Name' of the achievement. * @param bool & bAchieved - Returns the unlock status of the achievement. * @return bool - This function returns true upon success if all of the following conditions are met; otherwise, false. * RequestUserStats has completed and successfully returned its callback. * The 'API Name' of the specified achievement exists in App Admin on the Steamworks website, and the changes are published. * If the call is successful then the unlock status is returned via the bAchieved parameter. */ UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|GameServerStats") bool GetUserAchievement(FSteamID SteamIDUser, const FString& Name, bool& bAchieved) { return SteamGameServerStats()->GetUserAchievement(SteamIDUser, TCHAR_TO_UTF8(*Name), &bAchieved); } /** * Gets the current value of the a stat for the specified user. * You must have called RequestUserStats and it needs to return successfully via its callback prior to calling this. * * @param FSteamID SteamIDUser - The Steam ID of the user to get the stat for. * @param const FString & Name - The 'API Name' of the stat. Must not be longer than k_cchStatNameMax. * @param float & Data - The variable to return the stat value into. * @return bool - This function returns true upon success if all of the following conditions are met; otherwise, false. * The specified stat exists in App Admin on the Steamworks website, and the changes are published. * RequestUserStats has completed and successfully returned its callback. * The type passed to this function must match the type listed in the App Admin panel of the Steamworks website. */ UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|GameServerStats") bool GetUserStatInt(FSteamID SteamIDUser, const FString& Name, int32& Data) { return SteamGameServerStats()->GetUserStat(SteamIDUser, TCHAR_TO_UTF8(*Name), &Data); } /** * Gets the current value of the a stat for the specified user. * You must have called RequestUserStats and it needs to return successfully via its callback prior to calling this. * * @param FSteamID SteamIDUser - The Steam ID of the user to get the stat for. * @param const FString & Name - The 'API Name' of the stat. Must not be longer than k_cchStatNameMax. * @param float & Data - The variable to return the stat value into. * @return bool - This function returns true upon success if all of the following conditions are met; otherwise, false. * The specified stat exists in App Admin on the Steamworks website, and the changes are published. * RequestUserStats has completed and successfully returned its callback. * The type passed to this function must match the type listed in the App Admin panel of the Steamworks website. */ UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|GameServerStats") bool GetUserStatFloat(FSteamID SteamIDUser, const FString& Name, float& Data) { return SteamGameServerStats()->GetUserStat(SteamIDUser, TCHAR_TO_UTF8(*Name), &Data); } // #TODO RequestUserStats /** * Unlocks an achievement for the specified user. * You must have called RequestUserStats and it needs to return successfully via its callback prior to calling this! * This call only modifies Steam's in-memory state and is very cheap. To submit the stats to the server you must call StoreUserStats. * NOTE: These updates will work only on stats that game servers are allowed to edit. If the "Set By" field for this stat is "Official GS" then only game servers that have been declared as - * officially controlled by you will be able to set it. To do this you must set the IP range of your official servers in the Dedicated Servers section of App Admin. * * @param FSteamID SteamIDUser - The Steam ID of the user to unlock the achievement for. * @param const FString & Name - The 'API Name' of the Achievement to unlock. * @return bool - This function returns true upon success if all of the following conditions are met; otherwise, false. * The specified achievement "API Name" exists in App Admin on the Steamworks website, and the changes are published. * RequestUserStats has completed and successfully returned its callback for the specified user. * The stat must be allowed to be set by game server. */ UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|GameServerStats") bool SetUserAchievement(FSteamID SteamIDUser, const FString& Name) const { return SteamGameServerStats()->SetUserAchievement(SteamIDUser, TCHAR_TO_UTF8(*Name)); } /** * Sets / updates the value of a given stat for the specified user. * You must have called RequestUserStats and it needs to return successfully via its callback prior to calling this! * This call only modifies Steam's in-memory state and is very cheap. To submit the stats to the server you must call StoreUserStats. * NOTE: These updates will work only on stats that game servers are allowed to edit. If the "Set By" field for this stat is "Official GS" then only game servers that have been declared as - * officially controlled by you will be able to set it. To do this you must set the IP range of your official servers in the Dedicated Servers section of App Admin. * * @param FSteamID SteamIDUser - The Steam ID of the user to set the stat on. * @param const FString & Name - The 'API Name' of the stat. Must not be longer than k_cchStatNameMax. * @param float Data - The new value of the stat. This must be an absolute value, it will not increment or decrement for you. * @return bool - This function returns true upon success if all of the following conditions are met; otherwise, false. * The specified stat exists in App Admin on the Steamworks website, and the changes are published. * RequestUserStats has completed and successfully returned its callback for the specified user. * The type passed to this function must match the type listed in the App Admin panel of the Steamworks website. * The stat must be allowed to be set by game server. */ UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|GameServerStats") bool SetUserStatInt(FSteamID SteamIDUser, const FString& Name, int32 Data) { return SteamGameServerStats()->SetUserStat(SteamIDUser, TCHAR_TO_UTF8(*Name), Data); } /** * Sets / updates the value of a given stat for the specified user. * You must have called RequestUserStats and it needs to return successfully via its callback prior to calling this! * This call only modifies Steam's in-memory state and is very cheap. To submit the stats to the server you must call StoreUserStats. * NOTE: These updates will work only on stats that game servers are allowed to edit. If the "Set By" field for this stat is "Official GS" then only game servers that have been declared as - * officially controlled by you will be able to set it. To do this you must set the IP range of your official servers in the Dedicated Servers section of App Admin. * * @param FSteamID SteamIDUser - The Steam ID of the user to set the stat on. * @param const FString & Name - The 'API Name' of the stat. Must not be longer than k_cchStatNameMax. * @param float Data - The new value of the stat. This must be an absolute value, it will not increment or decrement for you. * @return bool - This function returns true upon success if all of the following conditions are met; otherwise, false. * The specified stat exists in App Admin on the Steamworks website, and the changes are published. * RequestUserStats has completed and successfully returned its callback for the specified user. * The type passed to this function must match the type listed in the App Admin panel of the Steamworks website. * The stat must be allowed to be set by game server. */ UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|GameServerStats") bool SetUserStatFloat(FSteamID SteamIDUser, const FString& Name, float Data) { return SteamGameServerStats()->SetUserStat(SteamIDUser, TCHAR_TO_UTF8(*Name), Data); } // #TODO StoreUserStats /** * Updates an AVGRATE stat with new values for the specified user. * You must have called RequestUserStats and it needs to return successfully via its callback prior to calling this! * This call only modifies Steam's in-memory state and is very cheap. To submit the stats to the server you must call StoreUserStats. * NOTE: These updates will work only on stats that game servers are allowed to edit. If the "Set By" field for this stat is "Official GS" then only game servers that have been declared as - * officially controlled by you will be able to set it. To do this you must set the IP range of your official servers in the Dedicated Servers section of App Admin. * * @param FSteamID SteamIDUser - The Steam ID of the user to update the AVGRATE stat for. * @param const FString & Name - The 'API Name' of the stat. Must not be longer than k_cchStatNameMax. * @param float CountThisSession - The value accumulation since the last call to this function. * @param float SessionLength - The amount of time in seconds since the last call to this function. * @return bool - This function returns true upon success if all of the following conditions are met; otherwise, false. * The specified stat exists in App Admin on the Steamworks website, and the changes are published. * RequestUserStats has completed and successfully returned its callback for the specified user. * The type must be AVGRATE in the Steamworks Partner backend. * The stat must be allowed to be set by game server. */ UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|GameServerStats") bool UpdateUserAvgRateStat(FSteamID SteamIDUser, const FString& Name, float CountThisSession, float SessionLength) const; /** Delegates */ /** Result when getting the latests stats and achievements for a user from the server. */ UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|GameServerStats", meta = (DisplayName = "OnGSStatsReceived")) FOnGSStatsReceivedDelegate m_OnGSStatsReceived; /** Result of a request to store the user stats. */ UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|GameServerStats", meta = (DisplayName = "OnGSStatsStored")) FOnGSStatsStoredDelegate m_OnGSStatsStored; /** * Callback indicating that a user's stats have been unloaded. * Call RequestUserStats again to access stats for this user. */ UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|GameServerStats", meta = (DisplayName = "OnGSStatsUnloaded")) FOnGSStatsUnloadedDelegate m_OnGSStatsUnloaded; protected: private: STEAM_CALLBACK_MANUAL(USteamGameServerStats, OnGSStatsReceived, GSStatsReceived_t, OnGSStatsReceivedCallback); STEAM_CALLBACK_MANUAL(USteamGameServerStats, OnGSStatsStored, GSStatsStored_t, OnGSStatsStoredCallback); STEAM_CALLBACK_MANUAL(USteamGameServerStats, OnGSStatsUnloaded, GSStatsUnloaded_t, OnGSStatsUnloadedCallback); };
#include "GUIDrawer.h" #include "GUI/VisualPreferences.h" #include "GUI/SimProperties.h" #include "SceneDrawer.h" #include <GLFW/glfw3.h> #include <stdio.h> namespace solar { namespace drawers { GUIDrawer::GUIDrawer(const SimData& data) : objectContextMenu(data) { switches.grid.selected = true; switches.lineTrails.selected = true; switches.planetScale.selected = false; drawGUI = true; } void GUIDrawer::Draw(SimData& data, Viewer& viewer, SceneDrawer& scene, size_t w, size_t h) { if (ImGui::IsKeyPressed(GLFW_KEY_F1)) drawGUI = !drawGUI; if (drawGUI) { TopMenuBar(data, viewer, scene, w, h); BotttomMenuBar(data, viewer, scene, w, h); } objectContextMenu.Draw(data, scene); } void GUIDrawer::TopMenuBar(SimData& data, Viewer& viewer, SceneDrawer& scene, size_t w, size_t h) { //To reflect changes from the outside code switches.pause.selected = viewer.IsPaused() ? true : false; switches.play.selected = viewer.IsRunning() ? true : false; auto context = ImGui::GetCurrentContext(); ImGui::SetNextWindowPos(ImVec2(0, 0)); ImGui::SetNextWindowContentSize(ImVec2(float(w), 0)); if (ImGui::Begin("TopMenuBar", nullptr, ImVec2(float(w), 0), 0.0f, ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove)) { if (ImGui::BeginMenuBar()) { auto draw = ImGui::GetWindowDrawList(); ImGui::AlignFirstTextHeightToWidgets(); ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); buttons.graphs.Draw("Graphs"); ImGui::TextTooltipOnHover("Enables creating graphs visualizing various physical properties of simulated objects."); ImGui::PopStyleColor(); if (buttons.graphs.selected) graphs(data, viewer.GetRunTime(), viewer.GetSimTime()); ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); buttons.unitsProps.Draw("List of objects"); ImGui::TextTooltipOnHover("Shows all simulated objects and their physical properties."); ImGui::PopStyleColor(); if (buttons.unitsProps.selected) unitsProps.Draw(data, scene.GetActiveCam()); ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); buttons.simControls.Draw("Simulation's Details"); ImGui::TextTooltipOnHover("Shows statistics about ongoing simulation."); ImGui::PopStyleColor(); if (buttons.simControls.selected)gui::SimProperties(viewer); ImGui::SameLine(w / 2.0f - offsets.pause / 2.0f);//Centered ImGui::BeginGroup(); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); TopButtons(viewer, draw); ImGui::EndGroup(); offsets.pause = ImGui::GetItemRectSize().x; ImGui::SameLine(w - offsets.prefs - context->Style.FramePadding.x); ImGui::BeginGroup(); TopRightSwitches(scene, viewer, draw); ImGui::SameLine(); if (ImGui::Button("Hide UI")) drawGUI = false; ImGui::TextTooltipOnHover("Hides all opened windows as well as both menu bars.\nPRESS 'F1' KEY TO BRING UI BACK."); ImGui::SameLine(); buttons.visuals.Draw("Visual Preferences"); ImGui::TextTooltipOnHover("Allows to change visual parts of the simulation."); ImGui::PopStyleColor(); if (buttons.visuals.selected) visualPrefs.Draw(data, scene); ImGui::EndGroup(); offsets.prefs = ImGui::GetItemRectSize().x; ImGui::EndMenuBar(); } } ImGui::End(); } void GUIDrawer::TopRightSwitches(SceneDrawer& scene, solar::Viewer & viewer, ImDrawList * draw) { auto style = ImGui::GetStyle(); auto buttonSize = style.FramePadding * 2.0f + ImGui::CalcTextSize("XX"); auto textCol = ImGui::GetColorU32(ImGuiCol_Text); ImVec2 cursorPos; //RealPlanetScale Button cursorPos = ImGui::GetCursorScreenPos(); switches.planetScale.selected = scene.GetSimDataDrawer().IsRealScaleEnabled(); if (switches.planetScale.DrawBlank(buttonSize)) scene.GetSimDataDrawer().SetRealScale(switches.planetScale.selected); ImGui::TextTooltipOnHover("If enabled shows real scale of simulated objects.\nOtherwise objects are always large enough to be visible on screen."); ImGui::SameLine(); draw->AddCircle(cursorPos + ImVec2(buttonSize.x*0.4f, buttonSize.y*0.5f), buttonSize.x*0.3f, textCol, 12, 2.0f); draw->AddCircleFilled(cursorPos + buttonSize*0.75f, buttonSize.x*0.4f - style.FramePadding.x, textCol, 12); //LineTrails button cursorPos = ImGui::GetCursorScreenPos(); switches.lineTrails.selected = scene.GetLineTrails().IsAnyEnabled(); if (switches.lineTrails.DrawBlank(buttonSize)) scene.SwitchLineTrails(switches.lineTrails.selected); ImGui::TextTooltipOnHover("Enables/Disables rendering of trails behind simulated objects."); ImGui::SameLine(); draw->PathArcTo(cursorPos + style.FramePadding, buttonSize.x*0.5f, 0, 3.14f / 2); draw->PathStroke(textCol, false, 2.0f); draw->AddCircleFilled(cursorPos + buttonSize*0.6f, buttonSize.x*0.15f, textCol); //Grid button cursorPos = ImGui::GetCursorScreenPos(); switches.grid.selected = scene.IsGridEnabled(); if (switches.grid.DrawBlank(buttonSize)) scene.SwitchGrid(switches.grid.selected); ImGui::TextTooltipOnHover("Enables/Disabled rendering of the grid."); ImGui::SameLine(); for (int i = 1; i <= 3; ++i) { draw->AddLine(cursorPos + ImVec2(buttonSize.x*0.25f*i, style.FramePadding.y), cursorPos + ImVec2(buttonSize.x*0.25f*i, buttonSize.y - style.FramePadding.y), textCol, 1.0f); draw->AddLine(cursorPos + ImVec2(style.FramePadding.x, buttonSize.x*0.25f*i), cursorPos + ImVec2(buttonSize.x - style.FramePadding.x, buttonSize.x*0.25f*i), textCol, 1.0f); } } void GUIDrawer::TopButtons(solar::Viewer & viewer, ImDrawList * draw) { auto style = ImGui::GetStyle(); auto buttonSize = style.FramePadding * 2.0f + ImGui::CalcTextSize("XX"); auto textCol = ImGui::GetColorU32(ImGuiCol_Text); auto greyCol = ImGui::ColorConvertFloat4ToU32(ImVec4(0.3f, 0.3f, 0.3f, 1.0f)); ImVec2 cursorPos; cursorPos = ImGui::GetCursorScreenPos(); if (ImGui::Button("##<<Raw", buttonSize)) viewer.SetRawMultiplier(std::max(int(viewer.GetRawMultiplier() - 10), 1)); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text("Decreses raw multiplier by 10.\nControls speed of the simulation at expense of CPU power.\nCurrent value: %u", viewer.GetRawMultiplier()); ImGui::EndTooltip(); } ImGui::SameLine(); auto col = viewer.GetRawMultiplier() > 1 ? textCol : greyCol; DrawSlowerTriangles(draw, cursorPos, buttonSize, style, col); draw->AddText(ImGui::GetFont(), ImGui::GetFontSize(), cursorPos + ImVec2(buttonSize.x*0.08f, buttonSize.y*0.55f), col, "R"); cursorPos = ImGui::GetCursorScreenPos(); if (ImGui::Button("##<<DT", buttonSize)) viewer.SetDTMultiplier(std::max(viewer.GetDTMultiplier() / 10, size_t(1))); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text("Divides DT multiplier by 10.\nControls speed of the simulation at expense of precision.\nCurrent value: %u", viewer.GetDTMultiplier()); ImGui::EndTooltip(); } ImGui::SameLine(); DrawSlowerTriangles(draw, cursorPos, buttonSize, style, viewer.GetDTMultiplier() > 1 ? textCol : greyCol); //Pause Button cursorPos = ImGui::GetCursorScreenPos(); if (switches.pause.DrawBlank(buttonSize) && viewer.IsRunning()) { viewer.PauseSimulation(); switches.play.selected = false; } ImGui::SameLine(); //Draw pause paralel lines draw->AddLine(ImVec2(cursorPos.x + buttonSize.x*0.35f, cursorPos.y + style.FramePadding.y), ImVec2(cursorPos.x + buttonSize.x*0.35f, cursorPos.y + buttonSize.y - style.FramePadding.x), textCol, 3.0f); draw->AddLine(ImVec2(cursorPos.x + buttonSize.x*0.65f, cursorPos.y + style.FramePadding.y), ImVec2(cursorPos.x + buttonSize.x*0.65f, cursorPos.y + buttonSize.y - style.FramePadding.x), textCol, 3.0f); //Play button cursorPos = ImGui::GetCursorScreenPos(); if (switches.play.DrawBlank(buttonSize) && viewer.IsPaused()) { viewer.ResumeSimulation(); switches.pause.selected = false; } ImGui::SameLine(); //Render play button at the centre of the button draw->AddTriangleFilled(ImVec2(cursorPos.x + style.FramePadding.x, cursorPos.y + style.FramePadding.y), ImVec2(cursorPos.x + style.FramePadding.x, cursorPos.y + buttonSize.y - style.FramePadding.y), ImVec2(cursorPos.x + buttonSize.x - style.FramePadding.x, cursorPos.y + buttonSize.y*0.5f), textCol); cursorPos = ImGui::GetCursorScreenPos(); if (ImGui::Button("##>>DT", buttonSize)) viewer.SetDTMultiplier(viewer.GetDTMultiplier() * 10); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text("Multiplies DT multiplier by 10.\nControls speed of the simulation at expense of precision.\nCurrent value: %u", viewer.GetDTMultiplier()); ImGui::EndTooltip(); } ImGui::SameLine(); DrawFasterTriangles(draw, cursorPos, style, buttonSize, textCol); cursorPos = ImGui::GetCursorScreenPos(); if (ImGui::Button("##>>Raw", buttonSize)) viewer.SetRawMultiplier(viewer.GetRawMultiplier() + (viewer.GetRawMultiplier() == 1 ? 9 : 10)); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text("Increases raw multiplier by 10.\nControls speed of the simulation at expense of CPU power.\nCurrent value: %u", viewer.GetRawMultiplier()); ImGui::EndTooltip(); } ImGui::SameLine(); DrawFasterTriangles(draw, cursorPos, style, buttonSize, textCol); draw->AddText(ImGui::GetFont(), ImGui::GetFontSize(), cursorPos + ImVec2(buttonSize.x*0.68f, buttonSize.y*0.55f), textCol, "R"); } void GUIDrawer::DrawFasterTriangles(ImDrawList * draw, ImVec2 &cursorPos, ImGuiStyle &style, ImVec2 &buttonSize, const ImU32 &textCol) { draw->AddTriangleFilled(ImVec2(cursorPos.x + style.FramePadding.x, cursorPos.y + style.FramePadding.y), ImVec2(cursorPos.x + style.FramePadding.x, cursorPos.y + buttonSize.y - style.FramePadding.y), ImVec2(cursorPos.x + buttonSize.x*0.5f, cursorPos.y + buttonSize.y*0.5f), textCol); draw->AddTriangleFilled(ImVec2(cursorPos.x + buttonSize.x*0.5f, cursorPos.y + style.FramePadding.y), ImVec2(cursorPos.x + buttonSize.x*0.5f, cursorPos.y + buttonSize.y - style.FramePadding.y), ImVec2(cursorPos.x + buttonSize.x - style.FramePadding.x, cursorPos.y + buttonSize.y*0.5f), textCol); } void GUIDrawer::DrawSlowerTriangles(ImDrawList * draw, ImVec2 &cursorPos, ImVec2 &buttonSize, ImGuiStyle &style, const ImU32 &textCol) { draw->AddTriangleFilled(ImVec2(cursorPos.x + buttonSize.x*0.5f, cursorPos.y + style.FramePadding.y), ImVec2(cursorPos.x + buttonSize.x*0.5f, cursorPos.y + buttonSize.y - style.FramePadding.y), ImVec2(cursorPos.x + style.FramePadding.x, cursorPos.y + buttonSize.y*0.5f), textCol); draw->AddTriangleFilled(ImVec2(cursorPos.x + buttonSize.x - style.FramePadding.x, cursorPos.y + style.FramePadding.y), ImVec2(cursorPos.x + buttonSize.x - style.FramePadding.x, cursorPos.y + buttonSize.y - style.FramePadding.y), ImVec2(cursorPos.x + buttonSize.x*0.5f, cursorPos.y + buttonSize.y*0.5f), textCol); } void GUIDrawer::BotttomMenuBar(SimData & data, Viewer & viewer, SceneDrawer & scene, size_t w, size_t h) { auto context = ImGui::GetCurrentContext(); //Calculated same way as in Imgui's window calculations - function MenuBarHeight() in imgui_internal.h auto menuBarHeight = ImGui::GetFontSize() + ImGui::GetStyle().FramePadding.y * 2.0f; ImGui::SetNextWindowPos(ImVec2(0, float(h) - menuBarHeight)); ImGui::SetNextWindowContentSize(ImVec2(float(w), 0)); if (ImGui::Begin("BottomMenuBar", nullptr, ImVec2(float(w), 0), 0.0f, ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove)) { if (ImGui::BeginMenuBar()) { ImGui::AlignFirstTextHeightToWidgets(); auto simTime = SplitTime(viewer.GetSimTime()); ImGui::Text("Simulated time: %u years, %u days, %u hours, %u minutes, %u seconds", simTime.Y, simTime.D, simTime.H, simTime.M, simTime.S); ImGui::SameLine(w / 2.0f - offsets.speedAndFollow / 2.0f); ImGui::BeginGroup(); ImGui::Text("\tSpeed: %ux", viewer.GetDTMultiplier()*viewer.GetRawMultiplier()); auto index = scene.GetActiveCam().GetFollowedObjectIndex(); if (index != Camera::noTarget) { ImGui::SameLine(); ImGui::Text("\tFollowing: %s", data[index].name.c_str()); ImGui::SameLine(); if (ImGui::SmallButton("X")) scene.GetActiveCam().FollowObject(Camera::noTarget); } ImGui::EndGroup(); offsets.speedAndFollow = ImGui::GetItemRectSize().x; if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); auto speedRatio = SplitTime(uint64_t(viewer.GetDTMultiplier()*viewer.GetRawMultiplier())); ImGui::Text("1 real second = %u years, %u days, %u hours, %u minutes, %u seconds", speedRatio.Y, speedRatio.D, speedRatio.H, speedRatio.M, speedRatio.S); ImGui::EndTooltip(); } ImGui::SameLine(); GridSize(w, context, menuBarHeight, scene); ImGui::EndMenuBar(); } } ImGui::End(); } void GUIDrawer::GridSize(const size_t &w, ImGuiContext * context, float menuBarHeight, solar::drawers::SceneDrawer & scene) { auto gridPos = w - offsets.grid - 2 * context->Style.FramePadding.x; auto draw = ImGui::GetWindowDrawList(); ImU32 col = ImGui::ColorConvertFloat4ToU32(ImVec4 {0.06f, 0.24f, 0.71f,1.0f}); draw->AddLine(ImVec2(gridPos - 100.0f, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f - 5.0f), ImVec2(gridPos, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f - 5.0f), col, 2.5f); draw->AddLine(ImVec2(gridPos - 100.0f, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f - 10.0f), ImVec2(gridPos - 100.0f, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f), col, 2.5f); draw->AddLine(ImVec2(gridPos, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f - 10.0f), ImVec2(gridPos, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f), col, 2.5f); draw->AddLine(ImVec2(gridPos - 50.0f, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f + 5.0f), ImVec2(gridPos, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f + 5.0f), col, 2.5f); draw->AddLine(ImVec2(gridPos - 50.0f, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f), ImVec2(gridPos - 50.0f, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f + 10.0f), col, 2.5f); draw->AddLine(ImVec2(gridPos, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f), ImVec2(gridPos, ImGui::GetCursorScreenPos().y + menuBarHeight / 2.0f + 10.0f), col, 2.5f); double scale = scene.GetGridScale(); std::string units = "meters"; double gridSize = scale; //Change to better units if appropiate if ((gridSize = scale / PhysUnits::lightYear) >= 1.0) units = "light years"; else if ((gridSize = scale / PhysUnits::AU) >= 1.0) units = "AU"; else if ((gridSize = scale / PhysUnits::kilometer) >= 1.0) units = "kilometres"; ImGui::SameLine(gridPos); ImGui::Text("%.5g / %.5g %s", gridSize, gridSize*scene.GetGrid().SmallToBig(), units.c_str()); char buffer[255]; snprintf(buffer, 255, "%f / %f %s", gridSize, gridSize*scene.GetGrid().SmallToBig(), units.c_str()); ImGui::TextTooltipOnHover(buffer); offsets.grid = ImGui::GetItemRectSize().x; } } }
#include <iostream> using namespace std; int main() { //logical variables - bool bool var; var = 0; bool var1 = 1; //целочислени стойности short var2; //2B - dva baita //long int var3; //4B - 4 baita /*short * 2B = 16bit * 2^16 = 65536 * no poneje ima i 0~65535 - this is unsigned short * za da ima i otricatelna 4ast: -32767 ~ 32767 = -2^15 ~ 2^15 * */ unsigned short var4 = -4437; //cout << var4 << endl ; double var5 = -5.76; float var6 = -34.4; char a = '7'; int b = 7; //CONBSTANTI //const int aa = 3; //cout << aa << endl; //aa = 4343; error assignment of read-only variable 'aa' //cout << aa << endl; //int ab =3, cd =5; //inicialize multiple variables //cin>>ab>>cd; //cout <<ab <<cd; //напишете програма която показва средно аритметичното от 2 числавкарани от потребителя /*int h1; int h2; cout<<"Please enter fist digit: "; cin >> h1 ; cout<<"Please enter second digit: "; cin >> h2 ; double h3 = (h1+h1)/2; cout<< h3;*/ int h1, h2; cout << "Enter a="; cin >> h1; cout << "enter b="; cin >> h2; cout << "Result =" << (h1+h2)/2 <<endl; return 0; }
// String.cpp // // ICS 46 Winter 2021 // Project #0: Getting to Know the ICS 46 VM // // Implement all of your String member functions in this file. // // Note that the entire standard library -- both the C Standard // Library and the C++ Standard Library -- is off-limits for this // task, as the goal is to exercise your low-level implementation // skills (pointers, memory management, and so on). #include "String.hpp"
/* ** EPITECH PROJECT, 2019 ** Mutex.hpp ** File description: ** ${FILEDESCRIPTION} */ #ifndef CCP_PLAZZA_2018_MUTEX_HPP #define CCP_PLAZZA_2018_MUTEX_HPP #include <mutex> class IMutex { public: virtual ~IMutex() = default; virtual void lock() = 0; virtual void unlock() = 0; virtual void trylock() = 0; }; class Mutex : public IMutex { public: ~Mutex(); void lock(); void unlock(); void trylock(); protected: std::mutex mutex; }; #endif //CCP_PLAZZA_2018_MUTEX_HPP
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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. */ #ifndef TESTBIDOMAINDISTRIBUTEDMESH_HPP_ #define TESTBIDOMAINDISTRIBUTEDMESH_HPP_ #include <cxxtest/TestSuite.h> #include "LuoRudy1991.hpp" #include "BidomainProblem.hpp" #include "DistributedVector.hpp" #include "HeartConfig.hpp" #include "PlaneStimulusCellFactory.hpp" #include "DistributedTetrahedralMesh.hpp" #include "TetrahedralMesh.hpp" #include "TrianglesMeshReader.hpp" #include "MemfemMeshReader.hpp" #include "PetscSetupAndFinalize.hpp" class TestBidomainDistributedMesh : public CxxTest::TestSuite { public: void TestBidomainProblemWithDistributedMesh2D() { HeartConfig::Instance()->SetSimulationDuration(1); //ms HeartConfig::Instance()->SetOutputDirectory("DistributedMesh2d"); HeartConfig::Instance()->SetOutputFilenamePrefix("tetrahedral2d"); // The default stimulus in PlaneStimulusCellFactory is not enough to generate propagation // here, increasing it an order of magnitude PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 2> cell_factory(-6000); // To avoid an issue with the Event handler only one simulation should be // in existance at a time: therefore monodomain simulation is defined in a block double seq_ave_voltage; { /////////////////////////////////////////////////////////////////// // TetrahedralMesh /////////////////////////////////////////////////////////////////// TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/2D_0_to_1mm_400_elements"); TetrahedralMesh<2,2> mesh; mesh.ConstructFromMeshReader(mesh_reader); BidomainProblem<2> nondistributed_problem( &cell_factory ); nondistributed_problem.SetMesh(&mesh); nondistributed_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); nondistributed_problem.Solve(); DistributedVector dist_nondistributed_voltage = nondistributed_problem.GetSolutionDistributedVector(); DistributedVector::Stripe nondistributed_voltage(dist_nondistributed_voltage, 0); DistributedVector::Stripe nondistributed_potential(dist_nondistributed_voltage, 1); double seq_local_ave_voltage = 0.0; for (DistributedVector::Iterator index = dist_nondistributed_voltage.Begin(); index != dist_nondistributed_voltage.End(); ++index) { if (index.Global==0) { TS_ASSERT_LESS_THAN(0, nondistributed_voltage[index]); } seq_local_ave_voltage += nondistributed_voltage[index]; } MPI_Reduce(&seq_local_ave_voltage, &seq_ave_voltage, 1, MPI_DOUBLE, MPI_SUM, PetscTools::MASTER_RANK, PETSC_COMM_WORLD); seq_ave_voltage /= mesh.GetNumNodes(); } /////////////////////////////////////////////////////////////////// // DistributedTetrahedralMesh /////////////////////////////////////////////////////////////////// HeartConfig::Instance()->SetOutputFilenamePrefix("distributed2d"); TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/2D_0_to_1mm_400_elements"); DistributedTetrahedralMesh<2,2> mesh(DistributedTetrahedralMeshPartitionType::DUMB); mesh.ConstructFromMeshReader(mesh_reader); BidomainProblem<2> distributed_problem( &cell_factory ); distributed_problem.SetMesh(&mesh); distributed_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); distributed_problem.Solve(); DistributedVector dist_distributed_voltage = distributed_problem.GetSolutionDistributedVector(); DistributedVector::Stripe distributed_voltage(dist_distributed_voltage, 0); DistributedVector::Stripe distributed_potential(dist_distributed_voltage, 1); double para_local_ave_voltage = 0.0; for (DistributedVector::Iterator index = dist_distributed_voltage.Begin(); index != dist_distributed_voltage.End(); ++index) { if (index.Global==0) { TS_ASSERT_LESS_THAN(0, distributed_voltage[index]); } para_local_ave_voltage += distributed_voltage[index]; } double para_ave_voltage; MPI_Reduce(&para_local_ave_voltage, &para_ave_voltage, 1, MPI_DOUBLE, MPI_SUM, PetscTools::MASTER_RANK, PETSC_COMM_WORLD); para_ave_voltage /= mesh.GetNumNodes(); /////////////////////////////////////////////////////////////////// // compare /////////////////////////////////////////////////////////////////// if (PetscTools::AmMaster()) { std::cout << seq_ave_voltage << " " << para_ave_voltage << std::endl; TS_ASSERT_DELTA(seq_ave_voltage, para_ave_voltage, 1.0); } } void TestBidomainProblemWithDistributedMesh2DParMetis() { HeartConfig::Instance()->SetSimulationDuration(1); //ms HeartConfig::Instance()->SetOutputDirectory("DistributedMesh2d"); HeartConfig::Instance()->SetOutputFilenamePrefix("tetrahedral2d"); // The default stimulus in PlaneStimulusCellFactory is not enough to generate propagation // here, increasing it an order of magnitude PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 2> cell_factory(-6000, 0.5); // To avoid an issue with the Event handler only one simulation should be // in existance at a time: therefore monodomain simulation is defined in a block double seq_ave_voltage=0.0; { /////////////////////////////////////////////////////////////////// // TetrahedralMesh /////////////////////////////////////////////////////////////////// TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/2D_0_to_1mm_400_elements"); TetrahedralMesh<2,2> mesh; mesh.ConstructFromMeshReader(mesh_reader); BidomainProblem<2> nondistributed_problem( &cell_factory ); nondistributed_problem.SetMesh(&mesh); nondistributed_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); nondistributed_problem.Solve(); DistributedVector dist_nondistributed_voltage = nondistributed_problem.GetSolutionDistributedVector(); DistributedVector::Stripe nondistributed_voltage(dist_nondistributed_voltage, 0); DistributedVector::Stripe nondistributed_potential(dist_nondistributed_voltage, 1); double seq_local_ave_voltage = 0.0; for (DistributedVector::Iterator index = dist_nondistributed_voltage.Begin(); index != dist_nondistributed_voltage.End(); ++index) { if (index.Global==0) { TS_ASSERT_LESS_THAN(0, nondistributed_voltage[index]); } seq_local_ave_voltage += nondistributed_voltage[index]; } MPI_Reduce(&seq_local_ave_voltage, &seq_ave_voltage, 1, MPI_DOUBLE, MPI_SUM, PetscTools::MASTER_RANK, PETSC_COMM_WORLD); seq_ave_voltage /= mesh.GetNumNodes(); } /////////////////////////////////////////////////////////////////// // DistributedTetrahedralMesh /////////////////////////////////////////////////////////////////// HeartConfig::Instance()->SetOutputFilenamePrefix("distributed2d"); HeartConfig::Instance()->SetMeshPartitioning("parmetis"); HeartConfig::Instance()->SetMeshFileName("mesh/test/data/2D_0_to_1mm_400_elements"); // TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/2D_0_to_1mm_400_elements"); // DistributedTetrahedralMesh<2,2> mesh(DistributedTetrahedralMeshPartitionType::PARMETIS_LIBRARY); // mesh.ConstructFromMeshReader(mesh_reader); BidomainProblem<2> distributed_problem( &cell_factory ); //distributed_problem.PrintOutput(false); // distributed_problem.SetMesh(&mesh); distributed_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); distributed_problem.Solve(); DistributedVector dist_distributed_voltage = distributed_problem.GetSolutionDistributedVector(); DistributedVector::Stripe distributed_voltage(dist_distributed_voltage, 0); DistributedVector::Stripe distributed_potential(dist_distributed_voltage, 1); double para_local_ave_voltage = 0.0; for (DistributedVector::Iterator index = dist_distributed_voltage.Begin(); index != dist_distributed_voltage.End(); ++index) { if (index.Global==0) { TS_ASSERT_LESS_THAN(0, distributed_voltage[index]); } para_local_ave_voltage += distributed_voltage[index]; } double para_ave_voltage; MPI_Reduce(&para_local_ave_voltage, &para_ave_voltage, 1, MPI_DOUBLE, MPI_SUM, PetscTools::MASTER_RANK, PETSC_COMM_WORLD); para_ave_voltage /= distributed_problem.rGetMesh().GetNumNodes(); /////////////////////////////////////////////////////////////////// // compare /////////////////////////////////////////////////////////////////// if (PetscTools::AmMaster()) { std::cout << seq_ave_voltage << " " << para_ave_voltage << std::endl; TS_ASSERT_DELTA(seq_ave_voltage, para_ave_voltage, 1.0); } } void TestBidomainProblemWithDistributedMeshFromMemfem3DParMetis() { HeartConfig::Instance()->SetSimulationDuration(1); //ms HeartConfig::Instance()->SetOutputDirectory("DistributedMesh3dRepViaTri"); HeartConfig::Instance()->SetOutputFilenamePrefix("tetrahedral3d"); // The default stimulus in PlaneStimulusCellFactory is not enough to generate propagation // here, increasing it an order of magnitude PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 3> cell_factory(-6000); // To avoid an issue with the Event handler only one simulation should be // in existance at a time: therefore monodomain simulation is defined in a block double seq_ave_voltage=0.0; { /////////////////////////////////////////////////////////////////// // TetrahedralMesh from Triangles /////////////////////////////////////////////////////////////////// TrianglesMeshReader<3,3> mesh_reader("mesh/test/data/SlabFromMemfem"); TetrahedralMesh<3,3> mesh; mesh.ConstructFromMeshReader(mesh_reader); TS_ASSERT_DELTA(mesh.GetVolume(), 1.5625, 1e-6); TS_ASSERT_EQUALS(mesh_reader.GetNumNodes(), 381u); TS_ASSERT_EQUALS(mesh_reader.GetNumElements(), 1030u); TS_ASSERT_EQUALS(mesh_reader.GetNumFaces(), 758u); BidomainProblem<3> nondistributed_problem( &cell_factory ); nondistributed_problem.SetMesh(&mesh); nondistributed_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); nondistributed_problem.Solve(); DistributedVector dist_nondistributed_voltage = nondistributed_problem.GetSolutionDistributedVector(); DistributedVector::Stripe nondistributed_voltage(dist_nondistributed_voltage, 0); DistributedVector::Stripe nondistributed_potential(dist_nondistributed_voltage, 1); double seq_local_ave_voltage = 0.0; for (DistributedVector::Iterator index = dist_nondistributed_voltage.Begin(); index != dist_nondistributed_voltage.End(); ++index) { if (index.Global==0) { TS_ASSERT_LESS_THAN(0, nondistributed_voltage[index]); } seq_local_ave_voltage += nondistributed_voltage[index]; } MPI_Reduce(&seq_local_ave_voltage, &seq_ave_voltage, 1, MPI_DOUBLE, MPI_SUM, PetscTools::MASTER_RANK, PETSC_COMM_WORLD); seq_ave_voltage /= mesh.GetNumNodes(); } /////////////////////////////////////////////////////////////////// // DistributedTetrahedralMesh from Memfem /////////////////////////////////////////////////////////////////// HeartConfig::Instance()->SetOutputDirectory("DistributedMesh3dDistViaMem"); BidomainProblem<3> distributed_problem( &cell_factory ); HeartConfig::Instance()->SetMeshFileName("mesh/test/data/Memfem_slab"); distributed_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); distributed_problem.Solve(); DistributedVector dist_distributed_voltage = distributed_problem.GetSolutionDistributedVector(); DistributedVector::Stripe distributed_voltage(dist_distributed_voltage, 0); DistributedVector::Stripe distributed_potential(dist_distributed_voltage, 1); double para_local_ave_voltage = 0.0; for (DistributedVector::Iterator index = dist_distributed_voltage.Begin(); index != dist_distributed_voltage.End(); ++index) { if (index.Global==0) { TS_ASSERT_LESS_THAN(0, distributed_voltage[index]); } para_local_ave_voltage += distributed_voltage[index]; } double para_ave_voltage; MPI_Reduce(&para_local_ave_voltage, &para_ave_voltage, 1, MPI_DOUBLE, MPI_SUM, PetscTools::MASTER_RANK, PETSC_COMM_WORLD); para_ave_voltage /= distributed_problem.rGetMesh().GetNumNodes(); /////////////////////////////////////////////////////////////////// // compare /////////////////////////////////////////////////////////////////// if (PetscTools::AmMaster()) { std::cout << seq_ave_voltage << " " << para_ave_voltage << std::endl; TS_ASSERT_DELTA(seq_ave_voltage, para_ave_voltage, 1.0); } } }; #endif /*TESTBIDOMAINDISTRIBUTEDMESH_HPP_*/
#pragma once #ifndef CONSOLE_HPP #define CONSOLE_HPP #include <QWidget> #include <QLineEdit> class Console : public QWidget { public: Console ( QWidget* parent ); }; #endif
// // Created by 梁栋 on 2019-05-01. // #include <vector> #include <stack> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: void flatten(TreeNode* root) { vector<TreeNode*> nodes; stack<TreeNode*> stack1; TreeNode* cur = root; while(cur != NULL || !stack1.empty()){ while (cur){ stack1.push(cur); nodes.push_back(cur); cur = cur->left; } cur = stack1.top(); stack1.pop(); cur = cur->right; } cur = root; for(int i=1;i<nodes.size();i++){ cur->right = nodes[i]; cur->left = NULL; cur = cur->right; } cur->right = NULL; } TreeNode* prev = NULL; void flattenV2(TreeNode* root){ if(root == NULL) return; flattenV2(root->right); flattenV2(root->left); root->right = prev; root->left = NULL; prev = root; } static void solution(){ TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->left->left = new TreeNode(3); root->left->right = new TreeNode(4); root->right = new TreeNode(5); root->right->right = new TreeNode(6); Solution solution1; solution1.flatten(root); while(root){ cout<<root->val<<"->"; root = root->right; } cout<<endl; } };
#include "employeeservice.h" EmployeeService::EmployeeService() { //ctor } void EmployeeService::add_employee(const Employee& employee) { cout << employee << endl; }
#include <string> #include <cstdio> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "util.h" using namespace std; /* Funciones de cadena ------------------------------------------------------------------------- */ // Borra los espacios en blanco a los costados de la cadena std::string &trimString(std::string &cad) { //Si la cadena esta vacia devolver, si el primer caracter es un newline, devolver if (cad.length() <= 0) return cad; //Remover los espacios en blanco del principio de la cadena while (cad[0] == ' ') cad.erase(1); //Remover los espacios en blanco del final de la cadena while (cad[cad.length() - 1] == ' ') cad.erase(cad.length() - 1); return cad; } // Borra los espacios en blanco y newlines a los costados de la cadena std::string& strtrimString(std::string &cad) { //Si la cadena esta vacia devolver; si el primer caracter es un newline, devolver if (cad.length() <= 0) return cad; if (cad[0] == '\n') { cad.erase(cad.begin(), cad.end()); return cad; } //Remover los espacios en blanco y newlines del principio de la cadena while ((cad[0] == '\n') || (cad[0] == ' ')) cad.erase(1); //Remover los espacios en blanco y newlines del final de la cadena while ((cad[cad.length() - 1] == '\n') || (cad[cad.length() - 1] == ' ')) cad.erase(cad.length() - 1); return cad; } //Hace una copia a mayusculas de una cadena std::string upperCase(std::string s) { char *buf = new char[s.length()]; s.copy(buf, s.length()); for (unsigned int i = 0; i < s.length(); i++) buf[i] = toupper(buf[i]); string r(buf, s.length()); delete buf; return r; } //Hace una copia a minusculas de una cadena std::string lowerCase(std::string s) { char *buf = new char[s.length()]; s.copy(buf, s.length()); for (unsigned int i = 0; i < s.length(); i++) buf[i] = tolower(buf[i]); string r(buf, s.length()); delete buf; return(r); } /* Funciones de cadena ------------------------------------------------------------------------- */ /* Funciones varias ---------------------------------------------------------------------------- */ std::string dominioEmail(std::string &cad) { int pos = cad.find("@"); if (pos > 0) { string resultado(cad, pos + 1); return(resultado); } else return(""); } std::string usuarioEmail(std::string &cad) { int pos = cad.find("@"); if (pos > 0) { string resultado(cad, 0, pos); return(resultado); } else return(""); } std::string dominioApache(const std::string &dom) { //La funcion devuelve el nombre de un dominio unsigned int pos; //Buscar el primer . pos = dom.find('.'); if (pos == string::npos) return(dom); //Declarar un nuevo string con el dominio string ret(dom, 0, pos); //Devolver la cadena return(ret); } std::string extensionApache(const std::string &dom) { /* La funcion devuelve la extension de un dominio con \ delante . */ unsigned int pos; //Buscar el primer . pos = dom.find('.'); if (pos == string::npos) return(dom); //Declarar un nuevo string con la extension string ret(dom, pos + 1); //Remplazar todos los . por / pos = ret.find('.'); while (pos != string::npos) { ret.insert(pos, "\\"); pos = ret.find('.', pos + 1); } //Devolver la cadena return(ret); } int existeArchivo(const std::string &path) { struct stat buf; int fd; mode_t mode; /* Tratar de abrir el archivo */ if (( fd = open(path.c_str(), O_RDONLY)) < 0) return(0); /* Obtener la informacion del archivo */ if ((fstat(fd, &buf)) < 0) { close(fd); return(0); } mode = buf.st_mode; if (S_ISREG(mode)) { close(fd); return(1); } else { close(fd); return(0); } } int existeDirectorio(const std::string &path) { struct stat buf; int fd; mode_t mode; /* Tratar de abrir el directorio */ if (( fd = open(path.c_str(), O_RDONLY)) < 0) return(0); /* Obtener la informacion del archivo */ if ((fstat(fd, &buf)) < 0) { close(fd); return(0); } mode = buf.st_mode; if (S_ISDIR(mode)) { close(fd); return(1); } else { close(fd); return(0); } } long obtenerTamanio(std::string archivo, std::string directorio) { /* Funcion que devuelve el tamanio de un archivo */ mode_t mode; int fd; std::string strfile; struct stat buf; long ret; /* Seleccionar el archivo a abrir */ if (directorio.length() <= 0) strfile = archivo; else { strfile = directorio; strfile += "/"; strfile += archivo; } /* Abrir el archivo */ if (( fd = open(strfile.c_str(), O_RDONLY)) < 0) return(-1); /* Obtener el status */ if ((fstat(fd, &buf)) < 0) return(-1); mode = buf.st_mode; /* Obtener el tamanio */ ret = buf.st_size; /* Cerrar el archivo */ close(fd); return(ret); } /* Funciones varias ---------------------------------------------------------------------------- */ /* Funciones de codificación ------------------------------------------------------------------- */ std::string codificarPassword(std::string password) { for (unsigned int x = 0; x < password.length(); x++) password[x] += 1; return(password); } std::string decodificarPassword(std::string password) { for (unsigned int x = 0; x < password.length(); x++) password[x] -= 1; return(password); } std::string passwordAleatorio() { string password; int numero; srand(time(NULL)); numero = (rand() % 99999999) + 1; char *temp = new char[9]; snprintf(temp, 9, "%d", numero); password = temp; delete temp; return(password); } /* Funciones de codificación ------------------------------------------------------------------- */