text
stringlengths
8
6.88M
#include <iostream> #include <stdio.h> #include <cstdlib> using namespace std; int main(){ int opc, cont; do{ cout<< "\t\tMenu Programas Estructuras de decision"<<endl; cout<< "\t1-Sueldo de un Trabajador"<<endl; cout<< "\t2-Tienda"<<endl; cout<< "\t3-Diagnostico Anemia"<<endl; cout<< "\t4-Numero medio"<<endl; cout<< "\t5-Juego del 21"<<endl; do{ cout<<"Ingrese una opcion"<<endl; cin>>opc; if(opc<=0 || opc>5) cout<<"Opcion invalida"<<endl; }while(opc<=0 || opc>5); switch(opc){ case 1: int cantH, horasExt, cant; float salarioH, pagoExtra, pago, pagoT, doblePago,t; cout<< "Ingrese el salario del trabajador por hora: "; cin>>salarioH; cout<<"Ingre la cantidad de horas trabajadas: "; cin>>cantH; if(cantH<=40){ pago=cantH*salarioH; pagoT=pago; }else{ horasExt=cantH-40; if (horasExt<=8){ pagoExtra=horasExt*(salarioH*2); pago=40*salarioH; pagoT=pago+pagoExtra; }else{ cant=horasExt-8; t=cant*(salarioH*3); pago=40*salarioH; doblePago=8*(2*salarioH); pagoT=pago+doblePago+t; } } cout<<"Pago total: "<<pagoT<<endl; break; case 2: int num; float costo,descuento,total; cout<<"Ingrese el costo de su compra sin descuento: "; cin>>costo; cout<<"Ingrese el numero de bolita que tiene: "; cin>>num; if(num==1){ descuento=0; }else if(num==2){ descuento=costo*0.1; }else if(num==3){ descuento=costo*0.25; }else if(num==4){ descuento=costo*0.5; }else if(num==5){ descuento=costo; } total=costo-descuento; cout<<"El costo de su compra es: "<<total<<endl; break; case 3: int edad,meses,resp, sexo; float nivelH; cout<<"Ingrese el sexo del paciente: (1)Masculino (2)Femenino"; cin>>sexo; cout<<"Ingrese el nivel de Hemoglobina: "; cin>>nivelH; cout<<"El tiene meses de nacer? 1-Si 2-No "; cin>>resp; if(resp==1){ cout<<"Ingrese los meses del paciente: "; cin>>meses; if((meses==1 && nivelH<13) || (meses>1 && meses<=6 && nivelH<10) || (meses>6 && meses<=12 && nivelH<11)){ cout<<"Tiene anemia"<<endl; }else{ cout<<"No tiene anemia"<<endl; } }else{ cout<<"Ingrese la edad del paciente: "; cin>>edad; if((edad>1 && edad<=5 && nivelH<11.5) || (edad>5 && edad<=10 && nivelH<12.6) || (edad>10 && edad<=15 && nivelH<13) || (edad>15 && sexo==2 && nivelH<12) || (edad>15 && sexo==1 && nivelH<14)){ cout<<"Tiene anemia"<<endl; }else{ cout<<"No tiene anemia"<<endl; } } break; case 4: float n1,n2,n3,medio; medio=0; cout<< "Ingrese el numero 1: "; cin>>n1; cout<< "Ingrese el numero 2: "; cin>>n2; cout<< "Ingrese el numero 3: "; cin>>n3; if(n1==n2 && n1==n3){ cout<< "Son iguales los tres numeros"<<endl; }else{ if((n1<n2 && n1>n3) || (n1<n3 && n1>n2)){ medio=n1; }else if((n2<n1 && n2>n3) || (n2<n3 && n2>n1)){ medio=n2; }else if((n3<n1 && n3>n2) || (n3<n2 && n3>n1)){ medio=n3; } cout<<"El numero medio es: "<<medio<<endl; } break; case 5: int c1, c2, c3; string carta1, carta2, carta3; int suma; cout << "De el valor de la carta 1" << endl; cin >> carta1; cout << "De el valor de la carta 2" << endl; cin >> carta2; cout << "De el valor de la carta 3" << endl; cin >> carta3; if ((carta1=="J") || (carta1=="Q") || (carta1=="K")) { carta1 = "10"; } if ((carta2=="J") || (carta2=="Q") || (carta2=="K")) { carta2 = "10"; } if ((carta3=="J") || (carta3=="Q") || (carta3=="K")) { carta3 = "10"; } if ((carta1=="AS") && (carta2=="AS") && (carta3=="AS")) { carta1 = "1"; carta2 = "1"; carta3 = "11"; } else { if ((carta1=="AS") && ((atof(carta2.c_str())+atof(carta3.c_str()))<=10)) { carta1 = "11"; } else { if ((carta1=="AS")) { carta1 = "1"; } } if ((carta2=="AS") && ((atof(carta1.c_str())+atof(carta3.c_str()))<=10)) { carta2 = "11"; } else { if ((carta2=="AS")) { carta2 = "1"; } } if ((carta3=="AS") && ((atof(carta1.c_str())+atof(carta2.c_str()))<=10)) { carta3 = "11"; } else { if ((carta3=="AS")) { carta3 = "1"; } } } c1 = atof(carta1.c_str()); c2 = atof(carta2.c_str()); c3 = atof(carta3.c_str()); suma = c1+c2+c3; cout << c1 << " " << c2 << " " << c3 << endl; if ((suma==21)) { cout << "Ganaste: " << suma << endl; } else { cout << "Perdiste: " << suma << endl; } break; } do{ cout<<"Quieres intentarlo de nuevo? 1-Si 2-No"<<endl; cin>>cont; }while((cont != 1) && (cont !=2 )); }while(cont==1); return 0; }
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <vector> #include <math.h> #define pb push_back using namespace std; int n; int r1, r2; struct emp { int val, idx; }; emp e[111]; vector <int> bonus; void input(){ scanf("%d %d %d", &n, &r1, &r2); for (int i = 0; i < n; i++) { scanf("%d", &e[i].val); e[i].idx = i + 1; } } bool cmp(emp e1, emp e2) { if (e1.val > e2.val) return 0; return 1; } void searchRight(int num) { int l = 0; int r = n - 1; int d = r2 - r1; while (l <= r) { int m = (l + r) / 2; if (num = e[m].val) { printf("%d\n", e[m].val); bonus.pb(e[m].idx); l = m + 1; } if (num > e[m].val) l = m + 1; if (num < e[m].val) { if (num <= e[m].val - d) { printf("%d\n", e[m].val); bonus.pb(e[m].idx); r = m - 1; } else { r = m - 1; } } } } void searchLeft(int num) { int l = 0; int r = n - 1; int d = r2 - r1; while (l <= r) { int m = (l + r) / 2; if (num = e[m].val) { bonus.pb(e[m].idx); r = m - 1; } if (num > e[m].val) l = m + 1; if (num < e[m].val) { if (num <= e[m].val - d) { bonus.pb(e[m].idx); r = m - 1; } else { r = m - 1; } } } } void solve(){ bonus.clear(); sort(e, e + n + 1, cmp); for (int i = 0; i < n; i++) printf("%d ", e[i + 1]); printf("\n"); searchRight(r1); //searchLeft(r1); for (int i = 0; i < bonus.size(); i++) printf("%d ", bonus[i]); //printf("%d\n", bonus.size()); /*sort(bonus.begin(), bonus.end(), cmp); for (int i = 0; i < bonus.size(); i++) { if (i > 0) printf(" "); printf("%d", bonus[i]); } printf("\n");*/ } int main() { int ntest; freopen("bonus.inp", "r", stdin); scanf("%d", &ntest); for (int i = 0; i < ntest; i++) { input(); solve(); } return 0; }
#pragma once #include "C:\Users\Andrey\Desktop\Linearization\Linerization\Working Test\version 1.1\include\signal.h" class Rectangle : public Signal { public: Rectangle(); ~Rectangle(void); void setVal(float); // инициализирует массив значений сигнала меандр };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2011-12 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #if defined(X11API) && defined(NS4P_COMPONENT_PLUGINS) #include "modules/pi/OpPainter.h" #include "modules/libgogi/pi_impl/mde_opwindow.h" #include "modules/libgogi/pi_impl/mde_opview.h" #include "platforms/x11api/plugins/plugin_unified_vega.h" #include "platforms/x11api/plugins/unix_oppluginadapter.h" #include "platforms/utilix/x11_all.h" #include "platforms/x11api/plugins/unix_oppluginimage.h" #include "platforms/x11api/pi/x11_client.h" OP_STATUS OpPluginWindow::Create(OpPluginWindow** newObj, const OpRect &rect, int scale, OpView* parent, BOOL windowless, OpWindow* op_window) { PluginUnifiedWindow *win = PluginUnifiedWindow::Create(rect, scale, parent, windowless, op_window); if (!win) { *newObj = 0; return OpStatus::ERR_NO_MEMORY; } *newObj = win; return OpStatus::OK; } PluginUnifiedWindow* PluginUnifiedWindow::Create(const OpRect& rect, int scale, OpView* parent_view, const bool windowless, OpWindow* parent_window) { if (windowless) { OP_ASSERT(parent_window || !"PluginUnifiedWindow::Create: Cannot create a plug-in window outside browser window"); return OP_NEW(PluginUnifiedWindow, (rect, scale, parent_view, parent_window)); } PluginUnifiedVega* p = OP_NEW(PluginUnifiedVega, (rect, scale, parent_view, parent_window)); if (!p || OpStatus::IsError(p->Init(X11Client::Instance()->GetDisplay()))) { OP_DELETE(p); return NULL; } return p; } unsigned int PluginUnifiedWindow::CheckPaintEvent() { return 1; } OP_STATUS PluginUnifiedWindow::EnableDirectPaint(const OpRect&) { return OpStatus::ERR_NOT_SUPPORTED; } void* PluginUnifiedWindow::GetHandle() { return 0; } unsigned int PluginUnifiedWindow::GetWindowHandle() { return 0; } void PluginUnifiedWindow::SetAdapter(UnixOpPluginAdapter* adapter) { m_adapter = adapter; adapter->SetPluginParentWindow(m_parent_window); } void PluginUnifiedWindow::SetPos(const int x, const int y) { m_plugin_rect.x = x; m_plugin_rect.y = y; } void PluginUnifiedWindow::SetSize(const int w, const int h) { m_plugin_rect.width = w; m_plugin_rect.height = h; } BOOL PluginUnifiedWindow::SendEvent(OpPlatformEvent* event) { OP_ASSERT(!"PluginUnifiedWindow::SendEvent: Shouldn't ever be used in a windowless instance"); return OpStatus::ERR; } OP_STATUS PluginUnifiedWindow::FocusEvent(OpPlatformEvent**, const bool) { OP_ASSERT(!"PluginUnifiedWindow::FocusEvent: Shouldn't ever be used in a windowless instance"); return OpStatus::ERR; } OP_STATUS PluginUnifiedWindow::KeyEvent(OpPlatformEvent**, OpKey::Code, const uni_char*, const bool, OpKey::Location location, const ShiftKeyState) { OP_ASSERT(!"PluginUnifiedWindow::KeyEvent: Shouldn't ever be used in a windowless instance"); return OpStatus::ERR; } OP_STATUS PluginUnifiedWindow::MouseEvent(OpPlatformEvent**, const OpPluginEventType, const OpPoint&, const int, const ShiftKeyState) { OP_ASSERT(!"PluginUnifiedWindow::MouseEvent: Deprecated. See UnixOpPluginTranslator::CreateMouseEvent."); return OpStatus::ERR; } OP_STATUS PluginUnifiedWindow::WindowMovedEvent(OpPlatformEvent** event) { return OpStatus::ERR_NOT_SUPPORTED; } BOOL PluginUnifiedWindow::UsesDirectPaint() const { return false; } #endif // X11API && NS4P_COMPONENT_PLUGINS
#include <iostream> #include <sstream> #include <vector> #include <list> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <unordered_map> #include <unordered_set> #include <string> #include <set> #include <stack> #include <cstdio> #include <cstring> #include <climits> #include <cstdlib> using namespace std; struct Node { int val; Node *left = NULL, *right = NULL, *parent = NULL; }; bool first = true; void postorder(Node* root) { if (root == NULL) return; postorder(root->left); postorder(root->right); if (first) { printf("%d", root->val); first = false; } else printf(" %d", root->val); } int main() { /*freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);*/ int n, val; cin >> n; string operation; Node* root = new Node(); root->parent = root; cin >> operation >> val; root->val = val; Node* p = root; vector<bool> visited(n+1, false); for (int i = 1; i < 2 * n; i++) { cin >> operation; if (operation == "Push") { cin >> val; if (p->left == NULL) { p->left = new Node(); p->left->val = val; p->left->parent = p; p = p->left; } else { p->right = new Node(); p->right->val = val; p->right->parent = p; p = p->right; } } else if (operation == "Pop") { while (visited[p->val]) p = p->parent; visited[p->val] = true; } } postorder(root); return 0; }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: JobFactory.cpp * Author: ssridhar * * Created on October 11, 2017, 1:06 PM */ #include "JobFactory.h" #include "StateFactory.h" #include "QueueFactory.h" webclient::Job_Factory* webclient::Job_Factory::m_pInstance = NULL; uint16_t webclient::Job_Factory::total_number_of_jobs = 0; webclient::Job* webclient::Job_Factory::p_jobs = NULL; /** * Job_Factory Constructor. */ webclient::Job_Factory::Job_Factory() { //Nothing } /** * ~Job_Factory Destructor. Clean up all the jobs created in the job factory. */ webclient::Job_Factory::~Job_Factory() { if (webclient::Job_Factory::p_jobs && webclient::Job_Factory::total_number_of_jobs > 0) { free(webclient::Job_Factory::p_jobs); webclient::Job_Factory::total_number_of_jobs = 0; } } /** * create_Jobs This function creates jobs based upon the specified input parameters. * @param starting_port Starting local port on the local host where to bind. * @param ending_port Ending local port on the host local where to bind. * @param local_ipv4_address Local IPv4 address on the local host where to bind. * @param remote_ipv4_address Remote IPv4 address of the remote host where to connect. * @param remote_address Remove host domain name. */ void webclient::Job_Factory::create_Jobs( uint16_t starting_port, uint16_t ending_port, uint32_t local_ipv4_address, uint32_t remote_ipv4_address, char remote_address[]) { webclient::Job_Factory::total_number_of_jobs = ending_port - starting_port + 1; webclient::Job_Factory::p_jobs = (webclient::Job *) calloc(total_number_of_jobs, sizeof (webclient::Job)); for (int index = 0; index < total_number_of_jobs; index++) { webclient::Job *p_job = (webclient::Job_Factory::p_jobs + index); if (p_job) { p_job->set_Job(starting_port + index, local_ipv4_address, remote_ipv4_address, remote_address); } } } /** * Enqueue_All_Jobs_to_specified_queue Invokes enqueue on the specified queue. * @param p_queue_id */ void webclient::Job_Factory::Enqueue_All_Jobs_to_specified_queue(void *p_queue_id) { uint64_t thread_data = (uint64_t) p_queue_id; uint8_t queue_id = (uint8_t) thread_data; if (queue_id < 0 || queue_id > webclient::State_Factory::get_total_number_of_states()) { LOG_ERROR("%s:%d Input parameters are invalid.\n", __FUNCTION__, __LINE__); return; } for (int index = 0; index < total_number_of_jobs; index++) { webclient::Job *p_job = (webclient::Job_Factory::p_jobs + index); if (p_job) { LOG_DEBUG("\n%s:%d queue_id=%d\n", __FUNCTION__, __LINE__, queue_id); webclient::Queue_Factory::Instance()->enqueue(queue_id, (void *) p_job, sizeof (p_job)); } } } /** * run_Job It invokes the state factory to run a job on this current state. * @param p_job_obj * @return */ int webclient::Job_Factory::run_Job(webclient::Job *p_job_obj) { uint8_t current_state = p_job_obj->return_current_job_state(); return webclient::State_Factory::run_job_on_this_current_state(current_state, p_job_obj); } /** * move_Job It changes the current state to the next state and enqueues the job to the next state. * @param p_job */ void webclient::Job_Factory::move_Job(void *p_job) { Job *p_job_obj = (Job *) p_job; if (!p_job_obj) { LOG_ERROR("%s:%d Input parameter(p_job) is invalid.\n", __FUNCTION__, __LINE__); return; } uint8_t current_state = p_job_obj->return_current_job_state(); uint8_t next_state = webclient::State_Factory::get_next_state(current_state); uint8_t init_state = webclient::State_Factory::get_init_state(); if (next_state == init_state) { LOG_DEBUG("%s:%s:%d Reached one loop of iteration..\n", __FILE__, __FUNCTION__, __LINE__); p_job_obj->increment_iteration_count(); } p_job_obj->set_current_job_state(next_state); LOG_DEBUG("%s:%s:%d Setting next state \ to=%d..\n", __FILE__, __FUNCTION__, __LINE__, p_job_obj->return_current_job_state()); //Enqueue it to the next queue. webclient::Queue_Factory::Instance()->enqueue(p_job_obj->return_current_job_state(), (void *) p_job_obj, sizeof (p_job_obj)); } /** * Instance It returns the job factory instance. * @return */ webclient::Job_Factory* webclient::Job_Factory::Instance() { if (!m_pInstance) { m_pInstance = new webclient::Job_Factory(); } return m_pInstance; }
/** * Lista * Implementacion de Lista Doblemente Enlazada con Templates **/ #ifndef __LISTA_DOBLEMENTE_ENLAZADA_H__ #define __LISTA_DOBLEMENTE_ENLAZADA_H__ #include "Nodo.h" #include "IteradorLista.h" #include "Comparador.h" /** * Una Lista es una colección de elementos ordenados secuencialmente. * Los elementos contenidos en una Lista pueden ser recorridos a través * del uso de Iteradores, entidad que encapsula el estado y comportamiento * de un instancia de recorrido sobre la estructura de datos. * */ template<class T> class Lista { private: /* Puntero al primer elemento de la lista */ Nodo<T>* primero; /* Puntero al último elemento de la lista */ Nodo<T>* ultimo; /* Comparador que utiliza para ordenar los elementos */ Comparador<T>* comparador; public: /** * pre : ninguna. * post: instancia vacia. Ordena los elementos de acuerdo al orden de * inserción. * */ Lista() { this->setPrimero(NULL); this->setUltimo(NULL); /* utiliza el comparador por defecto */ this->setComparador(new ComparadorConstante<T>()); } /** * pre : el comparador no es nulo. * post: instancia vacia. Ordena los elementos de acuerdo a comparador. * */ Lista(Comparador<T>* comparador) { this->setPrimero(NULL); this->setUltimo(NULL); this->setComparador(comparador); } /** * pre : ninguna. * post: libera los recursos asociados a la instancia. * */ virtual ~Lista() { IteradorLista<T> iterador = this->iterador(); while (iterador.tieneSiguiente()) { iterador.remover(); } delete this->getComparador(); } /* * Determina si la lista esta vacia o no */ bool estaVacia() { return (this->getPrimero() == NULL); } /** * pre : ninguna. * post: devuelve la cantidad de elementos que tiene la lista. * */ unsigned int tamanio() { unsigned int elementos = 0; IteradorLista<T> unIterador = this->iterador(); while (unIterador.tieneSiguiente()) { elementos++; unIterador.siguiente(); } return elementos; } /** * pre : ninguna. * post: agrega el dato a la estructura de lista, estructurando la * secuencia de elementos de acuerdo al comparador asociado. * */ void agregar(T dato) { bool insertar = false; Comparador<T>* comparador = this->getComparador(); /* itera por todos los elemento buscando el lugar para hacer * la inserción */ IteradorLista<T> iterador = this->iterador(); while (iterador.tieneSiguiente() && ! insertar) { if (comparador->comparar(iterador.get(), dato) == MAYOR) { /* lo inserta antes del elemento */ insertar = true; } else { /* pasa al siguiente elemento */ iterador.siguiente(); } } /* lo inserta en donde haya quedado el iterador */ iterador.insertar(dato); } /** * pre : ninguna. * post: devuelve una nueva instancia de iterador localizado en el * comienzo de la lista. * */ IteradorLista<T> iterador() { IteradorLista<T> unIterador(this); return unIterador; } /** * pre : ninguna. * post: busca el dato entre los elementos de la lista, utilizando * el comparador asignado. Devuelve un Iterador localizado * en el elemento si lo encuentra o en el fin de la lista * si no lo encuentra. * */ IteradorLista<T> buscar(T dato) { bool encontrado = false; Comparador<T>* comparador = this->getComparador(); /* itera por todos los elementos hasta encontrar el buscado o * no tener más elementos */ IteradorLista<T> iterador = this->iterador(); while (iterador.tieneSiguiente() && ! encontrado) { encontrado = comparador->comparar(dato, iterador.get()) == IGUAL; if (! encontrado){ iterador.siguiente(); } } return iterador; } private: /** * post: devuelve el primer nodo de la lista. */ Nodo<T>* getPrimero() { return this->primero; } /** * post: cambia el primer nodo de la lista. */ void setPrimero(Nodo<T>* nodo) { this->primero = nodo; } /** * post: devuelve el último nodo de la lista. */ Nodo<T>* getUltimo() { return this->ultimo; } /** * post: cambia el último nodo de la lista. */ void setUltimo(Nodo<T>* nodo) { this->ultimo = nodo; } /** * pre : ninguna. * post: devuelve el comparador usado para ordenar los elementos. */ Comparador<T>* getComparador() { return this->comparador; } /** * pre : la lista está vacia. * post: cambia el comparador usado para ordenar los elementos. */ void setComparador(Comparador<T>* comparador) { this->comparador = comparador; } /** * La clase IteradorLista<T> tiene acceso a todos los métodos * privados de Lista<T> ya que ambas entidades están vinculadas * intrínsecamente. */ friend class IteradorLista<T>; }; #endif
#ifndef _FA_MONITOR_COMM_COM #define _FA_MONITOR_COMM_COM #include "Comm.h" #include "fmt.h" class SerialCom : public Comm { public: SerialCom() : Comm(0) {} SerialCom(char* port, DWORD baudRate, BYTE byteSize, BYTE parity, BYTE stopBits) : Comm(0), port_(port), baudRate_(baudRate), byteSize_(byteSize), parity_(parity), stopBits_(stopBits) { //open(); } ~SerialCom() { //close(); } HANDLE open(); void receive(); void close(); HANDLE handle() { return handle_; } private: char* port_; DWORD baudRate_; /* Baudrate at which running */ /* CBR_110 110 CBR_300 300 CBR_600 600 CBR_1200 1200 CBR_2400 2400 CBR_4800 4800 CBR_9600 9600 CBR_14400 14400 CBR_19200 19200 CBR_38400 38400 CBR_56000 56000 CBR_57600 57600 CBR_115200 115200 CBR_128000 128000 CBR_256000 256000 */ BYTE byteSize_; /* Number of bits/byte, 4-8 */ BYTE parity_; /* 0-4=None,Odd,Even,Mark,Space */ /* NOPARITY 0 ODDPARITY 1 EVENPARITY 2 MARKPARITY 3 SPACEPARITY 4 */ BYTE stopBits_; /* 0,1,2 = 1, 1.5, 2 */ /* ONESTOPBIT 0 ONE5STOPBITS 1 TWOSTOPBITS 2 */ HANDLE handle_; }; #endif
#pragma once #include <set> #include <iostream> using namespace std; class BaseGameEntity; #define Dispatch MessageDispatcher::Instance() enum message_type { Msg_Bathroom, Msg_WantTissue }; struct Telegram { int Sender; int Receiver; int Msg; Telegram() : Sender(-1), Receiver(-1), Msg(-1) {} Telegram( int sender, int receiver, int msg) : Sender(sender), Receiver(receiver), Msg(msg) {} }; class MessageDispatcher { private: void Discharge(BaseGameEntity* pReceiver, const Telegram& msg); MessageDispatcher() {} MessageDispatcher(const MessageDispatcher&); public: static MessageDispatcher* Instance(); void Dispatch_Message( int sender, int receiver, int msg); };
//------------------------------------------------------------------------------ /* This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== FPUFlags FPUFlags::getCurrent () { unsigned int currentControl; const unsigned int newControl = 0; const unsigned int mask = 0; errno_t result = _controlfp_s (&currentControl, newControl, mask); if (result != 0) Throw (std::runtime_error ("error in _controlfp_s")); FPUFlags flags; flags.setMaskNaNs ((currentControl & _EM_INVALID) == _EM_INVALID); flags.setMaskDenormals ((currentControl & _EM_DENORMAL) == _EM_DENORMAL); flags.setMaskZeroDivides ((currentControl & _EM_ZERODIVIDE) == _EM_ZERODIVIDE); flags.setMaskOverflows ((currentControl & _EM_OVERFLOW) == _EM_OVERFLOW); flags.setMaskUnderflows ((currentControl & _EM_UNDERFLOW) == _EM_UNDERFLOW); //flags.setMaskInexacts ((currentControl & _EM_INEXACT) == _EM_INEXACT); flags.setFlushDenormals ((currentControl & _DN_FLUSH) == _DN_FLUSH); flags.setInfinitySigned ((currentControl & _IC_AFFINE) == _IC_AFFINE); Rounding rounding = roundDown; switch (currentControl & _MCW_RC) { case _RC_CHOP: rounding = roundChop; break; case _RC_UP: rounding = roundUp; break; case _RC_DOWN: rounding = roundDown; break; case _RC_NEAR: rounding = roundNear; break; default: Throw (std::runtime_error ("unknown rounding in _controlfp_s")); }; flags.setRounding (rounding); Precision precision = bits64; switch (currentControl & _MCW_PC ) { case _PC_64: precision = bits64; break; case _PC_53: precision = bits53; break; case _PC_24: precision = bits24; break; default: Throw (std::runtime_error ("unknown precision in _controlfp_s")); }; flags.setPrecision (precision); return flags; } static void setControl (const FPUFlags::Flag& flag, unsigned int& newControl, unsigned int& mask, unsigned int constant) { if (flag.is_set ()) { mask |= constant; if (flag.value ()) newControl |= constant; } } void FPUFlags::setCurrent (const FPUFlags& flags) { unsigned int newControl = 0; unsigned int mask = 0; setControl (flags.getMaskNaNs (), newControl, mask, _EM_INVALID); setControl (flags.getMaskDenormals (), newControl, mask, _EM_DENORMAL); setControl (flags.getMaskZeroDivides (), newControl, mask, _EM_ZERODIVIDE); setControl (flags.getMaskOverflows (), newControl, mask, _EM_OVERFLOW); setControl (flags.getMaskUnderflows (), newControl, mask, _EM_UNDERFLOW); //setControl (flags.getMaskInexacts(), newControl, mask, _EM_INEXACT); setControl (flags.getFlushDenormals (), newControl, mask, _DN_FLUSH); setControl (flags.getInfinitySigned (), newControl, mask, _IC_AFFINE); if (flags.getRounding ().is_set ()) { Rounding rounding = flags.getRounding ().value (); switch (rounding) { case roundChop: mask |= _MCW_RC; newControl |= _RC_CHOP; break; case roundUp: mask |= _MCW_RC; newControl |= _RC_UP; break; case roundDown: mask |= _MCW_RC; newControl |= _RC_DOWN; break; case roundNear: mask |= _MCW_RC; newControl |= _RC_NEAR; break; } } if (flags.getPrecision ().is_set ()) { switch (flags.getPrecision ().value ()) { case bits64: mask |= _MCW_PC; newControl |= _PC_64; break; case bits53: mask |= _MCW_PC; newControl |= _PC_53; break; case bits24: mask |= _MCW_PC; newControl |= _PC_24; break; } } unsigned int currentControl; errno_t result = _controlfp_s (&currentControl, newControl, mask); if (result != 0) Throw (std::runtime_error ("error in _controlfp_s")); }
#include<bits/stdc++.h> using namespace std; void findCommon(int arr1[],int arr2[],int m,int n) { int i=0,j=0; while(i<m && j<n) { if(arr1[i]<arr2[j]) i++; else if(arr2[j]<arr1[i]) j++; else { cout<<arr1[i]<<" "; i++; j++; } } } int main() { int m,n; cin>>m; int arr1[m]; for(int i=0;i<m;i++) cin>>arr1[i]; cin>>n; int arr2[n]; for(int i=0;i<n;i++) cin>>arr2[i]; findCommon(arr1,arr2,m,n); return 0; }
// Created on: 1999-11-18 // Created by: Andrey BETENEV // Copyright (c) 1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _STEPConstruct_AP203Context_HeaderFile #define _STEPConstruct_AP203Context_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> class StepBasic_Approval; class StepBasic_DateAndTime; class StepBasic_PersonAndOrganization; class StepBasic_SecurityClassificationLevel; class StepBasic_PersonAndOrganizationRole; class StepBasic_DateTimeRole; class StepBasic_ApprovalRole; class StepAP203_CcDesignPersonAndOrganizationAssignment; class StepAP203_CcDesignSecurityClassification; class StepAP203_CcDesignDateAndTimeAssignment; class StepAP203_CcDesignApproval; class StepBasic_ApprovalPersonOrganization; class StepBasic_ApprovalDateTime; class StepBasic_ProductCategoryRelationship; class StepShape_ShapeDefinitionRepresentation; class STEPConstruct_Part; class StepRepr_NextAssemblyUsageOccurrence; //! Maintains context specific for AP203 (required data and //! management information such as persons, dates, approvals etc.) //! It contains static entities (which can be shared), default //! values for person and organisation, and also provides //! tool for creating management entities around specific part (SDR). class STEPConstruct_AP203Context { public: DEFINE_STANDARD_ALLOC //! Creates tool and fills constant fields Standard_EXPORT STEPConstruct_AP203Context(); //! Returns default approval entity which //! is used when no other data are available Standard_EXPORT Handle(StepBasic_Approval) DefaultApproval(); //! Sets default approval Standard_EXPORT void SetDefaultApproval (const Handle(StepBasic_Approval)& app); //! Returns default date_and_time entity which //! is used when no other data are available Standard_EXPORT Handle(StepBasic_DateAndTime) DefaultDateAndTime(); //! Sets default date_and_time entity Standard_EXPORT void SetDefaultDateAndTime (const Handle(StepBasic_DateAndTime)& dt); //! Returns default person_and_organization entity which //! is used when no other data are available Standard_EXPORT Handle(StepBasic_PersonAndOrganization) DefaultPersonAndOrganization(); //! Sets default person_and_organization entity Standard_EXPORT void SetDefaultPersonAndOrganization (const Handle(StepBasic_PersonAndOrganization)& po); //! Returns default security_classification_level entity which //! is used when no other data are available Standard_EXPORT Handle(StepBasic_SecurityClassificationLevel) DefaultSecurityClassificationLevel(); //! Sets default security_classification_level Standard_EXPORT void SetDefaultSecurityClassificationLevel (const Handle(StepBasic_SecurityClassificationLevel)& sc); Standard_EXPORT Handle(StepBasic_PersonAndOrganizationRole) RoleCreator() const; Standard_EXPORT Handle(StepBasic_PersonAndOrganizationRole) RoleDesignOwner() const; Standard_EXPORT Handle(StepBasic_PersonAndOrganizationRole) RoleDesignSupplier() const; Standard_EXPORT Handle(StepBasic_PersonAndOrganizationRole) RoleClassificationOfficer() const; Standard_EXPORT Handle(StepBasic_DateTimeRole) RoleCreationDate() const; Standard_EXPORT Handle(StepBasic_DateTimeRole) RoleClassificationDate() const; //! Return predefined PersonAndOrganizationRole and DateTimeRole //! entities named 'creator', 'design owner', 'design supplier', //! 'classification officer', 'creation date', 'classification date', //! 'approver' Standard_EXPORT Handle(StepBasic_ApprovalRole) RoleApprover() const; //! Takes SDR (part) which brings all standard data around part //! (common for AP203 and AP214) and creates all the additional //! entities required for AP203 Standard_EXPORT void Init (const Handle(StepShape_ShapeDefinitionRepresentation)& sdr); //! Takes tool which describes standard data around part //! (common for AP203 and AP214) and creates all the additional //! entities required for AP203 //! //! The created entities can be obtained by calls to methods //! GetCreator(), GetDesignOwner(), GetDesignSupplier(), //! GetClassificationOfficer(), GetSecurity(), GetCreationDate(), //! GetClassificationDate(), GetApproval(), //! GetApprover(), GetApprovalDateTime(), //! GetProductCategoryRelationship() Standard_EXPORT void Init (const STEPConstruct_Part& SDRTool); //! Takes NAUO which describes assembly link to component //! and creates the security_classification entity associated to //! it as required by the AP203 //! //! Instantiated (or existing previously) entities concerned //! can be obtained by calls to methods //! GetClassificationOfficer(), GetSecurity(), //! GetClassificationDate(), GetApproval(), //! GetApprover(), GetApprovalDateTime() //! Takes tool which describes standard data around part //! (common for AP203 and AP214) and takes from model (or creates //! if missing) all the additional entities required by AP203 Standard_EXPORT void Init (const Handle(StepRepr_NextAssemblyUsageOccurrence)& nauo); Standard_EXPORT Handle(StepAP203_CcDesignPersonAndOrganizationAssignment) GetCreator() const; Standard_EXPORT Handle(StepAP203_CcDesignPersonAndOrganizationAssignment) GetDesignOwner() const; Standard_EXPORT Handle(StepAP203_CcDesignPersonAndOrganizationAssignment) GetDesignSupplier() const; Standard_EXPORT Handle(StepAP203_CcDesignPersonAndOrganizationAssignment) GetClassificationOfficer() const; Standard_EXPORT Handle(StepAP203_CcDesignSecurityClassification) GetSecurity() const; Standard_EXPORT Handle(StepAP203_CcDesignDateAndTimeAssignment) GetCreationDate() const; Standard_EXPORT Handle(StepAP203_CcDesignDateAndTimeAssignment) GetClassificationDate() const; Standard_EXPORT Handle(StepAP203_CcDesignApproval) GetApproval() const; Standard_EXPORT Handle(StepBasic_ApprovalPersonOrganization) GetApprover() const; Standard_EXPORT Handle(StepBasic_ApprovalDateTime) GetApprovalDateTime() const; //! Return entities (roots) instantiated for the part by method Init Standard_EXPORT Handle(StepBasic_ProductCategoryRelationship) GetProductCategoryRelationship() const; //! Clears all fields describing entities specific to each part Standard_EXPORT void Clear(); //! Initializes constant fields (shared entities) Standard_EXPORT void InitRoles(); //! Initializes all missing data which are required for assembly Standard_EXPORT void InitAssembly (const Handle(StepRepr_NextAssemblyUsageOccurrence)& nauo); //! Initializes ClassificationOfficer and ClassificationDate //! entities according to Security entity Standard_EXPORT void InitSecurityRequisites(); //! Initializes Approver and ApprovalDateTime //! entities according to Approval entity Standard_EXPORT void InitApprovalRequisites(); protected: private: //! Initializes all missing data which are required for part Standard_EXPORT void InitPart (const STEPConstruct_Part& SDRTool); Handle(StepBasic_Approval) defApproval; Handle(StepBasic_DateAndTime) defDateAndTime; Handle(StepBasic_PersonAndOrganization) defPersonAndOrganization; Handle(StepBasic_SecurityClassificationLevel) defSecurityClassificationLevel; Handle(StepBasic_PersonAndOrganizationRole) roleCreator; Handle(StepBasic_PersonAndOrganizationRole) roleDesignOwner; Handle(StepBasic_PersonAndOrganizationRole) roleDesignSupplier; Handle(StepBasic_PersonAndOrganizationRole) roleClassificationOfficer; Handle(StepBasic_DateTimeRole) roleCreationDate; Handle(StepBasic_DateTimeRole) roleClassificationDate; Handle(StepBasic_ApprovalRole) roleApprover; Handle(StepAP203_CcDesignPersonAndOrganizationAssignment) myCreator; Handle(StepAP203_CcDesignPersonAndOrganizationAssignment) myDesignOwner; Handle(StepAP203_CcDesignPersonAndOrganizationAssignment) myDesignSupplier; Handle(StepAP203_CcDesignPersonAndOrganizationAssignment) myClassificationOfficer; Handle(StepAP203_CcDesignSecurityClassification) mySecurity; Handle(StepAP203_CcDesignDateAndTimeAssignment) myCreationDate; Handle(StepAP203_CcDesignDateAndTimeAssignment) myClassificationDate; Handle(StepAP203_CcDesignApproval) myApproval; Handle(StepBasic_ApprovalPersonOrganization) myApprover; Handle(StepBasic_ApprovalDateTime) myApprovalDateTime; Handle(StepBasic_ProductCategoryRelationship) myProductCategoryRelationship; }; #endif // _STEPConstruct_AP203Context_HeaderFile
/* 题目:503. 下一个更大元素 II 链接:https://leetcode-cn.com/problems/next-greater-element-ii/ 知识点:单调栈+循环数组 */ class Solution { public: vector<int> nextGreaterElements(vector<int>& nums) { int n = nums.size(); vector<int> ans(n, -1); stack<int> s; // 单调栈,栈中下标对应的元素是单调递增的 // 取下标的时候,用 % 达到循环的效果 for (int i = 0; i < 2 * n - 1; i++) { while (!s.empty() && nums[s.top()] < nums[i % n]) { ans[s.top()] = nums[i % n]; s.pop(); } s.push(i % n); } return ans; } };
#ifndef VnaMarker_H #define VnaMarker_H // RsaToolbox #include "Definitions.h" // Qt #include <QObject> #include <QScopedPointer> namespace RsaToolbox { class Vna; class VnaTrace; class VnaMarker : public QObject { Q_OBJECT public: explicit VnaMarker(QObject *parent = 0); VnaMarker(const VnaMarker &other); VnaMarker(Vna *vna, VnaTrace *trace, uint index, QObject *parent = 0); VnaMarker(Vna *vna, QString traceName, uint index, QObject *parent = 0); ~VnaMarker(); QString name(); void setName(QString name); bool isDeltaOn(); bool isDeltaOff(); void deltaOn(bool isOn = true); void deltaOff(bool isOff = true); double y(); double x(); void coordinates(double &x, double &y); void setX(double x, SiPrefix prefix = SiPrefix::None); void searchForMax(); void searchForMin(); void searchFor(double y); void searchRightFor(double y); void searchRightForPeak(); void searchLeftFor(double y); void searchLeftForPeak(); // Calculate: void measureBandpassFilter(); void operator=(VnaMarker const &other); private: Vna *_vna; QScopedPointer<Vna> placeholder; QScopedPointer<VnaTrace> _trace; QString _traceName; uint _index; bool isFullyInitialized() const; void setSearchValue(double value); void searchForScpi(QString type); }; } #endif // VnaMarker_H
#include <systemc.h> #include <fstream> #include "tester.h" #include "adder4u.h" using namespace std; int sc_main(int argc, char *argv[]) { sc_signal <sc_uint<4> > mod_in1, mod_in2, mod_out; sc_signal <bool> mod_cin, mod_cout; sc_clock clk("clock", 10, SC_NS); Adder4 module_adder("adder"); module_adder.in1(mod_in1); module_adder.in2(mod_in2); module_adder.cin(mod_cin); module_adder.out(mod_out); module_adder.cout(mod_cout); Tester testbench("testbench1"); testbench.clk(clk); testbench.add_in1(mod_in1); testbench.add_in2(mod_in2); testbench.add_cin(mod_cin); sc_trace_file *t_file = sc_create_vcd_trace_file("test"); sc_trace(t_file, clk, "clock"); sc_trace(t_file, mod_in1, "a"); sc_trace(t_file, mod_in2, "b"); sc_trace(t_file, mod_cin, "cin"); sc_trace(t_file, mod_out, "s"); sc_trace(t_file, mod_cout, "cout"); sc_start(); }
#include "helper.h" #include "byteswap.h" std::ostream *PgSAHelpers::logout = &std::cout; int PgSAHelpers::numberOfThreads = 8; NullBuffer null_buffer; std::ostream null_stream(&null_buffer); // TIME clock_t checkpoint; clock_t PgSAHelpers::clock_checkpoint() { checkpoint = clock(); return checkpoint; // cout << "Clock reset!\n"; } unsigned long long int PgSAHelpers::clock_millis(clock_t checkpoint) { return (clock() - checkpoint) * (unsigned long long int) 1000 / CLOCKS_PER_SEC; } unsigned long long int PgSAHelpers::clock_millis() { return clock_millis(checkpoint); } chrono::steady_clock::time_point chronocheckpoint; chrono::steady_clock::time_point PgSAHelpers::time_checkpoint() { chronocheckpoint = chrono::steady_clock::now(); return chronocheckpoint; } unsigned long long int PgSAHelpers::time_millis(chrono::steady_clock::time_point checkpoint) { chrono::nanoseconds time_span = chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now() - checkpoint); return (double)time_span.count() / 1000000.0; } unsigned long long int PgSAHelpers::time_millis() { return time_millis(chronocheckpoint); } const size_t chunkSize = 10000000; void* PgSAHelpers::readArray(std::istream& in, size_t arraySizeInBytes) { if (in) { char* destArray = new char[arraySizeInBytes]; readArray(in, destArray, arraySizeInBytes); return (void*) destArray; } else throw(errno); } void PgSAHelpers::readArray(std::istream& in, void* destArray, size_t arraySizeInBytes) { if (in) { size_t length = arraySizeInBytes; char* ptr = (char*) destArray; size_t bytesLeft = length; while (bytesLeft > chunkSize) { in.read(ptr, chunkSize); ptr = ptr + chunkSize; bytesLeft -= chunkSize; } in.read(ptr, bytesLeft); } else throw(errno); } void PgSAHelpers::writeArray(std::ostream& out, void* srcArray, size_t arraySize, bool verbose) { size_t bytesLeft = arraySize; if (out) { while (bytesLeft > chunkSize) { out.write((char*) srcArray, chunkSize); srcArray = (void*) (((char*) srcArray) + chunkSize); bytesLeft -= chunkSize; } out.write((char*) srcArray, bytesLeft); } else throw(errno); if (verbose) cout << "Written " << arraySize << " bytes\n"; } void* PgSAHelpers::readWholeArray(std::istream& in, size_t& arraySizeInBytes) { if (in) { in.seekg(0, in.end); size_t length = in.tellg(); char* destArray = new char[length]; in.seekg(0, in.beg); char* ptr = destArray; size_t bytesLeft = length; while (bytesLeft > chunkSize) { in.read(ptr, chunkSize); ptr = ptr + chunkSize; bytesLeft -= chunkSize; } in.read(ptr, bytesLeft); arraySizeInBytes = length; return (void*) destArray; } else throw(errno); } void* PgSAHelpers::readWholeArrayFromFile(string srcFile, size_t& arraySizeInBytes) { time_checkpoint(); std::ifstream in(srcFile.c_str(), std::ifstream::binary); void* destArray = PgSAHelpers::readWholeArray(in, arraySizeInBytes); cout << "Read " << arraySizeInBytes << " bytes from " << srcFile << " in " << time_millis() << " msec \n"; return destArray; } void PgSAHelpers::writeArrayToFile(string destFile, void* srcArray, size_t arraySize) { time_checkpoint(); std::ofstream out(destFile.c_str(), std::ios::out | std::ios::binary); PgSAHelpers::writeArray(out, srcArray, arraySize); cout << "Write " << arraySize << " bytes to " << destFile << " in " << time_millis() << " msec \n"; } void PgSAHelpers::writeStringToFile(string destFile, const string &src) { writeArrayToFile(destFile, (void*) src.data(), src.length()); } bool PgSAHelpers::plainTextWriteMode = false; void PgSAHelpers::writeReadMode(std::ostream &dest, bool plainTextWriteMode) { dest << (plainTextWriteMode?TEXT_MODE_ID:BINARY_MODE_ID) << "\n"; } bool PgSAHelpers::confirmTextReadMode(std::istream &src) { string readMode; src >> readMode; if (readMode != TEXT_MODE_ID && readMode != BINARY_MODE_ID) { fprintf(stderr, "Expected READ MODE id (not: %s)\n", readMode.c_str()); exit(EXIT_FAILURE); } char check = src.get(); return readMode == TEXT_MODE_ID; } template<> void PgSAHelpers::writeValue(std::ostream &dest, const uint8_t value, bool plainTextWriteMode) { if (plainTextWriteMode) dest << (uint16_t) value << endl; else dest.write((char *) &value, sizeof(uint8_t)); } template<> void PgSAHelpers::readValue(std::istream &src, uint8_t &value, bool plainTextReadMode) { if (plainTextReadMode) { uint16_t temp; src >> temp; value = (uint8_t) temp; } else src.read((char *) &value, sizeof(uint8_t)); } void PgSAHelpers::writeUIntByteFrugal(std::ostream &dest, uint64_t value) { while (value >= 128) { uint8_t yByte = 128 + (value % 128); dest.write((char *) &yByte, sizeof(uint8_t)); value = value / 128; } uint8_t yByte = value; dest.write((char *) &yByte, sizeof(uint8_t)); } bool PgSAHelpers::bytePerReadLengthMode = false; void PgSAHelpers::readReadLengthValue(std::istream &src, uint16_t &value, bool plainTextReadMode) { if (bytePerReadLengthMode) readValue<uint8_t>(src, (uint8_t&) value, plainTextReadMode); else readValue<uint16_t>(src, value, plainTextReadMode); } void PgSAHelpers::writeReadLengthValue(std::ostream &dest, const uint16_t value) { if (bytePerReadLengthMode) writeValue<uint8_t>(dest, (uint8_t) value, plainTextWriteMode); else writeValue<uint16_t>(dest, value, plainTextWriteMode); } string PgSAHelpers::toString(unsigned long long value) { std::ostringstream oss; oss << value; return oss.str(); }; string PgSAHelpers::toMB(unsigned long long value, unsigned char decimalPlaces) { std::ostringstream oss; int power = 1000000; oss << value / power; if (decimalPlaces > 0) { oss << "."; for(int i = 0; i < decimalPlaces; i++) oss << ((value / (power /= 10)) % 10); } return oss.str(); } string PgSAHelpers::toString(long double value, unsigned char decimalPlaces) { std::ostringstream oss; oss << (long long int) value; if (decimalPlaces > 0) { oss << "."; int power = 1000000; unsigned long long decimals = (value - (long long int) value) * power; for(int i = 0; i < decimalPlaces; i++) oss << ((decimals / (power /= 10)) % 10); } return oss.str(); } unsigned long long int PgSAHelpers::powuint(unsigned long long int base, int exp) { if (exp == 0) return 1; if (exp == 1) return base; unsigned long long int tmp = PgSAHelpers::powuint(base, exp/2); if (exp%2 == 0) return tmp * tmp; else return base * tmp * tmp; } struct LUT { char complementsLut[256]; char sym2val[256]; char val2sym[5]; LUT() { memset(complementsLut, 0, 256); complementsLut['A'] = 'T'; complementsLut['a'] = 'T'; complementsLut['C'] = 'G'; complementsLut['c'] = 'G'; complementsLut['G'] = 'C'; complementsLut['g'] = 'C'; complementsLut['T'] = 'A'; complementsLut['t'] = 'A'; complementsLut['N'] = 'N'; complementsLut['n'] = 'N'; complementsLut['U'] = 'A'; complementsLut['u'] = 'A'; complementsLut['Y'] = 'R'; complementsLut['y'] = 'R'; complementsLut['R'] = 'Y'; complementsLut['r'] = 'Y'; complementsLut['K'] = 'M'; complementsLut['k'] = 'M'; complementsLut['M'] = 'K'; complementsLut['m'] = 'K'; complementsLut['B'] = 'V'; complementsLut['b'] = 'V'; complementsLut['D'] = 'H'; complementsLut['d'] = 'H'; complementsLut['H'] = 'D'; complementsLut['h'] = 'D'; complementsLut['V'] = 'B'; complementsLut['v'] = 'B'; val2sym[0] = 'A'; val2sym[1] = 'C'; val2sym[2] = 'G'; val2sym[3] = 'T'; val2sym[4] = 'N'; memset(sym2val, -1, 256); for(char i = 0; i < 5; i++) sym2val[val2sym[i]] = i; } } instance; char* complementsLUT = instance.complementsLut; char* sym2val = instance.sym2val; char* val2sym = instance.val2sym; uint8_t PgSAHelpers::symbol2value(char symbol) { return sym2val[symbol]; } char PgSAHelpers::value2symbol(uint8_t value) { return val2sym[value]; } uint8_t PgSAHelpers::mismatch2code(char actual, char mismatch) { uint8_t actualValue = symbol2value(actual); uint8_t mismatchValue = symbol2value(mismatch); return mismatchValue - (mismatchValue > actualValue?1:0); } char PgSAHelpers::code2mismatch(char actual, uint8_t code) { uint8_t actualValue = symbol2value(actual); return value2symbol(code < actualValue?code:(code+1)); } char PgSAHelpers::reverseComplement(char symbol) { return complementsLUT[symbol]; } void PgSAHelpers::reverseComplementInPlace(char* start, const std::size_t N) { char* left = start - 1; char* right = start + N; while (--right > ++left) { char tmp = complementsLUT[*left]; *left = complementsLUT[*right]; *right = tmp; } if (left == right) *left = complementsLUT[*left]; } string PgSAHelpers::reverseComplement(string kmer) { size_t kmer_length = kmer.size(); string revcomp; revcomp.resize(kmer_length); size_t j = kmer_length; for(size_t i = 0; i < kmer_length; i++) revcomp[--j] = complementsLUT[kmer[i]]; return revcomp; } void PgSAHelpers::reverseComplementInPlace(string &kmer) { reverseComplementInPlace((char*) kmer.data(), kmer.length()); } double PgSAHelpers::qualityScore2approxCorrectProb(string quality) { double val = 1; for (char q : quality) { switch (q) { case 33:case 34:case 35:case 36: return 0; case 37: val *= 0.6018928294465028; break; case 38: val *= 0.683772233983162; break; case 39: val *= 0.748811356849042; break; case 40: val *= 0.800473768503112; break; case 41: val *= 0.8415106807538887; break; case 42: val *= 0.8741074588205833; break; case 43: val *= 0.9; break; case 44: val *= 0.9205671765275718; break; case 45: val *= 0.9369042655519807; break; case 46: val *= 0.9498812766372727; break; case 47: val *= 0.9601892829446502; break; case 48: val *= 0.9683772233983162; break; case 49: val *= 0.9748811356849042; break; case 50: val *= 0.9800473768503112; break; case 51: val *= 0.9841510680753889; break; case 52: val *= 0.9874107458820583; break; case 53: val *= 0.99; break; case 54: val *= 0.9920567176527572; break; case 55: val *= 0.993690426555198; break; case 56: val *= 0.9949881276637272; break; case 57: val *= 0.996018928294465; break; case 58: val *= 0.9968377223398316; break; case 59: val *= 0.9974881135684904; break; case 60: val *= 0.9980047376850312; break; case 61: val *= 0.9984151068075389; break; case 62: val *= 0.9987410745882058; break; case 63: val *= 0.999; break; case 64: val *= 0.9992056717652757; break; case 65: val *= 0.9993690426555198; break; case 66: val *= 0.9994988127663728; break; case 67: val *= 0.9996018928294464; break; case 68: val *= 0.9996837722339832; break; default: ; } } return pow(val, 1.0/quality.length()); } double PgSAHelpers::qualityScore2correctProb(string quality) { double val = 1; for (char q : quality) { switch (q) { case 33: return 0; case 34: val *= 0.2056717652757185; break; case 35: val *= 0.36904265551980675; break; case 36: val *= 0.49881276637272776; break; case 37: val *= 0.6018928294465028; break; case 38: val *= 0.683772233983162; break; case 39: val *= 0.748811356849042; break; case 40: val *= 0.800473768503112; break; case 41: val *= 0.8415106807538887; break; case 42: val *= 0.8741074588205833; break; case 43: val *= 0.9; break; case 44: val *= 0.9205671765275718; break; case 45: val *= 0.9369042655519807; break; case 46: val *= 0.9498812766372727; break; case 47: val *= 0.9601892829446502; break; case 48: val *= 0.9683772233983162; break; case 49: val *= 0.9748811356849042; break; case 50: val *= 0.9800473768503112; break; case 51: val *= 0.9841510680753889; break; case 52: val *= 0.9874107458820583; break; case 53: val *= 0.99; break; case 54: val *= 0.9920567176527572; break; case 55: val *= 0.993690426555198; break; case 56: val *= 0.9949881276637272; break; case 57: val *= 0.996018928294465; break; case 58: val *= 0.9968377223398316; break; case 59: val *= 0.9974881135684904; break; case 60: val *= 0.9980047376850312; break; case 61: val *= 0.9984151068075389; break; case 62: val *= 0.9987410745882058; break; case 63: val *= 0.999; break; case 64: val *= 0.9992056717652757; break; case 65: val *= 0.9993690426555198; break; case 66: val *= 0.9994988127663728; break; case 67: val *= 0.9996018928294464; break; case 68: val *= 0.9996837722339832; break; case 69: val *= 0.999748811356849; break; case 70: val *= 0.9998004737685031; break; case 71: val *= 0.9998415106807539; break; case 72: val *= 0.9998741074588205; break; case 73: val *= 0.9999; break; default: val *= 1; } } return pow(val, 1.0/quality.length()); } int PgSAHelpers::readsSufPreCmp(const char* suffixPart, const char* prefixRead) { while (*suffixPart) { if (*suffixPart > *prefixRead) return 1; if (*suffixPart++ < *prefixRead++) return -1; } return 0; } int PgSAHelpers::strcmplcp(const char* lStrPtr, const char* rStrPtr, int length) { int i = 0; while (length - i >= 4) { int cmp = bswap_32(*(uint32_t*) lStrPtr) - bswap_32(*(uint32_t*) rStrPtr); if (cmp != 0) break; lStrPtr += 4; rStrPtr += 4; i += 4; } while (i < length) { i++; int cmp = *(unsigned char*)(lStrPtr++) - *(unsigned char*)(rStrPtr++); if (cmp > 0) return 1; if (cmp < 0) return -1; } return 0; }
#include "chemcontroller.h" #include <QtMath> // ДОБАВИТЬ ИСКЛЮЧЕНИЯ ChemController::ChemController(QObject *parent) : QObject(parent) { /* Name : CRC-16 Poly : 0x8005 x^16 + x^15 + x^2 + 1 Init : 0xFFFF Revert: true XorOut: 0x0000 Check : 0x4B37 ("123456789") MaxLen: 4095 bytes */ Crc16Table = new quint16 [256]{ 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441, 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041, 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040 }; _SerialPort = new QSerialPort(this); } ChemController::~ChemController(){ delete[] Crc16Table; // Удаление при завершении _SerialPort -> close(); // закрываем соединение при выходе delete _SerialPort; } quint16 ChemController::Crc16(quint8 pcBlock[], int len) { quint16 crc = 0xFFFF; for (int i = 0; i < len; i++) { crc = (quint16)((crc >> 8) ^ Crc16Table[((crc & 0xFF) ^ pcBlock[i])]); } return crc; } qint16 ChemController::BitConvent16(QByteArray data, int startoffset){ int first = data[startoffset]; int second = data[startoffset +1]; return (qint16) (first | (second << 8)); } qint32 ChemController::BitConvent32(QByteArray data, int startoffset){ int first = (data[startoffset]) | (data[startoffset + 1] << 8); int second = (data[startoffset + 2]) | (data[startoffset + 3] << 8); return (quint32) ((quint16) first | (quint32) (second << 16)); } void ChemController:: OpenPort(){ if (_SerialPort->isOpen()){ _SerialPort ->close(); } _SerialPort -> setPortName("com4"); // указываем параметры порта (далее) _SerialPort -> setBaudRate(QSerialPort::Baud57600); _SerialPort -> setDataBits(QSerialPort::Data8); _SerialPort -> setParity(QSerialPort::NoParity); _SerialPort -> setStopBits(QSerialPort :: OneStop); _SerialPort -> setFlowControl(QSerialPort:: NoFlowControl); _SerialPort -> open(QSerialPort::ReadWrite); } void ChemController:: CheckConnect(){ // Запрос статуса и проверка соединения QByteArray receivedData = ""; quint8 data[1]; data[0] = CMD_NOP; quint8 status; try{ qDebug() << "Checkconnect"; receivedData = writeAndRead(data,1); status = receivedData[0]; } catch (ChemException &err){ qDebug() << "Ответ не соответствует ожиданию."; throw ChemException("Ответ не соответствует ожиданию."); } if (status == RESP_OK && receivedData.size() == 1){ _isConnected = true; } else { _isConnected = false; qDebug() << "Ошибка при подключении к устройству!"; throw ChemException("Ошибка при подключении к устройству!"); } } void ChemController :: ClosePort(){ qDebug() << "Устройство отключено."; _SerialPort -> close(); } bool ChemController :: isConnected() const{ return _isConnected; } QByteArray ChemController::writeAndRead(quint8 *Data, int len){ // Функция отправка и чтения данных QByteArray SentData = ""; // Данные, посылаемые в порт quint16 crc = 0; crc = Crc16(Data, len); // высчитывается контрольную сумму CRC16 for (int i = 0; i< len; i++){ SentData.append((quint8)(Data[i])); } SentData.append((quint8)(crc & 0xff)); SentData.append((quint8)(crc>>8)); qDebug() << "writeAndRead"; qDebug() << SentData.toHex().toUpper(); SentData = SentData.toHex().toUpper(); // Переводим данные в шестанцатеричный код и отправляем его _SerialPort->write(":"); _SerialPort->write(SentData); _SerialPort-> write("="); _SerialPort->waitForReadyRead(1000); // ждем 1с, пока устройство обработает данные и ответит QString data = _SerialPort->readAll(); data = data.left(data.indexOf('=')); // читаем данные до символа "=" if (data.indexOf(":")== (-1)){ // проверка данных qDebug() << "Package start not found"; throw ChemException("Package start not found"); } if (data.length() < 5){ qDebug() << "Package too short"; throw ChemException("Package too short"); } if (data.length() % 2 == 0){ qDebug() << "Incorrect packet length"; throw ChemException("Incorrect packet length"); } data = data.remove(QChar(':')); // удаляем символ ":" //qDebug() << data; QByteArray b_data; // Создаем массив в котором будет храниться переведенная контрольная сумма b_data.resize(data.length() / 2); for (int i = 0; i < data.length() / 2; i ++ ){ b_data[i] =(data.mid(i*2, 2)).toInt(nullptr, 16); } b_data.resize(b_data.length() - 2); qDebug() << b_data; return b_data; } bool ChemController::IsOpen(){ return _SerialPort->isOpen(); } // Получить Получить значение АЦП термометра // <param name="id">Номер термометра, 1 или 2</param> // <returns>Значение АЦП</returns> quint16 ChemController::GetADCTemper(int id){ quint8 data[2]; data[0] = CMD_READ_TADC_VAL; data[1] = (quint8) id; QByteArray receivedData = ""; try { qDebug() << "Запрос значения АЦП" + QString::number(id) +"го Термометра"; receivedData = writeAndRead(data, 2); } catch (...) { qDebug() << "Произошла ошибка при запросе значения АЦП" + QString::number(id) +"го Термометра"; throw ChemException("Ошибка. Ошибка подключения."); } if (receivedData.size() == 5){ quint16 num = BitConvent16(receivedData, 3); return num; } else { qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } quint16 ChemController:: GetADCPress(int id){ quint8 data[2]; data[0] = CMD_READ_ADCPRESS_VAL; data[1] = (quint8) id; QByteArray receivedData = ""; try { qDebug() << "Запрос значения АЦП" + QString::number(id) +"го Пресса"; receivedData = writeAndRead(data, 2); } catch (...) { qDebug() << "Произошла ошибка при запросе значения АЦП" + QString::number(id) +"го Пресса"; throw ChemException("Ошибка. Ошибка подключения."); } if (receivedData.size() == 5){ quint16 num = BitConvent16(receivedData,3); return num; } else { qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } // <summary> // Получить температуру данного термометра // <param name="id">Номер термометра, 1 или 2</param> // <returns>Температура</returns> qreal ChemController:: GetTemper(int id){ quint8 data[2]; data[0] = CMD_READ_TEMPER; data[1] = (quint8) id; QByteArray receivedData = ""; try { qDebug() << "Запрос температуры " + QString::number(id) + " Термометра"; receivedData = writeAndRead(data, 2); } catch (...) { qDebug() << "Произошла ошибка при запросе температуры " + QString::number(id) + " Термометра" ; throw ChemException("Ошибка. Ошибка подключения."); } if (receivedData.size() == 5){ qint16 num =BitConvent16(receivedData,3); return (qreal) qRound((num *10) / 32.0) / 10.0; } else { qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } qreal ChemController:: GetSuppTemper(){ quint8 data[1]; data[0] = CMD_TSTAT_GET_SUPP_TPR; QByteArray receivedData = ""; try { qDebug() << "Запрос SuppTemper"; receivedData = writeAndRead(data, 1); } catch (...) { qDebug() << "Произошла ошибка при запросе SuppTemper" ; throw ChemException("Ошибка. Ошибка подключения."); } if (receivedData.size() == 4){ qint16 num = BitConvent16(receivedData,2); return (qreal) qRound((num *10) / 32.0) / 10.0; } else { qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } // Установить коэффициенты для преобразования кода АЦП в температуру (T = k*code + b) // <param name="id">Номер термометра, 1 или 2</param> // <param name="k">Коэффициент k</param> // <param name="b">Коэффициент b</param> void ChemController::TStatSetTCoeffs(int id, qreal k, qreal b){ quint8 data[18]; data[0] = CMD_SET_TCOEFFS; data[1] = (quint8) id; QByteArray receivedData = ""; qint64 ck = (qint64) (k *qPow(2,29)); qint64 cb = (qint64) (b *qPow(2,29)); for (int i = 0; i < 8; i++) { data[i + 2] = (quint8)(( ck >> (8 * i)) & 0xFF); data[i + 10] = (quint8)(( cb >> (8 * i)) & 0xFF); } try { qDebug() << "Установка коэффициенты для преобразования кода АЦП в температуру в " + QString::number(id) + "й Термометр"; receivedData = writeAndRead(data, 18); } catch (...) { qDebug() << "Произошла ошибка при установка коэффициенты для преобразования кода АЦП в " + QString::number(id) + "ом Термометре"; throw ChemException("Ошибка. Ошибка подключения."); } if (receivedData.size() != 3){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } // Команда для получения мощности устройства int ChemController:: TStatGetPower(){ quint8 data[1]; data[0] = CMD_TSTAT_GET_PWR; QByteArray receivedData = ""; try { qDebug() << "Запрос мощности устройства"; receivedData = writeAndRead(data, 1); } catch (...) { qDebug() << "Произошла ошибка при запросе мощности устройства"; throw ChemException("Ошибка. Ошибка подключения."); } if (receivedData.size() != 4) { qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } else { return BitConvent16(receivedData,2); } } bool ChemController:: TStatGetStatus(){ quint8 data[1]; QByteArray receiveData = ""; try { qDebug() << "Запрос статуса термостата"; receiveData = writeAndRead(data, 1); } catch (...) { qDebug() << "Произошла ошибка при запросе состояния термостата"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() != 3){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } quint8 status = receiveData[2]; if (status != 0) return true; else return false; } void ChemController ::TStatEnable(){ quint8 data[1]; data[0] = CMD_TSTAT_ENABLE; QByteArray receivedData; quint8 status; try { qDebug() << "Включение термостата"; receivedData = writeAndRead(data, 1); status = receivedData[0]; } catch (ChemException &err) { qDebug() << "Включение термостата произошло неудачно"; throw ChemException("Ошибка. Ошибка подключения."); } if (receivedData.size() == 2 && status == RESP_OK){ // size = 2 qDebug() << "Термостат включен"; } else { qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } void ChemController ::TStatDisable(){ quint8 data[1]; data[0] = CMD_TSTAT_DISABLE; QByteArray receivedData = ""; quint8 status; try { qDebug() << "Отключение термастата"; receivedData = writeAndRead(data, 1); status = receivedData[0]; } catch (ChemException &err) { qDebug() << "Отключение термостат произошло неудачно"; throw ChemException("Ошибка. Ошибка подключения."); } if (receivedData.size() == 2 && status == RESP_OK){ // size = 2 qDebug() << "Термостат выключен"; } else { qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); //emit error_( "Ошибка. Ответ не соответствует ожиданиям."); } } void ChemController::TStatSetPWM(qint16 val){ quint8 data[3]; data[0] = CMD_TSTAT_SET_PWM; QByteArray receiveData = ""; for (int i = 0; i < 2; i++) { data[i + 1] = (quint8)(( val >> (8 * i)) & 0xFF); } try { qDebug() << "Установка значение PWM"; receiveData = writeAndRead(data, 3); } catch (...) { qDebug() << "Произошла ошибка при установке установке значения PWM"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() != 2){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } void ChemController::TStatSetPID(qreal kP, qreal kI, qreal kD, qreal A){ quint8 data[9]; QByteArray receiveData = ""; data[0] = CMD_TSTAT_SET_PID; // Установить PID for (int i = 0; i < 2; i++) { data[i + 1] = (quint8)(( (quint16) (kP * qPow(2,5)) >> (8 * i) ) & 0xFF); data[i + 3] = (quint8)(( (quint16) (kI * qPow(2,5)) >> (8 * i) ) & 0xFF); data[i + 5] = (quint8)(( (quint16) (kD * qPow(2,5)) >> (8 * i) ) & 0xFF); data[i + 7] = (quint8)(( (quint16) (A * qPow(2,5)) >> (8 * i) ) & 0xFF); } try { qDebug() << "Установка значение PID"; receiveData = writeAndRead(data, 9); } catch (...) { qDebug() << "Произошла ошибка при установке установке значения PID"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() != 2){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } void ChemController::TStatSetTemper(qreal temper){ quint8 data[3]; QByteArray receiveData = ""; data[0] = CMD_TSTAT_SET_TEMPER; for (int i = 0; i < 2; i++){ data[i + 1] = (quint8)(( (qint16) (temper * qPow(2,5)) >> (8 * i) ) & 0xFF); } try { qDebug() << "Установка TStatSetTemper"; receiveData = writeAndRead(data, 3); } catch (...) { qDebug() << "Произошла ошибка при установки TStatTemper"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size()!= 2){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } void ChemController::ReacSetPCoeffs(int ch, qreal k, qreal b){ quint8 data[18]; QByteArray receiveData = ""; data[0] = CMD_REAC_SET_COEFF; qint64 ck = (qint64) (k * qPow(2,29)); qint64 cb = (qint64) (b * qPow(2,29)); data[1] =(quint8) (ch); for (int i = 0; i <8; i++){ data[i + 2] = (quint8)(( ck >> (8 * i)) & 0xFF); data[i + 10] = (quint8)(( cb >> (8 * i)) & 0xFF); } try { qDebug() << "Установка ReacPCoeffs"; receiveData = writeAndRead(data, 18); } catch (...) { qDebug() << "Произошла ошибка при установки ReacPCoeffs"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size()!= 3){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } bool ChemController::ReacIsEnable(){ quint8 data[1]; data[0] = CMD_REAC_GET_STATE; QByteArray receiveData = ""; quint8 status; try { qDebug() << "Проверка Состояния Реактора"; receiveData = writeAndRead(data); status = receiveData[2]; } catch (...) { qDebug() << "Произошла ошибка при проверки состояния Реактора"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size()!= 3){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } return status == 0 ? false : true; } void ChemController:: ReacEnable(bool val){ quint8 data[2]; QByteArray receiveData = ""; data[0] = CMD_REAC_SET_STATE; data[1] = (quint8)(val ? 1 : 0); try { qDebug() << "Отправка Состояния Реактора"; receiveData = writeAndRead(data, 2); } catch (...) { qDebug() << "Произошла ошибка при отправки состояния Реактора"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size()!= 2){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } void ChemController::ReacCalibration(){ quint8 data[1]; QByteArray receiveData = ""; data[0] = CMD_REAC_CALIBR; try { qDebug() << "Запуск калибровки реактора"; receiveData = writeAndRead(data); } catch (...) { qDebug() << "Произошла ошибка при запуске Калибровки Реактора"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size()!= 2){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } qreal ChemController::ReacGetCurrPress(int ch){ quint8 data[2]; QByteArray receiveData = ""; data[0] = CMD_REAC_GET_CURR_PRESS; data[1] = (quint8) ch; try { qDebug() << "Запрос значения ReacCurrPress"; receiveData = writeAndRead(data,2); } catch (...) { qDebug() << "Произошла ошибка при запросе значения ReacCurrPress"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() == 5){ qint16 t = BitConvent16(receiveData, 3); return (qreal) (qRound(t * 10 / 32.0)) / 10.0; } else { qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } int ChemController::ReacGetSyrVol(int ch){ quint8 data[2]; QByteArray receiveData = ""; data[0] = CMD_REAC_GET_VOL; data[1] = (quint8) ch; try { qDebug() << "Запрос значения REAC VOl"; receiveData = writeAndRead(data,2); } catch (...) { qDebug() << "Произошла ошибка при запросе значения REAC VOl"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() != 7){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } qint32 num = BitConvent32(receiveData, 3); return num; } void ChemController::ReacSetMotorVel(int ch, int val){ quint8 data[6]; QByteArray receiveData = ""; data[0] = CMD_REAC_SET_FREQ; data[1] = (quint8) ch; for (int i = 0; i < 4; i ++){ data[i + 2] = (quint8)(( val >> (8 * i)) & 0xFF); } try { qDebug() << "Установка Частоты Реактора"; receiveData = writeAndRead(data, 6); } catch (...) { qDebug() << "Произошла ошибка при Установки Частоты Реактора"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() != 2){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } void ChemController::ReacSyrSetMode(int ch, int mode){ quint8 data[3]; QByteArray receiveData = ""; data[0] = CMD_REAC_SYR_SET_MODE; data[1] = (quint8) ch; data[2] = (quint8) mode; try { qDebug() << "Установка Режима Реактора"; receiveData = writeAndRead(data, 3); } catch (...) { qDebug() << "Произошла ошибка при Установки Режима Реактора"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size()!= 4){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } int ChemController::ReacSyrGetMode(int ch){ QByteArray receiveData = ""; quint8 data[2]; data[0] = CMD_REAC_SYR_GET_MODE; data[1] = (quint8) ch; try { qDebug() << "Запрос Режима Реактора"; receiveData = writeAndRead(data, 2); } catch (...) { qDebug() << "Произошла ошибка при Запросе Режима Реактора"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size()!= 3){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } return (quint8) receiveData[2]; } void ChemController::ReacSetPID(qreal kP, qreal kI, qreal kD, qreal A){ QByteArray receiveData = ""; quint8 data[9]; data[0] = CMD_REAC_SET_PID; for (int i = 0; i < 2; i++){ data[i + 1] = (quint8)(( (quint16) (kP * qPow(2,5)) >> (8 * i) ) & 0xFF); data[i + 3] = (quint8)(( (quint16) (kI * qPow(2,5)) >> (8 * i) ) & 0xFF); data[i + 5] = (quint8)(( (quint16) (kD * qPow(2,5)) >> (8 * i) ) & 0xFF); data[i + 7] = (quint8)(( (quint16) (A * qPow(2,5)) >> (8 * i) ) & 0xFF); } try { qDebug() << "Установка PID"; receiveData = writeAndRead(data, 9); } catch (...) { qDebug() << "Произошла ошибка при Установке PID"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() != 2){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } void ChemController::ReacSetPress(int ch, qreal val){ QByteArray receiveData = ""; quint8 data[4]; data[0] = CMD_REAC_SET_PRESS; data[1] = (quint8) ch; for (int i = 0; i < 2; i++){ data[i + 2] = (quint8)(( (quint16) (val * qPow(2,5)) >> (8 * i) ) & 0xFF); } try { qDebug() << "Установка React Press"; receiveData = writeAndRead(data, 4); } catch (...) { qDebug() << "Произошла ошибка при Установке React Press"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() != 2){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } void ChemController::ReacSetMaxSteps(int ch, int val){ QByteArray receiveData = ""; quint8 data[6]; data[0] = CMD_REAC_SET_MAX_STEPS; data[1] = (quint8) ch; for (int i = 0; i < 4;i ++){ data[i + 2] = (quint8)(( val >> (8 * i)) & 0xFF); } try { qDebug() << "Установка React MaxSteps"; receiveData = writeAndRead(data, 6); } catch (...) { qDebug() << "Произошла ошибка при Установке React MaxSteps"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() != 3){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } int ChemController::ReacGetMaxSteps(int ch){ QByteArray receiveData = ""; quint8 data[2]; data[0] = CMD_REAC_GET_MAX_STEPS; data[1] = (quint8) ch; try { qDebug() << "Запрос React MaxSteps"; receiveData = writeAndRead(data, 2); } catch (...) { qDebug() << "Произошла ошибка при Запросе React MaxSteps"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() != 7){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } return BitConvent32(receiveData, 3); } void ChemController::ReacSetPsc(int ch, int val){ QByteArray receiveData = ""; quint8 data[4]; data[0] = CMD_REAC_SET_PSC; data[1] = (quint8) ch; for (int i = 0; i < 2;i ++){ data[i + 2] = (quint8)(( (quint16) val >> (8 * i)) & 0xFF); } try { qDebug() << "Установка React PSC"; receiveData = writeAndRead(data, 4); } catch (...) { qDebug() << "Произошла ошибка при Установка React PSC"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size()!= 3){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } int ChemController::ReacGetPsc(int ch){ QByteArray receiveData = ""; quint8 data[2]; data[0] = CMD_REAC_GET_PSC; data[1] = (quint8) ch; try { qDebug() << "Запрос React PSC"; receiveData = writeAndRead(data, 2); } catch (...) { qDebug() << "Произошла ошибка при Запросе React PSC"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size()!= 5){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } return BitConvent16(receiveData, 3); } int ChemController::ReacGetMotorVel(int ch){ QByteArray receiveData = ""; quint8 data[2]; data[0] = CMD_REAC_GET_FREQ; data[1] = (quint8) ch; try { qDebug() << "Запрос React MotorVel"; receiveData = writeAndRead(data, 2); } catch (...) { qDebug() << "Произошла ошибка при Запросе React MotorVel"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() != 7){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } return BitConvent32(receiveData, 3); } qreal ChemController::ReacGetSuppPress(int ch){ QByteArray receiveData = ""; quint8 data[2]; data[0] = CMD_REAC_GET_SUPP_PRESS; data[1] = (quint8) ch; try { qDebug() << "Запрос React SuppPress"; receiveData = writeAndRead(data, 2); } catch (...) { qDebug() << "Произошла ошибка при Запросе React SuppPress"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() == 5){ qint16 t = BitConvent16(receiveData, 3); return (qreal) qRound(t * 10 / 32.0) / 10.0; } else { qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } } bool ChemController::ReacGetCalibrFlag(){ QByteArray receiveData = ""; quint8 data[1]; data[0] = CMD_REAC_GET_CALIB_FLAG; try { qDebug() << "Запрос React CalibrFlag"; receiveData = writeAndRead(data); } catch (...) { qDebug() << "Произошла ошибка при Запросе React CalibrFlag"; throw ChemException("Ошибка. Ошибка подключения."); } if (receiveData.size() != 3){ qDebug() << "Ошибка. Ответ не соответствует ожиданиям."; throw ChemException("Ошибка. Ответ не соответствует ожиданиям."); } quint8 status = receiveData[2]; return status == 0 ? false : true; }
#include "GnMeshPCH.h" #include "GnInterfacePCH.h" #include "GnInterface.h" GnImplementRootRTTI(GnInterface); GnInterface::GnInterface() : mPushCount( 0 ), mTegID( -1 ) { SetIsHover( false ); SetIsCantPush( true ); SetIsDisable( false ); SetIsEnablePushMove( false ); mParentUseNode.retain(); } GnInterface::GnInterface(const gchar* pcImageName) : mPushCount( 0 ), mTegID( -1 ) { SetIsHover( false ); SetIsCantPush( true ); SetIsDisable( false ); SetIsEnablePushMove( false ); mParentUseNode.retain(); CreateDefaultImage( pcImageName ); } bool GnInterface::Push(float fPointX, float fPointY) { if( IfUseCheckCollision( fPointX, fPointY ) == false ) return false; Push(); return true; } bool GnInterface::PushUp(float fPointX, float fPointY) { if( IsPush() == false ) return false; // if( IfUseCheckCollision( fPointX, fPointY ) == false ) // { //// PushUp(); // return false; // } PushUp(); return true; } bool GnInterface::PushMove(float fPointX, float fPointY) { if( IfUseCheckCollision( fPointX, fPointY ) == false ) return false; return true; } void GnInterface::Push() { AddPushCount(); } void GnInterface::PushUp() { SubPushCount(); } void GnInterface::AddMeshToParentNode(Gn2DMeshObject *pChild) { GetParentUseNode()->addChild( pChild->GetMesh(), 0 ); } void GnInterface::AddToParentNode(GnInterfaceNode* pNode) { GetParentUseNode()->addChild( pNode, 0 ); } void GnInterface::AddInterfaceToParentNode(GnInterface* pInterface) { GetParentUseNode()->addChild( pInterface->GetParentUseNode(), 0 ); } void GnInterface::AddMeshToParentNode(Gn2DMeshObject *pChild, gtint iZorder) { GetParentUseNode()->addChild( pChild->GetMesh(), iZorder ); } void GnInterface::AddToParentNode(GnInterfaceNode* pNode, gtint iZorder) { GetParentUseNode()->addChild( pNode, iZorder ); } void GnInterface::AddInterfaceToParentNode(GnInterface* pInterface, gtint iZorder) { GetParentUseNode()->addChild( pInterface->GetParentUseNode(), iZorder ); } bool GnInterface::CreateDefaultImage(const gchar* pcImageName) { if( pcImageName == NULL ) mpsDefaultMesh = Gn2DMeshObject::Create( false ); else mpsDefaultMesh = Gn2DMeshObject::CreateFromTextureFile( pcImageName ); if( mpsDefaultMesh == NULL ) return false; SetContentSize( mpsDefaultMesh->GetSize().x, mpsDefaultMesh->GetSize().y ); AddMeshToParentNode( mpsDefaultMesh ); SetPosition( GetPosition() ); return true; }
#include <iostream> using namespace std; int main() { int a, b, ostatok; cout << "Vvedite znachenie A B\n"; cin >> a >> b; ostatok = a % b; cout << ostatok; }
/* Name: Copyright: Author: Xiaodong Xiao Date: 2019/9/13 20:16:30 Description: */ #include <bits/stdc++.h> #include <time.h> using namespace std; class Solution { public: /*下面居然能AC */ // vector<int> searchRange(vector<int>& nums, int target) { // if (nums.size() == 0) return {-1, -1}; // // int lo = -1, hi = -1; // for (int i = 0; i < nums.size(); ++i) if (nums[i] == target) { // lo = i; // break; // } // // if (lo == -1) return {-1, -1}; // for (int i = nums.size() - 1; i > -1; --i) if (nums[i] == target) { // hi = i; // break; // } // // return {lo, hi}; // } vector<int> searchRange(vector<int>& nums, int target) { if (nums.size() == 0) return {-1, -1}; vector<int> ans{-1, -1}; int lo = 0, hi = nums.size() - 1; while (lo < hi) { int mid = lo + (hi - lo>> 1); if (nums[mid] >= target) hi = mid; else lo = mid + 1; } if (nums[hi] != target) return ans; ans[0] = hi; lo = 0, hi = nums.size() - 1; while (lo < hi) { int mid = lo + (hi - lo + 1 >> 1); if (nums[mid] <= target) lo = mid; else hi = mid - 1; } ans[1] = lo; return ans; } }; int main() { vector<int> nums = {5,7,7,8,8,10}; int t = 8; auto xxd = Solution(); clock_t s, e; s = clock(); auto ans = xxd.searchRange(nums, t); e = clock(); cout << (double)(e - s) / CLOCKS_PER_SEC << endl; cout << endl << endl << ans[0] << " " << ans[1] << endl; return 0; }
//realwindow.hpp //ABC that handles real windows - creation, etc. //Created by Lewis Hosie //14-11-11 #include "varlist.hpp" #include "inputpasser.hpp" #ifndef e_realwindow #define e_realwindow class realwindow{ //It's like a realdoll, but sexier public: varholder thevars; virtual void takeevents(inputpasser& theinputpasser) = 0; virtual void swapbuffers(const renderer& therenderer) = 0; virtual void blitbuffer(char* thebuffer) = 0; virtual void putpixel(char* thepixel, int x, int y) = 0; }; #endif
// Ed Callaghan // Plotting script - for use with output of singleChannelFilling.cxx // April 2016 void drawAll() { TFile *fin = new TFile("singlePlots.root") ; int nch = 8 ; TCanvas *cAll = new TCanvas() ; cAll->Divide(3,3) ; TGaxis *aCa = new TGaxis(0.95, 0.1, 0.95, 0.9, 31.5, 34.5, 510, "+L") ; aCa->SetLineColor(3) ; aCa->SetLabelColor(3) ; // green TCanvas *ct ; char cname[15] ; for (int ich = 0 ; ich < nch ; ich++) { sprintf(cname, "timePlot_%d", ich) ; ct = (TCanvas *) fin->Get(cname) ; cAll->cd(ich + 1) ; ct->DrawClonePad() ; aCa->Draw() ; } ct = (TCanvas *) fin->Get("totalChargeEnergy") ; cAll->cd(9) ; ct->DrawClonePad() ; aCa->Draw() ; cAll->SetCanvasSize(2400, 1800) ; cAll->SaveAs("all-channels.pdf") ; cAll->SaveAs("all-channels.png") ; cAll->SetCanvasSize(800, 600) ; }
#include<bits/stdc++.h> using namespace std; typedef long long ll; main() { ll k, l; while(cin>>k>>l) { ll i, ans=0; for(i=l; i>1; ) { if(i%k==0) { i=i/k; ans++; } else { cout<<"NO"<<endl; return 0; } } cout<<"YES"<<endl<<ans-1<<endl; } return 0; }
// Simple C++ program to display "Hello World" // Header file for input output functions #include <stdio.h> #include<iostream> using namespace std; //main function - // where the execution of program begins int main() { //prints hello world //long version-- std::cout << "Hello World" << std::endl; cout<<"Hello World"; return 0; }
#include <iostream> using std::cout; using std::endl; using std::cin; #include <stdlib.h> #include <time.h> #include <vector> #include <cstring> const static int adjacentRooms[20][3] = { {1, 4, 7}, {0, 2, 9}, {1, 3, 11}, {2, 4, 13}, {0, 3, 5}, {4, 6, 14}, {5, 7, 16}, {0, 6, 8}, {7, 9, 17}, {1, 8, 10}, {9, 11, 18}, {2, 10, 12}, {11, 13, 19}, {3, 12, 14}, {5, 13, 15}, {14, 16, 19}, {6, 15, 17}, {8, 16, 18}, {10, 17, 19}, {12, 15, 18} }; class YetiGame { private: int numRooms; int currentRoom, startingPosition; int YetiRoom, batRoom1, batRoom2, pitRoom1, pitRoom2; int YetiStart, bat1Start, bat2Start; bool playerAlive, YetiAlive; int numArrows; void PlacePits(); void PlaceBats(); void PlaceYeti(); void PlacePlayer(); bool IsValidMove(int); bool IsRoomAdjacent(int, int); int Move(int); void InspectCurrentRoom(); void PerformAction(int); void MoveStartledYeti(int); void PlayGame(); void PlayAgain(); void PrintInstructions(); public: void StartGame(); YetiGame(); }; // default constructor YetiGame::YetiGame() { numRooms = 20; } // This function prints the instructions for the game void YetiGame::PrintInstructions() { char wait; cout << " Welcome to 'Hunt the Yeti'! " << endl; cout << " The Yeti lives in a cave of 20 rooms. Each room has 3 tunnels leading to" << endl; cout << " other rooms. (Look at a dodecahedron to see how this works - if you don't know" << endl; cout << " what a dodecahedron is, ask someone). \n" << endl; cout << " Hazards: \n" << endl; cout << " Bottomless pits - two rooms have bottomless pits in them. If you go there, you " << endl; cout << " fall into the pit (& lose!) \n" << endl; cout << " Super bats - two other rooms have super bats. If you go there, a bat grabs you" << endl; cout << " and takes you to some other room at random. (Which may be troublesome). Once the" << endl; cout << " bat has moved you, that bat moves to another random location on the map.\n\n" << endl; cout << " Yeti" << endl; cout << " The Yeti is not bothered by hazards (he has sucker feet and is too big for a" << endl; cout << " bat to lift). Usually he is asleep. Two things wake him up: you shooting an" << endl; cout << " arrow or you entering his room. If the Yeti wakes he moves (p=.75) one room or " << endl; cout << " stays still (p=.25). After that, if he is where you are, he eats you up and you lose!\n" << endl; cout << " You \n" << endl; cout << " Each turn you may move, save or shoot an arrow using the commands move, save, & shoot." << endl; cout << " Moving: you can move one room (thru one tunnel)." << endl; cout << " Arrows: you have 5 arrows. You lose when you run out. You aim by telling the" << endl; cout << " computer the rooms you want the arrow to go to. If the arrow can't go that way" << endl; cout << " (if no tunnel), the arrow will not fire." << endl; cout << " Warnings" << endl; cout << " When you are one room away from a Yeti or hazard, the computer says:" << endl; cout << " Yeti: 'hear footsteps'" << endl; cout << " Bat: 'hear wings flapping'" << endl; cout << " Pit: 'I feel cold air'" << endl; cout << endl; cout << "Press Y to return to the main menu." << endl; cin >> wait; } // This function will place two bats throughout the map void YetiGame::PlaceBats() { srand(time(NULL)); bool validRoom = false; while (!validRoom) { batRoom1 = rand() % 20 + 1; if (batRoom1 != YetiRoom) validRoom = true; } validRoom = false; while (!validRoom) { batRoom2 = rand() % 20 + 1; if (batRoom2 != YetiRoom && batRoom2 != batRoom1) validRoom = true; } bat1Start = batRoom1; bat2Start = batRoom2; } // places the pits void YetiGame::PlacePits() { srand(time(NULL)); pitRoom1 = rand() % 20 + 1; pitRoom2 = rand() % 20 + 1; } // this function randomly places the yeti in a room void YetiGame::PlaceYeti() { srand(time(NULL)); int randomRoom = rand() % 20 + 1; YetiRoom = randomRoom; YetiStart = YetiRoom; } // place the player in room 0 void YetiGame::PlacePlayer() { startingPosition = 0; currentRoom = Move(0); } bool YetiGame::IsValidMove(int roomID) { if (roomID < 0) return false; if (roomID > numRooms) return false; if (!IsRoomAdjacent(currentRoom, roomID)) return false; return true; } bool YetiGame::IsRoomAdjacent(int roomA, int roomB) { for (int j = 0; j < 3; j++) { if (adjacentRooms[roomA][j] == roomB) { return true; } } return false; } int YetiGame::Move(int newRoom) { return newRoom; } // Inspects the current room. // checks if you are adjacent to a hazard // it will print out the room description void YetiGame::InspectCurrentRoom() { srand(time(NULL)); if (currentRoom == YetiRoom) { cout << "The Yeti killed you!!!" << endl; cout << "LOSER!!!" << endl; PlayAgain(); } else if (currentRoom == batRoom1 || currentRoom == batRoom2) { int roomBatsLeft = currentRoom; bool validNewBatRoom = false; bool isBatRoom = false; cout << "Snatched by superbats!!" << endl; if (currentRoom == pitRoom1 || currentRoom == pitRoom2) cout << "Luckily, the bats saved you from the bottomless pit!!" << endl; while (!isBatRoom) { currentRoom = Move(rand() % 20 + 1); if (currentRoom != batRoom1 && currentRoom != batRoom2) isBatRoom = true; } cout << "The bats moved you to room "; cout << currentRoom << endl; InspectCurrentRoom(); if (roomBatsLeft == batRoom1) { while (!validNewBatRoom) { batRoom1 = rand() % 19 + 1; if (batRoom1 != YetiRoom && batRoom1 != currentRoom) validNewBatRoom = true; } } else { while (!validNewBatRoom) { batRoom2 = rand() % 19 + 1; if (batRoom2 != YetiRoom && batRoom2 != currentRoom) validNewBatRoom = true; } } } else if (currentRoom == pitRoom1 || currentRoom == pitRoom2) { cout << "fell in a pit!!!" << endl; cout << "GAME OVER!!!" << endl; PlayAgain(); } else { cout << "You are in room "; cout << currentRoom << endl; if (IsRoomAdjacent(currentRoom, YetiRoom)) { cout << "You hear loud footsteps..." << endl; } if (IsRoomAdjacent(currentRoom, batRoom1) || IsRoomAdjacent(currentRoom, batRoom2)) { cout << "hear wings flapping..." << endl; } if (IsRoomAdjacent(currentRoom, pitRoom1) || IsRoomAdjacent(currentRoom, pitRoom2)) { cout << "You feel cold air..." << endl; } cout << "Tunnels lead to rooms " << endl; for (int j = 0; j < 3; j++) { cout << adjacentRooms[currentRoom][j]; cout << " "; } cout << endl; } } // performs the action of the command or prints out an error. void YetiGame::PerformAction(int cmd) { int newRoom; switch (cmd) { case 1: cout << "Which room? " << endl; try { cin >> newRoom; // Check if the user inputted a valid room id if (IsValidMove(newRoom)) { currentRoom = Move(newRoom); InspectCurrentRoom(); } else { cout << "You cannot move there." << endl; } } catch (...) // Try...Catch block will catch if the user inputs text instead of a number. { cout << "You cannot move there." << endl; } break; case 2: if (numArrows > 0) { cout << "Which room? " << endl; try { cin >> newRoom; // Check if the user inputted a valid room id, then move player if (IsValidMove(newRoom)) { numArrows--; if (newRoom == YetiRoom) { cout << "ARGH.. there is and arrow in me!" << endl; cout << "Congratulations! You killed the yeti! You Win." << endl; cout << "Press 'Y' to return to the main menu." << endl; YetiAlive = false; cin >> newRoom; cin.clear(); cin.ignore(10000, '\n'); } else { cout << "Miss! But the yeti is scared" << endl; MoveStartledYeti(YetiRoom); cout << "Arrows Left: "; cout << numArrows << endl; if (YetiRoom == currentRoom) { cout << "The yeti attacked you! You have died." << endl; cout << "Game Over!" << endl; PlayAgain(); } } } else { cout << "You cannot shoot there." << endl; } } catch (...) // Try...Catch block will catch if the user inputs text instead of a number. { cout << "You cannot shoot there." << endl; } } else { cout << "You do not have any arrows!" << endl; } break; case 3: cout << "Quitting current game." << endl; playerAlive = false; break; default: cout << "You cannot do that. You can move, shoot, save or quit." << endl; break; } } // this function moves the yeti randomly to a room void YetiGame::MoveStartledYeti(int roomNum) { srand(time(NULL)); int rando = rand() % 3; if (rando != 3) YetiRoom = adjacentRooms[roomNum][rando]; } // This restarts the map from the begiinning void YetiGame::PlayAgain() { char reply; cout << "Would you like to replay the same map? Enter Y to play again." << endl; cin >> reply; if (reply == 'y' || reply == 'Y') { currentRoom = startingPosition; YetiRoom = YetiStart; batRoom1 = bat1Start; batRoom2 = bat2Start; cout << "please dont fail this time. \n" << endl; InspectCurrentRoom(); } else { playerAlive = false; } } void YetiGame::PlayGame() { int choice; bool validChoice = false; cout << "Running the game..." << endl; // Initialize the game PlaceYeti(); PlaceBats(); PlacePits(); PlacePlayer(); // game set up playerAlive = true; YetiAlive = true; numArrows = 5; //Inspects room InspectCurrentRoom(); // Main game loop. while (playerAlive && YetiAlive) { cout << "Enter an action choice." << endl; cout << "1) Move" << endl; cout << "2) Shoot" << endl; cout << "3) Quit" << endl; cout << ">>> "; do { validChoice = true; cout << "Please make a selection: "; try { cin >> choice; switch (choice) { case 1: PerformAction(choice); break; case 2: PerformAction(choice); break; case 3: PerformAction(choice); break; default: validChoice = false; cout << "Invalid choice. Please try again." << endl; cin.clear(); cin.ignore(10000, '\n'); break; } } catch (...) { validChoice = false; cout << "Invalid choice. Please try again." << endl; cin.clear(); cin.ignore(10000, '\n'); } } while (validChoice == false); } } //begins game loop void YetiGame::StartGame() { srand(time(NULL)); int choice; bool validChoice; bool keepPlaying; YetiStart = bat1Start = bat2Start = -1; do { keepPlaying = true; cout << "Welcome to Hunt The Yeti." << endl; cout << "1: Play Game" << endl; cout << "2: Print Instructions" << endl; cout << "3: Quit" << endl; do { validChoice = true; cout << "Please make a selection: "; try { cin >> choice; switch (choice) { case 1: PlayGame(); break; case 2: PrintInstructions(); break; case 3: cout << "Quitting." << endl; keepPlaying = false; break; default: validChoice = false; cout << "Invalid choice. Please try again." << endl; cin.clear(); cin.ignore(10000, '\n'); break; } } catch (...) { validChoice = false; cout << "Invalid choice. Please try again." << endl; cin.clear(); cin.ignore(10000, '\n'); } } while (validChoice == false); } while (keepPlaying); } int main() { // create Yeti Game YetiGame game; // start the game game.StartGame(); }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #ifdef MVFST_USE_LIBEV #include <quic/common/QuicAsyncUDPSocketImpl.h> #include <cstring> #include <sstream> #include <stdexcept> #include <fcntl.h> #include <netinet/in.h> #include <sys/socket.h> #include <unistd.h> namespace quic { QuicAsyncUDPSocketImpl::QuicAsyncUDPSocketImpl(QuicBackingEventBase* evb) { if (evb) { eventBase_ = dynamic_cast<QuicLibevEventBase*>(evb); CHECK(eventBase_) << "EventBase must be QuicLibevEventBase"; CHECK(eventBase_->isInEventBaseThread()); ev_init(&readWatcher_, QuicAsyncUDPSocketImpl::readWatcherCallback); readWatcher_.data = this; } } QuicAsyncUDPSocketImpl::~QuicAsyncUDPSocketImpl() { if (fd_ != -1) { close(); } if (eventBase_) { ev_io_stop(eventBase_->getLibevLoop(), &readWatcher_); } } void QuicAsyncUDPSocketImpl::pauseRead() { readCallback_ = nullptr; updateReadWatcher(); } void QuicAsyncUDPSocketImpl::resumeRead(ReadCallback* cb) { CHECK(!readCallback_) << "A read callback is already installed"; CHECK(fd_ != -1) << "Socket must be initialized before a read callback is attached"; CHECK(cb) << "A non-null callback is required to resume read"; readCallback_ = cb; updateReadWatcher(); } ssize_t QuicAsyncUDPSocketImpl::write( const folly::SocketAddress& address, const std::unique_ptr<folly::IOBuf>& buf) { if (fd_ == -1) { throw QuicAsyncUDPSocketException("socket is not initialized"); } sockaddr_storage addrStorage; address.getAddress(&addrStorage); int msg_flags = 0; struct msghdr msg; if (!connected_) { msg.msg_name = reinterpret_cast<void*>(&addrStorage); msg.msg_namelen = sizeof(addrStorage); } else { if (connectedAddress_ != address) { throw QuicAsyncUDPSocketException( "wrong destination address for connected socket"); } msg.msg_name = nullptr; msg.msg_namelen = 0; } iovec vec[16]; size_t iovec_len = buf->fillIov(vec, sizeof(vec) / sizeof(vec[0])).numIovecs; if (UNLIKELY(iovec_len == 0)) { buf->coalesce(); vec[0].iov_base = const_cast<uint8_t*>(buf->data()); vec[0].iov_len = buf->length(); iovec_len = 1; } msg.msg_iov = const_cast<struct iovec*>(vec); msg.msg_iovlen = iovec_len; msg.msg_control = nullptr; msg.msg_controllen = 0; msg.msg_flags = 0; return ::sendmsg(fd_, &msg, msg_flags); } int QuicAsyncUDPSocketImpl::getGSO() { // TODO: Implement GSO return -1; } int QuicAsyncUDPSocketImpl::writem( folly::Range<folly::SocketAddress const*> /* addrs */, const std::unique_ptr<folly::IOBuf>* /* bufs */, size_t /* count */) { LOG(INFO) << __func__; return -1; } void QuicAsyncUDPSocketImpl::setAdditionalCmsgsFunc( folly::Function<folly::Optional<folly::SocketOptionMap>()>&& /* additionalCmsgsFunc */) { LOG(WARNING) << "Setting an additional cmsgs function is not implemented for QuicAsyncUDPSocketImpl"; } bool QuicAsyncUDPSocketImpl::isBound() const { return bound_; } const folly::SocketAddress& QuicAsyncUDPSocketImpl::address() const { if (!bound_) { throw QuicAsyncUDPSocketException("socket is not bound"); } return localAddress_; } void QuicAsyncUDPSocketImpl::attachEventBase(QuicBackingEventBase* /* evb */) { LOG(INFO) << __func__; } void QuicAsyncUDPSocketImpl::close() { CHECK(eventBase_->isInEventBaseThread()); if (readCallback_) { auto cob = readCallback_; readCallback_ = nullptr; cob->onReadClosed(); } updateReadWatcher(); if (fd_ != -1 && ownership_ == FDOwnership::OWNS) { ::close(fd_); } fd_ = -1; } void QuicAsyncUDPSocketImpl::detachEventBase() { LOG(INFO) << __func__; } void QuicAsyncUDPSocketImpl::setCmsgs( const folly::SocketOptionMap& /* cmsgs */) { throw std::runtime_error("setCmsgs is not implemented."); } void QuicAsyncUDPSocketImpl::appendCmsgs( const folly::SocketOptionMap& /* cmsgs */) { throw std::runtime_error("appendCmsgs is not implemented."); } void QuicAsyncUDPSocketImpl::init(sa_family_t family) { if (fd_ != -1) { // Socket already initialized. return; } if (family != AF_INET && family != AF_INET6) { throw QuicAsyncUDPSocketException("address family not supported"); } NetworkFdType fd = ::socket(family, SOCK_DGRAM, IPPROTO_UDP); if (fd == -1) { throw QuicAsyncUDPSocketException("error creating socket", errno); } SCOPE_FAIL { ::close(fd); }; int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) { throw QuicAsyncUDPSocketException("error getting socket flags", errno); } if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0) { throw QuicAsyncUDPSocketException( "error setting socket nonblocking flag", errno); } int sockOptVal = 1; if (reuseAddr_ && ::setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, &sockOptVal, sizeof(sockOptVal)) != 0) { throw QuicAsyncUDPSocketException( "error setting reuse address on socket", errno); } if (reusePort_ && ::setsockopt( fd, SOL_SOCKET, SO_REUSEPORT, &sockOptVal, sizeof(sockOptVal)) != 0) { throw QuicAsyncUDPSocketException( "error setting reuse port on socket", errno); } fd_ = fd; ownership_ = FDOwnership::OWNS; } void QuicAsyncUDPSocketImpl::bind(const folly::SocketAddress& address) { // TODO: remove dependency on folly::SocketAdress since this pulls in // folly::portability and other headers which should be avoidable. if (fd_ == -1) { init(address.getFamily()); } // bind to the address sockaddr_storage addrStorage; address.getAddress(&addrStorage); auto& saddr = reinterpret_cast<sockaddr&>(addrStorage); if (::bind( fd_, (struct sockaddr*)&saddr, saddr.sa_family == AF_INET6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in)) != 0) { throw QuicAsyncUDPSocketException( "error binding socket to " + address.describe(), errno); } bzero(&saddr, sizeof(saddr)); socklen_t len = sizeof(saddr); if (::getsockname(fd_, &saddr, &len) != 0) { throw QuicAsyncUDPSocketException("error retrieving local address", errno); } localAddress_.setFromSockaddr(&saddr, len); bound_ = true; } void QuicAsyncUDPSocketImpl::connect(const folly::SocketAddress& address) { if (fd_ == -1) { init(address.getFamily()); } sockaddr_storage addrStorage; address.getAddress(&addrStorage); auto saddr = reinterpret_cast<sockaddr&>(addrStorage); if (::connect(fd_, &saddr, sizeof(saddr)) != 0) { throw QuicAsyncUDPSocketException( "error connecting UDP socket to " + address.describe(), errno); } connected_ = true; connectedAddress_ = address; if (!localAddress_.isInitialized()) { bzero(&saddr, sizeof(saddr)); socklen_t len = sizeof(saddr); if (::getsockname(fd_, &saddr, &len) != 0) { throw QuicAsyncUDPSocketException( "error retrieving local address", errno); } localAddress_.setFromSockaddr(&saddr, len); } } void QuicAsyncUDPSocketImpl::setDFAndTurnOffPMTU() { if (fd_ == -1) { throw QuicAsyncUDPSocketException("socket is not initialized"); } int optname = 0; int optval = 0; int level = 0; switch (localAddress_.getFamily()) { case AF_INET: level = IPPROTO_IP; optname = IP_MTU_DISCOVER; optval = IP_PMTUDISC_PROBE; break; case AF_INET6: level = IPPROTO_IPV6; optname = IPV6_MTU_DISCOVER; optval = IPV6_PMTUDISC_PROBE; break; } if (optname && optval && ::setsockopt(fd_, level, optname, &optval, sizeof(optval)) != 0) { throw QuicAsyncUDPSocketException("Failed to disable pmtud", errno); } } void QuicAsyncUDPSocketImpl::setErrMessageCallback( ErrMessageCallback* errMessageCallback) { errMessageCallback_ = errMessageCallback; } int QuicAsyncUDPSocketImpl::getGRO() { LOG(INFO) << __func__; return -1; } ssize_t QuicAsyncUDPSocketImpl::recvmsg(struct msghdr* msg, int flags) { return ::recvmsg(fd_, msg, flags); } int QuicAsyncUDPSocketImpl::recvmmsg( struct mmsghdr* msgvec, unsigned int vlen, unsigned int flags, struct timespec* timeout) { return ::recvmmsg(fd_, msgvec, vlen, (int)flags, timeout); } bool QuicAsyncUDPSocketImpl::setGRO(bool /* bVal */) { LOG(INFO) << __func__; return useGro_; } void QuicAsyncUDPSocketImpl::applyOptions( const folly::SocketOptionMap& options, folly::SocketOptionKey::ApplyPos pos) { for (const auto& opt : options) { if (opt.first.applyPos_ == pos) { if (::setsockopt( fd_, opt.first.level, opt.first.optname, &opt.second, sizeof(opt.second)) != 0) { throw QuicAsyncUDPSocketException( "failed to apply socket options", errno); } } } } QuicBackingEventBase* QuicAsyncUDPSocketImpl::getEventBase() const { return eventBase_; } void QuicAsyncUDPSocketImpl::setFD(NetworkFdType fd, FDOwnership ownership) { fd_ = fd; ownership_ = ownership; updateReadWatcher(); } // PRIVATE void QuicAsyncUDPSocketImpl::evHandleSocketRead() { CHECK(readCallback_); CHECK(readCallback_->shouldOnlyNotify()); readCallback_->onNotifyDataAvailable(*this); } void QuicAsyncUDPSocketImpl::updateReadWatcher() { CHECK(eventBase_) << "EventBase not initialized"; ev_io_stop(eventBase_->getLibevLoop(), &readWatcher_); if (readCallback_) { ev_io_set(&readWatcher_, fd_, EV_READ); ev_io_start(eventBase_->getLibevLoop(), &readWatcher_); } } // STATIC void QuicAsyncUDPSocketImpl::fromMsg( ReadCallback::OnDataAvailableParams& /* params */, struct msghdr& /* msg */) { LOG(INFO) << __func__; } // STATIC std::string QuicAsyncUDPSocketException::getMessage( const std::string& message, int errnoCopy) { std::stringstream msgStream; msgStream << message << ". errno=" << errnoCopy << " (" << std::strerror(errnoCopy) << ")"; return msgStream.str(); } // STATIC PRIVATE void QuicAsyncUDPSocketImpl::readWatcherCallback( struct ev_loop* /*loop*/, ev_io* w, int /*revents*/) { auto sock = static_cast<QuicAsyncUDPSocketImpl*>(w->data); CHECK(sock) << "Watcher callback does not have a valid QuicAsyncUDPSocketImpl pointer"; CHECK(sock->getEventBase()) << "Socket does not have an event base attached"; CHECK(sock->getEventBase()->isInEventBaseThread()) << "Watcher callback on wrong event base"; sock->evHandleSocketRead(); } } // namespace quic #endif // MVFST_USE_LIBEV
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "Direct3D11Renderer/RenderTarget/SwapChain.h" #include "Direct3D11Renderer/RenderTarget/RenderPass.h" #include "Direct3D11Renderer/Guid.h" // For "WKPDID_D3DDebugObjectName" #include "Direct3D11Renderer/D3D11.h" #include "Direct3D11Renderer/Mapping.h" #include "Direct3D11Renderer/Direct3D11Renderer.h" #include <Renderer/ILog.h> #include <Renderer/IAssert.h> #include <Renderer/IAllocator.h> #include <VersionHelpers.h> //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] namespace { namespace detail { //[-------------------------------------------------------] //[ Global definitions ] //[-------------------------------------------------------] typedef LONG NTSTATUS, *PNTSTATUS; typedef NTSTATUS (WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); //[-------------------------------------------------------] //[ Global functions ] //[-------------------------------------------------------] // From https://stackoverflow.com/a/36545162 RTL_OSVERSIONINFOW getRealOSVersion() { const HMODULE hModule = ::GetModuleHandleW(L"ntdll.dll"); if (hModule) { PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(4191) // warning C4191: 'reinterpret_cast': unsafe conversion from 'FARPROC' to '`anonymous-namespace'::detail::RtlGetVersionPtr' const RtlGetVersionPtr functionPointer = reinterpret_cast<RtlGetVersionPtr>(::GetProcAddress(hModule, "RtlGetVersion")); PRAGMA_WARNING_POP if (nullptr != functionPointer) { RTL_OSVERSIONINFOW rovi = { 0 }; rovi.dwOSVersionInfoSize = sizeof(rovi); if (0x00000000 == functionPointer(&rovi)) { return rovi; } } } RTL_OSVERSIONINFOW rovi = { 0 }; return rovi; } // "IsWindows10OrGreater()" isn't practically usable // - See "Windows Dev Center" -> "Version Helper functions" -> "IsWindows10OrGreater" at https://msdn.microsoft.com/en-us/library/windows/desktop/dn424972(v=vs.85).aspx // "For Windows 10, IsWindows10OrGreater returns false unless the application contains a manifest that includes a compatibility section that contains the GUID that designates Windows 10." bool isWindows10OrGreater() { return (getRealOSVersion().dwMajorVersion >= 10); } void handleDeviceLost(const Direct3D11Renderer::Direct3D11Renderer& direct3D11Renderer, HRESULT result) { // If the device was removed either by a disconnection or a driver upgrade, we must recreate all device resources if (DXGI_ERROR_DEVICE_REMOVED == result || DXGI_ERROR_DEVICE_RESET == result) { if (DXGI_ERROR_DEVICE_REMOVED == result) { result = direct3D11Renderer.getD3D11Device()->GetDeviceRemovedReason(); } RENDERER_LOG(direct3D11Renderer.getContext(), CRITICAL, "Direct3D 11 device lost on present: Reason code 0x%08X", static_cast<unsigned int>(result)) // TODO(co) Add device lost handling if needed. Probably more complex to recreate all device resources. } } //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] } // detail } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Direct3D11Renderer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] SwapChain::SwapChain(Renderer::IRenderPass& renderPass, Renderer::WindowHandle windowHandle) : ISwapChain(renderPass), mD3D11DeviceContext1(nullptr), mDxgiSwapChain(nullptr), mD3D11RenderTargetView(nullptr), mD3D11DepthStencilView(nullptr), mSynchronizationInterval(0), mAllowTearing(false) { const RenderPass& d3d11RenderPass = static_cast<RenderPass&>(renderPass); const Direct3D11Renderer& direct3D11Renderer = static_cast<Direct3D11Renderer&>(d3d11RenderPass.getRenderer()); direct3D11Renderer.getD3D11DeviceContext()->QueryInterface(__uuidof(ID3D11DeviceContext1), reinterpret_cast<void**>(&mD3D11DeviceContext1)); // Sanity check RENDERER_ASSERT(direct3D11Renderer.getContext(), 1 == d3d11RenderPass.getNumberOfColorAttachments(), "There must be exactly one Direct3D 11 render pass color attachment") // Get the Direct3D 11 device instance ID3D11Device* d3d11Device = direct3D11Renderer.getD3D11Device(); // Get the native window handle const HWND hWnd = reinterpret_cast<HWND>(windowHandle.nativeWindowHandle); // Get a DXGI factory instance const bool isWindows10OrGreater = ::detail::isWindows10OrGreater(); IDXGIFactory1* dxgiFactory1 = nullptr; IDXGIFactory2* dxgiFactory2 = nullptr; { IDXGIDevice* dxgiDevice = nullptr; IDXGIAdapter* dxgiAdapter = nullptr; d3d11Device->QueryInterface(IID_PPV_ARGS(&dxgiDevice)); dxgiDevice->GetAdapter(&dxgiAdapter); dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory1)); dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory2)); // Determines whether tearing support is available for fullscreen borderless windows // -> To unlock frame rates of UWP applications on the Windows Store and providing support for both AMD Freesync and NVIDIA's G-SYNC we must explicitly allow tearing // -> See "Windows Dev Center" -> "Variable refresh rate displays": https://msdn.microsoft.com/en-us/library/windows/desktop/mt742104(v=vs.85).aspx if (isWindows10OrGreater) { IDXGIFactory5* dxgiFactory5 = nullptr; dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory5)); if (nullptr != dxgiFactory5) { BOOL allowTearing = FALSE; if (SUCCEEDED(dxgiFactory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowTearing, sizeof(allowTearing)))) { mAllowTearing = true; } dxgiFactory5->Release(); } } // Release references dxgiAdapter->Release(); dxgiDevice->Release(); } // Get the width and height of the given native window and ensure they are never ever zero // -> See "getSafeWidthAndHeight()"-method comments for details long width = 1; long height = 1; { // Get the client rectangle of the given native window RECT rect; ::GetClientRect(hWnd, &rect); // Get the width and height... width = rect.right - rect.left; height = rect.bottom - rect.top; // ... and ensure that none of them is ever zero if (width < 1) { width = 1; } if (height < 1) { height = 1; } } { // Create the swap chain UINT bufferCount = 1; DXGI_SWAP_EFFECT swapEffect = DXGI_SWAP_EFFECT_DISCARD; const bool isWindows8OrGreater = ::IsWindows8OrGreater(); if (isWindows10OrGreater) { RENDERER_ASSERT(direct3D11Renderer.getContext(), d3d11RenderPass.getNumberOfMultisamples() == 1, "Direct3D 11 doesn't support multisampling if the flip model vertical synchronization is used") bufferCount = 2; swapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; } else if (isWindows8OrGreater) { RENDERER_ASSERT(direct3D11Renderer.getContext(), d3d11RenderPass.getNumberOfMultisamples() == 1, "Direct3D 11 doesn't support multisampling if the flip model vertical synchronization is used") bufferCount = 2; swapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; } // Quote from https://msdn.microsoft.com/de-de/library/windows/desktop/hh404557(v=vs.85).aspx : "Platform Update for Windows 7: DXGI_SCALING_NONE is not supported on Windows 7 or Windows Server 2008 R2" if (direct3D11Renderer.getD3DFeatureLevel() == D3D_FEATURE_LEVEL_11_1 && nullptr != dxgiFactory2 && isWindows8OrGreater) { // Fill DXGI swap chain description DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = {}; dxgiSwapChainDesc1.Width = static_cast<UINT>(width); dxgiSwapChainDesc1.Height = static_cast<UINT>(height); dxgiSwapChainDesc1.Format = static_cast<DXGI_FORMAT>(Mapping::getDirect3D11Format(d3d11RenderPass.getColorAttachmentTextureFormat(0))); dxgiSwapChainDesc1.SampleDesc.Count = 1; dxgiSwapChainDesc1.SampleDesc.Quality = 0; dxgiSwapChainDesc1.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; dxgiSwapChainDesc1.BufferCount = bufferCount; dxgiSwapChainDesc1.SwapEffect = swapEffect; dxgiSwapChainDesc1.Flags = mAllowTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0u; // Fill DXGI swap chain fullscreen description DXGI_SWAP_CHAIN_FULLSCREEN_DESC dxgiSwapChainFullscreenDesc = {}; dxgiSwapChainFullscreenDesc.RefreshRate.Numerator = 60; dxgiSwapChainFullscreenDesc.RefreshRate.Denominator = 1; dxgiSwapChainFullscreenDesc.Windowed = TRUE; // Create swap chain IDXGISwapChain1* dxgiSwapChain = nullptr; dxgiFactory2->CreateSwapChainForHwnd(d3d11Device, hWnd, &dxgiSwapChainDesc1, &dxgiSwapChainFullscreenDesc, nullptr, &dxgiSwapChain); mDxgiSwapChain = reinterpret_cast<IDXGISwapChain*>(dxgiSwapChain); } else { // Fill DXGI swap chain description DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc = {}; dxgiSwapChainDesc.BufferCount = bufferCount; dxgiSwapChainDesc.BufferDesc.Width = static_cast<UINT>(width); dxgiSwapChainDesc.BufferDesc.Height = static_cast<UINT>(height); dxgiSwapChainDesc.BufferDesc.Format = static_cast<DXGI_FORMAT>(Mapping::getDirect3D11Format(d3d11RenderPass.getColorAttachmentTextureFormat(0))); dxgiSwapChainDesc.BufferDesc.RefreshRate.Numerator = 60; dxgiSwapChainDesc.BufferDesc.RefreshRate.Denominator = 1; dxgiSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; dxgiSwapChainDesc.OutputWindow = hWnd; dxgiSwapChainDesc.SampleDesc.Count = 1; dxgiSwapChainDesc.SampleDesc.Quality = 0; dxgiSwapChainDesc.Windowed = TRUE; dxgiSwapChainDesc.SwapEffect = swapEffect; dxgiSwapChainDesc.Flags = mAllowTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0u; // Create swap chain dxgiFactory1->CreateSwapChain(d3d11Device, &dxgiSwapChainDesc, &mDxgiSwapChain); } } // Disable alt-return for automatic fullscreen state change // -> We handle this manually to have more control over it dxgiFactory1->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER); // Release our DXGI factory dxgiFactory1->Release(); dxgiFactory2->Release(); // Create the Direct3D 11 views if (nullptr != mDxgiSwapChain) { createDirect3D11Views(); } // Assign a default name to the resource for debugging purposes #ifdef RENDERER_DEBUG setDebugName("Swap chain"); #endif } SwapChain::~SwapChain() { // "DXGI Overview - Destroying a Swap Chain" at MSDN http://msdn.microsoft.com/en-us/library/bb205075.aspx states // "You may not release a swap chain in full-screen mode because doing so may create thread contention (which will // cause DXGI to raise a non-continuable exception). Before releasing a swap chain, first switch to windowed mode // (using IDXGISwapChain::SetFullscreenState( FALSE, NULL )) and then call IUnknown::Release." if (getFullscreenState()) { setFullscreenState(false); } // Release the used resources if (nullptr != mD3D11DepthStencilView) { mD3D11DepthStencilView->Release(); } if (nullptr != mD3D11RenderTargetView) { mD3D11RenderTargetView->Release(); } if (nullptr != mDxgiSwapChain) { mDxgiSwapChain->Release(); } if (nullptr != mD3D11DeviceContext1) { mD3D11DeviceContext1->Release(); } // After releasing references to these resources, we need to call "Flush()" to ensure that Direct3D also releases any references it might still have to the same resources - such as pipeline bindings static_cast<Direct3D11Renderer&>(getRenderer()).getD3D11DeviceContext()->Flush(); } //[-------------------------------------------------------] //[ Public virtual Renderer::IResource methods ] //[-------------------------------------------------------] void SwapChain::setDebugName(const char* name) { #ifdef RENDERER_DEBUG // Assign a debug name to the DXGI swap chain if (nullptr != mDxgiSwapChain) { // Set the debug name // -> First: Ensure that there's no previous private data, else we might get slapped with a warning mDxgiSwapChain->SetPrivateData(WKPDID_D3DDebugObjectName, 0, nullptr); mDxgiSwapChain->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(name)), name); } // Assign a debug name to the Direct3D 11 render target view if (nullptr != mD3D11RenderTargetView) { // Set the debug name // -> First: Ensure that there's no previous private data, else we might get slapped with a warning mD3D11RenderTargetView->SetPrivateData(WKPDID_D3DDebugObjectName, 0, nullptr); mD3D11RenderTargetView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(name)), name); } // Assign a debug name to the Direct3D 11 depth stencil view if (nullptr != mD3D11DepthStencilView) { // Set the debug name // -> First: Ensure that there's no previous private data, else we might get slapped with a warning mD3D11DepthStencilView->SetPrivateData(WKPDID_D3DDebugObjectName, 0, nullptr); mD3D11DepthStencilView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(name)), name); } #else std::ignore = name; #endif } //[-------------------------------------------------------] //[ Public virtual Renderer::IRenderTarget methods ] //[-------------------------------------------------------] void SwapChain::getWidthAndHeight(uint32_t& width, uint32_t& height) const { // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { // Get the Direct3D 11 swap chain description DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc; mDxgiSwapChain->GetDesc(&dxgiSwapChainDesc); // Get the width and height long swapChainWidth = 1; long swapChainHeight = 1; { // Get the client rectangle of the native output window // -> Don't use the width and height stored in "DXGI_SWAP_CHAIN_DESC" -> "DXGI_MODE_DESC" // because it might have been modified in order to avoid zero values RECT rect; ::GetClientRect(dxgiSwapChainDesc.OutputWindow, &rect); // Get the width and height... swapChainWidth = rect.right - rect.left; swapChainHeight = rect.bottom - rect.top; // ... and ensure that none of them is ever zero if (swapChainWidth < 1) { swapChainWidth = 1; } if (swapChainHeight < 1) { swapChainHeight = 1; } } // Write out the width and height width = static_cast<UINT>(swapChainWidth); height = static_cast<UINT>(swapChainHeight); } else { // Set known default return values width = 1; height = 1; } } //[-------------------------------------------------------] //[ Public virtual Renderer::ISwapChain methods ] //[-------------------------------------------------------] handle SwapChain::getNativeWindowHandle() const { // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { // Get the Direct3D 11 swap chain description DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc; mDxgiSwapChain->GetDesc(&dxgiSwapChainDesc); // Return the native window handle return reinterpret_cast<handle>(dxgiSwapChainDesc.OutputWindow); } // Error! return NULL_HANDLE; } void SwapChain::setVerticalSynchronizationInterval(uint32_t synchronizationInterval) { mSynchronizationInterval = synchronizationInterval; } void SwapChain::present() { // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { // TODO(co) "!getFullscreenState()": Add support for borderless window to get rid of this const Direct3D11Renderer& direct3D11Renderer = static_cast<Direct3D11Renderer&>(getRenderPass().getRenderer()); const UINT flags = ((mAllowTearing && 0 == mSynchronizationInterval && !getFullscreenState()) ? DXGI_PRESENT_ALLOW_TEARING : 0); ::detail::handleDeviceLost(direct3D11Renderer, mDxgiSwapChain->Present(mSynchronizationInterval, flags)); // Discard the contents of the render target // -> This is a valid operation only when the existing contents will be entirely overwritten. If dirty or scroll rectangles are used, this call should be removed. if (nullptr != mD3D11DeviceContext1) { mD3D11DeviceContext1->DiscardView(mD3D11RenderTargetView); if (nullptr != mD3D11DepthStencilView) { // Discard the contents of the depth stencil mD3D11DeviceContext1->DiscardView(mD3D11DepthStencilView); } } } } void SwapChain::resizeBuffers() { // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { Direct3D11Renderer& direct3D11Renderer = static_cast<Direct3D11Renderer&>(getRenderer()); // Get the currently set render target Renderer::IRenderTarget* renderTargetBackup = direct3D11Renderer.omGetRenderTarget(); // In case this swap chain is the current render target, we have to unset it before continuing if (this == renderTargetBackup) { direct3D11Renderer.omSetRenderTarget(nullptr); } else { renderTargetBackup = nullptr; } // Release the views if (nullptr != mD3D11DepthStencilView) { mD3D11DepthStencilView->Release(); mD3D11DepthStencilView = nullptr; } if (nullptr != mD3D11RenderTargetView) { mD3D11RenderTargetView->Release(); mD3D11RenderTargetView = nullptr; } // Get the swap chain width and height, ensures they are never ever zero UINT width = 1; UINT height = 1; getSafeWidthAndHeight(width, height); // Resize the Direct3D 11 swap chain // -> Preserve the existing buffer count and format const HRESULT result = mDxgiSwapChain->ResizeBuffers(0, width, height, DXGI_FORMAT_UNKNOWN, mAllowTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0u); if (SUCCEEDED(result)) { // Create the Direct3D 11 views createDirect3D11Views(); // If required, restore the previously set render target if (nullptr != renderTargetBackup) { direct3D11Renderer.omSetRenderTarget(renderTargetBackup); } } else { ::detail::handleDeviceLost(direct3D11Renderer, result); } } } bool SwapChain::getFullscreenState() const { // Window mode by default BOOL fullscreen = FALSE; // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { mDxgiSwapChain->GetFullscreenState(&fullscreen, nullptr); } // Done return (FALSE != fullscreen); } void SwapChain::setFullscreenState(bool fullscreen) { // Is there a valid swap chain? if (nullptr != mDxgiSwapChain) { mDxgiSwapChain->SetFullscreenState(fullscreen, nullptr); } } void SwapChain::setRenderWindow(Renderer::IRenderWindow*) { // TODO(sw) implement me } //[-------------------------------------------------------] //[ Protected virtual Renderer::RefCount methods ] //[-------------------------------------------------------] void SwapChain::selfDestruct() { RENDERER_DELETE(getRenderer().getContext(), SwapChain, this); } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] void SwapChain::getSafeWidthAndHeight(uint32_t& width, uint32_t& height) const { // Get the Direct3D 11 swap chain description DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc; mDxgiSwapChain->GetDesc(&dxgiSwapChainDesc); // Get the client rectangle of the native output window RECT rect; ::GetClientRect(dxgiSwapChainDesc.OutputWindow, &rect); // Get the width and height... long swapChainWidth = rect.right - rect.left; long swapChainHeight = rect.bottom - rect.top; // ... and ensure that none of them is ever zero if (swapChainWidth < 1) { swapChainWidth = 1; } if (swapChainHeight < 1) { swapChainHeight = 1; } // Write out the width and height width = static_cast<UINT>(swapChainWidth); height = static_cast<UINT>(swapChainHeight); } void SwapChain::createDirect3D11Views() { // Create a render target view ID3D11Texture2D* d3d11Texture2DBackBuffer = nullptr; HRESULT hResult = mDxgiSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<LPVOID*>(&d3d11Texture2DBackBuffer)); if (SUCCEEDED(hResult)) { // Get the Direct3D 11 device instance ID3D11Device* d3d11Device = static_cast<Direct3D11Renderer&>(getRenderer()).getD3D11Device(); // Create a render target view hResult = d3d11Device->CreateRenderTargetView(d3d11Texture2DBackBuffer, nullptr, &mD3D11RenderTargetView); d3d11Texture2DBackBuffer->Release(); if (SUCCEEDED(hResult)) { // Create depth stencil texture const Renderer::TextureFormat::Enum depthStencilAttachmentTextureFormat = static_cast<RenderPass&>(getRenderPass()).getDepthStencilAttachmentTextureFormat(); if (Renderer::TextureFormat::Enum::UNKNOWN != depthStencilAttachmentTextureFormat) { // Get the swap chain width and height, ensures they are never ever zero UINT width = 1; UINT height = 1; getSafeWidthAndHeight(width, height); // Create depth stencil texture ID3D11Texture2D* d3d11Texture2DDepthStencil = nullptr; D3D11_TEXTURE2D_DESC d3d11Texture2DDesc = {}; d3d11Texture2DDesc.Width = width; d3d11Texture2DDesc.Height = height; d3d11Texture2DDesc.MipLevels = 1; d3d11Texture2DDesc.ArraySize = 1; d3d11Texture2DDesc.Format = static_cast<DXGI_FORMAT>(Mapping::getDirect3D11Format(depthStencilAttachmentTextureFormat)); d3d11Texture2DDesc.SampleDesc.Count = 1; d3d11Texture2DDesc.SampleDesc.Quality = 0; d3d11Texture2DDesc.Usage = D3D11_USAGE_DEFAULT; d3d11Texture2DDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; d3d11Texture2DDesc.CPUAccessFlags = 0; d3d11Texture2DDesc.MiscFlags = 0; hResult = d3d11Device->CreateTexture2D(&d3d11Texture2DDesc, nullptr, &d3d11Texture2DDepthStencil); if (SUCCEEDED(hResult)) { // Create the depth stencil view D3D11_DEPTH_STENCIL_VIEW_DESC d3d11DepthStencilViewDesc = {}; d3d11DepthStencilViewDesc.Format = d3d11Texture2DDesc.Format; d3d11DepthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; d3d11DepthStencilViewDesc.Texture2D.MipSlice = 0; d3d11Device->CreateDepthStencilView(d3d11Texture2DDepthStencil, &d3d11DepthStencilViewDesc, &mD3D11DepthStencilView); d3d11Texture2DDepthStencil->Release(); } } } } } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Direct3D11Renderer
#include <sstream> #include <fstream> #include <vector> #include <string> inline std::vector<std::string> read_lines(const char* path) { std::vector<std::string> out; std::ifstream input(path); std::string line; while(std::getline(input, line)) { out.push_back(line); } return out; } inline std::string read_full_file(const char* path) { std::ifstream input(path); std::ostringstream os; os << input.rdbuf(); return os.str(); }
#pragma once #include "ZeroIScene.h" #include "PlayerCharacter.h" #include "ZeroSoundManager.h" class Enemy : public ZeroIScene { public: Enemy(); ~Enemy(); private: int followDistanceX; int followDistanceY; protected: void FollowPlayer(); enum CONDITION { MOVE, ATTACK, IDLE }; public: enum EnemyType { SLIME, WISP, TOTEM, GOLEM, DRAGON }; EnemyType enemyType; pair<float, float> damagedTimer; float health; bool isDamaged; void Update(float eTime) override; void Render() override; void Follow(PlayerCharacter* target, Enemy* enemy, int speed, float eTime, bool isMove); virtual void Damage(PlayerCharacter* player); virtual void Damage(PlayerCharacter* player, float eTime); virtual bool IsCollision(PlayerCharacter* player); };
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; const int maxn = 2015 + 10; int f[maxn],a[maxn]; int main() { int t,n; scanf("%d",&t); while (t--) { scanf("%d",&n); for (int i = 1;i < n; i++) { scanf("%d",&a[i]); f[i] = -INF; } f[0] = n*a[1]; for (int j = n-2;j >= 1;j--) for (int i = j;i <= n-2; i++) { f[i] = max(f[i],f[i-j]+a[j+1]-a[1]); } printf("%d\n",f[n-2]); } return 0; }
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Drawing/1.3.1/Colors.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.h> namespace g{namespace Fuse{namespace Drawing{struct Colors;}}} namespace g{namespace Uno{struct Float4;}} namespace g{ namespace Fuse{ namespace Drawing{ // public static class Colors :5 // { uClassType* Colors_typeof(); struct Colors : uObject { static ::g::Uno::Float4 Aqua_; static ::g::Uno::Float4& Aqua() { return Aqua_; } static ::g::Uno::Float4 Black_; static ::g::Uno::Float4& Black() { return Black_; } static ::g::Uno::Float4 Blue_; static ::g::Uno::Float4& Blue() { return Blue_; } static ::g::Uno::Float4 Fuchsia_; static ::g::Uno::Float4& Fuchsia() { return Fuchsia_; } static ::g::Uno::Float4 Gray_; static ::g::Uno::Float4& Gray() { return Gray_; } static ::g::Uno::Float4 Green_; static ::g::Uno::Float4& Green() { return Green_; } static ::g::Uno::Float4 Lime_; static ::g::Uno::Float4& Lime() { return Lime_; } static ::g::Uno::Float4 Maroon_; static ::g::Uno::Float4& Maroon() { return Maroon_; } static ::g::Uno::Float4 Navy_; static ::g::Uno::Float4& Navy() { return Navy_; } static ::g::Uno::Float4 Olive_; static ::g::Uno::Float4& Olive() { return Olive_; } static ::g::Uno::Float4 Purple_; static ::g::Uno::Float4& Purple() { return Purple_; } static ::g::Uno::Float4 Red_; static ::g::Uno::Float4& Red() { return Red_; } static ::g::Uno::Float4 Silver_; static ::g::Uno::Float4& Silver() { return Silver_; } static ::g::Uno::Float4 Teal_; static ::g::Uno::Float4& Teal() { return Teal_; } static ::g::Uno::Float4 Transparent_; static ::g::Uno::Float4& Transparent() { return Transparent_; } static ::g::Uno::Float4 White_; static ::g::Uno::Float4& White() { return White_; } static ::g::Uno::Float4 Yellow_; static ::g::Uno::Float4& Yellow() { return Yellow_; } }; // } }}} // ::g::Fuse::Drawing
#include "LinearLayout.h" void Gui::LinearLayout::Resize(const BaseElement *parent) { BaseElement::Resize(parent); Vec2f _start = { -1, -1 }; Vec2f _size = { 2, 2 }; float spacing; float filled_space = 0.0f; float l; if (vertical_) { spacing = 8.0f / parent->size_px()[1]; l = _size[1] - spacing * (elements_.size() + 1); for (BaseElement *el : elements_) { if (el->resizable()) { filled_space += el->rel_size()[1]; } else { l -= el->rel_size()[1]; } } } else { spacing = 8.0f / parent->size_px()[0]; l = _size[0] - spacing * (elements_.size() + 1); for (BaseElement *el : elements_) { if (el->resizable()) { filled_space += el->rel_size()[0]; } else { l -= el->rel_size()[0]; } } } float mult = 1; if (filled_space > 0) { mult = l / filled_space; } float pad = 0; if (vertical_) { pad = _start[1] + _size[1] - spacing; for (BaseElement *el : elements_) { el->Resize({ _start[0], 1 }, { _size[0], el->rel_size()[1] * mult }, this); pad -= (el->rel_size()[1] + spacing); el->Resize({ _start[0], pad }, { _size[0], el->rel_size()[1] }, this); } } else { pad = _start[0] + spacing; for (BaseElement *el : elements_) { el->Resize({ pad, _start[1] }, { el->rel_size()[0] * mult, _size[1] }, this); pad += el->rel_size()[0] + spacing; } } } void Gui::LinearLayout::Resize(const Vec2f &start, const Vec2f &size, const BaseElement *parent) { BaseElement::Resize(start, size, parent); } bool Gui::LinearLayout::Check(const Vec2i &p) const { for (BaseElement *el : elements_) { if (el->Check(p)) { return true; } } return false; } bool Gui::LinearLayout::Check(const Vec2f &p) const { for (BaseElement *el : elements_) { if (el->Check(p)) { return true; } } return false; } void Gui::LinearLayout::Focus(const Vec2i &p) { for (BaseElement *el : elements_) { el->Focus(p); } } void Gui::LinearLayout::Focus(const Vec2f &p) { for (BaseElement *el : elements_) { el->Focus(p); } } void Gui::LinearLayout::Press(const Vec2i &p, bool push) { for (BaseElement *el : elements_) { el->Press(p, push); } } void Gui::LinearLayout::Press(const Vec2f &p, bool push) { for (BaseElement *el : elements_) { el->Press(p, push); } } void Gui::LinearLayout::Draw(Renderer *r) { for (BaseElement *el : elements_) { el->Draw(r); } }
#include <iostream> #include <vector> #include <queue> using namespace std; class MedianFinder { public: // MedianFinder(){} void addNum(int num); double findMedian(); private: vector<int> v; }; void MedianFinder::addNum(int num){ // if(v.empty()){ // v.push_back(num); // return; // } size_t left = 0; size_t right = v.size(); while(left < right){ int mid = (left + right) / 2; if(v[mid] > num){ right = mid; }else if(v[mid] < num){ left = mid + 1; }else{ left = mid; right = mid; } } v.insert(v.begin() + left, num); return; } double MedianFinder::findMedian(){ if(v.empty()){ return 0; } int mid = v.size() / 2; if(v.size() % 2){ return v[mid]; } return static_cast<double>(v[mid - 1] + v[mid]) / 2; } class MedianFinder2 { public: // MedianFinder(){} void addNum(int num); double findMedian(); private: priority_queue<int> minQueue; priority_queue<int, vector<int>, greater<int>> maxQueue; }; void MedianFinder2::addNum(int num){ minQueue.push(num); maxQueue.push(minQueue.top()); minQueue.pop(); if(minQueue.size() < maxQueue.size()){ minQueue.push(maxQueue.top()); maxQueue.pop(); } } double MedianFinder2::findMedian(){ if(minQueue.empty()){ return 0; }else if(maxQueue.empty()){ return minQueue.top(); } if(minQueue.size() == maxQueue.size()){ return static_cast<double>(minQueue.top() + maxQueue.top()) / 2; } return minQueue.top(); } int main(void){ return 0; }
//Fuel Economy Tracker //Christopher Rennie #pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") //prevent console from opening #include<cstdlib> #include<iostream> #include<list> #include<fstream> #include<string> #include<Windows.h> #include<FL/Fl.H> #include<FL/Fl_Window.H> #include<FL/Fl_Box.H> #include<FL/Fl_Output.H> #include"dataEntry.h" #include"fileOps.h" #include"entryStats.h" #include"mainWindow.h" int main() { std::list<dataEntry*> testList; /*for (int i = 0; i < 5; i++) { dataEntry* test = new dataEntry(20180101, 67888, 56.11, 45.33, 1.27, 9.78); testList.push_back(test); } saveEntries(testList);*/ loadEntries(testList); entryStats* testStats = new entryStats(testList); mainWindow win(testStats, testList, 480, 360, "Fuel Economy"); return Fl::run(); }
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmServer.h" #include <algorithm> #include <cassert> #include <cstdint> #include <iostream> #include <mutex> #include <utility> #include <cm/memory> #include <cm/shared_mutex> #include "cmsys/FStream.hxx" #include "cm_jsoncpp_reader.h" #include "cm_jsoncpp_writer.h" #include "cmConnection.h" #include "cmFileMonitor.h" #include "cmJsonObjectDictionary.h" #include "cmServerDictionary.h" #include "cmServerProtocol.h" #include "cmSystemTools.h" #include "cmake.h" void on_signal(uv_signal_t* signal, int signum) { auto conn = static_cast<cmServerBase*>(signal->data); conn->OnSignal(signum); } static void on_walk_to_shutdown(uv_handle_t* handle, void* arg) { (void)arg; assert(uv_is_closing(handle)); if (!uv_is_closing(handle)) { uv_close(handle, &cmEventBasedConnection::on_close); } } class cmServer::DebugInfo { public: DebugInfo() : StartTime(uv_hrtime()) { } bool PrintStatistics = false; std::string OutputFile; uint64_t StartTime; }; cmServer::cmServer(cmConnection* conn, bool supportExperimental) : cmServerBase(conn) , SupportExperimental(supportExperimental) { // Register supported protocols: this->RegisterProtocol(new cmServerProtocol1); } cmServer::~cmServer() { Close(); for (cmServerProtocol* p : this->SupportedProtocols) { delete p; } } void cmServer::ProcessRequest(cmConnection* connection, const std::string& input) { Json::Reader reader; Json::Value value; if (!reader.parse(input, value)) { this->WriteParseError(connection, "Failed to parse JSON input."); return; } std::unique_ptr<DebugInfo> debug; Json::Value debugValue = value["debug"]; if (!debugValue.isNull()) { debug = cm::make_unique<DebugInfo>(); debug->OutputFile = debugValue["dumpToFile"].asString(); debug->PrintStatistics = debugValue["showStats"].asBool(); } const cmServerRequest request(this, connection, value[kTYPE_KEY].asString(), value[kCOOKIE_KEY].asString(), value); if (request.Type.empty()) { cmServerResponse response(request); response.SetError("No type given in request."); this->WriteResponse(connection, response, nullptr); return; } cmSystemTools::SetMessageCallback( [&request](const std::string& msg, const char* title) { reportMessage(msg, title, request); }); if (this->Protocol) { this->Protocol->CMakeInstance()->SetProgressCallback( [&request](const std::string& msg, float prog) { reportProgress(msg, prog, request); }); this->WriteResponse(connection, this->Protocol->Process(request), debug.get()); } else { this->WriteResponse(connection, this->SetProtocolVersion(request), debug.get()); } } void cmServer::RegisterProtocol(cmServerProtocol* protocol) { if (protocol->IsExperimental() && !this->SupportExperimental) { delete protocol; return; } auto version = protocol->ProtocolVersion(); assert(version.first >= 0); assert(version.second >= 0); auto it = std::find_if(this->SupportedProtocols.begin(), this->SupportedProtocols.end(), [version](cmServerProtocol* p) { return p->ProtocolVersion() == version; }); if (it == this->SupportedProtocols.end()) { this->SupportedProtocols.push_back(protocol); } } void cmServer::PrintHello(cmConnection* connection) const { Json::Value hello = Json::objectValue; hello[kTYPE_KEY] = "hello"; Json::Value& protocolVersions = hello[kSUPPORTED_PROTOCOL_VERSIONS] = Json::arrayValue; for (auto const& proto : this->SupportedProtocols) { auto version = proto->ProtocolVersion(); Json::Value tmp = Json::objectValue; tmp[kMAJOR_KEY] = version.first; tmp[kMINOR_KEY] = version.second; if (proto->IsExperimental()) { tmp[kIS_EXPERIMENTAL_KEY] = true; } protocolVersions.append(tmp); } this->WriteJsonObject(connection, hello, nullptr); } void cmServer::reportProgress(const std::string& msg, float progress, const cmServerRequest& request) { if (progress < 0.0f || progress > 1.0f) { request.ReportMessage(msg, ""); } else { request.ReportProgress(0, static_cast<int>(progress * 1000), 1000, msg); } } void cmServer::reportMessage(const std::string& msg, const char* title, const cmServerRequest& request) { std::string titleString; if (title) { titleString = title; } request.ReportMessage(msg, titleString); } cmServerResponse cmServer::SetProtocolVersion(const cmServerRequest& request) { if (request.Type != kHANDSHAKE_TYPE) { return request.ReportError("Waiting for type \"" + kHANDSHAKE_TYPE + "\"."); } Json::Value requestedProtocolVersion = request.Data[kPROTOCOL_VERSION_KEY]; if (requestedProtocolVersion.isNull()) { return request.ReportError("\"" + kPROTOCOL_VERSION_KEY + "\" is required for \"" + kHANDSHAKE_TYPE + "\"."); } if (!requestedProtocolVersion.isObject()) { return request.ReportError("\"" + kPROTOCOL_VERSION_KEY + "\" must be a JSON object."); } Json::Value majorValue = requestedProtocolVersion[kMAJOR_KEY]; if (!majorValue.isInt()) { return request.ReportError("\"" + kMAJOR_KEY + "\" must be set and an integer."); } Json::Value minorValue = requestedProtocolVersion[kMINOR_KEY]; if (!minorValue.isNull() && !minorValue.isInt()) { return request.ReportError("\"" + kMINOR_KEY + "\" must be unset or an integer."); } const int major = majorValue.asInt(); const int minor = minorValue.isNull() ? -1 : minorValue.asInt(); if (major < 0) { return request.ReportError("\"" + kMAJOR_KEY + "\" must be >= 0."); } if (!minorValue.isNull() && minor < 0) { return request.ReportError("\"" + kMINOR_KEY + "\" must be >= 0 when set."); } this->Protocol = cmServer::FindMatchingProtocol(this->SupportedProtocols, major, minor); if (!this->Protocol) { return request.ReportError("Protocol version not supported."); } std::string errorMessage; if (!this->Protocol->Activate(this, request, &errorMessage)) { this->Protocol = nullptr; return request.ReportError("Failed to activate protocol version: " + errorMessage); } return request.Reply(Json::objectValue); } bool cmServer::Serve(std::string* errorMessage) { if (this->SupportedProtocols.empty()) { *errorMessage = "No protocol versions defined. Maybe you need --experimental?"; return false; } assert(!this->Protocol); return cmServerBase::Serve(errorMessage); } cmFileMonitor* cmServer::FileMonitor() const { return fileMonitor.get(); } void cmServer::WriteJsonObject(const Json::Value& jsonValue, const DebugInfo* debug) const { cm::shared_lock<cm::shared_mutex> lock(ConnectionsMutex); for (auto& connection : this->Connections) { WriteJsonObject(connection.get(), jsonValue, debug); } } void cmServer::WriteJsonObject(cmConnection* connection, const Json::Value& jsonValue, const DebugInfo* debug) const { Json::FastWriter writer; auto beforeJson = uv_hrtime(); std::string result = writer.write(jsonValue); if (debug) { Json::Value copy = jsonValue; if (debug->PrintStatistics) { Json::Value stats = Json::objectValue; auto endTime = uv_hrtime(); stats["jsonSerialization"] = double(endTime - beforeJson) / 1000000.0; stats["totalTime"] = double(endTime - debug->StartTime) / 1000000.0; stats["size"] = static_cast<int>(result.size()); if (!debug->OutputFile.empty()) { stats["dumpFile"] = debug->OutputFile; } copy["zzzDebug"] = stats; result = writer.write(copy); // Update result to include debug info } if (!debug->OutputFile.empty()) { cmsys::ofstream myfile(debug->OutputFile.c_str()); myfile << result; } } connection->WriteData(result); } cmServerProtocol* cmServer::FindMatchingProtocol( const std::vector<cmServerProtocol*>& protocols, int major, int minor) { cmServerProtocol* bestMatch = nullptr; for (auto protocol : protocols) { auto version = protocol->ProtocolVersion(); if (major != version.first) { continue; } if (minor == version.second) { return protocol; } if (!bestMatch || bestMatch->ProtocolVersion().second < version.second) { bestMatch = protocol; } } return minor < 0 ? bestMatch : nullptr; } void cmServer::WriteProgress(const cmServerRequest& request, int min, int current, int max, const std::string& message) const { assert(min <= current && current <= max); assert(message.length() != 0); Json::Value obj = Json::objectValue; obj[kTYPE_KEY] = kPROGRESS_TYPE; obj[kREPLY_TO_KEY] = request.Type; obj[kCOOKIE_KEY] = request.Cookie; obj[kPROGRESS_MESSAGE_KEY] = message; obj[kPROGRESS_MINIMUM_KEY] = min; obj[kPROGRESS_MAXIMUM_KEY] = max; obj[kPROGRESS_CURRENT_KEY] = current; this->WriteJsonObject(request.Connection, obj, nullptr); } void cmServer::WriteMessage(const cmServerRequest& request, const std::string& message, const std::string& title) const { if (message.empty()) { return; } Json::Value obj = Json::objectValue; obj[kTYPE_KEY] = kMESSAGE_TYPE; obj[kREPLY_TO_KEY] = request.Type; obj[kCOOKIE_KEY] = request.Cookie; obj[kMESSAGE_KEY] = message; if (!title.empty()) { obj[kTITLE_KEY] = title; } WriteJsonObject(request.Connection, obj, nullptr); } void cmServer::WriteParseError(cmConnection* connection, const std::string& message) const { Json::Value obj = Json::objectValue; obj[kTYPE_KEY] = kERROR_TYPE; obj[kERROR_MESSAGE_KEY] = message; obj[kREPLY_TO_KEY] = ""; obj[kCOOKIE_KEY] = ""; this->WriteJsonObject(connection, obj, nullptr); } void cmServer::WriteSignal(const std::string& name, const Json::Value& data) const { assert(data.isObject()); Json::Value obj = data; obj[kTYPE_KEY] = kSIGNAL_TYPE; obj[kREPLY_TO_KEY] = ""; obj[kCOOKIE_KEY] = ""; obj[kNAME_KEY] = name; WriteJsonObject(obj, nullptr); } void cmServer::WriteResponse(cmConnection* connection, const cmServerResponse& response, const DebugInfo* debug) const { assert(response.IsComplete()); Json::Value obj = response.Data(); obj[kCOOKIE_KEY] = response.Cookie; obj[kTYPE_KEY] = response.IsError() ? kERROR_TYPE : kREPLY_TYPE; obj[kREPLY_TO_KEY] = response.Type; if (response.IsError()) { obj[kERROR_MESSAGE_KEY] = response.ErrorMessage(); } this->WriteJsonObject(connection, obj, debug); } void cmServer::OnConnected(cmConnection* connection) { PrintHello(connection); } void cmServer::OnServeStart() { cmServerBase::OnServeStart(); fileMonitor = std::make_shared<cmFileMonitor>(GetLoop()); } void cmServer::StartShutDown() { if (fileMonitor) { fileMonitor->StopMonitoring(); fileMonitor.reset(); } cmServerBase::StartShutDown(); } static void __start_thread(void* arg) { auto server = static_cast<cmServerBase*>(arg); std::string error; bool success = server->Serve(&error); if (!success || !error.empty()) { std::cerr << "Error during serve: " << error << std::endl; } } bool cmServerBase::StartServeThread() { ServeThreadRunning = true; uv_thread_create(&ServeThread, __start_thread, this); return true; } static void __shutdownThread(uv_async_t* arg) { auto server = static_cast<cmServerBase*>(arg->data); server->StartShutDown(); } bool cmServerBase::Serve(std::string* errorMessage) { #ifndef NDEBUG uv_thread_t blank_thread_t = {}; assert(uv_thread_equal(&blank_thread_t, &ServeThreadId)); ServeThreadId = uv_thread_self(); #endif errorMessage->clear(); ShutdownSignal.init(Loop, __shutdownThread, this); SIGINTHandler.init(Loop, this); SIGHUPHandler.init(Loop, this); SIGINTHandler.start(&on_signal, SIGINT); SIGHUPHandler.start(&on_signal, SIGHUP); OnServeStart(); { cm::shared_lock<cm::shared_mutex> lock(ConnectionsMutex); for (auto& connection : Connections) { if (!connection->OnServeStart(errorMessage)) { return false; } } } if (uv_run(&Loop, UV_RUN_DEFAULT) != 0) { // It is important we don't ever let the event loop exit with open handles // at best this is a memory leak, but it can also introduce race conditions // which can hang the program. assert(false && "Event loop stopped in unclean state."); *errorMessage = "Internal Error: Event loop stopped in unclean state."; return false; } return true; } void cmServerBase::OnConnected(cmConnection*) { } void cmServerBase::OnServeStart() { } void cmServerBase::StartShutDown() { ShutdownSignal.reset(); SIGINTHandler.reset(); SIGHUPHandler.reset(); { std::unique_lock<cm::shared_mutex> lock(ConnectionsMutex); for (auto& connection : Connections) { connection->OnConnectionShuttingDown(); } Connections.clear(); } uv_walk(&Loop, on_walk_to_shutdown, nullptr); } bool cmServerBase::OnSignal(int signum) { (void)signum; StartShutDown(); return true; } cmServerBase::cmServerBase(cmConnection* connection) { auto err = uv_loop_init(&Loop); (void)err; Loop.data = this; assert(err == 0); AddNewConnection(connection); } void cmServerBase::Close() { if (Loop.data) { if (ServeThreadRunning) { this->ShutdownSignal.send(); uv_thread_join(&ServeThread); } uv_loop_close(&Loop); Loop.data = nullptr; } } cmServerBase::~cmServerBase() { Close(); } void cmServerBase::AddNewConnection(cmConnection* ownedConnection) { { std::unique_lock<cm::shared_mutex> lock(ConnectionsMutex); Connections.emplace_back(ownedConnection); } ownedConnection->SetServer(this); } uv_loop_t* cmServerBase::GetLoop() { return &Loop; } void cmServerBase::OnDisconnect(cmConnection* pConnection) { auto pred = [pConnection](const std::unique_ptr<cmConnection>& m) { return m.get() == pConnection; }; { std::unique_lock<cm::shared_mutex> lock(ConnectionsMutex); Connections.erase( std::remove_if(Connections.begin(), Connections.end(), pred), Connections.end()); } if (Connections.empty()) { this->ShutdownSignal.send(); } }
#pragma once class TestBase; // Holds the data for one error encountered during a test // The tests are run in parallel, so the error messages cannot be written to the output // while the tests are running because the text from different tests would be intermingled. // This small class captures the information for a test error so that the error can be written // out at a later time class TestError { public: TestError(TestBase *testBase, const string& msg); virtual ~TestError() {}; string ToString(); private: TestError(){}; TestBase* m_testBase; string m_testName; string m_errorMsg; };
/* **************************************** Created by Hong Zhou based on an example from "Java for Engineers ans Scientist" by Gary J. Bronson **************************************** */ /************************************** This piece software can be used to calculate the average of numbers. ***************************************/ #include <iostream> #include <cstdlib> #include <cctype> using namespace std; int main (int argc, char ** argv) { int maxNums = 0; //number of values to average int count = 0; double num = 0.0; //current number input by user float total = 0.0; //the total numbers input by the user float average = 0.0; //the calculated average of the values char inMessage; //get user input. cout<<"Do you want to do average? [y/n]"<< endl; cin>>inMessage; cin.ignore(256, '\n'); if (inMessage != 'y') { return EXIT_SUCCESS; } cout<<"how many numbers would you like to average? [>2]" <<endl; cin>>maxNums; while (cin.fail()|| maxNums < 2){ cout<<"invalid input, try again:" << endl; cin.clear(); cin.ignore(80, '\n'); cin>>maxNums; } cin.ignore(256, '\n'); total=0; while(count < maxNums) { cout<<"Please enter number " << count+1 << endl; cin>>num; while (cin.fail()){ cout << num << endl; cout<<"invalid input, input " << count+1 <<" again" << endl; cin.clear(); cin.ignore(80, '\n'); cin>>num; } cin.ignore(256, '\n'); total+=num; count++; } average = total/maxNums; cout<<"The average of the " <<maxNums << " numbers" << " is " << average << endl; return 0; }
#pragma once #include <iostream> using namespace std; #include "aqua.h" class Caracatita:public aqua{ private: int idAnimal=9; static queue<animal*> ListaCusti[10]; static int numar_animale; public: virtual void TreceInCusca(); int getIDAnimal(); std::string facCaAnimalu(); Caracatita(); Caracatita(std::string ss,int x); virtual animal* GetAnimal(); virtual float GetFactorFericiala(animal* an) { int id = an->getIDCusca(); float factor = ListaCusti[id].size()+1; return (1/factor); } static int get_numar_animale(){return numar_animale;} static void Update_numar(){numar_animale++;} static void Reset_numar(){numar_animale=0;} friend ostream& operator<<(ostream& out,Caracatita x) { out<<"Eu sunt "<<x.getNume()<<". Fericirea mea e "<<x.getFericeala()<<"/10. Pretul meu e "<<x.getPret()<<"lei . Stau in acvariul "<<x.getIDCusca()<<". " <<x.facCaAnimalu(); return out; } };
/* * EmplaceInsertion.cpp * * Created on: May 30, 2016 * Author: bakhvalo */ #include "gtest/gtest.h" #include <type_traits> #include <vector> #include <string> #include <set> #include <list> #include <memory> #include <regex> // General idea for using emplacement methods is to avoid excessive temporaries. // And avoid calling constructor/destructor for this temporary. // Those tests show when there is advantage and where is not in using emplacement. TEST(EmplaceInsertionUnitTest, value_being_added_is_constructed_into_the_container_not_assigned) { std::vector<std::string> vs; // Here vector will move-assign the new value into place. // But move assignment requires an object to move from, and that means that a // temporary object will need to be created to be the source of the move // Meaning no gain in using emplacement. vs.emplace(vs.begin(), "xyzzy"); } TEST(EmplaceInsertionUnitTest, the_argument_type_being_passed_differ_from_the_type_held_by_the_container) { std::vector<std::string> vs; vs.emplace_back("xyzzy"); // this is much faster vs.emplace_back(std::string("xyzzy")); // than this. } TEST(EmplaceInsertionUnitTest, the_container_is_unlikely_to_reject_the_new_value_as_a_duplicate) { /* The reason this matters is that in order to detect whether a value is already in the container, emplacement implementations typically create a node with the new value so that they can compare the value of this node with existing container nodes. If the value to be added isn’t in the container, the node is linked in. However, if the value is already present, the emplacement is aborted and the node is destroyed, meaning that the cost of its construction and destruction was wasted */ std::set<std::string> set; set.emplace("abc"); set.emplace("abc"); // here performance is the same as for simple insert } namespace { class Widget { }; } TEST(EmplaceInsertionUnitTest, do_not_use_emplacement_for_resource_management_elements) { std::list<std::unique_ptr<Widget>> ptrs; ptrs.push_back(std::unique_ptr<Widget>(new Widget)); // this is ok. ptrs.emplace_back(new Widget); // potential memory leak. /* 1. The raw pointer resulting from “new Widget” is perfect-forwarded to the point inside emplace_back where a list node is to be allocated. That allocation fails, and an out-of-memory exception is thrown. 2. As the exception propagates out of emplace_back, the raw pointer that was the only way to get at the Widget on the heap is lost. That Widget (and any resources it owns) is leaked. */ } TEST(EmplaceInsertionUnitTest, emplacement_is_impacted_by_type_conversions_in_explicit_constructors) { std::vector<std::regex> regexes; //regexes.push_back(nullptr); // not compiles copy init forbids use of that ctor //regexes.emplace_back(nullptr); // compiles. Which is bad! Direct init permits // use of explicit std::regex ctor taking a pointer // Fails in runtime. // because: // push_back performs // std::regex r1 = nullptr; // error! won't compile. (Constructor is explicit). // but emplace performs // std::regex r2(nullptr); // compiles }
/* * 题目:26. 删除有序数组中的重复项 * 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/ */ class Solution { public: int removeDuplicates(vector<int>& nums) { int n = nums.size(); if (n == 0) { return 0; } int cnt = 1; for (int i = 1; i < n; i++) { if (nums[i] != nums[i - 1]) { nums[cnt++] = nums[i]; } } return cnt; } };
#include "EventFSM.h" #include "Execute.h" #include "Player.h" #include "Actions.h" EventFsm::~EventFsm() { NotificationCenter::getInstance()->removeAllObservers(this); } EventFsm* EventFsm::createEventFsm(Player* m_player) { EventFsm* fsm = new EventFsm(); if (fsm && fsm->init(m_player)) { fsm->autorelease(); } else { CC_SAFE_DELETE(fsm); fsm = NULL; } return fsm; } bool EventFsm::init(Player* m_player) { SkillExecute* State = new SkillExecute(); this->mstate = State; this->m_player = m_player; NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(EventFsm::standFunc), StringUtils::toString(standType), NULL); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(EventFsm::runFunc), StringUtils::toString(runType), NULL); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(EventFsm::attackFunc), StringUtils::toString(attackType), NULL); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(EventFsm::skillFunc), StringUtils::toString(skillType), NULL); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(EventFsm::hurtFunc), StringUtils::toString(hurtType), NULL); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(EventFsm::winFunc), StringUtils::toString(winType), NULL); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(EventFsm::deadFunc), StringUtils::toString(deadType), NULL); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(EventFsm::rightFunc), StringUtils::toString(rightType), NULL); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(EventFsm::leftFunc), StringUtils::toString(leftType), NULL); return true; } void EventFsm::standFunc(Ref* psender) { mstate->execute(m_player, standType); } void EventFsm::runFunc(Ref* psender) { mstate->execute(m_player, runType); } void EventFsm::attackFunc(Ref* psender) { mstate->execute(m_player, attackType); } void EventFsm::skillFunc(Ref* psender) { mstate->execute(m_player, skillType); } void EventFsm::hurtFunc(Ref* psender) { mstate->execute(m_player, hurtType); } void EventFsm::winFunc(Ref* psender) { mstate->execute(m_player, winType); } void EventFsm::deadFunc(Ref* psender) { mstate->execute(m_player, deadType); } void EventFsm::rightFunc(Ref* psender) { mstate->execute(m_player, rightType); } void EventFsm::leftFunc(Ref* psender) { mstate->execute(m_player, leftType); }
#include "ofDisplay.h" //-------------------------------------------------------------- void ofDisplay::setup(){ // displayOneServer.setName("display " + ofToString(display)); // mClient.setup(); // mClient.set("", "Simple Server"); } //-------------------------------------------------------------- void ofDisplay::update(){ } //-------------------------------------------------------------- void ofDisplay::draw(){ ofBackground(0); // Draw image main->effectsPingPong.src->getTexture().drawSubsection( 0, 0, main->windowWidth, main->windowHeight, 0, main->FBOheight - main->windowHeight*display ); // Draw frame glPointSize(10.f); // mClient.draw(50, 50); // displayOneServer.publishScreen(); // main->frameMesh.draw(); }
/* Name: ���Ƽ��ת�� Copyright: Author: Hill bamboo Date: 2019/8/15 17:17:37 Description: С�� */ #include <bits/stdc++.h> using namespace std; void num2k(long long num, int k) { if (num == 0) { printf("0\n"); return; } stack<int> stk; while (num) { stk.push(num % k); num /= k; } while (!stk.empty()) { printf("%d", stk.top()); stk.pop(); } } int main() { long long num; int k; scanf("%lld %d", &num, &k); num2k(num, k); return 0; }
#include "usart2.h" #include <unistd.h> #include <stdio.h> #include <string.h> USART2* USART2::s_pInstance = NULL; QThread* USART2::thread = NULL; USART2::USART2() { } USART2::~USART2() { initFD(); memset(txBuf, 0, 1024); memset(rxBuf, 0, 1024); } void USART2::initSerialPort(int dataBits, int parity, int stopBits, int baud) { initFD(); setDataBits(dataBits); setParity(parity); setStopBits(stopBits); setBaudrate(baud); memset(deviceName, 0, 30); memcpy(deviceName, USART2_DEVNAME, strlen(USART2_DEVNAME)); setDevName(deviceName); memset(txBuf, 0, 1024); memset(rxBuf, 0, 1024); // flush(Serial::FLUSH_RX|Serial::FLUSH_RX); } USART2* USART2::getInstance(void) { if(!s_pInstance) { s_pInstance = new USART2; thread = new QThread((QObject*)s_pInstance); IThread::addToMap((QObject*)s_pInstance, thread); } connect(thread, SIGNAL(started()), s_pInstance, SLOT(run())); return s_pInstance; } void USART2::run() { int len = 0; char buf[1024]; memset(buf, 0, 1024); while(true){ usleep(1); //qDebug("Hello, usart2 "); //writeData("hello, world\n", strlen("hello, world\n")); memset(buf, 0, 1024); len = readData(buf, 1024); if (len > 0){ saveData(buf, len); } } } void USART2::saveData(char* src, int len) { QMutexLocker locker(&rxBufMutex); memset(rxBuf, 0, 1024); memcpy(rxBuf, src, len); } void USART2::getData(char* buf) { QMutexLocker locker(&rxBufMutex); memset(buf, 0, 1024); memcpy(buf, rxBuf, 1024); memset(rxBuf, 0, 1024); }
// // GameUI.cpp // GetFish // // Created by zhusu on 15/1/27. // // #include "GameUI.h" #include "Common.h" #include "Tools.h" #include "Data.h" #include "GameScene.h" GameUI::GameUI():_dir(DIR_NONE) { } GameUI::~GameUI() { } bool GameUI::init() { if(CCLayer::init()) { _screenSize = CCDirector::sharedDirector()->getWinSize(); zuodi = CCSprite::createWithSpriteFrameName("ui_heibei.png"); zuodi->setAnchorPoint(ccp(0, 1)); zuodi->setPosition(ccp(_screenSize.width*0.035, _screenSize.height*0.97)); addChild(zuodi); _node = CCNode::create(); _node->setPosition(ccp(0, -2)); zuodi->addChild(_node); CCSprite* zi4 = CCSprite::createWithSpriteFrameName(("ui_tishi_zi4_"+Tools::intToString(GameScene::instance()->getSucType()+1)+".png").c_str()); zi4->setAnchorPoint(ccp(0, 0.5)); zi4->setPosition(ccp(zuodi->boundingBox().size.width*0.5-15, zuodi->boundingBox().size.height*0.5)); _node->addChild(zi4); if (GameScene::instance()->getSucType()==0) { CCArmatureDataManager::sharedArmatureDataManager()->addArmatureFileInfo(("fish/fish_"+Tools::intToString(GameScene::instance()->getSucAdd())+".csb").c_str()); CCArmature* fish = CCArmature::create(("fish_"+Tools::intToString(GameScene::instance()->getSucAdd())).c_str()); fish->setPosition(ccp(zuodi->boundingBox().size.width*0.5+50, zuodi->boundingBox().size.height*0.5)); fish->setScale(0.5); _node->addChild(fish); _num = CCLabelAtlas::create((","+Tools::intToString(GameScene::instance()->getSucNum())).c_str(), "ui/shuzi5.png", 12, 15, 43); _num->setAnchorPoint(ccp(0, 0.5)); _num->setPosition(ccp(zuodi->boundingBox().size.width*0.5+80, zuodi->boundingBox().size.height*0.5)); _node->addChild(_num); }else if (GameScene::instance()->getSucType()==1) { CCArmature* fish = CCArmature::create("item_2"); fish->setPosition(ccp(zuodi->boundingBox().size.width*0.5+50, zuodi->boundingBox().size.height*0.5)); _node->addChild(fish); _num = CCLabelAtlas::create((","+Tools::intToString(GameScene::instance()->getSucNum())).c_str(), "ui/shuzi5.png", 12, 15, 43); _num->setAnchorPoint(ccp(0, 0.5)); _num->setPosition(ccp(zuodi->boundingBox().size.width*0.5+70, zuodi->boundingBox().size.height*0.5)); _node->addChild(_num); }else if (GameScene::instance()->getSucType()==3) { _num = CCLabelAtlas::create((","+Tools::intToString(GameScene::instance()->getSucNum())).c_str(), "ui/shuzi5.png", 12, 15, 43); _num->setAnchorPoint(ccp(0, 0.5)); _num->setPosition(ccp(zi4->boundingBox().getMaxX()+5, zuodi->boundingBox().size.height*0.5)); _node->addChild(_num); } CCSprite* daojishi = CCSprite::createWithSpriteFrameName("ui_daojishi.png"); daojishi->setAnchorPoint(ccp(0.5, 1)); daojishi->setPosition(ccp(_screenSize.width*0.5, _screenSize.height+22)); addChild(daojishi); if (GameScene::instance()->getShip()->getActor()->count()>1) { CCNode* jindutiao1 = CCNode::create(); jindutiao1->setPosition(ccp(_screenSize.width*0.65, _screenSize.height*0.92)); addChild(jindutiao1); CCSprite* jindudi1 = CCSprite::createWithSpriteFrameName("ui_diaoyu1.png"); jindudi1->setAnchorPoint(ccp(0, 1)); jindudi1->setPosition(ccp(0, 0)); jindutiao1->addChild(jindudi1); CCSprite* tiao1 = CCSprite::createWithSpriteFrameName("ui_lanshang.png"); _score_tiao1 = CCProgressTimer::create(tiao1); _score_tiao1->setType(kCCProgressTimerTypeBar); _score_tiao1->setBarChangeRate(ccp(1,0)); _score_tiao1->setMidpoint(ccp(0, 0)); _score_tiao1->setPercentage(0); _score_tiao1->setAnchorPoint(ccp(0, 1)); _score_tiao1->setPosition(ccp(5, -7)); jindutiao1->addChild(_score_tiao1); _score_Label1 = CCLabelAtlas::create("0", "ui/shuzi8.png", 14, 21, 43); _score_Label1->setAnchorPoint(ccp(1, 0.5)); _score_Label1->setPosition(ccp(-5, -jindudi1->boundingBox().size.height*0.5)); jindutiao1->addChild(_score_Label1); } CCNode* jindutiao = CCNode::create(); if (GameScene::instance()->getShip()->getActor()->count()>1) { jindutiao->setPosition(ccp(_screenSize.width*0.65, _screenSize.height*0.99)); }else{ jindutiao->setPosition(ccp(_screenSize.width*0.65, _screenSize.height*0.95)); } addChild(jindutiao); if (GameScene::instance()->getShip()->getActor()->count()<=1) { CCSprite* jindudixing = CCSprite::createWithSpriteFrameName("ui_game_xing.png"); jindudixing->setPosition(ccp(-15, 2)); jindudixing->setAnchorPoint(ccp(0, 0.5)); jindutiao->addChild(jindudixing,10); } // CCSprite* jindu = CCSprite::createWithSpriteFrameName("ui_lvshang.png"); // // jindu->setAnchorPoint(ccp(0, 1)); // // jindu->setPosition(ccp(2, -5)); // // jindutiao->addChild(jindu); CCSprite* jindudi ; CCSprite* tiao; if (GameScene::instance()->getShip()->getActor()->count()<=1) { // for(int i = 0 ; i <3 ;++i){ // CCSprite* xing = CCSprite::createWithSpriteFrameName("ui_diaoyuxing.png"); // xing->setPosition(ccp(jindudi->boundingBox().size.width*0.3*(i+1), -20)); // // jindutiao->addChild(xing); // } tiao = CCSprite::createWithSpriteFrameName("ui_lvshangxing.png"); jindudi = CCSprite::createWithSpriteFrameName("ui_diaoyu1xing.png"); }else{ tiao = CCSprite::createWithSpriteFrameName("ui_lvshang.png"); jindudi = CCSprite::createWithSpriteFrameName("ui_diaoyu1.png"); } jindudi->setAnchorPoint(ccp(0, 1)); jindudi->setPosition(ccp(0, 0)); jindutiao->addChild(jindudi); _score_tiao = CCProgressTimer::create(tiao); _score_tiao->setType(kCCProgressTimerTypeBar); _score_tiao->setBarChangeRate(ccp(1,0)); _score_tiao->setMidpoint(ccp(0, 0)); _score_tiao->setPercentage(0); _score_tiao->setAnchorPoint(ccp(0, 1)); _score_tiao->setPosition(ccp(5, -7)); jindutiao->addChild(_score_tiao); _buttons = ButtonWithSpriteManage::create("ui/button.png"); addChild(_buttons); _buttons->addButton(BUTTON_GAME_PAUSE, "button_zanting.png", ccp(_screenSize.width*0.95, _screenSize.height*0.92)); if (IS_ON_BUTTON) { // _buttons->addButton(BUTTON_GAME_RIGHT, "button_you.png", ccp(_screenSize.width*0.075+140, _screenSize.height*0.1)); // // ButtonWithSprite* button = ButtonWithSprite::create(BUTTON_GAME_LEFT, "button_you.png",-1,1); // // button->setPosition(ccp(_screenSize.width*0.075, _screenSize.height*0.1)); // // _buttons->addButton(button); _hook = CCSprite::createWithSpriteFrameName("button_xiagou.png"); _hook->setPosition(ccp(_screenSize.width*0.925, _screenSize.height*0.1)); _hook->setScaleX(-1); _hook->setTag(-1); addChild(_hook); _left = CCSprite::createWithSpriteFrameName("button_you.png"); _left->setPosition(ccp(_screenSize.width*0.075, _screenSize.height*0.1)); _left->setScaleX(-1); _left->setTag(-1); addChild(_left); _right = CCSprite::createWithSpriteFrameName("button_you.png"); _right->setPosition(ccp(_screenSize.width*0.075+140, _screenSize.height*0.1)); _right->setTag(-1); addChild(_right); // _buttons->addButton(BUTTON_GAME_DO, "button_xiagou.png", ccp(_screenSize.width*0.925, _screenSize.height*0.1)); } float y =_screenSize.height*0.09 ; if (IS_ON_BUTTON) { y =_screenSize.height*0.3 ; } // _buttons->addButton(BUTTON_GAME_ALLGET, "button_citie.png", ccp(_screenSize.width*0.925, _screenSize.height*0.3)); ButtonWithSprite* all = ButtonWithSprite::create(BUTTON_GAME_ALLGET, "button_citie.png"); all->setPosition(ccp(_screenSize.width*0.925, y)); _citieLabel = CCLabelAtlas::create(Tools::intToString(getAll).c_str() , "ui/shuzi4.png", 21, 28, 43); _citieLabel->setScale(0.8); _citieLabel->setAnchorPoint(ccp(0.5, 0.5)); _citieLabel->setPosition(ccp(90,20)); all->addChild(_citieLabel); _buttons->addButton(all); _timeLabel = CCLabelAtlas::create("0", "ui/shuzi1.png", 21, 28, 43); _timeLabel->setAnchorPoint(ccp(0.5, 0.5)); _timeLabel->setPosition(ccp(_screenSize.width*0.5, _screenSize.height*0.96)); addChild(_timeLabel); _score_Label = CCLabelAtlas::create("0", "ui/shuzi8.png", 14, 21, 43); _score_Label->setAnchorPoint(ccp(1, 0.5)); _score_Label->setPosition(ccp(-5, -jindudi->boundingBox().size.height*0.5)); // _score_Label->setVisible(false); jindutiao->addChild(_score_Label,200); return true; } return false; } void GameUI::onEnter() { CCLayer::onEnter(); } void GameUI::onExit() { CCTextureCache::sharedTextureCache()->removeTextureForKey("ui/game.png"); CCSpriteFrameCache::sharedSpriteFrameCache()->removeSpriteFramesFromFile("ui/game.plist"); CCLayer::onExit(); } bool GameUI::GameUItouchesBegan(CCSet * touchs,CCEvent * event) { if (_buttons->touchesBegan(touchs, event)) { return true; } return false; } void GameUI::GameUItouchesMoved(CCSet * touchs,CCEvent * event) { _buttons->touchesMoved(touchs, event); } void GameUI::GameUItouchesCancelled(CCSet * touchs,CCEvent * event) { _buttons->touchesCancelled(touchs, event); } void GameUI::GameUItouchesEnded(CCSet * touchs,CCEvent * event) { _buttons->touchesEnded(touchs, event); } void GameUI::GameUItouchesMovedDir(cocos2d::CCSet *touchs, cocos2d::CCEvent *event) { _left->setScaleX(-1); _left->setScaleY(1); _right->setScale(1); _hook->setScale(1); setDir(DIR_NONE); _ishook = false; for(CCSetIterator iter=touchs->begin();iter!=touchs->end();iter++){ CCTouch * mytouch=(CCTouch *)(* iter); CCPoint pos=mytouch->getLocation(); if (_left->getTag() == mytouch->getID()&&_left->boundingBox().containsPoint(pos)) { _left->setScaleX(-0.8); _left->setScaleY(0.8); setDir(DIR_LEFT); } if (_right->getTag() == mytouch->getID()&& _right->boundingBox().containsPoint(pos)) { _right->setTag(mytouch->getID()); _right->setScale(0.8); setDir(DIR_RIGHT); } if (_hook->getTag() == mytouch->getID()&& _hook->boundingBox().containsPoint(pos)) { _hook->setTag(mytouch->getID()); _hook->setScale(0.8); _ishook = true; } } } void GameUI::GameUItouchesDir(cocos2d::CCSet *touchs, cocos2d::CCEvent *event) { _set = false; _hook->setScale(1); _ishook = false; for(CCSetIterator iter=touchs->begin();iter!=touchs->end();iter++){ CCTouch * mytouch=(CCTouch *)(* iter); CCPoint pos=mytouch->getLocation(); if (!_set&&(_left->getTag() == mytouch->getID()||_right->getTag() == mytouch->getID())) { _set = true; _left->setScaleX(-1); _left->setScaleY(1); _right->setScale(1); setDir(DIR_NONE); // CCLOG("?????? lt %i rt %i id %i",_left->getTag(),_right->getTag(),mytouch->getID()); } if (_left->boundingBox().containsPoint(pos)) { _left->setTag(mytouch->getID()); _left->setScaleX(-0.8); _left->setScaleY(0.8); setDir(DIR_LEFT); } if (_right->boundingBox().containsPoint(pos)) { _right->setTag(mytouch->getID()); _right->setScale(0.8); setDir(DIR_RIGHT); } if (_hook->boundingBox().containsPoint(pos)) { _hook->setTag(mytouch->getID()); _hook->setScale(0.8); _ishook = true; } } } int GameUI::getNowButtonID() const { return _buttons->getNowID(); } void GameUI::setTime(int time) { _timeLabel->setString(Tools::intToString(time).c_str()); } void GameUI::setScoreTiao(float sc) { _score_tiao->setPercentage(sc); } void GameUI::setScoreTiao1(float sc) { _score_tiao1->setPercentage(sc); } void GameUI::setScore(int sc) { _score_Label->setString(Tools::intToString(sc).c_str()); } void GameUI::setScore1(int sc) { _score_Label1->setString(Tools::intToString(sc).c_str()); } void GameUI::addMubiaoScore(std::vector<int> mubiao) { if (true) { return; } for (int i = 0 ; i<mubiao.size(); ++i) { CCLabelAtlas* mubiaoLabel = CCLabelAtlas::create(Tools::intToString(mubiao[i]).c_str(), "ui/shuzi2.png", 18, 26, 48); mubiaoLabel->setAnchorPoint(ccp(0.5, 0.5)); mubiaoLabel->setPosition(ccp(_screenSize.width*0.7+_screenSize.width*0.08*i, _screenSize.height*0.9)); addChild(mubiaoLabel); } } CCSprite* GameUI::getLeft() { return _left; } CCSprite* GameUI::getRight() { return _right; } CCSprite* GameUI::getHook() { return _hook; } void GameUI::setSucNum(std::string str) { _num->setString(str.c_str()); } void GameUI::setSuc() { zuodi->removeChild(_node, true); CCSprite* wancheng = CCSprite::createWithSpriteFrameName("dacheng.png"); wancheng->setPosition(ccp(zuodi->boundingBox().size.width*0.5+20,zuodi->boundingBox().size.height*0.5-2)); wancheng->setScale(3); CCScaleTo* sc = CCScaleTo::create(0.3, 1); wancheng->runAction(sc); zuodi->addChild(wancheng); } void GameUI::setCitieNum(int num) { _citieLabel->setString(Tools::intToString(num).c_str()); }
#include <stdio.h> #include <stdlib.h> struct node { int item; struct node *next; }; typedef struct node nd; nd *p1,*p2; main() { p1=(nd*)malloc(sizeof(nd)); p2=(nd*)malloc(sizeof(nd)); p1->item=12; p2->item=34; p1=p2; p2->next=p1; printf("%d %d\n",p1->item,p1->next->item); printf("%d %d",p2->item,p2->next->item); }
#include <iostream> #include <boost/program_options.hpp> #include "sodium.h" #include "cryptobox/core/HSM.hpp" namespace po = boost::program_options; namespace crb = cryptobox; void printHelp(std::ostream& out, po::options_description const& desc) { out << "--- Simple Cryptobox ---\n"; out << desc << "\n"; } // something very simple const std::string defaultStorageLocation = "default.crb"; void createKeys(std::ostream& out, int nKeys) { cryptobox::HSM hsm{defaultStorageLocation}; std::vector<std::optional<uint32_t>> ids(nKeys); for (auto& h : ids) h = hsm.Create(); for (auto const& h : ids) h ? out << "Key Handle " << h.value() << " created\n" : std::cout << "Invalid Key Handle"; } void signMessage(std::ostream& out, uint32_t const handle, std::string const& msg) { cryptobox::HSM hsm{defaultStorageLocation}; // for the original message it is a simple copy std::vector<unsigned char> msgV(msg.size()); for (int i=0; i<msg.size(); i++) msgV[i] = msg[i]; // signing if (auto signedMsg = hsm.Sign(handle, msgV); signedMsg.has_value()) { // we output hex-formatted binary blob for the signature std::vector<char> hex(signedMsg.value().size()*2+1); sodium_bin2hex(hex.data(), hex.size(), signedMsg.value().data(), signedMsg.value().size()); for (auto const c : hex) out << c; out << '\n'; } else { // ERROR out << "ERROR: Invalid handle provided...\n"; } } void verifySignature(std::ostream& out, uint32_t const handle, std::string const& signedMsg) { cryptobox::HSM hsm{defaultStorageLocation}; // decode hex to bin std::vector<unsigned char> bin(signedMsg.size()); size_t bin_len; sodium_hex2bin(bin.data(), bin.size(), signedMsg.data(), signedMsg.size(), NULL, &bin_len, NULL); assert(bin_len>0 && "Hex to Bin length greater than 0"); bin.resize(bin_len); if (auto result = hsm.Verify(handle, bin); result.has_value()) { if (auto status = result.value().first; status == crb::HSM::Rejected) out << "Verification: Rejected\n"; else out << "Verification: Accepted\n"; } else { // ERROR out << "ERROR: Invalid handle provided...\n"; } } int main(int argc, char** argv) { // Declare the supported options. po::options_description desc("Allowed options:"); desc.add_options() ("help", "produce help message") ("create", po::value<int>(), "create N keys") ("sign", po::value<std::string>(), "message to sign") ("verify", po::value<std::string>(), "signed msg to verify") ("handle", po::value<uint32_t>(), "handle id") ; // validate user input po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (std::exception const& e) { std::cout << "ERROR: "<< e.what() << std::endl; std::cout << "Terminating" << std::endl; return 1; } catch (...) { std::cout << "ERROR: uncaught exception" << std::endl; std::cout << "Terminating" << std::endl; return 1; } // help checked first if (vm.count("help")) { printHelp(std::cout, desc); return 0; } // check sodium if (sodium_init() == -1) { std::cout << "Sodium is not initialized properly! aborting...\n"; return 1; } // keys creation if (vm.count("create")) { auto nKeysToCreate = vm["create"].as<int>(); createKeys(std::cout, nKeysToCreate); // TODO return 0; } // signing process if (vm.count("sign")) { auto msg = vm["sign"].as<std::string>(); if (vm.count("handle")) { auto handle = vm["handle"].as<uint32_t>(); signMessage(std::cout, handle, msg); return 0; } else { std::cout << "WARNING: No Key Handle/Id was provided to sign the msg... \nTerminating...\n"; return 0; } } // verify if (vm.count("verify")) { auto signedMsg = vm["verify"].as<std::string>(); if (vm.count("handle")) { auto handle = vm["handle"].as<uint32_t>(); verifySignature(std::cout, handle, signedMsg); return 0; } else { std::cout << "WARNING: No Key Handle/Id was provided to sign the msg... \nTerminating...\n"; return 0; } } std::cout << "None of the known options were provided...\nTerminating\n"; printHelp(std::cout, desc); return 0; }
// wrong answer #include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <queue> #include <unordered_set> #include <unordered_map> #include <stack> #include <cstdio> #define INT_MIN (1<<31) #define INT_MAX (~INT_MIN) #define UNREACHABLE (INT_MAX>>2) #define INF (1e300) #define eps (1e-9) using namespace std; ifstream fin("11284_input.txt"); //#define cin fin struct dvd_info { dvd_info(int id_store, long long gain) { this->id_store = id_store; this->gain = gain; } int id_store; long long gain; }; int main() { int tttt; scanf("%d", &tttt); while (tttt--) { int n, m; scanf("%d %d", &n, &m); vector<vector<long long> > dist(n + 1, vector<long long>(n + 1, INT_MAX)); for (int i = 0; i < m; i++) { int s, t; long long d1, d2; scanf("%d %d %lld.%lld", &s, &t, &d1, &d2); // cout << "debug:\t" << d1 << d2 << endl; dist[s][t] = dist[t][s] = d1 * 100 + d2; } for (int i = 0; i <= n; i++) dist[i][i] = 0; for (int k = 0; k <= n; k++) for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); int p; scanf("%d", &p); vector<dvd_info> dvd; //(p, dvd_info(0, 0)); unordered_map<int, int> map; int count = 0; for (int i = 0; i < p; i++) { int id; long long d1, d2; scanf("%d %lld.%lld", &id, &d1, &d2); if (!map.count(id)) { map[id] = count++; dvd.push_back(dvd_info(id, d1 * 100 + d2)); } else { int pos = map[id]; dvd[pos].gain += d1 * 100 + d2; } } p = count; vector<vector<long long> > f(p, vector<long long>((1 << (p)), INT_MIN)); for (int i = 0; i < p; i++) f[i][1 << i] = - dist[0][dvd[i].id_store] + dvd[i].gain; vector< pair<int, int> > o; for (int i = 0; i < (1 << p); i++) { o.push_back(make_pair(__builtin_popcount(i), i)); } sort(o.begin(), o.end()); for (int i = 0; i < o.size(); i++) { int state = o[i].second; for (int j = 0; j < dvd.size(); j++) { if (f[j][state] == INT_MIN) continue; int u = dvd[j].id_store; //ret = max(ret, dp[state][j] - g[u][0]); for (int k = 0; k < dvd.size(); k++) { if ((state >> k) & 1) continue; int v = dvd[k].id_store; f[k][state | (1 << k)] = max(f[k][state | (1 << k)], f[j][state] - dist[u][v] + dvd[k].gain); } } } ////for (auto it : o) //for (int j = 0; j < (1 << (p)); j++) //{ // //int j = it.second; // for (int i = 0; i < p; i++) // to position i // { // int to = 1 << i; // for (int k = 0; k < p; k++) // from position k // if (i != k && f[k][j & (~to)] != INT_MIN) // { // int from = 1 << k; // if ((to & j) && (from & j)) // j contains to and from // f[i][j] = max(f[i][j], f[k][j & (~to)] + dvd[i].gain - dist[dvd[k].id_store][dvd[i].id_store]); // } // } //} long long result = 0; for (int j = 0; j < (1 << (p)); j++) for (int i = 0; i < p; i++) if (f[i][j] != INT_MIN) result = max(result, f[i][j] - dist[dvd[i].id_store][0]); if (result <= 0) printf("Don't leave the house\n"); else printf("Daniel can save $%lld.%02lld\n", result / 100, result % 100); } }
#ifndef BULLETS_T #define BULLETS_T #include <QGraphicsPixmapItem> #include <QObject> #include <QMediaPlayer> class Bullets : public QObject, public QGraphicsPixmapItem { Q_OBJECT public: Bullets(QGraphicsItem * parent = 0); ~Bullets(); public slots: void move(); private: QMediaPlayer * bulletSound; }; #endif // ! BULLET_T
$NetBSD$ Missing include on NetBSD. --- src/libexpr/primops/fetchGit.cc~ 2019-11-01 16:57:52.564146995 +0000 +++ src/libexpr/primops/fetchGit.cc 2019-11-01 16:59:08.187456642 +0000 @@ -6,6 +6,8 @@ #include "hash.hh" #include <sys/time.h> +#include <sys/wait.h> + #include <regex>
#pragma once #include "Task.h" #include "R2D2.h" #include "Robot.h" #include "Xwing.h" namespace T3D { class AnimationMove : public Task { public: float variance = 0.2f; float elapsedTime = 0; float time; bool rotate = false; bool displace = false; Vector3 startPos; Vector3 endPos; Quaternion startRot; Quaternion endRot; GameObject * object = NULL; AnimationMove(T3DApplication * app); ~AnimationMove(); void update(float dt); }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef MDE_OPFONTMANAGER_H #define MDE_OPFONTMANAGER_H #include "modules/pi/OpFont.h" struct MDE_GenericFonts { /** The name of the font used for serif */ const char* serif_font; /** The name of the font used for sans serif */ const char* sans_serif_font; /** The name of the font used for cursives */ const char* cursive_font; /** The name of the font used for fantasy */ const char* fantasy_font; /** The name of the font used for monospace */ const char* monospace_font; /** The default font */ const char* default_font; }; #ifdef _GLYPHTESTING_SUPPORT_ struct MDE_FONT; template<typename T, int SIZE> static T encodeValue(BYTE* bp) { const int BYTE_BITS = 8; T val = 0; for (int i = 0; i < SIZE; ++i) { val = (val << BYTE_BITS) | bp[i]; } return val; } #endif //_GLYPHTESTING_SUPPORT_ class MDE_OpFontManager : public OpFontManager { public: MDE_OpFontManager(); virtual ~MDE_OpFontManager(); void Clear(); OP_STATUS InitFonts(); /** Creates an OpFont object. @param face the name of the font @param size in pixels @param weight weight of the font (0-9). 4 is Normal, 7 is Bold. @param italic does the font contain italic glyphs? @param scale for the view where the font is used @return the created OpFont if it is valid or NULL. Please note that this font may not have all the attributes that you specified. The font may not be available in italic, for example. */ virtual OpFont* CreateFont(const uni_char* face, UINT32 size, UINT8 weight, BOOL italic, BOOL hasoutline, INT32 blur_radius); virtual OpFont* CreateFont(OpWebFontRef webfont, UINT32 size, INT32 blur_radius); virtual OpFont* CreateFont(OpWebFontRef webfont, UINT8 weight, BOOL italic, UINT32 size, INT32 blur_radius); virtual OP_STATUS AddWebFont(OpWebFontRef& webfont, const uni_char* full_path_of_file); virtual OP_STATUS RemoveWebFont(OpWebFontRef webfont); virtual OP_STATUS GetWebFontInfo(OpWebFontRef webfont, OpFontInfo* fontinfo); virtual OP_STATUS GetLocalFont(OpWebFontRef& localfont, const uni_char* facename); virtual BOOL SupportsFormat(int f); /** @return the number of fonts in the system */ virtual UINT32 CountFonts(); /** Get the font info for the specified font. @param fontnr the font you want the info for @param fontinfo an allocated fontinfo object */ virtual OP_STATUS GetFontInfo(UINT32 fontnr, OpFontInfo* fontinfo); /** Is called before first call to CountFonts or GetFontInfo. */ virtual OP_STATUS BeginEnumeration(); /** Is called after all calls to CountFonts and GetFontInfo. */ virtual OP_STATUS EndEnumeration(); virtual void BeforeStyleInit(class StyleManager* styl_man) {} /** Gets the name of the font that is default for the GenericFont. */ virtual const uni_char* GetGenericFontName(GenericFont generic_font); #ifdef PERSCRIPT_GENERIC_FONT virtual const uni_char* GetGenericFontName(GenericFont generic_font, WritingSystem::Script script) { return GetGenericFontName(generic_font); } #endif // PERSCRIPT_GENERIC_FONT #ifdef HAS_FONT_FOUNDRY /** * Search for a font on any given format ("helvetica", "adobe-helvetica", * "adobe-helvetica-iso8859-1" etc.). This method should support any format * that is likely to be used (which is implementation specific). It should * return (through full_name) the full, real font name, as it is (or would * have been) stored in OpFontDatabase. The method may choose not to verify * that the font name exists, as long as it's on the valid format, e.g. if * 'name' is "foo-bar-oste-pop", and the implementation of * FindBestFontName() says that this is the right format (even though the * font doesn't necessarily exist), it may report success. This method is * here to help core find the right font name based on a font specified * on a webpage. On X11, a part of the font name is the foundry name. * Foundry names are never specified on a webpage. A webpage may specify * "Arial" as the font name, while the actual font name on the system is * "Arial [Xft]". * @param name the font name to search for (like "helvetica", * "adobe-helvetica", "adobe-helvetica-iso8859-1", "Helvetica [Adobe]", * etc.) * @full_name the fully qualified name. This name should be on the format * as stored in OpFontDatabase. * @return OpStatus::OK on success, OpStatus::ERR_NO_MEMORY on allocation * failure, OpStatus::ERR on invalid font format. */ virtual OP_STATUS FindBestFontName(const uni_char *name, OpString &full_name); /** * Extract the foundry name from a font string (like "adobe-helvetica-22", * or whatever the font format looks like) * @param font the font string * @param foundry where to put the result. This will be a string * containing only the foundry name (like "adobe"). */ virtual OP_STATUS GetFoundry(const uni_char *font, OpString &foundry); /** * Set the preferred foundry. When a font name is specified without the * foundry (i.e. only the family name is specified) as, for example, the * argument to FindBestFontName(), and this family is available from * several foundries, choose the preferred foundry if possible. * @param foundry The new preferred foundry. */ virtual OP_STATUS SetPreferredFoundry(const uni_char *foundry); #endif // HAS_FONT_FOUNDRY #ifdef PLATFORM_FONTSWITCHING /** * Set the preferred font for a specific unicode block * @param ch a character contained by the actual unicode block. This can be the * first character in the block (like number 0x0370 for Greek), for example. * @param monospace is the specified font supposed to be a replacement for * monospace fonts? */ virtual void SetPreferredFont(uni_char ch, bool monospace, const uni_char *font, OpFontInfo::CodePage codepage=OpFontInfo::OP_DEFAULT_CODEPAGE); #endif // PLATFORM_FONTSWITCHING // additional functions not in OpFontManager interface: virtual OP_STATUS SetDefaultFonts(const MDE_GenericFonts* fonts); /** * Called from EndEnumeration to get the names of the default fonts * MDE_MI_OpFontManager has a default implementation. */ virtual OP_STATUS FindDefaultFonts(MDE_GenericFonts* fonts); #ifdef _GLYPHTESTING_SUPPORT_ virtual void UpdateGlyphMask(OpFontInfo *fontinfo); #endif // _GLYPHTESTING_SUPPORT_ private: OpFont* CreateFont(UINT32 fontnr, UINT32 size, UINT8 weight, BOOL italic, BOOL must_have_getoutline); #ifdef MDEFONT_MODULE OP_STATUS GetFontInfoInternal(const struct MDF_FONTINFO& info, OpFontInfo* fontinfo); #endif // MDEFONT_MODULE class DefaultFonts { public: DefaultFonts() : serif_font(NULL), sans_serif_font(NULL), cursive_font(NULL), fantasy_font(NULL), monospace_font(NULL), default_font(NULL) {} ~DefaultFonts() { Clear(); } void Clear() { op_free(serif_font); serif_font = NULL; op_free(sans_serif_font); sans_serif_font = NULL; op_free(cursive_font); cursive_font = NULL; op_free(fantasy_font); fantasy_font = NULL; op_free(monospace_font); monospace_font = NULL; op_free(default_font); default_font = NULL; } /* set the css fonts that are to be used */ uni_char* serif_font; uni_char* sans_serif_font; uni_char* cursive_font; uni_char* fantasy_font; uni_char* monospace_font; /* also set a default font */ uni_char* default_font; } m_default_fonts; UINT32 m_fontcount; uni_char** m_fontNames; BOOL m_isInEnumeration; }; #endif // MDE_OPFONTMANAGER_H
// Copyright (c) 2017-2018 John Biddiscombe // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // For compliance with the NVIDIA EULA: // "This software contains source code provided by NVIDIA Corporation." // This is a conversion of the NVIDIA cublas example matrixMulCUBLAS to use // pika style data structures, executors and futures and demonstrate a simple use // of computing a number of iteration of a matrix multiply on a stream and returning // a future when it completes. This can be used to chain/schedule other task // in a manner consistent with the future based API of pika. // // Example usage: bin/cublas_matmul --sizemult=10 --iterations=25 --pika:threads=8 // NB. The pika::threads param only controls how many parallel tasks to use for the CPU // comparison/checks and makes no difference to the GPU execution. // // Note: The pika::cuda::experimental::allocator makes use of device code and if used // this example must be compiled with nvcc instead of c++ which requires the following // cmake setting // set_source_files_properties(cublas_matmul.cpp // PROPERTIES CUDA_SOURCE_PROPERTY_FORMAT OBJ) // Currently, nvcc does not handle lambda functions properly and it is simpler to use // cudaMalloc/cudaMemcpy etc, so we do not #define PIKA_CUBLAS_DEMO_WITH_ALLOCATOR #include <pika/assert.hpp> #include <pika/chrono.hpp> #include <pika/cuda.hpp> #include <pika/execution.hpp> #include <pika/functional/bind_front.hpp> #include <pika/init.hpp> #include <pika/testing.hpp> #include <whip.hpp> #include <algorithm> #include <chrono> #include <cmath> #include <cstddef> #include <iostream> #include <random> #include <sstream> #include <utility> #include <vector> #if defined(PIKA_HAVE_HIP) # define CUBLAS_OP_N rocblas_operation_none # define cublasSgemm rocblas_sgemm #endif std::mt19937 gen; namespace cu = pika::cuda::experimental; namespace ex = pika::execution::experimental; namespace tt = pika::this_thread::experimental; // ------------------------------------------------------------------------- // Optional Command-line multiplier for matrix sizes struct sMatrixSize { unsigned int uiWA, uiHA, uiWB, uiHB, uiWC, uiHC; }; // ------------------------------------------------------------------------- // Compute reference data set matrix multiply on CPU // C = A * B // @param C reference data, computed but preallocated // @param A matrix A as provided to device // @param B matrix B as provided to device // @param hA height of matrix A // @param wB width of matrix B // ------------------------------------------------------------------------- template <typename T> void matrixMulCPU(T* C, const T* A, const T* B, unsigned int hA, unsigned int wA, unsigned int wB) { for (unsigned int i = 0; i < hA; ++i) { for (unsigned int j = 0; j < wB; ++j) { T sum = 0; for (unsigned int k = 0; k < wA; ++k) { T a = A[i * wA + k]; T b = B[k * wB + j]; sum += a * b; } C[i * wB + j] = (T) sum; } } } // ------------------------------------------------------------------------- // Compute the L2 norm difference between two arrays inline bool compare_L2_err( const float* reference, const float* data, const unsigned int len, const float epsilon) { PIKA_ASSERT(epsilon >= 0); float error = 0; float ref = 0; for (unsigned int i = 0; i < len; ++i) { float diff = reference[i] - data[i]; error += diff * diff; ref += reference[i] * reference[i]; } float normRef = sqrtf(ref); if (std::fabs(ref) < 1e-7f) { return false; } float normError = sqrtf(error); error = normError / normRef; bool result = error < epsilon; return result; } // ------------------------------------------------------------------------- // Run a simple test matrix multiply using CUBLAS // ------------------------------------------------------------------------- template <typename T> void matrixMultiply(pika::cuda::experimental::cuda_scheduler& cuda_sched, sMatrixSize& matrix_size, std::size_t /* device */, [[maybe_unused]] std::size_t iterations) { // Allocate host memory for matrices A and B unsigned int size_A = matrix_size.uiWA * matrix_size.uiHA; unsigned int size_B = matrix_size.uiWB * matrix_size.uiHB; unsigned int size_C = matrix_size.uiWC * matrix_size.uiHC; std::vector<T> h_A(size_A); std::vector<T> h_B(size_B); std::vector<T> h_C(size_C); std::vector<T> h_CUBLAS(size_C); // Fill A and B with random numbers auto randfunc = [](T& x) { x = gen() / (T) RAND_MAX; }; std::for_each(h_A.begin(), h_A.end(), randfunc); std::for_each(h_B.begin(), h_B.end(), randfunc); T *d_A, *d_B, *d_C; whip::malloc(&d_A, size_A * sizeof(T)); whip::malloc(&d_B, size_B * sizeof(T)); whip::malloc(&d_C, size_C * sizeof(T)); auto copy_A = ex::schedule(cuda_sched) | cu::then_with_stream(pika::util::detail::bind_front( whip::memcpy_async, d_A, h_A.data(), size_A * sizeof(T), whip::memcpy_host_to_device)); auto copy_B = ex::schedule(cuda_sched) | cu::then_with_stream(pika::util::detail::bind_front( whip::memcpy_async, d_B, h_B.data(), size_B * sizeof(T), whip::memcpy_host_to_device)); auto copy_AB = ex::when_all(std::move(copy_A), std::move(copy_B)) | ex::then([]() { std::cout << "The async host->device copy operations completed" << std::endl; }); tt::sync_wait(std::move(copy_AB)); std::cout << "Computing result using CUBLAS...\n"; const T alpha = 1.0f; const T beta = 0.0f; // Perform warmup operation with cublas // note cublas is column major ordering : transpose the order pika::chrono::detail::high_resolution_timer t1; // std::cout << "calling CUBLAS...\n"; auto gemm = ex::transfer_just(cuda_sched) | cu::then_with_cublas( [&](cublasHandle_t handle) { cu::check_cublas_error(cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, matrix_size.uiWB, matrix_size.uiHA, matrix_size.uiWA, &alpha, d_B, matrix_size.uiWB, d_A, matrix_size.uiWA, &beta, d_C, matrix_size.uiWA)); }, CUBLAS_POINTER_MODE_HOST); // wait until the operation completes tt::sync_wait(std::move(gemm)); double us1 = t1.elapsed<std::chrono::microseconds>(); std::cout << "warmup: elapsed_microseconds " << us1 << std::endl; // once the sender has been synchronized, the next call to // schedule/then_with_x will create a new event attached to a new sender so // we can reuse the same cuda scheduler stream if we want // See https://github.com/brycelelbach/wg21_p2300_std_execution/issues/466 // for details. #if defined(PIKA_HAVE_STDEXEC) std::cout << "skipping remainder of test because the stdexec implementation of split does not " "yet support move-only senders" << std::endl; #else pika::chrono::detail::high_resolution_timer t2; // This loop is currently inefficient. Because of the type-erasure with // unique_any_sender the cuBLAS calls are not scheduled on the same stream // without synchronization. ex::unique_any_sender<> gemms_finished = ex::just(); for (std::size_t j = 0; j < iterations; j++) { gemms_finished = std::move(gemms_finished) | ex::transfer(cuda_sched) | cu::then_with_cublas( [&](cublasHandle_t handle) { cu::check_cublas_error(cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, matrix_size.uiWB, matrix_size.uiHA, matrix_size.uiWA, &alpha, d_B, matrix_size.uiWB, d_A, matrix_size.uiWA, &beta, d_C, matrix_size.uiWA)); }, CUBLAS_POINTER_MODE_HOST); } auto gemms_finished_split = ex::split(std::move(gemms_finished)); auto matrix_print_finished = gemms_finished_split | ex::then([&]() { double us2 = t2.elapsed<std::chrono::microseconds>(); std::cout << "actual: elapsed_microseconds " << us2 << " iterations " << iterations << std::endl; // Compute and print the performance double usecPerMatrixMul = us2 / iterations; double flopsPerMatrixMul = 2.0 * (double) matrix_size.uiWA * (double) matrix_size.uiHA * (double) matrix_size.uiWB; double gigaFlops = (flopsPerMatrixMul * 1.0e-9) / (usecPerMatrixMul / 1e6); printf("Performance = %.2f GFlop/s, Time = %.3f msec/iter, Size = %.0f Ops\n", gigaFlops, 1e-3 * usecPerMatrixMul, flopsPerMatrixMul); }); // when the matrix operations complete, copy the result to the host auto copy_finished = std::move(gemms_finished_split) | ex::transfer(cuda_sched) | cu::then_with_stream(pika::util::detail::bind_front(whip::memcpy_async, h_CUBLAS.data(), d_C, size_C * sizeof(T), whip::memcpy_device_to_host)); auto all_done = ex::when_all(std::move(matrix_print_finished), std::move(copy_finished)) | ex::then([&]() { // compute reference solution on the CPU std::cout << "\nComputing result using host CPU...\n"; // compute reference solution on the CPU // allocate storage for the CPU result std::vector<T> reference(size_C); pika::chrono::detail::high_resolution_timer t3; matrixMulCPU<T>(reference.data(), h_A.data(), h_B.data(), matrix_size.uiHA, matrix_size.uiWA, matrix_size.uiWB); double us3 = t3.elapsed<std::chrono::microseconds>(); std::cout << "CPU elapsed_microseconds (1 iteration) " << us3 << std::endl; // check result (CUBLAS) bool resCUBLAS = compare_L2_err(reference.data(), h_CUBLAS.data(), size_C, 1e-6); PIKA_TEST_MSG(resCUBLAS, "matrix CPU/GPU comparison error"); // if the result was incorrect, we throw an exception, so here it's ok if (resCUBLAS) { std::cout << "\nComparing CUBLAS Matrix Multiply with CPU results: OK \n"; } }); tt::sync_wait(std::move(all_done)); #endif whip::free(d_A); whip::free(d_B); whip::free(d_C); } // ------------------------------------------------------------------------- int pika_main(pika::program_options::variables_map& vm) { // std::size_t device = vm["device"].as<std::size_t>(); std::size_t sizeMult = vm["sizemult"].as<std::size_t>(); std::size_t iterations = vm["iterations"].as<std::size_t>(); // unsigned int seed = std::random_device{}(); if (vm.count("seed")) seed = vm["seed"].as<unsigned int>(); pika::cuda::experimental::cuda_pool cuda_pool(device); // install cuda future polling handler pika::cuda::experimental::enable_user_polling poll("default"); // gen.seed(seed); std::cout << "using seed: " << seed << std::endl; // sizeMult = (std::min)(sizeMult, std::size_t(100)); sizeMult = (std::max)(sizeMult, std::size_t(1)); // int block_size = 32; sMatrixSize matrix_size; matrix_size.uiWA = 2 * block_size * sizeMult; matrix_size.uiHA = 4 * block_size * sizeMult; matrix_size.uiWB = 2 * block_size * sizeMult; matrix_size.uiHB = 4 * block_size * sizeMult; matrix_size.uiWC = 2 * block_size * sizeMult; matrix_size.uiHC = 4 * block_size * sizeMult; printf("MatrixA(%u,%u), MatrixB(%u,%u), MatrixC(%u,%u)\n\n", matrix_size.uiWA, matrix_size.uiHA, matrix_size.uiWB, matrix_size.uiHB, matrix_size.uiWC, matrix_size.uiHC); // -------------------------------- // test matrix multiply using cuda scheduler pika::cuda::experimental::cuda_scheduler cuda_sched(std::move(cuda_pool)); matrixMultiply<float>(cuda_sched, matrix_size, device, iterations); // -------------------------------- // sanity check : test again using a copy of the cuda scheduler std::cout << "\n\n\n------------" << std::endl; std::cout << "Checking copy semantics of cuda scheduler" << std::endl; pika::cuda::experimental::cuda_scheduler cuda_sched2 = cuda_sched; matrixMultiply<float>(cuda_sched2, matrix_size, device, 1); // -------------------------------- // sanity check : test again using a moved copy of the cuda scheduler std::cout << "\n\n\n------------" << std::endl; std::cout << "Checking move semantics of cuda scheduler" << std::endl; pika::cuda::experimental::cuda_scheduler cuda_sched3(std::move(cuda_sched)); matrixMultiply<float>(cuda_sched3, matrix_size, device, 1); return pika::finalize(); } // ------------------------------------------------------------------------- int main(int argc, char** argv) { printf("[pika Matrix Multiply CUBLAS] - Starting...\n"); using namespace pika::program_options; options_description cmdline("usage: " PIKA_APPLICATION_STRING " [options]"); // clang-format off cmdline.add_options() ("device", pika::program_options::value<std::size_t>()->default_value(0), "Device to use") ("sizemult", pika::program_options::value<std::size_t>()->default_value(5), "Multiplier") ("iterations", pika::program_options::value<std::size_t>()->default_value(30), "iterations") ("no-cpu", pika::program_options::value<bool>()->default_value(false), "disable CPU validation to save time") ("seed,s", pika::program_options::value<unsigned int>(), "the random number generator seed to use for this run"); // clang-format on pika::init_params init_args; init_args.desc_cmdline = cmdline; #if defined(PIKA_HAVE_STDEXEC) PIKA_TEST(true); #endif return pika::init(pika_main, argc, argv, init_args); }
#pragma once #include "texture.h" #include "sprite.h" #include "singleton.h" #include "named_vector.h" #include <nlohmann/json.hpp> struct SpriteInfo : public Sprite { std::string Name; uint32_t TextureId{ 0 }; }; void from_json(const nlohmann::json& j, SpriteInfo& info); void to_json(nlohmann::json& j, const SpriteInfo& info); struct AnimationInfo { uint32_t SpriteId; uint32_t Delay; // in ms }; class GraphicsImpl : public Singleton { public: NamedVector<Texture> Textures; NamedVector<Texture> Textures2D; NamedVector<SpriteInfo> Sprites; void Load(); void Reset(); private: ~GraphicsImpl() { Reset(); } void LoadTextures(); void LoadTexture(const std::string& fileName, const std::string& name); void LoadTexture(const Image& image, const std::string& name); void LoadSprites(); void LoadSpriteInfo(uint32_t textId, const std::string& fileName, NamedVector<SpriteInfo>& res); void AddSquare(NamedVector<SpriteInfo>& to); friend GraphicsImpl& GraphicsMut(); }; const GraphicsImpl& Graphics(); GraphicsImpl& GraphicsMut();
#pragma once #include <pthread.h> namespace pthreadhelp { class LockGuard { public: LockGuard() = delete ; LockGuard(pthread_mutex_t& mutex) : mutex(mutex) { pthread_mutex_lock(&mutex); } ~LockGuard() { pthread_mutex_unlock(&mutex); } private: pthread_mutex_t& mutex; }; template<class T> class SimpleQueue { public: SimpleQueue(); SimpleQueue(const SimpleQueue<T> &another); SimpleQueue<T>& operator=(const SimpleQueue<T> &other); virtual ~SimpleQueue(); virtual void enqueue(const T &item); virtual T dequeue(); virtual bool empty() const; protected: struct QueueNode; typedef QueueNode *PNode; struct QueueNode { T data; PNode next; QueueNode(T data = T(), PNode next = nullptr) : data(data), next(next) { } }; PNode mFront; PNode volatile mBack; }; template<class T> SimpleQueue<T>::SimpleQueue(const SimpleQueue<T> &another) : mFront(nullptr), mBack(nullptr) { mBack = new QueueNode(); mFront = new QueueNode(T(), mBack); if (!another.empty()) { for (PNode cur = another.mFront->next; cur; cur = cur->next) { enqueue(cur->data); } } } template<class T> SimpleQueue<T>& SimpleQueue<T>::operator=(const SimpleQueue<T> &other) { if (&other == this) { return *this; } mBack = new QueueNode(); mFront = new QueueNode(T(), mBack); if (!other.empty()) { for (PNode cur = other.mFront->next; cur != other.mBack; cur = cur->next) { enqueue(cur->data); } } return *this; } template<class T> SimpleQueue<T>::SimpleQueue() : mFront(nullptr), mBack(nullptr) { mBack = new QueueNode(); mFront = new QueueNode(T(), mBack); } template<class T> SimpleQueue<T>::~SimpleQueue() { for (PNode cur = mFront, tmp; cur; cur = tmp) { tmp = cur->next; delete cur; } } template<class T> bool SimpleQueue<T>::empty() const { return mFront->next == mBack; } template<class T> T SimpleQueue<T>::dequeue() { T result = mFront->next->data; PNode tmp = mFront; mFront = mFront->next; delete tmp; return result; } template<class T> void SimpleQueue<T>::enqueue(T const &item) { mBack->next = new QueueNode(); mBack->data = item; mBack = mBack->next; } }
#include "Characters.h" #include "Map.h" #include "MySFML.h" #include <iostream> //--------------------------------------------------------------------------------------- Character::Character() { hp = 100; state = State::Idle; } //--------------------------------------------------------------------------------------- void Character::Draw() { SetCoord(position); cout << Symb; } //--------------------------------------------------------------------------------------- void Character::move(Direction dir) { Position OldPos = position; switch (dir) { case Up: if (position.y > 0 && Map::get().isEmptyCell(position.y - 1, position.x)) { getMySFML().getSpriteHero().setTextureRect(IntRect(36, 166, 36, 53)); getMySFML().getSpriteHero().move(0, -0.1); break; } else return; case Down: if (position.y < Map::get().height && Map::get().isEmptyCell(position.y + 1, position.x)) { getMySFML().getSpriteHero().setTextureRect(IntRect(36, 0, 36, 53)); getMySFML().getSpriteHero().move(0, 0.1); break; } else return; case Left: if (position.x > 0 && Map::get().isEmptyCell(position.y, position.x - 1)) { getMySFML().getSpriteHero().setTextureRect(IntRect(36, 58, 36, 53)); getMySFML().getSpriteHero().move(-0.1, 0); break; } else return; case Right: if (position.x < Map::get().width && Map::get().isEmptyCell(position.y, position.x + 1)) { getMySFML().getSpriteHero().setTextureRect(IntRect(34, 113, 34, 53)); getMySFML().getSpriteHero().move(0.1, 0); break; } else return; case None: default: return; } SetCoord(OldPos); std::cout << ' '; Draw(); // if (Keyboard::isKeyPressed(Keyboard::S)) // { // heroSprite.setTextureRect(IntRect(36, 0, 36, 53)); // heroSprite.move(0, 0.1 * time); // } // else if (Keyboard::isKeyPressed(Keyboard::A)) // { // heroSprite.setTextureRect(IntRect(36, 58, 36, 53)); // heroSprite.move(-0.1 * time, 0); // } // else if (Keyboard::isKeyPressed(Keyboard::D)) // { // heroSprite.setTextureRect(IntRect(34, 113, 34, 53)); // heroSprite.move(0.1 * time, 0); // } // else if (Keyboard::isKeyPressed(Keyboard::W)) // { // heroSprite.setTextureRect(IntRect(36, 166, 36, 53)); // heroSprite.move(0, -0.1 * time); // } // if (Keyboard::isKeyPressed(Keyboard::S)) // { // CurrentFrame += 0.005*time; // if (CurrentFrame > 4) // CurrentFrame -= 4; // heroSprite.setTextureRect(IntRect(36 * int(CurrentFrame), 0, 36, 53)); // heroSprite.move(0, 0.1 * time); // } // else if (Keyboard::isKeyPressed(Keyboard::A)) // { // CurrentFrame += 0.005*time; // if (CurrentFrame > 4) // CurrentFrame -= 4; // heroSprite.setTextureRect(IntRect(36 * int(CurrentFrame), 58, 36, 53)); // heroSprite.move(-0.1 * time, 0); // } // else if (Keyboard::isKeyPressed(Keyboard::D)) // { // CurrentFrame += 0.005*time; // if (CurrentFrame > 4) // CurrentFrame -= 4; // heroSprite.setTextureRect(IntRect(34 * int(CurrentFrame), 113, 34, 53)); // heroSprite.move(0.1 * time, 0); // } // else if (Keyboard::isKeyPressed(Keyboard::W)) // { // CurrentFrame += 0.005*time; // if (CurrentFrame > 4) // CurrentFrame -= 4; // heroSprite.setTextureRect(IntRect(36 * int(CurrentFrame), 166, 36, 53)); // heroSprite.move(0, -0.1 * time); // } } //---------------------------------------------------------------------------------------
#include <string> #include <vector> using namespace std; class Solution { public: string longestPalindrome(string s) { // DP: /** * Fib: fib(n) = fib(n-1) + fib(n-2) * e.g.: * fib(5) * / \ * fib(4) [fib(3)] * / \ / \ * [fib(3)] fib(2) fib(2) fib(1) * ... * Here "fib(3)" has the overlapping calculation in a recursive solution, and - * we can solve this problem by using DP, to reuse the result of "fib(3)"; * * How to solve DP problem: * 1. find the exiting rules; * 2. find the recursive equation; * 3. set a 1/2/3 dimension array to save the result; * 4. fill out the array in a loop; * 5. find the result in the meanwhile and exit the loop according to the exit rules; */ const auto len = s.length(); if (len <= 1) { return s; } string str; bool dp[len][len]; for (auto i = 0; i < len; i++) { for (auto j = 0; j < len; j++) { dp[i][j] = false; } } /** * i 0 1 * j x - - * 0 x x - * 1 x x x */ for (auto j = 0; j < len; j++) { /** * exiting rules: * - P(i, i) = true; * - P(i, i + 1) = (s[i] == s[i + 1]); * - "j" must be greater or equal than "i", [i, j] indicates a substring; * * recursive equation: * - P(i, j) = (P(i + 1, j - 1) and s[i] == s[j]); */ for (auto i = 0; i <= j; i++) { if (i == j) { dp[i][j] = true; } else if (i == j - 1) { dp[i][j] = s.at(i) == s.at(j); } else { dp[i][j] = (dp[i + 1][j - 1] && (s.at(i) == s.at(j))); } if (dp[i][j] && (j - i + 1 > str.length())) { str = s.substr(i, j - i + 1); } } } return str; } };
#include <iostream> #include <vector> using namespace std; using ll = long long; int main() { ll A, B; cin >> A >> B; ll S = A + B; ll K; for (K = 1e6; K * (K + 1) / 2 > S; --K) {}; // 1+2+...+K <= A+B vector<int> a, b; for (int i = K; i > 0; --i) { if (A >= i) { a.push_back(i); A -= i; } else if (B >= i) { b.push_back(i); B -= i; } } cout << a.size() << endl; for (int c : a) cout << c << " "; cout << endl; cout << b.size() << endl; for (int c : b) cout << c << " "; cout << endl; return 0; }
/* -*- coding: utf-8 -*- !@time: 2020/3/2 21:42 !@author: superMC @email: 18758266469@163.com !@fileName: 0039_balanced_binary_tree.cpp */ #include <environment.h> #include <selfFun.h> using self_envs::TreeNode; class Solution { public: bool IsBalanced_Solution(TreeNode *pRoot) { if (pRoot == nullptr) return true; int depth = 0; return IsBalanced_Solution(pRoot, depth); } bool IsBalanced_Solution(TreeNode *pRoot, int &pDepth) { if (pRoot == nullptr) { pDepth = 0; return true; } int left = 0, right = 0; if (IsBalanced_Solution(pRoot->left, left) && IsBalanced_Solution(pRoot->right, right)) { int diff = left - right; if (abs(diff) <= 1) { pDepth = 1 + (left > right ? left : right); return true; } } return false; } }; int fun() { TreeNode *root = stringToTreeNode("[3,9,20,null,null,15,7]"); printf("%s", Solution().IsBalanced_Solution(root) ? "true" : "false"); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- ** ** Copyright (C) 2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef CRYPTO_UTILITY_H_ #define CRYPTO_UTILITY_H_ class CryptoUtility { public: /** * Converts the specified array of source bytes into a string with a base 64 * encoded representation of the source array. You can use * ConvertFromBase64() to convert the base 64 encoded string into byte * array. * @param[in] source Is the byte array to convert to a string with * a base 64 encoding of this data. * @param[in] source_length Is the number of source bytes to convert. * @param[out] base_64 Receives on success the base 64 encoded string. * * @retval OpStatus::OK On Success. * @retval OpStatus::ERR In case of an error. * * @see ConvertFromBase64() */ static OP_STATUS ConvertToBase64(const UINT8 *source, int source_length, OpString8 &base_64); /** * Converts the specified string from base 64 encoding into a byte array. * @param[in] source Is the string containing base 64 encoded data. * @param[out] binary Receives on success a newly allocated byte-array * that contains the data of the specified source. The * caller needs to free this byte-array by calling * OP_DELETEA(binary). * @param[out] length Receives on success the number of bytes in the * returned byte-array. * * @retval OpStatus::OK On Success. * @retval OpStatus::ERR_NO_MEMORY If there is not enough memory to allocate * the byte-array. * @retval OpStatus::ERR In case of any other error. * * @see ConvertToBase64() */ static OP_STATUS ConvertFromBase64(const char *source, UINT8 *&binary, int& length); }; #endif /* CRYPTO_UTILITY_H_ */
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2010 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #ifndef __SSLBASE_H #define __SSLBASE_H #ifdef _NATIVE_SSL_SUPPORT_ #include "modules/libssl/ssluint.h" #include "modules/libssl/base/sslenum.h" #include "modules/util/simset.h" #include "modules/datastream/fl_lib.h" class SSL_Alert; class SSL_Error_Status; class SSL_varvector32; class SSL_varvector16; class SSL_ConnectionState; class SSL_Cipher; class SSL_Hash; class LoadAndWritableList; typedef AutoDeleteHead SSL_Head; typedef DataStream_UIntBase LoadAndWritableUIntBase; typedef DataStream_UIntVarLength LoadAndWritableUIntVarLength; typedef DataStream_ByteArray LoadAndWritableByteArray; typedef LoadAndWritableList SSL_Handshake_Message_Base; OP_STATUS SetLangString(Str::LocaleString str, OpString &target); #include "modules/libssl/base/sslexcept.h" #include "modules/libssl/base/sslalertbase.h" #include "modules/libssl/base/sslerr.h" #include "modules/libssl/base/loadtemp.h" #include "modules/libssl/base/sslalert.h" #include "modules/libssl/base/sslvar.h" #include "modules/libssl/base/sslvarl1.h" #endif #endif
#include "settings.h" const QString Settings::GlassHeight = "glass/height"; const QString Settings::GlassWidth = "glass/width"; Settings::Settings() : QSettings("tetris.ini", QSettings::IniFormat) { }
#pragma once template <class Key, class T> class QMap; template <class T1, class T2> class QPair; class QString; class Configurator { public: static void readConfigurations(); static QString getHostName(); static int getPort(); private: static QPair<QString, QString> handleLine(QString line); static void writeDefaultConfigurationsFile(); static QMap<QString, QString> m_configurations; };
#include<iostream> #include<cstring> #include<climits> using namespace std; int n,dp[1000][1000]; int f(int i,int j,int arr[]) { if(i>j) return 0; int q1=arr[i]+min(f(i+1,j-1,arr),f(i+2,j,arr)); int q2=arr[j]+min(f(i,j-2,arr),f(i+1,j-1,arr)); return max(q1,q2); } int dpsol(int arr[]) { for(int i=0;i<=n;i++) { for(int j=0;j<=n;j++) { if(i>=j) dp[i][j]=0; else dp[i][j]=max((arr[i]+min(dp[i+1][j-1],dp[i+2][j])),(arr[j]+min(dp[i][j-2],dp[i+1][j-1]))); cout<<dp[i][j]<<" "; } cout<<endl; } return dp[n-1][n-1]; } int dp_memo(int i,int j,int arr[]) { if(i>j) return 0; if(dp[i][j]!=-1) return dp[i][j]; int q1=arr[i]+min(f(i+1,j-1,arr),f(i+2,j,arr)); int q2=arr[j]+min(f(i,j-2,arr),f(i+1,j-1,arr)); dp[i][j]=max(q1,q2); return dp[i][j]; } int main() { cin>>n; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; memset(dp,-1,sizeof(dp)); //Recursive call f(0,n-1,arr); //cout<<dpsol(arr)<<endl; cout<<dp_memo(0,n-1,arr); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @file * @author Owner: shuais * */ #ifndef __SYNC_BOOKMARK_ITEMS_H__ #define __SYNC_BOOKMARK_ITEMS_H__ #include "modules/sync/sync_coordinator.h" #include "modules/sync/sync_dataitem.h" #include "adjunct/quick/hotlist/HotlistManager.h" class SyncManager; class BookmarkSync; /************************************************************************* ** ** SyncBookmarkItems - forward bookmark syncing notifications to core bookmark syncer ** ** **************************************************************************/ class SyncBookmarkItems : public OpSyncDataClient , public HotlistModelListener { public: SyncBookmarkItems(); virtual ~SyncBookmarkItems(); // Implementing HotlistModelListener interface // Only handle OnHotlistItemChanged in Desktop, core will take care of adding/removing/moving void OnHotlistItemAdded(HotlistModelItem* item) {} void OnHotlistItemRemoved(HotlistModelItem* item, BOOL removed_as_child) {} void OnHotlistItemTrashed(HotlistModelItem* item ) {} void OnHotlistItemUnTrashed(HotlistModelItem* item) {} void OnHotlistItemMovedFrom(HotlistModelItem* item) {} void OnHotlistItemChanged(HotlistModelItem* item, BOOL moved_as_child, UINT32 changed_flag = HotlistModel::FLAG_UNKNOWN); // OpSyncDataClient virtual OP_STATUS SyncDataInitialize(OpSyncDataItem::DataItemType type); virtual OP_STATUS SyncDataAvailable(OpSyncCollection *new_items, OpSyncDataError& data_error); virtual OP_STATUS SyncDataFlush(OpSyncDataItem::DataItemType type, BOOL first_sync, BOOL is_dirty); virtual OP_STATUS SyncDataSupportsChanged(OpSyncDataItem::DataItemType type, BOOL has_support); private: BookmarkSync* m_core_bookmarks_syncer; BOOL m_is_receiving_items; // Avoid sending back change from sync server }; #endif // __SYNC_BOOKMARK_ITEMS_H__
#include <iostream> #include <string> #include <vector> using namespace std; int main() { string s; cin >> s; int len = s.length(); if (s[0] == 'A') { } }
#include "Pick.h" void iberbar::PickRayFromClient( D3DXVECTOR3* pOutRayPosition, D3DXVECTOR3* pOutRayDirection, const D3DXMATRIX* pMatProj, const CSize* pViewport, const CPoint* pClientPoint ) { assert( pOutRayPosition ); assert( pOutRayDirection ); assert( pMatProj ); assert( pViewport ); assert( pClientPoint ); // 暂时只考虑viewport的x和y都等于0的情况 *pOutRayPosition = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); *pOutRayDirection = D3DXVECTOR3( (((2.0f*pClientPoint->x/pViewport->cx)-1.0f)/(*pMatProj)(0,0)), (((-2.0f*pClientPoint->y/pViewport->cy)+1.0f)/(*pMatProj)(1,1)), 1.0f ); } void iberbar::TransformRay( D3DXVECTOR3* pOutRayPosition, D3DXVECTOR3* pOutRayDirection, const D3DXMATRIX* pMat ) { assert( pMat ); assert( pOutRayPosition ); assert( pOutRayDirection ); D3DXMATRIX lc_matViewInverse; D3DXMatrixInverse( &lc_matViewInverse, NULL, pMat ); D3DXVec3TransformCoord( pOutRayPosition, pOutRayPosition, &lc_matViewInverse ); D3DXVec3TransformNormal( pOutRayDirection, pOutRayDirection, &lc_matViewInverse ); D3DXVec3Normalize( pOutRayDirection, pOutRayDirection ); } void iberbar::Coordinate3dToClient( CPoint* pOutClientPoint, const iberbar::CSize* pViewport, const D3DXVECTOR3* pEye, const D3DXVECTOR3* pCoord, const D3DXMATRIX* pMatView, const D3DXMATRIX* pMatProj ) { D3DXVECTOR3 lc_point; D3DXVec3TransformCoord( &lc_point, pCoord, pMatView ); D3DXVec3TransformCoord( &lc_point, &lc_point, pMatProj ); pOutClientPoint->x = (lc_point.x+1)/2 * (float)pViewport->cx; pOutClientPoint->y = (1-lc_point.y)/2 * (float)pViewport->cy; }
// Created on: 1998-01-22 // Created by: Sergey ZARITCHNY // Copyright (c) 1998-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _PrsDim_EllipseRadiusDimension_HeaderFile #define _PrsDim_EllipseRadiusDimension_HeaderFile #include <gp_Elips.hxx> #include <PrsDim_Relation.hxx> #include <PrsDim_KindOfSurface.hxx> class Geom_OffsetCurve; class TopoDS_Shape; class TCollection_ExtendedString; class Geom_Surface; DEFINE_STANDARD_HANDLE(PrsDim_EllipseRadiusDimension, PrsDim_Relation) //! Computes geometry ( basis curve and plane of dimension) //! for input shape aShape from TopoDS //! Root class for MinRadiusDimension and MaxRadiusDimension class PrsDim_EllipseRadiusDimension : public PrsDim_Relation { DEFINE_STANDARD_RTTIEXT(PrsDim_EllipseRadiusDimension, PrsDim_Relation) public: virtual PrsDim_KindOfDimension KindOfDimension() const Standard_OVERRIDE { return PrsDim_KOD_ELLIPSERADIUS; } virtual Standard_Boolean IsMovable() const Standard_OVERRIDE { return Standard_True; } Standard_EXPORT void ComputeGeometry(); protected: Standard_EXPORT PrsDim_EllipseRadiusDimension(const TopoDS_Shape& aShape, const TCollection_ExtendedString& aText); protected: gp_Elips myEllipse; Standard_Real myFirstPar; Standard_Real myLastPar; Standard_Boolean myIsAnArc; Handle(Geom_OffsetCurve) myOffsetCurve; Standard_Real myOffset; Standard_Boolean myIsOffset; private: Standard_EXPORT void ComputeFaceGeometry(); Standard_EXPORT void ComputeCylFaceGeometry (const PrsDim_KindOfSurface aSurfType, const Handle(Geom_Surface)& aSurf, const Standard_Real Offset); Standard_EXPORT void ComputePlanarFaceGeometry(); Standard_EXPORT void ComputeEdgeGeometry(); }; #endif // _PrsDim_EllipseRadiusDimension_HeaderFile
#include <bits/stdc++.h> using namespace std; void heapify(vector<int>& v,int i){ //int temp = v[i-1]; while(i<=v.size()){ int childa = 2*i; int childb = 2*i+1; if(childa<=v.size()&&v[i-1]<v[childa-1]){ swap(v[i-1],v[childa-1]); heapify(v,childa); } if(childb<=v.size()&&v[i-1]<v[childb-1]) { swap(v[i-1],v[childb-1]); heapify(v,childb); } return; } } void deletenode(vector<int>& v,int i){ swap(v[v.size()-1],v[i-1]); cout<<v[v.size()-1]<<" "; v.pop_back(); int j = 2*i; while(j<=v.size()){ if(j<v.size()&&v[j]>v[j-1]) j++; if(v[j-1]>v[i-1]){ swap(v[j-1],v[i-1]); i=j; j=2*j; } else break; } } int main() { int n; cin>>n; vector<int> v(n); for(int i =0;i<n;i++){ cin>>v[i]; } for(int i = v.size();i>0;i--) { heapify(v,i); } cout<<"Heapify :"; for(int i =0;i<n;i++){ cout<<v[i]<<" "; } cout<<endl<<"Check if correctly heapified: "; for(int i =0;i<v.size();) { deletenode(v,1); } return 0; }
/** ****************************************************************************** * File Name : main.c * Description : Main program body ****************************************************************************** * * COPYRIGHT(c) 2016 STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal.h" #include <cstdlib> #include "diag/Trace.h" #include <memory> #include "f4Gpio.h" TIM_HandleTypeDef htim4; //UART_HandleTypeDef huart2; //SPI_HandleTypeDef hspi2; //char readBuf[1]; //__IO ITStatus UartReady = SET; std::unique_ptr<IGpio> gpio_a = std::make_unique<F4Gpio>(reinterpret_cast<uintptr_t>(GPIOA)); void SystemClock_Config(); static void MX_GPIO_Init(); int main() { /* MCU Configuration----------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* Configure the system clock */ SystemClock_Config(); /* Initialize all configured peripherals */ MX_GPIO_Init(); //#ifdef DEBUG // trace_printf("System clock: %u Hz\n", SystemCoreClock); //#endif __TIM4_CLK_ENABLE(); htim4.Init.Prescaler = 1342; htim4.Init.CounterMode = TIM_COUNTERMODE_UP; htim4.Init.Period = 62499; htim4.Instance = TIM4; //Same timer whose clocks we enabled HAL_TIM_Base_Init(&htim4); // Init timer HAL_TIM_Base_Start_IT(&htim4); // start timer interrupts HAL_NVIC_SetPriority(TIM4_IRQn, 0, 1); HAL_NVIC_EnableIRQ(TIM4_IRQn); HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET); gpio_a->writePin(GPIO_Pin::PIN_4, GPIO_PinState_::RESET); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmissing-noreturn" while (true) HAL_Delay(1000); #pragma clang diagnostic pop } void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { (void) htim; HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5); gpio_a->togglePin(GPIO_Pin::PIN_4); } /** System Clock Configuration */ void SystemClock_Config() { RCC_OscInitTypeDef RCC_OscInitStruct; RCC_ClkInitTypeDef RCC_ClkInitStruct; __PWR_CLK_ENABLE(); __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2); RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = 16; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; RCC_OscInitStruct.PLL.PLLM = 16; RCC_OscInitStruct.PLL.PLLN = 336; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; RCC_OscInitStruct.PLL.PLLQ = 7; HAL_RCC_OscConfig(&RCC_OscInitStruct); RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2); HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000); HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); } /** Configure pins as * Analog * Input * Output * EVENT_OUT * EXTI PA2 ------> USART2_TX PA3 ------> USART2_RX */ void MX_GPIO_Init() { GPIO_InitTypeDef GPIO_InitStruct; /* GPIO Ports Clock Enable */ __GPIOC_CLK_ENABLE(); __GPIOA_CLK_ENABLE(); /*Configure GPIO pin : PC13 - USER BUTTON */ GPIO_InitStruct.Pin = GPIO_PIN_13; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; GPIO_InitStruct.Pull = GPIO_PULLDOWN; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); /*Configure GPIO pin : PA5 - LD2 LED */ GPIO_InitStruct.Pin = GPIO_PIN_5|GPIO_PIN_4; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_LOW; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
#pragma once #include <glad/glad.h> #include <GLFW/glfw3.h> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include <shaders.h> #include <vector> #include <map> enum DRAW_MODE { DM_NORMAL, DM_NO_LINES, DM_ONLY_LINES }; class Object { private: std::vector<float> vertices; unsigned int VAO, VBO; public: DRAW_MODE drawMode = DM_NORMAL; glm::vec4 color; glm::vec4 lineColor; glm::vec3 position; glm::vec3 rotation = glm::vec3(0, 1, 0); float rotationAngle = 0; glm::vec3 scale = glm::vec3(1); Object(std::vector<float> nVertices = std::vector<float>(), glm::vec3 nPosition = glm::vec3(0), glm::vec4 nColor = glm::vec4(1), glm::vec4 nLineColor = glm::vec4(0), DRAW_MODE nDrawMode = DM_NO_LINES) { vertices = nVertices; position = nPosition; color = nColor; lineColor = nLineColor; drawMode = nDrawMode; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), &vertices[0], GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // normal attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); } void Draw(Shader shader) { glm::mat4 transform = glm::mat4(1.f); transform = glm::translate(transform, position); transform = glm::scale(transform, scale); transform = glm::rotate(transform, rotationAngle, rotation); glBindVertexArray(VAO); shader.setMat3("normalMat", glm::mat3(glm::inverse(glm::transpose(transform)))); shader.setMat4("model", transform); if (drawMode == DM_NORMAL || drawMode == DM_NO_LINES) { shader.setVec4("objectColor", color); glDrawArrays(GL_TRIANGLES, 0, 36); } if (drawMode == DM_NORMAL || drawMode == DM_ONLY_LINES) { shader.setVec4("objectColor", lineColor); glDrawArrays(GL_LINE_STRIP, 0, 36); } } void Destroy() { glDeleteBuffers(1, &VAO); glDeleteBuffers(1, &VBO); } };
#pragma once class BhvAIAttack : public Hourglass::IAction { public: void LoadFromXML(tinyxml2::XMLElement* data); bool IsRunningChild() const { return false; } void Init(Hourglass::Entity* entity); IBehavior::Result Update(Hourglass::Entity* entity); IBehavior* MakeCopy() const; private: StrID m_TargetTag; hg::Entity* m_Target; hg::Motor* m_Motor; hg::Animation* m_Animation; enum { kNumAttacks = 3 }; StrID m_AttackAnims[kNumAttacks]; float m_AttackAnimSpeeds[kNumAttacks]; float m_AttackInterval; float m_AttackDistance; float m_AttackStartTime; float m_NextAttackTime; bool m_DamageDealt; };
#include <iostream> #include <fstream> #include <map> #include <string> using namespace std; int main(int argc, char** args) { if(argc < 2) { cout << "Usage: rdbr <ROM database file>" << endl; return 1; } ifstream romdb_file; romdb_file.open(args[1]); if(!romdb_file.is_open()) { cout << "Could not open \'" << args[1] << "\'." << endl; return 1; } // get the size of the database uint16_t db_size; romdb_file.read(reinterpret_cast<char*>(&db_size), sizeof(uint16_t)); // go ahead and store titles in a map as they may be handy // later on map<string, string> headers; for(unsigned int i = 0; i < db_size; i++) { string hdr, title; char c = 'a'; // initialize for conditional while(c != '\0') { romdb_file.read(&c, sizeof(char)); hdr += c; } c = 'a'; // reinitialize for conditional while(c != '\0') { romdb_file.read(&c, sizeof(char)); title += c; } headers[hdr] = title; } romdb_file.close(); // print out list cout << "Found " << headers.size() << " titles." << endl; for(auto it = headers.begin(); it != headers.end(); it++) cout << it->first << " -> " << it->second << endl; return 0; }
#ifndef OPENCV_CUDA_SAMPLE_PERFORMANCE_H_ #define OPENCV_CUDA_SAMPLE_PERFORMANCE_H_ #include <iostream> #include <cstdio> #include <vector> #include <numeric> #include <string> #include <opencv2/core/utility.hpp> #define TAB " " class Runnable { public: explicit Runnable(const std::string& nameStr): name_(nameStr) {} virtual ~Runnable() {} const std::string& name() const { return name_; } virtual void run() = 0; private: std::string name_; }; class TestSystem { public: static TestSystem& instance() { static TestSystem me; return me; } void setWorkingDir(const std::string& val) { working_dir_ = val; } const std::string& workingDir() const { return working_dir_; } void setTestFilter(const std::string& val) { test_filter_ = val; } const std::string& testFilter() const { return test_filter_; } void setNumIters(int num_iters) { num_iters_ = num_iters; } void addInit(Runnable* init) { inits_.push_back(init); } void addTest(Runnable* test) { tests_.push_back(test); } void run(); // It's public because OpenCV callback uses it void printError(const std::string& msg); std::stringstream& startNewSubtest() { finishCurrentSubtest(); return cur_subtest_description_; } bool stop() const { return cur_iter_idx_ >= num_iters_; } void cpuOn() { cpu_started_ = cv::getTickCount(); } void cpuOff() { int64 delta = cv::getTickCount() - cpu_started_; cpu_times_.push_back(delta); ++cur_iter_idx_; } void cpuComplete() { cpu_elapsed_ += meanTime(cpu_times_); cur_subtest_is_empty_ = false; cur_iter_idx_ = 0; } void gpuOn() { gpu_started_ = cv::getTickCount(); } void gpuOff() { int64 delta = cv::getTickCount() - gpu_started_; gpu_times_.push_back(delta); ++cur_iter_idx_; } void gpuComplete() { gpu_elapsed_ += meanTime(gpu_times_); cur_subtest_is_empty_ = false; cur_iter_idx_ = 0; } bool isListMode() const { return is_list_mode_; } void setListMode(bool value) { is_list_mode_ = value; } private: TestSystem(): cur_subtest_is_empty_(true), cpu_elapsed_(0), gpu_elapsed_(0), speedup_total_(0.0), num_subtests_called_(0), is_list_mode_(false), num_iters_(10), cur_iter_idx_(0) { cpu_times_.reserve(num_iters_); gpu_times_.reserve(num_iters_); } void finishCurrentSubtest(); void resetCurrentSubtest() { cpu_elapsed_ = 0; gpu_elapsed_ = 0; cur_subtest_description_.str(""); cur_subtest_is_empty_ = true; cur_iter_idx_ = 0; cpu_times_.clear(); gpu_times_.clear(); } double meanTime(const std::vector<int64> &samples); void printHeading(); void printSummary(); void printMetrics(double cpu_time, double gpu_time, double speedup); std::string working_dir_; std::string test_filter_; std::vector<Runnable*> inits_; std::vector<Runnable*> tests_; std::stringstream cur_subtest_description_; bool cur_subtest_is_empty_; int64 cpu_started_; int64 gpu_started_; double cpu_elapsed_; double gpu_elapsed_; double speedup_total_; int num_subtests_called_; bool is_list_mode_; int num_iters_; int cur_iter_idx_; std::vector<int64> cpu_times_; std::vector<int64> gpu_times_; }; #define GLOBAL_INIT(name) \ struct name##_init: Runnable { \ name##_init(): Runnable(#name) { \ TestSystem::instance().addInit(this); \ } \ void run(); \ } name##_init_instance; \ void name##_init::run() #define TEST(name) \ struct name##_test: Runnable { \ name##_test(): Runnable(#name) { \ TestSystem::instance().addTest(this); \ } \ void run(); \ } name##_test_instance; \ void name##_test::run() #define SUBTEST TestSystem::instance().startNewSubtest() #define CPU_ON \ while (!TestSystem::instance().stop()) { \ TestSystem::instance().cpuOn() #define CPU_OFF \ TestSystem::instance().cpuOff(); \ } TestSystem::instance().cpuComplete() #define CUDA_ON \ while (!TestSystem::instance().stop()) { \ TestSystem::instance().gpuOn() #define CUDA_OFF \ TestSystem::instance().gpuOff(); \ } TestSystem::instance().gpuComplete() // Generates a matrix void gen(cv::Mat& mat, int rows, int cols, int type, cv::Scalar low, cv::Scalar high); // Returns abs path taking into account test system working dir std::string abspath(const std::string& relpath); #endif // OPENCV_CUDA_SAMPLE_PERFORMANCE_H_
// // nextNum // J. A. Pearson, jon@jpoffline.com // Feb 2017 // #pragma once #include <vector> #include <iostream> #include <string> #include "tools.h" #include "solution.h" #include "tests.h" #include "exception.h" #include "utils.h" //----------------- Declarations -----------------// namespace JP{ // Run the sampler with choices which are doubles. void run_nextNum_doubles(bool verbose); // Run the sampler with choices which are strings. void run_nextNum_strings(bool verbose); // Run the sampler for manual sample extraction. void run_nextNum_sample(int N); // Factory function to run the sampler for a generic data-type for the choices. template<typename CHOICES_TYPE> void run_sampler(std::vector<CHOICES_TYPE>& choices, std::vector<double> pdf, int nsamples, bool verbose); // Function to print the command-line usage to screen, void usage(); } //----------------- Definitions -----------------// namespace JP{ void run_nextNum_doubles(bool verbose) { ////////////////////////////////////////////////////////////// // // Driver function for the nextNum class // // This example shows the use case with a set of choices // which are DOUBLEs, and a set of probabilities that each // choice is selected. // typedef double CHOICES_TYPE; // ////////////////////////////////////////////////////////////// // Define the input: // choices, their probabilities, and the number of samples std::vector<CHOICES_TYPE> choices { -1, 0, 1, 2, 3}; std::vector<double> pdf {0.01, 0.3, 0.58, 0.1, 0.01}; int nsamples = 1000000; run_sampler<CHOICES_TYPE>(choices, pdf, nsamples, verbose); } void run_nextNum_strings(bool verbose) { ////////////////////////////////////////////////////////////// // // Driver function for the nextNum class // // This example shows the use case with a set of choices // which are STRINGs, and a set of probabilities that each // choice is selected. // typedef std::string CHOICES_TYPE; // ////////////////////////////////////////////////////////////// // Here define the input: // choices, their probabilities, and the number of samples. std::vector<CHOICES_TYPE> choices { "j", "p", "a", "i", "jp"}; std::vector<double> pdf {0.01, 0.3, 0.58, 0.1, 0.01}; int nsamples = 1000000; run_sampler<CHOICES_TYPE>(choices, pdf, nsamples, verbose); } void run_nextNum_sample(int N) { // Driver function for manual sample extraction. // Shows the use of direct extraction; prints to screen in this example implementation. typedef double CHOICES_TYPE; std::vector<CHOICES_TYPE> choices { -1, 0, 1, 2, 3}; std::vector<double> pdf {0.01, 0.3, 0.58, 0.1, 0.01}; JP::nextNum<CHOICES_TYPE> nextNum(choices, pdf); nextNum.print_choices(); std::cout << "Requested samples:" << std::endl; for(int i = 0; i < N; i++) { auto sample = nextNum.gen_sample(); std::cout << i+1 << "/" << N << ": " << sample << std::endl; } } template<typename CHOICES_TYPE> void run_sampler(std::vector<CHOICES_TYPE>& choices, std::vector<double> pdf, int nsamples, bool verbose) { // Factory function to run the sampler with an arbitrary data-type of choices, // for the provided choices, pdf, nsamples, and an option to give a verbose output. JP::nextNum<CHOICES_TYPE> nextNum(choices, pdf); if(verbose) nextNum.print_choices(); nextNum.gen_samples(nsamples); nextNum.analyse_samples(); } void usage() { // Function to print the command-line usage of the application to screen. std::cout << "nextNum sampler useage\n"; std::cout << "-------------------------------------------------------------------------------\n"; std::cout << "Options: -help Display this help message. \n"; std::cout << " -test Run unit tests. \n"; std::cout << " -double Run example sampler with doubles as the data type. \n"; std::cout << " -string Run example sampler with strings as the data type. \n"; std::cout << " -sample NSAMPLES Run sampler and yield back NSAMPLES samples. \n"; std::cout << "-------------------------------------------------------------------------------\n"; std::cout << "\n"; } }
#include <iostream> #include <vector> using namespace std; int main() { vector<int> v; int cnt = 0; for (int i = 0; i < 3; i++) { int x; cin >> x; v.push_back(x); } sort(v.begin(), v.end()); // sortして、それぞれの数の差が奇数か偶数で場合分け // cout << "even, even" << endl; if ((v[1] - v[0]) % 2 == 0 && (v[2] - v[0]) % 2 == 0) { cnt = ((v[2] - v[1]) / 2) + ((v[2] - v[0]) / 2); // cout << "even, odd" << endl; } else if ((v[1] - v[0]) % 2 == 0 && (v[2] - v[1]) % 2 != 0) { cnt = ((v[1] - v[0]) / 2) + 2 * (v[2] - (v[1] + 1)) / 2 + 1; // cout << "odd, even" << endl; } else if ((v[1] - v[0]) % 2 != 0 && (v[2] - v[1]) % 2 == 0) { cnt = (((v[2] + 1) - v[0]) / 2) + ((v[2] - v[1]) / 2) + 1; // cout << "even, even" << endl; } else if ((v[1] - v[0]) % 2 != 0 && (v[2] - v[1]) % 2 != 0) { cnt = ((v[2] - v[0]) / 2) + (((v[2] + 1) - v[1]) / 2) + 1; } cout << cnt << endl; return 0; }
#include <bits/stdc++.h> using namespace std; int n, k; int m[5][5]; bool dfs(int q, int v){ if(q == n){ return (v == 0); } for(int i=0; i<k; i++){ if(dfs(q+1, m[q][i] ^ v)) return true; } return false; } int main(){ cin >> n >> k; for(int i=0; i<n; i++){ for(int j=0; j<k; j++) cin >> m[i][j]; } if(dfs(0, 0)) cout << "Found" << endl; else cout << "Nothing" << endl; return 0; }
#ifndef SHIP_H #define SHIP_H #include "Location.h" class Ship { public: Ship(); virtual ~Ship(); bool isBurnt(); void setShip(Location deck[3]); Location _deck[3]; protected: private: }; #endif // SHIP_H
#pragma once #include "Block.h" #include <vector> #include "rectangularvectors.h" namespace WinTetris { class Polygon : public Block { public: Polygon(); void Rotate() override; }; }
#ifndef BALLLOCALIZER_H #define BALLLOCALIZER_H #include "Ball.h" #include "Maths.h" class BallLocalizer { public: BallLocalizer(); ~BallLocalizer(); void update(Math::Position robotPosition, const BallList& visibleBalls, const Math::Polygon& cameraFOV, double dt); Ball* getBallAround(float x, float y); void purge(const BallList& visibleBalls, const Math::Polygon& cameraFOV); bool isValid(Ball* ball, const BallList& visibleBalls, const Math::Polygon& cameraFOV); private: BallList balls; }; #endif // BALLLOCALIZER_H
/************************************************************************************************* ** Author: Chris Matian ** Date: 08/08/2017 ** Description: This is the header class specification file for initializing the Tic Tac Toe board. *************************************************************************************************/ #ifndef BOARD_HPP #define BOARD_HPP #include <iostream> using std::cout; using std::endl; using std::cin; // Enumerator enum gameState {X_WON, O_WON, DRAW, UNFINISHED}; class Board { public: // Default Constructor Board(); // Methods bool makeMove(int, int, char); int gameState(); void print(); private: // Board Declaration as char char board[3][3]; int turn; }; #endif
#pragma once #include "stdafx.h" #include "DataTypes\define.h" #include "skeleton.h" enum orient { R_Z_90 = 0x001, R_Y_90 = 0x010, R_X_90 = 0x100 }; #define VOLUME_REC(a) (a[0]*a[1]*a[2]) class boneAbstract { public: boneAbstract(bone* boneO, float voxelSize); boneAbstract(void); ~boneAbstract(void); Vec3i getSizeByOrientation(int orientation); Vec3i getSizeByOrientation(BOOL xRot, BOOL yRot, BOOL zRot); // Need to find // Vec3i posi; // int orientation; bone *original; // Unchanged Vec3i sizei; // temp float volumeRatiof; // ratio to total volume float aspectRatiof[2]; // ratio of two longer edge over shortest edge // For maintaining order after sorting int idxInArray; };
class Category_562 { duplicate = 569; };
#include "Central.hpp" #include "TitleScene.hpp" #include "BattleScene.hpp" #include "Key.hpp" #include "UseDxLib.hpp" #include <memory> namespace game { void TitleScene::Update() { //タイトル文字描画 DxLib::DrawString(50, 50,"文字シューティング", DxLib::GetColor(255, 255, 255)); if (Key::GetInstance().GetKey(KEY_INPUT_RETURN) == 1) Central::GetInstance().ChangeScene(std::make_unique<BattleScene>()); } }
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno. // WARNING: Changes might be lost if you edit this file directly. #include <_root.app18_accessor_app18_Button_Value.h> #include <app18.Button.h> #include <Uno.Bool.h> #include <Uno.Object.h> #include <Uno.String.h> #include <Uno.Type.h> #include <Uno.UX.IPropertyListener.h> #include <Uno.UX.PropertyObject.h> #include <Uno.UX.Selector.h> static uString* STRINGS[1]; static uType* TYPES[3]; namespace g{ // internal sealed class app18_accessor_app18_Button_Value :61 // { // static generated app18_accessor_app18_Button_Value() :61 static void app18_accessor_app18_Button_Value__cctor__fn(uType* __type) { ::g::Uno::UX::Selector_typeof()->Init(); app18_accessor_app18_Button_Value::Singleton_ = app18_accessor_app18_Button_Value::New1(); app18_accessor_app18_Button_Value::_name_ = ::g::Uno::UX::Selector__op_Implicit(::STRINGS[0/*"Value"*/]); } static void app18_accessor_app18_Button_Value_build(uType* type) { ::STRINGS[0] = uString::Const("Value"); ::TYPES[0] = ::g::app18::Button_typeof(); ::TYPES[1] = ::g::Uno::String_typeof(); ::TYPES[2] = ::g::Uno::Type_typeof(); type->SetFields(0, ::g::Uno::UX::Selector_typeof(), (uintptr_t)&app18_accessor_app18_Button_Value::_name_, uFieldFlagsStatic, ::g::Uno::UX::PropertyAccessor_typeof(), (uintptr_t)&app18_accessor_app18_Button_Value::Singleton_, uFieldFlagsStatic); } ::g::Uno::UX::PropertyAccessor_type* app18_accessor_app18_Button_Value_typeof() { static uSStrong< ::g::Uno::UX::PropertyAccessor_type*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::UX::PropertyAccessor_typeof(); options.FieldCount = 2; options.ObjectSize = sizeof(app18_accessor_app18_Button_Value); options.TypeSize = sizeof(::g::Uno::UX::PropertyAccessor_type); type = (::g::Uno::UX::PropertyAccessor_type*)uClassType::New("app18_accessor_app18_Button_Value", options); type->fp_build_ = app18_accessor_app18_Button_Value_build; type->fp_ctor_ = (void*)app18_accessor_app18_Button_Value__New1_fn; type->fp_cctor_ = app18_accessor_app18_Button_Value__cctor__fn; type->fp_GetAsObject = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::PropertyObject*, uObject**))app18_accessor_app18_Button_Value__GetAsObject_fn; type->fp_get_Name = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::Selector*))app18_accessor_app18_Button_Value__get_Name_fn; type->fp_get_PropertyType = (void(*)(::g::Uno::UX::PropertyAccessor*, uType**))app18_accessor_app18_Button_Value__get_PropertyType_fn; type->fp_SetAsObject = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::PropertyObject*, uObject*, uObject*))app18_accessor_app18_Button_Value__SetAsObject_fn; type->fp_get_SupportsOriginSetter = (void(*)(::g::Uno::UX::PropertyAccessor*, bool*))app18_accessor_app18_Button_Value__get_SupportsOriginSetter_fn; return type; } // public generated app18_accessor_app18_Button_Value() :61 void app18_accessor_app18_Button_Value__ctor_1_fn(app18_accessor_app18_Button_Value* __this) { __this->ctor_1(); } // public override sealed object GetAsObject(Uno.UX.PropertyObject obj) :67 void app18_accessor_app18_Button_Value__GetAsObject_fn(app18_accessor_app18_Button_Value* __this, ::g::Uno::UX::PropertyObject* obj, uObject** __retval) { return *__retval = uPtr(uCast< ::g::app18::Button*>(obj, ::TYPES[0/*app18.Button*/]))->Value(), void(); } // public override sealed Uno.UX.Selector get_Name() :64 void app18_accessor_app18_Button_Value__get_Name_fn(app18_accessor_app18_Button_Value* __this, ::g::Uno::UX::Selector* __retval) { return *__retval = app18_accessor_app18_Button_Value::_name_, void(); } // public generated app18_accessor_app18_Button_Value New() :61 void app18_accessor_app18_Button_Value__New1_fn(app18_accessor_app18_Button_Value** __retval) { *__retval = app18_accessor_app18_Button_Value::New1(); } // public override sealed Uno.Type get_PropertyType() :66 void app18_accessor_app18_Button_Value__get_PropertyType_fn(app18_accessor_app18_Button_Value* __this, uType** __retval) { return *__retval = ::TYPES[1/*string*/], void(); } // public override sealed void SetAsObject(Uno.UX.PropertyObject obj, object v, Uno.UX.IPropertyListener origin) :68 void app18_accessor_app18_Button_Value__SetAsObject_fn(app18_accessor_app18_Button_Value* __this, ::g::Uno::UX::PropertyObject* obj, uObject* v, uObject* origin) { uPtr(uCast< ::g::app18::Button*>(obj, ::TYPES[0/*app18.Button*/]))->SetValue(uCast<uString*>(v, ::TYPES[1/*string*/]), origin); } // public override sealed bool get_SupportsOriginSetter() :69 void app18_accessor_app18_Button_Value__get_SupportsOriginSetter_fn(app18_accessor_app18_Button_Value* __this, bool* __retval) { return *__retval = true, void(); } ::g::Uno::UX::Selector app18_accessor_app18_Button_Value::_name_; uSStrong< ::g::Uno::UX::PropertyAccessor*> app18_accessor_app18_Button_Value::Singleton_; // public generated app18_accessor_app18_Button_Value() [instance] :61 void app18_accessor_app18_Button_Value::ctor_1() { ctor_(); } // public generated app18_accessor_app18_Button_Value New() [static] :61 app18_accessor_app18_Button_Value* app18_accessor_app18_Button_Value::New1() { app18_accessor_app18_Button_Value* obj1 = (app18_accessor_app18_Button_Value*)uNew(app18_accessor_app18_Button_Value_typeof()); obj1->ctor_1(); return obj1; } // } } // ::g
#include <iostream> #include <cmath> #include <map> using namespace std; using ll = long long; using ld = long double; const ll MOD = 998244353; template <typename T> T gcd(T a, T b) { if (a < b) return gcd(b, a); return b == 0 ? a : gcd(b, a % b); } template <typename T, typename U> T mypow(T b, U n) { if (n == 0) return 1; if (n == 1) return b; if (n % 2 == 0) { return mypow(b * b, n / 2); } else { return mypow(b, n - 1) * b; } } int main() { int N; cin >> N; map<ll, int> s; for (int i = 0; i < N; ++i) { ll b; cin >> b; if (!s.count(b)) s[b] = 0; ++s[b]; } N = s.size(); ll a[N], c[N]; { int i = 0; for (auto p : s) { a[i] = p.first; c[i] = p.second; ++i; } } ll ans = 1; map<ll, int> cnt; for (int i = 0; i < N; ++i) { bool divided = false; for (int k = 4; k >= 2; --k) { ll p = roundl(powl((ld)a[i], (ld)1 / k)); if (mypow(p, k) == a[i]) { divided = true; if (!cnt.count(p)) cnt[p] = 0; cnt[p] += k * c[i]; break; } } if (divided) continue; for (int j = 0; j < N; ++j) { if (i == j) continue; ll g = gcd(a[i], a[j]); if (g == 1) continue; divided = true; if (!cnt.count(g)) cnt[g] = 0; cnt[g] += c[i]; if (!cnt.count(a[i] / g)) cnt[a[i] / g] = 0; cnt[a[i] / g] += c[i]; break; } if (divided) continue; ans *= (c[i] + 1) * (c[i] + 1); ans %= MOD; } for (auto p : cnt) { ans *= p.second + 1; ans %= MOD; } cout << ans << endl; return 0; }
#define RIGHT_BACKWARD 13 #define RIGHT_FORWARD 12 #define LEFT_BACKWARD 10 #define LEFT_FORWARD 9 #define STEER 14 int duty = 1150; int CYCLE = 4; int low = 200; int run = 165; int fast = 50; char command; void Forward(); void FastForward(); void TurnLeft(); void TurnRight(); void LeftForward(); void RightForward(); void Backward(); void Stop(); void Steer(float ratio); void setup() { Serial.begin(9600); pinMode(LEFT_BACKWARD,OUTPUT); pinMode(RIGHT_BACKWARD,OUTPUT); pinMode(LEFT_FORWARD,OUTPUT); pinMode(RIGHT_FORWARD,OUTPUT); pinMode(STEER,OUTPUT); digitalWrite(LEFT_FORWARD,HIGH); digitalWrite(RIGHT_FORWARD,HIGH); digitalWrite(LEFT_BACKWARD,HIGH); digitalWrite(RIGHT_BACKWARD,HIGH); //digitalWrite(STEER,HIGH); } void loop() { if (Serial.available()>0) { command=Serial.read(); if (command=='F') { Serial.println("Forward"); Forward(); Serial.read(); } else if (command=='B') { Serial.println("Backward"); Backward(); Serial.read(); } else if (command=='L') { Serial.println("TurnLeft"); TurnLeft(); Serial.read(); } else if (command=='R') { Serial.println("TurnRight"); TurnRight(); Serial.read(); } else if (command=='E') { Serial.println("RightForward"); RightForward(); Serial.read(); } else if (command=='Q') { Serial.println("LeftForward"); LeftForward(); Serial.read(); } else if (command=='W') { Serial.println("FastFoward"); FastForward(); Serial.read(); } else if (command=='S') { Serial.println("Stop"); Stop(); Serial.read(); } } } void Forward() { analogWrite(RIGHT_FORWARD,run); digitalWrite(RIGHT_BACKWARD,HIGH); analogWrite(LEFT_FORWARD,run); digitalWrite(LEFT_BACKWARD,HIGH); Steer(1.0); } void Backward() { digitalWrite(RIGHT_FORWARD,HIGH); analogWrite(RIGHT_BACKWARD,low); digitalWrite(LEFT_FORWARD,HIGH); analogWrite(LEFT_BACKWARD,low); Steer(1.0); } void TurnLeft() { digitalWrite(RIGHT_FORWARD,HIGH); analogWrite(RIGHT_BACKWARD,run+30); digitalWrite(LEFT_FORWARD,HIGH); analogWrite(LEFT_BACKWARD,run); Steer(0.85); } void TurnRight() { digitalWrite(RIGHT_FORWARD,HIGH); analogWrite(RIGHT_BACKWARD,run); digitalWrite(LEFT_FORWARD,HIGH); analogWrite(LEFT_BACKWARD,run+30); Steer(1.15); } void Stop() { digitalWrite(LEFT_BACKWARD,HIGH); digitalWrite(RIGHT_BACKWARD,HIGH); digitalWrite(LEFT_FORWARD,HIGH); digitalWrite(RIGHT_FORWARD,HIGH); Steer(1.0); } void Steer(float ratio) { int temp = ratio*duty; for (int i = 0;i < CYCLE;i++) { digitalWrite(STEER,HIGH); delayMicroseconds(temp); digitalWrite(STEER,LOW); delayMicroseconds(10000-temp); delayMicroseconds(6500); } } //Following are addition functions void FastForward() { digitalWrite(RIGHT_FORWARD,LOW); digitalWrite(LEFT_BACKWARD,HIGH); digitalWrite(LEFT_FORWARD,LOW); digitalWrite(LEFT_BACKWARD,HIGH); Steer(1.0); } void LeftForward() { analogWrite(RIGHT_FORWARD,run+5); digitalWrite(RIGHT_BACKWARD,HIGH); analogWrite(LEFT_FORWARD,run+40); digitalWrite(LEFT_BACKWARD,HIGH); Steer(1.15); } void RightForward() { analogWrite(RIGHT_FORWARD,run+40); digitalWrite(RIGHT_BACKWARD,HIGH); analogWrite(LEFT_FORWARD,run+5); digitalWrite(LEFT_BACKWARD,HIGH); Steer(0.85); }
/* * Twosum.h * * Created on: 2021. 9. 7. * Author: dhjeong */ #ifndef TWOSUM_TWOSUM_H_ #define TWOSUM_TWOSUM_H_ #include <vector> class Twosum { public: Twosum(); virtual ~Twosum(); void run(); private: void doTest(std::vector<int>& inputList, int target); }; #endif /* TWOSUM_TWOSUM_H_ */
#include <vector> using namespace std; class counterinfo{ public: int counternumber; int customerno; float depttimeallcurrcustomer; counterinfo(int counternumber,int customerno,float depttimeallcurrcustomer){ this->counternumber=counternumber; this->customerno=customerno; this->depttimeallcurrcustomer=depttimeallcurrcustomer; } }; class customernode{ public: int counterno; float arrivtime; float depttime; customernode(int counterno,float arrivtime,float depttime){ this->counterno=counterno; this->arrivtime=arrivtime; this->depttime=depttime; } }; class heap1 { vector<counterinfo*> data; public: heap1() { data.push_back(NULL); } int size() { return data.size() - 1; } bool isEmpty() { return size() == 0; } void removeMin() { if (isEmpty()) { throw "Empty Heap Error"; } data[1] = data[data.size() - 1]; data.pop_back(); int currentIndex = 1; int leftIndex = 2*currentIndex; int rightIndex = 2*currentIndex + 1; while (leftIndex < data.size()) { int minIndex = currentIndex; if (data[leftIndex]->customerno < data[minIndex]->customerno) { minIndex = leftIndex; } if (rightIndex < data.size() && data[rightIndex]->customerno < data[minIndex]->customerno) { minIndex = rightIndex; } if (minIndex == currentIndex) { break; } else { counterinfo* temp = data[minIndex]; data[minIndex] = data[currentIndex]; data[currentIndex] = temp; currentIndex = minIndex; leftIndex = 2*currentIndex; rightIndex = 2*currentIndex + 1; } } } counterinfo* displayroot() { if (isEmpty()) { throw "Empty Heap Error"; } return data[1]; } counterinfo* search(int counter){ for(int i=1;i<data.size();i++){ if(data[i]->counternumber==counter){ return data[i]; } } return NULL; } void insert(counterinfo* next) { data.push_back(next); int childIndex = data.size() - 1; int parentIndex = childIndex/2; while (childIndex != 1) { if (data[childIndex]->customerno >= data[parentIndex]->customerno) { break; } else { counterinfo* child = data[childIndex]; data[childIndex] = data[parentIndex]; data[parentIndex] = child; childIndex = parentIndex; parentIndex = childIndex/2; } } } void heapify(){ int currentIndex = 1; int leftIndex = 2*currentIndex; int rightIndex = 2*currentIndex + 1; while (leftIndex < data.size()) { int minIndex = currentIndex; if (data[leftIndex]->customerno < data[minIndex]->customerno) { minIndex = leftIndex; } if (rightIndex < data.size() && data[rightIndex]->customerno < data[minIndex]->customerno) { minIndex = rightIndex; } if (minIndex == currentIndex) { break; } else { counterinfo* temp = data[minIndex]; data[minIndex] = data[currentIndex]; data[currentIndex] = temp; currentIndex = minIndex; leftIndex = 2*currentIndex; rightIndex = 2*currentIndex + 1; } } } void heapifydel(int counter){ int childIndex=1; int parentIndex=0; for(int i=1;i<data.size();i++){ if(data[i]->counternumber==counter){ childIndex=i; parentIndex=childIndex/2; } } while (childIndex != 1) { if (data[childIndex]->customerno >= data[parentIndex]->customerno) { break; } else { counterinfo* child = data[childIndex]; data[childIndex] = data[parentIndex]; data[parentIndex] = child; childIndex = parentIndex; parentIndex = childIndex/2; } } } }; class heap2 { vector<customernode*> data; public: heap2() { data.push_back(NULL); } int size() { return data.size() - 1; } bool isEmpty() { return size() == 0; } void removeMin() { if (isEmpty()) { throw "Empty Heap Error"; } data[1] = data[data.size() - 1]; data.pop_back(); int currentIndex = 1; int leftIndex = 2*currentIndex; int rightIndex = 2*currentIndex + 1; while (leftIndex < data.size()) { int minIndex = currentIndex; if (data[leftIndex]->depttime < data[minIndex]->depttime) { minIndex = leftIndex; } if (rightIndex < data.size() && data[rightIndex]->depttime < data[minIndex]->depttime) { minIndex = rightIndex; } if (minIndex == currentIndex) { break; } else { customernode* temp = data[minIndex]; data[minIndex] = data[currentIndex]; data[currentIndex] = temp; currentIndex = minIndex; leftIndex = 2*currentIndex; rightIndex = 2*currentIndex + 1; } } } customernode* displayroot() { if (isEmpty()) { throw "Empty Heap Error"; } return data[1]; } void insert(customernode* next) { data.push_back(next); int childIndex = data.size() - 1; int parentIndex = childIndex/2; while (childIndex != 1) { if (data[childIndex]->depttime >= data[parentIndex]->depttime) { break; } else { customernode* child = data[childIndex]; data[childIndex] = data[parentIndex]; data[parentIndex] = child; childIndex = parentIndex; parentIndex = childIndex/2; } } } };
#include "PacketAccumulator.h" #include "RoomManager.h" PacketAccumulator::PacketAccumulator(RoomManager &roomManager) : m_roomManager(roomManager) { } bool PacketAccumulator::hasRoom(std::array<char, HASH_LENGTH> room) { const std::lock_guard<std::mutex> packetLock(m_packetMutex); return contains(m_packets, room); } void PacketAccumulator::addPacket(std::array<char, HASH_LENGTH> room, ReceivedPacket packet, connection_hdl&& handle) { { const std::lock_guard<std::mutex> packetLock(m_packetMutex); if (!contains(m_packets, room)) { return; } std::vector<ReceivedPacket>& roomPackets = m_packets[room]; roomPackets.emplace_back(packet); } uint16_t identifier = packet.identifier; const std::lock_guard<std::mutex> handleLock(m_handleMutex); std::vector<ReceivedConnection>& roomHandles = m_handles[room]; auto it = std::find_if(roomHandles.begin(), roomHandles.end(), [identifier](const auto& entry) { return identifier == entry.identifier; }); if (it == roomHandles.end()) { roomHandles.emplace_back(ReceivedConnection { identifier, handle, }); } } void PacketAccumulator::removeConnection(uint16_t identifier) { const std::lock_guard<std::mutex> handleLock(m_handleMutex); // technically you could be connected to more than one room, so we check all // later we can optimize this using another map going the opposite direction for (auto& room : m_handles) { auto it = std::find_if(room.second.begin(), room.second.end(), [identifier](const auto& entry) { return identifier == entry.identifier; }); if (it != room.second.end()) { room.second.erase(it); } } } void PacketAccumulator::createRoom(std::array<char, HASH_LENGTH> room) { { const std::lock_guard<std::mutex> packetLock(m_packetMutex); if (contains(m_packets, room)) { return; } m_packets[room] = std::vector<ReceivedPacket>(); } { const std::lock_guard<std::mutex> handleLock(m_handleMutex); m_handles[room] = std::vector<ReceivedConnection>(); } m_roomManager.createRoom(*this, room); } void PacketAccumulator::destroyRoom(std::array<char, HASH_LENGTH> room) { { const std::lock_guard<std::mutex> packetLock(m_packetMutex); if (!contains(m_packets, room)) { return; } m_packets.erase(m_packets.find(room)); } const std::lock_guard<std::mutex> handleLock(m_handleMutex); m_handles.erase(room); } void PacketAccumulator::getConnections(std::vector<ReceivedConnection>& connections, std::array<char, HASH_LENGTH> room) { connections.clear(); const std::lock_guard<std::mutex> handleLock(m_handleMutex); if (!contains(m_handles, room)) { return; } std::vector<ReceivedConnection>& existing = m_handles[room]; connections.reserve(existing.size()); std::copy(existing.begin(), existing.end(), std::back_inserter(connections)); } void PacketAccumulator::getPackets(std::vector<ReceivedPacket>& packets, std::array<char, HASH_LENGTH> room) { packets.clear(); const std::lock_guard<std::mutex> packetLock(m_packetMutex); if (!contains(m_packets, room)) { return; } std::vector<ReceivedPacket>& roomPackets = m_packets[room]; packets.swap(roomPackets); }
#include "sensor.h" Sensor::Sensor(std::string username, double latitude, double longitude, std::string ipAddress, size_t port) { this->username = username; this->latitude = latitude; this->longitude = longitude; this->port = port; this->ipAddress = ipAddress; } Measurement::Measurement(std::string username, std::string parameter, double averageValue) { this->username = username; this->parameter = parameter; this->averageValue = averageValue; } std::string Measurement::getUsername() { return this->username; } std::string Measurement::getParameter() { return this->parameter; } float Measurement::getAverageValue() { return this->averageValue; } void Sensor::addData(std::string parameter, float data) { this->measurements.push_back(new Measurement(this->getUsername() , parameter , data)); } float Sensor::getLatitude() { return this->latitude; } float Sensor::getLongitude() { return this->longitude; } std::string Sensor::getUsername() { return this->username; } size_t Sensor::getPort() { return this->port; } std::string Sensor::getIpAddress() { return this->ipAddress; } std::string Sensor::to_string() { std::string ans = ""; return std::string("userName = ") + std::string(this->username) + std::string(" , port: ") + std::to_string(this->port); } web::json::value Sensor::getJSON() { web::json::value value; value["username"] = json::value::string(this->getUsername()); value["latitude"] = json::value::number(this->getLatitude()); value["longitude"] = json::value::number(this->getLongitude()); value["port"] = json::value::number(this->getPort()); value["ipAddress"] = json::value::string(this->getIpAddress()); return value; }
#include<stdio.h> #include<string.h> #include<memory.h> int main(){ int i,j,T,n; int count[10]; scanf("%d",&T); while(T--){ scanf("%d",&n); memset(count,0,10*sizeof(int)); for(i=1;i<=n;i++){ int num=i; while(num>0){ count[num%10]++; num/=10; } } for(i=0;i<9;i++) printf("%d ",count[i]); printf("%d\n",count[9]); } return 0; }
//顺序队列 #include <iostream> using namespace std; template<class ElemType> class SqQueue { private: const static int MaxSize = 5; ElemType data[MaxSize]; //存放队列元素 int front, rear; //队头指针和队尾指针 public: SqQueue(); //初始化队列对象 bool IsEmpty(); //判断队列是否为空 bool IsFull(); //判断队列是否为满 bool EnQueue(const ElemType&); //入队 bool DeQueue(); //出队 friend ostream& operator<<(ostream& os, const SqQueue<ElemType>& sq) { int sFront = sq.front; int sRear = sq.rear; while (sFront != sRear) { os << "Data[" << sFront << "] = " << sq.data[sFront] << endl; sFront = (sFront + 1) % MaxSize; } return os; } }; template<class ElemType> SqQueue<ElemType>::SqQueue() { this->front = 0; this->rear = 0; } template<class ElemType> bool SqQueue<ElemType>::IsEmpty() { return front == rear; } template<class ElemType> bool SqQueue<ElemType>::IsFull() { return (rear + 1) % MaxSize == front; } template<class ELemType> bool SqQueue<ELemType>::EnQueue(const ELemType& enData) { if (IsFull()) { return false; } else { this->data[rear] = enData; rear = (rear + 1) % MaxSize; return true; } } template<class ElemType> bool SqQueue<ElemType>::DeQueue() { if (IsEmpty()) { return false; } else { cout << this->data[front] << " has been deleted." << endl; front = (front + 1) % MaxSize; return true; } } int main() { SqQueue<int> sq; int data; char choice; cout << "------SqQueue Menu------" << endl << "1-Push,2-Pop,3-Display,0-exit:"; cin >> choice; while (choice != '0') { switch (choice) { case '1': cout << "Input push data:"; cin >> data; if (sq.EnQueue(data)) { cout << "Done!" << endl; } else { cout << "Full!" << endl; } break; case '2': if (sq.DeQueue()) { cout << "Done!" << endl; } else { cout << "Empty!" << endl; } break; case '3': cout << sq << endl; break; default: cout << "Error!" << endl; break; } cout << "Continue or not:"; cin >> choice; } return 0; }
//javier Alvarez Reyes #include <cstdlib> #include <stdlib.h> #include <iostream> #include <fstream> #include<string> #include <sstream> using std::string; #include "vigenere3(E).h" using std::string; using namespace std; int main() { int x=1; int aea; string n; string m; string sifrado; cout << "coloque su mensaje" << endl; getline(cin, n); cout << "coloque la clave" << endl; getline(cin, m); cout << "seleccione(1) si va a cifrar o (2) si va a decifrar" << endl; cin >> aea; if(aea==1) { cifrado p1 = cifrado(x, m,n,sifrado); p1.cifrar(); } else if(aea==2) { cifrado p1 = cifrado(x, m,n,sifrado); p1.decifrar(); } }
#include<iostream> #include<bits/stdc++.h> #include<algorithm> #include<cmath> #define ll long long using namespace std; vector<int> vec; int main() { long n; cin>>n; while(n) { long r=n%8; vec.push_back(r); n=n/8; } for(int i=vec.size()-1;i>=0;i--) cout<<vec[i]; return 0; }
/* * main.cpp * * Created on: 2017年6月4日 * Author: lcy */ #include "BiTree.cpp" int main() { BiTNode<char>* p; CreateBiTree(p); PreOrderTraverse(p); std::cout << std::endl; InOrderTraverse(p); std::cout << std::endl; PostOrderTraverse(p); }
// // Created on 20/01/19. // // // Code for ROSL taken directly from implementation: https://github.com/tjof2/robustpca // #include <iostream> #include <iomanip> #include "ROSL.h" #include "../Algebra/Auxiliary.h" namespace Algorithms { void ROSL::ROSL_Recovery(arma::mat &input, uint64_t rank, double reg) { uint64_t m = input.n_rows; uint64_t n = input.n_cols; std::vector<arma::uvec> indices; for (uint64_t i = 0; i < input.n_cols; ++i) { indices.emplace_back(arma::find_nonfinite(input.col(i))); } ROSL rosl = ROSL(); rosl.Parameters(rank, //initial guess reg, // tba 1E-6, // tolerance, default value 500, // iterations, default value 0, // mode (0 = full, 1 = subsampling [not needed]) (uint64_t) -1, // subsampleL [not needed] (uint64_t) -1, // subsampleH [not needed] false // verbose ); Algebra::Algorithms::interpolate(input, false, &indices); arma::mat reconstruction; double err = 99.0; uint64_t iter = 0; while (err >= 1E-7 && ++iter < 100) { rosl.runROSL(&input); rosl.D.resize(m, n); rosl.alpha.resize(m, n); reconstruction = rosl.D.submat(arma::span::all, arma::span(0, rosl.rank - 1)) * rosl.alpha.submat(arma::span(0, rosl.rank - 1), arma::span::all); rosl.D.reset(); rosl.alpha.reset(); rosl.E.reset(); err = 0.0; for (uint64_t j = 0; j < input.n_cols; ++j) { for (uint64_t i : indices[j]) { double lastVal = input.at(i, j); double newVal = reconstruction.at(i, j); err += (lastVal - newVal) * (lastVal - newVal); input.at(i, j) = newVal; } } err = std::sqrt(err); } } void ROSL::runROSL(arma::mat *X) { uint64_t m = (*X).n_rows; uint64_t n = (*X).n_cols; switch (method) { case 0: // For fully-sampled ROSL InexactALM_ROSL(X); break; case 1: // For sub-sampled ROSL+ arma::uvec rowall, colall; arma::arma_rng::set_seed(18931); rowall = (Sh == m) ? arma::linspace<arma::uvec>(0, m - 1, m) : arma::shuffle( arma::linspace<arma::uvec>(0, m - 1, m)); colall = (Sl == n) ? arma::linspace<arma::uvec>(0, n - 1, n) : arma::shuffle( arma::linspace<arma::uvec>(0, n - 1, n)); arma::uvec rowsample, colsample; rowsample = (Sh == m) ? rowall : arma::join_vert(rowall.subvec(0, Sh - 1), arma::sort(rowall.subvec(Sh, m - 1))); colsample = (Sl == n) ? colall : arma::join_vert(colall.subvec(0, Sl - 1), arma::sort(colall.subvec(Sl, n - 1))); arma::mat Xperm; Xperm = (*X).rows(rowsample); Xperm = Xperm.cols(colsample); // Take the columns and solve the small ROSL problem arma::mat XpermTmp; XpermTmp = Xperm.cols(0, Sl - 1); InexactALM_ROSL(&XpermTmp); // Free some memory XpermTmp.set_size(Sh, Sl); // Now take the rows and do robust linear regression XpermTmp = Xperm.rows(0, Sh - 1); InexactALM_RLR(&XpermTmp); // Free some memory Xperm.reset(); XpermTmp.reset(); // Calculate low-rank component A = D * alpha; // Permute back A.cols(colsample) = A; A.rows(rowsample) = A; // Calculate error E = *X - A; break; } // Free some memory Z.reset(); Etmp.reset(); error.reset(); A.reset(); } void ROSL::InexactALM_ROSL(arma::mat *X) { uint64_t m = (*X).n_rows; uint64_t n = (*X).n_cols; int precision = (int)std::abs(std::log10(tol)) + 2; // Initialize A, Z, E, Etmp and error A.set_size(m, n); Z.set_size(m, n); E.set_size(m, n); Etmp.set_size(m, n); alpha.set_size(R, n); D.set_size(m, R); error.set_size(m, n); // Initialize alpha randomly arma::arma_rng::set_seed(18931); alpha.randu(); // Set all other matrices A = *X; D.zeros(); E.zeros(); Z.zeros(); Etmp.zeros(); double infnorm, fronorm; infnorm = arma::norm(arma::vectorise(*X), "inf"); fronorm = arma::norm(*X, "fro"); // These are tunable parameters double rho, mubar; mu = 10 * lambda / infnorm; rho = 1.5; mubar = mu * 1E7; double stopcrit; for (uint64_t i = 0; i < maxIter; i++) { // Error matrix and intensity thresholding Etmp = *X + Z - A; E = arma::abs(Etmp) - lambda / mu; E.transform([](double val) { return (val > 0.) ? val : 0.; }); E = E % arma::sign(Etmp); // Perform the shrinkage LowRankDictionaryShrinkage(X); // Update Z Z = (Z + *X - A - E) / rho; mu = (mu * rho < mubar) ? mu * rho : mubar; // Calculate stop criterion stopcrit = arma::norm(*X - A - E, "fro") / fronorm; roslIters = i + 1; // Exit if stop criteria is met if (stopcrit < tol) { // Report progress if (verbose) { std::cout << "---------------------------------------------------------" << std::endl; std::cout << " ROSL iterations: " << i + 1 << std::endl; std::cout << " Estimated rank: " << D.n_cols << std::endl; std::cout << " Final error: " << std::fixed << std::setprecision(precision) << stopcrit << std::endl; std::cout << "---------------------------------------------------------" << std::endl; } return; } } // Report convergence warning std::cout << "---------------------------------------------------------" << std::endl; std::cout << " WARNING: ROSL did not converge in " << roslIters << " iterations" << std::endl; std::cout << " Estimated rank: " << D.n_cols << std::endl; std::cout << " Final error: " << std::fixed << std::setprecision(precision) << stopcrit << std::endl; std::cout << "---------------------------------------------------------" << std::endl; } void ROSL::InexactALM_RLR(arma::mat *X) { uint64_t m = (*X).n_rows; uint64_t n = (*X).n_cols; int precision = (int)std::abs(std::log10(tol)) + 2; // Initialize A, Z, E, Etmp A.set_size(m, n); Z.set_size(m, n); E.set_size(m, n); Etmp.set_size(m, n); // Set all other matrices A = *X; E.zeros(); Z.zeros(); Etmp.zeros(); double infnorm, fronorm; infnorm = arma::norm(arma::vectorise(*X), "inf"); fronorm = arma::norm(*X, "fro"); // These are tunable parameters double rho, mubar; mu = 10 * 5E-2 / infnorm; rho = 1.5; mubar = mu * 1E7; double stopcrit; for (uint64_t i = 0; i < maxIter; i++) { // Error matrix and intensity thresholding Etmp = *X + Z - A; E = arma::abs(Etmp) - 1 / mu; E.transform([](double val) { return (val > 0.) ? val : 0.; }); E = E % arma::sign(Etmp); // SVD variables arma::mat Usvd, Vsvd; arma::vec Ssvd; arma::uvec Sshort; uint64_t SV; // Given D and A... arma::svd_econ(Usvd, Ssvd, Vsvd, D.rows(0, Sh - 1)); Sshort = arma::find(Ssvd > 0.); SV = Sshort.n_elem; alpha = Vsvd.cols(0, SV - 1) * arma::diagmat(1. / Ssvd.subvec(0, SV - 1)) * arma::trans(Usvd.cols(0, SV - 1)) * (*X + Z - E); A = (D.rows(0, Sh - 1)) * alpha; // Update Z Z = (Z + *X - A - E) / rho; mu = (mu * rho < mubar) ? mu * rho : mubar; // Calculate stop criterion stopcrit = arma::norm(*X - A - E, "fro") / fronorm; rlrIters = i + 1; // Exit if stop criteria is met if (stopcrit < tol) { // Report progress if (verbose) { std::cout << "---------------------------------------------------------" << std::endl; std::cout << " RLR iterations: " << i + 1 << std::endl; std::cout << " Estimated rank: " << D.n_cols << std::endl; std::cout << " Final error: " << std::fixed << std::setprecision(precision) << stopcrit << std::endl; std::cout << "---------------------------------------------------------" << std::endl; } return; } } // Report convergence warning std::cout << "---------------------------------------------------------" << std::endl; std::cout << " WARNING: RLR did not converge in " << rlrIters << " iterations" << std::endl; std::cout << " Estimated rank: " << D.n_cols << std::endl; std::cout << " Final error: " << std::fixed << std::setprecision(precision) << stopcrit << std::endl; std::cout << "---------------------------------------------------------" << std::endl; } void ROSL::LowRankDictionaryShrinkage(arma::mat *X) { // Get current rank estimate rank = D.n_cols; // Thresholding double alphanormthresh; arma::vec alphanorm(rank); alphanorm.zeros(); arma::uvec alphaindices; // Norms double dnorm; // Loop over columns of D for (uint64_t i = 0; i < rank; i++) { // Compute error and new D(:,i) D.col(i).zeros(); error = ((*X + Z - E) - (D * alpha)); D.col(i) = error * arma::trans(alpha.row(i)); dnorm = arma::norm(D.col(i)); // Shrinkage if (dnorm > 0.) { // Gram-Schmidt on D for (uint64_t j = 0; j < i; j++) { D.col(i) = D.col(i) - D.col(j) * (arma::trans(D.col(j)) * D.col(i)); } // Normalize D.col(i) /= arma::norm(D.col(i)); // Compute alpha(i,:) alpha.row(i) = arma::trans(D.col(i)) * error; // Magnitude thresholding alphanorm(i) = arma::norm(alpha.row(i)); alphanormthresh = (alphanorm(i) - 1 / mu > 0.) ? alphanorm(i) - 1 / mu : 0.; alpha.row(i) *= alphanormthresh / alphanorm(i); alphanorm(i) = alphanormthresh; } else { alpha.row(i).zeros(); alphanorm(i) = 0.; } } // Delete the zero bases alphaindices = arma::find(alphanorm != 0.); D = D.cols(alphaindices); alpha = alpha.rows(alphaindices); // Update A A = D * alpha; } } // namespace Algorithms
#include "display.h" #include <LedControl.h> LedControl lc = LedControl(10, 12, 11, N_DISPLAYS); uint8_t displayLines[N_DISPLAYS * 8]; uint8_t updatedLines[N_DISPLAYS]; void initDisplay() { for (uint8_t i = 0; i < N_DISPLAYS; i++) { // put your setup code here, to run once: lc.shutdown(i,false);// turn off power saving, enables display lc.setIntensity(i,5);// sets brightness (0~15 possible values) lc.clearDisplay(i);// clear screen } } void updateDisplay() { for (uint8_t line = 0; line < N_DISPLAYS * 8; line++) { if (updatedLines[line / 8] & (1 << (line % 8))) { lc.setRow(line / 8, 7 - line % 8, displayLines[line]); updatedLines[line / 8] &= ~(1 << (line % 8)); } } } void setPixel(uint8_t x, uint8_t y, bool on) { if (x < N_DISPLAYS * 8 && y < 8) { if (on) { displayLines[y + (x / 8) * 8] |= 1 << (x % 8); } else { displayLines[y + (x / 8) * 8] &= ~(1 << (x % 8)); } updatedLines[x / 8] |= 1 << y; } }
#include "Deck54.hpp" Deck54::Deck54() :Deck52(){ //{ As 14 3 4 5 6 7 8 9 10 Valet Dame Roi JokerNoir JokerRouge } * { Coeur Carreaux Trèfle Pique } const Card JokerNoir = Card (); const Card JokerRouge = Card (); (*this)+=JokerNoir+JokerRouge; }
#include <iberbar/RHI/OpenGL/ShaderProgram.h> #include <iberbar/Utility/String.h> #include <iberbar/Utility/FileHelper.h> iberbar::CResult iberbar::RHI::OpenGL::LoadShaderFromSource( GLenum shaderType, const char* pSource, GLuint* pShader ) { assert( pSource ); assert( pShader ); GLuint shader = glCreateShader( shaderType ); if (shader <= 0) return MakeResult( ResultCode::Bad, u8"创建shader失败" ); glShaderSource( shader, 1, &pSource, NULL ); glCompileShader( shader ); GLint compiled = 0; glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled ); if (!compiled) { CResult retCompile( ResultCode::Bad, "" ); GLint infoLen = 0; glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &infoLen ); if (infoLen) { retCompile.data.resize( infoLen + 1 ); glGetShaderInfoLog( shader, infoLen, NULL, &retCompile.data.front() ); retCompile.data[infoLen] = 0; } const char* ptr = retCompile.data.c_str(); glDeleteShader( shader ); shader = 0; return retCompile; } *pShader = shader; return CResult(); } iberbar::RHI::OpenGL::CShaderProgram::CShaderProgram( void ) : m_VertexShader( 0 ) , m_FragmentShader( 0 ) , m_Program( 0 ) { } iberbar::RHI::OpenGL::CShaderProgram::~CShaderProgram() { if ( m_Program > 0 ) glDeleteProgram( m_Program ); if ( m_VertexShader > 0 ) glDeleteShader( m_VertexShader ); if ( m_FragmentShader > 0 ) glDeleteShader( m_FragmentShader ); } iberbar::CResult iberbar::RHI::OpenGL::CShaderProgram::LoadFromSource( const char* pVertexSource, const char* pFragmentSource ) { if (StringIsNullOrEmpty( pVertexSource )) return MakeResult( ResultCode::Bad, u8"空白的顶点着色器代码" ); if (StringIsNullOrEmpty( pFragmentSource )) return MakeResult( ResultCode::Bad, u8"空白的片元着色器代码" ); CResult ret; ret = LoadShaderFromSource( GL_VERTEX_SHADER, pVertexSource, &m_VertexShader ); if (ret.IsOK() == false ) return ret; ret = LoadShaderFromSource( GL_FRAGMENT_SHADER, pFragmentSource, &m_FragmentShader ); if ( ret.IsOK() == false ) return ret; m_Program = glCreateProgram(); if (m_Program <= 0) return MakeResult( ResultCode::Bad, "" ); glAttachShader( m_Program, m_VertexShader ); glAttachShader( m_Program, m_FragmentShader ); glLinkProgram( m_Program ); GLint linkStatus = GL_FALSE; glGetProgramiv( m_Program, GL_LINK_STATUS, &linkStatus ); if (linkStatus != GL_TRUE) { ret.code = ResultCode::Bad; // 获取错误信息 GLint bufLength = 0; glGetProgramiv( m_Program, GL_INFO_LOG_LENGTH, &bufLength ); if (bufLength) { ret.data.resize( bufLength + 1 ); char* buf = (char*)malloc( bufLength + 1 ); glGetProgramInfoLog( m_Program, bufLength, NULL, ret.data.data() ); buf[bufLength] = 0; } glDeleteProgram( m_Program ); m_Program = 0; return ret; } return ret; } iberbar::CResult iberbar::RHI::OpenGL::CShaderProgram::LoadFromFile( const char* pVertexFile, const char* pFragmentFile ) { if ( StringIsNullOrEmpty( pVertexFile ) == true ) return MakeResult( ResultCode::Bad, u8"无效的顶点着色器文件" ); if ( StringIsNullOrEmpty( pFragmentFile ) == true ) return MakeResult( ResultCode::Bad, u8"无效的片元着色器文件" ); std::string strVertexSource; std::string strFragmentSource; CFileHelper fileHelper; if (fileHelper.OpenFileA( pVertexFile, "r" ) == false) return MakeResult( ResultCode::Bad, u8"打开顶点着色器文件失败" ); strVertexSource = fileHelper.ReadAsText(); fileHelper.CloseFile(); if (fileHelper.OpenFileA( pFragmentFile, "r" ) == false) return MakeResult( ResultCode::Bad, u8"打开片元着色器文件失败" ); strFragmentSource = fileHelper.ReadAsText(); fileHelper.CloseFile(); return LoadFromSource( strVertexSource.c_str(), strFragmentSource.c_str() ); } iberbar::RHI::OpenGL::CShaderProgramManager::CShaderProgramManager( void ) : m_pUsingShaderProgram( NULL ) { } iberbar::RHI::OpenGL::CShaderProgramManager::~CShaderProgramManager() { UNKNOWN_SAFE_RELEASE_NULL( m_pUsingShaderProgram ); auto iter = m_vShaderPrograms.begin(); auto end = m_vShaderPrograms.end(); for ( ; iter != end; iter++ ) { UNKNOWN_SAFE_RELEASE_NULL( iter->second ); } m_vShaderPrograms.clear(); } bool iberbar::RHI::OpenGL::CShaderProgramManager::AddShaderProgram( const TCHAR* strKey, CShaderProgram* pShaderProgram ) { if ( strKey == NULL || strKey[ 0 ] == 0 ) return false; if ( pShaderProgram == NULL ) return false; if ( FindShaderProgram( strKey ) == true ) return false; m_vShaderPrograms.insert( std::make_pair( strKey, pShaderProgram ) ); pShaderProgram->AddRef(); return true; } bool iberbar::RHI::OpenGL::CShaderProgramManager::FindShaderProgram( const TCHAR* strKey, CShaderProgram** ppOutShaderProgram ) { if ( StringIsNullOrEmpty( strKey ) == true ) return false; auto iter = m_vShaderPrograms.find( strKey ); if (iter == m_vShaderPrograms.end()) return false; CShaderProgram* pShader = iter->second; if ( pShader == nullptr ) return false; if ( ppOutShaderProgram ) { if ( *ppOutShaderProgram ) ( *ppOutShaderProgram )->Release(); ( *ppOutShaderProgram ) = pShader; ( *ppOutShaderProgram )->AddRef(); } return true; } void iberbar::RHI::OpenGL::CShaderProgramManager::UseShaderProgram( CShaderProgram* pUseShaderProgram ) { if ( pUseShaderProgram == m_pUsingShaderProgram ) return ; if ( m_pUsingShaderProgram ) m_pUsingShaderProgram->Release(); m_pUsingShaderProgram = pUseShaderProgram; if ( m_pUsingShaderProgram ) { m_pUsingShaderProgram->AddRef(); glUseProgram( m_pUsingShaderProgram->GetProgramUint() ); } else { glUseProgram( 0 ); } }