text
stringlengths
8
6.88M
// http://www.esp8266learning.com/esp8266-lm75-temperature-sensor-example.php // https://github.com/jlz3008/lm75 // I set device address to 0 soldering these pins (see above picture): // 1. A0 and GND together. // 2. A1 and GND together. // 3. A2 and GND together. // After soldering all three pins - A0 , A1 and A2 to one of GND or VCC the board is ready for use. // 1 0 0 1 A2 A1 A0 #include <lm75.h> #include <inttypes.h> #include <Wire.h> // address LM75 1001000 // address BMP280 1110111 TempI2C_LM75 termo = TempI2C_LM75(0x48, TempI2C_LM75::nine_bits); void setup() { Serial.begin(115200); Serial.println("Start"); Serial.print("Actual temp "); Serial.print(termo.getTemp()); Serial.println(" oC"); delay(2000); } void loop() { Serial.print(termo.getTemp()); Serial.println(" oC"); delay(5000); }
# include<iostream> using namespace std; float taghsim(float,float[],float[],int,int,float); void sort(float[],float[],float[],int); int main(){ int n; float W; cout<<"please enter total weight "<<"\n"; cin>>W; cout<<"please enter number of items "<<"\n"; cin>>n; float w[n]; float p[n]; int i; for(i=0;i<n;i++){ cout<<"please enter weight of item "<<i+1<<"\n"; cin>>w[i]; cout<<"please enter profit of item " <<i+1<<"\n"; cin>>p[i]; } float min=w[0]; for(i=1;i<n;i++){ if(w[i]<min){ min=w[i]; } } float pw[n]; for(i=0;i<n;i++){ pw[i]=p[i]/w[i]; } sort(pw,p,w,n); float j; j=taghsim(W,w,p,0,n,min); cout<<"profit ="<<j<<"\n"; return 0; } void sort(float pw[],float p[],float w[],int n){ int i,j; for(i=0;i<n-1;i++){ for(j=i+1;j<n;j++){ if(pw[j]>pw[i]){ pw[i]=pw[i]+pw[j]; pw[j]=pw[i]-pw[j]; pw[i]=pw[i]-pw[j]; w[i]=w[i]+w[j]; w[j]=w[i]-w[j]; w[i]=w[i]-w[j]; p[i]=p[i]+p[j]; p[j]=p[i]-p[j]; p[i]=p[i]-p[j]; } } } } float taghsim(float W,float w[],float p[],int i,int n,float min){ if(W>=min && i<n){ if(w[i]<=W){ return p[i]+taghsim(W-w[i],w,p,i+1,n,min); } else{ return taghsim(W,w,p,i+1,n,min); } } else{ return 0; } }
/* * UDPTransportStreamer.cpp * * Created on: 5 Apr 2011 * Author: two */ #include "UDPTransportStreamer.h" UDPTransportStreamer::UDPTransportStreamer() { // TODO Auto-generated constructor stub } UDPTransportStreamer::UDPTransportStreamer(struct sockaddr_in addr, int fdSocket, socklen_t fromLen) { m_CliAddr = addr; m_fdSocket = fdSocket; m_slFromLen = fromLen; m_nTimeOut = 0; // 0 = none m_bClientDead = false; } void UDPTransportStreamer::setTimeOut(int sec) { /* * Set the time out in seconds. 0 = none. * timeout for last STRT command. Will destroy self after that. */ m_nTimeOut = sec; } void UDPTransportStreamer::Setup() { return; } void UDPTransportStreamer::Execute() { return; } void UDPTransportStreamer::gotSTRTat(struct timeval* time) { /* * Marks this as the last time it got a STRT. */ m_tvLastSTRT.tv_sec = time->tv_sec; m_tvLastSTRT.tv_usec = time->tv_usec; } bool UDPTransportStreamer::isAddr(struct sockaddr_in *addr) { /* * Returns true if the port and addr is matched to that given in :) */ if(addr->sin_port == m_CliAddr.sin_port) { if(addr->sin_addr.s_addr == m_CliAddr.sin_addr.s_addr) return true; } return false; } bool UDPTransportStreamer::isClientDead() { return m_bClientDead; } void UDPTransportStreamer::sendPacket(char* buffer, int size) { if(m_bClientDead) return; //Don't send to dead clients... // Check last STRT? if(m_nTimeOut) { struct timedif td; struct timeval now; gettimeofday(&now, NULL); timeDifCalc(&m_tvLastSTRT, &now ,&td); if(td.dsec > m_nTimeOut) { //timed OUT! //m_bClientDead = true; return; } return; //Debug mode, code below is redundant... } int sendresult = sendto(m_slFromLen, buffer, size, 0, (struct sockaddr *)&m_CliAddr, m_slFromLen); cout << "Sending UDP data " << sendresult << endl; return; } UDPTransportStreamer::~UDPTransportStreamer() { // TODO Auto-generated destructor stub }
#include <iostream> #include <math.h> #include "TerrainRenderer.h" #include "Keyboard.h" #include "GL.h" TerrainRenderer::TerrainRenderer() { terrainShader.addShader("shaders/terrain.vert", GL_VERTEX_SHADER); terrainShader.addShader("shaders/terrain.tcs", GL_TESS_CONTROL_SHADER); terrainShader.addShader("shaders/terrain.tes", GL_TESS_EVALUATION_SHADER); terrainShader.addShader("shaders/terrain.geo", GL_GEOMETRY_SHADER); terrainShader.addShader("shaders/terrain.frag", GL_FRAGMENT_SHADER); //Load Uniform Locations and set Texture Channels terrainShader.start(); terrainShader.activateUniform("pvMat"); terrainShader.activateUniform("camPos"); terrainShader.activateUniform("amplitude"); terrainShader.activateUniform("size"); terrainShader.activateUniform("chunkId"); terrainShader.activateUniform("chunkSize"); terrainShader.activateUniform("chunkPos"); terrainShader.activateUniform("index"); terrainShader.activateUniform("lod"); terrainShader.activateUniform("morph0"); terrainShader.activateUniform("morph1"); terrainShader.activateUniform("morph2"); terrainShader.activateUniform("morph3"); terrainShader.activateUniform("diffuse_color"); terrainShader.activateUniform("tiling0"); terrainShader.activateUniform("tiling1"); terrainShader.activateUniform("tiling2"); terrainShader.activateUniform("tiling3"); terrainShader.activateUniform("displacement_factor_0"); terrainShader.activateUniform("displacement_factor_1"); terrainShader.activateUniform("displacement_factor_2"); terrainShader.activateUniform("displacement_factor_3"); terrainShader.bindTextureUnit("diffuse_map_0", 0); terrainShader.bindTextureUnit("diffuse_map_1", 1); terrainShader.bindTextureUnit("diffuse_map_2", 2); terrainShader.bindTextureUnit("diffuse_map_3", 3); terrainShader.bindTextureUnit("normal_map_0", 4); terrainShader.bindTextureUnit("normal_map_1", 5); terrainShader.bindTextureUnit("normal_map_2", 6); terrainShader.bindTextureUnit("normal_map_3", 7); terrainShader.bindTextureUnit("displacement_map_0", 8); terrainShader.bindTextureUnit("displacement_map_1", 9); terrainShader.bindTextureUnit("displacement_map_2", 10); terrainShader.bindTextureUnit("displacement_map_3", 11); terrainShader.bindTextureUnit("specular_map_0", 12); terrainShader.bindTextureUnit("specular_map_1", 13); terrainShader.bindTextureUnit("specular_map_2", 14); terrainShader.bindTextureUnit("specular_map_3", 15); terrainShader.bindTextureUnit("ambient_map_0", 16); terrainShader.bindTextureUnit("ambient_map_1", 17); terrainShader.bindTextureUnit("ambient_map_2", 18); terrainShader.bindTextureUnit("ambient_map_3", 19); terrainShader.bindTextureUnit("height_map", 20); terrainShader.bindTextureUnit("light_map", 21); terrainShader.bindTextureUnit("blend_map", 22); terrainShader.stop(); //Load Terrain Mesh terrainMesh.addVertexBuffer(std::vector<float>{ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0 }, 3, 0); //Positions terrainMesh.addVertexBuffer(std::vector<float>{ 0, 0, 0, 1, 1, 1, 1, 0 }, 2, 1); //TexCoords terrainMesh.addIndexBuffer(std::vector<unsigned int>{ 0, 3, 1, 1, 3, 2 }, terrainMeshIndexBuffer); //Indices } void TerrainRenderer::render(Scene& scene, glm::mat4& pMatrix, glm::vec4 clipPlane) { if(scene.terrain->renderMe){ //Calculate Matrices glm::mat4 vMatrix = scene.camera->getViewMatrix(); glm::mat4 pvMatrix = pMatrix * vMatrix; //Start Shader terrainShader.start(); //Bind Terrain Mesh terrainMesh.bind(); terrainMeshIndexBuffer.bind(); //Set Matrices terrainShader.setUniformVariable("pvMat", pvMatrix); //Set Camera Position terrainShader.setUniformVariable("camPos", scene.camera->posx, scene.camera->posy, scene.camera->posz); //Set Size terrainShader.setUniformVariable("size", scene.terrain->getConfig().size); //Set Amplitude terrainShader.setUniformVariable("amplitude", scene.terrain->getConfig().amplitude); //Set Morph Areas terrainShader.setUniformVariable("morph0", scene.terrain->getConfig().morphAreas[0]); terrainShader.setUniformVariable("morph1", scene.terrain->getConfig().morphAreas[1]); terrainShader.setUniformVariable("morph2", scene.terrain->getConfig().morphAreas[2]); terrainShader.setUniformVariable("morph3", scene.terrain->getConfig().morphAreas[3]); //Load Terrain Textures loadTexturePack(scene.terrain->getConfig().textures); //Enable backface Culling glCullFace(GL_BACK); glEnable(GL_CULL_FACE); //DEBUG - ENABLE LINE RENDER MODE if(!keyboard::isKeyPressed(GLFW_KEY_P)) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //Iterate Terrain Tree for(int i = 0; i < TERRAIN_DEFAULT_ROOT_NODES; i++){ for(int j = 0; j < TERRAIN_DEFAULT_ROOT_NODES; j++){ TerrainNode* rootNode = scene.terrain->getRootNodes()[i * TERRAIN_DEFAULT_ROOT_NODES +j]; renderNode(rootNode, 0); } } //Unbind Terrain Mesh terrainMeshIndexBuffer.unbind(); terrainMesh.unbind(); //Stop Shader terrainShader.stop(); //Reset Polygon Mode glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } void TerrainRenderer::renderNode(TerrainNode* node, int index){ if(node->isLeaf()){ terrainShader.setUniformVariable("chunkPos", node->position); terrainShader.setUniformVariable("chunkSize", node->size); terrainShader.setUniformVariable("lod", node->lod); terrainShader.setUniformVariable("index", glm::vec2(index -(index%2), index%2)); //Render glDrawElements(GL_PATCHES, terrainMeshIndexBuffer.size, GL_UNSIGNED_INT, 0); return; } //Go Throug Nodes Children for(int i = 0; i < 4; i++){ renderNode(node->children[i], i); } } void TerrainRenderer::loadTexturePack(TerrainTexturePack pack) { core::bindTexture(pack.diffuse_map_0, 0, GL_TEXTURE_2D); core::bindTexture(pack.diffuse_map_1, 1, GL_TEXTURE_2D); core::bindTexture(pack.diffuse_map_2, 2, GL_TEXTURE_2D); core::bindTexture(pack.diffuse_map_3, 3, GL_TEXTURE_2D); core::bindTexture(pack.normal_map_0, 4, GL_TEXTURE_2D); core::bindTexture(pack.normal_map_1, 5, GL_TEXTURE_2D); core::bindTexture(pack.normal_map_2, 6, GL_TEXTURE_2D); core::bindTexture(pack.normal_map_3, 7, GL_TEXTURE_2D); core::bindTexture(pack.displacement_map_0, 8, GL_TEXTURE_2D); core::bindTexture(pack.displacement_map_1, 9, GL_TEXTURE_2D); core::bindTexture(pack.displacement_map_2, 10, GL_TEXTURE_2D); core::bindTexture(pack.displacement_map_3, 11, GL_TEXTURE_2D); core::bindTexture(pack.specular_map_0, 12, GL_TEXTURE_2D); core::bindTexture(pack.specular_map_1, 13, GL_TEXTURE_2D); core::bindTexture(pack.specular_map_2, 14, GL_TEXTURE_2D); core::bindTexture(pack.specular_map_3, 15, GL_TEXTURE_2D); core::bindTexture(pack.ambient_map_0, 16, GL_TEXTURE_2D); core::bindTexture(pack.ambient_map_1, 17, GL_TEXTURE_2D); core::bindTexture(pack.ambient_map_2, 18, GL_TEXTURE_2D); core::bindTexture(pack.ambient_map_3, 19, GL_TEXTURE_2D); core::bindTexture(pack.height_map, 20, GL_TEXTURE_2D); core::bindTexture(pack.light_map, 21, GL_TEXTURE_2D); core::bindTexture(pack.blend_map, 22, GL_TEXTURE_2D); terrainShader.setUniformVariable("tiling0", pack.tiling_0); terrainShader.setUniformVariable("tiling1", pack.tiling_0); terrainShader.setUniformVariable("tiling2", pack.tiling_0); terrainShader.setUniformVariable("tiling3", pack.tiling_0); terrainShader.setUniformVariable("displacement_factor_0", pack.displacement_factor_0); terrainShader.setUniformVariable("displacement_factor_1", pack.displacement_factor_1); terrainShader.setUniformVariable("displacement_factor_2", pack.displacement_factor_2); terrainShader.setUniformVariable("displacement_factor_3", pack.displacement_factor_3); terrainShader.setUniformVariable("diffuse_color", pack.diffuse_color); }
 /* 题目描述 请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配 */ #include<iostream> using namespace std; #include<vector> #include<string> /* 请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配 1、考虑到“*”出现与否两种情况。 (1)第一个字母出现*直接报错的 (2)第二个字母为*时,有三种情况,字符串与*前面的字母匹配时,一是用*的无限匹配前面的字母功能,二是不适用他的这个功能,第三种情况是不匹配,那就直接跳过* (递归实现) 2、不出现“*”的情况 两个字符一样或者模式串是“.”都直接匹配。 3、递归结束情况 (1)两个字符串都为空,就是匹配成功 (2)第一个字符串没空,第二个空了,那就匹配失败 (3)匹配过程中不匹配,匹配失败 */ class Solution { public: bool match(char* str, char* pattern) { if (*str == '\0' && *pattern == '\0') return true; if (*str != '\0' && *pattern == '\0') return false; //if the next character in pattern is not '*' if (*(pattern + 1) != '*') { if (*str == *pattern || (*str != '\0' && *pattern == '.')) return match(str + 1, pattern + 1); else return false; } //if the next character is '*' else { if (*str == *pattern || (*str != '\0' && *pattern == '.')) return match(str, pattern + 2) || match(str + 1, pattern); else return match(str, pattern + 2); } } }; int main() { Solution a; char str[] = "a"; char pattern[] = ".*"; cout<<a.match(str, pattern)<<endl; return 0; }
#include <algorithm> #include <fstream> #include <set> #include <vector> extern "C" { #include "nebstructs.h" #include "nebcallbacks.h" #include "nebmodules.h" #include "nebmods.h" #include "broker.h" #ifdef HAVE_ICINGA #include "icinga.h" #else #include "nagios.h" #endif } #include "cereal/cereal.hpp" #include "cereal/types/string.hpp" #include "cereal/types/memory.hpp" #include "cereal/types/chrono.hpp" #include "cereal/archives/portable_binary.hpp" #include "zmqpp/zmqpp.hpp" #include "zmqpp/curve.hpp" #include "json.hpp" // for convenience using json = nlohmann::json; #include "module.h" namespace { std::unique_ptr<zmqpp::context> zmq_ctx = nullptr; std::unique_ptr<zmqpp::socket> server_socket = nullptr; std::unique_ptr<zmqpp::auth> zmq_authenticator = nullptr; json config_file_obj; } void dispatchJob(JobPtr job, std::string executor) { if (executor.empty()) executor = job->host_name; const auto job_id = getJobQueue()->addCheck(job); try { scheduleTimeout(job); zmqpp::message req_msg; log_debug_info(DEBUGL_CHECKS, DEBUGV_BASIC, "Dispatching check to %s (id: %lu hostname: %s service: %s)\n", executor.c_str(), job_id, job->host_name.c_str(), job->service_description.c_str()); req_msg.add(executor); std::ostringstream req_buffer; cereal::PortableBinaryOutputArchive archive(req_buffer); archive(*job); req_msg.add(req_buffer.str()); server_socket->send(req_msg); log_debug_info(DEBUGL_CHECKS, DEBUGV_MORE, "MQexec sent check successfully\n"); } catch (zmqpp::zmq_internal_exception& e) { std::stringstream ss; if (e.zmq_error() == EHOSTUNREACH) { ss << "Executor " << executor << " is not connected"; } else { ss << "ZeroMQ error while dispatching job to " << executor << ": " << e.what(); } auto error_msg = ss.str(); processJobError(job, error_msg); logit(NSLOG_RUNTIME_WARNING, TRUE, error_msg.c_str()); getJobQueue()->getCheck(job_id); } catch (std::exception& e) { std::stringstream ss; ss << "Error sending job to executor: " << e.what(); auto error_message = ss.str(); processJobError(job, error_message); logit(NSLOG_RUNTIME_WARNING, TRUE, error_message.c_str()); getJobQueue()->getCheck(job_id); } } int processIOEvent(int sd, int events, void* arg) { log_debug_info(DEBUGL_CHECKS, DEBUGV_MORE, "Entering mqexec I/O callback\n"); for (;;) { try { log_debug_info(DEBUGL_CHECKS, DEBUGV_MORE, "Entering mqexec receive loop\n"); zmqpp::message raw_msg; if (!server_socket->receive(raw_msg, true)) break; const auto last_part = raw_msg.parts() - 1; if (raw_msg.parts() == 0 || raw_msg.get(last_part).size() == 0) { log_debug_info(DEBUGL_CHECKS, DEBUGV_MORE, "Skipping mqexec message with empty payload\n"); continue; } log_debug_info(DEBUGL_CHECKS, DEBUGV_BASIC, "Received mqexec message\n"); std::istringstream response_buf(raw_msg.get(last_part)); cereal::PortableBinaryInputArchive archive(response_buf); Result res; archive(res); const auto job = getJobQueue()->getCheck(res.id); processResult(job, res); } catch (std::exception& e) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error receiving result from executor: %s", e.what()); } } log_debug_info(DEBUGL_CHECKS, DEBUGV_MORE, "Leaving mqexec I/O callback\n"); return 0; } int shutdownServer() { try { int fd; server_socket->get(zmqpp::socket_option::file_descriptor, fd); iobroker_unregister(nagios_iobs, fd); server_socket->close(); server_socket = nullptr; zmq_ctx->terminate(); zmq_ctx = nullptr; zmq_authenticator = nullptr; } catch (std::exception& e) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error shutting down MQexec! %s", e.what()); return 1; } return 0; } int initServer(std::string bind_point, std::string key_file_path, zmqpp::curve::keypair keys) { if (zmq_ctx || server_socket || zmq_authenticator) { logit(NSLOG_RUNTIME_ERROR, TRUE, "ZeroMQ shouldn't be inititalized yet!"); return 1; } logit(NSLOG_INFO_MESSAGE, TRUE, "Setting up MQexec"); zmq_ctx = std::unique_ptr<zmqpp::context>(new zmqpp::context{}); server_socket = std::unique_ptr<zmqpp::socket>(new zmqpp::socket(*zmq_ctx, zmqpp::socket_type::router)); if (!keys.secret_key.empty()) { logit(DEBUGL_PROCESS, DEBUGV_BASIC, "Configuring curve security for mqexec"); server_socket->set(zmqpp::socket_option::curve_secret_key, keys.secret_key); server_socket->set(zmqpp::socket_option::curve_public_key, keys.public_key); server_socket->set(zmqpp::socket_option::curve_server, true); } if (!key_file_path.empty()) { logit(DEBUGL_PROCESS, DEBUGV_BASIC, "Configuring curve authorization file for mqexec"); zmq_authenticator = std::unique_ptr<zmqpp::auth>(new zmqpp::auth(*zmq_ctx)); std::ifstream key_file_fp; key_file_fp.exceptions(std::ifstream::failbit | std::ifstream::badbit); key_file_fp.open(key_file_path); for (std::string line; std::getline(key_file_fp, line);) { std::string line_trimmed; // Trim out all whitespace characters into a "trimmed" copy of the line std::remove_copy_if(line.begin(), line.end(), std::back_inserter(line_trimmed), [](char c) -> bool { return std::isspace(c); }); // Skip lines that are less than 40 characters or that start with '#', which indicates // a comment. if (line_trimmed.size() < 40 || line_trimmed[0] == '#') continue; auto key = line_trimmed.substr(0, 40); logit(DEBUGL_CONFIG, DEBUGV_MOST, "Adding trusted key %s", key.c_str()); // We take the first 40 characters as z85 encoded keys. zmq_authenticator->configure_curve(key); } } server_socket->set(zmqpp::socket_option::router_mandatory, 1); try { logit(NSLOG_INFO_MESSAGE, TRUE, "Binding mqexec to %s", bind_point.c_str()); server_socket->bind(bind_point); } catch (zmqpp::zmq_internal_exception& e) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error binding mqexec to %s: %s", bind_point.c_str(), e.what()); shutdownServer(); return 1; } int fd; server_socket->get(zmqpp::socket_option::file_descriptor, fd); iobroker_register(nagios_iobs, fd, nullptr, processIOEvent); } NEB_API_VERSION(CURRENT_NEB_API_VERSION) nebmodule* handle; int handleStartup(int which, void* obj) { struct nebstruct_process_struct* ps = static_cast<struct nebstruct_process_struct*>(obj); try { switch (ps->type) { case NEBTYPE_PROCESS_EVENTLOOPSTART: { std::string allowed_key_file; if (config_file_obj.find("allowed_keys_file") != config_file_obj.end()) { allowed_key_file = config_file_obj.at("allowed_keys_file").get<std::string>(); } zmqpp::curve::keypair keys; if (config_file_obj.find("curve_keys") != config_file_obj.end()) { auto curve_keys = config_file_obj["curve_keys"]; keys.public_key = curve_keys.at("public").get<std::string>(); keys.secret_key = curve_keys.at("secret").get<std::string>(); } if (config_file_obj.find("bind_address") == config_file_obj.end()) { logit(NSLOG_RUNTIME_ERROR, TRUE, "MQexec config file is missing a bind address!"); return 1; } return initServer( config_file_obj.at("bind_address").get<std::string>(), allowed_key_file, keys); } break; case NEBTYPE_PROCESS_EVENTLOOPEND: { return shutdownServer(); } break; } } catch (std::exception& e) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Uncaught exception while starting mqexec!: %s", e.what()); return 1; } return 0; } int loadConfigFile(char* localargs) { try { std::ifstream config_file_obj_fp(localargs); if (!config_file_obj_fp) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error opening config file"); return 1; } config_file_obj = json::parse(config_file_obj_fp); } catch (std::exception& e) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error loading config file: %s", e.what()); return 1; } return 0; } extern "C" { // This is defined in nagios's objects.c, it should match the current // ABI version of the nagios nagmq is loaded into. extern int __nagios_object_structure_version; int nebmodule_deinit(int flags, int reason) { neb_deregister_module_callbacks(handle); shutdown_command_file_worker(); return 0; } int nebmodule_init(int flags, char* localargs, nebmodule* lhandle) { handle = lhandle; if (__nagios_object_structure_version != CURRENT_OBJECT_STRUCTURE_VERSION) { logit(NSLOG_RUNTIME_ERROR, TRUE, "NagMQ is loaded into a version of nagios with a different ABI " "than it was compiled for! You need to recompile NagMQ against the current " "nagios headers!"); return -1; } neb_set_module_info(handle, NEBMODULE_MODINFO_TITLE, const_cast<char*>("MQexec TNG")); neb_set_module_info(handle, NEBMODULE_MODINFO_AUTHOR, const_cast<char*>("Jonathan Reams")); neb_set_module_info(handle, NEBMODULE_MODINFO_VERSION, const_cast<char*>("v1")); neb_set_module_info(handle, NEBMODULE_MODINFO_LICENSE, const_cast<char*>("Apache v2")); neb_set_module_info(handle, NEBMODULE_MODINFO_DESC, const_cast<char*>("Distributed check execution with ZeroMQ")); neb_register_callback(NEBCALLBACK_PROCESS_DATA, lhandle, 0, handleStartup); neb_register_callback(NEBCALLBACK_HOST_CHECK_DATA, lhandle, 0, handleNebNagiosCheckInitiate); neb_register_callback(NEBCALLBACK_SERVICE_CHECK_DATA, lhandle, 0, handleNebNagiosCheckInitiate); return loadConfigFile(localargs); } }
#include "Event.h" #include <string> #include <iostream> using namespace std; Event::Event(int _time, int _place, Passenger* _passenger){ this->time = _time; this->place = _place; this->passenger = _passenger; }
#ifndef DISPLAY_DEVICE_MANAGER_H #define DISPLAY_DEVICE_MANAGER_H #include <string> class DisplayDeviceManager { static DisplayDeviceManager displayManager; public: DisplayDeviceManager() {} static DisplayDeviceManager* getDisplayManager() { return &displayManager; } int SetDisplayState(bool turnON = true); int EnumerateDisplay(); unsigned long long LastInputTime(); }; std::string MillisecondToTime(unsigned long long totalMillisecond); #endif // DISPLAY_DEVICE_MANAGER_H
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main(){ int n, m; cin >> n >> m; vector<int> x(m), y(m-1); for(int i=0; i<m; i++) cin >> x[i]; sort(x.begin(), x.end()); for(int i=1; i<m; i++) y[i-1] = x[i] - x[i-1]; sort(y.begin(), y.end()); int last = (m-1) - (n-1); int ans = 0; if(last > 0) for(int i=0; i<last; i++) ans += y[i]; cout << ans << endl; return 0; }
#pragma once #include <ionir/passes/pass.h> namespace ionir { struct DeadCodeEliminationPass : public Pass { IONSHARED_PASS_ID; explicit DeadCodeEliminationPass( ionshared::Ptr<ionshared::PassContext> context ); void visitBasicBlock(ionshared::Ptr<BasicBlock> node) override; // TODO: Optimize assignment to a dead variable (alloca but never used). }; }
// Copyright (c) 2014-2015 Dropbox, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cmath> #include <cstring> #include "core/types.h" #include "runtime/inline/boxing.h" #include "runtime/objmodel.h" #include "runtime/types.h" #include "runtime/util.h" namespace pyston { extern "C" PyObject* PyFloat_FromDouble(double d) noexcept { return boxFloat(d); } extern "C" PyObject* PyFloat_FromString(PyObject* v, char** pend) noexcept { Py_FatalError("unimplemented"); } extern "C" double PyFloat_AsDouble(PyObject* o) noexcept { if (o->cls == float_cls) return static_cast<BoxedFloat*>(o)->d; else if (isSubclass(o->cls, int_cls)) return static_cast<BoxedInt*>(o)->n; Py_FatalError("unimplemented"); return 0.0; } template <typename T> static inline void raiseDivZeroExcIfZero(T var) { if (var == 0) { raiseExcHelper(ZeroDivisionError, "float division by zero"); } } extern "C" double mod_float_float(double lhs, double rhs) { raiseDivZeroExcIfZero(rhs); double r = fmod(lhs, rhs); // Have to be careful here with signed zeroes: if (std::signbit(r) != std::signbit(rhs)) { if (r == 0) r *= -1; else r += rhs; } return r; } extern "C" double pow_float_float(double lhs, double rhs) { return pow(lhs, rhs); } extern "C" double div_float_float(double lhs, double rhs) { raiseDivZeroExcIfZero(rhs); return lhs / rhs; } extern "C" double floordiv_float_float(double lhs, double rhs) { raiseDivZeroExcIfZero(rhs); return floor(lhs / rhs); } extern "C" Box* floatAddFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxFloat(lhs->d + rhs->d); } extern "C" Box* floatAddInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxFloat(lhs->d + rhs->n); } extern "C" Box* floatAdd(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatAddInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatAddFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxFloat(lhs->d + PyLong_AsDouble(rhs)); } else { return NotImplemented; } } extern "C" Box* floatDivFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); raiseDivZeroExcIfZero(rhs->d); return boxFloat(lhs->d / rhs->d); } extern "C" Box* floatDivInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); raiseDivZeroExcIfZero(rhs->n); return boxFloat(lhs->d / rhs->n); } extern "C" Box* floatDiv(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatDivInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatDivFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxFloat(lhs->d / PyLong_AsDouble(rhs)); } else { return NotImplemented; } } extern "C" Box* floatTruediv(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatDivInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatDivFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxFloat(lhs->d / PyLong_AsDouble(rhs)); } else { return NotImplemented; } } extern "C" Box* floatRDivFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); raiseDivZeroExcIfZero(lhs->d); return boxFloat(rhs->d / lhs->d); } extern "C" Box* floatRDivInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); raiseDivZeroExcIfZero(lhs->d); return boxFloat(rhs->n / lhs->d); } extern "C" Box* floatRDiv(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatRDivInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatRDivFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxFloat(PyLong_AsDouble(rhs) / lhs->d); } else { return NotImplemented; } } extern "C" Box* floatFloorDivFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); raiseDivZeroExcIfZero(rhs->d); return boxFloat(floor(lhs->d / rhs->d)); } extern "C" Box* floatFloorDivInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); raiseDivZeroExcIfZero(rhs->n); return boxFloat(floor(lhs->d / rhs->n)); } extern "C" Box* floatFloorDiv(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatFloorDivInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatFloorDivFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else { return NotImplemented; } } extern "C" Box* floatEqFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxBool(lhs->d == rhs->d); } extern "C" Box* floatEqInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxBool(lhs->d == rhs->n); } extern "C" Box* floatEq(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatEqInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatEqFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxBool(lhs->d == PyLong_AsDouble(rhs)); } else { return NotImplemented; } } extern "C" Box* floatNeFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxBool(lhs->d != rhs->d); } extern "C" Box* floatNeInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxBool(lhs->d != rhs->n); } extern "C" Box* floatNe(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatNeInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatNeFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxBool(lhs->d != PyLong_AsDouble(rhs)); } else { return NotImplemented; } } extern "C" Box* floatLtFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxBool(lhs->d < rhs->d); } extern "C" Box* floatLtInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxBool(lhs->d < rhs->n); } extern "C" Box* floatLt(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatLtInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatLtFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxBool(lhs->d < PyLong_AsDouble(rhs)); } else { return NotImplemented; } } extern "C" Box* floatLeFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxBool(lhs->d <= rhs->d); } extern "C" Box* floatLeInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxBool(lhs->d <= rhs->n); } extern "C" Box* floatLe(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatLeInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatLeFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxBool(lhs->d <= PyLong_AsDouble(rhs)); } else { return NotImplemented; } } extern "C" Box* floatGtFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxBool(lhs->d > rhs->d); } extern "C" Box* floatGtInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxBool(lhs->d > rhs->n); } extern "C" Box* floatGt(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatGtInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatGtFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxBool(lhs->d > PyLong_AsDouble(rhs)); } else { return NotImplemented; } } extern "C" Box* floatGeFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxBool(lhs->d >= rhs->d); } extern "C" Box* floatGeInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxBool(lhs->d >= rhs->n); } extern "C" Box* floatGe(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatGeInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatGeFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxBool(lhs->d >= PyLong_AsDouble(rhs)); } else { return NotImplemented; } } extern "C" Box* floatModFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxFloat(mod_float_float(lhs->d, rhs->d)); } extern "C" Box* floatModInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxFloat(mod_float_float(lhs->d, rhs->n)); } extern "C" Box* floatMod(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatModInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatModFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxFloat(mod_float_float(lhs->d, PyLong_AsDouble(rhs))); } else { return NotImplemented; } } extern "C" Box* floatRModFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxFloat(mod_float_float(rhs->d, lhs->d)); } extern "C" Box* floatRModInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxFloat(mod_float_float(rhs->n, lhs->d)); } extern "C" Box* floatRMod(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatRModInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatRModFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxFloat(mod_float_float(PyLong_AsDouble(rhs), lhs->d)); } else { return NotImplemented; } } extern "C" Box* floatPowFloat(BoxedFloat* lhs, BoxedFloat* rhs, Box* mod = None) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); if (mod != None) raiseExcHelper(TypeError, "pow() 3rd argument not allowed unless all arguments are integers"); return boxFloat(pow(lhs->d, rhs->d)); } extern "C" Box* floatPowInt(BoxedFloat* lhs, BoxedInt* rhs, Box* mod = None) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); if (mod != None) raiseExcHelper(TypeError, "pow() 3rd argument not allowed unless all arguments are integers"); return boxFloat(pow(lhs->d, rhs->n)); } extern "C" Box* floatPow(BoxedFloat* lhs, Box* rhs, Box* mod) { assert(lhs->cls == float_cls); if (mod != None) raiseExcHelper(TypeError, "pow() 3rd argument not allowed unless all arguments are integers"); if (isSubclass(rhs->cls, int_cls)) { return floatPowInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatPowFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxFloat(pow(lhs->d, PyLong_AsDouble(rhs))); } else { return NotImplemented; } } extern "C" Box* floatMulFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxFloat(lhs->d * rhs->d); } extern "C" Box* floatMulInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxFloat(lhs->d * rhs->n); } extern "C" Box* floatMul(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatMulInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatMulFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxFloat(lhs->d * PyLong_AsDouble(rhs)); } else { return NotImplemented; } } extern "C" Box* floatSubFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxFloat(lhs->d - rhs->d); } extern "C" Box* floatSubInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxFloat(lhs->d - rhs->n); } extern "C" Box* floatSub(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatSubInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatSubFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxFloat(lhs->d - PyLong_AsDouble(rhs)); } else { return NotImplemented; } } extern "C" Box* floatRSubFloat(BoxedFloat* lhs, BoxedFloat* rhs) { assert(lhs->cls == float_cls); assert(rhs->cls == float_cls); return boxFloat(rhs->d - lhs->d); } extern "C" Box* floatRSubInt(BoxedFloat* lhs, BoxedInt* rhs) { assert(lhs->cls == float_cls); assert(isSubclass(rhs->cls, int_cls)); return boxFloat(rhs->n - lhs->d); } extern "C" Box* floatRSub(BoxedFloat* lhs, Box* rhs) { assert(lhs->cls == float_cls); if (isSubclass(rhs->cls, int_cls)) { return floatRSubInt(lhs, static_cast<BoxedInt*>(rhs)); } else if (rhs->cls == float_cls) { return floatRSubFloat(lhs, static_cast<BoxedFloat*>(rhs)); } else if (rhs->cls == long_cls) { return boxFloat(PyLong_AsDouble(rhs) - lhs->d); } else { return NotImplemented; } } Box* floatNeg(BoxedFloat* self) { assert(self->cls == float_cls); return boxFloat(-self->d); } bool floatNonzeroUnboxed(BoxedFloat* self) { assert(self->cls == float_cls); return self->d != 0.0; } Box* floatNonzero(BoxedFloat* self) { return boxBool(floatNonzeroUnboxed(self)); } std::string floatFmt(double x, int precision, char code) { char fmt[5] = "%.*g"; fmt[3] = code; if (isnan(x)) { return "nan"; } if (isinf(x)) { if (x > 0) return "inf"; return "-inf"; } char buf[40]; int n = snprintf(buf, 40, fmt, precision, x); int dot = -1; int exp = -1; int first = -1; for (int i = 0; i < n; i++) { char c = buf[i]; if (c == '.') { dot = i; } else if (c == 'e') { exp = i; } else if (first == -1 && c >= '0' && c <= '9') { first = i; } } if (dot == -1 && exp == -1) { if (n == precision) { memmove(buf + first + 2, buf + first + 1, (n - first - 1)); buf[first + 1] = '.'; exp = n + 1; int exp_digs = snprintf(buf + n + 1, 5, "e%+.02d", (n - first - 1)); n += exp_digs + 1; dot = 1; } else { buf[n] = '.'; buf[n + 1] = '0'; n += 2; return std::string(buf, n); } } if (exp != -1 && dot == -1) { return std::string(buf, n); } assert(dot != -1); int start, end; if (exp) { start = exp - 1; end = dot; } else { start = n - 1; end = dot + 2; } for (int i = start; i >= end; i--) { if (buf[i] == '0') { memmove(buf + i, buf + i + 1, n - i - 1); n--; } else if (buf[i] == '.') { memmove(buf + i, buf + i + 1, n - i - 1); n--; break; } else { break; } } return std::string(buf, n); } BoxedFloat* _floatNew(Box* a) { // FIXME CPython uses PyUnicode_EncodeDecimal: a = coerceUnicodeToStr(a); if (a->cls == float_cls) { return static_cast<BoxedFloat*>(a); } else if (isSubclass(a->cls, float_cls)) { return new BoxedFloat(static_cast<BoxedFloat*>(a)->d); } else if (isSubclass(a->cls, int_cls)) { return new BoxedFloat(static_cast<BoxedInt*>(a)->n); } else if (a->cls == str_cls) { const std::string& s = static_cast<BoxedString*>(a)->s; if (s == "nan") return new BoxedFloat(NAN); if (s == "-nan") return new BoxedFloat(-NAN); if (s == "inf") return new BoxedFloat(INFINITY); if (s == "-inf") return new BoxedFloat(-INFINITY); // TODO this should just use CPython's implementation: char* endptr; const char* startptr = s.c_str(); double r = strtod(startptr, &endptr); if (endptr != startptr + s.size()) raiseExcHelper(ValueError, "could not convert string to float: %s", s.c_str()); return new BoxedFloat(r); } else { static const std::string float_str("__float__"); Box* r = callattr(a, &float_str, CallattrFlags({.cls_only = true, .null_on_nonexistent = true }), ArgPassSpec(0), NULL, NULL, NULL, NULL, NULL); if (!r) { fprintf(stderr, "TypeError: float() argument must be a string or a number, not '%s'\n", getTypeName(a)); raiseExcHelper(TypeError, ""); } if (!isSubclass(r->cls, float_cls)) { raiseExcHelper(TypeError, "__float__ returned non-float (type %s)", r->cls->tp_name); } return static_cast<BoxedFloat*>(r); } } Box* floatNew(BoxedClass* _cls, Box* a) { if (!isSubclass(_cls->cls, type_cls)) raiseExcHelper(TypeError, "float.__new__(X): X is not a type object (%s)", getTypeName(_cls)); BoxedClass* cls = static_cast<BoxedClass*>(_cls); if (!isSubclass(cls, float_cls)) raiseExcHelper(TypeError, "float.__new__(%s): %s is not a subtype of float", getNameOfClass(cls), getNameOfClass(cls)); if (cls == float_cls) return _floatNew(a); BoxedFloat* f = _floatNew(a); return new (cls) BoxedFloat(f->d); } Box* floatStr(BoxedFloat* self) { if (!isSubclass(self->cls, float_cls)) raiseExcHelper(TypeError, "descriptor '__str__' requires a 'float' object but received a '%s'", getTypeName(self)); return boxString(floatFmt(self->d, 12, 'g')); } Box* floatRepr(BoxedFloat* self) { assert(self->cls == float_cls); return boxString(floatFmt(self->d, 16, 'g')); } Box* floatTrunc(BoxedFloat* self) { if (!isSubclass(self->cls, float_cls)) raiseExcHelper(TypeError, "descriptor '__trunc__' requires a 'float' object but received a '%s'", getTypeName(self)); double wholepart; /* integral portion of x, rounded toward 0 */ (void)modf(self->d, &wholepart); /* Try to get out cheap if this fits in a Python int. The attempt * to cast to long must be protected, as C doesn't define what * happens if the double is too big to fit in a long. Some rare * systems raise an exception then (RISCOS was mentioned as one, * and someone using a non-default option on Sun also bumped into * that). Note that checking for <= LONG_MAX is unsafe: if a long * has more bits of precision than a double, casting LONG_MAX to * double may yield an approximation, and if that's rounded up, * then, e.g., wholepart=LONG_MAX+1 would yield true from the C * expression wholepart<=LONG_MAX, despite that wholepart is * actually greater than LONG_MAX. However, assuming a two's complement * machine with no trap representation, LONG_MIN will be a power of 2 (and * hence exactly representable as a double), and LONG_MAX = -1-LONG_MIN, so * the comparisons with (double)LONG_MIN below should be safe. */ if ((double)LONG_MIN <= wholepart && wholepart < -(double)LONG_MIN) { const long aslong = (long)wholepart; return PyInt_FromLong(aslong); } return PyLong_FromDouble(wholepart); } extern "C" void printFloat(double d) { std::string s = floatFmt(d, 12, 'g'); printf("%s", s.c_str()); } static void _addFunc(const char* name, ConcreteCompilerType* rtn_type, void* float_func, void* int_func, void* boxed_func) { std::vector<ConcreteCompilerType*> v_ff, v_fi, v_fu; v_ff.push_back(BOXED_FLOAT); v_ff.push_back(BOXED_FLOAT); v_fi.push_back(BOXED_FLOAT); v_fi.push_back(BOXED_INT); v_fu.push_back(BOXED_FLOAT); v_fu.push_back(UNKNOWN); CLFunction* cl = createRTFunction(2, 0, false, false); addRTFunction(cl, float_func, rtn_type, v_ff); addRTFunction(cl, int_func, rtn_type, v_fi); addRTFunction(cl, boxed_func, UNKNOWN, v_fu); float_cls->giveAttr(name, new BoxedFunction(cl)); } static void _addFuncPow(const char* name, ConcreteCompilerType* rtn_type, void* float_func, void* int_func, void* boxed_func) { std::vector<ConcreteCompilerType*> v_ffu{ BOXED_FLOAT, BOXED_FLOAT, UNKNOWN }; std::vector<ConcreteCompilerType*> v_fiu{ BOXED_FLOAT, BOXED_INT, UNKNOWN }; std::vector<ConcreteCompilerType*> v_fuu{ BOXED_FLOAT, UNKNOWN, UNKNOWN }; CLFunction* cl = createRTFunction(3, 1, false, false); addRTFunction(cl, float_func, rtn_type, v_ffu); addRTFunction(cl, int_func, rtn_type, v_fiu); addRTFunction(cl, boxed_func, UNKNOWN, v_fuu); float_cls->giveAttr(name, new BoxedFunction(cl, { None })); } void setupFloat() { _addFunc("__add__", BOXED_FLOAT, (void*)floatAddFloat, (void*)floatAddInt, (void*)floatAdd); float_cls->giveAttr("__radd__", float_cls->getattr("__add__")); _addFunc("__div__", BOXED_FLOAT, (void*)floatDivFloat, (void*)floatDivInt, (void*)floatDiv); _addFunc("__rdiv__", BOXED_FLOAT, (void*)floatRDivFloat, (void*)floatRDivInt, (void*)floatRDiv); _addFunc("__floordiv__", BOXED_FLOAT, (void*)floatFloorDivFloat, (void*)floatFloorDivInt, (void*)floatFloorDiv); _addFunc("__truediv__", BOXED_FLOAT, (void*)floatDivFloat, (void*)floatDivInt, (void*)floatTruediv); _addFunc("__eq__", BOXED_BOOL, (void*)floatEqFloat, (void*)floatEqInt, (void*)floatEq); _addFunc("__ge__", BOXED_BOOL, (void*)floatGeFloat, (void*)floatGeInt, (void*)floatGe); _addFunc("__gt__", BOXED_BOOL, (void*)floatGtFloat, (void*)floatGtInt, (void*)floatGt); _addFunc("__le__", BOXED_BOOL, (void*)floatLeFloat, (void*)floatLeInt, (void*)floatLe); _addFunc("__lt__", BOXED_BOOL, (void*)floatLtFloat, (void*)floatLtInt, (void*)floatLt); _addFunc("__ne__", BOXED_BOOL, (void*)floatNeFloat, (void*)floatNeInt, (void*)floatNe); _addFunc("__mod__", BOXED_FLOAT, (void*)floatModFloat, (void*)floatModInt, (void*)floatMod); _addFunc("__rmod__", BOXED_FLOAT, (void*)floatRModFloat, (void*)floatRModInt, (void*)floatRMod); _addFunc("__mul__", BOXED_FLOAT, (void*)floatMulFloat, (void*)floatMulInt, (void*)floatMul); float_cls->giveAttr("__rmul__", float_cls->getattr("__mul__")); _addFuncPow("__pow__", BOXED_FLOAT, (void*)floatPowFloat, (void*)floatPowInt, (void*)floatPow); _addFunc("__sub__", BOXED_FLOAT, (void*)floatSubFloat, (void*)floatSubInt, (void*)floatSub); _addFunc("__rsub__", BOXED_FLOAT, (void*)floatRSubFloat, (void*)floatRSubInt, (void*)floatRSub); float_cls->giveAttr( "__new__", new BoxedFunction(boxRTFunction((void*)floatNew, UNKNOWN, 2, 1, false, false), { boxFloat(0.0) })); float_cls->giveAttr("__neg__", new BoxedFunction(boxRTFunction((void*)floatNeg, BOXED_FLOAT, 1))); CLFunction* nonzero = boxRTFunction((void*)floatNonzeroUnboxed, BOOL, 1); addRTFunction(nonzero, (void*)floatNonzero, UNKNOWN); float_cls->giveAttr("__nonzero__", new BoxedFunction(nonzero)); // float_cls->giveAttr("__nonzero__", new BoxedFunction(boxRTFunction((void*)floatNonzero, NULL, 1))); float_cls->giveAttr("__str__", new BoxedFunction(boxRTFunction((void*)floatStr, STR, 1))); float_cls->giveAttr("__repr__", new BoxedFunction(boxRTFunction((void*)floatRepr, STR, 1))); float_cls->giveAttr("__trunc__", new BoxedFunction(boxRTFunction((void*)floatTrunc, BOXED_INT, 1))); float_cls->freeze(); } void teardownFloat() { } }
/* * Copyright(c) 2018 WindSoul Network Technology, Inc. All rights reserved. */ /** * Desc: Module初始化的工具类。应对联机模式下客户端和服务端初始化差异问题 * Author: * Date: 2019-04-05 * Time: 16:55 */ #pragma once #include "Engine/World.h" #include "Constants/EnumDefine.h" #include "Unreal/Module/ModuleListManager.hpp" #include "Unreal/Character/BaseCharacter.h" class ModuleInitHelper { public: static void InitModulesForCharacter(UWorld* World, ABaseCharacter* Character, int ReplTypes) { if (World && Character) { for (ModuleInfoInterface* ModuleInfoPtr : ModuleListManager::CharacterModuleInfos) { if (ModuleInfoPtr) { if ((ModuleInfoPtr->GetReplType() & ReplTypes) > 0) { UObject* Obj = ModuleInfoPtr->SpawnModuleDeferred(World, Character); if (ACharacterModuleBase* Module = Cast<ACharacterModuleBase>(Obj)) { Character->Modules[(int)ModuleInfoPtr->GetModuleType()] = Module; int CurrReplType = ModuleInfoPtr->GetReplType() & ReplTypes; switch (CurrReplType) { case EModuleReplType::EMPT_ClientOnly: { break; } case EModuleReplType::EMPT_ServerOnly: { Module->SetReplicates(false); Module->SetAutonomousProxy(false); Module->bNetUseOwnerRelevancy = false; Module->bOnlyRelevantToOwner = true; Module->SetOwner(nullptr); break; } case EModuleReplType::EMPT_RepliateToClient: { Module->SetReplicates(true); Module->SetAutonomousProxy(false); Module->bNetUseOwnerRelevancy = false; Module->bOnlyRelevantToOwner = true; Module->SetOwner(Character); break; } case EModuleReplType::EMPT_RepliateToAllClient: { Module->SetReplicates(true); Module->SetAutonomousProxy(false); Module->bNetUseOwnerRelevancy = true; Module->bOnlyRelevantToOwner = false; Module->SetOwner(Character); break; } case EModuleReplType::EMPT_InteractWithClient: { Module->SetReplicates(true); Module->SetAutonomousProxy(true); Module->bNetUseOwnerRelevancy = true; Module->SetOwner(Character); break; } } } } } } if (Character->Modules.Num() == ModuleListManager::CharacterModuleInfos.Num()) { ENetMode NM = Character->GetNetMode(); for (int i = 0; i < Character->Modules.Num(); i++) { ACharacterModuleBase* _Module = Character->Modules[i]; if (_Module) { //if (ENetMode::NM_DedicatedServer == NM) { _Module->PostReplicationSetup(); } ModuleInfoInterface* ModuleInfo = ModuleListManager::CharacterModuleInfos[i]; if (ModuleInfo) { if (!(ENetMode::NM_Client == NM && (ModuleInfo->GetReplType() == EModuleReplType::EMPT_RepliateToClient || ModuleInfo->GetReplType() == EModuleReplType::EMPT_RepliateToAllClient || ModuleInfo->GetReplType() == EModuleReplType::EMPT_InteractWithClient))) { FTransform Transform; _Module->FinishSpawning(Transform); } } if (ENetMode::NM_DedicatedServer == NM) { _Module->OnServerAllModulesCreateComplete(); } } } } } } static void RefreshModuelTypeForClient(ABaseCharacter* Character) { if (Character) { if (ENetMode::NM_Client == Character->GetNetMode()) { if (Character->Modules.Num() == ModuleListManager::CharacterModuleInfos.Num()) { for (int i = 0; i < Character->Modules.Num(); i++) { if (ACharacterModuleBase* ModulePtr = Character->Modules[i]) { if (ModuleInfoInterface* ModuleInfo = ModuleListManager::CharacterModuleInfos[i]) { ModulePtr->SetModuleType(ModuleInfo->GetModuleType()); } } } } } } } static int FindModuleIndex(ACharacterModuleBase* ClientModule) { int Index = -1; if (ClientModule && ENetMode::NM_Client == ClientModule->GetNetMode()) { for (int i = 0; i < ModuleListManager::CharacterModuleInfos.Num(); i++) { if (ModuleInfoInterface* ModuleInfo = ModuleListManager::CharacterModuleInfos[i]) { if (ModuleInfo->ModuleTemplatePtr) { FString LStr1; FString RStr1; ModuleInfo->ModuleTemplatePtr->GetName().Split("_", &LStr1, &RStr1, ESearchCase::IgnoreCase, ESearchDir::FromEnd); FString LStr2; FString RStr2; ClientModule->GetName().Split("_", &LStr2, &RStr2, ESearchCase::IgnoreCase, ESearchDir::FromEnd); if (LStr1 == LStr2) { Index = i; break; } } } } } return Index; } static void InitModulesForActor(UWorld* World, ABaseActor* Character, int ReplTypes) { } };
#pragma once class GameCursor; enum MonsterID; class ShowMonsters : public GameObject { public: bool Start() override; void Update() override; void OnDestroy() override; void SetWindowActive(bool active) { m_isActive = active; } private: void InitFont(); void InitButtons(); void InitSideButtons(); void ButtonUpdate(); void ChangePage(); bool m_isActive = true; std::vector<SpriteRender*> m_monsterSps; std::vector<SpriteRender*> m_frames; std::vector<FontRender*> m_MonsterNames; std::map<SpriteRender*, MonsterID> m_spId; SpriteRender* m_backSp = nullptr; SpriteRender* m_quitSp = nullptr; SpriteRender* m_leftSp = nullptr; SpriteRender* m_rightSp = nullptr; const int nX =3; const int nY = 7; const int nButtonMax= 9; CVector3 m_basePos = { -370, 447.5,0 }; GameCursor* m_cur = nullptr; int m_currentPage = 1; int m_totalPage = 0; };
#include <bits/stdc++.h> #define REP(i, a, b) for(int i = (int)a; i < (int)b; i++) #define fastio ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0) #define pb push_back #define mp make_pair #define st first #define nd second #define vi vector<int> #define ii pair<int, int> #define ll long long int #define MAX 200010 #define MOD 1000000007 #define oo 0x7fffffff #define endl '\n' using namespace std; char change(char ini, char mov){ if(ini == 'N'){ if(mov == 'D'){ return 'L'; } return 'O'; }else if(ini == 'S'){ if(mov == 'D'){ return 'O'; } return 'L'; }else if(ini == 'L'){ if(mov == 'D'){ return 'S'; } return 'N'; } if(mov == 'D'){ return 'N'; } return 'S'; } int main() { fastio; // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int n; while(cin >> n && n){ string mov; cin >> mov; char ini = 'N'; REP(i, 0, n){ ini = change(ini, mov[i]); } cout << ini << endl; } return 0; }
#include <stdio.h> #include <conio.h> void start(); void showRectangular(); void showSquare(); void showDiagonal(); void showScalarDiagonal(); void showUnitary(); void showAddition(); void showSubtraction(); void showScalarMultiplication(); void showMultiplication(); void showTranspose(); void showSymetric(); void showSkewSymetric(); void showMatrixValidation(); void main () { char *ch[]={" RECTANGULAR MATRIX", " SQUARE MATRIX", " DIAGONAL MATRIX", " SCALAR DIAGONAL MATRIX", " UNITARY MATRIX", " ADDITION MATRIX", " SUBTRACTION MATRIX", " SCALAR MULTIPLICATION MATRIX", " MULTIPLICATION MATRIX", "TRANSPOSE MATRIX", "SYMETRIC MATRIX", "SKEW-SYMETRIC MATRIX", "MATRIX VALIDATION" }; int length; int forLoop; int op; clrscr(); gotoxy(25, 20); printf("WELCOME TO MATRIX APPLICATION"); printf("\n\n\n\t\t\t PRESS ENTER TO CONTINUE..."); getche(); clrscr(); gotoxy(26, 15); printf("PROGRAMMERS' NOTE"); gotoxy(5, 20); printf("The Application is intended to solve and clear the basic concepts of Matrix\n\n (plural Matrices)."); printf("\n\n\n\n=> This Matrix Application involves all the basic Matrix properties that are\n\n required by the basic learners of Matrices. Moreover it defines each\n\n property with an example."); printf(" GOOD LUCK !"); gotoxy(25, 40); printf("Press Enter to continue!"); getche(); do { // Start of DoWhile start(); gotoxy(8, 8); printf("Selection Menu for the Matrix"); gotoxy(10, 10); length=sizeof(ch)/sizeof(int); for(forLoop=0; forLoop<length; forLoop++) printf("\n\n\t%d. %s", (forLoop+1), ch[forLoop]); printf("\n\n\t%d. EXIT", forLoop+1); printf("\n\n\tEnter your Selection: "); scanf("%d", &op); switch (op){ case 1: showRectangular(); break; case 2: showSquare(); break; case 3: showDiagonal(); break; case 4: showScalarDiagonal(); break; case 5: showUnitary(); break; case 6: showAddition(); break; case 7: showSubtraction(); break; case 8: showScalarMultiplication(); break; case 9: showMultiplication(); break; case 10: showTranspose(); break; case 11: showSymetric(); break; case 12: showSkewSymetric(); break; case 13: showMatrixValidation(); break; case 14: break; default: break; } // End of Switch }while (op!=14); // End of DoWhile } // End of Main Method void start () { clrscr(); gotoxy(25,2); printf("MATRIX APPLICATION\n\n\n\n"); } void showRectangular(){ // RECTANGULAR MATRIX start(); int A[2][4]={1, 1, 1, 1, 2, 2, 2, 2}; int r, c, r2, c2; int i, j; gotoxy(25, 8); printf("RECTANGULAR MATRIX\n\n"); printf("\n\n\tA Rectangular Matrix is a matrix whose number of\n\n\trows will"); printf(" never be equal to number of columns.\n\n"); printf("\n\n\t=> No. of Rows != No. of Columns\n"); printf("\n\n\tLet A be any Matrix\n\n\n"); printf("\tA = "); for(i=0; i<2; i++) { // Start of For for(j=0; j<4; j++) printf(" %d ", A[i][j]); printf("\n\t "); } // End of For printf("\n\n\tWhose order is 2X4 is a Rectangular matrix.\n\n"); gotoxy(25, 40); printf("Press any Key to go back!"); getche(); } // End of Rectangular Method void showSquare() { // SQUARE MATRIX start(); int A[2][4]={1, 1, 1, 1, 2, 2, 2, 2}; int r, c, r2, c2; int i, j; gotoxy(25, 8); printf("SQUARE MATRIX\n\n"); printf("\n\n\tA Square Matrix is a matrix whose number of rows\n\n\twill always"); printf(" be equal to number of columns.\n\n"); printf("\n\n\t=> No. of Rows = No. of Columns\n"); printf("\n\n\tLet A be any Matrix\n\n\n"); printf("\tA = "); for (i=0; i<2; i++){ for(j=0; j<2; j++) printf(" %d ", A[i][j]); printf("\n\t "); } printf("\n\n\tWhose order is 2X2 is a Square matrix.\n\n"); gotoxy(25, 40); printf("Press any Key to go back!"); getche(); } // End of Square Method void showDiagonal(){ // DIAGONAL MATRIX start(); int A[10][10]; int r, c, r2, c2; int i, j; int TEMP[3][3]={1, 0, 0, 0, 2, 0, 0, 0, 3}; gotoxy(25, 8); printf("DIAGONAL MATRIX\n\n"); printf("\n\n\tA Diagonal Matrix will always be a Square matrix whose all\n\n\telements are zero except the diagonal elements.\n\n"); printf("\n\n\tLet D be any Matrix\n\n\n"); printf("\tD = "); for(i=0; i<3; i++){ for(j=0; j<3; j++) printf(" %d ", TEMP[i][j]); printf("\n\t "); } printf("\n\n\tWhose order is 3X3 is a Diagonal matrix.\n\n"); printf("\n\n\tNow you can try! Press Enter...\n\n"); getch(); clrscr(); start(); printf("\n\n\tMatrix D\n"); printf("\n\nEnter No. of Rows: "); scanf("%d", &r); printf("\n\nEnter No. of Columns: "); scanf("%d", &c); if (r==c){ printf("\n\n\n\tEnter values for Matrix D in matrix order\n\n\n"); printf("\tD = "); for(int i=0; i<r; i++) { for (int j=0; j<c; j++) scanf("%d", &A[i][j]); printf("\n\t "); } // End of for for(i=0; i<r; i++) for(int j=0; j<c; j++){ if (i==j){ if(A[i][j]!=0) ; else{ printf("\n\n\tOoh! It's a Non-Diagonal Matrix"); goto Label; } } else if(A[i][j]!=0) { printf("\n\n\tOoh! It's a Non-Diagonal Matrix"); goto Label; } } printf("\n\n\tHurrah! It's a Diagonal matrix \x01"); } else{ gotoxy(20,20); printf("Ooh! It's a Non-Square Matrix"); } Label: gotoxy(25, 40); printf("Press any Key to go back!"); getche(); } // End of Diagonal Method void showScalarDiagonal(){ // SCALAR DIAGONAL MATRIX start(); int A[10][10]; int r, c, r2, c2; int i, j; int TEMP[3][3]={5, 0, 0, 0, 5, 0, 0, 0, 5}; gotoxy(25, 8); printf("SCALAR DIAGONAL MATRIX\n\n"); printf("\n\n\tA Scalar Diagonal Matrix will always be a Diagonal matrix if and\n\n\tonly if it's Diagonal elements are same.\n\n"); printf("\n\n\tLet S be any Matrix\n\n\n"); printf("\tS = "); for(i=0; i<3; i++){ for(j=0; j<3; j++) printf(" %d ", TEMP[i][j]); printf("\n\t "); } printf("\n\n\tWhose order is 3X3 is a Scalar Diagonal matrix.\n\n"); printf("\n\n\tNow you can try! Press Enter...\n\n"); getch(); clrscr(); start(); printf("\n\n\tMatrix A\n"); printf("\n\nEnter No. of Rows: "); scanf("%d", &r); printf("\n\nEnter No. of Columns: "); scanf("%d", &c); if (r==c){ // Start of IF printf("\n\n\n\tEnter values for Matrix A in matrix order\n\n\n"); printf("\tA = "); for(i=0; i<r; i++) { for(j=0; j<c; j++) scanf("%d", &A[i][j]); printf("\n\t "); } for(i=0; i<r; i++) for(int j=0; j<c; j++){ if (i==j){ if(A[i][j]==A[0][0]) ; else{ printf("\n\n\tOoh! It's a Non-Scalar Diagonal matrix."); goto Label; } } else if(A[i][j]!=0){ printf("\n\n\tOoh! It's is a Non-Diagonal matrix."); goto Label; } } printf("\n\n\tHurrah! It's a Scalar Diagonal matrix \x01"); } else{ gotoxy(20,20); printf("Ooh! It's a Non-Square matrix."); } Label: gotoxy(25,40); printf("Press any Key to go back!"); getch(); } // end of scalarDiagonalMatrix void showUnitary(){ // UNITARY MATRIX start(); int A[3][3]={1, 0, 0, 0, 1, 0, 0, 0, 1}; int r, c, r2, c2; int i, j; gotoxy(25, 8); printf("UNITARY MATRIX\n\n"); printf("\n\n\tA Square Matrix Whose all elements except diagonal elements"); printf("\n\n\tare zero '0' and the diagonal elements are always '1'.\n\n"); printf("\n\n\t Let U be any Matrix\n\n\n"); printf("\tU = "); for(i=0; i<3; i++){ for(j=0; j<3; j++) printf(" %d ", A[i][j]); printf("\n"); printf("\t "); } printf("\n\n\tWhose order is 3X3 is a Unitary matrix.\n\n"); printf("\n\n\tNow you can try! Press Enter...\n\n"); getch(); clrscr(); start(); printf("\n\n\tMatrix A\n"); printf("\n\nEnter No. of Rows: "); scanf("%d", &r); printf("\n\nEnter No. of Columns: "); scanf("%d", &c); if (r==c){ // Start of IF printf("\n\n\n\tEnter values for Matrix A in matrix order"); printf("\n\n\tA = "); for(i=0; i<r; i++){ for(j=0; j<c; j++) scanf("%d", &A[i][j]); printf("\n\t "); } for(i=0; i<r; i++) for(int j=0; j<c; j++){ if (i==j){ if(A[i][j]==1) ; else{ printf("\n\n\tOoh! It's a non-Unitary Diagonal matrix."); goto Label; } } else if(A[i][j]!=0){ printf("\n\n\tOoh! It's a non-Diagonal matrix."); goto Label; } } printf("\n\n\tHurrah! It's a Unitary Diagonal matrix \x01"); } else{ gotoxy(20,20); printf("Ooh! It's a non-Square matrix."); } Label: gotoxy(25, 40); printf("Press any Key to go back!"); getch(); } // End of Unitary Method void showAddition(){ // MATRICES WITH ADDITION start(); int A[10][10], B[10][10], C[10][10]; int r, c, r2, c2; int i, j; gotoxy(25, 8); printf("ADDITION OF MATRIX\n\n"); printf("\n\n\tMatrix A"); printf("\n\nEnter No. of Rows: "); scanf("%d", &r); printf("\n\nEnter No. of Columns: "); scanf("%d", &c); printf("\n\n\tMatrix B"); printf("\n\nEnter No. of Rows: "); scanf("%d", &r2); printf("\n\nEnter No. of Columns: "); scanf("%d", &c2); if (r==r2 && c==c2){ // Start of IF clrscr(); printf("\n\n\tAddition is possible:"); printf("\n\n\tEnter values for Matrix A in matrix order\n\n"); printf("\tA = "); for(i=0; i<r; i++) { for(j=0; j<c; j++) scanf("%d", &A[i][j]); printf("\n\t "); } // End of for printf("\n\n\tEnter values for Matrix B in matrix order\n\n"); printf("\tB = "); for(i=0; i<r2; i++){ for (j=0; j<c2; j++) scanf("%d", &B[i][j]); printf("\n\t "); } // End of for printf("\n\n\tThe values of Matrix A is:\n\n"); printf("\tA = "); for(i=0; i<r; i++) { for (j=0; j<c; j++) printf("%d ", A[i][j]); printf("\n\t "); } // End of A printf("\n\n\tThe values of Matrix B is:\n\n"); printf("\tB = "); for(i=0; i<r2; i++){ for(j=0; j<c2; j++) printf("%d ", B[i][j]); printf("\n\t "); } // End of B printf("\n\n\tThe Addition of Matrices A & B is:\n\n"); for(i=0; i<r; i++) for(j=0; j<c; j++) C[i][j]=A[i][j]+B[i][j]; printf("\tA+B = "); for(i=0; i<r; i++){ // Start of outer For for(j=0; j<c; j++) printf("%d ", C[i][j]); printf("\n\t "); } } // End of IF else{ // Start of Else printf("\n\n\n\t\tThe Entered Matrices are not of same order\n"); printf("\n\n\t\tADDITION is not possible !\n"); } // End of Else printf("\n\n\t\tPress any Key to go back."); getche(); } // End of Addition Method void showSubtraction(){ // MATRICES WITH SUBTRACTION start(); int A[10][10], B[10][10], C[10][10]; int r, c, r2, c2; int i, j; gotoxy(24, 8); printf("SUBTRACTION OF MATRIX"); printf("\n\n\tMatrix A"); printf("\n\nEnter No. of Rows: "); scanf("%d", &r); printf("\n\nEnter No. of Columns: "); scanf("%d", &c); printf("\n\n\tMatrix B"); printf("\n\nEnter No. of Rows: "); scanf("%d", &r2); printf("\n\nEnter No. of Columns: "); scanf("%d", &c2); if(r==r2 && c==c2){ // Start of IF printf("\n\n\tSubtraction is possible:"); printf("\n\n\tEnter values for Matrix A in matrix order\n\n"); printf("\tA = "); for(i=0; i<r; i++){ for(j=0; j<c; j++) scanf("%d", &A[i][j]); printf("\n\t "); } printf("\n\n\tEnter values for Matrix B in matrix order\n\n"); printf("\tB = "); for(i=0; i<r2; i++) { for(j=0; j<c2; j++) scanf("%d", &B[i][j]); printf("\n\t "); } clrscr(); start(); printf("\n\n\tThe values of Matrix A is:\n\n"); printf("\tA = "); for(i=0; i<r; i++){ // start of A for(j=0; j<c; j++) printf("%d ", A[i][j]); printf("\n\t "); } // End of A printf("\n\n\tThe values of Matrix B is:\n\n"); printf("\tB = "); for(i=0; i<r2; i++){ // Start of B for(j=0; j<c2; j++) printf("%d ", B[i][j]); printf("\n\t "); } // End of B int sub; printf("\n\n\t1. A - B"); printf("\n\t2. B - A"); printf("\n\n\tEnter your selection: "); scanf("%d", &sub); if(sub==1){ printf("\n\n\tThe Subtraction of Matrices A - B is:\n"); for(i=0; i<r; i++) for(j=0; j<c; j++) C[i][j]=A[i][j]-B[i][j]; printf("\n\tA-B = "); for(i=0; i<r; i++){ // Start of outer for for(j=0; j<c; j++) printf("%d ", C[i][j]); printf("\n\t "); } // End of Outer For } // End of Inner If if(sub==2){ printf("\n\n\tThe Subtraction of Matrices B - A is:\n"); for(i=0; i<r; i++) for(j=0; j<c; j++) C[i][j]=B[i][j]-A[i][j]; printf("\n\tB-A = "); for(i=0; i<r; i++) { // Start of outer For for(int j=0; j<c; j++) printf("%d ", C[i][j]); printf("\n\t "); } // End of Outer For } // End of If } // End of IF else{ // Start of Else printf("\n\n\n\t\tThe Entered Matrices are not of same order\n"); printf("\n\n\t\tSUBTRATION is not possible !\n\n"); } // End of Else gotoxy(25,40); printf("Press any Key to go back."); getche(); } // End of Subtraction Method void showScalarMultiplication(){ // SCALAR MULTIPLICATION start(); int A[3][3]={2, 4, 3, 4, 2, 3, 6, 7, 4}; int r, c, r2, c2; int i, j; gotoxy(24, 8); printf("SCALAR MULTIPLICATION"); printf("\n\n\tLet K is a scalar and A be any Square Matrix then every\n\n\t"); printf("element of A is multiplied with a scalar K.\n"); printf("\n\n\tLet A be any Square Matrix\n\n"); for(i=0; i<3; i++){ printf("\t"); for(j=0; j<3; j++) printf(" %d ", A[i][j]); printf("\n"); } printf("\n\n\n\t"); printf("Let 5 is a scalar which multiplies matrix A\n\n"); for(i=0; i<3; i++){ printf("\t"); for(j=0; j<3; j++) printf(" %d ", 5*A[i][j]); printf("\n"); } printf("\n\n\tWhose order is 3X3 is a Scalar Diagonal matrix.\n\n"); printf("\n\n\n\tPress any Key to perform Scalar Multiplication.\n\n"); getche(); clrscr(); start(); printf("\n\n\tMatrix A"); printf("\n\n\tEnter No. of Rows: "); scanf("%d", &r); printf("\n\n\tEnter No. of Columns: "); scanf("%d", &c); printf("\n\n\tEnter values for Matrix A in matrix order\n\n"); printf("\tA = "); for(i=0; i<r; i++){ for(j=0; j<c; j++){ scanf("%d", &A[i][j]); } printf("\n\t "); } printf("\n\n\tEnter any Scalar value: "); scanf("%d", &r2); printf("\n\n\tThe values of Matrix A after multiplication is:\n\n"); printf("\tA = "); for(i=0; i<r; i++){ // start of A for(j=0; j<c; j++) printf(" %d ", r2*A[i][j]); printf("\n\t "); } // End of A gotoxy(25, 40); printf("Press any Key to go back!"); getche(); } // End of ScalarMultiplication Method void showMultiplication(){ // SquareMultiplication int A[5][5]; int B[5][5]; int C[5][5]; int X[5][5][5]; int i,j,m,a,b; start(); gotoxy(19,5); printf("SQUARE MATRIX MULTIPLICATION\n"); printf("\n\nEnter Rows: "); scanf("%d",&a); printf("\n\nEnter Columns: "); scanf("%d",&b); gotoxy(25,16); printf("Matrix A\n\n"); printf("\t\tEnter values in Matrix form:\n\n"); for(i=0;i<a;i++){ printf("\t\t\t"); for(j=0;j<b;j++){ scanf("%d", &A[i][j]); C[i][j]=0; } // end of Inner loop printf("\n"); } gotoxy(25,26); printf("Matrix B\n\n"); printf("\t\tEnter values in Matrix form:\n\n"); for(i=0;i<a;i++){ printf("\t\t\t"); for(j=0;j<b;j++){ scanf("%d", &B[i][j]); } // end of Inner Loop printf("\n"); } // SHOWING MATRIX A gotoxy(16,36); printf(" The values of Matrix A is:\n\n"); for(i=0; i<a; i++){ printf("\t\t\t"); for(j=0; j<b; j++) printf("%d ",A[i][j]); printf("\n"); } // end of Outer loop // SHOWING MATRIX B gotoxy(16,44); printf(" The values of Matrix B is:\n\n"); for(i=0; i<a; i++){ printf("\t\t\t"); for(j=0; j<b; j++) printf("%d ",B[i][j]); printf("\n"); } // end of Outer loop // MAIN LOGIC OF MULTIPLICATION for(i=0;i<a;i++){ for(j=0;j<b;j++){ for(m=0;m<a;m++){ X[i][j][m]=A[i][m]*B[m][j]; C[i][j]+=X[i][j][m]; } } } clrscr(); start(); gotoxy(24,20); printf("==========Matrix C==========\n\n"); for(i=0;i<a;i++){ printf("\t\t\t\t "); for(j=0;j<b;j++) printf("%d ",C[i][j]); printf("\n\n"); } // end of Outer loop getche(); } // End of Multiplication Method void showTranspose(){ // MATRICES WITH TRANSPOSE start(); int A[10][10], B[10][10]; int r, c, r2, c2; int i, j; gotoxy(25,8); printf("TRANSPOSE OF MATRIX\n\n"); printf("\n\n\tMatrix A"); printf("\n\nEnter No. of Rows: "); scanf("%d", &r); printf("\n\nEnter No. of Columns: "); scanf("%d", &c); printf("\n\n\tEnter values for Matrix A in matrix order\n\n"); printf("\tA = "); for(i=0; i<r; i++) { for(j=0; j<c; j++) scanf("%d", &A[i][j]); printf("\n\t "); } printf("\n\n\tThe transpose of Matrix A is:\n\n"); printf("\tA = "); for(i=0; i<c; i++) { // Start of for body for(j=0; j<r; j++) printf("%d ", A[j][i]); printf("\n\t "); } // End of for gotoxy(25, 40); printf("Press any Key to go back!"); getche(); } // End of Transpose Method void showSymetric(){ // SYMMETRIC MATRIX start(); int C[2][2]={2, 3, 3, 5}; int A[10][10]; int B[10][10]; int r, c; int i, j; // for forLoop gotoxy(25,8); printf("SYMETRIC MATRIX\n\n"); printf("\n\n A Square Matrix is said to be Symmetric,\n\n"); printf("\n\n\t If A(transpose) = A\n"); printf("\n\n\n\tLet A be any Matrix\n\n"); printf("\tA = "); for(i=0; i<2; i++){ for(j=0; j<2; j++) printf(" %d ", C[i][j]); printf("\n\t "); } printf("\n\n\t Transpose of Matrix A will be\n\n\n"); printf("\tA = "); for(i=0; i<2; i++){ for(j=0; j<2; j++){ printf(" %d ", C[j][i]); } printf("\n\t "); } printf("\n\n\tNow you can try! Press Enter...\n\n"); getch(); clrscr(); start(); printf("\n\n\tMatrix A"); printf("\n\nEnter No. of Rows: "); scanf("%d", &r); printf("\n\nEnter No. of Columns: "); scanf("%d", &c); if(r==c){ printf("\n\n\tEnter values of Matrix A in matrix order\n\n"); printf("\tA = "); for(i=0; i<r; i++){ for(j=0; j<c; j++) scanf("%d", &A[i][j]); printf("\n\t "); } // end of outer For printf("\n\n\tAfter Transpose the values of Matrix A are:\n\n"); printf("\tA(t) = "); for(i=0; i<r; i++){ for(j=0; j<c; j++){ printf("%d ", A[j][i]); } // end of inner For printf("\n\t "); } // end of outer For // Checking Symmetric Matrix for(i=0; i<r; i++){ for(j=0; j<c; j++) B[j][i]=A[i][j]; } // end of outer For for(i=0; i<r; i++){ for(j=0; j<c; j++){ if(B[i][j]==A[i][j]) ; else{ printf("\n\n\tA != A(Transpose)"); gotoxy(9,35); printf("=> This is not a Symmetric Matrix"); goto Label; } } // end of inner For printf("\n\t "); } // end of outer For printf("\n\n\t A = A(Transpose)"); printf("\n\n\t=> Hurrah! This is a Symmetric Matrix \x01"); } else{ gotoxy(25,25); printf("This is a non-Square Matrix"); } Label: gotoxy(25, 40); printf("Press any Key to go back!"); getche(); } // End of Symetric Method void showSkewSymetric (){ // SKEW SYMETRIC MATRIX start(); int A[3][3]={0, 1, 2, -1, 0, -3, -2, 3, 0}; int B[10][10]; int r, c; int i, j; gotoxy(25,8); printf("SKEW-SYMETRIC MATRIX\n\n"); printf("\n\nA Square Matrix is said to be Skew-Symmetric,\n\n"); printf("\n\n\t If A(transpose) = -A\n"); printf("\n\n\n\tLet A be any Matrix\n\n"); printf("\tA = "); for(i=0; i<3; i++){ for(j=0; j<3; j++){ printf("%d ", A[i][j]); } // end of inner For printf("\n\t "); } // end of outer For printf("\n\n\tTranspose of Matrix A will be\n\n"); printf("\tA = "); for(i=0; i<3; i++){ for(j=0; j<3; j++){ printf("%d ", A[j][i]); } // end of inner For printf("\n\t "); } // end of outer For printf("\n\n\tNow you can try! Press Enter...\n\n"); getch(); clrscr(); start(); printf("\n\n\tMatrix A"); printf("\n\nEnter No. of Rows: "); scanf("%d", &r); printf("\n\nEnter No. of Columns: "); scanf("%d", &c); if(r==c){ printf("\n\n\tA = "); for(i=0; i<r; i++) { for(j=0; j<c; j++){ scanf("%d", &A[i][j]); } // end of inner For printf("\n\t "); } // end of outer For printf("\n\n\tA(t) = "); for(i=0; i<r; i++) { for(j=0; j<c; j++){ printf("%d ", A[j][i]); } // end of inner For printf("\n\t "); } // end of outer For // performing Skew-Symmetric for(i=0; i<r; i++){ for(j=0; j<c; j++) B[i][j]=A[j][i]*-1; } // end of outer For // checking Skew-Symmetric for(i=0; i<r; i++){ for(j=0; j<c; j++){ if(B[i][j]==A[i][j]){ ; }else{ printf("\n\tA != - A(Transpose)\n\n"); printf("\n\t=> This is a non-Skew Symmetric Matrix"); goto Label; } } // end of inner For printf("\n\t "); } // end of outer For printf("\n\t A = - A(Transpose)"); printf("\n\t=> Hurrah! This is a Skew Symmetric Matrix \x01"); } else{ gotoxy(25,25); printf("This is a non-Square Matrix"); } Label: gotoxy(25,40); printf("Press any Key to go back!"); getche(); } // End of Skew-Symetric Method void showMatrixValidation () { // MATRIX VALIDATION start(); int A[10][10], B[10][10]; int r, c, r2, c2; int i, j; gotoxy(25,7); printf("VALIDATION MATRIX\n\n"); printf("\n\n\tEnter No. of Rows: "); scanf("%d", &r); printf("\n\tEnter No. of Columns: "); scanf("%d", &c); printf("\n\n\tEnter values for Matrix A in matrix order\n\n"); printf("\tA = "); for(i=0; i<r; i++){ for(j=0; j<c; j++) scanf("%d", &A[i][j]); printf("\n\t "); } // end of outer For clrscr(); start(); printf("\n\n\tThe values of Matrix A is:\n\n"); printf("\tA = "); for(i=0; i<r; i++){ // start of A for(j=0; j<c; j++) printf("%d ", A[i][j]); printf("\n\t "); } // End of A if (r==c){ // Checking Square Matrix printf("\n\n\tA is a Square Matrix\n\n"); // Checking Diagonal Matrix for(i=0; i<r; i++) for(j=0; j<c; j++){ if (i==j){ if(A[i][j]!=0) ; else{ printf("\n\n\tA is a Non-Diagonal Matrix\n\n"); goto Label2; } } else if(A[i][j]!=0){ printf("\n\n\tA is a Non-Diagonal Matrix\n\n"); goto Label2; } } printf("\n\n\tA is a Diagonal Matrix\n\n"); // Checking Scalar Diagonal for(i=0; i<r; i++) for(j=0; j<c; j++) { if (i==j){ if(A[i][j]==A[0][0]) ; else { printf("\n\n\tA is a non-Scalar Diagonal matrix.\n\n"); goto Label2; } } else if(A[i][j]!=0){ printf("\n\n\tA is a non-Diagonal matrix.\n\n"); goto Label2; } } printf("\n\n\tA is a Scalar Diagonal matrix.\n\n"); // Checking Unitary Diagonal for(i=0; i<r; i++) for(j=0; j<c; j++) { if (i==j){ if(A[i][j]==1) ; else{ printf("\n\n\tA is a non-Unitary Diagonal matrix.\n\n"); goto Label2; } } else if(A[i][j]!=0){ printf("\n\n\tA is a non-Diagonal matrix.\n\n"); goto Label2; } } printf("\n\n\tA is a Unitary Diagonal matrix.\n\n"); Label2: // Checking Symmetric Matrix for(i=0; i<r; i++){ for(j=0; j<c; j++){ B[j][i]=A[i][j]; } } for(i=0; i<r; i++){ for(j=0; j<c; j++){ if(B[i][j]==A[i][j]) ; else{ printf("\n\tA != A(Transpose)"); printf("\n => A is not a Symmetric Matrix"); goto Label3; } } printf("\n\t "); } printf("\n\n\tA = A(Transpose)"); printf("\n => A is a Symmetric Matrix\n\n"); Label3: // performing Skew-Symmetric for(i=0; i<r; i++){ for(j=0; j<c; j++) B[i][j]=A[j][i]*-1; } // checking Skew-Symmetric for(i=0; i<r; i++){ for(j=0; j<c; j++){ if(B[i][j]==A[i][j]){ ; } else{ printf("\n\n\tA != - A(Transpose)"); printf("\n => A is a non-Skew Symmetric Matrix"); goto Label; } } printf("\n\t "); } printf("\n\n\tA = - A(Transpose)"); printf("\n => A is a Skew Symmetric Matrix\n\n"); } // End of outer if else{ printf("\n\tA is a Rectangular Matrix\n\n"); printf("\n\tA is a Non-Diagonal Matrix\n\n"); printf("\n\tA is a non-Scalar Diagonal matrix.\n\n"); printf("\n\tA is a non-Unitary Diagonal matrix.\n\n"); printf("\n\tA != A(Transpose)"); printf("\n => A is not a Symmetric Matrix\n\n"); printf("\n\tA != -A(Transpose)"); printf("\n => A is not a Skew-Symmetric Matrix"); } Label: gotoxy(25,40); printf("Press any Key to go back!\n\n"); getche(); } // End of MatrixValidation Method
#define WIFI_RECONNECT_WAIT 20000 // in milliSeconds #define WIFI_AP_OFF_TIMER_DURATION 60000 // in milliSeconds #define WIFI_CONNECTION_CONSIDERED_STABLE 300000 // in milliSeconds #define WIFI_ALLOW_AP_AFTERBOOT_PERIOD 5 // in minutes #include "src/Globals/ESPEasyWiFiEvent.h" // ******************************************************************************** // WiFi state // ******************************************************************************** /* WiFi STA states: 1 STA off => ESPEASY_WIFI_DISCONNECTED 2 STA connecting 3 STA connected => ESPEASY_WIFI_CONNECTED 4 STA got IP => ESPEASY_WIFI_GOT_IP 5 STA connected && got IP => ESPEASY_WIFI_SERVICES_INITIALIZED N.B. the states are flags, meaning both "connected" and "got IP" must be set to be considered ESPEASY_WIFI_SERVICES_INITIALIZED The flag wifiConnectAttemptNeeded indicates whether a new connect attempt is needed. This is set to true when: - Security settings have been saved with AP mode enabled. FIXME TD-er, this may not be the best check. - WiFi connect timeout reached & No client is connected to the AP mode of the node. - Wifi is reset - WiFi setup page has been loaded with SSID/pass values. WiFi AP mode states: 1 AP on => reset AP disable timer 2 AP client connect/disconnect => reset AP disable timer 3 AP off => AP disable timer = 0; AP mode will be disabled when both apply: - AP disable timer (timerAPoff) expired - No client is connected to the AP. AP mode will be enabled when at least one applies: - No valid WiFi settings - Start AP timer (timerAPstart) expired Start AP timer is set or cleared at: - Set timerAPstart when "valid WiFi connection" state is observed. - Disable timerAPstart when ESPEASY_WIFI_SERVICES_INITIALIZED wifi state is reached. For the first attempt to connect after a cold boot (RTC values are 0), a WiFi scan will be performed to find the strongest known SSID. This will set RTC.lastBSSID and RTC.lastWiFiChannel Quick reconnect (using BSSID/channel of last connection) when both apply: - If wifi_connect_attempt < 3 - RTC.lastBSSID is known - RTC.lastWiFiChannel != 0 Change of wifi settings when both apply: - "other" settings valid - (wifi_connect_attempt % 2) == 0 Reset of wifi_connect_attempt to 0 when both apply: - connection successful - Connection stable (connected for > 5 minutes) */ // ******************************************************************************** // Check WiFi connected status // This is basically the state machine to switch between states: // - Initiate WiFi reconnect // - Start/stop of AP mode // ******************************************************************************** bool WiFiConnected() { START_TIMER; if (unprocessedWifiEvents()) { return false; } if ((timerAPstart != 0) && timeOutReached(timerAPstart)) { // Timer reached, so enable AP mode. setAP(true); timerAPstart = 0; } // For ESP82xx, do not rely on WiFi.status() with event based wifi. const bool validWiFi = (WiFi.RSSI() < 0) && WiFi.isConnected() && hasIPaddr(); if (wifiStatus != ESPEASY_WIFI_SERVICES_INITIALIZED) { if (validWiFi) { // Set internal wifiStatus and reset timer to disable AP mode markWiFi_services_initialized(); } } if (wifiStatus == ESPEASY_WIFI_SERVICES_INITIALIZED) { if (validWiFi) { // Connected, thus disable any timer to start AP mode. (except when in WiFi setup mode) if (!wifiSetupConnect) { timerAPstart = 0; } STOP_TIMER(WIFI_ISCONNECTED_STATS); return true; } // else wifiStatus is no longer in sync. addLog(LOG_LEVEL_INFO, F("WIFI : WiFiConnected() out of sync")); resetWiFi(); } // When made this far in the code, we apparently do not have valid WiFi connection. if (timerAPstart == 0) { // First run we do not have WiFi connection any more, set timer to start AP mode // Only allow the automatic AP mode in the first N minutes after boot. if ((wdcounter / 2) < WIFI_ALLOW_AP_AFTERBOOT_PERIOD) { timerAPstart = millis() + WIFI_RECONNECT_WAIT; timerAPoff = timerAPstart + WIFI_AP_OFF_TIMER_DURATION; } } if (wifiConnectTimeoutReached() && !wifiSetup) { // It took too long to make a connection, set flag we need to try again if (!wifiAPmodeActivelyUsed()) { wifiConnectAttemptNeeded = true; } wifiConnectInProgress = false; } delay(1); STOP_TIMER(WIFI_NOTCONNECTED_STATS); return false; } void WiFiConnectRelaxed() { if (!wifiConnectAttemptNeeded) { return; // already connected or connect attempt in progress need to disconnect first } if (!processedScanDone) { // Scan is still active, so do not yet connect. return; } // Start connect attempt now, so no longer needed to attempt new connection. wifiConnectAttemptNeeded = false; if (!prepareWiFi()) { addLog(LOG_LEVEL_ERROR, F("WIFI : Could not prepare WiFi!")); last_wifi_connect_attempt_moment = millis(); wifi_connect_attempt = 1; return; } if (wifiSetupConnect) { // wifiSetupConnect is when run from the setup page. RTC.lastWiFiSettingsIndex = 0; // Force to load the first settings. RTC.lastWiFiChannel = 0; // Force slow connect wifi_connect_attempt = 0; wifiSetupConnect = false; } // Switch between WiFi credentials if ((wifi_connect_attempt != 0) && ((wifi_connect_attempt % 2) == 0)) { if (selectNextWiFiSettings()) { // Switch WiFi settings, so the last known BSSID cannot be used for a quick reconnect. RTC.lastBSSID[0] = 0; } } const char *ssid = getLastWiFiSettingsSSID(); const char *passphrase = getLastWiFiSettingsPassphrase(); if (loglevelActiveFor(LOG_LEVEL_INFO)) { String log = F("WIFI : Connecting "); log += ssid; log += F(" attempt #"); log += wifi_connect_attempt; addLog(LOG_LEVEL_INFO, log); } setupStaticIPconfig(); setConnectionSpeed(); last_wifi_connect_attempt_moment = millis(); wifiConnectInProgress = true; // First try quick reconnect using last known BSSID and channel. bool useQuickConnect = RTC.lastBSSID[0] != 0 && RTC.lastWiFiChannel != 0 && wifi_connect_attempt < 3; if (useQuickConnect) { WiFi.begin(ssid, passphrase, RTC.lastWiFiChannel, &RTC.lastBSSID[0]); } else { WiFi.begin(ssid, passphrase); } ++wifi_connect_attempt; logConnectionStatus(); } // ******************************************************************************** // Set Wifi config // ******************************************************************************** bool prepareWiFi() { if (!selectValidWiFiSettings()) { addLog(LOG_LEVEL_ERROR, F("WIFI : No valid wifi settings")); // No need to wait longer to start AP mode. setAP(true); return false; } setSTA(true); char hostname[40]; safe_strncpy(hostname, WifiGetHostname().c_str(), sizeof(hostname)); #if defined(ESP8266) wifi_station_set_hostname(hostname); if (Settings.WifiNoneSleep()) { // Only set this mode during setup. // Reset to default power mode requires a reboot since setting it to WIFI_LIGHT_SLEEP will cause a crash. WiFi.setSleepMode(WIFI_NONE_SLEEP); } #endif // if defined(ESP8266) #if defined(ESP32) WiFi.setHostname(hostname); WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE); #endif // if defined(ESP32) if (RTC.lastWiFiChannel == 0 && wifi_connect_attempt <= 1) { WifiScan(true); } return true; } void resetWiFi() { addLog(LOG_LEVEL_INFO, F("Reset WiFi.")); lastDisconnectMoment = millis(); // Mark all flags to default to prevent handling old events. processedConnect = true; processedDisconnect = true; processedGotIP = true; processedDHCPTimeout = true; processedConnectAPmode = true; processedDisconnectAPmode = true; processedScanDone = true; wifiConnectAttemptNeeded = true; WifiDisconnect(); setWebserverRunning(false); // setWifiMode(WIFI_OFF); #ifdef ESP8266 // See https://github.com/esp8266/Arduino/issues/5527#issuecomment-460537616 WiFi.~ESP8266WiFiClass(); WiFi = ESP8266WiFiClass(); #endif // ifdef ESP8266 } // ******************************************************************************** // Disconnect from Wifi AP // ******************************************************************************** void WifiDisconnect() { #if defined(ESP32) WiFi.disconnect(); #else // if defined(ESP32) ETS_UART_INTR_DISABLE(); wifi_station_disconnect(); ETS_UART_INTR_ENABLE(); #endif // if defined(ESP32) wifiStatus = ESPEASY_WIFI_DISCONNECTED; processedDisconnect = false; } // ******************************************************************************** // Scan WiFi network // ******************************************************************************** void WifiScan(bool async, bool quick) { if (WiFi.scanComplete() == -1) { // Scan still busy return; } addLog(LOG_LEVEL_INFO, F("WIFI : Start network scan")); bool show_hidden = true; processedScanDone = false; lastGetScanMoment = millis(); if (quick) { #ifdef ESP8266 // Only scan a single channel if the RTC.lastWiFiChannel is known to speed up connection time. WiFi.scanNetworks(async, show_hidden, RTC.lastWiFiChannel); #else WiFi.scanNetworks(async, show_hidden); #endif } else { WiFi.scanNetworks(async, show_hidden); } } // ******************************************************************************** // Scan all Wifi Access Points // ******************************************************************************** void WifiScan() { // Direct Serial is allowed here, since this function will only be called from serial input. serialPrintln(F("WIFI : SSID Scan start")); WifiScan(false); const int8_t scanCompleteStatus = WiFi.scanComplete(); if (scanCompleteStatus <= 0) { serialPrintln(F("WIFI : No networks found")); } else { serialPrint(F("WIFI : ")); serialPrint(String(scanCompleteStatus)); serialPrintln(F(" networks found")); for (int i = 0; i < scanCompleteStatus; ++i) { // Print SSID and RSSI for each network found serialPrint(F("WIFI : ")); serialPrint(String(i + 1)); serialPrint(": "); serialPrintln(formatScanResult(i, " ")); delay(10); } } serialPrintln(""); } // ******************************************************************************** // Manage Wifi Modes // ******************************************************************************** void setSTA(bool enable) { switch (WiFi.getMode()) { case WIFI_OFF: if (enable) { setWifiMode(WIFI_STA); } break; case WIFI_STA: if (!enable) { setWifiMode(WIFI_OFF); } break; case WIFI_AP: if (enable) { setWifiMode(WIFI_AP_STA); } break; case WIFI_AP_STA: if (!enable) { setWifiMode(WIFI_AP); } break; default: break; } } void setAP(bool enable) { WiFiMode_t wifimode = WiFi.getMode(); switch (wifimode) { case WIFI_OFF: if (enable) { setWifiMode(WIFI_AP); } break; case WIFI_STA: if (enable) { setWifiMode(WIFI_AP_STA); } break; case WIFI_AP: if (!enable) { setWifiMode(WIFI_OFF); } break; case WIFI_AP_STA: if (!enable) { setWifiMode(WIFI_STA); } break; default: break; } } // Only internal scope void setAPinternal(bool enable) { if (enable) { // create and store unique AP SSID/PW to prevent ESP from starting AP mode with default SSID and No password! // setup ssid for AP Mode when needed String softAPSSID = WifiGetAPssid(); String pwd = SecuritySettings.WifiAPKey; IPAddress subnet(DEFAULT_AP_SUBNET); if (!WiFi.softAPConfig(apIP, apIP, subnet)) { addLog(LOG_LEVEL_ERROR, F("WIFI : [AP] softAPConfig failed!")); } if (WiFi.softAP(softAPSSID.c_str(), pwd.c_str())) { if (loglevelActiveFor(LOG_LEVEL_INFO)) { eventQueue.add(F("WiFi#APmodeEnabled")); String log(F("WIFI : AP Mode ssid will be ")); log += softAPSSID; log += F(" with address "); log += WiFi.softAPIP().toString(); addLog(LOG_LEVEL_INFO, log); } } else { if (loglevelActiveFor(LOG_LEVEL_ERROR)) { String log(F("WIFI : Error while starting AP Mode with SSID: ")); log += softAPSSID; log += F(" IP: "); log += apIP.toString(); addLog(LOG_LEVEL_ERROR, log); } } #ifdef ESP32 #else // ifdef ESP32 if (wifi_softap_dhcps_status() != DHCP_STARTED) { if (!wifi_softap_dhcps_start()) { addLog(LOG_LEVEL_ERROR, F("WIFI : [AP] wifi_softap_dhcps_start failed!")); } } #endif // ifdef ESP32 timerAPoff = millis() + WIFI_AP_OFF_TIMER_DURATION; } else { if (dnsServerActive) { dnsServerActive = false; dnsServer.stop(); } } } String getWifiModeString(WiFiMode_t wifimode) { switch (wifimode) { case WIFI_OFF: return F("OFF"); case WIFI_STA: return F("STA"); case WIFI_AP: return F("AP"); case WIFI_AP_STA: return F("AP+STA"); default: break; } return F("Unknown"); } void setWifiMode(WiFiMode_t wifimode) { const WiFiMode_t cur_mode = WiFi.getMode(); if (cur_mode == wifimode) { return; } if (wifimode != WIFI_OFF) { #ifdef ESP8266 // See: https://github.com/esp8266/Arduino/issues/6172#issuecomment-500457407 WiFi.forceSleepWake(); // Make sure WiFi is really active. #endif // ifdef ESP8266 delay(100); } addLog(LOG_LEVEL_INFO, String(F("WIFI : Set WiFi to ")) + getWifiModeString(wifimode)); int retry = 2; while (!WiFi.mode(wifimode) && retry > 0) { addLog(LOG_LEVEL_INFO, F("WIFI : Cannot set mode!!!!!")); delay(100); --retry; } if (wifimode == WIFI_OFF) { delay(1000); #ifdef ESP8266 WiFi.forceSleepBegin(); #endif // ifdef ESP8266 delay(1); } else { delay(30); // Must allow for some time to init. } bool new_mode_AP_enabled = WifiIsAP(wifimode); if (WifiIsAP(cur_mode) && !new_mode_AP_enabled) { eventQueue.add(F("WiFi#APmodeDisabled")); } if (WifiIsAP(cur_mode) != new_mode_AP_enabled) { // Mode has changed setAPinternal(new_mode_AP_enabled); } #ifdef FEATURE_MDNS MDNS.notifyAPChange(); #endif } bool WifiIsAP(WiFiMode_t wifimode) { #if defined(ESP32) return (wifimode == WIFI_MODE_AP) || (wifimode == WIFI_MODE_APSTA); #else // if defined(ESP32) return (wifimode == WIFI_AP) || (wifimode == WIFI_AP_STA); #endif // if defined(ESP32) } bool WifiIsSTA(WiFiMode_t wifimode) { #if defined(ESP32) return (wifimode & WIFI_MODE_STA) != 0; #else // if defined(ESP32) return (wifimode & WIFI_STA) != 0; #endif // if defined(ESP32) } // ******************************************************************************** // Determine Wifi AP name to set. (also used for mDNS) // ******************************************************************************** String WifiGetAPssid() { String ssid(Settings.Name); if (Settings.appendUnitToHostname()) { ssid += "_"; ssid += Settings.Unit; } return ssid; } // ******************************************************************************** // Determine hostname: basically WifiGetAPssid with spaces changed to - // ******************************************************************************** String WifiGetHostname() { String hostname(WifiGetAPssid()); hostname.replace(" ", "-"); hostname.replace("_", "-"); // See RFC952 return hostname; } bool useStaticIP() { return Settings.IP[0] != 0 && Settings.IP[0] != 255; } bool wifiConnectTimeoutReached() { // For the first attempt, do not wait to start connecting. if (wifi_connect_attempt == 0) { return true; } if (timeDiff(last_wifi_connect_attempt_moment, lastDisconnectMoment) > 0) { // Connection attempt was already ended. return true; } if (WifiIsAP(WiFi.getMode())) { // Initial setup of WiFi, may take much longer since accesspoint is still active. return timeOutReached(last_wifi_connect_attempt_moment + 20000); } // wait until it connects + add some device specific random offset to prevent // all nodes overloading the accesspoint when turning on at the same time. #if defined(ESP8266) const unsigned int randomOffset_in_msec = (wifi_connect_attempt == 1) ? 0 : 1000 * ((ESP.getChipId() & 0xF)); #endif // if defined(ESP8266) #if defined(ESP32) const unsigned int randomOffset_in_msec = (wifi_connect_attempt == 1) ? 0 : 1000 * ((ESP.getEfuseMac() & 0xF)); #endif // if defined(ESP32) return timeOutReached(last_wifi_connect_attempt_moment + DEFAULT_WIFI_CONNECTION_TIMEOUT + randomOffset_in_msec); } bool wifiAPmodeActivelyUsed() { if (!WifiIsAP(WiFi.getMode()) || (timerAPoff == 0)) { // AP not active or soon to be disabled in processDisableAPmode() return false; } return WiFi.softAPgetStationNum() != 0; // FIXME TD-er: is effectively checking for AP active enough or must really check for connected clients to prevent automatic wifi // reconnect? } void setConnectionSpeed() { #ifdef ESP8266 if (!Settings.ForceWiFi_bg_mode() || (wifi_connect_attempt > 10)) { WiFi.setPhyMode(WIFI_PHY_MODE_11N); } else { WiFi.setPhyMode(WIFI_PHY_MODE_11G); } #endif // ifdef ESP8266 // Does not (yet) work, so commented out. #ifdef ESP32 /* uint8_t protocol = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G; // Default to BG if (!Settings.ForceWiFi_bg_mode() || (wifi_connect_attempt > 10)) { // Set to use BGN protocol |= WIFI_PROTOCOL_11N; } if (WifiIsSTA(WiFi.getMode())) { esp_wifi_set_protocol(WIFI_IF_STA, protocol); } if (WifiIsAP(WiFi.getMode())) { esp_wifi_set_protocol(WIFI_IF_AP, protocol); } */ #endif // ifdef ESP32 } void setupStaticIPconfig() { setUseStaticIP(useStaticIP()); if (!useStaticIP()) { return; } const IPAddress ip = Settings.IP; const IPAddress gw = Settings.Gateway; const IPAddress subnet = Settings.Subnet; const IPAddress dns = Settings.DNS; if (loglevelActiveFor(LOG_LEVEL_INFO)) { String log = F("IP : Static IP : "); log += formatIP(ip); log += F(" GW: "); log += formatIP(gw); log += F(" SN: "); log += formatIP(subnet); log += F(" DNS: "); log += formatIP(dns); addLog(LOG_LEVEL_INFO, log); } WiFi.config(ip, gw, subnet, dns); } // ******************************************************************************** // Formatting WiFi related strings // ******************************************************************************** String formatScanResult(int i, const String& separator) { int32_t rssi = 0; return formatScanResult(i, separator, rssi); } String formatScanResult(int i, const String& separator, int32_t& rssi) { String result = WiFi.SSID(i); htmlEscape(result); #ifndef ESP32 if (WiFi.isHidden(i)) { result += F("#Hidden#"); } #endif // ifndef ESP32 rssi = WiFi.RSSI(i); result += separator; result += WiFi.BSSIDstr(i); result += separator; result += F("Ch:"); result += WiFi.channel(i); result += " ("; result += rssi; result += F("dBm) "); switch (WiFi.encryptionType(i)) { #ifdef ESP32 case WIFI_AUTH_OPEN: result += F("open"); break; case WIFI_AUTH_WEP: result += F("WEP"); break; case WIFI_AUTH_WPA_PSK: result += F("WPA/PSK"); break; case WIFI_AUTH_WPA2_PSK: result += F("WPA2/PSK"); break; case WIFI_AUTH_WPA_WPA2_PSK: result += F("WPA/WPA2/PSK"); break; case WIFI_AUTH_WPA2_ENTERPRISE: result += F("WPA2 Enterprise"); break; #else // ifdef ESP32 case ENC_TYPE_WEP: result += F("WEP"); break; case ENC_TYPE_TKIP: result += F("WPA/PSK"); break; case ENC_TYPE_CCMP: result += F("WPA2/PSK"); break; case ENC_TYPE_NONE: result += F("open"); break; case ENC_TYPE_AUTO: result += F("WPA/WPA2/PSK"); break; #endif // ifdef ESP32 default: break; } return result; } #ifndef ESP32 String SDKwifiStatusToString(uint8_t sdk_wifistatus) { switch (sdk_wifistatus) { case STATION_IDLE: return F("STATION_IDLE"); case STATION_CONNECTING: return F("STATION_CONNECTING"); case STATION_WRONG_PASSWORD: return F("STATION_WRONG_PASSWORD"); case STATION_NO_AP_FOUND: return F("STATION_NO_AP_FOUND"); case STATION_CONNECT_FAIL: return F("STATION_CONNECT_FAIL"); case STATION_GOT_IP: return F("STATION_GOT_IP"); } return getUnknownString(); } #endif // ifndef ESP32 String ArduinoWifiStatusToString(uint8_t arduino_corelib_wifistatus) { String log; switch (arduino_corelib_wifistatus) { case WL_IDLE_STATUS: log += F("WL_IDLE_STATUS"); break; case WL_NO_SSID_AVAIL: log += F("WL_NO_SSID_AVAIL"); break; case WL_SCAN_COMPLETED: log += F("WL_SCAN_COMPLETED"); break; case WL_CONNECTED: log += F("WL_CONNECTED"); break; case WL_CONNECT_FAILED: log += F("WL_CONNECT_FAILED"); break; case WL_CONNECTION_LOST: log += F("WL_CONNECTION_LOST"); break; case WL_DISCONNECTED: log += F("WL_DISCONNECTED"); break; default: log += arduino_corelib_wifistatus; break; } return log; } String ESPeasyWifiStatusToString() { String log; switch (wifiStatus) { case ESPEASY_WIFI_DISCONNECTED: log += F("ESPEASY_WIFI_DISCONNECTED"); break; case ESPEASY_WIFI_CONNECTED: log += F("ESPEASY_WIFI_CONNECTED"); break; case ESPEASY_WIFI_GOT_IP: log += F("ESPEASY_WIFI_GOT_IP"); break; case ESPEASY_WIFI_SERVICES_INITIALIZED: log += F("ESPEASY_WIFI_SERVICES_INITIALIZED"); break; default: log += wifiStatus; } return log; } void logConnectionStatus() { #ifndef ESP32 const uint8_t arduino_corelib_wifistatus = WiFi.status(); const uint8_t sdk_wifistatus = wifi_station_get_connect_status(); if ((arduino_corelib_wifistatus == WL_CONNECTED) != (sdk_wifistatus == STATION_GOT_IP)) { if (loglevelActiveFor(LOG_LEVEL_ERROR)) { String log = F("WIFI : SDK station status differs from Arduino status. SDK-status: "); log += SDKwifiStatusToString(sdk_wifistatus); log += F(" Arduino status: "); log += ArduinoWifiStatusToString(arduino_corelib_wifistatus); addLog(LOG_LEVEL_ERROR, log); } } #endif // ifndef ESP32 #ifndef BUILD_NO_DEBUG if (loglevelActiveFor(LOG_LEVEL_DEBUG_MORE)) { String log = F("WIFI : Arduino wifi status: "); log += ArduinoWifiStatusToString(WiFi.status()); log += F(" ESPeasy internal wifi status: "); log += ESPeasyWifiStatusToString(); addLog(LOG_LEVEL_DEBUG_MORE, log); } if (loglevelActiveFor(LOG_LEVEL_INFO)) { String log; switch (WiFi.status()) { case WL_NO_SSID_AVAIL: { log = F("WIFI : No SSID found matching: "); break; } case WL_CONNECT_FAILED: { log = F("WIFI : Connection failed to: "); break; } case WL_DISCONNECTED: { log = F("WIFI : WiFi.status() = WL_DISCONNECTED SSID: "); break; } case WL_IDLE_STATUS: { log = F("WIFI : Connection in IDLE state: "); break; } case WL_CONNECTED: { break; } default: break; } if (log.length() > 0) { const char *ssid = getLastWiFiSettingsSSID(); log += ssid; addLog(LOG_LEVEL_INFO, log); } } #endif // ifndef BUILD_NO_DEBUG } String getLastDisconnectReason() { String reason = "("; reason += lastDisconnectReason; reason += F(") "); switch (lastDisconnectReason) { case WIFI_DISCONNECT_REASON_UNSPECIFIED: reason += F("Unspecified"); break; case WIFI_DISCONNECT_REASON_AUTH_EXPIRE: reason += F("Auth expire"); break; case WIFI_DISCONNECT_REASON_AUTH_LEAVE: reason += F("Auth leave"); break; case WIFI_DISCONNECT_REASON_ASSOC_EXPIRE: reason += F("Assoc expire"); break; case WIFI_DISCONNECT_REASON_ASSOC_TOOMANY: reason += F("Assoc toomany"); break; case WIFI_DISCONNECT_REASON_NOT_AUTHED: reason += F("Not authed"); break; case WIFI_DISCONNECT_REASON_NOT_ASSOCED: reason += F("Not assoced"); break; case WIFI_DISCONNECT_REASON_ASSOC_LEAVE: reason += F("Assoc leave"); break; case WIFI_DISCONNECT_REASON_ASSOC_NOT_AUTHED: reason += F("Assoc not authed"); break; case WIFI_DISCONNECT_REASON_DISASSOC_PWRCAP_BAD: reason += F("Disassoc pwrcap bad"); break; case WIFI_DISCONNECT_REASON_DISASSOC_SUPCHAN_BAD: reason += F("Disassoc supchan bad"); break; case WIFI_DISCONNECT_REASON_IE_INVALID: reason += F("IE invalid"); break; case WIFI_DISCONNECT_REASON_MIC_FAILURE: reason += F("Mic failure"); break; case WIFI_DISCONNECT_REASON_4WAY_HANDSHAKE_TIMEOUT: reason += F("4way handshake timeout"); break; case WIFI_DISCONNECT_REASON_GROUP_KEY_UPDATE_TIMEOUT: reason += F("Group key update timeout"); break; case WIFI_DISCONNECT_REASON_IE_IN_4WAY_DIFFERS: reason += F("IE in 4way differs"); break; case WIFI_DISCONNECT_REASON_GROUP_CIPHER_INVALID: reason += F("Group cipher invalid"); break; case WIFI_DISCONNECT_REASON_PAIRWISE_CIPHER_INVALID: reason += F("Pairwise cipher invalid"); break; case WIFI_DISCONNECT_REASON_AKMP_INVALID: reason += F("AKMP invalid"); break; case WIFI_DISCONNECT_REASON_UNSUPP_RSN_IE_VERSION: reason += F("Unsupp RSN IE version"); break; case WIFI_DISCONNECT_REASON_INVALID_RSN_IE_CAP: reason += F("Invalid RSN IE cap"); break; case WIFI_DISCONNECT_REASON_802_1X_AUTH_FAILED: reason += F("802 1X auth failed"); break; case WIFI_DISCONNECT_REASON_CIPHER_SUITE_REJECTED: reason += F("Cipher suite rejected"); break; case WIFI_DISCONNECT_REASON_BEACON_TIMEOUT: reason += F("Beacon timeout"); break; case WIFI_DISCONNECT_REASON_NO_AP_FOUND: reason += F("No AP found"); break; case WIFI_DISCONNECT_REASON_AUTH_FAIL: reason += F("Auth fail"); break; case WIFI_DISCONNECT_REASON_ASSOC_FAIL: reason += F("Assoc fail"); break; case WIFI_DISCONNECT_REASON_HANDSHAKE_TIMEOUT: reason += F("Handshake timeout"); break; default: reason += getUnknownString(); break; } return reason; }
#include <iostream> #include <stdio.h> #include <cstdlib> #include <unistd.h> #include <time.h> #include <string.h> #include <string> #include <sstream> #include <vector> #include "ros/ros.h" #include "image_transport/image_transport.h" #include "cv_bridge/cv_bridge.h" #include "sensor_msgs/image_encodings.h" #include "sensor_msgs/Image.h" #include <opencv2/opencv.hpp> #include <decoder_h264/decoder_h264_node.hpp> #include <decoder_h264/H264Decoder.h> using namespace std; Mat g_frame; int g_lPort = 0; char* g_rgbBuffer = NULL; unsigned char* g_yuvBuffer = NULL; unsigned int g_len = 0; std::string g_error_info_str; long lUserID; long lRealPlayHandle; int flag = 0; cv::Mat g_result_pic; int g_get_image = 0; H264Decoder h264_decoder; void *display_image(void* args) { while(true) { if(g_get_image == 1) { try{ g_get_image = 0; cv::imshow("img", g_result_pic); cv::waitKey(30); } catch(const std::exception& e){ std::cerr << e.what() << '\n'; } } } } void decoder_h264_node::getstream_callback(const sensor_msgs::Image& msg) { vector<unsigned char> vc; vc = msg.data; //for (int n=0;n<4;n++) // printf(" 0x%02x\t%02x\n",vc[n],vc[n]); //std::cout << "strlen(pBuf):" << vc.size() << std::endl; unsigned char* pBuffer = &vc.at(0); int dwBufSize = vc.size(); //for (int n=0;n<4;n++) // printf(" 0x%02x\t%02x\n",vc[n],vc[n]); //std::cout << "strlen(pBuf):" << vc.size() << std::endl; for (int n=0;n<4;n++) //printf(" %02x ", pBuffer[n]); printf(" 0x%02x\t%02x\n",pBuffer+n,pBuffer[n]); std::cout << "strlen(pBuffer):" << dwBufSize << std::endl; //PS流数据解析处理 int nI = 0; int nCacheSize = 0; nI = m_mFrameCacheLenth; //直接--提取H264数据 bool bVideo = false; bool bPatialData = false; bPatialData = get_h246_fromps(pBuffer,dwBufSize, &m_pFrameCache[nI].pCacheBuffer, m_pFrameCache[nI].nCacheBufLenth, bVideo); if (bVideo) { if (bPatialData)//部分包数据 { //缓存数据 m_pFrameCache[nI].lTimeStamp = clock(); m_mFrameCacheLenth++; } else//包头 { int i = 0; if(m_mFrameCacheLenth>0) { long lH264DataLenth = m_mFrameCacheLenth*MAX_PACK_SIZE; BYTE* pH264Nal = NULL; pH264Nal = new BYTE[lH264DataLenth]; memset(pH264Nal, 0x00, lH264DataLenth); BYTE* pTempBuffer = pH264Nal; int nTempBufLenth = 0; for (i=0; i < m_mFrameCacheLenth; i++) { if(m_pFrameCache[i].pCacheBuffer!=NULL&&m_pFrameCache[i].nCacheBufLenth>0) { memcpy(pH264Nal+nTempBufLenth, m_pFrameCache[i].pCacheBuffer, m_pFrameCache[i].nCacheBufLenth); nTempBufLenth += m_pFrameCache[i].nCacheBufLenth; } if (m_pFrameCache[i].pCacheBuffer) { delete [](m_pFrameCache[i].pCacheBuffer); m_pFrameCache[i].pCacheBuffer = NULL; } m_pFrameCache[i].nCacheBufLenth = 0; } if (pH264Nal && nTempBufLenth>0) { bool bIsKeyFrame = false; //查找是否为关键帧 if(pH264Nal[4]==0x67) { bIsKeyFrame = true; } long lTimeStamp = clock(); try { if(pH264Nal[4] == 0x67) { printf("nTempBufLenth = %d ",nTempBufLenth); h264_decoder.decode(pH264Nal, nTempBufLenth); g_result_pic = h264_decoder.getMat(); g_get_image = 1; } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; } } if (pH264Nal) { delete []pH264Nal; pH264Nal = NULL; } // 缓存数据个数 清0 m_mFrameCacheLenth = 0; } } } } decoder_h264_node::decoder_h264_node() { ros::NodeHandle private_node_handle("~"); ros::NodeHandle node_handle_; heartbeat_pub_ = node_handle_.advertise<diagnostic_msgs::DiagnosticArray>("/decoder_h264/heartbeat", 1); getstream_sub_ = node_handle_.subscribe("/yida/internal/visible/image_proc", 1000, &decoder_h264_node::getstream_callback, this); for (int i = 0; i < MAX_DEV+1; i++) { if(i < MAX_DEV) { for(int nI=0; nI < MAX_FRAME_LENTH; nI++) { memset(&m_pFrameCache[nI], 0x00, sizeof(CacheBuffder)); } m_mFrameCacheLenth = 0; } } create_display_thread(); } decoder_h264_node::~decoder_h264_node() { } void decoder_h264_node::create_display_thread() { pthread_t ros_thread_display = 0; pthread_create(&ros_thread_display,NULL,display_image,NULL); } //从PS流中取H264数据 //返回值:是否为数据包 bool decoder_h264_node::get_h246_fromps(BYTE* pBuffer, int nBufLenth, BYTE** pH264, int& nH264Lenth, bool& bVideo) { if (!pBuffer || nBufLenth<=0) { return false; } BYTE* pH264Buffer = NULL; int nHerderLen = 0; if( pBuffer && pBuffer[0]==0x00 && pBuffer[1]==0x00 && pBuffer[2]==0x01 && pBuffer[3]==0xE0) //E==视频数据(此处E0标识为视频) { bVideo = true; nHerderLen = 9 + (int)pBuffer[8];//9个为固定的数据包头长度,pBuffer[8]为填充头部分的长度 pH264Buffer = pBuffer+nHerderLen; if (*pH264 == NULL) { *pH264 = new BYTE[nBufLenth]; } if (*pH264&&pH264Buffer&&(nBufLenth-nHerderLen)>0) { memcpy(*pH264, pH264Buffer, (nBufLenth-nHerderLen)); } nH264Lenth = nBufLenth-nHerderLen; return true; } else if(pBuffer && pBuffer[0]==0x00 && pBuffer[1]==0x00 && pBuffer[2]==0x01 && pBuffer[3]==0xC0) //C==音频数据? { *pH264 = NULL; nH264Lenth = 0; bVideo = false; } else if(pBuffer && pBuffer[0]==0x00 && pBuffer[1]==0x00 && pBuffer[2]==0x01 && pBuffer[3]==0xBA) //视频流数据包 包头 { bVideo = true; *pH264 = NULL; nH264Lenth = 0; return false; } return false; } void decoder_h264_node::update() { //if(g_frame.empty()) /*if(g_len == 0) { int level = 2; std::string message = g_error_info_str; std::string hardware_id = "visible_camera"; pub_heartbeat(level, message, hardware_id); } else { int level = 0; std::string message = "visible camera is ok!"; std::string hardware_id = "visible_camera_getstream"; pub_heartbeat(level, message, hardware_id); }*/ } void decoder_h264_node::pub_heartbeat(int level, string message, string hardware_id) { diagnostic_msgs::DiagnosticArray log; log.header.stamp = ros::Time::now(); diagnostic_msgs::DiagnosticStatus s; s.name = __app_name__; // 这里写节点的名字 s.level = level; // 0 = OK, 1 = Warn, 2 = Error if (!message.empty()) { s.message = message; // 问题描述 } s.hardware_id = hardware_id; // 硬件信息 log.status.push_back(s); heartbeat_pub_.publish(log); } int main(int argc, char **argv) { ros::init(argc, argv, __app_name__); decoder_h264_node hsdkcap; ros::Rate rate(40); while (ros::ok()) { hsdkcap.update(); ros::spinOnce(); rate.sleep(); } return 0; }
#include "qn_optimizer/qn_optimizer.h" #include <iostream> // TUNABLE PARAMETERS const double min_a = -4.75; const double min_b = 2.0; const double initial_guess_a = 0.0; const double initial_guess_b = 0.0; double objective_function(const Eigen::VectorXd& variables) { return std::pow(variables(0) - min_a, 2.0) + std::pow(variables(1) - min_b, 2.0); } void objective_gradient(const Eigen::VectorXd& operating_point, Eigen::VectorXd& gradient) { gradient(0) = 2*(operating_point(0) - min_a); gradient(1) = 2*(operating_point(1) - min_b); } int32_t main(int32_t argc, char** argv) { //qn_optimizer qno(2, &objective_function); qn_optimizer qno(2, &objective_function, &objective_gradient); // Set up the variable vector and insert initial guess. Eigen::VectorXd variables; variables.setZero(2); variables(0) = initial_guess_a; variables(1) = initial_guess_b; // Run optimization. double score; bool result = qno.optimize(variables, &score); // Display result. if(result) { std::cout << "minimized value: " << std::endl << variables << std::endl; } else { std::cout << "optimization failed" << std::endl; } // Display number of iterations. auto iterations = qno.iterations(); std::cout << "total iterations: " << iterations.size() << std::endl; for(auto iteration = iterations.cbegin(); iteration != iterations.cend(); ++iteration) { std::cout << *iteration << std::endl; } }
/* * Copyright (C) 2013 Tom Wong. All rights reserved. */ #include "gtdocnote.h" #include "gtdocmessage.pb.h" #include "gtserialize.h" #include <QtCore/QDebug> GT_BEGIN_NAMESPACE GtDocNote::GtDocNote(NoteType type, const GtDocRange &range) : m_type(type) , m_range(range) { Q_ASSERT(isValid()); } GtDocNote::~GtDocNote() { } void GtDocNote::setRange(const GtDocRange &range) { m_range = range; Q_ASSERT(isValid()); } bool GtDocNote::isValid() const { if (m_range.type() == GtDocRange::UnknownRange) return false; if (Underline == m_type) return (m_range.type() == GtDocRange::TextRange); return true; } void GtDocNote::serialize(GtDocNoteMsg &msg) const { msg.set_type(m_type); m_range.serialize(*msg.mutable_range()); } bool GtDocNote::deserialize(const GtDocNoteMsg &msg) { switch (msg.type()) { case GtDocNote::Highlight: case GtDocNote::Underline: m_type = (GtDocNote::NoteType)msg.type(); return m_range.deserialize(msg.range()); default: break; } return false; } #ifndef QT_NO_DATASTREAM QDataStream &operator<<(QDataStream &s, const GtDocNote &n) { return GtSerialize::serialize<GtDocNote, GtDocNoteMsg>(s, n); } QDataStream &operator>>(QDataStream &s, GtDocNote &n) { return GtSerialize::deserialize<GtDocNote, GtDocNoteMsg>(s, n); } #endif // QT_NO_DATASTREAM GT_END_NAMESPACE
/* Q. Create class MyString which contains character pointer (use new operator) Write a C++ program to overload following operators 1. To change case of each alphabet from given string 2. To print characte present at specified index */ #include<iostream> #include<stdlib.h> #include<string.h> #include<ctype.h> using namespace std; class MyString{ private: char *stringContent; public: MyString() { stringContent = new char[10]; strcpy(this->stringContent,"NA"); } MyString(char stringContent[20]) { int length = strlen(stringContent); this->stringContent = new char[length+1]; strcpy(this->stringContent,stringContent); } void operator ! () { int length = strlen(this->stringContent); int i; for(i=0;i<length;i++) { if(this->stringContent[i]>=65 && this->stringContent[i]<=90) this->stringContent[i] = tolower(this->stringContent[i]); else if(this->stringContent[i]>=97 && this->stringContent[i]<=122) this->stringContent[i] = toupper(this->stringContent[i]); } } void operator [](int index) { if(index>strlen(this->stringContent)) cout<<"Invalid Index"<<endl; else cout<<"Element at index: "<<index<<" is:"<<this->stringContent[index]<<endl; } void display() { cout<<"Content of String:"<<this->stringContent<<endl; } }; int main() { char string[50]; cout<<"Enter the String:"<<endl; cin>>string; MyString object(string); object.display(); !(object); object.display(); int index; cout<<"Enter the Position:"<<endl; cin>>index; object[index]; return 0; }
/************************************************************************/ /* 字符串移动(字符串为*号和 26 个字母的任意组合,把*号都移动到最左侧,把 字母移到最右侧并保持相对顺序不变),要求时间和空间复杂度最小 */ /************************************************************************/ #include <iostream> #include <string> #include <algorithm> using namespace std; class Solution{ public: void ReorderString(string &str){ int j = str.size() - 1; for(;j >= 0; --j){ if(str[j] == '*'){ break; } } for(int i = j; i >= 0; --i){ if(str[i] != '*'){ if(j != i){ swap(str[i], str[j]); if(j - 1 != i){ --j; } else{ j = i; } } } } } }; //int main(){ // string str("d**a***f**afa***"); // Solution solution; // solution.ReorderString(str); // return 0; //}
#include "Bank.h" // Lalalalalalalalala
#include "Item.h" Item::Item() { } void Item::Update() { } void Item::Draw() { } Item::~Item() { }
#define BREADBOARD //#define BUILD_ONE // master bedroom //#define BUILD_TWO // gameroom // breadboard with a wemos, and nothing else //#define WEMOS /* * module is a WeMos D1 R1 * flash size set to 4M (1M SPIFFS) or 4MB (FS:1MB OTA:~1019KB) (latest esp board sw uses this) * OR * module is a esp12e * flash size set to 4M (1M SPIFFS) or 4MB (FS:1MB OTA:~1019KB) (latest esp board sw uses this) * OR * module is a esp7 * flash size set to 1M (128KB SPIFFS) or 1MB (FS:128KB OTA:~438KB) (latest esp board sw uses this) * if this enough to do ota? (esp-07s has 4MB of memory..have a few of these) */ #ifdef BREADBOARD #define DISPLAY_22 #endif #ifdef BUILD_ONE #define LATCH_RELAYS #define DISPLAY_14 #endif #ifdef BUILD_TWO #define DISPLAY_18 #endif /* * todo: * tested with wemos and 1.8" display * tested with wemos and 2.2" display * button screen working with larger displays * * not tested with esp12 and 2.2" display * not tested with esp12 and 1.4" display * * * does the time flash mess up the wifi? * * * * * motion sensor seems very flaky (use 5v?) * test button screen with small displays * * fix degree in font file for small font (for outside temp) (optional) */ /* * library sources: * ESP8266WiFi, ESP8266WebServer, FS, DNSServer, Hash, EEPROM, ArduinoOTA - https://github.com/esp8266/Arduino * WebSocketsServer - https://github.com/Links2004/arduinoWebSockets (git) * WiFiManager - https://github.com/tzapu/WiFiManager (git) * ESPAsyncTCP - https://github.com/me-no-dev/ESPAsyncTCP (git) * ESPAsyncUDP - https://github.com/me-no-dev/ESPAsyncUDP (git) * PubSub - https://github.com/knolleary/pubsubclient (git) * TimeLib - https://github.com/PaulStoffregen/Time (git) * Timezone - https://github.com/JChristensen/Timezone (git) * ArduinoJson - https://github.com/bblanchon/ArduinoJson (git) * Adafruit_GFX.h - https://github.com/adafruit/Adafruit-GFX-Library (git) * Adafruit_ILI9341 - https://github.com/adafruit/Adafruit_ILI9341 (git) * TFT_ILI9163C.h - https://github.com/PaulStoffregen/TFT_ILI9163C * Adafruit_ST7735.h - https://github.com/adafruit/Adafruit-ST7735-Library */ /* * if LATCH_RELAYS is defined, the thermostat is using latch relays to drive the compressor, fan, and reversing valve * latch relays need a short pulse to turn them on or off * 3 gpios are used to turn each item on, 1 gpio is used to turn them all off * * if it isn't defined, then the thermostat is using either relays or thristors for control * 3 gpios are used, and the state must be left on to turn the item on */ //#define LATCH_RELAYS /* * if DISPLAY_14 is defined, the 1.4" 128x128 tft ILI9163C display is used * if DISPLAY_18 is defined, the 1.8" 128x160 tft ST7735 display is used * if DISPLAY_22 is defined, the 2.2" 240x320 tft ILI9340 display is used (uses the ILI9341 library) * if DISPLAY_28 is defined, the 2.8" 240x320 tft ILI9341 display is used * this display has a touch screen, but it doesn't seem to be very good. * we're not using the extra space on the taller display, just centering what we have on it. */ //#define DISPLAY_14 //#define DISPLAY_18 //#define DISPLAY_22 //#define DISPLAY_28 #include <ESP8266WiFi.h> #include <WebSocketsServer.h> #include <Hash.h> #include <TimeLib.h> #include <Timezone.h> //US Eastern Time Zone (New York, Detroit) TimeChangeRule myDST = {"EDT", Second, Sun, Mar, 2, -240}; //Daylight time = UTC - 4 hours TimeChangeRule mySTD = {"EST", First, Sun, Nov, 2, -300}; //Standard time = UTC - 5 hours Timezone myTZ(myDST, mySTD); // -------------------------------------------- // web server library includes #include <ESP8266WebServer.h> #include <ArduinoJson.h> #include <EEPROM.h> // -------------------------------------------- // file system (spiffs) library includes #include <FS.h> // -------------------------------------------- // wifi manager library includes #include <DNSServer.h> #include <WiFiManager.h> WiFiManager wifiManager; String ssid; // -------------------------------------------- // aync library includes #include <ESPAsyncTCP.h> #include <ESPAsyncUDP.h> // -------------------------------------------- // mqtt library includes #include <PubSubClient.h> // -------------------------------------------- // arduino ota library includes #include <ArduinoOTA.h> #include <WiFiClient.h> #include <ESP8266mDNS.h> #include <ESP8266HTTPUpdateServer.h> ESP8266HTTPUpdateServer httpUpdater; // -------------------------------------------- #include <Wire.h> // -------------------------------------------- const char *weekdayNames[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; // -------------------------------------------- #include <SPI.h> #include <Adafruit_GFX.h> #ifdef DISPLAY_14 #include <TFT_ILI9163C.h> #define GREEN 0x07E0 #define RED 0xF800 #define WIDTH 128 #define HEIGHT 128 #endif #ifdef DISPLAY_18 #include <Adafruit_ST7735.h> #define BLACK ST7735_BLACK #define GREEN ST7735_GREEN #define RED ST7735_RED #define WIDTH 128 #define HEIGHT 160 #endif #ifdef DISPLAY_22 #include <Adafruit_ILI9341.h> #define BLACK ILI9341_BLACK #define GREEN ILI9341_GREEN #define RED ILI9341_RED #define WIDTH 240 #define HEIGHT 320 #endif #ifdef DISPLAY_28 #include <Adafruit_ILI9341.h> #define BLACK ILI9341_BLACK #define GREEN ILI9341_GREEN #define RED ILI9341_RED #define WIDTH 240 #define HEIGHT 320 #endif #define ERASE BLACK //#define ERASE RED #if defined DISPLAY_22 || defined DISPLAY_28 // these fonts work well on the larger displays #include <Fonts/arial20pt7b.h> #include <Fonts/arial30pt7b-final.h> // numbers only with degree symbol #else // these fonts work well on the smaller displays #include <Fonts/arial12pt7b.h> #include <Fonts/arial18pt7b-final.h> // numbers only with degree symbol #endif const GFXfont *font_set[3]; int font_height[3]; // -------------------------------------------- // temperature sensor includes #include <OneWire.h> #include <DallasTemperature.h> // -------------------------------------------- #define WU_API_KEY "1a4e9749a84f549f" // thermostat key //#define WU_LOCATION "34241" #define WU_LOCATION "pws:MD0683" // weather station in serenoa #define WUNDERGROUND "api.wunderground.com" const char WUNDERGROUND_REQ1[] = "GET /api/"; const char WUNDERGROUND_REQ2[] = "/conditions/q/"; const char WUNDERGROUND_REQ3[] = ".json HTTP/1.1\r\n" "User-Agent: ESP8266/0.1\r\n" "Accept: */*\r\n" "Host: " WUNDERGROUND "\r\n" "Connection: close\r\n" "\r\n"; #define TEMP_IP_ADDR "192.168.1.16" #define TEMP_IP_PORT 9090 #define TEMP_ERROR -999 // -------------------------------------------- /* * esp-12 pin usage: * gpio5 - spi - d/c * gpio4 - 1-wire - temp sensor * gpio0 - i2c - sda * gpio2 - i2c - scl * gpio15 - spi - cd * gpio16 - relays reset * gpio14 - spi - sck * gpio12 - spi - miso (not used) * gpio13 - spi - mosi * * mux usage: * 0 - up button * 1 - enter button * 2 - down button * 3 - reversing valve relay * 4 - fan relay * 5 - compressor relay * 6 - display backlight led * 7 - motion sensor * int - not used */ // esp8266 i2c mux #define SDA 0 #define SCL 2 #ifdef BREADBOARD #define MUX 0x24 // mux board with switch 1 to on, 2&3 to off #else #ifdef BUILD_ONE // 1st gen thermostat uses the a version // using the PCF8674A which has a fixed address of 111. // 00111000 #define MUX 0x38 // PCF8574A, A0, A1, and A2 to GND #endif #ifdef BUILD_TWO // 2nd gen thermostat uses the normal version // using the PCF8574 which has a fixed address of 100. // 00100000 #define MUX 0x20 // PCF8574, A0, A1, and A2 to GND #endif #endif byte muxState; // hardware SPI pins #define __CS 15 #define __DC 5 // MOSI(SDA) 13 // RST wired to VCC // SCLK(SCK) 14 // MISO 12 // connected via the i2c mux #define LED B01000000 #ifdef DISPLAY_14 TFT_ILI9163C display = TFT_ILI9163C(__CS, __DC); #endif #ifdef DISPLAY_18 Adafruit_ST7735 display = Adafruit_ST7735(__CS, __DC, -1); #endif #ifdef DISPLAY_22 Adafruit_ILI9341 display = Adafruit_ILI9341(__CS, __DC, -1); #endif #ifdef DISPLAY_28 Adafruit_ILI9341 display = Adafruit_ILI9341(__CS, __DC); #endif // -------------------------------------------- // gpio 4 is available on the esp-12, but it blinks the blue led when used....weird // so use gpio16 instead...tried this, and didn't work...is gpio 1 not usable? #define ONE_WIRE_BUS 4 // D2 on wemos #define TimeBetweenMotionChecks 1000 #define MenuIdleTime 10000 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); // Pass our oneWire reference to Dallas Temperature. DallasTemperature sensors(&oneWire); // device address DeviceAddress thermometer1; DeviceAddress thermometer2; int numDevices; #define resolution 12 int lastTargetTemperature = TEMP_ERROR; bool isTargetCool; float lastTemp; float lastOutsideTemp = TEMP_ERROR; unsigned long lastMotionReadTime; unsigned long lastButtonPressTime; int targetCoolTemp; int targetHeatTemp; boolean isForcePrint = false; bool isDisplayOn; byte last_p_program = 0; byte last_p_time = 0; // size of the timeout line int lastPx; // -------------------------------------------- // these relays are connected thru a i2c mux #define FAN_PIN B00010000 #define COMPRESSOR_PIN B00100000 #define REVERSING_VALVE_PIN B00001000 #ifdef LATCH_RELAYS #define RESET_PIN 16 // not on the mux #endif #define FAN 0 #define COMPRESSOR 1 #define REVERSING_VALVE 2 const int relayPins[] = {FAN_PIN, COMPRESSOR_PIN, REVERSING_VALVE_PIN}; // -------------------------------------------- // these buttons are connected thru a i2c mux #define UP B00000001 #define ENTER B00000010 #define DOWN B00000100 const int buttonPins[] = {UP, ENTER, DOWN}; const int defaultButtonState = LOW; int numButtons; int *buttonStates; int *lastButtonStates; // the following variables are long's because the time, measured in miliseconds, // will quickly become a bigger number than can be stored in an int. long *lastDebounceTimes; // the last time the output pin was toggled const long debounceDelay = 50; // the debounce time // -------------------------------------------- // the motion sensor module was modified to bypass the 3.3v regulator // since we're providing it 3.3v already, it wouldn't work. // an extra wire was soldered from VCC to the reguator output // the difusing window was also removed since we're not interested in wide // angle motion #define MOTION B10000000 // -------------------------------------------- bool isSetup = false; bool isTempSetup = false; #define OFF 0 #define ON 1 #define TEMP 2 #define HOLD 3 const char *modeNames[] = { "OFF", "ON", "TEMP", "HOLD" }; #define COOL 0 #define HEAT 1 const char *modeStateNames[] = { "Cool", "Heat" }; byte mode; #define AUTO 0 const char *fanNames[] = { "Auto", "On" }; // actions #define SYSTEM_OFF 'o' #define SYSTEM_FAN 'f' #define SYSTEM_HEAT 'h' #define SYSTEM_COOL 'c' bool isFanOn; bool isCompressorOn; bool isReversingValueOn; enum screenState { MAIN, MENU }; screenState screen; int selectedMenuItem; unsigned long lastMinutes; unsigned long lastSeconds; #define MODE_BUTTON 0 #define FAN_BUTTON 1 #define EXIT_BUTTON 2 // -------------------------------------------- // program defination #define NUM_PROGRAMS 4 #define NUM_TIMES 4 #define PROGRAM_NAME_LENGTH 5 typedef struct { byte startTime; byte coolTemp; byte heatTemp; } timeType; typedef struct { byte isEnabled; byte dayMask; char name[PROGRAM_NAME_LENGTH]; timeType time[NUM_TIMES]; } programType; programType program[NUM_PROGRAMS]; void saveProgramConfig(void); void initProgram(void) { /* each day is a bit: sun is lsb, sat is msb ex: sat and tue: B01000100 time starts at 12am = 0, and goes in 15 minute increments ex: 3:30am: 14 default program: cool heat SS 1 6:00am 78 72 SS 2 6:30am 78 72 SS 3 4:00pm 78 72 SS 4 10:00pm 78 72 MT 1 6:00am 78 72 MT 2 8:30am 85 60 MT 3 3:45pm 78 72 MT 4 10:00pm 78 72 F 1 6:00am 78 72 F 2 6:30am 85 60 F 3 1:45pm 78 72 F 4 10:00pm 78 72 */ for (int i=0; i < NUM_PROGRAMS; ++i) { program[i].isEnabled = false; program[i].dayMask = B00000000; program[i].name[0] = '\0'; for (int j=0; j < NUM_TIMES; ++j) { program[i].time[j].startTime = 0; program[i].time[j].coolTemp = 78; program[i].time[j].heatTemp = 72; } } // sat-sun program program[0].isEnabled = true; program[0].dayMask = B01000001; strcpy(program[0].name, "S-S"); program[0].time[0].startTime = 6*4; // 6:00a program[0].time[1].startTime = 6*4+2; // 6:30a program[0].time[2].startTime = 15*4+3; // 3:45p program[0].time[3].startTime = 22*4; // 10:00p // mon-thu program program[1].isEnabled = true; program[1].dayMask = B00011110; strcpy(program[1].name, "M-T"); program[1].time[0].startTime = 6*4; // 6:00a program[1].time[1].startTime = 6*4+2; // 6:30a program[1].time[2].startTime = 15*4+3; // 3:45p program[1].time[3].startTime = 22*4; // 10:00p program[1].time[1].coolTemp = 85; program[1].time[1].heatTemp = 60; // fri program program[2].isEnabled = true; program[2].dayMask = B00100000; strcpy(program[2].name, "F"); program[2].time[0].startTime = 6*4; // 6:00a program[2].time[1].startTime = 6*4+2; // 6:30a program[2].time[2].startTime = 13*4+3; // 1:45p program[2].time[3].startTime = 22*4; // 10:00p program[2].time[1].coolTemp = 85; program[2].time[1].heatTemp = 60; saveProgramConfig(); } // -------------------------------------------- ESP8266WebServer server(80); File fsUploadFile; WebSocketsServer webSocket = WebSocketsServer(81); int webClient = -1; int programClient = -1; int setupClient = -1; int testClient = -1; int testAddr = -1; int testValue = -1; unsigned int testHeap = 0; int indent = 10; bool isTimeSet = false; WiFiClient espClient; PubSubClient client(espClient); #define HOST_NAME "THERMOSTAT" #define MQTT_IP_ADDR "192.168.1.210" #define MQTT_IP_PORT 1883 bool isPromModified; bool isMemoryReset = false; //bool isMemoryReset = true; typedef struct { char host_name[17]; char mqtt_ip_addr[17]; int mqtt_ip_port; byte use_mqtt; byte mode; byte fan; byte temperature_span; byte display_timeout; byte out_temp; byte swap_sensors; byte use_temp; char temp_ip_addr[17]; int temp_ip_port; char wu_key[20]; char wu_location[20]; } configType; configType config; uint8_t currentTempWidth = 0; uint8_t targetTempWidth = 0; uint8_t outsideTempWidth = 0; uint8_t dayWidth = 0; uint8_t timeWidth = 0; uint8_t modeWidth = 0; uint8_t fanWidth = 0; uint8_t stateWidth = 0; uint8_t programWidth = 0; const char *lastState = ""; void print(const char *str); void println(const char *str); void print(const __FlashStringHelper *str); void println(const __FlashStringHelper *str); void setupDisplay(void); void loadConfig(void); bool setupWifi(void); void requestOutsideTemperature(void); void gotOutsideTemperature(float tempF); void setupWebServer(void); void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght); void setupTime(void); void setupButtons(void); void setupRelays(void); void setupMotion(void); bool setupTempSensor(void); void drawMainScreen(void); void displayBacklight(bool); void loadProgramConfig(void); unsigned long sendNTPpacket(IPAddress& address); void printTime(bool isCheckProgram, bool isDisplay, bool isTest); void printCurrentTemperature(bool); void printTargetTemperature(bool); void eraseOutsideTemperature(bool); void printOutsideTemperature(bool); void printModeState(bool); void printFanState(bool); void printRunState(bool); void printProgramState(byte p_program, byte p_time, bool isDisplay); void setTargetTemp(int newTemp); void saveConfig(void); void relaysOff(void); void checkMotion(unsigned long time); void checkTime(unsigned long time); void checkTemperature(void); void checkInsideTemperature(void); void checkOutsideTemperature(void); void checkTemperature(DeviceAddress deviceAddress); void flashTime(); void checkButtons(void); void eraseTime(void); void everyFiveMinutes(void); void logTemperature(float inside, float outside); void checkUnit(void); void checkProgram(int day, int h, int m); void logTarget(int temperature); void doButton(int pin); void doUp(void); void doDown(void); void doEnter(void); void setSelectedMenuItem(int item); void doMenuEnter(void); void drawMenu(void); void drawButton(const char *s1, const char *s2, int i, int sel); void logAction(char state); void update(int addr, byte data); int showWeather(char *json); void setCursor(int x, int y); void setTextSize(int size); int getTargetTemperature(void); void checkOutsideTemperature(void); void sendWeb(const char *command, const char *value); void setUpAirTemp(void); void checkClientConnection(void); void send(byte addr, byte b) { #ifndef WEMOS Wire.beginTransmission(addr); Wire.write(b); Wire.endTransmission(); muxState = b; #endif } void setup(void) { // start serial port Serial.begin(115200); Serial.print(F("\n\n")); Wire.begin(SDA,SCL); send(MUX, 0xFF); setupDisplay(); #ifdef BREADBOARD println(F("BREADBOARD CONFIG")); #endif #ifdef BUILD_ONE println(F("BUILD_ONE CONFIG")); #endif #ifdef BUILD_TWO println(F("BUILD_TWO CONFIG")); #endif println(F("esp8266 thermostat")); println(F("compiled:")); print(F(__DATE__)); print(F(",")); println(F(__TIME__)); print(F("MUX at ")); Serial.println(MUX, HEX); display.println(MUX, HEX); if (!setupWifi()) return; // 512 bytes is not exact, but is more than enough EEPROM.begin(512); loadConfig(); loadProgramConfig(); isMemoryReset = false; setupWebServer(); setupMqtt(); setupOta(); webSocket.begin(); webSocket.onEvent(webSocketEvent); setupTime(); setupButtons(); setupRelays(); setupMotion(); if (setupTempSensor()) { isTempSetup = true; } lastMinutes = 0; lastSeconds = 0; lastMotionReadTime = -TimeBetweenMotionChecks; lastButtonPressTime = millis(); isSetup = true; drawMainScreen(); } #define TIME_BETWEEN_CONNECTS 1000*60 unsigned long lastAttempt; AsyncClient* airTempClient = NULL; void setUpAirTemp(void) { Serial.println(F("setting up air temp socket client")); lastAttempt = 0; airTempClient = new AsyncClient(); airTempClient->onConnect([](void *obj, AsyncClient* c) { Serial.printf("airClient: [A-TCP] onConnect\n"); }, NULL); airTempClient->onDisconnect([](void *obj, AsyncClient* c) { Serial.printf("airClient: [A-TCP] onDisconnect\n"); float airTemp = TEMP_ERROR; if ( airTemp != lastOutsideTemp ) { lastOutsideTemp = airTemp; eraseOutsideTemperature(true); } }, NULL); airTempClient->onError([](void *obj, AsyncClient* c, int8_t err) { Serial.printf("airClient: [A-TCP] onError: %s\n", c->errorToString(err)); }, NULL); airTempClient->onData([](void *obj, AsyncClient* c, void *buf, size_t len) { // Serial.printf("airClient: [A-TCP] onData: %s %d\n", buf, len); char *ptr = (char *)buf; float airTemp = strtod(ptr, &ptr); // Serial.println(airTemp); if ( airTemp != lastOutsideTemp ) { lastOutsideTemp = airTemp; if (screen == MAIN) printOutsideTemperature(true); } }, NULL); // ack received // airTempClient->onAck([](void *obj, AsyncClient* c, size_t len, uint32_t time) { // Serial.printf("airClient: [A-TCP] onAck\n"); // }, NULL); // ack timeout // airTempClient->onTimeout([](void *obj, AsyncClient* c, uint32_t time) { // Serial.printf("airClient: [A-TCP] onTimeout\n"); // }, NULL); // every 125ms when connected // airTempClient->onPoll([](void *obj, AsyncClient* c) { // Serial.printf("airClient: [A-TCP] onPoll\n"); // }, NULL); } void clearScreen(void) { #ifdef DISPLAY_14 display.clearScreen(); #endif #ifdef DISPLAY_18 display.fillScreen(BLACK); #endif #ifdef DISPLAY_22 display.fillScreen(BLACK); #endif #ifdef DISPLAY_28 display.fillScreen(BLACK); #endif } void setCursor(int x, int y) { display.setCursor(x, y); } void setupDisplay(void) { #ifdef DISPLAY_14 Serial.println(F("1.4\" tft display")); display.begin(); display.setBitrate(16000000); #endif #ifdef DISPLAY_18 Serial.println(F("1.8\" tft display")); display.initR(INITR_BLACKTAB); #endif #ifdef DISPLAY_22 Serial.println(F("2.2\" tft display")); display.begin(); #endif #ifdef DISPLAY_28 Serial.println(F("2.8\" tft display")); display.begin(); #endif clearScreen(); setCursor(0, 0); display.setTextColor(GREEN); display.setTextSize(1); #ifdef BREADBOARD #ifdef DISPLAY_14 display.setRotation(2); #endif #endif // set up fonts font_set[0] = NULL; font_height[0] = 8; #if defined DISPLAY_22 || defined DISPLAY_28 Serial.println(F("large fonts")); font_set[1] = &arial20pt7b; font_set[2] = &arial30pt7b; font_height[1] = 28; font_height[2] = 41; #else Serial.println(F("small fonts")); font_set[1] = &arial12pt7b; font_set[2] = &arial18pt7b; font_height[1] = 17; // font_height[2] = 21; font_height[2] = 25; font_width[1] = 12; font_width[2] = 14; font_width[2] = 20; #endif displayBacklight(true); } void drawTimeoutLine() { if (isDisplayOn) { // draw a line at the bottom that erases during screen timeout display.drawLine(0, HEIGHT-10, WIDTH, HEIGHT-10, GREEN); lastPx = 0; } } void displayBacklight(bool isOn) { Serial.printf("backlight %d\n", isOn); if (isSetup && !isDisplayOn && isOn) { // redraw the display before turning it on, so we don't see it flash isDisplayOn = true; drawMainScreen(); } #ifndef WEMOS if (isOn) send(MUX, muxState & ~LED); else send(MUX, muxState | LED); #endif isDisplayOn = isOn; } void print(const char *str) { Serial.print(str); display.print(str); } void print(const __FlashStringHelper *str) { Serial.print(str); display.print(str); } void println(const char *str) { Serial.println(str); display.println(str); } void println(const __FlashStringHelper *str) { Serial.println(str); display.println(str); } bool setupTempSensor(void) { // locate devices on the bus print(F("temp sensor: ")); sensors.begin(); numDevices = sensors.getDeviceCount(); if (numDevices != 1 && numDevices != 2) { println(F("not found")); return false; } char buf[2]; sprintf(buf, "%d", numDevices); print(buf); println(F(" found")); if (!sensors.getAddress(thermometer1, 0)) { println(F("unable to find address for temp sensor")); return false; } sensors.setResolution(thermometer1, resolution); if (numDevices == 2) { if (!sensors.getAddress(thermometer2, 1)) { println(F("unable to find address for outside temp sensor")); return false; } sensors.setResolution(thermometer2, resolution); } sensors.setWaitForConversion(false); sensors.requestTemperatures(); return true; } void printName() { if (webClient == -1) return; sendWeb("name", config.host_name); } void configModeCallback(WiFiManager *myWiFiManager) { // this callback gets called when the enter AP mode, and the users // need to connect to us in order to configure the wifi clearScreen(); setCursor(0, 0); display.setTextColor(GREEN); // cpd...font 1 is too small, 2 is too large to display the word "THERMOSTAT" setTextSize(1); println(F("")); println(F("WiFi Not Configured")); println(F("Join this network:")); println(F("")); setTextSize(2); const char *n = (strlen(config.host_name) > 0) ? config.host_name : HOST_NAME; println(n); setTextSize(1); println(F("And open a browser to:")); println(F("")); setTextSize(2); Serial.println(WiFi.softAPIP()); display.print(WiFi.softAPIP()); } bool setupWifi(void) { const char *n = (strlen(config.host_name) > 0) ? config.host_name : HOST_NAME; WiFi.hostname(n); // wifiManager.setDebugOutput(false); //reset settings - for testing //wifiManager.resetSettings(); ssid = WiFi.SSID(); if (ssid.length() > 0) { print(F("Connecting to ")); Serial.println(ssid); display.println(ssid); } //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode wifiManager.setAPCallback(configModeCallback); if(!wifiManager.autoConnect(n)) { Serial.println(F("failed to connect and hit timeout")); //reset and try again, or maybe put it to deep sleep ESP.reset(); delay(1000); } return true; } void setupTime(void) { if (!isSetup) println(F("Getting time")); else Serial.println(F("Getting time")); AsyncUDP* udp = new AsyncUDP(); // time.nist.gov NTP server // NTP requests are to port 123 if (udp->connect(IPAddress(129,6,15,28), 123)) { Serial.println(F("UDP connected")); udp->onPacket([](void *arg, AsyncUDPPacket packet) { Serial.println(F("received NTP packet")); byte *buf = packet.data(); //the timestamp starts at byte 40 of the received packet and is four bytes, // or two words, long. First, esxtract the two words: // convert four bytes starting at location 40 to a long integer unsigned long secsSince1900 = (unsigned long)buf[40] << 24; secsSince1900 |= (unsigned long)buf[41] << 16; secsSince1900 |= (unsigned long)buf[42] << 8; secsSince1900 |= (unsigned long)buf[43]; time_t utc = secsSince1900 - 2208988800UL; TimeChangeRule *tcr; time_t local = myTZ.toLocal(utc, &tcr); Serial.printf("\ntime zone %s\n", tcr->abbrev); setTime(local); // just print out the time printTime(false, false, true); isTimeSet = true; free(arg); }, udp); // Serial.println(F("sending NTP packet")); const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold outgoing packet // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // send a packet requesting a timestamp: udp->write(packetBuffer, NTP_PACKET_SIZE); } else { free(udp); if (!isSetup) print(F("\nWiFi:time failed...will retry in a minute\n")); else Serial.println(F("\nWiFi:time failed...will retry in a minute")); } } void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) { switch(type) { case WStype_DISCONNECTED: Serial.printf("[%u] Disconnected!\n", num); if (num == webClient) webClient = -1; else if (num == programClient) programClient = -1; else if (num == setupClient) setupClient = -1; else if (num == testClient) { testClient = -1; testAddr = -1; testValue = -1; testHeap = 0; } break; case WStype_CONNECTED: { IPAddress ip = webSocket.remoteIP(num); Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload); } if (strcmp((char *)payload,"/") == 0) { webClient = num; // send the current state printName(); printCurrentTemperature(false); printTargetTemperature(false); printOutsideTemperature(false); printModeState(false); printFanState(false); printRunState(false); isForcePrint = true; printProgramState(last_p_program, last_p_time, false); printTime(false, false, false); isForcePrint = false; } else if (strcmp((char *)payload,"/program") == 0) { programClient = num; // send programs char json[265]; strcpy(json, "{\"command\":\"program\",\"value\":["); for (int i=0; i < NUM_PROGRAMS; ++i) { sprintf(json+strlen(json), "%s[%d,%d,\"%s\",[", (i==0)?"":",", program[i].isEnabled, program[i].dayMask, program[i].name); for (int j=0; j < NUM_TIMES; ++j) { sprintf(json+strlen(json), "%d,%d,%d%s", program[i].time[j].startTime, program[i].time[j].coolTemp, program[i].time[j].heatTemp, (j==NUM_TIMES-1)?"]]":","); } } strcpy(json+strlen(json), "]}"); //Serial.printf("len %d\n", strlen(json)); webSocket.sendTXT(programClient, json, strlen(json)); } else if (strcmp((char *)payload,"/setup") == 0) { setupClient = num; char json[512]; strcpy(json, "{"); sprintf(json+strlen(json), "\"date\":\"%s\"", __DATE__); sprintf(json+strlen(json), ",\"time\":\"%s\"", __TIME__); sprintf(json+strlen(json), ",\"host_name\":\"%s\"", config.host_name); sprintf(json+strlen(json), ",\"use_mqtt\":\"%d\"", config.use_mqtt); sprintf(json+strlen(json), ",\"mqtt_ip_addr\":\"%s\"", config.mqtt_ip_addr); sprintf(json+strlen(json), ",\"mqtt_ip_port\":\"%d\"", config.mqtt_ip_port); sprintf(json+strlen(json), ",\"ssid\":\"%s\"", ssid.c_str()); sprintf(json+strlen(json), ",\"span\":\"%d\"", config.temperature_span); sprintf(json+strlen(json), ",\"timeout\":\"%d\"", config.display_timeout); sprintf(json+strlen(json), ",\"out_temp\":\"%d\"", config.out_temp); sprintf(json+strlen(json), ",\"swap\":\"%d\"", config.swap_sensors); sprintf(json+strlen(json), ",\"use_temp\":\"%d\"", config.use_temp); sprintf(json+strlen(json), ",\"temp_ip_addr\":\"%s\"", config.temp_ip_addr); sprintf(json+strlen(json), ",\"temp_ip_port\":\"%d\"", config.temp_ip_port); sprintf(json+strlen(json), ",\"key\":\"%s\"", config.wu_key); sprintf(json+strlen(json), ",\"location\":\"%s\"", config.wu_location); strcpy(json+strlen(json), "}"); // Serial.printf("len %d\n", strlen(json)); webSocket.sendTXT(setupClient, json, strlen(json)); } else if (strcmp((char *)payload,"/test") == 0) { testClient = num; testAddr = MUX; // send the addessses of the muxes we are using char json[128]; sprintf(json, "{\"msg\":\"MUX at %d\",\"addr\":\"%d\"}", MUX, MUX); // Serial.printf("len %d\n", strlen(json)); webSocket.sendTXT(testClient, json, strlen(json)); } else { Serial.printf("unknown call %s\n", payload); } break; case WStype_TEXT: Serial.printf("[%u] get Text: %s\n", num, payload); if (num == webClient) { const char *target = "command"; char *ptr = strstr((char *)payload, target) + strlen(target)+3; if (strncmp(ptr,"up",2) == 0) { setTargetTemp(lastTargetTemperature+1); } else if (strncmp(ptr,"down",4) == 0) { setTargetTemp(lastTargetTemperature-1); } else if (strncmp(ptr,"mode",4) == 0) { target ="value"; ptr = strstr(ptr, target) + strlen(target)+3; config.mode = strtol(ptr, &ptr, 10); saveConfig(); drawMainScreen(); } else if (strncmp(ptr,"fan",3) == 0) { target ="value"; ptr = strstr(ptr, target) + strlen(target)+3; config.fan = strtol(ptr, &ptr, 10); saveConfig(); drawMainScreen(); } } else if (num == programClient) { Serial.println(F("save programs")); char *ptr = strchr((char *)payload, '[')+2; for (int i=0; i < NUM_PROGRAMS; ++i) { program[i].isEnabled = strtol(ptr, &ptr, 10); ptr += 1; program[i].dayMask = strtol(ptr, &ptr, 10); ptr += 2; char *end = strchr(ptr, '\"'); memcpy(program[i].name, ptr, (end-ptr)); program[i].name[end-ptr] = '\0'; // Serial.printf("num %d,isEnabled %d,dayMask %d,name %s\n", i, program[i].isEnabled, program[i].dayMask, program[i].name); ptr = end + 3; for (int j=0; j < NUM_TIMES; ++j, ++ptr) { program[i].time[j].startTime = strtol(ptr, &ptr, 10); program[i].time[j].coolTemp = strtol(ptr+1, &ptr, 10); program[i].time[j].heatTemp = strtol(ptr+1, &ptr, 10); // Serial.printf("startTime %d, coolTemp %d, heatTemp %d\n", // program[i].time[j].startTime, // program[i].time[j].coolTemp, // program[i].time[j].heatTemp); } ptr += 3; } saveProgramConfig(); drawMainScreen(); } else if (num == setupClient) { const char *target = "command"; char *ptr = strstr((char *)payload, target) + strlen(target)+3; if (strncmp(ptr,"reboot",6) == 0) { ESP.restart(); } else if (strncmp(ptr,"save",4) == 0) { Serial.println(F("save setup")); const char *target = "host_name"; char *ptr = strstr((char *)payload, target) + strlen(target)+3; char *end = strchr(ptr, '\"'); memcpy(config.host_name, ptr, (end-ptr)); config.host_name[end-ptr] = '\0'; target = "use_mqtt"; ptr = strstr((char *)payload, target) + strlen(target)+3; config.use_mqtt = strtol(ptr, &ptr, 10); target = "mqtt_ip_addr"; ptr = strstr((char *)payload, target) + strlen(target)+3; end = strchr(ptr, '\"'); memcpy(config.mqtt_ip_addr, ptr, (end-ptr)); config.mqtt_ip_addr[end-ptr] = '\0'; target = "mqtt_ip_port"; ptr = strstr((char *)payload, target) + strlen(target)+3; config.mqtt_ip_port = strtol(ptr, &ptr, 10); target = "span"; ptr = strstr((char *)payload, target) + strlen(target)+3; config.temperature_span = strtol(ptr, &ptr, 10); target = "timeout"; ptr = strstr((char *)payload, target) + strlen(target)+3; config.display_timeout = strtol(ptr, &ptr, 10); target = "out_temp"; ptr = strstr((char *)payload, target) + strlen(target)+3; config.out_temp = strtol(ptr, &ptr, 10); target = "swap"; ptr = strstr((char *)payload, target) + strlen(target)+3; config.swap_sensors = strtol(ptr, &ptr, 10); target = "use_temp"; ptr = strstr((char *)payload, target) + strlen(target)+3; config.use_temp = strtol(ptr, &ptr, 10); target = "temp_ip_addr"; ptr = strstr((char *)payload, target) + strlen(target)+3; end = strchr(ptr, '\"'); memcpy(config.temp_ip_addr, ptr, (end-ptr)); config.temp_ip_addr[end-ptr] = '\0'; target = "temp_ip_port"; ptr = strstr((char *)payload, target) + strlen(target)+3; config.temp_ip_port = strtol(ptr, &ptr, 10); target = "key"; ptr = strstr((char *)payload, target) + strlen(target)+3; end = strchr(ptr, '\"'); memcpy(config.wu_key, ptr, (end-ptr)); config.wu_key[end-ptr] = '\0'; target = "location"; ptr = strstr((char *)payload, target) + strlen(target)+3; end = strchr(ptr, '\"'); memcpy(config.wu_location, ptr, (end-ptr)); config.wu_location[end-ptr] = '\0'; // Serial.printf("host_name %s\n", config.host_name); // Serial.printf("use_mqtt %d\n", config.use_mqtt); // Serial.printf("mqtt_ip_addr %s\n", config.mqtt_ip_addr); // Serial.printf("mqtt_ip_port %d\n", config.mqtt_ip_port); // Serial.printf("temperature_span %d\n", config.temperature_span); // Serial.printf("display_timeout %d\n", config.display_timeout); // Serial.printf("out_temp %d\n", config.out_temp); // Serial.printf("swap_sensors %d\n", config.swap_sensors); // Serial.printf("use_temp %d\n", config.use_temp); // Serial.printf("temp_ip_addr %s\n", config.temp_ip_addr); // Serial.printf("temp_ip_port %d\n", config.temp_ip_port); // Serial.printf("wu_key %s\n", config.wu_key); // Serial.printf("wu_location %s\n", config.wu_location); saveConfig(); } } else if (num == testClient) { Serial.printf("test %s\n", payload); const char *target = "addr"; char *ptr = strstr((char *)payload, target) + strlen(target)+3; int addr = strtol(ptr, &ptr, 10); target = "value"; ptr = strstr(ptr, target) + strlen(target)+3; int value = strtol(ptr, &ptr, 10); Serial.printf("%d %d\n", addr, value); send(addr, value); testAddr = addr; } break; } } void sendWeb(const char *command, const char *value) { char json[128]; sprintf(json, "{\"command\":\"%s\",\"value\":\"%s\"}", command, value); webSocket.sendTXT(webClient, json, strlen(json)); } void setupButtons(void) { numButtons = sizeof(buttonPins)/sizeof(buttonPins[0]); buttonStates = new int[numButtons]; lastButtonStates = new int[numButtons]; lastDebounceTimes = new long[numButtons]; // initialize the pushbutton pins as inputs for (int i=0; i < numButtons; ++i) { buttonStates[i] = defaultButtonState; lastButtonStates[i] = defaultButtonState; lastDebounceTimes[i] = 0; } println(F("buttons: setup")); } void setupRelays(void) { #ifdef LATCH_RELAYS println(F("using LATCH RELAYS")); pinMode(RESET_PIN, OUTPUT); digitalWrite(RESET_PIN, HIGH); #endif relaysOff(); isFanOn = false; isCompressorOn = false; isReversingValueOn = false; println(F("relays: setup")); } void relaysOff(void) { #ifdef LATCH_RELAYS // pulse the reset line low for 5ms to turn all the latch relays off digitalWrite(RESET_PIN, LOW); delay(5); digitalWrite(RESET_PIN, HIGH); #else byte value = muxState; for (int i=0; i < 3; ++i) value |= relayPins[i]; send(MUX, value); #endif Serial.println(F("relaysOff")); } #ifdef WEMOS #define MOTION_PIN 16 // D0 #endif void setupMotion(void) { println(F("motion: setup")); #ifdef WEMOS pinMode(MOTION_PIN, INPUT); #endif } unsigned long lastTime = millis(); void loop(void) { if (!isSetup) return; /* * the loop should be called every 1 ot 2 msec * * reading the 1wire temperature takes 12 msec, but we only read it * once per second...so most loops happen very quickly. * * drawing large font text on the display can also cause a slow loop. * * if we have too many slow loops, some services like wifi won't work properly */ unsigned long time = millis(); long delta = time - lastTime; if (delta > 25) { Serial.printf("slow loop: %lu\n", delta); } lastTime = time; // only check the motion sensor every so often if ( time - lastMotionReadTime > TimeBetweenMotionChecks ) { checkMotion(time); lastMotionReadTime = time; } unsigned long t = time - lastButtonPressTime; // turn off the display if idle if (isDisplayOn) { // erase some of the timeout line long timeout = (screen == MAIN) ? (config.display_timeout*1000) : MenuIdleTime; int px = t * WIDTH / timeout; if (lastPx != px) { lastPx = px; // Serial.println(px); display.drawLine(WIDTH, HEIGHT-10, WIDTH-px, HEIGHT-10, BLACK); } if (t > (config.display_timeout*1000)) { displayBacklight(false); } if (screen != MAIN) { // go back to main screen if idle if (t > MenuIdleTime ) { drawMainScreen(); } } } checkTime(time); #ifndef WEMOS // unsigned long startTime = millis(); checkButtons(); // unsigned long endTime = millis(); // Serial.printf("Time to read buttons: %d msec\n", (endTime - startTime)); #endif webSocket.loop(); server.handleClient(); MDNS.update(); // mqtt if (config.use_mqtt) { if (!client.connected()) { reconnect(); } client.loop(); } ArduinoOTA.handle(); if (config.out_temp) { if (numDevices == 1) { if (config.use_temp) checkClientConnection(); } } } void checkClientConnection(void) { if (airTempClient == NULL) setUpAirTemp(); // try and connect every minute if not already connected if (!airTempClient->connected()) { if (millis() > lastAttempt + TIME_BETWEEN_CONNECTS) { Serial.printf("connecting to socket server\n"); airTempClient->connect(config.temp_ip_addr, config.temp_ip_port); lastAttempt = millis(); } } } bool isFlash = false; void flashTime() { // the temperature sensor blocks the app from running while it is reading. // so, it may make the flash look off every time it is being checked isFlash = !isFlash; if (isFlash) eraseTime(); else printTime(false, true, false); } bool isMotion = false; void checkMotion(unsigned long time) { // Serial.println(F("checkMotion")); #ifdef WEMOS int val = digitalRead(MOTION_PIN); // read input value if (val == HIGH) { // check if the input is HIGH #else Wire.requestFrom(MUX, 1); if (!Wire.available()) return; byte value = Wire.read(); if ((value & MOTION) != 0) { #endif if (!isMotion) { // motion started isMotion = true; Serial.println(F("motion started")); lastButtonPressTime = time; if (!isDisplayOn) { displayBacklight(true); } else { // display is already on, just reset the timeout line drawTimeoutLine(); } } } else { if (isMotion) { // motion ended isMotion = false; Serial.println(F("motion ended")); } } } void everySecond() { if (isTempSetup) checkTemperature(); // flash the time if its not set if (screen == MAIN) { if (!isTimeSet) flashTime(); } } void checkTime(unsigned long time) { int seconds = second(); if (seconds != lastSeconds) { lastSeconds = seconds; everySecond(); } int minutes = minute(); if (minutes == lastMinutes) return; // Serial.printf("checkTime\n"); // resync time at 3am every morning // this also catches daylight savings time changes which happen at 2am if (minutes == 0 && hour() == 3) isTimeSet = false; if (!isTimeSet) setupTime(); lastMinutes = minutes; printTime(true, true, false); if (minutes % 5 == 0) everyFiveMinutes(); } void everyFiveMinutes(void) { if (config.out_temp) { // get the outside temperature, unless we are using a sensor outside // or a remote air temperature sensor if (!config.use_temp && numDevices == 1) { requestOutsideTemperature(); return; } } // log the temperatures to the database if (lastTemp != TEMP_ERROR && lastOutsideTemp != TEMP_ERROR) logTemperature(lastTemp, lastOutsideTemp); } void checkTemperature() { // Serial.println(F("checking temperature")); checkInsideTemperature(); if (config.out_temp) { // if we're not using a remote air temperature sensor, and have two connected sensors, // then read the second sensor now if (!config.use_temp && numDevices == 2) checkOutsideTemperature(); } // request new temperatures sensors.requestTemperatures(); } int lastSentTargetTemperature = TEMP_ERROR; void checkInsideTemperature(void) { // reading the 1wire temperature takes 12msec, so only check it once // per second. if we do it too often, we'll mess up other services (like wifi) // unsigned long startTime = millis(); float tempF = sensors.getTempF((config.swap_sensors == 0) ? thermometer1 : thermometer2); // unsigned long endTime = millis(); // Serial.printf("Time to read temperature sensor: %d msec\n", (endTime - startTime)); tempF = (float)round(tempF*10)/10.0; if ( tempF == lastTemp ) return; lastTemp = tempF; if (screen == MAIN) { printCurrentTemperature(true); int temp = getTargetTemperature(); if (temp != lastSentTargetTemperature ) { lastSentTargetTemperature = temp; logTarget(temp); printTargetTemperature(true); } } checkUnit(); } void checkOutsideTemperature(void) { // reading the 1wire temperature takes 12msec, so only check it once // per second. if we do it too often, we'll mess up other services (like wifi) float tempF = sensors.getTempF((config.swap_sensors == 0) ? thermometer2 : thermometer1); tempF = (float)round(tempF*10)/10.0; if ( tempF == lastOutsideTemp ) return; lastOutsideTemp = tempF; printOutsideTemperature(true); } void setTextSize(int size) { display.setFont(font_set[size-1]); } void eraseTime(void) { if (isDisplayOn) { if (timeWidth != 0) display.fillRect(WIDTH-timeWidth, 2 *(font_height[1] + 2), timeWidth, font_height[1], ERASE); if (dayWidth != 0) display.fillRect(WIDTH-dayWidth-2, font_height[1] + 2, dayWidth, font_height[1], ERASE); timeWidth = 0; dayWidth = 0; } } void printTime(bool isCheckProgram, bool isDisplay, bool isTest) { int dayOfWeek = weekday()-1; int hours = hour(); int minutes = minute(); const char *ampm = "A"; int h = hours; if (hours == 0) h = 12; else if (h == 12) ampm = "P"; else if (hours > 12) { h -= 12; ampm = "P"; } char buf[10]; sprintf(buf, "%d:%02d%s", h, minutes, ampm); // Serial.println(buf); if (isDisplay && isDisplayOn && screen == MAIN) { display.setTextColor(GREEN); setTextSize(2); // time if (timeWidth != 0) display.fillRect(WIDTH-timeWidth-1, 2 *(font_height[1] + 2), timeWidth, font_height[1], ERASE); setCursor(WIDTH-getStringWidth(buf)-4, 3 * font_height[1] + 2*2 - 1); display.print(buf); timeWidth = getStringWidth(buf)+1; // Serial.printf("time: %s\n", buf); // todo... only draw if the day has changed // day if (dayWidth != 0) display.fillRect(WIDTH-dayWidth-2, font_height[1] + 2, dayWidth, font_height[1], ERASE); setCursor(WIDTH-getStringWidth(weekdayNames[dayOfWeek])-4, 2 * font_height[1] + 2 - 1); display.print(weekdayNames[dayOfWeek]); dayWidth = getStringWidth(weekdayNames[dayOfWeek])+1; // Serial.printf("day: %s\n", weekdayNames[dayOfWeek]); } if (webClient != -1 || isTest) { char msg[6+1+4]; sprintf(msg, "%s %s", buf, weekdayNames[dayOfWeek]); if (webClient != -1) sendWeb("time", msg); if (isTest) Serial.printf("time is %s\n", msg); } if (isCheckProgram) checkProgram(dayOfWeek, hours, minutes); } byte getProgramForDay(int day) { // day: Sun = 0, Mon = 1, etc // convert day to a dayMask byte mask = 1 << day; // Serial.print("mask "); // Serial.println(mask, BIN); for (int i=0; i < NUM_PROGRAMS; ++i) { if ( program[i].isEnabled ) { if ( mask & program[i].dayMask ) { // Serial.printf("day match with %s\n", program[i].name); return i; } } } // we should never get here, this means they didn't configure // one of the days of the week in the programs Serial.print(F("error - no program defined for day")); Serial.println(day); return 0; } void checkProgram(int day, int h, int m) { if (config.mode == OFF) { printProgramState(0,0,true); return; } // Serial.println(F("check program")); byte ctime = h*4+(m/15); // Serial.printf("ctime %d day %d\n", ctime, day); byte p_program = getProgramForDay(day); // if the current time is before the first program time of the day, // then use the last program time/temp of the previous day byte p_time; if (ctime < program[p_program].time[0].startTime) { // Serial.println("using last program from previous day"); if (day == 0) day = 6; else --day; p_program = getProgramForDay(day); p_time = NUM_TIMES-1; } else { // locate which time slot we are in p_time = NUM_TIMES-1; for (int i=1; i < NUM_TIMES; ++i) { if (ctime < program[p_program].time[i].startTime) { p_time = i-1; break; } } } // Serial.printf("time match with %d\n", p_time); byte p_ctemp = program[p_program].time[p_time].coolTemp; byte p_htemp = program[p_program].time[p_time].heatTemp; // Serial.printf("target temp %d $d\n", p_ctemp, p_htemp); // if we just started a new program, then cancel the temp hold // cpd...perm hold should be checked here if (last_p_time != p_time) { if (config.mode == TEMP) { config.mode = ON; printModeState(true); } } printProgramState(p_program, p_time, true); if (config.mode == ON && (targetCoolTemp != p_ctemp || targetHeatTemp != p_htemp)) { targetCoolTemp = p_ctemp; targetHeatTemp = p_htemp; logTarget(getTargetTemperature()); printTargetTemperature(true); checkUnit(); } } void eraseOutsideTemperature(bool isDisplay) { if (isDisplay && isDisplayOn) { if (outsideTempWidth != 0) display.fillRect(WIDTH-outsideTempWidth, 0, outsideTempWidth, font_height[1], ERASE); outsideTempWidth = 0; } if (webClient != -1) { sendWeb("outsideTemp", ""); } } void addDegree(char *buf) { char *ptr = buf + strlen(buf); *ptr++ = (char)58; // char after 9 (we manually added degree symbol here) *ptr = '\0'; } void printOutsideTemperature(bool isDisplay) { if (!config.out_temp) return; if (lastOutsideTemp == TEMP_ERROR) return; if (isDisplay && isDisplayOn) { // weather underground only gives us integer precision for the temperature // the temp sensor or the remote air sensor gives us decimal precision // so only show the precision we have on the display char buf[8]; if (config.use_temp || numDevices == 2) dtostrf(lastOutsideTemp, 4, 1, buf); else sprintf(buf, "%d", (int)lastOutsideTemp); // cpd...this font doesn't have the degree symbol // addDegree(buf); display.setTextColor(GREEN); setTextSize(2); if (outsideTempWidth != 0) display.fillRect(WIDTH-outsideTempWidth, 0, outsideTempWidth, font_height[1], ERASE); setCursor(WIDTH-getStringWidth(buf)-1, font_height[1]-1); display.print(buf); outsideTempWidth = getStringWidth(buf)+1; // Serial.printf("outside temp: %s\n", buf); } if (webClient != -1) { char buf[7]; if (config.use_temp || numDevices == 2) dtostrf(lastOutsideTemp, 4, 1, buf); else sprintf(buf, "%d", (int)lastOutsideTemp); sendWeb("outsideTemp", buf); } } void printCurrentTemperature(bool isDisplay) { if (isDisplay && isDisplayOn) { char buf[8]; dtostrf(lastTemp, 4, 1, buf); addDegree(buf); display.setTextColor(GREEN); setTextSize(3); if (currentTempWidth != 0) display.fillRect(0, 0, currentTempWidth, font_height[2], ERASE); setCursor(0, font_height[2]-1); display.print(buf); currentTempWidth = getStringWidth(buf)+1; } if (webClient != -1) { char buf[7]; dtostrf(lastTemp, 4, 1, buf); sendWeb("currentTemp", buf); } } int getTargetTemperature(void) { if (lastTemp == TEMP_ERROR ) return TEMP_ERROR; else if (lastTargetTemperature == 0 || (lastTargetTemperature != targetCoolTemp && lastTargetTemperature != targetHeatTemp)) { /* * the target tempersature is either the target cool or heat terperature * whichever one the current temperature is closer to */ float midTemp = (targetCoolTemp - targetHeatTemp) / 2 + targetHeatTemp; if ( lastTemp >= midTemp ) { lastTargetTemperature = targetCoolTemp; isTargetCool = true; } else { lastTargetTemperature = targetHeatTemp; isTargetCool = false; } } else if (lastTargetTemperature == targetCoolTemp) { if ( lastTemp < targetHeatTemp ) { lastTargetTemperature = targetHeatTemp; isTargetCool = false; } } else if (lastTargetTemperature == targetHeatTemp) { if ( lastTemp > targetCoolTemp ) { lastTargetTemperature = targetCoolTemp; isTargetCool = true; } } return lastTargetTemperature; } void printTargetTemperature(bool isDisplay) { if (lastTargetTemperature == TEMP_ERROR) return; if (isDisplay && isDisplayOn) { if (targetTempWidth != 0) { display.fillRect(0, font_height[2] + 2, targetTempWidth, font_height[2], ERASE); targetTempWidth = 0; } if (config.mode != OFF) { char buf[6]; sprintf(buf, "%d", lastTargetTemperature); addDegree(buf); display.setTextColor(GREEN); setTextSize(3); setCursor(0, 2 * font_height[2] + 2 - 1); display.print(buf); targetTempWidth = getStringWidth(buf)+1; } } if (webClient != -1) { if (config.mode == OFF) sendWeb("targetTemp", ""); else { char buf[5]; sprintf(buf, "%d", lastTargetTemperature); sendWeb("targetTemp", buf); } } } void printModeState(bool isDisplay) { if (isDisplay && isDisplayOn) { display.setTextColor(GREEN); setTextSize(2); setCursor(0, 4 * font_height[1] + 3*2 - 1); display.print("Mode:"); if (modeWidth != 0) display.fillRect(WIDTH-modeWidth, 3 *(font_height[1] + 2), modeWidth, font_height[1], ERASE); setCursor(WIDTH-getStringWidth(modeNames[config.mode])-3, 4 * font_height[1] + 3*2 - 1); display.print(modeNames[config.mode]); modeWidth = getStringWidth(modeNames[config.mode]) + 1; } if (webClient != -1) { char buf[3]; sprintf(buf, "%d", config.mode); sendWeb("mode", buf); } } void printFanState(bool isDisplay) { if (isDisplay && isDisplayOn) { display.setTextColor(GREEN); setTextSize(2); setCursor(0, 5 * font_height[1] + 4*2 - 1); display.print("Fan:"); if (fanWidth != 0) display.fillRect(WIDTH-fanWidth, 4 *(font_height[1] + 2), fanWidth, font_height[1], ERASE); setCursor(WIDTH-getStringWidth(fanNames[config.fan])-1, 5 * font_height[1] + 4*2 - 1); display.print(fanNames[config.fan]); fanWidth = getStringWidth(fanNames[config.fan])+1; } if (webClient != -1) { char buf[3]; sprintf(buf, "%d", config.fan); sendWeb("fan", buf); } } void printRunState(bool isDisplay) { if (isDisplay && isDisplayOn) { const char *buf = ""; if (isCompressorOn) buf = modeStateNames[mode]; else if (isFanOn) buf = "Fan"; if (strcmp(buf, lastState) != 0) { display.setTextColor(GREEN); setTextSize(2); if (stateWidth != 0) display.fillRect(0, 5 *(font_height[1] + 2), stateWidth, font_height[1], ERASE); setCursor(0, 6 * font_height[1] + 5*2 - 1); display.print(buf); Serial.println("draw run state"); lastState = buf; stateWidth = getStringWidth(buf)+3; } } if (webClient != -1) { if (isCompressorOn) sendWeb("run", modeStateNames[mode]); else if (isFanOn) sendWeb("run", "Fan"); else sendWeb("run", ""); } } int getStringWidth(const char* buf) { int16_t x1, y1; uint16_t w, h; display.getTextBounds(buf, 0, 0, &x1, &y1, &w, &h); return w; } int getFontHeight() { int16_t x1, y1; uint16_t w, h; display.getTextBounds("[", 0, 0, &x1, &y1, &w, &h); return h; } void printProgramState(byte p_program, byte p_time, bool isDisplay) { if (last_p_program == p_program && last_p_time == p_time && !isForcePrint) return; last_p_program = p_program; last_p_time = p_time; if (isDisplay && isDisplayOn) { if (programWidth != 0) display.fillRect(WIDTH-programWidth, 5 *(font_height[1] + 2), programWidth, font_height[1], ERASE); if (config.mode == ON) { char buf[6]; sprintf(buf, "%s %d", program[p_program].name, p_time+1); display.setTextColor(GREEN); setTextSize(2); setCursor(WIDTH-getStringWidth(buf)-3, 6 * font_height[1] + 5*2 - 1); display.print(buf); programWidth = getStringWidth(buf)+1; } } if (webClient != -1) { if (config.mode != ON) sendWeb("program", ""); else { char buf[6]; sprintf(buf, "%s %d", program[p_program].name, p_time+1); sendWeb("program", buf); } } } void checkButtons(void) { if (testClient != -1 && testAddr != -1) { Wire.requestFrom(testAddr, 1); if (!Wire.available()) return; unsigned int heap = ESP.getFreeHeap(); byte value = Wire.read(); if (value != testValue || heap != testHeap) { testValue = value; testHeap = heap; char json[128]; sprintf(json, "{\"command\":\"read\",\"value\":\"%d\",\"heap\":\"%u\"}", value, heap); Serial.printf("sending %s\n", json); webSocket.sendTXT(testClient, json, strlen(json)); } } Wire.requestFrom(MUX, 1); if (!Wire.available()) return; byte value = Wire.read(); for (int i=0; i < numButtons; ++i) { int reading = ((value & buttonPins[i]) == 0) ? HIGH : LOW; // if (i == 1) // Serial.printf("%d %d %d\n", i, reading, lastButtonStates[i]); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited // long enough since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading != lastButtonStates[i]) { // reset the debouncing timer lastDebounceTimes[i] = millis(); } if ((millis() - lastDebounceTimes[i]) > debounceDelay) { // whatever the reading is at, it's been there for longer // than the debounce delay, so take it as the actual current state: // if the button state has changed: if (reading != buttonStates[i]) { buttonStates[i] = reading; if (reading != defaultButtonState) doButton(buttonPins[i]); } } // save the reading. Next time through the loop, // it'll be the lastButtonState: lastButtonStates[i] = reading; } } void doButton(int pin) { lastButtonPressTime = millis(); if (!isDisplayOn) { // just turn on the display, ignore the button press displayBacklight(true); return; } switch (pin) { case UP: doUp(); break; case DOWN: doDown(); break; case ENTER: doEnter(); break; } } void doUp(void) { switch(screen) { case MAIN: setTargetTemp(lastTargetTemperature+1); break; case MENU: setSelectedMenuItem(selectedMenuItem-1); break; } } void doDown(void) { switch(screen) { case MAIN: setTargetTemp(lastTargetTemperature-1); break; case MENU: setSelectedMenuItem(selectedMenuItem+1); break; } } void doEnter(void) { switch(screen) { case MAIN: screen = MENU; clearScreen(); setSelectedMenuItem(EXIT_BUTTON); drawTimeoutLine(); break; case MENU: doMenuEnter(); break; } } void doMenuEnter(void) { switch(selectedMenuItem) { case MODE_BUTTON: ++config.mode; if ( config.mode > HOLD ) config.mode = OFF; drawMenu(); break; case FAN_BUTTON: ++config.fan; if ( config.fan > ON ) config.fan = AUTO; drawMenu(); break; case EXIT_BUTTON: saveConfig(); drawMainScreen(); break; } } void drawMainScreen(void) { screen = MAIN; if (isDisplayOn) clearScreen(); if (lastTemp != TEMP_ERROR) printCurrentTemperature(true); printTargetTemperature(true); printOutsideTemperature(true); printModeState(true); printFanState(true); isForcePrint = true; printTime(true, true, false); isForcePrint = false; drawTimeoutLine(); checkUnit(); } void setSelectedMenuItem(int item) { if (item < MODE_BUTTON) item = EXIT_BUTTON; else if (item > EXIT_BUTTON ) item = MODE_BUTTON; selectedMenuItem = item; drawMenu(); } void drawMenu(void) { // display our ip address setCursor(0, 6 * font_height[1] + 5*2 - 1); display.setTextColor(GREEN); setTextSize(2); display.print(WiFi.localIP()); drawButton("Mode:", modeNames[config.mode], 0, selectedMenuItem); drawButton("Fan:", fanNames[config.fan], 1, selectedMenuItem); drawButton("Exit", NULL, 2, selectedMenuItem); } void drawButton(const char *s1, const char *s2, int i, int sel) { int color = (i == sel) ? RED : GREEN; int h = font_height[1]*1.5; int y = i*(font_height[1]*1.5); int y2 = y + (font_height[1]*1.2); display.fillRect(0,y,WIDTH,h,BLACK); display.drawRect(0,y,WIDTH,h,color); display.setTextColor(color); setCursor(10, y2); display.print(s1); if (s2 != NULL) display.print(s2); } void setTargetTemp(int newTemp) { if (config.mode == OFF) return; if (config.mode == ON) { config.mode = TEMP; printModeState(true); } if (isTargetCool) targetCoolTemp = newTemp; else targetHeatTemp = newTemp; lastTargetTemperature = newTemp; logTarget(newTemp); printTargetTemperature(true); printProgramState(last_p_program, last_p_time, true); checkUnit(); } void relayOn(int which) { #ifdef LATCH_RELAYS byte value = muxState; value &= ~relayPins[which]; send(MUX, value); delay(5); value |= relayPins[which]; send(MUX, value); #else byte value = muxState; value &= ~relayPins[which]; send(MUX, value); #endif Serial.printf("relay on %d\n", which); } void checkUnit(void) { // turn the unit on or off if needed if (config.mode == OFF) { if (isCompressorOn || isReversingValueOn) { relaysOff(); logAction(SYSTEM_OFF); isCompressorOn = false; isReversingValueOn = false; isFanOn = false; } if (config.fan == AUTO) { if (isFanOn) { relaysOff(); logAction(SYSTEM_OFF); isFanOn = false; } } else { if (!isFanOn) { relayOn(FAN); logAction(SYSTEM_FAN); isFanOn = true; } } } else { // cool or heat boolean isOn = false; float span = (float)config.temperature_span / 10.0; if (isCompressorOn) { // to prevent short cycling, don't turn off until we're // <span> degrees below target temp (cooling) // or <span> degrees above target temp (heating) if (lastTemp >= (targetCoolTemp-span)) { isOn = true; mode = COOL; } else if (lastTemp <= (targetHeatTemp+span)) { isOn = true; mode = HEAT; } } else { // to prevent short cycling, don't turn on until we're // <span> degrees above target temp (cooling) // or <span> degrees below target temp (heating) if (lastTemp >= (targetCoolTemp+span)) { isOn = true; mode = COOL; } else if (lastTemp <= (targetHeatTemp-span)) { isOn = true; mode = HEAT; } } if (isOn) { if (!isCompressorOn) { relayOn(COMPRESSOR); logAction((mode == HEAT) ? SYSTEM_HEAT : SYSTEM_COOL); isCompressorOn = true; } if (!isFanOn) { relayOn(FAN); isFanOn = true; } if (mode == COOL) { if (!isReversingValueOn) { relayOn(REVERSING_VALVE); isReversingValueOn = true; } } } else { if (isCompressorOn || isReversingValueOn || isFanOn) { relaysOff(); logAction(SYSTEM_OFF); isCompressorOn = false; isReversingValueOn = false; isFanOn = false; } } } if (screen == MAIN) printRunState(true); } #define MAGIC_NUM 0xB1 #define MAGIC_NUM_ADDRESS 0 #define CONFIG_ADDRESS 1 #define PROGRAM_ADDRESS CONFIG_ADDRESS + sizeof(config) void set(char *name, const char *value) { for (int i=strlen(value); i >= 0; --i) *(name++) = *(value++); } void loadConfig(void) { int magicNum = EEPROM.read(MAGIC_NUM_ADDRESS); if (magicNum != MAGIC_NUM) { println(F("invalid eeprom data")); isMemoryReset = true; } if (isMemoryReset) { // nothing saved in eeprom, use defaults println(F("using default config")); set(config.host_name, HOST_NAME); set(config.mqtt_ip_addr, MQTT_IP_ADDR); config.mqtt_ip_port = MQTT_IP_PORT; config.use_mqtt = 0; config.mode = OFF; config.fan = AUTO; config.temperature_span = 7; config.display_timeout = 20; config.out_temp = 0; config.swap_sensors = 0; config.use_temp = 0; set(config.temp_ip_addr, TEMP_IP_ADDR); config.temp_ip_port = TEMP_IP_PORT; set(config.wu_key, WU_API_KEY); set(config.wu_location, WU_LOCATION); saveConfig(); } else { int addr = CONFIG_ADDRESS; byte *ptr = (byte *)&config; for (int i=0; i < sizeof(config); ++i, ++ptr) *ptr = EEPROM.read(addr++); } lastTemp = TEMP_ERROR; lastOutsideTemp = TEMP_ERROR; // Serial.printf("host_name %s\n", config.host_name); // Serial.printf("use_mqtt %d\n", config.use_mqtt); // Serial.printf("mqqt_ip_addr %s\n", config.mqtt_ip_addr); // Serial.printf("mqtt_ip_port %d\n", config.mqtt_ip_port); // Serial.printf("mode %d\n", config.mode); // Serial.printf("fan %d\n", config.fan); // Serial.printf("temperature_span %d\n", config.temperature_span); // Serial.printf("display_timeout %d\n", config.display_timeout); // Serial.printf("out_temp %d\n", config.out_temp); // Serial.printf("swap_sensors %d\n", config.swap_sensors); // Serial.printf("use_temp %d\n", config.use_temp); // Serial.printf("temp_ip_addr %s\n", config.temp_ip_addr); // Serial.printf("temp_ip_port %d\n", config.temp_ip_port); // Serial.printf("wu_key %s\n", config.wu_key); // Serial.printf("wu_location %s\n", config.wu_location); } void loadProgramConfig(void) { if (isMemoryReset) { // nothing saved in eeprom, use defaults println(F("using default programs")); initProgram(); } else { println(F("loading programs from eeprom")); int addr = PROGRAM_ADDRESS; byte *ptr = (byte *)&program; for (int i = 0; i < sizeof(program); ++i, ++ptr, ++addr) *ptr = EEPROM.read(addr); } } void saveConfig(void) { isPromModified = false; update(MAGIC_NUM_ADDRESS, MAGIC_NUM); byte *ptr = (byte *)&config; int addr = CONFIG_ADDRESS; for (int j=0; j < sizeof(config); ++j, ++ptr) update(addr++, *ptr); if (isPromModified) EEPROM.commit(); } void saveProgramConfig(void) { isPromModified = false; Serial.printf("saving programs to eeprom\n"); int addr = PROGRAM_ADDRESS; byte *ptr = (byte *)&program; for (int i = 0; i < sizeof(program); ++i, ++ptr, ++addr) update(addr, *ptr); if (isPromModified) EEPROM.commit(); } void update(int addr, byte data) { if (EEPROM.read(addr) != data) { EEPROM.write(addr, data); isPromModified = true; } } void setupOta(void) { // Port defaults to 8266 // ArduinoOTA.setPort(8266); // Hostname defaults to esp8266-[ChipID] ArduinoOTA.setHostname(config.host_name); // No authentication by default // ArduinoOTA.setPassword("admin"); // Password can be set with it's md5 value as well // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3 // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3"); ArduinoOTA.onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) { type = "sketch"; } else { // U_FS type = "filesystem"; } // NOTE: if updating FS this would be the place to unmount FS using FS.end() Serial.println("Start updating " + type); }); ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); const char *msg = "Unknown Error"; if (error == OTA_AUTH_ERROR) { msg = "Auth Failed"; } else if (error == OTA_BEGIN_ERROR) { msg = "Begin Failed"; } else if (error == OTA_CONNECT_ERROR) { msg = "Connect Failed"; } else if (error == OTA_RECEIVE_ERROR) { msg = "Receive Failed"; } else if (error == OTA_END_ERROR) { msg = "End Failed"; } Serial.println(msg); }); ArduinoOTA.begin(); println(F("Arduino OTA ready")); char host[20]; sprintf(host, "%s-webupdate", config.host_name); MDNS.begin(host); httpUpdater.setup(&server); MDNS.addService("http", "tcp", 80); println(F("Web OTA ready")); } void setupMqtt() { client.setServer(config.mqtt_ip_addr, config.mqtt_ip_port); client.setCallback(callback); } void logTemperature(float inside, float outside) { if (config.use_mqtt) { // mqtt char topic[30]; sprintf(topic, "%s/temperature", config.host_name); char json[128]; sprintf(json, "{\"inside\":\"%f\",\"outside\":\"%f\"}", inside, outside); client.publish(topic, json); } } void logAction(char action) { if (config.use_mqtt) { // mqtt char topic[30]; sprintf(topic, "%s/action", config.host_name); char buf[10]; sprintf(buf, "%c", action); client.publish(topic, buf); } } void logTarget(int temperature) { if (config.use_mqtt) { // mqtt char topic[30]; sprintf(topic, "%s/target", config.host_name); char buf[10]; sprintf(buf, "%d", temperature); client.publish(topic, buf); } } void requestOutsideTemperature(void) { AsyncClient* aclient = new AsyncClient(); aclient->onConnect([](void *obj, AsyncClient* c) { // Serial.printf("[A-TCP] onConnect\n"); // after connecting, send the request, and wait for a reply // Make an HTTP GET request c->write(WUNDERGROUND_REQ1); c->write(config.wu_key); c->write(WUNDERGROUND_REQ2); c->write(config.wu_location); c->write(WUNDERGROUND_REQ3); }, NULL); aclient->onDisconnect([](void *obj, AsyncClient* c) { // Serial.printf("[A-TCP] onDisconnect\n"); free(c); }, NULL); aclient->onError([](void *obj, AsyncClient* c, int8_t err) { // Serial.printf("requestOutsideTemperature [A-TCP] onError: %s\n", c->errorToString(err)); }, NULL); aclient->onData([](void *obj, AsyncClient* c, void *buf, size_t len) { // Serial.printf("[A-TCP] onData: %s\n", buf); // search for the temperature in the response const char *target = "\"temp_f\":"; char *ptr = strstr((char *)buf, target); if (ptr != NULL) { ptr += strlen(target); int temp = strtol(ptr, &ptr, 10); Serial.print("outside temp is "); Serial.println(temp); gotOutsideTemperature((float)temp); c->close(true); // close right now...no more onData } }, NULL); // Serial.printf("request temp\n"); if (!aclient->connect(WUNDERGROUND, 80)) { free(aclient); } } void gotOutsideTemperature(float tempF) { if ( tempF != lastOutsideTemp ) { lastOutsideTemp = tempF; printOutsideTemperature(true); } // log the temperatures to the database if (lastTemp != TEMP_ERROR && lastOutsideTemp != TEMP_ERROR) logTemperature(lastTemp, lastOutsideTemp); } //format bytes String formatBytes(size_t bytes){ if (bytes < 1024){ return String(bytes)+"B"; } else if(bytes < (1024 * 1024)){ return String(bytes/1024.0)+"KB"; } else if(bytes < (1024 * 1024 * 1024)){ return String(bytes/1024.0/1024.0)+"MB"; } else { return String(bytes/1024.0/1024.0/1024.0)+"GB"; } } String getContentType(String filename){ if(server.hasArg("download")) return "application/octet-stream"; else if(filename.endsWith(".htm")) return "text/html"; else if(filename.endsWith(".html")) return "text/html"; else if(filename.endsWith(".css")) return "text/css"; else if(filename.endsWith(".js")) return "application/javascript"; else if(filename.endsWith(".png")) return "image/png"; else if(filename.endsWith(".gif")) return "image/gif"; else if(filename.endsWith(".jpg")) return "image/jpeg"; else if(filename.endsWith(".ico")) return "image/x-icon"; else if(filename.endsWith(".xml")) return "text/xml"; else if(filename.endsWith(".pdf")) return "application/x-pdf"; else if(filename.endsWith(".zip")) return "application/x-zip"; else if(filename.endsWith(".gz")) return "application/x-gzip"; return "text/plain"; } bool handleFileRead(String path){ Serial.println("handleFileRead: " + path); if(path.endsWith("/")) path += "index.htm"; String contentType = getContentType(path); String pathWithGz = path + ".gz"; if(SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)){ if(SPIFFS.exists(pathWithGz)) path += ".gz"; File file = SPIFFS.open(path, "r"); size_t sent = server.streamFile(file, contentType); file.close(); return true; } return false; } void handleFileUpload_edit(){ HTTPUpload& upload = server.upload(); if(upload.status == UPLOAD_FILE_START){ String filename = upload.filename; if(!filename.startsWith("/")) filename = "/"+filename; Serial.print("handleFileUpload Name: "); Serial.println(filename); fsUploadFile = SPIFFS.open(filename, "w"); filename = String(); } else if(upload.status == UPLOAD_FILE_WRITE){ //Serial.print("handleFileUpload Data: "); Serial.println(upload.currentSize); if(fsUploadFile) fsUploadFile.write(upload.buf, upload.currentSize); } else if(upload.status == UPLOAD_FILE_END){ if(fsUploadFile) fsUploadFile.close(); Serial.print("handleFileUpload Size: "); Serial.println(upload.totalSize); } } void handleFileDelete(){ if(server.args() == 0) return server.send(500, "text/plain", "BAD ARGS"); String path = server.arg(0); Serial.print(F("handleFileDelete: ")); Serial.println(path); if(path == "/") return server.send(500, "text/plain", "BAD PATH"); if(!SPIFFS.exists(path)) return server.send(404, "text/plain", "FileNotFound"); SPIFFS.remove(path); server.send(200, "text/plain", ""); path = String(); } void handleFileCreate(){ if(server.args() == 0) return server.send(500, "text/plain", "BAD ARGS"); String path = server.arg(0); Serial.print(F("handleFileCreate: ")); Serial.println(path); if(path == "/") return server.send(500, "text/plain", "BAD PATH"); if(SPIFFS.exists(path)) return server.send(500, "text/plain", "FILE EXISTS"); File file = SPIFFS.open(path, "w"); if(file) file.close(); else return server.send(500, "text/plain", "CREATE FAILED"); server.send(200, "text/plain", ""); path = String(); } void handleFileList() { if(!server.hasArg("dir")) {server.send(500, "text/plain", "BAD ARGS"); return;} String path = server.arg("dir"); Serial.print(F("handleFileList: ")); Serial.println(path); Dir dir = SPIFFS.openDir(path); path = String(); String output = "["; while(dir.next()){ File entry = dir.openFile("r"); if (output != "[") output += ','; bool isDir = false; output += "{\"type\":\""; output += (isDir)?"dir":"file"; output += "\",\"name\":\""; output += String(entry.name()).substring(1); output += "\"}"; entry.close(); } output += "]"; server.send(200, "text/json", output); } void countRootFiles(void) { int num = 0; size_t totalSize = 0; Dir dir = SPIFFS.openDir("/"); while (dir.next()) { ++num; String fileName = dir.fileName(); size_t fileSize = dir.fileSize(); totalSize += fileSize; Serial.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str()); } Serial.printf("FS File: serving %d files, size: %s from /\n", num, formatBytes(totalSize).c_str()); } void setupWebServer(void) { SPIFFS.begin(); countRootFiles(); //list directory server.on("/list", HTTP_GET, handleFileList); //load editor server.on("/edit", HTTP_GET, [](){ if(!handleFileRead("/edit.htm")) server.send(404, "text/plain", "FileNotFound"); }); //create file server.on("/edit", HTTP_PUT, handleFileCreate); //delete file server.on("/edit", HTTP_DELETE, handleFileDelete); //first callback is called after the request has ended with all parsed arguments //second callback handles file uploads at that location server.on("/edit", HTTP_POST, [](){ server.send(200, "text/plain", ""); }, handleFileUpload_edit); //called when the url is not defined here //use it to load content from SPIFFS server.onNotFound([](){ if(!handleFileRead(server.uri())) server.send(404, "text/plain", "FileNotFound"); }); server.begin(); Serial.println(F("HTTP server started")); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // // Create a random client ID // String clientId = "ESP8266Client-"; // clientId += String(random(0xffff), HEX); // // Attempt to connect // if (client.connect(clientId.c_str())) { if (client.connect(config.host_name)) { Serial.println("connected"); // ... and resubscribe char topic[30]; sprintf(topic, "%s/command", config.host_name); client.subscribe(topic); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } void callback(char* topic, byte* payload, unsigned int length) { // only topic we get is <host_name>/command // strip off the hostname from the topic topic += strlen(config.host_name) + 1; char value[12]; memcpy(value, payload, length); value[length] = '\0'; Serial.printf("Message arrived [%s] %s\n", topic, value); if (strcmp(topic, "command") == 0) { char action = *value; if (action == SYSTEM_OFF) { // cpd // config.mode = RUN; // modeChange(false); } else if (action == SYSTEM_FAN) { // cpd // config.mode = OFF; // modeChange(false); } else if (action == SYSTEM_HEAT) { // cpd // config.mode = OFF; // modeChange(false); } else if (action == SYSTEM_COOL) { // cpd // config.mode = OFF; // modeChange(false); } else { Serial.printf("Unknown action: %c\n", action); } } else { Serial.printf("Unknown topic: %s\n", topic); } } /* cpd...todo add wires to header for outside temp plug add 2nd temp sensor (sw done...just add the sensor) websockerclient if server restarts, we don't get a disconnect..just no more updates todo: implement a ping every 30 seconds. if no reply, then disconnect, and connect if server isn't running, we get disconnect messages over and over again...app is basically frozen when server starts, it connects, and all is well. after we get the disconnect message, we set a flag and start a timer when the flag is set, we don't call loop anymore for the ws client after 30 seconds, we call begin again....this works but kinda freezes the app if the connection doesn't happen right away try the websocket async method. test mode 00111111 - 63 - all off, no movement, display on 10111111 - 191 - all off, movement, display on 01111111 - 127 - all off, no movement, display off 00101111 - 47 - fan on, no movement, display on 00000111 - 7 - fan on, compressor on, display on dials on the motion sensor: left....doesn't seem to matter....set to middle right..must be turned all the way counter clockwise....otherwise, it false triggers...even thenn it is too sensitive i think this is caused by running it at 3.3 instead of 5v */
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "AnimationTestGameModeBase.h"
#pragma once #include <iberbar/Base/Platform.h> namespace iberbar { class CFpsTick { public: void update( int64 nElapsedTime ) { m_iFrameCount ++; m_fFpsTimeSlice += nElapsedTime; // if ( m_iFrameCount == 5 ) // { // float lc_fFpsTimeCur = GetElapseTimeS(); // m_fFpsTimeSlice = lc_fFpsTimeCur - m_fFpsTimePre; // m_fFPS = (float)m_iFrameCount / m_fFpsTimeSlice; // // m_fFpsTimePre = lc_fFpsTimeCur; // m_iFrameCount = 0; // } if ( m_fFpsTimeSlice > 1.0f ) { m_fFPS = (float)m_iFrameCount / m_fFpsTimeSlice; m_iFrameCount = 0; m_fFpsTimeSlice = 0.0f; } } private: int32 m_iFrameCount; int64 m_fFPS; int64 m_fFpsTimePre; int64 m_fFpsTimeSlice; }; }
#include "integration.hpp" #include <cmath> #include "../datastructures/multi_tree_view.hpp" #include "bases.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" using datastructures::static_for; namespace Time { TEST(Integration, Monomials) { Bases B; B.elem_tree.UniformRefine(4); static_for<10>([&](auto degree) { for (auto elem : B.elem_tree.Bfs()) { for (size_t n = 0; n < degree; n++) { auto f = [n](double x) { return pow(x, n); }; auto [a, b] = elem->Interval(); auto result = Integrate(f, *elem, degree); auto expected = (pow(b, n + 1) - pow(a, n + 1)) / (n + 1); EXPECT_NEAR(result, expected, 1e-10); } } }); } }; // namespace Time
#include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> #include <limits.h> #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "util.h" namespace util { using namespace std; vector<string> argv_to_strvec(int count, char** const argv) { vector<string> vargv; for(int i = 0; i < count; ++i) { vargv.emplace_back(argv[i]); } return vargv; } bool is_absolute_path(const std::string& path) { return path.length() > 0 && path[0] == '/'; } // TODO(andrei) Proper varadic function. std::string merge_paths(const std::string& path) { return path; } std::string merge_paths(const std::string& path1, const std::string& path2) { return path1 + "/" + path2; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::string merge_with(const std::vector<std::string>::iterator& start, const std::vector<std::string>::iterator& end, const std::string delimitator) { std::stringstream ss; for(auto it = start; it != end; ++it) { ss << *it; if(it + 1 != end) { ss << delimitator; } } return ss.str(); } char** get_raw_array(const std::vector<std::string>& v) { char** ret = new char*[v.size() + 1]; for(size_t i = 0; i < v.size(); ++i) { ret[i] = ::strdup(v[i].c_str()); } ret[v.size()] = nullptr; return ret; } bool getcwd(std::string *cwd) { // Note: PATH_MAX might not be sufficient. // See: insanecoding.blogspot.com/2007/11/pathmax-simply-isnt.html static char dir[PATH_MAX]; if(::getcwd(dir, sizeof(dir))) { *cwd = std::string(dir); return true; } return false; } bool setcwd(const std::string& cwd) { return 0 == ::chdir(cwd.c_str()); } bool is_file(const string& name) { struct stat stat_buf; return 0 == ::stat(name.c_str(), &stat_buf); } bool is_regular_file(const std::string& name) { struct stat stat_buf; if(0 == ::stat(name.c_str(), &stat_buf)) { return S_ISREG(stat_buf.st_mode); } return false; } bool is_directory(const std::string& name) { struct stat stat_buf; if(0 == ::stat(name.c_str(), &stat_buf)) { return S_ISDIR(stat_buf.st_mode); } return false; } string get_current_home() { char* home; if(nullptr == (home = ::getenv("HOME"))) { home = ::getpwuid(::getuid())->pw_dir; return string(home); } else { string ret(home); return ret; } } string get_current_user() { return string(::getpwuid(::getuid())->pw_name); } } // namespace util
#ifndef VECTOR_H #define VECTOR_H namespace phys { class Vector { public: Vector(); Vector(double x, double y, double z); double getX() const; double getY() const; double getZ() const; Vector sign(); Vector operator+ (Vector rhs); Vector operator- (Vector rhs); Vector operator* (Vector rhs); Vector operator/ (double number); Vector operator* (double number); Vector operator+ (double number); Vector operator- (double number); Vector operator- (); bool operator== (const Vector rhs) const; Vector abs(); double norm(); double dot(Vector rhs); Vector saturate(double min_val, double max_val); void setVector(Vector vec); private: double m_x{0}; double m_y{0}; double m_z{0}; }; Vector operator- (double lhs, Vector rhs); Vector operator+ (double lhs, Vector rhs); Vector operator* (double lhs, Vector rhs); double saturateNumber(double value, double min_val, double max_val); } #endif // VECTOR_H
// Created on: 1994-01-10 // Created by: Yves FRICAUD // Copyright (c) 1994-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 _Bisector_BisecPC_HeaderFile #define _Bisector_BisecPC_HeaderFile #include <Standard.hxx> #include <gp_Pnt2d.hxx> #include <TColStd_SequenceOfReal.hxx> #include <Standard_Integer.hxx> #include <Bisector_Curve.hxx> #include <GeomAbs_Shape.hxx> class Geom2d_Curve; class Geom2d_Geometry; class gp_Trsf2d; class gp_Vec2d; class Bisector_BisecPC; DEFINE_STANDARD_HANDLE(Bisector_BisecPC, Bisector_Curve) //! Provides the bisector between a point and a curve. //! the curvature on the curve has to be monoton. //! the point can't be on the curve exept at the extremities. class Bisector_BisecPC : public Bisector_Curve { public: Standard_EXPORT Bisector_BisecPC(); //! Constructs the bisector between the point <P> and //! the curve <Cu>. //! <Side> = 1. if the bisector curve is on the Left of <Cu> //! else <Side> = -1. //! <DistMax> is used to trim the bisector.The distance //! between the points of the bisector and <Cu> is smaller //! than <DistMax>. Standard_EXPORT Bisector_BisecPC(const Handle(Geom2d_Curve)& Cu, const gp_Pnt2d& P, const Standard_Real Side, const Standard_Real DistMax = 500); //! Constructs the bisector between the point <P> and //! the curve <Cu> Trimmed by <UMin> and <UMax> //! <Side> = 1. if the bisector curve is on the Left of <Cu> //! else <Side> = -1. //! Warning: the bisector is supposed all over defined between //! <UMin> and <UMax>. Standard_EXPORT Bisector_BisecPC(const Handle(Geom2d_Curve)& Cu, const gp_Pnt2d& P, const Standard_Real Side, const Standard_Real UMin, const Standard_Real UMax); //! Construct the bisector between the point <P> and //! the curve <Cu>. //! <Side> = 1. if the bisector curve is on the Left of <Cu> //! else <Side> = -1. //! <DistMax> is used to trim the bisector.The distance //! between the points of the bisector and <Cu> is smaller //! than <DistMax>. Standard_EXPORT void Perform (const Handle(Geom2d_Curve)& Cu, const gp_Pnt2d& P, const Standard_Real Side, const Standard_Real DistMax = 500); //! Returns True if the bisector is extended at start. Standard_EXPORT Standard_Boolean IsExtendAtStart() const Standard_OVERRIDE; //! Returns True if the bisector is extended at end. Standard_EXPORT Standard_Boolean IsExtendAtEnd() const Standard_OVERRIDE; //! Changes the direction of parametrization of <me>. //! The orientation of the curve is modified. If the curve //! is bounded the StartPoint of the initial curve becomes the //! EndPoint of the reversed curve and the EndPoint of the initial //! curve becomes the StartPoint of the reversed curve. Standard_EXPORT void Reverse() Standard_OVERRIDE; //! Returns the parameter on the reversed curve for //! the point of parameter U on <me>. Standard_EXPORT Standard_Real ReversedParameter (const Standard_Real U) const Standard_OVERRIDE; Standard_EXPORT Handle(Geom2d_Geometry) Copy() const Standard_OVERRIDE; //! Transformation of a geometric object. This tansformation //! can be a translation, a rotation, a symmetry, a scaling //! or a complex transformation obtained by combination of //! the previous elementaries transformations. Standard_EXPORT void Transform (const gp_Trsf2d& T) Standard_OVERRIDE; //! Returns the order of continuity of the curve. //! Raised if N < 0. Standard_EXPORT Standard_Boolean IsCN (const Standard_Integer N) const Standard_OVERRIDE; //! Value of the first parameter. Standard_EXPORT Standard_Real FirstParameter() const Standard_OVERRIDE; //! Value of the last parameter. Standard_EXPORT Standard_Real LastParameter() const Standard_OVERRIDE; Standard_EXPORT GeomAbs_Shape Continuity() const Standard_OVERRIDE; //! If necessary, breaks the curve in intervals of //! continuity <C1>. And returns the number of //! intervals. Standard_EXPORT Standard_Integer NbIntervals() const Standard_OVERRIDE; //! Returns the first parameter of the current //! interval. Standard_EXPORT Standard_Real IntervalFirst (const Standard_Integer Index) const Standard_OVERRIDE; //! Returns the last parameter of the current //! interval. Standard_EXPORT Standard_Real IntervalLast (const Standard_Integer Index) const Standard_OVERRIDE; Standard_EXPORT GeomAbs_Shape IntervalContinuity() const; Standard_EXPORT Standard_Boolean IsClosed() const Standard_OVERRIDE; Standard_EXPORT Standard_Boolean IsPeriodic() const Standard_OVERRIDE; //! Returns the distance between the point of //! parameter U on <me> and my point or my curve. Standard_EXPORT Standard_Real Distance (const Standard_Real U) const; Standard_EXPORT void D0 (const Standard_Real U, gp_Pnt2d& P) const Standard_OVERRIDE; Standard_EXPORT void D1 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V) const Standard_OVERRIDE; Standard_EXPORT void D2 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2) const Standard_OVERRIDE; Standard_EXPORT void D3 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2, gp_Vec2d& V3) const Standard_OVERRIDE; Standard_EXPORT gp_Vec2d DN (const Standard_Real U, const Standard_Integer N) const Standard_OVERRIDE; Standard_EXPORT void Dump (const Standard_Integer Deep = 0, const Standard_Integer Offset = 0) const; //! Returns the parameter on the curve1 of the projection //! of the point of parameter U on <me>. Standard_EXPORT Standard_Real LinkBisCurve (const Standard_Real U) const; //! Returns the reciproque of LinkBisCurve. Standard_EXPORT Standard_Real LinkCurveBis (const Standard_Real U) const; //! Returns the parameter on <me> corresponding to <P>. Standard_EXPORT Standard_Real Parameter (const gp_Pnt2d& P) const Standard_OVERRIDE; //! Returns <True> if the bisector is empty. Standard_EXPORT Standard_Boolean IsEmpty() const; DEFINE_STANDARD_RTTIEXT(Bisector_BisecPC,Bisector_Curve) protected: private: Standard_EXPORT void Values (const Standard_Real U, const Standard_Integer N, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2, gp_Vec2d& V3) const; Standard_EXPORT void Extension (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2, gp_Vec2d& V3) const; //! Computes the interval where the bisector is defined. Standard_EXPORT void ComputeIntervals(); Standard_EXPORT void CuspFilter(); Standard_EXPORT Standard_Real SearchBound (const Standard_Real U1, const Standard_Real U2) const; Standard_EXPORT void Init (const Handle(Geom2d_Curve)& Curve, const gp_Pnt2d& Point, const Standard_Real Sign, const TColStd_SequenceOfReal& StartIntervals, const TColStd_SequenceOfReal& EndIntervals, const Standard_Integer BisInterval, const Standard_Integer CurrentInterval, const Standard_Real ShiftParameter, const Standard_Real DistMax, const Standard_Boolean IsEmpty, const Standard_Boolean IsConvex, const Standard_Boolean ExtensionStart, const Standard_Boolean ExtensionEnd, const gp_Pnt2d& PointStartBis, const gp_Pnt2d& PointEndBis); Handle(Geom2d_Curve) curve; gp_Pnt2d point; Standard_Real sign; TColStd_SequenceOfReal startIntervals; TColStd_SequenceOfReal endIntervals; Standard_Integer bisInterval; Standard_Integer currentInterval; Standard_Real shiftParameter; Standard_Real distMax; Standard_Boolean isEmpty; Standard_Boolean isConvex; Standard_Boolean extensionStart; Standard_Boolean extensionEnd; gp_Pnt2d pointStartBis; gp_Pnt2d pointEndBis; }; #endif // _Bisector_BisecPC_HeaderFile
#include "employee.h" void Employee::setOffice(string str) { switch(str[0]) { case '0': office_ = "Millwright"; break; case '1': office_ = "Electronics"; break; case '2': office_ = "Developer"; break; default: office_ = "NO OFFICE"; break; } }
/* * @Fichier : classControl.h * @Auteur : Adam Martineau * @Date : 1/dec/2018 * @Bref : librairie pour controler et intéragire avec le robot * @Environnement : PlatformIO (visual studio code) * @Compilateur : c++ * @Matériel : arduino mega * @Revision : v2 */ //INCLUDES #include <LibRobus.h> #include <avr/eeprom.h> //DEFINES #define capt_1 A9 #define capt_2 A11 #define capt_3 A12 #define NBR_INGREDIENT 1 #define Pain 2 #define Fromage 3 #define Salade 4 #define Boulette 3 #define Poele 6 #define Drop 7 //CLASS DEFINITION class classControl { public: //--- LISTES DES VAR GLOBAL ---// bool is_menu_setup = false;//true: menu princ false: menu setup //index et structure du menu principal int index_menu = 1; char menu_main[6][20] = {"", "PATE DE CRABE", "COMBO CROUSTILLANT", "CRABE DELUXE", "Setup", ""}; //index et structure du menu principal int index_setup = 1; char menu_setup[6][20] = {"", "Calibration", "Afficher valeur M.", "Debuging", "Quitter", ""}; //valeur de threshold de pour les detecteurs de ligne int threshold_1 = eeprom_read_byte((uint8_t *)1) * 5; int threshold_2 = eeprom_read_byte((uint8_t *)2) * 5; int threshold_3 = eeprom_read_byte((uint8_t *)3) * 5; //valeur pour les vitesses de moteurs //la vitesse des moteurs est modifier en //modifiant ces valeurs float moteur_g = 0.1; float moteur_d = 0.1; //variable pour la gestion des stations bool flag = false; bool fini = false; int station = -1; /// --- DÉPLACEMENT --- /// /* * @Nom : mouvement() * @Brief : fonction principal pour le déplacement du robot * @Entré : void * @Sortie : void */ void mouvement(int bonneStation); /* * @Nom : read() * @Brief : lit le capteur de ligne * @Entré : void * @Sortie : retourn une valeur binaire (de 000 a 111) le bit 001 corespond * au capteur a droite, 010 lui au centre et 100 lui a gauche. Donc une ligne * perpandiculaire serais une valeur de 7 (111) */ int read(); /* * @Nom : avance() * @Brief : fait avence les deux moteurs à la meme vitesse * @Entré : void * @Sortie : void */ void avance(); /* * @Nom : alignement_d() * @Brief : fait avence le moteur de gauche plus rapidement pour * retourne vers la droite * @Entré : void * @Sortie : void */ void alignement_d(); /* * @Nom : alignement_g * @Brief : fait avence le moteur de droite plus rapidement pour * retourne vers la gauche * @Entré : void * @Sortie : void */ void alignement_g(); /* * @Nom : detect_station() * @Brief : fonction appele quand on detecte un station (ligne * perpendiculaire) et fait les action aproprie * @Entré : void * @Sortie : void */ bool detect_station(int bonneStation); /* * @Nom : turn_station() * @Brief : appele quand on detecte un station et qu'on veux tourne * a 90 degre pour aller rejoindre la station * @Entré : void * @Sortie : void */ void turn_Sort_station(bool direction); /* * @Nom : turn_station() * @Brief : appele quand on detecte un station et qu'on veux tourne * a 90 degre pour aller rejoindre la station * @Entré : void * @Sortie : void */ void turn_station(bool direction); /* * @Nom : mouvement_Station() * @Brief : suit la ligne jusqu'a la prochaine ligne perpendiculaire * @Entré : void * @Sortie : void */ void mouvement_Station(); /* * @Nom : mouvement_Fin() * @Brief : suit la ligne jusqu'a ce qu'elle n'existe plus * @Entré : void * @Sortie : void */ void mouvement_Fin(); /* * @Nom : demiTour() * @Brief : Fait un demi-tour * @Entré : void * @Sortie : void */ void demiTour(bool direction); /* * @Nom : quartTour(bool) * @Brief : fait un quart de tour du sens voulu * @Entré : indique la direction a tourner * @Sortie : void */ void quartTour(bool direction); /* * @Nom : prendreIngredient() * @Brief : Prend les ingredients * @Entré : void * @Sortie : void */ void prendreIngredient(); /* * @Nom : lacherIngredient() * @Brief : Laisse tomber l'ingredient * @Entré : void * @Sortie : void */ void lacherIngredient(); /* * @Nom : retourner() * @Brief : retourne à sa position initial * @Entré : void * @Sortie : void */ void retourner(); /*@Nom : allerPorter(bool) * @Brief : envoi les ingredients a la drop * @Entré : indique la direction qu'il doit aller * @Sortie : void */ void allerPorter(bool direction); /* * @Nom : bouletteStation() * @Brief : Handle la boulette de son arrivé au poele a la drop * @Entré : void * @Sortie : void */ void bouletteStation(); /// --- GESTION DE LA MANETTE ---/// /* * @Nom : gestion_ * @Brief : * @Entré : * @Sortie : */ void gestion_manette(); /* * @Nom : get_ir * @Brief : trete les donnes recu par le capteur infrarouge et retourne la commande * @Entré : void * @Sortie : un char qui décrie la commande recu */ int get_ir(); /// --- LCD REFRESH --- /// /* * @Nom : get_ir() * @Brief : fonction qui apelle soit la fonction la fonction * refresh main ou refresh setup dépendant on est dans quelle menu * @Entré : void * @Sortie : void */ void refresh_LCD(); /* * @Nom : refresh_main() * @Brief : refresh l'affichage du menu quand on est dans le * menu principal * @Entré : void * @Sortie : void */ void refresh_main(); /* * @Nom : refresh_setup() * @Brief : refresh l'affichage du menu setup quand on est dans le * menu principal * @Entré : void * @Sortie : void */ void refresh_setup(); /// --- GESTION DES OPTION DE MENU --- /// /* * @Nom : menu_enter() * @Brief : fonction appele quand on detecte un «enter» pour le menu * @Entré : void * @Sortie : void */ void menu_enter(); /// --- ASSEMBLAGE DES BURGERS --- /// /* * @Nom : burger1() * @Brief : assemblage du burger 1 * @Entré : void * @Sortie : void */ void burger1(); /* * @Nom : burger2() * @Brief : assemblage du burger 2 * @Entré : void * @Sortie : void */ void burger2(); /* * @Nom : burger3() * @Brief : assemblage du burger 3 * @Entré : void * @Sortie : void */ void burger3(); /// --- CALIBRATION --- /// /* * @Nom : calibration() * @Brief : fonction pour calibre les detecteur de ligne * @Entré : void * @Sortie : void */ void calibration(); /* * @Nom : print_values() * @Brief : print les valeur mediane de calibration enregistre dans * la EEPROM * @Entré : void * @Sortie : void */ void print_values(); }; //FONCTIONS DEFINITION void classControl::gestion_manette() { int remote = get_ir(); //gestion de déplacement dans le menu if(remote == 2) { if (!is_menu_setup) { index_menu++; if(index_menu == 5) { index_menu = 1; } } else { index_setup++; if(index_setup == 5) { index_setup = 1; } } refresh_LCD(); } else if(remote == 1) { if (!is_menu_setup) { index_menu--; if(index_menu == 0) { index_menu = 4; } } else { index_setup--; if(index_setup == 5) { index_setup = 5; } } refresh_LCD(); } else if(remote == 0 || remote == 4) { menu_enter(); } } int classControl::get_ir() { int retour = -1; uint32_t remote = REMOTE_read(); if(remote == 0x6604CFC6) //haut retour = 1; else if(remote == 0x6604CFFA) //bas retour = 2; else if(remote == 0x6604CFD6) //gauche retour = 3; else if(remote == 0x6604CFE6) //droite retour = 4; else if(remote == 0x6604CFF6) //enter retour = 0; return retour; } void classControl::refresh_LCD() { if (!is_menu_setup) refresh_main(); else refresh_setup(); } void classControl::refresh_main() { DISPLAY_Clear(); DISPLAY_SetCursor(0,0); DISPLAY_Printf(" "); DISPLAY_Printf(menu_main[index_menu - 1]); DISPLAY_SetCursor(1,0); DISPLAY_Printf(">>"); DISPLAY_Printf(menu_main[index_menu]); DISPLAY_SetCursor(2,0); DISPLAY_Printf(" "); DISPLAY_Printf(menu_main[index_menu + 1]); } void classControl::refresh_setup() { DISPLAY_Clear(); DISPLAY_SetCursor(0,0); DISPLAY_Printf(" "); DISPLAY_Printf(menu_setup[index_setup - 1]); DISPLAY_SetCursor(1,0); DISPLAY_Printf(">>"); DISPLAY_Printf(menu_setup[index_setup]); DISPLAY_SetCursor(2,0); DISPLAY_Printf(" "); DISPLAY_Printf(menu_setup[index_setup + 1]); } void classControl::menu_enter() { if(index_menu == 1 && !is_menu_setup) burger1(); else if(index_menu == 2 && !is_menu_setup) burger2(); else if(index_menu == 3 && !is_menu_setup) burger3(); else if(index_menu == 4 && !is_menu_setup) { index_menu = 1; is_menu_setup = !is_menu_setup; refresh_LCD(); } else if(index_setup == 1 && is_menu_setup) { calibration(); } else if(index_setup == 2 && is_menu_setup) { print_values(); } else if(index_setup == 3 && is_menu_setup) { while(true) { DISPLAY_Clear(); DISPLAY_SetCursor(0,0); DISPLAY_Printf((String) read()); delay(500); } } else if(index_setup == 4 && is_menu_setup) { index_setup = 1; is_menu_setup = !is_menu_setup; refresh_LCD(); } } void classControl::print_values() { DISPLAY_Clear(); DISPLAY_SetCursor(0,0); DISPLAY_Printf("Cap1:"); DISPLAY_Printf((String) (eeprom_read_byte((uint8_t *)1) * 5)); DISPLAY_SetCursor(1,0); DISPLAY_Printf("Cap2:"); DISPLAY_Printf((String) (eeprom_read_byte((uint8_t *)2) * 5)); DISPLAY_SetCursor(2,0); DISPLAY_Printf("Cap3:"); DISPLAY_Printf((String) (eeprom_read_byte((uint8_t *)3) * 5)); while(get_ir() != 0){} refresh_LCD(); } void classControl::calibration() { DISPLAY_Clear(); DISPLAY_SetCursor(0,0); DISPLAY_Printf("Calib. du noir"); while(get_ir() != 0){} DISPLAY_Clear(); DISPLAY_SetCursor(0,0); int a1 = analogRead(capt_1); int b1 = analogRead(capt_2); int c1 = analogRead(capt_3); DISPLAY_Printf("Cap1:"); DISPLAY_Printf((String) a1); DISPLAY_SetCursor(1,0); DISPLAY_Printf("Cap2:"); DISPLAY_Printf((String) b1); DISPLAY_SetCursor(2,0); DISPLAY_Printf("Cap3:"); DISPLAY_Printf((String) c1); while(get_ir() != 0){} DISPLAY_Clear(); DISPLAY_SetCursor(0,0); DISPLAY_Printf("Calib. du blanc"); while(get_ir() != 0){} DISPLAY_Clear(); DISPLAY_SetCursor(0,0); int a2 = analogRead(capt_1); int b2 = analogRead(capt_2); int c2 = analogRead(capt_3); DISPLAY_Printf("Cap1:"); DISPLAY_Printf((String) a2); DISPLAY_SetCursor(1,0); DISPLAY_Printf("Cap2:"); DISPLAY_Printf((String) b2); DISPLAY_SetCursor(2,0); DISPLAY_Printf("Cap3:"); DISPLAY_Printf((String) c2); while(get_ir() != 0){} DISPLAY_Clear(); DISPLAY_SetCursor(0,0); int a = a1 + a2; a = a / 2; int b = b1 + b2; b = b / 2; int c = c1 + c2; c = c / 2; DISPLAY_Printf("Thr1:"); DISPLAY_Printf((String) a); DISPLAY_SetCursor(1,0); DISPLAY_Printf("Thr2:"); DISPLAY_Printf((String) b); DISPLAY_SetCursor(2,0); DISPLAY_Printf("Thr3:"); DISPLAY_Printf((String) c); while(get_ir() != 0){} DISPLAY_Clear(); DISPLAY_SetCursor(0,0); eeprom_write_byte((uint8_t *)1, a / 5); eeprom_write_byte((uint8_t *)2, b / 5); eeprom_write_byte((uint8_t *)3, c / 5); threshold_1 = eeprom_read_byte((uint8_t *)1) * 5; threshold_2 = eeprom_read_byte((uint8_t *)2) * 5; threshold_3 = eeprom_read_byte((uint8_t *)3) * 5; DISPLAY_Printf("Calib. effectue"); delay(1500); refresh_LCD(); } void classControl::burger1() { mouvement(Pain); fini=false; mouvement(Boulette); fini=false; mouvement(Pain); fini=false; } void classControl::burger2() { mouvement(Pain); fini=false; mouvement(Boulette); fini=false; mouvement(Boulette); fini=false; mouvement(Pain); fini=false; } void classControl::burger3() { mouvement(Pain); fini=false; mouvement(Boulette); fini=false; mouvement(Pain); fini=false; mouvement(Pain); fini=false; } void classControl::mouvement(int bonneStation) { while(!fini) { //diagnostique MOTOR_SetSpeed(0, moteur_g); MOTOR_SetSpeed(1, moteur_d); int capteurs = read(); if(capteurs == 2)//Est centre { flag = false; avance(); } else if (capteurs == 6||capteurs==4)//Est décalé vers la gauche { flag = false; alignement_d(); } else if (capteurs == 3||capteurs==1)//Est décalé vers la droite { flag = false; alignement_g(); } else if (capteurs == 7 && flag == false)//Est à la ligne { { bool direction= bonneStation%2==0; flag = true; if(detect_station(floor((bonneStation)/2))==true)// le calcul traduit la station en nombre de ligne perpendiculaire { turn_station(direction); mouvement_Station(); if(bonneStation<5&&bonneStation!=Boulette) //Ingredients { prendreIngredient(); allerPorter(direction); } else if(bonneStation==Boulette) //Boulette { prendreIngredient(); demiTour(true); mouvement_Station(); turn_Sort_station(direction); mouvement(Poele); } else if (bonneStation==Poele) //Poele { bouletteStation(); } else if(bonneStation==Drop) //Drop { lacherIngredient(); retourner(); } } else { avance(); } } } } } void classControl::avance() { moteur_d = 0.2; moteur_g = 0.2; } void classControl::alignement_d() { moteur_d = 0.13; moteur_g = 0.2; } void classControl::alignement_g() { moteur_d = 0.2; moteur_g = 0.13; } int classControl::read() { int retourn = 0; if (analogRead(capt_3) <= threshold_3) retourn += 1; if (analogRead(capt_2) <= threshold_2) retourn += 2; if (analogRead(capt_1) <= threshold_1) retourn += 4; return retourn; } bool classControl::detect_station(int bonneStation) { station++; if (station == bonneStation) //regarde s'il est a la station voulu { return true; } else { return false; } } void classControl::turn_station(bool direction) { if(direction) { moteur_g=0; moteur_d=0.2; } else { moteur_g=0.2; moteur_d=0; } //avance un peu MOTOR_SetSpeed(0, 0.2); MOTOR_SetSpeed(1, 0.2); delay(250); //tourne pour ne plus voir la ligne MOTOR_SetSpeed(0, moteur_g); MOTOR_SetSpeed(1, moteur_d); delay(350); //tourne jusqu'a la prochaine ligne while(read() != 7){} } void classControl::turn_Sort_station(bool direction) { //avance un peu MOTOR_SetSpeed(0, 0.2); MOTOR_SetSpeed(1, 0.2); while(read()!=0){} while(read()!=7){} delay(150); //tourne d'un quart de tour quartTour(direction); } void classControl::prendreIngredient() { pince(false); delay(500); } void classControl::lacherIngredient() { pince(true);//ouvre delay(500); flip_bras(false);//vire le bras delay(800); flip_bras(true);//retourne le bras a sa position normal delay(500); } void classControl::retourner() { demiTour(true); mouvement_Station(); turn_Sort_station(true); mouvement_Fin();//Retourne sur la ligne principal demiTour(true); //réinitialise les variables pour la prochaine commande fini =true; station = -1; } void classControl::allerPorter(bool direction) { demiTour(true); mouvement_Station(); turn_Sort_station(direction); mouvement(Drop);//Avance a la chute } void classControl::demiTour(bool direction) { MOTOR_SetSpeed(direction,-0.15); MOTOR_SetSpeed(!direction,-0.15); delay(750); ENCODER_Reset(!direction); ENCODER_Reset(direction); while(89>ENCODER_Read(!direction)*0.023038563||-89<ENCODER_Read(direction)*0.023038563) { if(89>ENCODER_Read(!direction)*0.023038563)//tourne le moteur 1 tant qu'il ne fait pas 90 degree { MOTOR_SetSpeed(!direction,0.15); } else MOTOR_SetSpeed(!direction,0); if(-89<ENCODER_Read(direction)*0.023038563)//tourne le moteur 0 tant qu'il ne fait pas 90 degree { MOTOR_SetSpeed(direction,-0.1495); } else MOTOR_SetSpeed(direction,0); } MOTOR_SetSpeed(direction,0); MOTOR_SetSpeed(!direction,0); } void classControl::quartTour(bool direction) { ENCODER_Reset(direction); ENCODER_Reset(!direction); while(42>ENCODER_Read(direction)*0.023038563||-42<ENCODER_Read(!direction)*0.023038563) { if(42>ENCODER_Read(direction)*0.023038563)//tourne le moteur tant qu'il ne fait pas 45 degree { MOTOR_SetSpeed(direction,0.15); } else MOTOR_SetSpeed(direction,0); if(-42<ENCODER_Read(!direction)*0.023038563)//tourne le moteur tant qu'il ne fait pas 45 degree { MOTOR_SetSpeed(!direction,-0.1495); } else MOTOR_SetSpeed(!direction,0); } } void classControl::mouvement_Fin() { mouvement_Station(); bool Arrive=false; while(Arrive==false) { MOTOR_SetSpeed(0, moteur_g); MOTOR_SetSpeed(1, moteur_d); int capteurs = read(); if(capteurs == 2)//Est centre { flag = false; avance(); } else if (capteurs == 6||capteurs==4)//Est décalé vers la gauche { alignement_d(); } else if (capteurs == 3||capteurs==1)//Est décalé vers la droite { alignement_g(); } else if (capteurs == 7 && flag == false)//Est à la ligne { station--; if(station==-1) { MOTOR_SetSpeed(0, 0.15); MOTOR_SetSpeed(1, 0.15); delay(2000); Arrive=true; } flag =true; } } } void classControl::mouvement_Station() { //Avance jusqu'a ne plus voir de ligne while(read()==7) { MOTOR_SetSpeed(0, 0.1); MOTOR_SetSpeed(1, 0.1); } delay(200); //Avance à la prochaine ligne bool Arrive(false); while(Arrive==false) { MOTOR_SetSpeed(0, moteur_g); MOTOR_SetSpeed(1, moteur_d); int capteurs = read(); if(capteurs == 2)//Est centre { flag = false; avance(); } else if (capteurs == 6||capteurs==4)//Est décalé vers la gauche { flag = false; alignement_d(); } else if (capteurs == 3||capteurs==1)//Est décalé vers la droite { flag = false; alignement_g(); } else if (capteurs == 7 && flag == false)//Est à la ligne { //Arrete MOTOR_SetSpeed(0,0); MOTOR_SetSpeed(1,0); Arrive=true; } } } void classControl::bouletteStation() { pince(true);//ouvre delay(500); flip_bras(false);//flip le bras MOTOR_SetSpeed(1,-0.15);//recule pendant 1.5 sec MOTOR_SetSpeed(0,-0.15); delay(1500); MOTOR_SetSpeed(1,0);//arrete MOTOR_SetSpeed(0,0); flip_bras(true);//retourne son bras inferieur a la position normal delay(5000); //Attend 5 secondes mouvement_Station();//revient à la ligne delay(500); flip_bras(false);//flip le bras delay(500); MOTOR_SetSpeed(1,-0.15);//recule pendant 1.5 sec MOTOR_SetSpeed(0,-0.15); delay(1500); MOTOR_SetSpeed(1,0);//arrete MOTOR_SetSpeed(0,0); flip_bras(true);//retourne son bras inferieur a la position normal delay(5000); //Attend 5 secondes mouvement_Station(); prendreIngredient(); demiTour(false); //Retourne MOTOR_SetSpeed(0,0.15); MOTOR_SetSpeed(1,0.15); while(read()==7) delay(100); while(read()!=7){} while(read()==7) delay(100); while(read()!=7){}//bouge a la ligne de fin de la poele while(read()==7) delay(100); while(read()!=7){} mouvement_Station();//bouge a la drop lacherIngredient(); retourner(); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "cuehttp.hpp" using namespace cue::http; int main(int argc, char** argv) { router route; route.get("/plaintext", [](context& ctx) { ctx.type("text/plain"); ctx.status(200); ctx.body("Hello, World!"); }); cuehttp app; app.use(route); app.listen(8080).run(); return 0; }
#include <stdio.h> #include <string.h> #include <iostream> #include <sstream> #include "aruco.h" #include "math.h" #include "cvdrawingutils.h" #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> //#define CAMERA_NUM 1 using namespace cv; using namespace std; using namespace aruco; int width = 640; int height = 480; double exposure = 0.8; double brightness = 0.5; double contrast = 0.6; double saturation = 0.2; double hue = 0.5; double gain = 0.5; vector< Marker > TheMarkers; CameraParameters TheCameraParameters; MarkerDetector MDetector; float TheMarkerSize = 0.15; string TheIntrinsicFile="usbcam.yml"; Point2f cen; int main(int argc,char** argv) { int count=1; char num_char[3]; string num_str; Mat read_view,view,img_aruco; int CAMERA_NUM=0; if(argc>1) { CAMERA_NUM = atof(argv[1]); } else { cout<<"usage: --\"camera index\" --\"The IntrinsicFile\" --\"enable IR receive from ROS(true/false) \" "<<endl; return 0; } VideoCapture cap(CAMERA_NUM); cout<<"frame_width "<<cap.get(CV_CAP_PROP_FRAME_WIDTH)<<endl; cout<<"-----------------"<<endl; cout<<"frame_height "<<cap.get(CV_CAP_PROP_FRAME_HEIGHT)<<endl; //cap.set(CV_CAP_PROP_FOURCC ,CV_FOURCC('M', 'J', 'P', 'G') ); //cap.set(CV_CAP_PROP_FRAME_WIDTH ,width); //cap.set(CV_CAP_PROP_FRAME_HEIGHT ,height); cap.set(CV_CAP_PROP_EXPOSURE ,exposure); cap.set(CV_CAP_PROP_BRIGHTNESS ,brightness); cap.set(CV_CAP_PROP_CONTRAST,contrast); cap.set(CV_CAP_PROP_SATURATION,saturation); cap.set(CV_CAP_PROP_HUE,hue); cap.set(CV_CAP_PROP_GAIN,gain); //cap.set(CV_CAP_PROP_FPS, 25); char c; Mat CM = Mat(3, 3, CV_32FC1); Mat D; Mat viewUndistort; FileStorage fs2(TheIntrinsicFile,FileStorage::READ); fs2["camera_matrix"]>>CM; fs2["distortion_coefficients"]>>D; fs2.release(); Mat RM,TM; //Mat RT(3,1); Mat pos_tmp; Mat _RM,_TM; Mat map1,map2; cap>>view; img_aruco=view.clone(); // read camera parameters if passed TheCameraParameters.readFromXMLFile(TheIntrinsicFile); TheCameraParameters.resize(img_aruco.size()); MDetector.setThresholdParams(7, 7); MDetector.setThresholdParamRange(2, 0); initUndistortRectifyMap(CM,D,Mat(),Mat(),img_aruco.size(),CV_32FC1,map1,map2); namedWindow("Aruco", CV_WINDOW_NORMAL); while(c!='c') { c=waitKey(5); cap>>view; //img_aruco = view.clone(); //remap(view,viewUndistort,map1,map2,INTER_LINEAR); //undistort(view,viewUndistort,CM,D); //img_aruco=viewUndistort.clone(); img_aruco=view.clone(); // Detection of markers in the image passed MDetector.detect(img_aruco, TheMarkers, TheCameraParameters, TheMarkerSize); //cout<<"buffer: "<<buffer<<endl; for (unsigned int i = 0; i < TheMarkers.size(); i++) { //cout << endl << TheMarkers[i]; cen = TheMarkers[i].getCenter(); cout<<"cen["<<i<<"] "<<cen<<endl; RM=TheMarkers[i].Rvec; TM=TheMarkers[i].Tvec; cout<<"Rvec "<<RM<<endl; cout<<"Tvec "<<TM<<endl; float dis = TM.at<float>(0,0)*TM.at<float>(0,0)+TM.at<float>(1,0)*TM.at<float>(1,0)+TM.at<float>(2,0)*TM.at<float>(2,0); Rodrigues(RM,_RM); pos_tmp = _RM*TM; cout <<"POS_X "<<pos_tmp.at<float>(0,0)<<endl; cout <<"POS_Y "<<pos_tmp.at<float>(0,1)<<endl; cout <<"POS_Z "<<pos_tmp.at<float>(0,2)<<endl; cout<<"Rotation Matrix: "<< _RM<<endl; cout<<"distance "<<sqrt(dis)<<endl; TheMarkers[i].draw(img_aruco, Scalar(0, 0, 255), 1); } if (TheMarkers.size() != 0) cout << endl; // draw a 3d cube in each marker if there is 3d info if (TheCameraParameters.isValid()) for (unsigned int i = 0; i < TheMarkers.size(); i++) { CvDrawingUtils::draw3dCube(img_aruco, TheMarkers[i], TheCameraParameters); CvDrawingUtils::draw3dAxis(img_aruco, TheMarkers[i], TheCameraParameters); } imshow("view",view); imshow("Aruco",img_aruco); //imshow("thres", MDetector.getThresholdedImage()); //imshow("Video",view); //imshow("Video_undistort",viewUndistort); //setWindowProperty("Aruco", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN); if(c=='s') { sprintf(num_char,"%d",count); num_str=num_char; string Name_string="/home/chens/ghost27/ar/img/shot_"+num_str; Name_string= Name_string + ".jpg"; imwrite(Name_string, view); namedWindow("Shot View"); read_view=imread(Name_string); imshow("Shot_View",read_view); count++; } } return 0; }
#include <iostream> using namespace std; int main(void) { // 01 auto func = []() { cout << "Hello World 01" << endl; }; func(); // 02 []() { cout << "Hello World 02" << endl; }(); // 03 [](int i, int j) { cout << "Hello World 03 : i + j = " << i + j << endl; }(1, 2); // 04 int sum = [](int i, int j) -> int { return i + j; }(1, 2); cout << "Hello World 04 : i + j = " << sum << endl; // 05 cout << "Hello World 05 : i + j = " << [](int i, int j) -> int { return i + j; }(1, 2) << endl; // 06 int i = 1; int j = 2; [i, j]() { cout << "Hello World 06 : i + j = " << i + j << endl; }(); // 07 copy int k = 10; auto func1 = [k]() { cout << "Innter value : " << k << endl; }; for (int i = 0; i < 5; i++) { cout << "Outer value [" << i << "] : " << k << endl; func1(); k = k + 1; } // 08 reference int c = 10; auto func2 = [&c]() { cout << "Innter value : " << c << endl; }; for (int i = 0; i < 5; i++) { cout << "Outer value [" << i << "] : " << c << endl; func2(); c = c + 1; } return 0; }
#include <iostream> #define MAX 100001 using namespace std; int n; int matrix[MAX]; int sums[MAX]; // 시간복잡도 n^2 void noDp(){ int ret = 0; for(int i = 0; i < n; i++){ int sum = 0; for(int j = i; j < n; j++){ sum += matrix[j]; if(ret < sum){ ret = sum; } } } cout << ret << '\n'; } // 시간복잡도 n void dp(){ sums[0] = matrix[0]; int ret = sums[0]; for(int i = 1; i < n; i++){ if(sums[i-1] < 0){ sums[i] = matrix[i]; }else{ sums[i] = sums[i-1] + matrix[i]; } if(ret < sums[i]){ ret = sums[i]; } } cout << ret << '\n'; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cin >> n; for(int i = 0; i < n; i++){ cin >> matrix[i]; } dp(); return 0; }
/* * TApplication.h * * Created on: Apr 11, 2017 * Author: Alex */ #ifndef TAPPLICATION_H_ #define TAPPLICATION_H_ #include <app.h> #include <Elementary.h> #include <system_settings.h> #include <efl_extension.h> #include <dlog.h> #ifdef LOG_TAG #undef LOG_TAG #endif #define LOG_TAG "colorlines" #if !defined(PACKAGE) #define PACKAGE "org.tizen.colorlines" #endif class TView; class TApplication { public: TApplication(); virtual ~TApplication(); int my_argc; char **my_argv; public: static void Initialize(int argc, char *argv[]); static int Run(TView* view); static TApplication *instance() { return self; }; TView* view() { return myView; }; private: static TApplication *self; TView* myView; }; #endif /* TAPPLICATION_H_ */
#include "NeuroNet.h" #include <random> #include <fstream> NeuroNet::NeuroNet() { input_nodes = 0; hidden_nodes = 0; output_nodes = 0; training_rate = 0.0; } NeuroNet::NeuroNet(int input_nodes, int hidden_nodes, int output_nodes, double training_rate) { this->input_nodes = input_nodes; this->hidden_nodes = hidden_nodes; this->output_nodes = output_nodes; this->training_rate = training_rate; wih = Matrix<double>(hidden_nodes, input_nodes); who = Matrix<double>(output_nodes, hidden_nodes); wih_buffer = Matrix<double>(hidden_nodes, input_nodes); who_buffer = Matrix<double>(output_nodes, hidden_nodes); std::random_device rnd; std::mt19937 gen(rnd()); std::normal_distribution<double> nd(0.0, std::pow(hidden_nodes, -0.5)); for (size_t i = 0; i < wih.rows(); i++) { for (size_t j = 0; j < wih.columns(); j++) { wih.insert(i, j, nd(gen)); } } nd = std::normal_distribution<double>(0.0, std::pow(output_nodes, -0.5)); for (size_t i = 0; i < who.rows(); i++) { for (size_t j = 0; j < who.columns(); j++) { who.insert(i, j, nd(gen)); } } } std::vector<double> NeuroNet::query(std::vector<double>& input_values) { Matrix<double> inputs(input_values.size(), 1); for (size_t i = 0; i < input_values.size(); i++) { inputs.insert(i, 0, input_values[i]); } Matrix<double> hidden_inputs = Matrix<double>::dot(wih, inputs); Matrix<double> hidden_outputs(hidden_inputs.rows(), hidden_inputs.columns()); for (size_t i = 0; i < hidden_outputs.rows(); i++) { hidden_outputs.insert(i, 0, 1.0 / (1 + exp(-hidden_inputs(i, 0)))); } Matrix<double> final_inputs = Matrix<double>::dot(who, hidden_outputs); Matrix<double> final_outputs(final_inputs.rows(), final_inputs.columns()); for (size_t i = 0; i < final_inputs.rows(); i++) { final_outputs.insert(i, 0, 1.0 / (1 + exp(-final_inputs(i, 0)))); } std::vector<double> result(final_outputs.rows()); for (size_t i = 0; i < result.size(); i++) { result[i] = final_outputs(i, 0); } return result; } void NeuroNet::train(std::vector<double>& input_values, std::vector<double>& target_values) { Matrix<double> inputs(input_values.size(), 1); Matrix<double> targets(target_values.size(), 1); for (size_t i = 0; i < input_values.size(); i++) { inputs.insert(i, 0, input_values[i]); } for (size_t i = 0; i < target_values.size(); i++) { targets.insert(i, 0, target_values[i]); } Matrix<double> hidden_inputs = Matrix<double>::dot(wih, inputs); Matrix<double> hidden_outputs(hidden_inputs.rows(), hidden_inputs.columns()); for (size_t i = 0; i < hidden_outputs.rows(); i++) { hidden_outputs.insert(i, 0, 1.0 / (1 + exp(-hidden_inputs(i, 0)))); } Matrix<double> final_inputs = Matrix<double>::dot(who, hidden_outputs); Matrix<double> final_outputs(final_inputs.rows(), final_inputs.columns()); for (size_t i = 0; i < final_inputs.rows(); i++) { final_outputs.insert(i, 0, 1.0 / (1 + exp(-final_inputs(i, 0)))); } Matrix<double> output_errors = targets - final_outputs; Matrix<double> hidden_errors = Matrix<double>::dot(who.get_transpose(), output_errors); Matrix<double> buff = output_errors * final_outputs; for (size_t i = 0; i < final_outputs.rows(); i++) { for (size_t j = 0; j < final_outputs.columns(); j++) { buff.insert(i, j, buff(i,j) * (1 - final_outputs(i, j))); } } who += Matrix<double>::dot(buff, hidden_outputs.get_transpose()) * training_rate; buff = hidden_errors * hidden_outputs; for (size_t i = 0; i < hidden_outputs.rows(); i++) { for (size_t j = 0; j < hidden_outputs.columns(); j++) { buff.insert(i, j, buff(i,j) * (1 - hidden_outputs(i, j))); } } wih += Matrix<double>::dot(buff, inputs.get_transpose()) * training_rate; } void NeuroNet::save() { std::fstream out; out.open("./width.txt", std::fstream::out | std::fstream::trunc); out << input_nodes << " " << hidden_nodes << " " << output_nodes << " " << training_rate << " "; for (size_t i = 0; i < wih.rows(); i++) { for (size_t j = 0; j < wih.columns(); j++) { out << wih(i, j) << " "; } } for (size_t i = 0; i < who.rows(); i++) { for (size_t j = 0; j < who.columns(); j++) { out << who(i, j) << " "; } } out.close(); } void NeuroNet::load() { std::fstream in; in.open("./width.txt", std::fstream::in); in >> input_nodes >> hidden_nodes >> output_nodes >> training_rate; wih = Matrix<double>(hidden_nodes, input_nodes); who = Matrix<double>(output_nodes, hidden_nodes); for (size_t i = 0; i < wih.rows(); i++) { for (size_t j = 0; j < wih.columns(); j++) { double value; in >> value; wih.insert(i, j, value); } } for (size_t i = 0; i < who.rows(); i++) { for (size_t j = 0; j < who.columns(); j++) { double value; in >> value; who.insert(i, j, value); } } in.close(); }
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved. #pragma once #include "Core.h" #include "UnrealTournament.h" #include "AllowWindowsPlatformTypes.h" #include <mmdeviceapi.h> #include <audioclient.h> #include "LetMeTakeASelfie.generated.h" UCLASS(Blueprintable, Meta = (ChildCanTick)) class ALetMeTakeASelfie : public AActor { GENERATED_UCLASS_BODY() }; struct FLetMeTakeASelfie : FTickableGameObject, FSelfRegisteringExec { FLetMeTakeASelfie(); virtual void Tick(float DeltaTime); virtual bool IsTickable() const { return true; } virtual bool IsTickableInEditor() const { return true; } // Put a real stat id here virtual TStatId GetStatId() const { return TStatId(); } /** FSelfRegisteringExec implementation */ virtual bool Exec(UWorld* Inworld, const TCHAR* Cmd, FOutputDevice& Ar) override; void OnWorldCreated(UWorld* World, const UWorld::InitializationValues IVS); void OnWorldDestroyed(UWorld* World); TMap< UWorld*, USceneCaptureComponent2D* > WorldToSceneCaptureComponentMap; UWorld* SelfieWorld; bool bTakingAnimatedSelfie; float SelfieTimeTotal; int32 SelfieFrames; int32 SelfieFramesMax; float SelfieFrameDelay; float SelfieDeltaTimeAccum; bool bStartedAnimatedWritingTask; int32 SelfieWidth; int32 SelfieHeight; int32 SelfieFrameRate; bool bFirstPerson; bool bRegisteredSlateDelegate; // Capturing in a ring buffer, this is the current head int32 HeadFrame; TWeakObjectPtr<AUTProjectile> FollowingProjectile; int32 RecordedNumberOfScoringPlayers; float DelayedEventWriteTimer; float SelfieTimeWaited; TArray< TArray<FColor> > SelfieSurfaceImages; TArray<FColor> SelfieSurfData; bool bWaitingOnSelfieSurfData; bool bSelfieSurfDataReady; void ReadPixelsAsync(FRenderTarget* RenderTarget); /** Static: Readback textures for asynchronously reading the viewport frame buffer back to the CPU. We ping-pong between the buffers to avoid stalls. */ FTexture2DRHIRef ReadbackTextures[2]; /** Static: We ping pong between the textures in case the GPU is a frame behind (GSystemSettings.bAllowOneFrameThreadLag) */ int32 ReadbackTextureIndex; /** Static: Pointers to mapped system memory readback textures that game frames will be asynchronously copied to */ void* ReadbackBuffers[2]; /** The current buffer index. We bounce between them to avoid stalls. */ int32 ReadbackBufferIndex; void OnSlateWindowRenderedDuringCapture(SWindow& SlateWindow, void* ViewportRHIPtr); void CopyCurrentFrameToSavedFrames(); void StartCopyingNextGameFrame(const FViewportRHIRef& ViewportRHI); // Audio stuff IMMDevice* MMDevice; IAudioClient* AudioClient; IAudioCaptureClient* AudioCaptureClient; WAVEFORMATEX* WFX; int32 AudioBlockAlign; TArray<int8> AudioData; uint32 AudioDataLength; uint32 AudioTotalFrames; bool bCapturingAudio; void InitAudioLoopback(); void StopAudioLoopback(); void ReadAudioLoopback(); void WriteWebM(); }; /* Based on https://wiki.unrealengine.com/Multi-Threading:_How_to_Create_Threads_in_UE4 */ class FWriteWebMSelfieWorker : public FRunnable { FWriteWebMSelfieWorker(FLetMeTakeASelfie* InLetMeTakeASelfie) : LetMeTakeASelfie(InLetMeTakeASelfie) { Thread = FRunnableThread::Create(this, TEXT("FWriteWebMSelfieWorker"), 0, TPri_BelowNormal); } ~FWriteWebMSelfieWorker() { delete Thread; Thread = nullptr; } uint32 Run() { LetMeTakeASelfie->WriteWebM(); return 0; } public: static FWriteWebMSelfieWorker* RunWorkerThread(FLetMeTakeASelfie* InLetMeTakeASelfie) { if (Runnable) { delete Runnable; Runnable = nullptr; } if (Runnable == nullptr) { Runnable = new FWriteWebMSelfieWorker(InLetMeTakeASelfie); } return Runnable; } private: FLetMeTakeASelfie* LetMeTakeASelfie; FRunnableThread* Thread; static FWriteWebMSelfieWorker* Runnable; };
/* URL to Check the Data on Cloud using sylvesterf as Author and Channel ID 223662 https://thingspeak.com/channels/223662 */ #define TINY_GSM_MODEM_SIM800 #include <TinyGsmClient.h> #include <SoftwareSerial.h> #define server "api.thingspeak.com" #define apiKey "J0WJOEXGJNF0QNC8" #define mobile "9928492120" // Your GPRS Internet APN based on the SIM Card // Jio is NOT compatible const char apn[] = "imis/internet"; //APN for airtel:- airtelgprs.com // APN for idea:- imis/internet // APN for vodafone:- www // APN for reliance:- rcomnet // APN for bsnl:- bsnlnet // APN for Aircel:- aircelgprs.pr //SIM800 GND is connected to Arduino GND //SIM800 RX is connected to Arduino D7 //SIM800 TX is connected to Arduino D8 //SIM800 TX is connected to Arduino D8 #define SIM800_TX_PIN 8 //SIM800 RX is connected to Arduino D7 #define SIM800_RX_PIN 7 //Create software serial object to communicate with SIM800 // Rx , Tx SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN); TinyGsm modem(serialSIM800); TinyGsmClient client(modem); void setup() { // Set console baud rate Serial.begin(115200); delay(10); // Set GSM module baud rate serialSIM800.begin(9600); // Initializing the GSM setup_gsm(); } void setup_gsm() { delay(10); // Restart takes quite some time // To skip it, call init() instead of restart() Serial.println("Initializing modem..."); // Restart the Connection with the gsm module modem.restart(); // Return the information of the module String modemInfo = modem.getModemInfo(); Serial.print("Modem: "); Serial.println(modemInfo); Serial.print("Waiting for network..."); // Checking the network of your sim card if (!modem.waitForNetwork()) { Serial.println(" fail"); while (true); } Serial.println(" OK"); Serial.print("Connecting to "); Serial.print(apn); if (!modem.gprsConnect(apn, "", "")) { Serial.println(" fail"); while (true); } Serial.println(" connected"); } void loop() { // Checking connection with the client if ( !client.connected() ) { // If the client is not connected then reconnect reconnect(); } Serial.println(" connected"); // Function is creating JSON and posting the data to the server createJSONandPostData(); // After successfull posting the data on server stoping the client communication. // if you don't do this then the connection remain open hence it will send the data once or twice. client.stop(); // There needs to be atleast 15 sec delay in sending the data delay(20000); } void createJSONandPostData() { Serial.println("Creating JSON"); // Create the JSON for the data to be uploaded on the Cloud String data; data += "{"; data += "\"field1\":\""+String(22.4)+"\","; // Temperature data += "\"field2\":\""+String(260)+"\","; // Light data += "\"field3\":\""+String(31)+"\","; // Humidity data += "\"field4\":\""+String(1)+"\","; // Door Status ( OPEN=1 or CLOSE=0) data += "\"field5\":\""+String(0)+"\","; // Power Status ( ON=1 or OFF=0 ) data += "\"field6\":\""+String(0)+"\","; // Person Status ( YES=1 or NO=0 ) data += "\"field7\":\""+String(mobile)+"\","; // Unique ID data += "\"field8\":\""+String(mobile)+"\""; // Mobile number data += "}"; Serial.println(data); //printing the data on serial monitor //Making http post request client.println("POST /update?api_key="+String(apiKey)+" HTTP/1.1"); client.println("Host: "+String(server)); client.println("Accept: */*"); client.println("Content-Length: " + String(data.length())); client.println("Content-Type: application/json"); client.println(); client.println(data); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Connecting to Thingspeak server ..."); // Attempt to connect (clientId, username, password) if ( client.connect(server, 80) ) { Serial.println( "Connected" ); } else { Serial.print( "[FAILED] [ rc = " ); // Serial.print( client.state() ); Serial.println( " : retrying in 5 seconds]" ); // Wait 5 seconds before retrying delay( 5000 ); } } }
/////////////////////////////////////// // // Computer Graphics TSBK03 // Conrad Wahlén - conwa099 // /////////////////////////////////////// #include "Program.h" #include "GL_utilities.h" #include <iostream> Program::Program() { // Set all pointers to null screen = NULL; glcontext = NULL; cam = NULL; // Window init size winWidth = 400; winHeight = 400; // Start state isRunning = true; // Time init time.startTimer(); // Set program parameters cameraStartDistance = 2.9f; cameraStartAzimuth = (GLfloat)M_PI / 4.0f;//(GLfloat)M_PI / 2.0f; (GLfloat)M_PI / 4.0f; cameraStartPolar = (GLfloat)M_PI / 1.8f;//(GLfloat) M_PI / 2.3f; (GLfloat) M_PI / 1.8f; cameraStartTarget = glm::vec3(0.0f, 0.0f, 0.0f); cameraStartFov = 60.0f; cameraFrustumFar = 5000.0f; sceneSelect = 0; useOrtho = false; drawVoxelOverlay = false; takeTime = 0; runNumber = 0; runScene = 0; sceneAverage[0] = 0.0f; sceneAverage[1] = 0.0f; sceneAverage[2] = 0.0f; sceneAverage[3] = 0.0f; sceneAverage[4] = 0.0f; } int Program::Execute() { if(!Init()) { std::cout << "\nInit failed. Press enter to quit ..." << std::endl; getchar(); return -1; } SDL_Event Event; while(isRunning) { timeUpdate(); while(SDL_PollEvent(&Event)) OnEvent(&Event); CheckKeyDowns(); Update(); Render(); } Clean(); return 0; } void Program::timeUpdate() { time.endTimer(); param.deltaT = time.getLapTime(); param.currentT = time.getTime(); FPS = 1.0f / time.getLapTime(); } void APIENTRY openglCallbackFunction( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { (void)source; (void)type; (void)id; (void)severity; (void)length; (void)userParam; switch(id) { case 131185: // Buffer detailed info return; case 131218: // Nvidia Shader complilation performance warning return; case 131186: // Memory copied from Device to Host return; case 131204: // Texture state 0 is base level inconsistent return; case 131076: // Vertex attribute optimized away return; default: break; } fprintf(stderr, "ID: %d\n %s\n\n",id, message); if(severity == GL_DEBUG_SEVERITY_HIGH) { fprintf(stderr, "Aborting...\n"); abort(); } } bool Program::Init() { // SDL, glew and OpenGL init if(SDL_Init(SDL_INIT_VIDEO) != 0) { std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl; return false; } screen = SDL_CreateWindow("Voxel Cone Tracing", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, winWidth, winHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if(screen == 0) { std::cerr << "Failed to set Video Mode: " << SDL_GetError() << std::endl; return false; } #ifdef DEBUG SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); #endif // DEBUG glcontext = SDL_GL_CreateContext(screen); SDL_SetRelativeMouseMode(SDL_FALSE); #ifdef _WINDOWS GLenum glewErr = glewInit(); if(glewErr != GLEW_OK) { std::cerr << "Failed to initialize GLEW: " << glewGetErrorString(glewErr) << std::endl; return false; } #endif // _WINDOWS #ifdef DEBUG // Enable the debug callback glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(openglCallbackFunction, nullptr); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, true); #endif // DEBUG // Activate depth test and blend for masking textures glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_3D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); dumpInfo(); printError("after wrapper inits"); glGenBuffers(1, &programBuffer); glBindBufferBase(GL_UNIFORM_BUFFER, PROGRAM, programBuffer); glBufferData(GL_UNIFORM_BUFFER, sizeof(ProgramStruct), &param, GL_STREAM_DRAW); // Load shaders for drawing shaders.drawScene = loadShaders("src/shaders/drawModel.vert", "src/shaders/drawModel.frag"); shaders.drawData = loadShaders("src/shaders/drawData.vert", "src/shaders/drawData.frag"); // Load shaders for voxelization shaders.voxelize = loadShadersG("src/shaders/voxelization.vert", "src/shaders/voxelization.frag", "src/shaders/voxelization.geom"); // Single triangle shader for deferred shading etc. shaders.singleTriangle = loadShaders("src/shaders/drawTriangle.vert", "src/shaders/drawTriangle.frag"); // Draw voxels from 3D texture shaders.voxel = loadShaders("src/shaders/drawVoxel.vert", "src/shaders/drawVoxel.frag"); // Calculate mipmaps shaders.mipmap = CompileComputeShader("src/shaders/mipmap.comp"); // Create shadowmap shaders.shadowMap = loadShaders("src/shaders/shadowMap.vert", "src/shaders/shadowMap.frag"); // Set up the AntBar TwInit(TW_OPENGL_CORE, NULL); TwWindowSize(winWidth, winWidth); antBar = TwNewBar("VCT"); TwDefine(" VCT refresh=0.1 size='300 700' valueswidth=140 "); TwDefine(" VCT help='This program simulates Global Illumination with Voxel Cone Tracing.' "); // Set up the camera cam = new OrbitCamera(); if(!cam->Init(cameraStartTarget,cameraStartDistance,cameraStartPolar, cameraStartAzimuth, cameraStartFov, &winWidth, &winHeight, cameraFrustumFar)) return false; // Load scenes Scene* cornell = new Scene(); if(!cornell->Init("resources/cornell.obj", &shaders)) return false; scenes.push_back(cornell); //Scene* sponza = new Scene(); //if(!sponza->Init("resources/sponza.obj", &shaders)) return false; //scenes.push_back(sponza); // Initial Voxelization of the scenes cornell->CreateShadow(); cornell->RenderData(); cornell->Voxelize(); cornell->MipMap(); //sponza->CreateShadow(); //sponza->RenderData(); //sponza->Voxelize(); //sponza->MipMap(); // Add information to the antbar TwAddVarRO(antBar, "FPS", TW_TYPE_FLOAT, &FPS, " group=Info "); TwAddVarRO(antBar, "Cam Pos", cam->GetCameraTwType(), cam->GetCameraInfo(), NULL); //TwAddVarRW(antBar, "Cam Speed", TW_TYPE_FLOAT, cam->GetSpeedPtr(), " min=0 max=2000 step=10 group=Controls "); TwAddVarRW(antBar, "Cam Rot Speed", TW_TYPE_FLOAT, cam->GetRotSpeedPtr(), " min=0.0 max=0.010 step=0.001 group=Controls "); sceneType = TwDefineEnumFromString("Scene Selection", "Cornell, Sponza"); TwAddVarCB(antBar, "Select Scene", sceneType, SetNewSceneCB, GetNewSceneCB, this, " group=Controls "); TwAddVarCB(antBar, "SceneOptions", Scene::GetSceneOptionTwType(), Scene::SetSceneOptionsCB, Scene::GetSceneOptionsCB, GetCurrentScene(), " group=Scene opened=true "); TwAddVarCB(antBar, "SceneToGPU", Scene::GetSceneTwType(), Scene::SetSceneCB, Scene::GetSceneCB, GetCurrentScene(), " group=Scene opened=true "); TwAddVarRW(antBar, "LightDir", TW_TYPE_DIR3F, GetCurrentScene()->GetLightDir(), " group=Scene opened=true "); #ifdef DEBUG //TwAddVarCB(antBar, "DrawCmd", Scene::GetDrawIndTwType(), Scene::SetDrawIndCB, Scene::GetDrawIndCB, GetCurrentScene(), " group=Scene opened=true "); //TwAddVarCB(antBar, "CompCmd", Scene::GetCompIndTwType(), Scene::SetCompIndCB, Scene::GetCompIndCB, GetCurrentScene(), " group=Scene opened=true "); #endif // DEBUG // Check if AntTweak Setup is ok if(TwGetLastError() != NULL) return false; if(takeTime) { printf("Time per step logging\n"); printf("Scene\t CSA \t RDA \t V \t M \t DA\n"); } return true; } void Program::Update() { // Upload program params (incl time update) UploadParams(); GetCurrentScene()->UpdateBuffers(); // Update the camera cam->Update(param.deltaT); } void Program::Render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(runNumber < 5 && takeTime) { glFinish(); timer.startTimer(); } GetCurrentScene()->CreateShadow(); if(runNumber < 5 && takeTime) { glFinish(); timer.endTimer(); sceneAverage[0] += timer.getTimeMS() / 5.0f; timer.startTimer(); } GetCurrentScene()->RenderData(); if(runNumber < 5 && takeTime) { glFinish(); timer.endTimer(); sceneAverage[1] += timer.getTimeMS() / 5.0f; timer.startTimer(); } GetCurrentScene()->Voxelize(); if(runNumber < 5 && takeTime) { glFinish(); timer.endTimer(); sceneAverage[2] += timer.getTimeMS() / 5.0f; timer.startTimer(); } GetCurrentScene()->MipMap(); if(runNumber < 5 && takeTime) { glFinish(); timer.endTimer(); sceneAverage[3] += timer.getTimeMS() / 5.0f; timer.startTimer(); } GetCurrentScene()->Draw(); if(runNumber < 5 && takeTime) { glFinish(); timer.endTimer(); sceneAverage[4] += timer.getTimeMS() / 5.0f; runNumber++; } if(runNumber == 5 && takeTime) { printf("%4d \t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\n", runScene + 1, runScene > 0 ? sceneAverage[0] : 0.0f, sceneAverage[1], runScene > 1 ? sceneAverage[2] : 0.0f, runScene > 1 ? sceneAverage[3] : 0.0f, sceneAverage[4]); ToggleProgram(); } TwDraw(); SDL_GL_SwapWindow(screen); } void Program::ToggleProgram() { runScene = GetCurrentScene()->GetSceneParam()->voxelDraw; runScene++; runScene %= 5; GetCurrentScene()->GetSceneParam()->voxelDraw = runScene; runNumber = 0; sceneAverage[0] = 0.0f; sceneAverage[1] = 0.0f; sceneAverage[2] = 0.0f; sceneAverage[3] = 0.0f; sceneAverage[4] = 0.0f; if(runScene == 0 && takeTime) { takeTime++; } if(takeTime > 6) { takeTime = 0; } } void Program::Clean() { glDeleteBuffers(1, &programBuffer); TwTerminate(); SDL_GL_DeleteContext(glcontext); SDL_Quit(); } void Program::UploadParams() { // Update program parameters glBindBufferBase(GL_UNIFORM_BUFFER, PROGRAM, programBuffer); glBufferSubData(GL_UNIFORM_BUFFER, NULL, sizeof(ProgramStruct), &param); } void TW_CALL Program::SetNewSceneCB(const void* value, void* clientData) { Program* obj = static_cast<Program*>(clientData); obj->sceneSelect = *static_cast<const GLuint*>(value); obj->GetCurrentScene()->UpdateBuffers(); TwRemoveVar(obj->antBar, "SceneOptions"); TwRemoveVar(obj->antBar, "SceneToGPU"); TwRemoveVar(obj->antBar, "LightDir"); TwAddVarCB(obj->antBar, "SceneOptions", Scene::GetSceneOptionTwType(), Scene::SetSceneOptionsCB, Scene::GetSceneOptionsCB, obj->GetCurrentScene(), " group=Scene opened=true "); TwAddVarCB(obj->antBar, "SceneToGPU", Scene::GetSceneTwType(), Scene::SetSceneCB, Scene::GetSceneCB, obj->GetCurrentScene(), " group=Scene opened=true "); TwAddVarRW(obj->antBar, "LightDir", TW_TYPE_DIR3F, obj->GetCurrentScene()->GetLightDir(), " group=Scene opened=true "); #ifdef DEBUG //TwRemoveVar(obj->antBar, "DrawCmd"); //TwRemoveVar(obj->antBar, "CompCmd"); //TwAddVarCB(obj->antBar, "DrawCmd", Scene::GetDrawIndTwType(), Scene::SetDrawIndCB, Scene::GetDrawIndCB, obj->GetCurrentScene(), " group=Scene opened=true "); //TwAddVarCB(obj->antBar, "CompCmd", Scene::GetCompIndTwType(), Scene::SetCompIndCB, Scene::GetCompIndCB, obj->GetCurrentScene(), " group=Scene opened=true "); #endif // DEBUG } void TW_CALL Program::GetNewSceneCB(void* value, void* clientData) { *static_cast<GLuint*>(value) = static_cast<Program*>(clientData)->sceneSelect; } void Program::OnEvent(SDL_Event *Event) { switch(Event->type) { case SDL_QUIT: isRunning = false; break; case SDL_WINDOWEVENT: switch(Event->window.event) { case SDL_WINDOWEVENT_RESIZED: SDL_SetWindowSize(screen, Event->window.data1, Event->window.data2); SDL_GetWindowSize(screen, &winWidth, &winHeight); glViewport(0, 0, winWidth, winHeight); TwWindowSize(winWidth, winHeight); cam->Resize(); GetCurrentScene()->SetupSceneTextures(); break; } case SDL_KEYDOWN: OnKeypress(Event); break; case SDL_MOUSEMOTION: OnMouseMove(Event); break; case SDL_MOUSEBUTTONDOWN: TwMouseButton(TW_MOUSE_PRESSED, TW_MOUSE_LEFT); break; case SDL_MOUSEBUTTONUP: TwMouseButton(TW_MOUSE_RELEASED, TW_MOUSE_LEFT); break; case SDL_MOUSEWHEEL: cam->Zoom(1.0f + 0.05f * Event->wheel.y); default: break; } } void Program::OnKeypress(SDL_Event *Event) { TwKeyPressed(Event->key.keysym.sym, TW_KMOD_NONE); switch(Event->key.keysym.sym) { case SDLK_ESCAPE: isRunning = false; break; case SDLK_SPACE: break; case SDLK_f: cam->TogglePause(); SDL_SetRelativeMouseMode(SDL_GetRelativeMouseMode() ? SDL_FALSE : SDL_TRUE); break; case SDLK_g: int isBarHidden; TwGetParam(antBar, NULL, "iconified", TW_PARAM_INT32, 1, &isBarHidden); if(isBarHidden) { TwDefine(" VCT iconified=false "); } else { TwDefine(" VCT iconified=true "); } break; default: break; } } void Program::OnMouseMove(SDL_Event *Event) { const Uint8 *keystate = SDL_GetKeyboardState(NULL); if(!SDL_GetRelativeMouseMode()) { TwMouseMotion(Event->motion.x, Event->motion.y); } else { if(keystate[SDL_SCANCODE_LCTRL]) { GetCurrentScene()->PanLight((GLfloat)Event->motion.xrel, (GLfloat)Event->motion.yrel); } else { cam->Rotate(Event->motion.xrel, Event->motion.yrel); } } } void Program::CheckKeyDowns() { const Uint8 *keystate = SDL_GetKeyboardState(NULL); if(keystate[SDL_SCANCODE_W]) { //cam->MoveForward(); } if(keystate[SDL_SCANCODE_S]) { //cam->MoveBackward(); } if(keystate[SDL_SCANCODE_A]) { //cam->MoveLeft(); } if(keystate[SDL_SCANCODE_D]) { //cam->MoveRight(); } if(keystate[SDL_SCANCODE_Q]) { //cam->MoveUp(); } if(keystate[SDL_SCANCODE_E]) { //cam->MoveDown(); } }
#ifndef __IGDRAWING_H__ #define __IGDRAWING_H__ #include "igWidget.h" #include <SFML/Graphics.hpp> const igButton& DrawButton(const igButton& button); const igCheckbox& DrawCheckbox(const igCheckbox& checkbox, sf::Texture& thickTexture); const igTextbox& DrawTextbox(const igTextbox& textbox); const igLabel& DrawLabel(const igLabel& label); const igSlider& DrawSlider(const igSlider& slider); const igMove& DrawMove(const igMove& move); const igSeparator& DrawSeparator(const igSeparator& separator); const igAreaBG& DrawAreaBG(const igAreaBG& scrollArea); const igAreaFG& DrawAreaFG(const igAreaFG& scrollArea); const igDragged& DrawDragged(const igDragged& dragged); void DrawDrag(const igDrag<void>& drag); template <class R> const igDrag<R>& DrawDrag(const igDrag<R>& drag) { igDrag<void> tmp; tmp.rect = drag.rect; tmp.hover = drag.hover; tmp.down = drag.down; tmp.title = drag.title; DrawDrag(tmp); return drag; } #endif
// Created on: 1992-02-04 // Created by: Christian CAILLET // Copyright (c) 1992-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 _Transfer_TransferInput_HeaderFile #define _Transfer_TransferInput_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> class Interface_EntityIterator; class Transfer_TransferIterator; class Transfer_TransientProcess; class Interface_InterfaceModel; class Interface_Protocol; class Transfer_FinderProcess; //! A TransferInput is a Tool which fills an InterfaceModel with //! the result of the Transfer of CasCade Objects, once determined //! The Result comes from a TransferProcess, either from //! Transient (the Complete Result is considered, it must contain //! only Transient Objects) class Transfer_TransferInput { public: DEFINE_STANDARD_ALLOC //! Creates a TransferInput ready to use Standard_EXPORT Transfer_TransferInput(); //! Takes the transient items stored in a TransferIterator Standard_EXPORT Interface_EntityIterator Entities (Transfer_TransferIterator& list) const; //! Fills an InterfaceModel with the Complete Result of a Transfer //! stored in a TransientProcess (Starting Objects are Transient) //! The complete result is exactly added to the model Standard_EXPORT void FillModel (const Handle(Transfer_TransientProcess)& proc, const Handle(Interface_InterfaceModel)& amodel) const; //! Fills an InterfaceModel with results of the Transfer recorded //! in a TransientProcess (Starting Objects are Transient) : //! Root Result if <roots> is True (Default), Complete Result else //! The entities added to the model are determined from the result //! by by adding the referenced entities Standard_EXPORT void FillModel (const Handle(Transfer_TransientProcess)& proc, const Handle(Interface_InterfaceModel)& amodel, const Handle(Interface_Protocol)& proto, const Standard_Boolean roots = Standard_True) const; //! Fills an InterfaceModel with the Complete Result of a Transfer //! stored in a TransientProcess (Starting Objects are Transient) //! The complete result is exactly added to the model Standard_EXPORT void FillModel (const Handle(Transfer_FinderProcess)& proc, const Handle(Interface_InterfaceModel)& amodel) const; //! Fills an InterfaceModel with results of the Transfer recorded //! in a TransientProcess (Starting Objects are Transient) : //! Root Result if <roots> is True (Default), Complete Result else //! The entities added to the model are determined from the result //! by by adding the referenced entities Standard_EXPORT void FillModel (const Handle(Transfer_FinderProcess)& proc, const Handle(Interface_InterfaceModel)& amodel, const Handle(Interface_Protocol)& proto, const Standard_Boolean roots = Standard_True) const; protected: private: }; #endif // _Transfer_TransferInput_HeaderFile
#include "model.h" Model::Model() : m_leg(1.0), h_in(1.0), h_out(1.0) { } Model::~Model() { } /** * @brief Model::updateOscillator * @param state * @param dt */ void Model::updateOscillator(const State &state, const double &dt) { // Update our neural oscillator with the current state variables and the elapsed time. m_osc.timestep(getNeuralInput(state),dt); }
#include "precompiled.h" #include "skybox/jsskybox.h" #include "skybox/skybox.h" #include "script/script.h" namespace jsskybox { JSBool jsreset(JSContext *cx, uintN argc, jsval* vp); } void jsskybox::init() { script::gScriptEngine->AddFunction("system.render.skybox.reset", 0, jsskybox::jsreset); } JSBool jsskybox::jsreset(JSContext *cx, uintN argc, jsval* vp) { skybox::reset(); return JS_TRUE; }
#include "conflict_battle_records.hpp" #include "config/options_ptts.hpp" #include <limits> namespace nora { namespace scene { conflict_battle_records::conflict_battle_records() { auto ptt = PTTS_GET_COPY(options, 1u); gamedb_ = make_shared<db::connector>(ptt.game_db().ipport(), ptt.game_db().user(), ptt.game_db().password(), ptt.game_db().database()); gamedb_->start(); } void conflict_battle_records::add_record(const pd::conflict_battle_record& record) { lock_guard<mutex> lock(lock_); auto db_msg = make_shared<db::message>("add_conflict_battle_record", db::message::req_type::rt_insert); string str; record.SerializeToString(&str); db_msg->push_param(str); gamedb_->push_message(db_msg); } void conflict_battle_records::record(uint64_t gid, const function<void(pd::result, uint64_t, const pd::conflict_battle_record&)>& cb, const shared_ptr<service_thread>& st) const{ auto db_msg = make_shared<db::message>("get_conflict_battle_records", db::message::req_type::rt_select, [this, gid, cb] (const shared_ptr<db::message>& msg){ auto& results = msg->results(); if (!results.empty()) { ASSERT(results.size() == 1); const auto& result = results.front(); ASSERT(result.size() == 1); pd::conflict_battle_record record; record.ParseFromString(boost::any_cast<string>(result[0])); cb(pd::OK, gid, record); } else { cb(pd::NOT_FOUND, gid, pd::conflict_battle_record()); } }); db_msg->push_param(gid); gamedb_->push_message(db_msg, st); } } }
#pragma once #include "cDistrict.h" class cAssetDistrict : public cDistrict { public: cAssetDistrict(); virtual ~cAssetDistrict(); // begin of iDistrict virtual bool Actioon(); // end of iDistrict // begin of cAssetDistrict virtual bool SetSold(); virtual bool SetOwner(); virtual unsigned int GetPrice(); // begin of cAssetDistrict protected: iUser* m_owner; };
//Phoenix_RK /* https://leetcode.com/problems/unique-paths-ii/ Example 1: Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right Example 2: [[0,0],[1,1],[0,0]] Ans: 0 Example 3: [[0,1,0,0,0],[1,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] Ans: 0 Example 4: [[1,0]] Ans: 0 //value in each cell represents in how many ways that cell can be reached from the start. If an obstacle is present then we cannot get to that partcular cell and we cannot get past that cell along the path. */ class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m=obstacleGrid.size(),n=obstacleGrid[0].size(); int a[m][n]; if(obstacleGrid[0][0]==1) return 0; int flag=0; for(int i=0;i<m;i++) { if(obstacleGrid[i][0]==1) { a[i][0]=0; flag=1; } else if(flag==1) a[i][0]=0; else a[i][0]=1; } flag=0; for(int i=0;i<n;i++) { if(obstacleGrid[0][i]==1) { a[0][i]=0; flag=1; } else if(flag==1) a[0][i]=0; else a[0][i]=1; } for(int i=1;i<m;i++) { for(int j=1;j<n;j++) { if(obstacleGrid[i][j]==1) a[i][j]=0; else a[i][j]=a[i-1][j]+a[i][j-1]; } } /* for(int i=0;i<m;i++) { for(int j=0;j<n;j++) cout<<a[i][j]<<" "; cout<<endl; }*/ return a[m-1][n-1]; } };
//************************************************************************** // File......... : VRHostController.cpp // Project...... : VR // Author....... : Liu Zhi // Date......... : 2018-11 // Description.. : Implementation file of the class VRHostController used as business logics process // of VR Host Controller server. // History...... : First created by Liu Zhi 2018-11 // update by Liu Zhi 2019-02 //*************************************************************************** #include <direct.h> #include <thread> #ifdef _WINDOWS #include "../VRHostControllerUI/VRHostControllerUIDlg.h" #endif #include "VRHostController.h" #include "RemoteClientManager.h" #include "RemoteClient.h" #include "Util.h" VRHostController::VRHostController() { m_pConfReader = NULL; m_pNetEventServer = NULL; m_pClientMgr = NULL; m_pCSVFile = NULL; bStopFlag = false; } VRHostController::VRHostController(CVRHostControllerUIDlg *pUIDlg) { m_pVRHostControllerUIDlg = pUIDlg; m_pConfReader = NULL; m_pNetEventServer = NULL; m_pClientMgr = NULL; m_pCSVFile = NULL; bStopFlag = false; } VRHostController::~VRHostController() { if (m_pConfReader) { delete m_pConfReader; m_pConfReader = NULL; } if (m_pNetEventServer) { delete m_pNetEventServer; m_pNetEventServer = NULL; } if (m_pClientMgr) { delete m_pClientMgr; m_pClientMgr = NULL; } if (m_pCSVFile) { delete m_pCSVFile; m_pCSVFile = NULL; } } int VRHostController::ReadConfigFile() { m_pConfReader = CreateConfigReader(); char path[MAX_PATH_LEN] = { 0 }; _getcwd(path, MAX_PATH_LEN); strcat(path, "/VRHostController.xml"); bool ret = m_pConfReader->OpenFile(path); if (!ret) { LOG(error, "配置文件读取失败\n"); return FAIL; } } int VRHostController::Start() { if (!m_pConfReader) { LOG(error, "配置文件对象confReader为NULL!"); return FAIL; } m_port = m_pConfReader->GetInt("root.Server.port"); m_maxLinks = m_pConfReader->GetInt("root.Server.maxlinks"); m_pConfReader->GetStr("root.Server.name", m_HostCtlrID); m_pNetEventServer = CreateNetEvtServer(); bool bRet = m_pNetEventServer->Start(m_port, m_maxLinks); if (bRet == false) { return FAIL; } LOG(info, "VR主机控制器启动成功!"); return SUCCESS; } int VRHostController::CreateVRClientManager() { if (!m_pNetEventServer || strlen(m_HostCtlrID) == 0) { LOG(error, "创建用户管理器失败!"); return FAIL; } m_pClientMgr = new RemoteClientManager(); m_pClientMgr->SetNetworkService(m_pNetEventServer); m_pClientMgr->SetHostController(this); return SUCCESS; } void VRHostController::Run() { while (true) { if (bStopFlag == true) { break; } HandleNetEventFromClient(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } bool VRHostController::Stop() { return m_pNetEventServer->Stop(); } int VRHostController::CreateUserSeatMap() { if (!m_pCSVFile) { m_pCSVFile = new CSVFile(); } m_pCSVFile->OpenFile(); int ret = m_pCSVFile->ReadUserSeatMap(); if (ret != 0) { LOG(error, "读取user_seat_map失败!"); } else { m_USM = m_pCSVFile->GetUserSeatMap(); } //char* userid; //int seat; //User_Seat_Map::iterator it = m_USM.begin(); //while (it != m_USM.end()) //{ // seat = it->first; // userid =(char*) (it->second).c_str(); // cout << (*it).first << (*it).second << endl; // it++; //} //m_pCSVFile->Write(6, "wefrewrwerwe023"); return ret; } void VRHostController::HandleNetEventFromClient() { MsgQueue& msgQ = m_pNetEventServer->GetMsgQueue(); int msgAmount = msgQ.GetCount(); for (int i = 0; i < msgAmount; i++) { MessagePackage* pack = (MessagePackage*)msgQ.GetMsg(i); int msgID = pack->header()->id1; int cmdID = pack->header()->id2; int cid = pack->GetLinkID(); switch (msgID) { case link_connected: { RemoteClient* pClient = new RemoteClient(cid); pClient->SaveIP(pack->body(), pack->GetBodyLength()); m_pClientMgr->AddRemoteClient(pClient); m_pClientMgr->SendCmd(cid, link_connected, 0, NULL, 0); SendLogMsg(m_pClientMgr->GetOutputLog()); break; } case link_disconnected: { m_pClientMgr->DeleteRemoteClient(cid); break; } case ID_User_Login: { if (c2s_tell_seat_num == cmdID) //接收从VRClientAgent发来的座椅号消息 { int seatNum = *(int*)pack->body(); bool bRet = m_pClientMgr->AssignSeatNumToVRHost(cid, seatNum); } else if (c2s_tell_user_id == cmdID) //处理胶囊体发来的消息 { //更新终端类型为胶囊体类型, 一定要先更新类型,后绑定 m_pClientMgr->UpdateClientType(cid, Capsule); int len_userID = pack->GetBodyLength(); CopyData(m_UserID, pack->body(), len_userID, USER_ID_LENGTH); RemoteClient *client = NULL; bool bRet = m_pClientMgr->AllocateVRHostForUser(m_UserID, len_userID, &client); if (bRet) { int seatNumber = client->GetSeatNumber(); UserInfo usrInfo; memcpy(usrInfo.UserID, m_UserID, len_userID); usrInfo.SeatNumber = seatNumber; MessagePackage package; package.WriteHeader(ID_HostCtlr_Notify, s2c_rsp_seat_num); package.WriteBody(&usrInfo, sizeof(UserInfo)); //返回座席号给胶囊体 m_pClientMgr->SendMsg(cid, package); //向终端代理发送绑定的userID MessagePackage package1; package1.WriteHeader(ID_HostCtlr_Notify, s2c_tell_user_id); package1.WriteBody(m_UserID, len_userID); m_pClientMgr->SendMsg(client->GetLinkID(), package1); //向csv文件写入SeatNumber-UserID映射关系 m_pCSVFile->Write(seatNumber, usrInfo.UserID, client->GetIP()); } else { UserInfo usrInfo; memcpy(usrInfo.UserID, m_UserID, len_userID); usrInfo.SeatNumber = -1; MessagePackage package; package.WriteHeader(ID_HostCtlr_Notify, s2c_rsp_seat_num); package.WriteBody(&usrInfo, sizeof(UserInfo)); //返回座席号-1给胶囊体 m_pClientMgr->SendMsg(cid, package); } } break; } case ID_VRClientAgent_Notify: { if (c2s_device_status_changed == cmdID) { DeviceStatus *pDevStatus = (DeviceStatus*)pack->body(); int seatNum = pDevStatus->seatNumber; int stats = pDevStatus->status; if (DeviceState::RecycleEnable == stats) { m_pClientMgr->ReclaimVRHost(cid, seatNum); } } } default: { break; } } //switch }//for } void VRHostController::SendLogMsg(Output_Log& outLog) { LOG(outLog.m_logType, outLog.m_logStr.c_str()); #ifdef _WINDOWS m_pVRHostControllerUIDlg->SendUserConnectMsg(&outLog); #endif }
#include "../stdafx.hpp" #include "WinTerm.hpp" #ifndef MOUSE_WHEELED static const ::DWORD MOUSE_WHEELED = 4; #endif // MOUSE_WHEELED #ifndef MOUSE_HWHEELED static const ::DWORD MOUSE_HWHEELED = 8; #endif // MOUSE_HWHEELED static const ::DWORD SCRIPT_MODE_TRUE_TYPE_FONT = 9; static const ::DWORD BOX_DRAWING_RASTER_FONT = 8; namespace curses { CURSES_FORCEINLINE ::WORD color_to_attr(const text_color& color) { return (color.background << 4) | color.foreground; } CURSES_FORCEINLINE text_color attrs_to_color(::WORD attrs) { uint8_t foreground = attrs & 0x000F; uint8_t background = attrs >> 12; return text_color( foreground, background); } static bool resize_console(::HANDLE hConsole, ::SHORT width, ::SHORT height ) { ::CONSOLE_SCREEN_BUFFER_INFO csbi; // Hold Current Console Buffer Info ::BOOL bSuccess; ::SMALL_RECT srWindowRect;// Hold the New Console Size ::COORD coordScreen; bSuccess = ::GetConsoleScreenBufferInfo( hConsole, &csbi ); // Get the Largest Size we can size the Console Window to coordScreen = ::GetLargestConsoleWindowSize( hConsole ); // Define new possible console size, if requested larger then maximal set it into maximal coordScreen.X = std::min(width, coordScreen.X); coordScreen.Y = std::min(height, coordScreen.X); // Define the New Console Window Size and Scroll Position srWindowRect.Left = 0; srWindowRect.Top = 0; srWindowRect.Right = coordScreen.X - 1; srWindowRect.Bottom = coordScreen.Y - 1; // If the Current Buffer is Larger than what we want, Resize the // Console Window First, then the Buffer if( (csbi.dwSize.X * csbi.dwSize.Y) > (width * height) ) { bSuccess = ::SetConsoleWindowInfo( hConsole, TRUE, &srWindowRect ); bSuccess = ::SetConsoleScreenBufferSize( hConsole, coordScreen ); } // If the Current Buffer is Smaller than what we want, Resize the // Buffer First, then the Console Window if( (csbi.dwSize.X * csbi.dwSize.Y) < (width * height) ) { bSuccess = ::SetConsoleScreenBufferSize( hConsole, coordScreen ); bSuccess = ::SetConsoleWindowInfo( hConsole, TRUE, &srWindowRect ); } return bSuccess; } #define WM_SETCONSOLEINFO (WM_USER+201) #ifndef CURSES_HAS_CPP11 #pragma pack(push, 1) typedef struct _CONSOLE_INFO { ULONG Length; COORD ScreenBufferSize; COORD WindowSize; ULONG WindowPosX; ULONG WindowPosY; COORD FontSize; ULONG FontFamily; ULONG FontWeight; WCHAR FaceName[32]; ULONG CursorSize; ULONG FullScreen; ULONG QuickEdit; ULONG AutoPosition; ULONG InsertMode; USHORT ScreenColors; USHORT PopupColors; ULONG HistoryNoDup; ULONG HistoryBufferSize; ULONG NumberOfHistoryBuffers; COLORREF ColorTable[16]; ULONG CodePage; HWND Hwnd; WCHAR ConsoleTitle[0x100]; } CONSOLE_INFO; #pragma pack(pop) #else typedef struct alignas(8) _CONSOLE_INFO { ULONG Length; COORD ScreenBufferSize; COORD WindowSize; ULONG WindowPosX; ULONG WindowPosY; COORD FontSize; ULONG FontFamily; ULONG FontWeight; WCHAR FaceName[32]; ULONG CursorSize; ULONG FullScreen; ULONG QuickEdit; ULONG AutoPosition; ULONG InsertMode; USHORT ScreenColors; USHORT PopupColors; ULONG HistoryNoDup; ULONG HistoryBufferSize; ULONG NumberOfHistoryBuffers; COLORREF ColorTable[16]; ULONG CodePage; HWND Hwnd; WCHAR ConsoleTitle[0x100]; } CONSOLE_INFO; #endif // CURSES_HAS_CPP11 BOOL SetConsoleInfo(HWND hwndConsole, CONSOLE_INFO *pci) { DWORD dwConsoleOwnerPid; HANDLE hProcess; HANDLE hSection, hDupSection; PVOID ptrView = 0; HANDLE hThread; // // Open the process which "owns" the console // ::GetWindowThreadProcessId(hwndConsole, &dwConsoleOwnerPid); hProcess = ::OpenProcess(MAXIMUM_ALLOWED, FALSE, dwConsoleOwnerPid); // // Create a SECTION object backed by page-file, then map a view of // this section into the owner process so we can write the contents // of the CONSOLE_INFO buffer into it // hSection = ::CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, pci->Length, 0); // // Copy our console structure into the section-object // ptrView = ::MapViewOfFile(hSection, FILE_MAP_WRITE|FILE_MAP_READ, 0, 0, pci->Length); memcpy(ptrView, pci, pci->Length); ::UnmapViewOfFile(ptrView); // // Map the memory into owner process ::DuplicateHandle(::GetCurrentProcess(), hSection, hProcess, &hDupSection, 0, FALSE, DUPLICATE_SAME_ACCESS); // Send console window the "update" message ::SendMessage(hwndConsole, WM_SETCONSOLEINFO, (WPARAM)hDupSection, 0); hThread = ::CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)::CloseHandle, hDupSection, 0, 0); ::CloseHandle(hThread); ::CloseHandle(hSection); ::CloseHandle(hProcess); return TRUE; } static void GetConsoleSizeInfo(::HANDLE hcons, CONSOLE_INFO *pci) { ::CONSOLE_SCREEN_BUFFER_INFO csbi; ::GetConsoleScreenBufferInfo(hcons, &csbi); pci->ScreenBufferSize = csbi.dwSize; pci->WindowSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1; pci->WindowSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; pci->WindowPosX = csbi.srWindow.Left; pci->WindowPosY = csbi.srWindow.Top; } static void SetConsolePalette(::HANDLE hcons, const ::COLORREF* palette) { CONSOLE_INFO ci = { sizeof(ci) }; int i; HWND hwndConsole = GetConsoleWindow(); // get current size/position settings rather than using defaults.. GetConsoleSizeInfo(hcons, &ci); // set these to zero to keep current settings ci.FontSize.X = 0;//8; ci.FontSize.Y = 0;//12; ci.FontFamily = 0;//0x30;//FF_MODERN|FIXED_PITCH;//0x30; ci.FontWeight = 0;//0x400; //::lstrcpyW(ci.FaceName, L"Terminal"); ci.FaceName[0] = L'\0'; ci.CursorSize = 25; ci.FullScreen = FALSE; ci.QuickEdit = TRUE; ci.AutoPosition = 0x10000; ci.InsertMode = TRUE; ci.ScreenColors = MAKEWORD(0x7, 0x0); ci.PopupColors = MAKEWORD(0x5, 0xf); ci.HistoryNoDup = FALSE; ci.HistoryBufferSize = 50; ci.NumberOfHistoryBuffers = 4; // colour table for(i = 0; i < 16; i++) { ci.ColorTable[i] = palette[i]; } ci.CodePage = 0;//0x352; ci.Hwnd = hwndConsole; lstrcpyW(ci.ConsoleTitle, L""); SetConsoleInfo(hwndConsole, &ci); } // Terminal terminal::terminal(): hStdOut_(INVALID_HANDLE_VALUE), hStdIn_(INVALID_HANDLE_VALUE), hCons_(INVALID_HANDLE_VALUE), extConsole_(false) { extConsole_ = ::AttachConsole(ATTACH_PARENT_PROCESS); // for a gui application try to attach calling console, or allocate a new one if( !extConsole_) { // check current application is alrady a console one if(ERROR_ACCESS_DENIED != ::GetLastError() ) { // if gui applicaion with WinMain entry point // started from process withot allocated console extConsole_ = ::AllocConsole(); if(!extConsole_) { ::MessageBoxW(static_cast<::HWND>(NULL),L"Can not initialize console", L"Error", MB_OK | MB_ICONERROR); ::ExitProcess(-1); } } } hStdOut_ = ::GetStdHandle(STD_OUTPUT_HANDLE); assert(INVALID_HANDLE_VALUE != hStdOut_); hCons_ = ::CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE,// read/write access FILE_SHARE_READ | FILE_SHARE_WRITE,// shared NULL,// default security attributes CONSOLE_TEXTMODE_BUFFER, // must be TEXTMODE NULL); assert(INVALID_HANDLE_VALUE != hCons_); ::CONSOLE_SCREEN_BUFFER_INFO stdInfo; ::GetConsoleScreenBufferInfo(hStdOut_,&stdInfo); if( !resize_console(hCons_, 80, 43) ) { std::wprintf(L"Warn! Can not initialize console window. Windows error %i\n", ::GetLastError() ); } if(!::SetConsoleFont(hCons_, BOX_DRAWING_RASTER_FONT) ) { std::wprintf(L"Warn! Can not initialize console font. Windows error %i\n", ::GetLastError() ); } hStdIn_ = ::GetStdHandle(STD_INPUT_HANDLE); assert(INVALID_HANDLE_VALUE != hStdIn_); ::GetConsoleMode(hStdIn_, &ocm_); ::DWORD mode = ocm_; mode &= ~ENABLE_QUICK_EDIT_MODE; // disable system buffer from mouse selection mode &= ~ENABLE_PROCESSED_INPUT; // disable Ctrl+C system event mode = mode | ENABLE_MOUSE_INPUT | ENABLE_EXTENDED_FLAGS; // enable mouse assert(::SetConsoleMode(hStdIn_, mode) ); assert(::SetConsoleActiveScreenBuffer(hCons_)); ::SetConsoleCP(1200); // UTF16LE init_colors(hCons_); } terminal::~terminal() CURSES_NOEXCEPT { assert( ::SetConsoleMode(hStdIn_, ocm_) ); assert( ::SetConsoleActiveScreenBuffer(hStdOut_) ); ::CloseHandle(hCons_); if(extConsole_) { ::FreeConsole(); } } void terminal::init_colors(::HANDLE hcons) { ::COLORREF palette[16] = { 0x00000000, 0x00800000, 0x00008000, 0x00808000, 0x00000080, 0x00800080, 0x00008080, 0x00c0c0c0, 0x00808080, 0x00ff0000, 0x0000ff00, 0x00ffff00, 0x000000ff, 0x00ff00ff, 0x0000ffff, 0x00ffffff }; SetConsolePalette(hcons, palette); } inline ::WORD terminal::current_attributes() const { ::CONSOLE_SCREEN_BUFFER_INFO info; ::GetConsoleScreenBufferInfo(hCons_,&info); return info.wAttributes; } bounds terminal::get_bounds() const { ::CONSOLE_SCREEN_BUFFER_INFO info; ::GetConsoleScreenBufferInfo(hCons_,&info); return bounds(info.srWindow.Right+1,info.srWindow.Bottom+1); } void terminal::set_size(uint8_t width, uint8_t height) const { resize_console(hCons_,width,height); } void terminal::putch(const position& pos,char_t ch) const { put_line(pos,ch,1); } void terminal::move_cursor(uint8_t x, uint8_t y) const { ::COORD pos; pos.X = x; pos.Y = y; ::SetConsoleCursorPosition(hCons_, pos); } void terminal::set_cursor_visibility(bool visible) const { ::CONSOLE_CURSOR_INFO info; ::GetConsoleCursorInfo(hCons_, &info); info.bVisible = visible; // set the cursor visibility ::SetConsoleCursorInfo(hCons_, &info); } void terminal::put_line(const position& pos, char_t ch, uint8_t count) const { ::COORD coord; coord.X = pos.x; coord.Y = pos.y; ::DWORD written = 0; ::FillConsoleOutputCharacter(hCons_, ch, count, coord, &written); assert(written); ::WORD attrs = current_attributes(); ::FillConsoleOutputAttribute(hCons_, attrs, count, coord, &written); assert(written); } uint8_t terminal::put_text(const position& pos, const char_t* str) const { char_t *it = const_cast<char_t*>(str); position outp = pos; do { putch(outp,*it); ++outp.x; ++it; } while(*it != 0); return static_cast<uint8_t>(const_cast<const char_t*>(it)-str); } void terminal::fill_rectangle(const rectangle& r,char_t ch) const { position pos = r.left_top(); bounds bds = r.get_bounds(); uint8_t count = bds.width; uint8_t lines = r.left() + bds.height; for(uint8_t y = r.top(); y < lines; y++ ) { pos.y = y; put_line(pos,ch,count); } } void terminal::set_color(const text_color& color) const { assert(::SetConsoleTextAttribute(hCons_, color_to_attr(color))); } text_color terminal::current_color() const { return attrs_to_color(current_attributes()); } void terminal::clipt_rect(const rectangle& rect,texel* buff) const { ::COORD coordBufCoord; coordBufCoord.X = 0; coordBufCoord.Y = 0; bounds bds = rect.get_bounds(); ::COORD coordBufSize; coordBufSize.X = bds.width; coordBufSize.Y = bds.height; ::SMALL_RECT sr; sr.Left = rect.left(); sr.Top = rect.top(); sr.Right = rect.right(); sr.Bottom = rect.bottom(); CHAR_INFO *chiBuffer = reinterpret_cast<CHAR_INFO*>(buff); ::BOOL fSuccess = ::ReadConsoleOutputW( hCons_, // screen buffer to read from chiBuffer, // buffer to copy into coordBufSize, // col-row size of chiBuffer coordBufCoord, // top left dest. cell in chiBuffer &sr); // screen buffer source rectangle assert(fSuccess); } void terminal::paste_rect(const rectangle& rect, texel* data) const { ::COORD coordBufCoord; coordBufCoord.X = 0; coordBufCoord.Y = 0; bounds bds = rect.get_bounds(); ::COORD coordBufSize; coordBufSize.X = bds.width; coordBufSize.Y = bds.height; ::SMALL_RECT sr; sr.Left = rect.left(); sr.Top = rect.top(); sr.Right = rect.right(); sr.Bottom = rect.bottom(); ::CHAR_INFO *chiBuffer = reinterpret_cast<::CHAR_INFO*>(data); ::BOOL fSuccess = ::WriteConsoleOutputW( hCons_, // screen buffer to write to chiBuffer, // buffer to copy from coordBufSize, // col-row size of chiBuffer coordBufCoord, // top left src cell in chiBuffer &sr); // dest. screen buffer rectangle assert(fSuccess); } void terminal::set_window_title(const char_t* title) const { ::SetConsoleTitleW(title); } control_key_state terminal::extact_controls(::DWORD val) { control_key_state result; result.capslock = check_bit(val,CAPSLOCK_ON); result.enhanced = check_bit(val,ENHANCED_KEY); result.left_alt = check_bit(val,LEFT_ALT_PRESSED); result.left_ctrl = check_bit(val,LEFT_CTRL_PRESSED); result.numlock = check_bit(val,NUMLOCK_ON); result.right_alt = check_bit(val,RIGHT_ALT_PRESSED); result.right_ctrl = check_bit(val,RIGHT_CTRL_PRESSED); result.scrolllock = check_bit(val,SCROLLLOCK_ON); result.shift = check_bit(val,SHIFT_PRESSED); return result; } event terminal::create_key_event(const ::KEY_EVENT_RECORD& rcd) { event result; result.type = event_type::KEY; result.key.key_code = rcd.uChar.UnicodeChar; result.key.is_down = rcd.bKeyDown != FALSE; result.key.repeats = static_cast<uint8_t>(rcd.wRepeatCount); result.key.controls = extact_controls(rcd.dwControlKeyState); return result; } event terminal::create_mouse_event(const ::MOUSE_EVENT_RECORD& rcd) { event result; result.type = event_type::MOUSE; result.mouse.x = rcd.dwMousePosition.X; result.mouse.y = rcd.dwMousePosition.Y; result.mouse.state.first_btn = check_bit(rcd.dwButtonState,FROM_LEFT_1ST_BUTTON_PRESSED); result.mouse.state.second_btn = check_bit(rcd.dwButtonState,FROM_LEFT_2ND_BUTTON_PRESSED); result.mouse.state.third_btn = check_bit(rcd.dwButtonState,FROM_LEFT_3RD_BUTTON_PRESSED); result.mouse.state.fourth_btn = check_bit(rcd.dwButtonState,FROM_LEFT_4TH_BUTTON_PRESSED); result.mouse.state.double_click = check_bit(rcd.dwEventFlags,DOUBLE_CLICK); result.mouse.state.hor_wheeled = check_bit(rcd.dwEventFlags,MOUSE_HWHEELED); result.mouse.state.vert_wheeled = check_bit(rcd.dwEventFlags,MOUSE_WHEELED); result.mouse.state.moved = check_bit(rcd.dwEventFlags,MOUSE_MOVED); result.mouse.controls = extact_controls(rcd.dwControlKeyState); return result; } event terminal::create_resize_event(const ::WINDOW_BUFFER_SIZE_RECORD& rcd) { event result; result.type = event_type::RESIZE; result.resize.width = rcd.dwSize.X; result.resize.height = rcd.dwSize.Y; return result; } event terminal::wait_for_event() const { static ::INPUT_RECORD irb[1]; ::DWORD read = 0; while( !read ) { ::ReadConsoleInput(hStdIn_, irb, 1, &read); } switch(irb[0].EventType) { case KEY_EVENT: return create_key_event(irb[0].Event.KeyEvent); case MOUSE_EVENT: return create_mouse_event(irb[0].Event.MouseEvent); case WINDOW_BUFFER_SIZE_EVENT: return create_resize_event(irb[0].Event.WindowBufferSizeEvent); default: event ev; return ev; } } } // namespace curses
#include "node.h" #include "codegen.h" #include "parser.hpp" #include <string> using namespace std; static LLVMContext TheContext; static IRBuilder<> Builder(TheContext); static Function* mainFunc; static vector< pair <llvm::Type *,string > > pscVec; int curLang ; /* Compile the AST into a module */ void CodeGenContext::generateCode(NBlock& root) { std::cout << "Generating code...\n"; /* Create the top level interpreter function to call as entry */ BasicBlock* block = BasicBlock::Create(TheContext, "entry"); curLang = 2; if(curLang == 2) { vector<Type*> argTypes; argTypes.push_back(Type::getInt32Ty(MyContext)); FunctionType *ftype = FunctionType::get(Type::getVoidTy(MyContext), makeArrayRef(argTypes), false); Function *function = Function::Create(ftype, GlobalValue::ExternalLinkage, "printNum", this->module); } pushBlock(block); root.codeGen(*this); popBlock(); /* emit bytecode for the toplevel block */ /* Print the bytecode in a human-readable format to see if our program compiled properly */ std::cout << "Code is generated.\n"; //module->dump(); legacy::PassManager pm; pm.add(createPrintModulePass(outs())); pm.run(*module); } /* Executes the AST by running the main function */ GenericValue CodeGenContext::runCode() { std::cout << "Running code...\n"; ExecutionEngine *ee = EngineBuilder( unique_ptr<Module>(module) ).create(); ee->finalizeObject(); vector<GenericValue> noargs; GenericValue v = ee->runFunction(mainFunc, noargs); std::cout << "Code was run.\n"; return v; } /* Returns an LLVM type based on the identifier */ static Type *typeOf(const NIdentifier& type) { std::string typeStr = type.name; std::cout<<"look here\n"<<typeStr<<std::endl; if (type.name.compare("int") == 0) { return Type::getInt64Ty(MyContext); } else if (type.name.compare("string") == 0) { return Type::getInt8PtrTy(MyContext); } if(structType_map.find(typeStr) != structType_map.end()) { printf("\n\n\nritht\n\n"); return structType_map[typeStr]; } return Type::getVoidTy(MyContext); } /* -- Code Generation -- */ Value* NInteger::codeGen(CodeGenContext& context) { std::cout << "Creating integer: " << value << endl; return ConstantInt::get(Type::getInt64Ty(MyContext), value, true); } Value* NIdentifier::codeGen(CodeGenContext& context) { std::cout << "Creating identifier reference: " << name << endl; Value* tmpValue = context.getSymbolValue(name); if(tmpValue == nullptr) { std::cerr << "undeclared variable " << name << endl; return NULL; } return Builder.CreateLoad(tmpValue, false, ""); } Value* NMethodCall::codeGen(CodeGenContext& context) { //std::cout << "Creating method call: " << issd.name << endl; Function * calleeF = context.module->getFunction(this->id.name); if( !calleeF ){ printf("Function name not found\n"); } if( calleeF->arg_size() != this->arguments.size() ){ printf("Function arguments size not match, calleeF=\n"); } std::vector<Value*> argsv; for(auto it=this->arguments.begin(); it!=this->arguments.end(); it++){ argsv.push_back((*it)->codeGen(context)); if( !argsv.back() ){ // if any argument codegen fail return nullptr; } } std::cout << "\n\n success Creating method call: " << id.name << endl; return Builder.CreateCall(calleeF, argsv, "calltmp"); } Value* NBinaryOperator::codeGen(CodeGenContext& context) { cout << "Generating binary operator" << endl; Value* L = this->lhs.codeGen(context); Value* R = this->rhs.codeGen(context); switch (this->op){ case TPLUS: return Builder.CreateAdd(L, R, "addtmp"); case TMINUS: return Builder.CreateSub(L, R, "subtmp"); case TMUL: return Builder.CreateMul(L, R, "multmp"); case TDIV: return Builder.CreateSDiv(L, R, "divtmp"); case TCLT: return Builder.CreateICmpULT(L, R, "cmptmp"); case TCLE: return Builder.CreateICmpSLE(L, R, "cmptmp"); case TCGE: return Builder.CreateICmpSGE(L, R, "cmptmp"); case TCGT: return Builder.CreateICmpSGT(L, R, "cmptmp"); case TCEQ: return Builder.CreateICmpEQ(L, R, "cmptmp"); case TCNE: return Builder.CreateICmpNE(L, R, "cmptmp"); } return NULL; } Value* NAssignment::codeGen(CodeGenContext& context) { std::cout << "Creating assignment for " << lhs.name << endl; Value* dst = context.getSymbolValue(lhs.name); if(dst == nullptr) { std::cerr << "undeclared variable " << lhs.name << endl; return NULL; } Builder.CreateStore(rhs.codeGen(context), dst); return dst; } Value* NBlock::codeGen(CodeGenContext& context) { StatementList::const_iterator it; Value *last = NULL; for (it = statements.begin(); it != statements.end(); it++) { std::cout << "Generating code for " << typeid(**it).name() << endl; last = (**it).codeGen(context); } std::cout << "Creating block" << endl; return last; } Value* NExpressionStatement::codeGen(CodeGenContext& context) { std::cout << "Generating code for " << typeid(expression).name() << endl; return expression.codeGen(context); } Value* NReturnStatement::codeGen(CodeGenContext& context) { std::cout << "Generating return code for " << typeid(expression).name() << endl; Value *returnValue = expression.codeGen(context); context.setCurrentReturnValue(returnValue); return returnValue; } Value* NVariableDeclaration::codeGen(CodeGenContext& context) { std::cout << "Creating variable declaration asd" << type.name << " " << id.name << endl; if(curLang == 2) { pscVec.push_back({typeOf(type),id.name}); return nullptr; } Value * alloc = Builder.CreateAlloca(typeOf(type)); context.locals()[id.name] = alloc; std::cout<<id.name<<"'s value = "<<alloc<<endl; if (assignmentExpr != NULL) { NAssignment assn(id, *assignmentExpr); assn.codeGen(context); } return alloc; } Value* NExternDeclaration::codeGen(CodeGenContext& context) { vector<Type*> argTypes; VariableList::const_iterator it; for (it = arguments.begin(); it != arguments.end(); it++) { argTypes.push_back(typeOf((**it).type)); } FunctionType *ftype = FunctionType::get(typeOf(type), makeArrayRef(argTypes), false); Function *function = Function::Create(ftype, GlobalValue::ExternalLinkage, id.name.c_str(), context.module); return function; } Value* NFunctionDeclaration::codeGen(CodeGenContext& context) { vector<Type*> argTypes; VariableList::const_iterator it; for (it = arguments.begin(); it != arguments.end(); it++) { argTypes.push_back(typeOf((**it).type)); } FunctionType *ftype = FunctionType::get(typeOf(type), makeArrayRef(argTypes), false); cout<<"plc1"<<endl; Function *function = Function::Create(ftype, GlobalValue::InternalLinkage, id.name.c_str(), context.module); cout<<"plc2"<<endl; cout<<"kankan "<<id.name.c_str()<<"\n\n"; BasicBlock *bblock = BasicBlock::Create(MyContext, "entry", function, 0); string tmp = "main"; if(id.name.c_str()==tmp) { mainFunc = function; } context.pushBlock(bblock); Builder.SetInsertPoint(bblock); cout<<"p1"<<endl; Function::arg_iterator argsValues = function->arg_begin(); Value* argumentValue; for (it = arguments.begin(); it != arguments.end(); it++) { (**it).codeGen(context); argumentValue = &*argsValues++; argumentValue->setName((*it)->id.name.c_str()); StoreInst *inst = new StoreInst(argumentValue, context.locals()[(*it)->id.name], false, bblock); } if(curLang == 2) { for(auto tmpPair : pscVec) { llvm::Type* tmpType = tmpPair.first; string tmpName = tmpPair.second; Value * alloc = Builder.CreateAlloca(tmpType); context.locals()[tmpName] = alloc; std::cout<<tmpName<<"s value = "<<alloc<<endl; } } block.codeGen(context); if( context.getCurrentReturnValue() ){ Builder.CreateRet(context.getCurrentReturnValue()); } else{ Builder.CreateRet(0); } context.popBlock(); std::cout << "Creating function: " << id.name << endl; return function; }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "OnlineSessionSettings.h" #include "Engine/GameInstance.h" #include "MenuSystem/MenuInterface.h" #include "Interfaces/OnlineSessionInterface.h" #include "OnlineSubsystem.h" #include "COOP_GameInstance.generated.h" UCLASS() class COOPGAME_API UCOOP_GameInstance : public UGameInstance, public IMenuInterface { GENERATED_BODY() public: UCOOP_GameInstance(const FObjectInitializer& ObjectInitializer); virtual void Init() override; UFUNCTION(BlueprintCallable, Category = "COOP Game Instance") void HostGame(); UFUNCTION(BlueprintCallable, Category = "COOP Game Instance") void OnCreateNewSessionComplete(FName SessionName, bool Success); UFUNCTION(BlueprintCallable, Category = "COOP Game Instance") void FindNewSessions(); UFUNCTION(BlueprintCallable, Category = "COOP Game Instance") void OnFindSessionsComplete(bool Success); void OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result); UFUNCTION(BlueprintCallable, Category = "COOP Game Instance") void OnDestroySessionsComplete(); UFUNCTION(BlueprintCallable, Category = "COOP Game Instance") void JoinGame(int32 ServerIndex); UFUNCTION(BlueprintCallable, Category= "COOP Game Instance") void LoadMenu(); UFUNCTION(BlueprintCallable, Category = "COOP Game Instance") void LoadPauseMenu(); UFUNCTION(BlueprintCallable, Category = "COOP Game Instance") void ClientTravelToLevel(const FString& Address); UFUNCTION(BlueprintCallable, Category = "COOP Game Instance") void OnSessionLost(); UPROPERTY(EditAnywhere, Category= "COOP Game Instance") FString MainMenuLevel = "MainMenu"; private: FOnlineSessionSettings SessionSettings; TSubclassOf<class UUserWidget> MainMenuClass; TSubclassOf<class UUserWidget> PauseMenuClass; class UCOOP_MainMenu* MainMenu; class UCOOP_PauseMenu* PauseMenu; IOnlineSessionPtr SessionInterface; TSharedPtr<class FOnlineSessionSearch> SessionSearch; };
#include "Firebase_Client_Version.h" #if !FIREBASE_CLIENT_VERSION_CHECK(40319) #error "Mixed versions compilation." #endif /** * Google's Firebase QueryFilter class, QueryFilter.h version 1.0.7 * * This library supports Espressif ESP8266 and ESP32 * * Created December 19, 2022 * * This work is a part of Firebase ESP Client library * Copyright (c) 2023 K. Suwatchai (Mobizt) * * The MIT License (MIT) * Copyright (c) 2023 K. Suwatchai (Mobizt) * * * Permission is hereby granted, free of charge, to any person returning 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. */ #include "FirebaseFS.h" #ifdef ENABLE_RTDB #ifndef FIREBASE_QUERY_FILTER_H #define FIREBASE_QUERY_FILTER_H #include <Arduino.h> #include "FB_Utils.h" #include "signer/Signer.h" using namespace mb_string; class QueryFilter { friend class FirebaseData; friend class FB_RTDB; friend class FirebaseSession; public: QueryFilter(); ~QueryFilter(); template <typename T = const char *> QueryFilter &orderBy(T val) { return mOrderBy(toStringPtr(val)); } template <typename T = int> QueryFilter &limitToFirst(T val) { return mLimitToFirst(toStringPtr(val, -1)); } template <typename T = int> QueryFilter &limitToLast(T val) { return mLimitToLast(toStringPtr(val, -1)); } template <typename T = int> auto startAt(T val) -> typename enable_if<is_same<T, float>::value || is_same<T, double>::value || is_num_int<T>::value, QueryFilter &>::type { return mStartAt(toStringPtr(val, -1), false); } template <typename T = int> auto endAt(T val) -> typename enable_if<is_same<T, float>::value || is_same<T, double>::value || is_num_int<T>::value, QueryFilter &>::type { return mEndAt(toStringPtr(val, -1), false); } template <typename T = const char *> auto startAt(T val) -> typename enable_if<is_string<T>::value, QueryFilter &>::type { return mStartAt(toStringPtr(val), true); } template <typename T = const char *> auto endAt(T val) -> typename enable_if<is_string<T>::value, QueryFilter &>::type { return mEndAt(toStringPtr(val), true); } template <typename T = int> auto equalTo(T val) -> typename enable_if<is_num_int<T>::value, QueryFilter &>::type { return mEqualTo(toStringPtr(val), false); } template <typename T = const char *> auto equalTo(T val) -> typename enable_if<is_string<T>::value, QueryFilter &>::type { return mEqualTo(toStringPtr(val), true); } QueryFilter &clear(); private: MB_String _orderBy; MB_String _limitToFirst; MB_String _limitToLast; MB_String _startAt; MB_String _endAt; MB_String _equalTo; QueryFilter &mOrderBy(MB_StringPtr val); QueryFilter &mLimitToFirst(MB_StringPtr val); QueryFilter &mLimitToLast(MB_StringPtr val); QueryFilter &mStartAt(MB_StringPtr val, bool isString); QueryFilter &mEndAt(MB_StringPtr val, bool isString); QueryFilter &mEqualTo(MB_StringPtr val, bool isString); }; #endif #endif // ENABLE
void someFunc() { const char p[] = R"(a\ b c)"; }
/** * @file valknut/core/internal/integral_types.hpp * * @brief This internal header declares fixed size integral types * * @note This is an internal header file, included by other library headers. * Do not attempt to use it directly. */ #ifndef VALKNUT_CORE_INTERNAL_INTEGRAL_TYPES_HPP_ #define VALKNUT_CORE_INTERNAL_INTEGRAL_TYPES_HPP_ // Prevent pedantic errors for __int128 #if defined(__GNUC__) && (__GNUC__ >= 4) # pragma GCC system_header #endif #if defined(VALKNUT_COMPILER_CPP11) # include <cstdint> #elif defined(VALKNUT_PLATFORM_HAS_STDINT_H) # include <stdint.h> #elif !(defined(VALKNUT_COMPILER_MSVC) || defined(VALKNUT_COMPILER_INTEL)) # include <climits> #endif namespace valknut{ //! @addtogroup core //! @{ //-------------------------------------------------------------------------- // Integer Types //-------------------------------------------------------------------------- // define 128-bit types, if supported #ifdef VALKNUT_COMPILER_HAS_INT128 typedef signed __int128 s128; typedef unsigned __int128 u128; // We assume that s128 and u128 will also be the fastest and least types for // that type. A more accurate one could be overridden if necessary typedef s128 s128f; typedef u128 u128f; typedef s128 s128l; typedef u128 u128l; #endif // VALKNUT_COMPILER_HAS_INT128 #if VALKNUT_COMPILER_CPP11 // Basic signed typedef ::std::int8_t s8; ///< Signed 8-bit integer typedef ::std::int16_t s16; ///< Signed 16-bit integer typedef ::std::int32_t s32; ///< Signed 32-bit integer typedef ::std::int64_t s64; ///< Signed 64-bit integer // Basic unsigned typedef ::std::uint8_t u8; ///< Unsigned 8-bit integer typedef ::std::uint16_t u16; ///< Unsigned 16-bit integer typedef ::std::uint32_t u32; ///< Unsigned 32-bit integer typedef ::std::uint64_t u64; ///< Unsigned 64-bit integer // Fast signed typedef ::std::int_fast8_t s8f; ///< Fastest signed 8-bit integer typedef ::std::int_fast16_t s16f; ///< Fastest signed 16-bit integer typedef ::std::int_fast32_t s32f; ///< Fastest signed 32-bit integer typedef ::std::int_fast64_t s64f; ///< Fastest signed 64-bit integer // Fast unsigned typedef ::std::uint_fast8_t u8f; ///< Fastest unsigned 8-bit integer typedef ::std::uint_fast16_t u16f; ///< Fastest unsigned 16-bit integer typedef ::std::uint_fast32_t u32f; ///< Fastest unsigned 32-bit integer typedef ::std::uint_fast64_t u64f; ///< Fastest unsigned 64-bit integer // Least signed typedef ::std::int_least8_t s8l; ///< Least signed 8-bit integer typedef ::std::int_least16_t s16l; ///< Least signed 16-bit integer typedef ::std::int_least32_t s32l; ///< Least signed 32-bit integer typedef ::std::int_least64_t s64l; ///< Least signed 64-bit integer // Least unsigned typedef ::std::uint_least8_t u8l; ///< Least unsigned 8-bit integer typedef ::std::uint_least16_t u16l; ///< Least unsigned 16-bit integer typedef ::std::uint_least32_t u32l; ///< Least unsigned 32-bit integer typedef ::std::uint_least64_t u64l; ///< Least unsigned 64-bit integer // Max size int typedef ::std::intmax_t smaxint; ///< Maximum signed integer type typedef ::std::uintmax_t umaxint; ///< Maximum unsigned integer type // Pointer size typedef ::std::uintptr_t uptr; ///< Integer large enough for pointer address typedef ::std::ptrdiff_t ptrdiff; ///< Type representing difference between pointers #elif VALKNUT_PLATFORM_HAS_STDINT_H // Default to stdint's non-namespaced integers // Basic signed typedef ::int8_t s8; ///< Signed 8-bit integer typedef ::int16_t s16; ///< Signed 16-bit integer typedef ::int32_t s32; ///< Signed 32-bit integer typedef ::int64_t s64; ///< Signed 64-bit integer // Basic unsigned typedef ::uint8_t u8; ///< Unsigned 8-bit integer typedef ::uint16_t u16; ///< Unsigned 16-bit integer typedef ::uint32_t u32; ///< Unsigned 32-bit integer typedef ::uint64_t u64; ///< Unsigned 64-bit integer // Fast signed typedef ::int_fast8_t s8f; ///< Fastest signed 8-bit integer typedef ::int_fast16_t s16f; ///< Fastest signed 16-bit integer typedef ::int_fast32_t s32f; ///< Fastest signed 32-bit integer typedef ::int_fast64_t s64f; ///< Fastest signed 64-bit integer // Fast unsigned typedef ::uint_fast8_t u8f; ///< Fastest unsigned 8-bit integer typedef ::uint_fast16_t u16f; ///< Fastest unsigned 16-bit integer typedef ::uint_fast32_t u32f; ///< Fastest unsigned 32-bit integer typedef ::uint_fast64_t u64f; ///< Fastest unsigned 64-bit integer // Least signed typedef ::int_least8_t s8l; ///< Least signed 8-bit integer typedef ::int_least16_t s16l; ///< Least signed 16-bit integer typedef ::int_least32_t s32l; ///< Least signed 32-bit integer typedef ::int_least64_t s64l; ///< Least signed 64-bit integer // Least unsigned typedef ::uint_least8_t u8l; ///< Least unsigned 8-bit integer typedef ::uint_least16_t u16l; ///< Least unsigned 16-bit integer typedef ::uint_least32_t u32l; ///< Least unsigned 32-bit integer typedef ::uint_least64_t u64l; ///< Least unsigned 64-bit integer // Max size int typedef ::intmax_t smaxint; ///< Maximum signed integer type typedef ::uintmax_t umaxint; ///< Maximum unsigned integer type // Pointer size typedef ::uintptr_t uptr; ///< Integer large enough for pointer address typedef ::ptrdiff_t ptrdiff; ///< Type representing difference between pointers #else #if (VALKNUT_COMPILER_MSVC || VALKNUT_COMPILER_INTEL) // MSVC and Intel define intrinsic sizes // Basic signed typedef signed __int8 s8; ///< Signed 8-bit integer typedef signed __int16 s16; ///< Signed 16-bit integer typedef signed __int32 s32; ///< Signed 32-bit integer typedef signed __int64 s64; ///< Signed 64-bit integer // Basic unsigned typedef unsigned __int8 u8; ///< Unsigned 8-bit integer typedef unsigned __int16 u16; ///< Unsigned 16-bit integer typedef unsigned __int32 u32; ///< Unsigned 32-bit integer typedef unsigned __int64 u64; ///< Unsigned 64-bit integer #else // Have to manually discover sizes here #if (UCHAR_MAX == 0xff) typedef signed char s8; ///< Signed 8-bit integer typedef unsigned char u8; ///< Unsigned 8-bit integer #else #error "No 8-bit sized type available." #endif #if (USHRT_MAX == 0xffff) typedef signed short s16; ///< Signed 16-bit integer typedef unsigned short u16; ///< Unsigned 16-bit integer #elif (UINT_MAX == 0xffff) typedef signed int s16; ///< Signed 16-bit integer typedef unsigned int u16; ///< Unsigned 16-bit integer #endif #if (UINT_MAX == 0xffffffffL) typedef signed int s32; ///< Signed 32-bit integer typedef unsigned int u32; ///< Unsigned 32-bit integer #elif (ULONG_MAX == 0xffffffffL) typedef signed long s32; ///< Signed 32-bit integer typedef unsigned long u32; ///< Unsigned 32-bit integer #endif #if (ULONG_MAX == 0xffffffffffffffffL) typedef signed long s64; ///< Signed 64-bit integer typedef unsigned long u64; ///< Unsigned 64-bit integer #elif defined(VALKNUT_COMPILER_HAS_LONG_LONG) && \ ((defined(ULLONG_MAX) && (ULLONG_MAX == 0xffffffffffffffffLL)) || \ (defined(ULONG_LONG_MAX) && (ULONG_LONG_MAX == 0xffffffffffffffffLL))) typedef signed long long s64; ///< Signed 64-bit integer typedef unsigned long long u64; ///< Unsigned 64-bit integer #endif #endif // MSVC / Intel // There is no way for us to tell what is least/fastest, so assume that // each type is both the least and the fastest. // This can be optimized by a custom configuration if necessary, by // defining the constant VALKNUT_OVERRIDE_LEAST_MIN_INTS #ifndef VALKNUT_OVERRIDE_LEAST_MIN_INTS // Fast signed typedef s8 s8f; ///< Fastest signed 8-bit integer typedef s16 s16f; ///< Fastest signed 16-bit integer typedef s32 s32f; ///< Fastest signed 32-bit integer typedef s64 s64f; ///< Fastest signed 64-bit integer // Fast unsigned typedef u8 u8f; ///< Fastest unsigned 8-bit integer typedef u16 u16f; ///< Fastest unsigned 16-bit integer typedef u32 u32f; ///< Fastest unsigned 32-bit integer typedef u64 u64f; ///< Fastest unsigned 64-bit integer // Fast signed typedef s8 s8l; ///< Least signed 8-bit integer typedef s16 s16l; ///< Least signed 16-bit integer typedef s32 s32l; ///< Least signed 32-bit integer typedef s64 s64l; ///< Least signed 64-bit integer // Fast unsigned typedef u8 u8l; ///< Least unsigned 8-bit integer typedef u16 u16l; ///< Least unsigned 16-bit integer typedef u32 u32l; ///< Least unsigned 32-bit integer typedef u64 u64l; ///< Least unsigned 64-bit integer #endif // ifndef VALKNUT_OVERRIDE_LEAST_MIN_INTS // Max size int #if VALKNUT_COMPILER_HAS_INT128 typedef s128 smaxint; ///< Maximum signed integer type typedef u128 umaxint; ///< Maximum unsigned integer type #elif VALKNUT_COMPILER_HAS_LONG_LONG typedef s64 smaxint; ///< Maximum signed integer type typedef u64 umaxint; ///< Maximum unsigned integer type #else typedef s32 smaxint; ///< Maximum signed integer type typedef u32 umaxint; ///< Maximum unsigned integer type #endif // Pointer size #if VALKNUT_PLATFORM_PTR_SIZE == 4 typedef u32 uptr; ///< Integer large enough for pointer address typedef s32 ptrdiff; ///< Type representing difference between pointers #elif VALKNUT_PLATFORM_PTR_SIZE == 8 typedef u64 uptr; ///< Integer large enough for pointer address typedef s64 ptrdiff; ///< Type representing difference between pointers #endif // VALKNUT_PLATFORM_PTR_SIZE #endif // VALKNUT_COMPILER_CPP11 / VALKNUT_PLATFORM_HAS_STDINT_H //! @} } // namespace valknut #endif /* VALKNUT_CORE_INTERNAL_INTEGRAL_TYPES_HPP_ */
#include "Brain.hpp" #include <iomanip> const std::string Brain::identify(void) const { std::stringstream stream_ptr; const Brain *brain_ptr = this; const void *ptr_adr = static_cast<const void*>(this); stream_ptr << "0x" << std::uppercase << std::hex << (long long)(ptr_adr); return (stream_ptr.str()); } void Brain::show_iq(void) const { std::cout << "IQ: " << iq_ << std::endl; } void Brain::set_iq(int new_iq) { iq_ = new_iq; } Brain::Brain(int iq) : iq_(iq) { } Brain::Brain() : iq_(120) { } Brain::~Brain() { }
#include "VampireState.h" VampireState::VampireState(const std::string& name, int health, int damage, bool isUndead) : UnitState (name, health, health, damage, isUndead) { std::cout << " creating VampireState " << std::endl; } VampireState::~VampireState() { std::cout << " deleting VampireState " << std::endl; }
/* GT_EXTERNAL_LEGEND(2010) */ #ifndef GEN_KILL_TRANSFORMER_GUARD #define GEN_KILL_TRANSFORMER_GUARD 1 #include <iostream> #include <climits> #include <cassert> #include "wali/SemElem.hpp" /*! * @class GenKillTransformer_T * * GenKillTransformer_T is a templated class that implements the semiring * needed for a gen-kill dataflow-analysis problem. The template * parameter must implement the "Set" interface defined below * class Set { public: // not needed by GenKillTransformer_T but a good idea Set(); // Only Set constructor GenKillTransformer_T invokes Set( const Set& ); // not needed by GenKillTransformer_T but a good idea Set& operator=( const Set& ); static bool Eq( const Set& x, const Set& y ); static Set Diff( const Set& x, const Set& y, bool normalizing = false ); static Set Union( const Set& x, const Set& y ); static Set Intersect( const Set& x, const Set& y ); // Optional (but recommended) constant generator static const Set& UniverseSet(); // Optional (but recommended) constant generator static const Set& EmptySet(); std::ostream& print(std::ostream& o); }; For normal elements, a semiring element is represented by a pair of sets (k,g), which have the meaning \x.(x - k) union g. Note that if k and g were allowed to be arbitrary sets, it would introduce redundant elements into the domain: e.g., ({a,b}, {c,d}) would have the same meaning as ({a,b,c,d}, {c,d}). Therefore, there is a class invariant that k intersect g = empty, and the operation that builds a semiring element performs the normalization (k,g) |-> (k-g,g). However, often the universe of the domain is too large for k-g to be represented efficiently when k is the universal set; in this case, it may be acceptable to allow k and g to intersect iff k is the universe. (This also holds when Set is a cross product of domains and k has a universe component.) To support this, the normalization invokes the function Diff with normalizing==true. There are three special elements: 1. zero 2. one = (emptyset, emptyset) = \x.x 3. bottom = (emptyset, Univ) = \x.Univ Note that zero is a different element from the element (Univ, emptyset) The implementation maintains unique representations for zero */ template< typename Set > class GenKillTransformer_T : public wali::SemElem { public: // methods wali::sem_elem_t one() const { return MkOne(); } wali::sem_elem_t zero() const { return MkZero(); } wali::sem_elem_t bottom() const { return MkBottom(); } // A client uses makeGenKillTransformer_T to create a // GenKillTransformer_T instead of calling the constructor directly; // // makeGenKillTransformer_T normalizes the stored kill and gen sets // so that kill intersect gen == emptyset. // // makeGenKillTransformer_T also maintains unique representatives for the // special semiring values one, and bottom. // static wali::sem_elem_t makeGenKillTransformer_T(const Set& k, const Set& g ) { Set k_normalized = Set::Diff(k, g, true); if (Set::Eq(k_normalized, Set::EmptySet())&& Set::Eq(g, Set::UniverseSet())) { return MkBottom(); } else if (Set::Eq(k_normalized, Set::EmptySet()) && Set::Eq(g, Set::EmptySet())) { return MkOne(); } else { return new GenKillTransformer_T(k_normalized, g); } } ~GenKillTransformer_T() {} //------------------------------------------------- // Semiring methods //------------------------------------------------- static wali::sem_elem_t MkOne() { // Uses a method-static variable to avoid // problems with static-initialization order static GenKillTransformer_T* ONE = new GenKillTransformer_T(Set::EmptySet(), Set::EmptySet(), 1); return ONE; } bool IsOne() const { if(this == MkOne().get_ptr()) return true; assert(!Set::Eq(kill, Set::EmptySet()) || !Set::Eq(gen, Set::EmptySet())); return false; } // Zero is a special value that doesn't map to any gen/kill pair, // so all we really want out of this is a unique representative. // The gen/kill sets with which it is initialized are arbitrary. static wali::sem_elem_t MkZero() { // Uses a method-static variable to avoid // problems with static-initialization order static GenKillTransformer_T* ZERO = new GenKillTransformer_T(1); return ZERO; } bool IsZero() const { return is_zero; } static wali::sem_elem_t MkBottom() { // Uses a method-static variable to avoid // problems with static-initialization order static GenKillTransformer_T* BOTTOM = new GenKillTransformer_T(Set::EmptySet(), Set::UniverseSet(), 1); return BOTTOM; } bool IsBottom() const { if(this == MkBottom().get_ptr()) return true; assert(!Set::Eq(kill, Set::EmptySet()) || !Set::Eq(gen, Set::UniverseSet())); return false; } // // extend // // Return the extend of x (this) and y. // Considering x and y as functions, x extend y = y o x, // where (g o f)(v) = g(f(v)). // // FIXME: const: wali::SemElem::extend is not declared as const wali::sem_elem_t extend( wali::SemElem* _y ) { // Handle special case for either argument being zero() if( this->equal(zero()) || _y->equal(zero()) ) { return zero(); // zero extend _y = zero; this extend zero = zero } // Handle special case for either argument being one() if( this->equal(one()) ) { return _y; // one extend _y = _y } else if( _y->equal(one()) ) { return this; // this extend one = this } if( _y->equal(bottom()) ) { return bottom(); } const GenKillTransformer_T* y = dynamic_cast<GenKillTransformer_T*>(_y); Set temp_k( Set::Union( kill, y->kill ) ); Set temp_g( Set::Union( Set::Diff(gen,y->kill), y->gen) ); return makeGenKillTransformer_T( temp_k,temp_g ); } // FIXME: const: wali::SemElem::combine is not declared as const wali::sem_elem_t combine( wali::SemElem* _y ) { // Handle special case for either argument being zero() if( this->equal(zero()) ) { return _y; // zero combine _y = _y } if( _y->equal(zero()) ) { return this; // this combine zero = this } // Handle special case for either argument being bottom() if( this->equal(bottom()) || _y->equal(bottom()) ) { return bottom(); // bottom combine _y = bottom; } // this combine bottom = bottom const GenKillTransformer_T* y = dynamic_cast<GenKillTransformer_T*>(_y); Set temp_k( Set::Intersect( kill, y->kill ) ); Set temp_g( Set::Union( gen, y->gen ) ); return makeGenKillTransformer_T( temp_k,temp_g ); } wali::sem_elem_t quasiOne() const { return one(); } // // diff(GenKillTransformer_T* y) // // Return the difference between x (this) and y. // // The return value r has two properties: // 1. r ]= x, // i.e., isEqual(combine(x,r), x) == true // 2. y combine r = y combine a, // i.e., isEqual(combine(y,r), combine(y,a)) == true // wali::sem_elem_t diff( wali::SemElem* _y ) // const { // Handle special case for either argument being zero() if( this->equal(zero()) ) { return zero(); // zero - _y = zero } if( _y->equal(zero()) ) { return this; // this - zero = this } // Handle special case for second argument being bottom() if( _y->equal(bottom()) ) { return zero(); // this - bottom = zero } const GenKillTransformer_T* y = dynamic_cast<GenKillTransformer_T*>(_y); // Both *this and *y are proper (non-zero) values Set temp_k( Set::Diff(Set::UniverseSet(),Set::Diff(y->kill,kill)) ); Set temp_g( Set::Diff(gen,y->gen) ); return makeGenKillTransformer_T(temp_k, temp_g); } // Zero is a special representative that must be compared // by address rather by its contained Gen/Kill sets. bool isEqual(const GenKillTransformer_T* y) const { // Check for identical arguments: could be two special values (i.e., two // zeros, two ones, or two bottoms) or two identical instances of a // non-special semiring value. if(this == y) return true; // Return false if any argument is zero. // Zero has a unique representative, and thus the return value could // only be true via the preceding check for identicalness. // The same approach could be taken for one and bottom, but the // extra tests are not worth it. if(this->IsZero() || y->IsZero()) return false; return Set::Eq(kill,y->kill) && Set::Eq(gen,y->gen); } bool equal(wali::SemElem* _y) const { const GenKillTransformer_T* y = dynamic_cast<GenKillTransformer_T*>(_y); return this->isEqual(y); } bool equal(wali::sem_elem_t _y) const { const GenKillTransformer_T* y = dynamic_cast<GenKillTransformer_T*> (_y.get_ptr()); return this->isEqual(y); } std::ostream& print( std::ostream& o ) const { if(this->IsZero()) return o << "<zero>"; if(this->IsOne()) return o << "<one>"; if(this->IsBottom()) return o << "<bottom>"; o << "<\\S.(S - {"; kill.print(o); o << "}) U {"; gen.print(o); o << "}>"; return o; } std::ostream& prettyPrint( std::ostream& o ) const { return this->print(o); } //------------------------------------------------- // Other useful methods //------------------------------------------------- Set apply( const Set & input ) const { assert(!this->IsZero()); return Set::Union( Set::Diff(input,kill), gen ); } const Set& getKill() const { assert(!this->IsZero()); return kill; } const Set& getGen() const { assert(!this->IsZero()); return gen; } static std::ostream& print_static_transformers( std::ostream& o ) { o << "ONE\t=\t"; one()->print(o); o << std::endl; o << "ZERO\t=\t"; zero()->print(o); o << std::endl; o << "BOTTOM\t=\t"; bottom()->print(o); o << std::endl; return o; } private: // methods ----------------------------------------------------------- // Constructors // The constructors are private to ensure uniqueness of one, zero, and bottom // Constructor for legitimate values GenKillTransformer_T(const Set& k, const Set& g, unsigned int c=0) : wali::SemElem(), kill(k), gen(g), is_zero(false) { count = c; } // Constructor for zero GenKillTransformer_T(unsigned int c=0) : wali::SemElem(), is_zero(true) { count = c; } private: // members ----------------------------------------------------------- Set kill, gen; // Used to represent the function \S.(S - kill) U gen bool is_zero; // True for the zero element, False for all other values }; template< typename Set > std::ostream & operator<< (std::ostream& out, const GenKillTransformer_T<Set> & t) { t.print(out); return out; } // Yo, Emacs! // Local Variables: // c-file-style: "ellemtel" // c-basic-offset: 2 // End: #endif
#ifndef ZOMBIE_HPP # define ZOMBIE_HPP # include <string> # include <iostream> class Zombie { private: std::string name_; std::string type_; Zombie(); public: Zombie(const std::string &name, const std::string &type); ~Zombie(); void set_name(const std::string &new_name); void announce(void) const; }; #endif
/* * main.cpp * * Created on: Apr 1, 2015 * Author: eddy */ #include <iostream> #include <ncurses.h> #include "Game.h" //testing only #include "Window.h" int main(void){ // initscr(); // refresh(); // Window win; // win.create("test", 'x', 5, 9, 3, 35); // win.print_number(2); // getch(); // endwin(); Game game; game.init(); game.run(); return 0; }
SRC_URI += "file://add-subdir-objects-option.patch" libslp-location-dev_files += "${prefix}/lib/lib*.so"
#include <fstream> #include <string> #include <set> #include <vector> #include <assert.h> #include <windows.h> #include "../Md5Utils/Md5Utils.h" void ScanFiles(const std::string& dir, std::set<std::string>& names) { WIN32_FIND_DATAA finddata; std::string searchstring = dir + "*"; HANDLE hfine = FindFirstFileA(searchstring.c_str(), &finddata); if (hfine != INVALID_HANDLE_VALUE) { do { if (finddata.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) { if(strcmp(finddata.cFileName, ".svn")!=0&& strcmp(finddata.cFileName, ".")!=0&& strcmp(finddata.cFileName, "..")!=0) ScanFiles(dir + finddata.cFileName + "/", names); continue; } if(strstr(finddata.cFileName, ".hs")==0) { std::string name = dir; name += finddata.cFileName; names.insert(name); } } while (FindNextFileA(hfine, &finddata)); } FindClose(hfine); } int main(int argc, char** argv) { _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); std::ifstream except_list("exceptionlist.txt"); std::set<std::string> exception_files; std::string filename; while(except_list>>filename) { assert(exception_files.find(filename)==exception_files.end()); exception_files.insert(filename); } std::set<std::string> names; ScanFiles("", names); for(std::set<std::string>::iterator it = exception_files.begin(); it != exception_files.end(); ++it) { std::set<std::string>::iterator it_remove = names.find(*it); if(it_remove != names.end()) { names.erase(it_remove); } } FILE* hash_file = fopen("hash.txt", "w"); for(std::set<std::string>::iterator it = names.begin(); it != names.end(); ++it) { unsigned char hash[16]; std::vector<Md5Digest> hset; std::string name = *it; do { offset_type l; GenerateHash(name, hash, hset, l); char out[33]; HashToString(hash, out); fprintf(hash_file, "%s %lld %s\n", name.c_str(), l.offset, out); if(hset.size()>32) { std::string hashset_name(name + ".hs"); FILE* hashset_file = fopen(hashset_name.c_str(), "w"); fprintf(hashset_file, "%lld\n", l.offset); for(std::vector<Md5Digest>::iterator iter = hset.begin(); iter != hset.end() ; ++iter) { char out[33]; HashToString(iter->hash, out); fprintf(hashset_file, "%s\n", out); } fclose(hashset_file); name = hashset_name; } }while(hset.size()>32); } fclose(hash_file); return 0; }
#include "stdafx.h" #include "CAct_Dist.h" #include "../../Monster.h" #include "../ACTEffect.h" #include "../../../GameData.h" void CAct_Dist::Fire(Monster* me, Monster* target, const wchar_t* effectPath, const wchar_t* soundPath, float range, float baseDamage, CVector3 effectScale) { RotateToTarget(me, target); m_beamefk = NewGO<CEffect>(0); m_beamefk->SetPosition(target->Getpos()); CQuaternion er = CQuaternion::Identity(); er.SetRotationDeg(CVector3::AxisY(), 180); er.Multiply(me->GetRotation()); m_beamefk->SetRotation(er); m_beamefk->SetScale(effectScale); m_beamefk->Play(effectPath); Sound* sound = NewGO<Sound>(0, "snd"); sound->Init(soundPath); sound->Play(); crs = target->Getpos() - me->Getpos(); crs.Cross(CVector3::Up()); crs.Normalize(); crs *= range; m_targetPosition = target->Getpos(); m_me = me; m_baseDamage = baseDamage; } bool CAct_Dist::DamageCalc() { if (!m_beamefk->IsPlay()) return true; //for (auto mon : g_mons) { // if (mon == nullptr or mon == m_me) continue; // if (!IsHitting(mon, m_me)) continue; // float dmg = m_me->GetExAttack() * m_baseDamage; // mon->DamageEx(dmg); // if (m_state == ACTEffectGrant::State::enNull) continue; // if (m_isAbnormal[mon]) continue; // m_timerForGrantAbs[mon] += IGameTime().GetFrameDeltaTime(); // if (m_timerForGrantAbs[mon] > m_grantAbsTime) // GrantAbnormalState(mon, m_me, m_absEfkPath, m_state, m_DoTEndTime, m_DoTDamage); //} return false; }
#include <iostream> #include <functional> #include <map> #include <iterator> #include <any> #include <string> #include <vector> #include "CPPO.h" using namespace std; // CPPO implementation vector<string> nusstudios::core::mapping::strsplit(string s, string delimiter) { vector<string> result = {}; size_t pos = 0; string token; while ((pos = s.find(delimiter)) != string::npos) { token = s.substr(0, pos); if (token.length() != 0) { result.push_back(token); } s.erase(0, pos + delimiter.length()); } if (s.length() != 0) { result.push_back(s); } return result; } void nusstudios::core::mapping::iterate(string path, map<string, any> &mref, function<void(string, any)> callback, string path_sep) { for (auto itr = mref.begin(); itr != mref.end(); itr++) { string key = itr->first; any value = itr->second; string _path = path + path_sep + key; if (value.type() == typeid(map<string, any>)) { auto _value = any_cast<map<string, any>>(value); nusstudios::core::mapping::iterate(_path, _value, callback, path_sep); } else { callback(_path, value); } } if (mref.empty()) { callback(path, mref); } } string nusstudios::core::mapping::getleaf(string path, string path_sep) { size_t pos; if ((pos = path.rfind(path_sep)) == string::npos) { return path; } else { return path.substr(pos + 1); } } string nusstudios::core::mapping::getdiff(string fullp, string pp) { return fullp.substr(pp.length()); } string nusstudios::core::mapping::getmum(string path, string path_sep) { size_t pos; if ((pos = path.rfind(path_sep)) == string::npos) { return ""; } else { return path.substr(0, pos); } } bool nusstudios::core::mapping::hasindirection(string path, string path_sep) { return string::npos != path.find(path_sep); } vector<string> nusstudios::core::mapping::splitpath(string path, string path_sep) { return nusstudios::core::mapping::strsplit(path, path_sep); } template<class t> void nusstudios::core::mapping::printv(vector<t> &lst) { for (int i = 0; i < lst.size(); i++) { cout << (i == 0 ? "[ " : ""); cout << lst[i]; cout << (i != (lst.size() - 1) ? ", " : ""); cout << (i == (lst.size() - 1) ? " ]" : ""); } } any nusstudios::core::mapping::query(map<string, any>* mptr, string path, string &foundPath, string path_sep) { vector vctr = nusstudios::core::mapping::strsplit(path, path_sep); map<string, any> *submap = mptr; any* child; for (int i = 0; i < vctr.size(); i++) { if (submap->find(vctr[i]) != submap->end()) { if (foundPath.length() != 0) { foundPath += path_sep; } foundPath += vctr[i]; child = &submap->at(vctr[i]); if ((*child).type() == typeid(map<string, any>)) { submap = any_cast<map<string, any>>(child); if (i == vctr.size() - 1) return child; } else { return child; } } else { if (i == 0) { break; } else { return child; } } } return submap; } bool nusstudios::core::mapping::del(map<string, any>* mptr, string path, string path_sep) { string mom = nusstudios::core::mapping::getmum(path, path_sep); string pth; any node = nusstudios::core::mapping::query(mptr, mom, pth, path_sep); if (mom == pth) { string leaf = nusstudios::core::mapping::getleaf(path, path_sep); map<string, any>* ptr; if (nusstudios::core::mapping::hasindirection(path, path_sep)) { any* _ptr = any_cast<any*>(node); ptr = any_cast<map<string, any>>(_ptr); } else { ptr = any_cast<map<string, any>*>(node); } (*ptr).erase(leaf); return true; } else { return false; } } bool nusstudios::core::mapping::update(map<string, any>* mptr, string path, any value, string path_sep) { string pth; any a = nusstudios::core::mapping::query(mptr, path, pth, path_sep); if (pth == path) { if (pth == "") { if (value.type() == typeid(map<string, any>)) { map<string, any>* mp = any_cast<map<string, any>*>(a); *mp = any_cast<map<string, any>>(value); return true; } else { return false; } } else { any* ptr = any_cast<any*>(a); *ptr = value; return true; } } else { map<string, any> *mp; if (a.type() == typeid(any*)) { any* ptr = any_cast<any*>(a); if ((*ptr).type() != typeid(map<string, any>)) { return false; } else { mp = any_cast<map<string, any>>(ptr); } } else { mp = any_cast<map<string, any>*>(a); } vector<string> nonextpath = nusstudios::core::mapping::strsplit(getdiff(path, pth), path_sep); for (int i = 0; i < nonextpath.size() - 1; i++) { string nxtpth = nonextpath[i]; mp->insert({nxtpth, map<string, any>()}); mp = any_cast<map<string, any>>(&mp->at(nxtpth)); } mp->insert({nonextpath[nonextpath.size() - 1], value}); return true; } } nusstudios::core::mapping::CPPO::CPPO(map<string, any> inm, string path_separator) { _map = inm; path_sep = path_separator; printfunc = [this] (string path, any element) -> void { cout << endl << path << path_sep; if (element.type() == typeid(string)) { cout << any_cast<string>(element); } else if (element.type() == typeid(int)) { cout << any_cast<int>(element); } else if (element.type() == typeid(const char*)) { cout << any_cast<const char*>(element); } else if (element.type() == typeid(map<string, any>)) { // nothing } }; }; nusstudios::core::mapping::CPPO::~CPPO() {}; string nusstudios::core::mapping::CPPO::getleaf(string path) { return nusstudios::core::mapping::getleaf(path, path_sep); } string nusstudios::core::mapping::CPPO::getdiff(string fullp, string pp) { return nusstudios::core::mapping::getdiff(fullp, pp); } string nusstudios::core::mapping::CPPO::getmum(string path) { return nusstudios::core::mapping::getmum(path, path_sep); } bool nusstudios::core::mapping::CPPO::hasindirection(string path) { return nusstudios::core::mapping::hasindirection(path, path_sep); } vector<string> nusstudios::core::mapping::CPPO::splitpath(string path) { return nusstudios::core::mapping::splitpath(path, path_sep); } bool nusstudios::core::mapping::CPPO::update(string path, any value) { return nusstudios::core::mapping::update(&_map, path, value, path_sep); } bool nusstudios::core::mapping::CPPO::del(string path) { return nusstudios::core::mapping::del(&_map, path, path_sep); } any nusstudios::core::mapping::CPPO::queryptr(string path, string& found_path, bool cast_child_from_any_to_map_if_possible) { any a = nusstudios::core::mapping::query(&_map, path, found_path, path_sep); if (a.type() == typeid(map<string, any>*)) { nusstudios::core::mapping::CPPOPtr r(any_cast<map<string, any>*>(a), path_sep); return r; } else { any* optr = any_cast<any*>(a); if ((*optr).type() == typeid(map<string, any>)) { if (cast_child_from_any_to_map_if_possible) { nusstudios::core::mapping::CPPOPtr r(any_cast<map<string, any>>(optr), path_sep); return r; } else { return optr; } } else { return optr; } } } any nusstudios::core::mapping::CPPO::querycpy(string path, string &foundPath) { any a = nusstudios::core::mapping::query(&_map, path, foundPath, path_sep); if (a.type() == typeid(map<string, any>*)) { nusstudios::core::mapping::CPPO r(*any_cast<map<string, any>*>(a), path_sep); return r; } else { any* optr = any_cast<any*>(a); if ((*optr).type() == typeid(map<string, any>)) { nusstudios::core::mapping::CPPO r(any_cast<map<string, any>>(*optr), path_sep); return r; } else { return *optr; } } } void nusstudios::core::mapping::CPPO::printm(function<void(string, any)> callback) { nusstudios::core::mapping::iterate("root", _map, callback, path_sep); } void nusstudios::core::mapping::CPPO::printm() { nusstudios::core::mapping::iterate("root", _map, printfunc, path_sep); } // CPPOPtr implementation nusstudios::core::mapping::CPPOPtr::CPPOPtr(map<string, any>* mptr, string path_separator) { _map = mptr; path_sep = path_separator; printfunc = [this] (string path, any element) -> void { cout << endl << path << path_sep; if (element.type() == typeid(string)) { cout << any_cast<string>(element); } else if (element.type() == typeid(int)) { cout << any_cast<int>(element); } else if (element.type() == typeid(const char*)) { cout << any_cast<const char*>(element); } else if (element.type() == typeid(map<string, any>)) { // nothing } }; } nusstudios::core::mapping::CPPOPtr::~CPPOPtr() {}; string nusstudios::core::mapping::CPPOPtr::getleaf(string path) { return nusstudios::core::mapping::getleaf(path, path_sep); } string nusstudios::core::mapping::CPPOPtr::getdiff(string fullp, string pp) { return nusstudios::core::mapping::getdiff(fullp, pp); } string nusstudios::core::mapping::CPPOPtr::getmum(string path) { return nusstudios::core::mapping::getmum(path, path_sep); } bool nusstudios::core::mapping::CPPOPtr::hasindirection(string path) { return nusstudios::core::mapping::hasindirection(path, path_sep); } vector<string> nusstudios::core::mapping::CPPOPtr::splitpath(string path) { return nusstudios::core::mapping::splitpath(path, path_sep); } bool nusstudios::core::mapping::CPPOPtr::update(string path, any value) { return nusstudios::core::mapping::update(_map, path, value, path_sep); } bool nusstudios::core::mapping::CPPOPtr::del(string path) { return nusstudios::core::mapping::del(_map, path, path_sep); } any nusstudios::core::mapping::CPPOPtr::queryptr(string path, string& foundPath, bool cast_child_from_any_to_map_if_possible) { any a = nusstudios::core::mapping::query(_map, path, foundPath, path_sep); if (a.type() == typeid(map<string, any>*)) { nusstudios::core::mapping::CPPOPtr r(any_cast<map<string, any>*>(a), path_sep); return r; } else { any* optr = any_cast<any*>(a); if ((*optr).type() == typeid(map<string, any>)) { if (cast_child_from_any_to_map_if_possible) { nusstudios::core::mapping::CPPOPtr r(any_cast<map<string, any>>(optr), path_sep); return r; } else { return optr; } } else { return optr; } } } any nusstudios::core::mapping::CPPOPtr::querycpy(string path, string &foundPath) { any a = nusstudios::core::mapping::query(_map, path, foundPath, path_sep); if (a.type() == typeid(map<string, any>*)) { Mapping:CPPO r(*any_cast<map<string, any>*>(a), path_sep); return r; } else { any* optr = any_cast<any*>(a); if ((*optr).type() == typeid(map<string, any>)) { nusstudios::core::mapping::CPPO r(any_cast<map<string, any>>(*optr), path_sep); return r; } else { return *optr; } } } void nusstudios::core::mapping::CPPOPtr::printm(function<void(string, any)> callback) { nusstudios::core::mapping::iterate("root", *_map, callback, path_sep); } void nusstudios::core::mapping::CPPOPtr::printm() { nusstudios::core::mapping::iterate("root", *_map, printfunc, path_sep); } // using namespace nusstudios::core::mapping; int main() { /* CPPO obj({}, ">"); obj.update("key1", 5); obj.update("key2>asdfgh>qwerty>foo>bar", "const char*"); obj.update("string literal", string("str")); obj.printm(); cout << endl << endl; obj.del("key1"); obj.del("key2>asdfgh>foo"); obj.printm(); cout << endl << endl; string outp; any a = obj.queryptr("key2>asdfgh", outp, true); nusstudios::core::mapping::CPPOPtr aptr = any_cast<nusstudios::core::mapping::CPPOPtr>(a); aptr.update("yxc", 6); obj.printm(); any _a = obj.queryptr("key2>asdfgh", outp, false); any* _aptr = any_cast<any*>(_a); *_aptr = "map replaced with const char"; cout << endl << endl; obj.printm(); any a2 = obj.querycpy("key2", outp); nusstudios::core::mapping::CPPO _a2 = any_cast<nusstudios::core::mapping::CPPO>(a2); _a2.update("nxt", 5); cout << endl << endl; obj.printm(); */ }
#ifndef PERSPECTIVE_CUBE_HPP_ #define PERSPECTIVE_CUBE_HPP_ #include <string> namespace perspective_cube { extern const std::string module_name; int run(int argc, char **argv); } #endif // PERSPECTIVE_CUBE_HPP_
#include<fstream> #include<iostream> #include<stdexcept> using namespace std; void funcOne() throw(exception); void funcTwo() throw(exception); int main(int argc,char** argv) { try { funcOne(); } catch(exception& e) { cerr<<"Exception caught!\n"; exit(1); } return (0); } void funcOne() throw(exception) { string str1; string* str2=new string(); try { funcTwo(); } catch (...) { delete str2; throw ;//Rethrow the exception. } delete str2; } void funcTwo() throw(excepion) { ifstream istr; istr.open("filename"); throw exception(); istr.close(); }
/**************************************************************************************** * Copyright (c) 2010 www.projectiris.co.uk * * Michael Boyd <mb109@doc.ic.ac.uk>, Dragos Carmaciu <dc2309@doc.ic.ac.uk>, * * Francis Giannaros <kg109@doc.ic.ac.uk>, Thomas Payne <tp1809@doc.ic.ac.uk> and * * William Snell <ws1309@doc.ic.ac.uk>. * * Students at Imperial College London <http://imperial.ac.uk/computing> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ #include <QApplication> #include "mainwindow.h" #include <QDirIterator> #include <QDir> #include <QDebug> #include <QStringList> int main(int argc, char *argv[]) { QDir outputDir; // Create output directory if it doesn't exist yet outputDir.mkdir("output"); QApplication app(argc, argv); MainWindow mainWin; // If file given, load it automatically if (argc == 2) mainWin.loadFile(argv[1]); // Allow us to do some batch filtering on images else if(argc == 3 && QString(argv[1]) == "-b") { QString inputFolder = QDir::currentPath() + "/" + argv[2]; QString outputFolder = QDir::currentPath() + "/" + argv[3]; QDir outputDir; // Create output directory if it doesn't exist yet outputDir.mkdir(outputFolder); QStringList filterList; // Filter to only one image per person filterList << "*/2/*" << "*1_2.bmp"; // Iterate over all subdirectories, getting the right files QDirIterator it(inputFolder, filterList, QDir::Files, QDirIterator::Subdirectories); while (it.hasNext()) { QString currentFile = it.next(); qDebug() << "Now converting" << QFileInfo(currentFile).baseName(); mainWin.loadFile(currentFile); } } mainWin.show(); return app.exec(); }
#include<iostream> #include <torch/nn/module.h> #include <torch/nn/modules/linear.h> struct TestModuleImpl : public torch::nn::Cloneable<TestModuleImpl> { using torch::nn::Module::register_module; torch::nn::Linear l1{nullptr}, l2{nullptr}, l3{nullptr}; #if 0 TestModuleImpl() : l1(register_module("l1", torch::nn::Linear(10, 3))), l2(register_module("l2", torch::nn::Linear(3, 5))), l3(register_module("l3", torch::nn::Linear(5, 100))) { // Empty } #endif TestModuleImpl() { reset(); } void reset() override { l1 = register_module("l1", torch::nn::Linear(10, 3)); l2 = register_module("l2", torch::nn::Linear(3, 5)); l3 = register_module("l3", torch::nn::Linear(5, 100)); } }; TORCH_MODULE(TestModule); int main() { //TestModule m; auto m = std::make_shared<TestModule>(); // TestModuleImpl m; torch::Device device(torch::kCUDA, 0); m->to(device); m->parameters(); return 0; }
#ifndef MAMIFER_H #define MAMIFER_H #include "animal.h" #include <string.h> class mamifer : public animal { public: mamifer(){} mamifer(std::string price, int x):animal(price,x){} std::string Specie(); }; #endif // MAMIFER_H
#include <iostream> #include "Fraction.h" using namespace std; int main() { Fraction f1(1, 2); Fraction f2(1, 3); Fraction f3 = f1.add(f2); f1.display(); cout << "+"; f2.display(); cout << "="; f3.display(); cout << endl; Fraction f4 = f1.sub(f2); f1.display(); cout << "-"; f2.display(); cout << "="; f4.display(); cout << endl; Fraction f5 = f1.mul(f2); f1.display(); cout << "* 1/3 = "; f5.display(); cout << endl; Fraction f6 = f1.div(f2); f1.display(); cout << "나누기 1/3 = "; f6.display(); cout << endl; return 0; }
#pragma once #include "commands.hpp" namespace yama { //////////////////////////////////////////////////////////////////////////////// //! The game engine; divorced from system specifics. //////////////////////////////////////////////////////////////////////////////// class engine { public: engine(); ~engine(); void update(); void render(); void run(); void on_command(command_type cmd); void on_motion(int dx, int dy); void on_move_to(int x, int y); private: class impl_t; std::unique_ptr<impl_t> impl_; }; } //namespace yama
/************************************************************************/ /* 28、搜狐笔试题:给定一个实数数组,按序排列(从小到大) * ,从数组从找出若干个数,使得这若干个数的和与M最为接近,描述一个算法,并给出算法的复杂度 */ /************************************************************************/ #include <map> #include <vector> using namespace std; class Solution{ public: Solution(){ record.first = 10000; } vector<int> Closet(const vector<int> &argData, int target){ data = argData; for(int i = 0 ; i < data.size(); ++i){ if(abs(target - data[i]) < abs(record.first)){ record.first = target - data[i]; record.second.clear(); record.second.push_back(data[i]); } } for(int i = data.size(); i >= 2; --i){ vector<int> availRecord; GetCloset(0, data.size() - 1, i,target, availRecord); } return record.second; } private: pair<int, vector<int> > record; vector<int> data; vector<vector<int> > zeroRecord; void GetCloset(int start, int end, int k, int target, vector<int> &tRecord){ if(start >= end){ return; } if(k == 2){ int posLeft; int posRight; int result = TwoClosetSum(start, end, target, posLeft, posRight); if(abs(record.first) > abs(result) || result == 0){ record.first = result; tRecord.push_back(data[posRight]); tRecord.push_back(data[posLeft]); record.second = tRecord; if(result == 0){ zeroRecord.push_back(tRecord); } } } else{ for(int i = start; i <= end; ++i){ vector<int> temp = tRecord; temp.push_back(data[i]); GetCloset(i + 1, end, k - 1, target - data[i], temp); } } } int TwoClosetSum(int start, int end, int target, int &posLeft, int &posRight){ int closet = 10000; int i = start, j = end; int sum = data[start] + data[end]; while(i < j){ if(abs(target - sum) < abs(target - closet)){ closet = sum; posLeft = i; posRight = j; } if(sum == target){ break; } else if(sum < target){ ++i; sum = data[i] + data[j]; } else if(sum > target){ --j; sum = data[j] + data[i]; } } return target - closet; } }; //int main(){ // vector<int> data; // int A[] = {7,8,10,11,12}; // for(int i = 0; i < sizeof(A) / sizeof(A[0]); ++i){ // data.push_back(A[i]); // } // Solution solution; // solution.Closet(data, 8); // return 0; //}
#include<iostream> #include<queue> #include<stack> #include<vector> #include<stdio.h> #include<algorithm> #include<string> #include<string.h> #include<sstream> #include<math.h> #include<iomanip> #include<map> #define N 1005 #define M 25005 using namespace std; int root[N]; long long cost[N]; struct edge{ int from, to, len; edge(){} edge(int a, int b, int c){from = a; to = b; len =c;} bool operator <(const edge& e) const{return len<e.len;} } edges[M]; int find (int a) { if (root[a] < 0) return a; else return root[a] = find(root[a]); } void UnionSet (int set1, int set2, int c) { root[set1] += root[set2]; cost[set1] += cost[set2] + c; root[set2] = set1; } void Union (int a, int b, int c) { int root1=find(a); int root2=find(b); if (root[root1] < root[root2]) UnionSet(root1, root2, c); else UnionSet(root2, root1, c); } int main(){ int n,m,u,v,c,e,r,point; bool noway; while(scanf("%d %d", &n, &m)){ if(n==0 && m==0) break; memset(root,-1,sizeof(root)); memset(cost,0,sizeof(cost)); noway = true; e = 0; for(int j=0; j<m; j++){ scanf("%d %d %d", &u,&v,&c); edges[e++] = edge(u,v,c); } sort(edges, edges+e); queue<int> unuse; for(int j=0; j<e; j++){ int ui = edges[j].from; int vi = edges[j].to; int len = edges[j].len; if(find(ui) != find(vi)){ Union(ui,vi,len); r = find(ui); if(root[r] == -n){ point = j; noway = false; break; } }else{ unuse.push(len); } } if(noway) printf("\\(^o^)/ pray to god\n"); else{ printf("Min cost: %d\n", cost[r]); while(!unuse.empty()){ printf("%d ", unuse.front()); unuse.pop(); } if(point+1<e) printf("%d", edges[point+1].len); for(int j=point+2; j<e; j++){ printf(" %d", edges[j].len); } printf("\n"); } } return 0; }
// -*- LSST-C++ -*- /* * LSST Data Management System * Copyright 2012-2015 AURA/LSST. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <http://www.lsstcorp.org/LegalNotices/>. */ /** * @file * * @brief Task is a bundle of query task fields * * @author Daniel L. Wang, SLAC */ // Class header #include "wbase/Task.h" // Third-party headers #include "boost/regex.hpp" // LSST headers #include "lsst/log/Log.h" // Qserv headers #include "proto/TaskMsgDigest.h" #include "proto/worker.pb.h" #include "wbase/Base.h" #include "wbase/SendChannel.h" namespace { std::ostream& dump(std::ostream& os, lsst::qserv::proto::TaskMsg_Fragment const& f) { os << "frag: " << "q="; for(int i=0; i < f.query_size(); ++i) { os << f.query(i) << ","; } if(f.has_subchunks()) { os << " sc="; for(int i=0; i < f.subchunks().id_size(); ++i) { os << f.subchunks().id(i) << ","; } } os << " rt=" << f.resulttable(); return os; } } // annonymous namespace namespace lsst { namespace qserv { namespace wbase { // Task::ChunkEqual functor bool Task::ChunkEqual::operator()(Task::Ptr const& x, Task::Ptr const& y) { if(!x || !y) { return false; } if((!x->msg) || (!y->msg)) { return false; } return x->msg->has_chunkid() && y->msg->has_chunkid() && x->msg->chunkid() == y->msg->chunkid(); } // Task::PtrChunkIdGreater functor bool Task::ChunkIdGreater::operator()(Task::Ptr const& x, Task::Ptr const& y) { if(!x || !y) { return false; } if((!x->msg) || (!y->msg)) { return false; } return x->msg->chunkid() > y->msg->chunkid(); } std::string const Task::defaultUser = "qsmaster"; util::Sequential<int> Task::sequence{0}; IdSet Task::allTSeq{}; Task::Task() { tSeq = sequence.incr(); allTSeq.add(tSeq); LOGF_DEBUG("Task tSeq=%1% :%2%" % tSeq % allTSeq); } Task::Task(Task::TaskMsgPtr const& t, SendChannel::Ptr const& sc) : msg{t}, sendChannel{sc} { hash = hashTaskMsg(*t); dbName = "q_" + hash; if(t->has_user()) { user = t->user(); } else { user = defaultUser; } timestr[0] = '\0'; tSeq = sequence.incr(); allTSeq.add(tSeq); LOGF_DEBUG("Task(...) tSeq=%1% :%2%" % tSeq % allTSeq); } Task::~Task() { allTSeq.remove(tSeq); LOGF_DEBUG("~Task() tSeq=%1% :%2%" % tSeq % allTSeq); } /// Flag the Task as cancelled, try to stop the SQL query, and try to remove it from the schedule. void Task::cancel() { if (_cancelled.exchange(true)) { // Was already cancelled. return; } auto qr = _taskQueryRunner; // Want a copy in case _taskQueryRunner is reset. if (qr != nullptr) { qr->cancel(); } auto sched = _taskScheduler.lock(); if (sched != nullptr) { sched->taskCancelled(this); } } /// @return true if task has already been cancelled. bool Task::setTaskQueryRunner(TaskQueryRunner::Ptr const& taskQueryRunner) { _taskQueryRunner = taskQueryRunner; return getCancelled(); } void Task::freeTaskQueryRunner(TaskQueryRunner *tqr){ if (_taskQueryRunner.get() == tqr) { _taskQueryRunner.reset(); } else { LOGF_DEBUG("Task::freeTaskQueryRunner pointer didn't match!"); } } std::ostream& operator<<(std::ostream& os, Task const& t) { proto::TaskMsg& m = *t.msg; os << "Task: " << "msg: session=" << m.session() << " chunk=" << m.chunkid() << " db=" << m.db() << " entry time=" << t.timestr << " "; for(int i=0; i < m.fragment_size(); ++i) { dump(os, m.fragment(i)); os << " "; } return os; } std::string IdSet::toString() { std::ostringstream os; os << *this; return os.str(); } std::ostream& operator<<(std::ostream& os, IdSet const& idSet) { os << "count=" << idSet._ids.size() << " "; bool first = true; for(auto j: idSet._ids) { if (!first) { os << ", "; } else { first = false; } os << j; } return os; } }}} // namespace lsst::qserv::wbase
#include "../include/drift_diffusion.h" void Drift_diffusion::set_boundaries_space(void) { scaled_boundaries tmp_boundaries; list<scaled_layer_params>::iterator tmp_layer; /* Device params */ double V_build_scaled = layers_params_scaled.device.V_build_scaled; double V_a_scaled = layers_params_scaled.device.V_a_scaled; double W_a_scaled = layers_params_scaled.device.W_a_scaled; double W_c_scaled = layers_params_scaled.device.W_c_scaled; /* ETL params */ tmp_layer = layers_params_scaled.stack_params.begin(); double Nc_ETL_scaled = tmp_layer->N_c_scaled; double Nv_ETL_scaled = tmp_layer->N_v_scaled; double Ec_ETL_scaled = tmp_layer->E_c_scaled; double Ev_ETL_scaled = tmp_layer->E_v_scaled; /* HTL params */ tmp_layer = prev(layers_params_scaled.stack_params.end()); // End is theoretical object so 'prev' to get last double Nc_HTL_scaled = tmp_layer->N_c_scaled; double Nv_HTL_scaled = tmp_layer->N_v_scaled; double Ec_HTL_scaled = tmp_layer->E_c_scaled; double Ev_HTL_scaled = tmp_layer->E_v_scaled; // Cathode (top) -> x = 0 // Anode (top) -> x = L /* CATHODE/ETL */ // Electric field and potential tmp_boundaries.potential_bottom_scaled = (V_build_scaled - V_a_scaled); tmp_boundaries.electric_field_bottom_scaled = 0; // Electronic concentration tmp_boundaries.concentration_n_bottom_scaled = Nc_ETL_scaled*exp(-(Ec_ETL_scaled - W_a_scaled)); tmp_boundaries.concentration_p_bottom_scaled = Nv_ETL_scaled*exp(-(W_a_scaled - Ev_ETL_scaled)); tmp_boundaries.concentration_s_bottom_scaled = 0; // Electronic current tmp_boundaries.current_density_p_bottom_scaled = 0; /* ANODE/HTL */ // Electric field and potential tmp_boundaries.potential_top_scaled = 0; tmp_boundaries.electric_field_top_scaled = 0; // Electronic concentration tmp_boundaries.concentration_n_top_scaled = Nc_HTL_scaled*exp(-(Ec_HTL_scaled - W_c_scaled)); tmp_boundaries.concentration_p_top_scaled = Nv_HTL_scaled*exp(-(W_c_scaled - Ev_HTL_scaled)); tmp_boundaries.concentration_s_top_scaled = 0; // Electronic current tmp_boundaries.current_density_n_top_scaled = 0; boundaries_scaled = tmp_boundaries; } void Drift_diffusion::set_boundaries_time(void) { list<scaled_layer_params>::iterator tmp_layer=layers_params_scaled.stack_params.begin(); result_it_scaled.t_scaled = 0; result_it1_scaled.t_scaled = 0; /* Boundary values for t0 */ result_it_scaled.V_scaled.resize(grid_scaled.N_points_scaled); result_it_scaled.V_n_scaled.resize(grid_scaled.N_points_scaled); result_it_scaled.V_p_scaled.resize(grid_scaled.N_points_scaled); result_it_scaled.E_scaled.resize(grid_scaled.N_points_scaled); result_it_scaled.n_scaled.resize(grid_scaled.N_points_scaled); result_it_scaled.p_scaled.resize(grid_scaled.N_points_scaled); result_it_scaled.s_scaled.resize(grid_scaled.N_points_scaled); result_it_scaled.E_c_scaled.resize(grid_scaled.N_points_scaled); result_it_scaled.E_v_scaled.resize(grid_scaled.N_points_scaled); result_it_scaled.E_fn_scaled.resize(grid_scaled.N_points_scaled); result_it_scaled.E_fp_scaled.resize(grid_scaled.N_points_scaled); for (size_t i = 0; i < grid_scaled.N_points_scaled; i++) { if (grid_scaled.li_scaled[i] != tmp_layer->ID) ++tmp_layer; // For absorber parameters } }
#ifndef TREEVIEW_H #define TREEVIEW_H #include <QMainWindow> #include <QString> #include <QTreeView> #include <QTreeWidget> #include <QTreeWidgetItem> #include <QMimeData> #include <QDrag> #include <QDragEnterEvent> #include <QDragMoveEvent> // se usan estos? #include <QDialog> #include <QMutex> #include <QThread> namespace Ui { class TreeView; } class TreeView : public QTreeView { Q_OBJECT public: TreeView(QObject* parent = NULL); protected: void keyPressEvent(QKeyEvent *event); void startDrag(Qt::DropActions /*supportedActions*/); void dragEnterEvent(QDragEnterEvent *event); void dragMoveEvent(QDragMoveEvent *event); }; #endif // TREEVIEW_H
#include <iostream> using namespace std; template<class T> struct MyIter { typedef T value_type; T *ptr; MyIter(T * p=0):ptr(p){} T& operator* (){return *ptr;} }; template <class I> typename I::value_type func(I ite) {return *ite;} int main() { MyIter<int> ite(new int(8)); cout<<func(ite)<<endl; }
/***************************************************************************************************************** * File Name : quicksort.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\tutorials\nptel\DSAndAlgo\lecture10\quicksort.h * Created on : Dec 31, 2013 :: 12:49:24 PM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/ds/linkedlist.h> #include <programming/utils/treeutils.h> #include <programming/utils/llutils.h> /************************************************ User defined constants *******************************************/ #define null NULL /************************************************* Main code ******************************************************/ #ifndef QUICKSORT_H_ #define QUICKSORT_H_ unsigned int divideQuickSortStep(vector<int> userInput,unsigned int startIndex,unsigned int endIndex){ if(startIndex > endIndex){ return INT_MAX; } int key = userInput[endIndex],tempForSwap; while(startIndex < endIndex){ while(userInput[startIndex] >= key){ startIndex++; } while(userInput[endIndex] <= key && startIndex < endIndex){ // actually there is no need to check startIndex < endIndex condition endIndex--; } if(startIndex < endIndex){ tempForSwap = userInput[startIndex]; userInput[startIndex] = userInput[endIndex]; userInput[endIndex] = tempForSwap; } } return endIndex; } void quickSort(vector<int> userInput,unsigned int startIndex,unsigned int endIndex){ if(startIndex > endIndex){ return; } int dividingIndex = divideQuickSortStep(userInput,startIndex,endIndex); quickSort(userInput,startIndex,dividingIndex); quickSort(userInput,dividingIndex+1,endIndex); } #endif /* QUICKSORT_H_ */ /************************************************* End code *******************************************************/
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <vector> #include <math.h> using namespace std; struct toado{ int h,c; }; toado doMove(toado oldLoc,int h){ toado newLoc; newLoc.h = oldLoc.h + huong[h].h; // cap nhat toa do hang moi theo huong h newLoc.c = oldLoc.c + huong[h].c; // cap nhat toa do cot moi theo huong h return newLoc; } toado huong[5] = {-1,0 // N tren ,0,1 // E phai ,1,0 // S duoi ,0,-1}; // W trai void input() { for int i = 0; i < nhang; i++) scanf("%s", &s[i]); } int getIndexFromChar(char c){ if ( c == 'N' ) return 0; if ( c == 'E' ) return 1; if ( c == 'S' ) return 2; if (c == 'W') return 3; } void solve() { toado current; current.h = xph - 1; current.c = xpc -1; flag[current.h][current.c] = 1; } void reset() { int j, j; for (int i = 0; i < 111; i++) for (int j = 0; j < 111; j++) flag[i][i] = 0; } int main() { int ntest(); freopen("10116.inp"); while(scanf("%d %d %d", &nhang, &ncot, &cotxp) > 0) { if (nhang == 0; ncot == 0; cotxp ==0) { break; } input(); } return 0; }
#include <iostream> #include <vector> using namespace std; vector< vector<int> > aumentar( vector< vector<int> > ) ; vector<int> almacenar( vector<int> ) ; void mostrarMatriz( vector< vector<int> > ) ; int main() { vector< vector<int> > matriz( 3 , vector<int>(3) ) ; // matriz original vector< vector<int> > matrizAumentada( 6 , vector<int>(6) ) ; matriz = { {1,0,1},{0,1,0},{0,1,0} } ; cout << "Matriz original" << endl ; mostrarMatriz( matriz ) ; matrizAumentada = aumentar( matriz ) ; cout << "Matriz aumentada" << endl ; mostrarMatriz( matrizAumentada ) ; return 0 ; } // fin main vector< vector<int> > aumentar( vector< vector<int> > original ) { vector< vector<int> > matriz( 6 , vector<int>(6) ) ; int fila = 0 ; for( int i = 0 ; i < original.size() ; i++ ) { for( int j = 0 ; j < 2 ; j++ ) { matriz[fila] = almacenar( original[i] ) ; fila++ ; } } return matriz ; } // fin aumentar vector<int> almacenar( vector<int> original ) { vector<int> lista ; for( int i = 0 ; i < original.size() ; i++ ) { for( int j = 0 ; j < 2 ; j++ ) { lista.push_back( original.at(i) ) ; } } return lista ; } // fin almacenar void mostrarMatriz( vector< vector<int> > matriz ) { for( int i = 0 ; i < matriz.size() ; i++ ) { for( int j = 0 ; j < matriz.size() ; j++ ) { j == matriz.size() - 1 ? cout << matriz[i][j] << endl : cout << matriz[i][j] << " " ; } } } // fin mostrar
/* * MessageManager.cpp * * Created on: Jun 11, 2017 * Author: root */ #include "MessageManager.h" #include "Context.h" #include "../util.h" #include "Session.h" #include "Service_Handler.h" #include "../Log/Logger.h" #include <assert.h> #include "EpollMain.h" #include "../Encrypt/md5.h" namespace CommBaseOut { Message::Message():m_remoteID(-1),m_remoteType(0), m_localID(0),m_localType(0),m_timeout(0),m_reqID(0),m_channelID(-1), m_messageID(0),m_messageType(0),m_length(0),m_errno(0),m_security(false),m_sendTime(0),m_loopIndex(-1),m_group(-1),m_groupKey(-1) { // m_content = NEW_BASE(char, MAX_RECV_MSG_CONTENT_SIZE);// char[MAX_RECV_MSG_SIZE]; // m_content = (char*)NEW_BASE(char, MAX_RECV_MSG_CONTENT_SIZE);// char[MAX_RECV_MSG_SIZE]; m_content = (char *)malloc(MAX_RECV_MSG_CONTENT_SIZE * sizeof(char)); m_addr = NEW Inet_Addr; } Message::Message(int id, unsigned int type):m_remoteID(id),m_remoteType(type), m_localID(0),m_localType(0),m_timeout(0),m_reqID(0),m_channelID(-1), m_messageID(0),m_messageType(0),m_length(0),m_errno(0),m_security(false),m_sendTime(0),m_loopIndex(-1),m_group(-1),m_groupKey(-1) { // m_content = NEW_BASE(char, MAX_RECV_MSG_CONTENT_SIZE); m_content = (char *)malloc(MAX_RECV_MSG_CONTENT_SIZE * sizeof(char)); m_addr = NEW Inet_Addr; } Message::Message(int id, unsigned int type, int channel):m_remoteID(id),m_remoteType(type), m_localID(0),m_localType(0),m_timeout(0),m_reqID(0),m_channelID(channel), m_messageID(0),m_messageType(0),m_length(0),m_errno(0),m_security(false),m_sendTime(0),m_loopIndex(-1),m_group(-1),m_groupKey(-1) { // m_content = NEW_BASE(char, MAX_RECV_MSG_CONTENT_SIZE); m_content = (char *)malloc(MAX_RECV_MSG_CONTENT_SIZE * sizeof(char)); m_addr = NEW Inet_Addr; } Message::Message(int channel):m_remoteID(-1),m_remoteType(0), m_localID(0),m_localType(0),m_timeout(0),m_reqID(0),m_channelID(channel), m_messageID(0),m_messageType(0),m_length(0),m_errno(0),m_security(false),m_sendTime(0),m_loopIndex(-1),m_group(-1),m_groupKey(-1) { // m_content = NEW_BASE(char, MAX_RECV_MSG_CONTENT_SIZE); m_content = (char *)malloc(MAX_RECV_MSG_CONTENT_SIZE * sizeof(char)); m_addr = NEW Inet_Addr; } Message::Message(int id, unsigned int type, int group, int64 key):m_remoteID(id),m_remoteType(type), m_localID(0),m_localType(0),m_timeout(0),m_reqID(0),m_channelID(-1), m_messageID(0),m_messageType(0),m_length(0),m_errno(0),m_security(false),m_sendTime(0),m_loopIndex(-1),m_group(group),m_groupKey(key) { // m_content = NEW_BASE(char, MAX_RECV_MSG_CONTENT_SIZE); m_content = (char *)malloc(MAX_RECV_MSG_CONTENT_SIZE * sizeof(char)); m_addr = NEW Inet_Addr; } Message::Message(Safe_Smart_Ptr<Message> &message):m_remoteID(message->GetRemoteID()),m_remoteType(message->GetRemoteType()), m_localID(message->GetLocalID()),m_localType(message->GetLocalType()),m_timeout(0),m_reqID(message->GetReqID()),m_channelID(message->GetChannelID()), m_messageID(0),m_messageType(0),m_length(0),m_errno(0),m_security(false),m_sendTime(0),m_loopIndex(message->GetLoopIndex()),m_group(message->GetGroup()),m_groupKey(message->GetGroupKey()) { // m_content = NEW_BASE(char, MAX_RECV_MSG_CONTENT_SIZE); m_content = (char *)malloc(MAX_RECV_MSG_CONTENT_SIZE * sizeof(char)); m_addr = NEW Inet_Addr; } Message::~Message() { if(m_content) { // DELETE_BASE(m_content, eMemoryArray); free(m_content); m_content = 0; } } void Message::SetHead(packetHeader &head) { m_length = head.length; m_messageID = head.messageID; m_messageType = head.messageType; m_localID = head.remoteID; m_localType = head.remoteType; m_remoteType = head.localType; m_reqID = head.reqID; m_security = head.security; m_sendTime = head.sendTime; } void Message::GetHead(packetHeader * head) { head->length = m_length; head->messageID = m_messageID; head->messageType = m_messageType; head->remoteID = m_remoteID; head->remoteType = m_remoteType; head->localType = m_localType; head->reqID = m_reqID; head->security = m_security; head->sendTime = m_sendTime; head->toSmallEndian(); } void Message::SetContent(const char *content, int len) { //16为md5串 if((len + HEADER_LENGTH + 16) > MAX_MSG_PACKET_SIZE) { LOG_BASE(FILEINFO, "Message Set Content to Big[%d]", len); return ; } if((len + 16) > MAX_RECV_MSG_CONTENT_SIZE) { m_content = (char *)realloc(m_content, len + 16); } CUtil::SafeMemmove(m_content, len, content, len); m_length = len; } char *Message::GetContent() { return m_content; } void Message::EncryptMessage() { if(m_security) { if(m_length + 16 > MAX_MSG_PACKET_SIZE) { LOG_BASE(FILEINFO, "content encrypted beyond max len"); return; } MD5 md5(m_content, m_length); CUtil::SafeMemmove(m_content + m_length, MAX_MSG_PACKET_SIZE - m_length, md5.Digest(), 16); m_length += 16; } } bool Message::UnEncryptMessage() { if(m_security) { MD5 md5(m_content, m_length - 16); char ttt[32] = {0}; CUtil::SafeMemmove(ttt,32,m_content + 3, 16); if(strncmp((const char *)md5.Digest(), m_content + m_length - 16, 16) != 0) { return false; } m_length -= 16; } return true; } }
#include <iostream> #include <algorithm> #include <vector> using namespace std; int n; string temp, max1 = "", max2 = "", original, possible1, possible2; vector<pair<string, char>> allStr; bool mark(string x, char order) { for (int i = 0; i < 2 * n - 2; i++) { if (allStr[i].first == x && allStr[i].second == 'X') { allStr[i].second = order; return true; } } // cout << "not found :" << x << endl; //restart the process //initialize for (int i = 0; i < 2 * n - 2; i++) { allStr[i].second = 'X'; } return false; } int main() { cin >> n; for (int i = 0; i < 2 * n - 2; i++) { cin >> temp; allStr.push_back(make_pair(temp, 'X')); if (temp.length() > max1.length()) max1 = temp; else if (temp.length() == max1.length()) max2 = temp; } int len = max1.length(); //fuck it check both possible, n is small possible1 = max2 + max1[len - 1]; possible2 = max1 + max2[len - 1]; // cout << max1.substr(0, len - 1) << " subs " << max2.substr(1, len - 1) << endl; // cout << original << endl; bool res; original = possible1; for (int i = 0; i < n - 1; i++) { //i is count. r is for reverse order res = mark(original.substr(0, i + 1), 'P'); if (!res) { i = -1; original = possible2; continue; } res = mark(original.substr(n - i - 1, i + 1), 'S'); if (!res) { i = -1; original = possible2; } } for (int i = 0; i < 2 * n - 2; i++) cout << allStr[i].second; cout << endl; }
#ifndef _DIAGRAM_D_H #define _DIAGRAM_D_H #include "diagrams_a.hpp" #include "diagrams_b.hpp" #include "diagrams_c.hpp" class C; class D : virtual protected A, private B { public: C m_c; }; #endif
#pragma once #include <string> #include <thread> class c_task { public: c_task(std::string id); private: std::string generate_prototype(int length); std::string calc_hash(std::string &prot); int get_random(int minimum, int maximum); char get_rand_char(); void check_hash(std::string &hash); private: std::string m_id; };
#include "SettingManagerUI.hpp" #include <QHBoxLayout> #include <QDebug> #include "SettingProfileEditorUI.hpp" #include "SettingDeviceEditor.hpp" #include <QTimer> SettingManagerUI::SettingManagerUI(int defaultItem, QWidget *parent) : QUtilsFramelessDialog(parent) { initLayout(); initConnection(); pListWidget->setCurrentRow(defaultItem); } void SettingManagerUI::initLayout() { pListWidget = new ZListWidget; { pProfile = new QListWidgetItem("账户设置"); pDevice = new QListWidgetItem("设备管理"); pListWidget->addItem(pProfile); pListWidget->addItem(pDevice); } pStackWidget = new QStackedWidget; { pProfileEditer = new SettingProfileEditorUI; pDeviceEditor = new SettingDeviceEditor; pStackWidget->addWidget(pProfileEditer); pStackWidget->addWidget(pDeviceEditor); pStackWidget->layout()->setMargin(0); } QHBoxLayout *hboxMain = new QHBoxLayout; { hboxMain->addWidget(pListWidget, 1); hboxMain->addWidget(pStackWidget,3); hboxMain->setMargin(0); hboxMain->setSpacing(0); this->setBodyLayout(hboxMain); resize(600, 450); } setTitleText("设置"); } void SettingManagerUI::initConnection() { connect(pListWidget, &ZListWidget::currentRowChanged, pStackWidget, &QStackedWidget::setCurrentIndex); }
#include <iostream> #include <unordered_set> #include <algorithm> #include <cctype> using namespace std; bool isPalindromePermu(string s){ unordered_set<char> charSet; transform(s.begin(), s.end(), s.begin(),[](unsigned char c) -> unsigned char {return tolower(c);}); for(char c: s){ if(c != ' '){ if(charSet.find(c) == charSet.end()){ charSet.insert(c); }else{ charSet.erase(c); } } } if(charSet.size() > 1){ return false; } return true; } void test(bool output, bool expected, int testIndex){ if(output == expected){ cout << "test " << testIndex << " successed." << endl; }else{ cout << "test " << testIndex << " failed." << endl; } } int main(void){ test(isPalindromePermu("Tact Coa"), true, 0); test(isPalindromePermu("cat"), false, 1); test(isPalindromePermu(" "), true, 2); return 0; }
/* * Copyright (c) 2011 Pierre-Etienne Bougué <pe.bougue(a)gmail.com> * Copyright (c) 2011 Florian Colin <florian.colin28(a)gmail.com> * Copyright (c) 2011 Kamal Fadlaoui <kamal.fadlaoui(a)gmail.com> * Copyright (c) 2011 Quentin Lequy <quentin.lequy(a)gmail.com> * Copyright (c) 2011 Guillaume Pinot <guillaume.pinot(a)tremplin-utc.net> * Copyright (c) 2011 Cédric Royer <cedroyer(a)gmail.com> * Copyright (c) 2011 Guillaume Turri <guillaume.turri(a)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. * */ #ifndef TREEALG_HH #define TREEALG_HH #include "DecisionALG.hh" #include <vector> #include <list> #include <string> #include <sstream> #include <stdint.h> /** Structure contenant l'information utile du noeud d'un point de vue recherche de solution. Quelque soit la structure de l'arbre, on en aura toujours besoin. */ struct NodeContentALG { uint32_t nbSimu_m; float sumEval_m; DecisionALG * pDecision_m; NodeContentALG() : nbSimu_m(0), sumEval_m(0.0), pDecision_m(0) {} NodeContentALG(DecisionALG * pDecision_p) : nbSimu_m(0), sumEval_m(0.0), pDecision_m(pDecision_p) {} ~NodeContentALG() { // faudrait deleter là, mais si on delete, faut faire une copie pour le // move du vector... //delete pDecision_m; } // du coup on fait un clear manuel lors de la destruction d'un Node void clear() {delete pDecision_m; pDecision_m = 0; nbSimu_m = 0; sumEval_m = 0;} std::string toString() const { std::stringstream ss_l; ss_l << sumEval_m / nbSimu_m << "," << nbSimu_m; return ss_l.str(); } }; /** Classe servant d'interface pour l'arbre au sein de la MCTS. * Cette classe necessite en parametre template une classe implementant * un arbre. Il est conseille que cet arbre depende lui meme (template ou pas) * de la structure NodeContentALG ci dessus. * On utilise un iterateur pour gerer le deplacement dans l'arbre. */ template <typename TreeImpl> class TreeALG { public: TreeALG(); ~TreeALG(); typedef typename TreeImpl::iterator iterator; typedef std::vector<iterator> ChildrenPool; // renvoie un iterateur sur la racine iterator root(); // renvoie vrai si un iterateur a des fils bool hasChildren(iterator const &); // renvoie la liste des fils d'un iterateur ChildrenPool children(iterator const &); // detruit le noeud de l'iterateur qui devient donc invalide void deleteNode(iterator &); // renvoie un iterateur sur le noeud courant? iterator addChildren(iterator &, NodeContentALG &); std::string toString(int = -1); std::string toString(int, iterator const &); private: TreeImpl impl_m; }; #endif
// // Created by OLD MAN on 2020/1/7. // //小蒜给了若干个四位数,请求出其中满足以下条件的数的个数: // //个位数上的数字减去千位数上的数字,再减去百位数上的数字,再减去十位数上的数字的结果大于零。 // //输入格式 // 输入为两行,第一行为四位数的个数 n,第二行为 n 个的四位数,数与数之间以一个空格分开。(n≤100) // //输出格式 // 输出为一行,包含一个整数,表示满足条件的四位数的个数。 #include <iostream> using namespace std; int main(){ int n,m=0; cin>>n; for(int i = 0; i < n; i++){ int p ; cin>>p; //a:个位,b:十位,c:百位,d:千位 int a = p % 10, b = p / 10 % 10, c = p / 100 % 10, d = p / 1000 % 10; if (a - b - c - d > 0) m++; } cout<<m; }
#include <stdio.h> int main(){ int n; printf("Nhap so n: "); scanf("%d",&n); printf("Tat ca cac so chan tu 1 den %d la: ",n); for(int i=1;i<=n;i++){ if(i%2==0){ printf("%d",i); } } }
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #pragma once #include "Core/Path.hpp" #include "Core/Noncopyable.hpp" #include <memory> #include <cstdint> namespace TexturePacker { class Image { public: Image() = default; Image(Image&& rhs); Image(const Image& rhs); Image(const Push::Path& file); Image(uint32_t width, uint32_t height, uint32_t channels, uint8_t* data); uint32_t GetWidth() const; uint32_t GetHeight() const; uint32_t GetChannels() const; const uint8_t* GetData() const; Image GetOpaqueArea() const; void LoadPNG(const Push::Path& file); void SavePNG(const Push::Path& file); void SaveMeta(const Push::Path& file); private: uint32_t m_left = 0u; uint32_t m_right = 0u; uint32_t m_top = 0u; uint32_t m_bottom = 0u; uint32_t m_width = 0u; uint32_t m_height = 0u; uint32_t m_channels = 0u; std::unique_ptr<uint8_t[]> m_data; }; }
#include<iostream> using namespace std; int main() { long n,t; cin>>n>>t; long a[100000]; for(long i=0;i<n;i++) { cin>>a[i]; } while(t--) { long s1, s2; cin>>s1>>s2; long min=a[s1]; for(long i=s1;i<=s2;i++) { if(min>a[i]) { min =a[i]; } } cout<<min<<"\n"; } }
#include<stdio.h> #include<math.h> int main(int argc, char const *argv[]) { int t,x,y,len,count; scanf("%d",&t); for (int k = 1; k<=t; k++) { count = 0; scanf("%d%d",&x,&y); for (int i = x; i <= y; i++) { for (int j = 2; j <= sqrt(x); j++) { if (x%j==0) { break; } else count++; } } printf("%d\n",count); } return 0; }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <iostream> #include "cuehttp.hpp" using namespace cue::http; int main(int argc, char** argv) { router route; route.get("/test_session", [](context& ctx) { int view{1}; const auto view_str = ctx.session().get("view"); if (view_str.empty()) { ctx.session().set("view", std::to_string(view)); } else { view = std::atoi(view_str.data()); ctx.session().set("view", std::to_string(view + 1)); } ctx.type("text/html"); ctx.body(R"(<h1>Hello, )" + std::to_string(view) + R"( cuehttp!</h1>)"); ctx.status(200); }); session::options session_opt; session_opt.key = "cuehttp"; // session_opt.external_key.get = [](context& ctx) { // std::cout << "external_key.get" << std::endl; // return ctx.get("User-Token"); // }; // session_opt.external_key.set = [](context& ctx, std::string_view value) { // std::cout << "external_key.set" << std::endl; // return ctx.set("User-Token", value); // }; // session_opt.external_key.destroy = [](context& ctx, std::string_view value) { // std::cout << "external_key.destroy" << std::endl; // return ctx.remove("User-Token"); // }; cuehttp app; app.use(use_session(std::move(session_opt))); app.use(route.routes()); app.listen(10001).run(); return 0; }
#include <stdlib.h> #include <math.h> class GraphList{ public: int *data; unsigned int sampling=0; GraphList(unsigned int sampling); void push(int); bool check_peek(); bool what_peek(); }; GraphList::GraphList(unsigned int _sampling){ unsigned int smp=0; if(_sampling > 3){ if(_sampling%2==0){ smp = _sampling+1; }else{ smp = _sampling; } data = (int*)malloc(sizeof(int)*smp); for(int i=0;i<smp;i++){ data[i]=0; } sampling = smp; } } void GraphList::push(int _data){ for(int i=1;i<sampling;i++){ data[i] = data[i-1]; } data[0] = _data; } bool GraphList::check_peek(){ int mid_data_index = (sampling+1)/2; short int left_hand_slope = 0; short int right_hand_slope = 0; for(int i=0;i<mid_data_index;i++){ // half loop if(abs(data[mid_data_index-i]) > abs(data[mid_data_index-i-1])){ //center - left = +slope left_hand_slope += 1; }else{ left_hand_slope = 0; } if(abs(data[mid_data_index+i]) > abs(data[mid_data_index+i+1])){ //center - right = -slope right_hand_slope += 1; }else{ right_hand_slope = 0; } } if(left_hand_slope==right_hand_slope){ //has peek return true; }return false; } bool GraphList::what_peek(){ int mid_data_index = (sampling+1)/2; if(data[mid_data_index] - data[0] > 0){ //positive peek return true; }return false; // negative peek } //--- Sensor LED --- int sensorValue=0; #define sensorPin A0 //--- Sensor LED END --- //--- Sound Statistic Begin // Threshole int microphone_min_threshole = 20; int microphone_max_threshole = 620; int microphone_range = microphone_max_threshole - microphone_min_threshole; int sound_clap_threshole_high = 580; int sound_clap_threshole_low = 50; // Sound sensor Variable int analog_read_once = 0; int sound_realtime_sampling = 10; int sound_realtime_mean = 0; int sound_realtime_sum = 0; int sound_long_sum = 0; int sound_long_mean = 0; int sound_long_mean_prev = 0; int sound_max_peek = 0; int sound_max_peek_sum = 0; byte sound_max_peek_time_counter = 0; byte sound_clap_time_counter = 0; //peek analysis [in sample peek not global] int sound_peek_prev = 0; int sound_raw_peek_counter; int fade_divider_value=1; int sound_global_sum = 0; int sound_global_mean = 0; int sound_global_mean_prev =0; /*---- Timer ----*/ int sound_timer_counter[] = {0,0,0}; // t[1] is clap // t[2] is int sound_timer_realtime_prev[] = {0,0}; // t[1] is realtime average // t[2] is realtime long average // Graph statistic int sound_graph_min_avr = 0; int sound_graph_max_avr = 0; int sound_graph_long_mean = 0; int sound_graph_long_sum = 0; int sound_graph_long_count = 0; //--- Sound Statistic End /*------ Music NN model ------*/ // Scoring Music float music_type_score[] = {0,0,0,0}; /* [0] คือ เพลงร้องที่มี พิน กลอง เป็นจังหวะหลัก ไม่มีเสียงอื่น ex [A song for the season] * [1] คือ * * */ float music_tempo_score[] = {0,0,0,0}; /* [0] high peek per realtime_sampling * [1] high percentage (vol > 50) per long_mean */ /*------ Algorithm Variable --------*/ unsigned long now_time_milli=0; unsigned long prev_milli = 0; bool is_clap = false; int is_clap_counter=0; float sound_vol_percentage=0; bool is_slilence =false; GraphList graph = GraphList(5); void setup(){ Serial.begin(115200); pinMode(sensorPin,INPUT); pinMode(D0,OUTPUT); pinMode(D1,OUTPUT); pinMode(D2,OUTPUT); pinMode(D3,OUTPUT); pinMode(D4,OUTPUT); pinMode(D5,OUTPUT); pinMode(D7,OUTPUT); pinMode(D6,OUTPUT); } void loop() { now_time_milli=millis(); // Global Delay if(now_time_milli - prev_milli >= 10 ){ analog_read_once = analogRead (sensorPin); graph.push(analog_read_once); //Transform real Sensor amplitude to Percentage Amplitude (Volume) sound_vol_percentage = ((float)analog_read_once/(float)microphone_max_threshole)*100.0; if(sound_vol_percentage >= 50){ // เพลงมันส์ๆ ที่มักจะมีกราฟอยู่ด้านบน digitalWrite(D3,HIGH); }else{ digitalWrite(D3,LOW); } //ระบบวัดเสียงเพลงจากการตรวจสอบ peek if(graph.check_peek()){ float temp_peek_range_precentage = 0.08633; if(analog_read_once - sound_realtime_mean > microphone_range*temp_peek_range_precentage){ digitalWrite(D7,HIGH); }else if(analog_read_once - sound_realtime_mean < -(microphone_range*temp_peek_range_precentage)){ digitalWrite(D6,HIGH); } if(abs(analog_read_once - sound_peek_prev) > 50 && sound_peek_prev != 0){ digitalWrite(D5,HIGH); }else{ digitalWrite(D5,LOW); } sound_peek_prev = analog_read_once; }else{ digitalWrite(D7,LOW); digitalWrite(D6,LOW); } /*--- วัดเสียงเพลง แบบ percentage [by kanoon alogorithm] -----*/ fade_divider_value = (40.00-sensorValue*39/520); { sensorValue = analog_read_once; if(sensorValue > 520){ sensorValue = 520; } } // ท่อนฮุก ผ่านระบบ percentage if(fade_divider_value < 15){ digitalWrite(D2,HIGH); }else{ digitalWrite(D2,LOW); } /* --------- End kanoon algorithm -----------------*/ /*---system statistic---*/ sound_realtime_sum += analog_read_once; if(sound_max_peek < analog_read_once){ sound_max_peek = analog_read_once; sound_max_peek_time_counter = 0; sound_max_peek_sum += sound_max_peek; }else{ sound_max_peek_time_counter += 1; if(sound_max_peek_time_counter == (2*sound_realtime_sampling)){ //sound_max_peek = sound_max_peek_sum/sound_max_peek_time_counter; sound_max_peek = sound_realtime_mean; sound_max_peek_time_counter = 0; } } //Sound mod begin sound_timer_realtime_prev[0]+=1; sound_timer_realtime_prev[1]+=1; if(sound_timer_realtime_prev[0] >= sound_realtime_sampling){ //หา realtime_sampling_average sound_realtime_mean = sound_realtime_sum/sound_realtime_sampling; sound_long_sum += sound_realtime_sum; sound_realtime_sum = 0; sound_timer_realtime_prev[0] = 0; } if(sound_timer_realtime_prev[1] >= (10*sound_realtime_sampling)){ sound_long_mean_prev = sound_long_mean; sound_long_mean = sound_long_sum/(10*sound_realtime_sampling); // reset Long_sum sound_long_sum = 0; sound_timer_realtime_prev[1] = 0; } //Sound Mod End // หาผลรวมของเพลง sound_graph_long_count += 1; sound_graph_long_sum += analog_read_once; sound_graph_long_mean = sound_graph_long_sum/sound_graph_long_count; //Serial.print(sound_graph_long_count); //Serial.print("\t"); //Min Average if(analog_read_once < sound_realtime_mean){ //when sensor less than realtime average if(1){ } } /*------ End statistic system -----*/ //Find Slilence //if(abs(sound_long_mean - sound_realtime_mean) <= 15){ if(abs(sound_long_mean - sound_long_mean_prev) <= 3 && sound_realtime_mean < microphone_min_threshole+5){ // abs(mean-prev_mean) <= ค่าคงที่ จากการทดลองดูการแกว่งของค่า ในขณะเงียบ =[fix_when_change_sensor] // microphone_min_threshole + (low pass filter) สำหรับกัน noise ในขณะเงียบ // this condition worked when the room is really silence is_slilence = true; }else{ is_slilence = false; } //Find Peek clap if(is_slilence){ digitalWrite(D1,HIGH); sound_graph_long_count = 0; sound_graph_long_sum = 0; // Clap check v2 if(analog_read_once > sound_clap_threshole_high && !is_clap){ is_clap = true; sound_timer_counter[0] = 0; }else{ if(is_clap){ /*sound_timer_counter[0] += 1; if((analog_read_once > sound_clap_threshole_high) && sound_timer_counter[0] >= 20){ is_clap = false; }else{ if((sound_global_mean < sound_clap_threshole_low ) && sound_timer_counter[0] >= 30){ digitalWrite(D4,HIGH); } }*/ digitalWrite(D4,HIGH); delay(200); } } }else{ sound_timer_counter[0] += 1; if(sound_timer_counter[0] >= 2*(10*sound_realtime_sampling)+10){ // รอจนกระทั้งเป็น silence แต่ถ้าไม่เป็น ก็ถือว่าเป็นเสียงเพลง is_clap = false; } /*if((analog_read_once > sound_clap_threshole_high) && sound_timer_counter[0] >= 20){ // ตบมืออีกครั้ง แต่ละไว้ก่อน //is_clap = false; }else{ if((sound_global_mean < sound_clap_threshole_low ) && sound_timer_counter[0] >= 30){ digitalWrite(D4,HIGH); } }*/ digitalWrite(D4,LOW); digitalWrite(D1,LOW); } if(graph.check_peek( ) && sound_max_peek > sound_clap_threshole_high){ } Serial.print(fade_divider_value); Serial.print("\t"); Serial.print(sensorValue); Serial.print("\t"); Serial.print(analogRead (sensorPin)); Serial.print("\t"); Serial.print(sound_realtime_mean); Serial.print("\t"); Serial.print(sound_max_peek); Serial.print("\t"); Serial.print(sound_long_mean); Serial.print("\t"); Serial.print(sound_vol_percentage); Serial.print("\t"); //Serial.print(is_clap); //Serial.print("\t"); Serial.print(sound_graph_long_mean); Serial.println(); prev_milli = now_time_milli; } }
/* unfinished, meant to calculate Newton's Laws based on various inputs */ #include <iostream> #include "SecondLaw.h" using namespace std; int main() { cout << "Calculate Newton's Laws" << endl; cout << "Enter '999' for the missing variable to solve for." << endl; double friction; double mass; double acceleration; double forceNet; double weight; double weightParallel; double weightPerpendicular; double angle; double normalForce; char inMenu = 'y'; SecondLaw newLaw; while (inMenu == 'y') { cout << "Enter mass: "; cin >> mass; cout << "Enter fnet: "; cin >> forceNet; cout << "Enter acceleration: "; cin >> acceleration; newLaw.calculateMissing(forceNet, acceleration, mass); cout << "Calculate another? "; cin >> inMenu; } }
/* Copyright (c) 2022 Xavier Leclercq Released under the MIT License See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt */ #include "DirectoryComparisonTestCheckTests.hpp" using namespace Ishiko; DirectoryComparisonTestCheckTests::DirectoryComparisonTestCheckTests(const TestNumber& number, const TestContext& context) : TestSequence(number, "DirectoryComparisonTestCheck tests", context) { append<HeapAllocationErrorsTest>("Constructor test 1", ConstructorTest1); append<HeapAllocationErrorsTest>("run test 1", RunTest1); append<HeapAllocationErrorsTest>("run test 2", RunTest2); append<HeapAllocationErrorsTest>("run test 3", RunTest3); append<HeapAllocationErrorsTest>("run test 4", RunTest4); append<HeapAllocationErrorsTest>("run test 5", RunTest5); append<HeapAllocationErrorsTest>("run test 6", RunTest6); append<HeapAllocationErrorsTest>("run test 7", RunTest7); append<HeapAllocationErrorsTest>("run test 8", RunTest8); } void DirectoryComparisonTestCheckTests::ConstructorTest1(Test& test) { DirectoryComparisonTestCheck directoryComparisonCheck; ISHIKO_TEST_PASS(); } void DirectoryComparisonTestCheckTests::RunTest1(Test& test) { boost::filesystem::path outputDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir1"); boost::filesystem::path referenceDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir2"); DirectoryComparisonTestCheck directoryComparisonCheck(outputDirectoryPath, referenceDirectoryPath); Test checkTest(TestNumber(1), "DirectoryComparisonTestCheckTests_RunTest1"); directoryComparisonCheck.run(checkTest, __FILE__, __LINE__); ISHIKO_TEST_FAIL_IF_NEQ(directoryComparisonCheck.result(), TestCheck::Result::failed); ISHIKO_TEST_FAIL_IF_NEQ(checkTest.result(), TestResult::failed); ISHIKO_TEST_PASS(); } void DirectoryComparisonTestCheckTests::RunTest2(Test& test) { boost::filesystem::path outputDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir1"); boost::filesystem::path referenceDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir3"); DirectoryComparisonTestCheck directoryComparisonCheck(outputDirectoryPath, referenceDirectoryPath); Test checkTest(TestNumber(1), "DirectoryComparisonTestCheckTests_RunTest2"); directoryComparisonCheck.run(checkTest, __FILE__, __LINE__); checkTest.pass(); ISHIKO_TEST_FAIL_IF_NEQ(directoryComparisonCheck.result(), TestCheck::Result::passed); ISHIKO_TEST_FAIL_IF_NEQ(checkTest.result(), TestResult::passed); ISHIKO_TEST_PASS(); } void DirectoryComparisonTestCheckTests::RunTest3(Test& test) { boost::filesystem::path outputDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir1"); boost::filesystem::path referenceDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir4"); DirectoryComparisonTestCheck directoryComparisonCheck(outputDirectoryPath, referenceDirectoryPath); Test checkTest(TestNumber(1), "DirectoryComparisonTestCheckTests_RunTest3"); directoryComparisonCheck.run(checkTest, __FILE__, __LINE__); checkTest.pass(); ISHIKO_TEST_FAIL_IF_NEQ(directoryComparisonCheck.result(), TestCheck::Result::failed); ISHIKO_TEST_FAIL_IF_NEQ(checkTest.result(), TestResult::failed); ISHIKO_TEST_PASS(); } void DirectoryComparisonTestCheckTests::RunTest4(Test& test) { boost::filesystem::path outputDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir4"); boost::filesystem::path referenceDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir1"); DirectoryComparisonTestCheck directoryComparisonCheck(outputDirectoryPath, referenceDirectoryPath); Test checkTest(TestNumber(1), "DirectoryComparisonTestCheckTests_RunTest4"); directoryComparisonCheck.run(checkTest, __FILE__, __LINE__); checkTest.pass(); ISHIKO_TEST_FAIL_IF_NEQ(directoryComparisonCheck.result(), TestCheck::Result::failed); ISHIKO_TEST_FAIL_IF_NEQ(checkTest.result(), TestResult::failed); ISHIKO_TEST_PASS(); } void DirectoryComparisonTestCheckTests::RunTest5(Test& test) { boost::filesystem::path outputDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir5"); boost::filesystem::path referenceDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir6"); DirectoryComparisonTestCheck directoryComparisonCheck(outputDirectoryPath, referenceDirectoryPath); Test checkTest(TestNumber(1), "DirectoryComparisonTestCheckTests_RunTest5"); directoryComparisonCheck.run(checkTest, __FILE__, __LINE__); checkTest.pass(); ISHIKO_TEST_FAIL_IF_NEQ(directoryComparisonCheck.result(), TestCheck::Result::failed); ISHIKO_TEST_FAIL_IF_NEQ(checkTest.result(), TestResult::failed); ISHIKO_TEST_PASS(); } void DirectoryComparisonTestCheckTests::RunTest6(Test& test) { boost::filesystem::path outputDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir5"); boost::filesystem::path referenceDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir7"); DirectoryComparisonTestCheck directoryComparisonCheck(outputDirectoryPath, referenceDirectoryPath); Test checkTest(TestNumber(1), "DirectoryComparisonTestCheckTests_RunTest6"); directoryComparisonCheck.run(checkTest, __FILE__, __LINE__); checkTest.pass(); ISHIKO_TEST_FAIL_IF_NEQ(directoryComparisonCheck.result(), TestCheck::Result::passed); ISHIKO_TEST_FAIL_IF_NEQ(checkTest.result(), TestResult::passed); ISHIKO_TEST_PASS(); } void DirectoryComparisonTestCheckTests::RunTest7(Test& test) { boost::filesystem::path outputDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir1"); boost::filesystem::path referenceDirectoryPath = test.context().getDataPath("DoesNotExist"); DirectoryComparisonTestCheck directoryComparisonCheck(outputDirectoryPath, referenceDirectoryPath); Test checkTest(TestNumber(1), "DirectoryComparisonTestCheckTests_RunTest7"); directoryComparisonCheck.run(checkTest, __FILE__, __LINE__); ISHIKO_TEST_FAIL_IF_NEQ(directoryComparisonCheck.result(), TestCheck::Result::failed); ISHIKO_TEST_FAIL_IF_NEQ(checkTest.result(), TestResult::failed); ISHIKO_TEST_PASS(); } void DirectoryComparisonTestCheckTests::RunTest8(Test& test) { boost::filesystem::path outputDirectoryPath = test.context().getDataPath("DoesNotExist"); boost::filesystem::path referenceDirectoryPath = test.context().getDataPath("ComparisonTestDirectories/Dir1"); DirectoryComparisonTestCheck directoryComparisonCheck(outputDirectoryPath, referenceDirectoryPath); Test checkTest(TestNumber(1), "DirectoryComparisonTestCheckTests_RunTest8"); directoryComparisonCheck.run(checkTest, __FILE__, __LINE__); ISHIKO_TEST_FAIL_IF_NEQ(directoryComparisonCheck.result(), TestCheck::Result::failed); ISHIKO_TEST_FAIL_IF_NEQ(checkTest.result(), TestResult::failed); ISHIKO_TEST_PASS(); }
#include<iostream> #include<cmath> using namespace std; int main() { for (unsigned i = 1; i < 10; i++) { cout << pow(i,2) + pow(i - 1,2) << endl; } return 0; }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- // // Copyright (C) 2003 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // Espen Sand // #include "core/pch.h" #include "KioskResetDialog.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/managers/KioskManager.h" #include "modules/locale/locale-enum.h" #include "modules/locale/oplanguagemanager.h" //#include "modules/prefs/prefsmanager/prefsmanager.h" #include "modules/widgets/OpMultiEdit.h" KioskResetDialog::KioskResetDialog() :m_secs_to_shutdown(10), m_timer(0) { } KioskResetDialog::~KioskResetDialog() { OP_DELETE(m_timer); } void KioskResetDialog::OnInit() { if( !m_timer ) { m_timer = OP_NEW(OpTimer, ()); } m_timer->SetTimerListener( this ); m_timer->Start(1000); UpdateMessage(); } void KioskResetDialog::OnTimeOut(OpTimer* timer) { if (timer != m_timer) { Dialog::OnTimeOut(timer); return; } if( m_secs_to_shutdown <= 1 ) { CloseDialog(FALSE,TRUE,FALSE); if( g_application ) { KioskManager::GetInstance()->OnAutoReset(); } } else { m_secs_to_shutdown --; UpdateMessage(); timer->Start(1000); } } void KioskResetDialog::OnClose(BOOL user_initiated) { Dialog::OnClose(user_initiated); if( g_application ) KioskManager::GetInstance()->OnDialogClosed(); } void KioskResetDialog::UpdateMessage() { OpMultilineEdit* edit = (OpMultilineEdit*) GetWidgetByName("Edit"); if (edit) { edit->SetLabelMode(); OpString msg; if( m_secs_to_shutdown > 1 ) { OpString format; g_languageManager->GetString(Str::S_KIOSK_RESET_SECONDS,format); if( format.CStr() ) { msg.AppendFormat(format.CStr(),m_secs_to_shutdown); } } else { g_languageManager->GetString(Str::S_KIOSK_RESET_SECOND,msg); } edit->SetText(msg.CStr()); } }
#ifndef __OBJCATPATH_H #define __OBJCATPATH_H #include "TModelArray.h" #include "db_rec.h" //------------------------------------------------------------------------- namespace wh{ //------------------------------------------------------------------------- namespace object_catalog { //------------------------------------------------------------------------- namespace model { //------------------------------------------------------------------------- class MPathItem : public TModelData<rec::PathItem> { public: MPathItem(const char option = ModelOption::EnableParentNotify); virtual bool LoadThisDataFromDb(std::shared_ptr<whTable>&, const size_t)override; protected: }; //------------------------------------------------------------------------- class MPath : public TModelArray<MPathItem> { public: MPath(const char option = ModelOption::EnableParentNotify | ModelOption::EnableNotifyFromChild) :TModelArray<MPathItem>(option) {} wxString GetPathStr()const; wxString GetLastItemStr()const; protected: virtual bool GetSelectChildsQuery(wxString& query)const override; }; //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- class MTypeItem; //------------------------------------------------------------------------- class ClsPathItem : public TModelData<rec::Cls> { public: ClsPathItem(const char option = ModelOption::EnableParentNotify); virtual bool LoadThisDataFromDb(std::shared_ptr<whTable>&, const size_t)override; }; //------------------------------------------------------------------------- class ClsPath : public TModelArray<MPathItem> { public: ClsPath(const char option = ModelOption::EnableParentNotify | ModelOption::EnableNotifyFromChild) :TModelArray<MPathItem>(option) {} wxString AsString()const; void SetCls(std::shared_ptr<MTypeItem> cls); protected: virtual bool GetSelectChildsQuery(wxString& query)const override; std::shared_ptr<MTypeItem> mCls; }; //------------------------------------------------------------------------- class ObjPathItem : public TModelData<rec::PathItem> { public: ObjPathItem(const char option = ModelOption::EnableParentNotify); virtual bool LoadThisDataFromDb(std::shared_ptr<whTable>&, const size_t)override; }; //------------------------------------------------------------------------- class ObjPath : public TModelArray<ObjPathItem> { public: ObjPath(const char option = ModelOption::EnableParentNotify | ModelOption::EnableNotifyFromChild) :TModelArray<ObjPathItem>(option) {} wxString AsString()const; protected: virtual bool GetSelectChildsQuery(wxString& query)const override; }; //------------------------------------------------------------------------- }//namespace model { //------------------------------------------------------------------------- }//object_catalog { //------------------------------------------------------------------------- }//namespace wh{ //------------------------------------------------------------------------- #endif // __****_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #ifdef CSS_ANIMATIONS #include "modules/style/css.h" #include "modules/style/css_property_list.h" #include "modules/style/src/css_lexer.h" #include "modules/style/src/css_grammar.h" #include "modules/style/src/css_buffer.h" #include "modules/style/src/css_keyframes.h" CSS_KeyframeRule::CSS_KeyframeRule(CSS_KeyframesRule* keyframes, List<CSS_KeyframeSelector>& positions, CSS_property_list* prop_list) : m_keyframes(keyframes), m_prop_list(NULL) { Replace(positions, prop_list); } CSS_KeyframeRule::~CSS_KeyframeRule() { if (m_prop_list) m_prop_list->Unref(); m_positions.Clear(); } BOOL CSS_KeyframeRule::operator==(const CSS_KeyframeRule& other) { CSS_KeyframeSelector* selector = NULL; CSS_KeyframeSelector* other_selector = NULL; for (selector = GetFirstSelector(), other_selector = other.GetFirstSelector(); selector && other_selector; selector = selector->Suc(), other_selector = other_selector->Suc()) { if (selector->GetPosition() != other_selector->GetPosition()) return FALSE; } return !selector && !other_selector; } void CSS_KeyframeRule::Replace(List<CSS_KeyframeSelector>& positions, CSS_property_list* props) { m_positions.Clear(); while (!positions.Empty()) { CSS_KeyframeSelector* keyframe_sel = positions.First(); keyframe_sel->Out(); if (keyframe_sel->GetPosition() >= 0.0 && keyframe_sel->GetPosition() <= 1.0) keyframe_sel->Into(&m_positions); else OP_DELETE(keyframe_sel); } if (props) props->Ref(); if (m_prop_list) m_prop_list->Unref(); m_prop_list = props; } /* virtual */ OP_STATUS CSS_KeyframeRule::GetCssText(CSS* stylesheet, TempBuffer* buf, unsigned int indent_level) { GetKeyText(buf); RETURN_IF_ERROR(buf->Append(" { ")); TRAP_AND_RETURN(stat, m_prop_list->AppendPropertiesAsStringL(buf)); return buf->Append(" }"); } /* virtual */ CSS_PARSE_STATUS CSS_KeyframeRule::SetCssText(HLDocProfile* hld_prof, CSS* stylesheet, const uni_char* text, int len) { if (m_keyframes) return stylesheet->ParseAndInsertRule(hld_prof, this, NULL, m_keyframes, TRUE, CSS_TOK_DOM_KEYFRAME_RULE, text, len); else return OpStatus::OK; } OP_STATUS CSS_KeyframeRule::GetKeyText(TempBuffer* buf) const { for (CSS_KeyframeSelector* selector = GetFirstSelector(); selector; selector = selector->Suc()) { RETURN_IF_ERROR(buf->AppendDouble(selector->GetPosition() * 100)); RETURN_IF_ERROR(buf->Append("%")); if (selector->Suc()) RETURN_IF_ERROR(buf->AppendFormat(UNI_L(", "))); } return OpStatus::OK; } OP_STATUS CSS_KeyframeRule::SetKeyText(const uni_char* key_text, unsigned key_text_length) { // Parse something like '45%, 21.2%', a comma-separated list of // percentage values and set them as the list of selectors. AutoDeleteList<CSS_KeyframeSelector> new_positions; CSS_Buffer css_buf; if (css_buf.AllocBufferArrays(1)) { int token; css_buf.AddBuffer(key_text, uni_strlen(key_text)); CSS_Lexer lexer(&css_buf, FALSE); YYSTYPE value; while ((token = lexer.Lex(&value)) == CSS_TOK_SPACE) ; while (token != CSS_TOK_EOF) { double position = 0; switch (token) { case CSS_TOK_IDENT: position = css_buf.GetKeyframePosition(value.str.start_pos, value.str.str_len); break; case CSS_TOK_PERCENTAGE: position = value.number.number / 100.0; break; default: return OpStatus::OK; } if (position >= 0.0 && position <= 1.0) { CSS_KeyframeSelector* keyframe_selector = OP_NEW(CSS_KeyframeSelector, (position)); if (!keyframe_selector) return OpStatus::ERR_NO_MEMORY; keyframe_selector->Into(&new_positions); } else return OpStatus::OK; while ((token = lexer.Lex(&value)) == CSS_TOK_SPACE) ; if (token == CSS_TOK_EOF) break; if (token != CSS_COMMA) return OpStatus::OK; while ((token = lexer.Lex(&value)) == CSS_TOK_SPACE) ; } m_positions.Clear(); while (CSS_KeyframeSelector* keyframe_selector = new_positions.First()) { keyframe_selector->Out(); keyframe_selector->Into(&m_positions); } return OpStatus::OK; } else return OpStatus::ERR_NO_MEMORY; } /* virtual */ OP_STATUS CSS_KeyframesRule::GetCssText(CSS* stylesheet, TempBuffer* buf, unsigned int indent_level) { RETURN_IF_ERROR(buf->AppendFormat(UNI_L("@keyframes %s {\n"), m_name)); CSS_KeyframeRule* iter = First(); while (iter) { for (unsigned int i = 0; i < indent_level + 1 ; i++) RETURN_IF_ERROR(buf->Append(" ")); RETURN_IF_ERROR(iter->GetCssText(stylesheet, buf, indent_level + 1)); RETURN_IF_ERROR(buf->Append("\n")); iter = iter->Suc(); } for (unsigned int i = 0; i < indent_level; i++) RETURN_IF_ERROR(buf->Append(" ")); return buf->Append("}"); } /* virtual */ CSS_PARSE_STATUS CSS_KeyframesRule::SetCssText(HLDocProfile* hld_prof, CSS* stylesheet, const uni_char* text, int len) { return stylesheet->ParseAndInsertRule(hld_prof, this, NULL, this, TRUE, CSS_TOK_DOM_KEYFRAMES_RULE, text, len); } CSS_PARSE_STATUS CSS_KeyframesRule::AppendRule(HLDocProfile* hld_prof, CSS* sheet, const uni_char* rule, unsigned rule_length) { return sheet->ParseAndInsertRule(hld_prof, this, GetConditionalRule(), this, FALSE, CSS_TOK_DOM_KEYFRAME_RULE, rule, rule_length); } OP_STATUS CSS_KeyframesRule::DeleteRule(const uni_char* key_text, unsigned key_text_length) { List<CSS_KeyframeSelector> dummy; CSS_KeyframeRule comparison_rule(NULL, dummy, NULL); RETURN_IF_ERROR(comparison_rule.SetKeyText(key_text, key_text_length)); TempBuffer buf; CSS_KeyframeRule* iter = First(); while (iter) { buf.Clear(); if (comparison_rule == *iter) { CSS_KeyframeRule* delete_rule = iter; iter = iter->Suc(); delete_rule->Out(); OP_DELETE(delete_rule); } else iter = iter->Suc(); } return OpStatus::OK; } OP_STATUS CSS_KeyframesRule::FindRule(CSS_KeyframeRule*& rule, const uni_char* key_text, unsigned key_text_length) { List<CSS_KeyframeSelector> dummy; CSS_KeyframeRule comparison_rule(NULL, dummy, NULL); rule = NULL; RETURN_IF_ERROR(comparison_rule.SetKeyText(key_text, key_text_length)); TempBuffer buf; CSS_KeyframeRule* iter = First(); while (iter) { buf.Clear(); if (comparison_rule == *iter) { rule = iter; return OpStatus::OK; } else iter = iter->Suc(); } return OpStatus::OK; } #endif // CSS_ANIMATIONS