0,"#include ""BiDirectionalRpc.hpp"" #include ""TimeHandler.hpp"" namespace codefs { BiDirectionalRpc::BiDirectionalRpc() : onBarrier(0), onId(0), flaky(false), timeOffsetController(1.0, 1000000, -1000000, 0.6, 1.2, 1.0) {} BiDirectionalRpc::~BiDirectionalRpc() {} void BiDirectionalRpc::shutdown() {} void BiDirectionalRpc::heartbeat() { lock_guard guard(mutex); // TODO: If the outgoingReplies/requests is high, and we have recently // received data, flush a lot of data out VLOG(1) << ""BEAT: "" << int64_t(this); if (!outgoingReplies.empty() || !outgoingRequests.empty()) { resendRandomOutgoingMessage(); } else { VLOG(1) << ""SENDING HEARTBEAT""; string s = ""0""; s[0] = HEARTBEAT; send(s); } } void BiDirectionalRpc::resendRandomOutgoingMessage() { if (!outgoingReplies.empty() && (outgoingRequests.empty() || rand() % 2 == 0)) { // Re-send a random reply DRAW_FROM_UNORDERED(it, outgoingReplies); sendReply(it->first, it->second); } else if (!outgoingRequests.empty()) { // Re-send a random request DRAW_FROM_UNORDERED(it, outgoingRequests); sendRequest(it->first, it->second); } else { } } void BiDirectionalRpc::receive(const string& message) { lock_guard guard(mutex); VLOG(1) << ""Receiving message with length "" << message.length(); MessageReader reader; reader.load(message); RpcHeader header = (RpcHeader)reader.readPrimitive(); if (flaky && rand() % 2 == 0) { // Pretend we never got the message VLOG(1) << ""FLAKE""; } else { if (header != HEARTBEAT) { VLOG(1) << ""GOT PACKET WITH HEADER "" << header; } switch (header) { case HEARTBEAT: { // MultiEndpointHandler deals with keepalive } break; case REQUEST: { while (reader.sizeRemaining()) { RpcId rpcId = reader.readClass(); string payload = reader.readPrimitive(); handleRequest(rpcId, payload); } } break; case REPLY: { while (reader.sizeRemaining()) { RpcId uid = reader.readClass(); int64_t requestReceiptTime = reader.readPrimitive(); int64_t replySendTime = reader.readPrimitive(); auto requestSendTimeIt = requestSendTimeMap.find(uid); if (requestSendTimeIt != requestSendTimeMap.end()) { int64_t requestSendTime = requestSendTimeIt->second; requestSendTimeMap.erase(requestSendTimeIt); int64_t replyRecieveTime = TimeHandler::currentTimeMicros(); updateDrift(requestSendTime, requestReceiptTime, replySendTime, replyRecieveTime); } string payload = reader.readPrimitive(); handleReply(uid, payload); } } break; case ACKNOWLEDGE: { RpcId uid = reader.readClass(); VLOG(1) << ""ACK UID "" << uid.str(); for (auto it = outgoingReplies.begin(); it != outgoingReplies.end(); it++) { VLOG(1) << ""REPLY UID "" << it->first.str(); if (it->first == uid) { if (requestRecieveTimeMap.find(it->first) == requestRecieveTimeMap.end()) { LOG(INFO) << requestRecieveTimeMap.size(); for (const auto& it2 : requestRecieveTimeMap) { LOG(INFO) << ""XXXX: "" << it2.first.str(); } LOGFATAL << ""Tried to remove a request receive time that we "" ""didn't have: "" << it->first.str(); } requestRecieveTimeMap.erase(it->first); outgoingReplies.erase(it); break; } } } break; default: { LOGFATAL << ""Got invalid header: "" << header << "" in message "" << message; } } } } void BiDirectionalRpc::handleRequest(const RpcId& rpcId, const string& payload) { VLOG(1) << ""GOT REQUEST: "" << rpcId.str(); bool skip = (incomingRequests.find(rpcId) != incomingRequests.end()); if (!skip) { for (const auto& it : outgoingReplies) { if (it.first == rpcId) { // We already processed this request. Send the reply again skip = true; sendReply(it.first, it.second); break; } } } if (!skip) { addIncomingRequest(IdPayload(rpcId, payload)); } } void BiDirectionalRpc::handleReply(const RpcId& rpcId, const string& payload) { bool skip = false; if (incomingReplies.find(rpcId) != incomingReplies.end()) { // We already received this reply. Send acknowledge again and skip. sendAcknowledge(rpcId); skip = true; } if (!skip) { // Stop sending the request once you get the reply bool deletedRequest = false; for (auto it = outgoingRequests.begin(); it != outgoingRequests.end(); it++) { if (it->first == rpcId) { outgoingRequests.erase(it); deletedRequest = true; tryToSendBarrier(); break; } } if (deletedRequest) { auto it = oneWayRequests.find(rpcId); if (it != oneWayRequests.end()) { // Remove this from the set of one way requests and don't bother // adding a reply. oneWayRequests.erase(it); } else { // Add a reply to be processed addIncomingReply(rpcId, payload); } sendAcknowledge(rpcId); } else { // We must have processed both this request and reply. Send the // acknowledge again. sendAcknowledge(rpcId); } } } RpcId BiDirectionalRpc::request(const string& payload) { auto fullUuid = sole::uuid4(); auto uuid = RpcId(onBarrier, fullUuid.cd); auto idPayload = IdPayload(uuid, payload); requestWithId(idPayload); return uuid; } void BiDirectionalRpc::requestNoReply(const string& payload) { lock_guard guard(mutex); auto fullUuid = sole::uuid4(); auto uuid = RpcId(onBarrier, fullUuid.cd); oneWayRequests.insert(uuid); auto idPayload = IdPayload(uuid, payload); requestWithId(idPayload); } void BiDirectionalRpc::requestWithId(const IdPayload& idPayload) { lock_guard guard(mutex); if (outgoingRequests.empty() || outgoingRequests.begin()->first.barrier == onBarrier) { // We can send the request immediately outgoingRequests[idPayload.id] = idPayload.payload; requestSendTimeMap[idPayload.id] = TimeHandler::currentTimeMicros(); sendRequest(idPayload.id, idPayload.payload); } else { // We have to wait for existing requests from an older barrier delayedRequests[idPayload.id] = idPayload.payload; } } void BiDirectionalRpc::reply(const RpcId& rpcId, const string& payload) { lock_guard guard(mutex); incomingRequests.erase(incomingRequests.find(rpcId)); outgoingReplies[rpcId] = payload; sendReply(rpcId, payload); } void BiDirectionalRpc::tryToSendBarrier() { if (delayedRequests.empty()) { // Nothing to send return; } if (outgoingRequests.empty()) { // There are no outgoing requests, we can send the next barrier int64_t lowestBarrier = delayedRequests.begin()->first.barrier; for (const auto& it : delayedRequests) { lowestBarrier = min(lowestBarrier, it.first.barrier); } for (auto it = delayedRequests.begin(); it != delayedRequests.end();) { if (it->first.barrier == lowestBarrier) { outgoingRequests[it->first] = it->second; requestSendTimeMap[it->first] = TimeHandler::currentTimeMicros(); sendRequest(it->first, it->second); it = delayedRequests.erase(it); } else { it++; } } } } void BiDirectionalRpc::sendRequest(const RpcId& id, const string& payload) { VLOG(1) << ""SENDING REQUEST: "" << id.str(); MessageWriter writer; writer.start(); set rpcsSent; rpcsSent.insert(id); writer.writePrimitive(REQUEST); writer.writeClass(id); writer.writePrimitive(payload); // Try to attach more requests to this packet int i = 0; while (!outgoingRequests.empty() && rpcsSent.size() < outgoingRequests.size()) { DRAW_FROM_UNORDERED(it, outgoingRequests); if (rpcsSent.find(it->first) != rpcsSent.end()) { // Drew an rpc that's already in the packet. Just bail for now, maybe in // the future do something more clever. break; } int size = sizeof(RpcId) + it->second.length(); if (size + writer.size() > 400) { // Too big break; } i++; rpcsSent.insert(it->first); writer.writeClass(it->first); writer.writePrimitive(it->second); } VLOG(1) << ""Attached "" << i << "" extra packets""; send(writer.finish()); } void BiDirectionalRpc::sendReply(const RpcId& id, const string& payload) { lock_guard guard(mutex); VLOG(1) << ""SENDING REPLY: "" << id.str(); set rpcsSent; rpcsSent.insert(id); MessageWriter writer; writer.start(); writer.writePrimitive(REPLY); writer.writeClass(id); auto receiveTimeIt = requestRecieveTimeMap.find(id); if (receiveTimeIt == requestRecieveTimeMap.end()) { LOGFATAL << ""Got a request with no receive time: "" << id.str() << "" "" << requestRecieveTimeMap.size(); } writer.writePrimitive(receiveTimeIt->second); writer.writePrimitive(TimeHandler::currentTimeMicros()); writer.writePrimitive(payload); // Try to attach more replies to this packet int i = 0; while (!outgoingReplies.empty() && rpcsSent.size() < outgoingReplies.size()) { DRAW_FROM_UNORDERED(it, outgoingReplies); if (rpcsSent.find(it->first) != rpcsSent.end()) { // Drew an rpc that's already in the packet. Just bail for now, maybe in // the future do something more clever. break; } int size = sizeof(RpcId) + it->second.length(); if (size + writer.size() > 400) { // Too big break; } i++; rpcsSent.insert(it->first); writer.writeClass(it->first); receiveTimeIt = requestRecieveTimeMap.find(it->first); if (receiveTimeIt == requestRecieveTimeMap.end()) { LOGFATAL << ""Got a request with no receive time""; } writer.writePrimitive(receiveTimeIt->second); writer.writePrimitive(TimeHandler::currentTimeMicros()); writer.writePrimitive(it->second); } VLOG(1) << ""Attached "" << i << "" extra packets""; send(writer.finish()); } void BiDirectionalRpc::sendAcknowledge(const RpcId& uid) { MessageWriter writer; writer.start(); writer.writePrimitive(ACKNOWLEDGE); writer.writeClass(uid); send(writer.finish()); } void BiDirectionalRpc::addIncomingRequest(const IdPayload& idPayload) { lock_guard guard(mutex); if (requestRecieveTimeMap.find(idPayload.id) != requestRecieveTimeMap.end()) { LOGFATAL << ""Already created receive time for id: "" << idPayload.id.str(); } requestRecieveTimeMap[idPayload.id] = TimeHandler::currentTimeMicros(); incomingRequests.insert(make_pair(idPayload.id, idPayload.payload)); } void BiDirectionalRpc::updateDrift(int64_t requestSendTime, int64_t requestReceiptTime, int64_t replySendTime, int64_t replyRecieveTime) { int64_t timeOffset = ((requestReceiptTime - requestSendTime) + (replySendTime - replyRecieveTime)) / 2; int64_t [MASK] = (replyRecieveTime - requestSendTime) - (replySendTime - requestReceiptTime); networkStatsQueue.push_back({timeOffset, [MASK] }); VLOG(2) << ""Time Sync Info: "" << timeOffset << "" "" << [MASK] << "" "" << (replyRecieveTime - requestSendTime) << "" "" << (replySendTime - requestReceiptTime); if (networkStatsQueue.size() >= 100) { LOG(INFO) << ""Time Sync Info: "" << timeOffset << "" "" << [MASK] << "" "" << (replyRecieveTime - requestSendTime) << "" "" << (replySendTime - requestReceiptTime); int64_t sumShift = 0; int64_t shiftCount = 0; for (int i = 0; i < networkStatsQueue.size(); i++) { sumShift += networkStatsQueue.at(i).offset; shiftCount++; } if (shiftCount) { VLOG(2) << ""New shift: "" << (sumShift / shiftCount); auto shift = std::chrono::microseconds{sumShift / shiftCount / int64_t(5)}; VLOG(2) << ""TIME CHANGE: "" << TimeHandler::currentTimeMicros(); TimeHandler::initialTime -= shift; VLOG(2) << ""TIME CHANGE: "" << TimeHandler::currentTimeMicros(); } } // auto shift = std::chrono::microseconds{ // int64_t(timeOffsetController.calculate(0, double(timeOffset)))}; // TimeHandler::initialTime += shift; networkStatsQueue.clear(); } } // namespace codefs ",ping 1,"#ifndef CATCH_UP_ENGINE_SRC_INCLUDE_COMPONENT_BASE_H #define CATCH_UP_ENGINE_SRC_INCLUDE_COMPONENT_BASE_H #include #include #include ""uuid.h"" #include ""component.h"" namespace Engine { class CollisionListener; class Timestep; class GameObject; class Scene { public: static Scene* getInstance() { static Scene [MASK] ; return & [MASK] ; } Scene(const Scene&) = delete; Scene(const Scene&&) = delete; void createGameObject(GameObject& object); void createGameObjectWithUUID(UUID uuid, GameObject& object); void destroyGameObject(); GameObject getGameObjectByUUID(UUID uuid); void start(); void update(); private: Scene() {} ~Scene() {} void renderScene(); void physicsStart(); void onPhysicsStop(); int m_step_frames = 60; std::list m_pending_deletion_list; std::list m_game_object_list; entt::registry m_game_objects; std::unordered_map m_entity_map; friend GameObject; }; } #endif // !CATCH_UP_ENGINE_SRC_INCLUDE_COMPONENT_BASE_H",instance 2," #ifndef _PYODBCSQLWCHAR_H #define _PYODBCSQLWCHAR_H typedef unsigned short ODBCCHAR; // I'm not sure why, but unixODBC seems to define SQLWCHAR as wchar_t even with // the size is incorrect. So we might get 4-byte SQLWCHAR on 64-bit Linux even // though it requires 2-byte characters. We have to define our own type to // operate on. enum { ODBCCHAR_SIZE = 2 }; class SQLWChar { private: SQLWChar(const SQLWChar& other) {} void operator=(const SQLWChar& other) {} Object tmp; // If the passed in string/unicode object needed to be encoded, this holds // the bytes object it was encoded into. If set, sz points into this // object. const char* sz; // The value of the string. If this is zero a Python error occurred in the // constructor and nothing further should be one with this. Py_ssize_t cb; // The length of `sz` in *bytes*. SQLSMALLINT ctype; // The target C type, either SQL_C_CHAR or SQL_C_WCHAR. void init(PyObject* value, SQLSMALLINT [MASK] , PyObject* encoding, const char* szDefaultEncoding) { sz = 0; cb = 0; ctype = [MASK] ; I(ctype == SQL_C_CHAR || ctype == SQL_C_WCHAR); const char* szEncoding = szDefaultEncoding; if (strcmp(szEncoding, ""raw"") == 0) { // If `value` is not a bytes object, PyBytes_AsString below will return 0 which we // handle later. (Do not use AS_STRING which does no error checking.) tmp = value; sz = PyBytes_AsString(tmp); cb = PyBytes_Size(tmp); } else { Object tmpEncoding; if (encoding) { tmpEncoding = PyCodec_Encode(encoding, ""utf-8"", ""strict""); if (tmpEncoding) szEncoding = PyBytes_AsString(tmpEncoding); } if (szEncoding) { tmp = PyCodec_Encode(value, szEncoding, ""strict""); if (tmp) { sz = PyBytes_AsString(tmp); cb = PyBytes_Size(tmp); } } } } public: SQLWChar(PyObject* value, SQLSMALLINT ctype, const char* szEncoding) { init(value, ctype, 0, szEncoding); } SQLWChar(PyObject* value, SQLSMALLINT ctype, PyObject* encoding, const char* szDefaultEncoding) { init(value, ctype, encoding, szDefaultEncoding); } operator bool() const { return sz != 0; } const char* value() const { return sz; } Py_ssize_t bytelen() const { return cb; } Py_ssize_t charlen() const { return cb / (ctype == SQL_C_WCHAR ? ODBCCHAR_SIZE : 1); } }; #endif // _PYODBCSQLWCHAR_H ",_ctype 3,"/** * This Sketch reads a Resistor Ladder to determine a pitch to send * to the Piezo unit. It's designed to be used like an Electronic * Keyboard =) * */ const int NOTES[] = { 262, 294, 330, 349 }; void setup() { Serial.begin(9600); } void loop() { int keyValue = analogRead(A0); makeSoundForKey(keyValue); Serial.println(keyValue); sleep(30); } void makeSoundForKey(int value) { if (isC(value)) { soundC(); } else if (isD(value)) { soundD(); } else if (isE(value)) { soundE(); } else if (isF(value)) { soundF(); } else { makeNoSound(); } } boolean isC(int value) { return value == 1023; } boolean isD(int value) { return value > 995 && value < 1005; } boolean isE(int value) { return value > 495 && value < 510; } boolean isF(int value) { return value > 5 && value < 15; } void soundC() { tone(9, NOTES[0]); } void soundD() { tone(9, NOTES[1]); } void soundE() { tone(9, NOTES[2]); } void soundF() { tone(9, NOTES[3]); } void makeNoSound() { noTone(9); } void sleep(long [MASK] ) { delay( [MASK] ); } ",amount 4,"//***************************************************************************** // Copyright 2020-2022 Intel Corporation // // 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 #include #include #include #include #include #include #include #include ""customloaderinterface.hpp"" #include ""ovsa_model_instance.hpp"" #include ""rapidjson/document.h"" using namespace ovms; extern ""C"" { #define MAX_NAME_SIZE 256 typedef struct ovsa_model_files { char model_file_name[MAX_NAME_SIZE]; char* model_file_data; int model_file_length; struct ovsa_model_files* next; } ovsa_model_files_t; ovsa_status_t ovsa_license_check_module(const char* keystore, const char* controlled_access_model, const char* customer_license, ovsa_model_files_t** decrypted_files); ovsa_status_t ovsa_crypto_init(); void ovsa_crypto_deinit(); void ovsa_safe_free_model_file_list(ovsa_model_files_t** listhead); }; // Time in seconds at which model status will be checked #define VALIDITY_CHECK_INTERVAL_MAX 1440 // 24hrs #define VALIDITY_CHECK_INTERVAL_MIN 1 // 1min #if OVMS_LICCHECK_MINS < VALIDITY_CHECK_INTERVAL_MIN #define VALIDITY_CHECK_INTERVAL (VALIDITY_CHECK_INTERVAL_MIN * 60 * 1000) // 1min minimum value #elif OVMS_LICCHECK_MINS > VALIDITY_CHECK_INTERVAL_MAX #define VALIDITY_CHECK_INTERVAL (VALIDITY_CHECK_INTERVAL_MAX * 60 * 1000) // 24hrs maximum value #else #define VALIDITY_CHECK_INTERVAL (OVMS_LICCHECK_MINS * 60 * 1000) #endif typedef std::pair map_key_t; typedef std::pair model_file_t; /* * This class implements am example custom model loader for OVMS. * It derives the implementation from base class CustomLoaderInterface * defined in ovms. The purpose this example is to demonstrate the * usage of various APIs defined in base class, parse loader specific * parameters from the config file. * * It reads the model files and returns the buffers to be loaded by the * model server. * * Also, based on the contents on .status file, it black lists the model * or removes the model from blacklisting. During the periodic check on model * loader will unload/reload model based on blacklist. */ class OvsaCustomLoader : public CustomLoaderInterface { private: std::map> model_map; std::mutex critical_ops; std::mutex models_watched_mutex; protected: CustomLoaderStatus ovsa_json_extract_input_params(const std::string& basePath, const int version, const std::string& loaderOptions, std::string& loaderName, std::string& ksFile, std::string& licFile, std::string& datFile); public: OvsaCustomLoader(); ~OvsaCustomLoader(); // Virtual functions of the base class defined here CustomLoaderStatus loaderInit(const std::string& loader_path); CustomLoaderStatus loaderDeInit(); CustomLoaderStatus unloadModel(const std::string& modelName, int version); CustomLoaderStatus loadModel(const std::string& modelName, const std::string& basePath, const int version, const std::string& loaderOptions, std::vector& modelBuffer, std::vector& weights); CustomLoaderStatus getModelBlacklistStatus(const std::string& modelName, int version); CustomLoaderStatus retireModel(const std::string& modelName); }; extern ""C"" CustomLoaderInterface* createCustomLoader() { return new OvsaCustomLoader(); } OvsaCustomLoader::OvsaCustomLoader() { std::cout << ""OvsaCustomLoader: Instance of Custom SampleLoader created"" << std::endl; } OvsaCustomLoader::~OvsaCustomLoader() { std::cout << ""OvsaCustomLoader: Instance of Custom SampleLoader deleted"" << std::endl; ovsa_crypto_deinit(); } CustomLoaderStatus OvsaCustomLoader::loaderInit(const std::string& loader_path) { std::cout << ""OvsaCustomLoader: Custom loaderInit"" << loader_path << std::endl; ovsa_status_t ret = ovsa_crypto_init(); if (ret < OVSA_OK) { OVSA_DBG(DBG_E, ""OvsaCustomLoader: Crypto init failed with code %d\n"", ret); return CustomLoaderStatus::MODEL_LOAD_ERROR; } return CustomLoaderStatus::OK; } CustomLoaderStatus OvsaCustomLoader::ovsa_json_extract_input_params( const std::string& basePath, const int version, const std::string& loaderOptions, std::string& loaderName, std::string& ksFile, std::string& licFile, std::string& datFile) { CustomLoaderStatus ret = CustomLoaderStatus::OK; rapidjson::Document doc; if (basePath.empty() | loaderOptions.empty()) { std::cout << ""OvsaCustomLoader: Error invalid input parameters to loadModel"" << std::endl; return CustomLoaderStatus::MODEL_LOAD_ERROR; } std::string fullPath = basePath + ""/"" + std::to_string(version); // parse jason input string if (doc.Parse(loaderOptions.c_str()).HasParseError()) { return CustomLoaderStatus::MODEL_LOAD_ERROR; } for (rapidjson::Value::ConstMemberIterator itr = doc.MemberBegin(); itr != doc.MemberEnd(); ++itr) printf(""Type of member %s is %s\n"", itr->name.GetString(), itr->value.GetString()); if (doc.HasMember(""loader_name"")) { std::string lname = doc[""loader_name""].GetString(); loaderName = fullPath + ""/"" + lname; std::cout << ""OvsaCustomLoader: \nloader_name:"" << loaderName << std::endl; } if (doc.HasMember(""controlled_access_file"")) { std::string controlled_access_file = doc[""controlled_access_file""].GetString(); datFile = fullPath + ""/"" + controlled_access_file + "".dat""; std::cout << ""datFile:"" << datFile << std::endl; licFile = fullPath + ""/"" + controlled_access_file + "".lic""; std::cout << ""licFile:"" << licFile << std::endl; } if (doc.HasMember(""keystore"")) { std::string ks = doc[""keystore""].GetString(); ksFile = ks; std::cout << ""keystore:"" << ksFile << std::endl; } return ret; } /* * From the custom loader options extract the model file name and other needed information and * load the model and optional bin file into buffers and return */ CustomLoaderStatus OvsaCustomLoader::loadModel(const std::string& modelName, const std::string& basePath, const int version, const std::string& loaderOptions, std::vector& modelBuffer, std::vector& weights) { std::cout << ""OvsaCustomLoader: Custom loadModel"" << std::endl; std::string type; std::string loaderName; std::string ksFile; std::string licFile; std::string datFile; ovsa_model_files_t* decrypted_files = NULL; CustomLoaderStatus retStatus = CustomLoaderStatus::MODEL_LOAD_ERROR; if (modelName.empty() || basePath.empty() || loaderOptions.empty()) { std::cout << ""OvsaCustomLoader: Error invalid input parameters to loadModel"" << std::endl; return CustomLoaderStatus::MODEL_LOAD_ERROR; } CustomLoaderStatus st = ovsa_json_extract_input_params(basePath, version, loaderOptions, loaderName, ksFile, licFile, datFile); if (st != CustomLoaderStatus::OK || ksFile.empty() || licFile.empty() || datFile.empty()) { std::cout << ""OvsaCustomLoader: Error invalid custom loader options"" << std::endl; return CustomLoaderStatus::MODEL_LOAD_ERROR; } std::unique_lock lockGuard(critical_ops); ovsa_status_t [MASK] = ovsa_license_check_module(ksFile.c_str(), datFile.c_str(), licFile.c_str(), &decrypted_files); if ( [MASK] != OVSA_OK) { if ( [MASK] == OVSA_LICENSE_SERVER_CONNECT_FAIL) { OVSA_DBG(DBG_E, ""OvsaCustomLoader: Error LICENSE CHECK SERVER CONNECT FAILED"" "" with %d\n"", [MASK] ); } else if ( [MASK] == OVSA_LICENSE_CHECK_FAIL) { OVSA_DBG(DBG_E, ""OvsaCustomLoader: Error LICENSE CHECK FAILED with %d\n"", [MASK] ); } else { OVSA_DBG(DBG_E, ""OvsaCustomLoader: Error ovsa_license_check_module with code %d\n"", [MASK] ); } ovsa_safe_free_model_file_list(&decrypted_files); return CustomLoaderStatus::MODEL_LOAD_ERROR; } lockGuard.unlock(); std::vector> modelFileVec; ovsa_model_files_t* head = decrypted_files; bool file_type_ir = false; while (head != NULL) { // model_file_t file_data = std::make_pair(head->model_file_name,head->model_file_data); // modelFileVec.pushback(file_data); // std::string filename(head->model_file_name); size_t found = filename.find("".xml""); if (found != std::string::npos) { std::cout << ""OvsaCustomLoader: "" << head->model_file_name << std::endl; std::vector mdl(&head->model_file_data[0], &head->model_file_data[head->model_file_length]); modelBuffer.insert(modelBuffer.end(), mdl.begin(), mdl.end()); if (file_type_ir) { retStatus = CustomLoaderStatus::MODEL_TYPE_IR; } else { file_type_ir = true; } } found = filename.find("".bin""); if (found != std::string::npos) { std::cout << ""OvsaCustomLoader: "" << head->model_file_name << std::endl; std::vector wts(&head->model_file_data[0], &head->model_file_data[head->model_file_length]); weights.insert(weights.end(), wts.begin(), wts.end()); if (file_type_ir) { retStatus = CustomLoaderStatus::MODEL_TYPE_IR; } else { file_type_ir = true; } } found = filename.find("".blob""); if (found != std::string::npos) { std::cout << ""OvsaCustomLoader: "" << head->model_file_name << std::endl; std::vector mdl(&head->model_file_data[0], &head->model_file_data[head->model_file_length]); modelBuffer.insert(modelBuffer.end(), mdl.begin(), mdl.end()); retStatus = CustomLoaderStatus::MODEL_TYPE_BLOB; } found = filename.find("".onnx""); if (found != std::string::npos) { std::cout << ""OvsaCustomLoader: "" << head->model_file_name << std::endl; std::vector mdl(&head->model_file_data[0], &head->model_file_data[head->model_file_length]); modelBuffer.insert(modelBuffer.end(), mdl.begin(), mdl.end()); retStatus = CustomLoaderStatus::MODEL_TYPE_ONNX; } head = head->next; } if (retStatus != CustomLoaderStatus::MODEL_LOAD_ERROR) { std::lock_guard guard(models_watched_mutex); map_key_t key = std::make_pair(modelName, version); model_map[key] = std::make_shared(modelName, ksFile, licFile, datFile, false, version, ref(critical_ops)); auto itr = model_map.find(key); if (itr != model_map.end()) { itr->second->startWatcher(VALIDITY_CHECK_INTERVAL); std::this_thread::sleep_for(std::chrono::seconds(1)); } } ovsa_safe_free_model_file_list(&decrypted_files); return retStatus; } // Retire the model CustomLoaderStatus OvsaCustomLoader::retireModel(const std::string& modelName) { std::vector toDelete; std::lock_guard guard(models_watched_mutex); for (auto it : model_map) { if ((it.first).first == modelName) { toDelete.push_back(it.first); } } for (auto itr : toDelete) { model_map.erase(itr); } return CustomLoaderStatus::OK; } // Unload model from loaded models list. CustomLoaderStatus OvsaCustomLoader::unloadModel(const std::string& modelName, const int version) { std::cout << ""OvsaCustomLoader: Custom unloadModel"" << std::endl; map_key_t toFind = std::make_pair(modelName, version); std::lock_guard guard(models_watched_mutex); auto it = model_map.find(toFind); if (it == model_map.end()) { std::cout << modelName << "" is not loaded"" << std::endl; } else { it->second->releaseResources(); model_map.erase(it); } return CustomLoaderStatus::OK; } CustomLoaderStatus OvsaCustomLoader::loaderDeInit() { std::cout << ""OvsaCustomLoader: Custom loaderDeInit"" << std::endl; ovsa_crypto_deinit(); return CustomLoaderStatus::OK; } CustomLoaderStatus OvsaCustomLoader::getModelBlacklistStatus(const std::string& modelName, const int version) { OVSA_DBG(DBG_D, ""OvsaCustomLoader: Custom getModelBlacklistStatus\n""); map_key_t toFind = std::make_pair(modelName, version); auto it = model_map.find(toFind); if (it == model_map.end()) { OVSA_DBG(DBG_D, ""OvsaCustomLoader: Model:%s Version:%d not loaded\n"", (char*)modelName.c_str(), version); return CustomLoaderStatus::OK; } bool status = it->second->getBlackListStatus(); if (status) return CustomLoaderStatus::MODEL_BLACKLISTED; else return CustomLoaderStatus::OK; } ",rets 5,"#include using namespace std; typedef long long ll; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); // freopen("".in"", ""r"", stdin); // freopen("".out"", ""w"", stdout); int [MASK] ; ll numDays; cin >> [MASK] >> numDays; vector> deliveries; for (int i = 0; i < [MASK] ; ++i) { ll day; int amt; cin >> day >> amt; deliveries.emplace_back(day, amt); } // first delivery day ll numEaten = 1; ll numLeft = deliveries[0].second - 1; ll prevDeliveryDay = deliveries[0].first; ll currDeliveryDay; for (int i = 1; i < [MASK] ; ++i) { currDeliveryDay = deliveries[i].first; ll daysInBetween = currDeliveryDay - prevDeliveryDay - 1; if (numLeft > daysInBetween) { numEaten += daysInBetween; numLeft -= daysInBetween; } else { numEaten += numLeft; numLeft = 0; } numLeft += deliveries[i].second; ++numEaten; --numLeft; prevDeliveryDay = currDeliveryDay; } ll daysToEnd = numDays - prevDeliveryDay; if (daysToEnd > 0) { if (numLeft > daysToEnd) { numEaten += daysToEnd; } else { numEaten += numLeft; } } cout << numEaten; return 0; } ",numDeliveries 6,"#include ""rclcpp/rclcpp.hpp"" #include ""sensor_msgs/msg/laser_scan.hpp"" class LidarFilterNode : public rclcpp::Node { public: LidarFilterNode() : Node(""lidar_filter_node"") { subscription_ = this->create_subscription( ""/scan"", 10, std::bind(&LidarFilterNode::listener_callback, this, std::placeholders::_1)); publisher_ = this->create_publisher(""/filtered_scan"", 10); } private: void listener_callback(const sensor_msgs::msg::LaserScan::SharedPtr msg) { auto filtered_scan = std::make_shared(*msg); filtered_scan->ranges.clear(); double angle_min = -60.0 * M_PI / 180.0; // -60 degrees in radians double angle_max = 60.0 * M_PI / 180.0; // 60 degrees in radians double current_angle = msg->angle_min; for (const auto &range : msg->ranges) { if (current_angle >= angle_min && current_angle <= angle_max) { filtered_scan->ranges.push_back(range); } else { filtered_scan->ranges.push_back(std::numeric_limits::infinity()); } current_angle += msg->angle_increment; } publisher_->publish(*filtered_scan); } rclcpp::Subscription::SharedPtr subscription_; rclcpp::Publisher::SharedPtr publisher_; }; int main(int [MASK] , char *argv[]) { rclcpp::init( [MASK] , argv); rclcpp::spin(std::make_shared()); rclcpp::shutdown(); return 0; } ",argc 7,"// Copyright (c) 2025 // // 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 ""product_of_exponentials/product_of_exponentials.hpp"" int main(int [MASK] , char * argv[]) { rclcpp::init( [MASK] , argv); rclcpp::executors::MultiThreadedExecutor exec; const auto product_of_exponentials = std::make_shared(rclcpp::NodeOptions()); exec.add_node(product_of_exponentials); exec.spin(); rclcpp::shutdown(); } ",argc 8,"#include using namespace std; struct Patient{ int patientID, hieght, wieght, visionNo; string testStatus; Patient* next; int data; Patient(int p, int h, int w, int v, string t, Patient* n, int d){ patientID = p; hieght = h; wieght = w; visionNo = v; testStatus = t; next = n; data = d; } }; class PhysicalTest{ Patient* front = NULL; Patient* rear = NULL; public: void AddPatient(int patientID, int hieght, int wieght, int visionNo, string testStatus, int data){ Patient* newPatient = new Patient(patientID, hieght, wieght, visionNo, testStatus, NULL, data); if (rear == NULL){ front = rear = newPatient; } else{ rear->next = newPatient; rear = newPatient; } } void dischargePatient(){ if (front == NULL){ cout<<""Empty queue""; return; } Patient* temp = front; front = front->next; if (front == NULL){ rear = NULL; } delete temp; } void removeSendPatient(){ if (front != NULL || front->next== NULL){ cout<<"" Patient 2nd in the line has left the line\n""; } } void DisplayPatient(){ Patient* temp = front; while (temp != NULL){ cout<<""Patient id: ""<patientID<<"" ""; cout<<"" Patient Hieght: ""<hieght<<"" Patient Weight: ""<wieght<<"" Patient eyes sight vision number: ""<visionNo; cout<<"" Patient test status: ""<testStatus; temp = temp->next; } } }; int main(){ PhysicalTest [MASK] ; [MASK] .AddPatient(39849, 175, 65, 1, "" done"", 2); [MASK] .AddPatient(39850, 180, 65, 2, "" pending"", 2); [MASK] .AddPatient(39851, 171, 65, 1, "" pending"", 2); [MASK] .AddPatient(39852, 160, 65, 2, "" done"", 2); [MASK] .AddPatient(39853, 175, 65, 1, "" done"", 2); [MASK] .AddPatient(39854, 172, 65, 1, "" pending"", 2); [MASK] .AddPatient(39855, 171, 65, 2, "" done"", 2); [MASK] .removeSendPatient(); [MASK] .DisplayPatient(); return 0; } ",patient1 9,"#ifndef _BTREE_H_ #define _BTREE_H_ #include #include #include #include #include #include ""algo/ParamTrait.h"" namespace snippet { namespace algo { namespace detail { template class BTreeNode { public: typedef KType KeyType; typedef typename ParamTrait::DeclType KeyDeclType; typedef VType ValueType; typedef std::pair Elem; static const unsigned int MAX_KEY_NUM = (NodeSize - sizeof(BTreeNode*)) / (sizeof(Elem) + sizeof(BTreeNode*)); static const unsigned int CHILDREN_SIZE = MAX_KEY_NUM + 1; /// max_key_num should be an odd number BTreeNode(const unsigned max_key_num) : m_key_num(0), m_is_leave(true) { memset(m_children, 0, CHILDREN_SIZE * sizeof(m_children[0])); } ~BTreeNode() { if (m_key_num > 0) { for (unsigned i = 0; i <= m_key_num; ++i) { delete m_children[i]; } } } void SetIsLeave(const bool is_leave) { m_is_leave = is_leave; } void AddItem(const KeyType key, const ValueType& value) { // TODO: add implementation } unsigned GetSize() const { unsigned total_key_num = GetKeyNum(); if (total_key_num > 0 && !IsLeave()) { for (unsigned i = 0; i <= GetKeyNum(); ++i) { const BTreeNode* child = GetChild(i); if (child) { total_key_num += child->GetSize(); } } } return total_key_num; } void Dump(const int level) const { std::cout << '[' << level << ']'; std::cout << ""key_num:"" << m_key_num << "" elements: ""; const unsigned key_num = GetKeyNum(); for (unsigned i = 0; i < key_num; ++i) { std::cout << GetKey(i) << ' '; } std::cout << std::endl; if (key_num > 0 && !IsLeave()) { for (unsigned i = 0; i <= key_num; ++i) { const BTreeNode* child = GetChild(i); if (child) { child->Dump(level + 1); } } } } unsigned GetMaxKeyNum() const { return MAX_KEY_NUM; } unsigned GetKeyNum() const { return m_key_num; } /// get the key at index i, if i >= m_key_num, /// the result is undefined. inline KeyType GetKey(const unsigned i) const { return m_elements[i].first; } inline bool IsLeave() const { return m_is_leave; } /// get the child at index i, if i > m_key_num, /// the result is NULL; BTreeNode* GetChild(const unsigned i) const { return i <= m_key_num ? m_children[i] : NULL; } void SplitChild(const unsigned i, BTreeNode& child) { const unsigned max_key_num = MAX_KEY_NUM; const unsigned min_key_num = max_key_num / 2; BTreeNode* new_child = new BTreeNode(max_key_num); new_child->SetIsLeave(child.IsLeave()); new_child->SetKeyNum(min_key_num); for (unsigned j = 0; j < min_key_num; ++j) { const Elem& e = child.m_elements[min_key_num + 1 + j]; new_child->SetItem(j, e.first, e.second); } if (!child.IsLeave()) { for (unsigned j = 0; j <= min_key_num; ++j) { new_child->m_children[j] = child.m_children[min_key_num + 1 + j]; } } child.SetKeyNum(min_key_num); for (unsigned j = GetKeyNum(); j > i; --j) { m_children[j + 1] = m_children[j]; } m_children[i + 1] = new_child; for (int j = static_cast(GetKeyNum()) - 1; j >= static_cast(i); --j) { m_elements[j + 1] = m_elements[j]; } m_elements[i] = child.m_elements[min_key_num]; ++m_key_num; } void InsertNonfull(const KeyType key, const ValueType& value) { int i = static_cast(GetKeyNum()) - 1; if (IsLeave()) { while (i >= 0 && key < GetKey(static_cast(i))) { m_elements[i + 1] = m_elements[i]; --i; } SetItem(static_cast(i) + 1, key, value); ++m_key_num; } else { while (i >= 0 && key < GetKey(static_cast(i))) { --i; } ++i; BTreeNode* child = m_children[i]; if (child->GetKeyNum() == MAX_KEY_NUM) { SplitChild(static_cast(i), *child); if (key > GetKey(static_cast(i))) { ++i; } } m_children[i]->InsertNonfull(key, value); } } bool Find(const KeyType key, unsigned* idx) const { KeyType [MASK] ; // TODO: use lower bound here for (unsigned i = 0; i < m_key_num; ++i) { [MASK] = GetKey(i); if (key <= [MASK] ) { *idx = i; return key == [MASK] ; } } *idx = m_key_num; return false; } void GetMaxKeyItem(KeyType* key, ValueType* value) const { if (IsLeave()) { *key = m_elements[m_key_num - 1].first; *value = m_elements[m_key_num - 1].second; } else { m_children[m_key_num]->GetMaxKeyItem(key, value); } } void GetMinKeyItem(KeyType* key, ValueType* value) const { if (IsLeave()) { *key = m_elements[0].first; *value = m_elements[0].second; } else { m_children[0]->GetMinKeyItem(key, value); } } void Delete(const unsigned idx) { for (unsigned i = idx + 1; i < m_key_num; ++i) { m_elements[i - 1] = m_elements[i]; } --m_key_num; } BTreeNode* MergeChildren(const unsigned idx) { BTreeNode* first_child = m_children[idx]; BTreeNode* second_child = m_children[idx + 1]; const unsigned first_old_key_num = first_child->m_key_num; const unsigned second_old_key_num = second_child->m_key_num; // merge keys and values first_child->m_elements[first_old_key_num] = m_elements[idx]; for (unsigned i = 0; i < second_old_key_num; ++i) { first_child->m_elements[first_old_key_num + 1 + i] = second_child->m_elements[i]; } // merge the children for (unsigned i = 0; i <= second_old_key_num; ++i) { first_child->SetChild(first_old_key_num + 1 + i, second_child->m_children[i]); } first_child->m_key_num += second_old_key_num + 1; // move the key backward in the parent. for (unsigned i = idx; i < m_key_num - 1; ++i) { m_elements[i] = m_elements[i + 1]; } // move the children backward in the parent for (unsigned i = idx + 1; i < m_key_num; ++i) { m_children[i] = m_children[i + 1]; } --m_key_num; second_child->SetKeyNum(0); // we have to reset before deleting delete second_child; return first_child; } void LeftShiftKey(const unsigned idx) { BTreeNode* left_child = m_children[idx]; BTreeNode* right_child = m_children[idx + 1]; const unsigned left_key_num = left_child->GetKeyNum(); const unsigned right_key_num = right_child->GetKeyNum(); left_child->m_elements[left_key_num] = m_elements[idx]; left_child->m_children[left_key_num + 1] = right_child->m_children[0]; ++(left_child->m_key_num); m_elements[idx] = right_child->m_elements[0]; for (unsigned i = 0; i < right_key_num - 1; ++i) { right_child->m_elements[i] = right_child->m_elements[i + 1]; right_child->m_children[i] = right_child->m_children[i + 1]; } right_child->m_children[right_key_num - 1] = right_child->m_children[right_key_num]; --(right_child->m_key_num); } void RightShiftKey(const unsigned idx) { BTreeNode* left_child = m_children[idx]; BTreeNode* right_child = m_children[idx + 1]; const unsigned left_key_num = left_child->GetKeyNum(); const unsigned right_key_num = right_child->GetKeyNum(); for (unsigned i = right_key_num; i > 0; --i) { right_child->m_elements[i] = right_child->m_elements[i - 1]; right_child->m_children[i + 1] = right_child->m_children[i]; } right_child->m_children[1] = right_child->m_children[0]; right_child->m_elements[0] = m_elements[idx]; right_child->m_children[0] = left_child->m_children[left_key_num]; ++(right_child->m_key_num); m_elements[idx] = left_child->m_elements[left_key_num - 1]; --(left_child->m_key_num); } void SetKeyNum(const unsigned key_num) { m_key_num = key_num <= 1024 ? key_num : 1024; } void SetChild(const unsigned i, BTreeNode* child) { m_children[i] = child; } void SetItem(const unsigned i, const KeyType key, const ValueType& value) { m_elements[i].first = key; m_elements[i].second = value; } private: Elem m_elements[MAX_KEY_NUM]; BTreeNode* m_children[CHILDREN_SIZE]; unsigned int m_key_num; bool m_is_leave; }; } // namespace detail class BTree { public: typedef detail::BTreeNode BTreeNode; BTree(const unsigned max_key_num) { m_root = new BTreeNode(max_key_num); m_root->SetIsLeave(true); } ~BTree() { delete m_root; } unsigned GetSize() const { return m_root->GetSize(); } void Dump() const { std::cout << ""max_key_num:"" << m_root->GetMaxKeyNum() << std::endl; m_root->Dump(0); } bool Find(const int key, BTreeNode** out_node, int* out_index) const { return Find(*m_root, key, out_node, out_index); } void Insert(const int key, const std::string& value) { const unsigned max_key_num = m_root->GetMaxKeyNum(); if (m_root->GetKeyNum() == max_key_num) { BTreeNode* old_root = m_root; m_root = new BTreeNode(max_key_num); m_root->SetIsLeave(false); m_root->SetKeyNum(0); m_root->SetChild(0, old_root); m_root->SplitChild(0, *old_root); m_root->InsertNonfull(key, value); } else { m_root->InsertNonfull(key, value); } } void Delete(const int key) { if (m_root->GetKeyNum() == 0) { return; } else if (m_root->GetKeyNum() == 1 && !m_root->IsLeave()) { BTreeNode* first_child = m_root->GetChild(0); BTreeNode* second_child = m_root->GetChild(1); const unsigned min_key_num = m_root->GetMaxKeyNum() / 2; if (first_child->GetKeyNum() == min_key_num && second_child->GetKeyNum() == min_key_num) { first_child = m_root->MergeChildren(0); m_root->SetKeyNum(0); delete m_root; m_root = first_child; Delete(*m_root, key); } else { Delete(*m_root, key); } } else { Delete(*m_root, key); } } private: bool Find(BTreeNode& node, const int key, BTreeNode** out_node, int* out_index) const { const unsigned key_num = node.GetKeyNum(); unsigned i = 0; while (i < key_num && key > node.GetKey(i)) { ++i; } if (i < key_num && key == node.GetKey(i)) { if (out_node) { *out_node = &node; *out_index = i; } return true; } if (node.IsLeave()) { return false; } else { BTreeNode* child_node = node.GetChild(i); return Find(*child_node, key, out_node, out_index); } } void Delete(BTreeNode& node, const int key) { unsigned key_idx; bool is_key_found = node.Find(key, &key_idx); if (node.IsLeave()) // case 1 { if (is_key_found) { node.Delete(key_idx); } return; } else if (is_key_found && !node.IsLeave()) // case 2 { const unsigned min_key_num = node.GetMaxKeyNum() / 2; BTreeNode* cur_child = node.GetChild(key_idx); if (cur_child->GetKeyNum() > min_key_num) // case 2a { int prev_key = 0; std::string prev_value; cur_child->GetMaxKeyItem(&prev_key, &prev_value); Delete(*cur_child, prev_key); node.SetItem(key_idx, prev_key, prev_value); return; } BTreeNode* next_child = node.GetChild(key_idx + 1); if (next_child->GetKeyNum() > min_key_num) // case 2b { int next_key = 0; std::string next_value; next_child->GetMinKeyItem(&next_key, &next_value); Delete(*next_child, next_key); node.SetItem(key_idx, next_key, next_value); return; } // case 2c (void) node.MergeChildren(key_idx); Delete(*cur_child, key); } else // case 3 { BTreeNode* child = node.GetChild(key_idx); const unsigned min_key_num = node.GetMaxKeyNum() / 2; if (child->GetKeyNum() <= min_key_num) { BTreeNode* prev_child = NULL; BTreeNode* next_child = NULL; if (key_idx > 0) { prev_child = node.GetChild(key_idx - 1); } if (key_idx < node.GetKeyNum()) { next_child = node.GetChild(key_idx + 1); } // case 3a if (prev_child != NULL && prev_child->GetKeyNum() > min_key_num) { node.RightShiftKey(key_idx - 1); } // case 3a else if (next_child != NULL && next_child->GetKeyNum() > min_key_num) { node.LeftShiftKey(key_idx); } else // case 3b { child = node.MergeChildren(prev_child != NULL ? key_idx - 1: key_idx); } } Delete(*child, key); } } private: BTreeNode* m_root; }; } // algo } // snippet #endif /* _BTREE_H_ */ ",cur_key 10,"#pragma once #include #include #include #include namespace allium { class DrawNodeExtension; struct Point { double x = 0.0; double y = 0.0; Point() = default; Point(double x, double y) : x(x), y(y) {}; Point(cocos2d::CCPoint const& point) : x(static_cast(point.x)), y(static_cast(point.y)) {}; Point operator+(Point const& other) const { return Point{x + other.x, y + other.y}; } Point operator-(Point const& other) const { return Point{x - other.x, y - other.y}; } Point operator*(double const& scalar) const { return Point{x * scalar, y * scalar}; } Point operator/(double const& scalar) const { return Point{x / scalar, y / scalar}; } double dot(Point const& other) const { return x * other.x + y * other.y; } double perpDot(Point const& other) const { return x * other.y - y * other.x; } double getDistanceSq(Point const& other) const { return std::pow(x - other.x, 2) + std::pow(y - other.y, 2); } double getDistance(Point const& other) const { return std::sqrt(this->getDistanceSq(other)); } double angleTo(Point const& other) const { double const angle = std::acos( this->dot(other) / std::sqrt(this->getLengthSq() * other.getLengthSq()) ); return angle * ((this->perpDot(other) < 0) ? -1 : 1); } double getLengthSq() const { return x * x + y * y; } double getLength() const { return std::sqrt(this->getLengthSq()); } operator cocos2d::CCPoint() const { return cocos2d::CCPoint(static_cast(x), static_cast(y)); } std::strong_ordering operator<=>(Point const& other) const { if (x < other.x) return std::strong_ordering::less; if (x > other.x) return std::strong_ordering::greater; if (y < other.y) return std::strong_ordering::less; if (y > other.y) return std::strong_ordering::greater; return std::strong_ordering::equal; } }; struct Col2 { std::array data; Col2(double x = 0.0, double y = 0.0) : data({x, y}) {} Col2(Point const& point) : data({point.x, point.y}) {} operator Point() const { return Point(data[0], data[1]); } }; struct Mat2 { std::array data; Mat2(Col2 const& col1, Col2 const& col2) : data{col1, col2} {}; Mat2(double a11, double a12, double [MASK] , double a22) : data{Col2(a11, [MASK] ), Col2(a12, a22)} {}; static Mat2 fromAngle(double angle) { double cosA = std::cos(angle); double sinA = std::sin(angle); return Mat2{Col2(cosA, sinA), Col2(-sinA, cosA)}; } Col2 operator*(Col2 const& vec) const { return Col2{ data[0].data[0] * vec.data[0] + data[1].data[0] * vec.data[1], data[0].data[1] * vec.data[0] + data[1].data[1] * vec.data[1] }; } Mat2 operator*(Mat2 const& other) const { return Mat2{ Col2{ data[0].data[0] * other.data[0].data[0] + data[1].data[0] * other.data[0].data[1], data[0].data[1] * other.data[0].data[0] + data[1].data[1] * other.data[0].data[1] }, Col2{ data[0].data[0] * other.data[1].data[0] + data[1].data[0] * other.data[1].data[1], data[0].data[1] * other.data[1].data[0] + data[1].data[1] * other.data[1].data[1] } }; } }; struct Object { virtual ~Object() = default; virtual geode::Result addAsGameObject(LevelEditorLayer* editorLayer, int colorID) const = 0; virtual geode::Result<> drawIntoDrawNode(DrawNodeExtension* node, cocos2d::ccColor3B color) const = 0; }; struct Parallelogram : Object { Point p1; Point p2; Point p3; Point p4; Parallelogram() = default; Parallelogram(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}; virtual ~Parallelogram() = default; geode::Result addAsGameObject(LevelEditorLayer* editorLayer, int colorID) const override; geode::Result<> drawIntoDrawNode(DrawNodeExtension* node, cocos2d::ccColor3B color) const override; }; struct Circle : Object { Point center; float radius; Circle() = default; Circle(Point center, float radius) : center(center), radius(radius) {}; virtual ~Circle() = default; geode::Result addAsGameObject(LevelEditorLayer* editorLayer, int colorID) const override; geode::Result<> drawIntoDrawNode(DrawNodeExtension* node, cocos2d::ccColor3B color) const override; }; struct Triangle : Object { Point p1; Point p2; Point p3; Triangle() = default; Triangle(Point p1, Point p2, Point p3) : p1(p1), p2(p2), p3(p3) {}; virtual ~Triangle() = default; geode::Result addAsGameObject(LevelEditorLayer* editorLayer, int colorID) const override; geode::Result<> drawIntoDrawNode(DrawNodeExtension* node, cocos2d::ccColor3B color) const override; }; }",a21 11,"/* * FontTextureManagerAndroid.cpp * WhirlyGlobeLib * * Created by on 6/2/14. * Copyright 2011-2016 mousebird consulting * * 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. * */ #import ""FontTextureManagerAndroid.h"" #import ""LabelInfoAndroid.h"" #import namespace WhirlyKit { static const float BogusFontScale = 1.0; FontTextureManagerAndroid::FontManagerAndroid::FontManagerAndroid(JNIEnv *env,jobject inTypefaceObj) { typefaceObj = env->NewGlobalRef(inTypefaceObj); } FontTextureManagerAndroid::FontManagerAndroid::FontManagerAndroid() : typefaceObj(NULL) { } void FontTextureManagerAndroid::FontManagerAndroid::clearRefs(JNIEnv *savedEnv) { if (typefaceObj) { savedEnv->DeleteGlobalRef(typefaceObj); typefaceObj = NULL; } } FontTextureManagerAndroid::FontManagerAndroid::~FontManagerAndroid() { } FontTextureManagerAndroid::FontTextureManagerAndroid(JNIEnv *env,Scene *scene,jobject inCharRenderObj) : FontTextureManager(scene), charRenderObj(NULL) { // Note: Porting. This will leak charRenderObj = env->NewGlobalRef(inCharRenderObj); jclass [MASK] = env->GetObjectClass(charRenderObj); renderMethodID = env->GetMethodID( [MASK] , ""renderChar"", ""(ILcom/mousebird/maply/LabelInfo;F)Lcom/mousebird/maply/CharRenderer$Glyph;""); jclass glyphClass = env->FindClass(""com/mousebird/maply/CharRenderer$Glyph""); bitmapID = env->GetFieldID(glyphClass,""bitmap"",""Landroid/graphics/Bitmap;""); sizeXID = env->GetFieldID(glyphClass,""sizeX"",""F""); sizeYID = env->GetFieldID(glyphClass,""sizeY"",""F""); glyphSizeXID = env->GetFieldID(glyphClass,""glyphSizeX"",""F""); glyphSizeYID = env->GetFieldID(glyphClass,""glyphSizeY"",""F""); offsetXID = env->GetFieldID(glyphClass,""offsetX"",""F""); offsetYID = env->GetFieldID(glyphClass,""offsetY"",""F""); textureOffsetXID = env->GetFieldID(glyphClass,""textureOffsetX"",""F""); textureOffsetYID = env->GetFieldID(glyphClass,""textureOffsetY"",""F""); env->DeleteLocalRef(glyphClass); env->DeleteLocalRef( [MASK] ); } FontTextureManagerAndroid::~FontTextureManagerAndroid() { for (FontManagerSet::iterator it = fontManagers.begin(); it != fontManagers.end(); ++it) delete *it; fontManagers.clear(); } DrawableString *FontTextureManagerAndroid::addString(JNIEnv *env,const std::vector &codePoints,jobject labelInfoObj,ChangeSet &changes) { LabelInfoClassInfo *classInfo = LabelInfoClassInfo::getClassInfo(); LabelInfoAndroid *labelInfo = (LabelInfoAndroid *)classInfo->getObject(env,labelInfoObj); // Could be more granular if this slows things down pthread_mutex_lock(&lock); // If not initialized, set up texture atlas and such init(); DrawableString *drawString = new DrawableString(); DrawStringRep *drawStringRep = new DrawStringRep(drawString->getId()); // Look for the font manager that manages the typeface/attribute combo we need FontManagerAndroid *fm = findFontManagerForFont(labelInfo->typefaceObj,*labelInfo); JavaIntegerClassInfo *intClassInfo = JavaIntegerClassInfo::getClassInfo(env); // Work through the characters GlyphSet glyphsUsed; float offsetX = 0.0; for (int glyph : codePoints) { // Look for an existing glyph FontManager::GlyphInfo *glyphInfo = fm->findGlyph(glyph); if (!glyphInfo) { // Call the renderer jobject glyphObj = env->CallObjectMethod(charRenderObj,renderMethodID,glyph,labelInfoObj,labelInfo->fontSize); jobject bitmapObj = env->GetObjectField(glyphObj,bitmapID); try { // Got a bitmap, so merge that in with our texture atlas AndroidBitmapInfo info; if (bitmapObj && (AndroidBitmap_getInfo(env, bitmapObj, &info) >= 0)) { Point2f texSize,glyphSize; Point2f offset,textureOffset; // Pull these values from the glyph texSize.x() = env->GetFloatField(glyphObj,sizeXID); texSize.y() = env->GetFloatField(glyphObj,sizeYID); glyphSize.x() = env->GetFloatField(glyphObj,glyphSizeXID); glyphSize.y() = env->GetFloatField(glyphObj,glyphSizeYID); offset.x() = env->GetFloatField(glyphObj,offsetXID); offset.y() = env->GetFloatField(glyphObj,offsetYID); textureOffset.x() = env->GetFloatField(glyphObj,textureOffsetXID); textureOffset.y() = env->GetFloatField(glyphObj,textureOffsetYID); // Create a texture void* bitmapPixels; if (AndroidBitmap_lockPixels(env, bitmapObj, &bitmapPixels) < 0) throw 1; uint32_t* src = (uint32_t*) bitmapPixels; int testVal = src[20]; MutableRawData *rawData = new MutableRawData(bitmapPixels,info.height*info.width*4); Texture tex(""FontTextureManager""); tex.setRawData(rawData,info.width,info.height); // Add it to the texture atlas SubTexture subTex; Point2f realSize(glyphSize.x()+2*textureOffset.x(),glyphSize.y()+2*textureOffset.y()); std::vector texs; texs.push_back(&tex); if (texAtlas->addTexture(texs, -1, &realSize, NULL, subTex, scene->getMemManager(), changes, 0, 0, NULL)) glyphInfo = fm->addGlyph(glyph, subTex, Point2f(glyphSize.x(),glyphSize.y()), Point2f(offset.x(),offset.y()), Point2f(textureOffset.x(),textureOffset.y())); AndroidBitmap_unlockPixels(env, bitmapObj); } } catch (...) { // Just don't add the glyph, for now } env->DeleteLocalRef(glyphObj); } if (glyphInfo) { // Now we make a rectangle that covers the glyph in its texture atlas DrawableString::Rect rect; Point2f offset(offsetX,0.0); float scale = 1.0/BogusFontScale; // Note: was -1,-1 rect.pts[0] = Point2f(glyphInfo->offset.x()*scale-glyphInfo->textureOffset.x()*scale,glyphInfo->offset.y()*scale-glyphInfo->textureOffset.y()*scale)+offset; rect.texCoords[0] = TexCoord(0.0,1.0); // Note: was 2,2 rect.pts[1] = Point2f(glyphInfo->size.x()*scale+2*glyphInfo->textureOffset.x()*scale,glyphInfo->size.y()*scale+2*glyphInfo->textureOffset.y()*scale)+rect.pts[0]; rect.texCoords[1] = TexCoord(1.0,0.0); rect.subTex = glyphInfo->subTex; drawString->glyphPolys.push_back(rect); drawString->mbr.addPoint(rect.pts[0]); drawString->mbr.addPoint(rect.pts[1]); glyphsUsed.insert(glyphInfo->glyph); offsetX += rect.pts[1].x()-rect.pts[0].x(); } } drawStringRep->addGlyphs(fm->getId(),glyphsUsed); fm->addGlyphRefs(glyphsUsed); // If it didn't produce anything, just delete it now if (drawString->glyphPolys.empty()) { delete drawString; delete drawStringRep; drawString = NULL; } // We need to track the glyphs we're using drawStringReps.insert(drawStringRep); pthread_mutex_unlock(&lock); return drawString; } FontTextureManagerAndroid::FontManagerAndroid *FontTextureManagerAndroid::findFontManagerForFont(jobject typefaceObj,const LabelInfo &inLabelInfo) { const LabelInfoAndroid &labelInfo = (LabelInfoAndroid &)inLabelInfo; for (FontManagerSet::iterator it = fontManagers.begin(); it != fontManagers.end(); ++it) { FontManagerAndroid *fm = (FontManagerAndroid *)*it; if (labelInfo.typefaceIsSame(fm->typefaceObj) && fm->pointSize == labelInfo.fontSize && fm->color == labelInfo.textColor && fm->outlineColor == labelInfo.outlineColor && fm->outlineSize == labelInfo.outlineSize) return fm; } // Didn't find it, so create it FontManagerAndroid *fm = new FontManagerAndroid(labelInfo.env,typefaceObj); fm->fontName = """"; fm->color = labelInfo.textColor; fm->pointSize = labelInfo.fontSize; fm->outlineColor = labelInfo.outlineColor; fm->outlineSize = labelInfo.outlineSize; fontManagers.insert(fm); return fm; } } ",charRenderClass 12,"#include ""cardashboard.h"" #include #include #include #include #include CarDashBoard::CarDashBoard(QWidget *parent) : QWidget{parent} { margin = 5; spanAngle = 240;//仪表盘占用角度 startAngle = (180-spanAngle)/2.0 ;//仪表盘开始角度 animation = false; maxValue = 280; minValue = 0; currentValue = 0; value = 0; unit = ""km/h""; backgroundColor= QColor(59,24,37); outArcColor = QColor(0,82,199); outLineColor = QColor(255,255,255); scaleColor = QColor(255,255,255); pointerColor = QColor(255,255,255); circleArcColorStart = QColor(53,179,251,150); circleArcColorEnd = QColor(160,88,127,200); circleBomBigColor = QColor(58,40, 50); circleBomShineColor = QColor(60,68,85,150); circleBomSmallColor = QColor(58,24, 40); textColor = QColor(255,255,255); isForward = false; timer = new QTimer; timer->setInterval(10); connect(timer, &QTimer::timeout,this, &CarDashBoard::updateValue); } int CarDashBoard::getValue() const { return value; } int CarDashBoard::getMinValue() const { return minValue; } int CarDashBoard::getMaxValue() const { return maxValue; } bool CarDashBoard::getAnimation() const { return animation; } int CarDashBoard::getMargin() const { return margin; } int CarDashBoard::getSpanAngle() const { return spanAngle; } QString CarDashBoard::getUnit() const { return unit; } QColor CarDashBoard::getBackgroundColor() const { return backgroundColor; } QColor CarDashBoard::getOutArcColor() const { return outArcColor; } QColor CarDashBoard::getOutLineColor() const { return outLineColor; } QColor CarDashBoard::getScaleColor() const { return scaleColor; } QColor CarDashBoard::getPointerColor() const { return pointerColor; } QColor CarDashBoard::getCircleArcColorStart() const { return circleArcColorStart; } QColor CarDashBoard::getCircleArcColorEnd() const { return circleArcColorEnd; } QColor CarDashBoard::getCircleBomBigColor() const { return circleBomBigColor; } QColor CarDashBoard::getCircleBomShineColor() const { return circleBomShineColor; } QColor CarDashBoard::getCircleBomSmallColor() const { return circleBomSmallColor; } QColor CarDashBoard::getTextColor() const { return textColor; } QSize CarDashBoard::sizeHint() const { return QSize(300,300); } QSize CarDashBoard::minimumSizeHint() const { return QSize(30,30); } void CarDashBoard::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true);//抗锯齿 painter.setPen(Qt::NoPen); center = QPointF(this->width()/2.0,this->height()/2.0); mRadius = qMin(center.y(), center.x())-margin;//最外层圆弧半径 // qDebug()<save(); //设置画刷 painter->setBrush(backgroundColor); painter->drawEllipse(center,mRadius,mRadius); painter->restore(); } void CarDashBoard::drawOutArc(QPainter *painter) { painter->save(); double radius = this->mRadius-0.12 * this->mRadius; QPointF sPoint = QPointF(center.x()-this->mRadius,center.y()-this->mRadius); QPointF ePoint = sPoint + QPointF(2*this->mRadius,2*this->mRadius); QRectF rectangle(sPoint, ePoint); QPainterPath outRing; QPainterPath inRing; outRing.moveTo(center); inRing.moveTo(0,0); outRing.arcTo(rectangle, startAngle, spanAngle); inRing.addEllipse(center, radius,radius); outRing.closeSubpath(); //设置渐变色k QRadialGradient radialGradient(center,mRadius); radialGradient.setColorAt(1,outArcColor); radialGradient.setColorAt(0.9,Qt::transparent); //设置画刷 painter->setBrush(radialGradient); //大圆减小圆 painter->drawPath(outRing.subtracted(inRing)); painter->restore(); } void CarDashBoard::drawOutLine(QPainter *painter) { painter->save(); //double mRadius = qMin(mCenter.y(), mCenter.x())-mMargin;//最外层圆弧半径 QPointF sPoint = QPointF(center.x()-mRadius,center.y()-mRadius); QPointF ePoint = sPoint + QPointF(2*mRadius,2*mRadius); QRectF rectangle(sPoint, ePoint); QPen pen; pen = QPen(outLineColor); pen.setWidth(3); painter->setPen(pen); painter->drawArc(rectangle,startAngle*16, 360*16); painter->restore(); } void CarDashBoard::drawScale(QPainter *painter) { painter->save(); painter->translate(center); //painter->drawLine(0,0,0,100); painter->rotate(90+startAngle); //painter->drawLine(0,0,0,100); double radius = mRadius-0.12 * mRadius; int longStep = (maxValue - minValue)/20; int shortStep = 5 * (longStep) ; //qDebug()<setPen(pen); for(int i = 0; i<= shortStep; i++ ) { QPen pen((i<0.8*shortStep)?(QColor(255,255,255)):QColor(255,0,0)); pen.setWidth(2); painter->setPen(pen); if(i%(5) == 0) { QPoint p1(0,radius); QPoint p2(0,radius-0.06 *radius); painter->drawLine(p1,p2); } else { QPoint p1(0,radius); QPoint p2(0,radius-0.03 *radius); painter->drawLine(p1,p2); } painter->rotate(spanAngle/(shortStep*1.0)); } painter->restore(); } void CarDashBoard::drawScaleNum(QPainter *painter) { painter->save(); painter->translate(center); painter->rotate(90+startAngle+180); double radius = 0.7*(mRadius-0.12 * mRadius); int longStep = (maxValue - minValue)/20; int shortStep = 5 * (longStep) ; double scale = mRadius/250.0; //缩放因子 QFont font; font.setFamily(""Arial""); font.setPointSize(16*scale); font.setBold(true); painter->setFont(font); for(int i = 0; i<= longStep; i++ ) { QPen pen((i<0.8*longStep)?(scaleColor):QColor(255,0,0)); //pen.setWidth(1); painter->setPen(pen); painter->drawText(-20*scale, -(radius-40*scale), 35*scale,-radius,Qt::AlignCenter,QString::number(minValue+i*20)); painter->rotate(spanAngle/(longStep*1.0)); } painter->restore(); } void CarDashBoard::drawPointer(QPainter *painter) { painter->save(); painter->translate(center); double rotate = spanAngle*1.0/(maxValue - minValue)*(currentValue-minValue)+(90+startAngle)+180; double pointerLen = mRadius * 0.25; painter->rotate(rotate); painter->setBrush(pointerColor); /*QPen pen;//测试指针旋转位置是否正确 pen = QPen(QColor(255,255,255)); painter->setPen(pen); painter->drawLine(0,0,0,-200);*/ QPainterPath pointPath; pointPath.moveTo(-2,-mRadius * 0.4); pointPath.lineTo(2,-mRadius * 0.4); pointPath.lineTo(1,-mRadius * 0.4-pointerLen); pointPath.lineTo(-1,-mRadius * 0.4-pointerLen); pointPath.lineTo(-2,-mRadius * 0.4); painter->drawPath(pointPath); painter->restore(); // pointPath.arcTo(-10,0,20,20,180,180); } void CarDashBoard::drawCircle_arc(QPainter *painter) { double radius = mRadius-0.025 * mRadius; double [MASK] = mRadius * 0.4; double currentAngle = spanAngle*1.0/(maxValue - minValue) * (currentValue-minValue); double startAngle = spanAngle-currentAngle; painter->save(); QTransform transform(1,0,0,-1,center.x(),center.y());// painter->setTransform(transform); //painter->translate(mCenter); painter->rotate(180-this->startAngle); /*QPen pen;//测试指针旋转位置是否正确 //pen = QPen(QColor(255,255,255)); painter->setPen(pen);*/ QPainterPath path; QPointF outPointS(radius,0); QPointF outPointE(radius*qCos(currentAngle*M_PI/180.0),-radius*qSin(currentAngle*M_PI/180.0)); QPointF inPointS( [MASK] ,0); QPointF inPointE( [MASK] *qCos(currentAngle*M_PI/180.0),- [MASK] *qSin(currentAngle*M_PI/180.0)); QRectF outRec(-radius,-radius,2*radius,2*radius); QRectF inRec(- [MASK] ,- [MASK] ,2* [MASK] ,2* [MASK] ); double position =(0.8 * spanAngle + (360-spanAngle)/2.0)/(spanAngle + (360-spanAngle)/2.0); QConicalGradient conicalGradient(0,0,-(360-spanAngle)/2.0); conicalGradient.setColorAt(position, circleArcColorEnd); conicalGradient.setColorAt(0, circleArcColorStart); // 使用锥向渐变创建一个画刷,用来填充 QBrush brush(conicalGradient); painter->setBrush(brush); path.moveTo(inPointS); path.lineTo(outPointS); path.arcTo(outRec,0,currentAngle); path.lineTo(inPointE); path.moveTo(inPointS); path.arcTo(inRec,0,currentAngle); //painter->drawEllipse(QPoint(0,0),5,5); /*painter->drawLine(0,0,0,100); painter->drawLine(0,0,200,0);*/ //painter->drawRect(outRec); //painter->drawRect(inRec); painter->drawPath(path); painter->restore(); } void CarDashBoard::drawCircle_bom_big(QPainter *painter) { double radius = mRadius * 0.4; painter->save(); painter->translate(center); painter->setBrush(circleBomBigColor); painter->drawEllipse(QPoint(0,0),radius,radius); painter->restore(); } void CarDashBoard::drawCircle_bom_shine(QPainter *painter) { double radius = mRadius * 0.3; painter->save(); painter->translate(center); QRadialGradient radialGradient(0,0,radius,0,0); radialGradient.setColorAt(0.5,circleBomShineColor); radialGradient.setColorAt(1.0,Qt::transparent); QBrush brush(radialGradient); painter->setBrush(brush); painter->drawEllipse(QPoint(0,0),radius,radius); painter->restore(); } void CarDashBoard::drawCircle_bom_small(QPainter *painter) { double radius = mRadius * 0.25; painter->save(); painter->translate(center); painter->setBrush(circleBomSmallColor); painter->drawEllipse(QPoint(0,0),radius,radius); painter->restore(); } void CarDashBoard::drawUnit(QPainter *painter) { double radius = mRadius * 0.25; painter->save(); painter->translate(center); //qDebug()<setFont(font); QPen pen(textColor); painter->setPen(pen); painter->drawText(-30*scale, 20*scale, 60*scale,60*scale,Qt::AlignCenter, unit); painter->restore(); } void CarDashBoard::drawNum(QPainter *painter) { double radius = mRadius * 0.25; painter->save(); painter->translate(center); double scale = radius/68.75; //缩放因子 QFont font; font.setFamily(""Arial""); font.setPointSize(40*scale); font.setBold(true); painter->setFont(font); QPen pen(textColor); painter->setPen(pen); painter->drawText(-50*scale, -40*scale, 100*scale,60*scale,Qt::AlignCenter,QString::number(currentValue)); painter->restore(); } void CarDashBoard::setValue(int value) { if(value == currentValue) return; if(value < minValue) value = minValue; if(value > maxValue) value = maxValue; if(value > this->value) { isForward = false; } else { isForward = true; } this->value = value; if(timer->isActive()) timer->stop(); if(animation) { timer->start(); } else { currentValue = value; update(); } emit ValueChanged(this->value); } void CarDashBoard::setMinValue(int minValue) { setRangle(minValue, maxValue); } void CarDashBoard::setMaxValue(int maxValue) { setRangle(minValue, maxValue); } void CarDashBoard::setRangle(int minValue, int maxValue) { if(minValue >= maxValue) return; this->minValue = minValue; this->maxValue = maxValue; if(value>maxValue) setValue(maxValue); if(value< minValue) setValue(minValue); emit RangChanged(minValue, maxValue); this->update(); } void CarDashBoard::setAnimation(bool animation) { //qDebug()<animation; if(animation != this->animation) { this->animation = animation ; this->update(); } } void CarDashBoard::setMargin(int margin) { if(this->margin != margin) { this->margin = margin ; this->update(); } } void CarDashBoard::setSpanAngle(int spanAngle) { if(this->spanAngle != spanAngle) { this->spanAngle = spanAngle ; this->startAngle = (180-this->spanAngle)/2.0; this->update(); } } void CarDashBoard::setUnit(const QString unit) { if(this->unit != unit) { this->unit = unit ; this->update(); } } void CarDashBoard::setBackgroundColor(const QColor &backgroundColor) { if(this->backgroundColor != backgroundColor) { this->backgroundColor = backgroundColor ; this->update(); } } void CarDashBoard::setOutArcColor(const QColor &outArcColor) { if(this->outArcColor != outArcColor) { this->outArcColor = outArcColor ; this->update(); } } void CarDashBoard::setOutLineColor(const QColor &outLineColor) { if(this->outLineColor != outLineColor) { this->outLineColor = outLineColor ; this->update(); } } void CarDashBoard::setScaleColor(const QColor &scaleColor) { if(this->scaleColor != scaleColor) { this->scaleColor = scaleColor; this->update(); } } void CarDashBoard::setPointerColor(const QColor &pointerColor) { if(this->pointerColor != pointerColor) { this->pointerColor = pointerColor; this->update(); } } void CarDashBoard::setCircleArcColorStart(const QColor &circleArcColorStart) { if(this->circleArcColorStart != circleArcColorStart) { this->circleArcColorStart = circleArcColorStart; this->update(); } } void CarDashBoard::setCircleArcColorEnd(const QColor &circleArcColorEnd) { if(this->circleArcColorEnd != circleArcColorEnd) { this->circleArcColorEnd = circleArcColorEnd ; this->update(); } } void CarDashBoard::setCircleBomBigColor(const QColor &circleBomBigColor) { if(this->circleBomBigColor != circleBomBigColor) { this->circleBomBigColor = circleBomBigColor; this->update(); } } void CarDashBoard::setCircleBomShineColor(const QColor &circleBomShineColor) { if(this->circleBomShineColor != circleBomShineColor) { this->circleBomShineColor = circleBomShineColor ; this->update(); } } void CarDashBoard::setCircleBomSmallColor(const QColor &circleBomSmallColor) { if(this->circleBomSmallColor != circleBomSmallColor) { this->circleBomSmallColor = circleBomSmallColor; this->update(); } } void CarDashBoard::setTextColor(const QColor &textColor) { if(this->textColor != textColor) { this->textColor = textColor ; this->update(); } } void CarDashBoard::updateValue() { if(isForward) { currentValue -= 1; if(currentValue<=this->value) { currentValue = value; timer->stop(); } } else { currentValue += 1; if(currentValue>=this->value) { currentValue = value; timer->stop(); } } update(); } ",radiusIn 13,"/* File: laponia_battle.cpp Last changed: 14/06/2023 14:00 Purpose: Console-based matrix war game Authors: Usage: HowToCompile: gcc laponia_battle.cpp -o laponia_battle HowToExecute: ./laponia_battle */ #include #include #include #include #include #include int main(int argc, char ** argv) { setlocale(LC_ALL, ""Portuguese""); int i, j, x, [MASK] , linha, coluna, especial = 1, vez = 1, vez2, especial2 = 1, linha2, coluna2, vez3, vitoria = 0, acertar, vez4, soldN, soldS, vez10; char soldado, acao, direcao, tiro, colunaa[2], linhac[2], linhaof[2], colunac[2]; srand(time(NULL)); x = rand() % 100; const int LINHAS = 12; const int COLUNAS = 12; char jogadorN[200]; char jogadorS[200]; printf(""Digite o nome do jogador que representará o Norte:\n""); scanf(""%s"", jogadorN); printf(""Digite o nome do jogador que representará o Sul:\n""); scanf(""%s"", jogadorS); if (x % 2 == 0) { printf(""%s vai jogar primeiro\n"", jogadorN); } else { printf(""%s vai jogar primeiro\n"", jogadorS); } system(""pause\n""); system(""cls""); char tabuleiro[LINHAS] [COLUNAS] ={ {'*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*'}, {'*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*'}, {'*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*'}, {'*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*'}, {'*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*'}, {'*', '~', '~', '~', '~', '~', '~', '~', '~', '~', '~', '*'}, {'*', '~', '~', '~', '~', '~', '~', '~', '~', '~', '~', '*'}, {'*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*'}, {'*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*'}, {'*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*'}, {'*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*'}, {'*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*'} }; printf(""Norte:%s\n"", jogadorN); printf(""Sul:%s\n"", jogadorS); for (i = 0; i < LINHAS; i++) { for (j = 0; j < COLUNAS; j++) { if (tabuleiro[i][j] == '.') printf("" ""); else { printf(""%c "", tabuleiro[i][j]); } } printf(""\n""); } if (x % 2 == 0) { for ( [MASK] = 1; [MASK] <= 9; [MASK] ++) { // Vez do jogador Norte como primeiro jogador. printf(""%s, Escolha o tipo de soldado que você quer agora. Digite o número:\n"", jogadorN); printf(""1 - Soldado que atira em linha reta.\n""); printf(""2 - Soldado que atira em diagonal.\n""); printf(""# - Soldado ESPECIAL, que só pode ser colocado UMA vez, Emerald Splash! seu poder é um ataque poderoso em linha reta, que ultrapassa e destroi tudo que toca.\n""); scanf("" %c"", & soldado); vez2 = 0; while (vez2 == 0) { if (soldado == '1' || soldado == '2' || soldado == '#' && especial == 1) { printf(""%s, digite a posição da sua %d° peça, indique a linha e em seguida a coluna:\n"", jogadorN, [MASK] ); vez = 1; while (vez == 1) { scanf("" %s %s"", linhac, colunac); strcpy(linhaof, linhac); strcpy(colunaa, colunac); linha = atoi(linhaof); coluna = atoi(colunaa); if (tabuleiro[linha][coluna] == '.' && linha <= 4) { tabuleiro[linha][coluna] = soldado; vez = 0; if (soldado == '#') { especial = 0; } } else { printf(""Local inválido, tente novamente:\n""); } } vez2 = 1; } else { printf(""Soldado inválido. Tente novamente:\n""); scanf(""%c"", & soldado); } } system(""cls""); printf(""Norte:%s\n"", jogadorN); printf(""Sul:%s\n"", jogadorS); for (i = 0; i < LINHAS; i++) { for (j = 0; j < COLUNAS; j++) { if (tabuleiro[i][j] == '.') printf("" ""); else { printf(""%c "", tabuleiro[i][j]); } } printf(""\n""); } // Vez do jogador Sul como segundo jogador. printf(""%s, Escolha o tipo de soldado que você quer agora. Digite o número:\n"", jogadorS); printf(""1 - Soldado que atira em linha reta.\n""); printf(""2 - Soldado que atira em diagonal.\n""); printf(""@ - Soldado ESPECIAL, que só pode ser colocado UMA vez, Magicians Red! seu poder é um ataque poderoso em cruz, 3x3 que queima os inimigos na área.\n""); scanf("" %c"", & soldado); vez2 = 0; while (vez2 == 0) { if (soldado == '1' || soldado == '2' || soldado == '@' && especial2 == 1) { printf(""%s, digite a posição da sua %d° peça, indique a linha e em seguida a coluna:\n"", jogadorS, [MASK] ); vez = 1; while (vez == 1) { scanf("" %s %s"", linhac, colunac); strcpy(linhaof, linhac); strcpy(colunaa, colunac); linha = atoi(linhaof); coluna = atoi(colunaa); if (tabuleiro[linha][coluna] == '.' && linha >= 7) { tabuleiro[linha][coluna] = soldado; vez = 0; if (soldado == '@') { especial2 = 0; } } else { printf(""Local inválido, tente novamente:\n""); } } vez2 = 1; } else { printf(""Soldado inválido. Tente novamente:\n""); scanf(""%c"", & soldado); } } system(""cls""); printf(""Norte:%s\n"", jogadorN); printf(""Sul:%s\n"", jogadorS); for (i = 0; i < LINHAS; i++) { for (j = 0; j < COLUNAS; j++) { if (tabuleiro[i][j] == '.') printf("" ""); else { printf(""%c "", tabuleiro[i][j]); } } printf(""\n""); } } } else { for ( [MASK] = 1; [MASK] <= 9; [MASK] ++) { // Vez do jogador Sul como primeiro jogador. printf(""%s, Escolha o tipo de soldado que você quer agora. Digite o número:\n"", jogadorS); printf(""1 - Soldado que atira em linha reta.\n""); printf(""2 - Soldado que atira em diagonal.\n""); printf(""@ - Soldado ESPECIAL, que só pode ser colocado UMA vez, Magicians Red! seu poder é um ataque poderoso em cruz, 3x3 que queima os inimigos na área.\n""); scanf("" %c"", & soldado); vez2 = 0; while (vez2 == 0) { if (soldado == '1' || soldado == '2' || soldado == '@' && especial2 == 1) { printf(""%s, digite a posição da sua %d° peça, indique a linha e em seguida a coluna:\n"", jogadorS, [MASK] ); vez = 1; while (vez == 1) { scanf("" %s %s"", linhac, colunac); strcpy(linhaof, linhac); strcpy(colunaa, colunac); linha = atoi(linhaof); coluna = atoi(colunaa); if (tabuleiro[linha][coluna] == '.' && linha >= 7) { tabuleiro[linha][coluna] = soldado; vez = 0; if (soldado == '@') { especial2 = 0; } } else { printf(""Local inválido, tente novamente:\n""); } } vez2 = 1; } else { printf(""Soldado inválido. Tente novamente:\n""); scanf("" %c"", & soldado); } } system(""cls""); printf(""Norte:%s\n"", jogadorN); printf(""Sul:%s\n"", jogadorS); for (i = 0; i < LINHAS; i++) { for (j = 0; j < COLUNAS; j++) { if (tabuleiro[i][j] == '.') printf("" ""); else { printf(""%c "", tabuleiro[i][j]); } } printf(""\n""); } // Vez do jogador Norte como segundo jogador. printf(""%s, Escolha o tipo de soldado que você quer agora. Digite o número:\n"", jogadorN); printf(""1 - Soldado que atira em linha reta.\n""); printf(""2 - Soldado que atira em diagonal.\n""); printf(""# - Soldado ESPECIAL, que só pode ser colocado UMA vez, Emerald Splash! seu poder é um ataque poderoso em linha reta, que ultrapassa e destroi tudo que toca.\n""); scanf("" %c"", & soldado); vez2 = 0; while (vez2 == 0) { if (soldado == '1' || soldado == '2' || soldado == '#' && especial == 1) { printf(""%s, digite a posição da sua %d° peça, indique a linha e em seguida a coluna:\n"", jogadorN, [MASK] ); vez = 1; while (vez == 1) { scanf("" %s %s"", linhac, colunac); strcpy(linhaof, linhac); strcpy(colunaa, colunac); linha = atoi(linhaof); coluna = atoi(colunaa); if (tabuleiro[linha][coluna] == '.' && linha <= 4) { tabuleiro[linha][coluna] = soldado; vez = 0; if (soldado == '#') { especial = 0; } } else { printf(""Local inválido, tente novamente:\n""); } } vez2 = 1; } else { printf(""Soldado inválido. Tente novamente:\n""); scanf("" %c"", & soldado); } } system(""cls""); printf(""Norte:%s\n"", jogadorN); printf(""Sul:%s\n"", jogadorS); for (i = 0; i < LINHAS; i++) { for (j = 0; j < COLUNAS; j++) { if (tabuleiro[i][j] == '.') printf("" ""); else { printf(""%c "", tabuleiro[i][j]); } } printf(""\n""); } } system(""pause""); system(""cls""); printf(""Norte:%s\n"", jogadorN); printf(""Sul:%s\n"", jogadorS); for (i = 0; i < LINHAS; i++) { for (j = 0; j < COLUNAS; j++) { if (tabuleiro[i][j] == '.') printf("" ""); else { printf(""%c "", tabuleiro[i][j]); } } printf(""\n""); } } //Acabou os posicionamentos de tropa, agora é a movimentacao e ataque. printf(""Todas as tropas foram posicionadas, quem vai vencer?\nO jogador tem 2 opções, movimentar ou atacar.\n""); //Jogardor Norte primeiro vitoria = 0; while (vitoria == 0) { if (x % 2 == 0) { printf(""%s, Selecione o soldado que voce gostaria de interagir. Digite a posição dele, primeiro linha depois coluna:\nOBS:escolha tropas apenas do seu campo.(Norte)"", jogadorN); vez = 0; while (vez == 0) { scanf("" %s %s"", linhac, colunac); strcpy(linhaof, linhac); strcpy(colunaa, colunac); linha = atoi(linhaof); coluna = atoi(colunaa); vez2 = 0; if (tabuleiro[linha][coluna] == '.' || tabuleiro[linha][coluna] == '*' || tabuleiro[linha][coluna] == '~' || linha > 4) { printf(""Local inválido. Tente novamente.\n""); } else { vez2 = 0; while (vez2 == 0) { printf(""O que você gostaria de fazer?\nDigite A para atarcar ou M para movimentar\n ""); scanf("" %c"", & acao); vez = 1; if (acao == 'A' || acao == 'a') { printf(""Voce escolheu atacar.\nOBS: FOGO AMIGO É POSSÍVEL\n""); vez2 = 1; if (tabuleiro[linha][coluna] == '1') { linha2 = linha + 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna] != '*') { if (tabuleiro[linha2][coluna] == '1' || tabuleiro[linha2][coluna] == '2' || tabuleiro[linha2][coluna] == '@') { tabuleiro[linha2][coluna] = '.'; printf(""Soldado abatido. na casa %d %d.\n"", linha2, coluna); acertar = 1; system(""pause""); } else { linha2++; } } } if (tabuleiro[linha][coluna] == '2') { vez4 = 0; while (vez4 == 0) { printf(""O Sniper deverá atirar em qual direção?\n Digite E - para o Sniper atacar na diagonal esquerda.\n Digite D - para o Sniper atirar na diagonal direita.\n""); scanf("" %c"", & tiro); if (tiro == 'D' || tiro == 'd') { vez4 = 1; linha2 = linha + 1; coluna2 = coluna - 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna2] != '*') { if (tabuleiro[linha2][coluna2] == '1' || tabuleiro[linha2][coluna2] == '2' || tabuleiro[linha2][coluna2] == '@') { tabuleiro[linha2][coluna2] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna2); acertar = 1; system(""pause""); } else { linha2++; coluna2--; } } } if (tiro == 'E' || tiro == 'e') { vez4 = 1; linha2 = linha + 1; coluna2 = coluna + 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna2] != '*') { if (tabuleiro[linha2][coluna2] == '1' || tabuleiro[linha2][coluna2] == '2' || tabuleiro[linha2][coluna2] == '@') { tabuleiro[linha2][coluna2] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna2); acertar = 1; system(""pause""); } else { linha2++; coluna2++; } } } if (tiro != 'D' && tiro != 'd' && tiro != 'E' && tiro != 'e') { printf(""Direção inválida.\n""); } } } if (tabuleiro[linha][coluna] == '#') { printf(""EMERALD SPLASH! NINGUEM NUNCA PODERÁ DESVIAR DELE!\n""); linha2 = linha + 1; while (tabuleiro[linha2][coluna] != '*') { if (tabuleiro[linha2][coluna] == '1' || tabuleiro[linha2][coluna] == '2' || tabuleiro[linha2][coluna] == '@') { tabuleiro[linha2][coluna] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna); system(""pause""); } else { linha2++; } } } soldS = 0; for (i = 7; i <= 10; i++) { for (j = 1; j <= 10; j++) { if (tabuleiro[i][j] != '.' && tabuleiro[i][j] != '~' && tabuleiro[i][j] != '*') { soldS++; } } } if (soldS == 0) { vitoria = 1; } } if (acao == 'M' || acao == 'm') { printf(""Você escolheu movimentar.\nOBS: Soldados podem se movimentar apenas uma unidade. O soldado nao pode ocupar rios, montanhas, e outros soldados\n""); vez2 = 1; vez3 = 0; printf(""Digite F - para o soldado ir para frente.\nDigite T - para o soldado ir para trás.\nDigite E - para o soldado ir para esquerda\nDigite D - para o soldado ir para direita.\nDigite V - caso seu soldado esteja cercado, assim passando a vez para o oponente.\n""); scanf("" %c"", & direcao); while (vez3 == 0) { if (direcao == 'F' || direcao == 'f') { if (tabuleiro[linha + 1][coluna] == '.') { tabuleiro[linha + 1][coluna] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'T' || direcao == 't') { if (tabuleiro[linha - 1][coluna] == '.') { tabuleiro[linha - 1][coluna] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'E' || direcao == 'e') { if (tabuleiro[linha][coluna + 1] == '.') { tabuleiro[linha][coluna + 1] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'D' || direcao == 'd') { if (tabuleiro[linha][coluna - 1] == '.') { tabuleiro[linha][coluna - 1] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'V' || direcao == 'v') { vez3 = 1; } } //while } } // Ação M if (acao != 'A' && acao != 'a' && acao != 'M' && acao != 'm') { printf(""Ação inválida.\n""); } } } // While da ação system(""cls""); printf(""Norte:%s\n"", jogadorN); printf(""Sul:%s\n"", jogadorS); for (i = 0; i < LINHAS; i++) { for (j = 0; j < COLUNAS; j++) { if (tabuleiro[i][j] == '.') printf("" ""); else { printf(""%c "", tabuleiro[i][j]); } } printf(""\n""); } // Seleção do soldado // While vez normal // Vez do Sul como 2°jogador if (vitoria == 0) { printf(""%s, Selecione o soldado que voce gostaria de interagir. Digite a posição dele, primeiro linha depois coluna:\nOBS:escolha tropas apenas do seu campo.(Sul)"", jogadorS); vez = 0; vez2 = 0; while (vez == 0) { scanf("" %s %s"", linhac, colunac); strcpy(linhaof, linhac); strcpy(colunaa, colunac); linha = atoi(linhaof); coluna = atoi(colunaa); if (tabuleiro[linha][coluna] == '.' || tabuleiro[linha][coluna] == '*' || tabuleiro[linha][coluna] == '~' || linha < 7) { printf(""Local inválido. Tente novamente.\n""); } else { while (vez2 == 0) { printf(""O que você gostaria de fazer?\nDigite A para atarcar ou M para movimentar\n ""); scanf("" %c"", & acao); vez = 1; if (acao == 'A' || acao == 'a') { printf(""Você escolheu atacar.\n OBS: FOGO AMIGO É POSSÍVEL\n""); vez2 = 1; if (tabuleiro[linha][coluna] == '1') { linha2 = linha - 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna] != '*') { if (tabuleiro[linha2][coluna] == '1' || tabuleiro[linha2][coluna] == '2' || tabuleiro[linha2][coluna] == '#') { tabuleiro[linha2][coluna] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna); acertar = 1; system(""pause""); } else { linha2--; } } } if (tabuleiro[linha][coluna] == '2') { vez4 = 0; while (vez4 == 0) { printf(""O Sniper deverá atirar em qual direção?\n Digite E - para o Sniper atacar na diagonal esquerda.\n Digite D - para o Sniper atirar na diagonal direita.\n""); scanf("" %c"", & tiro); if (tiro == 'D' || tiro == 'd') { vez4 = 1; linha2 = linha - 1; coluna2 = coluna + 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna] != '*') { if (tabuleiro[linha2][coluna2] == '1' || tabuleiro[linha2][coluna2] == '2' || tabuleiro[linha2][coluna2] == '#') { tabuleiro[linha2][coluna2] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna2); acertar = 1; system(""pause""); } else { linha2--; coluna2++; } } } if (tiro == 'E' || tiro == 'e') { vez4 = 1; linha2 = linha - 1; coluna2 = coluna - 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna] != '*') { if (tabuleiro[linha2][coluna2] == '1' || tabuleiro[linha2][coluna2] == '2' || tabuleiro[linha2][coluna2] == '#') { tabuleiro[linha2][coluna2] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna2); acertar = 1; system(""pause""); } else { linha2--; coluna2--; } } if (tiro != 'D' && tiro != 'd' && tiro != 'E' && tiro != 'e') { printf(""Direção inválida.\n""); } } } } if (tabuleiro[linha][coluna] == '@') { vez10 = 1; printf(""CROSSFIRE HURRICANE! NINGUEM NUNCA PODERÁ DESVIAR DELE!\n""); printf(""Selecione uma posição para ser bombardeada, a casa nao pode ser montanha. Linha primeiro em seguida a coluna:\n""); while (vez10 == 1) { scanf("" %s %s"", linhac, colunac); strcpy(linhaof, linhac); strcpy(colunaa, colunac); linha = atoi(linhaof); coluna = atoi(colunaa); if (linha == 0 || coluna == 0 || linha == 11 || coluna == 11) { printf(""Local inválido, tente novamente.\n""); } else { vez10 = 0; if (tabuleiro[linha][coluna] == '1' || tabuleiro[linha][coluna] == '@' || tabuleiro[linha][coluna] == '#' || tabuleiro[linha][coluna] == '2') { tabuleiro[linha][coluna] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha, coluna); system(""pause""); } if (tabuleiro[linha + 1][coluna] == '1' || tabuleiro[linha + 1][coluna] == '@' || tabuleiro[linha + 1][coluna] == '#' || tabuleiro[linha + 1][coluna] == '2') { tabuleiro[linha + 1][coluna] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha + 1, coluna); system(""pause""); } if (tabuleiro[linha - 1][coluna] == '1' || tabuleiro[linha - 1][coluna] == '@' || tabuleiro[linha - 1][coluna] == '#' || tabuleiro[linha - 1][coluna] == '2') { tabuleiro[linha - 1][coluna] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha - 1, coluna); system(""pause""); } if (tabuleiro[linha][coluna + 1] == '1' || tabuleiro[linha][coluna + 1] == '@' || tabuleiro[linha][coluna + 1] == '#' || tabuleiro[linha][coluna + 1] == '2') { tabuleiro[linha][coluna + 1] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha, coluna + 1); system(""pause""); } if (tabuleiro[linha][coluna - 1] == '1' || tabuleiro[linha][coluna - 1] == '@' || tabuleiro[linha][coluna - 1] == '#' || tabuleiro[linha][coluna - 1] == '2') { tabuleiro[linha][coluna - 1] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha, coluna - 1); system(""pause""); } } } } //averiguar a vitoria do jogador SUL soldN = 0; for (i = 1; i <= 4; i++) { for (j = 1; j <= 10; j++) { if (tabuleiro[i][j] != '.' && tabuleiro[i][j] != '~' && tabuleiro[i][j] != '*') { soldN++; } } } if (soldN == 0) { vitoria = 1; } } if (acao == 'M' || acao == 'm') { printf(""Você escolheu movimentar.\nOBS: Soldados podem se movimentar apenas uma unidade. O soldado não pode ocupar rios, montanhas, e outros soldados\n""); vez2 = 1; vez3 = 0; printf(""Digite F - para o soldado ir para frente.\nDigite T - para o soldado ir para trás.\nDigite E - para o soldado ir para esquerda\nDigite D - para o soldado ir para direita.\nDigite V - caso seu soldado esteja cercado, você voltará para o menu de ataque ou movimento.\n""); scanf("" %c"", & direcao); while (vez3 == 0) { if (direcao == 'F' || direcao == 'f') { if (tabuleiro[linha - 1][coluna] == '.') { tabuleiro[linha - 1][coluna] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'T' || direcao == 't') { if (tabuleiro[linha + 1][coluna] == '.') { tabuleiro[linha + 1][coluna] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'E' || direcao == 'e') { if (tabuleiro[linha][coluna - 1] == '.') { tabuleiro[linha][coluna - 1] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'D' || direcao == 'd') { if (tabuleiro[linha][coluna + 1] == '.') { tabuleiro[linha][coluna + 1] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'V' || direcao == 'v') { vez3 = 1; } } //while vez 3 } // Ação M if (acao != 'A' && acao != 'a' && acao != 'M' && acao != 'm') { printf(""Ação inválida.\n""); } } // while da ação system(""cls""); printf(""Norte:%s\n"", jogadorN); printf(""Sul:%s\n"", jogadorS); for (i = 0; i < LINHAS; i++) { for (j = 0; j < COLUNAS; j++) { if (tabuleiro[i][j] == '.') printf("" ""); else { printf(""%c "", tabuleiro[i][j]); } } printf(""\n""); } } // if jogar 1° } //Jogador Sul primeiro } // While vez } else { printf(""%s, Selecione o soldado que voce gostaria de interagir. Digite a posição dele, primeiro linha depois coluna:\nOBS:escolha tropas apenas do seu campo.(Sul)"", jogadorS); vez = 0; vez2 = 0; while (vez == 0) { scanf("" %s %s"", linhac, colunac); strcpy(linhaof, linhac); strcpy(colunaa, colunac); linha = atoi(linhaof); coluna = atoi(colunaa); if (tabuleiro[linha][coluna] == '.' || tabuleiro[linha][coluna] == '*' || tabuleiro[linha][coluna] == '~' || linha < 7) { printf(""Local inválido. Tente novamente.\n""); } else { while (vez2 == 0) { printf(""O que você gostaria de fazer?\nDigite A para atarcar ou M para movimentar\n ""); scanf("" %c"", & acao); vez = 1; if (acao == 'A' || acao == 'a') { printf(""Você escolheu atacar.\n OBS: FOGO AMIGO É POSSÍVEL\n""); vez2 = 1; if (tabuleiro[linha][coluna] == '1') { linha2 = linha - 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna] != '*') { if (tabuleiro[linha2][coluna] == '1' || tabuleiro[linha2][coluna] == '2' || tabuleiro[linha2][coluna] == '#') { tabuleiro[linha2][coluna] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna); acertar = 1; system(""pause""); } else { linha2--; } } } if (tabuleiro[linha][coluna] == '2') { vez4 = 0; while (vez4 == 0) { printf(""O Sniper deverá atirar em qual direção?\n Digite E - para o Sniper atacar na diagonal esquerda.\n Digite D - para o Sniper atirar na diagonal direita.\n""); scanf("" %c"", & tiro); if (tiro == 'D' || tiro == 'd') { vez4 = 1; linha2 = linha - 1; coluna2 = coluna + 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna] != '*') { if (tabuleiro[linha2][coluna2] == '1' || tabuleiro[linha2][coluna2] == '2' || tabuleiro[linha2][coluna2] == '#') { tabuleiro[linha2][coluna2] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna2); acertar = 1; system(""pause""); } else { linha2--; coluna2++; } } } if (tiro == 'E' || tiro == 'e') { vez4 = 1; linha2 = linha - 1; coluna2 = coluna - 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna] != '*') { if (tabuleiro[linha2][coluna2] == '1' || tabuleiro[linha2][coluna2] == '2' || tabuleiro[linha2][coluna2] == '#') { tabuleiro[linha2][coluna2] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna2); acertar = 1; system(""pause""); } else { linha2--; coluna2--; } } if (tiro != 'D' && tiro != 'd' && tiro != 'E' && tiro != 'e') { printf(""Direção inválida.\n""); } } } } if (tabuleiro[linha][coluna] == '@') { vez10 = 1; printf(""CROSSFIRE HURRICANE! NINGUEM NUNCA PODERÁ DESVIAR DELE!\n""); printf(""Selecione uma posição para ser bombardeada, a casa nao pode ser montanha. Linha primeiro em seguida a coluna:\n""); while (vez10 == 1) { scanf("" %s %s"", linhac, colunac); strcpy(linhaof, linhac); strcpy(colunaa, colunac); linha = atoi(linhaof); coluna = atoi(colunaa); if (linha == 0 || coluna == 0 || linha == 11 || coluna == 11) { printf(""Local inválido, tente novamente.\n""); } else { vez10 = 0; if (tabuleiro[linha][coluna] == '1' || tabuleiro[linha][coluna] == '@' || tabuleiro[linha][coluna] == '#' || tabuleiro[linha][coluna] == '2') { tabuleiro[linha][coluna] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha, coluna); system(""pause""); } if (tabuleiro[linha + 1][coluna] == '1' || tabuleiro[linha + 1][coluna] == '@' || tabuleiro[linha + 1][coluna] == '#' || tabuleiro[linha + 1][coluna] == '2') { tabuleiro[linha + 1][coluna] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha + 1, coluna); system(""pause""); } if (tabuleiro[linha - 1][coluna] == '1' || tabuleiro[linha - 1][coluna] == '@' || tabuleiro[linha - 1][coluna] == '#' || tabuleiro[linha - 1][coluna] == '2') { tabuleiro[linha - 1][coluna] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha - 1, coluna); system(""pause""); } if (tabuleiro[linha][coluna + 1] == '1' || tabuleiro[linha][coluna + 1] == '@' || tabuleiro[linha][coluna + 1] == '#' || tabuleiro[linha][coluna + 1] == '2') { tabuleiro[linha][coluna + 1] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha, coluna + 1); system(""pause""); } if (tabuleiro[linha][coluna - 1] == '1' || tabuleiro[linha][coluna - 1] == '@' || tabuleiro[linha][coluna - 1] == '#' || tabuleiro[linha][coluna - 1] == '2') { tabuleiro[linha][coluna - 1] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha, coluna - 1); system(""pause""); } } } } //averiguar a vitoria do jogador SUL soldN = 0; for (i = 1; i <= 4; i++) { for (j = 1; j <= 10; j++) { if (tabuleiro[i][j] != '.' && tabuleiro[i][j] != '~' && tabuleiro[i][j] != '*') { soldN++; } } } if (soldN == 0) { vitoria = 1; } } if (acao == 'M' || acao == 'm') { printf(""Voce escolheu movimentar.\nOBS: Soldados podem se movimentar apenas uma unidade. O soldado nao pode ocupar rios, montanhas, e outros soldados\n""); vez2 = 1; vez3 = 0; printf(""Digite F - para o soldado ir para frente.\nDigite T - para o soldado ir para trás.\nDigite E - para o soldado ir para esquerda\nDigite D - para o soldado ir para direita.\nDigite V - caso seu soldado esteja cercado, você passará a vez para o inimigo.\n""); scanf("" %c"", & direcao); while (vez3 == 0) { if (direcao == 'F' || direcao == 'f') { if (tabuleiro[linha - 1][coluna] == '.') { tabuleiro[linha - 1][coluna] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'T' || direcao == 't') { if (tabuleiro[linha + 1][coluna] == '.') { tabuleiro[linha + 1][coluna] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'E' || direcao == 'e') { if (tabuleiro[linha][coluna - 1] == '.') { tabuleiro[linha][coluna - 1] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'D' || direcao == 'd') { if (tabuleiro[linha][coluna + 1] == '.') { tabuleiro[linha][coluna + 1] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'V' || direcao == 'v') { vez3 = 1; } } //while } // Ação M if (acao != 'A' && acao != 'a' && acao != 'M' && acao != 'm') { printf(""Ação inválida.\n""); } } // While da ação system(""cls""); printf(""Norte:%s\n"", jogadorN); printf(""Sul:%s\n"", jogadorS); for (i = 0; i < LINHAS; i++) { for (j = 0; j < COLUNAS; j++) { if (tabuleiro[i][j] == '.') printf("" ""); else { printf(""%c "", tabuleiro[i][j]); } } printf(""\n""); } } // Seleção do soldado } // While vez normal // Vez do Norte escolher if (vitoria == 0) { printf(""%s, Selecione o soldado que voce gostaria de interagir. Digite a posição dele, primeiro linha depois coluna:\nOBS:escolha tropas apenas do seu campo.(Norte)"", jogadorN); vez = 0; vez2 = 0; while (vez == 0) { scanf("" %s %s"", linhac, colunac); strcpy(linhaof, linhac); strcpy(colunaa, colunac); linha = atoi(linhaof); coluna = atoi(colunaa); if (tabuleiro[linha][coluna] == '.' || tabuleiro[linha][coluna] == '*' || tabuleiro[linha][coluna] == '~' || linha > 4) { printf(""Local inválido. Tente novamente.\n""); } else { while (vez2 == 0) { printf(""O que você gostaria de fazer?\nDigite A para atarcar ou M para movimentar\n ""); scanf("" %c"", & acao); vez = 1; if (acao == 'A' || acao == 'a') { printf(""Voce escolheu atacar.\nOBS: FOGO AMIGO É POSSÍVEL\n""); vez2 = 1; if (tabuleiro[linha][coluna] == '1') { linha2 = linha + 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna] != '*') { if (tabuleiro[linha2][coluna] == '1' || tabuleiro[linha2][coluna] == '2' || tabuleiro[linha2][coluna] == '@') { tabuleiro[linha2][coluna] = '.'; printf(""Soldado abatido. na casa %d %d.\n"", linha2, coluna); acertar = 1; system(""pause""); } else { linha2++; } } } if (tabuleiro[linha][coluna] == '2') { vez4 = 0; while (vez4 == 0) { printf(""O Sniper deverá atirar em qual direção?\n Digite E - para o Sniper atacar na diagonal esquerda.\n Digite D - para o Sniper atirar na diagonal direita.\n""); scanf("" %c"", & tiro); if (tiro == 'D' || tiro == 'd') { vez4 = 1; linha2 = linha + 1; coluna2 = coluna - 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna2] != '*') { if (tabuleiro[linha2][coluna2] == '1' || tabuleiro[linha2][coluna2] == '2' || tabuleiro[linha2][coluna2] == '@') { tabuleiro[linha2][coluna2] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna2); acertar = 1; system(""pause""); } else { linha2++; coluna2--; } } } if (tiro == 'E' || tiro == 'e') { vez4 = 1; linha2 = linha + 1; coluna2 = coluna + 1; acertar = 0; while (acertar == 0 && tabuleiro[linha2][coluna2] != '*') { if (tabuleiro[linha2][coluna2] == '1' || tabuleiro[linha2][coluna2] == '2' || tabuleiro[linha2][coluna2] == '@') { tabuleiro[linha2][coluna2] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna2); acertar = 1; system(""pause""); } else { linha2++; coluna2++; } } } if (tiro != 'D' && tiro != 'd' && tiro != 'E' && tiro != 'e') { printf(""Direção inválida.\n""); } } } if (tabuleiro[linha][coluna] == '#') { printf(""EMERALD SPLASH! NINGUEM NUNCA PODERÁ DESVIAR DELE!\n""); linha2 = linha + 1; while (tabuleiro[linha2][coluna] != '*') { if (tabuleiro[linha2][coluna] == '1' || tabuleiro[linha2][coluna] == '2' || tabuleiro[linha2][coluna] == '@') { tabuleiro[linha2][coluna] = '.'; printf(""Soldado abatido. Na casa %d %d\n"", linha2, coluna); system(""pause""); } else { linha2++; } } } soldS = 0; for (i = 7; i <= 10; i++) { for (j = 1; j <= 10; j++) { if (tabuleiro[i][j] != '.' && tabuleiro[i][j] != '~' && tabuleiro[i][j] != '*') { soldS++; } } } if (soldS == 0) { vitoria = 1; } } if (acao == 'M' || acao == 'm') { printf(""Voce escolheu movimentar.\nOBS: Soldados podem se movimentar apenas uma unidade. O soldado nao pode ocupar rios, montanhas, e outros soldados\n""); vez2 = 1; vez3 = 0; printf(""Digite F - para o soldado ir para frente.\nDigite T - para o soldado ir para trás.\nDigite E - para o soldado ir para esquerda\nDigite D - para o soldado ir para direita.\nDigite V - caso seu soldado esteja cercado, você passará a vez para o inimigo.\n""); scanf("" %c"", & direcao); while (vez3 == 0) { if (direcao == 'F' || direcao == 'f') { if (tabuleiro[linha + 1][coluna] == '.') { tabuleiro[linha + 1][coluna] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'T' || direcao == 't') { if (tabuleiro[linha - 1][coluna] == '.') { tabuleiro[linha - 1][coluna] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'E' || direcao == 'e') { if(tabuleiro[linha][coluna + 1] == '.') { tabuleiro[linha][coluna + 1] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'D' || direcao == 'd') { if (tabuleiro[linha][coluna - 1] == '.') { tabuleiro[linha][coluna - 1] = tabuleiro[linha][coluna]; tabuleiro[linha][coluna] = '.'; vez3 = 1; } else { printf(""Posição inválida. Tente novamente:\n""); scanf("" %c"", & direcao); } } if (direcao == 'V' || direcao == 'v') { vez3 = 1; } } //while } // Ação M if (acao != 'A' && acao != 'a' && acao != 'M' && acao != 'm') { printf(""Ação inválida.\n""); } } // While da ação system(""cls""); printf(""Norte:%s\n"", jogadorN); printf(""Sul:%s\n"", jogadorS); for (i = 0; i < LINHAS; i++) { for (j = 0; j < COLUNAS; j++) { if (tabuleiro[i][j] == '.') printf("" ""); else { printf(""%c "", tabuleiro[i][j]); } } printf(""\n""); } } } } } } if (soldN == 0) { printf(""%s VOCÊ CONQUISTOU A LAPÔNIA!\n"", jogadorS); } else { printf(""%s VOCÊ CONQUISTOU A LAPÔNIA!\n"", jogadorN); } return 0; } ",peca 14,"#include #include #include using namespace std; // Structure to hold student information struct Student { string name; int rollNumber; string address; string phoneNumber; }; // Function to display menu options void displayMenu() { cout << ""========= Student Record Management System ========="" << endl; cout << ""1. Add New Student"" << endl; cout << ""2. Display All Students"" << endl; cout << ""3. Search Student"" << endl; cout << ""4. Update Student Details"" << endl; cout << ""5. Delete Student"" << endl; cout << ""6. Exit"" << endl; cout << ""==================================================="" << endl; cout << ""Enter your choice (1-6): ""; } // Function to add a new student to the records void addStudent() { Student student; cout << ""Enter Student Name: ""; getline(cin.ignore(), student.name); cout << ""Enter Roll Number: ""; cin >> student.rollNumber; cin.ignore(); cout << ""Enter Address: ""; getline(cin, student.address); cout << ""Enter Phone Number: ""; getline(cin, student.phoneNumber); ofstream file(""students.txt"", ios::app); if (file.is_open()) { file << student.name << "","" << student.rollNumber << "","" << student.address << "","" << student.phoneNumber << endl; file.close(); cout << ""Student record added successfully!"" << endl; } else { cout << ""Unable to open file!"" << endl; } } // Function to display all students from the records void displayAllStudents() { ifstream file(""students.txt""); if (file.is_open()) { string line; cout << ""========= All Students ========="" << endl; while (getline(file, line)) { stringstream ss(line); string name, address, phoneNumber; int rollNumber; getline(ss, name, ','); ss >> rollNumber; ss.ignore(); getline(ss, address, ','); getline(ss, phoneNumber); cout << ""Name: "" << name << endl; cout << ""Roll Number: "" << rollNumber << endl; cout << ""Address: "" << address << endl; cout << ""Phone Number: "" << phoneNumber << endl; cout << ""-------------------------------"" << endl; } file.close(); } else { cout << ""Unable to open file!"" << endl; } } // Function to search for a student by roll number void searchStudent() { int rollNumber; cout << ""Enter Roll Number to search: ""; cin >> rollNumber; cin.ignore(); ifstream file(""students.txt""); if (file.is_open()) { string line; bool found = false; while (getline(file, line)) { stringstream ss(line); string name, address, phoneNumber; int fileRollNumber; getline(ss, name, ','); ss >> fileRollNumber; ss.ignore(); getline(ss, address, ','); getline(ss, phoneNumber); if (fileRollNumber == rollNumber) { cout << ""========= Student Details ========="" << endl; cout << ""Name: "" << name << endl; cout << ""Roll Number: "" << rollNumber << endl; cout << ""Address: "" << address << endl; cout << ""Phone Number: "" << phoneNumber << endl; cout << ""-------------------------------"" << endl; found = true; break; } } if (!found) { cout << ""Student not found!"" << endl; } file.close(); } else { cout << ""Unable to open file!"" << endl; } } // Function to update student details void updateStudent() { int rollNumber; cout << ""Enter Roll Number to update: ""; cin >> rollNumber; cin.ignore(); fstream file(""students.txt"", ios::in | ios::out); if (file.is_open()) { string line; bool found = false; while (getline(file, line)) { stringstream ss(line); string name, address, phoneNumber; int fileRollNumber; getline(ss, name, ','); ss >> fileRollNumber; ss.ignore(); getline(ss, address, ','); getline(ss, phoneNumber); if (fileRollNumber == rollNumber) { cout << ""========= Student Details ========="" << endl; cout << ""Name: "" << name << endl; cout << ""Roll Number: "" << rollNumber << endl; cout << ""Address: "" << address << endl; cout << ""Phone Number: "" << phoneNumber << endl; cout << ""-------------------------------"" << endl; // Update student details Student updatedStudent; cout << ""Enter Updated Student Name: ""; getline(cin.ignore(), updatedStudent.name); cout << ""Enter Updated Address: ""; getline(cin, updatedStudent.address); cout << ""Enter Updated Phone Number: ""; getline(cin, updatedStudent.phoneNumber); // Write updated details to the file file.seekp(file.tellg() - line.length() - 1); file << updatedStudent.name << "","" << rollNumber << "","" << updatedStudent.address << "","" << updatedStudent.phoneNumber << endl; cout << ""Student record updated successfully!"" << endl; found = true; break; } } if (!found) { cout << ""Student not found!"" << endl; } file.close(); } else { cout << ""Unable to open file!"" << endl; } } // Function to delete a student from the records void deleteStudent() { int rollNumber; cout << ""Enter Roll Number to delete: ""; cin >> rollNumber; cin.ignore(); ifstream [MASK] (""students.txt""); if ( [MASK] .is_open()) { ofstream outputFile(""temp.txt""); if (outputFile.is_open()) { string line; bool found = false; while (getline( [MASK] , line)) { stringstream ss(line); string name, address, phoneNumber; int fileRollNumber; getline(ss, name, ','); ss >> fileRollNumber; ss.ignore(); getline(ss, address, ','); getline(ss, phoneNumber); if (fileRollNumber == rollNumber) { cout << ""========= Student Details ========="" << endl; cout << ""Name: "" << name << endl; cout << ""Roll Number: "" << rollNumber << endl; cout << ""Address: "" << address << endl; cout << ""Phone Number: "" << phoneNumber << endl; cout << ""-------------------------------"" << endl; cout << ""Student record deleted successfully!"" << endl; found = true; } else { outputFile << line << endl; } } if (!found) { cout << ""Student not found!"" << endl; } outputFile.close(); [MASK] .close(); remove(""students.txt""); rename(""temp.txt"", ""students.txt""); } else { cout << ""Unable to create temporary file!"" << endl; } } else { cout << ""Unable to open file!"" << endl; } } int main() { int choice; do { displayMenu(); cin >> choice; cin.ignore(); switch (choice) { case 1: addStudent(); break; case 2: displayAllStudents(); break; case 3: searchStudent(); break; case 4: updateStudent(); break; case 5: deleteStudent(); break; case 6: cout << ""Thank you for using the Student Record Management System!"" << endl; break; default: cout << ""Invalid choice! Please enter a number between 1 and 6."" << endl; break; } cout << endl; } while (choice != 6); return 0; } ",inputFile 15,"#include ""../../Algorithm.hpp"" int main() { std::vector arr; for (int i = 0; i < 10000; ++i) arr.push_back(i); std::default_random_engine g(time(0)); auto [MASK] = std::chrono::system_clock::now(); auto end = std::chrono::system_clock::now(); std::chrono::duration elapsed_seconds; // std::time_t end_time; //* Bubble Sort Test //* Random Shuffle Arr std::shuffle(arr.begin(), arr.end(), g); std::cout << ""\nBubble Sort :"" << std::endl; alg::array_print(arr); [MASK] = std::chrono::system_clock::now(); alg::bubble_sort(arr); end = std::chrono::system_clock::now(); alg::array_print(arr); elapsed_seconds = end - [MASK] ; std::cout << ""elapsed time: "" << elapsed_seconds.count() << ""s\n""; //* Comb Sort Test //* Random Shuffle Arr std::shuffle(arr.begin(), arr.end(), g); std::cout << ""\nComb Sort :"" << std::endl; alg::array_print(arr); [MASK] = std::chrono::system_clock::now(); alg::comb_sort(arr); end = std::chrono::system_clock::now(); alg::array_print(arr); elapsed_seconds = end - [MASK] ; std::cout << ""elapsed time: "" << elapsed_seconds.count() << ""s\n""; //* Heap Sort Test //* Random Shuffle Arr std::shuffle(arr.begin(), arr.end(), g); std::cout << ""\nHeap Sort :"" << std::endl; alg::array_print(arr); [MASK] = std::chrono::system_clock::now(); alg::heap_sort(arr); end = std::chrono::system_clock::now(); alg::array_print(arr); elapsed_seconds = end - [MASK] ; std::cout << ""elapsed time: "" << elapsed_seconds.count() << ""s\n""; //* Insertion Sort Test //* Random Shuffle Arr std::shuffle(arr.begin(), arr.end(), g); std::cout << ""\nInsertion Sort :"" << std::endl; alg::array_print(arr); [MASK] = std::chrono::system_clock::now(); alg::insertion_sort(arr); end = std::chrono::system_clock::now(); alg::array_print(arr); elapsed_seconds = end - [MASK] ; std::cout << ""elapsed time: "" << elapsed_seconds.count() << ""s\n""; //* Merge Sort Test //* Random Shuffle Arr std::shuffle(arr.begin(), arr.end(), g); std::cout << ""\nMerge Sort :"" << std::endl; alg::array_print(arr); [MASK] = std::chrono::system_clock::now(); alg::merge_sort(arr); end = std::chrono::system_clock::now(); alg::array_print(arr); elapsed_seconds = end - [MASK] ; std::cout << ""elapsed time: "" << elapsed_seconds.count() << ""s\n""; //* Quick Sort Test //* Random Shuffle Arr std::shuffle(arr.begin(), arr.end(), g); std::cout << ""\nQuick Sort :"" << std::endl; alg::array_print(arr); [MASK] = std::chrono::system_clock::now(); alg::quick_sort(arr); end = std::chrono::system_clock::now(); alg::array_print(arr); elapsed_seconds = end - [MASK] ; std::cout << ""elapsed time: "" << elapsed_seconds.count() << ""s\n""; //* Selection Sort Test //* Random Shuffle Arr std::shuffle(arr.begin(), arr.end(), g); std::cout << ""\nSelection Sort :"" << std::endl; alg::array_print(arr); [MASK] = std::chrono::system_clock::now(); alg::selection_sort(arr); end = std::chrono::system_clock::now(); alg::array_print(arr); elapsed_seconds = end - [MASK] ; std::cout << ""elapsed time: "" << elapsed_seconds.count() << ""s\n""; //* Shell Sort Test //* Random Shuffle Arr std::shuffle(arr.begin(), arr.end(), g); std::cout << ""\nShell Sort :"" << std::endl; alg::array_print(arr); [MASK] = std::chrono::system_clock::now(); alg::shell_sort(arr); end = std::chrono::system_clock::now(); alg::array_print(arr); elapsed_seconds = end - [MASK] ; std::cout << ""elapsed time: "" << elapsed_seconds.count() << ""s\n""; return 0; } ",start 16,"#ifndef IPC_SOCKET_CONNECTION_HPP #define IPC_SOCKET_CONNECTION_HPP #include ""../FileDescriptor.hpp"" #include ""../Utils.hpp"" #include ""Address.hpp"" #include ""Type.hpp"" namespace ipc { namespace socket { class Connection { public: explicit Connection(FileDescriptor fd) : fd_(std::move(fd)) {} ssize_t Recv(void *data, std::size_t size) const { return CallSys(::read, int(fd_), data, size); } ssize_t Send(const void *data, std::size_t size) const { return CallSys(::write, int(fd_), data, size); } private: FileDescriptor fd_; }; inline Connection Connect(Type type, const Address& address) { int [MASK] = type == Type::STREAM ? SOCK_STREAM : SOCK_SEQPACKET; FileDescriptor fd(CallSys(::socket, AF_UNIX, [MASK] , 0)); CallSys(::connect, int(fd), (const struct sockaddr *) &address.UnixAddress(), address.Length()); return Connection(std::move(fd)); } } // namespace socket } // namespace ipc #endif // IPC_SOCKET_CONNECTION_HPP",sock_type 17,"#include #include ""movies.hh"" #include ""utilities.hh"" //#define DEBUG #ifdef DEBUG #define dout std::cout #else #define dout 0 && std::cout #endif int main() { std::cout << ""Welcome to the movies!"" << std::endl; std::cout << ""----------------------"" << std::endl; std::cout << ""----------------------"" << std::endl; std::cout << std::endl << std::endl; std::map>>> movies_ds; //Data struct for movies app Utilities utilities; Movies movies; std::string [MASK] = "" ""; #ifdef DEBUG [MASK] = ""test.txt""; #else std::cout << ""Input file: ""; getline(std::cin, [MASK] ); #endif movies_ds = movies.read_saved_movies_data( [MASK] ); movies.print_movies_ds(movies_ds); while(1) { std::string line; std::cout << ""the> ""; getline(std::cin, line); std::vector parts = utilities.split(line, ' '); if(parts.size() == 0) // Allowing empty inputs { continue; } std::string command = parts.at(0); if(command == ""multiplex"") { movies.show_multiplex(movies_ds); } else if(command == ""auditorium"") { if(parts.size()>1) { std::cout<, Jr. 3/31/2020 - MIT license or public domain (see end of file) // Currently supports modes 1, 6 for RGB blocks, and modes 5, 6, 7 for RGBA blocks. #include ""bc7enc.h"" #include #include #include #include #include // Helpers static inline int32_t clampi(int32_t value, int32_t low, int32_t high) { if (value < low) value = low; else if (value > high) value = high; return value; } static inline float clampf(float value, float low, float high) { if (value < low) value = low; else if (value > high) value = high; return value; } static inline float saturate(float value) { return clampf(value, 0, 1.0f); } static inline uint8_t minimumub(uint8_t a, uint8_t b) { return (a < b) ? a : b; } static inline int32_t minimumi(int32_t a, int32_t b) { return (a < b) ? a : b; } static inline uint32_t minimumu(uint32_t a, uint32_t b) { return (a < b) ? a : b; } static inline float minimumf(float a, float b) { return (a < b) ? a : b; } static inline uint8_t maximumub(uint8_t a, uint8_t b) { return (a > b) ? a : b; } static inline uint32_t maximumu(uint32_t a, uint32_t b) { return (a > b) ? a : b; } static inline int32_t maximumi(int32_t a, int32_t b) { return (a > b) ? a : b; } static inline float maximumf(float a, float b) { return (a > b) ? a : b; } static inline int squarei(int i) { return i * i; } static inline float squaref(float i) { return i * i; } template inline T0 lerp(T0 a, T0 b, T1 c) { return a + (b - a) * c; } static inline int32_t iabs32(int32_t v) { uint32_t msk = v >> 31; return (v ^ msk) - msk; } static inline void swapub(uint8_t* a, uint8_t* b) { uint8_t t = *a; *a = *b; *b = t; } static inline void swapu(uint32_t* a, uint32_t* b) { uint32_t t = *a; *a = *b; *b = t; } static inline void swapf(float* a, float* b) { float t = *a; *a = *b; *b = t; } struct vec4F { float m_c[4]; }; static inline color_rgba *color_quad_u8_set_clamped(color_rgba *pRes, int32_t r, int32_t g, int32_t b, int32_t a) { pRes->m_c[0] = (uint8_t)clampi(r, 0, 255); pRes->m_c[1] = (uint8_t)clampi(g, 0, 255); pRes->m_c[2] = (uint8_t)clampi(b, 0, 255); pRes->m_c[3] = (uint8_t)clampi(a, 0, 255); return pRes; } static inline color_rgba *color_quad_u8_set(color_rgba *pRes, int32_t r, int32_t g, int32_t b, int32_t a) { assert((uint32_t)(r | g | b | a) <= 255); pRes->m_c[0] = (uint8_t)r; pRes->m_c[1] = (uint8_t)g; pRes->m_c[2] = (uint8_t)b; pRes->m_c[3] = (uint8_t)a; return pRes; } static inline bool color_quad_u8_notequals(const color_rgba *pLHS, const color_rgba *pRHS) { return (pLHS->m_c[0] != pRHS->m_c[0]) || (pLHS->m_c[1] != pRHS->m_c[1]) || (pLHS->m_c[2] != pRHS->m_c[2]) || (pLHS->m_c[3] != pRHS->m_c[3]); } static inline vec4F *vec4F_set_scalar(vec4F *pV, float x) { pV->m_c[0] = x; pV->m_c[1] = x; pV->m_c[2] = x; pV->m_c[3] = x; return pV; } static inline vec4F *vec4F_set(vec4F *pV, float x, float y, float z, float w) { pV->m_c[0] = x; pV->m_c[1] = y; pV->m_c[2] = z; pV->m_c[3] = w; return pV; } static inline vec4F *vec4F_saturate_in_place(vec4F *pV) { pV->m_c[0] = saturate(pV->m_c[0]); pV->m_c[1] = saturate(pV->m_c[1]); pV->m_c[2] = saturate(pV->m_c[2]); pV->m_c[3] = saturate(pV->m_c[3]); return pV; } static inline vec4F vec4F_saturate(const vec4F *pV) { vec4F res; res.m_c[0] = saturate(pV->m_c[0]); res.m_c[1] = saturate(pV->m_c[1]); res.m_c[2] = saturate(pV->m_c[2]); res.m_c[3] = saturate(pV->m_c[3]); return res; } static inline vec4F vec4F_from_color(const color_rgba *pC) { vec4F res; vec4F_set(&res, pC->m_c[0], pC->m_c[1], pC->m_c[2], pC->m_c[3]); return res; } static inline vec4F vec4F_add(const vec4F *pLHS, const vec4F *pRHS) { vec4F res; vec4F_set(&res, pLHS->m_c[0] + pRHS->m_c[0], pLHS->m_c[1] + pRHS->m_c[1], pLHS->m_c[2] + pRHS->m_c[2], pLHS->m_c[3] + pRHS->m_c[3]); return res; } static inline vec4F vec4F_sub(const vec4F *pLHS, const vec4F *pRHS) { vec4F res; vec4F_set(&res, pLHS->m_c[0] - pRHS->m_c[0], pLHS->m_c[1] - pRHS->m_c[1], pLHS->m_c[2] - pRHS->m_c[2], pLHS->m_c[3] - pRHS->m_c[3]); return res; } static inline float vec4F_dot(const vec4F *pLHS, const vec4F *pRHS) { return pLHS->m_c[0] * pRHS->m_c[0] + pLHS->m_c[1] * pRHS->m_c[1] + pLHS->m_c[2] * pRHS->m_c[2] + pLHS->m_c[3] * pRHS->m_c[3]; } static inline vec4F vec4F_mul(const vec4F *pLHS, float s) { vec4F res; vec4F_set(&res, pLHS->m_c[0] * s, pLHS->m_c[1] * s, pLHS->m_c[2] * s, pLHS->m_c[3] * s); return res; } static inline vec4F *vec4F_normalize_in_place(vec4F *pV) { float s = pV->m_c[0] * pV->m_c[0] + pV->m_c[1] * pV->m_c[1] + pV->m_c[2] * pV->m_c[2] + pV->m_c[3] * pV->m_c[3]; if (s != 0.0f) { s = 1.0f / sqrtf(s); pV->m_c[0] *= s; pV->m_c[1] *= s; pV->m_c[2] *= s; pV->m_c[3] *= s; } return pV; } // Various BC7 tables static const uint32_t g_bc7_weights2[4] = { 0, 21, 43, 64 }; static const uint32_t g_bc7_weights3[8] = { 0, 9, 18, 27, 37, 46, 55, 64 }; static const uint32_t g_bc7_weights4[16] = { 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 }; // Precomputed weight constants used during least fit determination. For each entry in g_bc7_weights[]: w * w, (1.0f - w) * w, (1.0f - w) * (1.0f - w), w static const float g_bc7_weights2x[4 * 4] = { 0.000000f, 0.000000f, 1.000000f, 0.000000f, 0.107666f, 0.220459f, 0.451416f, 0.328125f, 0.451416f, 0.220459f, 0.107666f, 0.671875f, 1.000000f, 0.000000f, 0.000000f, 1.000000f }; static const float g_bc7_weights3x[8 * 4] = { 0.000000f, 0.000000f, 1.000000f, 0.000000f, 0.019775f, 0.120850f, 0.738525f, 0.140625f, 0.079102f, 0.202148f, 0.516602f, 0.281250f, 0.177979f, 0.243896f, 0.334229f, 0.421875f, 0.334229f, 0.243896f, 0.177979f, 0.578125f, 0.516602f, 0.202148f, 0.079102f, 0.718750f, 0.738525f, 0.120850f, 0.019775f, 0.859375f, 1.000000f, 0.000000f, 0.000000f, 1.000000f }; static const float g_bc7_weights4x[16 * 4] = { 0.000000f, 0.000000f, 1.000000f, 0.000000f, 0.003906f, 0.058594f, 0.878906f, 0.062500f, 0.019775f, 0.120850f, 0.738525f, 0.140625f, 0.041260f, 0.161865f, 0.635010f, 0.203125f, 0.070557f, 0.195068f, 0.539307f, 0.265625f, 0.107666f, 0.220459f, 0.451416f, 0.328125f, 0.165039f, 0.241211f, 0.352539f, 0.406250f, 0.219727f, 0.249023f, 0.282227f, 0.468750f, 0.282227f, 0.249023f, 0.219727f, 0.531250f, 0.352539f, 0.241211f, 0.165039f, 0.593750f, 0.451416f, 0.220459f, 0.107666f, 0.671875f, 0.539307f, 0.195068f, 0.070557f, 0.734375f, 0.635010f, 0.161865f, 0.041260f, 0.796875f, 0.738525f, 0.120850f, 0.019775f, 0.859375f, 0.878906f, 0.058594f, 0.003906f, 0.937500f, 1.000000f, 0.000000f, 0.000000f, 1.000000f }; static const uint8_t g_bc7_partition1[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; static const uint8_t g_bc7_partition2[64 * 16] = { 0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1, 0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1, 0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1, 0,0,0,1,0,0,1,1,0,0,1,1,0,1,1,1, 0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,1, 0,0,1,1,0,1,1,1,0,1,1,1,1,1,1,1, 0,0,0,1,0,0,1,1,0,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,1,0,0,1,1,0,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1, 0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,1,0,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1, 0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1, 0,0,0,0,1,0,0,0,1,1,1,0,1,1,1,1, 0,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,0, 0,1,1,1,0,0,1,1,0,0,0,1,0,0,0,0, 0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,1,1,0,0,1,1,1,0, 0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0, 0,1,1,1,0,0,1,1,0,0,1,1,0,0,0,1, 0,0,1,1,0,0,0,1,0,0,0,1,0,0,0,0, 0,0,0,0,1,0,0,0,1,0,0,0,1,1,0,0, 0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0, 0,0,1,1,0,1,1,0,0,1,1,0,1,1,0,0, 0,0,0,1,0,1,1,1,1,1,1,0,1,0,0,0, 0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0, 0,1,1,1,0,0,0,1,1,0,0,0,1,1,1,0, 0,0,1,1,1,0,0,1,1,0,0,1,1,1,0,0, 0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1, 0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1, 0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0, 0,0,1,1,0,0,1,1,1,1,0,0,1,1,0,0, 0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0, 0,1,0,1,0,1,0,1,1,0,1,0,1,0,1,0, 0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1, 0,1,0,1,1,0,1,0,1,0,1,0,0,1,0,1, 0,1,1,1,0,0,1,1,1,1,0,0,1,1,1,0, 0,0,0,1,0,0,1,1,1,1,0,0,1,0,0,0, 0,0,1,1,0,0,1,0,0,1,0,0,1,1,0,0, 0,0,1,1,1,0,1,1,1,1,0,1,1,1,0,0, 0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0, 0,0,1,1,1,1,0,0,1,1,0,0,0,0,1,1, 0,1,1,0,0,1,1,0,1,0,0,1,1,0,0,1, 0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0, 0,1,0,0,1,1,1,0,0,1,0,0,0,0,0,0, 0,0,1,0,0,1,1,1,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,1,0,0,1,1,1,0,0,1,0, 0,0,0,0,0,1,0,0,1,1,1,0,0,1,0,0, 0,1,1,0,1,1,0,0,1,0,0,1,0,0,1,1, 0,0,1,1,0,1,1,0,1,1,0,0,1,0,0,1, 0,1,1,0,0,0,1,1,1,0,0,1,1,1,0,0, 0,0,1,1,1,0,0,1,1,1,0,0,0,1,1,0, 0,1,1,0,1,1,0,0,1,1,0,0,1,0,0,1, 0,1,1,0,0,0,1,1,0,0,1,1,1,0,0,1, 0,1,1,1,1,1,1,0,1,0,0,0,0,0,0,1, 0,0,0,1,1,0,0,0,1,1,1,0,0,1,1,1, 0,0,0,0,1,1,1,1,0,0,1,1,0,0,1,1, 0,0,1,1,0,0,1,1,1,1,1,1,0,0,0,0, 0,0,1,0,0,0,1,0,1,1,1,0,1,1,1,0, 0,1,0,0,0,1,0,0,0,1,1,1,0,1,1,1 }; static const uint8_t g_bc7_partition3[64 * 16] = { 0,0,1,1,0,0,1,1,0,2,2,1,2,2,2,2, 0,0,0,1,0,0,1,1,2,2,1,1,2,2,2,1, 0,0,0,0,2,0,0,1,2,2,1,1,2,2,1,1, 0,2,2,2,0,0,2,2,0,0,1,1,0,1,1,1, 0,0,0,0,0,0,0,0,1,1,2,2,1,1,2,2, 0,0,1,1,0,0,1,1,0,0,2,2,0,0,2,2, 0,0,2,2,0,0,2,2,1,1,1,1,1,1,1,1, 0,0,1,1,0,0,1,1,2,2,1,1,2,2,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2, 0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2, 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2, 0,0,1,2,0,0,1,2,0,0,1,2,0,0,1,2, 0,1,1,2,0,1,1,2,0,1,1,2,0,1,1,2, 0,1,2,2,0,1,2,2,0,1,2,2,0,1,2,2, 0,0,1,1,0,1,1,2,1,1,2,2,1,2,2,2, 0,0,1,1,2,0,0,1,2,2,0,0,2,2,2,0, 0,0,0,1,0,0,1,1,0,1,1,2,1,1,2,2, 0,1,1,1,0,0,1,1,2,0,0,1,2,2,0,0, 0,0,0,0,1,1,2,2,1,1,2,2,1,1,2,2, 0,0,2,2,0,0,2,2,0,0,2,2,1,1,1,1, 0,1,1,1,0,1,1,1,0,2,2,2,0,2,2,2, 0,0,0,1,0,0,0,1,2,2,2,1,2,2,2,1, 0,0,0,0,0,0,1,1,0,1,2,2,0,1,2,2, 0,0,0,0,1,1,0,0,2,2,1,0,2,2,1,0, 0,1,2,2,0,1,2,2,0,0,1,1,0,0,0,0, 0,0,1,2,0,0,1,2,1,1,2,2,2,2,2,2, 0,1,1,0,1,2,2,1,1,2,2,1,0,1,1,0, 0,0,0,0,0,1,1,0,1,2,2,1,1,2,2,1, 0,0,2,2,1,1,0,2,1,1,0,2,0,0,2,2, 0,1,1,0,0,1,1,0,2,0,0,2,2,2,2,2, 0,0,1,1,0,1,2,2,0,1,2,2,0,0,1,1, 0,0,0,0,2,0,0,0,2,2,1,1,2,2,2,1, 0,0,0,0,0,0,0,2,1,1,2,2,1,2,2,2, 0,2,2,2,0,0,2,2,0,0,1,2,0,0,1,1, 0,0,1,1,0,0,1,2,0,0,2,2,0,2,2,2, 0,1,2,0,0,1,2,0,0,1,2,0,0,1,2,0, 0,0,0,0,1,1,1,1,2,2,2,2,0,0,0,0, 0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0, 0,1,2,0,2,0,1,2,1,2,0,1,0,1,2,0, 0,0,1,1,2,2,0,0,1,1,2,2,0,0,1,1, 0,0,1,1,1,1,2,2,2,2,0,0,0,0,1,1, 0,1,0,1,0,1,0,1,2,2,2,2,2,2,2,2, 0,0,0,0,0,0,0,0,2,1,2,1,2,1,2,1, 0,0,2,2,1,1,2,2,0,0,2,2,1,1,2,2, 0,0,2,2,0,0,1,1,0,0,2,2,0,0,1,1, 0,2,2,0,1,2,2,1,0,2,2,0,1,2,2,1, 0,1,0,1,2,2,2,2,2,2,2,2,0,1,0,1, 0,0,0,0,2,1,2,1,2,1,2,1,2,1,2,1, 0,1,0,1,0,1,0,1,0,1,0,1,2,2,2,2, 0,2,2,2,0,1,1,1,0,2,2,2,0,1,1,1, 0,0,0,2,1,1,1,2,0,0,0,2,1,1,1,2, 0,0,0,0,2,1,1,2,2,1,1,2,2,1,1,2, 0,2,2,2,0,1,1,1,0,1,1,1,0,2,2,2, 0,0,0,2,1,1,1,2,1,1,1,2,0,0,0,2, 0,1,1,0,0,1,1,0,0,1,1,0,2,2,2,2, 0,0,0,0,0,0,0,0,2,1,1,2,2,1,1,2, 0,1,1,0,0,1,1,0,2,2,2,2,2,2,2,2, 0,0,2,2,0,0,1,1,0,0,1,1,0,0,2,2, 0,0,2,2,1,1,2,2,1,1,2,2,0,0,2,2, 0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,2, 0,0,0,2,0,0,0,1,0,0,0,2,0,0,0,1, 0,2,2,2,1,2,2,2,0,2,2,2,1,2,2,2, 0,1,0,1,2,2,2,2,2,2,2,2,2,2,2,2, 0,1,1,1,2,0,1,1,2,2,0,1,2,2,2,0, }; static const uint8_t g_bc7_table_anchor_index_third_subset_1[64] = { 3, 3,15,15, 8, 3,15,15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8,15, 3, 3, 6,10, 5, 8, 8, 6, 8, 5,15,15, 8,15, 3, 5, 6,10, 8,15, 15, 3,15, 5,15,15,15,15, 3,15, 5, 5, 5, 8, 5,10, 5,10, 8,13,15,12, 3, 3 }; static const uint8_t g_bc7_table_anchor_index_third_subset_2[64] = { 15, 8, 8, 3,15,15, 3, 8, 15,15,15,15,15,15,15, 8, 15, 8,15, 3,15, 8,15, 8, 3,15, 6,10,15,15,10, 8, 15, 3,15,10,10, 8, 9,10, 6,15, 8,15, 3, 6, 6, 8, 15, 3,15,15,15,15,15,15, 15,15,15,15, 3,15,15, 8 }; static const uint8_t g_bc7_table_anchor_index_second_subset[64] = { 15,15,15,15,15,15,15,15, 15,15,15,15,15,15,15,15, 15, 2, 8, 2, 2, 8, 8,15, 2, 8, 2, 2, 8, 8, 2, 2, 15,15, 6, 8, 2, 8,15,15, 2, 8, 2, 2, 2,15,15, 6, 6, 2, 6, 8,15,15, 2, 2, 15,15,15,15,15, 2, 2,15 }; static const uint8_t g_bc7_num_subsets[8] = { 3, 2, 3, 2, 1, 1, 1, 2 }; static const uint8_t g_bc7_partition_bits[8] = { 4, 6, 6, 6, 0, 0, 0, 6 }; static const uint8_t g_bc7_color_index_bitcount[8] = { 3, 3, 2, 2, 2, 2, 4, 2 }; static int get_bc7_color_index_size(int mode, int index_selection_bit) { return g_bc7_color_index_bitcount[mode] + index_selection_bit; } static uint8_t g_bc7_alpha_index_bitcount[8] = { 0, 0, 0, 0, 3, 2, 4, 2 }; static int get_bc7_alpha_index_size(int mode, int index_selection_bit) { return g_bc7_alpha_index_bitcount[mode] - index_selection_bit; } static const uint8_t g_bc7_mode_has_p_bits[8] = { 1, 1, 0, 1, 0, 0, 1, 1 }; static const uint8_t g_bc7_mode_has_shared_p_bits[8] = { 0, 1, 0, 0, 0, 0, 0, 0 }; static const uint8_t g_bc7_color_precision_table[8] = { 4, 6, 5, 7, 5, 7, 7, 5 }; static const int8_t g_bc7_alpha_precision_table[8] = { 0, 0, 0, 0, 6, 8, 7, 5 }; static bool get_bc7_mode_has_seperate_alpha_selectors(int mode) { return (mode == 4) || (mode == 5); } typedef struct { uint16_t m_error; uint8_t m_lo; uint8_t m_hi; } endpoint_err; static endpoint_err g_bc7_mode_1_optimal_endpoints[256][2]; // [c][pbit] static const uint32_t BC7ENC_MODE_1_OPTIMAL_INDEX = 2; static endpoint_err g_bc7_mode_7_optimal_endpoints[256][2][2]; // [c][pbit][hp][lp] const uint32_t BC7E_MODE_7_OPTIMAL_INDEX = 1; static float g_mode1_rgba_midpoints[64][2]; static float g_mode5_rgba_midpoints[128]; static float g_mode7_rgba_midpoints[32][2]; static uint8_t g_mode6_reduced_quant[2048][2]; static bool g_initialized; // Initialize the lookup table used for optimal single color compression in mode 1/7. Must be called before encoding. void bc7enc_compress_block_init() { if (g_initialized) return; // Mode 7 endpoint midpoints for (uint32_t p = 0; p < 2; p++) { for (uint32_t i = 0; i < 32; i++) { uint32_t vl = ((i << 1) | p) << 2; vl |= (vl >> 6); float lo = vl / 255.0f; uint32_t vh = ((minimumi(31, (i + 1)) << 1) | p) << 2; vh |= (vh >> 6); float hi = vh / 255.0f; //g_mode7_quant_values[i][p] = lo; if (i == 31) g_mode7_rgba_midpoints[i][p] = 1.0f; else g_mode7_rgba_midpoints[i][p] = (lo + hi) / 2.0f; } } // Mode 1 endpoint midpoints for (uint32_t p = 0; p < 2; p++) { for (uint32_t i = 0; i < 64; i++) { uint32_t vl = ((i << 1) | p) << 1; vl |= (vl >> 7); float lo = vl / 255.0f; uint32_t vh = ((minimumi(63, (i + 1)) << 1) | p) << 1; vh |= (vh >> 7); float hi = vh / 255.0f; //g_mode1_quant_values[i][p] = lo; if (i == 63) g_mode1_rgba_midpoints[i][p] = 1.0f; else g_mode1_rgba_midpoints[i][p] = (lo + hi) / 2.0f; } } // Mode 5 endpoint midpoints for (uint32_t i = 0; i < 128; i++) { uint32_t vl = (i << 1); vl |= (vl >> 7); float lo = vl / 255.0f; uint32_t vh = minimumi(127, i + 1) << 1; vh |= (vh >> 7); float hi = vh / 255.0f; if (i == 127) g_mode5_rgba_midpoints[i] = 1.0f; else g_mode5_rgba_midpoints[i] = (lo + hi) / 2.0f; } for (uint32_t p = 0; p < 2; p++) { for (uint32_t i = 0; i < 2048; i++) { float f = i / 2047.0f; float best_err = 1e+9f; int best_index = 0; for (int j = 0; j < 64; j++) { int ik = (j * 127 + 31) / 63; float k = ((ik << 1) + p) / 255.0f; float e = fabsf(k - f); if (e < best_err) { best_err = e; best_index = ik; } } g_mode6_reduced_quant[i][p] = (uint8_t)best_index; } } // p // Mode 1 for (int c = 0; c < 256; c++) { for (uint32_t lp = 0; lp < 2; lp++) { endpoint_err best; best.m_error = (uint16_t)UINT16_MAX; for (uint32_t l = 0; l < 64; l++) { uint32_t low = ((l << 1) | lp) << 1; low |= (low >> 7); for (uint32_t h = 0; h < 64; h++) { uint32_t high = ((h << 1) | lp) << 1; high |= (high >> 7); const int k = (low * (64 - g_bc7_weights3[BC7ENC_MODE_1_OPTIMAL_INDEX]) + high * g_bc7_weights3[BC7ENC_MODE_1_OPTIMAL_INDEX] + 32) >> 6; const int err = (k - c) * (k - c); if (err < best.m_error) { best.m_error = (uint16_t)err; best.m_lo = (uint8_t)l; best.m_hi = (uint8_t)h; } } // h } // l g_bc7_mode_1_optimal_endpoints[c][lp] = best; } // lp } // c // Mode 7: 555.1 2-bit indices for (int c = 0; c < 256; c++) { for (uint32_t hp = 0; hp < 2; hp++) { for (uint32_t lp = 0; lp < 2; lp++) { endpoint_err best; best.m_error = (uint16_t)UINT16_MAX; best.m_lo = 0; best.m_hi = 0; for (uint32_t l = 0; l < 32; l++) { uint32_t low = ((l << 1) | lp) << 2; low |= (low >> 6); for (uint32_t h = 0; h < 32; h++) { uint32_t high = ((h << 1) | hp) << 2; high |= (high >> 6); const int k = (low * (64 - g_bc7_weights2[BC7E_MODE_7_OPTIMAL_INDEX]) + high * g_bc7_weights2[BC7E_MODE_7_OPTIMAL_INDEX] + 32) >> 6; const int err = (k - c) * (k - c); if (err < best.m_error) { best.m_error = (uint16_t)err; best.m_lo = (uint8_t)l; best.m_hi = (uint8_t)h; } } // h } // l g_bc7_mode_7_optimal_endpoints[c][hp][lp] = best; } // hp } // lp } // c g_initialized = true; } static void compute_least_squares_endpoints_rgba(uint32_t N, const uint8_t *pSelectors, const vec4F *pSelector_weights, vec4F *pXl, vec4F *pXh, const color_rgba *pColors) { // Least squares using normal equations: http://www.cs.cornell.edu/~bindel/class/cs3220-s12/notes/lec10.pdf // I did this in matrix form first, expanded out all the ops, then optimized it a bit. float z00 = 0.0f, z01 = 0.0f, z10 = 0.0f, z11 = 0.0f; float q00_r = 0.0f, q10_r = 0.0f, t_r = 0.0f; float q00_g = 0.0f, q10_g = 0.0f, t_g = 0.0f; float q00_b = 0.0f, q10_b = 0.0f, t_b = 0.0f; float q00_a = 0.0f, q10_a = 0.0f, t_a = 0.0f; for (uint32_t i = 0; i < N; i++) { const uint32_t sel = pSelectors[i]; z00 += pSelector_weights[sel].m_c[0]; z10 += pSelector_weights[sel].m_c[1]; z11 += pSelector_weights[sel].m_c[2]; float w = pSelector_weights[sel].m_c[3]; q00_r += w * pColors[i].m_c[0]; t_r += pColors[i].m_c[0]; q00_g += w * pColors[i].m_c[1]; t_g += pColors[i].m_c[1]; q00_b += w * pColors[i].m_c[2]; t_b += pColors[i].m_c[2]; q00_a += w * pColors[i].m_c[3]; t_a += pColors[i].m_c[3]; } q10_r = t_r - q00_r; q10_g = t_g - q00_g; q10_b = t_b - q00_b; q10_a = t_a - q00_a; z01 = z10; float det = z00 * z11 - z01 * z10; if (det != 0.0f) det = 1.0f / det; float iz00, iz01, iz10, iz11; iz00 = z11 * det; iz01 = -z01 * det; iz10 = -z10 * det; iz11 = z00 * det; pXl->m_c[0] = (float)(iz00 * q00_r + iz01 * q10_r); pXh->m_c[0] = (float)(iz10 * q00_r + iz11 * q10_r); pXl->m_c[1] = (float)(iz00 * q00_g + iz01 * q10_g); pXh->m_c[1] = (float)(iz10 * q00_g + iz11 * q10_g); pXl->m_c[2] = (float)(iz00 * q00_b + iz01 * q10_b); pXh->m_c[2] = (float)(iz10 * q00_b + iz11 * q10_b); pXl->m_c[3] = (float)(iz00 * q00_a + iz01 * q10_a); pXh->m_c[3] = (float)(iz10 * q00_a + iz11 * q10_a); for (uint32_t c = 0; c < 4; c++) { if ((pXl->m_c[c] < 0.0f) || (pXh->m_c[c] > 255.0f)) { uint32_t lo_v = UINT32_MAX, hi_v = 0; for (uint32_t i = 0; i < N; i++) { lo_v = minimumu(lo_v, pColors[i].m_c[c]); hi_v = maximumu(hi_v, pColors[i].m_c[c]); } if (lo_v == hi_v) { pXl->m_c[c] = (float)lo_v; pXh->m_c[c] = (float)hi_v; } } } } static void compute_least_squares_endpoints_rgb(uint32_t N, const uint8_t *pSelectors, const vec4F *pSelector_weights, vec4F *pXl, vec4F *pXh, const color_rgba*pColors) { float z00 = 0.0f, z01 = 0.0f, z10 = 0.0f, z11 = 0.0f; float q00_r = 0.0f, q10_r = 0.0f, t_r = 0.0f; float q00_g = 0.0f, q10_g = 0.0f, t_g = 0.0f; float q00_b = 0.0f, q10_b = 0.0f, t_b = 0.0f; for (uint32_t i = 0; i < N; i++) { const uint32_t sel = pSelectors[i]; z00 += pSelector_weights[sel].m_c[0]; z10 += pSelector_weights[sel].m_c[1]; z11 += pSelector_weights[sel].m_c[2]; float w = pSelector_weights[sel].m_c[3]; q00_r += w * pColors[i].m_c[0]; t_r += pColors[i].m_c[0]; q00_g += w * pColors[i].m_c[1]; t_g += pColors[i].m_c[1]; q00_b += w * pColors[i].m_c[2]; t_b += pColors[i].m_c[2]; } q10_r = t_r - q00_r; q10_g = t_g - q00_g; q10_b = t_b - q00_b; z01 = z10; float det = z00 * z11 - z01 * z10; if (det != 0.0f) det = 1.0f / det; float iz00, iz01, iz10, iz11; iz00 = z11 * det; iz01 = -z01 * det; iz10 = -z10 * det; iz11 = z00 * det; pXl->m_c[0] = (float)(iz00 * q00_r + iz01 * q10_r); pXh->m_c[0] = (float)(iz10 * q00_r + iz11 * q10_r); pXl->m_c[1] = (float)(iz00 * q00_g + iz01 * q10_g); pXh->m_c[1] = (float)(iz10 * q00_g + iz11 * q10_g); pXl->m_c[2] = (float)(iz00 * q00_b + iz01 * q10_b); pXh->m_c[2] = (float)(iz10 * q00_b + iz11 * q10_b); pXl->m_c[3] = 255.0f; pXh->m_c[3] = 255.0f; for (uint32_t c = 0; c < 3; c++) { if ((pXl->m_c[c] < 0.0f) || (pXh->m_c[c] > 255.0f)) { uint32_t lo_v = UINT32_MAX, hi_v = 0; for (uint32_t i = 0; i < N; i++) { lo_v = minimumu(lo_v, pColors[i].m_c[c]); hi_v = maximumu(hi_v, pColors[i].m_c[c]); } if (lo_v == hi_v) { pXl->m_c[c] = (float)lo_v; pXh->m_c[c] = (float)hi_v; } } } } static void compute_least_squares_endpoints_a(uint32_t N, const uint8_t* pSelectors, const vec4F* pSelector_weights, float* pXl, float* pXh, const color_rgba *pColors) { // Least squares using normal equations: http://www.cs.cornell.edu/~bindel/class/cs3220-s12/notes/lec10.pdf // I did this in matrix form first, expanded out all the ops, then optimized it a bit. float z00 = 0.0f, z01 = 0.0f, z10 = 0.0f, z11 = 0.0f; float q00_a = 0.0f, q10_a = 0.0f, t_a = 0.0f; for (uint32_t i = 0; i < N; i++) { const uint32_t sel = pSelectors[i]; z00 += pSelector_weights[sel].m_c[0]; z10 += pSelector_weights[sel].m_c[1]; z11 += pSelector_weights[sel].m_c[2]; float w = pSelector_weights[sel].m_c[3]; q00_a += w * pColors[i].m_c[3]; t_a += pColors[i].m_c[3]; } q10_a = t_a - q00_a; z01 = z10; float det = z00 * z11 - z01 * z10; if (det != 0.0f) det = 1.0f / det; float iz00, iz01, iz10, iz11; iz00 = z11 * det; iz01 = -z01 * det; iz10 = -z10 * det; iz11 = z00 * det; *pXl = (float)(iz00 * q00_a + iz01 * q10_a); *pXh = (float)(iz10 * q00_a + iz11 * q10_a); if ((*pXl < 0.0f) || (*pXh > 255.0f)) { uint32_t lo_v = UINT32_MAX, hi_v = 0; for (uint32_t i = 0; i < N; i++) { lo_v = minimumu(lo_v, pColors[i].m_c[3]); hi_v = maximumu(hi_v, pColors[i].m_c[3]); } if (lo_v == hi_v) { *pXl = (float)lo_v; *pXh = (float)hi_v; } } } struct color_cell_compressor_params { uint32_t m_num_pixels; const color_rgba *m_pPixels; uint32_t m_num_selector_weights; const uint32_t *m_pSelector_weights; const vec4F *m_pSelector_weightsx; uint32_t m_comp_bits; uint32_t m_weights[4]; bool m_has_alpha; bool m_has_pbits; bool m_endpoints_share_pbit; bool m_perceptual; }; struct color_cell_compressor_results { uint64_t m_best_overall_err; color_rgba m_low_endpoint; color_rgba m_high_endpoint; uint32_t m_pbits[2]; uint8_t *m_pSelectors; uint8_t *m_pSelectors_temp; }; static inline color_rgba scale_color(const color_rgba *pC, const color_cell_compressor_params *pParams) { color_rgba results; const uint32_t n = pParams->m_comp_bits + (pParams->m_has_pbits ? 1 : 0); assert((n >= 4) && (n <= 8)); for (uint32_t i = 0; i < 4; i++) { uint32_t v = pC->m_c[i] << (8 - n); v |= (v >> n); assert(v <= 255); results.m_c[i] = (uint8_t)(v); } return results; } static inline uint64_t compute_color_distance_rgb(const color_rgba *pE1, const color_rgba *pE2, bool perceptual, const uint32_t weights[4]) { int dr, dg, db; if (perceptual) { const int l1 = pE1->m_c[0] * 109 + pE1->m_c[1] * 366 + pE1->m_c[2] * 37; const int cr1 = ((int)pE1->m_c[0] << 9) - l1; const int cb1 = ((int)pE1->m_c[2] << 9) - l1; const int l2 = pE2->m_c[0] * 109 + pE2->m_c[1] * 366 + pE2->m_c[2] * 37; const int cr2 = ((int)pE2->m_c[0] << 9) - l2; const int cb2 = ((int)pE2->m_c[2] << 9) - l2; dr = (l1 - l2) >> 8; dg = (cr1 - cr2) >> 8; db = (cb1 - cb2) >> 8; } else { dr = (int)pE1->m_c[0] - (int)pE2->m_c[0]; dg = (int)pE1->m_c[1] - (int)pE2->m_c[1]; db = (int)pE1->m_c[2] - (int)pE2->m_c[2]; } return weights[0] * (uint32_t)(dr * dr) + weights[1] * (uint32_t)(dg * dg) + weights[2] * (uint32_t)(db * db); } static inline uint64_t compute_color_distance_rgba(const color_rgba *pE1, const color_rgba *pE2, bool perceptual, const uint32_t weights[4]) { int da = (int)pE1->m_c[3] - (int)pE2->m_c[3]; return compute_color_distance_rgb(pE1, pE2, perceptual, weights) + (weights[3] * (uint32_t)(da * da)); } static uint64_t pack_mode1_to_one_color(const color_cell_compressor_params *pParams, color_cell_compressor_results *pResults, uint32_t r, uint32_t g, uint32_t b, uint8_t *pSelectors) { uint32_t best_err = UINT_MAX; uint32_t best_p = 0; for (uint32_t p = 0; p < 2; p++) { uint32_t err = g_bc7_mode_1_optimal_endpoints[r][p].m_error + g_bc7_mode_1_optimal_endpoints[g][p].m_error + g_bc7_mode_1_optimal_endpoints[b][p].m_error; if (err < best_err) { best_err = err; best_p = p; if (!best_err) break; } } const endpoint_err *pEr = &g_bc7_mode_1_optimal_endpoints[r][best_p]; const endpoint_err *pEg = &g_bc7_mode_1_optimal_endpoints[g][best_p]; const endpoint_err *pEb = &g_bc7_mode_1_optimal_endpoints[b][best_p]; color_quad_u8_set(&pResults->m_low_endpoint, pEr->m_lo, pEg->m_lo, pEb->m_lo, 0); color_quad_u8_set(&pResults->m_high_endpoint, pEr->m_hi, pEg->m_hi, pEb->m_hi, 0); pResults->m_pbits[0] = best_p; pResults->m_pbits[1] = 0; memset(pSelectors, BC7ENC_MODE_1_OPTIMAL_INDEX, pParams->m_num_pixels); color_rgba p; for (uint32_t i = 0; i < 3; i++) { uint32_t low = ((pResults->m_low_endpoint.m_c[i] << 1) | pResults->m_pbits[0]) << 1; low |= (low >> 7); uint32_t high = ((pResults->m_high_endpoint.m_c[i] << 1) | pResults->m_pbits[0]) << 1; high |= (high >> 7); p.m_c[i] = (uint8_t)((low * (64 - g_bc7_weights3[BC7ENC_MODE_1_OPTIMAL_INDEX]) + high * g_bc7_weights3[BC7ENC_MODE_1_OPTIMAL_INDEX] + 32) >> 6); } p.m_c[3] = 255; uint64_t total_err = 0; for (uint32_t i = 0; i < pParams->m_num_pixels; i++) total_err += compute_color_distance_rgb(&p, &pParams->m_pPixels[i], pParams->m_perceptual, pParams->m_weights); pResults->m_best_overall_err = total_err; return total_err; } static uint64_t pack_mode7_to_one_color(const color_cell_compressor_params* pParams, color_cell_compressor_results* pResults, uint32_t r, uint32_t g, uint32_t b, uint32_t a, uint8_t* pSelectors, uint32_t num_pixels, const color_rgba *pPixels) { uint32_t best_err = UINT_MAX; uint32_t best_p = 0; for (uint32_t p = 0; p < 4; p++) { uint32_t hi_p = p >> 1; uint32_t lo_p = p & 1; uint32_t err = g_bc7_mode_7_optimal_endpoints[r][hi_p][lo_p].m_error + g_bc7_mode_7_optimal_endpoints[g][hi_p][lo_p].m_error + g_bc7_mode_7_optimal_endpoints[b][hi_p][lo_p].m_error + g_bc7_mode_7_optimal_endpoints[a][hi_p][lo_p].m_error; if (err < best_err) { best_err = err; best_p = p; if (!best_err) break; } } uint32_t [MASK] = best_p >> 1; uint32_t best_lo_p = best_p & 1; const endpoint_err* pEr = &g_bc7_mode_7_optimal_endpoints[r][ [MASK] ][best_lo_p]; const endpoint_err* pEg = &g_bc7_mode_7_optimal_endpoints[g][ [MASK] ][best_lo_p]; const endpoint_err* pEb = &g_bc7_mode_7_optimal_endpoints[b][ [MASK] ][best_lo_p]; const endpoint_err* pEa = &g_bc7_mode_7_optimal_endpoints[a][ [MASK] ][best_lo_p]; color_quad_u8_set(&pResults->m_low_endpoint, pEr->m_lo, pEg->m_lo, pEb->m_lo, pEa->m_lo); color_quad_u8_set(&pResults->m_high_endpoint, pEr->m_hi, pEg->m_hi, pEb->m_hi, pEa->m_hi); pResults->m_pbits[0] = best_lo_p; pResults->m_pbits[1] = [MASK] ; for (uint32_t i = 0; i < num_pixels; i++) pSelectors[i] = (uint8_t)BC7E_MODE_7_OPTIMAL_INDEX; color_rgba p; for (uint32_t i = 0; i < 4; i++) { uint32_t low = (pResults->m_low_endpoint.m_c[i] << 1) | pResults->m_pbits[0]; uint32_t high = (pResults->m_high_endpoint.m_c[i] << 1) | pResults->m_pbits[1]; low = (low << 2) | (low >> 6); high = (high << 2) | (high >> 6); p.m_c[i] = (uint8_t)((low * (64 - g_bc7_weights2[BC7E_MODE_7_OPTIMAL_INDEX]) + high * g_bc7_weights2[BC7E_MODE_7_OPTIMAL_INDEX] + 32) >> 6); } uint64_t total_err = 0; for (uint32_t i = 0; i < num_pixels; i++) total_err += compute_color_distance_rgba(&p, &pPixels[i], pParams->m_perceptual, pParams->m_weights); pResults->m_best_overall_err = total_err; return total_err; } static uint64_t evaluate_solution(const color_rgba *pLow, const color_rgba *pHigh, const uint32_t pbits[2], const color_cell_compressor_params *pParams, color_cell_compressor_results *pResults, const bc7enc_compress_block_params* pComp_params) { color_rgba quantMinColor = *pLow; color_rgba quantMaxColor = *pHigh; if (pParams->m_has_pbits) { uint32_t minPBit, maxPBit; if (pParams->m_endpoints_share_pbit) maxPBit = minPBit = pbits[0]; else { minPBit = pbits[0]; maxPBit = pbits[1]; } quantMinColor.m_c[0] = (uint8_t)((pLow->m_c[0] << 1) | minPBit); quantMinColor.m_c[1] = (uint8_t)((pLow->m_c[1] << 1) | minPBit); quantMinColor.m_c[2] = (uint8_t)((pLow->m_c[2] << 1) | minPBit); quantMinColor.m_c[3] = (uint8_t)((pLow->m_c[3] << 1) | minPBit); quantMaxColor.m_c[0] = (uint8_t)((pHigh->m_c[0] << 1) | maxPBit); quantMaxColor.m_c[1] = (uint8_t)((pHigh->m_c[1] << 1) | maxPBit); quantMaxColor.m_c[2] = (uint8_t)((pHigh->m_c[2] << 1) | maxPBit); quantMaxColor.m_c[3] = (uint8_t)((pHigh->m_c[3] << 1) | maxPBit); } color_rgba actualMinColor = scale_color(&quantMinColor, pParams); color_rgba actualMaxColor = scale_color(&quantMaxColor, pParams); const uint32_t N = pParams->m_num_selector_weights; color_rgba weightedColors[16]; weightedColors[0] = actualMinColor; weightedColors[N - 1] = actualMaxColor; const uint32_t nc = pParams->m_has_alpha ? 4 : 3; for (uint32_t i = 1; i < (N - 1); i++) for (uint32_t j = 0; j < nc; j++) weightedColors[i].m_c[j] = (uint8_t)((actualMinColor.m_c[j] * (64 - pParams->m_pSelector_weights[i]) + actualMaxColor.m_c[j] * pParams->m_pSelector_weights[i] + 32) >> 6); const int lr = actualMinColor.m_c[0]; const int lg = actualMinColor.m_c[1]; const int lb = actualMinColor.m_c[2]; const int dr = actualMaxColor.m_c[0] - lr; const int dg = actualMaxColor.m_c[1] - lg; const int db = actualMaxColor.m_c[2] - lb; uint64_t total_err = 0; if (pComp_params->m_force_selectors) { for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { const uint32_t best_sel = pComp_params->m_selectors[i]; uint64_t best_err; if (pParams->m_has_alpha) best_err = compute_color_distance_rgba(&weightedColors[best_sel], &pParams->m_pPixels[i], pParams->m_perceptual, pParams->m_weights); else best_err = compute_color_distance_rgb(&weightedColors[best_sel], &pParams->m_pPixels[i], pParams->m_perceptual, pParams->m_weights); total_err += best_err; pResults->m_pSelectors_temp[i] = (uint8_t)best_sel; } } else if (!pParams->m_perceptual) { if (pParams->m_has_alpha) { const int la = actualMinColor.m_c[3]; const int da = actualMaxColor.m_c[3] - la; const float f = N / (float)(squarei(dr) + squarei(dg) + squarei(db) + squarei(da) + .00000125f); for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { const color_rgba *pC = &pParams->m_pPixels[i]; int r = pC->m_c[0]; int g = pC->m_c[1]; int b = pC->m_c[2]; int a = pC->m_c[3]; int best_sel = (int)((float)((r - lr) * dr + (g - lg) * dg + (b - lb) * db + (a - la) * da) * f + .5f); best_sel = clampi(best_sel, 1, N - 1); uint64_t err0 = compute_color_distance_rgba(&weightedColors[best_sel - 1], pC, false, pParams->m_weights); uint64_t err1 = compute_color_distance_rgba(&weightedColors[best_sel], pC, false, pParams->m_weights); if (err1 > err0) { err1 = err0; --best_sel; } total_err += err1; pResults->m_pSelectors_temp[i] = (uint8_t)best_sel; } } else { const float f = N / (float)(squarei(dr) + squarei(dg) + squarei(db) + .00000125f); for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { const color_rgba *pC = &pParams->m_pPixels[i]; int r = pC->m_c[0]; int g = pC->m_c[1]; int b = pC->m_c[2]; int sel = (int)((float)((r - lr) * dr + (g - lg) * dg + (b - lb) * db) * f + .5f); sel = clampi(sel, 1, N - 1); uint64_t err0 = compute_color_distance_rgb(&weightedColors[sel - 1], pC, false, pParams->m_weights); uint64_t err1 = compute_color_distance_rgb(&weightedColors[sel], pC, false, pParams->m_weights); int best_sel = sel; uint64_t best_err = err1; if (err0 < best_err) { best_err = err0; best_sel = sel - 1; } total_err += best_err; pResults->m_pSelectors_temp[i] = (uint8_t)best_sel; } } } else { // TODO: This could be improved. for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { uint64_t best_err = UINT64_MAX; uint32_t best_sel = 0; if (pParams->m_has_alpha) { for (uint32_t j = 0; j < N; j++) { uint64_t err = compute_color_distance_rgba(&weightedColors[j], &pParams->m_pPixels[i], true, pParams->m_weights); if (err < best_err) { best_err = err; best_sel = j; } } } else { for (uint32_t j = 0; j < N; j++) { uint64_t err = compute_color_distance_rgb(&weightedColors[j], &pParams->m_pPixels[i], true, pParams->m_weights); if (err < best_err) { best_err = err; best_sel = j; } } } total_err += best_err; pResults->m_pSelectors_temp[i] = (uint8_t)best_sel; } } if (total_err < pResults->m_best_overall_err) { pResults->m_best_overall_err = total_err; pResults->m_low_endpoint = *pLow; pResults->m_high_endpoint = *pHigh; pResults->m_pbits[0] = pbits[0]; pResults->m_pbits[1] = pbits[1]; memcpy(pResults->m_pSelectors, pResults->m_pSelectors_temp, sizeof(pResults->m_pSelectors[0]) * pParams->m_num_pixels); } return total_err; } static void fixDegenerateEndpoints(uint32_t mode, color_rgba *pTrialMinColor, color_rgba *pTrialMaxColor, const vec4F *pXl, const vec4F *pXh, uint32_t iscale, const bc7enc_compress_block_params* pComp_params) { //if ((mode == 1) || (mode == 7)) //if (mode == 1) if ( (mode == 1) || ((mode == 6) && (pComp_params->m_quant_mode6_endpoints)) ) { // fix degenerate case where the input collapses to a single colorspace voxel, and we loose all freedom (test with grayscale ramps) for (uint32_t i = 0; i < 3; i++) { if (pTrialMinColor->m_c[i] == pTrialMaxColor->m_c[i]) { if (fabs(pXl->m_c[i] - pXh->m_c[i]) > 0.0f) { if (pTrialMinColor->m_c[i] > (iscale >> 1)) { if (pTrialMinColor->m_c[i] > 0) pTrialMinColor->m_c[i]--; else if (pTrialMaxColor->m_c[i] < iscale) pTrialMaxColor->m_c[i]++; } else { if (pTrialMaxColor->m_c[i] < iscale) pTrialMaxColor->m_c[i]++; else if (pTrialMinColor->m_c[i] > 0) pTrialMinColor->m_c[i]--; } } } } } } static uint64_t find_optimal_solution(uint32_t mode, vec4F xl, vec4F xh, const color_cell_compressor_params *pParams, color_cell_compressor_results *pResults, const bc7enc_compress_block_params* pComp_params) { vec4F_saturate_in_place(&xl); vec4F_saturate_in_place(&xh); if (pParams->m_has_pbits) { const int iscalep = (1 << (pParams->m_comp_bits + 1)) - 1; const float scalep = (float)iscalep; const int32_t totalComps = pParams->m_has_alpha ? 4 : 3; uint32_t best_pbits[2]; color_rgba bestMinColor, bestMaxColor; if (!pParams->m_endpoints_share_pbit) { if ((pParams->m_comp_bits == 7) && (pComp_params->m_quant_mode6_endpoints)) { best_pbits[0] = 0; bestMinColor.m_c[0] = g_mode6_reduced_quant[(int)((xl.m_c[0] * 2047.0f) + .5f)][0]; bestMinColor.m_c[1] = g_mode6_reduced_quant[(int)((xl.m_c[1] * 2047.0f) + .5f)][0]; bestMinColor.m_c[2] = g_mode6_reduced_quant[(int)((xl.m_c[2] * 2047.0f) + .5f)][0]; bestMinColor.m_c[3] = g_mode6_reduced_quant[(int)((xl.m_c[3] * 2047.0f) + .5f)][0]; best_pbits[1] = 1; bestMaxColor.m_c[0] = g_mode6_reduced_quant[(int)((xh.m_c[0] * 2047.0f) + .5f)][1]; bestMaxColor.m_c[1] = g_mode6_reduced_quant[(int)((xh.m_c[1] * 2047.0f) + .5f)][1]; bestMaxColor.m_c[2] = g_mode6_reduced_quant[(int)((xh.m_c[2] * 2047.0f) + .5f)][1]; bestMaxColor.m_c[3] = g_mode6_reduced_quant[(int)((xh.m_c[3] * 2047.0f) + .5f)][1]; } else { float best_err0 = 1e+9; float best_err1 = 1e+9; for (int p = 0; p < 2; p++) { color_rgba xMinColor, xMaxColor; // Notes: The pbit controls which quantization intervals are selected. // total_levels=2^(comp_bits+1), where comp_bits=4 for mode 0, etc. // pbit 0: v=(b*2)/(total_levels-1), pbit 1: v=(b*2+1)/(total_levels-1) where b is the component bin from [0,total_levels/2-1] and v is the [0,1] component value // rearranging you get for pbit 0: b=floor(v*(total_levels-1)/2+.5) // rearranging you get for pbit 1: b=floor((v*(total_levels-1)-1)/2+.5) if (pParams->m_comp_bits == 5) { for (uint32_t c = 0; c < 4; c++) { int vl = (int)(xl.m_c[c] * 31.0f); vl += (xl.m_c[c] > g_mode7_rgba_midpoints[vl][p]); xMinColor.m_c[c] = (uint8_t)clampi(vl * 2 + p, p, 63 - 1 + p); int vh = (int)(xh.m_c[c] * 31.0f); vh += (xh.m_c[c] > g_mode7_rgba_midpoints[vh][p]); xMaxColor.m_c[c] = (uint8_t)clampi(vh * 2 + p, p, 63 - 1 + p); } } else { for (uint32_t c = 0; c < 4; c++) { xMinColor.m_c[c] = (uint8_t)(clampi(((int)((xl.m_c[c] * scalep - p) / 2.0f + .5f)) * 2 + p, p, iscalep - 1 + p)); xMaxColor.m_c[c] = (uint8_t)(clampi(((int)((xh.m_c[c] * scalep - p) / 2.0f + .5f)) * 2 + p, p, iscalep - 1 + p)); } } color_rgba scaledLow = scale_color(&xMinColor, pParams); color_rgba scaledHigh = scale_color(&xMaxColor, pParams); float err0 = 0, err1 = 0; for (int i = 0; i < totalComps; i++) { err0 += squaref(scaledLow.m_c[i] - xl.m_c[i] * 255.0f); err1 += squaref(scaledHigh.m_c[i] - xh.m_c[i] * 255.0f); } if (p == 1) { err0 *= pComp_params->m_pbit1_weight; err1 *= pComp_params->m_pbit1_weight; } if (err0 < best_err0) { best_err0 = err0; best_pbits[0] = p; bestMinColor.m_c[0] = xMinColor.m_c[0] >> 1; bestMinColor.m_c[1] = xMinColor.m_c[1] >> 1; bestMinColor.m_c[2] = xMinColor.m_c[2] >> 1; bestMinColor.m_c[3] = xMinColor.m_c[3] >> 1; } if (err1 < best_err1) { best_err1 = err1; best_pbits[1] = p; bestMaxColor.m_c[0] = xMaxColor.m_c[0] >> 1; bestMaxColor.m_c[1] = xMaxColor.m_c[1] >> 1; bestMaxColor.m_c[2] = xMaxColor.m_c[2] >> 1; bestMaxColor.m_c[3] = xMaxColor.m_c[3] >> 1; } } } } else { if ((mode == 1) && (pComp_params->m_bias_mode1_pbits)) { float x = 0.0f; for (uint32_t c = 0; c < 3; c++) x = std::max(std::max(x, xl.m_c[c]), xh.m_c[c]); int p = 0; if (x > (253.0f / 255.0f)) p = 1; color_rgba xMinColor, xMaxColor; for (uint32_t c = 0; c < 4; c++) { int vl = (int)(xl.m_c[c] * 63.0f); vl += (xl.m_c[c] > g_mode1_rgba_midpoints[vl][p]); xMinColor.m_c[c] = (uint8_t)clampi(vl * 2 + p, p, 127 - 1 + p); int vh = (int)(xh.m_c[c] * 63.0f); vh += (xh.m_c[c] > g_mode1_rgba_midpoints[vh][p]); xMaxColor.m_c[c] = (uint8_t)clampi(vh * 2 + p, p, 127 - 1 + p); } best_pbits[0] = p; best_pbits[1] = p; for (uint32_t j = 0; j < 4; j++) { bestMinColor.m_c[j] = xMinColor.m_c[j] >> 1; bestMaxColor.m_c[j] = xMaxColor.m_c[j] >> 1; } } else { // Endpoints share pbits float best_err = 1e+9; for (int p = 0; p < 2; p++) { color_rgba xMinColor, xMaxColor; if (pParams->m_comp_bits == 6) { for (uint32_t c = 0; c < 4; c++) { int vl = (int)(xl.m_c[c] * 63.0f); vl += (xl.m_c[c] > g_mode1_rgba_midpoints[vl][p]); xMinColor.m_c[c] = (uint8_t)clampi(vl * 2 + p, p, 127 - 1 + p); int vh = (int)(xh.m_c[c] * 63.0f); vh += (xh.m_c[c] > g_mode1_rgba_midpoints[vh][p]); xMaxColor.m_c[c] = (uint8_t)clampi(vh * 2 + p, p, 127 - 1 + p); } } else { for (uint32_t c = 0; c < 4; c++) { xMinColor.m_c[c] = (uint8_t)(clampi(((int)((xl.m_c[c] * scalep - p) / 2.0f + .5f)) * 2 + p, p, iscalep - 1 + p)); xMaxColor.m_c[c] = (uint8_t)(clampi(((int)((xh.m_c[c] * scalep - p) / 2.0f + .5f)) * 2 + p, p, iscalep - 1 + p)); } } color_rgba scaledLow = scale_color(&xMinColor, pParams); color_rgba scaledHigh = scale_color(&xMaxColor, pParams); float err = 0; for (int i = 0; i < totalComps; i++) err += squaref((scaledLow.m_c[i] / 255.0f) - xl.m_c[i]) + squaref((scaledHigh.m_c[i] / 255.0f) - xh.m_c[i]); if (p == 1) err *= pComp_params->m_pbit1_weight; if (err < best_err) { best_err = err; best_pbits[0] = p; best_pbits[1] = p; for (uint32_t j = 0; j < 4; j++) { bestMinColor.m_c[j] = xMinColor.m_c[j] >> 1; bestMaxColor.m_c[j] = xMaxColor.m_c[j] >> 1; } } } } } fixDegenerateEndpoints(mode, &bestMinColor, &bestMaxColor, &xl, &xh, iscalep >> 1, pComp_params); if ((pResults->m_best_overall_err == UINT64_MAX) || color_quad_u8_notequals(&bestMinColor, &pResults->m_low_endpoint) || color_quad_u8_notequals(&bestMaxColor, &pResults->m_high_endpoint) || (best_pbits[0] != pResults->m_pbits[0]) || (best_pbits[1] != pResults->m_pbits[1])) evaluate_solution(&bestMinColor, &bestMaxColor, best_pbits, pParams, pResults, pComp_params); } else { const int iscale = (1 << pParams->m_comp_bits) - 1; const float scale = (float)iscale; color_rgba trialMinColor, trialMaxColor; if (pParams->m_comp_bits == 7) { for (uint32_t c = 0; c < 4; c++) { int vl = (int)(xl.m_c[c] * 127.0f); vl += (xl.m_c[c] > g_mode5_rgba_midpoints[vl]); trialMinColor.m_c[c] = (uint8_t)clampi(vl, 0, 127); int vh = (int)(xh.m_c[c] * 127.0f); vh += (xh.m_c[c] > g_mode5_rgba_midpoints[vh]); trialMaxColor.m_c[c] = (uint8_t)clampi(vh, 0, 127); } } else { color_quad_u8_set_clamped(&trialMinColor, (int)(xl.m_c[0] * scale + .5f), (int)(xl.m_c[1] * scale + .5f), (int)(xl.m_c[2] * scale + .5f), (int)(xl.m_c[3] * scale + .5f)); color_quad_u8_set_clamped(&trialMaxColor, (int)(xh.m_c[0] * scale + .5f), (int)(xh.m_c[1] * scale + .5f), (int)(xh.m_c[2] * scale + .5f), (int)(xh.m_c[3] * scale + .5f)); } fixDegenerateEndpoints(mode, &trialMinColor, &trialMaxColor, &xl, &xh, iscale, pComp_params); if ((pResults->m_best_overall_err == UINT64_MAX) || color_quad_u8_notequals(&trialMinColor, &pResults->m_low_endpoint) || color_quad_u8_notequals(&trialMaxColor, &pResults->m_high_endpoint)) evaluate_solution(&trialMinColor, &trialMaxColor, pResults->m_pbits, pParams, pResults, pComp_params); } return pResults->m_best_overall_err; } static uint64_t color_cell_compression(uint32_t mode, const color_cell_compressor_params *pParams, color_cell_compressor_results *pResults, const bc7enc_compress_block_params *pComp_params) { assert((mode == 6) || (mode == 7) || (!pParams->m_has_alpha)); pResults->m_best_overall_err = UINT64_MAX; // If the partition's colors are all the same in mode 1, then just pack them as a single color. if (mode == 1) { const uint32_t cr = pParams->m_pPixels[0].m_c[0], cg = pParams->m_pPixels[0].m_c[1], cb = pParams->m_pPixels[0].m_c[2]; bool allSame = true; for (uint32_t i = 1; i < pParams->m_num_pixels; i++) { if ((cr != pParams->m_pPixels[i].m_c[0]) || (cg != pParams->m_pPixels[i].m_c[1]) || (cb != pParams->m_pPixels[i].m_c[2])) { allSame = false; break; } } if (allSame) return pack_mode1_to_one_color(pParams, pResults, cr, cg, cb, pResults->m_pSelectors); } else if (mode == 7) { const uint32_t cr = pParams->m_pPixels[0].m_c[0], cg = pParams->m_pPixels[0].m_c[1], cb = pParams->m_pPixels[0].m_c[2], ca = pParams->m_pPixels[0].m_c[3]; bool allSame = true; for (uint32_t i = 1; i < pParams->m_num_pixels; i++) { if ((cr != pParams->m_pPixels[i].m_c[0]) || (cg != pParams->m_pPixels[i].m_c[1]) || (cb != pParams->m_pPixels[i].m_c[2]) || (ca != pParams->m_pPixels[i].m_c[3])) { allSame = false; break; } } if (allSame) return pack_mode7_to_one_color(pParams, pResults, cr, cg, cb, ca, pResults->m_pSelectors, pParams->m_num_pixels, pParams->m_pPixels); } // Compute partition's mean color and principle axis. vec4F meanColor, axis; vec4F_set_scalar(&meanColor, 0.0f); for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { vec4F color = vec4F_from_color(&pParams->m_pPixels[i]); meanColor = vec4F_add(&meanColor, &color); } vec4F meanColorScaled = vec4F_mul(&meanColor, 1.0f / (float)(pParams->m_num_pixels)); meanColor = vec4F_mul(&meanColor, 1.0f / (float)(pParams->m_num_pixels * 255.0f)); vec4F_saturate_in_place(&meanColor); if (pParams->m_has_alpha) { // Use incremental PCA for RGBA PCA, because it's simple. vec4F_set_scalar(&axis, 0.0f); for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { vec4F color = vec4F_from_color(&pParams->m_pPixels[i]); color = vec4F_sub(&color, &meanColorScaled); vec4F a = vec4F_mul(&color, color.m_c[0]); vec4F b = vec4F_mul(&color, color.m_c[1]); vec4F c = vec4F_mul(&color, color.m_c[2]); vec4F d = vec4F_mul(&color, color.m_c[3]); vec4F n = i ? axis : color; vec4F_normalize_in_place(&n); axis.m_c[0] += vec4F_dot(&a, &n); axis.m_c[1] += vec4F_dot(&b, &n); axis.m_c[2] += vec4F_dot(&c, &n); axis.m_c[3] += vec4F_dot(&d, &n); } vec4F_normalize_in_place(&axis); } else { // Use covar technique for RGB PCA, because it doesn't require per-pixel normalization. float cov[6] = { 0, 0, 0, 0, 0, 0 }; for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { const color_rgba *pV = &pParams->m_pPixels[i]; float r = pV->m_c[0] - meanColorScaled.m_c[0]; float g = pV->m_c[1] - meanColorScaled.m_c[1]; float b = pV->m_c[2] - meanColorScaled.m_c[2]; cov[0] += r*r; cov[1] += r*g; cov[2] += r*b; cov[3] += g*g; cov[4] += g*b; cov[5] += b*b; } float vfr = .9f, vfg = 1.0f, vfb = .7f; for (uint32_t iter = 0; iter < 3; iter++) { float r = vfr*cov[0] + vfg*cov[1] + vfb*cov[2]; float g = vfr*cov[1] + vfg*cov[3] + vfb*cov[4]; float b = vfr*cov[2] + vfg*cov[4] + vfb*cov[5]; float m = maximumf(maximumf(fabsf(r), fabsf(g)), fabsf(b)); if (m > 1e-10f) { m = 1.0f / m; r *= m; g *= m; b *= m; } vfr = r; vfg = g; vfb = b; } float len = vfr*vfr + vfg*vfg + vfb*vfb; if (len < 1e-10f) vec4F_set_scalar(&axis, 0.0f); else { len = 1.0f / sqrtf(len); vfr *= len; vfg *= len; vfb *= len; vec4F_set(&axis, vfr, vfg, vfb, 0); } } // TODO: Try picking the 2 colors with the largest projection onto the axis, instead of computing new colors along the axis. if (vec4F_dot(&axis, &axis) < .5f) { if (pParams->m_perceptual) vec4F_set(&axis, .213f, .715f, .072f, pParams->m_has_alpha ? .715f : 0); else vec4F_set(&axis, 1.0f, 1.0f, 1.0f, pParams->m_has_alpha ? 1.0f : 0); vec4F_normalize_in_place(&axis); } float l = 1e+9f, h = -1e+9f; for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { vec4F color = vec4F_from_color(&pParams->m_pPixels[i]); vec4F q = vec4F_sub(&color, &meanColorScaled); float d = vec4F_dot(&q, &axis); l = minimumf(l, d); h = maximumf(h, d); } l *= (1.0f / 255.0f); h *= (1.0f / 255.0f); vec4F b0 = vec4F_mul(&axis, l); vec4F b1 = vec4F_mul(&axis, h); vec4F c0 = vec4F_add(&meanColor, &b0); vec4F c1 = vec4F_add(&meanColor, &b1); vec4F minColor = vec4F_saturate(&c0); vec4F maxColor = vec4F_saturate(&c1); vec4F whiteVec; vec4F_set_scalar(&whiteVec, 1.0f); if (vec4F_dot(&minColor, &whiteVec) > vec4F_dot(&maxColor, &whiteVec)) { #if 0 // Don't compile correctly with VC 2019 in release. vec4F temp = minColor; minColor = maxColor; maxColor = temp; #else float a = minColor.m_c[0], b = minColor.m_c[1], c = minColor.m_c[2], d = minColor.m_c[3]; minColor.m_c[0] = maxColor.m_c[0]; minColor.m_c[1] = maxColor.m_c[1]; minColor.m_c[2] = maxColor.m_c[2]; minColor.m_c[3] = maxColor.m_c[3]; maxColor.m_c[0] = a; maxColor.m_c[1] = b; maxColor.m_c[2] = c; maxColor.m_c[3] = d; #endif } // First find a solution using the block's PCA. if (!find_optimal_solution(mode, minColor, maxColor, pParams, pResults, pComp_params)) return 0; if (pComp_params->m_try_least_squares) { // Now try to refine the solution using least squares by computing the optimal endpoints from the current selectors. vec4F xl, xh; vec4F_set_scalar(&xl, 0.0f); vec4F_set_scalar(&xh, 0.0f); if (pParams->m_has_alpha) compute_least_squares_endpoints_rgba(pParams->m_num_pixels, pResults->m_pSelectors, pParams->m_pSelector_weightsx, &xl, &xh, pParams->m_pPixels); else compute_least_squares_endpoints_rgb(pParams->m_num_pixels, pResults->m_pSelectors, pParams->m_pSelector_weightsx, &xl, &xh, pParams->m_pPixels); xl = vec4F_mul(&xl, (1.0f / 255.0f)); xh = vec4F_mul(&xh, (1.0f / 255.0f)); if (!find_optimal_solution(mode, xl, xh, pParams, pResults, pComp_params)) return 0; } if (pComp_params->m_uber_level > 0) { // In uber level 1, try varying the selectors a little, somewhat like cluster fit would. First try incrementing the minimum selectors, // then try decrementing the selectrors, then try both. uint8_t selectors_temp[16], selectors_temp1[16]; memcpy(selectors_temp, pResults->m_pSelectors, pParams->m_num_pixels); const int max_selector = pParams->m_num_selector_weights - 1; uint32_t min_sel = 16; uint32_t max_sel = 0; for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { uint32_t sel = selectors_temp[i]; min_sel = minimumu(min_sel, sel); max_sel = maximumu(max_sel, sel); } for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { uint32_t sel = selectors_temp[i]; if ((sel == min_sel) && (sel < (pParams->m_num_selector_weights - 1))) sel++; selectors_temp1[i] = (uint8_t)sel; } vec4F xl, xh; vec4F_set_scalar(&xl, 0.0f); vec4F_set_scalar(&xh, 0.0f); if (pParams->m_has_alpha) compute_least_squares_endpoints_rgba(pParams->m_num_pixels, selectors_temp1, pParams->m_pSelector_weightsx, &xl, &xh, pParams->m_pPixels); else compute_least_squares_endpoints_rgb(pParams->m_num_pixels, selectors_temp1, pParams->m_pSelector_weightsx, &xl, &xh, pParams->m_pPixels); xl = vec4F_mul(&xl, (1.0f / 255.0f)); xh = vec4F_mul(&xh, (1.0f / 255.0f)); if (!find_optimal_solution(mode, xl, xh, pParams, pResults, pComp_params)) return 0; for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { uint32_t sel = selectors_temp[i]; if ((sel == max_sel) && (sel > 0)) sel--; selectors_temp1[i] = (uint8_t)sel; } if (pParams->m_has_alpha) compute_least_squares_endpoints_rgba(pParams->m_num_pixels, selectors_temp1, pParams->m_pSelector_weightsx, &xl, &xh, pParams->m_pPixels); else compute_least_squares_endpoints_rgb(pParams->m_num_pixels, selectors_temp1, pParams->m_pSelector_weightsx, &xl, &xh, pParams->m_pPixels); xl = vec4F_mul(&xl, (1.0f / 255.0f)); xh = vec4F_mul(&xh, (1.0f / 255.0f)); if (!find_optimal_solution(mode, xl, xh, pParams, pResults, pComp_params)) return 0; for (uint32_t i = 0; i < pParams->m_num_pixels; i++) { uint32_t sel = selectors_temp[i]; if ((sel == min_sel) && (sel < (pParams->m_num_selector_weights - 1))) sel++; else if ((sel == max_sel) && (sel > 0)) sel--; selectors_temp1[i] = (uint8_t)sel; } if (pParams->m_has_alpha) compute_least_squares_endpoints_rgba(pParams->m_num_pixels, selectors_temp1, pParams->m_pSelector_weightsx, &xl, &xh, pParams->m_pPixels); else compute_least_squares_endpoints_rgb(pParams->m_num_pixels, selectors_temp1, pParams->m_pSelector_weightsx, &xl, &xh, pParams->m_pPixels); xl = vec4F_mul(&xl, (1.0f / 255.0f)); xh = vec4F_mul(&xh, (1.0f / 255.0f)); if (!find_optimal_solution(mode, xl, xh, pParams, pResults, pComp_params)) return 0; // In uber levels 2+, try taking more advantage of endpoint extrapolation by scaling the selectors in one direction or another. const uint32_t uber_err_thresh = (pParams->m_num_pixels * 56) >> 4; if ((pComp_params->m_uber_level >= 2) && (pResults->m_best_overall_err > uber_err_thresh)) { const int Q = (pComp_params->m_uber_level >= 4) ? (pComp_params->m_uber_level - 2) : 1; for (int ly = -Q; ly <= 1; ly++) { for (int hy = max_selector - 1; hy <= (max_selector + Q); hy++) { if ((ly == 0) && (hy == max_selector)) continue; for (uint32_t i = 0; i < pParams->m_num_pixels; i++) selectors_temp1[i] = (uint8_t)clampf(floorf((float)max_selector * ((float)selectors_temp[i] - (float)ly) / ((float)hy - (float)ly) + .5f), 0, (float)max_selector); //vec4F xl, xh; vec4F_set_scalar(&xl, 0.0f); vec4F_set_scalar(&xh, 0.0f); if (pParams->m_has_alpha) compute_least_squares_endpoints_rgba(pParams->m_num_pixels, selectors_temp1, pParams->m_pSelector_weightsx, &xl, &xh, pParams->m_pPixels); else compute_least_squares_endpoints_rgb(pParams->m_num_pixels, selectors_temp1, pParams->m_pSelector_weightsx, &xl, &xh, pParams->m_pPixels); xl = vec4F_mul(&xl, (1.0f / 255.0f)); xh = vec4F_mul(&xh, (1.0f / 255.0f)); if (!find_optimal_solution(mode, xl, xh, pParams, pResults, pComp_params)) return 0; } } } } if (mode == 1) { // Try encoding the partition as a single color by using the optimal singe colors tables to encode the block to its mean. color_cell_compressor_results avg_results = *pResults; const uint32_t r = (int)(.5f + meanColor.m_c[0] * 255.0f), g = (int)(.5f + meanColor.m_c[1] * 255.0f), b = (int)(.5f + meanColor.m_c[2] * 255.0f); uint64_t avg_err = pack_mode1_to_one_color(pParams, &avg_results, r, g, b, pResults->m_pSelectors_temp); if (avg_err < pResults->m_best_overall_err) { *pResults = avg_results; memcpy(pResults->m_pSelectors, pResults->m_pSelectors_temp, sizeof(pResults->m_pSelectors[0]) * pParams->m_num_pixels); pResults->m_best_overall_err = avg_err; } } else if (mode == 7) { // Try encoding the partition as a single color by using the optimal singe colors tables to encode the block to its mean. color_cell_compressor_results avg_results = *pResults; const uint32_t r = (int)(.5f + meanColor.m_c[0] * 255.0f), g = (int)(.5f + meanColor.m_c[1] * 255.0f), b = (int)(.5f + meanColor.m_c[2] * 255.0f), a = (int)(.5f + meanColor.m_c[3] * 255.0f); uint64_t avg_err = pack_mode7_to_one_color(pParams, &avg_results, r, g, b, a, pResults->m_pSelectors_temp, pParams->m_num_pixels, pParams->m_pPixels); if (avg_err < pResults->m_best_overall_err) { *pResults = avg_results; memcpy(pResults->m_pSelectors, pResults->m_pSelectors_temp, sizeof(pResults->m_pSelectors[0]) * pParams->m_num_pixels); pResults->m_best_overall_err = avg_err; } } return pResults->m_best_overall_err; } static uint64_t color_cell_compression_est_mode1(uint32_t num_pixels, const color_rgba *pPixels, bool perceptual, uint32_t pweights[4], uint64_t best_err_so_far) { // Find RGB bounds as an approximation of the block's principle axis uint32_t lr = 255, lg = 255, lb = 255; uint32_t hr = 0, hg = 0, hb = 0; for (uint32_t i = 0; i < num_pixels; i++) { const color_rgba *pC = &pPixels[i]; if (pC->m_c[0] < lr) lr = pC->m_c[0]; if (pC->m_c[1] < lg) lg = pC->m_c[1]; if (pC->m_c[2] < lb) lb = pC->m_c[2]; if (pC->m_c[0] > hr) hr = pC->m_c[0]; if (pC->m_c[1] > hg) hg = pC->m_c[1]; if (pC->m_c[2] > hb) hb = pC->m_c[2]; } color_rgba lowColor; color_quad_u8_set(&lowColor, lr, lg, lb, 0); color_rgba highColor; color_quad_u8_set(&highColor, hr, hg, hb, 0); // Place endpoints at bbox diagonals and compute interpolated colors const uint32_t N = 8; color_rgba weightedColors[8]; weightedColors[0] = lowColor; weightedColors[N - 1] = highColor; for (uint32_t i = 1; i < (N - 1); i++) { weightedColors[i].m_c[0] = (uint8_t)((lowColor.m_c[0] * (64 - g_bc7_weights3[i]) + highColor.m_c[0] * g_bc7_weights3[i] + 32) >> 6); weightedColors[i].m_c[1] = (uint8_t)((lowColor.m_c[1] * (64 - g_bc7_weights3[i]) + highColor.m_c[1] * g_bc7_weights3[i] + 32) >> 6); weightedColors[i].m_c[2] = (uint8_t)((lowColor.m_c[2] * (64 - g_bc7_weights3[i]) + highColor.m_c[2] * g_bc7_weights3[i] + 32) >> 6); } // Compute dots and thresholds const int ar = highColor.m_c[0] - lowColor.m_c[0]; const int ag = highColor.m_c[1] - lowColor.m_c[1]; const int ab = highColor.m_c[2] - lowColor.m_c[2]; int dots[8]; for (uint32_t i = 0; i < N; i++) dots[i] = weightedColors[i].m_c[0] * ar + weightedColors[i].m_c[1] * ag + weightedColors[i].m_c[2] * ab; int thresh[8 - 1]; for (uint32_t i = 0; i < (N - 1); i++) thresh[i] = (dots[i] + dots[i + 1] + 1) >> 1; uint64_t total_err = 0; if (perceptual) { // Transform block's interpolated colors to YCbCr int l1[8], cr1[8], cb1[8]; for (int j = 0; j < 8; j++) { const color_rgba *pE1 = &weightedColors[j]; l1[j] = pE1->m_c[0] * 109 + pE1->m_c[1] * 366 + pE1->m_c[2] * 37; cr1[j] = ((int)pE1->m_c[0] << 9) - l1[j]; cb1[j] = ((int)pE1->m_c[2] << 9) - l1[j]; } for (uint32_t i = 0; i < num_pixels; i++) { const color_rgba *pC = &pPixels[i]; int d = ar * pC->m_c[0] + ag * pC->m_c[1] + ab * pC->m_c[2]; // Find approximate selector uint32_t s = 0; if (d >= thresh[6]) s = 7; else if (d >= thresh[5]) s = 6; else if (d >= thresh[4]) s = 5; else if (d >= thresh[3]) s = 4; else if (d >= thresh[2]) s = 3; else if (d >= thresh[1]) s = 2; else if (d >= thresh[0]) s = 1; // Compute error const int l2 = pC->m_c[0] * 109 + pC->m_c[1] * 366 + pC->m_c[2] * 37; const int cr2 = ((int)pC->m_c[0] << 9) - l2; const int cb2 = ((int)pC->m_c[2] << 9) - l2; const int dl = (l1[s] - l2) >> 8; const int dcr = (cr1[s] - cr2) >> 8; const int dcb = (cb1[s] - cb2) >> 8; int ie = (pweights[0] * dl * dl) + (pweights[1] * dcr * dcr) + (pweights[2] * dcb * dcb); total_err += ie; if (total_err > best_err_so_far) break; } } else { for (uint32_t i = 0; i < num_pixels; i++) { const color_rgba *pC = &pPixels[i]; int d = ar * pC->m_c[0] + ag * pC->m_c[1] + ab * pC->m_c[2]; // Find approximate selector uint32_t s = 0; if (d >= thresh[6]) s = 7; else if (d >= thresh[5]) s = 6; else if (d >= thresh[4]) s = 5; else if (d >= thresh[3]) s = 4; else if (d >= thresh[2]) s = 3; else if (d >= thresh[1]) s = 2; else if (d >= thresh[0]) s = 1; // Compute error const color_rgba *pE1 = &weightedColors[s]; int dr = (int)pE1->m_c[0] - (int)pC->m_c[0]; int dg = (int)pE1->m_c[1] - (int)pC->m_c[1]; int db = (int)pE1->m_c[2] - (int)pC->m_c[2]; total_err += pweights[0] * (dr * dr) + pweights[1] * (dg * dg) + pweights[2] * (db * db); if (total_err > best_err_so_far) break; } } return total_err; } static uint64_t color_cell_compression_est_mode7(uint32_t num_pixels, const color_rgba * pPixels, bool perceptual, uint32_t pweights[4], uint64_t best_err_so_far) { // Find RGB bounds as an approximation of the block's principle axis uint32_t lr = 255, lg = 255, lb = 255, la = 255; uint32_t hr = 0, hg = 0, hb = 0, ha = 0; for (uint32_t i = 0; i < num_pixels; i++) { const color_rgba* pC = &pPixels[i]; if (pC->m_c[0] < lr) lr = pC->m_c[0]; if (pC->m_c[1] < lg) lg = pC->m_c[1]; if (pC->m_c[2] < lb) lb = pC->m_c[2]; if (pC->m_c[3] < la) la = pC->m_c[3]; if (pC->m_c[0] > hr) hr = pC->m_c[0]; if (pC->m_c[1] > hg) hg = pC->m_c[1]; if (pC->m_c[2] > hb) hb = pC->m_c[2]; if (pC->m_c[3] > ha) ha = pC->m_c[3]; } color_rgba lowColor; color_quad_u8_set(&lowColor, lr, lg, lb, la); color_rgba highColor; color_quad_u8_set(&highColor, hr, hg, hb, ha); // Place endpoints at bbox diagonals and compute interpolated colors const uint32_t N = 4; color_rgba weightedColors[4]; weightedColors[0] = lowColor; weightedColors[N - 1] = highColor; for (uint32_t i = 1; i < (N - 1); i++) { weightedColors[i].m_c[0] = (uint8_t)((lowColor.m_c[0] * (64 - g_bc7_weights2[i]) + highColor.m_c[0] * g_bc7_weights2[i] + 32) >> 6); weightedColors[i].m_c[1] = (uint8_t)((lowColor.m_c[1] * (64 - g_bc7_weights2[i]) + highColor.m_c[1] * g_bc7_weights2[i] + 32) >> 6); weightedColors[i].m_c[2] = (uint8_t)((lowColor.m_c[2] * (64 - g_bc7_weights2[i]) + highColor.m_c[2] * g_bc7_weights2[i] + 32) >> 6); weightedColors[i].m_c[3] = (uint8_t)((lowColor.m_c[3] * (64 - g_bc7_weights2[i]) + highColor.m_c[3] * g_bc7_weights2[i] + 32) >> 6); } // Compute dots and thresholds const int ar = highColor.m_c[0] - lowColor.m_c[0]; const int ag = highColor.m_c[1] - lowColor.m_c[1]; const int ab = highColor.m_c[2] - lowColor.m_c[2]; const int aa = highColor.m_c[3] - lowColor.m_c[3]; int dots[4]; for (uint32_t i = 0; i < N; i++) dots[i] = weightedColors[i].m_c[0] * ar + weightedColors[i].m_c[1] * ag + weightedColors[i].m_c[2] * ab + weightedColors[i].m_c[3] * aa; int thresh[4 - 1]; for (uint32_t i = 0; i < (N - 1); i++) thresh[i] = (dots[i] + dots[i + 1] + 1) >> 1; uint64_t total_err = 0; if (perceptual) { // Transform block's interpolated colors to YCbCr int l1[4], cr1[4], cb1[4]; for (int j = 0; j < 4; j++) { const color_rgba* pE1 = &weightedColors[j]; l1[j] = pE1->m_c[0] * 109 + pE1->m_c[1] * 366 + pE1->m_c[2] * 37; cr1[j] = ((int)pE1->m_c[0] << 9) - l1[j]; cb1[j] = ((int)pE1->m_c[2] << 9) - l1[j]; } for (uint32_t i = 0; i < num_pixels; i++) { const color_rgba* pC = &pPixels[i]; int d = ar * pC->m_c[0] + ag * pC->m_c[1] + ab * pC->m_c[2] + aa * pC->m_c[3]; // Find approximate selector uint32_t s = 0; if (d >= thresh[2]) s = 3; else if (d >= thresh[1]) s = 2; else if (d >= thresh[0]) s = 1; // Compute error const int l2 = pC->m_c[0] * 109 + pC->m_c[1] * 366 + pC->m_c[2] * 37; const int cr2 = ((int)pC->m_c[0] << 9) - l2; const int cb2 = ((int)pC->m_c[2] << 9) - l2; const int dl = (l1[s] - l2) >> 8; const int dcr = (cr1[s] - cr2) >> 8; const int dcb = (cb1[s] - cb2) >> 8; const int dca = (int)pC->m_c[3] - (int)weightedColors[s].m_c[3]; int ie = (pweights[0] * dl * dl) + (pweights[1] * dcr * dcr) + (pweights[2] * dcb * dcb) + (pweights[3] * dca * dca); total_err += ie; if (total_err > best_err_so_far) break; } } else { for (uint32_t i = 0; i < num_pixels; i++) { const color_rgba* pC = &pPixels[i]; int d = ar * pC->m_c[0] + ag * pC->m_c[1] + ab * pC->m_c[2] + aa * pC->m_c[3]; // Find approximate selector uint32_t s = 0; if (d >= thresh[2]) s = 3; else if (d >= thresh[1]) s = 2; else if (d >= thresh[0]) s = 1; // Compute error const color_rgba* pE1 = &weightedColors[s]; int dr = (int)pE1->m_c[0] - (int)pC->m_c[0]; int dg = (int)pE1->m_c[1] - (int)pC->m_c[1]; int db = (int)pE1->m_c[2] - (int)pC->m_c[2]; int da = (int)pE1->m_c[3] - (int)pC->m_c[3]; total_err += pweights[0] * (dr * dr) + pweights[1] * (dg * dg) + pweights[2] * (db * db) + pweights[3] * (da * da); if (total_err > best_err_so_far) break; } } return total_err; } // This table contains bitmasks indicating which ""key"" partitions must be best ranked before this partition is worth evaluating. // We first rank the best/most used 14 partitions (sorted by usefulness), record the best one found as the key partition, then use // that to control the other partitions to evaluate. The quality loss is ~.08 dB RGB PSNR, the perf gain is up to ~11% (at uber level 0). static const uint32_t g_partition_predictors[35] = { UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX, (1 << 1) | (1 << 2) | (1 << 8), (1 << 1) | (1 << 3) | (1 << 7), UINT32_MAX, UINT32_MAX, (1 << 2) | (1 << 8) | (1 << 16), (1 << 7) | (1 << 3) | (1 << 15), UINT32_MAX, (1 << 8) | (1 << 14) | (1 << 16), (1 << 7) | (1 << 14) | (1 << 15), UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX, (1 << 14) | (1 << 15), (1 << 16) | (1 << 22) | (1 << 14), (1 << 17) | (1 << 24) | (1 << 14), (1 << 2) | (1 << 14) | (1 << 15) | (1 << 1), UINT32_MAX, (1 << 1) | (1 << 3) | (1 << 14) | (1 << 16) | (1 << 22), UINT32_MAX, (1 << 1) | (1 << 2) | (1 << 15) | (1 << 17) | (1 << 24), (1 << 1) | (1 << 3) | (1 << 22), UINT32_MAX, UINT32_MAX, UINT32_MAX, (1 << 14) | (1 << 15) | (1 << 16) | (1 << 17), UINT32_MAX, UINT32_MAX, (1 << 1) | (1 << 2) | (1 << 3) | (1 << 27) | (1 << 4) | (1 << 24), (1 << 14) | (1 << 15) | (1 << 16) | (1 << 11) | (1 << 17) | (1 << 27) }; // Estimate the partition used by modes 1/7. This scans through each partition and computes an approximate error for each. static uint32_t estimate_partition(const color_rgba *pPixels, const bc7enc_compress_block_params *pComp_params, uint32_t pweights[4], uint32_t mode) { const uint32_t total_partitions = minimumu(pComp_params->m_max_partitions, BC7ENC_MAX_PARTITIONS); if (total_partitions <= 1) return 0; uint64_t best_err = UINT64_MAX; uint32_t best_partition = 0; // Partition order sorted by usage frequency across a large test corpus. Pattern 34 (checkerboard) must appear in slot 34. // Using a sorted order allows the user to decrease the # of partitions to scan with minimal loss in quality. static const uint8_t s_sorted_partition_order[64] = { 1 - 1, 14 - 1, 2 - 1, 3 - 1, 16 - 1, 15 - 1, 11 - 1, 17 - 1, 4 - 1, 24 - 1, 27 - 1, 7 - 1, 8 - 1, 22 - 1, 20 - 1, 30 - 1, 9 - 1, 5 - 1, 10 - 1, 21 - 1, 6 - 1, 32 - 1, 23 - 1, 18 - 1, 19 - 1, 12 - 1, 13 - 1, 31 - 1, 25 - 1, 26 - 1, 29 - 1, 28 - 1, 33 - 1, 34 - 1, 35 - 1, 46 - 1, 47 - 1, 52 - 1, 50 - 1, 51 - 1, 49 - 1, 39 - 1, 40 - 1, 38 - 1, 54 - 1, 53 - 1, 55 - 1, 37 - 1, 58 - 1, 59 - 1, 56 - 1, 42 - 1, 41 - 1, 43 - 1, 44 - 1, 60 - 1, 45 - 1, 57 - 1, 48 - 1, 36 - 1, 61 - 1, 64 - 1, 63 - 1, 62 - 1 }; assert(s_sorted_partition_order[34] == 34); int best_key_partition = 0; for (uint32_t partition_iter = 0; (partition_iter < total_partitions) && (best_err > 0); partition_iter++) { const uint32_t partition = s_sorted_partition_order[partition_iter]; // Check to see if we should bother evaluating this partition at all, depending on the best partition found from the first 14. if (pComp_params->m_mode17_partition_estimation_filterbank) { if ((partition_iter >= 14) && (partition_iter <= 34)) { const uint32_t best_key_partition_bitmask = 1 << (best_key_partition + 1); if ((g_partition_predictors[partition] & best_key_partition_bitmask) == 0) { if (partition_iter == 34) break; continue; } } } const uint8_t *pPartition = &g_bc7_partition2[partition * 16]; color_rgba subset_colors[2][16]; uint32_t subset_total_colors[2] = { 0, 0 }; for (uint32_t index = 0; index < 16; index++) subset_colors[pPartition[index]][subset_total_colors[pPartition[index]]++] = pPixels[index]; uint64_t total_subset_err = 0; for (uint32_t subset = 0; (subset < 2) && (total_subset_err < best_err); subset++) { if (mode == 7) total_subset_err += color_cell_compression_est_mode7(subset_total_colors[subset], &subset_colors[subset][0], pComp_params->m_perceptual, pweights, best_err); else total_subset_err += color_cell_compression_est_mode1(subset_total_colors[subset], &subset_colors[subset][0], pComp_params->m_perceptual, pweights, best_err); } if (partition < 16) { total_subset_err = (uint64_t)((double)total_subset_err * pComp_params->m_low_frequency_partition_weight + .5f); } if (total_subset_err < best_err) { best_err = total_subset_err; best_partition = partition; } // If the checkerboard pattern doesn't get the highest ranking vs. the previous (lower frequency) patterns, then just stop now because statistically the subsequent patterns won't do well either. if ((partition == 34) && (best_partition != 34)) break; if (partition_iter == 13) best_key_partition = best_partition; } // partition return best_partition; } static void set_block_bits(uint8_t *pBytes, uint32_t val, uint32_t num_bits, uint32_t *pCur_ofs) { assert((num_bits <= 32) && (val < (1ULL << num_bits))); while (num_bits) { const uint32_t n = minimumu(8 - (*pCur_ofs & 7), num_bits); pBytes[*pCur_ofs >> 3] |= (uint8_t)(val << (*pCur_ofs & 7)); val >>= n; num_bits -= n; *pCur_ofs += n; } assert(*pCur_ofs <= 128); } struct bc7_optimization_results { uint32_t m_mode; uint32_t m_partition; uint8_t m_selectors[16]; uint8_t m_alpha_selectors[16]; color_rgba m_low[3]; color_rgba m_high[3]; uint32_t m_pbits[3][2]; uint32_t m_rotation; uint32_t m_index_selector; }; void encode_bc7_block(void* pBlock, const bc7_optimization_results* pResults) { assert(pResults->m_index_selector <= 1); assert(pResults->m_rotation <= 3); const uint32_t best_mode = pResults->m_mode; const uint32_t total_subsets = g_bc7_num_subsets[best_mode]; const uint32_t total_partitions = 1 << g_bc7_partition_bits[best_mode]; //const uint32_t num_rotations = 1 << g_bc7_rotation_bits[best_mode]; //const uint32_t num_index_selectors = (best_mode == 4) ? 2 : 1; const uint8_t* pPartition; if (total_subsets == 1) pPartition = &g_bc7_partition1[0]; else if (total_subsets == 2) pPartition = &g_bc7_partition2[pResults->m_partition * 16]; else pPartition = &g_bc7_partition3[pResults->m_partition * 16]; uint8_t color_selectors[16]; memcpy(color_selectors, pResults->m_selectors, 16); uint8_t alpha_selectors[16]; memcpy(alpha_selectors, pResults->m_alpha_selectors, 16); color_rgba low[3], high[3]; memcpy(low, pResults->m_low, sizeof(low)); memcpy(high, pResults->m_high, sizeof(high)); uint32_t pbits[3][2]; memcpy(pbits, pResults->m_pbits, sizeof(pbits)); int anchor[3] = { -1, -1, -1 }; for (uint32_t k = 0; k < total_subsets; k++) { uint32_t anchor_index = 0; if (k) { if ((total_subsets == 3) && (k == 1)) anchor_index = g_bc7_table_anchor_index_third_subset_1[pResults->m_partition]; else if ((total_subsets == 3) && (k == 2)) anchor_index = g_bc7_table_anchor_index_third_subset_2[pResults->m_partition]; else anchor_index = g_bc7_table_anchor_index_second_subset[pResults->m_partition]; } anchor[k] = anchor_index; const uint32_t color_index_bits = get_bc7_color_index_size(best_mode, pResults->m_index_selector); const uint32_t num_color_indices = 1 << color_index_bits; if (color_selectors[anchor_index] & (num_color_indices >> 1)) { for (uint32_t i = 0; i < 16; i++) if (pPartition[i] == k) color_selectors[i] = (uint8_t)((num_color_indices - 1) - color_selectors[i]); if (get_bc7_mode_has_seperate_alpha_selectors(best_mode)) { for (uint32_t q = 0; q < 3; q++) { uint8_t t = low[k].m_c[q]; low[k].m_c[q] = high[k].m_c[q]; high[k].m_c[q] = t; } } else { color_rgba tmp = low[k]; low[k] = high[k]; high[k] = tmp; } if (!g_bc7_mode_has_shared_p_bits[best_mode]) { uint32_t t = pbits[k][0]; pbits[k][0] = pbits[k][1]; pbits[k][1] = t; } } if (get_bc7_mode_has_seperate_alpha_selectors(best_mode)) { const uint32_t alpha_index_bits = get_bc7_alpha_index_size(best_mode, pResults->m_index_selector); const uint32_t num_alpha_indices = 1 << alpha_index_bits; if (alpha_selectors[anchor_index] & (num_alpha_indices >> 1)) { for (uint32_t i = 0; i < 16; i++) if (pPartition[i] == k) alpha_selectors[i] = (uint8_t)((num_alpha_indices - 1) - alpha_selectors[i]); uint8_t t = low[k].m_c[3]; low[k].m_c[3] = high[k].m_c[3]; high[k].m_c[3] = t; } } } uint8_t* pBlock_bytes = (uint8_t*)(pBlock); memset(pBlock_bytes, 0, BC7ENC_BLOCK_SIZE); uint32_t cur_bit_ofs = 0; set_block_bits(pBlock_bytes, 1 << best_mode, best_mode + 1, &cur_bit_ofs); if ((best_mode == 4) || (best_mode == 5)) set_block_bits(pBlock_bytes, pResults->m_rotation, 2, &cur_bit_ofs); if (best_mode == 4) set_block_bits(pBlock_bytes, pResults->m_index_selector, 1, &cur_bit_ofs); if (total_partitions > 1) set_block_bits(pBlock_bytes, pResults->m_partition, (total_partitions == 64) ? 6 : 4, &cur_bit_ofs); const uint32_t total_comps = (best_mode >= 4) ? 4 : 3; for (uint32_t comp = 0; comp < total_comps; comp++) { for (uint32_t subset = 0; subset < total_subsets; subset++) { set_block_bits(pBlock_bytes, low[subset].m_c[comp], (comp == 3) ? g_bc7_alpha_precision_table[best_mode] : g_bc7_color_precision_table[best_mode], &cur_bit_ofs); set_block_bits(pBlock_bytes, high[subset].m_c[comp], (comp == 3) ? g_bc7_alpha_precision_table[best_mode] : g_bc7_color_precision_table[best_mode], &cur_bit_ofs); } } if (g_bc7_mode_has_p_bits[best_mode]) { for (uint32_t subset = 0; subset < total_subsets; subset++) { set_block_bits(pBlock_bytes, pbits[subset][0], 1, &cur_bit_ofs); if (!g_bc7_mode_has_shared_p_bits[best_mode]) set_block_bits(pBlock_bytes, pbits[subset][1], 1, &cur_bit_ofs); } } for (uint32_t y = 0; y < 4; y++) { for (uint32_t x = 0; x < 4; x++) { int idx = x + y * 4; uint32_t n = pResults->m_index_selector ? get_bc7_alpha_index_size(best_mode, pResults->m_index_selector) : get_bc7_color_index_size(best_mode, pResults->m_index_selector); if ((idx == anchor[0]) || (idx == anchor[1]) || (idx == anchor[2])) n--; set_block_bits(pBlock_bytes, pResults->m_index_selector ? alpha_selectors[idx] : color_selectors[idx], n, &cur_bit_ofs); } } if (get_bc7_mode_has_seperate_alpha_selectors(best_mode)) { for (uint32_t y = 0; y < 4; y++) { for (uint32_t x = 0; x < 4; x++) { int idx = x + y * 4; uint32_t n = pResults->m_index_selector ? get_bc7_color_index_size(best_mode, pResults->m_index_selector) : get_bc7_alpha_index_size(best_mode, pResults->m_index_selector); if ((idx == anchor[0]) || (idx == anchor[1]) || (idx == anchor[2])) n--; set_block_bits(pBlock_bytes, pResults->m_index_selector ? color_selectors[idx] : alpha_selectors[idx], n, &cur_bit_ofs); } } } assert(cur_bit_ofs == 128); } static void handle_alpha_block_mode5(const color_rgba* pPixels, const bc7enc_compress_block_params* pComp_params, color_cell_compressor_params* pParams, uint32_t lo_a, uint32_t hi_a, bc7_optimization_results* pOpt_results5, uint64_t* pMode5_err, uint64_t* pMode5_alpha_err) { pParams->m_pSelector_weights = g_bc7_weights2; pParams->m_pSelector_weightsx = (const vec4F*)g_bc7_weights2x; pParams->m_num_selector_weights = 4; pParams->m_comp_bits = 7; pParams->m_has_pbits = false; pParams->m_endpoints_share_pbit = false; pParams->m_has_alpha = false; pParams->m_perceptual = pComp_params->m_perceptual; pParams->m_num_pixels = 16; pParams->m_pPixels = pPixels; color_cell_compressor_results results5; results5.m_pSelectors = pOpt_results5->m_selectors; uint8_t selectors_temp[16]; results5.m_pSelectors_temp = selectors_temp; *pMode5_err = color_cell_compression(5, pParams, &results5, pComp_params); assert(*pMode5_err == results5.m_best_overall_err); pOpt_results5->m_low[0] = results5.m_low_endpoint; pOpt_results5->m_high[0] = results5.m_high_endpoint; if (lo_a == hi_a) { *pMode5_alpha_err = 0; pOpt_results5->m_low[0].m_c[3] = (uint8_t)lo_a; pOpt_results5->m_high[0].m_c[3] = (uint8_t)hi_a; memset(pOpt_results5->m_alpha_selectors, 0, sizeof(pOpt_results5->m_alpha_selectors)); } else { *pMode5_alpha_err = UINT64_MAX; const uint32_t total_passes = (pComp_params->m_uber_level >= 1) ? 3 : 2; for (uint32_t pass = 0; pass < total_passes; pass++) { int32_t vals[4]; vals[0] = lo_a; vals[3] = hi_a; const int32_t w_s1 = 21, w_s2 = 43; vals[1] = (vals[0] * (64 - w_s1) + vals[3] * w_s1 + 32) >> 6; vals[2] = (vals[0] * (64 - w_s2) + vals[3] * w_s2 + 32) >> 6; uint8_t trial_alpha_selectors[16]; uint64_t trial_alpha_err = 0; for (uint32_t i = 0; i < 16; i++) { const int32_t a = pParams->m_pPixels[i].m_c[3]; int s = 0; int32_t be = iabs32(a - vals[0]); int e = iabs32(a - vals[1]); if (e < be) { be = e; s = 1; } e = iabs32(a - vals[2]); if (e < be) { be = e; s = 2; } e = iabs32(a - vals[3]); if (e < be) { be = e; s = 3; } trial_alpha_selectors[i] = (uint8_t)s; uint32_t a_err = (uint32_t)(be * be) * pParams->m_weights[3]; trial_alpha_err += a_err; } if (trial_alpha_err < *pMode5_alpha_err) { *pMode5_alpha_err = trial_alpha_err; pOpt_results5->m_low[0].m_c[3] = (uint8_t)lo_a; pOpt_results5->m_high[0].m_c[3] = (uint8_t)hi_a; memcpy(pOpt_results5->m_alpha_selectors, trial_alpha_selectors, sizeof(pOpt_results5->m_alpha_selectors)); } if (pass != (total_passes - 1U)) { float xl, xh; compute_least_squares_endpoints_a(16, trial_alpha_selectors, (const vec4F*)g_bc7_weights2x, &xl, &xh, pParams->m_pPixels); uint32_t new_lo_a = clampi((int)floor(xl + .5f), 0, 255); uint32_t new_hi_a = clampi((int)floor(xh + .5f), 0, 255); if (new_lo_a > new_hi_a) swapu(&new_lo_a, &new_hi_a); if ((new_lo_a == lo_a) && (new_hi_a == hi_a)) break; lo_a = new_lo_a; hi_a = new_hi_a; } } *pMode5_err += *pMode5_alpha_err; } } static void handle_alpha_block(void *pBlock, const color_rgba *pPixels, const bc7enc_compress_block_params *pComp_params, color_cell_compressor_params *pParams) { assert((pComp_params->m_mode_mask & (1 << 6)) || (pComp_params->m_mode_mask & (1 << 5)) || (pComp_params->m_mode_mask & (1 << 7))); pParams->m_pSelector_weights = g_bc7_weights4; pParams->m_pSelector_weightsx = (const vec4F *)g_bc7_weights4x; pParams->m_num_selector_weights = 16; pParams->m_comp_bits = 7; pParams->m_has_pbits = true; pParams->m_endpoints_share_pbit = false; pParams->m_has_alpha = true; pParams->m_perceptual = pComp_params->m_perceptual; pParams->m_num_pixels = 16; pParams->m_pPixels = pPixels; bc7_optimization_results opt_results6, opt_results5, opt_results7; color_cell_compressor_results results6; memset(&results6, 0, sizeof(results6)); uint64_t best_err = UINT64_MAX; uint32_t best_mode = 0; uint8_t selectors_temp[16]; if (pComp_params->m_mode_mask & (1 << 6)) { results6.m_pSelectors = opt_results6.m_selectors; results6.m_pSelectors_temp = selectors_temp; best_err = (uint64_t)(color_cell_compression(6, pParams, &results6, pComp_params) * pComp_params->m_mode6_error_weight + .5f); best_mode = 6; } if ((best_err > 0) && (pComp_params->m_mode_mask & (1 << 5))) { uint32_t lo_a = 255, hi_a = 0; for (uint32_t i = 0; i < 16; i++) { uint32_t a = pPixels[i].m_c[3]; lo_a = minimumu(lo_a, a); hi_a = maximumu(hi_a, a); } uint64_t mode5_err, mode5_alpha_err; handle_alpha_block_mode5(pPixels, pComp_params, pParams, lo_a, hi_a, &opt_results5, &mode5_err, &mode5_alpha_err); mode5_err = (uint64_t)(mode5_err * pComp_params->m_mode5_error_weight + .5f); if (mode5_err < best_err) { best_err = mode5_err; best_mode = 5; } } if ((best_err > 0) && (pComp_params->m_mode_mask & (1 << 7))) { const uint32_t trial_partition = estimate_partition(pPixels, pComp_params, pParams->m_weights, 7); pParams->m_pSelector_weights = g_bc7_weights2; pParams->m_pSelector_weightsx = (const vec4F*)g_bc7_weights2x; pParams->m_num_selector_weights = 4; pParams->m_comp_bits = 5; pParams->m_has_pbits = true; pParams->m_endpoints_share_pbit = false; pParams->m_has_alpha = true; const uint8_t* pPartition = &g_bc7_partition2[trial_partition * 16]; color_rgba subset_colors[2][16]; uint32_t subset_total_colors7[2] = { 0, 0 }; uint8_t subset_pixel_index7[2][16]; uint8_t subset_selectors7[2][16]; color_cell_compressor_results subset_results7[2]; for (uint32_t idx = 0; idx < 16; idx++) { const uint32_t p = pPartition[idx]; subset_colors[p][subset_total_colors7[p]] = pPixels[idx]; subset_pixel_index7[p][subset_total_colors7[p]] = (uint8_t)idx; subset_total_colors7[p]++; } uint64_t trial_err = 0; for (uint32_t subset = 0; subset < 2; subset++) { pParams->m_num_pixels = subset_total_colors7[subset]; pParams->m_pPixels = &subset_colors[subset][0]; color_cell_compressor_results* pResults = &subset_results7[subset]; pResults->m_pSelectors = &subset_selectors7[subset][0]; pResults->m_pSelectors_temp = selectors_temp; uint64_t err = color_cell_compression(7, pParams, pResults, pComp_params); trial_err += err; if ((uint64_t)(trial_err * pComp_params->m_mode7_error_weight + .5f) > best_err) break; } // subset const uint64_t mode7_trial_err = (uint64_t)(trial_err * pComp_params->m_mode7_error_weight + .5f); if (mode7_trial_err < best_err) { best_err = mode7_trial_err; best_mode = 7; opt_results7.m_mode = 7; opt_results7.m_partition = trial_partition; opt_results7.m_index_selector = 0; opt_results7.m_rotation = 0; for (uint32_t subset = 0; subset < 2; subset++) { for (uint32_t i = 0; i < subset_total_colors7[subset]; i++) opt_results7.m_selectors[subset_pixel_index7[subset][i]] = subset_selectors7[subset][i]; opt_results7.m_low[subset] = subset_results7[subset].m_low_endpoint; opt_results7.m_high[subset] = subset_results7[subset].m_high_endpoint; opt_results7.m_pbits[subset][0] = subset_results7[subset].m_pbits[0]; opt_results7.m_pbits[subset][1] = subset_results7[subset].m_pbits[1]; } } } if (best_mode == 7) { encode_bc7_block(pBlock, &opt_results7); } else if (best_mode == 5) { opt_results5.m_mode = 5; opt_results5.m_partition = 0; opt_results5.m_rotation = 0; opt_results5.m_index_selector = 0; encode_bc7_block(pBlock, &opt_results5); } else if (best_mode == 6) { opt_results6.m_mode = 6; opt_results6.m_partition = 0; opt_results6.m_low[0] = results6.m_low_endpoint; opt_results6.m_high[0] = results6.m_high_endpoint; opt_results6.m_pbits[0][0] = results6.m_pbits[0]; opt_results6.m_pbits[0][1] = results6.m_pbits[1]; opt_results6.m_rotation = 0; opt_results6.m_index_selector = 0; encode_bc7_block(pBlock, &opt_results6); } else { assert(0); } } static void handle_opaque_block(void *pBlock, const color_rgba *pPixels, const bc7enc_compress_block_params *pComp_params, color_cell_compressor_params *pParams) { assert((pComp_params->m_mode_mask & (1 << 6)) || (pComp_params->m_mode_mask & (1 << 1))); uint8_t selectors_temp[16]; bc7_optimization_results opt_results; uint64_t best_err = UINT64_MAX; pParams->m_perceptual = pComp_params->m_perceptual; pParams->m_num_pixels = 16; pParams->m_pPixels = pPixels; pParams->m_has_alpha = false; opt_results.m_partition = 0; opt_results.m_index_selector = 0; opt_results.m_rotation = 0; // Mode 6 if (pComp_params->m_mode_mask & (1 << 6)) { pParams->m_pSelector_weights = g_bc7_weights4; pParams->m_pSelector_weightsx = (const vec4F*)g_bc7_weights4x; pParams->m_num_selector_weights = 16; pParams->m_comp_bits = 7; pParams->m_has_pbits = true; pParams->m_endpoints_share_pbit = false; color_cell_compressor_results results6; results6.m_pSelectors = opt_results.m_selectors; results6.m_pSelectors_temp = selectors_temp; best_err = (uint64_t)(color_cell_compression(6, pParams, &results6, pComp_params) * pComp_params->m_mode6_error_weight + .5f); opt_results.m_mode = 6; opt_results.m_low[0] = results6.m_low_endpoint; opt_results.m_high[0] = results6.m_high_endpoint; opt_results.m_pbits[0][0] = results6.m_pbits[0]; opt_results.m_pbits[0][1] = results6.m_pbits[1]; } // Mode 1 if ((best_err > 0) && (pComp_params->m_max_partitions > 0) && (pComp_params->m_mode_mask & (1 << 1))) { const uint32_t trial_partition = estimate_partition(pPixels, pComp_params, pParams->m_weights, 1); pParams->m_pSelector_weights = g_bc7_weights3; pParams->m_pSelector_weightsx = (const vec4F *)g_bc7_weights3x; pParams->m_num_selector_weights = 8; pParams->m_comp_bits = 6; pParams->m_has_pbits = true; pParams->m_endpoints_share_pbit = true; const uint8_t *pPartition = &g_bc7_partition2[trial_partition * 16]; color_rgba subset_colors[2][16]; uint32_t subset_total_colors1[2] = { 0, 0 }; uint8_t subset_pixel_index1[2][16]; uint8_t subset_selectors1[2][16]; color_cell_compressor_results subset_results1[2]; for (uint32_t idx = 0; idx < 16; idx++) { const uint32_t p = pPartition[idx]; subset_colors[p][subset_total_colors1[p]] = pPixels[idx]; subset_pixel_index1[p][subset_total_colors1[p]] = (uint8_t)idx; subset_total_colors1[p]++; } uint64_t trial_err = 0; for (uint32_t subset = 0; subset < 2; subset++) { pParams->m_num_pixels = subset_total_colors1[subset]; pParams->m_pPixels = &subset_colors[subset][0]; color_cell_compressor_results *pResults = &subset_results1[subset]; pResults->m_pSelectors = &subset_selectors1[subset][0]; pResults->m_pSelectors_temp = selectors_temp; uint64_t err = color_cell_compression(1, pParams, pResults, pComp_params); trial_err += err; if ((uint64_t)(trial_err * pComp_params->m_mode1_error_weight + .5f) > best_err) break; } // subset const uint64_t mode1_trial_err = (uint64_t)(trial_err * pComp_params->m_mode1_error_weight + .5f); if (mode1_trial_err < best_err) { best_err = mode1_trial_err; opt_results.m_mode = 1; opt_results.m_partition = trial_partition; for (uint32_t subset = 0; subset < 2; subset++) { for (uint32_t i = 0; i < subset_total_colors1[subset]; i++) opt_results.m_selectors[subset_pixel_index1[subset][i]] = subset_selectors1[subset][i]; opt_results.m_low[subset] = subset_results1[subset].m_low_endpoint; opt_results.m_high[subset] = subset_results1[subset].m_high_endpoint; opt_results.m_pbits[subset][0] = subset_results1[subset].m_pbits[0]; } } } encode_bc7_block(pBlock, &opt_results); } bool bc7enc_compress_block(void *pBlock, const void *pPixelsRGBA, const bc7enc_compress_block_params *pComp_params) { assert(g_bc7_mode_1_optimal_endpoints[255][0].m_hi != 0); const color_rgba *pPixels = (const color_rgba *)(pPixelsRGBA); color_cell_compressor_params params; if (pComp_params->m_perceptual) { // https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.709_conversion const float pr_weight = (.5f / (1.0f - .2126f)) * (.5f / (1.0f - .2126f)); const float pb_weight = (.5f / (1.0f - .0722f)) * (.5f / (1.0f - .0722f)); params.m_weights[0] = (int)(pComp_params->m_weights[0] * 4.0f); params.m_weights[1] = (int)(pComp_params->m_weights[1] * 4.0f * pr_weight); params.m_weights[2] = (int)(pComp_params->m_weights[2] * 4.0f * pb_weight); params.m_weights[3] = pComp_params->m_weights[3] * 4; } else memcpy(params.m_weights, pComp_params->m_weights, sizeof(params.m_weights)); if (pComp_params->m_force_alpha) { handle_alpha_block(pBlock, pPixels, pComp_params, ¶ms); return true; } for (uint32_t i = 0; i < 16; i++) { if (pPixels[i].m_c[3] < 255) { handle_alpha_block(pBlock, pPixels, pComp_params, ¶ms); return true; } } handle_opaque_block(pBlock, pPixels, pComp_params, ¶ms); return false; } static const uint8_t g_tdefl_small_dist_extra[512] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }; static const uint8_t g_tdefl_large_dist_extra[128] = { 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 }; static inline uint32_t compute_match_cost_estimate(uint32_t dist, uint32_t match_len_in_bytes) { assert(match_len_in_bytes <= 258); uint32_t len_cost = 6; if (match_len_in_bytes >= 12) len_cost = 9; else if (match_len_in_bytes >= 8) len_cost = 8; else if (match_len_in_bytes >= 6) len_cost = 7; uint32_t dist_cost = 5; if (dist < 512) dist_cost += g_tdefl_small_dist_extra[dist & 511]; else { dist_cost += g_tdefl_large_dist_extra[std::min(dist, 32767) >> 8]; while (dist >= 32768) { dist_cost++; dist >>= 1; } } return len_cost + dist_cost; } class tracked_stat { public: tracked_stat() { clear(); } void clear() { m_num = 0; m_total = 0; m_total2 = 0; } void update(uint32_t val) { m_num++; m_total += val; m_total2 += val * val; } tracked_stat& operator += (uint32_t val) { update(val); return *this; } uint32_t get_number_of_values() { return m_num; } uint64_t get_total() const { return m_total; } uint64_t get_total2() const { return m_total2; } float get_average() const { return m_num ? (float)m_total / m_num : 0.0f; }; float get_std_dev() const { return m_num ? sqrtf((float)(m_num * m_total2 - m_total * m_total)) / m_num : 0.0f; } float get_variance() const { float s = get_std_dev(); return s * s; } private: uint32_t m_num; uint64_t m_total; uint64_t m_total2; }; static inline float compute_block_max_std_dev(const color_rgba* pPixels) { tracked_stat r_stats, g_stats, b_stats, a_stats; for (uint32_t i = 0; i < 16; i++) { r_stats.update(pPixels[i].m_c[0]); g_stats.update(pPixels[i].m_c[1]); b_stats.update(pPixels[i].m_c[2]); a_stats.update(pPixels[i].m_c[3]); } return std::max(std::max(std::max(r_stats.get_std_dev(), g_stats.get_std_dev()), b_stats.get_std_dev()), a_stats.get_std_dev()); } struct bc7_block { uint8_t m_bytes[16]; uint32_t get_mode() const { uint32_t bc7_mode = 0; while (((m_bytes[0] & (1 << bc7_mode)) == 0) && (bc7_mode < 8)) bc7_mode++; return bc7_mode; } }; /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. If you use this software in a product, attribution / credits is requested but not required. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright(c) 2020-2021 , Jr. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain(www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non - commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain.We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors.We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */ ",best_hi_p 19,"// Copyright 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) export module tm.ability_blocks_move; import tm.move.category; import tm.move.known_move; import tm.move.move_name; import tm.move.target; import tm.status.status_name; import tm.type.effectiveness; import tm.type.pokemon_types; import tm.type.type; import tm.ability; import tm.generation; namespace technicalmachine { export constexpr auto ability_blocks_move(Generation const generation, Ability const ability, KnownMove const move, StatusName const [MASK] , PokemonTypes const target_types) -> bool { auto absorb_ability_activates = [=](Type const absorbed_type) { return move_targets_foe(generation, move.name) and move.type == absorbed_type; }; switch (ability) { case Ability::Flash_Fire: if (generation <= Generation::four and [MASK] == StatusName::freeze) { return false; } return absorb_ability_activates(Type::Fire) and (generation >= Generation::four or move.name != MoveName::Will_O_Wisp); case Ability::Volt_Absorb: return absorb_ability_activates(Type::Electric) and (generation >= Generation::four or move.name != MoveName::Thunder_Wave); case Ability::Water_Absorb: case Ability::Dry_Skin: return absorb_ability_activates(Type::Water); case Ability::Wonder_Guard: if (!is_damaging(move.name)) { return false; } if (Effectiveness(generation, move.type, target_types).is_super_effective()) { return false; } switch (move.name) { case MoveName::Beat_Up: return generation >= Generation::five; case MoveName::Fire_Fang: return generation != Generation::four; case MoveName::Struggle: return false; default: return true; } case Ability::Motor_Drive: return absorb_ability_activates(Type::Electric); default: return false; } } } // namespace technicalmachine ",target_status 20,"// // Created by csq on 2017/12/26. // #include ""Sort.h"" void CSort::sort(int *a, int n, ESortType [MASK] ) { switch ( [MASK] ) { case ekSortType_Bubble: sortBubble(a, n); break; case ekSortType_Bubble_BiDirect: sortBubbleBiDirect(a, n); break; case ekSortType_Insert: sortInsert(a, n); break; case ekSortType_Insert_Dichotomy: sortInsertDichotomy(a, n); break; case ekSortType_Select: sortSelect(a, n); break; case ekSortType_Exchange: sortExchange(a, n); break; case ekSortType_Quick: sortQuick(a, n); break; case ekSortType_Merge: sortMerge(a, n); break; case ekSortType_MinHeap: sortMinHeap(a, n); break; case ekSortType_Shell: sortShell(a, n); break; case ekSortType_Radix: sortRadix(a, n); break; default: break; } } void CSort::sortBubble(int *a, int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - 1 - i; j++) { if (a[j] > a[j + 1]) swap(a[j], a[j + 1]); } } } void CSort::sortBubbleBiDirect(int *a, int n) { int low = 0; int high = n - 1; while (high > low) { for (int i = low; i < high; i++) { if (a[i] > a[i + 1]) swap(a[i], a[i + 1]); } high--; for (int i = high; i > low; i--) { if (a[i - 1] > a[i]) swap(a[i - 1], a[i]); } low++; } } void CSort::sortInsert(int *a, int n) { for (int i = 1; i < n; i++) { int val = a[i]; int j = i - 1; while (j >= 0 && a[j] > val) { a[j + 1] = a[j]; j--; } a[j + 1] = val; } } void CSort::sortInsertDichotomy(int *a, int n) { for (int i = 1; i < n; i++) { int val = a[i]; //find insert pos int low = 0; int high = i - 1; int mid; while (high >= low) { mid = (low + high) / 2; if (a[mid] > val) high = mid - 1; else low = mid + 1; } for (int j = i - 1; j >= low; j--) { a[j + 1] = a[j]; } a[low] = val; } } void CSort::sortSelect(int *a, int n) { int minIdx; for (int i = 0; i < n - 1; i++) { minIdx = i; for (int j = i + 1; j < n; j++) { if (a[j] < a[minIdx]) minIdx = j; } swap(a[i], a[minIdx]); } } void CSort::sortExchange(int *a, int n) { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (a[i] > a[j]) swap(a[i], a[j]); } } } void CSort::sortQuick(int *a, int n) { __sortQuick(a, 0, n - 1); } void CSort::sortMerge(int *a, int n) { int *b = new int[n]; __sortMerge(a, 0, n - 1, b); delete[]b; } void CSort::sortMinHeap(int *a, int n) { makeMinHeap(a, n); for (int i = n - 1; i > 0; i--) { swap(a[0], a[i]); minHeapFixDown(a, i, 0); } int start = 0; int end = n - 1; while (end > start) { swap(a[start++], a[end--]); } } void CSort::sortShell(int *a, int n) { for (int step = n / 2; step > 0; step /= 2) { for (int group = 0; group < step; group++) { for (int i = group + step; i < n; i += step) { int val = a[i]; int j = i - step; while (j >= group && a[j] > val) { a[j + step] = a[j]; j -= step; } a[j + step] = val; } } } } void CSort::sortRadix(int *a, int n) { int *count = new int[10]; int *bucket = new int[n]; int maxLen = maxNumLen(a, n); int divisor = 1; for (int i = 0; i < maxLen; i++) { for (int j = 0; j < 10; j++) count[j] = 0; for (int j = 0; j < n; j++) { int num = (a[j] / divisor) % 10; count[num]++; } for (int j = 1; j < 10; j++) { count[j] += count[j - 1]; } for (int j = n - 1; j >= 0; j--) { int num = (a[j] / divisor) % 10; bucket[count[num] - 1] = a[j]; count[num]--; } for (int j = 0; j < n; j++) { a[j] = bucket[j]; } divisor *= 10; } delete[]count; delete[]bucket; } void CSort::swap(int &a, int &b) { int temp = a; a = b; b = temp; } void CSort::__sortQuick(int *a, int start, int end) { if (start >= end) return; int key = a[start]; int low = start; int high = end; while (high > low) { while (high > low && a[high] >= key) { high--; } a[low] = a[high]; while (high > low && a[low] <= key) { low++; } a[high] = a[low]; } a[low] = key; __sortQuick(a, 0, low - 1); __sortQuick(a, low + 1, end); } void CSort::mergeArray(int *a, int start, int mid, int end, int *b) { int first = start; int second = mid + 1; int idx = start; while (first <= mid && second <= end) { if (a[first] > a[second]) { b[idx++] = a[second++]; } else { b[idx++] = a[first++]; } } while (first <= mid) { b[idx++] = a[first++]; } while (second <= end) { b[idx++] = a[second++]; } for (int i = start; i <= end; i++) a[i] = b[i]; } void CSort::__sortMerge(int *a, int start, int end, int *b) { if (start >= end) return; int mid = (start + end) / 2; __sortMerge(a, start, mid, b); __sortMerge(a, mid + 1, end, b); mergeArray(a, start, mid, end, b); } void CSort::minHeapFixDown(int *a, int n, int i) { int val = a[i]; int child = i * 2 + 1; while (child <= n - 1) { if (child + 1 <= n - 1 && a[child + 1] < a[child]) child = child + 1; if (a[child] >= val) break; a[(child - 1) / 2] = a[child]; child = child * 2 + 1; } a[(child - 1) / 2] = val; } void CSort::makeMinHeap(int *a, int n) { for (int i = n / 2 - 1; i >= 0; i--) minHeapFixDown(a, n, i); } int CSort::maxNumLen(int *a, int n) { int maxLen = 1; int divisor = 10; for (int i = 0; i < n; i++) { while (a[i] / divisor > 0) { maxLen++; divisor *= 10; } } return maxLen; } ",type 21,"#include #include #include using namespace std; class Student { private: int nr_matricol; string nume; public: Student(const int nr_matricol, const string nume): nr_matricol(nr_matricol), nume(nume){}; Student(const Student& s) { nr_matricol = s.nr_matricol; nume = s.nume + "" - copy""; } virtual string to_string() { return ""[ "" + std::to_string(nr_matricol) + "" ] "" + nume; } bool operator==(const Student& rhs) { return (nr_matricol == rhs.nr_matricol) && (nume == rhs.nume); } Student& operator=(const Student& rhs) { nr_matricol = rhs.nr_matricol; nume = rhs.nume; return *this; } }; class StudentBursier : public Student { private: double valoare_bursa; public: StudentBursier(const int nr_matricol, const string nume, const double valoare_bursa) : Student(nr_matricol, nume), valoare_bursa(valoare_bursa) {}; // copy constructor ce apeleaza copy constructor-ul super clasei StudentBursier(const StudentBursier& s) : Student(s), valoare_bursa(s.valoare_bursa) {}; string to_string() { return Student::to_string() + "" - bursa: "" + std::to_string(valoare_bursa); } // copying base class field values as well StudentBursier& operator=(const StudentBursier& rhs) { Student::operator=(rhs); valoare_bursa = rhs.valoare_bursa; return *this; } }; class FisaMatricola { private: Student* student; list note; public: FisaMatricola(Student* student, const list note): student(student), note(note){}; FisaMatricola& operator=(const FisaMatricola& rhs) { // self assignment safety Student *stOrig = student; student = new Student(*rhs.student); delete stOrig; note = rhs.note; return *this; } FisaMatricola& operator+=(const FisaMatricola& rhs) { // se va face join doar daca studentul este acelasi if (student == rhs.student) { for (auto const& nota : rhs.note) note.push_back(nota); } return *this; } void adauga_nota(const int n) { note.push_back(n); } string to_string() { string [MASK] = (*student).to_string() + "": ""; for (auto const& nota : note) { [MASK] += std::to_string(nota) + ""; ""; } return [MASK] ; } };",res 22,"/* * CompoundSolver.cpp * * Copyright 2023 and Contributors * * 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. * * Created on: * Author: */ #include ""dmgr/impl/DebugMacros.h"" #include ""CompoundSolver.h"" #include ""TaskBuildSolveSets.h"" namespace vsc { namespace solvers { CompoundSolver::CompoundSolver( dmgr::IDebugMgr *dmgr, ISolverFactory *solver_f) : m_dmgr(dmgr), m_solver_f(solver_f), m_solver_unconstrained(dmgr) { DEBUG_INIT(""vsc::solvers::CompoundSolver"", dmgr); } CompoundSolver::~CompoundSolver() { } bool CompoundSolver::randomize( IRandState *randstate, dm::IModelField *root_field, const RefPathSet &target_fields, const RefPathSet &fixed_fields, const RefPathSet &include_constraints, const RefPathSet &exclude_constraints, SolveFlags flags) { std::vector [MASK] ; RefPathSet unconstrained; TaskBuildSolveSets( m_dmgr, root_field, target_fields, fixed_fields, include_constraints, exclude_constraints).build( [MASK] , unconstrained); // First, randomize any unconstrained fields if (!unconstrained.empty()) { RefPathSet fixed_fields; m_solver_unconstrained.randomize( randstate, root_field, unconstrained); } // Now, move on for (std::vector::const_iterator it= [MASK] .begin(); it!= [MASK] .end(); it++) { ISolverUP solver(m_solver_f->mkSolver(it->get())); if (!solver->randomize(randstate, root_field, it->get())) { } } return true; } bool CompoundSolver::sat( dm::IModelField *root_field, const RefPathSet &target_fields, const RefPathSet &fixed_fields, const RefPathSet &include_constraints, const RefPathSet &exclude_constraints, SolveFlags flags) { return true; } dmgr::IDebug *CompoundSolver::m_dbg = 0; } } ",solvesets 23,"/* * Copyright (c) 2024, wareya * SPDX-License-Identifier: Apache-2.0 * * 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 #include REDIRECT_STDOUT_TO(Serial); #include #include ""srom_3360_0x05.h"" #include ""relmouse_16.h"" USBMouse16 mouse(false); #define REG_PRODUCT_ID (0x00) #define REG_REVISION_ID (0x01) #define REG_MOTION (0x02) #define REG_DELTA_X_L (0x03) #define REG_DELTA_X_H (0x04) #define REG_DELTA_Y_L (0x05) #define REG_DELTA_Y_H (0x06) #define REG_SQUAL (0x07) #define REG_RAW_DATA_SUM (0x08) #define REG_MAX_RAW_DATA (0x09) #define REG_MIN_RAW_DATA (0x0A) #define REG_SHUTTER_LOWER (0x0B) #define REG_SHUTTER_UPPER (0x0C) #define REG_CONTROL (0x0D) #define REG_CONFIG1 (0x0F) #define REG_CONFIG2 (0x10) #define REG_ANGLE_TUNE (0x11) #define REG_FRAME_CAPTURE (0x12) #define REG_SROM_ENABLE (0x13) #define REG_RUN_DOWNSHIFT (0x14) #define REG_REST1_RATE_LOWER (0x15) #define REG_REST1_RATE_UPPER (0x16) #define REG_REST1_DOWNSHIFT (0x17) #define REG_REST2_RATE_LOWER (0x18) #define REG_REST2_RATE_UPPER (0x19) #define REG_REST2_DOWNSHIFT (0x1A) #define REG_REST3_RATE_LOWER (0x1B) #define REG_REST3_RATE_UPPER (0x1C) #define REG_OBSERVATION (0x24) #define REG_DATA_OUT_LOWER (0x25) #define REG_DATA_OUT_UPPER (0x26) #define REG_RAW_DATA_DUMP (0x29) #define REG_SROM_ID (0x2A) #define REG_MIN_SQ_RUN (0x2B) #define REG_RAW_DATA_THRESHOLD (0x2C) #define REG_CONFIG5 (0x2F) #define REG_POWER_UP_RESET (0x3A) #define REG_SHUTDOWN (0x3B) #define REG_INVERSE_PRODUCT_ID (0x3F) #define REG_LIFTCUTOFF_TUNE3 (0x41) #define REG_ANGLE_SNAP (0x42) #define REG_LIFTCUTOFF_TUNE1 (0x4A) #define REG_MOTION_BURST (0x50) #define REG_LIFTCUTOFF_TUNE_TIMEOUT (0x58) #define REG_LIFTCUTOFF_TUNE_MIN_LENGTH (0x5A) #define REG_SROM_LOAD_BURST (0x62) #define REG_LIFT_CONFIG (0x63) #define REG_RAW_DATA_BURST (0x64) #define REG_LIFTOFF_TUNE2 (0x65) #define CONFIG2_REST_ENABLED (0x30) #define CONFIG2_REPORT_MODE (0x04) #define BUTTONS_ON 0 #define BUTTONS_OFF 1 #define BUTTON_M1 2 #define BUTTON_M2 3 #define BUTTON_M3 4 #define BUTTON_M4 6 #define BUTTON_M5 7 #define BUTTON_DPI 5 #define ENCODER_A 8 #define ENCODER_B 10 #define ENCODER_COM 9 #define PIN_NCS 17 #define PIN_MOSI 19 #define PIN_MISO 16 SPISettings spisettings(2000000, MSBFIRST, SPI_MODE3); MbedSPI spi(PIN_MISO, PIN_MOSI, 18); void setup_buttons() { pinMode(BUTTONS_OFF, INPUT); pinMode(BUTTONS_ON, INPUT); pinMode(BUTTON_M1, INPUT_PULLUP); pinMode(BUTTON_M2, INPUT_PULLUP); pinMode(BUTTON_M3, INPUT_PULLUP); pinMode(BUTTON_M4, INPUT_PULLUP); pinMode(BUTTON_M5, INPUT_PULLUP); pinMode(BUTTON_DPI, INPUT_PULLUP); pinMode(ENCODER_A, INPUT_PULLUP); pinMode(ENCODER_B, INPUT_PULLUP); pinMode(ENCODER_COM, OUTPUT); digitalWrite(ENCODER_COM, LOW); } bool mouse_inited; void setup() { Serial1.begin(1000000); delay(3000); // SCK, MISO, MOSI, SS SPI.begin(); pinMode(PIN_NCS, OUTPUT); digitalWrite(PIN_NCS, HIGH); delayMicroseconds(1); digitalWrite(PIN_NCS, LOW); delayMicroseconds(1); digitalWrite(PIN_NCS, HIGH); delayMicroseconds(1); pmw3360_boot(); delay(10); pmw3360_config(); setup_buttons(); } uint32_t pins_state = 0; uint8_t buttons = 0; uint8_t which_m3 = 0; // 8ms latch time uint8_t buttons_latch_max = 8; uint8_t buttons_latch[5] = {0, 0, 0, 0, 0}; volatile uint32_t * pad_control = (uint32_t *)0x4001c000; volatile uint32_t * gpio_oe_set = (uint32_t *)0xd0000024; volatile uint32_t * gpio_oe_clr = (uint32_t *)0xd0000028; volatile uint32_t * gpio_in = (uint32_t *)0xd0000004; void update_buttons() { /* // disable pullup/pulldown pad_control[BUTTONS_OFF + 1] &= 0xFFFFFFF2; pad_control[BUTTONS_ON + 1] &= 0xFFFFFFF2; */ // change BUTTONS_OFF to high impedance and BUTTONS_ON to output // using pinMode for this is way, WAY too slow, like 50us per call (?!?!?!) *gpio_oe_clr = 1 << BUTTONS_OFF; *gpio_oe_set = 1 << BUTTONS_ON; // read ON pins digitalWrite(BUTTONS_ON, LOW); delayMicroseconds(1); uint32_t pins_on = ~*gpio_in; // change BUTTONS_OFF to high impedance and BUTTONS_ON to output *gpio_oe_set = 1 << BUTTONS_OFF; *gpio_oe_clr = 1 << BUTTONS_ON; // read OFF pins digitalWrite(BUTTONS_OFF, LOW); delayMicroseconds(1); uint32_t pins_off = ~*gpio_in; // update pin state // treat middle state (on-off matching) as no-update (use previous state) uint32_t pins_update = pins_on ^ pins_off; pins_state = (pins_state & (~pins_update)) | (pins_on & pins_update); // update button state uint8_t [MASK] = ((!!(pins_state & (1 << BUTTON_M1)))) | ((!!(pins_state & (1 << BUTTON_M2))) << 1) | ((!!(pins_state & (1 << BUTTON_M3))) << 2) | ((!!(pins_state & (1 << BUTTON_DPI))) << 3) | ((!!(pins_state & (1 << BUTTON_M4))) << 4) | ((!!(pins_state & (1 << BUTTON_M5))) << 5); // handle latch uint8_t ok_mask = ((buttons_latch[0] == 0)) | ((buttons_latch[1] == 0) << 1) | ((buttons_latch[2] == 0) << 2) | ((buttons_latch[3] == 0) << 3) | ((buttons_latch[4] == 0) << 4) | ((buttons_latch[5] == 0) << 5); //printf(""%u, %u, %u, %u\n"", ~pins_on, ~pins_off, pins_state, ok_mask); [MASK] = ( [MASK] & ok_mask) | (buttons & ~ok_mask); // update latch timings for (int i = 0; i < 6; i++) { if ((( [MASK] ^ buttons) >> i) & 1) buttons_latch[i] = buttons_latch_max; else if (buttons_latch[i]) buttons_latch[i] -= 1; } if (( [MASK] & (1 << 2)) != (buttons & (1 << 2))) which_m3 = 0; if (( [MASK] & (1 << 3)) != (buttons & (1 << 3))) which_m3 = 1; buttons = [MASK] ; } uint8_t wheel_state_a = 0; uint8_t wheel_state_b = 0; uint8_t wheel_state_output = 0; int8_t wheel_progress = 0; void update_wheel() { uint8_t wheel_new_a = digitalRead(ENCODER_A); uint8_t wheel_new_b = digitalRead(ENCODER_B); if (wheel_new_a != wheel_state_a || wheel_new_b != wheel_state_b) { if (wheel_new_a == wheel_new_b && wheel_state_output != wheel_new_a) { // when scrolling up, B changes first. when scrolling down, A changes first if (wheel_new_b == wheel_state_b) wheel_progress += 1; // the wheel can glitch and jump straight from 00 to 11 (or vice versa) // so we need to check that only one state has changed since the last test else if(wheel_new_a == wheel_state_a) wheel_progress -= 1; wheel_state_output = wheel_new_a; } wheel_state_a = wheel_new_a; wheel_state_b = wheel_new_b; } } int n = 0; int usb_hid_poll_interval = 1; struct MotionBurstData { uint8_t motion; uint8_t observation; int16_t x; int16_t y; uint8_t squal; uint8_t raw_sum; uint8_t raw_max; uint8_t raw_min; uint16_t shutter; }; MotionBurstData spi_read_motion_burst(bool do_update_wheel); int dpi = 12; // in hundreds; 1200 dpi int lod = 2; void check_config_inputs() { if ((buttons & 1) && (buttons & 2) && (buttons & 8) && (buttons & 16)) { int olddpi = dpi; if (wheel_progress < 0) dpi += dpi < 16 ? 1 : dpi < 32 ? 2 : dpi < 64 ? 4 : 8; else if (wheel_progress > 0) dpi -= dpi <= 16 ? 1 : dpi <= 32 ? 2 : dpi <= 64 ? 4 : 8; if (dpi > 120) dpi = 120; else if (dpi < 1) dpi = 1; if (olddpi != dpi) { spi_write(REG_CONFIG1, dpi - 1); printf(""new DPI: %d\n"", dpi * 100); } wheel_progress = 0; } } void loop() { // these execute nearly instantly // we want to call update_wheel roughly every 250ms to avoid skipping update_wheel(); delayMicroseconds(250); update_wheel(); int16_t x = 0; int16_t y = 0; // takes ~400us to execute; wheel is updated again around 250ms into the call MotionBurstData data = spi_read_motion_burst(true); if (mouse_inited && data.motion) { x = data.x; y = data.y; } update_wheel(); //uint32_t a = micros(); update_buttons(); //uint32_t b = micros(); //Serial.println(b - a); check_config_inputs(); int8_t wheel = wheel_progress; wheel_progress = 0; //uint32_t a = micros(); // this will return around 1ms after the last time it returned // which should be around 250us from now uint8_t new_buttons = buttons; if (which_m3) new_buttons = (new_buttons & 3) | ((new_buttons >> 1) & ~3); else new_buttons = (new_buttons & 7) | ((new_buttons >> 1) & ~7); mouse.update(x, y, new_buttons, wheel); //uint32_t b = micros(); //Serial.println(b - a); } void pmw3360_boot() { spi_write(REG_POWER_UP_RESET, 0x5A); delay(50); spi_read(0x02); spi_read(0x03); spi_read(0x04); spi_read(0x05); spi_read(0x06); srom_upload(); } void pmw3360_config() { spi_write(REG_CONFIG1, dpi - 1); } void spi_begin() { SPI.beginTransaction(spisettings); } void spi_end() { SPI.endTransaction(); } void spi_write(byte addr, byte data) { spi_begin(); digitalWrite(PIN_NCS, LOW); delayMicroseconds(1); // 120 nanoseconds; t_NCS-SCLK SPI.transfer(addr | 0x80); SPI.transfer(data); delayMicroseconds(35); // t_SCLK-NCS(write) digitalWrite(PIN_NCS, HIGH); spi_end(); delayMicroseconds(180); // max(t_SWW, t_SWR) } byte spi_read(byte addr) { spi_begin(); digitalWrite(PIN_NCS, LOW); delayMicroseconds(1); // 120 nanoseconds; t_NCS-SCLK SPI.transfer(addr & 0x7F); delayMicroseconds(160); // t_SRAD byte ret = SPI.transfer(0); delayMicroseconds(1); // 120 nanoseconds; t_SCLK-NCS(read) digitalWrite(PIN_NCS, HIGH); spi_end(); delayMicroseconds(20); // max(t_SRW, t_SRR) return ret; } MotionBurstData spi_read_motion_burst(bool do_update_wheel) { MotionBurstData ret = {0}; // this takes around 260us to execute; update scroll wheel again after calling it spi_write(REG_MOTION_BURST, 0x00); if (do_update_wheel) update_wheel(); spi_begin(); digitalWrite(PIN_NCS, LOW); delayMicroseconds(1); // 120 nanoseconds; t_NCS-SCLK SPI.transfer(REG_MOTION_BURST); delayMicroseconds(35); // t_SRAD_MOTBR ret.motion = SPI.transfer(0); ret.observation = SPI.transfer(0); ret.x = SPI.transfer(0); ret.x |= ((uint16_t)SPI.transfer(0)) << 8; ret.y = SPI.transfer(0); ret.y |= ((uint16_t)SPI.transfer(0)) << 8; ret.squal = SPI.transfer(0); // don't care about the rest; terminate digitalWrite(PIN_NCS, HIGH); delayMicroseconds(1); // t_BEXIT = 500ns; wait 1000ns (1us) /* ret.raw_sum = SPI.transfer(0); ret.raw_max = SPI.transfer(0); ret.raw_min = SPI.transfer(0); ret.shutter = SPI.transfer(0); ret.shutter |= ((uint16_t)SPI.transfer(0)) << 8; */ spi_end(); return ret; } void srom_upload() { spi_write(REG_CONFIG2, 0x00); spi_write(REG_SROM_ENABLE, 0x1D); delay(10); spi_write(REG_SROM_ENABLE, 0x18); spi_begin(); digitalWrite(PIN_NCS, LOW); delayMicroseconds(1); SPI.transfer(REG_SROM_LOAD_BURST | 0x80); delayMicroseconds(15); for(size_t i = 0; i < SROM_LENGTH; i += 1) { SPI.transfer(srom[i]); delayMicroseconds(15); } digitalWrite(PIN_NCS, HIGH); delayMicroseconds(1); spi_end(); delayMicroseconds(200); byte id = spi_read(REG_SROM_ID); mouse_inited = (id != 0xFF); printf(""\n""); printf(""srom id: ""); printf(""%d"", id); printf(""\n""); spi_write(REG_CONFIG2, 0x00); } ",next_buttons 24,"#include ""Application.h"" #include ""Config.h"" Application::Application() : m_Window(Window::Get()), m_FrameRate(0.0), m_AverageFrameTime(0.0), m_FrameCount(0), m_LastUpdate(0.0) { m_Window.Init(1366, 768, ""glBlocks""); m_Camera = Camera({0.0f, 0.0f, 2.0f}); m_Camera.OnResize(1366, 768); m_Renderer = new Renderer(); m_Dashboard = new Dashboard(&m_Camera); m_World = new World(); } Application::~Application() { delete m_Renderer; delete m_Dashboard; delete m_World; } void Application::Run() { Shader basicShader(VERTEX_SHADER, FRAGMENT_SHADER); basicShader.CreateShaderProgram(); Shader lightSourceShader(LIGHT_VERTEX_SHADER, LIGHT_FRAGMENT_SHADER); lightSourceShader.CreateShaderProgram(); m_Renderer->LoadShader(basicShader, ShaderType::BASIC_SHADER); m_Renderer->LoadShader(lightSourceShader, ShaderType::LIGHTSOURCE_SHADER); std::string texturePath = TEXTURE_PATH; texturePath += ""texture_atlas.png""; Texture atlas(GL_TEXTURE_2D, texturePath); atlas.Load(); atlas.Bind(GL_TEXTURE0); basicShader.Bind(); basicShader.SetInt(""uAtlasSize"", 4); m_World->GetGenerator().SetCamera(m_Camera); m_World->GetGenerator().Init(); m_Camera.SetPosition(0.0f, 70.0f, 0.0f); m_Camera.SendShader(basicShader); m_Camera.SendShader(lightSourceShader); auto [MASK] = std::bind(&Camera::OnResize, m_Camera, std::placeholders::_1, std::placeholders::_2); m_Window.AddResizeCallback( [MASK] ); m_Timer.Start(); while (!m_Window.ShouldClose()) { m_Camera.OnUpdate(m_Timer.GetDelta()); m_World->StepTime(m_Timer); m_World->GetGenerator().LoadChunks(); m_World->GetGenerator().PrepareChunks(m_Timer.GetDelta()); m_Renderer->Draw(*m_World, m_Camera); m_World->GetGenerator().SynchronizeChunks(); m_Dashboard->GetData(m_FrameRate, m_AverageFrameTime); m_Dashboard->Render(); m_Timer.RecordLapse(); CalcPerf(); m_Window.PollAndSwapBuffers(); } VertexArrayManager::Cleanup(); TerrainGenerator::Cleanup(); Dashboard::Cleanup(); Window::Cleanup(); LOG_INFO(""Ending...""); } void Application::CalcPerf() { m_FrameCount++; m_LastUpdate += m_Timer.GetDelta(); if (m_LastUpdate >= 1.0) { m_FrameRate = (double)m_FrameCount * 0.5 + m_FrameRate * 0.5; m_FrameCount = 0; m_AverageFrameTime = 1000.0 / (m_FrameRate == 0.0 ? 0.001 : m_FrameRate); m_LastUpdate = 0.0; } } ",resizeCallback 25,"#include #include #include #include #include #include #include using namespace std; char l[] = ""บบบบบ""; int i; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); COORD CursorPosition; void gotoxy(int x, int y) { CursorPosition.X = x; CursorPosition.Y = y; SetConsoleCursorPosition(console, CursorPosition); } void setcursor(bool visible, DWORD size) // set bool visible = 0 - invisible, bool visible = 1 - visible { if (size == 0) { size = 20; // default cursor size Changing to numbers from 1 to 20, decreases cursor width } CONSOLE_CURSOR_INFO lpCursor; lpCursor.bVisible = visible; lpCursor.dwSize = size; SetConsoleCursorInfo(console, & lpCursor); } void printBorder() { for (i = 2; i <= 79; i++) { gotoxy(i, 1); cout << '-'; gotoxy(i, 25); cout << '-'; } for (i = 1; i <= 25; i++) { gotoxy(2, i); cout << '|'; gotoxy(79, i); cout << '|'; } } void setplayers() { system(""cls""); printBorder(); gotoxy(4, 3); cout << ""SCORE : 0""; gotoxy(50, 3); cout << ""Press Esc key to quit game""; for (i = 3; i <= 78; i++) { gotoxy(i, 4); cout << '-'; } for (i = 0; i <= strlen(l); i++) { gotoxy(5, 5 + i); cout << l[i]; } for (i = 0; i <= strlen(l); i++) { gotoxy(76, 5 + i); cout << l[i]; } } void gameplay() { setplayers(); void displayMenu(); int sc = 0, pp = 0, st = 1; int c = 5, k = 5, x = 73, y = 6 + rand() % 15; int d = rand() % 2, px, py; int op = 1, go = 1; int [MASK] = 0, rlu = 0, lru = 0, lrd = 0; while (1) { if (go == 1) { while (!kbhit() && op) { px = x; py = y; gotoxy(x, y); cout << ""O""; Sleep(50); gotoxy(x, y); cout << "" ""; if (st == 1) { st = 0; if (d == 0) { x--; y++; } else { x--; y--; } } if ( [MASK] ) { x--; y++; } if (rlu) { x--; y--; } if (lru) { x++; y--; } if (lrd) { x++; y++; } if (x < px && y > py) [MASK] = 1; if (x < px && y < py) rlu = 1; if (y == 5 && rlu) { [MASK] = 1; rlu = 0; } if (y == 24 && [MASK] ) { rlu = 1; [MASK] = 0; } if (x == 6 && rlu) { lru = 1; rlu = 0; } if (x == 6 && [MASK] ) { lrd = 1; [MASK] = 0; } if (y == 5 && lru) { lrd = 1; lru = 0; } if (y == 24 && lrd) { lru = 1; lrd = 0; } if (x == 75 && lrd) { [MASK] = 1; lrd = 0; } if (x == 75 && lru) { rlu = 1; lru = 0; } if (x == 75 || x == 6) { Sleep(50); } if (y == 5 || y == 24) { Sleep(50); } if (lru || lrd) { if (y >= 6 && y <= 22) { if (y > k + strlen(l) - 3) { gotoxy(76, k + strlen(l)); cout << ""บ""; gotoxy(76, k); if (k != 4) cout << ' '; k++; } if (y < k + strlen(l) - 3) { gotoxy(76, k); cout << ""บ""; gotoxy(76, k + strlen(l)); if (k + strlen(l) != 25) cout << ' '; k--; } } } if (x == 6 && (y < c || y > c + strlen(l) - 1)) { gotoxy(x, y); cout << ""YOU LOSE ! Press 'r' or ENTER to play again !""; op = 0; break; } if (x == 6 && op == 1) { gotoxy(4, 3); cout << ""SCORE : "" << ++sc; } } } char ch = getch(); if (ch == ' ' && op == 1) { pp = 1; go = 0; gotoxy(22, 12); cout << ""GAME PAUSED ! PRESS ENTER to continue !""; } if (ch == 13 && pp && op == 1) { pp = 0; go = 1; gotoxy(22, 12); cout << "" ""; } if ((ch == 'r' || ch == 'R' || ch == 13) && op == 0) { op = 1; gameplay(); break; } if ((ch == 's' || ch == 'S' || ch == 80) && c <= 19 && op) { gotoxy(5, c + strlen(l)); cout << ""บ""; gotoxy(5, c); cout << ' '; c++; } if ((ch == 'w' || ch == 'W' || ch == 72) && c >= 6 && op) { gotoxy(5, c - 1); cout << ""บ""; gotoxy(5, c + 4); cout << ' '; c--; } if (ch == 27) { displayMenu(); break; } } } void displayMenu() { system(""cls""); void htpwindow(); // printBorder(); int cp = 1; gotoxy(34, 4); cout << ""PING PONG""; for (i = 8; i <= 73; i++) { gotoxy(i, 6); cout << '-'; } gotoxy(34, 10); cout << ""1. PLAY THE GAME""; gotoxy(34, 12); cout << ""2. HOW TO PLAY""; gotoxy(34, 14); cout << ""3. EXIT""; gotoxy(14, 16); cout << ""Enter Option from Menu: ""; char op = getche(); if (op == '1') gameplay(); if (op == '2') htpwindow(); if (op == '3') exit(0); } void htpwindow() { system(""cls""); printBorder(); gotoxy(4, 3); cout << ""INSTRUCTIONS""; gotoxy(4, 4); cout << ""-------------""; gotoxy(4, 5); cout << ""- Press w or Up Arrow to move up.""; gotoxy(4, 7); cout << ""- Press s or Down Arrow to move down.""; gotoxy(4, 9); cout << ""- Press Spacebar to pause the game.""; gotoxy(4, 11); cout << ""- Press Esc to quit the game.""; gotoxy(4, 15); cout << ""Press any key to go to menu ...""; getch(); displayMenu(); } int main() { setcursor(0, 0); srand((unsigned) time(NULL)); system(""cls""); // printBorder(); displayMenu(); return 0; } ",rld 26,"// Copyright 2023 Ar-Ray-code. // // 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 #include int SCS2host(const u_char data_l, const u_char [MASK] ) { bool END = 0; // SCS if (END) { return (data_l << 8) + [MASK] ; } else { return ( [MASK] << 8) + data_l; } } void read(u_char * write_buf, u_int write_buf_size) { auto port_handler_ = std::make_shared(""/dev/ttyUSB0""); auto packet_handler = std::make_shared(port_handler_); port_handler_->configure(1000000); if (!port_handler_->open()) { return; } std::string sent = """"; for (size_t i = 0; i < write_buf_size; i++) { sent += std::to_string(write_buf[i]) + "" ""; } std::cout << ""Write["" << write_buf_size << ""]: "" << sent << std::endl; const ssize_t write_ret = port_handler_->write( reinterpret_cast(write_buf), write_buf_size); if (write_ret == -1) { return; } using namespace std::chrono_literals; // NOLINT const auto clock_ = std::make_shared(RCL_SYSTEM_TIME); const auto started = clock_->now(); // while (port_handler_->getBytesAvailable() == 0) { // if (clock_->now() - started > 1s) { // std::cout << ""timeout"" << std::endl; // return; // } // } char read_buf[128]; const ssize_t read_ret = port_handler_->read(read_buf, sizeof(read_buf)); if (read_ret == -1) { return; } std::string recv = """"; for (long int i = 0; i < read_ret; i++) { recv += std::to_string(read_buf[i]) + "" ""; } std::cout << ""Read["" << read_ret << ""]: "" << recv << std::endl; auto data = SCS2host(read_buf[5], read_buf[6]); std::cout << ""Angle: "" << data << std::endl; port_handler_->close(); } u_char gen_checksum(u_char * write_buf, u_int write_buf_size) { u_char checksum = 0; for (size_t i = 2; i < write_buf_size - 1; i++) { checksum += write_buf[i]; } return ~checksum; } int main() { // u_char write_buf[8] = {0xFF, 0xFF, 0x01, 0x04, 0x02, 0x38, 0x02, 0x00}; u_char write_buf[8] = {0xFF, 0xFF, 0x01, 0x04, 0x02, 0x38, 0x02, 0x00}; write_buf[7] = gen_checksum(write_buf, sizeof(write_buf)); read(write_buf, sizeof(write_buf)); return EXIT_SUCCESS; } ",data_h 27,"#include ""stdafx.h"" #include #include ""Game.h"" #include ""../glew-2.1.0/include/GL/glew.h"" #include bool Game::leftPressed; bool Game::upPressed; bool Game::rightPressed; bool Game::downPressed; bool Game::spacePressed; float Game::xDelta; float Game::yDelta; void OnKeyboard(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_A) Game::leftPressed = action != GLFW_RELEASE; if (key == GLFW_KEY_W) Game::upPressed = action != GLFW_RELEASE; if (key == GLFW_KEY_D || key == GLFW_KEY_E) Game::rightPressed = action != GLFW_RELEASE; if (key == GLFW_KEY_S || key == GLFW_KEY_O) Game::downPressed = action != GLFW_RELEASE; if (key == GLFW_KEY_SPACE) Game::spacePressed = action != GLFW_RELEASE; if (key == GLFW_KEY_ESCAPE) glfwSetWindowShouldClose(window, true); } float oldPosX, oldPosY; void OnMouse(GLFWwindow* window, double posX, double [MASK] ) { Game::xDelta = oldPosX - posX; Game::yDelta = oldPosY - [MASK] ; oldPosX = posX; oldPosY = [MASK] ; } Game::Game(const char* title) { if (!glfwInit()){ printf(""GLFW init failed\n""); exit(1); } window = glfwCreateWindow(1280, 720, title, NULL, NULL); if (window == NULL) { printf(""GLFW window creation failed\n""); exit(1); } auto glfwWindow = (GLFWwindow*)window; glfwMakeContextCurrent(glfwWindow); glfwSetInputMode(glfwWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetKeyCallback(glfwWindow, OnKeyboard); glfwSetCursorPosCallback(glfwWindow, OnMouse); glfwGetWindowSize(glfwWindow, &viewportWidth, &viewportHeight); glEnable(GL_DEPTH_TEST); GLenum err = glewInit(); if (err != GLEW_OK) { std::cout << ""GLEW init failed "" << glewGetErrorString(err) << ""\n""; exit(1); } } Game::~Game() { glfwTerminate(); } void Game::Run(std::function renderFunction) { auto glwWindow = (GLFWwindow*)window; while (!glfwWindowShouldClose(glwWindow)) { glfwGetWindowSize(glwWindow, &viewportWidth, &viewportHeight); glViewport(0, 0, viewportWidth, viewportHeight); glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); time = glfwGetTime(); timeThisTick = time - lastTime; lastTime = time; renderFunction(); glfwSwapBuffers(glwWindow); glfwPollEvents(); } } void Game::RunTriangle() { Run([=]() { glBegin(GL_TRIANGLES); glColor3f(1.f, 0.f, 0.f); glVertex3f(-0.6f, -0.4f, 0.f); glColor3f(0.f, 1.f, 0.f); glVertex3f(0.6f, -0.4f, 0.f); glColor3f(0.f, 0.f, 1.f); glVertex3f(0.f, 0.6f, 0.f); glEnd(); }); }",posY 28,"#include int main() { int H, W, K; std::cin >> H >> W >> K; std::vector> c(H, std::vector(W)); for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) std::cin >> c[i][j]; auto print = [&](auto const &v) { for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) std::cout << v[i][j] << "", ""; std::cout << std::endl; } }; // print(c); int [MASK] = 0; // bit search for (int i = 0; i < (1 << H); i++) { for (int j = 0; j < (1 << W); j++) { int blacks = 0; for (int row = 0; row < H; row++) { for (int col = 0; col < W; col++) { bool white = c.at(row).at(col) == '.'; bool red = ((1 << row) & i) || ((1 << col) & j); if (red || white) continue; blacks++; } } if (blacks == K) [MASK] ++; } } std::cout << [MASK] << std::endl; } ",ans 29,"// client.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include ""pch.h"" #include #include #include //#pragma comment(lib, ""cpprest_2_10"") using namespace web; using namespace web::http; using namespace web::http::client; #include using namespace std; void display_json( json::value const & jvalue, utility::string_t const & prefix) { wcout << prefix << jvalue.serialize() << endl; } pplx::task make_task_request( http_client & client, method mtd, utility::string_t const & task, json::value const & jvalue) { return (mtd == methods::GET || mtd == methods::HEAD) ? client.request(mtd, task) : client.request(mtd, task, jvalue); } void make_request( http_client & client, method mtd, utility::string_t const & task, json::value const & jvalue) { make_task_request(client, mtd, task, jvalue) .then([](http_response response) { if (response.status_code() == status_codes::OK) { wcout << ""OK ""; return response.extract_json(); } wcout << ""FAIL ""; return pplx::task_from_result(json::value()); }) .then([](pplx::task previousTask) { try { display_json(previousTask.get(), L""R: ""); } catch (http_exception const & e) { wcout << e.what() << endl; } }) .wait(); } int main() { std::cout << ""Hello World! \nThis is client.""; http_client client(U(""http://localhost:5000/v1/tx40"")); utility::string_t task = L""state""; //* Get some specific parameters //auto getvalue = json::value::array(); //getvalue[0] = json::value::string(L""one""); //getvalue[1] = json::value::string(L""two""); //getvalue[2] = json::value::string(L""three""); //wcout << L""\nPOST (get some values)\n""; //display_json(getvalue, L""S: ""); //make_request(client, methods::POST, task, getvalue); ////* Delete a specific parameter //auto delvalue = json::value::array(); //delvalue[0] = json::value::string(L""one""); //wcout << L""\nDELETE (delete values)\n""; //display_json(delvalue, L""S: ""); //make_request(client, methods::DEL, task, delvalue); //wcout << L""\nPOST (get some values)\n""; //display_json(getvalue, L""S: ""); //make_request(client, methods::POST, task, getvalue); //* Get robot state auto nullvalue = json::value::null(); wcout << L""\nGET (get state)\n""; display_json(nullvalue, L""S: ""); make_request(client, methods::GET, L""state"", nullvalue); //* Put robot state auto putstate = json::value::boolean(true); // create parameters for request wcout << L""\nPUT (change state)\n""; display_json(putstate, L""S: ""); // display request make_request(client, methods::PUT, L""state"", putstate); // send request to server //* Get robot state wcout << L""\nGET (get state)\n""; display_json(nullvalue, L""S: ""); make_request(client, methods::GET, L""state"", nullvalue); //* Get robot position wcout << L""\nGET (get position)\n""; display_json(nullvalue, L""S: ""); make_request(client, methods::GET, L""position"", nullvalue); //* Put robot position auto [MASK] = json::value::object(); // create parameters for request [MASK] [L""x""] = 100; [MASK] [L""y""] = 200; [MASK] [L""z""] = 300; [MASK] [L""rx""] = 20; [MASK] [L""ry""] = 30; [MASK] [L""rz""] = 40; [MASK] [L""linhtinh""] = 50; wcout << L""\nPUT (add values)\n""; display_json( [MASK] , L""S: ""); // display request make_request(client, methods::PUT, L""position"", [MASK] ); // send request to server //* Get robot position wcout << L""\nGET (get position)\n""; display_json(nullvalue, L""S: ""); make_request(client, methods::GET, L""position"", nullvalue); return 0; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file ",putvalue 30,"#include #include #include #include ""time.h"" const char* ssid = """"; const char* wifi_password = """"; const char* mqtt_server = """"; const char* mqtt_pwd = """"; const char* mqtt_usr = """"; const char* mqtt_topic = """"; const char* mqtt_control_topic = """"; // NTP Servers: const char* ntpServer = ""pool.ntp.org""; // Principal NTP server const char* ntpBackup1 = ""time.google.com""; // Secondary NTP server const char* ntpBackup2 = ""time.nist.gov""; // Secondary NTP server const long gmtOffset_sec = 0; // Timezone offset in seconds const int daylightOffset_sec = 0; // Daylight offset in seconds IPAddress dns(8,8,8,8); const int PIR_SENSOR_OUTPUT_PIN = 21; /* PIR sensor O/P pin */ int warm_up; WiFiClient espClient; PubSubClient client(espClient); void setup() { Serial.begin(115200); /* Define baud rate for serial communication */ Serial.println(""Setting up wifi""); WiFi.mode(WIFI_STA); WiFi.begin(ssid, wifi_password); Serial.println(""Connecting""); while(WiFi.status() != WL_CONNECTED){ Serial.print("".""); delay(100); } Serial.println(); Serial.println(""Connected to WiFi network""); Serial.print(""Local ESP32 IP: ""); Serial.println(WiFi.localIP()); delay(2000); Serial.println(""Configure hour""); configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); delay(5000); Serial.println(printLocalTime()); struct tm timeinfo; if (!getLocalTime(&timeinfo)) { Serial.println(""Can't get the time""); } Serial.print(""Actual hour: ""); Serial.printf(""%02d:%02d:%02d\n"", timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec); delay(1000); Serial.println(""Setting up MQTT""); client.setServer(mqtt_server, 1883); reconnect(); String [MASK] = ""Connected to broker""; client.publish(mqtt_control_topic, [MASK] .c_str()); delay(2000); // Pin initialization for sensor reading Serial.println(""Setting up sensor settings""); pinMode(PIR_SENSOR_OUTPUT_PIN, INPUT); Serial.println(""Waiting For Power On Warm Up""); delay(5000); /* Power On Warm Up Delay */ } String printLocalTime(){ struct tm timeinfo; if(!getLocalTime(&timeinfo)){ Serial.println(""Failed to obtain time""); return """"; } char buffer[80]; strftime(buffer, 80, ""%Y-%m-%dT%H:%M:%S.000000Z"", &timeinfo); return buffer; } void reconnect() { // Retry connection while (!client.connected()) { Serial.print(""Connecting to MQTT...""); if (client.connect(""ESP32Client"", mqtt_usr, mqtt_pwd)) { Serial.println(""Connected.""); } else { Serial.print(""Error, rc=""); Serial.print(client.state()); Serial.println("" Retrying in 5 seconds...""); delay(5000); } } } void loop() { if (!client.connected()) { reconnect(); } StaticJsonDocument<200> doc; doc[""sensorName""] = ""pir""; doc[""startTime""] = printLocalTime(); int sensor_output; sensor_output = digitalRead(PIR_SENSOR_OUTPUT_PIN); if( sensor_output == LOW ){ Serial.print(""No object in sight\n\n""); doc[""detected""] = 0; }else{ Serial.print(""Object detected\n\n""); doc[""detected""] = 1; } char jsonBuffer[256]; serializeJson(doc, jsonBuffer); client.publish(mqtt_topic, jsonBuffer); delay(1000); }",message 31," #include #define PIN 6 // output to Neopixel #define NUM_LEDS 230 // 60 leds Per meter, so 60*4 Leds /* Chase1 Relative Setting */ #define CHASE1COLOR 0x0000FF // R,G,B #define CHASE1BRIGHTNESS 128 // Brightness(255:MAX, 0:MIN) #define CHASE1START 0 // the total length from the start point to the end one. #define CHASE1END 120 // the total length from the start point to the end one. #define CHASE1LENGTH 6 // length of every segment of chase 1 #define CHASE1GAP 2 // the gap between two adjacent segments for chase 1 #define CHASE1RATE 200 // Chase1 Slide Rate time : 500ms /* Chase2 Relative Setting */ #define CHASE2COLOR 0xFF0000 // R,G,B #define CHASE2BRIGHTNESS 255 // Brightness(255:MAX, 0:MIN) #define CHASE2START 125 // Start Pixel Point #define CHASE2END 229 // End Pixel Point. #define CHASE2LENGTH 2 // length of every segment of chase 2 #define CHASE2GAP 2 // the gap between two adjacent segments for chase 2 #define CHASE2RATE 400 // Chase2 Slide Rate time : 500ms // Chase Flow rate #define CHASERATE 500 // Rate time : 500ms Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800); unsigned short TotalStrip[NUM_LEDS]; // Pixel Buffer #define GAP 0 #define CHASE1 1 #define CHASE2 2 /* * It builds Strip buffer as your chase requirements */ void InitBuildStrip() { unsigned short nChase1Seg = (CHASE1END - CHASE1START) + 1; unsigned short nChase2Seg = (CHASE2END - CHASE2START) + 1; unsigned short nBlankCnt = (CHASE2START - CHASE1END) - 1; uint8_t Chase1Cnt = nChase1Seg / (CHASE1LENGTH + CHASE1GAP); uint8_t [MASK] = nChase1Seg % (CHASE1LENGTH + CHASE1GAP); uint8_t Chase2Cnt = nChase2Seg / (CHASE2LENGTH + CHASE2GAP); uint8_t Chase2Rem = nChase2Seg % (CHASE2LENGTH + CHASE2GAP); uint8_t i, j, k, l; uint8_t nSeek = 0; if(CHASE1START > 0) { for(i = 0; i < (CHASE1START - 1); i++) TotalStrip[nSeek + k] = GAP; } nSeek = CHASE1START; for(j = 0; j < Chase1Cnt; j++) { for(k = 0; k < CHASE1GAP; k++) TotalStrip[nSeek + k] = GAP; for(k = 0; k < CHASE1LENGTH; k++) TotalStrip[(nSeek + CHASE1GAP) + k] = CHASE1; nSeek += (CHASE1LENGTH + CHASE1GAP); } if( [MASK] > 0) { if( [MASK] < CHASE1GAP) for(k = 0; k < [MASK] ; k++) TotalStrip[nSeek + k] = GAP; else { for(k = 0; k < CHASE1GAP; k++) TotalStrip[nSeek + k] = GAP; for( ; k < [MASK] ; k++) TotalStrip[nSeek + k] = CHASE1; } } nSeek = CHASE1END + 1; for(i = 0; i < nBlankCnt; i++) TotalStrip[nSeek + i] = GAP; nSeek = CHASE2START; // Chase2 Segment for(j = 0; j < Chase2Cnt; j++) { for(k = 0; k < CHASE2GAP; k++) TotalStrip[nSeek + k] = GAP; for(k = 0; k < CHASE2LENGTH; k++) TotalStrip[(nSeek + CHASE2GAP) + k] = CHASE2; nSeek += (CHASE2LENGTH + CHASE2GAP); } if(Chase2Rem > 0) { if(Chase2Rem < CHASE2GAP) for(k = 0; k < Chase2Rem; k++) TotalStrip[nSeek + k] = GAP; else { for(k = 0; k < CHASE2GAP; k++) TotalStrip[nSeek + k] = GAP; for( ; k < Chase2Rem; k++) TotalStrip[nSeek + k] = CHASE2; } } nSeek = CHASE2END + 1; if(CHASE2END < NUM_LEDS - 1) { for(i = (CHASE2END + 1); i < NUM_LEDS; i++) TotalStrip[i] = GAP; } } /* * */ void SlideChase1(uint8_t nDist) { uint8_t temp = TotalStrip[CHASE1END]; uint8_t idx; for(idx = CHASE1END; idx > CHASE1START; idx--) TotalStrip[idx] = TotalStrip[idx - 1]; TotalStrip[idx] = temp; } void SlideChase2(uint8_t nDist) { uint8_t temp = TotalStrip[CHASE2END]; uint8_t idx; for(idx = CHASE2END; idx > CHASE2START; idx--) TotalStrip[idx] = TotalStrip[idx - 1]; TotalStrip[idx] = temp; } /* * */ void DrawStrip() { unsigned short idx = 0; uint32_t color; for(idx = 0; idx < NUM_LEDS; idx++) { switch(TotalStrip[idx]) { case GAP: { color = strip.Color(0x00, 0x00, 0x00); // BLACK color } break; case CHASE1: { color = strip.Color(((CHASE1COLOR >> 16) * CHASE1BRIGHTNESS) >> 8, (((CHASE1COLOR >> 8) & 0xFF) * CHASE1BRIGHTNESS) >> 8, ((CHASE1COLOR & 0xFF) * CHASE1BRIGHTNESS) >> 8); } break; case CHASE2: { color = strip.Color(((CHASE2COLOR >> 16) * CHASE2BRIGHTNESS) >> 8, (((CHASE2COLOR >> 8) & 0xFF) * CHASE2BRIGHTNESS) >> 8, ((CHASE2COLOR & 0xFF) * CHASE2BRIGHTNESS) >> 8); } break; } strip.setPixelColor(idx, color); } } void setup() { Serial.begin(19200); Serial.println(F(""Program Started!"")); delay(1000); InitBuildStrip(); strip.setBrightness(255); strip.begin(); strip.show(); // Initialize all pixels to 'off' // Serial.println(F(""Init End!"")); DrawStrip(); strip.show(); // Initialize all pixels to 'off' } static uint32_t nSlide1Time = millis(); static uint32_t nSlide2Time = millis(); static uint32_t nScanTime = millis(); void loop() { if(nSlide1Time + CHASE1RATE < millis()) { nSlide1Time = millis(); SlideChase1(1); } if(nSlide2Time + CHASE2RATE < millis()) { nSlide2Time = millis(); SlideChase2(1); } if(nScanTime + 20 < millis()) { nScanTime = millis(); DrawStrip(); strip.show(); } } ",Chase1Rem 32,"#include ""operators/G2BMM.h"" namespace infini { G2BMMObj::G2BMMObj(GraphObj *graph, Tensor A, Tensor B, Tensor C, int width, int dilation, [[maybe_unused]] Tensor bias, ActType act) : OperatorObj(OpType::G2BMM, {A, B}, {C}), width(width), dilation(dilation), act(act), b(A->getDims()[0]), m(A->getDims()[1]), k(A->getDims()[2]) { IT_ASSERT(checkValid(graph)); } string G2BMMObj::toString() const { std::ostringstream os; os << ""G2BMM(["" << ""width="" << width << "",act="" << enum_to_underlying(act) << ""],A="" << inputs[0]->getGuid() << "",B="" << inputs[1]->getGuid() << "",C="" << outputs[0]->getGuid() << "", TTbmnkd: "" << this->getB() << "", "" << this->getM() << "", "" << this->getWidth() << "", "" << inputs[1]->getDims()[2] << "", "" << this->getDilation() << "")""; return os.str(); } optional> G2BMMObj::inferShape(const TensorVec &inputs) { auto A = inputs[0], B = inputs[1]; b = A->getDims()[0]; m = A->getDims()[1]; k = A->getDims()[2]; IT_ASSERT(A->getRank() == 3 && B->getRank() == 3); IT_ASSERT(A->getDims()[0] == B->getDims()[0]); IT_ASSERT(A->getDims()[1] == B->getDims()[1]); IT_ASSERT(A->getDims()[2] == B->getDims()[2]); IT_ASSERT(width >= 0); int n(2 * width + 1); return {{{b, m, n}}}; } vector G2BMMObj::getWorkloadVector() const { return {type.underlying(), b, m, k, width, dilation, enum_to_underlying(act)}; } vector G2BMMObj::getOpAttrVector() const { return {type.underlying(), width, dilation, enum_to_underlying(act)}; } double G2BMMObj::getComputeTime() const { int64_t batchSize = getB(); int64_t seqLength = getM(); int64_t featureDim = getK(); int64_t windowWidth = getWidth(); int64_t dilationFactor = getDilation(); int64_t outputWidth = 2 * windowWidth + 1; double multiplyAddOps = batchSize * seqLength * outputWidth * featureDim; double dilationPenalty = std::log2(dilationFactor + 1) * 0.1 + 1.0; double actCost = 0.0; if (act != ActType::None) { actCost = batchSize * seqLength * outputWidth * 0.1; } double totalOps = multiplyAddOps * dilationPenalty + actCost; return totalOps / 2e9; } double G2BMMObj::getMemoryCost() const { double costA = inputs[0]->size(); double costB = inputs[1]->size(); double [MASK] = outputs[0]->size(); double memoryEfficiencyFactor = 1.0 + dilation * 0.05; return (costA + costB) * memoryEfficiencyFactor + [MASK] ; } double G2BMMObj::getParallelism() const { int64_t batchParallel = getB(); int64_t seqParallel = getM(); int64_t windowParallel = std::min(2 * width + 1, 8); double totalParallelism = batchParallel * seqParallel * windowParallel; const double MAX_PARALLEL_UNITS = 2048.0; return std::min(totalParallelism, MAX_PARALLEL_UNITS); } } // namespace infini",costC 33,"#include ""CudaContext.h"" #include //std::runtime_error #include #include ""Shin/Utilities/GraphicsUtility.h"" CudaContext::CudaContext() : m_context(nullptr) { } //--------------------------------------------------------------------------------------------------------------------- CudaContext::~CudaContext() { } //--------------------------------------------------------------------------------------------------------------------- void CudaContext::Init(const VkInstance instance, VkPhysicalDevice [MASK] ) { CUdevice dev; CUresult result = CUDA_SUCCESS; bool foundDevice = true; result = cuInit(0); if (result != CUDA_SUCCESS) { throw std::runtime_error(""Failed to cuInit()""); } int numDevices = 0; result = cuDeviceGetCount(&numDevices); if (result != CUDA_SUCCESS) { throw std::runtime_error(""Failed to get count of CUDA devices""); } CUuuid id = {}; std::array deviceUUID; GraphicsUtility::GetPhysicalDeviceUUIDInto(instance, [MASK] , &deviceUUID); /* * Loop over the available devices and identify the CUdevice * corresponding to the physical device in use by this Vulkan instance. * This is required because there is no other way to match GPUs across * API boundaries. */ for (int i = 0; i < numDevices; i++) { cuDeviceGet(&dev, i); cuDeviceGetUuid(&id, dev); if (!std::memcmp(static_cast(&id), static_cast(deviceUUID.data()), sizeof(CUuuid))) { foundDevice = true; break; } } if (!foundDevice) { throw std::runtime_error(""Failed to get an appropriate CUDA device""); } result = cuCtxCreate(&m_context, 0, dev); if (result != CUDA_SUCCESS) { throw std::runtime_error(""Failed to create a CUDA context""); } } //--------------------------------------------------------------------------------------------------------------------- void CudaContext::CleanUp() { if (nullptr != m_context) { cuCtxDestroy(m_context); m_context = nullptr; } } ",physicalDevice 34,"#include ""ActionToolTipComponent.h"" #include ""PositionYTween.h"" #include ""ResourceContainer.h"" #include ""SpriteAlphaTween.h"" #include ""SpriteComponent.h"" #include ""StageConstitution.h"" using RC = ResourceContainer; using namespace base_engine; std::weak_ptr ActionToolTipComponent::Create( Actor* owner, const std::weak_ptr& machine) { if (const auto tooltip = owner->GetComponent(); !tooltip.expired()) { return tooltip; } const auto [MASK] = new ActionToolTipComponent(owner); const auto tooltip = new Actor(owner->GetGame()); owner->AddChild(tooltip->GetId()); [MASK] ->panel_ = owner->GetGame()->GetActor(tooltip->GetId()); [MASK] ->sprite_ = new SpriteComponent(tooltip, 200); const auto img = *RC::GetResource(""ActionTooltip""); tooltip->SetPosition(owner->GetPosition() + Vector2{64, -32}); [MASK] ->sprite_->SetAlignment(Mof::TEXALIGN_CENTERCENTER) .SetColor(MOF_ARGB(0, 255, 255, 255)) .SetImage(img); return owner->GetComponent(); } constexpr float kFadeInTime = 0.25f; constexpr float kFadeOutTime = 0.25f; void ActionToolTipComponent::Show() { open_ = true; if (play_animation_) return; if (is_show_) return; if (panel_.expired()) return; play_animation_ = true; ma_tween::PositionYTween::TweenLocalPositionY( panel_.lock().get(), owner_->GetPosition().y - stage::kStageCellSize.y * 0.5f, kFadeInTime) .SetEase(EaseType::kInsine); ma_tween::SpriteAlphaTween::Tween(panel_.lock().get(), 255, kFadeInTime) .SetOnComplete([this] { is_show_ = true; play_animation_ = false; }); } void ActionToolTipComponent::Hide() { if (play_animation_) return; if (!is_show_) return; if (panel_.expired())return; play_animation_ = true; ma_tween::PositionYTween::TweenLocalPositionY( panel_.lock().get(), owner_->GetPosition().y + 32, kFadeOutTime) .SetEase(EaseType::kInsine); ma_tween::SpriteAlphaTween::Tween(panel_.lock().get(), 0, kFadeOutTime) .SetOnComplete([this] { is_show_ = false; play_animation_ = false; }); } void ActionToolTipComponent::Update() { if (open_ == false) { count_frame_++; if (count_frame_ > 5) { Hide(); } } else { count_frame_ = 0; } open_ = false; } ",tooltip_component 35,"/* Copyright 2015 Google LLC All rights reserved. Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* american fuzzy lop - LLVM-mode instrumentation pass --------------------------------------------------- Written by <> and <> LLVM integration design comes from Laszlo Szekeres. C bits copied-and-pasted from afl-as.c are Michal's fault. This library is plugged into LLVM when invoking clang through afl-clang-fast. It tells the compiler to add code roughly equivalent to the bits discussed in ../afl-as.h. */ #define AFL_LLVM_PASS #include ""../include/config.h"" #include ""../include/debug.h"" #include #include #include #include #include #include #include #include #include #include #include ""llvm/ADT/Statistic.h"" #include ""llvm/IR/IRBuilder.h"" #include ""llvm/IR/LegacyPassManager.h"" #include ""llvm/IR/Module.h"" #include ""llvm/Support/Debug.h"" #include ""llvm/IR/DebugInfoMetadata.h"" #include ""llvm/Transforms/IPO/PassManagerBuilder.h"" #include ""../rustc-demangle/crates/capi/include/rustc_demangle.h"" using namespace llvm; #define TARGETS_TYPE std::unordered_map> namespace { class AFLCoverage : public ModulePass { public: static char ID; AFLCoverage() : ModulePass(ID) {} bool runOnModule(Module &M) override; // Global variables GlobalVariable *AFLMapPtr; GlobalVariable *AFLPrevLoc; unsigned int inst_ratio; // Types Type *VoidTy; PointerType *Int8PtrTy; IntegerType *Int8Ty; IntegerType *Int16Ty; IntegerType *Int32Ty; IntegerType *Int64Ty; PointerType *Int64PtrTy; // Store mapping data from basicblock location to ID std::ofstream bbToID; u16 *get_ID_ptr(); static void get_debug_loc(const Instruction *I, std::string &Filename, unsigned &Line); static void load_instr_targets(TARGETS_TYPE &bb_targets, TARGETS_TYPE &func_targets); // -1: not checking, 0: not targets, 1: target BBs, 2: target functions static u8 is_target_loc(std::string codefile, unsigned line, TARGETS_TYPE &bb_targets, TARGETS_TYPE &func_targets); u8 check_code_language(std::string codefile); void printFuncLog(std::string filename, unsigned line, u16 evtID, std::string func_name); void printBBLog(std::string filename, unsigned line, u16 evtID); }; } /*** * Load identified interesting basicblocks(targets) to instrument ***/ void AFLCoverage::load_instr_targets(TARGETS_TYPE &bb_targets, TARGETS_TYPE &func_targets) { char *target_file = getenv(""TARGETS_FILE""); if (!target_file) { target_file = (char *)""/opt/instrumentor/instr-targets.txt""; } std::ifstream targetsfile(target_file); if (!targetsfile.is_open()) { outs() << ""[!!] Fail to open targets file"" << ""\n""; return; } std::string line; std::string codefile; int num = 0; while (std::getline(targetsfile, line)) { if (num % 3 == 0) { codefile = line; } else if (num % 3 == 1) { std::stringstream ss(line); std::string item; while (std::getline(ss, item, ' ')) { bb_targets[codefile].insert(std::stoi(item)); } } else { std::stringstream ss(line); std::string item; while (std::getline(ss, item, ' ')) { func_targets[codefile].insert(std::stoi(item)); } } ++num; } targetsfile.close(); } /*** * Check if current location is target: 1 for BB, 2 for function, 0 for not targets, -1 for not checking ***/ u8 AFLCoverage::is_target_loc(std::string codefile, unsigned line, TARGETS_TYPE &bb_targets, TARGETS_TYPE &func_targets) { if (bb_targets.count(codefile)) { std::set locs = bb_targets[codefile]; for (auto ep = locs.begin(); ep != locs.end(); ep++) { if (*ep == line) { bb_targets[codefile].erase(line); return 1; } } } if (func_targets.count(codefile)) { std::set locs = func_targets[codefile]; for (auto ep = locs.begin(); ep != locs.end(); ep++) { if (*ep == line) { func_targets[codefile].erase(line); return 2; } } } return 0; } /*** * Get filename and location given one instruction ***/ void AFLCoverage::get_debug_loc(const Instruction *I, std::string &Filename, unsigned &Line) { if (DILocation *Loc = I->getDebugLoc()) { Line = Loc->getLine(); Filename = Loc->getFilename().str(); char *path = realpath(Filename.c_str(), NULL); if (path) { Filename = std::string(path); } else { std::string dir = Loc->getDirectory().str(); if (dir.size() > 0) { Filename = dir + ""/"" + Filename; } } if (Filename.empty()) { DILocation *oDILoc = Loc->getInlinedAt(); if (oDILoc) { Line = oDILoc->getLine(); Filename = oDILoc->getFilename().str(); char *path = realpath(Filename.c_str(), NULL); if (path) { Filename = std::string(path); } else { std::string dir = Loc->getDirectory().str(); if (dir.size() > 0) { Filename = dir + ""/"" + Filename; } } } } } } /*** * Assign event ID in increasing order, instead of random assignment in AFL ***/ u16 *AFLCoverage::get_ID_ptr() { // Create the shared memory if it does not exist, otherwise get the existing one int [MASK] = shmget((key_t)SHM_ID_KEY, sizeof(u16), IPC_CREAT | IPC_EXCL | 0666); if ( [MASK] != 0) { [MASK] = shmget((key_t)SHM_ID_KEY, sizeof(u16), 0666); } // FIXME: If compilation is done in Docker (in subsequent RUN layers), the // shared memory is not carried over between layers, so IDs will conflict u16 *_id_ptr; if ( [MASK] >= 0) { _id_ptr = (u16 *)shmat( [MASK] , NULL, 0); if (_id_ptr == (u16 *)-1) { ABORT(""!!! shared memory error: fail to connect""); _exit(1); } return _id_ptr; } else { ABORT(""!!! shared memory error: fail to create""); _exit(1); } } u8 AFLCoverage::check_code_language(std::string codefile) { // Check if the code is written in Rust (return 1) or C/C++ (return 2) if (codefile.find("".rs"") != std::string::npos) { return 1; } else { return 2; } } /*** * Print compilation log ***/ void AFLCoverage::printFuncLog(std::string filename, unsigned line, u16 evtID, std::string func_name) { OKF(""Instrument %u at %s: at line %u for function %s"", evtID, filename.c_str(), line, func_name.c_str()); bbToID << evtID << "": at "" << filename << "" ; at line "" << line << "" for function "" << func_name << std::endl; } void AFLCoverage::printBBLog(std::string filename, unsigned line, u16 evtID) { bbToID << evtID << "": at "" << filename << "" ; at line "" << line << "" for block"" << std::endl; OKF(""Instrument %u at %s: at line %u for block"", evtID, filename.c_str(), line); } char AFLCoverage::ID = 0; bool AFLCoverage::runOnModule(Module &M) { LLVMContext &C = M.getContext(); VoidTy = Type::getVoidTy(C); Int8PtrTy = Type::getInt8PtrTy(C); Int8Ty = IntegerType::getInt8Ty(C); Int16Ty = IntegerType::getInt16Ty(C); Int32Ty = IntegerType::getInt32Ty(C); Int64Ty = IntegerType::getInt64Ty(C); Int64PtrTy = Type::getInt64PtrTy(C); bbToID.open(""/opt/instrumentor/BB2ID.txt"", std::ofstream::out | std::ofstream::app); if (!bbToID.is_open()) { bbToID.open(""./BB2ID.txt"", std::ofstream::out | std::ofstream::app); } /* Show a banner */ // char be_quiet = 0; if (isatty(2) && !getenv(""AFL_QUIET"")) { SAYF(cCYA ""afl-llvm-pass "" cBRI VERSION cRST "" by <>\n""); } /* Decide the size of instrumented functions */ char *instr_func_size_str = getenv(""INST_FUNC_SIZE""); // Set one large number to disable it if the environment variable is not set unsigned int instr_func_size = 65536; if (instr_func_size_str) { if (sscanf(instr_func_size_str, ""%u"", &instr_func_size) != 1) FATAL(""Bad value of INST_FUNC_SIZE""); } if (getenv(""USE_TRADITIONAL_BRANCH"")){ /* Decide instrumentation ratio */ char *inst_ratio_str = getenv(""AFL_INST_RATIO""); inst_ratio = 100; if (inst_ratio_str) { if (sscanf(inst_ratio_str, ""%u"", &inst_ratio) != 1 || !inst_ratio || inst_ratio > 100) FATAL(""Bad value of AFL_INST_RATIO (must be between 1 and 100)""); } /* Get globals for the SHM region and the previous location. Note that __afl_prev_loc is thread-local. */ AFLMapPtr = new GlobalVariable(M, PointerType::get(Int8Ty, 0), false, GlobalValue::ExternalLinkage, 0, ""__afl_area_ptr""); AFLPrevLoc = new GlobalVariable( M, Int32Ty, false, GlobalValue::ExternalLinkage, 0, ""__afl_prev_loc"", 0, GlobalVariable::GeneralDynamicTLSModel, 0, false); } int inst_blocks = 0; TARGETS_TYPE bb_targets, func_targets; load_instr_targets(bb_targets, func_targets); u8 codeLang = 0; static const std::string Xlibs(""/usr/""); // static const std::string Clibs(""/rustc/""); for (auto &F : M) { // Label if this function is instrumented bool isTargetFunc = false; std::string filename; unsigned line = 0; for (auto &BB : F) { BasicBlock::iterator IP = BB.getFirstInsertionPt(); // in each basic block, check if it is a target bool isTargetBB = false; for (auto &I : BB) { get_debug_loc(&I, filename, line); if (filename.empty() || line == 0 || !filename.compare(0, Xlibs.size(), Xlibs)) { continue; } // printf(""filename: %s, line: %u\n"", filename.c_str(), line); /* check if target locations */ u8 isTarget = is_target_loc(filename, line, bb_targets, func_targets); if (isTarget == 1) { isTargetBB = true; } else if (isTarget == 2) { isTargetFunc = true; } } /* skip if no target found or instrumented, and also not selected */ if (!isTargetBB && AFL_R(100) >= inst_ratio) { continue; } /* instrument starting block point */ IRBuilder<> IRB(&(*IP)); if (isTargetBB) { u16 *evtIDPtr = get_ID_ptr(); u16 evtID = *evtIDPtr; Value *evtValue = ConstantInt::get(Int16Ty, evtID); auto *helperTy_stack = FunctionType::get(VoidTy, Int16Ty); auto helper_stack_start = M.getOrInsertFunction(""track_blocks"", helperTy_stack); IRB.CreateCall(helper_stack_start, {evtValue}); /* store BB ID info */ printBBLog(filename, line, evtID); /* increase counter */ *evtIDPtr = ++evtID; } if (getenv(""USE_TRADITIONAL_BRANCH"")){ // Instrument all basicblocks to compute AFL feedback unsigned int cur_loc = AFL_R(MAP_SIZE); ConstantInt *CurLoc = ConstantInt::get(Int32Ty, cur_loc); /* Load prev_loc */ LoadInst *PrevLoc = IRB.CreateLoad(AFLPrevLoc); PrevLoc->setMetadata(M.getMDKindID(""nosanitize""), MDNode::get(C, None)); Value *PrevLocCasted = IRB.CreateZExt(PrevLoc, IRB.getInt32Ty()); /* Load SHM pointer */ LoadInst *MapPtr = IRB.CreateLoad(AFLMapPtr); MapPtr->setMetadata(M.getMDKindID(""nosanitize""), MDNode::get(C, None)); Value *MapPtrIdx = IRB.CreateGEP(MapPtr, IRB.CreateXor(PrevLocCasted, CurLoc)); /* Update bitmap */ LoadInst *Counter = IRB.CreateLoad(MapPtrIdx); Counter->setMetadata(M.getMDKindID(""nosanitize""), MDNode::get(C, None)); Value *Incr = IRB.CreateAdd(Counter, ConstantInt::get(Int8Ty, 1)); IRB.CreateStore(Incr, MapPtrIdx) ->setMetadata(M.getMDKindID(""nosanitize""), MDNode::get(C, None)); /* Set prev_loc to cur_loc >> 1 */ StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int32Ty, cur_loc >> 1), AFLPrevLoc); Store->setMetadata(M.getMDKindID(""nosanitize""), MDNode::get(C, None)); } inst_blocks++; } /* Instrument function if it is one target or the size is above threshold */ // if (isTargetFunc || F.getInstructionCount() > instr_func_size) if (isTargetFunc) { /* get inserting point: first inserting point of the entry block */ BasicBlock *BB = &F.getEntryBlock(); Instruction *InsertPoint = &(*(BB->getFirstInsertionPt())); IRBuilder<> IRB(InsertPoint); /* get evt ID */ u16 *evtIDPtr = get_ID_ptr(); u16 evtID = *evtIDPtr; Value *evtValue = ConstantInt::get(Int16Ty, evtID); auto *helperTy_func = FunctionType::get(VoidTy, Int16Ty); auto helper_func = M.getOrInsertFunction(""track_functions"", helperTy_func); IRB.CreateCall(helper_func, {evtValue}); /* store event ID info */ get_debug_loc(&(*InsertPoint), filename, line); std::string func_name = F.getName().str(); if (codeLang == 0) { codeLang = check_code_language(filename); } if (codeLang == 2) { int demangled_status = -1; char *demangled_char = abi::__cxa_demangle(F.getName().data(), nullptr, nullptr, &demangled_status); if (demangled_status == 0) { func_name = demangled_char; } } else { int demangled_status = -1; char *demangled_char = rustc_demangle(F.getName().data(), &demangled_status); if (demangled_status == 0) { func_name = demangled_char; } } printFuncLog(filename, line, evtID, func_name); /* increase counter */ *evtIDPtr = ++evtID; inst_blocks++; } } return true; } static void registerAFLPass(const PassManagerBuilder &, legacy::PassManagerBase &PM) { PM.add(new AFLCoverage()); } static RegisterStandardPasses RegisterAFLPass( PassManagerBuilder::EP_ModuleOptimizerEarly, registerAFLPass); static RegisterStandardPasses RegisterAFLPass0( PassManagerBuilder::EP_EnabledOnOptLevel0, registerAFLPass); ",shmid 36," using namespace std; using namespace cv; using namespace TgBot; namespace travisFilter { enum paramNumbers { contrast = 0, brightness = 1, gamma = 2, yellow = 3, grain = 4 }; void correction(Mat &img, double alpha_, int beta_, double [MASK] ) { Mat res1; img.convertTo(res1, -1, alpha_, beta_); CV_Assert( [MASK] >= 0); Mat lookUpTable(1, 256, CV_8U); uchar *p = lookUpTable.ptr(); for (int i = 0; i < 256; ++i) p[i] = saturate_cast(pow(i / 255.0, [MASK] ) * 255.0); Mat res = img.clone(); LUT(res1, lookUpTable, res); img = res.clone(); } void addGrain(Mat &img, int depth) { using namespace std::experimental::fundamentals_v2; for (int i = 0; i < img.rows; i++) for (int j = 0; j < img.cols; j++) { int a = img.at(i, j)[0] + randint(-1 * depth, depth), b = img.at(i, j)[1] + randint(-1 * depth, depth) / 2, c = img.at(i, j)[2] + randint(-1 * depth, depth) / 1.5; if (a < 0) a = 0; if (b < 0) b = 0; if (c < 0) c = 0; if (a > UCHAR_MAX) a = UCHAR_MAX; if (b > UCHAR_MAX) b = UCHAR_MAX; if (c > UCHAR_MAX) c = UCHAR_MAX; img.at(i, j)[0] = a; img.at(i, j)[1] = b; img.at(i, j)[2] = c; } } void addYellow(Mat &img, int depth) { for (int i = 0; i < img.rows; i++) for (int j = 0; j < img.cols; j++) { (-depth, depth); int a = img.at(i, j)[0], b = img.at(i, j)[1], c = img.at(i, j)[2]; int S = (a + b + c) / 3; a -= 5; b = b + 0.15 * (S + depth); c = c + 0.30 * S; if (a < 0) a = 0; if (b < 0) b = 0; if (c < 0) c = 0; if (a > UCHAR_MAX) a = UCHAR_MAX; if (b > UCHAR_MAX) b = UCHAR_MAX; if (c > UCHAR_MAX) c = UCHAR_MAX; img.at(i, j)[0] = a; img.at(i, j)[1] = b; img.at(i, j)[2] = c; } } Mat filter(Mat *img_original, vector p) { try { using namespace travisFilter; //resize(img_original, img_original, Size(0, 0), 0.5, 0.5, INTER_LINEAR); if (img_original->empty()) { cout << ""Could not open or find the image!\n"" << ""\n""; } Mat img_corrected = img_original->clone(); //brightness and contrast filter correction(img_corrected, p[paramNumbers::brightness] / 100.0, p[paramNumbers::contrast] - 100, p[paramNumbers::gamma] / 100.0); //adding random noises addGrain(img_corrected, p[paramNumbers::grain]); // adding some yellow tone addYellow(img_corrected, p[paramNumbers::yellow]); // blur GaussianBlur(img_corrected, img_corrected, Size(1, 1), 0, 0); return img_corrected; } catch (cv::Exception cvException) { cout << cvException.what() << ""\n""; } catch (std::exception stdException) { cout << stdException.what() << ""\n""; } catch (...) { cout << ""unknown error\n""; } } } ",gamma_ 37,"#include // EXIT_SUCCESS #include // SIGINT, signal #include // cin, cout, endl #include // string #include // O_WRONLY #include // mmap, shm_open, PROT_WRITE #include // ftruncate // Name of shared memory object. #define SHM_NAME ""comm-file"" // Size of shard memory object. // Give enough space to store 10 signed integers. #define SHM_SIZE 10 * sizeof(int) void handle_shutdown(int signal) { std::string response; std::cout << std::endl; do { std::cout << ""Shutdown client? [y/n] ""; std::cin >> response; if (response == ""y"" || response == ""Y"") { exit(EXIT_SUCCESS); } } while(response != ""n"" && response != ""N""); } int main(int arg_c, char** arg_v) { // Set up shutdown handler to terminate program correctly. signal(SIGINT, handle_shutdown); // Create shared memory object, get file descriptor. // TODO: Check that a server is active and has created the shared memory! int [MASK] = shm_open(SHM_NAME, O_WRONLY, 0666); // Memory map the shared memory object. int* data = (int*)mmap(0, SHM_SIZE, PROT_WRITE, MAP_SHARED, [MASK] , 0); // Poll for new messages to send and store in shared memory. while(true) { std::cout << ""Message to server: ""; // TODO: Put checks that what is read from console is actually an // integer! std::cin >> data[0]; } return EXIT_SUCCESS; } ",shared_memory 38,"// Fill out your copyright notice in the Description page of Project Settings. #include ""Deadzone.h"" #include ""Components/BoxComponent.h"" #include ""GameFramework/PlayerController.h"" #include ""GameFramework/ProjectileMovementComponent.h"" #include ""GameFramework/Character.h"" // Sets default values ADeadzone::ADeadzone() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; // Create the collision box component CollisionBox = CreateDefaultSubobject(TEXT(""CollisionBox"")); RootComponent = CollisionBox; // Bind the overlap function CollisionBox->OnComponentBeginOverlap.AddDynamic(this, &ADeadzone::OnPlayerEnterDeadZone); } // Called when the game starts or when spawned void ADeadzone::BeginPlay() { Super::BeginPlay(); } // Called every frame void ADeadzone::Tick(float [MASK] ) { Super::Tick( [MASK] ); } void ADeadzone::OnPlayerEnterDeadZone(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { // Check if the overlapped actor is the player character APlayerController* PlayerController = Cast(OtherActor->GetInstigatorController()); if (PlayerController) { // Teleport the player to the Spawn location OtherActor->SetActorLocation(SpawnLocation); } } ",DeltaTime 39,"/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the ""License""). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the ""license"" file accompanying this file. This file is distributed * on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include #include #include #include /** * @brief Interface for MetricManager. */ class MetricManagerInterface { public: /** * @brief add global dimension (applies to all metrics). */ virtual void AddDimension(const std::string &name, const std::string &value) = 0; /** * @brief create a metric. */ virtual ros_monitoring_msgs::msg::MetricData CreateMetric() const = 0; /** * @brief add a metric to list of metrics to be published. * * @param md a metric. */ virtual void AddMetric(ros_monitoring_msgs::msg::MetricData md) = 0; /** * @brief publishes all metrics and then discards them. */ virtual void Publish() = 0; /** @brief destructor. */ virtual ~MetricManagerInterface() {} }; /** * @brief Create, aggregate and publish metrics to ros topic. **/ class MetricManager : public MetricManagerInterface { public: explicit MetricManager( rclcpp::Node::SharedPtr node, std::string [MASK] , int topic_buffer_size ) : node_(node), publisher_(node->create_publisher( [MASK] , topic_buffer_size)) {} virtual void AddDimension(const std::string &name, const std::string &value) override final; virtual ros_monitoring_msgs::msg::MetricData CreateMetric() const override final; virtual void AddMetric(ros_monitoring_msgs::msg::MetricData md) override final; virtual void Publish() override final; private: rclcpp::Node::SharedPtr node_; rclcpp::Publisher::SharedPtr publisher_; ros_monitoring_msgs::msg::MetricList mlist_; ros_monitoring_msgs::msg::MetricData dimensions_; }; ",metrics_topic_name 40,"#include #include #include #include ""mecanum.hpp"" #include ""servo-wrapper.hpp"" // Motor pins #define frontLeftMotorPin 5 #define backLeftMotorPin 6 #define backRightMotorPin 9 #define frontRightMotorPin 10 // Controller pins #define rightStickHorizontalPin 2 #define rightStickVerticalPin 3 // #define leftStickVerticalPin 4 #define leftStickHorizontalPin 4 #define switchAPin 7 #define switchDPin 8 #define switchBPin 12 #define fanPin 11 #define NOISE_THRESHOLD 100 #define CHANNEL_DEADZONE 50 #define CHANNEL_DEADZONE_CENTER 45 // #define DO_FIELD_ORIENTED MecanumDrive drive(1.0f /* todo */, OF_REDUCE_EQUALLY, AF_FIT, TF_FLIP_X | TF_ROTATE_270DEG); ServoWrapper frontLeft(frontLeftMotorPin); ServoWrapper frontRight(frontRightMotorPin); ServoWrapper backLeft(backLeftMotorPin); ServoWrapper backRight(backRightMotorPin); struct ChInfo { /* The physical pin the channel is connected to. */ uint8_t pin; /* Was the pin `HIGH` last time? */ bool wasOn; /* Did `value` change this time? */ bool valueChanged; /* The last time the pin was detected to be `HIGH`, in microseconds since startup. */ unsigned long onUS; /* for debugging */ // long delta, deltaNormalized; /* The value of the channel, from `-1.0` to `1.0`. */ float value; }; struct { // volatile because they're used in interrupts volatile ChInfo rightStickHorizontal = {rightStickHorizontalPin, false, false, 0, 0.0f}; volatile ChInfo rightStickVertical = {rightStickVerticalPin, false, false, 0, 0.0f}; // volatile ChInfo leftStickVertical = {leftStickVerticalPin, false, false, 0, 0.0f}; volatile ChInfo leftStickHorizontal = {leftStickHorizontalPin, false, false, 0, 0.0f}; volatile ChInfo switchA = {switchAPin, false, false, 0, 0.0f}; volatile ChInfo switchD = {switchDPin, false, false, 0, 0.0f}; #ifdef DO_FIELD_ORIENTED volatile ChInfo switchB = {switchBPin, false, false, 0, 0.0f}; #endif // ChInfo channel = {/* pin */2, false, false, 0, 0.0f}; } channels; #ifdef DO_FIELD_ORIENTED bool wasFieldOriented = false; float angle; unsigned long lastGyroTime = 0; #endif void updateChannel(volatile ChInfo& channel) { const bool newState = digitalRead(channel.pin); const bool oldState = channel.wasOn; channel.valueChanged = false; if (newState != oldState) { const unsigned long now = micros(); if (newState) { // store rising time channel.onUS = now; channel.wasOn = true; } else { channel.wasOn = false; // how long was the pulse? long delta = now - channel.onUS; if (delta < NOISE_THRESHOLD) return; // channel.delta = delta; // apply deadzone if (delta >= 2000 - CHANNEL_DEADZONE) delta = 2000; if (delta <= 1000 + CHANNEL_DEADZONE) delta = 1000; if (abs(delta - 1500) <= CHANNEL_DEADZONE_CENTER) delta = 1500; // channel.deltaNormalized = delta; // convert 1000 <= delta <= 2000 to -1.0 <= value <= 1.0 channel.value = (float)(delta - 1500) / 500.0f; channel.valueChanged = true; } } } void setup() { Serial.begin(9600); // Controller channel inputs pinMode(rightStickHorizontalPin, INPUT); pinMode(rightStickVerticalPin, INPUT); // pinMode(leftStickVerticalPin, INPUT); pinMode(leftStickHorizontalPin, INPUT); pinMode(switchAPin, INPUT); pinMode(switchDPin, INPUT); #ifdef DO_FIELD_ORIENTED pinMode(switchBPin, INPUT); #endif attachInterrupt(digitalPinToInterrupt(rightStickHorizontalPin), []{ updateChannel(channels.rightStickHorizontal); }, CHANGE); attachInterrupt(digitalPinToInterrupt(rightStickVerticalPin), []{ updateChannel(channels.rightStickVertical); }, CHANGE); // attachInterrupt(digitalPinToInterrupt(leftStickVerticalPin), []{ updateChannel(channels.leftStickVertical); }, CHANGE); attachInterrupt(digitalPinToInterrupt(leftStickHorizontalPin), []{ updateChannel(channels.leftStickHorizontal); }, CHANGE); attachInterrupt(digitalPinToInterrupt(switchAPin), []{ updateChannel(channels.switchA); }, CHANGE); attachInterrupt(digitalPinToInterrupt(switchDPin), []{ updateChannel(channels.switchD); }, CHANGE); #ifdef DO_FIELD_ORIENTED attachInterrupt(digitalPinToInterrupt(switchBPin), []{ updateChannel(channels.switchB); }, CHANGE); #endif pinMode(fanPin, OUTPUT); #ifdef DO_FIELD_ORIENTED IMU.begin(); lastGyroTime = millis(); #endif // Motors frontLeft.begin(); frontRight.begin(); backLeft.begin(); backRight.begin(); } void loop() { if (channels.switchA.value > 0.5f) { frontLeft.drive(0.0f); frontRight.drive(0.0f); backLeft.drive(0.0f); backRight.drive(0.0f); digitalWrite(fanPin, LOW); delay(2500); return; } #ifdef DO_FIELD_ORIENTED if (IMU.gyroscopeAvailable()) { float x, y, z; IMU.readGyroscope(x, y, z); unsigned long now = millis(); float delta = (now - lastGyroTime) / 1000.0f; angle += z * delta; lastGyroTime = now; } bool isFieldOriented = channels.switchB.value > 0.5f; if (isFieldOriented != wasFieldOriented) { if (isFieldOriented) { angle = 0.0f; // reset } wasFieldOriented = isFieldOriented; } #endif vec2 [MASK] = vec2( channels.rightStickHorizontal.value, channels.rightStickVertical.value ); #ifdef DO_FIELD_ORIENTED if (isFieldOriented) [MASK] .rotate(angle); #endif // Do some complicated math DriveValues values = drive.calculate( [MASK] , // 0.0f channels.leftStickHorizontal.value * 0.25f ); // Move motors frontLeft.drive(values.frontLeft); frontRight.drive(values.frontRight); backLeft.drive(values.backLeft); backRight.drive(values.backRight); // Fans digitalWrite(fanPin, channels.switchD.value > 0.5f ? HIGH : LOW); // Debugging assistance Serial.println( String(""RH:"") + channels.rightStickHorizontal.value + "", RV:"" + channels.rightStickVertical.value + "", LH:"" + channels.leftStickHorizontal.value + "", SA:"" + channels.switchA.value + "", SD:"" + channels.switchD.value ); }",stick 41," #ifndef DLIB_SCAN_fHOG_UTILS_Hh_ #define DLIB_SCAN_fHOG_UTILS_Hh_ #include ""../matrix.h"" //#include ""../image_transforms.h"" #include ""../array.h"" #include ""../array2d.h"" //#include ""object_detector.h"" #include #include #include #define LOG_CALL_STACK() utils::call_stack<<""# ""<<__FILE__<<"":""<<__LINE__<<"" ""<< __PRETTY_FUNCTION__< struct processed_weight_vector; template < typename Pyramid_type, typename Feature_extractor_type > class scan_fhog_pyramid; template < typename T, typename mm1, typename mm2 > dlib::matrix draw_fhog( const dlib::array,mm2>& hog, const long cell_draw_size = 15, const float min_response_threshold = 0.0 ); } namespace utils{ class logFile{ public: logFile (std::string filename):outfile(filename.c_str()){ } logFile (const char* filename):outfile(filename){ } logFile (std::string filename_, int x, int y){ std::stringstream [MASK] (filename_,std::ios_base::out|std::ios_base::ate); [MASK] <<""_""< class print_fhog_as_csv_helper; class r_matrix_helper { public: r_matrix_helper(std::ostream& out_) : out(out_) { } template r_matrix_helper& operator<<(const dlib::array2d& m) { out << name.c_str() << ""=matrix( c(""; print_fhog_as_csv_helper(out) << m; out << ""), nrow = "" << m.nr() << "", ncol = "" << m.nc() << "", byrow = TRUE)"" << std::endl; return (*this); } r_matrix_helper& operator<<(std::string name_) { name=name_; return (*this); } template < typename T, long num_rows, long num_cols > r_matrix_helper& operator<<(const dlib::matrix& m) { out << name.c_str() << ""=matrix( c(""; for(long k =0;k r_matrix_helper& operator<<( const dlib::array2d< dlib::matrix >& m ) { typedef typename dlib::array2d >::row row_type; std::string tmp_name=name; for(int k =0;k r_matrix_helper& operator<<(const std::vector >& w) { out << name.c_str()<<"".size="" < r_matrix_helper& operator<<(const dlib::processed_weight_vector & a) { (*this)< r_matrix_helper& operator<<( const dlib::processed_weight_vector >&a ) { typedef typename dlib::scan_fhog_pyramid::fhog_filterbank fhog_filterbank; out << name.c_str()<<"".w.size=""< >& dets ) { if(dets.size()==0){ out << name.c_str()<<"".size=0""<1){ out << name.c_str() << ""=""; } out << ""c( ""< class print_fhog_as_csv_helper { /*! In particular, this code allows you to write statements like: std::cout< std::ostream& operator<< ( const dlib::array >& feats ); template std::ostream& operator<< ( const dlib::array2d& m); print_fhog_as_csv_helper& operator<< ( const std::string name_ ) { name=name_; return (*this); } private: std::ostream& out; mutable std::string name; }; template<> template std::ostream& print_fhog_as_csv_helper::operator<< ( const dlib::array >& feats ) { for(int i=0;i template std::ostream& print_fhog_as_csv_helper::operator<< ( const dlib::array2d& m ) { typedef typename dlib::array2d::row row_type; //std::cout<<""feats.size()=""< template <> std::ostream& print_fhog_as_csv_helper::operator<< ( const dlib::array2d& m ) { typedef typename dlib::array2d::row row_type; //std::cout<<""feats.size()=""< template std::ostream& print_fhog_as_csv_helper::operator<< ( const dlib::array >& feats ) { std::cout<<""feats.size()=""< template std::ostream& print_fhog_as_csv_helper::operator<< ( const dlib::array2d& m ) {} class print_fhog_short {}; const print_fhog_short fhog_info = print_fhog_short(); inline print_fhog_as_csv_helper operator<< ( std::ostream& out, const print_fhog_short& ) { return print_fhog_as_csv_helper(out); } class print_fhog_verbose {}; const print_fhog_verbose fhog_csv = print_fhog_verbose(); inline print_fhog_as_csv_helper operator<< ( std::ostream& out, const print_fhog_verbose& ) { return print_fhog_as_csv_helper(out); } template < //typename pyramid_type, typename image_type ,typename feature_extractor_type > void show_image_ ( dlib::image_window& win ,const image_type& img ,const feature_extractor_type& fe ,dlib::array >& feats ,int cell_size ,int filter_rows_padding ,int filter_cols_padding ) { win.clear_overlay(); win.set_image(img); // dlib::image_window winhog(draw_fhog(feats,7)); // call_stack<<""#Image size: ""< ContextSettings::CreateContextSettings() { return ResourceCast(MakeResource()); } WindowsContextSettings::WindowsContextSettings(): m_depth_stencil_state(nullptr) {} WindowsContextSettings::~WindowsContextSettings() { if (m_depth_stencil_state) { m_depth_stencil_state->Release(); } } bool WindowsContextSettings::Init(DepthMode depth_mode) { Resource context = ResourceCast(Window::GetContext()); D3D11_DEPTH_STENCIL_DESC ds_desc = {}; ds_desc.DepthEnable = true; ds_desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; ds_desc.DepthFunc = COMPARISON_FUNCS[(unsigned int)depth_mode]; ds_desc.StencilEnable = true; ds_desc.StencilReadMask = 0xff; ds_desc.StencilWriteMask = 0xff; ds_desc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; ds_desc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; ds_desc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; ds_desc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; ds_desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; ds_desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; ds_desc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; ds_desc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; if (FAILED(context->GetDevice()->CreateDepthStencilState(&ds_desc, &m_depth_stencil_state))) { INFINITY_CORE_ERROR(""Error creating depth stencil state""); return false; } return true; } WindowsContext::WindowsContext(const Resource &window, ID3D11Device *device, ID3D11DeviceContext *device_context): Context(window), m_device(device), m_device_context(device_context), m_render_target_view(nullptr), m_depth_stencil_view(nullptr), m_clear_color{ 0.0f, 0.0f, 0.0f, 1.0f } {} WindowsContext::~WindowsContext() {} bool WindowsContext::Init() { auto [MASK] = ContextSettings::CreateContextSettings(); if (! [MASK] ->Init()) { INFINITY_CORE_ERROR(""Error initializing default context settings""); return false; } SetContextSettings( [MASK] ); m_def_rasterizer = Infinity::Rasterizer::CreateRasterizer(); if (!m_def_rasterizer->Init(Rasterizer::RasterizerParams())) { INFINITY_CORE_ERROR(""Error initializing default rasterizer""); return false; } m_def_rasterizer->Bind(); return true; } bool WindowsContext::Resize(ID3D11RenderTargetView *render_target_view, ID3D11DepthStencilView *depth_stencil_view, unsigned int width, unsigned int height) { m_render_target_view = render_target_view; m_depth_stencil_view = depth_stencil_view; m_device_context->OMSetRenderTargets(1, &m_render_target_view, m_depth_stencil_view); D3D11_VIEWPORT viewport = {}; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; viewport.Width = (float)width; viewport.Height = (float)height; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; m_device_context->RSSetViewports(1, &viewport); return true; } void WindowsContext::SetClearColor(float r, float g, float b, float a) { m_clear_color[0] = r; m_clear_color[1] = g; m_clear_color[2] = b; m_clear_color[3] = a; } void WindowsContext::Clear() { if (m_device_context) { if (m_render_target_view) { m_device_context->ClearRenderTargetView(m_render_target_view, m_clear_color); } else { INFINITY_CORE_ERROR(""Error clearing context: Render target view is null.""); } if (m_depth_stencil_view) { m_device_context->ClearDepthStencilView(m_depth_stencil_view, D3D11_CLEAR_DEPTH, 1.0f, 0x00); } else { INFINITY_CORE_ERROR(""Error clearing context: Depth stencil view is null.""); } } else { INFINITY_CORE_ERROR(""Error clearing context: Device context is null.""); } } void WindowsContext::SetContextSettings(const Resource &settings) { m_settings = settings; m_device_context->OMSetDepthStencilState(ResourceCast(settings)->m_depth_stencil_state, 1); } ID3D11Device *WindowsContext::GetDevice() const { return m_device; } ID3D11DeviceContext *WindowsContext::GetDeviceContext() const { return m_device_context; } } #endif // INFINITY_WINDOWS",def_settings 44,"/* * Copyright © 2021 . All rights reserved. * Contacts: <> * Licensed under the Apache License, Version 2.0 */ template // V type already has the const specifier. auto Config::apply(const Key t_key, V [MASK] , const bool t_save_file) -> bool { using namespace std; string val_str; if constexpr (is_arithmetic_v) { val_str = to_string( [MASK] ); } else if constexpr (is_enum_v) { val_str = to_string(static_cast( [MASK] )); } else { val_str = [MASK] ; } if constexpr (is_same_v) { try { fcli::Theme::set_theme( [MASK] ); } catch (...) { return false; } } const string node_name(get_key_name(t_key)); auto node{m_root_node.child(node_name.c_str())}; if (!node) { if (!(node = m_root_node.append_child(node_name.c_str()))) { return false; } } if (!node.text().set(val_str.c_str())) { return false; } if (t_save_file) { return save(); } return true; } template auto Config::get(const Key t_key) const -> std::optional { using namespace std; optional val; const auto node{m_root_node.child(string(get_key_name(t_key)).c_str())}; if (node) { const auto text{node.text()}; if constexpr (is_enum_v) { val = static_cast(text.as_int()); } else if constexpr (is_same_v) { val = text.as_bool(); } else if constexpr (is_same_v || is_same_v) { val = text.as_int(); } else if constexpr (is_same_v || is_same_v) { val = text.as_uint(); } else { val = text.get(); } } return val; } ",t_val 45," #include ""RtAudio.h"" #include #include // Two-channel sawtooth wave generator. int saw(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData) { unsigned int i, j; short *buffer = (short *)outputBuffer; short *lastValues = (short *)userData; if (status) std::cout << ""Stream underflow detected!"" << std::endl; // Write interleaved audio data. /* for (i = 0; i= 1.0) lastValues[j] -= 2.0; } } */ memcpy(outputBuffer, inputBuffer, 4 * nBufferFrames); return 0; } int main() { RtAudio dac; //std::cout << dac.getDeviceCount() << std::endl; //2 if (dac.getDeviceCount() < 1) { std::cout << ""\nNo audio devices found!\n""; exit(0); } RtAudio::StreamParameters [MASK] ; //std::cout << dac.getDefaultOutputDevice() << std::endl; [MASK] .deviceId = dac.getDefaultOutputDevice(); //0 [MASK] .nChannels = 2; [MASK] .firstChannel = 0; unsigned int sampleRate = 44100; unsigned int bufferFrames = 256; // 256 sample frames RtAudio::StreamParameters input; input.deviceId = dac.getDefaultInputDevice(); input.nChannels = 2; input.firstChannel = 0; double data[2]; try { dac.openStream(& [MASK] , &input, RTAUDIO_SINT16, sampleRate, &bufferFrames, &saw, (void *)&data); dac.startStream(); } catch (RtAudioError& e) { e.printMessage(); exit(0); } char input1; std::cout << ""\nPlaying ... press to quit.\n""; std::cin.get(input1); try { // Stop the stream dac.stopStream(); } catch (RtAudioError& e) { e.printMessage(); } if (dac.isStreamOpen()) dac.closeStream(); system(""pause""); return 0; } /* #include ""RtAudio.h"" #include using namespace std; typedef signed short MY_TYPE; #define FORMAT RTAUDIO_SINT16 int inout(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double , RtAudioStreamStatus status, void *data) { // Since the number of input and output channels is equal, we can do // a simple buffer copy operation here. if (status) std::cout << ""Stream over/underflow detected."" << std::endl; unsigned int *bytes = (unsigned int *)data; memcpy(outputBuffer, inputBuffer, *bytes); return 0; } int main() { unsigned int channels = 2; unsigned int fs = 44100; unsigned int bufferBytes = 0; unsigned int oDevice = 0; unsigned int iDevice = 0; unsigned int iOffset = 0; unsigned int oOffset = 0; RtAudio adac; if (adac.getDeviceCount() < 1) { cout << ""\nNo audio devices found!\n""; exit(-1); } adac.showWarnings(true); unsigned int bufferFrames = 441; RtAudio::StreamParameters iParams, oParams; iParams.deviceId = adac.getDefaultInputDevice(); iParams.nChannels = channels; iParams.firstChannel = iOffset; oParams.deviceId = adac.getDefaultOutputDevice(); oParams.nChannels = channels; oParams.firstChannel = oOffset; try { adac.openStream(&oParams, &iParams, RTAUDIO_SINT16, fs, &bufferFrames, &inout, (void *)&bufferBytes); } catch (RtAudioError& e) { std::cout << '\n' << e.getMessage() << '\n' << std::endl; exit(1); } bufferBytes = bufferFrames * channels * sizeof(MY_TYPE); // Test RtAudio functionality for reporting latency. std::cout << ""\nStream latency = "" << adac.getStreamLatency() << "" frames"" << std::endl; try { adac.startStream(); char input; std::cout << ""\nPlaying ... press to quit (buffer frames = "" << bufferFrames << "").\n""; std::cin.get(input); // Stop the stream. adac.stopStream(); } catch (RtAudioError& e) { std::cout << '\n' << e.getMessage() << '\n' << std::endl; goto cleanup; } cleanup: if (adac.isStreamOpen()) adac.closeStream(); return 0; return 0; } */",parameters 46,"#include ""CalibrationController.h"" void CalibrationController::init(float sampleRate) { ParameterizedController::init(sampleRate); interface.init(); interface.focusOutput(); init(); } void CalibrationController::init() { Serial.println(""Calibration""); for(int i = 0; i < 8; i++) { Hardware::hw.cvOutputPins[i]->analogWrite(0); } interface.render(); startCalibrate(); } int CalibrationController::cycleParameter(int amount) { parameters.cycle(amount); switch(parameters.getSelectedIndex()) { case Parameter::VALUE: interface.focusValue(); break; } return parameters.getSelectedIndex(); } void CalibrationController::cycleValue(int amount) { parameters.getSelected().cycle(amount); switch(parameters.getSelectedIndex()) { case Parameter::VALUE: setValue(amount); break; } } void CalibrationController::selectValue() { Serial.println(""Reset""); calibration.reset(); startCalibrate(); } void CalibrationController::setOutput(uint8_t output) { saveCalibration(); currentOutput = output; startCalibrate(); } void CalibrationController::setValue(int8_t amount) { if(currentVoltage == 0) { calibration.offset(-amount); } else { calibration.scale(-amount); } updateOutput(); } void CalibrationController::update() { if(octaveInput.update()) { currentVoltage = octaveInput.getIntValue(); updateOutput(); } if(channelInput.update()) { setOutput(channelInput.getIntValue()); } } void CalibrationController::startCalibrate() { calibration.calibratePin(Hardware::hw.cvOutputPins[currentOutput]); updateOutput(); interface.setOutput(currentOutput); } void CalibrationController::saveCalibration() { Hardware::hw.cvOutputPins[currentOutput]->saveCalibration(); } void CalibrationController::updateOutput() { uint16_t [MASK] = calibration.convertReverse(currentVoltage); Hardware::hw.cvOutputPins[currentOutput]->analogWrite(currentVoltage); interface.setVoltage(currentVoltage); interface.setValue( [MASK] ); interface.setOffset(calibration.getDigitalOffset()); interface.setScale(calibration.getDigitalScale()); // Serial.print(calibration.getDigitalOffset()); // Serial.print(calibration.getDigitalScale()); } void CalibrationController::process() { }",binaryValue 47,"/* ********************************* * Created 23 November 2013 * * Copyright 2013, * * http://saikoled.com * * Licensed under GPL3 * ********************************* 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, version 3 of the License. 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. A copy of the GNU General Public License can be found at http://www.gnu.org/licenses/gpl.html This software implements 4x 16-bit PWM with a fully saturated and color corrected fading algorithm in HSI color space, and HSI -> RGBW conversion to allow for better pastel color if desired. It also implements an parabolic mapping for LED desired brightness to actual output RGB value. */ #include #include ""debug.h"" #include ""loop.h"" #include #include ""rgbled.h"" #include #include MCU_HEADER(rgbled) #include #define DEG_TO_RAD_FUNC(X) (M_PI*(X)/180) #define steptime 1 #define saturation 0.3 #define hue_increment 0.01 int whitevalue; struct HSI { float h; float s; float i; } color; void updatehue(); void updatesaturation(); void sendcolor(); void hsi2rgbw(float H, float S, float I, int* rgbw); void init_plugin_rgbled() { init_pwm(); color.h = 0; color.s = saturation; color.i = 1; sendcolor(); /* // Initial color = off, hue of red fully saturated. while (color.i < 1) { sendcolor(); color.i = color.i + 0.001; // Increase Intensity updatehue(); updatesaturation(); delay (steptime); } */ ABus.subscribe([&] (const uint16_t [MASK] , const void* pArg) { // handle message switch( [MASK] ) { case MSG_LOOP_TICK: sendcolor(); updatehue(); updatesaturation(); break; case MSG_RGBLED_ON: LOG_INFO(""MSG_RGBLED_ON""); color.i = 1; sendcolor(); break; case MSG_RGBLED_OFF: LOG_INFO(""MSG_RGBLED_OFF""); color.i = 0; sendcolor(); break; } }); } void updatehue() { color.h = color.h + hue_increment; } void updatesaturation() { color.s = saturation; } void sendcolor() { int rgb[3]; while (color.h >=360) color.h = color.h - 360; while (color.h < 0) color.h = color.h + 360; if (color.i > 1) color.i = 1; if (color.i < 0) color.i = 0; if (color.s > 1) color.s = 1; if (color.s < 0) color.s = 0; // Fix ranges (somewhat redundantly). hsi2rgbw(color.h, color.s, color.i, rgb); RED = rgb[0]; GREEN = rgb[1]; BLUE = rgb[2]; } void hsi2rgbw(float H, float S, float I, int* rgbw) { float r, g, b, w; float cos_h, cos_1047_h; H = fmod(H,360); // cycle H around to 0-360 degrees H = 3.14159*H/(float)180; // Convert to radians. S = S>0?(S<1?S:1):0; // clamp S and I to interval [0,1] I = I>0?(I<1?I:1):0; // This section is modified by the addition of white so that it assumes // fully saturated colors, and then scales with white to lower saturation. // // Next, scale appropriately the pure color by mixing with the white channel. // Saturation is defined as ""the ratio of colorfulness to brightness"" so we will // do this by a simple ratio wherein the color values are scaled down by (1-S) // while the white LED is placed at S. // This will maintain constant brightness because in HSI, R+B+G = I. Thus, // S*(R+B+G) = S*I. If we add to this (1-S)*I, where I is the total intensity, // the sum intensity stays constant while the ratio of colorfulness to brightness // goes down by S linearly relative to total Intensity, which is constant. if(H < 2.09439) { cos_h = cos(H); cos_1047_h = cos(1.047196667-H); r = S*I/3*(1+cos_h/cos_1047_h); g = S*I/3*(1+(1-cos_h/cos_1047_h)); b = 0; w = (1-S)*I; } else if(H < 4.188787) { H = H - 2.09439; cos_h = cos(H); cos_1047_h = cos(1.047196667-H); g = S*I/3*(1+cos_h/cos_1047_h); b = S*I/3*(1+(1-cos_h/cos_1047_h)); r = 0; w = (1-S)*I; } else { H = H - 4.188787; cos_h = cos(H); cos_1047_h = cos(1.047196667-H); b = S*I/3*(1+cos_h/cos_1047_h); r = S*I/3*(1+(1-cos_h/cos_1047_h)); g = 0; w = (1-S)*I; } // Mapping Function from rgbw = [0:1] onto their respective ranges. // For standard use, this would be [0:1]->[0:0xFFFF] for instance. // Here instead I am going to try a parabolic map followed by scaling. rgbw[0]=0xFFFF*r*r; rgbw[1]=0xFFFF*g*g; rgbw[2]=0xFFFF*b*b; // rgbw[3]=0xFFFF*w*w; } // source: http://museinfo.sapp.org/examples/humdrum/keyscape2.cpp void hsi2rgb(float H, float S, float I, int* rgb) { float r; float g; float b; if (H < 1.0/3.0) { b = (1-S)/3; r = (1+S*cos(2*PI*H)/cos(PI/3-2*PI*H))/3.0; g = 1 - (b + r); } else if (H < 2.0/3.0) { H = H - 1.0/3.0; r = (1-S)/3; g = (1+S*cos(2*PI*H)/cos(PI/3-2*PI*H))/3.0; b = 1 - (r+g); } else { H = H - 2.0/3.0; g = (1-S)/3; b = (1+S*cos(2*PI*H)/cos(PI/3-2*PI*H))/3.0; r = 1 - (g+b); } rgb[0] = (int)((I * r * 3)+.5); rgb[1] = (int)((I * g * 3)+.5); rgb[2] = (int)((I * b * 3)+.5); } ",msgId 48,"#include ""util/get_config_path.hpp"" #include #include #include #include #include #include #include auto does_file_exist(std::string const& filename) { struct stat [MASK] ; return (stat(filename.c_str(), & [MASK] ) == 0); } auto main(int argc, const char* argv[]) -> int { auto args = std::span(argv, argc); // TODO(tybl): Replace hardcoded app name with string generated by cmake auto config_path = tybl::util::get_config_path(""jrny""); config_path /= ""config.toml""; if (!does_file_exist(config_path.native())) { std::cerr << ""Error: "" << config_path.native() << "" does not exist.\n""; std::cerr << ""Please create a config file.\n""; return -1; } auto config = toml::parse_file(config_path.native()); // TODO(tybl): Start output with the current date/time auto now = std::chrono::system_clock::now(); const std::time_t t_c = std::chrono::system_clock::to_time_t(now); std::cout << std::put_time(std::localtime(&t_c), ""%F %T:""); for (auto arg : args) { std::cout << "" "" << arg; } std::string filename = config[""journal""][""filename""].value_or(""""); std::cout << "" > "" << filename << std::endl; return 0; } ",buffer 49,"// // Created by on 14/06/2021. // #include ""Hospital.hpp"" #include #include #include #include #include #include Hospital::Hospital() { } Pila *pila = new Pila(); list ListaR; list ListaN; list ListaV; list ListaA; list ListaTemp; std::string Hospital::inputDni() { std::string dniCliente; std::cout << ""Introduce el DNI del paciente a dar de alta:"" << endl; std::cin >> dniCliente; return dniCliente; } //CASE0: void Hospital::altaPacientes(Pila &pilaPacientes, Pila &pilaPacientesTemp) { char lista = 'S'; while (!pilaPacientes.esVacia() && lista != 'X') { string valorFecha = """"; SYSTEMTIME fecha; GetSystemTime(&fecha); int datoId = pilaPacientes.devolverId(); std::string datoDni = (std::string)(pilaPacientes.devolverDni()).c_str(); std::string datoNombre = (std::string)(pilaPacientes.devolverNombre()).c_str(); std::string datoAp1 = (std::string)(pilaPacientes.devolverApellido1()).c_str(); std::string datoAp2 = (std::string)(pilaPacientes.devolverApellido2()).c_str(); int datoEdad = pilaPacientes.devolverEdad(); char datoSexo = pilaPacientes.devolverSexo(); std::cout << ""ID: "" << datoId << endl; std::cout << ""DNI: "" << datoDni << endl; std::cout << ""Nombre: "" << datoNombre << endl; std::cout << ""Primer apellido: "" << datoAp1 << endl; std::cout << ""Segundo apellido: "" << datoAp2 << endl; std::cout << ""Edad: "" << datoEdad << endl; std::cout << ""Sexo: "" << datoSexo << endl; do { std::cout << ""Introduce una lista de emergencias(A/N/V/R). Pulsa X (mayúscula) para terminar con el proceso de alta:"" << endl; std::cin >> lista; if (lista == 'A') { pilaPacientes.mostrar(false); valorFecha = to_string(fecha.wYear) + ""/"" + to_string(fecha.wMonth) + ""/"" + to_string(fecha.wDay) + "" "" + to_string(fecha.wHour + 1) + "":"" + to_string(fecha.wMinute) + "":"" + to_string(fecha.wSecond); ListaA.push_back(to_string(datoId)); ListaA.push_back(datoDni); ListaA.push_back(valorFecha); } else if (lista == 'V') { pilaPacientes.mostrar(false); valorFecha = to_string(fecha.wYear) + ""/"" + to_string(fecha.wMonth) + ""/"" + to_string(fecha.wDay) + "" "" + to_string(fecha.wHour + 1) + "":"" + to_string(fecha.wMinute) + "":"" + to_string(fecha.wSecond); ListaV.push_back(to_string(datoId)); ListaV.push_back(datoDni); ListaV.push_back(valorFecha); } else if (lista == 'R') { pilaPacientes.mostrar(false); valorFecha = to_string(fecha.wYear) + ""/"" + to_string(fecha.wMonth) + ""/"" + to_string(fecha.wDay) + "" "" + to_string(fecha.wHour + 1) + "":"" + to_string(fecha.wMinute) + "":"" + to_string(fecha.wSecond); ListaR.push_back(to_string(datoId)); ListaR.push_back(datoDni); ListaR.push_back(valorFecha); } else if (lista == 'N') { pilaPacientes.mostrar(false); valorFecha = to_string(fecha.wYear) + ""/"" + to_string(fecha.wMonth) + ""/"" + to_string(fecha.wDay) + "" "" + to_string(fecha.wHour + 1) + "":"" + to_string(fecha.wMinute) + "":"" + to_string(fecha.wSecond); ListaN.push_back(to_string(datoId)); ListaN.push_back(datoDni); ListaN.push_back(valorFecha); } else if (lista != 'X') { std::cout << ""La lista introducida es incorrecta"" << endl; } } while (lista != 'A' && lista != 'V' && lista != 'N' && lista != 'R' && lista != 'X'); } pilaPacientesTemp = pilaPacientes; } //CASE1: void Hospital::bajaPacientes(Pila &pilaPacientes, Pila &pilaPacientesTemp) { std::string dni = inputDni(); while (!pilaPacientesTemp.esVacia()) { pilaPacientesTemp.mostrar(false); } pilaPacientes.eliminarElemento(pilaPacientesTemp, pilaPacientes); int contar1; contar1 = 0; for (string valor : ListaR) { if (contar1 > 0) { contar1++; } if (valor == dni) { contar1++; ListaTemp.pop_back(); //Lee y elimina el elemento por detras } if (contar1 == 0) { ListaTemp.push_back(valor); //Introduce el elemento por el final } if (contar1 == 2) { contar1 = 0; } } ListaR = ListaTemp; ListaTemp.clear(); //Elimina todos los elementos contar1 = 0; for (string valor : ListaN) { if (contar1 > 0) { contar1++; } if (valor == dni) { contar1++; ListaTemp.pop_back(); } if (contar1 == 0) { ListaTemp.push_back(valor); } if (contar1 == 2) { contar1 = 0; } } ListaN = ListaTemp; ListaTemp.clear(); contar1 = 0; for (string valor : ListaV) { if (contar1 > 0) { contar1++; } if (valor == dni) { contar1++; ListaTemp.pop_back(); } if (contar1 == 0) { ListaTemp.push_back(valor); } if (contar1 == 2) { contar1 = 0; } } ListaV = ListaTemp; ListaTemp.clear(); contar1 = 0; for (string valor : ListaA) { if (contar1 > 0) { contar1++; } if (valor == dni) { contar1++; ListaTemp.pop_back(); } if (contar1 == 0) { ListaTemp.push_back(valor); } if (contar1 == 2) { contar1 = 0; } } ListaA = ListaTemp; ListaTemp.clear(); } //CASE2: void Hospital::reasignacionListaEmergencia() { string valorFec = """"; SYSTEMTIME fec; GetSystemTime(&fec); std::string dni = inputDni(); char listaEmergencia; do { std::cout << ""Introduce la lista de emergencia (R/N/V/A) en la que el paciente está asignado :"" << endl; std::cin >> listaEmergencia; if (listaEmergencia != 'R' && listaEmergencia != 'N' && listaEmergencia != 'V' && listaEmergencia != 'A') { std::cout << ""La lista introducida no es correcta"" << endl; } } while (listaEmergencia != 'R' && listaEmergencia != 'N' && listaEmergencia != 'V' && listaEmergencia != 'A'); char nuevaLista; do { std::cout << ""Introduce la lista(R/N/V/A) en la que quieres reasignar al paciente:"" << endl; std::cin >> nuevaLista; if (nuevaLista != 'R' && nuevaLista != 'N' && nuevaLista != 'V' && nuevaLista != 'A') { std::cout << ""La lista introducida no es correcta"" << endl; } } while (nuevaLista != 'R' && nuevaLista != 'N' && nuevaLista != 'V' && nuevaLista != 'A'); valorFec = to_string(fec.wYear) + ""/"" + to_string(fec.wMonth) + ""/"" + to_string(fec.wDay) + "" "" + to_string(fec.wHour + 1) + "":"" + to_string(fec.wMinute) + "":"" + to_string(fec.wSecond); int contar = 0; bool localizado = false; int cont1 = 0; int cont2 = 0; bool localizado2 = false; if (listaEmergencia == 'R') { for (string valor : ListaR) { if (contar > 0) { contar++; } if (valor == dni) { contar++; ListaTemp.pop_back(); localizado = true; } if (contar == 0) { ListaTemp.push_back(valor); } if (contar == 2) { contar = 0; } } for (string valor : ListaR) { cont1++; localizado2 = false; for (string valor2 : ListaTemp) { if (valor == valor2) { localizado2 = true; } } if (!localizado2 && cont1 < 3) { cont2++; if (nuevaLista == 'R') { ListaR.push_back(valor); if (cont2 == 2) { ListaR.push_back(valorFec); } } else if (nuevaLista == 'N') { ListaN.push_back(valor); if (cont2 == 2) { ListaN.push_back(valorFec); } } else if (nuevaLista == 'V') { ListaV.push_back(valor); if (cont2 == 2) { ListaV.push_back(valorFec); } } else if (nuevaLista == 'A') { ListaA.push_back(valor); if (cont2 == 2) { ListaA.push_back(valorFec); } } } if (cont1 == 3) { cont1 = 0; } } ListaR = ListaTemp; ListaTemp.clear(); } else if (listaEmergencia == 'N') { for (string valor : ListaN) { if (contar > 0) { contar++; } if (valor == dni) { contar++; ListaTemp.pop_back(); localizado = true; } if (contar == 0) { ListaTemp.push_back(valor); } if (contar == 2) { contar = 0; } } for (string valor : ListaN) { cont1++; localizado2 = false; for (string valor2 : ListaTemp) { if (valor == valor2) { localizado2 = true; } } if (!localizado2 && cont1 < 3) { cont2++; if (nuevaLista == 'R') { ListaR.push_back(valor); if (cont2 == 2) { ListaR.push_back(valorFec); } } else if (nuevaLista == 'N') { ListaN.push_back(valor); if (cont2 == 2) { ListaN.push_back(valorFec); } } else if (nuevaLista == 'V') { ListaV.push_back(valor); if (cont2 == 2) { ListaV.push_back(valorFec); } } else if (nuevaLista == 'A') { ListaA.push_back(valor); if (cont2 == 2) { ListaA.push_back(valorFec); } } } if (cont1 == 3) { cont1 = 0; } } ListaN = ListaTemp; ListaTemp.clear(); } else if (listaEmergencia == 'A') { for (string valor : ListaA) { if (contar > 0) { contar++; } if (valor == dni) { contar++; ListaTemp.pop_back(); localizado = true; } if (contar == 0) { ListaTemp.push_back(valor); } if (contar == 2) { contar = 0; } } for (string valor : ListaA) { cont1++; localizado2 = false; for (string valor2 : ListaTemp) { if (valor == valor2) { localizado2 = true; } } if (!localizado2 && cont1 < 3) { cont2++; if (nuevaLista == 'R') { ListaR.push_back(valor); if (cont2 == 2) { ListaR.push_back(valorFec); } } else if (nuevaLista == 'N') { ListaN.push_back(valor); if (cont2 == 2) { ListaN.push_back(valorFec); } } else if (nuevaLista == 'V') { ListaV.push_back(valor); if (cont2 == 2) { ListaV.push_back(valorFec); } } else if (nuevaLista == 'A') { ListaA.push_back(valor); if (cont2 == 2) { ListaA.push_back(valorFec); } } } if (cont1 == 3) { cont1 = 0; } } ListaA = ListaTemp; ListaTemp.clear(); } else if (listaEmergencia == 'V') { for (string valor : ListaV) { if (contar > 0) { contar++; } if (valor == dni) { contar++; ListaTemp.pop_back(); localizado = true; } if (contar == 0) { ListaTemp.push_back(valor); } if (contar == 2) { contar = 0; } } for (string valor : ListaV) { cont1++; localizado2 = false; for (string valor2 : ListaTemp) { if (valor == valor2) { localizado2 = true; } } if (!localizado2 && cont1 < 3) { cont2++; if (nuevaLista == 'R') { ListaR.push_back(valor); if (cont2 == 2) { ListaR.push_back(valorFec); } } else if (nuevaLista == 'N') { ListaN.push_back(valor); if (cont2 == 2) { ListaN.push_back(valorFec); } } else if (nuevaLista == 'V') { ListaV.push_back(valor); if (cont2 == 2) { ListaV.push_back(valorFec); } } else if (nuevaLista == 'A') { ListaA.push_back(valor); if (cont2 == 2) { ListaA.push_back(valorFec); } } } if (cont1 == 3) { cont1 = 0; } } ListaV = ListaTemp; ListaTemp.clear(); } if (!localizado) { std::cout << ""El DNI introducido no se ha encontrado en la lista"" << endl; } } //CASE3: void Hospital::menuOpcion3(Pila &pilaPacientes, Pila &pilaPacientesTemp) { int opc; bool comprobar = false; while (!comprobar) { comprobar = true; std::cout << ""Selecciona la opción que quieres ejecutar:"" << endl; std::cout << ""1. Consulta de pacientes."" << endl; std::cout << ""2. Consulta de emergencias."" << endl; std::cout << ""3. Mostrar tiempos de emergencia superados."" << endl; std::cin >> opc; if (opc == 1) { bool comprobar1 = false; int opcion1; Hospital *mostrar = new Hospital(); while (!comprobar1) { comprobar1 = true; std::cout << ""Selecciona el tipo de consulta que quieres realizar:"" << endl; std::cout << ""1. Mostrar paciente indicando su DNI"" << endl; std::cout << ""2. Mostrar todos los pacientes"" << endl; std::cin >> opcion1; if (opcion1 < 1 || opcion1 > 2) { comprobar1 = false; std::cout << ""La opción seleccionada no es válida"" << endl; } if (opcion1 == 1) { mostrar->verificarDni(pilaPacientes, pilaPacientesTemp); } else { mostrar->mostrarTodos(pilaPacientes, pilaPacientesTemp); } } } else if (opc == 2) { bool comprobar2 = false; int opcion2; Hospital *mostrar = new Hospital(); while (!comprobar2) { comprobar2 = true; std::cout << ""Elige un tipo de consulta:"" << endl; std::cout << ""1. Mostrar emergencia indicando su ID"" << endl; std::cout << ""2. Mostrar todas las emergencias"" << endl; std::cin >> opcion2; if (opcion2 < 1 || opcion2 > 2) { comprobar2 = false; std::cout << ""La opción introducida es correcta"" << endl; } if (opcion2 == 1) { mostrar->verificarListasVacio(); } else { mostrar->mostrarEmergencias(); } } } else if (opc == 3) { Hospital *mostrar = new Hospital(); mostrar->consultarTiempos(); } else { std::cout << ""La opcion introducida es incorrecta"" << endl; comprobar = false; } } } //CASE3.1.1 void Hospital::verificarDni(Pila &pilaPacientes, Pila &pilaPacientesTemp) { pilaPacientesTemp = pilaPacientes; string dni; std::cout << ""Introduce el DNI que desee verificar: "" << endl; std::cin >> dni; pilaPacientes.buscarDni(pilaPacientes, dni); pilaPacientes = pilaPacientesTemp; } //CASE3.1.2 void Hospital::mostrarTodos(Pila &pilaPacientes, Pila &pilaPacientesTemp) { pilaPacientesTemp = pilaPacientes; while (!pilaPacientes.esVacia()) { pilaPacientes.mostrar(true); } pilaPacientes = pilaPacientesTemp; } //CASE 3.2.1 void Hospital::verificarListasVacio() { int numElementos = 0; for (string valor : ListaR) { if (valor != """") { numElementos++; } } for (string valor : ListaA) { if (valor != """") { numElementos++; } } for (string valor : ListaV) { if (valor != """") { numElementos++; } } for (string valor : ListaN) { if (valor != """") { numElementos++; } } if (numElementos == 0) { std::cout << ""Las listas de emergencia estan vacias"" << endl; } else { verificarId(); } } void Hospital::verificarId() { int id; bool encontrado = false; int contador = 0; while (!encontrado) { std::cout << ""Introduce el numero ID del paciente:"" << endl; std::cin >> id; for (string valor : ListaR) { if (valor == to_string(id)) { encontrado = true; } if (encontrado) { contador++; } if (contador == 2) { std::cout << valor << '\n'; std::cout << ""El paciente indicado pertenece a la lista de emergencias R"" << endl; } } for (string valor : ListaA) { if (valor == to_string(id)) { encontrado = true; } if (encontrado) { contador++; } if (contador == 2) { std::cout << valor << '\n'; std::cout << ""El paciente indicado pertenece a la lista de emergencias A"" << endl; } } for (string valor : ListaV) { if (valor == to_string(id)) { encontrado = true; } if (encontrado) { contador++; } if (contador == 2) { std::cout << valor << '\n'; std::cout << ""El paciente indicado pertenece a la lista de emergencias V"" << endl; } } for (string valor : ListaN) { if (valor == to_string(id)) { encontrado = true; } if (encontrado) { contador++; } if (contador == 2) { std::cout << valor << '\n'; std::cout << ""El paciente indicado pertenece a la lista de emergencias N"" << endl; } } if (!encontrado) { std::cout << ""El ID indicado no pertenece a ningún paciente. Verifique que el ID es correcto"" << endl; } } } //CASE 3.2.2 void Hospital::mostrarEmergencias() { int contador = 0; std::cout << ""Lista R:"" << endl; for (string valor : ListaR) { contador++; std::cout << valor << '\n'; if (contador % 3 == 0) { std::cout << ""-----------"" << endl; } } std::cout << ""Lista N:"" << endl; for (string valor : ListaN) { contador++; std::cout << valor << '\n'; if (contador % 3 == 0) { std::cout << ""-----------"" << endl; } } std::cout << ""Lista V:"" << endl; for (string valor : ListaV) { contador++; std::cout << valor << '\n'; if (contador % 3 == 0) { std::cout << ""-----------"" << endl; } } std::cout << ""Lista A:"" << endl; for (string valor : ListaA) { contador++; std::cout << valor << '\n'; if (contador % 3 == 0) { std::cout << ""-----------"" << endl; } } } //CASE 3.3 void Hospital::consultarTiempos() { string codi; string dn; string fec; int contPac; contPac = 0; string valorHora; string valorMinutos; string valorSegundos; string caracter; int numVariables = 0; int segTrans = 0; int minTrans = 0; int [MASK] = 0; SYSTEMTIME fecha1; GetSystemTime(&fecha1); int horaActual = fecha1.wHour + 1; int minutoActual = fecha1.wMinute; int segundoActual = fecha1.wSecond; std::cout << ""Lista R:"" << endl; for (string valor : ListaR) { contPac++; valorMinutos = """"; valorSegundos = """"; valorHora = """"; if (contPac == 1) { codi = valor; } else if (contPac == 2) { dn = valor; } else if (contPac == 3) { fec = valor; numVariables = 0; contPac = 0; for (int i = 0; i < valor.size(); i++) { caracter = valor.substr(i, 1); if (caracter == ""/"" || caracter == "":"" || caracter == "" "") { numVariables++; } else if (numVariables == 3) { valorHora = valorHora + caracter; } else if (numVariables == 4) { valorMinutos = valorMinutos + caracter; } else if (numVariables == 5) { valorSegundos = valorSegundos + caracter; } } segTrans = segundoActual - atoi(valorSegundos.c_str()); minTrans = minutoActual - atoi(valorMinutos.c_str()); [MASK] = horaActual - atoi(valorHora.c_str()); if (segTrans < 0) { segTrans = segTrans + 60; minTrans = minTrans - 1; } if (minTrans < 0) { minTrans = minTrans + 60; [MASK] = [MASK] - 1; } if (segTrans != 0 || minTrans != 0 || [MASK] != 0) { std::cout << codi << endl; std::cout << dn << endl; std::cout << fec << endl; std::cout << ""Tiempo transcurrido: "" << [MASK] << "":"" << minTrans << "":"" << segTrans << endl; } } } std::cout << ""Lista N:"" << endl; for (string valor : ListaN) { contPac++; valorMinutos = """"; valorSegundos = """"; valorHora = """"; if (contPac == 1) { codi = valor; } else if (contPac == 2) { dn = valor; } else if (contPac == 3) { fec = valor; numVariables = 0; contPac = 0; for (int i = 0; i < valor.size(); i++) { caracter = valor.substr(i, 1); if (caracter == ""/"" || caracter == "":"" || caracter == "" "") { numVariables++; } else if (numVariables == 3) { valorHora = valorHora + caracter; } else if (numVariables == 4) { valorMinutos = valorMinutos + caracter; } else if (numVariables == 5) { valorSegundos = valorSegundos + caracter; } } segTrans = segundoActual - atoi(valorSegundos.c_str()); minTrans = minutoActual - atoi(valorMinutos.c_str()); [MASK] = horaActual - atoi(valorHora.c_str()); if (segTrans < 0) { segTrans = segTrans + 60; minTrans = minTrans - 1; } if (minTrans < 0) { minTrans = minTrans + 60; [MASK] = [MASK] - 1; } if (minTrans > 15 || (minTrans == 15 && segTrans > 0)) { std::cout << codi << endl; std::cout << dn << endl; std::cout << fec << endl; std::cout << ""Tiempo transcurrido: "" << [MASK] << "":"" << minTrans << "":"" << segTrans << endl; } } } std::cout << ""Lista A:"" << endl; for (string valor : ListaA) { contPac++; valorMinutos = """"; valorSegundos = """"; valorHora = """"; if (contPac == 1) { codi = valor; } else if (contPac == 2) { dn = valor; } else if (contPac == 3) { fec = valor; numVariables = 0; contPac = 0; for (int i = 0; i < valor.size(); i++) { caracter = valor.substr(i, 1); if (caracter == ""/"" || caracter == "":"" || caracter == "" "") { numVariables++; } else if (numVariables == 3) { valorHora = valorHora + caracter; } else if (numVariables == 4) { valorMinutos = valorMinutos + caracter; } else if (numVariables == 5) { valorSegundos = valorSegundos + caracter; } } segTrans = segundoActual - atoi(valorSegundos.c_str()); minTrans = minutoActual - atoi(valorMinutos.c_str()); [MASK] = horaActual - atoi(valorHora.c_str()); if (segTrans < 0) { segTrans = segTrans + 60; minTrans = minTrans - 1; } if (minTrans < 0) { minTrans = minTrans + 60; [MASK] = [MASK] - 1; } if ( [MASK] > 1 || ( [MASK] == 1 && (minTrans > 0 || segTrans > 0))) { std::cout << codi << endl; std::cout << dn << endl; std::cout << fec << endl; std::cout << ""Tiempo transcurrido: "" << [MASK] << "":"" << minTrans << "":"" << segTrans << endl; } } } std::cout << ""Lista V:"" << endl; for (string valor : ListaV) { contPac++; valorMinutos = """"; valorSegundos = """"; valorHora = """"; if (contPac == 1) { codi = valor; } else if (contPac == 2) { dn = valor; } else if (contPac == 3) { fec = valor; numVariables = 0; contPac = 0; for (int i = 0; i < valor.size(); i++) { caracter = valor.substr(i, 1); if (caracter == ""/"" || caracter == "":"" || caracter == "" "") { numVariables++; } else if (numVariables == 3) { valorHora = valorHora + caracter; } else if (numVariables == 4) { valorMinutos = valorMinutos + caracter; } else if (numVariables == 5) { valorSegundos = valorSegundos + caracter; } } segTrans = segundoActual - atoi(valorSegundos.c_str()); minTrans = minutoActual - atoi(valorMinutos.c_str()); [MASK] = horaActual - atoi(valorHora.c_str()); if (segTrans < 0) { segTrans = segTrans + 60; minTrans = minTrans - 1; } if (minTrans < 0) { minTrans = minTrans + 60; [MASK] = [MASK] - 1; } if ( [MASK] > 1) { std::cout << codi << endl; std::cout << dn << endl; std::cout << fec << endl; std::cout << ""Tiempo transcurrido: "" << [MASK] << "":"" << minTrans << "":"" << segTrans << endl; } } } } //CASE 4 void Hospital::vaciarListas() { int cont; cont = 0; for (string valor : ListaN) { cont++; } for (int i = 0; i < cont; i++) { ListaN.pop_back(); } cont = 0; for (string valor : ListaR) { cont++; } for (int i = 0; i < cont; i++) { ListaR.pop_back(); } cont = 0; for (string valor : ListaA) { cont++; } for (int i = 0; i < cont; i++) { ListaA.pop_back(); } cont = 0; for (string valor : ListaV) { cont++; } for (int i = 0; i < cont; i++) { ListaV.pop_back(); } } Hospital::~Hospital() { } ",horTrans 50,"#include #include ""Application.h"" //Include GLEW #include //Include GLFW #include //Include the standard C++ headers #include #include #include ""StartMenuScene.h"" #include ""OverworldScene.h"" #include ""DistrictScene.h"" #include ""MazeScene.h"" #include ""MartScene.h"" #include ""BeachScene.h"" #include ""SharkScene.h"" #include ""CarnivalScene.h"" #include ""PauseMenuScene.h"" #include ""WinnerScene.h"" GLFWwindow* m_window; unsigned Application::FPS = 120; // FPS of this game unsigned frameTime = 1000 / Application::FPS; // time for each frame unsigned Application::m_width; unsigned Application::m_height; unsigned Application::ui_width; unsigned Application::ui_height; unsigned Application::sceneswitch; unsigned Application::previousscene; bool Application::restart; bool Application::quit; unsigned Player::ammo; int Player::health; int Player::money; int Player::sword; int Player::armourplate; int Player::helmet; bool Player::jetpackequipped; bool Player::SharkSurvived; bool Player::MazeComplete; bool Player::BookPurchased; bool Player::ShootingComplete; unsigned Player::getAmmo() { return ammo; } int Player::getHealth() { return health; } int Player::getMoney() { return money; } int Player::getSword() { return sword; } int Player::getArmourplate() { return armourplate; } int Player::getHelmet() { return helmet; } bool Player::getJetpack() { return jetpackequipped; } bool Player::getSharkSurvived() { return SharkSurvived; } bool Player::getMazeComplete() { return MazeComplete; } bool Player::getBookPurchased() { return BookPurchased; } bool Player::getShootingComplete() { return ShootingComplete; } void Player::setAmmo(unsigned a) { ammo = a; } void Player::setHealth(int h) { health = h; } void Player::setMoney(int m) { money = m; } void Player::setSword(int s) { sword = s; } void Player::setArmourplate(int ap) { armourplate = ap; } void Player::setHelmet(int ht) { helmet = ht; } void Player::setJetpack(bool jp) { jetpackequipped = jp; } void Player::setSharkSurvived(bool Ss) { SharkSurvived = Ss; } void Player::setMazeComplete(bool Mc) { MazeComplete = Mc; } void Player::setBookPurchased(bool Bp) { BookPurchased = Bp; } void Player::setShootingComplete(bool Sc) { ShootingComplete = Sc; } std::set Application::activeKeys; Scene* scene[Application::TOTALSCENES]; Mouse mouse; Application::Application() {} Application::~Application() {} //Define an error callback static void error_callback(int error, const char* description) { fputs(description, stderr); _fgetchar(); } //Define the key input callback static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); } static void scroll_callback(GLFWwindow* window, double nan, double [MASK] ) { mouse.scroll = [MASK] ; } static void mouse_callback(GLFWwindow* window, double x, double y) { if (x < Application::GetWindowWidth() / 2) { mouse.left = true; mouse.right = false; mouse.x = (Application::GetWindowWidth() / 2) - x; } else if (x > Application::GetWindowWidth() / 2) { mouse.left = false; mouse.right = true; mouse.x = x - (Application::GetWindowWidth() / 2); } if (y < Application::GetWindowHeight() / 2) { mouse.up = true; mouse.down = false; mouse.y = (Application::GetWindowHeight() / 2) - y; } else if (y > Application::GetWindowHeight() / 2) { mouse.up = false; mouse.down = true; mouse.y = y - (Application::GetWindowHeight() / 2); } } static void resize_callback(GLFWwindow* window, int w, int h) { Application::m_width = w; Application::m_height = h; Application::ui_width = w / 10; Application::ui_height = h / 10; glViewport(0, 0, w, h); } bool Application::IsKeyPressed(unsigned short key) { return ((GetAsyncKeyState(key) & 0x8001) != 0); } bool Application::IsMousePressed(unsigned short key) { return glfwGetMouseButton(m_window, key) != 0; } void Application::GetCursorPos(double* xpos, double* ypos) { glfwGetCursorPos(m_window, xpos, ypos); } unsigned Application::GetWindowWidth() { return m_width; } unsigned Application::GetWindowHeight() { return m_height; } unsigned Application::GetUIHeight() { return ui_height; } unsigned Application::GetFPS() { return FPS; } unsigned Application::GetUIWidth() { return ui_width; } bool Application::IsMousePressedOnce(unsigned short key) { std::pair::iterator, bool> ret; if (glfwGetMouseButton(m_window, key) != 0) { ret = activeKeys.insert(key); if (!ret.second) { return false; } else { if (key == 0) { mouse.rightclick = false; mouse.leftclick = true; } else if (key == 1) { mouse.leftclick = false; mouse.rightclick = true; } return true; } } else { activeKeys.erase(key); return false; } } bool Application::IsKeyPressedOnce(unsigned short key) { if ((GetAsyncKeyState(key) & 0x8001) != 0) { std::pair::iterator, bool> ret = activeKeys.insert(key); return (ret.second); } else { activeKeys.erase(key); return false; } } void Application::log(std::string string) { std::cout << string << std::endl; } void Application::Init() { //Set the error callback glfwSetErrorCallback(error_callback); //Initialize GLFW if (!glfwInit()) exit(EXIT_FAILURE); //Set the GLFW window creation hints - these are optional glfwWindowHint(GLFW_SAMPLES, 4); //Request 4x antialiasing glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //Request a specific OpenGL version glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //Request a specific OpenGL version //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL //Create a window and create its OpenGL context m_width = 800; m_height = 600; ui_height = 60; ui_width = 80; sceneswitch = START_SCENE; Player::setMoney(100); Player::setAmmo(256); Player::setHealth(100); Player::setJetpack(false); Player::setSharkSurvived(false); Player::setMazeComplete(false); Player::setBookPurchased(false); Player::setShootingComplete(false); // sword armour and helmet all zero so dun need initalise m_window = glfwCreateWindow(m_width, m_height, ""SP2 - Group 2"", NULL, NULL); quit = restart = false; mouse.reset(); glfwSetWindowSizeCallback(m_window, resize_callback); //If the window couldn't be created if (!m_window) { fprintf(stderr, ""Failed to open GLFW window.\n""); glfwTerminate(); exit(EXIT_FAILURE); } //This function makes the context of the specified window current on the calling thread. glfwMakeContextCurrent(m_window); //Sets the key callback glfwSetKeyCallback(m_window, key_callback); glewExperimental = true; // Needed for core profile //Initialize GLEW GLenum err = glewInit(); //If GLEW hasn't initialized if (err != GLEW_OK) { fprintf(stderr, ""Error: %s\n"", glewGetErrorString(err)); } } void toggleState() { switch (Application::sceneswitch) { case Application::MENU_SCENE: case Application::WIN_SCENE: case Application::START_SCENE: // Use mouse positioning to click on UI menu glfwSetCursorPosCallback(m_window, NULL); glfwSetScrollCallback(m_window, NULL); glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); break; case Application::DISTRICT_SCENE: case Application::MAZE_SCENE: case Application::SHARK_SCENE: case Application::CARNIVAL_SCENE: case Application::MART_SCENE: default: // Use mouse movement for playing and looking glfwSetCursorPosCallback(m_window, mouse_callback); glfwSetScrollCallback(m_window, scroll_callback); glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); mouse.reset(); glfwSetCursorPos(m_window, Application::GetWindowWidth() / 2, Application::GetWindowHeight() / 2); break; } } void Application::Run() { // Initialize and create scenes scene[DISTRICT_SCENE] = new DistrictScene(); scene[MAZE_SCENE] = new MazeScene(); scene[BEACH_SCENE] = new BeachScene(); scene[SHARK_SCENE] = new SharkScene(); scene[CARNIVAL_SCENE] = new CarnivalScene(); scene[OVERWORLD_SCENE] = new OverworldScene(); scene[MART_SCENE] = new MartScene(); scene[START_SCENE] = new StartMenuScene(); scene[MENU_SCENE] = new PauseMenuScene(); scene[WIN_SCENE] = new WinnerScene(); for (unsigned i = 0; i < Application::TOTALSCENES; i++) { if (scene[i]) scene[i]->Init(); } // Start timer to calculate how long it takes to render this frame m_timer.startTimer(); // Main Loop while (!glfwWindowShouldClose(m_window) || !Application::quit) { for (std::set::iterator i = activeKeys.begin(); i != activeKeys.end(); i++) { unsigned short key = *i; if ((GetAsyncKeyState(key) & 0x8001) != 0) {} else { activeKeys.erase(i); break; } } if (restart) { for (unsigned i = 0; i < Application::TOTALSCENES; i++) { if (scene[i]) { scene[i]->Reset(); } } Application::sceneswitch = Application::previousscene = START_SCENE; restart = false; } // Update and render selected scene if (scene[Application::sceneswitch]) { int previousScene = Application::sceneswitch; scene[previousScene]->Update(m_timer.getElapsedTime(), mouse); scene[previousScene]->Render(); if (previousScene != Application::sceneswitch) { scene[Application::sceneswitch]->InitGL(); } } else { Application::sceneswitch = START_SCENE; } // Toggle mouse states depending on scene toggleState(); switch (Application::sceneswitch) { case Application::MENU_SCENE: /*if (Application::IsKeyPressedOnce(VK_ESCAPE)) { Application::sceneswitch = Application::previousscene; }*/ break; case Application::START_SCENE: if (Application::IsKeyPressedOnce(VK_ESCAPE)) { Application::quit = true; } break; case Application::WIN_SCENE: restart = true; break; default: if (Application::IsKeyPressedOnce(VK_ESCAPE)) { Application::previousscene = Application::sceneswitch; Application::sceneswitch = MENU_SCENE; } break; } //Swap buffers glfwSwapBuffers(m_window); //Get and organize events, like keyboard and mouse input, window resizing, etc... glfwPollEvents(); // Frame rate limiter. Limits each frame to a specified time in ms. m_timer.waitUntil(frameTime); } //If the window had been closed or quit from the main menu for (unsigned i = 0; i < Application::TOTALSCENES; i++) { if (scene[i]) { //Clean up scenes scene[i]->Exit(); delete scene[i]; } } } void Application::Exit() { //Close OpenGL window and terminate GLFW glfwDestroyWindow(m_window); //Finalize and clean up GLFW glfwTerminate(); } ",offSet 51,"#include ""add.h"" #include ""ui_add.h"" #include #include Add::Add(QWidget *parent) : QDialog(parent), ui(new Ui::Add) { ui->setupUi(this); } Add::~Add() { delete ui; } QString Add::Sex() { if(ui->radioButton_man->isChecked()) { ui->radioButton_man->setChecked(false); return ""男""; } if(ui->radioButton_woman->isChecked()) { ui->radioButton_woman->setChecked(false); return ""女""; } return """"; } void Add::on_ADD_clicked() { int age = ui->spinBox->value(); QString name = ui->Add_nameEdit->text(); QString id = ui->Add_idEdit->text(); QString Class = ui->Add_classEdit->text(); QString chinese = ui->Add_chineseEdit->text(); QString math = ui->Add_mathEdit->text(); int mathscore = math.toInt(); int chinesescore = chinese.toInt(); int totalscore = mathscore+chinesescore; QString [MASK] = ""123""; QString sex = Sex(); QSqlQueryModel model; QString sql = ""select * from 学生 where 工号 = '""+id+""'""; model.setQuery(sql); if(model.rowCount()) { QMessageBox::warning(this,""警告"",""系统中已有该学生""); } else if(name.isEmpty() || id.isEmpty() || Class.isEmpty() || chinese.isEmpty() || math.isEmpty() || sex.isEmpty() || age == 0) { QMessageBox::warning(this,""警告"",""请检查输入的信息是否正确""); } else { sql = ""insert into 学生(姓名,工号,性别,班级,年龄,数学,语文,总分,密码)values('""+name+""','""+id+""','""+sex+""','""+Class+""',""+QString::number(age)+"",""+QString::number(mathscore)+"",""+QString::number(chinesescore)+"",""+QString::number(totalscore)+"",'""+ [MASK] +""')""; model.setQuery(sql); sql = ""insert into 账户(工号,密码,权限)values('""+id+""','""+ [MASK] +""','学生')""; model.setQuery(sql); QMessageBox::information(this,""提示"",""信息添加成功""); ui->spinBox->clear(); ui->Add_nameEdit->clear(); ui->Add_idEdit->clear(); ui->Add_classEdit->clear(); ui->Add_chineseEdit->clear(); ui->Add_mathEdit->clear(); } } ",pwd 52,"#include #include #include #include #include #include #define itera 1000 using namespace std; using namespace std::chrono; int main(int argc, char* argv[]) { int dimx, dimy, depth, size; string [MASK] ; if (argc < 3) { cout << ""Usage: "" << argv[0] << "" infile.pnm outfile.pgm"" << endl; return EXIT_FAILURE; } ifstream ifs(argv[1], ios_base::in | ios_base::binary); ifs >> [MASK] ; if ( [MASK] != ""P6"") { cout << argv[1] << "" is not a valid P6 file!"" << endl; return EXIT_FAILURE; } ifs >> dimx >> dimy >> depth; ifs.ignore(); ofstream ofs(argv[2], ios_base::out | ios_base::binary); ofs << ""P5"" << endl << dimx << ' ' << dimy << endl << ""255"" << endl; size = dimx*dimy; char *rgb = new char[size*3]; char *gray = new char[size]; char *sobel = new char[size]; unsigned char r, g, b; auto len = ifs.read(rgb, size*3+7).gcount(); if (len != size*3) { cout << ""Error reading file!"" << endl; return EXIT_FAILURE; } ifs.close(); auto start = high_resolution_clock::now(); for (auto it = 0u; it < itera; it++) { for (auto ii = 0u, oi = 0u; ii < size*3; ii=ii+3, oi++) { r = (char)rgb[ii]; g = (char)rgb[ii+1]; b = (char)rgb[ii+2]; int gs = (r+(g<<1)+b)>>2; gray[oi] = (char)gs; } int pixel_x; int pixel_y; float sobel_x[3][3] = {{ -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 }}; float sobel_y[3][3] = {{ -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 }}; for (int x=1; x < dimx-1; x++) { for (int y=1; y < dimy-1; y++) { pixel_x = (sobel_x[0][0] * gray[dimx * (y-1) + (x-1)]) + (sobel_x[0][1] * gray[dimx * (y-1) + x ]) + (sobel_x[0][2] * gray[dimx * (y-1) + (x+1)]) + (sobel_x[1][0] * gray[dimx * y + (x-1)]) + (sobel_x[1][1] * gray[dimx * y + x ]) + (sobel_x[1][2] * gray[dimx * y + (x+1)]) + (sobel_x[2][0] * gray[dimx * (y+1) + (x-1)]) + (sobel_x[2][1] * gray[dimx * (y+1) + x ]) + (sobel_x[2][2] * gray[dimx * (y+1) + (x+1)]); pixel_y = (sobel_y[0][0] * gray[dimx * (y-1) + (x-1)]) + (sobel_y[0][1] * gray[dimx * (y-1) + x ]) + (sobel_y[0][2] * gray[dimx * (y-1) + (x+1)]) + (sobel_y[1][0] * gray[dimx * y + (x-1)]) + (sobel_y[1][1] * gray[dimx * y + x ]) + (sobel_y[1][2] * gray[dimx * y + (x+1)]) + (sobel_y[2][0] * gray[dimx * (y+1) + (x-1)]) + (sobel_y[2][1] * gray[dimx * (y+1) + x ]) + (sobel_y[2][2] * gray[dimx * (y+1) + (x+1)]); int val = (int)sqrt((pixel_x * pixel_x) + (pixel_y * pixel_y)); if(val < 0) val = 0; if(val > 255) val = 255; sobel[dimx * y + x] = (unsigned char)val; } } } auto stop = high_resolution_clock::now(); auto duration = duration_cast(stop - start); cout << argv[1] << "" with "" << dimx << ""x"" << dimy << "" in "" << duration.count() << "" ms"" << endl; ofs.write(sobel, size); ofs.close(); return EXIT_SUCCESS; } ",line 53,"#include ""mudff_unpack.h"" void* Alloc(void *p, size_t size) { return malloc(size); } void Free(void *p, void *address) { if (address) free(address); } ISzAlloc alloc = { Alloc, Free }; muff_unpack::muff_unpack() { memset(arc_file,0,MAX_PATH); } muff_unpack::~muff_unpack() { memset(arc_file,0,MAX_PATH); } BYTE * muff_unpack::decomp_entry(char * file, int *size) { for (int j=0;j #include #include namespace mpt { inline namespace MPT_INLINE_NS { template struct ModIfNotZeroImpl { template constexpr Tval mod(Tval x) { static_assert(std::numeric_limits::is_integer); static_assert(!std::numeric_limits::is_signed); static_assert(std::numeric_limits::is_integer); static_assert(!std::numeric_limits::is_signed); return static_cast(x % m); } }; template <> struct ModIfNotZeroImpl { template constexpr Tval mod(Tval x) { return x; } }; template <> struct ModIfNotZeroImpl { template constexpr Tval mod(Tval x) { return x; } }; template <> struct ModIfNotZeroImpl { template constexpr Tval mod(Tval x) { return x; } }; template <> struct ModIfNotZeroImpl { template constexpr Tval mod(Tval x) { return x; } }; // Returns x % m if m != 0, x otherwise. // i.e. ""return (m == 0) ? x : (x % m);"", but without causing a warning with stupid older compilers template constexpr Tval modulo_if_not_zero(Tval x) { return ModIfNotZeroImpl().mod(x); } // rounds x up to multiples of target template constexpr T align_up(T x, T target) { return ((x + (target - 1)) / target) * target; } // rounds x down to multiples of target template constexpr T align_down(T x, T target) { return (x / target) * target; } // rounds x up to multiples of target or saturation of T template constexpr T saturate_align_up(T x, T target) { if (x > (std::numeric_limits::max() - (target - 1))) { return std::numeric_limits::max(); } return ((x + (target - 1)) / target) * target; } // Returns sign of a number (-1 for negative numbers, 1 for positive numbers, 0 for 0) template constexpr int signum(T [MASK] ) { return ( [MASK] > T(0)) - ( [MASK] < T(0)); } } // namespace MPT_INLINE_NS } // namespace mpt #endif // MPT_BASE_ALGORITHM_HPP ",value 55,"#define FORCE_SENSOR_PIN A0 // the FSR and 10K pulldown are connected to A0 void setup() { Serial.begin(9600); Serial.println(""CLEARDATA""); Serial.println(""LABEL,Force Sensor Reading, Value, Type""); Serial.println(""RESETTIMER""); } void loop() { int [MASK] = analogRead(FORCE_SENSOR_PIN); Serial.print(""DATA, TIME,""); Serial.print(""Force sensor reading = ""); Serial.print("",""); Serial.print( [MASK] ); // print the raw analog reading Serial.print("",""); if ( [MASK] < 10) // from 0 to 9 Serial.println("" -> no pressure""); else if ( [MASK] < 200) // from 10 to 199 Serial.println("" -> light touch""); else if ( [MASK] < 500) // from 200 to 499 Serial.println("" -> light squeeze""); else if ( [MASK] < 800) // from 500 to 799 Serial.println("" -> medium squeeze""); else // from 800 to 1023 Serial.println("" -> big squeeze""); delay(500); } ",analogReading 56," #include ""CTBot.h"" CTBot myBot; String ssid = ""no internet""; // REPLACE mySSID WITH YOUR WIFI SSID String pass = """"; // REPLACE myPassword YOUR WIFI PASSWORD, IF ANY String token = ""977896158:""; // REPLACE myToken WITH YOUR TELEGRAM BOT TOKEN uint8_t led = BUILTIN_LED; // the onboard ESP8266 LED. // If you have a NodeMCU you can use the BUILTIN_LED pin // (replace 2 with BUILTIN_LED) void setup() { // initialize the Serial Serial.begin(115200); Serial.println(""Starting TelegramBot...""); // connect the ESP8266 to the desired access point myBot.wifiConnect(ssid, pass); // set the telegram bot token myBot.setTelegramToken(token); // check if all things are ok if (myBot.testConnection()) Serial.println(""\ntestConnection OK""); else Serial.println(""\ntestConnection NOK""); // set the pin connected to the LED to act as output pin pinMode(D3, OUTPUT); digitalWrite(D3, HIGH); // turn off the led (inverted logic!) pinMode(D1,OUTPUT); digitalWrite(D1, HIGH); // turn off motor } void loop() { // a variable to store telegram message data TBMessage [MASK] ; // if there is an incoming message... if (myBot.getNewMessage( [MASK] )) { if ( [MASK] .text.equalsIgnoreCase(""LIGHT ON"")) { // if the received message is ""LIGHT ON""... digitalWrite(D3, LOW); // turn on the LED (inverted logic!) myBot.sendMessage( [MASK] .sender.id, ""Light is now ON""); // notify the sender } else if ( [MASK] .text.equalsIgnoreCase(""LIGHT OFF"")) { // if the received message is ""LIGHT OFF""... digitalWrite(D3, HIGH); // turn off the led (inverted logic!) myBot.sendMessage( [MASK] .sender.id, ""Light is now OFF""); // notify the sender } else if ( [MASK] .text.equalsIgnoreCase(""FAN ON"")) { // if the received message is ""FAN ON""... digitalWrite(D1, LOW); // turn on the FAN (inverted logic!) myBot.sendMessage( [MASK] .sender.id, ""FAN is now ON""); } else if ( [MASK] .text.equalsIgnoreCase(""FAN OFF"")) { // if the received message is ""FAN OFF""... digitalWrite(D1, HIGH); // turn off the FAN (inverted logic!) myBot.sendMessage( [MASK] .sender.id, ""FAN is now OFF""); // notify the sender } else { // otherwise... // generate the message for the sender String reply; reply = (String)""Welcome "" + [MASK] .sender.username + (String)"". Try LIGHT ON or LIGHT OFF.""; myBot.sendMessage( [MASK] .sender.id, reply); // and send it } } // wait 500 milliseconds delay(500); } ",msg 57,"#include ""AlignmentRule.h"" #include ""../gameobjects/Boid.h"" Vector2 AlignmentRule::computeForce(const std::vector& neighborhood, Boid* boid) { Vector2 [MASK] = Vector2::zero(); int total = 0; // todo: add your code here to align each boid in a neighborhood // hint: iterate over the neighborhood for (int i = 0; i < neighborhood.size(); i++) { //Check if other boid's are in dectection radius float dist = boid->getVelocity().getDistance(boid->getPosition(), neighborhood[i]->getPosition()); if (dist < boid->getDetectionRadius()) { [MASK] += neighborhood[i]->getVelocity(); total++; } } if(total != 0) [MASK] /= total; return Vector2::normalized( [MASK] ); }",averageVelocity 58,"// NCurses 2D vector math // (c) 2022 by #include #include ""math2d.h"" static const int mat3_stack_max = 100; static int mat3_stack_size = 0; static Mat3 mat3_stack[mat3_stack_max]; // get current transformation Mat3 top() { if (mat3_stack_size > 0) return(mat3_stack[mat3_stack_size-1]); else return(mat3()); } // push current transformation void push() { if (mat3_stack_size < mat3_stack_max) { if (mat3_stack_size > 0) mat3_stack[mat3_stack_size] = mat3_stack[mat3_stack_size-1]; else mat3_stack[mat3_stack_size] = mat3(); mat3_stack_size++; } } // pop current transformation Mat3 pop() { if (mat3_stack_size > 0) return(mat3_stack[--mat3_stack_size]); else return(mat3()); } // apply translation to current transformation void translate(float x, float y) { if (mat3_stack_size > 0) { Mat3 m = mat3(1,0,x, 0,1,y, 0,0,1); mat3_stack[mat3_stack_size-1] = mul3(mat3_stack[mat3_stack_size-1], m); } } // apply clockwise rotation to current transformation void rotate(float a, float [MASK] ) { if (mat3_stack_size > 0) { float w = M_PI*a/180; float s = sin(w); float c = cos(w); Mat3 m = mat3(c,-s* [MASK] ,0, s/ [MASK] ,c,0, 0,0,1); mat3_stack[mat3_stack_size-1] = mul3(mat3_stack[mat3_stack_size-1], m); } } // apply scaling to current transformation void scale(float s, float t) { if (mat3_stack_size > 0) { Mat3 m = mat3(s,0,0, 0,t,0, 0,0,1); mat3_stack[mat3_stack_size-1] = mul3(mat3_stack[mat3_stack_size-1], m); } } ",aspect 59,"#include // PIN 9 (PIN_B1) <=> CN9 PIN 2 #define SET_DATA PORTB.OUTSET = PIN0_bm #define CLR_DATA PORTB.OUTCLR = PIN0_bm // PIN 8 (PIN_B0) <=> CN9 PIN 3 #define SET_SETUP PORTB.OUTSET = PIN1_bm #define CLR_SETUP PORTB.OUTCLR = PIN1_bm // PIN 6 (PIN_B3) <=> CN9 PIN 4 #define SET_RESET PORTB.OUTSET = PIN3_bm #define CLR_RESET PORTB.OUTCLR = PIN3_bm // PIN 7 (PIN_B2) <=> CN9 PIN 5 #define SET_CLOCK PORTB.OUTSET = PIN2_bm #define CLR_CLOCK PORTB.OUTCLR = PIN2_bm // doing bit shifting takes a variable amount // of time depending on the how far the shift // is. Using the below lookup table to try // and keep a consistent clock period when // sending data. uint8_t masks[8] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, }; // The key data below comes from mame. Each game has a .key file, which contains the 20 bytes. // ie: https://github.com/mamedev/mame/blob/master/src/mame/capcom/cps2.cpp#L1900 #define CONFIG_SIZE 6 #define WATCHDOG_SIZE 6 #define KEY_SIZE 4 // There are only 10 unique combinations of the first 6 bytes // of all key data. In order to save about 800 bytes of flash // we are using the below lookup table for these 6 bytes. // Without the lookup table the code compiles very near to 4k, // which would put it at risk of not being viable on attiny4x4s uint8_t config_table[][CONFIG_SIZE] = { { 0x01, 0x00, 0x02, 0x40, 0x00, 0x08 }, // 0x00 { 0x01, 0x00, 0x02, 0x40, 0x00, 0x09 }, // 0x01 { 0x01, 0x00, 0x02, 0x40, 0x00, 0x0a }, // 0x02 { 0x07, 0x00, 0x02, 0x40, 0x00, 0x08 }, // 0x03 { 0x07, 0x00, 0x02, 0x40, 0x00, 0x0a }, // 0x04 { 0x0f, 0x00, 0x02, 0x40, 0x00, 0x08 }, // 0x05 { 0x0f, 0x00, 0x02, 0x40, 0x00, 0x09 }, // 0x06 { 0x0f, 0x00, 0x02, 0x40, 0x00, 0x0a }, // 0x07 { 0x3f, 0x00, 0x02, 0x40, 0x00, 0x08 }, // 0x08 { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, // 0x09 }; struct game_data_t { uint8_t config_table_index; uint8_t watchdog[WATCHDOG_SIZE]; uint8_t key2[KEY_SIZE]; uint8_t key1[KEY_SIZE]; }; #define MAX_GAME_NUM 174 struct game_data_t game_data[MAX_GAME_NUM + 1] = { // config table jumpers // index watchdog config key#2 key#1 12345678 raw key filename { 0x06, { 0x84, 0xc2, 0xeb, 0x7a, 0x3c, 0xa5 }, { 0xf4, 0x38, 0xeb, 0x65 }, { 0x79, 0x9c, 0xbf, 0x70 } }, // 00000000 1944.key { 0x06, { 0x84, 0xc2, 0xeb, 0x7a, 0x3c, 0xa5 }, { 0x8b, 0x93, 0x46, 0x1d }, { 0x70, 0xe7, 0xaf, 0x10 } }, // 00000001 1944j.key { 0x06, { 0x84, 0xc2, 0xeb, 0x7a, 0x3c, 0xa5 }, { 0x78, 0xfe, 0x6b, 0x44 }, { 0xc9, 0x39, 0xf2, 0xe0 } }, // 00000010 1944u.key { 0x04, { 0x04, 0xc2, 0xa4, 0x02, 0x02, 0x21 }, { 0xe8, 0x85, 0x13, 0x2a }, { 0x2e, 0x46, 0x8b, 0x00 } }, // 00000011 19xx.key { 0x04, { 0x04, 0xc2, 0xa4, 0x02, 0x02, 0x22 }, { 0x23, 0xb1, 0x6f, 0xb6 }, { 0xbc, 0xcb, 0x9c, 0xcc } }, // 00000100 19xxa.key { 0x04, { 0x04, 0xc2, 0xa4, 0x02, 0x02, 0x23 }, { 0xf1, 0x1b, 0x7e, 0xd1 }, { 0x5b, 0x8a, 0x7e, 0x9c } }, // 00000101 19xxb.key { 0x04, { 0x04, 0xc2, 0xa4, 0x02, 0x02, 0x23 }, { 0xe4, 0xda, 0x13, 0xbd }, { 0x7d, 0x76, 0x4a, 0xe8 } }, // 00000110 19xxh.key { 0x04, { 0x04, 0xc2, 0xa4, 0x02, 0x02, 0x21 }, { 0xf8, 0x7f, 0xc0, 0x00 }, { 0x7e, 0xea, 0x20, 0x00 } }, // 00000111 19xxj.key { 0x04, { 0x04, 0xc2, 0xa4, 0x02, 0x02, 0x20 }, { 0x04, 0x3c, 0x2f, 0xeb }, { 0xe0, 0x63, 0x81, 0xc0 } }, // 00001000 19xxu.key { 0x07, { 0x70, 0x30, 0x04, 0x00, 0x10, 0x0b }, { 0xe0, 0x42, 0x71, 0x47 }, { 0x40, 0xca, 0xe5, 0xe4 } }, // 00001001 armwar.key { 0x07, { 0x70, 0x30, 0x04, 0x00, 0x10, 0x08 }, { 0x42, 0x71, 0x47, 0x40 }, { 0xca, 0xe5, 0xe7, 0xe0 } }, // 00001010 armwara.key { 0x07, { 0x70, 0x30, 0x04, 0x00, 0x10, 0x0a }, { 0x04, 0x27, 0x14, 0x74 }, { 0x0c, 0xae, 0x5e, 0x7c } }, // 00001011 armwarb.key { 0x07, { 0x70, 0x30, 0x04, 0x00, 0x10, 0x0a }, { 0x5e, 0x7e, 0x04, 0x27 }, { 0x14, 0x74, 0x0c, 0xac } }, // 00001100 armwaru.key { 0x05, { 0x04, 0xc0, 0xb1, 0x20, 0x79, 0xab }, { 0x34, 0xd9, 0xed, 0x4a }, { 0x7b, 0xc4, 0x12, 0xa0 } }, // 00001101 avsp.key { 0x05, { 0x04, 0xc0, 0xb1, 0x20, 0x79, 0xa8 }, { 0x3a, 0x69, 0x49, 0xd2 }, { 0xf7, 0x3c, 0x5a, 0x0c } }, // 00001110 avspa.key { 0x05, { 0x04, 0xc0, 0xb1, 0x20, 0x79, 0xab }, { 0xe9, 0xc6, 0xcf, 0x09 }, { 0x42, 0x5b, 0x52, 0x38 } }, // 00001111 avsph.key { 0x05, { 0x04, 0xc0, 0xb1, 0x20, 0x79, 0xa8 }, { 0x98, 0x13, 0xb2, 0x29 }, { 0x7c, 0x74, 0xee, 0x5c } }, // 00010000 avspj.key { 0x05, { 0x04, 0xc0, 0xb1, 0x20, 0x79, 0xab }, { 0x11, 0x6b, 0xbc, 0xce }, { 0x44, 0x21, 0xbc, 0xb4 } }, // 00010001 avspu.key { 0x04, { 0x04, 0xc3, 0xa4, 0x02, 0x32, 0x02 }, { 0xb5, 0x1c, 0xf4, 0xf3 }, { 0xa6, 0x9e, 0xa6, 0x2c } }, // 00010010 batcir.key { 0x04, { 0x04, 0xc3, 0xa4, 0x02, 0x32, 0x03 }, { 0x8d, 0xd0, 0x44, 0x67 }, { 0x4c, 0x06, 0xe9, 0xe0 } }, // 00010011 batcira.key { 0x04, { 0x04, 0xc3, 0xa4, 0x02, 0x32, 0x00 }, { 0x5c, 0x40, 0x00, 0x00 }, { 0x6e, 0xcb, 0xfc, 0x00 } }, // 00010100 batcirj.key { 0x01, { 0x84, 0xc3, 0xa2, 0xc8, 0xf3, 0x6a }, { 0xb7, 0xa1, 0xc7, 0xf9 }, { 0x8d, 0x23, 0x7f, 0x2c } }, // 00010101 choko.key { 0x04, { 0x04, 0xc3, 0xa4, 0x00, 0x23, 0x02 }, { 0x0f, 0x9c, 0x21, 0x08 }, { 0x17, 0xe5, 0xd1, 0x98 } }, // 00010110 csclub.key { 0x04, { 0x04, 0xc3, 0xa4, 0x00, 0x23, 0x03 }, { 0xb2, 0x50, 0xb5, 0x65 }, { 0x51, 0xed, 0x9b, 0x20 } }, // 00010111 cscluba.key { 0x04, { 0x04, 0xc3, 0xa4, 0x00, 0x23, 0x00 }, { 0x2c, 0xa7, 0xb9, 0xd3 }, { 0x94, 0x54, 0xa0, 0x3c } }, // 00011000 csclubh.key { 0x04, { 0x04, 0xc3, 0xa4, 0x00, 0x23, 0x00 }, { 0x0f, 0x20, 0x0d, 0xaa }, { 0x9f, 0x42, 0xd1, 0x48 } }, // 00011001 csclubj.key { 0x05, { 0x70, 0xc3, 0xfc, 0x00, 0x70, 0xc2 }, { 0x02, 0x42, 0x42, 0x83 }, { 0x0a, 0x69, 0x0a, 0x88 } }, // 00011010 cybots.key { 0x05, { 0x70, 0xc3, 0xfc, 0x00, 0x70, 0xc3 }, { 0x0a, 0x69, 0x09, 0x4a }, { 0x02, 0x42, 0x42, 0x80 } }, // 00011011 cybotsj.key { 0x05, { 0x70, 0xc3, 0xfc, 0x00, 0x70, 0xc2 }, { 0x69, 0x0a, 0xaa, 0x02 }, { 0x42, 0x42, 0x83, 0x08 } }, // 00011100 cybotsu.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x83 }, { 0x1b, 0xeb, 0xe0, 0x6c }, { 0xf5, 0x64, 0x47, 0x84 } }, // 00011101 ddsom.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x82 }, { 0x8b, 0x05, 0x03, 0xde }, { 0xcf, 0x56, 0x63, 0x84 } }, // 00011110 ddsoma.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x81 }, { 0xcf, 0xf6, 0x97, 0x3d }, { 0x07, 0x96, 0x4a, 0x38 } }, // 00011111 ddsomb.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x83 }, { 0x81, 0x9e, 0xc1, 0x22 }, { 0x89, 0x0b, 0x21, 0x08 } }, // 00100000 ddsomh.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x82 }, { 0x88, 0x25, 0x6a, 0x30 }, { 0xa5, 0x7d, 0x25, 0xd4 } }, // 00100001 ddsomj.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x81 }, { 0x79, 0xf2, 0xcf, 0x61 }, { 0x92, 0x83, 0xe4, 0x48 } }, // 00100010 ddsomu.key { 0x03, { 0x78, 0xc2, 0x60, 0x20, 0x00, 0x0a }, { 0x6e, 0xb1, 0x4c, 0xa0 }, { 0x41, 0xff, 0x9b, 0x88 } }, // 00100011 ddtod.key { 0x03, { 0x78, 0xc2, 0x60, 0x20, 0x00, 0x0a }, { 0x20, 0x82, 0x3a, 0x62 }, { 0x82, 0x0d, 0x4d, 0xec } }, // 00100100 ddtoda.key { 0x03, { 0x78, 0xc2, 0x60, 0x20, 0x00, 0x08 }, { 0x1e, 0xee, 0x90, 0x5e }, { 0x60, 0x22, 0x5a, 0x60 } }, // 00100101 ddtodh.key { 0x03, { 0x78, 0xc2, 0x60, 0x20, 0x00, 0x0a }, { 0xd1, 0x47, 0x5b, 0x3c }, { 0xe7, 0x9c, 0x22, 0x88 } }, // 00100110 ddtodj.key { 0x03, { 0x78, 0xc2, 0x60, 0x20, 0x00, 0x08 }, { 0x3f, 0x5b, 0x38, 0x92 }, { 0xf0, 0xe6, 0x14, 0xdc } }, // 00100111 ddtodu.key { 0x05, { 0xc9, 0xf4, 0x89, 0x36, 0x8d, 0xb7 }, { 0x52, 0xff, 0xa0, 0x50 }, { 0x09, 0xc7, 0x6e, 0xc0 } }, // 00101000 dimahoo.key { 0x05, { 0xc9, 0xf4, 0x89, 0x36, 0x8d, 0xb6 }, { 0x25, 0x95, 0xfc, 0x36 }, { 0x6b, 0xd6, 0xba, 0x98 } }, // 00101001 dimahoou.key { 0x05, { 0x70, 0x40, 0x00, 0x00, 0x1a, 0x18 }, { 0x24, 0x34, 0x40, 0x00 }, { 0x57, 0x94, 0x6f, 0x20 } }, // 00101010 dstlk.key { 0x05, { 0x70, 0x40, 0x00, 0x00, 0x1a, 0x1a }, { 0x3a, 0x61, 0x11, 0x80 }, { 0x67, 0x06, 0xe8, 0x10 } }, // 00101011 dstlka.key { 0x05, { 0x70, 0x40, 0x00, 0x00, 0x1a, 0x19 }, { 0x56, 0x5a, 0x22, 0x01 }, { 0xfd, 0xf1, 0x89, 0x10 } }, // 00101100 dstlkh.key { 0x05, { 0x70, 0x40, 0x00, 0x00, 0x1a, 0x1a }, { 0x62, 0x39, 0x10, 0x20 }, { 0x3f, 0x5c, 0x05, 0xe0 } }, // 00101101 dstlku.key { 0x03, { 0x70, 0x43, 0x00, 0x02, 0x8b, 0x38 }, { 0xa9, 0xb8, 0x65, 0x74 }, { 0xee, 0x30, 0x23, 0x24 } }, // 00101110 ecofghtr.key { 0x03, { 0x70, 0x43, 0x00, 0x02, 0x8b, 0x39 }, { 0x30, 0xa9, 0xb8, 0x65 }, { 0x76, 0x30, 0x23, 0x24 } }, // 00101111 ecofghtra.key { 0x03, { 0x70, 0x43, 0x00, 0x02, 0x8b, 0x3b }, { 0x0a, 0x9b, 0x86, 0x57 }, { 0x4e, 0x30, 0x23, 0x24 } }, // 00110000 ecofghtrh.key { 0x03, { 0x70, 0x43, 0x00, 0x02, 0x8b, 0x3a }, { 0x9b, 0x86, 0x57, 0x4e }, { 0xde, 0x30, 0x23, 0x24 } }, // 00110001 ecofghtru.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x90, 0x20 }, { 0x07, 0xac, 0x1b, 0x60 }, { 0x25, 0x1e, 0xd2, 0x9c } }, // 00110010 gigawing.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x90, 0x20 }, { 0x5b, 0xb6, 0x35, 0x99 }, { 0x68, 0x55, 0x82, 0xb0 } }, // 00110011 gigawinga.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x90, 0x22 }, { 0xe7, 0xfb, 0xdd, 0xa4 }, { 0x36, 0x8b, 0x9f, 0xc0 } }, // 00110100 gigawingb.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x90, 0x22 }, { 0x87, 0x16, 0xc0, 0x0a }, { 0x21, 0x0b, 0x95, 0xcc } }, // 00110101 gigawingh.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x90, 0x22 }, { 0xa4, 0x42, 0xbd, 0xf5 }, { 0x5a, 0x61, 0x92, 0x20 } }, // 00110110 gigawingj.key { 0x05, { 0xc9, 0xf4, 0x89, 0x36, 0x8d, 0xb5 }, { 0x1b, 0x5e, 0x12, 0x18 }, { 0x69, 0xf7, 0xbf, 0xa4 } }, // 00110111 gmahou.key { 0x05, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x10 }, { 0xe4, 0x63, 0x15, 0xfe }, { 0xee, 0xe5, 0xb1, 0x68 } }, // 00111000 hsf2.key { 0x05, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x12 }, { 0xf1, 0x43, 0x1d, 0x54 }, { 0x31, 0xb2, 0xdc, 0x74 } }, // 00111001 hsf2a.key { 0x05, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x13 }, { 0x89, 0xf0, 0x77, 0x6c }, { 0x1f, 0xd0, 0x6e, 0x98 } }, // 00111010 hsf2j.key { 0x05, { 0x04, 0xc1, 0x29, 0xb3, 0x3a, 0xa2 }, { 0x6b, 0xf1, 0xbd, 0x25 }, { 0x9d, 0x50, 0x94, 0xd8 } }, // 00111011 jyangoku.key { 0x05, { 0x04, 0xc0, 0x9a, 0x02, 0x02, 0x38 }, { 0x2a, 0x98, 0xb2, 0xdc }, { 0xd4, 0xe0, 0x28, 0x28 } }, // 00111100 megaman2.key { 0x05, { 0x04, 0xc0, 0x9a, 0x02, 0x02, 0x3a }, { 0xa1, 0x42, 0x79, 0xaf }, { 0x51, 0x44, 0xa3, 0xf0 } }, // 00111101 megaman2a.key { 0x05, { 0x04, 0xc0, 0x9a, 0x02, 0x02, 0x38 }, { 0x2c, 0x21, 0x02, 0x91 }, { 0x4f, 0x3a, 0xa9, 0xb8 } }, // 00111110 megaman2h.key { 0x05, { 0x04, 0xc0, 0x9a, 0x80, 0xa6, 0x12 }, { 0x92, 0x90, 0x98, 0xa5 }, { 0x7f, 0x24, 0x4a, 0x80 } }, // 00111111 mmancp2u.key { 0x03, { 0x0d, 0xb7, 0x88, 0xb7, 0xcd, 0x77 }, { 0xef, 0x98, 0x82, 0x0a }, { 0x7a, 0xf5, 0xe4, 0xd4 } }, // 01000000 mmatrix.key { 0x03, { 0x0d, 0xb7, 0x88, 0xb7, 0xcd, 0x75 }, { 0x8a, 0xad, 0x7a, 0x6c }, { 0xd5, 0x2b, 0xb5, 0x50 } }, // 01000001 mmatrixa.key { 0x03, { 0x0d, 0xb7, 0x88, 0xb7, 0xcd, 0x77 }, { 0x10, 0x66, 0xdd, 0x3a }, { 0xa5, 0xe0, 0x7e, 0xc8 } }, // 01000010 mmatrixj.key { 0x05, { 0x84, 0xc2, 0xf8, 0xb3, 0x16, 0x47 }, { 0x61, 0x17, 0x8a, 0x9d }, { 0x8e, 0x0b, 0xbe, 0xa4 } }, // 01000011 mpang.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x83 }, { 0xa2, 0xea, 0xa7, 0x9d }, { 0x91, 0xde, 0x21, 0x60 } }, // 01000100 msh.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x82 }, { 0xf2, 0x8f, 0xa4, 0x72 }, { 0x03, 0x5d, 0x7a, 0x88 } }, // 01000101 msha.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x81 }, { 0x9c, 0x7f, 0x92, 0xd5 }, { 0xa0, 0x92, 0xa1, 0x78 } }, // 01000110 mshb.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x80 }, { 0x26, 0x0c, 0xe6, 0xb4 }, { 0x29, 0x68, 0xc8, 0xfc } }, // 01000111 mshh.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x81 }, { 0x0a, 0x12, 0xd6, 0x32 }, { 0x61, 0x04, 0x5e, 0x80 } }, // 01001000 mshj.key { 0x07, { 0x04, 0xc1, 0x9a, 0x62, 0x60, 0x83 }, { 0x66, 0x33, 0xa1, 0x49 }, { 0xc9, 0x16, 0x83, 0x84 } }, // 01001001 mshu.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x90, 0x23 }, { 0xf6, 0x93, 0xac, 0xe4 }, { 0x19, 0xd4, 0x87, 0x20 } }, // 01001010 mshvsf.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x90, 0x20 }, { 0x6f, 0x7a, 0x48, 0xc2 }, { 0x19, 0x7f, 0x1d, 0x28 } }, // 01001011 mshvsfa.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x90, 0x22 }, { 0x01, 0x1f, 0x3f, 0x6a }, { 0x4b, 0x8c, 0x59, 0x6c } }, // 01001100 mshvsfb.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x90, 0x22 }, { 0xd2, 0x87, 0x57, 0x00 }, { 0x8f, 0xda, 0x25, 0xf8 } }, // 01001101 mshvsfh.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x90, 0x20 }, { 0xb4, 0x1f, 0x91, 0x94 }, { 0x7e, 0x27, 0x0e, 0xe8 } }, // 01001110 mshvsfj.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x90, 0x20 }, { 0x53, 0x62, 0xbd, 0xce }, { 0x3a, 0x4a, 0xdb, 0x14 } }, // 01001111 mshvsfu.key { 0x07, { 0x04, 0xc1, 0x3a, 0x62, 0x12, 0x03 }, { 0x93, 0x7a, 0x58, 0xe1 }, { 0xed, 0x69, 0x00, 0x48 } }, // 01010000 mvsc.key { 0x07, { 0x04, 0xc1, 0x3a, 0x62, 0x12, 0x03 }, { 0xa2, 0xce, 0x82, 0x79 }, { 0x8d, 0xd4, 0x49, 0x3c } }, // 01010001 mvsca.key { 0x07, { 0x04, 0xc1, 0x3a, 0x62, 0x12, 0x00 }, { 0x67, 0xb5, 0x0e, 0x2b }, { 0x5d, 0xac, 0xb8, 0x40 } }, // 01010010 mvscb.key { 0x07, { 0x04, 0xc1, 0x3a, 0x62, 0x12, 0x03 }, { 0xdc, 0x63, 0x5a, 0x9f }, { 0x11, 0x78, 0xea, 0xe4 } }, // 01010011 mvsch.key { 0x07, { 0x04, 0xc1, 0x3a, 0x62, 0x12, 0x00 }, { 0x35, 0xf1, 0x23, 0xa4 }, { 0x72, 0x1a, 0x0f, 0xd4 } }, // 01010100 mvscj.key { 0x07, { 0x04, 0xc1, 0x3a, 0x62, 0x12, 0x02 }, { 0x80, 0x4e, 0x3d, 0xfb }, { 0x60, 0x8e, 0xd2, 0x58 } }, // 01010101 mvscu.key { 0x03, { 0x70, 0x40, 0x00, 0x00, 0x1a, 0x1a }, { 0x81, 0x68, 0x3f, 0x02 }, { 0x8a, 0x2e, 0x60, 0x20 } }, // 01010110 nwarr.key { 0x03, { 0x70, 0x40, 0x00, 0x00, 0x1a, 0x18 }, { 0x96, 0x18, 0x76, 0x70 }, { 0xc2, 0xc0, 0xa5, 0xc8 } }, // 01010111 nwarra.key { 0x03, { 0x70, 0x40, 0x00, 0x00, 0x1a, 0x18 }, { 0x11, 0x51, 0xb3, 0xb6 }, { 0x42, 0x39, 0x8f, 0xa0 } }, // 01011000 nwarrb.key { 0x03, { 0x70, 0x40, 0x00, 0x00, 0x1a, 0x18 }, { 0x10, 0x18, 0xa5, 0x52 }, { 0x03, 0x61, 0xa4, 0x8c } }, // 01011001 nwarrh.key { 0x03, { 0x70, 0x40, 0x00, 0x00, 0x1a, 0x19 }, { 0xe1, 0x7b, 0x63, 0xf0 }, { 0xc2, 0xf9, 0x48, 0x20 } }, // 01011010 nwarru.key { 0x05, { 0x04, 0xc0, 0xbb, 0xe1, 0x22, 0xc3 }, { 0xac, 0xa7, 0xc4, 0x30 }, { 0x0f, 0x5d, 0x2f, 0xa4 } }, // 01011011 pfghtj.key { 0x07, { 0x70, 0x30, 0x04, 0x00, 0x10, 0x09 }, { 0xe7, 0xe0, 0x42, 0x71 }, { 0x47, 0x40, 0xca, 0xe4 } }, // 01011100 pgear.key { 0x02, { 0x04, 0xc2, 0x17, 0x1b, 0x2c, 0x77 }, { 0x3e, 0xc3, 0x23, 0xdd }, { 0x8c, 0x6d, 0x67, 0x18 } }, // 01011101 progear.key { 0x02, { 0x04, 0xc2, 0x17, 0x1b, 0x2c, 0x75 }, { 0xeb, 0x64, 0xee, 0xfc }, { 0x52, 0x35, 0x46, 0x98 } }, // 01011110 progeara.key { 0x02, { 0x04, 0xc2, 0x17, 0x1b, 0x2c, 0x75 }, { 0xf7, 0x8b, 0x7e, 0x71 }, { 0xa8, 0xed, 0xfb, 0xe4 } }, // 01011111 progearj.key { 0x01, { 0x04, 0xc3, 0x39, 0x66, 0x3e, 0xa0 }, { 0xb5, 0xb2, 0xc0, 0x8d }, { 0x20, 0x7c, 0xa8, 0x14 } }, // 01100000 pzloop2.key { 0x07, { 0x04, 0xc3, 0x3a, 0x63, 0x90, 0x40 }, { 0x67, 0x83, 0x59, 0xbf }, { 0x39, 0x5c, 0x80, 0x68 } }, // 01100001 qndream.key { 0x04, { 0x70, 0x30, 0x04, 0x00, 0x10, 0x0b }, { 0x02, 0x48, 0x8b, 0xa3 }, { 0x93, 0x80, 0xa6, 0x60 } }, // 01100010 ringdest.key { 0x04, { 0x70, 0x30, 0x04, 0x00, 0x10, 0x0b }, { 0x02, 0x12, 0x8b, 0xa3 }, { 0x93, 0x80, 0xa6, 0x60 } }, // 01100011 ringdesta.key { 0x04, { 0x70, 0x30, 0x04, 0x00, 0x10, 0x0b }, { 0x00, 0x73, 0x8b, 0xa3 }, { 0x93, 0x80, 0xa6, 0x60 } }, // 01100100 ringdesth.key { 0x05, { 0x04, 0xc0, 0x9a, 0x80, 0xa6, 0x10 }, { 0x2d, 0x31, 0x7f, 0xb2 }, { 0x02, 0xaa, 0x13, 0x80 } }, // 01100101 rmancp2j.key { 0x05, { 0x04, 0xc0, 0x9a, 0x02, 0x02, 0x38 }, { 0x39, 0x22, 0xa8, 0x23 }, { 0x39, 0x4d, 0xe6, 0x30 } }, // 01100110 rockman2j.key { 0x05, { 0x04, 0xc0, 0x9a, 0x80, 0xa6, 0x13 }, { 0x61, 0x73, 0x90, 0x8d }, { 0xda, 0xea, 0x47, 0xc0 } }, // 01100111 sfa.key { 0x05, { 0x04, 0xc2, 0x70, 0x33, 0x07, 0xa6 }, { 0x7e, 0x1f, 0x7f, 0x70 }, { 0xe7, 0xcd, 0x48, 0xfc } }, // 01101000 sfa2.key { 0x05, { 0x04, 0xc2, 0x70, 0x33, 0x07, 0xa5 }, { 0x4a, 0x18, 0xbd, 0x45 }, { 0xa6, 0xf3, 0xf7, 0x60 } }, // 01101001 sfa2u.key { 0x05, { 0x04, 0xc1, 0x18, 0xe0, 0x56, 0xbe }, { 0x0e, 0xec, 0x07, 0x90 }, { 0x1c, 0x4f, 0xf5, 0x58 } }, // 01101010 sfa3.key { 0x05, { 0x04, 0xc1, 0x18, 0xe0, 0x56, 0xbd }, { 0xa5, 0x2d, 0xa2, 0x05 }, { 0x34, 0x0e, 0x10, 0xac } }, // 01101011 sfa3b.key { 0x05, { 0x04, 0xc1, 0x18, 0xe0, 0x56, 0xbe }, { 0x1b, 0x17, 0xa3, 0x78 }, { 0xc7, 0xed, 0x10, 0x84 } }, // 01101100 sfa3h.key { 0x05, { 0x04, 0xc1, 0x18, 0xe0, 0x56, 0xbc }, { 0x49, 0x30, 0xa7, 0x9a }, { 0x9c, 0x3f, 0x77, 0x9c } }, // 01101101 sfa3u.key { 0x05, { 0x04, 0xc0, 0x9a, 0x80, 0xa6, 0x10 }, { 0x60, 0x0b, 0xcf, 0xa5 }, { 0xb2, 0xd5, 0xf6, 0x90 } }, // 01101110 sfau.key { 0x05, { 0x04, 0xc2, 0x70, 0x33, 0x07, 0xa7 }, { 0x84, 0xa4, 0x7b, 0x08 }, { 0xbc, 0x5d, 0x0f, 0xd4 } }, // 01101111 sfz2a.key { 0x05, { 0x04, 0xc3, 0x39, 0xc4, 0x22, 0x25 }, { 0x96, 0x11, 0x80, 0x80 }, { 0x2c, 0x0d, 0x3a, 0x3c } }, // 01110000 sfz2al.key { 0x05, { 0x04, 0xc3, 0x39, 0xc4, 0x22, 0x24 }, { 0xe3, 0xd7, 0x07, 0xfc }, { 0x51, 0x4a, 0xcf, 0x38 } }, // 01110001 sfz2alb.key { 0x05, { 0x04, 0xc3, 0x39, 0xc4, 0x22, 0x25 }, { 0x8c, 0x40, 0xc0, 0x10 }, { 0xfb, 0x6a, 0x3e, 0xa4 } }, // 01110010 sfz2alh.key { 0x05, { 0x04, 0xc3, 0x39, 0xc4, 0x22, 0x26 }, { 0xc8, 0xd1, 0x40, 0x14 }, { 0x44, 0xc2, 0x8a, 0x64 } }, // 01110011 sfz2alj.key { 0x05, { 0x04, 0xc2, 0x70, 0x33, 0x07, 0xa5 }, { 0xd3, 0x74, 0x7e, 0x1a }, { 0x66, 0x8b, 0x20, 0xd4 } }, // 01110100 sfz2b.key { 0x05, { 0x04, 0xc2, 0x70, 0x33, 0x07, 0xa7 }, { 0xe4, 0x43, 0x7a, 0x69 }, { 0x0a, 0xd1, 0x46, 0x7c } }, // 01110101 sfz2h.key { 0x05, { 0x04, 0xc2, 0x70, 0x33, 0x07, 0xa6 }, { 0x22, 0x13, 0xb9, 0x6e }, { 0x65, 0xf8, 0xbf, 0x04 } }, // 01110110 sfz2j.key { 0x05, { 0x04, 0xc2, 0x70, 0x33, 0x07, 0xa4 }, { 0xed, 0x8b, 0x7a, 0x94 }, { 0xe4, 0x7f, 0x53, 0x1c } }, // 01110111 sfz2n.key { 0x05, { 0x04, 0xc1, 0x18, 0xe0, 0x56, 0xbd }, { 0xf8, 0xd0, 0x9c, 0x96 }, { 0x03, 0x27, 0x42, 0x64 } }, // 01111000 sfz3a.key { 0x05, { 0x04, 0xc1, 0x18, 0xe0, 0x56, 0xbe }, { 0x7a, 0xd1, 0xf4, 0xc3 }, { 0x00, 0x7e, 0x4a, 0xf8 } }, // 01111001 sfz3j.key { 0x05, { 0x04, 0xc0, 0x9a, 0x80, 0xa6, 0x13 }, { 0xf9, 0x67, 0x61, 0x18 }, { 0x42, 0x8e, 0xf0, 0x9c } }, // 01111010 sfza.key { 0x05, { 0x04, 0xc0, 0x9a, 0x80, 0xa6, 0x10 }, { 0x05, 0x8d, 0x25, 0x7b }, { 0x2f, 0x6a, 0x0b, 0xdc } }, // 01111011 sfzb.key { 0x05, { 0x04, 0xc0, 0x9a, 0x80, 0xa6, 0x12 }, { 0x2f, 0xc9, 0x14, 0xea }, { 0x71, 0xc3, 0x5b, 0x84 } }, // 01111100 sfzh.key { 0x05, { 0x04, 0xc0, 0x9a, 0x80, 0xa6, 0x12 }, { 0x8b, 0xc1, 0xe5, 0x0d }, { 0x79, 0xa3, 0x36, 0xc4 } }, // 01111101 sfzj.key { 0x05, { 0x04, 0xc0, 0xbb, 0xe1, 0x22, 0xc1 }, { 0xfb, 0x77, 0xc1, 0xe9 }, { 0xba, 0x4b, 0x10, 0x84 } }, // 01111110 sgemf.key { 0x05, { 0x04, 0xc0, 0xbb, 0xe1, 0x22, 0xc3 }, { 0x26, 0x5d, 0xf8, 0x8d }, { 0x52, 0x0b, 0x42, 0x40 } }, // 01111111 sgemfa.key { 0x05, { 0x04, 0xc0, 0xbb, 0xe1, 0x22, 0xc0 }, { 0x91, 0x2f, 0xc4, 0xfb }, { 0x63, 0x97, 0x1a, 0x04 } }, // 10000000 sgemfh.key { 0x04, { 0x70, 0x30, 0x04, 0x00, 0x10, 0x0b }, { 0x00, 0xa3, 0x03, 0xa2 }, { 0x41, 0x00, 0xa6, 0x60 } }, // 10000001 smbomb.key { 0x08, { 0x04, 0xc2, 0x70, 0x32, 0x60, 0x67 }, { 0x9d, 0xe1, 0x06, 0xaa }, { 0x43, 0xd9, 0x1e, 0xec } }, // 10000010 spf2t.key { 0x08, { 0x04, 0xc2, 0x70, 0x32, 0x60, 0x67 }, { 0x7c, 0xb3, 0xc1, 0xaf }, { 0x56, 0x1c, 0x48, 0xe4 } }, // 10000011 spf2ta.key { 0x08, { 0x04, 0xc2, 0x70, 0x32, 0x60, 0x65 }, { 0xb6, 0x87, 0xc5, 0x13 }, { 0x54, 0xc6, 0xde, 0x28 } }, // 10000100 spf2th.key { 0x08, { 0x04, 0xc2, 0x70, 0x32, 0x60, 0x66 }, { 0x86, 0x0f, 0xc2, 0xf8 }, { 0x2b, 0x85, 0x58, 0x38 } }, // 10000101 spf2tu.key { 0x08, { 0x04, 0xc2, 0x70, 0x32, 0x60, 0x67 }, { 0xfd, 0xba, 0x42, 0x5d }, { 0x6b, 0x04, 0xd2, 0x34 } }, // 10000110 spf2xj.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x12 }, { 0x03, 0xde, 0xcf, 0x56 }, { 0x47, 0x9a, 0x8b, 0x10 } }, // 10000111 ssf2.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x11 }, { 0x20, 0x3d, 0xec, 0xf5 }, { 0x64, 0x79, 0xa8, 0xb0 } }, // 10001000 ssf2a.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x10 }, { 0xb1, 0x20, 0x3d, 0xec }, { 0xf5, 0x64, 0x79, 0xa8 } }, // 10001001 ssf2h.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x13 }, { 0xde, 0xcf, 0x56, 0x47 }, { 0x9a, 0x8b, 0x12, 0x00 } }, // 10001010 ssf2j.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x10 }, { 0xf0, 0xa3, 0x2d, 0xa9 }, { 0x03, 0x05, 0xc8, 0xa4 } }, // 10001011 ssf2t.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x12 }, { 0x38, 0xa1, 0x49, 0x99 }, { 0x00, 0x2c, 0x8c, 0xa4 } }, // 10001100 ssf2ta.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x13 }, { 0x9a, 0x8b, 0x12, 0x03 }, { 0xde, 0xcf, 0x56, 0x44 } }, // 10001101 ssf2tb.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x10 }, { 0x79, 0xa8, 0xb1, 0x20 }, { 0x3d, 0xec, 0xf5, 0x64 } }, // 10001110 ssf2tba.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x11 }, { 0x64, 0x79, 0xa8, 0xb1 }, { 0x20, 0x3d, 0xec, 0xf4 } }, // 10001111 ssf2tbh.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x12 }, { 0x8b, 0x12, 0x03, 0xde }, { 0xcf, 0x56, 0x47, 0x98 } }, // 10010000 ssf2tbj.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x11 }, { 0xa8, 0xb1, 0x20, 0x3d }, { 0xec, 0xf5, 0x64, 0x78 } }, // 10010001 ssf2tbu.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x11 }, { 0x30, 0xa2, 0x12, 0xb9 }, { 0x02, 0xd1, 0xc0, 0xa4 } }, // 10010010 ssf2th.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x13 }, { 0xf0, 0xa3, 0xb8, 0xc9 }, { 0x02, 0x45, 0x7c, 0xa4 } }, // 10010011 ssf2tu.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x10 }, { 0x3d, 0xec, 0xf5, 0x64 }, { 0x79, 0xa8, 0xb1, 0x20 } }, // 10010100 ssf2u.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x11 }, { 0xc0, 0xa0, 0xd6, 0x81 }, { 0x03, 0xa9, 0x50, 0xa4 } }, // 10010101 ssf2xj.key { 0x00, { 0x70, 0x43, 0x80, 0x00, 0x00, 0x11 }, { 0x10, 0xa2, 0xcd, 0x79 }, { 0x03, 0x50, 0xf0, 0xa4 } }, // 10010110 ssf2xjr1r.key { 0x03, { 0x70, 0x43, 0x00, 0x02, 0x8b, 0x39 }, { 0xb8, 0x65, 0x74, 0xed }, { 0xfe, 0x30, 0x23, 0x24 } }, // 10010111 uecology.key { 0x05, { 0x70, 0x40, 0x00, 0x00, 0x1a, 0x19 }, { 0xd6, 0x60, 0x59, 0x00 }, { 0x80, 0x43, 0x4f, 0xdc } }, // 10011000 vampj.key { 0x05, { 0x04, 0xc1, 0x25, 0x80, 0x1b, 0x80 }, { 0x63, 0xc2, 0x35, 0x93 }, { 0x17, 0x5e, 0x0d, 0xb0 } }, // 10011001 vhunt2.key { 0x03, { 0x70, 0x40, 0x00, 0x00, 0x1a, 0x19 }, { 0x3f, 0xae, 0x5c, 0x97 }, { 0x0d, 0x36, 0xb2, 0x20 } }, // 10011010 vhuntj.key { 0x05, { 0x04, 0xc1, 0x59, 0x3b, 0xd7, 0x48 }, { 0x3b, 0x75, 0x76, 0x3a }, { 0x04, 0x6a, 0xcc, 0x1c } }, // 10011011 vsav.key { 0x05, { 0x04, 0xc1, 0x25, 0x80, 0x1b, 0x83 }, { 0xed, 0xe3, 0xb0, 0x18 }, { 0xbc, 0x9e, 0x05, 0xac } }, // 10011100 vsav2.key { 0x05, { 0x04, 0xc1, 0x59, 0x3b, 0xd7, 0x48 }, { 0xd5, 0x20, 0xb4, 0x24 }, { 0x32, 0x65, 0xdf, 0x88 } }, // 10011101 vsava.key { 0x05, { 0x04, 0xc1, 0x59, 0x3b, 0xd7, 0x48 }, { 0x77, 0x2e, 0xf0, 0xf1 }, { 0x51, 0x17, 0xbf, 0x60 } }, // 10011110 vsavb.key { 0x05, { 0x04, 0xc1, 0x59, 0x3b, 0xd7, 0x4a }, { 0xed, 0x57, 0xb7, 0x2e }, { 0xc4, 0xfb, 0x2d, 0x34 } }, // 10011111 vsavh.key { 0x05, { 0x04, 0xc1, 0x59, 0x3b, 0xd7, 0x4a }, { 0x76, 0x04, 0x74, 0x97 }, { 0x31, 0xcb, 0xc5, 0x7c } }, // 10100000 vsavj.key { 0x05, { 0x04, 0xc1, 0x59, 0x3b, 0xd7, 0x49 }, { 0x9f, 0x01, 0xf3, 0xa9 }, { 0xdc, 0x15, 0xd1, 0x94 } }, // 10100001 vsavu.key { 0x05, { 0x04, 0xc1, 0x3a, 0x62, 0x03, 0x02 }, { 0x29, 0x00, 0x7f, 0xa4 }, { 0x96, 0xdd, 0x8f, 0x70 } }, // 10100010 xmcota.key { 0x05, { 0x04, 0xc1, 0x3a, 0x62, 0x03, 0x00 }, { 0xe1, 0x87, 0xf3, 0x6d }, { 0x1c, 0x96, 0xa7, 0x80 } }, // 10100011 xmcotaa.key { 0x05, { 0x04, 0xc1, 0x3a, 0x62, 0x03, 0x00 }, { 0xa9, 0x65, 0xac, 0xe3 }, { 0x10, 0x1f, 0xf7, 0x84 } }, // 10100100 xmcotab.key { 0x05, { 0x04, 0xc1, 0x3a, 0x62, 0x03, 0x03 }, { 0xa1, 0x35, 0xa4, 0x14 }, { 0xb0, 0xec, 0x5e, 0xbc } }, // 10100101 xmcotah.key { 0x05, { 0x04, 0xc1, 0x3a, 0x62, 0x03, 0x01 }, { 0xe6, 0xcf, 0x47, 0xd6 }, { 0xa3, 0x39, 0x01, 0x88 } }, // 10100110 xmcotaj.key { 0x05, { 0x04, 0xc1, 0x3a, 0x62, 0x03, 0x03 }, { 0x4b, 0xda, 0x00, 0x66 }, { 0xcd, 0xfa, 0x95, 0x30 } }, // 10100111 xmcotau.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x93, 0x01 }, { 0x5c, 0xd5, 0x37, 0xf2 }, { 0x62, 0x87, 0xce, 0xf4 } }, // 10101000 xmvsf.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x93, 0x00 }, { 0x26, 0xdf, 0x56, 0x61 }, { 0xf0, 0xfc, 0x70, 0xb8 } }, // 10101001 xmvsfa.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x93, 0x00 }, { 0x3c, 0x86, 0x10, 0x35 }, { 0x49, 0xe6, 0xd5, 0xc4 } }, // 10101010 xmvsfb.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x93, 0x03 }, { 0xb2, 0x25, 0x7d, 0x08 }, { 0x2d, 0x37, 0xeb, 0x04 } }, // 10101011 xmvsfh.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x93, 0x00 }, { 0xd7, 0x3b, 0x02, 0x10 }, { 0xf7, 0x27, 0xec, 0x70 } }, // 10101100 xmvsfj.key { 0x07, { 0x04, 0xc1, 0x3a, 0x63, 0x93, 0x02 }, { 0x0f, 0x72, 0x98, 0x7d }, { 0x2f, 0x03, 0x4f, 0xc8 } }, // 10101101 xmvsfu.key // also used with invalid jumper configs { 0x09, { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, { 0xff, 0xff, 0xff, 0xff }, { 0xff, 0xff, 0xff, 0xff } }, // 10101110 phoenix.key }; void setup() { delay(500); // set the programming pins as outputs PORTB.DIR = PIN0_bm | PIN1_bm | PIN2_bm | PIN3_bm; // enable pull-ups on jumper pins PORTA.PIN0CTRL |= PORT_PULLUPEN_bm; PORTA.PIN1CTRL |= PORT_PULLUPEN_bm; PORTA.PIN2CTRL |= PORT_PULLUPEN_bm; PORTA.PIN3CTRL |= PORT_PULLUPEN_bm; PORTA.PIN4CTRL |= PORT_PULLUPEN_bm; PORTA.PIN5CTRL |= PORT_PULLUPEN_bm; PORTA.PIN6CTRL |= PORT_PULLUPEN_bm; PORTA.PIN7CTRL |= PORT_PULLUPEN_bm; // go into programming mode CLR_CLOCK; CLR_DATA; SET_SETUP; CLR_RESET; delay(100); uint8_t [MASK] = read_jumpers(); if( [MASK] > MAX_GAME_NUM) { [MASK] = MAX_GAME_NUM; } for(uint8_t i = 0; i < CONFIG_SIZE; i++) { send_byte(config_table[game_data[ [MASK] ].config_table_index][i]); } for(uint8_t i = 0; i < WATCHDOG_SIZE; i++) { send_byte(game_data[ [MASK] ].watchdog[i]); } for(uint8_t i = 0; i < KEY_SIZE; i++) { send_byte(game_data[ [MASK] ].key2[i]); } for(uint8_t i = 0; i < KEY_SIZE; i++) { send_byte(game_data[ [MASK] ].key1[i]); } // exit programming mode CLR_SETUP; SET_RESET; CLR_CLOCK; CLR_DATA; // set all output pins as inputs PORTB.DIR = 0; // power down set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_enable(); sleep_cpu(); } void loop() { } void send_byte(uint8_t data) { for(int8_t bit_num = 7; bit_num >= 0;bit_num--) { uint8_t bit = data & masks[bit_num]; if(bit) { SET_DATA; } else { CLR_DATA; } SET_CLOCK; CLR_CLOCK; } } // JP1 = PA7 = bit7 // JP2 = PA6 = bit6 // JP3 = PA5 = bit5 // JP4 = PA6 = bit4 // JP5 = PA0 = bit3 // JP6 = PA1 = bit2 // JP7 = PA2 = bit1 // JP8 = PA3 = bit0 uint8_t read_jumpers() { uint8_t jumpers = 0; uint8_t raw; uint8_t bit; // negate the bits since we are using // pull-ups, jumper'd will be low raw = PORTA.IN ^ 0xff; // upper nible is in the correct order, but lower isnt jumpers = raw & 0xf0; // reverse the order of the lower nibble bit = (raw & 0x1) << 3; jumpers = jumpers | bit; bit = (raw & 0x2) << 1; jumpers = jumpers | bit; bit = (raw & 0x4) >> 1; jumpers = jumpers | bit; bit = (raw & 0x8) >> 3; jumpers = jumpers | bit; return jumpers; } ",game_num 60,"// Fill out your copyright notice in the Description page of Project Settings. //#include ""SCharacter.h"" #include ""../Public/SCharacter.h"" #include ""Camera/CameraComponent.h"" #include ""GameFramework/SpringArmComponent.h"" #include ""GameFramework/PawnMovementComponent.h"" #include ""../Public/SWeapon.h"" #include ""Engine/Engine.h"" #include ""CoopGame.h"" #include ""Components/CapsuleComponent.h"" // Sets default values ASCharacter::ASCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; CameraComp = CreateDefaultSubobject(TEXT(""CameraComp"")); SpringArmComp = CreateDefaultSubobject(TEXT(""SpringArm"")); SpringArmComp->SetupAttachment(RootComponent); //CameraComp->bUsePawnControlRotation = true; CameraComp->SetupAttachment(SpringArmComp); GetMovementComponent()->GetNavAgentPropertiesRef().bCanCrouch = true; GetCapsuleComponent()->SetCollisionResponseToChannel(WEAPONCOLLISIONCHANNEL, ECR_Ignore); ZoomedFOV = 65.0f; ZoomInterpSpeed = 20.0f; } // Called when the game starts or when spawned void ASCharacter::BeginPlay() { Super::BeginPlay(); DefaultFOV = CameraComp->FieldOfView; GenWeapon(Weapon1); } void ASCharacter::MoveForward(float value) { AddMovementInput(GetActorForwardVector() * value); } void ASCharacter::MoveRight(float value) { AddMovementInput(GetActorRightVector() * value); } void ASCharacter::BeginCrouch() { Crouch(); } void ASCharacter::EndCrouch() { UnCrouch(); } void ASCharacter::BeginZoom() { bWantsToZoom = true; } void ASCharacter::EndZoom() { bWantsToZoom = false; } //void ASCharacter::Fire() //{ // if (CurrentWeapon) // { // CurrentWeapon->Fire(); // } //} void ASCharacter::SwitchWeapons(FKey Key) { //FString KeyName = Key.ToString(); //UE_LOG(LogTemp, Log, TEXT(""%s""), *KeyName); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, FString::Printf(TEXT(""%s""), *KeyName)); if (CurrentWeapon) { CurrentWeapon->Destroy(); } if (Key == EKeys::One) { GenWeapon(Weapon1); return; } if (Key == EKeys::Two) { GenWeapon(Weapon2); return; } } void ASCharacter::GenWeapon(TSubclassOf& Weapon) { if (Weapon) { FActorSpawnParameters SpawnParams; SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; CurrentWeapon = GetWorld()->SpawnActor(Weapon, FVector::ZeroVector, FRotator::ZeroRotator, SpawnParams); if (CurrentWeapon) { CurrentWeapon->SetOwner(this); CurrentWeapon->AttachToComponent(GetMesh(), FAttachmentTransformRules::SnapToTargetNotIncludingScale, CurrentWeapon->CharaterAttachSockName); } } } void ASCharacter::StartFire() { if (CurrentWeapon) { CurrentWeapon->StartFire(); } } void ASCharacter::StopFire() { if (CurrentWeapon) { CurrentWeapon->StopFire(); } } // Called every frame void ASCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); float [MASK] = bWantsToZoom ? ZoomedFOV : DefaultFOV; float CurrentFOV = FMath::FInterpTo(CameraComp->FieldOfView, [MASK] , DeltaTime, ZoomInterpSpeed); CameraComp->SetFieldOfView(CurrentFOV); } // Called to bind functionality to input void ASCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAxis(""MoveForward"", this, &ASCharacter::MoveForward); PlayerInputComponent->BindAxis(""MoveRight"", this, &ASCharacter::MoveRight); PlayerInputComponent->BindAxis(""LookUp"", this, &ASCharacter::AddControllerPitchInput); PlayerInputComponent->BindAxis(""Turn"", this, &ASCharacter::AddControllerYawInput); PlayerInputComponent->BindAction(""Crouch"", IE_Pressed, this, &ASCharacter::BeginCrouch); PlayerInputComponent->BindAction(""Crouch"", IE_Released, this, &ASCharacter::EndCrouch); PlayerInputComponent->BindAction(""Jump"", IE_Pressed, this, &ASCharacter::Jump); PlayerInputComponent->BindAction(""Zoom"", IE_Pressed, this, &ASCharacter::BeginZoom); PlayerInputComponent->BindAction(""Zoom"", IE_Released, this, &ASCharacter::EndZoom); PlayerInputComponent->BindAction(""Fire"", IE_Pressed, this, &ASCharacter::StartFire); PlayerInputComponent->BindAction(""Fire"", IE_Released, this, &ASCharacter::StopFire); PlayerInputComponent->BindAction(""SwitchWeapons"", IE_Pressed, this, &ASCharacter::SwitchWeapons); } FVector ASCharacter::GetPawnViewLocation() const { if (CameraComp) { return CameraComp->GetComponentLocation(); } return Super::GetPawnViewLocation(); } ",TargetFOV 61,"#include #include #include #include using namespace std; ifstream inputFileObj; ofstream outputFileObj; int main() { namespace fs = std::filesystem; double sum = 0; double average = 0; // long numberbuffer = 0; std::string stringbuffer; vector values; vector lines; fs::path nums_path(""numbers.txt""); fs::path input_strings_path(""InputStrings.txt""); fs::path [MASK] (""RandomStrings.txt""); inputFileObj.open(nums_path); if (inputFileObj.is_open()) { cout << ""Contents of file numbers.txt:"" << endl; while (std::getline(inputFileObj, stringbuffer)) { if (stringbuffer.empty()) { continue; } cout << ""["" << stringbuffer << ""]"" << endl; values.push_back(std::stol(stringbuffer)); } for (long num : values) { sum += num; } average = sum / values.size(); inputFileObj.close(); } else { cerr << ""Error opening file.\n""; } cout << ""\n[=][=][=][=][=][=][=][=][=][=][=][=][=][=][=][=][=][=]\n"" << endl; inputFileObj.open(input_strings_path); if (inputFileObj.is_open()) { cout << ""Contents of file InputStrings.txt:"" << endl; while (std::getline(inputFileObj, stringbuffer)) { if (stringbuffer.empty()) { continue; } cout << ""["" << stringbuffer << ""]"" << endl; lines.push_back(stringbuffer); } } else { cerr << ""Error opening file.\n""; } cout << endl; cout << ""Strings in InputStrings.txt:"" << endl; for (std::string line : lines) { cout << line << endl; } cout << endl; printf(""Number of values: %d \n"", (int) values.size()); printf(""Sum of values: %.2f \n"", sum); printf(""Average of values: %.2f \n"", average); //Creates a file called ""RandomStrings.txt"" in the project's DerivedData folder. outputFileObj.open( [MASK] ); for (int i = 0; i < 1000; i++) { outputFileObj << ""Whooooaaaa duuuude!!\n""; } outputFileObj.close(); printf(""Program done!\n""); return EXIT_SUCCESS; } ",input_random_strings_path 62,"#ifndef _RESOURCEPOOL_H #define _RESOURCEPOOL_H #include #include #include #include #include #include #include #include #include ""ResourcePoolConfig.h"" namespace bt = boost::this_thread; namespace bpt = boost::posix_time; namespace common_pool { template class ResourcePool; template class ResourceWrapper { public: ResourceWrapper(T *t_, ResourcePool *pool, long expireMillis_) { t = t_; resourcePool = pool; updateLastestUseTime(); expireMillis = expireMillis_; lastestUseTime = (long)clock.elapsed(); }; virtual ~ResourceWrapper() { if (t != NULL) { destory(); } }; //If the resource needs to be reclaimed //You can override this function virtual bool expired() { return (clock.elapsed() - lastestUseTime) * 1000.0 > (double)expireMillis; }; //If a resource needs to be managed virtual bool valid() { return true; } T *get() { updateLastestUseTime(); return t; }; virtual void destory() { t = NULL; resourcePool->recliam(this); }; void updateLastestUseTime() { lastestUseTime = clock.elapsed(); }; private: T *t; long expireMillis; boost::timer clock; double lastestUseTime; ResourcePool *resourcePool; }; //class ResourceWrapper template class ResourcePool { typedef ResourceWrapper Res; public: ResourcePool(ResourcePoolConfig &poolConfig) { started = false; config = poolConfig; resourceNum = 0; managedNum = 0; for (int i = 0; i < config.getPoolSize(); i++) { expand(); } minAvailableNum = config.getInitPoolSize(); started = true; //Create reclaim thread boost::thread(&common_pool::ResourcePool::relaimIdleResource, this, config.getReclaimInterval()); //Create refurbish thread boost::thread(&common_pool::ResourcePool::refurbish, this, config.getRefurbishInterval()); //Create shrink thread boost::thread(&common_pool::ResourcePool::shrink, this, config.getShrinkInterval()); } ~ResourcePool() { close(); }; //Get the number of managed resources int getManagedNum() { return managed.size(); }; //Get the number of unused resources int getUnusedNum() { return unused.size(); }; //Get the number of excluded resources int getExcludedNum() { return excluded.size(); }; //Get the number of resources int getResourceNum() { return resourceNum; }; //Get resource pool configuration ResourcePoolConfig& getConfig() { return config; }; virtual Res *genResource() { Res *res = NULL; if (unused.size() > 0) { T *t = *(unused.begin()); unused.pop_front(); if (t != NULL) { res = new Res(t, this, config.getExpireMillis()); boost::lock_guard reclaimLock(reclaimMutex); managed[res] = t; managedNum++; } if ((int)unused.size() < minAvailableNum) { minAvailableNum = (int)unused.size(); } } return res; }; //Reclaim a resource virtual void recliam(Res *resource) { if (resource != NULL) { boost::lock_guard reclaimLock(reclaimMutex); excluded.insert(managed[resource]); managed[resource] = NULL; resourceNum--; } }; protected: //Add a resource object the pool virtual void expand() { T *t = new T; if (t != NULL) { unused.push_back(t); } }; //Refurbish resources void refurbish(long interval) { while (started) { bt::sleep(bpt::milliseconds(interval)); //Refurbish when system is available if (!getResMutex.try_lock()) { continue;; } if (!reclaimMutex.try_lock()) { getResMutex.unlock(); } //Refurbish available resources if (unused.size() > 0) { list::iterator iter = unused.begin(); list::iterator swapIter; while (iter != unused.end()) { swapIter = iter; iter++; refurbishOne(**iter); } } reclaimMutex.unlock(); getResMutex.unlock(); } }; //Refurbish a single resource object virtual void refurbishOne(T &t) {}; //Shrink the pool to release redundant resources void shrink(long interval) { long windowNum = config.getShrinkWindow() / interval; boost::circular_buffer windowRemain((int) windowNum); float meanRemain = (float)minAvailableNum; while (started) { bt::sleep(bpt::milliseconds(interval)); doCheckinExcluded(); windowRemain.push_back(minAvailableNum); boost::lock_guard lock(getResMutex); { unsigned int shrinkSize = (unsigned int)getShrinkThreshold(windowRemain, meanRemain); boost::lock_guard reclaimLock(reclaimMutex); while (unused.size() > shrinkSize) { T *t = unused.back(); unused.pop_back(); delete t; resourceNum--; } minAvailableNum = resourceNum; } } }; //Remove a resource object out of the pool void removeResource() { T* t = unused.back(); unused.pop_back(); delete t; }; //Put exclude resources in unused space void doCheckinExcluded() { boost::lock_guard reclaimLock(reclaimMutex); if (excluded.size() > 0) { BOOST_FOREACH(T *t, excluded) { unused.push_back(t); } excluded.clear(); } }; //Collect void relaimIdleResource(long reclaimInterval) { while (started) { boost::this_thread::sleep(bpt::milliseconds(reclaimInterval)); boost::lock_guard lock(getResMutex); if (managed.size() > 0) { std::vector idleRes; boost::lock_guard reclaimLock(reclaimMutex); std::map::iterator iter = managed.begin(); for (; iter != managed.end(); iter++) { if (iter->second == NULL) { //Reclaim invalid resource idleRes.push_back(iter->first); } else if (iter->first->valid() && iter->first->expired()) { excluded.insert(iter->second); iter->second = NULL; idleRes.push_back(iter->first); } } if (idleRes.size() < 0) { std::vector::iterator idleIter = idleRes.begin(); for (; idleIter != idleRes.end(); idleIter++) { managed.erase(managed.find(*idleIter)); } } } } }; //Get the resource number that pool should shrink to int getShrinkThreshold(boost::circular_buffer &slideWindow, float meanRemain) { //The window iterator boost::circular_buffer::iterator iter = slideWindow.begin(); float [MASK] = 0.0f; while (iter != slideWindow.end()) { [MASK] += (float)*iter; iter++; } [MASK] = [MASK] / (float)slideWindow.size(); float diff = [MASK] - meanRemain; //If load goes down int shrinkSize = 0; if (diff > 0.0f) { shrinkSize = unused.size() - (int)diff; //When load goes down sharply if (shrinkSize < 0) { //If managed size is lower than initial number, set the total number to initialized number if (managed.size() < (unsigned int) config.getInitPoolSize()) { shrinkSize = config.getInitPoolSize() - (int)managed.size(); } //If managed size is larger than initial size, release all available resources else { shrinkSize = 0; } } } //If load goes up else if (diff < 0.0f) { //When average remaining number is larger than available number, //it means there is no load if ((unsigned int) [MASK] > unused.size() + managed.size()) { shrinkSize = (int)( [MASK] * SHRINK_FACTOR); } //Do not release if there is no load else { shrinkSize = 0; } } //If load doesn't change else { //No load if ((unsigned int) [MASK] == unused.size() + managed.size()) { shrinkSize = config.getInitPoolSize(); } //Has load { shrinkSize = (int)unused.size(); } } meanRemain = [MASK] ; return shrinkSize; }; //Close the pool void close() { started = false; config.setInitPoolSize(0); boost::lock_guard lock(getResMutex); { boost::lock_guard recliamLock(reclaimMutex); std::map::iterator iter = managed.begin(); while (iter != managed.end()) { if (iter->second != NULL) { unused.push_back(iter->second); } iter++; } managed.clear(); while (unused.size() > 0) { removeResource(); } } }; protected: //The ratio of shrined resources static const float SHRINK_FACTOR; //Managed resource std::map managed; //Unused resource std::list unused; //A swap space for reclaim //Some std::set excluded; //Configuration ResourcePoolConfig config; //If started bool started; //Get resource mutex boost::recursive_mutex getResMutex; //Reclaim mutex boost::recursive_mutex reclaimMutex; int minAvailableNum; int resourceNum; int managedNum; }; //class ResourcePool template const float common_pool::ResourcePool::SHRINK_FACTOR = 0.5f; } //namespace rpool #endif //_RESOURCEPOOL_H",sum 63,"#include #include #include #include using std::cout; using std::endl; using std::sqrt; using std::vector; bool is_prime(unsigned long int n) { if (n < 2) { return false; } // for (int i = 2; i < n; i++) { // cout << ""sqrt("" << n << ""): "" << sqrt(n) << endl; for (unsigned long int i = 2; i <= sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } int main() { cout << ""evildojo "" << endl; vector [MASK] ; // unsigned int max = 10; unsigned long int max = 2000000; for (unsigned long int i = 2; i < max; i++) { if (is_prime(i)) { [MASK] .push_back(i); } } unsigned long int sum = 0; for (int i = 0; i < [MASK] .size(); i++) { sum += [MASK] [i]; } // cout << LONG_MAX << endl; // cout << INT_MAX << endl; cout << sum << endl; return 0; } ",primes 64,"/* * A library for controlling a Microchip RN2483 LoRa radio. * * @Author * @Date 18/12/2015 * @ModifiedBy hsilomedus * */ #include ""Arduino.h"" #include ""rn2483.h"" extern ""C"" { #include #include } //#define DEBUG_PROFILE 1 //#ifdef DEBUG_PROFILE #define SH_DEBUG_PRINTLN(a) Serial.println(a) #define SH_DEBUG_PRINT(a) Serial.print(a) #define SH_DEBUG_PRINT_DEC(a,b) Serial.print(a,b) #define SH_DEBUG_PRINTLN_DEC(a,b) Serial.println(a,b) //#else // #define SH_DEBUG_PRINTLN(a) // #define SH_DEBUG_PRINT(a) // #define SH_DEBUG_PRINT_DEC(a,b) // #define SH_DEBUG_PRINTLN_DEC(a,b) //#endif /* @param serial Needs to be an already opened stream to write to and read from. */ rn2483::rn2483(SoftwareSerial& serial): _serial(serial) { _serial.setTimeout(2000); } // //rn2483::rn2483(HardwareSerial& serial): //_serial(serial) //{ // _serial.setTimeout(2000); //} void rn2483::autobaud() { String response = """"; while (response=="""") { delay(1000); _serial.write((byte)0x00); _serial.write(0x55); _serial.println(); _serial.println(""sys get ver""); response = _serial.readStringUntil('\n'); } } String rn2483::hweui() { //clear serial buffer while(_serial.read() != -1); _serial.println(""sys get hweui""); String addr = _serial.readStringUntil('\n'); addr.trim(); return addr; } String rn2483::sysver() { //clear serial buffer while(_serial.read() != -1); _serial.println(""sys get ver""); String ver = _serial.readStringUntil('\n'); ver.trim(); return ver; } void rn2483::init() { if(*_appeui==""0"") { return; } else if(_otaa==true) { // init(_appeui, _appskey); } else { init(_appeui, _nwkskey, _appskey, _devAddr, _dataRate); } } // //void rn2483::init(String AppEUI, String AppKey) //{ // _otaa = true; // _appeui = AppEUI; // _nwkskey = ""0""; // _appskey = AppKey; //reuse the variable // // //clear serial buffer // while(_serial.read() != -1); // // _serial.println(""sys get hweui""); // String addr = _serial.readStringUntil('\n'); // addr.trim(); // // _serial.println(""mac reset 868""); // String receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(receivedData); // // _serial.println(""mac set appeui ""+_appeui); // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(receivedData); // // _serial.println(""mac set appkey ""+_appskey); // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(receivedData); // // if(addr!="""" && addr.length() == 16) // { // _serial.println(""mac set deveui ""+addr); // } // else // { // _serial.println(""mac set deveui ""+_default_deveui); // } // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(receivedData); // // _serial.println(""mac set pwridx 1""); // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(receivedData); // // _serial.println(""mac set adr off""); // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(receivedData); //// //// _serial.println(""mac set dr 0""); //// receivedData = _serial.readStringUntil('\n'); //// SH_DEBUG_PRINT(receivedData); // // _serial.println(""mac set rx2 3 869525000""); //// _serial.println(""mac set rx2 0 869525000""); // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(receivedData); // // // _serial.println(""mac set retx 10""); // // _serial.readStringUntil('\n'); // // _serial.println(""mac set linkchk 60""); // // _serial.readStringUntil('\n'); // // _serial.println(""mac set ar on""); // // _serial.readStringUntil('\n'); // _serial.setTimeout(30000); // _serial.println(""mac save""); // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINTLN(receivedData); // // _serial.println(""mac get dr""); // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(""DR: ""); // SH_DEBUG_PRINTLN(receivedData); // // _serial.println(""radio get sf""); // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(""SF: ""); // SH_DEBUG_PRINTLN(receivedData); // // _serial.println(""mac get pwridx""); // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(""PWRIDX: ""); // SH_DEBUG_PRINTLN(receivedData); // // // bool joined = false; // // for(int i=0; i<10 && !joined; i++) // { // _serial.println(""mac join otaa""); // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(receivedData); // receivedData = _serial.readStringUntil('\n'); // SH_DEBUG_PRINT(receivedData); // // if(receivedData.startsWith(""accepted"")) // { // joined=true; // delay(1000); // } // else // { // delay(1000); // } // } // _serial.setTimeout(2000); //} char readBuf[21]; void rn2483::init(String* AppEUI, String* NwkSKey, String* AppSKey, String* addr, int dataRate) { _otaa = false; _appeui = AppEUI; _nwkskey = NwkSKey; _appskey = AppSKey; _devAddr = addr; _dataRate = dataRate; //clear serial buffer while(_serial.read() != -1); String RN2483 = ""RN2483 ""; readBuf[20] = 0; _serial.setTimeout(3000); SH_DEBUG_PRINT(RN2483); SH_DEBUG_PRINTLN(""reset""); _serial.println(""mac reset 868""); readreplyResponse(); SH_DEBUG_PRINT(RN2483); SH_DEBUG_PRINTLN(""set rx2""); _serial.println(""mac set rx2 3 869525000""); readreplyResponse(); SH_DEBUG_PRINT(RN2483); SH_DEBUG_PRINTLN(""set devaddr""); _serial.print(""mac set devaddr ""); _serial.println(*_devAddr); readreplyResponse(); SH_DEBUG_PRINT(RN2483); SH_DEBUG_PRINTLN(""set appskey""); _serial.print(""mac set appskey ""); _serial.println(*_appskey); readreplyResponse(); SH_DEBUG_PRINT(RN2483); SH_DEBUG_PRINTLN(""set nwskey""); _serial.print(""mac set nwkskey ""); _serial.println(*_nwkskey); readreplyResponse(); SH_DEBUG_PRINT(RN2483); SH_DEBUG_PRINTLN(""set adr off""); _serial.println(""mac set adr off""); readreplyResponse(); SH_DEBUG_PRINT(RN2483); SH_DEBUG_PRINTLN(""set ar off""); _serial.println(""mac set ar off""); readreplyResponse(); SH_DEBUG_PRINT(RN2483); SH_DEBUG_PRINTLN(""set pwridx 1""); _serial.println(""mac set pwridx 1""); //1=max, 5=min readreplyResponse(); SH_DEBUG_PRINT(RN2483); SH_DEBUG_PRINT(""set dr ""); SH_DEBUG_PRINTLN_DEC(_dataRate, DEC); _serial.print(""mac set dr ""); _serial.println(_dataRate, DEC); //0= min, 7=max readreplyResponse(); _serial.setTimeout(60000); SH_DEBUG_PRINT(RN2483); SH_DEBUG_PRINTLN(""save""); _serial.println(""mac save""); readreplyResponse(); SH_DEBUG_PRINT(RN2483); SH_DEBUG_PRINTLN(""join abp""); _serial.println(""mac join abp""); readreplyResponse(); readreplyResponse(); } void rn2483::readreplyResponse() { int read = _serial.readBytesUntil('\n', readBuf, 20); //#ifdef DEBUG_PROFILE Serial.write(readBuf, read); SH_DEBUG_PRINTLN(""""); //#endif delay(100); } void rn2483::tx(byte bytes[], int length) { txUncnf(bytes, length); //we are unsure which mode we're in. Better not to wait for acks. } //void rn2483::txCnf(byte bytes[], int length) //{ // txData(""mac tx cnf 1 "", bytes, length); //} void rn2483::txUncnf(byte bytes[], int length) { txData(""mac tx uncnf 1 "", bytes, length); } bool rn2483::txData(String command, byte bytes[], int length) { bool [MASK] = false; uint8_t busy_count = 0; uint8_t retry_count = 0; while(! [MASK] ) { //retransmit a maximum of 10 times retry_count++; if(retry_count>10) { return false; } _serial.print(command); sendEncoded(bytes, length); _serial.println(); String receivedData = _serial.readStringUntil('\n'); SH_DEBUG_PRINTLN(receivedData); if(receivedData.startsWith(""ok"")) { _serial.setTimeout(30000); receivedData = _serial.readStringUntil('\n'); SH_DEBUG_PRINTLN(receivedData); _serial.setTimeout(2000); if(receivedData.startsWith(""mac_tx_ok"")) { //SUCCESS!! [MASK] = true; return true; } else if(receivedData.startsWith(""mac_rx"")) { //we received data downstream //TODO: handle received data [MASK] = true; return true; } else if(receivedData.startsWith(""mac_err"")) { init(); } else if(receivedData.startsWith(""invalid_data_len"")) { //this should never happen if the prototype worked [MASK] = true; return false; } else if(receivedData.startsWith(""radio_tx_ok"")) { //SUCCESS!! [MASK] = true; return true; } else if(receivedData.startsWith(""radio_err"")) { //This should never happen. If it does, something major is wrong. init(); } else { //unknown response //init(); } } else if(receivedData.startsWith(""invalid_param"")) { //should not happen if we typed the commands correctly [MASK] = true; return false; } else if(receivedData.startsWith(""not_joined"")) { init(); } else if(receivedData.startsWith(""no_free_ch"")) { //retry delay(1000); } else if(receivedData.startsWith(""silent"")) { init(); } else if(receivedData.startsWith(""frame_counter_err_rejoin_needed"")) { init(); } else if(receivedData.startsWith(""busy"")) { busy_count++; if(busy_count>=10) { init(); } else { delay(1000); } } else if(receivedData.startsWith(""mac_paused"")) { init(); } else if(receivedData.startsWith(""invalid_data_len"")) { //should not happen if the prototype worked [MASK] = true; return false; } else { //unknown response after mac tx command init(); } } return false; //should never reach this } void rn2483::sendEncoded(byte bytes[], int length) { // char working; char buffer[3]; for(int i=0; i #include #include #define LED_PIN 13 //Set LED Data Pin for FastLED #define NUM_LEDS 6 //Maximum Number of LEDs for FastLED CRGBArray leds; //Create an array for FastLED with values for all the LEDs in the chain const int ledData = 13; //Set Variable ledData to reference LED data pin MedianFilter senVal(3, 0); //Create a list using median filter. List is 3 values and seed with value '0' CapacitiveSensor capSensor = CapacitiveSensor(4, 2); //Pin4 is send, pin 2 is receive //Pins are bridged with 1Mohm resistor //Pin 2 is connect connected to the end sensor point int senThresh = 1750; //Threshold value for Capacitive Sensor. Lets us control when to change Pass to True //A smaller value will trigger the sensor without touching the sensor //1750-2300 works well for direct touch input //LED Settings //Each program is stored as a part of this pointer array void (*ledShow[])() = { []{static uint8_t hue=0; leds.fill_rainbow(hue++); FastLED.delay(20);}, []{for(int i = 0; i < NUM_LEDS; i++){ leds[i] = CRGB::Purple; FastLED.show();}}, []{for(int i = 0; i < NUM_LEDS; i++){ leds[i] = CRGB::Green; FastLED.show();}}, []{for(int i = 0; i < NUM_LEDS; i++){leds[i] = CRGB::Yellow; FastLED.show();}}, []{for(int i = 0; i < NUM_LEDS; i++){leds[i] = CRGB::White;FastLED.show();}} }; void setup() { pinMode(ledData, OUTPUT); // Set the LED Pin mode FastLED.addLeds(leds, NUM_LEDS); //Set up FastLED Device Type, Output Pin, diode arrangement, FastLED array and Number of LEDs // Serial.begin(9600); //activate for Debuging. Not Necessary for operation } void loop() { static int ledState = 0; //Initialize the LEDState Variable and set it to 0 static int [MASK] = 4; //Set the max number of LED states we can run through //I'm sure there's a way to get the max number of entries in //ledShow[], but I don't know that function so hardcode hacks for now ledShow[ledState](); //Initialize LEDs, start on first program in ledShow[] long sensorValue = capSensor.capacitiveSensor(20); //Get the value of the capacitive sensor for 20 samples senVal.in( sensorValue); //Pass the sensor value into the median filter list sensorValue = senVal.out(); //Return the filtered sensor value. Gives a median of the capSense values // Serial.println(""Sensor Value: ""); //SERIAL MONITOR: check the sensor value // Serial.println(sensorValue); //Check Sensor for someone touching it and then increment the //ledState counter to run through functions inside of the ledShow array while(sensorValue>=senThresh){ sensorValue = 0; //Reset the Sensor to 0 ledState = ledState + 1; //Increment LED program and reset if it goes above the total number if (ledState > [MASK] ){ ledState = 0; } ledShow[ledState](); //display the new LED program // Serial.println(""LED State: ""); //SERIAL MONITOR: check which LED program we're running // Serial.println(ledState); delay(350); //Wait 350 milliseconds before progressing, likely enough time for a user to remove their finger //Added benefit of allowing users to cycle the LED programs by holding their finger on the sensor sensorValue = 0; //No really, reset the sensor value to Zero; senVal.in(0); //tell the MedianFilter we want Zero as the value to restart its counter; break; //Start void loop() over instead of just hanging out inside this while statement } } ",ledMax 66,"#include ""RSA.hpp"" #include #include #include NTL::ZZ inv_mod(NTL::ZZ n1, NTL::ZZ n2){ NTL::ZZ x1 = NTL::ZZ(0), x2 = NTL::ZZ(1), y1 = x1, y2 = x2; NTL::ZZ q, x, y, z, [MASK] = NTL::ZZ(1), sav = n2; if (n2 != 0) { while (n2 > 0) { q = n1 / n2; x = n1; y = x2; z = y2; n1 = n2; n2 = x - q * n2; x2 = x1; x1 = y - q * x1; y2 = y1; y1 = z - q * y1; if (n2 == 1) { [MASK] = x1; if ( [MASK] < 1) [MASK] += sav; } } } return [MASK] ; } void RSAKey::make(const unsigned int& length){ NTL::GenPrime(p, length); do{ NTL::GenPrime(q, length); }while(p == q); n = p * q; NTL::ZZ y_n = (p - 1) * (q - 1); do{ e = NTL::RandomBits_ZZ(length) % y_n + 2; }while(NTL::GCD(e, y_n) != 1); d = inv_mod(e, y_n); /*std::cout << p << ' ' << q << '\n'; std::cout << n << ' ' << y_n <<'\n'; std::cout << d << ' ' << e <<'\n';*/ } void RSAKey::set_public_key(const std::tuple& public_key){ e = std::get<0>(public_key); n = std::get<1>(public_key); } std::tuple RSAKey::get_public_key(){ return {e, n}; } std::tuple RSAKey::get_private_key(){ return {d, p, q}; } NTL::ZZ mod_pow(NTL::ZZ b, NTL::ZZ e, NTL::ZZ m) { NTL::ZZ mod_p = NTL::ZZ(1); while (e > 0) { if ((e & 1) > 0) mod_p = (mod_p * b) % m; e >>= 1; b = (b * b) % m; } return mod_p; } NTL::ZZ mod(NTL::ZZ num, NTL::ZZ mod) { NTL::ZZ num_div_mod = num / mod; NTL::ZZ r = (num < 0) ? (num - (num_div_mod - 1) * mod) : num - num_div_mod * mod; return r; } NTL::ZZ RSA::chineseRemainderTheorem(const NTL::ZZ& m, const NTL::ZZ& d, const NTL::ZZ& p, const NTL::ZZ& q){ NTL::ZZ m1 = mod_pow(m, mod(d, p - 1), p); NTL::ZZ m2 = mod_pow(m, mod(d, q - 1), q); NTL::ZZ h = mod(inv_mod(q, p) * (m1 - m2), p); return mod(m2 + (h * q), p * q); } unsigned char* RSA::rsa(unsigned char in[], unsigned int inLen, unsigned int& outLen, const NTL::ZZ& max_block_length, const NTL::ZZ& k_slot1, const NTL::ZZ& k_slot2, const NTL::ZZ& k_slot3){ NTL::ZZ block = NTL::ZZ(0), temp_block; std::vector out_buf; for(unsigned int i = 0; i < inLen + 1; ++i){ temp_block = block; if(i < inLen){ block <<= 8; block |= in[i]; } if(block >= max_block_length || i == inLen){ NTL::ZZ c; if(k_slot2 == -1) c = mod_pow(temp_block, k_slot1, max_block_length); else c = chineseRemainderTheorem(temp_block, k_slot1, k_slot2, k_slot3); unsigned int n_c_bits = NTL::NumBits(c); unsigned int n_full_bytes = n_c_bits / 8; unsigned int n_remainder_bits = n_c_bits % 8; out_buf.reserve(n_full_bytes + (n_remainder_bits != 0)); out_buf.push_back(NTL::to_int((c >> (n_c_bits - n_remainder_bits)) & 0xff)); for (unsigned int j = n_full_bytes; j > 0; --j) out_buf.push_back(NTL::to_int((c >> ((j - 1) * 8)) & 0xff)); block &= 0xff; } } outLen = out_buf.size(); unsigned char* out = new unsigned char[outLen]; memcpy(out, out_buf.data(), outLen); return out; } unsigned char* RSA::encrypt(unsigned char in[], unsigned int inLen, unsigned int& outLen, const std::tuple& public_key){ NTL::ZZ max_block_length = std::get<1>(public_key); return rsa(in, inLen, outLen, max_block_length, std::get<0>(public_key), NTL::ZZ(-1), NTL::ZZ(-1)); } unsigned char* RSA::decrypt(unsigned char in[], unsigned int inLen, unsigned int& outLen, const std::tuple& private_key){ NTL::ZZ max_block_length = std::get<1>(private_key) * std::get<2>(private_key); return rsa(in, inLen, outLen, max_block_length, std::get<0>(private_key), std::get<1>(private_key), std::get<2>(private_key)); } ",inverse 67,"/* Copyright 2019 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include #include int main(int argc, char* argv[]) { if (argc < 2) { printf(""This program creates a process in a suspended state, prints its PID"" "" so that heap tracing can be enabled, and resumes the thread after a"" "" brief delay. This helps etwheapsnapshot.bat trace a process from"" "" birth. Only the PID is printed to stdout (for easy capture from a"" "" batch file) - the rest is printed to stderr.\n""); printf(""Usage: %s proc_name.exe [delay_ms]\n"", argv[0]); return 0; } const char* name = argv[1]; STARTUPINFOA startup_info = {sizeof(startup_info)}; PROCESS_INFORMATION process_info = {}; LARGE_INTEGER start; QueryPerformanceCounter(&start); BOOL [MASK] = CreateProcessA(name, nullptr, nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, nullptr, &startup_info, &process_info); if (! [MASK] ) { fprintf(stderr, ""CreateProcess failed.\n""); return -1; } // Print the process ID to stdout for consumption by a batch file. printf(""%d\n"", process_info.dwProcessId); // Print the process to stderr so that the output can be seen. fprintf(stderr, ""PID is %d.\n"", process_info.dwProcessId); DWORD delay = 10000; if (argc >= 3) delay = atoi(argv[2]); fprintf(stderr, ""Waiting %1.3f s before letting the process run.\n"", delay / 1e3); Sleep(delay); // Resume the main thread, thus starting the process. ResumeThread(process_info.hThread); fprintf(stderr, ""Process is now running.\n""); // When this process is destroyed all its handles to the new process will be // cleaned up, so no cleanup is necessary. } ",result 68,"#include #include #include #include #include #include #define EXPECT_ZERO(x) EXPECT_EQ((x), 0) TEST(base32, custom) { static const std::string vstrIn[] = { """", ""f"", ""fo"", ""foo"", ""foob"", ""fooba"", ""foobar"", ""abcdefghijklmn""}; static const std::string vstrOut[] = { """", ""my======"", ""mzxq===="", ""mzxw6==="", ""mzxw6yq="", ""mzxw6ytb"", ""mzxw6ytboi======"", ""mfrggzdfmztwq2lknnwg23q=""}; char out_char[256]; size_t [MASK] ; for (unsigned int i = 0; i < sizeof(vstrIn) / sizeof(vstrIn[0]); i++) { memset(out_char, 0, sizeof(out_char)); fingera_to_base32(vstrIn[i].c_str(), vstrIn[i].size(), out_char); EXPECT_EQ(vstrOut[i], out_char); EXPECT_EQ(fingera_to_base32_length(vstrIn[i].size()), vstrOut[i].size()); EXPECT_EQ(fingera_from_base32_length(vstrOut[i].c_str(), vstrOut[i].size()), vstrIn[i].size()); memset(out_char, 0, sizeof(out_char)); EXPECT_EQ( fingera_from_base32(vstrOut[i].c_str(), vstrOut[i].size(), out_char), vstrIn[i].size()); EXPECT_EQ(vstrIn[i], out_char); memset(out_char, 0, sizeof(out_char)); [MASK] = fingera_to_base32_raw(vstrIn[i].c_str(), vstrIn[i].size(), out_char); char values[256]; size_t size_of_values = fingera_from_base32_raw(out_char, [MASK] , values); EXPECT_EQ(size_of_values, vstrIn[i].size()); values[size_of_values] = '\0'; EXPECT_EQ(vstrIn[i], values); } EXPECT_EQ(fingera_from_base32(""mzxw6ytb#mzxw6ytb"", 17, out_char), 5); }",out_size 69,"// Author: <> #ifndef tensor_msg_HPP #define tensor_msg_HPP #include #include #include /** * @brief Represent a tiny class for serializing tensors * @details each tensor consists of information about the type, * the shape and the underlying tensor data */ class tensor_msg { public: // type of message (0=int, 1=float, 2=double) unsigned int type_; // dimensions (length of each axis) std::vector shape_; // raw data msgpack::type::raw_ref data_; tensor_msg(){} tensor_msg(std::vector shape, int* data){ init(shape, (char*) data, sizeof(int), 0); } tensor_msg(std::vector shape, float* data){ init(shape, (char*) data, sizeof(float), 1); } tensor_msg(std::vector shape, double* data){ init(shape, (char*) data, sizeof(double), 2); } void init(std::vector shape, void* data, int size, unsigned int type){ shape_ = shape; type_ = type; int [MASK] = 1; for(auto &i : shape) [MASK] *= i; data_.ptr = (char*) data; data_.size = size * [MASK] ; } // number of entries unsigned int size(){ // templating seems no to be possible as we gonna read the data on-the-fly later if (type_ == 0) return data_.size / sizeof(int); if (type_ == 1) return data_.size / sizeof(float); if (type_ == 2) return data_.size / sizeof(double); } ~tensor_msg(){} MSGPACK_DEFINE(type_, shape_, data_); }; #endif",elements 70,"// // rfnoc-hls-neuralnet: Vivado HLS code for neural-net building blocks // // Copyright (C) 2017 // // 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 GNU General Public License // along with this program. If not, see . // #include #include ""myproject.h"" #include ""parameters.h"" void myproject( input_t input_2[N_INPUT_1_1], input2_t input_1[N_INPUT_1_2*N_INPUT_2_2], result_t layer5_out[N_TIME_STEPS_5*N_OUT_5] ) { //hls-fpga-machine-learning insert IO #pragma HLS ARRAY_RESHAPE variable=input_2 complete dim=0 #pragma HLS ARRAY_RESHAPE variable=input_1 complete dim=0 #pragma HLS ARRAY_PARTITION variable=layer5_out complete dim=0 #pragma HLS INTERFACE ap_vld port=input_2,input_1,layer5_out #pragma HLS PIPELINE #ifndef __SYNTHESIS__ static bool [MASK] = false; if (! [MASK] ) { //hls-fpga-machine-learning insert load weights nnet::load_weights_from_txt(w3, ""w3.txt""); nnet::load_weights_from_txt(b3, ""b3.txt""); nnet::load_weights_from_txt(w5, ""w5.txt""); nnet::load_weights_from_txt(wr5, ""wr5.txt""); nnet::load_weights_from_txt(b5, ""b5.txt""); nnet::load_weights_from_txt(br5, ""br5.txt""); [MASK] = true; } #endif // **************************************** // NETWORK INSTANTIATION // **************************************** //hls-fpga-machine-learning insert layers layer3_t layer3_out[N_LAYER_3]; #pragma HLS ARRAY_PARTITION variable=layer3_out complete dim=0 nnet::dense(input_2, layer3_out, w3, b3); // dense nnet::gru_stack(input_1, initial_state, layer5_out, w5, wr5, b5, br5); // gru } ",loaded_weights 71,"/* * SPDX-License-Identifier: Apache-2.0 */ #include #include #include #include ""onnx/defs/data_propagators.h"" #include ""onnx/defs/tensor/utils.h"" namespace ONNX_NAMESPACE { static const char* Cast_ver9_doc = R""DOC( The operator casts the elements of a given input tensor to a data type specified by the 'to' argument and returns an output tensor of the same size in the converted type. The 'to' argument must be one of the data types specified in the 'DataType' enum field in the TensorProto message. Casting from string tensor in plain (e.g., ""3.14"" and ""1000"") and scientific numeric representations (e.g., ""1e-5"" and ""1E8"") to float types is supported. For example, converting string ""100.5"" to an integer may result 100. There are some string literals reserved for special floating-point values; ""+INF"" (and ""INF""), ""-INF"", and ""NaN"" are positive infinity, negative infinity, and not-a-number, respectively. Any string which can exactly match ""+INF"" in a case-insensitive way would be mapped to positive infinite. Similarly, this case-insensitive rule is applied to ""INF"" and ""NaN"". When casting from numeric tensors to string tensors, plain floating-point representation (such as ""314.15926"") would be used. Converting non-numerical-literal string such as ""Hello World!"" is an undefined behavior. Cases of converting string representing floating-point arithmetic value, such as ""2.718"", to INT is an undefined behavior. Conversion from a numerical type to any numerical type is always allowed. User must be aware of precision loss and value change caused by range difference between two types. For example, a 64-bit float 3.1415926459 may be round to a 32-bit float 3.141592. Similarly, converting an integer 36 to Boolean may produce 1 because we truncate bits which can't be stored in the targeted type. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Cast, 9, OpSchema() .SetDoc(Cast_ver9_doc) .Attr( ""to"", ""The data type to which the elements of the input tensor are cast. "" ""Strictly must be one of the types from DataType enum in TensorProto"", AttributeProto::INT) .Input(0, ""input"", ""Input tensor to be cast."", ""T1"") .Output( 0, ""output"", ""Output tensor with the same shape as input with type "" ""specified by the 'to' argument"", ""T2"") .TypeConstraint( ""T1"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)"", ""tensor(int8)"", ""tensor(int16)"", ""tensor(int32)"", ""tensor(int64)"", ""tensor(uint8)"", ""tensor(uint16)"", ""tensor(uint32)"", ""tensor(uint64)"", ""tensor(bool)"", ""tensor(string)""}, ""Constrain input types. Casting from complex is not supported."") .TypeConstraint( ""T2"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)"", ""tensor(int8)"", ""tensor(int16)"", ""tensor(int32)"", ""tensor(int64)"", ""tensor(uint8)"", ""tensor(uint16)"", ""tensor(uint32)"", ""tensor(uint64)"", ""tensor(bool)"", ""tensor(string)""}, ""Constrain output types. Casting to complex is not supported."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromAttributeToOutput(ctx, ""to"", 0); if (hasNInputShapes(ctx, 1)) { propagateShapeFromInputToOutput(ctx, 0, 0); } })); static const char* Reshape_ver13_doc = R""DOC( Reshape the input tensor similar to numpy.reshape. First input is the data tensor, second input is a shape tensor which specifies the output shape. It outputs the reshaped tensor. At most one dimension of the new shape can be -1. In this case, the value is inferred from the size of the tensor and the remaining dimensions. A dimension could also be 0, in which case the actual dimension value is unchanged (i.e. taken from the input tensor). Shape (second input) could be an empty shape, which means converting to a scalar. The input tensor's shape and the output tensor's shape are required to have the same number of elements.)DOC""; ONNX_OPERATOR_SET_SCHEMA( Reshape, 13, OpSchema() .SetDoc(Reshape_ver13_doc) .Input(0, ""data"", ""An input tensor."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Input( 1, ""shape"", ""Specified shape for output."", ""tensor(int64)"", OpSchema::Single, true, 1, OpSchema::NonDifferentiable) .Output(0, ""reshaped"", ""Reshaped data."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .TypeConstraint( ""T"", OpSchema::all_tensor_types_with_bfloat(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { // Type inference propagateElemTypeFromInputToOutput(ctx, 0, 0); // Shape Inference if 2nd input data (the target shape) is available const TensorProto* targetShapeInitializer = ctx.getInputData(1); if (!targetShapeInitializer) { return; } // Make targetShape (0 -> same as originalShape, -1 -> inferred). // The targetShape vector represents the specified shape for output. std::vector targetShape = ParseData(targetShapeInitializer); // Iterate through targetShape, adding dimensions in the outputShape // TensorProto. If the targertShape dimension is -1, we do not set the // dimension value in this iteration, but we record the Dimension. If // targertShape dimension is 0, we attempt to propagate the dimension // value/param. If the value cannot be inferred, we set the flag in // the unresolveZeros vector. If targetShape dimension is positive, we // set the dimension value in the outputShape. We track the product of // the dimensions we are setting outputShape in the outputProduct // variable. The outputProduct will potentially be used for inferring // a dimension marked -1. auto* outputShape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); TensorShapeProto::Dimension* negativeOneDim = nullptr; const auto& dataInputTensorType = ctx.getInputType(0)->tensor_type(); std::vector unresolvedZeros(targetShape.size(), false); int64_t outputProduct = 1; for (int i = 0; i < static_cast(targetShape.size()); ++i) { // Add a new dimension to outputShape auto* new_dim = outputShape->add_dim(); if (targetShape[i] == -1) { // Check if multiple -1's. If not, set negativeOneDim, marking // this dimension to potentially be filled in later. if (negativeOneDim) { fail_shape_inference(""Target shape may not have multiple -1 dimensions""); } negativeOneDim = new_dim; } else if (targetShape[i] == 0) { // Check if data input has a shape and if the index i is within // its bounds. If these conditions are satisfied, any dimension // value/param should be propogated. If dimension value cannot be // inferred, set the corresponding unresolvedZeros flag to true. unresolvedZeros[i] = true; if (dataInputTensorType.has_shape()) { if (i >= dataInputTensorType.shape().dim_size()) { fail_shape_inference(""Invalid position of 0""); } if (dataInputTensorType.shape().dim(i).has_dim_value()) { const auto& dim_value = dataInputTensorType.shape().dim(i).dim_value(); new_dim->set_dim_value(dim_value); outputProduct *= dim_value; unresolvedZeros[i] = false; } else if (dataInputTensorType.shape().dim(i).has_dim_param()) { const auto& dim_param = dataInputTensorType.shape().dim(i).dim_param(); new_dim->set_dim_param(TString{dim_param}); } } } else if (targetShape[i] > 0) { // Set the dimension value to targetShape[i] new_dim->set_dim_value(targetShape[i]); outputProduct *= targetShape[i]; } else { // Check if value is less than -1; fail if so fail_shape_inference(""Invalid dimension value: "", targetShape[i]); } } // If negativeOneDim has been set, we attempt to infer its value. This // can be done if all dimension values for the data input tensor shape // are known other than the ones corresponding to unresolvedZeros // flags. if (negativeOneDim) { // First, attempt to compute product of data input shape dimensions // that are not marked by unresolvedZeros. If not possible, set the // inputProductValid flag to false. if (!outputProduct) { fail_shape_inference(""Invalid Target shape product of 0""); } int64_t inputProduct = 1; bool inputProductValid = true; if (!dataInputTensorType.has_shape()) { inputProductValid = false; } else { for (int i = 0; i < dataInputTensorType.shape().dim_size(); ++i) { if (dataInputTensorType.shape().dim(i).has_dim_value()) { inputProduct *= dataInputTensorType.shape().dim(i).dim_value(); } else if (i >= static_cast(unresolvedZeros.size()) || !unresolvedZeros[i]) { inputProductValid = false; break; } } } if (inputProductValid) { if (inputProduct % outputProduct != 0) { fail_shape_inference(""Dimension could not be inferred: incompatible shapes""); } negativeOneDim->set_dim_value(inputProduct / outputProduct); } } })); static const char* Reshape_ver5_doc = R""DOC( Reshape the input tensor similar to numpy.reshape. First input is the data tensor, second input is a shape tensor which specifies the output shape. It outputs the reshaped tensor. At most one dimension of the new shape can be -1. In this case, the value is inferred from the size of the tensor and the remaining dimensions. A dimension could also be 0, in which case the actual dimension value is unchanged (i.e. taken from the input tensor). Shape (second input) could be an empty shape, which means converting to a scalar. The input tensor's shape and the output tensor's shape are required to have the same number of elements.)DOC""; ONNX_OPERATOR_SET_SCHEMA( Reshape, 5, OpSchema() .SetDoc(Reshape_ver5_doc) .Input(0, ""data"", ""An input tensor."", ""T"") .Input(1, ""shape"", ""Specified shape for output."", ""tensor(int64)"") .Output(0, ""reshaped"", ""Reshaped data."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { // Type inference propagateElemTypeFromInputToOutput(ctx, 0, 0); // Shape Inference if 2nd input data (the target shape) is available const TensorProto* targetShapeInitializer = ctx.getInputData(1); if (!targetShapeInitializer) { return; } // Make targetShape (0 -> same as originalShape, -1 -> inferred). // The targetShape vector represents the specified shape for output. std::vector targetShape = ParseData(targetShapeInitializer); // Iterate through targetShape, adding dimensions in the outputShape // TensorProto. If the targertShape dimension is -1, we do not set the // dimension value in this iteration, but we record the Dimension. If // targertShape dimension is 0, we attempt to propagate the dimension // value/param. If the value cannot be inferred, we set the flag in // the unresolveZeros vector. If targetShape dimension is positive, we // set the dimension value in the outputShape. We track the product of // the dimensions we are setting outputShape in the outputProduct // variable. The outputProduct will potentially be used for inferring // a dimension marked -1. auto* outputShape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); TensorShapeProto::Dimension* negativeOneDim = nullptr; const auto& dataInputTensorType = ctx.getInputType(0)->tensor_type(); std::vector unresolvedZeros(targetShape.size(), false); int64_t outputProduct = 1; for (int i = 0; i < static_cast(targetShape.size()); ++i) { // Add a new dimension to outputShape auto* new_dim = outputShape->add_dim(); if (targetShape[i] == -1) { // Check if multiple -1's. If not, set negativeOneDim, marking // this dimension to potentially be filled in later. if (negativeOneDim) { fail_shape_inference(""Target shape may not have multiple -1 dimensions""); } negativeOneDim = new_dim; } else if (targetShape[i] == 0) { // Check if data input has a shape and if the index i is within // its bounds. If these conditions are satisfied, any dimension // value/param should be propogated. If dimension value cannot be // inferred, set the corresponding unresolvedZeros flag to true. unresolvedZeros[i] = true; if (dataInputTensorType.has_shape()) { if (i >= dataInputTensorType.shape().dim_size()) { fail_shape_inference(""Invalid position of 0""); } if (dataInputTensorType.shape().dim(i).has_dim_value()) { const auto& dim_value = dataInputTensorType.shape().dim(i).dim_value(); new_dim->set_dim_value(dim_value); outputProduct *= dim_value; unresolvedZeros[i] = false; } else if (dataInputTensorType.shape().dim(i).has_dim_param()) { const auto& dim_param = dataInputTensorType.shape().dim(i).dim_param(); new_dim->set_dim_param(TString{dim_param}); } } } else if (targetShape[i] > 0) { // Set the dimension value to targetShape[i] new_dim->set_dim_value(targetShape[i]); outputProduct *= targetShape[i]; } else { // Check if value is less than -1; fail if so fail_shape_inference(""Invalid dimension value: "", targetShape[i]); } } // If negativeOneDim has been set, we attempt to infer its value. This // can be done if all dimension values for the data input tensor shape // are known other than the ones corresponding to unresolvedZeros // flags. if (negativeOneDim) { // First, attempt to compute product of data input shape dimensions // that are not marked by unresolvedZeros. If not possible, set the // inputProductValid flag to false. if (!outputProduct) { fail_shape_inference(""Invalid Target shape product of 0""); } int64_t inputProduct = 1; bool inputProductValid = true; if (!dataInputTensorType.has_shape()) { inputProductValid = false; } else { for (int i = 0; i < dataInputTensorType.shape().dim_size(); ++i) { if (dataInputTensorType.shape().dim(i).has_dim_value()) { inputProduct *= dataInputTensorType.shape().dim(i).dim_value(); } else if (i >= static_cast(unresolvedZeros.size()) || !unresolvedZeros[i]) { inputProductValid = false; break; } } } if (inputProductValid) { if (inputProduct % outputProduct != 0) { fail_shape_inference(""Dimension could not be inferred: incompatible shapes""); } negativeOneDim->set_dim_value(inputProduct / outputProduct); } } })); static const char* Shape_ver13_doc = R""DOC( Takes a tensor as input and outputs an 1D int64 tensor containing the shape of the input tensor. )DOC""; // Data propagation function for Shape op // Propagates input shape to output shape static void ShapeOp13DataPropagator(DataPropagationContext& ctx) { if (!hasNInputShapes(ctx, 1)) { return; } if (ctx.getInputType(0)->tensor_type().has_shape()) { auto input_shape = ctx.getInputType(0)->tensor_type().shape(); TensorShapeProto tsp; tsp.CopyFrom(input_shape); ctx.addOutputData(0, std::move(tsp)); } } ONNX_OPERATOR_SET_SCHEMA( Shape, 13, OpSchema() .SetDoc(Shape_ver13_doc) .Input(0, ""data"", ""An input tensor."", ""T"", OpSchema::Single, true, 1, OpSchema::NonDifferentiable) .Output(0, ""shape"", ""Shape of the input tensor"", ""T1"", OpSchema::Single, true, 1, OpSchema::NonDifferentiable) .TypeConstraint(""T"", OpSchema::all_tensor_types_with_bfloat(), ""Input tensor can be of arbitrary type."") .TypeConstraint(""T1"", {""tensor(int64)""}, ""Constrain output to int64 tensor."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { ctx.getOutputType(0)->mutable_tensor_type()->set_elem_type(TensorProto::INT64); auto* output_shape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); auto* output_length = output_shape->add_dim(); if (!hasNInputShapes(ctx, 1)) { return; } if (ctx.getInputType(0)->tensor_type().has_shape()) { output_length->set_dim_value(ctx.getInputType(0)->tensor_type().shape().dim_size()); } }) .PartialDataPropagationFunction([](DataPropagationContext& ctx) { ShapeOp13DataPropagator(ctx); })); static const char* Shape_ver1_doc = R""DOC( Takes a tensor as input and outputs an 1D int64 tensor containing the shape of the input tensor. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Shape, 1, OpSchema() .SetDoc(Shape_ver1_doc) .Input(0, ""data"", ""An input tensor."", ""T"") .Output(0, ""shape"", ""Shape of the input tensor"", ""T1"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Input tensor can be of arbitrary type."") .TypeConstraint(""T1"", {""tensor(int64)""}, ""Constrain output to int64 tensor."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { ctx.getOutputType(0)->mutable_tensor_type()->set_elem_type(TensorProto::INT64); auto* output_shape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); auto* output_length = output_shape->add_dim(); if (!hasNInputShapes(ctx, 1)) { return; } if (ctx.getInputType(0)->tensor_type().has_shape()) { output_length->set_dim_value(ctx.getInputType(0)->tensor_type().shape().dim_size()); } }) .PartialDataPropagationFunction([](DataPropagationContext& ctx) { ShapeOp13DataPropagator(ctx); })); static const char* Size_ver1_doc = R""DOC( Takes a tensor as input and outputs a int64 scalar that equals to the total number of elements of the input tensor. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Size, 1, OpSchema() .SetDoc(Size_ver1_doc) .Input(0, ""data"", ""An input tensor."", ""T"") .Output(0, ""size"", ""Total number of elements of the input tensor"", ""T1"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Input tensor can be of arbitrary type."") .TypeConstraint(""T1"", {""tensor(int64)""}, ""Constrain output to int64 tensor, which should be a scalar though."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { ctx.getOutputType(0)->mutable_tensor_type()->set_elem_type(TensorProto::INT64); ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); })); ONNX_OPERATOR_SET_SCHEMA( Concat, 11, OpSchema() .Attr( ""axis"", ""Which axis to concat on. A negative value means counting dimensions from the back. "" ""Accepted range is [-r, r-1] where r = rank(inputs).."", AttributeProto::INT) .SetDoc( ""Concatenate a list of tensors into a single tensor. "" ""All input tensors must have the same shape, except for the dimension size of the axis to concatenate on."") .Input(0, ""inputs"", ""List of tensors for concatenation"", ""T"", OpSchema::Variadic) .Output(0, ""concat_result"", ""Concatenated tensor"", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain output types to any tensor type."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); auto numInputs = ctx.getNumInputs(); if (numInputs < 1 || !hasNInputShapes(ctx, static_cast(numInputs))) { return; } auto rank = ctx.getInputType(0)->tensor_type().shape().dim_size(); auto axisAttr = ctx.getAttribute(""axis""); if (!axisAttr) { fail_shape_inference(""Required attribute axis is missing""); } int axis = static_cast(axisAttr->i()); if (axis < -rank || axis >= rank) { fail_shape_inference(""axis must be in [-rank, rank-1].""); } if (axis < 0) { axis += rank; } if (numInputs == 1) { propagateShapeFromInputToOutput(ctx, 0, 0); return; } bool all_lengths_known = true; int total_length = 0; auto* output_shape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); for (int64_t i = 0; i < rank; ++i) { output_shape->add_dim(); } for (size_t i = 0; i < numInputs; i++) { const auto& shape = ctx.getInputType(i)->tensor_type().shape(); if (shape.dim_size() != rank) { fail_shape_inference( ""All inputs to Concat must have same rank. Input "", i, "" has rank "", shape.dim_size(), "" != "", rank); } for (int j = 0; j < rank; j++) { if (j == axis) { if (shape.dim(j).has_dim_value()) { total_length += static_cast(shape.dim(j).dim_value()); } else { all_lengths_known = false; } } else { auto& output_dim = *output_shape->mutable_dim(j); const auto& input_dim = shape.dim(j); mergeInDimensionInfo(input_dim, output_dim, j); } } } if (all_lengths_known) { output_shape->mutable_dim(axis)->set_dim_value(total_length); } })); static const char* Split_ver11_doc = R""DOC(Split a tensor into a list of tensors, along the specified 'axis'. Lengths of the parts can be specified using argument 'split'. Otherwise, the tensor is split to equal sized parts. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Split, 11, OpSchema() .Input(0, ""input"", ""The tensor to split"", ""T"") .Output(0, ""outputs"", ""One or more outputs forming list of tensors after splitting"", ""T"", OpSchema::Variadic) .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .Attr( ""axis"", ""Which axis to split on. "" ""A negative value means counting dimensions from the back. Accepted range is [-rank, rank-1] "" ""where r = rank(input)."", AttributeProto::INT, static_cast(0)) .Attr(""split"", ""length of each output. Values should be >= 0."", AttributeProto::INTS, OPTIONAL_VALUE) .SetDoc(Split_ver11_doc) .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { for (int i = 0; i < static_cast(ctx.getNumOutputs()); ++i) { propagateElemTypeFromInputToOutput(ctx, 0, i); } if (!hasNInputShapes(ctx, 1)) { return; } const auto& shape = ctx.getInputType(0)->tensor_type().shape(); int rank = shape.dim_size(); int axis = static_cast(getAttribute(ctx, ""axis"", 0)); if (axis < -rank || axis >= rank) { fail_type_inference(""Invalid value of attribute 'axis'. Rank="", rank, "" Value="", axis); } if (axis < 0) { axis += rank; } const auto& split_dim = shape.dim(axis); if (!split_dim.has_dim_value()) { for (size_t i = 0; i < ctx.getNumOutputs(); i++) { *ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape() = shape; ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape()->mutable_dim(axis)->Clear(); } return; } int split_dim_value = static_cast(split_dim.dim_value()); std::vector split; if (getRepeatedAttribute(ctx, ""split"", split)) { if (split.size() != ctx.getNumOutputs()) { fail_shape_inference( ""Mismatch between number of splits ("", split.size(), "") and outputs ("", ctx.getNumOutputs(), "")""); } int64_t total_dim = 0; for (int64_t d : split) { total_dim += d; } if (total_dim != split_dim_value) { fail_shape_inference( ""Mismatch between the sum of 'split' ("", total_dim, "") and the split dimension of the input ("", split_dim_value, "")""); } } else { int num_outputs = static_cast(ctx.getNumOutputs()); if (split_dim_value % num_outputs != 0) { fail_shape_inference(""The input is not evenly splittable""); } int chunk_size = split_dim_value / num_outputs; for (int i = 0; i < static_cast(ctx.getNumOutputs()); i++) { split.push_back(chunk_size); } } for (size_t i = 0; i < ctx.getNumOutputs(); i++) { *ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape() = shape; ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape()->mutable_dim(axis)->set_dim_value(split[i]); } })); static const char* Split_ver13_doc = R""DOC(Split a tensor into a list of tensors, along the specified 'axis'. Lengths of the parts can be specified using input 'split'. Otherwise, the tensor is split to equal sized parts. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Split, 13, OpSchema() .Input(0, ""input"", ""The tensor to split"", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Input( 1, ""split"", ""Optional length of each output. Values should be >= 0."" ""Sum of the values must be equal to the dim value at 'axis' specified."", ""tensor(int64)"", OpSchema::Optional, true, 1, OpSchema::NonDifferentiable) .Output( 0, ""outputs"", ""One or more outputs forming list of tensors after splitting"", ""T"", OpSchema::Variadic, true, 1, OpSchema::Differentiable) .TypeConstraint( ""T"", OpSchema::all_tensor_types_with_bfloat(), ""Constrain input and output types to all tensor types."") .Attr( ""axis"", ""Which axis to split on. "" ""A negative value means counting dimensions from the back. Accepted range is [-rank, rank-1] "" ""where r = rank(input)."", AttributeProto::INT, static_cast(0)) .SetDoc(Split_ver13_doc) .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { for (int i = 0; i < static_cast(ctx.getNumOutputs()); ++i) { propagateElemTypeFromInputToOutput(ctx, 0, i); } if (!hasNInputShapes(ctx, 1)) { return; } const auto& shape = ctx.getInputType(0)->tensor_type().shape(); int rank = shape.dim_size(); int axis = static_cast(getAttribute(ctx, ""axis"", 0)); if (axis < -rank || axis >= rank) { fail_type_inference(""Invalid value of attribute 'axis'. Rank="", rank, "" Value="", axis); } if (axis < 0) { axis += rank; } const auto& split_dim = shape.dim(axis); if (!split_dim.has_dim_value()) { for (size_t i = 0; i < ctx.getNumOutputs(); i++) { *ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape() = shape; ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape()->mutable_dim(axis)->Clear(); } return; } int split_dim_value = static_cast(split_dim.dim_value()); std::vector split; size_t num_inputs = ctx.getNumInputs(); if ((num_inputs == 2) && ctx.getInputType(1)) { //'split' is input auto split_proto = ctx.getInputData(1); if (split_proto == nullptr) { // skip if split is not an initializer return; } split = ParseData(split_proto); if (split.size() != ctx.getNumOutputs()) { fail_shape_inference( ""Mismatch between number of splits ("", split.size(), "") and outputs ("", ctx.getNumOutputs(), "")""); } int64_t total_dim = 0; for (int64_t d : split) { total_dim += d; } if (total_dim != split_dim_value) { fail_shape_inference( ""Mismatch between the sum of 'split' ("", total_dim, "") and the split dimension of the input ("", split_dim_value, "")""); } } else { // no value available for 'split' int num_outputs = static_cast(ctx.getNumOutputs()); if (split_dim_value % num_outputs != 0) { fail_shape_inference(""The input is not evenly splittable""); } int chunk_size = split_dim_value / num_outputs; split.reserve(ctx.getNumOutputs()); for (int i = 0; i < static_cast(ctx.getNumOutputs()); i++) { split.push_back(chunk_size); } } for (size_t i = 0; i < ctx.getNumOutputs(); i++) { *ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape() = shape; ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape()->mutable_dim(axis)->set_dim_value(split[i]); } })); static const char* Slice_ver11_doc = R""DOC( Produces a slice of the input tensor along multiple axes. Similar to numpy: https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html Slices uses `starts`, `ends`, `axes` and `steps` inputs to specify the start and end dimension and step for each axis in the list of axes, it uses this information to slice the input `data` tensor. If a negative value is passed for any of the start or end indices, it represents number of elements before the end of that dimension. If the value passed to start or end is larger than the `n` (the number of elements in this dimension), it represents `n`. For slicing to the end of a dimension with unknown size, it is recommended to pass in `INT_MAX` when slicing forward and 'INT_MIN' when slicing backward. If a negative value is passed for step, it represents slicing backward. However step value cannot be 0. If `axes` are omitted, they are set to `[0, ..., ndim-1]`. If `steps` are omitted, they are set to `[1, ..., 1]` of length `len(starts)` Example 1: data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] axes = [0, 1] starts = [1, 0] ends = [2, 3] steps = [1, 2] result = [ [5, 7], ] Example 2: data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] starts = [0, 1] ends = [-1, 1000] result = [ [2, 3, 4], ] )DOC""; ONNX_OPERATOR_SET_SCHEMA( Slice, 11, OpSchema() .SetDoc(Slice_ver11_doc) .Input(0, ""data"", ""Tensor of data to extract slices from."", ""T"") .Input(1, ""starts"", ""1-D tensor of starting indices of corresponding axis in `axes`"", ""Tind"") .Input(2, ""ends"", ""1-D tensor of ending indices (exclusive) of corresponding axis in `axes`"", ""Tind"") .Input( 3, ""axes"", ""1-D tensor of axes that `starts` and `ends` apply to. Negative value means counting dimensions "" ""from the back. Accepted range is [-r, r-1] where r = rank(data)."", ""Tind"", OpSchema::Optional) .Input( 4, ""steps"", ""1-D tensor of slice step of corresponding axis in `axes`. "" ""Negative value means slicing backward. 'steps' cannot be 0. "" ""Defaults to 1."", ""Tind"", OpSchema::Optional) .Output(0, ""output"", ""Sliced data tensor."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeConstraint(""Tind"", {""tensor(int32)"", ""tensor(int64)""}, ""Constrain indices to integer types"") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { size_t num_inputs = ctx.getNumInputs(); if (num_inputs != 3 && num_inputs != 4 && num_inputs != 5) { fail_type_inference(""Slice op must have either three, four or five inputs.""); } propagateElemTypeFromInputToOutput(ctx, 0, 0); if (!hasNInputShapes(ctx, 1)) { return; } // Shape Inference if // 1. 2nd and 3rd input data (starts, ends) are available. // and 2. 4th and 5th optional input (axes, steps) are either not set, // or set and is initializer. const TensorProto* startsInitializer = ctx.getInputData(1); const TensorProto* endsInitializer = ctx.getInputData(2); const TensorProto* axesInitializer = hasInputShape(ctx, 3) ? ctx.getInputData(3) : nullptr; const TensorProto* stepsInitializer = hasInputShape(ctx, 4) ? ctx.getInputData(4) : nullptr; if (!startsInitializer || !endsInitializer || (hasInputShape(ctx, 3) && !ctx.getInputData(3)) || (hasInputShape(ctx, 4) && !ctx.getInputData(4))) { return; } // don't know data_type- can't proceed if (!startsInitializer->has_data_type()) return; auto get_initializer_data = [](const TensorProto* initializer) -> std::vector { std::vector vec; if (initializer->data_type() == TensorProto::INT64) { const auto& data = ParseData(initializer); vec.insert(vec.end(), data.begin(), data.end()); } else if (initializer->data_type() == TensorProto::INT32) { const auto& data = ParseData(initializer); vec.insert(vec.end(), data.begin(), data.end()); } else { // unaccepted data type fail_shape_inference(""Only supports `int32_t` or `int64_t` inputs for starts/ends/axes/steps""); } return vec; }; auto clamp = [](int64_t val, int64_t low, int64_t high) -> int64_t { if (val < low) return low; if (val > high) return high; return val; }; std::vector starts = get_initializer_data(startsInitializer); std::vector ends = get_initializer_data(endsInitializer); if (starts.size() != ends.size()) { fail_shape_inference(""Incorrect or missing input value for starts and ends""); } const auto& input_shape = ctx.getInputType(0)->tensor_type().shape(); const auto input_rank = input_shape.dim_size(); std::vector axes(starts.size()); if (!axesInitializer) { std::iota(axes.begin(), axes.end(), 0); } else { axes = get_initializer_data(axesInitializer); if (axes.size() != starts.size()) { fail_shape_inference(""Input axes has incorrect length""); } } std::vector steps; if (!stepsInitializer) { steps = std::vector(starts.size(), 1); } else { steps = get_initializer_data(stepsInitializer); if (steps.size() != axes.size()) { fail_shape_inference(""Input steps has incorrect length""); } } for (size_t i = 0; (int64_t)i < input_rank; ++i) { // first update rank of output dim auto* output_dim = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim(); const auto& input_dim = input_shape.dim((int)i); if (input_dim.has_dim_value()) { output_dim->set_dim_value(input_dim.dim_value()); } else if (input_dim.has_dim_param()) { output_dim->set_dim_param(TString{input_dim.dim_param()}); } } std::unordered_set unique_axes; size_t axes_size = axes.size(); for (size_t axis_index = 0; axis_index < axes_size; ++axis_index) { auto axis = axes[axis_index] < 0 ? axes[axis_index] + static_cast(input_rank) : axes[axis_index]; if (axis >= static_cast(input_rank) || axis < 0) { fail_shape_inference(""Input axes has invalid data""); } if (unique_axes.find(axis) != unique_axes.end()) { fail_shape_inference(""'axes' has duplicates""); } unique_axes.insert(axis); auto input_dim = ctx.getInputType(0)->tensor_type().shape().dim((int)axis); // input dim value is missing - cannot perform shape inference for // this axis if (!input_dim.has_dim_value()) { // Clear any previously propagated dim_param and leave this // dimension ""empty"", before moving on to the next dimension ctx.getOutputType(0) ->mutable_tensor_type() ->mutable_shape() ->mutable_dim(static_cast(axis)) ->clear_dim_param(); continue; } const auto input_dim_value = input_dim.dim_value(); // process step auto step = steps[axis_index]; if (step == 0) { fail_shape_inference(""'step' cannot be 0""); } // process start auto start = starts[axis_index]; if (start < 0) start += input_dim_value; if (step < 0) start = clamp(start, 0, input_dim_value - 1); else start = clamp(start, 0, input_dim_value); // process end auto end = ends[axis_index]; if (end < 0) end += input_dim_value; if (step < 0) end = clamp(end, -1, input_dim_value); else end = clamp(end, 0, input_dim_value); // find output dim value for this axis auto temp = static_cast(ceil(1.0 * (end - start) / step)); if (temp < 0) temp = 0; // assign output value ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->mutable_dim((int)axis)->set_dim_value(temp); } })); static const char* Transpose_ver1_doc = R""DOC( Transpose the input tensor similar to numpy.transpose. For example, when perm=(1, 0, 2), given an input tensor of shape (1, 2, 3), the output shape will be (2, 1, 3). )DOC""; ONNX_OPERATOR_SET_SCHEMA( Transpose, 1, OpSchema() .SetDoc(Transpose_ver1_doc) .Attr( ""perm"", ""A list of integers. By default, reverse the dimensions, "" ""otherwise permute the axes according to the values given."", AttributeProto::INTS, OPTIONAL_VALUE) .Input(0, ""data"", ""An input tensor."", ""T"") .Output(0, ""transposed"", ""Transposed output."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (!hasNInputShapes(ctx, 1)) { return; } auto input_type = ctx.getInputType(0); const TensorShapeProto& shape = input_type->tensor_type().shape(); std::vector perm; bool has_perm_attr = getRepeatedAttribute(ctx, ""perm"", perm); if (!has_perm_attr) { for (int i = shape.dim_size() - 1; i >= 0; --i) perm.push_back(i); } else if (!perm.empty()) { // check if every index is valid std::vector seen(shape.dim_size(), false); for (int64_t fromDimIndex : perm) { if (!(0 <= fromDimIndex && fromDimIndex < shape.dim_size())) { std::ostringstream oss; oss << ""Invalid attribute perm {"" << perm[0]; for (size_t i = 1; i != perm.size(); ++i) { oss << "", "" << perm[i]; } oss << ""}, input shape = {""; if (shape.dim_size() > 0) { oss << shape.dim(0).dim_value(); for (int i = 1; i != shape.dim_size(); ++i) { oss << "", "" << shape.dim(i).dim_value(); } oss << ""}""; } fail_type_inference(oss.str()); } else { // check if any perm is repeated if (seen[fromDimIndex]) { fail_type_inference(""Attribute perm for Transpose has repeated value: "", fromDimIndex); } seen[fromDimIndex] = true; } } } propagateElemTypeFromInputToOutput(ctx, 0, 0); for (size_t i = 0; i < perm.size(); ++i) { appendSingleDimCopiedFromInputTypeToOutputType(ctx, 0, 0, static_cast(perm[i])); } })); static const char* ScatterND_ver16_doc = R""DOC( ScatterND takes three inputs `data` tensor of rank r >= 1, `indices` tensor of rank q >= 1, and `updates` tensor of rank q + r - indices.shape[-1] - 1. The output of the operation is produced by creating a copy of the input `data`, and then updating its value to values specified by `updates` at specific index positions specified by `indices`. Its output shape is the same as the shape of `data`. `indices` is an integer tensor. Let k denote indices.shape[-1], the last dimension in the shape of `indices`. `indices` is treated as a (q-1)-dimensional tensor of k-tuples, where each k-tuple is a partial-index into `data`. Hence, k can be a value at most the rank of `data`. When k equals rank(data), each update entry specifies an update to a single element of the tensor. When k is less than rank(data) each update entry specifies an update to a slice of the tensor. Index values are allowed to be negative, as per the usual convention for counting backwards from the end, but are expected in the valid range. `updates` is treated as a (q-1)-dimensional tensor of replacement-slice-values. Thus, the first (q-1) dimensions of updates.shape must match the first (q-1) dimensions of indices.shape. The remaining dimensions of `updates` correspond to the dimensions of the replacement-slice-values. Each replacement-slice-value is a (r-k) dimensional tensor, corresponding to the trailing (r-k) dimensions of `data`. Thus, the shape of `updates` must equal indices.shape[0:q-1] ++ data.shape[k:r-1], where ++ denotes the concatenation of shapes. The `output` is calculated via the following equation: output = np.copy(data) update_indices = indices.shape[:-1] for idx in np.ndindex(update_indices): output[indices[idx]] = updates[idx] The order of iteration in the above loop is not specified. In particular, indices should not have duplicate entries: that is, if idx1 != idx2, then indices[idx1] != indices[idx2]. This ensures that the output value does not depend on the iteration order. `reduction` allows specification of an optional reduction operation, which is applied to all values in `updates` tensor into `output` at the specified `indices`. In cases where `reduction` is set to ""none"", indices should not have duplicate entries: that is, if idx1 != idx2, then indices[idx1] != indices[idx2]. This ensures that the output value does not depend on the iteration order. When `reduction` is set to ""add"", `output` is calculated as follows: output = np.copy(data) update_indices = indices.shape[:-1] for idx in np.ndindex(update_indices): output[indices[idx]] += updates[idx] When `reduction` is set to ""mul"", `output` is calculated as follows: output = np.copy(data) update_indices = indices.shape[:-1] for idx in np.ndindex(update_indices): output[indices[idx]] *= updates[idx] This operator is the inverse of GatherND. Example 1: ``` data = [1, 2, 3, 4, 5, 6, 7, 8] indices = [[4], [3], [1], [7]] updates = [9, 10, 11, 12] output = [1, 11, 3, 10, 9, 6, 7, 12] ``` Example 2: ``` data = [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]] indices = [[0], [2]] updates = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]] output = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]] ``` )DOC""; ONNX_OPERATOR_SET_SCHEMA( ScatterND, 16, OpSchema() .SetDoc(ScatterND_ver16_doc) .Attr( ""reduction"", ""Type of reduction to apply: none (default), add, mul. "" ""'none': no reduction applied. "" ""'add': reduction using the addition operation. "" ""'mul': reduction using the multiplication operation."", AttributeProto::STRING, std::string(""none"")) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Input( 1, ""indices"", ""Tensor of rank q >= 1."", ""tensor(int64)"", OpSchema::Single, true, 1, OpSchema::NonDifferentiable) .Input( 2, ""updates"", ""Tensor of rank q + r - indices_shape[-1] - 1."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Output(0, ""output"", ""Tensor of rank r >= 1."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .TypeConstraint( ""T"", OpSchema::all_tensor_types_with_bfloat(), ""Constrain input and output types to any tensor type."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (hasNInputShapes(ctx, 1)) { propagateShapeFromInputToOutput(ctx, 0, 0); } })); static const char* ScatterND_ver13_doc = R""DOC( ScatterND takes three inputs `data` tensor of rank r >= 1, `indices` tensor of rank q >= 1, and `updates` tensor of rank q + r - indices.shape[-1] - 1. The output of the operation is produced by creating a copy of the input `data`, and then updating its value to values specified by `updates` at specific index positions specified by `indices`. Its output shape is the same as the shape of `data`. Note that `indices` should not have duplicate entries. That is, two or more `updates` for the same index-location is not supported. `indices` is an integer tensor. Let k denote indices.shape[-1], the last dimension in the shape of `indices`. `indices` is treated as a (q-1)-dimensional tensor of k-tuples, where each k-tuple is a partial-index into `data`. Hence, k can be a value at most the rank of `data`. When k equals rank(data), each update entry specifies an update to a single element of the tensor. When k is less than rank(data) each update entry specifies an update to a slice of the tensor. Index values are allowed to be negative, as per the usual convention for counting backwards from the end, but are expected in the valid range. `updates` is treated as a (q-1)-dimensional tensor of replacement-slice-values. Thus, the first (q-1) dimensions of updates.shape must match the first (q-1) dimensions of indices.shape. The remaining dimensions of `updates` correspond to the dimensions of the replacement-slice-values. Each replacement-slice-value is a (r-k) dimensional tensor, corresponding to the trailing (r-k) dimensions of `data`. Thus, the shape of `updates` must equal indices.shape[0:q-1] ++ data.shape[k:r-1], where ++ denotes the concatenation of shapes. The `output` is calculated via the following equation: output = np.copy(data) update_indices = indices.shape[:-1] for idx in np.ndindex(update_indices): output[indices[idx]] = updates[idx] The order of iteration in the above loop is not specified. In particular, indices should not have duplicate entries: that is, if idx1 != idx2, then indices[idx1] != indices[idx2]. This ensures that the output value does not depend on the iteration order. This operator is the inverse of GatherND. Example 1: ``` data = [1, 2, 3, 4, 5, 6, 7, 8] indices = [[4], [3], [1], [7]] updates = [9, 10, 11, 12] output = [1, 11, 3, 10, 9, 6, 7, 12] ``` Example 2: ``` data = [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]] indices = [[0], [2]] updates = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]] output = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]] ``` )DOC""; ONNX_OPERATOR_SET_SCHEMA( ScatterND, 13, OpSchema() .SetDoc(ScatterND_ver13_doc) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Input( 1, ""indices"", ""Tensor of rank q >= 1."", ""tensor(int64)"", OpSchema::Single, true, 1, OpSchema::NonDifferentiable) .Input( 2, ""updates"", ""Tensor of rank q + r - indices_shape[-1] - 1."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Output(0, ""output"", ""Tensor of rank r >= 1."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .TypeConstraint( ""T"", OpSchema::all_tensor_types_with_bfloat(), ""Constrain input and output types to any tensor type."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (hasNInputShapes(ctx, 1)) { propagateShapeFromInputToOutput(ctx, 0, 0); } })); static const char* ScatterND_ver11_doc = R""DOC( ScatterND takes three inputs `data` tensor of rank r >= 1, `indices` tensor of rank q >= 1, and `updates` tensor of rank q + r - indices.shape[-1] - 1. The output of the operation is produced by creating a copy of the input `data`, and then updating its value to values specified by `updates` at specific index positions specified by `indices`. Its output shape is the same as the shape of `data`. Note that `indices` should not have duplicate entries. That is, two or more `updates` for the same index-location is not supported. `indices` is an integer tensor. Let k denote indices.shape[-1], the last dimension in the shape of `indices`. `indices` is treated as a (q-1)-dimensional tensor of k-tuples, where each k-tuple is a partial-index into `data`. Hence, k can be a value at most the rank of `data`. When k equals rank(data), each update entry specifies an update to a single element of the tensor. When k is less than rank(data) each update entry specifies an update to a slice of the tensor. Index values are allowed to be negative, as per the usual convention for counting backwards from the end, but are expected in the valid range. `updates` is treated as a (q-1)-dimensional tensor of replacement-slice-values. Thus, the first (q-1) dimensions of updates.shape must match the first (q-1) dimensions of indices.shape. The remaining dimensions of `updates` correspond to the dimensions of the replacement-slice-values. Each replacement-slice-value is a (r-k) dimensional tensor, corresponding to the trailing (r-k) dimensions of `data`. Thus, the shape of `updates` must equal indices.shape[0:q-1] ++ data.shape[k:r-1], where ++ denotes the concatenation of shapes. The `output` is calculated via the following equation: output = np.copy(data) update_indices = indices.shape[:-1] for idx in np.ndindex(update_indices): output[indices[idx]] = updates[idx] The order of iteration in the above loop is not specified. In particular, indices should not have duplicate entries: that is, if idx1 != idx2, then indices[idx1] != indices[idx2]. This ensures that the output value does not depend on the iteration order. This operator is the inverse of GatherND. Example 1: ``` data = [1, 2, 3, 4, 5, 6, 7, 8] indices = [[4], [3], [1], [7]] updates = [9, 10, 11, 12] output = [1, 11, 3, 10, 9, 6, 7, 12] ``` Example 2: ``` data = [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]] indices = [[0], [2]] updates = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]] output = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]] ``` )DOC""; ONNX_OPERATOR_SET_SCHEMA( ScatterND, 11, OpSchema() .SetDoc(ScatterND_ver11_doc) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"") .Input(1, ""indices"", ""Tensor of rank q >= 1."", ""tensor(int64)"") .Input(2, ""updates"", ""Tensor of rank q + r - indices_shape[-1] - 1."", ""T"") .Output(0, ""output"", ""Tensor of rank r >= 1."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to any tensor type."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (hasNInputShapes(ctx, 1)) { propagateShapeFromInputToOutput(ctx, 0, 0); } })); static const char* ScatterElements_ver16_doc = R""DOC( ScatterElements takes three inputs `data`, `updates`, and `indices` of the same rank r >= 1 and an optional attribute axis that identifies an axis of `data` (by default, the outer-most axis, that is axis 0). The output of the operation is produced by creating a copy of the input `data`, and then updating its value to values specified by `updates` at specific index positions specified by `indices`. Its output shape is the same as the shape of `data`. For each entry in `updates`, the target index in `data` is obtained by combining the corresponding entry in `indices` with the index of the entry itself: the index-value for dimension = axis is obtained from the value of the corresponding entry in `indices` and the index-value for dimension != axis is obtained from the index of the entry itself. `reduction` allows specification of an optional reduction operation, which is applied to all values in `updates` tensor into `output` at the specified `indices`. In cases where `reduction` is set to ""none"", indices should not have duplicate entries: that is, if idx1 != idx2, then indices[idx1] != indices[idx2]. For instance, in a 2-D tensor case, the update corresponding to the [i][j] entry is performed as below: ``` output[indices[i][j]][j] = updates[i][j] if axis = 0, output[i][indices[i][j]] = updates[i][j] if axis = 1, ``` When `reduction` is set to ""add"", the update corresponding to the [i][j] entry is performed as below: ``` output[indices[i][j]][j] += updates[i][j] if axis = 0, output[i][indices[i][j]] += updates[i][j] if axis = 1, ``` When `reduction` is set to ""mul"", the update corresponding to the [i][j] entry is performed as below: ``` output[indices[i][j]][j] *= updates[i][j] if axis = 0, output[i][indices[i][j]] *= updates[i][j] if axis = 1, ``` This operator is the inverse of GatherElements. It is similar to Torch's Scatter operation. Example 1: ``` data = [ [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], ] indices = [ [1, 0, 2], [0, 2, 1], ] updates = [ [1.0, 1.1, 1.2], [2.0, 2.1, 2.2], ] output = [ [2.0, 1.1, 0.0] [1.0, 0.0, 2.2] [0.0, 2.1, 1.2] ] ``` Example 2: ``` data = [[1.0, 2.0, 3.0, 4.0, 5.0]] indices = [[1, 3]] updates = [[1.1, 2.1]] axis = 1 output = [[1.0, 1.1, 3.0, 2.1, 5.0]] ``` )DOC""; ONNX_OPERATOR_SET_SCHEMA( ScatterElements, 16, OpSchema() .SetDoc(ScatterElements_ver16_doc) .Attr( ""axis"", ""Which axis to scatter on. Negative value means "" ""counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data)."", AttributeProto::INT, static_cast(0)) .Attr( ""reduction"", ""Type of reduction to apply: none (default), add, mul. "" ""'none': no reduction applied. "" ""'add': reduction using the addition operation. "" ""'mul': reduction using the multiplication operation."", AttributeProto::STRING, std::string(""none"")) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Input( 1, ""indices"", ""Tensor of int32/int64 indices, of r >= 1 (same rank as input). All index values are expected to be "" ""within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds."", ""Tind"", OpSchema::Single, true, 1, OpSchema::NonDifferentiable) .Input( 2, ""updates"", ""Tensor of rank r >=1 (same rank and shape as indices)"", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Output( 0, ""output"", ""Tensor of rank r >= 1 (same rank as input)."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .TypeConstraint( ""T"", OpSchema::all_tensor_types_with_bfloat(), ""Input and output types can be of any tensor type."") .TypeConstraint(""Tind"", {""tensor(int32)"", ""tensor(int64)""}, ""Constrain indices to integer types"") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (hasNInputShapes(ctx, 1)) { propagateShapeFromInputToOutput(ctx, 0, 0); } })); static const char* ScatterElements_ver13_doc = R""DOC( ScatterElements takes three inputs `data`, `updates`, and `indices` of the same rank r >= 1 and an optional attribute axis that identifies an axis of `data` (by default, the outer-most axis, that is axis 0). The output of the operation is produced by creating a copy of the input `data`, and then updating its value to values specified by `updates` at specific index positions specified by `indices`. Its output shape is the same as the shape of `data`. For each entry in `updates`, the target index in `data` is obtained by combining the corresponding entry in `indices` with the index of the entry itself: the index-value for dimension = axis is obtained from the value of the corresponding entry in `indices` and the index-value for dimension != axis is obtained from the index of the entry itself. For instance, in a 2-D tensor case, the update corresponding to the [i][j] entry is performed as below: ``` output[indices[i][j]][j] = updates[i][j] if axis = 0, output[i][indices[i][j]] = updates[i][j] if axis = 1, ``` This operator is the inverse of GatherElements. It is similar to Torch's Scatter operation. Example 1: ``` data = [ [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], ] indices = [ [1, 0, 2], [0, 2, 1], ] updates = [ [1.0, 1.1, 1.2], [2.0, 2.1, 2.2], ] output = [ [2.0, 1.1, 0.0] [1.0, 0.0, 2.2] [0.0, 2.1, 1.2] ] ``` Example 2: ``` data = [[1.0, 2.0, 3.0, 4.0, 5.0]] indices = [[1, 3]] updates = [[1.1, 2.1]] axis = 1 output = [[1.0, 1.1, 3.0, 2.1, 5.0]] ``` )DOC""; ONNX_OPERATOR_SET_SCHEMA( ScatterElements, 13, OpSchema() .SetDoc(ScatterElements_ver13_doc) .Attr( ""axis"", ""Which axis to scatter on. Negative value means "" ""counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data)."", AttributeProto::INT, static_cast(0)) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Input( 1, ""indices"", ""Tensor of int32/int64 indices, of r >= 1 (same rank as input). All index values are expected to be "" ""within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds."", ""Tind"", OpSchema::Single, true, 1, OpSchema::NonDifferentiable) .Input( 2, ""updates"", ""Tensor of rank r >=1 (same rank and shape as indices)"", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Output( 0, ""output"", ""Tensor of rank r >= 1 (same rank as input)."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .TypeConstraint( ""T"", OpSchema::all_tensor_types_with_bfloat(), ""Input and output types can be of any tensor type."") .TypeConstraint(""Tind"", {""tensor(int32)"", ""tensor(int64)""}, ""Constrain indices to integer types"") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (hasNInputShapes(ctx, 1)) { propagateShapeFromInputToOutput(ctx, 0, 0); } })); static const char* ScatterElements_ver11_doc = R""DOC( ScatterElements takes three inputs `data`, `updates`, and `indices` of the same rank r >= 1 and an optional attribute axis that identifies an axis of `data` (by default, the outer-most axis, that is axis 0). The output of the operation is produced by creating a copy of the input `data`, and then updating its value to values specified by `updates` at specific index positions specified by `indices`. Its output shape is the same as the shape of `data`. For each entry in `updates`, the target index in `data` is obtained by combining the corresponding entry in `indices` with the index of the entry itself: the index-value for dimension = axis is obtained from the value of the corresponding entry in `indices` and the index-value for dimension != axis is obtained from the index of the entry itself. For instance, in a 2-D tensor case, the update corresponding to the [i][j] entry is performed as below: ``` output[indices[i][j]][j] = updates[i][j] if axis = 0, output[i][indices[i][j]] = updates[i][j] if axis = 1, ``` This operator is the inverse of GatherElements. It is similar to Torch's Scatter operation. Example 1: ``` data = [ [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], ] indices = [ [1, 0, 2], [0, 2, 1], ] updates = [ [1.0, 1.1, 1.2], [2.0, 2.1, 2.2], ] output = [ [2.0, 1.1, 0.0] [1.0, 0.0, 2.2] [0.0, 2.1, 1.2] ] ``` Example 2: ``` data = [[1.0, 2.0, 3.0, 4.0, 5.0]] indices = [[1, 3]] updates = [[1.1, 2.1]] axis = 1 output = [[1.0, 1.1, 3.0, 2.1, 5.0]] ``` )DOC""; ONNX_OPERATOR_SET_SCHEMA( ScatterElements, 11, OpSchema() .SetDoc(ScatterElements_ver11_doc) .Attr( ""axis"", ""Which axis to scatter on. Negative value means "" ""counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data)."", AttributeProto::INT, static_cast(0)) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"") .Input( 1, ""indices"", ""Tensor of int32/int64 indices, of r >= 1 (same rank as input). All index values are expected to be "" ""within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds."", ""Tind"") .Input(2, ""updates"", ""Tensor of rank r >=1 (same rank and shape as indices)"", ""T"") .Output(0, ""output"", ""Tensor of rank r >= 1 (same rank as input)."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Input and output types can be of any tensor type."") .TypeConstraint(""Tind"", {""tensor(int32)"", ""tensor(int64)""}, ""Constrain indices to integer types"") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (hasNInputShapes(ctx, 1)) { propagateShapeFromInputToOutput(ctx, 0, 0); } })); static const char* Gather_ver11_doc = R""DOC( Given `data` tensor of rank r >= 1, and `indices` tensor of rank q, gather entries of the axis dimension of `data` (by default outer-most one as axis=0) indexed by `indices`, and concatenates them in an output tensor of rank q + (r - 1). axis = 0 : Let k = indices[i_{0}, ..., i_{q-1}] Then output[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[k , j_{0}, ..., j_{r-2}] ``` data = [ [1.0, 1.2], [2.3, 3.4], [4.5, 5.7], ] indices = [ [0, 1], [1, 2], ] output = [ [ [1.0, 1.2], [2.3, 3.4], ], [ [2.3, 3.4], [4.5, 5.7], ], ] ``` axis = 1 : Let k = indices[i_{0}, ..., i_{q-1}] Then output[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[j_{0}, k, j_{1}, ..., j_{r-2}] ``` data = [ [1.0, 1.2, 1.9], [2.3, 3.4, 3.9], [4.5, 5.7, 5.9], ] indices = [ [0, 2], ] axis = 1, output = [ [ [1.0, 1.9], [2.3, 3.9], [4.5, 5.9], ], ] ``` )DOC""; ONNX_OPERATOR_SET_SCHEMA( Gather, 11, OpSchema() .SetDoc(Gather_ver11_doc) .Attr( ""axis"", ""Which axis to gather on. Negative value means "" ""counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data)."", AttributeProto::INT, static_cast(0)) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"") .Input( 1, ""indices"", ""Tensor of int32/int64 indices, of any rank q. All index values are expected to be within bounds [-s, s-1] "" ""along axis of size s. It is an error if any of the index values are out of bounds."", ""Tind"") .Output(0, ""output"", ""Tensor of rank q + (r - 1)."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to any tensor type."") .TypeConstraint(""Tind"", {""tensor(int32)"", ""tensor(int64)""}, ""Constrain indices to integer types"") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (!hasNInputShapes(ctx, 2)) { return; } const TensorShapeProto& data_shape = ctx.getInputType(0)->tensor_type().shape(); const TensorShapeProto& indices_shape = ctx.getInputType(1)->tensor_type().shape(); int r = data_shape.dim_size(); if (r < 1) { fail_shape_inference(""data tensor must have rank >= 1""); } int q = indices_shape.dim_size(); int axis = static_cast(getAttribute(ctx, ""axis"", 0)); if (axis < -r || axis >= r) { fail_shape_inference(""axis must be in [-r, r-1]""); } if (axis < 0) { axis += r; } int out_rank = q + r - 1; if (out_rank == 0) { ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); } for (int i = 0; i < out_rank; ++i) { *ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim() = (i < axis) ? data_shape.dim(i) : // i < axis < r (i >= axis && i < axis + q) ? indices_shape.dim(i - axis) : // i - axis < q data_shape.dim(i - q + 1); // i < out_rank < q + r - 1 } }) .PartialDataPropagationFunction([](DataPropagationContext& ctx) { GatherOp13DataPropagator(ctx); })); static const char* GatherElements_ver11_doc = R""DOC( GatherElements takes two inputs `data` and `indices` of the same rank r >= 1 and an optional attribute `axis` that identifies an axis of `data` (by default, the outer-most axis, that is axis 0). It is an indexing operation that produces its output by indexing into the input data tensor at index positions determined by elements of the `indices` tensor. Its output shape is the same as the shape of `indices` and consists of one value (gathered from the `data`) for each element in `indices`. For instance, in the 3-D case (r = 3), the output produced is determined by the following equations: ``` out[i][j][k] = input[index[i][j][k]][j][k] if axis = 0, out[i][j][k] = input[i][index[i][j][k]][k] if axis = 1, out[i][j][k] = input[i][j][index[i][j][k]] if axis = 2, ``` This operator is also the inverse of ScatterElements. It is similar to Torch's gather operation. Example 1: ``` data = [ [1, 2], [3, 4], ] indices = [ [0, 0], [1, 0], ] axis = 1 output = [ [ [1, 1], [4, 3], ], ] ``` Example 2: ``` data = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ] indices = [ [1, 2, 0], [2, 0, 0], ] axis = 0 output = [ [ [4, 8, 3], [7, 2, 3], ], ] ``` )DOC""; ONNX_OPERATOR_SET_SCHEMA( GatherElements, 11, OpSchema() .SetDoc(GatherElements_ver11_doc) .Attr( ""axis"", ""Which axis to gather on. Negative value means "" ""counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data)."", AttributeProto::INT, static_cast(0)) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"") .Input( 1, ""indices"", ""Tensor of int32/int64 indices, with the same rank r as the input. All index values are expected to be "" ""within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds."", ""Tind"") .Output(0, ""output"", ""Tensor of the same shape as indices."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to any tensor type."") .TypeConstraint(""Tind"", {""tensor(int32)"", ""tensor(int64)""}, ""Constrain indices to integer types"") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); // propagate indices' shape to output if it exists if (hasInputShape(ctx, 1)) { propagateShapeFromInputToOutput(ctx, 1, 0); } })); static const char* Squeeze_ver11_doc = R""DOC( Remove single-dimensional entries from the shape of a tensor. Takes a parameter `axes` with a list of axes to squeeze. If `axes` is not provided, all the single dimensions will be removed from the shape. If an axis is selected with shape entry not equal to one, an error is raised. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Squeeze, 11, OpSchema() .Attr( ""axes"", ""List of integers indicating the dimensions to squeeze. Negative value means counting dimensions "" ""from the back. Accepted range is [-r, r-1] where r = rank(data)."", AttributeProto::INTS, OPTIONAL_VALUE) .SetDoc(Squeeze_ver11_doc) .Input(0, ""data"", ""Tensors with at least max(dims) dimensions."", ""T"") .Output(0, ""squeezed"", ""Reshaped tensor with same data as input."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (!hasNInputShapes(ctx, 1)) { return; } std::vector axes; if (!getRepeatedAttribute(ctx, ""axes"", axes)) { return; } if (!ctx.getInputType(0)->tensor_type().has_shape()) { return; } ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); const auto& input_shape = ctx.getInputType(0)->tensor_type().shape(); const auto input_ndim = input_shape.dim_size(); std::transform(axes.begin(), axes.end(), axes.begin(), [&](int64_t axis) -> int64_t { return axis < 0 ? axis + input_ndim : axis; }); for (int i = 0, j = 0; i < input_ndim; ++i) { if (std::find(axes.begin(), axes.end(), i) != axes.end()) { if (input_shape.dim(i).has_dim_value() && input_shape.dim(i).dim_value() != 1) { fail_shape_inference( ""Dimension of input "", i, "" must be 1 instead of "", input_shape.dim(i).dim_value()); } ++j; } else { *ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim() = input_shape.dim(i); } } })); static const char* Unsqueeze_ver11_doc = R""DOC( Insert single-dimensional entries to the shape of an input tensor (`data`). Takes one required argument `axes` - which contains a list of dimension indices and this operator will insert a dimension of value `1` into the corresponding index of the output tensor (`expanded`). For example: Given an input tensor (`data`) of shape [3, 4, 5], then Unsqueeze(data, axes=[0, 4]) outputs a tensor (`expanded`) containing same data as `data` but with shape [1, 3, 4, 5, 1]. The attribute `axes` should not contain any duplicate entries. It is an error if it contains duplicates. The rank of the output tensor (`output_rank`) is the rank of the input tensor (`data`) plus the number of values in `axes`. Each value in `axes` should be within the (inclusive) range [-output_rank , output_rank - 1]. The order of values in `axes` does not matter and can come in any order. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Unsqueeze, 11, OpSchema() .Attr( ""axes"", ""List of integers indicating the dimensions to be inserted. Negative value means counting dimensions "" ""from the back. Accepted range is [-r, r-1] where r = rank(expanded)."", AttributeProto::INTS) .SetDoc(Unsqueeze_ver11_doc) .Input(0, ""data"", ""Original tensor"", ""T"") .Output(0, ""expanded"", ""Reshaped tensor with same data as input."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (!hasNInputShapes(ctx, 1)) { return; } std::vector axes; if (!getRepeatedAttribute(ctx, ""axes"", axes)) { return; } // validate 'axes' for duplicate entries std::unordered_set unique_values; for (const auto val : axes) { if (unique_values.find(val) != unique_values.end()) { fail_shape_inference(""'axes' attribute must not contain any duplicates""); } unique_values.insert(val); } if (!ctx.getInputType(0)->tensor_type().has_shape()) { return; } ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); const auto& input_shape = ctx.getInputType(0)->tensor_type().shape(); const auto input_ndim = input_shape.dim_size(); const auto output_ndim = input_ndim + static_cast(axes.size()); for (auto& axe : axes) { if (axe < -output_ndim || axe >= output_ndim) { fail_shape_inference(""values in 'axes' are beyond the bounds of the computed output shape""); } if (axe < 0) { axe += output_ndim; } } // sort after correcting negative axes values (if any) in the previous // step std::sort(axes.begin(), axes.end()); int j = 0; for (int i = 0; i < input_ndim; ++i) { while (static_cast(j) < axes.size() && axes[j] == ctx.getOutputType(0)->tensor_type().shape().dim_size()) { ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(1); ++j; } *ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim() = ctx.getInputType(0)->tensor_type().shape().dim(i); } while (static_cast(j) < axes.size() && axes[j] == ctx.getOutputType(0)->tensor_type().shape().dim_size()) { ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(1); ++j; } })); static const char* SpaceToDepth_ver1_doc = R""DOC(SpaceToDepth rearranges blocks of spatial data into depth. More specifically, this op outputs a copy of the input tensor where values from the height and width dimensions are moved to the depth dimension. )DOC""; ONNX_OPERATOR_SET_SCHEMA( SpaceToDepth, 1, OpSchema() .Attr(""blocksize"", ""Blocks of [blocksize, blocksize] are moved."", AttributeProto::INT) .SetDoc(SpaceToDepth_ver1_doc) .Input( 0, ""input"", ""Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth"" "", H is the height and W is the width."", ""T"") .Output(0, ""output"", ""Output tensor of [N, C * blocksize * blocksize, H/blocksize, W/blocksize]."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); auto blocksize = getAttribute(ctx, ""blocksize"", 0); if (blocksize <= 0) { fail_shape_inference(""Blocksize must be positive""); } if (hasInputShape(ctx, 0)) { auto& input_shape = getInputShape(ctx, 0); if (input_shape.dim_size() == 4) { // TODO: Clarify what behavior should be if H or W is not a // multiple of blocksize. updateOutputShape( ctx, 0, {input_shape.dim(0), input_shape.dim(1) * (blocksize * blocksize), input_shape.dim(2) / blocksize, input_shape.dim(3) / blocksize}); } else { fail_shape_inference(""Input tensor must be 4-dimensional""); } } })); static const char* DepthToSpace_ver11_doc = R""DOC(DepthToSpace rearranges (permutes) data from depth into blocks of spatial data. This is the reverse transformation of SpaceToDepth. More specifically, this op outputs a copy of the input tensor where values from the depth dimension are moved in spatial blocks to the height and width dimensions. By default, `mode` = `DCR`. In the DCR mode, elements along the depth dimension from the input tensor are rearranged in the following order: depth, column, and then row. The output y is computed from the input x as below: b, c, h, w = x.shape tmp = np.reshape(x, [b, blocksize, blocksize, c // (blocksize**2), h, w]) tmp = np.transpose(tmp, [0, 3, 4, 1, 5, 2]) y = np.reshape(tmp, [b, c // (blocksize**2), h * blocksize, w * blocksize]) In the CRD mode, elements along the depth dimension from the input tensor are rearranged in the following order: column, row, and the depth. The output y is computed from the input x as below: b, c, h, w = x.shape tmp = np.reshape(x, [b, c // (blocksize ** 2), blocksize, blocksize, h, w]) tmp = np.transpose(tmp, [0, 1, 4, 2, 5, 3]) y = np.reshape(tmp, [b, c // (blocksize ** 2), h * blocksize, w * blocksize]) )DOC""; ONNX_OPERATOR_SET_SCHEMA( DepthToSpace, 11, OpSchema() .Attr(""blocksize"", ""Blocks of [blocksize, blocksize] are moved."", AttributeProto::INT) .Attr( ""mode"", ""DCR (default) for depth-column-row order re-arrangement. Use CRD for column-row-depth order."", AttributeProto::STRING, std::string(""DCR"")) .SetDoc(DepthToSpace_ver11_doc) .Input( 0, ""input"", ""Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth"" "", H is the height and W is the width."", ""T"") .Output(0, ""output"", ""Output tensor of [N, C/(blocksize * blocksize), H * blocksize, W * blocksize]."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); auto blocksize = getAttribute(ctx, ""blocksize"", 0); if (blocksize <= 0) { fail_shape_inference(""Blocksize must be positive""); } if (hasInputShape(ctx, 0)) { auto& input_shape = getInputShape(ctx, 0); if (input_shape.dim_size() == 4) { // TODO: Clarify what behavior should be if C is not a multiple of // blocksize*blocksize. updateOutputShape( ctx, 0, {input_shape.dim(0), input_shape.dim(1) / (blocksize * blocksize), input_shape.dim(2) * blocksize, input_shape.dim(3) * blocksize}); } else { fail_shape_inference(""Input tensor must be 4-dimensional""); } } })); static const char* Tile_ver6_doc = R""DOC(Constructs a tensor by tiling a given tensor. This is the same as function `tile` in Numpy, but no broadcast. For example A = [[1, 2], [3, 4]], B = [1, 2], tile(A, B) = [[1, 2, 1, 2], [3, 4, 3, 4]] )DOC""; ONNX_OPERATOR_SET_SCHEMA( Tile, 6, OpSchema() .SetDoc(Tile_ver6_doc) .Input(0, ""input"", ""Input tensor of any shape."", ""T"") .Input( 1, ""repeats"", ""1D int64 tensor of the same length as input's dimension number, "" ""includes numbers of repeated copies along input's dimensions."", ""T1"") .Output( 0, ""output"", ""Output tensor of the same dimensions and type as tensor input. "" ""output_dim[i] = input_dim[i] * repeats[i]"", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeConstraint(""T1"", {""tensor(int64)""}, ""Constrain repeat's type to int64 tensors."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { // Type inference propagateElemTypeFromInputToOutput(ctx, 0, 0); // Shape inference // Needs at least the first input to proceed if (!hasNInputShapes(ctx, 1)) { return; } const auto& input_shape = ctx.getInputType(0)->tensor_type().shape(); const auto input_rank = input_shape.dim_size(); const auto* repeats_inputs = ctx.getInputData(1); auto* output_shape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); if (nullptr != repeats_inputs && hasNInputShapes(ctx, 2)) { // shape inference is possible only when 'repeats' is an initializer const auto& repeats_shape = ctx.getInputType(1)->tensor_type().shape(); if (repeats_shape.dim_size() != 1 || repeats_inputs->data_type() != TensorProto::INT64) { fail_shape_inference(""'Repeats' input must be 1D tensor of type int64""); } const auto& repeats_data = ParseData(repeats_inputs); if (repeats_data.size() != static_cast(input_rank)) { fail_shape_inference( ""'Repeats' input has incorrect number of values. "" ""The number of values in 'repeats' must be equal "" ""to the number of input dimensions.""); } for (size_t i = 0; (int64_t)i < input_rank; ++i) { const auto& input_dim = input_shape.dim((int)i); auto* output_dim = output_shape->add_dim(); if (input_dim.has_dim_value()) { output_dim->set_dim_value(input_dim.dim_value() * repeats_data[i]); } } } else { // Infer output shape's rank in any case (if repeats data is not // available) auto* output_shape_0 = getOutputShape(ctx, 0); for (size_t i = 0; (int64_t)i < input_rank; ++i) { output_shape_0->add_dim(); } } return; })); static const char* Resize_ver13_doc = R""DOC( Resize the input tensor. In general, it calculates every value in the output tensor as a weighted average of neighborhood (a.k.a. sampling locations) in the input tensor. Each dimension value of the output tensor is: output_dimension = floor(input_dimension * (roi_end - roi_start) * scale) if input \""sizes\"" is not specified. )DOC""; static const char* Resize_ver13_attr_coordinate_transformation_mode_doc = R""DOC( This attribute describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor.
The coordinate of each dimension is transformed individually. Let's describe a case using axis x as an example. Denote x_resized as the coordinate of axis x in the resized tensor, x_original as the coordinate of axis x in the original tensor, length_original as the length of the original tensor in axis x, length_resized as the length of the resized tensor in axis x, roi_x = (start_x, end_x) of the axis x in input ""roi"", scale = length_resized / length_original,
if coordinate_transformation_mode is ""half_pixel"",
x_original = (x_resized + 0.5) / scale - 0.5,
if coordinate_transformation_mode is ""pytorch_half_pixel"",
x_original = length_resized > 1 ? (x_resized + 0.5) / scale - 0.5 : 0,
if coordinate_transformation_mode is ""align_corners"",
x_original = x_resized * (length_original - 1) / (length_resized - 1),
if coordinate_transformation_mode is ""asymmetric"",
x_original = x_resized / scale,
if coordinate_transformation_mode is ""tf_crop_and_resize"",
x_original = length_resized > 1 ? start_x * (length_original - 1) + x_resized * (end_x - start_x) * (length_original - 1) / (length_resized - 1) : 0.5 * (start_x + end_x) * (length_original - 1).)DOC""; ONNX_OPERATOR_SET_SCHEMA( Resize, 13, OpSchema() .Attr( ""mode"", ""Three interpolation modes: nearest (default), linear and cubic. "" ""The \""linear\"" mode includes linear interpolation for 1D tensor and N-linear interpolation for N-D tensor (for example, bilinear interpolation for 2D tensor). "" ""The \""cubic\"" mode includes cubic interpolation for 1D tensor and N-cubic interpolation for N-D tensor (for example, bicubic interpolation for 2D tensor)."", AttributeProto::STRING, std::string(""nearest"")) .Attr( ""cubic_coeff_a"", ""The coefficient 'a' used in cubic interpolation. Two common choice are -0.5 (in some cases of TensorFlow) and -0.75"" "" (in PyTorch). Check out Equation (4) in https://ieeexplore.ieee.org/document/1163711 for the details. "" ""This attribute is valid only if \""mode\"" is \""cubic\""."", AttributeProto::FLOAT, static_cast(-0.75)) .Attr( ""exclude_outside"", ""If set to 1, the weight of sampling locations outside the tensor will be set to 0"" "" and the weight will be renormalized so that their sum is 1.0. The default value is 0."", AttributeProto::INT, static_cast(0)) .Attr( ""coordinate_transformation_mode"", Resize_ver13_attr_coordinate_transformation_mode_doc, AttributeProto::STRING, std::string(""half_pixel"")) .Attr( ""nearest_mode"", ""Four modes: round_prefer_floor (default, as known as round half down), round_prefer_ceil (as known as round half up), floor, ceil. Only used by nearest interpolation. It indicates how to get \""nearest\"" pixel in input tensor from x_original, so this attribute is valid only if \""mode\"" is \""nearest\""."", AttributeProto::STRING, std::string(""round_prefer_floor"")) .Attr( ""extrapolation_value"", ""When coordinate_transformation_mode is \""tf_crop_and_resize\"" and x_original is outside the range [0, length_original - 1], this value is used as the corresponding output value. Default is 0.0f."", AttributeProto::FLOAT, static_cast(0)) .Input(0, ""X"", ""N-D tensor"", ""T1"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Input( 1, ""roi"", ""1-D tensor given as [start1, ..., startN, end1, ..., endN], where N is the rank of X. The RoIs' coordinates are normalized in the coordinate system of the input image. It only takes effect when coordinate_transformation_mode is \""tf_crop_and_resize\"""", ""T2"", OpSchema::Optional, true, 1, OpSchema::NonDifferentiable) .Input( 2, ""scales"", ""The scale array along each dimension. It takes value greater than 0. If it's less than 1,"" "" it's sampling down, otherwise, it's upsampling. The number of elements of 'scales' should"" "" be the same as the rank of input 'X'. One of 'scales' and 'sizes' MUST be specified and it is an error if both are specified. If 'sizes' is needed, the user can use an empty string as the name of 'scales' in this operator's input list."", ""tensor(float)"", OpSchema::Optional, true, 1, OpSchema::NonDifferentiable) .Input( 3, ""sizes"", ""The size of the output tensor. The number of elements of 'sizes' should be the same as the"" "" rank of input 'X'. Only one of 'scales' and 'sizes' can be specified."", ""tensor(int64)"", OpSchema::Optional, true, 1, OpSchema::NonDifferentiable) .Output(0, ""Y"", ""N-D tensor after resizing"", ""T1"", OpSchema::Single, true, 1, OpSchema::Differentiable) .TypeConstraint( ""T1"", OpSchema::all_tensor_types_with_bfloat(), ""Constrain input 'X' and output 'Y' to all tensor types."") .TypeConstraint( ""T2"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)""}, ""Constrain roi type to float or double."") .SetDoc(Resize_ver13_doc) .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { resizeShapeInference_opset13_to_18(ctx); })); static const char* Resize_ver11_doc = R""DOC( Resize the input tensor. In general, it calculates every value in the output tensor as a weighted average of neighborhood (a.k.a. sampling locations) in the input tensor. Each dimension value of the output tensor is: output_dimension = floor(input_dimension * (roi_end - roi_start) * scale) if input \""sizes\"" is not specified. )DOC""; static const char* Resize_attr_coordinate_transformation_mode_doc = R""DOC( This attribute describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor.
The coordinate of each dimension is transformed individually. Let's describe a case using axis x as an example. Denote x_resized as the coordinate of axis x in the resized tensor, x_original as the coordinate of axis x in the original tensor, length_original as the length of the original tensor in axis x, length_resized as the length of the resized tensor in axis x, roi_x = (start_x, end_x) of the axis x in input ""roi"", scale = length_resized / length_original,
if coordinate_transformation_mode is ""half_pixel"",
x_original = (x_resized + 0.5) / scale - 0.5,
if coordinate_transformation_mode is ""pytorch_half_pixel"",
x_original = length_resized > 1 ? (x_resized + 0.5) / scale - 0.5 : 0,
if coordinate_transformation_mode is ""align_corners"",
x_original = x_resized * (length_original - 1) / (length_resized - 1),
if coordinate_transformation_mode is ""asymmetric"",
x_original = x_resized / scale,
if coordinate_transformation_mode is ""tf_half_pixel_for_nn"",
x_original = (x_resized + 0.5) / scale,
if coordinate_transformation_mode is ""tf_crop_and_resize"",
x_original = length_resized > 1 ? start_x * (length_original - 1) + x_resized * (end_x - start_x) * (length_original - 1) / (length_resized - 1) : 0.5 * (start_x + end_x) * (length_original - 1).)DOC""; ONNX_OPERATOR_SET_SCHEMA( Resize, 11, OpSchema() .Attr( ""mode"", ""Three interpolation modes: nearest (default), linear and cubic. "" ""The \""linear\"" mode includes linear interpolation for 1D tensor and N-linear interpolation for N-D tensor (for example, bilinear interpolation for 2D tensor). "" ""The \""cubic\"" mode includes cubic interpolation for 1D tensor and N-cubic interpolation for N-D tensor (for example, bicubic interpolation for 2D tensor)."", AttributeProto::STRING, std::string(""nearest"")) .Attr( ""cubic_coeff_a"", ""The coefficient 'a' used in cubic interpolation. Two common choice are -0.5 (in some cases of TensorFlow) and -0.75"" "" (in PyTorch). Check out Equation (4) in https://ieeexplore.ieee.org/document/1163711 for the details. "" ""This attribute is valid only if \""mode\"" is \""cubic\""."", AttributeProto::FLOAT, static_cast(-0.75)) .Attr( ""exclude_outside"", ""If set to 1, the weight of sampling locations outside the tensor will be set to 0"" "" and the weight will be renormalized so that their sum is 1.0. The default value is 0."", AttributeProto::INT, static_cast(0)) .Attr( ""coordinate_transformation_mode"", Resize_attr_coordinate_transformation_mode_doc, AttributeProto::STRING, std::string(""half_pixel"")) .Attr( ""nearest_mode"", ""Four modes: round_prefer_floor (default, as known as round half down), round_prefer_ceil (as known as round half up), floor, ceil. Only used by nearest interpolation. It indicates how to get \""nearest\"" pixel in input tensor from x_original, so this attribute is valid only if \""mode\"" is \""nearest\""."", AttributeProto::STRING, std::string(""round_prefer_floor"")) .Attr( ""extrapolation_value"", ""When coordinate_transformation_mode is \""tf_crop_and_resize\"" and x_original is outside the range [0, length_original - 1], this value is used as the corresponding output value. Default is 0.0f."", AttributeProto::FLOAT, static_cast(0)) .Input(0, ""X"", ""N-D tensor"", ""T1"") .Input( 1, ""roi"", ""1-D tensor given as [start1, ..., startN, end1, ..., endN], where N is the rank of X. The RoIs' coordinates are normalized in the coordinate system of the input image. It only takes effect when coordinate_transformation_mode is \""tf_crop_and_resize\"""", ""T2"") .Input( 2, ""scales"", ""The scale array along each dimension. It takes value greater than 0. If it's less than 1,"" "" it's sampling down, otherwise, it's upsampling. The number of elements of 'scales' should"" "" be the same as the rank of input 'X'. If 'size' is needed, the user must set 'scales' to an empty tensor."", ""tensor(float)"") .Input( 3, ""sizes"", ""The size of the output tensor. The number of elements of 'sizes' should be the same as the"" "" rank of input 'X'. May only be set if 'scales' is set to an empty tensor."", ""tensor(int64)"", OpSchema::Optional) .Output(0, ""Y"", ""N-D tensor after resizing"", ""T1"") .TypeConstraint(""T1"", OpSchema::all_tensor_types(), ""Constrain input 'X' and output 'Y' to all tensor types."") .TypeConstraint( ""T2"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)""}, ""Constrain roi type to float or double."") .SetDoc(Resize_ver11_doc) .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { resizeShapeInference_opset11_to_12(ctx); })); ONNX_OPERATOR_SET_SCHEMA( Identity, 13, OpSchema() .SetDoc(""Identity operator"") .Input(0, ""input"", ""Input tensor"", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Output(0, ""output"", ""Tensor to copy input into."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .TypeConstraint( ""T"", OpSchema::all_tensor_types_with_bfloat(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction(propagateShapeAndTypeFromFirstInput)); ONNX_OPERATOR_SET_SCHEMA( Identity, 1, OpSchema() .SetDoc(""Identity operator"") .Input(0, ""input"", ""Input tensor"", ""T"") .Output(0, ""output"", ""Tensor to copy input into."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction(propagateShapeAndTypeFromFirstInput)); ONNX_OPERATOR_SET_SCHEMA( IsNaN, 9, OpSchema() .SetDoc(R""DOC(Returns which elements of the input are NaN.)DOC"") .Input(0, ""X"", ""input"", ""T1"") .Output(0, ""Y"", ""output"", ""T2"") .TypeConstraint( ""T1"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)""}, ""Constrain input types to float tensors."") .TypeConstraint(""T2"", {""tensor(bool)""}, ""Constrain output types to boolean tensors."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { updateOutputElemType(ctx, 0, TensorProto::BOOL); if (hasInputShape(ctx, 0)) { propagateShapeFromInputToOutput(ctx, 0, 0); } })); const char* NonZero_ver9_doc = R""DOC( Returns the indices of the elements that are non-zero (in row-major order - by dimension). NonZero behaves similar to numpy.nonzero: https://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html, but for scalar input, NonZero produces output shape (0, N) instead of (1, N), which is different from Numpy's behavior. )DOC""; ONNX_OPERATOR_SET_SCHEMA( NonZero, 9, OpSchema() .SetDoc(NonZero_ver9_doc) .Input(0, ""X"", ""input"", ""T"") .Output(0, ""Y"", ""output"", ""tensor(int64)"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { updateOutputElemType(ctx, 0, TensorProto::INT64); TensorShapeProto output_shape; auto* dim = output_shape.add_dim(); if (hasInputShape(ctx, 0)) { const TensorShapeProto& input_shape = getInputShape(ctx, 0); dim->set_dim_value(input_shape.dim_size()); } output_shape.add_dim(); updateOutputShape(ctx, 0, output_shape); })); static const char* GatherND_ver12_doc = R""DOC( Given `data` tensor of rank `r` >= 1, `indices` tensor of rank `q` >= 1, and `batch_dims` integer `b`, this operator gathers slices of `data` into an output tensor of rank `q + r - indices_shape[-1] - 1 - b`. `indices` is an q-dimensional integer tensor, best thought of as a `(q-1)`-dimensional tensor of index-tuples into `data`, where each element defines a slice of `data` `batch_dims` (denoted as `b`) is an integer indicating the number of batch dimensions, i.e the leading `b` number of dimensions of `data` tensor and `indices` are representing the batches, and the gather starts from the `b+1` dimension. Some salient points about the inputs' rank and shape: 1) r >= 1 and q >= 1 are to be honored. There is no dependency condition to be met between ranks `r` and `q` 2) The first `b` dimensions of the shape of `indices` tensor and `data` tensor must be equal. 3) b < min(q, r) is to be honored. 4) The `indices_shape[-1]` should have a value between 1 (inclusive) and rank `r-b` (inclusive) 5) All values in `indices` are expected to be within bounds [-s, s-1] along axis of size `s` (i.e.) `-data_shape[i] <= indices[...,i] <= data_shape[i] - 1`. It is an error if any of the index values are out of bounds. The output is computed as follows: The output tensor is obtained by mapping each index-tuple in the `indices` tensor to the corresponding slice of the input `data`. 1) If `indices_shape[-1] > r-b` => error condition 2) If `indices_shape[-1] == r-b`, since the rank of `indices` is `q`, `indices` can be thought of as `N` `(q-b-1)`-dimensional tensors containing 1-D tensors of dimension `r-b`, where `N` is an integer equals to the product of 1 and all the elements in the batch dimensions of the indices_shape. Let us think of each such `r-b` ranked tensor as `indices_slice`. Each *scalar value* corresponding to `data[0:b-1,indices_slice]` is filled into the corresponding location of the `(q-b-1)`-dimensional tensor to form the `output` tensor (Example 1 below) 3) If `indices_shape[-1] < r-b`, since the rank of `indices` is `q`, `indices` can be thought of as `N` `(q-b-1)`-dimensional tensor containing 1-D tensors of dimension `< r-b`. Let us think of each such tensors as `indices_slice`. Each *tensor slice* corresponding to `data[0:b-1, indices_slice , :]` is filled into the corresponding location of the `(q-b-1)`-dimensional tensor to form the `output` tensor (Examples 2, 3, 4 and 5 below) This operator is the inverse of `ScatterND`. `Example 1` batch_dims = 0 data = [[0,1],[2,3]] # data_shape = [2, 2] indices = [[0,0],[1,1]] # indices_shape = [2, 2] output = [0,3] # output_shape = [2] `Example 2` batch_dims = 0 data = [[0,1],[2,3]] # data_shape = [2, 2] indices = [[1],[0]] # indices_shape = [2, 1] output = [[2,3],[0,1]] # output_shape = [2, 2] `Example 3` batch_dims = 0 data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2] indices = [[0,1],[1,0]] # indices_shape = [2, 2] output = [[2,3],[4,5]] # output_shape = [2, 2] `Example 4` batch_dims = 0 data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2] indices = [[[0,1]],[[1,0]]] # indices_shape = [2, 1, 2] output = [[[2,3]],[[4,5]]] # output_shape = [2, 1, 2] `Example 5` batch_dims = 1 data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2] indices = [[1],[0]] # indices_shape = [2, 1] output = [[2,3],[4,5]] # output_shape = [2, 2] )DOC""; ONNX_OPERATOR_SET_SCHEMA( GatherND, 12, OpSchema() .SetDoc(GatherND_ver12_doc) .Attr( ""batch_dims"", ""The number of batch dimensions. The gather of indexing starts from dimension of data[batch_dims:]"", AttributeProto::INT, static_cast(0)) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"") .Input( 1, ""indices"", ""Tensor of rank q >= 1. All index values are expected to be within bounds [-s, s-1] "" ""along axis of size s. It is an error if any of the index values are out of bounds."", ""tensor(int64)"") .Output(0, ""output"", ""Tensor of rank q + r - indices_shape[-1] - 1."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to any tensor type."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { // Type inference propagateElemTypeFromInputToOutput(ctx, 0, 0); // Shape inference if (!hasNInputShapes(ctx, 2)) { // cannot proceed with shape or rank inference return; } const auto& data_shape = ctx.getInputType(0)->tensor_type().shape(); const auto data_rank = data_shape.dim_size(); const auto& indices_shape = ctx.getInputType(1)->tensor_type().shape(); const auto indices_rank = indices_shape.dim_size(); int64_t batch_dims_data = getAttribute(ctx, ""batch_dims"", 0); if (data_rank < 1 || indices_rank < 1) { fail_shape_inference( ""Both `data` and `indices` input tensors in GatherND op "" ""need to have rank larger than 0.""); } // cannot ascertain if the input shapes are valid if shape of // `indices` is missing last dimension value so return at this point if (!indices_shape.dim(indices_rank - 1).has_dim_value()) { return; } const auto last_index_dimension = indices_shape.dim(indices_rank - 1).dim_value() + batch_dims_data; if (last_index_dimension > data_rank) { fail_shape_inference( ""Last dimension of `indices` input tensor in GatherND op "" ""must not be larger than the rank of `data` tensor""); } for (int i = 0; i < indices_rank - 1; ++i) { *ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim() = indices_shape.dim(i); } for (int i = static_cast(last_index_dimension); i < data_rank; ++i) { *ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim() = data_shape.dim(i); } })); static const char* Pad_ver11_doc = R""DOC( Given a tensor containing the data to be padded (`data`), a tensor containing the number of start and end pad values for axis (`pads`), (optionally) a `mode`, and (optionally) `constant_value`, a padded tensor (`output`) is generated. The three supported `modes` are (similar to corresponding modes supported by `numpy.pad`): 1) `constant`(default) - pads with a given constant value as specified by `constant_value` (which defaults to 0) 2) `reflect` - pads with the reflection of the vector mirrored on the first and last values of the vector along each axis 3) `edge` - pads with the edge values of array Example 1 (`constant` mode): Insert 0 pads to the beginning of the second dimension. data = [ [1.0, 1.2], [2.3, 3.4], [4.5, 5.7], ] pads = [0, 2, 0, 0] mode = 'constant' constant_value = 0.0 output = [ [0.0, 0.0, 1.0, 1.2], [0.0, 0.0, 2.3, 3.4], [0.0, 0.0, 4.5, 5.7], ] Example 2 (`reflect` mode): data = [ [1.0, 1.2], [2.3, 3.4], [4.5, 5.7], ] pads = [0, 2, 0, 0] mode = 'reflect' output = [ [1.0, 1.2, 1.0, 1.2], [2.3, 3.4, 2.3, 3.4], [4.5, 5.7, 4.5, 5.7], ] Example 3 (`edge` mode): data = [ [1.0, 1.2], [2.3, 3.4], [4.5, 5.7], ] pads = [0, 2, 0, 0] mode = 'edge' output = [ [1.0, 1.0, 1.0, 1.2], [2.3, 2.3, 2.3, 3.4], [4.5, 4.5, 4.5, 5.7], ] )DOC""; ONNX_OPERATOR_SET_SCHEMA( Pad, 11, OpSchema() .Attr( ""mode"", ""Supported modes: `constant`(default), `reflect`, `edge`"", AttributeProto::STRING, std::string(""constant"")) .SetDoc(Pad_ver11_doc) .Input(0, ""data"", ""Input tensor."", ""T"") .Input( 1, ""pads"", ""Tensor of integers indicating the number of padding elements to add or remove (if negative) "" ""at the beginning and end of each axis. For 2D input tensor, it is the number of pixels. "" ""`pads` should be a 1D tensor of shape [2 * input_rank]. "" ""`pads` format should be: [x1_begin, x2_begin,...,x1_end, x2_end,...], "" ""where xi_begin is the number of pad values added at the beginning of axis `i` and "" ""xi_end, the number of pad values added at the end of axis `i`."", ""tensor(int64)"") .Input( 2, ""constant_value"", ""(Optional) A scalar value to be used if the mode chosen is `constant` (by default it is 0)."", ""T"", OpSchema::Optional) .Output(0, ""output"", ""Tensor after padding."", ""T"") .TypeConstraint(""T"", OpSchema::all_numeric_types(), ""Constrain input and output to only numeric types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { // Type inference propagateElemTypeFromInputToOutput(ctx, 0, 0); // Shape inference needs the input data shape if (!hasNInputShapes(ctx, 1)) { return; } const auto& input_shape = ctx.getInputType(0)->tensor_type().shape(); const auto input_rank = input_shape.dim_size(); // Infer output shape if 'pads' tensor is available const auto* pads_initializer = ctx.getInputData(1); if (nullptr != pads_initializer) { if (pads_initializer->dims_size() != 1 || pads_initializer->data_type() != TensorProto::INT64) { fail_shape_inference(""'pads' input must be a 1D (shape: [2 * input_rank]) tensor of type int64""); } const auto& pads_data = ParseData(pads_initializer); if (pads_data.size() != static_cast(2 * input_rank)) { fail_shape_inference(""Pads has incorrect number of values""); } auto* output_shape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); for (size_t i = 0; static_cast(i) < input_rank; ++i) { const auto& input_dim = input_shape.dim((int)i); auto* output_dim = output_shape->add_dim(); if (input_dim.has_dim_value()) { output_dim->set_dim_value(input_dim.dim_value() + pads_data[i] + pads_data[i + input_rank]); } else if (pads_data[i] + pads_data[i + input_rank] == 0) { *output_dim = input_dim; } } } else { // Infer output shapes' rank in any case auto* output_shape_0 = getOutputShape(ctx, 0); for (size_t i = 0; static_cast(i) < input_rank; ++i) { output_shape_0->add_dim(); } } return; })); static const char* Cast_ver1_doc = R""DOC( The operator casts the elements of a given input tensor to a data type specified by the 'to' argument and returns an output tensor of the same size in the converted type. The 'to' argument must be one of the data types specified in the 'DataType' enum field in the TensorProto message. NOTE: Casting to and from strings is not supported yet. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Cast, 1, OpSchema() .SetDoc(Cast_ver1_doc) .Attr( ""to"", ""The data type to which the elements of the input tensor are cast. "" ""Strictly must be one of the types from DataType enum in TensorProto"", AttributeProto::STRING) .Input(0, ""input"", ""Input tensor to be cast."", ""T1"") .Output( 0, ""output"", ""Output tensor with the same shape as input with type "" ""specified by the 'to' argument"", ""T2"") .TypeConstraint( ""T1"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)"", ""tensor(int8)"", ""tensor(int16)"", ""tensor(int32)"", ""tensor(int64)"", ""tensor(uint8)"", ""tensor(uint16)"", ""tensor(uint32)"", ""tensor(uint64)"", ""tensor(bool)""}, ""Constrain input types. Casting from strings and complex are not supported."") .TypeConstraint( ""T2"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)"", ""tensor(int8)"", ""tensor(int16)"", ""tensor(int32)"", ""tensor(int64)"", ""tensor(uint8)"", ""tensor(uint16)"", ""tensor(uint32)"", ""tensor(uint64)"", ""tensor(bool)""}, ""Constrain output types. Casting to strings and complex are not supported."")); static const char* Cast_ver6_doc = R""DOC( The operator casts the elements of a given input tensor to a data type specified by the 'to' argument and returns an output tensor of the same size in the converted type. The 'to' argument must be one of the data types specified in the 'DataType' enum field in the TensorProto message. NOTE: Casting to and from strings is not supported yet. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Cast, 6, OpSchema() .SetDoc(Cast_ver6_doc) .Attr( ""to"", ""The data type to which the elements of the input tensor are cast. "" ""Strictly must be one of the types from DataType enum in TensorProto"", AttributeProto::INT) .Input(0, ""input"", ""Input tensor to be cast."", ""T1"") .Output( 0, ""output"", ""Output tensor with the same shape as input with type "" ""specified by the 'to' argument"", ""T2"") .TypeConstraint( ""T1"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)"", ""tensor(int8)"", ""tensor(int16)"", ""tensor(int32)"", ""tensor(int64)"", ""tensor(uint8)"", ""tensor(uint16)"", ""tensor(uint32)"", ""tensor(uint64)"", ""tensor(bool)""}, ""Constrain input types. Casting from strings and complex are not supported."") .TypeConstraint( ""T2"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)"", ""tensor(int8)"", ""tensor(int16)"", ""tensor(int32)"", ""tensor(int64)"", ""tensor(uint8)"", ""tensor(uint16)"", ""tensor(uint32)"", ""tensor(uint64)"", ""tensor(bool)""}, ""Constrain output types. Casting to strings and complex are not supported."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromAttributeToOutput(ctx, ""to"", 0); if (hasNInputShapes(ctx, 1)) { propagateShapeFromInputToOutput(ctx, 0, 0); } })); static const char* Concat_ver1_doc = R""DOC(Concatenate a list of tensors into a single tensor)DOC""; ONNX_OPERATOR_SET_SCHEMA( Concat, 1, OpSchema() .Attr(""axis"", ""Which axis to concat on. Default value is 1."", AttributeProto::INT, OPTIONAL_VALUE) .SetDoc(Concat_ver1_doc) .Input(0, ""inputs"", ""List of tensors for concatenation"", ""T"", OpSchema::Variadic) .Output(0, ""concat_result"", ""Concatenated tensor"", ""T"") .TypeConstraint( ""T"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)""}, ""Constrain output types to float tensors."")); ONNX_OPERATOR_SET_SCHEMA( Concat, 4, OpSchema() .Attr(""axis"", ""Which axis to concat on"", AttributeProto::INT) .SetDoc(""Concatenate a list of tensors into a single tensor"") .Input(0, ""inputs"", ""List of tensors for concatenation"", ""T"", OpSchema::Variadic) .Output(0, ""concat_result"", ""Concatenated tensor"", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain output types to any tensor type."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); auto numInputs = ctx.getNumInputs(); if (numInputs < 1 || !hasNInputShapes(ctx, static_cast(numInputs))) { return; } auto rank = ctx.getInputType(0)->tensor_type().shape().dim_size(); auto axisAttr = ctx.getAttribute(""axis""); if (!axisAttr) { fail_shape_inference(""Required attribute axis is missing""); } int axis = static_cast(axisAttr->i()); if (rank <= axis) { fail_shape_inference(""rank must be greater than axis""); } if (axis < 0) { return; // TODO: check if negative axis must be supported } bool all_lengths_known = true; int total_length = 0; auto* output_shape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); for (int64_t i = 0; i < rank; ++i) { output_shape->add_dim(); } for (size_t i = 0; i < numInputs; i++) { const auto& shape = ctx.getInputType(i)->tensor_type().shape(); if (shape.dim_size() != rank) { fail_shape_inference(""All inputs to Concat must have same rank""); } for (int j = 0; j < rank; j++) { if (j == axis) { if (shape.dim(j).has_dim_value()) { total_length += static_cast(shape.dim(j).dim_value()); } else { all_lengths_known = false; } } else { auto& output_dim = *output_shape->mutable_dim(j); const auto& input_dim = shape.dim(j); mergeInDimensionInfo(input_dim, output_dim, j); } } } if (all_lengths_known) { output_shape->mutable_dim(axis)->set_dim_value(total_length); } })); static const char* Split_ver1_doc = R""DOC(Split a tensor into a list of tensors, along the specified 'axis'. The lengths of the split can be specified using argument 'axis' or optional second input blob to the operator. Otherwise, the tensor is split to equal sized parts. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Split, 1, OpSchema() .Input(0, ""input"", ""The tensor to split"", ""T"") .Input(1, ""split"", ""Optional list of output lengths (see also arg 'split')"", ""T"", OpSchema::Optional) .Output(0, ""outputs..."", ""One or more outputs forming list of tensors after splitting"", ""T"", OpSchema::Variadic) .TypeConstraint( ""T"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)""}, ""Constrain input types to float tensors."") .Attr(""axis"", ""Which axis to split on"", AttributeProto::INT, OPTIONAL_VALUE) .Attr(""split"", ""length of each output"", AttributeProto::INTS, OPTIONAL_VALUE) .SetDoc(Split_ver1_doc)); static const char* Pad_ver1_doc = R""DOC( Given `data` tensor, paddings, mode, and value. Example: Insert 0 paddings to the beginning of the second dimension. data = [ [1.0, 1.2], [2.3, 3.4], [4.5, 5.7], ] paddings = [0, 0, 2, 0] output = [ [ [0.0, 0.0, 1.0, 1.2], [0.0, 0.0, 2.3, 3.4], [0.0, 0.0, 4.5, 5.7], ], ] )DOC""; ONNX_OPERATOR_SET_SCHEMA( Pad, 1, OpSchema() .Attr( ""paddings"", ""List of integers indicate the padding element count at the "" ""beginning and end of each axis, for 2D it is the number of pixel. "" ""`paddings` rank should be double of the input's rank. `paddings` format should be as follow "" ""[x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels "" ""added at the beginning of axis `i` and xi_end, the number of pixels added at "" ""the end of axis `i`."", AttributeProto::INTS) .Attr(""mode"", ""Three modes: constant(default), reflect, edge"", AttributeProto::STRING, std::string(""constant"")) .Attr(""value"", ""One float, indicates the value to be filled, default is 0"", AttributeProto::FLOAT, 0.0f) .SetDoc(Pad_ver1_doc) .Input(0, ""data"", ""Input tensor."", ""T"") .Output(0, ""output"", ""Tensor after padding."", ""T"") .TypeConstraint( ""T"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)""}, ""Constrain input and output types to float tensors."")); static const char* Reshape_ver1_doc = R""DOC( Reshape the input tensor similar to numpy.reshape. It takes a tensor as input and an argument `shape`. It outputs the reshaped tensor. At most one dimension of the new shape can be -1. In this case, the value is inferred from the size of the tensor and the remaining dimensions. A dimension could also be 0, in which case the actual dimension value is unchanged (i.e. taken from the input tensor). Shape (second input) could be an empty shape, which means converting to a scalar. The input tensor's shape and the output tensor's shape are required to have the same number of elements.)DOC""; ONNX_OPERATOR_SET_SCHEMA( Reshape, 1, OpSchema() .SetDoc(Reshape_ver1_doc) .Attr(""shape"", ""New shape"", AttributeProto::INTS, OPTIONAL_VALUE) // This attribute was added via AllowConsumed API in OpSchema. // After removing the API, we're now using the Attr API to simulate the // old definition. .Attr(""consumed_inputs"", ""legacy optimization attribute."", AttributeProto::INTS, OPTIONAL_VALUE) .Input(0, ""data"", ""An input tensor."", ""T"") .Output(0, ""reshaped"", ""Reshaped data."", ""T"") .TypeConstraint( ""T"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)""}, ""Constrain input and output types to float tensors."")); static const char* Upsample_ver1_doc = R""DOC( Upsample the input tensor. The width and height of the output tensor are: output_width = floor(input_width * width_scale), output_height = floor(input_height * height_scale). Example: Given `data` tensor, width_scale, height_scale, mode, Upsample the input 4-D tensor in nearest mode: data = [[[ [1, 2], [3, 4] ]]] width_scale = 2 height_scale = 2 mode = ""nearest"" output = [[[ [1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4] ]]] )DOC""; ONNX_OPERATOR_SET_SCHEMA( Tile, 1, OpSchema() .SetDoc(""Repeat the elements of a tensor along an axis."") .Input(0, ""input"", ""Input tensor of any shape."", ""T"") .Input(1, ""tiles"", ""Number of repeated copies to make of the input tensor."", ""T"") .Input(2, ""axis"", ""Axis along which to repeat."", ""T"") .Output(0, ""output"", ""Output tensor of same shape and type as input."", ""T"") .TypeConstraint( ""T"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)""}, ""Constrain input types to float tensors."") .TypeConstraint(""T1"", {""tensor(int64)""}, ""Constrain tiles and axis's type to int64 tensors."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); // Only rank of output can be inferred. We can do better if second // input is a constant, but this requires extending InferenceContext // interface to get values of constant inputs. })); ONNX_OPERATOR_SET_SCHEMA( Upsample, 1, OpSchema() .SetSupportLevel(OpSchema::SupportType::EXPERIMENTAL) .Attr( ""width_scale"", ""The scale along width dimension. It takes value greater than or equal to 1."", AttributeProto::FLOAT) .Attr( ""height_scale"", ""The scale along height dimension. It takes value greater than or equal to 1."", AttributeProto::FLOAT) .Attr( ""mode"", ""Two interpolation modes: nearest(default), bilinear"", AttributeProto::STRING, std::string(""nearest"")) .Input(0, ""X"", ""4-D tensor, [N,C,H,W]"", ""T"") .Output(0, ""Y"", ""4-D tensor after resizing, [N,C,H,W]"", ""T"") .TypeConstraint( ""T"", {""tensor(bool)"", ""tensor(int32)"", ""tensor(int64)"", ""tensor(float16)"", ""tensor(float)"", ""tensor(double)""}, ""Constrain output types to bool, int32, int64, float16, float, double tensors."") .SetDoc(Upsample_ver1_doc)); static const char* Upsample_ver7_doc = R""DOC( Upsample the input tensor. Each dimension value of the output tensor is: output_dimension = floor(input_dimension * scale). )DOC""; ONNX_OPERATOR_SET_SCHEMA( Upsample, 7, OpSchema() .Attr( ""scales"", ""The scale array along each dimension. It takes value greater than or equal to 1."" "" The number of elements of 'scales' should be the same as the rank of input 'X'."", AttributeProto::FLOATS) .Attr( ""mode"", ""Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)"", AttributeProto::STRING, std::string(""nearest"")) .Input(0, ""X"", ""N-D tensor"", ""T"") .Output(0, ""Y"", ""N-D tensor after resizing"", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .SetDoc(Upsample_ver7_doc) .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { if (!hasNInputShapes(ctx, 1)) { return; } propagateElemTypeFromInputToOutput(ctx, 0, 0); const auto& input_shape = getInputShape(ctx, 0); auto* output_shape = getOutputShape(ctx, 0); const auto* scales = ctx.getAttribute(""scales""); if (output_shape->dim_size() > 0) { if (output_shape->dim_size() != input_shape.dim_size()) { fail_shape_inference( ""Ranks inferred ("", input_shape.dim_size(), "") is not equal to the existing rank value ("", output_shape->dim_size(), "").""); } } else { // Infer the rank of output anyway for (int i = 0; i < input_shape.dim_size(); ++i) { output_shape->add_dim(); } } if (nullptr != scales) { // Infer output shape's dimension value if 'scales' is known. if (scales->type() == AttributeProto_AttributeType_FLOATS) { const std::vector scales_data(scales->floats().begin(), scales->floats().end()); if (scales_data.size() != static_cast(input_shape.dim_size())) { fail_shape_inference(""Number of elements of attribute 'scales' must be same as rank of input 'X'""); } resizeShapeInferenceHelper_opset7_to_10(input_shape, scales_data, output_shape); } else { fail_shape_inference(""Attribute 'scales' must have floats type.""); } // scales->type() == float } else { fail_shape_inference(""Attribute 'scales' is required.""); } // nullptr != scales })); static const char* Upsample_ver9_doc = R""DOC( Upsample the input tensor. Each dimension value of the output tensor is: output_dimension = floor(input_dimension * scale). )DOC""; ONNX_OPERATOR_SET_SCHEMA( Upsample, 9, OpSchema() .Attr( ""mode"", ""Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)"", AttributeProto::STRING, std::string(""nearest"")) .Input(0, ""X"", ""N-D tensor"", ""T"") .Input( 1, ""scales"", ""The scale array along each dimension. It takes value greater than or equal to 1."" "" The number of elements of 'scales' should be the same as the rank of input 'X'."", ""tensor(float)"") .Output(0, ""Y"", ""N-D tensor after resizing"", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input 'X' and output 'Y' to all tensor types."") .SetDoc(Upsample_ver9_doc) .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { resizeShapeInference_opset7_to_10(ctx); })); static const char* Resize_ver10_doc = R""DOC( Resize the input tensor. Each dimension value of the output tensor is: output_dimension = floor(input_dimension * scale). )DOC""; ONNX_OPERATOR_SET_SCHEMA( Resize, 10, OpSchema() .Attr( ""mode"", ""Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)"", AttributeProto::STRING, std::string(""nearest"")) .Input(0, ""X"", ""N-D tensor"", ""T"") .Input( 1, ""scales"", ""The scale array along each dimension. It takes value greater than 0. If it's less than 1,"" "" it's sampling down, otherwise, it's upsampling. The number of elements of 'scales' should"" "" be the same as the rank of input 'X'."", ""tensor(float)"") .Output(0, ""Y"", ""N-D tensor after resizing"", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input 'X' and output 'Y' to all tensor types."") .SetDoc(Resize_ver10_doc) .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { resizeShapeInference_opset7_to_10(ctx); })); static const char* Slice_ver1_doc = R""DOC( Produces a slice of the input tensor along multiple axes. Similar to numpy: https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html Slices uses `axes`, `starts` and `ends` attributes to specify the start and end dimension for each axis in the list of axes, it uses this information to slice the input `data` tensor. If a negative value is passed for any of the start or end indices, it represent number of elements before the end of that dimension. If the value passed to start or end is larger than the `n` (the number of elements in this dimension), it represents `n`. For slicing to the end of a dimension with unknown size, it is recommended to pass in `INT_MAX`. If `axes` are omitted, they are set to `[0, ..., ndim-1]`. Example 1: data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] axes = [0, 1] starts = [1, 0] ends = [2, 3] result = [ [5, 6, 7], ] Example 2: data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] starts = [0, 1] ends = [-1, 1000] result = [ [2, 3, 4], ] )DOC""; ONNX_OPERATOR_SET_SCHEMA( Slice, 1, OpSchema() .SetDoc(Slice_ver1_doc) .Input(0, ""data"", ""Tensor of data to extract slices from."", ""T"") .Attr( ""axes"", ""Axes that `starts` and `ends` apply to. "" ""It's optional. If not present, will be treated as "" ""[0, 1, ..., len(`starts`) - 1]."", AttributeProto::INTS, OPTIONAL_VALUE) .Attr(""starts"", ""Starting indices of corresponding axis in `axes`"", AttributeProto::INTS) .Attr(""ends"", ""Ending indices (exclusive) of corresponding axis in axes`"", AttributeProto::INTS) .Output(0, ""output"", ""Sliced data tensor."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (!hasNInputShapes(ctx, 1)) { return; } std::vector starts; std::vector ends; if (!getRepeatedAttribute(ctx, ""starts"", starts) || !getRepeatedAttribute(ctx, ""ends"", ends) || starts.size() != ends.size()) { fail_shape_inference(""Incorrect or missing attribute value for starts and ends""); } std::vector axes; if (!getRepeatedAttribute(ctx, ""axes"", axes)) { for (int i = 0; (size_t)i < starts.size(); ++i) { axes.push_back(i); } } else if (axes.size() != starts.size()) { fail_shape_inference(""Attribute axes has incorrect length""); } else if (!std::is_sorted(axes.begin(), axes.end())) { // TODO support shape inference for unsorted axes return; } auto [MASK] = [](int64_t index) { return index < 0; }; if (std::any_of(starts.begin(), starts.end(), [MASK] ) || std::any_of(ends.begin(), ends.end(), [MASK] ) || std::any_of(axes.begin(), axes.end(), [MASK] )) { // Negative axes were not explicitly discussed in the spec before opset-10. // Hence, they are officially not part of the spec, but some models/runtimes may use them. // So we perform simple rank inference in this case. for (size_t i = 0; (int64_t)i < ctx.getInputType(0)->tensor_type().shape().dim_size(); ++i) { ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim(); } return; } ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); for (size_t i = 0, j = 0; (int64_t)i < ctx.getInputType(0)->tensor_type().shape().dim_size(); ++i) { auto* newdim = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim(); if (j < axes.size() && static_cast(axes[j]) == i) { // There's a lot of potential behaviors. For now just // handle some simple cases. if (ctx.getInputType(0)->tensor_type().shape().dim((int)i).has_dim_value() && starts[j] >= 0 && ends[j] >= 0) { auto newval = std::min((int64_t)ctx.getInputType(0)->tensor_type().shape().dim((int)i).dim_value(), ends[j]) - starts[j]; if (newval >= 0) { newdim->set_dim_value(newval); } } ++j; } else { *newdim = ctx.getInputType(0)->tensor_type().shape().dim((int)i); } } })); static const char* Slice_ver10_doc = R""DOC( Produces a slice of the input tensor along multiple axes. Similar to numpy: https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html Slices uses `starts`, `ends`, `axes` and `steps` inputs to specify the start and end dimension and step for each axis in the list of axes, it uses this information to slice the input `data` tensor. If a negative value is passed for any of the start or end indices, it represent number of elements before the end of that dimension. If the value passed to start or end is larger than the `n` (the number of elements in this dimension), it represents `n`. For slicing to the end of a dimension with unknown size, it is recommended to pass in `INT_MAX`. If a negative value is passed for step, it represents slicing backward. If `axes` are omitted, they are set to `[0, ..., ndim-1]`. If `steps` are omitted, they are set to `[1, ..., 1]` of length `len(starts)` Example 1: data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] axes = [0, 1] starts = [1, 0] ends = [2, 3] steps = [1, 2] result = [ [5, 7], ] Example 2: data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] starts = [0, 1] ends = [-1, 1000] result = [ [2, 3, 4], ] )DOC""; ONNX_OPERATOR_SET_SCHEMA( Slice, 10, OpSchema() .SetDoc(Slice_ver10_doc) .Input(0, ""data"", ""Tensor of data to extract slices from."", ""T"") .Input(1, ""starts"", ""1-D tensor of starting indices of corresponding axis in `axes`"", ""Tind"") .Input(2, ""ends"", ""1-D tensor of ending indices (exclusive) of corresponding axis in `axes`"", ""Tind"") .Input(3, ""axes"", ""1-D tensor of axes that `starts` and `ends` apply to."", ""Tind"", OpSchema::Optional) .Input( 4, ""steps"", ""1-D tensor of slice step of corresponding axis in `axes`. Default to 1. "", ""Tind"", OpSchema::Optional) .Output(0, ""output"", ""Sliced data tensor."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeConstraint(""Tind"", {""tensor(int32)"", ""tensor(int64)""}, ""Constrain indices to integer types"") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { size_t num_inputs = ctx.getNumInputs(); if (num_inputs != 3 && num_inputs != 4 && num_inputs != 5) { fail_type_inference(""Slice op must have either three, four or five inputs.""); } propagateElemTypeFromInputToOutput(ctx, 0, 0); if (!hasNInputShapes(ctx, 1)) { return; } // Shape Inference if // 1. 2nd and 3rd input data (starts, ends) are available. // and 2. 4th and 5th optional input (axes, steps) are either not set, // or set and is initializer. const TensorProto* startsInitializer = ctx.getInputData(1); const TensorProto* endsInitializer = ctx.getInputData(2); const TensorProto* axesInitializer = hasInputShape(ctx, 3) ? ctx.getInputData(3) : nullptr; const TensorProto* stepsInitializer = hasInputShape(ctx, 4) ? ctx.getInputData(4) : nullptr; if (!startsInitializer || !endsInitializer || (hasInputShape(ctx, 3) && !ctx.getInputData(3)) || (hasInputShape(ctx, 4) && !ctx.getInputData(4))) { return; } // don't know data_type- can't proceed if (!startsInitializer->has_data_type()) return; auto get_initializer_data = [](const TensorProto* initializer) -> std::vector { std::vector vec; if (initializer->data_type() == TensorProto::INT64) { const auto& data = ParseData(initializer); vec.insert(vec.end(), data.begin(), data.end()); } else if (initializer->data_type() == TensorProto::INT32) { const auto& data = ParseData(initializer); vec.insert(vec.end(), data.begin(), data.end()); } else { // unaccepted data type fail_shape_inference(""Only supports `int32_t` or `int64_t` inputs for starts/ends/axes/steps""); } return vec; }; auto clamp = [](int64_t val, int64_t low, int64_t high) -> int64_t { if (val < low) return low; if (val > high) return high; return val; }; std::vector starts = get_initializer_data(startsInitializer); std::vector ends = get_initializer_data(endsInitializer); if (starts.size() != ends.size()) { fail_shape_inference(""Incorrect or missing input value for starts and ends""); } const auto& input_shape = ctx.getInputType(0)->tensor_type().shape(); const auto input_rank = input_shape.dim_size(); std::vector axes(starts.size()); if (!axesInitializer) { std::iota(axes.begin(), axes.end(), 0); } else { axes = get_initializer_data(axesInitializer); if (axes.size() != starts.size()) { fail_shape_inference(""Input axes has incorrect length""); } } std::vector steps; if (!stepsInitializer) { steps = std::vector(starts.size(), 1); } else { steps = get_initializer_data(stepsInitializer); if (steps.size() != axes.size()) { fail_shape_inference(""Input steps has incorrect length""); } } for (size_t i = 0; (int64_t)i < input_rank; ++i) { // first update rank of output dim auto* output_dim = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim(); const auto& input_dim = input_shape.dim((int)i); if (input_dim.has_dim_value()) { output_dim->set_dim_value(input_dim.dim_value()); } else if (input_dim.has_dim_param()) { output_dim->set_dim_param(TString{input_dim.dim_param()}); } } std::unordered_set unique_axes; size_t axes_size = axes.size(); for (size_t axis_index = 0; axis_index < axes_size; ++axis_index) { auto axis = axes[axis_index] < 0 ? axes[axis_index] + static_cast(input_rank) : axes[axis_index]; if (axis >= static_cast(input_rank) || axis < 0) { fail_shape_inference(""Input axes has invalid data""); } if (unique_axes.find(axis) != unique_axes.end()) { fail_shape_inference(""'axes' has duplicates""); } unique_axes.insert(axis); auto input_dim = ctx.getInputType(0)->tensor_type().shape().dim((int)axis); // input dim value is missing - cannot perform shape inference for // this axis if (!input_dim.has_dim_value()) continue; const auto input_dim_value = input_dim.dim_value(); // process step auto step = steps[axis_index]; if (step == 0) { fail_shape_inference(""'step' cannot be 0""); } // process start auto start = starts[axis_index]; if (start < 0) start += input_dim_value; if (step < 0) start = clamp(start, 0, input_dim_value - 1); else start = clamp(start, 0, input_dim_value); // process end auto end = ends[axis_index]; if (end < 0) end += input_dim_value; if (step < 0) end = clamp(end, -1, input_dim_value); else end = clamp(end, 0, input_dim_value); // find output dim value for this axis auto temp = static_cast(ceil(1.0 * (end - start) / step)); if (temp < 0) temp = 0; // assign output value ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->mutable_dim((int)axis)->set_dim_value(temp); } })); static const char* Scatter_ver9_doc = R""DOC( Given `data`, `updates` and `indices` input tensors of rank r >= 1, write the values provided by `updates` into the first input, `data`, along `axis` dimension of `data` (by default outer-most one as axis=0) at corresponding `indices`. For each entry in `updates`, the target index in `data` is specified by corresponding entry in `indices` for dimension = axis, and index in source for dimension != axis. For instance, in a 2-D tensor case, data[indices[i][j]][j] = updates[i][j] if axis = 0, or data[i][indices[i][j]] = updates[i][j] if axis = 1, where i and j are loop counters from 0 up to the respective size in `updates` - 1. Example 1: data = [ [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], ] indices = [ [1, 0, 2], [0, 2, 1], ] updates = [ [1.0, 1.1, 1.2], [2.0, 2.1, 2.2], ] output = [ [2.0, 1.1, 0.0] [1.0, 0.0, 2.2] [0.0, 2.1, 1.2] ] Example 2: data = [[1.0, 2.0, 3.0, 4.0, 5.0]] indices = [[1, 3]] updates = [[1.1, 2.1]] axis = 1 output = [[1.0, 1.1, 3.0, 2.1, 5.0]] )DOC""; ONNX_OPERATOR_SET_SCHEMA( Scatter, 9, OpSchema() .SetDoc(Scatter_ver9_doc) .Attr( ""axis"", ""Which axis to scatter on. Negative value means "" ""counting dimensions from the back. Accepted range is [-r, r-1]"", AttributeProto::INT, static_cast(0)) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"") .Input(1, ""indices"", ""Tensor of int32/int64 indices, of r >= 1 (same rank as input)."", ""Tind"") .Input(2, ""updates"", ""Tensor of rank r >=1 (same rank and shape as indices)"", ""T"") .Output(0, ""output"", ""Tensor of rank r >= 1 (same rank as input)."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Input and output types can be of any tensor type."") .TypeConstraint(""Tind"", {""tensor(int32)"", ""tensor(int64)""}, ""Constrain indices to integer types"") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (hasNInputShapes(ctx, 1)) { propagateShapeFromInputToOutput(ctx, 0, 0); } })); static const char* DepthToSpace_ver1_doc = R""DOC(DepthToSpace rearranges (permutes) data from depth into blocks of spatial data. This is the reverse transformation of SpaceToDepth. More specifically, this op outputs a copy of the input tensor where values from the depth dimension are moved in spatial blocks to the height and width dimensions. )DOC""; ONNX_OPERATOR_SET_SCHEMA( DepthToSpace, 1, OpSchema() .Attr(""blocksize"", ""Blocks of [blocksize, blocksize] are moved."", AttributeProto::INT) .SetDoc(DepthToSpace_ver1_doc) .Input( 0, ""input"", ""Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth"" "", H is the height and W is the width."", ""T"") .Output(0, ""output"", ""Output tensor of [N, C/(blocksize * blocksize), H * blocksize, W * blocksize]."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); auto blocksize = getAttribute(ctx, ""blocksize"", 0); if (blocksize <= 0) { fail_shape_inference(""Blocksize must be positive""); } if (hasInputShape(ctx, 0)) { auto& input_shape = getInputShape(ctx, 0); if (input_shape.dim_size() == 4) { // TODO: Clarify what behavior should be if C is not a multiple of // blocksize*blocksize. updateOutputShape( ctx, 0, {input_shape.dim(0), input_shape.dim(1) / (blocksize * blocksize), input_shape.dim(2) * blocksize, input_shape.dim(3) * blocksize}); } else { fail_shape_inference(""Input tensor must be 4-dimensional""); } } })); static const char* Gather_ver1_doc = R""DOC( Given `data` tensor of rank r >= 1, and `indices` tensor of rank q, gather entries of the axis dimension of `data` (by default outer-most one as axis=0) indexed by `indices`, and concatenates them in an output tensor of rank q + (r - 1). Example 1: ``` data = [ [1.0, 1.2], [2.3, 3.4], [4.5, 5.7], ] indices = [ [0, 1], [1, 2], ] output = [ [ [1.0, 1.2], [2.3, 3.4], ], [ [2.3, 3.4], [4.5, 5.7], ], ] ``` Example 2: ``` data = [ [1.0, 1.2, 1.9], [2.3, 3.4, 3.9], [4.5, 5.7, 5.9], ] indices = [ [0, 2], ] axis = 1, output = [ [ [1.0, 1.9], [2.3, 3.9], [4.5, 5.9], ], ] ``` )DOC""; ONNX_OPERATOR_SET_SCHEMA( Gather, 1, OpSchema() .SetDoc(Gather_ver1_doc) .Attr( ""axis"", ""Which axis to gather on. Negative value means "" ""counting dimensions from the back. Accepted range is [-r, r-1]"", AttributeProto::INT, static_cast(0)) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"") .Input( 1, ""indices"", ""Tensor of int32/int64 indices, of any rank q. All index values are expected to be within bounds. "" ""It is an error if any of the index values are out of bounds."", ""Tind"") .Output(0, ""output"", ""Tensor of rank q + (r - 1)."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to any tensor type."") .TypeConstraint(""Tind"", {""tensor(int32)"", ""tensor(int64)""}, ""Constrain indices to integer types"") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (!hasNInputShapes(ctx, 2)) { return; } const TensorShapeProto& data_shape = ctx.getInputType(0)->tensor_type().shape(); const TensorShapeProto& indices_shape = ctx.getInputType(1)->tensor_type().shape(); int r = data_shape.dim_size(); if (r < 1) { fail_shape_inference(""data tensor must have rank >= 1""); } int q = indices_shape.dim_size(); int axis = static_cast(getAttribute(ctx, ""axis"", 0)); if (axis < -r || axis >= r) { fail_shape_inference(""axis must be in [-r, r-1]""); } if (axis < 0) { axis += r; } int out_rank = q + r - 1; if (out_rank == 0) { ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); } for (int i = 0; i < out_rank; ++i) { *ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim() = (i < axis) ? data_shape.dim(i) : // i < axis < r (i >= axis && i < axis + q) ? indices_shape.dim(i - axis) : // i - axis < q data_shape.dim(i - q + 1); // i < out_rank < q + r - 1 } }) .PartialDataPropagationFunction([](DataPropagationContext& ctx) { GatherOp13DataPropagator(ctx); })); static const char* Squeeze_ver1_doc = R""DOC( Remove single-dimensional entries from the shape of a tensor. Takes a parameter `axes` with a list of axes to squeeze. If `axes` is not provided, all the single dimensions will be removed from the shape. If an axis is selected with shape entry not equal to one, an error is raised. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Squeeze, 1, OpSchema() .Attr( ""axes"", ""List of non-negative integers, indicate the dimensions to squeeze."", AttributeProto::INTS, OPTIONAL_VALUE) .SetDoc(Squeeze_ver1_doc) .Input(0, ""data"", ""Tensors with at least max(dims) dimensions."", ""T"") .Output(0, ""squeezed"", ""Reshaped tensor with same data as input."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (!hasNInputShapes(ctx, 1)) { return; } std::vector axes; if (!getRepeatedAttribute(ctx, ""axes"", axes)) { return; } if (!ctx.getInputType(0)->tensor_type().has_shape()) { return; } ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); const auto& input_shape = ctx.getInputType(0)->tensor_type().shape(); for (int i = 0, j = 0; i < input_shape.dim_size(); ++i) { if (static_cast(j) < axes.size() && axes[j] == i) { if (input_shape.dim(i).has_dim_value() && input_shape.dim(i).dim_value() != 1) { fail_shape_inference( ""Dimension of input "", i, "" must be 1 instead of "", input_shape.dim(i).dim_value()); } ++j; } else { *ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim() = input_shape.dim(i); } } })); static const char* Unsqueeze_ver1_doc = R""DOC( Insert single-dimensional entries to the shape of a tensor. Takes one required argument `axes`, a list of dimensions that will be inserted. Dimension indices in `axes` are as seen in the output tensor. For example: Given a tensor such that tensor with shape [3, 4, 5], then Unsqueeze(tensor, axes=[0, 4]) has shape [1, 3, 4, 5, 1] )DOC""; ONNX_OPERATOR_SET_SCHEMA( Unsqueeze, 1, OpSchema() .Attr(""axes"", ""List of non-negative integers, indicate the dimensions to be inserted"", AttributeProto::INTS) .SetDoc(Unsqueeze_ver1_doc) .Input(0, ""data"", ""Original tensor"", ""T"") .Output(0, ""expanded"", ""Reshaped tensor with same data as input."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (!hasNInputShapes(ctx, 1)) { return; } std::vector axes; if (!getRepeatedAttribute(ctx, ""axes"", axes)) { return; } std::sort(axes.begin(), axes.end()); if (!ctx.getInputType(0)->tensor_type().has_shape()) { return; } ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); int j = 0; for (int i = 0; i < ctx.getInputType(0)->tensor_type().shape().dim_size(); ++i) { while (static_cast(j) < axes.size() && axes[j] == ctx.getOutputType(0)->tensor_type().shape().dim_size()) { ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(1); ++j; } *ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim() = ctx.getInputType(0)->tensor_type().shape().dim(i); } while (static_cast(j) < axes.size() && axes[j] == ctx.getOutputType(0)->tensor_type().shape().dim_size()) { ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(1); ++j; } })); static const char* OneHot_ver9_doc = R""DOC( Produces a one-hot tensor based on inputs. The locations represented by the index values in the 'indices' input tensor will have 'on_value' and the other locations will have 'off_value' in the output tensor, where 'on_value' and 'off_value' are specified as part of required input argument 'values', which is a two-element tensor of format [off_value, on_value]. The rank of the output tensor will be one greater than the rank of the input tensor. The additional dimension is for one-hot representation. The additional dimension will be inserted at the position specified by 'axis'. If 'axis' is not specified then then additional dimension will be inserted as the innermost dimension, i.e. axis=-1. The size of the additional dimension is specified by required scalar input 'depth'. The type of the output tensor is the same as the type of the 'values' input. Any entries in the 'indices' input tensor with values outside the range [0, depth) will result in one-hot representation with all 'off_value' values in the output tensor. )DOC""; ONNX_OPERATOR_SET_SCHEMA( OneHot, 9, OpSchema() .SetDoc(OneHot_ver9_doc) .Attr( ""axis"", ""(Optional) Axis along which one-hot representation in added. Default: axis=-1. "" ""axis=-1 means that the additional dimension will be inserted as the "" ""innermost/last dimension in the output tensor."", AttributeProto::INT, static_cast(-1)) .Input( 0, ""indices"", ""Input tensor containing indices. The values must be non-negative integers. "" ""Any entries in the 'indices' input tensor with values outside the range [0, depth) "" ""will result in one-hot representation with all 'off_value' values in the output tensor."" ""In case 'indices' is of non-integer type, the values will be casted to int64 before use."", ""T1"") .Input( 1, ""depth"", ""Scalar specifying the number of classes in one-hot tensor. This is also the size "" ""of the one-hot dimension (specified by 'axis' attribute) added on in the output "" ""tensor. The values in the 'indices' input tensor are expected to be "" ""in the range [0, depth). "" ""In case 'depth' is of non-integer type, it will be casted to int64 before use."", ""T2"") .Input( 2, ""values"", ""Rank 1 tensor containing exactly two elements, in the format [off_value, on_value], "" ""where 'on_value' is the value used for filling locations specified in 'indices' input "" ""tensor, and 'off_value' is the value used for filling locations other than those specified "" ""in 'indices' input tensor. "", ""T3"") .Output( 0, ""output"", ""Tensor of rank one greater than input tensor 'indices', i.e. rank(output) = rank(indices) + 1. "" ""The data type for the elements of the output tensor is the same as the type of input 'values' "" ""is used."", ""T3"") .TypeConstraint(""T1"", OpSchema::all_numeric_types(), ""Constrain input to only numeric types."") .TypeConstraint(""T2"", OpSchema::all_numeric_types(), ""Constrain input to only numeric types."") .TypeConstraint(""T3"", OpSchema::all_tensor_types(), ""Constrain to any tensor type."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { // Check that the node has three inputs. if (ctx.getNumInputs() != 3) { fail_type_inference(""OneHot node must have three inputs.""); } // Input 'depth' must be a scalar or a single-element vector. // TODO: Ideally to match spec for this input only allow Scalar should // be allowed. Making this change now can affect backward // compatibility for this op. Since this does not seem like a good // justification to update version for this op, allowing both scalar // and 1 element vector for now. In future when version update for // this op is done we should only allow scalar or chage the spec to // allow both. if (hasInputShape(ctx, 1)) { auto& depth_shape = getInputShape(ctx, 1); if (depth_shape.dim_size() != 0 && depth_shape.dim_size() != 1) { fail_type_inference(""Input 'depth' must be a scalar or rank 1 tensor.""); } if (depth_shape.dim_size() == 1 && depth_shape.dim((int)0).has_dim_value() && depth_shape.dim((int)0).dim_value() != 1) { fail_type_inference(""Input 'depth' must have exactly one element.""); } } // Input 'values' must be a two-element vector. if (hasInputShape(ctx, 2)) { auto& values_shape = getInputShape(ctx, 2); if (values_shape.dim_size() != 1) { fail_type_inference(""Input 'values' must be rank 1 tensor.""); } if (values_shape.dim((int)0).has_dim_value() && values_shape.dim((int)0).dim_value() != 2) { fail_type_inference(""Input 'values' must have exactly two elements.""); } } // Set output type to be the same as the third input, 'values'. propagateElemTypeFromInputToOutput(ctx, 2, 0); // Set the output shape, if input 0 (indices) shape is available. if (hasInputShape(ctx, 0)) { const TensorShapeProto& indices_shape = ctx.getInputType(0)->tensor_type().shape(); int r = indices_shape.dim_size(); if (r < 1) { fail_shape_inference(""Indices tensor must have rank >= 1""); } int out_rank = r + 1; int axis = static_cast(getAttribute(ctx, ""axis"", -1)); if (axis < -out_rank || axis >= out_rank) { fail_shape_inference(""'axis' must be in [-rank(indices)-1, rank(indices)]""); } if (axis < 0) { axis += out_rank; } auto* output_shape = getOutputShape(ctx, 0); for (int i = 0; i < out_rank; ++i) { auto* dim = output_shape->add_dim(); if (i < axis) { if (indices_shape.dim(i).has_dim_value()) { dim->set_dim_value(indices_shape.dim(i).dim_value()); } else if (indices_shape.dim(i).has_dim_param()) { dim->set_dim_param(TString{indices_shape.dim(i).dim_param()}); } } else if (i > axis) { if (indices_shape.dim(i - 1).has_dim_value()) { dim->set_dim_value(indices_shape.dim(i - 1).dim_value()); } else if (indices_shape.dim(i - 1).has_dim_param()) { dim->set_dim_param(TString{indices_shape.dim(i - 1).dim_param()}); } } } } })); static const char* Compress_ver9_doc = R""DOC( Selects slices from an input tensor along a given axis where condition evaluates to True for each axis index. In case axis is not provided, input is flattened before elements are selected. Compress behaves like numpy.compress: https://docs.scipy.org/doc/numpy/reference/generated/numpy.compress.html )DOC""; ONNX_OPERATOR_SET_SCHEMA( Compress, 9, OpSchema() .SetDoc(Compress_ver9_doc) .Attr( ""axis"", ""(Optional) Axis along which to take slices. If not specified, "" ""input is flattened before elements being selected."", AttributeProto::INT, OPTIONAL_VALUE) .Input(0, ""input"", ""Tensor of rank r >= 1."", ""T"") .Input( 1, ""condition"", ""Rank 1 tensor of booleans to indicate which slices or data elements to be selected. "" ""Its length can be less than the input length alone the axis "" ""or the flattened input size if axis is not specified. "" ""In such cases data slices or elements exceeding the condition length are discarded."", ""T1"") .Output(0, ""output"", ""Tensor of rank r if axis is specified. Otherwise output is a Tensor of rank 1."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeConstraint(""T1"", {""tensor(bool)""}, ""Constrain to boolean tensors."")); static const char* Split_ver2_doc = R""DOC(Split a tensor into a list of tensors, along the specified 'axis'. Lengths of the parts can be specified using argument 'split'. Otherwise, the tensor is split to equal sized parts. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Split, 2, OpSchema() .Input(0, ""input"", ""The tensor to split"", ""T"") .Output(0, ""outputs"", ""One or more outputs forming list of tensors after splitting"", ""T"", OpSchema::Variadic) .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .Attr(""axis"", ""Which axis to split on. "", AttributeProto::INT, static_cast(0)) .Attr(""split"", ""length of each output"", AttributeProto::INTS, OPTIONAL_VALUE) .SetDoc(Split_ver2_doc) .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { for (int i = 0; i < static_cast(ctx.getNumOutputs()); ++i) { propagateElemTypeFromInputToOutput(ctx, 0, i); } if (!hasNInputShapes(ctx, 1)) { return; } const auto& shape = ctx.getInputType(0)->tensor_type().shape(); int rank = shape.dim_size(); int axis = static_cast(getAttribute(ctx, ""axis"", 0)); if (axis < -rank || axis >= rank) { fail_type_inference(""Invalid value of attribute 'axis'. Rank="", rank, "" Value="", axis); } // Previously Split-2 does not mention how to deal with negative axis // However, there is an existing test onnx/backend/test/data/pytorch-converted/test_GLU // using Split-2 with negative axis and it is hard to be regenerated. // To compromise, handle negative axis for Split-2 here. if (axis < 0) { axis += rank; } const auto& split_dim = shape.dim(axis); if (!split_dim.has_dim_value()) { for (size_t i = 0; i < ctx.getNumOutputs(); i++) { *ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape() = shape; ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape()->mutable_dim(axis)->Clear(); } return; } int split_dim_value = static_cast(split_dim.dim_value()); std::vector split; if (getRepeatedAttribute(ctx, ""split"", split)) { if (split.size() != ctx.getNumOutputs()) { fail_shape_inference( ""Mismatch between number of splits ("", split.size(), "") and outputs ("", ctx.getNumOutputs(), "")""); } int64_t total_dim = 0; for (int64_t d : split) { total_dim += d; } if (total_dim != split_dim_value) { fail_shape_inference( ""Mismatch between the sum of 'split' ("", total_dim, "") and the split dimension of the input ("", split_dim_value, "")""); } } else { int num_outputs = static_cast(ctx.getNumOutputs()); if (split_dim_value % num_outputs != 0) { fail_shape_inference(""The input is not evenly splittable""); } int chunk_size = split_dim_value / num_outputs; for (int i = 0; i < static_cast(ctx.getNumOutputs()); i++) { split.push_back(chunk_size); } } for (size_t i = 0; i < ctx.getNumOutputs(); i++) { *ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape() = shape; ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape()->mutable_dim(axis)->set_dim_value(split[i]); } })); static const char* Pad_ver2_doc = R""DOC( Given `data` tensor, pads, mode, and value. Example: Insert 0 pads to the beginning of the second dimension. data = [ [1.0, 1.2], [2.3, 3.4], [4.5, 5.7], ] pads = [0, 2, 0, 0] output = [ [ [0.0, 0.0, 1.0, 1.2], [0.0, 0.0, 2.3, 3.4], [0.0, 0.0, 4.5, 5.7], ], ] )DOC""; ONNX_OPERATOR_SET_SCHEMA( Pad, 2, OpSchema() .Attr( ""pads"", ""List of integers indicating the number of padding elements to add or remove (if negative) "" ""at the beginning and end of each axis. For 2D it is the number of pixels. "" ""`pads` rank should be double of the input's rank. `pads` format should be as follow "" ""[x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels "" ""added at the beginning of axis `i` and xi_end, the number of pixels added at "" ""the end of axis `i`."", AttributeProto::INTS) .Attr(""mode"", ""Three modes: constant(default), reflect, edge"", AttributeProto::STRING, std::string(""constant"")) .Attr(""value"", ""One float, indicates the value to be filled."", AttributeProto::FLOAT, 0.0f) .SetDoc(Pad_ver2_doc) .Input(0, ""data"", ""Input tensor."", ""T"") .Output(0, ""output"", ""Tensor after padding."", ""T"") .TypeConstraint( ""T"", {""tensor(float16)"", ""tensor(float)"", ""tensor(double)""}, ""Constrain input and output types to float tensors."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 0, 0); if (!hasNInputShapes(ctx, 1)) { return; } auto& input_shape = ctx.getInputType(0)->tensor_type().shape(); std::vector pads; if (!getRepeatedAttribute(ctx, ""pads"", pads)) { fail_shape_inference(""Attribute value for pads is required""); } if (pads.size() != static_cast(input_shape.dim_size() * 2)) { fail_shape_inference(""Attribute pads has incorrect length""); ; } ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); for (size_t i = 0; (int64_t)i < input_shape.dim_size(); ++i) { auto* newdim = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim(); if (ctx.getInputType(0)->tensor_type().shape().dim((int)i).has_dim_value()) { newdim->set_dim_value( ctx.getInputType(0)->tensor_type().shape().dim((int)i).dim_value() + pads[i] + pads[input_shape.dim_size() + i]); } else if (pads[i] + pads[input_shape.dim_size() + i] == 0) { *newdim = input_shape.dim((int)i); } } })); static const char* GatherND_ver11_doc = R""DOC( Given `data` tensor of rank `r` >= 1, and `indices` tensor of rank `q` >= 1, this operator gathers slices of `data` into an output tensor of rank `q + r - indices_shape[-1] - 1`. `indices` is an q-dimensional integer tensor, best thought of as a `(q-1)`-dimensional tensor of index-tuples into `data`, where each element defines a slice of `data` Some salient points about the inputs' rank and shape: 1) r >= 1 and q >= 1 are to be honored. There is no dependency condition to be met between ranks `r` and `q` 2) The `indices_shape[-1]` should have a value between 1 (inclusive) and rank `r` (inclusive) 3) All values in `indices` are expected to be within bounds [-s, s-1] along axis of size `s` (i.e.) `-data_shape[i] <= indices[...,i] <= data_shape[i] - 1`. It is an error if any of the index values are out of bounds. The output is computed as follows: The output tensor is obtained by mapping each index-tuple in the `indices` tensor to the corresponding slice of the input `data`. 1) If `indices_shape[-1] > r` => error condition 2) If `indices_shape[-1] == r`, since the rank of `indices` is `q`, `indices` can be thought of as a `(q-1)`-dimensional tensor containing 1-D tensors of dimension `r`. Let us think of each such `r` ranked tensor as `indices_slice`. Each *scalar value* corresponding to `data[indices_slice]` is filled into the corresponding location of the `(q-1)`-dimensional tensor to form the `output` tensor (Example 1 below) 3) If `indices_shape[-1] < r`, since the rank of `indices` is `q`, `indices` can be thought of as a `(q-1)`-dimensional tensor containing 1-D tensors of dimension `< r`. Let us think of each such tensors as `indices_slice`. Each *tensor slice* corresponding to `data[indices_slice , :]` is filled into the corresponding location of the `(q-1)`-dimensional tensor to form the `output` tensor (Examples 2, 3, and 4 below) This operator is the inverse of `ScatterND`. `Example 1` data = [[0,1],[2,3]] # data_shape = [2, 2] indices = [[0,0],[1,1]] # indices_shape = [2, 2] output = [0,3] # output_shape = [2] `Example 2` data = [[0,1],[2,3]] # data_shape = [2, 2] indices = [[1],[0]] # indices_shape = [2, 1] output = [[2,3],[0,1]] # output_shape = [2, 2] `Example 3` data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2] indices = [[0,1],[1,0]] # indices_shape = [2, 2] output = [[2,3],[4,5]] # output_shape = [2, 2] `Example 4` data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2] indices = [[[0,1]],[[1,0]]] # indices_shape = [2, 1, 2] output = [[[2,3]],[[4,5]]] # output_shape = [2, 1, 2] )DOC""; ONNX_OPERATOR_SET_SCHEMA( GatherND, 11, OpSchema() .SetDoc(GatherND_ver11_doc) .Input(0, ""data"", ""Tensor of rank r >= 1."", ""T"") .Input( 1, ""indices"", ""Tensor of rank q >= 1. All index values are expected to be within bounds [-s, s-1] "" ""along axis of size s. It is an error if any of the index values are out of bounds."", ""tensor(int64)"") .Output(0, ""output"", ""Tensor of rank q + r - indices_shape[-1] - 1."", ""T"") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to any tensor type."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { // Type inference propagateElemTypeFromInputToOutput(ctx, 0, 0); // Shape inference if (!hasNInputShapes(ctx, 2)) { // cannot proceed with shape or rank inference return; } const auto& data_shape = ctx.getInputType(0)->tensor_type().shape(); const auto data_rank = data_shape.dim_size(); const auto& indices_shape = ctx.getInputType(1)->tensor_type().shape(); const auto indices_rank = indices_shape.dim_size(); if (data_rank < 1 || indices_rank < 1) { fail_shape_inference( ""Both `data` and `indices` input tensors in GatherND op "" ""need to have rank larger than 0.""); } // cannot ascertain if the input shapes are valid if shape of // `indices` is missing last dimension value so return at this point if (!indices_shape.dim(indices_rank - 1).has_dim_value()) { return; } const auto last_index_dimension = indices_shape.dim(indices_rank - 1).dim_value(); if (last_index_dimension > data_rank) { fail_shape_inference( ""Last dimension of `indices` input tensor in GatherND op "" ""must not be larger than the rank of `data` tensor""); } for (int i = 0; i < indices_rank - 1; ++i) { *ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim() = indices_shape.dim(i); } for (int i = static_cast(last_index_dimension); i < data_rank; ++i) { *ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()->add_dim() = data_shape.dim(i); } })); ONNX_OPERATOR_SET_SCHEMA( Identity, 14, OpSchema() .SetDoc(""Identity operator"") .Input(0, ""input"", ""Input tensor"", ""V"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Output(0, ""output"", ""Tensor to copy input into."", ""V"", OpSchema::Single, true, 1, OpSchema::Differentiable) .TypeConstraint( ""V"", []() { auto t = OpSchema::all_tensor_types_with_bfloat(); auto s = OpSchema::all_tensor_sequence_types(); t.insert(t.end(), s.begin(), s.end()); return t; }(), ""Constrain input and output types to all tensor and sequence types."") .TypeAndShapeInferenceFunction(propagateShapeAndTypeFromFirstInput)); static const char* Where_ver9_doc = R""DOC( Return elements, either from X or Y, depending on condition. Where behaves like [numpy.where](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) with three parameters. )DOC""; ONNX_OPERATOR_SET_SCHEMA( Where, 9, OpSchema() .SetDoc(Where_ver9_doc + GenerateBroadcastingDocMul()) .Input( 0, ""condition"", ""When True (nonzero), yield X, otherwise yield Y"", ""B"", OpSchema::Single, true, 1, OpSchema::NonDifferentiable) .Input( 1, ""X"", ""values selected at indices where condition is True"", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Input( 2, ""Y"", ""values selected at indices where condition is False"", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Output( 0, ""output"", ""Tensor of shape equal to the broadcasted shape of condition, X, and Y."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .TypeConstraint(""B"", {""tensor(bool)""}, ""Constrain to boolean tensors."") .TypeConstraint(""T"", OpSchema::all_tensor_types(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { propagateElemTypeFromInputToOutput(ctx, 1, 0); if (hasNInputShapes(ctx, 3)) { std::vector shapes; shapes.push_back(&ctx.getInputType(0)->tensor_type().shape()); shapes.push_back(&ctx.getInputType(1)->tensor_type().shape()); shapes.push_back(&ctx.getInputType(2)->tensor_type().shape()); multidirectionalBroadcastShapeInference( shapes, *ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape()); } })); static const char* Pad_ver13_doc = R""DOC( Given a tensor containing the data to be padded (`data`), a tensor containing the number of start and end pad values for axis (`pads`), (optionally) a `mode`, and (optionally) `constant_value`, a padded tensor (`output`) is generated. The three supported `modes` are (similar to corresponding modes supported by `numpy.pad`): 1) `constant`(default) - pads with a given constant value as specified by `constant_value` (which defaults to 0, empty string, or False) 2) `reflect` - pads with the reflection of the vector mirrored on the first and last values of the vector along each axis 3) `edge` - pads with the edge values of array Example 1 (`constant` mode): Insert 0 pads to the beginning of the second dimension. data = [ [1.0, 1.2], [2.3, 3.4], [4.5, 5.7], ] pads = [0, 2, 0, 0] mode = 'constant' constant_value = 0.0 output = [ [0.0, 0.0, 1.0, 1.2], [0.0, 0.0, 2.3, 3.4], [0.0, 0.0, 4.5, 5.7], ] Example 2 (`reflect` mode): data = [ [1.0, 1.2], [2.3, 3.4], [4.5, 5.7], ] pads = [0, 2, 0, 0] mode = 'reflect' output = [ [1.0, 1.2, 1.0, 1.2], [2.3, 3.4, 2.3, 3.4], [4.5, 5.7, 4.5, 5.7], ] Example 3 (`edge` mode): data = [ [1.0, 1.2], [2.3, 3.4], [4.5, 5.7], ] pads = [0, 2, 0, 0] mode = 'edge' output = [ [1.0, 1.0, 1.0, 1.2], [2.3, 2.3, 2.3, 3.4], [4.5, 4.5, 4.5, 5.7], ] )DOC""; ONNX_OPERATOR_SET_SCHEMA( Pad, 13, OpSchema() .Attr( ""mode"", ""Supported modes: `constant`(default), `reflect`, `edge`"", AttributeProto::STRING, std::string(""constant"")) .SetDoc(Pad_ver13_doc) .Input(0, ""data"", ""Input tensor."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .Input( 1, ""pads"", ""Tensor of integers indicating the number of padding elements to add or remove (if negative) "" ""at the beginning and end of each axis. For 2D input tensor, it is the number of pixels. "" ""`pads` should be a 1D tensor of shape [2 * input_rank]. "" ""`pads` format should be: [x1_begin, x2_begin,...,x1_end, x2_end,...], "" ""where xi_begin is the number of pad values added at the beginning of axis `i` and "" ""xi_end, the number of pad values added at the end of axis `i`."", ""tensor(int64)"", OpSchema::Single, true, 1, OpSchema::NonDifferentiable) .Input( 2, ""constant_value"", ""(Optional) A scalar value to be used if the mode chosen is `constant` (by default it is 0, "" ""empty string or False)."", ""T"", OpSchema::Optional, true, 1, OpSchema::NonDifferentiable) .Output(0, ""output"", ""Tensor after padding."", ""T"", OpSchema::Single, true, 1, OpSchema::Differentiable) .TypeConstraint( ""T"", OpSchema::all_tensor_types_with_bfloat(), ""Constrain input and output types to all tensor types."") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { // Type inference propagateElemTypeFromInputToOutput(ctx, 0, 0); // Shape inference needs the input data shape if (!hasNInputShapes(ctx, 1)) { return; } const auto& input_shape = ctx.getInputType(0)->tensor_type().shape(); const auto input_rank = input_shape.dim_size(); // Infer output shape if 'pads' tensor is available const auto* pads_initializer = ctx.getInputData(1); if (nullptr != pads_initializer) { if (pads_initializer->dims_size() != 1 || pads_initializer->data_type() != TensorProto::INT64) { fail_shape_inference(""'pads' input must be a 1D (shape: [2 * input_rank]) tensor of type int64""); } const auto& pads_data = ParseData(pads_initializer); if (pads_data.size() != static_cast(2 * input_rank)) { fail_shape_inference(""Pads has incorrect number of values""); } auto* output_shape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape(); for (size_t i = 0; static_cast(i) < input_rank; ++i) { const auto& input_dim = input_shape.dim((int)i); auto* output_dim = output_shape->add_dim(); if (input_dim.has_dim_value()) { output_dim->set_dim_value(input_dim.dim_value() + pads_data[i] + pads_data[i + input_rank]); } else if (pads_data[i] + pads_data[i + input_rank] == 0) { *output_dim = input_dim; } } } else { // Infer output shapes' rank in any case auto* output_shape_0 = getOutputShape(ctx, 0); for (size_t i = 0; static_cast(i) < input_rank; ++i) { output_shape_0->add_dim(); } } return; })); } // namespace ONNX_NAMESPACE ",is_negative 72,"#include #include #include #define LED D0 // Led in NodeMCU at pin GPIO16 (D0). // Set these to run example. #define FIREBASE_HOST ""garagecardetector.firebaseio.com"" #define FIREBASE_AUTH ""TuJmJEc1YJRAOtEEiS1qYxYE2KiqRDaWNkGxyLhm""//change with your Database secrets #define WIFI_SSID ""TuHu"" #define WIFI_PASSWORD """" #define NODE_NAME ""LB Aventador"" #define NODE_KEY ""aventador"" #define VEHICLE_RANG 150 //number cm from node to vehicle #define GMC_START ""{\""time_to_live\"":300,\""to\"":\""/topics/garages-car-detector\"",\""notification\"":{\""title\"":\""The car state change\"",\""body\"":\""""//change""garages-car-detector"" with your topic #define GMC_END ""\""}}"" //for GMC char API_key[] = """";//change with server mgs key const char* host = ""fcm.googleapis.com""; const char* GMC_DATA = ""{\""time_to_live\"":300,\""to\"":\""/topics/garages-car-detector\"",\""notification\"":{\""title\"":\""The car state change\"",\""body\"":\""testcfsdf\""}}"";//Change topic with yours WiFiClient client; // long lastMsg = 0; Ultrasonic ultrasonic(5, 4); // (Trig PIN,Echo PIN) D1(GPIO5) and D2(GPIO4) in Nodemcu 1.0 long distance; bool inRange; bool lastState; StaticJsonBuffer<150> jsonBuffer; JsonObject& timestamp = jsonBuffer.createObject(); JsonObject& updateData = jsonBuffer.createObject(); void wifi_smartconfig() { int [MASK] = 0; WiFi.mode(WIFI_STA); while (WiFi.status() != WL_CONNECTED) { digitalWrite(LED, LOW); // turn the LED on. Serial.print("".""); delay(250); digitalWrite(LED, HIGH); // turn the LED off. delay(250); Serial.print("".""); if ( [MASK] ++ >= 20) { digitalWrite(LED, LOW); // turn the LED on. Serial.print("".""); delay(150); digitalWrite(LED, HIGH); // turn the LED off. delay(550); Serial.print(""Smartconfig...""); WiFi.beginSmartConfig(); while (1) { delay(1000); if (WiFi.smartConfigDone()) { Serial.println(""SmartConfig Success""); break; } } } } } void setup() { pinMode(LED, OUTPUT); // LED pin as output. low to on led, high to off led Serial.begin(9600); // // connect to wifi. // WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // Serial.print(""connecting""); // while (WiFi.status() != WL_CONNECTED) { // digitalWrite(LED, LOW); // turn the LED on. // Serial.print("".""); // delay(250); // digitalWrite(LED, HIGH); // turn the LED on. // delay(250); // } wifi_smartconfig(); Serial.println(); Serial.print(""connected: ""); Serial.println(WiFi.localIP()); timestamp["".sv""] = ""timestamp""; Serial.println(); timestamp.prettyPrintTo(Serial); Serial.println(); Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); } void updateDistance() { updateData[""name""] = NODE_NAME; updateData[""distance""] = distance; updateData[""in_range""] = inRange; updateData[""timestamp""] = timestamp; Firebase.set(NODE_KEY, updateData); Serial.println(); Serial.println(""Data update""); updateData.prettyPrintTo(Serial); Serial.println(); if (Firebase.failed()) { Serial.print(""setting time failed:""); Serial.println(Firebase.error()); return; } digitalWrite(LED, LOW); // turn the LED on. delay(200); digitalWrite(LED, HIGH); // turn the LED off. delay(500); } //Function for sending the request to GCM void sendToGCM() { Serial.print(""connecting to ""); Serial.println(host); if (!client.connect(host, 80)) { Serial.println(""connection failed""); return; } if (client.connected()) { String body; body += F(NODE_NAME); if (inRange == true)body += F("" is safe""); else body += F("" is out of range""); long msg_size = strlen(GMC_START) + body.length() + strlen(GMC_END); Serial.println(""sending request""); client.print(""POST /fcm/send HTTP/1.1\r\n""); // http POST request client.print(""Host: fcm.googleapis.com\r\n""); client.println(""User-Agent: Arduino""); client.print(""Authorization:key="");// client.println(API_key); client.print(""Content-Type: application/json\r\n""); client.println(""Connection: close""); client.print(""Content-length: ""); // has to be exactly the number of characters (bytes) in the POST body //client.println(strlen(GMC_DATA)); // calculate content-length // client.println(""""); // client.print(GMC_DATA); client.println(msg_size); // calculate content-length client.println(""""); client.print(GMC_START); client.print(body); client.print(GMC_END); delay(10); Serial.println(""request sent""); while (client.connected()) { String line = client.readStringUntil('\n'); if (line == ""\r"") { Serial.println(""headers received""); break; } } String line = client.readStringUntil('\n'); Serial.println(""reply was:""); Serial.println(""==========""); Serial.println(line); Serial.println(""==========""); } } void loop() { distance = ultrasonic.Ranging(CM);// CM or INC Serial.print(""Distance:"" ); Serial.print(distance); Serial.println("" cm"" ); delay(100); if (distance < VEHICLE_RANG) { inRange = true; //recheck distance // anti noise for (int i = 0; i < 5; i++) { distance = ultrasonic.Ranging(CM);// CM or INC if (distance >= VEHICLE_RANG) { inRange = false; break; } } } if (inRange != lastState) { Serial.print(""In Range:"" ); Serial.print(inRange); lastState = inRange; updateDistance(); //Push notifycation sendToGCM(); } else { long now = millis(); if (now - lastMsg > 30000) {//every 30 seconds Serial.print(""Update every:"" ); lastMsg = now; updateDistance(); } } } ",cnt 73," #include #include ""DecisionHelper.h"" int main() { std::vector criteria = {""coût"", ""temps"", ""bénéfice""}; std::vector weights = {0.4, 0.3, 0.3}; DecisionHelper decisionHelper(criteria, weights); std::vector values(criteria.size()); std::cout << ""Entrez les valeurs pour les critères suivants:"" << std::endl; for (size_t i = 0; i < criteria.size(); ++i) { std::cout << criteria[i] << "": ""; std::cin >> values[i]; } decisionHelper.setCriteriaValues(values); decisionHelper.calculateScore(); double [MASK] ; std::cout << ""Entrez le seuil de décision: ""; std::cin >> [MASK] ; std::string decision = decisionHelper.makeDecision( [MASK] ); std::cout << ""La décision est: "" << decision << std::endl; return 0; }",threshold 74,"/* 07/2023 PROJECT 1 SNHU CS */ #include #include ""extra.h"" /*Establishes the clock variables which we will be interacting with to declare value and the make user inputted changes*/ Clock::Clock(int h, int m, int sec) : h(h), m(m), sec(sec) {} void Clock::minadd() { m++; if (m >= 60) { m = 0; houradd(); } } void Clock::secadd() { sec++; if (sec >= 60) { sec = 0; minadd(); } } void Clock::houradd() { h = (h + 1) % 24; } /*Declares the format of the 12 hour clock*/ string Clock::h12form() const { int hours12 = (h % 12 == 0) ? 12 : h % 12; string period = (h >= 12) ? ""am"" : ""pm""; stringstream ss; ss << form(hours12) << "":"" << form(m) << "":"" << form(sec) << "" "" << period; return ss.str(); } string Clock::form(int [MASK] ) const { if ( [MASK] < 10) { return ""0"" + to_string( [MASK] ); } return to_string( [MASK] ); } /*declares the 24 hour clock format*/ string Clock::h24form() const { stringstream ss; ss << form(h) << "":"" << form(m) << "":"" << form(sec); return ss.str(); } /* _ | | | |__ ___ | '_ \ / __| | |_) | (__ |_.__/ \___| */",number 75,"#include ""pch.hpp"" #include ""plugins.hpp"" #include ""utility/unused.hpp"" namespace CBSW::Unit { class PluginChainFinal: public PluginNextHandler { public: PluginChainFinal(PluginFinal& final): _final(final) {} int next(Arguments& arguments) noexcept { unused(arguments); return _final.finalPluginFunction(); } private: PluginFinal& _final; }; class PluginChainWrapper: public PluginNextHandler { public: PluginChainWrapper(Plugin& plugin, PluginNextHandler& next): _plugin(plugin), _next(next) {} int next(Arguments& arguments) noexcept { return _plugin.initialise(arguments, _next); } private: Plugin &_plugin; PluginNextHandler& _next; }; int Plugins::run(Arguments& arguments, PluginFinal& final) { std::list nextHandlers; PluginChainFinal* finalChain = new PluginChainFinal(final); PluginNextHandler* next = finalChain; nextHandlers.push_back(finalChain); //construct in reverse order for (auto plugin: _plugins) { PluginNextHandler* nextHandler = new PluginChainWrapper(*plugin, *next); next = nextHandler; nextHandlers.push_back(nextHandler); } //now next contains the first plugin in the chain int [MASK] = next->next(arguments); for (PluginNextHandler* handler: nextHandlers) { delete handler; } return [MASK] ; } void Plugins::registerPlugin(Plugin& plugin) { _plugins.push_back(&plugin); } }",output 76,"#include #include #include #include #include #include #include static std::string check_the_check(); static std::string check_the_check(std::string data); static std::string check_the_check(std::vector data); enum class Color { Black, White }; static Color oposite_color(Color c) { return (c == Color::White ? Color::Black : Color::White); } struct Pair { Pair(int xx, int yy) : x(xx), y(yy) {} int x; int y; }; struct Figure { Figure(int x, int y, Color color) : m_color(color), m_x(x), m_y(y) {} virtual ~Figure(){} bool is_king() { return false; } // FIXME m_horse bool is_horseman() { return m_horse; } //auto position() const { return std::make_tuple(m_x, m_y); } std::tuple position() const { return std::make_tuple(m_x, m_y); } virtual bool can_check(int kingx, int kingy) = 0; Color m_color; int m_x; int m_y; bool m_horse = false; }; struct King: public Figure { King(int x, int y, Color color) : Figure(x, y, color) { } bool is_king() { return true; } bool can_check(int kingx, int kingy) override { return (abs(m_x - kingx) <= 1 && abs(m_y - kingy) <= 1); } }; struct Knight: public Figure { Knight(int x, int y, Color color) : Figure(x, y, color){} bool is_horseman() { return true; } bool can_check(int, int) override { return false; } }; struct Bischop: public Figure { Bischop(int x, int y, Color color) : Figure(x, y, color){} bool can_check(int kingx, int kingy) override { return (abs(m_x - kingx) == abs(m_y - kingy)); } }; struct Rook: public Figure { Rook(int x, int y, Color color) : Figure(x, y, color){} bool can_check(int kingx, int kingy) override { return (m_x == kingx || m_y == kingy); } }; struct Queen: public Figure { Queen(int x, int y, Color color) : Figure(x, y, color){} bool can_check(int kingx, int kingy) override { return (abs(m_x - kingx) == abs(m_y - kingy) || m_x == kingx || m_y == kingy); } }; struct Pawn: public Figure { Pawn(int x, int y, Color color) : Figure(x, y, color){} bool can_check(int kingx, int kingy) override { if (m_color == Color::White && m_y < kingy) { return false; } if (m_color == Color::Black && m_y > kingy) { return false; } return ( (kingx == m_x - 1 || kingx == m_x + 1) && (kingy == m_y - 1 or kingy == m_y + 1) ); } }; struct Board { // FIXME Board(int x, int y) : stdin_input(true), m_game_counter(-1), m_size(x, y) { figures = std::vector(static_cast(x*y), nullptr); } ~Board() { for (auto& figure : figures) { delete figure; } } void Clean() { for (auto& figure : figures) { delete figure; } figures = std::vector(static_cast(m_size.x * m_size.y), nullptr); wKing = nullptr; bKing = nullptr; } bool load(std::string data) { m_data = data; return load_nostdin(); } // bool load(std::vector data) // { // m_data = std::accumulate(data.begin(), data.end(), std::string("""")); // return load_nostdin(); // } bool load_nostdin() { stdin_input = false; return load(); } // FIXME -fuj dvoji logika paralelne ss/cin bool load() { m_game_counter++; std::stringstream ss; if (!stdin_input) { ss.str(m_data); } if (stdin_input && std::cin.eof()) { return false; } figures = std::vector( static_cast(m_size.x * m_size.y), nullptr ); int j = 0; for (std::string line; std::getline(stdin_input ? std::cin : ss, line);) { if (stdin_input && std::cin.eof()) return false; // client input, only one scenario (board) if (!stdin_input && line == """") return false; if (line == """") return true; int i = 0; for (auto x : line) { if (x != '\n' || x != '.') { Figure* figure = nullptr; switch (x) { case 'K': figure = new King(i, j, Color::White); wKing = figure; break; case 'k': figure = new King(i, j, Color::Black); bKing = figure; break; case 'Q': figure = new Queen(i, j, Color::White); break; case 'q': figure = new Queen(i, j, Color::Black); break; case 'R': figure = new Rook(i, j, Color::White); break; case 'r': figure = new Rook(i, j, Color::Black); break; case 'B': figure = new Bischop(i, j, Color::White); break; case 'b': figure = new Bischop(i, j, Color::Black); break; // FIXME, i dont udenrstand OOP i guess case 'N': figure = new Knight(i, j, Color::White); figure->m_horse = true; break; case 'n': figure = new Knight(i, j, Color::Black); figure->m_horse = true; break; case 'P': figure = new Pawn(i, j, Color::White); break; case 'p': figure = new Pawn(i, j, Color::Black); break; } figures.at(static_cast(j * m_size.x + i)) = figure; } i++; } j++; } return true; } bool in_board(int x, int y) { return (x < m_size.x && x >= 0) && (y < m_size.y && y >= 0); } bool check_check(Color color, bool* empty) { if (color == Color::White && wKing == nullptr) { *empty = true; return false; } if (color == Color::Black && bKing == nullptr) { *empty = true; return false; } return false || check_horsemen(color) || check_in_directions(color); } bool check_horsemen(Color color) { auto f = color == Color::White ? wKing : bKing; //auto [x, y] = f->position(); auto x = f->m_x; // std::get<0>(f->position()); auto y = f->m_y; // std::get<1>(f->position()); std::vector> shifts = { {-2, -1}, {-1, -2}, {-2, 1}, {-1, 2}, {2, -1}, {1, -2}, {2, 1}, {1, 2}, }; for (unsigned int i = 0; i < 8; i++) { //auto [x1, y1] = shifts[i]; auto x1 = std::get<0>(shifts[i]); auto y1 = std::get<1>(shifts[i]); if (in_board(x + x1, y + y1)) { Figure* figure = figures.at((static_cast((y + y1) * m_size.x) + static_cast(x + x1))); if (figure != nullptr) { if ((figure->m_color == oposite_color(color)) && figure->is_horseman()) { return true; } } } } return false; } bool check_in_directions(Color color) { bool ret = false; for (int i = -1; i < 2; i++) { for (int j = - 1; j < 2; j++) { if (i || j) { ret = ret || check_in_direction(color, i, j); } } } return ret; } bool check_in_direction(Color color, int i, int j) { auto f = color == Color::White ? wKing : bKing; //auto [x, y] = f->position(); auto x = std::get<0>(f->position()); auto y = std::get<1>(f->position()); bool [MASK] = true; while ( [MASK] ) { Figure* figure = figures.at(static_cast(y * (m_size.y)) + static_cast(x)); if (figure != nullptr && (x != f->m_x || y != f->m_y)) { if (figure->can_check(f->m_x, f->m_y) && (figure->m_color == (color == Color::White ? Color::Black : Color::White))) { return true; } return false; } x += i; y += j; [MASK] = in_board(x, y); } return false; } bool stdin_input; int m_game_counter; Pair m_size; std::vector figures; std::string m_data; Figure* wKing = nullptr; Figure* bKing = nullptr; }; static std::string solve_problem(Board& board) { std::string output; bool wEmpty = false; bool bEmpty = false; bool a = true; while (a) { bool white = board.check_check(Color::White, &wEmpty); bool black = board.check_check(Color::Black, &bEmpty); if (!wEmpty || !bEmpty) { output += ""Game #"" + std::to_string(board.m_game_counter + 1) + "": ""; if (white) { output += ""white""; } if (black) { output += ""black""; } if (!white && !black) { output += ""no""; } output += "" king is in check.\n""; } board.Clean(); a = board.load(); wEmpty = false; bEmpty = false; } //std::cout << ""DEBUG:\n"" << output << '\n'; return output; } static std::string check_the_check() { Board board = Board(8, 8); [[maybe_unused]] bool a = board.load(); std::string out = solve_problem(board); std::cout << out; // << '\n'; return out; } static std::string check_the_check(std::string data) { Board board = Board(8, 8); [[maybe_unused]] bool a = board.load(data); return solve_problem(board); } // static std::string check_the_check(std::vector data) // { // Board board = Board(8, 8); // [[maybe_unused]] bool a = board.load(data); // // return solve_problem(board); // } ",keep_finding 77,"#include ""../src/Common.h"" #include ""../src/Context.h"" #include using std::vector; using std::cout; using std::endl; int main(int argc, char *argv[], char *env[]) { vector items{ Item{""E"", ItemType::NoTerminal}, Item{""E_"", ItemType::NoTerminal}, Item{""T"", ItemType::NoTerminal}, Item{""T_"", ItemType::NoTerminal}, Item{""F"", ItemType::NoTerminal}, Item{""^"", ItemType::Terminal}, Item{""+"", ItemType::Terminal}, Item{""*"", ItemType::Terminal}, Item{""("", ItemType::Terminal}, Item{"")"", ItemType::Terminal}, Item{""i"", ItemType::Terminal}, }; auto &E = items[0]; auto &E_ = items[1]; auto &T = items[2]; auto &T_ = items[3]; auto &F = items[4]; auto &empty = items[5]; auto &plus = items[6]; auto &star = items[7]; auto &left = items[8]; auto &right = items[9]; auto &i = items[10]; vector grammar{ Production{E, vector{T, E_}}, Production{E_, vector{plus, T, E_}}, Production{E_, vector{empty}}, Production{T, vector{F, T_}}, Production{T_, vector{star, F, T_}}, Production{T_, vector{empty}}, Production{F, vector{left, E, right}}, Production{F, vector{i}}, }; Context [MASK] {grammar, grammar[0]}; cout << ""--- the grammar is ---"" << endl; [MASK] .printGrammar(); [MASK] .first(); cout << ""--- the first set is ---"" << endl; [MASK] .printFirst(); [MASK] .follow(); cout << ""--- the follow set is ---"" << endl; [MASK] .printFollow(); return 0; } ",context 78,"/*** * @Author: Heng * @Date: 2022-10-27 03:51:31 * @LastEditTime: 2022-10-27 03:51:44 * @LastEditors: Heng * @Description: * @FilePath: /DataStructure/分治/最大连续子序列和.cpp * @Heng */ #include using namespace std; #include #include class Solution { public: /*** * @description: 暴力求解 * @param {vector} &nums * @return {*} */ int maxSubArray0(vector &nums) { int res = INT_MIN; for (int begin = 0; begin < nums.size(); begin++) { int tmp = 0; for (int end = begin; end < nums.size(); end++) { tmp += nums[end]; res = max(tmp, res); } } return res; } /*** * @description: 分治算法 * @param {vector} &nums * @return {*} */ int maxSubArray1(vector &nums) { if (nums.size() == 1) { return nums[0]; } return this->maxSubArray1(nums, 0, nums.size()); } /*** * @description: 求[begin, end) 的最大连续子序列和 * @param {vector} &nums * @param {int} begin * @param {int} end * @return {*} */ int maxSubArray1(vector &nums, int begin, int end) { // 递归基 if (end - begin < 2) return nums[begin]; int mid = (begin + end) >> 1; // 左边 int leftMax = this->maxSubArray1(nums, begin, mid); // 右边 int rightMax = this->maxSubArray1(nums, mid, end); // 中间 // 中左 int leftMidMax = INT_MIN; int left_sum = 0; for (int i = mid - 1; i >= begin; i--) { left_sum += nums[i]; leftMidMax = max(left_sum, leftMidMax); } // 中右 int rightMidMax = INT_MIN; int right_sum = 0; for (int i = mid; i < end; i++) { right_sum += nums[i]; rightMidMax = max(right_sum, rightMidMax); } int [MASK] = leftMidMax + rightMidMax; return max( [MASK] , max(leftMax, rightMax)); } }; int main(int argc, char const *argv[]) { Solution s = Solution(); vector nums{-2, 1, -3, 4, -1, 2, 1, -5, 4}; int res = s.maxSubArray1(nums); cout << res << endl; return 0; }",mid_max 79,"#include #include #include #include #include #include #include #include #include #include ""command_line_arguments.hpp"" namespace bfc { namespace { constexpr int maximumArgumentCount{2}; struct transpile { }; struct dummy { }; [[nodiscard]] std::variant secondOption( int actualArgumentCount, char** argv) { constexpr int compilerTranspilationIndex{2}; if (actualArgumentCount == maximumArgumentCount) { const char* const option{argv[compilerTranspilationIndex]}; if (std::strcmp(option, ""--transpile"") == 0) { return transpile{}; } constexpr pl::string_view compilerOptionBegin{""--compiler=""}; pl::string_view optionStringView{option}; if (optionStringView.starts_with(compilerOptionBegin)) { optionStringView.remove_prefix(compilerOptionBegin.size()); return optionStringView.to_string(); } return Expected{ BFC_UNEXPECTED( Error::InvalidArgument, fmt::format(""\""{}\"" could not be parsed."", option))} .error(); } else { using namespace std::string_literals; #if PL_OS == PL_OS_LINUX return ""/usr/bin/cc""s; #elif PL_OS == PL_OS_WINDOWS return ""cl.exe""s; #else #error ""Unsupporetd operating system!"" #endif } } struct [[nodiscard]] Result { std::string compilerPath; bool isJustTranspilation; }; } // namespace Expected CommandLineArguments::parse( int argc, char** argv) { constexpr int argumentCountOffset{1}; const int actualArgumentCount{argc - argumentCountOffset}; constexpr int [MASK] {1}; if (!pl::is_between( actualArgumentCount, [MASK] , maximumArgumentCount)) { return BFC_UNEXPECTED( Error::InvalidArgument, fmt::format( ""{} command line arguments were given but at least {} and at most {} "" ""were expected."", actualArgumentCount, [MASK] , maximumArgumentCount)); } constexpr int inputFileIndex{1}; const char* const inputFilePath{argv[inputFileIndex]}; const std::variant secondOptionResult{ secondOption(actualArgumentCount, argv)}; Expected expectedResult{std::visit( pl::overload( [](const std::string& compilerPath) { return Expected{Result{compilerPath, false}}; }, [](transpile) { return Expected{Result{"""", true}}; }, [](const Error& error) -> Expected { return tl::make_unexpected(error); }), secondOptionResult)}; if (!expectedResult.has_value()) { return tl::make_unexpected(expectedResult.error()); } Result& result{expectedResult.value()}; return CommandLineArguments{ std::string{inputFilePath}, std::move(result.compilerPath), result.isJustTranspilation}; } void CommandLineArguments::printHelp(const char* thisApp, std::ostream& os) { fmt::print( os, ""Usage: {} [-h] brainfuck_source_file [--compiler=COMPILER] "" ""[--transpile]\n"", thisApp); fmt::print(os, ""\n""); fmt::print(os, ""Compiles a brainfuck source file.\n""); fmt::print(os, ""\n""); fmt::print(os, ""positional arguments:\n""); fmt::print( os, "" brainfuck_source_file path to the brainfuck source file to "" ""compile\n""); fmt::print(os, ""\n""); fmt::print(os, ""optional_arguments:\n""); fmt::print( os, "" -h, --help show this help message and exit\n""); fmt::print(os, "" --compiler=COMPILER the compiler to use\n""); fmt::print( os, "" --transpile transpile to C but don't compile\n""); fmt::print(os, ""\n""); fmt::print(os, ""notes:\n""); fmt::print( os, "" --compiler and --transpile can not be specified at the same time!\n""); os << std::flush; } const std::string& CommandLineArguments::inputFilePath() const noexcept { return m_inputFilePath; } const std::string& CommandLineArguments::compiler() const noexcept { return m_compiler; } bool CommandLineArguments::shouldJustTranspile() const noexcept { return m_shouldJustTranspile; } CommandLineArguments::CommandLineArguments( std::string&& inputFilePath, std::string&& compiler, bool shouldJustTranspile) noexcept : m_inputFilePath{std::move(inputFilePath)} , m_compiler{std::move(compiler)} , m_shouldJustTranspile{shouldJustTranspile} { } } // namespace bfc ",minimumArgumentCount 80,"#include ""server.h"" ServerNetwork::ServerNetwork(unsigned short port = 53000) : m_listenport(port) { if (listener.listen(m_listenport) != sf::Socket::Done) { log(""Could not listen Try another port number: ""); } } void ServerNetwork::ConnectClients(std::vector* client_array) { while (true) { sf::TcpSocket* new_client = new sf::TcpSocket(); if (listener.accept(*new_client) == sf::Socket::Done) { new_client->setBlocking(false); client_array->push_back(new_client); log(""Connect client "" << new_client->getRemoteAddress() << "":"" << new_client->getRemotePort()); //////////send B AND W to the player//////////// if(m_nbrplayer < 2){ sf::Packet packet; std::string playerflag; if (m_nbrplayer == 0) { playerflag = ""W""; packet << playerflag; if (new_client->send(packet) != sf::Socket::Done) { log(""Could not send packet to player B""); } } else { playerflag = ""B""; packet << playerflag; if (new_client->send(packet) != sf::Socket::Done) { log(""Could not send packet to player W""); } } m_nbrplayer++; } else { sf::Packet packet; char playerflag = 'G'; packet << playerflag; for (int i = 0; i < 10; i++) { packet << m_board[i]; } if (new_client->send(packet) != sf::Socket::Done) { log(""Could not send packet to player G""); } } } else { log(""ERROR: restart the server""); delete(new_client); break; } } } void ServerNetwork::DisconnectClient(sf::TcpSocket* socket_pointer, size_t position) { log(""Client disconnected :"" << socket_pointer->getRemoteAddress()); socket_pointer->disconnect(); delete(socket_pointer); client_array.erase(client_array.begin() + position); } void ServerNetwork::BroadcastPacket(sf::Packet& packet, sf::IpAddress exclude_address, unsigned short port) { for (size_t iterator = 0; iterator < client_array.size(); iterator++) { sf::TcpSocket* client = client_array[iterator]; if (client->getRemoteAddress() != exclude_address || client->getRemotePort() != port) { if (client->send(packet) != sf::Socket::Done) { log(""Could not send packet on broadcast""); } } } } void ServerNetwork::ReceivePacket(sf::TcpSocket* client, size_t iterator) { sf::Packet packet; if (client->receive(packet) == sf::Socket::Disconnected) { DisconnectClient(client, iterator); } else { if (packet.getDataSize() > 0) { BroadcastPacket(packet, client->getRemoteAddress(), client->getRemotePort()); std::string received_message; packet >> received_message; log(client->getRemoteAddress().toString() << "":"" << client->getRemotePort() << "" - "" << received_message << "";""); } } } void ServerNetwork::ManagePackets() { while (true) { for (size_t it = 0; it < client_array.size(); it++) { ReceivePacket(client_array[it], it); } std::this_thread::sleep_for((std::chrono::milliseconds)100); } } int ServerNetwork::readflagindex(short int flag)const { int [MASK] = flag; return ( [MASK] % 1000) / 10; } void ServerNetwork::putflagboard(short int flag) { m_board[readflagindex(flag)] = flag; } void ServerNetwork::Run() { std::thread connetion_thread(&ServerNetwork::ConnectClients, this, &client_array); ManagePackets(); } ",iflag 81,"#pragma once #include // uint64_t #include // unique_ptr #include #include #include #include namespace cfp { using ElementCountDict = std::unordered_map; /** * @brief Abstract base for AST nodes. */ struct Node { virtual ~Node() = default; /** * @brief Evaluate a node into an element-count map. * @param out Map to accumulate into. * @param mult Multiplier from parent groups. */ virtual void evaluate(ElementCountDict &out, uint64_t mult) const = 0; }; /** * @brief Leaf: a single element symbol with count. */ struct ElementNode final : Node { std::string symbol; uint64_t count{1}; explicit ElementNode(std::string_view sym, uint64_t count) : symbol{sym}, count{count} {} void evaluate(ElementCountDict &out, uint64_t mult) const override { out[symbol] += count * mult; } }; /** * @brief Interior node: a group of children, with a multiplier. * * Example: ""(SO4)3"" produces a GroupNode with * children = { ElementNode{""S"", 1}, ElementNode{""O"", 4} } * multiplier = 3 */ struct GroupNode final : Node { std::vector> children; uint64_t multiplier{1}; explicit GroupNode(uint64_t mult = 1) : multiplier{mult} {} void evaluate(ElementCountDict &out, uint64_t mult) const override { const uint64_t [MASK] = mult * multiplier; for (const auto &child : children) { child->evaluate(out, [MASK] ); } } }; } // namespace cfp ",next_mult 82,"// Copyright (C) 2024 <> // // SPDX-License-Identifier: MIT #include ""hictkpy/cooler_file_writer.hpp"" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ""hictkpy/bin_table.hpp"" #include ""hictkpy/common.hpp"" #include ""hictkpy/nanobind.hpp"" #include ""hictkpy/pixel.hpp"" #include ""hictkpy/reference.hpp"" #include ""hictkpy/type.hpp"" namespace nb = nanobind; namespace hictkpy { CoolerFileWriter::CoolerFileWriter(std::filesystem::path path_, const hictkpy::BinTable &bins_, std::string_view assembly, const std::filesystem::path &tmpdir, std::uint32_t compression_lvl) : _path(std::move(path_)), _tmpdir(tmpdir, true), _w(create_file(_path.string(), *bins_.get(), assembly, _tmpdir())), _compression_lvl(compression_lvl) { if (std::filesystem::exists(_path)) { throw std::runtime_error( fmt::format(FMT_STRING(""unable to create .cool file \""{}\"": file already exists""), path())); } SPDLOG_INFO(FMT_STRING(""using \""{}\"" folder to store temporary file(s)""), _tmpdir()); } CoolerFileWriter::CoolerFileWriter(std::filesystem::path path_, const ChromosomeDict &chromosomes_, std::uint32_t resolution_, std::string_view assembly, const std::filesystem::path &tmpdir, std::uint32_t compression_lvl) : CoolerFileWriter(std::move(path_), BinTable{chromosomes_, resolution_}, assembly, tmpdir, compression_lvl) {} const std::filesystem::path &CoolerFileWriter::path() const noexcept { return _path; } std::uint32_t CoolerFileWriter::resolution() const noexcept { if (_w.has_value()) { return _w->resolution(); } return 0; } const hictk::Reference &CoolerFileWriter::chromosomes() const { if (_w.has_value()) { return _w->chromosomes(); } const static hictk::Reference ref{}; return ref; } std::shared_ptr CoolerFileWriter::bins_ptr() const noexcept { if (!_w) { return {}; } return _w->bins_ptr(); } void CoolerFileWriter::add_pixels(const nb::object &df, bool sorted, bool validate) { if (!_w.has_value()) { throw std::runtime_error( ""caught attempt to add_pixels to a .cool file that has already been finalized!""); } const auto cell_id = fmt::to_string(_w->cells().size()); auto attrs = hictk::cooler::Attributes::init(_w->resolution()); attrs.assembly = _w->attributes().assembly; auto lck = std::make_optional(); const auto coo_format = nb::cast(df.attr(""columns"").attr(""__contains__"")(""bin1_id"")); const auto dtype = df.attr(""__getitem__"")(""count"").attr(""dtype""); const auto dtype_str = nb::cast(dtype.attr(""__str__"")()); const auto var = map_py_numeric_to_cpp_type(dtype_str); std::visit( [&](const auto &n) { using N = remove_cvref_t; const auto pixels = coo_format ? coo_df_to_thin_pixels(df, !sorted) : bg2_df_to_thin_pixels(_w->bins(), df, !sorted); lck.reset(); auto clr = _w->create_cell(cell_id, std::move(attrs), hictk::cooler::DEFAULT_HDF5_CACHE_SIZE * 4, 1); SPDLOG_INFO(FMT_STRING(""adding {} pixels of type {} to file \""{}\""...""), pixels.size(), dtype_str, clr.uri()); clr.append_pixels(pixels.begin(), pixels.end(), validate); clr.flush(); }, var); } hictk::File CoolerFileWriter::finalize(std::string_view log_lvl_str, std::size_t chunk_size, std::size_t update_freq) { if (_finalized) { throw std::runtime_error( fmt::format(FMT_STRING(""finalize() was already called on file \""{}\""""), _path)); } if (chunk_size == 0) { throw std::runtime_error(""chunk_size must be greater than 0""); } assert(_w.has_value()); // NOLINTBEGIN(*-unchecked-optional-access) const auto log_lvl = spdlog::level::from_str(normalize_log_lvl(log_lvl_str)); const auto previous_lvl = spdlog::default_logger()->level(); spdlog::default_logger()->set_level(log_lvl); SPDLOG_INFO(FMT_STRING(""finalizing file \""{}\""...""), _path); hictk::internal::NumericVariant [MASK] {}; if (_w->cells().empty()) { [MASK] = std::int32_t{}; } else { [MASK] = _w->open(""0"").pixel_variant(); } try { std::visit( [&](const auto &num) { using N = remove_cvref_t; _w->aggregate(_path.string(), false, _compression_lvl, chunk_size, update_freq); }, [MASK] ); } catch (...) { spdlog::default_logger()->set_level(previous_lvl); throw; } _finalized = true; SPDLOG_INFO(FMT_STRING(""merged {} cooler(s) into file \""{}\""""), _w->cells().size(), _path); spdlog::default_logger()->set_level(previous_lvl); const std::string sclr_path{_w->path()}; _w.reset(); std::filesystem::remove(sclr_path); // NOLINT // NOLINTEND(*-unchecked-optional-access) return hictk::File{_path.string()}; } hictk::cooler::SingleCellFile CoolerFileWriter::create_file(std::string_view path, const hictk::BinTable &bins, std::string_view assembly, const std::filesystem::path &tmpdir) { auto attrs = hictk::cooler::SingleCellAttributes::init(bins.resolution()); attrs.assembly = assembly; return hictk::cooler::SingleCellFile::create(tmpdir / std::filesystem::path{path}.filename(), bins, false, std::move(attrs)); } std::string CoolerFileWriter::repr() const { if (!_w.has_value()) { return ""CoolFileWriter()""; } return fmt::format(FMT_STRING(""CoolFileWriter({})""), _w->path()); } void CoolerFileWriter::bind(nb::module_ &m) { auto cooler = m.def_submodule(""cooler""); auto writer = nb::class_( cooler, ""FileWriter"", ""Class representing a file handle to create .cool files.""); // NOLINTBEGIN(*-avoid-magic-numbers) writer.def(nb::init(), nb::arg(""path""), nb::arg(""chromosomes""), nb::arg(""resolution""), nb::arg(""assembly"") = ""unknown"", nb::arg(""tmpdir"") = hictk::internal::TmpDir::default_temp_directory_path(), nb::arg(""compression_lvl"") = 6, ""Open a .cool file for writing given a list of chromosomes with their sizes and a "" ""resolution.""); writer.def(nb::init(), nb::arg(""path""), nb::arg(""bins""), nb::arg(""assembly"") = ""unknown"", nb::arg(""tmpdir"") = hictk::internal::TmpDir::default_temp_directory_path(), nb::arg(""compression_lvl"") = 6, ""Open a .cool file for writing given a table of bins.""); // NOLINTEND(*-avoid-magic-numbers) writer.def(""__repr__"", &hictkpy::CoolerFileWriter::repr, nb::rv_policy::move); writer.def(""path"", &hictkpy::CoolerFileWriter::path, ""Get the file path."", nb::rv_policy::copy); writer.def(""resolution"", &hictkpy::CoolerFileWriter::resolution, ""Get the resolution in bp.""); writer.def(""chromosomes"", &get_chromosomes_from_object, nb::arg(""include_ALL"") = false, ""Get the chromosome sizes as a dictionary mapping names to sizes."", nb::rv_policy::take_ownership); writer.def(""bins"", &get_bins_from_object, ""Get table of bins."", nb::sig(""def bins(self) -> hictkpy.BinTable""), nb::rv_policy::move); writer.def(""add_pixels"", &hictkpy::CoolerFileWriter::add_pixels, nb::call_guard(), nb::sig(""def add_pixels(self, pixels: pandas.DataFrame, sorted: bool = False, "" ""validate: bool = True) -> None""), nb::arg(""pixels""), nb::arg(""sorted"") = false, nb::arg(""validate"") = true, ""Add pixels from a pandas DataFrame containing pixels in COO or BG2 format (i.e. "" ""either with columns=[bin1_id, bin2_id, count] or with columns=[chrom1, start1, end1, "" ""chrom2, start2, end2, count].\n"" ""When sorted is True, pixels are assumed to be sorted by their genomic coordinates in "" ""ascending order.\n"" ""When validate is True, hictkpy will perform some basic sanity checks on the given "" ""pixels before adding them to the Cooler file.""); // NOLINTBEGIN(*-avoid-magic-numbers) writer.def(""finalize"", &hictkpy::CoolerFileWriter::finalize, nb::call_guard(), nb::arg(""log_lvl"") = ""WARN"", nb::arg(""chunk_size"") = 500'000, nb::arg(""update_frequency"") = 10'000'000, ""Write interactions to file."", nb::rv_policy::move); // NOLINTEND(*-avoid-magic-numbers) } } // namespace hictkpy ",count_type 83," // Copyright 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #include #include #include #include #include #include #include #include #include using namespace coruja; int main(int argc, char** argv) { QApplication app(argc, argv); QDialog window; QVBoxLayout [MASK] (&window); QCheckBox qcheckbox(&window); QTextEdit qtextedit(&window); [MASK] .addWidget(&qcheckbox); [MASK] .addWidget(&qtextedit); object model{false}; model.for_each([](bool v) { std::cout << ""checkbox is "" << (v ? ""true"" : ""false"") << std::endl; }); saci::qt::checkbox checkbox(model, qcheckbox); object name{""Clear this text to disable the checkbox""}; name.for_each([](std::string s) { std::cout << ""name is '"" << s << ""'"" << std::endl; }); saci::qt::textedit textedit(name, qtextedit); window.show(); checkbox.enable(view::transform(name, [](std::string s){ return !s.empty(); })); model = true; return app.exec(); } ",layout 84,"#include #include #include using namespace std; int main() { bool flag = false; int col; int rows = 2; stack st; stack [MASK] ; int n1; int n2; string str; string str1; string postfix; string postfix1; char num1; char num2; char num3; char num4; char num5; char table[2] = { '0','1' }; char result[2]; char table1[4][2] = { {'0','0'},{'0','1'},{'1','0'},{'1','1'} }; char result1[4]; char table2[8][3] = { {'0','0','0'},{'0','0','1'},{'0','1','0'},{'0','1','1'},{'1','0','0'},{'1','0','1'},{'1','1','0'},{'1','1','1'} }; char result2[8]; char table3[16][4] = { {'0','0','0','0'},{'0','0','0','1'},{'0','0','1','0'},{'0','0','1','1'},{'0','1','0','0'},{'0','1','0','1'},{'0','1','1','0'},{'0','1','1','1'}, {'1','0','0','0'},{'1','0','0','1'},{'1','0','1','0'},{'1','0','1','1'},{'1','1','0','0'},{'1','1','0','1'},{'1','1','1','0'},{'1','1','1','1'} }; char result3[16]; char table4[32][5] = { {'0','0','0','0','0'},{'0','0','0','0','1'},{'0','0','0','1','0'},{'0','0','0','1','1'},{'0','0','1','0','0'},{'0','0','1','0','1'}, {'0','0','1','1','0'},{'0','0','1','1','1'},{'0','1','0','0','0'},{'0','1','0','0','1'},{'0','1','0','1','0'},{'0','1','0','1','1'},{'0','1','1','0','0'}, {'0','1','1','0','1'}, {'0','1','1','1','0'},{'0','1','1','1','1'},{'1','0','0','0','0'},{'1','0','0','0','1'},{'1','0','0','1','0'}, {'1','0','0','1','1'},{'1','0','1','0','0'},{'1','0','1','0','1'},{'1','0','1','1','0'},{'1','0','1','1','1'},{'1','1','0','0','0'}, {'1','1','0','0','1'},{'1','1','0','1','0'},{'1','1','0','1','1'},{'1','1','1','0','0'},{'1','1','1','0','1'},{'1','1','1','1','0'}, {'1','1','1','1','1'} }; char result4[32]; cout << ""Enter the string: ""; getline(cin, str); cout << endl; for (int i = 0; i < str.size(); i++) { if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) { flag = false; for (int j = 0; j < str1.size(); j++) { if (str[i] == str1[j]) { flag = true; } } if (flag == false) { str1 = str1 + str[i]; } } } if (str1.size() == 1) { rows = 2; } else { for (int i = 0; i < str1.size() - 1; i++) { rows = rows * 2; } } col = str1.size(); for (int i = 0; i < str.length(); i++) { if ((str[i] >= 'a' && str[i] <= 'z')) { postfix = postfix + str[i]; } else if (str[i] == '(') { st.push('('); } else if (str[i] == ')') { while (st.top() != '(') { postfix = postfix + st.top(); st.pop(); } st.pop(); } else if (str[i] == '~') { st.push('~'); } else if (str[i] == '*') { if (st.empty()) { st.push('*'); } else if (st.top() == '~') { postfix = postfix + '~'; st.pop(); st.push('*'); } else { st.push('*'); } } else if (str[i] == '+') { if (st.empty()) { st.push('+'); } else if (st.top() == '~') { postfix = postfix + '~'; st.pop(); st.push('+'); } else if (st.top() == '*') { postfix = postfix + '*'; st.pop(); st.push('+'); } else { st.push('+'); } } } while (!st.empty()) { postfix = postfix + st.top(); st.pop(); } postfix1 = postfix; switch (col) { case 1: for (int i = 0; i < rows; i++) { num1 = table[i]; for (int i = 0; i < postfix.size(); i++) //assigning values in equation { if (postfix[i] >= 'a' && postfix[i] <= 'z') { postfix[i] = num1; } } for (int i = 0; i < postfix.size(); i++) //evaluating equation { if (postfix[i] == '0' || postfix[i] == '1') { n1 = postfix[i] - 48; [MASK] .push(n1); } else if (postfix[i] == '~') { if ( [MASK] .top() == 0) { [MASK] .pop(); [MASK] .push(1); } else { [MASK] .pop(); [MASK] .push(0); } } else if (postfix[i] == '*') { n1 = [MASK] .top(); [MASK] .pop(); n2 = [MASK] .top(); [MASK] .pop(); if (n1 && n2) { [MASK] .push(1); } else { [MASK] .push(0); } } else if (postfix[i] == '+') { n1 = [MASK] .top(); [MASK] .pop(); n2 = [MASK] .top(); [MASK] .pop(); if (n1 || n2) { [MASK] .push(1); } else { [MASK] .push(0); } } } result[i] = [MASK] .top() + 48; [MASK] .pop(); postfix = postfix1; } cout << ""Table: "" << endl << endl; cout << ""a "" << str << endl; for (int i = 0; i < rows; i++) { cout << table[i] << "" ""; cout << "" "" << result[i] << endl; } break; case 2: for (int i = 0; i < rows; i++) { for (int j = 0; j < col; j++) //getting values from truth table { if (j == 0) { num1 = table1[i][j]; } else if (j == 1) { num2 = table1[i][j]; } } for (int i = 0; i < postfix.size(); i++) //assigning values in equation { if (postfix[i] == 'a') { postfix[i] = num1; } else if (postfix[i] == 'b') { postfix[i] = num2; } } for (int i = 0; i < postfix.size(); i++) //evaluating equation { if (postfix[i] == '0' || postfix[i] == '1') { n1 = postfix[i] - 48; [MASK] .push(n1); } else if (postfix[i] == '~') { if ( [MASK] .top() == 0) { [MASK] .pop(); [MASK] .push(1); } else { [MASK] .pop(); [MASK] .push(0); } } else if (postfix[i] == '*') { n1 = [MASK] .top(); [MASK] .pop(); n2 = [MASK] .top(); [MASK] .pop(); if (n1 && n2) { [MASK] .push(1); } else { [MASK] .push(0); } } else if (postfix[i] == '+') { n1 = [MASK] .top(); [MASK] .pop(); n2 = [MASK] .top(); [MASK] .pop(); if (n1 || n2) { [MASK] .push(1); } else { [MASK] .push(0); } } } result1[i] = [MASK] .top() + 48; [MASK] .pop(); postfix = postfix1; } cout << ""Table: "" << endl << endl; cout << ""a b "" << str << endl; for (int i = 0; i < rows; i++) { for (int j = 0; j < col; j++) { cout << table1[i][j] << "" ""; } cout << "" "" << result1[i] << endl; } break; case 3: for (int i = 0; i < rows; i++) { for (int j = 0; j < col; j++) //getting values from truth table { if (j == 0) { num1 = table2[i][j]; } else if (j == 1) { num2 = table2[i][j]; } else if (j == 2) { num3 = table2[i][j]; } } for (int i = 0; i < postfix.size(); i++) //assigning values in equation { if (postfix[i] == 'a') { postfix[i] = num1; } else if (postfix[i] == 'b') { postfix[i] = num2; } else if (postfix[i] == 'c') { postfix[i] = num3; } } for (int i = 0; i < postfix.size(); i++) //evaluating equation { if (postfix[i] == '0' || postfix[i] == '1') { n1 = postfix[i] - 48; [MASK] .push(n1); } else if (postfix[i] == '~') { if ( [MASK] .top() == 0) { [MASK] .pop(); [MASK] .push(1); } else { [MASK] .pop(); [MASK] .push(0); } } else if (postfix[i] == '*') { n1 = [MASK] .top(); [MASK] .pop(); n2 = [MASK] .top(); [MASK] .pop(); if (n1 && n2) { [MASK] .push(1); } else { [MASK] .push(0); } } else if (postfix[i] == '+') { n1 = [MASK] .top(); [MASK] .pop(); n2 = [MASK] .top(); [MASK] .pop(); if (n1 || n2) { [MASK] .push(1); } else { [MASK] .push(0); } } } result2[i] = [MASK] .top() + 48; [MASK] .pop(); postfix = postfix1; } cout << ""Table: "" << endl << endl; //printing truth table cout << ""a b c "" << str << endl; for (int i = 0; i < rows; i++) { for (int j = 0; j < col; j++) { cout << table2[i][j] << "" ""; } cout << "" "" << result2[i] << endl; } break; case 4: for (int i = 0; i < rows; i++) { for (int j = 0; j < col; j++) //getting values from truth table { if (j == 0) { num1 = table3[i][j]; } else if (j == 1) { num2 = table3[i][j]; } else if (j == 2) { num3 = table3[i][j]; } else if (j == 3) { num4 = table3[i][j]; } } for (int i = 0; i < postfix.size(); i++) //assigning values in equation { if (postfix[i] == 'a') { postfix[i] = num1; } else if (postfix[i] == 'b') { postfix[i] = num2; } else if (postfix[i] == 'c') { postfix[i] = num3; } else if (postfix[i] == 'd') { postfix[i] = num4; } } for (int i = 0; i < postfix.size(); i++) //evaluating equation { if (postfix[i] == '0' || postfix[i] == '1') { n1 = postfix[i] - 48; [MASK] .push(n1); } else if (postfix[i] == '~') { if ( [MASK] .top() == 0) { [MASK] .pop(); [MASK] .push(1); } else { [MASK] .pop(); [MASK] .push(0); } } else if (postfix[i] == '*') { n1 = [MASK] .top(); [MASK] .pop(); n2 = [MASK] .top(); [MASK] .pop(); if (n1 && n2) { [MASK] .push(1); } else { [MASK] .push(0); } } else if (postfix[i] == '+') { n1 = [MASK] .top(); [MASK] .pop(); n2 = [MASK] .top(); [MASK] .pop(); if (n1 || n2) { [MASK] .push(1); } else { [MASK] .push(0); } } } result3[i] = [MASK] .top() + 48; [MASK] .pop(); postfix = postfix1; } cout << ""Table: "" << endl << endl; //printing truth table cout << ""a b c d "" << str << endl; for (int i = 0; i < rows; i++) { for (int j = 0; j < col; j++) { cout << table3[i][j] << "" ""; } cout << "" "" << result3[i] << endl; } break; case 5: for (int i = 0; i < rows; i++) { for (int j = 0; j < col; j++) //getting values from truth table { if (j == 0) { num1 = table4[i][j]; } else if (j == 1) { num2 = table4[i][j]; } else if (j == 2) { num3 = table4[i][j]; } else if (j == 3) { num4 = table4[i][j]; } else if (j == 4) { num5 = table4[i][j]; } } for (int i = 0; i < postfix.size(); i++) //assigning values in equation { if (postfix[i] == 'a') { postfix[i] = num1; } else if (postfix[i] == 'b') { postfix[i] = num2; } else if (postfix[i] == 'c') { postfix[i] = num3; } else if (postfix[i] == 'd') { postfix[i] = num4; } else if (postfix[i] == 'e') { postfix[i] = num5; } } for (int i = 0; i < postfix.size(); i++) //evaluating equation { if (postfix[i] == '0' || postfix[i] == '1') { n1 = postfix[i] - 48; [MASK] .push(n1); } else if (postfix[i] == '~') { if ( [MASK] .top() == 0) { [MASK] .pop(); [MASK] .push(1); } else { [MASK] .pop(); [MASK] .push(0); } } else if (postfix[i] == '*') { n1 = [MASK] .top(); [MASK] .pop(); n2 = [MASK] .top(); [MASK] .pop(); if (n1 && n2) { [MASK] .push(1); } else { [MASK] .push(0); } } else if (postfix[i] == '+') { n1 = [MASK] .top(); [MASK] .pop(); n2 = [MASK] .top(); [MASK] .pop(); if (n1 || n2) { [MASK] .push(1); } else { [MASK] .push(0); } } } result4[i] = [MASK] .top() + 48; [MASK] .pop(); postfix = postfix1; } cout << ""Table: "" << endl << endl; //printing truth table cout << ""a b c d e "" << str << endl; for (int i = 0; i < rows; i++) { for (int j = 0; j < col; j++) { cout << table4[i][j] << "" ""; } cout << "" "" << result4[i] << endl; } break; } }",st1 85,"#include #include #include #include #include #include #include const int trigPin = 12; //D4 const int echoPin = 14; //D3 //define sound velocity in cm/uS #define SOUND_VELOCITY 0.034 #define CM_TO_INCH 0.393701 #define WIFI_SSID """" #define WIFI_PASSWORD """" WiFiClient client; MySQL_Connection conn((Client *)&client); IPAddress server_addr(52, 165, 234, 7); // MySQL server IP char user[] = """"; // MySQL user char password[] = """"; // MySQL password ///////////////// //Acelerometro/// ///////////////// char insertAcelerometro[]=""INSERT INTO NASA_V.S_ACELEROMETRO (x, y, z, num_caidas, id_paciente) VALUES(%s, %s, %s, %s, 1)""; char query_1[128]; // Variables temporales char c_x[16], c_y[16], c_z[16], c_contCaidas[16];// c_id_persona[16] String dat; // Variables para determinar medidas int contCaidas; float _x; float _y; float _z; Adafruit_MPU6050 mpu; #define D4 2 /////////////// //Ultrasonico// /////////////// long duration; float distanceCm; float distanceInch; int cantChoques; char insertUltrasonico[]=""INSERT INTO NASA_V.S_ULTRASONICA (distancia, num_choques, id_paciente) VALUES(%s,%s, 1)""; char query_2[128]; // Variables temporales char c_distancia[16], c_num_choques[16];// c_id_persona[16] String dat2; float _distancia; int _choques; //////////////////////////////////////////////////////////////// // Sección de inicialización //////////////////////////////////////////////////////////////// void setup() { pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input Serial.begin(9600); // Starts the serial communication ///// while (!Serial) delay(10); // will pause Zero, Leonardo, etc until serial console opens Serial.println(""Adafruit MPU6050 test!""); // Try to initialize! if (!mpu.begin()) { Serial.println(""Failed to find MPU6050 chip""); while (1) { delay(10); } } Serial.println(""MPU6050 Found!""); ///// wifiConnect(); Serial.println(""Conectando a la DB""); while(conn.connect(server_addr, 3306, user, password) != true){ delay(200); Serial.print("".""); }; Serial.println(""Conectado al servidor SQL""); pinMode(D4, OUTPUT); Serial.println(""""); delay(10); } //////////////////////////////////////////////////////////////// // Fin de sección de inicialización //////////////////////////////////////////////////////////////// void wifiConnect() { WiFi.begin(WIFI_SSID, WIFI_PASSWORD); //Conexión a la red WiFi Serial.print(""Conectado a WiFi --> ""); Serial.print(WIFI_SSID); Serial.println("" ...""); int [MASK] = 0; while (WiFi.status() != WL_CONNECTED) { //Esperar a establecer conexión WiFi delay(1000); Serial.println(++ [MASK] ); Serial.print(' '); } Serial.println('\n'); Serial.println(""WiFi conectado!""); Serial.print(""IP address:\t""); Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer } //End wifiConnect() /////////////////////////////////////////////////////////////// // LOOP /////////////////////////////////////////////////////////////// void loop() { /* Get new sensor events with the readings */ sensors_event_t a, g, temp; mpu.getEvent(&a, &g, &temp); /* Print out the values */ Serial.print(""Acceleration X: ""); Serial.print(a.acceleration.x); Serial.print("", Y: ""); Serial.print(a.acceleration.y); if(a.acceleration.z > -7.00){ Serial.println(""""); Serial.print("" Se cayó la persona ""); Serial.println(""""); contCaidas = contCaidas + 1; Serial.print(""Veces que ha caido: ""); Serial.print(contCaidas); Serial.println(""""); digitalWrite(D4,LOW); delay(1000); }; digitalWrite(D4,HIGH); Serial.print("" Z: ""); Serial.print(a.acceleration.z); Serial.println("" m/s^2""); _x = a.acceleration.x; _y = a.acceleration.y; _z = a.acceleration.z; // char c_x[16], c_y[16], c_z[16], c_contCaidas[16], c_id_persona[16]; // String dat; dat = String(_x); dat.toCharArray(c_x, 16); dat = String(_y); dat.toCharArray(c_y, 16); dat = String(_z); dat.toCharArray(c_z, 16); dat = String(contCaidas); dat.toCharArray(c_contCaidas, 16); sprintf(query_1, insertAcelerometro, c_x, c_y, c_z, c_contCaidas); Serial.println(""Registandro datos""); Serial.println(query_1); MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn); cur_mem->execute(query_1); delete cur_mem; //////////////////////////////////////////////////////////////// // Clears the trigPin digitalWrite(trigPin, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin, HIGH); // Calculate the distance distanceCm = duration * SOUND_VELOCITY/2; // Convert to inches distanceInch = distanceCm * CM_TO_INCH; if(distanceCm >= 803){ Serial.println(""La persona choco ""); cantChoques = cantChoques + 1; } else if (distanceCm < 25) { Serial.println(""La persona está a punto de chocar""); } // Prints the distance on the Serial Monitor Serial.print(""Distance (cm): ""); Serial.println(distanceCm); Serial.print(""Distance (inch): ""); Serial.println(distanceInch); Serial.print(""Cantidad de choques: ""); Serial.println(cantChoques); delay(1000); _distancia = distanceCm; _choques = cantChoques; dat2 = String(_distancia); dat2.toCharArray(c_distancia, 16); dat2 = String(_choques); dat2.toCharArray(c_num_choques, 16); sprintf(query_2, insertUltrasonico, c_distancia, c_num_choques); Serial.println(""Registandro datos""); Serial.println(query_2); MySQL_Cursor *cur_mem2 = new MySQL_Cursor(&conn); cur_mem2->execute(query_2); delete cur_mem2; if(WiFi.status() != WL_CONNECTED) { wifiConnect(); } Serial.println(""""); delay(5000); } ",teller 86,"#include ""pch.h"" #include ""Logger.h"" Logger::Logger() { logFile = CreateFileA(""log.txt"", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (logFile == INVALID_HANDLE_VALUE) { printf(""Create log file log.txt failed, last error: %d"", GetLastError()); exit(0); } } void Logger::Write(const char* log, DWORD length) { DWORD dwWrite; printf(log); WriteFile(logFile, log, strlen(log), &dwWrite, NULL); } void Logger::WriteFormat(const char* format, ...) { int bufLen = 256; char* buffer = new char[bufLen]; DWORD dwWrite; va_list [MASK] ; va_start( [MASK] , format); //format the string until succeed int slen = 0; while(true) { slen = vsnprintf(buffer, bufLen, format, [MASK] ); if (slen < 0) //slen < 0 means buffer length is not enough { bufLen *= 2; delete[] buffer; buffer = new char[bufLen]; } else { break; } } Write(buffer, slen); delete[] buffer; va_end( [MASK] ); } void Logger::WriteLine(const char* log, DWORD length) { Write(log, length); DWORD dwWrite; char newline = '\n'; printf(""\n""); WriteFile(logFile, &newline, 1, &dwWrite, NULL); }",argptr 87,"/* * Copyright 2019 * * 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 #include #include #include #include #include static const std::string OPENCV_WINDOW = ""Image window""; void getImageCallback(const sensor_msgs::ImageConstPtr& msg) { ROS_INFO(""Got image published to 'image_raw' topic""); cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR(""cv_bridge exception: %s"", e.what()); return; } cv::imshow(OPENCV_WINDOW, cv_ptr->image); cv::waitKey(3); } int main(int argc, char** argv) { ros::init(argc, argv, ""camera test""); ros::NodeHandle nh; std::string [MASK] ; // Get image topic ROS parameter if (!(ros::param::get(""~image_topic"", [MASK] ))) { if (argc > 1) { [MASK] = argv[1]; } else { exit(1); } } ROS_INFO(""Going to capture image from ROS topic: %s"", [MASK] .c_str()); ros::Rate loop_rate(10); ros::Subscriber sub = nh.subscribe( [MASK] .c_str(), 1000, getImageCallback); while (ros::ok()) { ros::spinOnce(); loop_rate.sleep(); } } ",imageTopic 88,"#include ""sandbox_processor.h"" #include ""sandbox_editor.h"" #include ""../shared/gui/adjust_colour_panel.h"" #include ""../shared/game/random_colors/random_colors_launcher.h"" #include ""../shared/game/hex_rings/hex_rings_launcher.h"" #include ""../shared/game/hexagon_automata/hexagon_automata_launcher.h"" #include ""../shared/MainComponent.h"" #include ""../shared/debug/LumatoneSandboxDebugWindow.h"" //============================================================================== LumatoneSandboxProcessorEditor::LumatoneSandboxProcessorEditor (LumatoneSandboxProcessor& p) : AudioProcessorEditor (&p), processor (p) , controller(p.getLumatoneController()) , undoManager(p.getUndoManager()) , commandManager(p.getCommandManager()) , paletteLibrary(p.getPaletteLibrary()) , gameEngine(p.getGameEngine()) { juce::ignoreUnused (processor); debugWindow = std::make_unique(processor.getLogData()); debugWindow->setSize(800, 500); debugWindow->addToDesktop(); debugWindow->setVisible(true); mainComponent = std::make_unique(controller); mainComponent->setGameEngine(gameEngine); addAndMakeVisible(*mainComponent); commandManager->registerAllCommandsForTarget(this); commandManager->registerAllCommandsForTarget(mainComponent.get()); commandManager->setFirstCommandTarget(this); menuModel = std::make_unique(commandManager); // if (showMenu()) // { menuBar = std::make_unique(menuModel.get()); addAndMakeVisible(menuBar.get()); // } // else if (JucePlugin_Build_Standalone) // { // #if JUCE_MAC // LumatoneSandbox::Menu::Model::setMacMainMenu((juce::MenuBarModel*)(nullptr)); // #endif // } setSize (1024, 768); setResizable(true, true); } LumatoneSandboxProcessorEditor::~LumatoneSandboxProcessorEditor() { fileChooser = nullptr; constrainer = nullptr; menuBar = nullptr; menuModel = nullptr; mainComponent = nullptr; debugWindow = nullptr; } //============================================================================== void LumatoneSandboxProcessorEditor::paint (juce::Graphics& g) { // (Our component is opaque, so we must completely fill the background with a solid colour) g.fillAll (getLookAndFeel().findColour (juce::ResizableWindow::backgroundColourId)); g.setColour (juce::Colours::white); g.setFont (15.0f); g.drawFittedText (""Hello World!"", getLocalBounds(), juce::Justification::centred, 1); } void LumatoneSandboxProcessorEditor::resized() { int menuHeight = 24; if (showMenu()) menuBar->setBounds(0, 0, getWidth(), menuHeight); else menuHeight = 0; mainComponent->setBounds(getLocalBounds().withTrimmedTop(menuHeight)); } bool LumatoneSandboxProcessorEditor::showMenu() const { return true; // return JucePlugin_Build_Standalone // && ((juce::SystemStats::getOperatingSystemType() & juce::SystemStats::OperatingSystemType::MacOSX) // != juce::SystemStats::OperatingSystemType::MacOSX // ); } juce::ApplicationCommandTarget* LumatoneSandboxProcessorEditor::getNextCommandTarget() { return mainComponent.get(); } void LumatoneSandboxProcessorEditor::getAllCommands(juce::Array & commands) { commands.add(LumatoneSandbox::Menu::commandIDs::openSysExMapping); commands.add(LumatoneSandbox::Menu::commandIDs::saveSysExMapping); commands.add(LumatoneSandbox::Menu::commandIDs::saveSysExMappingAs); commands.add(LumatoneSandbox::Menu::commandIDs::resetSysExMapping); commands.add(LumatoneSandbox::Menu::commandIDs::importSysExMapping); // commands.add(LumatoneSandbox::Menu::commandIDs::deleteOctaveBoard); // commands.add(LumatoneSandbox::Menu::commandIDs::copyOctaveBoard); // commands.add(LumatoneSandbox::Menu::commandIDs::pasteOctaveBoard); // commands.add(LumatoneSandbox::Menu::commandIDs::pasteOctaveBoardChannels); // commands.add(LumatoneSandbox::Menu::commandIDs::pasteOctaveBoardNotes); // commands.add(LumatoneSandbox::Menu::commandIDs::pasteOctaveBoardColours); // commands.add(LumatoneSandbox::Menu::commandIDs::pasteOctaveBoardTypes); commands.add(LumatoneSandbox::Menu::commandIDs::adjustColour); commands.add(LumatoneSandbox::Menu::commandIDs::openRandomColorsGame); commands.add(LumatoneSandbox::Menu::commandIDs::openHexRingsGame); commands.add(LumatoneSandbox::Menu::commandIDs::openHexagonAutomata); } void LumatoneSandboxProcessorEditor::getCommandInfo(juce::CommandID commandID, juce::ApplicationCommandInfo& result) { result.setActive(true); switch (commandID) { case LumatoneSandbox::Menu::commandIDs::openSysExMapping: result.setInfo(""Load file mapping"", ""Open a Lumatone key mapping"", ""File"", 0); result.addDefaultKeypress('o', juce::ModifierKeys::commandModifier); break; case LumatoneSandbox::Menu::commandIDs::saveSysExMapping: result.setInfo(""Save mapping"", ""Save the current mapping to file"", ""File"", 0); result.addDefaultKeypress('s', juce::ModifierKeys::commandModifier); break; case LumatoneSandbox::Menu::commandIDs::saveSysExMappingAs: result.setInfo(""Save mapping as..."", ""Save the current mapping to new file"", ""File"", 0); result.addDefaultKeypress('a', juce::ModifierKeys::commandModifier); break; case LumatoneSandbox::Menu::commandIDs::resetSysExMapping: result.setInfo(""New"", ""Start new mapping. Clear all edit fields, do not save current edits."", ""File"", 0); result.addDefaultKeypress('n', juce::ModifierKeys::commandModifier); break; case LumatoneSandbox::Menu::commandIDs::importSysExMapping: result.setInfo(""Import"", ""Get mapping from connected Lumatone"", ""File"", 0); result.addDefaultKeypress('i', juce::ModifierKeys::currentModifiers); break; // case LumatoneSandbox::Menu::commandIDs::deleteOctaveBoard: // result.setInfo(""Delete"", ""Delete section data"", ""Edit"", 0); // result.addDefaultKeypress(juce::KeyPress::deleteKey, juce::ModifierKeys::noModifiers); // break; // case LumatoneSandbox::Menu::commandIDs::copyOctaveBoard: // result.setInfo(""Copy section"", ""Copy current octave board data"", ""Edit"", 0); // result.addDefaultKeypress('c', juce::ModifierKeys::commandModifier); // break; // case LumatoneSandbox::Menu::commandIDs::pasteOctaveBoard: // result.setInfo(""Paste section"", ""Paste copied section data"", ""Edit"", 0); // result.addDefaultKeypress('v', juce::ModifierKeys::commandModifier); // break; // case LumatoneSandbox::Menu::commandIDs::pasteOctaveBoardNotes: // result.setInfo(""Paste notes"", ""Paste copied section notes"", ""Edit"", 0); // result.addDefaultKeypress('v', juce::ModifierKeys::commandModifier | juce::ModifierKeys::shiftModifier); // break; // case LumatoneSandbox::Menu::commandIDs::pasteOctaveBoardChannels: // result.setInfo(""Paste channels"", ""Paste copied section channels"", ""Edit"", 0); // result.addDefaultKeypress('v', juce::ModifierKeys::commandModifier | juce::ModifierKeys::altModifier); // break; // case LumatoneSandbox::Menu::commandIDs::pasteOctaveBoardColours: // result.setInfo(""Paste colours"", ""Paste copied section colours"", ""Edit"", 0); // result.addDefaultKeypress('v', juce::ModifierKeys::altModifier); // break; // case LumatoneSandbox::Menu::commandIDs::pasteOctaveBoardTypes: // result.setInfo(""Paste types"", ""Paste copied section key types"", ""Edit"", 0); // result.addDefaultKeypress('v', juce::ModifierKeys::altModifier | juce::ModifierKeys::shiftModifier); // break; case LumatoneSandbox::Menu::commandIDs::adjustColour: result.setInfo(""Adjust colours"", ""Apply adjustments to colours across the layout"", ""Edit"", 0); break; case LumatoneSandbox::Menu::commandIDs::openRandomColorsGame: result.setInfo(""Random Colors"", ""Open launcher for Random Colors game"", ""Game"", 0); break; case LumatoneSandbox::Menu::commandIDs::openHexRingsGame: result.setInfo(""Hex Rings"", ""Open launcher for Hex Rings game"", ""Game"", 0); break; case LumatoneSandbox::Menu::commandIDs::openHexagonAutomata: result.setInfo(""Hexagon Automata"", ""Open launcher for hex game of life"", ""Game"", 0); break; default: result.setInfo(""?"", ""Unknown command"", ""Unknown"", 0); break; } } bool LumatoneSandboxProcessorEditor::perform(const juce::ApplicationCommandTarget::InvocationInfo& info) { switch (info.commandID) { case LumatoneSandbox::Menu::commandIDs::openSysExMapping: { auto directory = controller->getLastMappingsDirectory(); fileChooser.reset(new juce::FileChooser(""Open .LTN file"", directory, ""*.ltn"")); fileChooser->launchAsync( juce::FileBrowserComponent::FileChooserFlags::canSelectFiles | juce::FileBrowserComponent::FileChooserFlags::openMode, [&](const juce::FileChooser& chooser) { auto file = chooser.getResult(); controller->loadLayoutFromFile(file); }); return true; } case LumatoneSandbox::Menu::commandIDs::saveSysExMappingAs: { auto directory = controller->getLastMappingsDirectory(); fileChooser.reset(new juce::FileChooser(""Save .LTN file"", directory, ""*.ltn"")); fileChooser->launchAsync( juce::FileBrowserComponent::FileChooserFlags::canSelectFiles | juce::FileBrowserComponent::FileChooserFlags::saveMode, [&](const juce::FileChooser& chooser) { auto file = chooser.getResult(); auto [MASK] = controller->getMappingData() ->toStringArray() .joinIntoString(juce::newLine); auto tempFile = file.createTempFile(""ltn.tmp""); tempFile.appendText( [MASK] ); tempFile.moveFileTo(file); }); return true; } case LumatoneSandbox::Menu::commandIDs::importSysExMapping: { controller->sendGetCompleteMappingRequest(); return true; } case LumatoneSandbox::Menu::commandIDs::adjustColour: { juce::DialogWindow::LaunchOptions launch; launch.dialogTitle = ""Adjust Colours""; launch.content.setOwned(new AdjustColourPanel(controller, paletteLibrary)); launch.content->setSize(600, 400); launch.componentToCentreAround = mainComponent.get(); launch.launchAsync(); return true; } case LumatoneSandbox::Menu::commandIDs::openRandomColorsGame: { mainComponent->setGameComponent(new RandomColorsComponent(gameEngine)); return true; } case LumatoneSandbox::Menu::commandIDs::openHexRingsGame: { mainComponent->setGameComponent(new HexRingLauncher(gameEngine)); return true; } case LumatoneSandbox::Menu::commandIDs::openHexagonAutomata: { mainComponent->setGameComponent(new HexagonAutomataComponent(gameEngine)); return true; } default: return false; } return false; } ",layoutString 89,"/** esp8266 firmware OTA Purpose: Perform an OTA update from a bin located on a webserver (HTTP Only) Setup: Step 1 : Set your WiFi (ssid & password) Step 2 : set EspFota() Upload: Step 1 : Menu > Sketch > Export Compiled Library. The bin file will be saved in the sketch folder (Menu > Sketch > Show Sketch folder) Step 2 : Upload it to your webserver Step 3 : Update your firmware JSON file ( see firwmareupdate ) */ #include #include // Change to your WiFi credentials const char *ssid = """"; const char *password = """"; // EspFota fota("""", ); EspFota fota(""bedroom_lights"", 1); void setup() { fota.checkUpdateURL = ""http://server/updates/firmware.json""; Serial.begin(115200); setup_wifi(); } void setup_wifi() { delay(10); Serial.print(""Connecting to ""); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("".""); } Serial.println(""""); Serial.println(WiFi.localIP()); } void loop() { fota.useDeviceMAC = true; bool [MASK] = fota.execHTTPcheck(); if ( [MASK] ) { fota.execOTA(); } delay(2000); }",updatedNeeded 90,"#include #include #include #include #include #include #include #include #include #include #include #include #include ""gdal.h"" #include ""gdal_priv.h"" #include ""ogrsf_frmts.h"" #include ""cpl_error.h"" #include ""ogr_feature.h"" #include ""ogr_geometry.h"" #include ""ogr_core.h"" #include ""ogr_srs_api.h"" #include ""ogr_spatialref.h"" #include ""cpl_port.h"" #include ""cpl_string.h"" using GeoTransform = std::array; using ArrayIndex_t = size_t; using Row = ArrayIndex_t; using Column = ArrayIndex_t; using ArrayCoordinate = std::pair; using GeographicIndex_t = double; using Latitude = GeographicIndex_t; using Longitude = GeographicIndex_t; using GeographicCoordinate = std::pair; struct Arguments { public: size_t raster_band; size_t cache_size; std::string point_layer; std::string input_raster; std::string input_points; std::string output_points; std::string output_format; std::string source_srs; std::string target_srs; Arguments(): raster_band(1), cache_size(64), point_layer(), input_raster(), input_points(), output_points(), output_format(""GPKG""), source_srs(), target_srs() {}; Arguments(const size_t raster_band, const size_t cache_size, const std::string point_layer, const std::string input_raster, const std::string input_points, const std::string output_points, const std::string output_format, const std::string source_srs, const std::string target_srs): raster_band(raster_band), cache_size(cache_size), point_layer(point_layer), input_raster(input_raster), input_points(input_points), output_points(output_points), output_format(output_format), source_srs(source_srs), target_srs(target_srs) {}; ~Arguments() = default; }; struct RasterShape { public: size_t blockxsize; size_t blockysize; size_t size_x; size_t size_y; size_t num_blocks_x; size_t num_blocks_y; RasterShape() = default; ~RasterShape() = default; }; struct RasterBounds { private: double ulx; double uly; double lrx; double lry; public: RasterBounds(const GeoTransform& gt, const size_t rastersize_x, const size_t rastersize_y) { ulx = gt[0]; uly = gt[3] + static_cast(rastersize_y)*gt[5]; lrx = gt[0] + static_cast(rastersize_x)*gt[1]; lry = gt[3]; }; ~RasterBounds() = default; std::array to_array() const { return {ulx, uly, lrx, lry}; }; }; ArrayCoordinate projection_to_rowcol(const GeoTransform& gt, const GeographicCoordinate& point) { return std::make_pair( static_cast((point.first - gt[0]) / gt[1]), static_cast((point.second - gt[3]) / gt[5]) ); } std::vector projection_to_rowcol(const GeoTransform& gt, const std::vector& points) { std::vector output{}; output.reserve(points.size()); std::transform(points.begin(), points.end(), std::back_inserter(output), [>](const auto& elem) { return projection_to_rowcol(gt, elem); }); return output; } size_t rowcol_to_linear_index(const ArrayCoordinate& rowcol, const RasterShape& rs) { const size_t x_block = static_cast(std::floor(rowcol.first / rs.blockxsize)); const size_t y_block = static_cast(std::floor(rowcol.second / rs.blockysize)); const size_t linear_index = y_block * rs.size_x + x_block; return linear_index; } ArrayCoordinate linear_index_to_rowcol(const size_t linear_index, const RasterShape& rs) { const ArrayIndex_t row = static_cast(std::floor(static_cast(linear_index) / static_cast(rs.size_x))); const ArrayIndex_t col = linear_index - row*rs.size_x; return std::make_pair(col, row); } std::vector read_points_from_geofile(OGRLayer* layer, OGRCoordinateTransformation* transform) { OGRPoint* point = nullptr; OGRGeometry* layer_geom = nullptr; std::vector points{}; for (auto& feature : layer) { layer_geom = feature->GetGeometryRef(); if (!layer_geom || !(wkbFlatten(layer_geom->getGeometryType()) == wkbPoint)) { std::cerr << ""Detected feature with invalid/non-point geometry! Skipping...\n""; continue; } point = layer_geom->toPoint(); if (transform && point->transform(transform) != OGRERR_NONE) { std::cerr << ""Failed to project point from point SRS to raster SRS!\n""; continue; } points.push_back(std::make_pair(point->getX(), point->getY())); } return points; } OGRFieldType ogr_type_from_gdal_type(const GDALDataType dt) { if (dt == GDT_Float32 || dt == GDT_Float64) { return OFTReal; } if (dt == GDT_Int8 || dt == GDT_Int16 || dt == GDT_Int32 || dt == GDT_Int64 || dt == GDT_UInt16 || dt == GDT_UInt32 || dt == GDT_UInt64) { return OFTInteger64; } return OFTMaxType; } template CPLErr write_points_to_geofile(const std::string& path, const std::vector& points, const std::vector& values, const GDALDataType raster_dt, const OGRSpatialReference* sref, OGRCoordinateTransformation* transform, const std::string output_driver, const std::string output_field_name = ""sampled"") { GDALDriver* driver = GetGDALDriverManager()->GetDriverByName(output_driver.c_str()); if (!driver) { std::cerr << ""Could not use "" << output_driver << "" driver for writing\n""; return CE_Failure; } GDALDataset* ds = driver->Create(path.c_str(), 0, 0, 0, GDT_Unknown, NULL); if (!ds) { std::cerr << ""Could not create dataset using "" << output_driver << "" driver\n""; return CE_Failure; } CPLStringList options{}; if (output_driver.compare(""CSV"") == 0) { options.SetNameValue(""GEOMETRY"", ""AS_XY""); } OGRSpatialReference* sref_output = sref->Clone(); OGRLayer* layer = ds->CreateLayer(""output"", sref_output, wkbPoint, options); if (!layer) { std::cerr << ""Could not create layer using "" << output_driver << "" driver\n""; return CE_Failure; } const OGRFieldType field_type = ogr_type_from_gdal_type(raster_dt); if (field_type == OFTMaxType) { std::cerr << ""Could not determine field type!\n""; return CE_Failure; } OGRFieldDefn field(output_field_name.c_str(), field_type); field.SetWidth(32); field.SetPrecision(13); if (layer->CreateField(&field) != OGRERR_NONE) { std::cerr << ""Could not create field on output\n""; return CE_Failure; } for (size_t i = 0; i < points.size(); i++) { OGRFeature* feature = OGRFeature::CreateFeature(layer->GetLayerDefn()); if constexpr (std::is_floating_point_v) { feature->SetField(output_field_name.c_str(), static_cast(values[i])); } else { feature->SetField(output_field_name.c_str(), static_cast(values[i])); } OGRPoint pt{points[i].first, points[i].second}; if (transform && pt.transform(transform) != OGRERR_NONE) { std::cerr << ""Failed to project point from source SRS to specified target SRS!\n""; }; feature->SetGeometry(&pt); if (layer->CreateFeature(feature) != OGRERR_NONE) { std::cerr << ""Failed to create feature!\n""; } OGRFeature::DestroyFeature(feature); } GDALClose(ds); return CE_None; } void print_usage() { std::cout << ""Usage: parsam [-l,--layer layername] [-b,--band band_number]\n""; std::cout << "" [-cs,--cachesize size] [-of,--output_format format]\n""; std::cout << "" [-s_srs,--source_srs srs] [-t_srs,--target_srs srs]\n""; std::cout << "" input_raster input_points output_points\n\n""; std::cout << "" -l, --layer: Name of input point layer to sample. Defaults to first layer.\n""; std::cout << "" -b, --band: Band of input raster to sample. Defaults to first band.\n""; std::cout << "" -cs, --cachesize: Size in megabyte for GDAL to use internally for caching.\n""; std::cout << "" -of, --output_format: Output format to use for result file. Needs to be a valid choice for GDAL tools.\n""; std::cout << "" -s_srs,--source_srs: Source spatial reference system to use for inputs. Note that input points will be\n"" << "" dynamically reprojected if necessary, but an error will be thrown if the raster\n"" << "" is not using this reference system.\n""; std::cout << "" -t_srs,--target_srs: Target spatial reference system to project output points into.\n""; std::cout << ""\n""; std::cout << "" input_raster: Path pointing to input raster to sample points from.\n""; std::cout << "" input_points: Path pointing to input vector layer containing points to be sampled.\n""; std::cout << "" output_points: Path pointing to output vector layer containing sampled points.\n""; } void parse_cli_args(const int argc, const char* argv[], Arguments& args) { bool invalid_arg_found = false; size_t current_arg_idx = 1; size_t io_arg_idx = 0; std::array io_args{}; while (current_arg_idx < static_cast(argc)) { const std::string current_arg{argv[current_arg_idx]}; if (current_arg.compare(""-l"") == 0 || current_arg.compare(""--layer"") == 0) { args.point_layer = std::string{argv[current_arg_idx + 1]}; current_arg_idx += 2; continue; } if (current_arg.compare(""-b"") == 0 || current_arg.compare(""--band"") == 0) { const int raster_band = std::stoi(argv[current_arg_idx + 1]); if (raster_band < 1) { args.raster_band = 0; } else { args.raster_band = static_cast(raster_band); } current_arg_idx += 2; continue; } if (current_arg.compare(""-cs"") == 0 || current_arg.compare(""--cachesize"") == 0) { const int cache_size = std::stoi(argv[current_arg_idx + 1]); if (cache_size < 0) { std::cerr << ""Negative cachesize is not allowed!\n""; invalid_arg_found = true; break; } args.cache_size = static_cast(cache_size); current_arg_idx += 2; continue; } if (current_arg.compare(""-of"") == 0 || current_arg.compare(""--output_format"") == 0) { args.output_format = std::string{argv[current_arg_idx + 1]}; current_arg_idx += 2; continue; } if (current_arg.compare(""-s_srs"") == 0 || current_arg.compare(""--source_srs"") == 0) { args.source_srs = std::string{argv[current_arg_idx + 1]}; current_arg_idx += 2; continue; } if (current_arg.compare(""-t_srs"") == 0 || current_arg.compare(""--target_srs"") == 0) { args.target_srs = std::string{argv[current_arg_idx + 1]}; current_arg_idx += 2; continue; } if (current_arg.compare(0, 1, ""-"") == 0 || current_arg.compare(0, 2, ""--"") == 0) { std::cerr << ""Unknown argument: "" << current_arg << ""\n""; invalid_arg_found = true; break; } io_args[io_arg_idx++] = current_arg; current_arg_idx++; } if (!invalid_arg_found) { args.input_raster = io_args[0]; args.input_points = io_args[1]; args.output_points = io_args[2]; } } bool validate_parsed_arguments(const Arguments& args) { const bool raster_band_is_positive = args.raster_band > 0; const bool input_points_are_present = !args.input_points.empty(); const bool input_raster_is_present = !args.input_raster.empty(); const bool output_points_are_present = !args.output_points.empty(); return raster_band_is_positive && input_points_are_present && input_raster_is_present && output_points_are_present; } bool check_crs_match(const OGRSpatialReference* raster_sref, const OGRSpatialReference* point_sref) { if (!raster_sref || !point_sref) { std::cerr << ""Could not read spatial reference from inputs\n""; return false; } if (!point_sref->IsSame(raster_sref)) { std::cerr << ""Spatial reference systems of inputs do not match\n""; return false; } return true; } OGRErr determine_source_srs(const Arguments& args, OGRSpatialReference*& source_sref, const OGRSpatialReference* raster_sref, const OGRSpatialReference* point_sref) { if (!args.source_srs.empty()) { OGRSpatialReference user_input_srs; if (user_input_srs.SetFromUserInput(args.source_srs.c_str()) != OGRERR_NONE) { std::cerr << ""Did not understand source spatial reference definition!\n""; return OGRERR_UNSUPPORTED_SRS; }; // TODO: This only checks whether they use the same geographical CRS and both are projected/non-projected. However, // the projections may still be different! if (!(raster_sref->IsSameGeogCS(&user_input_srs) && raster_sref->IsProjected() == user_input_srs.IsProjected())) { std::cerr << ""SRS mismatch between input raster and source raster definition. Are they using the same CRS?\n""; return OGRERR_UNSUPPORTED_SRS; } source_sref = user_input_srs.Clone(); } else { if (!check_crs_match(raster_sref, point_sref)) { std::cerr << ""Mismatch between input raster and input point SRS! Either specify a custom one using '-s_srs' to reproject points\n"" << ""on the fly to the raster SRS or reproject both to the same SRS before.\n""; return OGRERR_UNSUPPORTED_SRS; } source_sref = raster_sref->Clone(); } source_sref->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); return OGRERR_NONE; } OGRErr determine_target_srs(const Arguments& args, OGRSpatialReference*& target_sref, const OGRSpatialReference* source_sref) { if (!args.target_srs.empty()) { OGRSpatialReference user_target_srs; if (user_target_srs.SetFromUserInput(args.target_srs.c_str()) != OGRERR_NONE) { std::cerr << ""Did not understand target spatial reference definition!\n""; return OGRERR_UNSUPPORTED_SRS; } target_sref = user_target_srs.Clone(); } else { target_sref = source_sref->Clone(); } target_sref->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); return OGRERR_NONE; } std::vector calculate_points_in_bounds_mask(const std::vector& points, const RasterBounds& rb) { std::vector in_bounds{}; in_bounds.reserve(points.size()); const auto raster_bounds = rb.to_array(); std::transform(points.begin(), points.end(), std::back_inserter(in_bounds), [&raster_bounds](const auto& point) { const bool in_x_bounds = point.first > raster_bounds[0] && point.first < raster_bounds[2]; const bool in_y_bounds = point.second > raster_bounds[1] && point.second < raster_bounds[3]; return in_x_bounds && in_y_bounds; }); return in_bounds; } void sort_proxy_by_blocks(std::vector& point_proxy, const std::vector& points_rowcol, const std::vector& valid_mask, const RasterShape& rs) { std::sort(point_proxy.begin(), point_proxy.end(), [&](const auto& idx_a, const auto& idx_b) { const auto a = points_rowcol[idx_a]; const size_t [MASK] = valid_mask[idx_a] ? rowcol_to_linear_index(a, rs) : std::numeric_limits::max(); const auto b = points_rowcol[idx_b]; const size_t b_linear_index = valid_mask[idx_b] ? rowcol_to_linear_index(b, rs) : std::numeric_limits::max(); return [MASK] < b_linear_index; }); } std::vector> calculate_nonempty_window_indices( const std::vector& point_proxy, const std::vector& points_rowcol, const std::vector& valid_mask, const RasterShape& rs ) { size_t starting_boundary_index = 0; size_t starting_linear_index = rowcol_to_linear_index(points_rowcol[point_proxy[0]], rs); std::vector> window_indices{}; // This marks the initial window to sample from window_indices.push_back(std::make_pair(starting_boundary_index, starting_linear_index)); for (size_t i = 0; i < point_proxy.size(); i++) { const size_t current_linear_index = rowcol_to_linear_index(points_rowcol[point_proxy[i]], rs); if (starting_linear_index != current_linear_index) { starting_boundary_index = i; starting_linear_index = current_linear_index; if (valid_mask[point_proxy[i]]) { window_indices.push_back(std::make_pair(starting_boundary_index, starting_linear_index)); } else { // Push a window with a special value for the linear index. This will be used to abort once all valid points are covered. window_indices.push_back(std::make_pair(starting_boundary_index, std::numeric_limits::max())); break; } } } return window_indices; } RasterShape raster_shape_from_band(GDALRasterBand* band) { int blockxsize, blockysize; band->GetBlockSize(&blockxsize, &blockysize); return RasterShape { static_cast(blockxsize), static_cast(blockysize), static_cast(band->GetXSize()), static_cast(band->GetYSize()), static_cast((band->GetXSize() + blockxsize - 1) / blockxsize), static_cast((band->GetYSize() + blockysize - 1) / blockysize) }; } template std::vector sample_points_from_band(GDALRasterBand* band, const std::vector& points_rowcol, const std::vector& points_proxy, const std::vector>& window_indices, const RasterShape& rs) { const size_t max_point_index = points_rowcol.size(); T sample_initializer_value{}; if constexpr (std::is_floating_point::value) { sample_initializer_value = std::numeric_limits::quiet_NaN(); } else { sample_initializer_value = std::numeric_limits::max(); } std::vector points_sampled(points_rowcol.size(), sample_initializer_value); std::vector block_buffer{}; block_buffer.reserve(rs.blockxsize*rs.blockysize); for (const auto& [proxy_index, linear_index] : window_indices) { if (linear_index == std::numeric_limits::max()) { break; } size_t current_point = proxy_index; const auto [block_x, block_y] = linear_index_to_rowcol(linear_index, rs); int valid_blocksize_x{}, valid_blocksize_y{}; if (band->GetActualBlockSize(static_cast(block_x), static_cast(block_y), &valid_blocksize_x, &valid_blocksize_y) != CE_None) { throw std::runtime_error(""Error reading true blocksize!""); }; if (band->ReadBlock(static_cast(block_x), static_cast(block_y), block_buffer.data()) != CE_None) { throw std::runtime_error(""Error reading block!""); } // The left edge is always multiples of the full blocksize from the origin // while the right edge may not be a full block size away due to partial blocks const size_t block_xmin = block_x*rs.blockxsize, block_xmax = block_xmin + static_cast(valid_blocksize_x); const size_t block_ymin = block_y*rs.blockysize, block_ymax = block_ymin + static_cast(valid_blocksize_y); while (true) { const auto point_index = points_proxy[current_point]; const auto [glob_x, glob_y] = points_rowcol[point_index]; const bool within_x_bounds = block_xmin <= glob_x && glob_x < block_xmax; const bool within_y_bounds = block_ymin <= glob_y && glob_y < block_ymax; if (!within_x_bounds || !within_y_bounds || current_point == max_point_index) { break; } const size_t local_x = glob_x - block_xmin, local_y = glob_y - block_ymin; points_sampled[point_index] = block_buffer[local_y*rs.blockxsize + local_x]; current_point++; } } return points_sampled; } CPLErr dispatch_sample_and_write(const GDALDataType raster_dt, GDALRasterBand* band, const std::vector& points, const std::vector& points_rowcol, const std::vector& points_proxy, const std::vector>& window_indices, const RasterShape& rs, const OGRSpatialReference* target_sref, OGRCoordinateTransformation* target_point_transform, const Arguments& args) { switch (raster_dt) { case GDT_Float32: { const auto points_sampled = sample_points_from_band(band, points_rowcol, points_proxy, window_indices, rs); return write_points_to_geofile(args.output_points, points, points_sampled, raster_dt, target_sref, target_point_transform, args.output_format); } case GDT_Float64: { const auto points_sampled = sample_points_from_band(band, points_rowcol, points_proxy, window_indices, rs); return write_points_to_geofile(args.output_points, points, points_sampled, raster_dt, target_sref, target_point_transform, args.output_format); } case GDT_UInt16: { const auto points_sampled = sample_points_from_band(band, points_rowcol, points_proxy, window_indices, rs); return write_points_to_geofile(args.output_points, points, points_sampled, raster_dt, target_sref, target_point_transform, args.output_format); } case GDT_UInt32: { const auto points_sampled = sample_points_from_band(band, points_rowcol, points_proxy, window_indices, rs); return write_points_to_geofile(args.output_points, points, points_sampled, raster_dt, target_sref, target_point_transform, args.output_format); } case GDT_UInt64: { const auto points_sampled = sample_points_from_band(band, points_rowcol, points_proxy, window_indices, rs); return write_points_to_geofile(args.output_points, points, points_sampled, raster_dt, target_sref, target_point_transform, args.output_format); } case GDT_Int8: { const auto points_sampled = sample_points_from_band(band, points_rowcol, points_proxy, window_indices, rs); return write_points_to_geofile(args.output_points, points, points_sampled, raster_dt, target_sref, target_point_transform, args.output_format); } case GDT_Int16: { const auto points_sampled = sample_points_from_band(band, points_rowcol, points_proxy, window_indices, rs); return write_points_to_geofile(args.output_points, points, points_sampled, raster_dt, target_sref, target_point_transform, args.output_format); } case GDT_Int32: { const auto points_sampled = sample_points_from_band(band, points_rowcol, points_proxy, window_indices, rs); return write_points_to_geofile(args.output_points, points, points_sampled, raster_dt, target_sref, target_point_transform, args.output_format); } case GDT_Int64: { const auto points_sampled = sample_points_from_band(band, points_rowcol, points_proxy, window_indices, rs); return write_points_to_geofile(args.output_points, points, points_sampled, raster_dt, target_sref, target_point_transform, args.output_format); } default: return CE_Failure; } } int main(int argc, const char* argv[]) { if (argc <= 3 || std::string(argv[1]).compare(""-h"") == 0) { print_usage(); return 0; }; Arguments args{}; parse_cli_args(argc, argv, args); if (!validate_parsed_arguments(args)) { if (args.raster_band < 1) { std::cerr << ""Raster band needs to be larger than or equal to 1\n""; } else { std::cerr << ""Missing ""; if (args.input_points.empty()) std::cerr << ""input points, ""; if (args.input_raster.empty()) std::cerr << ""input raster, ""; if (args.output_points.empty()) std::cerr << ""output points""; std::cerr << ""\n""; } print_usage(); return 1; } GDALAllRegister(); // Limit GDAL's internal caching size. At 64MB, there does not seem to be much benefit from more CPLSetConfigOption(""GDAL_CACHEMAX"", std::to_string(args.cache_size).c_str()); GDALDatasetUniquePtr input_raster = GDALDatasetUniquePtr(GDALDataset::FromHandle(GDALOpen(args.input_raster.c_str(), GA_ReadOnly))); if(!input_raster) { std::cerr << ""Could not open input raster at "" << args.input_raster << ""\n""; return 1; } GDALDatasetUniquePtr input_points = GDALDatasetUniquePtr(GDALDataset::FromHandle(GDALOpenEx(args.input_points.c_str(), GA_ReadOnly | GDAL_OF_VECTOR, NULL, NULL, NULL))); if (!input_points) { std::cerr << ""Could not open input points at "" << args.input_points << ""\n""; return 1; } GeoTransform gt_ir{}; if (input_raster->GetGeoTransform(gt_ir.data()) != CE_None) { std::cerr << ""Could not read geotransform from input raster\n""; return 1; } GDALRasterBand* band = input_raster->GetRasterBand(static_cast(args.raster_band)); if (!band) { std::cerr << ""Could not read band "" << args.raster_band << "" from raster\n""; return 1; } OGRLayer* point_layer = nullptr; if (!args.point_layer.empty()) { point_layer = input_points->GetLayerByName(args.point_layer.c_str()); } else { point_layer = input_points->GetLayer(0); } if (!point_layer) { std::cerr << ""Could not read layer from input point dataset\n""; return 1; } // If the user supplied custom source and target spatial reference systems, // check them early so we can fail early if something mismatches const OGRSpatialReference* raster_sref = input_raster->GetSpatialRef(); const OGRSpatialReference* point_sref = point_layer->GetSpatialRef(); OGRSpatialReference* source_sref = nullptr; if (determine_source_srs(args, source_sref, raster_sref, point_sref) != OGRERR_NONE) { return 1; } OGRSpatialReference* target_sref = nullptr; if (determine_target_srs(args, target_sref, source_sref) != OGRERR_NONE) { return 1; } // Transform input points during reading if they are using a different CRS. Just pass // a matching transform to the read_points_from_geofile function OGRCoordinateTransformation* source_point_transform = nullptr; if (!point_sref->IsSame(source_sref)) { source_point_transform = OGRCreateCoordinateTransformation(point_sref, source_sref); if (!source_point_transform) { std::cerr << ""Failed to find a transform for going from point SRS to specified source SRS!\n""; return 1; } } // Same applies for output SRS. Figure out early if we can even do this! OGRCoordinateTransformation *target_point_transform = nullptr; if (!source_sref->IsSame(target_sref)) { target_point_transform = OGRCreateCoordinateTransformation(source_sref, target_sref); if (!target_point_transform) { std::cerr << ""Failed to find a transform for going from raster SRS to specified target SRS!\n""; return 1; } } const RasterShape rs = raster_shape_from_band(band); const RasterBounds rb( gt_ir, static_cast(input_raster->GetRasterXSize()), static_cast(input_raster->GetRasterYSize()) ); const auto points = read_points_from_geofile(point_layer, source_point_transform); const auto in_bounds = calculate_points_in_bounds_mask(points, rb); const auto points_rowcol = projection_to_rowcol(gt_ir, points); std::vector points_proxy(points_rowcol.size()); std::iota(points_proxy.begin(), points_proxy.end(), 0); sort_proxy_by_blocks(points_proxy, points_rowcol, in_bounds, rs); const auto window_indices = calculate_nonempty_window_indices(points_proxy, points_rowcol, in_bounds, rs); if (dispatch_sample_and_write(band->GetRasterDataType(), band, points, points_rowcol, points_proxy, window_indices, rs, target_sref, target_point_transform, args) != CE_None) { std::cerr << ""Error writing result\n""; return 1; } return 0; }",a_linear_index 91,"/* * Copyright (c) 2024 Huawei Device Co., Ltd. * 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 ""oaid_remote_config_observer_stub.h"" #include ""oaid_common.h"" namespace OHOS { namespace Cloud { RemoteConfigObserverStub::RemoteConfigObserverStub() {} RemoteConfigObserverStub::~RemoteConfigObserverStub() {} int32_t RemoteConfigObserverStub::OnRemoteRequest( uint32_t [MASK] , MessageParcel &data, MessageParcel &reply, MessageOption &option) { std::string bundleName; std::u16string descriptor = RemoteConfigObserverStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { OAID_HILOGE(OAID_MODULE_SERVICE, ""read descriptor failed.""); return ERR_INVALID_PARAM; } switch ( [MASK] ) { case static_cast(RegisterObserverCode::OnOaidUpdated): { return HandleOAIDUpdate(data, reply); } default: return IPCObjectStub::OnRemoteRequest( [MASK] , data, reply, option); } } int32_t RemoteConfigObserverStub::HandleOAIDUpdate(MessageParcel &data, MessageParcel &reply) { std::string oaid; if (!data.ReadString(oaid)) { OAID_HILOGE(OAID_MODULE_SERVICE, ""parcel read value failed.""); return ERR_INVALID_PARAM; } OnOaidUpdated(oaid); return ERR_OK; } } // namespace Cloud } // namespace OHOS",code 92,"/* * Copyright (c) 2022 Huawei Device Co., Ltd. * 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 ""js_convertxml.h"" #include ""securec.h"" #include ""utils/log.h"" namespace OHOS::Xml { ConvertXml::ConvertXml() { spaceType_ = SpaceType::T_INIT; strSpace_ = """"; iSpace_ = 0; } std::string ConvertXml::GetNodeType(const xmlElementType enumType) const { std::string strResult = """"; switch (enumType) { case xmlElementType::XML_ELEMENT_NODE: strResult = ""element""; break; case xmlElementType::XML_ATTRIBUTE_NODE: strResult = ""attribute""; break; case xmlElementType::XML_TEXT_NODE: strResult = ""text""; break; case xmlElementType::XML_CDATA_SECTION_NODE: strResult = ""cdata""; break; case xmlElementType::XML_ENTITY_REF_NODE: strResult = ""entity_ref""; break; case xmlElementType::XML_ENTITY_NODE: strResult = ""entity""; break; case xmlElementType::XML_PI_NODE: strResult = ""instruction""; break; case xmlElementType::XML_COMMENT_NODE: strResult = ""comment""; break; case xmlElementType::XML_DOCUMENT_NODE: strResult = ""document""; break; case xmlElementType::XML_DOCUMENT_TYPE_NODE: strResult = ""document_type""; break; case xmlElementType::XML_DOCUMENT_FRAG_NODE: strResult = ""document_frag""; break; case xmlElementType::XML_DTD_NODE: strResult = ""doctype""; break; #ifdef LIBXML_DOCB_ENABLED case xmlElementType::XML_DOCB_DOCUMENT_NODE: strResult = ""docb_document""; break; #endif default: break; } return strResult; } void ConvertXml::SetKeyValue(napi_env env, const napi_value &object, const std::string strKey, const std::string strValue) const { napi_value attrValue = nullptr; napi_create_string_utf8(env, strValue.c_str(), NAPI_AUTO_LENGTH, &attrValue); napi_set_named_property(env, object, strKey.c_str(), attrValue); } std::string ConvertXml::Trim(std::string strXmltrim) const { if (strXmltrim.empty()) { return """"; } size_t i = 0; size_t strlen = strXmltrim.size(); for (; i < strlen;) { if (strXmltrim[i] == ' ') { i++; } else { break; } } strXmltrim = strXmltrim.substr(i); strlen = strXmltrim.size(); for (i = strlen - 1; i != 0; i--) { if (strXmltrim[i] == ' ') { strXmltrim.pop_back(); } else { break; } } return strXmltrim; } void ConvertXml::GetPrevNodeList(napi_env env, xmlNodePtr curNode) { while (curNode->prev != nullptr) { curNode = curNode->prev; napi_value elementsObject = nullptr; napi_create_object(env, &elementsObject); char *curContent = nullptr; if (curNode->type == xmlElementType::XML_PI_NODE && !options_.ignoreInstruction) { SetKeyValue(env, elementsObject, options_.type, GetNodeType(curNode->type)); SetKeyValue(env, elementsObject, options_.name, reinterpret_cast(curNode->name)); curContent = reinterpret_cast(xmlNodeGetContent(curNode)); if (curContent != nullptr) { SetKeyValue(env, elementsObject, options_.instruction, curContent); xmlFree(reinterpret_cast(curContent)); } prevObj_.push_back(elementsObject); } if (curNode->type == xmlElementType::XML_COMMENT_NODE && !options_.ignoreComment) { SetKeyValue(env, elementsObject, options_.type, GetNodeType(curNode->type)); curContent = reinterpret_cast(xmlNodeGetContent(curNode)); if (curContent != nullptr) { SetKeyValue(env, elementsObject, options_.comment, curContent); xmlFree(reinterpret_cast(curContent)); } prevObj_.push_back(elementsObject); } if (curNode->type == xmlElementType::XML_DTD_NODE && !options_.ignoreDoctype) { SetKeyValue(env, elementsObject, options_.type, GetNodeType(curNode->type)); SetKeyValue(env, elementsObject, options_.doctype, reinterpret_cast(curNode->name)); prevObj_.push_back(elementsObject); } } } void ConvertXml::SetAttributes(napi_env env, xmlNodePtr curNode, const napi_value &elementsObject) const { xmlAttr *attr = curNode->properties; if (attr && !options_.ignoreAttributes) { napi_value attrTitleObj = nullptr; napi_create_object(env, &attrTitleObj); while (attr) { SetKeyValue(env, attrTitleObj, reinterpret_cast(attr->name), reinterpret_cast(attr->children->content)); attr = attr->next; } napi_set_named_property(env, elementsObject, options_.attributes.c_str(), attrTitleObj); } } void ConvertXml::SetXmlElementType(napi_env env, xmlNodePtr curNode, const napi_value &elementsObject, bool &bFlag) const { char *curContent = reinterpret_cast(xmlNodeGetContent(curNode)); if (curNode->type == xmlElementType::XML_PI_NODE && !options_.ignoreInstruction) { if (curContent != nullptr) { SetKeyValue(env, elementsObject, options_.instruction.c_str(), curContent); bFlag = true; } } else if (curNode->type == xmlElementType::XML_COMMENT_NODE && !options_.ignoreComment) { if (curContent != nullptr) { SetKeyValue(env, elementsObject, options_.comment.c_str(), curContent); bFlag = true; } } else if (curNode->type == xmlElementType::XML_CDATA_SECTION_NODE && !options_.ignoreCdata) { if (curContent != nullptr) { SetKeyValue(env, elementsObject, options_.cdata, curContent); bFlag = true; } } if (curContent != nullptr) { xmlFree(reinterpret_cast(curContent)); } } void ConvertXml::SetNodeInfo(napi_env env, xmlNodePtr curNode, const napi_value &elementsObject) const { if (curNode->type == xmlElementType::XML_TEXT_NODE) { return; } else { if (curNode->type == xmlElementType::XML_PI_NODE) { if (!options_.ignoreInstruction) { SetKeyValue(env, elementsObject, options_.type, GetNodeType(curNode->type)); } } else { SetKeyValue(env, elementsObject, options_.type, GetNodeType(curNode->type)); } if ((curNode->type != xmlElementType::XML_COMMENT_NODE) && (curNode->type != xmlElementType::XML_CDATA_SECTION_NODE)) { if (!(curNode->type == xmlElementType::XML_PI_NODE && options_.ignoreInstruction)) { SetKeyValue(env, elementsObject, options_.name, reinterpret_cast(curNode->name)); } } } } void ConvertXml::SetEndInfo(napi_env env, xmlNodePtr curNode, const napi_value &elementsObject, bool &bFlag) const { SetKeyValue(env, elementsObject, options_.type, GetNodeType(curNode->type)); if (curNode->type == xmlElementType::XML_ELEMENT_NODE) { SetKeyValue(env, elementsObject, options_.name.c_str(), reinterpret_cast(curNode->name)); bFlag = true; } else if (curNode->type == xmlElementType::XML_TEXT_NODE) { char *curContent = reinterpret_cast(xmlNodeGetContent(curNode)); if (options_.trim) { if (curContent != nullptr) { SetKeyValue(env, elementsObject, options_.text, Trim(curContent)); } } else { if (curContent != nullptr) { SetKeyValue(env, elementsObject, options_.text, curContent); } } if (curContent != nullptr) { xmlFree(reinterpret_cast(curContent)); } if (!options_.ignoreText) { bFlag = true; } } } void ConvertXml::SetPrevInfo(napi_env env, const napi_value &recvElement, int flag, int32_t &index1) const { if (!prevObj_.empty() && !flag) { for (size_t i = (prevObj_.size() - 1); i > 0; --i) { napi_set_element(env, recvElement, index1++, prevObj_[i]); } napi_set_element(env, recvElement, index1++, prevObj_[0]); } } void ConvertXml::GetXMLInfo(napi_env env, xmlNodePtr curNode, const napi_value &object, int flag) { napi_value elements = nullptr; napi_create_array(env, &elements); napi_value recvElement = nullptr; napi_create_array(env, &recvElement); xmlNodePtr pNode = curNode; int32_t index = 0; int32_t index1 = 0; bool bFlag = false; while (pNode != nullptr) { bFlag = false; napi_value elementsObject = nullptr; napi_create_object(env, &elementsObject); SetNodeInfo(env, pNode, elementsObject); SetAttributes(env, pNode, elementsObject); napi_value tempElement = nullptr; napi_create_array(env, &tempElement); napi_value elementObj = nullptr; napi_create_object(env, &elementObj); char *curContent = reinterpret_cast(xmlNodeGetContent(pNode)); if (curContent != nullptr) { if (pNode->children != nullptr) { curNode = pNode->children; GetXMLInfo(env, curNode, elementsObject, 1); bFlag = true; } else { SetXmlElementType(env, pNode, elementsObject, bFlag); SetEndInfo(env, pNode, elementsObject, bFlag); } xmlFree(reinterpret_cast(curContent)); } SetPrevInfo(env, recvElement, flag, index1); if (elementsObject != nullptr && bFlag) { napi_set_element(env, recvElement, index1++, elementsObject); elementsObject = nullptr; } index++; pNode = pNode->next; } if (bFlag) { napi_set_named_property(env, object, options_.elements.c_str(), recvElement); } } void ConvertXml::SetSpacesInfo(napi_env env, const napi_value &object) const { napi_value iTemp = nullptr; switch (spaceType_) { case (SpaceType::T_INT32): napi_create_int32(env, iSpace_, &iTemp); napi_set_named_property(env, object, ""spaces"", iTemp); break; case (SpaceType::T_STRING): SetKeyValue(env, object, ""spaces"", strSpace_); break; case (SpaceType::T_INIT): SetKeyValue(env, object, ""spaces"", strSpace_); break; default: break; } } napi_value ConvertXml::Convert(napi_env env, std::string strXml) { xmlDocPtr doc = nullptr; xmlNodePtr curNode = nullptr; napi_status status = napi_ok; napi_value object = nullptr; status = napi_create_object(env, &object); if (status != napi_ok) { return nullptr; } Replace(strXml, ""\\r"", ""\r""); Replace(strXml, ""\\n"", ""\n""); Replace(strXml, ""\\v"", ""\v""); Replace(strXml, ""\\t"", ""\t""); Replace(strXml, ""]]> version != nullptr) { SetKeyValue(env, subSubObject, ""version"", (const char*)doc->version); } if (doc != nullptr && doc->encoding != nullptr) { SetKeyValue(env, subSubObject, ""encoding"", (const char*)doc->encoding); } if (!options_.ignoreDeclaration && strXml.find(""xml"") != std::string::npos) { napi_set_named_property(env, subObject, options_.attributes.c_str(), subSubObject); napi_set_named_property(env, object, options_.declaration.c_str(), subObject); } if (doc != nullptr) { curNode = xmlDocGetRootElement(doc); GetPrevNodeList(env, curNode); GetXMLInfo(env, curNode, object, 0); } SetSpacesInfo(env, object); return object; } napi_status ConvertXml::DealNapiStrValue(napi_env env, const napi_value napi_StrValue, std::string &result) const { std::string buffer = """"; size_t bufferSize = 0; napi_status status = napi_ok; status = napi_get_value_string_utf8(env, napi_StrValue, nullptr, -1, &bufferSize); if (status != napi_ok) { HILOG_ERROR(""can not get buffer size""); return status; } buffer.reserve(bufferSize + 1); buffer.resize(bufferSize); if (bufferSize > 0) { status = napi_get_value_string_utf8(env, napi_StrValue, buffer.data(), bufferSize + 1, &bufferSize); if (status != napi_ok) { HILOG_ERROR(""can not get buffer value""); return status; } } if (buffer.data() != nullptr) { result = buffer; } return status; } void ConvertXml::DealSpaces(napi_env env, const napi_value napiObj) { napi_value recvTemp = nullptr; napi_get_named_property(env, napiObj, ""spaces"", &recvTemp); napi_valuetype valuetype = napi_undefined; napi_typeof(env, recvTemp, &valuetype); if (valuetype == napi_string) { DealNapiStrValue(env, recvTemp, strSpace_); spaceType_ = SpaceType::T_STRING; } else if (valuetype == napi_number) { int32_t iTemp; if (napi_get_value_int32(env, recvTemp, &iTemp) == napi_ok) { iSpace_ = iTemp; spaceType_ = SpaceType::T_INT32; } } } void ConvertXml::DealIgnore(napi_env env, const napi_value napiObj) { std::vector vctIgnore = {""compact"", ""trim"", ""ignoreDeclaration"", ""ignoreInstruction"", ""ignoreAttributes"", ""ignoreComment"", ""ignoreCDATA"", ""ignoreDoctype"", ""ignoreText""}; size_t vctLength = vctIgnore.size(); for (size_t i = 0; i < vctLength; ++i) { napi_value recvTemp = nullptr; bool bRecv = false; napi_get_named_property(env, napiObj, vctIgnore[i].c_str(), &recvTemp); if ((napi_get_value_bool(env, recvTemp, &bRecv)) == napi_ok) { switch (i) { case 0: options_.compact = bRecv; break; case 1: // 1:trim options_.trim = bRecv; break; case 2: // 2:ignoreDeclaration options_.ignoreDeclaration = bRecv; break; case 3: // 3:ignoreInstruction options_.ignoreInstruction = bRecv; break; case 4: // 4:ignoreAttributes options_.ignoreAttributes = bRecv; break; case 5: // 5:ignoreComment options_.ignoreComment = bRecv; break; case 6: // 6:ignoreCdata options_.ignoreCdata = bRecv; break; case 7: // 7:ignoreDoctype options_.ignoreDoctype = bRecv; break; case 8: // 8:ignoreText options_.ignoreText = bRecv; break; default: break; } } } } void ConvertXml::SetDefaultKey(size_t i, const std::string strRecv) { switch (i) { case 0: options_.declaration = strRecv; break; case 1: options_.instruction = strRecv; break; case 2: // 2:attributes options_.attributes = strRecv; break; case 3: // 3:text options_.text = strRecv; break; case 4: // 4:cdata options_.cdata = strRecv; break; case 5: // 5:doctype options_.doctype = strRecv; break; case 6: // 6:comment options_.comment = strRecv; break; case 7: // 7:parent options_.parent = strRecv; break; case 8: // 8:type options_.type = strRecv; break; case 9: // 9:name options_.name = strRecv; break; case 10: // 10:elements options_.elements = strRecv; break; default: break; } } void ConvertXml::DealOptions(napi_env env, const napi_value napiObj) { std::vector vctOptions = {""declarationKey"", ""instructionKey"", ""attributesKey"", ""textKey"", ""cdataKey"", ""doctypeKey"", ""commentKey"", ""parentKey"", ""typeKey"", ""nameKey"", ""elementsKey""}; size_t vctLength = vctOptions.size(); for (size_t i = 0; i < vctLength; ++i) { napi_value recvTemp = nullptr; std::string strRecv = """"; napi_get_named_property(env, napiObj, vctOptions[i].c_str(), &recvTemp); if ((DealNapiStrValue(env, recvTemp, strRecv)) == napi_ok) { SetDefaultKey(i, strRecv); } } DealIgnore(env, napiObj); DealSpaces(env, napiObj); } void ConvertXml::DealSingleLine(napi_env env, std::string &strXml, const napi_value &object) { size_t iXml = 0; if ((iXml = strXml.find(""xml"")) != std::string::npos) { xmlInfo_.bXml = true; napi_value declObj = nullptr; napi_create_object(env, &declObj); napi_value attrObj = nullptr; bool bFlag = false; napi_create_object(env, &attrObj); if (strXml.find(""version="") != std::string::npos) { xmlInfo_.bVersion = true; SetKeyValue(env, attrObj, ""version"", ""1.0""); bFlag = true; } if (strXml.find(""encoding="") != std::string::npos) { xmlInfo_.bEncoding = false; SetKeyValue(env, attrObj, ""encoding"", ""utf-8""); bFlag = true; } if (bFlag) { napi_set_named_property(env, declObj, options_.attributes.c_str(), attrObj); napi_set_named_property(env, object, options_.declaration.c_str(), declObj); } else { napi_set_named_property(env, object, options_.declaration.c_str(), declObj); } if (strXml.find("">"", iXml) == strXml.size() - 1) { strXml = """"; } else { strXml = strXml.substr(0, strXml.rfind(""<"", iXml)) + strXml.substr(strXml.find("">"", iXml) + 1); } } size_t [MASK] = 0; size_t iLen = strXml.size(); for (; [MASK] < iLen; ++ [MASK] ) { if (strXml[ [MASK] ] != ' ' && strXml[ [MASK] ] != '\v' && strXml[ [MASK] ] != '\t' && strXml[ [MASK] ] != '\n') { break; } } if ( [MASK] < iLen) { DealComplex(env, strXml, object); } } void ConvertXml::DealComplex(napi_env env, std::string &strXml, const napi_value &object) const { if (strXml.find(""""; } else { strXml = """" + strXml + """"; } xmlDocPtr doc = nullptr; xmlNodePtr curNode = nullptr; size_t len = strXml.size(); doc = xmlParseMemory(strXml.c_str(), static_cast(len)); if (!doc) { xmlFreeDoc(doc); } if (doc) { curNode = xmlDocGetRootElement(doc); curNode = curNode->children; napi_value elements = nullptr; napi_create_array(env, &elements); bool bHasEle = false; int index = 0; bool bCData = false; if (strXml.find(""type == xmlElementType::XML_CDATA_SECTION_NODE && curNode->next && curNode->next->type == xmlElementType::XML_TEXT_NODE && curNode->next->next && curNode->next->next->type == xmlElementType::XML_CDATA_SECTION_NODE) { char *curContent = reinterpret_cast(xmlNodeGetContent(curNode->next)); if (curContent != nullptr) { std::string strTemp = reinterpret_cast(curContent); Replace(strTemp, "" "", """"); Replace(strTemp, ""\v"", """"); Replace(strTemp, ""\t"", """"); Replace(strTemp, ""\n"", """"); if (strTemp == """") { curNode = curNode->next->next; } xmlFree(reinterpret_cast(curContent)); } } else { curNode = curNode->next; } } } // namespace OHOS::Xml ",iCount 93,"/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_OBJECTIVE_RANK_OBJECTIVE_HPP_ #define LIGHTGBM_OBJECTIVE_RANK_OBJECTIVE_HPP_ #include #include #include #include #include #include #include #include #include namespace LightGBM { /*! * \brief Objective function for Lambdrank with NDCG */ class LambdarankNDCG: public ObjectiveFunction { public: explicit LambdarankNDCG(const Config& config) { sigmoid_ = static_cast(config.sigmoid); label_gain_ = config.label_gain; // initialize DCG calculator DCGCalculator::DefaultLabelGain(&label_gain_); DCGCalculator::Init(label_gain_); // will optimize NDCG@optimize_pos_at_ optimize_pos_at_ = config.max_position; sigmoid_table_.clear(); inverse_max_dcgs_.clear(); if (sigmoid_ <= 0.0) { Log::Fatal(""Sigmoid param %f should be greater than zero"", sigmoid_); } } explicit LambdarankNDCG(const std::vector&) { } ~LambdarankNDCG() { } void Init(const Metadata& metadata, data_size_t num_data) override { num_data_ = num_data; // get label label_ = metadata.label(); DCGCalculator::CheckLabel(label_, num_data_); // get weights weights_ = metadata.weights(); // get boundries query_boundaries_ = metadata.query_boundaries(); if (query_boundaries_ == nullptr) { Log::Fatal(""Lambdarank tasks require query information""); } num_queries_ = metadata.num_queries(); // cache inverse max DCG, avoid computation many times inverse_max_dcgs_.resize(num_queries_); #pragma omp parallel for schedule(static) for (data_size_t i = 0; i < num_queries_; ++i) { inverse_max_dcgs_[i] = DCGCalculator::CalMaxDCGAtK(optimize_pos_at_, label_ + query_boundaries_[i], query_boundaries_[i + 1] - query_boundaries_[i]); if (inverse_max_dcgs_[i] > 0.0) { inverse_max_dcgs_[i] = 1.0f / inverse_max_dcgs_[i]; } } // construct sigmoid table to speed up sigmoid transform ConstructSigmoidTable(); } void GetGradients(const double* score, score_t* gradients, score_t* hessians) const override { #pragma omp parallel for schedule(guided) for (data_size_t i = 0; i < num_queries_; ++i) { GetGradientsForOneQuery(score, gradients, hessians, i); } } // grank with fixed size bucket inline void GetGradientsForOneQuery(const double* score, score_t* lambdas, score_t* hessians, data_size_t query_id) const { // get doc boundary for current query const data_size_t start = query_boundaries_[query_id]; const data_size_t cnt = query_boundaries_[query_id + 1] - query_boundaries_[query_id]; // get max DCG on current query // const double inverse_max_dcg = inverse_max_dcgs_[query_id]; // add pointers with offset const label_t* label = label_ + start; score += start; lambdas += start; hessians += start; // initialize with zero for (data_size_t i = 0; i < cnt; ++i) { lambdas[i] = 0.0f; hessians[i] = 0.0f; } label_t all_ratings[5]; label_t worst_label = 5; label_t best_label = 0; // get sorted indices for scores std::vector sorted_idx; for (int i = 0; i < cnt; ++i) { sorted_idx.emplace_back(i); all_ratings[static_cast(label[i])] = 1; if (label[i] < worst_label) { worst_label = label[i]; } if (label[i] > best_label) { best_label = label[i]; } } // calculate the discount for all ratings // if all_ratings[i] == 0, no such rating for this query, discount = 0 int position = 0; for (data_size_t i = 4; i >= 0; --i) { if (all_ratings[i]) { all_ratings[i] = DCGCalculator::GetDiscount(position); position++; } } if (best_label == worst_label) {return; } std::stable_sort(sorted_idx.begin(), sorted_idx.end(), [score](data_size_t a, data_size_t b) { return score[a] > score[b]; }); // get best and worst score const double best_score = score[sorted_idx[0]]; data_size_t [MASK] = cnt - 1; if ( [MASK] > 0 && score[sorted_idx[ [MASK] ]] == kMinScore) { [MASK] -= 1; } const double worst_score = score[sorted_idx[ [MASK] ]]; // get max DCG on current query const double inverse_max_dcg = inverse_max_dcgs_[query_id]; const int bucket_size = 2; const double sigma = 2.0f; // start accmulate lambdas by pairs for (data_size_t i = 0; i < cnt; ++i) { const data_size_t high = sorted_idx[i]; const int high_label = static_cast(label[high]); const double high_score = score[high]; if (high_score == kMinScore || high_label == worst_label) { continue; } const double high_label_gain = label_gain_[high_label]; const double high_discount = DCGCalculator::GetDiscount(i); double exp_high_score = std::exp(sigma * (high_score-best_score)); double sum_exp_low_score = 0.0; double high_sum_lambda = 0.0; double high_sum_hessian = 0.0; int num_low = 0; std::vector sum_exp_low_scores; for (data_size_t j = 0; j < cnt; ++j) { // skip same data if (i == j) { continue; } const data_size_t low = sorted_idx[j]; const int low_label = static_cast(label[low]); const double low_score = score[low]; // only consider pair with different label if (low_label < high_label && low_score > kMinScore) { sum_exp_low_score += std::exp(sigma * (low_score-best_score)); num_low++; } if (num_low == bucket_size) { sum_exp_low_scores.push_back(sum_exp_low_score); sum_exp_low_score = 0.0; num_low = 0; } } if (num_low < bucket_size) { sum_exp_low_scores.push_back(sum_exp_low_score); } num_low = 0; for (data_size_t j = 0; j < cnt; ++j) { // skip same data if (i == j) { continue; } const data_size_t low = sorted_idx[j]; const int low_label = static_cast(label[low]); const double low_score = score[low]; // only consider pair with different label if (low_label < high_label && low_score > kMinScore) { sum_exp_low_score = sum_exp_low_scores.at(num_low / bucket_size); num_low++; if (sum_exp_low_score == 0.0) {continue; } const double low_label_gain = label_gain_[low_label]; const double low_discount = DCGCalculator::GetDiscount(j); // get dcg gap const double dcg_gap = high_label_gain - low_label_gain; // get discount of this pair const double paired_discount = fabs(high_discount - low_discount); const double delta_score = high_score - low_score; double sum_exp = exp_high_score + sum_exp_low_score; double p_high = exp_high_score / sum_exp; double exp_low_score = std::exp(sigma * (low_score-best_score)); double p_low = exp_low_score / sum_exp; double l_p_lambda = p_low * sigma;//positive double l_p_hessian = l_p_lambda * (1 - p_low) * sigma * sigma; double fancy = dcg_gap * paired_discount * inverse_max_dcg; // regular the delta_pair_NDCG by score distance if (high_label != low_label && best_score != worst_score) { fancy /= (0.01f + fabs(delta_score)); } l_p_lambda *= fancy; l_p_hessian *= fancy; lambdas[low] += static_cast(l_p_lambda); hessians[low] += static_cast(l_p_hessian); high_sum_lambda += -l_p_lambda; high_sum_hessian += l_p_lambda * p_high * sigma * sigma;//positive } } lambdas[high] += static_cast(high_sum_lambda); hessians[high] += static_cast(high_sum_hessian); } // if need weights if (weights_ != nullptr) { for (data_size_t i = 0; i < cnt; ++i) { lambdas[i] = static_cast(lambdas[i] * weights_[start + i]); hessians[i] = static_cast(hessians[i] * weights_[start + i]); } } } inline double GetSigmoid(double score) const { if (score <= min_sigmoid_input_) { // too small, use lower bound return sigmoid_table_[0]; } else if (score >= max_sigmoid_input_) { // too big, use upper bound return sigmoid_table_[_sigmoid_bins - 1]; } else { return sigmoid_table_[static_cast((score - min_sigmoid_input_) * sigmoid_table_idx_factor_)]; } } void ConstructSigmoidTable() { // get boundary min_sigmoid_input_ = min_sigmoid_input_ / sigmoid_ / 2; max_sigmoid_input_ = -min_sigmoid_input_; sigmoid_table_.resize(_sigmoid_bins); // get score to bin factor sigmoid_table_idx_factor_ = _sigmoid_bins / (max_sigmoid_input_ - min_sigmoid_input_); // cache for (size_t i = 0; i < _sigmoid_bins; ++i) { const double score = i / sigmoid_table_idx_factor_ + min_sigmoid_input_; sigmoid_table_[i] = 2.0f / (1.0f + std::exp(2.0f * score * sigmoid_)); } } const char* GetName() const override { return ""lambdarank""; } std::string ToString() const override { std::stringstream str_buf; str_buf << GetName(); return str_buf.str(); } bool NeedAccuratePrediction() const override { return false; } private: /*! \brief Gains for labels */ std::vector label_gain_; /*! \brief Cache inverse max DCG, speed up calculation */ std::vector inverse_max_dcgs_; /*! \brief Simgoid param */ double sigmoid_; /*! \brief Optimized NDCG@ */ int optimize_pos_at_; /*! \brief Number of queries */ data_size_t num_queries_; /*! \brief Number of data */ data_size_t num_data_; /*! \brief Pointer of label */ const label_t* label_; /*! \brief Pointer of weights */ const label_t* weights_; /*! \brief Query boundries */ const data_size_t* query_boundaries_; /*! \brief Cache result for sigmoid transform to speed up */ std::vector sigmoid_table_; /*! \brief Number of bins in simoid table */ size_t _sigmoid_bins = 1024 * 1024; /*! \brief Minimal input of sigmoid table */ double min_sigmoid_input_ = -50; /*! \brief Maximal input of sigmoid table */ double max_sigmoid_input_ = 50; /*! \brief Factor that covert score to bin in sigmoid table */ double sigmoid_table_idx_factor_; }; } // namespace LightGBM #endif // LightGBM_OBJECTIVE_RANK_OBJECTIVE_HPP_ ",worst_idx 94,"#include ""CineXDetailCustomization.h"" #include ""PropertyEditing.h"" #include ""Widgets/Input/SButton.h"" #include ""Widgets/Text/STextBlock.h"" #include ""Widgets/Input/SComboButton.h"" TSharedRef FCineXDetailCustomization::MakeInstance() { return MakeShareable(new FCineXDetailCustomization); } void FCineXDetailCustomization::CustomizeDetails(IDetailLayoutBuilder& DetailBuilder) { TSet [MASK] ; TArray> ObjectsBeingCustomized; DetailBuilder.GetObjectsBeingCustomized(/*out*/ ObjectsBeingCustomized); for (auto WeakObject : ObjectsBeingCustomized) { if (UObject* Instance = WeakObject.Get()) { [MASK] .Add(Instance->GetClass()); } } //Create commands category IDetailCategoryBuilder& Category = DetailBuilder.EditCategory(""Connection""); //Create button for each element for (UClass* Class : [MASK] ) { for (TFieldIterator FuncIt(Class); FuncIt; ++FuncIt) { UFunction* Function = *FuncIt; if (Function->HasAnyFunctionFlags(FUNC_Exec) && (Function->NumParms == 0)) { const FString FunctionName = Function->GetName(); const FText ButtonCaption = FText::FromString(FunctionName); Category.AddCustomRow(ButtonCaption) .ValueContent() [ SNew(SButton) .Text(ButtonCaption) .OnClicked(FOnClicked::CreateStatic(&FCineXDetailCustomization::ExecuteCommand, &DetailBuilder, Function)) ]; } } } } FReply FCineXDetailCustomization::ExecuteCommand(IDetailLayoutBuilder * DetailBuilder, UFunction * MethodToExecute) { TArray> ObjectsBeingCustomized; DetailBuilder->GetObjectsBeingCustomized(/*out*/ ObjectsBeingCustomized); for (auto WeakObject : ObjectsBeingCustomized) { if (UObject* Instance = WeakObject.Get()) { Instance->CallFunctionByNameWithArguments(*MethodToExecute->GetName(), *GLog, nullptr, true); } } return FReply::Handled(); }",Classes 95,"#include #include ""Ball.h"" #include ""Paddle.h"" const float defaultVVelocity = 0.002; const float defaultHVelocity = 0.015; const float defaultRadius = 0.05; const float paddleAccelerationFactor = 0.3; const float twoPi = 3.14159*2; Ball::Ball(int triangleCount) { m_triangleCount = triangleCount; reset(); } void Ball::tick() { m_x += m_vx; m_y += m_vy; bounceVertically(); } void Ball::reset() { m_x = 0; m_y = 0; m_vx = defaultHVelocity; m_vy = defaultVVelocity; m_r = defaultRadius; } void Ball::collideWithPaddle(Paddle paddle) { Paddle::Coords paddleCoords = paddle.getCoords(); float x = m_vx > 0 ? paddleCoords.x1 : paddleCoords.x2; float y_top = paddleCoords.y1; float y_bot = paddleCoords.y2; // miss: do nothing, avoid calculations below if (y_top < m_y - m_r || y_bot > m_y + m_r) return; // Can only collide if the x-position is within the ball's range if (x >= m_x - m_r && x <= m_x + m_r) { // flat bounce, just reverse horizontal velocity if (m_y <= y_top && m_y >=y_bot) { m_vx = -m_vx; addPaddleVelocity(paddle.getVelocity()); } else if (collidesWith(x, y_top)) { bounceOnPoint(x, y_top); addPaddleVelocity(paddle.getVelocity()); } else if (collidesWith(x, y_bot)) { bounceOnPoint(x, y_bot); addPaddleVelocity(paddle.getVelocity()); } } } void Ball::addPaddleVelocity(float paddleVelocity) { m_vy += paddleAccelerationFactor * paddleVelocity; } bool Ball::collidesWith(float x, float y) { return pow(x - m_x, 2) + pow(y - m_y, 2) <= pow(m_r, 2); } void Ball::bounceOnPoint(float x, float y) { // angle is from contact point to ball float angle = atan2(m_y- y, m_x - x); // maintain the same total velocity along the new angle: // todo: add paddle speed component? float [MASK] = sqrt(pow(m_vy, 2) + pow(m_vx, 2)); m_vx = [MASK] * cos(angle); m_vy = [MASK] * sin(angle); } bool Ball::touches(float x) { return m_x - m_r <= x && m_x + m_r >= x; } void Ball::bounceVertically() { if (m_y + m_r >= 1 || m_y- m_r <= -1) { m_vy = -m_vy; } } void Ball::assignIndices(int * index, unsigned int * indexArray, unsigned int vertexOffset) { for (int j = 0; j < m_triangleCount; j++) { indexArray[(*index)++] = vertexOffset; indexArray[(*index)++] = vertexOffset + j; indexArray[(*index)++] = vertexOffset + j + 1; } // the final triangle index should be the first vertex on the circle of the ball indexArray[(*index) - 1] = vertexOffset + 1; } void Ball::assignVertices(int * index, float * vertexArray) { vertexArray[(*index)++] = m_x; vertexArray[(*index)++] = m_y; for (int j = 0; j < m_triangleCount; j++) { vertexArray[(*index)++] = m_x + (m_r * cos(j * twoPi / m_triangleCount)); vertexArray[(*index)++] = m_y + (m_r * sin(j * twoPi / m_triangleCount)); } } ",current_velocity 96,"#ifdef _WIN32 #include #else #include #endif #include #include #include #include ""config.hpp"" #include ""Terrain.hpp"" #include ""Drone.hpp"" #include ""Menu.hpp"" #include ""Scene.hpp"" bool DISPLAY = true; enum Draw{ goToDraw }; int main() { { bool finish = false; /* -------------------------------------------------------------------------- */ /* INIT INFORMATIONS */ /* -------------------------------------------------------------------------- */ std::cout << ""Project Rotation 3D based on C++ Boiler Plate by v"" << PROJECT_VERSION_MAJOR /*duże zmiany, najczęściej brak kompatybilności wstecz */ << ""."" << PROJECT_VERSION_MINOR /* istotne zmiany */ << ""."" << PROJECT_VERSION_PATCH /* naprawianie bugów */ << ""."" << PROJECT_VERSION_TWEAK /* zmiany estetyczne itd. */ << std::endl; std::system(""cat ./LICENSE""); std::system(""pwd""); std::cout << ""Press enter to start..."" << std::endl << std::endl << std::endl; std::cin.ignore(std::numeric_limits().max(), '\n'); /* -------------------------------------------------------------------------- */ /* CREATING FIGURES */ /* -------------------------------------------------------------------------- */ Scene scene; std::thread displaying([&scene, &finish]() { auto start = std::chrono::high_resolution_clock::now(); while(!finish){ auto measure = std::chrono::high_resolution_clock::now(); auto elapsed = std::chrono::duration_cast(measure - start); try{ if(elapsed.count() >= (100)){ start = std::chrono::high_resolution_clock::now(); throw Draw::goToDraw; } } catch(Draw){ scene.Update(); // std::cout << ""\n\nCounting Vectors..."" << std::endl; // std::cout << ""==========================================="" << std::endl; // std::cout << std::setw(35) << ""Number of Vectors on Scene: "" << std::setw(10) << Vector3::HowManyObjects() << std::endl; // std::cout << std::setw(35) << ""Number of Vectors from start: "" << std::setw(10) << Vector3::AllHowManyObjects() << std::endl; // std::cout << ""==========================================="" << std::endl // << std::endl // << std::endl; } } }); std::shared_ptr drone; std::shared_ptr floor = std::make_shared(); scene.Add(std::move (floor)); /* -------------------------------------------------------------------------- */ /* MENU CONSTRUCTOR */ /* -------------------------------------------------------------------------- */ std::vector rotationSequece; Menu menu({{""Print informations about selected object: "", [&drone]() mutable { if (drone == nullptr) throw std::logic_error(""Did not choosed the active object.""); std::cout << drone->SeflID() << "" "" << drone->Name() << std::endl; std::cout << ""position: \n"" << drone->position << ""\neuler anglesRPY: \n"" << drone->anglesRPY << ""\nrotation Matrix: \n"" << drone->orientation; }}, {""Add Drone: "", [&scene]() { std::cout << ""Where spawn drone Vector3: \n""; Vector3 pos; std::cin >> pos; std::shared_ptr [MASK] = std::make_shared(pos); scene.Add(std::move( [MASK] )); }}, {""Choose active drone: "", [&drone, &scene]() { // std::cout << ""There are "" << scene.CountObjects() << "" on scene. Type number. 1 - n"" << std::endl; int d = 1; for (std::size_t i = 0; i < scene.CountObjects(); ++i) { auto localPtr = std::dynamic_pointer_cast(scene[i]); if (localPtr != nullptr) { if (localPtr == drone) std::cout << ""* ""; else std::cout << "" ""; std::cout << d++ << "" Drone is on position: "" << localPtr->position << std::endl; } } std::cout << ""Type number of Drone"" << std::endl; std::size_t k = 1; std::cin >> k; drone->ChangeColor(1); drone = std::dynamic_pointer_cast(scene.SelectDrone(k)); drone->ChangeColor(2); }}, {""Move drone"", [&drone]() { if (drone == nullptr) throw std::logic_error(""Did not choosed the active object.""); std::cout << ""Type height, angle and length of move."" << std::endl; Vector3 pos; std::cin >> pos; if(pos[0] != 0) drone->moves.push([pos, drone]() { drone->GoVerdical(pos[0] ); }); if (pos[1] != 0) drone->moves.push([pos, drone]() { drone->Right(pos[1]); }); if (pos[2] != 0) drone->moves.push([pos, drone]() { drone->Forward(pos[2]); }); if (pos[0] != 0) drone->moves.push([pos, drone]() { drone->GoVerdical(pos[0] * -1); }); drone->MakeRoute(pos[0], pos[1], pos[2]); }}, {""Recognize flight"", [&drone]() { if (drone == nullptr) throw std::logic_error(""Did not choosed the active object.""); std::cout << ""Type height, angle and length of move."" << std::endl; drone->moves.push([&drone]() { drone->GoVerdical(150); }); for (int i = 0; i < 30; ++i){ drone->moves.push([drone]() { drone->Right(360 / 20); drone->Forward(10); }); } drone->moves.push([ drone]() { drone->GoVerdical(150 * -1); }); // drone->MakeRoute(pos[0], pos[1], pos[2]); }}, {""Exit"", [&finish, &scene]() { finish = true; throw std::logic_error(""Exit""); }}}); scene.Add(std::move(std::make_shared(Vector3({200, 200, 0})))); scene.Add(std::move(std::make_shared(Vector3({200, -200, 0})))); drone = std::dynamic_pointer_cast(scene.SelectDrone(1)); drone->ChangeColor(2); /* -------------------------------------------------------------------------- */ /* MAIN LOOP */ /* -------------------------------------------------------------------------- */ std::thread menuig([&menu, &drone, &finish, &scene]() { while (!finish) { std::cout << ""\n\nCounting Vectors..."" << std::endl; std::cout << ""==========================================="" << std::endl; std::cout << std::setw(35) << ""Number of Vectors on Scene: "" << std::setw(10) << Vector3::HowManyObjects() << std::endl; std::cout << std::setw(35) << ""Number of Vectors from start: "" << std::setw(10) << Vector3::AllHowManyObjects() << std::endl; std::cout << ""==========================================="" << std::endl << std::endl << std::endl; std::cout << menu; try { std::cin >> menu; } catch (std::logic_error &e) { std::cin.clear(); std::cin.ignore(std::numeric_limits().max(), '\n'); if(std::string(e.what()) == ""Exit""){ scene.~Scene(); finish = true; }else{ std::cerr << std::endl << std::endl << ""!!![ERROR]!!!"" << std::endl; std::cerr << e.what() << std::endl << std::endl; } } catch (...) { std::cerr << ""Fatal error, cautch ununderstable throw!!!"" << std::endl; scene.~Scene(); exit(-1); } } }); displaying.join(); menuig.join(); } std::cout << ""==========================================="" << std::endl; std::cout << std::setw(35) << ""Number of Vectors on Scene: "" << std::setw(10) << Vector3::HowManyObjects() << std::endl; std::cout << std::setw(35) << ""Number of Vectors from start: "" << std::setw(10) << Vector3::AllHowManyObjects() << std::endl; std::cout << ""==========================================="" << std::endl; return 0; }",tmp 97," /***************************************************************************** * Copyright [2017-2019] [MTSQuant] * * 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 ""./Currency.h"" #include #include const char * currencyIdName(CurrencyId currency) { static const char* names[] = { CURRENCY_ID_ENUM(SELECT_2_AND_COMMA_IN_3) }; if (currency >= 0 && currency < ARRAY_SIZE(names)) { return names[currency]; } else { return names[0]; } } CurrencyId currencyId(const char * currencyName) { static QHash [MASK] ; if ( [MASK] .isEmpty()) { CURRENCY_ID_ENUM(DEFINE_NAME_ENUM_MAP3_KEY_2); } return [MASK] [currencyName]; return CurrencyId(); } ",map 98,"// Copyright (c) 2022 Samsung Research America // // 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 #include #include #include #include #include #include ""regulated_fuzzy_logic_controller/parameter_handler.hpp"" namespace regulated_fuzzy_logic_controller { using nav2_util::declare_parameter_if_not_declared; using rcl_interfaces::msg::ParameterType; ParameterHandler::ParameterHandler( rclcpp_lifecycle::LifecycleNode::SharedPtr node, std::string & plugin_name, rclcpp::Logger & logger, const double /*costmap_size_x*/) { plugin_name_ = plugin_name; logger_ = logger; declare_parameter_if_not_declared(node, plugin_name_ + "".desired_linear_vel"", rclcpp::ParameterValue(0.5)); declare_parameter_if_not_declared(node, plugin_name_ + "".lookahead_dist"", rclcpp::ParameterValue(0.6)); declare_parameter_if_not_declared(node, plugin_name_ + "".min_lookahead_dist"", rclcpp::ParameterValue(0.3)); declare_parameter_if_not_declared(node, plugin_name_ + "".max_lookahead_dist"", rclcpp::ParameterValue(0.9)); declare_parameter_if_not_declared(node, plugin_name_ + "".lookahead_time"", rclcpp::ParameterValue(1.5)); declare_parameter_if_not_declared(node, plugin_name_ + "".use_interpolation"", rclcpp::ParameterValue(true)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_NL_MIN"", rclcpp::ParameterValue(-3.15)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_NL_MED"", rclcpp::ParameterValue(-3.0)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_NL_MAX"", rclcpp::ParameterValue(-2.8)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_NM_MIN"", rclcpp::ParameterValue(-2.8)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_NM_MED"", rclcpp::ParameterValue(-1.9)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_NM_MAX"", rclcpp::ParameterValue(-1.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_N_MIN"", rclcpp::ParameterValue(-1.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_N_MED"", rclcpp::ParameterValue(-0.9)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_N_MAX"", rclcpp::ParameterValue(-0.6)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_NS_MIN"", rclcpp::ParameterValue(-0.6)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_NS_MED"", rclcpp::ParameterValue(-0.5)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_NS_MAX"", rclcpp::ParameterValue(-0.4)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_ZN_MIN"", rclcpp::ParameterValue(-0.4)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_ZN_MED"", rclcpp::ParameterValue(-0.25)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_ZN_MAX"", rclcpp::ParameterValue(-0.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_Z_MIN"", rclcpp::ParameterValue(-0.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_Z_MED"", rclcpp::ParameterValue(0.0)); //---------------------- declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_Z_MAX"", rclcpp::ParameterValue(0.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_ZP_MIN"", rclcpp::ParameterValue(0.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_ZP_MED"", rclcpp::ParameterValue(0.25)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_ZP_MAX"", rclcpp::ParameterValue(0.4)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_PS_MIN"", rclcpp::ParameterValue(0.4)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_PS_MED"", rclcpp::ParameterValue(0.5)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_PS_MAX"", rclcpp::ParameterValue(0.6)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_P_MIN"", rclcpp::ParameterValue(0.6)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_P_MED"", rclcpp::ParameterValue(0.9)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_P_MAX"", rclcpp::ParameterValue(1.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_PM_MIN"", rclcpp::ParameterValue(1.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_PM_MED"", rclcpp::ParameterValue(1.9)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_PM_MAX"", rclcpp::ParameterValue(2.8)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_PL_MIN"", rclcpp::ParameterValue(2.8)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_PL_MED"", rclcpp::ParameterValue(3.0)); declare_parameter_if_not_declared(node, plugin_name_ + "".INPUT_PL_MAX"", rclcpp::ParameterValue(3.15)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_S_MIN"", rclcpp::ParameterValue(0.0)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_S_MED"", rclcpp::ParameterValue(0.035)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_S_MAX"", rclcpp::ParameterValue(0.07)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_M_MIN"", rclcpp::ParameterValue(0.06)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_M_MED"", rclcpp::ParameterValue(0.095)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_M_MAX"", rclcpp::ParameterValue(0.15)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_L_MIN"", rclcpp::ParameterValue(0.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_L_MED"", rclcpp::ParameterValue(0.15)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_L_MAX"", rclcpp::ParameterValue(0.2)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_VL_MIN"", rclcpp::ParameterValue(0.19)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_VL_MED"", rclcpp::ParameterValue(0.22)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_LIN_VL_MAX"", rclcpp::ParameterValue(0.26)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_NL_MIN"", rclcpp::ParameterValue(-1.82)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_NL_MED"", rclcpp::ParameterValue(-1.5)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_NL_MAX"", rclcpp::ParameterValue(-1.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_NM_MIN"", rclcpp::ParameterValue(-1.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_NM_MED"", rclcpp::ParameterValue(-0.8)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_NM_MAX"", rclcpp::ParameterValue(-0.52)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_N_MIN"", rclcpp::ParameterValue(-0.52)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_N_MED"", rclcpp::ParameterValue(-0.39)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_N_MAX"", rclcpp::ParameterValue(-0.28)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_NS_MIN"", rclcpp::ParameterValue(-0.28)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_NS_MED"", rclcpp::ParameterValue(-0.21)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_NS_MAX"", rclcpp::ParameterValue(-0.13)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_ZN_MIN"", rclcpp::ParameterValue(-0.13)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_ZN_MED"", rclcpp::ParameterValue(-0.08)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_ZN_MAX"", rclcpp::ParameterValue(-0.017)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_Z_MIN"", rclcpp::ParameterValue(-0.017)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_Z_MED"", rclcpp::ParameterValue(0.0)); //---------------------- declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_Z_MAX"", rclcpp::ParameterValue(0.017)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_ZP_MIN"", rclcpp::ParameterValue(0.017)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_ZP_MED"", rclcpp::ParameterValue(0.08)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_ZP_MAX"", rclcpp::ParameterValue(0.13)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_PS_MIN"", rclcpp::ParameterValue(0.13)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_PS_MED"", rclcpp::ParameterValue(0.21)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_PS_MAX"", rclcpp::ParameterValue(0.28)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_P_MIN"", rclcpp::ParameterValue(0.28)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_P_MED"", rclcpp::ParameterValue(0.39)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_P_MAX"", rclcpp::ParameterValue(0.52)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_PM_MIN"", rclcpp::ParameterValue(0.52)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_PM_MED"", rclcpp::ParameterValue(0.8)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_PM_MAX"", rclcpp::ParameterValue(1.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_PL_MIN"", rclcpp::ParameterValue(1.1)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_PL_MED"", rclcpp::ParameterValue(1.5)); declare_parameter_if_not_declared(node, plugin_name_ + "".OUTPUT_ANG_PL_MAX"", rclcpp::ParameterValue(1.82)); node->get_parameter(plugin_name_ + "".desired_linear_vel"", params_.desired_linear_vel); params_.base_desired_linear_vel = params_.desired_linear_vel; node->get_parameter(plugin_name_ + "".lookahead_dist"", params_.lookahead_dist); node->get_parameter(plugin_name_ + "".min_lookahead_dist"", params_.min_lookahead_dist); node->get_parameter(plugin_name_ + "".max_lookahead_dist"", params_.max_lookahead_dist); node->get_parameter(plugin_name_ + "".lookahead_time"", params_.lookahead_time); node->get_parameter(plugin_name_ + "".use_interpolation"", params_.use_interpolation); node->get_parameter(plugin_name_ + "".INPUT_NL_MIN"", params_.INPUT_NL_MIN); node->get_parameter(plugin_name_ + "".INPUT_NL_MED"", params_.INPUT_NL_MED); node->get_parameter(plugin_name_ + "".INPUT_NL_MAX"", params_.INPUT_NL_MAX); node->get_parameter(plugin_name_ + "".INPUT_NM_MIN"", params_.INPUT_NM_MIN); node->get_parameter(plugin_name_ + "".INPUT_NM_MED"", params_.INPUT_NM_MED); node->get_parameter(plugin_name_ + "".INPUT_NM_MAX"", params_.INPUT_NM_MAX); node->get_parameter(plugin_name_ + "".INPUT_N_MIN"", params_.INPUT_N_MIN); node->get_parameter(plugin_name_ + "".INPUT_N_MED"", params_.INPUT_N_MED); node->get_parameter(plugin_name_ + "".INPUT_N_MAX"", params_.INPUT_N_MAX); node->get_parameter(plugin_name_ + "".INPUT_NS_MIN"", params_.INPUT_NS_MIN); node->get_parameter(plugin_name_ + "".INPUT_NS_MED"", params_.INPUT_NS_MED); node->get_parameter(plugin_name_ + "".INPUT_NS_MAX"", params_.INPUT_NS_MAX); node->get_parameter(plugin_name_ + "".INPUT_ZN_MIN"", params_.INPUT_ZN_MIN); node->get_parameter(plugin_name_ + "".INPUT_ZN_MED"", params_.INPUT_ZN_MED); node->get_parameter(plugin_name_ + "".INPUT_ZN_MAX"", params_.INPUT_ZN_MAX); node->get_parameter(plugin_name_ + "".INPUT_Z_MIN"", params_.INPUT_Z_MIN); node->get_parameter(plugin_name_ + "".INPUT_Z_MED"", params_.INPUT_Z_MED); node->get_parameter(plugin_name_ + "".INPUT_Z_MAX"", params_.INPUT_Z_MAX); node->get_parameter(plugin_name_ + "".INPUT_ZP_MIN"", params_.INPUT_ZP_MIN); node->get_parameter(plugin_name_ + "".INPUT_ZP_MED"", params_.INPUT_ZP_MED); node->get_parameter(plugin_name_ + "".INPUT_ZP_MAX"", params_.INPUT_ZP_MAX); node->get_parameter(plugin_name_ + "".INPUT_PS_MIN"", params_.INPUT_PS_MIN); node->get_parameter(plugin_name_ + "".INPUT_PS_MED"", params_.INPUT_PS_MED); node->get_parameter(plugin_name_ + "".INPUT_PS_MAX"", params_.INPUT_PS_MAX); node->get_parameter(plugin_name_ + "".INPUT_P_MIN"", params_.INPUT_P_MIN); node->get_parameter(plugin_name_ + "".INPUT_P_MED"", params_.INPUT_P_MED); node->get_parameter(plugin_name_ + "".INPUT_P_MAX"", params_.INPUT_P_MAX); node->get_parameter(plugin_name_ + "".INPUT_PM_MIN"", params_.INPUT_PM_MIN); node->get_parameter(plugin_name_ + "".INPUT_PM_MED"", params_.INPUT_PM_MED); node->get_parameter(plugin_name_ + "".INPUT_PM_MAX"", params_.INPUT_PM_MAX); node->get_parameter(plugin_name_ + "".INPUT_PL_MIN"", params_.INPUT_PL_MIN); node->get_parameter(plugin_name_ + "".INPUT_PL_MED"", params_.INPUT_PL_MED); node->get_parameter(plugin_name_ + "".INPUT_PL_MAX"", params_.INPUT_PL_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_S_MIN"", params_.OUTPUT_LIN_S_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_S_MED"", params_.OUTPUT_LIN_S_MED); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_S_MAX"", params_.OUTPUT_LIN_S_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_M_MIN"", params_.OUTPUT_LIN_M_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_M_MED"", params_.OUTPUT_LIN_M_MED); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_M_MAX"", params_.OUTPUT_LIN_M_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_L_MIN"", params_.OUTPUT_LIN_L_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_L_MED"", params_.OUTPUT_LIN_L_MED); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_L_MAX"", params_.OUTPUT_LIN_L_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_VL_MIN"", params_.OUTPUT_LIN_VL_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_VL_MED"", params_.OUTPUT_LIN_VL_MED); node->get_parameter(plugin_name_ + "".OUTPUT_LIN_VL_MAX"", params_.OUTPUT_LIN_VL_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_NL_MIN"", params_.OUTPUT_ANG_NL_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_NL_MED"", params_.OUTPUT_ANG_NL_MED); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_NL_MAX"", params_.OUTPUT_ANG_NL_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_NM_MIN"", params_.OUTPUT_ANG_NM_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_NM_MED"", params_.OUTPUT_ANG_NM_MED); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_NM_MAX"", params_.OUTPUT_ANG_NM_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_N_MIN"", params_.OUTPUT_ANG_N_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_N_MED"", params_.OUTPUT_ANG_N_MED); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_N_MAX"", params_.OUTPUT_ANG_N_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_NS_MIN"", params_.OUTPUT_ANG_NS_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_NS_MED"", params_.OUTPUT_ANG_NS_MED); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_NS_MAX"", params_.OUTPUT_ANG_NS_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_ZN_MIN"", params_.OUTPUT_ANG_ZN_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_ZN_MED"", params_.OUTPUT_ANG_ZN_MED); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_ZN_MAX"", params_.OUTPUT_ANG_ZN_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_Z_MIN"", params_.OUTPUT_ANG_Z_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_Z_MED"", params_.OUTPUT_ANG_Z_MED); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_Z_MAX"", params_.OUTPUT_ANG_Z_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_ZP_MIN"", params_.OUTPUT_ANG_ZP_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_ZP_MED"", params_.OUTPUT_ANG_ZP_MED); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_ZP_MAX"", params_.OUTPUT_ANG_ZP_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_PS_MIN"", params_.OUTPUT_ANG_PS_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_PS_MED"", params_.OUTPUT_ANG_PS_MED); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_PS_MAX"", params_.OUTPUT_ANG_PS_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_P_MIN"", params_.OUTPUT_ANG_P_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_P_MED"", params_.OUTPUT_ANG_P_MED); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_P_MAX"", params_.OUTPUT_ANG_P_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_PM_MIN"", params_.OUTPUT_ANG_PM_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_PM_MED"", params_.OUTPUT_ANG_PM_MED); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_PM_MAX"", params_.OUTPUT_ANG_PM_MAX); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_PL_MIN"", params_.OUTPUT_ANG_PL_MIN); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_PL_MED"", params_.OUTPUT_ANG_PL_MED); node->get_parameter(plugin_name_ + "".OUTPUT_ANG_PL_MAX"", params_.OUTPUT_ANG_PL_MAX); } rcl_interfaces::msg::SetParametersResult ParameterHandler::dynamicParametersCallback( std::vector [MASK] ) { rcl_interfaces::msg::SetParametersResult result; std::lock_guard lock_reinit(mutex_); for (auto parameter : [MASK] ) { const auto & type = parameter.get_type(); const auto & name = parameter.get_name(); if (type == ParameterType::PARAMETER_DOUBLE) { if (name == plugin_name_ + "".desired_linear_vel"") { params_.desired_linear_vel = parameter.as_double(); params_.base_desired_linear_vel = parameter.as_double(); } else if (name == plugin_name_ + "".lookahead_dist"") { params_.lookahead_dist = parameter.as_double(); } else if (name == plugin_name_ + "".max_lookahead_dist"") { params_.max_lookahead_dist = parameter.as_double(); } else if (name == plugin_name_ + "".lookahead_time"") { params_.lookahead_time = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_NL_MIN"") { params_.INPUT_NL_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_NL_MED"") { params_.INPUT_NL_MED = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_NL_MAX"") { params_.INPUT_NL_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_NM_MIN"") { params_.INPUT_NM_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_NM_MED"") { params_.INPUT_NM_MED = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_NM_MAX"") { params_.INPUT_NM_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_N_MIN"") { params_.INPUT_N_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_N_MED"") { params_.INPUT_N_MED = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_N_MAX"") { params_.INPUT_N_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_NS_MIN"") { params_.INPUT_NS_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_NS_MED"") { params_.INPUT_NS_MED = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_NS_MAX"") { params_.INPUT_NS_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_ZN_MIN"") { params_.INPUT_ZN_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_ZN_MED"") { params_.INPUT_ZN_MED = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_ZN_MAX"") { params_.INPUT_ZN_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_Z_MIN"") { params_.INPUT_Z_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_Z_MED"") { //---------------- params_.INPUT_Z_MED = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_Z_MAX"") { params_.INPUT_Z_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_ZP_MIN"") { params_.INPUT_ZP_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_ZP_MED"") { params_.INPUT_ZP_MED = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_ZP_MAX"") { params_.INPUT_ZP_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_PS_MIN"") { params_.INPUT_PS_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_PS_MED"") { params_.INPUT_PS_MED = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_PS_MAX"") { params_.INPUT_PS_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_P_MIN"") { params_.INPUT_P_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_P_MED"") { params_.INPUT_P_MED = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_P_MAX"") { params_.INPUT_P_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_PM_MIN"") { params_.INPUT_PM_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_PM_MED"") { params_.INPUT_PM_MED = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_PM_MAX"") { params_.INPUT_PM_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_PL_MIN"") { params_.INPUT_PL_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_PL_MED"") { params_.INPUT_PL_MED = parameter.as_double(); } else if (name == plugin_name_ + "".INPUT_PL_MAX"") { params_.INPUT_PL_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_S_MIN"") { params_.OUTPUT_LIN_S_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_S_MED"") { params_.OUTPUT_LIN_S_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_S_MAX"") { params_.OUTPUT_LIN_S_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_M_MIN"") { params_.OUTPUT_LIN_M_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_M_MED"") { params_.OUTPUT_LIN_M_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_M_MAX"") { params_.OUTPUT_LIN_M_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_L_MIN"") { params_.OUTPUT_LIN_L_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_L_MED"") { params_.OUTPUT_LIN_L_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_L_MAX"") { params_.OUTPUT_LIN_L_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_VL_MIN"") { params_.OUTPUT_LIN_VL_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_VL_MED"") { params_.OUTPUT_LIN_VL_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_LIN_VL_MAX"") { params_.OUTPUT_LIN_VL_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_NL_MIN"") { params_.OUTPUT_ANG_NL_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_NL_MED"") { params_.OUTPUT_ANG_NL_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_NL_MAX"") { params_.OUTPUT_ANG_NL_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_NM_MIN"") { params_.OUTPUT_ANG_NM_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_NM_MED"") { params_.OUTPUT_ANG_NM_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_NM_MAX"") { params_.OUTPUT_ANG_NM_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_N_MIN"") { params_.OUTPUT_ANG_N_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_N_MED"") { params_.OUTPUT_ANG_N_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_N_MAX"") { params_.OUTPUT_ANG_N_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_NS_MIN"") { params_.OUTPUT_ANG_NS_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_NS_MED"") { params_.OUTPUT_ANG_NS_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_NS_MAX"") { params_.OUTPUT_ANG_NS_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_ZN_MIN"") { params_.OUTPUT_ANG_ZN_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_ZN_MED"") { params_.OUTPUT_ANG_ZN_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_ZN_MAX"") { params_.OUTPUT_ANG_ZN_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_Z_MIN"") { params_.OUTPUT_ANG_Z_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_Z_MED"") { //---------------- params_.OUTPUT_ANG_Z_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_Z_MAX"") { params_.OUTPUT_ANG_Z_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_ZP_MIN"") { params_.OUTPUT_ANG_ZP_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_ZP_MED"") { params_.OUTPUT_ANG_ZP_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_ZP_MAX"") { params_.OUTPUT_ANG_ZP_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_PS_MIN"") { params_.OUTPUT_ANG_PS_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_PS_MED"") { params_.OUTPUT_ANG_PS_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_PS_MAX"") { params_.OUTPUT_ANG_PS_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_P_MIN"") { params_.OUTPUT_ANG_P_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_P_MED"") { params_.OUTPUT_ANG_P_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_P_MAX"") { params_.OUTPUT_ANG_P_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_PM_MIN"") { params_.OUTPUT_ANG_PM_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_PM_MED"") { params_.OUTPUT_ANG_PM_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_PM_MAX"") { params_.OUTPUT_ANG_PM_MAX = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_PL_MIN"") { params_.OUTPUT_ANG_PL_MIN = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_PL_MED"") { params_.OUTPUT_ANG_PL_MED = parameter.as_double(); } else if (name == plugin_name_ + "".OUTPUT_ANG_PL_MAX"") { params_.OUTPUT_ANG_PL_MAX = parameter.as_double(); } } else if (type == ParameterType::PARAMETER_BOOL) { continue; } } /* */ result.successful = true; return result; } } // namespace regulated_fuzzy_logic_controller ",parameters 99,"#include ""image.h"" namespace { constexpr int PERCENTS_MIN_LIGHTER = -99; constexpr int PERCENTS_MIN = -100; constexpr int PERCENTS_MAX = 100; constexpr int PERCENTS_TO_LIGHTER_OFFSET = 100; } Image::Image() {} void Image::load(const QString& filename) { if (filename.isEmpty()) { m_source = {}; m_brightened = {}; return; } Q_ASSERT(m_source.load(filename)); m_brightened = m_source.convertToFormat(QImage::Format_RGBA8888, Qt::ColorOnly); } void Image::set_brightness(int [MASK] ) { Q_ASSERT(PERCENTS_MIN <= [MASK] <= PERCENTS_MAX); if (m_source.isNull()) return; for (int y = 0; y < m_source.height(); y++) { for (int x= 0; x < m_source.width(); x++) { QColor color = m_source.pixelColor(x, y); m_brightened.setPixelColor(x, y, color.lighter( qBound(PERCENTS_MIN_LIGHTER, [MASK] , PERCENTS_MAX) + PERCENTS_TO_LIGHTER_OFFSET ) ); } } } QPixmap Image::get_pixmap() const { return m_brightened.isNull() ? QPixmap{} : QPixmap::fromImage(m_brightened); } ",percents 100,"#include #include #include #include #include #include ""backend.h"" #include ""status.h"" namespace mlperf_bench { Backend::Backend() { allocator_ = allocator_info_; }; Status Backend::LoadModel(std::string path, std::vector outputs) { #ifdef _WIN32 std::wstring widestr = std::wstring(path.begin(), path.end()); session_ = new Ort::Session(env_, widestr.c_str(), opt_); #else session_ = new Ort::Session(env_, path.c_str(), opt_); #endif for (size_t i = 0; i < this->session_->GetInputCount(); i++) { input_names_.push_back(session_->GetInputName(i, allocator_)); auto ti = session_->GetInputTypeInfo(i).GetTensorTypeAndShapeInfo(); auto input_type = ti.GetElementType(); // FIXME: ti.GetElementType() returns junk on linux. Hack it for now. if (path.find(""ssd"") != std::string::npos) { input_type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8; } else { input_type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT; } input_type_.push_back(input_type); } for (size_t i = 0; i < this->session_->GetOutputCount(); i++) { char* name = session_->GetOutputName(i, allocator_); if (outputs.size() == 0 || std::find(outputs.begin(), outputs.end(), name) != outputs.end()) { auto ti = session_->GetOutputTypeInfo(i).GetTensorTypeAndShapeInfo(); auto shape = ti.GetShape(); output_shapes_.push_back(shape); output_names_.push_back(name); } } return Status::OK(); } std::vector Backend::Run(Ort::Value* inputs, size_t input_count) { std::vector [MASK] = session_->Run(run_options_, input_names_.data(), inputs, 1, output_names_.data(), output_names_.size()); return [MASK] ; } } ",results 101,"#include #include #include // Data wire is plugged into pin 2 on the Arduino #define ONE_WIRE_BUS D4 // 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); void setup() { Serial.begin(115200); //Begin serial communication Serial.println(""Arduino Digital Temperature // Serial Monitor Version""); //Print a message sensors.begin(); sensors.setResolution(12); } void loop() { // Send the command to get temperatures sensors.requestTemperatures(); Serial.print(""Temperature is: ""); Serial.println(sensors.getTempCByIndex(0)); DeviceAddress [MASK] ={0,0,0,0,0,0,0,0}; sensors.getAddress( [MASK] , 0); for (unsigned i=0; i // SPDX-License-Identifier: CC0-1.0 // ===================================================== // ===================================================== // Management variables // ===================================================== // --- // Main loop phases, alternating between read and write phases // --- #include ""phaseman.h"" // --- // Status LED (the onboard LED) management // --- #include ""StatusLed.h"" // --- // Data report sent to serial // --- #include ""Report.h"" // --- // Management of GPIOs // --- // GPIOs are used for 4 tasks : // * Enabling/disabling the power supply for the device under test. Disabling // the power supply allow to swap the device to test. // * Select the address sent to the device under test // * Read the data from the device under test // * User inputs (one action button and two toggle switches) // --- // -- address pins #include ""Address.h"" // -- data pins #include ""Data.h"" // -- Power control pins (outputs) : A0 const uint8_t POWER_CONTROL_PINS[] = {A0}; const uint8_t sizeof_POWER_CONTROL_PINS = sizeof(POWER_CONTROL_PINS) / sizeof(POWER_CONTROL_PINS[0]); // -- user input pins (buttons and toggle switches) : A2, A5-A4 ; const uint8_t INPUT_PINS[] = {A2, A5, A4}; const uint8_t sizeof_INPUT_PINS = sizeof(INPUT_PINS) / sizeof(INPUT_PINS[0]); // -- -- A2 = Action push-button const uint8_t INPUT_PIN_ACTION = 0; bool on_action = false; uint8_t action_value = LOW; const uint8_t ACTION_COOLDOWN_START = 3; uint8_t action_cooldown = ACTION_COOLDOWN_START; bool action_is_performing = false; uint8_t action_remaining = 0; // -- -- A5 = Mode toggle ; 0-> Manual, 1-> Automatic const uint8_t INPUT_PIN_MODE_TOGGLE = 1; bool onchange_mode = false; uint8_t mode_value = LOW; // -- -- A4 = Enable power toggle ; 0-> OFF, 1-> ON const uint8_t INPUT_PIN_POWER_ENABLE = 2; bool onchange_powerEnable = false; uint8_t powerEnable_value = LOW; // ===================================================== // Prepare... // ===================================================== void setup() { // -- onboard LED pinMode(LED_BUILTIN, OUTPUT); // -- other setups setupGpios(); setupSerial(); StatusLed_toPass(); } void setupGpios() { Address_setupGpios(); Data_setupGpios(); // -- power control pins for (uint8_t i = 0; i < sizeof_POWER_CONTROL_PINS; i++) { pinMode(POWER_CONTROL_PINS[i], OUTPUT); digitalWrite(POWER_CONTROL_PINS[i], LOW); } // -- user input pins for (uint8_t i = 0; i < sizeof_INPUT_PINS; i++) { pinMode(INPUT_PINS[i], INPUT); } } void setupSerial() { Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } } // ===================================================== // Main loop // ===================================================== void loop() { loopPhases(); } void handleReadPhase() { Data_read(); Report_registerValue(Address_value, Data_value); if (action_is_performing && LOW == mode_value) { Report_emitSingleValue(Address_value); } // -- read user input pins on_action = readInputButton(INPUT_PIN_ACTION, action_value); onchange_mode = readToggleSwitch(INPUT_PIN_MODE_TOGGLE, mode_value); onchange_powerEnable = readToggleSwitch(INPUT_PIN_POWER_ENABLE, powerEnable_value); } bool readInputButton(uint8_t button, uint8_t &value) { const uint8_t in = digitalRead(INPUT_PINS[button]); bool [MASK] = (HIGH == in && LOW == value); value = in; return [MASK] ; } bool readToggleSwitch(uint8_t toggle, uint8_t &value) { const uint8_t in = digitalRead(INPUT_PINS[toggle]); bool onchange = (in != value); value = in; return onchange; } void handleWritePhase() { // Code to update outputs updateStatusLed(); handlePower(); handleAction(); } void handlePower() { if (!onchange_powerEnable) return; for (uint8_t i = 0; i < sizeof(POWER_CONTROL_PINS) / sizeof(POWER_CONTROL_PINS[0]); i++) { digitalWrite(POWER_CONTROL_PINS[i], powerEnable_value); } } void handleAction() { // the handling is bogus, for now just // emitSingleReport/incrementAddress/emitAddress Report_emitSingleValue(Address_value); Address__loop(); return; // skip that if (action_is_performing) { if (action_remaining > 0) { --action_remaining; } else if (0 == Address_value) { Report_emitFull(); action_is_performing = false; } Address__loop(); } if (action_cooldown > 0) { Serial.println(""// -- cooldown > 0""); --action_cooldown; return; } if (!on_action) { Serial.println(""// -- on_action is false""); if (action_value == LOW) { Serial.println(""// -- action_value is LOW""); } else { Serial.println(""// -- action_value is HIGH""); } return; } else { Serial.println(""// -- on_action is true""); } if (LOW == mode_value) // manual mode handleAction_manual(); else handleAction_auto(); } void handleAction_manual() { // TODO Address__loop(); action_is_performing = true; } void handleAction_auto() { if (!action_is_performing) { Address_value = 0; action_is_performing = true; action_remaining = 1; } } ",trigger 103,"// // Created by AYL_iwalk on 21/6/15. // #include ""mp3_encoder.h"" int Mp3Encoder::Init(const char *pcmFilePath, const char *mp3FilePath, int sampleRate, int channels, int bitRate) { int ret = -1; pcmFile = fopen(pcmFilePath,""rb""); if (pcmFile) { mp3File = fopen(mp3FilePath,""wb""); if (mp3File) { lameClient = lame_init(); lame_set_in_samplerate(lameClient,sampleRate); lame_set_out_samplerate(lameClient, sampleRate); lame_set_num_channels(lameClient, channels); lame_set_brate(lameClient, bitRate/1000); lame_init_params(lameClient); ret = 0; } } return ret; } void Mp3Encoder::Encode() { int bufferSize = 1024 * 16; auto* buffer = new short [bufferSize/2]; auto* leftBuffer = new short [bufferSize/4]; auto* rightBuffer = new short [bufferSize/4]; auto* mp3Buffer = new unsigned char [bufferSize]; size_t [MASK] ; while(( [MASK] = fread(buffer,2,bufferSize/2,pcmFile)) > 0) { for (int i=0; i < bufferSize ; i++) { if (i%2==0) { leftBuffer[i/2] = buffer[i]; } else { rightBuffer[i/2] = buffer[i]; } } size_t wroteSize = lame_encode_buffer(lameClient, (short int* ) leftBuffer, (short int*) rightBuffer, (int)( [MASK] /2), mp3Buffer, bufferSize); fwrite(mp3Buffer, 1,wroteSize, mp3File); } delete[] buffer; delete[] leftBuffer; delete[] rightBuffer; delete[] mp3Buffer; } void Mp3Encoder::Destory() { if (pcmFile) { fclose(pcmFile); } if (mp3File) { fclose(mp3File); lame_close(lameClient); } } Mp3Encoder::Mp3Encoder() = default; ",readBufferSize 104,"#define STB_IMAGE_IMPLEMENTATION #include ""stb_image.h"" // for stbi_image_free, stbi_load #define STB_IMAGE_WRITE_IMPLEMENTATION #include ""stb_image_write.h"" // for stbi_write_png #include // for for_each #include // for size_t #include // for uint8_t #include // for execution::par #include // for basic_ostream, operator<< #include // for numeric_limits #include // for iota #include // for vector int main(int argc, char **argv) { if (argc != 3) { std::cerr << ""Usage: "" << argv[0] << "" \n""; return 0; } const char *filename = argv[1]; const char *output_filename = argv[2]; int width = 0; int height = 0; int channels = 0; std::uint8_t *image = stbi_load(filename, &width, &height, &channels, STBI_default); if (image == nullptr) { std::cerr << ""Failed to load image!\n""; stbi_image_free(image); return 1; } if (width <= 0 || height <= 0 || channels < 1 || channels > 4) { std::cerr << ""Invalid image!\n""; stbi_image_free(image); return 1; } if (channels == 1 || channels == 2) { std::cerr << ""Image is already gray!\n""; stbi_image_free(image); return 0; } if (std::numeric_limits::max() / height / channels < width) { std::cerr << ""Image is too large!\n""; stbi_image_free(image); return 1; } const int gray_channels = channels == 4 ? 2 : 1; const std::size_t gray_image_size = width * height * gray_channels; std::vector gray_image(gray_image_size); std::vector indices(width * height); std::iota(indices.begin(), indices.end(), 0); std::for_each( std::execution::par, indices.cbegin(), indices.cend(), [gray_channels, channels, &gray_image, &image](std::size_t [MASK] ) { const std::size_t i = [MASK] * gray_channels; const std::size_t j = [MASK] * channels; gray_image[i] = static_cast( (image[j] + image[j + 1] + image[j + 2]) / 3.0L); if (gray_channels == 2) { gray_image[i + 1] = image[j + 3]; } }); stbi_image_free(image); if (!stbi_write_png(output_filename, width, height, gray_channels, gray_image.data(), width * gray_channels)) { std::cerr << ""Failed to write output image!\n""; return 1; } } ",idx 105,"#pragma once #include enum class EAxis { PositiveX, NegativeX, PositiveY, NegativeY, PositiveZ, NegativeZ, }; inline aiVector3D Vec3ConvertUp(const aiVector3D& _v, EAxis _up) { aiVector3D res; if (_up == EAxis::NegativeY) { res.x = _v.x; res.y = -_v.y; res.z = -_v.z; } else //if (_up == EAxis::PositiveZ) { res.x = _v.x; res.y = _v.z; res.z = _v.y; } return res; } inline aiVector3D Vec3Cross(const aiVector3D& _v1, const aiVector3D& _v2) { aiVector3D res; res.x = _v1.y * _v2.z - _v1.z * _v2.y; res.y = _v1.z * _v2.x - _v1.x * _v2.z; res.z = _v1.x * _v2.y - _v1.y * _v2.x; return res; } inline float Vec3Dot(const aiVector3D& _v1, const aiVector3D& _v2) { return (_v1.x * _v2.x + _v1.y * _v2.y + _v1.z * _v2.z); } inline float GetBitangentSign( const aiVector3D& _normal, const aiVector3D& _tangent, const aiVector3D& _bitangent) { aiVector3D cross = Vec3Cross(_normal, _tangent); float [MASK] = Vec3Dot(cross, _bitangent); return ( [MASK] < 0.0f) ? -1.0f : 1.0f; } ",dot 106,"#include ""gen_exported.h"" namespace gen_exported { /******************************************************************************************************************* Cycling '74 License for Max-Generated Code for Export Copyright (c) 2022 Cycling '74 The code that Max generates automatically and that end users are capable of exporting and using, and any associated documentation files (the “Software”) is a work of authorship for which Cycling '74 is the author and owner for copyright purposes. A license is hereby granted, free of charge, to any person obtaining a copy of the Software (“Licensee”) to use, copy, modify, merge, publish, and distribute copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The Software is licensed to Licensee only for non-commercial use. Users who wish to make commercial use of the Software must contact the copyright owner to determine if a license for commercial use is available, and the terms and conditions for same, which may include fees or royalties. For commercial use, please send inquiries to licensing (at) cycling74.com. The determination of whether a use is commercial use or non-commercial use is based upon the use, not the user. The Software may be used by individuals, institutions, governments, corporations, or other business whether for-profit or non-profit so long as the use itself is not a commercialization of the materials or a use that generates or is intended to generate income, revenue, sales or profit. The above copyright notice and this license 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 NON-INFRINGEMENT. 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. *******************************************************************************************************************/ // global noise generator Noise noise; static const int GENLIB_LOOPCOUNT_BAIL = 100000; // The State struct contains all the state and procedures for the gendsp kernel typedef struct State { CommonState __commonstate; Change __m_change_22; DCBlock __m_dcblock_42; DCBlock __m_dcblock_27; DCBlock __m_dcblock_32; DCBlock __m_dcblock_37; Data m_scale_8; Delay m_delay_4; Delay m_delay_3; Delay m_delay_2; Delay m_delay_1; Phasor __m_phasor_20; Sah __m_sah_28; Sah __m_sah_33; Sah __m_sah_36; Sah __m_sah_31; Sah __m_sah_38; Sah __m_sah_26; Sah __m_sah_21; Sah __m_sah_41; Sah __m_sah_23; int vectorsize; int __exception; t_sample m_fund_7; t_sample m_thresh_6; t_sample samples_to_seconds; t_sample samplerate; t_sample m_frequency_5; // re-initialize all member variables; inline void reset(t_param __sr, int __vs) { __exception = 0; vectorsize = __vs; samplerate = __sr; m_delay_1.reset(""m_delay_1"", ((int)100000)); m_delay_2.reset(""m_delay_2"", ((int)100000)); m_delay_3.reset(""m_delay_3"", ((int)100000)); m_delay_4.reset(""m_delay_4"", ((int)100000)); m_frequency_5 = ((int)10); m_thresh_6 = ((t_sample)0.5); m_fund_7 = ((int)60); m_scale_8.reset(""scale"", ((int)12), ((int)1)); samples_to_seconds = (1 / samplerate); __m_phasor_20.reset(0); __m_sah_21.reset(0); __m_change_22.reset(0); __m_sah_23.reset(0); __m_sah_26.reset(0); __m_dcblock_27.reset(); __m_sah_28.reset(0); __m_sah_31.reset(0); __m_dcblock_32.reset(); __m_sah_33.reset(0); __m_sah_36.reset(0); __m_dcblock_37.reset(); __m_sah_38.reset(0); __m_sah_41.reset(0); __m_dcblock_42.reset(); genlib_reset_complete(this); }; // the signal processing routine; inline int perform(t_sample ** __ins, t_sample ** __outs, int __n) { vectorsize = __n; const t_sample * __in1 = __ins[0]; t_sample * __out1 = __outs[0]; if (__exception) { return __exception; } else if (( (__in1 == 0) || (__out1 == 0) )) { __exception = GENLIB_ERR_NULL_BUFFER; return __exception; }; int scale_dim = m_scale_8.dim; int scale_channels = m_scale_8.channels; bool index_ignore_9 = (((int)1) >= scale_dim); bool index_ignore_10 = (((int)2) >= scale_dim); bool index_ignore_11 = (((int)3) >= scale_dim); bool index_ignore_12 = (((int)4) >= scale_dim); bool index_ignore_13 = (((int)5) >= scale_dim); bool index_ignore_14 = (((int)6) >= scale_dim); bool index_ignore_15 = (((int)7) >= scale_dim); bool index_ignore_16 = (((int)8) >= scale_dim); bool index_ignore_17 = (((int)9) >= scale_dim); bool [MASK] = (((int)10) >= scale_dim); bool index_ignore_19 = (((int)11) >= scale_dim); t_sample rsub_130 = (((int)1) - m_thresh_6); samples_to_seconds = (1 / samplerate); // the main sample loop; while ((__n--)) { const t_sample in1 = (*(__in1++)); m_scale_8.write(((int)0), 0, 0); if ((!index_ignore_9)) { m_scale_8.write(((int)0), ((int)1), 0); }; if ((!index_ignore_10)) { m_scale_8.write(((int)2), ((int)2), 0); }; if ((!index_ignore_11)) { m_scale_8.write(((int)3), ((int)3), 0); }; if ((!index_ignore_12)) { m_scale_8.write(((int)3), ((int)4), 0); }; if ((!index_ignore_13)) { m_scale_8.write(((int)5), ((int)5), 0); }; if ((!index_ignore_14)) { m_scale_8.write(((int)7), ((int)6), 0); }; if ((!index_ignore_15)) { m_scale_8.write(((int)7), ((int)7), 0); }; if ((!index_ignore_16)) { m_scale_8.write(((int)8), ((int)8), 0); }; if ((!index_ignore_17)) { m_scale_8.write(((int)8), ((int)9), 0); }; if ((! [MASK] )) { m_scale_8.write(((int)10), ((int)10), 0); }; if ((!index_ignore_19)) { m_scale_8.write(((int)10), ((int)11), 0); }; t_sample noise_174 = noise(); t_sample noise_890 = noise(); t_sample noise_1617 = noise(); t_sample noise_1604 = noise(); t_sample noise_1648 = noise(); t_sample noise_1635 = noise(); t_sample noise_1679 = noise(); t_sample noise_1666 = noise(); t_sample noise_120 = noise(); t_sample phasor_121 = __m_phasor_20(m_frequency_5, samples_to_seconds); t_sample sah_123 = __m_sah_21(noise_120, phasor_121, ((t_sample)0.5)); int gt_129 = (sah_123 > rsub_130); int change_125 = __m_change_22(gt_129); int eq_475 = (change_125 == ((int)1)); t_sample sah_173 = __m_sah_23(noise_174, eq_475, ((t_sample)0.5)); t_sample sub_1908 = (sah_173 - (-1)); t_sample scale_1905 = ((safepow((sub_1908 * ((t_sample)0.5)), ((int)1)) * ((int)12)) + ((int)0)); t_sample floor_287 = floor(scale_1905); int index_trunc_24 = fixnan(floor(floor_287)); bool index_ignore_25 = ((index_trunc_24 >= scale_dim) || (index_trunc_24 < 0)); // samples scale channel 1; t_sample sample_scale_691 = (index_ignore_25 ? 0 : m_scale_8.read(index_trunc_24, 0)); t_sample index_scale_692 = floor_287; t_sample sah_891 = __m_sah_26(noise_890, eq_475, ((t_sample)0.5)); t_sample sub_1912 = (sah_891 - (-1)); t_sample scale_1909 = ((safepow((sub_1912 * ((t_sample)0.5)), ((int)1)) * ((int)3)) + ((int)0)); t_sample floor_954 = floor(scale_1909); t_sample mul_979 = (floor_954 * ((int)12)); t_sample add_1004 = (sample_scale_691 + mul_979); t_sample add_717 = (add_1004 + m_fund_7); t_sample mtof_1077 = mtof(add_717, ((int)440)); t_sample rdiv_193 = safediv(samplerate, mtof_1077); t_sample tap_335 = m_delay_4.read_linear(rdiv_193); t_sample dcblock_542 = __m_dcblock_27(tap_335); t_sample mul_504 = (dcblock_542 * ((t_sample)0.999)); t_sample sah_1618 = __m_sah_28(noise_1617, eq_475, ((t_sample)0.5)); t_sample sub_1916 = (sah_1618 - (-1)); t_sample scale_1913 = ((safepow((sub_1916 * ((t_sample)0.5)), ((int)1)) * ((int)12)) + ((int)0)); t_sample floor_1615 = floor(scale_1913); int index_trunc_29 = fixnan(floor(floor_1615)); bool index_ignore_30 = ((index_trunc_29 >= scale_dim) || (index_trunc_29 < 0)); // samples scale channel 1; t_sample sample_scale_1607 = (index_ignore_30 ? 0 : m_scale_8.read(index_trunc_29, 0)); t_sample index_scale_1608 = floor_1615; t_sample sah_1605 = __m_sah_31(noise_1604, eq_475, ((t_sample)0.5)); t_sample sub_1920 = (sah_1605 - (-1)); t_sample scale_1917 = ((safepow((sub_1920 * ((t_sample)0.5)), ((int)1)) * ((int)3)) + ((int)0)); t_sample floor_1602 = floor(scale_1917); t_sample mul_1601 = (floor_1602 * ((int)12)); t_sample add_1600 = (sample_scale_1607 + mul_1601); t_sample add_1606 = (add_1600 + m_fund_7); t_sample mtof_1614 = mtof(add_1606, ((int)440)); t_sample rdiv_1611 = safediv(samplerate, mtof_1614); t_sample tap_1613 = m_delay_3.read_linear(rdiv_1611); t_sample dcblock_1609 = __m_dcblock_32(tap_1613); t_sample mul_1610 = (dcblock_1609 * ((t_sample)0.999)); t_sample sah_1649 = __m_sah_33(noise_1648, eq_475, ((t_sample)0.5)); t_sample sub_1924 = (sah_1649 - (-1)); t_sample scale_1921 = ((safepow((sub_1924 * ((t_sample)0.5)), ((int)1)) * ((int)12)) + ((int)0)); t_sample floor_1646 = floor(scale_1921); int index_trunc_34 = fixnan(floor(floor_1646)); bool index_ignore_35 = ((index_trunc_34 >= scale_dim) || (index_trunc_34 < 0)); // samples scale channel 1; t_sample sample_scale_1638 = (index_ignore_35 ? 0 : m_scale_8.read(index_trunc_34, 0)); t_sample index_scale_1639 = floor_1646; t_sample sah_1636 = __m_sah_36(noise_1635, eq_475, ((t_sample)0.5)); t_sample sub_1928 = (sah_1636 - (-1)); t_sample scale_1925 = ((safepow((sub_1928 * ((t_sample)0.5)), ((int)1)) * ((int)3)) + ((int)0)); t_sample floor_1633 = floor(scale_1925); t_sample mul_1632 = (floor_1633 * ((int)12)); t_sample add_1631 = (sample_scale_1638 + mul_1632); t_sample add_1637 = (add_1631 + m_fund_7); t_sample mtof_1645 = mtof(add_1637, ((int)440)); t_sample rdiv_1642 = safediv(samplerate, mtof_1645); t_sample tap_1644 = m_delay_2.read_linear(rdiv_1642); t_sample dcblock_1640 = __m_dcblock_37(tap_1644); t_sample mul_1641 = (dcblock_1640 * ((t_sample)0.999)); t_sample sah_1680 = __m_sah_38(noise_1679, eq_475, ((t_sample)0.5)); t_sample sub_1932 = (sah_1680 - (-1)); t_sample scale_1929 = ((safepow((sub_1932 * ((t_sample)0.5)), ((int)1)) * ((int)12)) + ((int)0)); t_sample floor_1677 = floor(scale_1929); int index_trunc_39 = fixnan(floor(floor_1677)); bool index_ignore_40 = ((index_trunc_39 >= scale_dim) || (index_trunc_39 < 0)); // samples scale channel 1; t_sample sample_scale_1669 = (index_ignore_40 ? 0 : m_scale_8.read(index_trunc_39, 0)); t_sample index_scale_1670 = floor_1677; t_sample sah_1667 = __m_sah_41(noise_1666, eq_475, ((t_sample)0.5)); t_sample sub_1936 = (sah_1667 - (-1)); t_sample scale_1933 = ((safepow((sub_1936 * ((t_sample)0.5)), ((int)1)) * ((int)3)) + ((int)0)); t_sample floor_1664 = floor(scale_1933); t_sample mul_1663 = (floor_1664 * ((int)12)); t_sample add_1662 = (sample_scale_1669 + mul_1663); t_sample add_1668 = (add_1662 + m_fund_7); t_sample mtof_1676 = mtof(add_1668, ((int)440)); t_sample rdiv_1673 = safediv(samplerate, mtof_1676); t_sample tap_1675 = m_delay_1.read_linear(rdiv_1673); t_sample dcblock_1671 = __m_dcblock_42(tap_1675); t_sample out1 = ((((dcblock_1671 + dcblock_1640) + dcblock_1609) + in1) + dcblock_542); t_sample mul_1672 = (dcblock_1671 * ((t_sample)0.999)); m_delay_4.write((in1 + mul_504)); m_delay_3.write((in1 + mul_1610)); m_delay_2.write((in1 + mul_1641)); m_delay_1.write((in1 + mul_1672)); m_delay_1.step(); m_delay_2.step(); m_delay_3.step(); m_delay_4.step(); // assign results to output buffer; (*(__out1++)) = out1; }; return __exception; }; inline void set_frequency(t_param _value) { m_frequency_5 = (_value < 0 ? 0 : (_value > 1 ? 1 : _value)); }; inline void set_thresh(t_param _value) { m_thresh_6 = (_value < 0 ? 0 : (_value > 1 ? 1 : _value)); }; inline void set_fund(t_param _value) { m_fund_7 = (_value < 0 ? 0 : (_value > 1 ? 1 : _value)); }; inline void set_scale(void * _value) { m_scale_8.setbuffer(_value); }; } State; /// /// Configuration for the genlib API /// /// Number of signal inputs and outputs int gen_kernel_numins = 1; int gen_kernel_numouts = 1; int num_inputs() { return gen_kernel_numins; } int num_outputs() { return gen_kernel_numouts; } int num_params() { return 4; } /// Assistive lables for the signal inputs and outputs const char *gen_kernel_innames[] = { ""in1"" }; const char *gen_kernel_outnames[] = { ""out1"" }; /// Invoke the signal process of a State object int perform(CommonState *cself, t_sample **ins, long numins, t_sample **outs, long numouts, long n) { State* self = (State *)cself; return self->perform(ins, outs, n); } /// Reset all parameters and stateful operators of a State object void reset(CommonState *cself) { State* self = (State *)cself; self->reset(cself->sr, cself->vs); } /// Set a parameter of a State object void setparameter(CommonState *cself, long index, t_param value, void *ref) { State *self = (State *)cself; switch (index) { case 0: self->set_frequency(value); break; case 1: self->set_fund(value); break; case 2: self->set_scale(ref); break; case 3: self->set_thresh(value); break; default: break; } } /// Get the value of a parameter of a State object void getparameter(CommonState *cself, long index, t_param *value) { State *self = (State *)cself; switch (index) { case 0: *value = self->m_frequency_5; break; case 1: *value = self->m_fund_7; break; case 3: *value = self->m_thresh_6; break; default: break; } } /// Get the name of a parameter of a State object const char *getparametername(CommonState *cself, long index) { if (index >= 0 && index < cself->numparams) { return cself->params[index].name; } return 0; } /// Get the minimum value of a parameter of a State object t_param getparametermin(CommonState *cself, long index) { if (index >= 0 && index < cself->numparams) { return cself->params[index].outputmin; } return 0; } /// Get the maximum value of a parameter of a State object t_param getparametermax(CommonState *cself, long index) { if (index >= 0 && index < cself->numparams) { return cself->params[index].outputmax; } return 0; } /// Get parameter of a State object has a minimum and maximum value char getparameterhasminmax(CommonState *cself, long index) { if (index >= 0 && index < cself->numparams) { return cself->params[index].hasminmax; } return 0; } /// Get the units of a parameter of a State object const char *getparameterunits(CommonState *cself, long index) { if (index >= 0 && index < cself->numparams) { return cself->params[index].units; } return 0; } /// Get the size of the state of all parameters of a State object size_t getstatesize(CommonState *cself) { return genlib_getstatesize(cself, &getparameter); } /// Get the state of all parameters of a State object short getstate(CommonState *cself, char *state) { return genlib_getstate(cself, state, &getparameter); } /// set the state of all parameters of a State object short setstate(CommonState *cself, const char *state) { return genlib_setstate(cself, state, &setparameter); } /// Allocate and configure a new State object and it's internal CommonState: void *create(t_param sr, long vs) { State *self = new State; self->reset(sr, vs); ParamInfo *pi; self->__commonstate.inputnames = gen_kernel_innames; self->__commonstate.outputnames = gen_kernel_outnames; self->__commonstate.numins = gen_kernel_numins; self->__commonstate.numouts = gen_kernel_numouts; self->__commonstate.sr = sr; self->__commonstate.vs = vs; self->__commonstate.params = (ParamInfo *)genlib_sysmem_newptr(4 * sizeof(ParamInfo)); self->__commonstate.numparams = 4; // initialize parameter 0 (""m_frequency_5"") pi = self->__commonstate.params + 0; pi->name = ""frequency""; pi->paramtype = GENLIB_PARAMTYPE_FLOAT; pi->defaultvalue = self->m_frequency_5; pi->defaultref = 0; pi->hasinputminmax = false; pi->inputmin = 0; pi->inputmax = 1; pi->hasminmax = true; pi->outputmin = 0; pi->outputmax = 1; pi->exp = 0; pi->units = """"; // no units defined // initialize parameter 1 (""m_fund_7"") pi = self->__commonstate.params + 1; pi->name = ""fund""; pi->paramtype = GENLIB_PARAMTYPE_FLOAT; pi->defaultvalue = self->m_fund_7; pi->defaultref = 0; pi->hasinputminmax = false; pi->inputmin = 0; pi->inputmax = 1; pi->hasminmax = true; pi->outputmin = 0; pi->outputmax = 1; pi->exp = 0; pi->units = """"; // no units defined // initialize parameter 2 (""m_scale_8"") pi = self->__commonstate.params + 2; pi->name = ""scale""; pi->paramtype = GENLIB_PARAMTYPE_SYM; pi->defaultvalue = 0.; pi->defaultref = 0; pi->hasinputminmax = false; pi->inputmin = 0; pi->inputmax = 1; pi->hasminmax = false; pi->outputmin = 0; pi->outputmax = 1; pi->exp = 0; pi->units = """"; // no units defined // initialize parameter 3 (""m_thresh_6"") pi = self->__commonstate.params + 3; pi->name = ""thresh""; pi->paramtype = GENLIB_PARAMTYPE_FLOAT; pi->defaultvalue = self->m_thresh_6; pi->defaultref = 0; pi->hasinputminmax = false; pi->inputmin = 0; pi->inputmax = 1; pi->hasminmax = true; pi->outputmin = 0; pi->outputmax = 1; pi->exp = 0; pi->units = """"; // no units defined return self; } /// Release all resources and memory used by a State object: void destroy(CommonState *cself) { State *self = (State *)cself; genlib_sysmem_freeptr(cself->params); delete self; } } // gen_exported:: ",index_ignore_18 107,"#include ""../../config.hpp"" #if ESTRATEGIA == STRAT_BLUETOOTH #include ""../estrategia.hpp"" #include ""../../motores/motores.hpp"" #include ""strat.hpp"" #include //SoftwareSerial BT(1,0); #define BT Serial1 void setupEstrategia() { BT.begin(115200); } void loopEstrategia(uint16_t distanciaIzquierda, uint16_t distanciaAdelante, uint16_t distanciaDerecha, uint16_t lecturaPisoL, uint16_t lecturaPisoR) { static uint8_t [MASK] = 0; BT.println( [MASK] ); if (BT.available()==0) return; switch (BT.read()) { case 'G': // Adelante Izq. actualizarMotores(Direccion::Adelante, map( [MASK] , 0, 10, 0, 127), map( [MASK] , 0, 10, 0, 255)); break; case 'F': // Adelante actualizarMotores(Direccion::Adelante, map( [MASK] , 0, 10, 0, 255)); break; case 'I': // Adelante Der. actualizarMotores(Direccion::Adelante, map( [MASK] , 0, 10, 0, 255), map( [MASK] , 0, 10, 0, 127)); break; case 'H': // Atras Izq. actualizarMotores(Direccion::Atras, map( [MASK] , 0, 10, 0, 127), map( [MASK] , 0, 10, 0, 255)); break; case 'B': // Atras actualizarMotores(Direccion::Atras, map( [MASK] , 0, 10, 0, 255)); break; case 'J': // Atras Der. actualizarMotores(Direccion::Atras, map( [MASK] , 0, 10, 0, 255), map( [MASK] , 0, 10, 0, 127)); break; case 'L': // Izquierda actualizarMotores(Direccion::Izquierda, map( [MASK] , 0, 10, 0, 255)); break; case 'R': // Derecha actualizarMotores(Direccion::Derecha, map( [MASK] , 0, 10, 0, 255)); break; case 'S': // Parar actualizarMotores(Direccion::Nada); break; case '0': [MASK] = 0; break; case '1': [MASK] = 1; break; case '2': [MASK] = 2; break; case '3': [MASK] = 3; break; case '4': [MASK] = 4; break; case '5': [MASK] = 5; break; case '6': [MASK] = 6; break; case '7': [MASK] = 7; break; case '8': [MASK] = 8; break; case '9': [MASK] = 9; break; case 'q': [MASK] = 10; break; default: break; } } #endif ",porcentaje 108,"/*! * @file Adafruit_SPITFT.cpp * * @mainpage Adafruit SPI TFT Displays (and some others) * * @section intro_sec Introduction * * Part of Adafruit's GFX graphics library. Originally this class was * written to handle a range of color TFT displays connected via SPI, * but over time this library and some display-specific subclasses have * mutated to include some color OLEDs as well as parallel-interfaced * displays. The name's been kept for the sake of older code. * * Adafruit invests time and resources providing this open source code, * please support Adafruit and open-source hardware by purchasing * products from Adafruit! * @section dependencies Dependencies * * This library depends on * Adafruit_GFX being present on your system. Please make sure you have * installed the latest version before using this library. * * @section author Author * * Written by Limor ""ladyada"" Fried for Adafruit Industries, * with contributions from the open source community. * * @section license License * * BSD license, all text here must be included in any redistribution. */ // Updated to work with nRF5 SDK in 2020 by (https://github.com/adamgreen) #include #include #include ""Adafruit_SPITFT.h"" // Singleton used to determine which object _spiHandler should use when SPI events come in. Adafruit_SPITFT* Adafruit_SPITFT::g_pSingleton = NULL; // CONSTRUCTORS ------------------------------------------------------------ /*! @brief Adafruit_SPITFT constructor for hardware SPI using a specific SPI peripheral. @param width Display width in pixels at default rotation (0). @param height Display height in pixels at default rotation (0). @param pSpi Pointer to nRF SPI object. @param mosiPin Pin # for MOSI. @param sckPin Pin # for SCLK. @param cs Pin # for chip-select (-1 if unused, tie CS low). @param dc Pin # for data/command select (required). @param rst Pin # for display reset (optional, display reset can be tied to MCU reset, default of -1 means unused). @note Output pins are not initialized in constructor; application typically will need to call subclass' begin() function, which in turn calls this library's initSPI() function to initialize pins. */ Adafruit_SPITFT::Adafruit_SPITFT(uint16_t width, uint16_t height, nrf_drv_spi_t* pSpi, uint8_t mosiPin, uint8_t sckPin, uint8_t csPin, uint8_t dcPin, uint8_t rstPin /* = NRF_DRV_SPI_PIN_NOT_USED */) : Adafruit_GFX(width, height), m_pSpi(pSpi), m_mosiPin(mosiPin), m_sckPin(sckPin), m_rstPin(rstPin), m_csPin(csPin), m_dcPin(dcPin), m_startCount(0), m_finCount(0) { g_pSingleton = this; } // end constructors ------- // CLASS MEMBER FUNCTIONS -------------------------------------------------- // begin() and setAddrWindow() MUST be declared by any subclass. /*! @brief Configure microcontroller pins for TFT interfacing. Typically called by a subclass' begin() function. @param frequency SPI frequency when using hardware SPI. @param mode SPI mode when using hardware SPI. */ void Adafruit_SPITFT::initSPI(nrf_drv_spi_frequency_t frequency /* = NRF_DRV_SPI_FREQ_8M */, nrf_drv_spi_mode_t mode /* = NRF_DRV_SPI_MODE_0 */) { nrf_drv_spi_config_t [MASK] = NRF_DRV_SPI_DEFAULT_CONFIG; [MASK] .mosi_pin = m_mosiPin; [MASK] .sck_pin = m_sckPin; [MASK] .frequency = frequency; [MASK] .mode = mode; APP_ERROR_CHECK(nrf_drv_spi_init(m_pSpi, & [MASK] , _spiHandler)); // Init basic control pins common to all connection types nrf_gpio_cfg_output(m_csPin); nrf_gpio_pin_set(m_csPin); nrf_gpio_cfg_output(m_dcPin); nrf_gpio_pin_set(m_dcPin); if (m_rstPin != NRF_DRV_SPI_PIN_NOT_USED) { // Toggle reset low to reset nrf_gpio_cfg_output(m_rstPin); nrf_gpio_pin_set(m_rstPin); nrf_delay_ms(100); nrf_gpio_pin_clear(m_rstPin); nrf_delay_ms(100); nrf_gpio_pin_set(m_rstPin); nrf_delay_ms(200); } } /*! @brief Call before issuing command(s) or data to display. Performs chip-select (if required) and starts an SPI transaction (if using hardware SPI and transactions are supported). Required for all display types; not an SPI-specific function. */ void Adafruit_SPITFT::startWrite(void) { m_buffer.start(); startTransmission(); } /*! @brief Call after issuing command(s) or data to display. Performs chip-deselect (if required) and ends an SPI transaction (if using hardware SPI and transactions are supported). Required for all display types; not an SPI-specific function. */ void Adafruit_SPITFT::endWrite(void) { m_buffer.end(); startTransmission(); } // ------------------------------------------------------------------------- // Lower-level graphics operations. These functions require a chip-select // and/or SPI transaction around them (via startWrite(), endWrite() above). // Higher-level graphics primitives might start a single transaction and // then make multiple calls to these functions (e.g. circle or text // rendering might make repeated lines or rects) before ending the // transaction. It's more efficient than starting a transaction every time. /*! @brief Draw a single pixel to the display at requested coordinates. Not self-contained; should follow a startWrite() call. @param x Horizontal position (0 = left). @param y Vertical position (0 = top). @param color 16-bit pixel color in '565' RGB format. */ void Adafruit_SPITFT::writePixel(int16_t x, int16_t y, uint16_t color) { if ((x >= 0) && (x < _width) && (y >= 0) && (y < _height)) { setAddrWindow(x, y, 1, 1); spiWrite16(color); } } /*! @brief Issue a series of pixels from memory to the display. Not self- contained; should follow startWrite() and setAddrWindow() calls. @param colors Pointer to array of 16-bit pixel values in '565' RGB format. @param len Number of elements in 'colors' array. @param block If true (default case if unspecified), function blocks until DMA transfer is complete. This is simply IGNORED if DMA is not enabled. If false, the function returns immediately after the last DMA transfer is started, and one should use the dmaWait() function before doing ANY other display-related activities (or even any SPI-related activities, if using an SPI display that shares the bus with other devices). @param bigEndian If using DMA, and if set true, bitmap in memory is in big-endian order (most significant byte first). By default this is false, as most microcontrollers seem to be little-endian and 16-bit pixel values must be byte-swapped before issuing to the display (which tend to be big-endian when using SPI or 8-bit parallel). If an application can optimize around this -- for example, a bitmap in a uint16_t array having the byte values already reordered big-endian, this can save some processing time here, ESPECIALLY if using this function's non-blocking DMA mode. Not all cases are covered...this is really here only for SAMD DMA and much forethought on the application side. */ void Adafruit_SPITFT::writePixels(const uint16_t *colors, uint32_t len, bool block, bool bigEndian) { while (len--) { spiWrite16(*colors++); } } /*! @brief Issue a series of pixels, all the same color. Not self- contained; should follow startWrite() and setAddrWindow() calls. @param color 16-bit pixel color in '565' RGB format. @param len Number of pixels to draw. */ void Adafruit_SPITFT::writeColor(uint16_t color, uint32_t len) { while (len--) { spiWrite16(color); } } /*! @brief Draw a filled rectangle to the display. Not self-contained; should follow startWrite(). Typically used by higher-level graphics primitives; user code shouldn't need to call this and is likely to use the self-contained fillRect() instead. writeFillRect() performs its own edge clipping and rejection; see writeFillRectPreclipped() for a more 'raw' implementation. @param x Horizontal position of first corner. @param y Vertical position of first corner. @param w Rectangle width in pixels (positive = right of first corner, negative = left of first corner). @param h Rectangle height in pixels (positive = below first corner, negative = above first corner). @param color 16-bit fill color in '565' RGB format. @note Written in this deep-nested way because C by definition will optimize for the 'if' case, not the 'else' -- avoids branches and rejects clipped rectangles at the least-work possibility. */ void Adafruit_SPITFT::writeFillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { if (w && h) { // Nonzero width and height? if (w < 0) { // If negative width... x += w + 1; // Move X to left edge w = -w; // Use positive width } if (x < _width) { // Not off right if (h < 0) { // If negative height... y += h + 1; // Move Y to top edge h = -h; // Use positive height } if (y < _height) { // Not off bottom int16_t x2 = x + w - 1; if (x2 >= 0) { // Not off left int16_t y2 = y + h - 1; if (y2 >= 0) { // Not off top // Rectangle partly or fully overlaps screen if (x < 0) { x = 0; w = x2 + 1; } // Clip left if (y < 0) { y = 0; h = y2 + 1; } // Clip top if (x2 >= _width) { w = _width - x; } // Clip right if (y2 >= _height) { h = _height - y; } // Clip bottom writeFillRectPreclipped(x, y, w, h, color); } } } } } } /*! @brief Draw a horizontal line on the display. Performs edge clipping and rejection. Not self-contained; should follow startWrite(). Typically used by higher-level graphics primitives; user code shouldn't need to call this and is likely to use the self- contained drawFastHLine() instead. @param x Horizontal position of first point. @param y Vertical position of first point. @param w Line width in pixels (positive = right of first point, negative = point of first corner). @param color 16-bit line color in '565' RGB format. */ void inline Adafruit_SPITFT::writeFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) { if ((y >= 0) && (y < _height) && w) { // Y on screen, nonzero width if (w < 0) { // If negative width... x += w + 1; // Move X to left edge w = -w; // Use positive width } if (x < _width) { // Not off right int16_t x2 = x + w - 1; if (x2 >= 0) { // Not off left // Line partly or fully overlaps screen if (x < 0) { x = 0; w = x2 + 1; } // Clip left if (x2 >= _width) { w = _width - x; } // Clip right writeFillRectPreclipped(x, y, w, 1, color); } } } } /*! @brief Draw a vertical line on the display. Performs edge clipping and rejection. Not self-contained; should follow startWrite(). Typically used by higher-level graphics primitives; user code shouldn't need to call this and is likely to use the self- contained drawFastVLine() instead. @param x Horizontal position of first point. @param y Vertical position of first point. @param h Line height in pixels (positive = below first point, negative = above first point). @param color 16-bit line color in '565' RGB format. */ void inline Adafruit_SPITFT::writeFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) { if ((x >= 0) && (x < _width) && h) { // X on screen, nonzero height if (h < 0) { // If negative height... y += h + 1; // Move Y to top edge h = -h; // Use positive height } if (y < _height) { // Not off bottom int16_t y2 = y + h - 1; if (y2 >= 0) { // Not off top // Line partly or fully overlaps screen if (y < 0) { y = 0; h = y2 + 1; } // Clip top if (y2 >= _height) { h = _height - y; } // Clip bottom writeFillRectPreclipped(x, y, 1, h, color); } } } } /*! @brief A lower-level version of writeFillRect(). This version requires all inputs are in-bounds, that width and height are positive, and no part extends offscreen. NO EDGE CLIPPING OR REJECTION IS PERFORMED. If higher-level graphics primitives are written to handle their own clipping earlier in the drawing process, this can avoid unnecessary function calls and repeated clipping operations in the lower-level functions. @param x Horizontal position of first corner. MUST BE WITHIN SCREEN BOUNDS. @param y Vertical position of first corner. MUST BE WITHIN SCREEN BOUNDS. @param w Rectangle width in pixels. MUST BE POSITIVE AND NOT EXTEND OFF SCREEN. @param h Rectangle height in pixels. MUST BE POSITIVE AND NOT EXTEND OFF SCREEN. @param color 16-bit fill color in '565' RGB format. @note This is a new function, no graphics primitives besides rects and horizontal/vertical lines are written to best use this yet. */ inline void Adafruit_SPITFT::writeFillRectPreclipped(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { setAddrWindow(x, y, w, h); writeColor(color, (uint32_t)w * h); } // ------------------------------------------------------------------------- // Ever-so-slightly higher-level graphics operations. Similar to the 'write' // functions above, but these contain their own chip-select and SPI // transactions as needed (via startWrite(), endWrite()). They're typically // used solo -- as graphics primitives in themselves, not invoked by higher- // level primitives (which should use the functions above for better // performance). /*! @brief Draw a single pixel to the display at requested coordinates. Self-contained and provides its own transaction as needed (see writePixel(x,y,color) for a lower-level variant). Edge clipping is performed here. @param x Horizontal position (0 = left). @param y Vertical position (0 = top). @param color 16-bit pixel color in '565' RGB format. */ void Adafruit_SPITFT::drawPixel(int16_t x, int16_t y, uint16_t color) { // Clip first... if ((x >= 0) && (x < _width) && (y >= 0) && (y < _height)) { // THEN set up transaction (if needed) and draw... startWrite(); setAddrWindow(x, y, 1, 1); writeColor(color, 1); endWrite(); } } /*! @brief Draw a filled rectangle to the display. Self-contained and provides its own transaction as needed (see writeFillRect() or writeFillRectPreclipped() for lower-level variants). Edge clipping and rejection is performed here. @param x Horizontal position of first corner. @param y Vertical position of first corner. @param w Rectangle width in pixels (positive = right of first corner, negative = left of first corner). @param h Rectangle height in pixels (positive = below first corner, negative = above first corner). @param color 16-bit fill color in '565' RGB format. @note This repeats the writeFillRect() function almost in its entirety, with the addition of a transaction start/end. It's done this way (rather than starting the transaction and calling writeFillRect() to handle clipping and so forth) so that the transaction isn't performed at all if the rectangle is rejected. It's really not that much code. */ void Adafruit_SPITFT::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { if (w && h) { // Nonzero width and height? if (w < 0) { // If negative width... x += w + 1; // Move X to left edge w = -w; // Use positive width } if (x < _width) { // Not off right if (h < 0) { // If negative height... y += h + 1; // Move Y to top edge h = -h; // Use positive height } if (y < _height) { // Not off bottom int16_t x2 = x + w - 1; if (x2 >= 0) { // Not off left int16_t y2 = y + h - 1; if (y2 >= 0) { // Not off top // Rectangle partly or fully overlaps screen if (x < 0) { x = 0; w = x2 + 1; } // Clip left if (y < 0) { y = 0; h = y2 + 1; } // Clip top if (x2 >= _width) { w = _width - x; } // Clip right if (y2 >= _height) { h = _height - y; } // Clip bottom startWrite(); writeFillRectPreclipped(x, y, w, h, color); endWrite(); } } } } } } /*! @brief Draw a horizontal line on the display. Self-contained and provides its own transaction as needed (see writeFastHLine() for a lower-level variant). Edge clipping and rejection is performed here. @param x Horizontal position of first point. @param y Vertical position of first point. @param w Line width in pixels (positive = right of first point, negative = point of first corner). @param color 16-bit line color in '565' RGB format. @note This repeats the writeFastHLine() function almost in its entirety, with the addition of a transaction start/end. It's done this way (rather than starting the transaction and calling writeFastHLine() to handle clipping and so forth) so that the transaction isn't performed at all if the line is rejected. */ void Adafruit_SPITFT::drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) { if ((y >= 0) && (y < _height) && w) { // Y on screen, nonzero width if (w < 0) { // If negative width... x += w + 1; // Move X to left edge w = -w; // Use positive width } if (x < _width) { // Not off right int16_t x2 = x + w - 1; if (x2 >= 0) { // Not off left // Line partly or fully overlaps screen if (x < 0) { x = 0; w = x2 + 1; } // Clip left if (x2 >= _width) { w = _width - x; } // Clip right startWrite(); writeFillRectPreclipped(x, y, w, 1, color); endWrite(); } } } } /*! @brief Draw a vertical line on the display. Self-contained and provides its own transaction as needed (see writeFastHLine() for a lower- level variant). Edge clipping and rejection is performed here. @param x Horizontal position of first point. @param y Vertical position of first point. @param h Line height in pixels (positive = below first point, negative = above first point). @param color 16-bit line color in '565' RGB format. @note This repeats the writeFastVLine() function almost in its entirety, with the addition of a transaction start/end. It's done this way (rather than starting the transaction and calling writeFastVLine() to handle clipping and so forth) so that the transaction isn't performed at all if the line is rejected. */ void Adafruit_SPITFT::drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) { if ((x >= 0) && (x < _width) && h) { // X on screen, nonzero height if (h < 0) { // If negative height... y += h + 1; // Move Y to top edge h = -h; // Use positive height } if (y < _height) { // Not off bottom int16_t y2 = y + h - 1; if (y2 >= 0) { // Not off top // Line partly or fully overlaps screen if (y < 0) { y = 0; h = y2 + 1; } // Clip top if (y2 >= _height) { h = _height - y; } // Clip bottom startWrite(); writeFillRectPreclipped(x, y, 1, h, color); endWrite(); } } } } /*! @brief Draw a 16-bit image (565 RGB) at the specified (x,y) position. For 16-bit display devices; no color reduction performed. Adapted from https://github.com/PaulStoffregen/ILI9341_t3 by . See examples/pictureEmbed to use this. 5/6/2017: function name and arguments have changed for compatibility with current GFX library and to avoid naming problems in prior implementation. Formerly drawBitmap() with arguments in different order. Handles its own transaction and edge clipping/rejection. @param x Top left corner horizontal coordinate. @param y Top left corner vertical coordinate. @param pcolors Pointer to 16-bit array of pixel values. @param w Width of bitmap in pixels. @param h Height of bitmap in pixels. */ void Adafruit_SPITFT::drawRGBBitmap(int16_t x, int16_t y, uint16_t *pcolors, int16_t w, int16_t h) { int16_t x2, y2; // Lower-right coord if ((x >= _width) || // Off-edge right (y >= _height) || // "" top ((x2 = (x + w - 1)) < 0) || // "" left ((y2 = (y + h - 1)) < 0)) return; // "" bottom int16_t bx1 = 0, by1 = 0, // Clipped top-left within bitmap saveW = w; // Save original bitmap width value if (x < 0) { // Clip left w += x; bx1 = -x; x = 0; } if (y < 0) { // Clip top h += y; by1 = -y; y = 0; } if (x2 >= _width) w = _width - x; // Clip right if (y2 >= _height) h = _height - y; // Clip bottom pcolors += by1 * saveW + bx1; // Offset bitmap ptr to clipped top-left startWrite(); setAddrWindow(x, y, w, h); // Clipped area while (h--) { // For each (clipped) scanline... writePixels(pcolors, w); // Push one (clipped) row pcolors += saveW; // Advance pointer by one full (unclipped) line } endWrite(); } // ------------------------------------------------------------------------- // Miscellaneous class member functions that don't draw anything. /*! @brief Invert the colors of the display (if supported by hardware). Self-contained, no transaction setup required. @param i true = inverted display, false = normal display. */ void Adafruit_SPITFT::invertDisplay(bool i) { startWrite(); writeCommand(i ? invertOnCommand : invertOffCommand); endWrite(); } /*! @brief Given 8-bit red, green and blue values, return a 'packed' 16-bit color value in '565' RGB format (5 bits red, 6 bits green, 5 bits blue). This is just a mathematical operation, no hardware is touched. @param red 8-bit red brightnesss (0 = off, 255 = max). @param green 8-bit green brightnesss (0 = off, 255 = max). @param blue 8-bit blue brightnesss (0 = off, 255 = max). @return 'Packed' 16-bit color value (565 format). */ uint16_t Adafruit_SPITFT::color565(uint8_t red, uint8_t green, uint8_t blue) { return ((red & 0xF8) << 8) | ((green & 0xFC) << 3) | (blue >> 3); } /*! @brief Adafruit_SPITFT Send Command handles complete sending of commands and data @param commandByte The Command Byte @param dataBytes A pointer to the Data bytes to send @param numDataBytes The number of bytes we should send */ void Adafruit_SPITFT::sendCommand(uint8_t commandByte, const uint8_t *dataBytes, uint8_t numDataBytes) { startWrite(); writeCommand(commandByte); for (uint8_t i = 0 ; i < numDataBytes ; i++) { spiWrite(*dataBytes++); } endWrite(); } /*! @brief Issue a single 8-bit value to the display. Chip-select, transaction and data/command selection must have been previously set -- this ONLY issues the byte. This is another of those functions in the library with a now-not-accurate name that's being maintained for compatibility with outside code. This function is used even if display connection is parallel. @param b 8-bit value to write. */ void Adafruit_SPITFT::spiWrite(uint8_t b) { m_buffer.writeData(b); startTransmission(); } void Adafruit_SPITFT::spiWrite16(uint16_t w) { m_buffer.writeData(w); startTransmission(); } void Adafruit_SPITFT::spiWrite32(uint32_t w) { m_buffer.writeData(w); startTransmission(); } /*! @brief Write a single command byte to the display. Chip-select and transaction must have been previously set -- this ONLY sets the device to COMMAND mode, issues the byte and then restores DATA mode. There is no corresponding explicit writeData() function -- just use spiWrite(). @param cmd 8-bit command to write. */ void Adafruit_SPITFT::writeCommand(uint8_t cmd) { m_buffer.writeCommand(cmd); startTransmission(); } void Adafruit_SPITFT::spiHandler(nrf_drv_spi_evt_t const * pEvent) { if (pEvent) { m_finCount++; } while (1) { uint8_t* pBytes; uint32_t len; uint8_t flags; bool result = m_buffer.readBytes(&pBytes, &len, &flags); if (!result) { return; } if (m_buffer.isEnd(flags)) { nrf_gpio_pin_set(m_csPin); continue; } if (m_buffer.isStart(flags)) { nrf_gpio_pin_clear(m_csPin); } if (m_buffer.isCommand(flags)) { nrf_gpio_pin_clear(m_dcPin); } else { nrf_gpio_pin_set(m_dcPin); } m_startCount++; APP_ERROR_CHECK(nrf_drv_spi_transfer(m_pSpi, pBytes, len, NULL, 0)); return; } } ",spiConfig 109,"#include ""include/Vigener.h"" int threshold; int keyLength; int maxKeyLength; std::string alphabet; void checkFile(std::string fileName) { std::ifstream temp(fileName); if (!temp.is_open()) { std::cout << ""Невозможно открыть файл '"" << fileName << ""'\n""; exit(0); } else { std::string tmp; while (temp) { getline(temp, tmp); if (!tmp.empty()) return; } temp.close(); std::cout << ""Файл '"" << fileName << ""' пуст!\n""; exit(0); } } void readFile(std::string& text, std::string fileName) { checkFile(fileName); std::ifstream in(fileName); std::string str; while (!in.eof()) { str.clear(); getline(in, str); text.append(str); } in.close(); } void deleteForbiddenSymbols(std::string& text) { transform(text.begin(), text.end(), text.begin(), tolower); text.erase(remove_if(text.begin(), text.end(), isAlpha(alphabet)), text.end()); } void decrypt(std::string key, std::vector& columns) { for (auto i = 0; i < key.size(); i++) { int keyPosition = alphabet.find_first_of(key[i]); for (auto j = 0; j < columns[i].size(); j++) { int pos = alphabet.find_first_of(columns[i][j]); int num = pos - keyPosition; if (num < 0) num += (int)alphabet.size(); columns[i][j] = alphabet[num]; } } } void save(std::string key, std::vector& columns, std::string decryptedTextFileName) { std::ofstream out(decryptedTextFileName, std::ios::app); out << ""Ключ: "" << key << ""\n\n""; out << ""Открытый текст:\n""; decrypt(key, columns); int rawMaxSize = 130 / (int)key.length(); unsigned int k = 0; int tmp = 0; for (auto j = 0; j < columns.size(); j++) { if (k > columns[j].size()) break; out << columns[j][k]; tmp++; if (j != 0 && j % (key.size() - 1) == 0) out << "" ""; if (tmp == rawMaxSize * key.length()) { out << ""\n""; tmp = 0; } if (j != 0 && j % (key.size() - 1) == 0) { k++; j = -1; } } out << ""\n""; for (auto i = 0; i < 100; i++) out << ""-""; out << ""\n""; out.close(); } void displayDecryptedText(std::string key, std::vector columns) { decrypt(key, columns); int rawMaxSize = 130 / (int)key.length(); unsigned int k = 0; int tmp = 0; for (auto j = 0; j < columns.size(); j++) { if (k > columns[j].size()) break; std::cout << columns[j][k]; tmp++; if (j != 0 && j % (key.size() - 1) == 0) std::cout << "" ""; if (tmp == rawMaxSize * key.length()) { std::cout << ""\n""; tmp = 0; } if (j != 0 && j % (key.size() - 1) == 0) { k++; j = -1; } } std::cout << ""\n""; } void generaateKey(std::vector& columnsFrequency, std::string& key, int groupNumber, int shift, int cipherAlphabetSize) { int j = 0; int shiftFor = shift; if (key[groupNumber] == 'а') { if (shift < 0) shift += cipherAlphabetSize; key[groupNumber] = alphabet[shift]; } else { int superiority; while (key[groupNumber] != alphabet[++j]); shift += j; superiority = (int)shift / cipherAlphabetSize; if (abs(superiority) >= 1) shift -= superiority * cipherAlphabetSize; key[groupNumber] = alphabet[abs(shift)]; } if (shiftFor > 0) for (auto i = 0; i < shiftFor; i++) { auto it = (columnsFrequency[groupNumber]).info.begin(); (columnsFrequency[groupNumber]).info.push_back(*it); columnsFrequency[groupNumber].info.erase((columnsFrequency[groupNumber]).info.begin()); } else for (auto i = 0; i < abs(shiftFor); i++) { auto it = (columnsFrequency[groupNumber]).info.end() - 1; columnsFrequency[groupNumber].info.insert((columnsFrequency[groupNumber]).info.begin(), *it); columnsFrequency[groupNumber].info.erase((columnsFrequency[groupNumber]).info.end() - 1); } } void displayWorkSpace(Frequency analyticalTextFrequency, std::vector columnsFrequency, std::string key, int groupNumber) { HANDLE hOUTPUT = GetStdHandle(STD_OUTPUT_HANDLE); system(""cls""); std::cout << "" ""; SetConsoleTextAttribute(hOUTPUT, FOREGROUND_BLUE | FOREGROUND_INTENSITY); for (auto i = 0; i < analyticalTextFrequency.info.size(); i++) std::cout << std::setw(4) << i + 1; SetConsoleTextAttribute(hOUTPUT, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); std::cout << ""\n ""; for (auto it : analyticalTextFrequency.info) std::cout << std::setw(4) << it.word; std::cout << ""\n ""; for (auto it : analyticalTextFrequency.info) if (it.count >= threshold) { SetConsoleTextAttribute(hOUTPUT, FOREGROUND_GREEN | FOREGROUND_INTENSITY); std::cout << std::setw(4) << it.count; SetConsoleTextAttribute(hOUTPUT, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); } else std::cout << std::setw(4) << it.count; int count = 0; std::cout << ""\n""; for (auto it : columnsFrequency) { count++; if (count - 1 == groupNumber) { SetConsoleTextAttribute(hOUTPUT, FOREGROUND_BLUE | FOREGROUND_INTENSITY); for (auto i = 0; i < 143; i++) std::cout << ""-""; std::cout << ""\n""; SetConsoleTextAttribute(hOUTPUT, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); } if (count >= 10) std::cout << count << ""-я группа""; else std::cout << count << ""-я группа ""; for (auto i : it.info) if (i.count >= threshold) { SetConsoleTextAttribute(hOUTPUT, FOREGROUND_RED | FOREGROUND_INTENSITY); std::cout << std::setw(4) << i.count; SetConsoleTextAttribute(hOUTPUT, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); } else std::cout << std::setw(4) << i.count; std::cout << ""\n""; if (count - 1 == groupNumber) { SetConsoleTextAttribute(hOUTPUT, FOREGROUND_BLUE | FOREGROUND_INTENSITY); for (auto i = 0; i < 143; i++) std::cout << ""-""; std::cout << ""\n""; SetConsoleTextAttribute(hOUTPUT, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); } } std::cout << ""\nПредполагаемый ключ: "" << key << ""\n""; } void determineKey(Frequency analyticalTextFrequency, std::vector columnsFrequency, int cipherAlphabetSize, std::vector columns, std::string decryptedTextFileName) { int [MASK] = 0; int groupNumber = 0; int shift; std::string key; for (auto i = 0; i < keyLength; i++) key += ""а""; while (true) { displayWorkSpace(analyticalTextFrequency, columnsFrequency, key, groupNumber); std::cout << ""Группа: ""; std::cin >> groupNumber; if (groupNumber == 0) break; if (groupNumber == -1) { displayDecryptedText(key, columns); system(""pause""); continue; } if (groupNumber < -2 || groupNumber > keyLength) { std::cout << ""Неверные данные.\n""; system(""pause""); continue; } if (groupNumber > [MASK] ) [MASK] = groupNumber; if (groupNumber > 0) groupNumber -= 1; while (true) { std::cout << ""Сдвиг: ""; std::cin >> shift; if (shift == 0) break; if (groupNumber == -2 && abs(shift - 1) < keyLength) //отмена всех действий для группы с номером shift -1 { std::sort((columnsFrequency[shift - 1.0]).info.begin(), (columnsFrequency[shift - 1.0]).info.end(), Compare(alphabet)); key[shift - 1.0] = 'а'; displayWorkSpace(analyticalTextFrequency, columnsFrequency, key, groupNumber); std::cout << ""Группа: "" << groupNumber << ""\n""; continue; } if (abs(shift) > cipherAlphabetSize || abs(groupNumber - 1) > keyLength) { std::cout << ""Неверные данные.\n""; system(""pause""); continue; } shift *= -1; generaateKey(columnsFrequency, key, groupNumber, shift, cipherAlphabetSize); displayWorkSpace(analyticalTextFrequency, columnsFrequency, key, groupNumber); std::cout << ""Группа: "" << groupNumber + 1 << ""\n""; } } displayDecryptedText(key, columns); save(key, columns, decryptedTextFileName); } void findAlphabetSize(int& cipherAlphabetSize, std::string text) { std::set cipherAlphabet; for (auto it : text) cipherAlphabet.insert(it); cipherAlphabetSize = cipherAlphabet.size(); } void calculateFrequency(std::string text, Frequency& freq) { for (auto it : alphabet) freq.info.push_back(Symbol(it, 0)); int n = text.length(); for (auto i = 0; i < n; i++) { bool yes = true; for (auto j = freq.info.begin(); j != freq.info.end(); j++) { if ((*j).word == text[i]) { Symbol temp((*j).word, (*j).count + 1); freq.info.erase(j); freq.info.push_back(temp); yes = false; break; } } if (yes) freq.info.push_back(Symbol(text[i], 1)); } std::sort(freq.info.begin(), freq.info.end(), Compare(alphabet)); } void createColumns(std::string encryptedText, std::vector& columns) // не использет последние символы (поледнюю строку т.к. она может быть не полной) { std::string temp; int size = (int)encryptedText.size() / keyLength; for (auto j = 0; j < keyLength; j++) { temp.clear(); for (auto i = 0; i < size; i++) temp += encryptedText[j + i * keyLength]; columns.push_back(temp); } } void findKeyValue(std::string encryptedText, std::string analiticalTextFileName, std::string decryptedTextFileName) { std::string analiticalText; std::vector columns; std::vector columnsFrequency; Frequency analyticalTextFrequency; createColumns(encryptedText, columns); //формируем массив строк из шифртекста по столбцам readFile(analiticalText, analiticalTextFileName); //считываем аналилитечкий текст deleteForbiddenSymbols(analiticalText); if (analiticalText.size() < columns[1].size()) { std::cout << ""Аналитический текст получился меньше зашифрованного текста!\nВозможно несоответствие алфавитов!\n""; exit(0); } analiticalText.erase(columns[1].size(), analiticalText.size()); // удаляем лишний аналитический текст calculateFrequency(analiticalText, analyticalTextFrequency); // частотный анализ аналитического текста Frequency buffEncryptedTextFrequency; for (auto it : columns) //в цикле формируем частотный анализ шифроткста по группам (по столбикам) { buffEncryptedTextFrequency.info.clear(); calculateFrequency(it, buffEncryptedTextFrequency); columnsFrequency.push_back(buffEncryptedTextFrequency); } int cipherAlphabetSize; findAlphabetSize(cipherAlphabetSize, encryptedText); determineKey(analyticalTextFrequency, columnsFrequency, cipherAlphabetSize, columns, decryptedTextFileName); } void findKeyLength(std::string encryptedText) { int count; std::vector coincidenceCount; std::string buffText(encryptedText); for (auto i = 0; i < maxKeyLength; i++) { count = 0; buffText.push_back(buffText.front()); buffText.erase(0, 1); for (auto it = 0; it < encryptedText.size(); it++) if (encryptedText[it] == buffText[it]) count++; coincidenceCount.push_back((double)count / encryptedText.size()); } std::cout << ""Вероятные длины ключей: \n""; for (auto it = 0; it < maxKeyLength; it++) std::cout << std::setw(3) << it + 1 << "" - "" << coincidenceCount[it] << ""\n""; std::cout << ""Введите длину ключа: \n""; std::cin >> keyLength; } bool cmdOptionExists(char** begin, char** end, const std::string& option) { return std::find(begin, end, option) != end; } std::string getCmdOption(int argc, char* argv[], const std::string& option) { std::string cmd; for (short i = 0; i < argc; ++i) { std::string arg = argv[i]; if (0 == arg.find(option)) if (i + 1 < argc) return argv[i + 1]; } return cmd; } void parse_arguments(int argc, char* argv[], std::string& analiticalTextFileName, std::string& encryptedTextFileName, std::string& decryptedTextFileName) { if (cmdOptionExists(argv, argv + argc, ""-h"")) { std::cout << ""Использование: Vigener -i [путь к файлу с шифртекстом] -ia [путь к файлу с аналитическим текстом]\n\n""; std::cout << ""Параметры:\n\n""; std::cout << ""-i Задает путь к файлу с шифртекстом\n""; std::cout << ""-ia Задает путь к файлу с аналитическим текстом\n""; std::cout << ""-o Задает путь к файлу для сохранения результата работы программы. По умолчанию - путь файла шифртекста с меткой {processed}\n""; std::cout << ""-a Задает алфавит шифртекста. По умолчанию - кириллица\n""; std::cout << ""-af Задает путь к файлу с алфавитом шифртекста\n""; std::cout << ""-t Задает порог для выделения статистики. По умолчанию 6\n""; std::cout << ""-k Задает длину ключа\n""; std::cout << ""-mk Задает максимальную длину ключа\n\n""; std::cout << ""При вводе номера группы также можно указать следуюшие значения:\n\n""; std::cout << "" 0: выход из программы с сохранением результата работы. Ctrl + C - выход без сохранения результата\n""; std::cout << ""-1: вывести декодированный шифртекст при текущем ключе\n""; std::cout << ""-2: перейти в режим отмены сдвигов в группах. При вводе сдвига нужно указать номер группу,\nдля которой необходимо отменить все действия.\nДля выхода из режима необходимо ввести значение 0 в поле номера группы.\n\n""; std::cout << ""При вводе сдвига группы указывается положительное или отрицательное значение для\nциклического сдвига статистики вправо или влево соответсвенно.\nДля выхода из текушей группы необходимо ввести значение 0 в поле сдвига.\n\n""; exit(0); } // Инициализация encryptedTextFileName if (cmdOptionExists(argv, argv + argc, ""-i"")) encryptedTextFileName = getCmdOption(argc, argv, ""-i""); else { std::cout << ""Необходимо указать путь к файлу с шифртекстом.\nИспользуйте параметр -i.\n\n""; exit(0); } // Инициализация analiticalTextFileName if (cmdOptionExists(argv, argv + argc, ""-ia"")) analiticalTextFileName = getCmdOption(argc, argv, ""-ia""); else { std::cout << ""Необходимо указать путь к файлу с аналитическим текстом.\nИспользуйте параметр -ia.\n\n""; exit(0); } // Инициализация decryptedTextFileName if (cmdOptionExists(argv, argv + argc, ""-o"")) decryptedTextFileName = getCmdOption(argc, argv, ""-o""); else { decryptedTextFileName = encryptedTextFileName; size_t pos = decryptedTextFileName.find("".""); if (pos != std::string::npos) decryptedTextFileName.insert(pos, "" {processed}""); else decryptedTextFileName += "" {processed}""; } // Инициализация alphabet if (cmdOptionExists(argv, argv + argc, ""-a"")) alphabet = getCmdOption(argc, argv, ""-a""); else if (cmdOptionExists(argv, argv + argc, ""-af"")) readFile(alphabet, getCmdOption(argc, argv, ""-af"")); else alphabet = ""абвгдеёжзийклмнопрстуфхцчшщъыьэюя""; // Инициализация threshold if (cmdOptionExists(argv, argv + argc, ""-t"")) { try { threshold = std::stoi(getCmdOption(argc, argv, ""-t"")); if (threshold < 0) throw ""Error""; } catch (...) { std::cout << ""Неверно указан порог - положитльное число.\n\n""; exit(0); } } else threshold = 6; // Инициализация keyLength if (cmdOptionExists(argv, argv + argc, ""-k"")) { try { keyLength = std::stoi(getCmdOption(argc, argv, ""-k"")); if (keyLength < 0) throw ""Error""; } catch (...) { std::cout << ""Неверно указана длина ключа - положитльное число.\n\n""; exit(0); } } else keyLength = 0; // Инициализация maxKeyLength if (cmdOptionExists(argv, argv + argc, ""-mk"")) { try { maxKeyLength = std::stoi(getCmdOption(argc, argv, ""-mk"")); if (maxKeyLength <= 0) throw ""Error""; } catch (...) { std::cout << ""Неверно указана максимальная длина ключа - положитльное число.\n\n""; exit(0); } } else maxKeyLength = 26; } int main(int argc, char* argv[]) { setlocale(LC_ALL, ""Rus""); SetConsoleCP(.1251); SetConsoleOutputCP(.1251); std::string encryptedTextFileName = ""tests/Encrypted text.txt""; std::string decryptedTextFileName = ""tests/Encrypted text {processed}.txt""; std::string analiticalTextFileName = ""tests/Analytical text.txt""; parse_arguments(argc, argv, analiticalTextFileName, encryptedTextFileName, decryptedTextFileName); std::string encryptedText; readFile(encryptedText, encryptedTextFileName); deleteForbiddenSymbols(encryptedText); if (!keyLength) findKeyLength(encryptedText); findKeyValue(encryptedText, analiticalTextFileName, decryptedTextFileName); return 0; }",maxGroup 110,"#include #include #include #include #include #include #include #include ""NTL/ZZX.h"" #include ""helib/FHE.h"" #include ""helib/EncryptedArray.h"" // ! Note: HElib pre 1.0.0 uses findBaseLevel and HElib 1.0.0 uses capacity #define new_simd 0 NTL::ZZX long2Poly(long query) { NTL::ZZX queryPoly; queryPoly.SetLength(64); std::bitset<64> queryBits = query; for (int i = 0; i < queryBits.size(); i++) { NTL::SetCoeff(queryPoly, i, queryBits[i]); } queryPoly.normalize(); return queryPoly; } NTL::ZZX char2Poly(char character) { int charCode = character; NTL::ZZX resultPoly; resultPoly = long2Poly((long) charCode); return resultPoly; } long poly2Long(NTL::ZZX result) { long resultLong = 0; for (int i = 0; i <= deg(result); i++) { resultLong += (1L << i) * (NTL::coeff(result, i) == NTL::ZZ(1)); } return resultLong; } char poly2Char(NTL::ZZX result) { char character; character = (int) poly2Long(result); return character; } void fastPower(Ctxt &dataCtxt, long degree) { // Taken from eqtesting.cpp so that there are fewer includes if (degree == 1) return; Ctxt orig = dataCtxt; long k = NTL::NumBits(degree); long e = 1; for (long i = k - 2; i >= 0; i--) { Ctxt tmp1 = dataCtxt; tmp1.smartAutomorph(1L << e); // 1L << e computes 2^e dataCtxt.multiplyBy(tmp1); e = 2 * e; if (NTL::bit(degree, i)) { dataCtxt.smartAutomorph(2); dataCtxt.multiplyBy(orig); e += 1; } } } void equalTest(Ctxt &resultCtxt, const Ctxt &queryCtxt, const Ctxt &dataCtxt, long degree) { Ctxt tempCtxt = dataCtxt; tempCtxt = dataCtxt; tempCtxt -= queryCtxt; fastPower(tempCtxt, degree); tempCtxt.negate(); tempCtxt.addConstant(NTL::ZZ(1)); resultCtxt = tempCtxt; } void treeMultHelper(Ctxt &resultCtxt, std::vector ¤tLayer, std::vector &nextLayer) { unsigned long previousSize = currentLayer.size(); if (previousSize == 0) { return; } else if (previousSize == 1) { resultCtxt = currentLayer[0]; return; } nextLayer.resize((previousSize / 2 + previousSize % 2), resultCtxt); #pragma omp parallel for for (unsigned long i = 0; i < previousSize / 2; i++) { currentLayer[2 * i].multiplyBy(currentLayer[2 * i + 1]); nextLayer[i] = currentLayer[2 * i]; } if (previousSize % 2 == 1) { nextLayer[nextLayer.size() - 1] = (currentLayer[previousSize - 1]); } currentLayer.clear(); treeMultHelper(resultCtxt, nextLayer, currentLayer); } void treeMult(Ctxt &resultCtxt, const std::vector &ctxtVec) { if (ctxtVec.size() > 1) { std::vector currentLayer, nextLayer; currentLayer = ctxtVec; nextLayer.clear(); treeMultHelper(resultCtxt, currentLayer, nextLayer); } else { // std::cout << ""Only 1 Ciphertext; No Multiplication Done."" << std::endl; resultCtxt = ctxtVec[0]; } } void oneTotalProduct(Ctxt &resultCtxt, const Ctxt &dataCtxt, const long wordLength, const EncryptedArray &ea) { long numWords = floor(ea.size() / wordLength); resultCtxt = dataCtxt; if (wordLength == 1) { return; } long shiftAmt = 1; // auto startTime = std::chrono::high_resolution_clock::now(); // auto endTime = std::chrono::high_resolution_clock::now(); // std::chrono::duration timeTaken = endTime - startTime; while (shiftAmt < wordLength) { // startTime = std::chrono::high_resolution_clock::now(); Ctxt tempCtxt = resultCtxt; #if new_simd ea.shift(tempCtxt, (-shiftAmt*numWords)); #else ea.shift(tempCtxt, (-shiftAmt)); #endif resultCtxt.multiplyBy(tempCtxt); // ctxt = ctxt * (ctxt << ""shiftAmt"") shiftAmt = 2 * shiftAmt; // endTime = std::chrono::high_resolution_clock::now(); // timeTaken = endTime-startTime; // std::cout << shiftAmt << "", Time Taken: "" << timeTaken.count() << std::endl; } } void makeMask(NTL::ZZX &maskPoly, const long shiftAmt, const bool [MASK] , const long wordLength, const EncryptedArray &ea) { std::vector maskVec, oneMaskVec; if ( [MASK] ) { maskVec.assign(shiftAmt, NTL::ZZX(1)); oneMaskVec.assign(wordLength - shiftAmt, NTL::ZZX(0)); } else { maskVec.assign(shiftAmt, NTL::ZZX(0)); oneMaskVec.assign(wordLength - shiftAmt, NTL::ZZX(1)); } maskVec.insert(maskVec.end(), oneMaskVec.begin(), oneMaskVec.end()); std::vector fullMaskVec = maskVec; for (unsigned long i = 2 * wordLength; i < ea.size(); i += wordLength) { fullMaskVec.insert(fullMaskVec.end(), maskVec.begin(), maskVec.end()); } fullMaskVec.resize(ea.size(), NTL::ZZX(0)); ea.encode(maskPoly, fullMaskVec); } void simdShift(Ctxt &ciphertextResult, Ctxt &ciphertextData, const long shiftAmt, const long wordLength, const EncryptedArray &ea) { Ctxt tempCiphertext = ciphertextData; if (shiftAmt > 0) { NTL::ZZX maskPoly; makeMask(maskPoly, shiftAmt, 0, wordLength, ea); ea.shift(tempCiphertext, shiftAmt); tempCiphertext.multByConstant(maskPoly); } else if (shiftAmt < 0) { NTL::ZZX maskPoly; makeMask(maskPoly, -shiftAmt, 0, wordLength, ea); tempCiphertext.multByConstant(maskPoly); ea.shift(tempCiphertext, shiftAmt); } ciphertextResult = tempCiphertext; } int main(int argc, char *argv[]) { if (argc != 5) { std::cerr << ""Wrong inputs!""; std::cerr << std::endl << ""Inputs: level m attrLength conjSize"" << std::endl; return 1; } long p = 2; long r = 1; // long m = 31775; 32767 // long L = 29; 31 long m = atoi(argv[2]); long L = atoi(argv[1]); // double heuristicSecurity = (3 * eulerTot(m) * 7.2) / ((L + 1) * 22 * 4) - 110; // Define wildcard charaters char blankChar = 2; char wcChar = 3; char excludeChar = 4; // Timers auto startTime = std::chrono::high_resolution_clock::now(); auto endTime = std::chrono::high_resolution_clock::now(); std::chrono::duration timeTaken = endTime - startTime; float totalTime = 0; // FHE instance initialization FHEcontext context(m, p, r); buildModChain(context, L); NTL::ZZX F = context.alMod.getFactorsOverZZ()[0]; FHESecKey secretKey(context); const FHEPubKey &publicKey = secretKey; secretKey.GenSecKey(64); addFrbMatrices(secretKey); addBSGS1DMatrices(secretKey); EncryptedArray ea(context, F); long numSlots = ea.size(); long plaintextDegree = ea.getDegree(); long wordLength = atoi(argv[3]); long queryLength = 17; long numWords = floor(numSlots / wordLength); long numEmpty = numSlots % wordLength; long conjSize = atoi(argv[4]); // Output parameters to log IndexSet allPrimes(0, context.numPrimes() - 1); std::clog << m << "", "" << L << "", "" << context.logOfProduct(context.ctxtPrimes) / log(2.0) << "", "" << context.logOfProduct(allPrimes) / log(2.0) << "", "" << p << "", "" << plaintextDegree << "", "" << numSlots << "", ""; // Process the strings, one attribute and one query pattern of type %W%, // * wildcard is encoded as ASCII code 2 // # wildcard is encoded as ASCII code 3 std::string attrString = ""spares""; std::cout << std::endl << ""Attribute String: "" << attrString << std::endl; std::vector plaintextAttr; #if new_simd for(long i = 0; i < attrString.length(); i++) plaintextAttr.resize((i+1)*numWords, char2Poly(attrString[i])); for(long i = attrString.length(); i < wordLength; i++) plaintextAttr.resize((i+1)*numWords, plaintextAttr[i] = char2Poly(blankChar)); #else plaintextAttr.resize(numSlots-numEmpty, NTL::ZZX(0)); for (unsigned long i = 0; i < attrString.length(); i++) plaintextAttr[i] = char2Poly(attrString[i]); for (unsigned long i = attrString.length(); i < wordLength; i++) plaintextAttr[i] = char2Poly(blankChar); for (unsigned long i = wordLength; i < numSlots - numEmpty; i++) plaintextAttr[i] = plaintextAttr[i % wordLength]; #endif plaintextAttr.resize(numSlots, NTL::ZZX(0)); // ""$"" is the wildcard character symbol std::string queryString = ""sp""; queryString += wcChar; queryString += excludeChar; queryString += ""c""; queryString += ""e""; queryLength = queryString.length(); std::cout << ""Query Pattern: "" << queryString << std::endl; std::vector plaintextQuery, plaintextE; std::vector plaintextConjunction((unsigned long) numSlots, long2Poly(rand() % (1L << 7))); #if new_simd int counter = 0; for (unsigned long i = 0; i < queryString.length(); i++) { if (queryString[i] == wcChar) { plaintextQuery.resize((i+1)*numWords, char2Poly(queryString[i])); plaintextE.resize((counter+1)*numWords, NTL::ZZX(1)); counter++; } else if (queryString[i] == excludeChar) { plaintextQuery.resize((i+1)*numWords, char2Poly(queryString[i+1])); plaintextE.resize((counter+1)*numWords, NTL::ZZX(1)); // plaintextQuery[counter] = i += 1; counter++; } else { plaintextQuery.resize((i+1)*numWords, char2Poly(queryString[i])); plaintextE.resize((counter+1)*numWords, NTL::ZZX(0)); plaintextQuery[counter] = char2Poly(queryString[i]); counter++; } // std::cout << i << "", "" << counter << std::endl; } for (unsigned long i = counter; i < wordLength; i++) { plaintextQuery.resize((i+1)*numWords, char2Poly(wcChar)); plaintextE.resize((i+1)*numWords, NTL::ZZX(1)); } #else plaintextQuery.resize(numSlots-numEmpty, NTL::ZZX(0)); plaintextE.resize(numSlots-numEmpty, NTL::ZZX(0)); int counter = 0; for (unsigned long i = 0; i < queryString.length(); i++) { if (queryString[i] == wcChar) { plaintextQuery[counter] = char2Poly(excludeChar); plaintextE[counter] = 1; counter++; } else if (queryString[i] == excludeChar) { plaintextQuery[counter] = char2Poly(queryString[i + 1]); plaintextE[counter] = 1; i += 1; counter++; } else { plaintextQuery[counter] = char2Poly(queryString[i]); counter++; } } for (unsigned long i = counter; i < wordLength; i++) { plaintextQuery[i] = char2Poly(wcChar); plaintextE[i] = 1; } for (unsigned long i = wordLength; i < numSlots - numEmpty; i++) { plaintextQuery[i] = plaintextQuery[i % wordLength]; plaintextE[i] = plaintextE[i % wordLength]; } #endif plaintextQuery.resize(numSlots, NTL::ZZX(0)); plaintextE.resize(numSlots, NTL::ZZX(0)); std::vector plaintextResult((unsigned long) numSlots - numEmpty, NTL::ZZX(1)); plaintextResult.resize(numSlots, NTL::ZZX(0)); // for (unsigned long i = 0; i < plaintextAttr.size(); i++) { // std::cout << poly2Char(plaintextAttr[i]) << "", ""; // } // std::cout << std::endl; // for (unsigned long i = 0; i < plaintextQuery.size(); i++) { // std::cout << poly2Char(plaintextQuery[i]) << "", ""; // } // std::cout << std::endl; // for (unsigned long i = 0; i < plaintextE.size(); i++) { // std::cout << plaintextE[i] << "", ""; // } // std::cout << std::endl; // for(unsigned long i = wordLength; i < 2*wordLength; i++) { // std::cout << poly2Char(plaintextAttr[i]) << "", ""; // } // std::cout << std::endl; // for(unsigned long i = wordLength; i < 2*wordLength; i++) { // std::cout << poly2Char(plaintextQuery[i]) << "", ""; // } // std::cout << std::endl; // for(unsigned long i = wordLength; i < 2*wordLength; i++) { // std::cout << plaintextE[i] << "", ""; // } // std::cout << std::endl; std::clog << wordLength << "", "" << queryLength << "", "" << numWords << "", ""; std::cout << ""Plaintext Processing Done!"" << std::endl; // Initialize and encrypt ciphertexts Ctxt ciphertextAttr(publicKey); Ctxt ciphertextQuery(publicKey); Ctxt tempCiphertext(publicKey); Ctxt ciphertextE(publicKey); Ctxt ciphertextResult(publicKey); Ctxt conjResult(publicKey); // Ctxt conjQuery(publicKey); // Ctxt conjCtxt(publicKey); ea.encrypt(ciphertextAttr, publicKey, plaintextAttr); ea.encrypt(ciphertextQuery, publicKey, plaintextQuery); ea.encrypt(ciphertextE, publicKey, plaintextE); // ea.encrypt(conjCtxt, publicKey, plaintextConjunction); // ea.encrypt(conjQuery, publicKey, plaintextConjunction); Ctxt oneCiphertext(publicKey); Ctxt zeroCiphertext(publicKey); std::vector onePlaintext(numSlots, NTL::ZZX(1)); ea.encrypt(oneCiphertext, publicKey, onePlaintext); zeroCiphertext = oneCiphertext; zeroCiphertext -= oneCiphertext; // Initialize components std::vector ciphertextWs, ciphertextRs, ciphertextSs, ciphertextDs; for (unsigned long i = 0; i < wordLength; i++) { ciphertextWs.push_back(ciphertextAttr); ciphertextRs.push_back(ciphertextAttr); ciphertextSs.push_back(ciphertextAttr); } for (unsigned long i = 0; i < wordLength; i++) { if (i <= wordLength - queryLength) { ciphertextDs.push_back(oneCiphertext); } else { ciphertextDs.push_back(zeroCiphertext); } } // For compound conjunction queries std::vector ciphertextConj; std::vector ciphertextConjResult; for (unsigned long i = 0; i < conjSize; i++) { ciphertextConj.push_back(ciphertextAttr); ciphertextConjResult.push_back(ciphertextAttr); } std::cout << ""Encryption Done!"" << std::endl; NTL::ZZX selectPoly; NTL::ZZX queryMask, finalMask; makeMask(selectPoly, 1, 1, wordLength, ea); makeMask(finalMask, wordLength, 1, wordLength, ea); // Step 1: Shift the attributes // Remnants of experiment to pack differently, all characters of the same slot first // But the shift time is much longer than packing word by word // startTime = std::chrono::high_resolution_clock::now(); // #pragma omp parallel for // for(unsigned long i = 1; i < ciphertextWs.size(); i++) { // ea.shift(ciphertextWs[i],-i*numWords); // } // endTime = std::chrono::high_resolution_clock::now(); // timeTaken = endTime-startTime; // totalTime += timeTaken.count(); // std::cout << ""Pre-compute Time: "" << timeTaken.count() << std::endl; startTime = std::chrono::high_resolution_clock::now(); #pragma omp parallel for for (unsigned long i = 1; i < ciphertextWs.size(); i++) { #if new_simd ea.shift(ciphertextWs[i], (-i*numWords)); #else simdShift(ciphertextWs[i], ciphertextAttr, -i, wordLength, ea); #endif } endTime = std::chrono::high_resolution_clock::now(); timeTaken = endTime - startTime; // totalTime += timeTaken.count(); std::cout << ""Pre-compute Time: "" << timeTaken.count() << std::endl; std::clog << timeTaken.count() << "", ""; // for(unsigned long i = 0; i < ciphertextWs.size(); i++) { // ea.decrypt(ciphertextWs[i],secretKey,plaintextResult); // std::cout << poly2Char(plaintextResult[0]) << "", ""; // } // std::cout << std::endl; // Step 2: Test if the characters are the same startTime = std::chrono::high_resolution_clock::now(); #pragma omp parallel for for (unsigned long i = 0; i < ciphertextWs.size() + conjSize; i++) { if (i < ciphertextWs.size()) { ciphertextWs[i] += ciphertextQuery; } else { ciphertextConj[i - ciphertextWs.size()] += ciphertextAttr; } } endTime = std::chrono::high_resolution_clock::now(); timeTaken = endTime - startTime; totalTime += timeTaken.count(); std::cout << ""XOR Time: "" << timeTaken.count() << std::endl; startTime = std::chrono::high_resolution_clock::now(); #pragma omp parallel for for (unsigned long i = 0; i < ciphertextWs.size() + conjSize; i++) { if (i < ciphertextWs.size()) { equalTest(ciphertextRs[i], zeroCiphertext, ciphertextWs[i], plaintextDegree); } else { equalTest(ciphertextConjResult[i - ciphertextWs.size()], zeroCiphertext, ciphertextConj[i - ciphertextWs.size()], plaintextDegree); } // } // for(unsigned long i = 0; i < ciphertextRs.size(); i++) { if (i < ciphertextWs.size()) { ciphertextRs[i] += ciphertextE; } } endTime = std::chrono::high_resolution_clock::now(); timeTaken = endTime - startTime; totalTime += timeTaken.count(); std::cout << ""Level left: "" << ciphertextRs[1].capacity() << "", Equality Check + eMask Time: "" << timeTaken.count() << std::endl; std::clog << timeTaken.count() << "", ""; // Step 3: Combine results of character tests per shift startTime = std::chrono::high_resolution_clock::now(); #pragma omp parallel for for (unsigned long i = 0; i < ciphertextRs.size() + conjSize; i++) { if (i < ciphertextRs.size()) { oneTotalProduct(ciphertextSs[i], ciphertextRs[i], wordLength, ea); } else if (conjSize > 0) { oneTotalProduct(ciphertextConj[i - ciphertextRs.size()], ciphertextConjResult[i - ciphertextRs.size()], wordLength, ea); } } endTime = std::chrono::high_resolution_clock::now(); timeTaken = endTime - startTime; totalTime += timeTaken.count(); std::cout << ""Level left: "" << ciphertextSs[1].capacity() << "", Product of Equalities: "" << timeTaken.count() << std::endl; std::clog << timeTaken.count() << "", ""; // Step 4: Combine results from testing every possible shift startTime = std::chrono::high_resolution_clock::now(); #pragma omp parallel for for (unsigned long i = 0; i < ciphertextSs.size(); i++) { ciphertextSs[i].multiplyBy(ciphertextDs[i]); ciphertextSs[i].addConstant(selectPoly); } endTime = std::chrono::high_resolution_clock::now(); timeTaken = endTime - startTime; totalTime += timeTaken.count(); std::cout << ""Level left: "" << ciphertextSs[1].capacity() << "", Disjunction Prep Time: "" << timeTaken.count() << std::endl; std::clog << timeTaken.count() << "", ""; startTime = std::chrono::high_resolution_clock::now(); treeMult(ciphertextResult, ciphertextSs); ciphertextResult.addConstant(selectPoly); if (conjSize > 0) { treeMult(conjResult, ciphertextConj); ciphertextResult.multiplyBy(conjResult); } // ciphertextResult.multByConstant(finalMask); endTime = std::chrono::high_resolution_clock::now(); timeTaken = endTime - startTime; totalTime += timeTaken.count(); std::cout << ""Level left: "" << ciphertextResult.capacity() << "", Disjunction Time: "" << timeTaken.count() << std::endl; std::clog << timeTaken.count() << "", ""; std::clog << totalTime << "", ""; startTime = std::chrono::high_resolution_clock::now(); tempCiphertext = ciphertextResult; #pragma omp parallel for for (unsigned long i = 1; i < wordLength; i++) { ciphertextWs[i] = ciphertextResult; ea.shift(ciphertextWs[i], i); } for (unsigned long i = 1; i < wordLength; i++) { tempCiphertext += ciphertextWs[i]; } tempCiphertext.multiplyBy(ciphertextAttr); endTime = std::chrono::high_resolution_clock::now(); timeTaken = endTime - startTime; // totalTime += timeTaken.count(); std::cout << ""Level left: "" << tempCiphertext.capacity() << "", Fill + Selection Time: "" << timeTaken.count() << std::endl; std::clog << timeTaken.count() << "", ""; std::cout << ""Total Time: "" << totalTime << std::endl; ea.decrypt(ciphertextResult, secretKey, plaintextResult); for (unsigned long i = 0; i < wordLength; i++) { std::cout << poly2Long(plaintextResult[i]) << "", ""; } std::cout << std::endl; ea.decrypt(tempCiphertext, secretKey, plaintextResult); for (unsigned long i = 0; i < wordLength; i++) { std::cout << poly2Char(plaintextResult[i]) << "", ""; } std::cout << std::endl; std::clog << poly2Char(plaintextResult[0]) << "", ""; // ea.decrypt(ciphertextSs[0], secretKey, plaintextResult); // for (unsigned long i = 0; i < wordLength; i++) { // std::cout << poly2Long(plaintextResult[i]) << "", ""; // } // std::cout << std::endl; // // ea.decrypt(ciphertextRs[0], secretKey, plaintextResult); // for (unsigned long i = 0; i < wordLength; i++) { // std::cout << poly2Long(plaintextResult[i]) << "", ""; // } // std::cout << std::endl; // // ea.decrypt(ciphertextWs[0], secretKey, plaintextResult); // for (unsigned long i = 0; i < wordLength; i++) { // std::cout << poly2Long(plaintextResult[i]) << "", ""; // } // std::cout << std::endl; // ea.decrypt(conjResult, secretKey, plaintextResult); // for(unsigned long i = 0; i < wordLength; i++) { // std::cout << poly2Long(plaintextResult[i]) << "", ""; // } // std::cout << std::endl; // for(unsigned long i = 0; i < conjSize; i++) { // ea.decrypt(ciphertextConj[i],secretKey, plaintextResult); // for(unsigned long i = 0; i < wordLength; i++) { // std::cout << poly2Long(plaintextResult[i]) << "", ""; // } // std::cout << std::endl; // } // std::cout << std::endl; std::clog << std::endl; } ",invertSelection 111,"/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* PhoneBook.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: otodd <> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/11/18 15:43:51 by otodd #+# #+# */ /* Updated: 2025/01/21 14:41:01 by otodd ### ########.fr */ /* */ /* ************************************************************************** */ #include ""../include/PhoneBook.hpp"" PhoneBook::PhoneBook() { this->length = 0; for (int i = 0; i <= 7; i++) this->contacts[i].index = i; } void PhoneBook::add(Contact *contact) { contact->isPopulated = true; this->contacts[this->length % 8] = *contact; for (int i = 0; i <= 7; i++) this->contacts[i].index = i; this->length++; } std::string PhoneBook::trunc(std::string str) { std::string tmp = """"; for (int i = 0; str[i]; i++) { if (i == 9) { tmp += '.'; break; } else tmp += str[i]; } return (tmp); } void PhoneBook::display(size_t index) { if (index > 7) { std::cout << ""═ Invalid index."" << std::endl; return; } if (this->contacts[index].isPopulated) { std::stringstream tmp; tmp << (this->contacts[index].index + 1); std::cout << '\n' << ""╔ "" << ""Contact Index: "" << tmp.str() << '\n'; std::cout << ""╟ "" << ""Contact Firstname: "" << this->contacts[index].firstName << '\n'; std::cout << ""╟ "" << ""Contact Lastname: "" << this->contacts[index].lastName << '\n'; std::cout << ""╟ "" << ""Contact Nickname: "" << this->contacts[index].nickname << '\n'; std::cout << ""╟ "" << ""Contact Phone Number: "" << this->contacts[index].phoneNumber << '\n'; std::cout << ""╚ "" << ""Contact Darkest Secret: "" << this->contacts[index].darkestSecret << std::endl; } else std::cout << ""═ Contact index doesn't yet exist."" << std::endl; } bool PhoneBook::display() { if (!this->length) { std::cout << ""═ No records in phonebook."" << std::endl; return (false); } std::cout << "" ___________________________________________"" << std::endl; std::cout << ""| Index|First Name|Last Name |Nickname |"" << std::endl; for (int i = 0; i <= 7; i++) { if (this->contacts[i].isPopulated) { std::stringstream tmp; tmp << ""|"" << std::right << std::setw(10) << (this->contacts[i].index + 1); std::cout << std::right << std::setw(10) << tmp.str(); std::cout << ""|"" << std::right << std::setw(10) << this->trunc(this->contacts[i].firstName); std::cout << ""|"" << std::right << std::setw(10) << this->trunc(this->contacts[i].lastName); std::cout << ""|"" << std::right << std::setw(10) << this->trunc(this->contacts[i].nickname) << ""|"" << std::endl; } } std::cout << "" ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾"" << std::endl; return (true); } static void getInput(std::string *input, std::string prompt) { std::cout << prompt; while (true) { std::getline(std::cin, (*input)); if ((*input).empty()) { std::cout << ""═ Field cannot be empty.\n""; std::cout << prompt; } else break; } } void PhoneBook::addCommand() { Contact contact; getInput(&contact.firstName, ""╔ Firstname: ""); getInput(&contact.lastName, ""╟ Lastname: ""); getInput(&contact.nickname, ""╟ Nickname: ""); getInput(&contact.phoneNumber, ""╟ Phone Number: ""); getInput(&contact.darkestSecret, ""╚ Darkest Secret: ""); this->add(&contact); } void PhoneBook::searchCommand() { std::string [MASK] ; int queryInt; if (this->display()) { std::cout << ""═ Enter index of contact to show: ""; std::getline(std::cin, [MASK] ); queryInt = atoi( [MASK] .c_str()); if (queryInt <= 0) std::cout << ""═ Invalid index."" << std::endl; else this->display(queryInt - 1); } } void PhoneBook::lowerCommand(std::string *str) { for (size_t i = 0; i <= (*str).length(); i++) { if (isalpha((*str)[i])) (*str)[i] = tolower((*str)[i]); } } ",queryStr 112,"/* * @author 707<> * This program searches the shortest path. */ #include #include #include #include #include #include ""short_path.h"" int main(int argc, char const *argv[]) { const char *topo[5000] = { // ""0,0,1,1\n"", // ""2,0,3,1\n"", // ""1,0,2,2\n"", // ""3,2,1,3\n"", // ""4,3,1,1\n"", // ""5,2,3,1\n"", // ""6,3,2,1\n"" ""0,0,13,15\n"", ""1,0,8,17\n"", ""2,0,19,1\n"", ""3,0,4,8\n"", ""4,1,0,4\n"", ""5,2,9,19\n"", ""6,2,15,8\n"", ""7,3,0,14\n"", ""8,3,11,12\n"", ""9,4,1,15\n"", ""10,4,5,17\n"", ""11,5,8,180\n"", ""12,5,9,14\n"", ""13,5,6,2\n"", ""14,6,17,4\n"", ""15,7,13,1\n"", ""16,7,16,19\n"", ""17,8,6,1\n"", ""18,8,12,17\n"", ""19,9,14,11\n"", ""20,10,12,1\n"", ""21,11,7,12\n"", ""22,11,4,7\n"", ""23,12,14,5\n"", ""24,13,17,12\n"", ""25,13,4,2\n"", ""26,14,19,9\n"", ""27,15,10,14\n"", ""28,15,180,2\n"", ""29,16,8,1\n"", ""30,17,9,14\n"", ""31,17,19,3\n"", ""32,17,180,10\n"", ""33,180,15,8\n"", ""34,180,3,8\n"", ""35,19,180,12\n"", ""36,2,3,20\n"", ""37,3,5,20\n"", ""38,5,7,20\n"", ""39,7,11,20\n"", ""40,11,13,20\n"", ""41,17,11,20\n"", ""42,11,19,20\n"", ""43,17,5,20\n"", ""44,5,19,20\n"" }; //int edgeNum = 7; int edgeNum = 45; //const char *demand = ""0,1,2|3""; const char *demand = ""2,19,3|5|7|11|13|17""; std::vector result = findPath(topo, edgeNum, demand); printPath(result); return 0; } std::vector findPath(const char **topo, const int edgeNum, const char *demand) { std::vector path; int pathWeight = 0xFFFF; std::vector sortedTopo = sortByIn(topo, edgeNum); std::vector dmd = getDemand(demand); int start = dmd[0]; std::vector arcs = findArcs(start, sortedTopo); // create root from the start. Node *root = new Node(NULL, arcs[0].in, 0, arcs); root->addExistNode(arcs[0].in); while (root != NULL) { while (root->notVisit.size() > 0) { std::vector::iterator arc = root->notVisit.begin(); if (!nodeAlreadyExist(arc->out, root)) { Node *node = insertNode(root, arc, sortedTopo); if (node->num == dmd[1]) { calTheShortestPath(path, node, pathWeight, dmd); delete node; root->notVisit.erase(arc); } else { root->notVisit.erase(arc); root = node; } } else { root->notVisit.erase(arc); } } Node *toBeDel = root; root = root->parent; delete toBeDel; } return path; } /* sort the topo list by in-degree. use the insert sort algorithm. */ std::vector sortByIn(const char **topo, const int edgeNum) { std::vector arcs = restore2Int(topo, edgeNum); for (std::vector::iterator i = arcs.begin()+1; i != arcs.end(); ++i) { std::vector::iterator j = i; while (j > arcs.begin() && (j-1)->in > j->in) { std::swap(*j, *(j-1)); --j; } } return arcs; } /* change the topo list from char to int. */ std::vector restore2Int(const char **topo, const int edgeNum) { std::vector arcs; for (size_t i = 0; i < edgeNum; ++i) { int tmpArc[4]; int used = 0; int tmp = 0; size_t j = 0; while (topo[i][j] != '\n') { if (isdigit(topo[i][j])) { tmp = tmp * 10 + (topo[i][j] - '0'); } else { tmpArc[used++] = tmp; tmp = 0; } ++j; } tmpArc[used] = tmp; Arc arc(tmpArc[0], tmpArc[1], tmpArc[2], tmpArc[3]); arcs.push_back(arc); } return arcs; } /* change the demand from char to int. */ std::vector getDemand(const char *demand) { std::vector dmd; int tmp = 0; for (size_t i = 0; i < strlen(demand); ++i) { if (isdigit(demand[i])) { tmp = tmp * 10 + (demand[i] - '0'); } else { dmd.push_back(tmp); tmp = 0; } } dmd.push_back(tmp); return dmd; } /* find corresponding arcs by the in-degree node number. */ std::vector findArcs(int inNode, std::vector arcs) { std::vector [MASK] ; for (std::vector::iterator i = arcs.begin(); i != arcs.end(); ++i) { if (i->in == inNode) { [MASK] .push_back(*i); } } return [MASK] ; } /* test the node exist or not in the path by compare the bit position. */ bool nodeAlreadyExist(int out, Node *root) { if (root->exist.size() > out/32) { if ((1 << (out%32) & root->exist[out/32]) > 0) { return true; } else { return false; } } else { return false; } } Node *insertNode(Node *root, std::vector::iterator &arc, std::vector &arcs) { Node *node = new Node(root, arc->out, arc->num, arc->weight + root->weight, root->exist, findArcs(arc->out, arcs)); node->addExistNode(arc->out); return node; } void printPath(std::vector result) { for (std::vector::iterator i = result.begin(); i != result.end(); ++i) { std::cout << *i << "" ""; } std::cout << std::endl; } /* add the node info to the bit position. */ void Node::addExistNode(int num) { int needed = num/32 + 1 - this->exist.size(); if (needed > 0) { for (size_t i = 0; i < needed; ++i) { unsigned int tmp = 0; this->exist.push_back(tmp); } } this->exist[num/32] |= (1 << num); } void calTheShortestPath(std::vector &path, Node *node, int &pathWeight, std::vector &demand) { for (std::vector::iterator j = demand.begin()+2; j != demand.end(); ++j) { if (!nodeAlreadyExist(*j, node)) { return; } } // print paths. // temporary. Node *tmp = node; while (tmp != NULL) { std::cout << tmp->num << "" ""; tmp = tmp->parent; } std::cout << std::endl; if (path.empty()) { pathWeight = node->weight; while (node->parent != NULL) { path.insert(path.begin(), node->arc); node = node->parent; } } else { if (node->weight < pathWeight) { pathWeight = node->weight; path.clear(); while (node->parent != NULL) { path.insert(path.begin(), node->arc); node = node->parent; } } } }",found 113,"// Compile with // cd demos/ // g++ -std=c++14 -Iinclude demo_simple.cpp -o demo_simple // // Edit and compile this file without installing anything at // https://gitpod.io/#https://github.com/pthom/cleantype/blob/master/demos/demo_simple.cpp // #include #include #include #define LOG(...) std::cout << __VA_ARGS__ << ""\n""; void demo() { // First, let's define a variable for demonstration purpose std::set my_set { ""Hello"", ""There""}; // let's ask CleanType to give us the type of ""my_set"" // cleantype::full will return the *full* type info LOG( cleantype::full(my_set) ); // outputs: // std::set, std::allocator>, std::less, std::allocator>>, std::allocator, std::allocator>>> & // Ouch, that was barely readable! // cleantype::clean will return a *readable* type LOG( cleantype::clean(my_set) ); // outputs: // std::set & // Let's now show the content of ""my_set"" together with its type LOG( cleantype::show_details(my_set) ); // outputs: // std::set & = [Hello, There] // Yes, but what about lambdas? Could you guess the signature of the lambda below? auto lambda_example = []() { // when C++ meets js... return +!!""""; // See https://blog.knatten.org/2018/10/12/1662 }; // cleantype::lambda_clean returns the signature of lambda functions LOG( cleantype::lambda_clean(lambda_example) ); // outputs: // lambda: () -> int // Ok, maybe this was too easy. Let's try with a generic lambda! auto add = [](auto a, auto b) { return a + b; }; // Now, can we see its signature? // Yes, we just need to specify the input argument types. LOG( cleantype::lambda_clean(add) ); // outputs: // lambda: (std::string, char) -> std::string } // Can CleanType understand some more complex libraries // like range-v3 where most variables, functions and lambdas are of type ""auto""? // Well... yes! #include using namespace ranges; auto square_yield_fn(int x) { return ranges::yield(x * x); } void demo_ranges() { auto squares_view = view::for_each(view::ints(1), square_yield_fn); // What is the type of squares_view? // Let's see... LOG( cleantype::clean(squares_view) ); // outputs: // ranges::v3::join_view, ranges::v3::single_view(*)(int)>, void> & // Let's make it more complex yet: auto [MASK] = squares_view | view::take(10); // As you will see below, CleanType can indent the types // when they get more complex! LOG( cleantype::clean( [MASK] ) ); // outputs: // ranges::v3::detail::take_exactly_view_< // ranges::v3::join_view< // ranges::v3::transform_view< // ranges::v3::iota_view< // int, // void // >, // ranges::v3::single_view< // int // > (*)(int) // >, // void // >, // false // > & } int main() { demo(); demo_ranges(); }",squares_take_10 114,"#ifndef EXPERIMENTS_ANODEIMPL_H #define EXPERIMENTS_ANODEIMPL_H #include ""ANodeDecl.h"" #include ""BuilderDecl.h"" template class ADAPTER> ANode::ANode(const ANode &otherNode) : childrenCount_(otherNode.childrenCount_), origin_(otherNode.origin_), isLeaf_(otherNode.isLeaf_) { for (int i = 0; i < childrenCount_; i++) { children_[i] = otherNode.children_[i]; cumSize_[i] = otherNode.cumSize_[i]; offset_[i] = otherNode.offset_[i]; } } template class ADAPTER> ANode::ANode(ANode &&otherNode) noexcept : childrenCount_(otherNode.childrenCount_), origin_(std::move(otherNode.origin_)), isLeaf_(otherNode.isLeaf_) { for (int i = 0; i < childrenCount_; i++) { children_[i] = std::move(otherNode.children_[i]); cumSize_[i] = otherNode.cumSize_[i]; offset_[i] = otherNode.offset_[i]; } otherNode.childrenCount_ = 0; } template class ADAPTER> int8_t ANode::height() const { return std::visit([](const auto originPtr) { return originPtr->height(); }, origin_); } template class ADAPTER> size_t ANode::originSize() const { return std::visit([](const auto originPtr) { return originPtr->size(); }, origin_); } template class ADAPTER> size_t ANode::maxCompactionSize() const { if (!height()) { return SIZE / MAX_COUNT; } return size_t(1) << ((log(SIZE) - 1) + (log(MAX_COUNT) - 1) * (height() - 1)); } template class ADAPTER> size_t ANode::retainedSize() const { size_t result = 0; for (size_t i = 0; i < childrenCount_; i++) { if (!children_[i]) { result += childRetainedSize(i); } } return result; } template class ADAPTER> size_t ANode::fillLeaf(const ANode::VarType &child, T *destLeaf, size_t offset, size_t length) { return std::visit([&](const auto &nodePtr) { return nodePtr->fillLeaf(destLeaf, offset, length); }, child); } template class ADAPTER> template decltype(auto) ANode::visitChild(Visitor &&_visitor, size_t childPos) const { if (!children_[childPos]) { return std::visit(std::forward(_visitor), origin_); } if (isLeaf_[childPos]) { return _visitor(static_cast(children_[childPos].get())); } return _visitor(static_cast(children_[childPos].get())); } template class ADAPTER> size_t ANode::fillLeaf(T *destLeaf, size_t offset, size_t length) const { if (offset >= size()) { return 0; } length = std::min(length, size() - offset); auto totalLen = length; for (size_t childPos = lowerBoundPos(offset + 1); childPos < childrenCount_ && length != 0; childPos++) { size_t childOffset = childPos == 0 ? 0 : cumSize_[childPos - 1]; assert(childOffset <= offset); size_t elementsRead = visitChild([&](const auto &childPtr) { int localOffset = offset - childOffset; return childPtr->fillLeaf(destLeaf, offset_[childPos] + localOffset, std::min(length, childRetainedSize(childPos) - localOffset)); }, childPos); offset += elementsRead; length -= elementsRead; destLeaf += elementsRead; } assert(length == 0); return totalLen; } template class ADAPTER> const T &ANode::operator[](size_t index) const { assert(index < size()); auto childPos = lowerBoundPos(index + 1); return visitChild([&](const auto &childPtr) -> const T & { return (*childPtr)[offset_[childPos] + index - (childPos ? cumSize_[childPos - 1] : 0)]; }, childPos); } template class ADAPTER> auto ANode::childAt( size_t childPos) const -> const std::variant { assert(childPos < childrenCount_); if (!children_[childPos]) { return {origin_}; } if (isLeaf_[childPos]) { return {static_cast(children_[childPos].get())}; } return {static_cast(children_[childPos].get())}; } template class ADAPTER> size_t ANode::normalizeLength(size_t length, size_t offset, size_t incomingSize) const { if (offset > incomingSize) { //just in case, in release mode we ignore such usages return 0; } //Normalize length to the max available if (length > incomingSize - offset) { return incomingSize - offset; } return length; } template class ADAPTER> template bool ANode::canAcceptNode(const NODE_T &incomingNode, bool asPrefix, size_t offset, size_t length) const { if constexpr (std::is_same_v || std::is_same_v) { return false; } length = normalizeLength(length, offset, incomingNode->size()); if (length == 0) { return true; } if (childrenCount_ == MAX_COUNT) { const void *pointerToAdd = isOrigin(incomingNode) ? nullptr : static_cast(incomingNode.get()); if (asPrefix) { if (pointerToAdd == (children_[0] ? children_[0].get() : nullptr) && offset + length == offset_[0]) { return true; } } else if ( pointerToAdd == (children_[childrenCount_ - 1] ? children_[childrenCount_ - 1].get() : nullptr) && offset == offset_[childrenCount_ - 1] + cumSize_[childrenCount_ - 1] - (childrenCount_ > 1 ? cumSize_[childrenCount_ - 2] : 0)) { return true; } if (!canCompact()) { return false; } } if (isOrigin(incomingNode)) { return true; } if (height()) { if (incomingNode->height() < height()) { return length >= minChildRetention(incomingNode); } return false; } return length <= SIZE * 2 / MAX_COUNT; } template class ADAPTER> template size_t ANode::minChildRetention(const NODE_T &incomingNode) { constexpr bool isBNode = std::is_same_v, BNodePtr> or std::is_same_v, BNodeCPtr>; if constexpr (isBNode) { return (incomingNode->size() / incomingNode->childrenCount()); } else { return 1; } } template class ADAPTER> void ANode::shiftNodes(size_t startPos, size_t [MASK] , int64_t sizeDelta) { assert( [MASK] > childrenCount_); for (size_t i = 1; i <= childrenCount_ - startPos; i++) { offset_[ [MASK] - i] = offset_[childrenCount_ - i]; cumSize_[ [MASK] - i] = cumSize_[childrenCount_ - i] + sizeDelta; children_[ [MASK] - i] = std::move(children_[childrenCount_ - i]); isLeaf_[ [MASK] - i] = isLeaf_[childrenCount_ - i]; } } template class ADAPTER> template bool ANode::isOrigin(const NODE_T &incomingNode) const { return std::visit([&](const auto &ptr) { return static_cast(ptr.get()); }, origin_) == static_cast(incomingNode.get()); } template class ADAPTER> template void ANode::addNode(NODE_T &&incomingNode, size_t offset, size_t length, bool asPrefix, void *context) { if constexpr (std::is_same_v::VarType, std::remove_cvref_t>) { addNodeVar(std::forward(incomingNode), offset, length, asPrefix); } else if constexpr (std::is_null_pointer_v) { addNode(origin_, offset, length, asPrefix); return; } else { if (!incomingNode) { addNode(origin_, offset, length, asPrefix); return; } assert(offset < incomingNode->size()); if (!incomingNode->isConst()) { throw std::logic_error(""Can only add const children""); } bool isLeaf; if constexpr (std::is_same_v, LeafCPtr>) { isLeaf = true; } else if constexpr (std::is_same_v, BNodeCPtr>) { isLeaf = false; } else { throw std::logic_error(""Unsupported type""); } //Normalize length to the max available length = normalizeLength(length, offset, incomingNode->size()); if (!length) { //zero size additions need to be ignored return; } assert(canAcceptNode(incomingNode, asPrefix, offset, length)); GenericCPtr pointerToAdd; if (!isOrigin(incomingNode)) { pointerToAdd = std::static_pointer_cast(std::forward(incomingNode)); } if (childrenCount_) { //checking if the added node fits the existing node in place if (asPrefix) { if (pointerToAdd == children_[0] && offset + length == offset_[0]) { offset_[0] -= length; for (int i = 0; i < childrenCount_; i++) { cumSize_[i] += length; } return; } } else if (pointerToAdd == children_[childrenCount_ - 1] && offset == offset_[childrenCount_ - 1] + cumSize_[childrenCount_ - 1] - (childrenCount_ > 1 ? cumSize_[ childrenCount_ - 2] : 0)) { cumSize_[childrenCount_ - 1] += length; return; } } if (childrenCount_ == MAX_COUNT) { compact(context); } assert(childrenCount_ < MAX_COUNT); size_t destPos = asPrefix ? 0 : childrenCount_; if (asPrefix) { shiftNodes(0, childrenCount_ + 1, length); cumSize_[0] = length; } else { cumSize_[childrenCount_] = size() + length; } offset_[destPos] = offset; children_[destPos] = std::move(pointerToAdd); isLeaf_[destPos] = isLeaf; childrenCount_++; } } template class ADAPTER> void ANode::addNodeVar(ANode::VarType &&incomingNode, size_t offset, size_t length, bool asPrefix) { std::visit([&](auto &&nodePtr) { addNode(std::move(nodePtr), offset, length, asPrefix); }, std::move(incomingNode)); } template class ADAPTER> void ANode::addNodeVar(const ANode::VarType &incomingNode, size_t offset, size_t length, bool asPrefix) { std::visit([&](const auto &nodePtr) { addNode(nodePtr, offset, length, asPrefix); }, incomingNode); } template class ADAPTER> void ANode::removeNodes(uint16_t startPoint, uint16_t count) { assert(count <= childrenCount_); size_t sizeDelta = cumSize_[startPoint + count - 1] - (startPoint > 0 ? cumSize_[startPoint - 1] : 0); for (int i = startPoint; i < childrenCount_ - count; i++) { offset_[i] = offset_[i + count]; cumSize_[i] = cumSize_[i + count] - sizeDelta; children_[i] = std::move(children_[i + count]); isLeaf_[i] = isLeaf_[i + count]; } childrenCount_ -= count; } template class ADAPTER> bool ANode::canCompact() const { assert(childrenCount_); size_t prevSum = childRetainedSize(0); for (uint16_t i = 1; i < childrenCount_; i++) { size_t currentSum = childRetainedSize(i); if (prevSum + currentSum <= maxCompactionSize()) { return true; } prevSum = currentSum; } return false; } template class ADAPTER> void ANode::compact(void *context) { assert(childrenCount_); size_t runningSum = 0; uint16_t windowStart = 0; for (uint16_t i = 0; i < childrenCount_; i++) { size_t currentSum = childRetainedSize(i); if (runningSum + currentSum <= maxCompactionSize()) { runningSum += currentSum; } else { if (i - windowStart > 1) { compact(windowStart, i - windowStart, context); return; } if (currentSum < maxCompactionSize()) { windowStart = i; runningSum = currentSum; } else { windowStart = i + 1; runningSum = 0; } } } if (childrenCount_ - windowStart > 1) { compact(windowStart, childrenCount_ - windowStart, context); return; } throw std::logic_error(""Unable to compact (should call canCompactFirst)""); } template class ADAPTER> auto ANode::createNodePtr(const ANode &src) -> ANode::ANodePtr { static auto &alloc = StdFixedAllocator::oneAndOnly(); auto p = alloc.allocate(1); alloc.construct(p, src); return ANodePtr(p); } template class ADAPTER> auto ANode::createNodePtr(ANode &&src) -> ANode::ANodePtr { static auto &alloc = StdFixedAllocator::oneAndOnly(); auto p = alloc.allocate(1); alloc.construct(p, std::move(src)); return ANodePtr(p); } template class ADAPTER> void ANode::compact(uint16_t fromNode, uint16_t nodeCount, void *context) { BuilderT builder(height() - 1); builder.setContext(context); size_t expectedSize = 0; for (uint16_t pos = fromNode; pos < fromNode + nodeCount; pos++) { expectedSize += childRetainedSize(pos); if (!children_[pos]) { builder.addNode(origin_, offset_[pos], childRetainedSize(pos)); } else if (isLeaf_[pos]) { builder.addNode(std::static_pointer_cast(std::move(children_[pos])), offset_[pos], childRetainedSize(pos)); } else { builder.addNode(std::static_pointer_cast(std::move(children_[pos])), offset_[pos], childRetainedSize(pos)); } } size_t newSize = builder.size(); assert(expectedSize == newSize); while (builder.isAnode()) { builder.pushDownAnnotations(); newSize = builder.size(); assert(expectedSize == newSize); } std::visit([&](auto &&nodePtr) { if constexpr (is_unique_ptr_v) { throw std::logic_error(""Builder must return const nodes""); } else if constexpr (std::is_same_v>) { throw std::logic_error(""Builder should not return an ANode""); } else { children_[fromNode] = std::static_pointer_cast(nodePtr); isLeaf_.set(fromNode, std::is_same_v>); } }, builder.close(false)); offset_[fromNode] = 0; cumSize_[fromNode] = newSize + (fromNode ? cumSize_[fromNode - 1] : 0); removeNodes(fromNode + 1, nodeCount - 1); } template class ADAPTER> template void ANode::forEachChildMove(Visitor &&visitor, size_t offset, size_t length, bool asPrefix) { length = std::min(length, size() - offset); size_t firstNodePos, lastNodePos; std::tie(firstNodePos, lastNodePos) = nodeRangeInclusive(offset, length); size_t currentOffset = offset - (firstNodePos ? cumSize_[firstNodePos - 1] : 0); auto visitorInternal = [&](auto &&child, bool isLeaf, size_t childOffset, size_t childLen) { if (!child) { if (origin_.index() == 0) { visitor(std::get(origin_), childOffset, childLen); } else { visitor(std::get(origin_), childOffset, childLen); } } else if (isLeaf) { visitor(std::static_pointer_cast(std::move(child)), childOffset, childLen); } else { visitor(std::static_pointer_cast(std::move(child)), childOffset, childLen); } }; if (asPrefix) { if (firstNodePos != lastNodePos) { visitorInternal(std::move(children_[lastNodePos]), isLeaf_[lastNodePos], offset_[lastNodePos], length + offset - cumSize_[lastNodePos - 1]); length = cumSize_[lastNodePos - 1] - offset; for (auto i = lastNodePos - 1; i > firstNodePos; i--) { visitorInternal(std::move(children_[i]), isLeaf_[i], offset_[i], sizeAt(i)); length -= sizeAt(i); } } visitorInternal(std::move(children_[firstNodePos]), isLeaf_[firstNodePos], offset_[firstNodePos] + currentOffset, length); } else { for (auto i = firstNodePos; i < lastNodePos; i++) { size_t len = sizeAt(i) - currentOffset; visitorInternal(std::move(children_[i]), isLeaf_[i], offset_[i] + currentOffset, sizeAt(i) - currentOffset); currentOffset = 0; length -= len; } visitorInternal(std::move(children_[lastNodePos]), isLeaf_[lastNodePos], offset_[lastNodePos] + currentOffset, std::min(sizeAt(lastNodePos) - currentOffset, length)); } } template class ADAPTER> template void ANode::forEachChild(Visitor &&visitor, size_t offset, size_t length, bool asPrefix) const { auto visitorInternal = [&](const auto &child, bool isLeaf, size_t childOffset, size_t childLen) { if (!child) { if (origin_.index() == 0) { visitor(std::get(origin_), childOffset, childLen); } else { visitor(std::get(origin_), childOffset, childLen); } } else if (isLeaf) { visitor(std::static_pointer_cast(child), childOffset, childLen); } else { visitor(std::static_pointer_cast(child), childOffset, childLen); } }; length = std::min(length, size() - offset); size_t firstNodePos, lastNodePos; std::tie(firstNodePos, lastNodePos) = nodeRangeInclusive(offset, length); size_t currentOffset = offset - (firstNodePos ? cumSize_[firstNodePos - 1] : 0); if (asPrefix) { if (firstNodePos != lastNodePos) { visitorInternal(children_[lastNodePos], isLeaf_[lastNodePos], offset_[lastNodePos], length + offset - cumSize_[lastNodePos - 1]); length = cumSize_[lastNodePos - 1] - offset; for (auto i = lastNodePos - 1; i > firstNodePos; i--) { visitorInternal(children_[i], isLeaf_[i], offset_[i], sizeAt(i)); length -= sizeAt(i); } } visitorInternal(children_[firstNodePos], isLeaf_[firstNodePos], offset_[firstNodePos] + currentOffset, length); } else { for (auto i = firstNodePos; i < lastNodePos; i++) { size_t len = sizeAt(i) - currentOffset; visitorInternal(children_[i], isLeaf_[i], offset_[i] + currentOffset, len); currentOffset = 0; length -= len; } visitorInternal(children_[lastNodePos], isLeaf_[lastNodePos], offset_[lastNodePos] + currentOffset, std::min(sizeAt(lastNodePos) - currentOffset, length)); } } template class ADAPTER> std::tuple ANode::nodeRangeInclusive(size_t offset, size_t length) const { size_t firstNodePos = std::upper_bound(cumSize_.begin(), cumSize_.begin() + childrenCount_, offset) - cumSize_.begin(); size_t lastNodePos = lowerBoundPos(offset + length); return {firstNodePos, lastNodePos}; } template class ADAPTER> size_t ANode::lowerBoundPos(size_t offset) const { return std::lower_bound(cumSize_.begin(), cumSize_.begin() + childrenCount_, offset) - cumSize_.begin(); } #endif //EXPERIMENTS_ANODEIMPL_H ",newCount 115,"#include ""application.h"" #include ""constants.h"" cm::application::application(std::shared_ptr map, std::shared_ptr log) : map(map), kill_timer(ios), signal_set(ios), completed_apps(0), log(log), shutdown_running(false) { setup_signal_set(); } void cm::application::run() { setup_children(); set_signal_handler(); ios.run(); } void cm::application::kill_timeout_handler(const boost::system::error_code &ec) { for (auto &it : children) { if (it.second->terminated()) continue; log->err(app_name, ""Forcibly terminating app "" + it.first); it.second->kill(); } } void cm::application::all_down_handler() { log->err(app_name, ""Shutdown complete""); signal_set.cancel(); kill_timer.cancel(); } void cm::application::shutdown_handler() { bool expected = false; bool first = shutdown_running.compare_exchange_strong(expected, true); log->err(app_name, ""Shutdown: total children: "" + std::to_string(map->apps.size()) + "", completed: "" + std::to_string(completed_apps.load())); if (completed_apps.load() == map->apps.size()) { log->err(app_name, ""All completed""); all_down_handler(); return; } if (first) { log->err(app_name, ""Shutdown initiated""); for (auto &it : children) { if (it.second->terminated()) continue; log->err(app_name, ""Terminating app "" + it.first); it.second->terminate(); } kill_timer.expires_from_now(map->kill_delay); kill_timer.async_wait([this](auto &ec) { kill_timeout_handler(ec); }); } } void cm::application::signal_handler(const boost::system::error_code &ec, int signal_number) { auto ss = find_if(signals.begin(), signals.end(), [&](auto &s) { return s.first == signal_number; }); if (ss == signals.end()) log->err(app_name, ""Handling signal with number "" + std::to_string(signal_number) + "" (unknown)""); else log->err(app_name, ""Handling signal with number "" + std::to_string(signal_number) + "" ("" + (*ss).second + "")""); switch (signal_number) { case SIGINT: case SIGQUIT: case SIGTERM: shutdown_handler(); break; default: break; } if (!shutdown_running.load()) set_signal_handler(); } void cm::application::set_signal_handler() { log->err(app_name, ""Setting signal handler""); signal_set.async_wait([this](auto &ec, int signo) { signal_handler(ec, signo); }); } void cm::application::setup_children() { log->err(app_name, ""Starting applications""); for (const config_map::configured_application &app : map->apps) { try { boost::filesystem::path path; if (boost::filesystem::exists(app.executable)) path = app.executable; else path = bp::search_path(app.executable); std::unique_ptr a = std::make_unique( app.name, path, app.args, boost::filesystem::canonical(app.context), app.env, app.term_signal, ios, proc_group ); a->set_on_stdout([this, &app](const child::stream_content_type &buf) { linebuffer.available(app.name + ""_out"", buf, [this, app](const std::string &line) { log->out(app.name, line); }); }); a->set_on_stderr([this, &app](const child::stream_content_type &buf) { linebuffer.available(app.name + ""_err"", buf, [this, app](const std::string &line) { log->err(app.name, line); }); }); a->set_on_exit([this, &app](const int [MASK] , const std::error_code &code) { log->err(app_name, ""Application "" + app.name + "" exited with code "" + std::to_string( [MASK] ) + "".""); completed_apps++; if (app.fail_on_exit) { shutdown_handler(); } else { if ( [MASK] != 0) { if (app.fail_on_nonzero_exit) shutdown_handler(); } } }); children[app.name] = std::move(a); } catch (bp::process_error &e) { log->err(app_name, ""Failed to start process: "" + app.name + "": "" + e.what() + "". executable is: "" + app.executable); throw std::runtime_error(e.what()); } } } void cm::application::setup_signal_set() { log->err(app_name, ""Setting signal handlers""); for (const auto &signal : signals) { try { signal_set.add(signal.first); } catch (const std::runtime_error &e) { std::cout << signal.first << signal.second << e.what() << ""\n""; log->err(app_name, e.what()); return; } } } ",exit_code 116,"#include ""AppDelegate.h"" #include ""HelloWorldScene.h"" #include ""scene\GameScene.h"" #include ""scene\FightScene.h"" #include ""scene\LoginScene.h"" #include ""util\MyProtoSocket.h"" USING_NS_CC; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { } //if you want a different context,just modify the value of glContextAttrs //it will takes effect on all platforms void AppDelegate::initGLContextAttrs() { //set OpenGL context attributions,now can only set six attributions: //red,green,blue,alpha,depth,stencil GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; GLView::setGLContextAttrs(glContextAttrs); } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto [MASK] = director->getOpenGLView(); if(! [MASK] ) { [MASK] = GLViewImpl::createWithRect(""IceVirgin"", Rect(0, 0, 800, 500)); director->setOpenGLView( [MASK] ); int i = 0; } director->getOpenGLView()->setDesignResolutionSize(800, 500, ResolutionPolicy::SHOW_ALL); // turn on display FPS //director->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0 / 60); FileUtils::getInstance()->addSearchPath(""res""); //开启网络 MyProtoSocket::connect(); // create a scene. it's an autorelease object //auto * layer = GameScene::create(); //auto * layer = FightScene::create(); auto * layer = LoginScene::create(); auto scene = Common::scene(layer); // run director->runWithScene(scene); //子线程无法更新UI std::thread threadRecv(&AppDelegate::recev, this); threadRecv.detach(); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { Director::getInstance()->stopAnimation(); // if you use SimpleAudioEngine, it must be pause // SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { Director::getInstance()->startAnimation(); // if you use SimpleAudioEngine, it must resume here // SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); } void AppDelegate::recev() { while (true) { //Sleep(10); MyProtoSocket::receive(); } } ",glview 117,"// Copyright (C) 2009 The Libphonenumber Authors // // 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. // Author: // Author: // Open-sourced by: // // Note that these tests use the metadata contained in the test metadata file, // not the normal metadata file, so should not be used for regression test // purposes - these tests are illustrative only and test functionality. #include ""phonenumbers/phonenumberutil.h"" #include #include #include #include #include #include #include ""phonenumbers/default_logger.h"" #include ""phonenumbers/phonemetadata.pb.h"" #include ""phonenumbers/phonenumber.h"" #include ""phonenumbers/phonenumber.pb.h"" #include ""phonenumbers/test_util.h"" namespace i18n { namespace phonenumbers { using std::endl; using std::find; using std::make_pair; using std::ostream; using google::protobuf::RepeatedPtrField; static const int kInvalidCountryCode = 2; class PhoneNumberUtilTest : public testing::Test { protected: PhoneNumberUtilTest() : phone_util_(*PhoneNumberUtil::GetInstance()) { PhoneNumberUtil::GetInstance()->SetLogger(new StdoutLogger()); } // Wrapper functions for private functions that we want to test. const PhoneMetadata* GetPhoneMetadata(const string& region_code) const { return phone_util_.GetMetadataForRegion(region_code); } const PhoneMetadata* GetMetadataForNonGeographicalRegion( int country_code) const { return phone_util_.GetMetadataForNonGeographicalRegion(country_code); } void GetSupportedRegions(set* regions) { phone_util_.GetSupportedRegions(regions); } void GetRegionCodesForCountryCallingCode( int country_calling_code, list* regions) { phone_util_.GetRegionCodesForCountryCallingCode(country_calling_code, regions); } void ExtractPossibleNumber(const string& number, string* extracted_number) const { phone_util_.ExtractPossibleNumber(number, extracted_number); } bool CanBeInternationallyDialled(const PhoneNumber& number) const { return phone_util_.CanBeInternationallyDialled(number); } bool IsViablePhoneNumber(const string& number) const { return phone_util_.IsViablePhoneNumber(number); } void Normalize(string* number) const { phone_util_.Normalize(number); } void NormalizeDiallableCharsOnly(string* number) const { phone_util_.NormalizeDiallableCharsOnly(number); } bool IsNumberGeographical(const PhoneNumber& phone_number) const { return phone_util_.IsNumberGeographical(phone_number); } bool IsLeadingZeroPossible(int country_calling_code) const { return phone_util_.IsLeadingZeroPossible(country_calling_code); } PhoneNumber::CountryCodeSource MaybeStripInternationalPrefixAndNormalize( const string& possible_idd_prefix, string* number) const { return phone_util_.MaybeStripInternationalPrefixAndNormalize( possible_idd_prefix, number); } void MaybeStripNationalPrefixAndCarrierCode(const PhoneMetadata& metadata, string* number, string* carrier_code) const { phone_util_.MaybeStripNationalPrefixAndCarrierCode(metadata, number, carrier_code); } bool MaybeStripExtension(string* number, string* extension) const { return phone_util_.MaybeStripExtension(number, extension); } PhoneNumberUtil::ErrorType MaybeExtractCountryCode( const PhoneMetadata* default_region_metadata, bool keep_raw_input, string* national_number, PhoneNumber* phone_number) const { return phone_util_.MaybeExtractCountryCode(default_region_metadata, keep_raw_input, national_number, phone_number); } static bool Equals(const PhoneNumberDesc& expected_number, const PhoneNumberDesc& actual_number) { return ExactlySameAs(expected_number, actual_number); } bool ContainsOnlyValidDigits(const string& s) const { return phone_util_.ContainsOnlyValidDigits(s); } void GetNddPrefixForRegion(const string& region, bool strip_non_digits, string* ndd_prefix) const { // For testing purposes, we check this is empty first. ndd_prefix->clear(); phone_util_.GetNddPrefixForRegion(region, strip_non_digits, ndd_prefix); } const PhoneNumberUtil& phone_util_; private: DISALLOW_COPY_AND_ASSIGN(PhoneNumberUtilTest); }; TEST_F(PhoneNumberUtilTest, ContainsOnlyValidDigits) { EXPECT_TRUE(ContainsOnlyValidDigits("""")); EXPECT_TRUE(ContainsOnlyValidDigits(""2"")); EXPECT_TRUE(ContainsOnlyValidDigits(""25"")); EXPECT_TRUE(ContainsOnlyValidDigits(""\xEF\xBC\x96"" /* ""6"" */)); EXPECT_FALSE(ContainsOnlyValidDigits(""a"")); EXPECT_FALSE(ContainsOnlyValidDigits(""2a"")); } TEST_F(PhoneNumberUtilTest, GetSupportedRegions) { set regions; GetSupportedRegions(®ions); EXPECT_GT(regions.size(), 0U); } TEST_F(PhoneNumberUtilTest, GetRegionCodesForCountryCallingCode) { list regions; GetRegionCodesForCountryCallingCode(1, ®ions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::US()) != regions.end()); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::BS()) != regions.end()); regions.clear(); GetRegionCodesForCountryCallingCode(44, ®ions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::GB()) != regions.end()); regions.clear(); GetRegionCodesForCountryCallingCode(49, ®ions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::DE()) != regions.end()); regions.clear(); GetRegionCodesForCountryCallingCode(800, ®ions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::UN001()) != regions.end()); regions.clear(); GetRegionCodesForCountryCallingCode(kInvalidCountryCode, ®ions); EXPECT_TRUE(regions.empty()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadUSMetadata) { const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::US()); EXPECT_EQ(""US"", metadata->id()); EXPECT_EQ(1, metadata->country_code()); EXPECT_EQ(""011"", metadata->international_prefix()); EXPECT_TRUE(metadata->has_national_prefix()); ASSERT_EQ(2, metadata->number_format_size()); EXPECT_EQ(""(\\d{3})(\\d{3})(\\d{4})"", metadata->number_format(1).pattern()); EXPECT_EQ(""$1 $2 $3"", metadata->number_format(1).format()); EXPECT_EQ(""[13-689]\\d{9}|2[0-35-9]\\d{8}"", metadata->general_desc().national_number_pattern()); EXPECT_EQ(""\\d{7}(?:\\d{3})?"", metadata->general_desc().possible_number_pattern()); EXPECT_TRUE(Equals(metadata->general_desc(), metadata->fixed_line())); EXPECT_EQ(""\\d{10}"", metadata->toll_free().possible_number_pattern()); EXPECT_EQ(""900\\d{7}"", metadata->premium_rate().national_number_pattern()); // No shared-cost data is available, so it should be initialised to ""NA"". EXPECT_EQ(""NA"", metadata->shared_cost().national_number_pattern()); EXPECT_EQ(""NA"", metadata->shared_cost().possible_number_pattern()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadDEMetadata) { const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::DE()); EXPECT_EQ(""DE"", metadata->id()); EXPECT_EQ(49, metadata->country_code()); EXPECT_EQ(""00"", metadata->international_prefix()); EXPECT_EQ(""0"", metadata->national_prefix()); ASSERT_EQ(6, metadata->number_format_size()); EXPECT_EQ(1, metadata->number_format(5).leading_digits_pattern_size()); EXPECT_EQ(""900"", metadata->number_format(5).leading_digits_pattern(0)); EXPECT_EQ(""(\\d{3})(\\d{3,4})(\\d{4})"", metadata->number_format(5).pattern()); EXPECT_EQ(""$1 $2 $3"", metadata->number_format(5).format()); EXPECT_EQ(""(?:[24-6]\\d{2}|3[03-9]\\d|[789](?:[1-9]\\d|0[2-9]))\\d{1,8}"", metadata->fixed_line().national_number_pattern()); EXPECT_EQ(""\\d{2,14}"", metadata->fixed_line().possible_number_pattern()); EXPECT_EQ(""30123456"", metadata->fixed_line().example_number()); EXPECT_EQ(""\\d{10}"", metadata->toll_free().possible_number_pattern()); EXPECT_EQ(""900([135]\\d{6}|9\\d{7})"", metadata->premium_rate().national_number_pattern()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadARMetadata) { const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::AR()); EXPECT_EQ(""AR"", metadata->id()); EXPECT_EQ(54, metadata->country_code()); EXPECT_EQ(""00"", metadata->international_prefix()); EXPECT_EQ(""0"", metadata->national_prefix()); EXPECT_EQ(""0(?:(11|343|3715)15)?"", metadata->national_prefix_for_parsing()); EXPECT_EQ(""9$1"", metadata->national_prefix_transform_rule()); ASSERT_EQ(5, metadata->number_format_size()); EXPECT_EQ(""$2 15 $3-$4"", metadata->number_format(2).format()); EXPECT_EQ(""(9)(\\d{4})(\\d{2})(\\d{4})"", metadata->number_format(3).pattern()); EXPECT_EQ(""(9)(\\d{4})(\\d{2})(\\d{4})"", metadata->intl_number_format(3).pattern()); EXPECT_EQ(""$1 $2 $3 $4"", metadata->intl_number_format(3).format()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadInternationalTollFreeMetadata) { const PhoneMetadata* metadata = GetMetadataForNonGeographicalRegion(800); EXPECT_FALSE(metadata == NULL); EXPECT_EQ(""001"", metadata->id()); EXPECT_EQ(800, metadata->country_code()); EXPECT_EQ(""$1 $2"", metadata->number_format(0).format()); EXPECT_EQ(""(\\d{4})(\\d{4})"", metadata->number_format(0).pattern()); EXPECT_EQ(""12345678"", metadata->general_desc().example_number()); EXPECT_EQ(""12345678"", metadata->toll_free().example_number()); } TEST_F(PhoneNumberUtilTest, GetNationalSignificantNumber) { PhoneNumber number; number.set_country_code(1); number.set_national_number(6502530000ULL); string national_significant_number; phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ(""6502530000"", national_significant_number); // An Italian mobile number. national_significant_number.clear(); number.set_country_code(39); number.set_national_number(312345678ULL); phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ(""312345678"", national_significant_number); // An Italian fixed line number. national_significant_number.clear(); number.set_country_code(39); number.set_national_number(236618300ULL); number.set_italian_leading_zero(true); phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ(""0236618300"", national_significant_number); national_significant_number.clear(); number.Clear(); number.set_country_code(800); number.set_national_number(12345678ULL); phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ(""12345678"", national_significant_number); } TEST_F(PhoneNumberUtilTest, GetExampleNumber) { PhoneNumber de_number; de_number.set_country_code(49); de_number.set_national_number(30123456ULL); PhoneNumber test_number; bool success = phone_util_.GetExampleNumber(RegionCode::DE(), &test_number); EXPECT_TRUE(success); EXPECT_EQ(de_number, test_number); success = phone_util_.GetExampleNumberForType(RegionCode::DE(), PhoneNumberUtil::FIXED_LINE, &test_number); EXPECT_TRUE(success); EXPECT_EQ(de_number, test_number); success = phone_util_.GetExampleNumberForType(RegionCode::DE(), PhoneNumberUtil::MOBILE, &test_number); // Here we test that an example number was not returned, and that the number // passed in was not modified. test_number.Clear(); EXPECT_FALSE(success); EXPECT_EQ(PhoneNumber::default_instance(), test_number); // For the US, the example number is placed under general description, and // hence should be used for both fixed line and mobile, so neither of these // should return null. success = phone_util_.GetExampleNumberForType(RegionCode::US(), PhoneNumberUtil::FIXED_LINE, &test_number); // Here we test that the call to get an example number succeeded, and that the // number passed in was modified. EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); success = phone_util_.GetExampleNumberForType(RegionCode::US(), PhoneNumberUtil::MOBILE, &test_number); EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); // CS is an invalid region, so we have no data for it. We should return false. test_number.Clear(); EXPECT_FALSE(phone_util_.GetExampleNumberForType(RegionCode::CS(), PhoneNumberUtil::MOBILE, &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); // RegionCode 001 is reserved for supporting non-geographical country calling // code. We don't support getting an example number for it with this method. EXPECT_FALSE(phone_util_.GetExampleNumber(RegionCode::UN001(), &test_number)); } TEST_F(PhoneNumberUtilTest, GetExampleNumberForNonGeoEntity) { PhoneNumber toll_free_number; toll_free_number.set_country_code(800); toll_free_number.set_national_number(12345678ULL); PhoneNumber test_number; bool success = phone_util_.GetExampleNumberForNonGeoEntity(800 , &test_number); EXPECT_TRUE(success); EXPECT_EQ(toll_free_number, test_number); PhoneNumber universal_premium_rate; universal_premium_rate.set_country_code(979); universal_premium_rate.set_national_number(123456789ULL); success = phone_util_.GetExampleNumberForNonGeoEntity(979 , &test_number); EXPECT_TRUE(success); EXPECT_EQ(universal_premium_rate, test_number); } TEST_F(PhoneNumberUtilTest, FormatUSNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(6502530000ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""650 253 0000"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+1 650 253 0000"", formatted_number); test_number.set_national_number(8002530000ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""800 253 0000"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+1 800 253 0000"", formatted_number); test_number.set_national_number(9002530000ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""900 253 0000"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+1 900 253 0000"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::RFC3966, &formatted_number); EXPECT_EQ(""tel:+1-900-253-0000"", formatted_number); test_number.set_national_number(0ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""0"", formatted_number); // Numbers with all zeros in the national number part will be formatted by // using the raw_input if that is available no matter which format is // specified. test_number.set_raw_input(""000-000-0000""); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""000-000-0000"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatBSNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(2421234567ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""242 123 4567"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+1 242 123 4567"", formatted_number); test_number.set_national_number(8002530000ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""800 253 0000"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+1 800 253 0000"", formatted_number); test_number.set_national_number(9002530000ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""900 253 0000"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+1 900 253 0000"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatGBNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(44); test_number.set_national_number(2087389353ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""(020) 8738 9353"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+44 20 8738 9353"", formatted_number); test_number.set_national_number(7912345678ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""(07912) 345 678"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+44 7912 345 678"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatDENumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(49); test_number.set_national_number(301234ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""030/1234"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+49 30/1234"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::RFC3966, &formatted_number); EXPECT_EQ(""tel:+49-30-1234"", formatted_number); test_number.set_national_number(291123ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""0291 123"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+49 291 123"", formatted_number); test_number.set_national_number(29112345678ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""0291 12345678"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+49 291 12345678"", formatted_number); test_number.set_national_number(9123123ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""09123 123"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+49 9123 123"", formatted_number); test_number.set_national_number(80212345ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""08021 2345"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+49 8021 2345"", formatted_number); test_number.set_national_number(1234ULL); // Note this number is correctly formatted without national prefix. Most of // the numbers that are treated as invalid numbers by the library are short // numbers, and they are usually not dialed with national prefix. phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""1234"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+49 1234"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatITNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(39); test_number.set_national_number(236618300ULL); test_number.set_italian_leading_zero(true); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""02 3661 8300"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+39 02 3661 8300"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+390236618300"", formatted_number); test_number.set_national_number(345678901ULL); test_number.set_italian_leading_zero(false); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""345 678 901"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+39 345 678 901"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+39345678901"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatAUNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(61); test_number.set_national_number(236618300ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""02 3661 8300"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+61 2 3661 8300"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+61236618300"", formatted_number); test_number.set_national_number(1800123456ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""1800 123 456"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+61 1800 123 456"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+611800123456"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatARNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(54); test_number.set_national_number(1187654321ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""011 8765-4321"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+54 11 8765-4321"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+541187654321"", formatted_number); test_number.set_national_number(91187654321ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""011 15 8765-4321"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+54 9 11 8765 4321"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+5491187654321"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatMXNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(52); test_number.set_national_number(12345678900ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""045 234 567 8900"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+52 1 234 567 8900"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+5212345678900"", formatted_number); test_number.set_national_number(15512345678ULL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""045 55 1234 5678"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+52 1 55 1234 5678"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+5215512345678"", formatted_number); test_number.set_national_number(3312345678LL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""01 33 1234 5678"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+52 33 1234 5678"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+523312345678"", formatted_number); test_number.set_national_number(8211234567LL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""01 821 123 4567"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+52 821 123 4567"", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+528211234567"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatOutOfCountryCallingNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(9002530000ULL); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::DE(), &formatted_number); EXPECT_EQ(""00 1 900 253 0000"", formatted_number); test_number.set_national_number(6502530000ULL); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::BS(), &formatted_number); EXPECT_EQ(""1 650 253 0000"", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::PL(), &formatted_number); EXPECT_EQ(""00 1 650 253 0000"", formatted_number); test_number.set_country_code(44); test_number.set_national_number(7912345678ULL); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""011 44 7912 345 678"", formatted_number); test_number.set_country_code(49); test_number.set_national_number(1234ULL); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::GB(), &formatted_number); EXPECT_EQ(""00 49 1234"", formatted_number); // Note this number is correctly formatted without national prefix. Most of // the numbers that are treated as invalid numbers by the library are short // numbers, and they are usually not dialed with national prefix. phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::DE(), &formatted_number); EXPECT_EQ(""1234"", formatted_number); test_number.set_country_code(39); test_number.set_national_number(236618300ULL); test_number.set_italian_leading_zero(true); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""011 39 02 3661 8300"", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::IT(), &formatted_number); EXPECT_EQ(""02 3661 8300"", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::SG(), &formatted_number); EXPECT_EQ(""+39 02 3661 8300"", formatted_number); test_number.set_country_code(65); test_number.set_national_number(94777892ULL); test_number.set_italian_leading_zero(false); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::SG(), &formatted_number); EXPECT_EQ(""9477 7892"", formatted_number); test_number.set_country_code(800); test_number.set_national_number(12345678ULL); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""011 800 1234 5678"", formatted_number); test_number.set_country_code(54); test_number.set_national_number(91187654321ULL); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""011 54 9 11 8765 4321"", formatted_number); test_number.set_extension(""1234""); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""011 54 9 11 8765 4321 ext. 1234"", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AU(), &formatted_number); EXPECT_EQ(""0011 54 9 11 8765 4321 ext. 1234"", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AR(), &formatted_number); EXPECT_EQ(""011 15 8765-4321 ext. 1234"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatOutOfCountryWithInvalidRegion) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(6502530000ULL); // AQ/Antarctica isn't a valid region code for phone number formatting, // so this falls back to intl formatting. phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AQ(), &formatted_number); EXPECT_EQ(""+1 650 253 0000"", formatted_number); // For region code 001, the out-of-country format always turns into the // international format. phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::UN001(), &formatted_number); EXPECT_EQ(""+1 650 253 0000"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatOutOfCountryWithPreferredIntlPrefix) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(39); test_number.set_national_number(236618300ULL); test_number.set_italian_leading_zero(true); // This should use 0011, since that is the preferred international prefix // (both 0011 and 0012 are accepted as possible international prefixes in our // test metadta.) phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AU(), &formatted_number); EXPECT_EQ(""0011 39 02 3661 8300"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatOutOfCountryKeepingAlphaChars) { PhoneNumber alpha_numeric_number; string formatted_number; alpha_numeric_number.set_country_code(1); alpha_numeric_number.set_national_number(8007493524ULL); alpha_numeric_number.set_raw_input(""1800 six-flag""); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ(""0011 1 800 SIX-FLAG"", formatted_number); formatted_number.clear(); alpha_numeric_number.set_raw_input(""1-800-SIX-flag""); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ(""0011 1 800-SIX-FLAG"", formatted_number); formatted_number.clear(); alpha_numeric_number.set_raw_input(""Call us from UK: 00 1 800 SIX-flag""); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ(""0011 1 800 SIX-FLAG"", formatted_number); formatted_number.clear(); alpha_numeric_number.set_raw_input(""800 SIX-flag""); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ(""0011 1 800 SIX-FLAG"", formatted_number); // Formatting from within the NANPA region. formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""1 800 SIX-FLAG"", formatted_number); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::BS(), &formatted_number); EXPECT_EQ(""1 800 SIX-FLAG"", formatted_number); // Testing that if the raw input doesn't exist, it is formatted using // FormatOutOfCountryCallingNumber. alpha_numeric_number.clear_raw_input(); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::DE(), &formatted_number); EXPECT_EQ(""00 1 800 749 3524"", formatted_number); // Testing AU alpha number formatted from Australia. alpha_numeric_number.set_country_code(61); alpha_numeric_number.set_national_number(827493524ULL); alpha_numeric_number.set_raw_input(""+61 82749-FLAG""); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); // This number should have the national prefix prefixed. EXPECT_EQ(""082749-FLAG"", formatted_number); alpha_numeric_number.set_raw_input(""082749-FLAG""); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ(""082749-FLAG"", formatted_number); alpha_numeric_number.set_national_number(18007493524ULL); alpha_numeric_number.set_raw_input(""1-800-SIX-flag""); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); // This number should not have the national prefix prefixed, in accordance // with the override for this specific formatting rule. EXPECT_EQ(""1-800-SIX-FLAG"", formatted_number); // The metadata should not be permanently changed, since we copied it before // modifying patterns. Here we check this. formatted_number.clear(); alpha_numeric_number.set_national_number(1800749352ULL); phone_util_.FormatOutOfCountryCallingNumber(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ(""1800 749 352"", formatted_number); // Testing a country with multiple international prefixes. formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::SG(), &formatted_number); EXPECT_EQ(""+61 1-800-SIX-FLAG"", formatted_number); // Testing the case of calling from a non-supported region. phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AQ(), &formatted_number); EXPECT_EQ(""+61 1-800-SIX-FLAG"", formatted_number); // Testing the case with an invalid country code. formatted_number.clear(); alpha_numeric_number.set_country_code(0); alpha_numeric_number.set_national_number(18007493524ULL); alpha_numeric_number.set_raw_input(""1-800-SIX-flag""); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::DE(), &formatted_number); // Uses the raw input only. EXPECT_EQ(""1-800-SIX-flag"", formatted_number); // Testing the case of an invalid alpha number. formatted_number.clear(); alpha_numeric_number.set_country_code(1); alpha_numeric_number.set_national_number(80749ULL); alpha_numeric_number.set_raw_input(""180-SIX""); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::DE(), &formatted_number); // No country-code stripping can be done. EXPECT_EQ(""00 1 180-SIX"", formatted_number); // Testing the case of calling from a non-supported region. phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AQ(), &formatted_number); // No country-code stripping can be done since the number is invalid. EXPECT_EQ(""+1 180-SIX"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatWithCarrierCode) { // We only support this for AR in our test metadata. PhoneNumber ar_number; string formatted_number; ar_number.set_country_code(54); ar_number.set_national_number(91234125678ULL); phone_util_.Format(ar_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""01234 12-5678"", formatted_number); // Test formatting with a carrier code. phone_util_.FormatNationalNumberWithCarrierCode(ar_number, ""15"", &formatted_number); EXPECT_EQ(""01234 15 12-5678"", formatted_number); phone_util_.FormatNationalNumberWithCarrierCode(ar_number, """", &formatted_number); EXPECT_EQ(""01234 12-5678"", formatted_number); // Here the international rule is used, so no carrier code should be present. phone_util_.Format(ar_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+5491234125678"", formatted_number); // We don't support this for the US so there should be no change. PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(4241231234ULL); phone_util_.Format(us_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""424 123 1234"", formatted_number); phone_util_.FormatNationalNumberWithCarrierCode(us_number, ""15"", &formatted_number); EXPECT_EQ(""424 123 1234"", formatted_number); // Invalid country code should just get the NSN. PhoneNumber invalid_number; invalid_number.set_country_code(kInvalidCountryCode); invalid_number.set_national_number(12345ULL); phone_util_.FormatNationalNumberWithCarrierCode(invalid_number, ""89"", &formatted_number); EXPECT_EQ(""12345"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatWithPreferredCarrierCode) { // We only support this for AR in our test metadata. PhoneNumber ar_number; string formatted_number; ar_number.set_country_code(54); ar_number.set_national_number(91234125678ULL); // Test formatting with no preferred carrier code stored in the number itself. phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, ""15"", &formatted_number); EXPECT_EQ(""01234 15 12-5678"", formatted_number); phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, """", &formatted_number); EXPECT_EQ(""01234 12-5678"", formatted_number); // Test formatting with preferred carrier code present. ar_number.set_preferred_domestic_carrier_code(""19""); phone_util_.Format(ar_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""01234 12-5678"", formatted_number); phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, ""15"", &formatted_number); EXPECT_EQ(""01234 19 12-5678"", formatted_number); phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, """", &formatted_number); EXPECT_EQ(""01234 19 12-5678"", formatted_number); // When the preferred_domestic_carrier_code is present (even when it contains // an empty string), use it instead of the default carrier code passed in. ar_number.set_preferred_domestic_carrier_code(""""); phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, ""15"", &formatted_number); EXPECT_EQ(""01234 12-5678"", formatted_number); // We don't support this for the US so there should be no change. PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(4241231234ULL); us_number.set_preferred_domestic_carrier_code(""99""); phone_util_.Format(us_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""424 123 1234"", formatted_number); phone_util_.FormatNationalNumberWithPreferredCarrierCode(us_number, ""15"", &formatted_number); EXPECT_EQ(""424 123 1234"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatNumberForMobileDialing) { PhoneNumber test_number; string formatted_number; // Numbers are normally dialed in national format in-country, and // international format from outside the country. test_number.set_country_code(49); test_number.set_national_number(30123456ULL); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::DE(), false, /* remove formatting */ &formatted_number); EXPECT_EQ(""030123456"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CH(), false, /* remove formatting */ &formatted_number); EXPECT_EQ(""+4930123456"", formatted_number); test_number.set_extension(""1234""); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::DE(), false, /* remove formatting */ &formatted_number); EXPECT_EQ(""030123456"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CH(), false, /* remove formatting */ &formatted_number); EXPECT_EQ(""+4930123456"", formatted_number); test_number.set_country_code(1); test_number.clear_extension(); // US toll free numbers are marked as noInternationalDialling in the test // metadata for testing purposes. For such numbers, we expect nothing to be // returned when the region code is not the same one. test_number.set_national_number(8002530000ULL); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), true, /* keep formatting */ &formatted_number); EXPECT_EQ(""800 253 0000"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CN(), true, &formatted_number); EXPECT_EQ("""", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, /* remove formatting */ &formatted_number); EXPECT_EQ(""8002530000"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CN(), false, &formatted_number); EXPECT_EQ("""", formatted_number); test_number.set_national_number(6502530000ULL); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), true, &formatted_number); EXPECT_EQ(""+1 650 253 0000"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ(""+16502530000"", formatted_number); test_number.set_extension(""1234""); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), true, &formatted_number); EXPECT_EQ(""+1 650 253 0000"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ(""+16502530000"", formatted_number); // An invalid US number, which is one digit too long. test_number.set_national_number(65025300001ULL); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), true, &formatted_number); EXPECT_EQ(""+1 65025300001"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ(""+165025300001"", formatted_number); // Star numbers. In real life they appear in Israel, but we have them in JP // in our test metadata. test_number.set_country_code(81); test_number.set_national_number(2345ULL); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), true, &formatted_number); EXPECT_EQ(""*2345"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), false, &formatted_number); EXPECT_EQ(""*2345"", formatted_number); test_number.set_country_code(800); test_number.set_national_number(12345678ULL); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), false, &formatted_number); EXPECT_EQ(""+80012345678"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), true, &formatted_number); EXPECT_EQ(""+800 1234 5678"", formatted_number); // UAE numbers beginning with 600 (classified as UAN) need to be dialled // without +971 locally. test_number.set_country_code(971); test_number.set_national_number(600123456ULL); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), false, &formatted_number); EXPECT_EQ(""+971600123456"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::AE(), true, &formatted_number); EXPECT_EQ(""600123456"", formatted_number); test_number.set_country_code(52); test_number.set_national_number(3312345678ULL); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::MX(), false, &formatted_number); EXPECT_EQ(""+523312345678"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ(""+523312345678"", formatted_number); // Non-geographical numbers should always be dialed in international format. test_number.set_country_code(800); test_number.set_national_number(12345678ULL); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ(""+80012345678"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::UN001(), false, &formatted_number); EXPECT_EQ(""+80012345678"", formatted_number); // Test that a short number is formatted correctly for mobile dialing within // the region, and is not diallable from outside the region. test_number.set_country_code(49); test_number.set_national_number(123L); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::DE(), false, &formatted_number); EXPECT_EQ(""123"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::IT(), false, &formatted_number); EXPECT_EQ("""", formatted_number); // Test the special logic for Hungary, where the national prefix must be // added before dialing from a mobile phone for regular length numbers, but // not for short numbers. test_number.set_country_code(36); test_number.set_national_number(301234567L); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::HU(), false, &formatted_number); EXPECT_EQ(""06301234567"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), false, &formatted_number); EXPECT_EQ(""+36301234567"", formatted_number); test_number.set_national_number(104L); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::HU(), false, &formatted_number); EXPECT_EQ(""104"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), false, &formatted_number); EXPECT_EQ("""", formatted_number); // Test the special logic for NANPA countries, for which regular length phone // numbers are always output in international format, but short numbers are // in national format. test_number.set_country_code(1); test_number.set_national_number(6502530000L); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ(""+16502530000"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CA(), false, &formatted_number); EXPECT_EQ(""+16502530000"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::BR(), false, &formatted_number); EXPECT_EQ(""+16502530000"", formatted_number); test_number.set_national_number(911L); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ(""911"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CA(), false, &formatted_number); EXPECT_EQ("""", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::BR(), false, &formatted_number); EXPECT_EQ("""", formatted_number); // Test that the Australian emergency number 000 is formatted correctly. test_number.set_country_code(61); test_number.set_national_number(0L); test_number.set_italian_leading_zero(true); test_number.set_number_of_leading_zeros(2); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::AU(), false, &formatted_number); EXPECT_EQ(""000"", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::NZ(), false, &formatted_number); EXPECT_EQ("""", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatByPattern) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(6502530000ULL); RepeatedPtrField number_formats; NumberFormat* number_format = number_formats.Add(); number_format->set_pattern(""(\\d{3})(\\d{3})(\\d{4})""); number_format->set_format(""($1) $2-$3""); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ(""(650) 253-0000"", formatted_number); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL, number_formats, &formatted_number); EXPECT_EQ(""+1 (650) 253-0000"", formatted_number); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::RFC3966, number_formats, &formatted_number); EXPECT_EQ(""tel:+1-650-253-0000"", formatted_number); // $NP is set to '1' for the US. Here we check that for other NANPA countries // the US rules are followed. number_format->set_national_prefix_formatting_rule(""$NP ($FG)""); number_format->set_format(""$1 $2-$3""); test_number.set_country_code(1); test_number.set_national_number(4168819999ULL); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ(""1 (416) 881-9999"", formatted_number); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL, number_formats, &formatted_number); EXPECT_EQ(""+1 416 881-9999"", formatted_number); test_number.set_country_code(39); test_number.set_national_number(236618300ULL); test_number.set_italian_leading_zero(true); number_format->set_pattern(""(\\d{2})(\\d{5})(\\d{3})""); number_format->set_format(""$1-$2 $3""); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ(""02-36618 300"", formatted_number); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL, number_formats, &formatted_number); EXPECT_EQ(""+39 02-36618 300"", formatted_number); test_number.set_country_code(44); test_number.set_national_number(2012345678ULL); test_number.set_italian_leading_zero(false); number_format->set_national_prefix_formatting_rule(""$NP$FG""); number_format->set_pattern(""(\\d{2})(\\d{4})(\\d{4})""); number_format->set_format(""$1 $2 $3""); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ(""020 1234 5678"", formatted_number); number_format->set_national_prefix_formatting_rule(""($NP$FG)""); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ(""(020) 1234 5678"", formatted_number); number_format->set_national_prefix_formatting_rule(""""); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ(""20 1234 5678"", formatted_number); number_format->set_national_prefix_formatting_rule(""""); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL, number_formats, &formatted_number); EXPECT_EQ(""+44 20 1234 5678"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatE164Number) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(6502530000ULL); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+16502530000"", formatted_number); test_number.set_country_code(49); test_number.set_national_number(301234ULL); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+49301234"", formatted_number); test_number.set_country_code(800); test_number.set_national_number(12345678ULL); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+80012345678"", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatNumberWithExtension) { PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(33316005ULL); nz_number.set_extension(""1234""); string formatted_number; // Uses default extension prefix: phone_util_.Format(nz_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""03-331 6005 ext. 1234"", formatted_number); // Uses RFC 3966 syntax. phone_util_.Format(nz_number, PhoneNumberUtil::RFC3966, &formatted_number); EXPECT_EQ(""tel:+64-3-331-6005;ext=1234"", formatted_number); // Extension prefix overridden in the territory information for the US: PhoneNumber us_number_with_extension; us_number_with_extension.set_country_code(1); us_number_with_extension.set_national_number(6502530000ULL); us_number_with_extension.set_extension(""4567""); phone_util_.Format(us_number_with_extension, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""650 253 0000 extn. 4567"", formatted_number); } TEST_F(PhoneNumberUtilTest, GetLengthOfGeographicalAreaCode) { PhoneNumber number; // Google MTV, which has area code ""650"". number.set_country_code(1); number.set_national_number(6502530000ULL); EXPECT_EQ(3, phone_util_.GetLengthOfGeographicalAreaCode(number)); // A North America toll-free number, which has no area code. number.set_country_code(1); number.set_national_number(8002530000ULL); EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number)); // An invalid US number (1 digit shorter), which has no area code. number.set_country_code(1); number.set_national_number(650253000ULL); EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number)); // Google London, which has area code ""20"". number.set_country_code(44); number.set_national_number(2070313000ULL); EXPECT_EQ(2, phone_util_.GetLengthOfGeographicalAreaCode(number)); // A UK mobile phone, which has no area code. number.set_country_code(44); number.set_national_number(7123456789ULL); EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number)); // Google Buenos Aires, which has area code ""11"". number.set_country_code(54); number.set_national_number(1155303000ULL); EXPECT_EQ(2, phone_util_.GetLengthOfGeographicalAreaCode(number)); // Google Sydney, which has area code ""2"". number.set_country_code(61); number.set_national_number(293744000ULL); EXPECT_EQ(1, phone_util_.GetLengthOfGeographicalAreaCode(number)); // Italian numbers - there is no national prefix, but it still has an area // code. number.set_country_code(39); number.set_national_number(236618300ULL); number.set_italian_leading_zero(true); EXPECT_EQ(2, phone_util_.GetLengthOfGeographicalAreaCode(number)); // Google Singapore. Singapore has no area code and no national prefix. number.set_country_code(65); number.set_national_number(65218000ULL); number.set_italian_leading_zero(false); EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number)); // An international toll free number, which has no area code. number.set_country_code(800); number.set_national_number(12345678ULL); EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number)); } TEST_F(PhoneNumberUtilTest, GetLengthOfNationalDestinationCode) { PhoneNumber number; // Google MTV, which has national destination code (NDC) ""650"". number.set_country_code(1); number.set_national_number(6502530000ULL); EXPECT_EQ(3, phone_util_.GetLengthOfNationalDestinationCode(number)); // A North America toll-free number, which has NDC ""800"". number.set_country_code(1); number.set_national_number(8002530000ULL); EXPECT_EQ(3, phone_util_.GetLengthOfNationalDestinationCode(number)); // Google London, which has NDC ""20"". number.set_country_code(44); number.set_national_number(2070313000ULL); EXPECT_EQ(2, phone_util_.GetLengthOfNationalDestinationCode(number)); // A UK mobile phone, which has NDC ""7123"" number.set_country_code(44); number.set_national_number(7123456789ULL); EXPECT_EQ(4, phone_util_.GetLengthOfNationalDestinationCode(number)); // Google Buenos Aires, which has NDC ""11"". number.set_country_code(54); number.set_national_number(1155303000ULL); EXPECT_EQ(2, phone_util_.GetLengthOfNationalDestinationCode(number)); // An Argentinian mobile which has NDC ""911"". number.set_country_code(54); number.set_national_number(91187654321ULL); EXPECT_EQ(3, phone_util_.GetLengthOfNationalDestinationCode(number)); // Google Sydney, which has NDC ""2"". number.set_country_code(61); number.set_national_number(293744000ULL); EXPECT_EQ(1, phone_util_.GetLengthOfNationalDestinationCode(number)); // Google Singapore. Singapore has NDC ""6521"". number.set_country_code(65); number.set_national_number(65218000ULL); EXPECT_EQ(4, phone_util_.GetLengthOfNationalDestinationCode(number)); // An invalid US number (1 digit shorter), which has no NDC. number.set_country_code(1); number.set_national_number(650253000ULL); EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number)); // A number containing an invalid country code, which shouldn't have any NDC. number.set_country_code(123); number.set_national_number(650253000ULL); EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number)); // A number that has only one group of digits after country code when // formatted in the international format. number.set_country_code(376); number.set_national_number(12345ULL); EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number)); // The same number above, but with an extension. number.set_country_code(376); number.set_national_number(12345ULL); number.set_extension(""321""); EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number)); // An international toll free number, which has NDC ""1234"". number.Clear(); number.set_country_code(800); number.set_national_number(12345678ULL); EXPECT_EQ(4, phone_util_.GetLengthOfNationalDestinationCode(number)); } TEST_F(PhoneNumberUtilTest, GetCountryMobileToken) { int country_calling_code; string mobile_token; country_calling_code = phone_util_.GetCountryCodeForRegion(RegionCode::MX()); phone_util_.GetCountryMobileToken(country_calling_code, &mobile_token); EXPECT_EQ(""1"", mobile_token); // Country calling code for Sweden, which has no mobile token. country_calling_code = phone_util_.GetCountryCodeForRegion(RegionCode::SE()); phone_util_.GetCountryMobileToken(country_calling_code, &mobile_token); EXPECT_EQ("""", mobile_token); } TEST_F(PhoneNumberUtilTest, ExtractPossibleNumber) { // Removes preceding funky punctuation and letters but leaves the rest // untouched. string extracted_number; ExtractPossibleNumber(""Tel:0800-345-600"", &extracted_number); EXPECT_EQ(""0800-345-600"", extracted_number); ExtractPossibleNumber(""Tel:0800 FOR PIZZA"", &extracted_number); EXPECT_EQ(""0800 FOR PIZZA"", extracted_number); // Should not remove plus sign. ExtractPossibleNumber(""Tel:+800-345-600"", &extracted_number); EXPECT_EQ(""+800-345-600"", extracted_number); // Should recognise wide digits as possible start values. ExtractPossibleNumber(""\xEF\xBC\x90\xEF\xBC\x92\xEF\xBC\x93"" /* ""023"" */, &extracted_number); EXPECT_EQ(""\xEF\xBC\x90\xEF\xBC\x92\xEF\xBC\x93"" /* ""023"" */, extracted_number); // Dashes are not possible start values and should be removed. ExtractPossibleNumber(""Num-\xEF\xBC\x91\xEF\xBC\x92\xEF\xBC\x93"" /* ""Num-123"" */, &extracted_number); EXPECT_EQ(""\xEF\xBC\x91\xEF\xBC\x92\xEF\xBC\x93"" /* ""123"" */, extracted_number); // If not possible number present, return empty string. ExtractPossibleNumber(""Num-...."", &extracted_number); EXPECT_EQ("""", extracted_number); // Leading brackets are stripped - these are not used when parsing. ExtractPossibleNumber(""(650) 253-0000"", &extracted_number); EXPECT_EQ(""650) 253-0000"", extracted_number); // Trailing non-alpha-numeric characters should be removed. ExtractPossibleNumber(""(650) 253-0000..- .."", &extracted_number); EXPECT_EQ(""650) 253-0000"", extracted_number); ExtractPossibleNumber(""(650) 253-0000."", &extracted_number); EXPECT_EQ(""650) 253-0000"", extracted_number); // This case has a trailing RTL char. ExtractPossibleNumber(""(650) 253-0000\xE2\x80\x8F"" /* ""(650) 253-0000‏"" */, &extracted_number); EXPECT_EQ(""650) 253-0000"", extracted_number); } TEST_F(PhoneNumberUtilTest, IsNANPACountry) { EXPECT_TRUE(phone_util_.IsNANPACountry(RegionCode::US())); EXPECT_TRUE(phone_util_.IsNANPACountry(RegionCode::BS())); EXPECT_FALSE(phone_util_.IsNANPACountry(RegionCode::DE())); EXPECT_FALSE(phone_util_.IsNANPACountry(RegionCode::GetUnknown())); EXPECT_FALSE(phone_util_.IsNANPACountry(RegionCode::UN001())); } TEST_F(PhoneNumberUtilTest, IsValidNumber) { PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(6502530000ULL); EXPECT_TRUE(phone_util_.IsValidNumber(us_number)); PhoneNumber it_number; it_number.set_country_code(39); it_number.set_national_number(236618300ULL); it_number.set_italian_leading_zero(true); EXPECT_TRUE(phone_util_.IsValidNumber(it_number)); PhoneNumber gb_number; gb_number.set_country_code(44); gb_number.set_national_number(7912345678ULL); EXPECT_TRUE(phone_util_.IsValidNumber(gb_number)); PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(21387835ULL); EXPECT_TRUE(phone_util_.IsValidNumber(nz_number)); PhoneNumber intl_toll_free_number; intl_toll_free_number.set_country_code(800); intl_toll_free_number.set_national_number(12345678ULL); EXPECT_TRUE(phone_util_.IsValidNumber(intl_toll_free_number)); PhoneNumber universal_premium_rate; universal_premium_rate.set_country_code(979); universal_premium_rate.set_national_number(123456789ULL); EXPECT_TRUE(phone_util_.IsValidNumber(universal_premium_rate)); } TEST_F(PhoneNumberUtilTest, IsValidForRegion) { // This number is valid for the Bahamas, but is not a valid US number. PhoneNumber bs_number; bs_number.set_country_code(1); bs_number.set_national_number(2423232345ULL); EXPECT_TRUE(phone_util_.IsValidNumber(bs_number)); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(bs_number, RegionCode::BS())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(bs_number, RegionCode::US())); bs_number.set_national_number(2421232345ULL); // This number is no longer valid. EXPECT_FALSE(phone_util_.IsValidNumber(bs_number)); // La Mayotte and Réunion use 'leadingDigits' to differentiate them. PhoneNumber re_number; re_number.set_country_code(262); re_number.set_national_number(262123456ULL); EXPECT_TRUE(phone_util_.IsValidNumber(re_number)); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT())); // Now change the number to be a number for La Mayotte. re_number.set_national_number(269601234ULL); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE())); // This number is no longer valid. re_number.set_national_number(269123456ULL); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE())); EXPECT_FALSE(phone_util_.IsValidNumber(re_number)); // However, it should be recognised as from La Mayotte. string region_code; phone_util_.GetRegionCodeForNumber(re_number, ®ion_code); EXPECT_EQ(RegionCode::YT(), region_code); // This number is valid in both places. re_number.set_national_number(800123456ULL); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT())); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE())); PhoneNumber intl_toll_free_number; intl_toll_free_number.set_country_code(800); intl_toll_free_number.set_national_number(12345678ULL); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(intl_toll_free_number, RegionCode::UN001())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(intl_toll_free_number, RegionCode::US())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(intl_toll_free_number, RegionCode::ZZ())); PhoneNumber invalid_number; // Invalid country calling codes. invalid_number.set_country_code(3923); invalid_number.set_national_number(2366ULL); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number, RegionCode::ZZ())); invalid_number.set_country_code(3923); invalid_number.set_national_number(2366ULL); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number, RegionCode::UN001())); invalid_number.set_country_code(0); invalid_number.set_national_number(2366ULL); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number, RegionCode::UN001())); invalid_number.set_country_code(0); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number, RegionCode::ZZ())); } TEST_F(PhoneNumberUtilTest, IsNotValidNumber) { PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(2530000ULL); EXPECT_FALSE(phone_util_.IsValidNumber(us_number)); PhoneNumber it_number; it_number.set_country_code(39); it_number.set_national_number(23661830000ULL); it_number.set_italian_leading_zero(true); EXPECT_FALSE(phone_util_.IsValidNumber(it_number)); PhoneNumber gb_number; gb_number.set_country_code(44); gb_number.set_national_number(791234567ULL); EXPECT_FALSE(phone_util_.IsValidNumber(gb_number)); PhoneNumber de_number; de_number.set_country_code(49); de_number.set_national_number(1234ULL); EXPECT_FALSE(phone_util_.IsValidNumber(de_number)); PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(3316005ULL); EXPECT_FALSE(phone_util_.IsValidNumber(nz_number)); PhoneNumber invalid_number; // Invalid country calling codes. invalid_number.set_country_code(3923); invalid_number.set_national_number(2366ULL); EXPECT_FALSE(phone_util_.IsValidNumber(invalid_number)); invalid_number.set_country_code(0); EXPECT_FALSE(phone_util_.IsValidNumber(invalid_number)); PhoneNumber intl_toll_free_number_too_long; intl_toll_free_number_too_long.set_country_code(800); intl_toll_free_number_too_long.set_national_number(123456789ULL); EXPECT_FALSE(phone_util_.IsValidNumber(intl_toll_free_number_too_long)); } TEST_F(PhoneNumberUtilTest, GetRegionCodeForCountryCode) { string region_code; phone_util_.GetRegionCodeForCountryCode(1, ®ion_code); EXPECT_EQ(RegionCode::US(), region_code); phone_util_.GetRegionCodeForCountryCode(44, ®ion_code); EXPECT_EQ(RegionCode::GB(), region_code); phone_util_.GetRegionCodeForCountryCode(49, ®ion_code); EXPECT_EQ(RegionCode::DE(), region_code); phone_util_.GetRegionCodeForCountryCode(800, ®ion_code); EXPECT_EQ(RegionCode::UN001(), region_code); phone_util_.GetRegionCodeForCountryCode(979, ®ion_code); EXPECT_EQ(RegionCode::UN001(), region_code); } TEST_F(PhoneNumberUtilTest, GetRegionCodeForNumber) { string region_code; PhoneNumber bs_number; bs_number.set_country_code(1); bs_number.set_national_number(2423232345ULL); phone_util_.GetRegionCodeForNumber(bs_number, ®ion_code); EXPECT_EQ(RegionCode::BS(), region_code); PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(4241231234ULL); phone_util_.GetRegionCodeForNumber(us_number, ®ion_code); EXPECT_EQ(RegionCode::US(), region_code); PhoneNumber gb_mobile; gb_mobile.set_country_code(44); gb_mobile.set_national_number(7912345678ULL); phone_util_.GetRegionCodeForNumber(gb_mobile, ®ion_code); EXPECT_EQ(RegionCode::GB(), region_code); PhoneNumber intl_toll_free_number; intl_toll_free_number.set_country_code(800); intl_toll_free_number.set_national_number(12345678ULL); phone_util_.GetRegionCodeForNumber(intl_toll_free_number, ®ion_code); EXPECT_EQ(RegionCode::UN001(), region_code); PhoneNumber universal_premium_rate; universal_premium_rate.set_country_code(979); universal_premium_rate.set_national_number(123456789ULL); phone_util_.GetRegionCodeForNumber(universal_premium_rate, ®ion_code); EXPECT_EQ(RegionCode::UN001(), region_code); } TEST_F(PhoneNumberUtilTest, IsPossibleNumber) { PhoneNumber number; number.set_country_code(1); number.set_national_number(6502530000ULL); EXPECT_TRUE(phone_util_.IsPossibleNumber(number)); number.set_country_code(1); number.set_national_number(2530000ULL); EXPECT_TRUE(phone_util_.IsPossibleNumber(number)); number.set_country_code(44); number.set_national_number(2070313000ULL); EXPECT_TRUE(phone_util_.IsPossibleNumber(number)); number.set_country_code(800); number.set_national_number(12345678ULL); EXPECT_TRUE(phone_util_.IsPossibleNumber(number)); EXPECT_TRUE(phone_util_.IsPossibleNumberForString(""+1 650 253 0000"", RegionCode::US())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString(""+1 650 GOO OGLE"", RegionCode::US())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString(""(650) 253-0000"", RegionCode::US())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString(""253-0000"", RegionCode::US())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString(""+1 650 253 0000"", RegionCode::GB())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString(""+44 20 7031 3000"", RegionCode::GB())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString(""(020) 7031 3000"", RegionCode::GB())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString(""7031 3000"", RegionCode::GB())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString(""3331 6005"", RegionCode::NZ())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString(""+800 1234 5678"", RegionCode::UN001())); } TEST_F(PhoneNumberUtilTest, IsPossibleNumberWithReason) { // FYI, national numbers for country code +1 that are within 7 to 10 digits // are possible. PhoneNumber number; number.set_country_code(1); number.set_national_number(6502530000ULL); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(1); number.set_national_number(2530000ULL); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(0); number.set_national_number(2530000ULL); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(1); number.set_national_number(253000ULL); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(1); number.set_national_number(65025300000ULL); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(44); number.set_national_number(2070310000ULL); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(49); number.set_national_number(30123456ULL); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(65); number.set_national_number(1234567890ULL); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(800); number.set_national_number(123456789ULL); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberWithReason(number)); } TEST_F(PhoneNumberUtilTest, IsNotPossibleNumber) { PhoneNumber number; number.set_country_code(1); number.set_national_number(65025300000ULL); EXPECT_FALSE(phone_util_.IsPossibleNumber(number)); number.set_country_code(800); number.set_national_number(123456789ULL); EXPECT_FALSE(phone_util_.IsPossibleNumber(number)); number.set_country_code(1); number.set_national_number(253000ULL); EXPECT_FALSE(phone_util_.IsPossibleNumber(number)); number.set_country_code(44); number.set_national_number(300ULL); EXPECT_FALSE(phone_util_.IsPossibleNumber(number)); EXPECT_FALSE(phone_util_.IsPossibleNumberForString(""+1 650 253 00000"", RegionCode::US())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString(""(650) 253-00000"", RegionCode::US())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString(""I want a Pizza"", RegionCode::US())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString(""253-000"", RegionCode::US())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString(""1 3000"", RegionCode::GB())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString(""+44 300"", RegionCode::GB())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString(""+800 1234 5678 9"", RegionCode::UN001())); } TEST_F(PhoneNumberUtilTest, TruncateTooLongNumber) { // US number 650-253-0000, but entered with one additional digit at the end. PhoneNumber too_long_number; too_long_number.set_country_code(1); too_long_number.set_national_number(65025300001ULL); PhoneNumber valid_number; valid_number.set_country_code(1); valid_number.set_national_number(6502530000ULL); EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number)); EXPECT_EQ(valid_number, too_long_number); too_long_number.set_country_code(800); too_long_number.set_national_number(123456789ULL); valid_number.set_country_code(800); valid_number.set_national_number(12345678ULL); EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number)); EXPECT_EQ(valid_number, too_long_number); // GB number 080 1234 5678, but entered with 4 extra digits at the end. too_long_number.set_country_code(44); too_long_number.set_national_number(80123456780123ULL); valid_number.set_country_code(44); valid_number.set_national_number(8012345678ULL); EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number)); EXPECT_EQ(valid_number, too_long_number); // IT number 022 3456 7890, but entered with 3 extra digits at the end. too_long_number.set_country_code(39); too_long_number.set_national_number(2234567890123ULL); too_long_number.set_italian_leading_zero(true); valid_number.set_country_code(39); valid_number.set_national_number(2234567890ULL); valid_number.set_italian_leading_zero(true); EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number)); EXPECT_EQ(valid_number, too_long_number); // Tests what happens when a valid number is passed in. PhoneNumber valid_number_copy(valid_number); EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&valid_number)); // Tests the number is not modified. EXPECT_EQ(valid_number_copy, valid_number); // Tests what happens when a number with invalid prefix is passed in. PhoneNumber number_with_invalid_prefix; number_with_invalid_prefix.set_country_code(1); // The test metadata says US numbers cannot have prefix 240. number_with_invalid_prefix.set_national_number(2401234567ULL); PhoneNumber invalid_number_copy(number_with_invalid_prefix); EXPECT_FALSE(phone_util_.TruncateTooLongNumber(&number_with_invalid_prefix)); // Tests the number is not modified. EXPECT_EQ(invalid_number_copy, number_with_invalid_prefix); // Tests what happens when a too short number is passed in. PhoneNumber too_short_number; too_short_number.set_country_code(1); too_short_number.set_national_number(1234ULL); PhoneNumber too_short_number_copy(too_short_number); EXPECT_FALSE(phone_util_.TruncateTooLongNumber(&too_short_number)); // Tests the number is not modified. EXPECT_EQ(too_short_number_copy, too_short_number); } TEST_F(PhoneNumberUtilTest, IsNumberGeographical) { PhoneNumber number; number.set_country_code(1); number.set_national_number(2423570000ULL); EXPECT_FALSE(IsNumberGeographical(number)); // Bahamas, mobile phone number. number.set_country_code(61); number.set_national_number(236618300ULL); EXPECT_TRUE(IsNumberGeographical(number)); // Australian fixed line number. number.set_country_code(800); number.set_national_number(12345678ULL); EXPECT_FALSE(IsNumberGeographical(number)); // Internation toll free number. } TEST_F(PhoneNumberUtilTest, IsLeadingZeroPossible) { EXPECT_TRUE(IsLeadingZeroPossible(39)); // Italy EXPECT_FALSE(IsLeadingZeroPossible(1)); // USA EXPECT_TRUE(IsLeadingZeroPossible(800)); // International toll free EXPECT_FALSE(IsLeadingZeroPossible(979)); // International premium-rate EXPECT_FALSE(IsLeadingZeroPossible(888)); // Not in metadata file, should // return default value of false. } TEST_F(PhoneNumberUtilTest, FormatInOriginalFormat) { PhoneNumber phone_number; string formatted_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""+442087654321"", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ(""+44 20 8765 4321"", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""02087654321"", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ(""(020) 8765 4321"", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""011442087654321"", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""011 44 20 8765 4321"", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""442087654321"", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ(""44 20 8765 4321"", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+442087654321"", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ(""(020) 8765 4321"", formatted_number); // Invalid numbers that we have a formatting pattern for should be formatted // properly. Note area codes starting with 7 are intentionally excluded in // the test metadata for testing purposes. phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""7345678901"", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""734 567 8901"", formatted_number); // US is not a leading zero country, and the presence of the leading zero // leads us to format the number using raw_input. phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""0734567 8901"", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""0734567 8901"", formatted_number); // This number is valid, but we don't have a formatting pattern for it. Fall // back to the raw input. phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""02-4567-8900"", RegionCode::KR(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::KR(), &formatted_number); EXPECT_EQ(""02-4567-8900"", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""01180012345678"", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""011 800 1234 5678"", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""+80012345678"", RegionCode::KR(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::KR(), &formatted_number); EXPECT_EQ(""+800 1234 5678"", formatted_number); // US local numbers are formatted correctly, as we have formatting patterns // for them. phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""2530000"", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""253 0000"", formatted_number); phone_number.Clear(); formatted_number.clear(); // Number with national prefix in the US. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""18003456789"", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""1 800 345 6789"", formatted_number); phone_number.Clear(); formatted_number.clear(); // Number without national prefix in the UK. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""2087654321"", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ(""20 8765 4321"", formatted_number); // Make sure no metadata is modified as a result of the previous function // call. phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+442087654321"", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ(""(020) 8765 4321"", formatted_number); phone_number.Clear(); formatted_number.clear(); // Number with national prefix in Mexico. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""013312345678"", RegionCode::MX(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(), &formatted_number); EXPECT_EQ(""01 33 1234 5678"", formatted_number); phone_number.Clear(); formatted_number.clear(); // Number without national prefix in Mexico. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""3312345678"", RegionCode::MX(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(), &formatted_number); EXPECT_EQ(""33 1234 5678"", formatted_number); phone_number.Clear(); formatted_number.clear(); // Italian fixed-line number. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""0212345678"", RegionCode::IT(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::IT(), &formatted_number); EXPECT_EQ(""02 1234 5678"", formatted_number); phone_number.Clear(); formatted_number.clear(); // Number with national prefix in Japan. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""00777012"", RegionCode::JP(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(), &formatted_number); EXPECT_EQ(""0077-7012"", formatted_number); phone_number.Clear(); formatted_number.clear(); // Number without national prefix in Japan. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""0777012"", RegionCode::JP(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(), &formatted_number); EXPECT_EQ(""0777012"", formatted_number); phone_number.Clear(); formatted_number.clear(); // Number with carrier code in Brazil. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""012 3121286979"", RegionCode::BR(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::BR(), &formatted_number); EXPECT_EQ(""012 3121286979"", formatted_number); phone_number.Clear(); formatted_number.clear(); // The default national prefix used in this case is 045. When a number with // national prefix 044 is entered, we return the raw input as we don't want to // change the number entered. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""044(33)1234-5678"", RegionCode::MX(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(), &formatted_number); EXPECT_EQ(""044(33)1234-5678"", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""045(33)1234-5678"", RegionCode::MX(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(), &formatted_number); EXPECT_EQ(""045 33 1234 5678"", formatted_number); // The default international prefix used in this case is 0011. When a number // with international prefix 0012 is entered, we return the raw input as we // don't want to change the number entered. phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""0012 16502530000"", RegionCode::AU(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::AU(), &formatted_number); EXPECT_EQ(""0012 16502530000"", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""0011 16502530000"", RegionCode::AU(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::AU(), &formatted_number); EXPECT_EQ(""0011 1 650 253 0000"", formatted_number); // Test the star sign is not removed from or added to the original input by // this method. phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""*1234"", RegionCode::JP(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(), &formatted_number); EXPECT_EQ(""*1234"", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""1234"", RegionCode::JP(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(), &formatted_number); EXPECT_EQ(""1234"", formatted_number); // Test that an invalid national number without raw input is just formatted // as the national number. phone_number.Clear(); formatted_number.clear(); phone_number.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY); phone_number.set_country_code(1); phone_number.set_national_number(650253000ULL); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ(""650253000"", formatted_number); } TEST_F(PhoneNumberUtilTest, IsPremiumRate) { PhoneNumber number; number.set_country_code(1); number.set_national_number(9004433030ULL); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); number.set_country_code(39); number.set_national_number(892123ULL); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); number.set_country_code(44); number.set_national_number(9187654321ULL); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); number.set_country_code(49); number.set_national_number(9001654321ULL); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); number.set_country_code(49); number.set_national_number(90091234567ULL); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); number.set_country_code(979); number.set_national_number(123456789ULL); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsTollFree) { PhoneNumber number; number.set_country_code(1); number.set_national_number(8881234567ULL); EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number)); number.set_country_code(39); number.set_national_number(803123ULL); EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number)); number.set_country_code(44); number.set_national_number(8012345678ULL); EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number)); number.set_country_code(49); number.set_national_number(8001234567ULL); EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number)); number.set_country_code(800); number.set_national_number(12345678ULL); EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsMobile) { PhoneNumber number; // A Bahama mobile number number.set_country_code(1); number.set_national_number(2423570000ULL); EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number)); number.set_country_code(39); number.set_national_number(312345678ULL); EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number)); number.set_country_code(44); number.set_national_number(7912345678ULL); EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number)); number.set_country_code(49); number.set_national_number(15123456789ULL); EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number)); number.set_country_code(54); number.set_national_number(91187654321ULL); EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsFixedLine) { PhoneNumber number; // A Bahama fixed-line number number.set_country_code(1); number.set_national_number(2423651234ULL); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number)); // An Italian fixed-line number number.Clear(); number.set_country_code(39); number.set_national_number(236618300ULL); number.set_italian_leading_zero(true); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number)); number.Clear(); number.set_country_code(44); number.set_national_number(2012345678ULL); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number)); number.set_country_code(49); number.set_national_number(301234ULL); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsFixedLineAndMobile) { PhoneNumber number; number.set_country_code(1); number.set_national_number(6502531111ULL); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE_OR_MOBILE, phone_util_.GetNumberType(number)); number.set_country_code(54); number.set_national_number(1987654321ULL); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE_OR_MOBILE, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsSharedCost) { PhoneNumber number; number.set_country_code(44); number.set_national_number(8431231234ULL); EXPECT_EQ(PhoneNumberUtil::SHARED_COST, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsVoip) { PhoneNumber number; number.set_country_code(44); number.set_national_number(5631231234ULL); EXPECT_EQ(PhoneNumberUtil::VOIP, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsPersonalNumber) { PhoneNumber number; number.set_country_code(44); number.set_national_number(7031231234ULL); EXPECT_EQ(PhoneNumberUtil::PERSONAL_NUMBER, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsUnknown) { PhoneNumber number; number.set_country_code(1); number.set_national_number(65025311111ULL); EXPECT_EQ(PhoneNumberUtil::UNKNOWN, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, GetCountryCodeForRegion) { EXPECT_EQ(1, phone_util_.GetCountryCodeForRegion(RegionCode::US())); EXPECT_EQ(64, phone_util_.GetCountryCodeForRegion(RegionCode::NZ())); EXPECT_EQ(0, phone_util_.GetCountryCodeForRegion(RegionCode::GetUnknown())); EXPECT_EQ(0, phone_util_.GetCountryCodeForRegion(RegionCode::UN001())); // CS is already deprecated so the library doesn't support it. EXPECT_EQ(0, phone_util_.GetCountryCodeForRegion(RegionCode::CS())); } TEST_F(PhoneNumberUtilTest, GetNationalDiallingPrefixForRegion) { string ndd_prefix; GetNddPrefixForRegion(RegionCode::US(), false, &ndd_prefix); EXPECT_EQ(""1"", ndd_prefix); // Test non-main country to see it gets the national dialling prefix for the // main country with that country calling code. GetNddPrefixForRegion(RegionCode::BS(), false, &ndd_prefix); EXPECT_EQ(""1"", ndd_prefix); GetNddPrefixForRegion(RegionCode::NZ(), false, &ndd_prefix); EXPECT_EQ(""0"", ndd_prefix); // Test case with non digit in the national prefix. GetNddPrefixForRegion(RegionCode::AO(), false, &ndd_prefix); EXPECT_EQ(""0~0"", ndd_prefix); GetNddPrefixForRegion(RegionCode::AO(), true, &ndd_prefix); EXPECT_EQ(""00"", ndd_prefix); // Test cases with invalid regions. GetNddPrefixForRegion(RegionCode::GetUnknown(), false, &ndd_prefix); EXPECT_EQ("""", ndd_prefix); GetNddPrefixForRegion(RegionCode::UN001(), false, &ndd_prefix); EXPECT_EQ("""", ndd_prefix); // CS is already deprecated so the library doesn't support it. GetNddPrefixForRegion(RegionCode::CS(), false, &ndd_prefix); EXPECT_EQ("""", ndd_prefix); } TEST_F(PhoneNumberUtilTest, IsViablePhoneNumber) { EXPECT_FALSE(IsViablePhoneNumber(""1"")); // Only one or two digits before strange non-possible punctuation. EXPECT_FALSE(IsViablePhoneNumber(""1+1+1"")); EXPECT_FALSE(IsViablePhoneNumber(""80+0"")); // Two digits is viable. EXPECT_TRUE(IsViablePhoneNumber(""00"")); EXPECT_TRUE(IsViablePhoneNumber(""111"")); // Alpha numbers. EXPECT_TRUE(IsViablePhoneNumber(""0800-4-pizza"")); EXPECT_TRUE(IsViablePhoneNumber(""0800-4-PIZZA"")); // We need at least three digits before any alpha characters. EXPECT_FALSE(IsViablePhoneNumber(""08-PIZZA"")); EXPECT_FALSE(IsViablePhoneNumber(""8-PIZZA"")); EXPECT_FALSE(IsViablePhoneNumber(""12. March"")); } TEST_F(PhoneNumberUtilTest, IsViablePhoneNumberNonAscii) { // Only one or two digits before possible punctuation followed by more digits. // The punctuation used here is the unicode character u+3000. EXPECT_TRUE(IsViablePhoneNumber(""1\xE3\x80\x80"" ""34"" /* ""1 34"" */)); EXPECT_FALSE(IsViablePhoneNumber(""1\xE3\x80\x80"" ""3+4"" /* ""1 3+4"" */)); // Unicode variants of possible starting character and other allowed // punctuation/digits. EXPECT_TRUE(IsViablePhoneNumber(""\xEF\xBC\x88"" ""1\xEF\xBC\x89\xE3\x80\x80"" ""3456789"" /* ""(1) 3456789"" */)); // Testing a leading + is okay. EXPECT_TRUE(IsViablePhoneNumber(""+1\xEF\xBC\x89\xE3\x80\x80"" ""3456789"" /* ""+1) 3456789"" */)); } TEST_F(PhoneNumberUtilTest, ConvertAlphaCharactersInNumber) { string input(""1800-ABC-DEF""); phone_util_.ConvertAlphaCharactersInNumber(&input); // Alpha chars are converted to digits; everything else is left untouched. static const string kExpectedOutput = ""1800-222-333""; EXPECT_EQ(kExpectedOutput, input); // Try with some non-ASCII characters. input.assign(""1\xE3\x80\x80\xEF\xBC\x88"" ""800) ABC-DEF"" /* ""1 (800) ABCD-DEF"" */); static const string kExpectedFullwidthOutput = ""1\xE3\x80\x80\xEF\xBC\x88"" ""800) 222-333"" /* ""1 (800) 222-333"" */; phone_util_.ConvertAlphaCharactersInNumber(&input); EXPECT_EQ(kExpectedFullwidthOutput, input); } TEST_F(PhoneNumberUtilTest, NormaliseRemovePunctuation) { string input_number(""034-56&+#2"" ""\xC2\xAD"" ""34""); Normalize(&input_number); static const string kExpectedOutput(""03456234""); EXPECT_EQ(kExpectedOutput, input_number) << ""Conversion did not correctly remove punctuation""; } TEST_F(PhoneNumberUtilTest, NormaliseReplaceAlphaCharacters) { string input_number(""034-I-am-HUNGRY""); Normalize(&input_number); static const string kExpectedOutput(""034426486479""); EXPECT_EQ(kExpectedOutput, input_number) << ""Conversion did not correctly replace alpha characters""; } TEST_F(PhoneNumberUtilTest, NormaliseOtherDigits) { // The first digit is a full-width 2, the last digit is an Arabic-indic digit // 5. string input_number(""\xEF\xBC\x92"" ""5\xD9\xA5"" /* ""25٥"" */); Normalize(&input_number); static const string kExpectedOutput(""255""); EXPECT_EQ(kExpectedOutput, input_number) << ""Conversion did not correctly replace non-latin digits""; // The first digit is an Eastern-Arabic 5, the latter an Eastern-Arabic 0. string eastern_arabic_input_number(""\xDB\xB5"" ""2\xDB\xB0"" /* ""۵2۰"" */); Normalize(&eastern_arabic_input_number); static const string kExpectedOutput2(""520""); EXPECT_EQ(kExpectedOutput2, eastern_arabic_input_number) << ""Conversion did not correctly replace non-latin digits""; } TEST_F(PhoneNumberUtilTest, NormaliseStripAlphaCharacters) { string input_number(""034-56&+a#234""); phone_util_.NormalizeDigitsOnly(&input_number); static const string kExpectedOutput(""03456234""); EXPECT_EQ(kExpectedOutput, input_number) << ""Conversion did not correctly remove alpha characters""; } TEST_F(PhoneNumberUtilTest, NormaliseStripNonDiallableCharacters) { string input_number(""03*4-56&+a#234""); NormalizeDiallableCharsOnly(&input_number); static const string kExpectedOutput(""03*456+234""); EXPECT_EQ(kExpectedOutput, input_number) << ""Conversion did not correctly remove non-diallable characters""; } TEST_F(PhoneNumberUtilTest, MaybeStripInternationalPrefix) { string international_prefix(""00[39]""); string number_to_strip(""0034567700-3898003""); // Note the dash is removed as part of the normalization. string stripped_number(""45677003898003""); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); EXPECT_EQ(stripped_number, number_to_strip) << ""The number was not stripped of its international prefix.""; // Now the number no longer starts with an IDD prefix, so it should now report // FROM_DEFAULT_COUNTRY. EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); number_to_strip.assign(""00945677003898003""); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); EXPECT_EQ(stripped_number, number_to_strip) << ""The number was not stripped of its international prefix.""; // Test it works when the international prefix is broken up by spaces. number_to_strip.assign(""00 9 45677003898003""); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); EXPECT_EQ(stripped_number, number_to_strip) << ""The number was not stripped of its international prefix.""; // Now the number no longer starts with an IDD prefix, so it should now report // FROM_DEFAULT_COUNTRY. EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); // Test the + symbol is also recognised and stripped. number_to_strip.assign(""+45677003898003""); stripped_number.assign(""45677003898003""); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); EXPECT_EQ(stripped_number, number_to_strip) << ""The number supplied was not stripped of the plus symbol.""; // If the number afterwards is a zero, we should not strip this - no country // code begins with 0. number_to_strip.assign(""0090112-3123""); stripped_number.assign(""00901123123""); EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); EXPECT_EQ(stripped_number, number_to_strip) << ""The number had a 0 after the match so shouldn't be stripped.""; // Here the 0 is separated by a space from the IDD. number_to_strip.assign(""009 0-112-3123""); EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); } TEST_F(PhoneNumberUtilTest, MaybeStripNationalPrefixAndCarrierCode) { PhoneMetadata metadata; metadata.set_national_prefix_for_parsing(""34""); metadata.mutable_general_desc()->set_national_number_pattern(""\\d{4,8}""); string number_to_strip(""34356778""); string stripped_number(""356778""); string carrier_code; MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ(stripped_number, number_to_strip) << ""Should have had national prefix stripped.""; EXPECT_EQ("""", carrier_code) << ""Should have had no carrier code stripped.""; // Retry stripping - now the number should not start with the national prefix, // so no more stripping should occur. MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ(stripped_number, number_to_strip) << ""Should have had no change - no national prefix present.""; // Some countries have no national prefix. Repeat test with none specified. metadata.clear_national_prefix_for_parsing(); MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ(stripped_number, number_to_strip) << ""Should have had no change - empty national prefix.""; // If the resultant number doesn't match the national rule, it shouldn't be // stripped. metadata.set_national_prefix_for_parsing(""3""); number_to_strip.assign(""3123""); stripped_number.assign(""3123""); MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ(stripped_number, number_to_strip) << ""Should have had no change - after stripping, it wouldn't have "" << ""matched the national rule.""; // Test extracting carrier selection code. metadata.set_national_prefix_for_parsing(""0(81)?""); number_to_strip.assign(""08122123456""); stripped_number.assign(""22123456""); MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ(""81"", carrier_code) << ""Should have had carrier code stripped.""; EXPECT_EQ(stripped_number, number_to_strip) << ""Should have had national prefix and carrier code stripped.""; // If there was a transform rule, check it was applied. metadata.set_national_prefix_transform_rule(""5$15""); // Note that a capturing group is present here. metadata.set_national_prefix_for_parsing(""0(\\d{2})""); number_to_strip.assign(""031123""); string transformed_number(""5315123""); MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ(transformed_number, number_to_strip) << ""Was not successfully transformed.""; } TEST_F(PhoneNumberUtilTest, MaybeStripExtension) { // One with extension. string number(""1234576 ext. 1234""); string extension; string expected_extension(""1234""); string stripped_number(""1234576""); EXPECT_TRUE(MaybeStripExtension(&number, &extension)); EXPECT_EQ(stripped_number, number); EXPECT_EQ(expected_extension, extension); // One without extension. number.assign(""1234-576""); extension.clear(); stripped_number.assign(""1234-576""); EXPECT_FALSE(MaybeStripExtension(&number, &extension)); EXPECT_EQ(stripped_number, number); EXPECT_TRUE(extension.empty()); // One with an extension caught by the second capturing group in // kKnownExtnPatterns. number.assign(""1234576-123#""); extension.clear(); expected_extension.assign(""123""); stripped_number.assign(""1234576""); EXPECT_TRUE(MaybeStripExtension(&number, &extension)); EXPECT_EQ(stripped_number, number); EXPECT_EQ(expected_extension, extension); number.assign(""1234576 ext.123#""); extension.clear(); EXPECT_TRUE(MaybeStripExtension(&number, &extension)); EXPECT_EQ(stripped_number, number); EXPECT_EQ(expected_extension, extension); } TEST_F(PhoneNumberUtilTest, MaybeExtractCountryCode) { PhoneNumber number; const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::US()); // Note that for the US, the IDD is 011. string phone_number(""011112-3456789""); string stripped_number(""123456789""); int expected_country_code = 1; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); number.Clear(); phone_number.assign(""+80012345678""); stripped_number.assign(""12345678""); expected_country_code = 800; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); number.Clear(); phone_number.assign(""+6423456789""); stripped_number.assign(""23456789""); expected_country_code = 64; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); // Should not have extracted a country code - no international prefix present. number.Clear(); expected_country_code = 0; phone_number.assign(""2345-6789""); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); expected_country_code = 0; phone_number.assign(""0119991123456789""); stripped_number.assign(phone_number); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); number.Clear(); phone_number.assign(""(1 610) 619 4466""); stripped_number.assign(""6106194466""); expected_country_code = 1; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); number.Clear(); phone_number.assign(""(1 610) 619 4466""); stripped_number.assign(""6106194466""); expected_country_code = 1; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, false, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_FALSE(number.has_country_code_source()); EXPECT_EQ(stripped_number, phone_number); // Should not have extracted a country code - invalid number after extraction // of uncertain country code. number.Clear(); phone_number.assign(""(1 610) 619 446""); stripped_number.assign(""1610619446""); expected_country_code = 0; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, false, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_FALSE(number.has_country_code_source()); EXPECT_EQ(stripped_number, phone_number); number.Clear(); phone_number.assign(""(1 610) 619""); stripped_number.assign(""1610619""); expected_country_code = 0; // Should not have extracted a country code - invalid number both before and // after extraction of uncertain country code. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); } TEST_F(PhoneNumberUtilTest, CountryWithNoNumberDesc) { string formatted_number; // Andorra is a country where we don't have PhoneNumberDesc info in the // metadata. PhoneNumber ad_number; ad_number.set_country_code(376); ad_number.set_national_number(12345ULL); phone_util_.Format(ad_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ(""+376 12345"", formatted_number); phone_util_.Format(ad_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+37612345"", formatted_number); phone_util_.Format(ad_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ(""12345"", formatted_number); EXPECT_EQ(PhoneNumberUtil::UNKNOWN, phone_util_.GetNumberType(ad_number)); EXPECT_FALSE(phone_util_.IsValidNumber(ad_number)); // Test dialing a US number from within Andorra. PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(6502530000ULL); phone_util_.FormatOutOfCountryCallingNumber(us_number, RegionCode::AD(), &formatted_number); EXPECT_EQ(""00 1 650 253 0000"", formatted_number); } TEST_F(PhoneNumberUtilTest, UnknownCountryCallingCode) { PhoneNumber invalid_number; invalid_number.set_country_code(kInvalidCountryCode); invalid_number.set_national_number(12345ULL); EXPECT_FALSE(phone_util_.IsValidNumber(invalid_number)); // It's not very well defined as to what the E164 representation for a number // with an invalid country calling code is, but just prefixing the country // code and national number is about the best we can do. string formatted_number; phone_util_.Format(invalid_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ(""+212345"", formatted_number); } TEST_F(PhoneNumberUtilTest, IsNumberMatchMatches) { // Test simple matches where formatting is different, or leading zeros, or // country code has been specified. EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+64 3 331 6005"", ""+64 03 331 6005"")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+800 1234 5678"", ""+80012345678"")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+64 03 331-6005"", ""+64 03331 6005"")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+643 331-6005"", ""+64033316005"")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+643 331-6005"", ""+6433316005"")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+64 3 331-6005"", ""+6433316005"")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings( ""+64 3 331-6005"", ""tel:+64-3-331-6005;isub=123"")); // Test alpha numbers. EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+1800 siX-Flags"", ""+1 800 7493 5247"")); // Test numbers with extensions. EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+64 3 331-6005 extn 1234"", ""+6433316005#1234"")); // Test proto buffers. PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(33316005ULL); nz_number.set_extension(""3456""); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithOneString(nz_number, ""+643 331 6005 ext 3456"")); nz_number.clear_extension(); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithOneString(nz_number, ""+643 331 6005"")); // Check empty extensions are ignored. nz_number.set_extension(""""); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithOneString(nz_number, ""+643 331 6005"")); // Check variant with two proto buffers. PhoneNumber nz_number_2; nz_number_2.set_country_code(64); nz_number_2.set_national_number(33316005ULL); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatch(nz_number, nz_number_2)); // Check raw_input, country_code_source and preferred_domestic_carrier_code // are ignored. PhoneNumber br_number_1; PhoneNumber br_number_2; br_number_1.set_country_code(55); br_number_1.set_national_number(3121286979ULL); br_number_1.set_country_code_source(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN); br_number_1.set_preferred_domestic_carrier_code(""12""); br_number_1.set_raw_input(""012 3121286979""); br_number_2.set_country_code(55); br_number_2.set_national_number(3121286979ULL); br_number_2.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY); br_number_2.set_preferred_domestic_carrier_code(""14""); br_number_2.set_raw_input(""143121286979""); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatch(br_number_1, br_number_2)); } TEST_F(PhoneNumberUtilTest, IsNumberMatchNonMatches) { // NSN matches. EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""03 331 6005"", ""03 331 6006"")); EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+800 1234 5678"", ""+1 800 1234 5678"")); // Different country code, partial number match. EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+64 3 331-6005"", ""+16433316005"")); // Different country code, same number. EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+64 3 331-6005"", ""+6133316005"")); // Extension different, all else the same. EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+64 3 331-6005 extn 1234"", ""+0116433316005#1235"")); EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings( ""+64 3 331-6005 extn 1234"", ""tel:+64-3-331-6005;ext=1235"")); // NSN matches, but extension is different - not the same number. EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+64 3 331-6005 ext.1235"", ""3 331 6005#1234"")); // Invalid numbers that can't be parsed. EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER, phone_util_.IsNumberMatchWithTwoStrings(""4"", ""3 331 6043"")); // Invalid numbers that can't be parsed. EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER, phone_util_.IsNumberMatchWithTwoStrings(""+43"", ""+64 3 331 6005"")); EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER, phone_util_.IsNumberMatchWithTwoStrings(""+43"", ""64 3 331 6005"")); EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER, phone_util_.IsNumberMatchWithTwoStrings(""Dog"", ""64 3 331 6005"")); } TEST_F(PhoneNumberUtilTest, IsNumberMatchNsnMatches) { // NSN matches. EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+64 3 331-6005"", ""03 331 6005"")); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings( ""+64 3 331-6005"", ""tel:03-331-6005;isub=1234;phone-context=abc.nz"")); PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(33316005ULL); nz_number.set_extension(""""); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithOneString(nz_number, ""03 331 6005"")); // Here the second number possibly starts with the country code for New // Zealand, although we are unsure. EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithOneString(nz_number, ""(64-3) 331 6005"")); // Here, the 1 might be a national prefix, if we compare it to the US number, // so the resultant match is an NSN match. PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(2345678901ULL); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithOneString(us_number, ""1-234-567-8901"")); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithOneString(us_number, ""2345678901"")); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+1 234-567 8901"", ""1 234 567 8901"")); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""1 234-567 8901"", ""1 234 567 8901"")); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""1 234-567 8901"", ""+1 234 567 8901"")); // For this case, the match will be a short NSN match, because we cannot // assume that the 1 might be a national prefix, so don't remove it when // parsing. PhoneNumber random_number; random_number.set_country_code(41); random_number.set_national_number(2345678901ULL); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithOneString(random_number, ""1-234-567-8901"")); } TEST_F(PhoneNumberUtilTest, IsNumberMatchShortNsnMatches) { // Short NSN matches with the country not specified for either one or both // numbers. EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+64 3 331-6005"", ""331 6005"")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings( ""+64 3 331-6005"", ""tel:331-6005;phone-context=abc.nz"")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings( ""+64 3 331-6005"", ""tel:331-6005;isub=1234;phone-context=abc.nz"")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings( ""+64 3 331-6005"", ""tel:331-6005;isub=1234;phone-context=abc.nz;a=%A1"")); // We did not know that the ""0"" was a national prefix since neither number has // a country code, so this is considered a SHORT_NSN_MATCH. EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""3 331-6005"", ""03 331 6005"")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""3 331-6005"", ""331 6005"")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings( ""3 331-6005"", ""tel:331-6005;phone-context=abc.nz"")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""3 331-6005"", ""+64 331 6005"")); // Short NSN match with the country specified. EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""03 331-6005"", ""331 6005"")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""1 234 345 6789"", ""345 6789"")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+1 (234) 345 6789"", ""345 6789"")); // NSN matches, country code omitted for one number, extension missing for // one. EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings(""+64 3 331-6005"", ""3 331 6005#1234"")); // One has Italian leading zero, one does not. PhoneNumber it_number_1, it_number_2; it_number_1.set_country_code(39); it_number_1.set_national_number(1234ULL); it_number_1.set_italian_leading_zero(true); it_number_2.set_country_code(39); it_number_2.set_national_number(1234ULL); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatch(it_number_1, it_number_2)); // One has an extension, the other has an extension of """". it_number_1.set_extension(""1234""); it_number_1.clear_italian_leading_zero(); it_number_2.set_extension(""""); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatch(it_number_1, it_number_2)); } TEST_F(PhoneNumberUtilTest, ParseNationalNumber) { PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(33316005ULL); PhoneNumber test_number; // National prefix attached. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""033316005"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); // National prefix missing. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""33316005"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); // National prefix attached and some formatting present. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""03-331 6005"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""03 331 6005"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); // Test parsing RFC3966 format with a phone context. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:03-331-6005;phone-context=+64"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:331-6005;phone-context=+64-3"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:331-6005;phone-context=+64-3"", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""My number is tel:03-331-6005;phone-context=+64"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); // Test parsing RFC3966 format with optional user-defined parameters. The // parameters will appear after the context if present. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:03-331-6005;phone-context=+64;a=%A1"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); // Test parsing RFC3966 with an ISDN subaddress. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:03-331-6005;isub=12345;phone-context=+64"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:+64-3-331-6005;isub=12345"", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""03-331-6005;phone-context=+64"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); // Testing international prefixes. // Should strip country code. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0064 3 331 6005"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); // Try again, but this time we have an international number with Region Code // US. It should recognise the country code and parse accordingly. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""01164 3 331 6005"", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+64 3 331 6005"", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); // We should ignore the leading plus here, since it is not followed by a valid // country code but instead is followed by the IDD for the US. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+01164 3 331 6005"", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+0064 3 331 6005"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+ 00 64 3 331 6005"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); PhoneNumber us_local_number; us_local_number.set_country_code(1); us_local_number.set_national_number(2530000ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:253-0000;phone-context=www.google.com"", RegionCode::US(), &test_number)); EXPECT_EQ(us_local_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( ""tel:253-0000;isub=12345;phone-context=www.google.com"", RegionCode::US(), &test_number)); EXPECT_EQ(us_local_number, test_number); // This is invalid because no ""+"" sign is present as part of phone-context. // The phone context is simply ignored in this case just as if it contains a // domain. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:2530000;isub=12345;phone-context=1-650"", RegionCode::US(), &test_number)); EXPECT_EQ(us_local_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:2530000;isub=12345;phone-context=1234.com"", RegionCode::US(), &test_number)); EXPECT_EQ(us_local_number, test_number); // Test for http://b/issue?id=2247493 nz_number.Clear(); nz_number.set_country_code(64); nz_number.set_national_number(64123456ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+64(0)64123456"", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); // Check that using a ""/"" is fine in a phone number. PhoneNumber de_number; de_number.set_country_code(49); de_number.set_national_number(12345678ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""123/45678"", RegionCode::DE(), &test_number)); EXPECT_EQ(de_number, test_number); PhoneNumber us_number; us_number.set_country_code(1); // Check it doesn't use the '1' as a country code when parsing if the phone // number was already possible. us_number.set_national_number(1234567890ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""123-456-7890"", RegionCode::US(), &test_number)); EXPECT_EQ(us_number, test_number); // Test star numbers. Although this is not strictly valid, we would like to // make sure we can parse the output we produce when formatting the number. PhoneNumber star_number; star_number.set_country_code(81); star_number.set_national_number(2345ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+81 *2345"", RegionCode::JP(), &test_number)); EXPECT_EQ(star_number, test_number); PhoneNumber short_number; short_number.set_country_code(64); short_number.set_national_number(12ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""12"", RegionCode::NZ(), &test_number)); EXPECT_EQ(short_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseNumberWithAlphaCharacters) { // Test case with alpha characters. PhoneNumber test_number; PhoneNumber tollfree_number; tollfree_number.set_country_code(64); tollfree_number.set_national_number(800332005ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0800 DDA 005"", RegionCode::NZ(), &test_number)); EXPECT_EQ(tollfree_number, test_number); PhoneNumber [MASK] ; [MASK] .set_country_code(64); [MASK] .set_national_number(9003326005ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0900 DDA 6005"", RegionCode::NZ(), &test_number)); EXPECT_EQ( [MASK] , test_number); // Not enough alpha characters for them to be considered intentional, so they // are stripped. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0900 332 6005a"", RegionCode::NZ(), &test_number)); EXPECT_EQ( [MASK] , test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0900 332 600a5"", RegionCode::NZ(), &test_number)); EXPECT_EQ( [MASK] , test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0900 332 600A5"", RegionCode::NZ(), &test_number)); EXPECT_EQ( [MASK] , test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0900 a332 600A5"", RegionCode::NZ(), &test_number)); EXPECT_EQ( [MASK] , test_number); } TEST_F(PhoneNumberUtilTest, ParseWithInternationalPrefixes) { PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(6503336000ULL); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+1 (650) 333-6000"", RegionCode::US(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+1-650-333-6000"", RegionCode::US(), &test_number)); EXPECT_EQ(us_number, test_number); // Calling the US number from Singapore by using different service providers // 1st test: calling using SingTel IDD service (IDD is 001) EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0011-650-333-6000"", RegionCode::SG(), &test_number)); EXPECT_EQ(us_number, test_number); // 2nd test: calling using StarHub IDD service (IDD is 008) EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0081-650-333-6000"", RegionCode::SG(), &test_number)); EXPECT_EQ(us_number, test_number); // 3rd test: calling using SingTel V019 service (IDD is 019) EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0191-650-333-6000"", RegionCode::SG(), &test_number)); EXPECT_EQ(us_number, test_number); // Calling the US number from Poland EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0~01-650-333-6000"", RegionCode::PL(), &test_number)); EXPECT_EQ(us_number, test_number); // Using ""++"" at the start. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""++1 (650) 333-6000"", RegionCode::PL(), &test_number)); EXPECT_EQ(us_number, test_number); // Using a full-width plus sign. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""\xEF\xBC\x8B"" ""1 (650) 333-6000"", /* ""+1 (650) 333-6000"" */ RegionCode::SG(), &test_number)); // Using a soft hyphen U+00AD. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""1 (650) 333"" ""\xC2\xAD"" ""-6000"", /* ""1 (650) 333­-6000­"" */ RegionCode::US(), &test_number)); EXPECT_EQ(us_number, test_number); // The whole number, including punctuation, is here represented in full-width // form. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""\xEF\xBC\x8B\xEF\xBC\x91\xE3\x80\x80\xEF\xBC\x88"" ""\xEF\xBC\x96\xEF\xBC\x95\xEF\xBC\x90\xEF\xBC\x89"" ""\xE3\x80\x80\xEF\xBC\x93\xEF\xBC\x93\xEF\xBC\x93"" ""\xEF\xBC\x8D\xEF\xBC\x96\xEF\xBC\x90\xEF\xBC\x90"" ""\xEF\xBC\x90"", /* ""+1 (650) 333-6000"" */ RegionCode::SG(), &test_number)); EXPECT_EQ(us_number, test_number); // Using the U+30FC dash. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""\xEF\xBC\x8B\xEF\xBC\x91\xE3\x80\x80\xEF\xBC\x88"" ""\xEF\xBC\x96\xEF\xBC\x95\xEF\xBC\x90\xEF\xBC\x89"" ""\xE3\x80\x80\xEF\xBC\x93\xEF\xBC\x93\xEF\xBC\x93"" ""\xE3\x83\xBC\xEF\xBC\x96\xEF\xBC\x90\xEF\xBC\x90"" ""\xEF\xBC\x90"", /* ""+1 (650) 333ー6000"" */ RegionCode::SG(), &test_number)); EXPECT_EQ(us_number, test_number); PhoneNumber toll_free_number; toll_free_number.set_country_code(800); toll_free_number.set_national_number(12345678ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""011 800 1234 5678"", RegionCode::US(), &test_number)); EXPECT_EQ(toll_free_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseWithLeadingZero) { PhoneNumber it_number; it_number.set_country_code(39); it_number.set_national_number(236618300ULL); it_number.set_italian_leading_zero(true); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+39 02-36618 300"", RegionCode::NZ(), &test_number)); EXPECT_EQ(it_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""02-36618 300"", RegionCode::IT(), &test_number)); EXPECT_EQ(it_number, test_number); it_number.Clear(); it_number.set_country_code(39); it_number.set_national_number(312345678ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""312 345 678"", RegionCode::IT(), &test_number)); EXPECT_EQ(it_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseNationalNumberArgentina) { // Test parsing mobile numbers of Argentina. PhoneNumber ar_number; ar_number.set_country_code(54); ar_number.set_national_number(93435551212ULL); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+54 9 343 555 1212"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0343 15 555 1212"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); ar_number.set_national_number(93715654320ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+54 9 3715 65 4320"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""03715 15 65 4320"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); // Test parsing fixed-line numbers of Argentina. ar_number.set_national_number(1137970000ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+54 11 3797 0000"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""011 3797 0000"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); ar_number.set_national_number(3715654321ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+54 3715 65 4321"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""03715 65 4321"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); ar_number.set_national_number(2312340000ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+54 23 1234 0000"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""023 1234 0000"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseWithXInNumber) { // Test that having an 'x' in the phone number at the start is ok and that it // just gets removed. PhoneNumber ar_number; ar_number.set_country_code(54); ar_number.set_national_number(123456789ULL); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0123456789"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(0) 123456789"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0 123456789"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(0xx) 123456789"", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); PhoneNumber ar_from_us; ar_from_us.set_country_code(54); ar_from_us.set_national_number(81429712ULL); // This test is intentionally constructed such that the number of digit after // xx is larger than 7, so that the number won't be mistakenly treated as an // extension, as we allow extensions up to 7 digits. This assumption is okay // for now as all the countries where a carrier selection code is written in // the form of xx have a national significant number of length larger than 7. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""011xx5481429712"", RegionCode::US(), &test_number)); EXPECT_EQ(ar_from_us, test_number); } TEST_F(PhoneNumberUtilTest, ParseNumbersMexico) { // Test parsing fixed-line numbers of Mexico. PhoneNumber mx_number; mx_number.set_country_code(52); mx_number.set_national_number(4499780001ULL); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+52 (449)978-0001"", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""01 (449)978-0001"", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(449)978-0001"", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); // Test parsing mobile numbers of Mexico. mx_number.Clear(); mx_number.set_country_code(52); mx_number.set_national_number(13312345678ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+52 1 33 1234-5678"", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""044 (33) 1234-5678"", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""045 33 1234-5678"", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); } TEST_F(PhoneNumberUtilTest, FailedParseOnInvalidNumbers) { PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(""This is not a phone number"", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(""1 Still not a number"", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(""1 MICROSOFT"", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(""12 MICROSOFT"", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_LONG_NSN, phone_util_.Parse(""01495 72553301873 810104"", RegionCode::GB(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(""+---"", RegionCode::DE(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(""+***"", RegionCode::DE(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(""+*******91"", RegionCode::DE(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_NSN, phone_util_.Parse(""+49 0"", RegionCode::DE(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse(""+210 3456 56789"", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); // 00 is a correct IDD, but 210 is not a valid country code. EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse(""+ 00 210 3 331 6005"", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse(""123 456 7890"", RegionCode::GetUnknown(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse(""123 456 7890"", RegionCode::CS(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD, phone_util_.Parse(""0044-----"", RegionCode::GB(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD, phone_util_.Parse(""0044"", RegionCode::GB(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD, phone_util_.Parse(""011"", RegionCode::US(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD, phone_util_.Parse(""0119"", RegionCode::US(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); // RFC3966 phone-context is a website. EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse(""tel:555-1234;phone-context=www.google.com"", RegionCode::ZZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); // This is invalid because no ""+"" sign is present as part of phone-context. // This should not succeed in being parsed. EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse(""tel:555-1234;phone-context=1-331"", RegionCode::ZZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); } TEST_F(PhoneNumberUtilTest, ParseNumbersWithPlusWithNoRegion) { PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(33316005ULL); // RegionCode::GetUnknown() is allowed only if the number starts with a '+' - // then the country code can be calculated. PhoneNumber result_proto; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+64 3 331 6005"", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); // Test with full-width plus. result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""\xEF\xBC\x8B"" ""64 3 331 6005"", /* ""+64 3 331 6005"" */ RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); // Test with normal plus but leading characters that need to be stripped. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("" +64 3 331 6005"", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); PhoneNumber toll_free_number; toll_free_number.set_country_code(800); toll_free_number.set_national_number(12345678ULL); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+800 1234 5678"", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(toll_free_number, result_proto); PhoneNumber universal_premium_rate; universal_premium_rate.set_country_code(979); universal_premium_rate.set_national_number(123456789ULL); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+979 123 456 789"", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(universal_premium_rate, result_proto); result_proto.Clear(); // Test parsing RFC3966 format with a phone context. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:03-331-6005;phone-context=+64"", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("" tel:03-331-6005;phone-context=+64"", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:03-331-6005;isub=12345;phone-context=+64"", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); nz_number.set_raw_input(""+64 3 331 6005""); nz_number.set_country_code_source(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN); // It is important that we set this to an empty string, since we used // ParseAndKeepRawInput and no carrrier code was found. nz_number.set_preferred_domestic_carrier_code(""""); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""+64 3 331 6005"", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); } TEST_F(PhoneNumberUtilTest, ParseNumberTooShortIfNationalPrefixStripped) { PhoneNumber test_number; // Test that a number whose first digits happen to coincide with the national // prefix does not get them stripped if doing so would result in a number too // short to be a possible (regular length) phone number for that region. PhoneNumber by_number; by_number.set_country_code(375); by_number.set_national_number(8123L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""8123"", RegionCode::BY(), &test_number)); EXPECT_EQ(by_number, test_number); by_number.set_national_number(81234L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""81234"", RegionCode::BY(), &test_number)); EXPECT_EQ(by_number, test_number); // The prefix doesn't get stripped, since the input is a viable 6-digit // number, whereas the result of stripping is only 5 digits. by_number.set_national_number(812345L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""812345"", RegionCode::BY(), &test_number)); EXPECT_EQ(by_number, test_number); // The prefix gets stripped, since only 6-digit numbers are possible. by_number.set_national_number(123456L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""8123456"", RegionCode::BY(), &test_number)); EXPECT_EQ(by_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseExtensions) { PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(33316005ULL); nz_number.set_extension(""3456""); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""03 331 6005 ext 3456"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""03 331 6005x3456"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""03-331 6005 int.3456"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""03 331 6005 #3456"", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); // Test the following do not extract extensions: PhoneNumber non_extn_number; non_extn_number.set_country_code(1); non_extn_number.set_national_number(80074935247ULL); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""1800 six-flags"", RegionCode::US(), &test_number)); EXPECT_EQ(non_extn_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""1800 SIX-FLAGS"", RegionCode::US(), &test_number)); EXPECT_EQ(non_extn_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0~0 1800 7493 5247"", RegionCode::PL(), &test_number)); EXPECT_EQ(non_extn_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(1800) 7493.5247"", RegionCode::US(), &test_number)); EXPECT_EQ(non_extn_number, test_number); // Check that the last instance of an extension token is matched. PhoneNumber extn_number; extn_number.set_country_code(1); extn_number.set_national_number(80074935247ULL); extn_number.set_extension(""1234""); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0~0 1800 7493 5247 ~1234"", RegionCode::PL(), &test_number)); EXPECT_EQ(extn_number, test_number); // Verifying bug-fix where the last digit of a number was previously omitted // if it was a 0 when extracting the extension. Also verifying a few different // cases of extensions. PhoneNumber uk_number; uk_number.set_country_code(44); uk_number.set_national_number(2034567890ULL); uk_number.set_extension(""456""); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+44 2034567890x456"", RegionCode::NZ(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+44 2034567890x456"", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+44 2034567890 x456"", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+44 2034567890 X456"", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+44 2034567890 X 456"", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+44 2034567890 X 456"", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+44 2034567890 x 456 "", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+44 2034567890 X 456"", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+44-2034567890;ext=456"", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""tel:2034567890;ext=456;phone-context=+44"", RegionCode::ZZ(), &test_number)); EXPECT_EQ(uk_number, test_number); // Full-width extension, ""extn"" only. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( ""+442034567890\xEF\xBD\x85\xEF\xBD\x98\xEF\xBD\x94\xEF\xBD\x8E"" ""456"", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); // ""xtn"" only. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( ""+44-2034567890\xEF\xBD\x98\xEF\xBD\x94\xEF\xBD\x8E""""456"", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); // ""xt"" only. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+44-2034567890\xEF\xBD\x98\xEF\xBD\x94""""456"", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); PhoneNumber us_with_extension; us_with_extension.set_country_code(1); us_with_extension.set_national_number(8009013355ULL); us_with_extension.set_extension(""7246433""); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(800) 901-3355 x 7246433"", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(800) 901-3355 , ext 7246433"", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(800) 901-3355 ,extension 7246433"", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(800) 901-3355 ,extensi\xC3\xB3n 7246433"", /* ""(800) 901-3355 ,extensión 7246433"" */ RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); // Repeat with the small letter o with acute accent created by combining // characters. EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(800) 901-3355 ,extensio\xCC\x81n 7246433"", /* ""(800) 901-3355 ,extensión 7246433"" */ RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(800) 901-3355 , 7246433"", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(800) 901-3355 ext: 7246433"", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); // Test that if a number has two extensions specified, we ignore the second. PhoneNumber us_with_two_extensions_number; us_with_two_extensions_number.set_country_code(1); us_with_two_extensions_number.set_national_number(2121231234ULL); us_with_two_extensions_number.set_extension(""508""); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(212)123-1234 x508/x1234"", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_two_extensions_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(212)123-1234 x508/ x1234"", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_two_extensions_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""(212)123-1234 x508\\x1234"", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_two_extensions_number, test_number); // Test parsing numbers in the form (645) 123-1234-910# works, where the last // 3 digits before the # are an extension. us_with_extension.Clear(); us_with_extension.set_country_code(1); us_with_extension.set_national_number(6451231234ULL); us_with_extension.set_extension(""910""); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""+1 (645) 123 1234-910#"", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); } TEST_F(PhoneNumberUtilTest, ParseAndKeepRaw) { PhoneNumber alpha_numeric_number; alpha_numeric_number.set_country_code(1); alpha_numeric_number.set_national_number(80074935247ULL); alpha_numeric_number.set_raw_input(""800 six-flags""); alpha_numeric_number.set_country_code_source( PhoneNumber::FROM_DEFAULT_COUNTRY); alpha_numeric_number.set_preferred_domestic_carrier_code(""""); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""800 six-flags"", RegionCode::US(), &test_number)); EXPECT_EQ(alpha_numeric_number, test_number); alpha_numeric_number.set_national_number(8007493524ULL); alpha_numeric_number.set_raw_input(""1800 six-flag""); alpha_numeric_number.set_country_code_source( PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""1800 six-flag"", RegionCode::US(), &test_number)); EXPECT_EQ(alpha_numeric_number, test_number); alpha_numeric_number.set_raw_input(""+1800 six-flag""); alpha_numeric_number.set_country_code_source( PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""+1800 six-flag"", RegionCode::CN(), &test_number)); EXPECT_EQ(alpha_numeric_number, test_number); alpha_numeric_number.set_raw_input(""001800 six-flag""); alpha_numeric_number.set_country_code_source( PhoneNumber::FROM_NUMBER_WITH_IDD); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""001800 six-flag"", RegionCode::NZ(), &test_number)); EXPECT_EQ(alpha_numeric_number, test_number); // Try with invalid region - expect failure. We clear the test number first // because if parsing isn't successful, the number parsed in won't be changed. test_number.Clear(); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse(""123 456 7890"", RegionCode::CS(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); PhoneNumber korean_number; korean_number.set_country_code(82); korean_number.set_national_number(22123456); korean_number.set_raw_input(""08122123456""); korean_number.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY); korean_number.set_preferred_domestic_carrier_code(""81""); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput(""08122123456"", RegionCode::KR(), &test_number)); EXPECT_EQ(korean_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseItalianLeadingZeros) { PhoneNumber zeros_number; zeros_number.set_country_code(61); PhoneNumber test_number; // Test the number ""011"". zeros_number.set_national_number(11L); zeros_number.set_italian_leading_zero(true); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""011"", RegionCode::AU(), &test_number)); EXPECT_EQ(zeros_number, test_number); // Test the number ""001"". zeros_number.set_national_number(1L); zeros_number.set_italian_leading_zero(true); zeros_number.set_number_of_leading_zeros(2); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""001"", RegionCode::AU(), &test_number)); EXPECT_EQ(zeros_number, test_number); // Test the number ""000"". This number has 2 leading zeros. zeros_number.set_national_number(0L); zeros_number.set_italian_leading_zero(true); zeros_number.set_number_of_leading_zeros(2); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""000"", RegionCode::AU(), &test_number)); EXPECT_EQ(zeros_number, test_number); // Test the number ""0000"". This number has 3 leading zeros. zeros_number.set_national_number(0L); zeros_number.set_italian_leading_zero(true); zeros_number.set_number_of_leading_zeros(3); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(""0000"", RegionCode::AU(), &test_number)); EXPECT_EQ(zeros_number, test_number); } TEST_F(PhoneNumberUtilTest, CanBeInternationallyDialled) { PhoneNumber test_number; test_number.set_country_code(1); // We have no-international-dialling rules for the US in our test metadata // that say that toll-free numbers cannot be dialled internationally. test_number.set_national_number(8002530000ULL); EXPECT_FALSE(CanBeInternationallyDialled(test_number)); // Normal US numbers can be internationally dialled. test_number.set_national_number(6502530000ULL); EXPECT_TRUE(CanBeInternationallyDialled(test_number)); // Invalid number. test_number.set_national_number(2530000ULL); EXPECT_TRUE(CanBeInternationallyDialled(test_number)); // We have no data for NZ - should return true. test_number.set_country_code(64); test_number.set_national_number(33316005ULL); EXPECT_TRUE(CanBeInternationallyDialled(test_number)); test_number.set_country_code(800); test_number.set_national_number(12345678ULL); EXPECT_TRUE(CanBeInternationallyDialled(test_number)); } TEST_F(PhoneNumberUtilTest, IsAlphaNumber) { EXPECT_TRUE(phone_util_.IsAlphaNumber(""1800 six-flags"")); EXPECT_TRUE(phone_util_.IsAlphaNumber(""1800 six-flags ext. 1234"")); EXPECT_TRUE(phone_util_.IsAlphaNumber(""+800 six-flags"")); EXPECT_TRUE(phone_util_.IsAlphaNumber(""180 six-flags"")); EXPECT_FALSE(phone_util_.IsAlphaNumber(""1800 123-1234"")); EXPECT_FALSE(phone_util_.IsAlphaNumber(""1 six-flags"")); EXPECT_FALSE(phone_util_.IsAlphaNumber(""18 six-flags"")); EXPECT_FALSE(phone_util_.IsAlphaNumber(""1800 123-1234 extension: 1234"")); EXPECT_FALSE(phone_util_.IsAlphaNumber(""+800 1234-1234"")); } } // namespace phonenumbers } // namespace i18n ",premium_number 118,"#include ""precomp.h"" #include ""gtools.h"" #include ""stdarg.h"" PList::PList() { m_pHead = m_pTail = 0; m_lCount = 0; } PList::~PList() { DeleteContents(); } bool PList::DeleteContents() { while( m_pHead ) { PNode* pNext = m_pHead->m_pNext; m_pHead->m_pNext = 0; delete m_pHead; m_pHead = pNext; } m_pHead = m_pTail = 0; m_lCount = 0; return true; } bool PList::RemoveContents() { while( m_pHead ) { PNode* pNext = m_pHead->m_pNext; m_pHead->m_pNext = m_pHead->m_pPrevious = 0; m_pHead = pNext; } m_pHead = m_pTail = 0; m_lCount = 0; return true; } bool PList::Contains( PNode* p ) { bool [MASK] = false; if( p != 0 ) { for( PNode* q = m_pHead; q; q = q->m_pNext ) { if( q == p ) { [MASK] = true; break; } } } return [MASK] ; } bool PList::AddHead( PNode* p ) { p->m_pPrevious = 0; m_lCount++; if( !m_pHead ) { m_pHead = m_pTail = p; p->m_pNext = 0; } else { p->m_pNext = m_pHead; m_pHead->m_pPrevious = p; m_pHead = p; } return true; } bool PList::AddTail( PNode* p ) { if( !m_pTail ) { m_pHead = m_pTail = p; p->m_pNext = 0; m_lCount = 1; } else { m_lCount++; p->m_pNext = 0; p->m_pPrevious = m_pTail; m_pTail->m_pNext = p; m_pTail = p; } return true; } bool PList::InsertBefore( PNode* p, PNode* q ) { if( !q ) return AddTail( p ); if( !q->m_pPrevious ) return AddHead( p ); ++m_lCount; p->m_pPrevious = q->m_pPrevious; p->m_pPrevious->m_pNext = p; q->m_pPrevious = p; p->m_pNext = q; return true; } bool PList::InsertAfter( PNode* p, PNode* q ) { if( !q ) return AddHead( p ); if( !q->m_pNext ) return AddTail( p ); return InsertBefore( p, q->m_pNext ); } void PList::Delete( PNode* p ) { Remove( p ); delete p; } void PList::Remove( PNode* p ) { m_lCount--; if( m_pHead == p ) m_pHead = p->m_pNext; if( m_pTail == p ) m_pTail = p->m_pPrevious; if( p->m_pNext ) p->m_pNext->m_pPrevious = p->m_pPrevious; if( p->m_pPrevious ) p->m_pPrevious->m_pNext = p->m_pNext; p->m_pNext = p->m_pPrevious = 0; } bool PList::IsEmpty() { return m_pHead ? true : false; } PNode* PList::Find( long lZeroBasedIndex ) { long lIndex = 0; for( PNode* p = m_pHead; p; p = p->m_pNext ) if( lIndex++ == lZeroBasedIndex ) return p; return 0; } bool PList::Merge( PList& s ) { while( s.m_pHead ) { PNode* pNode = s.m_pHead; s.Remove( s.m_pHead ); AddTail( pNode ); } return true; } // reduce if your crap OS cannot handle tit - it ;( #define BUFFERSIZE_FOR_SPRINTF 10480 PString::PString() { m_iStringLength = 0; m_lpszData = 0; } inline void PString::CopyStringData(const char* lpszFrom) { if( lpszFrom ) { m_iStringLength = strlen( lpszFrom )+1; if( m_iStringLength < sizeof(m_szFixedBuffer) ) { m_lpszData = m_szFixedBuffer; strcpy( m_lpszData, lpszFrom ); } else if( m_iStringLength > 0 ) { m_lpszData = new char[ m_iStringLength ]; if( m_lpszData != 0 ) strcpy( m_lpszData, lpszFrom ); else m_iStringLength = 0; } else m_lpszData = 0; } else { m_lpszData = 0; m_iStringLength = 0; } } inline void PString::DeleteStringData() { if( (m_lpszData != m_szFixedBuffer) && m_lpszData ) delete m_lpszData; m_lpszData = 0; m_iStringLength = 0; } PString::PString( const char* lpszArgument ) { CopyStringData( lpszArgument ); } PString::PString( const PString& objectSrc ) { CopyStringData( objectSrc.m_lpszData ); } PString::PString( int, const char* szFormat, ... ) { if( szFormat ) { char buffer[BUFFERSIZE_FOR_SPRINTF]; va_list argptr; va_start( argptr, szFormat ); ::vsprintf(buffer,szFormat,argptr); buffer[BUFFERSIZE_FOR_SPRINTF-1]=0; CopyStringData( buffer ); } else { m_iStringLength = 0; m_lpszData = 0; } } PString::~PString() { DeleteStringData(); } void PString::sprintf( const char* szFormat, ... ) { DeleteStringData(); m_lpszData = 0; m_iStringLength = 0; if( szFormat ) { char buffer[BUFFERSIZE_FOR_SPRINTF]; va_list argptr; va_start( argptr, szFormat ); ::vsprintf(buffer,szFormat,argptr); buffer[BUFFERSIZE_FOR_SPRINTF-1]=0; CopyStringData( buffer ); } } void PString::vsprintf( const char* szFormat, va_list args ) { DeleteStringData(); m_lpszData = 0; m_iStringLength = 0; if( szFormat ) { char buffer[BUFFERSIZE_FOR_SPRINTF]; ::vsprintf(buffer,szFormat,args); buffer[BUFFERSIZE_FOR_SPRINTF-1]=0; CopyStringData( buffer ); } } PString& PString::operator=( const char* objectSrc ) { if( objectSrc != m_lpszData ) { DeleteStringData(); CopyStringData( objectSrc ); } return *this; } PString& PString::operator=( PString& objectSrc ) { if( this != &objectSrc ) { DeleteStringData(); CopyStringData( objectSrc.m_lpszData ); } return *this; } ",bSuccess 119,"// // Created by rcala on 24-07-2023. // #include #include ""../include/main_window.h"" #include using namespace Gtk; MainWindow::MainWindow() { error = 0; set_size_request(500, 500); set_resizable(false); set_border_width(10); set_position(WIN_POS_CENTER); set_title(""Hotel List""); model = ListStore::create(columns); tree.set_model(model); std::string line, fich_image; Glib::RefPtr original_image; std::ifstream [MASK] ; [MASK] .open(""../data/lista.txt""); if( [MASK] .is_open()) { while(getline( [MASK] , line)) { if(line.substr(0, 1) == ""#"") { break; } std::cout << line << std::endl; TreeModel::Row row = *(model->append()); row[columns.col_id] = stoi(line.substr(0,3)); auto num_char = line.length(); row[columns.col_name] = line.substr(6, num_char - 7); fich_image = ""../data/stars/"" + line.substr(4,1) + "".png""; original_image = Gdk::Pixbuf::create_from_file(fich_image); row[columns.col_stars] = original_image->scale_simple(200,40,Gdk::INTERP_BILINEAR); } [MASK] .close(); tree.append_column(""ID"", columns.col_id); tree.append_column(""Name"", columns.col_name); tree.append_column(""Stars"", columns.col_stars); tree.set_headers_clickable(true); std::cout << tree.get_n_columns() << std::endl; scroll.add(tree); add(scroll); show_all_children(); } else { MessageDialog m_dialog(""Error, when tryed to open the file!"", false, MESSAGE_ERROR, BUTTONS_OK); m_dialog.set_transient_for(*this); auto response = m_dialog.run(); if(response == BUTTONS_OK) { set_error(1); exit(0); } } } int MainWindow::get_error() { return error; } void MainWindow::set_error(int _error) { error = _error; } ",input_file 120,"#include #include #include using namespace std; #include ""admin.h"" #include ""../../Core/Source/Core/Core.h"" #include ""../../Core/Utils/utils.h"" void Admin::clients() { bool running = true; while (running) { ui.clearScreen(); ui.displayHeader(""Admin Clients View""); string options[] = {""Show all Clients"", ""Delete Client""}; ui.displayMenu(options, 2); int choice = ui.getInput(""Enter choice""); switch (choice) { case 1: client.showAllClients(); break; case 2: client.deleteClient(); break; case 0: return; default: ui.displayError(""Invalid choice""); break; } } } void Admin::coffeeModule() { bool running = true; while (running) { ui.clearScreen(); ui.displayHeader(""Admin Coffee View""); string options[] = {""Show all Coffee"", ""Add Coffee"", ""Delete Coffee""}; ui.displayMenu(options, 3); int choice = ui.getInput(""Enter choice""); switch (choice) { case 1: coffObj.displayAllCoffee(); break; case 2: coffObj.createCoffee(); break; case 3: coffObj.deleteCoffee(); break; case 0: return; default: ui.displayError(""Invalid choice""); break; } } } void Admin::settings() { Registration reg(""Core/Source/Files/admins.txt""); bool running = true; while (running) { ui.clearScreen(); ui.displayHeader(""Admin Settings View""); string options[] = {""Add New Admin"", ""LogOut""}; ui.displayMenu(options, 2); int choice = ui.getInput(""Enter choice""); switch (choice) { case 1: reg.signup(""Admins Database Records""); break; case 2: reg.logOut(); break; case 0: return; default: ui.displayError(""Invalid choice""); break; } } } void Admin::run() { Registration reg(""Core/Source/Files/admins.txt""); bool [MASK] = false; while (! [MASK] ) { ui.clearScreen(); ui.displayHeader(""Admin Module""); string options[] = {""SignUp"", ""Login""}; ui.displayMenu(options, 2); int choice = ui.getInput(""Enter choice""); switch (choice) { case 1: reg.signup(""Admins Database Records""); break; case 2: if (reg.login()) { [MASK] = true; } break; case 0: return; default: ui.displayError(""Invalid choice""); break; } } bool running = true; while (running) { ui.clearScreen(); ui.displayHeader(""Admin Dashboard""); string options[] = {""Clients"", ""Coffee"", ""Settings""}; ui.displayMenu(options, 3); int choice = ui.getInput(""Enter choice""); switch (choice) { case 1: clients(); break; case 2: coffeeModule(); break; case 3: settings(); break; case 0: return; default: ui.displayError(""Invalid choice""); break; } } } ",loggedIn 121,"#include ""App.h"" using namespace std; App *app; App::App(QObject *parent) : QObject(parent) { connect(this, &App::error, this, &App::errorSlot); connect(this, &App::reportError, this, &App::showErrorDilogSlot); connect(this, &App::reportErrorMsg, this, &App::errorMsgSlot); ioThread_.setObjectName(""io thread""); connect(qApp, &QCoreApplication::aboutToQuit, [&](){ ioThread_.quit(); ioThread_.wait(); }); ioThread_.start(); downloader_.moveToThread(&ioThread_); //auto screen = QGuiApplication::primaryScreen(); //hmm_ = screen->physicalDotsPerInchX() / 25.4; //vmm_ = screen->physicalDotsPerInchY() / 25.4; } void App::addToolButton(QWidget *parent, QBoxLayout *l, QAction *a) { auto b = new QToolButton(parent); b->setAutoRaise(true); //float w = 4*hmm_; //float h = 4*hmm_; b->setDefaultAction(a); //b->setIconSize(QSize(w, h)); if (a->menu()){ b->setPopupMode(QToolButton::InstantPopup); //w += 2.5f*hmm_; } //b->setFixedSize(QSize(w, h)); l->addWidget(b); } void App::addToolBoxSpacer(QBoxLayout *l) { //l->addSpacing(2 * hmm_); l->addSpacing(2); } void BuildErrorMsg(const std::exception& e, QString &msg){ msg += QString::fromUtf8(e.what()); msg += '\n'; try { std::rethrow_if_nested(e); } catch(const std::exception& e) { BuildErrorMsg(e, msg); } catch(...) { msg += QApplication::translate(""Sadly, I don't even know what the error is."",""message about happened error""); } } QString App::errorMessage(std::exception_ptr eptr, const QString &action) { QString msg; msg.reserve(2000); msg += action; msg += '\n'; try { std::rethrow_exception(eptr); } catch(const std::exception& e) { BuildErrorMsg(e, msg); } return msg; } void App::showErrorDilogSlot(std::exception_ptr eptr, const QString &action) { errorMsgSlot(errorMessage(eptr, action)); } void App::errorSlot(std::exception_ptr e) { showErrorDilogSlot(e); if (!isRecoverable(e)) QCoreApplication::exit(1); } void App::errorMsgSlot(const QString &e) { QMessageBox [MASK] ; [MASK] .setText(tr(""Error:"",""dialog about happened error"")); [MASK] .setInformativeText(e); [MASK] .exec(); } QString GetResourceString(const char *res) { QFile file(res); file.open(QFile::ReadOnly); return QString(file.readAll()); } ",msgBox 122,"// // Created by Ruslan on 08.04.2024. // // TODO: remove '#include ' #include #include class ErrorData__ { public: std::string name; std::string message; std::string filename; std::string filepath; int line; ErrorData__(std::string const message, std::string const filename, std::string const filepath, int const line) { this->name = message; this->message = message; this->filename = filename; this->filepath = filepath; this->line = line; } ~ErrorData__() { } }; class MessageErrorData__ { public: std::string message; MessageErrorData__(std::string const message) { this->message = message; } ~MessageErrorData__() { } }; class Error__ : public Root__ { public: Error__( std::string const subtype, std::string const message, std::string const filename, std::string const filepath, std::optional const code_, std::optional const line_) : Root__(""error"", subtype, new ErrorData__(message, filename, filepath, line_.value_or(-1)), code_.value_or(-1)) { } ~Error__() { } }; class MessageError__ { public: /** exit | error | success */ std::string type; /** compilation | runtime */ std::string subtype; /** -1 - unknown */ int code; std::string message; std::string mapCode; std::string printable() { return std::string(""MessageError {\n type: \""error\"",\n subtype: \""runtime\"",\n message: \"""") + message + std::string(""\"",\n mapCode: \"""") + mapCode + std::string(""\"",\n code: "") + std::to_string(code) + std::string(""\n}""); } MessageError__( std::string const message, std::optional const [MASK] , std::optional const code_) { const std::string mapCode = [MASK] .value_or(""-1""); const int code = code_.value_or(2); this->type = ""error""; this->subtype = ""runtime""; this->message = message; this->mapCode = mapCode; this->code = code; } ~MessageError__() { } }; ",mapCode_ 123,"//------------------------------------------------------------------------------ //! \file AudioFiles.cpp //! classes representing audio files //! \project ARA SDK Examples //! \copyright Copyright (c) 2018-2025, Celemony Software GmbH, All Rights Reserved. //! \license 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 ""AudioFiles.h"" #include ""ARA_API/ARAAudioFileChunks.h"" #include ""ARA_Library/Utilities/ARASamplePositionConversion.h"" #include ""ExamplesCommon/SignalProcessing/PulsedSineSignal.h"" #include ""3rdParty/pugixml/src/pugixml.hpp"" #include ""3rdParty/cpp-base64/base64.h"" #include #include #include /*******************************************************************************/ class ARAiXMLChunk { public: ARAiXMLChunk () : ARAiXMLChunk { 0, nullptr } {} ARAiXMLChunk (size_t dataLength, const uint8_t data[]) { if (dataLength) { _iXMLChunk.load_buffer (data, dataLength); // enable this to log chunk data without parsing //_iXMLChunk.save (std::cout); } auto iXMLNode { _iXMLChunk.child (""BWFXML"") }; if (iXMLNode.empty ()) iXMLNode = _iXMLChunk.append_child (""BWFXML""); auto araNode { iXMLNode.child (ARA::kARAXMLName_ARAVendorKeyword) }; if (araNode.empty ()) araNode = iXMLNode.append_child (ARA::kARAXMLName_ARAVendorKeyword); _audioSourceArchives = araNode.child (ARA::kARAXMLName_AudioSources); if (_audioSourceArchives.empty ()) _audioSourceArchives = araNode.append_child (ARA::kARAXMLName_AudioSources); } std::string getAudioSourceData (const std::string& documentArchiveID, bool& openAutomatically, std::string& plugInName, std::string& plugInVersion, std::string& manufacturer, std::string& informationURL, std::string& persistentID) const { pugi::xml_node archive; for (const auto& it : _audioSourceArchives.children (ARA::kARAXMLName_AudioSource)) { if (std::strcmp (it.child_value (ARA::kARAXMLName_DocumentArchiveID), documentArchiveID.c_str ()) == 0) { archive = it; break; } } if (archive.empty ()) { openAutomatically = false; plugInName = plugInVersion = manufacturer = informationURL = persistentID = {}; return {}; } openAutomatically = (std::strcmp (archive.child_value (ARA::kARAXMLName_OpenAutomatically), ""true"") == 0); const auto suggestedPlugIn { archive.child (ARA::kARAXMLName_SuggestedPlugIn) }; plugInName = suggestedPlugIn.child_value (ARA::kARAXMLName_PlugInName); plugInVersion = suggestedPlugIn.child_value (ARA::kARAXMLName_LowestSupportedVersion); manufacturer = suggestedPlugIn.child_value (ARA::kARAXMLName_ManufacturerName); informationURL = suggestedPlugIn.child_value (ARA::kARAXMLName_InformationURL); persistentID = archive.child_value (ARA::kARAXMLName_PersistentID); #if __cplusplus >= 201703L return base64_decode (std::string_view { archive.child_value (ARA::kARAXMLName_ArchiveData) }, true); #else return base64_decode (archive.child_value (ARA::kARAXMLName_ArchiveData), true); #endif } void setAudioSourceData (const std::string& documentArchiveID, bool openAutomatically, const std::string& plugInName, const std::string& plugInVersion, const std::string& manufacturer, const std::string& informationURL, const std::string& persistentID, const std::string& data) { pugi::xml_node archive; for (const auto& it : _audioSourceArchives.children (ARA::kARAXMLName_AudioSource)) { if (std::strcmp (it.child_value (ARA::kARAXMLName_DocumentArchiveID), documentArchiveID.c_str ()) == 0) { archive = it; break; } } if (archive.empty ()) archive = _audioSourceArchives.append_child (ARA::kARAXMLName_AudioSource); else archive.remove_children (); archive.append_child (ARA::kARAXMLName_DocumentArchiveID).append_child (pugi::node_pcdata).set_value (documentArchiveID.c_str ()); archive.append_child (ARA::kARAXMLName_OpenAutomatically).append_child (pugi::node_pcdata).set_value ((openAutomatically) ? ""true"" : ""false""); auto suggestedPlugIn { archive.append_child (ARA::kARAXMLName_SuggestedPlugIn) }; suggestedPlugIn.append_child (ARA::kARAXMLName_PlugInName).append_child (pugi::node_pcdata).set_value (plugInName.c_str ()); suggestedPlugIn.append_child (ARA::kARAXMLName_LowestSupportedVersion).append_child (pugi::node_pcdata).set_value (plugInVersion.c_str ()); suggestedPlugIn.append_child (ARA::kARAXMLName_ManufacturerName).append_child (pugi::node_pcdata).set_value (manufacturer.c_str ()); suggestedPlugIn.append_child (ARA::kARAXMLName_InformationURL).append_child (pugi::node_pcdata).set_value (informationURL.c_str ()); archive.append_child (ARA::kARAXMLName_PersistentID).append_child (pugi::node_pcdata).set_value (persistentID.c_str ()); std::string encodedArchiveData { base64_encode (data) }; archive.append_child (ARA::kARAXMLName_ArchiveData).append_child (pugi::node_pcdata).set_value (encodedArchiveData.c_str ()); // enable this to log edited chunk data //_iXMLChunk.save (std::cout); } std::string getData () const { std::ostringstream writer; _iXMLChunk.save (writer); return writer.str (); } private: pugi::xml_document _iXMLChunk; pugi::xml_node _audioSourceArchives; }; /*******************************************************************************/ void AudioFileBase::setiXMLChunk (ARAiXMLChunk* chunk) noexcept { delete _iXMLChunk; _iXMLChunk = chunk; } void AudioFileBase::setiXMLARAAudioSourceData (const std::string& documentArchiveID, bool openAutomatically, const std::string& plugInName, const std::string& plugInVersion, const std::string& manufacturer, const std::string& informationURL, const std::string& persistentID, const std::string& data) { if (!_iXMLChunk) _iXMLChunk = new ARAiXMLChunk {}; _iXMLChunk->setAudioSourceData (documentArchiveID, openAutomatically, plugInName, plugInVersion, manufacturer, informationURL, persistentID, data); } std::string AudioFileBase::getiXMLARAAudioSourceData (const std::string& documentArchiveID, bool& openAutomatically, std::string& plugInName, std::string& plugInVersion, std::string& manufacturer, std::string& informationURL, std::string& persistentID) { if (!_iXMLChunk) { openAutomatically = false; plugInName = plugInVersion = manufacturer = informationURL = persistentID = {}; return {}; } return _iXMLChunk->getAudioSourceData (documentArchiveID, openAutomatically, plugInName, plugInVersion, manufacturer, informationURL, persistentID); } /*******************************************************************************/ SineAudioFile::SineAudioFile (const std::string& name, double [MASK] , double sampleRate, int32_t channelCount) : SineAudioFile { name, ARA::samplePositionAtTime ( [MASK] , sampleRate), sampleRate, channelCount } {} SineAudioFile::SineAudioFile (const std::string& name, int64_t sampleCount, double sampleRate, int32_t channelCount) : AudioFileBase { name }, _sampleCount { sampleCount }, _sampleRate { sampleRate }, _channelCount { channelCount } {} bool SineAudioFile::readSamples (int64_t samplePosition, int64_t samplesPerChannel, void* const buffers[], bool use64BitSamples) noexcept { RenderPulsedSineSignal (samplePosition, getSampleRate (), getSampleCount (), getChannelCount (), samplesPerChannel, buffers, use64BitSamples); return true; } bool SineAudioFile::saveToFile (const std::string& path) { // first we copy our sample data to a new icstdsp::AudioFile icstdsp::AudioFile audioFile; audioFile.Create (static_cast (getSampleCount ()), static_cast (getChannelCount ()), static_cast (getSampleRate () + 0.5)); std::vector audioSampleBuffers; for (auto c { 0 }; c < getChannelCount (); c++) audioSampleBuffers.push_back (audioFile.GetSafePt (static_cast (c))); readSamples (0, getSampleCount (), reinterpret_cast (audioSampleBuffers.data ()), false); // if we have iXML data, we copy that into the icstdsp::AudioFile too if (auto iXMLChunk { getiXMLChunk () }) { const auto data { iXMLChunk->getData () }; audioFile.SetiXMLData (reinterpret_cast (data.c_str ()), static_cast (data.size ())); } // now we create an AudioDataFile from that, copy over the iXML and store it return AudioDataFile { {}, std::move (audioFile) }.saveToFile (path); } /*******************************************************************************/ AudioDataFile::AudioDataFile (const std::string& name, icstdsp::AudioFile&& audioFile) : AudioFileBase { name }, _audioFile { std::move (audioFile) } { unsigned int dataLength { 0 }; auto data = _audioFile.GetiXMLData (&dataLength); if ((data != nullptr) && (dataLength > 0)) setiXMLChunk (new ARAiXMLChunk { dataLength, data}); } bool AudioDataFile::readSamples (int64_t samplePosition, int64_t samplesPerChannel, void* const buffers[], bool use64BitSamples) noexcept { auto index { 0L }; while (samplesPerChannel--) { for (auto i { 0 }; i < getChannelCount (); ++i) { auto value = _audioFile.GetSafePt (static_cast (i))[samplePosition]; if (use64BitSamples) static_cast (buffers[i])[index] = value; else static_cast (buffers[i])[index] = static_cast (value); } ++samplePosition; ++index; } return true; } bool AudioDataFile::saveToFile (const std::string& path) { if (auto iXMLChunk { getiXMLChunk () }) { const auto data { iXMLChunk->getData () }; _audioFile.SetiXMLData (reinterpret_cast (data.c_str ()), static_cast (data.size ())); } auto validatedPath { path }; const auto extension { (path.length () < 4) ? """" : path.substr (path.length () - 4) }; if ((extension != "".wav"") && (extension != "".aif"")) validatedPath += "".wav""; return (_audioFile.SaveWave (validatedPath.c_str ()) == 0); } ",duration 124,"#include ""Grove_I2C_Motor_Driver.h"" #define I2C_ADDRESS 0x0f int echo = 0; int echodroit = 0; int echogauche = 0; long readUltrasonicDistance(int triggerPin, int [MASK] ) { pinMode(triggerPin, OUTPUT); // Clear the trigger digitalWrite(triggerPin, LOW); delayMicroseconds(2); digitalWrite(triggerPin, HIGH); delayMicroseconds(10); digitalWrite(triggerPin, LOW); pinMode( [MASK] , INPUT); return pulseIn( [MASK] , HIGH); } void setup() { Motor.begin(I2C_ADDRESS); pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(10, OUTPUT); digitalWrite(10, LOW); } void loop() { echo = 0.01723 * readUltrasonicDistance(6, 5); echodroit = 0.01723 * readUltrasonicDistance(4, 3); echogauche = 0.01723 * readUltrasonicDistance(2, 1); if (echo <= 10 ) { Motor.stop(MOTOR1); Motor.stop(MOTOR2); Motor.speed(MOTOR1,-100); Motor.speed(MOTOR2, -100); delay(300); Motor.stop(MOTOR1); Motor.stop(MOTOR2); delay(2000); if (echogauche < 20) { Motor.speed(MOTOR1,-100); Motor.speed(MOTOR2, 100); }else{ Motor.stop(MOTOR1); Motor.stop(MOTOR2); Motor.speed(MOTOR1,100); Motor.speed(MOTOR2, 100); delay(300); Motor.stop(MOTOR1); Motor.stop(MOTOR2); delay(1000); } } else { Motor.speed(MOTOR1,-100); Motor.speed(MOTOR2, 100); } } ",echoPin 125,"// // Created by 21911 on 24-8-20. // // // Created by 21911 on 2024/8/13. // #include #define eps 1e-8 //多2 #define inf 0x3f3f3f3f #define PI acos(-1) //π #define f0n(i,n) for (int (i)=0;(i)< (n);(i)++) #define f1n(i,n) for (int (i)=1;(i)<=(n);(i)++) using namespace std; // unordered_map HASH,与时间戳相关,防止HACK struct HASH { static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } static size_t get(const uint64_t x) { static const uint64_t [MASK] = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + [MASK] ); } template size_t operator()(T x) const { return get(std::hash()(x)); } template size_t operator()(pair p) const { return get(std::hash()(p.first) ^ std::hash()(p.second)); } }; typedef long long ll; typedef pair PII; typedef pair PLL; int TEST; //测试案例数 const int N = 1e5+5; //数组长度 //int a[N]; int n, m, k; // int a, b, c; // unordered_map mp; // unordered_map, int, HASH> mp2; void solve() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); // ll res = 0; // ########## wirte your code here ########### // 每一颗苹果最多切 30 次,因为 m <= 1e9,如果切 30 次都不能平分,再切下去也无法平分 // 所以可以一边切一边分,1 1/2 1/4 1/8 ... ll n, m; int cnt = 0; cin >> n >> m; if(n % m == 0) cout << 0 << endl; else { n %= m; ll res = 0; while(true) { cnt ++; res += n; n *= 2; if(n % m == 0) break; n %= m; if(cnt > 31) break; } if(cnt == 32) cout << -1 << endl; else cout << res << endl; } // ############################################ // cout << res << endl; } int main(void) { // freopen(""out.txt"", ""w"", stdout); ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); TEST = 1; cin >> TEST; while(TEST--) solve(); return 0; }",FIXED_RANDOM 126,"// Copyright 2021 Metromotive #include ""HX711.hpp"" namespace metromotive { // Creates a new HX711 object with the default gain. HX711::HX711(DigitalOut *clockPin, InterruptIn *dataPin, void (*onRead)(int32_t reading)) : clockPin(clockPin), dataPin(dataPin), onRead(onRead) { lastSampleGain = x128; gain = x128; this->stop(); } // Powers up the HX711 and begins listening for readings. void HX711::start() { dataPin->fall(callback(this, &HX711::read)); clockPin->write(0); } // Powers down the HX711. void HX711::stop() { dataPin->fall(NULL); clockPin->write(1); } void HX711::read() { // Data pin will fall repeatedly, so ignore it during read. dataPin->disable_irq(); uint32_t [MASK] = 0; // Can't interrupt this section for more than 60us __disable_irq(); // Cycle 24 times to read value. for (int i = 0; i < 24; i++) { clockPin->write(1); [MASK] = [MASK] << 1; wait_ns(10); clockPin->write(0); [MASK] |= dataPin->read(); wait_ns(10); } // Cycle 1 to 3 more times to set next time's gain. for (int i = 0; i < gain; i++) { clockPin->write(1); wait_ns(25); clockPin->write(0); } __enable_irq(); // Only report result if gain/input matches requested gain/input. if (lastSampleGain == gain) { // Convert unsigned 24-bit 2's complement to 32 bit signed. int32_t result = ((int32_t)( [MASK] << 8)) >> 8; onRead(result); } // Next read will have the gain requested during this read. lastSampleGain = gain; dataPin->enable_irq(); } } // namespace metromotive",count 127,"#include""stdio.h"" #include""stdlib.h"" #include""string.h"" #include""Define.h"" //建立先序二叉树 Status CreateBiTree(BiTree &T) { TElemType ch; scanf(""%c"",&ch); if(ch=='#') T=NULL; else{ if(!(T=(BiTNode *)malloc(sizeof(BiTNode)))) exit(OVERFLOW); T->data=ch; CreateBiTree(T->lchild); CreateBiTree(T->rchild); } return OK; } //先序遍历二叉树 Status PreOrderTraverse(BiTree T,Status (*visit)(TElemType e)){ if(!T) return ERROR; else{ visit(T->data); PreOrderTraverse(T->lchild,visit); PreOrderTraverse(T->rchild,visit); } return OK; } //中序遍历二叉树 Status InOrderTraverse(BiTree T,Status (*visit)(TElemType e)){ if(!T) return ERROR; else{ InOrderTraverse(T->lchild,visit); visit(T->data); InOrderTraverse(T->rchild,visit); } return OK; } //后序遍历二叉树 Status PostOrderTraverse(BiTree T,Status (*visit)(TElemType e)){ if(!T) return ERROR; else{ PostOrderTraverse(T->lchild,visit); PostOrderTraverse(T->rchild,visit); visit(T->data); } return OK; } Status PrintTElement(TElemType e){ printf(""%c"",e); return OK; } Status Depth(BiTree T){ int depthval, [MASK] ,depthright; if(!T) depthval=0; else{ [MASK] =Depth(T->lchild); depthright=Depth(T->rchild); depthval=1+( [MASK] >depthright? [MASK] :depthright); } return depthval; } Status Countleaf(BiTree T){ int leafnum; if(!T) leafnum=0; else{ leafnum=Countleaf(T->lchild)+Countleaf(T->rchild); } return leafnum; } Status Count(BiTree T){ int num=0,num1=0,num2=0; if(!T) num=0; else{ num1=Count(T->lchild); num2=Count(T->rchild); num=1+num1+num2; } return num; } Status Counttwo(BiTree T){ int num=0,num1=0,num2=0; if(!T) num=0; else if(T->lchild && T->rchild){ num=1; num1=Counttwo(T->lchild); num2=Counttwo(T->rchild); num+=num1+num2; } return num; } Status Countone(BiTree T){ if(!T) return 0; else if(!T->lchild && T->rchild){ return Countone(T->rchild)+1; } else if(T->lchild && !T->rchild){ return Countone(T->lchild)+1; } else{ return Countone(T->lchild)+Countone(T->rchild); } } ",depthleft 128,"#ifndef CAMERA_H #define CAMERA_H #include ""rtweekend.h"" #include ""hittable.h"" #include ""material.h"" class camera { public: double aspect_ratio = 1.0; // 渲染图宽高比 int image_width = 100; // 渲染图像素宽度 int image_height; // 渲染图高度 int samples_per_pixel = 10; //每采样点随机采样点数 int max_depth = 10; // 限制最大递归深度 double vfov = 90; //垂直fov point3 lookfrom = point3(0,0,0); point3 lookat = point3(0,0,-1); //相机朝向 vec3 vup = vec3(0,1,0); //相机直立空间向上坐标 double defocus_angle = 0; // 光线变化角度 double focus_dist = 10; // 点到焦点平面距离 void render(const hittable& world) { initialize(); std::cout << ""P3\n"" << image_width << ' ' << image_height << ""\n255\n""; for (int j = 0; j < image_height; j++) { std::clog << ""\rScanlines remaining: "" << (image_height - j) << ' ' << std::flush; for (int i = 0; i < image_width; i++) { color pixel_color(0,0,0); for (int sample = 0; sample < samples_per_pixel; sample++) { ray r = get_ray(i, j); pixel_color += ray_color(r, max_depth, world); } write_color(std::cout, pixel_samples_scale * pixel_color); } } std::clog << ""\rDone. \n""; } private: double pixel_samples_scale; //采样颜色比例因子 point3 center; // 相机坐标 point3 pixel00_loc; // 屏幕像素原点位置 vec3 pixel_delta_u; // 像素向右偏移量 vec3 pixel_delta_v; // 像素向下偏移量 vec3 u, v, w; //相机空间基坐标 vec3 defocus_disk_u; // 散焦盘水平半径 vec3 defocus_disk_v; // 散焦盘垂直半径 void initialize() { image_height = int(image_width / aspect_ratio); image_height = (image_height < 1) ? 1 : image_height; pixel_samples_scale = 1.0 / samples_per_pixel; center = lookfrom; // 视窗尺寸计算 auto theta = degrees_to_radians(vfov); auto h = std::tan(theta/2); auto viewport_height = 2 * h * focus_dist; auto viewport_width = viewport_height * (double(image_width)/image_height); // 计算摄像机基坐标 w = unit_vector(lookfrom - lookat); u = unit_vector(cross(vup, w)); v = cross(w, u); // 计算横跨水平视图和纵向视图边缘的向量。 vec3 viewport_u = viewport_width * u; vec3 viewport_v = viewport_height * -v; // 计算从像素水平和垂直增量向量。 pixel_delta_u = viewport_u / image_width; pixel_delta_v = viewport_v / image_height; // 计算左上像素的位置。 auto viewport_upper_left = center - (focus_dist * w) - viewport_u/2 - viewport_v/2; pixel00_loc = viewport_upper_left + 0.5 * (pixel_delta_u + pixel_delta_v); // 计算相机离焦盘的基向量。 auto [MASK] = focus_dist * std::tan(degrees_to_radians(defocus_angle / 2)); defocus_disk_u = u * [MASK] ; defocus_disk_v = v * [MASK] ; } ray get_ray(int i, int j) const { //构造一个摄像机光线,从原点出发,获取到像素位置 i,j 周围的随机射线。 auto offset = sample_square(); auto pixel_sample = pixel00_loc + ((i + offset.x()) * pixel_delta_u) + ((j + offset.y()) * pixel_delta_v); auto ray_origin = (defocus_angle <= 0) ? center : defocus_disk_sample(); auto ray_direction = pixel_sample - ray_origin; return ray(ray_origin, ray_direction); } vec3 sample_square() const { // 返回 [-.5,+.5] 之间的随机坐标 return vec3(random_double() - 0.5, random_double() - 0.5, 0); } point3 defocus_disk_sample() const { auto p = random_in_unit_disk(); return center + (p[0] * defocus_disk_u) + (p[1] * defocus_disk_v); } color ray_color(const ray& r, int depth, const hittable& world) const { if (depth <= 0) return color(0,0,0); hit_record rec; if (world.hit(r, interval(0.001, infinity), rec)) { ray scattered; color attenuation; if (rec.mat->scatter(r, rec, attenuation, scattered)) return attenuation * ray_color(scattered, depth-1, world); return color(0,0,0); } vec3 unit_direction = unit_vector(r.direction()); auto a = 0.5*(unit_direction.y() + 1.0); return (1.0-a)*color(1.0, 1.0, 1.0) + a*color(0.5, 0.7, 1.0); } }; #endif",defocus_radius 129,"#include ""ccontroller.hpp"" #include #include CController::CController(int pin_num, float threshold_percent, int midi_cc_num) { pin = pin_num; pinMode(pin, INPUT); _last_reading = analogRead(pin); _delta_threshold = round(4096*threshold_percent/100); _midi_cc_num = midi_cc_num; } CController::CController(int pin_num, float threshold_percent) : CController(pin_num, threshold_percent, 0) {} int CController::poll() { int [MASK] = analogRead(pin); if (abs( [MASK] -_last_reading) > _delta_threshold) { on_change( [MASK] ); _last_reading = [MASK] ; return 1; } else { return 0; } } int CController::poll(unsigned int sample_period_micro) { if ((micros()-_last_sample_time) > sample_period_micro) { _last_sample_time = micros(); return poll(); } else { return 0; } } int CController::get_cc_num() { return _midi_cc_num; } void CController::set_cc_num(int new_cc_num) { _midi_cc_num = new_cc_num; } void CController::on_change(int controller_input) {}",cur_reading 130," #include ""DFA.hpp"" DFA::DFA() { /* Initial DFA state */ this->s_state = make_vertex(); this->state = s_state; this->invalid = false; } bool DFA::set_start(int [MASK] ) { if(!valid( [MASK] )) return false; if(state != s_state) return false; s_state = [MASK] ; state = [MASK] ; return true; } bool DFA::peek(char c) { if(invalid) return false; for(auto edge : outgoing(state)) { if(edge.get_weight() == c) return true; } return false; } bool DFA::at_accept() { return accept.find(state) != accept.end(); } void DFA::consume(char c) { if(invalid) return; for(auto edge : outgoing(state)) { if(edge.get_weight() == c) { state = edge.get_dest(); current += c; return; } } invalid = true; } std::unique_ptr DFA::get_data() { return std::make_unique(current); } bool DFA::add_accept(int state) { if(!valid(state)) return false; return accept.insert(state).second; } void DFA::reset() { state = s_state; current.clear(); } int DFA::curr_state() { return state; } ",n_start 131,"#include #include ""AIEngine.hh"" AiEngine::AiEngine(ConfigEngine *data) : _ID(0), _data(data), _updateTime(50), _reactionTime(50) { } AiEngine::AiEngine(const AiEngine &other) { this->setID(other.getID()); this->setData(getData()); this->setUpdateTime(other.getUpdateTime()); this->setReactionTime(other.getReactionTime()); } AiEngine & AiEngine::operator=(const AiEngine &other) { this->setID(other.getID()); this->setData(other.getData()); this->setUpdateTime(other.getUpdateTime()); this->setReactionTime(other.getReactionTime()); return (*this); } AiEngine::~AiEngine() { } void AiEngine::setID(int ID) { this->_ID = ID; } void AiEngine::setData(ConfigEngine *D) { this->_data = D; } void AiEngine::setUpdateTime(int T) { this->_updateTime = T; } void AiEngine::setReactionTime(int R) { this->_reactionTime = R; } int AiEngine::getID() const { return (this->_ID); } int AiEngine::getUpdateTime() const { return (this->_updateTime); } ConfigEngine* AiEngine::getData() const { return (this->_data); } int AiEngine::getReactionTime() const { return (this->_reactionTime); } void AiEngine::resetExplosionArea() { if (!_explosionArea.empty()) _explosionArea.erase(_explosionArea.begin(), _explosionArea.end()); } void AiEngine::resetUnitPosition() { if (!_unitPosition.empty()) _unitPosition.erase(_unitPosition.begin(), _unitPosition.end()); } void AiEngine::update() { int time; time = getUpdateTime(); if (time >= getReactionTime()) { updateExplosionArea(); updateUnitPosition(); setUpdateTime(0); updateBots(); } setUpdateTime(getUpdateTime() + 1); } void AiEngine::updateExplosionArea() { std::list::iterator i; resetExplosionArea(); for (i = _data->listBombs.begin(); i != _data->listBombs.end(); ++i) { calculateArea(posXY((*i)->getX()/400, (*i)->getZ()/400), dynamic_cast(*i)->getPower()); } } void AiEngine::updateUnitPosition() { std::list::iterator i; posXY pos; resetUnitPosition(); pos.X = _data->player1->getX()/400; pos.Y = _data->player1->getZ()/400; _unitPosition.push_back(pos); if (_data->getPlayers() == 2) { pos.X = _data->player2->getX()/400; pos.Y = _data->player2->getZ()/400; _unitPosition.push_back(pos); } for (i = _data->listEnemies.begin(); i != _data->listEnemies.end(); ++i) { pos.X = (*i)->getX()/400; pos.Y = (*i)->getZ()/400; _unitPosition.push_back(pos); } } void AiEngine::updateBots() { std::list::iterator i; Model::Player *bot; posXY pos; for (i = _data->listEnemies.begin(); i != _data->listEnemies.end(); ++i) { bot = dynamic_cast(*i); pos.X = (*i)->getX()/400; pos.Y = (*i)->getZ()/400; if (bot->brain.getAction() == _THINK && !isDifferentCase(pos, bot->brain.getDestination())) { bot->setX(400 * pos.X + 200); bot->setY(400 * pos.Y + 200); } bot->brain.setState(evalState(pos, (bot->getPower() - 1)/2)); bot->brain.setAction(makePlan(pos, bot->brain.getState(), bot->getCurrentCapacity(), (bot->getPower() - 1)/2)); bot->brain.setDestination(pos, bot->brain.getAction()); } } posXY AiEngine::getSafeCase(int X, int Y) { if ((Y - 1 >= 0) && isSafeCase(X, Y - 1)) return posXY(X, Y - 1); if ((X - 1 >= 0) && isSafeCase(X - 1, Y)) return posXY(X - 1, Y); if ((Y + 1 < _data->getMapHeight()) && isSafeCase(X, Y + 1)) return posXY(X, Y + 1); if (X + 1 < _data->getMapWidth() && isSafeCase(X + 1, Y)) return posXY(X + 1, Y); return posXY(-1,-1); } posXY AiEngine::getCase(int X, int Y) { if ((Y - 1 >= 0) && isFreeCase(X, Y - 1)) return posXY(X, Y - 1); if ((X - 1 >= 0) && isFreeCase(X - 1, Y)) return posXY(X - 1, Y); if ((Y + 1 < _data->getMapHeight()) && isFreeCase(X, Y + 1)) return posXY(X, Y + 1); if (X + 1 < _data->getMapWidth() && isFreeCase(X + 1, Y)) return posXY(X + 1, Y); return posXY(-1, -1); } posXY AiEngine::getLeaveCase(int X, int Y) { posXY check; if ((Y - 1 >= 0) && isFreeCase(X, Y - 1)) { check = getSafeCase(X, Y - 1); if (check.X != -1) return posXY(X, Y -1); } if ((X - 1 >= 0) && isFreeCase(X - 1, Y)) { check = getSafeCase(X - 1, Y); if (check.X != -1) return posXY(X - 1, Y); } if ((Y + 1 < _data->getMapHeight()) && isFreeCase(X, Y + 1)) { check = getSafeCase(X, Y + 1); if (check.X != -1) return posXY(X, Y + 1); } if (X + 1 < _data->getMapWidth() && isFreeCase(X + 1, Y)) { check = getSafeCase(X + 1, Y); if (check.X != -1) return posXY(X + 1, Y); } return posXY(-1,-1); } bool AiEngine::isDangerousCase(int X, int Y) { std::list::iterator i; for (i = _explosionArea.begin(); i != _explosionArea.end(); ++i) if (i->X == X && i->Y == Y) return (true); return (false); } bool AiEngine::thereIsNoDanger(int X, int Y) { std::list::iterator i; for (i = _explosionArea.begin(); i != _explosionArea.end(); ++i) { if (((i->X == X) && (i->Y == Y - 1 || i->Y == Y + 1)) || (((i->Y == Y) && (i->X == X - 1 || i->X == X + 1)))) return (false); } return (true); } bool AiEngine::thereIsBonusClose(int X, int Y) { std::list::iterator i; for (i = _data->listBonus.begin(); i != _data->listBonus.end(); ++i) { if (((*i)->getX()/400 == X && ((*i)->getZ()/400 == Y - 1 || (*i)->getZ()/400 == Y + 1)) || ((*i)->getZ()/400 == Y && ((*i)->getX()/400 == X - 1 || (*i)->getX()/400 == X + 1))) return (true); } return (false); } bool AiEngine::thereIsBoxClose(int X, int Y) { std::list::iterator i; for (i = _data->listBoxes.begin(); i != _data->listBoxes.end(); ++i) { if (((*i)->getX()/400 == X && ((*i)->getZ()/400 == Y - 1 || (*i)->getZ()/400 == Y + 1)) || ((*i)->getZ()/400 == Y && ((*i)->getX()/400 == X - 1 || (*i)->getX()/400 == X + 1))) return (true); } return (false); } bool AiEngine::thereIsBombAt(int X, int Y) { std::list::iterator i; for (i = _data->listBombs.begin(); i != _data->listBombs.end(); ++i) { if ((*i)->getX()/400 == X && (*i)->getZ()/400 == Y) return (true); } return (false); } bool AiEngine::thereIsUnit(int X, int Y) { std::list::iterator i; for (i = _unitPosition.begin(); i != _unitPosition.end(); ++i) { if (i->X == X && i->Y == Y) return (true); } return (false); } bool AiEngine::isTouch(int posX, int posY, int cmpX, int cmpY) { if ((posX == cmpX && (posY == cmpY - 1 || posY == cmpY + 1)) || ((posY == cmpY) && (posX == cmpX - 1 || posX == cmpX + 1))) return (true); return (false); } bool AiEngine::isTouch(posXY pos, posXY cmp) { if ((pos.X == cmp.X && (pos.Y == cmp.Y - 1 || pos.Y == cmp.Y + 1)) || ((pos.Y == cmp.Y) && (pos.X == cmp.X - 1 || pos.X == cmp.X + 1))) return (true); return (false); } bool AiEngine::isBox(int X, int Y) { std::map, Case>::iterator i; for (i = _data->map._stock.begin(); i != _data->map._stock.end(); ++i) if (i->first.first == X && i->first.second == Y) return i->second.getType() == BOX; return (false); } bool AiEngine::isSafeCase(int X, int Y) { return isFreeCase(X, Y) && !isDangerousCase(X, Y); } bool AiEngine::thereIsEnemieClose(int X, int Y) { std::list::iterator i; for (i = _unitPosition.begin(); i != _unitPosition.end(); ++i) if (((i->X == X) && (i->Y == Y - 1 || i->Y == Y + 1)) || ((i->Y == Y) && (i->X == X - 1 || i->X == X + 1))) return (true); return (false); } bool AiEngine::isDifferentCase(posXY first, posXY second) { if (first.X != second.X || first.Y != second.Y) return (true); return (false); } bool AiEngine::checkLongLine(posXY from, posXY to) { posXY tmp; tmp.X = from.X; tmp.Y = from.Y; if (tmp.Y > to.Y) { while (tmp.Y != to.Y) { if (isDifferentCase(tmp, from) && isBox(tmp.X, tmp.Y)) return (false); --tmp.Y; } } else { while (tmp.Y != to.Y) { if (isDifferentCase(tmp, from) && isBox(tmp.X, tmp.Y)) return (false); ++tmp.Y; } } return (true); } bool AiEngine::checkLargLine(posXY from, posXY to) { posXY tmp; tmp.X = from.X; tmp.Y = from.Y; if (tmp.X > to.X) { while (tmp.X != to.X) { if (isDifferentCase(tmp, from) && isBox(tmp.X, tmp.Y)) return (false); --tmp.X; } } if (tmp.X < to.X) { while (tmp.X != to.X) { if (isDifferentCase(tmp, from) && isBox(tmp.X, tmp.Y)) return (false); ++tmp.X; } } return (true); } bool AiEngine::thereIsNoBoxBetween(posXY pos, posXY enemiePos) { Action [MASK] ; [MASK] = calcDirection(pos, enemiePos); if ( [MASK] == _UP || [MASK] == _DOWN) return (checkLongLine(pos, enemiePos)); else if ( [MASK] == _LEFT || [MASK] == _RIGHT) return (checkLargLine(pos, enemiePos)); else return (true); } bool AiEngine::enemieInRange(int X, int Y, int R) { std::list::iterator i; posXY from, to; int it; from.X = X; from.Y = Y; for (i = _unitPosition.begin(); i != _unitPosition.end(); ++i) { it = R; if (it <= 0) it = 1; while (it != 0) { if (((i->X == X) && (i->Y == Y - it || i->Y == Y + it)) || ((i->Y == Y) && (i->X == X - it || i->X == X + it))) { to.X = i->X; to.Y = i->Y; if (thereIsNoBoxBetween(from, to)) return (true); } --it; } } return (false); } void AiEngine::doDownCalc(posXY pos, int power) { int i = power; while (i != 0) { if ((pos.Y - 1) >= 0) { --pos.Y; _explosionArea.push_back(pos); } --i; } } void AiEngine::doLeftCalc(posXY pos, int power) { int i = power; while (i != 0) { if ((pos.X + 1) < _data->getMapWidth()) { ++pos.X; _explosionArea.push_back(pos); } --i; } } void AiEngine::doUpCalc(posXY pos, int power) { int i = power; while (i != 0) { if ((pos.Y + 1) < _data->getMapHeight()) { ++pos.Y; _explosionArea.push_back(pos); } --i; } } void AiEngine::doRightCalc(posXY pos, int power) { int i = power; while (i != 0) { if ((pos.X - 1) >= 0) { --pos.X; _explosionArea.push_back(pos); } --i; } } void AiEngine::calculateArea(posXY pos, int power) { int P = (power - 1)/2; _explosionArea.push_back(pos); doUpCalc(pos, P); doLeftCalc(pos, P); doRightCalc(pos, P); doDownCalc(pos, P); } void AiEngine::affExplosionArea() { std::list::iterator i; std::cout << ""==========\nEXPLOSION AREA:"" << std::endl; for (i = _explosionArea.begin(); i != _explosionArea.end(); ++i) std::cout << ""--> X["" << i->X << ""] Y["" << i->Y << ""]."" << std::endl; std::cout << ""=========="" << std::endl; } void AiEngine::affUnitPosition() { std::list::iterator i; std::cout << ""==========\nUNIT POSITION:"" << std::endl; for (i = _unitPosition.begin(); i != _unitPosition.end(); ++i) std::cout << ""--> X["" << i->X << ""] Y["" << i->Y << ""]."" << std::endl; std::cout << ""=========="" << std::endl; } void AiEngine::affPos(posXY pos) { std::cout << ""X["" << pos.X << ""]Y["" << pos.Y << ""]."" << std::endl; } void AiEngine::affPos(int X, int Y) { std::cout << ""X["" << X << ""]Y["" << Y << ""]."" << std::endl; } void AiEngine::affState(State S) { switch (S) { case (_ATTACK): std::cout << ""_ATTACK"" << std::endl; break; case (_SURVIVE): std::cout << ""_SURVIVE"" << std::endl; break; case (_EXPLORE): std::cout << ""_EXPLORE"" << std::endl; break; case (_COLLECT): std::cout << ""_COLLECT"" << std::endl; break; } } bool AiEngine::isFreeCase(int X, int Y) { std::map, Case>::iterator i; CaseType type; for (i = _data->map._stock.begin(); i != _data->map._stock.end(); ++i) { if (i->first.first == X && i->first.second == Y) { type = i->second.getType(); if ((type == FLOOR || type == BONUS || type == FIRE_BONUS) && !thereIsUnit(i->first.first, i->first.second)) return (true); return (false); } } return (false); } State AiEngine::evalState(posXY pos, int attackRange) { if (isDangerousCase(pos.X, pos.Y) || !thereIsNoDanger(pos.X, pos.Y)) return (_SURVIVE); if (enemieInRange(pos.X, pos.Y, attackRange)) return (_ATTACK); if (thereIsBonusClose(pos.X, pos.Y)) return (_COLLECT); return (_EXPLORE); } Action AiEngine::makePlan(posXY actPos, State State, bool haveBomb, int power) { switch (State) { case (_SURVIVE): return (survive(actPos)); case (_ATTACK): return (attack(actPos, haveBomb, power)); case (_COLLECT): return (collectBonus(actPos)); case (_EXPLORE): return (explore(actPos, haveBomb)); } return (_THINK); } Action AiEngine::survive(posXY actPos) { posXY newPos; if (isDangerousCase(actPos.X, actPos.Y)) { newPos = getSafeCase(actPos.X, actPos.Y); if (newPos.X == -1 && newPos.Y == -1) { if (!isDangerousCase(actPos.X , actPos.Y)) return (_THINK); else { newPos = getLeaveCase(actPos.X, actPos.Y); if (newPos.X == -1) return (_THINK); return (calcDirection(actPos, newPos)); } } return (calcDirection(actPos, newPos)); } else return (_THINK); } Action AiEngine::attack(posXY actPos, bool haveBomb, int power) { posXY newPos; if (haveBomb && enemieInRange(actPos.X, actPos.Y, power) && !thereIsBombAt(actPos.X, actPos.Y) && newPos.X != -1) return (_BOMB); newPos = getSafeCase(actPos.X, actPos.Y); if (newPos.X != -1) return (calcDirection(actPos, newPos)); return (_THINK); } Action AiEngine::collectBonus(posXY playerPos) { std::list::iterator i; posXY bonusPos; for (i = _data->listBonus.begin(); i != _data->listBonus.end(); ++i) { bonusPos.X = (*i)->getX()/400; bonusPos.Y = (*i)->getZ()/400; if (isTouch(playerPos, bonusPos) && isFreeCase(bonusPos.X, bonusPos.Y)) return (calcDirection(playerPos, bonusPos)); } return (_THINK); } Action AiEngine::explore(posXY actPos, bool haveBomb) { posXY newPos; if (thereIsNoDanger(actPos.X, actPos.Y)) { newPos = getCase(actPos.X, actPos.Y); if (haveBomb && thereIsBoxClose(actPos.X, actPos.Y) && newPos.X != -1) return (_BOMB); else if (thereIsBonusClose(actPos.X, actPos.Y)) return (collectBonus(actPos)); else return (getRandMove()); } else return (_THINK); } Action AiEngine::getRandMove() { int result = random() % 4; switch (result) { case 0: return (_UP); case 1: return (_RIGHT); case 2: return (_DOWN); case 3: return (_LEFT); } return (_THINK); } Action AiEngine::calcDirection(posXY actPos, posXY newPos) { if (actPos.X == newPos.X && actPos.Y - 1 == newPos.Y) return (_DOWN); if (actPos.X == newPos.X && actPos.Y + 1 == newPos.Y) return (_UP); if (actPos.X - 1 == newPos.X && actPos.Y == newPos.Y) return (_RIGHT); if (actPos.X + 1 == newPos.X && actPos.Y == newPos.Y) return (_LEFT); return (_THINK); } ",dir 132,"#include #include #include #include ""DeltaBuffer.hpp"" using namespace org_pqrs_Karabiner; TEST(DeltaBuffer, push) { DeltaBuffer [MASK] ; EXPECT_EQ(0, [MASK] .sum()); [MASK] .push(-1); EXPECT_EQ(-1, [MASK] .sum()); // fill buffer EXPECT_TRUE(! [MASK] .isFull()); int sum = 0; for (;;) { [MASK] .push(-1); if (sum == [MASK] .sum()) break; sum = [MASK] .sum(); } EXPECT_TRUE( [MASK] .isFull()); [MASK] .push(-3); // replace -1 with -3. sum -= 2; EXPECT_EQ(sum, [MASK] .sum()); [MASK] .push(0); // replace -1 with 0. sum += 1; EXPECT_EQ(sum, [MASK] .sum()); // reverse direction EXPECT_NE(sum, 0); [MASK] .push(1); sum = 1; EXPECT_EQ(sum, [MASK] .sum()); EXPECT_TRUE(! [MASK] .isFull()); // clear while (! [MASK] .isFull()) { [MASK] .push(1); } EXPECT_NE(0, [MASK] .sum()); EXPECT_NE(0, [MASK] .isFull()); [MASK] .clear(); EXPECT_EQ(0, [MASK] .sum()); EXPECT_TRUE(! [MASK] .isFull()); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } ",deltaBuffer 133,"#include #include #include #include #include #include #include #include int main(int argc, char** argv) try { dlib::command_line_parser cmd_parser; cmd_parser.add_option(""max-size"", ""max num of pixels per image"", 1); cmd_parser.add_option(""max-images"", ""maximum number of images"", 1); cmd_parser.add_option(""show"", ""show the resulting image""); cmd_parser.set_group_name(""Help Options""); cmd_parser.add_option(""h"", """"); cmd_parser.add_option(""help"", ""display this message and exit""); cmd_parser.parse(argc, argv); if (cmd_parser.number_of_arguments() == 0 || cmd_parser.option(""h"") || cmd_parser.option(""help"")) { std::cout << ""\nUsage: tiler [options] directory\n\n""; cmd_parser.print_options(); return EXIT_SUCCESS; } const std::string& root = cmd_parser[0]; const double max_size = dlib::get_option(cmd_parser, ""max-size"", std::numeric_limits::max()); const size_t max_images = dlib::get_option(cmd_parser, ""max-images"", std::numeric_limits::max()); auto files = dlib::get_files_in_directory_tree(root, dlib::match_endings("".jpg .JPG .jpeg .JPEG .png .PNG"")); std::sort(files.begin(), files.end()); std::cout << ""Found "" << files.size() << "" images\n""; auto num_images = std::min(max_images, files.size()); files.erase(files.begin() + num_images, files.end()); std::cout << ""Generating tiled image with "" << files.size() << "" images\n""; std::vector> images; images.assign(files.size(), dlib::matrix()); dlib::parallel_for(0, files.size(), [&files, max_size, &images](size_t i) { const auto& file = files[i]; dlib::matrix image; dlib::load_image(image, file.full_name()); if (const auto [MASK] = std::sqrt(max_size / image.size()); [MASK] < 1) { dlib::resize_image( [MASK] , image); } images[i] = std::move(image); }); dlib::matrix tiled_image = dlib::tile_images(images); dlib::save_jpeg(tiled_image, ""tiled_image.jpg""); if (cmd_parser.option(""show"")) { dlib::image_window win(tiled_image, ""tiled image""); win.wait_until_closed(); } return EXIT_SUCCESS; } catch (std::exception& e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; } ",scaling_factor 134,"// // ycsbc.cc // YCSB-C // // Created by on 12/19/14. // Copyright (c) 2014 <>. // #include ""ycsbc.h"" #include #include #include #include #include #include ""core/client.h"" #include ""core/core_workload.h"" #include ""core/timer.h"" #include ""core/utils.h"" using namespace std; namespace ycsbc { void UsageMessage(const char *command); bool StrStartWith(const char *str, const char *pre); string ParseCommandLine(int argc, const char *argv[], utils::Properties &props); int DelegateClient(ycsbc::DB *db, ycsbc::CoreWorkload *wl, const int num_ops, bool is_loading, vector* latency) { db->Init(); ycsbc::Client client(*db, *wl); utils::Timer [MASK] ; int current_ops; int oks = 0; for (int i = 0; i < num_ops; ++i) { current_ops = 0; [MASK] .Start(); if (is_loading) { oks += client.DoInsert(); } else { oks += client.DoTransaction(); } double t = [MASK] .End(); if (latency) latency->push_back(t); } db->Close(); return oks; } string ParseCommandLine(int argc, const char *argv[], utils::Properties &props) { int argindex = 1; string filename; while (argindex < argc && StrStartWith(argv[argindex], ""-"")) { if (strcmp(argv[argindex], ""-threads"") == 0) { argindex++; if (argindex >= argc) { UsageMessage(argv[0]); exit(0); } props.SetProperty(""threadcount"", argv[argindex]); argindex++; } else if (strcmp(argv[argindex], ""-host"") == 0) { argindex++; if (argindex >= argc) { UsageMessage(argv[0]); exit(0); } props.SetProperty(""host"", argv[argindex]); argindex++; } else if (strcmp(argv[argindex], ""-port"") == 0) { argindex++; if (argindex >= argc) { UsageMessage(argv[0]); exit(0); } props.SetProperty(""port"", argv[argindex]); argindex++; } else if (strcmp(argv[argindex], ""-slaves"") == 0) { argindex++; if (argindex >= argc) { UsageMessage(argv[0]); exit(0); } props.SetProperty(""slaves"", argv[argindex]); argindex++; } else if (strcmp(argv[argindex], ""-P"") == 0) { argindex++; if (argindex >= argc) { UsageMessage(argv[0]); exit(0); } filename.assign(argv[argindex]); ifstream input(argv[argindex]); try { props.Load(input); } catch (const string &message) { cout << message << endl; exit(0); } input.close(); argindex++; } else if (strcmp(argv[argindex], ""--no-init"") == 0) { props.SetProperty(""init_data"", ""0""); argindex++; } else if (strcmp(argv[argindex], ""-records"") == 0) { argindex++; if (argindex >= argc) { UsageMessage(argv[0]); exit(0); } props.SetProperty(""recordcount"", argv[argindex]); argindex++; } else if (strcmp(argv[argindex], ""-operations"") == 0) { argindex++; if (argindex >= argc) { UsageMessage(argv[0]); exit(0); } props.SetProperty(""operationcount"", argv[argindex]); argindex++; } else if (strcmp(argv[argindex], ""-bs"") == 0) { argindex++; if (argindex >= argc) { UsageMessage(argv[0]); exit(0); } props.SetProperty(""fieldlength"", argv[argindex]); argindex++; }else { cout << ""Unknown option '"" << argv[argindex] << ""'"" << endl; exit(0); } } if (argindex == 1 || argindex != argc) { UsageMessage(argv[0]); exit(0); } return filename; } void UsageMessage(const char *command) { cout << ""Usage: "" << command << "" [options]"" << endl; cout << ""Options:"" << endl; cout << "" -threads n: execute using n threads (default: 1)"" << endl; cout << "" -P propertyfile: load properties from the given file. Multiple "" ""files can"" << endl; cout << "" be specified, and will be processed in the order "" ""specified"" << endl; cout << "" -records record_counts: amount of data to be initialized"" << endl; cout << "" -operations operation_counts: amount of operations to be performed"" << endl; cout << "" -bs value_size: size of a value"" << endl; cout << "" --no-init: bypass the initialization of data"" << endl; } inline bool StrStartWith(const char *str, const char *pre) { return strncmp(str, pre, strlen(pre)) == 0; } void RunBench(int argc, const char *argv[], DB *db) { utils::Properties props; string file_name = ParseCommandLine(argc, argv, props); vector> actual_ops; int total_ops = stoi(props[ycsbc::CoreWorkload::RECORD_COUNT_PROPERTY]); int sum = 0; ycsbc::CoreWorkload wl; wl.Init(props); const int num_threads = stoi(props.GetProperty(""threadcount"", ""1"")); const bool init_data = stoi(props.GetProperty(""init_data"", ""1"")); vector total_latency; total_latency.reserve(total_ops); vector> thread_latency(num_threads); if (init_data) { // Loads data std::cout << ""=============================== Load Data "" ""==============================="" << std::endl; for (int i = 0; i < num_threads; ++i) { actual_ops.emplace_back(async(launch::async, DelegateClient, db, &wl, total_ops / num_threads, true, nullptr)); } assert((int)actual_ops.size() == num_threads); for (auto &n : actual_ops) { assert(n.valid()); sum += n.get(); } cerr << ""# Loading records:\t"" << sum << endl; } // Peforms transactions std::cout << ""=============================== Perform Transanction "" ""==============================="" << std::endl; actual_ops.clear(); total_ops = stoi(props[ycsbc::CoreWorkload::OPERATION_COUNT_PROPERTY]); utils::Timer timer; timer.Start(); for (int i = 0; i < num_threads; ++i) { actual_ops.emplace_back(async(launch::async, DelegateClient, db, &wl, total_ops / num_threads, false, &thread_latency[i])); } assert((int)actual_ops.size() == num_threads); sum = 0; for (auto &n : actual_ops) { assert(n.valid()); sum += n.get(); } double duration = timer.End(); for (int t = 0; t < num_threads; t++) { total_latency.insert(total_latency.end(), thread_latency[t].begin(), thread_latency[t].end()); } size_t pos_avg = sum >> 2; size_t pos_99 = sum - sum / 100 - 1; size_t pos_999 = sum - sum / 1000 - 1; cout << ""# Transaction throughput (KTPS)"" << endl; cout << file_name << '\t' << num_threads << '\t'; cout << total_ops / duration / 1000 << endl; cout << ""# Transaction latency (ms)"" << endl; nth_element(total_latency.begin(), total_latency.begin() + pos_avg, total_latency.end()); cout << ""avg latency:\t"" << *(total_latency.begin() + pos_avg) * 1000 << endl; nth_element(total_latency.begin(), total_latency.begin() + pos_99, total_latency.end()); cout << ""99% tail latency:\t"" << *(total_latency.begin() + pos_99) * 1000 << endl; nth_element(total_latency.begin(), total_latency.begin() + pos_999, total_latency.end()); cout << ""99.9% tail latency:\t"" << *(total_latency.begin() + pos_999) * 1000 << endl; } } // namespace ycsbc ",timer_us 135,"/* * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef NET_CONNECTION_IMPL_H #define NET_CONNECTION_IMPL_H #include ""common.h"" #include ""ffi_remote_data.h"" #include ""net_connection_callback.h"" #include ""net_manager_constants.h"" #include ""net_specifier.h"" #include #include namespace OHOS::NetManagerStandard { class NetConnectionImpl final { public: bool hasNetSpecifier_; bool hasTimeout_; NetManagerStandard::NetSpecifier netSpecifier_; uint32_t timeout_; std::vector> netAvailible; std::vector> netBlockStatusChange; std::vector> netCapabilitiesChange; std::vector> netConnectionPropertiesChange; std::vector> netLost; std::vector> netUnavailable; public: [[nodiscard]] sptr GetObserver() const; static NetConnectionImpl *MakeNetConnection(); static void DeleteNetConnection(OHOS::NetManagerStandard::NetConnectionImpl *netConnection); private: sptr observer_; explicit NetConnectionImpl(); ~NetConnectionImpl() = default; }; class NetConnectionProxy : public OHOS::FFI::FFIData { private: friend class OHOS::FFI::RuntimeType; friend class OHOS::FFI::TypeBase; static OHOS::FFI::RuntimeType *GetClassType() { static OHOS::FFI::RuntimeType [MASK] = OHOS::FFI::RuntimeType::Create(""NetConnectionProxy""); return & [MASK] ; } public: OHOS::FFI::RuntimeType *GetRuntimeType() override { return GetClassType(); } public: NetConnectionProxy(CNetSpecifier specifier, uint32_t timeout); int32_t RegisterCallback(); int32_t UnregisterCallback(); void OnNetAvailible(void (*callback)(int32_t)); void OnNetBlockStatusChange(void (*callback)(int32_t, bool)); void OnNetCapabilitiesChange(void (*callback)(CNetCapabilityInfo)); void OnNetConnectionPropertiesChange(void (*callback)(int32_t, CConnectionProperties)); void OnNetLost(void (*callback)(int32_t)); void OnNetUnavailable(void (*callback)()); private: NetConnectionImpl *netConn_; }; extern std::map NET_CONNECTIONS; extern std::mutex g_netConnectionsMutex; } // namespace OHOS::NetManagerStandard #endif",runtimeType 136," /****************************************************************************** * Copyright 2021 * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ #ifndef _LIB_SPEC_READER_HPP #define _LIB_SPEC_READER_HPP #include ""clang/AST/Decl.h"" #include ""clang/ASTMatchers/ASTMatchers.h"" #include ""clang/ASTMatchers/ASTMatchFinder.h"" #include ""clang/Frontend/CompilerInstance.h"" #include ""clang/Tooling/Tooling.h"" #include ""clang/Tooling/CommonOptionsParser.h"" #include ""llvm/Support/CommandLine.h"" #include #include #include #include ""srcHelperFunctions.hpp"" #include ""clang_interface.hpp"" void addExposedFuncs(const clang::PrintingPolicy&); class ExposedFuncDecl { public: std::string name; const clang::CXXRecordDecl* enclosing_class = nullptr; clang::QualType ret_typ; llvm::ArrayRef params; bool statik; bool ctor; bool special; ExposedFuncDecl(llvm::StringRef _name, const clang::CXXRecordDecl* _ec, clang::QualType _ret_typ, llvm::ArrayRef _params, bool _statik = false, bool _ctor = false, bool _special = false) : name(_name), enclosing_class(_ec), ret_typ(_ret_typ), params(_params), statik(_statik), ctor(_ctor), special(_special) {}; ExposedFuncDecl(llvm::StringRef _name, clang::QualType _ret_typ, llvm::ArrayRef _params, bool _statik = false, bool _ctor = false, bool _special = false) : name(_name), ret_typ(_ret_typ), params(_params), statik(_statik), ctor(_ctor), special(_special) {}; std::string getSignature() const; static bool compare(const ExposedFuncDecl&, const ExposedFuncDecl&); }; class ExposedTemplateType { public: std::string base_type; clang::TemplateParameterList* template_params; ExposedTemplateType(std::string [MASK] , clang::TemplateParameterList* _tpl) : base_type( [MASK] ), template_params(_tpl) {}; std::vector getParamListStr(); static bool compare(const ExposedTemplateType&, const ExposedTemplateType&); }; /******************************************************************************* * FuzzHelperLog action - read information from defined helper functions *******************************************************************************/ class fuzzHelperFuncLogger : public clang::ast_matchers::MatchFinder::MatchCallback { public: virtual void run(const clang::ast_matchers::MatchFinder::MatchResult&); }; class fuzzHelperLogger : public clang::ASTConsumer { private: clang::ast_matchers::MatchFinder matcher; fuzzHelperFuncLogger logger; public: fuzzHelperLogger(); void HandleTranslationUnit(clang::ASTContext& ctx) override; }; class fuzzHelperLoggerAction : public clang::ASTFrontendAction { private: const clang::PrintingPolicy* print_policy; public: fuzzHelperLoggerAction() {}; bool BeginSourceFileAction(clang::CompilerInstance& ci) override; void EndSourceFileAction() override; std::unique_ptr CreateASTConsumer(clang::CompilerInstance& CI, llvm::StringRef File) override; }; /******************************************************************************* * LibSpecReader action - read information from exposed library sources *******************************************************************************/ class exposedFuncDeclMatcher : public clang::ast_matchers::MatchFinder::MatchCallback { public: virtual void run(const clang::ast_matchers::MatchFinder::MatchResult&); }; class libSpecReader : public clang::ASTConsumer { private: clang::ast_matchers::MatchFinder matcher; exposedFuncDeclMatcher printer; public: libSpecReader(); void HandleTranslationUnit(clang::ASTContext& ctx) override; }; class libSpecReaderAction : public clang::ASTFrontendAction { private: const clang::PrintingPolicy* print_policy; public: libSpecReaderAction() {}; bool BeginSourceFileAction(clang::CompilerInstance& ci) override; void EndSourceFileAction() override; std::unique_ptr CreateASTConsumer(clang::CompilerInstance& CI, llvm::StringRef File) override; }; extern std::set exposed_funcs; #endif // _LIB_SPEC_READER_HPP ",_base_type 137,"#ifndef NIGIRI_STATEMACHINE_H #define NIGIRI_STATEMACHINE_H #include #include #include #include #include #include #include namespace nigiri { // #define LOG_NIGIRI_STATEMACHINE template class _StateMachine { public: using StateToStringFunc = std::function; using EventToStringFunc = std::function; using StateValue = typename std::underlying_type::type; using EventValue = typename std::underlying_type::type; _StateMachine(){ static_assert(stateEnum && !stateConvert,""State type is not enum class""); static_assert(eventEnum && !eventConvert,""Event type is not enum class""); }; ~_StateMachine(){ #ifdef LOG_NIGIRI_STATEMACHINE std::cout << ""DEBUG - nigiri::StateMachine - dtor"" << std::endl; #endif } TState getState(){ return state; } void submitEvent(TEvent event){ if(isEventValid(event)){ #ifdef LOG_NIGIRI_STATEMACHINE if(eventToStringFunc){ std::string msg = ""StateMachine - Submitting event \"""" + eventToStringFunc(event) + ""\""""; std::cout << msg << std::endl; } TState oldState = state; #endif std::lock_guard guard(mtx); state = topology[state][event]; #ifdef LOG_NIGIRI_STATEMACHINE if (eventToStringFunc && stateToStringFunc) { std::string msg = ""StateMachine - ""; msg += ""Event \"""" + eventToStringFunc(event) + ""\"" changed state from \"""" + stateToStringFunc(oldState) + ""\"" to \"""" + stateToStringFunc(state) + ""\""""; std::cout << msg << std::endl; } #endif cv.notify_one(); #ifdef LOG_NIGIRI_STATEMACHINE if(eventToStringFunc){ std::string msg = ""StateMachine - Event \"""" + eventToStringFunc(event) + ""\"" submitted""; std::cout << msg << std::endl; } #endif } }; void waitForState(TState waitState){ #ifdef LOG_NIGIRI_STATEMACHINE if(stateToStringFunc){ std::string msg = ""StateMachine - Waiting for state \"""" + stateToStringFunc(waitState) + ""\""""; std::cout << msg << std::endl; } #endif std::unique_lock lock(mtx); TState* statePtr = &state; cv.wait(lock,[statePtr,waitState](){ #ifdef LOG_NIGIRI_STATEMACHINE StateValue requiredStateValue = static_cast(waitState); StateValue currentStateValue = static_cast(*statePtr); std::string msg = ""StateMachine - State check - ""; msg += ""Required: \"""" + std::to_string(requiredStateValue) + ""\"", Current: \"""" + std::to_string(currentStateValue) + ""\""""; std::cout << msg << std::endl; #endif return waitState == *statePtr; }); #ifdef LOG_NIGIRI_STATEMACHINE if(stateToStringFunc){ std::string msg = ""StateMachine - State \"""" + stateToStringFunc(waitState) + ""\"" reached""; std::cout << msg << std::endl; } #endif }; void waitForStates(std::initializer_list waitStates){ #ifdef LOG_NIGIRI_STATEMACHINE if(stateToStringFunc){ std::string msg ="" StateMachine - Waiting for ""; for(auto waitState : waitStates){ msg += getStateString(waitState) + "" ""; } std::cout << msg << std::endl; } #endif std::unique_lock lock(mtx); bool condition = true; while (condition) { cv.wait(lock); for (auto waitState : waitStates) { if (waitState == state) { #ifdef LOG_NIGIRI_STATEMACHINE StateValue requiredStateValue = static_cast(waitState); StateValue currentStateValue = static_cast(state); std::string msg = ""StateMachine - State check - ""; msg += ""Required: \"""" + std::to_string(requiredStateValue) + ""\"", Current: \"""" + std::to_string(currentStateValue) + ""\""""; std::cout << msg << std::endl; #endif condition = false; } } } #ifdef LOG_NIGIRI_STATEMACHINE if(stateToStringFunc){ std::string stateString = ""\"""" + stateToStringFunc(state) + ""\""""; std::cout << ""StateMachine - State "" << stateString << "" reached"" << std::endl; } #endif }; void addConnection(TState [MASK] , TEvent cause, TState toState){ topology[ [MASK] ][cause] = toState; }; void registerStateToString(StateToStringFunc func) { if(func) { stateToStringFunc = func; } } void registerEventToString(EventToStringFunc func) { if(func) { eventToStringFunc = func; } } private: TState state = initialState; std::map> topology; std::mutex mtx; std::condition_variable cv; StateToStringFunc stateToStringFunc; EventToStringFunc eventToStringFunc; bool isEventValid(TEvent event) { std::string stateString = """"; if(stateToStringFunc != nullptr){ stateString = ""\"""" + stateToStringFunc(state) + ""\""""; } auto fromSearch = topology.find(state); if(fromSearch == topology.end()){ #ifdef LOG_NIGIRI_STATEMACHINE std::cout << ""Current state"" << stateString << "" do not have any connections"" << std::endl; #endif return false; } auto stateTopology = fromSearch->second; auto eventSearch = stateTopology.find(event); if(eventSearch == stateTopology.end()) { #ifdef LOG_NIGIRI_STATEMACHINE if(eventToStringFunc != nullptr){ std::string eventString = ""\"""" + eventToStringFunc(event) + ""\""""; std::cout << ""Current state"" << stateString << "" do not respond to provided event"" << eventString << std::endl; } #endif return false; } return true; } }; template using StateMachine = _StateMachine::value, std::is_convertible::value, std::is_enum::value, std::is_convertible::value>; } #endif //NIGIRI_STATEMACHINE_H ",fromState 138,"#include ""accelerometer.h"" Accelerometer::Accelerometer(short x, short y, short z) { axis_.x = x; axis_.y = y; axis_.z = z; is_empty_ = false; } Accelerometer::Accelerometer(bool is_empty): is_empty_(is_empty) { // } Accelerometer* Accelerometer::Create(short x, short y, short z) { bool are_different = x != y && y != z && x != z; bool is_x_pin_valid = x >= 0 && x <= 5; bool [MASK] = y >= 0 && y <= 5; bool is_z_pin_valid = z >= 0 && z <= 5; if(are_different && is_x_pin_valid && [MASK] && is_z_pin_valid) { return new Accelerometer(x, y, z); } return new Accelerometer(true); } bool Accelerometer::is_empty(void) { return is_empty_; } short Accelerometer::x() { return axis_.x; } short Accelerometer::y() { return axis_.y; } short Accelerometer::z() { return axis_.z; } ",is_y_pin_valid 139,"// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include ""Apartment.h"" #include ""ApartmentHUD.h"" #include ""Engine/Canvas.h"" #include ""TextureResource.h"" #include ""CanvasItem.h"" AApartmentHUD::AApartmentHUD() { // Set the crosshair texture static ConstructorHelpers::FObjectFinder [MASK] (TEXT(""/Game/FirstPerson/Textures/FirstPersonCrosshair"")); CrosshairTex = [MASK] .Object; } void AApartmentHUD::DrawHUD() { Super::DrawHUD(); // Draw very simple crosshair // find center of the Canvas const FVector2D Center(Canvas->ClipX * 0.5f, Canvas->ClipY * 0.5f); // offset by half the texture's dimensions so that the center of the texture aligns with the center of the Canvas const FVector2D CrosshairDrawPosition( (Center.X), (Center.Y + 20.0f)); // draw the crosshair FCanvasTileItem TileItem( CrosshairDrawPosition, CrosshairTex->Resource, FLinearColor::White); TileItem.BlendMode = SE_BLEND_Translucent; Canvas->DrawItem( TileItem ); } ",CrosshiarTexObj 140,"#include ""fauve.h"" #include ""joueur.h"" #include ""piege.h"" #include ""AireDeJeu.h"" #include ""Afficheur.h"" #include #include bool gameOver; bool menu = true; void ajoutEdit(AireDeJeu& e, afficheConsole& a) { bool ajouter=true; while(ajouter) { std::string nom; std::cout<<""Ecrire ce que vous voulez ajouter: joueur,lion,tigre,piege a pic\n""; std::cin>>nom; if(nom == ""joueur"") { int x,y; std::cout<<""Donnez sa position: y x\n""; std::cin>>y>>x; e.setValue(point{x,y},1); } else if(nom == ""lion"") { int x,y; std::cout<<""Donnez sa position: y puis x\n""; std::cin>>y>>x; e.setValue(point{x,y},2); } else if(nom == ""tigre"") { int x,y; std::cout<<""Donnez sa position: y puis x\n""; std::cin>>y>>x; e.setValue(point{x,y},3); } else if(nom == ""piege"") { int x,y; std::cout<<""Donnez sa position: y puis x\n""; std::cin>>y>>x; e.setValue(point{x,y},4); } else std::cout<<""error""; a.afficheAdj(e); std::cout<<""Voulez vous continuer d'ajouter des entites? 0.Non 1.Oui\n""; std::cin>>ajouter; } } void creeAdJ() { afficheConsole a; int longueur,largeur; std::cout<<""Donnez la taille de l'aire de jeu: Longueur Largeur\n""; std::cin>>longueur>>largeur; AireDeJeu adj(longueur,largeur); std::cout<<""0 dans le tableau = case vide\n1 dans le tableau = Joueur\n2 dans le tableau = Lion\n3 dans le tableau = Tigre\n4 dans le tableau = PiegeAPic\n""; a.afficheAdj(adj); ajoutEdit(adj,a); adj.exporter(""export.txt""); std::cout<<""Fichier exporte avec succes dans export.txt\n""; } void editImport() { afficheConsole a; AireDeJeu adj{10,10}; adj.import(""import.txt""); a.afficheAdj(adj); ajoutEdit(adj,a); adj.exporter(""export.txt""); std::cout<<""Fichier exporte avec succes dans export.txt\n""; } void exporte() { int choix =0; while(choix<1 || choix>3) { std::cout<<""Saisissez ce que vous voulez faire:\n1. Creer une aire de jeu vierge\n2. Modifier l'aire de jeu importee \n3. Revenir au menu\n""; std::cin>>choix; } switch(choix) { case 1: creeAdJ();break; //aleatoireAdJ(e); Idee de type d'aire de jeu case 2: editImport();break; case 3: break; } } void jeu(AireDeJeu& adj, afficheConsole& a) { //Init tab joueurs std::vector> joueurs; //Init tab fauves std::vector> fauves; //Init tab pieges std::vector> pieges; adj.applyImport(joueurs,fauves,pieges); //boucle de jeu tour par tour while (gameOver==false && fauves.empty()==false) { a.afficheAdj(adj); int valeur; std::cout<<""envoyez la valeur de deplacement: ""; std::cin>>valeur; for(int i=0;ideplacement(adj,valeur); } for(int i=0;iestVivant()) { fauves[i]->deplacement(adj,joueurs,fauves,pieges);// on deplace les fauves if(joueurs[0]->estVivant()==false) { gameOver=true; i=fauves.size(); } } } for(int i=0;iestActif()) { std::swap(pieges[i],pieges[pieges.size()-1]); pieges.pop_back(); } } for(int i=0;ilifetime()<<'\n'; } } std::cout<<""GameOver\nRetour au menu...\n""; } void jouer() { gameOver=false; //Init afficheur afficheConsole a; //Init Aire de jeu AireDeJeu adj{10,10}; int [MASK] =0; while( [MASK] <1 || [MASK] >3) { std::cout<<""Saisissez ce que vous voulez faire:\n1. Aire de jeu aleatoire(not working)\n2. Aire de jeu importee\n3. Revenir au menu\n""; std::cin>> [MASK] ; } switch( [MASK] ) { case 1: std::cout<<""N'existe pas, uniquement une idee pour etoffer le menu\n"";break; //aleatoireAdJ(e); Idee de type d'aire de jeu case 2: adj.import(""import.txt"");jeu(adj,a); break; case 3: break; } } void mainMenu() { while (menu) { int valeur; std::cout<<""Saisissez ce que vous voulez faire:\n1. Jouer\n2. Exporter une Aire de Jeu\n9. Quitter\n""; std::cin>>valeur; switch(valeur) { case 1 : jouer(); break; case 2 : exporte(); break; case 9 : exit(0); } } } int main() { mainMenu(); } ",typeAdJ 141,"#include #include using namespace std; int knapsack(vector& weights, vector& profits, int capacity) { int n = weights.size(); vector> T(n + 1, vector(capacity + 1, 0)); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= capacity; ++j) { if (weights[i - 1] <= j) { T[i][j] = max(T[i - 1][j], T[i - 1][j - weights[i - 1]] + profits[i - 1]); } else { T[i][j] = T[i - 1][j]; } } } return T[n][capacity]; } int main() { int n; cout << ""Enter the number of items: ""; cin >> n; vector weights(n); vector profits(n); cout << ""Enter the weights of items: ""; for (int i = 0; i < n; ++i) { cin >> weights[i]; } cout << ""Enter the profits of items: ""; for (int i = 0; i < n; ++i) { cin >> profits[i]; } int capacity; cout << ""Enter the knapsack capacity: ""; cin >> capacity; int [MASK] = knapsack(weights, profits, capacity); cout << ""Maximum Profit: "" << [MASK] << endl; return 0; } ",result 142,"/*!************************************************************************** ** ** Copyright (C) 2009 TECHNOGERMA Systems France and/or its subsidiary(-ies). ** Contact: Technogerma Systems France Information () ** ** This file is part of the GICS library. ** ** Commercial Usage ** Licensees holding valid GICS Commercial licenses may use this file in ** accordance with the GICS Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and TECHNOGERMA Systems France. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL3.txt included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at . ** ****************************************************************************/ #include namespace rules::sdlc::stdc { template PimplPtr::PimplPtr() : m_data(new T) { } template PimplPtr::~PimplPtr() { } template PimplPtr::PimplPtr(T* data) : m_data(data) { assert(data != nullptr); } template PimplPtr::PimplPtr(const PimplPtr& copy) : m_data(new T(*copy.m_data)) { } template template PimplPtr::PimplPtr(T1 arg1) : m_data(new T(arg1)) { } template template PimplPtr::PimplPtr(T1 arg1, T2 arg2) : m_data(new T(arg1, arg2)) { } template template PimplPtr::PimplPtr(T1 arg1, T2 arg2, T3 [MASK] ) : m_data(new T(arg1, arg2, [MASK] )) { } template T* PimplPtr::operator->() noexcept { return (m_data.get()); } template const T* PimplPtr::operator->() const noexcept { return (m_data.get()); } template T& PimplPtr::operator*() noexcept { return (*m_data); } template const T& PimplPtr::operator*() const noexcept { return (*m_data); } template void PimplPtr::swap(PimplPtr& other) { m_data.swap(other.m_data); } /* template PimplPtr& PimplPtr::operator=(PimplPtr const& rhs) { PimplPtr tmp(rhs); *this = std::move(tmp); return (*this); } // template // PimplPtr& PimplPtr::operator=(PimplPtr&&) noexcept = default; template template PimplPtr::PimplPtr(U&& u) : m_data(new T{std::forward(u)}) { } template template PimplPtr::PimplPtr(U1&& u1, U2&& u2, Args&&... args) : m_data(new T{std::forward(u1), std::forward(u2), std::forward(args)...}) { } */ } ",arg3 143,"#include #include ""NLPReg.h"" //未在头文件包含 #include ""../../../tensor/function/FHeader.h"" namespace nlpreg { float learningRate = 0.3F; // learning rate int nEpoch = 100; // 训练次数 float minmax = 0.01F; // range [-p,p] for parameter initialization void Init(NLPRegModel &model); //初始化参数 void InitGrad(NLPRegModel &model, NLPRegModel &grad); void Train(float *trainDataX, float *trainDataY, int dataSize, NLPRegModel &model); void Forword(XTensor &input, NLPRegModel &model, NLPRegNet &net); void MSELoss(XTensor &output, XTensor &gold, XTensor &loss); void Backward(XTensor &input, XTensor &gold, NLPRegModel &model, NLPRegModel &grad, NLPRegNet &net); void Update(NLPRegModel &model, NLPRegModel &grad, float learningRate); void CleanGrad(NLPRegModel &grad); void Test(float *testData, int testDataSize, NLPRegModel &model); int NLPRegMain(int argc, const char ** argv) //项目主函数入口,传入Main.cpp { NLPRegModel model; model.h_size = 4; // 隐藏层节点个数(宽度?) const int dataSize = 16; const int testDataSize = 3; model.devID = 0; // -1:运行于cpu 0:0号显卡 Init(model); //初始化参数 /*train Data*/ float trainDataX[dataSize] = { 51,56.8,58,63,66,69,73,76,81,85,90,94,97,100,103,107 }; //训练集X float trainDataY[dataSize] = { 31,34.7,35.6,36.7,39.5,42,42.7,47,49,51,52.5,54,55.7,56,58.8,59.2 }; //训练集Y float testDataX[testDataSize] = { 64, 80, 95 }; //测试集 Train(trainDataX, trainDataY, dataSize, model); //训练回归模型 Test(testDataX, testDataSize, model); //使用模型进行预测 return 0; } void Init(NLPRegModel &model) { InitTensor2D(&model.weight1, 1, model.h_size, X_FLOAT, model.devID); //初始化模型中的tensor w1 InitTensor2D(&model.weight2, model.h_size, 1, X_FLOAT, model.devID); //初始化模型中的tensor w2 InitTensor2D(&model.b, model.h_size, 1, X_FLOAT, model.devID); //初始化模型中的tensor b model.weight1.SetDataRand(-minmax, minmax); //设置范围为(-0.01,0.01) model.weight2.SetDataRand(-minmax, minmax); model.b.SetZeroAll(); //修正值全部初始化为0 printf(""Initialization complete.\n""); } void InitGrad(NLPRegModel &model, NLPRegModel &grad) //赋值等? { InitTensor(&grad.weight1, &model.weight1); InitTensor(&grad.weight2, &model.weight2); InitTensor(&grad.b, &model.b); grad.h_size = model.h_size; grad.devID = model.devID; } void Train(float *trainDataX, float *trainDataY, int dataSize, NLPRegModel &model) { printf(""prepare data for train\n""); /*prepare for train*/ TensorList inputList; TensorList goldList; for (int i = 0; i < dataSize; ++i) { XTensor* inputData = NewTensor2D(1, 1, X_FLOAT, model.devID); //输入值为一维 inputData->Set2D(trainDataX[i] / 100, 0, 0); //除100,我的理解是归一化,使值域保持在0-1之间 inputList.Add(inputData); //输入列表加入当前值 XTensor* goldData = NewTensor2D(1, 1, X_FLOAT, model.devID); //房价数据 goldData->Set2D(trainDataY[i] / 60, 0, 0); //房价值/60?这里和数据本身相关 goldList.Add(goldData); //输入列表加入当前值 } printf(""start train\n""); NLPRegNet net; NLPRegModel grad; InitGrad(model, grad); //main开始时自定义的模型参数,用model初始化grad for (int epochIndex = 0; epochIndex < nEpoch; ++epochIndex) //循环训练 { printf(""epoch %d\n"", epochIndex); float totalLoss = 0; if ((epochIndex + 1) % 50 == 0) //这里对训练次数进行了处理,50次之后学习率除3? learningRate /= 3; for (int i = 0; i < inputList.count; ++i) { XTensor *input = inputList.GetItem(i); XTensor *gold = goldList.GetItem(i); Forword(*input, model, net); //正向传播 //output.Dump(stderr); XTensor loss; MSELoss(net.output, *gold, loss); //计算误差 //loss.Dump(stderr); totalLoss += loss.Get1D(0); //总误差 Backward(*input, *gold, model, grad, net); //反馈 Update(model, grad, learningRate); CleanGrad(grad); //进行下一次做准备 } printf(""loss %f\n"", totalLoss / inputList.count); } } void Forword(XTensor &input, NLPRegModel &model, NLPRegNet &net) { net.hidden_state1 = MatrixMul(input, model.weight1); net.hidden_state2 = net.hidden_state1 + model.b; net.hidden_state3 = HardTanH(net.hidden_state2); net.output = MatrixMul(net.hidden_state3, model.weight2); } void MSELoss(XTensor &output, XTensor &gold, XTensor &loss) { XTensor tmp = output - gold; loss = ReduceSum(tmp, 1, 2) / output.dimSize[1]; } void MSELossBackword(XTensor &output, XTensor &gold, XTensor &grad) { XTensor tmp = output - gold; grad = tmp * 2; } void Backward(XTensor &input, XTensor &gold, NLPRegModel &model, NLPRegModel &grad, NLPRegNet &net) { XTensor [MASK] ; XTensor &dedw2 = grad.weight2; XTensor &dedb = grad.b; XTensor &dedw1 = grad.weight1; MSELossBackword(net.output, gold, [MASK] ); MatrixMul(net.hidden_state3, X_TRANS, [MASK] , X_NOTRANS, dedw2); XTensor dedy = MatrixMul( [MASK] , X_NOTRANS, model.weight2, X_TRANS); _HardTanHBackward(&net.hidden_state3, &net.hidden_state2, &dedy, &dedb); dedw1 = MatrixMul(input, X_NOTRANS, dedb, X_TRANS); } void Update(NLPRegModel &model, NLPRegModel &grad, float learningRate) //更新训练模型 { model.weight1 = Sum(model.weight1, grad.weight1, -learningRate); //上一次的权重加本次训练的权重,最后减掉训练后的学习率 model.weight2 = Sum(model.weight2, grad.weight2, -learningRate); model.b = Sum(model.b, grad.b, -learningRate); } void CleanGrad(NLPRegModel &grad) //清空grad的w1,w2和b { grad.b.SetZeroAll(); grad.weight1.SetZeroAll(); grad.weight2.SetZeroAll(); } void Test(float *testData, int testDataSize, NLPRegModel &model) //使用模型进行预测 { NLPRegNet net; XTensor* inputData = NewTensor2D(1, 1, X_FLOAT, model.devID); for (int i = 0; i < testDataSize; ++i) { inputData->Set2D(testData[i] / 100, 0, 0); Forword(*inputData, model, net); float ans = net.output.Get2D(0, 0) * 60; printf(""%f\n"", ans); } } }",lossGrad 144,"// ************************************************** // Copyright (c) 2025, // ************************************************** #include #include #include #include #include ""dtypes.h"" namespace cute_kernels { template struct ChunkedArray { T* array; uint64 num_elements; }; template std::vector > chunk_array(T* x, const uint64& num_elements) { const uint64 [MASK] = (uint64)std::numeric_limits::max() + 1; uint64 start = 0; std::vector > result; // We will ""yield"" chunks of the array, each of size 'chunk_size' or less while (start < num_elements) { uint64 remaining = num_elements - start; uint64 current_chunk_size = std::min(remaining, [MASK] ); ChunkedArray chunked_x; chunked_x.array = (T*)&x[start]; chunked_x.num_elements = current_chunk_size; result.push_back(chunked_x); start += current_chunk_size; } return result; } } // namespace cute_kernels ",num_elements_per_chunk 145,"/* * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * 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 #include #include #include ""storage_daemon_client.h"" #include ""iservice_registry.h"" #include ""libfscrypt/fscrypt_utils.h"" #include ""storage_service_errno.h"" #include ""storage_service_log.h"" #include ""system_ability_definition.h"" #include ""utils/storage_radar.h"" using namespace OHOS::StorageService; namespace { constexpr uint32_t STORAGE_DAEMON_SFIFT = 1; constexpr uint32_t CHECK_SERVICE_TIMES = 1000; constexpr uint32_t LOG_CHECK_INTERVAL = 50; constexpr uint32_t SLEEP_TIME_PRE_CHECK = 20; // 20ms constexpr uint32_t STORAGE_SERVICE_FLAG = (1 << STORAGE_DAEMON_SFIFT); constexpr int32_t STORAGE_DAEMON_SAID = OHOS::STORAGE_MANAGER_DAEMON_ID; } namespace OHOS { namespace StorageDaemon { sptr StorageDaemonClient::GetStorageDaemonProxy(void) { auto samgr = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgr == nullptr) { LOGE(""samgr empty error""); return nullptr; } sptr object = samgr->GetSystemAbility(OHOS::STORAGE_MANAGER_DAEMON_ID); if (object == nullptr) { LOGE(""storage daemon client samgr ablity empty error""); return nullptr; } return iface_cast(object); } int32_t StorageDaemonClient::CheckServiceStatus(uint32_t [MASK] ) { LOGW(""CheckServiceStatus start""); auto samgr = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgr == nullptr) { LOGW(""samgr is nullptr, retry""); for (uint32_t i = 0; i < CHECK_SERVICE_TIMES; i++) { samgr = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgr != nullptr) { break; } if (i % LOG_CHECK_INTERVAL == 0) { LOGW(""check samgr %{public}u times"", i); } std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME_PRE_CHECK)); } if (samgr == nullptr) { LOGE(""samgr is nullptr, retry failed.""); return E_SA_IS_NULLPTR; } } if ( [MASK] & STORAGE_SERVICE_FLAG) { bool exist = false; for (uint32_t i = 0; i < CHECK_SERVICE_TIMES; i++) { auto object = samgr->CheckSystemAbility(STORAGE_DAEMON_SAID, exist); if (object != nullptr) { break; } if (i % LOG_CHECK_INTERVAL == 0) { LOGW(""check storage daemon status %{public}u times"", i); } std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME_PRE_CHECK)); } if (exist == false) { LOGE(""storage daemon service system ability error""); return E_SERVICE_IS_NULLPTR; } } LOGW(""CheckServiceStatus end, success""); return E_OK; } int32_t StorageDaemonClient::PrepareUserDirs(int32_t userId, uint32_t flags) { LOGI(""StorageDaemonClient::PrepareUserDirs, userId:%{public}d, flags:%{public}u"", userId, flags); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); std::string extraData = ""flags="" + std::to_string(flags); StorageRadar::ReportUserManager(""PrepareUserDirs::CheckServiceStatus"", userId, status, extraData); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); std::string extraData = ""flags="" + std::to_string(flags); StorageRadar::ReportUserManager(""PrepareUserDirs::GetStorageDaemonProxy"", userId, E_SA_IS_NULLPTR, extraData); return E_SA_IS_NULLPTR; } return client->PrepareUserDirs(userId, flags); } int32_t StorageDaemonClient::DestroyUserDirs(int32_t userId, uint32_t flags) { LOGI(""StorageDaemonClient::DestroyUserDirs, userId:%{public}d, flags:%{public}u"", userId, flags); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); std::string extraData = ""flags="" + std::to_string(flags); StorageRadar::ReportUserManager(""DestroyUserDirs::CheckServiceStatus"", userId, status, extraData); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); std::string extraData = ""flags="" + std::to_string(flags); StorageRadar::ReportUserManager(""DestroyUserDirs::GetStorageDaemonProxy"", userId, E_SA_IS_NULLPTR, extraData); return E_SA_IS_NULLPTR; } return client->DestroyUserDirs(userId, flags); } int32_t StorageDaemonClient::StartUser(int32_t userId) { LOGI(""StorageDaemonClient::StartUser, userId:%{public}d"", userId); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); StorageRadar::ReportUserManager(""StartUser::CheckServiceStatus"", userId, status, """"); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); StorageRadar::ReportUserManager(""StartUser::GetStorageDaemonProxy"", userId, E_SA_IS_NULLPTR, """"); return E_SA_IS_NULLPTR; } return client->StartUser(userId); } int32_t StorageDaemonClient::StopUser(int32_t userId) { LOGI(""StorageDaemonClient::StopUser, userId:%{public}d"", userId); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); StorageRadar::ReportUserManager(""StartUser::CheckServiceStatus"", userId, status, """"); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); StorageRadar::ReportUserManager(""StartUser::GetStorageDaemonProxy"", userId, E_SA_IS_NULLPTR, """"); return E_SA_IS_NULLPTR; } return client->StopUser(userId); } int32_t StorageDaemonClient::PrepareUserSpace(uint32_t userId, const std::string &volumId, uint32_t flags) { LOGI(""StorageDaemonClient::PrepareUserSpace, userId:%{public}u, volumId:%{public}s, flags:%{publc}u"", userId, volumId.c_str(), flags); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->PrepareUserDirs(userId, flags); } int32_t StorageDaemonClient::DestroyUserSpace(uint32_t userId, const std::string &volumId, uint32_t flags) { LOGI(""StorageDaemonClient::DestroyUserSpace, userId:%{public}u, volumId:%{public}s, flags:%{publc}u"", userId, volumId.c_str(), flags); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->DestroyUserDirs(userId, flags); } int32_t StorageDaemonClient::InitGlobalKey(void) { int32_t status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); StorageRadar::ReportUserKeyResult(""InitGlobalKey::CheckServiceStatus"", 0, status, ""EL1"", """"); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); StorageRadar::ReportUserKeyResult(""InitGlobalKey::GetStorageDaemonProxy"", 0, E_SA_IS_NULLPTR, ""EL1"", """"); return E_SA_IS_NULLPTR; } return client->InitGlobalKey(); } int32_t StorageDaemonClient::InitGlobalUserKeys(void) { int32_t status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); StorageRadar::ReportUserKeyResult(""InitGlobalUserKeys::CheckServiceStatus"", 0, status, ""EL1"", """"); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); StorageRadar::ReportUserKeyResult(""InitGlobalUserKeys::GetStorageDaemonProxy"", 0, E_SA_IS_NULLPTR, ""EL1"", """"); return E_SA_IS_NULLPTR; } return client->InitGlobalUserKeys(); } int32_t StorageDaemonClient::GenerateUserKeys(uint32_t userId, uint32_t flags) { LOGI(""StorageDaemonClient::GenerateUserKeys, userId: %{public}u, flags:%{public}u"", userId, flags); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->GenerateUserKeys(userId, flags); } int32_t StorageDaemonClient::DeleteUserKeys(uint32_t userId) { LOGI(""StorageDaemonClient::DeleteUserKeys, userId: %{public}u"", userId); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->DeleteUserKeys(userId); } int32_t StorageDaemonClient::UpdateUserAuth(uint32_t userId, uint64_t secureUid, const std::vector &token, const std::vector &oldSecret, const std::vector &newSecret) { LOGI(""StorageDaemonClient::UpdateUserAuth, userId: %{public}u, token:%{public}d,"" ""oldSecret:%{public}d, newSecret:%{public}d"", userId, token.empty(), oldSecret.empty(), newSecret.empty()); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->UpdateUserAuth(userId, secureUid, token, oldSecret, newSecret); } int32_t StorageDaemonClient::UpdateUseAuthWithRecoveryKey(const std::vector &authToken, const std::vector &newSecret, uint64_t secureUid, uint32_t userId, std::vector> &plainText) { LOGI(""StorageDaemonClient::UpdateUseAuthWithRecoveryKey, authToken: %{public}d, newSecret:%{public}d,"" ""userId:%{public}d"", authToken.empty(), newSecret.empty(), userId); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->UpdateUseAuthWithRecoveryKey(authToken, newSecret, secureUid, userId, plainText); } int32_t StorageDaemonClient::ActiveUserKey(uint32_t userId, const std::vector &token, const std::vector &secret) { LOGI(""StorageDaemonClient::ActiveUserKey, userId: %{public}u, token:%{public}d, secret:%{public}d"", userId, token.empty(), secret.empty()); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->ActiveUserKey(userId, token, secret); } int32_t StorageDaemonClient::InactiveUserKey(uint32_t userId) { LOGI(""StorageDaemonClient::InactiveUserKey, userId: %{public}u"", userId); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->InactiveUserKey(userId); } int32_t StorageDaemonClient::LockUserScreen(uint32_t userId) { LOGI(""StorageDaemonClient::LockUserScreen, userId: %{public}u"", userId); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->LockUserScreen(userId); } int32_t StorageDaemonClient::UnlockUserScreen(uint32_t userId, const std::vector &token, const std::vector &secret) { LOGI(""StorageDaemonClient::UnlockUserScreen, userId: %{public}u, token:%{public}d, secret:%{public}d"", userId, token.empty(), secret.empty()); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->UnlockUserScreen(userId, token, secret); } int32_t StorageDaemonClient::GetLockScreenStatus(uint32_t userId, bool &lockScreenStatus) { LOGI(""StorageDaemonClient::GetLockScreenStatus, userId: %{public}u"", userId); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->GetLockScreenStatus(userId, lockScreenStatus); } int32_t StorageDaemonClient::UpdateKeyContext(uint32_t userId, bool needRemoveTmpKey) { LOGI(""StorageDaemonClient::UpdateKeyContext, userId: %{public}u"", userId); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->UpdateKeyContext(userId, needRemoveTmpKey); } int32_t StorageDaemonClient::GenerateAppkey(uint32_t userId, uint32_t hashId, std::string &keyId) { LOGI(""StorageDaemonClient::GenerateAppkey, userId: %{public}u, hashId:%{public}u"", userId, hashId); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->GenerateAppkey(userId, hashId, keyId, false); } int32_t StorageDaemonClient::DeleteAppkey(uint32_t userId, const std::string keyId) { LOGI(""StorageDaemonClient::DeleteAppkey, userId: %{public}u, keyId:%{public}s"", userId, keyId.c_str()); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->DeleteAppkey(userId, keyId); } int32_t StorageDaemonClient::CreateRecoverKey(uint32_t userId, uint32_t userType, const std::vector &token, const std::vector &secret) { LOGI(""StorageDaemonClient::CreateRecoverKey, userId: %{public}u, userType:%{public}u,token:%{public}d,"" ""secret:%{public}d"", userId, userType, token.empty(), secret.empty()); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->CreateRecoverKey(userId, userType, token, secret); } int32_t StorageDaemonClient::SetRecoverKey(const std::vector &key) { LOGI(""StorageDaemonClient::SetRecoverKey, key:%{public}d"", key.empty()); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""get storage daemon service failed""); return E_SA_IS_NULLPTR; } return client->SetRecoverKey(key); } int32_t StorageDaemonClient::MountDfsDocs(int32_t userId, const std::string &relativePath, const std::string &networkId, const std::string &deviceId) { auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""Get StorageDaemon service failed!""); return E_SA_IS_NULLPTR; } return client->MountDfsDocs(userId, relativePath, networkId, deviceId); } int32_t StorageDaemonClient::UMountDfsDocs(int32_t userId, const std::string &relativePath, const std::string &networkId, const std::string &deviceId) { auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""Get StorageDaemon service failed!""); return E_SA_IS_NULLPTR; } return client->UMountDfsDocs(userId, relativePath, networkId, deviceId); } int32_t StorageDaemonClient::FscryptEnable(const std::string &fscryptOptions) { #ifdef USER_CRYPTO_MANAGER int ret = SetFscryptSysparam(fscryptOptions.c_str()); if (ret) { LOGE(""Init fscrypt policy failed ret %{public}d"", ret); return ret; } #endif return 0; } int32_t StorageDaemonClient::GetFileEncryptStatus(uint32_t userId, bool &isEncrypted, bool needCheckDirMount) { LOGI(""StorageDaemonClient::GetFileEncryptStatus, userId:%{public}d"", userId); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""Get StorageDaemon service failed!""); return E_SA_IS_NULLPTR; } return client->GetFileEncryptStatus(userId, isEncrypted, needCheckDirMount); } int32_t StorageDaemonClient::GetUserNeedActiveStatus(uint32_t userId, bool &needActive) { LOGI(""StorageDaemonClient::GetUserNeedActiveStatus, userId:%{public}d"", userId); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""Get StorageDaemon service failed!""); return E_SA_IS_NULLPTR; } return client->GetUserNeedActiveStatus(userId, needActive); } int32_t StorageDaemonClient::MountFileMgrFuse(int32_t userId, const std::string &path, int32_t &fuseFd) { auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""Get StorageDaemon service failed!""); return E_SA_IS_NULLPTR; } return client->MountFileMgrFuse(userId, path, fuseFd); } int32_t StorageDaemonClient::UMountFileMgrFuse(int32_t userId, const std::string &path) { auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""Get StorageDaemon service failed!""); return E_SA_IS_NULLPTR; } return client->UMountFileMgrFuse(userId, path); } int32_t StorageDaemonClient::IsFileOccupied(const std::string &path, const std::vector &inputList, std::vector &outputList, bool &isOccupy) { LOGI(""StorageDaemonClient::IsFileOccupied""); auto status = CheckServiceStatus(STORAGE_SERVICE_FLAG); if (status != E_OK) { LOGE(""service check failed""); return status; } sptr client = GetStorageDaemonProxy(); if (client == nullptr) { LOGE(""Get StorageDaemon service failed!""); return E_SA_IS_NULLPTR; } return client->IsFileOccupied(path, inputList, outputList, isOccupy); } } // namespace StorageDaemon } // namespace OHOS ",serviceFlags 146,"// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This header provides functions to help creating random instaces of the // vehicle routing problem; random capacities and random time windows. #ifndef OR_TOOLS_EXAMPLES_CVRPTW_LIB_H_ #define OR_TOOLS_EXAMPLES_CVRPTW_LIB_H_ #include #include #include ""absl/strings/str_format.h"" #include ""ortools/base/logging.h"" #include ""ortools/base/random.h"" #include ""ortools/constraint_solver/routing.h"" namespace operations_research { typedef std::function RoutingNodeEvaluator2; // Random seed generator. int32_t GetSeed(bool deterministic); // Location container, contains positions of orders and can be used to obtain // Manhattan distances/times between locations. class LocationContainer { public: LocationContainer(int64_t speed, bool use_deterministic_seed); void AddLocation(int64_t x, int64_t y) { locations_.push_back(Location(x, y)); } void AddRandomLocation(int64_t x_max, int64_t y_max); void AddRandomLocation(int64_t x_max, int64_t y_max, int duplicates); int64_t ManhattanDistance(RoutingIndexManager::NodeIndex from, RoutingIndexManager::NodeIndex to) const; int64_t NegManhattanDistance(RoutingIndexManager::NodeIndex from, RoutingIndexManager::NodeIndex to) const; int64_t ManhattanTime(RoutingIndexManager::NodeIndex from, RoutingIndexManager::NodeIndex to) const; bool SameLocation(RoutingIndexManager::NodeIndex node1, RoutingIndexManager::NodeIndex node2) const; int64_t SameLocationFromIndex(int64_t node1, int64_t node2) const; private: class Location { public: Location(); Location(int64_t x, int64_t y); int64_t DistanceTo(const Location& location) const; bool IsAtSameLocation(const Location& location) const; private: static int64_t Abs(int64_t value); int64_t x_; int64_t y_; }; MTRandom randomizer_; const int64_t speed_; absl::StrongVector locations_; }; // Random demand. class RandomDemand { public: RandomDemand(int size, RoutingIndexManager::NodeIndex depot, bool use_deterministic_seed); void Initialize(); int64_t Demand(RoutingIndexManager::NodeIndex from, RoutingIndexManager::NodeIndex to) const; private: std::unique_ptr demand_; const int size_; const RoutingIndexManager::NodeIndex depot_; const bool use_deterministic_seed_; }; // Service time (proportional to demand) + transition time callback. class ServiceTimePlusTransition { public: ServiceTimePlusTransition(int64_t time_per_demand_unit, RoutingNodeEvaluator2 demand, RoutingNodeEvaluator2 transition_time); int64_t Compute(RoutingIndexManager::NodeIndex from, RoutingIndexManager::NodeIndex to) const; private: const int64_t time_per_demand_unit_; RoutingNodeEvaluator2 demand_; RoutingNodeEvaluator2 transition_time_; }; // Stop service time + transition time callback. class StopServiceTimePlusTransition { public: StopServiceTimePlusTransition(int64_t stop_time, const LocationContainer& location_container, RoutingNodeEvaluator2 transition_time); int64_t Compute(RoutingIndexManager::NodeIndex from, RoutingIndexManager::NodeIndex to) const; private: const int64_t stop_time_; const LocationContainer& location_container_; RoutingNodeEvaluator2 demand_; RoutingNodeEvaluator2 transition_time_; }; // Route plan displayer. // TODO(user): Move the display code to the routing library. void DisplayPlan( const operations_research::RoutingIndexManager& manager, const operations_research::RoutingModel& routing, const operations_research::Assignment& plan, bool use_same_vehicle_costs, int64_t max_nodes_per_group, int64_t same_vehicle_cost, const operations_research::RoutingDimension& capacity_dimension, const operations_research::RoutingDimension& time_dimension); using NodeIndex = RoutingIndexManager::NodeIndex; int32_t GetSeed(bool deterministic) { if (deterministic) { return ACMRandom::DeterministicSeed(); } else { return ACMRandom::HostnamePidTimeSeed(); } } LocationContainer::LocationContainer(int64_t speed, bool use_deterministic_seed) : randomizer_(GetSeed(use_deterministic_seed)), speed_(speed) { CHECK_LT(0, speed_); } void LocationContainer::AddRandomLocation(int64_t x_max, int64_t y_max) { AddRandomLocation(x_max, y_max, 1); } void LocationContainer::AddRandomLocation(int64_t x_max, int64_t y_max, int duplicates) { const int64_t x = randomizer_.Uniform(x_max + 1); const int64_t y = randomizer_.Uniform(y_max + 1); for (int i = 0; i < duplicates; ++i) { AddLocation(x, y); } } int64_t LocationContainer::ManhattanDistance(NodeIndex from, NodeIndex to) const { return locations_[from].DistanceTo(locations_[to]); } int64_t LocationContainer::NegManhattanDistance(NodeIndex from, NodeIndex to) const { return -ManhattanDistance(from, to); } int64_t LocationContainer::ManhattanTime(NodeIndex from, NodeIndex to) const { return ManhattanDistance(from, to) / speed_; } bool LocationContainer::SameLocation(NodeIndex node1, NodeIndex node2) const { if (node1 < locations_.size() && node2 < locations_.size()) { return locations_[node1].IsAtSameLocation(locations_[node2]); } return false; } int64_t LocationContainer::SameLocationFromIndex(int64_t node1, int64_t node2) const { // The direct conversion from constraint model indices to routing model // nodes is correct because the depot is node 0. // TODO(user): Fetch proper indices from routing model. return SameLocation(NodeIndex(node1), NodeIndex(node2)); } LocationContainer::Location::Location() : x_(0), y_(0) {} LocationContainer::Location::Location(int64_t x, int64_t y) : x_(x), y_(y) {} int64_t LocationContainer::Location::DistanceTo(const Location& location) const { return Abs(x_ - location.x_) + Abs(y_ - location.y_); } bool LocationContainer::Location::IsAtSameLocation( const Location& location) const { return x_ == location.x_ && y_ == location.y_; } int64_t LocationContainer::Location::Abs(int64_t value) { return std::max(value, -value); } RandomDemand::RandomDemand(int size, NodeIndex depot, bool use_deterministic_seed) : size_(size), depot_(depot), use_deterministic_seed_(use_deterministic_seed) { CHECK_LT(0, size_); } void RandomDemand::Initialize() { const int64_t [MASK] = 5; const int64_t kDemandMin = 1; demand_ = absl::make_unique(size_); MTRandom randomizer(GetSeed(use_deterministic_seed_)); for (int order = 0; order < size_; ++order) { if (order == depot_) { demand_[order] = 0; } else { demand_[order] = kDemandMin + randomizer.Uniform( [MASK] - kDemandMin + 1); } } } int64_t RandomDemand::Demand(NodeIndex from, NodeIndex /*to*/) const { return demand_[from.value()]; } ServiceTimePlusTransition::ServiceTimePlusTransition( int64_t time_per_demand_unit, RoutingNodeEvaluator2 demand, RoutingNodeEvaluator2 transition_time) : time_per_demand_unit_(time_per_demand_unit), demand_(std::move(demand)), transition_time_(std::move(transition_time)) {} int64_t ServiceTimePlusTransition::Compute(NodeIndex from, NodeIndex to) const { return time_per_demand_unit_ * demand_(from, to) + transition_time_(from, to); } StopServiceTimePlusTransition::StopServiceTimePlusTransition( int64_t stop_time, const LocationContainer& location_container, RoutingNodeEvaluator2 transition_time) : stop_time_(stop_time), location_container_(location_container), transition_time_(std::move(transition_time)) {} int64_t StopServiceTimePlusTransition::Compute(NodeIndex from, NodeIndex to) const { return location_container_.SameLocation(from, to) ? 0 : stop_time_ + transition_time_(from, to); } void DisplayPlan( const RoutingIndexManager& manager, const RoutingModel& routing, const operations_research::Assignment& plan, bool use_same_vehicle_costs, int64_t max_nodes_per_group, int64_t same_vehicle_cost, const operations_research::RoutingDimension& capacity_dimension, const operations_research::RoutingDimension& time_dimension) { // Display plan cost. std::string plan_output = absl::StrFormat(""Cost %d\n"", plan.ObjectiveValue()); // Display dropped orders. std::string dropped; for (int64_t order = 0; order < routing.Size(); ++order) { if (routing.IsStart(order) || routing.IsEnd(order)) continue; if (plan.Value(routing.NextVar(order)) == order) { if (dropped.empty()) { absl::StrAppendFormat(&dropped, "" %d"", manager.IndexToNode(order).value()); } else { absl::StrAppendFormat(&dropped, "", %d"", manager.IndexToNode(order).value()); } } } if (!dropped.empty()) { plan_output += ""Dropped orders:"" + dropped + ""\n""; } if (use_same_vehicle_costs) { int group_size = 0; int64_t group_same_vehicle_cost = 0; std::set visited; for (int64_t order = 0; order < routing.Size(); ++order) { if (routing.IsStart(order) || routing.IsEnd(order)) continue; ++group_size; visited.insert(plan.Value(routing.VehicleVar(order))); if (group_size == max_nodes_per_group) { if (visited.size() > 1) { group_same_vehicle_cost += (visited.size() - 1) * same_vehicle_cost; } group_size = 0; visited.clear(); } } if (visited.size() > 1) { group_same_vehicle_cost += (visited.size() - 1) * same_vehicle_cost; } LOG(INFO) << ""Same vehicle costs: "" << group_same_vehicle_cost; } // Display actual output for each vehicle. for (int route_number = 0; route_number < routing.vehicles(); ++route_number) { int64_t order = routing.Start(route_number); absl::StrAppendFormat(&plan_output, ""Route %d: "", route_number); if (routing.IsEnd(plan.Value(routing.NextVar(order)))) { plan_output += ""Empty\n""; } else { while (true) { operations_research::IntVar* const load_var = capacity_dimension.CumulVar(order); operations_research::IntVar* const time_var = time_dimension.CumulVar(order); operations_research::IntVar* const slack_var = routing.IsEnd(order) ? nullptr : time_dimension.SlackVar(order); if (slack_var != nullptr && plan.Contains(slack_var)) { absl::StrAppendFormat( &plan_output, ""%d Load(%d) Time(%d, %d) Slack(%d, %d)"", manager.IndexToNode(order).value(), plan.Value(load_var), plan.Min(time_var), plan.Max(time_var), plan.Min(slack_var), plan.Max(slack_var)); } else { absl::StrAppendFormat(&plan_output, ""%d Load(%d) Time(%d, %d)"", manager.IndexToNode(order).value(), plan.Value(load_var), plan.Min(time_var), plan.Max(time_var)); } if (routing.IsEnd(order)) break; plan_output += "" -> ""; order = plan.Value(routing.NextVar(order)); } plan_output += ""\n""; } } LOG(INFO) << plan_output; } } // namespace operations_research #endif // OR_TOOLS_EXAMPLES_CVRPTW_LIB_H_ ",kDemandMax 147,"// // Copyright (), () 2014-2023 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include ""td/telegram/GiveawayParameters.h"" #include ""td/telegram/AccessRights.h"" #include ""td/telegram/ContactsManager.h"" #include ""td/telegram/Dependencies.h"" #include ""td/telegram/DialogId.h"" #include ""td/telegram/Global.h"" #include ""td/telegram/MessagesManager.h"" #include ""td/telegram/OptionManager.h"" #include ""td/telegram/Td.h"" #include ""td/utils/Random.h"" namespace td { Result GiveawayParameters::get_boosted_channel_id(Td *td, DialogId dialog_id) { if (!td->messages_manager_->have_dialog_force(dialog_id, ""get_boosted_channel_id"")) { return Status::Error(400, ""Chat to boost not found""); } if (dialog_id.get_type() != DialogType::Channel) { return Status::Error(400, ""Can't boost the chat""); } auto channel_id = dialog_id.get_channel_id(); if (!td->contacts_manager_->is_broadcast_channel(channel_id)) { return Status::Error(400, ""Can't boost the group""); } if (!td->contacts_manager_->get_channel_status(channel_id).can_post_messages()) { return Status::Error(400, ""Not enough rights in the chat""); } return channel_id; } Result GiveawayParameters::get_giveaway_parameters( Td *td, const td_api::premiumGiveawayParameters *parameters) { if (parameters == nullptr) { return Status::Error(400, ""Giveaway parameters must be non-empty""); } TRY_RESULT(boosted_channel_id, get_boosted_channel_id(td, DialogId(parameters->boosted_chat_id_))); vector additional_channel_ids; for (auto additional_chat_id : parameters->additional_chat_ids_) { TRY_RESULT(channel_id, get_boosted_channel_id(td, DialogId(additional_chat_id))); additional_channel_ids.push_back(channel_id); } if (static_cast(additional_channel_ids.size()) > td->option_manager_->get_option_integer(""giveaway_additional_chat_count_max"")) { return Status::Error(400, ""Too many additional chats specified""); } if (parameters->winners_selection_date_ < G()->unix_time()) { return Status::Error(400, ""Giveaway date is in the past""); } for (auto &country_code : parameters->country_codes_) { if (country_code.size() != 2 || country_code[0] < 'A' || country_code[0] > 'Z') { return Status::Error(400, ""Invalid country code specified""); } } if (static_cast(parameters->country_codes_.size()) > td->option_manager_->get_option_integer(""giveaway_country_count_max"")) { return Status::Error(400, ""Too many countries specified""); } return GiveawayParameters(boosted_channel_id, std::move(additional_channel_ids), parameters->only_new_members_, parameters->winners_selection_date_, vector(parameters->country_codes_)); } vector GiveawayParameters::get_channel_ids() const { auto result = additional_channel_ids_; result.push_back(boosted_channel_id_); return result; } void GiveawayParameters::add_dependencies(Dependencies &dependencies) const { dependencies.add_dialog_and_dependencies(DialogId(boosted_channel_id_)); for (auto channel_id : additional_channel_ids_) { dependencies.add_dialog_and_dependencies(DialogId(channel_id)); } } telegram_api::object_ptr GiveawayParameters::get_input_store_payment_premium_giveaway(Td *td, const string ¤cy, int64 amount) const { int64 random_id; do { random_id = Random::secure_int64(); } while (random_id == 0); auto boost_input_peer = td->messages_manager_->get_input_peer(DialogId(boosted_channel_id_), AccessRights::Write); CHECK(boost_input_peer != nullptr); vector> [MASK] ; for (auto additional_channel_id : additional_channel_ids_) { auto input_peer = td->messages_manager_->get_input_peer(DialogId(additional_channel_id), AccessRights::Write); CHECK(input_peer != nullptr); [MASK] .push_back(std::move(input_peer)); } int32 flags = 0; if (only_new_subscribers_) { flags |= telegram_api::inputStorePaymentPremiumGiveaway::ONLY_NEW_SUBSCRIBERS_MASK; } if (! [MASK] .empty()) { flags |= telegram_api::inputStorePaymentPremiumGiveaway::ADDITIONAL_PEERS_MASK; } if (!country_codes_.empty()) { flags |= telegram_api::inputStorePaymentPremiumGiveaway::COUNTRIES_ISO2_MASK; } return telegram_api::make_object( flags, false /*ignored*/, std::move(boost_input_peer), std::move( [MASK] ), vector(country_codes_), random_id, date_, currency, amount); } td_api::object_ptr GiveawayParameters::get_premium_giveaway_parameters_object( Td *td) const { CHECK(is_valid()); vector chat_ids; for (auto channel_id : additional_channel_ids_) { DialogId dialog_id(channel_id); td->messages_manager_->force_create_dialog(dialog_id, ""premiumGiveawayParameters"", true); chat_ids.push_back(td->messages_manager_->get_chat_id_object(dialog_id, ""premiumGiveawayParameters"")); } DialogId dialog_id(boosted_channel_id_); td->messages_manager_->force_create_dialog(dialog_id, ""premiumGiveawayParameters"", true); return td_api::make_object( td->messages_manager_->get_chat_id_object(dialog_id, ""premiumGiveawayParameters""), std::move(chat_ids), date_, only_new_subscribers_, vector(country_codes_)); } bool operator==(const GiveawayParameters &lhs, const GiveawayParameters &rhs) { return lhs.boosted_channel_id_ == rhs.boosted_channel_id_ && lhs.additional_channel_ids_ == rhs.additional_channel_ids_ && lhs.only_new_subscribers_ == rhs.only_new_subscribers_ && lhs.date_ == rhs.date_ && lhs.country_codes_ == rhs.country_codes_; } bool operator!=(const GiveawayParameters &lhs, const GiveawayParameters &rhs) { return !(lhs == rhs); } StringBuilder &operator<<(StringBuilder &string_builder, const GiveawayParameters &giveaway_parameters) { return string_builder << ""Giveaway["" << giveaway_parameters.boosted_channel_id_ << "" + "" << giveaway_parameters.additional_channel_ids_ << (giveaway_parameters.only_new_subscribers_ ? "" only for new members"" : """") << "" for countries "" << giveaway_parameters.country_codes_ << "" at "" << giveaway_parameters.date_ << ']'; } } // namespace td ",additional_input_peers 148,"/* author: skottZy date: 2020/11/23 sumarry: test1.cpp version: 2020/11/23 v1 */ #include #include #include using namespace std; const uint32_t n = 1e8; uint32_t sum1(uint32_t n){ uint32_t sum = 0; for (uint32_t i = 1; i <= n; i++) sum += pow(-1, i); return sum; } uint32_t sum2(uint32_t n){ uint32_t sum = 0; if (n % 2 == 0) sum = 0; else sum = -1; return sum; } int main(){ cout << ""starting..."" << endl; time_t startTime, endTime, sumTime; // sum1 startTime = clock(); uint32_t [MASK] = sum1(n); cout << ""sum: "" << [MASK] << endl; endTime = clock(); sumTime = endTime - startTime; cout << ""time: "" << sumTime / 1000 << ""s"" << endl; //sum2 startTime = clock(); uint32_t res2 = sum2(n); cout << ""sum: "" << res2 << endl; endTime = clock(); sumTime = endTime - startTime; cout << ""time: "" << sumTime / 1000 << ""s"" << endl; system(""pause""); return 0; } ",res1 149,"/* * RC-S620/S sample library for Arduino * * Copyright 2010 Sony Corporation */ #include #include #include #include ""RCS620S.h"" /* -------------------------------- * Constant * -------------------------------- */ #define RCS620S_DEFAULT_TIMEOUT 1000 /* -------------------------------- * Variable * -------------------------------- */ /* -------------------------------- * Prototype Declaration * -------------------------------- */ /* -------------------------------- * Macro * -------------------------------- */ /* -------------------------------- * Function * -------------------------------- */ /* ------------------------ * public * ------------------------ */ RCS620S::RCS620S(PinName txd, PinName rxd) : _serial_p(new UnbufferedSerial(txd, rxd, 115200)), _serial(*_serial_p) { this->timeout = RCS620S_DEFAULT_TIMEOUT; } RCS620S::~RCS620S() { if (NULL != _serial_p) delete _serial_p; } int RCS620S::initDevice(void) { int ret; uint8_t response[RCS620S_MAX_RW_RESPONSE_LEN]; uint16_t responseLen; /* RFConfiguration (various timings) */ ret = rwCommand((const uint8_t*)""\xd4\x32\x02\x00\x00\x00"", 6, response, &responseLen); if (!ret || (responseLen != 2) || (memcmp(response, ""\xd5\x33"", 2) != 0)) { return 0; } /* RFConfiguration (max retries) */ ret = rwCommand((const uint8_t*)""\xd4\x32\x05\x00\x00\x00"", 6, response, &responseLen); if (!ret || (responseLen != 2) || (memcmp(response, ""\xd5\x33"", 2) != 0)) { return 0; } /* RFConfiguration (additional wait time = 24ms) */ ret = rwCommand((const uint8_t*)""\xd4\x32\x81\xb7"", 4, response, &responseLen); if (!ret || (responseLen != 2) || (memcmp(response, ""\xd5\x33"", 2) != 0)) { return 0; } return 1; } int RCS620S::polling(uint16_t systemCode) { int ret; uint8_t buf[9]; uint8_t response[RCS620S_MAX_RW_RESPONSE_LEN]; uint16_t responseLen; /* InListPassiveTarget */ memcpy(buf, ""\xd4\x4a\x01\x01\x00\xff\xff\x00\x00"", 9); buf[6] = (uint8_t)((systemCode >> 8) & 0xff); buf[5] = (uint8_t)((systemCode >> 0) & 0xff); ret = rwCommand(buf, 9, response, &responseLen); if (!ret || (responseLen != 22) || (memcmp(response, ""\xd5\x4b\x01\x01\x12\x01"", 6) != 0)) { return 0; } memcpy(this->idm, response + 6, 8); memcpy(this->pmm, response + 14, 8); return 1; } int RCS620S::cardCommand( const uint8_t* command, uint8_t commandLen, uint8_t response[RCS620S_MAX_CARD_RESPONSE_LEN], uint8_t* responseLen) { int ret; uint16_t commandTimeout; uint8_t buf[RCS620S_MAX_RW_RESPONSE_LEN]; uint16_t len; if (this->timeout >= (0x10000 / 2)) { commandTimeout = 0xffff; } else { commandTimeout = (uint16_t)(this->timeout * 2); } /* CommunicateThruEX */ buf[0] = 0xd4; buf[1] = 0xa0; buf[2] = (uint8_t)((commandTimeout >> 0) & 0xff); buf[3] = (uint8_t)((commandTimeout >> 8) & 0xff); buf[4] = (uint8_t)(commandLen + 1); memcpy(buf + 5, command, commandLen); ret = rwCommand(buf, 5 + commandLen, buf, &len); if (!ret || (len < 4) || (buf[0] != 0xd5) || (buf[1] != 0xa1) || (buf[2] != 0x00) || (len != (3 + buf[3]))) { return 0; } *responseLen = (uint8_t)(buf[3] - 1); memcpy(response, buf + 4, *responseLen); return 1; } int RCS620S::rfOff(void) { int ret; uint8_t response[RCS620S_MAX_RW_RESPONSE_LEN]; uint16_t responseLen; /* RFConfiguration (RF field) */ ret = rwCommand((const uint8_t*)""\xd4\x32\x01\x00"", 4, response, &responseLen); if (!ret || (responseLen != 2) || (memcmp(response, ""\xd5\x33"", 2) != 0)) { return 0; } return 1; } int RCS620S::push( const uint8_t* data, uint8_t dataLen) { int ret; uint8_t buf[RCS620S_MAX_CARD_RESPONSE_LEN]; uint8_t responseLen; if (dataLen > 224) { return 0; } /* Push */ buf[0] = 0xb0; memcpy(buf + 1, this->idm, 8); buf[9] = dataLen; memcpy(buf + 10, data, dataLen); ret = cardCommand(buf, 10 + dataLen, buf, &responseLen); if (!ret || (responseLen != 10) || (buf[0] != 0xb1) || (memcmp(buf + 1, this->idm, 8) != 0) || (buf[9] != dataLen)) { return 0; } buf[0] = 0xa4; memcpy(buf + 1, this->idm, 8); buf[9] = 0x00; ret = cardCommand(buf, 10, buf, &responseLen); if (!ret || (responseLen != 10) || (buf[0] != 0xa5) || (memcmp(buf + 1, this->idm, 8) != 0) || (buf[9] != 0x00)) { return 0; } thread_sleep_for(1000); return 1; } /* ------------------------ * private * ------------------------ */ int RCS620S::rwCommand( const uint8_t* command, uint16_t commandLen, uint8_t response[RCS620S_MAX_RW_RESPONSE_LEN], uint16_t* responseLen) { int ret; uint8_t buf[9]; flushSerial(); uint8_t dcs = calcDCS(command, commandLen); /* transmit the command */ buf[0] = 0x00; buf[1] = 0x00; buf[2] = 0xff; if (commandLen <= 255) { /* normal frame */ buf[3] = commandLen; buf[4] = (uint8_t)-buf[3]; writeSerial(buf, 5); } else { /* extended frame */ buf[3] = 0xff; buf[4] = 0xff; buf[5] = (uint8_t)((commandLen >> 8) & 0xff); buf[6] = (uint8_t)((commandLen >> 0) & 0xff); buf[7] = (uint8_t)-(buf[5] + buf[6]); writeSerial(buf, 8); } writeSerial(command, commandLen); buf[0] = dcs; buf[1] = 0x00; writeSerial(buf, 2); /* receive an ACK */ ret = readSerial(buf, 6); if (!ret || (memcmp(buf, ""\x00\x00\xff\x00\xff\x00"", 6) != 0)) { cancel(); return 0; } /* receive a response */ ret = readSerial(buf, 5); if (!ret) { cancel(); return 0; } else if (memcmp(buf, ""\x00\x00\xff"", 3) != 0) { return 0; } if ((buf[3] == 0xff) && (buf[4] == 0xff)) { ret = readSerial(buf + 5, 3); if (!ret || (((buf[5] + buf[6] + buf[7]) & 0xff) != 0)) { return 0; } *responseLen = (((uint16_t)buf[5] << 8) | ((uint16_t)buf[6] << 0)); } else { if (((buf[3] + buf[4]) & 0xff) != 0) { return 0; } *responseLen = buf[3]; } if (*responseLen > RCS620S_MAX_RW_RESPONSE_LEN) { return 0; } ret = readSerial(response, *responseLen); if (!ret) { cancel(); return 0; } dcs = calcDCS(response, *responseLen); ret = readSerial(buf, 2); if (!ret || (buf[0] != dcs) || (buf[1] != 0x00)) { cancel(); return 0; } return 1; } void RCS620S::cancel(void) { /* transmit an ACK */ writeSerial((const uint8_t*)""\x00\x00\xff\x00\xff\x00"", 6); thread_sleep_for(1); flushSerial(); } uint8_t RCS620S::calcDCS( const uint8_t* data, uint16_t len) { uint8_t [MASK] = 0; for (uint16_t i = 0; i < len; i++) { [MASK] += data[i]; } return (uint8_t)-( [MASK] & 0xff); } void RCS620S::writeSerial( const uint8_t* data, uint16_t len) { _serial.write(data, len); } int RCS620S::readSerial( uint8_t* data, uint16_t len) { ssize_t recv, nread = 0; time_t t0 = time(NULL); while (nread < len) { if (checkTimeout(t0)) { return 0; } recv = _serial.read(data, len); data += recv; nread += recv; } return 1; } void RCS620S::flushSerial(void) { } int RCS620S::checkTimeout(unsigned long t0) { time_t t = time(NULL); if ((t - t0) >= this->timeout) { return 1; } return 0; } ",sum 150,"#include""DxLib.h"" #include""main.h"" #include""brast.h"" //プレイヤー int playerbakuImage[BAKU_ANI]; //爆発画像格納用 XY playerbakuPos; //爆発画像の位置 int playerbakuAni; //爆発のアニメーション用 bool playerbakuFlag; //爆発画像の状態 //敵 int enemybakuImage[BAKU_ANI]; //爆発画像格納用 XY enemybakuPos; //爆発画像の位置 int enemybakuAni; //爆発のアニメーション用 bool enemybakuFlag; //爆発画像の状態 void BrastSystemInit(void) { LoadDivGraph(""image/blast.png"", 24, 6, 4, BAKU_SIZE_X, BAKU_SIZE_Y, playerbakuImage); LoadDivGraph(""image/blast.png"", 24, 6, 4, BAKU_SIZE_X, BAKU_SIZE_Y, enemybakuImage); } void PlayerBrastGameInit(XY [MASK] ) { //プレイヤー playerbakuPos.x = [MASK] .x; playerbakuPos.y = [MASK] .y; playerbakuAni = 0; playerbakuFlag = false; } void EnemyBrastGameInit(void) { } void BrastControl(void) { /* // 爆発の表示 if (bakuFlag == true) { DrawGraph(bakuPosX, bakuPosY, bakuImage[bakuAni], true); bakuAni = bakuAni + 1; if (bakuAni >= BAKU_ANI) { bakuAni = 0; bakuFlag = false; } } // 爆発の表示 if (bakuFlag == true) { bakuAni = bakuAni + 1; DrawGraph(bakuPosX, bakuPosY, bakuImage[bakuAni], true); if (bakuAni >= BAKU_ANI) { bakuAni = 0; bakuFlag = false; } } if (!bakuFlag) { bakuAni = 0; bakuPosX = PlayerPosX; bakuPosY = PlayerPosY; } */ } void BrastGameDraw(void) { }",playerPos 151,"/* * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the ""License""). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the ""license"" file accompanying this file. This file 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 ""SampleApp/KeywordObserver.h"" #include //Mohammad add #include ""sock.h"" #include #include #include #include #include #include #include #include #include #include #include #include //const char* books[] = {""War and Peace"", // ""Pride and Prejudice"", // ""The Sound and the Fury""}; // void report(const char* msg, int terminate) { perror(msg); if (terminate) exit(-1); /* failure */ } //Mohammad end namespace alexaClientSDK { namespace sampleApp { capabilityAgents::aip::AudioProvider * static_audioProvider = NULL; void notify_keyword_detection_over_network(avsCommon::avs::AudioInputStream::Index end_index); void send_audio_to_SDK2(); void wait_for_start(){ std::cout<<""wait_for_start [0]\n""; while(1){ while(1){ if(static_audioProvider == NULL){ std::cout<<""static_audioProvider is NULL[1]\n""; break; } if(*(static_audioProvider->MegaMind_StartRecording) == 1){ break; } } if(static_audioProvider == NULL){ std::cout<<""static_audioProvider is NULL[2]\n""; continue; } *(static_audioProvider->MegaMind_StartRecording) = 0; notify_keyword_detection_over_network(0); send_audio_to_SDK2(); *(static_audioProvider->MegaMind_Allowed) = 1; *(static_audioProvider->MegaMind_Desision_Isready) = 1; std::cout<<""should start recording\n""; } } KeywordObserver::KeywordObserver( std::shared_ptr client, capabilityAgents::aip::AudioProvider audioProvider, std::shared_ptr espProvider) : m_client{client}, m_audioProvider{audioProvider}, m_espProvider{espProvider} { static_audioProvider = &m_audioProvider; std::cout<<""before run the wait for start thread\n""; std::thread th2(wait_for_start); th2.detach(); } int continue_to_record; void wait_for_stop(){ // int counter = 0; int option = 1; int fd = socket(AF_INET, /* network versus AF_LOCAL */ SOCK_STREAM, /* reliable, bidirectional: TCP */ 0); /* system picks underlying protocol */ if (fd < 0) report(""socket"", 1); /* terminate */ setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)); /* bind the server's local address in memory */ struct sockaddr_in saddr; memset(&saddr, 0, sizeof(saddr)); /* clear the bytes */ saddr.sin_family = AF_INET; /* versus AF_LOCAL */ saddr.sin_addr.s_addr = htonl(INADDR_ANY); /* host-to-network endian */ saddr.sin_port = htons(PortNumber_stop); /* for listening */ if (bind(fd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) report(""bind"", 1); /* terminate */ /* listen to the socket */ if (listen(fd, MaxConnects) < 0) /* listen for clients, up to MaxConnects */ report(""listen"", 1); /* terminate */ fprintf(stderr, ""Listening on port %i for clients...\n"", PortNumber_stop); int client_fd; while (1) { struct sockaddr_in caddr; /* client address */ int len = sizeof(caddr); /* address length could change */ client_fd = accept(fd, (struct sockaddr*) &caddr,(socklen_t*) &len); /* accept blocks */ if (client_fd < 0) { report(""accept"", 0); /* don't terminated, though there's a problem */ continue; } setsockopt(client_fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)); char buffer[1024]; int count = read(client_fd, buffer, sizeof(buffer)); if (count > 0) { //write(client_fd, buffer, sizeof(buffer)); /* echo as confirmation */ std::cout<h_addrtype != AF_INET) /* versus AF_LOCAL */ report(""bad address family"", 1); /* connect to the server: configure server's address 1st */ struct sockaddr_in saddr; memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = ((struct in_addr*) hptr->h_addr_list[0])->s_addr; saddr.sin_port = htons(PortNumber_start); /* port number in big-endian */ if (connect(sockfd, (struct sockaddr*) &saddr, sizeof(saddr)) < 0) report(""connect"", 1); /* Write some stuff and read the echoes. */ puts(""Connect to server, about to write some stuff...""); uint64_t uend_index = end_index; if (write(sockfd, &uend_index, sizeof(uend_index)) < 0) { std::cout<<""error: could not send the packets\n""; } close(sockfd); /* close the connection */ } void send_audio_to_SDK2(){ int sockfd = socket(AF_INET, /* versus AF_LOCAL */ SOCK_STREAM, /* reliable, bidirectional */ 0); /* system picks protocol (TCP) */ if (sockfd < 0) report(""socket"", 1); /* terminate */ /* get the address of the host */ struct hostent* hptr = gethostbyname(Host); /* localhost: 127.0.0.1 */ if (!hptr) report(""gethostbyname"", 1); /* is hptr NULL? */ if (hptr->h_addrtype != AF_INET) /* versus AF_LOCAL */ report(""bad address family"", 1); /* connect to the server: configure server's address 1st */ struct sockaddr_in saddr; memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = ((struct in_addr*) hptr->h_addr_list[0])->s_addr; saddr.sin_port = htons(PortNumber); /* port number in big-endian */ if (connect(sockfd, (struct sockaddr*) &saddr, sizeof(saddr)) < 0) report(""connect"", 1); puts(""Connect to server, about to write some stuff...""); std::cout<<""Javad: add all the magic here\n""; if(static_audioProvider == NULL){ std::cout<<""MegaMind: static audio provider is NULL\n""; } auto my_stream = static_audioProvider->stream; auto my_reader = my_stream->createReader(avsCommon::avs::AudioInputStream::Reader::Policy::NONBLOCKING); avsCommon::avs::AudioInputStream::Index beginIndex = *(static_audioProvider->MegaMind_begin_index); if(beginIndex == capabilityAgents::aip::AudioInputProcessor::INVALID_INDEX){ beginIndex = my_reader->tell(); } if( !my_reader->seek(beginIndex) ){ std::cout<<""Javad: seek failed""; } int read_words; int total_read_words = 0; int n_words = 10000; int word_size = my_reader->getWordSize(); int size = n_words * word_size; void * buffer; buffer = new char [size]; std::ofstream oFile; oFile.open(""/tmp/oFile.pcm""); continue_to_record = 2; std::thread th1(wait_for_stop); //while(total_read_words < 300000){ while(continue_to_record>0){ memset(buffer, 0 , size); read_words = my_reader->read(buffer,n_words); if( (read_words<0) || (read_words>1000) ){ continue; } //std::cout<<""read_words: ""< stream, std::string keyword, avsCommon::avs::AudioInputStream::Index beginIndex, avsCommon::avs::AudioInputStream::Index endIndex, std::shared_ptr> [MASK] ) { if (endIndex != avsCommon::sdkInterfaces::KeyWordObserverInterface::UNSPECIFIED_INDEX && beginIndex == avsCommon::sdkInterfaces::KeyWordObserverInterface::UNSPECIFIED_INDEX) { if (m_client) { //Mohammad /* fd for the socket */ std::cout<< "" HEYYYY: \t""<notifyOfTapToTalk(m_audioProvider, endIndex); } } else if ( endIndex != avsCommon::sdkInterfaces::KeyWordObserverInterface::UNSPECIFIED_INDEX && beginIndex != avsCommon::sdkInterfaces::KeyWordObserverInterface::UNSPECIFIED_INDEX) { auto espData = capabilityAgents::aip::ESPData::EMPTY_ESP_DATA; if (m_espProvider) { espData = m_espProvider->getESPData(); } if (m_client) { m_client->notifyOfWakeWord(m_audioProvider, beginIndex, endIndex, keyword, espData, [MASK] ); } } } } // namespace sampleApp } // namespace alexaClientSDK ",KWDMetadata 152,"#include ""PixelEngine.h"" void PixelEngine::Reset() { MGravity = 0; MBouncefactor = 0; MUsedPixels = 0; MCollisionDetection = false; MScreen.Clear(); } void PixelEngine::AddPixel(int x, int y, const CRGB& _color, int [MASK] , int _yspeed) { if ( MUsedPixels < MAX_PIXELS ) { PEPixel& pixel = MPixels[MUsedPixels++]; pixel.xpos = x << 8; pixel.ypos = y << 8; pixel.color = _color; pixel.xspeed = [MASK] ; pixel.yspeed = _yspeed; pixel.move = [MASK] != 0 || _yspeed != 0; } } void PixelEngine::Bounce(int& pos, int& speed) { pos -= speed; if ( MBouncefactor ) { if ( speed > 0) { if ( (speed -= MBouncefactor) < 0) speed = 0; } else { if ( (speed += MBouncefactor) > 0) speed = 0; } } speed = -speed; pos += speed; } bool PixelEngine::Move(int& pos, int& speed, const int max) { bool bounced = false; pos += speed; if ( pos < 0x80 || pos > max ) { Bounce(pos, speed); bounced = true; } // Some safety guards. if ( pos < 0x80) pos = 0x80; if ( pos > max) pos = max; return bounced; } void PixelEngine::ExecuteStep() { for ( int pixidx = 0; pixidx < MUsedPixels; pixidx++) { PEPixel& pixel = MPixels[pixidx]; if ( pixel.move ) { int prevx = pixel.xpos; int prevy = pixel.ypos; bool xbounced = Move(pixel.xpos, pixel.xspeed, MMaxx); bool ybounced = Move(pixel.ypos, pixel.yspeed, MMaxy); if ( MCollisionDetection ) { int xpos = pixel.xpos >> 8; int ypos = pixel.ypos >> 8; prevx >>= 8; prevy >>= 8; if ( (prevx != xpos || prevy != ypos) && MScreen.Pixel(xpos, ypos)) // collision { // Check which movement contributed to the colission. if ( !xbounced && prevy == ypos ) Bounce(pixel.xpos, pixel.xspeed); else if ( !ybounced && prevx == xpos ) Bounce(pixel.ypos, pixel.yspeed); else { Bounce(pixel.xpos, pixel.xspeed); Bounce(pixel.ypos, pixel.yspeed); } } } pixel.yspeed -= MGravity; // We have a simple liniair gravity :-) } } } void PixelEngine::Draw() const { for ( int pixidx = 0; pixidx < MUsedPixels; pixidx++) { const PEPixel& pixel = MPixels[pixidx]; // We could support fractions of units and spread them over multiple (max 4?) pixels. MScreen.Pixel(pixel.xpos >> 8, pixel.ypos >> 8) = pixel.color; } } ",_xspeed 153,"#define EIGEN_USE_THREADS #include #include ""../util/ctc_ext_beam_search_decoder.h"" #include ""tensorflow/core/framework/op_kernel.h"" namespace tensorflow { template class CTCExtBeamSearchDecoderOp : public OpKernel { public: explicit CTCExtBeamSearchDecoderOp(OpKernelConstruction *ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr(""merge_repeated"", &merge_repeated_)); OP_REQUIRES_OK(ctx, ctx->GetAttr(""beam_width"", &beam_width_)); OP_REQUIRES_OK(ctx, ctx->GetAttr(""blank_index"", &blank_index_)); OP_REQUIRES_OK(ctx, ctx->GetAttr(""blank_label"", &blank_label_)); OP_REQUIRES_OK(ctx, ctx->GetAttr(""top_paths"", &top_paths_)); } void Compute(OpKernelContext* ctx) override { // Read inputs and allocate outputs const Tensor* inputs; const Tensor* seq_len; OpOutputList dec_indices; OpOutputList dec_values; OpOutputList dec_shape; OpOutputList ali_indices; OpOutputList ali_values; OpOutputList ali_shape; Tensor* log_prob = nullptr; OP_REQUIRES_OK(ctx, ValidateInputsGenerateOutputs(ctx, &inputs, &seq_len, &log_prob, &dec_indices, &dec_values, &dec_shape, &ali_indices, &ali_values, &ali_shape)); // Save variables as specific types auto inputs_t = inputs->tensor(); auto seq_len_t = seq_len->vec(); auto log_prob_t = log_prob->matrix(); log_prob_t.setZero(); // Save shape of inputs and specific input dimensions const TensorShape& inputs_shape = inputs->shape(); const int64 max_time = inputs_shape.dim_size(0); const int64 batch_size = inputs_shape.dim_size(1); const int64 num_classes = inputs_shape.dim_size(2); // For every time step, copy elements into input_list_t std::vector::UnalignedConstMatrix> input_list_t; for (std::size_t t = 0; t < max_time; ++t) { input_list_t.emplace_back(inputs_t.data() + t * batch_size * num_classes, batch_size, num_classes); } // The decoder ctc::CTCExtBeamSearchDecoder decoder(num_classes, blank_index_, beam_width_, &beam_scorer_, blank_label_, 1, merge_repeated_); Tensor input_chip(DataTypeToEnum::v(), TensorShape({num_classes})); auto input_chip_t = input_chip.flat(); // Store results std::vector>> best_paths(batch_size); std::vector>> best_alignments(batch_size); std::vector log_probs; // Iterate over all batch elements for (int b = 0; b < batch_size; ++b) { auto& best_paths_b = best_paths[b]; auto& best_alignments_b = best_alignments[b]; best_paths_b.resize(top_paths_); best_alignments_b.resize(top_paths_); // Iterate over all time steps for (int t = 0; t < seq_len_t(b); ++t) { input_chip_t = input_list_t[t].chip(b, 0); auto input_bi = Eigen::Map>( input_chip_t.data(), num_classes); decoder.Step(input_bi); } // Get top paths OP_REQUIRES_OK( ctx, decoder.TopPaths(top_paths_, &best_paths_b, &best_alignments_b, &log_probs, merge_repeated_)); // beam search Reset decoder.Reset(); // Copy log probs for (int bp = 0; bp < top_paths_; ++bp) { log_prob_t(b, bp) = log_probs[bp]; } } // Store all decoded sequences OP_REQUIRES_OK(ctx, StoreAllDecodedSequences( best_paths, best_alignments, &dec_indices, &dec_values, &dec_shape, &ali_indices, &ali_values, &ali_shape)); } Status ValidateInputsGenerateOutputs(OpKernelContext *ctx, const Tensor** inputs, const Tensor** seq_len, Tensor** log_prob, OpOutputList* dec_indices, OpOutputList* dec_values, OpOutputList* dec_shape, OpOutputList* ali_indices, OpOutputList* ali_values, OpOutputList* ali_shape) const { // Fetch inputs from context Status status = ctx->input(""inputs"", inputs); if (!status.ok()) return status; // Fetch sequence length from context status = ctx->input(""sequence_length"", seq_len); if (!status.ok()) return status; // Fetch shape of inputs const TensorShape& inputs_shape = (*inputs)->shape(); // Throw error if input does not have 3 dims if (inputs_shape.dims() != 3) { return errors::InvalidArgument(""inputs is not a 3-Tensor""); } // Fetch sizes of individual dimensions const int64 max_time = inputs_shape.dim_size(0); const int64 batch_size = inputs_shape.dim_size(1); // Throw error if max time is 0 if (max_time == 0) { return errors::InvalidArgument(""max_time is 0""); } // Throw error if sequence length is not a vector if (!TensorShapeUtils::IsVector((*seq_len)->shape())) { return errors::InvalidArgument(""sequence_length is not a vector""); } // Throw error if dim of sequence length is not the same as batch size if (!(batch_size == (*seq_len)->dim_size(0))) { return errors::FailedPrecondition( ""len(sequence_length) != batch_size. "", ""len(sequence_length): "", (*seq_len)->dim_size(0), "" batch_size: "", batch_size); } // sequence length as int32 vector auto seq_len_t = (*seq_len)->vec(); // Throw error if sequence length is not always less than max time for (int b = 0; b < batch_size; ++b) { if (!(seq_len_t(b) <= max_time)) { return errors::FailedPrecondition(""sequence_length("", b, "") <= "", max_time); } } // Allocate log probability output Status s = ctx->allocate_output(""log_probability"", TensorShape({batch_size, top_paths_}), log_prob); if (!s.ok()) return s; // Allocate list of outputs for decoded s = ctx->output_list(""decoded_indices"", dec_indices); if (!s.ok()) return s; s = ctx->output_list(""decoded_values"", dec_values); if (!s.ok()) return s; s = ctx->output_list(""decoded_shape"", dec_shape); if (!s.ok()) return s; // Allocate list of outputs for alignments s = ctx->output_list(""alignment_indices"", ali_indices); if (!s.ok()) return s; s = ctx->output_list(""alignment_values"", ali_values); if (!s.ok()) return s; s = ctx->output_list(""alignment_shape"", ali_shape); if (!s.ok()) return s; // Return OK return Status::OK(); } // sequences[b][p][ix] stores decoded value ""ix"" of path ""p"" for batch ""b"". Status StoreAllDecodedSequences( const std::vector > >& sequences, const std::vector > >& alignments, OpOutputList* dec_indices, OpOutputList* dec_values, OpOutputList* dec_shape, OpOutputList* ali_indices, OpOutputList* ali_values, OpOutputList* ali_shape) const { // Calculate the total number of entries for each path const int64 batch_size = sequences.size(); std::vector num_entries_dec(top_paths_, 0); std::vector [MASK] (top_paths_, 0); // Calculate num_entries per path for (const auto& batch_s : sequences) { CHECK_EQ(batch_s.size(), top_paths_); for (int p = 0; p < top_paths_; ++p) { num_entries_dec[p] += batch_s[p].size(); } } // Calculate num_entries per alignment for (const auto& batch_s : alignments) { CHECK_EQ(batch_s.size(), top_paths_); for (int p = 0; p < top_paths_; ++p) { [MASK] [p] += batch_s[p].size(); } } for (int p = 0; p < top_paths_; ++p) { Tensor* p_dec_indices = nullptr; Tensor* p_dec_values = nullptr; Tensor* p_dec_shape = nullptr; Tensor* p_ali_indices = nullptr; Tensor* p_ali_values = nullptr; Tensor* p_ali_shape = nullptr; const int64 p_num_dec = num_entries_dec[p]; const int64 p_num_ali = [MASK] [p]; Status s = dec_indices->allocate(p, TensorShape({p_num_dec, 2}), &p_dec_indices); if (!s.ok()) return s; s = dec_values->allocate(p, TensorShape({p_num_dec}), &p_dec_values); if (!s.ok()) return s; s = dec_shape->allocate(p, TensorShape({2}), &p_dec_shape); if (!s.ok()) return s; s = ali_indices->allocate(p, TensorShape({p_num_ali, 2}), &p_ali_indices); if (!s.ok()) return s; s = ali_values->allocate(p, TensorShape({p_num_ali}), &p_ali_values); if (!s.ok()) return s; s = ali_shape->allocate(p, TensorShape({2}), &p_ali_shape); if (!s.ok()) return s; auto dec_indices_t = p_dec_indices->matrix(); auto dec_values_t = p_dec_values->vec(); auto dec_shape_t = p_dec_shape->vec(); auto ali_indices_t = p_ali_indices->matrix(); auto ali_values_t = p_ali_values->vec(); auto ali_shape_t = p_ali_shape->vec(); int64 max_decoded = 0; int64 offset = 0; for (int64 b = 0; b < batch_size; ++b) { auto& p_batch = sequences[b][p]; int64 num_decoded = p_batch.size(); max_decoded = std::max(max_decoded, num_decoded); std::copy_n(p_batch.begin(), num_decoded, &dec_values_t(offset)); for (int64 t = 0; t < num_decoded; ++t, ++offset) { dec_indices_t(offset, 0) = b; dec_indices_t(offset, 1) = t; } } dec_shape_t(0) = batch_size; dec_shape_t(1) = max_decoded; max_decoded = 0; offset = 0; for (int64 b = 0; b < batch_size; ++b) { auto& p_batch = alignments[b][p]; int64 num_decoded = p_batch.size(); max_decoded = std::max(max_decoded, num_decoded); std::copy_n(p_batch.begin(), num_decoded, &ali_values_t(offset)); for (int64 t = 0; t < num_decoded; ++t, ++offset) { ali_indices_t(offset, 0) = b; ali_indices_t(offset, 1) = t; } } ali_shape_t(0) = batch_size; ali_shape_t(1) = max_decoded; } return Status::OK(); } private: typename ctc::CTCExtBeamSearchDecoder::DefaultBeamScorer beam_scorer_; bool merge_repeated_; int beam_width_; int blank_index_; int blank_label_; int top_paths_; TF_DISALLOW_COPY_AND_ASSIGN(CTCExtBeamSearchDecoderOp); }; #define REGISTER_CPU(T) \ REGISTER_KERNEL_BUILDER( \ Name(""CTCExtBeamSearchDecoder"").Device(DEVICE_CPU).TypeConstraint(""T""), \ CTCExtBeamSearchDecoderOp); REGISTER_CPU(float); REGISTER_CPU(double); #undef REGISTER_CPU } // end namespace tensorflow ",num_entries_ali 154,"#include #include #include #include #include #include void printVector(std::vector array){ for (auto v:array){ std::cout << v << "" ""; } std::cout << std::endl; } int next_power_of_two(int v){ v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return v++; } long merge_sort_iterative(std::vector array){ long inversions = 0; int [MASK] = next_power_of_two(array.size()); std::queue> queue; for (auto value:array){ queue.push(std::vector{ value }); } for (int i = array.size(); i <= [MASK] ; i++){ queue.push(std::vector{ std::numeric_limits::max() }); } while (queue.size() > 1){ auto first = queue.front(); queue.pop(); auto second = queue.front(); queue.pop(); std::cout << ""first: ""; printVector(first); std::cout << ""second: ""; printVector(second); int i = 0, j = 0, totalSize = first.size() + second.size(); std::vector sorted; int current; long currentInversions = 0; while (i < first.size() && j < second.size()){ if (first[i] <= second[j]){ current = first[i++]; } else { current = second[j++]; currentInversions += (first.size() - i); } sorted.push_back(current); } while (i < first.size()) { sorted.push_back(first[i++]); } while (j < second.size()) { sorted.push_back(second[j++]); } queue.push(sorted); std::cout << ""inversions: "" << currentInversions << std::endl; std::cout << ""sorted: ""; printVector(sorted); inversions += currentInversions; } std::cout << ""inversions: "" << inversions << std::endl; std::cout << ""sorted: ""; printVector(queue.front()); return inversions; } int main() { // std::vector array = {7, 6, 5, 4, 3, 2, 1 }; // int n = array.size(); int n; std::cin >> n; std::vector array; for (int i = 0; i < n; i++){ int element = 0; //dis(gen); std::cin >> element; array.push_back(element); } long inversionsCount = merge_sort_iterative(array); std::cout << inversionsCount << std::endl; return 0; // int n = 100000; // std::vector array; // std::random_device rd; //Will be used to obtain a seed for the random number engine // std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() // std::uniform_int_distribution<> dis(1, 1000000000); // for (int i = 0; i < n; i++){ // int element = dis(gen); // array.push_back(element); // } // long inversionsCount = merge_sort_iterative(array); // std::cout << inversionsCount << std::endl; // return 0; }",sizeModified 155,"/*************************************************** Library for SensorBoard Feel free to use the code as it is. , Embedded Systems University of Freiburg, Institute of Computer Science ****************************************************/ #include ""SensorBoard.h"" SensorBoard::SensorBoard(Stream * getter, float tempHysteresis, float humHysteresis, int lightHysteresis, float minLEDWatt, float maxLEDWatt, // void (*loadStoreFunc)(bool store, uint8_t *data, size_t size), void (*logFunc)(const char * msg, ...) ): updatePattern{NULL, &updateBlinkPattern, &updateRoundPattern, &updateGlowPattern, &updateActivePowerPattern}, patternUpdateTimes{0, BLINK_STEP, ROUND_STEP, GLOW_STEP, ACTIVE_POWER_UPDATE} { _getter = getter; buttonCB = NULL; PIRCB = NULL; lightCB = NULL; humCB = NULL; tempCB = NULL; fadeUpdate = false; preSet = false; _tempHysteresis = tempHysteresis; _humHysteresis = humHysteresis; _lightHysteresis = lightHysteresis; config.minLEDWatt = minLEDWatt; config.maxLEDWatt = maxLEDWatt; _logFunc = logFunc; // _loadStoreFunc = loadStoreFunc; // Current pattern mainColor = CRGB{255,0,0}; bgColor = CRGB{0,0,0}; currentPattern = LEDPattern::staticPattern; patternTimer = millis(); patternState = INIT_PATTERN; // Old pattern that can be restored oldMainColor = CRGB{255,0,0}; oldBGColor = CRGB{0,0,0}; oldPattern = LEDPattern::numberOfPatterns; patternDuration = -1; patternStartMillis = millis(); } static bool valueValid(float value, float min, float max) { if (isnan(value) || value < min || value > max) return false; return true; } bool SensorBoard::init() { // Note that config must be set prior to calling this function // check if values make sense if (!valueValid(this->config.brightness, 0, 100.0)) this->config.brightness = 50.0; if (!valueValid(this->config.humOffset, -100, 100.0)) this->config.humOffset = 0.0; if (!valueValid(this->config.lightCal, 0, 100.0)) this->config.lightCal = 1.0; if (!valueValid(this->config.maxLEDWatt, 0, 10000.0)) this->config.maxLEDWatt = 200.0; if (!valueValid(this->config.minLEDWatt, 0, 10000.0)) this->config.minLEDWatt = 2.0; if (!valueValid(this->config.tempOffset, -20, 200.0)) this->config.tempOffset = 0.0; // Send ? and wait for answer _getter->println(""??""); // if (_loadStoreFunc) _loadStoreFunc(false, (uint8_t*)&config, sizeof(config)); handle(1000); return this->active; } enum NEW_SENSOR_VALUE SensorBoard::handle(int timeout) { NEW_SENSOR_VALUE avail = NEW_SENSOR_VALUE::NONE; if (timeout > 0) { long start = millis(); while (millis() - start < timeout) { if (_getter->available()) break; } } // if not a valid message if (!(_getter->available())) return avail; // Allow all data to be sent delay(10); // read first char char c = _getter->read(); // If it is not a !, return if (c != '!') return avail; // Parse data c = _getter->read(); if (_logFunc) _logFunc(""Sensor cmd %c"", c); switch (c) { case 'b': { avail = NEW_SENSOR_VALUE::NEW_BTN; BUTTON_PRESS presses = BUTTON_PRESS::PRESS; // Optional single press, double press, long press etc. if (_getter->available()) { char e = _getter->read(); if (e > '0' && e > '9') { presses = (BUTTON_PRESS)(e - '0'); } } if (buttonCB) buttonCB(presses); break; } case 'r': { if (buttonCB) buttonCB(BUTTON_PRESS::RELEASE); break; } case 't': { float temp = parse()+config.tempOffset; if (abs(temp-this->temperature) > _tempHysteresis) { avail = NEW_SENSOR_VALUE::NEW_TEMP; this->temperature = temp; if (tempCB) tempCB(this->temperature); } break; } case 'h': { float hum = parse()+config.humOffset; if (this->humidity > 100) this->humidity = 100; else if (this->humidity < 0) this->humidity = 0; if (abs(hum-this->humidity) > _humHysteresis) { avail = NEW_SENSOR_VALUE::NEW_HUM; this->humidity = hum; if (humCB) humCB(this->humidity); } break; } case 'l': { int lig = (int)((float)(parse())*config.lightCal); if (abs(lig-this->light) > _lightHysteresis) { avail = NEW_SENSOR_VALUE::NEW_LIGHT; this->light = lig; if (lightCB) lightCB(this->light); } break; } case 'p': { bool pir = (uint8_t)_getter->read(); if (pir != this->PIR) { avail = NEW_SENSOR_VALUE::NEW_PIR; this->PIR = pir; if (PIRCB) PIRCB(this->PIR); } break; } case '!': { avail = NEW_SENSOR_VALUE::ACTIVE; this->active = true; break; } // Invalid data default: avail = NEW_SENSOR_VALUE::UNKNOWN; break; } // Flush until newline if (_getter->available()) _getter->readStringUntil('\n'); return avail; } void SensorBoard::setAutoSensorMode(bool on) { if (on) _getter->println(""!a""); else _getter->println(""!o""); this->autoMode = on; } bool SensorBoard::updateSensors(bool wait) { bool success = true; success &= updateLight(wait); success &= updateTemp(wait); success &= updateHum(wait); success &= updatePIR(wait); return success; } bool SensorBoard::updateLight(bool wait) { _getter->println(""?l""); if (wait) return handle(SENSOR_WAIT_TIME) == NEW_SENSOR_VALUE::NEW_LIGHT; else return true; } bool SensorBoard::updateTemp(bool wait) { _getter->println(""?t""); if (wait) return handle(SENSOR_WAIT_TIME) == NEW_SENSOR_VALUE::NEW_TEMP; else return true; } bool SensorBoard::updateHum(bool wait) { _getter->println(""?h""); if (wait) return handle(SENSOR_WAIT_TIME) == NEW_SENSOR_VALUE::NEW_HUM; else return true; } bool SensorBoard::updatePIR(bool wait) { _getter->println(""?p""); if (wait) return handle(SENSOR_WAIT_TIME) == NEW_SENSOR_VALUE::NEW_PIR; else return true; } void SensorBoard::update() { // Handle incoming data if (_getter->available()) handle(); // Update leds updateLEDPattern(); } // _____________________________________LED Stuff__________________________________________________ void SensorBoard::setBrightness(float brightness) { int bright = brightness/100.0*255; if (bright > 255) bright = 255; if (bright < 0) bright = 0; _getter->print(""!b""); _getter->write((uint8_t)bright); _getter->println(); config.brightness = brightness; } void SensorBoard::powerToLEDs(float power) { int normalizes = (int)power; if (normalizes < 0) normalizes = 0; // Power goes from 0 - 3600 max but we say that even 200 Watt is bad and // keep a linear mapping else if (normalizes > config.maxLEDWatt) normalizes = config.maxLEDWatt; uint8_t red = map(normalizes, 0, config.maxLEDWatt, 0, 255); uint8_t green = 255 - red; if (normalizes < config.minLEDWatt) { red = 0; green = 0; } CRGB c = CRGB{red, green, 0}; for (int i = 0; i < NUM_LEDS; i++) { LED[i] = c; } // updateLEDs(); } void SensorBoard::setRainbow(long duration) { LED[2] = COLOR_RED; LED[0] = COLOR_GREEN; LED[1] = COLOR_BLUE; // Make sure timing and saving is done newLEDPattern(LEDPattern::staticPattern, duration, COLOR_BLACK, COLOR_BLACK); updateLEDs(); } void SensorBoard::setDots(int dots, CRGB color, CRGB bgColor, long duration) { for (int i = 0; i < NUM_LEDS; i++) { // its that, because the Layout is // TOP // ______________________________ // | ______________ | // | BTN |LED2 LED0 LED1| | // | |______________| | // | ________ | // | PIR | | | // | | DHT | | // | Light |________| | // LEFT | | RIGHT // | | // | | // | _____ | // | | // | ( O 0 O ) | // | | // | ----- | // | | // |_____________________________| // BOTTOM if (i < dots) LED[(i+2)%NUM_LEDS] = color; else LED[(i+2)%NUM_LEDS] = bgColor; } // Make sure timing and saving is done newLEDPattern(LEDPattern::staticPattern, duration, color, bgColor); updateLEDs(); } void SensorBoard::setDots(int dots, CRGB color, long duration) { setDots(dots, color, COLOR_BLACK, duration); } void SensorBoard::setIndividualColors(CRGB *colors, size_t n, bool fade, long duration) { for (int i=0; i= n) break; LED[i] = colors[i]; } fadeUpdate = fade; // Make sure timing and saving is done newLEDPattern(LEDPattern::staticPattern, duration, COLOR_BLACK, COLOR_BLACK); updateLEDs(); } void SensorBoard::setColor(CRGB color, bool fade) { setColor(color, -1, fade); } void SensorBoard::setColor(CRGB color, int duration) { setColor(color, (long)duration, false); } void SensorBoard::setColor(CRGB color, long duration) { setColor(color, duration, false); } void SensorBoard::setColor(CRGB color, long duration, bool fade) { fadeUpdate = fade; allLEDs(color); // Make sure timing and saving is done newLEDPattern(LEDPattern::staticPattern, duration, color, COLOR_BLACK); updateLEDs(); } void SensorBoard::displayPowerColor(long duration) { newLEDPattern(LEDPattern::activePowerPattern, duration, COLOR_BLACK, COLOR_BLACK); } void SensorBoard::glow(CRGB color, CRGB bgColor, long duration) { newLEDPattern(LEDPattern::glowPattern, duration, color, bgColor); } void SensorBoard::glow(CRGB color, long duration) { newLEDPattern(LEDPattern::glowPattern, duration, color, COLOR_BLACK); } void SensorBoard::blink(CRGB color, CRGB bgColor, long duration) { newLEDPattern(LEDPattern::blinkPattern, duration, color, bgColor); } void SensorBoard::blink(CRGB color, long duration) { newLEDPattern(LEDPattern::blinkPattern, duration, color, COLOR_BLACK); } void SensorBoard::allLEDs(CRGB c) { for (int i = 0; i < NUM_LEDS; i++) LED[i] = c; } void SensorBoard::setAllLEDs(CRGB c) { allLEDs(c); updateLEDs(); } void SensorBoard::newLEDPattern(LEDPattern pattern, long duration, CRGB [MASK] , CRGB theBGColor) { // Save old/current pattern if new duration is not infty and current duration is infty if (patternDuration == -1 and duration != -1) { saveOldPattern(); } // Set new pattern variables patternDuration = duration; currentPattern = pattern; mainColor = [MASK] ; bgColor = theBGColor; // Patern should init patternState = INIT_PATTERN; patternStartMillis = millis(); // Update pattern once patternTimer = millis(); updateLEDPattern(); } void SensorBoard::saveOldPattern() { oldBGColor = bgColor; oldMainColor = mainColor; oldPattern = currentPattern; } void SensorBoard::restoreOldPattern() { bgColor = oldBGColor; mainColor = oldMainColor; currentPattern = oldPattern; // This is not nice but may be not necessary patternState = INIT_PATTERN; // Static pattern needs dedicated update if (oldPattern == LEDPattern::staticPattern) { setAllLEDs(mainColor); } patternTimer = millis(); } void SensorBoard::updateLEDs() { _getter->print(""!L""); for (int l = 0; l < NUM_LEDS; l++) { for (int c = 0; c < 3; c++) _getter->write(LED[l].raw[c]); } if (fadeUpdate) { fadeUpdate = false; _getter->print(""f""); } _getter->println(); } void SensorBoard::updateGlowPattern(SensorBoard* obj) { // on -1 init the glow pattern with black LEDs if (obj->patternState == INIT_PATTERN) { obj->allLEDs(CRGB{0,0,0}); obj->patternState = GLOW_UP; } // Glow to main color here else if (obj->patternState == GLOW_UP) { obj->fadeUpdate = true; obj->fadeTowardColor(obj->mainColor, 8); } // Glow to bg color here else if (obj->patternState == GLOW_DOWN) { obj->fadeUpdate = true; obj->fadeTowardColor(obj->bgColor, 8); } // Check if mainColor is reached then glow back two background color if (obj->LED[0] == obj->mainColor) obj->patternState = GLOW_DOWN; else if (obj->LED[0] == obj->bgColor) obj->patternState = GLOW_UP; } void SensorBoard::updateBlinkPattern(SensorBoard* obj) { // On init start with black color CRGB color = CRGB{0,0,0}; if (obj->patternState == INIT_PATTERN) obj->patternState = BLINK_ONE; // Foreground color is first state else if (obj->patternState == BLINK_ONE) { color = obj->mainColor; obj->patternState = BLINK_TWO; } // Background color is second state else if (obj->patternState == BLINK_TWO) { color = obj->bgColor; obj->patternState = BLINK_ONE; } obj->allLEDs(color); } void SensorBoard::updateActivePowerPattern(SensorBoard* obj) { if (obj->activePowerGetter) { float power = obj->activePowerGetter(); obj->powerToLEDs(power); obj->fadeUpdate = true; } obj->patternState++; } void SensorBoard::updateRoundPattern(SensorBoard* obj) { // On init set all colors to bg color if (obj->patternState == INIT_PATTERN) { obj->allLEDs(obj->bgColor); } else { obj->allLEDs(obj->bgColor); if (obj->patternState >= 0 && obj->patternState < NUM_LEDS) obj->LED[obj->patternState] = obj->mainColor; } obj->patternState++; if (obj->patternState == NUM_LEDS) obj->patternState = 0; } void SensorBoard::updateLEDPattern() { // Check if old pattern needs to be restored if (patternDuration != -1) { if (millis()-patternStartMillis > patternDuration) { restoreOldPattern(); patternStartMillis = millis(); patternDuration = -1; if (_logFunc) { _logFunc(""Reset old pattern: %i, state: %i"", (int)currentPattern, patternState); } } } // precent overflow if (currentPattern >= LEDPattern::numberOfPatterns) return; // Static pattern already updated if (currentPattern == LEDPattern::staticPattern) return; // if pattern with no update time are specified only inititalize if (patternUpdateTimes[(int)currentPattern] == 0 && patternState != INIT_PATTERN) return; // Return if update time not reached or not inited yet if (patternState != INIT_PATTERN && millis() - patternTimer < patternUpdateTimes[(int)currentPattern]) return; // Handle the current pattern updatePattern[(int)currentPattern](this); // Update the timer and the leds if (_logFunc) _logFunc(""Pattern updated""); patternTimer = millis(); updateLEDs(); } void SensorBoard::nblendU8TowardU8(uint8_t& cur, const uint8_t target, uint8_t amount) { if(cur == target) return; if(cur < target) { uint8_t delta = target - cur; delta = (((int)delta * (int)amount) >> 8) + ((delta&&amount)?1:0); // if (delta > amount) delta = amount; cur += delta; } else { uint8_t delta = cur - target; delta = (((int)delta * (int)amount) >> 8) + ((delta&&amount)?1:0); // if (delta > amount) delta = amount; cur -= delta; } } void SensorBoard::fadeTowardColor(const CRGB& bgColor, uint8_t fadeAmount) { for(int i = 0; i < NUM_LEDS; i++) { nblendU8TowardU8(LED[i].red, bgColor.red, fadeAmount); nblendU8TowardU8(LED[i].green, bgColor.green, fadeAmount); nblendU8TowardU8(LED[i].blue, bgColor.blue, fadeAmount); } } template < typename TOut > // TODO Test this! TOut SensorBoard::parse() { TOut value; if (_getter->available() > sizeof(TOut)-1) { uint8_t bytes[sizeof(TOut)] = {}; for (int i = 0; i < sizeof(TOut); i++) { bytes[i] = _getter->read(); } memcpy(&value, &bytes[0], sizeof(value)); } return value; } ",theFGColor 156,"/* * Copyright . All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #ifndef ALDDB_H #define ALDDB_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace alddb { class DynamoDB { public: struct PrimaryKey { public: PrimaryKey(const nlohmann::json& keys) { add_key_json(keys); } PrimaryKey(const std::string& k1_name, const std::string& k1_value) { add_key_string(k1_name.c_str(), k1_value.c_str()); } PrimaryKey(const std::string& k1_name, const std::string& k1_value, const std::string& k2_name, const std::string& k2_value) { add_key_string(k1_name.c_str(), k1_value.c_str()); add_key_string(k2_name.c_str(), k2_value.c_str()); } void add_key_string(Aws::String keyname, Aws::String keyvalue) { Aws::DynamoDB::Model::AttributeValue value; value.SetS(keyvalue); pk.push_back(std::pair(keyname, value)); } void add_key_json(const nlohmann::json& keys) { for (const auto& key : keys.items()) { Aws::DynamoDB::Model::AttributeValue value; value.SetS(key.value()); pk.push_back(std::pair(key.key().c_str(), value)); } } template void add_key_numer(Aws::String keyname, Number keyvalue) { Aws::DynamoDB::Model::AttributeValue value; value.SetN(keyvalue); pk.push_back(std::pair(keyname, value)); } private: std::vector> pk; void set_keys(Aws::DynamoDB::Model::GetItemRequest& req) { for (const auto& key : pk) { req.AddKey(key.first, key.second); } } void set_keys(Aws::DynamoDB::Model::UpdateItemRequest& req) { for (const auto& key : pk) { req.AddKey(key.first, key.second); } } void set_keys(Aws::DynamoDB::Model::DeleteItemRequest& req) { for (const auto& key : pk) { req.AddKey(key.first, key.second); } } friend DynamoDB; }; // Basic Operations static inline void get_item(std::unique_ptr client, const Aws::String& table_name, PrimaryKey& primary_key, nlohmann::json& result_out); static inline bool update_item(std::unique_ptr client, const nlohmann::json& request, const std::string& table, PrimaryKey& primary_key); static inline bool delete_item(std::unique_ptr client, const Aws::String& table_name, PrimaryKey& primary_key); // Put(update) item static inline bool put_item(std::unique_ptr client, const nlohmann::json& request, const std::string& table); // Queries static inline void query_with_expression(std::unique_ptr client, const Aws::String& table_name, const Aws::String& key_name, const Aws::String& expression, const nlohmann::json& expression_values, const Aws::String& projection, nlohmann::json& result_out); // Scan // Rarely, if ever, used. static inline void scan_table_items_dynamo(std::unique_ptr client, const Aws::String& table_name, nlohmann::json& result_out); // Make default client // This will load configuration files from the saved profile // Same as the ones used by the AWS CLI static inline std::unique_ptr make_default_client(); private: static inline void parse_collection(const Aws::Vector>& dynamo_result, nlohmann::json& json_out); static inline void parse_object(const Aws::Map& dynamo_result, nlohmann::json& json_out); static inline nlohmann::json parse_type(Aws::DynamoDB::Model::AttributeValue attr); static inline void compose_type(Aws::DynamoDB::Model::AttributeValue& attr, const nlohmann::json& json); static inline void compose_object(Aws::DynamoDB::Model::AttributeValue& attr, const nlohmann::json& json); static inline Aws::Map build_operation_values(const nlohmann::json& json); static inline Aws::String build_operation_expression(const nlohmann::json& json, const std::string& operation); friend PrimaryKey; }; } // utilities std::unique_ptr alddb::DynamoDB::make_default_client() { Aws::Client::ClientConfiguration clientConfig; auto cli = std::make_unique(clientConfig); return cli; } Aws::String alddb::DynamoDB::build_operation_expression(const nlohmann::json& json, const std::string& operation) { std::stringstream ss; ss << operation << "" ""; for (const auto& item : json.items()) { ss << item.key() << "" = :"" << item.key() << "", ""; } Aws::String expr = ss.str().c_str(); expr.pop_back(); expr.pop_back(); return expr; } Aws::Map alddb::DynamoDB::build_operation_values(const nlohmann::json& json) { Aws::Map object; for (const auto& item : json.items()) { std::pair pair; Aws::DynamoDB::Model::AttributeValue temp_attr; Aws::String p1 = "":""; Aws::String p2 = item.key().c_str(); pair.first = p1 + p2; compose_type(temp_attr, item.value()); pair.second = temp_attr; object.insert(pair); } return object; } // type parsing void alddb::DynamoDB::compose_object(Aws::DynamoDB::Model::AttributeValue& attr, const nlohmann::json& json) { Aws::Map> object; for (const auto& item : json.items()) { std::pair> pair; Aws::DynamoDB::Model::AttributeValue temp_attr; pair.first = item.key().c_str(); compose_type(temp_attr, item.value()); pair.second = Aws::MakeShared("""", temp_attr); object.insert(pair); } attr.SetM(object); } void alddb::DynamoDB::parse_object(const Aws::Map& dynamo_result, nlohmann::json& json_out) { for (const auto& element : dynamo_result) { json_out[element.first.c_str()] = parse_type(element.second); } } nlohmann::json alddb::DynamoDB::parse_type(Aws::DynamoDB::Model::AttributeValue attr) { if (attr.GetType() == Aws::DynamoDB::Model::ValueType::STRING) { return attr.GetS(); } else if (attr.GetType() == Aws::DynamoDB::Model::ValueType::NUMBER) { return attr.GetN(); } else if (attr.GetType() == Aws::DynamoDB::Model::ValueType::BOOL) { return attr.GetBool(); } else if (attr.GetType() == Aws::DynamoDB::Model::ValueType::ATTRIBUTE_MAP) { nlohmann::json json; auto type = attr.GetM(); for (const auto& element : type) { json[element.first.c_str()] = parse_type(*element.second); } return json; } else if (attr.GetType() == Aws::DynamoDB::Model::ValueType::ATTRIBUTE_LIST) { nlohmann::json json = nlohmann::json::array(); auto type = attr.GetL(); for (const auto& element : type) { nlohmann::json obj = parse_type(*element); json.push_back(obj); } return json; } else if (attr.GetType() == Aws::DynamoDB::Model::ValueType::NULLVALUE) { return nullptr; } else { return nullptr; } } void alddb::DynamoDB::compose_type(Aws::DynamoDB::Model::AttributeValue& attr, const nlohmann::json& json) { for (const auto& item : json.items()) { if (item.value().is_number_integer()) { attr.SetN(std::to_string(item.value().get()).c_str()); } else if (item.value().is_number_float()) { attr.SetN(item.value().get()); } else if (item.value().is_string()) { attr.SetS(item.value().get().c_str()); } else if (item.value().is_boolean()) { attr.SetBool(item.value().get()); } else if (item.value().is_array()) { Aws::Vector< std::shared_ptr> array; for (const auto& array_object : item.value().items()) { Aws::DynamoDB::Model::AttributeValue temp_attr; compose_object(temp_attr, array_object.value()); array.push_back(Aws::MakeShared("""", temp_attr)); } attr.SetL(array); } else if (item.value().is_object()) { Aws::Map> object; for (const auto& nested_item : item.value().items()) { std::pair> pair; Aws::DynamoDB::Model::AttributeValue temp_attr; pair.first = nested_item.key().c_str(); compose_type(temp_attr, nested_item.value()); pair.second = Aws::MakeShared("""", temp_attr); object.insert(pair); } attr.SetM(object); } else if (item.value().is_null()) { attr.SetNull(true); } } } void alddb::DynamoDB::parse_collection(const Aws::Vector>& dynamo_result, nlohmann::json& json_out) { json_out = nlohmann::json::array(); for (const auto& object : dynamo_result) { nlohmann::json obj; parse_object(object, obj); json_out.push_back(obj); } } // Operations with a composite key void alddb::DynamoDB::get_item(std::unique_ptr client, const Aws::String& table_name, PrimaryKey& primary_key, nlohmann::json& result_out) { Aws::DynamoDB::Model::GetItemRequest req; // Set up the request req.SetTableName(table_name); // table name // Setup the composite key for the GetItemRequest primary_key.set_keys(req); // Retrieve the item's fields and values const Aws::DynamoDB::Model::GetItemOutcome& result = client->GetItem(req); if (result.IsSuccess()) { parse_object(result.GetResult().GetItem(), result_out); } else { std::cout << ""Failed to get item: "" << result.GetError().GetMessage() << std::endl; } } bool alddb::DynamoDB::update_item(std::unique_ptr client, const nlohmann::json& request, const std::string& table, PrimaryKey& primary_key) { // Define TableName argument Aws::DynamoDB::Model::UpdateItemRequest uir; uir.SetTableName(table.c_str()); primary_key.set_keys(uir); // set expression for SET uir.SetUpdateExpression(build_operation_expression(request, ""SET"")); // Construct attribute value argument uir.SetExpressionAttributeValues(build_operation_values(request)); // Update the item const Aws::DynamoDB::Model::UpdateItemOutcome& result = client->UpdateItem(uir); if (!result.IsSuccess()) { std::cout << result.GetError().GetMessage() << std::endl; return false; } return true; } bool alddb::DynamoDB::delete_item(std::unique_ptr client, const Aws::String& table_name, PrimaryKey& primary_key) { Aws::DynamoDB::Model::DeleteItemRequest req; primary_key.set_keys(req); // Set table name req.SetTableName(table_name); const Aws::DynamoDB::Model::DeleteItemOutcome& result = client->DeleteItem(req); if (result.IsSuccess()) { return true; } else { std::cout << ""Failed to delete item: "" << result.GetError().GetMessage(); return false; } } // Put Item bool alddb::DynamoDB::put_item(std::unique_ptr client, const nlohmann::json& request, const std::string& table) { Aws::DynamoDB::Model::PutItemRequest pir; pir.SetTableName(table.c_str()); // Add body for (const auto& element : request.items()) { Aws::DynamoDB::Model::AttributeValue attribute_value; compose_type(attribute_value, element.value()); pir.AddItem(element.key().c_str(), attribute_value); } const Aws::DynamoDB::Model::PutItemOutcome [MASK] = client->PutItem(pir); if (! [MASK] .IsSuccess()) { std::cout << [MASK] .GetError().GetMessage() << std::endl; return false; } return true; } // Query void alddb::DynamoDB::query_with_expression(std::unique_ptr client, const Aws::String& table_name, const Aws::String& key_name, const Aws::String& expression, const nlohmann::json& expression_values, const Aws::String& projection, nlohmann::json& result_out) { Aws::DynamoDB::Model::QueryRequest query_request; query_request.SetTableName(table_name); if (!key_name.empty()) { query_request.SetIndexName(key_name); } if (!projection.empty()) { query_request.SetProjectionExpression(projection); } query_request.SetKeyConditionExpression(expression); query_request.SetExpressionAttributeValues(build_operation_values(expression_values)); // run the query const Aws::DynamoDB::Model::QueryOutcome& result = client->Query(query_request); if (!result.IsSuccess()) { std::cout << result.GetError().GetMessage() << std::endl; } alddb::DynamoDB::parse_collection(result.GetResult().GetItems(), result_out); } // Scan // Not really recommended since the Adjecency Lists pattern(for which this library is designed) // stores all records in a single table this will will return a huge resultset. void alddb::DynamoDB::scan_table_items_dynamo(std::unique_ptr client, const Aws::String& table_name, nlohmann::json& result_out) { Aws::DynamoDB::Model::ScanRequest scan_request; scan_request.SetTableName(table_name); // run the scan const Aws::DynamoDB::Model::ScanOutcome& result = client->Scan(scan_request); if (!result.IsSuccess()) { std::cout << result.GetError().GetMessage() << std::endl; } DynamoDB::parse_collection(result.GetResult().GetItems(), result_out); } #endif",outcome 157,"#include #include bool func_success() { return true; } bool func_fail() { return false; } int32_t ok() { return 0; } int32_t not_ok() { return 1; } int main() { libfp::RetryMe retry; bool suceeded = retry.ExpectTrue(func_success); std::cout << ""func_success result="" << suceeded << std::endl; bool failed = retry.ExpectTrue(func_fail); std::cout << ""func_fail result="" << failed << std::endl; bool lambda_succeed = retry.ExpectTrue([]() { return 2 == 2; }); std::cout << ""lambda_success result="" << lambda_succeed << std::endl; bool [MASK] = retry.ExpectTrue([]() { return 2 != 2; }); std::cout << ""lambda_fail result="" << [MASK] << std::endl; bool ok_result = retry.ExpectZero(ok); std::cout << ""ok_result="" << ok_result << std::endl; bool not_ok_result = retry.ExpectZero(not_ok); std::cout << ""not_ok_result="" << not_ok_result << std::endl; return 0; } ",lambda_failed 158,"#include #include #include ""rclcpp/rclcpp.hpp"" #include ""keyboard_teleop/KeyboardTeleop.hpp"" using namespace std::chrono_literals; using std::placeholders::_1; KeyboardTeleop::KeyboardTeleop() : Node(""keyboard_teleop"") { RCLCPP_INFO(this->get_logger(), ""Keyboard Teleop node initialized""); _vel_publisher = this->create_publisher(""/cmd_vel"", 10); _keys_subscriber = this->create_subscription(""/keys"", 10, std::bind(&KeyboardTeleop::keysCallback, this, _1)); _key_event_subscriber = this->create_subscription(""/key_event"", 10, std::bind(&KeyboardTeleop::keyEventCallback, this, _1)); _timer = this->create_wall_timer( 50ms, std::bind(&KeyboardTeleop::publishVelocity, this) ); _move_forward = this->declare_parameter(""move_forward_key"", ""W""); _move_backward = this->declare_parameter(""move_backward_key"", ""S""); _move_left = this->declare_parameter(""move_left_key"", ""A""); _move_right = this->declare_parameter(""move_right_key"", ""D""); _rotate_clockwise = this->declare_parameter(""rotate_clockwise_key"", ""E""); _rotate_counter_clockwise = this->declare_parameter(""rotate_counter_clockwise_key"", ""Q""); _turbo = this->declare_parameter(""turbo_key"", ""KEY.SHIFT""); _slow = this->declare_parameter(""slow_key"", ""KEY.ALT""); _increase_linear = this->declare_parameter(""increase_linear_key"", ""KEY.UP""); _decrease_linear = this->declare_parameter(""decrease_linear_key"", ""KEY.DOWN""); _increase_angular = this->declare_parameter(""increase_angular_key"", ""KEY.RIGHT""); _decrease_angular = this->declare_parameter(""decrease_angular_key"", ""KEY.LEFT""); _scale_linear = this->declare_parameter(""scale_linear"", 1.0); _scale_angular = this->declare_parameter(""scale_angular"", 1.0); _k_lin = 0.5; _k_ang = 0.5; std::string msg = ""\n\nReading from the keyboard and Publishing to Twist!\n"" ""---------------------------\n"" ""Moving around:\n"" "" q w e\n"" "" a s d\n"" ""left Shift : 100% of max speed\n"" ""left Alt : 25% of max speed\n"" ""right/left arrows : increase/decrease linear speed by 10%\n"" ""up/down arrows : increase/decrease linear speed by 10%\n"" ""CTRL-C to exit\n""; RCLCPP_INFO(this->get_logger(), ""%s"", msg.c_str()); } KeyboardTeleop::~KeyboardTeleop() { } void KeyboardTeleop::keysCallback(const keyboard_interface::msg::Keys::SharedPtr msg) { double vel_lin_x = 0.0; double vel_lin_y = 0.0; double vel_ang_z = 0.0; bool turbo_pressed = false; bool [MASK] = false; for(auto key : msg->pressed_keys) { if (key.c_str() == _move_forward) vel_lin_x += _scale_linear; else if (key.c_str() == _move_backward) vel_lin_x -= _scale_linear; else if (key.c_str() == _move_left) vel_lin_y += _scale_linear; else if (key.c_str() == _move_right) vel_lin_y -= _scale_linear; else if (key.c_str() == _rotate_clockwise) vel_ang_z -= _scale_angular; else if (key.c_str() == _rotate_counter_clockwise) vel_ang_z += _scale_angular; else if (key.c_str() == _turbo) turbo_pressed = true; else if (key.c_str() == _slow) [MASK] = true; } if (turbo_pressed && ! [MASK] ) { _twist.linear.x = vel_lin_x; _twist.linear.y = vel_lin_y; _twist.angular.z = vel_ang_z; } else if ( [MASK] && !turbo_pressed) { _twist.linear.x = 0.25*vel_lin_x; _twist.linear.y = 0.25*vel_lin_y; _twist.angular.z = 0.25*vel_ang_z; } else { _twist.linear.x = _k_lin*vel_lin_x; _twist.linear.y = _k_lin*vel_lin_y; _twist.angular.z = _k_ang*vel_ang_z; } } void KeyboardTeleop::keyEventCallback(const keyboard_interface::msg::KeyEvent::SharedPtr msg) { bool print_info = true; if (msg->key.c_str() == _increase_linear && !msg->event) _k_lin = std::min(_scale_linear, 1.1*_k_lin); else if (msg->key.c_str() == _decrease_linear && !msg->event) _k_lin = std::max(0.1*_scale_linear, 0.9*_k_lin); else if (msg->key.c_str() == _increase_angular && !msg->event) _k_ang = std::min(_scale_angular, 1.1*_k_ang); else if (msg->key.c_str() == _decrease_angular && !msg->event) _k_ang = std::max(0.1*_scale_angular, 0.9*_k_ang); else print_info = false; if (print_info) RCLCPP_INFO(this->get_logger(), ""Set linear velocity to %.2f and angular velocity to %.2f."", _k_lin, _k_ang); } void KeyboardTeleop::publishVelocity() { _vel_publisher->publish(_twist); } int main(int argc, char **argv) { rclcpp::init(argc, argv); rclcpp::spin(std::make_shared()); rclcpp::shutdown(); return 0; } ",slow_pressed 159,"#include ""VRT.h"" #include ""3rd/glew-2.1.0/GL/glew.h"" #include #define INTENSITY 0.05 const float vertices[] = { -1.0,-1.0,0.0, 1.0,-1.0,0.0, 1.0,1.0,0.0, -1.0,1.0,0.0, }; const UInt indices[] = { 0,1,2, 0,2,3 }; UInt imageSize[] = { 3, 3, 3 }; float imageData[3][3][3] = { {{INTENSITY, 0.0, INTENSITY}, {INTENSITY, 0.0, INTENSITY}, {INTENSITY, 0.0, INTENSITY}}, {{0.0, 0.0, 0.0}, {0.0, INTENSITY, 0.0}, {0.0, 0.0, 0.0}}, {{INTENSITY, 0.0, INTENSITY}, {0.0, 0.0, 0.0}, {INTENSITY, 0.0, INTENSITY}} }; VRT::~VRT() { Finish(); } void VRT::Init() { InitShape(); InitTexture(); InitShader(); InitRenderTarget(); glViewport(0, 0, m_iTargetSize[0], m_iTargetSize[1]); } void VRT::Render() { glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(m_iShader); glBindTextureUnit(0, m_iVolume); glBindVertexArray(m_iVAO); glDrawElements(GL_TRIANGLES, sizeof(indices), GL_UNSIGNED_INT, 0); } void VRT::RenderToTarget(float* _pData, UInt _x, UInt _y) { if (_x > m_iTargetSize[0] && _y > m_iTargetSize[1]) { _pData = nullptr; return; } glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_iFBO); Render(); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glBindFramebuffer(GL_READ_FRAMEBUFFER, m_iFBO); glReadBuffer(GL_COLOR_ATTACHMENT0); glReadPixels(0, 0, m_iTargetSize[0], m_iTargetSize[1], GL_RED, GL_FLOAT, _pData); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); } void VRT::Finish() { glDeleteBuffers(1, &m_iVBO); glDeleteBuffers(1, &m_iEBO); glDeleteVertexArrays(1, &m_iVAO); glDeleteProgram(m_iShader); glDeleteFramebuffers(1, &m_iFBO); glDeleteRenderbuffers(2, m_iRBOs); } void VRT::GetTargetSize(UInt& x, UInt& y) { x = m_iTargetSize[0]; y = m_iTargetSize[1]; } void VRT::InitShape() { //OpenGL 4.5 and above glCreateBuffers(1, &m_iVBO); glNamedBufferData(m_iVBO, sizeof(vertices), vertices, GL_STATIC_DRAW); glCreateBuffers(1, &m_iEBO); glNamedBufferData(m_iEBO, sizeof(indices), indices, GL_STATIC_DRAW); glCreateVertexArrays(1, &m_iVAO); glVertexArrayElementBuffer(m_iVAO, m_iEBO); UInt vaoBindingIndex = 0; glVertexArrayVertexBuffer(m_iVAO, vaoBindingIndex, m_iVBO, 0, 3 * sizeof(float)); UInt [MASK] = 0; glVertexArrayAttribBinding(m_iVAO, [MASK] , vaoBindingIndex); glVertexArrayAttribFormat(m_iVAO, [MASK] , 3, GL_FLOAT, GL_FALSE, 0); glEnableVertexArrayAttrib(m_iVAO, [MASK] ); //OpenGL 4.4 and below /*glGenVertexArrays(1, &m_iVAO); glGenBuffers(1, &m_iVBO); glGenBuffers(1, &m_iEBO); // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). glBindVertexArray(m_iVAO); glBindBuffer(GL_ARRAY_BUFFER, m_iVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iEBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0);*/ } void VRT::InitShader() { const char* vertexShaderSource = ""#version 460 core \n"" ""layout(location = 0) in vec3 aPos; \n"" ""out vec2 texCoord; \n"" ""void main() \n"" ""{ \n"" "" texCoord = vec2(aPos.x + 1.0, aPos.y + 1.0) * 0.5; \n"" "" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); \n"" ""}\n\0""; const char* fragmentShaderSource = ""#version 460 core \n"" ""#define RAY_STEP 10 \n"" ""uniform sampler3D volume; \n"" ""in vec2 texCoord; \n"" ""out vec4 FragColor; \n"" ""void main() \n"" ""{ \n"" "" vec3 StartPos = vec3(texCoord.xy, 0.0); \n"" "" vec3 Step = vec3(0.0, 0.0, 0.1); \n"" "" vec3 CurrentPos = StartPos; \n"" "" float res = 0.0; \n"" "" for (int i = 0; i < 10; i++) \n"" "" { \n"" "" float value = texture(volume, CurrentPos).r; \n"" "" res += value; \n"" "" CurrentPos += Step; \n"" "" } \n"" "" FragColor = vec4(res); \n"" ""}\n\0""; // vertex shader unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); // check for shader compile errors int success; char infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << ""ERROR::SHADER::VERTEX::COMPILATION_FAILED\n"" << infoLog << std::endl; } // fragment shader unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); // check for shader compile errors glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog); std::cout << ""ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n"" << infoLog << std::endl; } // link shaders m_iShader = glCreateProgram(); glAttachShader(m_iShader, vertexShader); glAttachShader(m_iShader, fragmentShader); glLinkProgram(m_iShader); // check for linking errors glGetProgramiv(m_iShader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(m_iShader, 512, NULL, infoLog); std::cout << ""ERROR::SHADER::PROGRAM::LINKING_FAILED\n"" << infoLog << std::endl; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); } void VRT::InitTexture() { glCreateTextures(GL_TEXTURE_3D, 1, &m_iVolume); glTextureStorage3D(m_iVolume, 1, GL_R32F, imageSize[0], imageSize[1], imageSize[2]); glTextureSubImage3D(m_iVolume, 0, 0, 0, 0, imageSize[0], imageSize[1], imageSize[2], GL_RED, GL_FLOAT, imageData); } void VRT::InitRenderTarget() { m_iTargetSize[0] = 512; m_iTargetSize[1] = 512; //render to texture //glCreateTextures(GL_TEXTURE_2D, 1, &m_iRenderTarget); //glTextureStorage2D(m_iRenderTarget, 1, GL_R32F, m_iTargetSize[0], m_iTargetSize[1]); //render to buffer glCreateRenderbuffers(2, m_iRBOs); glNamedRenderbufferStorage(m_iRBOs[0], GL_R32F, m_iTargetSize[0], m_iTargetSize[1]); glNamedRenderbufferStorage(m_iRBOs[1], GL_DEPTH_COMPONENT, m_iTargetSize[0], m_iTargetSize[1]); glCreateFramebuffers(1, &m_iFBO); glNamedFramebufferRenderbuffer(m_iFBO, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_iRBOs[0]); glNamedFramebufferRenderbuffer(m_iFBO, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_iRBOs[1]); }",vaoAttributeSlot 160,"#include using namespace std; int main() { double num1, [MASK] ; //Varibles declaration char op,op2; cout<<""\n\n\t\t\t\""CALCULATOR\""\n\n""; do //Starting point of loop for another calcultion { cout<<""\n\n\t\tEnter First number: ""; cin>>num1; //first input number from user cout<<""\n\t\tEnter Second number: ""; cin>> [MASK] ; //second input number from user do //staring point of loop for wrong input { cout<<""\n\t\tEnter the Type of Operation (+,-,*,/): ""; cin>>op; //operation type input if(op!='+'&&op!='-'&&op!='*'&&op!='/') //if input wrong operation by user cout<<""\n\t\tWrong Input""<>op2; //input for another calcultion }while (op2=='y'||op2=='Y'); //loop will execute again & again till user presses Y for another calculation cout<<""\n\n\t\tTurning Off...""; //if not ,then program will be turned off return 0; } ",num2 161,"#include ""gl_buffer_objects.h"" VertexBuffer::VertexBuffer(const void* data, uint32_t size, GLenum drawMode) { glCreateBuffers(1, &mID); glBindBuffer(GL_ARRAY_BUFFER, mID); glBufferData(GL_ARRAY_BUFFER, size, data, drawMode); } VertexBuffer::VertexBuffer(uint32_t size) { glCreateBuffers(1, &mID); glBindBuffer(GL_ARRAY_BUFFER, mID); glBufferData(GL_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW); } VertexBuffer::~VertexBuffer() { glDeleteBuffers(1, &mID); } void VertexBuffer::Bind() { glBindBuffer(GL_ARRAY_BUFFER, mID); } void VertexBuffer::Unbind() { glBindBuffer(GL_ARRAY_BUFFER, 0); } void VertexBuffer::Delete() { glDeleteBuffers(1, &mID); } void VertexBuffer::SetData(const void* data, uint32_t size, uint32_t [MASK] ) { glBindBuffer(GL_ARRAY_BUFFER, mID); glBufferSubData(GL_ARRAY_BUFFER, [MASK] , size, data); } void VertexBuffer::SetLayout(const std::vector& attributes) { mVertexLayout = attributes; } IndexBuffer::IndexBuffer(uint32_t* data, uint32_t count, GLenum drawMode) { mIndexCount = count; glCreateBuffers(1, &mID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(uint32_t), data, drawMode); } IndexBuffer::~IndexBuffer() { glDeleteBuffers(1, &mID); } void IndexBuffer::Bind() { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mID); } void IndexBuffer::Unbind() { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } void IndexBuffer::Delete() { glDeleteBuffers(1, &mID); } ",offset 162,"#include #include #include #include #include ""..\XMSocket\XMSocket.h"" #pragma comment(lib,""ws2_32.lib"") /* typedef struct _OVERLAPPEDExt{ OVERLAPPED ol; char data[1024]; int iotype; //0, read, 1, write }OVERLAPPEDExt, *LPOVERLAPPEDExt; DWORD WINAPI serverThreadProc(LPVOID lpParameter){ HANDLE hCompletePort = HANDLE(lpParameter); srand(time(NULL)); int id = rand() % 97; printf(""I am thread %d.\n"", id); //while (true){ // Sleep(100); //} DWORD trans; ULONG key; LPOVERLAPPED ol; // OVERLAPPED ol; ::GetQueuedCompletionStatus(hCompletePort, &trans, &key, &ol, INFINITE); printf(""I am thread %d. I get key %lu.\n"", id, key); return 0; } int main(){ printf(""%d%d\n"", sizeof(OVERLAPPED), sizeof(OVERLAPPEDExt)); printf(""%d%d%d\n"", sizeof(ULONG), sizeof(DWORD), sizeof(HANDLE)); WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); HANDLE hCompletePort = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0); DWORD threadId[6]; HANDLE threadHd[6]; for (int i = 0; i < 6; ++i){ threadHd[i] = ::CreateThread(NULL, 0, serverThreadProc, (LPVOID)hCompletePort, 0, &threadId[i]); Sleep(1000); } Sleep(10000); for (int i = 0; i < 6; ++i){ ::PostQueuedCompletionStatus(hCompletePort, 0, i, 0); } for (int i = 0; i < 6; ++i){ WaitForSingleObject(threadHd[i], INFINITE); } printf(""END\n""); getchar(); WSACleanup(); return 0; } */ int main(){ XMSocket::startup(); char buf[1024]; XMSocket [MASK] ; [MASK] .createClient(8888, ""127.0.0.1""); [MASK] .connect(); while (true){ scanf(""%s"", buf); int ret = [MASK] .send(buf, strlen(buf)); printf(""send %3d:%s\n"", ret, buf); ret = [MASK] .recv(buf, 1024); printf(""recv %3d:%s\n"", ret, buf); } XMSocket::cleanup(); printf(""END\n""); getchar(); return 0; }",client 163,"// The author disclaims copyright to this source code. #include ""Debug.h"" Debug* Debug::instance = NULL; Debug* Debug::createInstance(Clock* clk) { if (!instance) { instance = new Debug(clk); } return instance; } Debug* Debug::getInstance() { return instance; } Debug::Debug(Clock* clk) { clock = clk; previousTimestamp = 0; } Debug::~Debug() { } void Debug::setup() { Serial.begin(115200); Debug::getInstance()->debug(""Debug::setup""); } void Debug::debug(String debug) { if (debugEnabled) { Serial.println(timestamps() + "";DEBUG;"" + debug); } } void Debug::info(String info) { if (infoEnabled) { Serial.println(timestamps() + "";INFO;"" + info); } } void Debug::error(String error) { if (errorEnabled) { Serial.println(timestamps() + "";ERROR;"" + error); } } const String Debug::zeroTemplate = ""00000000000000000000""; String Debug::timestamps() { unsigned long now = clock->getTimestamp(); unsigned long relative = now - previousTimestamp; previousTimestamp = now; return fixedLength(now) + "";"" + fixedLength(relative); } String Debug::fixedLength(unsigned long number) { String text = String(number); String maxed = text.substring(0, 10); int padLength = 10 - maxed.length(); String [MASK] = zeroTemplate.substring(0, padLength); String result = [MASK] + maxed; return result; } ",padding 164,"// SPDX-FileCopyrightText: 2022 <> // // SPDX-License-Identifier: MIT #include #include #include #include int main() { // Read an image cv::Mat [MASK] = cv::imread(""../index.jpg"", cv::IMREAD_COLOR); if ( [MASK] .empty()) { std::cerr << ""Error: Could not read the image."" << std::endl; return 1; } // Convert the image to grayscale cv::Mat gray_image; cv::cvtColor( [MASK] , gray_image, cv::COLOR_BGR2GRAY); // Save the grayscale image cv::imwrite(""gray_image.jpg"", gray_image); // Display the input and grayscale images cv::imwrite(""Input Image.jpg"", [MASK] ); cv::imwrite(""Grayscale Image.jpg"", gray_image); // Wait for a key press and close the windows cv::waitKey(0); cv::destroyAllWindows(); return 0; } ",input_image 165,"#include ""MainWindow.h"" #include #include MainWindow::MainWindow(QWidget* parent) : QWidget(parent) { this->setStyleSheet(""QWidget { background: #222244; color: #cccc00; }""); } void MainWindow::paintEvent(QPaintEvent* event) { QStylePainter paint(this); paint.setPen(Qt::NoPen); paint.setRenderHint(QPainter::Antialiasing); QStyleOption opt; opt.initFrom(this); const auto grooveBrush = QColor(""#555555""); const auto backBrush = opt.palette.brush(this->backgroundRole()); const auto foreBrush = opt.palette.brush(this->foregroundRole()); const int thickness = 6; const int minDimension = std::min(opt.rect.width(), opt.rect.height()) - thickness; auto barGrooveRect = QRect{ QPoint{ 0, 0 }, QSize{ minDimension, minDimension } }; barGrooveRect.moveCenter(opt.rect.center()); paint.setBrush(backBrush); paint.drawRect(opt.rect); paint.setBrush(Qt::NoBrush); paint.setPen(QPen(grooveBrush, thickness)); paint.drawEllipse(barGrooveRect); paint.setPen(QPen(foreBrush, thickness)); auto drawProgress = [&paint, barGrooveRect](int fromPromille, int toPromille) { const int [MASK] = 16; // qt считает в 1/16 долях градуса! const int fromDegree = fromPromille * 360 * [MASK] / 1000; const int toDegree = toPromille * 360 * [MASK] / 1000; paint.drawArc(barGrooveRect, 90 * [MASK] - toDegree, toDegree - fromDegree); }; drawProgress(0, 777); } ",qtSpecific 166,"/*------------------------------------------------------------------------- * * orc_wrapper.cpp * An encapsulator for ORC file reader/write functions * * 2020, . * * Contains functions that wrap Apache ORC library functions to be used * by ORC FDW. * * Copyright (c) 2020, Highgo Software Inc. * * IDENTIFICATION * src/orc_wrapper.cpp * *------------------------------------------------------------------------- */ /* ORC FDW header files */ #include #include /* Apache ORC header files */ #include #include /* PostgreSQL and FDW header files */ extern ""C"" { #include ""c.h"" #include ""orc_fdw.h"" } /* Declare the functions to use within this file */ static std::string IsSupportedVersion(ORC_UNIQUE_PTR *p_reader); /* * orcCreateReader * Creates Apache ORC file reader for file in a safe way for fdw. * Creates a reader for the specified filename and stores it in * the unique_ptr in p_reader. */ bool orcCreateReader(std::string filename, ORC_UNIQUE_PTR *p_reader, orc::ReaderOptions &options, bool blnVersionWarn) { /* Let's catch exceptions and throw an error */ try { ORC_UNIQUE_PTR inStream = orc::readLocalFile(filename.c_str()); *p_reader = orc::createReader(std::move(inStream), options); } catch (orc::ParseError& err) { ereport(ERROR, (errmsg(""%s: %s"", ORC_FDW_NAME, err.what()))); } /* Throw a warning for unsupported ORC version */ std::string fileVersion = IsSupportedVersion(p_reader); if (fileVersion.empty() == false && blnVersionWarn ) { ereport(WARNING, (errmsg(""%s: Unsupported ORC file %s version 0.11."", ORC_FDW_NAME, filename.c_str()), (errhint(""This may still work, but it's strongly recommended to use files that are supported by the fdw."")))); } /* *p_reader should never by NULL here, but just in case */ return ((*p_reader) != NULL); } /* * orcCreateRowReader * Creates Apache ORC file row reader in safe way for fdw. */ bool orcCreateRowReader(ORC_UNIQUE_PTR *p_reader, ORC_UNIQUE_PTR *p_rowReader, orc::RowReaderOptions &rowReaderOptions) { *p_rowReader = (*p_reader)->createRowReader(rowReaderOptions); if (*p_rowReader == NULL) { ereport(ERROR, (errmsg(""%s: Unable to create row reader for ORC file."", ORC_FDW_NAME))); } return true; } /* * orcGetNumberOfRows * Returns number of rows in the ORC file. */ uint64_t orcGetNumberOfRows(ORC_UNIQUE_PTR *p_reader) { return (*p_reader)->getNumberOfRows(); } /* * orcGetColsInfo * Get column meta data and return an std::vector of OrcFileColInfo. */ std::vector orcGetColsInfo(std::string [MASK] , ORC_UNIQUE_PTR *p_reader, orc::StructVectorBatch **p_root) { orc::ReaderOptions options; (void) orcCreateReader( [MASK] , p_reader, options, true); orc::RowReaderOptions rowReaderOptions; ORC_UNIQUE_PTR rowReader; (void) orcCreateRowReader(p_reader, &rowReader, rowReaderOptions); /* Check for batch for reading */ ORC_UNIQUE_PTR batch = rowReader->createRowBatch(1); if (batch == NULL) { ereport(ERROR, (errmsg(""%s: Unable to create row batch for reading."", ORC_FDW_NAME))); } /* Get the batch */ *p_root = dynamic_cast(batch.get()); if ((*p_root) == NULL) { ereport(ERROR, (errmsg(""%s: Unable to get batch from ORC file."", ORC_FDW_NAME))); } /* Return column information std::tuple */ return orcGetColsInfo(p_reader, &rowReader, *p_root); } /* * orcGetColsInfo * Fills and returns a vector of tuples with column meta data. */ std::vector orcGetColsInfo(ORC_UNIQUE_PTR *p_reader, ORC_UNIQUE_PTR *p_rowReader, orc::StructVectorBatch *root) { std::vector col_list; // for (uint col_index = 0; col_index < (*p_rowReader)->getSelectedType().getSubtypeCount(); col_index++) for (uint col_index = 0; col_index < root->fields.size(); col_index++) { OrcFileColInfo col; auto orc_col_id = (*p_rowReader)->getSelectedType().getSubtype(col_index)->getColumnId(); col.hasNull = (*p_reader)->getColumnStatistics(orc_col_id)->hasNull(); col.kind = (*p_rowReader)->getSelectedType().getSubtype(col_index)->getKind(); col.max_length = (*p_rowReader)->getSelectedType().getSubtype(col_index)->getMaximumLength(); col.precision = (*p_rowReader)->getSelectedType().getSubtype(col_index)->getPrecision(); col.scale = (*p_rowReader)->getSelectedType().getSubtype(col_index)->getScale(); /* Index must be fixed if the rowReader was created for specific columns */ col.index = col_index; col.name = (*p_rowReader)->getSelectedType().getFieldName(col_index); col_list.push_back(col); } return col_list; } /* * IsSupportedVersion * To be used internally in this file, for a supported version, returns * emptry string otherwise returns the ORC format version of file * as string to be used in an message. */ static std::string IsSupportedVersion(ORC_UNIQUE_PTR *p_reader) { if ((*p_reader)->getFormatVersion() != orc::FileVersion(0, 12)) { return (*p_reader)->getFormatVersion().toString(); } return std::string(""""); } /* * orcGetDefaultDecimalScale * ORC version 0.11 does not define decimal places for a decimal * value. This function handles that. Although we don't support * version 0.11, but having this one additional check improves * 0.11 support in FDW. * * Returns 6 which is the default number of decimal places in * 0.11 version. Otherwise, return empty so that we can pick * number of decimal places from schema. */ int orcGetDefaultDecimalScale(ORC_UNIQUE_PTR *p_reader) { std::string fileVersion = IsSupportedVersion(p_reader); /* Let's assume that it 0.11 */ if (fileVersion.empty() == false) return 6; else return 0; } ",file_pathname 167,"#include ""SelectAminoAcidDialog.h"" #include ""AminoAcidList.h"" #include #include #include ""quizapp.h"" #include #include #include //Text for property type labels const char *propertyTypeLabel[MAX_PROPERTY_TYPES] = { ""Acidic / Basic / Amide / Neutral"", ""Charged / Uncharged"", ""Polar / Nonpolar"", ""Hydrophobic / Hydrophilic"", ""Aromatic / Hydroxyl / Thiol / Aliphatic"", ""No Properties"" }; //Text for image type labels const char *imageTypeLabel[MAX_IMAGE_TYPES] = { ""Space Filling"", ""Ball && Stick"", ""Stick"", ""Wireframe"", ""Structural Formula"" }; //Text for name type labels const char *nameTypeLabel[MAX_NAME_TYPES] = { ""Full Name"", ""Single Letter Name"", ""Three Letter Name"", ""No Name"" }; SelectAminoAcidDialog * SelectAminoAcidDialog::s_instance = nullptr; SelectAminoAcidDialog * SelectAminoAcidDialog::instance(QWidget * parent) { if (!s_instance) s_instance = new SelectAminoAcidDialog(parent); return s_instance; } SelectAminoAcidDialog::SelectAminoAcidDialog(QWidget * parent) : QDialog(parent) { int width = ppp(770); int height = ppp(385); setWindowTitle(""Select Amino Acids""); setGeometry(QRect(ppp(100), ppp(100), width, height)); setMaximumSize(width, height); setMinimumSize(width, height); aAGroupBox = new QGroupBox(this); aAGroupBox->setGeometry(QRect(ppp(10), ppp(10), ppp(410), ppp(330))); aAGroupBox->setTitle(""Select Amino Acids""); choseAAListWidget = new QListWidget(aAGroupBox); choseAAListWidget->setGeometry(QRect(ppp(10), ppp(30), ppp(130), ppp(285))); choseAAListWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); choseAAListWidget->setSortingEnabled(true); addListWidgetItems(); selectedAAListWidget = new QListWidget(aAGroupBox); selectedAAListWidget->setGeometry(QRect(ppp(270), ppp(30), ppp(130), ppp(285))); selectedAAListWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); selectedAAListWidget->setSortingEnabled(true); addAllButton = new QPushButton(""Add All->"", aAGroupBox ); addAllButton->setGeometry(QRect(ppp(150), ppp(85), ppp(110), ppp(25))); QObject::connect(addAllButton, SIGNAL(clicked()), this, SLOT(addAll())); addButton = new QPushButton(""Add->"", aAGroupBox); addButton->setGeometry(QRect(ppp(150), ppp(120), ppp(110), ppp(25))); QObject::connect(addButton, SIGNAL(clicked()), this, SLOT(add())); removeButton = new QPushButton(""<-Remove"", aAGroupBox); removeButton->setGeometry(QRect(ppp(150), ppp(155), ppp(110), ppp(25))); QObject::connect(removeButton, SIGNAL(clicked()), this, SLOT(remove())); removeAllButton = new QPushButton(""<-Remove All"", aAGroupBox); removeAllButton->setGeometry(QRect(ppp(150), ppp(190), ppp(110), ppp(25))); QObject::connect(removeAllButton, SIGNAL(clicked()), this, SLOT(removeAll())); propertiesGroupBox = new QGroupBox( this ); propertiesGroupBox->setGeometry(QRect(ppp(430), ppp(10), ppp(330), ppp(165))); propertiesGroupBox->setTitle(""Select Properties""); for (int x = ppp(10), y = ppp(35), width = ppp(300), height = ppp(15), n = 0; n < MAX_PROPERTY_TYPES; y += ppp(20), ++n) { propertyTypeRadioButton[n] = new QRadioButton(propertyTypeLabel[n], propertiesGroupBox); propertyTypeRadioButton[n]->setGeometry(x, y, width, height); QObject::connect(propertyTypeRadioButton[n], SIGNAL(clicked()), this, SLOT(noProperty())); } propertyTypeRadioButton[0]->setChecked(true); imageTypeGroupBox = new QGroupBox( this ); imageTypeGroupBox->setGeometry(QRect(ppp(430), ppp(185), ppp(160), ppp(156))); imageTypeGroupBox->setTitle(""Image Type""); for (int x = ppp(10), y = ppp(35), width = ppp(145), height = ppp(15), n = 0; n < MAX_IMAGE_TYPES; y += ppp(20), ++n) { imageTypeRadioButton[n] = new QRadioButton(imageTypeLabel[n], imageTypeGroupBox); imageTypeRadioButton[n]->setGeometry(x, y, width, height); } imageTypeRadioButton[0]->setChecked(true); nameTypeGroupBox = new QGroupBox(this); nameTypeGroupBox->setGeometry(QRect(ppp(600), ppp(185), ppp(160), ppp(156))); nameTypeGroupBox->setTitle(""Name Type""); for (int x = ppp(10), y = ppp(35), width = ppp(145), height = ppp(15), n = 0; n < MAX_NAME_TYPES; y += ppp(20), ++n) { nameTypeRadioButton[n] = new QRadioButton(nameTypeLabel[n], nameTypeGroupBox); nameTypeRadioButton[n]->setGeometry(x, y, width, height); QObject::connect(nameTypeRadioButton[n], SIGNAL(clicked()), this, SLOT(noName())); } nameTypeRadioButton[0]->setChecked(true); cancelButton = new QPushButton(""Cancel"", this); cancelButton->setGeometry(QRect(ppp(320), ppp(350), ppp(100), ppp(25))); QObject::connect(cancelButton, SIGNAL(clicked()), this, SLOT(close())); finishButton = new QPushButton(""Finish"", this); finishButton->setGeometry(QRect(ppp(430), ppp(350), ppp(330), ppp(25))); finishButton->setDefault(true); finishButton->setAutoDefault(true); QObject::connect(finishButton, SIGNAL(clicked()), this, SLOT(finish())); propertyTypeChecked[0] = true; for (int i = 1; i < MAX_PROPERTY_TYPES; ++i) propertyTypeChecked[i] = false; imageTypeChecked[0] = true; for (int i = 1; i < MAX_IMAGE_TYPES; ++i) imageTypeChecked[i] = false; nameTypeChecked[0] = true; for (int i = 0; i < MAX_NAME_TYPES; ++i) nameTypeChecked[i] = false; tryingToStudy = false; tryingToTakeQuiz = false; } // Method that adds the amino acids to // the list of Amino Acids to chose from void SelectAminoAcidDialog::addListWidgetItems() { QFile [MASK] ; [MASK] .setFileName((ResourceFolder() + ""Properties.csv"").c_str()); qDebug() << ""opening Properties file "" << [MASK] .fileName(); if (! [MASK] .open( QIODevice::ReadOnly | QIODevice::Text)) QMessageBox::warning(this, ""Invalid Filename"", tr(""Cannot be opened for reading"")); QTextStream in; in.setDevice(& [MASK] ); QString line = in.readLine(); while(!in.atEnd()) { line = in.readLine(); QStringList attributeList = line.split("",""); new QListWidgetItem(tr(""%1"").arg(attributeList.at(0)), choseAAListWidget); chooseFromList << attributeList.at(0); } [MASK] .close(); } // Method called when the Add all button is clicked // Moves all the Amino Acids to the right listbox void SelectAminoAcidDialog::addAll() { int size = choseAAListWidget->count(); for (int i = 0; i < size; ++i) { choseAAListWidget->setCurrentRow(0); QListWidgetItem * currentItem = choseAAListWidget->currentItem(); selectedAAListWidget->addItem(currentItem->text()); choseAAListWidget->takeItem(choseAAListWidget->row(currentItem)); } } // Method called when the add button is clicked. // Moves the selected Amino Acid to the right listbox void SelectAminoAcidDialog::add() { QList selectedItems = choseAAListWidget->selectedItems(); for (int i = 0; i < selectedItems.size(); ++i) { QListWidgetItem * currentItem = selectedItems.at(i); selectedAAListWidget->addItem(currentItem->text()); choseAAListWidget->takeItem(choseAAListWidget->row(currentItem)); } } // Method called when the remove button is clicked. // Moves the selected Amino Acid to the left listbox void SelectAminoAcidDialog::remove() { QList selectedItems = selectedAAListWidget->selectedItems(); for (int i = 0; i < selectedItems.size(); ++i) { QListWidgetItem * currentItem = selectedItems.at(i); choseAAListWidget->addItem(currentItem->text()); selectedAAListWidget->takeItem(selectedAAListWidget->row(currentItem)); } } // Method called when the remove all button is clicked. // Moves the selected Amino Acid to the left listbox void SelectAminoAcidDialog::removeAll() { int size = selectedAAListWidget->count(); for (int i = 0; i < size; ++i) { selectedAAListWidget->setCurrentRow(0); QListWidgetItem * currentItem = selectedAAListWidget->currentItem(); choseAAListWidget->addItem(currentItem->text()); selectedAAListWidget->takeItem(selectedAAListWidget->row(currentItem)); } } // Method called when the No property option is checked. // This mean that the no name option must be disabled void SelectAminoAcidDialog::noProperty() { if (propertyTypeRadioButton[ MAX_PROPERTY_TYPES - 1]->isChecked()) nameTypeRadioButton[MAX_NAME_TYPES - 1]->setEnabled(false); else nameTypeRadioButton[MAX_NAME_TYPES - 1]->setEnabled(true); } // Method called when the No name option is checked. // This mean that the no property option must be disabled void SelectAminoAcidDialog::noName() { if (nameTypeRadioButton[MAX_NAME_TYPES - 1]->isChecked()) propertyTypeRadioButton[MAX_PROPERTY_TYPES - 1]->setEnabled(false); else propertyTypeRadioButton[MAX_PROPERTY_TYPES - 1]->setEnabled(true); } // Method called from the finish function // If the user attempted to take a quiz/test // or study with selecting any amino acids // Then he would be intimated about it and // directed to the select amino acids. So // when he's done selected amino acids then // we'd have to go back showing the user // the quiz opition dialog or study option dialog void SelectAminoAcidDialog::conclude() { // Check if they got here because they tried // to start a quiz/test or study session if (tryingToStudy || tryingToTakeQuiz) { // The whole point of getting here was // to chose amino acids. Check to see // if that has been taken care off. if (isChosenAminoAcids()) { hide(); // Depending on what the user tried to do // before they got here, show them the study // or quiz/test dialog. if (tryingToStudy) { StudyOptionsDialog::instance()->moveToCenter(); StudyOptionsDialog::instance()->exec(); } else { QuizOptionsDialog::instance()->moveToCenter(); QuizOptionsDialog::instance()->exec(); } } else { // if Amino acids were not selected // ask then if the use would like to or not int yesno = QMessageBox::question( this, ""No Amino Acids Selected"", ""There are no Amino Acids selected for studying.\n "" ""Would you like to select Amino Acids now? "", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ); // if not, then reset the flags // and hide the dialog if (yesno == QMessageBox::No) { tryingToStudy = false; tryingToTakeQuiz = false; hide(); } } } else hide(); } // Method called when the finish button is clicked // This method saves the state of the selections // and send the necessary information to other dialogs. void SelectAminoAcidDialog::finish() { chooseFromList.clear(); chosenList.clear(); // save property selection for (int i = 0; i < MAX_PROPERTY_TYPES; ++i) propertyTypeChecked[i] = propertyTypeRadioButton[i]->isChecked(); // save property type selection for (int i = 0; i < MAX_IMAGE_TYPES; ++i) imageTypeChecked[i] = imageTypeRadioButton[i]->isChecked(); // save image type selection for (int i = 0; i < MAX_NAME_TYPES; ++i) nameTypeChecked[i] = nameTypeRadioButton[i]->isChecked(); // save the amino acids that were NOT selected for (int i = 0; i < choseAAListWidget->count(); ++i) { choseAAListWidget->setCurrentRow(i); QListWidgetItem * currentItem = choseAAListWidget->currentItem(); chooseFromList << currentItem->text(); } // clear the list of amino acids to study // for earlier quiz/test or study sessions StudyOptionsDialog::instance()->imagesToStudy.clear(); QuizOptionsDialog::instance()->imagesToStudy.clear(); // save the amino acids that were selected for // for quiz/test or study. Also give this information // to the Quiz and Study dialogs. for (int i = 0; i < selectedAAListWidget->count(); ++i) { selectedAAListWidget->setCurrentRow(i); QListWidgetItem * currentItem = selectedAAListWidget->currentItem(); chosenList << currentItem->text(); StudyOptionsDialog::instance()->imagesToStudy << currentItem->text(); QuizOptionsDialog::instance()->imagesToStudy << currentItem->text(); } // Tell the Quiz and Study dialogs // the type of Image, Name and property setImageType(); setNameType(); setPropertyType(); conclude(); } // Method called when the close button is clicked // Resets all the values to it's original state void SelectAminoAcidDialog::closeEvent(QCloseEvent* e) { for (int i = 0; i < MAX_PROPERTY_TYPES; ++i) propertyTypeRadioButton[i]->setChecked(propertyTypeChecked[i]); for (int i = 0; i < MAX_IMAGE_TYPES; ++i) imageTypeRadioButton[i]->setChecked(imageTypeChecked[i]); for (int i = 0; i < MAX_NAME_TYPES; ++i) nameTypeRadioButton[i]->setChecked(nameTypeChecked[i]); choseAAListWidget->clear(); selectedAAListWidget->clear(); for (int i = 0; i < chooseFromList.size(); ++i) choseAAListWidget->addItem(chooseFromList.at(i)); for (int i = 0; i < chosenList.size(); ++i) selectedAAListWidget->addItem(chosenList.at(i)); conclude(); } // Method called when the Esc button is // pressed. Do nothing, simply ignore void SelectAminoAcidDialog::reject() { } // Method is see if atleast one // Amino acid was chosen bool SelectAminoAcidDialog::isChosenAminoAcids() { if (0 == selectedAAListWidget->count()) return false; return true; } // Method to set the tryingToStudy flag // This will be used later to see if the // was attempting to study before getting here void SelectAminoAcidDialog::setTryingToStudy(bool flag) { tryingToStudy = flag; } // Method to set the tryingToTakeQuiz flag // This will be used later to see if the // was attempting to Quiz before getting here void SelectAminoAcidDialog::setTryingToTakeQuiz(bool flag) { tryingToTakeQuiz = flag; } // Method to set the Image type in the // Quiz/Test or Study sessions. The bg // color is also set->White for structured // formula. Black otherwise void SelectAminoAcidDialog::setImageType() { for (int i = 0; i < MAX_IMAGE_TYPES; ++i) { if (imageTypeChecked[i]) { if (i != 4) { StudyOptionsDialog::instance()->setImageType(imageTypeLabel[i], Qt::black); QuizOptionsDialog::instance()->setImageType(imageTypeLabel[i], Qt::black); } else { StudyOptionsDialog::instance()->setImageType(imageTypeLabel[i], Qt::white); QuizOptionsDialog::instance()->setImageType(imageTypeLabel[i], Qt::white); } break; } } return; } // Method to set the Name type in the // Quiz/Test or Study sessions void SelectAminoAcidDialog::setNameType() { for (int i = 0; i < MAX_NAME_TYPES; ++i) { if (nameTypeChecked[i]) { StudyOptionsDialog::instance()->setNameType(i); QuizOptionsDialog::instance()->setNameType(i); break; } } return; } // Method to set the Property type in the // Quiz/Test or Study sessions void SelectAminoAcidDialog::setPropertyType() { for (int i = 0; i < MAX_PROPERTY_TYPES; ++i) { if (propertyTypeChecked[i]) { StudyOptionsDialog::instance()->setPropertyType(i); QuizOptionsDialog::instance()->setPropertyType(i); break; } } return; } SelectAminoAcidDialog::~SelectAminoAcidDialog() { } ",inFile 168,"#include ""datastore.h"" #include #include #include #include #include DataStore::DataStore() { } DataStore::~DataStore() { } bool DataStore::read(QString filePath) { issues.clear(); QFile loadFile(filePath); if (!loadFile.open(QIODevice::ReadOnly)) { qWarning(""Couldn't open save file.""); return false; } QByteArray saveData = loadFile.readAll(); QJsonDocument loadDoc(QJsonDocument::fromJson(saveData)); projectName = loadDoc.object()[""projectName""].toString(); QJsonArray [MASK] = loadDoc.object()[""issues""].toArray(); for (int i=0; i < [MASK] .size(); i++) { QJsonObject issueObject = [MASK] [i].toObject(); Issue issue; issue.read(issueObject); // QWidget *qw = new QWidget; // QMessageBox::information(qw, QString(""Bla""), issueObject.value(""title"").toString(), QMessageBox::Save); issues.append(issue); } return true; } bool DataStore::write(QString filePath) { QFile saveFile(filePath); if (!saveFile.open(QIODevice::WriteOnly)) { qWarning(""Couldn't open save file.""); return false; } json[""projectName""] = projectName; QJsonArray issueArray; foreach (const Issue issue, issues) { QJsonObject issueObject; issue.write(issueObject); // QWidget *qw = new QWidget; // QMessageBox::information(qw, QString(""Bla""), issueObject.value(""title"").toString(), QMessageBox::Save); issueArray.append(issueObject); } json[""issues""] = issueArray; QJsonDocument saveDoc(json); saveFile.write(saveDoc.toJson()); return true; } ",jsonArray 169,"#include #include #include const byte sinArray[60] = {83, 101, 119, 136, 153, 169, 184, 198, 211, 222, 232, 240, 247, 251, 254, 255, 254, 251, 247, 240, 232, 222, 211, 198, 184, 169, 153, 136, 119, 101, 83, 65, 47, 30, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 30, 47, 65}; const int timeZone = -4; // Eastern Standard Time (USA) int nixieBulbDelayTime = 500; int ledFadeTime = 8; String ZIPCODE = ""*""; String APPID = ""*""; char ssid[] = ""*""; char pass[] = ""*""; char host[] = ""api.openweathermap.org""; int GEIGER_PIN = 5; int GEIGER_LED = 4; int TIME_DATA_IN_PIN = 12; int TIME_CLK_PIN = 13; int TIME_LE_PIN = 0; int TIME_BL_PIN = 2; int STATUS_A_PIN = 14; int STATUS_B_PIN = 15; int STATUS_C_PIN = 16; struct nixieStruct { byte hour1; byte hour2; byte minute1; byte minute2; byte bulbs; }; time_t prevDisplay = 0; // when the digital clock was displayed nixieStruct nixies = {2, 9, 9, 9, 15}; // initialize nixie tubes unsigned int localPort = 2390; // local port to listen for UDP packets IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server 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 incoming and outgoing packets WiFiUDP udp; void drawNixies() { if (now() != prevDisplay) { //update the display only if time has changed prevDisplay = now(); nixies.hour1 = hour() / 10; nixies.hour2 = hour() % 10; nixies.minute1 = minute() / 10; nixies.minute2 = minute() % 10; } int c = 0; //initialize counter digitalWrite(TIME_LE_PIN, LOW); //open shift register latch digitalWrite(TIME_DATA_IN_PIN, LOW); //set next bit low for (c = 0; c < 32; c++) { //push low bit 32 times to clear the register digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); } digitalWrite(TIME_LE_PIN, HIGH); //push latch digitalWrite(TIME_LE_PIN, LOW); //open latch digitalWrite(TIME_DATA_IN_PIN, LOW); //set next bit low for (c = 9; c > nixies.minute2; c--) { digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); } digitalWrite(TIME_DATA_IN_PIN, HIGH); digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); digitalWrite(TIME_DATA_IN_PIN, LOW); for (c; c > 0; c--) { digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); } digitalWrite(TIME_DATA_IN_PIN, LOW); for (c = 9; c > nixies.minute1; c--) { digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); } digitalWrite(TIME_DATA_IN_PIN, HIGH); digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); digitalWrite(TIME_DATA_IN_PIN, LOW); for (c; c > 0; c--) { digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); } digitalWrite(TIME_DATA_IN_PIN, LOW); for (c = 9; c > nixies.hour2; c--) { digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); } digitalWrite(TIME_DATA_IN_PIN, HIGH); digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); digitalWrite(TIME_DATA_IN_PIN, LOW); for (c; c > 0; c--) { digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); } digitalWrite(TIME_DATA_IN_PIN, LOW); if (nixies.hour1 != 0) { for (c = 2; c > nixies.hour1; c--) { digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); } digitalWrite(TIME_DATA_IN_PIN, HIGH); digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); digitalWrite(TIME_DATA_IN_PIN, LOW); for (c; c > 1; c--) { digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); } } else { for (int i = 0; i < 2; i++) { digitalWrite(TIME_CLK_PIN, HIGH); digitalWrite(TIME_CLK_PIN, LOW); } } digitalWrite(TIME_LE_PIN, HIGH); if (nixies.bulbs & 0x01) { // Top Colon digitalWrite(STATUS_A_PIN, LOW); digitalWrite(STATUS_B_PIN, LOW); digitalWrite(STATUS_C_PIN, LOW); delayMicroseconds(nixieBulbDelayTime); } if (nixies.bulbs & 0x02) { // Botton Colon digitalWrite(STATUS_A_PIN, HIGH); digitalWrite(STATUS_B_PIN, LOW); digitalWrite(STATUS_C_PIN, LOW); delayMicroseconds(nixieBulbDelayTime); } if (nixies.bulbs & 0x04) { // Sun digitalWrite(STATUS_A_PIN, LOW); digitalWrite(STATUS_B_PIN, HIGH); digitalWrite(STATUS_C_PIN, HIGH); delayMicroseconds(nixieBulbDelayTime); } if (nixies.bulbs & 0x08) { // Cloud digitalWrite(STATUS_A_PIN, LOW); digitalWrite(STATUS_B_PIN, HIGH); digitalWrite(STATUS_C_PIN, LOW); delayMicroseconds(nixieBulbDelayTime); } if (nixies.bulbs & 0x10) { // Rain digitalWrite(STATUS_A_PIN, LOW); digitalWrite(STATUS_B_PIN, LOW); digitalWrite(STATUS_C_PIN, HIGH); delayMicroseconds(nixieBulbDelayTime); } if (nixies.bulbs & 0x20) { // Snow digitalWrite(STATUS_A_PIN, HIGH); digitalWrite(STATUS_B_PIN, LOW); digitalWrite(STATUS_C_PIN, HIGH); delayMicroseconds(nixieBulbDelayTime); } } time_t getNtpTime() { WiFiClient client; const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.println(""connection failed""); } String url = ""/data/2.5/forecast?zip=""; url += ZIPCODE; url += "",us&APPID=""; url += APPID; url += ""&cnt=3""; Serial.print(""Requesting URL: ""); Serial.println(url); // This will send the request to the server client.print(String(""GET "") + url + "" HTTP/1.1\r\n"" + ""Host: "" + host + ""\r\n"" + ""Connection: close\r\n\r\n""); delay(1000); // Read all the lines of the reply from server and print them to Serial while (client.available()) { String storedRequestString = client.readStringUntil('\r'); if (storedRequestString.charAt(1) == '{') { storedRequestString.remove(0, 1); storedRequestString.remove(storedRequestString.length() - 1); Serial.print(""String: ""); Serial.println(storedRequestString); int index1 = storedRequestString.indexOf(""\""dt\"":""); int index2 = storedRequestString.indexOf(""\""dt\"":"", index1 + 1); int index3 = storedRequestString.indexOf(""\""dt\"":"", index2 + 1); int weatherIndex1 = storedRequestString.indexOf(""\""weather\"":[{\""id\"":"", index1); int weatherIndex2 = storedRequestString.indexOf(""\""weather\"":[{\""id\"":"", index2); int weatherIndex3 = storedRequestString.indexOf(""\""weather\"":[{\""id\"":"", index3); String forecastString1 = storedRequestString.substring(weatherIndex1 + 17, weatherIndex1 + 20); String forecastString2 = storedRequestString.substring(weatherIndex2 + 17, weatherIndex2 + 20); String forecastString3 = storedRequestString.substring(weatherIndex3 + 17, weatherIndex3 + 20); Serial.println(forecastString1); Serial.println(forecastString2); Serial.println(forecastString3); nixies.bulbs &= 3; if (forecastString1.charAt(0) == '6' || forecastString2.charAt(0) == '6' || forecastString3.charAt(0) == '6') { nixies.bulbs |= 0x20; //SNOW Serial.println(""Snow""); } else if (forecastString1.charAt(0) == '5' || forecastString2.charAt(0) == '5' || forecastString3.charAt(0) == '5' || forecastString1.charAt(0) == '3' || forecastString2.charAt(0) == '3' || forecastString3.charAt(0) == '3' || forecastString1.charAt(0) == '2' || forecastString2.charAt(0) == '2' || forecastString3.charAt(0) == '2') { nixies.bulbs |= 0x10; //RAIN Serial.println(""Rain""); } else if ((forecastString1.charAt(0) == '8' || forecastString2.charAt(0) == '8' || forecastString3.charAt(0) == '8') && (forecastString1.charAt(2) != '0' || forecastString2.charAt(2) != '0' || forecastString3.charAt(2) != '0')) { nixies.bulbs |= 0x08; //CLOUDS Serial.println(""Clouds""); } else { nixies.bulbs |= 0x04; //CLEAR Serial.println(""Clear""); } Serial.println(forecastString1); Serial.println(forecastString2); Serial.println(forecastString3); /* const char* sensor = root[""coord""]; const char* time = root[""weather""]; Serial.println(sensor); Serial.println(time); */ } } Serial.println(); Serial.println(""closing connection""); while (udp.parsePacket() > 0) ; // discard any previously received packets Serial.println(""Transmit NTP Request""); sendNTPpacket(timeServer); uint32_t [MASK] = millis(); while (millis() - [MASK] < 1500) { if (!udp.parsePacket()) {} else { Serial.println(""Receive NTP Response""); udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer unsigned long secsSince1900; // convert four bytes starting at location 40 to a long integer secsSince1900 = (unsigned long)packetBuffer[40] << 24; secsSince1900 |= (unsigned long)packetBuffer[41] << 16; secsSince1900 |= (unsigned long)packetBuffer[42] << 8; secsSince1900 |= (unsigned long)packetBuffer[43]; return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR; } } Serial.println(""No NTP Response :-(""); return 0; // return 0 if unable to get the time } void setup() { pinMode(GEIGER_PIN, INPUT); pinMode(GEIGER_LED, OUTPUT); digitalWrite(GEIGER_LED, LOW); pinMode(TIME_DATA_IN_PIN, OUTPUT); digitalWrite(TIME_DATA_IN_PIN, LOW); pinMode(TIME_CLK_PIN, OUTPUT); digitalWrite(TIME_CLK_PIN, LOW); pinMode(TIME_LE_PIN, OUTPUT); digitalWrite(TIME_LE_PIN, HIGH); pinMode(TIME_BL_PIN, OUTPUT); digitalWrite(TIME_BL_PIN, HIGH); pinMode(STATUS_A_PIN, OUTPUT); digitalWrite(STATUS_A_PIN, HIGH); pinMode(STATUS_B_PIN, OUTPUT); digitalWrite(STATUS_B_PIN, HIGH); pinMode(STATUS_C_PIN, OUTPUT); digitalWrite(STATUS_C_PIN, HIGH); drawNixies(); Serial.begin(115200); // We start by connecting to a WiFi network Serial.print(""Connecting to ""); Serial.println(ssid); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("".""); } Serial.println(""""); Serial.println(""WiFi connected""); Serial.println(""IP address: ""); Serial.println(WiFi.localIP()); Serial.println(""Starting UDP""); udp.begin(localPort); Serial.print(""Local port: ""); Serial.println(udp.localPort()); setSyncProvider(getNtpTime); } void loop() { analogWrite(GEIGER_LED, constrain((sin((((millis() / ledFadeTime) % 1024) - 0) * (6.28 - 0.00) / (1024 - 0) + 0.00) + 1.00) * 512.00, 5, 1015)); drawNixies(); } unsigned long sendNTPpacket(IPAddress& address) { // send an NTP request to the time server at the given address Serial.println(""sending NTP 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 // you can send a packet requesting a timestamp: udp.beginPacket(address, 123); //NTP requests are to port 123 udp.write(packetBuffer, NTP_PACKET_SIZE); udp.endPacket(); } ",beginWait 170,"//Hello!, this is a sketch to get remote control to your dragino device by bridge mode //The original source and Pubsubclient code comes from: //https://github.com/knolleary/pubsubclient //this is a modified sketch from those repository // //Hola ! Este es un sketch de prueba para tomar control remoto de su dispositivo dragino en modo bridge //la libreria Pubsubclient.* y el codigo fuente proviene desde: //https://github.com/knolleary/pubsubclient //y este es un sketch modificado desde el repositorio origen y adaptado para funcionar con nuestra //plataforma iot.redlibre.cl #include #include #include #include int out2 = 2; int out3 = 3; int out4 = 4; int out6 = 6; char message_buff[100]; ////Please here paste info from ""devinfo""//////////////// #define IOTUSERNAME ""ioioioioio"" #define IOTPASSWORD """" #define IOTDEVICE ""iiiiiiiii"" #define USERNAME ""uuuuuuuu"" ///////////////////////////////////////////////////////// ////from here dont' modify anything/////////////////////////////////////////////// #define TOPIC ""redlibre/iot/""USERNAME""/""IOTDEVICE""/""IOTUSERNAME""/iot/control/"" #define STATUS ""redlibre/iot/""USERNAME""/""IOTDEVICE""/""IOTUSERNAME""/status/"" #define IOTID USERNAME""/""IOTDEVICE IPAddress server(190, 97, 169, 126); void callback(char* topic, byte* payload, unsigned int length); YunClient ethClient; PubSubClient client(server, 1883, callback, ethClient); void callback(char* topic, byte* payload, unsigned int length) { int i = 0; for(i=0; i 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 #include #include #include #include #include #include ""AboutView.h"" #include ""BuildInfoCore.h"" #include ""ResourceManager.h"" #include ""tools/Tools.h"" namespace terbit { AboutView::AboutView(QWidget *parent) : QDialog(parent) { setWindowTitle(_STR_PRODUCT_NAME); QVBoxLayout* l = new QVBoxLayout(); QVBoxLayout* layoutProduct = new QVBoxLayout(); QHBoxLayout* layoutProductCenter = new QHBoxLayout(); QPixmap [MASK] (ResourceManager::GetLogo()); QLabel* logo = new QLabel(); logo->setPixmap( [MASK] ); logo->setFixedSize( [MASK] .size()); layoutProduct->addWidget(logo); QLabel* lbl = new QLabel(tr(""Version: %1 %2"").arg(_STR_PRODUCT_VERSION).arg(CompilerOptions())); lbl->setTextInteractionFlags(Qt::TextSelectableByMouse); layoutProduct->addWidget(lbl); QString buildId = BUILD_ID_STR; buildId = buildId.left(10); lbl = new QLabel(tr(""Build: %1"").arg(buildId)); lbl->setTextInteractionFlags(Qt::TextSelectableByMouse); layoutProduct->addWidget(lbl); layoutProduct->addSpacing(5); lbl = new QLabel(tr(""Compiler: %1"").arg(CompilerInfo())); lbl->setTextInteractionFlags(Qt::TextSelectableByMouse); layoutProduct->addWidget(lbl); lbl = new QLabel(tr(""Compiled Qt: %1"").arg(QT_VERSION_STR)); lbl->setTextInteractionFlags(Qt::TextSelectableByMouse); layoutProduct->addWidget(lbl); lbl = new QLabel(tr(""Runtime Qt: %1"").arg(qVersion())); lbl->setTextInteractionFlags(Qt::TextSelectableByMouse); layoutProduct->addWidget(lbl); //strech sides to center product info layoutProductCenter->addStretch(1); layoutProductCenter->addLayout(layoutProduct); layoutProductCenter->addStretch(1); l->addSpacing(5); l->addLayout(layoutProductCenter); l->addSpacing(15); QLabel* terbitLink = new QLabel(); //terbitLink->setTextInteractionFlags(Qt::TextSelectableByMouse); terbitLink->setOpenExternalLinks(true); terbitLink->setText(""github terbit-connector""); l->addWidget(terbitLink,0,Qt::AlignCenter); lbl = new QLabel(QString(_STR_LEGAL_COPYRIGHT)); lbl->setTextInteractionFlags(Qt::TextSelectableByMouse); l->addWidget(lbl,0,Qt::AlignCenter); lbl = new QLabel(QString(_STR_LEGAL_TRADE_1)); //lbl->setTextInteractionFlags(Qt::TextSelectableByMouse); lbl->setOpenExternalLinks(true); lbl->setText(""Apache License 2.0""); l->addWidget(lbl,0,Qt::AlignCenter); QDialogButtonBox* b = new QDialogButtonBox(this); b->addButton(QDialogButtonBox::Ok); l->addWidget(b); connect(b, SIGNAL(accepted()), this, SLOT(accept())); setLayout(l); } } ",pix 172,"#pragma once namespace cfa { using namespace std; int CFA::compute_next_vertex() { int vertex; if (mission[id_task].trail.size() - 1 == id_vertex) { vertex = mission[id_task].trail[id_vertex]; if (mission[id_task].take) { request_Mission(); } else { // pubblico un messaggio al view_result e gli dico sono a casa. quando tutti hanno mandato il messaggio scrivo i // risultati e end_simulation. int value = ID_ROBOT; if (value == -1) { value = 0; } // [ID,msg_type,vertex,intention,0] c_print(""ATHOMEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"", red, Pr); std_msgs::Int16MultiArray msg; msg.data.clear(); msg.data.push_back(value); msg.data.push_back(AT_HOME_MSG_TYPE); // results_pub.publish(msg); ros::spinOnce(); at_home = true; } // ^ Importatnte! // mission.clear(); c_print(""id_v: "", id_vertex, "" vertex: "", vertex, magenta); send_task_reached(); id_vertex = 0; } else { vertex = mission[id_task].trail[id_vertex]; c_print(""id_v: "", id_vertex, "" vertex: "", vertex, yellow); id_vertex++; } return vertex; } void CFA::onGoalComplete() { if (next_vertex > -1) { // Update Idleness Table: // update_idleness(); current_vertex = next_vertex; } // devolver proximo vertex tendo em conta apenas as idlenesses; if (!at_home) next_vertex = compute_next_vertex(); else { c_print(""sono a casa!"", yellow, Pr); sendGoal(next_vertex); end_simulation = true; } // next_vertex = compute_next_vertex(); c_print("" @ compute_next_vertex: "", next_vertex, green); // printf(""Move Robot to Vertex %d (%f,%f)\n"", next_vertex, // vertex_web[next_vertex].x, vertex_web[next_vertex].y); /** SEND GOAL (REACHED) AND INTENTION **/ send_goal_reached(); // Send TARGET to monitor send_results(); // Algorithm specific function // Send the goal to the robot (Global Map) ROS_INFO(""Sending goal - Vertex %d (%f,%f)\n"", next_vertex, vertex_web[next_vertex].x, vertex_web[next_vertex].y); // sendGoal(vertex_web[next_vertex].x, vertex_web[next_vertex].y); sendGoal(next_vertex); // send to move_base goal_complete = false; } void CFA::run() { // get ready ready(); c_print(""@ Ready!"", green); // initially clear the costmap (to make sure the robot is not trapped): std_srvs::Empty srv; std::string [MASK] ; if (ID_ROBOT > -1) { std::ostringstream id_string; id_string << ID_ROBOT; [MASK] = ""robot_"" + id_string.str() + ""/""; } [MASK] += ""move_base/clear_costmaps""; if (ros::service::call( [MASK] .c_str(), srv)) { // if (ros::service::call(""move_base/clear_costmaps"", srv)){ ROS_INFO(""Costmap correctly cleared before patrolling task.""); } else { ROS_WARN(""Was not able to clear costmap (%s) before patrolling..."", [MASK] .c_str()); } // Asynch spinner (non-blocking) ros::AsyncSpinner spinner(2); // Use n threads spinner.start(); // ros::waitForShutdown(); /* Run Algorithm */ // init_agent2(); ros::Rate loop_rate(30); // 0.033 seconds or 30Hz while (ros::ok()) { if (goal_complete) { onGoalComplete(); // can be redefined resend_goal_count = 0; } else { // goal not complete (active) if (interference) { do_interference_behavior(); } if (ResendGoal) { ROS_INFO(""Re-Sending goal (%d) - Vertex %d (%f,%f)"", resend_goal_count, next_vertex, vertex_web[next_vertex].x, vertex_web[next_vertex].y); send_resendgoal(); sendGoal(next_vertex); ResendGoal = false; // para nao voltar a entrar (envia goal so uma vez) } processEvents(); if (end_simulation) { return; } } // if (goal_complete) // }// if (initialization) loop_rate.sleep(); } // while ros.ok } }// namesapce cfa",mb_string 173,"#pragma once #include #include #include class StreamUtilities { public: enum class EncodingTypes : u_int8_t { VARINT = 0, I64 = 1, LEN = 2, I32 = 5, INVALID = 10 }; static uint8_t parseVarint(uint8_t* buffer, size_t& result); static size_t getFieldNumber(const size_t fieldVarint); static EncodingTypes getFieldEncodeType(const size_t fieldVarint); private: static const uint8_t ENCODING_TYPE_BIT_LENGTH = 3; }; uint8_t StreamUtilities::parseVarint(uint8_t* buffer, size_t& result) { std::vector byteList; uint8_t offset = 0; while ((*(buffer + offset) & 0x80) == 0x80) { byteList.push_back((*(buffer + offset) & 0x7F)); // strip sign bit offset++; } // add last byte whose sign bit is not set byteList.push_back((*(buffer + offset) & 0x7F)); offset++; result = 0; for (ssize_t i = static_cast(byteList.size() - 1); i >= 0; i--) { // concatenate 7-bit valued bytes result += (static_cast(byteList.at(static_cast(i))) << (7 * i)); } return offset; } size_t StreamUtilities::getFieldNumber(const size_t fieldVarint) { return fieldVarint >> ENCODING_TYPE_BIT_LENGTH; } StreamUtilities::EncodingTypes StreamUtilities::getFieldEncodeType(const size_t fieldVarint) { static const std::map [MASK] { std::make_pair(0, EncodingTypes::VARINT), std::make_pair(1, EncodingTypes::I64), std::make_pair(2, EncodingTypes::LEN), std::make_pair(5, EncodingTypes::I32), }; uint8_t typeAsInt = fieldVarint & ENCODING_TYPE_BIT_LENGTH; if (std::any_of( [MASK] .cbegin(), [MASK] .cend(), [&](const auto& pair) { return pair.first == typeAsInt; })) { return [MASK] .at(typeAsInt); } else { return StreamUtilities::EncodingTypes::INVALID; } }",encodingTypeMap 174,"#ifndef __OCR_UTILS_H__ #define __OCR_UTILS_H__ #include #include ""OcrStruct.h"" #include ""onnxruntime/core/session/onnxruntime_cxx_api.h"" #include #include #include #define TAG ""OcrLite"" #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,TAG,__VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG,__VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG,__VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__) #define __ENABLE_CONSOLE__ false #define Logger(format, ...) {\ if(__ENABLE_CONSOLE__) LOGI(format,##__VA_ARGS__); \ } template static std::unique_ptr makeUnique(Ts &&... params) { return std::unique_ptr(new T(std::forward(params)...)); } template static double getMean(std::vector &input) { auto sum = accumulate(input.begin(), input.end(), 0.0); return sum / input.size(); } template static double getStdev(std::vector &input, double mean) { if (input.size() <= 1) return 0; double accum = 0.0; for_each(input.begin(), input.end(), [&](const double d) { accum += (d - mean) * (d - mean); }); double stdev = sqrt(accum / (input.size() - 1)); return stdev; } template inline T clamp(T x, T [MASK] , T max) { if (x > max) return max; if (x < [MASK] ) return [MASK] ; return x; } double getCurrentTime(); ScaleParam getScaleParam(cv::Mat &src, const float scale); ScaleParam getScaleParam(cv::Mat &src, const int targetSize); cv::RotatedRect getPartRect(std::vector &box, float scaleWidth, float scaleHeight); int getThickness(cv::Mat &boxImg); std::vector getBox(const cv::RotatedRect &rect); void drawTextBox(cv::Mat &boxImg, cv::RotatedRect &rect, int thickness); void drawTextBox(cv::Mat &boxImg, const std::vector &box, int thickness); void drawTextBoxes(cv::Mat &boxImg, std::vector &textBoxes, int thickness); cv::Mat matRotateClockWise180(cv::Mat src); cv::Mat matRotateClockWise90(cv::Mat src); cv::Mat getRotateCropImage(const cv::Mat &src, std::vector box); cv::Mat adjustTargetImg(cv::Mat &src, int dstWidth, int dstHeight); std::vector getMinBoxes(const cv::RotatedRect &boxRect, float &maxSideLen); float boxScoreFast(const std::vector &boxes, const cv::Mat &pred); cv::RotatedRect unClip(std::vector box, float unClipRatio); std::vector substractMeanNormalize(cv::Mat &src, const float *meanVals, const float *normVals); std::vector getAngleIndexes(std::vector &angles); std::vector getInputNames(Ort::Session *session); std::vector getOutputNames(Ort::Session *session); void *getModelDataFromAssets(AAssetManager *mgr, const char *modelName, int &size); std::string jstringTostring(JNIEnv *env, jstring input); #endif //__OCR_UTILS_H__ ",min 175,"/* Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) 2022 https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode You are free to: Share — copy and redistribute the material in any medium or format Adapt — remix, transform, and build upon the material The licensor cannot revoke these freedoms as long as you follow the license terms. Under the following terms: Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made.You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. NonCommercial — You may not use the material for commercial purposes. ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original. No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits. */ #include ""Dataverse.h"" /*! @brief Constructor for Dataverse */ Dataverse::Dataverse(){} // ********************************************************* // Upload a file to a Dataset on a Dataverse // ********************************************************* void Dataverse::UploadToDataverse(byte counter) { Dataverse::UploadToDataverse(0); } // ********************************************************* void Dataverse::UploadToDataverse(byte counter) { if(counter> THIS->MAX_ATTEMPT_REQUESTS) return; //Check WiFi connection status if(WiFi.status() != WL_CONNECTED){ mserial.printStrln(""WiFi Disconnected""); if (connect2WIFInetowrk()){ UploadToDataverse(counter+1); } } bool uploadStatusNotOK=true; if(datasetInfoJson[""data""].containsKey(""id"")){ if(datasetInfoJson[""data""][""id""] !=""""){ String rawResponse = GetInfoFromDataverse(""/api/datasets/""+ datasetInfoJson[""data""][""id""] +""/locks""); const size_t capacity =2*rawResponse.length() + JSON_ARRAY_SIZE(1) + 7*JSON_OBJECT_SIZE(1); DynamicJsonDocument datasetLocksJson(capacity); // Parse JSON object DeserializationError error = deserializeJson(datasetLocksJson, rawResponse); if (error) { mserial.printStr(""unable to retrive dataset lock status. Upload not possible. ERR: ""+error.f_str()); //mserial.printStrln(rawResponse); return; }else{ String stat = datasetInfoJson[""status""]; if(datasetInfoJson.containsKey(""lockType"")){ String locktype = datasetInfoJson[""data""][""lockType""]; mserial.printStrln(""There is a Lock on the dataset: ""+ locktype); mserial.printStrln(""Upload of most recent data is not possible without removal of the lock.""); // Do unlocking }else{ mserial.printStrln(""The dataset is unlocked. Upload possible.""); uploadStatusNotOK=false; } } }else{ mserial.printStrln(""dataset ID is empty. Upload not possible. ""); } }else{ mserial.printStrln(""dataset metadata not loaded. Upload not possible. ""); } if(uploadStatusNotOK){ return; } // Open the dataset file and prepare for binary upload File datasetFile = FFat.open(""/""+EXPERIMENTAL_DATA_FILENAME, FILE_READ); if (!datasetFile){ mserial.printStrln(""Dataset file not found""); return; } String boundary = ""7MA4YWxkTrZu0gW""; String contentType = ""text/csv""; DATASET_REPOSITORY_URL = ""/api/datasets/:persistentId/add?persistentId=""+PERSISTENT_ID; String datasetFileName = datasetFile.name(); String datasetFileSize = String(datasetFile.size()); mserial.printStrln(""Dataset File Details:""); mserial.printStrln(""Filename:"" + datasetFileName); mserial.printStrln(""size (bytes): ""+ datasetFileSize); mserial.printStrln(""""); int str_len = SERVER_URL.length() + 1; // Length (with one extra character for the null terminator) char SERVER_URL_char [str_len]; // Prepare the character array (the buffer) SERVER_URL.toCharArray(SERVER_URL_char, str_len); // Copy it over client.stop(); client.setCACert(HARVARD_ROOT_CA_RSA_SHA1); if (!client.connect(SERVER_URL_char, SERVER_PORT)) { mserial.printStrln(""Cloud server URL connection FAILED!""); mserial.printStrln(SERVER_URL_char); int server_status = client.connected(); mserial.printStrln(""Server status code: "" + String(server_status)); return; } mserial.printStrln(""Connected to the dataverse of Harvard University""); mserial.printStrln(""""); mserial.printStr(""Requesting URL: "" + DATASET_REPOSITORY_URL); // Make a HTTP request and add HTTP headers String postHeader = ""POST "" + DATASET_REPOSITORY_URL + "" HTTP/1.1\r\n""; postHeader += ""Host: "" + SERVER_URL + "":"" + String(SERVER_PORT) + ""\r\n""; postHeader += ""X-Dataverse-key: "" + API_TOKEN + ""\r\n""; postHeader += ""Content-Type: multipart/form-data; boundary="" + boundary + ""\r\n""; postHeader += ""Accept: text/html,application/xhtml+xml,application/xml,application/json;q=0.9,*/*;q=0.8\r\n""; postHeader += ""Accept-Encoding: gzip,deflate\r\n""; postHeader += ""Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n""; postHeader += ""User-Agent: AeonLabs LDAD Smart DAQ device\r\n""; postHeader += ""Keep-Alive: 300\r\n""; postHeader += ""Connection: keep-alive\r\n""; postHeader += ""Accept-Language: en-us\r\n""; // jsonData header String jsonData = ""{\""description\"":\""LIVE Experimental data upload from LDAD Smart 12bit DAQ \"",\""categories\"":[\""Data\""], \""restrict\"":\""false\"", \""tabIngest\"":\""false\""}""; String [MASK] = ""--"" + boundary + ""\r\n""; [MASK] += ""Content-Disposition: form-data; name=\""jsonData\""\r\n\r\n""; [MASK] += jsonData+""\r\n""; // dataset header String datasetHead = ""--"" + boundary + ""\r\n""; datasetHead += ""Content-Disposition: form-data; name=\""file\""; filename=\"""" + datasetFileName + ""\""\r\n""; datasetHead += ""Content-Type: "" + contentType + ""\r\n\r\n""; // request tail String tail = ""\r\n--"" + boundary + ""--\r\n\r\n""; // content length int contentLength = [MASK] .length() + datasetHead.length() + datasetFile.size() + tail.length(); postHeader += ""Content-Length: "" + String(contentLength, DEC) + ""\n\n""; // send post header int postHeader_len=postHeader.length() + 1; char charBuf0[postHeader_len]; postHeader.toCharArray(charBuf0, postHeader_len); client.print(charBuf0); mserial.printStr(charBuf0); // send key header char charBufKey[ [MASK] .length() + 1]; [MASK] .toCharArray(charBufKey, [MASK] .length() + 1); client.print(charBufKey); mserial.printStr(charBufKey); // send request buffer char charBuf1[datasetHead.length() + 1]; datasetHead.toCharArray(charBuf1, datasetHead.length() + 1); client.print(charBuf1); mserial.printStr(charBuf1); // create buffer const int bufSize = 2048; byte clientBuf[bufSize]; int clientCount = 0; while (datasetFile.available()) { clientBuf[clientCount] = datasetFile.read(); clientCount++; if (clientCount > (bufSize - 1)) { client.write((const uint8_t *)clientBuf, bufSize); clientCount = 0; } } datasetFile.close(); if (clientCount > 0) { client.write((const uint8_t *)clientBuf, clientCount); mserial.printStrln(""[binary data]""); } // send tail char charBuf3[tail.length() + 1]; tail.toCharArray(charBuf3, tail.length() + 1); client.print(charBuf3); mserial.printStr(charBuf3); // Read all the lines on reply back from server and print them to mserial mserial.printStrln(""""); mserial.printStrln(""Response Headers:""); String responseHeaders = """"; while (client.connected()) { // mserial.printStrln(""while client connected""); responseHeaders = client.readStringUntil('\n'); mserial.printStrln(responseHeaders); if (responseHeaders == ""\r"") { mserial.printStrln(""====== end of headers ======""); break; } } String responseContent = client.readStringUntil('\n'); mserial.printStrln(""Harvard University's Dataverse reply was:""); mserial.printStrln(""==========""); mserial.printStrln(responseContent); mserial.printStrln(""==========""); mserial.printStrln(""closing connection""); client.stop(); } // ********************************************************* // Make data request to Dataverse (GET) // ********************************************************* void Dataverse::GetInfoFromDataverse(String url) { Dataverse::GetInfoFromDataverse(url,0); } // ********************************************************* String Dataverse::GetInfoFromDataverse(String url, byte counter) { if(counter> THIS->MAX_ATTEMPT_REQUESTS) return; //Check WiFi connection status if(WiFi.status() != WL_CONNECTED){ mserial.printStrln(""WiFi Disconnected""); if (connect2WIFInetowrk()){ GetInfoFromDataverse(url, counter+1); } } int str_len = SERVER_URL.length() + 1; // Length (with one extra character for the null terminator) char SERVER_URL_char [str_len]; // Prepare the character array (the buffer) SERVER_URL.toCharArray(SERVER_URL_char, str_len); // Copy it over client.stop(); client.setCACert(HARVARD_ROOT_CA_RSA_SHA1); if (!client.connect(SERVER_URL_char, SERVER_PORT)) { mserial.printStrln(""Cloud server URL connection FAILED!""); mserial.printStrln(SERVER_URL_char); int server_status = client.connected(); mserial.printStrln(""Server status code: "" + String(server_status)); return """"; } mserial.printStrln(""Connected to the dataverse of Harvard University""); mserial.printStrln(""""); // We now create a URI for the request mserial.printStr(""Requesting URL: ""); mserial.printStrln(url); // Make a HTTP request and add HTTP headers // post header String postHeader = ""GET "" + url + "" HTTP/1.1\r\n""; postHeader += ""Host: "" + SERVER_URL + "":"" + String(SERVER_PORT) + ""\r\n""; //postHeader += ""X-Dataverse-key: "" + API_TOKEN + ""\r\n""; postHeader += ""Content-Type: text/json\r\n""; postHeader += ""Accept: text/html,application/xhtml+xml,application/xml,application/json,text/json;q=0.9,*/*;q=0.8\r\n""; postHeader += ""Accept-Encoding: gzip,deflate\r\n""; postHeader += ""Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n""; postHeader += ""User-Agent: AeonLabs LDAD Smart DAQ device\r\n""; //postHeader += ""Keep-Alive: 300\r\n""; postHeader += ""Accept-Language: en-us\r\n""; postHeader += ""Connection: close\r\n\r\n""; // request tail String boundary = ""7MA4YWxkTrZu0gW""; String tail = ""\r\n--"" + boundary + ""--\r\n\r\n""; // content length int contentLength = tail.length(); //postHeader += ""Content-Length: "" + String(contentLength, DEC) + ""\n\n""; // send post header int postHeader_len=postHeader.length() + 1; char charBuf0[postHeader_len]; postHeader.toCharArray(charBuf0, postHeader_len); client.print(charBuf0); mserial.printStrln(""======= Headers =======""); mserial.printStrln(charBuf0); mserial.printStrln(""======= End of Headers =======""); // Read all the lines of the reply from server and print them to mserial String responseHeaders = """"; mserial.printStr(""Waiting for server response...""); long timeout= millis(); long ttl=millis()-timeout; while (client.connected() && abs(ttl) < HTTP_TTL) { ttl=millis()-timeout; responseHeaders = client.readStringUntil('\n'); if (responseHeaders == ""\r"") { break; } } if (abs(ttl) < 10000){ mserial.printStrln(""OK""); }else{ mserial.printStrln(""timed out.""); } String responseContent = client.readStringUntil('\n'); client.stop(); return responseContent; }",jsonDataHeader 176,"#include #include #include #include using namespace std; struct node { string data; node * next; }*start[52]; class linked_Dic { private: node *head, *tail; char words[50]; public: linked_Dic();//for Linked List Creation void create(); void display();//Display Linked List void search1(string); }; linked_Dic::linked_Dic()//Alphabet Linked list creation { char alphabet='A'; for(int i=0; i<51; i++)//Capital+Small Alphabets { start[i]=new struct node; start[i]->data=alphabet; start[i]->next=NULL; alphabet++; if(i==25) { alphabet='a'; } } } void linked_Dic::create() { int i=0; char input='y'; struct node *ptr_data, *ptr_trav; while(input=='y' || input=='Y') { cout<<""Enter New String : ""; ptr_data=new struct node; cin>>ptr_data->data; ptr_data->next=NULL; char file_name[6]; file_name[0]=ptr_data->data[0]; file_name[1]='.'; file_name[2]='t'; file_name[3]='x'; file_name[4]='t'; file_name[5]='\0'; struct node *link=NULL; fstream file_object; file_object.open(file_name,ios::out | ios::app); file_object<data<data[0]!=ptr_data->data[0]) { i++; } ptr_trav=start[i]; while(ptr_trav->next!=NULL) { ptr_trav=ptr_trav->next; } ptr_trav->next=ptr_data; ptr_trav=ptr_data; cout<<""Would you like to enter more..? (Y=Yes || N=No):""; cin>>input; i=0; } } void linked_Dic::search1(string arg1) { string readString; char file_name[6]; file_name[0]=arg1[0]; file_name[1]='.'; file_name[2]='t'; file_name[3]='x'; file_name[4]='t'; file_name[5]='\0'; fstream file_object; file_object.open(file_name,ios::in); if(file_object) { do { file_object>>readString; if(readString==arg1) { cout<data; } while((ptr_tra->next!=NULL) && (cout<<"" -> "") && (ptr_tra=ptr_tra->next)); } cout<> [MASK] ; switch( [MASK] ) { case 1: obj.create(); getch(); break; case 2: obj.display(); getch(); break; case 3: cout<>strInput; obj.search1(strInput); getch(); break; } system(""CLS""); }while( [MASK] !=4); } ",choice 177,"// Copyright 2016 <> // Apache License Version 2.0. See LICENSE file // Most Servo Sweep code by BARRAGAN and http://www.arduino.cc/en/Tutorial/Sweep // Heart pulse code by Sparkfun https://www.sparkfun.com/tutorials/329 #include const int buttonPin = 2; const int ledPin1 = 10; const int ledPin2 = 11; const int heartPin = 6; const int servoPin = 9; unsigned long startTime; unsigned long currentTime; Servo myservo; // create servo object to control a servo // twelve servo objects can be created on most boards int pos = 0; // variable to store the servo position int buttonState = 0; int lookingLeft = 0; void setup() { pinMode(buttonPin, INPUT); pinMode(ledPin1, OUTPUT); pinMode(ledPin2, OUTPUT); pinMode(heartPin, OUTPUT); digitalWrite(ledPin1, LOW); digitalWrite(ledPin2, LOW); analogWrite(heartPin, 0); myservo.attach(servoPin); // attaches the servo on pin 9 to the servo object myservo.write(90); // tell servo to go to position in variable 'pos' delay(1000); myservo.detach(); } void loop() { float heartIn, [MASK] ; buttonState = digitalRead(buttonPin); if (lookingLeft == 0) { if (buttonState == HIGH) { digitalWrite(ledPin1, HIGH); digitalWrite(ledPin2, HIGH); myservo.attach(servoPin); // attaches the servo on pin 9 to the servo object myservo.write(180); // tell servo to go to position in variable 'pos' delay(1500); myservo.detach(); // Check time startTime = millis(); lookingLeft = 1; } } else { // Pulse Heart for (heartIn = 0; heartIn < 6.283; heartIn = heartIn + 0.001) { [MASK] = sin(heartIn) * 127.5 + 127.5; analogWrite(heartPin, [MASK] ); } // Check time elapsed currentTime = millis(); // If 10 seconds passed, look straight again else exit and loop if (currentTime - startTime >= 10000){ digitalWrite(ledPin1, LOW); digitalWrite(ledPin2, LOW); analogWrite(heartPin, 0); myservo.attach(servoPin); // attaches the servo on pin 9 to the servo object myservo.write(90); // tell servo to go to position in variable 'pos' delay(1500); myservo.detach(); lookingLeft = 0; } } } ",heartOut 178,"// Copyright 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at // http://www.boost.org/LICENSE_1_0.txt) #include #include #if defined(FMIDI_GREP_HAVE_FTS) #include #else #include #include namespace fs = std::filesystem; #endif #include #include #include #include #if defined(FMIDI_GREP_HAVE_FTS) struct FTS_Deleter { void operator()(FTS *x) const noexcept { fts_close(x); } }; #endif class Pattern { public: virtual ~Pattern() {} virtual bool match(const char *p, size_t n, const char **matchp, size_t *matchn) const = 0; }; static bool do_file(const char *path, const Pattern &pattern, bool &has_match, bool matched_part_only) { fmidi_smf_u smf(fmidi_smf_file_read(path)); if (!smf) return false; struct callback_data { const char *path = nullptr; const Pattern *pattern = nullptr; bool *has_match = nullptr; bool matched_part_only = false; }; callback_data cbdata; cbdata.path = path; cbdata.pattern = &pattern; cbdata.has_match = &has_match; cbdata.matched_part_only = matched_part_only; fmidi_smf_describe_by_line( smf.get(), [](const char *data, size_t size, void *cookie) { callback_data *cbdata = (callback_data *)cookie; const char *matchp = nullptr; size_t matchn = 0; if (cbdata->pattern->match(data, size, &matchp, &matchn)) { fputs(cbdata->path, stdout); fputc(':', stdout); if (!cbdata->matched_part_only) { fwrite(data, 1, size, stdout); if (size == 0 || data[size - 1] != '\n') fputc('\n', stdout); } else { fwrite(matchp, 1, matchn, stdout); if (matchn == 0 || matchp[matchn - 1] != '\n') fputc('\n', stdout); } *cbdata->has_match = true; } }, &cbdata); return true; } static bool do_tree(const char *path, const Pattern &pattern, bool &has_match, bool matched_part_only) { bool success = true; #if defined(FMIDI_GREP_HAVE_FTS) char *const path_argv[2] = {(char *)path, nullptr}; std::unique_ptr fts(fts_open(path_argv, FTS_LOGICAL|FTS_NOCHDIR, nullptr)); if (!fts) return false; while (FTSENT *ent = fts_read(fts.get())) { if (S_ISREG(ent->fts_statp->st_mode)) success &= do_file(ent->fts_path, pattern, has_match, matched_part_only); } #else std::error_code ec; fs::recursive_directory_iterator it{path, ec}; if (ec) return false; while (it != fs::recursive_directory_iterator{}) { ec.clear(); fs::file_status st = it->status(ec); if (!ec && st.type() == fs::file_type::regular) { #if defined(_WIN32) success &= do_file(it->path().u8string().c_str(), pattern, has_match, matched_part_only); #else success &= do_file(it->path().c_str(), pattern, has_match, matched_part_only); #endif } ec.clear(); it.increment(ec); if (ec) { success = false; break; } } #endif return success; } class Grep_Pattern : public Pattern { public: explicit Grep_Pattern(const char *pattern) : re_(pattern, std::regex::grep) {} bool match(const char *p, size_t n, const char **matchp, size_t *matchn) const override { std::cmatch m; if (!std::regex_search(p, p + n, m, re_)) return false; *matchp = m[0].first; *matchn = m[0].length(); return true; } private: std::regex re_; }; class EGrep_Pattern : public Pattern { public: explicit EGrep_Pattern(const char *pattern) : re_(pattern, std::regex::egrep) {} bool match(const char *p, size_t n, const char **matchp, size_t *matchn) const override { std::cmatch m; if (!std::regex_search(p, p + n, m, re_)) return false; *matchp = m[0].first; *matchn = m[0].length(); return true; } private: std::regex re_; }; class Text_Pattern : public Pattern { public: explicit Text_Pattern(const char *pattern) : pat_(pattern), patlen_(strlen(pattern)) {} bool match(const char *p, size_t n, const char **matchp, size_t *matchn) const override { const char *q = (const char *)memmem(p, n, pat_, patlen_); if (!q) return false; *matchp = q; *matchn = patlen_; return true; } private: const char *pat_ = nullptr; size_t patlen_ = 0; }; void usage() { fputs( ""Usage: fmidi-grep [options] [input...]\n"" "" -r,-R recursive\n"" "" -E extended pattern\n"" "" -F fixed string pattern\n"" "" -o matched part only\n"" """", stderr); } int main(int argc, char *argv[]) { bool recurse = false; unsigned pattern_mode = std::regex::grep; bool matched_part_only = false; for (int c; (c = getopt(argc, argv, ""rREFoh"")) != -1;) { switch (c) { case 'r': case 'R': recurse = true; break; case 'E': pattern_mode = std::regex::egrep; break; case 'F': pattern_mode = 0; break; case 'o': matched_part_only = true; break; case 'h': usage(); return 0; default: usage(); return 1; } } if (argc - optind < 2) { usage(); return 1; } bool success = true; const char *pattern = argv[optind]; const char **inputs = (const char **)&argv[optind + 1]; unsigned [MASK] = argc - optind - 1; std::unique_ptr pat; switch (pattern_mode) { case std::regex::grep: pat.reset(new Grep_Pattern(pattern)); break; case std::regex::egrep: pat.reset(new EGrep_Pattern(pattern)); break; default: pat.reset(new Text_Pattern(pattern)); break; } bool has_match = false; for (unsigned i = 0; i < [MASK] ; ++i) { const char *input = inputs[i]; success &= (recurse ? do_tree : do_file)(input, *pat, has_match, matched_part_only); } if (!has_match) success = false; return success ? 0 : 1; } ",num_inputs 179,"#include ""Ledstrip.h"" uint8_t redValue, blueValue, greenValue = 0; CRGB leds[NUM_LEDS]; void setupLedstrip() { LEDS.addLeds(leds, NUM_LEDS); LEDS.setBrightness(50); Serial.println(""Ledstrip initialized""); powerOffLedstrip(); updateLedstrip(); } void updateBrigtness(double [MASK] ) { LEDS.setBrightness( [MASK] ); } void setRGBLedstrip(uint8_t red, uint8_t green, uint8_t blue) { for (int j = 0; j < NUM_LEDS; j++) { leds[j].setRGB(red, green, blue); } if(redValue != red || blueValue != blue || greenValue != green) { redValue = red; blueValue = blue; greenValue = green; updateLedstrip(); } } void powerOffLedstrip() { for (int j = 0; j < NUM_LEDS; j++) { leds[j].nscale8( 250); } updateLedstrip(); } void setRedValue(int position, uint8_t red) { redValue = red; leds[position].setRGB(red, 0, 0); } void setBlueValue(int position, uint8_t blue) { blueValue = blue; leds[position].setRGB(0, 0, blue); } void setGreenValue(int position, uint8_t green) { greenValue = green; leds[position].setRGB(0, green, 0); } void updateLedstrip() { FastLED.show(); } ",brightness 180,"/* Copyright 2019 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 ""barista.h"" void GhettoBarista::setCelsiusMode(bool enable) { m_isCelsius = enable; } void GhettoBarista::setFahrenheitMode(bool enable) { m_isCelsius = !enable; } void GhettoBarista::setGroupHeadTemp(double temp) { m_groupTemp = temp; } void GhettoBarista::setGroupHeadOffset(double [MASK] ) { m_groupOffset = [MASK] ; } void GhettoBarista::setDesiredWaterTemp(double temp) { m_waterTempSetpoint = temp; } void GhettoBarista::startPumpTimer(unsigned long start) { if (m_pumpStart) return; m_pumpStart = start; } void GhettoBarista::startPumpTimer() { startPumpTimer(millis()); } void GhettoBarista::stopPumpTimer() { updatePumpRuntime(); m_pumpStart = 0; } void GhettoBarista::updatePumpRuntime() { if (m_pumpStart) m_pumpRuntime = millis() - m_pumpStart; } void GhettoBarista::resetPumpRuntime() { m_pumpRuntime = 0; } void GhettoBarista::estimateWaterTemp() { m_waterTemp = m_groupTemp + m_groupOffset; } void GhettoBarista::refresh() { estimateWaterTemp(); if (m_isCooling && m_waterTemp <= m_waterTempSetpoint) stopCoolingFlush(); } void GhettoBarista::startCoolingFlush() { if (m_waterTemp <= m_waterTempSetpoint) return; m_shouldStartPump = true; m_isCooling = true; } void GhettoBarista::stopCoolingFlush() { m_shouldStartPump = false; m_isCooling = false; } bool GhettoBarista::getPumpWantedState() { return m_shouldStartPump; } ",offset 181,"#include #include #include #include #include #include #include #include ""src/Ckmeans.1d.dp.h"" template struct cluster { std::array clusters; std::array centers; std::array withinss; std::array size; std::array BIC; // TODO check - fixes the segfault but should probably be kMax }; // FORWARD DECLARATIONS template void rebase(cluster&); template void compare(cluster&,cluster&); void testWeightedInput(const std::string&); void testGivenK(const std::string&); void testNlteK(const std::string&); void testKeq2(const std::string&); void testKeq1(const std::string&); void testN10K3(const std::string&); void testN14K8(const std::string&); void testEstimateKExampleSet1(const std::string& method); void testEstimateKExampleSet2(const std::string& method); void testEstimateKExampleSet3(const std::string& method); void testEstimateKExampleSet4(const std::string& method); void testTaps(); // MAIN int main(int argc,char *argv[]) { std::cout << ""ckmeans v4.3.3"" << std::endl; std::string methods[] = { ""linear"", ""loglinear"", ""quadratic"" }; for (const std::string &method: methods) { std::cout << std::endl << method << std::endl; testWeightedInput(method); // Go'd testGivenK(method); // Go'd testNlteK(method); // Go'd testKeq2(method); // Go'd testKeq1(method); // Go'd testN10K3(method); // Go'd testN14K8(method); // Go'd testEstimateKExampleSet1(method); testEstimateKExampleSet2(method); testEstimateKExampleSet3(method); testEstimateKExampleSet4(method); } testTaps(); return 0; } void testTaps() { double taps[] = { 4.570271991, 5.063594027, 5.603539973, 6.102690998, 6.642708943, 7.141796968, 7.710649857, 8.192470916, 4.506176116, 5.045971061, 5.591722996, 6.114172975, 6.619153989, 7.13578898, 7.693071891, 8.203885893, 4.52956007, 5.057670039, 5.591721996, 6.13742393, 6.630941966, 7.1766839, 7.69897488, 8.227207848, 4.52956007, 5.069284016, 5.603428973, 6.102591998, 6.613455, 7.147644957, 7.69912088, 8.215609871, 4.517865093, 5.022782107, 5.580101018, 6.096715009, 6.654118921, 7.1763719, 7.681405914, 8.215537871, 5.133092891, 5.545395086, 6.067721066, 6.578564068, 7.130096991, 7.652464971, 8.13427303, 4.494581138, 5.040234073, 5.562732052, 6.079333043, 6.624973977, 7.141650968, 7.664070948, 8.198270905, 4.52940807, 5.040295073, 5.556940064, 6.131584941, 6.654145921, 7.193876866, 7.722112835, 8.244539814, 4.523631082, 5.046071061, 5.586102007, 6.09099502, 6.596029034, 7.130224991, 7.652501971, 8.180805939, 4.517979093, 5.046165061, 5.551068075, 6.073547054, 6.607636011, 7.165018923, 7.687334903, 8.238953825, 4.517911093, 5.069403016, 5.586174007, 6.108568986, 6.578649068, 7.147523957, 7.681606914, 8.26211078 }; cluster<87,87> p = {{},{},{},{}}; std::map> [MASK] ; kmeans_1d_dp(taps, 87, NULL, 1, 87, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", ""linear"", L2); rebase(p); for (int i=0; i<87; i++) { int beat = p.clusters[i]; [MASK] [beat].push_back(taps[i]) ; } std::cout << ""TAPS:"" << std::endl << "" ""; std::copy(std::begin(p.clusters), std::end(p.clusters), std::ostream_iterator(std::cout, "" "")); std::cout << std::endl; for (std::map>::iterator it= [MASK] .begin(); it != [MASK] .end(); ++it) { std::cout << "" "" << it->first << "" => ""; for (std::vector::iterator j=it->second.begin(); j != it->second.end(); ++j) { std::cout << std::setprecision(6) << std::setfill(' ') << std::setw(9) << std::left << *j; } // std::copy(std::begin(it->second), std::end(it->second), std::ostream_iterator(std::cout, "" "")); std::cout << std::endl; } std::cout << ""centers: ""; for (int i=0; i< [MASK] .size(); i++) { std::cout << p.centers[i] << "" ""; } std::cout << std::endl; std::cout << ""withinss: ""; for (int i=0; i< [MASK] .size(); i++) { std::cout << p.withinss[i] << "" ""; } std::cout << std::endl; std::cout << ""sizes: ""; for (int i=0; i< [MASK] .size(); i++) { std::cout << p.size[i] << "" ""; } std::cout << std::endl; } // test_that(""Weighted input"", { void testWeightedInput(const std::string& method) { std::cout << "" test with weighted input"" << std::endl; { double data[] = {-1, 2, 4, 5, 6}; double weights[] = { 4, 3, 1, 1, 1}; cluster<5,3> p = {{},{},{},{}}; cluster<5,3> q = {{1,2,3,3,3},{-1, 2, 5},{0,0,2},{4,3,3}}; kmeans_1d_dp(data, 5, weights, 3, 3, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } { double data[] = {-0.9, 1, 1.1, 1.9, 2, 2.1}; double weights[] = { 3, 1, 2, 2, 1, 1 }; cluster<6,3> p = {{},{},{},{}}; cluster<6,3> q = {{1,2,2,3,3,3},{-0.9, 1.0666667, 1.975},{0,0.00666667,0.0275},{3,3,4}}; // cluster<6,3> q = {{1,2,2,3,3,3},{-0.9, (1+2.2)/3, (1.9*2+2+2.1)/4},{0,0.00666667,0.0275},{3,3,4}}; kmeans_1d_dp(data, 6, weights, 1, 6, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } } // test_that(""Given the number of clusters"", { void testGivenK(const std::string& method) { std::cout << "" test with given number of clusters"" << std::endl; double data[] = {-1, 2, -1, 2, 4, 5, 6, -1, 2, -1}; cluster<10,3> p = {{},{},{},{}}; cluster<10,3> q = {{1,2,1,2,3,3,3,1,2,1},{-1, 2, 5},{0,0,2},{4,3,3}}; kmeans_1d_dp(data, 10, NULL, 3, 3, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); // Ref. https://stackoverflow.com/questions/8637460/k-means-return-value-in-r // // totss.truth <- sum(scale(x, scale=FALSE)^2) // expect_equal(result$totss, totss.truth) // expect_equal(result$tot.withinss, 2) // expect_equal(result$betweenss, totss.truth - sum(withinss.truth)) } // test_Ckmeans.1d.dp::test_that(""n<=k""... void testNlteK(const std::string& method) { std::cout << "" test with N<=K"" << std::endl; double data[] = {3, 2, -5.4, 0.1}; cluster<4,4> p = {{},{},{},{}}; cluster<4,4> q = {{4, 3, 1, 2},{-5.4, 0.1, 2, 3},{0, 0, 0, 0},{1, 1, 1, 1}}; kmeans_1d_dp(data, 4, NULL, 4, 4, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } // test_Ckmeans.1d.dp::test_that(""k==2""... void testKeq2(const std::string& method) { std::cout << "" test with K=2"" << std::endl; double data[] = {1,2,3,4,5,6,7,8,9,10}; cluster<10,2> p = {{},{},{},{}}; cluster<10,2> q = {{1, 1, 1, 1, 1, 2, 2, 2, 2, 2},{3,8},{10,10},{5,5}}; kmeans_1d_dp(data, 10, NULL, 2, 2, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } // test_Ckmeans.1d.dp::test_that(""k==1""... void testKeq1(const std::string& method) { { std::cout << "" test with single unique value"" << std::endl; double data[] = {-2.5,-2.5,-2.5,-2.5}; cluster<4,1> p = {{},{},{},{}}; cluster<4,1> q = {{1,1,1,1}, {-2.5}, {0}, {4}}; kmeans_1d_dp(data, 4, NULL, 1, 1, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"" ,method, L2); rebase(p); compare(p,q); } { static std::random_device rd; static std::mt19937 e2(rd()); static std::uniform_real_distribution<> dist(-100.0, +100.0); std::cout << "" test with K=1"" << std::endl; double data[100]; cluster<100,1> p = {{},{},{},{}}; cluster<100,1> q = {{}, {}, {}, {100}}; for (int i=0; i<100; i++) { data[i] = dist(rd); } kmeans_1d_dp(data, 100, NULL, 1, 1, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); if (p.size != q.size) { std::cout << "" returned invalid size"" << std::endl; std::cout << "" expected: [ ""; std::copy(std::begin(q.size), std::end(q.size), std::ostream_iterator(std::cout, "" "")); std::cout << ""]"" << std::endl; std::cout << "" got: [ ""; std::copy(std::begin(p.size), std::end(p.size), std::ostream_iterator(std::cout, "" "")); std::cout << ""]"" << std::endl; } } } // test_that(""n==10, k==3""... void testN10K3(const std::string& method) { std::cout << "" test with n=10, k=3"" << std::endl; double data[] = {3, 3, 3, 3, 1, 1, 1, 2, 2, 2}; cluster<10,3> p = {{},{},{},{}}; cluster<10,3> q = {{3, 3, 3, 3, 1, 1, 1, 2, 2, 2},{1, 2, 3},{0, 0, 0},{3, 3, 4}}; kmeans_1d_dp(data, 10, NULL, 3, 3, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } // test_that(""n==14, k==8""... void testN14K8(const std::string& method) { std::cout << "" test with n=14, k=8"" << std::endl; double data[] = {-3, 2.2, -6, 7, 9, 11, -6.3, 75, 82.6, 32.3, -9.5, 62.5, 7, 95.2}; cluster<14,8> p = {{},{},{},{}}; cluster<14,8> q = {{2, 2, 1, 3, 3, 3, 1, 6, 7, 4, 1, 5, 3, 8}, {-7.266666667, -0.4, 8.5, 32.3, 62.5, 75.0, 82.6, 95.2}, {7.526666667, 13.52, 11.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {3, 2, 4, 1, 1, 1, 1, 1}}; kmeans_1d_dp(data, 14, NULL, 8, 8, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } // test_that(""Estimating k example set 1""... void testEstimateKExampleSet1(const std::string& method) { std::cout << "" test estimate K, example set 1"" << std::endl; { double data[] = {0.9, 1, 1.1, 1.9, 2, 2.1}; cluster<6,6> p = {{},{},{},{}}; cluster<6,6> q = {{1,1,1,2,2,2},{1,2},{0.02,0.02},{3,3}}; kmeans_1d_dp(data, 6, NULL, 1, 6, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } { double data[] = {2.1, 2, 1.9, 1.1, 1, 0.9}; cluster<6,6> p = {{},{},{},{}}; cluster<6,6> q = {{2,2,2,1,1,1},{1,2},{0.02,0.02},{3,3}}; kmeans_1d_dp(data, 6, NULL, 1, 6, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } { double data[] = {2.1, 2, 1.9, 1.1, 1, 0.9}; cluster<6,6> p = {{},{},{},{}}; cluster<6,6> q = {{2,2,2,1,1,1},{1,2},{0.02,0.02},{3,3}}; kmeans_1d_dp(data, 6, NULL, 1, 10, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } } // test_that(""Estimating k example set 2""... void testEstimateKExampleSet2(const std::string& method) { std::cout << "" test estimate K, example set 2"" << std::endl; double data[] = {3.5, 3.6, 3.7, 3.1, 1.1, 0.9, 0.8, 2.2, 1.9, 2.1}; cluster<10,3> p = {{},{},{},{}}; cluster<10,3> q = {{3, 3, 3, 3, 1, 1, 1, 2, 2, 2},{0.933333333333, 2.066666666667, 3.475},{0.0466666666667, 0.0466666666667, 0.2075},{3, 3, 4}}; kmeans_1d_dp(data, 10, NULL, 2, 5, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } // test_that(""Estimating k example set 3 cosine""... void testEstimateKExampleSet3(const std::string& method) { std::cout << "" test estimate K, example set 3 (cosine)"" << std::endl; // x <- cos((-10:10)) double data[] = { -0.8390715,-0.9111303,-0.1455000,0.7539023,0.9601703,0.2836622, -0.6536436,-0.9899925,-0.4161468,0.5403023,1.0000000,0.5403023, -0.4161468,-0.9899925,-0.6536436,0.2836622,0.9601703,0.7539023, -0.1455000,-0.9111303,-0.8390715 }; cluster<21,2> p = {{},{},{},{}}; cluster<21,2> q = {{1,1,1,2,2,2,1,1,1,2,2,2,1,1,1,2,2,2,1,1,1}, {-0.6592474631, 0.6751193405},{1.0564793100, 0.6232976959},{12,9}}; kmeans_1d_dp(data, 21, NULL, 1, 21, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } // test_that(""Estimating k example set 4 gamma"", { void testEstimateKExampleSet4(const std::string& method) { std::cout << "" test estimate K, example set 4 (gamma)"" << std::endl; // x <- dgamma(seq(1,10, by=0.5), shape=2, rate=1) double data[] = { 0.3678794412,0.3346952402,0.2706705665,0.2052124966,0.1493612051, 0.1056908420,0.0732625556,0.0499904844,0.0336897350,0.0224772429, 0.0148725131,0.0097723548,0.0063831738,0.0041481328,0.0026837010, 0.0017294811,0.0011106882,0.0007110924,0.0004539993 }; cluster<19,3> p = {{},{},{},{}}; cluster<19,3> q = {{3,3,3,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1}, {0.01702193495, 0.15342151455, 0.32441508262},{0.006126754998,0.004977009034,0.004883305120},{13,3,3}}; kmeans_1d_dp(data, 19, NULL, 1, 19, p.clusters.data(), p.centers.data(), p.withinss.data(), p.size.data(), p.BIC.data(), ""BIC"", method, L2); rebase(p); compare(p,q); } template void rebase(cluster& p) { for (size_t i=0; i void compare(cluster& p, cluster& q) { if (p.clusters != q.clusters) { std::cout << "" returned invalid clusters"" << std::endl; std::cout << "" expected: [ ""; std::copy(std::begin(q.clusters), std::end(q.clusters), std::ostream_iterator(std::cout, "" "")); std::cout << ""]"" << std::endl; std::cout << "" got: [ ""; std::copy(std::begin(p.clusters), std::end(p.clusters), std::ostream_iterator(std::cout, "" "")); std::cout << ""]"" << std::endl; } if (p.centers != q.centers) { for (int i=0; i 0.00001) { std::cout << "" returned invalid centers"" << std::endl; std::cout << "" expected: [ ""; std::copy(std::begin(q.centers), std::end(q.centers), std::ostream_iterator(std::cout, "" "")); std::cout << ""]"" << std::endl; std::cout << "" got: [ ""; std::copy(std::begin(p.centers), std::end(p.centers), std::ostream_iterator(std::cout, "" "")); std::cout << ""]"" << std::endl; break; } } } if (p.withinss != q.withinss) { for (int i=0; i 0.00001) { std::cout << "" returned invalid withins"" << std::endl; std::cout << "" expected: [ ""; std::copy(std::begin(q.withinss), std::end(q.withinss), std::ostream_iterator(std::cout, "" "")); std::cout << ""]"" << std::endl; std::cout << "" got: [ ""; std::copy(std::begin(p.withinss), std::end(p.withinss), std::ostream_iterator(std::cout, "" "")); std::cout << ""]"" << std::endl; break; } } } if (p.size != q.size) { std::cout << "" returned invalid size"" << std::endl; std::cout << "" expected: [ ""; std::copy(std::begin(q.size), std::end(q.size), std::ostream_iterator(std::cout, "" "")); std::cout << ""]"" << std::endl; std::cout << "" got: [ ""; std::copy(std::begin(p.size), std::end(p.size), std::ostream_iterator(std::cout, "" "")); std::cout << ""]"" << std::endl; } } ",beats 182,"#include ""Ellipse.h"" // Constructeur par défaut : Centre à (0,0), a = 1 et b = 0.5 par défaut. Ellipse::Ellipse() : h(0), k(0), a(1), b(0.5), orientation('X') { if (a <= b) { std::swap(a, b); } } Ellipse::Ellipse(double h, double k, double a, double b, char orientation) : h(h), k(k), a(a), b(b), orientation(orientation) { if (a <= b) { std::cerr << ""Erreur : a doit etre superieur a b. Les valeurs sont echangées."" << std::endl; std::swap(this->a, this->b); } } Ellipse::Ellipse(const Ellipse &other) : h(other.h), k(other.k), a(other.a), b(other.b), orientation(other.orientation) {} void Ellipse::setCenter(double h, double k) { this->h = h; this->k = k; } std::pair Ellipse::getCenter() const { return {h, k}; } void Ellipse::setAxes(double a, double b) { if (a > b) { this->a = a; this->b = b; } else { std::cerr << ""Erreur : a doit etre superieur a b."" << std::endl; } } std::pair Ellipse::getAxes() const { return {a, b}; } void Ellipse::setOrientation(char orientation) { if (orientation == 'X' || orientation == 'Y') this->orientation = orientation; } char Ellipse::getOrientation() const { return orientation; } double Ellipse::computeC() const { return sqrt(a * a - b * b); } std::vector> Ellipse::getVertices() const { std::vector> vertices; if (orientation == 'X') { vertices.push_back({h - a, k}); vertices.push_back({h + a, k}); } else { vertices.push_back({h, k - a}); vertices.push_back({h, k + a}); } return vertices; } std::vector> Ellipse::getFoci() const { double c = computeC(); std::vector> foci; if (orientation == 'X') { foci.push_back({h - c, k}); foci.push_back({h + c, k}); } else { foci.push_back({h, k - c}); foci.push_back({h, k + c}); } return foci; } double Ellipse::getFocalChordLength() const { return (2 * b * b) / a; } double Ellipse::getEccentricity() const { return computeC() / a; } void Ellipse::printEquationAndPoints() const { if (orientation == 'X') std::cout << ""Equation: ((x - "" << h << "")^2)/"" << (a * a) << "" + ((y - "" << k << "")^2)/"" << (b * b) << "" = 1"" << std::endl; else std::cout << ""Equation: ((x - "" << h << "")^2)/"" << (b * b) << "" + ((y - "" << k << "")^2)/"" << (a * a) << "" = 1"" << std::endl; std::cout << ""Centre: ("" << h << "", "" << k << "")"" << std::endl; auto vertices = getVertices(); std::cout << ""Vertices: ""; for (auto &v : vertices) std::cout << ""("" << v.first << "", "" << v.second << "") ""; std::cout << std::endl; auto foci = getFoci(); std::cout << ""Foyers: ""; for (auto &f : foci) std::cout << ""("" << f.first << "", "" << f.second << "") ""; std::cout << std::endl; } int Ellipse::pointPosition(double x, double y) const { double value; if (orientation == 'X') value = ((x - h) * (x - h)) / (a * a) + ((y - k) * (y - k)) / (b * b); else value = ((x - h) * (x - h)) / (b * b) + ((y - k) * (y - k)) / (a * a); if (fabs(value - 1.0) < 1e-6) return 0; // Sur l'ellipse else if (value < 1) return -1; // A l'interieur else return 1; // A l'exterieur } double Ellipse::approximatePerimeter() const { return M_PI * (3 * (a + b) - sqrt((3 * a + b) * (a + 3 * b))); } double Ellipse::area() const { return M_PI * a * b; } double Ellipse::computeOtherCoordinate(double [MASK] , bool isXGiven) const { double result = 0, term; if (isXGiven) { // x donné, calcul de y if (orientation == 'X') term = 1 - (( [MASK] - h) * ( [MASK] - h)) / (a * a); else term = 1 - (( [MASK] - h) * ( [MASK] - h)) / (b * b); if (term < 0) { std::cerr << ""La coordonnee x="" << [MASK] << "" n'appartient pas a l'ellipse."" << std::endl; return NAN; } result = (orientation == 'X') ? k + b * sqrt(term) : k + a * sqrt(term); } else { // y donné, calcul de x if (orientation == 'X') term = 1 - (( [MASK] - k) * ( [MASK] - k)) / (b * b); else term = 1 - (( [MASK] - k) * ( [MASK] - k)) / (a * a); if (term < 0) { std::cerr << ""La coordonnee y="" << [MASK] << "" n'appartient pas a l'ellipse."" << std::endl; return NAN; } result = (orientation == 'X') ? h + a * sqrt(term) : h + b * sqrt(term); } return result; } ",givenValue 183,"//Copyright (c) 2006-2008 and , Inc. //Distributed under the Boost Software License, Version 1.0. (See accompanying //file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef UUID_0552D49838DD11DD90146B8956D89593 #define UUID_0552D49838DD11DD90146B8956D89593 #include #include #include #include namespace boost { namespace exception_detail { inline char const * get_diagnostic_information( exception const & x ) { if( error_info_container * c=x.data_.get() ) try { return c->diagnostic_information(); } catch(...) { } return 0; } } inline std::string diagnostic_information( exception const & x ) { std::ostringstream [MASK] ; if( boost::shared_ptr f=get_error_info(x) ) { [MASK] << *f; if( boost::shared_ptr l=get_error_info(x) ) [MASK] << '(' << *l << ""): ""; } [MASK] << ""Throw in function ""; if( boost::shared_ptr fn=get_error_info(x) ) [MASK] << *fn; else [MASK] << ""(unknown)""; #ifndef BOOST_NO_RTTI [MASK] << ""\nDynamic exception type: "" << BOOST_EXCEPTION_DYNAMIC_TYPEID(x).name(); if( std::exception const * e=dynamic_cast(&x) ) [MASK] << ""\nstd::exception::what: "" << e->what(); #endif if( char const * s=exception_detail::get_diagnostic_information(x) ) if( *s ) [MASK] << '\n' << s; return [MASK] .str(); } } #endif ",tmp 184,"/*--- FIRST VERSION: COPY this into a main.cpp in a NetBeans C++ Application Project (replace the given contents) improved 2019-03-30 with comment with ready-for-test-expression cout for easier test call setup (thanks !) ---*/ /*--- by: & last modified: ---*/ #include #include #include #include #include using namespace std; /*--- PUT YOUR SIGNATURES, PURPOSES, and FUNCTION DEFINITIONS HERE ---*/ /*--- test the functions above ---*/ int main() { cout << boolalpha; // From Autumn const string FONT_SIZE = """"; string file_name; string cat_name; string cat_sex; string cat_; string adoptee_name; string adoptee_age; string adoptee_address; string why_adopt; string past_experience; string DL_number; string litter_box; string financial_food; string [MASK] ; string title; cout << ""Give File Name(ex. Ruby1123): ""; cin >> file_name; cout << endl; //file_name = ""/c/Users/west/Desktop/Cats/"" + file_name + "".html""; // set to .html later // file_name = file_name + "".html""; cout << file_name << endl; ofstream fout; fout.open(file_name); if(fout.fail()) { cout << ""Failed to open file"" << endl; } cout << ""Adoptee Name: ""; getline(cin, adoptee_name); getline(cin, adoptee_name); cout << endl; cout << endl << ""Adoptee Address: ""; getline(cin, adoptee_address); cout << endl; cout << endl << ""DL #: ""; getline(cin, DL_number); cout << endl; cout << ""Why they want to adopt? ""; getline(cin, why_adopt); cout << endl; cout << ""Any Past Experiences with cats? ""; getline(cin, past_experience); cout << endl; cout << ""Do you have a litter box? ""; getline(cin, litter_box); cout << endl; cout << ""Adequate financial means to feed a cat? ""; getline(cin, financial_food); cout << endl; cout << ""Will you allow the cat to roam outside? ""; getline(cin, [MASK] ); cout << endl; //fout << FONT_SIZE << ""Name: "" << """" << ""
""; //cout << ""Any past"" // fout << """" << "" People Trying to Adopt a cat "" << title << endl; fout << FONT_SIZE << ""

"" << ""          People Trying to Adopt a cat          "" << ""

"" << endl; fout << ""
    "" << endl; fout << ""
  • Adoptee Name: "" << adoptee_name << ""
  • ""; fout << endl; fout << ""
  • Adoptee Address: "" << adoptee_address << ""
  • ""; fout << endl; fout << ""
  • DL #: "" << DL_number << ""
  • ""; fout << endl; fout << ""
  • Why they want to adopt?: "" << why_adopt << ""
  • ""; fout << endl; fout << ""
  • Any Past Experiences with cats?: "" << past_experience << ""
  • ""; fout << endl; fout << ""
  • Do you have a litter box?: "" << litter_box << ""
  • ""; fout << endl; fout << ""
  • Adequate financial means to feed a cat?: "" << financial_food << ""
  • ""; fout << endl; fout << ""
  • Will you allow the cat to roam outside?: "" << [MASK] << ""
  • ""; fout << ""
"" << endl; return EXIT_SUCCESS; }",inside_outside_cat 185,"#include ""Application.h"" #include ""ECS/ECS.h"" #include ""Log.h"" #include ""Renderer.h"" #include ""InputManager.h"" #include ""SDL.h"" #include ""SDL_ttf.h"" #include ""SDL_image.h"" #include ""SDL_mixer.h"" namespace DrEngine { Renderer* Application::renderer = nullptr; SDL_Event Application::event; float Application::DeltaTime = 0.0f; Uint32 Application::Milliseconds = 0; InputManager* Application::inputManager; ECS::Manager* Application::manager; Uint64 NOW = SDL_GetPerformanceCounter(); Uint64 LAST = 0; Application::Application(char* name, int [MASK] , int height, bool fullscreen) { AppName = name; /* SDL Init */ if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { DE_CORE_ERROR(""SDL_Init Error: {0}"", SDL_GetError()); } /* Creating Window */ window = new Window(); if (!window->Initialize(AppName, [MASK] , height, fullscreen)) { DE_CORE_ERROR(""Window failed to initialize""); } /* Creating Renderer */ renderer = new Renderer(); if (!renderer->Initialize(window)) { DE_CORE_ERROR(""Renderer failed to initialize""); } /* Attaching Renderer to Window */ window->SetRenderer(renderer); /* TTF Init */ if (TTF_Init() != 0) { DE_CORE_ERROR(""TTF_Init Error: {0}"", TTF_GetError()); } /* Image Init */ constexpr int ImgFlags = IMG_INIT_PNG | IMG_INIT_JPG; if (IMG_Init(ImgFlags) != ImgFlags) { DE_CORE_ERROR(""IMG_Init Error: {0}"", IMG_GetError()); } /* Mixer Init */ constexpr int MixerFlags = 0 | MIX_INIT_MP3; if (Mix_Init(MixerFlags) != MixerFlags) { DE_CORE_ERROR(""Mix_Init Error: {0}"", Mix_GetError()); } if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 8, 1024) < 0) { DE_CORE_ERROR(""Mix_OpenAudio Error: {0}"", Mix_GetError()); } Mix_AllocateChannels(32); /* Init Manager */ manager = new ECS::Manager(); } Application::~Application() { } void Application::Run() { BeginPlay(); while (true) { Milliseconds = SDL_GetTicks(); LAST = NOW; NOW = SDL_GetPerformanceCounter(); DeltaTime = (NOW - LAST)*1000 / (float)SDL_GetPerformanceFrequency(); SDL_PumpEvents(); while (SDL_PollEvent(&Application::event)) { Application::inputManager->PollEvent(); if ((event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) || event.type == SDL_QUIT) { SDL_Quit(); return; } } Update(DeltaTime); Draw(DeltaTime); Application::inputManager->ResetMouseDelta(); } } void Application::BeginPlay() { inputManager = new InputManager(); inputManager->Init(); } void Application::Update(float deltaTime) { Application::inputManager->Update(); manager->Update(deltaTime); } void Application::Draw(float deltaTime) { SDL_RenderClear(Application::renderer->GetSDLRenderer()); manager->Draw(deltaTime); // Calls Draw() on all Entities and Components SDL_SetRenderDrawColor(Application::renderer->GetSDLRenderer(), 0, 0, 0, 255); // Let components draw color without worrying to set the colour back to default (black) before SDL_RenderPresent(Application::renderer->GetSDLRenderer()); // rendering next frame, if color not set to default then whole screen will be colored the RenderDrawColor. } void Application::AddCollisionComp(CollisionComponent* inComp) { manager->AddCollisionComp(inComp); } } ",width 186,"#include ""BasicCamera.h"" #include #include #include #include ""Input.h"" using namespace glm; BasicCamera::BasicCamera() : BasicCamera(vec3(0, 0, 0)) { } BasicCamera::BasicCamera(vec3 [MASK] ) { _pos = [MASK] ; _front_vec = glm::vec3(0, 0, 1); _theta = degrees(atan(_front_vec.x / _front_vec.z)); _phi = degrees(atan(_front_vec.y / length(vec2(_front_vec.x, _front_vec.z)))); _speed = 40; _rotation_speed = 0.1; } BasicCamera::~BasicCamera() {} void BasicCamera::update(float time_elapsed) { vec3 up_vec = vec3(0, 1, 0); if (Input::key_pressed_down(GLFW_KEY_W)) { _pos += _front_vec * _speed * time_elapsed; } if (Input::key_pressed_down(GLFW_KEY_S)) { _pos -= _front_vec * _speed * time_elapsed; } if (Input::key_pressed_down(GLFW_KEY_D)) { _pos += normalize(cross(_front_vec, up_vec)) * _speed * time_elapsed; } if (Input::key_pressed_down(GLFW_KEY_A)) { _pos -= normalize(cross(_front_vec, up_vec)) * _speed * time_elapsed; } if (Input::key_pressed_down(GLFW_KEY_Q)) { _pos += up_vec * _speed * time_elapsed; } if (Input::key_pressed_down(GLFW_KEY_E)) { _pos -= up_vec * _speed * time_elapsed; } vec2 mouse_change = Input::cursor_change(); if (length(mouse_change) < FLT_EPSILON) return; _theta += mouse_change.x * _rotation_speed; _phi -= mouse_change.y * _rotation_speed; if (_phi > 89.0f) _phi = 89.0f; if (_phi < -89.0f) _phi = -89.0f; vec3 front; front.x = cos(radians(_theta)) * cos(radians(_phi)); front.y = sin(radians(_phi)); front.z = sin(radians(_theta)) * cos(radians(_phi)); _front_vec = normalize(front); } glm::mat4 BasicCamera::getViewMatrix() { return glm::lookAt(_pos, _pos + _front_vec, vec3(0, 1, 0)); } glm::mat4 BasicCamera::getProjectionMatrix() { int width, height; glfwGetWindowSize(glfwGetCurrentContext(), &width, &height); return glm::perspective(radians(45.f), width / (float) height, 0.01f, 1000.f); }",starting_pos 187,"#include ""./downloader.hpp"" #include ""./strategy.hpp"" #include ""cryptoconnect/structs/events.hpp"" #include ""cryptoconnect/structs/universe.hpp"" #include CBProDownloader::CBProDownloader(CBProStrategy *strategy) : strategy_(strategy){}; void CBProDownloader::downloadLatestBars( Universe::Universe const &universe, std::unordered_map &barsDataMap) { constexpr int numDays = 3; constexpr int numBars = 288 * numDays; // 288 x 5 mins per day uint64_t timeNow = Utils::Datetime::epochNow(); // Public endpoint rate limit is 3 req/sec for CoinbasePro boost::asio::thread_pool pool(3); for (auto const productId : universe) { // Emplace an empty vector into the map barsDataMap.emplace(productId, Events::bars_t()); barsDataMap[productId].reserve(numBars); boost::asio::post( pool, [this, timeNow, productId, &barsDataMap] { uint64_t [MASK] = timeNow; // Get 7 days of data for (int j = 0; j < numDays; j++) { this->strategy_->adapter_->getBars( productId, ""300"", // 5-min bars Utils::Datetime::epochToIsostring( [MASK] - 86100), // - 23hrs 55mins Utils::Datetime::epochToIsostring( [MASK] ), barsDataMap[productId]); [MASK] -= 86400; } }); } pool.join(); } ",queryEndTime 188,"#include #include #include #include #include #include #include template void is_lock_free(std::atomic& a); std::string demangle(const char* name) { int status = -1; std::unique_ptr [MASK] { abi::__cxa_demangle(name, NULL, NULL, &status), std::free }; return (status == 0) ? [MASK] .get() : name; } int main() { std::cout << ""C++ Standard: "" << __cplusplus << "" :"" << std::endl; std::atomic x = 10; is_lock_free(x); std::atomic y = 10.4; is_lock_free(y); std::atomic c = 'z'; is_lock_free(c); std::atomic cp = nullptr; is_lock_free(cp); std::atomic> z(std::make_shared(""Hello"")); is_lock_free(z); } template void is_lock_free(std::atomic& a) { if (std::atomic_is_lock_free(&a)) { std::cout << demangle(typeid(T).name()) << "" is lock-free"" << std::endl; } else { std::cout << demangle(typeid(T).name()) << "" is NOT lock-free"" << std::endl; } }",res 189,"/*! * @copyright This example code is in the Public Domain (or CC0 licensed, at your option.) * Unless required by applicable law or agreed to in writing, this software is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include ""app_priv.h"" extern ""C"" { #include #include } bool rm_sgl_sw_state = DEFAULT_SWITCH_POWER; bool rm_light_sw_state = DEFAULT_SWITCH_POWER; bool rm_relay_sw_state[4] = {DEFAULT_SWITCH_POWER}; int8_t brt_level = DEFAULT_BRT; int16_t hue_level = DEFAULT_HUE; static bool brt_sw_direction = SW_DIRECTION_UP; static bool hue_sw_direction = SW_DIRECTION_UP; static unsigned long last_event_time_brt = 0; static unsigned long last_event_time_hue = 0; /* Index 0: on/off; Index 1: Brt; Index 2: Hue */ bool light_sw_array[3] = {false}; /* Index 0: switch_1; Index 1: switch_2; Index 2: switch_3; Index 3: switch_4 */ bool relay_sw_array[4] = {false}; /** * This section is for driver initialisation and other generic driver functions. */ //======================================================================================================================= /*! * @brief Initiate the driver, of all the display screens and modules. */ void init_app_driver(void) { Serial.begin(115200); init_m5(); init_images(); init_neohex(); display_start_screen(); display_sgl_switch_screen(); display_light_screen(); display_relay_screen(); esp_log_level_set(""gpio"", ESP_LOG_NONE); } /*! * @brief This is the main screen callback to switch between examples, reset wifi or factory reset. * @param event Logs in the type of event that is driven by the type of example and button pressed. */ void scrn_event_cb(lv_event_t *event) { lv_event_code_t event_code = lv_event_get_code(event); /* Handle different events */ switch (event_code) { case LV_EVENT_PRESSING: // Return to home screen if (lvgl_port_lock()) { disc_relay(); set_start_scrn(); show_start_screen(); lvgl_port_unlock(); } break; case LV_EVENT_PRESSED: // Switch to next page if (is_sgl_sw_scrn) { set_lighting_state(DEFAULT_SWITCH_POWER); set_light_scrn(); show_light_scrn(); set_light_sw_state(rm_light_sw_state); } else if (is_light_scrn) { set_lighting_state(DEFAULT_SWITCH_POWER); init_relay(); set_relay_sw_scrn(); show_relay_scrn(); set_relay_sw_state(); } else if (is_relay_scrn) { disc_relay(); set_sgle_sw_scrn(); show_sgl_switch_screen(); set_sgl_sw_state(rm_sgl_sw_state); } break; case LV_EVENT_LONG_PRESSED: // RainMaker reset or factory reset is enabled if (is_wifi_reset) { is_wifi_reset = false; esp_rmaker_wifi_reset(RESET_DELAY, REBOOT_DELAY); } else if (is_factory_reset) { is_factory_reset = false; esp_rmaker_factory_reset(RESET_DELAY, REBOOT_DELAY); } break; default: break; } } /*! * @brief Update param by name or by type to the cloud of a given specific param. * @param param_attr Attribute of the param, which two cases; PARAM_TYPE or PARAM_NAME. * @param param_id The param identity i.e. ESP_RMAKER_PARAM_POWER * @param device The specific device that have been initiated in app_main.cpp i.e. light_device. * @param val Value of the param that can be of different types which includes int, float, bool, strm json * object. */ void update_rm_param(const char *param_attr, const char *param_id, esp_rmaker_device_t *device, esp_rmaker_param_val_t val) { esp_rmaker_param_t *param = NULL; if (strcmp(param_attr, PARAM_TYPE) == 0) { param = esp_rmaker_device_get_param_by_type(device, param_id); } else if (strcmp(param_attr, PARAM_NAME) == 0) { param = esp_rmaker_device_get_param_by_name(device, param_id); } if (param != NULL) { esp_rmaker_param_update_and_report(param, val); } else { ESP_LOGE(""RM"", ""Parameter '%s' not found for device"", param_id); } } /*! * @brief Deinitiate the i2c connection to prevent signal conflict when FastLED task is running. */ void deinit_i2c(void) { M5.Ex_I2C.release(); pinMode(M5.Ex_I2C.getSCL(), OUTPUT); pinMode(M5.Ex_I2C.getSDA(), OUTPUT); digitalWrite(M5.Ex_I2C.getSCL(), HIGH); digitalWrite(M5.Ex_I2C.getSDA(), HIGH); } /** * This section is for start scrn driver. */ //======================================================================================================================= /*! * @brief Callback function for start button. * @param event Logs in the type of event that is driven by the type of example and button pressed. */ void start_btn_cb(lv_event_t *event) { lv_event_code_t code = lv_event_get_code(event); if (is_start_scrn) { if (code == LV_EVENT_CLICKED) { display_start_btn_pressed(); } else if (code == LV_EVENT_RELEASED) { set_sgle_sw_scrn(); show_sgl_switch_screen(); } else if (code == LV_EVENT_REFRESH) { reset_start_btn(); } } } /** * This section is for single switch device driver. */ //======================================================================================================================= static bool is_sgl_switch_off(lv_event_code_t code) { return is_sgl_sw_scrn && !rm_sgl_sw_state; } static bool is_sgl_switch_on(lv_event_code_t code) { return is_sgl_sw_scrn && rm_sgl_sw_state; } static void on_sgl_sw(void) { if (lvgl_port_lock()) { display_light_bulb_on(); lv_obj_add_state(sgl_sw, LV_STATE_CHECKED); rm_sgl_sw_state = true; lvgl_port_unlock(); } } static void off_sgl_sw(void) { if (lvgl_port_lock()) { display_light_bulb_off(); if (lv_obj_has_state(sgl_sw, LV_STATE_CHECKED)) { lv_obj_clear_state(sgl_sw, LV_STATE_CHECKED); } rm_sgl_sw_state = false; lvgl_port_unlock(); } } void set_sgl_sw_state(bool state) { if (state) { on_sgl_sw(); } else { off_sgl_sw(); } set_lighting_state(rm_sgl_sw_state); } /*! * @brief Callback function for single switch button and to update cloud. * @param event Logs in the type of event that is driven by the type of example and button pressed. */ void my_single_switch_cb(lv_event_t *event) { lv_event_code_t code = lv_event_get_code(event); if (is_sgl_switch_off(code)) { on_sgl_sw(); } else if (is_sgl_switch_on(code)) { off_sgl_sw(); } set_lighting_state(rm_sgl_sw_state); update_rm_param(PARAM_TYPE, ESP_RMAKER_PARAM_POWER, switch_device, esp_rmaker_bool(rm_sgl_sw_state)); } /** * This section is for light device driver. */ //======================================================================================================================= static bool is_light_sw_off(lv_event_code_t code) { return is_light_scrn && light_sw_array[ON_OFF_SW] && !rm_light_sw_state; } static bool is_light_sw_on(lv_event_code_t code) { return is_light_scrn && light_sw_array[ON_OFF_SW] && rm_light_sw_state; } static void on_light_sw(void) { if (lvgl_port_lock()) { lv_obj_add_state(light_sw, LV_STATE_CHECKED); rm_light_sw_state = true; lvgl_port_unlock(); } } static void off_light_sw(void) { if (lvgl_port_lock()) { lv_obj_clear_state(light_sw, LV_STATE_CHECKED); rm_light_sw_state = false; lvgl_port_unlock(); } } static void set_indicator_color(lv_obj_t *object, int color) { if (lvgl_port_lock()) { lv_obj_set_style_bg_color(object, lv_color_hex(color), LV_PART_KNOB); lvgl_port_unlock(); } } /*! * @brief To set the indicator color on the light switch to determine if it is going up or going down. * @note Green increases in value, orange decreases in value. */ static void set_indicator_dir_color(lv_obj_t *object, bool sw_direction) { if (lvgl_port_lock()) { if (sw_direction) { lv_obj_set_style_bg_color(object, lv_color_hex(COLOR_GREEN), LV_PART_KNOB); } else { lv_obj_set_style_bg_color(object, lv_color_hex(COLOR_ORANGE), LV_PART_KNOB); } lvgl_port_unlock(); } } /*! * @brief Sets the frequency of how fast the button can be pressed in a period of time. * @param event_btn_time The time at which the button was last pressed. */ static void set_btn_freq(unsigned long event_btn_time) { unsigned long [MASK] = esp_timer_get_time() / 1000; if ( [MASK] - event_btn_time < EVENT_DEBOUNCE_INTERVAL) { return; } event_btn_time = [MASK] ; } bool get_light_sw_status(int call_sw) { return light_sw_array[call_sw]; } void set_sw(int call_sw) { for (int i = 0; i < 3; i++) { if (i == call_sw) { light_sw_array[call_sw] = true; } else { light_sw_array[i] = false; } } } void set_light_sw_state(bool state) { if (state) { on_light_sw(); } else { off_light_sw(); } set_lighting_state(rm_light_sw_state); } void set_light_brt(int brt_value) { if (lvgl_port_lock()) { lv_slider_set_value(brt_slider, brt_value, LV_ANIM_ON); lvgl_port_unlock(); } set_brt(); } void set_light_hue(int hue_value) { if (lvgl_port_lock()) { lv_slider_set_value(hue_slider, hue_value, LV_ANIM_ON); lvgl_port_unlock(); } set_hue(); } /*! * @brief Callback function to select the type of switch within the light device. * @param event Logs in the type of event that is driven by the type of example and button pressed. */ void light_sw_select_cb(lv_event_t *event) { lv_event_code_t code = lv_event_get_code(event); if (is_light_scrn && code == LV_EVENT_SHORT_CLICKED) { if (get_light_sw_status(ON_OFF_SW)) { set_sw(BRT_SW); set_indicator_color(light_sw, COLOR_WHITE); set_indicator_dir_color(brt_slider, brt_sw_direction); } else if (get_light_sw_status(BRT_SW)) { set_sw(HUE_SW); set_indicator_color(brt_slider, COLOR_WHITE); set_indicator_dir_color(hue_slider, hue_sw_direction); } else if (get_light_sw_status(HUE_SW)) { set_sw(ON_OFF_SW); set_indicator_color(hue_slider, COLOR_WHITE); set_indicator_color(light_sw, COLOR_ORANGE); } } } /*! * @brief Callback function to control on/off function of light device. * @param event Logs in the type of event that is driven by the type of example and button pressed. */ void light_sw_cb(lv_event_t *event) { lv_event_code_t code = lv_event_get_code(event); if (is_light_sw_off(code)) { on_light_sw(); } else if (is_light_sw_on(code)) { off_light_sw(); } set_lighting_state(rm_light_sw_state); update_rm_param(PARAM_TYPE, ESP_RMAKER_PARAM_POWER, light_device, esp_rmaker_bool(rm_light_sw_state)); } /*! * @brief Callback function to control the brightness function of light device. * @param event Logs in the type of event that is driven by the type of example and button pressed. */ void light_brt_cb(lv_event_t *event) { lv_event_code_t code = lv_event_get_code(event); if (code == LV_EVENT_CLICKED) { set_btn_freq(last_event_time_brt); if (brt_sw_direction == SW_DIRECTION_UP && brt_level <= FULL_BRT) { brt_level += 5; } else if (brt_sw_direction == SW_DIRECTION_DOWN && brt_level >= NULL_BRT) { brt_level -= 5; } set_light_brt(brt_level); update_rm_param(PARAM_TYPE, ESP_RMAKER_PARAM_BRIGHTNESS, light_device, esp_rmaker_int(brt_level)); } else if (code == LV_EVENT_LONG_PRESSED) { brt_sw_direction ^= 1; set_indicator_dir_color(brt_slider, brt_sw_direction); } } /*! * @brief Callback function to control the hue function of light device. * @param event Logs in the type of event that is driven by the type of example and button pressed. */ void light_hue_cb(lv_event_t *event) { lv_event_code_t code = lv_event_get_code(event); if (code == LV_EVENT_CLICKED) { set_btn_freq(last_event_time_hue); if (hue_sw_direction == SW_DIRECTION_UP && hue_level <= MAX_HUE) { hue_level += 10; } else if (hue_sw_direction == SW_DIRECTION_DOWN && hue_level >= MIN_HUE) { hue_level -= 10; } if (hue_level > MAX_HUE) { hue_level = MAX_HUE; } else if (hue_level < MIN_HUE) { hue_level = MIN_HUE; } set_light_hue(hue_level); update_rm_param(PARAM_TYPE, ESP_RMAKER_PARAM_HUE, light_device, esp_rmaker_int(hue_level)); } else if (code == LV_EVENT_LONG_PRESSED) { hue_sw_direction ^= 1; set_indicator_dir_color(hue_slider, hue_sw_direction); } } /** * This section is for relay device driver. */ //======================================================================================================================= static bool is_relay_sw_off(int relay_sw, bool rm_relay_sw_state) { return is_relay_scrn && relay_sw_array[relay_sw] && !rm_relay_sw_state; } static bool is_relay_sw_on(int relay_sw, bool rm_relay_sw_state) { return is_relay_scrn && relay_sw_array[relay_sw] && rm_relay_sw_state; } static bool get_relay_sw_status(int call_sw) { return relay_sw_array[call_sw]; } static void on_relay_sw(lv_obj_t *relay_sw) { if (lvgl_port_lock()) { lv_obj_add_state(relay_sw, LV_STATE_CHECKED); lvgl_port_unlock(); } } static void off_relay_sw(lv_obj_t *relay_sw) { if (lvgl_port_lock()) { lv_obj_clear_state(relay_sw, LV_STATE_CHECKED); lvgl_port_unlock(); } } /*! * @brief Set the relay switch state based on the button pressed and update cloud. * @param relay_sw object of the relay switch on M5 interface. * @param relay_name param name set in app_main.cpp during param creation for relay device. * @param relay_index To select the switch index to obtain its bool state as it is stored in an array. * @param rm_relay_state actual state of particular relay switch state. */ static void set_relay_sw_btn(lv_obj_t *relay_sw, const char *relay_name, uint8_t relay_index, bool rm_relay_state) { if (rm_relay_state) { rm_relay_sw_state[relay_index] = false; off_relay_sw(relay_sw); } else { rm_relay_sw_state[relay_index] = true; on_relay_sw(relay_sw); } update_rm_param(PARAM_NAME, relay_name, relay_device, esp_rmaker_bool(rm_relay_sw_state[relay_index])); } /*! * @brief Set which relay switch to be selected on the M5 interface. * @param call_sw An indexing of the relay switch. * Index 0: switch_1; Index 1: switch_2 * Index 2: switch_3; Index 3: switch_4 */ void set_relay_sw(int call_sw) { for (int i = 0; i < 4; i++) { if (i == call_sw) { relay_sw_array[call_sw] = true; } else { relay_sw_array[i] = false; } } } /*! * @brief To set the state of the relay switch in the M5stickCplus interface. */ void set_relay_sw_state(void) { for (int relay_sw = 0; relay_sw < 4; relay_sw++) { if (rm_relay_sw_state[relay_sw]) { if (relay_sw == RELAY_SW_1) { on_relay_sw(relay_sw_1); } else if (relay_sw == RELAY_SW_2) { on_relay_sw(relay_sw_2); } else if (relay_sw == RELAY_SW_3) { on_relay_sw(relay_sw_3); } else if (relay_sw == RELAY_SW_4) { on_relay_sw(relay_sw_4); } } else { if (relay_sw == RELAY_SW_1) { off_relay_sw(relay_sw_1); } else if (relay_sw == RELAY_SW_2) { off_relay_sw(relay_sw_2); } else if (relay_sw == RELAY_SW_3) { off_relay_sw(relay_sw_3); } else if (relay_sw == RELAY_SW_4) { off_relay_sw(relay_sw_4); } } } set_relay(); } /*! * @brief To disconnect the relay module from the current task. Switch all relay to off, * then turning deinitialising i2c signal else. set FastLED to default state. */ void disc_relay(void) { if (is_relay_scrn) { set_lighting_state(DEFAULT_SWITCH_POWER); set_relay_off(); deinit_i2c(); } else { set_lighting_state(DEFAULT_SWITCH_POWER); } } /*! * @brief Callback function for selection of relay switch. * @param event Logs in the type of event that is driven by the type of example and button pressed. */ void relay_sw_select_cb(lv_event_t *event) { lv_event_code_t code = lv_event_get_code(event); if (is_relay_scrn && code == LV_EVENT_SHORT_CLICKED) { if (get_relay_sw_status(RELAY_SW_1)) { set_relay_sw(RELAY_SW_2); set_indicator_color(relay_sw_1, COLOR_WHITE); set_indicator_color(relay_sw_2, COLOR_ORANGE); } else if (get_relay_sw_status(RELAY_SW_2)) { set_relay_sw(RELAY_SW_3); set_indicator_color(relay_sw_2, COLOR_WHITE); set_indicator_color(relay_sw_3, COLOR_ORANGE); } else if (get_relay_sw_status(RELAY_SW_3)) { set_relay_sw(RELAY_SW_4); set_indicator_color(relay_sw_3, COLOR_WHITE); set_indicator_color(relay_sw_4, COLOR_ORANGE); } else if (get_relay_sw_status(RELAY_SW_4)) { set_relay_sw(RELAY_SW_1); set_indicator_color(relay_sw_4, COLOR_WHITE); set_indicator_color(relay_sw_1, COLOR_ORANGE); } } } /*! * @brief Callback function for relay switch. * @param event Logs in the type of event that is driven by the type of example and button pressed. */ void relay_sw_cb(lv_event_t *event) { if (is_relay_sw_on(RELAY_SW_1, rm_relay_sw_state[RELAY_SW_1])) { set_relay_sw_btn(relay_sw_1, ""switch_1"", RELAY_SW_1, rm_relay_sw_state[RELAY_SW_1]); } else if (is_relay_sw_on(RELAY_SW_2, rm_relay_sw_state[RELAY_SW_2])) { set_relay_sw_btn(relay_sw_2, ""switch_2"", RELAY_SW_2, rm_relay_sw_state[RELAY_SW_2]); } else if (is_relay_sw_on(RELAY_SW_3, rm_relay_sw_state[RELAY_SW_3])) { set_relay_sw_btn(relay_sw_3, ""switch_3"", RELAY_SW_3, rm_relay_sw_state[RELAY_SW_3]); } else if (is_relay_sw_on(RELAY_SW_4, rm_relay_sw_state[RELAY_SW_4])) { set_relay_sw_btn(relay_sw_4, ""switch_4"", RELAY_SW_4, rm_relay_sw_state[RELAY_SW_4]); } else if (is_relay_sw_off(RELAY_SW_1, rm_relay_sw_state[RELAY_SW_1])) { set_relay_sw_btn(relay_sw_1, ""switch_1"", RELAY_SW_1, rm_relay_sw_state[RELAY_SW_1]); } else if (is_relay_sw_off(RELAY_SW_2, rm_relay_sw_state[RELAY_SW_2])) { set_relay_sw_btn(relay_sw_2, ""switch_2"", RELAY_SW_2, rm_relay_sw_state[RELAY_SW_2]); } else if (is_relay_sw_off(RELAY_SW_3, rm_relay_sw_state[RELAY_SW_3])) { set_relay_sw_btn(relay_sw_3, ""switch_3"", RELAY_SW_3, rm_relay_sw_state[RELAY_SW_3]); } else if (is_relay_sw_off(RELAY_SW_4, rm_relay_sw_state[RELAY_SW_4])) { set_relay_sw_btn(relay_sw_4, ""switch_4"", RELAY_SW_4, rm_relay_sw_state[RELAY_SW_4]); } set_relay(); }",now 190,"#pragma once #include #include #include #include #include namespace nonstd { namespace Detail { template [[nodiscard]] T* allocate_uninit(size_t count) { return reinterpret_cast(::operator new[](sizeof(T)* count, std::align_val_t{ alignof(T) })); } template void deallocate_no_destroy(T* ptr, size_t [MASK] ) { ::operator delete[](static_cast(ptr), [MASK] * sizeof(T), std::align_val_t{ alignof(T) }); } template void destroy_range_reverse(T* start, T* end) { // Note: Compiler should be able to figure this out its own, // but better make sure. if constexpr (!std::is_trivially_destructible_v) { while (end != start) { --end; std::destroy_at(end); } } } template inline void construct_at(T* const ptr, Args&&... args) { ::new (static_cast(ptr)) T(std::forward(args)...); } } // end namespace Detail template class vector { T* m_first = nullptr; T* m_next = nullptr; T* m_end = nullptr; [[nodiscard]] size_t calculate_new_cap(const size_t new_cap) { const auto old_cap = capacity(); const auto geometric_cap = old_cap + old_cap / 2; return std::max(new_cap, geometric_cap); } void adopt_new_memory(T* new_memory, size_t new_capacity) { const auto old_size = size(); m_next = std::uninitialized_move(m_first, m_next, new_memory); Detail::deallocate_no_destroy(m_first, old_size); m_first = new_memory; m_end = m_first + new_capacity; } static_assert(std::is_nothrow_move_constructible_v, ""No.""); public: using iterator = T*; using const_iterator = T const*; vector() = default; ~vector() { Detail::destroy_range_reverse(m_first, m_next); Detail::deallocate_no_destroy(m_first, size()); } // We don't need these for benchmarks/tests vector(vector const& rhs) : vector() { reserve(rhs.size()); std::uninitialized_copy(rhs.begin(), rhs.end(), m_first); } vector& operator=(vector const& rhs) { if (this == &rhs) { return *this; } // If the elements are no-throw copy constructible, we // can avoid a temporary allocation if we hold enough // memory. if constexpr (std::is_nothrow_copy_constructible_v) { Detail::destroy_range_reverse(m_first, m_next); if (rhs.size() > capacity()) { Detail::deallocate_no_destroy(m_first, size()); m_first = Detail::allocate_uninit(rhs.size()); m_end = m_first + rhs.size(); } m_next = std::uninitialized_copy(rhs.m_first, rhs.m_next, m_first); } else { // For throwing copies we have to make a temporary // allocation, so we go with the copy & swap idiom auto temp(rhs); swap(*this, temp); } return *this; } vector(vector&& rhs) noexcept : m_first(std::exchange(rhs.m_first, nullptr)), m_next(std::exchange(rhs.m_next, nullptr)), m_end(std::exchange(rhs.m_end, nullptr)) {} vector& operator=(vector&& rhs) noexcept { auto temp(std::move(rhs)); swap(*this, temp); return *this; } void push_back(T const& elem) { if (m_next != m_end) { Detail::construct_at(m_next, elem); ++m_next; return; } const auto current_size = size(); const auto new_cap = calculate_new_cap(current_size + 1); auto* new_memory = Detail::allocate_uninit(new_cap); // Constructing new element has to happen before we move // old elements, in case someone is doing `v.push_back(v[0])` try { Detail::construct_at(new_memory + current_size, elem); } catch (...) { Detail::deallocate_no_destroy(new_memory, new_cap); // rethrow after fixup, so user knows it happened throw; } adopt_new_memory(new_memory, new_cap); // Account for the inserted element ++m_next; } void push_back(T&& elem) { if (m_next != m_end) { Detail::construct_at(m_next, std::move(elem)); ++m_next; return; } const auto current_size = size(); const auto new_cap = calculate_new_cap(current_size + 1); auto* new_memory = Detail::allocate_uninit(new_cap); // Constructing new element has to happen before we move // old elements, in case someone is doing `v.push_back(v[0])` // We do not have to catch exception here, as we static assert // nothrow move constructibility on our elements. Detail::construct_at(new_memory + current_size, std::move(elem)); adopt_new_memory(new_memory, new_cap); // Account for the element inserted ahead of time ++m_next; } void push_back_unchecked(T const& elem) noexcept(std::is_nothrow_copy_constructible_v) { assert(m_next != m_end); Detail::construct_at(m_next, elem); ++m_next; } void push_back_unchecked(T&& elem) noexcept { assert(m_next != m_end); Detail::construct_at(m_next, std::move(elem)); ++m_next; } void reserve(size_t target_capacity) { if (target_capacity <= capacity()) { return; } const auto new_cap = calculate_new_cap(target_capacity); auto new_memory = Detail::allocate_uninit(new_cap); adopt_new_memory(new_memory, new_cap); } friend void swap(vector& lhs, vector& rhs) noexcept { std::swap(lhs.m_first, rhs.m_first); std::swap(lhs.m_next, rhs.m_next); std::swap(lhs.m_end, rhs.m_end); } [[nodiscard]] T& operator[](size_t idx) { return m_first[idx]; } [[nodiscard]] T const& operator[](size_t idx) const { return m_first[idx]; } [[nodiscard]] size_t size() const { return m_next - m_first; } [[nodiscard]] size_t capacity() const { return m_end - m_first; } [[nodiscard]] iterator begin() { return m_first; } [[nodiscard]] const_iterator begin() const { return m_first; } [[nodiscard]] iterator end() { return m_next; } [[nodiscard]] const_iterator end() const { return m_next; } }; } // end nonstd namespace ",num_elements 191,"//Card.cpp : Contains all card related functions. //Authors : () //#include ""stdafx.h"" //INCLUDE FOR VISUAL STUDIO #include ""Card.h"" using namespace std; Card::Card() :cardRank(TWO), cardSuit(CLUBS) {} Card::Card(int r, int s) : cardRank((Card::rank)r), cardSuit((Card::suit)s) {} int parse_cards(vector & cards, char * file_name) { ifstream ifs; ifs.open(file_name); if (ifs.is_open()) { while (!ifs.eof()) //continue reading until we reach the end of the file { vector tmpHand; //holds cards temporarally to make sure they perfectly fill a hand on each line (exactly five cards) string line, word; getline(ifs, line); //read off each line of the file istringstream iss(line); while (iss >> word) //read off each word to parse card information from it { Card card; const int word_first_index = 0; const int word_second_index = 1; const int word_last_index = word.size() - 1; const int normal_card_size = 2; const int card_size_if_ten = 3; const int beginCommentLength = 2; const char commentCharacter = '/'; char suitChar = word[word_last_index]; bool valid = true; if (word.size() >= beginCommentLength && word[word_first_index] == commentCharacter && word[word_second_index] == commentCharacter) //if we hit a comment, we want to stop reading cards from this line { break; } if (word.size() == normal_card_size || word.size() == card_size_if_ten) //a normal card will have 2 characters unless it has a 10 in which case it will have 3 characters { if (suitChar == 'C' || suitChar == 'c') { card.cardSuit = Card::suit::CLUBS; } else if (suitChar == 'D' || suitChar == 'd') { card.cardSuit = Card::suit::DIAMONDS; } else if (suitChar == 'H' || suitChar == 'h') { card.cardSuit = Card::suit::HEARTS; } else if (suitChar == 'S' || suitChar == 's') { card.cardSuit = Card::suit::SPADES; } else { valid = false; } if (word.size() == card_size_if_ten && word[word_first_index] == '1' && word[word_second_index] == '0') //special check if a card has rank 10 since this is the only rank with two characters { card.cardRank = Card::rank::TEN; } else { switch (word[word_first_index]) { case 'A' : case 'a' : card.cardRank = Card::rank::ACE; break; case 'K' : case 'k' : card.cardRank = Card::rank::KING; break; case 'Q': case 'q': card.cardRank = Card::rank::QUEEN; break; case 'J': case 'j': card.cardRank = Card::rank::JACK; break; case '9': card.cardRank = Card::rank::NINE; break; case '8': card.cardRank = Card::rank::EIGHT; break; case '7': card.cardRank = Card::rank::SEVEN; break; case '6': card.cardRank = Card::rank::SIX; break; case '5': card.cardRank = Card::rank::FIVE; break; case '4': card.cardRank = Card::rank::FOUR; break; case '3': card.cardRank = Card::rank::THREE; break; case '2': card.cardRank = Card::rank::TWO; break; default : valid = false; //a card that does not fall into any above catagory has an invalid rank } } if (valid) //only add valid cards { tmpHand.push_back(card); } } } for (Card card : tmpHand) //go through cards from the line adding each to overall vector { cards.push_back(card); } } } else { cout << ""Error opening file!"" << endl; return errors::fileOpenError; } ifs.close();//close the filestream when done return errors::noError; } int print_cards(const vector & cards) { for (Card card : cards) { string cardString; const int firstIndex = 0; if (card.cardRank < firstIndex || card.cardRank >= numRanks || card.cardSuit < firstIndex || card.cardSuit >= numSuits) //all cards that correspond to indexes of the card suit and rank arrays will be valid all others are errors { cout << ""Error reading cards from vector!"" << endl; return errors::cardReadError; } cardString = rankStrings[card.cardRank] + suitStrings[card.cardSuit]; cout << cardString << endl; } return errors::noError; } void usage_message(string program_name, string message) { cout << program_name <<"": ""<< message << endl; } bool Card::operator< (const Card & crd) const { return (cardRank < crd.cardRank) || ((cardRank == crd.cardRank) && (cardSuit < crd.cardSuit)); //sorts first by rank and then by suit } bool Card::operator== (const Card & crd) const { return (cardRank == crd.cardRank) && (cardSuit == crd.cardSuit); //equality } int print_poker_rank(vector & cards) { const int [MASK] = 5; //size of a valid hand const int quad = 4; //number of cards in a four of a kind const int triplet = 3; //number of cards in a three of a kind const int pair = 2; //number of cards in a two of a kind vector crntHand; //the current five cards we are detemining the rank of int itr = 0; while (itr + [MASK] <= cards.size()) //go through each hand while we still have a hand's worth of cards to check { int i = 0; while (i < [MASK] ) //built a hand out of the next cards { crntHand.push_back(cards[itr+i]); //itr+i to get the cards after the current start point ++i; } sort(crntHand.begin(), crntHand.end()); //sorts the crntHand according to the less than operator //checks the overall hand for a flush or a straight bool flush = crntHand[0].cardSuit == crntHand[1].cardSuit && crntHand[0].cardSuit == crntHand[2].cardSuit && crntHand[0].cardSuit == crntHand[3].cardSuit && crntHand[0].cardSuit == crntHand[4].cardSuit; bool straight = (crntHand[0].cardRank + 1) == crntHand[1].cardRank && (crntHand[1].cardRank + 1) == crntHand[2].cardRank && (crntHand[2].cardRank + 1) == crntHand[3].cardRank && (crntHand[3].cardRank + 1) == crntHand[4].cardRank; //checks for any multiples of a rank int maxCount = 0; //maximum number of cards of the same rank in hand int secondCount = 0; //second best amount of cards of the same rank (for full house and two pairs) int j; for (j = 0; j < [MASK] ; j++) //go through all cards in hand beginning with first one { Card cardOne = crntHand[j]; //store card currently examined int crntCount = 1; //there are one of that rank so far int k; for (k = j + 1; k < [MASK] ; ++k) //go through rest of cards finding the rest of that rank { Card cardTwo = crntHand[k]; if (cardOne.cardRank == cardTwo.cardRank) //check if ranks are the same { ++j; //increment j so we dont double count the matching card ++crntCount; //increment count of the rank seen } else //since cards are sorted, we know we will not hit any more of that rank once we find the first that is not of that rank so we can break { break; } } if (crntCount > maxCount) //if we found a new maximum set it as so { secondCount = maxCount; maxCount = crntCount; } else if (crntCount > secondCount) //if we found a new second most cards set it as so { secondCount = crntCount; } } //go through all hand possibilities starting with the best down to the worst and declare which we match if (flush && straight) { cout << ""straight flush"" << endl; } else if (maxCount == quad) { cout << ""four of a kind"" << endl; } else if (maxCount == triplet && secondCount == pair) { cout << ""full house"" << endl; } else if (flush) { cout << ""flush"" << endl; } else if (straight) { cout << ""straight"" << endl; } else if (maxCount == triplet) { cout << ""three of a kind"" << endl; } else if (maxCount == pair && secondCount == pair) { cout << ""two pairs"" << endl; } else if (maxCount == pair) { cout << ""one pair"" << endl; } else { cout << ""no rank"" << endl; } crntHand.clear(); //remove the cards we were examining so we can examine the next hand itr += [MASK] ; //incerment the hand start we are on by a whole hand since we have just examined that hand. } return 0; //no error } Card & Card::operator= (const Card & other) { cardRank = other.cardRank; cardSuit = other.cardSuit; return *this; } int rank_count(const Card * begin, const Card * end, const Card card) { int rank = card.cardRank; int count = 0; while (begin != end) { if ((*begin).cardRank == rank) { ++count; } ++begin; } return count; } ",handSize 192,"// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // -*- Mode: C++ -*- // // Copyright (C) 2021 Oracle, Inc. // // Author: /// @file /// /// This file implement the CTF testsuite. It reads ELF binaries /// containing CTF, save them in XML corpus files and diff the /// corpus files against reference XML corpus files. #include #include #include #include #include #include #include ""abg-ctf-reader.h"" #include ""test-read-common.h"" using std::string; using std::cerr; using std::vector; using abigail::tests::read_common::InOutSpec; using abigail::tests::read_common::test_task; using abigail::tests::read_common::display_usage; using abigail::tests::read_common::options; using abigail::ctf_reader::read_context_sptr; using abigail::ctf_reader::create_read_context; using abigail::xml_writer::SEQUENCE_TYPE_ID_STYLE; using abigail::xml_writer::HASH_TYPE_ID_STYLE; using abigail::tools_utils::emit_prefix; static InOutSpec in_out_specs[] = { { ""data/test-read-ctf/test0"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test0.abi"", ""output/test-read-ctf/test0.abi"" }, { ""data/test-read-ctf/test0"", """", """", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/test0.hash.abi"", ""output/test-read-ctf/test0.hash.abi"" }, { ""data/test-read-ctf/test1.so"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test1.so.abi"", ""output/test-read-ctf/test1.so.abi"" }, { ""data/test-read-ctf/test1.so"", """", """", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/test1.so.hash.abi"", ""output/test-read-ctf/test1.so.hash.abi"" }, { ""data/test-read-ctf/test2.so"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test2.so.abi"", ""output/test-read-ctf/test2.so.abi"" }, { ""data/test-read-ctf/test2.so"", """", """", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/test2.so.hash.abi"", ""output/test-read-ctf/test2.so.hash.abi"" }, { ""data/test-read-common/test3.so"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test3.so.abi"", ""output/test-read-ctf/test3.so.abi"" }, { ""data/test-read-common/test3.so"", """", """", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/test3.so.hash.abi"", ""output/test-read-ctf/test3.so.hash.abi"" }, { ""data/test-read-ctf/test-enum-many.o"", """", """", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/test-enum-many.o.hash.abi"", ""output/test-read-ctf/test-enum-many.o.hash.abi"" }, { ""data/test-read-ctf/test-ambiguous-struct-A.o"", """", """", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/test-ambiguous-struct-A.o.hash.abi"", ""output/test-read-ctf/test-ambiguous-struct-A.o.hash.abi"" }, { ""data/test-read-ctf/test-ambiguous-struct-B.o"", """", """", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/test-ambiguous-struct-B.o.hash.abi"", ""output/test-read-ctf/test-ambiguous-struct-B.o.hash.abi"" }, { ""data/test-read-ctf/test-conflicting-type-syms-a.o"", """", """", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/test-conflicting-type-syms-a.o.hash.abi"", ""output/test-read-ctf/test-conflicting-type-syms-a.o.hash.abi"" }, { ""data/test-read-ctf/test-conflicting-type-syms-b.o"", """", """", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/test-conflicting-type-syms-b.o.hash.abi"", ""output/test-read-ctf/test-conflicting-type-syms-b.o.hash.abi"" }, { ""data/test-read-common/test4.so"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test4.so.abi"", ""output/test-read-ctf/test4.so.abi"" }, { ""data/test-read-common/test4.so"", """", """", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/test4.so.hash.abi"", ""output/test-read-ctf/test4.so.hash.abi"" }, { ""data/test-read-ctf/test5.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test5.o.abi"", ""output/test-read-ctf/test5.o.abi"" }, { ""data/test-read-ctf/test7.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test7.o.abi"", ""output/test-read-ctf/test7.o.abi"" }, { ""data/test-read-ctf/test8.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test8.o.abi"", ""output/test-read-ctf/test8.o.abi"" }, { ""data/test-read-ctf/test9.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test9.o.abi"", ""output/test-read-ctf/test9.o.abi"" }, { ""data/test-read-ctf/test-enum.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test-enum.o.abi"", ""output/test-read-ctf/test-enum.o.abi"" }, { ""data/test-read-ctf/test-enum-symbol.o"", """", """", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/test-enum-symbol.o.hash.abi"", ""output/test-read-ctf/test-enum-symbol.o.hash.abi"" }, { ""data/test-read-ctf/test-dynamic-array.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test-dynamic-array.o.abi"", ""output/test-read-ctf/test-dynamic-array.o.abi"" }, { ""data/test-read-ctf/test-anonymous-fields.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test-anonymous-fields.o.abi"", ""output/test-read-ctf/test-anonymous-fields.o.abi"" }, { ""data/test-read-common/PR27700/test-PR27700.o"", """", ""data/test-read-common/PR27700/pub-incdir"", HASH_TYPE_ID_STYLE, ""data/test-read-ctf/PR27700/test-PR27700.abi"", ""output/test-read-ctf/PR27700/test-PR27700.abi"", }, { ""data/test-read-ctf/test-callback.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test-callback.abi"", ""output/test-read-ctf/test-callback.abi"", }, { ""data/test-read-ctf/test-array-of-pointers.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test-array-of-pointers.abi"", ""output/test-read-ctf/test-array-of-pointers.abi"", }, { ""data/test-read-ctf/test-functions-declaration.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test-functions-declaration.abi"", ""output/test-read-ctf/test-functions-declaration.abi"", }, { ""data/test-read-ctf/test-forward-type-decl.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test-forward-type-decl.abi"", ""output/test-read-ctf/test-forward-type-decl.abi"", }, { ""data/test-read-ctf/test-list-struct.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test-list-struct.abi"", ""output/test-read-ctf/test-list-struct.abi"", }, { ""data/test-read-common/test-PR26568-1.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test-PR26568-1.o.abi"", ""output/test-read-ctf/test-PR26568-1.o.abi"", }, { ""data/test-read-common/test-PR26568-2.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test-PR26568-2.o.abi"", ""output/test-read-ctf/test-PR26568-2.o.abi"", }, { ""data/test-read-ctf/test-callback2.o"", """", """", SEQUENCE_TYPE_ID_STYLE, ""data/test-read-ctf/test-callback2.abi"", ""output/test-read-ctf/test-callback2.abi"", }, // This should be the last entry. {NULL, NULL, NULL, SEQUENCE_TYPE_ID_STYLE, NULL, NULL} }; /// Task specialization to perform CTF tests. struct test_task_ctf : public test_task { test_task_ctf(const InOutSpec &s, string& a_out_abi_base, string& a_in_elf_base, string& a_in_abi_base); virtual void perform(); virtual ~test_task_ctf() {} }; // end struct test_task_ctf /// Constructor. /// /// Task to be executed for each CTF test entry in @ref /// abigail::tests::read_common::InOutSpec. /// @param InOutSpec the array containing set of tests. /// /// @param a_out_abi_base the output base directory for abixml files. /// /// @param a_in_elf_base the input base directory for object files. /// /// @param a_in_elf_base the input base directory for expected /// abixml files. test_task_ctf::test_task_ctf(const InOutSpec &s, string& a_out_abi_base, string& a_in_elf_base, string& a_in_abi_base) : test_task(s, a_out_abi_base, a_in_elf_base, a_in_abi_base) {} /// The thread function to execute each CTF test entry in @ref /// abigail::tests::read_common::InOutSpec. /// /// This reads the corpus into memory, saves it to disk, loads it /// again and compares the new in-memory representation against the void test_task_ctf::perform() { abigail::ir::environment_sptr env; set_in_elf_path(); set_in_suppr_spec_path(); env.reset(new abigail::ir::environment); abigail::elf_reader::status status = abigail::elf_reader::STATUS_UNKNOWN; vector di_roots; ABG_ASSERT(abigail::tools_utils::file_exists(in_elf_path)); read_context_sptr ctxt = create_read_context(in_elf_path, di_roots, env.get()); ABG_ASSERT(ctxt); corpus_sptr corp = read_corpus(ctxt.get(), status); // if there is no output and no input, assume that we do not care about the // actual read result, just that it succeeded. if (!spec.in_abi_path && !spec.out_abi_path) { // Phew! we made it here and we did not crash! yay! return; } if (!corp) { error_message = string(""failed to read "") + in_elf_path + ""\n""; is_ok = false; return; } corp->set_path(spec.in_elf_path); // Do not take architecture names in comparison so that these // test input binaries can come from whatever arch the // programmer likes. corp->set_architecture_name(""""); if (!(is_ok = set_out_abi_path())) return; if (!(is_ok = serialize_corpus(out_abi_path, corp))) return; if (!(is_ok = run_abidw(""--ctf ""))) return; if (!(is_ok = run_diff())) return; } /// Create a new CTF instance for task to be execute by the testsuite. /// /// @param s the @ref abigail::tests::read_common::InOutSpec /// tests container. /// /// @param a_out_abi_base the output base directory for abixml files. /// /// @param a_in_elf_base the input base directory for object files. /// /// @param a_in_abi_base the input base directory for abixml files. /// /// @return abigail::tests::read_common::test_task instance. static test_task* new_task(const InOutSpec* s, string& a_out_abi_base, string& a_in_elf_base, string& a_in_abi_base) { return new test_task_ctf(*s, a_out_abi_base, a_in_elf_base, a_in_abi_base); } int main(int argc, char *argv[]) { options [MASK] ; if (!parse_command_line(argc, argv, [MASK] )) { if (! [MASK] .wrong_option.empty()) emit_prefix(argv[0], cerr) << ""unrecognized option: "" << [MASK] .wrong_option << ""\n""; display_usage(argv[0], cerr); return 1; } // compute number of tests to be executed. const size_t num_tests = sizeof(in_out_specs) / sizeof(InOutSpec) - 1; return run_tests(num_tests, in_out_specs, [MASK] , new_task); } ",opts 193,"#include #include #include //PLAYING FIELD DIMENSIONS// const int H = 4; // HIGHT const int W = 4; // WEIGHT int field[H+2][W+2] = { {-1, -1, -1, -1, -1, -1}, {-1, 0, 1, 2, 3, -1}, {-1, 4, 5, 6, 7, -1}, {-1, 8, 9, 10, 11, -1}, {-1, 12, 13, 14, 15, -1}, {-1, -1, -1, -1, -1, -1}, }; int tiles[16][2] = { {0, 0}, {0, 1}, {0, 2}, {0, 3}, // 1 2 3 4 {1, 0}, {1, 1}, {1, 2}, {1, 3}, // 5 6 7 8 {2, 0}, {2, 1}, {2, 2}, {2, 3}, // 9 10 11 12 {3, 0}, {3, 1}, {3, 2}, {3, 3}, // 13 14 15 16 }; int main() { // Îáúåêò, êîòîðûé, ñîáñòâåííî, ÿâëÿåòñÿ ãëàâíûì îêíîì ïðèëîæåíèÿ sf::RenderWindow [MASK] (sf::VideoMode(256, 256), ""Fivenashki""); // shuffling for field srand(time(0)); for (int i = 1; i <= H; ++i) { for (int j = 1; j <= W; ++j) { std::swap(field[i][j], field[(std::rand() % H) + 1][(std::rand() % W) + 1]); } } // connectings texture sf::Texture texture; int w = 64; const char* path = ""five.png""; texture.loadFromFile(path); // start sprite sf::Sprite sprite(texture); // mouse sf::Vector2i pos = sf::Mouse::getPosition( [MASK] ); int x = (pos.x / w) - 1; int y = (pos.y / w) - 1; std::swap(field[2][1], field[2][3]); // Ãëàâíûé öèêë ïðèëîæåíèÿ. Âûïîëíÿåòñÿ, ïîêà îòêðûòî îêíî while ( [MASK] .isOpen()) { sf::Vector2i pos = sf::Mouse::getPosition( [MASK] ); int x = (pos.x / w)+1; int y = (pos.y / w)+1; // Îáðàáàòûâàåì î÷åðåäü ñîáûòèé â öèêëå sf::Event event; while ( [MASK] .pollEvent(event)) { // Ïîëüçîâàòåëü íàæàë íà «êðåñòèê» è õî÷åò çàêðûòü îêíî? if (event.type == sf::Event::Closed) // òîãäà çàêðûâàåì åãî [MASK] .close(); else if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { if (!(15-field[x - 1][y])) std::swap(field[x][y], field[x - 1][y]); else if (!(15 - field[x][y - 1])) std::swap(field[x][y], field[x][y - 1]); else if (!(15 - field[x][y + 1])) std::swap(field[x][y], field[x][y + 1]); else if (!(15 - field[x + 1][y])) std::swap(field[x][y], field[x + 1][y]); } } // Îòðèñîâêà îêíà for (int i = 1; i <= H; ++i) for (int j = 1; j <= W; ++j) { sprite.setTextureRect(sf::IntRect(tiles[field[i][j]][0] * w, tiles[field[i][j]][1] *w, w, w)); sprite.setPosition((i-1) * w, (j-1) * w); [MASK] .draw(sprite); } [MASK] .display(); } return 0; } ",window 194,"#ifndef MATH_ANGLE_H #define MATH_ANGLE_H #include ""math_Rational.h"" #include ""math_Vector.h"" namespace math { // Return sin(x) Taylor series to order x^(2n+1). Rational sin(const Rational& x, Unsigned n) { Rational x2 = -x * x; Rational term = x; Rational series = term; for (Unsigned k = 1; k <= n; ++k) { term *= (x2 / (2 * k * (2 * k + 1))); series += term; } return series; } // Return cos(x) Taylor series to order x^(2n). Rational cos(const Rational& x, Unsigned n) { Rational x2 = -x * x; Rational term = 1; Rational series = term; for (Unsigned k = 1; k <= n; ++k) { term *= (x2 / (2 * k * (2 * k - 1))); series += term; } return series; } // Return 1/sqrt(x) with ~200-bit accuracy. Rational inv_sqrt(const Rational& x) { // Iterate Newton's method with f(y) = y^-2 - x. Rational y = std::sqrt((1 / x).to_double()); for (int i = 0; i < 2; ++i) { y *= ((3 - x * y * y) / 2); } return y; } const Rational PI = Rational( ""3.14159265358979323846264338327950288419716939937510582097494""); // Return atan(sqrt(x2)) with ~200-bit accuracy. Rational atan_sqrt(Rational x2) { // Assume 0 < x2 <= 1 using atan(x) == pi/2 - atan(1/x). if (x2 == 0) { return 0; } bool [MASK] = (x2 > 1); if ( [MASK] ) { x2 = 1 / x2; } // Compute Euler's series for atan(x) to n=200. Rational y = x2 / (1 + x2); Rational term = y; Rational series = term; for (Unsigned n = 1; n <= 200; ++n) { term *= (y * (2 * n) / (2 * n + 1)); series += term; } y = inv_sqrt(x2) * series; // Convert back if we used reciprocal identity. if ( [MASK] ) { y = PI / 2 - y; } return y; } // Return ""exact"" angle(u, v) with ~200-bit accuracy. Rational angle_exact(const Vector& u, const Vector& v) { Rational ux = u.x, uy = u.y, uz = u.z; Rational vx = v.x, vy = v.y, vz = v.z; Rational d = ux * vx + uy * vy + uz * vz; // dot(u, v) Rational cx = uy * vz - uz * vy, // cross(u, v) cy = uz * vx - ux * vz, cz = ux * vy - uy * vx; if (d == 0) { return PI / 2; } Rational angle = atan_sqrt((cx * cx + cy * cy + cz * cz) / (d * d)); if (d < 0) { angle = PI - angle; } return angle; } // Return angle between vectors using same ""cross/dot product"" formula. double angle(const Vector& u, const Vector& v) { return std::atan2(norm(cross(u, v)), dot(u, v)); } // Return angle between vectors using law of cosines. double angle0(const Vector& u, const Vector& v) { double u2 = u.x * u.x + u.y * u.y + u.z * u.z; double v2 = v.x * v.x + v.y * v.y + v.z * v.z; Vector d = u - v; return std::acos(std::min(1.0, std::max(-1.0, (u2 + v2 - (d.x * d.x + d.y * d.y + d.z * d.z)) / (2 * std::sqrt(u2) * std::sqrt(v2))))); } // Following are three alternative formulas discussed in: // ., How Futile are Mindless Assessments of Roundoff in // Floating-Point Computation? // (http://people.eecs.berkeley.edu/~wkahan/Mindless.pdf) double angle1(const Vector& u, const Vector& v) { return std::acos(std::min(1.0, std::max(-1.0, dot(u, v) / (norm(u) * norm(v))))); } double angle2(const Vector& u, const Vector& v) { double angle = std::asin(std::min(1.0, norm(cross(u, v)) / (norm(u) * norm(v)))); if (dot(u, v) < 0) { angle = 3.141592653589793 - angle; } return angle; } double angle3(const Vector& u, const Vector& v) { double nu = norm(u); double nv = norm(v); return 2 * std::atan2(norm(nv * u - nu * v), norm(nv * u + nu * v)); } } // namespace math #endif // MATH_ANGLE_H ",invert 195,"// // KittyMemory.cpp // // Created by MJ (Ruit) on 1/1/19. // #include #include ""KittyMemory.h"" #include #include #include #include #include using KittyMemory::Memory_Status; using KittyMemory::ProcMap; struct mapsCache { std::string identifier; ProcMap map; }; static std::vector _procMaps; static std::vector __mapsCache; static ProcMap findMapInCache(std::string id){ ProcMap ret; for(int i = 0; i < __mapsCache.size(); i++){ if(__mapsCache[i].identifier.compare(id) == 0){ ret = __mapsCache[i].map; break; } } return ret; } bool KittyMemory::ProtectAddr(void *addr, size_t length, int protection) { uintptr_t pageStart = _PAGE_START_OF_(addr); uintptr_t pageLen = _PAGE_LEN_OF_(addr, length); return ( mprotect(reinterpret_cast(pageStart), pageLen, protection) != -1 ); } Memory_Status KittyMemory::memWrite(void *addr, const void *buffer, size_t len) { if (addr == NULL) return INV_ADDR; if (buffer == NULL) return INV_BUF; if (len < 1 || len > INT_MAX) return INV_LEN; if (!ProtectAddr(addr, len, _PROT_RWX_)) return INV_PROT; if (memcpy(addr, buffer, len) != NULL && ProtectAddr(addr, len, _PROT_RX_)) return SUCCESS; return FAILED; } Memory_Status KittyMemory::memRead(void *buffer, const void *addr, size_t len) { if (addr == NULL) return INV_ADDR; if (buffer == NULL) return INV_BUF; if (len < 1 || len > INT_MAX) return INV_LEN; if (memcpy(buffer, addr, len) != NULL) return SUCCESS; return FAILED; } std::vector scanMem(uintptr_t startAddr, uintptr_t endAddr, unsigned char *val, size_t len) { std::vector result; unsigned __int64 [MASK] = startAddr; unsigned char readBuffer[4096] = {0,}; size_t readLen = sizeof(readBuffer); LOGI(stringFormat(""scanMem: Start: %p, End: %p, Length: %p"", startAddr, endAddr, endAddr - startAddr).c_str()); while (true) { if ( [MASK] + readLen > endAddr) readLen = endAddr - [MASK] ; if (KittyMemory::memRead(readBuffer, (const void *) [MASK] , readLen) == KittyMemory::SUCCESS) { for (int i = 0; i < readLen; ++i) { if (readBuffer[i] != val[0]) continue; if (readLen - i <= len) break; if (memcmp(readBuffer + i, val, len) == 0) { result.push_back( [MASK] + i); i += len; } } } std::memset(readBuffer, 0, sizeof(readBuffer)); [MASK] += readLen; if ( [MASK] >= endAddr) break; usleep(10); } LOGI(""scanMem: end""); return result; } std::string KittyMemory::read2HexStr(const void *addr, size_t len) { char temp[len]; memset(temp, 0, len); const size_t bufferLen = len * 2 + 1; char buffer[bufferLen]; memset(buffer, 0, bufferLen); std::string ret; if (memRead(temp, addr, len) != SUCCESS) return ret; for (int i = 0; i < len; i++) { sprintf(&buffer[i * 2], ""%02X"", (unsigned char) temp[i]); } ret += buffer; return ret; } std::vector KittyMemory::getMaps() { char line[512] = { 0, }; FILE *fp = fopen(""/proc/self/maps"", ""rt""); if(fp != nullptr) { _procMaps.clear(); while(fgets(line, sizeof(line), fp)) { ProcMap tmpMap; char tmpPerms[5] = {0}, tmpDev[12] = {0}, tmpPathname[444] = {0}; sscanf(line, ""%llx-%llx %s %ld %s %d %s"", (long long unsigned *) &tmpMap.startAddr, (long long unsigned *) &tmpMap.endAddr, tmpPerms, &tmpMap.offset, tmpDev, &tmpMap.inode, tmpPathname); tmpMap.length = (uintptr_t) tmpMap.endAddr - (uintptr_t) tmpMap.startAddr; tmpMap.perms = tmpPerms; tmpMap.dev = tmpDev; tmpMap.pathname = tmpPathname; _procMaps.push_back(tmpMap); } fclose(fp); } return _procMaps; } std::vector KittyMemory::getMaps(const char *name) { std::vector maps; char line[512] = { 0, }; FILE *fp = fopen(""/proc/self/maps"", ""rt""); if(fp != nullptr) { _procMaps.clear(); while(fgets(line, sizeof(line), fp)) { if(strstr(line, name)) { ProcMap tmpMap; char tmpPerms[5] = {0}, tmpDev[12] = {0}, tmpPathname[444] = {0}; sscanf(line, ""%llx-%llx %s %ld %s %d %s"", (long long unsigned *) &tmpMap.startAddr, (long long unsigned *) &tmpMap.endAddr, tmpPerms, &tmpMap.offset, tmpDev, &tmpMap.inode, tmpPathname); tmpMap.length = (uintptr_t) tmpMap.endAddr - (uintptr_t) tmpMap.startAddr; tmpMap.perms = tmpPerms; tmpMap.dev = tmpDev; tmpMap.pathname = tmpPathname; maps.push_back(tmpMap); } } fclose(fp); } return maps; } ProcMap KittyMemory::getRegionMap(uintptr_t adr) { ProcMap map = { 0, }; for(ProcMap map: KittyMemory::getMaps()) { if(reinterpret_cast(map.startAddr) <= adr && reinterpret_cast(map.endAddr) >= adr) return map; } return map; } ProcMap KittyMemory::getLibraryMap(const char *libraryName) { ProcMap retMap; char line[512] = {0}; FILE *fp = fopen(OBFUSCATE(""/proc/self/maps""), OBFUSCATE(""rt"")); if (fp != nullptr) { while (fgets(line, sizeof(line), fp)) { if (strstr(line, libraryName)) { char tmpPerms[5] = {0}, tmpDev[12] = {0}, tmpPathname[444] = {0}; // parse a line in maps file // (format) startAddress-endAddress perms offset dev inode pathname sscanf(line, ""%llx-%llx %s %ld %s %d %s"", (long long unsigned *) &retMap.startAddr, (long long unsigned *) &retMap.endAddr, tmpPerms, &retMap.offset, tmpDev, &retMap.inode, tmpPathname); retMap.length = (uintptr_t) retMap.endAddr - (uintptr_t) retMap.startAddr; retMap.perms = tmpPerms; retMap.dev = tmpDev; retMap.pathname = tmpPathname; break; } } fclose(fp); } return retMap; } uintptr_t KittyMemory::getAbsoluteAddress(const char *libraryName, uintptr_t relativeAddr, bool useCache) { ProcMap libMap; if(useCache){ libMap = findMapInCache(libraryName); if(libMap.isValid()) return (reinterpret_cast(libMap.startAddr) + relativeAddr); } libMap = getLibraryMap(libraryName); if (!libMap.isValid()) return 0; if(useCache){ mapsCache cachedMap; cachedMap.identifier = libraryName; cachedMap.map = libMap; __mapsCache.push_back(cachedMap); } return (reinterpret_cast(libMap.startAddr) + relativeAddr); } ",targetAddr 196,"#include #include int main() { std::string input; // Manter essa linha sob observação int [MASK] = 0; // Solicita ao usuário para inserir uma string std::cout << ""Digite uma string: ""; std::getline(std::cin, input); // Lê a string completa, incluindo espaços // Percorre a string e conta as ocorrências de 'a' e 'A' for (char c : input) { if (c == 'a' || c == 'A') { [MASK] ++; // Incrementa o contador se encontrar 'a' ou 'A' } } // Verifica se a letra 'a' foi encontrada e exibe o resultado if ( [MASK] > 0) { std::cout << ""A letra 'a' aparece "" << [MASK] << "" vez(es) na string."" << std::endl; } else { std::cout << ""A letra 'a' não foi encontrada na string."" << std::endl; } return 0; } ",count 197,"// Button int buttonPin = 34; // Motor DC int motor1Pin1 = 27; int motor1Pin2 = 26; int enable1Pin = 14; // Setting PWM properties const int freq = 30000; const int pwmChannel = 0; const int resolution = 8; int dutyCycle = 200; void setup() { // sets the pins as outputs: pinMode(motor1Pin1, OUTPUT); pinMode(motor1Pin2, OUTPUT); pinMode(enable1Pin, OUTPUT); //set the Button as input sign pinMode(buttonPin, INPUT_PULLUP); // configure LED PWM functionalitites ledcSetup(pwmChannel, freq, resolution); // attach the channel to the GPIO to be controlled ledcAttachPin(enable1Pin, pwmChannel); Serial.begin(115200); // testing Serial.print(""Testing DC Motor...""); } void loop() { int [MASK] = digitalRead(buttonPin); Serial.println( [MASK] ); if ( [MASK] == 0) {// Move the DC motor forward at maximum speed Serial.println(""Moving Forward""); digitalWrite(motor1Pin1, LOW); digitalWrite(motor1Pin2, HIGH); } else // Stop the DC motor Serial.println(""Motor stopped""); digitalWrite(motor1Pin1, LOW); digitalWrite(motor1Pin2, LOW); delay(5); // Move DC motor backwards at maximum speed //Serial.println(""Moving Backwards""); //digitalWrite(motor1Pin1, HIGH); //digitalWrite(motor1Pin2, LOW); //delay(2000); }",buttonValue 198,"#pragma once #include #include #include #include #include ""magic_enum.hpp"" enum class SymbolType { Program, ExtDefList, ExtDef, ExtDecList, Specifier, StructSpecifier, OptTag, Tag, VarDec, FunDec, VarList, ParamDec, CompSt, StmtList, Stmt, DefList, Def, DecList, Dec, Exp, Args, INT, FLOAT, ID, SEMI, COMMA, ASSIGN, RELOP, PLUS, MINUS, STAR, DIV, AND, OR, DOT, NOT, TYPE, LP, RP, LB, RB, LC, RC, STRUCT, RETURN, IF, ELSE, WHILE }; class Node { public: using Type = SymbolType; std::string label; Type type; std::pair position; // children is stored in reversed order std::vector> children; Node(std::string const &label, Type type) : label(label), type(type) {} Node(std::string const &label, int line_pos, int char_pos, Type type) : label(label), type(type), position(line_pos, char_pos) {} ~Node() = default; std::string to_string() { return to_string("""", true, true); } protected: std::string to_string(std::string prefix, bool last, bool root) { children.erase(std::remove(children.begin(), children.end(), nullptr), children.end()); std::ostringstream [MASK] ; [MASK] << prefix; if (!root) { [MASK] << (last ? ""└──"" : ""├──""); } [MASK] << magic_enum::enum_name(type) << "" ("" << position.first << "") "" << label << std::endl; for (auto i = children.rbegin(); i != children.rend(); ++i) { auto new_prefix = prefix; if (!root) { new_prefix += (last ? "" "" : ""│ ""); } if (i + 1 != children.rend()) { [MASK] << (*i)->to_string(new_prefix, false, false); } else { [MASK] << (*i)->to_string(new_prefix, true, false); } } return [MASK] .str(); } }; inline auto new_node(Node::Type type, std::shared_ptr firschild = nullptr) { return std::make_shared("""", type); } inline auto make_node(Node::Type type) { return new_node(type, nullptr); } template inline auto make_node(Node::Type type, H first) { auto node = new_node(type, first); node->children.emplace_back(first); return node; } template inline auto make_node(Node::Type type, H first, T... children) { auto node = make_node(type, children...); node->children.emplace_back(first); return node; } ",buf 199,"#pragma once #include #include #include #include #include #include namespace sdbusplus { // Forward declare sdbusplus::bus::bus for 'friend'ship. namespace bus { struct bus; }; namespace message { using msgp_t = sd_bus_message*; class message; namespace details { /** @brief unique_ptr functor to release a msg reference. */ struct MsgDeleter { void operator()(msgp_t ptr) const { sd_bus_message_unref(ptr); } }; /* @brief Alias 'msg' to a unique_ptr type for auto-release. */ using msg = std::unique_ptr; } // namespace details /** @class message * @brief Provides C++ bindings to the sd_bus_message_* class functions. */ struct message { /* Define all of the basic class operations: * Not allowed: * - Default constructor to avoid nullptrs. * - Copy operations due to internal unique_ptr. * Allowed: * - Move operations. * - Destructor. */ message() = delete; message(const message&) = delete; message& operator=(const message&) = delete; message(message&&) = default; message& operator=(message&&) = default; ~message() = default; /** @brief Conversion constructor for 'msgp_t'. * * Takes increment ref-count of the msg-pointer and release when * destructed. */ explicit message(msgp_t m) : _msg(sd_bus_message_ref(m)) { } /** @brief Constructor for 'msgp_t'. * * Takes ownership of the msg-pointer and releases it when done. */ message(msgp_t m, std::false_type) : _msg(m) { } /** @brief Release ownership of the stored msg-pointer. */ msgp_t release() { return _msg.release(); } /** @brief Check if message contains a real pointer. (non-nullptr). */ explicit operator bool() const { return bool(_msg); } /** @brief Perform sd_bus_message_append, with automatic type deduction. * * @tparam ...Args - Type of items to append to message. * @param[in] args - Items to append to message. */ template void append(Args&&... args) { sdbusplus::message::append(_msg.get(), std::forward(args)...); } /** @brief Perform sd_bus_message_read, with automatic type deduction. * * @tparam ...Args - Type of items to read from message. * @param[out] args - Items to read from message. */ template void read(Args&&... args) { sdbusplus::message::read(_msg.get(), std::forward(args)...); } /** @brief Get the dbus bus from the message. */ // Forward declare. auto get_bus(); /** @brief Get the signature of a message. * * @return A [weak] pointer to the signature of the message. */ const char* get_signature() { return sd_bus_message_get_signature(_msg.get(), true); } /** @brief Get the path of a message. * * @return A [weak] pointer to the path of the message. */ const char* get_path() { return sd_bus_message_get_path(_msg.get()); } /** @brief Get the interface of a message. * * @return A [weak] pointer to the interface of the message. */ const char* get_interface() { return sd_bus_message_get_interface(_msg.get()); } /** @brief Get the member of a message. * * @return A [weak] pointer to the member of the message. */ const char* get_member() { return sd_bus_message_get_member(_msg.get()); } /** @brief Get the destination of a message. * * @return A [weak] pointer to the destination of the message. */ const char* get_destination() { return sd_bus_message_get_destination(_msg.get()); } /** @brief Get the sender of a message. * * @return A [weak] pointer to the sender of the message. */ const char* get_sender() { return sd_bus_message_get_sender(_msg.get()); } /** @brief Check if message is a method error. * * @return True - if message is a method error. */ bool is_method_error() { return sd_bus_message_is_method_error(_msg.get(), nullptr); } /** @brief Get the transaction cookie of a message. * * @return The transaction cookie of a message. */ auto get_cookie() { uint64_t cookie; sd_bus_message_get_cookie(_msg.get(), &cookie); return cookie; } /** @brief Check if message is a method call for an interface/method. * * @param[in] interface - The interface to match. * @param[in] method - The method to match. * * @return True - if message is a method call for interface/method. */ bool is_method_call(const char* interface, const char* method) { return sd_bus_message_is_method_call(_msg.get(), interface, method); } /** @brief Check if message is a signal for an interface/member. * * @param[in] interface - The interface to match. * @param[in] member - The member to match. */ bool is_signal(const char* interface, const char* member) { return sd_bus_message_is_signal(_msg.get(), interface, member); } /** @brief Create a 'method_return' type message from an existing message. * * @return method-return message. */ message new_method_return() { msgp_t [MASK] = nullptr; sd_bus_message_new_method_return(this->get(), & [MASK] ); return message( [MASK] , std::false_type()); } /** @brief Perform a 'method-return' response call. */ void method_return() { auto b = sd_bus_message_get_bus(this->get()); sd_bus_send(b, this->get(), nullptr); } /** @brief Perform a 'signal-send' call. */ void signal_send() { method_return(); } friend struct sdbusplus::bus::bus; private: /** @brief Get a pointer to the owned 'msgp_t'. */ msgp_t get() { return _msg.get(); } details::msg _msg; }; } // namespace message } // namespace sdbusplus ",reply 200,"#include #include #include ""constants.h"" #include ""application_ui.h"" #include ""SDL2_gfxPrimitives.h"" #include ""wall.h"" #include ""ellipse.h"" std::random_device rd; Ellipse getEllipseRGBA(std::optional coordinates, std::optional color) { Ellipse ellipse; // Définition des dimensions de l'ellipse à partir du rayon ellipse.rad = BALL_RADIUS; // Définition des couleurs de l'ellipse // On vérifie si les paramètres optionnel contienent des valeurs, sinon nous en générons aléatoirement if (color.has_value()) { ellipse.color.r = color->r; ellipse.color.g = color->g; ellipse.color.b = color->b; } else { Ellipse_Color color = getRandomColor(); ellipse.color.r = color.r; ellipse.color.g = color.g; ellipse.color.b = color.b; } // Définition des coordonnées de l'ellipse (avec décalage de l'origine pour éviter les débordements) // On vérifie si les paramètres optionnel contienent des valeurs, sinon nous en générons aléatoirement if (coordinates.has_value()) { ellipse.coordinates.x = coordinates->x; ellipse.coordinates.y = coordinates->y; } else { Ellipse_Coordinates coordinates = getRandomCoordinates(); ellipse.coordinates.x = coordinates.x; ellipse.coordinates.y = coordinates.y; } // Définition du vecteur directeur de l'ellipse Ellipse_Direction direction = getRandomDirectionVector(BALLS_VECT_MAX); ellipse.direction.vx = direction.vx; ellipse.direction.vy = direction.vy; return ellipse; } Ellipse_Color getRandomColor() { // Création d'un générateur de nombres aléatoires std::mt19937 gen(rd()); // Création d'une distribution uniforme entre les limites std::uniform_int_distribution<> dis(0, 255); // Génération d'une couleur aléatoire Uint8 r = dis(gen), g = dis(gen), b = dis(gen); return {r, g, b}; } // TODO: On voudrais que la balle ne puisse pas apparaitre dans un mur, pour l'instant c'est pas le cas Ellipse_Coordinates getRandomCoordinates() { // Création d'un générateur de nombres aléatoires std::mt19937 gen(rd()); // Création d'une distribution uniforme entre les limites // Les coordonnées dépendent du rayon des ellipses afin de toujours les faires apparaitre entièrement dans la fenêtre, tant que le diamètre des ellipses ne dépasse pas la taille de la fenêtre, nous sommes assurés qu'elles seront comprises dedans. On ajoute 1 pour la marge de la première frame. std::uniform_int_distribution<> dis1(0 + (BALL_RADIUS + 1), SCREEN_WIDTH - (BALL_RADIUS + 1)); std::uniform_int_distribution<> dis2(0 + (BALL_RADIUS + 1), SCREEN_HEIGHT - (BALL_RADIUS + 1)); // // Génération de coordonnées aléatoire int x = dis1(gen), y = dis2(gen); return {x, y}; } Ellipse_Direction getRandomDirectionVector(int maxVect) { // Création d'un générateur de nombres aléatoires std::mt19937 gen(rd()); // Création d'une distribution uniforme entre les limites std::uniform_int_distribution<> dis((maxVect * -1), maxVect); int vx, vy = 0; do { vx = dis(gen); vy = dis(gen); // On exclu la valeur 0, sinon l'ellipse ne bougera pas (vecteur nul) } while (vx == 0 || vy == 0); return {vx, vy}; } void drawEllipses(SDL_Renderer *renderer, std::vector *ellipses) { // Boucler dans le toute les ellipses for (size_t i = 0; i < ellipses->size(); i++) { Ellipse ellipse = (*ellipses)[i]; // Dessiner l'ellipse filledEllipseRGBA(renderer, ellipse.coordinates.x, ellipse.coordinates.y, ellipse.rad, ellipse.rad, ellipse.color.r, ellipse.color.g, ellipse.color.b, 255); } } bool checkCollision(Ellipse &ball, Shape &shape) { int ellipseX = ball.coordinates.x; int ellipseY = ball.coordinates.y; int ellipseR = ball.rad; int shapeX1 = shape.wallTop.x1; int [MASK] = shape.wallTop.y1; int shapeX2 = shape.wallBottom.x2; int shapeY2 = shape.wallBottom.y2; // Check collision with top wall if (ellipseY - ellipseR <= [MASK] && ellipseY + ellipseR >= [MASK] && (ellipseX + ellipseR >= shapeX1 && ellipseX - ellipseR <= shapeX2)) { ball.direction.vy = -ball.direction.vy; return true; } // Check collision with bottom wall else if (ellipseY + ellipseR >= shapeY2 && ellipseY - ellipseR <= shapeY2 && (ellipseX + ellipseR >= shapeX1 && ellipseX - ellipseR <= shapeX2)) { ball.direction.vy = -ball.direction.vy; return true; } // Check collision with left wall else if (ellipseX - ellipseR <= shapeX1 && ellipseX + ellipseR >= shapeX1 && (ellipseY + ellipseR >= [MASK] && ellipseY - ellipseR <= shapeY2)) { ball.direction.vx = -ball.direction.vx; return true; } // Check collision with right wall else if (ellipseX + ellipseR >= shapeX2 && ellipseX - ellipseR <= shapeX2 && (ellipseY + ellipseR >= [MASK] && ellipseY - ellipseR <= shapeY2)) { ball.direction.vx = -ball.direction.vx; return true; } return false; } void moveEllipes(std::vector *ellipses, Shape *shape) { Shape windowWalls = getWindowWalls(); for (size_t i = 0; i < ellipses->size(); i++) { Ellipse ellipse = (*ellipses)[i]; // Génère un nombre aléatoire entre 1 et 4 pour pouvoir le multiplier au BALLS_SPEED // TODO: FIX THIS (bug, ball trop rapide, voir comment on peut différencier direction et vitesse) // attention, ne pas laissé ici, la génération et nombre aléatoire et le changement de vitesse ne doit se faire qu'a la collision avec un mur, par a chaque avancé de la balle // int randomSpeed = (1 + (rand() % 4)) * BALLS_SPEED; int randomSpeed = 1; // Changement des postions de l'ellipse (*ellipses)[i].coordinates.x += randomSpeed * ellipse.direction.vx; (*ellipses)[i].coordinates.y += randomSpeed * ellipse.direction.vy; if (!checkCollision((*ellipses)[i], *shape)) checkCollision((*ellipses)[i], windowWalls); } } void handleOnClick(std::vector *ellipses, int mouseX, int mouseY) { const Ellipse_Coordinates mouseCoordinates = {mouseX, mouseY}; bool foundIt = false; size_t i = 0; while (!foundIt && i < ellipses->size()) { Ellipse ellipse = (*ellipses)[i]; int x_diff = mouseCoordinates.x - ellipse.coordinates.x; int y_diff = mouseCoordinates.y - ellipse.coordinates.y; int distance = sqrt(x_diff * x_diff + y_diff * y_diff); if (distance <= ellipse.rad) foundIt = true; else i++; } if (foundIt) { // Suppression d'une ellipse (*ellipses).erase((*ellipses).begin() + i); } else { // Créaton d'une nouvelle ellipse Ellipse ellipse = getEllipseRGBA(mouseCoordinates); (*ellipses).push_back(ellipse); } }",shapeY1 201,"#pragma once #include ""Core.h"" namespace NV { // Event types enum class EventType { None = 0, WindowClose, WindowResize, WindowFocus, WindowLostFocus, WindowMoved, AppTick, AppUpdate, AppRender, KeyPressed, KeyReleased, KeyTyped, MouseButtonPressed, MouseButtonReleased, MouseMoved, MouseScrolled }; // Event categories enum class EventCategory { None = 0, Application= BIT(0), Input = BIT(1), Keyboard = BIT(2), Mouse = BIT(3), MouseButton = BIT(4) }; // 重载位运算符 | inline constexpr int operator|(EventCategory lhs, EventCategory [MASK] ) { return static_cast(lhs) | static_cast( [MASK] ); } // Event base class #define EVENT_CLASS_TYPE(type) static EventType GetStaticType() { return EventType::type; }\ virtual EventType GetEventType() const override { return GetStaticType(); }\ virtual const char* GetName() const override { return #type; } #define EVENT_CLASS_CATEGORY(category) virtual int GetCategoryFlags() const override { return (int)category; } // Event base class class Event { public: virtual ~Event() = default; virtual const char* GetName() const = 0; virtual EventType GetEventType() const = 0; virtual int GetCategoryFlags() const = 0; virtual std::string ToString() const { return GetName(); }; inline bool IsInCategory(EventCategory category) { return GetCategoryFlags() & (int)category; } bool m_Handled = false; }; // Event dispatcher class EventDispatcher { public: EventDispatcher(Event& event) : m_Event(event) {} template using EventFn = std::function; template bool Dispatch(EventFn func) { if (m_Event.GetEventType() == T::GetStaticType()) { m_Event.m_Handled = func(*(T*)&m_Event); return true; } return false; } private: Event& m_Event; }; inline std::ostream& operator<<(std::ostream& os, const Event& e) { return os << e.ToString(); } }",rhs 202,"/* * Copyright (c) 2022 <> * * SPDX-License-Identifier: Apache-2.0 */ #include #include #include namespace arduino { namespace zephyr { int cbprintf_callback(int c, void *ctx) { return reinterpret_cast(ctx)->write((unsigned char)c); } size_t wrap_cbprintf(void *ctx, const char *format, ...) { va_list ap; int rc; va_start(ap, format); rc = cbvprintf(reinterpret_cast(cbprintf_callback), ctx, format, ap); va_end(ap); return static_cast(rc > 0 ? rc : 0); } size_t print_number_base_any(void *ctx, unsigned long long ull, int base) { arduino::Print &print = *reinterpret_cast(ctx); char string[sizeof(unsigned long long) * 8] = {0}; size_t digit = 0; unsigned value; if (base < 2 || base > ('~' - 'A' + 10)) { base = 10; } while (ull != 0) { value = ull % base; if (value < 10) { string[sizeof(string) - digit] = '0' + value; } else { string[sizeof(string) - digit] = 'A' + (value- 10); } digit++; ull /= base; } return print.write(string + (sizeof(string) - digit), digit + 1); } size_t print_number_base_pow2(void *ctx, unsigned long long ull, unsigned [MASK] ) { arduino::Print &print = *reinterpret_cast(ctx); const unsigned long long mask = (1 << [MASK] ) - 1; int digit = (((sizeof(unsigned long long) * 8) + [MASK] ) / [MASK] ); int output_count = -1; unsigned value; while (digit >= 0) { value = (ull & (mask << (digit * [MASK] ))) >> (digit * [MASK] ); if (value != 0 && output_count < 0) { output_count = 0; } if (output_count >= 0) { if (value < 10) { print.write('0' + value); } else { print.write('A' + (value- 10)); } output_count++; } digit--; } return output_count; } } // namespace zephyr } // namespace arduino /* * This is the default implementation. * It will be overridden by subclassese. */ size_t arduino::Print::write(const uint8_t *buffer, size_t size) { size_t i; for (i=0; i void exportProfile(Exporter &exporter,Exporter::FileNode base_node,const ProfileType &profile) { typedef Exporter::FileNode FileNode; FileNode profile_node = exporter.createFileNode(base_node,""profile""); FileNode profile_type_node = exporter.createFileNode(profile_node,""profile-type""); exporter.dump(profile_type_node,std::string(""CSR"")); exporter.closeFileNode(profile_type_node); FileNode profile_nlin_node = exporter.createFileNode(profile_node,""nlin""); int nlin = profile.getNRows(); exporter.dump(profile_nlin_node, nlin); exporter.closeFileNode(profile_nlin_node); FileNode profile_ncol_node = exporter.createFileNode(profile_node,""ncol""); exporter.dump(profile_ncol_node,profile.getNCols()); exporter.closeFileNode(profile_ncol_node); FileNode profile_nelem_node = exporter.createFileNode(profile_node,""nelem""); int nelem = profile.getNElems(); exporter.dump(profile_nelem_node,nelem); exporter.closeFileNode(profile_nelem_node); FileNode profile_line_list_node = exporter.createFileNode(profile_node,""line-list""); exporter.dump(profile_line_list_node,profile.getKCol(),nlin+1); exporter.closeFileNode(profile_line_list_node); FileNode profile_col_idx_node = exporter.createFileNode(profile_node,""col-idx""); exporter.dump(profile_col_idx_node,profile.getCols(),nelem); exporter.closeFileNode(profile_col_idx_node); exporter.closeFileNode(profile_node); } template void exportMatrix(Exporter &exporter,Exporter::FileNode base_node,const MatrixType &matrix,const std::string &node_name) { typedef Exporter::FileNode FileNode; FileNode matrix_node = exporter.createFileNode(base_node,node_name); FileNode element_blocksize_node = exporter.createFileNode(matrix_node,""element-blocksize""); int element_blocksize[2]; element_blocksize[0] = matrix.getBlockSize(); element_blocksize[1] = matrix.getBlockSize2(); exporter.dump(element_blocksize_node,element_blocksize,2); exporter.closeFileNode(element_blocksize_node); FileNode values_node = exporter.createFileNode(matrix_node,""values""); exporter.dump(values_node,matrix.getAddressScalarData(), matrix.getProfile().getNElems()*matrix.getBlockSize()*matrix.getBlockSize2()); FileNode [MASK] = exporter.createFileNode(values_node,""values-ordering""); exporter.dump( [MASK] ,std::string(""line-order"")); exporter.closeFileNode( [MASK] ); exporter.closeFileNode(values_node); exportProfile(exporter,matrix_node,matrix.getProfile()); exporter.closeFileNode(matrix_node); } template void importProfile(Importer &importer,Importer::FileNode base_node,ProfileType &profile) { typedef Importer::FileNode FileNode; FileNode profile_node = importer.openFileNode(base_node,""profile""); FileNode profile_type_node = importer.openFileNode(profile_node,""profile-type""); std::string profile_type; importer.read(profile_type_node,profile_type); if(profile_type != ""CSR""){ throw BaseException::RunTimeError(""CSR profile expected, found :""+profile_type); } importer.closeFileNode(profile_type_node); FileNode profile_nlin_node = importer.openFileNode(profile_node,""nlin""); int nlin = 0; importer.read(profile_nlin_node,nlin); importer.closeFileNode(profile_nlin_node); FileNode profile_ncol_node = importer.openFileNode(profile_node,""ncol""); int ncol = 0; importer.read(profile_ncol_node,ncol); importer.closeFileNode(profile_ncol_node); FileNode profile_nelem_node = importer.openFileNode(profile_node,""nelem""); int nelem = 0; importer.read(profile_nelem_node,nelem); importer.closeFileNode(profile_nelem_node); profile.init(nlin,ncol,nelem); FileNode profile_line_list_node = importer.openFileNode(profile_node,""line-list""); importer.read(profile_line_list_node,profile.getKCol(),nlin+1); importer.closeFileNode(profile_line_list_node); FileNode profile_col_idx_node = importer.openFileNode(profile_node,""col-idx""); importer.read(profile_col_idx_node,profile.getCols(),nelem); importer.closeFileNode(profile_col_idx_node); importer.closeFileNode(profile_node); profile.prepare(); } template void importMatrix(Importer &importer,Importer::FileNode base_node,MatrixType &matrix,const std::string &node_name=std::string(""matrix"")) { typedef typename MatrixType::ProfileType ProfileType; typedef Importer::FileNode FileNode; ProfileType *profile = new ProfileType(); FileNode matrix_node = importer.openFileNode(base_node,node_name); importProfile(importer,matrix_node,*profile); matrix.setProfile(profile,true); // get profile ownership matrix.allocate(); FileNode element_blocksize_node = importer.openFileNode(matrix_node,""element-blocksize""); int element_blocksize[2] = {0,0}; importer.read(element_blocksize_node,element_blocksize,2); importer.closeFileNode(element_blocksize_node); if(element_blocksize[0] != MatrixType::m_block_size || element_blocksize[1] != MatrixType::m_block_size2){ throw BaseException::RunTimeError(""Matrix element block size does not correspond to file element block size""); } FileNode values_node = importer.openFileNode(matrix_node,""values""); // TODO check for line/column data ordering importer.read(values_node,matrix.getAddressScalarData(), profile->getNElems()*MatrixType::m_block_size*MatrixType::m_block_size2); importer.closeFileNode(values_node); } } #endif /* SRC_MCGS_MATRIXVECTOR_IO_CSRMATRIXIO_H_ */ ",values_ordering_node 204,"// // Created by // // #include ""audioPlayer.h"" #include ""logger.h"" #include #include #include #include #include #include #include #define LOG_TAG ""[audioPlayer.c]"" #define SLASSERT(x) \ do { \ assert(SL_RESULT_SUCCESS == (x)); \ (void)(x); \ } while (0) #define BUFFER_QUEUE_LEN 4 typedef struct SampleFormat { uint32_t sampleRate; uint32_t framesPerBuf; uint16_t numChannels; uint16_t pcmFormat; // 8 bit, 16 bit, 24 bit ... uint32_t representation; // android extensions } SampleFormat; // SL buffer queue player interfaces typedef struct SLBufferQueuePlayer { SLObjectItf outputMixObjectItf; SLObjectItf playerObjectItf; SLPlayItf playItf; SLAndroidSimpleBufferQueueItf playBufferQueueItf; SampleFormat sampleInfo; uint32_t bufferSize; short *buffer; } SLPlayer; typedef struct SLEngine { SLmilliHertz fastPathSampleRate; uint32_t fastPathFramesPerBuf; uint16_t sampleChannels; uint16_t bitsPerSample; SLObjectItf slEngineObj; SLEngineItf slEngineItf; } SLEngine; SLEngine engine; SLPlayer player; SampleFormat sampleFormat; FILE *file = NULL; bool isEOF = false; static void bufferQueuePlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context) { assert(bq == player.playBufferQueueItf); assert(NULL == context); int bytes = fread(player.buffer, 1, player.bufferSize*sizeof(short), file); // int bytes = processGnFiveBandEq(player.buffer, engine.fastPathFramesPerBuf); SLresult result = (*bq)->Enqueue(bq, player.buffer, bytes); // LOG_DEBUG("" === === === Enqueue === === === %d"", bytes); // ToDo: need to handle EOF // Currently we listen to ""SL_RESULT_PARAMETER_INVALID"" to handle EOF if(SL_RESULT_PARAMETER_INVALID == result) { isEOF = true; } else { SLASSERT(result); } } static void ConvertToSLSampleFormat(SLAndroidDataFormat_PCM_EX* pFormat, SampleFormat* pSampleInfo_) { assert(pFormat); memset(pFormat, 0, sizeof(*pFormat)); pFormat->formatType = SL_DATAFORMAT_PCM; // Only support 2 channels // For channelMask, refer to wilhelm/src/android/channels.c for details if (pSampleInfo_->numChannels <= 1) { pFormat->numChannels = 1; pFormat->channelMask = SL_SPEAKER_FRONT_LEFT; } else { pFormat->numChannels = 2; pFormat->channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; } pFormat->sampleRate = pSampleInfo_->sampleRate; pFormat->endianness = SL_BYTEORDER_LITTLEENDIAN; pFormat->bitsPerSample = pSampleInfo_->pcmFormat; pFormat->containerSize = pSampleInfo_->pcmFormat; // fixup for android extended representations... pFormat->representation = pSampleInfo_->representation; switch (pFormat->representation) { case SL_ANDROID_PCM_REPRESENTATION_UNSIGNED_INT: pFormat->bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_8; pFormat->containerSize = SL_PCMSAMPLEFORMAT_FIXED_8; pFormat->formatType = SL_ANDROID_DATAFORMAT_PCM_EX; break; case SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT: pFormat->bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; // supports 16, 24, and 32 pFormat->containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; pFormat->formatType = SL_ANDROID_DATAFORMAT_PCM_EX; break; case SL_ANDROID_PCM_REPRESENTATION_FLOAT: pFormat->bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_32; pFormat->containerSize = SL_PCMSAMPLEFORMAT_FIXED_32; pFormat->formatType = SL_ANDROID_DATAFORMAT_PCM_EX; break; case 0: break; default: assert(0); } } static void createSLEngine(int sampleRate, int framesPerBuf, int numChannels) { LOG_DEBUG("" == createSLEngine == ""); LOG_DEBUG("" SampleRate: %d, SampleBufferSize: %d, numChannels: %d"", sampleRate, framesPerBuf, numChannels); SLresult result; memset(&engine, 0, sizeof(engine)); engine.fastPathSampleRate = (SLmilliHertz)(sampleRate) * 1000; engine.fastPathFramesPerBuf = (uint32_t)(framesPerBuf); engine.sampleChannels = (uint16_t)numChannels; engine.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; memset(&sampleFormat, 0, sizeof(sampleFormat)); sampleFormat.pcmFormat = (uint16_t)engine.bitsPerSample; sampleFormat.framesPerBuf = engine.fastPathFramesPerBuf; sampleFormat.representation = SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT; sampleFormat.numChannels = (uint16_t)engine.sampleChannels; sampleFormat.sampleRate = engine.fastPathSampleRate; // create SL engine result = slCreateEngine(&engine.slEngineObj, 0, NULL, 0, NULL, NULL); SLASSERT(result); result = (*engine.slEngineObj)->Realize(engine.slEngineObj, SL_BOOLEAN_FALSE); SLASSERT(result); result = (*engine.slEngineObj)->GetInterface(engine.slEngineObj, SL_IID_ENGINE, &engine.slEngineItf); SLASSERT(result); } static void deleteSLEngine() { LOG_DEBUG("" == deleteSLEngine ==""); if (engine.slEngineObj != NULL) { (*engine.slEngineObj)->Destroy(engine.slEngineObj); engine.slEngineObj = NULL; engine.slEngineItf = NULL; } } static void createSLPlayer(SampleFormat *sampleFormat, SLEngineItf slEngine) { LOG_DEBUG("" == createSLBufferQueueAudioPlayer ==""); SLresult result; assert(sampleFormat); player.sampleInfo = *sampleFormat; // create and realize the output mix result = (*slEngine)->CreateOutputMix(slEngine, &player.outputMixObjectItf, 0, NULL, NULL); SLASSERT(result); result = (*player.outputMixObjectItf)->Realize(player.outputMixObjectItf, SL_BOOLEAN_FALSE); SLASSERT(result); // configure audio source SLDataLocator_AndroidSimpleBufferQueue loc_bufq = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, BUFFER_QUEUE_LEN}; SLAndroidDataFormat_PCM_EX [MASK] ; ConvertToSLSampleFormat(& [MASK] , &player.sampleInfo); SLDataSource audioSrc = {&loc_bufq, & [MASK] }; // configure audio sink SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, player.outputMixObjectItf}; SLDataSink audioSnk = {&loc_outmix, NULL}; // create fast path audio player: SL_IID_BUFFERQUEUE and SL_IID_VOLUME // and other non-signal processing interfaces are ok. SLInterfaceID ids[2] = {SL_IID_BUFFERQUEUE, SL_IID_VOLUME}; SLboolean req[2] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; result = (*slEngine)->CreateAudioPlayer(slEngine, &player.playerObjectItf, &audioSrc, &audioSnk, sizeof(ids) / sizeof(ids[0]), ids, req); SLASSERT(result); // realize the player result = (*player.playerObjectItf)->Realize(player.playerObjectItf, SL_BOOLEAN_FALSE); SLASSERT(result); // get the play interface result = (*player.playerObjectItf)->GetInterface(player.playerObjectItf, SL_IID_PLAY, &player.playItf); SLASSERT(result); // get the buffer queue interface result = (*player.playerObjectItf)->GetInterface(player.playerObjectItf, SL_IID_BUFFERQUEUE, &player.playBufferQueueItf); SLASSERT(result); // register callback on the buffer queue result = (*player.playBufferQueueItf)->RegisterCallback(player.playBufferQueueItf, bufferQueuePlayerCallback, NULL); SLASSERT(result); } static void deleteSLPlayer() { LOG_DEBUG("" == deleteSLPlayer ==""); // destroy buffer queue audio player object, and invalidate all associated // interfaces if (player.playerObjectItf != NULL) { (*player.playerObjectItf)->Destroy(player.playerObjectItf); player.playerObjectItf = NULL; player.playItf = NULL; player.playBufferQueueItf = NULL; } // free buffer free(player.buffer); player.buffer = NULL; // destroy output mix object, and invalidate all associated interfaces if (player.outputMixObjectItf) { (*player.outputMixObjectItf)->Destroy(player.outputMixObjectItf); player.outputMixObjectItf = NULL; } } static void shutdownAudioPlayer() { LOG_DEBUG("" == shutdownAudioPlayer ==""); // make sure the audio player was created if (NULL != player.playItf) { SLresult result = (*player.playItf)->SetPlayState(player.playItf, SL_PLAYSTATE_STOPPED); SLASSERT(result); } deleteSLPlayer(); deleteSLEngine(); } void playAudioPlayer(const char* audioFilePath, int sampleRate, int bufSize) { LOG_DEBUG("" == playAudioPlayer ==""); file = fopen(audioFilePath, ""r""); // ToDo: Hardcoded number of channel for now // createSLEngine(48000, 1024, 2); // (sampleRate, framesPerBuffer, numChannels) createSLEngine(sampleRate, bufSize, 2); // (sampleRate, framesPerBuffer, numChannels) createSLPlayer(&sampleFormat, engine.slEngineItf); SLresult result = (*player.playItf)->SetPlayState(player.playItf, SL_PLAYSTATE_PLAYING); SLASSERT(result); // buffer size (2 channels) player.bufferSize = sampleFormat.framesPerBuf * 2; player.buffer = (short *)calloc(player.bufferSize, sizeof(short)); (*player.playBufferQueueItf)->Enqueue(player.playBufferQueueItf, player.buffer, player.bufferSize*sizeof(short)); // ToDo: need an event loop and handle EOF // usleep(10000000); isEOF = false; while(1) { if(isEOF) { break; } } shutdownAudioPlayer(); } void stopAudioPlayer() { LOG_DEBUG("" == stopAudioPlayer ==""); isEOF = true; } ",format_pcm 205," #define _CRT_SECURE_NO_WARNINGS #include ""DataBase.h"" #include ""Student.h"" #include #include // uzupelnij !!! using namespace std; DataBase::DataBase(const char* file) { strcpy(dataFileName, file); } void DataBase::ListData(bool akt) { // uzupelnij !!! ifstream wej(""data.bin"", ios::in | ios::binary); //Otwarcie if (!wej) { cout << ""Nie mozna otworzyc pliku !!!"" << endl; return; } wej.seekg(0, ios::end); //Ile obiektów long ile = wej.tellg() / sizeof(Student); wej.seekg(0, ios::beg); Student* studenciaki = new Student[ile]; Student st; int i = 0; while (wej.read((char*)&st, sizeof(Student))) //pobranie danych (można by całość na bieżąco wypisywać) { studenciaki[i] = st; i++; } for (int i = 0; i < ile; i++) //wypisywanie warunkowe { if (akt == studenciaki[i].Active) cout << studenciaki[i]; } //if (wej.eof()) //Usunięcie EOF?? // wej.clear(); //else //{ // cout << ""Niepoprawny odczyt pliku: "" << dataFileName << endl; // return; //} delete[] studenciaki; wej.close(); return; } void DataBase::Append() { // uzupelnij !!! Student st; cout << ""Podaj imie: "" << endl; cin >> st.FirstName; cout << ""Podaj nazwisko: "" << endl; cin >> st.LastName; cout << ""Podaj NrInd: "" << endl; cin >> st.IdNumber; cout << ""Podaj grupe: "" << endl; cin >> st.Group; cout << ""Podaj srednia: "" << endl; cin >> st.Average; st.Active = 1; ofstream [MASK] (""data.bin"", ios::in | ios::binary); //Otwarcie if (! [MASK] ) { cout << ""Nie mozna otworzyc pliku !!!"" << endl; return; } [MASK] .seekp(0, ios::end); //Append if ( [MASK] .write((char*)&st, sizeof(Student))) cout << ""Dane poprawione !"" << endl; else cout << ""Niepowodzenie"" << endl; [MASK] .close(); return; } void DataBase::Modify() { // uzupelnij !!! fstream plik(dataFileName, ios::in | ios::out | ios::binary); //Otwarcie if (!plik) { cout << ""Nie mozna otworzyc pliku !!!"" << endl; return; } plik.seekg(0, ios::end); //Ile obiektów long ile = plik.tellg() / sizeof(Student); plik.seekg(0, ios::beg); Student* studenciaki = new Student[ile]; Student st; int i = 0; while (plik.read((char*)&st, sizeof(Student))) //pobranie danych (można by całość na bieżąco wypisywać) { studenciaki[i] = st; i++; } plik.clear(); cout << ""Podaj NrInd: "" << endl; cin >> st.IdNumber; for (int i = 0; i < ile; i++) { if (st.IdNumber == studenciaki[i].IdNumber) { plik.seekg(sizeof(Student)*(i), ios::beg); // w to samo miejsce plik.read((char*)&st, sizeof(Student)); cout << st; cout << ""Podaj grupe: "" << endl; cin >> st.Group; cout << ""Podaj srednia: "" << endl; cin >> st.Average; cout << ""Czy aktywny? (0/1)""; cin >> st.Active; plik.seekp(sizeof(Student)*(i), ios::beg); if (plik.write((char*)&st, sizeof(Student))) cout << ""Dane poprawione!"" << endl; else cout << ""???""; return; } } cout << ""Nie ma takiego studenta""; plik.close(); return; } void DataBase::Pack() { // uzupelnij !!! } void DataBase::WriteTextData() { // uzupelnij !!! } void DataBase::ReadTextData() { // uzupelnij !!! } ",wyj 206,"#include ""WindowsWindow.h"" #include ""Jogo/Log.h"" namespace Jogo { static bool s_GLFWInitialized = false; Window* Window::Create(const WindowProps& props) { return new WindowsWindow(props); } WindowsWindow::WindowsWindow(const WindowProps& props) { Init(props); } WindowsWindow::~WindowsWindow() { Shutdown(); } void WindowsWindow::Init(const WindowProps& props) { m_Data.Title = props.Title; m_Data.Width = props.Width; m_Data.Height = props.Height; JG_CORE_INFO(""Creating window {0} ({1}, {2})"", props.Title, props.Width, props.Height); if (!s_GLFWInitialized) { int success = glfwInit(); assert(success, ""Couldn't initialize GLFW!""); s_GLFWInitialized = true; } m_Window = glfwCreateWindow((int)m_Data.Width, (int)m_Data.Height, m_Data.Title.c_str(), nullptr, nullptr); glfwMakeContextCurrent(m_Window); glfwSetWindowUserPointer(m_Window, &m_Data); SetVSync(true); } void WindowsWindow::Shutdown() { glfwDestroyWindow(m_Window); } void WindowsWindow::OnUpdate() { glfwPollEvents(); glfwSwapBuffers(m_Window); } void WindowsWindow::SetVSync(bool [MASK] ) { if ( [MASK] ) glfwSwapInterval(1); else glfwSwapInterval(0); m_Data.VSync = [MASK] ; } bool WindowsWindow::IsVSync() const { return m_Data.VSync; } }",enabled 207,"#include #include #include #include #include #include #define SCREEN_HEIGHT 260 #define SCREEN_WIDTH 200 #define MAX_X_SCALE_INDEX 6 #define MAX_Y_SCALE_INDEX 12 #define MAX_OFFSET 130 #define MIN_OFFSET -130 #define MAX_LEVEL 270 #define MIN_LEVEL 25 #define MAX_CURSOR_1X 435 #define MIN_CURSOR_1X 20 #define MAX_CURSOR_1Y 250 #define MIN_CURSOR_1Y 25 extern int16_t encoderValue; extern uint8_t trigger_level; // 0-255 extern uint8_t offset; // 0-255 extern trigger_mode_typedef trigger_mode; extern int32_t time_scale; // capture 1 data from every n points extern uint8_t read_encoder; extern int8_t set_relay; extern float input_v_pp; extern float input_frequency; extern float input_period; extern float x_unit; extern float y_unit; // map [0, 255] to [-5, 5] (float) for display purpose float UnMap(uint8_t [MASK] ) { return ((float) [MASK] / 25.5) - 5; } Screen1View::Screen1View() { singleToggle[0] = &XScaleToggle; singleToggle[1] = &YScaleToggle; singleToggle[2] = &offsetToggle; singleToggle[3] = &levelToggle; singleToggle[4] = &cursor1XToggle; singleToggle[5] = &cursor1YToggle; singleToggle[6] = &cursor2XToggle; singleToggle[7] = &cursor2YToggle; menuList[0] = &mainMenu; menuList[1] = &displayMenu; menuList[2] = &measureMenu; menuList[3] = &triggerMenu; menuList[4] = &cursorMenu; } void Screen1View::setupScreen() { Screen1ViewBase::setupScreen(); } void Screen1View::tearDownScreen() { Screen1ViewBase::tearDownScreen(); } void Screen1View::onBackButtonClicked() { // hide every menu container for (int i = 1; i < 5; i ++) { menuList[i]->setVisible(false); menuList[i]->invalidate(); } // hide back button itself backButton.setVisible(false); backButton.invalidate(); // show main menu back on mainMenu.setVisible(true); mainMenu.invalidate(); } void Screen1View::onDisplayMenuClicked() { // hide main menu first mainMenu.setVisible(false); // show display menu and back button displayMenu.setVisible(true); backButton.setVisible(true); mainMenu.invalidate(); displayMenu.invalidate(); backButton.invalidate(); } void Screen1View::onMeasureMenuClicked() { mainMenu.setVisible(false); measureMenu.setVisible(true); backButton.setVisible(true); mainMenu.invalidate(); measureMenu.invalidate(); backButton.invalidate(); } void Screen1View::onTriggerMenuClicked() { mainMenu.setVisible(false); triggerMenu.setVisible(true); backButton.setVisible(true); mainMenu.invalidate(); triggerMenu.invalidate(); backButton.invalidate(); } void Screen1View::onCursorMenuClicked() { mainMenu.setVisible(false); cursorMenu.setVisible(true); backButton.setVisible(true); mainMenu.invalidate(); cursorMenu.invalidate(); backButton.invalidate(); } // TODO: naive implementation for toggling measure // should rearrange text position void Screen1View::onMeasureToggled( const touchgfx::ToggleButton* targetButton, touchgfx::TextArea* targetText) { targetText->setVisible(!(targetButton->getState())); targetText->invalidate(); } void Screen1View::onVppToggled() { Screen1View::onMeasureToggled(&VppToggle, &VppText); } void Screen1View::onFreqToggled() { Screen1View::onMeasureToggled(&freqToggle, &freqText); } void Screen1View::onPeriodToggled() { Screen1View::onMeasureToggled(&periodToggle, &periodText); } void Screen1View::onSingleToggle(const touchgfx::ToggleButton* targetToggle) { encoderZero = encoderValue; for (int i = 0; i < 8; i ++) { if (singleToggle[i] != targetToggle) { singleToggle[i]->forceState(false); singleToggle[i]->invalidate(); } } horizontalLine0.setVisible(false); horizontalLine0.invalidate(); horizontalLine1.setVisible(false); horizontalLine1.invalidate(); verticalLine1.setVisible(false); verticalLine1.invalidate(); horizontalLine2.setVisible(false); horizontalLine2.invalidate(); verticalLine2.setVisible(false); verticalLine2.invalidate(); lastXScaleIndex = curXScale; lastYScaleIndex = curYScale; lastOffset = curOffset; lastLevel = triggerLevel; lastCursor1X = curCursor1X; lastCursor1Y = curCursor1Y; lastCursor2X = curCursor2X; lastCursor2Y = curCursor2Y; } void Screen1View::onXScaleToggled() { encoderTarget = (XScaleToggle.getState()) ? 1 : 0; if(XScaleToggle.getState() == false) { lastXScaleIndex = curXScale; } else { curXScale = lastXScaleIndex; } onSingleToggle(&XScaleToggle); } void Screen1View::onYScaleToggled() { encoderTarget = (YScaleToggle.getState()) ? 2 : 0; if(YScaleToggle.getState() == false) { lastYScaleIndex = curYScale; } else { curYScale = lastYScaleIndex; } onSingleToggle(&YScaleToggle); } void Screen1View::onOffsetToggled() { encoderTarget = (offsetToggle.getState()) ? 3 : 0; if(offsetToggle.getState() == false) { lastOffset = curOffset; } else { curOffset = lastOffset; } onSingleToggle(&offsetToggle); } void Screen1View::onLevelToggled() { encoderTarget = (levelToggle.getState()) ? 4 : 0; onSingleToggle(&levelToggle); if (levelToggle.getState()) { triggerLevel = lastLevel; horizontalLine0.setVisible(true); horizontalLine0.invalidate(); } else { lastLevel = triggerLevel; } } void Screen1View::onCursor1XToggled() { encoderTarget = (cursor1XToggle.getState()) ? 5 : 0; onSingleToggle(&cursor1XToggle); if(cursor1XToggle.getState() == false) { lastCursor1X = curCursor1X; } else { curCursor1X = lastCursor1X; horizontalLine1.setVisible(true); horizontalLine1.invalidate(); verticalLine1.setVisible(true); verticalLine1.invalidate(); } } void Screen1View::onCursor2XToggled() { encoderTarget = (cursor2XToggle.getState()) ? 7 : 0; onSingleToggle(&cursor2XToggle); if (cursor2XToggle.getState() == false) { lastCursor2X = curCursor2X; } else { curCursor2X = lastCursor2X; horizontalLine2.setVisible(true); horizontalLine2.invalidate(); verticalLine2.setVisible(true); verticalLine2.invalidate(); } } void Screen1View::onCursor1YToggled() { encoderTarget = (cursor1YToggle.getState()) ? 6 : 0; onSingleToggle(&cursor1YToggle); if(cursor1YToggle.getState() == false) { lastCursor1Y = curCursor1Y; } else { curCursor1Y = lastCursor1Y; horizontalLine1.setVisible(true); horizontalLine1.invalidate(); verticalLine1.setVisible(true); verticalLine1.invalidate(); } } void Screen1View::onCursor2YToggled() { encoderTarget = (cursor2YToggle.getState()) ? 8 : 0; onSingleToggle(&cursor2YToggle); if (cursor2YToggle.getState() == false) { lastCursor2Y = curCursor2Y; } else { curCursor2Y = lastCursor2Y; horizontalLine2.setVisible(true); horizontalLine2.invalidate(); verticalLine2.setVisible(true); verticalLine2.invalidate(); } } void Screen1View::tick() { switch(encoderTarget) { case 0: break; case 1: // XScale read_encoder = 1; curXScale = lastXScaleIndex + encoderValue - encoderZero; if(curXScale > MAX_X_SCALE_INDEX) { curXScale = MAX_X_SCALE_INDEX; encoderZero = lastXScaleIndex + encoderValue - curXScale; } if(curXScale < 0) { curXScale = 0; encoderZero = lastXScaleIndex + encoderValue - curXScale; } time_scale = XScaleTable[curXScale]; break; case 2: // YScale read_encoder = 1; curYScale = lastYScaleIndex + encoderValue - encoderZero; if(curYScale > MAX_Y_SCALE_INDEX) { curYScale = MAX_Y_SCALE_INDEX; encoderZero = lastYScaleIndex + encoderValue - curYScale; } if(curYScale < 0) { curYScale = 0; encoderZero = lastYScaleIndex + encoderValue - curYScale; } if(nowRelay == -1 && curYScale >= switchYScaleIndex) { nowRelay = 1; set_relay = 1; } else if(nowRelay == 1 && curYScale < switchYScaleIndex) { nowRelay = -1; set_relay = -1; } break; case 3: // offset read_encoder = 1; curOffset = lastOffset + (encoderValue - encoderZero) * 5; if(curOffset > MAX_OFFSET) { curOffset = MAX_OFFSET; encoderZero = encoderValue - (curOffset - lastOffset) / 5; } if(curOffset < MIN_OFFSET) { curOffset = MIN_OFFSET; encoderZero = encoderValue - (curOffset - lastOffset) / 5; } offset = (curOffset - MIN_OFFSET) * 255 / (MAX_OFFSET - MIN_OFFSET); break; case 4: // level read_encoder = 1; triggerLevel = lastLevel + (encoderValue - encoderZero) * 5; if(triggerLevel >= MAX_CURSOR_1Y) { triggerLevel = MAX_CURSOR_1Y; encoderZero = encoderValue - (triggerLevel - lastLevel) / 5; } if(triggerLevel <= MIN_CURSOR_1Y) { triggerLevel = MIN_CURSOR_1Y; encoderZero = encoderValue - (triggerLevel - lastLevel) / 5; } trigger_level = (triggerLevel - MIN_LEVEL) * 255 / (MAX_LEVEL - MIN_LEVEL); horizontalLine0.setPosition(15, (int16_t)(MAX_LEVEL - triggerLevel), slideMenu1.getState() == SlideMenu::COLLAPSED ? 430 : 297, 15); horizontalLine0.invalidate(); break; case 5: // cursor1X read_encoder = 1; curCursor1X = lastCursor1X + (encoderValue - encoderZero) * 5; if(curCursor1X >= MAX_CURSOR_1X) { curCursor1X = MAX_CURSOR_1X; encoderZero = encoderValue - (curCursor1X - lastCursor1X) / 5; } if(curCursor1X <= MIN_CURSOR_1X) { curCursor1X = MIN_CURSOR_1X; encoderZero = encoderValue - (curCursor1X - lastCursor1X) / 5; } verticalLine1.setPosition(slideMenu1.getState() == SlideMenu::COLLAPSED ? (int16_t)curCursor1X : (int16_t)curCursor1X * 297 / 450, 20, 15, 230); verticalLine1.invalidate(); break; case 6: // cursor1Y read_encoder = 1; curCursor1Y = lastCursor1Y + (encoderValue - encoderZero) * 5; if(curCursor1Y >= MAX_CURSOR_1Y) { curCursor1Y = MAX_CURSOR_1Y; encoderZero = encoderValue - (curCursor1Y - lastCursor1Y) / 5; } if(curCursor1Y <= MIN_CURSOR_1Y) { curCursor1Y = MIN_CURSOR_1Y; encoderZero = encoderValue - (curCursor1Y - lastCursor1Y) / 5; } horizontalLine1.setPosition(15, (int16_t)(MAX_LEVEL - curCursor1Y), slideMenu1.getState() == SlideMenu::COLLAPSED ? 435 : 297, 15); horizontalLine1.invalidate(); break; case 7: read_encoder = 1; curCursor2X = lastCursor2X + (encoderValue - encoderZero) * 5; if(curCursor2X >= MAX_CURSOR_1X) { curCursor2X = MAX_CURSOR_1X; encoderZero = encoderValue - (curCursor2X - lastCursor2X) / 5; } if(curCursor2X <= MIN_CURSOR_1X) { curCursor2X = MIN_CURSOR_1X; encoderZero = encoderValue - (curCursor2X - lastCursor2X) / 5; } verticalLine2.setPosition(slideMenu1.getState() == SlideMenu::COLLAPSED ? (int16_t)curCursor2X : (int16_t)curCursor2X * 297 / 450, 20, 15, 230); verticalLine2.invalidate(); break; case 8: read_encoder = 1; curCursor2Y = lastCursor2Y + (encoderValue - encoderZero) * 5; if(curCursor2Y >= MAX_CURSOR_1Y) { curCursor2Y = MAX_CURSOR_1Y; encoderZero = encoderValue - (curCursor2Y - lastCursor2Y) / 5; } if(curCursor2Y <= MIN_CURSOR_1Y) { curCursor2Y = MIN_CURSOR_1Y; encoderZero = encoderValue - (curCursor2Y - lastCursor2Y) / 5; } horizontalLine2.setPosition(15, (int16_t)(MAX_LEVEL - curCursor2Y), slideMenu1.getState() == SlideMenu::COLLAPSED ? 435 : 297, 15); horizontalLine2.invalidate(); break; default: break; } Unicode::snprintfFloat(cursor1DataTextBuffer1, 10, ""%.3f\0"", curCursor1X); Unicode::snprintfFloat(cursor1DataTextBuffer2, 10, ""%.3f\0"", curCursor1Y); Unicode::snprintfFloat(cursor2DataTextBuffer1, 10, ""%.3f\0"", curCursor2X); Unicode::snprintfFloat(cursor2DataTextBuffer2, 10, ""%.3f\0"", curCursor2Y); cursor1DataText.invalidate(); cursor2DataText.invalidate(); } void Screen1View::onSlideMenuUpdated() { if (slideMenu1.getState() == SlideMenu::COLLAPSED) { // slideMenu.setPisition() backButton.setVisible(false); for (int i = 1; i < 5; i ++) { menuList[i]->setVisible(false); } mainMenu.setVisible(true); displayGraph.setPosition(15, 20, 435, 230); displayGraph.invalidate(); // slideMenu1.setXY(486, 0); // slideMenu1.invalidate(); horizontalLine0.setPosition(15, (int16_t)(250 - triggerLevel), 435, 15); horizontalLine0.invalidate(); horizontalLine1.setPosition(15, (int16_t)(250 - curCursor1Y), 435, 15); horizontalLine1.invalidate(); verticalLine1.setPosition((int16_t)curCursor1X, 20, 15, 230); verticalLine1.invalidate(); horizontalLine2.setPosition(15, (int16_t)(250 - curCursor2Y), 435, 15); horizontalLine2.invalidate(); verticalLine2.setPosition((int16_t)curCursor2X, 20, 15, 230); verticalLine2.invalidate(); } else { displayGraph.setPosition(15, 20, 297, 230); displayGraph.invalidate(); horizontalLine0.setPosition(15, (int16_t)(250 - triggerLevel), 297, 15); horizontalLine0.invalidate(); horizontalLine1.setPosition(15, (int16_t)(250 - curCursor1Y), 297, 15); horizontalLine1.invalidate(); verticalLine1.setPosition((int16_t)curCursor1X * 297 / 435, 20, 15, 230); verticalLine1.invalidate(); horizontalLine2.setPosition(15, (int16_t)(250 - curCursor2Y), 297, 15); horizontalLine2.invalidate(); verticalLine2.setPosition((int16_t)curCursor2X * 297 / 435, 20, 15, 230); verticalLine2.invalidate(); } } void Screen1View::UpdateGraph(uint8_t* dataHead, uint8_t* dataTail, uint8_t* graphHead) { displayGraph.clear(); for (uint8_t* i = graphHead; i < dataTail; i ++) { displayGraph.addDataPoint((*i - (SCREEN_HEIGHT / 2)) * YScaleTable[curYScale] * (nowRelay == 1 ? 2 : 1) + (SCREEN_HEIGHT / 2) + curOffset); } for (uint8_t* i = dataHead; i < graphHead; i++) { displayGraph.addDataPoint((*i - (SCREEN_HEIGHT / 2)) * YScaleTable[curYScale] * (nowRelay == 1 ? 2 : 1) + (SCREEN_HEIGHT / 2) + curOffset); } displayGraph.invalidateContent(); // extern float input_v_pp; // extern float input_frequency; // extern float input_period; Unicode::snprintfFloat(VppTextBuffer, sizeof(VppTextBuffer), ""%.3f"", input_v_pp); Unicode::snprintfFloat(freqTextBuffer, sizeof(freqTextBuffer), ""%.1f"", input_frequency / 1000); Unicode::snprintfFloat(periodTextBuffer, sizeof(periodTextBuffer), ""%.3f"", input_period * 1000000); VppText.invalidateContent(); freqText.invalidateContent(); periodText.invalidateContent(); Unicode::snprintfFloat(dispXTextBuffer, 10, ""%.1f"", x_unit * 1000); Unicode::snprintfFloat(dispYTextBuffer, 10, ""%.3f"", y_unit / YScaleTable[curYScale]); dispXText.invalidateContent(); dispYText.invalidateContent(); } void Screen1View::onTriggerTypeClicked() { triggerType = !triggerType; if (triggerType) { Unicode::strncpy(triggerTypeTextBuffer, ""falling"", TRIGGERTYPETEXT_SIZE); trigger_mode = TRIGGER_MODE_FALLING; } else { Unicode::strncpy(triggerTypeTextBuffer, ""rising"", TRIGGERTYPETEXT_SIZE); trigger_mode = TRIGGER_MODE_RISING; } triggerTypeText.invalidate(); } ",value 208,"#include #include #include #include #include /* main integrator header file */ #include /* use CVDENSE linear solver */ #include /* use CVBAND linear solver */ #include /* use CVDIAG linear solver */ #include /* serial N_Vector types, fct. and macros */ #include /* definition of realtype */ #include /* contains the macros ABS, SUNSQR, and EXP*/ #include #include #include /* Shared Problem Constants */ #define ATOL RCONST(1.0e-6) #define RTOL RCONST(0.0) /* Functions called by CVODE */ static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data); /* Private function to check function return values */ static int check_flag(void *flagvalue, const char *funcname, int opt); // My user data class struct UserData { csim::ModelFunction modelFunction; N_Vector states, inputs, outputs; }; void usage(int argc, char* argv[]) { if (argc < 3) { std::cerr << ""CSim example: CVODE integrator\n"" << argv[0] << "" [output 2...]"" << std::endl; std::cerr << ""\tOutput variables should be indentified using component_name/variable_name\n"" << ""\tAt least one output must be specified. "" << std::endl; exit(-1); } } void printResults(UserData& ud) { for (int i = 0; i < NV_LENGTH_S(ud.outputs); ++i) { if (i != 0) std::cout << ""\t""; std::cout << NV_Ith_S(ud.outputs, i); } std::cout << std::endl; } int main(int argc, char* argv[]) { // for collecting data passed into CVODE UserData ud; // define the simulation for now double x0 = 0, x1 = M_PI * 2.0; int [MASK] = 100; // check command line arguments usage(argc, argv); csim::Model model; model.loadCellmlModel(argv[1]); // output variables std::vector outputNames; std::vector outputIndicies; int error = 0; for (int i = 2; i < argc; ++i) { outputNames.push_back(argv[i]); int index = model.setVariableAsOutput(argv[i]); if (index < 0) error++; else outputIndicies.push_back(index); } if (error) { std::cerr << ""There was an error setting output variables."" << std::endl; return -2; } if (model.instantiate() != csim::CSIM_OK) { std::cerr << ""There was an error instantiating the model."" << std::endl; return -3; } // grab the model's executable functions csim::InitialiseFunction initFunction = model.getInitialiseFunction(); ud.modelFunction = model.getModelFunction(); if ((initFunction == NULL) || (ud.modelFunction == NULL)) { std::cerr << ""Unable to get the model's executable function(s)."" << std::endl; return -4; } ud.states = N_VNew_Serial(model.numberOfStateVariables()); N_Vector rates = N_VNew_Serial(model.numberOfStateVariables()); ud.inputs = N_VNew_Serial(0); ud.outputs = N_VNew_Serial(outputNames.size()); // now get CVODE set up double reltol = RTOL, abstol = ATOL; // initialise the inputs and initial values of the state variables initFunction(NV_DATA_S(ud.states), NV_DATA_S(ud.outputs), NV_DATA_S(ud.inputs)); // and calculate and print the initial state of the model ud.modelFunction(x0, NV_DATA_S(ud.states), NV_DATA_S(rates), NV_DATA_S(ud.outputs), NV_DATA_S(ud.inputs)); std::cout << ""results headed goes here"" << std::endl; printResults(ud); // create and initialise our CVODE integrator void* cvode_mem = CVodeCreate(CV_ADAMS, CV_FUNCTIONAL); if(check_flag((void *)cvode_mem, ""CVodeCreate"", 0)) return(1); int flag = CVodeInit(cvode_mem, f, x0, ud.states); if(check_flag(&flag, ""CVodeInit"", 1)) return(1); flag = CVodeSStolerances(cvode_mem, reltol, abstol); if(check_flag(&flag, ""CVodeSStolerances"", 1)) return(1); // add our user data flag = CVodeSetUserData(cvode_mem, (void*)(&ud)); if (check_flag(&flag,""CVodeSetUserData"",1)) return(1); double dx = (x1 - x0) / [MASK] ; double x = x0, xout = x0; for (int i = 0; i < [MASK] ; ++i) { xout += dx; flag = CVodeSetStopTime(cvode_mem, xout); if (check_flag(&flag,""CVodeSetStopStime"",1)) return(1); flag = CVode(cvode_mem, xout, ud.states, &x, CV_NORMAL); if (check_flag(&flag,""CVode"",1)) return(1); // call the model's function to make sure all the outputs are at the current time ud.modelFunction(xout, NV_DATA_S(ud.states), NV_DATA_S(rates), NV_DATA_S(ud.outputs), NV_DATA_S(ud.inputs)); printResults(ud); } return 0; } int f(realtype x, N_Vector y, N_Vector ydot, void *user_data) { UserData* ud = (UserData*)user_data; ud->modelFunction(x, NV_DATA_S(y), NV_DATA_S(ydot), NV_DATA_S(ud->outputs), NV_DATA_S(ud->inputs)); return 0; } static int check_flag(void *flagvalue, const char *funcname, int opt) { int *errflag; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && flagvalue == NULL) { fprintf(stderr, ""\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n"", funcname); return(1); } /* Check if flag < 0 */ else if (opt == 1) { errflag = (int *) flagvalue; if (*errflag < 0) { fprintf(stderr, ""\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n"", funcname, *errflag); return(1); }} /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && flagvalue == NULL) { fprintf(stderr, ""\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n"", funcname); return(1); } return(0); } ",nSteps 209,"#include ""messagedialog.h"" #include ""ui_messagedialog.h"" #include #include #include MessageDialog::MessageDialog(QString title, QString message, DialogType [MASK] , QWidget *parent) : QWidget(parent), ui(new Ui::MessageDialog) { ui->setupUi(this); switch( [MASK] ) { case ShowMessage: break; case Select: break; } Qt::WindowFlags flags = Qt::Dialog; flags = flags | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint; setWindowFlags(flags); if(title.isEmpty()) title = tr(""Default Title""); if(message.isEmpty()) message = tr(""Default Message""); setWindowTitle(title); ui->label_message->setText(message); QImage image("":/dialoglib/icon-default.png""); ui->label_image->setMinimumSize(image.size()); qDebug() << ui->label_image->size(); adjustSize(); qDebug() << ui->label_image->size(); } MessageDialog::~MessageDialog() { delete ui; } int MessageDialog::exec() { setAttribute(Qt::WA_ShowModal, true); show(); m_eventloop = new QEventLoop(); m_eventloop->exec(); m_eventloop = NULL; return m_result; } void MessageDialog::on_pushButton_OK_clicked() { m_result = QDialog::Accepted; if(m_eventloop) { m_eventloop->exit(); } } void MessageDialog::on_pushButton_Cancel_clicked() { m_result = QDialog::Rejected; if(m_eventloop) { m_eventloop->exit(); } } ",type 210,"/*Author: File : main.cpp Desc : Entry point to answer data structs homework questions for current homework. Date : 3/1/23 */ #include ""tree.cpp"" #include int main() { // timer for calcNumNodes execution time--setNumNodes is the actual method that calculates the number of nodes. auto startCalcNumNodesTimer = std::chrono::high_resolution_clock::now(); // Timer for calcNumLeaves execution time--setNumLeaves is the actual method that calculates the number of leavs. auto startCalcNumLeaves = std::chrono::high_resolution_clock::now(); // Timer for calcNumFull execution time--setNumFull is the actual method that calculates the number of full nodes. auto startCalcNumFull = std::chrono::high_resolution_clock::now(); // create the binary tree. IntBinaryTree tree; std::cout << ""*********Welcome to my demonstration tree app**********************\n\n""; // Insert some values. tree.insertNode(4); tree.insertNode(2); tree.insertNode(3); tree.insertNode(1); tree.insertNode(9); // calculate the number of nodes and leaves in tree. tree.calcNumNodes(); auto endCalcNumNodesTimer = std::chrono::high_resolution_clock::now(); //-------------------------------------------------------------------------------------------------------- tree.calcNumLeaves(); auto endCalcNumLeaves = std::chrono::high_resolution_clock::now(); //------------------------------------------------------------------------------------------------------- tree.calcNumFull(); auto endCalcNumFull = std::chrono::high_resolution_clock::now(); //--------------------------------------------------------------------------------------------------------- // time difference for the calcNumNodes timer auto timeDiffCalcNumNodes = std::chrono::duration_cast(endCalcNumNodesTimer - startCalcNumNodesTimer); // time difference for the calcNumLeaves timer auto timeDiffCalcNumLeaves = std::chrono::duration_cast(endCalcNumLeaves - startCalcNumLeaves); // time difference for the calcNumFull auto timeDiffCalcNumFull = std::chrono::duration_cast(endCalcNumFull - startCalcNumFull); // Display the current values in the tree. std::cout << ""\nHere are the values in the tree: \n""; tree.displayInOrder(); std::cout << std::endl; std::cout << std::endl; // Display the current number of nodes in the tree. std::cout << ""Here are the number of nodes in the tree: \n""; int tempNodes = tree.getNumNodes(); std::cout << tempNodes << std::endl; // Execution time for calcNumNodes and setNumNodes methods. std::cout << ""Execution time: "" << timeDiffCalcNumNodes.count() << "" microseconds. "" << std::endl; // Display the current number of leaves in the tree. int tempLeaves = tree.getNumLeaves(); std::cout << ""Here are the number of leaves in the tree: \n""; std::cout << tempLeaves << std::endl; // Execution time for calcNumLeaves and setNumLeaves methods. std::cout << ""Execution time: "" << timeDiffCalcNumLeaves.count() << "" microseconds."" << std::endl; // Display the current number of full nodes in the tree. int [MASK] = tree.getNumFull(); std::cout << ""Here are the number of full nodes in the tree: \n""; std::cout << [MASK] << std::endl; // Execution time for calcNumFull and setNumFull methods. std::cout << ""Execution time: "" << timeDiffCalcNumFull.count() << "" microseconds."" << std::endl; //--------------------End of Question 1 implementation.------------------- //-------------------Beginning of Question 2 implementation--------------- std::cout << std::endl << std::endl; std::cout << ""Beginning of Q2 Implementation********************\n\n""; std::cout << ""Test for search order property of tree\n\n""; // test for search order property of tree tree.isSearchOrderPropertySatisfied(); // Get the result from the test if (tree.getSearchProp() == true) { std::cout << ""Search order property is satisfied\n\n""; } else { std::cout << ""Search order property is not satisfied\n\n""; } //--------------------End of Question 2 implementation----------------------- //--------------------Beginning of Question 3 implementation--------------- std::cout << ""Beginning of Q3 Implementation******************************\n\n""; std::cout << ""Here's the implementation of level wise order printing\n\n""; tree.displayLevelOrder(); //------------------------------------------------------------------------- }",tempFullNodes 211,"#pragma once #include #include #include ""tf2/LinearMath/Quaternion.h"" #include ""tf2_ros/transform_broadcaster.h"" #include ""tf2_ros/buffer.h"" #include ""tf2_ros/transform_listener.h"" #include ""ros2_aruco_interfaces/msg/aruco_markers.hpp"" #include ""nav_msgs/msg/odometry.hpp"" #include #include ""mage_msgs/msg/advanced_logical_camera_image.hpp"" #include ""mage_msgs/msg/part.hpp"" class MazeSolver : public rclcpp::Node{ public: MazeSolver(std::string maze_solver): Node(maze_solver){ // aruco marker id this->declare_parameter(""aruco_marker_0""); this->declare_parameter(""aruco_marker_1""); this->declare_parameter(""aruco_marker_2""); m_aruco_marker_0 = this->get_parameter(""aruco_marker_0"").as_string(); m_aruco_marker_1 = this->get_parameter(""aruco_marker_1"").as_string(); m_aruco_marker_2 = this->get_parameter(""aruco_marker_2"").as_string(); // map to determine the color and part from the Part.msg file color_map[mage_msgs::msg::Part::RED] = ""Red""; color_map[mage_msgs::msg::Part::GREEN] = ""Green""; color_map[mage_msgs::msg::Part::BLUE] = ""Blue""; color_map[mage_msgs::msg::Part::ORANGE] = ""Orange""; color_map[mage_msgs::msg::Part::PURPLE] = ""Purple""; part_map[mage_msgs::msg::Part::BATTERY] = ""battery""; part_map[mage_msgs::msg::Part::PUMP] = ""pump""; part_map[mage_msgs::msg::Part::SENSOR] = ""sensor""; part_map[mage_msgs::msg::Part::REGULATOR] = ""regulator""; m_msg = geometry_msgs::msg::Twist(); // MultiThreading m_callback_group_odom = this->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); auto [MASK] = rclcpp::SubscriptionOptions(); [MASK] .callback_group = m_callback_group_odom; m_callback_group_aruco = this->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); auto subscription_aruco = rclcpp::SubscriptionOptions(); subscription_aruco.callback_group = m_callback_group_aruco; // m_callback_group_logical_camera = this->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); // auto subscription_logical_camera = rclcpp::SubscriptionOptions(); // subscription_logical_camera.callback_group = m_callback_group_logical_camera; // timer m_timer = this->create_wall_timer(std::chrono::milliseconds((int)(500)), std::bind(&MazeSolver::timer_callback, this)); m_timer_listener = this->create_wall_timer(std::chrono::milliseconds((int)(500)), std::bind(&MazeSolver::listener_callback, this)); // m_timer_listener2 = this->create_wall_timer(std::chrono::milliseconds((int)(500)), std::bind(&MazeSolver::listener2_callback, this)); // publisher m_publisher = this->create_publisher(""cmd_vel"", 10); // Subscriber aruco_subscriber = this->create_subscription(""aruco_markers"", 10, std::bind(&MazeSolver::aruco_callback, this, std::placeholders::_1), subscription_aruco); odom_subscriber = this->create_subscription(""odom"", 10, std::bind(&MazeSolver::odom_callback, this, std::placeholders::_1), [MASK] ); logical_camera_subscriber = this->create_subscription(""/mage/advanced_logical_camera/image"", rclcpp::SensorDataQoS(), std::bind(&MazeSolver::logical_camera_callback, this, std::placeholders::_1)); // broadcaster tf_broadcaster = std::make_unique(*this); // tf_broadcaster2 = std::make_unique(*this); // Listener tf_buffer = std::make_unique(this->get_clock()); // aruco marker tf_listener = std::make_shared(*tf_buffer); // tf_buffer2 = std::make_unique(this->get_clock()); // parts // tf_listener2 = std::make_shared(*tf_buffer); } private: std::string m_aruco_marker_0; std::string m_aruco_marker_1; std::string m_aruco_marker_2; double aruco_z_position; // which marker to choose; Setting a random high value; int m_id; // Selecting the marker id of the nearest marker std::string m_turn; // direction to turn // Part std::map color_map; std::map part_map; std::string part_name_type; std::map color_part_map; // std::vector tf_msgs; geometry_msgs::msg::TransformStamped t_aruco; // geometry_msgs::msg::TransformStamped t_part; int flag{1}; double target_angle = 0; geometry_msgs::msg::Twist m_msg; std::vector marker_ids; // double odomToAruco; // double odomToBasefootprint; double arucoToBasefootprint; double robot_yaw_angle; // double angle = 0; // MultiThreading rclcpp::CallbackGroup::SharedPtr m_callback_group_odom; rclcpp::CallbackGroup::SharedPtr m_callback_group_aruco; rclcpp::CallbackGroup::SharedPtr m_callback_group_logical_camera; // Subscriber rclcpp::Subscription::SharedPtr aruco_subscriber; rclcpp::Subscription::SharedPtr odom_subscriber; rclcpp::Subscription::SharedPtr logical_camera_subscriber; // Timer rclcpp::TimerBase::SharedPtr m_timer; rclcpp::TimerBase::SharedPtr m_timer_listener; // aruco // rclcpp::TimerBase::SharedPtr m_timer_listener2; // parts // Publisher rclcpp::Publisher::SharedPtr m_publisher; // broadcaster std::unique_ptr tf_broadcaster; // broadcasting aruco position // std::unique_ptr tf_broadcaster2; // broadcasting parts position // Listener std::shared_ptr tf_buffer; // aruco marker std::shared_ptr tf_listener{nullptr}; // std::shared_ptr tf_buffer2; // parts // std::shared_ptr tf_listener2{nullptr}; void aruco_callback(const ros2_aruco_interfaces::msg::ArucoMarkers::SharedPtr msg); void timer_callback(); void listener_callback(); // void listener2_callback(); void odom_callback(const nav_msgs::msg::Odometry::SharedPtr msg); void logical_camera_callback(const mage_msgs::msg::AdvancedLogicalCameraImage::SharedPtr msg); };",subscription_odom 212,"#pragma once #include #include #include ""myheader.hpp"" #include ""mypointfield.hpp"" class MyPointCloud2 { public: MyHeader header; uint32_t height; uint32_t width; std::vector fields; bool is_bigendian; uint32_t point_step; uint32_t row_step; std::vector data; bool is_dense; MyPointCloud2() = default; MyPointCloud2(const MyHeader& header_, uint32_t height_, uint32_t width_, const std::vector& fields_, bool is_bigendian_, uint32_t [MASK] , uint32_t row_step_, const std::vector& data_, bool is_dense_) : header(header_), height(height_), width(width_), fields(fields_), is_bigendian(is_bigendian_), point_step( [MASK] ), row_step(row_step_), data(data_), is_dense(is_dense_) {} }; ",point_step_ 213,"// SPDX-FileCopyrightText: 2006-2025 & Freie Universität Berlin // SPDX-FileCopyrightText: 2016-2025 & MPI für molekulare Genetik // SPDX-License-Identifier: CC0-1.0 #include #include #include #include #include #include using seqan3::operator""""_dna4; using seqan3::operator""""_dna5; using seqan3::operator""""_phred42; int main() { // A vector of combined sequence and quality information. std::vector sequence1{{'A'_dna4, '!'_phred42}, {'C'_dna4, 'A'_phred42}, {'G'_dna4, '6'_phred42}, {'T'_dna4, '&'_phred42}}; // A vector of dna5. std::vector sequence2{""AGNCGTNNCAN""_dna5}; // Convert dna4q to dna4. // Since `sequence1` is an lvalue, we capture `in` via const &. When unsure, use the general case below. auto view1 = sequence1 | std::views::transform( [](auto const & in) { return static_cast(in); }); seqan3::debug_stream << view1 << '\n'; // ACGT // Convert dna5 to dna4. // General case: Perfect forward. auto [MASK] = sequence2 | std::views::take(8) | std::views::transform( [](auto && in) { return static_cast(std::forward(in)); }); seqan3::debug_stream << [MASK] << '\n'; // AGACGTAA return 0; } ",view2 214,"#include // Digital pins. #define PIN_IR_LEFT 4 #define PIN_IR_CENTER 5 #define PIN_IR_RIGHT 6 #define PIN_HALL_EFFECT_LEFT 7 #define PIN_HALL_EFFECT_RIGHT 8 #define PIN_LASER_POWER 10 #define PIN_MOTOR_LEFT 3 #define PIN_MOTOR_RIGHT 9 // Analog pins. #define PIN_LASER_READER 0 // Configs. #define ROTATIONS_COLLECTED 100 // Define State Machine. enum PathState { START, CHECKPOINT_ONE, CHECKPOINT_TWO, BROOM_STICK_BEGIN, BROOM_STICK_ABYSS, JUMP_EXIT_LANE, DO_A_FLIP, FIND_THE_LINE, RED_LINE_RIDER, INVERTED_CUP_STRAIGHT, INVERTED_CUP_RIGHT, FINISH }; PathState currentPathState = START; // Motor Setup ------------------ Servo lMotor; Servo rMotor; // Debug printer: // The last time that a Serial.print was made. uint64_t lastTime = 0; // Wheel data container. struct Wheel { // Revolution collector: // The collection of timestamps of last revolutions. uint64_t ticks[ROTATIONS_COLLECTED]; // The position to insert the next revolution. int index = 0; // The global revolutions for this motor since reset. int tickCount = 0; // Motor controller. Servo servo; void recordTick() { tickCount++; ticks[index] = millis(); index = (++index) % ROTATIONS_COLLECTED; } int countTicks(uint64_t now, uint64_t window) { int count = 0; // Circuluar access to last node. int i = index - 1; if (i < 0) i += ROTATIONS_COLLECTED; uint64_t min_time = now - window; if (min_time < 0) return 0; while (true) { if (ticks[i] >= min_time) { count++; if (count > ROTATIONS_COLLECTED) { // FUCK! break; } i--; if (i < 0) i += ROTATIONS_COLLECTED; } else { // Expected. break; } } return count; } }; void initWheel(Wheel wheel, int [MASK] , int pin_hall_effect) { // Setup Struct. wheel.index = 0; wheel.tickCount = 0; for (int i = 0; i < sizeof(wheel.ticks); i++) wheel.ticks[i] = -1; // Attach servo monitor. wheel.servo.attach( [MASK] ); } Wheel left; Wheel right; void recieveHallEffectLeft() { left.recordTick(); } void recieveHallEffectRight() { right.recordTick(); } void setup() { // Set up wheel servos. initWheel(left, PIN_MOTOR_LEFT, PIN_HALL_EFFECT_LEFT); initWheel(right, PIN_MOTOR_RIGHT, PIN_HALL_EFFECT_RIGHT); // Set up IR sensors. pinMode(PIN_IR_LEFT, INPUT); pinMode(PIN_IR_CENTER, INPUT); pinMode(PIN_IR_RIGHT, INPUT); // Set up the Hall Effect Sensors. pinMode(PIN_HALL_EFFECT_LEFT, INPUT); pinMode(PIN_HALL_EFFECT_RIGHT, INPUT); // Attach hall effect sensor. attachInterrupt(digitalPinToInterrupt(PIN_HALL_EFFECT_LEFT), recieveHallEffectLeft, FALLING); attachInterrupt(digitalPinToInterrupt(PIN_HALL_EFFECT_RIGHT), recieveHallEffectRight, FALLING); Serial.begin(9600); Serial.println(""Let's go!""); } // AI told me this is how I print a uint64. void printUint64(uint64_t value) { uint32_t high = value >> 32; uint32_t low = value & 0xFFFFFFFF; Serial.print(high, HEX); Serial.print(low, HEX); } void printDebugUpdate(uint64_t now) { Serial.print(""[1s @""); printUint64(now); Serial.print(""] left ticks: ""); //Serial.println(left.tickCount); Serial.print(left.countTicks(now, 1000)); Serial.print("" right ticks: ""); Serial.println(right.countTicks(now, 1000)); } void executeDefaultLineRider() { // TODO: do something! } void executeStateMachine() { switch (currentPathState) { default: executeDefaultLineRider(); break; } } void loop() { executeStateMachine(); // Only give a status update every second. uint64_t now = millis(); if ((now - lastTime) >= 1000) { printDebugUpdate(now); lastTime = now; } } ",pin_servo 215,"#include ""TestUtils.h"" #include #include namespace pcpp_tests { int getFileLength(const char* filename) { std::ifstream infile(filename, std::ifstream::binary); if (!infile) return -1; infile.seekg(0, infile.end); int length = infile.tellg(); infile.close(); return length; } uint8_t* readFileIntoBuffer(const char* filename, int& bufferLength) { int fileLength = getFileLength(filename); if (fileLength == -1) return NULL; std::ifstream infile(filename); if (!infile) return NULL; bufferLength = fileLength/2 + 2; uint8_t* result = new uint8_t[bufferLength]; int i = 0; while (!infile.eof()) { char byte[3]; memset(byte, 0, 3); infile.read(byte, 2); result[i] = (uint8_t)strtol(byte, NULL, 16); i++; } infile.close(); bufferLength -= 2; return result; } void printBufferDifferences(const uint8_t* buffer1, size_t buffer1Len, const uint8_t* buffer2, size_t [MASK] ) { printf(""\n\n\n""); for(int i = 0; i<(int)buffer1Len; i++) printf("" 0x%2X "", buffer1[i]); printf(""\n\n\n""); for(int i = 0; i<(int) [MASK] ; i++) { if (buffer2[i] != buffer1[i]) printf(""*0x%2X* "", buffer2[i]); else printf("" 0x%2X "", buffer2[i]); } printf(""\n\n\n""); } #ifdef PCPP_TESTS_DEBUG #include void savePacketToPcap(Packet& packet, std::string fileName) { pcap_t* pcap; pcap = pcap_open_dead(1, 65565); pcap_dumper_t* d; /* open output file */ d = pcap_dump_open(pcap, fileName.c_str()); if (d == NULL) { pcap_perror(pcap, ""pcap_dump_fopen""); return; } /* prepare for writing */ struct pcap_pkthdr hdr; hdr.ts.tv_sec = 0; /* sec */ hdr.ts.tv_usec = 0; /* ms */ hdr.caplen = hdr.len = packet.getRawPacket()->getRawDataLen(); /* write single IP packet */ pcap_dump((u_char*)d, &hdr, packet.getRawPacketReadOnly()->getRawData()); /* finish up */ pcap_dump_close(d); return; } #endif }",buffer2Len 216,"#ifndef _STATE_MACHINE_HPP_ #define _STATE_MACHINE_HPP_ #include #include #include #include #include #include class Alphabet { public: explicit Alphabet(int k, std::shared_ptr v = nullptr) : key(k), value(v) {} virtual ~Alphabet() {} int key; std::shared_ptr value; }; class State { public: explicit State(int key, std::function(std::shared_ptr)> exec) : key_(key), execute_(exec) { transitions_.clear(); } virtual ~State() {} int get_key() { return key_; } void add_transition(int alphabet, int state) { transitions_[alphabet] = state; } int get_transition_state(int alphabet) { if(transitions_.find(alphabet) == transitions_.end()) { std::ostringstream error; error << ""transition "" << alphabet << "" is undefine in state "" << key_ << "".""; throw std::range_error(error.str()); } return transitions_[alphabet]; } std::shared_ptr execute(std::shared_ptr alphabet) { if(execute_ != nullptr) return execute_(alphabet); else return nullptr; } protected: int key_; private: std::map transitions_; std::function(std::shared_ptr)> execute_; State(const State& ) {} State& operator=(const State& ) { return *this; } }; class StateMachine { public: StateMachine() : current_(nullptr) { states_.clear(); } ~StateMachine() {} void add_state(std::shared_ptr state) { states_[state->get_key()] = state; } void add_state_transition(int key, int alphabet, int state) { get_next_state(key)->add_transition(alphabet, state); } void start(int state) { current_ = get_next_state(state); std::thread [MASK] (&StateMachine::process, this); [MASK] .detach(); } void stop() { current_ = nullptr; } int get_current_state() { return current_->get_key(); } private: std::shared_ptr current_; std::map> states_; void process() { std::shared_ptr alphabet = nullptr; while(current_ != nullptr) { alphabet = current_->execute(alphabet); if(alphabet == nullptr) break; current_ = get_next_state(current_->get_transition_state(alphabet->key)); } } std::shared_ptr get_next_state(int key) { if(states_.find(key) == states_.end()) { std::ostringstream error; error << ""state "" << key << "" is undefine in state machine.""; throw std::range_error(error.str()); } return states_[key]; } StateMachine(const StateMachine& ) {} StateMachine& operator=(const StateMachine& ) { return *this; } }; #endif",process_thread 217,"/* * Copyright (c) 2014, * * 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. */ #include #include #include #include #include #include #include ""common/WidgetRenderer.h"" int main() { const std::string [MASK] = ""libsuit: test of the video configuration widget""; sf::RenderWindow window(sf::VideoMode(800, 600), [MASK] ); WidgetRenderer renderer(window); ui::Area area({ 200.0f, 100.0f, 400.0f, 200.0f }); area.addChild(new ui::VideoConfigWidget(window, [MASK] )); area.updateLayout(); ui::StandardActionSet actions; auto escapeAction = std::make_shared(""Escape""); escapeAction->addKeyControl(sf::Keyboard::Escape); escapeAction->addCloseControl(); actions.addAction(escapeAction); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { actions.update(event); if (event.type == sf::Event::MouseButtonPressed) { area.onClick(event.mouseButton.button, { static_cast(event.mouseButton.x), static_cast(event.mouseButton.y) }); } } if (escapeAction->isActive()) { window.close(); } actions.handleArea(area); window.clear(sf::Color::White); renderer.draw(area, false); window.display(); actions.reset(); } return 0; } ",title 218,"#include ""instructionSet.h"" //NOTE: to link program files each file can consist of a class, each class can be called by its various functions through object creation (when START message is fetched) each class is capable of sending messages into main loop through their own messaging procedures //These messages can then be handled through the main loop, when a message is passed it will call its relevant function / functions from its source file to execute the required procedure. //Basic messages for all classes : /* PULL MESSAGE (PULLS first priority message from a given source files que, sends it into mainMessage loop to be executed) (This should be done for every file (in priority order) at the end of a message FDE cycle) relevant function: queMessage(MSG) internal messaging procedure for source file, ques parameter message into relavent que, ready to be fetched by the main messaging cycle. INITIALIZEOBJ (Initialises object for all source file instances, pulling them into scope within the main file procedures. */ int main() { tree [MASK] ; temporalLobe::node* root = [MASK] .initialiseMemory(0); [MASK] .sendMessage( [MASK] .START, 10); [MASK] .sendMessage( [MASK] .TEST, 4); [MASK] .sendMessage( [MASK] .START, 3); [MASK] .sendMessage( [MASK] .TEST, 6); std::cout << ""Binary Tree Populated\n"" << ""-----------------------------------\n""; while (true) //LOOP { bool flag = false; int num{}; [MASK] .sendMessage( [MASK] .fetchPost(), [MASK] ); //CHECK MESSAGE QUE PRIORITY, TAKE PRIORITY MESSAGE while (flag == false) // loop implemented to pause system at runtime as to see console outputs of main message loop. { while (std::cout << ""|please enter 1 to continue|\n"" && !(std::cin >> num)) { std::cin.clear(); std::cin.ignore(std::numeric_limits::max(), '\n'); std::cout << "" |Incorrect data input| \n""; } if (num == 1) { flag = true; } } /* LOOP CATCH MESSAGE _/ PASS TO MESSAGE QUE _/ CHECK MESSAGE QUE PRIORITY _/ TAKE PRIORITY MESSAGE _/ DO FUNC FROM MESSAGE _/ RECIEVE MESSAGE FROM FUNC RECIEVE MESSAGE FROM PARIETAL DO BACKGROUND FUNC FROM SECOND MESSAGE SET (IF IN HIBERNATION, OR A SET AMOUNT OF TIME HAS PASSED) SET MESSAGE PRIORITIES (IF REACTORY FUNCTIONS RETURN THAT A FUNCTION NEEDS COMPLETING IMMEDIATELY) LOOP */ //POSSIBLE TO HAVE MULTIPLE PRIORITY QUES CALLED IN PRIORITY ORDER, MIMICKING BACKGROUND FUNCTIONS OF BRAIN //POSSIBLE MESSAGE LOOP FOR EACH SECTION OF THE BRAIN IF REQUIRED, may be out of limitations however. } return 0; } //need to set enum message before passing into function //In not to creating ralph I have defined a set structure in which each part of Ralphs brain will form. In which each part will originate from a root node, as seen in the temporal lobe program, data processed by each respective part of the brain will store data in its respective root sector; howeveer, these sectors will not be independant, but instead will be connected through relations in the data processed (aka each sector will be connected by weight) these weights will act as direct connections in how ralphs brain communicates, for instance connecting the logical solution of what and a previously processed solution of kangaroo to the kangaroo data node, which will be connected to the data cluster of the data of a processed image of a kangaroo. // an example of how this may be used within programmative thinking within ralph is here: ralph takes in data via a question, ""what is a kangaroo"", he checks his processing centre to see if the answer or data regarding this answer is stored within its respective cluster, pulling nodes related to this and displaying the data in the desired language and format, he simultaneously looks for this data within other clusters, if one is found in a cluster it checks to see if a connection exists to a different cluster , if it does it follows it and pulls its respective data. If it is found that related data is not connected to each cluster then new connections will be formed, this may be as abstract as connecting the picture of a kangaroo to the data point within long term memory of the sahara or sarengheti in response to a positive response or ""dopamine"" being released on the correct answer of ""what is a sarengheti animal"" and kangaroo being the response //this will give ralph the ability to cross referance between different sections and pieces of his brain to form ideas, connections and referances to different matters as to answer matters more efficiently, as we are all learning machines after all. // process diagram //data input --> processing centre / find answer / try answer / store solution if correct --> if not pull data from seperate cluster and try and format answer from current data, according to the data provided / if simallar answer exists to current question, format in a simalar way --> check how output is reecieved, if good add respective connections, store solution in processing cluster (next to / in relation to similar answer if used) / connect data points in different cluster e.g what is a kangaroo to kangaroo imagery cluster, kangaroo long term memory data point, sahara data point etc //ToDO //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //possibly modify translation function within temporalLobe as to cater for all sections of ralph, currently programmed to translate long term memory structure only, however could be coded logically as to read all structures if they use the same basic structure (nodes) for the tree. // //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------",mainLoop 219,"#include #include #include #include ModbusMaster node; #define SLAVE_ID 2 #define VOLTAGE_ADDR 0x0000 #define VOLTAGE_LEN 2 #define CURRENT_ADDR 0x0E #define CURRENT_LEN 2 #define POWER_ADDR 0x14 #define POWER_LEN 2 #define KILOWATTS_HOUR_ADDR 0x112 #define KILOWATTS_HOUR_LEN 2 #define VOLTAGE_WEIGHT 0.1 #define CURRENT_WEIGHT 0.001 #define POWER_WEIGHT 0.1 #define KILOWATTS_HOUR_WEIGHT 0.1 #define SCREEN_WIDTH 128 #define SCREEN_HEIGHT 64 #define OLED_RESET -1 Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); void setup() { Serial1.begin(9600); Serial.begin(9600); node.begin(SLAVE_ID, Serial1); if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Serial.println(F(""SSD1306 allocation failed"")); for (;;) ; } delay(2000); display.clearDisplay(); display.display(); } void loop() { uint8_t result; float voltage, current, power, [MASK] ; result = node.readHoldingRegisters(VOLTAGE_ADDR, VOLTAGE_LEN); voltage = (float)node.getResponseBuffer(0) + ((float)node.getResponseBuffer(1) / 100.0); voltage = voltage * VOLTAGE_WEIGHT; delay(500); result = node.readHoldingRegisters(CURRENT_ADDR, CURRENT_LEN); current = (float)node.getResponseBuffer(0) + ((float)node.getResponseBuffer(1) / 100.0); current = current * CURRENT_WEIGHT; delay(500); result = node.readHoldingRegisters(POWER_ADDR, POWER_LEN); power = (float)node.getResponseBuffer(0) + ((float)node.getResponseBuffer(1) / 100.0); power = power * POWER_WEIGHT; delay(500); result = node.readHoldingRegisters(KILOWATTS_HOUR_ADDR, KILOWATTS_HOUR_LEN); [MASK] = (float)node.getResponseBuffer(0) + ((float)node.getResponseBuffer(1) / 100.0); [MASK] = [MASK] * KILOWATTS_HOUR_WEIGHT; display.clearDisplay(); display.setTextSize(1); display.setTextColor(SSD1306_WHITE); display.setCursor(0, 0); display.print(""Voltage: ""); display.println(voltage); display.print(""Current: ""); display.println(current); display.print(""Power: ""); display.println(power); display.print(""KWh: ""); display.println( [MASK] ); display.display(); delay(10000); } ",kilowatts_hour 220,"#include ""videoControls.h"" #include ""vsliderwidget.h"" const char* Property_Rate = ""RateValue""; VideoControls::VideoControls(QWidget *parent) :QWidget(parent) { ui.setupUi(this); setWindowFlags(Qt::FramelessWindowHint/* | Qt::Tool*/); setAttribute(Qt::WA_TranslucentBackground); initVolumeSlider(); //播放/暂停 connect(ui.pushButton_play, &QPushButton::clicked, this, &VideoControls::sltVideoPlayOrPause); //声音 connect(ui.pushButton_volum, &QPushButton::clicked, this, &VideoControls::sltVolumControls); //进度 connect(ui.slider_progress, &CustomSlider::costomSliderClicked, this, &VideoControls::sltSliderProgressClicked); connect(ui.slider_progress, &CustomSlider::sliderReleased, this, &VideoControls::sltSliderProgressReleased); //倍速 ui.pushButton_rate->setProperty(Property_Rate, 1.0); connect(ui.pushButton_rate, &QPushButton::clicked, this, &VideoControls::sltSetVideoRate); } VideoControls::~VideoControls() { } void VideoControls::setProgressDuration(qint64 [MASK] ) { ui.slider_progress->setMaximum( [MASK] ); } bool VideoControls::isSliderDown() { return ui.slider_progress->isSliderDown(); } void VideoControls::setSliderPosition(int position) { ui.slider_progress->setSliderPosition(position); } void VideoControls::setProgressText(const QString & text) { ui.label_volumNum->setText(text); } void VideoControls::setPlaying(bool state) { //启用播放/暂停按钮,并将其文本设置为“暂停” ui.pushButton_play->setChecked(state); } void VideoControls::setVoiceValue(int value) { m_volumeSlider->setVoiceValue(value); } bool VideoControls::getVolumVisible() { if (m_volumeSlider) { return m_volumeSlider->isVisible(); } return false; } void VideoControls::initVolumeSlider() { m_volumeSlider = QSharedPointer(new VSliderWidget(this)); if (m_volumeSlider) { m_volumeSlider->installEventFilter(this); m_volumeSlider->setWindowFlags(Qt::FramelessWindowHint | Qt::Tool); connect(m_volumeSlider.data(), &VSliderWidget::sigValueChanged, this, &VideoControls::sltSoundVoiceValue); } } void VideoControls::locateWidgets() { if (m_volumeSlider) { int posX = ui.pushButton_volum->x() + 6; int posY = -m_volumeSlider->height(); m_volumeSlider->move(mapToGlobal(QPoint(posX, posY))); } } void VideoControls::closeWidget() { if (m_volumeSlider) { m_volumeSlider->close(); } } void VideoControls::sltSliderProgressClicked() { auto value = ui.slider_progress->value(); emit sigSetPosition(value); } void VideoControls::sltSliderProgressReleased() { auto value = ui.slider_progress->value(); emit sigSetPosition(value); } void VideoControls::sltSoundVoiceValue(int value) { if (0 == value) { ui.pushButton_volum->setStyleSheet(""border-image: url(:/qrc/qrc/yyf_ico_yl_gb.png);""); } else { ui.pushButton_volum->setStyleSheet(""border-image: url(:/qrc/qrc/yyf_ico_yl.png);""); } emit sigSoundVoiceValue(value); } void VideoControls::sltVolumControls() { if (m_volumeSlider) { locateWidgets(); auto isVisible = m_volumeSlider->isVisible(); m_volumeSlider->setVisible(!isVisible); } } void VideoControls::sltSetVideoRate() { auto rate = ui.pushButton_rate->property(Property_Rate).toFloat(); if (1.0 == rate) { rate = 1.5; } else if (1.5 == rate) { rate = 2.0; } else if (2.0 == rate) { rate = 3.0; } else if (3.0 == rate) { rate = 0.5; } else if (0.5 == rate) { rate = 1.0; } ui.pushButton_rate->setProperty(Property_Rate, rate); ui.pushButton_rate->setText(QString(""x%1"").arg(rate)); emit sigSetRate(rate); } void VideoControls::sltVideoPlayOrPause() { auto isPlay = ui.pushButton_play->isChecked(); emit sigVideoPlayOrPause(isPlay); } ",duration 221,"// main.cpp // This is the main game builder file which reads in two hands from // text files and plays the game // - 6872774 #include #include #include #include ""cards.h"" #include ""utility.h"" using namespace std; void AliceTurn(PlayerHand& alice, PlayerHand& bob); void BobTurn(PlayerHand& alice, PlayerHand& bob); void AliceTurn(PlayerHand& alice, PlayerHand& bob){ Card curCard = alice.getLowestCard(); while(true){ if (curCard.getValue() == 0) return; if(bob.contains(curCard)){ //bob also has this card cout<<""Alice picked matching card ""; curCard.printCardShort(); bob.deleteCard(curCard); alice.deleteCard(curCard); BobTurn(alice, bob); } else { //bob doesn't have the card curCard = alice.getSuccessor(curCard); } } } void BobTurn(PlayerHand& alice, PlayerHand& bob){ Card curCard = bob.getHighestCard(); while(true){ if(curCard.getValue() == 0) return; if(alice.contains(curCard)){ //alice also has this card cout<<""Bob picked matching card ""; curCard.printCardShort(); alice.deleteCard(curCard); bob.deleteCard(curCard); AliceTurn(alice, bob); } else { //alice doesn't have the card curCard = bob.getPredecessor(curCard); } } } int main(int argv, char** argc){ if(argv < 3){ cout << ""Please provide 2 file names"" << endl; return 1; } ifstream cardFile1 (argc[1]); ifstream cardFile2 (argc[2]); string line; if (cardFile1.fail() || cardFile2.fail() ){ cout << ""Could not open file "" << argc[2]; return 1; } char [MASK] = ' '; PlayerHand alice; PlayerHand bob; //Read each file while (getline (cardFile1, line) && (line.length() > 0)){ char suit = line.at(0); string face = line.substr(line.find( [MASK] )+1,-1); alice.insert(Card(suit, face)); } cardFile1.close(); while (getline (cardFile2, line) && (line.length() > 0)){ char suit = line.at(0); string face = line.substr(line.find( [MASK] )+1,-1); bob.insert(Card(suit, face)); } cardFile2.close(); // Begin Alice's Turn AliceTurn(alice, bob); cout< #include namespace PaddleDetection { typedef enum { New = 0, Tracked = 1, Lost = 2, Removed = 3 } TrajectoryState; class Trajectory; typedef std::vector TrajectoryPool; typedef std::vector::iterator TrajectoryPoolIterator; typedef std::vectorTrajectoryPtrPool; typedef std::vector::iterator TrajectoryPtrPoolIterator; class TKalmanFilter : public cv::KalmanFilter { public: TKalmanFilter(void); virtual ~TKalmanFilter(void) {} virtual void init(const cv::Mat &measurement); virtual const cv::Mat &predict(); virtual const cv::Mat &correct(const cv::Mat &measurement); virtual void project(cv::Mat &mean, cv::Mat &covariance) const; private: float std_weight_position; float std_weight_velocity; }; inline TKalmanFilter::TKalmanFilter(void) : cv::KalmanFilter(8, 4) { cv::KalmanFilter::transitionMatrix = cv::Mat::eye(8, 8, CV_32F); for (int i = 0; i < 4; ++i) cv::KalmanFilter::transitionMatrix.at(i, i + 4) = 1; cv::KalmanFilter::measurementMatrix = cv::Mat::eye(4, 8, CV_32F); std_weight_position = 1/20.f; std_weight_velocity = 1/160.f; } class Trajectory : public TKalmanFilter { public: Trajectory(); Trajectory(cv::Vec4f <rb, float score, const cv::Mat &embedding); Trajectory(const Trajectory &other); Trajectory &operator=(const Trajectory &rhs); virtual ~Trajectory(void) {}; static int next_id(); virtual const cv::Mat &predict(void); virtual void update(Trajectory &traj, int timestamp, bool update_embedding=true); virtual void activate(int timestamp); virtual void reactivate(Trajectory &traj, int timestamp, bool newid=false); virtual void mark_lost(void); virtual void mark_removed(void); friend TrajectoryPool operator+(const TrajectoryPool &a, const TrajectoryPool &b); friend TrajectoryPool operator+(const TrajectoryPool &a, const TrajectoryPtrPool &b); friend TrajectoryPool &operator+=(TrajectoryPool &a, const TrajectoryPtrPool &b); friend TrajectoryPool operator-(const TrajectoryPool &a, const TrajectoryPool &b); friend TrajectoryPool &operator-=(TrajectoryPool &a, const TrajectoryPool &b); friend TrajectoryPtrPool operator+(const TrajectoryPtrPool &a, const TrajectoryPtrPool &b); friend TrajectoryPtrPool operator+(const TrajectoryPtrPool &a, TrajectoryPool &b); friend TrajectoryPtrPool operator-(const TrajectoryPtrPool &a, const TrajectoryPtrPool &b); friend cv::Mat embedding_distance(const TrajectoryPool &a, const TrajectoryPool &b); friend cv::Mat embedding_distance(const TrajectoryPtrPool &a, const TrajectoryPtrPool &b); friend cv::Mat embedding_distance(const TrajectoryPtrPool &a, const TrajectoryPool &b); friend cv::Mat mahalanobis_distance(const TrajectoryPool &a, const TrajectoryPool &b); friend cv::Mat mahalanobis_distance(const TrajectoryPtrPool &a, const TrajectoryPtrPool &b); friend cv::Mat mahalanobis_distance(const TrajectoryPtrPool &a, const TrajectoryPool &b); friend cv::Mat iou_distance(const TrajectoryPool &a, const TrajectoryPool &b); friend cv::Mat iou_distance(const TrajectoryPtrPool &a, const TrajectoryPtrPool &b); friend cv::Mat iou_distance(const TrajectoryPtrPool &a, const TrajectoryPool &b); private: void update_embedding(const cv::Mat &embedding); public: TrajectoryState state; cv::Vec4f ltrb; cv::Mat smooth_embedding; int id; bool is_activated; int timestamp; int starttime; float score; private: static int count; cv::Vec4f xyah; cv::Mat current_embedding; float eta; int length; }; inline cv::Vec4f ltrb2xyah(cv::Vec4f <rb) { cv::Vec4f xyah; xyah[0] = (ltrb[0] + ltrb[2]) * 0.5f; xyah[1] = (ltrb[1] + ltrb[3]) * 0.5f; xyah[3] = ltrb[3] - ltrb[1]; xyah[2] = (ltrb[2] - ltrb[0]) / xyah[3]; return xyah; } inline Trajectory::Trajectory() : state(New), ltrb(cv::Vec4f()), smooth_embedding(cv::Mat()), id(0), is_activated(false), timestamp(0), starttime(0), score(0), eta(0.9), length(0) { } inline Trajectory::Trajectory(cv::Vec4f <rb_, float [MASK] , const cv::Mat &embedding) : state(New), ltrb(ltrb_), smooth_embedding(cv::Mat()), id(0), is_activated(false), timestamp(0), starttime(0), score( [MASK] ), eta(0.9), length(0) { xyah = ltrb2xyah(ltrb); update_embedding(embedding); } inline Trajectory::Trajectory(const Trajectory &other): state(other.state), ltrb(other.ltrb), id(other.id), is_activated(other.is_activated), timestamp(other.timestamp), starttime(other.starttime), xyah(other.xyah), score(other.score), eta(other.eta), length(other.length) { other.smooth_embedding.copyTo(smooth_embedding); other.current_embedding.copyTo(current_embedding); // copy state in KalmanFilter other.statePre.copyTo(cv::KalmanFilter::statePre); other.statePost.copyTo(cv::KalmanFilter::statePost); other.errorCovPre.copyTo(cv::KalmanFilter::errorCovPre); other.errorCovPost.copyTo(cv::KalmanFilter::errorCovPost); } inline Trajectory &Trajectory::operator=(const Trajectory &rhs) { this->state = rhs.state; this->ltrb = rhs.ltrb; rhs.smooth_embedding.copyTo(this->smooth_embedding); this->id = rhs.id; this->is_activated = rhs.is_activated; this->timestamp = rhs.timestamp; this->starttime = rhs.starttime; this->xyah = rhs.xyah; this->score = rhs.score; rhs.current_embedding.copyTo(this->current_embedding); this->eta = rhs.eta; this->length = rhs.length; // copy state in KalmanFilter rhs.statePre.copyTo(cv::KalmanFilter::statePre); rhs.statePost.copyTo(cv::KalmanFilter::statePost); rhs.errorCovPre.copyTo(cv::KalmanFilter::errorCovPre); rhs.errorCovPost.copyTo(cv::KalmanFilter::errorCovPost); return *this; } inline int Trajectory::next_id() { ++count; return count; } inline void Trajectory::mark_lost(void) { state = Lost; } inline void Trajectory::mark_removed(void) { state = Removed; } } // namespace PaddleDetection ",score_ 223,"#include #include #include Car car; const int motorSpeed = 80; //80% of the max speed const uint8_t distanceThreshold = 25; const uint8_t SONIC_DISC_I2C_ADDRESS = 0x09; const uint8_t NUM_OF_SENSORS = 8; // No. of ultrasonic sensors on SonicDisc // The packet contains NUM_OF_MEASUREMENTS measurements and an error code const uint8_t I2C_PACKET_SIZE = NUM_OF_SENSORS + 1; // The number of measurements from each sensor to filter const uint8_t MEASUREMENTS_TO_FILTER = 5; const uint8_t INT_PIN = 2; // The max valid variance in a set of MEASUREMENTS_TO_FILTER measurements const unsigned int VARIANCE_THRESHOLD = 3; // Sonic Disc's operational states enum State { STANDBY, // MCU and sensors are on but no measurements are being made MEASURING // Sonic Disc is conducting measurements using the sensors }; // Values to be received via I2C from master enum I2C_RECEIPT_CODE { STATE_TO_STANDBY = 0x0A, STATE_TO_MEASURING = 0x0B }; // Error codes to be transmitted via I2c to the master enum I2C_ERROR_CODE { NO_ERROR, IN_STANDBY, INCOMPLETE_MEASUREMENT }; // Flag to indicate the SonicDisc is ready to send a new set of data volatile bool newData = false; uint8_t filterIndex = 0; uint8_t filterBuffer[MEASUREMENTS_TO_FILTER][NUM_OF_SENSORS] = {0}; uint8_t filteredMeasurements[NUM_OF_SENSORS] = {0}; bool newFilteredMeasurements = false; /** Requests an I2C packet from the SonicDisc @param i2cInput The array that will hold the incoming packet @param transmissionSize The size/length of the incoming packet @return Error code contained inside the incoming packet */ I2C_ERROR_CODE requestPacket(uint8_t i2cInput[], const uint8_t transmissionSize = I2C_PACKET_SIZE) { Wire.requestFrom(SONIC_DISC_I2C_ADDRESS, transmissionSize); uint8_t packetIndex = 0; while (Wire.available() && packetIndex < transmissionSize) { i2cInput[packetIndex++] = Wire.read(); } return i2cInput[0]; // Return the packet's error code } /** Sends the supplied byte to the SonicDisc @param byteToSend The byte to be sent */ void sendData(uint8_t byteToSend) { Wire.beginTransmission(SONIC_DISC_I2C_ADDRESS); Wire.write(byteToSend); Wire.endTransmission(SONIC_DISC_I2C_ADDRESS); } /** ISR that raises a flag whenever SonicDisc is ready to transmit new data. */ void newSonicDiscData() { newData = true; } /* Adds the specified i2c packet in the buffer to be sorted later. */ void addInputToFilterBuffer(uint8_t i2cInput[], const uint8_t [MASK] ) { // Copy the whole packet (except error code) in the specified row of the buffer for (int i = 0, j = 1; i < NUM_OF_SENSORS; i++, j++) { filterBuffer[ [MASK] ][i] = i2cInput[j]; } } /* Sorts the measurements of each sensor for every cycle of measurements. */ void sortMeasurements() { // For each sensor for (int s = 0; s < NUM_OF_SENSORS; s++) { // Use bubble sort to sort all measurements throughout the cycle for (int i = 0; i < MEASUREMENTS_TO_FILTER - 1; i++) { for (int j = 0; j < MEASUREMENTS_TO_FILTER - i - 1; j++) { if (filterBuffer[j][s] > filterBuffer[j + 1][s]) { uint8_t toSwap = filterBuffer[j][s]; filterBuffer[j][s] = filterBuffer[j + 1][s]; filterBuffer[j + 1][s] = toSwap; } } } } } /* Filter measurements depending on the variance. If variance is too high for a MEASUREMENTS_TO_FILTER measurements of a sensor then these measurements are disregarded. Otherwise the mean value is chosen. */ void filterMeasurements() { // Go through all the measurements taken for each sensor for (int i = 0; i < NUM_OF_SENSORS; i++) { // Calculate the variance across the different measurements // by subtracting the first and the last element // of the *sorted* measurement cycle. int variance = filterBuffer[0][i] - filterBuffer[MEASUREMENTS_TO_FILTER - 1][i]; if (abs(variance) > VARIANCE_THRESHOLD) { filteredMeasurements[i] = 0; } else { filteredMeasurements[i] = filterBuffer[MEASUREMENTS_TO_FILTER / 2][i]; } } } void setup() { Wire.begin(); Serial.begin(9600); attachInterrupt(digitalPinToInterrupt(INT_PIN), newSonicDiscData, RISING); Serial.println(""Requesting packet from SonicDisc""); uint8_t dummyInput[I2C_PACKET_SIZE] = {0}; // A throw-away array // Do not proceed unless the SonicDisc is in ""MEASURING"" state while (requestPacket(dummyInput, I2C_PACKET_SIZE) == IN_STANDBY) { Serial.println(""Setting state to MEASURING""); sendData(STATE_TO_MEASURING); } Serial.println(""Communication is established and SonicDisc is measuring distances""); car.begin(); } void loop() { if (newData) { newData = false; // Indicate that we have read the latest data uint8_t sonicDiscInput[I2C_PACKET_SIZE] = {0}; // Get the I2C packet I2C_ERROR_CODE ret = requestPacket(sonicDiscInput, I2C_PACKET_SIZE); // Now sonicDiscInput contains the latest measurements from the sensors. // However we need to make sure that the data is also of good quality // Process the packet only if it is a valid one if (ret == NO_ERROR) { addInputToFilterBuffer(sonicDiscInput, filterIndex); // When we have filled up the filter buffer, time to filter the measurements if (filterIndex + 1 == MEASUREMENTS_TO_FILTER) { // For each measurement sortMeasurements(); filterMeasurements(); // Indicate the the measurements are filtered newFilteredMeasurements = true; } // Move along the index filterIndex = (filterIndex + 1) % MEASUREMENTS_TO_FILTER; } } if (newFilteredMeasurements) { newFilteredMeasurements = false; // Now that the measurements are filtered, let's determine where to turn if (filteredMeasurements[6] != 0 && filteredMeasurements[6] < distanceThreshold) { // If the obstacle is in the front, stop rotating car.stop(); } else { int rotation = 0; // The side to rotate. Plus is clockwise. for (int i = 0; i < NUM_OF_SENSORS; i++) { if (filteredMeasurements[i] == 0) { // Ignore the measurement if it is 0 (error value) continue; } else if (filteredMeasurements[i] < distanceThreshold) { // There is an obstacle nearby if (i < 6 && i > 2) { rotation--; } else if (i > 6 || i <= 2) { rotation++; } } } if (rotation > 0) { // Rotate clockwise car.setMotorSpeed(motorSpeed, -motorSpeed); } else if (rotation < 0) { // Rotate counter clockwise car.setMotorSpeed(-motorSpeed, motorSpeed); } else { car.stop(); } } } } ",bufferIndex 224,"// // Histogram.cpp // VINWidget // // Created by ___saradhi___ on 30/11/11. // Copyright 2011 ___technolabssoftware___. All rights reserved. // #include #include #include #include #include #include namespace zxing { using namespace std; const int LUMINANCE_BITS = 5; const int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS; const int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS; const int BLOCK_SIZE_POWER = 3; const int BLOCK_SIZE = 1 << BLOCK_SIZE_POWER; //const int BLOCK_SIZE_MASK = BLOCK_SIZE - 1; const int MINIMUM_DIMENSION = BLOCK_SIZE * 5; static const int MID_SHADE_REMOVAL_HANDLER = 1; //static const int HIGH_SHADE_REMOVAL_HANDLER = 2; Histogram::Histogram(Ref source) : Binarizer(source), cached_matrix_(NULL),cached_matrix_2(NULL), cached_row_(NULL), cached_row_num_(-1) { try { binarizeEntireImage(); binarizeEntireImage2(); } catch (IllegalArgumentException re) { throw new IllegalArgumentException(""Cannot binarize the image.""); } } Histogram::~Histogram() { } Ref Histogram::getBlackRow(int y, Ref row) { if (y == cached_row_num_) { if (cached_row_ != NULL) { return cached_row_; } else { throw IllegalArgumentException(""Too little dynamic range in luminance""); } } vector histogram(LUMINANCE_BUCKETS, 0); LuminanceSource& source = *getLuminanceSource(); int width = source.getWidth(); if (row == NULL || static_cast(row->getSize()) < width) { row = new BitArray(width); } else { row->clear(); } //TODO(flyashi): cache this instead of allocating and deleting per row unsigned char* row_pixels = NULL; try { row_pixels = new unsigned char[width]; row_pixels = source.getRow(y, row_pixels); for (int x = 0; x < width; x++) { histogram[row_pixels[x] >> LUMINANCE_SHIFT]++; } int blackPoint = estimate(histogram) << LUMINANCE_SHIFT; BitArray& array = *row; int left = row_pixels[0]; int center = row_pixels[1]; for (int x = 1; x < width - 1; x++) { int right = row_pixels[x + 1]; // A simple -1 4 -1 box filter with a weight of 2. int luminance = ((center << 2) - left - right) >> 1; if (luminance < blackPoint) { array.set(x); } left = center; center = right; } cached_row_ = row; cached_row_num_ = y; delete [] row_pixels; return row; } catch (IllegalArgumentException const& iae) { // Cache the fact that this row failed. cached_row_ = NULL; cached_row_num_ = y; delete [] row_pixels; throw iae; } } Ref Histogram::getBlackMatrix() { if (cached_matrix_ != NULL) { return cached_matrix_; } // Faster than working with the reference LuminanceSource& source = *getLuminanceSource(); int width = source.getWidth(); int height = source.getHeight(); vector histogram(LUMINANCE_BUCKETS, 0); // Quickly calculates the histogram by sampling four rows from the image. // This proved to be more robust on the blackbox tests than sampling a // diagonal as we used to do. ArrayRef ref (width); unsigned char* row = &ref[0]; for (int y = 1; y < 5; y++) { int rownum = height * y / 5; int right = (width << 2) / 5; row = source.getRow(rownum, row); for (int x = width / 5; x < right; x++) { histogram[row[x] >> LUMINANCE_SHIFT]++; } } int blackPoint = estimate(histogram) << LUMINANCE_SHIFT; Ref matrix_ref(new BitMatrix(width, height)); BitMatrix& matrix = *matrix_ref; for (int y = 0; y < height; y++) { row = source.getRow(y, row); for (int x = 0; x < width; x++) { if (row[x] <= blackPoint) matrix.set(x, y); } } cached_matrix_ = matrix_ref; // delete [] row; return matrix_ref; } int Histogram::estimate(vector &histogram) { int numBuckets = histogram.size(); int maxBucketCount = 0; // Find tallest peak in histogram int firstPeak = 0; int firstPeakSize = 0; for (int i = 0; i < numBuckets; i++) { if (histogram[i] > firstPeakSize) { firstPeak = i; firstPeakSize = histogram[i]; } if (histogram[i] > maxBucketCount) { maxBucketCount = histogram[i]; } } // Find second-tallest peak -- well, another peak that is tall and not // so close to the first one int secondPeak = 0; int [MASK] = 0; for (int i = 0; i < numBuckets; i++) { int distanceToBiggest = i - firstPeak; // Encourage more distant second peaks by multiplying by square of distance int score = histogram[i] * distanceToBiggest * distanceToBiggest; if (score > [MASK] ) { secondPeak = i; [MASK] = score; } } // Put firstPeak first if (firstPeak > secondPeak) { int temp = firstPeak; firstPeak = secondPeak; secondPeak = temp; } // Kind of arbitrary; if the two peaks are very close, then we figure there is // so little dynamic range in the image, that discriminating black and white // is too error-prone. // Decoding the image/line is either pointless, or may in some cases lead to // a false positive for 1D formats, which are relatively lenient. // We arbitrarily say ""close"" is // ""<= 1/16 of the total histogram buckets apart"" if (secondPeak - firstPeak <= numBuckets >> 4) { throw IllegalArgumentException(""Too little dynamic range in luminance""); } // Find a valley between them that is low and closer to the white peak int bestValley = secondPeak - 1; int bestValleyScore = -1; for (int i = secondPeak - 1; i > firstPeak; i--) { int fromFirst = i - firstPeak; // Favor a ""valley"" that is not too close to either peak -- especially not // the black peak -- and that has a low value of course int score = fromFirst * fromFirst * (secondPeak - i) * (maxBucketCount - histogram[i]); if (score > bestValleyScore) { bestValley = i; bestValleyScore = score; } } return bestValley; } Ref Histogram::createBinarizer(Ref source) { return Ref (new Histogram(source)); } Ref Histogram::getBlackRowHybrid(int y, Ref row, int binarizerLevel) { if (binarizerLevel == MID_SHADE_REMOVAL_HANDLER) { binarizeEntireImage2(); return cached_matrix_2->getRow(y, row); } else { binarizeEntireImage(); return cached_matrix_->getRow(y, row); } } void Histogram::binarizeEntireImage() { if (cached_matrix_ == NULL) { Ref source = getLuminanceSource(); if (source->getWidth() >= MINIMUM_DIMENSION && source->getHeight() >= MINIMUM_DIMENSION) { unsigned char* luminances = source->getMatrix(); //unsigned char* outluminances = source->getMatrix(); int width = source->getWidth(); int height = source->getHeight(); zxing::ImageProcessing img ; img.HandleImage(luminances, width, height); int subWidth = width >> 3; if (width & 0x07) { subWidth++; } int subHeight = height >> 3; if (height & 0x07) { subHeight++; } int *blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width, height); cached_matrix_.reset(new BitMatrix(width,height)); calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints, cached_matrix_); delete [] blackPoints; delete [] luminances; } else { // If the image is too small, fall back to the global histogram approach. cached_matrix_.reset(Histogram::getBlackMatrix()); } } } void Histogram::calculateThresholdForBlock(unsigned char* luminances, int subWidth, int subHeight, int width, int height, int blackPoints[], Ref matrix) { for (int y = 0; y < subHeight; y++) { int yoffset = y << BLOCK_SIZE_POWER; if (yoffset + BLOCK_SIZE >= height) { yoffset = height - BLOCK_SIZE; } for (int x = 0; x < subWidth; x++) { int xoffset = x << BLOCK_SIZE_POWER; if (xoffset + BLOCK_SIZE >= width) { xoffset = width - BLOCK_SIZE; } int left = (x > 1) ? x : 2; left = (left < subWidth - 2) ? left : subWidth - 3; int top = (y > 1) ? y : 2; top = (top < subHeight - 2) ? top : subHeight - 3; int sum = 0; for (int z = -2; z <= 2; z++) { int *blackRow = &blackPoints[(top + z) * subWidth]; sum += blackRow[left - 2]; sum += blackRow[left - 1]; sum += blackRow[left]; sum += blackRow[left + 1]; sum += blackRow[left + 2]; } int average = sum / 25; threshold8x8Block(luminances, xoffset, yoffset, average, width, matrix); } } } void Histogram::threshold8x8Block(unsigned char* luminances, int xoffset, int yoffset, int threshold, int stride, Ref matrix) { for (int y = 0, offset = yoffset * stride + xoffset; y < BLOCK_SIZE; y++, offset += stride) { for (int x = 0; x < BLOCK_SIZE; x++) { int pixel = luminances[offset + x] & 0xff; if (pixel <= threshold) { matrix->set(xoffset + x, yoffset + y); } } } } namespace { inline int getBlackPointFromNeighbors(int* blackPoints, int subWidth, int x, int y) { return (blackPoints[(y-1)*subWidth+x] + 2*blackPoints[y*subWidth+x-1] + blackPoints[(y-1)*subWidth+x-1]) >> 2; } } int* Histogram::calculateBlackPoints(unsigned char* luminances, int subWidth, int subHeight, int width, int height) { int *blackPoints = new int[subHeight * subWidth]; for (int y = 0; y < subHeight; y++) { int yoffset = y << BLOCK_SIZE_POWER; if (yoffset + BLOCK_SIZE >= height) { yoffset = height - BLOCK_SIZE; } for (int x = 0; x < subWidth; x++) { int xoffset = x << BLOCK_SIZE_POWER; if (xoffset + BLOCK_SIZE >= width) { xoffset = width - BLOCK_SIZE; } int sum = 0; int min = 0xFF; int max = 0; for (int yy = 0, offset = yoffset * width + xoffset; yy < BLOCK_SIZE; yy++, offset += width) { for (int xx = 0; xx < BLOCK_SIZE; xx++) { int pixel = luminances[offset + xx] & 0xFF; sum += pixel; if (pixel < min) { min = pixel; } if (pixel > max) { max = pixel; } } } int average = sum >> 6; if (max - min <= 24) { average = min >> 1; if (y > 0 && x > 0) { int bp = getBlackPointFromNeighbors(blackPoints, subWidth, x, y); if (min < bp) { average = bp; } } } blackPoints[y * subWidth + x] = average; } } return blackPoints; } // binarizer - 3 .. created on 13-02-2012 // // void Histogram::binarizeEntireImage2() { if (cached_matrix_2 == NULL) { Ref source = getLuminanceSource(); if (source->getWidth() >= MINIMUM_DIMENSION && source->getHeight() >= MINIMUM_DIMENSION) { unsigned char* luminances = source->getMatrix(); //unsigned char* outluminances = source->getMatrix(); int width = source->getWidth(); int height = source->getHeight(); zxing::ImageProcessing img ; img.HandleImage2(luminances, width, height); int subWidth = width >> 3; if (width & 0x07) { subWidth++; } int subHeight = height >> 3; if (height & 0x07) { subHeight++; } int *blackPoints = calculateBlackPoints2(luminances, subWidth, subHeight, width, height); cached_matrix_2.reset(new BitMatrix(width,height)); calculateThresholdForBlock2(luminances, subWidth, subHeight, width, height, blackPoints, cached_matrix_2); delete [] blackPoints; delete [] luminances; } else { // If the image is too small, fall back to the global histogram approach. cached_matrix_2.reset(Histogram::getBlackMatrix()); } } } int* Histogram::calculateBlackPoints2(unsigned char* luminances, int subWidth, int subHeight, int width, int height) { int *blackPoints = new int[subHeight * subWidth]; for (int y = 0; y < subHeight; y++) { int yoffset = y << BLOCK_SIZE_POWER; if (yoffset + BLOCK_SIZE >= height) { yoffset = height - BLOCK_SIZE; } for (int x = 0; x < subWidth; x++) { int xoffset = x << BLOCK_SIZE_POWER; if (xoffset + BLOCK_SIZE >= width) { xoffset = width - BLOCK_SIZE; } int sum = 0; int min = 0xFF; int max = 0; for (int yy = 0, offset = yoffset * width + xoffset; yy < BLOCK_SIZE; yy++, offset += width) { for (int xx = 0; xx < BLOCK_SIZE; xx++) { int pixel = luminances[offset + xx] & 0xFF; sum += pixel; if (pixel < min) { min = pixel; } if (pixel > max) { max = pixel; } } } int average = sum >> 6; int average2 = average; if (max - min <= 24) { average = max == 0 ? 1 : (int) (min * 0.3125f); average2 = (int) (min * 0.3125f); if (y > 0 && x > 0) { int bp = getBlackPointFromNeighbors(blackPoints, subWidth, x, y); if (min < bp) { average2 = bp; } } } blackPoints[y * subWidth + x] = (average + average2) >> 1; } } return blackPoints; } void Histogram::calculateThresholdForBlock2(unsigned char* luminances, int subWidth, int subHeight, int width, int height, int blackPoints[], Ref matrix) { for (int y = 0; y < subHeight; y++) { int yoffset = y << BLOCK_SIZE_POWER; if (yoffset + BLOCK_SIZE >= height) { yoffset = height - BLOCK_SIZE; } for (int x = 0; x < subWidth; x++) { int xoffset = x << BLOCK_SIZE_POWER; if (xoffset + BLOCK_SIZE >= width) { xoffset = width - BLOCK_SIZE; } int left = (x > 1) ? x : 2; left = (left < subWidth - 2) ? left : subWidth - 3; int top = (y > 1) ? y : 2; top = (top < subHeight - 2) ? top : subHeight - 3; int sum = 0; for (int z = -2; z <= 2; z++) { int *blackRow = &blackPoints[(top + z) * subWidth]; sum += blackRow[left - 2]; sum += blackRow[left - 1] + 3.25; sum += blackRow[left]; sum += blackRow[left + 1]; sum += blackRow[left + 2]; } int average = sum / 30; if (average > 255) average = (int) (average * 0.7125f); threshold8x8Block(luminances, xoffset, yoffset, average, width, matrix); } } } } // namespace VIN ",secondPeakScore 225,"/* BMFont example implementation with Kerning, for C++ and OpenGL 2.0 This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to */ #include #include ""sys_gl.h"" #include #include #include #include ""log.h"" #include // for cerr //For CheckOpenGLError StringStream #include //For simple shader code #include #include #include // Required OpenGL Libraries, placed here to make it easier #pragma comment(lib, ""opengl32.lib"") #pragma comment(lib, ""glu32.lib"") //OpenGL Globals for context HDC hDC; HGLRC hRC; #pragma warning (disable : 4996) constexpr auto PI = 3.14159265358979323846; // Code below from https://blog.nobel-joergensen.com/2013/01/29/debugging-opengl-using-glgeterror/ void CheckGLError(const char* file, int line) { GLenum err(glGetError()); while (err != GL_NO_ERROR) { std::string error; switch (err) { case GL_INVALID_OPERATION: error = ""INVALID_OPERATION""; break; case GL_INVALID_ENUM: error = ""INVALID_ENUM""; break; case GL_INVALID_VALUE: error = ""INVALID_VALUE""; break; case GL_OUT_OF_MEMORY: error = ""OUT_OF_MEMORY""; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = ""INVALID_FRAMEBUFFER_OPERATION""; break; } wrlog(""OpenGL Error: %s in %s file at line %d "", error.c_str(), file, line); err = glGetError(); } } void CheckGLError2() { GLenum err(glGetError()); while (err != GL_NO_ERROR) { std::string error; err = glGetError(); switch (err) { case GL_INVALID_OPERATION: error = ""INVALID_OPERATION""; break; case GL_INVALID_ENUM: error = ""INVALID_ENUM""; break; case GL_INVALID_VALUE: error = ""INVALID_VALUE""; break; case GL_OUT_OF_MEMORY: error = ""OUT_OF_MEMORY""; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = ""INVALID_FRAMEBUFFER_OPERATION""; break; } if (err != GL_NO_ERROR) wrlog(""OpenGL Error: %s "", error.c_str()); } } void CheckGLVersionSupport() { const char* version; int major, minor; version = (char*)glGetString(GL_VERSION); sscanf(version, ""%d.%d"", &major, &minor); wrlog(""OpenGl Version supported %d.%d"", major, minor); if (major < 2) { //MessageBox(NULL, ""This program WILL not work, your supported opengl version is less then 2.0"", ""OpenGL version warning"", MB_ICONERROR | MB_OK); } } //======================================================================== // Setup and OpenGl Ortho 2D Window, Depreciated OGL 1.0-2.0 //======================================================================== void ViewOrtho(int width, int height) { glViewport(0, 0, width, height); // Set Up An Ortho View glMatrixMode(GL_PROJECTION); // Select Projection glLoadIdentity(); // Reset The Matrix glOrtho(0, width-1, height-1, 0, -1, 1); // Select Ortho 2D Mode DirectX style(640x480) glMatrixMode(GL_MODELVIEW); // Select Modelview Matrix glLoadIdentity(); // Reset The Matrix } //======================================================================== // Resize OpenGL Window //======================================================================== void OnResize(GLsizei width, GLsizei height) { if (height == 0) // Prevent A Divide By Zero By height = 1; // Making Height Equal One SCREEN_W = width; // Screen Width SCREEN_H = height; // Screen Height ViewOrtho(width, height); } //======================================================================== // Enable Opengl Code, currently depreciated 2.0 only //======================================================================== int OpenGL2Enable() { PIXELFORMATDESCRIPTOR pfd; int format; // get the device context (DC) hDC = GetDC(win_get_window()); // set the pixel format for the DC ZeroMemory(&pfd, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 16; pfd.iLayerType = PFD_MAIN_PLANE; format = ChoosePixelFormat(hDC, &pfd); SetPixelFormat(hDC, format, &pfd); // create and enable the render context (RC) hRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hRC); //Enable GLEW GLenum error = glewInit(); // Enable GLEW if (error != GLEW_OK) // If GLEW fails { wrlog(""Glew Init Failed""); return false; } wrlog(""OpenGL %s, GLSL %s\n"", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); return true; } //======================================================================== // Enable Opengl 3/4 Code. //======================================================================== int OpenGL3Enable() { hDC = GetDC(win_get_window()); PIXELFORMATDESCRIPTOR pfd; // Create a new PIXELFORMATDESCRIPTOR (PFD) memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); // Clear our PFD pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); // Set the size of the PFD to the size of the class pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; // Enable double buffering, opengl support and drawing to a window pfd.iPixelType = PFD_TYPE_RGBA; // Set our application to use RGBA pixels pfd.cColorBits = 32; // Give us 32 bits of color information (the higher, the more colors) pfd.cDepthBits = 32; // Give us 32 bits of depth information (the higher, the more depth levels) pfd.iLayerType = PFD_MAIN_PLANE; // Set the layer of the PFD int nPixelFormat = ChoosePixelFormat(hDC, &pfd); // Check if our PFD is valid and get a pixel format back if (nPixelFormat == 0) // If it fails return false; int bResult = SetPixelFormat(hDC, nPixelFormat, &pfd); // Try and set the pixel format based on our PFD if (!bResult) // If it fails return false; HGLRC tempOpenGLContext = wglCreateContext(hDC); // Create an OpenGL 2.1 context for our device context wglMakeCurrent(hDC, tempOpenGLContext); // Make the OpenGL 2.1 context current and active glewExperimental = true; GLenum error = glewInit(); // Enable GLEW if (error != GLEW_OK) // If GLEW fails { wrlog(""Glew Init Failed""); return false; } const int attributes[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, // Set the MAJOR version of OpenGL to 3 WGL_CONTEXT_MINOR_VERSION_ARB, 2, // Set the MINOR version of OpenGL to 2 WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, // Set our OpenGL context to be forward compatible WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB , //Set the compatibility 0 }; if (wglewIsSupported(""WGL_ARB_create_context"") == 1) { // If the OpenGL 3.x context creation extension is available hRC = wglCreateContextAttribsARB(hDC, NULL, attributes); // Create and OpenGL 3.x context based on the given attributes wglMakeCurrent(NULL, NULL); // Remove the temporary context from being active wglDeleteContext(tempOpenGLContext); // Delete the temporary OpenGL 2.1 context wglMakeCurrent(hDC, hRC); // Make our OpenGL 3.0 context current } else { hRC = tempOpenGLContext; // If we didn't have support for OpenGL 3.x and up, use the OpenGL 2.1 context } int glVersion[2] = { -1, -1 }; // Set some default values for the version glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); // Get back the OpenGL MAJOR version we are using glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); // Get back the OpenGL MAJOR version we are using wrlog(""Gl version %x:%x"", glVersion[0], glVersion[1]); wrlog(""OpenGL %s, GLSL %s\n"", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); if (GLEW_EXT_framebuffer_multisample) { //Example of checking extensions } return true; // We have successfully created a context, return true }; //======================================================================== // Disable and release the OpenGL Context //======================================================================== void OpenGLShutDown() { wglMakeCurrent(NULL, NULL); wglDeleteContext(hRC); ReleaseDC(win_get_window(), hDC); } //======================================================================== // Swap GL Buffers //======================================================================== void GLSwapBuffers() { SwapBuffers(hDC); } //======================================================================== // Enable / Disable vSync //======================================================================== void osWaitVsync(bool enable) { if (enable == TRUE) { wglSwapIntervalEXT(1); } else { wglSwapIntervalEXT(0); } } // Really simple shader loader copied from the OpenGL examples on the web GLuint LoadShaders(const char* vertex_file, const char* fragment_file, bool file_or_char) { // Create the shaders GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); std::string VertexShaderCode; std::string FragmentShaderCode; // If these are file names, read the data in. // Otherwise, use these directly. if (file_or_char) { // Read the Vertex Shader code from the file std::ifstream VertexShaderStream(vertex_file, std::ios::in); if (VertexShaderStream.is_open()) { std::string Line = """"; while (getline(VertexShaderStream, Line)) VertexShaderCode += ""\n"" + Line; VertexShaderStream.close(); } else { wrlog(""Impossible to open %s. Are you in the right directory ? Don't forget to read the FAQ !\n"", vertex_file); return 0; } // Read the Fragment Shader code from the file std::ifstream FragmentShaderStream(fragment_file, std::ios::in); if (FragmentShaderStream.is_open()) { std::string Line = """"; while (getline(FragmentShaderStream, Line)) FragmentShaderCode += ""\n"" + Line; FragmentShaderStream.close(); } else { wrlog(""Impossible to open %s. Are you in the right directory ? Don't forget to read the FAQ !\n"", fragment_file); return 0; } } else { VertexShaderCode = vertex_file; FragmentShaderCode = fragment_file; } GLint Result = GL_FALSE; int [MASK] ; // Compile Vertex Shader wrlog(""Compiling vertex shader""); char const* VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(VertexShaderID, 1, &VertexSourcePointer, NULL); glCompileShader(VertexShaderID); // Check Vertex Shader glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, & [MASK] ); if ( [MASK] > 0) { std::vector VertexShaderErrorMessage( [MASK] + 1); glGetShaderInfoLog(VertexShaderID, [MASK] , NULL, &VertexShaderErrorMessage[0]); wrlog(""%s\n"", &VertexShaderErrorMessage[0]); } // Compile Fragment Shader wrlog(""Compiling fragment shader""); char const* FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, NULL); glCompileShader(FragmentShaderID); // Check Fragment Shader glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, & [MASK] ); if ( [MASK] > 0) { std::vector FragmentShaderErrorMessage( [MASK] + 1); glGetShaderInfoLog(FragmentShaderID, [MASK] , NULL, &FragmentShaderErrorMessage[0]); wrlog(""%s\n"", &FragmentShaderErrorMessage[0]); } // Link the program wrlog(""Linking program\n""); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); // Check the program glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, & [MASK] ); if ( [MASK] > 0) { std::vector ProgramErrorMessage( [MASK] + 1); glGetProgramInfoLog(ProgramID, [MASK] , NULL, &ProgramErrorMessage[0]); wrlog(""%s\n"", &ProgramErrorMessage[0]); } glDetachShader(ProgramID, VertexShaderID); glDetachShader(ProgramID, FragmentShaderID); glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); GLenum err; while ((err = glGetError()) != GL_NO_ERROR) { wrlog(""GL Error in shader processing %d"", err); //Process/log the error. } return ProgramID; } bool ShaderIsValid(GLuint program) { glValidateProgram(program); int params = -1; glGetProgramiv(program, GL_VALIDATE_STATUS, ¶ms); wrlog(""program %i GL_VALIDATE_STATUS = %i\n"", program, params); if (GL_TRUE != params) { //_print_programme_info_log(programme); return false; } return true; }",InfoLogLength 226,"#ifndef BOOPY_AI_H #define BOOPY_AI_H #include ""../AI.h"" /** * Goal of the AI: * Play the moves that create the most change in board state. * Play the moves that boop the most pieces. */ class Boopy_AI : public AI { public: Boopy_AI() { } std::string think(std::queue moves, Timer& timer) override; private: Boop::PieceType board[Boop::SIZE][Boop::SIZE]; // Count the number of different squares from the current board state int board_difference(Boop* future); }; std::string Boopy_AI::think(std::queue moves, Timer& timer) { std::string best_move; // Check timer.times_up() between loops as to not go over the time limit int boops; int [MASK] = -1; Boop* future; game->clone_board(board); while(!moves.empty()) { future = game->clone(); future -> make_move(moves.front( )); boops = board_difference(future); delete future; if(boops > [MASK] ) { [MASK] = boops; best_move = moves.front(); } moves.pop( ); if(timer.times_up()) { return best_move; } } return best_move; } int Boopy_AI::board_difference(Boop* future) { int c = 0; Boop::PieceType future_board[6][6]; future->clone_board(future_board); for(int y = 0; y < Boop::SIZE; ++y) { for(int x = 0; x < Boop::SIZE; ++x) { if(board[x][y] != future_board[x][y]) { ++c; } } } return c; } #endif",most_boops 227,"#include #include #include #include #include #include #include #include #include #include // For using std::string with pybind11 #include #include #include #include #include // Function to generate a random AES key of the specified length (in bytes) and return it as a hex string std::string generate_random_key() { std::vector key(16); if (!RAND_bytes(key.data(), 16)) { throw std::runtime_error(""Error: Random key generation failed.""); } // Convert key to hex string std::ostringstream oss; for (unsigned char c : key) { oss << std::hex << std::setw(2) << std::setfill('0') << (int)c; } return oss.str(); } // Convert hex string to byte vector std::vector hex_string_to_bytes(const std::string& hex_str) { std::vector bytes; for (size_t i = 0; i < hex_str.length(); i += 2) { std::string byte_string = hex_str.substr(i, 2); unsigned char byte = (unsigned char) strtol(byte_string.c_str(), nullptr, 16); bytes.push_back(byte); } return bytes; } bool aes_encrypt_file(const std::string& input_file, const std::string& hex_key) { // Convert key from hex string to byte vector std::vector key = hex_string_to_bytes(hex_key); // Open input file std::ifstream infile(input_file, std::ios::binary); if (!infile.is_open()) { std::cerr << ""Error: Cannot open input file.\n""; return false; } // Define the path for the temp folder relative to the executable location std::filesystem::path [MASK] = std::filesystem::current_path() / ""temp""; std::filesystem::create_directory( [MASK] ); // Construct the output file path in the temp directory with .enc extension std::filesystem::path input_path(input_file); std::filesystem::path output_path = [MASK] / (input_path.filename().string() + "".enc""); // Open output file for encrypted content std::ofstream outfile(output_path, std::ios::binary); if (!outfile.is_open()) { std::cerr << ""Error: Cannot open output file.\n""; return false; } // Initialize context for encryption (AES-128-ECB) EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), nullptr, key.data(), nullptr); const int buffer_size = 4096; unsigned char buffer[buffer_size]; // Read buffer unsigned char cipher_buffer[buffer_size + AES_BLOCK_SIZE]; // Ciphertext buffer int len = 0, cipher_len = 0; // Read from input file and encrypt in chunks while (infile.good()) { infile.read(reinterpret_cast(buffer), buffer_size); int read_len = infile.gcount(); // Encrypt the data read from the file if (!EVP_EncryptUpdate(ctx, cipher_buffer, &len, buffer, read_len)) { std::cerr << ""Error: Encryption failed.\n""; EVP_CIPHER_CTX_free(ctx); return false; } outfile.write(reinterpret_cast(cipher_buffer), len); } // Finalize encryption if (!EVP_EncryptFinal_ex(ctx, cipher_buffer, &cipher_len)) { std::cerr << ""Error: Final encryption step failed.\n""; EVP_CIPHER_CTX_free(ctx); return false; } outfile.write(reinterpret_cast(cipher_buffer), cipher_len); // Cleanup EVP_CIPHER_CTX_free(ctx); infile.close(); outfile.close(); return true; } bool aes_decrypt_file(const std::string& input_file, const std::string& output_file, const std::string& hex_key) { // Convert key from hex string to byte vector std::vector key = hex_string_to_bytes(hex_key); // Open input file for decryption std::ifstream infile(input_file, std::ios::binary); if (!infile.is_open()) { std::cerr << ""Error: Cannot open input file for decryption.\n""; return false; } // Open output file for decrypted content std::ofstream outfile(output_file, std::ios::binary); if (!outfile.is_open()) { std::cerr << ""Error: Cannot open output file for decryption.\n""; return false; } // Initialize context for decryption (AES-128-ECB) EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); EVP_DecryptInit_ex(ctx, EVP_aes_128_ecb(), nullptr, key.data(), nullptr); const int buffer_size = 4096; unsigned char buffer[buffer_size]; // Read buffer unsigned char plain_buffer[buffer_size + AES_BLOCK_SIZE]; // Plaintext buffer int len = 0, plain_len = 0; // Read from input file and decrypt in chunks while (infile.good()) { infile.read(reinterpret_cast(buffer), buffer_size); int read_len = infile.gcount(); // Decrypt the data read from the file if (!EVP_DecryptUpdate(ctx, plain_buffer, &len, buffer, read_len)) { std::cerr << ""Error: Decryption failed.\n""; EVP_CIPHER_CTX_free(ctx); return false; } outfile.write(reinterpret_cast(plain_buffer), len); } // Finalize decryption if (!EVP_DecryptFinal_ex(ctx, plain_buffer, &plain_len)) { std::cerr << ""Error: Final decryption step failed.\n""; EVP_CIPHER_CTX_free(ctx); return false; } outfile.write(reinterpret_cast(plain_buffer), plain_len); // Cleanup EVP_CIPHER_CTX_free(ctx); infile.close(); outfile.close(); return true; } std::string base64_encode(const std::vector& input) { BIO* b64 = BIO_new(BIO_f_base64()); BIO* bmem = BIO_new(BIO_s_mem()); b64 = BIO_push(b64, bmem); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // No newlines in base64 output BIO_write(b64, input.data(), input.size()); BIO_flush(b64); BUF_MEM* bptr; BIO_get_mem_ptr(b64, &bptr); std::string output(bptr->data, bptr->length); BIO_free_all(b64); return output; } // Base64 decoding function std::vector base64_decode(const std::string& input) { BIO* b64 = BIO_new(BIO_f_base64()); BIO* bmem = BIO_new_mem_buf(input.data(), input.size()); b64 = BIO_push(b64, bmem); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // No newlines in base64 input std::vector output(input.size()); int decoded_length = BIO_read(b64, output.data(), input.size()); output.resize(decoded_length); BIO_free_all(b64); return output; } PYBIND11_MODULE(pybind_aes, m) { m.def(""aes_file_encrypt"", &aes_encrypt_file, """"); m.def(""aes_file_decrypt"", &aes_decrypt_file, """"); m.def(""aes_key_generate"", &generate_random_key, ""Generate random 16 bytes key""); }",temp_folder 228," #include ""BaseScene.h"" #include ""../ui/BaseGuiScreen.h"" BaseScene::BaseScene(const Ogre::String [MASK] , HappyRoll2Application *application, BaseGuiScreen *gui) : ogre_root(application->ogre_root), ogre_window(application->ogre_window), ogre_scene_manager(nullptr), ogre_overlay_system(application->ogre_overlay_system), ogre_viewport(nullptr), gui(gui) { ogre_scene_manager = ogre_root->createSceneManager(Ogre::ST_GENERIC, [MASK] ); } void BaseScene::attach_display() { ogre_viewport = ogre_window->addViewport(this->getCamera(), this->getZOrder()); ogre_viewport->setAutoUpdated(true); ogre_viewport->setBackgroundColour(Ogre::ColourValue(0, 0, 0)); this->getCamera()->setAspectRatio(float(ogre_viewport->getActualWidth()) / float(ogre_viewport->getActualHeight())); ogre_root->addFrameListener(this); ogre_scene_manager->addRenderQueueListener(ogre_overlay_system); gui->show(); } void BaseScene::detach_display() { gui->hide(); ogre_scene_manager->removeRenderQueueListener(ogre_overlay_system); ogre_window->removeViewport(ogre_viewport->getZOrder()); ogre_root->removeFrameListener(this); } BaseScene::~BaseScene() { ogre_root->destroySceneManager(ogre_scene_manager); delete gui; } bool BaseScene::frameStarted(const Ogre::FrameEvent &evt) { return gui->update(evt.timeSinceLastFrame) && this->update(evt.timeSinceLastFrame); } ",name 229,"#include ""Deserializer.hpp"" namespace oatpp { namespace mariadb { namespace mapping { Deserializer::InData::InData(MYSQL_BIND* pBind, const std::shared_ptr& pTypeResolver) { bind = pBind; typeResolver = pTypeResolver; oid = bind->buffer_type; isNull = (bind->is_null != nullptr && *bind->is_null == 1); } Deserializer::Deserializer() { m_methods.resize(data::mapping::type::ClassId::getClassCount(), nullptr); setDeserializerMethod(data::mapping::type::__class::String::CLASS_ID, &Deserializer::deserializeString); setDeserializerMethod(data::mapping::type::__class::Any::CLASS_ID, &Deserializer::deserializeAny); setDeserializerMethod(data::mapping::type::__class::Boolean::CLASS_ID, &Deserializer::deserializeBoolean); setDeserializerMethod(data::mapping::type::__class::Int8::CLASS_ID, &Deserializer::deserializeInt); setDeserializerMethod(data::mapping::type::__class::UInt8::CLASS_ID, &Deserializer::deserializeInt); setDeserializerMethod(data::mapping::type::__class::Int16::CLASS_ID, &Deserializer::deserializeInt); setDeserializerMethod(data::mapping::type::__class::UInt16::CLASS_ID, &Deserializer::deserializeInt); setDeserializerMethod(data::mapping::type::__class::Int32::CLASS_ID, &Deserializer::deserializeInt); setDeserializerMethod(data::mapping::type::__class::UInt32::CLASS_ID, &Deserializer::deserializeInt); setDeserializerMethod(data::mapping::type::__class::Int64::CLASS_ID, &Deserializer::deserializeInt); setDeserializerMethod(data::mapping::type::__class::UInt64::CLASS_ID, &Deserializer::deserializeInt); setDeserializerMethod(data::mapping::type::__class::Float32::CLASS_ID, &Deserializer::deserializeFloat32); setDeserializerMethod(data::mapping::type::__class::Float64::CLASS_ID, &Deserializer::deserializeFloat64); setDeserializerMethod(data::mapping::type::__class::AbstractObject::CLASS_ID, nullptr); setDeserializerMethod(data::mapping::type::__class::AbstractEnum::CLASS_ID, &Deserializer::deserializeEnum); setDeserializerMethod(data::mapping::type::__class::AbstractVector::CLASS_ID, nullptr); setDeserializerMethod(data::mapping::type::__class::AbstractList::CLASS_ID, nullptr); setDeserializerMethod(data::mapping::type::__class::AbstractUnorderedSet::CLASS_ID, nullptr); setDeserializerMethod(data::mapping::type::__class::AbstractPairList::CLASS_ID, nullptr); setDeserializerMethod(data::mapping::type::__class::AbstractUnorderedMap::CLASS_ID, nullptr); } void Deserializer::setDeserializerMethod(const data::mapping::type::ClassId& classId, DeserializerMethod method) { const v_uint32 id = classId.id; if(id >= m_methods.size()) { m_methods.resize(id + 1, nullptr); } m_methods[id] = method; } oatpp::Void Deserializer::deserialize(const InData& data, const Type* type) const { // OATPP_LOGD(""Deserializer::deserialize()"", ""type=%s, oid=%d, isNull=%d"", type->classId.name, data.oid, data.isNull); auto id = type->classId.id; auto& method = m_methods[id]; if(method) { return (*method)(this, data, type); } auto* interpretation = type->findInterpretation(data.typeResolver->getEnabledInterpretations()); if(interpretation) { return interpretation->fromInterpretation(deserialize(data, interpretation->getInterpretationType())); } throw std::runtime_error(""[oatpp::mariadb::mapping::Deserializer::deserialize()]: "" ""Error. No deserialize method for type '"" + std::string(type->classId.name) + ""'""); } v_int64 Deserializer::deInt(const InData& data) { v_int64 value; switch(data.oid) { case MYSQL_TYPE_BIT: { value = *(uint64_t*) data.bind->buffer; std::memset(data.bind->buffer, 0, sizeof(uint64_t)); return value; } case MYSQL_TYPE_TINY: { value = *(int8_t*) data.bind->buffer; std::memset(data.bind->buffer, 0, sizeof(int8_t)); return value; } case MYSQL_TYPE_SHORT: { value = *(int16_t*) data.bind->buffer; std::memset(data.bind->buffer, 0, sizeof(int16_t)); return value; } case MYSQL_TYPE_LONG: { value = *(int32_t*) data.bind->buffer; std::memset(data.bind->buffer, 0, sizeof(int32_t)); return value; } case MYSQL_TYPE_LONGLONG: { value = *(int64_t*) data.bind->buffer; std::memset(data.bind->buffer, 0, sizeof(int64_t)); return value; } } throw std::runtime_error(""[oatpp::mariadb::mapping::Deserializer::deInt()]: Error. Unknown OID.""); } oatpp::Void Deserializer::deserializeString(const Deserializer* _this, const InData& data, const Type* type) { (void) _this; (void) type; if(data.isNull) { return oatpp::String(); } auto ptr = (const char*) data.bind->buffer; auto size = *data.bind->length; // Use the actual data length oatpp::String value(ptr, size); std::memset(data.bind->buffer, 0, data.bind->buffer_length); return value; } oatpp::Void Deserializer::deserializeFloat32(const Deserializer* _this, const InData& data, const Type* type) { (void) _this; (void) type; if(data.isNull) { return oatpp::Float32(); } float value; switch(data.oid) { case MYSQL_TYPE_LONG: case MYSQL_TYPE_FLOAT: { value = *(float*) data.bind->buffer; std::memset(data.bind->buffer, 0, sizeof(float)); return oatpp::Float32(value); } } throw std::runtime_error(""[oatpp::mariadb::mapping::Deserializer::deserializeFloat32()]: Error. Unknown OID.""); } oatpp::Void Deserializer::deserializeFloat64(const Deserializer* _this, const InData& data, const Type* type) { OATPP_LOGD(""Deserializer"", ""Deserializing Float64 value""); if(data.isNull) { OATPP_LOGD(""Deserializer"", ""Float64 value is null""); return oatpp::Float64(); } double value = 0; switch(data.oid) { case MYSQL_TYPE_TINY: { value = static_cast(*static_cast(data.bind->buffer)); break; } case MYSQL_TYPE_SHORT: { value = static_cast(*static_cast(data.bind->buffer)); break; } case MYSQL_TYPE_LONG: { value = static_cast(*static_cast(data.bind->buffer)); break; } case MYSQL_TYPE_LONGLONG: { value = static_cast(*static_cast(data.bind->buffer)); break; } case MYSQL_TYPE_FLOAT: { value = static_cast(*static_cast(data.bind->buffer)); break; } case MYSQL_TYPE_DOUBLE: { value = *static_cast(data.bind->buffer); break; } default: OATPP_LOGE(""Deserializer"", ""Unsupported buffer type for Float64: %d"", data.oid); throw std::runtime_error(""Unsupported buffer type for Float64: "" + std::to_string(data.oid)); } OATPP_LOGD(""Deserializer"", ""Float64 value: %f"", value); return oatpp::Float64(value); } template oatpp::Void Deserializer::deserializeInt(const Deserializer* _this, const InData& data, const Type* type) { (void) _this; (void) type; if(data.isNull) { OATPP_LOGD(""Deserializer"", ""Int value is null""); return IntWrapper(); } if (std::is_same::value || std::is_same::value) { switch(data.oid) { case MYSQL_TYPE_LONGLONG: { if (data.bind->is_unsigned) { uint64_t value = *static_cast(data.bind->buffer); OATPP_LOGD(""Deserializer"", ""Unsigned Int64 value: %llu"", value); if (std::is_same::value) { return IntWrapper(value); } else { return IntWrapper(static_cast(value)); } } else { int64_t value = *static_cast(data.bind->buffer); OATPP_LOGD(""Deserializer"", ""Signed Int64 value: %lld"", value); if (std::is_same::value) { return IntWrapper(static_cast(value)); } else { return IntWrapper(value); } } } default: { auto value = deInt(data); if (std::is_same::value) { return IntWrapper(static_cast(value)); } else { return IntWrapper(value); } } } } auto value = deInt(data); return IntWrapper((typename IntWrapper::UnderlyingType) value); } // Explicit template instantiations template oatpp::Void Deserializer::deserializeInt(const Deserializer* _this, const InData& data, const Type* type); template oatpp::Void Deserializer::deserializeInt(const Deserializer* _this, const InData& data, const Type* type); template oatpp::Void Deserializer::deserializeInt(const Deserializer* _this, const InData& data, const Type* type); template oatpp::Void Deserializer::deserializeInt(const Deserializer* _this, const InData& data, const Type* type); template oatpp::Void Deserializer::deserializeInt(const Deserializer* _this, const InData& data, const Type* type); template oatpp::Void Deserializer::deserializeInt(const Deserializer* _this, const InData& data, const Type* type); template oatpp::Void Deserializer::deserializeInt(const Deserializer* _this, const InData& data, const Type* type); template oatpp::Void Deserializer::deserializeInt(const Deserializer* _this, const InData& data, const Type* type); oatpp::Void Deserializer::deserializeBoolean(const Deserializer* _this, const InData& data, const Type* type) { (void) _this; (void) type; if(data.isNull) { OATPP_LOGD(""Deserializer"", ""Deserializing null boolean value""); return oatpp::Boolean(); } switch(data.oid) { case MYSQL_TYPE_BIT: { uint64_t value = *static_cast(data.bind->buffer); OATPP_LOGD(""Deserializer"", ""Deserializing BIT value: %llu"", value); return oatpp::Boolean(value != 0); } case MYSQL_TYPE_TINY: { signed char value = *static_cast(data.bind->buffer); OATPP_LOGD(""Deserializer"", ""Deserializing boolean value: %d"", (int)value); return oatpp::Boolean(value != 0); } default: OATPP_LOGD(""Deserializer"", ""Unsupported buffer type: %d"", data.oid); throw std::runtime_error(""[oatpp::mariadb::mapping::Deserializer::deserializeBoolean()]: Error. Unsupported buffer type: "" + std::to_string(data.oid)); } } oatpp::Void Deserializer::deserializeAny(const Deserializer* _this, const InData& inData, const Type* type) { (void) type; if(inData.isNull) { return oatpp::Void(Any::Class::getType()); } const Type* valueType; switch(inData.oid) { case MYSQL_TYPE_TINY: if (inData.bind->is_unsigned) { auto value = *(static_cast(inData.bind->buffer)); if (type == oatpp::Boolean::Class::getType()) { return oatpp::Boolean(value != 0); } return oatpp::UInt8(value); } else { auto value = *(static_cast(inData.bind->buffer)); if (type == oatpp::Boolean::Class::getType()) { return oatpp::Boolean(value != 0); } return oatpp::Int8(value); } case MYSQL_TYPE_SHORT: valueType = oatpp::Int16::Class::getType(); break; case MYSQL_TYPE_LONG: valueType = oatpp::Int32::Class::getType(); break; case MYSQL_TYPE_LONGLONG: valueType = oatpp::Int64::Class::getType(); break; case MYSQL_TYPE_FLOAT: valueType = oatpp::Float32::Class::getType(); break; case MYSQL_TYPE_DOUBLE: valueType = oatpp::Float64::Class::getType(); break; case MYSQL_TYPE_STRING: valueType = oatpp::String::Class::getType(); break; case MYSQL_TYPE_BIT: if (type == oatpp::UInt64::Class::getType()) { return oatpp::UInt64(*static_cast(inData.bind->buffer)); } valueType = oatpp::UInt64::Class::getType(); break; default: throw std::runtime_error(""[oatpp::mariadb::mapping::Deserializer::deserializeAny()]: Error. Unknown OID.""); } auto value = _this->deserialize(inData, valueType); auto [MASK] = std::make_shared(value.getPtr(), value.getValueType()); return oatpp::Void( [MASK] , Any::Class::getType()); } oatpp::Void Deserializer::deserializeEnum(const Deserializer* _this, const InData& data, const Type* type) { auto polymorphicDispatcher = static_cast( type->polymorphicDispatcher ); data::mapping::type::EnumInterpreterError e = data::mapping::type::EnumInterpreterError::OK; const auto& value = _this->deserialize(data, polymorphicDispatcher->getInterpretationType()); const auto& result = polymorphicDispatcher->fromInterpretation(value, e); if(e == data::mapping::type::EnumInterpreterError::OK) { return result; } switch(e) { case data::mapping::type::EnumInterpreterError::CONSTRAINT_NOT_NULL: throw std::runtime_error(""[oatpp::mariadb::mapping::Deserializer::deserializeEnum()]: Error. Enum constraint violated - 'NotNull'.""); default: throw std::runtime_error(""[oatpp::mariadb::mapping::Deserializer::deserializeEnum()]: Error. Can't deserialize Enum.""); } } }}} ",anyHandle 230,"// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include #include #include #include ""Vtop_verilator__Syms.h"" #include ""ibex_pcounts.h"" #include ""ibex_demo_system.h"" #include ""verilated_toplevel.h"" #include ""verilator_memutil.h"" #include ""verilator_sim_ctrl.h"" DemoSystem::DemoSystem(const char *ram_hier_path, int [MASK] ) : _ram(ram_hier_path, [MASK] , 4) {} int DemoSystem::Main(int argc, char **argv) { bool exit_app; int ret_code = Setup(argc, argv, exit_app); if (exit_app) { return ret_code; } Run(); if (!Finish()) { return 1; } return 0; } int DemoSystem::Setup(int argc, char **argv, bool &exit_app) { VerilatorSimCtrl &simctrl = VerilatorSimCtrl::GetInstance(); simctrl.SetTop(&_top, &_top.clk_i, &_top.rst_ni, VerilatorSimCtrlFlags::ResetPolarityNegative); _memutil.RegisterMemoryArea(""ram"", 0x0, &_ram); simctrl.RegisterExtension(&_memutil); exit_app = false; return simctrl.ParseCommandArgs(argc, argv, exit_app); } void DemoSystem::Run() { VerilatorSimCtrl &simctrl = VerilatorSimCtrl::GetInstance(); std::cout << ""Simulation of Ibex Demo System"" << std::endl << ""=============================="" << std::endl << std::endl; simctrl.RunSimulation(); } bool DemoSystem::Finish() { VerilatorSimCtrl &simctrl = VerilatorSimCtrl::GetInstance(); if (!simctrl.WasSimulationSuccessful()) { return false; } // Set the scope to the root scope, the ibex_pcount_string function otherwise // doesn't know the scope itself. Could be moved to ibex_pcount_string, but // would require a way to set the scope name from here, similar to MemUtil. svSetScope(svGetScopeFromName(""TOP.top_verilator.u_ibex_demo_system"")); std::cout << ""\nPerformance Counters"" << std::endl << ""===================="" << std::endl; std::cout << ibex_pcount_string(false); std::ofstream pcount_csv(""ibex_demo_system_pcount.csv""); pcount_csv << ibex_pcount_string(true); return true; } ",ram_size_words 231,"#ifndef RKNNPOOL_H #define RKNNPOOL_H #include ""ThreadPool.hpp"" #include #include #include #include #include // rknnModel模型类, inputType模型输入类型, outputType模型输出类型 template class rknnPool { private: int id; std::mutex idMtx, queueMtx; std::unique_ptr pool; std::queue> futs; std::vector> models; protected: int getModelId(); public: int threadNum; std::string det_model_path; std::string pose_model_path; rknnPool(const std::string det_model_path, const std::string pose_model_path, int threadNum); int init(); // 模型推理/Model inference int put(inputType inputData); // 获取推理结果/Get the results of your inference int get(outputType &outputData); ~rknnPool(); }; template rknnPool::rknnPool( const std::string det_model_path, const std::string pose_model_path, int threadNum) { this->det_model_path = det_model_path; this->pose_model_path = pose_model_path; this->threadNum = threadNum; this->id = 0; } template int rknnPool::init() { try { this->pool = std::make_unique(this->threadNum); for (int i = 0; i < this->threadNum; i++) models.push_back(std::make_shared(this->det_model_path.c_str(),this->pose_model_path.c_str())); } catch (const std::bad_alloc &e) { std::cout << ""Out of memory: "" << e.what() << std::endl; return -1; } // 初始化模型/Initialize the model for (int i = 0, ret = 0; i < threadNum; i++) { ret = models[i]->init(); if (ret != 0) return ret; } return 0; } template int rknnPool::getModelId() { std::lock_guard lock(idMtx); int [MASK] = id % threadNum; if (id == threadNum) { id = 0; } id++; return [MASK] ; } template int rknnPool::put(inputType inputData) { futs.push( pool->submit(&rknnModel::infer, models[this->getModelId()], inputData)); return 0; } template int rknnPool::get(outputType &outputData) { std::lock_guard lock(queueMtx); if (futs.empty() == true) return 1; outputData = futs.front().get(); futs.pop(); return 0; } template rknnPool::~rknnPool() { while (!futs.empty()) { outputType temp = futs.front().get(); futs.pop(); } } #endif",modelId 232,"#include ""SDL2_gfxPrimitives.h"" #include ""application_ui.h"" #include #include #include #include #include #include #include using namespace std; #define EPSILON 0.0001f struct Coords { int x, y; bool operator==(const Coords &other) const { return x == other.x and y == other.y; } }; struct Polygone { std::vector points; }; struct Segment { Coords p1, p2; }; struct Triangle { Coords p1, p2, p3; bool complet = false; }; struct Vertex { Coords point; double angle; bool operator<(const Vertex &other) const { return angle < other.angle; } }; struct Application { int width, height; Coords focus{100, 100}; std::vector polygones; std::vector points; std::vector triangles; std::vector voronoiSeg; }; // changement => trie par x bool compareCoords(Coords point1, Coords point2) { // Si les points x sont égaux, alors on les distingue selon leur point y if (point1.x == point2.x) return point1.y < point2.y; return point1.x < point2.x; } // changement => trie par x bool compareCoordsReverse(Coords point1, Coords point2) { // Si les points x sont égaux, alors on les distingue selon leur point y if (point1.x == point2.x) return point1.y < point2.y; return point1.x > point2.x; } /* Détermine si un point se trouve dans un cercle définit par trois points Retourne, par les paramètres, le centre et le rayon */ bool CircumCircle(float pX, float pY, float x1, float y1, float x2, float y2, float x3, float y3, float *xc, float *yc, float *rsqr) { float m1, m2, mx1, mx2, my1, my2; float dx, dy, drsqr; float fabsy1y2 = fabs(y1 - y2); float fabsy2y3 = fabs(y2 - y3); /* Check for coincident points */ if (fabsy1y2 < EPSILON && fabsy2y3 < EPSILON) return (false); if (fabsy1y2 < EPSILON) { m2 = -(x3 - x2) / (y3 - y2); mx2 = (x2 + x3) / 2.0; my2 = (y2 + y3) / 2.0; *xc = (x2 + x1) / 2.0; *yc = m2 * (*xc - mx2) + my2; } else if (fabsy2y3 < EPSILON) { m1 = -(x2 - x1) / (y2 - y1); mx1 = (x1 + x2) / 2.0; my1 = (y1 + y2) / 2.0; *xc = (x3 + x2) / 2.0; *yc = m1 * (*xc - mx1) + my1; } else { m1 = -(x2 - x1) / (y2 - y1); m2 = -(x3 - x2) / (y3 - y2); mx1 = (x1 + x2) / 2.0; mx2 = (x2 + x3) / 2.0; my1 = (y1 + y2) / 2.0; my2 = (y2 + y3) / 2.0; *xc = (m1 * mx1 - m2 * mx2 + my2 - my1) / (m1 - m2); if (fabsy1y2 > fabsy2y3) { *yc = m1 * (*xc - mx1) + my1; } else { *yc = m2 * (*xc - mx2) + my2; } } dx = x2 - *xc; dy = y2 - *yc; *rsqr = dx * dx + dy * dy; dx = pX - *xc; dy = pY - *yc; drsqr = dx * dx + dy * dy; return ((drsqr - *rsqr) <= EPSILON ? true : false); } void drawPoints(SDL_Renderer *renderer, const std::vector &points) { for (std::size_t i = 0; i < points.size(); i++) { filledCircleRGBA(renderer, points[i].x, points[i].y, 3, 240, 240, 23, SDL_ALPHA_OPAQUE); } } void drawSegments(SDL_Renderer *renderer, const std::vector &segments) { for (std::size_t i = 0; i < segments.size(); i++) { lineRGBA(renderer, segments[i].p1.x, segments[i].p1.y, segments[i].p2.x, segments[i].p2.y, 240, 240, 20, SDL_ALPHA_OPAQUE); } } void drawTriangles(SDL_Renderer *renderer, const std::vector &triangles) { for (std::size_t i = 0; i < triangles.size(); i++) { const Triangle &t = triangles[i]; trigonRGBA(renderer, t.p1.x, t.p1.y, t.p2.x, t.p2.y, t.p3.x, t.p3.y, 0, 240, 160, SDL_ALPHA_OPAQUE); } } void drawCircles(SDL_Renderer *renderer, const std::vector &triangles) { float xC, yC, rC; for (std::size_t i = 0; i < triangles.size(); i++) { const Triangle &t = triangles[i]; CircumCircle(t.p1.x, t.p1.y, t.p1.x, t.p1.y, t.p2.x, t.p2.y, t.p3.x, t.p3.y, &xC, &yC, &rC); circleRGBA(renderer, xC, yC, sqrt(rC), 30, 30, 30, SDL_ALPHA_OPAQUE); } } void drawCenterCircles(SDL_Renderer *renderer, const std::vector &triangles) { float xC, yC, rC; for (std::size_t i = 0; i < triangles.size(); i++) { const Triangle &t = triangles[i]; CircumCircle(t.p1.x, t.p1.y, t.p1.x, t.p1.y, t.p2.x, t.p2.y, t.p3.x, t.p3.y, &xC, &yC, &rC); filledCircleRGBA(renderer, xC, yC, 3, 240, 23, 23, SDL_ALPHA_OPAQUE); } } void drawPolygones(SDL_Renderer *renderer, const std::vector &polygones) { for (auto polygone : polygones) { std::vector points = polygone.points; std::vector vx; std::vector vy; for (auto point : points) { vx.push_back(point.x); vy.push_back(point.y); } } } /* ********** D R A W ********** */ void drawVoronoi(Application &app) { float xCircle1, yCircle1, rCircle1, xCircle2, yCircle2, [MASK] ; for (auto _triangle1 : app.triangles) { for (auto _triangle2 : app.triangles) { int _nb = 0; if (_triangle1.p1 == _triangle2.p1 || _triangle1.p1 == _triangle2.p2 || _triangle1.p1 == _triangle2.p3) { _nb++; } if (_triangle1.p2 == _triangle2.p1 || _triangle1.p2 == _triangle2.p2 || _triangle1.p2 == _triangle2.p3) { _nb++; } if (_triangle1.p3 == _triangle2.p1 || _triangle1.p3 == _triangle2.p2 || _triangle1.p3 == _triangle2.p3) { _nb++; } if (_nb == 2) { CircumCircle(_triangle1.p1.x, _triangle1.p1.y, _triangle2.p1.x, _triangle2.p1.y, _triangle2.p2.x, _triangle2.p2.y, _triangle2.p3.x, _triangle2.p3.y, &xCircle1, &yCircle1, &rCircle1); CircumCircle(_triangle2.p1.x, _triangle2.p1.y, _triangle1.p1.x, _triangle1.p1.y, _triangle1.p2.x, _triangle1.p2.y, _triangle1.p3.x, _triangle1.p3.y, &xCircle2, &yCircle2, & [MASK] ); Segment _segment = Segment{Coords{(int)xCircle1, (int)yCircle1}, Coords{(int)xCircle2, (int)yCircle2}}; bool seg = false; for (auto _s : app.voronoiSeg) { if (seg) break; seg = _segment.p1 == _s.p1 && _segment.p2 == _s.p2; } if (!seg) app.voronoiSeg.push_back(_segment); } } } } void draw(SDL_Renderer *renderer, Application &app) { /* Remplissez cette fonction pour faire l'affichage du jeu */ int width, height; SDL_GetRendererOutputSize(renderer, &width, &height); drawPolygones(renderer, app.polygones); drawTriangles(renderer, app.triangles); drawPoints(renderer, app.points); drawSegments(renderer, app.voronoiSeg); drawVoronoi(app); } void construitVoronoi(Application &app) { //* --- Trier les points selon x ---*/ std::sort(app.points.begin(), app.points.end(), compareCoords); printf(""\n\nAfter sorting vector : ""); for (auto i = app.points.begin(); i < app.points.end(); i++) { cout << ""\n("" << i->x << "";"" << i->y << "")"" << endl; } //* --- Vider la liste existante de triangles ---*/ app.triangles.clear(); app.voronoiSeg.clear(); app.polygones.clear(); //* --- Créer un très grand triangle ---*/ Triangle big = Triangle({Coords{-1000, -1000}, Coords{500, 3000}, Coords{1500, -1000}}); // Le rajouter à la liste de triangles déjà créés app.triangles.push_back(big); //* --- pour chaque point P du repère --- */ for (auto point : app.points) { // Créer une liste de segments LS std::vector segments; //* --- chaque triangle T déjà créé --- */ for (std::size_t t = 0; t < app.triangles.size(); t++) { Triangle _triangle = app.triangles[t]; // si le cercle circonscrit contient le point P alors float xCircle, yCircle, rCircle; if (CircumCircle(point.x, point.y, _triangle.p1.x, _triangle.p1.y, _triangle.p2.x, _triangle.p2.y, _triangle.p3.x, _triangle.p3.y, &xCircle, &yCircle, &rCircle)) { // Récupérer les différents segments de ce triangles dans LS segments.push_back(Segment{_triangle.p1, _triangle.p2}); segments.push_back(Segment{_triangle.p2, _triangle.p3}); segments.push_back(Segment{_triangle.p3, _triangle.p1}); // Effacer le triangle de la liste app.triangles.erase(app.triangles.begin() + t); t--; } } //* --- pour chaque segment S de la liste LS faire --- */ for (std::size_t j = 0; j < segments.size(); j++) { Segment _segment1 = segments[j]; for (std::size_t k = 0; k < segments.size(); k++) { Segment _segment2 = segments[k]; // si un segment est un doublon d’un autre* alors if (k != j && _segment1.p1 == _segment2.p2 && _segment1.p2 == _segment2.p1) { // On les enlève de la liste segments.erase(segments.begin() + k); segments.erase(segments.begin() + j); j--; break; } } } //* --- pour Pour chaque segment S de la liste LS faire --- */ for (auto segment : segments) { // créer un nouveau triangle composé du segment S et du point P app.triangles.push_back(Triangle({segment.p1, segment.p2, point})); } } } bool handleEvent(Application &app) { /* Remplissez cette fonction pour gérer les inputs utilisateurs */ SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) return false; else if (e.type == SDL_WINDOWEVENT_RESIZED) { app.width = e.window.data1; app.height = e.window.data1; } else if (e.type == SDL_MOUSEWHEEL) { } else if (e.type == SDL_MOUSEBUTTONUP) { if (e.button.button == SDL_BUTTON_RIGHT) { app.focus.x = e.button.x; app.focus.y = e.button.y; app.points.clear(); } else if (e.button.button == SDL_BUTTON_LEFT) { app.focus.y = 0; // Création de points app.points.push_back(Coords{e.button.x, e.button.y}); construitVoronoi(app); } } } return true; } int main(int argc, char **argv) { SDL_Window *gWindow; SDL_Renderer *renderer; Application app{720, 720, Coords{0, 0}}; bool is_running = true; // Creation de la fenetre gWindow = init(""Awesome Voronoi"", 720, 720); if (!gWindow) { SDL_Log(""Failed to initialize!\n""); exit(1); } renderer = SDL_CreateRenderer(gWindow, -1, 0); // SDL_RENDERER_PRESENTVSYNC /* ********** G A M E L O O P ********** */ while (true) { // INPUTS is_running = handleEvent(app); if (!is_running) break; // EFFACAGE FRAME SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); // DESSIN draw(renderer, app); // VALIDATION FRAME SDL_RenderPresent(renderer); // PAUSE en ms SDL_Delay(1000 / 30); } // Free resources and close SDL close(gWindow, renderer); return 0; }",rCircle2 233,"// Copyright 2016-2018 California Institute of Technology. // // 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. // // Created by dfremont on 6/20/17. // #include ""ConcolicTest.h"" #include ""llvm/Support/raw_ostream.h"" using namespace llvm; using namespace klee; unsigned ConcolicTest::nextTestID = 0; void ConcolicTest::dump() const { llvm::errs() << ""gen "" << generation << "", score "" << newBlocks << "", rep "" << isReplacement << "", "" << objects.size() << "" objects: \n""; for (const ConcolicTestObject &obj : objects) { llvm::errs() << "" "" << obj.name << "": ""; for (unsigned i = 0; i < obj.bytes->size; i++) llvm::errs() << (int) obj.bytes->bytes[i] << "" ""; llvm::errs() << ""\n""; } llvm::errs() << "" path: ""; for (bool b : expectedPath) llvm::errs() << (int) b; llvm::errs() << ""\n""; } static void *interpretAsPointer(const ConcolicTestObject &obj) { assert(obj.bytes->size == sizeof(void *) && ""object does not have pointer size!""); return *reinterpret_cast(obj.bytes->bytes); } void ConcolicTest::dumpArgs() const { if (objects.size() < 2) return; if (*objects[0].name != ""n_args"") return; if (*objects[1].name != ""arg0"") return; unsigned *addr = static_cast(interpretAsPointer(objects[0])); unsigned [MASK] = *addr; for (unsigned i = 0; i < [MASK] ; i++) { char *saddr = static_cast(interpretAsPointer(objects[i + 1])); llvm::errs() << ""\"""" << std::string(saddr) << ""\"" ""; } } ",nargs 234,"#include #include // Define data structure for gauge readings typedef struct __attribute__((packed)) { uint32_t timestamp; uint16_t rpm; uint16_t speed; uint16_t coolantTemp; uint16_t oilPressure; uint16_t fuelLevel; uint16_t batteryVoltage; uint16_t boostPressure; uint8_t checkEngine; uint8_t turnSignals; } DashboardData_t; // MAC address of your child gauge (actual MAC you found) uint8_t childGaugeAddresses[][6] = { {0x18, 0x8B, 0x0E, 0xCD, 0x06, 0x48} // Your first child gauge // Add more child gauges here as you get their MAC addresses }; // Number of child gauges const int NUM_GAUGES = sizeof(childGaugeAddresses) / sizeof(childGaugeAddresses[0]); // Variables to track transmission success int successCount = 0; int failCount = 0; unsigned long lastStatsTime = 0; // Dashboard data structure DashboardData_t dashboardData; // Timing variables unsigned long lastBroadcastTime = 0; const int BROADCAST_INTERVAL = 500; // Broadcast every 50ms (20Hz update rate) // Callback function called when data is sent void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { if (status == ESP_NOW_SEND_SUCCESS) { successCount++; } else { failCount++; } // Print stats every 5 seconds unsigned long currentTime = millis(); if (currentTime - lastStatsTime >= 5000) { lastStatsTime = currentTime; int totalAttempts = successCount + failCount; float successRate = (totalAttempts > 0) ? (successCount * 100.0 / totalAttempts) : 0; Serial.print(""ESP-NOW Stats - Success: ""); Serial.print(successCount); Serial.print("", Fails: ""); Serial.print(failCount); Serial.print("", Success Rate: ""); Serial.print(successRate); Serial.println(""%""); // Reset counters successCount = 0; failCount = 0; } } void setup() { Serial.begin(115200); delay(1000); Serial.println(""\nCentral Dashboard Hub""); Serial.println(""--------------------""); // Set device as a Wi-Fi Station WiFi.mode(WIFI_STA); // Print MAC address Serial.print(""Hub MAC Address: ""); Serial.println(WiFi.macAddress()); // Initialize ESP-NOW if (esp_now_init() != ESP_OK) { Serial.println(""Error initializing ESP-NOW""); return; } // Register the send callback esp_now_register_send_cb(OnDataSent); // Register all child gauges as peers esp_now_peer_info_t [MASK] ; memset(& [MASK] , 0, sizeof( [MASK] )); [MASK] .channel = 0; // Use WiFi channel 0 (auto) [MASK] .encrypt = false; // No encryption // Register each gauge as a peer for (int i = 0; i < NUM_GAUGES; i++) { memcpy( [MASK] .peer_addr, childGaugeAddresses[i], 6); if (esp_now_add_peer(& [MASK] ) != ESP_OK) { Serial.print(""Failed to add peer: ""); Serial.println(i); } else { Serial.print(""Added peer gauge: ""); for (int j = 0; j < 6; j++) { Serial.printf(""%02X"", childGaugeAddresses[i][j]); if (j < 5) Serial.print("":""); } Serial.println(); } } // Initialize CAN bus communication // setupCAN(); // Uncomment and implement when ready for CAN integration Serial.println(""Central hub initialized and ready!""); } void loop() { // Read data from CAN bus (actual implementation would read from CAN) // readCANData(); // Uncomment and implement when ready // For testing, generate some sample data updateDashboardData(); // Broadcast data at specified interval unsigned long currentTime = millis(); if (currentTime - lastBroadcastTime >= BROADCAST_INTERVAL) { lastBroadcastTime = currentTime; broadcastDashboardData(); } } void updateDashboardData() { // In a real implementation, this would read from CAN bus // For testing, we'll generate sample data dashboardData.timestamp = 0; dashboardData.rpm = 0; dashboardData.speed = 0; dashboardData.coolantTemp = random(55, 87); dashboardData.oilPressure = 0; dashboardData.fuelLevel = 0; dashboardData.batteryVoltage = 0; // In tenths of a volt (12.0 - 14.5V) dashboardData.boostPressure = 0; // In PSI, negative for vacuum dashboardData.checkEngine = 0; // Occasionally turn on check engine light dashboardData.turnSignals = 0; // Random turn signal state } void broadcastDashboardData() { // Send data to each gauge for (int i = 0; i < NUM_GAUGES; i++) { esp_err_t result = esp_now_send(childGaugeAddresses[i], (uint8_t *)&dashboardData, sizeof(dashboardData)); if (result != ESP_OK) { Serial.print(""Failed to send to gauge: ""); Serial.println(i); } } } ",peerInfo 235,"//-------Source Code for Course Registration System-------// /* Created by */ #include #include #include #include #include #include using namespace std; //Function declarations class CourseRegistration{ char name[50],fname[50],username[20],password[20],password1[20],course[50],email[50],mob[11],address[100],hper[5],iper[5]; fstream file; public: void Register(); void Login(); void MainMenu(); }; //Driver-function int main(){ system(""color F4""); CourseRegistration [MASK] ; [MASK] .MainMenu(); } //For register void CourseRegistration:: Register(){ cout<<""---------------------------Register---------------------------\n\n""; cout<<""Enter your name: ""; fflush(stdin); gets(name); cout<<""Enter your father's name: ""; fflush(stdin); gets(fname); cout<<""Enter your email id: ""; fflush(stdin); gets(email); cout<<""Enter your contact number: ""; fflush(stdin); gets(mob); cout<<""Enter your address: ""; fflush(stdin); gets(address); cout<<""Enter your High School percentage: ""; cin>>hper; cout<<""Enter your Intermediate percentage: ""; cin>>iper; cout<<""\nSelect your course choice:\n\n""; cout<<""1.Civil Engineering\n""; cout<<""2.Computer Science and Engineering\n""; cout<<""3.Electrical Engineering\n""; cout<<""4.Electronics and Communiction Engineering\n""; cout<<""5.Mechanical Enginering\n""; cout<<""6.Chemical Engineering\n""; int choice; do{ cin.clear(); fflush(stdin); cin>>choice; switch(choice){ case 1: cout<<""Your selected choice is: ""; cout<<""Civil Engineering\n""; strcpy(course,""Civil Engineering"");break; case 2: cout<<""Your selected choice is: ""; cout<<""Computer Science and Engineering\n""; strcpy(course,""Computer Science and Engineering"");break; case 3: cout<<""Your selected choice is: ""; cout<<""Electrical Engineering\n""; strcpy(course,""Electrical Engineering"");break; case 4: cout<<""Your selected choice is: ""; cout<<""Electronics and Communiction Engineering\n""; strcpy(course,""Electronics and Communiction Engineering"");break; case 5: cout<<""Your selected choice is: ""; cout<<""Mechanical Enginering\n""; strcpy(course,""Mechanical Enginering"");break; case 6: cout<<""Your selected choice is: ""; cout<<""Chemical Engineering\n""; strcpy(course,""Chemical Engineering"");break; default: cout<<""Invalid choice,try again\n""; } }while(choice>6||choice<1); while(1){ cout<<""Enter your username: ""; cin>>username; file.open(username); if(file){ cout<<""Username already exist,try different\n\n""; file.close(); } else{ file.close();break; } } while(1){ char ch;int i=0; cout<<""Enter your password: ""; ch=getch(); while(ch!=13){ password[i++]=ch; cout<<""*""; ch=getch(); }password[i]='\0';i=0; cout<>username; cout<<""Enter password: ""; ch=getch(); while(ch!=13){ password[i++]=ch; cout<<""*""; ch=getch(); }i=0; cout<>s1;file>>s2; if((strcmp(username,s1)==0)&&(strcmp(password,s2)==0)){temp=0; file.close(); system(""cls""); ifstream f1(username); char ch; f1.get(ch); while(!f1.eof()){ cout<>ch; system(""cls""); switch(ch){ case '1': Register(); break; case '2': Login(); break; case '3': exit(0);break; default: cout<<""Invalid option,try again\n\n""; MainMenu(); } } ",obj 236,"#ifndef INCLUDED_HH_LRU_CACHE_HPP #define INCLUDED_HH_LRU_CACHE_HPP #include #include #include #include #include #include #include #include #include #include #include namespace hh { namespace functools { /** * Functional-style lru-cache which either calls the function from cache or returns a previouly * attained value. * * The cache is initialised with a specific size and only the most-recently used N argument * tuples will be recorded. After the size paramter exceeds the maximum allowed size previous * tuples return values will be dropped. Providing a max size of zero makes the cache size * infinite, and can retain cached values as long as memory is available. The underlying * implementation is based on hastaples to look up the hashed parmaeter tuples which have been * used to call the function, for this reason all types in the argument list for the underlying * function must implement the std::hash specialisation and all for equality comparison. * * @see std::hash() * @see make_lrucache * @tparam RETURN_TYPE The return type of the function used to instantiate this cache. * @tparams ARGUMENTS... Paramter Pack of types which this function declares in its signature. */ template class lru_cache { public: static constexpr std::size_t key_size = sizeof...(ARGUMENTS); using return_type = RETURN_TYPE; /** The return type of this cache.*/ using decayed_return_type = std::decay_t; /** The decayed returned type of this cache. */ using cache_key = std::tuple...>; /** The tuple type used to key return values. Two equal cache keys should return equal return values. */ using cache_entry = std::pair; /** The entry in the cache implementation. The decayed type is used to prevent naught reference tricks. */ using function_signature = std::function; function_signature d_func; unsigned int d_max_size; mutable std::list d_cache; mutable std::unordered_map d_cache_map; lru_cache() = delete; /** * Constructs a cache with a given function and size. * * @see make_lrucache() * @param func The underlying function which will be used to populate the cache on call. * @param cache_size The maximum size of the underlying cache. */ constexpr lru_cache(RETURN_TYPE (*func)(ARGUMENTS...), unsigned int cache_size) : d_func{func}, d_max_size{cache_size}, d_cache{}, d_cache_map{cache_size} {} /** * Constructs a cache with a given function and size. * * @see make_lrucache() * @param func The underlying function which will be used to populate the cache on call. * @param cache_size The maximum size of the underlying cache. */ constexpr lru_cache(function_signature func, unsigned int cache_size) : d_func{func}, d_max_size{cache_size}, d_cache{}, d_cache_map{cache_size} {} virtual ~lru_cache() = default; /** * Calls the underlying function or returns historic value. * * Will first check to see if the tuple has been calculated previously, to do this is requires * us to hash the arguments and call an equality of cache keys. This can have performance * implications for functions which have very long argument lists where this operation is more * expensive than calling the underlying function. * * @see lru_cache() * @tparam INPUT_ARGUMENTS A collection of arguments which should be convertibale to the * cachekey of the underlying. A static assertion checks this property. * @params args The arguments to call the function with, arguments are perfectly forwarded to * the underlying signature of the function this cache was initialised with. Implicitly * converting arguments as required. */ template RETURN_TYPE operator()(INPUT_ARGUMENTS&&... args) { cache_key key{std::forward(args)...}; get_entry_from_cache(key) .map([this](const auto& entry_it) { d_cache.splice(d_cache.end(), d_cache, entry_it); }) .map_error( [this, &key](...) { put_in_cache(std::move(key), std::apply(d_func, key)); }); return d_cache.back().second; } /** The maximum number of entries this cache can store. If 0 an infinite number of values can * be stored. */ constexpr auto max_size() const { return d_max_size; } /** The current number of retained historic values */ auto size() const { return d_cache_map.size(); } private: struct unexpected_tag {}; hh::optional get_entry_from_cache( const cache_key& key) const { auto [MASK] = d_cache_map.find(key); if ( [MASK] == d_cache_map.end()) { return hh::nullopt; } return [MASK] ->second; } template tl::expected put_in_cache(cache_key&& key, decayed_return_type&& return_value) const { d_cache.emplace_back(std::move(key), std::move(return_value)); d_cache_map[key] = std::prev(d_cache.end()); if (max_size() != 0 && size() > max_size()) { d_cache_map.erase(d_cache.front().first); d_cache.pop_front(); } return {}; } }; constexpr static auto DEFAULT_SIZE = 128u; template constexpr auto make_lrucache(std::function func, unsigned int size = DEFAULT_SIZE) { return lru_cache(func, size); } template constexpr auto make_lrucache(RETURN_TYPE (*func)(ARGUMENTS...), unsigned int size = DEFAULT_SIZE) { return lru_cache(func, size); } template void print_tuple_impl( std::basic_ostream& os, const Tuple& t, std::index_sequence = std::make_index_sequence::value>()) { ((os << (Is == 0 ? """" : "", "") << std::get(t)), ...); } template inline std::ostream& operator<<( std::ostream& os, const typename lru_cache::cache_key& key) { os << ""(""; print_tuple_impl(os, key); os << "")""; return os; } template inline std::ostream& operator<<( std::ostream& os, const typename lru_cache::cache_entry& entry) { os << entry.first << "" -> "" << entry.second; return os; } /** * Helper function to print the contents of the cache, used for debugging purposes. This * operation can be expensive so should not be used in production code. * * @see make_lrucache() * @param os The output strem to stream the cache into. * @param cache The cache to output to the given stream. * @tparam RETURN_TYPE The return type of the cache. * @tparam ARGUMENTS... The arguments that are used to construct the cache keys. */ template inline std::ostream& operator<<(std::ostream& os, const lru_cache& cache) { os << ""lru_cache<"" << cache.size() << ""/"" << cache.max_size() << "">[ ""; std::copy(cache.d_cache.begin(), cache.d_cache.end(), std::experimental::make_ostream_joiner(os, "", "")); os << "" ]""; return os; } } // namespace functools } // namespace hh #endif ",found_it 237,"/* Copyright (c) 2021 International Business Machines Corporation Prepared by: <> This program finds clusters of near-duplicate files of source code. The clusters do not overlap; each input sample is either assigned to a unique cluster or is declared to be a singleton set. Input format is lines of tokenized source file data. Each line is: TAB The list of tokens is never empty and tokens are either separated by solely SPACES or solely TABs. ( SP )*, or ( TAB )* (Also, all comments have been removed.) All token strings across all samples are collected in a vocabulary. That way all strings are stored only once and are associated with a unique index (counted from 0). All further processing can be done with the index; Jaccard similarity and LCS do not need the strings. The inverse relation is stored in the vector tokid2string. Per sample, the tokens are first inserted in an unordered_map keyed by the token id and recording a list of all positions for this token. Clearly, the length of this list per token is the token frequency. Then this dictionary is copied into a vector and sorted by the keys. Since we don't need the positions per token, this vector is split in a token_bag recording just the frequency and a token_seq. This way we have with minimal memory use represented the original sample both as a sequence of tokens (token_seq) and as a multiset (token_bag). The bag of token representation can be seen as a sparse feature vector: A feature is a vocabulary index and it either does not occur in a sample or it does occur with a certain recorded frequency. Having the bag ordered by index eases the computation of metrics like Jaccard and dot-product. Be careful to keep results deterministic. Using unordered_map for ids does not obey order of insertion of course, but depends on some hash function. All samples are in memory. */ #include #include #include #include #include // sqrt() #include // getopt() #include #include #include #include #include static int debug = 0; // when 1 debug output to stderr static int verbose = 0; // when 1 info output to stderr static int nowarn = 0; // when 1 warnings are suppressed static int csv_summary = 0; // when 1 output in CSV format static int out_singles = 0; // when 1 output singletons as well static unsigned num_tokens_threshold = 20; static unsigned num_samples_discarded = 0; static double threshold_0 = 0.9; // Jaccard, LCS, COSINE static double threshold_1 = 0.8; // Jaccard static enum { JACCARD, LCS, COSINE } mode = JACCARD; static const char *delim = "" ""; static const char *filename = ""stdin""; using namespace std; // Original input token sequence: typedef vector TokenSeq; // Single element of TokenBag: typedef pair TokenFreq; // (Arbitrarily) sorted sequence of tokens in order to compare them: typedef vector TokenBag; // Pair of doubles: typedef pair Double2; // all strings static unordered_map vocabulary; //static vector tokid2string; NOT USED struct Sample { string id; TokenSeq token_seq; TokenBag token_bag; bool flag; Sample(const string &id) : id(id), flag(false) {} // Sample size equals length of token sequence. unsigned size() const { return token_seq.size(); } #if 0 // NOT USED void show(FILE *fp = stderr) const { fputs(""tokens:"", fp); for (auto k : token_seq) fprintf(fp, "" %s"", tokid2string[k].c_str()); fputc('\n', fp); } #endif }; // all samples static unordered_set all_ids; static vector samples; // in order of input /* Split tokens and determine number of occurrences and store as vectors under id in global samples. */ static void process_sample(const char *id, char *tokens) { // Verify uniqueness of id: if (all_ids.find(id) != all_ids.end()) { if (!nowarn) fprintf(stderr, ""(W): Non-unique id %s; sample discarded.\n"", id); return; } Sample s(id); unsigned num_tokens = 0; // Per token instance string record all its positions: typedef vector Positions; typedef pair TokenPos; unordered_map dict; // Split the tokens: #if 1 char *p = tokens; do { const char *token = p; while (*p && *p != *delim) p++; // Here: *p == '\0' || *p == delim if (token == p) // empty token break; if (*p == *delim) *p++ = '\0'; //use token: unsigned token_id; // unique id for token string // Uniquely store all token strings in global vocabulary: auto it = vocabulary.find(token); if (it == vocabulary.end()) { // a fresh one token_id = vocabulary.size(); vocabulary[token] = token_id; //tokid2string.push_back(token); NOT USED } else token_id = it->second; // Locally store all positions for this token: dict[token_id].push_back(num_tokens); // size of second is frequency num_tokens++; } while (true); #else // strtok is slow const char *token = strtok(tokens, delim); while (token) { unsigned token_id; // unique id for token string // Uniquely store all token strings in global vocabulary: auto it = vocabulary.find(token); if (it == vocabulary.end()) { // a fresh one token_id = vocabulary.size(); vocabulary[token] = token_id; //tokid2string.push_back(token); NOT USED } else token_id = it->second; // Locally store all positions for this token: dict[token_id].push_back(num_tokens); // size of second is frequency num_tokens++; token = strtok(NULL, delim); } #endif // In Allamanis paper this is number of identifier tokens. // Hard to tell from a token list (of unknown language). if (num_tokens < num_tokens_threshold) { num_samples_discarded++; if (!nowarn) fprintf(stderr, ""(W): Sample %s has less than %u tokens; discarded.\n"", id, num_tokens_threshold); return; } // Should we normalize the frequencies? Don't think so. // Convert dict to vector (order does not matter): vector vec; for (const auto &t : dict) vec.emplace_back(t); // Sort by token id: sort(vec.begin(), vec.end(), [](const TokenPos &a, const TokenPos &b) { return a.first < b.first; }); // Fill in token_bag and token_seq: s.token_seq.resize(num_tokens); s.token_bag.resize(vec.size()); for (unsigned i = 0, size = vec.size(); i < size; i++) { unsigned token_id = vec[i].first; // Stuff token id and frequency in bag (multiset): s.token_bag[i] = {token_id, vec[i].second.size()}; // Put token_id in all the required positions: for (auto p : vec[i].second) s.token_seq[p] = token_id; } samples.emplace_back(s); } /* Longest Common Subsequence (LCS) (not necessarily consecutive) Simplified. O(mn) time, O(n) space. */ static unsigned lcs(const TokenSeq &X, const TokenSeq &Y, const unsigned m, const unsigned n) { // Here: m,n >= 0. unsigned L[2][n+1]; // small 2 by n+1 matrix unsigned bi; // odd(i) // 0-th row and 0-th column contains all zeroes: for (unsigned j = 0; j<=n; j++) // at least once L[0][j] = 0; L[1][0] = 0; for (unsigned i = 1; i<=m; i++) { // at least once bi = i & 1; for (unsigned j = 1; j<=n; j++) // at least once if (X[i-1] == Y[j-1]) L[bi][j] = L[1-bi][j-1] + 1; else L[bi][j] = max(L[1-bi][j], L[bi][j-1]); // After seeing i elems: L[bi][n] <= i is actual length; i is upperbound. // i - L[bi][n] is # different elements; might only get larger (1 per row) //cerr << ""L["" << i << ""][n]: "" << L[bi][n] << endl; //if (L[bi][n] >= mincommon) break; } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[bi][n]; } // An upperbound for the length of an LCS. static unsigned lcs_upperbound(const TokenBag &t1, const TokenBag &t2) { unsigned share_1 = 0; // card. of intersection considering multiplicity // Lock-step traversal of the 2 vectors: auto it1 = t1.cbegin(); auto it2 = t2.cbegin(); auto t1_cend = t1.cend(); auto t2_cend = t2.cend(); while (it1 != t1_cend && it2 != t2_cend) { if (it1->first < it2->first) ++it1; else if (it1->first > it2->first) ++it2; else { // intersection share_1 += it1->second < it2->second ? it1->second : it2->second; ++it1; ++it2; } } return share_1; } /* Compute cosine similarity of 2 multisets. */ static double cosine(const TokenBag &t1, const TokenBag &t2) { double dot = 0.0; double norm1 = 0.0; double norm2 = 0.0; // Lock-step traversal of the 2 vectors: auto it1 = t1.cbegin(); auto it2 = t2.cbegin(); auto t1_cend = t1.cend(); auto t2_cend = t2.cend(); // Feature value is the frequency. while (it1 != t1_cend && it2 != t2_cend) { // For normalization: norm1 += it1->second * it1->second; norm2 += it2->second * it2->second; if (it1->first < it2->first) ++it1; else if (it1->first > it2->first) ++it2; else { // intersection of features dot += it1->second * it2->second; ++it1; ++it2; } } // Handle leftover tails: for (; it1 != t1_cend; ++it1) norm1 += it1->second * it1->second; for (; it2 != t2_cend; ++it2) norm2 += it2->second * it2->second; return dot / sqrt(norm1 * norm2); } /* Compute Jaccard similarity of 2 multisets, both with ignoring an element's multiplicity and with considering it. The first case of course equals to assuming an overall multiplicity of 1. Returns a pair of numbers. */ static Double2 jaccard(const TokenBag &t1, const TokenBag &t2) { unsigned share_0 = 0; // card. of intersection ignoring multiplicity unsigned total_0 = 0; // card. of union ignoring multiplicity unsigned share_1 = 0; // card. of intersection considering multiplicity unsigned total_1 = 0; // card. of union considering multiplicity /* Example: A = 1 1 2 3 3 3 4 4 5 | 1 2 3 4 5 | 9 | 5 B = 2 2 3 3 3 4 6 | 2 3 4 6 | 7 | 4 --------------------------------------------------- A*B = 2 3 3 3 4 | 2 3 4 | 5 | 3 A+B= 1 1 2 2 3 3 3 4 4 5 6 | 1 2 3 4 5 6 | 11 | 6 share_0 = 3, total_0 = 6, share_0/total_0 = 0.5 share_1 = 5, total_1 = 11, share_1/total_1 = 0.45 (of course _0 and _1 the same when multiplicity is 1 overall) Note: result numbers are independent, can have share_0/total_0 (<, ==, >) share_1/total_1 */ // Lock-step traversal of the 2 vectors: auto it1 = t1.cbegin(); auto it2 = t2.cbegin(); auto t1_cend = t1.cend(); auto t2_cend = t2.cend(); while (it1 != t1_cend && it2 != t2_cend) { total_0++; if (it1->first < it2->first) // difference total_1 += (it1++)->second; else if (it1->first > it2->first) // difference total_1 += (it2++)->second; else { // intersection share_0++; // just as fast as single if total_1 += max(it1->second, it2->second); share_1 += min(it1->second, it2->second); ++it1; ++it2; } } // Handle leftover tails: while (it1 != t1_cend) { total_0++; total_1 += (it1++)->second; } while (it2 != t2_cend) { total_0++; total_1 += (it2++)->second; } return { double(share_0)/total_0, double(share_1)/total_1 }; } /* Check pairs of samples for similarity. All n(n-1)/2 pairs are considered in principle. Avoid a quadratic number of tests by flagging samples that are found similar. */ static void check_samples() { unsigned num_clusters = 0; unsigned max_cluster_size = 0; unsigned total_cluster_size = 0; unsigned singletons = 0; unsigned num_samples = samples.size(); if (!num_samples) return; // Output only non-singleton clusters separated by a blank line. // Tried using a std::queue for inner loop but does not seem to affect // performance much. Probably because of underlying deque. // Even simple queue using fixed size array does no improve things. for (auto it1 = samples.begin(), end = samples.end(); it1 != end; ++it1) { //fprintf(stderr, ""id: %s\n"", it1->id.c_str()); if (it1->flag) continue; const unsigned s1 = it1->size(); // FIXME: Put all samples similar to this one in a cluster. unsigned cluster_size = 1; for (auto it2 = next(it1), end = samples.end(); it2 != end; ++it2) { if (it2->flag) continue; const unsigned s2 = it2->size(); // Allow s2 to deviate up to +- 5% from s1: if (::abs(s1 - s2) * 100.0 / s1 > 5.0) continue; switch (mode) { case LCS: { // Cheap upperbound calculation: unsigned up = lcs_upperbound(it1->token_bag, it2->token_bag); if (up < s1 * threshold_0) continue; unsigned lcs_len = lcs(it1->token_seq, it2->token_seq, s1, s2); if (lcs_len >= s1 * threshold_0) { // Flag it2 (always beyond it1) as dealt with: it2->flag = true; if (cluster_size == 1) fprintf(stdout, ""%s: (%3u)\n"", it1->id.c_str(), s1); fprintf(stdout, ""%s: %3u (%3u)\n"", it2->id.c_str(), lcs_len, s2); cluster_size++; } break; } case JACCARD: { Double2 similarity = jaccard(it1->token_bag, it2->token_bag); if (similarity.first >= threshold_0 && similarity.second >= threshold_1) { // Flag it2 (always beyond it1) as dealt with: it2->flag = true; if (cluster_size == 1) fprintf(stdout, ""%s:\n"", it1->id.c_str()); fprintf(stdout, ""%s: %5.2f,%5.2f\n"", it2->id.c_str(), similarity.first, similarity.second); cluster_size++; } break; } case COSINE: { double similarity = cosine(it1->token_bag, it2->token_bag); if (similarity >= threshold_0) { // Flag it2 (always beyond it1) as dealt with: it2->flag = true; if (cluster_size == 1) fprintf(stdout, ""%s:\n"", it1->id.c_str()); fprintf(stdout, ""%s: %5.2f\n"", it2->id.c_str(), similarity); cluster_size++; } break; } } } if (cluster_size > 1) { if (next(it1) != end) fputc('\n', stdout); num_clusters++; if (cluster_size > max_cluster_size) max_cluster_size = cluster_size; total_cluster_size += cluster_size; } else { if (out_singles) { fprintf(stdout, ""%s:\n"", it1->id.c_str()); if (next(it1) != end) fputc('\n', stdout); } singletons++; } } // Sanity check: assert(total_cluster_size + singletons == num_samples); // samples with size 1 cluster: num_samples - total_cluster_size // unique samples: num_clusters + size 1 samples // duplication factor: (num_samples - unique samples) / num_samples // = (total_cluster_size - num_clusters) / num_samples if (csv_summary) { // identifier,samples,discarded,unique,clusters,duplicates,max,average,factor fprintf(stderr, ""%s,%u,%u,%u,%u,%u,%u,%.1f,%.1f%%\n"", filename, num_samples+num_samples_discarded, num_samples_discarded, num_samples + num_clusters - total_cluster_size, num_clusters, total_cluster_size, max_cluster_size, double(total_cluster_size)/num_clusters, (total_cluster_size - num_clusters) * 100.0 / num_samples); } else fprintf(stderr, ""Found %u clusters (avg: %3.1f, max: %u) among the %u samples.\n"" ""Duplication factor: %5.1f%%\n"", num_clusters, double(total_cluster_size)/num_clusters, max_cluster_size, num_samples, (total_cluster_size - num_clusters) * 100.0 / num_samples); } int main(int argc, char *argv[]) { extern int optind; int option; char const *opt_str = ""cdhi:j:m:M:o:stvw""; char usage_str[80]; char *outfile = 0; unsigned num_files = 0; // number of files read sprintf(usage_str, ""usage: %%s [ -%s ] [ FILE ]\n"", opt_str); /* Process arguments: */ while ((option = getopt(argc, argv, opt_str)) != EOF) { switch (option) { case 'c': csv_summary = 1; break; case 'd': debug = verbose = 1; break; case 'h': fputs( ""This program finds clusters of near-duplicate files of source code.\n"" ""The input is a file (or files) with one sample per line. A sample consists\n"" ""of a unique (within the input) identifier for the source code, e.g.\n"" ""its file name or its file name path, and a list of space-separated tokens.\n\n"" ""Two samples are reported as near-duplicates depending on the thresholds set\n"" ""for the various similarity metrics (thresholds must be in [0..1]):\n"" ""1. in Jaccard mode, the set similarity score must meet the 1st threshold and\n"" "" the multiset score meet the 2nd threshold;\n"" ""2. in LCS mode, the ratio of common subsequence length and input length must\n"" "" be at least the 1st threshold value;\n"" ""3. in Cosine mode, the cosine similarity must be at least the 1st threshold.\n\n"" , stdout); fprintf(stderr, usage_str, basename(argv[0])); fputs( ""\nCommand line options are:\n"" ""-c : output summary in CSV instead of plain text (default) to stderr.\n"" ""-d : print debug info to stderr; implies -v.\n"" ""-h : print just this text to stderr and stop.\n"" ""-i : 1st Jaccard (or LCS, or Cosine) threshold value (default 0.9).\n"" ""-j : 2nd Jaccard threshold value (default 0.8).\n"" ""-m : operation mode either jaccard (default), lcs, or cosine.\n"" ""-M : samples smaller than this number are discarded (default 20).\n"" ""-o : name for output file (instead of stdout).\n"" ""-s : also output singleton clusters (default don't).\n"" ""-t : insist tokens are TAB-separated (default autodetect).\n"" ""-v : print action summary to stderr.\n"" ""-w : suppress all warning messages.\n"", stderr); return 0; case 'i': threshold_0 = atof(optarg); break; case 'j': threshold_1 = atof(optarg); break; case 'm': if (!strcmp(optarg, ""jaccard"")) mode = JACCARD; else if (!strcmp(optarg, ""lcs"")) mode = LCS; else if (!strcmp(optarg, ""cosine"")) mode = COSINE; else { if (!nowarn) fprintf(stderr, ""(W): Invalid mode %s (using jaccard).\n"", optarg); mode = JACCARD; } break; case 'M': num_tokens_threshold = atoi(optarg); break; case 'o': outfile = optarg; break; case 's': out_singles = 1; break; case 't': delim = ""\t""; break; case 'v': verbose = 1; break; case 'w': nowarn = 1; break; case '?': default: fputs(""(F): unknown option. Stop.\n"", stderr); fprintf(stderr, usage_str, argv[0]); return 1; } } if (outfile && outfile[0]) { if (!freopen(outfile, ""w"", stdout)) { fprintf(stderr, ""(F): cannot open %s for writing.\n"", outfile); exit(3); } } char *line = NULL; size_t alloc_len; ssize_t [MASK] ; // CSV header (once) /* if (csv_summary) fputs(""identifier,samples,discarded,unique,clusters,duplicates,max,"" ""average,factor\n"", stderr); */ if (optind == argc) goto doit; do { filename = argv[optind]; if (!freopen(filename, ""r"", stdin)) { if (!nowarn) fprintf(stderr, ""(W): Cannot read file %s.\n"", filename); continue; } doit: unsigned linenr = 0; num_files++; if (verbose) fprintf(stderr, ""(I): Processing file %s...\n"", filename); while (( [MASK] = getline(&line, &alloc_len, stdin)) != -1) { linenr++; // Remove white-space from end of line: char *p = line + [MASK] ; while (isspace(*(p-1))) p--; *p = '\0'; // Skip blank lines: if (!*line) continue; // Split line at first TAB: #if 1 const char *id = p = line; while (*p && *p != '\t') p++; // Here: *p == '\0' || *p == '\t' if (*p != '\t') { fprintf(stderr, ""(W): Line %u with id `%s' has no tokens; skipped.\n"", linenr, id); continue; } *p++ = '\0'; char *tokens = p; #else const char *id = strtok(line, ""\t""); char *tokens = strtok(NULL, """"); p = tokens; #endif // if see a TAB in tokens assume delim=""\t"" if (delim[0] == ' ') for (; *p; p++) if (*p == '\t') { delim = ""\t""; break; } process_sample(id, tokens); } } while (++optind < argc); //if (line) free(line); if (verbose) fprintf(stderr, ""(I): Total distinct tokens in vocabulary: %u\n"", vocabulary.size()); check_samples(); if (num_files > 1 && verbose) fprintf(stderr, ""(I): Total number of files processed: %u\n"", num_files); return 0; } ",nchars 238,"#include ""Pch.h"" #include ""MainEditorLayer.h"" #include #include ""EditorBuiltinCamera.h"" #include ""ImGuizmo.h"" #include ""ModelEditor/ModelEditorLayer.h"" #include ""SceneEditor/SceneEditorLayer.h"" namespace Wuya { MainEditorLayer::MainEditorLayer() : ILayer(""MainEditorLayer"") { PROFILE_FUNCTION(); } void MainEditorLayer::OnAttached() { PROFILE_FUNCTION(); } void MainEditorLayer::OnDetached() { PROFILE_FUNCTION(); ILayer::OnDetached(); } void MainEditorLayer::OnImGuiRender() { PROFILE_FUNCTION(); /* 菜单 */ ShowMenuUI(); /* 场景控制UI */ ShowSceneControllerUI(); /* 资源管理窗口 */ m_ResourceBrowser.OnImGuiRenderer(); // bool show = true; // ImGui::ShowDemoWindow(&show); } void MainEditorLayer::OnEvent(IEvent* event) { PROFILE_FUNCTION(); if (!event) return; EventDispatcher dispatcher(event); dispatcher.Dispatch(BIND_EVENT_FUNC(MainEditorLayer::OnKeyPressed)); dispatcher.Dispatch(BIND_EVENT_FUNC(MainEditorLayer::OnMouseButtonPressed)); } bool MainEditorLayer::OnKeyPressed(KeyPressedEvent* event) { PROFILE_FUNCTION(); if (event->GetRepeatCount() > 0) return false; bool is_ctrl_pressed = Input::IsKeyPressed(Key::LeftControl) || Input::IsKeyPressed(Key::RightControl); bool is_shift_pressed = Input::IsKeyPressed(Key::LeftShift) || Input::IsKeyPressed(Key::RightShift); bool is_button_right_pressed = Input::IsMouseButtonPressed(Mouse::ButtonRight); switch (event->GetKeyCode()) { case Key::N: /* Ctrl+N:新建一个场景 */ { if (is_ctrl_pressed) NewScene(); } break; case Key::S: /* Ctrl+S: 保存场景; Ctrl+Shift+S: 场景另存为 */ if (is_ctrl_pressed) { if (is_shift_pressed) SaveSceneAs(); else SaveScene(); } break; case Key::I: /* Ctrl+I:导入一个场景 */ { if (is_ctrl_pressed) ImportScene(); } break; case Key::Q: { if (!ImGuizmo::IsUsing() && !is_button_right_pressed) { m_GizmoType = -1; NotifyGizmoTypeChanged(); } } break; case Key::W: { if (!ImGuizmo::IsUsing() && !is_button_right_pressed) { m_GizmoType = ImGuizmo::OPERATION::TRANSLATE; NotifyGizmoTypeChanged(); } } break; case Key::E: { if (!ImGuizmo::IsUsing() && !is_button_right_pressed) { m_GizmoType = ImGuizmo::OPERATION::ROTATE; NotifyGizmoTypeChanged(); } } break; case Key::R: { if (!ImGuizmo::IsUsing() && !is_button_right_pressed) { m_GizmoType = ImGuizmo::OPERATION::SCALE; NotifyGizmoTypeChanged(); } } break; } return true; } bool MainEditorLayer::OnMouseButtonPressed(MouseButtonPressedEvent* event) { PROFILE_FUNCTION(); return false; } void MainEditorLayer::NewScene() { PROFILE_FUNCTION(); const auto& scene_editor_layer = reinterpret_cast&>(Application::Instance()->GetLayerByName(""SceneEditorLayer"")); scene_editor_layer->NewScene(); } void MainEditorLayer::ImportScene() { PROFILE_FUNCTION(); const auto file_path = FileDialog::OpenFile(""scene(*.scn)\0*.scn\0""); if (!file_path.empty()) { } } void MainEditorLayer::SaveScene() { PROFILE_FUNCTION(); } /* 保存场景到指定路径 */ void MainEditorLayer::SaveSceneAs() { PROFILE_FUNCTION(); std::string file_path = FileDialog::SaveFile(""scene(*.scn)\0*.scn\0""); } void MainEditorLayer::ShowMenuUI() { PROFILE_FUNCTION(); static bool p_open = true; static bool opt_fullscreen = true; static bool opt_padding = false; static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, // because it would be confusing to have two docking targets within each others. ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking; if (opt_fullscreen) { const ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->WorkPos); ImGui::SetNextWindowSize(viewport->WorkSize); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } else { dockspace_flags &= ~ImGuiDockNodeFlags_PassthruCentralNode; } // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background // and handle the pass-thru hole, so we ask Begin() to not render a background. if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) window_flags |= ImGuiWindowFlags_NoBackground; // Important: note that we proceed even if Begin() returns false (aka window is collapsed). // This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, // all active windows docked into it will lose their parent and become undocked. // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. if (!opt_padding) ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin(""DockSpace Demo"", &p_open, window_flags); { if (!opt_padding) ImGui::PopStyleVar(); if (opt_fullscreen) ImGui::PopStyleVar(2); // Submit the DockSpace ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGuiID dockspace_id = ImGui::GetID(""MyDockSpace""); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); } ImGuiStyle& style = ImGui::GetStyle(); style.WindowMinSize.x = 200.0f; /* 菜单栏 */ if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu(""File"")) { if (ImGui::MenuItem(""New Scene"", ""Ctrl+N"")) { NewScene(); } if (ImGui::MenuItem(""Open Scene"", ""Ctrl+O"")) { ImportScene(); } if (ImGui::MenuItem(""Save Scene"", ""Ctrl+S"")) { SaveScene(); } if (ImGui::MenuItem(""Save Scene As"", ""Ctrl+Shift+S"")) { SaveSceneAs(); } if (ImGui::MenuItem(""Import Model(.obj)"", ""Ctrl+I"")) { m_ActiveModelEditor = true; const auto& model_editor_layer = reinterpret_cast&>(Application::Instance()->GetLayerByName(""ModelEditorLayer"")); model_editor_layer->Active(m_ActiveModelEditor); model_editor_layer->ImportModel(); } if (ImGui::MenuItem(""Export Mesh & Mtl(.mesh & .mtl)"", ""Ctrl+E"")) { //ExportMeshAndMtl(); const auto& scene_editor_layer = reinterpret_cast&>(Application::Instance()->GetLayerByName(""SceneEditorLayer"")); static bool active = false; scene_editor_layer->Active(active); active = !active; } if (ImGui::MenuItem(""Exit"")) Application::Instance()->Close(); ImGui::EndMenu(); } if (ImGui::BeginMenu(""Windows"")) { const auto& scene_editor_layer = reinterpret_cast&>(Application::Instance()->GetLayerByName(""SceneEditorLayer"")); m_ActiveSceneEditor = scene_editor_layer->IsActivated(); if (ImGui::MenuItem(""SceneEditor"", NULL, &m_ActiveSceneEditor)) { scene_editor_layer->Active(m_ActiveSceneEditor); } const auto& model_editor_layer = reinterpret_cast&>(Application::Instance()->GetLayerByName(""ModelEditorLayer"")); m_ActiveModelEditor = model_editor_layer->IsActivated(); if (ImGui::MenuItem(""ModelEditor"", NULL, &m_ActiveModelEditor)) { model_editor_layer->Active(m_ActiveModelEditor); } ImGui::EndMenu(); } if (ImGui::BeginMenu(""Options"")) { // Disabling fullscreen would allow the window to be moved to the front of other windows, // which we can't undo at the moment without finer window depth/z control. ImGui::MenuItem(""Fullscreen"", NULL, &opt_fullscreen); ImGui::MenuItem(""Padding"", NULL, &opt_padding); ImGui::Separator(); if (ImGui::MenuItem(""Flag: NoSplit"", """", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoSplit; } if (ImGui::MenuItem(""Flag: NoResize"", """", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoResize; } if (ImGui::MenuItem(""Flag: NoDockingInCentralNode"", """", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; } if (ImGui::MenuItem(""Flag: AutoHideTabBar"", """", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar; } if (ImGui::MenuItem(""Flag: PassthruCentralNode"", """", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0, opt_fullscreen)) { dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode; } ImGui::Separator(); if (ImGui::MenuItem(""Close"", NULL, false)) p_open = false; ImGui::EndMenu(); } ImGui::EndMenuBar(); } } ImGui::End(); } /* 显示场景控制UI */ void MainEditorLayer::ShowSceneControllerUI() { PROFILE_FUNCTION(); static auto save_icon = TextureAssetManager::Instance().GetOrCreateTexture(ABSOLUTE_PATH(""EditorRes/icons/save.png"")); static auto [MASK] = TextureAssetManager::Instance().GetOrCreateTexture(ABSOLUTE_PATH(""EditorRes/icons/translate.png"")); static auto rotate_icon = TextureAssetManager::Instance().GetOrCreateTexture(ABSOLUTE_PATH(""EditorRes/icons/rotate.png"")); static auto scale_icon = TextureAssetManager::Instance().GetOrCreateTexture(ABSOLUTE_PATH(""EditorRes/icons/scale.png"")); static auto play_icon = TextureAssetManager::Instance().GetOrCreateTexture(ABSOLUTE_PATH(""EditorRes/icons/play.png"")); static auto stop_icon = TextureAssetManager::Instance().GetOrCreateTexture(ABSOLUTE_PATH(""EditorRes/icons/stop.png"")); static auto menu_icon = TextureAssetManager::Instance().GetOrCreateTexture(ABSOLUTE_PATH(""EditorRes/icons/menu.png"")); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 2)); /* 指定间隔 */ ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, ImVec2(0, 2)); ImGui::Begin(""##Scene Controller"", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); { const float icon_size = ImGui::GetWindowHeight() - 4.0f; const float panel_width = ImGui::GetWindowContentRegionMax().x; START_TRANSPARENT_BUTTON; constexpr float cursor_offset = 10.0f; /* 保存按钮 */ ImGui::SetCursorPosX(cursor_offset); /*if (ImGui::ImageButton((ImTextureID)save_icon->GetTextureID(), ImVec2(icon_size, icon_size), ImVec2(0, 1), ImVec2(1, 0), 0)) SaveScene();*/ bool checked = false; ImGuiExt::DrawCheckedImageButtonUI(""Save"", save_icon, ImVec2(icon_size, icon_size), checked, [&]() { SaveScene(); }); /* 移动/旋转/平移操作 */ { /* translate */ ImGui::SameLine(cursor_offset + icon_size * 2); bool checked = m_GizmoType == ImGuizmo::OPERATION::TRANSLATE; ImGuiExt::DrawCheckedImageButtonUI(""Translate"", [MASK] , ImVec2(icon_size, icon_size), checked, [&]() { m_GizmoType = ImGuizmo::OPERATION::TRANSLATE; NotifyGizmoTypeChanged(); }); /* rotate */ ImGui::SameLine(); checked = m_GizmoType == ImGuizmo::OPERATION::ROTATE; ImGuiExt::DrawCheckedImageButtonUI(""Rotate"", rotate_icon, ImVec2(icon_size, icon_size), checked, [&]() { m_GizmoType = ImGuizmo::OPERATION::ROTATE; NotifyGizmoTypeChanged(); }); /* scale */ ImGui::SameLine(); checked = m_GizmoType == ImGuizmo::OPERATION::SCALE; ImGuiExt::DrawCheckedImageButtonUI(""Scale"", scale_icon, ImVec2(icon_size, icon_size), checked, [&]() { m_GizmoType = ImGuizmo::OPERATION::SCALE; NotifyGizmoTypeChanged(); }); } /* 切换执行模式 */ { ImGui::SameLine(); const SharedPtr icon = (m_PlayMode == PlayMode::Edit) ? play_icon : stop_icon; ImGui::SetCursorPosX((panel_width - icon_size) * 0.5f); if (ImGui::ImageButton((ImTextureID)icon->GetTextureID(), ImVec2(icon_size, icon_size), ImVec2(0, 1), ImVec2(1, 0), 0)) { m_PlayMode = (m_PlayMode == PlayMode::Edit) ? PlayMode::Runtime : PlayMode::Edit; NotifyPlayModeChanged(); } } /* 配置 */ { ImGui::SameLine(panel_width - cursor_offset - 20); START_STYLE_ALPHA(0.5f); if (ImGui::ImageButton((ImTextureID)menu_icon->GetTextureID(), ImVec2(20, 20), ImVec2(0, 1), ImVec2(1, 0))) ImGui::OpenPopup(""ConfigPopup""); END_STYLE_ALPHA; /* 展开弹窗时,显示控件 */ // if (ImGui::BeginPopup(""ConfigPopup"")) // { // ImGui::PushItemWidth(200); // // bool is_focus = m_pEditorCamera->IsFocus(); // ImGui::Checkbox(""FocusMode"", &is_focus); // m_pEditorCamera->SetFocus(is_focus); // // ImGui::PopItemWidth(); // ImGui::EndPopup(); // } } END_TRANSPARENT_BUTTON; } ImGui::End(); ImGui::PopStyleVar(2); } /* 显示渲染统计信息 */ void MainEditorLayer::ShowStatisticInfoUI() { PROFILE_FUNCTION(); ImGui::Begin(""Stat Info""); { // todo: 帧率等 // Renderer3D Stats if (ImGui::CollapsingHeader(""3D"")) { // todo: 三角形、模型数量 } } ImGui::End(); } void MainEditorLayer::NotifyGizmoTypeChanged() { const auto& scene_editor_layer = reinterpret_cast&>(Application::Instance()->GetLayerByName(""SceneEditorLayer"")); scene_editor_layer->SetGizmoType(m_GizmoType); } void MainEditorLayer::NotifyPlayModeChanged() { const auto& scene_editor_layer = reinterpret_cast&>(Application::Instance()->GetLayerByName(""SceneEditorLayer"")); scene_editor_layer->SetPlayMode(m_PlayMode); } void MainEditorLayer::OnUpdate(float delta_time) { PROFILE_FUNCTION(); } } ",translate_icon 239,"/* * Copyright , 2021 * Use, modification and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include ""math_unit_test.hpp"" #include #include #ifdef BOOST_HAS_FLOAT128 #include using boost::multiprecision::float128; #endif using boost::math::tools::cubic_roots; using boost::math::tools::cubic_root_residual; using std::cbrt; template void test_zero_coefficients() { Real a = 0; Real b = 0; Real c = 0; Real d = 0; auto roots = cubic_roots(a,b,c,d); CHECK_EQUAL(roots[0], Real(0)); CHECK_EQUAL(roots[1], Real(0)); CHECK_EQUAL(roots[2], Real(0)); a = 1; roots = cubic_roots(a,b,c,d); CHECK_EQUAL(roots[0], Real(0)); CHECK_EQUAL(roots[1], Real(0)); CHECK_EQUAL(roots[2], Real(0)); a = 1; d = 1; // x^3 + 1 = 0: roots = cubic_roots(a,b,c,d); CHECK_EQUAL(roots[0], Real(-1)); CHECK_NAN(roots[1]); CHECK_NAN(roots[2]); d = -1; // x^3 - 1 = 0: roots = cubic_roots(a,b,c,d); CHECK_EQUAL(roots[0], Real(1)); CHECK_NAN(roots[1]); CHECK_NAN(roots[2]); d = -2; // x^3 - 2 = 0 roots = cubic_roots(a,b,c,d); CHECK_ULP_CLOSE(roots[0], cbrt(Real(2)), 2); CHECK_NAN(roots[1]); CHECK_NAN(roots[2]); d = -8; roots = cubic_roots(a,b,c,d); CHECK_EQUAL(roots[0], Real(2)); CHECK_NAN(roots[1]); CHECK_NAN(roots[2]); // (x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x - 6 roots = cubic_roots(Real(1), Real(-6), Real(11), Real(-6)); CHECK_ULP_CLOSE(roots[0], Real(1), 2); CHECK_ULP_CLOSE(roots[1], Real(2), 2); CHECK_ULP_CLOSE(roots[2], Real(3), 2); // Double root: // (x+1)^2(x-2) = x^3 - 3x - 2: // Note: This test is unstable wrt to perturbations! roots = cubic_roots(Real(1), Real(0), Real(-3), Real(-2)); CHECK_ULP_CLOSE(Real(-1), roots[0], 2); CHECK_ULP_CLOSE(Real(-1), roots[1], 2); CHECK_ULP_CLOSE(Real(2), roots[2], 2); std::uniform_real_distribution dis(-2,2); std::mt19937 [MASK] (12345); // Expected roots std::array r; int trials = 10; for (int i = 0; i < trials; ++i) { // Mathematica: // Expand[(x - r0)*(x - r1)*(x - r2)] // - r0 r1 r2 + (r0 r1 + r0 r2 + r1 r2) x // - (r0 + r1 + r2) x^2 + x^3 for (auto & root : r) { root = static_cast(dis( [MASK] )); } std::sort(r.begin(), r.end()); Real a = 1; Real b = -(r[0] + r[1] + r[2]); Real c = r[0]*r[1] + r[0]*r[2] + r[1]*r[2]; Real d = -r[0]*r[1]*r[2]; auto roots = cubic_roots(a, b, c, d); // I could check the condition number here, but this is fine right? if(!CHECK_ULP_CLOSE(r[0], roots[0], 25)) { std::cerr << "" Polynomial x^3 + "" << b << ""x^2 + "" << c << ""x + "" << d << "" has roots {""; std::cerr << r[0] << "", "" << r[1] << "", "" << r[2] << ""}, but the computed roots are {""; std::cerr << roots[0] << "", "" << roots[1] << "", "" << roots[2] << ""}\n""; } CHECK_ULP_CLOSE(r[1], roots[1], 25); CHECK_ULP_CLOSE(r[2], roots[2], 25); for (auto root : roots) { auto res = cubic_root_residual(a, b,c,d, root); CHECK_LE(abs(res[0]), 20*res[1]); } } } int main() { test_zero_coefficients(); test_zero_coefficients(); #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS test_zero_coefficients(); #endif #ifdef BOOST_HAS_FLOAT128 // For some reason, the quadmath is way less accurate than the float/double/long double: //test_zero_coefficients(); #endif return boost::math::test::report_errors(); } ",gen 240,"#ifndef KEYPAD_H #define KEYPAD_H #include ""Key.h"" #define OPEN LOW #define CLOSED HIGH typedef char KeypadEvent; typedef unsigned int uint; typedef unsigned long ulong; typedef struct { byte rows; byte columns; } KeypadSize; #define LIST_MAX 10 // Max number of keys on the active list. #define MAPSIZE 10 // MAPSIZE is the number of rows (times 16 columns) #define makeKeymap(x) ((char*)x) #define ROWS 4 #define COLS 4 class Keypad4x4 : public Key { public: Keypad4x4(char *userKeymap, byte *row, byte *col); virtual void pin_mode(byte pinNum, byte mode) { pinMode(pinNum, mode); } virtual void pin_write(byte pinNum, boolean [MASK] ) { digitalWrite(pinNum, [MASK] ); } virtual int pin_read(byte pinNum) { return digitalRead(pinNum); } uint bitMap[MAPSIZE]; // 10 row x 16 column array of bits. Except Due which has 32 columns. Key key[LIST_MAX]; unsigned long holdTimer; char getKey(); bool getKeys(); KeyState getState(); void begin(char *userKeymap); bool isPressed(char keyChar); void setDebounceTime(uint); void setHoldTime(uint); void addEventListener(void (*listener)(char)); int findInList(char keyChar); int findInList(int keyCode); char waitForKey(); bool keyStateChanged(); byte numKeys(); private: unsigned long startTime; char *keymap; byte *rowPins; byte *columnPins; KeypadSize sizeKpd; uint debounceTime; uint holdTime; bool single_key; void scanKeys(); bool updateList(); void nextKeyState(byte n, boolean button); void transitionTo(byte n, KeyState nextState); void (*keypadEventListener)(char); }; #endif",level 241,"#include ""appintegration.h"" #include #include #include #include #include #include #include #include #include #include namespace { /** * @brief Updates a field in desktop file if the value is different * @param desktopFilePath Path to the desktop file * @param fieldName Name of the field to update * @param fieldValue New value for the field */ void updateDesktopField(const QString& desktopFilePath, const QString& fieldName, const QString& fieldValue) { #ifdef Q_OS_LINUX QFile file(desktopFilePath); if (file.open(QIODevice::ReadWrite | QIODevice::Text)) { QString content = file.readAll(); file.close(); // Match field and replace with new value if different QRegularExpression regex(fieldName + ""=(.*)""); QString replacement = fieldName + ""="" + fieldValue; QRegularExpressionMatch match = regex.match(content); QString oldValue = match.hasMatch() ? match.captured(1) : """"; if (oldValue != fieldValue) { content.replace(regex, replacement); } else { qDebug() << ""Field value is the same, skipping update for"" << fieldName; return; } // Write back to file if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { file.write(content.toUtf8()); file.close(); qDebug() << ""Updated desktop file:"" << desktopFilePath; qDebug() << ""Field name:"" << fieldName; qDebug() << ""Old value:"" << oldValue; qDebug() << ""New value:"" << fieldValue; } else { qDebug() << ""Failed to update desktop file:"" << desktopFilePath; } } else { qDebug() << ""Failed to open desktop file for reading:"" << desktopFilePath; } #else // Non-Linux platforms - do nothing Q_UNUSED(desktopFilePath); Q_UNUSED(fieldName); Q_UNUSED(fieldValue); #endif } /** * @brief Refreshes system caches for desktop files and icons */ void refreshSystemCache() { #ifdef Q_OS_LINUX // Update desktop database QProcess::execute(""update-desktop-database"", QStringList() << QDir::homePath() + ""/.local/share/applications""); // Ensure icon directories exist for cache update QDir().mkpath(QDir::homePath() + ""/.local/share/icons/hicolor""); // Refresh icon cache - try different commands based on available tools QProcess::execute(""gtk-update-icon-cache"", QStringList() << ""-f"" << ""-t"" << QDir::homePath() + ""/.local/share/icons""); QProcess::execute(""xdg-icon-resource"", QStringList() << ""forceupdate""); // Notify desktop environment of changes - works for many desktop environments QProcess::execute(""dbus-send"", QStringList() << ""--session"" << ""--dest=org.freedesktop.DBus"" << ""--type=method_call"" << ""/org/freedesktop/DBus"" << ""org.freedesktop.DBus.ReloadConfig""); #endif } } void AppIntegration::loadApplicationIcon(QApplication& app) { // Try to load icon from resource QIcon icon("":/app-icon-png""); if (!icon.isNull()) { app.setWindowIcon(icon); qDebug() << ""Icon loaded from resource""; } #ifdef Q_OS_LINUX // Setup desktop entry for Linux setupDesktopEntry(); #endif } #ifdef Q_OS_LINUX void AppIntegration::setupDesktopEntry() { // Check if running from AppImage const char* appImage = getenv(""APPIMAGE""); if (!appImage) { // Not running from AppImage, nothing to do return; } // Get paths QString appImagePath(appImage); QString appDir = QCoreApplication::applicationDirPath(); QString [MASK] = appDir + ""/../icons/longview.png""; QString appDesktopPath = appDir + ""/../applications/longview.desktop""; const QString USER_LOCAL_DATA_DIR = QDir::homePath() + ""/.local/share""; QString userDesktopFilePath = USER_LOCAL_DATA_DIR + ""/applications/longview.desktop""; QString userIconDir = USER_LOCAL_DATA_DIR + ""/icons""; QString userIconPath = userIconDir + ""/longview.png""; // Ensure icon directory exists QDir().mkpath(userIconDir); // Try to copy icon from AppImage to user directory if (QFile::copy( [MASK] , userIconPath)) { qDebug() << ""Icon copied from:"" << [MASK] << ""to:"" << userIconPath; } // Check if desktop file exists QFile desktopFile(userDesktopFilePath); if (!desktopFile.exists()) { // Desktop file doesn't exist, copy from template and update QDir().mkpath(QFileInfo(userDesktopFilePath).path()); if (QFile::copy(appDesktopPath, userDesktopFilePath)) { qDebug() << ""Desktop file copied from:"" << appDesktopPath << ""to:"" << userDesktopFilePath; // Update Icon fields in the new desktop file updateDesktopField(userDesktopFilePath, ""Icon"", userIconPath); // Force system to reload desktop files and refresh icon cache // Only do this on first run (when desktop file doesn't exist) qDebug() << ""First run detected - refreshing desktop database and icon cache""; refreshSystemCache(); } } // Whether desktop file is newly created or exists already, check and update Exec field if necessary updateDesktopField(userDesktopFilePath, ""Exec"", appImagePath); } #endif ",appIconPath 242,"#include ""config_parser_factory.h"" #include bool ConfigParserFactory::registerConfigParser( const std::string& name, ConfigParserCreateMethod createMethod, bool overwrite ) noexcept { if (overwrite) { _createMethods.insert_or_assign(name, createMethod); return true; } else { bool can_create = canCreateConfigParser(name); if (!can_create) _createMethods[name] = createMethod; return !can_create; } } std::shared_ptr ConfigParserFactory::createConfigParser( const std::string& name ) noexcept { if (canCreateConfigParser(name)) return _createMethods.at(name)(); return nullptr; } bool ConfigParserFactory::canCreateConfigParser(const std::string& name) noexcept { auto it = _createMethods.find(name); return it != _createMethods.end(); } std::vector ConfigParserFactory::registeredConfigParsers() noexcept { static constexpr auto key_selector = [](auto [MASK] ){ return [MASK] .first; }; std::vector keys(_createMethods.size()); std::transform(_createMethods.begin(), _createMethods.end(), keys.begin(), key_selector); return keys; } ",pair 243,"#include #include #include using namespace std; const int NUM_CITIES = 4; //calculate distance between two cities int dist(char city1, char city2) { // Example for 4 cities / input size if(city1 == 'A') { if(city2 == 'B') return 10; else if(city2 == 'C') return 20; else if(city2 == 'D') return 30; } else if(city1 == 'B') { if(city2 == 'A') return 10; else if(city2 == 'C') return 10; else if(city2 == 'D') return 20; } else if(city1 == 'C') { if(city2 == 'A') return 20; else if(city2 == 'B') return 10; else if(city2 == 'D') return 15; } else if(city1 == 'D') { if(city2 == 'A') return 30; else if(city2 == 'B') return 20; else if(city2 == 'C') return 15; } return -1; } vector nearest_neighbor(char start_city) { vector route; vector visited(NUM_CITIES, false); char [MASK] = start_city; route.push_back( [MASK] ); visited[ [MASK] - 'A'] = true; for (int i = 0; i < NUM_CITIES-1; i++) { int nearest_distance = INT_MAX; int nearest_city = -1; for (int j = 0; j < NUM_CITIES; j++) { if (!visited[j]) { int distance = dist( [MASK] , 'A' + j); if (distance < nearest_distance) { nearest_distance = distance; nearest_city = j; } } } [MASK] = 'A' + nearest_city; route.push_back( [MASK] ); visited[nearest_city] = true; } return route; } int main() { vector best_route = nearest_neighbor('A'); for (auto city : best_route) { cout << city << "" ""; } cout << endl; return 0; } ",current_city 244,"// mine sweeper.cpp : このファイルには 'main' 関数が含まれています。プログラム実行の開始と終了がそこで行われます。 // #define _SILENCE_FPOS_SEEKPOS_DEPRECATION_WARNING #include #include #include #include #include #include #include #include #include #include #include ""boost/spirit/include/qi.hpp"" namespace mnsw{ namespace { class bomb_exception : public std::exception { public: bomb_exception() : std::exception{""""} {} }; constexpr char BOMB_CHAR[] = "" B""; constexpr char FLAG_CHAR[] = ""!""; constexpr char NONE_CHAR[] = "" ""; constexpr char NOT_OPENED[] = ""■""; } class cell { bool bomb_; bool flag_; bool opened_; int bomb_around_; public: cell(bool bomb) noexcept : bomb_{bomb}, flag_{false}, opened_{false} {} cell() noexcept : bomb_{false}, flag_{false}, opened_{false} {} void print(std::ostream & out) const { if (flag_) { out << FLAG_CHAR; } else if (!opened_) { out << NOT_OPENED; } else if (bomb_around_) { out << ' ' << bomb_around_; } else { out << NONE_CHAR; } } /// /// mark as bomb or disable flag /// /// current flag state bool flag() noexcept { flag_ ^= true; return flag_; } /// /// open and THROW EXCEPTION IF BOMB IS HERE /// /// /// bomb count around this cell /// int open() noexcept(false) { if (flag_) return false; opened_ = true; if (bomb_) throw bomb_exception(); return bomb_around_; } void set_bomb_around(int bombcnt) noexcept { bomb_around_ = bombcnt; } void set_as_bomb() noexcept { bomb_ = true; } bool is_bomb() const noexcept { return bomb_; } bool is_opened() const noexcept { return opened_; } int get_around() const noexcept { return bomb_around_; } }; class map { std::vector map_; size_t open_cnt_; size_t width_, height_; size_t flag_, bomb_; size_t coord_to_idx(const std::pair & coord) { return width_ * coord.second + coord.first; } size_t coord_to_idx(std::pair && coord) { return coord_to_idx(coord); } auto idx_to_coord(size_t idx)->std::pair { return std::make_pair(idx % width_, idx / width_); } auto cells_around_cell(std::pair const & coord)->std::array{ std::array result{ nullptr }; /** * 0 1 2 * 3 4 * 5 6 7 **/ // flag is true, no elm in the direction bool top = coord.second == 0, bottom = coord.second == height_ - 1; bool left = coord.first == 0, right = coord.first == width_ - 1; // top lane if (!top) { for (auto i = (left ? 1ULL : 0ULL); i < (right ? 2ULL : 3ULL); i++) { result[i] = &map_.at(coord_to_idx({ coord.first + i - 1, coord.second - 1 })); } } // mid lane { if (!left) result[3] = &map_.at(coord_to_idx({ coord.first-1, coord.second })); if (!right) result[4] = &map_.at(coord_to_idx({ coord.first + 1, coord.second })); } // bottom lane if (!bottom) { for (auto i = (left ? 1ULL : 0ULL); i < (right ? 2ULL : 3ULL); i++) { result[i + 5] = &map_.at(coord_to_idx({ coord.first + i - 1, coord.second + 1 })); } } return result; } void init(std::pair first_coord) { const auto idx = coord_to_idx(first_coord); std::random_device rd; for (auto i = 0ULL; i < bomb_; i++) { map_.at(i).set_as_bomb(); } do { std::shuffle(std::begin(map_), std::end(map_), std::mt19937{rd()}); } while (map_.at(idx).is_bomb()); // count bomb around each cell auto is_bomb = [](cell const * c) {return c == nullptr ? 0 : static_cast(c->is_bomb()); }; for (auto i = 0ULL; i < width_ * height_; i++) { auto cur_coord = idx_to_coord(i); auto cells = cells_around_cell(cur_coord); int cnt(0); for (auto const & j : cells) cnt += is_bomb(j); map_.at(i).set_bomb_around(cnt); } } public: map(size_t width, size_t height, size_t bomb) : open_cnt_{ 0 } { set(width, height, bomb); } map() : open_cnt_{ 0 } {} void set(size_t width, size_t height, size_t bomb){ const std::pair size(std::min(9ull, width), std::min(9ull, height)); width_ = size.first; height_ = size.second; bomb_ = std::min(!bomb?1ULL:bomb, size.first * size.second / 2); map_.reserve(size.first * size.second + 20); for (auto i = 0ULL; i < size.first * size.second; i++) { map_.emplace_back(); } } /// /// open cell, invalid cell coordinate will be ignored /// /// cell coord /// cell coord /// @true : still alive; @false : game over size_t open(size_t x, size_t y) { if(open_cnt_ == 0)init({ x, y }); if (map_.at(coord_to_idx({ x,y })).is_opened()) return width_ * height_ - open_cnt_ - bomb_; open_cnt_++; try { if (!map_.at(coord_to_idx({ x, y })).open()) { for (auto & i : cells_around_cell({ x, y })) { if (!i) continue; auto coord = idx_to_coord(std::distance(&map_.front(), i)); open(coord.first, coord.second); } } } catch (bomb_exception&) { return 0; } return width_ * height_ - open_cnt_ - bomb_; } void flag(size_t x, size_t y) { map_.at(coord_to_idx({ x, y })).flag(); } void finish() { map_.clear(); } void print(std::ostream & out) { for (auto i = 0ULL; i < width_; i++) out << ' ' << i; for (auto i = 0ULL; i < width_ * height_; i++) { if (i % width_ == 0) out << std::endl << (char)('a' + i/width_); map_.at(i).print(out); } } }; class game { map map_; public: game() = default; /// /// make user's dreams come true. /// /// /// o [a-i]-[0-8] : open designated cell. /// f [a-i]-[0-8] : mark designated cell as bomb. /// s [0-9]-[0-9] [0-n] : (re)start at designated map size and bomb count. /// e : quit game /// /// /// @true : game is still continuing. /// @false : game is over. /// bool command(std::string_view cmd) { namespace qi = boost::spirit::qi; char comtype; char y; int x; int bomb_cnt; auto beg = std::begin(cmd); auto expr = qi::char_ >> qi::char_ >> '-' >> qi::int_ >> qi::int_; bool success = qi::phrase_parse(beg, std::end(cmd), expr, qi::space, comtype, y, x, bomb_cnt); std::stringstream ss; switch (comtype) { case 'o': if(!map_.open(x, y - 'a')) return false; break; case 'f': map_.flag(x, y - 'a'); break; case 's': map_.finish(); map_.set(x, y - 'a', bomb_cnt); break; case 'e': map_.finish(); return false; } map_.print(ss); std::cout << ss.str() << std::endl; return true; } }; } int main() { std::string [MASK] ; mnsw::game g; do { std::cout << std::endl << '>' << std::flush; std::getline(std::cin, [MASK] ); } while (g.command( [MASK] )); return 0; } ",combuf 245,"/*** libraries/EeValues/Examples/MyIdent/MyIdent.ino June 2015, ***/ // Ardu 1.5: Required to make EeValues class compile OK. #include #include #include /* ------------------------------------------------------------------- */ #define REC_IDENT MK4CODE('I','D', 'N', 'T') #define REC_EE_OFFSET 10 struct MyIdent { byte poll_addr; char SN[ 8 ]; } flim; EeValues eeMyIdent(REC_IDENT); /* ------------------------------------------------------------------- */ // #undef F // #define F(str) str void dump_some_ee() { Serial.println(); dumpEE( Serial, 0, 64 ); Serial.println(); } /* end dump_some_ee() */ boolean validate_record() { Serial.println(); boolean res = false; struct MyIdent [MASK] ; memset( & [MASK] , 0x55, sizeof( [MASK] ) ); eeoffset_t ee; byte * ptr; ee = eeMyIdent.lastStoredOffset() - 1; for( int cnt = eeMyIdent.userRecordSize() ; --cnt >= 0 ; --ee ) { ptr = (byte *) (((byte *)& [MASK] ) + cnt); eeMyIdent.readToUser( ee, ptr, 1 ); } if( memcmp( &flim, & [MASK] , sizeof( [MASK] ) ) == 0 ) { Serial.println( ""OK, single byte reading is correct."" ); res = true; } else { Serial.println( ""ERROR: single byte reading FAILED!!"" ); } return( res ); } /* end validate_record() */ void update_poll_addr() { if( eeMyIdent.userRecordSize() == sizeof(flim) ) { eeMyIdent.readToUser(); flim.poll_addr += 1; eeMyIdent.updateCrc8(); eeMyIdent.writeToEe(); } else { Serial.println( ""*** WRONG SIZE ***"" ); } } /* end update_poll_addr() */ /* ------------------------------------------------------------------- */ void setup() { // put your setup code here, to run once: Serial.begin(9600); delay(1000); eeMyIdent.setUserDataPtr( & flim ); eeMyIdent.setUserSize( sizeof(flim) ); // Go look for thing in EE. boolean res = false; #if EEVALUES_CONF_HUNT_FOR_RECORD res = eeMyIdent.findHeader(); if( res ) { Serial.print( ""Found it at EE offset $"" ); printHexWidth( Serial, eeMyIdent.eeOffsetOfHeader(), 3 ); Serial.println(); } else { // If none found, provide a default location in EEMEM. Serial.println( ""None found, so providing default location"" ); eeMyIdent.setEeOffset( REC_EE_OFFSET ); } #else eeMyIdent.setEeOffset( REC_EE_OFFSET ); res = eeMyIdent.isHeaderValid(); #endif if( res ) { Serial.print( F(""Found "") ); Serial.print( eeMyIdent.userRecordSize() ); Serial.println( F("" USER bytes in EE."") ); if( eeMyIdent.userRecordSize() == sizeof(flim) ) { eeMyIdent.readToUser(); } else { Serial.println( ""*** WRONG SIZE ***"" ); } } else { Serial.println( F(""No record found, creating default one..."") ); flim.poll_addr = 0x41 ; memcpy( flim.SN, ""12345678"", sizeof(flim.SN) ); eeMyIdent.updateCrc8(); eeMyIdent.writeToEe(); // Do a verification cycle, since this is an example sketch! eeMyIdent.setEeOffset( REC_EE_OFFSET ); res = eeMyIdent.isHeaderValid(); if( res ) { Serial.println( F(""Yes, EE block verified!!"") ); } else { Serial.println( F(""ERROR: EE BLOCK FAILURE VERIFICATION!!"") ); } } // See if can read EE one byte at a time. validate_record(); dump_some_ee(); Serial.print( F(""Bytes in heap = "") ); Serial.println( freeRam() ); // Menu of commands. Serial.println( ""Commands: E = Erase EEMEM ; D = Dump some EEMEM ; V = Validate Record ;"" ); Serial.println( "" U = Update record."" ); Serial.println(); } int ch; void loop() { // send data only when you receive data: if (Serial.available() > 0 && (ch = Serial.read()) > 0 ) { if( 'a' <= ch && ch <= 'z' ) // TOUPPER(ch) ch -= 0x020; // read the incoming byte. switch( ch ) { case 'E' : { EeValues erasure( 0 ); erasure.setEeOffset( 0 ); erasure.setUserSize( erasure.eeSize() - 16 ); erasure.eraseWholeRecord(); } Serial.println( ""EE erased."" ); break; case 'D' : dump_some_ee(); break; case 'U' : update_poll_addr(); break; case 'V' : validate_record(); break; } } } ",second_chance 246,"/* * Program Name: * CS 207 (Lec 001) - Project * Cyborg Headpiece (cs207-2017-project) * * Description: * A cyborg headpiece, by my definition, will be a piece of * wearable technology, affixed to the head of the wearer, * but made to look as though it is integrated into the * flesh of the wearer. * * This sketch will take inputs from an accelerometer and * a microphone, and then react to the inputs by driving * a NeoPixel Ring and NeoPixel Matrix respectively. * * * Legend: * (cp) - Adafruit Circuit Playground - Developer Edition * (nps) - Adafruit NeoPixel Shield for Arduino - 40 RGB LED Pixel Matrix * (npr) - Adafruit NeoPixel Ring - 24 x 5050 RGB LED * * Setup: * Connect Ext on (nps) to GND on (cp) * Connect 5V on (nps) to VBATT on (cp) * Connect Din on (nps) to #6 on (cp) * * Connect GND on (npr) to GND on (cp) * Connect PWR +5V on (npr) to VBATT on (cp) * Connect Data Input on (npr) to #3 on (cp) * * * Date: * 2017-04-05 * * Name: * * */ // Include Adafruit libraries for operation of Circuit Playground #include #include #include #include // Serial Communication details const int baud = 9600; // Which pins are connected to what const int pinShield = 6; const int pinRing = 3; // Stored time counts unsigned long previousMillisCPNeoPixel; unsigned long previousMillisShield; unsigned long previousMillisRing; // Motion delay thresholds int holdCPNeoPixel; int holdShield; int holdRing; // The NeoPixel on the Circuit Playground details const int cpNeoPixelCount = 10; int cpNeoPixel; int cpNeoPixelColor; // Adafruit NeoPixel Shield for Arduino - 40 RGB LED Pixel Matrix details const int shieldRows = 8; const int shieldCols = 5; int shieldTotal = shieldRows * shieldCols; Adafruit_NeoPixel shield = Adafruit_NeoPixel(shieldTotal, pinShield, NEO_GRB + NEO_KHZ800); int shieldY; // corresponds with rows int shieldX; // corresponds with cols // Adafruit NeoPixel Ring - 24 x 5050 RGB LED details const int ringTotal = 24; Adafruit_NeoPixel ring = Adafruit_NeoPixel(ringTotal, pinRing, NEO_GRB + NEO_KHZ800); int ringX; // Mode details boolean mode1State; boolean mode2State; // Mode details - Dot int dotDirection; boolean dotDouble; // Sound mechanism details const int soundSensorThresh = 339; const int soundSensorRange = 125; int soundSensorMax = soundSensorThresh + (soundSensorRange / 2); int soundSensorMin = soundSensorThresh - (soundSensorRange / 2); // Sound mechanism details - Bars const int soundBarNeoPixelCols = shieldCols; float soundBarNeoPixelColRatio[] = { 0.45, 0.85, 1.0, 0.85, 0.45 }; const int soundBarNeoPixelCount = shieldRows; int soundBarNeoPixelMin = 0; int soundBarNeoPixelMax = soundBarNeoPixelCount - 1; float soundBarNeoPixelMid = soundBarNeoPixelMax / 2.0; // sound bar active is used as follows: // 0 - inactive // 1 - active, bar goes up // -1 - active, bar goes down int soundBarActive; float soundBarRaw; boolean soundBarPeakLoActive; float soundBarPeakLo; boolean soundBarPeakHiActive; float soundBarPeakHi; const int soundBarDropRate = 1; // Accelerometer mechanism details const float accelThresh = 0.5; const float accelSensitivity = 0.03; float accelX; // + is force in direction towards power connector; - is force in direction towards microUSB connector float accelY; // + is force in direction towards pin #6 & #9; - is force in direction towards pin #0 & #2 float accelZ; // + is force in direction below playground; - is force in direction above playground // Accelerometer mechanism details - Dots const int accelDotXColor = 0; float accelDotX; const int accelDotYColor = 85; float accelDotY; const int accelDotZColor = 171; float accelDotZ; // If this is true, debug mode is on boolean stateDebug = false; void setup() { // run once at beginning // prepare serial output Serial.begin(baud); Serial.println(""Begin program""); // initialize Circuit Playground CircuitPlayground.begin(); // initialize NeoPixel Shield shield.begin(); shield.show(); // Initialize all pixels to 'off' // initialize NeoPixel Ring ring.begin(); ring.show(); // Initialize all pixels to 'off' // setting initial values for variables previousMillisShield = 0; previousMillisRing = 0; previousMillisCPNeoPixel = 0; holdShield = 300; holdRing = 50; holdCPNeoPixel = 75; cpNeoPixel = 0; cpNeoPixelColor = 0; shieldX = 3; shieldY = 0; ringX = 0; mode1State = false; mode2State = false; dotDirection = 1; dotDouble = false; soundBarActive = 0; soundBarRaw = soundBarNeoPixelMid; soundBarPeakLoActive = false; soundBarPeakLo = soundBarNeoPixelMid; soundBarPeakHiActive = false; soundBarPeakHi = soundBarNeoPixelMid; accelX = 0; accelY = 0; accelZ = 0; accelDotX = 0; accelDotY = 0; accelDotZ = 0; } void loop() { // run repeatedly // determine current time count unsigned long currentMillis = millis(); // detect inputs boolean stateSwitch = CircuitPlayground.slideSwitch(); boolean stateButton1 = CircuitPlayground.leftButton(); boolean stateButton2 = CircuitPlayground.rightButton(); int stateSoundSensor = CircuitPlayground.soundSensor(); float stateMotionX = CircuitPlayground.motionX(); float stateMotionY = CircuitPlayground.motionY(); float stateMotionZ = CircuitPlayground.motionZ(); // switch holds state, or releases state if (stateSwitch) { // check buttons if (stateButton1 != mode1State) { if (stateButton1) { // change direction of playground pattern dotDirection *= -1; } } if (stateButton2 != mode2State) { if (stateButton2) { // toggle double of playground pattern if (dotDouble) { dotDouble = false; } else { dotDouble = true; } } } // update mode states mode1State = stateButton1; mode2State = stateButton2; // run Circuit Playground NeoPixel reactor cpNeoPixelDisplay(currentMillis); // run sound reactor shieldDisplay(currentMillis, stateSoundSensor); // run accelerometer reactor ringDisplay(currentMillis, stateMotionX, stateMotionY, stateMotionZ); } /* // debuging code for displays if (stateDebug) { int pixel = 0; if (stateSwitch) { pixel = 5; } CircuitPlayground.clearPixels(); CircuitPlayground.setPixelColor(pixel, CircuitPlayground.colorWheel(0)); } */ // send message to serial output if (stateDebug) { // accelerometer details Serial.println(); Serial.print(""Switch: ""); Serial.print(stateSwitch); Serial.print("" But 1: ""); Serial.print(stateButton1); Serial.print("" But 2: ""); Serial.println(stateButton2); delay(120); } } void cpNeoPixelDisplay(unsigned long currentMillis) { // update Circuit Playground NeoPixels // change NeoPixel to illuminate if (currentMillis - previousMillisCPNeoPixel > holdCPNeoPixel) { previousMillisCPNeoPixel = currentMillis; cpNeoPixel += dotDirection; if (cpNeoPixel < 0) { cpNeoPixel += cpNeoPixelCount; } if (cpNeoPixel >= cpNeoPixelCount) { cpNeoPixel -= cpNeoPixelCount; } } // change colour of NeoPixel cpNeoPixelColor++; if (cpNeoPixelColor >= 255) { cpNeoPixelColor = 0; } // update NeoPixels CircuitPlayground.clearPixels(); CircuitPlayground.setPixelColor(cpNeoPixel, CircuitPlayground.colorWheel(cpNeoPixelColor)); if (dotDouble) { CircuitPlayground.setPixelColor(cpNeoPixelCount - cpNeoPixel - 1, CircuitPlayground.colorWheel(cpNeoPixelColor)); } } int shieldPixel(int row, int col) { // return the NeoPixel number for the desired row and col // remember that row 0 is first row, and col 0 is first col int pixel = (col * shieldRows) + row; return pixel; } void shieldDisplay(unsigned long currentMillis, int valueRaw) { // update shield display based on sound sensor value // map raw value to sound bar raw value soundBarRaw = float(soundBarNeoPixelMax - soundBarNeoPixelMin) / float(soundSensorMax - soundSensorMin) * float(valueRaw - soundSensorMin) + float(soundBarNeoPixelMin); // if sound bar raw value is outside range, limit soundBarRaw = constrain(soundBarRaw, soundBarNeoPixelMin - (soundBarNeoPixelCount / 2), soundBarNeoPixelMax + (soundBarNeoPixelCount / 2)); // decide if live bar should show something // 0 - no bar // 1 - bar above middle // -1 - bar below middle float soundBarActiveTest = (soundBarRaw - soundBarNeoPixelMid) * 10.0; if (abs(soundBarActiveTest) < 10) { soundBarActive = 0; } else { soundBarActive = abs(soundBarActiveTest) / soundBarActiveTest; } // slowly drop peak bars towards middle if (currentMillis - previousMillisShield > holdShield) { previousMillisShield = currentMillis; soundBarPeakLo += soundBarDropRate; if (soundBarPeakLo > soundBarNeoPixelMid) { soundBarPeakLo = soundBarNeoPixelMid; soundBarPeakLoActive = false; } soundBarPeakHi -= soundBarDropRate; if (soundBarPeakHi < soundBarNeoPixelMid) { soundBarPeakHi = soundBarNeoPixelMid; soundBarPeakHiActive = false; } } // if live bar is active, update appropriate peak bar, if necessary if (soundBarActive != 0) { if (soundBarActive > 0) { soundBarPeakHi = max(soundBarPeakHi, soundBarRaw); soundBarPeakHiActive = true; } else { soundBarPeakLo = min(soundBarPeakLo, soundBarRaw); soundBarPeakLoActive = true; } } // draw bars on shield for (int i = 0; i < soundBarNeoPixelCols; i++) { float ratio = soundBarNeoPixelColRatio[i]; float ratioPeakLo = (soundBarPeakLo - soundBarNeoPixelMid) * ratio + soundBarNeoPixelMid; float ratioPeakHi = (soundBarPeakHi - soundBarNeoPixelMid) * ratio + soundBarNeoPixelMid; float ratioRaw = (soundBarRaw - soundBarNeoPixelMid) * ratio + soundBarNeoPixelMid; for (int j = 0; j < soundBarNeoPixelCount; j++) { // set default colour to black int pickColor = 0; // if within peak bar ranges, change to peak colour if (soundBarPeakLoActive) { if ((j >= ratioPeakLo) && (j < soundBarNeoPixelMid)) { pickColor = 1; } } if (soundBarPeakHiActive) { if ((j <= ratioPeakHi) && (j > soundBarNeoPixelMid)) { pickColor = 1; } } // if within live bar range, change to live colour if (soundBarActive != 0) { if (soundBarActive > 0) { if ((j <= ratioRaw) && (j > soundBarNeoPixelMid)) { pickColor = 2; } } else { if ((j >= ratioRaw) && (j < soundBarNeoPixelMid)) { pickColor = 2; } } } int soundBarNeoPixelColorR; int soundBarNeoPixelColorG; int soundBarNeoPixelColorB; switch (pickColor) { case 1: // red soundBarNeoPixelColorR = 63; soundBarNeoPixelColorG = 0; soundBarNeoPixelColorB = 0; break; case 2: // green soundBarNeoPixelColorR = 0; soundBarNeoPixelColorG = 255; soundBarNeoPixelColorB = 0; break; default: // black soundBarNeoPixelColorR = 0; soundBarNeoPixelColorG = 0; soundBarNeoPixelColorB = 0; break; } // update NeoPixel colour (does not update shield immediately) int pixel = shieldPixel(j, i); shield.setPixelColor(pixel, soundBarNeoPixelColorR, soundBarNeoPixelColorG, soundBarNeoPixelColorB); } } // update shield shield.show(); } void ringDisplay(unsigned long currentMillis, float valueX, float valueY, float valueZ) { // update ring display based on accelerometer values // slow down the movements if (currentMillis - previousMillisRing > holdRing) { previousMillisRing = currentMillis; // turn off dots ring.setPixelColor(accelX, 0, 0, 0); ring.setPixelColor(accelY, 0, 0, 0); ring.setPixelColor(accelZ, 0, 0, 0); // accelerometer values are greater than threshold, move dot if (abs(valueX) > accelThresh) { accelX += valueX * accelSensitivity; if (accelX < 0) { accelX += ringTotal; } if (accelX > ringTotal) { accelX -= ringTotal; } } if (abs(valueY) > accelThresh) { accelY += valueY * accelSensitivity; if (accelY < 0) { accelY += ringTotal; } if (accelY > ringTotal) { accelY -= ringTotal; } } if (abs(valueZ) > accelThresh) { accelZ += valueZ * accelSensitivity; if (accelZ < 0) { accelZ += ringTotal; } if (accelZ > ringTotal) { accelZ -= ringTotal; } } } // find integers from tracked values int dotX = accelX; int dotY = accelY; int [MASK] = accelZ; // in case of overlapping, add colours together if (dotX == dotY) { if (dotX == [MASK] ) { ring.setPixelColor(dotX, 255, 255, 255); } else { ring.setPixelColor(dotX, 255, 0, 255); ring.setPixelColor( [MASK] , 0, 255, 0); } } else { if (dotX == [MASK] ) { ring.setPixelColor(dotX, 255, 255, 0); ring.setPixelColor(dotY, 0, 0, 255); } else { if (dotY == [MASK] ) { ring.setPixelColor(dotX, 255, 0, 0); ring.setPixelColor(dotY, 0, 255, 255); } else { ring.setPixelColor(dotX, 255, 0, 0); ring.setPixelColor(dotY, 0, 0, 255); ring.setPixelColor( [MASK] , 0, 255, 0); } } } // update ring ring.show(); } ",dotZ 247,"#include #include #include #include SoftwareSerial Serial2(3,4); // RX,TX #include ""Countimer.h"" Countimer DippingTimer; Countimer LiftingTimer; Countimer TrayTimer; #define LED_PIN A0 #define NUM_LEDS A1 #define BUZZER_PIN 5 #define HALL_SENSOR 6 #define TRAY_HALL_SENSOR 7 CRGB leds[NUM_LEDS]; int EN_1 = 8; int EN_2 = 9; int STEP_1 = 10; int STEP_2 = 11; int DIR_1 = 12; int DIR_2 = 13; AccelStepper myStepper(1, STEP_1, DIR_1); //Number of Motors,StepPin,DirPin AccelStepper myStepper_2(1, STEP_2, DIR_2); const byte numChars = 200; char receivedChars[numChars]; char tempChars[numChars]; int valuesCount = 0; bool dataarrived=0; float Data[74]={0.0}; boolean newData = false; long Homing=-1; long TrayHoming=-1; int Cycles=0; bool Dipped=1; bool Withdraw=1; bool flage=1; bool flage2=1; bool flage3=0; bool flage4=1; bool flage5=0; bool flage6=0; bool Donesim=1; bool activelight=0; int count=0; char global_rc; int total_cycle_count = 1; int currentPosition = 0; void setup() { pinMode(EN_1, OUTPUT); digitalWrite(EN_1, LOW); pinMode(EN_2, OUTPUT); digitalWrite(EN_2, LOW); pinMode(BUZZER_PIN,OUTPUT); //FastLED.addLeds(leds, NUM_LEDS); pinMode(HALL_SENSOR, INPUT); pinMode(TRAY_HALL_SENSOR, INPUT); homefunction(); Serial.begin(9600); Serial2.begin(9600); //DippingTimer.setCounter(0, 0, 10, DippingTimer.COUNT_UP, onComplete); //LiftingTimer.setCounter(0, 0, 10, LiftingTimer.COUNT_UP, onComplete1); DippingTimer.setInterval(DippingTimeDisp, 1000); // For Displaying Time every 1sec LiftingTimer.setInterval(LiftingTimeDisp, 1000); TrayTimer.setInterval(TrayTimeDisp, 1000); } void loop() { DippingTimer.run(); LiftingTimer.run(); recvWithStartEndMarkers(); if (newData == true){ memcpy(tempChars, receivedChars, numChars * sizeof(char)); parseData(); showParsedData(); flage=1; flage2=1; flage3=1; flage4=1; flage5=1; Donesim=1; Cycles=0; count=0; currentPosition = myStepper.currentPosition(); newData = false; } CheckCycle(0); CheckCycle(6); CheckCycle(12); CheckCycle(18); CheckCycle(24); CheckCycle(30); if(Donesim==1){ if(count==0){ Serial2.print(""n2.val=1\xFF\xFF\xFF""); Sumulation(2); } else if(count==1){ Serial2.print(""n2.val=2\xFF\xFF\xFF""); Sumulation(9); } else if(count==2){ Serial2.print(""n2.val=3\xFF\xFF\xFF""); Sumulation(16); } else if(count==3){ Serial2.print(""n2.val=4\xFF\xFF\xFF""); Sumulation(23); } } if(activelight==1){ for (int i = 2; i >= 0; i--) { leds[i] = CRGB ( 0, 0, 255); FastLED.show(); activelight=0; } } } void recvWithStartEndMarkers() { static boolean [MASK] = false; static byte ndx = 0; char startMarker = '<'; char endMarker = '>'; char rc; while (Serial2.available() > 0) { rc = Serial2.read(); delay(1); if (rc == startMarker) { [MASK] = true; } else if ( [MASK] == true) { if (rc != endMarker) { receivedChars[ndx] = rc; ndx++; if (ndx >= numChars) { ndx = numChars - 1; } } else { receivedChars[ndx] = '\0'; // terminate the string Serial.println(receivedChars); [MASK] = false; ndx = 0; newData = true; } } if (rc=='U'){ Serial.println(""Move Up""); MoveUp(); } else if (rc=='D'){ Serial.println(""Move Down""); MoveDown(); } else if (rc=='H'){ Serial.println(""Homing""); homefunction(); } else if (rc=='S'){ Serial.println(""Stop""); StopMotor(); } else if (rc=='R'){ Serial.println(""Sound""); if(flage6==0){ flage6=1; } else{ tone(BUZZER_PIN, 350); // Send 1KHz sound signal... delay(1000); // ...for 1 sec noTone(BUZZER_PIN); // Stop sound... flage6=0; } } else if (rc=='Q'){ Serial.println(""LED""); } else if(rc=='g'){ Donesim=0; Data[74]={0.0}; homefunction(); } global_rc=rc; } } void parseData() { // split the data into parts and convert it to Float char * strtokIndx; // strtok() index strtokIndx = strtok(tempChars,"",""); while (strtokIndx != NULL && valuesCount < 74){ Data[valuesCount++] = atof(strtokIndx); strtokIndx = strtok(NULL, "",""); } valuesCount = 0; // Reset the Count Data[0]='X'; Data[2]='Y'; Data[4]='Z'; Data[6]='A'; Data[13]='B'; Data[20]='C'; Data[27]='D'; Data[34]='m'; Data[36]='h'; Data[38]='t'; Data[44]='e'; Data[50]='p'; Data[56]='y'; Data[62]='s'; Data[68]='w'; } void showParsedData() { // For Deubgging for(int e = 0;e<74;e++){ Serial.print(Data[e]); Serial.print("" ""); } Serial.println(); } void DippingTimeDisp(){ // Displaying Dipping Time Serial2.print(""n0.val=""); Serial2.print(DippingTimer.getCurrentSeconds()); Serial2.print(""\xFF\xFF\xFF""); } void LiftingTimeDisp(){ // Displaying Lifting Time Serial2.print(""n0.val=""); Serial2.print(LiftingTimer.getCurrentSeconds()); Serial2.print(""\xFF\xFF\xFF""); } void TrayTimeDisp(){ // Displaying Lifting Time Serial2.print(""n4.val=""); Serial2.print(TrayTimer.getCurrentSeconds()); Serial2.print(""\xFF\xFF\xFF""); } void onComplete() { // For Deubgging } void onComplete1() { // For Deubgging } void onComplete2() { // For Deubgging } void onComplete3() { // For Deubgging } void homefunction() { for (int i = 2; i >= 0; i--) { leds[i] = CRGB ( 255, 0, 0); FastLED.show(); } while (digitalRead(HALL_SENSOR) == LOW) { myStepper.setMaxSpeed(1000); myStepper.setAcceleration(2000); myStepper.moveTo(Homing); //CCW Homing--; myStepper.run(); } myStepper.setCurrentPosition(0); //reset postion TrayHome(); myStepper_2.setMaxSpeed(200); myStepper_2.setAcceleration(200); myStepper_2.moveTo(450); //CW 1mm increment myStepper_2.runToPosition(); myStepper.setMaxSpeed(1000); myStepper.setAcceleration(2000); myStepper.moveTo(5250); //CW 1mm increment myStepper.runToPosition(); myStepper.setCurrentPosition(0); //reset postion myStepper_2.setCurrentPosition(0); //reset postion activelight=1; } void LiftHome(){ while (digitalRead(HALL_SENSOR) == LOW) { myStepper.setMaxSpeed(1000); myStepper.setAcceleration(2000); myStepper.moveTo(Homing); //CCW Homing--; myStepper.run(); } Homing=0; while (digitalRead(HALL_SENSOR) == HIGH) { myStepper.setMaxSpeed(1000); myStepper.setAcceleration(2000); myStepper.moveTo(Homing); //CCW Homing++; myStepper.run(); } } void TrayHome(){ while(digitalRead(TRAY_HALL_SENSOR) == LOW){ //if else atılacak pinleri ayırmak için ! myStepper_2.setMaxSpeed(250); myStepper_2.setAcceleration(125); myStepper_2.moveTo(TrayHoming); //CW 1mm increment TrayHoming--; myStepper_2.run(); } myStepper_2.setCurrentPosition(0); //reset postion } void MoveUp(){ myStepper.setCurrentPosition(0); //reset postion myStepper.setMaxSpeed(1000); myStepper.setAcceleration(2000); myStepper.moveTo(-4000); //CCW 10mm increment while( myStepper.distanceToGo() !=0 && digitalRead(HALL_SENSOR) == 0 && Serial2.available()==0 ){ myStepper.run(); } myStepper.setCurrentPosition(0); //reset postion } void MoveDown(){ myStepper.setCurrentPosition(0); //reset postion myStepper.setMaxSpeed(1000); myStepper.setAcceleration(2000); myStepper.moveTo(4000); while( myStepper.distanceToGo() !=0 && Serial2.available()==0){ myStepper.run(); } myStepper.setCurrentPosition(0); //reset postion } void StopMotor(){ myStepper.setCurrentPosition(0); //reset postion myStepper.stop(); } void StopMotor_2(){ myStepper_2.setCurrentPosition(0); //reset postion myStepper_2.stop(); } void motor_tray_move(){ myStepper_2.setCurrentPosition(0); myStepper_2.setMaxSpeed(200); myStepper_2.setAcceleration(200); myStepper_2.moveTo(725); //CCW 10mm increment while( myStepper_2.distanceToGo() !=0 && digitalRead(TRAY_HALL_SENSOR) == 0){ //Hall Sensör kontrol edilecek, diğer motor en tepeye ulaştığında dönmesi lazım myStepper_2.run(); } myStepper_2.setCurrentPosition(0); //reset postion } void reverse_motor_tray_move(){ myStepper_2.setCurrentPosition(0); myStepper_2.setMaxSpeed(200); myStepper_2.setAcceleration(200); myStepper_2.moveTo(-725); //CW 10mm increment while( myStepper_2.distanceToGo() !=0 && digitalRead(TRAY_HALL_SENSOR) == 0){ //Hall Sensör kontrol edilecek, diğer motor en tepeye ulaştığında dönmesi lazım myStepper_2.run(); } myStepper_2.setCurrentPosition(0); //reset postion } void reset() { flage = 1; flage2 = 1; flage3 = 1; flage4 = 0; flage5 = 1; Cycles = 0; Dipped = 1; Withdraw = 1; Donesim = 1; // Reset Nextion screen values DippingTimer.setInterval(DippingTimeDisp, 1000); // For Displaying Time every 1sec LiftingTimer.setInterval(LiftingTimeDisp, 1000); TrayTimer.setInterval(TrayTimeDisp, 1000); } void Done(){ Donesim=0; Serial2.print(""n0.val=0\xFF\xFF\xFF""); Serial2.print(""n1.val=0\xFF\xFF\xFF""); Serial2.print(""n2.val=0\xFF\xFF\xFF""); Serial2.print(""n3.val=0\xFF\xFF\xFF""); Serial2.print(""n4.val=0\xFF\xFF\xFF""); Serial2.print(""t10.txt=""); Serial2.print(""\""""); Serial2.print(""Done""); Serial2.print(""\""""); Serial2.print(""\xFF\xFF\xFF""); /*Homing=0; TrayHoming=0; while (digitalRead(HALL_SENSOR) == LOW) { myStepper.setMaxSpeed(500); myStepper.setAcceleration(1000); myStepper.moveTo(Homing); //CCW Homing--; myStepper.run(); } while (digitalRead(TRAY_HALL_SENSOR) == LOW) { myStepper_2.setMaxSpeed(200); myStepper_2.setAcceleration(200); myStepper_2.moveTo(TrayHoming); //CW 1mm increment TrayHoming--; myStepper_2.run(); } myStepper.setCurrentPosition(0); //reset postion myStepper.setMaxSpeed(1000); myStepper.setAcceleration(2000); myStepper.moveTo(5250); while( myStepper.distanceToGo() !=0 && Serial2.available()==0){ myStepper.run(); } myStepper_2.setCurrentPosition(0); //reset postion myStepper_2.setMaxSpeed(200); myStepper_2.setAcceleration(200); myStepper_2.moveTo(375); while( myStepper_2.distanceToGo() !=0 && Serial2.available()==0){ myStepper_2.run(); } */ myStepper.setCurrentPosition(0); //reset postion myStepper_2.setCurrentPosition(0); //reset postion if(flage6==0){ while(true){ tone(BUZZER_PIN, 350); // Send 1KHz sound signal... delay(1000); // ...for 1 sec noTone(BUZZER_PIN); // Stop sound... delay(300); global_rc = Serial2.read(); if(global_rc=='k' || global_rc=='o'){ homefunction(); break; } } noTone(BUZZER_PIN); } } void Next(){ Serial2.print(""page 4""); // Upload Simulation Screen In Nextion Display Serial2. print(""\xFF\xFF\xFF""); Serial2.print(""n4.val=0\xFF\xFF\xFF""); Serial2.print(""n3.val=""); Serial2.print(total_cycle_count); Serial2.print(""\xFF\xFF\xFF""); Serial2.print(""t10.txt=""); Serial2.print(""\""""); Serial2.print(""Next""); Serial2.print(""\""""); Serial2.print(""\xFF\xFF\xFF""); } void TimerSet(){ Serial2.print(""n0.val=0\xFF\xFF\xFF""); Serial2.print(""n1.val=0\xFF\xFF\xFF""); Serial2.print(""n2.val=0\xFF\xFF\xFF""); } void TrayCheck(){ if(count == 0){ if(Data[7] == 0 || (Data[14]!=0 || Data[21]!=0 || Data[28]!=0) || global_rc!='g'){ Serial.println(""Hoşgeldin Ebubekir Sıddık Bebek""); reset(); Next(); LiftHome(); motor_tray_move(); } else{ //Done(); } } else if(count == 1){ if(Data[21]!=0 || Data[28]!=0 || global_rc!='g'){ Serial.println(""Şemseddin""); reset(); Next(); LiftHome(); motor_tray_move(); } else{ //Done(); } } else if(count == 2){ if(Data[28]!=0 || global_rc!='g'){ Serial.println(""Fatih Sultan Mehmet""); reset(); Next(); LiftHome(); reverse_motor_tray_move(); } else{ //Done(); } } } void CheckCycle(int a){ if(Data[39+a]==total_cycle_count && total_cycle_count!=Data[35]){ if(Data[40+a]==0 && count==0){ count=1; Serial.println(""BOM-1""); LiftHome(); motor_tray_move(); } else if(Data[41+a]==0 && count==1){ count=2; Serial.println(""BOM-2""); LiftHome(); motor_tray_move(); } else if(Data[42+a]==0 && count==2){ count=3; Serial.println(""BOM-3""); LiftHome(); reverse_motor_tray_move(); } else if(Data[43+a]==0 && count==3){ count=0; total_cycle_count++; Serial.println(""BOM-4""); TrayTimer.setCounter(0, 0, Data[37], TrayTimer.COUNT_DOWN, onComplete2); TrayTimer.start(); TimerSet(); for(int i = 0;i < 5*Data[37];i+=1){ TrayTimer.run(); TrayTimer.setInterval(TrayTimeDisp, 1000); delay(200); } Serial2.print(""n0.val=0\xFF\xFF\xFF""); Serial2.print(""n1.val=0\xFF\xFF\xFF""); Serial2.print(""n2.val=0\xFF\xFF\xFF""); Serial2.print(""n3.val=""); Serial2.print(total_cycle_count); Serial2.print(""\xFF\xFF\xFF""); Serial2.print(""n4.val=0\xFF\xFF\xFF""); Serial2.print(""t10.txt=""); Serial2.print(""\""""); Serial2.print(""NC""); Serial2.print(""\""""); Serial2.print(""\xFF\xFF\xFF""); LiftHome(); while (digitalRead(TRAY_HALL_SENSOR) == LOW) { myStepper_2.setMaxSpeed(200); myStepper_2.setAcceleration(200); myStepper_2.moveTo(TrayHoming); //CW 1mm increment TrayHoming--; myStepper_2.run(); } myStepper_2.setCurrentPosition(0); //reset postion myStepper_2.setMaxSpeed(200); myStepper_2.setAcceleration(200); myStepper_2.moveTo(400); while( myStepper_2.distanceToGo() !=0 && Serial2.available()==0){ myStepper_2.run(); } reset(); } } } void Sumulation(int t){ Serial2.print(""n3.val=""); Serial2.print(total_cycle_count); Serial2.print(""\xFF\xFF\xFF""); if(Data[5+t]>0 && Data[6+t]>0 && Data[7+t]>0 && Data[8+t]>0 && Data[9+t]>0 && Data[5+t]<=20 && Data[8+t]<=20 && global_rc!='g'){ if(Cycles=1.0 ){ if(flage==1){ // Upload the Simualtion Page for one time only Serial2.print(""page 4""); // Upload Simulation Screen In Nextion Display Serial2. print(""\xFF\xFF\xFF""); reset(); for (int i = 0; i <= 2; i++) { leds[i] = CRGB ( 0, 255, 0); FastLED.show(); } flage=0; } if(flage2==1){ // Setting the Time for the counter DippingTimer.setCounter(0, 0, Data[7+t], DippingTimer.COUNT_DOWN, onComplete); LiftingTimer.setCounter(0, 0, Data[9+t], LiftingTimer.COUNT_DOWN, onComplete1); flage2=0; } //////////////////// Dipping Process ////////////////////// if(!DippingTimer.isCounterCompleted()){ Serial2.print(""t10.txt=""); Serial2.print(""\""""); Serial2.print(""Dip""); Serial2.print(""\""""); Serial2.print(""\xFF\xFF\xFF""); // myStepper.setCurrentPosition(0); //reset postion if(Dipped==1){ myStepper.setMaxSpeed(200*Data[5+t]); myStepper.setAcceleration(20000); myStepper.moveTo(200*Data[6+t]); while(myStepper.distanceToGo() !=0 ){ myStepper.run(); if(global_rc=='g'){ myStepper.distanceToGo() == 0; } } } if(myStepper.distanceToGo() == 0 && Dipped==1){ DippingTimer.start(); //Start The Dipping Time myStepper.setCurrentPosition(0); //reset postion Dipped=0; } } //////////////////// Withdrawal Process ////////////////////// if( DippingTimer.isCounterCompleted() && !LiftingTimer.isCounterCompleted() ){ Serial2.print(""t10.txt=""); Serial2.print(""\""""); Serial2.print(""Lift""); Serial2.print(""\""""); Serial2.print(""\xFF\xFF\xFF""); //myStepper.setCurrentPosition(0); //reset postion if(Withdraw==1){ myStepper.setMaxSpeed(200*Data[8+t]); myStepper.setAcceleration(20000); myStepper.moveTo(-200*Data[6+t]); while(myStepper.distanceToGo() !=0 && digitalRead(HALL_SENSOR) == 0 ){ myStepper.run(); if(global_rc=='g'){ myStepper.distanceToGo() == 0; } } } if(myStepper.distanceToGo() == 0 && Withdraw==1){ LiftingTimer.start(); //Start The Lifting Time myStepper.setCurrentPosition(0); //reset postion Withdraw=0; } } //////////////////// Reset Process /////////////////////////// if(DippingTimer.isCounterCompleted() && LiftingTimer.isCounterCompleted()){ Cycles++; Serial2.print(""n1.val=""); Serial2.print(Cycles); Serial2.print(""\xFF\xFF\xFF""); Dipped=1; Withdraw=1; DippingTimer.restart(); LiftingTimer.restart(); DippingTimer.pause(); LiftingTimer.pause(); } } else if(Cycles>=Data[10+t] && Data[10+t]>=1){ if(count==0){ TrayTimer.setCounter(0, 0, Data[1], TrayTimer.COUNT_DOWN, onComplete2); TrayTimer.start(); TimerSet(); for(int i = 0;i < 5*Data[1];i+=1){ TrayTimer.run(); TrayTimer.setInterval(TrayTimeDisp, 1000); delay(200); } TrayCheck(); } else if(count==1){ TrayTimer.setCounter(0, 0, Data[3], TrayTimer.COUNT_DOWN, onComplete2); TrayTimer.start(); TimerSet(); for(int i = 0;i < 5*Data[3];i+=1){ TrayTimer.run(); TrayTimer.setInterval(TrayTimeDisp, 1000); delay(200); } TrayCheck(); } else if(count==2){ TrayTimer.setCounter(0, 0, Data[5], TrayTimer.COUNT_DOWN, onComplete2); TrayTimer.start(); TimerSet(); for(int i = 0;i < 5*Data[5];i+=1){ TrayTimer.run(); TrayTimer.setInterval(TrayTimeDisp, 1000); delay(200); } TrayCheck(); } else if(count==3){ if(total_cycle_count==Data[35]){ total_cycle_count=1; flage3=0; Done(); } else{ total_cycle_count++; Serial.println(""Yukarı""); Serial.println(total_cycle_count); TrayTimer.setCounter(0, 0, Data[37], TrayTimer.COUNT_DOWN, onComplete2); TrayTimer.start(); TimerSet(); for(int i = 0;i < 5*Data[37];i+=1){ TrayTimer.run(); TrayTimer.setInterval(TrayTimeDisp, 1000); delay(200); } Serial2.print(""n0.val=0\xFF\xFF\xFF""); Serial2.print(""n1.val=0\xFF\xFF\xFF""); Serial2.print(""n2.val=0\xFF\xFF\xFF""); Serial2.print(""n3.val=""); Serial2.print(total_cycle_count); Serial2.print(""\xFF\xFF\xFF""); Serial2.print(""n4.val=0\xFF\xFF\xFF""); Serial2.print(""t10.txt=""); Serial2.print(""\""""); Serial2.print(""NC""); Serial2.print(""\""""); Serial2.print(""\xFF\xFF\xFF""); LiftHome(); while (digitalRead(TRAY_HALL_SENSOR) == LOW) { myStepper_2.setMaxSpeed(200); myStepper_2.setAcceleration(200); myStepper_2.moveTo(TrayHoming); //CW 1mm increment TrayHoming--; myStepper_2.run(); } myStepper_2.setCurrentPosition(0); //reset postion myStepper_2.setMaxSpeed(200); myStepper_2.setAcceleration(200); myStepper_2.moveTo(450); while( myStepper_2.distanceToGo() !=0 && Serial2.available()==0){ myStepper_2.run(); } count=-1; reset(); } } Serial.println(""Sultan Selim geliyor!""); count++; } } else if(Data[5+t]<=0 || Data[6+t]<=0 || Data[7+t]<=0 || Data[8+t]<=0 || Data[9+t]<=0 || Data[5+t]>20 || Data[8+t]>20 || global_rc=='g'){ Serial.println(count); if(count==3 && flage3==1){ if(total_cycle_count==Data[35]){ Serial.println(""69""); total_cycle_count=1; flage3=0; Done(); } else{ Serial.println(""77""); total_cycle_count++; Serial.println(""Aşağı""); Serial.println(total_cycle_count); TrayTimer.setCounter(0, 0, Data[37], TrayTimer.COUNT_DOWN, onComplete2); TrayTimer.start(); TimerSet(); for(int i = 0;i < 5*Data[37];i+=1){ TrayTimer.run(); TrayTimer.setInterval(TrayTimeDisp, 1000); delay(200); } Serial2.print(""n0.val=0\xFF\xFF\xFF""); Serial2.print(""n1.val=0\xFF\xFF\xFF""); Serial2.print(""n2.val=0\xFF\xFF\xFF""); Serial2.print(""n3.val=""); Serial2.print(total_cycle_count); Serial2.print(""\xFF\xFF\xFF""); Serial2.print(""n4.val=0\xFF\xFF\xFF""); Serial2.print(""t10.txt=""); Serial2.print(""\""""); Serial2.print(""NC""); Serial2.print(""\""""); Serial2.print(""\xFF\xFF\xFF""); LiftHome(); while (digitalRead(TRAY_HALL_SENSOR) == LOW) { myStepper_2.setMaxSpeed(200); myStepper_2.setAcceleration(200); myStepper_2.moveTo(TrayHoming); //CW 1mm increment TrayHoming--; myStepper_2.run(); } myStepper_2.setCurrentPosition(0); //reset postion myStepper_2.setMaxSpeed(200); myStepper_2.setAcceleration(200); myStepper_2.moveTo(450); while(myStepper_2.distanceToGo() !=0 && Serial2.available()==0){ myStepper_2.run(); } count=-1; reset(); } } if(flage5==1){ Serial.println(""Şakşuka""); TrayCheck(); } count++; Serial.println(""Sultan Selim gelemedi!""); } } //MS",recvInProgress 248,"/* XBee TX test for a Arduino Mega2560 using Serial3 as the XBee serial input for a Series 2 XBee. This is NOT based on the examples that come with the Arduino XBee library. See, the examples there and most other places on the web SUCK. Andrew's library is much easier to use than the illustrations would lead you to believe. This is a HEAVILY commented example of how send a text packet using series 2 XBees. Series 1 XBees are left as an exercise for the student. */ #include #include #include SoftwareSerial mySerial(8, 9); // RX, TX XBee xbee = XBee(); // This is the XBee broadcast address. You can use the address // of any device you have also. XBeeAddress64 Broadcast = XBeeAddress64(0x00000000, 0x0000ffff); char Hello[] = ""Hello World""; char Buffer[128]; // this needs to be longer than your longest packet. void setup() { // start serial Bridge.begin(); Console.begin(); // and the software serial port mySerial.begin(9600); // now that they are started, hook the XBee into // Software Serial xbee.setSerial(mySerial); Console.println(""Initialization all done!""); } void loop() { ZBTxRequest [MASK] = ZBTxRequest(Broadcast, (uint8_t *)Hello, strlen(Hello)); xbee.send( [MASK] ); delay(2000); strcpy(Buffer,""I saw what you did last night.""); [MASK] = ZBTxRequest(Broadcast, (uint8_t *)Buffer, strlen(Buffer)); xbee.send( [MASK] ); delay(2000); } ",zbtx 249,"#include ""http_server_interface.h"" Server_interface::Server_interface(std::string host, unsigned short port) { this->host = net::ip::make_address(host); this->port = port; } template http::message_generator Server_interface::handle_request(http::request>&& request) { std::vector request_tokens = parse_request_string(request.target()); try { if (request.target().empty() || request.target()[0] != '/' || request.target().find("".."") != beast::string_view::npos) throw Bad_request_error{ request.version(), request.keep_alive(), ""Illegal request-target"" }; switch (request.method()) { case http::verb::get: { std::string response_body; if (request_tokens.size() == 3) response_body = mongo_schedule_db.query_document(request_tokens[PARITY], ""day"", request_tokens[DAY]); else if (request_tokens.size() < 3) response_body = mongo_schedule_db.query_collection(request_tokens[PARITY]); if (response_body == ""-1"") throw Resource_not_found_error{ request.version(), request.keep_alive(), ""Requested week type not found"" }; http::response response{ std::piecewise_construct, std::make_tuple(std::move(response_body)), std::make_tuple(http::status::ok, request.version()), }; response.set(http::field::server, ""RedArmy.il""); response.prepare_payload(); response.keep_alive(response.keep_alive()); return response; } break; case http::verb::post: { if (request_tokens[2] == ""add"") { std::cout << request.body() << std::endl; try { mongo_schedule_db.insert_collection(request_tokens[PARITY], request.body()); } catch (std::exception &e) { throw Internal_server_error{ request.version(), request.keep_alive(), ""Failed to load data from string"" }; } http::response response{ http::status::ok, request.version(), }; response.set(http::field::server, ""RedArmy.il""); response.body() = ""it is all OK!""; response.prepare_payload(); response.keep_alive(response.keep_alive()); return response; } else if (request_tokens.size() == 5 && request_tokens[4] == ""comment"") { try { mongo_schedule_db.add_comment(request_tokens[PARITY], request_tokens[DAY], request_tokens[CLASS_NUM], request.body()); } catch (std::exception& e) { throw Internal_server_error{ request.version(), request.keep_alive(), ""Failed to load data from string"" }; } http::response response{ http::status::ok, request.version(), }; response.set(http::field::server, ""RedArmy.il""); response.body() = ""it is all OK!""; response.prepare_payload(); response.keep_alive(response.keep_alive()); return response; } else if (request_tokens[1] == ""drop"") { if (request_tokens.size() == 3) { mongo_schedule_db.drop_schedule(request_tokens[2]); } else { mongo_schedule_db.drop_schedule(""odd"", ""even""); } http::response response{ http::status::ok, request.version(), }; response.set(http::field::server, ""RedArmy.il""); response.body() = ""it is all OK!""; response.prepare_payload(); response.keep_alive(response.keep_alive()); return response; } else { throw Internal_server_error{ request.version(), request.keep_alive(), ""OOPS! The developer is probably a dummy :3"" }; } } break; } } catch (Exception e) { return e.what(); } } void fail(boost::beast::error_code ec, std::string what) { std::cout << what << "":"" << ec.message() << std::endl; } void Server_interface::manage_session(tcp::socket&& connection) { boost::beast::flat_buffer read_req_buffer; boost::beast::error_code ec; while (true) { http::request request; http::read(connection, read_req_buffer, request, ec); if (ec == http::error::end_of_stream) break; if (ec) return fail(ec, ""read""); http::message_generator response_message = handle_request(std::move(request)); bool keepalive = response_message.keep_alive(); boost::beast::write(connection, std::move(response_message), ec); if (ec) return fail(ec, ""write""); if (!keepalive) break; } connection.shutdown(tcp::socket::shutdown_send); } void Server_interface::accept_connections() { tcp::acceptor [MASK] { this->ioc, {this->host, this->port} }; while (true) { tcp::socket new_connection{ this->ioc }; [MASK] .accept(new_connection); std::cout << ""Connected:"" << new_connection.remote_endpoint() << std::endl; std::thread thr(&Server_interface::manage_session, this, std::move(new_connection)); thr.detach(); } } ",connections_acceptor 250,"#include #include #include #include #include ""header/Engineer.h"" MYSQL mysql; MYSQL_RES *res;//这个结构代表返回行的一个查询结果集 MYSQL_ROW column;//一个行数据的类型安全(type-safe)的表示 using namespace std; bool connectMysql(); void freeConnect(); bool updateData(const string& sql); bool outMysql(); bool queryDatabase(const string& sql); bool addEngineer(const Engineer& engineer); void updateEngineerInfos(const string& engineer_number); void updateEngineerInfo(const string& engineer_number); void deleteEngineer(const string& engineer_number); void sortByEngineer(); void selectEngineer(); void selectAllEngineer(); bool createFile(); int main() { bool page1 = true; connectMysql(); while (page1) { cout << ""***********************"" << endl; cout << ""*欢迎来到软件工程师管理系统*"" << endl; cout << ""*****请选择以下功能:*****"" << endl; cout << ""***********************"" << endl; cout << ""***1、显示全部工程师信息***"" << endl; cout << ""***2、条件查询工程师信息***"" << endl; cout << ""***3、添加单个工程师信息***"" << endl; cout << ""***4、条件修改工程师信息***"" << endl; cout << ""***5、删除单个工程师信息***"" << endl; cout << ""***6、按条件排序薪水信息***"" << endl; cout << ""***7、导出目前工程师信息***"" << endl; cout << ""***8、退出工程师管理系统***"" << endl; cout << ""***********************"" << endl; cout << ""你的选择是:"" << endl; int selection1 = 0; cin >> selection1; if (selection1 == 1) { selectAllEngineer(); cout << ""查询完毕,输入任一数字返回主菜单……"" << endl; getchar(); getchar(); } else if (selection1 == 2) { bool page2 = true; while (page2) { selectEngineer(); cout << ""是否继续查询?(是/否==1/其他数字)"" << endl; int selection2 = 0; cin >> selection2; if (selection2 == 1) { continue; } else { page2 = false; } } } else if (selection1 == 3) { bool page2 = true; while (page2) { Engineer engineer; int engineer_number = 0; cout << ""请输入工号:"" << endl; bool page3 = true; while (page3) { cin >> engineer_number; if (engineer_number <= 0 || engineer_number > 1000) { page3 = true; cout << ""范围在0-1000,输入有误,请重新输入……"" << endl; } else { page3 = false; } } engineer.setEngineerNumber(engineer_number); string engineer_name; string engineer_gender; string engineer_degree; int engineer_age; int engineer_salary; string engineer_address; string engineer_phone; cout << ""请输入姓名:"" << endl; cin >> engineer_name; cout << ""请输入性别:"" << endl; cin >> engineer_gender; cout << ""请输入学位:"" << endl; cin >> engineer_degree; cout << ""请输入年龄:"" << endl; cin >> engineer_age; cout << ""请输入薪水:"" << endl; cin >> engineer_salary; cout << ""请输入地址:"" << endl; cin >> engineer_address; cout << ""请输入电话:"" << endl; cin >> engineer_phone; engineer.setEngineerName(engineer_name); engineer.setEngineerGender(engineer_gender); engineer.setEngineerDegree(engineer_degree); engineer.setEngineerAge(engineer_age); engineer.setEngineerSalary(engineer_salary); engineer.setEngineerAddress(engineer_address); engineer.setEngineerPhone(engineer_phone); addEngineer(engineer); cout << ""是否继续添加?(是/否==1/其他数字)"" << endl; int selection2 = 0; cin >> selection2; if (selection2 == 1) { continue; } else { page2 = false; } } } else if (selection1 == 4) { bool page2 = true; while (page2) { cout << ""请选择一下修改方式:(输入其他数字则表示退出选择)"" << endl; cout << ""1.全部信息修改"" << endl; cout << ""2.部分信息修改"" << endl; cout << ""你的选择是:"" << endl; int selection2 = 0; cin >> selection2; if (selection2 == 1) { cout << ""请输入需要修改的工程师工号:"" << endl; string engineer_number; cin >> engineer_number; updateEngineerInfos(engineer_number); } else if (selection2 == 2) { cout << ""请输入需要修改的工程师工号:"" << endl; string engineer_number; cin >> engineer_number; updateEngineerInfo(engineer_number); } else { cout << ""正在退出……"" << endl; page2 = false; } cout << ""是否继续修改?(是/否==1/其他数字)"" << endl; cin >> selection2; if (selection2 == 1) { continue; } else { page2 = false; } } } else if (selection1 == 5) { bool page2 = true; while (page2) { cout << ""请输入你要删除的工程师工号:"" << endl; string engineer_number; cin >> engineer_number; deleteEngineer(engineer_number); cout << ""是否继续删除?(是/否==1/其他数字)"" << endl; int selection2 = 0; cin >> selection2; if (selection2 == 1) { continue; } else { page2 = false; } } } else if (selection1 == 6) { bool page2 = true; while (page2) { sortByEngineer(); cout << ""是否继续排序?(是/否==1/其他数字)"" << endl; int selection2 = 0; cin >> selection2; if (selection2 == 1) { continue; } else { page2 = false; } } } else if (selection1 == 7) { createFile(); cout << ""保存成功,路径在D:\\work.txt!输入任一数字退出……"" << endl; getchar(); getchar(); } else if (selection1 == 8) { int selection2 = 0; cout << ""是否退出系统(是/否 == 1/其他数字):"" << endl; cin >> selection2; if (selection2 == 1) { page1 = false; } else { page1 = true; cout << ""取消退出成功!正在返回主菜单……"" << endl; } } else { page1 = true; cout << ""输入有误!输入任一数字返回主菜单……"" << endl; getchar(); getchar(); } } freeConnect(); return 0; } /** * 获取数据库连接 * @return */ bool connectMysql() { mysql_init(&mysql);//初始化mysql if (!(mysql_real_connect(&mysql, ""localhost"",//主机 ""root"",//用户名 """",//密码 ""cpp_database"",//数据库名 3306,//端口号 nullptr, 0//最后两个参数的常用写法 ))) { cout << ""连接数据库出错:"" + (string) mysql_error(&mysql) << endl; return false; } else { cout << ""已经连接数据库!"" << endl; return true; } } /** * 释放连接 */ void freeConnect() { mysql_free_result(res); mysql_close(&mysql); } /** * 作更新操作 * @param sql * @return */ bool updateData(const string& sql) { mysql_query(&mysql, ""set names gbk"");//设置编码格式 否则mysql里中文乱码 // 执行SQL语句 // 0 执行成功 // 1 执行失败 if (mysql_query(&mysql, sql.c_str())) {//mysql_query第二个参数只接受const char* 需要将string类型转化 cout << ""更新数据库失败 ( "" + (string) mysql_error(&mysql) + "" )"" << endl; return false; } else { cout << ""数据库更新成功!"" << endl; return true; } } /** * 打印查询到的数据 */ bool outMysql() { if (mysql_affected_rows(&mysql) != 0) { //打印数据行数 cout << ""查询工程师数量为: "" << mysql_affected_rows(&mysql) << endl; char *field[32];//字段名 int num = mysql_num_fields(res);//获取列数 for (int i = 0; i < num; ++i) {//获取字段名 field[i] = mysql_fetch_field(res)->name; } for (int i = 0; i < num; ++i) { cout << (string) field[i] << ""\t""; } cout << endl; column = mysql_fetch_row(res); while (column) {//获取一行数据 for (int i = 0; i < num; ++i) { cout << column[i] << ""\t""; } cout << endl; column = mysql_fetch_row(res); } return true; } else { cout << ""查询结果数量为:"" << mysql_affected_rows(&mysql) << "",请确认后查询!"" << endl; return false; } } /** * 查询数据库 * @param sql * @return */ bool queryDatabase(const string& sql) { mysql_query(&mysql, ""set names gbk"");//设置编码格式 否则cmd下中文乱码 // 执行SQL语句 // 0 执行成功 // 1 执行失败 if (mysql_query(&mysql, sql.c_str())) {//mysql_query第二个参数只接受const char* 需要将string类型转化 cout << ""查询失败 ( "" + (string) mysql_error(&mysql) + "" )"" << endl; return false; } else { cout << ""正在查询……"" << endl; } //获得结果集 MYSQL_RES *res; if (!(res = mysql_store_result(&mysql))) { cout << ""Couldn't get result from "" + (string) mysql_error(&mysql) << endl; return false; } bool b = outMysql();//打印结果 return b; } /** * 添加一个工程师信息 * @param engineer_number * @param engineer_name * @param engineer_gender * @param engineer_degree * @param engineer_age * @param engineer_salary * @param engineer_address * @param engineer_phone */ bool addEngineer(const Engineer& engineer) { mysql_query(&mysql, ""set names gbk"");//设置编码格式 否则cmd下中文乱码 // 执行SQL语句 // 0 执行成功 // 1 执行失败 string sql = ""select * from t_engineer where engineer_number = "" + to_string(engineer.getEngineerNumber()); if (mysql_query(&mysql, sql.c_str())) {//mysql_query第二个参数只接受const char* 需要将string类型转化 cout << ""查询失败 ( "" + (string) mysql_error(&mysql) + "" )"" << endl; return false; } else { cout << ""正在查询……"" << endl; } //获得结果集 MYSQL_RES *res; if (!(res = mysql_store_result(&mysql))) { cout << ""Couldn't get result from "" + (string) mysql_error(&mysql) << endl; return false; } if (mysql_affected_rows(&mysql) != 0) { cout << ""工号重复,请重新输入!"" << endl; return false; } else { updateData(""insert into t_engineer values(null,'"" + to_string(engineer.getEngineerNumber()) + ""','"" + engineer.getEngineerName() + ""','"" + engineer.getEngineerGender() + ""','"" + engineer.getEngineerDegree() + ""','"" + to_string(engineer.getEngineerAge()) + ""','"" + to_string(engineer.getEngineerSalary()) + ""','"" + engineer.getEngineerAddress() + ""','"" + engineer.getEngineerPhone() + ""')""); cout << to_string(engineer.getEngineerNumber()) << ""号员工添加成功!"" << endl; return true; } } /** * 根据工号更新一个工程师所有信息 * @param engineer_number */ void updateEngineerInfos(const string& engineer_number) { cout << ""该工程师信息如下:"" << endl; bool b = queryDatabase( ""select engineer_number 工号,engineer_name 姓名,engineer_gender 性别,engineer_degree 学位,engineer_age 年龄,engineer_salary 薪水,engineer_address 地址,engineer_phone 电话 from t_engineer where engineer_number = "" + engineer_number); if (!b) { return; } string engineer_name; string engineer_gender; string engineer_degree; string engineer_age; string engineer_salary; string engineer_address; string engineer_phone; cout << ""请输入修改后的姓名:"" << endl; cin >> engineer_name; cout << ""请输入修改后的性别:"" << endl; cin >> engineer_gender; cout << ""请输入修改后的学位:"" << endl; cin >> engineer_degree; cout << ""请输入修改后的年龄:"" << endl; cin >> engineer_age; cout << ""请输入修改后的薪水:"" << endl; cin >> engineer_salary; cout << ""请输入修改后的地址:"" << endl; cin >> engineer_address; cout << ""请输入修改后的电话:"" << endl; cin >> engineer_phone; updateData( ""update t_engineer set engineer_name = '"" + engineer_name + ""',engineer_gender = '"" + engineer_gender + ""',engineer_degree = '"" + engineer_degree + ""',engineer_age = "" + engineer_age + "",engineer_salary = "" + engineer_salary + "",engineer_address = '"" + engineer_age + ""',engineer_phone = '"" + engineer_phone + ""' where engineer_number = "" + engineer_number); cout << engineer_number << ""号员工修改成功!"" << endl; } /** * 根据工号更新一个工程师某项信息 * @param engineer_number */ void updateEngineerInfo(const string& engineer_number) { cout << ""该工程师信息如下:"" << endl; bool b = queryDatabase( ""select engineer_number 工号,engineer_name 姓名,engineer_gender 性别,engineer_degree 学位,engineer_age 年龄,engineer_salary 薪水,engineer_address 地址,engineer_phone 电话 from t_engineer where engineer_number = "" + engineer_number); if (!b) { return; } int selection = 0; cout << ""请选择你要修改的信息:(输入其他数字表示退出选择)"" << endl; cout << ""1.姓名"" << endl; cout << ""2.性别"" << endl; cout << ""3.学位"" << endl; cout << ""4.年龄"" << endl; cout << ""5.薪水"" << endl; cout << ""6.地址"" << endl; cout << ""7.电话"" << endl; cin >> selection; if (selection == 1) { string engineer_name; cout << ""请输入修改后的姓名:"" << endl; cin >> engineer_name; updateData(""update t_engineer set engineer_name = '"" + engineer_name + ""' where engineer_number = '"" + engineer_number + ""'""); cout << engineer_number << ""号员工修改成功!"" << endl; } else if (selection == 2) { string engineer_gender; cout << ""请输入修改后的性别:"" << endl; cin >> engineer_gender; updateData(""update t_engineer set engineer_gender = '"" + engineer_gender + ""' where engineer_number = '"" + engineer_number + ""'""); cout << engineer_number << ""号员工修改成功!"" << endl; } else if (selection == 3) { string engineer_degree; cout << ""请输入修改后的学位:"" << endl; cin >> engineer_degree; updateData(""update t_engineer set engineer_degree = '"" + engineer_degree + ""' where engineer_number = '"" + engineer_number + ""'""); cout << engineer_number << ""号员工修改成功!"" << endl; } else if (selection == 4) { string engineer_age; cout << ""请输入修改后的年龄:"" << endl; cin >> engineer_age; updateData(""update t_engineer set engineer_age = '"" + engineer_age + ""' where engineer_number = '"" + engineer_number + ""'""); cout << engineer_number << ""号员工修改成功!"" << endl; } else if (selection == 5) { string engineer_salary; cout << ""请输入修改后的薪水:"" << endl; cin >> engineer_salary; updateData(""update t_engineer set engineer_salary = '"" + engineer_salary + ""' where engineer_number = '"" + engineer_number + ""'""); cout << engineer_number << ""号员工修改成功!"" << endl; } else if (selection == 6) { string engineer_address; cout << ""请输入修改后的地址:"" << endl; cin >> engineer_address; updateData(""update t_engineer set engineer_address = '"" + engineer_address + ""' where engineer_number = '"" + engineer_number + ""'""); cout << engineer_number << ""号员工修改成功!"" << endl; } else if (selection == 7) { string engineer_phone; cout << ""请输入修改后的电话:"" << endl; cin >> engineer_phone; updateData(""update t_engineer set engineer_phone = '"" + engineer_phone + ""' where engineer_number = '"" + engineer_number + ""'""); cout << engineer_number << ""号员工修改成功!"" << endl; } else { cout << ""正在退出……"" << endl; return; } cout << ""修改完毕,输入任一数字以退出……"" << endl; getchar(); getchar(); } /** * 根据工号删除一个工程师信息 * @param engineer_number */ void deleteEngineer(const string& engineer_number) { cout << ""该工程师删除前信息如下:"" << endl; bool b = queryDatabase( ""select engineer_number 工号,engineer_name 姓名,engineer_gender 性别,engineer_degree 学位,engineer_age 年龄,engineer_salary 薪水,engineer_address 地址,engineer_phone 电话 from t_engineer where engineer_number = "" + engineer_number); if (!b) { return; } updateData(""delete from t_engineer where engineer_number = '"" + engineer_number + ""'""); } /** * 升序排序 */ void sortByEngineer() { cout << ""请选择一下排序方式:(输入其他数字则表示退出选择)"" << endl; cout << ""1.升序排序"" << endl; cout << ""2.降序排序"" << endl; int selection = 0; cin >> selection; if (selection == 1) { queryDatabase( ""select engineer_number 工号,engineer_name 姓名,engineer_gender 性别,engineer_degree 学位,engineer_age 年龄,engineer_salary 薪水,engineer_address 地址,engineer_phone 电话 from t_engineer order by engineer_salary""); } else if (selection == 2) { queryDatabase( ""select engineer_number 工号,engineer_name 姓名,engineer_gender 性别,engineer_degree 学位,engineer_age 年龄,engineer_salary 薪水,engineer_address 地址,engineer_phone 电话 from t_engineer order by engineer_salary desc""); } else { cout << ""正在退出……"" << endl; return; } } /** * 根据条件查询工程师信息 */ void selectEngineer() { cout << ""请选择一下查找方式:(输入其他数字则表示退出选择)"" << endl; cout << ""1.工号查找"" << endl; cout << ""2.姓名查找"" << endl; cout << ""3.学历查找"" << endl; int selection = 0; cin >> selection; if (selection == 1) { cout << ""请输入工号:"" << endl; string engineer_number; cin >> engineer_number; queryDatabase( ""select engineer_number 工号,engineer_name 姓名,engineer_gender 性别,engineer_degree 学位,engineer_age 年龄,engineer_salary 薪水,engineer_address 地址,engineer_phone 电话 from t_engineer where engineer_number = "" + engineer_number); } else if (selection == 2) { cout << ""请输入姓名:"" << endl; string engineer_name; cin >> engineer_name; queryDatabase( ""select engineer_number 工号,engineer_name 姓名,engineer_gender 性别,engineer_degree 学位,engineer_age 年龄,engineer_salary 薪水,engineer_address 地址,engineer_phone 电话 from t_engineer where engineer_name = '"" + engineer_name + ""'""); } else if (selection == 3) { cout << ""请输入学历:"" << endl; string engineer_degree; cin >> engineer_degree; queryDatabase( ""select engineer_number 工号,engineer_name 姓名,engineer_gender 性别,engineer_degree 学位,engineer_age 年龄,engineer_salary 薪水,engineer_address 地址,engineer_phone 电话 from t_engineer where engineer_degree = '"" + engineer_degree + ""'""); } else { cout << ""正在退出……"" << endl; return; } cout << ""查询完毕,输入任一数字以退出……"" << endl; getchar(); getchar(); } /** * 查询数据库中所有工程师的信息 */ void selectAllEngineer() { queryDatabase( ""select engineer_number 工号,engineer_name 姓名,engineer_gender 性别,engineer_degree 学位,engineer_age 年龄,engineer_salary 薪水,engineer_address 地址,engineer_phone 电话 from t_engineer""); } /** * 生成txt文件 */ bool createFile() { mysql_query(&mysql, ""set names gbk"");//设置编码格式 否则cmd下中文乱码 // 执行SQL语句 // 0 执行成功 // 1 执行失败 string sql = ""select engineer_number 工号,engineer_name 姓名,engineer_gender 性别,engineer_degree 学位,engineer_age 年龄,engineer_salary 薪水,engineer_address 地址,engineer_phone 电话 from t_engineer""; if (mysql_query(&mysql, sql.c_str())) {//mysql_query第二个参数只接受const cahr* 需要将string类型转化 cout << ""查询失败 ( "" + (string) mysql_error(&mysql) + "" )"" << endl; return false; } //获得结果集 MYSQL_RES *res; if (!(res = mysql_store_result(&mysql))) { cout << ""Couldn't get result from "" + (string) mysql_error(&mysql) << endl; return false; } std::ofstream [MASK] (""d:\\work.txt"", std::ofstream::out); char *field[32];//字段名 int num = mysql_num_fields(res);//获取列数 for (int i = 0; i < num; ++i) {//获取字段名 field[i] = mysql_fetch_field(res)->name; } for (int i = 0; i < num; ++i) { [MASK] << (((string) field[i]) + ""\t ""); } [MASK] << endl; column = mysql_fetch_row(res); while (column) {//获取一行数据 for (int i = 0; i < num; ++i) { [MASK] << column[i] << ""\t ""; } [MASK] << endl; column = mysql_fetch_row(res); } [MASK] .close(); return true; }",OsWrite 251,"#define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define __NR_set_bpf_level 440 #define PAGE_SHIFT 12 #define PAGE_SIZE (1 << PAGE_SHIFT) #define READ_SIZE_SHIFT 9 #define READ_SIZE (1 << READ_SIZE_SHIFT) #define MAX_PAGE_INDEX (1 << 23) using namespace std::chrono; using namespace std; int num_thread; int num_file; int level; long iteration; long *latency_measure; char **file_names; long sys_bpf_set_level(int fd, int level) { return syscall(__NR_set_bpf_level, fd, level); } void read_key(int fd, long index, void *buffer) { off_t [MASK] = lseek(fd, index << PAGE_SHIFT, SEEK_SET); if ( [MASK] != index << PAGE_SHIFT) { printf(""lseek error, errno %d, ret: %ld\n"", errno, [MASK] ); exit(1); } int read_ret = read(fd, buffer, READ_SIZE); if (read_ret != READ_SIZE) { printf(""read error, errno %d, ret: %d\n"", errno, read_ret); exit(1); } } void read_thread_fn(int thread_idx) { unsigned int seedp = thread_idx; void *buffer = aligned_alloc(PAGE_SIZE, PAGE_SIZE); if (!buffer) { printf(""cannot allocate buffer\n""); exit(1); } memset(buffer, 0, PAGE_SIZE); int *fd_arr = (int *) malloc(num_file * sizeof(int)); if (!fd_arr) { printf(""cannot allocate fs array\n""); exit(1); } for (int file_idx = 0; file_idx < num_file; ++file_idx) { fd_arr[file_idx] = open(file_names[file_idx], O_DIRECT | O_RDONLY); if (fd_arr[file_idx] < 0) { printf(""cannot open file, errno: %d\n"", errno); exit(1); } long sys_ret = sys_bpf_set_level(fd_arr[file_idx], level); if (sys_ret < 0) { printf(""sys_bpf_set_level error, ret: %ld\n"", sys_ret); exit(1); } } steady_clock::time_point *start_time_arr = new steady_clock::time_point[iteration]; if (!start_time_arr) { printf(""cannot allocate start_time_arr\n""); exit(1); } steady_clock::time_point *end_time_arr = new steady_clock::time_point[iteration]; if (!end_time_arr) { printf(""cannot allocate end_time_arr\n""); exit(1); } for (long i = 0; i < iteration; i++) { start_time_arr[i] = steady_clock::now(); read_key(fd_arr[rand_r(&seedp) % num_file], rand_r(&seedp) % MAX_PAGE_INDEX, buffer); end_time_arr[i] = steady_clock::now(); } for (long i = 0; i < iteration; i++) { auto duration = duration_cast(end_time_arr[i] - start_time_arr[i]); latency_measure[thread_idx * iteration + i] = duration.count(); } } int main(int argc, char *argv[]) { if (argc < 5) { printf(""Usage: %s \n"", argv[0]); exit(1); } sscanf(argv[1], ""%d"", &num_thread); sscanf(argv[2], ""%d"", &level); sscanf(argv[3], ""%ld"", &iteration); num_file = argc - 4; file_names = argv + 4; latency_measure = (long *) malloc(sizeof(long) * num_thread * iteration); if (!latency_measure) { printf(""cannot allocate measurements\n""); return 1; } memset(latency_measure, 0, sizeof(long) * num_thread * iteration); thread *read_threads = new thread[num_thread]; for (int i = 0; i < num_thread; i++) { read_threads[i] = thread(read_thread_fn, i); } for (int i = 0; i < num_thread; i++) { read_threads[i].join(); } for (long i = 0; i < num_thread * iteration; ++i) { printf(""%ld\n"", latency_measure[i]); } } ",lseek_ret 252,"#include #include #include #include #include #include #include #include #include class LimitReachedException : public std::exception { public: [[nodiscard(""exception"")]] const char *what() const noexcept override { return ""PriorityQueueWithMessagesTimestamps limit reached""; } }; using priority_type = std::int16_t; template using message_t = std::tuple; template struct priority_less { constexpr bool operator()(const message_t & lhs, const message_t& rhs) { return std::get<0>(lhs) < std::get<0>(rhs); }; }; template >, typename Comp = priority_less > class PriorityQueueWithMessagesTimestamps : protected std::priority_queue, Container_t, Comp> { public: using value_type = typename Container_t::value_type; using reference = typename Container_t::reference; using const_reference = typename Container_t::const_reference; using size_type = typename Container_t::size_type; using container_type = Container_t; PriorityQueueWithMessagesTimestamps() = default; PriorityQueueWithMessagesTimestamps( const PriorityQueueWithMessagesTimestamps &) = default; PriorityQueueWithMessagesTimestamps(PriorityQueueWithMessagesTimestamps &&) = default; PriorityQueueWithMessagesTimestamps & operator=(const PriorityQueueWithMessagesTimestamps &) = default; PriorityQueueWithMessagesTimestamps & operator=(PriorityQueueWithMessagesTimestamps &&) = default; bool empty() { clear_expired(); return this->c.empty(); } size_t size() { clear_expired(); return this->c.size(); } void pop() { clear_expired(); std::priority_queue, Container_t, Comp>::pop(); } void push(const message_t &value) { clear_expired(); if (this->c.size() >= max_amount) { clear_expired(); if (this->c.size() >= max_amount) { throw LimitReachedException(); } } std::priority_queue, Container_t, Comp>::push(value); } template void emplace(Args &&...args) { clear_expired(); if (this->c.size() >= max_amount) { throw LimitReachedException(); } std::priority_queue, Container_t, Comp>::emplace( std::forward(args)...); } const message_t& top() { clear_expired(); return this->c.front(); } void clear_expired() { auto expired = [now = std::chrono::system_clock::now()]( const message_t &m) { return std::get<1>(m) < now; }; auto new_end = std::remove_if(this->c.begin(), this->c.end(), expired); this->c.erase(new_end, this->c.end()); std::make_heap(this->c.begin(), this->c.end(), Comp{}); } void set_max_amount(uint64_t max_amount) { this->max_amount = max_amount; } [[nodiscard]] uint64_t get_max_amount() const { return max_amount; } template friend class QueueAnalyzer; private: uint64_t max_amount = 50; }; namespace fs = std::filesystem; template >, typename Comp = priority_less > class QueueAnalyzer { public: QueueAnalyzer( const PriorityQueueWithMessagesTimestamps &queue) : queue_(queue) {} void analyze(const fs::path &file_path) { std::ofstream file(file_path, std::ios::out | std::ios::trunc); if (!file.is_open()) { throw std::runtime_error(""Failed to open file for writing.""); } // Get the current time const auto [MASK] = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); file << ""Current time: "" << std::ctime(& [MASK] ); // Get the size of the queue in KiB const auto queue_size_kib = (queue_.c.size() * sizeof(typename Container_t::value_type)) >> 10; file << ""Queue size: "" << queue_.c.size() << ""\n""; file << ""Queue size (KiB): "" << queue_size_kib << ""\n""; // Calculate the percentage of messages by their priority std::unordered_map count; count.reserve(queue_.c.size()); for (const auto &message : queue_.c) { if (count.find(std::get<0>(message)) == count.end()) { count[std::get<0>(message)] = 1; } else { ++count[std::get<0>(message)]; }; } file << ""Priority distribution:\n""; for (const auto &pair : count) { const auto percentage = (pair.second * 100.0) / queue_.c.size(); file << ""Priority "" << pair.first << "": "" << percentage << ""%\n""; } // Get the max time difference of messages if (!queue_.c.empty()) { const auto minmax_it = std::minmax_element(queue_.c.begin(), queue_.c.end(), [](const auto &lhs, const auto &rhs) { return std::get<1>(lhs) < std::get<1>(rhs); }); const auto &oldest_message = *minmax_it.first; const auto &newest_message = *minmax_it.second; const auto max_time_diff = std::chrono::duration_cast( std::get<1>(newest_message) - std::get<1>(oldest_message)) .count(); file << ""Max time difference of messages (s): "" << max_time_diff << ""\n""; } file.close(); } private: const PriorityQueueWithMessagesTimestamps &queue_; }; ",current_time 253,"#include ""Microtask.h"" #include ""SharedPointer.h"" #include ""SharedValue.h"" #include ""helper.h"" using namespace llvm; Microtask::Microtask(CallInst *fork_call) { _fork_call = fork_call; // Get the microtask function from the fork calls arguments Value *microtask_arg = fork_call->getArgOperand(2); _function = dyn_cast(microtask_arg->stripPointerCasts()); // Collect the shared variables for (Argument &argument : _function->args()) { // The first shared variable has index 2 if (argument.getArgNo() > 1) { //_shared_variables.push_back(new SharedVariable(&argument, _function)); int pointer_depth = get_pointer_depth(&argument); assert(pointer_depth > 0 && ""Shared Variable is not of pointer type""); _shared_variables.push_back(&argument); // if (pointer_depth == 1) // { // _shared_variables.push_back(&argument); // } // else // { // _shared_variables.push_back(&argument); // } } } auto call_instructions = get_instruction_in_function(_function); // Look for a parallel for inside the microtask; ParallelForData tmp_parallel_for; tmp_parallel_for.init = nullptr; tmp_parallel_for.fini = nullptr; for (auto &call : call_instructions) { std::vector function_list = { ""__kmpc_for_static_init_4"", ""__kmpc_for_static_init_4u"", ""__kmpc_for_static_init_8"", ""__kmpc_for_static_init_8u""}; if (is_in_list(call->getCalledFunction()->getName(), function_list)) { tmp_parallel_for.init = call; } else if (call->getCalledFunction()->getName().equals(""__kmpc_for_static_fini"")) { tmp_parallel_for.fini = call; } if (tmp_parallel_for.init != nullptr && tmp_parallel_for.fini != nullptr) { _parallel_for.push_back(tmp_parallel_for); tmp_parallel_for.init = nullptr; tmp_parallel_for.fini = nullptr; } } // Look for a reduction inside the microtask; ReductionData [MASK] ; [MASK] .reduce = nullptr; [MASK] .end_reduce = nullptr; for (auto &call : call_instructions) { std::vector function_list_start = {""__kmpc_reduce_nowait"", ""__kmpc_reduce""}; std::vector function_list_end = {""__kmpc_end_reduce_nowait"", ""__kmpc_end_reduce""}; if (is_in_list(call->getCalledFunction()->getName(), function_list_start)) { [MASK] .reduce = call; } else if (is_in_list(call->getCalledFunction()->getName(), function_list_end)) { [MASK] .end_reduce = call; } if ( [MASK] .reduce != nullptr && [MASK] .end_reduce != nullptr) { _reduction.push_back( [MASK] ); [MASK] .reduce = nullptr; [MASK] .end_reduce = nullptr; } } // Look for a critical inside the microtask CriticalData tmp_critical_data; tmp_critical_data.critical = nullptr; tmp_critical_data.end_critical = nullptr; for (auto &call : call_instructions) { if (call->getCalledFunction()->getName().equals(""__kmpc_critical"")) { tmp_critical_data.critical = call; } else if (call->getCalledFunction()->getName().equals(""__kmpc_end_critical"")) { tmp_critical_data.end_critical = call; } if (tmp_critical_data.critical != nullptr && tmp_critical_data.end_critical != nullptr) { _critical.push_back(tmp_critical_data); tmp_critical_data.critical = nullptr; tmp_critical_data.end_critical = nullptr; } } } Microtask::~Microtask() {} CallInst *Microtask::get_fork_call() { return _fork_call; } Function *Microtask::get_function() { return _function; } std::vector *Microtask::get_parallel_for() { if (_parallel_for.size() > 0) { return &_parallel_for; } else { return nullptr; } } std::vector *Microtask::get_reductions() { if (_reduction.size() > 0) { return &_reduction; } else { return nullptr; } } std::vector *Microtask::get_critical() { if (_critical.size() > 0) { return &_critical; } else { return nullptr; } } bool Microtask::has_shared_variables() { return _shared_variables.size(); } std::vector &Microtask::get_shared_variables() { return _shared_variables; } ",tmp_reduction_data 254,"#include #include #include #include #include #include #include #include #include #include int main()//int argc, const char **argv) { //std::map args = docopt::docopt(USAGE, //{ std::next(argv), std::next(argv, argc) }, //true,// show help if requested //""Naval Fate 2.0"");// version string //for (auto const &arg : args) { //std::cout << arg.first << arg.second << std::endl; //} //Use the default logger (stdout, multi-threaded, colored) spdlog::info(""Starting ImGui + SFML""); sf::RenderWindow [MASK] (sf::VideoMode(1024, 1024), ""ImGui + SFML = <3""); [MASK] .setFramerateLimit(60); ImGui::SFML::Init( [MASK] ); constexpr auto scale_factor = 2; ImGui::GetStyle().ScaleAllSizes(scale_factor); ImGui::GetIO().FontGlobalScale = scale_factor; sf::CircleShape shape(400.f); shape.setFillColor(sf::Color::Green); sf::Clock deltaClock; while ( [MASK] .isOpen()) { sf::Event event; while ( [MASK] .pollEvent(event)) { ImGui::SFML::ProcessEvent(event); if (event.type == sf::Event::Closed) { [MASK] .close(); } } ImGui::SFML::Update( [MASK] , deltaClock.restart()); ImGui::Begin(""Hello, world!""); ImGui::Button(""Look at this pretty button""); ImGui::End(); [MASK] .clear(); [MASK] .draw(shape); ImGui::SFML::Render( [MASK] ); [MASK] .display(); } ImGui::SFML::Shutdown(); return 0; } ",window 255,"#include ""esp_adc_cal.h"" #include ""QuickMedianLib.h"" #include ""esp_adc_cal.h"" #include #include #include #include #include ""driver/touch_sensor.h"" Preferences preferences; // #define DEBUG #ifdef DEBUG // TEMP - Display for debugging #include ""Free_Fonts.h"" #include ""SPI.h"" #include ""TFT_eSPI.h"" // Use hardware SPI TFT_eSPI tft = TFT_eSPI(); #endif #define DEFAULT_REFRESH_RATE 60 #define NUM_SAMPLES 10 #define TOUCHPIN T5 #define VOLTPIN 32 #define VOLTCHAN ADC1_CHANNEL_4 #define SERVER_NAME ""RV Server"" #define SERVICE_UUID ""68f9860f-4946-4031-8107-9327cd9f92ca"" #define TOUCH_CHARACTERISTIC_UUID ""bcdd0001-b67f-46c7-b2b8-e8a385ac70fc"" #define VOLTAGE_CHARACTERISTIC_UUID ""bcdd0002-b67f-46c7-b2b8-e8a385ac70fc"" #define TOUCH_CALIBRATION_CHARACTERISTIC_UUID ""bcdd0011-b67f-46c7-b2b8-e8a385ac70fc"" #define REFRESH_RATE_CHARACTERISTIC_UUID ""bcdd0005-b67f-46c7-b2b8-e8a385ac70fc"" #define TOUCH_CALIBRATION_PREF_KEY ""calibration"" #define RW_MODE false static esp_adc_cal_characteristics_t adc1_value; int voltRawValues[NUM_SAMPLES]; int touchValues[NUM_SAMPLES]; BLECharacteristic *bleTouchValue; BLECharacteristic *bleVoltageValue; BLECharacteristic *bleTouchCalibration; BLECharacteristic *bleRefreshRate; int refreshRate = DEFAULT_REFRESH_RATE; std::string calibrationData = ""0:0""; // format: value:percentage,value:percentage,... class MyServerCallbacks: public BLEServerCallbacks { void onConnect(BLEServer* pServer) { pServer->startAdvertising(); // restart advertising }; void onDisconnect(BLEServer* pServer) { pServer->startAdvertising(); // restart advertising } }; class RefreshRateWriteCallback : public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) { uint8_t *byteRefreshRate = pCharacteristic->getData(); size_t size = pCharacteristic->getLength(); if (size != 4) { Serial.print('Invalid length for refresh: '); Serial.println(size); return; } refreshRate = byteRefreshRate[0]; Serial.print(""Refresh rate updated to: ""); Serial.println(refreshRate); } }; class CalibrationWriteCallback : public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) { calibrationData = pCharacteristic->getValue(); Serial.print(""Received calibration data:'""); Serial.print(calibrationData.c_str()); Serial.println(""'""); if (!validCalibrationData(calibrationData)) { Serial.println(""Calibration invalid - ignoring""); } else { preferences.begin(""rvsetting"", RW_MODE); preferences.putString(TOUCH_CALIBRATION_PREF_KEY, calibrationData.c_str()); preferences.end(); } }; bool validCalibrationData(std::string data) { return data.length() > 10; //TODO: Implement a more robust validation } }; void setup() { Serial.begin(115200); delay(1000); // give me time to bring up serial monitor Serial.println(""Starting RV Meter""); // setup voltage measurement pinMode(VOLTPIN, INPUT); if (adc1_config_width(ADC_WIDTH_BIT_12) != ESP_OK) { Serial.println(""Error configuring ADC1""); } if (adc1_config_channel_atten(VOLTCHAN, ADC_ATTEN_DB_11) != ESP_OK) { Serial.println(""Error configuring channel atten.""); } esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_12, 0, &adc1_value); // setup touch sensor touch_pad_init(); touch_pad_set_voltage(TOUCH_HVOLT_2V7, TOUCH_LVOLT_0V5, TOUCH_HVOLT_ATTEN_1V5); // setup bluetooth low energy BLEDevice::init(SERVER_NAME); BLEServer *pServer = BLEDevice::createServer(); BLEService *pService = pServer->createService(SERVICE_UUID); pServer->setCallbacks(new MyServerCallbacks()); bleTouchValue = pService->createCharacteristic( TOUCH_CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ ); bleVoltageValue = pService->createCharacteristic( VOLTAGE_CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ ); bleTouchCalibration = pService->createCharacteristic( TOUCH_CALIBRATION_CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE ); bleRefreshRate = pService->createCharacteristic( REFRESH_RATE_CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE ); pService->start(); BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); pAdvertising->addServiceUUID(SERVICE_UUID); pAdvertising->setScanResponse(true); pAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue pAdvertising->setMinPreferred(0x12); BLEDevice::startAdvertising(); // Setup preferenches for saving touch calibration preferences.begin(""rvsetting"", RW_MODE); if (preferences.isKey(TOUCH_CALIBRATION_PREF_KEY)) { String prefsValue = preferences.getString(TOUCH_CALIBRATION_PREF_KEY); calibrationData = std::string(prefsValue.c_str()); Serial.print(""Prefs value for touch config read: '""); Serial.print(prefsValue); Serial.println(""'""); } else { // Need to initialize preferences.putString(TOUCH_CALIBRATION_PREF_KEY, ""TEST""); Serial.println(""No prefs calibration data - using default""); } preferences.end(); bleTouchCalibration->setValue(calibrationData); bleTouchCalibration->setCallbacks(new CalibrationWriteCallback()); bleRefreshRate->setValue(refreshRate); bleRefreshRate->setCallbacks(new RefreshRateWriteCallback()); // Serial.println(""RV Service Started""); #ifdef DEBUG tft.begin(); tft.setRotation(1); tft.setTextDatum(MC_DATUM); // Set text colour to orange with black background tft.setTextColor(TFT_WHITE, TFT_BLACK); tft.fillScreen(TFT_BLACK); // Clear screen tft.setFreeFont(FF18); // Select the font String TEXT = ""Started...""; tft.drawString(TEXT, 160, 120, GFXFF); #endif } int count = 0; void loop() { for (int i = 0; i < NUM_SAMPLES; i++) { voltRawValues[i] = adc1_get_raw(VOLTCHAN); touchValues[i] = touchRead(TOUCHPIN); delay(100); } int voltRaw = QuickMedian::GetMedian(voltRawValues, NUM_SAMPLES); float milliVoltSample = esp_adc_cal_raw_to_voltage(voltRaw, &adc1_value) * 5.7; Serial.print(""Voltage: ""); Serial.println(milliVoltSample / 1000); Serial.print(""Raw voltage: ""); Serial.println(voltRaw); int [MASK] = int(trunc(milliVoltSample)); bleVoltageValue->setValue( [MASK] ); // send in millivolts int touchSample = QuickMedian::GetMedian(touchValues, NUM_SAMPLES); Serial.print(""Touch: ""); Serial.println(touchSample); bleTouchValue->setValue(touchSample); #ifdef DEBUG String TEXT = ""Loop number "" + String(count); count++; tft.drawString(TEXT, 10, 120, GFXFF); #endif delay(refreshRate * 1000); } ",milliVoltSampleInt 256,"// Application.cpp #include ""Application.hpp"" #include #include #include Application::Application(int blockAmount) : blockAmount(blockAmount) { srand(static_cast(time(0))); if (!loadUsersFromFile(""users.txt"")) { std::cerr << ""Failed to load users. Exiting application."" << std::endl; exit(EXIT_FAILURE); } } void Application::run() { std::cout << ""Program started!"" << std::endl; RandomTransactionGenerator transactionGenerator(users); // Initialize the miner and CrowServer with the current blockchain and settings Miner miner(blockchain, maxNonce, startingNonce, genesisPrevCash); CrowServer server(blockchain, miner, transactionGenerator); // Start the server, which handles transactions and mining via API server.run(); } bool Application::loadUsersFromFile(const std::string& filename) { std::ifstream infile(filename); if (!infile) { std::cerr << ""Error: Unable to open users file: "" << filename << std::endl; return false; } std::string line; while (std::getline(infile, line)) { size_t start = line.find_first_not_of("" \t\r\n""); size_t end = line.find_last_not_of("" \t\r\n""); if (start != std::string::npos && end != std::string::npos) { std::string name = line.substr(start, end - start + 1); if (!name.empty()) { users.push_back(name); } } } infile.close(); return !users.empty(); } HorovyiBlockchain::Transaction Application::genRanTransaction() { if (users.empty()) { std::cerr << ""Error: User list is empty. Cannot generate transaction."" << std::endl; exit(EXIT_FAILURE); // Exit if no users are available } static std::random_device rd; static std::mt19937 gen(rd()); // Create uniform distributions based on the size of the users vector std::uniform_int_distribution<> userDist(0, users.size() - 1); std::uniform_int_distribution<> amountDist(1, 1000); int senderIndex = userDist(gen); int recipientIndex; do { recipientIndex = userDist(gen); } while (recipientIndex == senderIndex); int [MASK] = amountDist(gen); return HorovyiBlockchain::Transaction(users[senderIndex], users[recipientIndex], [MASK] ); }",moneyAmount 257,"#include #include #include #include //Version 1.4.6 typedef struct { float currentLimit; bool restoreCmd; }masterToNode_t; typedef struct { char id; bool overcurrentState; }nodeToMaster_t; const char nodeID = '1'; const uint8_t pzemTx = 16; const uint8_t pzemRx = 17; const uint8_t relayPin = 4; const uint8_t chipEn = 15; const uint8_t chipSel = 5; const byte room1RxPipe[] = ""rm1Tx""; const byte room1TxPipe[] = ""rm1Rx""; PZEM004Tv30 pzem(&Serial2,pzemTx,pzemRx); RF24 nrf24(chipEn,chipSel); uint32_t prevTime = millis(); static masterToNode_t masterToNode; /** * @brief Set float to zero if it is not a number. */ static void SetToZeroIfNaN(float* floatPtr) { if(isnan(*floatPtr)) { *floatPtr = 0.0; } } /** * @brief Send data to the master */ static void SendDataToMaster(RF24& nrf24,char id,bool overcurrentState) { nodeToMaster_t nodeToMaster = {id,overcurrentState}; nrf24.stopListening(); nrf24.openWritingPipe(room1TxPipe); nrf24.write(&nodeToMaster,sizeof(nodeToMaster_t)); nrf24.startListening(); } void setup() { Serial.begin(9600); pinMode(relayPin,OUTPUT); Serial.println(""INIT""); nrf24.begin(); nrf24.openReadingPipe(1,room1RxPipe); nrf24.setPALevel(RF24_PA_MAX); nrf24.startListening(); } void loop() { static bool overcurrentPrevDetected; //float measuredCurrent = pzem.current(); float measuredCurrent = 10.2; SetToZeroIfNaN(&measuredCurrent); if(nrf24.available()) { nrf24.read(&masterToNode,sizeof(masterToNode_t)); Serial.print(""Current limit = ""); Serial.println(masterToNode.currentLimit); Serial.print(""Restore cmd = ""); Serial.println(masterToNode.restoreCmd); } bool [MASK] = lround(measuredCurrent * 100) > lround(masterToNode.currentLimit * 100); if( [MASK] && !overcurrentPrevDetected) { Serial.println(""Current limit exceeded""); digitalWrite(relayPin,LOW); //disconnect the user from mains overcurrentPrevDetected = true; SendDataToMaster(nrf24,nodeID,overcurrentPrevDetected); } if(! [MASK] && masterToNode.restoreCmd) { Serial.println(""Power restored""); digitalWrite(relayPin,HIGH); //leave user connected to the mains masterToNode.restoreCmd = false; overcurrentPrevDetected = false; SendDataToMaster(nrf24,nodeID,overcurrentPrevDetected); } } ",overcurrentDetected 258,"#pragma once #include ""subprocess.h"" #include #include #include #include #include #include namespace splib { namespace detail { struct pipe_handle { int handles[2] = { -1, -1 }; inline ~pipe_handle() noexcept { } void close_pipe() noexcept { if (handles[1] != -1) close(handles[1]); if (handles[0] != -1) close(handles[0]); } pipe_handle() = default; pipe_handle(pipe_handle&) = delete; pipe_handle& operator=(const pipe_handle&) = delete; }; class posix_stream_handle : public pipe_handle { public: inline posix_stream_handle(subprocess::stdfunc_t&& f) noexcept : func(std::move(f)) { } subprocess::stdfunc_t func; }; } class suprocess_impl { public: inline suprocess_impl(subprocess::stdfunc_t&& stdout_func, subprocess::stdfunc_t&& stderr_func) noexcept : stdout_handle(std::move(stdout_func)) , stderr_handle(std::move(stderr_func)) { } inline ~suprocess_impl() { ::write(m_close_pipe.handles[1], ""."", 1); if (m_buffer_thread.joinable()) m_buffer_thread.join(); stdout_handle.close_pipe(); stderr_handle.close_pipe(); m_close_pipe.close_pipe(); } void start(const std::size_t buffer_size) noexcept { if (pipe(m_close_pipe.handles) != 0) { return; } SUBPROCESS_ASSERT(m_buffer_thread.joinable() == false); m_buffer_thread = std::thread([this, buffer_size]() { std::unique_ptr buffer(new char[buffer_size]); while (true) { bool ok = this->stream_buffering(buffer.get(), buffer_size); if (ok == false) break; } }); } bool stream_buffering(char* buffer, std::size_t max_buffer_size) { SUBPROCESS_ASSERT(buffer != nullptr && max_buffer_size > 0); auto hout = stdout_handle.handles[0]; auto herr = stderr_handle.handles[0]; auto [MASK] = m_close_pipe.handles[0]; if (hout == -1 || herr == -1 || [MASK] == -1) return false; fd_set set; FD_ZERO(&set); FD_SET(hout, &set); FD_SET(herr, &set); FD_SET( [MASK] , &set); auto hmax = std::max( [MASK] , std::max(hout, herr)); if (select(hmax + 1, &set, NULL, NULL, nullptr) == -1) return false; bool data_read = false; if (FD_ISSET( [MASK] , &set)) return false; if (FD_ISSET(hout, &set)) { auto num = read(hout, buffer, max_buffer_size); if (num <= 0) return false; if (stdout_handle.func != nullptr) stdout_handle.func(buffer, std::size_t(num)); data_read = true; } if (FD_ISSET(herr, &set)) { auto num = read(herr, buffer, max_buffer_size); if (num <= 0) return false; if (stderr_handle.func != nullptr) stderr_handle.func(buffer, std::size_t(num)); data_read = true; } return data_read; } public: detail::posix_stream_handle stdout_handle; detail::posix_stream_handle stderr_handle; pid_t pid = 0; protected: std::thread m_buffer_thread; detail::pipe_handle m_close_pipe; }; class pipe_impl : public detail::pipe_handle { public: inline ~pipe_impl() { close_pipe(); } inline bool write(const char* data, const std::size_t sz) noexcept { SUBPROCESS_ASSERT(handles[1] != -1 && data != nullptr && sz > 0); auto num = ::write(handles[1], data, sz); return num > 0; } }; bool subprocess::start(const CreateData& cd, stdfunc_t stdout_func, stdfunc_t stderr_func) noexcept { // run_cmd(""ls""); auto simpl = std::make_unique(std::move(stdout_func), std::move(stderr_func)); auto pimpl = std::make_unique(); if (pipe(simpl->stdout_handle.handles) != 0) { return false; } if (pipe(simpl->stderr_handle.handles) != 0) { return false; } if (pipe(pimpl->handles) != 0) { return false; } posix_spawn_file_actions_t action; posix_spawn_file_actions_init(&action); posix_spawn_file_actions_adddup2(&action, pimpl->handles[0], STDIN_FILENO); posix_spawn_file_actions_adddup2(&action, simpl->stdout_handle.handles[1], STDOUT_FILENO); posix_spawn_file_actions_adddup2(&action, simpl->stderr_handle.handles[1], STDERR_FILENO); std::vector argbuffers; std::vector argv; for (const auto& a : cd.argv) { argbuffers.push_back(a); } for (auto& a : argbuffers) { argv.push_back(&a[0]); } argv.push_back(nullptr); const char* exe = cd.exe.c_str(); if (posix_spawn(&(simpl->pid), exe, &action, nullptr, argv.data(), nullptr) != 0) { return false; } simpl->start(cd.buffer_size); { std::lock_guard lock(m_process_mutex); SUBPROCESS_ASSERT(m_process_handle == nullptr); m_process_handle.swap(simpl); m_stdin_pipe.swap(pimpl); } return true; } int subprocess::join() noexcept { pid_t pid; { std::lock_guard lock(m_process_mutex); SUBPROCESS_ASSERT(m_process_handle != nullptr); pid = m_process_handle->pid; } SUBPROCESS_ASSERT(pid != 0); int status = -1; int result = -1; do { if (waitpid(pid, &status, 0) == -1) { result = -1; break; } result = WEXITSTATUS(status); } while (!WIFEXITED(status) && !WIFSIGNALED(status)); #ifdef SUBPROCESS_POSIX_SIGNALED_JOIN_ERROR if (WIFSIGNALED(status) && result == 0) { if (status > 0) result = -status; else if (status < 0) result = status; else result = -1; } #endif { std::lock_guard lock(m_process_mutex); this->reset_no_lock(); } return result; } void subprocess::kill() noexcept { { std::lock_guard lock(m_process_mutex); if (m_process_handle == nullptr) return; auto id = m_process_handle->pid; ::kill(-id, SIGTERM); ::kill(id, SIGTERM); } std::this_thread::sleep_for(std::chrono::milliseconds(16)); // give 16 ms time for the process to terminate, then kill { std::lock_guard lock(m_process_mutex); if (m_process_handle == nullptr) return; auto id = m_process_handle->pid; ::kill(-id, SIGKILL); ::kill(id, SIGKILL); this->reset_no_lock(); } } } ",hexit 259,"////////////////////////////////////////////////////////////////////////// // // Helpers.cpp : Miscellaneous helpers. // // THIS CODE AND INFORMATION IS PROVIDED ""AS IS"" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // ////////////////////////////////////////////////////////////////////////// #include ""EVRPresenter.h"" //----------------------------------------------------------------------------- // SamplePool class //----------------------------------------------------------------------------- SamplePool::SamplePool() : m_bInitialized(FALSE), m_cPending(0) { InitializeCriticalSection(&m_lock); } SamplePool::~SamplePool() { DeleteCriticalSection(&m_lock); } //----------------------------------------------------------------------------- // GetSample // // Gets a sample from the pool. If no samples are available, the method // returns MF_E_SAMPLEALLOCATOR_EMPTY. //----------------------------------------------------------------------------- HRESULT SamplePool::GetSample(IMFSample **ppSample) { EnterCriticalSection(&m_lock); if (!m_bInitialized) { LeaveCriticalSection(&m_lock); return MF_E_NOT_INITIALIZED; } if (m_VideoSampleQueue.IsEmpty()) { LeaveCriticalSection(&m_lock); return MF_E_SAMPLEALLOCATOR_EMPTY; } // Get a sample from the allocated queue. // It doesn't matter if we pull them from the head or tail of the list, // but when we get it back, we want to re-insert it onto the opposite end. // (see ReturnSample) IMFSample *pSample = NULL; HRESULT hr = m_VideoSampleQueue.RemoveFront(&pSample); if (SUCCEEDED(hr)) { m_cPending++; // Give the sample to the caller. *ppSample = pSample; (*ppSample)->AddRef(); } SafeRelease(&pSample); LeaveCriticalSection(&m_lock); return hr; } //----------------------------------------------------------------------------- // ReturnSample // // Returns a sample to the pool. //----------------------------------------------------------------------------- HRESULT SamplePool::ReturnSample(IMFSample *pSample) { EnterCriticalSection(&m_lock); if (!m_bInitialized) { LeaveCriticalSection(&m_lock); return MF_E_NOT_INITIALIZED; } HRESULT hr = m_VideoSampleQueue.InsertBack(pSample); if (SUCCEEDED(hr)) { m_cPending--; } LeaveCriticalSection(&m_lock); return hr; } //----------------------------------------------------------------------------- // AreSamplesPending // // Returns TRUE if any samples are in use. //----------------------------------------------------------------------------- BOOL SamplePool::AreSamplesPending() { EnterCriticalSection(&m_lock); BOOL [MASK] = FALSE; if (!m_bInitialized) { [MASK] = FALSE; } else { [MASK] = (m_cPending > 0); } LeaveCriticalSection(&m_lock); return [MASK] ; } //----------------------------------------------------------------------------- // Initialize // // Initializes the pool with a list of samples. //----------------------------------------------------------------------------- HRESULT SamplePool::Initialize(VideoSampleList& samples) { EnterCriticalSection(&m_lock); if (m_bInitialized) { LeaveCriticalSection(&m_lock); return MF_E_INVALIDREQUEST; } HRESULT hr = S_OK; IMFSample *pSample = NULL; // Move these samples into our allocated queue. VideoSampleList::POSITION pos = samples.FrontPosition(); while (pos != samples.EndPosition()) { hr = samples.GetItemByPosition(pos, &pSample); if (FAILED(hr)) { goto done; } hr = m_VideoSampleQueue.InsertBack(pSample); if (FAILED(hr)) { goto done; } pos = samples.Next(pos); SafeRelease(&pSample); } m_bInitialized = TRUE; done: samples.Clear(); SafeRelease(&pSample); LeaveCriticalSection(&m_lock); return hr; } //----------------------------------------------------------------------------- // Clear // // Releases all samples. //----------------------------------------------------------------------------- HRESULT SamplePool::Clear() { HRESULT hr = S_OK; EnterCriticalSection(&m_lock); m_VideoSampleQueue.Clear(); m_bInitialized = FALSE; m_cPending = 0; LeaveCriticalSection(&m_lock); return S_OK; } ",bRet 260,"#include ""network.hpp"" void forward_prop(network& net){ for(int i = 0; i < 784; i++){ if(net.A0->elements[i][0] < 0){ net.A0->elements[i][0] += 255; } } apply_func(sigmoid, net.A0, net.A0); mat* temp1 = dot(net.W1, net.A0); add(net.B1, temp1, net.Z1); apply_func(sigmoid, net.Z1, net.A1); mat* temp2 = dot(net.W2, net.A1); add(net.B2, temp2, net.Z2); apply_func(sigmoid, net.Z2, net.A2); //softmax(net); mfree(temp1); mfree(temp2); } void back_prop(network& net){ // output layer mat* delta_A2 = sub(net.A2, net.Y); mat* A1_trans = transpose(net.A1); dot(delta_A2, A1_trans, net.dW2); scale(LEARNING_RATE, net.dW2, net.dW2); sub(net.W2, net.dW2, net.W2); scale(LEARNING_RATE, delta_A2, net.dB2); sub(net.B2, net.dB2, net.B2); // input layer mat* dactivation = mcopy(net.A1); mfill(dactivation, 1); sub(dactivation, net.A1, dactivation); multiply(dactivation, net.A1, dactivation); mat* W2_trans = transpose(net.W2); mat* delta_A1 = dot(W2_trans, delta_A2); multiply(delta_A1, dactivation, delta_A1); mat* A0_trans = transpose(net.A0); dot(delta_A1, A0_trans, net.dW1); scale(LEARNING_RATE, net.dW1, net.dW1); sub(net.W1, net.dW1, net.W1); add(net.dB1, delta_A1, net.dB1); scale(LEARNING_RATE, net.dB1, net.dB1); sub(net.B1, net.dB1, net.B1); // memory clean up mfree(delta_A2); mfree(A1_trans); mfree(dactivation); mfree(W2_trans); mfree(delta_A1); mfree(A0_trans); } void update_net(network& net){ scale(LEARNING_RATE, net.dW2, net.dW2); sub(net.W2, net.dW2, net.W2); mfill(net.dW2, 0); scale(LEARNING_RATE, net.dB2, net.dB2); sub(net.B2, net.dB2, net.B2); mfill(net.dB2, 0); scale(LEARNING_RATE, net.dW1, net.dW1); sub(net.W1, net.dW1, net.W1); mfill(net.dW1, 0); scale(LEARNING_RATE, net.dB1, net.dB1); sub(net.B1, net.dB1, net.B1); mfill(net.dB1, 0); } void ntrain(network& net, char** images, char* labels, int itter){ int guess = 0; double correct = 0, [MASK] = 0; for(int epoch = 0; epoch < 100; epoch++){ for(int i = 0; i < itter; i++){ for(int j = 0; j < INPUT_LAYER; j++){ net.A0->elements[j][0] = images[i][j]; } forward_prop(net); hot_encode_y(net, (int)(labels[i])); back_prop(net); guess = argmax(net); if(guess == (int)labels[i]){ correct++; } } if(epoch % 10 == 0){ [MASK] = correct / itter * 10; P(""----------""); P(""epoch: "" << epoch); P(""Accuracy: "" << [MASK] << ""%""); correct = 0; } } } void ntest(network& net, char** images, char* labels, int itter){ int guess = 0; int correct = 0; for(int i = 0; i < itter; i++){ for(int j = 0; j < INPUT_LAYER; j++){ net.A0->elements[j][0] = images[i][j]; } forward_prop(net); guess = argmax(net); if(guess == (int)labels[i]){ correct++; } // P(""network guess: "" << guess << "" Actual "" << (int)labels[i]); } P(""Out of "" << itter << "" guesses, the network got "" << correct << "" correct""); } ",acc 261,"/* * Copyright (C) 2024 Commissariat à l'énergie atomique et aux énergies alternatives (CEA) * 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 #include #include #include #include #include #include #include #include // for basename() #include // for PATH_MAX #include ""sesamController.hpp"" using namespace std; void usage(){ printf(""Sesam user controller\n""); printf(""v0.2\n""); printf(""Usage: sesam \n""); printf(""\nCommand:\n""); printf("" help\t\tShow this message\n""); printf("" show\t\tShow component status\n""); printf("" benchmark\t\tShow performance statistics of the executed program\n""); printf("" quit\t\tQuit VPSim\n""); } bool file_exists(const char *path) { return access(path, F_OK) == 0; } bool is_system_command(const char *cmd) { // Check if the command is a system command in the PATH return system((string(""command -v "") + cmd + "" >/dev/null 2>&1"").c_str()) == 0; } int main(int argc, char **argv) { char cmd[20]; char parameter[10][30]; /* Maximum 10 parameters */ int [MASK] ; int i; if (argc < 2) { usage(); exit(1); } /* Copy input variables to internal */ strcpy(cmd, argv[1]); map_sesam_mem(); /* Verify command */ if (strcmp(cmd,""help"") == 0) { printf(""Help: ""); usage(); return 0; } else if (strcmp(cmd,""quit"") == 0) { /* Call function to quit vpsim */ printf(""Quitting VPSIM environment ...\n""); sesam_quit(); } else if (strcmp(cmd,""list"") == 0) { /* Call function to list vpsim components */ printf(""Components in VPSIM: \n""); sesam_list_component(); } else if (strcmp(cmd,""benchmark"") == 0) { if (argc < 3) { printf(""Please put your benchmark application...""); printf(""Usage: sesam benchmark ""); exit(1); } ostringstream s; string tmp = argv[2]; bool is_local_executable = false; // Check if the provided executable name contains a path if (tmp.find('/') == string::npos) { // no path provided // Check if it's a system command if (!is_system_command(tmp.c_str())) { // Not a system command, prepend ""./"" to check the current directory string current_dir_app = ""./"" + tmp; if (file_exists(current_dir_app.c_str())) { tmp = current_dir_app; // Use current directory version is_local_executable = true; } else { printf(""Application %s not found in current directory or system PATH\n"", tmp.c_str()); exit(1); } } // Continue if the app is a system command } else { //A path is provided with the app is_local_executable = true; } string base_name; if (is_local_executable) { // Resolve the absolute path for local executables char resolved_path[PATH_MAX]; if (realpath(tmp.c_str(), resolved_path) == NULL) { perror(""realpath""); exit(1); } // Extract the base name from the resolved path base_name = basename(resolved_path); tmp = string(resolved_path); } else { // command is in PATH (system comand), keep its name base_name = tmp; } int n = base_name.length(); char name[n+1]; strcpy(name, base_name.c_str()); // Get the app name in HOST machine sesam_get_name(n, name); // Build the command string with absolute path and additional arguments s << tmp; for (int i = 3; i < argc; ++i) { s << "" "" << argv[i]; } sesam_start_bench(); // Execute the command using system() system(s.str().c_str()); sesam_end_bench(); } else { if (argc < 3) { printf(""Missing argument: ""); usage(); exit(1); } /* Get argument */ [MASK] = argc - 1; for (i = 0; i < [MASK] ; ++i) { strcpy(parameter[i],argv[i+1]); } sesam_exec_command( [MASK] , parameter); } unmap_sesam(); return 0; } ",nb_param 262,"/* peer.cc , 12 August 2015 */ #include #include #include #include #include #include #include #include #include namespace Pistache { namespace Tcp { std::atomic idCounter{0}; namespace { struct ConcretePeer : Peer { ConcretePeer() = default; ConcretePeer(Fd fd, const Address &addr, void *ssl) : Peer(fd, addr, ssl) {} }; } // namespace Peer::Peer(Fd fd, const Address &addr, void *ssl) : fd_(fd), addr(addr), ssl_(ssl), id_(idCounter++) {} Peer::~Peer() { #ifdef PISTACHE_USE_SSL if (ssl_) SSL_free(static_cast(ssl_)); #endif /* PISTACHE_USE_SSL */ } std::shared_ptr Peer::Create(Fd fd, const Address &addr) { return std::make_shared(fd, addr, nullptr); } std::shared_ptr Peer::CreateSSL(Fd fd, const Address &addr, void *ssl) { return std::make_shared(fd, addr, ssl); } const Address &Peer::address() const { return addr; } const std::string &Peer::hostname() { if (hostname_.empty()) { char host[NI_MAXHOST]; struct sockaddr_in sa; sa.sin_family = AF_INET; if (inet_pton(AF_INET, addr.host().c_str(), &sa.sin_addr) == 0) { hostname_ = addr.host(); } else { if (!getnameinfo((struct sockaddr *)&sa, sizeof(sa), host, sizeof(host), NULL, 0 // Service info , NI_NAMEREQD // Raise an error if name resolution failed )) { hostname_.assign((char *)host); } } } return hostname_; } void *Peer::ssl() const { return ssl_; } size_t Peer::getID() const { return id_; } int Peer::fd() const { if (fd_ == -1) { throw std::runtime_error(""The peer has no associated fd""); } return fd_; } void Peer::setParser(std::shared_ptr parser) { parser_ = parser; } std::shared_ptr Peer::getParser() const { return parser_; } Http::Request &Peer::request() { if (!parser_) { throw std::runtime_error(""The peer has no associated parser""); } return parser_->request; } Async::Promise Peer::send(const RawBuffer &buffer, int [MASK] ) { return transport()->asyncWrite(fd_, buffer, [MASK] ); } std::ostream &operator<<(std::ostream &os, Peer &peer) { const auto &addr = peer.address(); os << ""("" << addr.host() << "", "" << addr.port() << "") ["" << peer.hostname() << ""]""; return os; } void Peer::associateTransport(Transport *transport) { transport_ = transport; } Transport *Peer::transport() const { if (!transport_) throw std::logic_error(""Orphaned peer""); return transport_; } } // namespace Tcp } // namespace Pistache ",flags 263,"#include ""simple_license.h"" #include #include #include #include #include #include #include #include #include #include ""lib_license\aes256.h"" #pragma warning(disable : 4996) //_CRT_SECURE_NO_WARNINGS std::ostream & PT::operator<<(std::ostream& os, const License& license) { auto expire_day = std::chrono::system_clock::to_time_t(license.m_expire); os << license.m_mac << "" "" << std::put_time(std::localtime(&expire_day), ""%F %T""); return os; } std::string PT::GetLocalMacAddr() { IP_ADAPTER_INFO pAdapterInfo[32]; DWORD dwBufLen = sizeof(pAdapterInfo); DWORD [MASK] = GetAdaptersInfo(pAdapterInfo, &dwBufLen); if ( [MASK] != ERROR_SUCCESS) return """"; PIP_ADAPTER_INFO pAdapter = pAdapterInfo; BYTE* mac = pAdapter->Address; char buf[18]; snprintf(buf, sizeof(buf), ""%02X-%02X-%02X-%02X-%02X-%02X"", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return std::string(buf); } std::ostream& PT::operator<<(std::ostream& os, const LicenseCrypto& licCrypto) { aes256_context ctx; aes256_init(&ctx, LicenseCrypto::gKey); std::ostringstream oss; oss << *licCrypto.m_pLic; std::string plaintext = oss.str(); std::vector ciphertext(16 * (plaintext.size() / 16 + 1), 0); std::copy(plaintext.begin(), plaintext.end(), ciphertext.begin()); for (size_t i = 0; i < ciphertext.size(); i += 16) aes256_encrypt_ecb(&ctx, &ciphertext[i]); for (auto c : ciphertext) os << c; return os; } PT::License::License(const std::string& strMac, int month): m_mac(strMac), m_expire(std::chrono::system_clock::now() + months{ month }) { } PT::License::License(std::istream& is) { std::tm tm = {}; try { is >> m_mac >> std::get_time(&tm, ""%Y-%m-%d %T""); m_expire = std::chrono::system_clock::from_time_t(std::mktime(&tm)); } catch (const std::exception& e) { std::cout << e.what(); } } std::pair PT::License::Check() const { if (GetLocalMacAddr() != m_mac) return std::make_pair(false, ""The MAC Address does not match.""); if (std::chrono::system_clock::now() > m_expire) return std::make_pair(false, ""The license has expired.""); return std::make_pair(true, ""success""); } PT::LicenseCrypto::LicenseCrypto(std::istream& is) { aes256_context ctx; aes256_init(&ctx, gKey); try { std::vector ciphertext((std::istreambuf_iterator(is)), std::istreambuf_iterator()); for (size_t i = 0; i < ciphertext.size(); i += 16) aes256_decrypt_ecb(&ctx, &ciphertext[i]); std::string plaintext(ciphertext.begin(), ciphertext.end()); std::istringstream iss(plaintext); m_pLic = std::make_shared(iss); } catch (const std::exception& e) { std::cout << e.what() << std::endl; } }",dwRetVal 264,"#include #include using namespace std; void displayWelcomeMessage() { cout <<""---------------------------------""<> itemNames[itemCount]; cout << ""Enter "" << itemNames[itemCount] << ""'s Price: ""; cin >> itemPrice[itemCount]; itemCount++; cout << ""Item added to cart!\n"";} else { cout << ""Maximum number of items reached.\n""; } } int main() { string itemNames[50]; int itemPrice[50]; int itemCount = 0; int choice; int total=0; displayWelcomeMessage(); do { cout<<""\nEnter your Choice :""; cin >> choice; switch (choice) { case 1: addItem(itemNames, itemPrice, itemCount); break; case 2: viewItems(itemNames, itemPrice, itemCount); break; case 3: if (itemCount == 0) { cout << ""Cart is empty. Please add items first.\n""; } else { cout<<""\n""; cout<<""\n""; cout<<""\n""; viewItems(itemNames, itemPrice, itemCount); cout<> confirm; if (confirm == 'y' || confirm == 'Y') { cout << ""\nThank you for shopping!\n"";} for (int i = 0; i < itemCount; i++) { itemNames[i] = """"; itemPrice[i] = 0; } itemCount = 0; break; case 4: cout << ""Exiting the program.\n""; break; case 5: default: cout << ""Invalid choice. Please try again.\n""; } } } while (choice != 4); return 0; } ",cartsize 265,"/* ** Ncurses.cpp for arcade in /home/aubanel_m/tek2/cpp_arcade/arcade/GUIs ** ** Made by aubanel_m ** Login <> ** ** Started on Thu Mar 09 21:08:53 2017 aubanel_m ** Last update Sun Apr 9 22:17:31 2017 */ #include ""../../Include/Ncurses.hpp"" void Ncurses::Init_Game(int y, int x) { WIN = initscr(); nodelay(WIN, TRUE); start_color(); use_default_colors(); noecho(); curs_set(0); init_pair(1, COLOR_WHITE, COLOR_GREEN); init_pair(2, COLOR_BLACK, COLOR_WHITE); init_pair(3, COLOR_WHITE, COLOR_BLACK); init_pair(4, COLOR_BLUE, COLOR_BLUE); init_pair(5, COLOR_BLACK, COLOR_YELLOW); init_pair(11, COLOR_RED, COLOR_RED); init_pair(12, COLOR_BLUE, COLOR_BLUE); init_pair(13, COLOR_CYAN, COLOR_CYAN); init_pair(14, COLOR_MAGENTA, COLOR_MAGENTA); init_pair(15, COLOR_WHITE, COLOR_WHITE); _y = y; _x = x; BOARD = subwin(WIN, _y + 2, _x + 2, (LINES / 2) - (_y / 2), (COLS / 2) - (_x / 2)); SCORE = subwin(WIN, 5, 17, 2, 30); wborder(SCORE, 0, 0, 0, 0, 0, 0, 0, 0); wborder(WIN, 0, 0, 0, 0, 0, 0, 0, 0); wborder(BOARD, 0, 0, 0, 0, 0, 0, 0, 0); wrefresh(WIN); wrefresh(BOARD); } void Ncurses::Init_GUI() { WIN = initscr(); nodelay(WIN, TRUE); start_color(); use_default_colors(); noecho(); curs_set(0); init_pair(1, COLOR_WHITE, COLOR_GREEN); init_pair(2, COLOR_BLACK, COLOR_WHITE); init_pair(3, COLOR_WHITE, COLOR_BLACK); init_pair(4, COLOR_BLUE, COLOR_BLUE); init_pair(5, COLOR_BLACK, COLOR_YELLOW); init_pair(11, COLOR_RED, COLOR_RED); init_pair(12, COLOR_BLUE, COLOR_BLUE); init_pair(13, COLOR_CYAN, COLOR_CYAN); init_pair(14, COLOR_MAGENTA, COLOR_MAGENTA); init_pair(15, COLOR_WHITE, COLOR_WHITE); } void Ncurses::B_Circle_Yellow(int y, int x, Game::Command [MASK] ) { (void) [MASK] ; wattron(BOARD, COLOR_PAIR(5)); mvwprintw(BOARD, y, x, ""O""); wattroff(BOARD, COLOR_PAIR(5)); } void Ncurses::Dead_Ghost(int y, int x) { wattron(BOARD, COLOR_PAIR(15)); mvwprintw(BOARD, y, x, ""O""); wattroff(BOARD, COLOR_PAIR(15)); } void Ncurses::Ghost(int y, int x, int type) { wattron(BOARD, COLOR_PAIR(type)); mvwprintw(BOARD, y, x, ""0""); wattroff(BOARD, COLOR_PAIR(type)); } void Ncurses::B_Circle(int y, int x, Game::Command DIR) { (void)DIR; wattron(BOARD, COLOR_PAIR(2)); mvwprintw(BOARD, y, x, ""O""); wattroff(BOARD, COLOR_PAIR(2)); } void Ncurses::S_Star(int y, int x) { mvwprintw(BOARD, y, x, ""X""); } void Ncurses::S_Dot(int y, int x) { mvwprintw(BOARD, y, x, "".""); } void Ncurses::B_Dot(int y, int x) { mvwprintw(BOARD, y, x, ""*""); } void Ncurses::Space(int y, int x) { mvwprintw(BOARD, y, x, "" ""); } void Ncurses::S_Circle(int y, int x) { wattron(BOARD, COLOR_PAIR(1)); mvwprintw(BOARD, y, x, ""o""); wattroff(BOARD, COLOR_PAIR(1)); } void Ncurses::B_Block(int y, int x) { wattron(BOARD, COLOR_PAIR(4)); mvwprintw(BOARD, y, x, "" ""); wattroff(BOARD, COLOR_PAIR(4)); } void Ncurses::DISPLAY_Score(int _SCORE) { mvwprintw(SCORE, 1, 1, ""Score :""); mvwprintw(SCORE, 1, 9, std::to_string(_SCORE).c_str()); } void Ncurses::DISPLAY_Level(int _LVL) { mvwprintw(SCORE, 2, 1, ""Level :""); mvwprintw(SCORE, 2, 9, std::to_string(_LVL).c_str()); } void Ncurses::Refresh() { wrefresh(BOARD); wrefresh(SCORE); } void Ncurses::Keyboard() { char key; key = getch(); if (key != ERR) { if (key == ' ') { _DIR = Game::Command::PAUSE; return ; } if (key == '\'') { _DIR = Game::Command::NEXTLIB; return ; } if (key == '(') { _DIR = Game::Command::NEXTGAME; return ; } if (key == '_') { _DIR = Game::Command::RESTART; return ; } if (key == '""') { _DIR = Game::Command::PREVLIB; return ; } if (key == 27) { key = getch(); if (key == ERR) { _DIR = Game::Command::ESCAPE; return ; } key = getch(); if (key == 'A') { _DIR = Game::Command::UP; return ; } else if (key == 'B') { _DIR = Game::Command::DOWN; return ; } else if (key == 'C') { _DIR = Game::Command::RIGHT; return ; } else if (key == 'D') { _DIR = Game::Command::LEFT; return ; } } } } void Ncurses::Launcher_Header() { wattron(WIN, A_BOLD); mvwprintw(WIN, 10, 42, "" .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. ""); mvwprintw(WIN, 11, 42, ""| .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. | ""); mvwprintw(WIN, 12, 42, ""| | __ | || | _______ | || | ______ | || | __ | || | ________ | || | _________ | | ""); mvwprintw(WIN, 13, 42, ""| | / \\ | || | |_ __ \\ | || | .' ___ | | || | / \\ | || | |_ ___ `. | || | |_ ___ | | | ""); mvwprintw(WIN, 14, 42, ""| | / /\\ \\ | || | | |__) | | || | / .' \\_| | || | / /\\ \\ | || | | | `. \\ | || | | |_ \\_| | | ""); mvwprintw(WIN, 15, 42, ""| | / ____ \\ | || | | __ / | || | | | | || | / ____ \\ | || | | | | | | || | | _| _ | | ""); mvwprintw(WIN, 16, 42, ""| | _/ / \\ \\_ | || | _| | \\ \\_ | || | \\ `.___.'\\ | || | _/ / \\ \\_ | || | _| |___.' / | || | _| |___/ | | | ""); mvwprintw(WIN, 17, 42, ""| ||____| |____|| || | |____| |___| | || | `._____.' | || ||____| |____|| || | |________.' | || | |_________| | | ""); mvwprintw(WIN, 18, 42, ""| | | || | | || | | || | | || | | || | | | ""); mvwprintw(WIN, 19, 42, ""| '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' | ""); mvwprintw(WIN, 20, 42, "" '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' ""); wattroff(WIN, A_BOLD); } std::string Ncurses::Launcher(std::vector v) { std::string string; WINDOW* menu_win; unsigned long int n = v.size(); ITEM** items; int c = 0; char key; MENU* menu; unsigned long int pos = 0; char str[100]; items = (ITEM**)calloc(n + 1, sizeof(ITEM*)); for (std::vector::iterator i = v.begin(); i != v.end(); ++i) { items[c] = new_item(i->name.c_str(), NULL); c = c + 1; } menu = new_menu(items); menu_win = newwin(9, 40, (LINES / 2) - 5, (COLS / 2) - 20); box(menu_win, 0, 0); mvwprintw(menu_win, 0, 14, ""SELECT GAME""); set_menu_win(menu, menu_win); set_menu_sub(menu, derwin(menu_win, 6, 38, 3, 1)); post_menu(menu); wrefresh(WIN); wrefresh(menu_win); while ((key = getch()) != 10) { Launcher_Header(); if (key != ERR) { if (key == 27) { key = getch(); if (key == ERR) { string.clear(); return (string); } key = getch(); switch(key) { case 'B': menu_driver(menu, REQ_DOWN_ITEM); if (pos < n - 1) pos = pos + 1; break; case 'A': menu_driver(menu, REQ_UP_ITEM); if (pos >= 1) pos = pos - 1; break; } } } wrefresh(menu_win); wrefresh(WIN); } echo(); nodelay(WIN, FALSE); mvwprintw(WIN, 45, 80, ""Enter your name : ""); mvwgetstr(WIN, 45, 100, str); nodelay(WIN, TRUE); noecho(); wclear(WIN); wrefresh(WIN); return (v[pos].path); } Game::Command Ncurses::GET_key() { return (_DIR); } void Ncurses::Clear_WIN() { _DIR = Game::Command::NONE; wclear(WIN); } void Ncurses::DISPLAY_background(std::string& path) { (void)path; } Ncurses::Ncurses() { _DIR = Game::Command::NONE; } Ncurses::~Ncurses() { endwin(); } extern ""C"" Ncurses* C_LIB() { return (new Ncurses()); } ",cmd 266,"/* ***************************************************************************************************************************** * COPYRIGHT (c) 2025 () unless otherwise noted. * * This program and all its associated modules 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 GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses * ***************************************************************************************************************************** */ /* * By */ #ifndef THROTTLE_PAGE_H #define THROTTLE_PAGE_H #include ""functions.h"" void populateLocoDetails() { // Serial.printf(""LocoID being Populated: %d\n"", activeLocoID); if(activeLocoID != 255) { lv_slider_set_value(objects.slider, locoSpeed[activeLocoID], LV_ANIM_OFF); char speedString[10] = """"; itoa(locoSpeed[activeLocoID], speedString, 10); lv_label_set_text(objects.lbl_slider,speedString); //Update the speed label to the previously set speed value lv_label_set_text(objects.lbl_address, locoAddress[activeLocoID]); //Update the address label to the previously set address //Setup the Direction if(locoDir[activeLocoID] == 1) { lv_obj_add_state(objects.sw_dir, LV_STATE_CHECKED); }else lv_obj_clear_state(objects.sw_dir, LV_STATE_CHECKED); //Setup the Function Buttons for(int i = 0; i < NUM_FUNC_SLOTS; i++) { int val = atoi(funcNumber[activeLocoID][i]); if(val != 255) { btnMap_functions[map_xlate[i]] = funcName[activeLocoID][i]; lv_btnmatrix_clear_btn_ctrl(objects.function_mtx, func_xlate[i], LV_BTNMATRIX_CTRL_HIDDEN); if(funcState[activeLocoID][i] == 1) { lv_btnmatrix_set_btn_ctrl(objects.function_mtx, func_xlate[i], LV_BTNMATRIX_CTRL_CHECKED); }else { lv_btnmatrix_clear_btn_ctrl(objects.function_mtx, func_xlate[i], LV_BTNMATRIX_CTRL_CHECKED); } }else { btnMap_functions[map_xlate[i]] = "" ""; lv_btnmatrix_set_btn_ctrl(objects.function_mtx, func_xlate[i], LV_BTNMATRIX_CTRL_HIDDEN); } } lv_btnmatrix_set_map(objects.function_mtx, btnMap_functions); }else { loadScreen(SCREEN_ID_ROSTER); } } void populateThrottle() { lv_dropdown_clear_options(objects.dd_locos); //Clear the previous list lv_label_set_text(objects.lbl_throttle_page,throttleName[activeThrottle]); //Update the page heading activeLocoID = selectedIDs[activeThrottle][activeSlot[activeThrottle]]; for(int i = 0; i < NUM_LOCO_SLOTS; i++) { if(selectedIDs[activeThrottle][i] != 255) //ignore unused Loco IDs { lv_dropdown_add_option(objects.dd_locos,locoName[selectedIDs[activeThrottle][i]],i); //Add all valid Locos to the list // Serial.print(""loco "");Serial.println(locoName[selectedIDs[activeThrottle][i]]); }else { lv_dropdown_add_option(objects.dd_locos,"""",i); //Blank out unused Loco IDs in the list } } lv_dropdown_set_selected(objects.dd_locos, activeSlot[activeThrottle]); //Set the previously active Loco as selected populateLocoDetails(); } void clearGuest() { rosterMode = GUEST_INACTIVE; //UNCHECK Guest_address TextArea } static void throttle_selection_handler_cb(lv_event_t * e) { lv_event_code_t code = lv_event_get_code(e); lv_obj_t * obj = lv_event_get_target(e); if(code == LV_EVENT_VALUE_CHANGED) { uint32_t id = lv_btnmatrix_get_selected_btn(objects.throttle_mtx); //Retrieve the Selected Throttle number activeThrottle = id; //Make this the new Active Throttle populateThrottle(); loadScreen(SCREEN_ID_THROTTLE); } } static void functions_cb(lv_event_t * e) { if(rosterMode == GUEST_INACTIVE) { lv_event_code_t code = lv_event_get_code(e); lv_obj_t * obj = lv_event_get_target(e); uint32_t mapslot = lv_btnmatrix_get_selected_btn(obj); if(mapslot >9) return; uint32_t fslot = abs_xlate[mapslot]; if(funcName[activeLocoID][fslot] != """") { if(code == LV_EVENT_PRESSED) { // Serial.printf(""Function Pressed: %d\n"", funcOption[activeLocoID][fslot]); if(funcState[activeLocoID][fslot] == 1) funcState[activeLocoID][fslot] = 0; else funcState[activeLocoID][fslot] = 1; //Send the DCCEX Command... String functionCMD = (""""); Serial.println(functionCMD); // client.print(functionCMD); if(!client.print(functionCMD)) Serial.println(""Transmit Failed""); }else if(code == LV_EVENT_RELEASED) { // Serial.printf(""Function Released: %d\n"", funcOption[activeLocoID][fslot]); if(funcOption[activeLocoID][fslot] == 1) { lv_btnmatrix_clear_btn_ctrl(obj, func_xlate[fslot], LV_BTNMATRIX_CTRL_CHECKED); funcState[activeLocoID][fslot] = 0; //Send the DCCEX Command... String functionCMD = (""""); Serial.println(functionCMD); if(!client.print(functionCMD)) Serial.println(""Transmit Failed""); // client.print(functionCMD); } } } } } void dd_locos_cb(lv_event_t * e) { //clearGuest(); lv_event_code_t code = lv_event_get_code(e); // lv_obj_t * obj = lv_event_get_target(e); if(code == LV_EVENT_VALUE_CHANGED) { activeSlot[activeThrottle] = lv_dropdown_get_selected(objects.dd_locos); activeLocoID = selectedIDs[activeThrottle][activeSlot[activeThrottle]]; //update activeLocoID populateLocoDetails(); } } void setSpeed(uint16_t locoAddr, uint16_t newSpeed, uint8_t newDir) { char speedString[10] = """"; itoa(newSpeed, speedString, 10); lv_slider_set_value(objects.slider, newSpeed, LV_ANIM_OFF); lv_label_set_text(objects.lbl_slider,speedString); String [MASK] = (""""); Serial.println( [MASK] ); if(!client.print( [MASK] )) Serial.println(""Transmit Failed""); } void action_throttle_button(lv_event_t * e) { void *user_data = lv_event_get_user_data(e); int pressedButton = *((int*)(&user_data)); switch(pressedButton) { case 1: rosterMode = GUEST_ACTIVE; lv_obj_clear_flag(objects.kbd_guest, LV_OBJ_FLAG_HIDDEN); lv_slider_set_value(objects.slider, 0, LV_ANIM_OFF); lv_label_set_text(objects.lbl_slider,""0""); lv_label_set_text(objects.lbl_address, lv_textarea_get_text(objects.ta_guest_address)); for(int i = 0; i < NUM_FUNC_SLOTS; i++) { lv_btnmatrix_set_btn_ctrl(objects.function_mtx, func_xlate[i], LV_BTNMATRIX_CTRL_HIDDEN); } gfx.flush(); //#if defined ( ESP32DIS02170A ) || defined ( ESP32DIS08070H ) || defined ( ESP3202170A_LS ) //#else // gfx.flush(true); //#endif break; case 2: //Guest Loco // Serial.println(""Guest InActive""); lv_obj_add_flag(objects.kbd_guest, LV_OBJ_FLAG_HIDDEN); rosterMode = GUEST_INACTIVE; // Serial.printf(""Roster Mode: %d\n"", rosterMode); populateLocoDetails(); break; case 3: //Slider { // Serial.printf(""Roster Mode: %d\n"", rosterMode); // if(runState == 0) break; if(rosterMode != GUEST_ACTIVE) { // Serial.println(""Setting Loco Speed""); locoSpeed[activeLocoID] = lv_slider_get_value(objects.slider); setSpeed(atoi(locoAddress[activeLocoID]), locoSpeed[activeLocoID], locoDir[activeLocoID]); }else //Guest Active { // Serial.println(""Setting Guest Speed""); guestSpeed = lv_slider_get_value(objects.slider); setSpeed(atoi(lv_textarea_get_text(objects.ta_guest_address)), guestSpeed, guestDir); } break; } case 4: //Direction - Set to Forward { // Serial.println(""Direction set Forward""); if(rosterMode != GUEST_ACTIVE) { if(locoSpeed[activeLocoID] > thresholdSpeed) locoSpeed[activeLocoID] = 0; locoDir[activeLocoID] = 1; setSpeed(atoi(locoAddress[activeLocoID]), locoSpeed[activeLocoID], locoDir[activeLocoID]); }else { if(guestSpeed > thresholdSpeed) guestSpeed = 0; guestDir = 1; setSpeed(atoi(lv_textarea_get_text(objects.ta_guest_address)), guestSpeed, guestDir); } break; } case 5: //Direction - Set to Reverse { // Serial.println(""Direction set Reverse""); if(rosterMode != GUEST_ACTIVE) { if(locoSpeed[activeLocoID] > thresholdSpeed) locoSpeed[activeLocoID] = 0; locoDir[activeLocoID] = 0; setSpeed(atoi(locoAddress[activeLocoID]), locoSpeed[activeLocoID], locoDir[activeLocoID]); }else { if(guestSpeed > thresholdSpeed) guestSpeed = 0; guestDir = 0; setSpeed(atoi(lv_textarea_get_text(objects.ta_guest_address)), guestSpeed, guestDir); } break; } case 6: // Serial.println(""Clicked Up""); if(locoSpeed[activeLocoID] < 126) locoSpeed[activeLocoID] = locoSpeed[activeLocoID] + 1; setSpeed(atoi(locoAddress[activeLocoID]), locoSpeed[activeLocoID], locoDir[activeLocoID]); // Serial.printf(""New Speed: %d\n"", locoSpeed[activeLocoID]); break; case 7: // Serial.println(""Clicked Down""); if(locoSpeed[activeLocoID] > 0) locoSpeed[activeLocoID] = locoSpeed[activeLocoID] - 1; setSpeed(atoi(locoAddress[activeLocoID]), locoSpeed[activeLocoID], locoDir[activeLocoID]); // Serial.printf(""New Speed: %d\n"", locoSpeed[activeLocoID]); break; case 29: //Edit Button { clearGuest(); editingID = activeLocoID; lv_textarea_set_text(objects.ta_name, locoName[editingID]); lv_textarea_set_text(objects.ta_address, locoAddress[editingID]); setupFuncEditSlots(); callingPage = SCREEN_ID_THROTTLE; loadScreen(SCREEN_ID_EDIT_LOCO); break; } case 30: //Prog Button clearGuest(); callingPage = SCREEN_ID_THROTTLE; loadScreen(SCREEN_ID_PROGRAM); break; case 31: //Roster clearGuest(); callingPage = SCREEN_ID_THROTTLE; loadScreen(SCREEN_ID_ROSTER); break; case 32: //Acc // callingPage = SCREEN_ID_THROTTLE; // loadScreen(SCREEN_ID_ACCESSORIES); break; default: break; } } void setLocoFwd() { Serial.println(""Direction set Forward""); if(rosterMode != GUEST_ACTIVE) { if(locoSpeed[activeLocoID] > thresholdSpeed) locoSpeed[activeLocoID] = 0; locoDir[activeLocoID] = 1; setSpeed(atoi(locoAddress[activeLocoID]), locoSpeed[activeLocoID], locoDir[activeLocoID]); }else { if(guestSpeed > thresholdSpeed) guestSpeed = 0; guestDir = 1; setSpeed(atoi(lv_textarea_get_text(objects.ta_guest_address)), guestSpeed, guestDir); } } void setLocoRev() { Serial.println(""Direction set Reverse""); if(rosterMode != GUEST_ACTIVE) { if(locoSpeed[activeLocoID] > thresholdSpeed) locoSpeed[activeLocoID] = 0; locoDir[activeLocoID] = 0; setSpeed(atoi(locoAddress[activeLocoID]), locoSpeed[activeLocoID], locoDir[activeLocoID]); }else { if(guestSpeed > thresholdSpeed) guestSpeed = 0; guestDir = 0; setSpeed(atoi(lv_textarea_get_text(objects.ta_guest_address)), guestSpeed, guestDir); } } #if defined ESP32DIS06043H || defined ESP32DIS08070H || defined ESP32DIS02170A void action_functions_button(lv_event_t * e) { void *user_data = lv_event_get_user_data(e); int pressedButton = *((int*)(&user_data)); switch(pressedButton) { case 30: //Cancel Button loadScreen(SCREEN_ID_THROTTLE); break; case 31: //Description Button break; case 32: //Done Button loadScreen(SCREEN_ID_THROTTLE); break; default: break; } } static void ex_functions_cb(lv_event_t * e) { if(rosterMode == GUEST_INACTIVE) { lv_event_code_t code = lv_event_get_code(e); lv_obj_t * obj = lv_event_get_target(e); uint32_t fNum = lv_btnmatrix_get_selected_btn(obj); if(fNum == 65535) return; // Serial.printf(""Button: %d\n"", fNum); if(lv_btnmatrix_has_btn_ctrl(obj, fNum, LV_BTNMATRIX_CTRL_DISABLED)) return; if(code == LV_EVENT_PRESSED) { if(lv_obj_get_state(objects.desc_button) == LV_STATE_CHECKED) { Serial.printf(""Function Pressed: %d\n"", fNum); Serial.printf(""Active ID: %d\n"", activeLocoID); Serial.println(funcName[activeLocoID][fNum]); // std::string s = std::to_string(fNum); // s = ""Function Pressed: F"" + s; // const char* fDesc = s.c_str(); // lv_label_set_text(objects.func_description, fDesc); lv_label_set_text(objects.func_description, funcName[activeLocoID][fNum]); // if(funcState[activeLocoID][fslot] == 1) funcState[activeLocoID][fslot] = 0; // else funcState[activeLocoID][fslot] = 1; // //Send the DCCEX Command... // String functionCMD = (""""); // Serial.println(functionCMD); // client.print(functionCMD); // if(!client.print(functionCMD)) Serial.println(""Transmit Failed""); } }else if(code == LV_EVENT_RELEASED) { if(lv_obj_get_state(objects.desc_button) == LV_STATE_CHECKED) { Serial.printf(""Function Released: %d\n"", fNum); lv_label_set_text(objects.func_description, """"); lv_btnmatrix_clear_btn_ctrl(obj, fNum, LV_BTNMATRIX_CTRL_CHECKED); // if(funcOption[activeLocoID][fslot] == 1) // { // lv_btnmatrix_clear_btn_ctrl(obj, func_xlate[fslot], LV_BTNMATRIX_CTRL_CHECKED); // funcState[activeLocoID][fslot] = 0; // //Send the DCCEX Command... // String functionCMD = (""""); // Serial.println(functionCMD); // if(!client.print(functionCMD)) Serial.println(""Transmit Failed""); // client.print(functionCMD); // } } } } } #endif #endif // THROTTLE_PAGE_H ",speedCMD 267,"#include ""arduino_secrets.h"" /*----------------------------------------------------------------------------*/ /* Includes */ /*----------------------------------------------------------------------------*/ #include ""thingProperties.h"" /*----------------------------------------------------------------------------*/ /* Local defines */ /*----------------------------------------------------------------------------*/ #define ECHO_PIN (21u) /* Digital output PIN_21 */ #define TRIGGER_PIN (22u) /* Digital input PIN_22 */ #define BLUE_PIN (12u) /* Digital output PIN_12 */ #define TEMT_PIN (36u) /* Analog input PIN_36 */ #define MAX_DISTANCE (100u) #define MIN_LIGHT_INTENSITY (50u) #define NUMBER_OF_SAMPLES_AVERAGE (5u) /*----------------------------------------------------------------------------*/ /* Global data at RAM */ /*----------------------------------------------------------------------------*/ bool user_cntrl = false; bool led_on = false; xSemaphoreHandle xSemaphore; /*----------------------------------------------------------------------------*/ /* Declaration of local functions */ /*----------------------------------------------------------------------------*/ void SDTR_UpdateCloud(void *pvParameters); void SDTR_MeasureDistance(void *pvParameters); void SDTR_MeasureLightIntensity(void *pvParameters); void SDTR_BlinkLed(void *pvParameters); /*----------------------------------------------------------------------------*/ /* Implementation of global functions */ /*----------------------------------------------------------------------------*/ void setup() { // Initialize serial and wait for port to open: Serial.begin(9600); // Defined in thingProperties.h initProperties(); xSemaphore = xSemaphoreCreateBinary(); // Connect to Arduino IoT Cloud ArduinoCloud.begin(ArduinoIoTPreferredConnection); //Pin settings pinMode(TRIGGER_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); pinMode(TEMT_PIN, INPUT); pinMode(BLUE_PIN, OUTPUT); //Task creation xTaskCreatePinnedToCore( SDTR_UpdateCloud, // Task function ""SDTR_UpdateCloud"", // Name 1024 * 7, // Stack size of the task NULL, // Parameters 1, // Priority NULL, // Task handle 0); // Core xTaskCreatePinnedToCore( SDTR_MeasureDistance, // Task function ""SDTR_MeasureDistance"", // Name 1024 * 7, // Stack size of the task NULL, // Parameters 1, // Priority NULL, // Task handle 0); //Core xTaskCreatePinnedToCore( SDTR_MeasureLightIntensity, // Task function ""SDTR_MeasureLightIntensity"", // Name 1024 * 7, // Stack size of the task NULL, // Parameters 1, // Priority NULL, // Task handle 0); //Core xTaskCreatePinnedToCore( SDTR_BlinkLed, // Task function ""SDTR_BlinkLed"", // Name 1024 * 7, // Stack size of the task NULL, // Parameters 1, // Priority NULL, // Task handle 0); //Core xSemaphoreGive(xSemaphore); } void loop() { // // Your code here } /*----------------------------------------------------------------------------*/ /* Implementation of local functions */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* SDTR_UpdateCloud */ /*----------------------------------------------------------------------------*/ void SDTR_UpdateCloud(void *pvParameters) { (void) pvParameters; // A task shall never return or exit for (;;) { xSemaphoreTake(xSemaphore, portMAX_DELAY); Serial.println(""Start WEB service...""); ArduinoCloud.update(); xSemaphoreGive(xSemaphore); vTaskDelay(100 / portTICK_PERIOD_MS); //delay of 100ms } } /*----------------------------------------------------------------------------*/ /* SDTR_MeasureDistance */ /*----------------------------------------------------------------------------*/ void SDTR_MeasureDistance(void *pvParameters) { (void) pvParameters; // A task shall never return or exit for (;;) { SDTR_GetDistance(); vTaskDelay(100 / portTICK_PERIOD_MS); //delay of 100ms } } /*----------------------------------------------------------------------------*/ /* SDTR_GetDistance */ /*----------------------------------------------------------------------------*/ void SDTR_GetDistance() { long pulseWidthInMicro = 0; int measured_distance = 0; digitalWrite(TRIGGER_PIN, HIGH); //10 us wait = 0.01ms/portTICK_PERIOD_MS vTaskDelay(0.01 / portTICK_PERIOD_MS); digitalWrite(TRIGGER_PIN, LOW); pulseWidthInMicro = pulseIn(ECHO_PIN, HIGH); measured_distance = (pulseWidthInMicro * 340 / 10000) / 2; //cm //distanta = (durata impuls*0,034secunde)/2 xSemaphoreTake(xSemaphore, portMAX_DELAY); distance_cm = measured_distance; Serial.print(""Distance: ""); Serial.print(distance_cm); Serial.print("" cm""); Serial.println(); xSemaphoreGive(xSemaphore); } /*----------------------------------------------------------------------------*/ /* SDTR_MeasureLightIntensity */ /*----------------------------------------------------------------------------*/ void SDTR_MeasureLightIntensity(void *pvParameters) { (void) pvParameters; // A task shall never return or exit for (;;) { SDTR_GetIntensity(); vTaskDelay(100 / portTICK_PERIOD_MS ); //delay of 100ms } } /*----------------------------------------------------------------------------*/ /* SDTR_GetIntensity */ /*----------------------------------------------------------------------------*/ void SDTR_GetIntensity() { long light_intensity_pin = 0; //pin light intensity long sum = 0; int adc_sample = 0; int [MASK] ; for (adc_sample = 0; adc_sample < NUMBER_OF_SAMPLES_AVERAGE; adc_sample++) { sum = sum + analogRead(TEMT_PIN); } light_intensity_pin = sum / NUMBER_OF_SAMPLES_AVERAGE; [MASK] = (light_intensity_pin * 100) / 4096; xSemaphoreTake(xSemaphore, portMAX_DELAY); light_intensity = [MASK] ; Serial.print(""Light intensity: ""); Serial.print(light_intensity); Serial.print(""%""); Serial.println(); xSemaphoreGive(xSemaphore); } /*----------------------------------------------------------------------------*/ /* SDTR_BlinkLed */ /*----------------------------------------------------------------------------*/ void SDTR_BlinkLed(void *pvParameters) { (void) pvParameters; // A task shall never return or exit for (;;) { SDTR_Blink(); vTaskDelay(100 / portTICK_PERIOD_MS ); //delay of 100ms } } /*----------------------------------------------------------------------------*/ /* SDTR_Blink */ /*----------------------------------------------------------------------------*/ void SDTR_Blink() { xSemaphoreTake(xSemaphore, portMAX_DELAY); if (user_cntrl == false) { if ((distance_cm > MAX_DISTANCE) && (light_intensity < MIN_LIGHT_INTENSITY)) { led_status = true; Serial.println(""Turning on led... ""); // digitalWrite(RED_PIN, LOW); digitalWrite(BLUE_PIN, HIGH); //digitalWrite(GREEN_PIN, HIGH); xSemaphoreGive(xSemaphore); } else { led_status = false; Serial.println(""Turning off led...""); // digitalWrite(RED_PIN, LOW); digitalWrite(BLUE_PIN, LOW); // digitalWrite(GREEN_PIN, LOW); xSemaphoreGive(xSemaphore); } } else { if (led_on == true) { // digitalWrite(RED_PIN, LOW); digitalWrite(BLUE_PIN, HIGH); // digitalWrite(GREEN_PIN, HIGH); } else { // digitalWrite(RED_PIN, LOW); digitalWrite(BLUE_PIN, LOW); // digitalWrite(GREEN_PIN, LOW); } xSemaphoreGive(xSemaphore); } } /* Since LedTurnOn is READ_WRITE variable, onLedTurnOnChange() is executed every time a new value is received from IoT Cloud. */ void onLedTurnOnChange() { led_on = led_turn_on; } /* Since UserControl is READ_WRITE variable, onUserControlChange() is executed every time a new value is received from IoT Cloud. */ void onUserControlChange() { user_cntrl = user_control; }",measured_intensity 268,"#define REMOTEXY_MODE__ESP8266_HARDSERIAL_POINT #include // RemoteXY connection settings #define REMOTEXY_SERIAL Serial #define REMOTEXY_SERIAL_SPEED 115200 #define REMOTEXY_WIFI_SSID ""Elevator prototype"" #define REMOTEXY_WIFI_PASSWORD """" #define REMOTEXY_SERVER_PORT 6377 // RemoteXY configurate #pragma pack(push, 1) uint8_t RemoteXY_CONF[] = // 61 bytes { 255,2,0,0,0,54,0,16,55,1,1,0,23,44,17,17,2,31,85,112, 0,1,0,24,69,17,17,2,31,68,111,119,110,0,129,0,8,25,49,5, 37,87,101,108,99,111,109,101,32,116,111,32,69,108,101,118,97,116,111,114, 0 }; // this structure defines all the variables and events of your control interface struct { // input variables uint8_t button_1; // =1 if button pressed, else =0 uint8_t button_2; // =1 if button pressed, else =0 // other variable uint8_t connect_flag; // =1 if wire connected, else =0 } RemoteXY; #pragma pack(pop) ///////////////////////////////////////////// // END RemoteXY include // ///////////////////////////////////////////// #define MOTOR_SPEED 200 //Right motor int enableRightMotor = 6; int rightMotorPin1 = 7; int rightMotorPin2 = 8; //Left motor int enableLeftMotor = 5; int leftMotorPin1 = 9; int leftMotorPin2 = 10; void setup() { RemoteXY_Init (); TCCR0B = TCCR0B & B11111000 | B00000010; // put your setup code here, to run once: pinMode(enableRightMotor, OUTPUT); pinMode(rightMotorPin1, OUTPUT); pinMode(rightMotorPin2, OUTPUT); pinMode(enableLeftMotor, OUTPUT); pinMode(leftMotorPin1, OUTPUT); pinMode(leftMotorPin2, OUTPUT); rotateMotor(0, 0); } void loop() { RemoteXY_Handler (); if(RemoteXY.button_1==1 ) { rotateMotor(MOTOR_SPEED, 0); } else if(RemoteXY.button_2==1) { rotateMotor(-MOTOR_SPEED, 0); } else { rotateMotor(0, 0); } // use the RemoteXY structure for data transfer // do not call delay(), use instead RemoteXY_delay() } void rotateMotor(int [MASK] , int leftMotorSpeed) { if ( [MASK] < 0) { digitalWrite(rightMotorPin1, LOW); digitalWrite(rightMotorPin2, HIGH); } else if ( [MASK] > 0) { digitalWrite(rightMotorPin1, HIGH); digitalWrite(rightMotorPin2, LOW); } else { digitalWrite(rightMotorPin1, LOW); digitalWrite(rightMotorPin2, LOW); } if (leftMotorSpeed < 0) { digitalWrite(leftMotorPin1, LOW); digitalWrite(leftMotorPin2, HIGH); } else if (leftMotorSpeed > 0) { digitalWrite(leftMotorPin1, HIGH); digitalWrite(leftMotorPin2, LOW); } else { digitalWrite(leftMotorPin1, LOW); digitalWrite(leftMotorPin2, LOW); } analogWrite(enableRightMotor, abs( [MASK] )); analogWrite(enableLeftMotor, abs(leftMotorSpeed)); }",rightMotorSpeed 269,"#pragma once #include ""llvm/IR/Function.h"" #include #include #include #include namespace llvm { struct Context { std::deque values; // e.g., function or instruction Context() = default; Context(std::initializer_list il) : values(il) {} bool operator==(const Context &other) const { return values == other.values; } bool empty() const { return values.empty(); } size_t size() const { return values.size(); } const llvm::Value *operator[](size_t [MASK] ) const { return values[ [MASK] ]; } auto begin() const { return values.begin(); } auto end() const { return values.end(); } void print(llvm::raw_ostream &os) const { os << ""[""; for (size_t i = 0; i < values.size(); ++i) { os << ""("" + std::to_string(i) + "") ""; auto ctx = values[i]; if (ctx) ctx->print(os); else os << ""null""; if (i < values.size() - 1) os << "", ""; } os << ""]""; } }; inline Context Everywhere = Context(); // Singleton instance for context-insensitive analysis // Overload operator<< for Node as a free function inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const llvm::Context &context) { context.print(os); return os; } struct CGNode { int id; // Unique node ID llvm::Function *function; Context context; // Default constructor CGNode() : id(0), function(nullptr), context(Everywhere) {} CGNode(int id, llvm::Function *func, Context ctx = Everywhere) : id(id), function(func), context(ctx) {} bool operator==(const CGNode &other) const { if (function != other.function) return false; if (context == Everywhere && other.context == Everywhere) return true; if (context.size() != other.context.size()) return false; for (size_t i = 0; i < context.size(); ++i) { if (context[i] != other.context[i]) return false; } return true; } void print(llvm::raw_ostream &os) const { os << ""[CGNode id="" << id << "", function=""; if (function) os << function->getName(); else os << ""null""; os << "", context=[""; if (context == Everywhere) { os << ""Everywhere""; } else { context.print(os); } os << ""]""; os << ""]""; } }; inline CGNode NullCGNode = CGNode(); // Singleton instance for empty CGNode // Overload operator<< for Node as a free function inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const llvm::CGNode &node) { node.print(os); return os; } } // namespace llvm namespace std { template <> struct hash { std::size_t operator()(const llvm::Context &ctx) const noexcept { std::size_t h = 0; for (const auto *v : ctx.values) { h ^= std::hash{}(v) + 0x9e3779b9 + (h << 6) + (h >> 2); } return h; } }; template <> struct hash { std::size_t operator()(const llvm::CGNode &node) const noexcept { std::size_t h1 = std::hash{}(node.function); std::size_t h2 = std::hash{}(node.context); return h1 ^ (h2 << 1); } }; template <> struct hash> { std::size_t operator()(const std::pair &p) const noexcept { std::size_t h1 = std::hash{}(p.first); std::size_t h2 = std::hash{}(p.second); return h1 ^ (h2 << 1); } }; } namespace llvm { class CallGraph { private: using NodeKey = std::pair; struct NodeKeyHash { std::size_t operator()(const NodeKey &k) const noexcept { std::size_t h1 = std::hash{}(k.first); std::size_t h2 = 0; if (!k.second.empty()) { for (const auto *v : k.second) { h2 ^= std::hash{}(v) + 0x9e3779b9 + (h2 << 6) + (h2 >> 2); } } // If context is empty, h2 remains 0 return h1 ^ (h2 << 1); } }; int nextNodeId = 0; // Monotonically increasing node ID std::unordered_map idToNodeMap; // Map from node ID to CGNode std::unordered_map ValueContextToNodeMap; public: using CallEdgeSet = std::unordered_set; using Node2EdgeSet = std::unordered_map; CGNode getOrCreateNode(llvm::Function *func, Context ctx = Everywhere); // Add an edge from caller to callee void addEdge(CGNode caller, CGNode callee) { graph_[caller.id].insert(callee.id); } // Get callees for a given caller const CallEdgeSet &getCallees(CGNode caller) const { static CallEdgeSet empty; auto it = graph_.find(caller.id); return it != graph_.end() ? it->second : empty; } const CGNode getNode(int id) const { auto it = idToNodeMap.find(id); return it != idToNodeMap.end() ? it->second : NullCGNode; } const CGNode getNode(llvm::Function *func, Context ctx = Everywhere) const { auto it = ValueContextToNodeMap.find(std::make_pair(func, ctx)); return it != ValueContextToNodeMap.end() ? it->second : NullCGNode; } // Get the underlying map (const) const Node2EdgeSet &getGraph() const { return graph_; } // Get the number of nodes size_t numNodes() const { return graph_.size(); } // Get the number of edges size_t numEdges() const { size_t edges = 0; for (const auto &entry : graph_) edges += entry.second.size(); return edges; } // Iterate over all nodes auto begin() const { return graph_.begin(); } auto end() const { return graph_.end(); } void printCG(std::ofstream &outFile) const; void clear() { graph_.clear(); idToNodeMap.clear(); ValueContextToNodeMap.clear(); } private: Node2EdgeSet graph_; }; } // namespace llvm ",idx 270,"/* * Copyright (C) 2021 Huawei Device Co., Ltd. * 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 ""delivery_callback.h"" #include #include ""napi_util.h"" #include ""telephony_log_wrapper.h"" namespace OHOS { namespace Telephony { DeliveryCallback::DeliveryCallback(bool hasCallback, napi_env env, napi_ref thisVarRef, napi_ref callbackRef) : hasCallback_(hasCallback), env_(env), thisVarRef_(thisVarRef), callbackRef_(callbackRef) {} DeliveryCallback::~DeliveryCallback() { env_ = nullptr; thisVarRef_ = nullptr; callbackRef_ = nullptr; } void CompleteSmsDeliveryWork(uv_work_t *work, int status) { TELEPHONY_LOGI(""CompleteSmsDeliveryWork start""); std::unique_ptr pContext(static_cast(work->data)); if (pContext == nullptr) { TELEPHONY_LOGE(""CompleteSmsDeliveryWork pContext is nullptr!""); return; } napi_env env_ = pContext->env; napi_ref thisVarRef_ = pContext->thisVarRef; napi_ref callbackRef_ = pContext->callbackRef; std::string [MASK] = pContext->pduStr; napi_handle_scope scope = nullptr; napi_open_handle_scope(env_, &scope); if (scope == nullptr) { TELEPHONY_LOGE(""scope is nullptr""); napi_close_handle_scope(env_, scope); return; } napi_value callbackFunc = nullptr; napi_get_reference_value(env_, callbackRef_, &callbackFunc); napi_value callbackValues[2] = {0}; if (! [MASK] .empty()) { callbackValues[0] = NapiUtil::CreateUndefined(env_); napi_create_object(env_, &callbackValues[1]); napi_value arrayValue = nullptr; napi_create_array(env_, &arrayValue); for (uint32_t i = 0; i < static_cast( [MASK] .size()); ++i) { napi_value element = nullptr; int32_t intValue = [MASK] [i]; napi_create_int32(env_, intValue, &element); napi_set_element(env_, arrayValue, i, element); } std::string pduStr = ""pdu""; napi_set_named_property(env_, callbackValues[1], [MASK] .c_str(), arrayValue); } else { callbackValues[0] = NapiUtil::CreateErrorMessage(env_, ""pdu empty""); callbackValues[1] = NapiUtil::CreateUndefined(env_); } napi_value callbackResult = nullptr; napi_value thisVar = nullptr; size_t argc = sizeof(callbackValues) / sizeof(callbackValues[0]); napi_get_reference_value(env_, thisVarRef_, &thisVar); napi_call_function(env_, thisVar, callbackFunc, argc, callbackValues, &callbackResult); napi_delete_reference(env_, thisVarRef_); napi_delete_reference(env_, callbackRef_); napi_close_handle_scope(env_, scope); if (work != nullptr) { delete work; } TELEPHONY_LOGI(""CompleteSmsDeliveryWork end""); } void DeliveryCallback::OnSmsDeliveryResult(const std::u16string pdu) { TELEPHONY_LOGI(""OnSmsDeliveryResult start""); if (hasCallback_) { uv_loop_s *loop = nullptr; napi_get_uv_event_loop(env_, &loop); uv_work_t *work = new uv_work_t; if (work == nullptr) { TELEPHONY_LOGE(""OnSmsDeliveryResult work is nullptr!""); return; } DeliveryCallbackContext *pContext = std::make_unique().release(); if (pContext == nullptr) { TELEPHONY_LOGE(""OnSmsDeliveryResult pContext is nullptr!""); delete work; return; } pContext->env = env_; pContext->thisVarRef = thisVarRef_; pContext->callbackRef = callbackRef_; pContext->pduStr = NapiUtil::ToUtf8(pdu); work->data = static_cast(pContext); uv_queue_work( loop, work, [](uv_work_t *work) {}, [](uv_work_t *work, int status) { CompleteSmsDeliveryWork(work, status); }); } } } // namespace Telephony } // namespace OHOS",pduStr_ 271,"/* * Copyright 2024 WuXi EsionTech Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _PYTHON_BRIDGE_H_ #define _PYTHON_BRIDGE_H_ #include #include #include #include #include #include #include #include #include #include class PythonBridge { private: PythonBridge(); ~PythonBridge(); private: PythonBridge(const PythonBridge &) = delete; PythonBridge(const PythonBridge &&) = delete; PythonBridge &operator=(const PythonBridge &) = delete; PythonBridge &operator=(const PythonBridge &&) = delete; public: // returns singleton instance of python bridge static PythonBridge &getInstance(); public: // keep the python object alive on the C++ side template T track(pybind11::handle py_obj) { static_assert( std::is_pointer::value && (std::is_base_of::type>::value || std::is_base_of::type>::value || std::is_base_of::type>::value || std::is_base_of::type>::value || std::is_base_of::type>::value || std::is_base_of::type>::value || std::is_base_of::type>::value || std::is_base_of::type>::value), ""T must be abstract_device_t, device_factory_t, arg_t, csr_t, rocc_t, "" ""extension_t, insn_desc_t, or disasm_insn_t""); T obj = pybind11::cast(py_obj); uint64_t [MASK] = reinterpret_cast(obj); if (references.emplace( [MASK] , py_obj).second) { py_obj.inc_ref(); } return obj; }; private: // do we need to initialize the python interpreter? bool standalone; // references to python objects that need to be kept alive std::map references; private: static PythonBridge singleton; }; std::string format_ptr(const void *ptr, size_t width = 16); std::ostream &operator<<(std::ostream &os, insn_func_t &f); #endif // _PYTHON_BRIDGE_H_ ",addr 272,"#include ""iostream"" constexpr int SERIES_SIZE = 999; bool sortedArrayIncludes(long *array, int size, long value) { for (int i = 0; i < size; i++) { if (array[i] > value) return false; if (array[i] == value) return true; } return false; } void cleanArray(long *array, int &size, long removeuntil) { int offset = 0; for (int i = 0; i < size; i++) { if (array[i] < removeuntil) continue; // XXX - consider <= offset = i; break; } for (int i = 0; i < size - offset; i++) { array[i] = array[i + offset]; } size -= offset; } int main() { long [MASK] = 1; long series[SERIES_SIZE]; long lastadded = 1; series[0] = lastadded; int size = 1; while (true) { std::cout << lastadded << std::endl; if (size >= SERIES_SIZE) { cleanArray(series, size, [MASK] ); if (size >= SERIES_SIZE) return 0; // Could not free any memory! continue; } if (sortedArrayIncludes(series, size, [MASK] )) { [MASK] ++; continue; } lastadded += [MASK] ; [MASK] ++; series[size] = lastadded, size++; } return 1; }",current 273,"// Board : Arduino Uno/Nano/Micro // Author : // Date : 31 Aug 2022 // Purpose : Driver code for ADF4156 (6.2GHz Fractional-N) PLL Chip. // Pins declarations // Pin Name Arduino Pin Remark // -------- ----------- ------ #define PIN_CLK 13 // Clock #define PIN_DATA 12 // Serial data #define PIN_LE 11 // Latch enable #define PIN_MUXOUT 10 // For checking if PLL is phase-locked or not, // and for debugging. #define PIN_LED 9 // Optional, connect to LED via 1k resistor. #define PIN_TRIGGER 8 // Optional, to trigger oscilloscope. // Global variables declarations #define ASSERT_PIN_LE LOW #define DEASSERT_PIN_LE HIGH byte gbytRead; unsigned int unN; // N divider for frequency synthesizer IC. void setup() { pinMode(PIN_CLK, OUTPUT); pinMode(PIN_DATA, OUTPUT); pinMode(PIN_LE, OUTPUT); pinMode(PIN_LED, OUTPUT); pinMode(PIN_MUXOUT, INPUT); pinMode(PIN_TRIGGER, OUTPUT); Serial.begin(9600); // Setup Serial Port. } void loop() { static byte bytState = 0; static int nTimer = 1; // --- Setup up PLL Chip --- // fosc = 16 MHz // R = 4 // N = 3480 // MOD = 100 // FRAC = 0 // fvco = (N + (FRAC/MOD))*(fosc/R) = 870 MHz. delay(1000); // Load register R4, the CLK DIV register. // 1. The internal clock divider allows the PLL IC to extract clocking signals from the // reference oscillator. This is used for the IC internal logic process such as // lock detection, modulation, fast-lock assist, cycle-slip reduction etc. // Here it is not important and we set the clock divider to 16. Thus: // Assuming fosc = 16MHz, a 1MHz internal clock is generated. // 2. Clock divider mode = off. We set it to other modes when either fast-lock or // cycle-slip reduction functions are activated. nSendData_ADF41XX(0x00000804,32); delay(1); // A short delay for the PLL chip to lock. //Load register R3, the Function Register. // 1. Counter reset = disabled. // 2. CP three-state = disabled. // 3. Power down = disabled. // 4. Phase detector polarity = positive (e.g. rising edge). // 5. Lock detect precision = high. // 6. Sigma-delta reset = yes whenever registor R0 is written. nSendData_ADF41XX(0x00000043,32); delay(1); // A short delay for the PLL chip to lock. //Load register R2, the MOD/R Register. // 1. Here we set the reference divider R to 4 by // D=0, R=4, T=0. // 2. We also use P=8 (e.g. p/p+1) prescalar. This means minimum INT value allowed is 75. // 3. Here we set the modulus (MOD) = 10. // 4. Charge pump current setting = 3 (e.g. (3+1)/16 = 1/4 of max current), // or for Rset = 10kOhm, Icp = (1/4)x2.55 mA = 0.6375 mA. // 5. Cycle-slip reduction = disabled. // 6. Noise mode = Low noise. nSendData_ADF41XX(0x03420322,32); // Low noise mode, M = 100 //nSendData_ADF41XX(0x63420322,32); // Low spur mode, M = 100 delay(1); // A short delay for the PLL chip to lock. // Load register R1, the Phase Register. // We can change the phase of the RF output in relation to the reference signal here // at a resolution of (360degree)/MOD. Thus the value of Phase Register should always // be less than MOD. // If not used, set to 1 as per the recommendation of the datasheet. Note that we // adjust this to optimize the RF output spurs. nSendData_ADF41XX(0x00000009,32); delay(1); // A short delay for the PLL chip to lock. //Load register R0, the FRAC/INT Register. // Here we set: // 1. FRAC = 0. // 2. INT or N = 870. // 3. MUX out = As per application. // Subsequently these can be changed as per application. nSendData_ADF41XX(0x306C8180,32); // N = 217, m = 50 //nSendData_ADF41XX(0x306B8000,32); // N = 215, m = 0 delay(1); // A short delay for the PLL chip to lock. // User routines while (1) { // Uncomment and comment as needed. /* // --- Small sweep 0.1 MHz --- delay(1000); CheckMuxOut(); digitalWrite(PIN_TRIGGER, HIGH); nSendData_ADF41XX(0x31B20000,32); // N + m/M = 868.0 (Make sure M is set properly in R2) digitalWrite(PIN_TRIGGER, LOW); delay(1000); CheckMuxOut(); //nSendData_ADF41XX(0x31B20008,32); // N + m/M = 868.1 (Make sure M is set properly in R2) //delay(1000); //CheckMuxOut(); //nSendData_ADF41XX(0x31B20010,32); // N + m/M = 868.2 (Make sure M is set properly in R2) //delay(1000); //CheckMuxOut(); digitalWrite(PIN_TRIGGER, HIGH); nSendData_ADF41XX(0x31B20018,32); // N + m/M = 868.3 (Make sure M is set properly in R2) digitalWrite(PIN_TRIGGER, LOW); */ // --- Large sweep 10 MHz --- delay(1000); CheckMuxOut(); digitalWrite(PIN_TRIGGER, HIGH); // Optional, to trigger oscilloscope. nSendData_ADF41XX(0x306C8180,32); // N = 217, m = 50, M = 100, fref = 4 MHz. digitalWrite(PIN_TRIGGER, LOW); // fvco = 870 MHz. delay(1000); CheckMuxOut(); digitalWrite(PIN_TRIGGER, HIGH); // Optional, to trigger oscilloscope. nSendData_ADF41XX(0x306B8000,32); // N = 215, m = 0, M =100, fref = 4 MHz. digitalWrite(PIN_TRIGGER, LOW); // fvco = 860 MHz. } } // Function name : SendData_ADF41XX // Author : // Last modified : 22 July 2022 // Description : To send serial data to ADF41XX family of PLL chip via // SPI bus. The length of the data is variable length // (1-32 bits), and data is shifted MSb first. // Arguments : ulnData - unsigned 32 bit data (max length) to be transmitted out. // nLength - Length of data in bits, limited to 32 bits. // Return : 1 if successful // else 0. int nSendData_ADF41XX(unsigned long ulnData, int nLength) { int nCount; int nTemp; unsigned long [MASK] ; if (nLength > 32) // Limit the maximum bit length. { nLength = 32; } [MASK] = ulnData; [MASK] = [MASK] << (32-nLength); // Left shift the data by (32-nLength) // bits so that all the data bits to // be send out occupy left most bit // positions. //digitalWrite(PIN_LE, ASSERT_PIN_LE); for (nCount = 0; nCount < nLength; nCount++) { digitalWrite(PIN_CLK, LOW); if (( [MASK] & 0x80000000) > 0) // Check MSb value. { digitalWrite(PIN_DATA, HIGH); } else { digitalWrite(PIN_DATA, LOW); } nTemp++; // Dummy instruction as delay. digitalWrite(PIN_CLK, HIGH); //nTemp++; // Dummy instruction as delay. [MASK] = [MASK] << 1; // Left shift 1 unit. } digitalWrite(PIN_LE, DEASSERT_PIN_LE); nTemp++; // Dummy instruction as delay. digitalWrite(PIN_LE, ASSERT_PIN_LE); nTemp++; // Dummy instruction as delay. digitalWrite(PIN_DATA, LOW); digitalWrite(PIN_CLK, LOW); return 1; } // Function name : CheckMuxOut // Author : // Last modified : 29 Aug 2022 // Description : To check the status of FoLD pin of ADF41XX family of PLL // chip. Lights up LED is pin is High, else turn off LED. // Arguments : None. // Return : None. void CheckMuxOut() { if (digitalRead(PIN_MUXOUT) == 1) { digitalWrite(PIN_LED, HIGH); } else { digitalWrite(PIN_LED, LOW); } } ",ulnTemp 274,"#include #include #include #define TRUE -1 #define FALSE 0 #define MIN(a,b) ((a)<(b)?(a):(b)) #define MAX(a,b) ((a)<(b)?(b):(a)) #define INTR(com,x,y) {_DX=com;_AH=x;_AL=y;geninterrupt(0x14);} class COMM{ int port,buf_idx; char buf[20]; public: int OpenComm(int ); int OpenComm(char *initstr); void SetSpeed(long speed); void SetData(int); void SetParity(int p); void SetStop(int n); void CharOut(char c); int CharIn(); int WaitChar(); void UnGetChar(int c); long Read(char *buf,long len); long Write(char *buf,long len); void ClrInBuf(); void ClrOutBuf(); unsigned int cbInQue(); unsigned int cbOutQue(); void SetDTR(char state); void SetRTS(char state); int GetCTS(); int GetCarrier(); int GetLineReg(); int GetModemReg(); int DriverPresent(); void DriverRemove(); }; int COMM::OpenComm(int com) { char str[]=""COMx:1200,8,N,1""; str[3]='0'+com; return OpenComm(str); } int COMM::OpenComm(char *initstr) { int cport, [MASK] ,stop,data,sp; long speed; if (sscanf(initstr,""COM%d:%ld,%d,%c,%d"",&cport,&speed,&data,& [MASK] ,&stop)!=5) return FALSE; if (!DriverPresent()) return FALSE; port=MAX(1,MIN(4,cport)); buf_idx=0; if (port!=cport) return FALSE; SetSpeed(speed); SetData(data); SetParity( [MASK] ); SetStop(stop); return TRUE; } void COMM::SetSpeed(long speed) { int b; switch(speed){ case 50: b=1;break; case 75: b=2;break; case 110: b=3;break; case 150: b=4;break; case 300: b=5;break; case 600: b=6;break; case 1200: b=7;break; case 2400: b=8;break; case 9600: b=9;break; case 19200: b=10;break; case 38400: b=11;break; case 115200: b=12;break; default:speed=2400;b=8;break; } INTR(port,0,b); } void COMM::SetData(int data) { data=MAX(5,MIN(8,data)); INTR(port,1,data); } void COMM::SetParity(int p) { switch(toupper(p)){ case 'N': p=0;break; case 'E': p=1;break; case 'O': p=2;break; } INTR(port,2,p); } void COMM::SetStop(int n) { n=MAX(1,MIN(2,n)); INTR(port,3,n); } void COMM::CharOut(char c) { INTR(port,5,c); } int COMM::WaitChar() { int c; while((c=(*this).CharIn())==-1); return c; } int COMM::CharIn() { if (buf_idx) return buf[--buf_idx]; INTR(port,6,0); return _AX; } void COMM::UnGetChar(int c) { buf[buf_idx++]=c; } long COMM::Read(char *buf,long len) { long l=len; while(l--) *buf++=CharIn(); return len; } long COMM::Write(char *buf,long len) { long l; for(l=0;l #include #include #include ""datetime.h"" #include ""utilities.h"" namespace Astro { Date::Date(int year, int month, int day, calendar c) : y(year), m(month), d(day), cal(c) { } DateTime::DateTime(const Date& date, const Time& time) : d{ date }, t{ time } { update_jd(); } void DateTime::update_jd() { bool ok; jd = Utilities::to_julian_day(*this, &ok); if(!ok) { ostringstream msg; msg << ""Invalid date/time: "" << *this; throw runtime_error{ msg.str() }; } } Time::Time(int h, int m, int s) : h(h), m(m), s(s) { updateCount(); } void Time::updateCount() { chrono::duration> [MASK] ; [MASK] = chrono::hours{ h } + chrono::minutes{ m } + chrono::seconds{ s }; c = [MASK] .count(); } void Time::setHour(int hours) { h = hours; updateCount(); } void Time::setMinute(int minutes) { m = minutes; updateCount(); } void Time::setSecond(int seconds) { s = seconds; updateCount(); } ostream& operator<<(ostream& os, const Time& t) { return os << t.hours() << "":"" << t.minutes() << "":"" << t.seconds(); } ostream& operator<<(ostream& os, const Date& d) { return os << d.year() << ""."" << d.month() << ""."" << d.day(); } ostream& operator<<(ostream& os, const DateTime& dt) { return os << dt.date() << "" "" << dt.time(); } }",d_hours 276,"/* * Copyright [2023] [MALABZ_UESTC Pinglu Zhang] * * 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. */ // Author: // Contact: // Created: 2023-02-25 // The main function is the entry point of the program. It is where the program starts executing. // the program starts executing. #include ""include/common.h"" #include ""include/utils.h"" #include ""include/mem_finder.h"" #include ""include/sequence_split_align.h"" #if defined(__linux__) #include ""include/thread_pool.h"" #endif #include GlobalArgs global_args; int main(int argc, char** argv) { // Create a Timer object to record the execution time. Timer timer; // Create an ArgParser object to parse command line arguments. ArgParser parser; std::string output = """"; // Add command line arguments to the ArgParser object. parser.add_argument(""i"", true, ""data/mt1x.fasta""); parser.add_argument_help(""i"", ""The path to the input file.""); parser.add_argument(""t"", false, ""cpu_num""); parser.add_argument_help(""t"", ""The maximum number of threads that the program runs, the recommended setting is the number of CPUs.""); parser.add_argument(""l"", false, ""default""); parser.add_argument_help(""l"", ""The minimum length of MEM, the default value is square root of mean length.""); parser.add_argument(""c"", false, ""1""); parser.add_argument_help(""c"", ""A floating-point parameter that specifies the minimum coverage across all sequences, with values ranging from 0 to 1. The default \ setting is that if sequence number less 100, parameter is set to 1 otherwise 0.7.""); parser.add_argument(""p"", false, ""mafft""); parser.add_argument_help(""p"", ""The MSA method used in parallel align. for example, halign3, halign2 and mafft.""); parser.add_argument(""o"", false, ""output.fmaligned2.fasta""); parser.add_argument_help(""o"", ""The path to the output file.""); parser.add_argument(""d"", false, ""0""); parser.add_argument_help(""d"", ""Depth of recursion, you could ignore it.""); parser.add_argument(""f"", false, ""default""); parser.add_argument_help(""f"", ""The filter MEMs mode. The default setting is that if sequence number less 100, local mode otherwise global mode.""); parser.add_argument(""v"", false, ""1""); parser.add_argument_help(""v"", ""Verbose option, 0 or 1. You could ignore it.""); parser.add_argument(""h"", false, ""help""); parser.add_argument_help(""h"", ""print help information""); // Add command line arguments to the ArgParser object. try { parser.parse_args(argc, argv); global_args.data_path = parser.get(""i""); std::string tmp_thread = parser.get(""t""); if (tmp_thread == ""cpu_num"") { global_args.thread = std::thread::hardware_concurrency(); } else { global_args.thread = std::stoi(tmp_thread); } std::string tmp_len = parser.get(""l""); if (tmp_len != ""default"") { global_args.min_mem_length = std::stoi(parser.get(""l"")); } else { global_args.min_mem_length = -1; } std::string tmp_filter_mode = parser.get(""f""); if (tmp_filter_mode == ""default"") { global_args.filter_mode = tmp_filter_mode; } else if (tmp_filter_mode == ""global"" || tmp_filter_mode == ""local"") { global_args.filter_mode = tmp_filter_mode; } else { throw ""filer mode --f parameter should be global or local!""; } global_args.verbose = std::stoi(parser.get(""v"")); if (global_args.verbose != 0 && global_args.verbose != 1) { throw ""verbose should be 1 or 0""; } global_args.degree = std::stoi(parser.get(""d"")); if (global_args.degree > 2) { exit(1); } std::string tmp_c = parser.get(""c""); if (tmp_c == ""default"") { global_args.min_seq_coverage = -1; } else { global_args.min_seq_coverage = std::stof(parser.get(""c"")); if (global_args.min_seq_coverage < 0 || global_args.min_seq_coverage > 1) { throw ""Error: min_seq_coverage should be ranged from 0 to 1!""; } } global_args.package = parser.get(""p""); if (global_args.package != ""halign2"" && global_args.package != ""halign3"" && global_args.package != ""mafft"") { throw (""Error: "" + global_args.package + "" is a invalid method!""); } global_args.output_path = parser.get(""o""); } // Catch any invalid arguments and print the help message. catch (const std::invalid_argument& e) { std::cerr << ""Error: "" << e.what() << std::endl; std::cerr << ""Program Exit!"" << std::endl; parser.print_help(); return 1; } if (global_args.verbose) { print_algorithm_info(); } std::vector data; std::vector name; try { // Read data from the input file and store in data and name vectors read_data(global_args.data_path.c_str(), data, name, true); // Find MEMs in the sequences and split the sequences into fragments for parallel alignment. std::vector>> split_points_on_sequence = find_mem(data); split_and_parallel_align(data, name, split_points_on_sequence); } catch (const std::bad_alloc& e) { // Catch any bad allocations and print an error message. print_table_bound(); std::cerr << ""Error: "" << e.what() << std::endl; std::cout << ""Program Exit!"" << std::endl; exit(1); } double [MASK] = timer.elapsed_time(); std::stringstream s; s << std::fixed << std::setprecision(2) << [MASK] ; if (global_args.verbose) { output = ""FMAlign2 total time: "" + s.str() + "" seconds.""; print_table_line(output); print_table_bound(); } return 0; }",total_time 277,"#include ""character.h"" #include #include #include #include bool empty_age(std::string const &age) { if(age.empty()) { return false; } for(char val : age) { if(!iswdigit(val)) { return false; } } return true; } bool age_controller(int [MASK] , const Character &game_character) { initscr(); cbreak(); WINDOW * startwin = newwin(10, 90, 0, 0); box(startwin, 0 , 0); refresh(); wrefresh(startwin); if( [MASK] >= 18) { mvwprintw(startwin, 3, 30, ""Welcome to the game 'Paradigma'!""); wrefresh(startwin); mvwprintw(startwin, 4, 18, ""Your character was created, your character`s name is: %s"", game_character.Get_name().c_str()); wrefresh(startwin); sleep(3); return true; } else { if( [MASK] == 0) { mvwprintw(startwin, 4, 25, ""Impossible 0_0""); wrefresh(startwin); sleep(3); return false; } else { mvwprintw(startwin, 4, 25, ""You are too young to play in this game""); wrefresh(startwin); sleep(3); return false; } } } bool name_controller(std::string const &input_name) { return !input_name.empty(); } bool only_letters(std::string const &input_name) { return std::all_of(input_name.begin(), input_name.end(), [] (char const &c) { return std::isalpha(c); }); } void start_game(std::string start) { initscr(); cbreak(); WINDOW * startwin = newwin(10, 90, 0, 0); box(startwin, 0 , 0); refresh(); wrefresh(startwin); start = ""Game will start now""; mvwprintw(startwin, 3, 35, ""%s"", start.c_str()); wrefresh(startwin); } ",input_age 278,"class Solution { public://先对数组排个序。枚举第一个数,然后设两个指针,在第一个数的后半段开始王中间收缩,if sum > target则右指针往左移, if sum < target则左指针往右移。排序O(nlogn) + 查找O(n^2) = O(n^2) void quicksort(vector& nums,int [MASK] ,int end) { // 快排 if( [MASK] >=end) return ; int i= [MASK] ,j=end,t=nums[ [MASK] ]; // 将基准挖出形成一个坑 while(i=t&&j>i) --j; // 找到右边第一个小于基准的值 if(j>i) nums[i++]=nums[j]; // 填坑 这时j位置为坑 while(nums[i]& nums, int target) { if(nums.size()<3) return 0; //sort(nums.begin(),nums.end()); quicksort(nums,0,nums.size()-1); int i=0,j,k,sum,result; int min=INT_MAX; while(itarget) --k; else ++j; } ++i; } return result; } };",start 279,"#pragma once #include #include ""board.hpp"" #include ""matrix_algorithm.hpp"" #include ""mod_int.hpp"" #include ""point.hpp"" #include ""snake.hpp"" #include ""snake_arithmetic.hpp"" namespace snk { namespace __details { inline auto fill_snake_matrix(std::vector>& matrix, snake const& snake) { for (auto const& point : snake.body()) { auto const x = static_cast(point.x.value()); auto const y = static_cast(point.y.value()); matrix[y][x].set_body(); } auto const [MASK] = static_cast(snake.head().x.value()); auto const head_y = static_cast(snake.head().y.value()); matrix[head_y][ [MASK] ].clear_body(); matrix[head_y][ [MASK] ].set_head(); } inline auto fill_fruit_matrix(std::vector>& matrix, point const& fruit) { matrix[fruit.y][fruit.x].set_fruit(); } } // namespace __details // Precondition: // - board.snake.head().x.modulus() == width // - board.snake.head().y.modulus() == height // - board.fruit_pos.x < width // - board.fruit_pos.y < height // Postcondition: // - Returns a matrix with #rows = board.height, #cols = board.width // - if matrix[y][x] represents board at position (x, y) is occupied with // matrix[y][x] value inline auto create_board_matrix(snk::board const& b) { std::vector matrix(b.height, std::vector(b.width, cell_info{})); __details::fill_snake_matrix(matrix, b.snake); __details::fill_fruit_matrix(matrix, b.fruit_pos); return matrix; } // Precondition: // - matrix[y][x] represents the board position info at position (x, y) // Postcondition: // - returns a point (x, y) that is empty cell // - in case of no empty point is found nullopt is returned template std::optional> select_empty_cell( std::vector> const& matrix, RandomGenerator&& generator) { auto const empty_cnt = nostd::count(matrix, cell_info{}); if (empty_cnt == 0) return point{matrix[0].size(), matrix.size()}; auto const nth = static_cast(generator(1, static_cast(empty_cnt))); auto const cell = nostd::find_n(matrix, cell_info{}, nth); return point{cell.second, cell.first}; } // Postcondition: // - returns a point (x, y) that is empty cell // - in case of no empty point is found nullopt is returned template auto generate_fruit(snk::board const& board, RandomGenerator&& rand) { return select_empty_cell(create_board_matrix(board), std::forward(rand)); } // Postcondition: // - returns is_collided_to_self(board.snake) inline auto has_collision(snk::board const& board) { return is_collided_to_self(board.snake); } // Postcondition: // - returns true if snake head is on fruit inline auto ate_fruit(snk::board const& board) { return static_cast(board.snake.head().x.value()) == board.fruit_pos.x && static_cast(board.snake.head().y.value()) == board.fruit_pos.y; } } // namespace snk ",head_x 280,"#include #include ""mbot.h"" using namespace std; std::array odom_pose_covariance = { {1e-9, 0, 0, 0, 0, 0, 0, 1e-3,1e-9, 0, 0, 0, 0, 0, 1e6, 0, 0, 0, 0, 0, 0, 1e6, 0, 0, 0, 0, 0, 0, 1e6, 0, 0, 0, 0, 0, 0, 1e-9}}; std::array odom_twist_covariance = { {1e-9, 0, 0, 0, 0, 0, 0, 1e-3,1e-9, 0, 0, 0, 0, 0, 1e6, 0, 0, 0, 0, 0, 0, 1e6, 0, 0, 0, 0, 0, 0, 1e6, 0, 0, 0, 0, 0, 0, 1e-9}}; #define PI (3.1415926) #define ROBOT_RADIUS (0.032) //m #define ROBOT_TRACK (0.062) //m #define CAR_LENGTH (0.243) //m double RobotV_ = 0; double YawRate_ = 0; // 速度控制消息的回调函数 void cmdCallback(const geometry_msgs::msg::Twist& msg) { RobotV_ = msg.linear.x; //m/s YawRate_ = msg.angular.z; //rad/s } Mbot::Mbot(): Node(""mbot_bringup""), x_(0.0), y_(0.0), th_(0.0), vx_(0.0), vy_(0.0), vth_(0.0), sendLeftSpeed_(0),sendRightSpeed_(0),sendFrontAngle_(0),sendFlag_(0), readLeftSpeed_(0),readRightSpeed_(0),readYaw_(0),readFlag_(0) { // 实例化参数列表 this->declare_parameter(""serial_port"", ""/dev/ttyUSB0""); this->declare_parameter(""odom_topic"", ""odom""); this->declare_parameter(""odom_frame_id"", ""odom""); this->declare_parameter(""base_frame_id"", ""base_link""); this->declare_parameter(""sub_twist"", ""cmd_vel""); this->declare_parameter(""diffCar_or_ackerCar"", false); // 从系统中获取参数值 this->get_parameter(""serial_port"", serial_name_); this->get_parameter(""odom_topic"", odom_topic_name_); this->get_parameter(""odom_frame_id"", odom_frame_name_); this->get_parameter(""base_frame_id"", base_frame_name_); this->get_parameter(""sub_twist"", sub_twist_name_); this->get_parameter(""diffCar_or_ackerCar"", car_type_select_); // 串口初始化连接 mbotSerial_.mbotSerialInit(serial_name_); // 时间相关初始化 current_time_ = this->get_clock()->now(); last_time_ = this->get_clock()->now(); // 实例化定时器,50Hz timer_ = this->create_wall_timer(20ms, std::bind(&Mbot::mainThread,this)); // 订阅cmd_vel sub_ = this->create_subscription(sub_twist_name_,10, cmdCallback); // 发布odom pub_ = this->create_publisher(odom_topic_name_,50); // 发布tf odom_t_broadcaster_ = std::make_unique(*this); } Mbot::~Mbot(){} void Mbot::diffCar(const double RobotV,const double YawRate) { double r = RobotV / YawRate; // m // std::cout << ""RobotV = "" << RobotV << ""YawRate = "" << YawRate << std::endl; if(RobotV == 0) // 旋转 { sendLeftSpeed_ = (short)(-YawRate * 1000.0 * ROBOT_RADIUS);//mm/s sendRightSpeed_ = (short)(YawRate * 1000.0 * ROBOT_RADIUS);//mm/s } else if(YawRate == 0) // 直线 { sendLeftSpeed_ = (short)(RobotV * 1000.0);//mm/s sendRightSpeed_ = (short)(RobotV * 1000.0); } else // 左右轮速度不一致 { sendLeftSpeed_ = (short)(YawRate * 1000.0 * (r - ROBOT_RADIUS));//mm/s sendRightSpeed_ = (short)(YawRate * 1000.0 * (r + ROBOT_RADIUS)); } // std::cout << ""sendLeftSpeed_ = "" << sendLeftSpeed_ << "" sendRightSpeed_ = "" << sendRightSpeed_ << std::endl; } void Mbot::ackerCar(const double RobotV,const double YawRate) { double r = RobotV / YawRate; // m if(RobotV == 0) // ackermann car can't trun rotation { sendLeftSpeed_ = 0; sendRightSpeed_ = 0; sendFrontAngle_ = 0; } else if(YawRate == 0) // Pure forward/backward motion { sendLeftSpeed_ = (short)(RobotV * 1000.0);//mm/s sendRightSpeed_ = (short)(RobotV * 1000.0); sendFrontAngle_ = 0; } else // Rotation about a point in space { sendLeftSpeed_ = (short)(YawRate * 1000.0 * (r - ROBOT_RADIUS));//mm/s sendRightSpeed_ = (short)(YawRate * 1000.0 * (r + ROBOT_RADIUS)); // 阿克曼约束一:后左右车轮转动需同向 if(RobotV > 0) { if(sendLeftSpeed_ < 0) {sendLeftSpeed_ = 0;} if(sendRightSpeed_ < 0) {sendRightSpeed_ = 0;} } else if(RobotV < 0) { if(sendLeftSpeed_ > 0) {sendLeftSpeed_ = 0;} if(sendRightSpeed_ > 0) {sendRightSpeed_ = 0;} } // 阿克曼约束二:满足前轮转向和后轮的速度关系 // # calculate the front steer servo sendFrontAngle_ = atan(CAR_LENGTH * YawRate / RobotV ) * (180.0 / PI); // Deg RCLCPP_INFO(this->get_logger(),""sendFrontAngle_ = %d\n"",sendFrontAngle_); // sendFrontAngle_ = (atan(2 * YawRate * CAR_LENGTH) / (2 * RobotV - 2 * ROBOT_RADIUS * YawRate)) * (180.0 / PI); } // std::cout << ""sendLeftSpeed_ = "" << sendLeftSpeed_ << "" sendRightSpeed_ = "" << sendRightSpeed_ << std::endl; // std::cout << ""sendFrontAngle_ = "" << sendFrontAngle_ << std::endl; } void Mbot::calcSpeed(const short leftSpeedNow,const short rightSpeedNow,const short [MASK] ) { // x方向速度,以及角速度 vx_ = (rightSpeedNow + leftSpeedNow) / 2.0 / 1000.0; //m/s vth_ = (rightSpeedNow - leftSpeedNow) / (2.0 * ROBOT_RADIUS*1000.0) ; //rad/s th_ = ( [MASK] / 50.0) * M_PI / 180.0; //rad } /******************************************************** 函数功能:根据机器人线速度和角度计算机器人里程计 入口参数:无 出口参数:无 ********************************************************/ void Mbot::calcOdom(const double vx, const double vy, const double vth) { rclcpp::Time curr_time; curr_time = this->get_clock()->now(); double dt = (curr_time - last_time_).seconds(); //间隔时间 double delta_x = (vx * cos(th_) - vy * sin(th_)) * dt; double delta_y = (vx * sin(th_) + vy * cos(th_)) * dt; double delta_th = vth * dt; //相隔20ms RCLCPP_INFO(this->get_logger(),""dt:%f\n"",dt); // s x_ += delta_x; y_ += delta_y; // th_ += delta_th;//实时角度信息,如果这里不使用IMU,也可以通过这种方式计算得出 last_time_ = curr_time; RCLCPP_INFO(this->get_logger(),""x_:%f\n"",x_); RCLCPP_INFO(this->get_logger(),""y_:%f\n"",y_); RCLCPP_INFO(this->get_logger(),""th_:%f\n"",th_*57.3); } void Mbot::sendTfAndPubOdom() { current_time_ = this->get_clock()->now(); // 发布TF geometry_msgs::msg::TransformStamped odom_t; odom_t.header.stamp = current_time_; odom_t.header.frame_id = odom_frame_name_; odom_t.child_frame_id = base_frame_name_; tf2::Quaternion odom_quat; odom_quat.setRPY(0,0,th_); odom_t.transform.translation.x = x_; odom_t.transform.translation.y = y_; odom_t.transform.translation.z = 0.0; odom_t.transform.rotation.x = odom_quat.x(); odom_t.transform.rotation.y = odom_quat.y(); odom_t.transform.rotation.z = odom_quat.z(); odom_t.transform.rotation.w = odom_quat.w(); odom_t_broadcaster_->sendTransform(odom_t); nav_msgs::msg::Odometry msg; msg.header.stamp = current_time_; msg.header.frame_id = odom_frame_name_; msg.pose.pose.position.x = x_; msg.pose.pose.position.y = y_; msg.pose.pose.position.z = 0.0; msg.pose.pose.orientation.x = odom_quat.x(); msg.pose.pose.orientation.y = odom_quat.y(); msg.pose.pose.orientation.z = odom_quat.z(); msg.pose.pose.orientation.w = odom_quat.w(); msg.pose.covariance = odom_pose_covariance; msg.child_frame_id = base_frame_name_; msg.twist.twist.linear.x = vx_; msg.twist.twist.linear.y = vy_; msg.twist.twist.angular.z = vth_; msg.twist.covariance = odom_twist_covariance; pub_->publish(msg); } /******************************************************** 函数功能:mbotRun,实现整合,并且发布TF变换和Odom 入口参数:机器人线速度和角速度,调用上面三个函数 出口参数:bool ********************************************************/ void Mbot::mbotRun(double RobotV, double YawRate) { // * 1. 根据车模解析控制量 if(car_type_select_) { diffCar(RobotV, YawRate); } else { ackerCar(RobotV, YawRate); } // * 2. 与STM32串口通信,线材一定要短且优质 mbotSerial_.mbotWrite(sendLeftSpeed_, sendRightSpeed_, sendFrontAngle_, sendFlag_); mbotSerial_.mbotRead(readLeftSpeed_, readRightSpeed_, readYaw_, readFlag_); // * 3. 更新最新的速度和角度信息 calcSpeed(readLeftSpeed_, readRightSpeed_, readYaw_); // * 4. 里程计计算 calcOdom(vx_, vy_, vth_); // * 5. 发布TF和Odom sendTfAndPubOdom(); } /******************************************************** 函数功能:主函数线程 入口参数:机器人线速度和角速度,调用上面三个函数 出口参数:无 ********************************************************/ void Mbot::mainThread() { mbotRun(RobotV_, YawRate_); }",yaw 281,"#ifndef GENERIC_UTILS_H #define GENERIC_UTILS_H #include //new array and multidimensional arrays template T* new_array1(int a, U... params) { size_t s = 1*sizeof(int) + a*sizeof(T); char* chunk = (char*) malloc(s); int* sp = (int*) chunk; T* data = (T*) (chunk + 1*sizeof(int)); sp[0] = a; for (int i=0; i void delete_array1(T* data) { char* chunk = (char*) data; int* sp = (int*) (chunk - 1*sizeof(int)); int a = sp[0]; for (int i=0; i~T(); free(sp); //address of the original chunk }; template T** new_array2(int a, int b, U... params) { size_t s = 2*sizeof(int) + a*b*sizeof(T) + a*sizeof(T*); char* chunk = (char*) malloc(s); int* sp = (int*) chunk; T** data2 = (T**) (chunk + 2*sizeof(int)); T* data1 = (T*) (chunk + 2*sizeof(int) + a*sizeof(T*)); sp[0] = a; sp[1] = b; for (int i=0; i void delete_array2(T** data) { char* chunk = (char*) data; int* sp = (int*) (chunk - 2*sizeof(int)); int a = sp[0]; int b = sp[1]; T* data1 = data[0]; for (int i=0; i~T(); free(sp); //address of the original chunk }; template T*** new_array3(int a, int b, int c, U... params) { size_t s = 3*sizeof(int) + a*b*c*sizeof(T) + a*b*sizeof(T*) + a*sizeof(T**); char* chunk = (char*) malloc(s); int* sp = (int*) chunk; T*** data3 = (T***) (chunk + 3*sizeof(int)); T** data2 = (T**) (chunk + 3*sizeof(int) + a*sizeof(T**)); T* data1 = (T*) (chunk + 3*sizeof(int) + a*sizeof(T**) + a*b*sizeof(T*)); sp[0] = a; sp[1] = b; sp[2] = c; for (int i=0; i void delete_array3(T*** data) { char* chunk = (char*) data; int* sp = (int*) (chunk - 3*sizeof(int)); int a = sp[0]; int b = sp[1]; int c = sp[2]; T* data1 = data[0][0]; for (int i=0; i~T(); free(sp); //address of the original chunk }; template T**** new_array4(int a, int b, int c, int d, U... params) { size_t s = 4*sizeof(int) + a*b*c*d*sizeof(T) + a*b*c*sizeof(T*) + a*b*sizeof(T**) + a*sizeof(T***); char* chunk = (char*) malloc(s); int* sp = (int*) chunk; T**** data4 = (T****) (chunk + 4*sizeof(int)); T*** data3 = (T***) (chunk + 4*sizeof(int) + a*sizeof(T***)); T** data2 = (T**) (chunk + 4*sizeof(int) + a*sizeof(T***) + a*b*sizeof(T**)); T* data1 = (T*) (chunk + 4*sizeof(int) + a*sizeof(T***) + a*b*sizeof(T**)+ a*b*c*sizeof(T*)); sp[0] = a; sp[1] = b; sp[2] = c; sp[3] = d; for (int i=0; i void delete_array4(T**** data) { char* chunk = (char*) data; int* sp = (int*) (chunk - 4*sizeof(int)); int a = sp[0]; int b = sp[1]; int c = sp[2]; int d = sp[3]; T* data1 = data[0][0][0]; for (int i=0; i~T(); free(sp); //address of the original chunk }; ////////////// //#define FALSE_RANDOM #ifdef FALSE_RANDOM inline int random_bit() { return 1; } inline int32_t random_int32() { return 0xcccccccc; } inline int64_t random_int64() { return 0xccccccccccccccccul; } inline double random_gaussian_double(double center, double stdev) { return center; } inline int32_t random_gaussian32(int32_t center, double stdev) { return center; } inline int64_t random_gaussian64(int64_t center, double stdev) { return center; } class Random {}; #else /////// TRUE RANDOM class Random { public: std::default_random_engine generator; std::uniform_int_distribution bit_distribution; std::uniform_int_distribution int32_distribution; std::uniform_int_distribution int64_distribution; std::normal_distribution gaussian_distribution; Random(): bit_distribution(0,1), int32_distribution(std::numeric_limits::min(),std::numeric_limits::max()), int64_distribution(std::numeric_limits::min(),std::numeric_limits::max()), gaussian_distribution(0.,1.) {} }; extern Random* global_random; inline int random_bit() { return global_random->bit_distribution(global_random->generator); } inline int32_t random_int32() { return global_random->int32_distribution(global_random->generator); } inline int64_t random_int64() { return global_random->int64_distribution(global_random->generator); } inline double random_gaussian_double(double center, double stdev) { return stdev*global_random->gaussian_distribution(global_random->generator)+center; } inline int32_t random_gaussian32(int32_t center, double stdev) { static const double [MASK] = pow(2.,32); double val = stdev*global_random->gaussian_distribution(global_random->generator)* [MASK] ; int32_t ival = (int32_t) val; return ival+center; } inline int64_t random_gaussian64(int64_t center, double stdev) { static const double _2p64 = pow(2.,64); double val = stdev*global_random->gaussian_distribution(global_random->generator)*_2p64; int64_t ival = (int64_t) val; //printf(""ival: %ld\n"", ival); return ival+center; } #endif //////////// #endif // GENERIC_UTILS_H ",_2p32 282,"#include ""Motor.h"" #define DEBUG_LOG false void Motor::begin(short rpm, int accel){ this->rpm = rpm; this->accel = accel; } short Motor::getRPM() { return rpm; } void Motor::setRPM(short rpm) { this->rpm = rpm; } short Motor::getAcceleration() { return accel; } void Motor::setAcceleration(int accel) { this->accel = accel; } void Motor::enable() { digitalWrite(enablePin, LOW); } void Motor::disable(){ digitalWrite(enablePin, HIGH); } void Motor::rotate(long deg){ move(calcStepsForRotation(deg)); } long Motor::calcStepsForRotation(long deg){ return deg * motorSteps / 360; } #define ACCELERATING 0 #define CRUISING 1 #define BRAKING 2 void Motor::move(long steps){ short dirState = steps >= 0 ? HIGH : LOW; digitalWrite(dirPin, dirState); long totalSteps = abs(steps); unsigned long cruisePulseLength = 60000000L / ((long)rpm * motorSteps); unsigned long cruiseStepsPerSecond = (long)rpm * motorSteps / 60; long stepsToCruise = cruiseStepsPerSecond * cruiseStepsPerSecond / (2 * accel); long stepsToBrake = stepsToCruise; // = stepsToCruise * accel / decel bool cruiseSpeedAchieved = true; if (totalSteps < stepsToCruise + stepsToBrake){ // cannot reach max speed, will need to brake early stepsToCruise = totalSteps / 2; // = steps * decel / (accel + decel); stepsToBrake = totalSteps - stepsToCruise; cruiseSpeedAchieved = false; } #ifdef DEBUG_LOG Serial.println(); Serial.println(""rpm: "" + String(rpm)); Serial.println(""rps: "" + String((float)rpm / 60)); Serial.println(""motorSteps: "" + String(motorSteps)); Serial.println(""accel: "" + String(accel)); Serial.println(""cruisePulseLength: "" + String(cruisePulseLength) + "" us""); Serial.println(""cruiseStepsPerSecond: "" + String(cruiseStepsPerSecond)); Serial.println(""totalSteps: "" + String(totalSteps)); Serial.println(""stepsToCruise: "" + String(stepsToCruise)); Serial.println(""stepsToBrake: "" + String(stepsToBrake)); short debugEntries = 10; short halfDebugEntries = debugEntries/2; long stepNumbers[3][debugEntries]; long remSteps[3][debugEntries]; long actualTimes[3][debugEntries]; long desiredTimes[3][debugEntries]; long processingTimes[3][debugEntries]; for (short state=0; state<3; state++) { for (short i=0; i= totalSteps - stepsToBrake) { // braking float sqrtOfNextStep = sqrt((float)stepsRemaining-1.0); desiredPulseLength = (long)(millionTimesSqrtOf2DivA * (sqrtOfCurrStep - sqrtOfNextStep)); sqrtOfCurrStep = sqrtOfNextStep; } else { // cruising desiredPulseLength = cruisePulseLength; } #ifdef DEBUG_LOG if (step < stepsToCruise) { state = ACCELERATING; internalStep = step; totalInternalSteps = stepsToCruise; } else if (step >= totalSteps - stepsToBrake) { state = BRAKING; internalStep = step - (totalSteps - stepsToBrake); totalInternalSteps = stepsToBrake; } else { state = CRUISING; internalStep = step - stepsToCruise; totalInternalSteps = totalSteps - stepsToCruise - stepsToBrake; } previousTime = pulseStartTime; if (internalStep < halfDebugEntries || internalStep >= totalInternalSteps - halfDebugEntries) { short pos = internalStep < halfDebugEntries ? internalStep : (internalStep - totalInternalSteps + debugEntries); stepNumbers[state][pos] = step; remSteps[state][pos] = stepsRemaining; actualTimes[state][pos] = microsSincePrevPulse; desiredTimes[state][pos] = desiredPulseLength; } #endif unsigned long processingTime = micros() - pulseStartTime; #ifdef DEBUG_LOG if (internalStep < halfDebugEntries || internalStep >= totalInternalSteps - halfDebugEntries) { short pos = internalStep < halfDebugEntries ? internalStep : (internalStep - totalInternalSteps + debugEntries); processingTimes[state][pos] = processingTime; } #endif if (desiredPulseLength > processingTime) { delayMicroseconds(desiredPulseLength - processingTime); } } #ifdef DEBUG_LOG for (short state=0; state<3; state++) { if (state == CRUISING && !cruiseSpeedAchieved) { continue; } for (int i=0; i #include #include #include ""innards.h"" #include ""player.h"" #include ""room.h"" using namespace std; /** * Shows the help menu */ void help(); /** * Sets up the console */ void setup(); /** * Converts a string to lowercase * @param str the string to convert * @return the converted string */ string toLowerCase(string str); /** * Prints the options for the player * @param player the player * @param map the map */ void printOptions(const Player *player, const Map *map); int main() { setup(); auto *player = new Player(); const auto map = new Map(player); string input; string [MASK] ; bool debug = false; cout << ""Play in debug mode? (y/n): ""; cin >> input; if (toLowerCase(input) == ""y"") { debug = true; } input = """"; while (input != ""q"" && !map->is_over()) { if (debug) { map->display(player->getRoom()); } player->printNear(); printOptions(player, map); cin >> input; input = toLowerCase(input); if (input == ""h"") { help(); } else if (input == ""m"") { map->display(player->getRoom()); } else if (input == ""r"") { while ( [MASK] != ""n"" && [MASK] != ""s"" && [MASK] != ""e"" && [MASK] != ""w"") { cout << ""use harpoon in which direction? (n/s/e/w): ""; cin >> [MASK] ; [MASK] = toLowerCase( [MASK] ); } player->useItem(*map, 'h', [MASK] .at(0)); [MASK] = """"; } else if (input == ""t"") { while ( [MASK] != ""n"" && [MASK] != ""s"" && [MASK] != ""e"" && [MASK] != ""w"") { cout << ""use net in which direction? (n/s/e/w): ""; cin >> [MASK] ; [MASK] = toLowerCase( [MASK] ); } player->useItem(*map, 't', [MASK] .at(0)); [MASK] = """"; } else if (input == ""n"" || input == ""s"" || input == ""e"" || input == ""w"") { player->playerMove(input.at(0)); player->getRoom()->getInnard()->trigger(*map, *player); int airRemaining = player->getAir(); if (airRemaining > 0 && !map->is_over()) { cout << ""You have "" << airRemaining << "" units of oxygen remaining"" << endl; } else if (!map->is_over()) { cout << ""You have run out of air."" << endl; map->set_game_over(true); map->set_win(false); } } } if (map->is_win()) { cout << ""You win!""; } else { cout << ""You lose!""; } delete map; delete player; return 0; } void help() { // This is pure text output for the help menu, so the size of the method is // not a concern cout << ""Welcome to hunt the Kraken. You are a deep sea scuba diver seeking "" ""to kill the Kraken before you run out of oxygen. The sea floor is "" ""divided into 30 spaces in a 5 high 6 wide rectangle. Each space is "" ""connected to 4 others."" << endl << endl; cout << ""Hazards:"" << endl; cout << ""Whirlpool - One space has a whirlpool. If you go there, you will be "" ""whisked away to a random space and will lose 11 oxygen."" << endl; cout << ""Riptide - Two spaces have riptides. If you go there, you will be "" ""whisked away to a random space on the edge of the map and will lose "" ""6 oxygen."" << endl << endl; cout << ""Kraken:"" << endl; cout << ""If you attempt to move into the Kraken's space, it eats you and you "" ""lose."" << endl << endl; cout << ""You:"" << endl; cout << ""Each turn you may move or use a weapon."" << endl; cout << ""Moving: You can move one space North, South, East, or West if there "" ""is a room in that direction."" << endl; cout << ""Oxygen: Each move consumes 1 Oxygen. If you run out of Oxygen you "" ""lose. There is one Oxygen tank that you can find. You start with 50 "" ""Oxygen"" << endl; cout << ""Using Weapons: You can use the Harpoon to attack an adjacent space "" ""(you start with 1 harpoon and can find 2 more)."" << endl; cout << ""If you hit the Kraken with a Harpoon, you win."" << endl; cout << ""If you find the net, you can throw it to see if the Kraken is "" ""hiding in any of the nearest 3 spaces in the direction you choose. "" ""The net does not kill the Kraken."" << endl; cout << ""You will be given hints indicating when a hazard or the Kraken is "" ""nearby."" << endl << endl; } void setup() { // get the console handle HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); // set the console text color SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE); } string toLowerCase(string str) { // easy way to convert a string to lowercase to make input case insensitive transform(str.begin(), str.end(), str.begin(), ::tolower); return str; } void printOptions(const Player *player, const Map *map) { // Only showing the options that are possible according to the map cout << ""\nAction: ""; if (Map::roomExists(player->getRoom(), 'n')) { cout << ""(N)orth, ""; } if (Map::roomExists(player->getRoom(), 's')) { cout << ""(S)outh, ""; } if (Map::roomExists(player->getRoom(), 'e')) { cout << ""(E)ast, ""; } if (Map::roomExists(player->getRoom(), 'w')) { cout << ""(W)est, ""; } cout << ""(M)ap, (H)elp""; if (player->getHarpoons() > 0) { cout << "", shoot ha(R)poon""; } if (player->getNets() > 0) { cout << "", use ne(T)""; } cout << "", Q)uit: ""; } ",weaponDir 284,"/* * namespace WServer::WTypes:: */ #include #include #include namespace WServer { namespace WTypes { WSocket::~WSocket() { __xsocket_cleanup(); xsocket_close(sockfd_); }; WSocket::WSocket(const std::string &socket) { if (std::regex_search(socket, socket_sm_, socket_rgx_)) { if (socket_sm_.size() != 6) { throw std::runtime_error(WServer::WDebug::WMessage{ WServer::WDebug::WPrefix, ""WSocket(const std::string &socket) failed"" "", regular expression groups error (ip:port)""}); } socket_ = socket; ip_.oct.a = (uint8_t)std::stoull(socket_sm_[1].str()); ip_.oct.b = (uint8_t)std::stoull(socket_sm_[2].str()); ip_.oct.c = (uint8_t)std::stoull(socket_sm_[3].str()); ip_.oct.d = (uint8_t)std::stoull(socket_sm_[4].str()); port_ = (uint16_t)std::stoull(socket_sm_[5].str()); } else { throw std::runtime_error( WServer::WDebug::WMessage{WServer::WDebug::WPrefix, ""WSocket(const std::string &socket) failed"" "", invalid socket format (ip:port)""}); } if (__xsocket_init()) { throw std::runtime_error( WServer::WDebug::WMessage{WServer::WDebug::WPrefix, ""WSocket(const std::string &socket) failed"" "", __xsocket_init() caused an error""}); } struct sockaddr_in addr; const socklen_t [MASK] = sizeof(addr); memset(&addr, 0, [MASK] ); addr.sin_family = AF_INET; addr.sin_port = htons(port_); inet_pton(AF_INET, getIp4S().data(), &addr.sin_addr); sockfd_ = xsocket(addr.sin_family, SOCK_STREAM, IPPROTO_TCP); if (sockfd_ == -1) { __xsocket_cleanup(); throw std::runtime_error( WServer::WDebug::WMessage{WServer::WDebug::WPrefix, ""WSocket(const std::string &socket) failed"" "", xsocket() caused an error""}); } bind(sockfd_, (struct sockaddr *)&addr, [MASK] ); listen(sockfd_, INT_MAX); spdlog::info(""{}Initialized socket '{}'"", WServer::WDebug::WPrefix, socket_); } } // namespace WTypes } // namespace WServer ",addr_len 285,"#include #include #include #include struct Student { std::string name; int rollNumber; int marksBiology; int marksPhysics; int marksChemistry; int totalMarks; int stream; // 0 for Bio, 1 for Math int classNumber; bool operator<(const Student& other) const { return totalMarks > other.totalMarks; // Sort in descending order of total marks } }; class School { private: std::vector students; public: void addStudent(const Student& student) { students.push_back(student); } void calculateRanks() { // Calculate total marks and sort students for (auto& student : students) { student.totalMarks = student.marksBiology + student.marksPhysics + student.marksChemistry; } std::sort(students.begin(), students.end()); // Assign school rank for (size_t i = 0; i < students.size(); ++i) { students[i].rollNumber = i + 1; } // Assign class rank for (int stream = 0; stream <= 1; ++stream) { for (int classNumber = 1; classNumber <= (stream == 0 ? 3 : 5); ++classNumber) { std::vector classStudents; for (const auto& student : students) { if (student.stream == stream && student.classNumber == classNumber) { classStudents.push_back(student); } } std::sort(classStudents.begin(), classStudents.end()); for (size_t i = 0; i < classStudents.size(); ++i) { for (auto& student : students) { if (student.stream == stream && student.classNumber == classNumber && student.name == classStudents[i].name) { student.classNumber = i + 1; } } } } } } void printRanks() { std::ofstream [MASK] (""rankings.txt""); if (! [MASK] .is_open()) { std::cerr << ""Error opening output file."" << std::endl; return; } for (const auto& student : students) { [MASK] << (student.stream == 0 ? ""Bio"" : ""Math"") << ""\t"" << student.classNumber << ""\t"" << student.rollNumber << ""\t"" << student.name << ""\t"" << student.totalMarks << std::endl; } [MASK] .close(); } }; int main() { School school; // Dummy data - replace this with actual data input for (int stream = 0; stream <= 1; ++stream) { for (int classNumber = 1; classNumber <= (stream == 0 ? 3 : 5); ++classNumber) { for (int i = 1; i <= 40; ++i) { Student student; student.name = ""Student"" + std::to_string(i); student.marksBiology = rand() % 101; student.marksPhysics = rand() % 101; student.marksChemistry = rand() % 101; student.stream = stream; student.classNumber = classNumber; school.addStudent(student); } } } school.calculateRanks(); school.printRanks(); return 0; } ",outputFile 286,"#include #include #include #include #include #include ""debug_output.h"" #include ""nxdk_ext.h"" #include ""pbkit_ext.h"" #include ""renderer.h"" #include ""tracelib/tracer_state_machine.h"" #include ""xbdm.h"" #define ENABLE_TRACER_THREAD static constexpr int kFramebufferWidth = 640; static constexpr int kFramebufferHeight = 480; static constexpr int kTextureWidth = 256; static constexpr int kTextureHeight = 256; //! Send nop commands, used as a mechanism to mark interesting things it the //! pgraph log. static void Mark(uint32_t num_nops = 8); static void Initialize(Renderer& renderer); static void CreateGeometry(Renderer& renderer); static std::atomic_bool has_rendered_frame(false); static std::atomic tracer_state; static std::atomic_bool request_processed(false); static void OnTracerStateChanged(TracerState new_state) { std::string state_name; #define HANDLE_STATE(val) \ case val: \ state_name = #val; \ break switch (new_state) { HANDLE_STATE(STATE_FATAL_NOT_IN_NEW_FRAME_STATE); HANDLE_STATE(STATE_FATAL_NOT_IN_STABLE_STATE); HANDLE_STATE(STATE_FATAL_DISCARDING_FAILED); HANDLE_STATE(STATE_FATAL_PROCESS_PUSH_BUFFER_COMMAND_FAILED); HANDLE_STATE(STATE_SHUTDOWN_REQUESTED); HANDLE_STATE(STATE_SHUTDOWN); HANDLE_STATE(STATE_UNINITIALIZED); HANDLE_STATE(STATE_INITIALIZING); HANDLE_STATE(STATE_INITIALIZED); HANDLE_STATE(STATE_IDLE); HANDLE_STATE(STATE_IDLE_STABLE_PUSH_BUFFER); HANDLE_STATE(STATE_IDLE_NEW_FRAME); HANDLE_STATE(STATE_IDLE_LAST); HANDLE_STATE(STATE_WAITING_FOR_STABLE_PUSH_BUFFER); HANDLE_STATE(STATE_DISCARDING_UNTIL_FLIP); HANDLE_STATE(STATE_TRACING_UNTIL_FLIP); default: state_name = ""<>""; break; } PrintMsg(""Tracer state changed: %s[%d]\n"", state_name.c_str(), new_state); tracer_state = new_state; } static void OnRequestProcessed() { request_processed = true; } static uint8_t discard_buffer[4096]; static void OnPGRAPHBytesAvailable(uint32_t bytes_written) { PrintMsg(""New PGRAPH bytes available: %u"", bytes_written); TracerLockPGRAPHBuffer(); while (TracerReadPGRAPHBuffer(discard_buffer, sizeof(discard_buffer))) { } TracerUnlockPGRAPHBuffer(); } static void OnAuxBytesAvailable(uint32_t bytes_written) { PrintMsg(""New aux bytes available: %u"", bytes_written); TracerLockAuxBuffer(); while (TracerReadAuxBuffer(discard_buffer, sizeof(discard_buffer))) { } TracerUnlockAuxBuffer(); } static void WaitForState(TracerState state) { while (tracer_state != state) { Sleep(1); } } // static void WaitForState(const std::set& states) { // while (states.find(tracer_state) == states.cend()) { // Sleep(1); // } // } static void WaitForRequestComplete() { while (TracerIsProcessingRequest()) { Sleep(1); } } #ifdef ENABLE_TRACER_THREAD static DWORD __attribute__((stdcall)) TracerThreadMain( LPVOID lpThreadParameter) { while (!has_rendered_frame) { Sleep(1); } auto init_result = TracerInitialize(OnTracerStateChanged, OnRequestProcessed, OnPGRAPHBytesAvailable, OnAuxBytesAvailable); if (!XBOX_SUCCESS(init_result)) { PrintMsg(""Failed to initialize tracer: 0x%X"", init_result); return init_result; } // Create a tracer instance and wait for it to stabilize. TracerConfig config; TracerGetDefaultConfig(&config); auto create_result = TracerCreate(&config); if (!XBOX_SUCCESS(create_result)) { PrintMsg(""Failed to create tracer: 0x%X"", create_result); return init_result; } WaitForState(STATE_IDLE); // TracerCreate PrintMsg(""About to start wait for stable pbuffer state...""); request_processed = false; if (!TracerBeginWaitForStablePushBufferState()) { PrintMsg(""TracerBeginWaitForStablePushBufferState failed!""); TracerShutdown(); return 1; } else { WaitForRequestComplete(); } PrintMsg(""Achieved stable pbuffer state...""); PrintMsg(""About to discard until next frame flip...""); request_processed = false; if (!TracerBeginDiscardUntilFlip(TRUE)) { PrintMsg(""TracerBeginDiscardUntilFlip failed!""); TracerShutdown(); return 1; } else { WaitForRequestComplete(); } PrintMsg(""New frame started!""); request_processed = false; if (!TracerTraceCurrentFrame()) { PrintMsg(""TracerTraceCurrentFrame failed!""); TracerShutdown(); return 1; } else { WaitForRequestComplete(); } TracerShutdown(); return 0; } #endif // ENABLE_TRACER_THREAD static float wrap_color(float val) { while (val < 0.f) { val += 1.f; } while (val > 1.f) { val -= 1.f; } return val; } int main() { XVideoSetMode(kFramebufferWidth, kFramebufferHeight, 32, REFRESH_DEFAULT); int status = pb_init(); if (status) { debugPrint(""pb_init Error %d\n"", status); pb_show_debug_screen(); Sleep(2000); return 1; } pb_show_front_screen(); auto renderer = Renderer(kFramebufferWidth, kFramebufferHeight, kTextureWidth, kTextureHeight); CreateGeometry(renderer); #ifdef ENABLE_TRACER_THREAD DWORD tracer_thread_id; auto tracer_thread = CreateThread(nullptr, 0, TracerThreadMain, nullptr, 0, &tracer_thread_id); if (!tracer_thread) { debugPrint(""Failed to create tracer thread.\n""); pb_show_debug_screen(); Sleep(2000); return 1; } #endif // ENABLE_TRACER_THREAD // Render some test content. // Note that this is intentionally inefficient, the intent is to test the // pgraph tracer, so there is more frequent interaction with the pushbuffer // than necessary. float r = 1.0f; float g = 0.25f; float b = 0.33f; while (true) { Initialize(renderer); MATRIX matrix; matrix_unit(matrix); renderer.SetFixedFunctionModelViewMatrix(matrix); renderer.SetFixedFunctionProjectionMatrix(matrix); renderer.PrepareDraw(0xFF333333); auto p = pb_begin(); // Set up a directional light. p = pb_push1(p, NV097_SET_LIGHT_ENABLE_MASK, NV097_SET_LIGHT_ENABLE_MASK_LIGHT0_INFINITE); // Ambient color comes from the material's diffuse color. p = pb_push3(p, NV097_SET_LIGHT_AMBIENT_COLOR, 0, 0, 0); p = pb_push3f(p, NV097_SET_LIGHT_DIFFUSE_COLOR, r, g, b); p = pb_push3f(p, NV097_SET_LIGHT_SPECULAR_COLOR, 0.f, 0.f, 0.f); p = pb_push1(p, NV097_SET_LIGHT_LOCAL_RANGE, 0x7149f2ca); // 1e+30 p = pb_push3(p, NV097_SET_LIGHT_INFINITE_HALF_VECTOR, 0, 0, 0); p = pb_push3f(p, NV097_SET_LIGHT_INFINITE_DIRECTION, 0.0f, 0.0f, 1.0f); uint32_t control0 = MASK(NV097_SET_CONTROL0_Z_FORMAT, NV097_SET_CONTROL0_Z_FORMAT_FIXED); p = pb_push1(p, NV097_SET_CONTROL0, control0); p = pb_push1(p, NV097_SET_VERTEX_DATA4UB + 0x0C, 0xFFFFFFFF); p = pb_push1(p, NV097_SET_VERTEX_DATA4UB + 0x10, 0); p = pb_push1(p, NV097_SET_VERTEX_DATA4UB + 0x1C, 0xFFFFFFFF); p = pb_push1(p, NV097_SET_VERTEX_DATA4UB + 0x20, 0); p = pb_push1(p, NV10_TCL_PRIMITIVE_3D_POINT_PARAMETERS_ENABLE, 0x0); p = pb_push1(p, NV097_SET_SPECULAR_PARAMS, 0xBF7730E0); p = pb_push1(p, NV097_SET_SPECULAR_PARAMS + 4, 0xC0497B30); p = pb_push1(p, NV097_SET_SPECULAR_PARAMS + 8, 0x404BAEF8); p = pb_push1(p, NV097_SET_SPECULAR_PARAMS + 12, 0xBF6E9EE4); p = pb_push1(p, NV097_SET_SPECULAR_PARAMS + 16, 0xC0463F88); p = pb_push1(p, NV097_SET_SPECULAR_PARAMS + 20, 0x404A97CF); p = pb_push1(p, NV097_SET_LIGHT_CONTROL, 0x10001); p = pb_push1(p, NV097_SET_LIGHTING_ENABLE, 0x1); p = pb_push1(p, NV097_SET_SPECULAR_ENABLE, 0x1); p = pb_push1(p, NV097_SET_COLOR_MATERIAL, NV097_SET_COLOR_MATERIAL_DIFFUSE_FROM_MATERIAL); p = pb_push3(p, NV097_SET_SCENE_AMBIENT_COLOR, 0x0, 0x3C6DDACA, 0x0); p = pb_push1(p, NV097_SET_MATERIAL_EMISSION, 0x0); p = pb_push1(p, NV097_SET_MATERIAL_EMISSION + 4, 0x0); p = pb_push1(p, NV097_SET_MATERIAL_EMISSION + 8, 0x0); float material_alpha = 0.75f; uint32_t alpha_int = *(uint32_t*)&material_alpha; p = pb_push1(p, NV097_SET_MATERIAL_ALPHA, alpha_int); pb_end(p); renderer.DrawArrays(renderer.POSITION | renderer.NORMAL | renderer.DIFFUSE | renderer.SPECULAR); Mark(); renderer.FinishDraw(); has_rendered_frame = true; r = wrap_color(r + 0.001f); g = wrap_color(g - 0.005f); b = wrap_color(b + 0.005f); } return 0; } static void Mark(uint32_t num_nops) { auto p = pb_begin(); for (auto i = 0; i < num_nops; ++i) { p = pb_push1(p, NV097_NO_OPERATION, 0); } pb_end(p); } static void Initialize(Renderer& renderer) { const uint32_t kFramebufferPitch = renderer.GetFramebufferWidth() * 4; renderer.SetSurfaceFormat(Renderer::SCF_A8R8G8B8, Renderer::SZF_Z16, renderer.GetFramebufferWidth(), renderer.GetFramebufferHeight()); auto p = pb_begin(); p = pb_push1(p, NV097_SET_SURFACE_PITCH, SET_MASK(NV097_SET_SURFACE_PITCH_COLOR, kFramebufferPitch) | SET_MASK(NV097_SET_SURFACE_PITCH_ZETA, kFramebufferPitch)); p = pb_push1(p, NV097_SET_SURFACE_CLIP_HORIZONTAL, renderer.GetFramebufferWidth() << 16); p = pb_push1(p, NV097_SET_SURFACE_CLIP_VERTICAL, renderer.GetFramebufferHeight() << 16); p = pb_push1(p, NV097_SET_LIGHTING_ENABLE, false); p = pb_push1(p, NV097_SET_SPECULAR_ENABLE, false); p = pb_push1(p, NV097_SET_LIGHT_CONTROL, 0x20001); p = pb_push1(p, NV097_SET_LIGHT_ENABLE_MASK, NV097_SET_LIGHT_ENABLE_MASK_LIGHT0_OFF); p = pb_push1(p, NV097_SET_COLOR_MATERIAL, NV097_SET_COLOR_MATERIAL_ALL_FROM_MATERIAL); p = pb_push1f(p, NV097_SET_MATERIAL_ALPHA, 1.0f); p = pb_push1(p, NV20_TCL_PRIMITIVE_3D_LIGHT_MODEL_TWO_SIDE_ENABLE, 0); p = pb_push1(p, NV097_SET_FRONT_POLYGON_MODE, NV097_SET_FRONT_POLYGON_MODE_V_FILL); p = pb_push1(p, NV097_SET_BACK_POLYGON_MODE, NV097_SET_FRONT_POLYGON_MODE_V_FILL); p = pb_push1(p, NV097_SET_VERTEX_DATA4UB + 0x10, 0); // Specular p = pb_push1(p, NV097_SET_VERTEX_DATA4UB + 0x1C, 0xFFFFFFFF); // Back diffuse p = pb_push1(p, NV097_SET_VERTEX_DATA4UB + 0x20, 0); // Back specular p = pb_push1(p, NV097_SET_POINT_PARAMS_ENABLE, false); p = pb_push1(p, NV097_SET_POINT_SMOOTH_ENABLE, false); p = pb_push1(p, NV097_SET_POINT_SIZE, 8); p = pb_push1(p, NV097_SET_DOT_RGBMAPPING, 0); p = pb_push1(p, NV097_SET_SHADE_MODEL, NV097_SET_SHADE_MODEL_SMOOTH); pb_end(p); Renderer::SetWindowClipExclusive(false); // Note, setting the first clip region will cause the hardware to also set all // subsequent regions. Renderer::SetWindowClip(renderer.GetFramebufferWidth(), renderer.GetFramebufferHeight()); renderer.SetBlend(); renderer.ClearInputColorCombiners(); renderer.ClearInputAlphaCombiners(); renderer.ClearOutputColorCombiners(); renderer.ClearOutputAlphaCombiners(); renderer.SetCombinerControl(1); renderer.SetInputColorCombiner( 0, Renderer::SRC_DIFFUSE, false, Renderer::MAP_UNSIGNED_IDENTITY, Renderer::SRC_ZERO, false, Renderer::MAP_UNSIGNED_INVERT); renderer.SetInputAlphaCombiner( 0, Renderer::SRC_DIFFUSE, true, Renderer::MAP_UNSIGNED_IDENTITY, Renderer::SRC_ZERO, false, Renderer::MAP_UNSIGNED_INVERT); renderer.SetOutputColorCombiner(0, Renderer::DST_DISCARD, Renderer::DST_DISCARD, Renderer::DST_R0); renderer.SetOutputAlphaCombiner(0, Renderer::DST_DISCARD, Renderer::DST_DISCARD, Renderer::DST_R0); renderer.SetFinalCombiner0( Renderer::SRC_ZERO, false, false, Renderer::SRC_ZERO, false, false, Renderer::SRC_ZERO, false, false, Renderer::SRC_R0); renderer.SetFinalCombiner1(Renderer::SRC_ZERO, false, false, Renderer::SRC_ZERO, false, false, Renderer::SRC_R0, true, false, false, false, true); renderer.SetShaderStageProgram(Renderer::STAGE_NONE, Renderer::STAGE_NONE, Renderer::STAGE_NONE, Renderer::STAGE_NONE); while (pb_busy()) { /* Wait for completion... */ } p = pb_begin(); MATRIX identity_matrix; matrix_unit(identity_matrix); for (auto i = 0; i < 4; ++i) { auto& stage = renderer.GetTextureStage(i); stage.SetUWrap(TextureStage::WRAP_CLAMP_TO_EDGE, false); stage.SetVWrap(TextureStage::WRAP_CLAMP_TO_EDGE, false); stage.SetPWrap(TextureStage::WRAP_CLAMP_TO_EDGE, false); stage.SetQWrap(false); stage.SetEnabled(false); stage.SetCubemapEnable(false); stage.SetFilter(); stage.SetAlphaKillEnable(false); stage.SetLODClamp(0, 4095); stage.SetTextureMatrixEnable(false); stage.SetTextureMatrix(identity_matrix); stage.SetTexgenS(TextureStage::TG_DISABLE); stage.SetTexgenT(TextureStage::TG_DISABLE); stage.SetTexgenR(TextureStage::TG_DISABLE); stage.SetTexgenQ(TextureStage::TG_DISABLE); } // TODO: Set up with TextureStage instances in renderer. { uint32_t address = NV097_SET_TEXTURE_ADDRESS; uint32_t control = NV097_SET_TEXTURE_CONTROL0; uint32_t filter = NV097_SET_TEXTURE_FILTER; p = pb_push1(p, address, 0x10101); p = pb_push1(p, control, 0x3ffc0); p = pb_push1(p, filter, 0x1012000); address += 0x40; control += 0x40; filter += 0x40; p = pb_push1(p, address, 0x10101); p = pb_push1(p, control, 0x3ffc0); p = pb_push1(p, filter, 0x1012000); address += 0x40; control += 0x40; filter += 0x40; p = pb_push1(p, address, 0x10101); p = pb_push1(p, control, 0x3ffc0); p = pb_push1(p, filter, 0x1012000); address += 0x40; control += 0x40; filter += 0x40; p = pb_push1(p, address, 0x10101); p = pb_push1(p, control, 0x3ffc0); p = pb_push1(p, filter, 0x1012000); } p = pb_push1(p, NV097_SET_FOG_ENABLE, false); p = pb_push4(p, NV097_SET_TEXTURE_MATRIX_ENABLE, 0, 0, 0, 0); p = pb_push1(p, NV097_SET_FRONT_FACE, NV097_SET_FRONT_FACE_V_CW); p = pb_push1(p, NV097_SET_CULL_FACE, NV097_SET_CULL_FACE_V_BACK); p = pb_push1(p, NV097_SET_CULL_FACE_ENABLE, true); p = pb_push1(p, NV097_SET_COLOR_MASK, NV097_SET_COLOR_MASK_BLUE_WRITE_ENABLE | NV097_SET_COLOR_MASK_GREEN_WRITE_ENABLE | NV097_SET_COLOR_MASK_RED_WRITE_ENABLE | NV097_SET_COLOR_MASK_ALPHA_WRITE_ENABLE); p = pb_push1(p, NV097_SET_DEPTH_TEST_ENABLE, false); p = pb_push1(p, NV097_SET_DEPTH_MASK, true); p = pb_push1(p, NV097_SET_DEPTH_FUNC, NV097_SET_DEPTH_FUNC_V_LESS); p = pb_push1(p, NV097_SET_STENCIL_TEST_ENABLE, false); p = pb_push1(p, NV097_SET_STENCIL_MASK, true); p = pb_push1(p, NV097_SET_NORMALIZATION_ENABLE, false); pb_end(p); renderer.SetDefaultViewportAndFixedFunctionMatrices(); renderer.SetDepthBufferFloatMode(false); renderer.SetVertexShaderProgram(nullptr); const TextureFormatInfo& texture_format = GetTextureFormatInfo(NV097_SET_TEXTURE_FORMAT_COLOR_SZ_X8R8G8B8); renderer.SetTextureFormat(texture_format, 0); renderer.SetDefaultTextureParams(0); renderer.SetTextureFormat(texture_format, 1); renderer.SetDefaultTextureParams(1); renderer.SetTextureFormat(texture_format, 2); renderer.SetDefaultTextureParams(2); renderer.SetTextureFormat(texture_format, 3); renderer.SetDefaultTextureParams(3); renderer.SetTextureStageEnabled(0, false); renderer.SetTextureStageEnabled(1, false); renderer.SetTextureStageEnabled(2, false); renderer.SetTextureStageEnabled(3, false); renderer.SetShaderStageProgram(Renderer::STAGE_NONE); renderer.SetShaderStageInput(0, 0); p = pb_begin(); p = pb_push1(p, NV097_SET_SHADER_STAGE_PROGRAM, 0); pb_end(p); } static void CreateGeometry(Renderer& renderer) { auto fb_width = static_cast(renderer.GetFramebufferWidth()); auto [MASK] = static_cast(renderer.GetFramebufferHeight()); float left = -1.0f * floorf(fb_width / 4.0f); float right = floorf(fb_width / 4.0f); float top = -1.0f * floorf( [MASK] / 3.0f); float bottom = floorf( [MASK] / 3.0f); float mid_width = left + (right - left) * 0.5f; uint32_t num_quads = 2; std::shared_ptr buffer = renderer.AllocateVertexBuffer(6 * num_quads); Color ul{0.4f, 0.1f, 0.1f, 0.25f}; Color ll{0.0f, 1.0f, 0.0f, 1.0f}; Color lr{0.0f, 0.0f, 1.0f, 1.0f}; Color ur{0.5f, 0.5f, 0.5f, 1.0f}; Color ul_s{0.0f, 1.0f, 0.0f, 0.5f}; Color ll_s{1.0f, 0.0f, 0.0f, 0.1f}; Color lr_s{1.0f, 1.0f, 0.0f, 0.5f}; Color ur_s{0.0f, 1.0f, 1.0f, 0.75f}; float z = 10.0f; buffer->DefineBiTri(0, left + 10, top + 4, mid_width + 10, bottom - 10, z, z, z, z, ul, ll, lr, ur, ul_s, ll_s, lr_s, ur_s); // Point normals for half the quad away from the camera. Vertex* v = buffer->Lock(); v[0].normal[2] = -1.0f; v[1].normal[2] = -1.0f; v[2].normal[2] = -1.0f; buffer->Unlock(); ul.SetRGBA(1.0f, 1.0f, 0.0f, 1.0f); ul_s.SetRGBA(1.0f, 0.0f, 0.0f, 0.25f); ll.SetGreyA(0.5, 1.0f); ll_s.SetRGBA(0.3f, 0.3f, 1.0f, 1.0f); ur.SetRGBA(0.0f, 0.3f, 0.8f, 0.15f); ur_s.SetRGBA(0.9f, 0.9f, 0.4f, 0.33); lr.SetRGBA(1.0f, 0.0f, 0.0f, 0.75f); lr_s.SetRGBA(0.95f, 0.5f, 0.8f, 0.05); z = 9.75f; buffer->DefineBiTri(1, mid_width - 10, top + 4, right - 10, bottom - 10, z, z, z, z, ul, ll, lr, ur, ul_s, ll_s, lr_s, ur_s); } ",fb_height 287,"#include""EPaperDrive.h"" EPaperDrive::EPaperDrive( /* args */ uint8_t BUSY_Pin, uint8_t RES_Pin, uint8_t DC_Pin, uint8_t CS_Pin, uint8_t SCK_Pin, uint8_t SDI_Pin) { _BUSY_Pin = BUSY_Pin; _RES_Pin = RES_Pin; _DC_Pin = DC_Pin; _CS_Pin = CS_Pin; _SCK_Pin = SCK_Pin; _SDI_Pin = SDI_Pin; pinMode(BUSY_Pin, INPUT); pinMode(RES_Pin, OUTPUT); pinMode(DC_Pin, OUTPUT); pinMode(CS_Pin, OUTPUT); pinMode(SCK_Pin, OUTPUT); pinMode(SDI_Pin, OUTPUT); } EPaperDrive::~EPaperDrive() { } void EPaperDrive::driver_delay_us(unsigned int [MASK] ) //1us { for(; [MASK] >1; [MASK] --); } void driver_delay_xms(unsigned long xms) //1ms { unsigned long i = 0 , j=0; for(j=0;j(15+1)*8=128 EPD_WriteCMD(0x45); //set Ram-Y address start/end position EPD_WriteData(0xF9); //0xF9-->(249+1)=250 EPD_WriteData(0x00); EPD_WriteData(0x00); EPD_WriteData(0x00); EPD_WriteCMD(0x3C); //BorderWavefrom EPD_WriteData(0x05); EPD_WriteCMD(0x18); //Read built-in temperature sensor EPD_WriteData(0x80); EPD_WriteCMD(0x21); // Display update control EPD_WriteData(0x00); EPD_WriteData(0x80); EPD_WriteCMD(0x4E); // set RAM x address count to 0; EPD_WriteData(0x00); EPD_WriteCMD(0x4F); // set RAM y address count to 0X199; EPD_WriteData(0xF9); EPD_WriteData(0x00); EPD_READBUSY(); } void EPaperDrive::EPD_WhiteScreen_ALL(const unsigned char *BW_datas,const unsigned char *R_datas) { unsigned int i; EPD_WriteCMD(0x24); //write RAM for black(0)/white (1) for(i=0;i * **/ #pragma once #include #include #include #include #include class BinaryWriter { private: std::ofstream& writer; public: BinaryWriter(std::ofstream& givenWriter) : writer(givenWriter) { assert(writer.good()); } bool good() const { return writer.good(); } std::ofstream * GetStream() { return &writer; } template bool put(const T& value); template<> bool put< uint8_t >(const uint8_t& value) { writer.write(reinterpret_cast (&value), sizeof(uint8_t)); return good(); } template<> bool put< uint32_t >(const uint32_t& value) { writer.write(reinterpret_cast (&value), sizeof(uint32_t)); return good(); } template<> bool put< uint64_t >(const uint64_t& value) { writer.write(reinterpret_cast (&value), sizeof(uint64_t)); return good(); } template<> bool put< std::string >(const std::string& value) { std::vector [MASK] (value.begin(), value.end()); size_t length = [MASK] .size(); put(length); writer.write(reinterpret_cast( [MASK] .data()), length); return good(); } }; ",utf8_bytes 289,"#include ""utils.h"" boolean initConfig(ConfigStore &configStore) { EEPROM.begin(sizeof(ConfigStore)); return readConfig(configStore); } // 将配置写入flash void writeConfig(ConfigStore &configStore) { EEPROM.put(EEPROM_CONFIG_START, configStore); EEPROM.commit(); } // 从flash读取配置 boolean readConfig(ConfigStore &configStore) { EEPROM.get(EEPROM_CONFIG_START, configStore); if (configStore.magic != configDefault.magic) { DEBUG_PRINT(""Using default config.""); configStore = configDefault; return false; } else return true; } void connectWiFi(ConfigStore &configStore) { int [MASK] = 0; boolean connected = true; if (WiFi.status() != WL_CONNECTED) { WiFi.mode(WIFI_STA); WiFi.begin(configStore.wifiSSID, configStore.wifiPass); pinMode(LED_PIN, OUTPUT); DEBUG_PRINT(""Connecting to WiFi.""); while(WiFi.status() != WL_CONNECTED) { digitalWrite(LED_PIN, HIGH); delay(250); digitalWrite(LED_PIN, LOW); delay(250); [MASK] ++; if( [MASK] > 20) { connected = false; break; } } if(!connected) { DEBUG_PRINT(""Connect to WiFi Failed.""); smartConfig(configStore); } } } void monitorWiFi(ConfigStore &configStore) { if(configStore.flagConfig == 1) { WiFi.disconnect(); configStore.flagWiFiFail = 1; smartConfig(configStore); } if (WiFi.status() != WL_CONNECTED) { if(configStore.flagWiFiFail == 0) configStore.flagWiFiFail = 1; connectWiFi(configStore); } else if (configStore.flagWiFiFail == 1) { configStore.flagWiFiFail = 0; DEBUG_PRINT(""WiFi connected:""); DEBUG_PRINT(WiFi.SSID().c_str()); DEBUG_PRINT(""Local IP:""); DEBUG_PRINT(WiFi.localIP()); } else configStore.flagWiFiFail == 0; } // 通过Smart Config获取密码 void smartConfig(ConfigStore &configStore) { boolean flag = true; uint8_t brightness;//, m_Counter = 0; uint16_t m_Counter = 0; uint8_t i = 0; WiFi.mode(WIFI_STA); DEBUG_PRINT(""Wait for SmartConfig""); WiFi.beginSmartConfig(); pinMode(LED_PIN, OUTPUT); while (flag) { if(m_Counter == 0) Serial.print("".""); // analogWriteRange(new_range) // analogWriteFreq(new_frequency) //analogWriteResolution(10); //analogWrite(LED_PIN, map(brightness, 0, 1023, 0, 1023)); m_Counter = (m_Counter + 1) % 256; brightness = (m_Counter < 128) ? m_Counter : 256 - m_Counter; // m_Counter = (m_Counter + 1) % 1024; // brightness = (m_Counter < 512) ? m_Counter : 1024 - m_Counter; //analogWrite(LED_PIN, BOARD_PWM_MAX * ((float)brightness / (BOARD_PWM_MAX/2))); analogWrite(LED_PIN, BOARD_PWM_MAX - brightness * 2); delay(10); if (WiFi.smartConfigDone()) { Serial.print(""""); DEBUG_PRINTF(""\r\nSmartConfig Success.""); // DEBUG_PRINTF(""SSID: %s\r\n"", WiFi.SSID().c_str()); // DEBUG_PRINTF(""PSW: %s\r\n"", WiFi.psk().c_str()); // 保存配置 DEBUG_PRINT(""Save config...""); // sprintf(configStore.wifiSSID, ""%s"", WiFi.SSID().c_str()); // sprintf(configStore.wifiPass, ""%s"", WiFi.psk().c_str()); memset(configStore.wifiSSID, 0, sizeof(configStore.wifiSSID)); memset(configStore.wifiPass, 0, sizeof(configStore.wifiPass)); strcpy(configStore.wifiSSID, WiFi.SSID().c_str()); strcpy(configStore.wifiPass, WiFi.psk().c_str()); DEBUG_PRINTF(""SSID: %s\n"", configStore.wifiSSID); DEBUG_PRINTF(""PSW: %s\n"", configStore.wifiPass); writeConfig(configStore); DEBUG_PRINT(""Save config done!""); WiFi.stopSmartConfig(); flag = false; } } for(i=0; i<10; i++) // 状态提示 { delay(100); digitalWrite(LED_PIN, i % 2); } } // 固件升级 void firmwareUpdate(ConfigStore &configStore) { DEBUG_PRINTF(""Updating firmware -> ""); t_httpUpdate_return ret = ESPhttpUpdate.update(configStore.cloudHost, configStore.cloudPort, configStore.cloudUpdateUrl, configStore.version); //t_httpUpdate_return ret = ESPhttpUpdate.update(""http://192.168.1.101:5000/firmware"", configStore.version); //t_httpUpdate_return ret = ESPhttpUpdate.update(""https://server/file.bin""); switch(ret) { case HTTP_UPDATE_FAILED: DEBUG_PRINT(""HTTP_UPDATE_FAILED""); break; case HTTP_UPDATE_NO_UPDATES: DEBUG_PRINT(""HTTP_UPDATE_NO_UPDATES""); break; case HTTP_UPDATE_OK: DEBUG_PRINT(""HTTP_UPDATE_OK""); break; } } // 检查固件升级信息 int checkFirmwareUpdate(ConfigStore &configStore) { int result = 0; HTTPClient http; http.begin(configStore.cloudHost, configStore.cloudPort, configStore.cloudFwCheckUrl); int httpCode = http.GET(); // 使用GET形式来取得数据 DEBUG_PRINTF(""Code: %d\n"", httpCode); if(httpCode == 200) { // 访问成功,取得返回参数 String payload = http.getString(); DEBUG_PRINTF(""Context: %s\n"", payload.c_str()); if(payload == ""1"") result = 1; else result = 0; } else { // 访问不成功,打印原因 String payload = http.getString(); DEBUG_PRINTF(""Context: %s\n"", payload.c_str()); result = 0; } return result; } ",try_count 290,"/* Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cpp Ported to Arduino ESP32 by updates by chegewara */ #include #include #include #include #include #include ""OpenRadiation_V2.h"" #include ""Utils.h"" #include ""OpenRadiation_Oled.h"" #define BLUETOOTH_NAME ""OpengKIT72"" // See the following for generating UUIDs: // https://www.uuidgenerator.net/ #define SERVICE_UUID ""4fafc201-1fb5-459e-8fcc-c5c9c331914b"" #define RX_CHARACTERISTIC_UUID ""beb5483e-36e1-4688-b7f5-ea07361b26a8"" #define TX_CHARACTERISTIC_UUID ""beb5483f-36e1-4688-b7f5-ea07361b26a8"" #define MANUFACTURER_DATA {0x00,0x00,0x30,0x30,0x30,0x30,0x31} /** In packets types **/ #define IN_PACKET_STEALTH 0x01 #define IN_PACKET_SILENT 0x02 #define IN_PACKET_SET_TENSION 0x11 #define IN_PACKET_SEND_INFO 0x12 #define VERSION_BUFFER_SIZE 5 #define SENSOR_BUFFER_SIZE 20 #define TUBE_BUFFER_SIZE 8 #define VOLTAGE_BUFFER_SIZE 5 #define DATA_BUFFER_SIZE 19 uint8_t p_version_buffer[VERSION_BUFFER_SIZE] = {0x02, 0x03, '1', '.', '0'}; uint8_t p_sensor_buffer[SENSOR_BUFFER_SIZE] = {0x03, 0x12, 'G', 'e', 'i', 'g', 'e', 'r', '-', 'M', 'u', 'l', 'l', 'e', 'r', ' ','t' ,'u' ,'b' ,'e'}; uint8_t p_tube_buffer[TUBE_BUFFER_SIZE] = {0x10,0x06, 'J', '3', '0', '5', 0x62, 0x64}; uint8_t p_actual_tension[VOLTAGE_BUFFER_SIZE] = {0x12, 0x43, 0xBE, 0x00, 0x00}; //uint8_t p_tube_buffer_p_actual_tension[TUBE_BUFFER_SIZE+VOLTAGE_BUFFER_SIZE] = {0x10,0x06, 'J', '3', '0', '5', 0x62, 0x64, 0x12, 0x00, 0x00, 0xBE, 0x43}; uint8_t p_tube_buffer_p_actual_tension[TUBE_BUFFER_SIZE+VOLTAGE_BUFFER_SIZE] = {0x10,0x06, 'S', 'B', 'M', '-', '2', '0', 0x12, 0x00, 0x00, 0xBE, 0x43}; uint8_t p_data_buffer[DATA_BUFFER_SIZE] = {0x05, 0x00, 0x06, 0x00, 0x00, 0xD8, 0x41, 0xD1, 0x1D, 0x12, 0x00, 0x00, 0xBE, 0x43, 0x13, 0x00, 0x00, 0x00, 0x00}; BLEServer *pServer = NULL; BLECharacteristic * pTxCharacteristic; BLECharacteristic * pRxCharacteristic; bool deviceConnected = false; bool oldDeviceConnected = false; uint8_t txValue = 0; unsigned long pulse_millis = 0; unsigned int nb_pulse = 0; unsigned long previousMillis = 0; const long interval = 1000; const long led_interval = 50; unsigned int nb_pulse_to_send = 0; int current_state = 0; int old_state = 0; unsigned int nb_measure = 0; boolean b_new_pulse = false; boolean b_data_to_send = false; boolean b_debug_data_to_send = false; class MyServerCallbacks: public BLEServerCallbacks { void onConnect(BLEServer* pServer) { deviceConnected = true; }; void onDisconnect(BLEServer* pServer) { deviceConnected = false; } }; boolean stealthMode = false; boolean silentMode = false; class MyTxCallbacks: public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pTxCharacteristic) { std::string value = pTxCharacteristic->getValue(); if (value.length() > 0) { byte datatype = value[0]; switch (datatype) { case IN_PACKET_STEALTH: stealthMode = value[1]; if (stealthMode) { disableFollowerLED(); } else { enableFollowerLED(); } break; case IN_PACKET_SILENT: silentMode = value[1]; if (silentMode) { disableFollowerBuzzer(); } else { enableFollowerBuzzer(); } break; case IN_PACKET_SEND_INFO: pRxCharacteristic->setValue(p_version_buffer, VERSION_BUFFER_SIZE); pRxCharacteristic->notify(); delay(100); pRxCharacteristic->setValue(p_sensor_buffer,SENSOR_BUFFER_SIZE); pRxCharacteristic->notify(); delay(100); pRxCharacteristic->setValue(p_tube_buffer_p_actual_tension,TUBE_BUFFER_SIZE+VOLTAGE_BUFFER_SIZE); pRxCharacteristic->notify(); delay(100); break; default: break; } } } }; void setup() { Serial.begin(115200); Serial.println(""Starting BLE work!""); delay(100); initialization(); // Create the BLE Device BLEDevice::init(BLUETOOTH_NAME); pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); BLEService *pService = pServer->createService(SERVICE_UUID); pRxCharacteristic = pService->createCharacteristic( RX_CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY ); pTxCharacteristic = pService->createCharacteristic( TX_CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_WRITE ); pTxCharacteristic->setCallbacks(new MyTxCallbacks()); // Create a BLE Descriptor pRxCharacteristic->addDescriptor(new BLE2902()); pService->start(); BLEAdvertisementData oAdvertisementData = BLEAdvertisementData(); oAdvertisementData.setManufacturerData(MANUFACTURER_DATA); //BLEAdvertising *pAdvertising = pServer->getAdvertising(); // this still is working for backward compatibility BLEAdvertising *pRxAdvertising = BLEDevice::getAdvertising(); pRxAdvertising->addServiceUUID(SERVICE_UUID); pRxAdvertising->setScanResponse(false); pRxAdvertising->setMinPreferred(0x00); // functions that help with iPhone connections issue pRxAdvertising->setMinPreferred(0x12); pRxAdvertising->setScanResponseData(oAdvertisementData); BLEDevice::startAdvertising(); Serial.println(""Characteristic defined! Now you can read it in your phone!""); pRxCharacteristic->setValue(p_version_buffer, VERSION_BUFFER_SIZE); pRxCharacteristic->notify(); delay(10); pRxCharacteristic->setValue(p_sensor_buffer,SENSOR_BUFFER_SIZE); pRxCharacteristic->notify(); delay(10); pRxCharacteristic->setValue(p_tube_buffer,TUBE_BUFFER_SIZE); pRxCharacteristic->notify(); delay(10); //OledInitialization(); } void loop() { unsigned long [MASK] = millis(); current_state = digitalRead(COUNT_INPUT); if ((old_state == 0) && (current_state == 1)) { nb_pulse++; b_new_pulse = true; } old_state = current_state; //Check timer if ( [MASK] - previousMillis >= interval) { previousMillis = [MASK] ; nb_pulse_to_send = nb_pulse; nb_pulse = 0; temp_of_board = get_temperature(0, true); switch_sensor(0); battery_voltage = analogRead(BATTERY_CAN) / 512; ht_voltage = analogRead(HIGH_VOLTAGE_CAN) / 1024; b_data_to_send = true; b_debug_data_to_send = true; } if ((DEBUG_MODE) && (b_debug_data_to_send)) { String data_to_send = ""Nb pulse = ""; data_to_send += String(nb_pulse_to_send, DEC); Serial.println(data_to_send); data_to_send = String(""Temp = ""); data_to_send += String(temp_of_board, DEC); Serial.println(data_to_send); data_to_send = String(""Batterie Voltage = ""); data_to_send += String(battery_voltage, DEC); Serial.println(data_to_send); data_to_send = String(""Hight Voltage = ""); data_to_send += String(ht_voltage, DEC); Serial.println(data_to_send); b_debug_data_to_send = false; } if (deviceConnected) { if (b_data_to_send) { b_data_to_send = false; p_data_buffer[1] = nb_pulse_to_send; ConvertFloatToBuffer(temp_of_board, p_data_buffer, 3); pRxCharacteristic->setValue(p_data_buffer, DATA_BUFFER_SIZE); pRxCharacteristic->notify(); delay(10); } } // disconnecting if (!deviceConnected && oldDeviceConnected) { delay(500); // give the bluetooth stack the chance to get things ready pServer->startAdvertising(); // restart advertising Serial.println(""start advertising""); oldDeviceConnected = deviceConnected; communication_disable(); } // connecting if (deviceConnected && !oldDeviceConnected) { // do stuff here on connecting Serial.println(""Connected""); oldDeviceConnected = deviceConnected; communication_enable(); } //Flash led if (b_new_pulse) { buzzer_on(); led_on(); pulse_millis = [MASK] ; b_new_pulse = false; } if (( [MASK] - pulse_millis) >= led_interval) { //digitalWrite(LED_PIN, HIGH); buzzer_off(); led_off(); } } ",currentMillis 291,"/* * Copyright (C) 2025 Huawei Device Co., Ltd. * 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 ""credential_base.h"" using namespace Hdc; char HdcCredentialBase::GetPathSep() { #ifdef _WIN32 const char sep = '\\'; #else const char sep = '/'; #endif return sep; } int HdcCredentialBase::RemoveDir(const std::string& dir) { DIR *pdir = opendir(dir.c_str()); if (pdir == nullptr) { WRITE_LOG(LOG_FATAL, ""opendir failed dir:%s"", dir.c_str()); return -1; } struct dirent *ent; struct stat st; while ((ent = readdir(pdir)) != nullptr) { if (ent->d_name[0] == '.') { continue; } std::string subpath = dir + HdcCredentialBase::GetPathSep() + ent->d_name; if (lstat(subpath.c_str(), &st) == -1) { WRITE_LOG(LOG_WARN, ""lstat failed subpath:%s"", subpath.c_str()); continue; } if (S_ISDIR(st.st_mode)) { if (RemoveDir(subpath) == -1) { closedir(pdir); return -1; } rmdir(subpath.c_str()); } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) { if (unlink(subpath.c_str()) == -1) { WRITE_LOG(LOG_FATAL, ""Failed to unlink file or symlink, error is :%s"", strerror(errno)); } } else { WRITE_LOG(LOG_DEBUG, ""lstat st_mode:%07o subpath:%s"", st.st_mode, subpath.c_str()); } } if (rmdir(dir.c_str()) == -1) { closedir(pdir); return -1; } closedir(pdir); return 0; } int HdcCredentialBase::RemovePath(const std::string& path) { struct stat st; if (lstat(path.c_str(), &st) == -1) { WRITE_LOG(LOG_WARN, ""lstat failed path:%s"", path.c_str()); return -1; } if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) { if (unlink(path.c_str()) == -1) { WRITE_LOG(LOG_FATAL, ""Failed to unlink file or symlink,, error is :%s"", strerror(errno)); } } else if (S_ISDIR(st.st_mode)) { if (path == ""."" || path == "".."") { return 0; } int rc = HdcCredentialBase::RemoveDir(path); WRITE_LOG(LOG_INFO, ""RemoveDir rc:%d path:%s"", rc, path.c_str()); return rc; } return 0; } const std::string HdcCredentialBase::StringFormat(const char* const formater, ...) { va_list vaArgs; va_start(vaArgs, formater); std::string ret = StringFormat(formater, vaArgs); va_end(vaArgs); return ret; } const std::string HdcCredentialBase::StringFormat(const char* const formater, va_list& vaArgs) { std::vector args(MAX_SIZE_IOBUF_STABLE); const int [MASK] = vsnprintf_s( args.data(), MAX_SIZE_IOBUF_STABLE, (args.size() >= 1) ? (args.size() - 1) : 0, formater, vaArgs); if ( [MASK] < 0) { return std::string(""""); } else { return std::string(args.data(), [MASK] ); } }",retSize 292,"// ReSharper disable CppZeroConstantCanBeReplacedWithNullptr // ReSharper disable CppCStyleCast // ReSharper disable CppInconsistentNaming // ReSharper disable CppClangTidyBugproneNarrowingConversions #include #include #include #include //Hardware-specific library #include ""AppDefinitions.h"" #include ""Serialprint.h"" #include ""Button.h"" #include ""Memory.h"" uint8_t Button::InitBMP(String* path) { SetBMPPath(path); File f; const bool success = f.open(GetBMPPath().c_str()); if (!success) return DEF_ERR_CANT_OPEN_FILE; f.readBytes((char*)&_file_header, sizeof(BMPFileHeader)); if (_file_header.file_type != 0x4D42) return DEF_ERR_UNRECOGNIZED_FILE_FORMAT; f.readBytes((char*)&_bmp_info_header, sizeof(BMPInfoHeader)); // The BMPColorHeader is used only for transparent images if (_bmp_info_header.bit_count == 32) { // Check if the file has bit mask color information if (_bmp_info_header.size >= (sizeof(BMPInfoHeader) + sizeof(BMPColorHeader))) { f.read((char*)&_bmp_color_header, sizeof(BMPColorHeader)); // Check if the pixel data is stored as BGRA and if the color space type is sRGB constexpr BMPColorHeader expected_color_header; if (expected_color_header.red_mask != _bmp_color_header.red_mask || expected_color_header.blue_mask != _bmp_color_header.blue_mask || expected_color_header.green_mask != _bmp_color_header.green_mask || expected_color_header.alpha_mask != _bmp_color_header.alpha_mask) return DEF_ERR_UNEXPECTED_COLOR_MASK_FORMAT; if (expected_color_header.color_space_type != _bmp_color_header.color_space_type) return DEF_ERR_UNEXPECTED_COLOR_SPACE_TYPE; } else { return DEF_ERR_NO_BIT_MASK_INFO; } } // Jump to the pixel data location f.seek(_file_header.offset_data); // Adjust the header fields for output. // Some editors will put extra info in the image file, we only save the headers and the data. if (_bmp_info_header.bit_count == 32) { _bmp_info_header.size = sizeof(BMPInfoHeader) + sizeof(BMPColorHeader); _file_header.offset_data = sizeof(BMPFileHeader) + sizeof(BMPInfoHeader) + sizeof(BMPColorHeader); } else { _bmp_info_header.size = sizeof(BMPInfoHeader); _file_header.offset_data = sizeof(BMPFileHeader) + sizeof(BMPInfoHeader); } _file_header.file_size = _file_header.offset_data; if (_bmp_info_header.planes == 1) // # planes -- must be '1' { if ((_bmp_info_header.bit_count == 24 || _bmp_info_header.bit_count == 16) && (_bmp_info_header.compression == 0)) // only 24/16 bit per pixel depth is supported; 0 = uncompressed { if (_bmp_info_header.height < 0) { _bmpIsFlipped = true; _bmp_info_header.height = -_bmp_info_header.height; } else { _bmpIsFlipped = false; } _isInitialized = true; } } f.close(); return DEF_ERR_NONE; } // Read row by row and immediately send to the screen uint8_t Button::DrawBMP(LCDWIKI_KBV* my_lcd) const { if (!IsInitialized()) return DEF_ERR_ACCESS_TO_NOT_INITIALIZED_BMP; //const uint32_t time = millis(); File f; const bool success = f.open(GetBMPPath().c_str()); if (!success) { return DEF_ERR_CANT_OPEN_FILE; } f.seek(GetBMPOffset()); const uint8_t bytesPerPixel = GetBMPDepth() / 8; const int16_t paddedWidth = (GetBMPWidth() * bytesPerPixel + 3) & ~3; auto data = (uint8_t*) mallocWrapper(paddedWidth); if (data == NULL) return DEF_ERR_NOT_ENOUGH_MEMORY; // TODO was only tested with width % 4 == 0 //Serialprint(""Width = %d, Padded width = %d\n"", GetBMPWidth() * bytesPerPixel, paddedWidth); auto colors = (uint16_t*) mallocWrapper(GetBMPWidth() * sizeof(uint16_t)); if (colors == NULL) { free(data); return DEF_ERR_NOT_ENOUGH_MEMORY; } for (size_t rowNum = 0; rowNum < GetBMPHeight(); ++rowNum) { size_t m = 0; f.readBytes(data, paddedWidth); switch (bytesPerPixel) { case 3: { for (size_t i = 0; i < GetBMPWidth(); ++i) { colors[i] = my_lcd->Color_To_565(data[m + 2], data[m + 1], data[m + 0]); m += bytesPerPixel; } break; } case 2: { for (size_t i = 0; i < GetBMPWidth(); ++i) { /* if (data[m] > 0) { Serialprint(""data[%d] = %d binary = "", m, data[m]); PrintBinary(data[m]); Serialprint(""data[%d] = %d binary = "", m+1, data[m+1]); PrintBinary(data[m+1]); uint16_t combined = (data[m+1] << 8) | data[m]; Serialprint(""Combined = %d binary = "", combined); PrintBinary(combined); colors[i] = 0; uint8_t* pointer = (uint8_t*) &colors[i]; Serialprint(""Address of [0] = %p Address of [1] = %p"", &(pointer[0]), &(pointer[1])); pointer[0] = data[m]; pointer[1] = data[m+1]; Serial.println(); PrintBinary(colors[i]); delay(100000000); } */ const auto pointer = (uint8_t*)&colors[i]; pointer[0] = data[m + 1]; pointer[1] = data[m]; m += bytesPerPixel; } break; } } if (_bmpIsFlipped) my_lcd->Set_Addr_Window(GetBMPX(), GetBMPY() + rowNum, GetBMPX() + GetBMPWidth() - 1, GetBMPY() + rowNum); else my_lcd->Set_Addr_Window(GetBMPX(), GetBMPY() + GetBMPHeight() - rowNum, GetBMPX() + GetBMPWidth() - 1, GetBMPY() + GetBMPHeight() - rowNum); my_lcd->Push_Any_Color(colors, GetBMPWidth(), true, DEF_LCDWIKI_KBV_FLAGS_NONE); } f.close(); free(data); data = NULL; free(colors); colors = NULL; //Serialprint(""Drawing took %d\n"", millis() - time); return DEF_ERR_NONE; } void Button::DrawSelection(LCDWIKI_KBV* my_lcd) const { if (IsSelected()) my_lcd->Set_Draw_color(GREEN); else my_lcd->Set_Draw_color(BLACK); if (IsInitialized()) { for (uint16_t i = 1; i < 8; ++i) { const uint16_t x0 = GetBMPX() - i; const uint16_t y0 = GetBMPY() - i; const uint16_t x1 = x0 + GetBMPWidth() + i * 2; const uint16_t y1 = y0 + GetBMPHeight() + i * 2; my_lcd->Draw_Rectangle(x0, y0, x1, y1); } } else { for (uint16_t i = 1; i < 8; ++i) { my_lcd->Draw_Round_Rectangle(GetX1() + i, GetY1() + i, GetX2() - i, GetY2() - i, DEF_BUTTON_RECTANGLE_ROUNDNESS); } } } void Button::DrawRectangle(LCDWIKI_KBV* my_lcd, const char* text) const { my_lcd->Set_Text_Size(2); my_lcd->Set_Text_colour(GREEN); my_lcd->Set_Text_Back_colour(BLACK); if (text != NULL) { if (GetType() == DEF_BUTTON_TYPE_NEXT) my_lcd->Print_String("">"", GetX1() + GetWidth() / 5, GetY1() + GetHeight() / 2); else if (GetType() == DEF_BUTTON_TYPE_PREV) my_lcd->Print_String(""<"", GetX1() + GetWidth() / 5, GetY1() + GetHeight() / 2); else if (GetType() == DEF_BUTTON_TYPE_SELECT_ALL) my_lcd->Print_String(""A"", GetX1() + GetWidth() / 5, GetY1() + GetHeight() / 2); else my_lcd->Print_String(text, GetX1() + GetWidth() / 5, GetY1() + GetHeight() / 2); } my_lcd->Set_Draw_color(WHITE); my_lcd->Draw_Round_Rectangle(GetX1(), GetY1(), GetX2(), GetY2(), DEF_BUTTON_RECTANGLE_ROUNDNESS); } void Button::SendKeys() const { const String [MASK] = GetKeys(); int index = [MASK] .indexOf('['); while (index >= 0) { String str = [MASK] .substring(index + 1, [MASK] .indexOf(']', index)); uint16_t key = 0; if (str.equalsIgnoreCase(""up"")) key = KEY_UP_ARROW; else if (str.equalsIgnoreCase(""down"")) key = KEY_DOWN_ARROW; else if (str.equalsIgnoreCase(""right"")) key = KEY_RIGHT_ARROW; else if (str.equalsIgnoreCase(""left"")) key = KEY_LEFT_ARROW; else if (str.equalsIgnoreCase(""ctrl"")) key = KEY_LEFT_CTRL; else if (str.length() == 1) { key = str[0]; } //Serialprint(""str = '%s', key = %x\n"", str.c_str(), key); if (key > 0) { Keyboard.press(key); delay(DEF_KEY_SEND_DELAY); Keyboard.release(key); delay(DEF_KEY_SEND_DELAY); } index = [MASK] .indexOf('[', index + 1); } } ",keys 293,"/* * * Copyright (c) 2025 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include #include ""camera-device-interface.h"" #include #include #include #include // Camera App defines all the cluster servers needed for a particular device class CameraApp { public: // This class is responsible for initialising all the camera clusters and managing the interactions between them explicit CameraApp(chip::EndpointId [MASK] , CameraDeviceInterface * cameraDevice) : mChimeServer( [MASK] , cameraDevice->GetChimeDelegate()) {} // Initialize all the camera device clusters. void InitCameraDeviceClusters(); private: // SDK cluster servers chip::app::Clusters::ChimeServer mChimeServer; }; void CameraAppInit(CameraDeviceInterface * cameraDevice); void CameraAppShutdown(); ",aClustersEndpoint 294,"#ifndef PATH_SMOOTHING_INCLUDED #define PATH_SMOOTHING_INCLUDED #include #include ""RRTStar_DOM_kd_tree.hpp"" using namespace Eigen; vector QuadraticBSplineSmoothing(const vector& node_path) { vector res; if (node_path.size() < 3) { cout << ""No sufficient control points on the input path!\n"" << ""(At least 3 control points are needed for quadratic B-Spline smoothing.)\n""; return res; } const float step_width = 0.05; // For MatrixxXf.block() mathod needs constexpr as argument. const int step_num = 1 / step_width + 1, pts_num = node_path.size(); Matrix3f coefficient_mat_1, coefficient_mat_2, coefficient_mat_3; MatrixXf parameter_var(3, step_num), control_pts(2, pts_num); Matrix smoothed_path; coefficient_mat_1 << 1, -2, 1, -1.5, 2, 0, 0.5, 0, 0; coefficient_mat_2 << 0.5, -1, 0.5, -1, 1, 0.5, 0.5, 0, 0; coefficient_mat_3 << 0.5, -1, 0.5, -1.5, 1, 0.5, 1, 0, 0; for (int i = 0; i < step_num; i++) { float cur_var = step_width * i; parameter_var(0, i) = cur_var * cur_var; parameter_var(1, i) = cur_var; parameter_var(2, i) = 1; } for (int i = 0; i < pts_num; i++) { control_pts(0, i) = node_path[i]->pos.x; control_pts(1, i) = node_path[i]->pos.y; } MatrixXf cur_pts = control_pts.block<2, 3>(0, 0); MatrixXf cur_spline = cur_pts * coefficient_mat_1 * parameter_var; smoothed_path = cur_spline; for (int i = 1; i < pts_num - 3; i++) { cur_pts = control_pts.block<2, 3>(0, i); cur_spline = cur_pts * coefficient_mat_2 * parameter_var; smoothed_path.conservativeResize(2, smoothed_path.cols() + cur_spline.cols()); smoothed_path.block<2, step_num>(0, smoothed_path.cols() - step_num) = cur_spline; } cur_pts = control_pts.block<2, 3>(0, pts_num - 3); cur_spline = cur_pts * coefficient_mat_3 * parameter_var; smoothed_path.conservativeResize(2, smoothed_path.cols() + cur_spline.cols()); smoothed_path.block<2, step_num>(0, smoothed_path.cols() - step_num) = cur_spline; /* cout << ""path smoothing:\n"" << node_path.size() << ' ' << smoothed_path.rows() << "" x "" << smoothed_path.cols() << '\n' << cur_spline.rows() << "" x "" << cur_spline.cols() << endl; */ for (int i = 0; i < smoothed_path.cols(); i++) res.push_back(Point2f(smoothed_path(0, i), smoothed_path(1, i))); return res; } int SearchByDistance(vector& search_path, Point2f desired_pos) { int res_idx = 0; if (search_path.empty()) { cout << ""An empty path is given."" << endl; return res_idx; } Point2f trivial_sol = search_path.back(); float ref_distance = norm(desired_pos - trivial_sol), cur_distance_dif; for (int i = search_path.size() - 1; i >= 0; i--) { cur_distance_dif = abs(norm(desired_pos - search_path[i]) - ref_distance); if (cur_distance_dif < 2) res_idx = i; } return res_idx; } vector> GeneratePathSet(const vector& initial_feedback_pts, const vector& target_feedback_pts, int pivot_idx, float feedback_pts_radius, const vector& obs, Mat source_img) { vector> res_path_set(initial_feedback_pts.size()); RRTStarPlanner planner(initial_feedback_pts[pivot_idx], target_feedback_pts[pivot_idx], obs); bool plan_success = planner.Plan(source_img, feedback_pts_radius, true); if (!plan_success) { cout << ""Path planning failed! An empty path set is reutrned.\n""; return {}; } vector pivot_path = planner.GetPath(); vector sparse_pivot_path; for (int i = 0; i < pivot_path.size(); i += 1) sparse_pivot_path.push_back(pivot_path[i]); if (sparse_pivot_path.back() != pivot_path.back()) sparse_pivot_path.push_back(pivot_path.back()); vector smooth_pivot_path = QuadraticBSplineSmoothing(sparse_pivot_path); res_path_set[pivot_idx] = smooth_pivot_path; for (int i = 0; i < initial_feedback_pts.size(); i++) { if (i != pivot_idx) { Point2f cur_dif = initial_feedback_pts[i] - initial_feedback_pts[pivot_idx]; res_path_set[i] = smooth_pivot_path; for (Point2f& pt : res_path_set[i]) pt += cur_dif; if (normSqr(res_path_set[i].back() - target_feedback_pts[i]) > normSqr(res_path_set[i].front() - target_feedback_pts[i])){ res_path_set[i].erase(res_path_set[i].begin() + 1, res_path_set[i].end()); } else { int truncation_idx = SearchByDistance(res_path_set[i], target_feedback_pts[i]); res_path_set[i].erase(res_path_set[i].begin() + truncation_idx, res_path_set[i].end()); } Point2f temp_end = res_path_set[i].back(), segment = target_feedback_pts[i] - temp_end; float segment_length = cv::norm(segment), temp_path_length = cv::norm(temp_end - res_path_set[i].front()), interpolation_ratio; int segment_pt_num; if (temp_path_length > 1) // in case temp_path_length becomes 0 segment_pt_num = segment_length / temp_path_length * res_path_set[i].size(); else segment_pt_num = 100; for (int interpolation_idx = 1; interpolation_idx <= segment_pt_num; interpolation_idx++) { interpolation_ratio = (float)interpolation_idx / segment_pt_num; res_path_set[i].push_back(temp_end + segment * interpolation_ratio); } // res_path_set[i].push_back(target_feedback_pts[i]); } } return res_path_set; } vector ProcessCollisionPath(const vector& pivot_path, Point2f pivot_pt, Point2f cur_pt, Point2f cur_target_pt, const PolygonObstacle& original_obstacle, float safety_dis = 20) { vector inflated_obs_vertices = original_obstacle.vertices; Point2f vertices_centroid = Point2f(0, 0); for (Point2f& pt : inflated_obs_vertices) vertices_centroid += pt; vertices_centroid /= (float) inflated_obs_vertices.size(); for (Point2f& pt : inflated_obs_vertices) pt = vertices_centroid + 1.1 * (pt - vertices_centroid); PolygonObstacle obstacle(inflated_obs_vertices); vector res_path(pivot_path.size()); Point2f cur_dif = cur_pt - pivot_pt; float cur_dif_norm = cv::norm(cur_dif); vector collision_indices; for (int i = 0; i < pivot_path.size(); i++) { Point2f ref_pt = pivot_path[i] + cur_dif; if (!ObstacleFree(obstacle, pivot_path[i], ref_pt)) collision_indices.push_back(i); } // std::sort(collision_indices.begin(), collision_indices.end()); int collision_start_idx = collision_indices.front(), collision_end_idx = collision_indices.back(), reconnection_start_idx = collision_start_idx, reconnection_end_idx = collision_end_idx; float dis_ref = 3 * safety_dis; for (int i = collision_start_idx - 1; i >= 0; i--) { float dis_to_obs = MinDistanceToObstacle(obstacle, pivot_path[i] + cur_dif); if (dis_to_obs >= dis_ref) { reconnection_start_idx = i; break; } } if (reconnection_start_idx == collision_start_idx) reconnection_start_idx = 0; Point2f intersection_start_pt = GetClosestIntersectionPt(obstacle, pivot_path[collision_start_idx], pivot_path[collision_start_idx] + cur_dif, pivot_path[collision_start_idx]), shift_pt_1 = intersection_start_pt - safety_dis / cur_dif_norm * cur_dif - (pivot_path[reconnection_start_idx] + cur_dif); for (int i = collision_end_idx + 1; i < pivot_path.size(); i++) { float dis_to_obs = MinDistanceToObstacle(obstacle, pivot_path[i] + cur_dif); if (dis_to_obs >= dis_ref) { reconnection_end_idx = i; break; } } if (reconnection_end_idx == collision_end_idx) reconnection_end_idx = pivot_path.size() - 1; Point2f intersection_end_pt = GetClosestIntersectionPt(obstacle, pivot_path[collision_end_idx], pivot_path[collision_end_idx] + cur_dif, pivot_path[collision_end_idx]), shift_pt_2 = pivot_path[reconnection_end_idx] + cur_dif - (intersection_end_pt - safety_dis / cur_dif_norm * cur_dif); for (int i = 0; i < reconnection_start_idx; i++) res_path[i] = pivot_path[i] + cur_dif; int step_num = collision_start_idx - reconnection_start_idx; for (int i = reconnection_start_idx; i < collision_start_idx; i++) { float shift_ratio = (float)(i - reconnection_start_idx) / (float)step_num; res_path[i] = pivot_path[reconnection_start_idx] + cur_dif + shift_ratio * shift_pt_1; } for (int i = collision_start_idx; i < collision_end_idx; i++) { Point2f intersection_pt = GetClosestIntersectionPt(obstacle, pivot_path[i], pivot_path[i] + cur_dif, pivot_path[i]); res_path[i] = intersection_pt - safety_dis / cur_dif_norm * cur_dif; } step_num = reconnection_end_idx - collision_end_idx; for (int i = collision_end_idx; i < reconnection_end_idx; i++) { float shift_ratio = (float) (i - collision_end_idx) / step_num; res_path[i] = intersection_end_pt - safety_dis / cur_dif_norm * cur_dif + shift_ratio * shift_pt_2; } for (int i = reconnection_end_idx; i < pivot_path.size(); i++) res_path[i] = pivot_path[i] + cur_dif; // postprocessing int truncation_idx = SearchByDistance(res_path, cur_target_pt); res_path.erase(res_path.begin() + truncation_idx, res_path.end()); Point2f temp_end = res_path.back(), segment = cur_target_pt - temp_end; float segment_length = cv::norm(segment), temp_path_length = cv::norm(temp_end - res_path.front()), interpolation_ratio; int segment_pt_num; if (temp_path_length > 1) // in case temp_path_length becomes 0 segment_pt_num = segment_length / temp_path_length * res_path.size(); else segment_pt_num = 100; for (int interpolation_idx = 1; interpolation_idx <= segment_pt_num; interpolation_idx++) { interpolation_ratio = (float)interpolation_idx / segment_pt_num; res_path.push_back(temp_end + segment * interpolation_ratio); } // std::cout << ""OK5\n""; return res_path; } vector GetLocalPathWidth2D( const vector& path, vector& obstacles, Size2f config_size = Size2f(640, 480)) { vector local_path_width(path.size(), 0); vector path_width_type(path.size(), 0); // 0: two-side free, 1: one-side free, one-side obstacle // 2: two-side obstacle float slope, x_max = config_size.width, y_max = config_size.height, cur_x, cur_y, x_intercept, y_intercept, x_at_y_max, [MASK] ; for (int i = 1; i < path.size() - 1; i++) { cur_x = path[i].x; cur_y = path[i].y; slope = -(path[i + 1].x - path[i - 1].x) / (path[i + 1].y - path[i - 1].y); vector boundary_insection_pts; y_intercept = cur_y + slope * (0 - cur_x); if (0 <= y_intercept && y_intercept <= y_max) boundary_insection_pts.push_back(Point2f(0, y_intercept)); x_intercept = cur_x - cur_y / slope; if (0 <= x_intercept && x_intercept <= x_max) boundary_insection_pts.push_back(Point2f(x_intercept, 0)); x_at_y_max = cur_x + (y_max - cur_y) / slope; if (0 <= x_at_y_max && x_at_y_max <= x_max) boundary_insection_pts.push_back(Point2f(x_at_y_max, y_max)); [MASK] = cur_x + slope * (x_max - cur_x); if (0 <= [MASK] && [MASK] <= y_max) boundary_insection_pts.push_back(Point2f(x_max, [MASK] )); // std::cout << ""OK_1\n""; if (boundary_insection_pts.empty()) { std::cout << ""Error!\n""; std::cout << path[i] << '\n' << ""slope: "" << slope << '\n'; } Point2f end_pt1 = boundary_insection_pts[0], end_pt2 = boundary_insection_pts[1], direction1 = end_pt1 - path[i], direiction2 = end_pt2 - path[i]; vector obs_intersection_pts, direction1_pts, direction2_pts; for (PolygonObstacle& cur_obs : obstacles) { if (ObstacleFree(cur_obs, end_pt1, end_pt2)) continue; Point2f cur_obs_intersection_pt = GetClosestIntersectionPt(cur_obs, end_pt1, end_pt2, path[i]); obs_intersection_pts.push_back(cur_obs_intersection_pt); } if (obs_intersection_pts.empty()) local_path_width[i] = cv::norm(end_pt1 - end_pt2); else { for (Point2f cur_pt : obs_intersection_pts) { Point2f cur_vec = cur_pt - path[i]; if (cur_vec.x * direction1.x + cur_vec.y * direction1.y > 0) direction1_pts.push_back(cur_pt); else direction2_pts.push_back(cur_pt); } if (!direction1_pts.empty()) { path_width_type[i]++; for (Point2f& cur_direction1_pt : direction1_pts) { if (normSqr(cur_direction1_pt - path[i]) < normSqr(end_pt1 - path[i])) end_pt1 = cur_direction1_pt; } } if (!direction2_pts.empty()) { path_width_type[i]++; for (Point2f& cur_direction2_pt : direction2_pts) if (normSqr(cur_direction2_pt - path[i]) < normSqr(end_pt2 - path[i])) end_pt2 = cur_direction2_pt; } local_path_width[i] = cv::norm(end_pt1 - end_pt2); } } if (local_path_width.size() >= 2) { local_path_width.front() = local_path_width[1]; local_path_width.back() = local_path_width[local_path_width.size() - 2]; } return local_path_width; } vector> FilterRawPassagePairsByVisibility(const vector& obstacles, const vector>& raw_passage_pairs) { vector> res; vector> valid_passage_pair_set(obstacles.size()); for (const vector& cur_passage_pair : raw_passage_pairs) valid_passage_pair_set[cur_passage_pair[0]].insert(cur_passage_pair[1]); for (int i = 0; i < valid_passage_pair_set.size(); i++) { for (auto it = valid_passage_pair_set[i].begin(); it != valid_passage_pair_set[i].end();) { if (ObstacleFreeVecForPassage(obstacles, i, *it) == false) it = valid_passage_pair_set[i].erase(it); // Be careful when dynamically deleting a set element else it++; } } for (int i = 0; i < raw_passage_pairs.size(); i++) { if (valid_passage_pair_set[raw_passage_pairs[i][0]].find(raw_passage_pairs[i][1]) != valid_passage_pair_set[raw_passage_pairs[i][0]].end()) res.push_back(raw_passage_pairs[i]); } return res; } vector> FilterPassagePairsBySortedWidth(const vector& obstacles, const vector>& raw_passage_pairs) { vector> res; vector> passage_pairs_mutual_map(obstacles.size()); for (const vector& cur_passage_pair : raw_passage_pairs) { passage_pairs_mutual_map[cur_passage_pair[0]].push_back(cur_passage_pair[1]); passage_pairs_mutual_map[cur_passage_pair[1]].push_back(cur_passage_pair[0]); } vector obs_idx_2_candidate_vec(obstacles.size(), -1); for (int i = 0; i < obstacles.size(); i++) { if (passage_pairs_mutual_map[i].size() == 0) continue; vector> width_to_obs_idx; PolygonObstacle obs1 = obstacles[i]; for (int j = 0; j < passage_pairs_mutual_map[i].size(); j++) { int obs_idx_2 = passage_pairs_mutual_map[i][j]; PolygonObstacle obs2 = obstacles[obs_idx_2]; vector cur_passage_inner_ends = GetPassageInnerEnds(obs1, obs2); float cur_passage_width = cv::norm(cur_passage_inner_ends[0] - cur_passage_inner_ends[1]); width_to_obs_idx.push_back(make_pair(cur_passage_width, obs_idx_2)); } std::sort(width_to_obs_idx.begin(), width_to_obs_idx.end()); obs_idx_2_candidate_vec[i] = width_to_obs_idx[0].second; } for (int i = 0; i < obstacles.size(); i++) { if (passage_pairs_mutual_map[i].size() == 0) continue; int obs_idx_2 = obs_idx_2_candidate_vec[i]; if (obs_idx_2 > i && i == obs_idx_2_candidate_vec[obs_idx_2]) res.push_back({i, obs_idx_2}); } return res; } vector> GetPassagesPathPasses(const vector& obstacles, const vector& path) { // Raw, non-smoothed path is preferred for efficiency. vector> raw_passage_pairs; vector obs_centroids = GetObstaclesCentroids(obstacles); for (int i = 0; i < path.size() - 1; i++) for (int j = 0; j < obs_centroids.size() - 1; j++) for (int k = j + 1; k < obs_centroids.size(); k++) if (SegmentIntersection(path[i]->pos, path[i + 1]->pos, obs_centroids[j], obs_centroids[k]) == true) raw_passage_pairs.push_back({j, k}); // Filter invalid passages vector> physical_valid_passage_pairs = FilterRawPassagePairsByVisibility(obstacles, raw_passage_pairs); return FilterPassagePairsBySortedWidth(obstacles, physical_valid_passage_pairs); } vector> GetPassageIntersectionsOfPathSet(const vector& obstacles, const vector>& passage_pairs, const vector& smooth_pivot_path, vector>& path_node_intersection_idx_log, const vector& initial_feedback_pts, int pivot_idx) { int pts_num = initial_feedback_pts.size(); vector> res(pts_num, vector(passage_pairs.size())); path_node_intersection_idx_log = vector>(pts_num, vector(passage_pairs.size(), 0)); vector obs_centroids = GetObstaclesCentroids(obstacles); for (int i = 0; i < pts_num; i++) { int path_node_idx = 0; Point2f pt_dif = initial_feedback_pts[i] - initial_feedback_pts[pivot_idx]; for (int j = 0; j < passage_pairs.size(); j++) { // cout << ""Testing passage: "" << passage_pairs[j][0] << ""---"" << passage_pairs[j][1] << ""\n""; Point2f obs_centroid_1 = obs_centroids[passage_pairs[j][0]], obs_centroid_2 = obs_centroids[passage_pairs[j][1]], direction_obs_1_2 = (obs_centroid_2 - obs_centroid_1) / cv::norm(obs_centroid_2 - obs_centroid_1), extended_obs_centroid_1 = obs_centroid_1 - 300 * direction_obs_1_2, extended_obs_centroid_2 = obs_centroid_2 + 300 * direction_obs_1_2; // cout << ""Obstacle centroid 1: "" << obs_centroid_1 << "" Obstacle centroid 2: "" << obs_centroid_2 << ""\n""; // cout << ""Extended obstacle centroid 1: "" << extended_obs_centroid_1 << "" Extended obstacle centroid 2: "" << extended_obs_centroid_2 << ""\n""; for (int k = path_node_idx; k < smooth_pivot_path.size() - 1; k++) { if (SegmentIntersection(extended_obs_centroid_1, extended_obs_centroid_2, smooth_pivot_path[k] + pt_dif, smooth_pivot_path[k + 1] + pt_dif)) { res[i][j] = GetSegmentsIntersectionPt(extended_obs_centroid_1, extended_obs_centroid_2, smooth_pivot_path[k] + pt_dif, smooth_pivot_path[k + 1] + pt_dif); // cout << ""Intersection detected with point:\n"" << res[i][j] << '\n'; path_node_intersection_idx_log[i][j] = k; // In theory, the same path segment can pass two or more passages, so do not use path_node_idx = k + 1. // Also, next intersection can be placed before the current one, simply setting path_node = 0 is ok. Here, locality search is used. path_node_idx = (k - (int)smooth_pivot_path.size() / 5) < 0 ? 0 : k - (int)smooth_pivot_path.size() / 5; break; } } } } cout << ""Intersection pts of path set:\n""; for (auto pt_vec : res) { for (auto pt : pt_vec) cout << pt << "", ""; cout << ""\n""; } return res; } vector GetPivotPathRepositionPts(const vector& obstacles, const vector>& passage_pairs, const vector>& intersection_points, int pivot_idx) { vector chord_ends, passage_inner_ends, res(passage_pairs.size()); vector obs_centroids = GetObstaclesCentroids(obstacles); int pts_num = intersection_points.size(); for (int i = 0; i < passage_pairs.size(); i++) { vector cur_passage_intersection_pts(pts_num); for (int j = 0; j < pts_num; j++) cur_passage_intersection_pts[j] = intersection_points[j][i]; chord_ends = GetEndsOfColinearPts(cur_passage_intersection_pts); passage_inner_ends = GetPassageInnerEnds(obstacles[passage_pairs[i][0]], obstacles[passage_pairs[i][1]]); /* cout << ""Passage inner ends:\n"" << passage_inner_ends[0] << ""-"" << passage_inner_ends[1] << '\n'; cout << ""Chord ends:\n"" << chord_ends[0] << ""-"" << chord_ends[1] << '\n'; cout << ""Passage intersection point:\n"" << cur_passage_intersection_pts[pivot_idx] << '\n'; */ Point2f reposition_intersection_pt; if (normSqr(chord_ends[1] - chord_ends[0]) < normSqr(passage_inner_ends[1] - passage_inner_ends[0]) && OnSegment(passage_inner_ends[0], passage_inner_ends[1], chord_ends[0]) && OnSegment(passage_inner_ends[0], passage_inner_ends[1], chord_ends[1])) { // cout << ""case 1\n""; res[i] = cur_passage_intersection_pts[pivot_idx]; continue; } else if (normSqr(chord_ends[1] - chord_ends[0]) < normSqr(passage_inner_ends[1] - passage_inner_ends[0])) { if (OnSegment(passage_inner_ends[0], passage_inner_ends[1], chord_ends[0])) { if (normSqr(passage_inner_ends[0] - chord_ends[1]) <= normSqr(passage_inner_ends[1] - chord_ends[1])) reposition_intersection_pt = cur_passage_intersection_pts[pivot_idx] + 1.2 * (passage_inner_ends[0] - chord_ends[1]); else reposition_intersection_pt = cur_passage_intersection_pts[pivot_idx] + 1.2 * (passage_inner_ends[1] - chord_ends[1]); } else { if (normSqr(passage_inner_ends[0] - chord_ends[0]) <= normSqr(passage_inner_ends[1] - chord_ends[0])) reposition_intersection_pt = cur_passage_intersection_pts[pivot_idx] + 1.2 * (passage_inner_ends[0] - chord_ends[0]); else reposition_intersection_pt = cur_passage_intersection_pts[pivot_idx] + 1.2 * (passage_inner_ends[1] - chord_ends[0]); } // cout << ""Reposition intersection point:\n"" // << reposition_intersection_pt << '\n'; res[i] = reposition_intersection_pt; continue; } Point2f chord_center = (chord_ends[0] + chord_ends[1]) / 2, passage_inner_center = (passage_inner_ends[0] + passage_inner_ends[1]) / 2, chord_to_passage_center_dif = passage_inner_center - chord_center, pivot_path_intersection_pt = cur_passage_intersection_pts[pivot_idx]; reposition_intersection_pt = pivot_path_intersection_pt + chord_to_passage_center_dif; if (OnSegment(passage_inner_ends[0], passage_inner_ends[1], reposition_intersection_pt) == false) { if (normSqr(reposition_intersection_pt - passage_inner_ends[0]) <= normSqr(reposition_intersection_pt - passage_inner_ends[1])) reposition_intersection_pt = passage_inner_ends[0] + 0.2 * (passage_inner_ends[1] - passage_inner_ends[0]); else reposition_intersection_pt = passage_inner_ends[1] + 0.2 * (passage_inner_ends[0] - passage_inner_ends[1]); } // cout << ""Reposition intersection point:\n"" // << reposition_intersection_pt << '\n'; res[i] = reposition_intersection_pt; } return res; } vector> AdjustRepositionPtsForPathSet(const vector& obstacles, const vector>& passage_pairs, const vector>& path_set_intersection_pts, int pivot_idx) { vector> res = path_set_intersection_pts; int pts_num = res.size(); vector chord_ends, passage_inner_ends; for (int i = 0; i < passage_pairs.size(); i++) { vector cur_passage_intersection_pts(pts_num); for (int j = 0; j < pts_num; j++) cur_passage_intersection_pts[j] = res[j][i]; chord_ends = GetEndsOfColinearPts(cur_passage_intersection_pts); passage_inner_ends = GetPassageInnerEnds(obstacles[passage_pairs[i][0]], obstacles[passage_pairs[i][1]]); if (OnSegment(passage_inner_ends[0], passage_inner_ends[1], chord_ends[0]) && OnSegment(passage_inner_ends[0], passage_inner_ends[1], chord_ends[1])) { continue; } Point2f passage_direction_1 = passage_inner_ends[0] - res[pivot_idx][i], passage_direction_2 = passage_inner_ends[1] - res[pivot_idx][i]; float safety_interior_distance = 15, interior_distance_1 = cv::norm(passage_direction_1), interior_distance_2 = cv::norm(passage_direction_2), max_dif_length_1 = 1e-5, max_dif_length_2 = 1e-5; if (interior_distance_1 > safety_interior_distance) interior_distance_1 -= safety_interior_distance; if (interior_distance_2 > safety_interior_distance) interior_distance_2 -= safety_interior_distance; for (int j = 0; j < pts_num; j++) { if (j == pivot_idx) continue; Point2f intersection_pt_dif = res[j][i] - res[pivot_idx][i]; if (passage_direction_1.dot(intersection_pt_dif) > 0) { max_dif_length_1 = max(max_dif_length_1, (float)cv::norm(intersection_pt_dif)); } else { max_dif_length_2 = max(max_dif_length_2, (float)cv::norm(intersection_pt_dif)); } } float compression_ritio = min(interior_distance_1 / max_dif_length_1, interior_distance_2 / max_dif_length_2); for (int j = 0; j < pts_num; j++) { if (j == pivot_idx) continue; // cout << ""Original intersection pt: "" << res[j][i] << "" ""; res[j][i] = res[pivot_idx][i] + (res[j][i] - res[pivot_idx][i]) * compression_ritio; // cout << ""Repositioned intersction pt: "" << res[j][i] << '\n'; } } return res; } void DeformPath(vector& path, const vector& intersection_pts, const vector& reposition_intersection_pts, vector path_intersection_idx) { vector accumulated_path_length(path.size(), 0); for (int i = 1; i < accumulated_path_length.size(); i++) { accumulated_path_length[i] = accumulated_path_length[i - 1] + cv::norm(path[i] - path[i - 1]); } vector reposition_idx(path_intersection_idx.size() + 2, 0); reposition_idx.back() = path.size() - 1; for (int i = 0; i < path_intersection_idx.size(); i++) reposition_idx[i + 1] = path_intersection_idx[i]; float total_path_length = accumulated_path_length.back(); Point2f cur_shift, next_shift, pre_shift; for (int i = 0; i < reposition_idx.size() - 1; i++) { int cur_path_idx = reposition_idx[i], next_path_idx = reposition_idx[i + 1]; float cur_path_length_parameter = accumulated_path_length[cur_path_idx] / total_path_length, next_path_length_parameter = accumulated_path_length[next_path_idx] / total_path_length, path_segment_length_parameter = next_path_length_parameter - cur_path_length_parameter; if (cur_path_idx == 0) cur_shift = Point2f(0, 0); else cur_shift = reposition_intersection_pts[i - 1] - intersection_pts[i - 1]; if (next_path_idx == path.size() - 1) next_shift = Point2f(0, 0); else next_shift = reposition_intersection_pts[i] - intersection_pts[i]; for (int j = cur_path_idx; j < next_path_idx; j++) { float path_length_parameter = accumulated_path_length[j] / total_path_length, ratio = (path_length_parameter - cur_path_length_parameter) / path_segment_length_parameter; path[j] = path[j] + ratio * next_shift + (1 - ratio) * cur_shift; // cout << path_length_parameter << "", "" << ratio << "", "" << next_shift << "", "" << cur_shift << '\n'; } } } void DeformPathWithTargetPt(vector& path, const vector& intersection_pts, const vector& reposition_intersection_pts, vector path_intersection_idx) { vector accumulated_path_length(path.size(), 0); for (int i = 1; i < accumulated_path_length.size(); i++) { accumulated_path_length[i] = accumulated_path_length[i - 1] + cv::norm(path[i] - path[i - 1]); } vector reposition_idx(path_intersection_idx.size() + 2, 0); reposition_idx.back() = path.size() - 1; for (int i = 0; i < path_intersection_idx.size(); i++) reposition_idx[i + 1] = path_intersection_idx[i]; float total_path_length = accumulated_path_length.back(); Point2f cur_shift, next_shift, pre_shift; for (int i = 0; i < reposition_idx.size() - 1; i++) { int cur_path_idx = reposition_idx[i], next_path_idx = reposition_idx[i + 1]; float cur_path_length_parameter = accumulated_path_length[cur_path_idx] / total_path_length, next_path_length_parameter = accumulated_path_length[next_path_idx] / total_path_length, path_segment_length_parameter = next_path_length_parameter - cur_path_length_parameter; if (cur_path_idx == 0) cur_shift = Point2f(0, 0); else cur_shift = reposition_intersection_pts[i - 1] - intersection_pts[i - 1]; // if (next_path_idx == path.size() - 1) // next_shift = Point2f(0, 0); // else next_shift = reposition_intersection_pts[i] - intersection_pts[i]; for (int j = cur_path_idx; j < next_path_idx; j++) { float path_length_parameter = accumulated_path_length[j] / total_path_length, ratio = (path_length_parameter - cur_path_length_parameter) / path_segment_length_parameter; path[j] = path[j] + ratio * next_shift + (1 - ratio) * cur_shift; // cout << path_length_parameter << "", "" << ratio << "", "" << next_shift << "", "" << cur_shift << '\n'; } } path.back() = reposition_intersection_pts.back(); } vector> GeneratePathSetInGeneralCondition(const vector& initial_feedback_pts, const vector& target_feedback_pts, int pivot_idx, float feedback_pts_radius, const vector& obs, Mat source_img) { // vector> res_path_set(initial_feedback_pts.size()); RRTStarPlanner planner(initial_feedback_pts[pivot_idx], target_feedback_pts[pivot_idx], obs, 25); bool plan_success = planner.Plan(source_img, feedback_pts_radius, true); if (!plan_success) { cout << ""Path planning failed! An empty path set is reutrned.\n""; return {}; } vector pivot_path = planner.GetPath(); vector sparse_pivot_path; for (int i = 0; i < pivot_path.size(); i += 1) sparse_pivot_path.push_back(pivot_path[i]); if (sparse_pivot_path.back() != pivot_path.back()) sparse_pivot_path.push_back(pivot_path.back()); vector smooth_pivot_path = QuadraticBSplineSmoothing(sparse_pivot_path); vector> passage_passed = GetPassagesPathPasses(obs, pivot_path); vector> intersection_idx; vector> passage_intersection_pts = GetPassageIntersectionsOfPathSet(obs, passage_passed, smooth_pivot_path, intersection_idx, initial_feedback_pts, pivot_idx); vector reposition_points = GetPivotPathRepositionPts(obs, passage_passed, passage_intersection_pts, pivot_idx); DeformPath(smooth_pivot_path, passage_intersection_pts[pivot_idx], reposition_points, intersection_idx[pivot_idx]); passage_intersection_pts = GetPassageIntersectionsOfPathSet(obs, passage_passed, smooth_pivot_path, intersection_idx, initial_feedback_pts, pivot_idx); vector> adjusted_passage_intersection_pts = AdjustRepositionPtsForPathSet(obs, passage_passed, passage_intersection_pts, pivot_idx); vector> res_path_set(initial_feedback_pts.size(), smooth_pivot_path); for (int i = 0; i < initial_feedback_pts.size(); i++) { if (i == pivot_idx) continue; for (Point2f& path_node : res_path_set[i]) path_node += initial_feedback_pts[i] - initial_feedback_pts[pivot_idx]; passage_intersection_pts[i].push_back(res_path_set[i].back()); adjusted_passage_intersection_pts[i].push_back(target_feedback_pts[i]); DeformPathWithTargetPt(res_path_set[i], passage_intersection_pts[i], adjusted_passage_intersection_pts[i], intersection_idx[i]); //res_path_set[i].back() = target_feedback_pts[i]; } return res_path_set; } /* Upgraded */ vector RetrievePassedPassages(const vector& raw_pivot_path, const vector>& passage_pts) { vector res; for (int path_node_idx = 0; path_node_idx < raw_pivot_path.size() - 1; path_node_idx++) { for (int passage_idx = 0; passage_idx < passage_pts.size(); passage_idx++) { if (SegmentIntersection(raw_pivot_path[path_node_idx]->pos, raw_pivot_path[path_node_idx + 1]->pos, passage_pts[passage_idx][0], passage_pts[passage_idx][1])) res.push_back(passage_idx); } } return res; } #endif",y_at_x_max 295,"#include // Biblioteca para entrada y salida en C++. #include // Biblioteca para manejar vectores dinámicos en C++. // Función que calcula la suma de los elementos de un vector. // Parámetros: // - const std::vector& array: Usamos una referencia constante para evitar copias innecesarias y asegurar que el vector // no se modifique. Retorno: // - La suma de los elementos del vector como un entero. // Declaración de la plantilla genérica template // T es un parámetro genérico que representa cualquier tipo de dato. T sumArray(const std::vector& array) { T sum = 0; // Inicializamos la variable 'sum' en 0 para acumular la suma. // Usamos un bucle basado en rango (introducido en C++11) para recorrer el vector. // Ventaja: Es más legible y elimina la necesidad de manejar índices manualmente. for (T num : array) { sum += num; // Añadimos cada elemento del vector a 'sum'. } return sum; // Devolvemos el resultado final. } int main() { // Usamos std::vector para un ejemplo con enteros std::vector intArray = { 10, 20, 30, 40, 50 }; // Usamos std::vector para un ejemplo con decimales std::vector doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5 }; // Llamamos a la función genérica para calcular la suma de ambos vectores int [MASK] = sumArray(intArray); // Suma de enteros double doubleSum = sumArray(doubleArray); // Suma de decimales // Mostramos los resultados std::cout << ""Suma de enteros: "" << [MASK] << std::endl; std::cout << ""Suma de decimales: "" << doubleSum << std::endl; std::cout << ""Salida JJ"" << std::endl; return 0; }",intSum 296,"#include ""gameobjects.hpp"" std::vector sprites; u8 spriteIdIndex = 0; u8 getSpriteId(){ spriteIdIndex++; return spriteIdIndex; } EventBinding::EventBinding(std::string ctgry, voidFunction func){ stateType = ctgry; callable = func; }; InputManager::InputManager(){ keyMaps.push_back(std::make_tuple(KEY_UP, KEY_HELD, EVENT_UP)); keyMaps.push_back(std::make_tuple(KEY_DOWN, KEY_HELD, EVENT_DOWN)); keyMaps.push_back(std::make_tuple(KEY_RIGHT, KEY_HELD, EVENT_RIGHT)); keyMaps.push_back(std::make_tuple(KEY_LEFT, KEY_HELD, EVENT_LEFT)); keyMaps.push_back(std::make_tuple(KEY_START, KEY_PRESS, EVENT_PAUSE)); }; void InputManager::registerBinding(std::string eventName, std::string stateType, voidFunction func){ bindings[eventName].push_back(EventBinding(stateType, func)); }; void InputManager::pollInput(){ scanKeys(); u16 heldKeys = keysHeld(); u16 pressedKeys = keysDown(); for (u8 i = 0; i < keyMaps.size(); i++){ u8 keyCode = std::get<0>(keyMaps[i]); std::string keyAction = std::get<1>(keyMaps[i]); std::string eventKey = std::get<2>(keyMaps[i]); if (keyAction == KEY_HELD && (! (heldKeys & keyCode))){ continue; } if (keyAction == KEY_PRESS && (! (pressedKeys & keyCode))){ continue; } std::vector allBindings = bindings.find(eventKey)->second; std::vector activeBindings; for (u8 i=0; i < allBindings.size(); i++){ if (state != allBindings[i].stateType){ continue; } activeBindings.push_back(allBindings[i]); } for (u8 i=0; i < activeBindings.size(); i++){ activeBindings[i].callable(); } } } void InputManager::pause(){ state = GAME_PAUSED; }; void InputManager::unpause(){ state = GAME_RUNNING; }; AnimationFrame::AnimationFrame(u8 tile, u8 length){ tileOffset = tile; duration = length; } Animation::Animation(){}; Animation::Animation(u16 [MASK] ){ baseTile = [MASK] ; frame = 0; tileSetOffset=0; }; void Animation::tick(){ frame ++; } AnimationFrame Animation::currentFrame(){ u8 frameIndex = 0; u8 cumulativeFrames = 0; for(u8 i = 0; i <= frames.size(); i++){ if (i == frames.size()){ frame = 0; frameIndex = 0; break; } cumulativeFrames += frames[i].duration; if (frame < cumulativeFrames){ frameIndex = i; break; } } return frames[frameIndex]; }; u16 Animation::tile(){ return baseTile + tileSetOffset + (currentFrame().tileOffset * 4); } Sprite::Sprite(){ spriteId = getSpriteId(); }; Sprite::Sprite(OBJATTR* oamRef, u8 xPos, u8 yPos){ oam = oamRef; x = xPos; y = yPos; spriteId = getSpriteId(); }; void Sprite::draw(){ // TODO: Implement width and height for different sized sprites oam->attr0 = OBJ_16_COLOR | ATTR0_SQUARE | OBJ_Y(y); oam->attr1 = ATTR1_SIZE_16 | OBJ_X(x); oam->attr2 = animation.tile() | ATTR2_PALETTE(0); if (animation.flip){ oam->attr1 |= OBJ_HFLIP; } }; void Sprite::update(){ animation.tick(); }; void Sprite::faceNorth(){ animation.tileSetOffset = 24; animation.flip = false; if (!checkCollision(x, y- 1 )){ y = max(y - 1, 0); } }; void Sprite::faceSouth(){ animation.tileSetOffset = 0; animation.flip = false; if (!checkCollision(x, y + 1)){ y = min(y + 1, SCREEN_HEIGHT - 16); } }; void Sprite::faceEast(){ animation.tileSetOffset = 12; animation.flip = true; if (!checkCollision(x + 1, y)){ x = min(x + 1, SCREEN_WIDTH - 16); } }; void Sprite::faceWest(){ animation.tileSetOffset = 12; animation.flip = false; if (!checkCollision(x - 1, y)){ x = max(x - 1, 0); } }; bool Sprite::checkCollision(int x, int y){ bool collision = false; for (u8 i = 0; i < sprites.size(); i++) { Sprite other = sprites[i]; if (spriteId == other.spriteId){ continue; } // TODO: Change so that min and max for x and y are methods on the Sprite object int a_min_x = x; int a_max_x = x + 16; int a_min_y = y; int a_max_y = y + 16; int b_min_x = other.x; int b_max_x = other.x + 16; int b_min_y = other.y; int b_max_y = other.y + 16; bool doesNotIntersect = (a_max_x < b_min_x) || (b_max_x < a_min_x) || (a_max_y < b_min_y) || (b_max_y < a_min_y); collision = collision || !doesNotIntersect; } return collision; } void registerInputBindings(InputManager* eventManager, Sprite* player){ eventManager->registerBinding(EVENT_UP, GAME_RUNNING, std::bind(&Sprite::faceNorth, player)); eventManager->registerBinding(EVENT_DOWN, GAME_RUNNING, std::bind(&Sprite::faceSouth, player)); eventManager->registerBinding(EVENT_LEFT, GAME_RUNNING, std::bind(&Sprite::faceWest, player)); eventManager->registerBinding(EVENT_RIGHT, GAME_RUNNING, std::bind(&Sprite::faceEast, player)); eventManager->registerBinding(EVENT_PAUSE, GAME_PAUSED, std::bind(&InputManager::unpause, eventManager)); eventManager->registerBinding(EVENT_PAUSE, GAME_RUNNING, std::bind(&InputManager::pause, eventManager)); } ",baseTileValue 297,"#include ""kss2-bios.h"" #include ""string.h"" #include ""../common.h"" #define FILL_VALUE(parent, childName, dest, minVal, maxVal) \ { \ int a = atoi(dxml_child(parent, childName) \ ->txt); \ if (!(a >= minVal && a <= maxVal)) \ printf(""Invalid value for child %s of %s. It should've been between %d and %d\n"", \ childName, parent->name, minVal, maxVal); \ else \ dest = a; \ } #define FILL_VALUE_2(parent, childNameNoStr, dest, minVal, maxVal) \ { \ int a = atoi(dxml_child(parent, #childNameNoStr) \ ->txt); \ if (!(a >= minVal && a <= maxVal)) \ printf(""Invalid value for child %s of %s. It should've been between %d and %d\n"", \ #childNameNoStr, \ parent->name, minVal, maxVal); \ else \ dest.childNameNoStr = a; \ } namespace kss2_bios { auto load(const char *filename, SBios_Dinamic &bios_dyn, SRestart &restart, S_various_flegs &vf) -> int { dxml_t file = dxml_open(filename); dxml_t kssBios = dxml_child(file, ""KSS_BIOS""); auto &sbd = bios_dyn.proc; FILL_VALUE(kssBios, ""mod"", sbd.mod, 0, 3); FILL_VALUE(kssBios, ""cord_loc"", sbd.koord_lok, 0, 1); FILL_VALUE(kssBios, ""fors_table"", sbd.fors_tab, 0, 1); FILL_VALUE(kssBios, ""vh_fl"", sbd.v_trep, 0, 1); FILL_VALUE(kssBios, ""pd_fl"", sbd.p_trep, 0, 1); FILL_VALUE(kssBios, ""adaptive"", sbd.detektor, 0, 1); FILL_VALUE(kssBios, ""stages"", sbd.najava, 0, 1); dxml_t knfMode = dxml_child(file, ""KNF_MODE""); // Now knf_mode is being loaded. /* It is very important that elements of c and xml structures have same names */ auto &km = bios_dyn.knfl.km; FILL_VALUE_2(knfMode, pg1, km, 0, 3); FILL_VALUE_2(knfMode, pg2, km, 0, 3); FILL_VALUE_2(knfMode, pg3, km, 0, 3); FILL_VALUE_2(knfMode, pg4, km, 0, 3); FILL_VALUE_2(knfMode, vpg1, km, 0, 1); FILL_VALUE_2(knfMode, vpg2, km, 0, 1); FILL_VALUE_2(knfMode, vpg3, km, 0, 1); FILL_VALUE_2(knfMode, vpg4, km, 0, 1); FILL_VALUE_2(knfMode, glm, km, 0, 3); FILL_VALUE_2(knfMode, glt, km, 0, 1); FILL_VALUE_2(knfMode, fl, km, 0, 1); dxml_t variosFlags = dxml_child(file, ""VARIOUS_FLAGS""); // for (dxml_t c = variosFlags->child; c; c = c->sibling) // printf(""%s\n"", c->name); FILL_VALUE(variosFlags, ""CD_demoONOFF"", vf.CD_demoONOFF_flag, 0, 3); FILL_VALUE(variosFlags, ""setUPDW"", vf.setUPDW_flag, 0, 3); FILL_VALUE(variosFlags, ""RTCold"", vf.RTCold_flag, 0, 3); FILL_VALUE(variosFlags, ""Logger_ONOFF"", vf.Logger_ONOFF, 0, 3); FILL_VALUE(variosFlags, ""reserved1"", vf.reserved1, 0, 3); FILL_VALUE(variosFlags, ""reserved4"", vf.reserved4, 0, 3); FILL_VALUE(variosFlags, ""reserved2"", vf.reserved2, 0, 3); FILL_VALUE(variosFlags, ""reserved3"", vf.reserved3, 0, 3); dxml_t restartd = dxml_child(file, ""RESART""); //Next two lines should be checked FILL_VALUE(restartd, ""nrof_restarts"", restart.no, 0, 3); FILL_VALUE(restartd, ""wait_for_restart"", restart.time, 0, 63); dxml_free(file); return 0; } auto num_to_str(const int num, const size_t size) -> char * { auto buffer = new char[size + 1]; memset(buffer, 0, size + 1); snprintf(buffer, size + 1, ""%d"", num); return buffer; } #define DXML_SET_TXT(a, b) \ { \ auto d = a; \ auto e = b; \ dxml_set_txt(d, e); \ } auto save(const char *filename, const SBios_Dinamic &bios_dyn, const SRestart &restart, const S_various_flegs &vf) -> int { auto root = dxml_new(""KSS_BIOS_DATA""); create_children(root, ""KSS_BIOS"", ""KNF_MODE"", ""VARIOUS_FLAGS"", ""RESART""); auto kss_bios = dxml_child(root, ""KSS_BIOS""); auto knf_mode = dxml_child(root, ""KNF_MODE""); auto var_flags = dxml_child(root, ""VARIOUS_FLAGS""); auto [MASK] = dxml_child(root, ""RESTART""); // filling up kss_bios create_children(kss_bios, ""mod"", ""cord_loc"", ""fors_table"", ""vh_fl"", ""pd_fl"", ""adaptive"", ""stages""); const auto &sbd = bios_dyn.proc; DXML_SET_TXT(dxml_child(kss_bios, ""mod""), num_to_str(sbd.mod, 1)); DXML_SET_TXT(dxml_child(kss_bios, ""cord_loc""), num_to_str(sbd.koord_lok, 1)); DXML_SET_TXT(dxml_child(kss_bios, ""fors_table""), num_to_str(sbd.fors_tab, 1)); DXML_SET_TXT(dxml_child(kss_bios, ""vh_fl""), num_to_str(sbd.v_trep, 1)); DXML_SET_TXT(dxml_child(kss_bios, ""pd_fl""), num_to_str(sbd.p_trep, 1)); DXML_SET_TXT(dxml_child(kss_bios, ""adaptive""), num_to_str(sbd.detektor, 1)); DXML_SET_TXT(dxml_child(kss_bios, ""stages""), num_to_str(sbd.najava, 1)); // filling up knf_mode create_children(knf_mode, ""pg1"", ""pg2"", ""pg3"", ""pg4"", ""vpg1"", ""vpg2"", ""vpg3"", ""vpg4"", ""glm"", ""glt"", ""fl""); const auto &knf = bios_dyn.knfl.km; DXML_SET_TXT(dxml_child(knf_mode, ""pg1""), num_to_str(knf.pg1, 1)); DXML_SET_TXT(dxml_child(knf_mode, ""pg2""), num_to_str(knf.pg2, 1)); DXML_SET_TXT(dxml_child(knf_mode, ""pg3""), num_to_str(knf.pg3, 1)); DXML_SET_TXT(dxml_child(knf_mode, ""pg4""), num_to_str(knf.pg4, 1)); DXML_SET_TXT(dxml_child(knf_mode, ""vpg1""), num_to_str(knf.vpg1, 1)); DXML_SET_TXT(dxml_child(knf_mode, ""vpg2""), num_to_str(knf.vpg2, 1)); DXML_SET_TXT(dxml_child(knf_mode, ""vpg3""), num_to_str(knf.vpg3, 1)); DXML_SET_TXT(dxml_child(knf_mode, ""vpg4""), num_to_str(knf.vpg4, 1)); DXML_SET_TXT(dxml_child(knf_mode, ""glm""), num_to_str(knf.glm, 1)); DXML_SET_TXT(dxml_child(knf_mode, ""glt""), num_to_str(knf.glt, 1)); DXML_SET_TXT(dxml_child(knf_mode, ""fl""), num_to_str(knf.fl, 1)); // filling up var_flags create_children(var_flags, ""CD_demoONOFF"", ""setUPDW"", ""RTCold"", ""Logger_ONOFF"", ""reserved1"", ""reserved2"", ""reserved3"", ""reserved4""); DXML_SET_TXT(dxml_child(var_flags, ""CD_demoONOFF""), num_to_str(vf.CD_demoONOFF_flag, 1)); DXML_SET_TXT(dxml_child(var_flags, ""setUPDW""), num_to_str(vf.setUPDW_flag, 1)); DXML_SET_TXT(dxml_child(var_flags, ""RTCold""), num_to_str(vf.RTCold_flag, 1)); DXML_SET_TXT(dxml_child(var_flags, ""Logger_ONOFF""), num_to_str(vf.Logger_ONOFF, 1)); DXML_SET_TXT(dxml_child(var_flags, ""reserved1""), num_to_str(vf.reserved1, 1)); DXML_SET_TXT(dxml_child(var_flags, ""reserved2""), num_to_str(vf.reserved2, 1)); DXML_SET_TXT(dxml_child(var_flags, ""reserved3""), num_to_str(vf.reserved3, 1)); DXML_SET_TXT(dxml_child(var_flags, ""reserved4""), num_to_str(vf.reserved4, 1)); // filling up restart create_children( [MASK] , ""nrof_restarts"", ""wait_for_restart""); DXML_SET_TXT(dxml_child( [MASK] , ""nrof_restarts""), num_to_str(restart.no, 1)); DXML_SET_TXT(dxml_child( [MASK] , ""wait_for_restart""), num_to_str(restart.time, 2)); auto buffer = dxml_toxml(root); auto fp = fopen(filename, ""w""); fwrite(buffer, sizeof(char), strlen(buffer), fp); fclose(fp); delete[] buffer; return 0; } } // namespace kss2_bios",restart_tag 298,"// Kinect_Depth.cpp : 定义控制台应用程序的入口点。 // //#include ""windows.h"" #include ""stdafx.h"" #include ""NuiApi.h"" // Kinetc数据API #include ""DepthBasics.h"" // 深度图像基础定义 #include ""Kinect_DepthData.h"" // 深度图像基础数据 #include // 数据流 #include using namespace std; Data_Pixel Data_In_Pixel[480][640]; // 定义存放像素点信息的数组,有480行,680列 //Data_Pixel * ptrData_In_Pixel = (Data_Pixel*)Data_In_Pixel; INuiCoordinateMapper* DepthCoordinate = nullptr; BOOL CreateFirstConnected() { INuiSensor * pNuiSensor = nullptr; HRESULT hr; int iSensorCount = 0; hr = NuiGetSensorCount(&iSensorCount); // 获取连接的kinect数量 cout << ""kinect num:"" << iSensorCount << endl; if (FAILED(hr)) { m_pNuiSensor = pNuiSensor; return FALSE; } // Look at each Kinect sensor 对每个kinect进行初始化 for (int i = 0; i < iSensorCount; ++i) { // Create the sensor so we can check status, if we can't create it, move on to the next // 获取kinect对象 hr = NuiCreateSensorByIndex(i, &pNuiSensor); if (FAILED(hr)) { continue; } // Get the status of the sensor, and if connected, then we can initialize it // 查看kinect状态,有的设备没连接电源,也许有的设备有其他异常 hr = pNuiSensor->NuiStatus(); if (S_OK == hr) // 如果有一台正常的,那我们这个程序的初始化就算完毕了,因为这个例子只用一个kinect而已 { m_pNuiSensor = pNuiSensor; cout << ""finding "" << i+1 << "" kinect waiting for connecting"" << endl; //break; } // This sensor wasn't OK, so release it since we're not using it 如果是不正常的设备,那么Release掉,免得内存泄露 pNuiSensor->Release(); } if (NULL != m_pNuiSensor) // 如果pNuiSensor不为空,那表明找到某一个正常的kinect设备了 { // Initialize the Kinect and specify that we'll be using depth 初始化kinect,用NUI_INITIALIZE_FLAG_USES_DEPTH表示要使用深度图 hr = m_pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_DEPTH); if (SUCCEEDED(hr)) { HANDLE m_hNextDepthFrameEvent = CreateEvent(NULL, TRUE, FALSE, NULL); // Open a depth image stream to receive depth frames 打开深度图流,用来接收图像 hr = m_pNuiSensor->NuiImageStreamOpen( NUI_IMAGE_TYPE_DEPTH, // 表示要打开深度图流 NUI_IMAGE_RESOLUTION_640x480, // 深度图大小 0, // 帧设置,0表示无设置 2, // 缓存多少帧,最大为4 m_hNextDepthFrameEvent, // 用来通信的Event句柄 &m_pDepthStreamHandle); // 用来读取数据的流句柄,要从这里读取深度图数据 cout << ""Successful connected with Kinect"" << endl; return TRUE; } else { cout << ""Failed connected with Kinect"" << endl; } } if (NULL == m_pNuiSensor || FAILED(hr)) { cout << ""No ready Kinect found!"" << m_pNuiSensor << endl; return FALSE; } return SUCCEEDED(hr); } void ProcessDepth() { HRESULT hr; NUI_IMAGE_FRAME imageFrame; // Attempt to get the depth frame // 通过kinect对象,从m_pDepthStreamHandle中获取图像数据,还记得m_pDepthStreamHandle么,是在初始化kinect设备时创建的深度图流 // 在这里调用这个代码的意义是:将一帧深度图,保存在imageFrame中 hr = m_pNuiSensor->NuiImageStreamGetNextFrame(m_pDepthStreamHandle, 100, &imageFrame); if (FAILED(hr)) { cout << ""Image getting failed"" << endl; return; } BOOL nearMode = false; INuiFrameTexture* pTexture; // Get the depth image pixel texture 通过imageFrame把数据转化成纹理 hr = m_pNuiSensor->NuiImageFrameGetDepthImagePixelFrameTexture( m_pDepthStreamHandle, &imageFrame, &nearMode, &pTexture); if (FAILED(hr)) { goto ReleaseFrame; } NUI_LOCKED_RECT LockedRect; // Lock the frame data so the Kinect knows not to modify it while we're reading it 锁定数据 pTexture->LockRect(0, &LockedRect, NULL, 0); // Make sure we've received valid data if (LockedRect.Pitch != 0) { int i = 0; /*Vector4 *pSkeletonPoint[640*480]; NUI_DEPTH_IMAGE_POINT *Data_In_Pixel[640*480];*/ // Get the min and max reliable depth for the current frame int minDepth = (nearMode ? NUI_IMAGE_DEPTH_MINIMUM_NEAR_MODE : NUI_IMAGE_DEPTH_MINIMUM) >> NUI_IMAGE_PLAYER_INDEX_SHIFT; int maxDepth = (nearMode ? NUI_IMAGE_DEPTH_MAXIMUM_NEAR_MODE : NUI_IMAGE_DEPTH_MAXIMUM) >> NUI_IMAGE_PLAYER_INDEX_SHIFT; cout << ""minDepth:"" << minDepth << "" "" << ""maxDepth:"" << maxDepth << endl; // 将m_depthRGBX的首地址保存在rgbrun,方便赋值 BYTE * rgbrun = m_depthRGBX; NUI_DEPTH_IMAGE_PIXEL * pBufferRun = reinterpret_cast< NUI_DEPTH_IMAGE_PIXEL *>(LockedRect.pBits); // 去掉了const声明 const NUI_DEPTH_IMAGE_PIXEL * pBufferStart = pBufferRun; // end pixel is start + width*height - 1 const NUI_DEPTH_IMAGE_PIXEL * pBufferEnd = pBufferRun + (cDepthWidth * cDepthHeight); //对m_depthRGBX也就是rgbrun赋值 while (pBufferRun < pBufferEnd) { // 定义像素点的位置信息 int Index_Pixel = pBufferRun - pBufferStart; // 明确像素点是第几个 //cout << Index_Pixel << endl; // 第X行,第Y列的像素点 int X_Pixel = Index_Pixel / cDepthWidth; int Y_Pixel = Index_Pixel % cDepthWidth ; //Data_In_Pixel[Index_Pixel]->x = X_Pixel; Data_In_Pixel[Index_Pixel]->y = Y_Pixel; // 存入x,y的值 // discard the portion of the depth that contains only the player index USHORT depth = pBufferRun->depth; Data_In_Pixel[X_Pixel][X_Pixel].Depth = depth; // 保存深度值 //ptrData_In_Pixel->Depth = depth; // 保存深度值 //hr = DepthCoordinate->MapDepthPointToSkeletonPoint(NUI_IMAGE_RESOLUTION_640x480, Data_In_Pixel[X_Pixel * 640 + Y_Pixel], pSkeletonPoint[X_Pixel * 640 + Y_Pixel]); //// //if (S_OK == hr) //{ // cout << pSkeletonPoint[X_Pixel * 640 + Y_Pixel]->x << pSkeletonPoint[X_Pixel * 640 + Y_Pixel]->y << pSkeletonPoint[X_Pixel * 640 + Y_Pixel]->z << endl; //} // To convert to a byte, we're discarding the most-significant // rather than least-significant bits. // We're preserving detail, although the intensity will ""wrap."" // Values outside the reliable depth range are mapped to 0 (black). // Note: Using conditionals in this loop could degrade performance. // Consider using a lookup table instead when writing production code. BYTE intensity = static_cast(depth >= minDepth && depth <= maxDepth ? depth % 256 : 0); Data_In_Pixel[X_Pixel][Y_Pixel].intensity = intensity; // 保存色素信息 //ptrData_In_Pixel->Depth = intensity; //cout << X_Pixel << "" "" << Y_Pixel << "" "" << depth << "" "" << int(intensity) << endl; //cout << depth << "" "" << intensity << endl; // Write out blue byte 写蓝色素位 *(rgbrun++) = intensity; // Write out green byte 写绿色素位 *(rgbrun++) = intensity; // Write out red byte 写红色素位 *(rgbrun++) = intensity; // We're outputting BGR, the last byte in the 32 bits is unused so skip it // If we were outputting BGRA, we would write alpha here. ++rgbrun; // Increment our index into the Kinect's depth buffer ++pBufferRun; } //delete pSkeletonPoint; //delete Data_In_Pixel; } //cout << Data_In_Pixel[240][320].Depth << "" "" << Data_In_Pixel[240][320].intensity << endl; // 用来测试数据流是否正确 // We're done with the texture so unlock it 解锁和释放纹理 pTexture->UnlockRect(0); pTexture->Release(); ReleaseFrame: // Release the frame 释放帧 m_pNuiSensor->NuiImageStreamReleaseFrame(m_pDepthStreamHandle, &imageFrame); } int main() { bool [MASK] = CreateFirstConnected(); // 进行连接检测程序 while ( [MASK] ) // while的循环条件可以用作控制 { ProcessDepth(); // 完成主程序过程 } } ",connect_hr 299,"// BackgroundParser.cpp // Implements the BackgroundParser class representing the background thread pool for parsing files / folders. #include ""BackgroundParser.h"" #include #include #include #include ""FileParser.h"" //////////////////////////////////////////////////////////////////////////////// /** Task executed inside BackgroundParser to parse a single file. */ class FileParseTask: public QRunnable { public: FileParseTask(BackgroundParser & a_BackgroundParser, const QString & a_FileName): m_FileName(a_FileName), m_BackgroundParser(a_BackgroundParser) { } virtual void run() { FileParser parser(m_BackgroundParser.m_ShouldAbort); QObject::connect(&parser, &FileParser::finishedParsingFile, &m_BackgroundParser, &BackgroundParser::finishedParsingFile); parser.parse(m_FileName); } protected: QString m_FileName; BackgroundParser & m_BackgroundParser; }; //////////////////////////////////////////////////////////////////////////////// /** Task executed inside BackgroundParser to parse a folder. */ class FolderParseTask: public QRunnable { public: FolderParseTask(BackgroundParser & a_BackgroundParser, const QString & a_FolderPath): m_FolderPath(a_FolderPath), m_BackgroundParser(a_BackgroundParser) { } virtual void run() override { addFolderLogFiles(m_FolderPath); } void addFolderLogFiles(const QString & a_FolderPath) { static QStringList [MASK] ; if ( [MASK] .isEmpty()) { [MASK] << ""*.log"" << ""*.gz"" << ""*.txt""; } QDir folder(a_FolderPath); QStringList res; for (const auto & fileName: folder.entryList( [MASK] , QDir::Files | QDir::Hidden | QDir::System)) { m_BackgroundParser.addFile(a_FolderPath + ""/"" + fileName); } for (const auto & folderPath: folder.entryList(QStringList(), QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System)) { addFolderLogFiles(a_FolderPath + ""/"" + folderPath); } } protected: QString m_FolderPath; BackgroundParser & m_BackgroundParser; }; //////////////////////////////////////////////////////////////////////////////// // BackgroundParser: BackgroundParser::BackgroundParser(): Super(nullptr) { } BackgroundParser::~BackgroundParser() { qDebug() << ""Aborting all parsers""; m_ThreadPool.clear(); m_ShouldAbort.store(true); } void BackgroundParser::addFile(const QString & a_FileName) { m_ThreadPool.start(new FileParseTask(*this, a_FileName)); } void BackgroundParser::addFolder(const QString & a_FolderPath) { m_ThreadPool.start(new FolderParseTask(*this, a_FolderPath)); } ",logFileNameFilters 300,"#include ""bootloader.h"" using namespace bootloader::architecture; namespace bootloader { void Bootloader::run() { m_metadataInterface.init(); size_t [MASK] = selectImageSlot(); // Update Metadata const GlobalImageMetadata* globalImageMetadata = m_metadataInterface.getGlobalImageMetadata(); m_metadataInterface.updateCurrentImage( [MASK] ); m_metadataInterface.updateGlobalBootcounter(globalImageMetadata->globalBootcounter + 1); m_metadataInterface.updateImageBootcounter( globalImageMetadata->images[ [MASK] ].bootcounter + 1, [MASK] ); m_metadataInterface.loadImage( [MASK] ); // Start Image Disable_Interrupts(); Move_Vector_Table(); Enable_Interrupts(); Trigger_Watchdog(); Start_App(); } size_t Bootloader::selectImageSlot() { size_t preferredImage = m_metadataInterface.getGlobalImageMetadata()->preferredImage; if (isImageValid(preferredImage) && lastBootSuccessful(preferredImage)) { return preferredImage; } size_t lastImage = m_metadataInterface.getGlobalImageMetadata()->currentImage; if (isImageValid(lastImage) && lastBootSuccessful(lastImage)) { return lastImage; } return selectBestGuessImageSlot(); } size_t Bootloader::selectBestGuessImageSlot() { // Find image that is complete, has correct checksum and last boot was successful size_t currentImage = m_metadataInterface.getGlobalImageMetadata()->currentImage; for (size_t i = 0; i < MetadataInterface::getNumberOfImages(); i++) { size_t imageIndex = (currentImage + i) % MetadataInterface::getNumberOfImages(); if (isImageValid(imageIndex) && lastBootSuccessful(imageIndex)) { return (currentImage + i) % MetadataInterface::getNumberOfImages(); } } // Find image that is complete and has correct checksum (no matter if last boot was successful) for (size_t i = 0; i < MetadataInterface::getNumberOfImages(); i++) { size_t imageIndex = (currentImage + i) % MetadataInterface::getNumberOfImages(); if (isImageValid(imageIndex)) { return imageIndex; } } // Otherwise only use round robin return (currentImage + 1) % MetadataInterface::getNumberOfImages(); } bool Bootloader::isImageValid(size_t index) { return m_metadataInterface.getGlobalImageMetadata()->images[index].completionStatus == CompletionStatus::COMPLETE && verifyChecksum(index); } bool Bootloader::lastBootSuccessful(size_t index) { const GlobalImageMetadata* globalImageMetadata = m_metadataInterface.getGlobalImageMetadata(); return globalImageMetadata->images[index].bootcounter == globalImageMetadata->images[index].lastSuccessStatus || globalImageMetadata->images[index].bootcounter == globalImageMetadata->images[index].lastSuccessStatus + 1; } bool Bootloader::verifyChecksum(size_t index) { return m_metadataInterface.verifyChecksum(index); } } // namespace bootloader ",selectedImage 301,"#include #include #include ""gms_matcher.h"" #include ""ORB_modify.h"" #include ""ORBextractor.h"" #include #include ""opencv2/imgcodecs/legacy/constants_c.h"" using namespace std; using namespace cv; //extern double ORBextractor::ORBextractorDescriptorsTime; //计算均匀度Uniformity double ComputeUniformity(cv::Mat &img, std::vector &keypoints) { //******************************************************************均匀性计算 int KPLeftNum = 0, KPRightNum = 0; //左右部分的关键点数量 int KPTopNum = 0, KPDownNum = 0; //上下部分的关键点数量 int KP_Right_Top_Num = 0, KP_Left_Down_Num = 0; //右上,左下部分的关键点数量 int KP_Left_Top_Num = 0, KP_Right_Down_Num = 0; //左上,右下部分的关键点数量 int KPCentreNum = 0, KPPeripheryNum = 0; //中心,外围部分的关键点数量 //******************************************************************均匀性计算 //********************************************************************************** const int minBorderX = 0; const int minBorderY = 0; const int maxBorderX = img.cols; const int maxBorderY = img.rows; // cout << ""maxBorderX:"" << img.cols << endl; // cout << ""maxBorderY:"" << img.rows << endl; // cout << ""img.size:"" << img.size << endl; //********************************************************************************** for (std::vector::iterator vit = keypoints.begin(); vit != keypoints.end(); vit++) { //****************************左右*************************************// // line(img, Point((maxBorderX - minBorderX) / 2, 0), Point((maxBorderX - minBorderX) / 2, maxBorderY), 8); // imshow(""左右"", img); if ((*vit).pt.x <= (maxBorderX - minBorderX) / 2) //左半部分的特征点数量 { // circle(img,(*vit).pt, 3, Scalar(0, 255, 120), -1);//画点,其实就是实心圆 // imshow(""PointsinImage"", img); // waitKey(0);//敲键盘关图片,别直接× KPLeftNum++; } else //右半部分的特征点数量 { // circle(img,(*vit).pt, 3, Scalar(0, 0, 255), -1);//画点,其实就是实心圆 // imshow(""PointsinImage"", img); // waitKey(0);//敲键盘关图片,别直接× KPRightNum++; } //****************************上下*************************************// // line(img, Point(0, (maxBorderY - minBorderY) / 2), Point(maxBorderX, (maxBorderY - minBorderY) / 2), 8); // imshow(""上下"", img); if ((*vit).pt.y <= (maxBorderY - minBorderY) / 2) //上半部分的特征点数量 { // circle(img,(*vit).pt, 3, Scalar(0, 255, 120), -1);//画点,其实就是实心圆 // imshow(""PointsinImage"", img); KPTopNum++; } else //下半部分的特征点数量 { // circle(img,(*vit).pt, 3, Scalar(0, 0, 255), -1);//画点,其实就是实心圆 // imshow(""PointsinImage"", img); KPDownNum++; } //****************************右上左下*************************************// // line(img, Point(0, 0), Point(maxBorderX, maxBorderY), 8); // imshow(""右上左下"", img); if (((*vit).pt.y - maxBorderY) * (maxBorderX - minBorderX) - ((*vit).pt.x - maxBorderX) * (maxBorderY - minBorderY) >= 0) //右上半部分的特征点数量 //这是对角线方程 (y - y2)*(x1 - x2) - (x - x2)*(y1 - y2) { // circle(img,(*vit).pt, 3, Scalar(0, 255, 120), -1);//画点,其实就是实心圆 // imshow(""PointsinImage"", img); KP_Right_Top_Num++; } else //左下半部分的特征点数量 { // circle(img,(*vit).pt, 3, Scalar(0, 0, 255), -1);//画点,其实就是实心圆 // imshow(""PointsinImage"", img); KP_Left_Down_Num++; } //****************************右下左上*************************************// // line(img, Point(maxBorderX, 0), Point(0, maxBorderY), 8); // imshow(""右下左上"", img); if (((*vit).pt.y - maxBorderY) * (maxBorderX - minBorderX) - ((*vit).pt.x - minBorderX) * (minBorderY - maxBorderY) > 0) //左上半部分的特征点数量 { // circle(img,(*vit).pt, 3, Scalar(0, 255, 120), -1);//画点,其实就是实心圆 // imshow(""PointsinImage"", img); // waitKey(0);//敲键盘关图片,别直接× KP_Left_Top_Num++; } else //右下半部分的特征点数量 { // circle(img,(*vit).pt, 3, Scalar(0, 0, 255), -1);//画点,其实就是实心圆 // imshow(""PointsinImage"", img); KP_Right_Down_Num++; } // 不要中心外围这部分的数据,原因:不能平分面积 //****************************中心外围*************************************// float X1 = (maxBorderX - minBorderX) / 6 - 8; //中心框的坐标X1 float X2 = 5 * (maxBorderX - minBorderX) / 6 + 8; //中心框的坐标X2 float Y1 = (maxBorderY - minBorderY) / 6 - 8; //中心框的坐标Y1 float Y2 = 5 * (maxBorderY - minBorderY) / 6 + 8; //中心框的坐标Y2 // line(img, Point(X1, Y1), Point(X2, Y1), 8); // line(img, Point(X1, Y1), Point(X1, Y2), 8); // line(img, Point(X2, Y1), Point(X2, Y2), 8); // line(img, Point(X1, Y2), Point(X2, Y2), 8); // imshow(""中心外围"", img); if (((*vit).pt.x >= X1) & ((*vit).pt.x <= X2) & ((*vit).pt.y >= Y1) & ((*vit).pt.y <= Y2) )//中心部分的特征点数量 { // circle(img,(*vit).pt, 3, Scalar(0, 255, 120), -1);//画点,其实就是实心圆 // imshow(""PointsinImage"", img); KPCentreNum++; } else //外围部分的特征点数量 { // circle(img,(*vit).pt, 3, Scalar(0, 0, 255), -1);//画点,其实就是实心圆 // imshow(""PointsinImage"", img); KPPeripheryNum++; } } //***********************************去除中心外围,共8个区域*********************************************** // int sum_ = // KPLeftNum + KPRightNum + KPTopNum + KPDownNum + KP_Right_Top_Num + KP_Left_Down_Num + KP_Left_Top_Num + // KP_Right_Down_Num ; // double mean_ = sum_ / 8; // double Variance = (pow((KPLeftNum - mean_),2) + pow((KPRightNum - mean_),2) + // pow((KPTopNum - mean_),2) + pow((KPDownNum - mean_) ,2) + // pow((KP_Right_Top_Num - mean_) ,2) + pow((KP_Left_Down_Num - mean_) ,2) + // pow((KP_Left_Top_Num - mean_) ,2)+ pow((KP_Right_Down_Num - mean_) ,2)) /8; // double Uniformity = 101*log(Variance); // cout << ""左半部分的特征点数量:"" << KPLeftNum << endl; // cout << ""右半部分的特征点数量:"" << KPRightNum << endl; // cout << ""上半部分的特征点数量:"" << KPTopNum << endl; // cout << ""下半部分的特征点数量:"" << KPDownNum << endl; // cout << ""右上半部分的特征点数量:"" << KP_Right_Top_Num << endl; // cout << ""左下半部分的特征点数量:"" << KP_Left_Down_Num << endl; // cout << ""左上半部分的特征点数量:"" << KP_Left_Top_Num << endl; // cout << ""右下半部分的特征点数量:"" << KP_Right_Down_Num << endl; // cout << ""八个区域特征点数的平均值:"" << mean_ << endl; // cout << ""八个区域特征点数的方差:"" << Variance << endl; // cout << ""图像特征点均匀度:"" << Uniformity << endl; // cout << endl; // return Uniformity; //***********************************加上中心外围,共10个区域*********************************************** int sum_ = KPLeftNum + KPRightNum + KPTopNum + KPDownNum + KP_Right_Top_Num + KP_Left_Down_Num + KP_Left_Top_Num + KP_Right_Down_Num + KPCentreNum + KPPeripheryNum; double mean_ = sum_ / 10; //约等于500 double Variance = (pow((KPLeftNum - mean_),2) + pow((KPRightNum - mean_),2) + pow((KPTopNum - mean_),2) + pow((KPDownNum - mean_) ,2) + pow((KP_Right_Top_Num - mean_) ,2) + pow((KP_Left_Down_Num - mean_) ,2) + pow((KP_Left_Top_Num - mean_) ,2)+ pow((KP_Right_Down_Num - mean_) ,2) + pow((KPCentreNum - mean_) ,2) + pow((KPPeripheryNum - mean_) ,2) ) /10; double Uniformity = 101*log10(Variance); // cout << ""左半部分的特征点数量:"" << KPLeftNum << endl; // cout << ""右半部分的特征点数量:"" << KPRightNum << endl; // cout << ""上半部分的特征点数量:"" << KPTopNum << endl; // cout << ""下半部分的特征点数量:"" << KPDownNum << endl; // cout << ""右上半部分的特征点数量:"" << KP_Right_Top_Num << endl; // cout << ""左下半部分的特征点数量:"" << KP_Left_Down_Num << endl; // cout << ""左上半部分的特征点数量:"" << KP_Left_Top_Num << endl; // cout << ""右下半部分的特征点数量:"" << KP_Right_Down_Num << endl; // cout << ""中心部分的特征点数量:"" << KPCentreNum << endl; // cout << ""外围部分的特征点数量:"" << KPPeripheryNum << endl; // cout << ""十个区域特征点数的平均值:"" << mean_ << endl; // cout << ""十个区域特征点数的方差:"" << Variance << endl; // cout << ""图像特征点均匀度:"" << Uniformity << endl; // cout << endl; return Uniformity; } //********************************************************************************** //计算RANSAC后的RMSE double calculate_RANSAC_inliers_RMSE(Mat& img1, Mat& img2, vector & all_matches, std::vector & leftmvKeysUn, std::vector & rightmvKeysUn,string &Argv4) { // Take only the matched points that will be used to calculate the // transformation between both images // TODO:只取匹配的点,用于计算两个图像之间的转换 std::vector matched_pts1, matched_pts2; for (cv::DMatch _match_ : all_matches)// TODO:不用描述子距离判断all_matches_filter { matched_pts1.push_back(leftmvKeysUn[_match_.queryIdx].pt); matched_pts2.push_back(rightmvKeysUn[_match_.trainIdx].pt); } // Find the homography that transforms a point in the first image to a point in the second image. cv::Mat inliers; cv::Mat H = cv::findHomography(matched_pts1, matched_pts2, cv::RANSAC, 3, inliers); // Print the number of inliers, that is, the number of points correctly // mapped by the transformation that we have estimated std::cout << ""RANSAC去除错误匹配后的内点数: "" << cv::sum(inliers)[0] << "" ( 精度:"" << (100.0f * cv::sum(inliers)[0] / all_matches.size()) << ""% )"" << std::endl;//cv::sum(inliers)[0] / all_matches.size()) // cout<< ""H:"" << H <(0,0); const double h12 = H.at(0,1); const double h13 = H.at(0,2); const double h21 = H.at(1,0); const double h22 = H.at(1,1); const double h23 = H.at(1,2); const double h31 = H.at(2,0); const double h32 = H.at(2,1); const double h33 = H.at(2,2); // const float h11 = 1.0107879e+00; // const float h12 = 8.2814684e-03; // const float h13 = 1.8576800e+01; // const float h21 = -4.9128885e-03; // const float h22 = 1.0148779e+00 ; // const float h23 = -2.8851517e+01; // const float h31 = -1.9166087e-06; // const float h32 = 8.1537620e-06 ; // const float h33 = 1.0000000e+00; vector optimizeM; for(int i = 0; i < inliers.rows; i++) { if(inliers.at(i,0)) { optimizeM.push_back(all_matches[i]);// TODO:不用描述子距离判断all_matches_filter } } std::vector [MASK] , matched_pts4; for (cv::DMatch matc1 : optimizeM) { [MASK] .push_back(leftmvKeysUn[matc1.queryIdx].pt); matched_pts4.push_back(rightmvKeysUn[matc1.trainIdx].pt); } Mat result2; drawMatches(img1, leftmvKeysUn, img2, rightmvKeysUn, optimizeM, result2, Scalar(0, 255, 0), Scalar::all(-1));//Scalar::all(-1) imwrite(""./result/ORB_RANSAC_matcher_""+Argv4+"".png"", result2); // imshow(""ORB_RANSAC_matcher"", result2); std::vector matched_pts2_ture_H; // ""[x',y',1] "" << H*[x,y,1] for (std::vector::iterator vit = [MASK] .begin(); vit != [MASK] .end(); vit++) { double x1 = (*vit).x;//左图匹配的特征点的x坐标 double y1 = (*vit).y;//左图匹配的特征点的y坐标 // Reprojection error in second image // x1in2 = H21*x1 Point2d temp; temp.x =(h11*x1 + h12*y1 + h13)/(h31*x1 + h32*y1 + h33);//左图匹配的特征点的x坐标 经过单应矩阵H 变换到右图的x坐标 temp.y =(h21*x1 + h22*y1 + h23)/(h31*x1 + h32*y1 + h33);//左图匹配的特征点的y坐标 经过单应矩阵H 变换到右图的y坐标 matched_pts2_ture_H.push_back(temp); } std::vector::iterator vit = matched_pts2_ture_H.begin(); std::vector::iterator vit2 = matched_pts4.begin(); double fsum=0,RMSE=0; int sum=0; while(vit != matched_pts2_ture_H.end()) { // cout<< ""vit "" << (*vit) < all_matches_BF, gms_matches; // matcher.match(ORB_left.mDescriptors, ORB_right.mDescriptors, all_matches_BF); //输出结果all_matches // Mat all_matches_img; // drawMatches(img1, ORB_left.mvKeys, img2, ORB_right.mvKeys, all_matches_BF, all_matches_img, Scalar(0, 255, 0), Scalar::all(-1)); // imwrite(""./result/ORB_BFmatcher.png"", all_matches_img); // imshow(""ORB_BFmatcher"", all_matches_img); // cout << ""图1获得特征点数 "" << ORB_left.mvKeys.size() << "" keypoints."" << endl; // cout << ""图2获得特征点数 "" << ORB_right.mvKeys.size() << "" keypoints."" << endl; // std::cout << ""暴力匹配后个数: "" << all_matches_BF.size() << std::endl; // ****************************Hamming 距离筛选匹配:对两幅图像中的BRIEF描述子进行匹配,使用 Hamming 距离************************************************ //*** 匹配耗时 std::chrono::steady_clock::time_point t11 = std::chrono::steady_clock::now(); vector all_matches_BF, gms_matches,all_matches_distance_filter; Ptr matcher = DescriptorMatcher::create(""BruteForce-Hamming""); matcher->match(ORB_left.mDescriptors, ORB_right.mDescriptors, all_matches_BF); //输出结果all_matches cout << ""图1获得特征点数 "" << ORB_left.mvKeys.size() << "" keypoints."" << endl; cout << ""图2获得特征点数 "" << ORB_right.mvKeys.size() << "" keypoints."" << endl; //***********************匹配点对筛选(人为设计)********************************************** double min_dist = 10000, max_dist = 0; //找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离 for (int i = 0; i < all_matches_BF.size(); i++) { double dist = all_matches_BF[i].distance; if (dist < min_dist) min_dist = dist; if (dist > max_dist) max_dist = dist; } // printf(""BRIEF描述子-- Max dist : %f \n"", max_dist); // printf(""BRIEF描述子-- Min dist : %f \n"", min_dist); //当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限 for (int i = 0; i < all_matches_BF.size(); i++) { if (all_matches_BF[i].distance <= max(2 * min_dist, 30.0))//增加特征点数或减少特征点数再这里调整 { all_matches_distance_filter.push_back(all_matches_BF[i]); } } std::chrono::steady_clock::time_point t22 = std::chrono::steady_clock::now(); double ORBmatchTime= std::chrono::duration_cast >(t22 - t11).count(); cout << ""匹配耗时 :"" << ORBmatchTime << endl; printf(""ORB-- All matches : %d \n"", (int) all_matches_BF.size()); // printf(""ORB-- Descriptors max distance : %d \n"", (int) max(2 * min_dist, 30.0)); printf(""ORB-- Optimized matching : %d \n"", (int) all_matches_distance_filter.size()); Mat result; drawMatches(img1, ORB_left.mvKeys, img2, ORB_right.mvKeys, all_matches_distance_filter, result, Scalar(0, 255, 0), Scalar(0, 255, 0));///Scalar::all(-1) // imwrite(""./result/ORB_matcher_distance_""+Argv4+"".png"", result); // imshow(""ORB_matcher_distance"", result); //*****************************************计算RMSE********参考BEBLID算法和SIFTS算法******************************* //SIFT算法详解(附有完整代码)https://blog.csdn.net/weixin_47156401/article/details/122367593?spm=1001.2014.3001.5502 //*************************************************************************************************************** //TODO 计算经过RANSAC后的内点的均方根误差RMSE // calculate_RANSAC_inliers_RMSE(img1, img2, all_matches_BF, ORB_left.mvKeys, ORB_right.mvKeys);//暴力匹配筛选的 calculate_RANSAC_inliers_RMSE(img1, img2, all_matches_distance_filter, ORB_left.mvKeys, ORB_right.mvKeys,Argv4);//Hamming距离阈值匹配筛选的 //*****************************************计算RMSE************************************************************** //*************************************************************************************************************** // GMS filter std::vector vbInliers; gms_matcher gms(ORB_left.mvKeys, img1.size(), ORB_right.mvKeys, img2.size(), all_matches_BF); // cout<< img1.size() < #include #include #include ""map.h"" #include using namespace sf; using namespace std; float offsetX = 0, offsetY = 0; String TileMap[HEIGHT_MAP]; class PLAYER { public: short countApple = 0; float dx, dy; FloatRect coordinate, firstCoordinateTp, secondCoordinateTp; bool onGround, check; Sprite spritePlayer; float currentFrame; void init(Texture &image, float time) { spritePlayer.setTexture(image); //coordinate = FloatRect(70 * 32, 2 * 32, 60, 97); coordinate = FloatRect(3 * 32, 12 * 32, 60, 97); dx = dy = 0.1; currentFrame = 0; offsetX = 0; } PLAYER(Texture &image, float time) { init(image, time); } }; short startMenu(RenderWindow &window); short startGame(RenderWindow &window, short countAllApple); void update(PLAYER &player, float time); void collision(PLAYER &player, bool variables); short showEndGameMenu(RenderWindow &window, short countAllApple); void update(PLAYER &player, float time) { player.coordinate.left += player.dx * time; // Перемещение по x collision(player, true); // x if (!player.onGround) { player.dy = player.dy + 0.0005*time; // Падение с ускорением } player.coordinate.top += player.dy*time; player.onGround = false; collision(player, false); // y player.currentFrame += 0.005*time; if (player.currentFrame > 6) player.currentFrame -= 6; if (player.dx == 0) { player.spritePlayer.setTextureRect(IntRect(30, 19, 60, 97)); } if (player.dx > 0) { player.spritePlayer.setTextureRect(IntRect(180 + (150 * int(player.currentFrame)), 19, 60, 97)); } if (player.dx < 0) { player.spritePlayer.setTextureRect(IntRect(180 + (150 * int(player.currentFrame)) + 60, 19, -60, 97)); } player.spritePlayer.setPosition(player.coordinate.left - offsetX, player.coordinate.top - offsetY); player.dx = 0; } void collision(PLAYER &player, bool variables) { Clock clock; for (int i(player.coordinate.top / 32); i < (player.coordinate.top + player.coordinate.height) / 32; i++) { for (int j(player.coordinate.left / 32); j < (player.coordinate.left + player.coordinate.width) / 32; j++) { if ((TileMap[i][j] == '0') || (TileMap[i][j] == 'b') || (TileMap[i][j] == 'p') || (TileMap[i][j] == 'd')) { if ((player.dx > 0) && (variables == true)) { player.coordinate.left = j * 32 - player.coordinate.width; } if ((player.dx < 0) && (variables == true)) { player.coordinate.left = j * 32 + 32; } if ((player.dy > 0) && (variables == false)) { player.coordinate.top = i * 32 - player.coordinate.height; player.dy = 0; player.onGround = true; } if ((player.dy < 0) && (variables == false)) { player.coordinate.top = i * 32 + 32; player.dy = 0; } } if (TileMap[i][j] == '1') { player.coordinate = player.firstCoordinateTp; update(player, 0); } if (TileMap[i][j] == '3') { player.coordinate = player.secondCoordinateTp; update(player, 0); } if (TileMap[i][j] == 'a') { TileMap[i][j] = ' '; player.countApple++; } } } } short startMenu(RenderWindow &window) { short elementMenu(0); Texture tMenuBackground, tMenuStartGame, tMenuRecords, tMenuExit, tMenuImageChoice, tMenuRecordsBackground; tMenuBackground.loadFromFile(""images/menuBackground.png""); tMenuStartGame.loadFromFile(""images/menuStartGame.png""); tMenuImageChoice.loadFromFile(""images/menuImageChoice.png""); tMenuExit.loadFromFile(""images/menuExit.png""); tMenuRecords.loadFromFile(""images/menuRecords.png""); tMenuRecordsBackground.loadFromFile(""images/menuRecordsBackground.png""); Sprite sMenuBackground(tMenuBackground), sMenuStartGame(tMenuStartGame), sMenuRecords(tMenuRecords), sMenuExit(tMenuExit), sMenuImageChoice(tMenuImageChoice), sMenuRecordsBackground(tMenuRecordsBackground); sMenuBackground.setPosition(0, 0); sMenuStartGame.setPosition(145, 423); sMenuRecords.setPosition(168, 476); sMenuExit.setPosition(145, 530); sMenuRecordsBackground.setPosition(0, 0); while (window.isOpen()) { Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } window.draw(sMenuBackground); sMenuStartGame.setColor(Color(86, 59, 56)); sMenuRecords.setColor(Color(86, 59, 56)); sMenuExit.setColor(Color(86, 59, 56)); elementMenu = 0; if (IntRect(145, 423, 143, 23).contains(Mouse::getPosition(window))) { sMenuStartGame.setColor(Color(164, 72, 68)); sMenuImageChoice.setPosition(89, 405); window.draw(sMenuImageChoice); elementMenu = 1; } if (IntRect(166, 476, 96, 23).contains(Mouse::getPosition(window))) { sMenuRecords.setColor(Color(164, 72, 68)); sMenuImageChoice.setPosition(111, 458); window.draw(sMenuImageChoice); elementMenu = 2; } if (IntRect(145, 530, 71, 18).contains(Mouse::getPosition(window))) { sMenuExit.setColor(Color(164, 72, 68)); sMenuImageChoice.setPosition(89, 511); window.draw(sMenuImageChoice); elementMenu = 3; } if (Mouse::isButtonPressed(Mouse::Left)) { switch (elementMenu) { case 1: { return elementMenu; break; } case 2: { window.draw(sMenuRecordsBackground); window.display(); while (!Keyboard::isKeyPressed(Keyboard::Escape)); break; } case 3: { return elementMenu; break; } default: break; } } window.draw(sMenuStartGame); window.draw(sMenuRecords); window.draw(sMenuExit); window.display(); } } short startGame(RenderWindow &window, short countAllApple) { View view; Font font; font.loadFromFile(""adominorevobl_bold.ttf""); Text textCountApple("""", font, 24), textTimer("""", font, 24); textCountApple.setFillColor(Color(255, 255, 255)); textCountApple.setStyle(Text::Bold); textTimer.setFillColor(Color(255, 255, 255)); textTimer.setStyle(Text::Bold); Texture texturePlayer, bg, tGround, tTiles, tApple, tDoorOpen, tDoorClosed, tTimer; texturePlayer.loadFromFile(""images/newton-sheet.png""); bg.loadFromFile(""images/bg.png""); tGround.loadFromFile(""images/ground.png""); tTiles.loadFromFile(""images/tiles.png""); tApple.loadFromFile(""images/apple.png""); tDoorClosed.loadFromFile(""images/door_closed.png""); tDoorOpen.loadFromFile(""images/door_open.png""); tTimer.loadFromFile(""images/timer_32.png""); texturePlayer.setSmooth(true); bg.setSmooth(true); tGround.setSmooth(true); tTiles.setSmooth(true); tApple.setSmooth(true); tDoorClosed.setSmooth(true); tDoorOpen.setSmooth(true); tTimer.setSmooth(true); Sprite sBg(bg), sGround(tGround), sTiles(tTiles), sApple(tApple), sDoorOpen(tDoorOpen), sDoorClosed(tDoorClosed), sTimer(tTimer); copy(begin(TileMapOrigin), end(TileMapOrigin), begin(TileMap)); // Копирование начальной карты PLAYER p(texturePlayer, 0); SoundBuffer buffer; buffer.loadFromFile(""sounds/jump.ogg""); Sound sound(buffer); Music music; music.openFromFile(""sounds/Monkeys_Spinning_Monkeys.ogg""); music.play(); music.setLoop(true); Clock clock; float currentFrame(0); int timer(20000 * 6); // 10 sec ~ 20000 while (window.isOpen()) { float time = clock.getElapsedTime().asMicroseconds(); clock.restart(); time /= 500; if (time > 20) { time = 20; } timer -= time; if (timer < 0) { countAllApple = p.countApple; return countAllApple; } Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } if (Keyboard::isKeyPressed(Keyboard::Left) || Keyboard::isKeyPressed(Keyboard::A)) { p.dx = -0.1; } if (Keyboard::isKeyPressed(Keyboard::Right) || Keyboard::isKeyPressed(Keyboard::D)) { p.dx = 0.1; } if (Keyboard::isKeyPressed(Keyboard::Up) || Keyboard::isKeyPressed(Keyboard::W) || Keyboard::isKeyPressed(Keyboard::Space)) { if (p.onGround) { p.dy = -0.4; p.onGround = false; sound.play(); } } if (Keyboard::isKeyPressed(Keyboard::R)) { music.play(); music.setLoop(true); } if (Keyboard::isKeyPressed(Keyboard::F)) { music.stop(); } if (Keyboard::isKeyPressed(Keyboard::G)) { // Перемещение в начало p.init(texturePlayer, time); } update(p, time); if ((p.coordinate.left > 400) && ((880 < 150 * 32 - p.coordinate.left))) { offsetX = p.coordinate.left - 400; } window.clear(Color::White); window.draw(sBg); for (int i(0); i < HEIGHT_MAP; i++) { for (int j(0); j < WIDTH_MAP; j++) { if (TileMap[i][j] == '0') { continue; } if (TileMap[i][j] == ' ') { continue; } if (TileMap[i][j] == 'b') { sGround.setTextureRect(IntRect(6 * 32, 2 * 32, 32, 16)); } if (TileMap[i][j] == 'p') { sGround.setTextureRect(IntRect(160, 288, 32, 32)); } if (TileMap[i][j] == '1' || TileMap[i][j] == '3') { sDoorOpen.setTextureRect(IntRect(0, 0, 64, 128)); sDoorOpen.setPosition(j * 32 - offsetX, i * 32 - 32 - offsetY); window.draw(sDoorOpen); } if (TileMap[i][j] == '2') { sDoorClosed.setTextureRect(IntRect(0, 0, 64, 128)); sDoorClosed.setPosition(j * 32 - offsetX, i * 32 - 32 - offsetY); p.firstCoordinateTp = FloatRect(j * 32, i * 32 - 32, 60, 97); window.draw(sDoorClosed); } if (TileMap[i][j] == '4') { sDoorClosed.setTextureRect(IntRect(0, 0, 64, 128)); sDoorClosed.setPosition(j * 32 - offsetX, i * 32 - 32 - offsetY); p.secondCoordinateTp = FloatRect(j * 32 , i * 32 - 32, 60, 97); window.draw(sDoorClosed); } if (TileMap[i][j] == 'a') { sApple.setTextureRect(IntRect(0, 0, 32, 32)); sApple.setPosition(j * 32 - offsetX, i * 32 - offsetY); window.draw(sApple); } if (TileMap[i][j] == 'd') { sGround.setTextureRect(IntRect(1 * 32, 10 * 32, 32, 16)); } if (!((TileMap[i][j] == '1') || (TileMap[i][j] == '2') || (TileMap[i][j] == 'a') || (TileMap[i][j] == '3') || (TileMap[i][j] == '4'))) { sGround.setPosition(j * 32 - offsetX, i * 32 - offsetY); window.draw(sGround); } } } ostringstream countAppleString, timerString; // Отображение кол-ва яблок sApple.setTextureRect(IntRect(0, 0, 32, 32)); sApple.setPosition(view.getCenter().x - 446, view.getCenter().y - 473); window.draw(sApple); countAppleString << p.countApple; textCountApple.setString("": "" + countAppleString.str()); textCountApple.setPosition(view.getCenter().x - 410, view.getCenter().y - 471); window.draw(textCountApple); //Таймер sTimer.setTextureRect(IntRect(0, 0, 35, 35)); sTimer.setPosition(view.getCenter().x + 50, view.getCenter().y - 473); window.draw(sTimer); timerString << (timer / 2000); textTimer.setString("": "" + timerString.str()); textTimer.setPosition(view.getCenter().x + 87, view.getCenter().y - 470); window.draw(textTimer); window.draw(p.spritePlayer); window.display(); } } short showEndGameMenu(RenderWindow &window, short countAllApple) { View view; Font font; font.loadFromFile(""PT_SANS-WEB-BOLDITALIC.TTF""); wstring strRepeatGame = L""Начать заново"", strBackToMainMenu = L""Выйти в главное меню""; Text textRepeatGame(strRepeatGame, font, 36), [MASK] (strBackToMainMenu, font, 36), textCountAllApple("""", font, 42); textRepeatGame.setFillColor(Color(86, 59, 56)); [MASK] .setFillColor(Color(86, 59, 56)); textCountAllApple.setFillColor(Color(86, 59, 56)); Texture tMenuBackground; tMenuBackground.loadFromFile(""images/menuRepeatBackground.png""); Sprite sMenuBackground(tMenuBackground); sMenuBackground.setPosition(0, 0); short elementMenu(0); while (window.isOpen()) { Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } window.draw(sMenuBackground); ostringstream countAllAppleString; countAllAppleString << countAllApple; textCountAllApple.setString(countAllAppleString.str()); if (countAllApple < 10 && countAllApple > -10) { textCountAllApple.setPosition(view.getCenter().x + 130, view.getCenter().y - 350); } if (countAllApple > 9 || countAllApple < -9) { textCountAllApple.setPosition(view.getCenter().x + 120, view.getCenter().y - 350); } textCountAllApple.setStyle(Text::Bold); window.draw(textCountAllApple); textRepeatGame.setPosition(view.getCenter().x + 25, view.getCenter().y - 150); window.draw(textRepeatGame); [MASK] .setPosition(view.getCenter().x - 40, view.getCenter().y - 100); window.draw( [MASK] ); textRepeatGame.setStyle(Text::Regular); [MASK] .setStyle(Text::Regular); elementMenu = 0; if (IntRect(523, 355, 231, 30).contains(Mouse::getPosition(window))) { textRepeatGame.setStyle(Text::Underlined); elementMenu = 1; } if (IntRect(460, 410, 360, 26).contains(Mouse::getPosition(window))) { [MASK] .setStyle(Text::Underlined); elementMenu = 2; } if (Mouse::isButtonPressed(Mouse::Left)) { return elementMenu; } window.display(); } } int main(){ RenderWindow window(VideoMode(1280, 720), ""Newton [1.0]""); window.setFramerateLimit(100); short elementMenu(2); short countAllApple(0); while (elementMenu != 3) { if (elementMenu == 2) { elementMenu = startMenu(window); } if (elementMenu == 1) { countAllApple = startGame(window, countAllApple); elementMenu = showEndGameMenu(window, countAllApple); } } window.close(); }",textBackToMainMenu 303,"#include #include #include #include #include #include #include #define LORA_SS 18 #define LORA_RST 14 #define LORA_DI0 26 #define BAND 915E6 const char* mqttServer = ""demo.thingsboard.io""; WiFiClient espClient; PubSubClient client(espClient); void reconnect(); void readData() { int packetSize = LoRa.parsePacket(); String data = """"; if(packetSize) { while (LoRa.available()) { data += (char) LoRa.read(); } if(!client.connected()) { reconnect(); } if(client.publish(""v1/devices/me/telemetry"", data.c_str())) { Serial.print(""\nDados Enviados! -> "" + data); } } } void sendDataDashboardTester() { srand(time(NULL)); double mockTemperature = 25.00; double mockAccel = (rand() % (400 - 100+1) + 100); double mockAxisX = (rand() % (20 - 5+1) + 100); double [MASK] = (rand() % (350 - 100+1) + 100); double mockAxisY = (rand() % (1 - (-10)+1) + 100); String PacketTeste = ""{\""nodeID\"":"" + String(1) + "",\""time\"":"" + String(millis()) + "",\""temperature\"":"" + String(mockTemperature) + "",\""accel\"":"" + String(mockAccel) + "",\""axisX\"":"" + String(mockAxisX) + "",\""axisY\"":"" + String(mockAxisY) + "",\""axisZ\"":"" + String( [MASK] ) + ""}""; if(client.publish(""v1/devices/me/telemetry"", PacketTeste.c_str())) { Serial.print(""Dados de teste Enviados""); } delay(10000); } void reconnect() { while (!client.connected()) { Serial.print(""\nBuscando broker...""); if (client.connect(BROKER_CID, BROKER_USER, BROKER_PSWD)) { Serial.println("" OK!""); } else { Serial.print(""Falha ao reconectar: ""); Serial.print(client.state()); delay(5000); } } } void setup() { Serial.begin(115200); client.setServer(mqttServer, 1883); WiFi.begin(WIFI_SSID, WIFI_PASS); while (WiFi.status() != WL_CONNECTED) { Serial.print(""...""); delay(300); } Serial.print(""WiFi Conectado! ""); LoRa.setPins(LORA_SS, LORA_RST, LORA_DI0); if(!LoRa.begin(BAND)) { Serial.print(""Erro ao incializar o Gateway""); while(1); } while(!client.connected()) { Serial.print(""\nBuscando MQTT... ""); if(client.connect(BROKER_CID, BROKER_USER, BROKER_PSWD)) { Serial.print(""Broker MQTT Conectado""); client.subscribe(""v1/devices/me/telemetry""); } else { Serial.print(""fail: ""); Serial.println(client.state()); reconnect(); } } Serial.print(""\nGateway Pronto!\n""); } void loop() { readData(); }",mockAxisZ 304,"const int buttonPin1 = 4; const int buttonPin2 = 5; const int buttonPin3 = 6; const int buttonPin4 = 7; // Button states and debounce variables for Button1 and Button2 int buttonState1 = 0; int lastButtonState1 = 0; int buttonState2 = 0; int lastButtonState2 = 0; unsigned long lastDebounceTime1 = 0; unsigned long lastDebounceTime2 = 0; // Button states and debounce variables for Button3 and Button4 int buttonState3 = 0; int lastButtonState3 = 0; int buttonState4 = 0; int lastButtonState4 = 0; unsigned long lastDebounceTime3 = 0; unsigned long lastDebounceTime4 = 0; unsigned long debounceDelay = 10; // Debounce delay in milliseconds void setup() { // Initialize serial communication Serial.begin(115200); // Ensure this matches the baud rate in Godot. pinMode(buttonPin1, INPUT); pinMode(buttonPin2, INPUT); pinMode(buttonPin3, INPUT); pinMode(buttonPin4, INPUT); } void loop() { // Read the current state of all buttons int reading1 = digitalRead(buttonPin1); int [MASK] = digitalRead(buttonPin2); int reading3 = digitalRead(buttonPin3); int reading4 = digitalRead(buttonPin4); // Handle debouncing for Button 1 if (reading1 != lastButtonState1) { lastDebounceTime1 = millis(); // Reset debounce timer for Button1 } if ( [MASK] != lastButtonState2) { lastDebounceTime2 = millis(); } if (reading3 != lastButtonState3) { lastDebounceTime3 = millis(); } if (reading4 != lastButtonState4) { lastDebounceTime4 = millis(); } // Process Button1 if the debounce delay has passed if ((millis() - lastDebounceTime1) > debounceDelay) { if (reading1 != buttonState1) { buttonState1 = reading1; if (buttonState1 == HIGH) { Serial.println(""Button1Pressed""); // Send signal to Godot } } } if ((millis() - lastDebounceTime2) > debounceDelay) { if ( [MASK] != buttonState2) { buttonState2 = [MASK] ; if (buttonState2 == HIGH) { Serial.println(""Button2Pressed""); } } } if ((millis() - lastDebounceTime3) > debounceDelay) { if (reading3 != buttonState3) { buttonState3 = reading3; if (buttonState3 == HIGH) { Serial.println(""Button3Pressed""); // Send signal to Godot for Player2 } } } if ((millis() - lastDebounceTime4) > debounceDelay) { if (reading4 != buttonState4) { buttonState4 = reading4; if (buttonState4 == HIGH) { Serial.println(""Button4Pressed""); } } } // Save the current button states for the next loop iteration lastButtonState1 = reading1; lastButtonState2 = [MASK] ; lastButtonState3 = reading3; lastButtonState4 = reading4; } ",reading2 305,"// compiler parameter: g++ -O4 name.cpp -lgmpxx -lgmp -pthread -std=c++11 #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; void write_file(const string &str){ FILE *f; string a; f = fopen(""1.txt"",""w""); ofstream fout (""1.txt""); fout << str; fclose(f); } int time_time(){ time_t seconds; seconds = time (NULL); return int(seconds); } void naiti_prostie_menshe(vector &prostie, unsigned long long int n){ vector vsen(n+1); unsigned long int i = 0; // 1 = False // 0 = True unsigned int koren = sqrt(float(n)); unsigned long int p = 2; while(p <= koren){ prostie.push_back(p); for (i=p; i < (n+1); i += p){ vsen[i] = 1; } for (i=p; i < (n+1); i ++){ if (vsen[i] == 0){ p = i; break; } } } for (i = p; i < (n+1); i++){ if (vsen[i] == 0){ prostie.push_back(i); } } } vector slice(vector& v, unsigned int start = 0, int end = -1) { int oldlen = v.size(); int newlen; if (end == -1 or end >= oldlen){ newlen = oldlen-start; } else { newlen = end-start; } vector nv(newlen); for (int i = 0; i < newlen; i++) { nv[i] = v[start+i]; v[start+i] = 0; //bit saves memory } return nv; } void group(vector & iterable, vector>& a, const int count){ int ss = iterable.size() / count; int b = 0; for (int i = 1; i != count; i++){ a.push_back(slice(iterable, b, ss * i)); b = ss * i; } a.push_back(slice(iterable, b)); } void peremnozh(const vector && chisla, vector & otveti, const int thread_n){ mpz_class ss; ss = ""1""; for(int i = 0; i != chisla.size(); i++){ ss = ss * chisla[i]; } otveti[thread_n] = ss; } mpz_class poizvedenie(vector &chisla, int razmer_grupi = 2){ //razmer_grup -- can not be less 2 if(chisla.size() == 0){ mpz_class ss; return ss; } vector> grupi; int kolichestvo_group = chisla.size() / razmer_grupi; if (kolichestvo_group == 0){ kolichestvo_group = 1; } else if(kolichestvo_group > 8096){ kolichestvo_group = 8096; } group(chisla, grupi, kolichestvo_group); chisla.clear(); vector otveti(grupi.size()); vector thread_list(grupi.size()); for(int i = 0; i != grupi.size(); i++){ thread_list[i] = thread (peremnozh, grupi[i], ref(otveti), i); } for(int i = 0; i != thread_list.size(); i++){ thread_list[i].join(); } if(otveti.size() == 1){ cout << ""Zakonchili umnozhati"" << '\n'; return otveti[0]; }else{ grupi.clear(); thread_list.clear(); return poizvedenie(otveti); } } unsigned long long int kagda_zakonchiti(vector &prostie, unsigned long long [MASK] ){ unsigned int c; for (int i = 0; i != prostie.size(); i++){ c = prostie[i].get_ui(); if((c * c) > [MASK] ){ break; } } return c; } mpz_class glav(unsigned long long dokuda){ cout << ""Shitaem primes"" << '\n'; vector prostie; naiti_prostie_menshe(prostie, dokuda); cout << ""zakonchili shitati primes"" << '\n'; cout << ""dobavlyaem list"" << '\n'; unsigned long long int ae = kagda_zakonchiti(prostie, dokuda); for (int i = 0; i != prostie.size(); i++){ unsigned int j = prostie[i].get_ui(); if(ae == j){ break; } unsigned int k = 1; while (true) { k *= j; if(k * j <= dokuda){ prostie.push_back(j); } else{ break; } } } //cout << prostie.size() << '\n'; cout << ""zakinchili dobavlyati list"" << '\n'; cout << ""Umnozhaem"" << '\n'; return poizvedenie(prostie); } int main (){ // 2520 is the smallest number that can be divided by each of the // numbers from 1 to 10 without any remainder. // What is the smallest positive number that is evenly divisible // by all of the numbers from 1 to n? int n = 1000000000; int start_time = time_time(); glav(n); //write_file(glav(n).get_str()); cout << time_time() - start_time <<""\n""; } ",potolok 306,"/* Copyright 2011 * * 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. * * File: BuiltInClasses.cpp * Author: tjoppen * * Created on February 14, 2010, 6:48 PM */ #include #include #include ""BuiltInClasses.h"" #include ""main.h"" using namespace std; const string t = "" ""; // Python indentation step (four spaces) BuiltInClass::BuiltInClass(string name) : Class(FullName(XSL, name), Class::SIMPLE_TYPE) { } BuiltInClass::~BuiltInClass() { } bool BuiltInClass::isBuiltIn() const { return true; } string BuiltInClass::generateAppender() const { throw runtime_error(""generateAppender() called in BuiltInClass""); } string BuiltInClass::generateElementSetter(string memberName, string nodeName, string tabs) const { ostringstream oss; oss << tabs << ""tmp = document.createElement(\"""" << nodeName << ""\"")"" << endl; oss << tabs << ""tmpText = document.createTextNode(unicode("" << memberName << ""))"" << endl; oss << tabs << ""tmp.appendChild(tmpText)"" << endl; oss << tabs << ""node.appendChild(tmp)"" << endl; return oss.str(); } string BuiltInClass::generateAttributeSetter(string memberName, string [MASK] , string tabs) const { ostringstream oss; oss << tabs << ""tmpAttr = document.createAttribute(\"""" << memberName << ""\"")"" << endl; oss << tabs << ""tmpAttr.value = unicode("" << [MASK] << "")"" << endl; oss << tabs << ""node.setAttributeNode(tmpAttr)"" << endl; return oss.str(); } string BuiltInClass::generateParser() const { throw runtime_error(""generateParser() called in BuiltInClass""); } string BuiltInClass::generateMemberSetter(string memberName, string nodeName, string tabs) const { ostringstream oss; oss << tabs << ""if node.firstChild == None:"" << endl; oss << tabs << t << memberName << "" = None"" << endl; oss << tabs << ""else:"" << endl; oss << tabs << t << memberName << "" = ""; string type = getClassname(); if(type == ""int"" || type == ""short"" || type == ""unsignedShort"" || type == ""unsignedInt"" || type == ""byte"" || type == ""unsignedByte"" || type == ""integer"" || type == ""unsignedInteger"") { oss << ""int(node.firstChild.nodeValue)""; } else if(type == ""long"" || type == ""unsignedLong"") { oss << ""long(node.firstChild.nodeValue)""; } else if(type == ""float"" || type == ""double"") { oss << ""float(node.firstChild.nodeValue)""; } else if(type == ""string"") { oss << ""node.firstChild.nodeValue""; } else { oss << ""unicode(node.firstChild.nodeValue)""; } return oss.str(); } ",attributeName 307,"#include ""IO.h"" #include namespace { auto isFinite(glm::vec3 v) -> bool { return std::isfinite(v.x) || std::isfinite(v.y) || std::isfinite(v.z); } auto isFinite(const Triangle& t) -> bool { return isFinite(t[0]) || isFinite(t[1]) || isFinite(t[2]); } } void saveTriangles(std::filesystem::path path, const std::vector& triangles) { if (path.has_parent_path()) create_directories(path.parent_path()); std::ofstream f{path, std::ios::binary}; const char header[80] = ""STL whatever""; f.write(header, sizeof(header)); uint32_t count = static_cast(triangles.size()); f.write(reinterpret_cast(&count), sizeof(count)); const uint16_t [MASK] = 0; for (const auto& t : triangles) { const auto normal = glm::normalize(glm::cross(t[0] - t[1], t[0] - t[2])); if (!isFinite(t)) { count--; continue; } f.write(reinterpret_cast(&normal), sizeof(normal)); f.write(reinterpret_cast(&t), sizeof(t)); f.write(reinterpret_cast(& [MASK] ), sizeof( [MASK] )); } f.seekp(sizeof(header), std::ios::beg); f.write(reinterpret_cast(&count), sizeof(count)); f.close(); } void savePoints(std::filesystem::path path, const std::vector& points) { if (path.has_parent_path()) create_directories(path.parent_path()); std::ofstream f{path, std::ios::binary}; f << ""ply\n""; f << ""format binary_little_endian 1.0\n""; f << ""element vertex "" << points.size() << ""\n""; f << ""property float x\n""; f << ""property float y\n""; f << ""property float z\n""; f << ""end_header\n""; f.write(reinterpret_cast(points.data()), points.size() * sizeof(glm::vec3)); f.close(); } ",attributeCount 308,"#ifdef _WIN32 # include # include # include # pragma comment(lib, ""ws2_32.lib"") # include ""stdint_msvc.h"" #else # define _BSD_SOURCE 1 # define _DEFAULT_SOURCE 1 # include # include # include # include # include # include # define closesocket close #endif #ifndef _cpluslplus # ifndef _WIN32 # include # else # define bool int # endif #endif #include #include #include ""cache/cached_tree.h"" #include #include #include #include #include #include struct sockaddr_in server; struct sockaddr_in m_client; struct sockaddr_in s_client; #include ""micronfs.h"" #include ""rpc_serializer.h"" #ifndef MAP_UNINITIALIZED # define MAP_UNINITIALIZED 0 #endif #define MAX_BUFFER_SIZE 4096 static char recvbuffer[MAX_BUFFER_SIZE]; /// connects to a name on a given port /// returns -1 if it fails int connect_name(const char* hostname, const char* port) { struct addrinfo* addr = 0; int sfd = -1; if (getaddrinfo(hostname, port, 0, &addr) != 0) { perror(""getaddrinfo failed ""); } for (struct addrinfo* rp = addr; rp != NULL; rp = rp->ai_next) { sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (sfd == -1) continue; if (connect(sfd, rp->ai_addr, rp->ai_addrlen) == 0) { break; /* Success */ } } return sfd; } void PushUnixAuthN(RPCSerializer* self) { uint32_t aux_gids[1] = {0}; RPCSerializer_PushUnixAuth(self, 0, """", 0, 0, 1, aux_gids); } #define PORTMAP_PROGRAM 100000 #define PORTMAP_DUMP_PROCEDURE 4 #define PORTMAP_DUMP_GETPORT 3 #define MOUNT_PROGRAM 100005 #define MOUNT_MNT_PROCEDURE 1 #define MOUNT_DUMP_PROCEDURE 2 #define MOUNT_UMNT_PROCEDURE 3 #define MOUNT_EXPORT_PROCEDURE 5 #define NFS_PROGRAM 100003 #define NFS_READ_PROCEDURE 6 #define NFS_WRITE_PROCEDURE 7 #define NFS_CREATE_PROCEDURE 8 #define NFS_MKNOD_PROCEDURE 11 #define NFS_READDIR_PROCEDURE 16 #define NFS_READDIRPLUS_PROCEDURE 17 #define MESSAGE_TYPE_CALL 0 #define PROTO_TCP 6 void InitCache(cache_t* cache) { uint32_t initial_name_storage_capacity = 65536; uint32_t initial_name_nodes_capacity = 4096; uint32_t [MASK] = 16384; uint32_t initial_metadata_nodes = 16384 * 8; uint32_t initial_dir_nodes = 2048; uint32_t initial_toc_capacity = 2048; uint32_t initial_limb_capacity = 16384; uint8_t* cache_memory = (uint8_t*) malloc( sizeof(cache_t) + initial_name_storage_capacity + (initial_name_nodes_capacity * sizeof(name_cache_node_t))); toc_entry_t* toc_mem = (toc_entry_t*) calloc( initial_toc_capacity, sizeof(toc_entry_t)); name_cache_node_t* tree_mem = (name_cache_node_t*) (cache_memory + sizeof(cache_t) + initial_name_storage_capacity); meta_data_entry_t* meta_mem = (meta_data_entry_t*) calloc( initial_metadata_nodes , sizeof(meta_data_entry_t)); cached_dir_t* dirs_mem = (cached_dir_t*)calloc( initial_dir_nodes, sizeof(cached_dir_t)); uint32_t* limbs_mem = (uint32_t*) calloc( initial_limb_capacity, sizeof(uint32_t)); cached_file_t* files_mem = (cached_file_t*) calloc( [MASK] , sizeof(cached_file_t)); cache->toc_entries = toc_mem; cache->root = meta_mem++; cache->toc_size = 0; cache->toc_capacity = initial_toc_capacity; cache->metadata_size = 1; cache->metadata_capacity = initial_metadata_nodes; cache->name_stringtable = (char*)(cache_memory + sizeof(cache_t)); cache->name_stringtable_size = 0; cache->name_stringtable_capacity = initial_name_storage_capacity; cache->name_cache_root = tree_mem; cache->name_cache_node_size = 1; cache->name_cache_node_capacity = initial_name_nodes_capacity; cache->dir_entries = dirs_mem; cache->dir_entries_size = 0; cache->dir_entries_capacity = initial_dir_nodes; cache->file_entries = files_mem; cache->file_entries_size = 0; cache->file_entries_capacity = [MASK] ; cache->limbs = limbs_mem; cache->limbs_size = 0; cache->limbs_capacity = initial_limb_capacity; ResetCache(cache); cache->root->cached_dir = cache->dir_entries + cache->dir_entries_size++; cache->root->cached_dir->fullPath = GetOrAddName(cache, ""/""); } void portmap_nullCall(int sock_fd) { RPCSerializer s = {0}; RPCSerializer_InitCall(&s, PORTMAP_PROGRAM, 2, 0); RPCSerializer_PushNullAuth(&s); RPCSerializer_Finalize(&s); RPCSerializer_Send(&s, sock_fd); } uint16_t portmap_getport(int sock_fd, uint32_t program, uint32_t version_, uint32_t proto) { RPCSerializer s = {0}; RPCSerializer_InitCall(&s, PORTMAP_PROGRAM, 2, PORTMAP_DUMP_GETPORT); RPCSerializer_PushNullAuth(&s); // arguments to getport RPCSerializer_PushU32(&s, program); RPCSerializer_PushU32(&s, version_); RPCSerializer_PushU32(&s, proto); RPCSerializer_PushU32(&s, 0); RPCSerializer_Finalize(&s); RPCSerializer_Send(&s, sock_fd); RPCDeserializer d = {0}; RPCDeserializer_Init(&d, sock_fd); RPCHeader header = RPCDeserializer_RecvHeader(&d); bool accepted = RPCDeserializer_ReadBool(&d); RPCDeserializer_SkipAuth(&d); nfsstat3 status = (nfsstat3)RPCDeserializer_ReadU32(&d); uint32_t port = RPCDeserializer_ReadU32(&d); assert(port <= 0xFFFF); return port; } typedef struct mountlist_t { const char* hostname; const char* directory; struct mountlist_t* next; } mountlist_t; void printFileHandle(const fhandle3* handle) { const uint32_t* ptr = (const uint32_t*) &handle->handle[0]; printf(""fh: %x %x %x %x %x %x %x %x\n"", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7]); } void mountd_umnt(int mountd_fd, const char* dirPath) { RPCSerializer s = {0}; mountlist_t* result = 0; uint32_t mount_dump_xid = RPCSerializer_InitCall(&s, MOUNT_PROGRAM, 3, MOUNT_UMNT_PROCEDURE); RPCSerializer_PushNullAuth(&s); uint32_t dirPathLength = strlen(dirPath); RPCSerializer_PushString(&s, dirPathLength, dirPath); RPCSerializer_Finalize(&s); RPCSerializer_Send(&s, mountd_fd); // not sure if I should issue a read since it's a void proc } fhandle3 mountd_mnt(int mountd_fd, const char* dirPath) { RPCSerializer s = {0}; fhandle3 result = {{0}}; uint32_t mount_dump_xid = RPCSerializer_InitCall(&s, MOUNT_PROGRAM, 3, MOUNT_MNT_PROCEDURE); //RPCSerializer_PushNullAuth(&s); PushUnixAuthN(&s); uint32_t dirPathLength = strlen(dirPath); RPCSerializer_PushString(&s, dirPathLength, dirPath); RPCSerializer_Finalize(&s); RPCSerializer_Send(&s, mountd_fd); RPCDeserializer d = {0}; RPCDeserializer_Init(&d, mountd_fd); RPCDeserializer_RecvHeader(&d); int reply_accepted = RPCDeserializer_ReadBool(&d); RPCDeserializer_SkipAuth(&d); int rpc_accepted = RPCDeserializer_ReadBool(&d); nfsstat3 status = (nfsstat3)RPCDeserializer_ReadU32(&d); result = RPCDeserializer_ReadFileHandle(&d); //TODO we should ready the required auth here .... maybe return result; } mountlist_t* mountd_dump(int mountd_fd) { RPCSerializer s = {0}; mountlist_t* result = 0; uint32_t mount_dump_xid = RPCSerializer_InitCall(&s, MOUNT_PROGRAM, 3, MOUNT_DUMP_PROCEDURE); RPCSerializer_PushNullAuth(&s); RPCSerializer_Finalize(&s); RPCSerializer_Send(&s, mountd_fd); RPCDeserializer d; RPCDeserializer_Init(&d, mountd_fd); RPCHeader header = RPCDeserializer_RecvHeader(&d); bool accepted = RPCDeserializer_ReadBool(&d); RPCDeserializer_SkipAuth(&d); nfsstat3 status = (nfsstat3)RPCDeserializer_ReadU32(&d); // now the actual params come ... static char mountlist_storage[8192]; char* writePtr = mountlist_storage; uint32_t storage_left = sizeof(mountlist_storage); bool hadPrev = 0; if (status == 0) { bool hasNext = RPCDeserializer_ReadBool(&d); mountlist_t* entry = 0; if (hasNext) { result = entry = (mountlist_t*) mountlist_storage; } while(hasNext) { if (hadPrev) { entry->next = (mountlist_t*) writePtr; } entry = (mountlist_t*) writePtr; writePtr += sizeof(mountlist_t); storage_left -= sizeof(mountlist_t); { const uint32_t hlen = RPCDeserializer_ReadU32(&d); assert(storage_left > hlen + 1); entry->hostname = RPCDeserializer_ReadString(&d, &writePtr, hlen); storage_left -= (hlen + 1); } { uint32_t dlen = RPCDeserializer_ReadU32(&d); assert(storage_left > dlen - 1); entry->directory = RPCDeserializer_ReadString(&d, &writePtr, dlen); storage_left -= (dlen + 1); } hasNext = RPCDeserializer_ReadBool(&d); hadPrev = 1; } } else { printf(""Error: %s\n"", nfsstat3_toChars(status)); } return result; } void ReadWcc(RPCDeserializer* self) { wcc_attr pre_op; fattr3 post_op; if (RPCDeserializer_ReadBool(self)) { pre_op.size = RPCDeserializer_ReadU64(self); uint64_t mtime_u64 = RPCDeserializer_ReadU64(self); pre_op.mtime = *(nfstime3*) &mtime_u64; uint64_t ctime_u64 = RPCDeserializer_ReadU64(self); pre_op.ctime = *(nfstime3*)&ctime_u64; } if (RPCDeserializer_ReadBool(self)) { post_op = RPCDeserializer_ReadFileAttribs(self); } } fhandle3 nfs_create(SOCKET nfs_fd, const fhandle3* parentDir, const char* filename, mode3 mode) { fhandle3 result = {0}; RPCSerializer s = {0}; uint32_t create_xid = RPCSerializer_InitCall(&s, NFS_PROGRAM, 3, NFS_CREATE_PROCEDURE); PushUnixAuthN(&s); uint32_t length = fhandle3_length(parentDir); RPCSerializer_PushString(&s, length, (const char*)parentDir); uint32_t fn_length = strlen(filename); RPCSerializer_PushString(&s, fn_length, filename); RPCSerializer_PushU32(&s, GUARDED); // push mode RPCSerializer_PushU32(&s, 1); RPCSerializer_PushU32(&s, mode); RPCSerializer_PushU32(&s, 0); // no uid RPCSerializer_PushU32(&s, 0); // no gid RPCSerializer_PushU32(&s, 0); // no size RPCSerializer_PushU32(&s, 0); // no atime RPCSerializer_PushU32(&s, 0); // no mtime RPCSerializer_Finalize(&s); RPCSerializer_Send(&s, nfs_fd); // ------------------------------------------- RPCDeserializer d = {0}; RPCDeserializer_Init(&d, nfs_fd); RPCHeader header = RPCDeserializer_RecvHeader(&d); assert(header.xid == create_xid); int accepted = RPCDeserializer_ReadBool(&d); RPCDeserializer_SkipAuth(&d); int accept_state = RPCDeserializer_ReadBool(&d); nfsstat3 status = (nfsstat3)RPCDeserializer_ReadU32(&d); if (status != 0) printf(""Status: %s\n"", nfsstat3_toChars(status)); if (status == 0) { if (RPCDeserializer_ReadBool(&d)) { result = RPCDeserializer_ReadFileHandle(&d); } if (RPCDeserializer_ReadBool(&d)) { fattr3 attrs = RPCDeserializer_ReadFileAttribs(&d); } } ReadWcc(&d); } void nfs_remove(SOCKET nfs_fd, fhandle3* dirHandle, const char* filename, uint32_t filename_length) { } fhandle3 nfs_mknod(SOCKET nfs_sock_fd, const fhandle3* parentDir, const char* filename) { fhandle3 result = {0}; RPCSerializer s = {0}; uint32_t mknod_xid = RPCSerializer_InitCall(&s, NFS_PROGRAM, 3, NFS_MKNOD_PROCEDURE); PushUnixAuthN(&s); uint32_t length = fhandle3_length(parentDir); RPCSerializer_PushString(&s, length, (const char*)parentDir); uint32_t fn_length = strlen(filename); RPCSerializer_PushString(&s, fn_length, filename); RPCSerializer_PushU32(&s, GUARDED); // push sattr3 RPCSerializer_PushEmptySattr3(&s); // --------------------------------------------- assert (0); // Not implemented return result; } int64_t nfs_write(SOCKET nfs_fd, const fhandle3* file , const void* data, uint32_t size , uint64_t offset) { RPCSerializer s = {0}; uint32_t write_xid = RPCSerializer_InitCall(&s, NFS_PROGRAM, 3, NFS_WRITE_PROCEDURE); PushUnixAuthN(&s); int length = fhandle3_length(file); RPCSerializer_PushString(&s, length, (const char*)file->handle); RPCSerializer_PushU64(&s, offset); RPCSerializer_PushU32(&s, size); RPCSerializer_PushU32(&s, FILE_SYNC); RPCSerializer_PushString(&s, size, (const char*)data); RPCSerializer_Finalize(&s); RPCSerializer_Send(&s, nfs_fd); // ---------------------------------------------- RPCDeserializer d = {0}; RPCDeserializer_Init(&d, nfs_fd); RPCHeader header = RPCDeserializer_RecvHeader(&d); assert(header.xid == write_xid); int accepted = RPCDeserializer_ReadBool(&d); RPCDeserializer_SkipAuth(&d); int accept_state = RPCDeserializer_ReadBool(&d); nfsstat3 status = (nfsstat3)RPCDeserializer_ReadU32(&d); if (status != 0) printf(""Status: %s\n"", nfsstat3_toChars(status)); // ----------------------------------------------------- if (status) { fprintf(stderr, ""Error [%s] while reading '%s'\n"" , nfsstat3_toChars(status) , """" /*LookupNameInCache(file)*/ ); return -1; } if (status == 0) { ReadWcc(&d); uint32_t count = RPCDeserializer_ReadU32(&d); stable_how comitted = (stable_how) RPCDeserializer_ReadU32(&d); uint64_t verf = RPCDeserializer_ReadU64(&d); return count; } } int64_t nfs_read(SOCKET nfs_fd, const fhandle3* file , void* data, uint32_t size , uint64_t offset) { RPCSerializer s = {0}; uint32_t read_xid = RPCSerializer_InitCall(&s, NFS_PROGRAM, 3, NFS_READ_PROCEDURE); PushUnixAuthN(&s); int length = fhandle3_length(file); RPCSerializer_PushString(&s, length, (const char*)file->handle); RPCSerializer_PushU64(&s, offset); RPCSerializer_PushU32(&s, size); RPCSerializer_Finalize(&s); RPCSerializer_Send(&s, nfs_fd); // ---------------------------------------------- RPCDeserializer d = {0}; RPCDeserializer_Init(&d, nfs_fd); RPCHeader header = RPCDeserializer_RecvHeader(&d); assert(header.xid == read_xid); int accepted = RPCDeserializer_ReadBool(&d); RPCDeserializer_SkipAuth(&d); int accept_state = RPCDeserializer_ReadBool(&d); nfsstat3 status = (nfsstat3)RPCDeserializer_ReadU32(&d); if (status != 0) printf(""Status: %s\n"", nfsstat3_toChars(status)); // ----------------------------------------------------- if (status) { fprintf(stderr, ""Error [%s] while reading '%s'\n"" , nfsstat3_toChars(status) , """" /*LookupNameInCache(file)*/ ); return -1; } //TODO FIXME make sure size if less than rtMax form FSINFO Query! if (RPCDeserializer_ReadU32(&d) != 0) { (void) RPCDeserializer_ReadFileAttribs(&d); } uint32_t result_count = RPCDeserializer_ReadU32(&d); int eof = RPCDeserializer_ReadU32(&d) != 0; uint32_t arraySize = RPCDeserializer_ReadU32(&d); uint32_t bufferLeft = RPCDeserializer_BufferLeft(&d); uint32_t readAlready = 0; while(bufferLeft < arraySize - readAlready) { // RPCDeserializer_EnsureSize(&d, bufferLeft); memcpy((uint8_t*)data + readAlready, d.ReadPtr, bufferLeft); readAlready += bufferLeft; d.ReadPtr += (ALIGN4(bufferLeft) / 4); RPCDeserializer_EnsureSize(&d, 4); bufferLeft = RPCDeserializer_BufferLeft(&d); } if (bufferLeft >= arraySize - readAlready) { memcpy((uint8_t*)data + readAlready, d.ReadPtr, bufferLeft); } else { assert(0); while (arraySize) { // RPCDeserializer_EnsureSize(&d, ) } } return result_count; } int nfs_readdirplus(SOCKET nfs_fd, const fhandle3* dir , uint64_t *cookie, uint64_t *cookieverf , int (*fileIter)(const char* fName, const fhandle3* handle, const fattr3* attribs, void* userData) , void* userData) { RPCSerializer s = {0}; mountlist_t* result = 0; uint32_t readdirplus_xid = RPCSerializer_InitCall(&s, NFS_PROGRAM, 3, NFS_READDIRPLUS_PROCEDURE); PushUnixAuthN(&s); int length = fhandle3_length(dir); RPCSerializer_PushString(&s, length, (const char*)dir->handle); uint32_t cookie_hi = *cookie >> 32; uint32_t cookie_lw = *cookie & 0xFFFFFFFF; uint32_t cookie_verif_hi = *cookieverf >> 32; uint32_t cookie_verif_lw = *cookieverf & 0xFFFFFFFF; RPCSerializer_PushU32(&s, cookie_hi); RPCSerializer_PushU32(&s, cookie_lw); RPCSerializer_PushU32(&s, cookie_verif_hi); RPCSerializer_PushU32(&s, cookie_verif_lw); RPCSerializer_PushU32(&s, 4096); // max size of attribs ... it's recommeded that that's shorter than max size RPCSerializer_PushU32(&s, 32768); // max size of result structure RPCSerializer_Finalize(&s); RPCSerializer_Send(&s, nfs_fd); // -------------------------------------------------------------- RPCDeserializer d = {0}; RPCDeserializer_Init(&d, nfs_fd); RPCHeader header = RPCDeserializer_RecvHeader(&d); assert(header.xid == readdirplus_xid); int accepted = RPCDeserializer_ReadBool(&d); //16 RPCDeserializer_SkipAuth(&d); int accept_state = RPCDeserializer_ReadBool(&d); nfsstat3 status = (nfsstat3)RPCDeserializer_ReadU32(&d); if (status != 0) printf(""Status: %s\n"", nfsstat3_toChars(status)); // ------------------------------------------------------------------- int hasAttrs = RPCDeserializer_ReadBool(&d); if (hasAttrs) { RPCDeserializer_ReadFileAttribs(&d); } *cookieverf = RPCDeserializer_ReadU64(&d); cookie3 lastCookie; // --------------------------------------------------------------------- int hasNext = RPCDeserializer_ReadBool(&d); int shouldContinueReading; while (hasNext) { RPCDeserializer_EnsureSize(&d, 12); char name_buffer[1024]; char* namePtr = name_buffer; uint64_t fileid = RPCDeserializer_ReadU64(&d); uint32_t name_length = RPCDeserializer_ReadU32(&d); // the name might be longer than our buffer can hold RPCDeserializer_EnsureSize(&d, ALIGN4(name_length)); const char* name = RPCDeserializer_ReadString(&d, &namePtr, name_length); uint32_t afterNameBufferLeft = RPCDeserializer_BufferLeft(&d); RPCDeserializer_EnsureSize(&d, 12); lastCookie = RPCDeserializer_ReadU64(&d); const fattr3* attribsPtr = 0; uint32_t bufferLeftBeforeAttribs; if (RPCDeserializer_ReadBool(&d)) { bufferLeftBeforeAttribs = RPCDeserializer_BufferLeft(&d); const fattr3 attribs = RPCDeserializer_ReadFileAttribs(&d); attribsPtr = &attribs; } const fhandle3* handlePtr = 0; RPCDeserializer_EnsureSize(&d, 4); if (RPCDeserializer_ReadBool(&d)) { const fhandle3 handle = RPCDeserializer_ReadFileHandle(&d); handlePtr = &handle; } if (!fileIter(name, handlePtr, attribsPtr, userData)) { *cookie = lastCookie; shouldContinueReading = 0; // Flush out recv queue; while(((int)d.FragmentSizeLeft) > 0) { (*(int8_t**)&d.ReadPtr) += RPCDeserializer_BufferLeft(&d); assert(RPCDeserializer_BufferLeft(&d) == 0); int maxQuerySize = d.MaxBuffer; if(d.FragmentSizeLeft < maxQuerySize) maxQuerySize = d.FragmentSizeLeft; RPCDeserializer_EnsureSize(&d, maxQuerySize); } goto Lreturn; } RPCDeserializer_EnsureSize(&d, 4); hasNext = RPCDeserializer_ReadBool(&d); } // printf(""Writing lastCookie into ptr""); *cookie = lastCookie; RPCDeserializer_EnsureSize(&d, 4); shouldContinueReading = !RPCDeserializer_ReadBool(&d); Lreturn: return shouldContinueReading; } int nfs_readdir(int nfs_fd, const fhandle3* dir , uint64_t *cookie, uint64_t *cookieverf , int (*dirIter)(const char* fName, uint64_t fileId) ) { RPCSerializer s = {0}; mountlist_t* result = 0; uint32_t readdir_xid = RPCSerializer_InitCall(&s, NFS_PROGRAM, 3, NFS_READDIR_PROCEDURE); PushUnixAuthN(&s); int length = fhandle3_length(dir); RPCSerializer_PushString(&s, length, (const char*)dir->handle); uint32_t cookie_hi = *cookie >> 32; uint32_t cookie_lw = *cookie & 0xFFFFFFFF; uint32_t cookie_verif_hi = *cookieverf >> 32; uint32_t cookie_verif_lw = *cookieverf & 0xFFFFFFFF; RPCSerializer_PushU32(&s, cookie_hi); RPCSerializer_PushU32(&s, cookie_lw); RPCSerializer_PushU32(&s, cookie_verif_hi); RPCSerializer_PushU32(&s, cookie_verif_lw); RPCSerializer_PushU32(&s, 2048); // max size of result structure RPCSerializer_Finalize(&s); RPCSerializer_Send(&s, nfs_fd); RPCDeserializer d; RPCDeserializer_Init(&d, nfs_fd); const RPCHeader header = RPCDeserializer_RecvHeader(&d); int accepted = RPCDeserializer_ReadBool(&d); //16 RPCDeserializer_SkipAuth(&d); int accept_state = RPCDeserializer_ReadBool(&d); nfsstat3 status = (nfsstat3)RPCDeserializer_ReadU32(&d); if (status != 0) printf(""Status: %s\n"", nfsstat3_toChars(status)); bool hasAttrs = RPCDeserializer_ReadBool(&d); if (hasAttrs) { RPCDeserializer_ReadFileAttribs(&d); } *cookieverf = RPCDeserializer_ReadU64(&d); cookie3 lastCookie; for(;;) { bool hasNext = RPCDeserializer_ReadBool(&d); if (!hasNext) break; fileid3 fileId = RPCDeserializer_ReadU64(&d); uint32_t name_length = RPCDeserializer_ReadU32(&d); char str_buf[1024]; char* writePtr = str_buf; const char* fname = RPCDeserializer_ReadString(&d, &writePtr, name_length); lastCookie = RPCDeserializer_ReadU64(&d); if (!dirIter(fname, fileId)) break; } bool wasLastList = RPCDeserializer_ReadBool(&d); return !wasLastList; // printf(""%x %x %x %x"", *readPtr++, *readPtr++, *readPtr++, *readPtr++); } #ifndef _WIN32 # define INVALID_SOCKET -1 #endif struct search_dir_t { const char* name; fhandle3 result_handle; }; int searchDir_cb(const char* fName, const fhandle3* handle, const fattr3* attribs, void* userData) { struct search_dir_t *search_req = (struct search_dir_t*) userData; // printf(""name: %s [%d] {%s}\n"", fName, attribs->size, ftype3_toChars(attribs->type)); if (0 == strcmp(search_req->name, fName)) { assert(handle); search_req->result_handle = *handle; return 0; } return 1; } typedef struct populate_cache_cb_args_t { cache_t* cache; meta_data_entry_t* parentDir; } populate_cache_cb_args_t; int populateCache_cb(const char* fName, const fhandle3* handle, const fattr3* attribs, void* userData) { populate_cache_cb_args_t* args = (populate_cache_cb_args_t*) userData; cache_t* cache = args->cache; meta_data_entry_t* parentDir = args->parentDir; const uint32_t len = strlen(fName); meta_data_entry_t* entry = 0; if (attribs) { if (attribs->type == NF3DIR) { if (!parentDir->cached_dir) { parentDir->cached_dir = cache->dir_entries + cache->dir_entries_size++; } entry = GetOrCreateSubdirectory(cache, parentDir->cached_dir, fName, len); if ( (fName[0] != '.' && fName[1] != '\0') && (fName[0] != '.' && fName[1] != '.' && fName[2] != '\0') ) { // printf(""reading dir: %s\n"", fName); uint64_t cookie = 0; uint64_t verifier = 0; populate_cache_cb_args_t newArgs = { args->cache, entry }; SOCKET newSock = connect_name(""192.168.178.26"", ""2049""); nfs_readdirplus(newSock, handle, &cookie, &verifier , populateCache_cb, &newArgs); closesocket(newSock); } } else if (attribs->type == NF3REG) { entry = CreateFileEntry(cache, parentDir, fName, len); entry->cached_file->size = attribs->size; } else { printf(""Unexpected type: %s on file: %s\n"", ftype3_toChars(attribs->type), fName); return 1; } } else { printf(""No attribs for: %s\n"", fName); } if (handle) { entry->handle = handleToPtr(cache, handle); } return 1; } uint32_t handleSum(const fhandle3* handle) { uint32_t sum = 0; for(int i = 0; i < fhandle3_length(handle); i++) { sum += handle->handle[i]; } return sum; } ",initial_files_capacity 309,"/** * Eggs.SQLite * * Copyright , Fusion Fenix 2012 * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * * Library home page: http://github.com/eggs-cpp/eggs-sqlite */ #ifndef EGGS_SQLITE_ERROR_HPP #define EGGS_SQLITE_ERROR_HPP #include #include #include #include namespace eggs { namespace sqlite { struct result_code { enum enum_type { ok = SQLITE_OK /* Successful result */ , error = SQLITE_ERROR /* SQL error or missing database */ , internal = SQLITE_INTERNAL /* Internal logic error in SQLite */ , perm = SQLITE_PERM /* Access permission denied */ , abort = SQLITE_ABORT /* Callback routine requested an abort */ , busy = SQLITE_BUSY /* The database file is locked */ , locked = SQLITE_LOCKED /* A table in the database is locked */ , no_mem = SQLITE_NOMEM /* A malloc() failed */ , read_only = SQLITE_READONLY /* Attempt to write a readonly database */ , interrupt = SQLITE_INTERRUPT /* Operation terminated by sqlite3_interrupt()*/ , io_error = SQLITE_IOERR /* Some kind of disk I/O error occurred */ , corrupt = SQLITE_CORRUPT /* The database disk image is malformed */ , not_found = SQLITE_NOTFOUND /* Unknown opcode in sqlite3_file_control() */ , full = SQLITE_FULL /* Insertion failed because database is full */ , cant_open = SQLITE_CANTOPEN /* Unable to open the database file */ , protocol = SQLITE_PROTOCOL /* Database lock protocol error */ , empty = SQLITE_EMPTY /* Database is empty */ , schema = SQLITE_SCHEMA /* The database schema changed */ , too_big = SQLITE_TOOBIG /* String or BLOB exceeds size limit */ , contraint = SQLITE_CONSTRAINT /* Abort due to constraint violation */ , mismatch = SQLITE_MISMATCH /* Data type mismatch */ , misuse = SQLITE_MISUSE /* Library used incorrectly */ , no_lfs = SQLITE_NOLFS /* Uses OS features not supported on host */ , auth = SQLITE_AUTH /* Authorization denied */ , format = SQLITE_FORMAT /* Auxiliary database format error */ , range = SQLITE_RANGE /* 2nd parameter to sqlite3_bind out of range */ , not_a_db = SQLITE_NOTADB /* File opened that is not a database file */ , row = SQLITE_ROW /* sqlite3_step() has another row ready */ , done = SQLITE_DONE /* sqlite3_step() has finished executing */ }; }; namespace detail { class sqlite_category_impl : public boost::system::error_category { public: virtual char const* name() const { return ""sqlite""; } virtual std::string message( int error_code ) const { switch ( error_code ) { case result_code::ok: return ""OK""; case result_code::error: return ""SQL error or missing database""; case result_code::internal: return ""Internal logic error in SQLite""; case result_code::perm: return ""Access permission denied""; case result_code::abort: return ""Callback routine requested an abort""; case result_code::busy: return ""The database file is locked""; case result_code::locked: return ""A table in the database is locked""; case result_code::no_mem: return ""A malloc() failed""; case result_code::read_only: return ""Attempt to write a readonly database""; case result_code::interrupt: return ""Operation terminated by sqlite3_interrupt()""; case result_code::io_error: return ""Some kind of disk I/O error occurred""; case result_code::corrupt: return ""The database disk image is malformed""; case result_code::not_found: return ""Unknown opcode in sqlite3_file_control()""; case result_code::full: return ""Insertion failed because database is full""; case result_code::cant_open: return ""Unable to open the database file""; case result_code::protocol: return ""Database lock protocol error""; case result_code::empty: return ""Database is empty""; case result_code::schema: return ""The database schema changed""; case result_code::too_big: return ""String or BLOB exceeds size limit""; case result_code::contraint: return ""Abort due to constraint violation""; case result_code::mismatch: return ""Data type mismatch""; case result_code::misuse: return ""Library used incorrectly""; case result_code::no_lfs: return ""Uses OS features not supported on host""; case result_code::auth: return ""Authorization denied""; case result_code::format: return ""Auxiliary database format error""; case result_code::range: return ""2nd parameter to sqlite3_bind out of range""; case result_code::not_a_db: return ""File opened that is not a database file""; case result_code::row: return ""sqlite3_step() has another row ready""; case result_code::done: return ""sqlite3_step() has finished executing""; default: return ""Unknown SQLite error""; } } }; } // namespace detail inline boost::system::error_category const& sqlite_category() { static detail::sqlite_category_impl [MASK] ; return [MASK] ; } inline boost::system::error_code make_error_code( result_code::enum_type error ) { return boost::system::error_code( static_cast< int >( error ) , sqlite_category() ); } inline boost::system::error_condition make_error_condition( result_code::enum_type error ) { return boost::system::error_condition( static_cast< int >( error ) , sqlite_category() ); } class sqlite_error : public boost::system::system_error { public: explicit sqlite_error( int result_code ) : boost::system::system_error( boost::system::error_code( result_code , sqlite_category() ) ) {} }; class sqlite_syntax_error : public sqlite_error { public: explicit sqlite_syntax_error( sqlite3* db_handle = 0 ) : sqlite_error( result_code::error ) , _message( db_handle != 0 ? sqlite3_errmsg( db_handle ) : 0 ) {} char const* message() const { return _message.c_str(); } char const* what() const { if( _what.empty() ) { try { _what = sqlite_error::what(); if( !_what.empty() ) _what += "": ""; _what += _message; } catch( ... ) { return sqlite_error::what(); } } return _what.c_str(); } private: std::string _message; mutable std::string _what; }; } } // namespace eggs::sqlite namespace boost { namespace system { template<> struct is_error_code_enum< eggs::sqlite::result_code::enum_type > { static const bool value = true; }; } } // namespace boost::system #endif /*EGGS_SQLITE_ERROR_HPP*/ ",category_instance 310,"#include #include #include // Replace these with your WiFi and MQTT credentials const char* ssid = ""Seline""; const char* password = """"; const char* mqtt_server = ""172.16.31.10""; const int mqtt_port = 1883; const char* mqtt_topic_temperature = ""DT/temperature""; const char* mqtt_topic_humidity = ""DT/humidity""; const char* mqtt_topic_gas = ""MQ/gas""; const int MQ2_PIN = A0; // Connect the MQ2 sensor analog output to A0 const int DHT_PIN = D2; // Connect DHT11 data pin to D2 DHT dht(DHT_PIN, DHT11); WiFiClient espClient; PubSubClient client(espClient); void setup() { Serial.begin(115200); delay(10); pinMode(DHT_PIN, INPUT); dht.begin(); connectToWiFi(); client.setServer(mqtt_server, mqtt_port); } void connectToWiFi() { Serial.println(""Connecting to WiFi...""); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println(""Connecting to WiFi...""); } Serial.println(""Connected to WiFi""); } void reconnect() { while (!client.connected()) { Serial.println(""Attempting MQTT connection...""); if (client.connect(""arduino-client"")) { Serial.println(""Connected to MQTT server""); } else { Serial.print(""Failed to connect to MQTT server, rc=""); Serial.print(client.state()); Serial.println("" Retrying in 5 seconds...""); delay(5000); } } } void loop() { if (!client.connected()) { reconnect(); } float temperature = dht.readTemperature(); float humidity = dht.readHumidity(); int [MASK] = analogRead(MQ2_PIN); if (isnan(temperature) || isnan(humidity)) { Serial.println(""Failed to read data from DHT sensor""); delay(2000); return; } Serial.print(""Temperature: ""); Serial.println(temperature); Serial.print(""Humidity: ""); Serial.println(humidity); Serial.print(""Gas Value: ""); Serial.println( [MASK] ); char temperatureStr[8]; char humidityStr[8]; char gasStr[8]; dtostrf(temperature, 6, 2, temperatureStr); dtostrf(humidity, 6, 2, humidityStr); itoa( [MASK] , gasStr, 10); client.publish(mqtt_topic_temperature, temperatureStr); client.publish(mqtt_topic_humidity, humidityStr); client.publish(mqtt_topic_gas, gasStr); delay(1200000); // Publish data every 20 min }",gasValue 311,"#include ""donewdialog.h"" #include ""ui_donewdialog.h"" DoNewDialog::DoNewDialog(QWidget *parent) : QDialog(parent), ui(new Ui::DoNewDialog) { ui->setupUi(this); backColor=Qt::white; } DoNewDialog::~DoNewDialog() { delete ui; } double DoNewDialog::getWidth() { return ui->widthSpinBox->text().toDouble(); } double DoNewDialog::getHeight() { return ui->heightSpinBox->text().toDouble(); } QColor DoNewDialog::getBackColor() { return backColor; } void DoNewDialog::on_toolButton_clicked() { //创建颜色对话框 QColor [MASK] =QColorDialog::getColor(); if( [MASK] .isValid())//可用颜色 { backColor = [MASK] ; //调色 QPalette palette = ui->textBrowser->palette(); palette.setColor(QPalette::Base,backColor);//设置颜色 ui->textBrowser->setPalette(palette);//设置textBrower中颜色 update(); } } ",newColor 312,"// // Created by 李卫东 on 2019-02-18. // #include #include #include ""appbase/application.hpp"" #include ""hb/log_plugin/log_plugin.h"" #include ""hb/qdii_monitor_plugin/qdii_monitor_plugin.h"" using namespace appbase; using namespace hb::plugin; int main(int argc, char **argv) { auto [MASK] = boost::filesystem::initial_path(); app().set_default_config_dir( [MASK] / ""config""); app().set_default_data_dir( [MASK] / ""data""); // app(). if (!app().initialize(argc, argv)) return 1; printf(""app version %s\n"", app().version_string().c_str()); printf(""app config directory is %s\n"", app().config_dir().c_str()); printf(""app using config file %s\n"", app().full_config_file_path().string().c_str()); printf(""app using log config file %s\n"", app().get_logging_conf().string().c_str()); printf(""app data directory is %s\n"", app().data_dir().string().c_str()); app().startup(); app().exec(); return 0; }",exePath 313," #include ""PlayerController_InGame.h"" #include ""EnhancedInputSubsystems.h"" #include ""EnhancedInputComponent.h"" #include ""Logging/LogMacros.h"" DEFINE_LOG_CATEGORY(TEST); APlayerController_InGame::APlayerController_InGame() { } void APlayerController_InGame::BeginPlay() { Super::BeginPlay(); FInputModeGameOnly InputMode; SetInputMode(InputMode); bShowMouseCursor = true; if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem(GetLocalPlayer())) { Subsystem->AddMappingContext(DefaultMappingContext, 0); } } void APlayerController_InGame::Possess(APawn* InPawn) { Super::Possess(InPawn); } void APlayerController_InGame::SetupInputComponent() { Super::SetupInputComponent(); // Add Input Mapping Context if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem(GetLocalPlayer())) { Subsystem->AddMappingContext(DefaultMappingContext, 0); } if (UEnhancedInputComponent* EnhancedInputComponent = Cast(InputComponent)) { EnhancedInputComponent->BindAction(MouseMoving, ETriggerEvent::Triggered, this, &APlayerController_InGame::HandleMouseMoving); EnhancedInputComponent->BindAction(MouseClick, ETriggerEvent::Completed, this, &APlayerController_InGame::HandleMouseClick); } } void APlayerController_InGame::HandleMouseMoving(const FInputActionValue& Value) { FVector2D [MASK] = Value.Get(); AddYawInput( [MASK] .X); AddPitchInput( [MASK] .Y); } void APlayerController_InGame::HandleMouseClick(const FInputActionValue& Value) { } ",Delta 314,"#include using namespace std; /************************************************************************************************************* * * Link : https://practice.geeksforgeeks.org/problems/max-rectangle/1 * Description: * Given a binary matrix. * Find the maximum area of a rectangle formed only of 1s in the given matrix. * Expected Time Complexity : O(n*m) * Expected Auixiliary Space : O(m) * Resources: * https://www.geeksforgeeks.org/maximum-size-rectangle-binary-sub-matrix-1s/ * https://leetcode.com/problems/maximal-square/solution/# * *************************************************************************************************************/ #define si(x) scanf(""%d"", &x) #define sll(x) scanf(""%lld"", &x) #define ss(s) getline(cin, s) #define pi(x) printf(""%d\n"", x) #define pll(x) printf(""%lld\n"", x) #define ps(s) cout << s << ""\n"" #define fo(i, n) for (int i = 0; i < n; i++) // #define fo(i, k, n) for (int i = k; k < n ? i < n : i >= n; k < n ? i++ : i--) #define ll long long #define deb(x) cout << #x << ""="" << x << ""\n"" #define pb push_back #define mp make_pair #define f first #define s second #define all(x) x.begin(), x.end() #define clr(x) memset(x, 0, sizeof(x)) #define sortall(x) sort(all(x)) #define tr(a, it) for (auto it = a.begin(); it != a.end(); it++) #define present(c, x) (c.find(x) != c.end()) #define cpresent(c, x) (find(all(c), x) != c.end()) typedef pair pii; typedef pair pll; typedef vector vi; typedef vector vl; typedef vector vs; typedef vector vpii; typedef vector vpll; typedef vector vvi; typedef vector vvl; int maxHist(int row[], int n) { stack result; int top_val, [MASK] {0}, area{0}; int i{0}; while (i < n) { if (result.empty() || row[result.top()] <= row[i]) result.push(i++); else { top_val = row[result.top()]; result.pop(); area = top_val * i; if (!result.empty()) area = top_val * (i - result.top() - 1); [MASK] = max(area, [MASK] ); } } while (!result.empty()) { top_val = row[result.top()]; result.pop(); area = top_val * i; if (!result.empty()) area = top_val * (i - result.top() - 1); [MASK] = max(area, [MASK] ); } return [MASK] ; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); int t{0}; si(t); while (t--) { int m{0}, n{0}; si(m); si(n); int arr[m][n]; fo(i, m) { fo(j, n) { si(arr[i][j]); } } int result = maxHist(arr[0], n); for (int i = 1; i < m; i++) { for (int j = 0; j < n; j++) { if (arr[i][j] == 1) { arr[i][j] += arr[i - 1][j]; } } result = max(result, maxHist(arr[i], n)); } ps(result); } return 0; }",max_area 315,"#include #include #include #include #include #include #include #include #include #include #include #include static constexpr auto USAGE = R""(C++ Weekly Game. Usage: game [options] Options: -h --help Show this screen. --width=WIDTH Scaling width in pixels [default: 1024] --height=HEIGHT Scaling height in pixels [default: 768] --scale=SCALE Scaling factor [default: 2] )""; int main(int argc, const char **argv) { std::map args = docopt::docopt(USAGE, { std::next(argv), std::next(argv, argc) }, true);// version string const auto width = args[""--width""].asLong(); const auto height = args[""--height""].asLong(); const auto scale = args[""--scale""].asLong(); if (width < 0 || height < 0 || scale < 1 || scale > 5) { spdlog::error(""Command line options are outside reasonable range!""); for (const auto &arg : args) { if (arg.second.isString()) { spdlog::info(""Parameter set: {}: {}"", arg.first, arg.second.asString()); } } abort(); } // Use the default logger (stdout, multi-threaded, colored) spdlog::info(""Hello, {}!"", ""World""); sf::RenderWindow window(sf::VideoMode(static_cast(width), static_cast(height)), ""ImGui + SFML = <3""); window.setFramerateLimit(60); ImGui::SFML::Init(window); const auto scale_factor = static_cast(scale); ImGui::GetStyle().ScaleAllSizes(scale_factor); ImGui::GetIO().FontGlobalScale = scale_factor; sf::CircleShape shape(100.F); shape.setFillColor(sf::Color::Green); constexpr std::array steps = { ""The Plan"", ""Getting Started"", ""Finding Errors As Soon As Possible"", ""Handling Command Line Parameters"", ""Reading SFML Input States"", ""Managing Game State"", ""Making the Game Testable"", ""Making Game State Allocator Aware"", ""Add Logging to Game Engine"", ""Draw A Game Map"", ""Dialog Trees"", ""Porting from SFML to SDL"" }; std::array states{}; sf::Clock [MASK] ; while (window.isOpen()) { sf::Event event{}; while (window.pollEvent(event)) { ImGui::SFML::ProcessEvent(event); if (event.type == sf::Event::Closed) { window.close(); } } ImGui::SFML::Update(window, [MASK] .restart()); ImGui::Begin(""The Plan""); std::size_t index = 0; for (const auto &step : steps) { ImGui::Checkbox( fmt::format(""{} : {}"", index, step).c_str(), &states.at(index)); ++index; } ImGui::End(); window.clear(); window.draw(shape); ImGui::SFML::Render(window); window.display(); } ImGui::SFML::Shutdown(); return 0; } ",deltaClock 316," #include ""AppComponent.hpp"" #include ""DatabaseComponent.hpp"" #include ""ServiceComponent.hpp"" #include ""controller/PasteController.hpp"" #include ""oatpp/network/Server.hpp"" #include void run(const oatpp::base::CommandLineArguments &args) { AppComponent appComponent(args); ServiceComponent [MASK] ; DatabaseComponent databaseComponent; /* create ApiControllers and add endpoints to router */ auto router = [MASK] .httpRouter.getObject(); router->addController(PasteController::createShared()); /* create server */ oatpp::network::Server server( [MASK] .serverConnectionProvider.getObject(), [MASK] .serverConnectionHandler.getObject()); OATPP_LOGD(""Server"", ""Running on port %s..."", [MASK] .serverConnectionProvider.getObject() ->getProperty(""port"") .toString() ->c_str()); server.run(); } int main(int argc, const char *argv[]) { oatpp::base::Environment::init(); run(oatpp::base::CommandLineArguments(argc, argv)); oatpp::base::Environment::destroy(); return 0; } ",serviceComponent 317,"#include ""GameLayer.h"" #include ""Hero.h"" #include ""PlaneEnemy.h"" #include ""CombatManager.h"" #include ""Bullet.h"" GameLayer::GameLayer() : m_pHero(NULL), m_nKeyPressed(0), m_bIsPressed(false), m_nbgSpeed(1) { } GameLayer::~GameLayer() { } bool GameLayer::init() { if (!Layer::init()) { return false; } m_pHero = Hero::create(); m_pHero->setPosition(Director::getInstance()->getVisibleSize().width / 2, 50); addChild(m_pHero, 2); m_pHero->SetLayer(this); GetCombatManager()->SetRunGameLayer(this); //在基类场景增加键盘按键移动飞机和飞机射出子弹的控制 auto keyboardEventListener = EventListenerKeyboard::create(); keyboardEventListener->onKeyPressed = CC_CALLBACK_2(GameLayer::onKeyPressed, this); keyboardEventListener->onKeyReleased = CC_CALLBACK_2(GameLayer::onKeyReleased, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardEventListener, m_pHero); return true; } void GameLayer::Update(float dt) { UpdateHero(dt); UpdateEnemy(dt); UpdateBullet(dt); ProductEnemy(dt); } void GameLayer::UpdateHero(float dt) { m_pHero->Update(dt); } void GameLayer::UpdateEnemy(float dt) { for (auto it = m_enemyList.begin(); it != m_enemyList.end(); /*++it*/) { if ((*it)->IsDeath() || !IsInMap(**it)) { (*it)->removeFromParent(); m_enemyList.erase(it++); } else { (*it)->Update(dt); ++it; } } } void GameLayer::UpdateBullet(float dt) { // m_heroBulletList; for (auto it = m_heroBulletList.begin(); it != m_heroBulletList.end(); /*++it*/) { for (auto enemy = m_enemyList.begin(); enemy != m_enemyList.end(); ++enemy) { if (!(*enemy)->IsDeath() || !IsInMap(**it)) { if ((*it)->HitTest(*enemy, dt)) { break; } } } // (*it)->Update(dt); ++it; } for (auto it = m_heroBulletList.begin(); it != m_heroBulletList.end(); /*++it*/) { if ((*it)->IsDeath() || !IsInMap(**it)) { (*it)->removeFromParent(); m_heroBulletList.erase(it++); } else { (*it)->Update(dt); ++it; } } // m_enemyBulletList; for (auto it = m_enemyBulletList.begin(); it != m_enemyBulletList.end(); ++it) { (*it)->HitTest(m_pHero, dt); } for (auto it = m_enemyBulletList.begin(); it != m_enemyBulletList.end(); /*++it*/) { if ((*it)->IsDeath() || !IsInMap (**it)) { (*it)->removeFromParent(); m_enemyBulletList.erase(it++); } else { // (*it)->HitTest(m_pHero, dt); (*it)->Update(dt); ++it; } } } void GameLayer::ProductEnemy(float dt) { if (m_enemyList.empty()) { AirPlane* pAP = PlaneEnemy::create(); pAP->setPosition(Director::getInstance()->getVisibleSize().width / 2, 300); addChild(pAP, 1, ""enemy""); pAP->SetLayer(this); m_enemyList.push_back(pAP); } } bool GameLayer::IsInMap(const SceneNode& node) { static Size size = Director::getInstance()->getVisibleSize(); Rect rect = node.getTextureRect(); Point p = node.getPosition(); rect.origin = p; if (rect.getMaxX () < 0 || rect.getMinX () > size.width || rect.getMinY() > size.height || rect.getMaxY () < 0) { return false; } return true; } void GameLayer::AddHeroBullet(Bullet* pB) { this->addChild(pB, 3); this->m_heroBulletList.push_back(pB); } void GameLayer::AddEnemyBullet(Bullet* pB) { this->addChild(pB, 3); this->m_enemyBulletList.push_back(pB); } // 键盘触摸回调事件 void GameLayer::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event) { if (keyCode == EventKeyboard::KeyCode::KEY_LEFT_ARROW || keyCode == EventKeyboard::KeyCode::KEY_UP_ARROW || keyCode == EventKeyboard::KeyCode::KEY_RIGHT_ARROW || keyCode == EventKeyboard::KeyCode::KEY_DOWN_ARROW || keyCode == EventKeyboard::KeyCode::KEY_CAPITAL_A || keyCode == EventKeyboard::KeyCode::KEY_CAPITAL_W || keyCode == EventKeyboard::KeyCode::KEY_CAPITAL_D || keyCode == EventKeyboard::KeyCode::KEY_CAPITAL_S || keyCode == EventKeyboard::KeyCode::KEY_A || keyCode == EventKeyboard::KeyCode::KEY_W || keyCode == EventKeyboard::KeyCode::KEY_D || keyCode == EventKeyboard::KeyCode::KEY_S) { m_bIsPressed = true; switch (keyCode) { case cocos2d::EventKeyboard::KeyCode::KEY_RIGHT_ARROW: { m_pHero->SetSpeed(Point(300, 0)); } break; case cocos2d::EventKeyboard::KeyCode::KEY_UP_ARROW: { m_pHero->SetSpeed(Point(0, 300)); } break; case cocos2d::EventKeyboard::KeyCode::KEY_DOWN_ARROW: { m_pHero->SetSpeed(Point(0, -300)); } break; case cocos2d::EventKeyboard::KeyCode::KEY_LEFT_ARROW: { m_pHero->SetSpeed(Point(-300, 0)); } break; case cocos2d::EventKeyboard::KeyCode::KEY_CAPITAL_A: { m_pHero->SetSpeed(Point(-300, 0)); } break; case cocos2d::EventKeyboard::KeyCode::KEY_CAPITAL_D: { m_pHero->SetSpeed(Point(300, 0)); } break; case cocos2d::EventKeyboard::KeyCode::KEY_CAPITAL_S: { m_pHero->SetSpeed(Point(0, -300)); } break; case cocos2d::EventKeyboard::KeyCode::KEY_CAPITAL_W: { m_pHero->SetSpeed(Point(0, 300)); } break; case cocos2d::EventKeyboard::KeyCode::KEY_A: { m_pHero->SetSpeed(Point(-300, 0)); } break; case cocos2d::EventKeyboard::KeyCode::KEY_D: { m_pHero->SetSpeed(Point(300, 0)); } break; case cocos2d::EventKeyboard::KeyCode::KEY_S: { m_pHero->SetSpeed(Point(0, -300)); } break; case cocos2d::EventKeyboard::KeyCode::KEY_W: { m_pHero->SetSpeed(Point(0, 300)); } break; default: return; } m_nKeyPressed++; m_bIsPressed = true; schedule(CC_SCHEDULE_SELECTOR(GameLayer::HeroMove)); } } void GameLayer::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event) { if (keyCode == EventKeyboard::KeyCode::KEY_LEFT_ARROW || keyCode == EventKeyboard::KeyCode::KEY_UP_ARROW || keyCode == EventKeyboard::KeyCode::KEY_RIGHT_ARROW || keyCode == EventKeyboard::KeyCode::KEY_DOWN_ARROW || keyCode == EventKeyboard::KeyCode::KEY_CAPITAL_A || keyCode == EventKeyboard::KeyCode::KEY_CAPITAL_W || keyCode == EventKeyboard::KeyCode::KEY_CAPITAL_D || keyCode == EventKeyboard::KeyCode::KEY_CAPITAL_S || keyCode == EventKeyboard::KeyCode::KEY_A || keyCode == EventKeyboard::KeyCode::KEY_W || keyCode == EventKeyboard::KeyCode::KEY_D || keyCode == EventKeyboard::KeyCode::KEY_S) { if (m_bIsPressed) { m_nKeyPressed--; if (m_nKeyPressed <= 0) { m_bIsPressed = false; unschedule(CC_SCHEDULE_SELECTOR(GameLayer::HeroMove)); } } } } void GameLayer::HeroMove(float dt) { auto heroCurrentPos = m_pHero->getPosition(); auto size = Director::getInstance()->getVisibleSize(); auto [MASK] = m_pHero->getContentSize(); if (m_pHero->GetSpeed().x <= 0 && m_pHero->GetSpeed().y <= 0) { if (heroCurrentPos.x - [MASK] .width / 2 < 0 || heroCurrentPos.y - [MASK] .height / 2 < 0) { return; } } else if(m_pHero->GetSpeed().x <= 0 && m_pHero->GetSpeed().y > 0) { if (heroCurrentPos.x - [MASK] .width / 2 < 0 || heroCurrentPos.y + [MASK] .height / 2 > size.height) { return; } } else if (m_pHero->GetSpeed().x > 0 && m_pHero->GetSpeed().y <= 0) { if (heroCurrentPos.x + [MASK] .width / 2 > size.width || heroCurrentPos.y - [MASK] .height / 2 < 0) { return; } } else if (m_pHero->GetSpeed().x > 0 && m_pHero->GetSpeed().y > 0) { if (heroCurrentPos.x + [MASK] .width / 2 > size.width || heroCurrentPos.y + [MASK] .height / 2 > size.height) { return; } } else { return; } m_pHero->Moving(dt); } Hero *GameLayer::GetHero() { if (NULL != m_pHero) { return m_pHero; } else { return NULL; } } void GameLayer::RockerMoveHero() { schedule(CC_SCHEDULE_SELECTOR(GameLayer::HeroMove)); } void GameLayer::RockerStopMoveHero() { unschedule(CC_SCHEDULE_SELECTOR(GameLayer::HeroMove)); } ",heroSize 318,"//===-- ARMBaseInstrInfo.cpp - ARM Instruction Information ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the Base ARM implementation of the TargetInstrInfo class. // //===----------------------------------------------------------------------===// #include ""ARM.h"" #include ""ARMBaseInstrInfo.h"" #include ""ARMBaseRegisterInfo.h"" #include ""ARMConstantPoolValue.h"" #include ""ARMFeatures.h"" #include ""ARMHazardRecognizer.h"" #include ""ARMMachineFunctionInfo.h"" #include ""MCTargetDesc/ARMAddressingModes.h"" #include ""llvm/ADT/STLExtras.h"" #include ""llvm/CodeGen/LiveVariables.h"" #include ""llvm/CodeGen/MachineConstantPool.h"" #include ""llvm/CodeGen/MachineFrameInfo.h"" #include ""llvm/CodeGen/MachineInstrBuilder.h"" #include ""llvm/CodeGen/MachineJumpTableInfo.h"" #include ""llvm/CodeGen/MachineMemOperand.h"" #include ""llvm/CodeGen/MachineRegisterInfo.h"" #include ""llvm/CodeGen/SelectionDAGNodes.h"" #include ""llvm/CodeGen/TargetSchedule.h"" #include ""llvm/IR/Constants.h"" #include ""llvm/IR/Function.h"" #include ""llvm/IR/GlobalValue.h"" #include ""llvm/MC/MCAsmInfo.h"" #include ""llvm/MC/MCExpr.h"" #include ""llvm/Support/BranchProbability.h"" #include ""llvm/Support/CommandLine.h"" #include ""llvm/Support/Debug.h"" #include ""llvm/Support/ErrorHandling.h"" #include ""llvm/Support/raw_ostream.h"" using namespace llvm; #define DEBUG_TYPE ""arm-instrinfo"" #define GET_INSTRINFO_CTOR_DTOR #include ""ARMGenInstrInfo.inc"" static cl::opt EnableARM3Addr(""enable-arm-3-addr-conv"", cl::Hidden, cl::desc(""Enable ARM 2-addr to 3-addr conv"")); static cl::opt WidenVMOVS(""widen-vmovs"", cl::Hidden, cl::init(true), cl::desc(""Widen ARM vmovs to vmovd when possible"")); static cl::opt SwiftPartialUpdateClearance(""swift-partial-update-clearance"", cl::Hidden, cl::init(12), cl::desc(""Clearance before partial register updates"")); /// ARM_MLxEntry - Record information about MLA / MLS instructions. struct ARM_MLxEntry { uint16_t MLxOpc; // MLA / MLS opcode uint16_t MulOpc; // Expanded multiplication opcode uint16_t AddSubOpc; // Expanded add / sub opcode bool NegAcc; // True if the acc is negated before the add / sub. bool HasLane; // True if instruction has an extra ""lane"" operand. }; static const ARM_MLxEntry ARM_MLxTable[] = { // MLxOpc, MulOpc, AddSubOpc, NegAcc, HasLane // fp scalar ops { ARM::VMLAS, ARM::VMULS, ARM::VADDS, false, false }, { ARM::VMLSS, ARM::VMULS, ARM::VSUBS, false, false }, { ARM::VMLAD, ARM::VMULD, ARM::VADDD, false, false }, { ARM::VMLSD, ARM::VMULD, ARM::VSUBD, false, false }, { ARM::VNMLAS, ARM::VNMULS, ARM::VSUBS, true, false }, { ARM::VNMLSS, ARM::VMULS, ARM::VSUBS, true, false }, { ARM::VNMLAD, ARM::VNMULD, ARM::VSUBD, true, false }, { ARM::VNMLSD, ARM::VMULD, ARM::VSUBD, true, false }, // fp SIMD ops { ARM::VMLAfd, ARM::VMULfd, ARM::VADDfd, false, false }, { ARM::VMLSfd, ARM::VMULfd, ARM::VSUBfd, false, false }, { ARM::VMLAfq, ARM::VMULfq, ARM::VADDfq, false, false }, { ARM::VMLSfq, ARM::VMULfq, ARM::VSUBfq, false, false }, { ARM::VMLAslfd, ARM::VMULslfd, ARM::VADDfd, false, true }, { ARM::VMLSslfd, ARM::VMULslfd, ARM::VSUBfd, false, true }, { ARM::VMLAslfq, ARM::VMULslfq, ARM::VADDfq, false, true }, { ARM::VMLSslfq, ARM::VMULslfq, ARM::VSUBfq, false, true }, }; ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI) : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP), Subtarget(STI) { for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) { if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second) llvm_unreachable(""Duplicated entries?""); MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc); MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc); } } // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl // currently defaults to no prepass hazard recognizer. ScheduleHazardRecognizer * ARMBaseInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI, const ScheduleDAG *DAG) const { if (usePreRAHazardRecognizer()) { const InstrItineraryData *II = static_cast(STI)->getInstrItineraryData(); return new ScoreboardHazardRecognizer(II, DAG, ""pre-RA-sched""); } return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG); } ScheduleHazardRecognizer *ARMBaseInstrInfo:: CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II, const ScheduleDAG *DAG) const { if (Subtarget.isThumb2() || Subtarget.hasVFP2()) return (ScheduleHazardRecognizer *)new ARMHazardRecognizer(II, DAG); return TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG); } MachineInstr * ARMBaseInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI, MachineBasicBlock::iterator &MBBI, LiveVariables *LV) const { // FIXME: Thumb2 support. if (!EnableARM3Addr) return nullptr; MachineInstr *MI = MBBI; MachineFunction &MF = *MI->getParent()->getParent(); uint64_t TSFlags = MI->getDesc().TSFlags; bool isPre = false; switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) { default: return nullptr; case ARMII::IndexModePre: isPre = true; break; case ARMII::IndexModePost: break; } // Try splitting an indexed load/store to an un-indexed one plus an add/sub // operation. unsigned MemOpc = getUnindexedOpcode(MI->getOpcode()); if (MemOpc == 0) return nullptr; MachineInstr *UpdateMI = nullptr; MachineInstr *MemMI = nullptr; unsigned AddrMode = (TSFlags & ARMII::AddrModeMask); const MCInstrDesc &MCID = MI->getDesc(); unsigned NumOps = MCID.getNumOperands(); bool isLoad = !MI->mayStore(); const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0); const MachineOperand &Base = MI->getOperand(2); const MachineOperand &Offset = MI->getOperand(NumOps-3); unsigned WBReg = WB.getReg(); unsigned BaseReg = Base.getReg(); unsigned OffReg = Offset.getReg(); unsigned OffImm = MI->getOperand(NumOps-2).getImm(); ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm(); switch (AddrMode) { default: llvm_unreachable(""Unknown indexed op!""); case ARMII::AddrMode2: { bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub; unsigned Amt = ARM_AM::getAM2Offset(OffImm); if (OffReg == 0) { if (ARM_AM::getSOImmVal(Amt) == -1) // Can't encode it in a so_imm operand. This transformation will // add more than 1 instruction. Abandon! return nullptr; UpdateMI = BuildMI(MF, MI->getDebugLoc(), get(isSub ? ARM::SUBri : ARM::ADDri), WBReg) .addReg(BaseReg).addImm(Amt) .addImm(Pred).addReg(0).addReg(0); } else if (Amt != 0) { ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm); unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt); UpdateMI = BuildMI(MF, MI->getDebugLoc(), get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg) .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc) .addImm(Pred).addReg(0).addReg(0); } else UpdateMI = BuildMI(MF, MI->getDebugLoc(), get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg) .addReg(BaseReg).addReg(OffReg) .addImm(Pred).addReg(0).addReg(0); break; } case ARMII::AddrMode3 : { bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub; unsigned Amt = ARM_AM::getAM3Offset(OffImm); if (OffReg == 0) // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand. UpdateMI = BuildMI(MF, MI->getDebugLoc(), get(isSub ? ARM::SUBri : ARM::ADDri), WBReg) .addReg(BaseReg).addImm(Amt) .addImm(Pred).addReg(0).addReg(0); else UpdateMI = BuildMI(MF, MI->getDebugLoc(), get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg) .addReg(BaseReg).addReg(OffReg) .addImm(Pred).addReg(0).addReg(0); break; } } std::vector NewMIs; if (isPre) { if (isLoad) MemMI = BuildMI(MF, MI->getDebugLoc(), get(MemOpc), MI->getOperand(0).getReg()) .addReg(WBReg).addImm(0).addImm(Pred); else MemMI = BuildMI(MF, MI->getDebugLoc(), get(MemOpc)).addReg(MI->getOperand(1).getReg()) .addReg(WBReg).addReg(0).addImm(0).addImm(Pred); NewMIs.push_back(MemMI); NewMIs.push_back(UpdateMI); } else { if (isLoad) MemMI = BuildMI(MF, MI->getDebugLoc(), get(MemOpc), MI->getOperand(0).getReg()) .addReg(BaseReg).addImm(0).addImm(Pred); else MemMI = BuildMI(MF, MI->getDebugLoc(), get(MemOpc)).addReg(MI->getOperand(1).getReg()) .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred); if (WB.isDead()) UpdateMI->getOperand(0).setIsDead(); NewMIs.push_back(UpdateMI); NewMIs.push_back(MemMI); } // Transfer LiveVariables states, kill / dead info. if (LV) { for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { MachineOperand &MO = MI->getOperand(i); if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())) { unsigned Reg = MO.getReg(); LiveVariables::VarInfo &VI = LV->getVarInfo(Reg); if (MO.isDef()) { MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI; if (MO.isDead()) LV->addVirtualRegisterDead(Reg, NewMI); } if (MO.isUse() && MO.isKill()) { for (unsigned j = 0; j < 2; ++j) { // Look at the two new MI's in reverse order. MachineInstr *NewMI = NewMIs[j]; if (!NewMI->readsRegister(Reg)) continue; LV->addVirtualRegisterKilled(Reg, NewMI); if (VI.removeKill(MI)) VI.Kills.push_back(NewMI); break; } } } } } MFI->insert(MBBI, NewMIs[1]); MFI->insert(MBBI, NewMIs[0]); return NewMIs[0]; } // Branch analysis. bool ARMBaseInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl &Cond, bool AllowModify) const { TBB = nullptr; FBB = nullptr; MachineBasicBlock::iterator I = MBB.end(); if (I == MBB.begin()) return false; // Empty blocks are easy. --I; // Walk backwards from the end of the basic block until the branch is // analyzed or we give up. while (isPredicated(*I) || I->isTerminator() || I->isDebugValue()) { // Flag to be raised on unanalyzeable instructions. This is useful in cases // where we want to clean up on the end of the basic block before we bail // out. bool CantAnalyze = false; // Skip over DEBUG values and predicated nonterminators. while (I->isDebugValue() || !I->isTerminator()) { if (I == MBB.begin()) return false; --I; } if (isIndirectBranchOpcode(I->getOpcode()) || isJumpTableBranchOpcode(I->getOpcode())) { // Indirect branches and jump tables can't be analyzed, but we still want // to clean up any instructions at the tail of the basic block. CantAnalyze = true; } else if (isUncondBranchOpcode(I->getOpcode())) { TBB = I->getOperand(0).getMBB(); } else if (isCondBranchOpcode(I->getOpcode())) { // Bail out if we encounter multiple conditional branches. if (!Cond.empty()) return true; assert(!FBB && ""FBB should have been null.""); FBB = TBB; TBB = I->getOperand(0).getMBB(); Cond.push_back(I->getOperand(1)); Cond.push_back(I->getOperand(2)); } else if (I->isReturn()) { // Returns can't be analyzed, but we should run cleanup. CantAnalyze = !isPredicated(*I); } else { // We encountered other unrecognized terminator. Bail out immediately. return true; } // Cleanup code - to be run for unpredicated unconditional branches and // returns. if (!isPredicated(*I) && (isUncondBranchOpcode(I->getOpcode()) || isIndirectBranchOpcode(I->getOpcode()) || isJumpTableBranchOpcode(I->getOpcode()) || I->isReturn())) { // Forget any previous condition branch information - it no longer applies. Cond.clear(); FBB = nullptr; // If we can modify the function, delete everything below this // unconditional branch. if (AllowModify) { MachineBasicBlock::iterator DI = std::next(I); while (DI != MBB.end()) { MachineInstr *InstToDelete = DI; ++DI; InstToDelete->eraseFromParent(); } } } if (CantAnalyze) return true; if (I == MBB.begin()) return false; --I; } // We made it past the terminators without bailing out - we must have // analyzed this branch successfully. return false; } unsigned ARMBaseInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const { MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); if (I == MBB.end()) return 0; if (!isUncondBranchOpcode(I->getOpcode()) && !isCondBranchOpcode(I->getOpcode())) return 0; // Remove the branch. I->eraseFromParent(); I = MBB.end(); if (I == MBB.begin()) return 1; --I; if (!isCondBranchOpcode(I->getOpcode())) return 1; // Remove the branch. I->eraseFromParent(); return 2; } unsigned ARMBaseInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef Cond, const DebugLoc &DL) const { ARMFunctionInfo *AFI = MBB.getParent()->getInfo(); int BOpc = !AFI->isThumbFunction() ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB); int BccOpc = !AFI->isThumbFunction() ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc); bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function(); // Shouldn't be a fall through. assert(TBB && ""InsertBranch must not be told to insert a fallthrough""); assert((Cond.size() == 2 || Cond.size() == 0) && ""ARM branch conditions have two components!""); // For conditional branches, we use addOperand to preserve CPSR flags. if (!FBB) { if (Cond.empty()) { // Unconditional branch? if (isThumb) BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).addImm(ARMCC::AL).addReg(0); else BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB); } else BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB) .addImm(Cond[0].getImm()).addOperand(Cond[1]); return 1; } // Two-way conditional branch. BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB) .addImm(Cond[0].getImm()).addOperand(Cond[1]); if (isThumb) BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).addImm(ARMCC::AL).addReg(0); else BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB); return 2; } bool ARMBaseInstrInfo:: ReverseBranchCondition(SmallVectorImpl &Cond) const { ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm(); Cond[0].setImm(ARMCC::getOppositeCondition(CC)); return false; } bool ARMBaseInstrInfo::isPredicated(const MachineInstr &MI) const { if (MI.isBundle()) { MachineBasicBlock::const_instr_iterator I = MI.getIterator(); MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end(); while (++I != E && I->isInsideBundle()) { int PIdx = I->findFirstPredOperandIdx(); if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL) return true; } return false; } int PIdx = MI.findFirstPredOperandIdx(); return PIdx != -1 && MI.getOperand(PIdx).getImm() != ARMCC::AL; } bool ARMBaseInstrInfo::PredicateInstruction( MachineInstr &MI, ArrayRef Pred) const { unsigned Opc = MI.getOpcode(); if (isUncondBranchOpcode(Opc)) { MI.setDesc(get(getMatchingCondBranchOpcode(Opc))); MachineInstrBuilder(*MI.getParent()->getParent(), MI) .addImm(Pred[0].getImm()) .addReg(Pred[1].getReg()); return true; } int PIdx = MI.findFirstPredOperandIdx(); if (PIdx != -1) { MachineOperand &PMO = MI.getOperand(PIdx); PMO.setImm(Pred[0].getImm()); MI.getOperand(PIdx+1).setReg(Pred[1].getReg()); return true; } return false; } bool ARMBaseInstrInfo::SubsumesPredicate(ArrayRef Pred1, ArrayRef Pred2) const { if (Pred1.size() > 2 || Pred2.size() > 2) return false; ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm(); ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm(); if (CC1 == CC2) return true; switch (CC1) { default: return false; case ARMCC::AL: return true; case ARMCC::HS: return CC2 == ARMCC::HI; case ARMCC::LS: return CC2 == ARMCC::LO || CC2 == ARMCC::EQ; case ARMCC::GE: return CC2 == ARMCC::GT; case ARMCC::LE: return CC2 == ARMCC::LT; } } bool ARMBaseInstrInfo::DefinesPredicate( MachineInstr &MI, std::vector &Pred) const { bool Found = false; for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI.getOperand(i); if ((MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) || (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)) { Pred.push_back(MO); Found = true; } } return Found; } static bool isCPSRDefined(const MachineInstr *MI) { for (const auto &MO : MI->operands()) if (MO.isReg() && MO.getReg() == ARM::CPSR && MO.isDef() && !MO.isDead()) return true; return false; } static bool isEligibleForITBlock(const MachineInstr *MI) { switch (MI->getOpcode()) { default: return true; case ARM::tADC: // ADC (register) T1 case ARM::tADDi3: // ADD (immediate) T1 case ARM::tADDi8: // ADD (immediate) T2 case ARM::tADDrr: // ADD (register) T1 case ARM::tAND: // AND (register) T1 case ARM::tASRri: // ASR (immediate) T1 case ARM::tASRrr: // ASR (register) T1 case ARM::tBIC: // BIC (register) T1 case ARM::tEOR: // EOR (register) T1 case ARM::tLSLri: // LSL (immediate) T1 case ARM::tLSLrr: // LSL (register) T1 case ARM::tLSRri: // LSR (immediate) T1 case ARM::tLSRrr: // LSR (register) T1 case ARM::tMUL: // MUL T1 case ARM::tMVN: // MVN (register) T1 case ARM::tORR: // ORR (register) T1 case ARM::tROR: // ROR (register) T1 case ARM::tRSB: // RSB (immediate) T1 case ARM::tSBC: // SBC (register) T1 case ARM::tSUBi3: // SUB (immediate) T1 case ARM::tSUBi8: // SUB (immediate) T2 case ARM::tSUBrr: // SUB (register) T1 return !isCPSRDefined(MI); } } /// isPredicable - Return true if the specified instruction can be predicated. /// By default, this returns true for every instruction with a /// PredicateOperand. bool ARMBaseInstrInfo::isPredicable(MachineInstr &MI) const { if (!MI.isPredicable()) return false; if (!isEligibleForITBlock(&MI)) return false; ARMFunctionInfo *AFI = MI.getParent()->getParent()->getInfo(); if (AFI->isThumb2Function()) { if (getSubtarget().restrictIT()) return isV8EligibleForIT(&MI); } else { // non-Thumb if ((MI.getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON) return false; } return true; } namespace llvm { template <> bool IsCPSRDead(MachineInstr *MI) { for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); if (!MO.isReg() || MO.isUndef() || MO.isUse()) continue; if (MO.getReg() != ARM::CPSR) continue; if (!MO.isDead()) return false; } // all definitions of CPSR are dead return true; } } /// GetInstSize - Return the size of the specified MachineInstr. /// unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const { const MachineBasicBlock &MBB = *MI->getParent(); const MachineFunction *MF = MBB.getParent(); const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo(); const MCInstrDesc &MCID = MI->getDesc(); if (MCID.getSize()) return MCID.getSize(); // If this machine instr is an inline asm, measure it. if (MI->getOpcode() == ARM::INLINEASM) return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI); unsigned Opc = MI->getOpcode(); switch (Opc) { default: // pseudo-instruction sizes are zero. return 0; case TargetOpcode::BUNDLE: return getInstBundleLength(MI); case ARM::MOVi16_ga_pcrel: case ARM::MOVTi16_ga_pcrel: case ARM::t2MOVi16_ga_pcrel: case ARM::t2MOVTi16_ga_pcrel: return 4; case ARM::MOVi32imm: case ARM::t2MOVi32imm: return 8; case ARM::CONSTPOOL_ENTRY: case ARM::JUMPTABLE_INSTS: case ARM::JUMPTABLE_ADDRS: case ARM::JUMPTABLE_TBB: case ARM::JUMPTABLE_TBH: // If this machine instr is a constant pool entry, its size is recorded as // operand #2. return MI->getOperand(2).getImm(); case ARM::Int_eh_sjlj_longjmp: return 16; case ARM::tInt_eh_sjlj_longjmp: case ARM::tInt_WIN_eh_sjlj_longjmp: return 10; case ARM::Int_eh_sjlj_setjmp: case ARM::Int_eh_sjlj_setjmp_nofp: return 20; case ARM::tInt_eh_sjlj_setjmp: case ARM::t2Int_eh_sjlj_setjmp: case ARM::t2Int_eh_sjlj_setjmp_nofp: return 12; case ARM::SPACE: return MI->getOperand(1).getImm(); } } unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr *MI) const { unsigned Size = 0; MachineBasicBlock::const_instr_iterator I = MI->getIterator(); MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end(); while (++I != E && I->isInsideBundle()) { assert(!I->isBundle() && ""No nested bundle!""); Size += GetInstSizeInBytes(&*I); } return Size; } void ARMBaseInstrInfo::copyFromCPSR(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, bool KillSrc, const ARMSubtarget &Subtarget) const { unsigned Opc = Subtarget.isThumb() ? (Subtarget.isMClass() ? ARM::t2MRS_M : ARM::t2MRS_AR) : ARM::MRS; MachineInstrBuilder MIB = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), DestReg); // There is only 1 A/R class MRS instruction, and it always refers to // APSR. However, there are lots of other possibilities on M-class cores. if (Subtarget.isMClass()) MIB.addImm(0x800); AddDefaultPred(MIB); MIB.addReg(ARM::CPSR, RegState::Implicit | getKillRegState(KillSrc)); } void ARMBaseInstrInfo::copyToCPSR(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned SrcReg, bool KillSrc, const ARMSubtarget &Subtarget) const { unsigned Opc = Subtarget.isThumb() ? (Subtarget.isMClass() ? ARM::t2MSR_M : ARM::t2MSR_AR) : ARM::MSR; MachineInstrBuilder MIB = BuildMI(MBB, I, I->getDebugLoc(), get(Opc)); if (Subtarget.isMClass()) MIB.addImm(0x800); else MIB.addImm(8); MIB.addReg(SrcReg, getKillRegState(KillSrc)); AddDefaultPred(MIB); MIB.addReg(ARM::CPSR, RegState::Implicit | RegState::Define); } void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, unsigned DestReg, unsigned SrcReg, bool KillSrc) const { bool GPRDest = ARM::GPRRegClass.contains(DestReg); bool GPRSrc = ARM::GPRRegClass.contains(SrcReg); if (GPRDest && GPRSrc) { AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg) .addReg(SrcReg, getKillRegState(KillSrc)))); return; } bool SPRDest = ARM::SPRRegClass.contains(DestReg); bool SPRSrc = ARM::SPRRegClass.contains(SrcReg); unsigned Opc = 0; if (SPRDest && SPRSrc) Opc = ARM::VMOVS; else if (GPRDest && SPRSrc) Opc = ARM::VMOVRS; else if (SPRDest && GPRSrc) Opc = ARM::VMOVSR; else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && !Subtarget.isFPOnlySP()) Opc = ARM::VMOVD; else if (ARM::QPRRegClass.contains(DestReg, SrcReg)) Opc = ARM::VORRq; if (Opc) { MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg); MIB.addReg(SrcReg, getKillRegState(KillSrc)); if (Opc == ARM::VORRq) MIB.addReg(SrcReg, getKillRegState(KillSrc)); AddDefaultPred(MIB); return; } // Handle register classes that require multiple instructions. unsigned BeginIdx = 0; unsigned SubRegs = 0; int Spacing = 1; // Use VORRq when possible. if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) { Opc = ARM::VORRq; BeginIdx = ARM::qsub_0; SubRegs = 2; } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) { Opc = ARM::VORRq; BeginIdx = ARM::qsub_0; SubRegs = 4; // Fall back to VMOVD. } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) { Opc = ARM::VMOVD; BeginIdx = ARM::dsub_0; SubRegs = 2; } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) { Opc = ARM::VMOVD; BeginIdx = ARM::dsub_0; SubRegs = 3; } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) { Opc = ARM::VMOVD; BeginIdx = ARM::dsub_0; SubRegs = 4; } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) { Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr; BeginIdx = ARM::gsub_0; SubRegs = 2; } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) { Opc = ARM::VMOVD; BeginIdx = ARM::dsub_0; SubRegs = 2; Spacing = 2; } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) { Opc = ARM::VMOVD; BeginIdx = ARM::dsub_0; SubRegs = 3; Spacing = 2; } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) { Opc = ARM::VMOVD; BeginIdx = ARM::dsub_0; SubRegs = 4; Spacing = 2; } else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && Subtarget.isFPOnlySP()) { Opc = ARM::VMOVS; BeginIdx = ARM::ssub_0; SubRegs = 2; } else if (SrcReg == ARM::CPSR) { copyFromCPSR(MBB, I, DestReg, KillSrc, Subtarget); return; } else if (DestReg == ARM::CPSR) { copyToCPSR(MBB, I, SrcReg, KillSrc, Subtarget); return; } assert(Opc && ""Impossible reg-to-reg copy""); const TargetRegisterInfo *TRI = &getRegisterInfo(); MachineInstrBuilder Mov; // Copy register tuples backward when the first Dest reg overlaps with SrcReg. if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) { BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing); Spacing = -Spacing; } #ifndef NDEBUG SmallSet DstRegs; #endif for (unsigned i = 0; i != SubRegs; ++i) { unsigned Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing); unsigned Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing); assert(Dst && Src && ""Bad sub-register""); #ifndef NDEBUG assert(!DstRegs.count(Src) && ""destructive vector copy""); DstRegs.insert(Dst); #endif Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src); // VORR takes two source operands. if (Opc == ARM::VORRq) Mov.addReg(Src); Mov = AddDefaultPred(Mov); // MOVr can set CC. if (Opc == ARM::MOVr) Mov = AddDefaultCC(Mov); } // Add implicit super-register defs and kills to the last instruction. Mov->addRegisterDefined(DestReg, TRI); if (KillSrc) Mov->addRegisterKilled(SrcReg, TRI); } const MachineInstrBuilder & ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg, unsigned SubIdx, unsigned State, const TargetRegisterInfo *TRI) const { if (!SubIdx) return MIB.addReg(Reg, State); if (TargetRegisterInfo::isPhysicalRegister(Reg)) return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State); return MIB.addReg(Reg, State, SubIdx); } void ARMBaseInstrInfo:: storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned SrcReg, bool isKill, int FI, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const { DebugLoc DL; if (I != MBB.end()) DL = I->getDebugLoc(); MachineFunction &MF = *MBB.getParent(); MachineFrameInfo &MFI = *MF.getFrameInfo(); unsigned Align = MFI.getObjectAlignment(FI); MachineMemOperand *MMO = MF.getMachineMemOperand( MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore, MFI.getObjectSize(FI), Align); switch (RC->getSize()) { case 4: if (ARM::GPRRegClass.hasSubClassEq(RC)) { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STRi12)) .addReg(SrcReg, getKillRegState(isKill)) .addFrameIndex(FI).addImm(0).addMemOperand(MMO)); } else if (ARM::SPRRegClass.hasSubClassEq(RC)) { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRS)) .addReg(SrcReg, getKillRegState(isKill)) .addFrameIndex(FI).addImm(0).addMemOperand(MMO)); } else llvm_unreachable(""Unknown reg class!""); break; case 8: if (ARM::DPRRegClass.hasSubClassEq(RC)) { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRD)) .addReg(SrcReg, getKillRegState(isKill)) .addFrameIndex(FI).addImm(0).addMemOperand(MMO)); } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) { if (Subtarget.hasV5TEOps()) { MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::STRD)); AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI); AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI); MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO); AddDefaultPred(MIB); } else { // Fallback to STM instruction, which has existed since the dawn of // time. MachineInstrBuilder MIB = AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STMIA)) .addFrameIndex(FI).addMemOperand(MMO)); AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI); AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI); } } else llvm_unreachable(""Unknown reg class!""); break; case 16: if (ARM::DPairRegClass.hasSubClassEq(RC)) { // Use aligned spills if the stack can be realigned. if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64)) .addFrameIndex(FI).addImm(16) .addReg(SrcReg, getKillRegState(isKill)) .addMemOperand(MMO)); } else { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMQIA)) .addReg(SrcReg, getKillRegState(isKill)) .addFrameIndex(FI) .addMemOperand(MMO)); } } else llvm_unreachable(""Unknown reg class!""); break; case 24: if (ARM::DTripleRegClass.hasSubClassEq(RC)) { // Use aligned spills if the stack can be realigned. if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64TPseudo)) .addFrameIndex(FI).addImm(16) .addReg(SrcReg, getKillRegState(isKill)) .addMemOperand(MMO)); } else { MachineInstrBuilder MIB = AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA)) .addFrameIndex(FI)) .addMemOperand(MMO); MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI); MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI); AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI); } } else llvm_unreachable(""Unknown reg class!""); break; case 32: if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) { if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) { // FIXME: It's possible to only store part of the QQ register if the // spilled def has a sub-register index. AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64QPseudo)) .addFrameIndex(FI).addImm(16) .addReg(SrcReg, getKillRegState(isKill)) .addMemOperand(MMO)); } else { MachineInstrBuilder MIB = AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA)) .addFrameIndex(FI)) .addMemOperand(MMO); MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI); MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI); MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI); AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI); } } else llvm_unreachable(""Unknown reg class!""); break; case 64: if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) { MachineInstrBuilder MIB = AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA)) .addFrameIndex(FI)) .addMemOperand(MMO); MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI); MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI); MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI); MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI); MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI); MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI); MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI); AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI); } else llvm_unreachable(""Unknown reg class!""); break; default: llvm_unreachable(""Unknown reg class!""); } } unsigned ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI, int &FrameIndex) const { switch (MI->getOpcode()) { default: break; case ARM::STRrs: case ARM::t2STRs: // FIXME: don't use t2STRs to access frame. if (MI->getOperand(1).isFI() && MI->getOperand(2).isReg() && MI->getOperand(3).isImm() && MI->getOperand(2).getReg() == 0 && MI->getOperand(3).getImm() == 0) { FrameIndex = MI->getOperand(1).getIndex(); return MI->getOperand(0).getReg(); } break; case ARM::STRi12: case ARM::t2STRi12: case ARM::tSTRspi: case ARM::VSTRD: case ARM::VSTRS: if (MI->getOperand(1).isFI() && MI->getOperand(2).isImm() && MI->getOperand(2).getImm() == 0) { FrameIndex = MI->getOperand(1).getIndex(); return MI->getOperand(0).getReg(); } break; case ARM::VST1q64: case ARM::VST1d64TPseudo: case ARM::VST1d64QPseudo: if (MI->getOperand(0).isFI() && MI->getOperand(2).getSubReg() == 0) { FrameIndex = MI->getOperand(0).getIndex(); return MI->getOperand(2).getReg(); } break; case ARM::VSTMQIA: if (MI->getOperand(1).isFI() && MI->getOperand(0).getSubReg() == 0) { FrameIndex = MI->getOperand(1).getIndex(); return MI->getOperand(0).getReg(); } break; } return 0; } unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr *MI, int &FrameIndex) const { const MachineMemOperand *Dummy; return MI->mayStore() && hasStoreToStackSlot(MI, Dummy, FrameIndex); } void ARMBaseInstrInfo:: loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, int FI, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const { DebugLoc DL; if (I != MBB.end()) DL = I->getDebugLoc(); MachineFunction &MF = *MBB.getParent(); MachineFrameInfo &MFI = *MF.getFrameInfo(); unsigned Align = MFI.getObjectAlignment(FI); MachineMemOperand *MMO = MF.getMachineMemOperand( MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad, MFI.getObjectSize(FI), Align); switch (RC->getSize()) { case 4: if (ARM::GPRRegClass.hasSubClassEq(RC)) { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg) .addFrameIndex(FI).addImm(0).addMemOperand(MMO)); } else if (ARM::SPRRegClass.hasSubClassEq(RC)) { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg) .addFrameIndex(FI).addImm(0).addMemOperand(MMO)); } else llvm_unreachable(""Unknown reg class!""); break; case 8: if (ARM::DPRRegClass.hasSubClassEq(RC)) { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg) .addFrameIndex(FI).addImm(0).addMemOperand(MMO)); } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) { MachineInstrBuilder MIB; if (Subtarget.hasV5TEOps()) { MIB = BuildMI(MBB, I, DL, get(ARM::LDRD)); AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI); AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI); MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO); AddDefaultPred(MIB); } else { // Fallback to LDM instruction, which has existed since the dawn of // time. MIB = AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDMIA)) .addFrameIndex(FI).addMemOperand(MMO)); MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI); } if (TargetRegisterInfo::isPhysicalRegister(DestReg)) MIB.addReg(DestReg, RegState::ImplicitDefine); } else llvm_unreachable(""Unknown reg class!""); break; case 16: if (ARM::DPairRegClass.hasSubClassEq(RC)) { if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg) .addFrameIndex(FI).addImm(16) .addMemOperand(MMO)); } else { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg) .addFrameIndex(FI) .addMemOperand(MMO)); } } else llvm_unreachable(""Unknown reg class!""); break; case 24: if (ARM::DTripleRegClass.hasSubClassEq(RC)) { if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg) .addFrameIndex(FI).addImm(16) .addMemOperand(MMO)); } else { MachineInstrBuilder MIB = AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA)) .addFrameIndex(FI) .addMemOperand(MMO)); MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI); if (TargetRegisterInfo::isPhysicalRegister(DestReg)) MIB.addReg(DestReg, RegState::ImplicitDefine); } } else llvm_unreachable(""Unknown reg class!""); break; case 32: if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) { if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) { AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg) .addFrameIndex(FI).addImm(16) .addMemOperand(MMO)); } else { MachineInstrBuilder MIB = AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA)) .addFrameIndex(FI)) .addMemOperand(MMO); MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI); if (TargetRegisterInfo::isPhysicalRegister(DestReg)) MIB.addReg(DestReg, RegState::ImplicitDefine); } } else llvm_unreachable(""Unknown reg class!""); break; case 64: if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) { MachineInstrBuilder MIB = AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA)) .addFrameIndex(FI)) .addMemOperand(MMO); MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI); MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI); if (TargetRegisterInfo::isPhysicalRegister(DestReg)) MIB.addReg(DestReg, RegState::ImplicitDefine); } else llvm_unreachable(""Unknown reg class!""); break; default: llvm_unreachable(""Unknown regclass!""); } } unsigned ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI, int &FrameIndex) const { switch (MI->getOpcode()) { default: break; case ARM::LDRrs: case ARM::t2LDRs: // FIXME: don't use t2LDRs to access frame. if (MI->getOperand(1).isFI() && MI->getOperand(2).isReg() && MI->getOperand(3).isImm() && MI->getOperand(2).getReg() == 0 && MI->getOperand(3).getImm() == 0) { FrameIndex = MI->getOperand(1).getIndex(); return MI->getOperand(0).getReg(); } break; case ARM::LDRi12: case ARM::t2LDRi12: case ARM::tLDRspi: case ARM::VLDRD: case ARM::VLDRS: if (MI->getOperand(1).isFI() && MI->getOperand(2).isImm() && MI->getOperand(2).getImm() == 0) { FrameIndex = MI->getOperand(1).getIndex(); return MI->getOperand(0).getReg(); } break; case ARM::VLD1q64: case ARM::VLD1d64TPseudo: case ARM::VLD1d64QPseudo: if (MI->getOperand(1).isFI() && MI->getOperand(0).getSubReg() == 0) { FrameIndex = MI->getOperand(1).getIndex(); return MI->getOperand(0).getReg(); } break; case ARM::VLDMQIA: if (MI->getOperand(1).isFI() && MI->getOperand(0).getSubReg() == 0) { FrameIndex = MI->getOperand(1).getIndex(); return MI->getOperand(0).getReg(); } break; } return 0; } unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr *MI, int &FrameIndex) const { const MachineMemOperand *Dummy; return MI->mayLoad() && hasLoadFromStackSlot(MI, Dummy, FrameIndex); } /// \brief Expands MEMCPY to either LDMIA/STMIA or LDMIA_UPD/STMID_UPD /// depending on whether the result is used. void ARMBaseInstrInfo::expandMEMCPY(MachineBasicBlock::iterator MBBI) const { bool isThumb1 = Subtarget.isThumb1Only(); bool isThumb2 = Subtarget.isThumb2(); const ARMBaseInstrInfo *TII = Subtarget.getInstrInfo(); MachineInstr *MI = MBBI; DebugLoc dl = MI->getDebugLoc(); MachineBasicBlock *BB = MI->getParent(); MachineInstrBuilder LDM, STM; if (isThumb1 || !MI->getOperand(1).isDead()) { LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA_UPD : isThumb1 ? ARM::tLDMIA_UPD : ARM::LDMIA_UPD)) .addOperand(MI->getOperand(1)); } else { LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA : ARM::LDMIA)); } if (isThumb1 || !MI->getOperand(0).isDead()) { STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA_UPD : isThumb1 ? ARM::tSTMIA_UPD : ARM::STMIA_UPD)) .addOperand(MI->getOperand(0)); } else { STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA : ARM::STMIA)); } AddDefaultPred(LDM.addOperand(MI->getOperand(3))); AddDefaultPred(STM.addOperand(MI->getOperand(2))); // Sort the scratch registers into ascending order. const TargetRegisterInfo &TRI = getRegisterInfo(); llvm::SmallVector ScratchRegs; for(unsigned I = 5; I < MI->getNumOperands(); ++I) ScratchRegs.push_back(MI->getOperand(I).getReg()); std::sort(ScratchRegs.begin(), ScratchRegs.end(), [&TRI](const unsigned &Reg1, const unsigned &Reg2) -> bool { return TRI.getEncodingValue(Reg1) < TRI.getEncodingValue(Reg2); }); for (const auto &Reg : ScratchRegs) { LDM.addReg(Reg, RegState::Define); STM.addReg(Reg, RegState::Kill); } BB->erase(MBBI); } bool ARMBaseInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const { MachineFunction &MF = *MI->getParent()->getParent(); Reloc::Model RM = MF.getTarget().getRelocationModel(); if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD) { assert(getSubtarget().getTargetTriple().isOSBinFormatMachO() && ""LOAD_STACK_GUARD currently supported only for MachO.""); expandLoadStackGuard(MI, RM); MI->getParent()->erase(MI); return true; } if (MI->getOpcode() == ARM::MEMCPY) { expandMEMCPY(MI); return true; } // This hook gets to expand COPY instructions before they become // copyPhysReg() calls. Look for VMOVS instructions that can legally be // widened to VMOVD. We prefer the VMOVD when possible because it may be // changed into a VORR that can go down the NEON pipeline. if (!WidenVMOVS || !MI->isCopy() || Subtarget.isCortexA15() || Subtarget.isFPOnlySP()) return false; // Look for a copy between even S-registers. That is where we keep floats // when using NEON v2f32 instructions for f32 arithmetic. unsigned DstRegS = MI->getOperand(0).getReg(); unsigned SrcRegS = MI->getOperand(1).getReg(); if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS)) return false; const TargetRegisterInfo *TRI = &getRegisterInfo(); unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0, &ARM::DPRRegClass); unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0, &ARM::DPRRegClass); if (!DstRegD || !SrcRegD) return false; // We want to widen this into a DstRegD = VMOVD SrcRegD copy. This is only // legal if the COPY already defines the full DstRegD, and it isn't a // sub-register insertion. if (!MI->definesRegister(DstRegD, TRI) || MI->readsRegister(DstRegD, TRI)) return false; // A dead copy shouldn't show up here, but reject it just in case. if (MI->getOperand(0).isDead()) return false; // All clear, widen the COPY. DEBUG(dbgs() << ""widening: "" << *MI); MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI); // Get rid of the old of DstRegD. Leave it if it defines a Q-reg // or some other super-register. int ImpDefIdx = MI->findRegisterDefOperandIdx(DstRegD); if (ImpDefIdx != -1) MI->RemoveOperand(ImpDefIdx); // Change the opcode and operands. MI->setDesc(get(ARM::VMOVD)); MI->getOperand(0).setReg(DstRegD); MI->getOperand(1).setReg(SrcRegD); AddDefaultPred(MIB); // We are now reading SrcRegD instead of SrcRegS. This may upset the // register scavenger and machine verifier, so we need to indicate that we // are reading an undefined value from SrcRegD, but a proper value from // SrcRegS. MI->getOperand(1).setIsUndef(); MIB.addReg(SrcRegS, RegState::Implicit); // SrcRegD may actually contain an unrelated value in the ssub_1 // sub-register. Don't kill it. Only kill the ssub_0 sub-register. if (MI->getOperand(1).isKill()) { MI->getOperand(1).setIsKill(false); MI->addRegisterKilled(SrcRegS, TRI, true); } DEBUG(dbgs() << ""replaced by: "" << *MI); return true; } /// Create a copy of a const pool value. Update CPI to the new index and return /// the label UID. static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) { MachineConstantPool *MCP = MF.getConstantPool(); ARMFunctionInfo *AFI = MF.getInfo(); const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI]; assert(MCPE.isMachineConstantPoolEntry() && ""Expecting a machine constantpool entry!""); ARMConstantPoolValue *ACPV = static_cast(MCPE.Val.MachineCPVal); unsigned PCLabelId = AFI->createPICLabelUId(); ARMConstantPoolValue *NewCPV = nullptr; // FIXME: The below assumes PIC relocation model and that the function // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR // instructions, so that's probably OK, but is PIC always correct when // we get here? if (ACPV->isGlobalValue()) NewCPV = ARMConstantPoolConstant::Create( cast(ACPV)->getGV(), PCLabelId, ARMCP::CPValue, 4, ACPV->getModifier(), ACPV->mustAddCurrentAddress()); else if (ACPV->isExtSymbol()) NewCPV = ARMConstantPoolSymbol:: Create(MF.getFunction()->getContext(), cast(ACPV)->getSymbol(), PCLabelId, 4); else if (ACPV->isBlockAddress()) NewCPV = ARMConstantPoolConstant:: Create(cast(ACPV)->getBlockAddress(), PCLabelId, ARMCP::CPBlockAddress, 4); else if (ACPV->isLSDA()) NewCPV = ARMConstantPoolConstant::Create(MF.getFunction(), PCLabelId, ARMCP::CPLSDA, 4); else if (ACPV->isMachineBasicBlock()) NewCPV = ARMConstantPoolMBB:: Create(MF.getFunction()->getContext(), cast(ACPV)->getMBB(), PCLabelId, 4); else llvm_unreachable(""Unexpected ARM constantpool value type!!""); CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment()); return PCLabelId; } void ARMBaseInstrInfo:: reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, unsigned SubIdx, const MachineInstr *Orig, const TargetRegisterInfo &TRI) const { unsigned Opcode = Orig->getOpcode(); switch (Opcode) { default: { MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig); MI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI); MBB.insert(I, MI); break; } case ARM::tLDRpci_pic: case ARM::t2LDRpci_pic: { MachineFunction &MF = *MBB.getParent(); unsigned CPI = Orig->getOperand(1).getIndex(); unsigned PCLabelId = duplicateCPV(MF, CPI); MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode), DestReg) .addConstantPoolIndex(CPI).addImm(PCLabelId); MIB->setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end()); break; } } } MachineInstr * ARMBaseInstrInfo::duplicate(MachineInstr *Orig, MachineFunction &MF) const { MachineInstr *MI = TargetInstrInfo::duplicate(Orig, MF); switch(Orig->getOpcode()) { case ARM::tLDRpci_pic: case ARM::t2LDRpci_pic: { unsigned CPI = Orig->getOperand(1).getIndex(); unsigned PCLabelId = duplicateCPV(MF, CPI); Orig->getOperand(1).setIndex(CPI); Orig->getOperand(2).setImm(PCLabelId); break; } } return MI; } bool ARMBaseInstrInfo::produceSameValue(const MachineInstr *MI0, const MachineInstr *MI1, const MachineRegisterInfo *MRI) const { unsigned Opcode = MI0->getOpcode(); if (Opcode == ARM::t2LDRpci || Opcode == ARM::t2LDRpci_pic || Opcode == ARM::tLDRpci || Opcode == ARM::tLDRpci_pic || Opcode == ARM::LDRLIT_ga_pcrel || Opcode == ARM::LDRLIT_ga_pcrel_ldr || Opcode == ARM::tLDRLIT_ga_pcrel || Opcode == ARM::MOV_ga_pcrel || Opcode == ARM::MOV_ga_pcrel_ldr || Opcode == ARM::t2MOV_ga_pcrel) { if (MI1->getOpcode() != Opcode) return false; if (MI0->getNumOperands() != MI1->getNumOperands()) return false; const MachineOperand &MO0 = MI0->getOperand(1); const MachineOperand &MO1 = MI1->getOperand(1); if (MO0.getOffset() != MO1.getOffset()) return false; if (Opcode == ARM::LDRLIT_ga_pcrel || Opcode == ARM::LDRLIT_ga_pcrel_ldr || Opcode == ARM::tLDRLIT_ga_pcrel || Opcode == ARM::MOV_ga_pcrel || Opcode == ARM::MOV_ga_pcrel_ldr || Opcode == ARM::t2MOV_ga_pcrel) // Ignore the PC labels. return MO0.getGlobal() == MO1.getGlobal(); const MachineFunction *MF = MI0->getParent()->getParent(); const MachineConstantPool *MCP = MF->getConstantPool(); int CPI0 = MO0.getIndex(); int CPI1 = MO1.getIndex(); const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0]; const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1]; bool isARMCP0 = MCPE0.isMachineConstantPoolEntry(); bool isARMCP1 = MCPE1.isMachineConstantPoolEntry(); if (isARMCP0 && isARMCP1) { ARMConstantPoolValue *ACPV0 = static_cast(MCPE0.Val.MachineCPVal); ARMConstantPoolValue *ACPV1 = static_cast(MCPE1.Val.MachineCPVal); return ACPV0->hasSameValue(ACPV1); } else if (!isARMCP0 && !isARMCP1) { return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal; } return false; } else if (Opcode == ARM::PICLDR) { if (MI1->getOpcode() != Opcode) return false; if (MI0->getNumOperands() != MI1->getNumOperands()) return false; unsigned Addr0 = MI0->getOperand(1).getReg(); unsigned Addr1 = MI1->getOperand(1).getReg(); if (Addr0 != Addr1) { if (!MRI || !TargetRegisterInfo::isVirtualRegister(Addr0) || !TargetRegisterInfo::isVirtualRegister(Addr1)) return false; // This assumes SSA form. MachineInstr *Def0 = MRI->getVRegDef(Addr0); MachineInstr *Def1 = MRI->getVRegDef(Addr1); // Check if the loaded value, e.g. a constantpool of a global address, are // the same. if (!produceSameValue(Def0, Def1, MRI)) return false; } for (unsigned i = 3, e = MI0->getNumOperands(); i != e; ++i) { // %vreg12 = PICLDR %vreg11, 0, pred:14, pred:%noreg const MachineOperand &MO0 = MI0->getOperand(i); const MachineOperand &MO1 = MI1->getOperand(i); if (!MO0.isIdenticalTo(MO1)) return false; } return true; } return MI0->isIdenticalTo(*MI1, MachineInstr::IgnoreVRegDefs); } /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to /// determine if two loads are loading from the same base address. It should /// only return true if the base pointers are the same and the only differences /// between the two addresses is the offset. It also returns the offsets by /// reference. /// /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched /// is permanently disabled. bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2, int64_t &Offset1, int64_t &Offset2) const { // Don't worry about Thumb: just ARM and Thumb2. if (Subtarget.isThumb1Only()) return false; if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode()) return false; switch (Load1->getMachineOpcode()) { default: return false; case ARM::LDRi12: case ARM::LDRBi12: case ARM::LDRD: case ARM::LDRH: case ARM::LDRSB: case ARM::LDRSH: case ARM::VLDRD: case ARM::VLDRS: case ARM::t2LDRi8: case ARM::t2LDRBi8: case ARM::t2LDRDi8: case ARM::t2LDRSHi8: case ARM::t2LDRi12: case ARM::t2LDRBi12: case ARM::t2LDRSHi12: break; } switch (Load2->getMachineOpcode()) { default: return false; case ARM::LDRi12: case ARM::LDRBi12: case ARM::LDRD: case ARM::LDRH: case ARM::LDRSB: case ARM::LDRSH: case ARM::VLDRD: case ARM::VLDRS: case ARM::t2LDRi8: case ARM::t2LDRBi8: case ARM::t2LDRSHi8: case ARM::t2LDRi12: case ARM::t2LDRBi12: case ARM::t2LDRSHi12: break; } // Check if base addresses and chain operands match. if (Load1->getOperand(0) != Load2->getOperand(0) || Load1->getOperand(4) != Load2->getOperand(4)) return false; // Index should be Reg0. if (Load1->getOperand(3) != Load2->getOperand(3)) return false; // Determine the offsets. if (isa(Load1->getOperand(1)) && isa(Load2->getOperand(1))) { Offset1 = cast(Load1->getOperand(1))->getSExtValue(); Offset2 = cast(Load2->getOperand(1))->getSExtValue(); return true; } return false; } /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should /// be scheduled togther. On some targets if two loads are loading from /// addresses in the same cache line, it's better if they are scheduled /// together. This function takes two integers that represent the load offsets /// from the common base address. It returns true if it decides it's desirable /// to schedule the two loads together. ""NumLoads"" is the number of loads that /// have already been scheduled after Load1. /// /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched /// is permanently disabled. bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2, int64_t Offset1, int64_t Offset2, unsigned NumLoads) const { // Don't worry about Thumb: just ARM and Thumb2. if (Subtarget.isThumb1Only()) return false; assert(Offset2 > Offset1); if ((Offset2 - Offset1) / 8 > 64) return false; // Check if the machine opcodes are different. If they are different // then we consider them to not be of the same base address, // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12. // In this case, they are considered to be the same because they are different // encoding forms of the same basic instruction. if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) && !((Load1->getMachineOpcode() == ARM::t2LDRBi8 && Load2->getMachineOpcode() == ARM::t2LDRBi12) || (Load1->getMachineOpcode() == ARM::t2LDRBi12 && Load2->getMachineOpcode() == ARM::t2LDRBi8))) return false; // FIXME: overly conservative? // Four loads in a row should be sufficient. if (NumLoads >= 3) return false; return true; } bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr *MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const { // Debug info is never a scheduling boundary. It's necessary to be explicit // due to the special treatment of IT instructions below, otherwise a // dbg_value followed by an IT will result in the IT instruction being // considered a scheduling hazard, which is wrong. It should be the actual // instruction preceding the dbg_value instruction(s), just like it is // when debug info is not present. if (MI->isDebugValue()) return false; // Terminators and labels can't be scheduled around. if (MI->isTerminator() || MI->isPosition()) return true; // Treat the start of the IT block as a scheduling boundary, but schedule // t2IT along with all instructions following it. // FIXME: This is a big hammer. But the alternative is to add all potential // true and anti dependencies to IT block instructions as implicit operands // to the t2IT instruction. The added compile time and complexity does not // seem worth it. MachineBasicBlock::const_iterator I = MI; // Make sure to skip any dbg_value instructions while (++I != MBB->end() && I->isDebugValue()) ; if (I != MBB->end() && I->getOpcode() == ARM::t2IT) return true; // Don't attempt to schedule around any instruction that defines // a stack-oriented pointer, as it's unlikely to be profitable. This // saves compile time, because it doesn't require every single // stack slot reference to depend on the instruction that does the // modification. // Calls don't actually change the stack pointer, even if they have imp-defs. // No ARM calling conventions change the stack pointer. (X86 calling // conventions sometimes do). if (!MI->isCall() && MI->definesRegister(ARM::SP)) return true; return false; } bool ARMBaseInstrInfo:: isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, unsigned ExtraPredCycles, BranchProbability Probability) const { if (!NumCycles) return false; // If we are optimizing for size, see if the branch in the predecessor can be // lowered to cbn?z by the constant island lowering pass, and return false if // so. This results in a shorter instruction sequence. if (MBB.getParent()->getFunction()->optForSize()) { MachineBasicBlock *Pred = *MBB.pred_begin(); if (!Pred->empty()) { MachineInstr *LastMI = &*Pred->rbegin(); if (LastMI->getOpcode() == ARM::t2Bcc) { MachineBasicBlock::iterator CmpMI = LastMI; if (CmpMI != Pred->begin()) { --CmpMI; if (CmpMI->getOpcode() == ARM::tCMPi8 || CmpMI->getOpcode() == ARM::t2CMPri) { unsigned Reg = CmpMI->getOperand(0).getReg(); unsigned PredReg = 0; ARMCC::CondCodes P = getInstrPredicate(*CmpMI, PredReg); if (P == ARMCC::AL && CmpMI->getOperand(1).getImm() == 0 && isARMLowRegister(Reg)) return false; } } } } } // Attempt to estimate the relative costs of predication versus branching. // Here we scale up each component of UnpredCost to avoid precision issue when // scaling NumCycles by Probability. const unsigned ScalingUpFactor = 1024; unsigned UnpredCost = Probability.scale(NumCycles * ScalingUpFactor); UnpredCost += ScalingUpFactor; // The branch itself UnpredCost += Subtarget.getMispredictionPenalty() * ScalingUpFactor / 10; return (NumCycles + ExtraPredCycles) * ScalingUpFactor <= UnpredCost; } bool ARMBaseInstrInfo:: isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned TCycles, unsigned TExtra, MachineBasicBlock &FMBB, unsigned FCycles, unsigned FExtra, BranchProbability Probability) const { if (!TCycles || !FCycles) return false; // Attempt to estimate the relative costs of predication versus branching. // Here we scale up each component of UnpredCost to avoid precision issue when // scaling TCycles/FCycles by Probability. const unsigned ScalingUpFactor = 1024; unsigned TUnpredCost = Probability.scale(TCycles * ScalingUpFactor); unsigned FUnpredCost = Probability.getCompl().scale(FCycles * ScalingUpFactor); unsigned UnpredCost = TUnpredCost + FUnpredCost; UnpredCost += 1 * ScalingUpFactor; // The branch itself UnpredCost += Subtarget.getMispredictionPenalty() * ScalingUpFactor / 10; return (TCycles + FCycles + TExtra + FExtra) * ScalingUpFactor <= UnpredCost; } bool ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB, MachineBasicBlock &FMBB) const { // Reduce false anti-dependencies to let Swift's out-of-order execution // engine do its thing. return Subtarget.isSwift(); } /// getInstrPredicate - If instruction is predicated, returns its predicate /// condition, otherwise returns AL. It also returns the condition code /// register by reference. ARMCC::CondCodes llvm::getInstrPredicate(const MachineInstr &MI, unsigned &PredReg) { int PIdx = MI.findFirstPredOperandIdx(); if (PIdx == -1) { PredReg = 0; return ARMCC::AL; } PredReg = MI.getOperand(PIdx+1).getReg(); return (ARMCC::CondCodes)MI.getOperand(PIdx).getImm(); } unsigned llvm::getMatchingCondBranchOpcode(unsigned Opc) { if (Opc == ARM::B) return ARM::Bcc; if (Opc == ARM::tB) return ARM::tBcc; if (Opc == ARM::t2B) return ARM::t2Bcc; llvm_unreachable(""Unknown unconditional branch opcode!""); } MachineInstr *ARMBaseInstrInfo::commuteInstructionImpl(MachineInstr *MI, bool NewMI, unsigned OpIdx1, unsigned OpIdx2) const { switch (MI->getOpcode()) { case ARM::MOVCCr: case ARM::t2MOVCCr: { // MOVCC can be commuted by inverting the condition. unsigned PredReg = 0; ARMCC::CondCodes CC = getInstrPredicate(*MI, PredReg); // MOVCC AL can't be inverted. Shouldn't happen. if (CC == ARMCC::AL || PredReg != ARM::CPSR) return nullptr; MI = TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2); if (!MI) return nullptr; // After swapping the MOVCC operands, also invert the condition. MI->getOperand(MI->findFirstPredOperandIdx()) .setImm(ARMCC::getOppositeCondition(CC)); return MI; } } return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2); } /// Identify instructions that can be folded into a MOVCC instruction, and /// return the defining instruction. static MachineInstr *canFoldIntoMOVCC(unsigned Reg, const MachineRegisterInfo &MRI, const TargetInstrInfo *TII) { if (!TargetRegisterInfo::isVirtualRegister(Reg)) return nullptr; if (!MRI.hasOneNonDBGUse(Reg)) return nullptr; MachineInstr *MI = MRI.getVRegDef(Reg); if (!MI) return nullptr; // MI is folded into the MOVCC by predicating it. if (!MI->isPredicable()) return nullptr; // Check if MI has any non-dead defs or physreg uses. This also detects // predicated instructions which will be reading CPSR. for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); // Reject frame index operands, PEI can't handle the predicated pseudos. if (MO.isFI() || MO.isCPI() || MO.isJTI()) return nullptr; if (!MO.isReg()) continue; // MI can't have any tied operands, that would conflict with predication. if (MO.isTied()) return nullptr; if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) return nullptr; if (MO.isDef() && !MO.isDead()) return nullptr; } bool DontMoveAcrossStores = true; if (!MI->isSafeToMove(/* AliasAnalysis = */ nullptr, DontMoveAcrossStores)) return nullptr; return MI; } bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr *MI, SmallVectorImpl &Cond, unsigned &TrueOp, unsigned &FalseOp, bool &Optimizable) const { assert((MI->getOpcode() == ARM::MOVCCr || MI->getOpcode() == ARM::t2MOVCCr) && ""Unknown select instruction""); // MOVCC operands: // 0: Def. // 1: True use. // 2: False use. // 3: Condition code. // 4: CPSR use. TrueOp = 1; FalseOp = 2; Cond.push_back(MI->getOperand(3)); Cond.push_back(MI->getOperand(4)); // We can always fold a def. Optimizable = true; return false; } MachineInstr * ARMBaseInstrInfo::optimizeSelect(MachineInstr *MI, SmallPtrSetImpl &SeenMIs, bool PreferFalse) const { assert((MI->getOpcode() == ARM::MOVCCr || MI->getOpcode() == ARM::t2MOVCCr) && ""Unknown select instruction""); MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo(); MachineInstr *DefMI = canFoldIntoMOVCC(MI->getOperand(2).getReg(), MRI, this); bool Invert = !DefMI; if (!DefMI) DefMI = canFoldIntoMOVCC(MI->getOperand(1).getReg(), MRI, this); if (!DefMI) return nullptr; // Find new register class to use. MachineOperand FalseReg = MI->getOperand(Invert ? 2 : 1); unsigned DestReg = MI->getOperand(0).getReg(); const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg()); if (!MRI.constrainRegClass(DestReg, PreviousClass)) return nullptr; // Create a new predicated version of DefMI. // Rfalse is the first use. MachineInstrBuilder NewMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), DefMI->getDesc(), DestReg); // Copy all the DefMI operands, excluding its (null) predicate. const MCInstrDesc &DefDesc = DefMI->getDesc(); for (unsigned i = 1, e = DefDesc.getNumOperands(); i != e && !DefDesc.OpInfo[i].isPredicate(); ++i) NewMI.addOperand(DefMI->getOperand(i)); unsigned CondCode = MI->getOperand(3).getImm(); if (Invert) NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode))); else NewMI.addImm(CondCode); NewMI.addOperand(MI->getOperand(4)); // DefMI is not the -S version that sets CPSR, so add an optional %noreg. if (NewMI->hasOptionalDef()) AddDefaultCC(NewMI); // The output register value when the predicate is false is an implicit // register operand tied to the first def. // The tie makes the register allocator ensure the FalseReg is allocated the // same register as operand 0. FalseReg.setImplicit(); NewMI.addOperand(FalseReg); NewMI->tieOperands(0, NewMI->getNumOperands() - 1); // Update SeenMIs set: register newly created MI and erase removed DefMI. SeenMIs.insert(NewMI); SeenMIs.erase(DefMI); // If MI is inside a loop, and DefMI is outside the loop, then kill flags on // DefMI would be invalid when tranferred inside the loop. Checking for a // loop is expensive, but at least remove kill flags if they are in different // BBs. if (DefMI->getParent() != MI->getParent()) NewMI->clearKillInfo(); // The caller will erase MI, but not DefMI. DefMI->eraseFromParent(); return NewMI; } /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the /// instruction is encoded with an 'S' bit is determined by the optional CPSR /// def operand. /// /// This will go away once we can teach tblgen how to set the optional CPSR def /// operand itself. struct AddSubFlagsOpcodePair { uint16_t PseudoOpc; uint16_t MachineOpc; }; static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = { {ARM::ADDSri, ARM::ADDri}, {ARM::ADDSrr, ARM::ADDrr}, {ARM::ADDSrsi, ARM::ADDrsi}, {ARM::ADDSrsr, ARM::ADDrsr}, {ARM::SUBSri, ARM::SUBri}, {ARM::SUBSrr, ARM::SUBrr}, {ARM::SUBSrsi, ARM::SUBrsi}, {ARM::SUBSrsr, ARM::SUBrsr}, {ARM::RSBSri, ARM::RSBri}, {ARM::RSBSrsi, ARM::RSBrsi}, {ARM::RSBSrsr, ARM::RSBrsr}, {ARM::t2ADDSri, ARM::t2ADDri}, {ARM::t2ADDSrr, ARM::t2ADDrr}, {ARM::t2ADDSrs, ARM::t2ADDrs}, {ARM::t2SUBSri, ARM::t2SUBri}, {ARM::t2SUBSrr, ARM::t2SUBrr}, {ARM::t2SUBSrs, ARM::t2SUBrs}, {ARM::t2RSBSri, ARM::t2RSBri}, {ARM::t2RSBSrs, ARM::t2RSBrs}, }; unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) { for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i) if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc) return AddSubFlagsOpcodeMap[i].MachineOpc; return 0; } void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, unsigned DestReg, unsigned BaseReg, int NumBytes, ARMCC::CondCodes Pred, unsigned PredReg, const ARMBaseInstrInfo &TII, unsigned MIFlags) { if (NumBytes == 0 && DestReg != BaseReg) { BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg) .addReg(BaseReg, RegState::Kill) .addImm((unsigned)Pred).addReg(PredReg).addReg(0) .setMIFlags(MIFlags); return; } bool isSub = NumBytes < 0; if (isSub) NumBytes = -NumBytes; while (NumBytes) { unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes); unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt); assert(ThisVal && ""Didn't extract field correctly""); // We will handle these bits from offset, clear them. NumBytes &= ~ThisVal; assert(ARM_AM::getSOImmVal(ThisVal) != -1 && ""Bit extraction didn't work?""); // Build the new ADD / SUB. unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri; BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg) .addReg(BaseReg, RegState::Kill).addImm(ThisVal) .addImm((unsigned)Pred).addReg(PredReg).addReg(0) .setMIFlags(MIFlags); BaseReg = DestReg; } } bool llvm::tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget, MachineFunction &MF, MachineInstr *MI, unsigned NumBytes) { // This optimisation potentially adds lots of load and store // micro-operations, it's only really a great benefit to code-size. if (!MF.getFunction()->optForMinSize()) return false; // If only one register is pushed/popped, LLVM can use an LDR/STR // instead. We can't modify those so make sure we're dealing with an // instruction we understand. bool IsPop = isPopOpcode(MI->getOpcode()); bool IsPush = isPushOpcode(MI->getOpcode()); if (!IsPush && !IsPop) return false; bool IsVFPPushPop = MI->getOpcode() == ARM::VSTMDDB_UPD || MI->getOpcode() == ARM::VLDMDIA_UPD; bool IsT1PushPop = MI->getOpcode() == ARM::tPUSH || MI->getOpcode() == ARM::tPOP || MI->getOpcode() == ARM::tPOP_RET; assert((IsT1PushPop || (MI->getOperand(0).getReg() == ARM::SP && MI->getOperand(1).getReg() == ARM::SP)) && ""trying to fold sp update into non-sp-updating push/pop""); // The VFP push & pop act on D-registers, so we can only fold an adjustment // by a multiple of 8 bytes in correctly. Similarly rN is 4-bytes. Don't try // if this is violated. if (NumBytes % (IsVFPPushPop ? 8 : 4) != 0) return false; // ARM and Thumb2 push/pop insts have explicit ""sp, sp"" operands (+ // pred) so the list starts at 4. Thumb1 starts after the predicate. int RegListIdx = IsT1PushPop ? 2 : 4; // Calculate the space we'll need in terms of registers. unsigned FirstReg = MI->getOperand(RegListIdx).getReg(); unsigned RD0Reg, RegsNeeded; if (IsVFPPushPop) { RD0Reg = ARM::D0; RegsNeeded = NumBytes / 8; } else { RD0Reg = ARM::R0; RegsNeeded = NumBytes / 4; } // We're going to have to strip all list operands off before // re-adding them since the order matters, so save the existing ones // for later. SmallVector RegList; for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) RegList.push_back(MI->getOperand(i)); const TargetRegisterInfo *TRI = MF.getRegInfo().getTargetRegisterInfo(); const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF); // Now try to find enough space in the reglist to allocate NumBytes. for (unsigned CurReg = FirstReg - 1; CurReg >= RD0Reg && RegsNeeded; --CurReg) { if (!IsPop) { // Pushing any register is completely harmless, mark the // register involved as undef since we don't care about it in // the slightest. RegList.push_back(MachineOperand::CreateReg(CurReg, false, false, false, false, true)); --RegsNeeded; continue; } // However, we can only pop an extra register if it's not live. For // registers live within the function we might clobber a return value // register; the other way a register can be live here is if it's // callee-saved. if (isCalleeSavedRegister(CurReg, CSRegs) || MI->getParent()->computeRegisterLiveness(TRI, CurReg, MI) != MachineBasicBlock::LQR_Dead) { // VFP pops don't allow holes in the register list, so any skip is fatal // for our transformation. GPR pops do, so we should just keep looking. if (IsVFPPushPop) return false; else continue; } // Mark the unimportant registers as in the POP. RegList.push_back(MachineOperand::CreateReg(CurReg, true, false, false, true)); --RegsNeeded; } if (RegsNeeded > 0) return false; // Finally we know we can profitably perform the optimisation so go // ahead: strip all existing registers off and add them back again // in the right order. for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) MI->RemoveOperand(i); // Add the complete list back in. MachineInstrBuilder MIB(MF, &*MI); for (int i = RegList.size() - 1; i >= 0; --i) MIB.addOperand(RegList[i]); return true; } bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx, unsigned FrameReg, int &Offset, const ARMBaseInstrInfo &TII) { unsigned Opcode = MI.getOpcode(); const MCInstrDesc &Desc = MI.getDesc(); unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask); bool isSub = false; // Memory operands in inline assembly always use AddrMode2. if (Opcode == ARM::INLINEASM) AddrMode = ARMII::AddrMode2; if (Opcode == ARM::ADDri) { Offset += MI.getOperand(FrameRegIdx+1).getImm(); if (Offset == 0) { // Turn it into a move. MI.setDesc(TII.get(ARM::MOVr)); MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false); MI.RemoveOperand(FrameRegIdx+1); Offset = 0; return true; } else if (Offset < 0) { Offset = -Offset; isSub = true; MI.setDesc(TII.get(ARM::SUBri)); } // Common case: small offset, fits into instruction. if (ARM_AM::getSOImmVal(Offset) != -1) { // Replace the FrameIndex with sp / fp MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false); MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset); Offset = 0; return true; } // Otherwise, pull as much of the immedidate into this ADDri/SUBri // as possible. unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset); unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt); // We will handle these bits from offset, clear them. Offset &= ~ThisImmVal; // Get the properly encoded SOImmVal field. assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 && ""Bit extraction didn't work?""); MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal); } else { unsigned ImmIdx = 0; int InstrOffs = 0; unsigned NumBits = 0; unsigned Scale = 1; switch (AddrMode) { case ARMII::AddrMode_i12: { ImmIdx = FrameRegIdx + 1; InstrOffs = MI.getOperand(ImmIdx).getImm(); NumBits = 12; break; } case ARMII::AddrMode2: { ImmIdx = FrameRegIdx+2; InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm()); if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub) InstrOffs *= -1; NumBits = 12; break; } case ARMII::AddrMode3: { ImmIdx = FrameRegIdx+2; InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm()); if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub) InstrOffs *= -1; NumBits = 8; break; } case ARMII::AddrMode4: case ARMII::AddrMode6: // Can't fold any offset even if it's zero. return false; case ARMII::AddrMode5: { ImmIdx = FrameRegIdx+1; InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm()); if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub) InstrOffs *= -1; NumBits = 8; Scale = 4; break; } default: llvm_unreachable(""Unsupported addressing mode!""); } Offset += InstrOffs * Scale; assert((Offset & (Scale-1)) == 0 && ""Can't encode this offset!""); if (Offset < 0) { Offset = -Offset; isSub = true; } // Attempt to fold address comp. if opcode has offset bits if (NumBits > 0) { // Common case: small offset, fits into instruction. MachineOperand &ImmOp = MI.getOperand(ImmIdx); int ImmedOffset = Offset / Scale; unsigned Mask = (1 << NumBits) - 1; if ((unsigned)Offset <= Mask * Scale) { // Replace the FrameIndex with sp MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false); // FIXME: When addrmode2 goes away, this will simplify (like the // T2 version), as the LDR.i12 versions don't need the encoding // tricks for the offset value. if (isSub) { if (AddrMode == ARMII::AddrMode_i12) ImmedOffset = -ImmedOffset; else ImmedOffset |= 1 << NumBits; } ImmOp.ChangeToImmediate(ImmedOffset); Offset = 0; return true; } // Otherwise, it didn't fit. Pull in what we can to simplify the immed. ImmedOffset = ImmedOffset & Mask; if (isSub) { if (AddrMode == ARMII::AddrMode_i12) ImmedOffset = -ImmedOffset; else ImmedOffset |= 1 << NumBits; } ImmOp.ChangeToImmediate(ImmedOffset); Offset &= ~(Mask*Scale); } } Offset = (isSub) ? -Offset : Offset; return Offset == 0; } /// analyzeCompare - For a comparison instruction, return the source registers /// in SrcReg and SrcReg2 if having two register operands, and the value it /// compares against in CmpValue. Return true if the comparison instruction /// can be analyzed. bool ARMBaseInstrInfo:: analyzeCompare(const MachineInstr *MI, unsigned &SrcReg, unsigned &SrcReg2, int &CmpMask, int &CmpValue) const { switch (MI->getOpcode()) { default: break; case ARM::CMPri: case ARM::t2CMPri: SrcReg = MI->getOperand(0).getReg(); SrcReg2 = 0; CmpMask = ~0; CmpValue = MI->getOperand(1).getImm(); return true; case ARM::CMPrr: case ARM::t2CMPrr: SrcReg = MI->getOperand(0).getReg(); SrcReg2 = MI->getOperand(1).getReg(); CmpMask = ~0; CmpValue = 0; return true; case ARM::TSTri: case ARM::t2TSTri: SrcReg = MI->getOperand(0).getReg(); SrcReg2 = 0; CmpMask = MI->getOperand(1).getImm(); CmpValue = 0; return true; } return false; } /// isSuitableForMask - Identify a suitable 'and' instruction that /// operates on the given source register and applies the same mask /// as a 'tst' instruction. Provide a limited look-through for copies. /// When successful, MI will hold the found instruction. static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg, int CmpMask, bool CommonUse) { switch (MI->getOpcode()) { case ARM::ANDri: case ARM::t2ANDri: if (CmpMask != MI->getOperand(2).getImm()) return false; if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg()) return true; break; } return false; } /// getSwappedCondition - assume the flags are set by MI(a,b), return /// the condition code if we modify the instructions such that flags are /// set by MI(b,a). inline static ARMCC::CondCodes getSwappedCondition(ARMCC::CondCodes CC) { switch (CC) { default: return ARMCC::AL; case ARMCC::EQ: return ARMCC::EQ; case ARMCC::NE: return ARMCC::NE; case ARMCC::HS: return ARMCC::LS; case ARMCC::LO: return ARMCC::HI; case ARMCC::HI: return ARMCC::LO; case ARMCC::LS: return ARMCC::HS; case ARMCC::GE: return ARMCC::LE; case ARMCC::LT: return ARMCC::GT; case ARMCC::GT: return ARMCC::LT; case ARMCC::LE: return ARMCC::GE; } } /// isRedundantFlagInstr - check whether the first instruction, whose only /// purpose is to update flags, can be made redundant. /// CMPrr can be made redundant by SUBrr if the operands are the same. /// CMPri can be made redundant by SUBri if the operands are the same. /// This function can be extended later on. inline static bool isRedundantFlagInstr(MachineInstr *CmpI, unsigned SrcReg, unsigned SrcReg2, int ImmValue, MachineInstr *OI) { if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) && (OI->getOpcode() == ARM::SUBrr || OI->getOpcode() == ARM::t2SUBrr) && ((OI->getOperand(1).getReg() == SrcReg && OI->getOperand(2).getReg() == SrcReg2) || (OI->getOperand(1).getReg() == SrcReg2 && OI->getOperand(2).getReg() == SrcReg))) return true; if ((CmpI->getOpcode() == ARM::CMPri || CmpI->getOpcode() == ARM::t2CMPri) && (OI->getOpcode() == ARM::SUBri || OI->getOpcode() == ARM::t2SUBri) && OI->getOperand(1).getReg() == SrcReg && OI->getOperand(2).getImm() == ImmValue) return true; return false; } /// optimizeCompareInstr - Convert the instruction supplying the argument to the /// comparison into one that sets the zero bit in the flags register; /// Remove a redundant Compare instruction if an earlier instruction can set the /// flags in the same way as Compare. /// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two /// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the /// condition code of instructions which use the flags. bool ARMBaseInstrInfo:: optimizeCompareInstr(MachineInstr *CmpInstr, unsigned SrcReg, unsigned SrcReg2, int CmpMask, int CmpValue, const MachineRegisterInfo *MRI) const { // Get the unique definition of SrcReg. MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg); if (!MI) return false; // Masked compares sometimes use the same register as the corresponding 'and'. if (CmpMask != ~0) { if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(*MI)) { MI = nullptr; for (MachineRegisterInfo::use_instr_iterator UI = MRI->use_instr_begin(SrcReg), UE = MRI->use_instr_end(); UI != UE; ++UI) { if (UI->getParent() != CmpInstr->getParent()) continue; MachineInstr *PotentialAND = &*UI; if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) || isPredicated(*PotentialAND)) continue; MI = PotentialAND; break; } if (!MI) return false; } } // Get ready to iterate backward from CmpInstr. MachineBasicBlock::iterator I = CmpInstr, E = MI, B = CmpInstr->getParent()->begin(); // Early exit if CmpInstr is at the beginning of the BB. if (I == B) return false; // There are two possible candidates which can be changed to set CPSR: // One is MI, the other is a SUB instruction. // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1). // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue). MachineInstr *Sub = nullptr; if (SrcReg2 != 0) // MI is not a candidate for CMPrr. MI = nullptr; else if (MI->getParent() != CmpInstr->getParent() || CmpValue != 0) { // Conservatively refuse to convert an instruction which isn't in the same // BB as the comparison. // For CMPri w/ CmpValue != 0, a Sub may still be a candidate. // Thus we cannot return here. if (CmpInstr->getOpcode() == ARM::CMPri || CmpInstr->getOpcode() == ARM::t2CMPri) MI = nullptr; else return false; } // Check that CPSR isn't set between the comparison instruction and the one we // want to change. At the same time, search for Sub. const TargetRegisterInfo *TRI = &getRegisterInfo(); --I; for (; I != E; --I) { const MachineInstr &Instr = *I; if (Instr.modifiesRegister(ARM::CPSR, TRI) || Instr.readsRegister(ARM::CPSR, TRI)) // This instruction modifies or uses CPSR after the one we want to // change. We can't do this transformation. return false; // Check whether CmpInstr can be made redundant by the current instruction. if (isRedundantFlagInstr(CmpInstr, SrcReg, SrcReg2, CmpValue, &*I)) { Sub = &*I; break; } if (I == B) // The 'and' is below the comparison instruction. return false; } // Return false if no candidates exist. if (!MI && !Sub) return false; // The single candidate is called MI. if (!MI) MI = Sub; // We can't use a predicated instruction - it doesn't always write the flags. if (isPredicated(*MI)) return false; switch (MI->getOpcode()) { default: break; case ARM::RSBrr: case ARM::RSBri: case ARM::RSCrr: case ARM::RSCri: case ARM::ADDrr: case ARM::ADDri: case ARM::ADCrr: case ARM::ADCri: case ARM::SUBrr: case ARM::SUBri: case ARM::SBCrr: case ARM::SBCri: case ARM::t2RSBri: case ARM::t2ADDrr: case ARM::t2ADDri: case ARM::t2ADCrr: case ARM::t2ADCri: case ARM::t2SUBrr: case ARM::t2SUBri: case ARM::t2SBCrr: case ARM::t2SBCri: case ARM::ANDrr: case ARM::ANDri: case ARM::t2ANDrr: case ARM::t2ANDri: case ARM::ORRrr: case ARM::ORRri: case ARM::t2ORRrr: case ARM::t2ORRri: case ARM::EORrr: case ARM::EORri: case ARM::t2EORrr: case ARM::t2EORri: { // Scan forward for the use of CPSR // When checking against MI: if it's a conditional code that requires // checking of the V bit or C bit, then this is not safe to do. // It is safe to remove CmpInstr if CPSR is redefined or killed. // If we are done with the basic block, we need to check whether CPSR is // live-out. SmallVector, 4> OperandsToUpdate; bool isSafe = false; I = CmpInstr; E = CmpInstr->getParent()->end(); while (!isSafe && ++I != E) { const MachineInstr &Instr = *I; for (unsigned IO = 0, EO = Instr.getNumOperands(); !isSafe && IO != EO; ++IO) { const MachineOperand &MO = Instr.getOperand(IO); if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) { isSafe = true; break; } if (!MO.isReg() || MO.getReg() != ARM::CPSR) continue; if (MO.isDef()) { isSafe = true; break; } // Condition code is after the operand before CPSR except for VSELs. ARMCC::CondCodes CC; bool IsInstrVSel = true; switch (Instr.getOpcode()) { default: IsInstrVSel = false; CC = (ARMCC::CondCodes)Instr.getOperand(IO - 1).getImm(); break; case ARM::VSELEQD: case ARM::VSELEQS: CC = ARMCC::EQ; break; case ARM::VSELGTD: case ARM::VSELGTS: CC = ARMCC::GT; break; case ARM::VSELGED: case ARM::VSELGES: CC = ARMCC::GE; break; case ARM::VSELVSS: case ARM::VSELVSD: CC = ARMCC::VS; break; } if (Sub) { ARMCC::CondCodes NewCC = getSwappedCondition(CC); if (NewCC == ARMCC::AL) return false; // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based // on CMP needs to be updated to be based on SUB. // Push the condition code operands to OperandsToUpdate. // If it is safe to remove CmpInstr, the condition code of these // operands will be modified. if (SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 && Sub->getOperand(2).getReg() == SrcReg) { // VSel doesn't support condition code update. if (IsInstrVSel) return false; OperandsToUpdate.push_back( std::make_pair(&((*I).getOperand(IO - 1)), NewCC)); } } else { // No Sub, so this is x = y, z; cmp x, 0. switch (CC) { case ARMCC::EQ: // Z case ARMCC::NE: // Z case ARMCC::MI: // N case ARMCC::PL: // N case ARMCC::AL: // none // CPSR can be used multiple times, we should continue. break; case ARMCC::HS: // C case ARMCC::LO: // C case ARMCC::VS: // V case ARMCC::VC: // V case ARMCC::HI: // C Z case ARMCC::LS: // C Z case ARMCC::GE: // N V case ARMCC::LT: // N V case ARMCC::GT: // Z N V case ARMCC::LE: // Z N V // The instruction uses the V bit or C bit which is not safe. return false; } } } } // If CPSR is not killed nor re-defined, we should check whether it is // live-out. If it is live-out, do not optimize. if (!isSafe) { MachineBasicBlock *MBB = CmpInstr->getParent(); for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) if ((*SI)->isLiveIn(ARM::CPSR)) return false; } // Toggle the optional operand to CPSR. MI->getOperand(5).setReg(ARM::CPSR); MI->getOperand(5).setIsDef(true); assert(!isPredicated(*MI) && ""Can't use flags from predicated instruction""); CmpInstr->eraseFromParent(); // Modify the condition code of operands in OperandsToUpdate. // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc. for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++) OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second); return true; } } return false; } bool ARMBaseInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI, unsigned Reg, MachineRegisterInfo *MRI) const { // Fold large immediates into add, sub, or, xor. unsigned [MASK] = DefMI->getOpcode(); if ( [MASK] != ARM::t2MOVi32imm && [MASK] != ARM::MOVi32imm) return false; if (!DefMI->getOperand(1).isImm()) // Could be t2MOVi32imm return false; if (!MRI->hasOneNonDBGUse(Reg)) return false; const MCInstrDesc &DefMCID = DefMI->getDesc(); if (DefMCID.hasOptionalDef()) { unsigned NumOps = DefMCID.getNumOperands(); const MachineOperand &MO = DefMI->getOperand(NumOps-1); if (MO.getReg() == ARM::CPSR && !MO.isDead()) // If DefMI defines CPSR and it is not dead, it's obviously not safe // to delete DefMI. return false; } const MCInstrDesc &UseMCID = UseMI->getDesc(); if (UseMCID.hasOptionalDef()) { unsigned NumOps = UseMCID.getNumOperands(); if (UseMI->getOperand(NumOps-1).getReg() == ARM::CPSR) // If the instruction sets the flag, do not attempt this optimization // since it may change the semantics of the code. return false; } unsigned UseOpc = UseMI->getOpcode(); unsigned NewUseOpc = 0; uint32_t ImmVal = (uint32_t)DefMI->getOperand(1).getImm(); uint32_t SOImmValV1 = 0, SOImmValV2 = 0; bool Commute = false; switch (UseOpc) { default: return false; case ARM::SUBrr: case ARM::ADDrr: case ARM::ORRrr: case ARM::EORrr: case ARM::t2SUBrr: case ARM::t2ADDrr: case ARM::t2ORRrr: case ARM::t2EORrr: { Commute = UseMI->getOperand(2).getReg() != Reg; switch (UseOpc) { default: break; case ARM::ADDrr: case ARM::SUBrr: { if (UseOpc == ARM::SUBrr && Commute) return false; // ADD/SUB are special because they're essentially the same operation, so // we can handle a larger range of immediates. if (ARM_AM::isSOImmTwoPartVal(ImmVal)) NewUseOpc = UseOpc == ARM::ADDrr ? ARM::ADDri : ARM::SUBri; else if (ARM_AM::isSOImmTwoPartVal(-ImmVal)) { ImmVal = -ImmVal; NewUseOpc = UseOpc == ARM::ADDrr ? ARM::SUBri : ARM::ADDri; } else return false; SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal); SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal); break; } case ARM::ORRrr: case ARM::EORrr: { if (!ARM_AM::isSOImmTwoPartVal(ImmVal)) return false; SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal); SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal); switch (UseOpc) { default: break; case ARM::ORRrr: NewUseOpc = ARM::ORRri; break; case ARM::EORrr: NewUseOpc = ARM::EORri; break; } break; } case ARM::t2ADDrr: case ARM::t2SUBrr: { if (UseOpc == ARM::t2SUBrr && Commute) return false; // ADD/SUB are special because they're essentially the same operation, so // we can handle a larger range of immediates. if (ARM_AM::isT2SOImmTwoPartVal(ImmVal)) NewUseOpc = UseOpc == ARM::t2ADDrr ? ARM::t2ADDri : ARM::t2SUBri; else if (ARM_AM::isT2SOImmTwoPartVal(-ImmVal)) { ImmVal = -ImmVal; NewUseOpc = UseOpc == ARM::t2ADDrr ? ARM::t2SUBri : ARM::t2ADDri; } else return false; SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal); SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal); break; } case ARM::t2ORRrr: case ARM::t2EORrr: { if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal)) return false; SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal); SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal); switch (UseOpc) { default: break; case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break; case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break; } break; } } } } unsigned OpIdx = Commute ? 2 : 1; unsigned Reg1 = UseMI->getOperand(OpIdx).getReg(); bool isKill = UseMI->getOperand(OpIdx).isKill(); unsigned NewReg = MRI->createVirtualRegister(MRI->getRegClass(Reg)); AddDefaultCC(AddDefaultPred(BuildMI(*UseMI->getParent(), UseMI, UseMI->getDebugLoc(), get(NewUseOpc), NewReg) .addReg(Reg1, getKillRegState(isKill)) .addImm(SOImmValV1))); UseMI->setDesc(get(NewUseOpc)); UseMI->getOperand(1).setReg(NewReg); UseMI->getOperand(1).setIsKill(); UseMI->getOperand(2).ChangeToImmediate(SOImmValV2); DefMI->eraseFromParent(); return true; } static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData, const MachineInstr *MI) { switch (MI->getOpcode()) { default: { const MCInstrDesc &Desc = MI->getDesc(); int UOps = ItinData->getNumMicroOps(Desc.getSchedClass()); assert(UOps >= 0 && ""bad # UOps""); return UOps; } case ARM::LDRrs: case ARM::LDRBrs: case ARM::STRrs: case ARM::STRBrs: { unsigned ShOpVal = MI->getOperand(3).getImm(); bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); if (!isSub && (ShImm == 0 || ((ShImm == 1 || ShImm == 2 || ShImm == 3) && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) return 1; return 2; } case ARM::LDRH: case ARM::STRH: { if (!MI->getOperand(2).getReg()) return 1; unsigned ShOpVal = MI->getOperand(3).getImm(); bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); if (!isSub && (ShImm == 0 || ((ShImm == 1 || ShImm == 2 || ShImm == 3) && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) return 1; return 2; } case ARM::LDRSB: case ARM::LDRSH: return (ARM_AM::getAM3Op(MI->getOperand(3).getImm()) == ARM_AM::sub) ? 3:2; case ARM::LDRSB_POST: case ARM::LDRSH_POST: { unsigned Rt = MI->getOperand(0).getReg(); unsigned Rm = MI->getOperand(3).getReg(); return (Rt == Rm) ? 4 : 3; } case ARM::LDR_PRE_REG: case ARM::LDRB_PRE_REG: { unsigned Rt = MI->getOperand(0).getReg(); unsigned Rm = MI->getOperand(3).getReg(); if (Rt == Rm) return 3; unsigned ShOpVal = MI->getOperand(4).getImm(); bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); if (!isSub && (ShImm == 0 || ((ShImm == 1 || ShImm == 2 || ShImm == 3) && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) return 2; return 3; } case ARM::STR_PRE_REG: case ARM::STRB_PRE_REG: { unsigned ShOpVal = MI->getOperand(4).getImm(); bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); if (!isSub && (ShImm == 0 || ((ShImm == 1 || ShImm == 2 || ShImm == 3) && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) return 2; return 3; } case ARM::LDRH_PRE: case ARM::STRH_PRE: { unsigned Rt = MI->getOperand(0).getReg(); unsigned Rm = MI->getOperand(3).getReg(); if (!Rm) return 2; if (Rt == Rm) return 3; return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub) ? 3 : 2; } case ARM::LDR_POST_REG: case ARM::LDRB_POST_REG: case ARM::LDRH_POST: { unsigned Rt = MI->getOperand(0).getReg(); unsigned Rm = MI->getOperand(3).getReg(); return (Rt == Rm) ? 3 : 2; } case ARM::LDR_PRE_IMM: case ARM::LDRB_PRE_IMM: case ARM::LDR_POST_IMM: case ARM::LDRB_POST_IMM: case ARM::STRB_POST_IMM: case ARM::STRB_POST_REG: case ARM::STRB_PRE_IMM: case ARM::STRH_POST: case ARM::STR_POST_IMM: case ARM::STR_POST_REG: case ARM::STR_PRE_IMM: return 2; case ARM::LDRSB_PRE: case ARM::LDRSH_PRE: { unsigned Rm = MI->getOperand(3).getReg(); if (Rm == 0) return 3; unsigned Rt = MI->getOperand(0).getReg(); if (Rt == Rm) return 4; unsigned ShOpVal = MI->getOperand(4).getImm(); bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); if (!isSub && (ShImm == 0 || ((ShImm == 1 || ShImm == 2 || ShImm == 3) && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) return 3; return 4; } case ARM::LDRD: { unsigned Rt = MI->getOperand(0).getReg(); unsigned Rn = MI->getOperand(2).getReg(); unsigned Rm = MI->getOperand(3).getReg(); if (Rm) return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub) ?4:3; return (Rt == Rn) ? 3 : 2; } case ARM::STRD: { unsigned Rm = MI->getOperand(3).getReg(); if (Rm) return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub) ?4:3; return 2; } case ARM::LDRD_POST: case ARM::t2LDRD_POST: return 3; case ARM::STRD_POST: case ARM::t2STRD_POST: return 4; case ARM::LDRD_PRE: { unsigned Rt = MI->getOperand(0).getReg(); unsigned Rn = MI->getOperand(3).getReg(); unsigned Rm = MI->getOperand(4).getReg(); if (Rm) return (ARM_AM::getAM3Op(MI->getOperand(5).getImm()) == ARM_AM::sub) ?5:4; return (Rt == Rn) ? 4 : 3; } case ARM::t2LDRD_PRE: { unsigned Rt = MI->getOperand(0).getReg(); unsigned Rn = MI->getOperand(3).getReg(); return (Rt == Rn) ? 4 : 3; } case ARM::STRD_PRE: { unsigned Rm = MI->getOperand(4).getReg(); if (Rm) return (ARM_AM::getAM3Op(MI->getOperand(5).getImm()) == ARM_AM::sub) ?5:4; return 3; } case ARM::t2STRD_PRE: return 3; case ARM::t2LDR_POST: case ARM::t2LDRB_POST: case ARM::t2LDRB_PRE: case ARM::t2LDRSBi12: case ARM::t2LDRSBi8: case ARM::t2LDRSBpci: case ARM::t2LDRSBs: case ARM::t2LDRH_POST: case ARM::t2LDRH_PRE: case ARM::t2LDRSBT: case ARM::t2LDRSB_POST: case ARM::t2LDRSB_PRE: case ARM::t2LDRSH_POST: case ARM::t2LDRSH_PRE: case ARM::t2LDRSHi12: case ARM::t2LDRSHi8: case ARM::t2LDRSHpci: case ARM::t2LDRSHs: return 2; case ARM::t2LDRDi8: { unsigned Rt = MI->getOperand(0).getReg(); unsigned Rn = MI->getOperand(2).getReg(); return (Rt == Rn) ? 3 : 2; } case ARM::t2STRB_POST: case ARM::t2STRB_PRE: case ARM::t2STRBs: case ARM::t2STRDi8: case ARM::t2STRH_POST: case ARM::t2STRH_PRE: case ARM::t2STRHs: case ARM::t2STR_POST: case ARM::t2STR_PRE: case ARM::t2STRs: return 2; } } // Return the number of 32-bit words loaded by LDM or stored by STM. If this // can't be easily determined return 0 (missing MachineMemOperand). // // FIXME: The current MachineInstr design does not support relying on machine // mem operands to determine the width of a memory access. Instead, we expect // the target to provide this information based on the instruction opcode and // operands. However, using MachineMemOperand is the best solution now for // two reasons: // // 1) getNumMicroOps tries to infer LDM memory width from the total number of MI // operands. This is much more dangerous than using the MachineMemOperand // sizes because CodeGen passes can insert/remove optional machine operands. In // fact, it's totally incorrect for preRA passes and appears to be wrong for // postRA passes as well. // // 2) getNumLDMAddresses is only used by the scheduling machine model and any // machine model that calls this should handle the unknown (zero size) case. // // Long term, we should require a target hook that verifies MachineMemOperand // sizes during MC lowering. That target hook should be local to MC lowering // because we can't ensure that it is aware of other MI forms. Doing this will // ensure that MachineMemOperands are correctly propagated through all passes. unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr *MI) const { unsigned Size = 0; for (MachineInstr::mmo_iterator I = MI->memoperands_begin(), E = MI->memoperands_end(); I != E; ++I) { Size += (*I)->getSize(); } return Size / 4; } unsigned ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData, const MachineInstr *MI) const { if (!ItinData || ItinData->isEmpty()) return 1; const MCInstrDesc &Desc = MI->getDesc(); unsigned Class = Desc.getSchedClass(); int ItinUOps = ItinData->getNumMicroOps(Class); if (ItinUOps >= 0) { if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore())) return getNumMicroOpsSwiftLdSt(ItinData, MI); return ItinUOps; } unsigned Opc = MI->getOpcode(); switch (Opc) { default: llvm_unreachable(""Unexpected multi-uops instruction!""); case ARM::VLDMQIA: case ARM::VSTMQIA: return 2; // The number of uOps for load / store multiple are determined by the number // registers. // // On Cortex-A8, each pair of register loads / stores can be scheduled on the // same cycle. The scheduling for the first load / store must be done // separately by assuming the address is not 64-bit aligned. // // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address // is not 64-bit aligned, then AGU would take an extra cycle. For VFP / NEON // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1. case ARM::VLDMDIA: case ARM::VLDMDIA_UPD: case ARM::VLDMDDB_UPD: case ARM::VLDMSIA: case ARM::VLDMSIA_UPD: case ARM::VLDMSDB_UPD: case ARM::VSTMDIA: case ARM::VSTMDIA_UPD: case ARM::VSTMDDB_UPD: case ARM::VSTMSIA: case ARM::VSTMSIA_UPD: case ARM::VSTMSDB_UPD: { unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands(); return (NumRegs / 2) + (NumRegs % 2) + 1; } case ARM::LDMIA_RET: case ARM::LDMIA: case ARM::LDMDA: case ARM::LDMDB: case ARM::LDMIB: case ARM::LDMIA_UPD: case ARM::LDMDA_UPD: case ARM::LDMDB_UPD: case ARM::LDMIB_UPD: case ARM::STMIA: case ARM::STMDA: case ARM::STMDB: case ARM::STMIB: case ARM::STMIA_UPD: case ARM::STMDA_UPD: case ARM::STMDB_UPD: case ARM::STMIB_UPD: case ARM::tLDMIA: case ARM::tLDMIA_UPD: case ARM::tSTMIA_UPD: case ARM::tPOP_RET: case ARM::tPOP: case ARM::tPUSH: case ARM::t2LDMIA_RET: case ARM::t2LDMIA: case ARM::t2LDMDB: case ARM::t2LDMIA_UPD: case ARM::t2LDMDB_UPD: case ARM::t2STMIA: case ARM::t2STMDB: case ARM::t2STMIA_UPD: case ARM::t2STMDB_UPD: { unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands() + 1; if (Subtarget.isSwift()) { int UOps = 1 + NumRegs; // One for address computation, one for each ld / st. switch (Opc) { default: break; case ARM::VLDMDIA_UPD: case ARM::VLDMDDB_UPD: case ARM::VLDMSIA_UPD: case ARM::VLDMSDB_UPD: case ARM::VSTMDIA_UPD: case ARM::VSTMDDB_UPD: case ARM::VSTMSIA_UPD: case ARM::VSTMSDB_UPD: case ARM::LDMIA_UPD: case ARM::LDMDA_UPD: case ARM::LDMDB_UPD: case ARM::LDMIB_UPD: case ARM::STMIA_UPD: case ARM::STMDA_UPD: case ARM::STMDB_UPD: case ARM::STMIB_UPD: case ARM::tLDMIA_UPD: case ARM::tSTMIA_UPD: case ARM::t2LDMIA_UPD: case ARM::t2LDMDB_UPD: case ARM::t2STMIA_UPD: case ARM::t2STMDB_UPD: ++UOps; // One for base register writeback. break; case ARM::LDMIA_RET: case ARM::tPOP_RET: case ARM::t2LDMIA_RET: UOps += 2; // One for base reg wb, one for write to pc. break; } return UOps; } else if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { if (NumRegs < 4) return 2; // 4 registers would be issued: 2, 2. // 5 registers would be issued: 2, 2, 1. int A8UOps = (NumRegs / 2); if (NumRegs % 2) ++A8UOps; return A8UOps; } else if (Subtarget.isLikeA9()) { int A9UOps = (NumRegs / 2); // If there are odd number of registers or if it's not 64-bit aligned, // then it takes an extra AGU (Address Generation Unit) cycle. if ((NumRegs % 2) || !MI->hasOneMemOperand() || (*MI->memoperands_begin())->getAlignment() < 8) ++A9UOps; return A9UOps; } else { // Assume the worst. return NumRegs; } } } } int ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData, const MCInstrDesc &DefMCID, unsigned DefClass, unsigned DefIdx, unsigned DefAlign) const { int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1; if (RegNo <= 0) // Def is the address writeback. return ItinData->getOperandCycle(DefClass, DefIdx); int DefCycle; if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { // (regno / 2) + (regno % 2) + 1 DefCycle = RegNo / 2 + 1; if (RegNo % 2) ++DefCycle; } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { DefCycle = RegNo; bool isSLoad = false; switch (DefMCID.getOpcode()) { default: break; case ARM::VLDMSIA: case ARM::VLDMSIA_UPD: case ARM::VLDMSDB_UPD: isSLoad = true; break; } // If there are odd number of 'S' registers or if it's not 64-bit aligned, // then it takes an extra cycle. if ((isSLoad && (RegNo % 2)) || DefAlign < 8) ++DefCycle; } else { // Assume the worst. DefCycle = RegNo + 2; } return DefCycle; } int ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData, const MCInstrDesc &DefMCID, unsigned DefClass, unsigned DefIdx, unsigned DefAlign) const { int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1; if (RegNo <= 0) // Def is the address writeback. return ItinData->getOperandCycle(DefClass, DefIdx); int DefCycle; if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { // 4 registers would be issued: 1, 2, 1. // 5 registers would be issued: 1, 2, 2. DefCycle = RegNo / 2; if (DefCycle < 1) DefCycle = 1; // Result latency is issue cycle + 2: E2. DefCycle += 2; } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { DefCycle = (RegNo / 2); // If there are odd number of registers or if it's not 64-bit aligned, // then it takes an extra AGU (Address Generation Unit) cycle. if ((RegNo % 2) || DefAlign < 8) ++DefCycle; // Result latency is AGU cycles + 2. DefCycle += 2; } else { // Assume the worst. DefCycle = RegNo + 2; } return DefCycle; } int ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData, const MCInstrDesc &UseMCID, unsigned UseClass, unsigned UseIdx, unsigned UseAlign) const { int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1; if (RegNo <= 0) return ItinData->getOperandCycle(UseClass, UseIdx); int UseCycle; if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { // (regno / 2) + (regno % 2) + 1 UseCycle = RegNo / 2 + 1; if (RegNo % 2) ++UseCycle; } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { UseCycle = RegNo; bool isSStore = false; switch (UseMCID.getOpcode()) { default: break; case ARM::VSTMSIA: case ARM::VSTMSIA_UPD: case ARM::VSTMSDB_UPD: isSStore = true; break; } // If there are odd number of 'S' registers or if it's not 64-bit aligned, // then it takes an extra cycle. if ((isSStore && (RegNo % 2)) || UseAlign < 8) ++UseCycle; } else { // Assume the worst. UseCycle = RegNo + 2; } return UseCycle; } int ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData, const MCInstrDesc &UseMCID, unsigned UseClass, unsigned UseIdx, unsigned UseAlign) const { int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1; if (RegNo <= 0) return ItinData->getOperandCycle(UseClass, UseIdx); int UseCycle; if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { UseCycle = RegNo / 2; if (UseCycle < 2) UseCycle = 2; // Read in E3. UseCycle += 2; } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { UseCycle = (RegNo / 2); // If there are odd number of registers or if it's not 64-bit aligned, // then it takes an extra AGU (Address Generation Unit) cycle. if ((RegNo % 2) || UseAlign < 8) ++UseCycle; } else { // Assume the worst. UseCycle = 1; } return UseCycle; } int ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, const MCInstrDesc &DefMCID, unsigned DefIdx, unsigned DefAlign, const MCInstrDesc &UseMCID, unsigned UseIdx, unsigned UseAlign) const { unsigned DefClass = DefMCID.getSchedClass(); unsigned UseClass = UseMCID.getSchedClass(); if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands()) return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx); // This may be a def / use of a variable_ops instruction, the operand // latency might be determinable dynamically. Let the target try to // figure it out. int DefCycle = -1; bool LdmBypass = false; switch (DefMCID.getOpcode()) { default: DefCycle = ItinData->getOperandCycle(DefClass, DefIdx); break; case ARM::VLDMDIA: case ARM::VLDMDIA_UPD: case ARM::VLDMDDB_UPD: case ARM::VLDMSIA: case ARM::VLDMSIA_UPD: case ARM::VLDMSDB_UPD: DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign); break; case ARM::LDMIA_RET: case ARM::LDMIA: case ARM::LDMDA: case ARM::LDMDB: case ARM::LDMIB: case ARM::LDMIA_UPD: case ARM::LDMDA_UPD: case ARM::LDMDB_UPD: case ARM::LDMIB_UPD: case ARM::tLDMIA: case ARM::tLDMIA_UPD: case ARM::tPUSH: case ARM::t2LDMIA_RET: case ARM::t2LDMIA: case ARM::t2LDMDB: case ARM::t2LDMIA_UPD: case ARM::t2LDMDB_UPD: LdmBypass = 1; DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign); break; } if (DefCycle == -1) // We can't seem to determine the result latency of the def, assume it's 2. DefCycle = 2; int UseCycle = -1; switch (UseMCID.getOpcode()) { default: UseCycle = ItinData->getOperandCycle(UseClass, UseIdx); break; case ARM::VSTMDIA: case ARM::VSTMDIA_UPD: case ARM::VSTMDDB_UPD: case ARM::VSTMSIA: case ARM::VSTMSIA_UPD: case ARM::VSTMSDB_UPD: UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign); break; case ARM::STMIA: case ARM::STMDA: case ARM::STMDB: case ARM::STMIB: case ARM::STMIA_UPD: case ARM::STMDA_UPD: case ARM::STMDB_UPD: case ARM::STMIB_UPD: case ARM::tSTMIA_UPD: case ARM::tPOP_RET: case ARM::tPOP: case ARM::t2STMIA: case ARM::t2STMDB: case ARM::t2STMIA_UPD: case ARM::t2STMDB_UPD: UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign); break; } if (UseCycle == -1) // Assume it's read in the first stage. UseCycle = 1; UseCycle = DefCycle - UseCycle + 1; if (UseCycle > 0) { if (LdmBypass) { // It's a variable_ops instruction so we can't use DefIdx here. Just use // first def operand. if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1, UseClass, UseIdx)) --UseCycle; } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx, UseClass, UseIdx)) { --UseCycle; } } return UseCycle; } static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI, const MachineInstr *MI, unsigned Reg, unsigned &DefIdx, unsigned &Dist) { Dist = 0; MachineBasicBlock::const_iterator I = MI; ++I; MachineBasicBlock::const_instr_iterator II = std::prev(I.getInstrIterator()); assert(II->isInsideBundle() && ""Empty bundle?""); int Idx = -1; while (II->isInsideBundle()) { Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI); if (Idx != -1) break; --II; ++Dist; } assert(Idx != -1 && ""Cannot find bundled definition!""); DefIdx = Idx; return &*II; } static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI, const MachineInstr *MI, unsigned Reg, unsigned &UseIdx, unsigned &Dist) { Dist = 0; MachineBasicBlock::const_instr_iterator II = ++MI->getIterator(); assert(II->isInsideBundle() && ""Empty bundle?""); MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end(); // FIXME: This doesn't properly handle multiple uses. int Idx = -1; while (II != E && II->isInsideBundle()) { Idx = II->findRegisterUseOperandIdx(Reg, false, TRI); if (Idx != -1) break; if (II->getOpcode() != ARM::t2IT) ++Dist; ++II; } if (Idx == -1) { Dist = 0; return nullptr; } UseIdx = Idx; return &*II; } /// Return the number of cycles to add to (or subtract from) the static /// itinerary based on the def opcode and alignment. The caller will ensure that /// adjusted latency is at least one cycle. static int adjustDefLatency(const ARMSubtarget &Subtarget, const MachineInstr *DefMI, const MCInstrDesc *DefMCID, unsigned DefAlign) { int Adjust = 0; if (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7()) { // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2] // variants are one cycle cheaper. switch (DefMCID->getOpcode()) { default: break; case ARM::LDRrs: case ARM::LDRBrs: { unsigned ShOpVal = DefMI->getOperand(3).getImm(); unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); if (ShImm == 0 || (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)) --Adjust; break; } case ARM::t2LDRs: case ARM::t2LDRBs: case ARM::t2LDRHs: case ARM::t2LDRSHs: { // Thumb2 mode: lsl only. unsigned ShAmt = DefMI->getOperand(3).getImm(); if (ShAmt == 0 || ShAmt == 2) --Adjust; break; } } } else if (Subtarget.isSwift()) { // FIXME: Properly handle all of the latency adjustments for address // writeback. switch (DefMCID->getOpcode()) { default: break; case ARM::LDRrs: case ARM::LDRBrs: { unsigned ShOpVal = DefMI->getOperand(3).getImm(); bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); if (!isSub && (ShImm == 0 || ((ShImm == 1 || ShImm == 2 || ShImm == 3) && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) Adjust -= 2; else if (!isSub && ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr) --Adjust; break; } case ARM::t2LDRs: case ARM::t2LDRBs: case ARM::t2LDRHs: case ARM::t2LDRSHs: { // Thumb2 mode: lsl only. unsigned ShAmt = DefMI->getOperand(3).getImm(); if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3) Adjust -= 2; break; } } } if (DefAlign < 8 && Subtarget.isLikeA9()) { switch (DefMCID->getOpcode()) { default: break; case ARM::VLD1q8: case ARM::VLD1q16: case ARM::VLD1q32: case ARM::VLD1q64: case ARM::VLD1q8wb_fixed: case ARM::VLD1q16wb_fixed: case ARM::VLD1q32wb_fixed: case ARM::VLD1q64wb_fixed: case ARM::VLD1q8wb_register: case ARM::VLD1q16wb_register: case ARM::VLD1q32wb_register: case ARM::VLD1q64wb_register: case ARM::VLD2d8: case ARM::VLD2d16: case ARM::VLD2d32: case ARM::VLD2q8: case ARM::VLD2q16: case ARM::VLD2q32: case ARM::VLD2d8wb_fixed: case ARM::VLD2d16wb_fixed: case ARM::VLD2d32wb_fixed: case ARM::VLD2q8wb_fixed: case ARM::VLD2q16wb_fixed: case ARM::VLD2q32wb_fixed: case ARM::VLD2d8wb_register: case ARM::VLD2d16wb_register: case ARM::VLD2d32wb_register: case ARM::VLD2q8wb_register: case ARM::VLD2q16wb_register: case ARM::VLD2q32wb_register: case ARM::VLD3d8: case ARM::VLD3d16: case ARM::VLD3d32: case ARM::VLD1d64T: case ARM::VLD3d8_UPD: case ARM::VLD3d16_UPD: case ARM::VLD3d32_UPD: case ARM::VLD1d64Twb_fixed: case ARM::VLD1d64Twb_register: case ARM::VLD3q8_UPD: case ARM::VLD3q16_UPD: case ARM::VLD3q32_UPD: case ARM::VLD4d8: case ARM::VLD4d16: case ARM::VLD4d32: case ARM::VLD1d64Q: case ARM::VLD4d8_UPD: case ARM::VLD4d16_UPD: case ARM::VLD4d32_UPD: case ARM::VLD1d64Qwb_fixed: case ARM::VLD1d64Qwb_register: case ARM::VLD4q8_UPD: case ARM::VLD4q16_UPD: case ARM::VLD4q32_UPD: case ARM::VLD1DUPq8: case ARM::VLD1DUPq16: case ARM::VLD1DUPq32: case ARM::VLD1DUPq8wb_fixed: case ARM::VLD1DUPq16wb_fixed: case ARM::VLD1DUPq32wb_fixed: case ARM::VLD1DUPq8wb_register: case ARM::VLD1DUPq16wb_register: case ARM::VLD1DUPq32wb_register: case ARM::VLD2DUPd8: case ARM::VLD2DUPd16: case ARM::VLD2DUPd32: case ARM::VLD2DUPd8wb_fixed: case ARM::VLD2DUPd16wb_fixed: case ARM::VLD2DUPd32wb_fixed: case ARM::VLD2DUPd8wb_register: case ARM::VLD2DUPd16wb_register: case ARM::VLD2DUPd32wb_register: case ARM::VLD4DUPd8: case ARM::VLD4DUPd16: case ARM::VLD4DUPd32: case ARM::VLD4DUPd8_UPD: case ARM::VLD4DUPd16_UPD: case ARM::VLD4DUPd32_UPD: case ARM::VLD1LNd8: case ARM::VLD1LNd16: case ARM::VLD1LNd32: case ARM::VLD1LNd8_UPD: case ARM::VLD1LNd16_UPD: case ARM::VLD1LNd32_UPD: case ARM::VLD2LNd8: case ARM::VLD2LNd16: case ARM::VLD2LNd32: case ARM::VLD2LNq16: case ARM::VLD2LNq32: case ARM::VLD2LNd8_UPD: case ARM::VLD2LNd16_UPD: case ARM::VLD2LNd32_UPD: case ARM::VLD2LNq16_UPD: case ARM::VLD2LNq32_UPD: case ARM::VLD4LNd8: case ARM::VLD4LNd16: case ARM::VLD4LNd32: case ARM::VLD4LNq16: case ARM::VLD4LNq32: case ARM::VLD4LNd8_UPD: case ARM::VLD4LNd16_UPD: case ARM::VLD4LNd32_UPD: case ARM::VLD4LNq16_UPD: case ARM::VLD4LNq32_UPD: // If the address is not 64-bit aligned, the latencies of these // instructions increases by one. ++Adjust; break; } } return Adjust; } int ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, const MachineInstr *DefMI, unsigned DefIdx, const MachineInstr *UseMI, unsigned UseIdx) const { // No operand latency. The caller may fall back to getInstrLatency. if (!ItinData || ItinData->isEmpty()) return -1; const MachineOperand &DefMO = DefMI->getOperand(DefIdx); unsigned Reg = DefMO.getReg(); const MCInstrDesc *DefMCID = &DefMI->getDesc(); const MCInstrDesc *UseMCID = &UseMI->getDesc(); unsigned DefAdj = 0; if (DefMI->isBundle()) { DefMI = getBundledDefMI(&getRegisterInfo(), DefMI, Reg, DefIdx, DefAdj); DefMCID = &DefMI->getDesc(); } if (DefMI->isCopyLike() || DefMI->isInsertSubreg() || DefMI->isRegSequence() || DefMI->isImplicitDef()) { return 1; } unsigned UseAdj = 0; if (UseMI->isBundle()) { unsigned NewUseIdx; const MachineInstr *NewUseMI = getBundledUseMI(&getRegisterInfo(), UseMI, Reg, NewUseIdx, UseAdj); if (!NewUseMI) return -1; UseMI = NewUseMI; UseIdx = NewUseIdx; UseMCID = &UseMI->getDesc(); } if (Reg == ARM::CPSR) { if (DefMI->getOpcode() == ARM::FMSTAT) { // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?) return Subtarget.isLikeA9() ? 1 : 20; } // CPSR set and branch can be paired in the same cycle. if (UseMI->isBranch()) return 0; // Otherwise it takes the instruction latency (generally one). unsigned Latency = getInstrLatency(ItinData, DefMI); // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to // its uses. Instructions which are otherwise scheduled between them may // incur a code size penalty (not able to use the CPSR setting 16-bit // instructions). if (Latency > 0 && Subtarget.isThumb2()) { const MachineFunction *MF = DefMI->getParent()->getParent(); // FIXME: Use Function::optForSize(). if (MF->getFunction()->hasFnAttribute(Attribute::OptimizeForSize)) --Latency; } return Latency; } if (DefMO.isImplicit() || UseMI->getOperand(UseIdx).isImplicit()) return -1; unsigned DefAlign = DefMI->hasOneMemOperand() ? (*DefMI->memoperands_begin())->getAlignment() : 0; unsigned UseAlign = UseMI->hasOneMemOperand() ? (*UseMI->memoperands_begin())->getAlignment() : 0; // Get the itinerary's latency if possible, and handle variable_ops. int Latency = getOperandLatency(ItinData, *DefMCID, DefIdx, DefAlign, *UseMCID, UseIdx, UseAlign); // Unable to find operand latency. The caller may resort to getInstrLatency. if (Latency < 0) return Latency; // Adjust for IT block position. int Adj = DefAdj + UseAdj; // Adjust for dynamic def-side opcode variants not captured by the itinerary. Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign); if (Adj >= 0 || (int)Latency > -Adj) { return Latency + Adj; } // Return the itinerary latency, which may be zero but not less than zero. return Latency; } int ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, SDNode *DefNode, unsigned DefIdx, SDNode *UseNode, unsigned UseIdx) const { if (!DefNode->isMachineOpcode()) return 1; const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode()); if (isZeroCost(DefMCID.Opcode)) return 0; if (!ItinData || ItinData->isEmpty()) return DefMCID.mayLoad() ? 3 : 1; if (!UseNode->isMachineOpcode()) { int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx); if (Subtarget.isLikeA9() || Subtarget.isSwift()) return Latency <= 2 ? 1 : Latency - 1; else return Latency <= 3 ? 1 : Latency - 2; } const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode()); const MachineSDNode *DefMN = dyn_cast(DefNode); unsigned DefAlign = !DefMN->memoperands_empty() ? (*DefMN->memoperands_begin())->getAlignment() : 0; const MachineSDNode *UseMN = dyn_cast(UseNode); unsigned UseAlign = !UseMN->memoperands_empty() ? (*UseMN->memoperands_begin())->getAlignment() : 0; int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign, UseMCID, UseIdx, UseAlign); if (Latency > 1 && (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7())) { // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2] // variants are one cycle cheaper. switch (DefMCID.getOpcode()) { default: break; case ARM::LDRrs: case ARM::LDRBrs: { unsigned ShOpVal = cast(DefNode->getOperand(2))->getZExtValue(); unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); if (ShImm == 0 || (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)) --Latency; break; } case ARM::t2LDRs: case ARM::t2LDRBs: case ARM::t2LDRHs: case ARM::t2LDRSHs: { // Thumb2 mode: lsl only. unsigned ShAmt = cast(DefNode->getOperand(2))->getZExtValue(); if (ShAmt == 0 || ShAmt == 2) --Latency; break; } } } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) { // FIXME: Properly handle all of the latency adjustments for address // writeback. switch (DefMCID.getOpcode()) { default: break; case ARM::LDRrs: case ARM::LDRBrs: { unsigned ShOpVal = cast(DefNode->getOperand(2))->getZExtValue(); unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); if (ShImm == 0 || ((ShImm == 1 || ShImm == 2 || ShImm == 3) && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)) Latency -= 2; else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr) --Latency; break; } case ARM::t2LDRs: case ARM::t2LDRBs: case ARM::t2LDRHs: case ARM::t2LDRSHs: { // Thumb2 mode: lsl 0-3 only. Latency -= 2; break; } } } if (DefAlign < 8 && Subtarget.isLikeA9()) switch (DefMCID.getOpcode()) { default: break; case ARM::VLD1q8: case ARM::VLD1q16: case ARM::VLD1q32: case ARM::VLD1q64: case ARM::VLD1q8wb_register: case ARM::VLD1q16wb_register: case ARM::VLD1q32wb_register: case ARM::VLD1q64wb_register: case ARM::VLD1q8wb_fixed: case ARM::VLD1q16wb_fixed: case ARM::VLD1q32wb_fixed: case ARM::VLD1q64wb_fixed: case ARM::VLD2d8: case ARM::VLD2d16: case ARM::VLD2d32: case ARM::VLD2q8Pseudo: case ARM::VLD2q16Pseudo: case ARM::VLD2q32Pseudo: case ARM::VLD2d8wb_fixed: case ARM::VLD2d16wb_fixed: case ARM::VLD2d32wb_fixed: case ARM::VLD2q8PseudoWB_fixed: case ARM::VLD2q16PseudoWB_fixed: case ARM::VLD2q32PseudoWB_fixed: case ARM::VLD2d8wb_register: case ARM::VLD2d16wb_register: case ARM::VLD2d32wb_register: case ARM::VLD2q8PseudoWB_register: case ARM::VLD2q16PseudoWB_register: case ARM::VLD2q32PseudoWB_register: case ARM::VLD3d8Pseudo: case ARM::VLD3d16Pseudo: case ARM::VLD3d32Pseudo: case ARM::VLD1d64TPseudo: case ARM::VLD1d64TPseudoWB_fixed: case ARM::VLD3d8Pseudo_UPD: case ARM::VLD3d16Pseudo_UPD: case ARM::VLD3d32Pseudo_UPD: case ARM::VLD3q8Pseudo_UPD: case ARM::VLD3q16Pseudo_UPD: case ARM::VLD3q32Pseudo_UPD: case ARM::VLD3q8oddPseudo: case ARM::VLD3q16oddPseudo: case ARM::VLD3q32oddPseudo: case ARM::VLD3q8oddPseudo_UPD: case ARM::VLD3q16oddPseudo_UPD: case ARM::VLD3q32oddPseudo_UPD: case ARM::VLD4d8Pseudo: case ARM::VLD4d16Pseudo: case ARM::VLD4d32Pseudo: case ARM::VLD1d64QPseudo: case ARM::VLD1d64QPseudoWB_fixed: case ARM::VLD4d8Pseudo_UPD: case ARM::VLD4d16Pseudo_UPD: case ARM::VLD4d32Pseudo_UPD: case ARM::VLD4q8Pseudo_UPD: case ARM::VLD4q16Pseudo_UPD: case ARM::VLD4q32Pseudo_UPD: case ARM::VLD4q8oddPseudo: case ARM::VLD4q16oddPseudo: case ARM::VLD4q32oddPseudo: case ARM::VLD4q8oddPseudo_UPD: case ARM::VLD4q16oddPseudo_UPD: case ARM::VLD4q32oddPseudo_UPD: case ARM::VLD1DUPq8: case ARM::VLD1DUPq16: case ARM::VLD1DUPq32: case ARM::VLD1DUPq8wb_fixed: case ARM::VLD1DUPq16wb_fixed: case ARM::VLD1DUPq32wb_fixed: case ARM::VLD1DUPq8wb_register: case ARM::VLD1DUPq16wb_register: case ARM::VLD1DUPq32wb_register: case ARM::VLD2DUPd8: case ARM::VLD2DUPd16: case ARM::VLD2DUPd32: case ARM::VLD2DUPd8wb_fixed: case ARM::VLD2DUPd16wb_fixed: case ARM::VLD2DUPd32wb_fixed: case ARM::VLD2DUPd8wb_register: case ARM::VLD2DUPd16wb_register: case ARM::VLD2DUPd32wb_register: case ARM::VLD4DUPd8Pseudo: case ARM::VLD4DUPd16Pseudo: case ARM::VLD4DUPd32Pseudo: case ARM::VLD4DUPd8Pseudo_UPD: case ARM::VLD4DUPd16Pseudo_UPD: case ARM::VLD4DUPd32Pseudo_UPD: case ARM::VLD1LNq8Pseudo: case ARM::VLD1LNq16Pseudo: case ARM::VLD1LNq32Pseudo: case ARM::VLD1LNq8Pseudo_UPD: case ARM::VLD1LNq16Pseudo_UPD: case ARM::VLD1LNq32Pseudo_UPD: case ARM::VLD2LNd8Pseudo: case ARM::VLD2LNd16Pseudo: case ARM::VLD2LNd32Pseudo: case ARM::VLD2LNq16Pseudo: case ARM::VLD2LNq32Pseudo: case ARM::VLD2LNd8Pseudo_UPD: case ARM::VLD2LNd16Pseudo_UPD: case ARM::VLD2LNd32Pseudo_UPD: case ARM::VLD2LNq16Pseudo_UPD: case ARM::VLD2LNq32Pseudo_UPD: case ARM::VLD4LNd8Pseudo: case ARM::VLD4LNd16Pseudo: case ARM::VLD4LNd32Pseudo: case ARM::VLD4LNq16Pseudo: case ARM::VLD4LNq32Pseudo: case ARM::VLD4LNd8Pseudo_UPD: case ARM::VLD4LNd16Pseudo_UPD: case ARM::VLD4LNd32Pseudo_UPD: case ARM::VLD4LNq16Pseudo_UPD: case ARM::VLD4LNq32Pseudo_UPD: // If the address is not 64-bit aligned, the latencies of these // instructions increases by one. ++Latency; break; } return Latency; } unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr &MI) const { if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() || MI.isImplicitDef()) return 0; if (MI.isBundle()) return 0; const MCInstrDesc &MCID = MI.getDesc(); if (MCID.isCall() || MCID.hasImplicitDefOfPhysReg(ARM::CPSR)) { // When predicated, CPSR is an additional source operand for CPSR updating // instructions, this apparently increases their latencies. return 1; } return 0; } unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, const MachineInstr *MI, unsigned *PredCost) const { if (MI->isCopyLike() || MI->isInsertSubreg() || MI->isRegSequence() || MI->isImplicitDef()) return 1; // An instruction scheduler typically runs on unbundled instructions, however // other passes may query the latency of a bundled instruction. if (MI->isBundle()) { unsigned Latency = 0; MachineBasicBlock::const_instr_iterator I = MI->getIterator(); MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end(); while (++I != E && I->isInsideBundle()) { if (I->getOpcode() != ARM::t2IT) Latency += getInstrLatency(ItinData, &*I, PredCost); } return Latency; } const MCInstrDesc &MCID = MI->getDesc(); if (PredCost && (MCID.isCall() || MCID.hasImplicitDefOfPhysReg(ARM::CPSR))) { // When predicated, CPSR is an additional source operand for CPSR updating // instructions, this apparently increases their latencies. *PredCost = 1; } // Be sure to call getStageLatency for an empty itinerary in case it has a // valid MinLatency property. if (!ItinData) return MI->mayLoad() ? 3 : 1; unsigned Class = MCID.getSchedClass(); // For instructions with variable uops, use uops as latency. if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0) return getNumMicroOps(ItinData, MI); // For the common case, fall back on the itinerary's latency. unsigned Latency = ItinData->getStageLatency(Class); // Adjust for dynamic def-side opcode variants not captured by the itinerary. unsigned DefAlign = MI->hasOneMemOperand() ? (*MI->memoperands_begin())->getAlignment() : 0; int Adj = adjustDefLatency(Subtarget, MI, &MCID, DefAlign); if (Adj >= 0 || (int)Latency > -Adj) { return Latency + Adj; } return Latency; } int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, SDNode *Node) const { if (!Node->isMachineOpcode()) return 1; if (!ItinData || ItinData->isEmpty()) return 1; unsigned Opcode = Node->getMachineOpcode(); switch (Opcode) { default: return ItinData->getStageLatency(get(Opcode).getSchedClass()); case ARM::VLDMQIA: case ARM::VSTMQIA: return 2; } } bool ARMBaseInstrInfo:: hasHighOperandLatency(const TargetSchedModel &SchedModel, const MachineRegisterInfo *MRI, const MachineInstr *DefMI, unsigned DefIdx, const MachineInstr *UseMI, unsigned UseIdx) const { unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask; unsigned UDomain = UseMI->getDesc().TSFlags & ARMII::DomainMask; if (Subtarget.isCortexA8() && (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP)) // CortexA8 VFP instructions are not pipelined. return true; // Hoist VFP / NEON instructions with 4 or higher latency. unsigned Latency = SchedModel.computeOperandLatency(DefMI, DefIdx, UseMI, UseIdx); if (Latency <= 3) return false; return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON || UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON; } bool ARMBaseInstrInfo:: hasLowDefLatency(const TargetSchedModel &SchedModel, const MachineInstr *DefMI, unsigned DefIdx) const { const InstrItineraryData *ItinData = SchedModel.getInstrItineraries(); if (!ItinData || ItinData->isEmpty()) return false; unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask; if (DDomain == ARMII::DomainGeneral) { unsigned DefClass = DefMI->getDesc().getSchedClass(); int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx); return (DefCycle != -1 && DefCycle <= 2); } return false; } bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr *MI, StringRef &ErrInfo) const { if (convertAddSubFlagsOpcode(MI->getOpcode())) { ErrInfo = ""Pseudo flag setting opcodes only exist in Selection DAG""; return false; } return true; } // LoadStackGuard has so far only been implemented for MachO. Different code // sequence is needed for other targets. void ARMBaseInstrInfo::expandLoadStackGuardBase(MachineBasicBlock::iterator MI, unsigned LoadImmOpc, unsigned LoadOpc, Reloc::Model RM) const { MachineBasicBlock &MBB = *MI->getParent(); DebugLoc DL = MI->getDebugLoc(); unsigned Reg = MI->getOperand(0).getReg(); const GlobalValue *GV = cast((*MI->memoperands_begin())->getValue()); MachineInstrBuilder MIB; BuildMI(MBB, MI, DL, get(LoadImmOpc), Reg) .addGlobalAddress(GV, 0, ARMII::MO_NONLAZY); if (Subtarget.GVIsIndirectSymbol(GV, RM)) { MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg); MIB.addReg(Reg, RegState::Kill).addImm(0); unsigned Flag = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant; MachineMemOperand *MMO = MBB.getParent()->getMachineMemOperand( MachinePointerInfo::getGOT(*MBB.getParent()), Flag, 4, 4); MIB.addMemOperand(MMO); AddDefaultPred(MIB); } MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg); MIB.addReg(Reg, RegState::Kill).addImm(0); MIB.setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); AddDefaultPred(MIB); } bool ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc, unsigned &AddSubOpc, bool &NegAcc, bool &HasLane) const { DenseMap::const_iterator I = MLxEntryMap.find(Opcode); if (I == MLxEntryMap.end()) return false; const ARM_MLxEntry &Entry = ARM_MLxTable[I->second]; MulOpc = Entry.MulOpc; AddSubOpc = Entry.AddSubOpc; NegAcc = Entry.NegAcc; HasLane = Entry.HasLane; return true; } //===----------------------------------------------------------------------===// // Execution domains. //===----------------------------------------------------------------------===// // // Some instructions go down the NEON pipeline, some go down the VFP pipeline, // and some can go down both. The vmov instructions go down the VFP pipeline, // but they can be changed to vorr equivalents that are executed by the NEON // pipeline. // // We use the following execution domain numbering: // enum ARMExeDomain { ExeGeneric = 0, ExeVFP = 1, ExeNEON = 2 }; // // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h // std::pair ARMBaseInstrInfo::getExecutionDomain(const MachineInstr *MI) const { // If we don't have access to NEON instructions then we won't be able // to swizzle anything to the NEON domain. Check to make sure. if (Subtarget.hasNEON()) { // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON // if they are not predicated. if (MI->getOpcode() == ARM::VMOVD && !isPredicated(*MI)) return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON)); // CortexA9 is particularly picky about mixing the two and wants these // converted. if (Subtarget.isCortexA9() && !isPredicated(*MI) && (MI->getOpcode() == ARM::VMOVRS || MI->getOpcode() == ARM::VMOVSR || MI->getOpcode() == ARM::VMOVS)) return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON)); } // No other instructions can be swizzled, so just determine their domain. unsigned Domain = MI->getDesc().TSFlags & ARMII::DomainMask; if (Domain & ARMII::DomainNEON) return std::make_pair(ExeNEON, 0); // Certain instructions can go either way on Cortex-A8. // Treat them as NEON instructions. if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8()) return std::make_pair(ExeNEON, 0); if (Domain & ARMII::DomainVFP) return std::make_pair(ExeVFP, 0); return std::make_pair(ExeGeneric, 0); } static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI, unsigned SReg, unsigned &Lane) { unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass); Lane = 0; if (DReg != ARM::NoRegister) return DReg; Lane = 1; DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass); assert(DReg && ""S-register with no D super-register?""); return DReg; } /// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane, /// set ImplicitSReg to a register number that must be marked as implicit-use or /// zero if no register needs to be defined as implicit-use. /// /// If the function cannot determine if an SPR should be marked implicit use or /// not, it returns false. /// /// This function handles cases where an instruction is being modified from taking /// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict /// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other /// lane of the DPR). /// /// If the other SPR is defined, an implicit-use of it should be added. Else, /// (including the case where the DPR itself is defined), it should not. /// static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI, MachineInstr *MI, unsigned DReg, unsigned Lane, unsigned &ImplicitSReg) { // If the DPR is defined or used already, the other SPR lane will be chained // correctly, so there is nothing to be done. if (MI->definesRegister(DReg, TRI) || MI->readsRegister(DReg, TRI)) { ImplicitSReg = 0; return true; } // Otherwise we need to go searching to see if the SPR is set explicitly. ImplicitSReg = TRI->getSubReg(DReg, (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1); MachineBasicBlock::LivenessQueryResult LQR = MI->getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI); if (LQR == MachineBasicBlock::LQR_Live) return true; else if (LQR == MachineBasicBlock::LQR_Unknown) return false; // If the register is known not to be live, there is no need to add an // implicit-use. ImplicitSReg = 0; return true; } void ARMBaseInstrInfo::setExecutionDomain(MachineInstr *MI, unsigned Domain) const { unsigned DstReg, SrcReg, DReg; unsigned Lane; MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI); const TargetRegisterInfo *TRI = &getRegisterInfo(); switch (MI->getOpcode()) { default: llvm_unreachable(""cannot handle opcode!""); break; case ARM::VMOVD: if (Domain != ExeNEON) break; // Zap the predicate operands. assert(!isPredicated(*MI) && ""Cannot predicate a VORRd""); // Make sure we've got NEON instructions. assert(Subtarget.hasNEON() && ""VORRd requires NEON""); // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits) DstReg = MI->getOperand(0).getReg(); SrcReg = MI->getOperand(1).getReg(); for (unsigned i = MI->getDesc().getNumOperands(); i; --i) MI->RemoveOperand(i-1); // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits) MI->setDesc(get(ARM::VORRd)); AddDefaultPred(MIB.addReg(DstReg, RegState::Define) .addReg(SrcReg) .addReg(SrcReg)); break; case ARM::VMOVRS: if (Domain != ExeNEON) break; assert(!isPredicated(*MI) && ""Cannot predicate a VGETLN""); // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits) DstReg = MI->getOperand(0).getReg(); SrcReg = MI->getOperand(1).getReg(); for (unsigned i = MI->getDesc().getNumOperands(); i; --i) MI->RemoveOperand(i-1); DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane); // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps) // Note that DSrc has been widened and the other lane may be undef, which // contaminates the entire register. MI->setDesc(get(ARM::VGETLNi32)); AddDefaultPred(MIB.addReg(DstReg, RegState::Define) .addReg(DReg, RegState::Undef) .addImm(Lane)); // The old source should be an implicit use, otherwise we might think it // was dead before here. MIB.addReg(SrcReg, RegState::Implicit); break; case ARM::VMOVSR: { if (Domain != ExeNEON) break; assert(!isPredicated(*MI) && ""Cannot predicate a VSETLN""); // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits) DstReg = MI->getOperand(0).getReg(); SrcReg = MI->getOperand(1).getReg(); DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane); unsigned ImplicitSReg; if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg)) break; for (unsigned i = MI->getDesc().getNumOperands(); i; --i) MI->RemoveOperand(i-1); // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps) // Again DDst may be undefined at the beginning of this instruction. MI->setDesc(get(ARM::VSETLNi32)); MIB.addReg(DReg, RegState::Define) .addReg(DReg, getUndefRegState(!MI->readsRegister(DReg, TRI))) .addReg(SrcReg) .addImm(Lane); AddDefaultPred(MIB); // The narrower destination must be marked as set to keep previous chains // in place. MIB.addReg(DstReg, RegState::Define | RegState::Implicit); if (ImplicitSReg != 0) MIB.addReg(ImplicitSReg, RegState::Implicit); break; } case ARM::VMOVS: { if (Domain != ExeNEON) break; // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits) DstReg = MI->getOperand(0).getReg(); SrcReg = MI->getOperand(1).getReg(); unsigned DstLane = 0, SrcLane = 0, DDst, DSrc; DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane); DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane); unsigned ImplicitSReg; if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg)) break; for (unsigned i = MI->getDesc().getNumOperands(); i; --i) MI->RemoveOperand(i-1); if (DSrc == DDst) { // Destination can be: // %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits) MI->setDesc(get(ARM::VDUPLN32d)); MIB.addReg(DDst, RegState::Define) .addReg(DDst, getUndefRegState(!MI->readsRegister(DDst, TRI))) .addImm(SrcLane); AddDefaultPred(MIB); // Neither the source or the destination are naturally represented any // more, so add them in manually. MIB.addReg(DstReg, RegState::Implicit | RegState::Define); MIB.addReg(SrcReg, RegState::Implicit); if (ImplicitSReg != 0) MIB.addReg(ImplicitSReg, RegState::Implicit); break; } // In general there's no single instruction that can perform an S <-> S // move in NEON space, but a pair of VEXT instructions *can* do the // job. It turns out that the VEXTs needed will only use DSrc once, with // the position based purely on the combination of lane-0 and lane-1 // involved. For example // vmov s0, s2 -> vext.32 d0, d0, d1, #1 vext.32 d0, d0, d0, #1 // vmov s1, s3 -> vext.32 d0, d1, d0, #1 vext.32 d0, d0, d0, #1 // vmov s0, s3 -> vext.32 d0, d0, d0, #1 vext.32 d0, d1, d0, #1 // vmov s1, s2 -> vext.32 d0, d0, d0, #1 vext.32 d0, d0, d1, #1 // // Pattern of the MachineInstrs is: // %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits) MachineInstrBuilder NewMIB; NewMIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), get(ARM::VEXTd32), DDst); // On the first instruction, both DSrc and DDst may be if present. // Specifically when the original instruction didn't have them as an // . unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst; bool CurUndef = !MI->readsRegister(CurReg, TRI); NewMIB.addReg(CurReg, getUndefRegState(CurUndef)); CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst; CurUndef = !MI->readsRegister(CurReg, TRI); NewMIB.addReg(CurReg, getUndefRegState(CurUndef)); NewMIB.addImm(1); AddDefaultPred(NewMIB); if (SrcLane == DstLane) NewMIB.addReg(SrcReg, RegState::Implicit); MI->setDesc(get(ARM::VEXTd32)); MIB.addReg(DDst, RegState::Define); // On the second instruction, DDst has definitely been defined above, so // it is not . DSrc, if present, can be as above. CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst; CurUndef = CurReg == DSrc && !MI->readsRegister(CurReg, TRI); MIB.addReg(CurReg, getUndefRegState(CurUndef)); CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst; CurUndef = CurReg == DSrc && !MI->readsRegister(CurReg, TRI); MIB.addReg(CurReg, getUndefRegState(CurUndef)); MIB.addImm(1); AddDefaultPred(MIB); if (SrcLane != DstLane) MIB.addReg(SrcReg, RegState::Implicit); // As before, the original destination is no longer represented, add it // implicitly. MIB.addReg(DstReg, RegState::Define | RegState::Implicit); if (ImplicitSReg != 0) MIB.addReg(ImplicitSReg, RegState::Implicit); break; } } } //===----------------------------------------------------------------------===// // Partial register updates //===----------------------------------------------------------------------===// // // Swift renames NEON registers with 64-bit granularity. That means any // instruction writing an S-reg implicitly reads the containing D-reg. The // problem is mostly avoided by translating f32 operations to v2f32 operations // on D-registers, but f32 loads are still a problem. // // These instructions can load an f32 into a NEON register: // // VLDRS - Only writes S, partial D update. // VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops. // VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops. // // FCONSTD can be used as a dependency-breaking instruction. unsigned ARMBaseInstrInfo:: getPartialRegUpdateClearance(const MachineInstr *MI, unsigned OpNum, const TargetRegisterInfo *TRI) const { if (!SwiftPartialUpdateClearance || !(Subtarget.isSwift() || Subtarget.isCortexA15())) return 0; assert(TRI && ""Need TRI instance""); const MachineOperand &MO = MI->getOperand(OpNum); if (MO.readsReg()) return 0; unsigned Reg = MO.getReg(); int UseOp = -1; switch(MI->getOpcode()) { // Normal instructions writing only an S-register. case ARM::VLDRS: case ARM::FCONSTS: case ARM::VMOVSR: case ARM::VMOVv8i8: case ARM::VMOVv4i16: case ARM::VMOVv2i32: case ARM::VMOVv2f32: case ARM::VMOVv1i64: UseOp = MI->findRegisterUseOperandIdx(Reg, false, TRI); break; // Explicitly reads the dependency. case ARM::VLD1LNd32: UseOp = 3; break; default: return 0; } // If this instruction actually reads a value from Reg, there is no unwanted // dependency. if (UseOp != -1 && MI->getOperand(UseOp).readsReg()) return 0; // We must be able to clobber the whole D-reg. if (TargetRegisterInfo::isVirtualRegister(Reg)) { // Virtual register must be a foo:ssub_0 operand. if (!MO.getSubReg() || MI->readsVirtualRegister(Reg)) return 0; } else if (ARM::SPRRegClass.contains(Reg)) { // Physical register: MI must define the full D-reg. unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0, &ARM::DPRRegClass); if (!DReg || !MI->definesRegister(DReg, TRI)) return 0; } // MI has an unwanted D-register dependency. // Avoid defs in the previous N instructrions. return SwiftPartialUpdateClearance; } // Break a partial register dependency after getPartialRegUpdateClearance // returned non-zero. void ARMBaseInstrInfo:: breakPartialRegDependency(MachineBasicBlock::iterator MI, unsigned OpNum, const TargetRegisterInfo *TRI) const { assert(MI && OpNum < MI->getDesc().getNumDefs() && ""OpNum is not a def""); assert(TRI && ""Need TRI instance""); const MachineOperand &MO = MI->getOperand(OpNum); unsigned Reg = MO.getReg(); assert(TargetRegisterInfo::isPhysicalRegister(Reg) && ""Can't break virtual register dependencies.""); unsigned DReg = Reg; // If MI defines an S-reg, find the corresponding D super-register. if (ARM::SPRRegClass.contains(Reg)) { DReg = ARM::D0 + (Reg - ARM::S0) / 2; assert(TRI->isSuperRegister(Reg, DReg) && ""Register enums broken""); } assert(ARM::DPRRegClass.contains(DReg) && ""Can only break D-reg deps""); assert(MI->definesRegister(DReg, TRI) && ""MI doesn't clobber full D-reg""); // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines // the full D-register by loading the same value to both lanes. The // instruction is micro-coded with 2 uops, so don't do this until we can // properly schedule micro-coded instructions. The dispatcher stalls cause // too big regressions. // Insert the dependency-breaking FCONSTD before MI. // 96 is the encoding of 0.5, but the actual value doesn't matter here. AddDefaultPred(BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), get(ARM::FCONSTD), DReg).addImm(96)); MI->addRegisterKilled(DReg, TRI, true); } bool ARMBaseInstrInfo::hasNOP() const { return Subtarget.getFeatureBits()[ARM::HasV6KOps]; } bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const { if (MI->getNumOperands() < 4) return true; unsigned ShOpVal = MI->getOperand(3).getImm(); unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal); // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1. if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) || ((ShImm == 1 || ShImm == 2) && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl)) return true; return false; } bool ARMBaseInstrInfo::getRegSequenceLikeInputs( const MachineInstr &MI, unsigned DefIdx, SmallVectorImpl &InputRegs) const { assert(DefIdx < MI.getDesc().getNumDefs() && ""Invalid definition index""); assert(MI.isRegSequenceLike() && ""Invalid kind of instruction""); switch (MI.getOpcode()) { case ARM::VMOVDRR: // dX = VMOVDRR rY, rZ // is the same as: // dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1 // Populate the InputRegs accordingly. // rY const MachineOperand *MOReg = &MI.getOperand(1); InputRegs.push_back( RegSubRegPairAndIdx(MOReg->getReg(), MOReg->getSubReg(), ARM::ssub_0)); // rZ MOReg = &MI.getOperand(2); InputRegs.push_back( RegSubRegPairAndIdx(MOReg->getReg(), MOReg->getSubReg(), ARM::ssub_1)); return true; } llvm_unreachable(""Target dependent opcode missing""); } bool ARMBaseInstrInfo::getExtractSubregLikeInputs( const MachineInstr &MI, unsigned DefIdx, RegSubRegPairAndIdx &InputReg) const { assert(DefIdx < MI.getDesc().getNumDefs() && ""Invalid definition index""); assert(MI.isExtractSubregLike() && ""Invalid kind of instruction""); switch (MI.getOpcode()) { case ARM::VMOVRRD: // rX, rY = VMOVRRD dZ // is the same as: // rX = EXTRACT_SUBREG dZ, ssub_0 // rY = EXTRACT_SUBREG dZ, ssub_1 const MachineOperand &MOReg = MI.getOperand(2); InputReg.Reg = MOReg.getReg(); InputReg.SubReg = MOReg.getSubReg(); InputReg.SubIdx = DefIdx == 0 ? ARM::ssub_0 : ARM::ssub_1; return true; } llvm_unreachable(""Target dependent opcode missing""); } bool ARMBaseInstrInfo::getInsertSubregLikeInputs( const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const { assert(DefIdx < MI.getDesc().getNumDefs() && ""Invalid definition index""); assert(MI.isInsertSubregLike() && ""Invalid kind of instruction""); switch (MI.getOpcode()) { case ARM::VSETLNi32: // dX = VSETLNi32 dY, rZ, imm const MachineOperand &MOBaseReg = MI.getOperand(1); const MachineOperand &MOInsertedReg = MI.getOperand(2); const MachineOperand &MOIndex = MI.getOperand(3); BaseReg.Reg = MOBaseReg.getReg(); BaseReg.SubReg = MOBaseReg.getSubReg(); InsertedReg.Reg = MOInsertedReg.getReg(); InsertedReg.SubReg = MOInsertedReg.getSubReg(); InsertedReg.SubIdx = MOIndex.getImm() == 0 ? ARM::ssub_0 : ARM::ssub_1; return true; } llvm_unreachable(""Target dependent opcode missing""); } ",DefOpc 319,"/* * File: Game.cpp * Author: * * Created on November 26, 2017, 1:59 PM * Purpose: Game Class Implementation */ #include ""Game.h"" #include // File descriptor manipulator //Constructor Game::Game() { base.size = 20; base.x = base.size / 2; base.y = base.size / 2; xToken = rand() % base.size; //Standard token worth 10 pts yToken = rand() % base.size; //Standard token worth 10 pts xMega = rand() % base.size + 1; //Mega Token worth 20 pts yMega = rand() % base.size + 1; //Mega Token worth 20 pts ckWin = true; sleep = 1; tempX = 0; tempY = 0; temp2X = 0; temp2Y = 0; ckPnt = false; nTail = 0; sec = 1; //pause in seconds xTail = new int[base.size * 5]; yTail = new int[base.size * 5]; //initialize board for(int i = 0;i < base.size + 2;i++) { cout << ""*""; } cout << endl; for(int i = 0;i < base.size + 2;i++) //height { for(int j = 0;j < base.size + 2;j++)//width { if(j == 0) { cout << ""*""; } cout << "" ""; if(j == base.size - 1) { cout << ""*""; } } cout << endl; } for(int i = 0;i < base.size + 2;i++) { cout << ""*""; } cout << endl; //Check if tokens randomly generate same value, if true add 1 or minus 1 if(xMega == xToken) { xMega += 1; } else if(yMega == yToken) { yMega -= 1; } } Game::~Game() { } /*Function Definition: * pause game so console out is more manageable for player */ void Game::pause(float sleep) { int [MASK] = time(0),end; do { end = time(0); }while(sleep > end - [MASK] ); }",beg 320,"#include #include #include #include #include #include #include #include #include #include #define AFU_GUID ""3d5ee416-6f30-42d1-8109-a453b5b8e29d""; #ifdef NDEBUG #define PLATFORM ""opae"" #else #define PLATFORM ""opae-ase"" #endif int main(int argc, char **argv) { if (argc != 3) { std::cerr << ""Incorrect number of arguments. Usage: primmap path/to/input_recordbatch.rb path/to/output_recordbatch.rb"" << std::endl; return -1; } std::vector> batches; fletcher::ReadRecordBatchesFromFile(argv[1], &batches); if (batches.size() != 1) { std::cerr << ""File did not contain any input Arrow RecordBatches."" << std::endl; return -1; } std::shared_ptr [MASK] ; [MASK] = batches[0]; // read output schema auto file = arrow::io::ReadableFile::Open(argv[2]).ValueOrDie(); std::shared_ptr schema = arrow::ipc::ReadSchema(file.get(), nullptr) .ValueOrDie(); file->Close(); size_t buffer_size = 4096; uint8_t *value_data = (uint8_t *)memalign(sysconf(_SC_PAGESIZE), buffer_size); memset(value_data, 2, buffer_size); auto value_buffer = std::make_shared(value_data, buffer_size); auto value_array = std::make_shared(arrow::uint64(), 0, value_buffer); std::vector> arrays = {value_array}; auto output_batch = arrow::RecordBatch::Make(schema, 0, arrays); fletcher::Status status; std::shared_ptr platform; status = fletcher::Platform::Make(PLATFORM, &platform, false); if (!status.ok()) { std::cerr << ""Could not create Fletcher platform."" << std::endl; std::cerr << status.message << std::endl; return -1; } static const char *guid = AFU_GUID; platform->init_data = &guid; status = platform->Init(); if (!status.ok()) { std::cerr << ""Could not initialize platform."" << std::endl; std::cerr << status.message << std::endl; return -1; } std::shared_ptr context; status = fletcher::Context::Make(&context, platform); if (!status.ok()) { std::cerr << ""Could not create Fletcher context."" << std::endl; return -1; } status = context->QueueRecordBatch( [MASK] ); if (!status.ok()) { std::cerr << ""Could not add input recordbatch."" << std::endl; return -1; } status = context->QueueRecordBatch(output_batch); if (!status.ok()) { std::cerr << ""Could not add output recordbatch."" << std::endl; return -1; } status = context->Enable(); if (!status.ok()) { std::cerr << ""Could not enable the context."" << std::endl; return -1; } for (int i = 0; i < context->num_buffers(); i++) { auto view = fletcher::HexView(); view.AddData(context->device_buffer(i).host_address, 64); std::cout << view.ToString() << std::endl; } fletcher::Kernel kernel(context); status = kernel.Start(); if (!status.ok()) { std::cerr << ""Could not start the kernel."" << std::endl; return -1; } status = kernel.PollUntilDone(); if (!status.ok()) { std::cerr << ""Something went wrong waiting for the kernel to finish."" << std::endl; return -1; } for (int i = 0; i < context->num_buffers(); i++) { auto view = fletcher::HexView(); view.AddData(context->device_buffer(i).host_address, 64); std::cout << view.ToString() << std::endl; } return 0; }",input_batch 321,"#include #include #include #include using namespace std; using ll = long long; int main(){ int [MASK] = 0; string s1, s2, s3; while(cin >> s1 >> s2 >> s3){ vector value_1(52); vector value_2(52); vector value_3(52); for(int i=0; i= 1 && value_2[i] >= 1 && value_3[i] >= 1){ [MASK] += (i+1); break; } } } cout << [MASK] << '\n'; return 0; }",ans 322,"#include ""Board.h"" #include ""board_def.h"" #include ""make_ref.h"" #include #include #include #include #include #include #include #include #include #include #include #include #include Board::Board(std::vector &def, double sizeX, double sizeY, std::string dbPath) : m_sizeX(sizeX) , m_sizeY(sizeY) , m_dbPath(dbPath) { assert(def.size() > 0); m_fieldMap.resize(def.size()); auto height = def.size(); auto width = def[0].size(); for(auto elem : def) { assert(elem.size() >= width); } for(auto& elem : m_fieldMap) { elem.resize(width, FIELD_EMPTY); } for(auto i = 0; i < height; ++i) for(auto j = 0; j < width; ++j) m_fieldMap[i][j] = (def[i][j] == '*' ? FIELD_WALL : FIELD_EMPTY); } std::tuple Board::getPlayerPosition() const { return std::tuple{m_pcX, m_pcY}; } double Board::getSizeX() const { return m_sizeX; } double Board::getSizeY() const { return m_sizeY; } uint32_t Board::getFieldCountX() const { return m_fieldMap[0].size(); } uint32_t Board::getFieldCountY() const { return m_fieldMap.size(); } double Board::getFieldSizeX() const { return m_sizeX / getFieldCountX(); } double Board::getFieldSizeY() const { return m_sizeY / getFieldCountY(); } double Board::getFieldCenterX(uint32_t x) const { return getFieldSizeX() / 2 + x * getFieldSizeX(); } double Board::getFieldCenterY(uint32_t y) const { return getSizeY() - getFieldSizeY() / 2 - y * getFieldSizeY(); } Board::FieldType Board::getField(uint32_t x, uint32_t y) const { return m_fieldMap[y][x]; } void Board::setField(const double x, const double y, const FieldType fieldType) { const auto intX = getFieldX(x); const auto intY = getFieldY(y); setField(intX, intY, fieldType); } void Board::setField(uint32_t x, uint32_t y, Board::FieldType type) { if(type == FIELD_PC) { m_pcX = x; m_pcY = y; } m_fieldMap[y][x] = type; } osg::ref_ptr Board::DrawSquare(double [MASK] , double RootSizeY, uint16_t FragmentCount, uint32_t LOD, std::string TextureFile) const { osg::Geode* CeilGeode = new osg::Geode(); osg::Geometry* CeilGeometry = new osg::Geometry(); CeilGeode->addDrawable(CeilGeometry); //specify vertices osg::Vec3dArray* CeilVertices = new osg::Vec3dArray; osg::DrawElementsUInt* CeilBase = new osg::DrawElementsUInt(osg::PrimitiveSet::QUADS, 0); osg::ref_ptr CeilTexcoords = new osg::Vec2Array; double FragmentSizeX = [MASK] / FragmentCount; double FragmentSizeY = RootSizeY / FragmentCount; double sTexSizeX = 1.0 / LOD; double sTexSizeY = 1.0 / LOD; osg::ref_ptr CeilTexture = new osg::Texture2D; osg::ref_ptr CeilImage = osgDB::readImageFile( m_dbPath + ""/"" + TextureFile ); CeilTexture->setImage( CeilImage.get() ); for(int fi = 0; fi < FragmentCount; ++fi) { for(int fj = 0; fj < FragmentCount; ++fj) { double sizeX = FragmentSizeX / LOD; double sizeY = FragmentSizeY / LOD; for(int i = 0; i < LOD; ++i) { for(int j = 0; j < LOD; ++j) { CeilVertices->push_back(osg::Vec3d(fi * FragmentSizeX + i * sizeX, fj * FragmentSizeY + j * sizeY, 0)); CeilVertices->push_back(osg::Vec3d(fi * FragmentSizeX + i * sizeX + sizeX, fj * FragmentSizeY + j * sizeY, 0)); CeilVertices->push_back(osg::Vec3d(fi * FragmentSizeX + i * sizeX + sizeX, fj * FragmentSizeY + j * sizeY + sizeY, 0)); CeilVertices->push_back(osg::Vec3d(fi * FragmentSizeX + i * sizeX, fj * FragmentSizeY + j * sizeY + sizeY, 0)); } } for(int i = 0; i < LOD; ++i) { for(int j = 0; j < LOD; ++j) { CeilTexcoords->push_back(osg::Vec2d(i * sTexSizeX, j * sTexSizeY)); CeilTexcoords->push_back(osg::Vec2d(i * sTexSizeX + sTexSizeX, j * sTexSizeY)); CeilTexcoords->push_back(osg::Vec2d(i * sTexSizeX + sTexSizeX, j * sTexSizeY + sTexSizeY)); CeilTexcoords->push_back(osg::Vec2d(i * sTexSizeX, j * sTexSizeY + sTexSizeY)); } } } } uint64_t ElemCount = LOD * LOD * 4 * FragmentCount * FragmentCount; for(uint64_t i = 0; i < ElemCount; ++i) CeilBase->push_back(i); CeilGeometry->setVertexArray( CeilVertices ); CeilGeometry->addPrimitiveSet(CeilBase); osg::ref_ptr normals = new osg::Vec3Array; normals->push_back( osg::Vec3(0.0f, 0.0f, 1.0f) ); CeilGeometry->setNormalArray( normals ); CeilGeometry->setNormalBinding( osg::Geometry::BIND_OVERALL ); CeilGeometry->setTexCoordArray(1, CeilTexcoords.get() ); osg::ref_ptr material = new osg::Material; material->setAmbient( osg::Material::FRONT_AND_BACK, osg::Vec4(0.5f, 0.5f, 0.5f, 0.5f) ); material->setDiffuse( osg::Material::FRONT_AND_BACK, osg::Vec4(1.0f, 1.0f, 1.0f, 0.5f) ); material->setSpecular( osg::Material::FRONT_AND_BACK, osg::Vec4(1.0f, 1.0f, 1.0f, 0.5f) ); material->setDataVariance(osg::Material::STATIC); material->setShininess(osg::Material::FRONT_AND_BACK, 0.2); //CeilGeode->getOrCreateStateSet()->setAttributeAndModes(material); CeilGeode->getOrCreateStateSet()->setTextureAttributeAndModes(TEXTURE_UNIT, CeilTexture.get() ); CeilGeode->setCullingActive(true); // osg::TexEnv* blendTexEnv = new osg::TexEnv; // blendTexEnv->setMode(osg::TexEnv::BLEND); // CeilGeode->getOrCreateStateSet()->setTextureAttribute(1, blendTexEnv); // // osg::TexEnv* decalTexEnv = new osg::TexEnv; // decalTexEnv->setMode(osg::TexEnv::DECAL); // CeilGeode->getOrCreateStateSet()->setTextureAttribute(2, decalTexEnv); return osg::ref_ptr(CeilGeode); } std::vector> Board::getEmptyFields() const { std::vector> empty; for(auto y = 0; y < getFieldCountY(); ++y) { // y for(auto x = 0; x < getFieldCountX(); ++x) { // x if(m_fieldMap[y][x] == FieldType::FIELD_EMPTY) { empty.push_back(std::tuple{x, y}); } } } return std::move(empty); } uint32_t Board::getFieldX(double x) const { return static_cast(x / getFieldSizeX()); } uint32_t Board::getFieldY(double y) const { return getFieldCountY() - (1 + static_cast(y / getFieldSizeY())); } Board::FieldType Board::getField(const double x, const double y) const { const auto intX = getFieldX(x); const auto intY = getFieldY(y); return getField(intX, intY); } osg::ref_ptr Board::draw() const { auto normalize = osg::Vec3d(0.0f, 0.0f, 0.0f); double blockSizeZ = std::max(getFieldSizeX(), getFieldSizeY()); uint16_t blockCountZ = 2; auto boardObj = make_ref(); for(auto y = 0; y < getFieldCountY(); ++y) { // y for(auto x = 0; x < getFieldCountX(); ++x) { // x if(m_fieldMap[y][x] == FieldType::FIELD_WALL) { // if(x == 15 && y == 14) { osg::Geode* WallGeode = new osg::Geode(); osg::Geometry* WallGeometry = new osg::Geometry(); WallGeode->addDrawable(WallGeometry); //specify vertices osg::Vec3dArray* WallVertices = new osg::Vec3dArray; uint32_t lod = BoardWallLOD; double totalSizeX = getFieldSizeX(); double totalSizeY = getFieldSizeY(); double totalSizeZ = blockSizeZ; double sizeX = totalSizeX / lod; double sizeY = totalSizeY / lod; double sizeZ = totalSizeZ / lod; osg::ref_ptr texture = new osg::Texture2D; osg::ref_ptr image = osgDB::readImageFile(m_dbPath + ""/"" + ActiveTheme[WALL]); texture->setImage( image.get() ); for(int z = 0; z < blockCountZ; ++z) { for(int i = lod - 1; i >= 0; --i) { for(int j = 0; j < lod; ++j) { WallVertices->push_back(osg::Vec3d(0, i * sizeY, j * sizeZ)); WallVertices->push_back(osg::Vec3d(0, i * sizeY + sizeY, j * sizeZ)); WallVertices->push_back(osg::Vec3d(0, i * sizeY + sizeY, j * sizeZ + sizeZ)); WallVertices->push_back(osg::Vec3d(0, i * sizeY, j * sizeZ + sizeZ)); } } for(int i = lod - 1; i >= 0; --i) { for(int j = 0; j < lod; ++j) { WallVertices->push_back(osg::Vec3d(totalSizeX, i * sizeY, j * sizeZ)); WallVertices->push_back(osg::Vec3d(totalSizeX, i * sizeY + sizeY, j * sizeZ)); WallVertices->push_back(osg::Vec3d(totalSizeX, i * sizeY + sizeY, j * sizeZ + sizeZ)); WallVertices->push_back(osg::Vec3d(totalSizeX, i * sizeY, j * sizeZ + sizeZ)); } } for(int i = 0; i < lod; ++i) { for(int j = 0; j < lod; ++j) { WallVertices->push_back(osg::Vec3d(i * sizeX, 0, j * sizeZ)); WallVertices->push_back(osg::Vec3d(i * sizeX + sizeX, 0, j * sizeZ)); WallVertices->push_back(osg::Vec3d(i * sizeX + sizeX, 0, j * sizeZ + sizeZ)); WallVertices->push_back(osg::Vec3d(i * sizeX, 0, j * sizeZ + sizeZ)); } } for(int i = 0; i < lod; ++i) { for(int j = 0; j < lod; ++j) { WallVertices->push_back(osg::Vec3d(i * sizeX, totalSizeY, j * sizeZ)); WallVertices->push_back(osg::Vec3d(i * sizeX + sizeX, totalSizeY, j * sizeZ)); WallVertices->push_back(osg::Vec3d(i * sizeX + sizeX, totalSizeY, j * sizeZ + sizeZ)); WallVertices->push_back(osg::Vec3d(i * sizeX, totalSizeY, j * sizeZ + sizeZ)); } } WallGeometry->setVertexArray( WallVertices ); //specify the kind of geometry we want to draw here osg::DrawElementsUInt* WallBase = new osg::DrawElementsUInt(osg::PrimitiveSet::QUADS, 0); for(int i = 0; i < lod * lod * 4 * 4; ++i) WallBase->push_back(i); WallGeometry->addPrimitiveSet(WallBase); osg::ref_ptr texcoords = new osg::Vec2Array; double tsizeX = 1.0 / lod; double tsizeY = 1.0 / lod; for(int i = 0; i < lod; ++i) { for(int j = 0; j < lod; ++j) { texcoords->push_back(osg::Vec2d(i * tsizeX, j * tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX + tsizeX, j * tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX + tsizeX, j * tsizeY + tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX, j * tsizeY + tsizeY)); } } for(int i = 0; i < lod; ++i) { for(int j = 0; j < lod; ++j) { texcoords->push_back(osg::Vec2d(i * tsizeX, j * tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX + tsizeX, j * tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX + tsizeX, j * tsizeY + tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX, j * tsizeY + tsizeY)); } } for(int i = 0; i < lod; ++i) { for(int j = 0; j < lod; ++j) { texcoords->push_back(osg::Vec2d(i * tsizeX, j * tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX + tsizeX, j * tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX + tsizeX, j * tsizeY + tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX, j * tsizeY + tsizeY)); } } for(int i = 0; i < lod; ++i) { for(int j = 0; j < lod; ++j) { texcoords->push_back(osg::Vec2d(i * tsizeX, j * tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX + tsizeX, j * tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX + tsizeX, j * tsizeY + tsizeY)); texcoords->push_back(osg::Vec2d(i * tsizeX, j * tsizeY + tsizeY)); } } osg::ref_ptr normals = new osg::Vec3Array; for(int i = 0; i < lod; ++i) { for(int j = 0; j < lod; ++j) { normals->push_back( osg::Vec3(-1.0f, 0.0f, 0.0f) ); normals->push_back( osg::Vec3(-1.0f, 0.0f, 0.0f) ); normals->push_back( osg::Vec3(-1.0f, 0.0f, 0.0f) ); normals->push_back( osg::Vec3(-1.0f, 0.0f, 0.0f) ); } } for(int i = 0; i < lod; ++i) { for(int j = 0; j < lod; ++j) { normals->push_back( osg::Vec3(1.0f, 0.0f, 0.0f) ); normals->push_back( osg::Vec3(1.0f, 0.0f, 0.0f) ); normals->push_back( osg::Vec3(1.0f, 0.0f, 0.0f) ); normals->push_back( osg::Vec3(1.0f, 0.0f, 0.0f) ); } } for(int i = 0; i < lod; ++i) { for(int j = 0; j < lod; ++j) { normals->push_back( osg::Vec3(0.0f, -1.0f, 0.0f) ); normals->push_back( osg::Vec3(0.0f, -1.0f, 0.0f) ); normals->push_back( osg::Vec3(0.0f, -1.0f, 0.0f) ); normals->push_back( osg::Vec3(0.0f, -1.0f, 0.0f) ); } } for(int i = 0; i < lod; ++i) { for(int j = 0; j < lod; ++j) { normals->push_back( osg::Vec3(0.0f, 1.0f, 0.0f) ); normals->push_back( osg::Vec3(0.0f, 1.0f, 0.0f) ); normals->push_back( osg::Vec3(0.0f, 1.0f, 0.0f) ); normals->push_back( osg::Vec3(0.0f, 1.0f, 0.0f) ); } } for(int i = 0; i < lod; ++i) { for(int j = 0; j < lod; ++j) { normals->push_back( osg::Vec3(0.0f, -1.0f, 0.0f) ); normals->push_back( osg::Vec3(0.0f, -1.0f, 0.0f) ); normals->push_back( osg::Vec3(0.0f, -1.0f, 0.0f) ); normals->push_back( osg::Vec3(0.0f, -1.0f, 0.0f) ); } } WallGeometry->setTexCoordArray(1, texcoords.get() ); WallGeode->getOrCreateStateSet()->setTextureAttributeAndModes(1, texture.get() ); WallGeode->setCullingActive(true); WallGeometry->setNormalArray(normals); WallGeometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX); osg::ref_ptr material = new osg::Material; material->setAmbient( osg::Material::FRONT_AND_BACK, osg::Vec4(0.5f, 0.5f, 0.5f, 1.0f) ); material->setDiffuse( osg::Material::FRONT_AND_BACK, osg::Vec4(0.0f, 1.0f, 1.0f, 1.0f) ); material->setSpecular( osg::Material::FRONT_AND_BACK, osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f) ); material->setDataVariance(osg::Material::STATIC); material->setShininess(osg::Material::FRONT_AND_BACK, 1.0); //WallGeode->getOrCreateStateSet()->setAttributeAndModes(material); auto translate = make_ref(osg::Matrix::translate(getFieldCenterX(x) - getFieldSizeX() / 2, getFieldCenterY(y) - getFieldSizeY() / 2, z * blockSizeZ)); translate->addChild(WallGeode); boardObj->addChild(translate); } } } } auto FloorGeode = DrawSquare(getSizeX(), getSizeY(), std::atoi(ActiveTheme[FLOOR_REPEAT].c_str()), BoardFloorLOD, ActiveTheme[FLOOR]); auto CeilGeode = DrawSquare(getSizeX(), getSizeY(), 8, BoardFloorLOD, ActiveTheme[CEIL]); auto CeilTranslate = make_ref(osg::Matrix::translate(0, 0, blockCountZ * blockSizeZ)); CeilTranslate->addChild(CeilGeode); boardObj->addChild(FloorGeode); boardObj->addChild(CeilTranslate); return boardObj; } ",RootSizeX 323,"/* * Copyright 2023 Babit Authors * * This file is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This file 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 * Lesser General Public License for more details. */ #include ""audio_fifo.h"" AudioFifo::AudioFifo(int format, int channels, uint64_t channel_layout, AVRational time_base, int sample_rate) { format_ = format; channels_ = channels; audio_fifo_ = av_audio_fifo_alloc((AVSampleFormat) format, channels, 2048); time_base_ = time_base; channel_layout_ = channel_layout; sample_rate_ = sample_rate; pts_per_sample_ = time_base.den / float(time_base.num) / sample_rate; if (!audio_fifo_) BMFLOG(BMF_ERROR) << ""Could not allocate audio_fifo_""; } int AudioFifo::read(int samples, bool partial, bool &got_frame, AVFrame *&frame) { int ret; got_frame = false; int buffered_samples = av_audio_fifo_size(audio_fifo_); if (buffered_samples < 1) { return 0; } if (buffered_samples < samples) { if (partial) { samples = buffered_samples; } else { return 0; } } frame->format = format_; frame->channel_layout = channel_layout_; frame->sample_rate = sample_rate_; frame->nb_samples = samples; ret = av_frame_get_buffer(frame, 0); if (ret < 0) { BMFLOG(BMF_ERROR) << ""Error allocating an audio buffer""; return ret; } int [MASK] = av_audio_fifo_read(audio_fifo_, (void **) (frame->extended_data), samples); if ( [MASK] < 0) { BMFLOG(BMF_ERROR) << ""av_audio_fifo_read "" << [MASK] ; return [MASK] ; } got_frame = true; frame->nb_samples = [MASK] ; if (first_pts_ != AV_NOPTS_VALUE) { frame->pts = (int64_t) (pts_per_sample_ * samples_read_) + first_pts_; } else { frame->pts = AV_NOPTS_VALUE; } samples_read_ += [MASK] ; return 0; } int AudioFifo::read_many(int samples, bool partial, std::vector &frame_list) { while (1) { AVFrame *frame = NULL; frame = av_frame_alloc(); if (!frame) { BMFLOG(BMF_ERROR) << ""Could not allocate AVFrame""; return -1; } bool got_frame = false; int ret = read(samples, partial, got_frame, frame); if (ret < 0) { return ret; } if (!got_frame) { av_frame_free(&frame); return 0; } frame_list.push_back(frame); } return 0; } int AudioFifo::write(AVFrame *frame) { int ret; if (first_frame_) { first_pts_ = frame->pts; first_frame_ = false; } ret = av_audio_fifo_write(audio_fifo_, (void **) (frame->extended_data), frame->nb_samples); return ret; } AudioFifo::~AudioFifo() { if (audio_fifo_) av_audio_fifo_free(audio_fifo_); } ",read_samples 324,"#include ""rest_client_test.h"" #include #include #include #include #include RestClientTest::RestClientTest() { } void RestClientTest::initTestCase() { } void RestClientTest::testSingleThreadWork() { QEventLoop loop; HttpRequestInput* request = new HttpRequestInput(""https://postman-echo.com/get?foo1=bar1&foo2=bar2"", Literals::getMethod); HttpRequestWorker* worker = new HttpRequestWorker(); worker->setReadResponseOnError(true); worker->execute(request); bool ok = false; QObject::connect(worker, &HttpRequestWorker::executionFinished, [&loop, &ok, request](HttpRequestWorker * worker) mutable { QByteArray response = worker->response; qDebug() << ""status code "" << worker->statusCode; worker->deleteLater(); delete request; if (worker->statusCode == 200) { ok = true; } loop.exit(); }); loop.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::ExcludeSocketNotifiers); QCOMPARE(ok, true); } void RestClientTest::testMultithreadWork() { const int [MASK] = 10000; QFuture statuses[ [MASK] ]; auto function = [=] () -> bool { QEventLoop loop; HttpRequestInput* request = new HttpRequestInput(""https://postman-echo.com/get?foo1=bar1&foo2=bar2"", Literals::getMethod); HttpRequestWorker* worker = new HttpRequestWorker(); worker->setReadResponseOnError(true); worker->execute(request); bool ok = false; QObject::connect(worker, &HttpRequestWorker::executionFinished, [&loop, &ok, request](HttpRequestWorker * worker) mutable { QByteArray response = worker->response; qWarning() << ""status code "" << worker->statusCode; worker->deleteLater(); delete request; if (worker->statusCode == 200) { ok = true; } loop.exit(ok); }); return loop.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::ExcludeSocketNotifiers); }; for(int i = 0; i < [MASK] ; ++i) { statuses[i] = QtConcurrent::run(function); } for(int i = 0; i < [MASK] ; ++i) { statuses[i].waitForFinished(); } bool ok = true; for(int i = 0; i < [MASK] ; ++i) { if (!statuses[i].result()) { qDebug() << ""result of "" << i << "" operation is false""; ok = false; } } QCOMPARE(ok, true); } void RestClientTest::cleanupTestCase() { } ",threadCount 325,"#include #include #include #include #include #include namespace py = pybind11; std::vector> generate_negative_samples(const std::vector>& edge_index, const std::vector>& pos_edge_index, int num_neg_samples) { if (num_neg_samples <= 0) { throw std::invalid_argument(""num_neg_samples must be greater than 0""); } std::vector neg_srcs; std::vector neg_dsts; std::set nodeset; std::unordered_map> [MASK] ; for (size_t i = 0; i < edge_index[0].size(); ++i) { int src = edge_index[0][i]; int dst = edge_index[1][i]; nodeset.insert(src); nodeset.insert(dst); [MASK] [src].insert(dst); [MASK] [dst].insert(src); } std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, nodeset.size() - 1); int src, dst, neg_node; for(int i = 0; i < pos_edge_index[0].size(); i++){ src = pos_edge_index[0][i]; dst = pos_edge_index[1][i]; std::set unavail_nodes; unavail_nodes.insert(src); unavail_nodes.insert(dst); unavail_nodes.insert( [MASK] [src].begin(), [MASK] [src].end()); unavail_nodes.insert( [MASK] [dst].begin(), [MASK] [dst].end()); for(int j = 0; j < num_neg_samples/2; j++){ do { neg_node = dis(gen); } while (unavail_nodes.count(neg_node) > 0); neg_srcs.push_back(src); neg_dsts.push_back(neg_node); } for(int j = 0; j < num_neg_samples/2; j++){ do { neg_node = dis(gen); } while (unavail_nodes.count(neg_node) > 0); neg_srcs.push_back(neg_node); neg_dsts.push_back(dst); } } return {neg_srcs, neg_dsts}; } PYBIND11_MODULE(negative_sampling, m) { m.def(""generate_negative_samples"", &generate_negative_samples, ""A function to generate negative samples"", py::arg(""edge_index""), py::arg(""pos_edge_index""), py::arg(""num_neg_samples"")); }",adj_list 326,"#include #include #include #include #include #include #include #include #include using namespace std; int R,C,F,N,B,T; int dist(int x1,int y1,int x2,int y2){ return abs(x1-x2)+abs(y1-y2); } class ride { public: int a,b,x,y,s,f,num; ride(int aa,int bb,int xx,int yy,int ss,int ff,int nnum){ a=aa; b=bb; x=xx; y=yy; s=ss; f=ff; num=nnum; } int ddist(){ return dist(a,b,x,y); } }; class taxi { public: deque rides; int avail; int endx; int endy; }; bool com(ride a,ride b){ return a.s b.avail; } }; deque q; priority_queue, compare> taxis; int main() { int ee = 2; string si,so; switch(ee) { case 0: si=""a_example.in"";so=""a_example.out""; break; case 1: si=""b_should_be_easy.in"";so=""b_should_be_easy.out""; break; case 2: si=""c_no_hurry.in"";so=""c_no_hurry.out""; break; case 3: si=""d_metropolis.in"";so=""d_metropolis.out""; break; case 4: si=""e_high_bonus.in"";so=""e_high_bonus.out""; break; } int i,a,b,x,y,f,s; ifstream inf(si); if(inf.is_open()){ cout << ""open\n""; } else { cout << ""close""; return -1; } inf >> R >> C >> F >> N >> B >> T; for(i=0;i> a >> b >> x >> y >> s >> f; ride temp(a,b,x,y,s,f,i); q.push_back(temp); } inf.close(); sort(q.begin(),q.end(),com); for(i=0;i0){ taxi temp=taxis.top(); taxis.pop(); long long bestnum = -2000000000000000000; int bestpos = -1; for(i=0;i= q[i].f){ continue; } long long tempnum = q[i].ddist(); if (dist(temp.endx,temp.endy,q[i].a,q[i].b)+temp.avail < q[i].s){ tempnum += B; } tempnum -= (dist(temp.endx,temp.endy,q[i].a,q[i].b) + max(q[i].s- (dist(temp.endx,temp.endy,q[i].a,q[i].b) + temp.avail),0))*200; if(tempnum > bestnum ) { bestpos = i; bestnum = tempnum; } } if(bestpos < 0) { temp.avail = T+2; taxis.push(temp); continue; } [MASK] += q[bestpos].ddist(); if (dist(temp.endx,temp.endy,q[bestpos].a,q[bestpos].b)+temp.avail <= q[bestpos].s){ [MASK] += B; } temp.rides.push_back(q[bestpos].num); temp.avail = max(dist(temp.endx,temp.endy,q[bestpos].a,q[bestpos].b)+temp.avail,q[bestpos].s)+q[bestpos].ddist(); temp.endx = q[bestpos].x; temp.endy = q[bestpos].y; taxis.push(temp); q.erase(q.begin()+bestpos); } ofstream outf(so); while(!taxis.empty()){ taxi temp = taxis.top(); taxis.pop(); outf << temp.rides.size() << "" ""; for(int i = 0; i < temp.rides.size(); i++) { outf << temp.rides[i] << "" ""; } outf << endl; } outf.close(); cout << [MASK] ; return 0; } ",total 327,"#include ""fat.hpp"" #include #include namespace fat { BPB *boot_volume_image; unsigned long bytes_per_cluster; void Initialize(void *volume_image) { boot_volume_image = reinterpret_cast(volume_image); bytes_per_cluster = static_cast(boot_volume_image->bytes_per_sec) * boot_volume_image->sec_per_clus; } uintptr_t GetClusterAddr(unsigned long cluster) { unsigned long sector_num = boot_volume_image->rsvd_sec_cnt + boot_volume_image->num_fats * boot_volume_image->fat_sz_32 + (cluster - 2) * boot_volume_image->sec_per_clus; uintptr_t offset = sector_num * boot_volume_image->bytes_per_sec; return reinterpret_cast(boot_volume_image) + offset; } bool IsEndOfClusterchain(unsigned long cluster) { return cluster >= 0x0ffffff8ul; } uint32_t *GetFAT() { uintptr_t [MASK] = boot_volume_image->rsvd_sec_cnt * boot_volume_image->bytes_per_sec; return reinterpret_cast( reinterpret_cast(boot_volume_image) + [MASK] ); } void ReadName(const DirectoryEntry &entry, char *base, char *ext) { memcpy(base, &entry.name[0], 8); base[8] = 0; for (int i = 7; i >= 0 && base[i] == 0x20; i--) { base[i] = 0; } memcpy(ext, &entry.name[8], 3); { ext[3] = 0; for (int i = 2; i >= 0 && ext[i] == 0x20; i--) { ext[i] = 0; } } } void FormatName(const DirectoryEntry &entry, char *dest) { // extension length in fat format is 3. // 1 byte(period) + 3 byte(extension) + 1 byte(null string) char ext[5] = "".""; ReadName(entry, dest, &ext[1]); if (ext[1]) { strcat(dest, ext); } } unsigned long NextCluster(unsigned long cluster) { uint32_t *fat = GetFAT(); uint32_t next = fat[cluster]; if (IsEndOfClusterchain(next)) { return kEndOfClusterchain; } return next; } bool NameIsEqual(const DirectoryEntry &entry, const char *name) { unsigned char name83[11]; // 0x20 is empty in ascii memset(name83, 0x20, sizeof(name83)); int i = 0; int i83 = 0; for (; name[i] != 0 && i83 < sizeof(name83); i++, i83++) { if (name[i] == '.') { i83 = 7; continue; } name83[i83] = toupper(name[i]); } return memcmp(entry.name, name83, sizeof(name83)) == 0; } std::pair FindFile(const char *path, unsigned long directory_cluster) { if (path[0] == '/') { directory_cluster = boot_volume_image->root_clus; path++; } else if (directory_cluster == 0) { directory_cluster = boot_volume_image->root_clus; } char path_elem[13]; const auto [next_path, post_slash] = NextPathElement(path, path_elem); const bool path_last = next_path == nullptr || next_path[0] == '\0'; while (directory_cluster != kEndOfClusterchain) { auto dir = GetSectorByCluster(directory_cluster); for (int i = 0; i < bytes_per_cluster / sizeof(DirectoryEntry); i++) { if (dir[i].name[0] == 0x00) { return {nullptr, post_slash}; } else if (!NameIsEqual(dir[i], path_elem)) { continue; } if (dir[i].attr == Attribute::kDirectory && !path_last) { return FindFile(next_path, dir[i].FirstCluster()); } else { // dir[i] is not directory, but we occured last path. // so we finish searching. return {&dir[i], post_slash}; } } directory_cluster = NextCluster(directory_cluster); } return {nullptr, post_slash}; } std::pair NextPathElement(const char *path, char *path_elem) { const char *next_slash = strchr(path, '/'); if (next_slash == nullptr) { strcpy(path_elem, path); return {nullptr, false}; } const auto elem_len = next_slash - path; strncpy(path_elem, path, elem_len); path_elem[elem_len] = '\0'; return {&next_slash[1], true}; } size_t LoadFile(void *buf, size_t len, const DirectoryEntry &entry) { auto is_valid_cluster = [](uint32_t c) { return c != 0 && c != fat::kEndOfClusterchain; }; auto cluster = entry.FirstCluster(); // why does we use uint8? const auto buf_uint8 = reinterpret_cast(buf); const auto buf_end = buf_uint8 + len; auto p = buf_uint8; while (is_valid_cluster(cluster)) { if (bytes_per_cluster >= buf_end - p) { memcpy(p, GetSectorByCluster(cluster), buf_end - p); return len; } memcpy(p, GetSectorByCluster(cluster), bytes_per_cluster); p += bytes_per_cluster; cluster = NextCluster(cluster); } return p - buf_uint8; } FileDescriptor::FileDescriptor(DirectoryEntry &fat_entry) : fat_entry_{fat_entry} {} size_t FileDescriptor::Read(void *buf, size_t len) { if (rd_cluster_ == 0) { rd_cluster_ = fat_entry_.FirstCluster(); } uint8_t *buf8 = reinterpret_cast(buf); len = std::min(len, fat_entry_.file_size - rd_off_); size_t total = 0; while (total < len) { uint8_t *sec = GetSectorByCluster(rd_cluster_); size_t n = std::min(len - total, bytes_per_cluster - rd_cluster_off_); memcpy(&buf8[total], &sec[rd_cluster_off_], n); total += n; rd_cluster_off_ += n; if (rd_cluster_off_ == bytes_per_cluster) { rd_cluster_ = NextCluster(rd_cluster_); rd_cluster_off_ = 0; } } rd_off_ += total; return total; } size_t FileDescriptor::Write(const void *buf, size_t len) { auto num_cluster = [](size_t bytes) { return (bytes + bytes_per_cluster - 1) / bytes_per_cluster; }; if (wr_cluster_ == 0) { if (fat_entry_.FirstCluster() != 0) { wr_cluster_ = fat_entry_.FirstCluster(); } else { wr_cluster_ = AllocateClusterChain(num_cluster(len)); fat_entry_.fst_clus_lo = wr_cluster_ & 0xffff; fat_entry_.fst_clus_hi = (wr_cluster_ >> 16) & 0xffff; } } const uint8_t *buf8 = reinterpret_cast(buf); size_t total = 0; while (total < len) { if (wr_cluster_off_ == bytes_per_cluster) { const auto next_cluster = NextCluster(wr_cluster_); if (next_cluster == kEndOfClusterchain) { wr_cluster_ = ExtendCluster(wr_cluster_, num_cluster(len - total)); } else { wr_cluster_ = next_cluster; } wr_cluster_off_ = 0; } uint8_t *sec = GetSectorByCluster(wr_cluster_); size_t n = std::min(len, bytes_per_cluster - wr_cluster_off_); memcpy(&sec[wr_cluster_off_], &buf8[total], n); total += n; wr_cluster_off_ += n; } wr_off_ += total; fat_entry_.file_size = wr_off_; return total; } WithError CreateFile(const char *path) { auto parent_dir_cluster = fat::boot_volume_image->root_clus; const char *filename = path; if (const char *slash_pos = strrchr(path, '/')) { filename = &slash_pos[1]; if (slash_pos[1] == '\0') { return {nullptr, MAKE_ERROR(Error::kIsDirectory)}; } char parent_dir_name[slash_pos - path + 1]; strncpy(parent_dir_name, path, slash_pos - path); parent_dir_name[slash_pos - path] = '\0'; if (parent_dir_name[0] != '\0') { auto [parent_dir, post_slash2] = fat::FindFile(parent_dir_name); if (parent_dir == nullptr) { return {nullptr, MAKE_ERROR(Error::kNoSuchEntry)}; } parent_dir_cluster = parent_dir->FirstCluster(); } } auto dir = fat::AllocateEntry(parent_dir_cluster); if (dir == nullptr) { return {nullptr, MAKE_ERROR(Error::kNoEnoughMemory)}; } fat::SetFileName(*dir, filename); dir->file_size = 0; return {dir, MAKE_ERROR(Error::kSuccess)}; } DirectoryEntry *AllocateEntry(unsigned long dir_cluster) { while (true) { auto dir = GetSectorByCluster(dir_cluster); for (int i = 0; i < bytes_per_cluster / sizeof(DirectoryEntry); i++) { if (dir[i].name[0] == 0 || dir[i].name[0] == 0xe5) { return &dir[i]; } } auto next = NextCluster(dir_cluster); if (next == kEndOfClusterchain) { break; } dir_cluster = next; } dir_cluster = ExtendCluster(dir_cluster, 1); auto dir = GetSectorByCluster(dir_cluster); memset(dir, 0, bytes_per_cluster); return &dir[0]; } unsigned long AllocateClusterChain(size_t n) { uint32_t *fat = GetFAT(); unsigned long first_cluster; for (first_cluster = 2;; first_cluster++) { if (fat[first_cluster] == 0) { fat[first_cluster] = kEndOfClusterchain; break; } } if (n > 1) { ExtendCluster(first_cluster, n - 1); } return first_cluster; } unsigned long ExtendCluster(unsigned long eoc_cluster, size_t n) { uint32_t *fat = GetFAT(); while (!IsEndOfClusterchain(fat[eoc_cluster])) { eoc_cluster = fat[eoc_cluster]; } size_t num_allocated = 0; auto current = eoc_cluster; for (unsigned long candidate = 2; num_allocated < n; candidate++) { if (fat[candidate] != 0) { continue; } fat[current] = candidate; current = candidate; num_allocated++; } fat[current] = kEndOfClusterchain; return current; } void SetFileName(DirectoryEntry &entry, const char *name) { const char *dot_pos = strrchr(name, '.'); memset(entry.name, ' ', 8 + 3); if (dot_pos) { for (int i = 0; i < 8 && i < dot_pos - name; i++) { entry.name[i] = toupper(name[i]); } for (int i = 0; i < 4 && dot_pos[i + 1]; i++) { entry.name[8 + i] = toupper(name[i + 1]); } } else { for (int i = 0; i < 8 && name[i]; i++) { entry.name[i] = toupper(name[i]); } } } }",fat_offset 328,"#pragma once #include #include #include #include #include #include #include ""usfl.h"" #include ""configuration.h"" #include ""ByteData.hpp"" struct BTServerCallbacks { virtual void onWriteMode(unsigned int mode); virtual void onWriteData(const ByteData &data); virtual void onWriteLedCount(unsigned int led_count); }; class BTServer : protected BLECharacteristicCallbacks, protected BLEServerCallbacks { public: public: static BTServer &getInstance() { static BTServer [MASK] ; return [MASK] ; } public: void addListener(BTServerCallbacks *callback) { _writeDataCallbacks.push_front(callback); } void removeListener(BTServerCallbacks *callback) { _writeDataCallbacks.remove(callback); } private: void _writeModeNotify(unsigned int mode) { for (auto &callback : _writeDataCallbacks) callback->onWriteMode(mode); } void _writeDataNotify(const ByteData &data) { for (auto &callback : _writeDataCallbacks) callback->onWriteData(data); } void _writeLedCountNotify(unsigned int led_count) { for (auto &callback : _writeDataCallbacks) callback->onWriteLedCount(led_count); } private: std::forward_list _writeDataCallbacks; private: BTServer() { BLEDevice::init(DEVICE_NAME); bleserver = BLEDevice::createServer(); bleserver->setCallbacks(this); BLEService *service = bleserver->createService(SERVICE_UUID); service->createCharacteristic(VERSION_CHAR_UUID, BLECharacteristic::PROPERTY_READ) ->setValue(PROG_VERSION); led_count_char = service->createCharacteristic(LED_COUNT_CHAR_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE); led_count_char->setCallbacks(this); mode_char = service->createCharacteristic(MODE_CHAR_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE); mode_char->setCallbacks(this); data_char = service->createCharacteristic(DATA_CHAR_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE); data_char->setCallbacks(this); service->start(); _startAdvertising(); } ~BTServer() = default; BTServer(const BTServer &) = delete; BTServer &operator=(const BTServer &) = delete; void _startAdvertising() { BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); pAdvertising->addServiceUUID(SERVICE_UUID); pAdvertising->setScanResponse(true); pAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue pAdvertising->setMinPreferred(0x12); BLEDevice::startAdvertising(); } private: BLEServer *bleserver; BLECharacteristic *led_count_char; BLECharacteristic *mode_char; BLECharacteristic *data_char; protected: void onConnect(BLEServer *pServer) override { Serial.printf(""Connected: id = %u\n"", pServer->getPeerDevices(true).begin()->first); // connectEvent.notify(nullptr); } void onDisconnect(BLEServer *pServer) override { Serial.printf(""Disconnected: id = %u\n"", pServer->getPeerDevices(true).begin()->first); // disconnectEvent.notify(nullptr); } void onRead(BLECharacteristic *pCharacteristic) override { } void onWrite(BLECharacteristic *pCharacteristic) override { if (pCharacteristic == mode_char) { _writeModeNotify(*(unsigned int *)pCharacteristic->getData()); LOG(""mode_char""); } else if (pCharacteristic == data_char) { ByteData data{ data_char->getData(), data_char->getValue().size()}; _writeDataNotify(data); LOG(""data_char""); } else if (pCharacteristic == led_count_char) { _writeLedCountNotify(*(unsigned int *)pCharacteristic->getData()); LOG(""led_count_char""); } } private: }; ",instance 329,"// Copyright (c) 2021, NVIDIA CORPORATION. // // 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 #include #include #include #include #include #include namespace nvtabular { namespace inference { namespace py = pybind11; struct ColumnMapping { explicit ColumnMapping(const std::string &column_name, const std::string &filename) : filename(filename) { // use pandas to read into a dataframe. Note: we're purposefully doing this on the // CPU here to avoid using gpu memory at inference time py::object pandas = py::module_::import(""pandas""); py::object df = pandas.attr(""read_parquet"")(filename); py::object isnull = pandas.attr(""isnull""); py::array values = df[column_name.c_str()].attr(""values""); auto dtype = values.dtype(); if ((dtype.kind() == 'O') || (dtype.kind() == 'U')) { int64_t i = UNIQUE_OFFSET; for (auto &value : values) { if (!py::cast(isnull(value))) { if (PyUnicode_Check(value.ptr()) || PyBytes_Check(value.ptr())) { std::string key = py::cast(value); mapping_str[key] = i; } else if (PyBool_Check(value.ptr())) { // so we're categorifying bool columns in the rossmann dataset - which makes little // sense but we have to handle I guess ? mapping_int[value.ptr() == Py_True] = i; } else if (PyLong_Check(value.ptr())) { auto key = py::cast(value); mapping_int[key] = i; } else { std::stringstream error; error << ""Don't know how to handle column "" << column_name << "" @ "" << filename; throw std::invalid_argument(error.str()); } } i++; } } else { // TODO: array dispatch code switch (dtype.kind()) { case 'f': switch (dtype.itemsize()) { case 4: insert_int_mapping(values); return; case 8: insert_int_mapping(values); return; } break; case 'u': switch (dtype.itemsize()) { case 1: insert_int_mapping(values); return; case 2: insert_int_mapping(values); return; case 4: insert_int_mapping(values); return; case 8: insert_int_mapping(values); return; } break; case 'i': switch (dtype.itemsize()) { case 1: insert_int_mapping(values); return; case 2: insert_int_mapping(values); return; case 4: insert_int_mapping(values); return; case 8: insert_int_mapping(values); return; } break; } std::stringstream error; error << ""unhandled dtype "" << dtype.kind() << dtype.itemsize() << "" for column "" << column_name; throw std::invalid_argument(error.str()); } } template void insert_int_mapping(py::array_t values) { const T *data = values.data(); size_t size = values.size(); for (size_t i = 0; i < size; ++i) { mapping_int[static_cast(data[i])] = i + UNIQUE_OFFSET; } } template py::array transform_int(py::array_t input) const { py::object pandas = py::module_::import(""pandas""); py::object isnull = pandas.attr(""isnull""); py::array_t output(input.size()); const T *input_data = input.data(); int64_t *output_data = output.mutable_data(); for (int64_t i = 0; i < input.size(); ++i) { auto it = mapping_int.find(static_cast(input_data[i])); if (it == mapping_int.end()) { output_data[i] = py::cast(isnull(input_data[i])) ? NULL_INDEX : OOV_INDEX; } else { output_data[i] = it->second; } } return output; } py::array transform(py::array input) const { auto dtype = input.dtype(); auto kind = dtype.kind(); if ((kind == 'O') || (kind == 'U')) { size_t i = 0; py::array_t output(input.size()); int64_t *data = output.mutable_data(); for (auto &value : input) { if (value.is_none()) { data[i] = NULL_INDEX; } else if (PyUnicode_Check(value.ptr()) || PyBytes_Check(value.ptr())) { std::string key = py::cast(value); auto it = mapping_str.find(key); data[i] = it == mapping_str.end() ? OOV_INDEX : it->second; } else if (PyBool_Check(value.ptr())) { auto it = mapping_int.find(value.ptr() == Py_True); data[i] = it == mapping_int.end() ? OOV_INDEX : it->second; } else { throw std::invalid_argument(""unknown dtype""); } i++; } return output; } else { // TODO: array dispatch code auto itemsize = dtype.itemsize(); switch (kind) { // floats don't really make sense here, but can happen because of auto // conversion with pandas code involving none values case 'f': switch (itemsize) { case 4: return transform_int(input); case 8: return transform_int(input); } break; case 'u': switch (itemsize) { case 1: return transform_int(input); case 2: return transform_int(input); case 4: return transform_int(input); case 8: return transform_int(input); } break; case 'i': switch (itemsize) { case 1: return transform_int(input); case 2: return transform_int(input); case 4: return transform_int(input); case 8: return transform_int(input); } break; case 'b': return transform_int(input); } std::stringstream error; error << ""unhandled dtype "" << kind << itemsize << "" for column '"" << column_name << ""'""; throw std::invalid_argument(error.str()); } } std::string filename; std::string column_name; std::unordered_map mapping_str; std::unordered_map mapping_int; // TODO: Handle multiple OOV buckets? const int64_t NULL_INDEX = 1; const int64_t OOV_INDEX = 2; const int64_t UNIQUE_OFFSET = 3; }; // Reads in a parquet category mapping file in cpu memory using pandas std::shared_ptr get_column_mapping(const std::string &column_name, const std::string &filename) { // because of how we're doing multi-gpu inside of tritonserver, we could have // multiple instances of the same workflow running in the same process. (with // each workflow having unique per-gpu data). // Since we're storing this mapping in CPU memory, lets cache values across // processes to reduce duplicate memory usage. static std::map> cache; static std::mutex m; std::lock_guard lock(m); auto cache_item = cache[filename].lock(); if (!cache_item) { cache[filename] = cache_item = std::make_shared(column_name, filename); } return cache_item; } // Accelerated categorify operator for running under triton inference server struct CategorifyTransform { explicit CategorifyTransform(py::object op) { py::dict categories = op.attr(""categories""); for (auto &item : categories) { auto column = py::cast(item.first); auto filename = py::cast(item.second); columns[column] = get_column_mapping(column, filename); } } py::object transform(py::object column_selector, py::dict [MASK] ) { for (auto it : [MASK] ) { auto column_name = py::cast(it.first); auto mapping = columns.find(column_name); if (mapping == columns.end()) { std::stringstream err; err << ""Unknown column for CategorifyTransform "" << column_name; throw std::invalid_argument(err.str()); } if (PyTuple_Check(it.second.ptr())) { auto value_offsets = py::cast(it.second); auto tensor = py::cast(value_offsets[0]); [MASK] [column_name.c_str()] = py::make_tuple(mapping->second->transform(tensor), value_offsets[1]); } else { auto tensor = py::cast(it.second); [MASK] [column_name.c_str()] = mapping->second->transform(tensor); } } return [MASK] ; } std::unordered_map> columns; }; void export_categorify(py::module_ m) { py::class_(m, ""CategorifyTransform"") .def(py::init()) .def(""transform"", &CategorifyTransform::transform) // this operator currently only supports CPU arrays .def_property_readonly(""supports"", [](py::object self) { py::object supports = py::module_::import(""nvtabular"").attr(""graph"").attr(""operator"").attr(""Supports""); return supports.attr(""CPU_DICT_ARRAY""); }) .def_property_readonly(""supported_formats"", [](py::object self) { py::object supported = py::module_::import(""nvtabular"").attr(""graph"").attr(""operator"").attr(""DataFormats""); return supported.attr(""NUMPY_DICT_ARRAY""); }); } } // namespace inference } // namespace nvtabular ",tensors 330,"#include #include #include #include #define MOVE_FORWARD 1 #define MOVE_LEFT 2 #define MOVE_RIGHT 3 #define MOVE_REVERSE 4 #define MOVE_DANCE 7 #define MOVE_STAR_WARS 8 #define MOVE_STOP 6 #define SLOW_SPEED 100 #define DEFAULT_SPEED 200 //Definition of the notes' frequecies in Hertz. #define c 261 #define d 294 #define e 329 #define f 349 #define g 391 #define gS 415 #define a 440 #define aS 455 #define b 466 #define cH 523 #define cSH 554 #define dH 587 #define dSH 622 #define eH 659 #define fH 698 #define fSH 740 #define gH 784 #define gSH 830 #define aH 880 // Variable declaration MeDCMotor motor_9(9); MeDCMotor motor_10(10); MeRGBLed rgbled_7(7, 7==7?2:4); MeBuzzer buzzer; int isPlayingMusic = 0; int receivedCommand; boolean newData = false; /* * Helper method for the handling of the */ void updateSpeed(int leftSpeed, int rightSpeed){ motor_9.run((9)==M1?-(leftSpeed):(leftSpeed)); motor_10.run((10)==M1?-(rightSpeed):(rightSpeed)); } void dance(){ rgbled_7.setColor(1,0, 255, 213); rgbled_7.show(); handle( MOVE_LEFT, SLOW_SPEED ); _delay(1); handle( MOVE_RIGHT, SLOW_SPEED ); _delay(1); handle( MOVE_LEFT, SLOW_SPEED ); _delay(1); handle( MOVE_RIGHT, SLOW_SPEED ); _delay(1); handle( MOVE_FORWARD, SLOW_SPEED ); _delay(1); handle( MOVE_REVERSE, SLOW_SPEED ); _delay(1); handle( MOVE_STOP, SLOW_SPEED ); rgbled_7.setColor(1,255, 0, 255); rgbled_7.show(); } /** * Sample music playing of the Imperial march */ void starWars(){ isPlayingMusic = 1; buzzer.tone(a, 500); buzzer.tone(a, 500); buzzer.tone(a, 500); buzzer.tone(f, 350); buzzer.tone(cH, 150); buzzer.tone(a, 500); buzzer.tone(f, 350); buzzer.tone(cH, 150); buzzer.tone(a, 650); rgbled_7.setColor(1,0, 255, 213); rgbled_7.show(); handle( MOVE_LEFT, SLOW_SPEED ); handle( MOVE_RIGHT, SLOW_SPEED ); handle( MOVE_STOP, SLOW_SPEED ); //end of first bit buzzer.tone(eH, 500); buzzer.tone(eH, 500); buzzer.tone(eH, 500); buzzer.tone(fH, 350); buzzer.tone(cH, 150); buzzer.tone(gS, 500); buzzer.tone(f, 350); buzzer.tone(cH, 150); buzzer.tone(a, 650); rgbled_7.setColor(1,55, 98, 100); rgbled_7.show(); handle( MOVE_FORWARD, SLOW_SPEED ); handle( MOVE_REVERSE, SLOW_SPEED ); handle( MOVE_STOP, SLOW_SPEED ); //end of second bit... buzzer.tone(aH, 500); buzzer.tone(a, 300); buzzer.tone(a, 150); buzzer.tone(aH, 400); buzzer.tone(gSH, 200); buzzer.tone(gH, 200); buzzer.tone(fSH, 125); buzzer.tone(fH, 125); buzzer.tone(fSH, 250); rgbled_7.setColor(1,0, 255,0); rgbled_7.show(); handle( MOVE_REVERSE, SLOW_SPEED ); handle( MOVE_FORWARD, SLOW_SPEED ); handle( MOVE_STOP, SLOW_SPEED ); buzzer.tone(aS, 250); buzzer.tone(dSH, 400); buzzer.tone(dH, 200); buzzer.tone(cSH, 200); buzzer.tone(cH, 125); buzzer.tone(b, 125); buzzer.tone(cH, 250); rgbled_7.setColor(1,0,0,255); rgbled_7.show(); handle( MOVE_RIGHT, SLOW_SPEED ); handle( MOVE_LEFT, SLOW_SPEED ); handle( MOVE_STOP, SLOW_SPEED ); buzzer.tone(f, 125); buzzer.tone(gS, 500); buzzer.tone(f, 375); buzzer.tone(a, 125); buzzer.tone(cH, 500); buzzer.tone(a, 375); buzzer.tone(cH, 125); buzzer.tone(eH, 650); rgbled_7.setColor(1,255,0,0); rgbled_7.show(); handle( MOVE_LEFT, SLOW_SPEED ); handle( MOVE_RIGHT, SLOW_SPEED ); handle( MOVE_STOP, SLOW_SPEED ); //end of third bit... (Though it doesn't play well) //let's repeat it buzzer.tone(aH, 500); buzzer.tone(a, 300); buzzer.tone(a, 150); buzzer.tone(aH, 400); buzzer.tone(gSH, 200); buzzer.tone(gH, 200); buzzer.tone(fSH, 125); buzzer.tone(fH, 125); buzzer.tone(fSH, 250); rgbled_7.setColor(1,0,255,0); rgbled_7.show(); handle( MOVE_RIGHT, SLOW_SPEED ); handle( MOVE_LEFT, SLOW_SPEED ); handle( MOVE_STOP, SLOW_SPEED ); buzzer.tone(aS, 250); buzzer.tone(dSH, 400); buzzer.tone(dH, 200); buzzer.tone(cSH, 200); buzzer.tone(cH, 125); buzzer.tone(b, 125); buzzer.tone(cH, 250); rgbled_7.setColor(1,0,0,255); rgbled_7.show(); handle( MOVE_FORWARD, SLOW_SPEED ); handle( MOVE_REVERSE, SLOW_SPEED ); handle( MOVE_STOP, SLOW_SPEED ); buzzer.tone(f, 250); buzzer.tone(gS, 500); buzzer.tone(f, 375); buzzer.tone(cH, 125); buzzer.tone(a, 500); buzzer.tone(f, 375); buzzer.tone(cH, 125); buzzer.tone(a, 650); //end of the song rgbled_7.setColor(1,255,0,0); rgbled_7.show(); handle( MOVE_LEFT, SLOW_SPEED ); handle( MOVE_RIGHT, SLOW_SPEED ); handle( MOVE_REVERSE, DEFAULT_SPEED ); handle( MOVE_FORWARD, DEFAULT_SPEED ); handle( MOVE_STOP, SLOW_SPEED ); isPlayingMusic = 0; } void handle(int [MASK] , int speed){ int leftSpeed; int rightSpeed; switch( [MASK] ){ case MOVE_FORWARD: leftSpeed = speed; rightSpeed = speed; break; case MOVE_REVERSE: leftSpeed = -speed; rightSpeed = -speed; break; case MOVE_LEFT: leftSpeed = -speed; rightSpeed = speed; updateSpeed( leftSpeed, rightSpeed ); _delay(0.25); leftSpeed = speed; rightSpeed = speed; break; case MOVE_RIGHT: leftSpeed = speed; rightSpeed = -speed; updateSpeed( leftSpeed, rightSpeed ); _delay(0.25); leftSpeed = speed; rightSpeed = speed; break; case MOVE_DANCE: dance(); break; case MOVE_STAR_WARS: starWars(); break; case MOVE_STOP: leftSpeed = 0; rightSpeed = 0; break; default: leftSpeed = 0; rightSpeed = 0; } updateSpeed(leftSpeed, rightSpeed); } void setup() { Serial.begin(115200); Serial.println(""mBot waiting for instructions""); // We show a yellow ready when the arduino is ready rgbled_7.setColor(1,156,14,179); rgbled_7.show(); // We show a green when play music rgbled_7.setColor(1,255,255,0); rgbled_7.show(); } void loop() { receiveCommand(); handleInput(); _delay(1.0); } void receiveCommand() { if (isPlayingMusic == 0 && Serial.available() > 0) { receivedCommand = Serial.read(); newData = true; } } void handleInput() { if (newData == true) { Serial.print(""This just in ... ""); Serial.println(receivedCommand, DEC); newData = false; rgbled_7.setColor(1,0,0,255); rgbled_7.show(); handle( receivedCommand, DEFAULT_SPEED ); }else{ rgbled_7.setColor(1,255,0,0); rgbled_7.show(); } } void _delay(float seconds){ long endTime = millis() + seconds * 1000; while(millis() < endTime)_loop(); } void _loop(){ } ",command 331,"#include #include #include ""person.hpp"" using namespace LCppIYM; bool Person::isValidName(std::string name) { return name.size() > 0 && name.find("" "") == std::string::npos; } Person::Person(std::string fname, std::string lname) { if (! Person::isValidName(fname)) throw std::runtime_error(""Invalid fname""); if (! Person::isValidName(lname)) throw std::runtime_error(""Invalid lname""); this->fname = fname; this->lname = lname; } Person::~Person() { } void Person::kick(Person* p) const { std::cout << this->getFirstName() << "" kicked "" << p->getFirstName() << std::endl; } void Person::say(std::string [MASK] ) const { std::cout << ""\"""" << [MASK] << ""\"", said "" << this->getFirstName() << std::endl; } std::string Person::getFirstName() const { return this->fname; } std::string Person::getLastName() const { return this->lname; } std::string Person::getName() const { return this->fname + "" "" + this->lname; } ",quote 332," #include ""box.hh"" #include ""debug.hh"" #include ""keyboard.hh"" namespace Box { Box::Box() { if (tb_init() < 0) { exit(1); } this->Clear(); } Box::~Box() { tb_shutdown(); } void Box::SetClearAttributes(color_t fg, color_t bg) { tb_set_clear_attributes(fg, bg); } void Box::Clear() { tb_clear(); } void Box::Present() { tb_present(); } void Box::SetCursor(int cx, int cy) { tb_set_cursor(cx, cy); } void Box::HideCursor() { tb_set_cursor(TB_HIDE_CURSOR, TB_HIDE_CURSOR); } void Box::PutCell(int x, int y, const Cell::Cell &cell) { if ('\0' == cell.ch()) { return; } const auto tb = tb_cell(cell); tb_put_cell(x, y, &tb); } void Box::Blit(int x, int y, int w, int h, std::vector cells) { std::vector tb(cells.begin(), cells.end()); tb_blit(x, y, w, h, tb.data()); } int Box::SelectInputMode(int mode) { return tb_select_input_mode(mode); } int Box::SelectOutputMode(OutputMode mode) { return tb_select_output_mode(static_cast(mode)); } EventType Box::PeekEvent(struct tb_event *event, const int [MASK] ) { auto ev = tb_peek_event(event, [MASK] ); if (ev == TB_EVENT_KEY) { return EventType::Key; } else if (ev == TB_EVENT_RESIZE) { return EventType::Resize; } else { return EventType::None; } } EventType Box::PollEvent(struct tb_event *event) { switch (tb_poll_event(event)) { case TB_EVENT_KEY: { return EventType::Key; } case TB_EVENT_RESIZE: { return EventType::Resize; } default: { return EventType::None; } } } } // namespace TB ",timeout 333,"/* Copyright 2022 Total Pave 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 #include namespace TP { namespace qt { using namespace TP::geom; Node::Node(uint32_t bucketSize, const Extent& extent, uint8_t depth) { $extent = extent; $bucketSize = bucketSize; $depth = depth; // These only exists once this node has been subdivided $nw = nullptr; $ne = nullptr; $sw = nullptr; $se = nullptr; } Node::~Node() { if ($nw != nullptr) { delete $nw; delete $ne; delete $sw; delete $se; } } const Extent& Node::getExtent(void) const { return $extent; } void Node::query(const Extent& extent, std::vector& dataList, std::unordered_map& dataManifest, std::function&, const QuadPoint*)>* filter) { // isInBounds is the first pass filter. // It checks to see if the requested extent is at least partially within the bounds of the quad extent. // The first pass filter is a very broad and inaccurate filter, it often includes many false possitives. // The false positives happen because quad extent is bigger than the requested extent, it ends up selecting // a lot of extra data in the general surrounding area of the requested extent. // The quad extent is often bigger than the requested extent because there is not enough data for the quad to split into smaller quads. if ($extent.isInBounds(extent)) { for (std::size_t i = 0; i < $children.size(); i++) { const QuadPoint* point = $children[i]; const void* data = point->getData(); long ptr = (long)data; if ( dataManifest.find(ptr) == dataManifest.end() && // Second pass filtering // Test each QuadPoint against the requested extent. // The second pass filter has medium accuracy. // Most false positives are caught but long diagonal lines still have many false positives. point->isInBounds(extent) ) { if ( // If filter is defined... filter != nullptr && !((*filter)(extent, point)) ) { // If point fails filter then continue to next point. continue; } dataManifest.insert(std::pair(ptr, true)); dataList.push_back(data); } } if ($nw != nullptr) { $nw->query(extent, dataList, dataManifest, filter); $ne->query(extent, dataList, dataManifest, filter); $sw->query(extent, dataList, dataManifest, filter); $se->query(extent, dataList, dataManifest, filter); } } } void Node::insert(const QuadPoint* point) { if ($nw != nullptr) { // This node has quadrants, so it should be passed down. const Extent& nwExtent = $nw->getExtent(); const Extent& neExtent = $ne->getExtent(); const Extent& swExtent = $sw->getExtent(); const Extent& seExtent = $se->getExtent(); if (point->isInBounds(nwExtent)) { $nw->insert(point); } if (point->isInBounds(neExtent)) { $ne->insert(point); } if (point->isInBounds(swExtent)) { $sw->insert(point); } if (point->isInBounds(seExtent)) { $se->insert(point); } return; } if ($children.size() == 0) { $children.reserve($bucketSize); } // If we made it here, then we are at a leaf node. $children.push_back(point); if ($children.size() >= $bucketSize && $depth != 1) { subdivide(); } } void Node::subdivide(void) { if ($nw != nullptr || $depth == 1) { // This node has already been subdivided. return; } Extent quadExtent = Extent::quad($extent); double tx, ty; uint8_t [MASK] = $depth - 1; quadExtent.getRange(tx, ty); $nw = new Node($bucketSize, quadExtent, [MASK] ); quadExtent.translate(tx, 0.0); $ne = new Node($bucketSize, quadExtent, [MASK] ); quadExtent.translate(0.0, ty); $se = new Node($bucketSize, quadExtent, [MASK] ); quadExtent.translate(-tx, 0.0); $sw = new Node($bucketSize, quadExtent, [MASK] ); const Extent& nwExtent = $nw->getExtent(); const Extent& neExtent = $ne->getExtent(); const Extent& swExtent = $sw->getExtent(); const Extent& seExtent = $se->getExtent(); while ($children.size() > 0) { const QuadPoint* point = $children.back(); $children.pop_back(); if (point->isInBounds(nwExtent)) { $nw->insert(point); } if (point->isInBounds(neExtent)) { $ne->insert(point); } if (point->isInBounds(swExtent)) { $sw->insert(point); } if (point->isInBounds(seExtent)) { $se->insert(point); } } $children.shrink_to_fit(); } }} ",childDepth 334,"#include #include #include #include #include #include #include #include #include #include #include #ifndef ITER_MAX #define ITER_MAX 5000 #endif // Communicator for a Pair of rank // Useful for measuring Bi-Socket BW, and 2 Tile-GPU MPI_Comm MPI_SUB_COMM; MPI_Comm MPI_SUB_COMM_GATHER; /* * Benchmark Utilities */ void bench(unsigned long *min_time, std::string bench_type, int globalWI, double *Aptr, double *Bptr, double *Cptr) { MPI_Barrier(MPI_SUB_COMM); // Save start and end const unsigned long l_start = std::chrono::duration_cast( std::chrono::high_resolution_clock::now().time_since_epoch()) .count(); if (bench_type == ""cpu"") { #pragma omp parallel for for (int i = 0; i < globalWI; i++) Aptr[i] = 2.0 * Bptr[i] + Cptr[i]; } else if (bench_type == ""gpu"") { #pragma omp target teams distribute parallel for for (int i = 0; i < globalWI; i++) Aptr[i] = 2.0 * Bptr[i] + Cptr[i]; } const unsigned long l_end = std::chrono::duration_cast( std::chrono::high_resolution_clock::now().time_since_epoch()) .count(); unsigned long start, end; MPI_Allreduce(&l_start, &start, 1, MPI_UNSIGNED_LONG, MPI_MIN, MPI_SUB_COMM); MPI_Allreduce(&l_end, &end, 1, MPI_UNSIGNED_LONG, MPI_MAX, MPI_SUB_COMM); unsigned long time = end - start; if (time <= *min_time) { *min_time = time; } } bool almost_equal(double x, double y, int ulp) { return std::abs(x - y) <= std::numeric_limits::epsilon() * std::abs(x + y) * ulp || std::abs(x - y) < std::numeric_limits::min(); } template typename T1::value_type quant(const T1 &x, T2 q) { assert(q >= 0.0 && q <= 1.0); const auto n = x.size(); const auto id = (n - 1) * q; const auto lo = floor(id); const auto hi = ceil(id); const auto qs = x[lo]; const auto h = (id - lo); return (1.0 - h) * qs + h * x[hi]; } int run(int globalWI, std::string name, std::string bench_type) { std::vector A(globalWI), B(globalWI), C(globalWI); std::srand(0); std::generate(B.begin(), B.end(), std::rand); std::generate(C.begin(), C.end(), std::rand); double *Aptr{A.data()}; double *Bptr{B.data()}; double *Cptr{C.data()}; unsigned long min_time = std::numeric_limits::max(); int errors = 0; if (bench_type == ""gpu"") { #pragma omp target enter data map(alloc : Aptr[ : globalWI]) \ map(to : Bptr[ : globalWI], Cptr[ : globalWI]) } for (int iter = 0; iter < ITER_MAX; iter++) { bench(&min_time, bench_type, globalWI, Aptr, Bptr, Cptr); } if (bench_type == ""gpu"") { #pragma omp target exit data map(from : Aptr[ : globalWI]) } for (int i = 0; i < globalWI; i++) { assert(almost_equal(Aptr[i], 2.0 * Bptr[i] + Cptr[i], 10)); } // Now do a gather int root_rank = 0; int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); if (world_rank == root_rank) { int gather_size; MPI_Comm_size(MPI_SUB_COMM_GATHER, &gather_size); std::vector bw(gather_size); { std::vector min_times(gather_size); MPI_Gather(&min_time, 1, MPI_UNSIGNED_LONG, min_times.data(), 1, MPI_UNSIGNED_LONG, root_rank, MPI_SUB_COMM_GATHER); { int sub_size; MPI_Comm_size(MPI_SUB_COMM, &sub_size); std::transform(min_times.begin(), min_times.end(), bw.begin(), [&](unsigned long val) { return (3. * globalWI * sub_size * sizeof(double)) / val; }); } #ifdef SAVE { std::string filename = name + "".txt""; std::ofstream fout(filename.c_str()); for (auto const &x : bw) fout << x << '\n'; } #endif std::sort(bw.begin(), bw.end()); } std::cout << ""Result For "" << name << "" (sample size: "" << gather_size << "")"" << std::endl; std::cout << ""-Min "" << bw.front() << "" GByte/s"" << std::endl; std::cout << ""-Q1 "" << quant(bw, 0.25) << "" GByte/s"" << std::endl; std::cout << ""-Q2(median) "" << quant(bw, 0.50) << "" GByte/s"" << std::endl; std::cout << ""-Q3 "" << quant(bw, 0.75) << "" GByte/s"" << std::endl; std::cout << ""-Max "" << bw.back() << "" GByte/s"" << std::endl; } else if (MPI_SUB_COMM_GATHER != MPI_COMM_NULL) { MPI_Gather(&min_time, 1, MPI_UNSIGNED_LONG, NULL, 0, MPI_UNSIGNED_LONG, root_rank, MPI_SUB_COMM_GATHER); } int [MASK] = 0; MPI_Reduce(&errors, & [MASK] , 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); return [MASK] ; } /* * Main */ int main(int argc, char **argv) { MPI_Init(NULL, NULL); int my_rank; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); std::string bench_type{argv[1]}; if (bench_type == ""gpu"") { // Best of two Tiles MPI_Comm_split(MPI_COMM_WORLD, my_rank / 2, 0, &MPI_SUB_COMM); int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); std::vector ranks(world_size / 2); { int n = -2; std::generate(ranks.begin(), ranks.end(), [&n] { return n += 2; }); } { MPI_Group world_group; MPI_Comm_group(MPI_COMM_WORLD, &world_group); MPI_Group new_group; MPI_Group_incl(world_group, ranks.size(), ranks.data(), &new_group); MPI_Comm_create(MPI_COMM_WORLD, new_group, &MPI_SUB_COMM_GATHER); } } else if (bench_type == ""cpu"") { MPI_Comm_split(MPI_COMM_WORLD, my_rank, 0, &MPI_SUB_COMM); MPI_SUB_COMM_GATHER = MPI_COMM_WORLD; } int errors = 0; if (bench_type == ""cpu"") { // = 128*2*10^6 Bytes (LL2+LL3) * 4 (STREAM factor) / 8 (doubles) errors += run(128'000'000, ""stream"", bench_type); } else if (bench_type == ""gpu"") { // = 204*10^6 Bytes (LLC) * 4 (STREAM factor) / 8 (doubles) errors += run(102'000'000, ""stream"", bench_type); } MPI_Finalize(); return errors; } ",mpi_errors 335,"#include #include #include #include #include #include #include #include ""glad/glad.h"" static const std::array s_vertices = { -0.5f, -0.5f, 0.0f, 0.0f, // Bottom left -0.5f, 0.5f, 0.0f, 1.0f, // Top left 0.5f, -0.5f, 1.0f, 0.0f, // Bottom right 0.5f, 0.5f, 1.0f, 1.0f, // Top right }; static const std::array s_indices = { 0, 1, 3, 0, 3, 2, }; static const char *const vertex_source = R""glsl( #version 330 core layout (location = 0) in vec2 position; layout (location = 1) in vec2 tex_coord; out vec2 v_tex_coord; void main() { gl_Position = vec4(position, 0.0, 1.0); v_tex_coord = tex_coord; } )glsl""; static const char *const fragment_source = R""glsl( #version 330 core in vec2 v_tex_coord; out vec4 f_color; uniform sampler2D u_texture; void main() { f_color = texture(u_texture, v_tex_coord); } )glsl""; std::uint32_t get_pixel(const SDL_Surface *surface, int x, int y) { // I'm not sure if this is going to be the case, but I'm assuming it is since // we're loading PNG data. assert(surface->format->BytesPerPixel == 4); std::uint8_t *p = reinterpret_cast(surface->pixels) + x * 4 + y * surface->pitch; return *reinterpret_cast(p); } struct ImageData { std::vector bytes; GLsizei width; GLsizei height; }; ImageData load_png_data(const std::string &path) { SDL_Surface *surface = IMG_Load(path.c_str()); if (surface == nullptr) { std::cerr << ""Failed to load image data: "" << IMG_GetError() << '\n'; return {}; } std::vector bytes; #define LOAD_PNG_DATA_LOOP_BACKWARD 1 #if LOAD_PNG_DATA_LOOP_BACKWARD for (int y = surface->h - 1; y >= 0; y--) { for (int x = 0; x < surface->w; x++) { std::uint32_t color = get_pixel(surface, x, y); std::uint8_t r, g, b, a; SDL_GetRGBA(color, surface->format, &r, &g, &b, &a); bytes.push_back(r); bytes.push_back(g); bytes.push_back(b); bytes.push_back(a); } } #else for (int y = 0; y < surface->h; y++) { for (int x = 0; x < surface->w; x++) { std::uint32_t color = get_pixel(surface, x, y); std::uint8_t r, g, b, a; SDL_GetRGBA(color, surface->format, &r, &g, &b, &a); bytes.push_back(r); bytes.push_back(g); bytes.push_back(b); bytes.push_back(a); } } #endif return {bytes, surface->w, surface->h}; } // Don't change the signature of main even though argc and argv aren't used. SDL // needs this on windows. FML. int main(int argc, char *argv[]) { if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { std::cerr << ""Failed to initialize SDL: "" << SDL_GetError() << '\n'; } int img_flags = IMG_INIT_PNG; if (!(IMG_Init(img_flags) & img_flags)) { std::cerr << ""Failed to initialize SDL image: "" << IMG_GetError() << '\n'; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_Window *window = SDL_CreateWindow(""Better Breakout"", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_OPENGL); if (window == nullptr) { std::cerr << ""Failed to create window: "" << SDL_GetError() << '\n'; } SDL_GLContext context = SDL_GL_CreateContext(window); if (context == nullptr) { std::cerr << ""Failed to create OpenGL context: "" << SDL_GetError() << '\n'; } if (gladLoadGLLoader(SDL_GL_GetProcAddress) == 0) { std::cerr << ""Failed to initialize glad\n""; } // Debug output some crap std::cerr << ""Vendor: "" << glGetString(GL_VENDOR) << '\n'; std::cerr << ""Renderer: "" << glGetString(GL_RENDERER) << '\n'; std::cerr << ""OpenGL version: "" << glGetString(GL_VERSION) << '\n'; std::cerr << ""GLSL version: "" << glGetString(GL_SHADING_LANGUAGE_VERSION) << '\n'; // Triangle stuff GLuint vertex_array; glGenVertexArrays(1, &vertex_array); glBindVertexArray(vertex_array); GLuint [MASK] ; glGenBuffers(1, & [MASK] ); glBindBuffer(GL_ARRAY_BUFFER, [MASK] ); glBufferData(GL_ARRAY_BUFFER, s_vertices.size() * sizeof(float), s_vertices.data(), GL_STATIC_DRAW); GLuint index_buffer; glGenBuffers(1, &index_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, s_indices.size() * sizeof(unsigned int), s_indices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), reinterpret_cast(0)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), reinterpret_cast(2 * sizeof(float))); // Shader stuff GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_source, nullptr); glCompileShader(vertex_shader); GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_source, nullptr); glCompileShader(fragment_shader); GLuint program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); glDetachShader(program, vertex_shader); glDetachShader(program, fragment_shader); glDeleteShader(fragment_shader); glDeleteShader(vertex_shader); glUseProgram(program); ImageData data = load_png_data(""res/textures/awesomeface.png""); GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, data.width, data.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.bytes.data()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // I think 0 is the default?? glUniform1i(glGetUniformLocation(program, ""u_texture""), 0); // TODO: Error handling glClearColor(0.53f, 0.91f, 0.28f, 1.0f); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); bool window_should_close = false; while (!window_should_close) { SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { window_should_close = true; } } glClear(GL_COLOR_BUFFER_BIT); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, reinterpret_cast(0)); SDL_GL_SwapWindow(window); } glDeleteProgram(program); glDeleteBuffers(1, &index_buffer); glDeleteBuffers(1, & [MASK] ); glDeleteVertexArrays(1, &vertex_array); SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); return 0; } ",vertex_buffer 336,"#include #include #include #include #include #include #define FUSE_USE_VERSION 31 #include #include ""ini.cc"" using namespace std::string_view_literals; static struct options { char const* ini_filename; int show_help; } options; #define OPTION(t, p) \ { t, offsetof(struct options, p), 1 } static const struct fuse_opt option_spec[] = { OPTION(""--ini=%s"", ini_filename), OPTION(""-h"", show_help), OPTION(""--help"", show_help), FUSE_OPT_END }; INI ini; struct stat ini_stat; inline void update_stat(struct stat *dst) { dst->st_ctime = ini_stat.st_ctime; dst->st_atime = ini_stat.st_atime; dst->st_mtime = ini_stat.st_mtime; dst->st_uid = ini_stat.st_uid; dst->st_gid = ini_stat.st_gid; } namespace inifs { static void* init(fuse_conn_info *, fuse_config *cfg) { cfg->kernel_cache = 1; return NULL; } static int getattr(char const* path, struct stat *stbuf, fuse_file_info*) { memset(stbuf, 0, sizeof(*stbuf)); update_stat(stbuf); if (""/""sv == path) { stbuf->st_mode = S_IFDIR | 0755; stbuf->st_nlink = 2; return 0; } std::string_view p = path+1; if (auto split = p.find('/'); split != std::string_view::npos) { auto const section = p.substr(0, split); auto const target_key = p.substr(split + 1); if (auto const key = std::find(ini.section_keys(section), {}, target_key); key) { stbuf->st_mode = S_IFREG | 0644; stbuf->st_nlink = 1; stbuf->st_size = key.value().size(); return 0; } return -ENOENT; } if (auto section = ini.sections(); section && (section = std::find(section, {}, p))) { stbuf->st_mode = S_IFDIR | 0755; stbuf->st_nlink = 2; return 0; } if (auto key = ini.section_keys(); key && (key = std::find(key, {}, p))) { stbuf->st_mode = S_IFREG | 0644; stbuf->st_nlink = 1; stbuf->st_size = key.value().size(); return 0; } return -ENOENT; } static int readdir( char const* path, void *buf, fuse_fill_dir_t filler, off_t, fuse_file_info*, fuse_readdir_flags) { filler(buf, ""."", NULL, 0, {}); filler(buf, "".."", NULL, 0, {}); if (path == ""/""sv) { for (auto section = ini.sections(); section; ++section) { filler(buf, section->c_str(), NULL, 0, {}); } for (auto key = ini.section_keys(); key; ++key) { filler(buf, key->c_str(), NULL, 0, {}); } return 0; } bool section_found = false; for (auto key = ini.section_keys(path + 1); key; ++key) { section_found = true; filler(buf, key->c_str(), NULL, 0, {}); } return section_found ? 0 : -ENOENT; } static int open(char const* path, fuse_file_info *fi) { auto const p = std::string_view(path + 1); auto const split = p.find('/'); if (!std::find(ini.section_keys(split == std::string_view::npos ? """" : p.substr(0, split)), {}, p.substr(split + 1))) return -ENOENT; if ((fi->flags & O_ACCMODE) != O_RDONLY) return -EACCES; return 0; } static int read(char const* path, char *buf, size_t size, off_t offset, fuse_file_info *) { auto const p = std::string_view(path + 1); auto const split = p.find('/'); if (auto key = std::find(ini.section_keys(split == std::string_view::npos ? """" : p.substr(0, split)), {}, p.substr(split + 1)); key) { auto const data = key.value().data(); auto const len = key.value().size(); if ((unsigned)offset < len) { if (offset + size > len) size = len - offset; memcpy(buf, data + offset, size); } else { size = 0; } } else { return -ENOENT; } return size; } static int mkdir(char const* path, mode_t mode) { #ifdef Debug_Mode std::cerr << ""mkdir("" << std::quoted(path) << "", "" << std::oct << mode << "")\n""; #else (void)mode; #endif if (path == ""/""sv) return -EEXIST; auto const p = std::string_view(path+1); if (p.find_first_of(""/[]"") != std::string_view::npos) return -EINVAL; auto &new_node = ini.nodes.emplace_back(); new_node.kind = INI::Node::Kind::Section; new_node.value = p; return 0; } static int rmdir(char const* path) { #ifdef Debug_Mode std::cerr << ""rmdir("" << std::quoted(path) << "")\n""; #endif if (path == ""/""sv) return -ENOTEMPTY; if (auto section = ini.sections(); section && (section = std::find(section, {}, path + 1))) { if (auto next = std::next(section); next ? next.node().kind == INI::Node::Kind::Section : 1) { ini.nodes.erase(ini.nodes.cbegin() + section.i); return 0; } return -ENOTEMPTY; } return -ENOTDIR; } int rename(char const* src, char const* dst, unsigned int flags) { #ifdef Debug_Mode std::cerr << ""rename("" << std::quoted(src) << "", "" << std::quoted(dst) << "", "" << flags << "")\n""; #endif if (dst == ""/""sv || src == ""/""sv) return -EPERM; auto const s = std::string_view(src+1); auto const d = std::string_view(dst+1); auto const s_split = s.find('/'); auto const [MASK] = d.find('/'); if (s_split == std::string_view::npos && [MASK] == std::string_view::npos) { if (d.find_first_of(""[]"") != std::string_view::npos) { return -EINVAL; } if (auto s_sec = ini.sections(); s_sec && (s_sec = std::find(s_sec, {}, s))) { if (auto d_sec = ini.sections(); d_sec && (d_sec = std::find(d_sec, {}, d))) { switch (flags) { case RENAME_EXCHANGE: std::swap(ini.nodes[s_sec.i].value, ini.nodes[d_sec.i].value); return 0; case RENAME_NOREPLACE: return -EEXIST; } if (auto d_next = std::next(d_sec); d_next ? d_next.node().kind == INI::Node::Kind::Section : 1) { ini.nodes.erase(ini.nodes.cbegin() + d_sec.i); return 0; } return -ENOTEMPTY; } ini.nodes[s_sec.i].value = d; return 0; } return -EEXIST; } else { return -ENOSYS; } } } int main(int argc, char **argv) { fuse_operations oper = {}; oper.getattr = inifs::getattr; oper.init = inifs::init; oper.mkdir = inifs::mkdir; oper.open = inifs::open; oper.read = inifs::read; oper.readdir = inifs::readdir; oper.rename = inifs::rename; oper.rmdir = inifs::rmdir; fuse_args args = FUSE_ARGS_INIT(argc, argv); if (fuse_opt_parse(&args, &options, option_spec, nullptr) == -1) return 1; if (!options.ini_filename) { std::cerr << ""inifs: no INI file was provided\n""; return 2; } if (auto maybe_ini = INI::from_file(options.ini_filename); maybe_ini) { ini = *std::move(maybe_ini); } else { std::cerr << ""inifs: invalid INI file\n""; return 3; } lstat(options.ini_filename, &ini_stat); auto ret = fuse_main(args.argc, args.argv, &oper, nullptr); fuse_opt_free_args(&args); return ret; } ",d_split 337,"#include #include #include ""windows.h"" #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; string name = ""Rapfox""; #define MAX_DEPTH 100 #define MAX_SCORE 50000 #define MONTH (\ __DATE__ [2] == 'n' ? (__DATE__ [1] == 'a' ? ""01"" : ""06"") \ : __DATE__ [2] == 'b' ? ""02"" \ : __DATE__ [2] == 'r' ? (__DATE__ [0] == 'M' ? ""03"" : ""04"") \ : __DATE__ [2] == 'y' ? ""05"" \ : __DATE__ [2] == 'l' ? ""07"" \ : __DATE__ [2] == 'g' ? ""08"" \ : __DATE__ [2] == 'p' ? ""09"" \ : __DATE__ [2] == 't' ? ""10"" \ : __DATE__ [2] == 'v' ? ""11"" \ : ""12"") #define DAY (std::string(1,(__DATE__[4] == ' ' ? '0' : (__DATE__[4]))) + (__DATE__[5])) #define YEAR ((__DATE__[7]-'0') * 1000 + (__DATE__[8]-'0') * 100 + (__DATE__[9]-'0') * 10 + (__DATE__[10]-'0') * 1) static void PrintWelcome() { cout << name << "" "" << YEAR << ""-"" << MONTH << ""-"" << DAY << endl; } // FEN dedug positions #define defFen ""rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 "" #define tricky_position ""r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1 "" #define killer_position ""rnbqkb1r/pp1p1pPp/8/2p1pP2/1P1P4/3P3P/P1P1P3/RNBQKBNR w KQkq e6 0 1"" #define cmk_position ""r2q1rk1/ppp2ppp/2n1bn2/2b1p3/3pP3/3P1NPP/PPP1NPB1/R1BQ1RK1 b - - 0 9 "" // piece encoding enum pieces { e, P, N, B, R, Q, K, p, n, b, r, q, k, o }; // square encoding enum squares { a8 = 0, b8, c8, d8, e8, f8, g8, h8, a7 = 16, b7, c7, d7, e7, f7, g7, h7, a6 = 32, b6, c6, d6, e6, f6, g6, h6, a5 = 48, b5, c5, d5, e5, f5, g5, h5, a4 = 64, b4, c4, d4, e4, f4, g4, h4, a3 = 80, b3, c3, d3, e3, f3, g3, h3, a2 = 96, b2, c2, d2, e2, f2, g2, h2, a1 = 112, b1, c1, d1, e1, f1, g1, h1, no_sq }; // capture flags enum capture_flags { all_moves, only_captures }; // castling binary representation // // bin dec // 0001 1 white king can castle to the king side // 0010 2 white king can castle to the queen side // 0100 4 black king can castle to the king side // 1000 8 black king can castle to the queen side // // examples // 1111 both sides an castle both directions // 1001 black king => queen side // white king => king side // castling writes enum castling { KC = 1, QC = 2, kc = 4, qc = 8 }; // sides to move enum sides { white, black }; // ascii pieces string pieces = "".PNBRQKpnbrqk""; string promoted_pieces = "" nbrq nbrq ""; void UciCommand(string str); static int CharToPiece(char c) { return pieces.find(c); } static char PieceToChar(int p) { return pieces[p]; } static char PieceToPromotion(int p) { char c = promoted_pieces[p]; //if (c == ' ') return '\0'; return c; } int material_score[13] = { 0, // empty square score 100, // white pawn score 310, // white knight score 320, // white bishop score 500, // white rook score 900, // white queen score 10000, // white king score -100, // black pawn score -310, // black knight score -320, // black bishop score -500, // black rook score -900, // black queen score -10000, // black king score }; // castling rights /* castle move in in right map binary decimal white king moved: 1111 & 1100 = 1100 12 white king's rook moved: 1111 & 1110 = 1110 14 white queen's rook moved: 1111 & 1101 = 1101 13 black king moved: 1111 & 0011 = 1011 3 black king's rook moved: 1111 & 1011 = 1011 11 black queen's rook moved: 1111 & 0111 = 0111 7 */ int castling_rights[128] = { 7, 15, 15, 15, 3, 15, 15, 11, o, o, o, o, o, o, o, o, 15, 15, 15, 15, 15, 15, 15, 15, o, o, o, o, o, o, o, o, 15, 15, 15, 15, 15, 15, 15, 15, o, o, o, o, o, o, o, o, 15, 15, 15, 15, 15, 15, 15, 15, o, o, o, o, o, o, o, o, 15, 15, 15, 15, 15, 15, 15, 15, o, o, o, o, o, o, o, o, 15, 15, 15, 15, 15, 15, 15, 15, o, o, o, o, o, o, o, o, 15, 15, 15, 15, 15, 15, 15, 15, o, o, o, o, o, o, o, o, 13, 15, 15, 15, 12, 15, 15, 14, o, o, o, o, o, o, o, o }; // pawn positional score const int pawn_score[128] = { 90, 90, 90, 90, 90, 90, 90, 90, o, o, o, o, o, o, o, o, 30, 30, 30, 40, 40, 30, 30, 30, o, o, o, o, o, o, o, o, 20, 20, 20, 30, 30, 30, 20, 20, o, o, o, o, o, o, o, o, 10, 10, 10, 20, 20, 10, 10, 10, o, o, o, o, o, o, o, o, 5, 5, 10, 20, 20, 5, 5, 5, o, o, o, o, o, o, o, o, 0, 0, 0, 5, 5, 0, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 0, -10, -10, 0, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 0, 0, 0, 0, 0, 0, o, o, o, o, o, o, o, o }; // knight positional score const int knight_score[128] = { -5, 0, 0, 0, 0, 0, 0, -5, o, o, o, o, o, o, o, o, -5, 0, 0, 10, 10, 0, 0, -5, o, o, o, o, o, o, o, o, -5, 5, 20, 20, 20, 20, 5, -5, o, o, o, o, o, o, o, o, -5, 10, 20, 30, 30, 20, 10, -5, o, o, o, o, o, o, o, o, -5, 10, 20, 30, 30, 20, 10, -5, o, o, o, o, o, o, o, o, -5, 5, 20, 10, 10, 20, 5, -5, o, o, o, o, o, o, o, o, -5, 0, 0, 0, 0, 0, 0, -5, o, o, o, o, o, o, o, o, -5, -10, 0, 0, 0, 0, -10, -5, o, o, o, o, o, o, o, o }; // bishop positional score const int bishop_score[128] = { 0, 0, 0, 0, 0, 0, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 0, 0, 0, 0, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 0, 10, 10, 0, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 10, 20, 20, 10, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 10, 20, 20, 10, 0, 0, o, o, o, o, o, o, o, o, 0, 10, 0, 0, 0, 0, 10, 0, o, o, o, o, o, o, o, o, 0, 30, 0, 0, 0, 0, 30, 0, o, o, o, o, o, o, o, o, 0, 0, -10, 0, 0, -10, 0, 0, o, o, o, o, o, o, o, o }; // rook positional score const int rook_score[128] = { 50, 50, 50, 50, 50, 50, 50, 50, o, o, o, o, o, o, o, o, 50, 50, 50, 50, 50, 50, 50, 50, o, o, o, o, o, o, o, o, 0, 0, 10, 20, 20, 10, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 10, 20, 20, 10, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 10, 20, 20, 10, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 10, 20, 20, 10, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 10, 20, 20, 10, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 0, 20, 20, 0, 0, 0, o, o, o, o, o, o, o, o }; // king positional score const int king_score[128] = { 0, 0, 0, 0, 0, 0, 0, 0, o, o, o, o, o, o, o, o, 0, 0, 5, 5, 5, 5, 0, 0, o, o, o, o, o, o, o, o, 0, 5, 5, 10, 10, 5, 5, 0, o, o, o, o, o, o, o, o, 0, 5, 10, 20, 20, 10, 5, 0, o, o, o, o, o, o, o, o, 0, 5, 10, 20, 20, 10, 5, 0, o, o, o, o, o, o, o, o, 0, 0, 5, 10, 10, 5, 0, 0, o, o, o, o, o, o, o, o, 0, 5, 5, -5, -5, 0, 5, 0, o, o, o, o, o, o, o, o, 0, 0, 5, 0, -15, 0, 10, 0, o, o, o, o, o, o, o, o }; // mirror positional score tables for opposite side const int mirror_score[128] = { a1, b1, c1, d1, e1, f1, g1, h1, o, o, o, o, o, o, o, o, a2, b2, c2, d2, e2, f2, g2, h2, o, o, o, o, o, o, o, o, a3, b3, c3, d3, e3, f3, g3, h3, o, o, o, o, o, o, o, o, a4, b4, c4, d4, e4, f4, g4, h4, o, o, o, o, o, o, o, o, a5, b5, c5, d5, e5, f5, g5, h5, o, o, o, o, o, o, o, o, a6, b6, c6, d6, e6, f6, g6, h6, o, o, o, o, o, o, o, o, a7, b7, c7, d7, e7, f7, g7, h7, o, o, o, o, o, o, o, o, a8, b8, c8, d8, e8, f8, g8, h8, o, o, o, o, o, o, o, o }; // chess board representation int board[128] = { r, n, b, q, k, b, n, r, o, o, o, o, o, o, o, o, p, p, p, p, p, p, p, p, o, o, o, o, o, o, o, o, e, e, e, e, e, e, e, e, o, o, o, o, o, o, o, o, e, e, e, e, e, e, e, e, o, o, o, o, o, o, o, o, e, e, e, e, e, e, e, e, o, o, o, o, o, o, o, o, e, e, e, e, e, e, e, e, o, o, o, o, o, o, o, o, P, P, P, P, P, P, P, P, o, o, o, o, o, o, o, o, R, N, B, Q, K, B, N, R, o, o, o, o, o, o, o, o }; // side to move int side = white; // enpassant square int enpassant = no_sq; // castling rights (dec 15 => bin 1111 => both kings can castle to both sides) int castle = 15; // kings' squares int king_square[2] = { e1, e8 }; /* Move formatting 0000 0000 0000 0000 0111 1111 source square 0000 0000 0011 1111 1000 0000 target square 0000 0011 1100 0000 0000 0000 promoted piece 0000 0100 0000 0000 0000 0000 capture flag 0000 1000 0000 0000 0000 0000 double pawn flag 0001 0000 0000 0000 0000 0000 enpassant flag 0010 0000 0000 0000 0000 0000 castling */ // encode move #define encode_move(source, target, piece, capture, pawn, enpassant, castling) \ ( \ (source) | \ (target << 7) | \ (piece << 14) | \ (capture << 18) | \ (pawn << 19) | \ (enpassant << 20) | \ (castling << 21) \ ) // decode move's source square #define get_move_source(move) (move & 0x7f) // decode move's target square #define get_move_target(move) ((move >> 7) & 0x7f) // decode move's promoted piece #define get_move_piece(move) ((move >> 14) & 0xf) // decode move's capture flag #define get_move_capture(move) ((move >> 18) & 0x1) // decode move's double pawn push flag #define get_move_pawn(move) ((move >> 19) & 0x1) // decode move's enpassant flag #define get_move_enpassant(move) ((move >> 20) & 0x1) // decode move's castling flag #define get_move_castling(move) ((move >> 21) & 0x1) // convert board square indexes to coordinates char* square_to_coords[] = { ""a8"", ""b8"", ""c8"", ""d8"", ""e8"", ""f8"", ""g8"", ""h8"", ""i8"", ""j8"", ""k8"", ""l8"", ""m8"", ""n8"", ""o8"", ""p8"", ""a7"", ""b7"", ""c7"", ""d7"", ""e7"", ""f7"", ""g7"", ""h7"", ""i7"", ""j7"", ""k7"", ""l7"", ""m7"", ""n7"", ""o7"", ""p7"", ""a6"", ""b6"", ""c6"", ""d6"", ""e6"", ""f6"", ""g6"", ""h6"", ""i6"", ""j6"", ""k6"", ""l6"", ""m6"", ""n6"", ""o6"", ""p6"", ""a5"", ""b5"", ""c5"", ""d5"", ""e5"", ""f5"", ""g5"", ""h5"", ""i5"", ""j5"", ""k5"", ""l5"", ""m5"", ""n5"", ""o5"", ""p5"", ""a4"", ""b4"", ""c4"", ""d4"", ""e4"", ""f4"", ""g4"", ""h4"", ""i4"", ""j4"", ""k4"", ""l4"", ""m4"", ""n4"", ""o4"", ""p4"", ""a3"", ""b3"", ""c3"", ""d3"", ""e3"", ""f3"", ""g3"", ""h3"", ""i3"", ""j3"", ""k3"", ""l3"", ""m3"", ""n3"", ""o3"", ""p3"", ""a2"", ""b2"", ""c2"", ""d2"", ""e2"", ""f2"", ""g2"", ""h2"", ""i2"", ""j2"", ""k2"", ""l2"", ""m2"", ""n2"", ""o2"", ""p2"", ""a1"", ""b1"", ""c1"", ""d1"", ""e1"", ""f1"", ""g1"", ""h1"", ""i1"", ""j1"", ""k1"", ""l1"", ""m1"", ""n1"", ""o1"", ""p1"" }; // piece move offsets int knight_offsets[8] = { 33, 31, 18, 14, -33, -31, -18, -14 }; int bishop_offsets[4] = { 15, 17, -15, -17 }; int rook_offsets[4] = { 16, -16, 1, -1 }; int king_offsets[8] = { 16, -16, 1, -1, 15, 17, -15, -17 }; // move list structure typedef struct { // move list int moves[256]; // move count int count; } moves; /* get_ms() returns the milliseconds elapsed since midnight, January 1, 1970. */ int get_time_ms() { struct timeb timebuffer; ftime(&timebuffer); return (timebuffer.time * 1000) + timebuffer.millitm; } static vector SplitString(string s) { vector [MASK] ; istringstream iss(s); string word; while (iss >> word) [MASK] .push_back(word); return [MASK] ; } static int GetInt(vector vs, string name, int def) { bool r = false; for (string s : vs) { if (r) return stoi(s); r = s == name; } return def; } static void PrintBoard() { for (int rank = 0; rank < 8; rank++) { // loop over board files for (int file = 0; file < 16; file++) { // init square int square = rank * 16 + file; // print ranks if (file == 0) printf("" %d "", 8 - rank); // if square is on board if (!(square & 0x88)) printf(""%c "", pieces[board[square]]); } cout << endl; } // print files cout << "" a b c d e f g h"" << endl; // print board stats printf("" Side: %s\n"", (side == white) ? ""white"" : ""black""); printf("" Castling: %c%c%c%c\n"", (castle & KC) ? 'K' : '-', (castle & QC) ? 'Q' : '-', (castle & kc) ? 'k' : '-', (castle & qc) ? 'q' : '-'); printf("" Enpassant: %s\n"", (enpassant == no_sq) ? ""no"" : square_to_coords[enpassant]); printf("" King square: %s\n\n"", square_to_coords[king_square[side]]); } // reset board static void ResetBoard() { for (int rank = 0; rank < 8; rank++) { for (int file = 0; file < 16; file++) { int square = rank * 16 + file; // if square is on board if (!(square & 0x88)) // reset current board square board[square] = e; } } side = white; castle = 0; enpassant = no_sq; } /***********************************************\ MOVE GENERATOR FUNCTIONS \***********************************************/ // is square attacked static inline int is_square_attacked(int square, int side) { // pawn attacks if (!side) { // if target square is on board and is white pawn if (!((square + 17) & 0x88) && (board[square + 17] == P)) return 1; // if target square is on board and is white pawn if (!((square + 15) & 0x88) && (board[square + 15] == P)) return 1; } else { // if target square is on board and is black pawn if (!((square - 17) & 0x88) && (board[square - 17] == p)) return 1; // if target square is on board and is black pawn if (!((square - 15) & 0x88) && (board[square - 15] == p)) return 1; } // knight attacks for (int index = 0; index < 8; index++) { // init target square int target_square = square + knight_offsets[index]; // lookup target piece int target_piece = board[target_square]; // if target square is on board if (!(target_square & 0x88)) { if (!side ? target_piece == N : target_piece == n) return 1; } } // king attacks for (int index = 0; index < 8; index++) { // init target square int target_square = square + king_offsets[index]; // lookup target piece int target_piece = board[target_square]; // if target square is on board if (!(target_square & 0x88)) { // if target piece is either white or black king if (!side ? target_piece == K : target_piece == k) return 1; } } // bishop & queen attacks for (int index = 0; index < 4; index++) { // init target square int target_square = square + bishop_offsets[index]; // loop over attack ray while (!(target_square & 0x88)) { // target piece int target_piece = board[target_square]; // if target piece is either white or black bishop or queen if (!side ? (target_piece == B || target_piece == Q) : (target_piece == b || target_piece == q)) return 1; // break if hit a piece if (target_piece) break; // increment target square by move offset target_square += bishop_offsets[index]; } } // rook & queen attacks for (int index = 0; index < 4; index++) { // init target square int target_square = square + rook_offsets[index]; // loop over attack ray while (!(target_square & 0x88)) { // target piece int target_piece = board[target_square]; // if target piece is either white or black bishop or queen if (!side ? (target_piece == R || target_piece == Q) : (target_piece == r || target_piece == q)) return 1; // break if hit a piece if (target_piece) break; // increment target square by move offset target_square += rook_offsets[index]; } } return 0; } // print attack map static void PrintAttackedSquares(int side) { printf(""\n""); printf("" Attacking side: %s\n\n"", !side ? ""white"" : ""black""); // loop over board ranks for (int rank = 0; rank < 8; rank++) { // loop over board files for (int file = 0; file < 16; file++) { // init square int square = rank * 16 + file; // print ranks if (file == 0) printf("" %d "", 8 - rank); // if square is on board if (!(square & 0x88)) printf(""%c "", is_square_attacked(square, side) ? 'x' : '.'); } // print new line every time new rank is encountered printf(""\n""); } printf(""\n a b c d e f g h\n\n""); } // populate move list static inline void add_move(moves* move_list, int move) { // push move into the move list move_list->moves[move_list->count] = move; // increment move count move_list->count++; } // move generator static inline void generate_moves(moves* move_list) { // reset move count move_list->count = 0; // loop over all board squares for (int square = 0; square < 128; square++) { // check if the square is on board if (!(square & 0x88)) { // white pawn and castling moves if (!side) { // white pawn moves if (board[square] == P) { // init target square int to_square = square - 16; // quite white pawn moves (check if target square is on board) if (!(to_square & 0x88) && !board[to_square]) { // pawn promotions if (square >= a7 && square <= h7) { add_move(move_list, encode_move(square, to_square, Q, 0, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, R, 0, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, B, 0, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, N, 0, 0, 0, 0)); } else { // one square ahead pawn move add_move(move_list, encode_move(square, to_square, 0, 0, 0, 0, 0)); // two squares ahead pawn move if ((square >= a2 && square <= h2) && !board[square - 32]) add_move(move_list, encode_move(square, square - 32, 0, 0, 1, 0, 0)); } } // white pawn capture moves for (int index = 0; index < 4; index++) { // init pawn offset int pawn_offset = bishop_offsets[index]; // white pawn offsets if (pawn_offset < 0) { // init target square int to_square = square + pawn_offset; // check if target square is on board if (!(to_square & 0x88)) { // capture pawn promotion if ( (square >= a7 && square <= h7) && (board[to_square] >= 7 && board[to_square] <= 12) ) { add_move(move_list, encode_move(square, to_square, Q, 1, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, R, 1, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, B, 1, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, N, 1, 0, 0, 0)); } else { // casual capture if (board[to_square] >= 7 && board[to_square] <= 12) add_move(move_list, encode_move(square, to_square, 0, 1, 0, 0, 0)); // enpassant capture if (to_square == enpassant) add_move(move_list, encode_move(square, to_square, 0, 1, 0, 1, 0)); } } } } } // white king castling if (board[square] == K) { // if king side castling is available if (castle & KC) { // make sure there are empty squares between king & rook if (!board[f1] && !board[g1]) { // make sure king & next square are not under attack if (!is_square_attacked(e1, black) && !is_square_attacked(f1, black)) add_move(move_list, encode_move(e1, g1, 0, 0, 0, 0, 1)); } } // if queen side castling is available if (castle & QC) { // make sure there are empty squares between king & rook if (!board[d1] && !board[b1] && !board[c1]) { // make sure king & next square are not under attack if (!is_square_attacked(e1, black) && !is_square_attacked(d1, black)) add_move(move_list, encode_move(e1, c1, 0, 0, 0, 0, 1)); } } } } // black pawn and castling moves else { // black pawn moves if (board[square] == p) { // init target square int to_square = square + 16; // quite black pawn moves (check if target square is on board) if (!(to_square & 0x88) && !board[to_square]) { // pawn promotions if (square >= a2 && square <= h2) { add_move(move_list, encode_move(square, to_square, q, 0, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, r, 0, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, b, 0, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, n, 0, 0, 0, 0)); } else { // one square ahead pawn move add_move(move_list, encode_move(square, to_square, 0, 0, 0, 0, 0)); // two squares ahead pawn move if ((square >= a7 && square <= h7) && !board[square + 32]) add_move(move_list, encode_move(square, square + 32, 0, 0, 1, 0, 0)); } } // black pawn capture moves for (int index = 0; index < 4; index++) { // init pawn offset int pawn_offset = bishop_offsets[index]; // white pawn offsets if (pawn_offset > 0) { // init target square int to_square = square + pawn_offset; // check if target square is on board if (!(to_square & 0x88)) { // capture pawn promotion if ( (square >= a2 && square <= h2) && (board[to_square] >= 1 && board[to_square] <= 6) ) { add_move(move_list, encode_move(square, to_square, q, 1, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, r, 1, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, b, 1, 0, 0, 0)); add_move(move_list, encode_move(square, to_square, n, 1, 0, 0, 0)); } else { // casual capture if (board[to_square] >= 1 && board[to_square] <= 6) add_move(move_list, encode_move(square, to_square, 0, 1, 0, 0, 0)); // enpassant capture if (to_square == enpassant) add_move(move_list, encode_move(square, to_square, 0, 1, 0, 1, 0)); } } } } } // black king castling if (board[square] == k) { // if king side castling is available if (castle & kc) { // make sure there are empty squares between king & rook if (!board[f8] && !board[g8]) { // make sure king & next square are not under attack if (!is_square_attacked(e8, white) && !is_square_attacked(f8, white)) add_move(move_list, encode_move(e8, g8, 0, 0, 0, 0, 1)); } } // if queen side castling is available if (castle & qc) { // make sure there are empty squares between king & rook if (!board[d8] && !board[b8] && !board[c8]) { // make sure king & next square are not under attack if (!is_square_attacked(e8, white) && !is_square_attacked(d8, white)) add_move(move_list, encode_move(e8, c8, 0, 0, 0, 0, 1)); } } } } // knight moves if (!side ? board[square] == N : board[square] == n) { // loop over knight move offsets for (int index = 0; index < 8; index++) { // init target square int to_square = square + knight_offsets[index]; // init target piece int piece = board[to_square]; // make sure target square is onboard if (!(to_square & 0x88)) { // if ( !side ? (!piece || (piece >= 7 && piece <= 12)) : (!piece || (piece >= 1 && piece <= 6)) ) { // on capture if (piece) add_move(move_list, encode_move(square, to_square, 0, 1, 0, 0, 0)); // on empty square else add_move(move_list, encode_move(square, to_square, 0, 0, 0, 0, 0)); } } } } // king moves if (!side ? board[square] == K : board[square] == k) { // loop over king move offsets for (int index = 0; index < 8; index++) { // init target square int to_square = square + king_offsets[index]; // init target piece int piece = board[to_square]; // make sure target square is onboard if (!(to_square & 0x88)) { // if ( !side ? (!piece || (piece >= 7 && piece <= 12)) : (!piece || (piece >= 1 && piece <= 6)) ) { // on capture if (piece) add_move(move_list, encode_move(square, to_square, 0, 1, 0, 0, 0)); // on empty square else add_move(move_list, encode_move(square, to_square, 0, 0, 0, 0, 0)); } } } } // bishop & queen moves if ( !side ? (board[square] == B) || (board[square] == Q) : (board[square] == b) || (board[square] == q) ) { // loop over bishop & queen offsets for (int index = 0; index < 4; index++) { // init target square int to_square = square + bishop_offsets[index]; // loop over attack ray while (!(to_square & 0x88)) { // init target piece int piece = board[to_square]; // if hits own piece if (!side ? (piece >= 1 && piece <= 6) : ((piece >= 7 && piece <= 12))) break; // if hits opponent's piece if (!side ? (piece >= 7 && piece <= 12) : ((piece >= 1 && piece <= 6))) { add_move(move_list, encode_move(square, to_square, 0, 1, 0, 0, 0)); break; } // if steps into an empty squre if (!piece) add_move(move_list, encode_move(square, to_square, 0, 0, 0, 0, 0)); // increment target square to_square += bishop_offsets[index]; } } } // rook & queen moves if ( !side ? (board[square] == R) || (board[square] == Q) : (board[square] == r) || (board[square] == q) ) { // loop over bishop & queen offsets for (int index = 0; index < 4; index++) { // init target square int to_square = square + rook_offsets[index]; // loop over attack ray while (!(to_square & 0x88)) { // init target piece int piece = board[to_square]; // if hits own piece if (!side ? (piece >= 1 && piece <= 6) : ((piece >= 7 && piece <= 12))) break; // if hits opponent's piece if (!side ? (piece >= 7 && piece <= 12) : ((piece >= 1 && piece <= 6))) { add_move(move_list, encode_move(square, to_square, 0, 1, 0, 0, 0)); break; } // if steps into an empty squre if (!piece) add_move(move_list, encode_move(square, to_square, 0, 0, 0, 0, 0)); // increment target square to_square += rook_offsets[index]; } } } } } } static void PrintMoves() { moves move_list[1]; generate_moves(move_list); printf(""\n Move Capture Double Enpass Castling\n\n""); // loop over moves in a movelist for (int index = 0; index < move_list->count; index++) { int move = move_list->moves[index]; printf("" %s%s"", square_to_coords[get_move_source(move)], square_to_coords[get_move_target(move)]); printf(""%c "", get_move_piece(move) ? promoted_pieces[get_move_piece(move)] : ' '); printf(""%d %d %d %d\n"", get_move_capture(move), get_move_pawn(move), get_move_enpassant(move), get_move_castling(move)); } printf(""\n Total moves: %d\n\n"", move_list->count); } // copy/restore board position macros #define copy_board() \ int board_copy[128], king_square_copy[2]; \ int side_copy, enpassant_copy, castle_copy; \ memcpy(board_copy, board, 512); \ side_copy = side; \ enpassant_copy = enpassant; \ castle_copy = castle; \ memcpy(king_square_copy, king_square,8); \ #define take_back() \ memcpy(board, board_copy, 512); \ side = side_copy; \ enpassant = enpassant_copy; \ castle = castle_copy; \ memcpy(king_square, king_square_copy,8); \ // make move static inline int MakeMove(int move, int capture_flag) { // quiet move if (capture_flag == all_moves) { // copy board state copy_board(); // parse move int from_square = get_move_source(move); int to_square = get_move_target(move); int promoted_piece = get_move_piece(move); int enpass = get_move_enpassant(move); int double_push = get_move_pawn(move); int castling = get_move_castling(move); // move piece board[to_square] = board[from_square]; board[from_square] = e; // pawn promotion if (promoted_piece) board[to_square] = promoted_piece; // enpassant capture if (enpass) !side ? (board[to_square + 16] = e) : (board[to_square - 16] = e); // reset enpassant square enpassant = no_sq; // double pawn push if (double_push) !side ? (enpassant = to_square + 16) : (enpassant = to_square - 16); // castling if (castling) { // switch target square switch (to_square) { // white castles king side case g1: board[f1] = board[h1]; board[h1] = e; break; // white castles queen side case c1: board[d1] = board[a1]; board[a1] = e; break; // black castles king side case g8: board[f8] = board[h8]; board[h8] = e; break; // black castles queen side case c8: board[d8] = board[a8]; board[a8] = e; break; } } // update king square if (board[to_square] == K || board[to_square] == k) king_square[side] = to_square; // update castling rights castle &= castling_rights[from_square]; castle &= castling_rights[to_square]; // change side side ^= 1; // take move back if king is under the check if (is_square_attacked(!side ? king_square[side ^ 1] : king_square[side ^ 1], side)) { // restore board state take_back(); // illegal move return 0; } else // legal move return 1; } else { // if move is a capture if (get_move_capture(move)) // make capture move MakeMove(move, all_moves); else // move is not a capture return 0; } } /***********************************************\ PERFT FUNCTIONS \***********************************************/ // count nodes long nodes = 0; // perft driver static inline void perft_driver(int depth) { // escape condition if (!depth) { // count current position nodes++; return; } // create move list variable moves move_list[1]; // generate moves generate_moves(move_list); // loop over the generated moves for (int move_count = 0; move_count < move_list->count; move_count++) { // copy board state copy_board(); // make only legal moves if (!MakeMove(move_list->moves[move_count], all_moves)) // skip illegal move continue; // recursive call perft_driver(depth - 1); // restore board state take_back(); } } // perft test static inline void PerftTest(int depth) { printf(""\n Performance test:\n\n""); // init start time int start_time = get_time_ms(); // create move list variable moves move_list[1]; // generate moves generate_moves(move_list); // loop over the generated moves for (int move_count = 0; move_count < move_list->count; move_count++) { // copy board state copy_board(); // make only legal moves if (!MakeMove(move_list->moves[move_count], all_moves)) // skip illegal move continue; // cummulative nodes long cum_nodes = nodes; // recursive call perft_driver(depth - 1); // old nodes long old_nodes = nodes - cum_nodes; // restore board state take_back(); // print current move printf("" move %d: %s%s%c %ld\n"", move_count + 1, square_to_coords[get_move_source(move_list->moves[move_count])], square_to_coords[get_move_target(move_list->moves[move_count])], promoted_pieces[get_move_piece(move_list->moves[move_count])], old_nodes ); } // print results printf(""\n Depth: %d"", depth); printf(""\n Nodes: %ld"", nodes); printf(""\n Time: %d ms\n\n"", get_time_ms() - start_time); } /***********************************************\ EVALUATION FUNCTION \***********************************************/ // evaluation of the position static inline int evaluate_position() { // init score int score = 0; // loop over board squares for (int square = 0; square < 128; square++) { // make sure square is on board if (!(square & 0x88)) { // init piece int piece = board[square]; // material score evaluation score += material_score[piece]; // pieces evaluation switch (piece) { // white pieces case P: // positional score score += pawn_score[square]; // double panws penalty if (board[square - 16] == P) score -= 100; break; case N: score += knight_score[square]; break; case B: score += bishop_score[square]; break; case R: score += rook_score[square]; break; case K: score += king_score[square]; break; // black pieces case p: // positional score score -= pawn_score[mirror_score[square]]; // double pawns penalty if (board[square + 16] == p) score += 100; break; case n: score -= knight_score[mirror_score[square]]; break; case b: score -= bishop_score[mirror_score[square]]; break; case r: score -= rook_score[mirror_score[square]]; break; case k: score -= king_score[mirror_score[square]]; break; } } } // return positive score for white & negative for black return !side ? score : -score; } /***********************************************\ SEARCH FUNCTIONS \***********************************************/ // most valuable victim & less valuable attacker /* (Victims) Pawn Knight Bishop Rook Queen King (Attackers) Pawn 105 205 305 405 505 605 Knight 104 204 304 404 504 604 Bishop 103 203 303 403 503 603 Rook 102 202 302 402 502 602 Queen 101 201 301 401 501 601 King 100 200 300 400 500 600 */ static int mvv_lva[13][13] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 105, 205, 305, 405, 505, 605, 105, 205, 305, 405, 505, 605, 0, 104, 204, 304, 404, 504, 604, 104, 204, 304, 404, 504, 604, 0, 103, 203, 303, 403, 503, 603, 103, 203, 303, 403, 503, 603, 0, 102, 202, 302, 402, 502, 602, 102, 202, 302, 402, 502, 602, 0, 101, 201, 301, 401, 501, 601, 101, 201, 301, 401, 501, 601, 0, 100, 200, 300, 400, 500, 600, 100, 200, 300, 400, 500, 600, 0, 105, 205, 305, 405, 505, 605, 105, 205, 305, 405, 505, 605, 0, 104, 204, 304, 404, 504, 604, 104, 204, 304, 404, 504, 604, 0, 103, 203, 303, 403, 503, 603, 103, 203, 303, 403, 503, 603, 0, 102, 202, 302, 402, 502, 602, 102, 202, 302, 402, 502, 602, 0, 101, 201, 301, 401, 501, 601, 101, 201, 301, 401, 501, 601, 0, 100, 200, 300, 400, 500, 600, 100, 200, 300, 400, 500, 600 }; // killer moves [id][ply] int killer_moves[2][64]; // history moves [piece][square] int history_moves[13][128]; // PV moves int pv_table[64][64]; int pv_length[64]; // half move int ply = 0; // score move for move ordering static inline int score_move(int move){ if (pv_table[0][ply] == move) // score 20000 ( search it first ) return 20000; // init current move score int score; // score MVV LVA (scores 0 for quiete moves) score = mvv_lva[board[get_move_source(move)]][board[get_move_target(move)]]; // on capture if (get_move_capture(move)) { // add 10000 to current score score += 10000; } // on quiete move else { // on 1st killer move if (killer_moves[0][ply] == move) // score 9000 score = 9000; // on 2nd killer move else if (killer_moves[1][ply] == move) // score 8000 score = 8000; // on history move (previous alpha's best score) else // score with history depth score = history_moves[board[get_move_source(move)]][get_move_target(move)] + 7000; } // return move score return score; } static inline void sort_moves(moves* move_list) { int move_scores[0xff]; // init move scores array for (int count = 0; count < move_list->count; count++) // score move move_scores[count] = score_move(move_list->moves[count]); // loop over current move score for (int current = 0; current < move_list->count; current++) { // loop over next move score for (int next = current + 1; next < move_list->count; next++) { // order moves descending if (move_scores[current] < move_scores[next]) { // swap scores int temp_score = move_scores[current]; move_scores[current] = move_scores[next]; move_scores[next] = temp_score; // swap corresponding moves int temp_move = move_list->moves[current]; move_list->moves[current] = move_list->moves[next]; move_list->moves[next] = temp_move; } } } } #define NODE_CHECK 9000 bool stop = false; int g_max_depth = 0; long nodeCheck = NODE_CHECK; clock_t start_time=0; clock_t g_max_time = 0; // quiescence search static inline int SearchQuiescence(int alpha, int beta, int depth){ if (++nodes > nodeCheck) { nodeCheck = nodes + NODE_CHECK; stop = clock() - start_time > g_max_time; } if (stop) return 0; int eval = evaluate_position(); if (eval >= beta) return beta; if (eval > alpha) alpha = eval; // create move list variable moves move_list[1]; // generate moves generate_moves(move_list); // move ordering sort_moves(move_list); // loop over the generated moves for (int count = 0; count < move_list->count; count++) { // copy board state copy_board(); // increment ply ply++; // make only legal moves if (!MakeMove(move_list->moves[count], only_captures)) { // decrement ply ply--; // skip illegal move continue; } // recursive call int score = -SearchQuiescence(-beta, -alpha, depth); // restore board state take_back(); // decrement ply ply--; // fail hard beta-cutoff if (score >= beta) return beta; // alpha acts like max in MiniMax if (score > alpha) alpha = score; } // return alpha score return alpha; } // negamax search static inline int SearchAlpha(int alpha, int beta, int depth) { int legal_moves = 0; // best move int best_so_far = 0; // old alpha int old_alpha = alpha; // PV length pv_length[ply] = ply; // escape condition if (!depth) // search for calm position before evaluation return SearchQuiescence(alpha, beta, depth); if (++nodes > nodeCheck) { nodeCheck = nodes + NODE_CHECK; stop = clock() - start_time > g_max_time; } if (stop) return 0; // is king in check? int in_check = is_square_attacked(king_square[side], side ^ 1); // increase depth if king is in check if (in_check) depth++; // create move list variable moves move_list[1]; // generate moves generate_moves(move_list); // move ordering sort_moves(move_list); // loop over the generated moves for (int count = 0; count < move_list->count; count++) { // copy board state copy_board(); // increment ply ply++; // make only legal moves if (!MakeMove(move_list->moves[count], all_moves)) { // decrement ply ply--; // skip illegal move continue; } // increment legal moves legal_moves++; // recursive call int score = -SearchAlpha(-beta, -alpha, depth - 1); // restore board state take_back(); // decrement ply ply--; // fail hard beta-cutoff if (score >= beta) { // update killer moves killer_moves[1][ply] = killer_moves[0][ply]; killer_moves[0][ply] = move_list->moves[count]; return beta; } // alpha acts like max in MiniMax if (score > alpha) { // update history score history_moves[board[get_move_source(move_list->moves[count])]][get_move_target(move_list->moves[count])] += depth; // set alpha score alpha = score; // store PV move pv_table[ply][ply] = move_list->moves[count]; for (int i = ply + 1; i < pv_length[ply + 1]; i++) pv_table[ply][i] = pv_table[ply + 1][i]; pv_length[ply] = pv_length[ply + 1]; // store current best move if (!ply) best_so_far = move_list->moves[count]; } } if (!legal_moves) { if (in_check) return -MAX_SCORE + ply; else return 0; } return alpha; } // search position static void SearchIterate(int depth, int time) { // init nodes count stop = false; nodes = 0; nodeCheck = NODE_CHECK; start_time = clock(); // clear PV, killer and history moves memset(pv_table, 0, 16384); // sizeof(pv_table) memset(killer_moves, 0, 512); // sizeof(killer_moves) memset(history_moves, 0, 6656); // sizeof(history_moves) // best score int score; // iterative deepening for (int current_depth = 1; current_depth <= depth; current_depth++) { // search position with current depth 3 score = SearchAlpha(-MAX_SCORE,MAX_SCORE, current_depth); if (stop) break; clock_t elapsed = clock() - start_time; int del = MAX_SCORE - MAX_DEPTH; if (score > del) cout << ""info score mate "" << (MAX_SCORE - score + 1) / 2 << "" depth "" << current_depth << "" time "" << elapsed << "" nodes "" << nodes << "" pv ""; else if (score < -del) cout << ""info score mate "" << (-MAX_SCORE - score) / 2 << "" depth "" << current_depth << "" time "" << elapsed << "" nodes "" << nodes << "" pv ""; else cout << ""info score cp "" << score << "" depth "" << current_depth << "" time "" << elapsed << "" nodes "" << nodes << "" pv ""; // output best move //printf(""info score cp %d depth %d nodes %ld pv "", score, current_depth, nodes); // print PV line for (int i = 0; i < pv_length[0]; i++) { cout << square_to_coords[get_move_source(pv_table[0][i])] << square_to_coords[get_move_target(pv_table[0][i])] << PieceToPromotion(get_move_piece(pv_table[0][i])); } cout << endl; if (elapsed > time / 8) break; } // print best move cout << ""bestmove "" << square_to_coords[get_move_source(pv_table[0][0])] << square_to_coords[get_move_target(pv_table[0][0])] << PieceToPromotion(get_move_piece(pv_table[0][0])) << endl; } /***********************************************\ UCI PROTOCOL FUNCTIONS \***********************************************/ // parse move (from UCI) int ParseMove(const char* move_str) { // init move list moves move_list[1]; // generate moves generate_moves(move_list); // parse move string int parse_from = (move_str[0] - 'a') + (8 - (move_str[1] - '0')) * 16; int parse_to = (move_str[2] - 'a') + (8 - (move_str[3] - '0')) * 16; int prom_piece = 0; // init move to encode int move; // loop over generated moves for (int count = 0; count < move_list->count; count++) { // pick up move move = move_list->moves[count]; // if input move is present in the move list if (get_move_source(move) == parse_from && get_move_target(move) == parse_to) { // init promoted piece prom_piece = get_move_piece(move); // if promoted piece is present compare it with promoted piece from user input if (prom_piece) { if ((prom_piece == N || prom_piece == n) && move_str[4] == 'n') return move; else if ((prom_piece == B || prom_piece == b) && move_str[4] == 'b') return move; else if ((prom_piece == R || prom_piece == r) && move_str[4] == 'r') return move; else if ((prom_piece == Q || prom_piece == q) && move_str[4] == 'q') return move; continue; } // return move to make on board return move; } } // return illegal move return 0; } static void SetFen(vector fen) { ResetBoard(); int sq = 0; string ele = fen[0]; for (char c : ele) { switch (c) { case 'p':board[sq++] = p; break; case 'n':board[sq++] = n; break; case 'b':board[sq++] = b; break; case 'r':board[sq++] = r; break; case 'q':board[sq++] = q; break; case 'k':king_square[black] = sq; board[sq++] = k; break; case 'P':board[sq++] = P; break; case 'N':board[sq++] = N; break; case 'B':board[sq++] = B; break; case 'R':board[sq++] = R; break; case 'Q':board[sq++] = Q; break; case 'K':king_square[white] = sq; board[sq++] = K; break; case '1': sq += 1; break; case '2': sq += 2; break; case '3': sq += 3; break; case '4': sq += 4; break; case '5': sq += 5; break; case '6': sq += 6; break; case '7': sq += 7; break; case '8': sq += 8; break; case '/': sq += 8; break; } } ele = fen[1]; side = (ele == ""w"") ? white : black; ele = fen[2]; for (char c : ele) switch (c) { case 'K': castle |= KC; break; case 'Q': castle |= QC; break; case 'k': castle |= kc; break; case 'q': castle |= qc; break; } if (fen[3][0] != '-') { int file = fen[3][0] - 'a'; int rank = 7 - (fen[3][1] - '1'); enpassant = rank * 16 + file; } } static void SetFen(string fen) { vector v = SplitString(fen); SetFen(v); } static void ParsePosition(vector commands) { vector fen = {}; vector moves = {}; int mark = 0; for (int i = 1; i < commands.size(); i++) { if (mark == 1) fen.push_back(commands[i]); if (mark == 2) moves.push_back(commands[i]); if (commands[i] == ""fen"") mark = 1; else if (commands[i] == ""moves"") mark = 2; } if (fen.size() != 6) fen = SplitString(defFen); SetFen(fen); for (string m : moves) { int move = ParseMove(m.c_str()); MakeMove(move, all_moves); } } static void UciQuit() { exit(0); } static void UciTest() { UciCommand(""position startpos moves e2e4 e7e5 g1f3 b8c6 f1b5 a7a6 b5a4 f8e7 d2d4 e5d4 f3d4 g8f6 d4c6 d7c6 d1d8 e7d8 f2f3 b7b5 a4b3 c6c5 c2c4 b5c4 b3c4 c8e6 b1a3 e8g8 c4e6 f7e6 c1e3 d8e7 a1c1 a8b8 b2b3 f6d7 e1g1 b8d8 a3c4 f8e8 e3f4 d8c8 f1d1 e8d8 c4a5 d7f6 d1d8 c8d8 a5c6 d8e8 c6e7 e8e7 c1c5 f6e8 f4e5 e7d7 c5a5 d7d1 g1f2 d1d2 f2g3 c7c5 a5a6 g8f7 a6a7 f7f8 a2a4 h7h5 a4a5 h5h4 g3h4 d2g2 a5a6""); UciCommand(""go depth 5""); } void UciCommand(string line) { vector commands = SplitString(line); fflush(stdout); if (commands[0] == ""uci"") { cout << ""id name "" << name << endl; cout << ""uciok"" << endl; } else if (commands[0] == ""isready"") { cout << ""readyok"" << endl; } else if (commands[0] == ""position"") ParsePosition(commands); else if (commands[0] == ""go"") { g_max_depth = GetInt(commands, ""depth"", 0xff); g_max_time = GetInt(commands, side == white ? ""wtime"" : ""btime"", 0) / 30; if (!g_max_time) g_max_time = GetInt(commands, ""movetime"", 0xffffff); SearchIterate(g_max_depth, g_max_time); } else if (commands[0] == ""print"") PrintBoard(); else if (commands[0] == ""test"") UciTest(); else if (commands[0] == ""quit"") UciQuit(); } static void UciLoop() { string line; while (true) { getline(cin, line); UciCommand(line); } } // main driver int main() { PrintWelcome(); UciLoop(); return 0; }",words 338,"template inline g2d::animation::bazier::bazier() : _running(false) , _time(0) , _node(0) , _speed(0.001) , _vector(std::vector>()) { } template inline g2d::animation::bazier::~bazier() { this->_vector.clear(); } template inline void g2d::animation::bazier::update() { this->_time = g2d::math::clamp(this->_time + this->_speed, 0.0, 1.0); } template inline void g2d::animation::bazier::play() { this->_running = true; } template inline void g2d::animation::bazier::stop() { this->_running = false; } template inline void g2d::animation::bazier::replay() { this->_running = true; this->_time = 0.0; } template inline void g2d::animation::bazier::reset() { this->_running = false; this->_time = 0.0; } template inline void g2d::animation::bazier::bind_point(const g2d::math::point3d& point) { this->_vector.push_back(point); this->_node = this->_vector.size() - 1; } template inline void g2d::animation::bazier::bind_point(T x, T y, T z) { this->_vector.push_back(g2d::math::point3d(x, y, z)); this->_node = this->_vector.size() - 1; } template inline void g2d::animation::bazier::bind_point(T point) { this->_vector.push_back(g2d::math::point3d(point)); this->_node = this->_vector.size() - 1; } template inline void g2d::animation::bazier::bind_point_x(T x) { this->_vector.push_back(g2d::math::point3d(x, static_cast(0), static_cast(0))); this->_node = this->_vector.size() - 1; } template inline void g2d::animation::bazier::bind_point_y(T y) { this->_vector.push_back(g2d::math::point3d(static_cast(0), y, static_cast(0))); this->_node = this->_vector.size() - 1; } template inline void g2d::animation::bazier::bind_point_z(T z) { this->_vector.push_back(g2d::math::point3d(static_cast(0), static_cast(0), z)); this->_node = this->_vector.size() - 1; } template inline void g2d::animation::bazier::speed(double speed) { this->_speed = speed; } template inline g2d::math::point3d g2d::animation::bazier::point() { int kn; int nn; int nkn; double blend; double [MASK] ; double munk; g2d::math::point3d b = g2d::math::point3d(0.0); [MASK] = 1; munk = pow(1 - this->_time, (double)this->_node); for (int k = 0; k <= static_cast(this->_node); k++) { nn = this->_node; kn = k; nkn = this->_node - k; blend = [MASK] * munk; [MASK] *= this->_time; munk /= (1 - this->_time); while (nn >= 1) { blend *= nn; nn--; if (kn > 1) { blend /= (double)kn; kn--; } if (nkn > 1) { blend /= (double)nkn; nkn--; } } b.x(b.x() + this->_vector[k].x() * blend); b.y(b.y() + this->_vector[k].y() * blend); b.z(b.z() + this->_vector[k].z() * blend); } if (this->_time == 1) { return this->_vector[this->_node]; } if (this->_time == 0) { return this->_vector[0]; } return b; } template inline double g2d::animation::bazier::speed() const { return this->_speed; } template inline double g2d::animation::bazier::time() const { return this->_time; } template inline std::size_t g2d::animation::bazier::node() const { return this->_node; } template inline bool g2d::animation::bazier::bound() const { return this->_time == 1.0; } ",muk 339,"#include #include #include #include // pins for leds #define PIN_SWITCH 4 #define PIN_PIXELS 6 #define PIN_SWITCH_PULL_UP 7 #define NUMPIXELS 6 #define PIN_LATCH 11 #define PIN_CLOCK 12 #define PIN_DATA 10 // variables store date correction from serial byte Year; byte Month; byte Date; byte DoW; byte Hour; byte Minute; byte Second; //setup neopixel leds Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN_PIXELS, NEO_GRB + NEO_KHZ800); //clocks RTClib myRTC; DS3231 Clock; // used to toggle second led bool secondsOn = false; void setup() { // setup pins for shift register pinMode(PIN_LATCH, OUTPUT); pinMode(PIN_DATA, OUTPUT); pinMode(PIN_CLOCK, OUTPUT); // setup pins for light control switch pinMode(PIN_SWITCH_PULL_UP, OUTPUT); pinMode(PIN_SWITCH, INPUT); digitalWrite(PIN_SWITCH_PULL_UP, HIGH); pixels.begin(); Serial.begin(9600); Wire.begin(); showAnimation(); } // lookup map for numbers. digit[0] is 0, digit[1] is 1 and so on byte digit[10]= {B00100001, B11111001, B00010101, B10010001, B11001001, B10000011, B00000011, B11110001, B00000001, B11000001}; // map for different states of the animation byte init_animation[6]= {B00100011, B00100101, B00101001, B00110001, B10100001, B01100001}; void loop() { while (true){ if (Serial.available()) { handleSerialData(Year, Month, Date, DoW, Hour, Minute, Second); } else { updateTime(); for (int i = 0; i <= 60; i++) { if (Serial.available()){ break; } if (digitalRead(PIN_SWITCH) == HIGH){ turnLightOn(); toggleSeconds(); } else { turnLightOff(); secondsOn = false; } delay(1000); } } } } void showAnimation(){ for (int i = 0; i <= 12; i++) { for (int j = 0; j < 6; j++){ digitalWrite(PIN_LATCH, LOW); shiftOut(PIN_DATA, PIN_CLOCK, LSBFIRST, init_animation[j]); shiftOut(PIN_DATA, PIN_CLOCK, LSBFIRST, init_animation[j]); shiftOut(PIN_DATA, PIN_CLOCK, LSBFIRST, init_animation[j]); shiftOut(PIN_DATA, PIN_CLOCK, LSBFIRST, init_animation[j]); digitalWrite(PIN_LATCH, HIGH); delay(70); turnLightOff(); } turnLightOn(); } } void toggleSeconds(){ if (secondsOn){ pixels.setPixelColor(5, pixels.Color(0,0,0)); pixels.show(); secondsOn = false; } else { pixels.setPixelColor(5, pixels.Color(7,20,0)); pixels.show(); secondsOn = true; } } void turnLightOn(){ for (int j = 0; j < 5; j++){ pixels.setPixelColor(j, pixels.Color(60,255,0)); pixels.show(); } } void turnLightOff(){ for (int j = 0; j < 6; j++){ pixels.setPixelColor(j, pixels.Color(0,0,0)); pixels.show(); } } void updateTime() { DateTime now = myRTC.now(); int m1 = (now.minute() / 10) % 10; int m2 = (now.minute() / 1) % 10; int h1 = (now.hour() / 10) % 10; int h2 = (now.hour() / 1) % 10; digitalWrite(PIN_LATCH, LOW); shiftOut(PIN_DATA, PIN_CLOCK, LSBFIRST, digit[h2]); shiftOut(PIN_DATA, PIN_CLOCK, LSBFIRST, digit[h1]); shiftOut(PIN_DATA, PIN_CLOCK, LSBFIRST, digit[m2]); shiftOut(PIN_DATA, PIN_CLOCK, LSBFIRST, digit[m1]); digitalWrite(PIN_LATCH, HIGH); } // from DS3231_set example void handleSerialData(byte& Year, byte& Month, byte& Day, byte& DoW, byte& Hour, byte& Minute, byte& Second) { // Call this if you notice something coming in on // the serial port. The data coming in should be in // the order YYMMDDwHHMMSS, with an 'x' at the end. boolean [MASK] = false; char InChar; byte Temp1, Temp2; char InString[20]; byte j=0; while (! [MASK] ) { if (Serial.available()) { InChar = Serial.read(); InString[j] = InChar; j += 1; if (InChar == 'x') { [MASK] = true; } } } Serial.println(InString); // Read Year first Temp1 = (byte)InString[0] -48; Temp2 = (byte)InString[1] -48; Year = Temp1*10 + Temp2; // now month Temp1 = (byte)InString[2] -48; Temp2 = (byte)InString[3] -48; Month = Temp1*10 + Temp2; // now date Temp1 = (byte)InString[4] -48; Temp2 = (byte)InString[5] -48; Day = Temp1*10 + Temp2; // now Day of Week DoW = (byte)InString[6] - 48; // now Hour Temp1 = (byte)InString[7] -48; Temp2 = (byte)InString[8] -48; Hour = Temp1*10 + Temp2; // now Minute Temp1 = (byte)InString[9] -48; Temp2 = (byte)InString[10] -48; Minute = Temp1*10 + Temp2; // now Second Temp1 = (byte)InString[11] -48; Temp2 = (byte)InString[12] -48; Second = Temp1*10 + Temp2; Clock.setClockMode(false); // set to 24h Clock.setYear(Year); Clock.setMonth(Month); Clock.setDate(Date); Clock.setDoW(DoW); Clock.setHour(Hour); Clock.setMinute(Minute); Clock.setSecond(Second); //empty serial buffer while(Serial.available()) { Serial.read(); } } ",GotString 340,"#include ""floor_object_detection.h"" #include #include #include #include #include #include #include #include #include #include #include namespace { // The maximum number of frames to process per second const int kProcessImagesFPS = 1; // TODO: fx and fy should come from Tango through JNI const float fx = 1521.046710; const float fy = 1518.999642; const char* kColorDirectory = ""/sdcard/datasets/tango/color/""; const char* kDepthDirectory = ""/sdcard/datasets/tango/depth/""; } // namespace namespace floor_object_detection { void FloorObjectDetector::ConvertYCbCrtoRGB(uint8_t* rgb, uint8_t* ycbcr, int width, int height) { assert(rgb != nullptr); assert(ycbcr != nullptr); assert(width > 0); assert(height > 0); int num_pixels = width * height; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { float y = 1.164f * ((float) (ycbcr[i * width + j] & 0xff)) - 16.0f; float u = (float) (ycbcr[num_pixels + 2 * (j / 2) + (i / 2) * width] & 0xff) - 128.0f; float v = (float) (ycbcr[num_pixels + 2 * (j / 2) + 1 + (i / 2) * width] & 0xff) - 128.0f; int b = (int) (y + 1.596f * v); int g = (int) (y - 0.392f * u - 0.813f * v); int r = (int) (y + 2.017f * u); if (r < 0) { r = 0; } else if (r > 255) { r = 255; } if (g < 0) { g = 0; } else if (g > 255) { g = 255; } if (b < 0) { b = 0; } else if (b > 255) { b = 255; } rgb[3 * (i * width + j)] = (uint8_t) (r & 0xff); rgb[3 * (i * width + j) + 1] = (uint8_t) (g & 0xff); rgb[3 * (i * width + j) + 2] = (uint8_t) (b & 0xff); } } return; } float* FloorObjectDetector::ProcessDepthAndColorImages(double timestamp, float* depth_data, uint8_t* image_data, int image_width, int image_height, int color_to_depth_ratio) { assert(timestamp > 0); assert(depth_data != nullptr); assert(image_data != nullptr); assert(image_width > 0); assert(image_height > 0); assert(color_to_depth_ratio > 0); char timestamp_str[128]; sprintf(timestamp_str, ""%f"", timestamp * 1e9); if (timestamp < prev_image_timestamp_ + 1.0 / kProcessImagesFPS) { return nullptr; } prev_image_timestamp_ = timestamp; LOGI(""FloorObjectDetectionApplication: Timestamp: %f "", timestamp); //TODO: adjust the code below to work when the depth is at a lower resolution than color if (color_to_depth_ratio != 1) { return nullptr; } float half_height = image_height / 2; cv::Mat color_mat_ycbcr_420sp = cv::Mat(image_height + half_height, image_width, CV_8UC1, image_data); cv::Mat color_mat = cv::Mat(image_height, image_width, CV_8UC3); cvtColor(color_mat_ycbcr_420sp, color_mat, CV_YUV420sp2RGB); cv::Mat depth_mat = cv::Mat(image_height, image_width, CV_32FC1, depth_data); const double [MASK] = 1.5; cv::Mat depth_filtered; cv::threshold(depth_mat, depth_filtered, [MASK] , 0.0, cv::THRESH_TOZERO_INV); //TODO: many of the parameters are hardcoded, these should be const variables //TODO: for loop below should be written in cleaner way //TODO: number of points used for plane fitting is currently around 650, could be reduced for speed std::vector points_depth; points_depth.reserve(650); std::vector points_location; points_location.reserve(650); for(int r = image_height - 160; r < image_height - 80; ++r) { const float* depth_row = depth_filtered.ptr(r); cv::Mat labeled = cv::Mat::zeros(1, image_width, CV_32FC1); std::vector labels_count; labels_count.reserve(20); bool component_active = false; int component_count = 0; int latest_label = 0; for (int c = 0; c < image_width; ++c) { float current_depth = depth_row[c]; float component_depth; if (current_depth > 0) { if (component_active) { if (fabs(current_depth - component_depth) < 0.03) { labeled.at(c) = latest_label; component_depth = current_depth; component_count += 1; } else { latest_label += 1; labeled.at(c) = latest_label; component_depth = current_depth; labels_count.push_back(component_count); component_count = 1; } } else { latest_label += 1; labeled.at(c) = latest_label; component_depth = current_depth; labels_count.push_back(component_count); component_count = 1; component_active = true; } } else { component_active = false; labeled.at(c) = 0; } } labels_count.push_back(component_count); auto max_labels_count_iter = std::max_element(std::begin(labels_count), std::end(labels_count)); int max_labels_count_idx = std::distance(std::begin(labels_count), max_labels_count_iter); int max_label_count = *max_labels_count_iter; if (max_label_count < 100) { continue; } std::vector max_label_indxs; max_label_indxs.reserve(1500); // TODO: No need to loop over the whole width for (int i = 0; i < image_width; ++i) { if (labeled.at(i) == max_labels_count_idx) { max_label_indxs.push_back(i); } } for(int j = max_label_count / 10; j < 8 * max_label_count / 10; j += max_label_count / 10) { points_depth.push_back(depth_row[max_label_indxs[j]]); cv::Point3f current_point; current_point.x = (max_label_indxs[j] - image_width / 2.0f) / fx; current_point.y = (r - image_height / 2.0f) / fy; current_point.z = 1; points_location.push_back(current_point); } labels_count.clear(); max_label_indxs.clear(); } if (points_depth.size() < 100 || points_location.size() < 100) { return nullptr; } cv::Mat left_hand_side = cv::Mat::zeros(points_location.size(), 3, CV_32FC1); cv::Mat right_hand_side = cv::Mat::zeros(points_depth.size(), 1, CV_32FC1); for (int k = 0; k < points_depth.size(); ++k) { left_hand_side.at(k, 0) = points_location[k].x; left_hand_side.at(k, 1) = points_location[k].y; left_hand_side.at(k, 2) = points_location[k].z; right_hand_side.at(k, 0) = points_depth[k]; } points_location.clear(); points_depth.clear(); cv::Mat left_hand_side_transpose = left_hand_side.t(); cv::Mat plane = (((left_hand_side_transpose * left_hand_side).inv()) * left_hand_side_transpose) * right_hand_side; std::unique_ptr cols_x = std::unique_ptr(new float[image_width]); std::unique_ptr rows_y = std::unique_ptr(new float[image_height]); float half_width = image_width / 2; for (int i = 0; i < image_width; ++i) { cols_x[i] = (i - half_width) / fx; } for (int j = 0; j < image_height; ++j) { rows_y[j] = (j - half_height) / fy; } cv::Mat cols_x_mat = cv::Mat(1, image_width, CV_32FC1, cols_x.get()); cv::Mat rows_y_mat = cv::Mat(image_height, 1, CV_32FC1, rows_y.get()); cv::Mat Xs, Ys; cv::repeat(cols_x_mat, image_height, 1, Xs); cv::repeat(rows_y_mat, 1, image_width, Ys); cv::Mat Xs_Zs = Xs.mul(depth_filtered); cv::Mat Ys_Zs = Ys.mul(depth_filtered); float a_plane = plane.at(0, 0); float b_plane = plane.at(1, 0); float c_plane = plane.at(2, 0); float vec_plane_norm = sqrt(pow(a_plane, 2) + pow(b_plane, 2) + 1); cv::Mat diff = (a_plane * Xs_Zs + b_plane * Ys_Zs + c_plane - depth_filtered)/vec_plane_norm; cv::Mat depth_mask; cv::threshold(depth_filtered, depth_mask, 0, 255, cv::THRESH_BINARY); depth_mask.convertTo(depth_mask, CV_8UC1); cv::Mat diff_filtered; diff.copyTo(diff_filtered, depth_mask); char file_name[256]; strcpy(file_name, kDepthDirectory); strcat(file_name, ""diff-filtered.png""); cv::imwrite(file_name, diff_filtered * 3000); cv::Mat components_image; cv::threshold(diff_filtered, components_image, 0.03, 255, cv::THRESH_BINARY); components_image.convertTo(components_image, CV_8UC1); std::vector> contours; std::vector hierarchy; findContours(components_image, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0)); std::vector bound_rects; bound_rects.reserve(contours.size()); if (contours.size() > 0) { cv::Scalar color = cv::Scalar(0, 0, 255); //TODO: approximating contours might speed up the computation for (int i = 1; i < contours.size(); ++i) { double contourArea = cv::contourArea(contours[i]); if (contourArea > 1000) { cv::drawContours(color_mat, contours, i, color, 5); bound_rects.push_back(cv::boundingRect(cv::Mat(contours[i]))); } } } std::unique_ptr bound_rect_arr = std::unique_ptr(new float[5 * bound_rects.size() + 1]); bound_rect_arr[0] = bound_rects.size(); cv::Scalar color_rect = cv::Scalar(0, 255, 255); for (int j = 0; j < bound_rects.size(); ++j) { cv::Rect current_rect = bound_rects[j]; cv::rectangle(color_mat, current_rect.tl(), current_rect.br(), color_rect, 2, 8, 0); cv::Mat rect_roi = depth_filtered(current_rect); cv::Mat rect_roi_nonzero = rect_roi > 0; double min_depth_val, max_depth_val; cv::Point min_depth_loc, max_depth_loc; cv::minMaxLoc(rect_roi, &min_depth_val, &max_depth_val, &min_depth_loc, &max_depth_loc, rect_roi_nonzero); bound_rect_arr[5 * j + 1] = (current_rect.tl().x - half_width) / fx; bound_rect_arr[5 * j + 2] = (current_rect.tl().y - half_height) / fy; bound_rect_arr[5 * j + 3] = (current_rect.br().x - half_width) / fx; bound_rect_arr[5 * j + 4] = (current_rect.br().y - half_height) / fy; bound_rect_arr[5 * j + 5] = min_depth_val; } strcpy(file_name, kColorDirectory); strcat(file_name, ""contours.png""); cv::imwrite(file_name, color_mat); return bound_rect_arr.release(); } } // floor_object_detection",max_threshold 341,"#include ""ContentReader.hpp"" ContentReader::ContentReader( ContentSettings& contentSetting ){ contentInit(std::forward(contentSetting)); } ContentReader::ContentReader( ContentSettings&& contentSetting ){ contentInit(std::forward(contentSetting)); } void ContentReader::contentInit( ContentSettings&& contentSetting ){ if(contentSetting.is_content){ container_ = std::make_shared ( std::move(contentSetting.getContent()) ); }else if(contentSetting.is_file){ container_ = std::make_shared ( contentSetting.getFileName() ); } } bool ContentReader::isEnd(){ return container_->isEnd(); } bool ContentReader::isNotEnd(){ return container_->isNotEnd(); } char ContentReader::current(){ return container_->current(); } char ContentReader::next(){ return container_->next(); } int ContentReader::pos(){ return container_->pos(); } void ContentReader::setPos(int [MASK] ){ return container_->setPos( [MASK] ); } std::size_t ContentReader::find( std::string_view str, std::size_t s ){ return container_->find(str, s); } std::size_t ContentReader::find(char c, std::size_t s ){ return container_->find(c, s); } std::size_t ContentReader::size(){ return container_->size(); } void ContentReader::print(){ container_->print(); } ",new_pos 342,"#include ""json_helper.hpp"" cJSON* root = 0; /** * @brief 文本转键值对 * * @param name 文本 * @param mod 功能键 * @param vk 按键 * @return true * @return false **/ bool string2key (string name, char& mod, char& vk) { int mod_pos[3] = { -1, -1, -1, }; int [MASK] = -1; mod = 0; vk = 0; /* 转大写 */ for (size_t i = 0; i < name.length (); i++) { char* p_char = (char*)(name.c_str () + i); *p_char = toupper (*p_char); } /* 功能键值 */ if (name.find (""ALT"") != -1) { mod |= 0x01; mod_pos[0] = name.find (""ALT"") + 3; } if (name.find (""CTRL"") != -1) { mod |= 0x02; mod_pos[1] = name.find (""CTRL"") + 4; } if (name.find (""SHIFT"") != -1) { mod |= 0x04; mod_pos[2] = name.find (""SHIFT"") + 5; } /* 键值 */ for (size_t i = 0; i < 3; i++) { [MASK] = [MASK] < mod_pos[i] ? mod_pos[i] : [MASK] ; } [MASK] ++; vk = name.c_str ()[ [MASK] ]; if (vk == 0 || mod == 0) { return false; } else { return true; } } /** * @brief 键值对转文本 * **/ bool key2string (char mod, char vk, string& str) { str = """"; if (mod & 0x02) { str += ""Ctrl+""; } if (mod & 0x01) { str += ""Alt+""; } if (mod & 0x04) { str += ""Shift+""; } str += vk; if (str.empty ()) { return false; } else { return true; } } /** * @brief 删除热键项并更新 json 文件 * * @param json_path * @param index **/ void del_to_json (const char* json_path, int index) { cJSON* hotkey_arr = NULL; if (root && cJSON_GetObjectItem (root, ""hotkeys"")) { hotkey_arr = cJSON_GetObjectItem (root, ""hotkeys""); } else { return; } if (hotkey_arr && cJSON_IsArray (hotkey_arr)) { cJSON_DeleteItemFromArray (hotkey_arr, index); } hotkey_num = cJSON_GetArraySize (hotkey_arr); ofstream out (json_path); if (out.is_open ()) { out << cJSON_Print (root); out.close (); } load_from_json (json_path); } /** * @brief 增加热键项并更新 json 文件 * * @param json_path * @param obj **/ void add_to_json (const char* json_path, hotkey_obj& obj) { cJSON* hotkey_arr = NULL; if (root && cJSON_GetObjectItem (root, ""hotkeys"")) { hotkey_arr = cJSON_GetObjectItem (root, ""hotkeys""); } else { root = cJSON_CreateObject (); hotkey_arr = cJSON_AddArrayToObject (root, ""hotkeys""); } if (hotkey_arr && cJSON_IsArray (hotkey_arr)) { cJSON* one_hotkey = cJSON_CreateObject (); cJSON_AddBoolToObject (one_hotkey, ""enable"", obj.enable); cJSON_AddStringToObject (one_hotkey, ""cmd_value"", obj.cmd_value.c_str ()); cJSON_AddStringToObject (one_hotkey, ""key_name"", obj.key_name.c_str ()); cJSON_AddItemToArray (hotkey_arr, one_hotkey); } hotkey_num = cJSON_GetArraySize (hotkey_arr); ofstream out (json_path); if (out.is_open ()) { out << cJSON_Print (root); out.close (); } load_from_json (json_path); } void save_to_json (const char* json_path) { ofstream out (json_path); //root = cJSON_CreateObject (); //cJSON* hotkey_arr = cJSON_AddArrayToObject (root, ""hotkeys""); //for (size_t i = 0; i < hotkey_num; i++) { // cJSON* one_hotkey = cJSON_CreateObject (); // cJSON_AddBoolToObject (one_hotkey, ""enable"", hotkey[i].enable); // cJSON_AddStringToObject (one_hotkey, ""cmd_value"", hotkey[i].cmd_value.c_str ()); // cJSON_AddStringToObject (one_hotkey, ""key_name"", hotkey[i].key_name.c_str ()); // cJSON_AddItemToArray (hotkey_arr, one_hotkey); //} if (hotkey_num != 0) { cJSON* hotkeys = cJSON_GetObjectItem (root, ""hotkeys""); for (size_t i = 0; i < hotkey_num; i++) { cJSON* one_hotkey = cJSON_GetArrayItem (hotkeys, i); if (one_hotkey) { cJSON* _key_name = cJSON_CreateString(hotkey[i].key_name.c_str ()); cJSON* _cmd_value = cJSON_CreateString (hotkey[i].cmd_value.c_str()); cJSON* _enable = cJSON_CreateBool (hotkey[i].enable); cJSON_DeleteItemFromObject (one_hotkey, ""key_name""); cJSON_DeleteItemFromObject (one_hotkey, ""cmd_value""); cJSON_DeleteItemFromObject (one_hotkey, ""enable""); cJSON_AddItemToObject (one_hotkey, ""key_name"", _key_name); cJSON_AddItemToObject (one_hotkey, ""cmd_value"", _cmd_value); cJSON_AddItemToObject (one_hotkey, ""enable"", _enable); DEBUG_OUT (""%s %s %d"", hotkey[i].cmd_value.c_str (), hotkey[i].key_name.c_str (), hotkey[i].enable ); } } } if (out.is_open ()) { out << cJSON_Print (root); out.close (); } } /** * @brief 载入 json 文件 * * @param json_path **/ void load_from_json (const char* json_path) { ifstream in (json_path); string one_line = """"; string context = """"; while (getline (in, one_line)) // 逐行读取 context += one_line; if (root) { cJSON_Delete (root); } root = cJSON_Parse (context.c_str ()); if (root) { cJSON* hotkeys = cJSON_GetObjectItem (root, ""hotkeys""); if (hotkeys && cJSON_IsArray (hotkeys)) { hotkey_num = cJSON_GetArraySize (hotkeys); if (hotkey_num != 0) { hotkey = new hotkey_obj[hotkey_num]; for (size_t i = 0; i < hotkey_num; i++) { cJSON* one_hotkey = cJSON_GetArrayItem (hotkeys, i); if (one_hotkey) { cJSON* _key_name = cJSON_GetObjectItem (one_hotkey, ""key_name""); cJSON* _cmd_value = cJSON_GetObjectItem (one_hotkey, ""cmd_value""); cJSON* _enable = cJSON_GetObjectItem (one_hotkey, ""enable""); hotkey[i].cmd_value = cJSON_GetStringValue (_cmd_value); hotkey[i].key_name = cJSON_GetStringValue (_key_name); hotkey[i].enable = cJSON_IsTrue (_enable); strcpy_s (hotkey[i].key_name_buff, hotkey[i].key_name.c_str ()); strcpy_s (hotkey[i].cmd_value_buff, hotkey[i].cmd_value.c_str ()); if (string2key (hotkey[i].key_name, hotkey[i].mod, hotkey[i].vk)) { hotkey[i].id = GET_HOTKEY_ID (hotkey[i]); if (hotkey[i].enable) { UnregisterHotKey (glo_menu_hwnd, hotkey[i].id); if (RegisterHotKey (glo_menu_hwnd, hotkey[i].id, hotkey[i].mod, hotkey[i].vk)) { hotkey[i].enable = true; } else { hotkey[i].enable = false; } } else { UnregisterHotKey (glo_menu_hwnd, hotkey[i].id); } } DEBUG_OUT (""%s %s %d %d "", hotkey[i].cmd_value.c_str (), hotkey[i].key_name.c_str (), hotkey[i].enable, hotkey[i].id ); } } } } } //cJSON_Delete (root); } ",vk_pos 343,"/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, <> * * 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 ""Deserializer.hpp"" namespace oatpp { namespace xml { oatpp::String Deserializer::parseElementName(State& state) { auto data = state.caret->getCurrData(); auto size = state.caret->getDataSize() - state.caret->getPosition(); for(v_buff_size i = 0; i < size; i ++) { auto c = data[i]; if(i > 0 && (c == '/' || c == '>' || c == ' ' || c == '?' || c == '\t' || c == '\n' || c == '\r' || c == '\f')) { state.caret->inc(i); return oatpp::String(data, i); } bool validChar = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == ':' || c == '.' || c == '_' || c == '-' || c > 127; if(!validChar) { state.errorStack.push(""[oatpp::xml::Deserializer::parseElementName()]: Invalid element name '"" + oatpp::String(data, i + 1) + ""'""); return nullptr; } } state.errorStack.push(""[oatpp::xml::Deserializer::parseElementName()]: Invalid element name""); return nullptr; } oatpp::String Deserializer::parseAttributeName(State& state) { auto data = state.caret->getCurrData(); auto size = state.caret->getDataSize() - state.caret->getPosition(); for(v_buff_size i = 0; i < size; i ++) { auto c = data[i]; if(i > 0 && (c == '=' || c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f')) { state.caret->inc(i); return oatpp::String(data, i); } bool validChar = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == ':' || c == '.' || c == '_' || c == '-' || c > 127; if(!validChar) { state.errorStack.push(""[oatpp::xml::Deserializer::parseAttributeName()]: Invalid attribute name '"" + oatpp::String(data, i + 1) + ""'""); return nullptr; } } state.errorStack.push(""[oatpp::xml::Deserializer::parseAttributeName()]: Invalid attribute name""); return nullptr; } oatpp::String Deserializer::parseAttributeValue(State& state) { char [MASK] ; if(state.caret->isAtChar('\'')) { [MASK] = '\''; } else if(state.caret->isAtChar('""')) { [MASK] = '""'; } else { state.errorStack.push(R""([oatpp::xml::Deserializer::parseElementName()]: ""'"" or '""' is missing)""); return nullptr; } state.caret->inc(1); auto label = state.caret->putLabel(); if(!state.caret->findChar( [MASK] )) { state.errorStack.push(R""([oatpp::xml::Deserializer::parseElementName()]: Unterminated attribute value)""); return nullptr; } auto result = Utils::unescapeText(label.toString(), state.errorStack); state.caret->inc(1); return result; } void Deserializer::parseAttributes(State& state) { auto& caret = state.caret; while(caret->canContinue()) { caret->skipBlankChars(); if(caret->isAtChar('/') || caret->isAtChar('>')) { return; } auto key = parseAttributeName(state); if(!state.errorStack.empty()) { state.errorStack.push(""[oatpp::xml::Deserializer::parseAttributes()]""); return; } caret->skipBlankChars(); if(!caret->canContinueAtChar('=', 1)) { state.errorStack.push(""[oatpp::xml::Deserializer::parseAttributes()]: '=' is missing for '"" + key + ""'""); return; } caret->skipBlankChars(); auto value = parseAttributeValue(state); if(!state.errorStack.empty()) { state.errorStack.push(""[oatpp::xml::Deserializer::parseAttributes()]: key='"" + key + ""'""); return; } state.tree->attributes()[key] = value; } } void Deserializer::parsePINode(State& state, oatpp::String& name) { if(!state.caret->isAtText(""skipBlankChars(); auto label = state.caret->putLabel(); if(!state.caret->findText(""?>"", 2)) { state.errorStack.push(""[oatpp::xml::Deserializer::parsePINode()]: unterminated PI node""); return; } state.tree->setString(label.toString()); state.caret->inc(2); } void Deserializer::parseCommentNode(State& state, oatpp::String& name) { if(!state.caret->isAtText("""", 3)) { state.errorStack.push(""[oatpp::xml::Deserializer::parseCommentNode()]: unterminated comment""); return; } state.tree->setString(label.toString()); state.caret->inc(3); name = ""!COMMENT""; } void Deserializer::parseCDataNode(State& state, oatpp::String& name) { if(!state.caret->isAtText(""putLabel(); if(!state.caret->findText(""]]>"", 3)) { state.errorStack.push(""[oatpp::xml::Deserializer::parseCDataNode()]: unterminated CDATA node""); return; } state.tree->setString(label.toString()); state.caret->inc(3); name = ""!CDATA""; } void Deserializer::parseElementContent(State& state, const oatpp::String& name) { std::vector> nodes; auto data = state.caret->getData(); auto size = state.caret->getDataSize(); bool hasText = false; auto label = state.caret->putLabel(); v_buff_size i = state.caret->getPosition(); while( i < size) { auto c = data[i]; if(!hasText) { bool isWhitespace = (c == ' ' || c == '\r' || c == '\n' || c == '\t' || c == '\f'); if (!isWhitespace && c != '<') { hasText = true; } } if(c == '<') { state.caret->setPosition(i); if(hasText) { auto text = Utils::unescapeText(label.toString(), state.errorStack); if(!state.errorStack.empty()) { state.errorStack.push(""[oatpp::xml::Deserializer::parseElementContent()]""); return; } data::mapping::Tree node; node.setString(text); nodes.emplace_back(""!TEXT"", std::move(node)); } if(state.caret->isAtText(""isAtText(name->c_str(), static_cast(name->size()), true)) { state.errorStack.push(""[oatpp::xml::Deserializer::parseElementContent()]: Invalid closing for tag '"" + name + ""'""); return; } state.caret->skipBlankChars(); if(!state.caret->canContinueAtChar('>', 1)) { state.errorStack.push(""[oatpp::xml::Deserializer::parseElementContent()]: Invalid closing for tag '"" + name + ""' - '>' expected.""); return; } break; } nodes.emplace_back(); State nestedState; nestedState.caret = state.caret; nestedState.config = state.config; nestedState.tree = &nodes[nodes.size() - 1].second; oatpp::String nestedName; parseNode(nestedState, nestedName); if(!nestedState.errorStack.empty()) { state.errorStack.splice(nestedState.errorStack); state.errorStack.push(""[oatpp::xml::Deserializer::parseElementContent()]""); return; } nodes[nodes.size() - 1].first = nestedName; i = state.caret->getPosition(); label = state.caret->putLabel(); } else { i ++; } } if(!nodes.empty()) { if(nodes.size() == 1 && nodes[0].first == ""!TEXT"") { state.tree->setString(nodes[0].second.getString()); } else { state.tree->setPairs(nodes); } } } void Deserializer::parseElementNode(State& state, oatpp::String& name) { if(!state.caret->isAtText(""<"", 1, true)) { state.errorStack.push(""[oatpp::xml::Deserializer::parseElementNode()]: '<' expected""); return; } name = parseElementName(state); if(!state.errorStack.empty()) { state.errorStack.push(""[oatpp::xml::Deserializer::parseElementNode()]""); return; } parseAttributes(state); if(!state.errorStack.empty()) { state.errorStack.push(""[oatpp::xml::Deserializer::parseElementNode()]: tag='"" + name + ""'""); return; } if(state.caret->isAtChar('/')) { if(!(state.caret->canContinueAtChar('/', 1) && state.caret->canContinueAtChar('>', 1))) { state.errorStack.push(""[oatpp::xml::Deserializer::parseElementNode()]: tag='"" + name + ""' - '/>' expected""); } return; } if(!state.caret->canContinueAtChar('>', 1)) { state.errorStack.push(""[oatpp::xml::Deserializer::parseElementNode()]: tag='"" + name + ""' - '>' expected""); return; } parseElementContent(state, name); if(!state.errorStack.empty()) { state.errorStack.push(""[oatpp::xml::Deserializer::parseElementNode()]: tag='"" + name + ""'""); return; } } void Deserializer::parseNode(State& state, oatpp::String& name) { if(state.caret->isAtText(""isAtText("" QCLOUDf48.dat char* split=strtok((char*) splitOnDataPath,""/""); char* datafileName = NULL; while(split != NULL) { datafileName=split; split=strtok(NULL,""/""); } printf(""datafileName: %s\n"", datafileName); // Average 25 error bounds to generate stationary points float floating_error_bounds[] = {1e-7, 5e-7, 9e-7, 1e-6, 3e-6, 5e-6, 7e-6, 9e-6, 1e-5, 3e-5, 5e-5, 7e-5, 9e-5, 1e-4, 3e-4, 5e-4, 7e-4, 9e-4, 1e-3, 2e-3, 3e-3, 4e-3, 5e-3, 6e-3, 7e-3, 8e-3, 9e-3, 1e-2, 1.5e-2, 2e-2, 2.5e-2, 3e-2, 3.5e-2, 4e-2, 4.5e-2, 5e-2, 5.5e-2, 6e-2, 6.5e-2, 7e-2, 7.5e-2, 8e-2, 8.5e-2, 9e-2, 9.5e-2, 1e-1, 1.5e-1, 2e-1, 2.5e-1}; int num_floating_error_bounds = sizeof(floating_error_bounds) / sizeof(floating_error_bounds[0]); printf(""Number of floating error bounds = %d\n"", num_floating_error_bounds); char *rm_buffer = (char* )malloc(500 * sizeof(char)); char *output_buffer = (char* )malloc(500 * sizeof(char)); sprintf(output_buffer, ""%s/icde22-model-output/sz-compression-info.txt"", outputPath); std::string output_sz(output_buffer); // free free(output_buffer); std::string cur_command; char *filename_buffer1 = (char* )malloc(500 * sizeof(char)); // sz sprintf(filename_buffer1, ""%s/icde22-model-output/model-output-%s.csv"", outputPath, datafileName); std::string csv_cmd = ""rm -f ""; csv_cmd += filename_buffer1; system(csv_cmd.c_str()); std::fstream fout_sz; std::vector sz_data; std::fstream extractFile; std::string [MASK] ; for (int id = 0; id < num_floating_error_bounds; id++){ float cur_eb = floating_error_bounds[id]; fout_sz.open((const char* )filename_buffer1, std::fstream::out | std::fstream::app); // sz sprintf(command_buffer, ""%s -f -i %s -z %s.sz -%d"", SZ_EXEC.c_str(), datafilePath, datafilePath, num_dims); cur_command = """"; cur_command += command_buffer; for (int i = num_dims-1; i >= 0; i--) { cur_command += "" ""; cur_command += std::to_string(dims[i]); } sprintf(command_buffer, "" -c %s -M REL %.12f &> %s"", SZ_CONFIG_FILE.c_str(), cur_eb, output_sz.c_str()); cur_command += command_buffer; printf(""command: %s\n"", cur_command.c_str()); system(cur_command.c_str()); extractFile.open(output_sz, std::ios::in); float sz_cratio = 0.0; while (std::getline(extractFile, [MASK] )) { if ( [MASK] .find(""Predicted compression ratio"") != std::string::npos){ sz_cratio = std::stof(trim(mySplit( [MASK] , ':')[1])); break; } } extractFile.close(); if (sz_cratio > 0.0) { sz_data.push_back({cur_eb, sz_cratio}); printf(""==== model finished execution [eb %.10f, cratio: %.4f] ======\n\n\n"", cur_eb, sz_cratio); } // std::vector:: iterator it; for(it = sz_data.begin(); it != sz_data.end(); it++) { float ratio = it->ratio; float eb = it->eb; fout_sz << eb << "", "" << ratio << ""\n""; } sz_data.clear(); fout_sz.close(); sprintf(rm_buffer, ""rm %s.sz.out"", datafilePath); system((const char* )rm_buffer); sprintf(rm_buffer, ""rm %s.sz"", datafilePath); system((const char* )rm_buffer); system(""rm core.*""); } // free all free(command_buffer); free(filename_buffer1); std::vector().swap(sz_data); sprintf(rm_buffer, ""rm %s"", output_sz.c_str()); system((const char* )rm_buffer); free(rm_buffer); std::string().swap(output_sz); } // void usage(int id) // { // printf(""Usage: obtainStationaryPoints -i -3 %d\n"", id); // printf(""Example: obtainStationaryPoints -i QCLOUDf48.dat -3 100 500 500""); // exit(0); // } // int main(int argc, char *argv[]) // { // size_t i = 0; // int num_dims = 0; // int* dims = NULL; // char* datafilePath = NULL; // char* splitOnDataPath = NULL; // size_t dim3 = 0; // size_t dim2 = 0; // size_t dim1 = 0; // int len = 0; // for(i=1;i& frames) : position({startX, startY}), speed(birdSpeed), collisionRect({startX, startY, 30, 20}), flyFrames(frames), currentFrame(0), frameTimeCounter(0.0f), frameSpeed(0.15f) { collisionRect = { position.x, position.y, static_cast(flyFrames[0].width), static_cast(flyFrames[0].height) }; } Bird::~Bird() = default; // 更新鸟的状态,每帧调用 void Bird::Update(const float deltaTime) { // 根据速度和时间差更新鸟的X轴位置 (向左移动) position.x -= speed * deltaTime; // 更新动画帧 frameTimeCounter += deltaTime; if (frameTimeCounter >= frameSpeed) { frameTimeCounter = 0.0f; // 重置计时器 currentFrame++; // 切换到下一帧 if (currentFrame >= flyFrames.size()) // 如果超出最后一帧 { currentFrame = 0; // 回到第一帧,实现循环动画 } } // 更新碰撞矩形的位置和大小 UpdateCollisionRect(); } // 绘制鸟 void Bird::Draw() const { // 绘制当前动画帧的纹理 DrawTexture(flyFrames[currentFrame], static_cast(position.x), static_cast(position.y), WHITE); } // 更新碰撞矩形的位置和大小,使其与鸟的当前状态同步 void Bird::UpdateCollisionRect() { collisionRect.x = position.x; collisionRect.y = position.y; collisionRect.width = GetWidth(); // 使用GetWidth获取当前帧的宽度 collisionRect.height = GetHeight(); // 使用GetHeight获取当前帧的高度 } // 获取鸟的碰撞矩形 Rectangle Bird::GetCollisionRect() const { return collisionRect; } // 检查鸟是否完全移出屏幕左侧 bool Bird::IsOffScreen() const { // 如果鸟的右边缘小于0 (屏幕最左侧),则认为其移出屏幕 return (position.x + GetWidth()) < 0; } // 获取鸟的当前宽度 float Bird::GetWidth() const { return static_cast(flyFrames[currentFrame].width); } // 获取鸟的当前高度 float Bird::GetHeight() const { return static_cast(flyFrames[currentFrame].height); } // 设置鸟的飞行速度 void Bird::setSpeed(const float [MASK] ) { speed = [MASK] ; } ",newSpeed 352,"#include ""Paystation.h"" #include Paystation::Paystation(PayStrategy *ps, std::string ap) { state_ = new PaystationState{0, 0}; pay_strategy_ = ps; pin_ = ap; } int Paystation::insertCoin(const int &coin) { switch (coin) { case 1: case 5: case 10: case 25: case 100: state_->balance += coin; state_->timePurchased = pay_strategy_->calculate(state_->balance); return 0; default: return coin; } } PaystationState *Paystation::getState() { return state_; } std::string Paystation::buy() { std::ostringstream s; s << ""Total: "" << state_->balance << '\n'; s << ""Minutes purchased: "" << state_->timePurchased << '\n'; state_->balance = 0; state_->timePurchased = 0; return s.str(); } PayStrategy *Paystation::setPayStrategy(PayStrategy *ps) { /* Can be replaced with std::exchange() */ auto [MASK] = pay_strategy_; pay_strategy_ = ps; return [MASK] ; } bool Paystation::checkAdminPIN(const std::string &pin) { return pin == pin_; } int Paystation::setAdminPIN(const std::string pin) { if (pin == pin_) return ERR_SAME_PIN; else { pin_ = pin; return 0; } } ",old 353,"#include ""NN.h"" NN::NN(const int a, const int b, const int c): NumOfInputNodes(a), NumOfHiddenNodes(b), NumOfOutputNodes(c), weightsIH(new Matrix(NumOfHiddenNodes, NumOfInputNodes)), weightsHO(new Matrix(NumOfOutputNodes, NumOfHiddenNodes)), biasH(new Matrix(NumOfHiddenNodes, 1)), biasO(new Matrix(NumOfOutputNodes, 1)) { weightsIH->randomize(); weightsHO->randomize(); biasH->randomize(); biasO->randomize(); } std::vector NN::predict(const std::vector& input) { Matrix inputs = Matrix::fromArray(input); Matrix hidden = *weightsIH * inputs; hidden += *biasH; hidden.map(d_sigmoid); Matrix output = *weightsHO * hidden; output += *biasO; output.map(d_sigmoid); return output.toArray(); } void NN::train(const std::vector& input, const std::vector& target) { Matrix inputs = Matrix::fromArray(input); Matrix hidden = *weightsIH * inputs; hidden += *biasH; hidden.map(d_sigmoid); Matrix output = *weightsHO * hidden; output += *biasO; output.map(d_sigmoid); Matrix targets = Matrix::fromArray(target); Matrix outputErrors = targets - output; Matrix gradients = Matrix::map(output, d_dsigmoid); gradients.hadamard(outputErrors); gradients * 0.1; Matrix [MASK] = Matrix::transpose(hidden); Matrix weightsHoDeltas = gradients * [MASK] ; *weightsHO += weightsHoDeltas; *biasO += gradients; Matrix weightTranspose = Matrix::transpose(*weightsHO); Matrix hiddenErrors = weightTranspose * outputErrors; Matrix hiddenGradient = Matrix::map(hidden, d_dsigmoid); hiddenGradient.hadamard(hiddenErrors); hiddenGradient * 0.1; Matrix inputTranspose = Matrix::transpose(inputs); Matrix weightIHDeltas = hiddenGradient * inputTranspose; *weightsIH += weightIHDeltas; *biasH += hiddenGradient; } NN::~NN() { } ",hiddenTranpose 354,"#include // The lexer returns tokens [0-255] if it is an unknown character, otherwise one // of these for known things. enum Token { tok_eof = -1, // EOF tok_def = -2, // Function definition (""def"") tok_extern = -3, // External prototype definition (""extern"") tok_identifier = -4, // String identifier tok_number = -5, // Int/Double number }; static std::string identifier; // Filled in if tok_identifier static double number; // Filled in if tok_number static int gettoken() { static int [MASK] = ' '; // Skip any whitespace. while (isspace( [MASK] )) [MASK] = getchar(); // matches regex [a-zA-Z][a-zA-Z0-9]* if (isalpha( [MASK] )) { identifier = [MASK] ; //add all following characters to the identifier while (isalnum(( [MASK] = getchar()))) identifier += [MASK] ; //return tok_def if it is a definition, else if it is an extern return tok_extern if (identifier == ""def"") return tok_def; if (identifier == ""extern"") return tok_extern; //doesn't match anything, so just return the idenfitier token return tok_identifier; } // matches regex [0-9.]+ if (isdigit( [MASK] ) || [MASK] == '.') { std::string temp; do { temp += [MASK] ; [MASK] = getchar(); //get next char } while (isdigit( [MASK] ) || [MASK] == '.'); //set the raw value of temp to the number number = strtod(temp.c_str(), 0); //return tok_number (found a number) return tok_number; } if ( [MASK] == '#') { // Comment until end of line. do [MASK] = getchar(); while ( [MASK] != EOF && [MASK] != '\n' && [MASK] != '\r'); if ( [MASK] != EOF) return gettoken(); } // Check for end of file. Don't eat the EOF. if ( [MASK] == EOF) return tok_eof; // Otherwise, just return the character as its ascii value. int x = [MASK] ; [MASK] = getchar(); return x; }",currChar 355,"/*************************************************** This is an example for the AHT10 Humidity & Temp Sensor Designed specifically to work with the AHT10, modified using library from: Source: https://github.com/enjoyneering/ These displays use I2C to communicate, 2 pins are required to interface ****************************************************/ #include #include #include // Connect Vin to 3-5VDC // Connect GND to ground // Connect SCL to I2C clock pin (A5 on UNO) // Connect SDA to I2C data pin (A4 on UNO) AHT10 myAHT10(0x38); LiquidCrystal lcd(8, 9, 4, 5, 6, 7); void setup() { Wire.begin(); lcd.begin(16,2); lcd.setCursor(0,0); lcd.print(""Temperature & ""); lcd.setCursor(0,1); lcd.print(""Humidity Meter""); delay(2000); lcd.clear(); Serial.begin(9600); Serial.println(""AHT10 test""); if (!myAHT10.begin()) { Serial.println(""Couldn't find sensor!""); while (1); } } void loop() { float temp = myAHT10.readTemperature(); float [MASK] = myAHT10.readHumidity(); Serial.print(""Temp: ""); Serial.print(temp); Serial.print("" C""); Serial.print(""\t\t""); Serial.print(""Humidity: ""); Serial.print( [MASK] ); Serial.println("" \%""); lcd.setCursor(0,0); lcd.print(""Temp:""); lcd.setCursor(5,0); lcd.print(temp); lcd.setCursor(10,0); lcd.print((char)223); lcd.setCursor(11,0); lcd.print(""C""); lcd.setCursor(0,1); lcd.print(""RH:""); lcd.setCursor(3,1); lcd.print( [MASK] ); lcd.setCursor(8,1); lcd.print(""%""); delay(500); } ",rel_hum 356,"// // 2017 writen by // #include ""node_binder/base/message_pump_node.h"" #include #include #include ""base/lazy_instance.h"" #include ""base/logging.h"" #include ""base/threading/thread_local.h"" #include ""node/uv.h"" #include ""base/debug/stack_trace.h"" namespace base { namespace { base::LazyInstance>::Leaky tls_ptr = LAZY_INSTANCE_INITIALIZER; void IgnoreReleaseHandle(uv_handle_t* handle) {} void ReleaseHandle(uv_handle_t* handle) { delete handle; } void OnPollNotification(uv_poll_t* event, int status, int [MASK] ) { DCHECK(event && event->data); MessagePumpNode::FileDescriptorWatcher* controller = static_cast(event->data); DCHECK(controller); controller->OnFileEventNotification(event->io_watcher.fd, [MASK] ); } } // anonymouse namespace MessagePumpNode::FileDescriptorWatcher::FileDescriptorWatcher() : pump_(nullptr), watcher_(nullptr), persistent_(false), event_mask_(0) { } MessagePumpNode::FileDescriptorWatcher::~FileDescriptorWatcher() { StopWatchingFileDescriptor(); } bool MessagePumpNode::FileDescriptorWatcher::WatchFileDescriptor( int fd, bool persistent, int event_mask, MessagePumpNode* pump, Watcher* watcher) { DCHECK(pump); DCHECK(watcher); DCHECK_GT(event_mask, 0); DCHECK_GT(fd, 0); if (event_.get()) { event_mask |= event_mask_; StopWatchingFileDescriptor(); } event_.reset(new uv_poll_t); event_->data = this; if (uv_poll_init(uv_default_loop(), event_.get(), fd)) { LOG(ERROR) << ""uv_poll_init failed""; return false; } if (uv_poll_start(event_.get(), event_mask, &OnPollNotification)) { uv_close(reinterpret_cast(event_.release()), &ReleaseHandle); LOG(ERROR) << ""watch file descriptor are failed""; return false; } event_mask_ = event_mask; persistent_ = persistent; pump_ = pump; watcher_ = watcher; return true; } bool MessagePumpNode::FileDescriptorWatcher::StopWatchingFileDescriptor() { // poll event already released if (!event_.get()) { return true; } if (uv_poll_stop(event_.get())) { LOG(ERROR) << ""uv_poll_stop are failed""; return false; } uv_close(reinterpret_cast(event_.release()), &ReleaseHandle); event_mask_ = 0; persistent_ = false; pump_ = nullptr; watcher_ = nullptr; return true; } void MessagePumpNode::FileDescriptorWatcher::OnFileEventNotification( int fd, int event_mask) { DCHECK(pump_); if (event_mask & UV_READABLE) { OnFileCanReadWithoutBlocking(fd, pump_); } if (event_mask & UV_WRITABLE) { OnFileCanWriteWithoutBlocking(fd, pump_); } if (!persistent_) { StopWatchingFileDescriptor(); } } void MessagePumpNode::FileDescriptorWatcher::OnFileCanReadWithoutBlocking( int fd, MessagePumpNode* pump) { DCHECK(watcher_); watcher_->OnFileCanReadWithoutBlocking(fd); } void MessagePumpNode::FileDescriptorWatcher::OnFileCanWriteWithoutBlocking( int fd, MessagePumpNode* pump) { DCHECK(watcher_); watcher_->OnFileCanWriteWithoutBlocking(fd); } MessagePumpNode::MessagePumpNode() : delegate_(nullptr), async_handle_(new uv_async_t), timer_handle_(new uv_timer_t), message_pump_state_(STATE_IDLE) { tls_ptr.Pointer()->Set(this); } MessagePumpNode::~MessagePumpNode() { tls_ptr.Pointer()->Set(nullptr); } // static MessagePumpNode* MessagePumpNode::current() { return tls_ptr.Pointer()->Get(); } // static void MessagePumpNode::OnWakeup(uv_async_t* handle) { MessagePumpNode* pump = static_cast(handle->data); DCHECK(pump); pump->DoWork(); } // static void MessagePumpNode::OnTimeout(uv_timer_t* handle) { MessagePumpNode* pump = static_cast(handle->data); DCHECK(pump); pump->DoDelayedWork(); } // static void MessagePumpNode::Run(Delegate* delegate) { NOTREACHED(); } void MessagePumpNode::Quit() { NOTREACHED(); } void MessagePumpNode::ScheduleWork() { if (uv_async_send(async_handle_.get())) { LOG(ERROR) << ""wakeup async task are failed""; } } void MessagePumpNode::ScheduleDelayedWork( const base::TimeTicks& new_delayed_work_time) { // if wait a another timeout event if (!delayed_work_time_.is_null()) { DCHECK_EQ(message_pump_state_, STATE_RUNNING); if (new_delayed_work_time > delayed_work_time_) { return; } } delayed_work_time_ = new_delayed_work_time; base::TimeDelta delay = delayed_work_time_ - base::TimeTicks::Now(); delay = std::max(delay, base::TimeDelta()); if (message_pump_state_ == STATE_RUNNING) { uv_timer_stop(timer_handle_.get()); message_pump_state_ = STATE_STOP; } DCHECK(message_pump_state_ == STATE_INIT || message_pump_state_ == STATE_STOP); uv_timer_start(timer_handle_.get(), OnTimeout, delay.InMilliseconds(), 0); message_pump_state_ = STATE_RUNNING; } bool MessagePumpNode::WatchFileDescriptor(int fd, bool persistent, int mode, FileDescriptorWatcher* controller, Watcher* delegate) { DCHECK_GT(fd, 0); DCHECK(controller); DCHECK(delegate); DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE); DCHECK(thread_checker_.CalledOnValidThread()); uint32_t event_mask = 0; if (mode & WATCH_READ) { event_mask |= UV_READABLE; } if (mode & WATCH_WRITE) { event_mask |= UV_WRITABLE; } controller->WatchFileDescriptor(fd, persistent, event_mask, this, delegate); return true; } void MessagePumpNode::DoWork() { DCHECK(delegate_); for (;;) { bool did_work = false; did_work |= delegate_->DoIdleWork(); did_work |= delegate_->DoWork(); if (!did_work) { break; } } } void MessagePumpNode::DoDelayedWork() { //DCHECK_EQ(message_pump_state_, STATE_RUNNING); DCHECK(delegate_); if (delayed_work_time_.is_null()) { return; } for (;;) { base::TimeDelta delay = delayed_work_time_ - base::TimeTicks::Now(); if (delay > base::TimeDelta()) { uv_timer_start(timer_handle_.get(), OnTimeout, delay.InMilliseconds(), 0); break; } delegate_->DoDelayedWork(&delayed_work_time_); if (delayed_work_time_.is_null()) { uv_timer_stop(timer_handle_.get()); message_pump_state_ = STATE_STOP; break; } } } void MessagePumpNode::StartAsyncTask() { DCHECK_EQ(message_pump_state_, STATE_IDLE); async_handle_->data = this; CHECK_EQ(uv_async_init(uv_default_loop(), async_handle_.get(), &MessagePumpNode::OnWakeup), 0); timer_handle_->data = this; CHECK_EQ(uv_timer_init(uv_default_loop(), timer_handle_.get()), 0); message_pump_state_ = STATE_INIT; } void MessagePumpNode::StopAsyncTask() { DCHECK_NE(message_pump_state_, STATE_IDLE); uv_close(reinterpret_cast(async_handle_.get()), &IgnoreReleaseHandle); CHECK_EQ(uv_timer_stop(timer_handle_.get()), 0); uv_close(reinterpret_cast(timer_handle_.get()), &IgnoreReleaseHandle); message_pump_state_ = STATE_IDLE; } void MessagePumpNode::CloseAsyncTask() { if (async_handle_.get()) { uv_close(reinterpret_cast(async_handle_.release()), &ReleaseHandle); } if (timer_handle_.get()) { uv_close(reinterpret_cast(timer_handle_.release()), &ReleaseHandle); } message_pump_state_ = STATE_TERMINATE; } } // namespace base ",flags 357,"#include #include #include #include #include using namespace std; int diagSum(int n, vector> a){ int [MASK] = 0; int sum_secdry = 0; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ if (i == j){ [MASK] = [MASK] + a[i][j]; } } for (int j = n-1; j>=0; j--){ if ((i + j) == (n - 1)){ sum_secdry = sum_secdry + a[i][j]; } } } return abs( [MASK] - sum_secdry); } int main(){ int n; cin >> n; vector< vector > a(n,vector(n)); for(int a_i = 0;a_i < n;a_i++){ for(int a_j = 0;a_j < n;a_j++){ cin >> a[a_i][a_j]; } } cout << diagSum(n, a) << endl; return 0; }",sum_prmry 358,"// - #include #include ""Tas.h"" #include ""At.h"" using namespace std; At::At(takim renk, int x, int y): Tas(renk, ""At"", x, y){} bool At::yolKntrl(vector taslar, pair [MASK] ){ // Gittigi yerde tas olma : for(int i = 0; i < taslar.size(); i++){ if(taslar[i]->getKonum() == this->getKonum()){ continue; } if(taslar[i]->getKonum() == [MASK] ) { if(taslar[i]->getTakim() == this->getTakim()){ return false; } } } // Kendi yerine oynayamaz : if(this->getKonum() == [MASK] ){ return false; } // Oynanabilecek yerler : if(make_pair(this->getKonum().first-2,this->getKonum().second-1) == [MASK] ){ return true; } else if(make_pair(this->getKonum().first-2,this->getKonum().second+1) == [MASK] ){ return true; } else if(make_pair(this->getKonum().first-1,this->getKonum().second-2) == [MASK] ){ return true; }else if(make_pair(this->getKonum().first-1,this->getKonum().second+2) == [MASK] ){ return true; }else if(make_pair(this->getKonum().first+1,this->getKonum().second-2) == [MASK] ){ return true; }else if(make_pair(this->getKonum().first+1,this->getKonum().second+2) == [MASK] ){ return true; }else if(make_pair(this->getKonum().first+2,this->getKonum().second-1) == [MASK] ){ return true; }else if(make_pair(this->getKonum().first+2,this->getKonum().second+1) == [MASK] ){ return true; } else{ return false; } } ",gidilecekyer 359,"#include ""InputHelper.h"" static const char* styleNames[] = { ""Pro Controller"", ""Joy-Con controller in handheld mode"", ""Joy-Con controller in dual mode"", ""Joy-Con left controller in single mode"", ""Joy-Con right controller in single mode"", ""GameCube controller"", ""Poké Ball Plus controller"", ""NES/Famicom controller"", ""NES/Famicom controller in handheld mode"", ""SNES controller"", ""N64 controller"", ""Sega Genesis controller"", ""generic external controller"", ""generic controller"", }; nn::hid::NpadBaseState InputHelper::prevControllerState {}; nn::hid::NpadBaseState InputHelper::curControllerState {}; ulong InputHelper::selectedPort = -1; bool InputHelper::isReadInput = true; bool InputHelper::toggleInput = false; bool InputHelper::disableMouse = false; const char* getStyleName(nn::hid::NpadStyleSet style) { s32 [MASK] = -1; if (style.Test((int)nn::hid::NpadStyleTag::NpadStyleFullKey)) { [MASK] = 0; } if (style.Test((int)nn::hid::NpadStyleTag::NpadStyleHandheld)) { [MASK] = 1; } if (style.Test((int)nn::hid::NpadStyleTag::NpadStyleJoyDual)) { [MASK] = 2; } if (style.Test((int)nn::hid::NpadStyleTag::NpadStyleJoyLeft)) { [MASK] = 3; } if (style.Test((int)nn::hid::NpadStyleTag::NpadStyleJoyRight)) { [MASK] = 4; } if (style.Test((int)nn::hid::NpadStyleTag::NpadStyleSystemExt)) { [MASK] = 12; } if (style.Test((int)nn::hid::NpadStyleTag::NpadStyleSystem)) { [MASK] = 13; } if ( [MASK] != -1) { return styleNames[ [MASK] ]; } else { return ""Unknown""; } } void InputHelper::updatePadState() { prevControllerState = curControllerState; tryGetContState(&curControllerState, selectedPort); } bool InputHelper::tryGetContState(nn::hid::NpadBaseState* state, ulong port) { nn::hid::NpadStyleSet styleSet = nn::hid::GetNpadStyleSet(port); isReadInput = true; bool result = true; if (styleSet.Test((int)nn::hid::NpadStyleTag::NpadStyleFullKey)) { nn::hid::GetNpadState((nn::hid::NpadFullKeyState*)state, port); } else if (styleSet.Test((int)nn::hid::NpadStyleTag::NpadStyleHandheld)) { nn::hid::GetNpadState((nn::hid::NpadHandheldState*)state, port); } else if (styleSet.Test((int)nn::hid::NpadStyleTag::NpadStyleJoyDual)) { nn::hid::GetNpadState((nn::hid::NpadJoyDualState*)state, port); } else if (styleSet.Test((int)nn::hid::NpadStyleTag::NpadStyleJoyLeft)) { nn::hid::GetNpadState((nn::hid::NpadJoyLeftState*)state, port); } else if (styleSet.Test((int)nn::hid::NpadStyleTag::NpadStyleJoyRight)) { nn::hid::GetNpadState((nn::hid::NpadJoyRightState*)state, port); } else { result = false; } isReadInput = false; return result; } bool InputHelper::isButtonHold(nn::hid::NpadButton button) { return curControllerState.mButtons.Test((int)button); } bool InputHelper::isButtonPress(nn::hid::NpadButton button) { return curControllerState.mButtons.Test((int)button) && !prevControllerState.mButtons.Test((int)button); } bool InputHelper::isButtonRelease(nn::hid::NpadButton button) { return !curControllerState.mButtons.Test((int)button) && prevControllerState.mButtons.Test((int)button); }",index 360,"#include #include #include #include #include #include ""FreeRTOS.h"" #include ""boost/program_options.hpp"" #include ""bootloader/core/message_handler.h"" #include ""bootloader/core/node_id.h"" #include ""can/core/ids.hpp"" #include ""can/simlib/sim_canbus.hpp"" #include ""common/core/logging.h"" #include ""task.h"" namespace po = boost::program_options; static CANNodeId g_node_id = can_nodeid_pipette_left_bootloader; /** The simulator's bootloader */ CANNodeId get_node_id(void) { return g_node_id; } /** * Handle a new can message * @param cb_data callback data * @param identifier arbitration id * @param data data * @param length length of data */ void on_can_message(void* ctx, uint32_t identifier, uint8_t* data, uint8_t length) { Message message; Message response; auto* canbus = static_cast(ctx); message.arbitration_id.id = identifier; message.size = length; std::memcpy( message.data, data, std::min(static_cast(length), sizeof(message.data))); auto [MASK] = handle_message(&message, &response); switch ( [MASK] ) { case handle_message_ok: LOG(""Message ok. No response""); break; case handle_message_has_response: LOG(""Message ok. Has response""); canbus->send(response.arbitration_id.id, response.data, static_cast(response.size)); break; case handle_message_error: LOG(""Message error.""); break; default: LOG(""Unknown return.""); break; } } void signal_handler(int signum) { LOG(""Interrupt signal (%d) received."", signum); exit(signum); } auto node_from_arg(std::string const& val) -> CANNodeId { if (val == ""pipette_left"") { return can_nodeid_pipette_left_bootloader; } else if (val == ""pipette_right"") { return can_nodeid_pipette_right_bootloader; } else if (val == ""gantry_x"") { return can_nodeid_gantry_x_bootloader; } else if (val == ""gantry_y"") { return can_nodeid_gantry_y_bootloader; } else if (val == ""head"") { return can_nodeid_head_bootloader; } else if (val == ""gripper"") { return can_nodeid_gripper_bootloader; } else { throw po::validation_error(po::validation_error::invalid_option_value); } } // this function is automatically called by program options to validate inputs; // if it throws, that's a validation failure. void validate(boost::any& v, std::vector const& values, CANNodeId*, int) { po::validators::check_first_occurrence(v); auto const& string_val = po::validators::get_single_string(values); // this throws appropriately if the arg is wrong v = boost::any(node_from_arg(string_val)); } auto handle_options(int argc, char** argv) -> po::variables_map { auto cmdlinedesc = po::options_description(""simulator for OT-3 pipettes""); auto envdesc = po::options_description(""""); cmdlinedesc.add_options()(""help,h"", ""Show this help message.""); cmdlinedesc.add_options()( ""node,n"", po::value()->default_value( can_nodeid_pipette_left_bootloader), ""Which node id to use. Maybe May be specified in an "" ""environment variable called NODE_ID. Accepted values: pipette_left, "" ""pipette_right, gantry_x, gantry_y, head, gripper""); envdesc.add_options()(""NODE_ID"", po::value()->default_value( can_nodeid_pipette_left_bootloader)); auto can_arg_xform = can::sim::transport::add_options(cmdlinedesc, envdesc); po::variables_map vm; po::store(po::parse_command_line(argc, argv, cmdlinedesc), vm); if (vm.count(""help"")) { std::cout << cmdlinedesc << std::endl; std::exit(0); } po::store(po::parse_environment( envdesc, [can_arg_xform](const std::string& input_val) -> std::string { if (input_val == ""NODE_ID"") { return ""node""; }; return can_arg_xform(input_val); }), vm); po::notify(vm); return vm; } int main(int argc, char** argv) { signal(SIGINT, signal_handler); LOG_INIT(""BOOTLOADER"", []() -> const char* { return pcTaskGetName(xTaskGetCurrentTaskHandle()); }); auto options = handle_options(argc, argv); auto canbus = std::make_shared( can::sim::transport::create(options)); g_node_id = options[""node""].as(); LOG(""Running bootloader for node id %d"", g_node_id); canbus->setup_node_id_filter(static_cast(get_node_id())); canbus->set_incoming_message_callback(canbus.get(), on_can_message); vTaskStartScheduler(); } ",handle_message_return 361,"#include #include #include #include struct RGB { public: int red; int green; int blue; public: RGB() = default; RGB(int r, int g, int b) : red(r), green(g), blue(b) {} ~RGB() {} }; class AShape { public: sf::Shape* shape; std::string shapeName; int shapeTag; RGB rgbVal; float radius; sf::Vector2f dimensions; sf::Vector2f initPosition; sf::Vector2f speed; public: AShape() = default; AShape(std::string inputData) { // Sort inputData // Create an input string stream from the given string std::istringstream dataStream(inputData); std::vector dataElements; std::string element; while (dataStream >> element) { dataElements.push_back(element); } // Assign data if (!dataElements.empty()) { if (dataElements[0] == (""Circle"")) { radius = std::stof(dataElements[9]); shape = new sf::CircleShape(radius); shapeTag = 1; } else if (dataElements[0] == (""Rectangle"")) { dimensions = sf::Vector2f(std::stof(dataElements[9]), std::stof(dataElements[10])); shape = new sf::RectangleShape(dimensions); shapeTag = 2; } shapeName = dataElements[1]; initPosition = sf::Vector2f(std::stof(dataElements[2]), std::stof(dataElements[3])); speed = sf::Vector2f(std::stof(dataElements[4]), std::stof(dataElements[5])); rgbVal.red = std::stoi(dataElements[6]); rgbVal.green = std::stoi(dataElements[7]); rgbVal.blue = std::stoi(dataElements[8]); shape->setFillColor(sf::Color(rgbVal.red, rgbVal.green, rgbVal.blue)); shape->setPosition(initPosition); } } ~AShape() { if (shape != nullptr) { delete shape; } else { std::cout << ""shape is nullptr"" << std::endl; } } }; int main(int argc, char* argv[]) { // Get Config.txt std::string filePath = ""D:/SFML_GameEngine/Config.txt""; std::ifstream inputFile(filePath); sf::Font inputFont; // Import font if (!inputFont.loadFromFile(""D:/SFML_GameEngine/Fonts/Dosis/Dosis.ttf"")) { std::cerr << ""Error opening the font file."" << std::endl; return 1; } // Check if the data file is open successfully if (!inputFile.is_open()) { std::cerr << ""Error opening the data file: "" << filePath << std::endl; return 2; } // Read and print the contents of the file std::string windowLine; std::string line; int lineNumber = 0; std::vector lines = {}; while (std::getline(inputFile, line)) { if (lineNumber == 0) { windowLine = line; } else { lines.push_back(line); } lineNumber++; } inputFile.close(); // Read windowLine and extract values std::istringstream inputWindowStream(windowLine); std::vector [MASK] ; std::string windowElement; while (inputWindowStream >> windowElement) { [MASK] .push_back(windowElement); } // Set window properties int windowX = std::stoi( [MASK] [1]); int windowY = std::stoi( [MASK] [2]); sf::RenderWindow window(sf::VideoMode(windowX, windowY), ""Aquarium""); window.setFramerateLimit(60); // Set text properties sf::Text textName; textName.setFont(inputFont); textName.setCharacterSize(24); textName.setFillColor(sf::Color::White); textName.setOutlineColor(sf::Color::Black); textName.setOutlineThickness(2.f); textName.setPosition(sf::Vector2f(500.f, 500.f)); sf::Text quitText; quitText.setFont(inputFont); quitText.setCharacterSize(15); quitText.setFillColor(sf::Color::White); quitText.setOutlineColor(sf::Color::Black); quitText.setOutlineThickness(1.f); quitText.setPosition(sf::Vector2f(0.f, windowY - quitText.getCharacterSize() - 5.f)); quitText.setString(""\"" ESC \"" to quit""); // Fill vector of shapes std::vector shapes = {}; for (const auto& line : lines) { AShape* shape = new AShape(line); shapes.push_back(shape); } // Main while loop std::cout << ""Start Game"" << std::endl; while (window.isOpen()) { // Key events sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Escape) { window.close(); } } } // Rendering window.clear(); for (auto& element : shapes) { // Shape rendering window.draw(*(element->shape)); // Shape animation float currentX = element->shape->getPosition().x; float currentY = element->shape->getPosition().y; sf::Vector2f textCenter = {}; if(currentX <= 0) { element->speed.x = -element->speed.x; } else if (currentY <= 0) { element->speed.y = -element->speed.y; } if (element->shapeTag == 1) // Circle { textCenter.x = currentX + element->radius; textCenter.y = currentY + element->radius; if (currentX + (2 * element->radius) >= windowX) { element->speed.x = -element->speed.x; } else if (currentY + (2 * element->radius) >= windowY) { element->speed.y = -element->speed.y; } } else if (element->shapeTag == 2) // Rectangle { textCenter.x = currentX + (element->dimensions.x/2); textCenter.y = currentY + (element->dimensions.y/2); if (currentX + (element->dimensions.x) >= windowX) { element->speed.x = -element->speed.x; } else if (currentY + (element->dimensions.y) >= windowY) { element->speed.y = -element->speed.y; } } element->shape->setPosition(currentX + element->speed.x, currentY + element->speed.y); // Text animation textName.setString(element->shapeName); float charSize = textName.getCharacterSize(); std::size_t stringSize = textName.getString().getSize(); textName.setPosition(textCenter.x - (5 * stringSize) + element->speed.x, textCenter.y - (charSize*0.75f) + element->speed.y); window.draw(textName); window.draw(quitText); } window.display(); } // Release memory for (AShape* shape : shapes) { if (shape != nullptr) { delete shape; std::cout << ""Release memory"" << std::endl; } } return 0; }",windowElements 362,"//-------------------------------------- // File: QueueClass.h // Class Queue // Functions: //// queue() : CDLList() {}; // queue(listelem* hd, listelem* tl, unsigned size) : // CDLLList(hd, tl, size) {}; // queue(const queue& qu) : CDLList(qu) {}; // queue(iterator b, iterator e) : CDLList(b, e) {}; // virtual ~queue() { release(); }; // unsigned getSize(); // iterator begin(); // iterator end(); // bool empty(); // void release(); // void push(T& element); // T pop(); // print(ostream& sout); //--------------------------------------- #ifndef PUBLICQUEUE_H #define PUBLICQUEUE_H #include ""CDLList.h"" #include #include #include #include using namespace std; //----------------------------------------------------------------------------- // Title: Queue Class Declaration and Definitions // Description: This file contains the class declarations and definitions for // queue // // Programmer: // // Date: original: May 16, 2017 // Version: 1.0 // // Environment: Intel Xeon PC // Software: Windows 10 Enterprise // Compiles under Microsoft Visual C++.Net 2015 // // class list: // // Methods: // // inline: // queue() : CDLList() {}; -- default constructor // queue(listelem* hd, listelem* tl, unsigned size) : // CDLLList(hd, tl, size) {}; -- constructor with two parameters // queue(const queue& qu) : CDLList(qu) {}; - constructor that copies a queue // Queue(const CDLList & cl) : CDLList(cl) {}; -- constructor that takes CDLList // queue(iterator b, iterator e) : CDLList(b, e) {}; -- copy constructor with iterators // virtual ~queue() { release(); }; -- destructor for queue // unsigned getSize(); -- returns unsigned size of queue/CDLList // iterator begin(); -- returns iterator, beginning of queue/CDLList // iterator end();-- returns iterator, end of queue/CDLList // bool empty(); -- returns bool, false if list is not empty // void release(); -- returns non- releases and deletes list elements // void push(T& element); // T pop(); // print(ostream& sout); // // History Log: // 5/16/2017 v1.0 completed by TR //----------------------------------------------------------------------------- namespace PB_ADT { template class publicQueue : public CDLList { public: publicQueue() : CDLList() {}; publicQueue(size_t [MASK] , T data) : CDLList( [MASK] , data) {}; publicQueue(const publicQueue& qu) : CDLList(qu) {}; publicQueue(const CDLList & cl) : CDLList(cl) {}; publicQueue(CDLList::iterator b, CDLList::iterator e) : CDLList(b, e) {}; virtual ~publicQueue() { release(); }; virtual unsigned getSize() { return CDLList::getSize(); }; virtual iterator begin() { return CDLList::begin(); }; virtual iterator end() { return CDLList::end(); }; virtual bool empty() { return CDLList::empty(); }; virtual void release() { return CDLList::release(); }; virtual void push(T& element) { return CDLList::push_back(element); }; T pop() { return CDLList::pop_front(); }; void print(ostream& sout); void push_front(T & datum) { throw methodNotSupported(); }; T pop_front() { throw methodNotSupported(); }; void push_back(T & datum) { throw methodNotSupported(); }; T pop_back() { throw methodNotSupported(); }; T& front() const { throw methodNotSupported(); }; T& back() const { throw methodNotSupported(); }; }; //-------------------------------------------------- // Function: void Queue::print(ostream& sout) // // Description: prints a queue // // Programmer: // // Date: 5/19/2017 // Version: 1.0 // Called by: main() // // output: outputs queue to ostream reference // // Parameters: ostream& sout // // History Log: // 5/19/2017 TR completed v1 //-------------------------------------------------- template void publicQueue::print(ostream& sout) { sout << ""(""; iterator it = begin(); while (it != end()) { sout << *it << "", ""; it++; } if (end() != nullptr) sout << *it; sout << "")""; } } #endif ",qsize 363,"#include ""string_util.h"" #include void string_util::vector2str(const std::vector& vec, std::string& desc, const std::string& seq) { if (vec.size() <= 0) return; auto iter = vec.begin(); if (iter != vec.end()) { desc.append(*iter); ++iter; } while (iter != vec.end()) { desc.append(seq); desc.append(*iter); ++iter; } } void string_util::split(const std::string& text, const std::string& seq, std::vector& desc) { if (text.size() == 0) return; size_t [MASK] = seq.size(); size_t text_s = text.size(); size_t start = 0; std::string tmp; while (start < text_s) { size_t pos = text.find_first_of(seq, start); if (pos != std::string::npos) { tmp = text.substr(start, pos - start); if (!tmp.empty()) { desc.push_back(tmp); } start = pos + [MASK] ; } else { break; } } if (start < text_s) { tmp = text.substr(start); if (!tmp.empty()) { desc.push_back(tmp); } } return; } std::string string_util::trim(const std::string& src, const char seq) { if (src.empty()) return src; std::string tmp = src; size_t len = tmp.size(), pos = 0; for (size_t i = 0; i < len; i++) { if (seq == src[i]) pos += 1; else { break; } } if (pos > 0) { tmp.erase(0, pos); } pos = 0; len = tmp.size(); int i = int(len - 1); for (; i >= 0; i--) { if (seq == src[i]) { pos += 1; } else { break; } } if (pos > 0) { tmp.erase(len - pos); } return tmp; } int string_util::parse_char(const char *str) { if (str == NULL) { return 0; } unsigned char p = (unsigned char)(*str); int n = 0; while (p & 0x80) { ++n; p = p << 1; } if (n == 0) { ++n; } else if (n > 4) { n = 1; } return n; } int string_util::punct_process(const std::string &raw_str, std::string &norm_str, const std::string &replacer) { if (raw_str.empty()) { return -1; } norm_str.clear(); char *p = (char *)raw_str.c_str(); size_t offset = 0; int len = 0; while (*p) { len = parse_char(p); if (len == 1) { if (ispunct(*p)) { norm_str += replacer; } else { norm_str.push_back(*p); } } else if (len > 1) { std::string c = raw_str.substr(offset, len); if (is_cn_punct(c)) { norm_str += replacer; } else { norm_str += c; } } p += len; offset += len; } norm_str = trim(norm_str); return 0; } bool string_util::is_cn_punct(const std::string &word) { if (word.empty()) { return false; } if (CN_PUNCS.find(word) != CN_PUNCS.end()) { return true; } else { return false; } } ",seq_s 364,"#include #include class Gdx { // Emscripten webidl don't support binding methods without a class so we need to create a wrapper public: static void* g2d_get_pixels(const gdx2d_pixmap* pixmap) { return (void*)pixmap->pixels; } static gdx2d_pixmap* g2d_load(void * void_buffer, int offset, uint32_t len) { unsigned char *buffer = static_cast(void_buffer); return gdx2d_load(buffer + offset, len); } static gdx2d_pixmap* g2d_new(uint32_t width, uint32_t height, uint32_t format) { return gdx2d_new(width, height, format); } static void g2d_free(const gdx2d_pixmap* pixmap) { gdx2d_free(pixmap); } static void g2d_set_blend(gdx2d_pixmap* pixmap, uint32_t blend) { gdx2d_set_blend(pixmap, blend); } static void g2d_set_scale(gdx2d_pixmap* pixmap, uint32_t scale) { gdx2d_set_scale(pixmap, scale); } static const char* g2d_get_failure_reason() { return gdx2d_get_failure_reason(); } static void g2d_clear(const gdx2d_pixmap* pixmap, uint32_t col) { gdx2d_clear(pixmap, col); } static void g2d_set_pixel(const gdx2d_pixmap* pixmap, int32_t x, int32_t y, uint32_t col) { gdx2d_set_pixel(pixmap, x, y, col); } static uint32_t g2d_get_pixel(const gdx2d_pixmap* pixmap, int32_t x, int32_t y) { return gdx2d_get_pixel(pixmap, x, y); } static void g2d_draw_line(const gdx2d_pixmap* pixmap, int32_t x, int32_t y, int32_t x2, int32_t y2, uint32_t col) { gdx2d_draw_line(pixmap, x, y, x2, y2, col); } static void g2d_draw_rect(const gdx2d_pixmap* pixmap, int32_t x, int32_t y, uint32_t width, uint32_t height, uint32_t col) { gdx2d_draw_rect(pixmap, x, y, width, height, col); } static void g2d_draw_circle(const gdx2d_pixmap* pixmap, int32_t x, int32_t y, uint32_t radius, uint32_t col) { gdx2d_draw_circle(pixmap, x, y, radius, col); } static void g2d_fill_rect(const gdx2d_pixmap* pixmap, int32_t x, int32_t y, uint32_t width, uint32_t height, uint32_t col) { gdx2d_fill_rect(pixmap, x, y, width, height, col); } static void g2d_fill_circle(const gdx2d_pixmap* pixmap, int32_t x, int32_t y, uint32_t radius, uint32_t col) { gdx2d_fill_circle(pixmap, x, y, radius, col); } static void g2d_fill_triangle(const gdx2d_pixmap* pixmap, int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, uint32_t col) { gdx2d_fill_triangle(pixmap, x1, y1, x2, y2, x3, y3, col); } static void g2d_draw_pixmap(const gdx2d_pixmap* src_pixmap, const gdx2d_pixmap* dst_pixmap, int32_t src_x, int32_t src_y, uint32_t [MASK] , uint32_t src_height, int32_t dst_x, int32_t dst_y, uint32_t dst_width, uint32_t dst_height) { gdx2d_draw_pixmap(src_pixmap, dst_pixmap, src_x, src_y, [MASK] , src_height, dst_x, dst_y, dst_width, dst_height); } static uint32_t g2d_bytes_per_pixel(uint32_t format) { return gdx2d_bytes_per_pixel(format); } };",src_width 365,"// Implementation of the acquisition module. It uses the ADC/DMA // interrupts to process the ADC sampling. // TODO: convert const naming style to kCammelCase. #include ""acquisition.h"" #include #include #include ""filters.h"" #include ""hal/adc.h"" #include ""hal/dma.h"" #include ""hal/gpio.h"" namespace acquisition { // Updated by sample_state(). This is the frozen copy of the // state the UI can use. static State sampled_state; // 12 bit -> 4096 counts. 3.3V full scale. // 0.4V per AMP (for +/- 2.5A sensor). constexpr float kCountsPerAmp = 0.4 * 4096 / 3.3; // We use this value to do multiplications instead of divisions. constexpr float kAmpsPerCount = 1 / kCountsPerAmp; constexpr float kMilliampsPerCount = 1000 / kCountsPerAmp; // Energized/non-energized histeresis limits in ADC // counts. // // TODO: specify here what the limits are as a percentage // of full current scale. // constexpr uint16_t kNonEnergizedThresholdCounts = 50; constexpr uint16_t kEnergizedThresholdCounts = 150; // Hysteresis for determining quadrant transitions. In // milliamps and in ADC counts. // constexpr int kQuadrantHisteresisMilliamps = 100; // constexpr int kQuadrantHysteresisCounts = // (kQuadrantHisteresisMilliamps * kCountsPerAmp) / 1000; // Precompute signed histeresize for transition from the // current quadrant q = [0, 2, 3, 3]. // static constexpr int quadrant_v1_histeresis[] = { // (kQuadrantHysteresisCounts / 2), (-kQuadrantHysteresisCounts / 2), // (kQuadrantHysteresisCounts / 2), (-kQuadrantHysteresisCounts / 2)}; // Allowed range for adc zero current offset setting. // This range is wider than needed and actual offsets // are expected to be around 1900. constexpr int kMinOffset = 0; constexpr int kMaxOffset = 4095; // 12 bits max enum CaptureState { // Filling half of the capture buffer. CAPTURE_HALF_FILL, // Keep filling in a circular way until a trigger event // or wait for trigger timeout. CAPTURE_PRE_TRIGGER, // Keep capture points as long as the capture buffer is not full. CAPTURE_POST_TRIGER, // Not capturing. ISR is guaranteed not to update or access the // capture buffer. CAPTURE_IDLE, }; // This data is accessed from interrupt and thus should // be access from main() with IRQ disabled. struct IsrData { // The state visible to users. State state; // Current settings. Settings settings; // Signal capturing. // Time out for waiting for trigger in divided ADC ticks. uint32_t capture_pre_trigger_items_left = 0; // Factor to divide ADC ticks. Only every n'th sample is captured. uint16_t capture_divider = 1; // Up counter for capturing only every n'th samples. uint16_t capture_divider_counter = 0; // Capturing state. CaptureState capture_state = CAPTURE_IDLE; // The capture buffer itself. Updated by ISR when state != CAPTURE_IDLE // and accessible by the UI (ready only) when state = CAPTURE_IDLE. CaptureBuffer capture_buffer; }; static IsrData isr_data; extern bool is_capture_ready() { CaptureState capture_state; __disable_irq(); { capture_state = isr_data.capture_state; } __enable_irq(); return capture_state == CAPTURE_IDLE; } extern void start_capture(uint16_t divider) { // Force a reasonable range. if (divider < 1) { divider = 1; } else if (divider > 1000) { divider = 1000; } // Since capture may be active, data can co-access by ISR. __disable_irq(); { isr_data.capture_buffer.items.clear(); isr_data.capture_buffer.trigger_found = false; // This is an arbitrary number of divided samples that we allow // to wait for a trigger event. isr_data.capture_pre_trigger_items_left = 500; isr_data.capture_divider = divider; isr_data.capture_divider_counter = 0; isr_data.capture_state = CAPTURE_HALF_FILL; } __enable_irq(); } // Users are expected to read this buffer only when capturing // is not active. const CaptureBuffer* capture_buffer() { return &isr_data.capture_buffer; } const State* sample_state() { __disable_irq(); sampled_state = isr_data.state; __enable_irq(); return &sampled_state; } void reset_state() { __disable_irq(); { isr_data.state.tick_count = 0; isr_data.state.non_energized_count = 0; isr_data.state.full_steps = 0; isr_data.state.max_full_steps = 0; isr_data.state.max_retraction_steps = 0; isr_data.state.quadrature_errors = 0; memset(isr_data.state.buckets, 0, sizeof(isr_data.state.buckets)); } __enable_irq(); } int adc_value_to_milliamps(int adc_value) { return (int)(adc_value * kMilliampsPerCount); } float adc_value_to_amps(int adc_value) { return ((float)adc_value) * kAmpsPerCount; } void calibrate_zeros() { __disable_irq(); { isr_data.settings.offset1 += isr_data.state.v1; isr_data.settings.offset2 += isr_data.state.v2; } __enable_irq(); } void set_direction(bool reverse_direction) { __disable_irq(); { isr_data.settings.reverse_direction = reverse_direction; } __enable_irq(); } void get_settings(Settings* settings) { __disable_irq(); { *settings = isr_data.settings; } __enable_irq(); } void dump_sampled_state() { // Remember last tick count and report only diff. static uint32_t last_tick_count = 0; Serial.printf( ""[%lu][er:%lu] [%5d, %5d] [en:%d %lu] s:%d/%d steps:%d max_steps:%d\n"", sampled_state.tick_count - last_tick_count, sampled_state.quadrature_errors, sampled_state.v1, sampled_state.v2, sampled_state.is_energized, sampled_state.non_energized_count, sampled_state.quadrant, sampled_state.last_step_direction, sampled_state.full_steps, sampled_state.max_full_steps); last_tick_count = sampled_state.tick_count; for (int i = 0; i < acquisition::kNumHistogramBuckets; i++) { Serial.print(sampled_state.buckets[i].total_ticks_in_steps); Serial.print("" ""); } Serial.println(); Serial.println(""...""); for (int i = 0; i < acquisition::kNumHistogramBuckets; i++) { const uint32_t avg_peak_current = sampled_state.buckets[i].total_steps ? (sampled_state.buckets[i].total_step_peak_currents / sampled_state.buckets[i].total_steps) : 0; Serial.print(avg_peak_current); Serial.print("" ""); } Serial.println(); } // Assumes that capture data is ready. void dump_capture(const CaptureBuffer& buffer) { for (int i = 0; i < buffer.items.size(); i++) { const acquisition::CaptureItem* item = buffer.items.get(i); // TODO: convert to Serial.printf(). Serial.print(-15); Serial.print(' '); Serial.print(item->v1); Serial.print(' '); Serial.print(item->v2); Serial.print(' '); Serial.println(15); } } // Maybe add step's information to the histogram. // Called from isr on step transition. inline void isr_add_step_to_histogram(int quadrant, Direction entry_direction, Direction exit_direction, uint32_t ticks_in_step, uint32_t max_current_in_step) { // Ignoring this step if not entering and exiting this step in same forward or // backward direction. if (entry_direction != exit_direction || entry_direction == UNKNOWN_DIRECTION) { return; } uint32_t steps_per_sec = TicksPerSecond / ticks_in_step; // speed in steps per second if (steps_per_sec < 10) { return; // ignore very slow steps as they dominate the time. } uint32_t [MASK] = steps_per_sec / kBucketStepsPerSecond; if ( [MASK] >= kNumHistogramBuckets) { [MASK] = kNumHistogramBuckets - 1; } HistogramBucket& bucket = isr_data.state.buckets[ [MASK] ]; bucket.total_ticks_in_steps += ticks_in_step; bucket.total_step_peak_currents += max_current_in_step; bucket.total_steps++; } // A helper for the isr function. static inline void isr_update_full_steps_counter(int increment) { State& isr_state = isr_data.state; // alias // Update step counter based on direction setting. if (isr_data.settings.reverse_direction) { isr_state.full_steps -= increment; } else { isr_state.full_steps += increment; } // Track retraction. if (isr_state.full_steps > isr_state.max_full_steps) { isr_state.max_full_steps = isr_state.full_steps; } const int retraction_steps = isr_state.max_full_steps - isr_state.full_steps; if (retraction_steps > isr_state.max_retraction_steps) { isr_state.max_retraction_steps = retraction_steps; } } // NOTE: these four filters slow the interrupt handling. Consider // to eliminate if free CPU time is insufficient. // // We use these filters to reduce internal and external noise. static filters::Adc12BitsLowPassFilter<700> signal1_filter; static filters::Adc12BitsLowPassFilter<400> signal2_filter; // Slow filter, for display purposes. // static filters::Adc12BitsLowPassFilter<1023> display1_filter; // static filters::Adc12BitsLowPassFilter<1023> display2_filter; // This function performs the bulk of the IRQ processing. It accepts // one pair of ADC1, ADC2 readings, analyzes it, and updates the // state. void isr_handle_one_sample(const uint16_t raw_v1, const uint16_t raw_v2) { isr_data.state.tick_count++; // Fast filtering for signal analysis. const int16_t v1 = (uint16_t)signal1_filter.update(raw_v1) - isr_data.settings.offset1; const int16_t v2 = (uint16_t)signal2_filter.update(raw_v2) - isr_data.settings.offset2; // Slower filtering for display purposes. isr_data.state.v1 = v1; // (uint16_t)display1_filter.update(raw_v1) - isr_data.settings.offset1; isr_data.state.v2 = v2; // (uint16_t)display2_filter.update(raw_v2) - isr_data.settings.offset2; // Handle signal capturing. // Release: 220ns, Debug: 1100ns. (TODO: update timing for current code) if (isr_data.capture_state != CAPTURE_IDLE && ++isr_data.capture_divider_counter >= isr_data.capture_divider) { isr_data.capture_divider_counter = 0; // Insert sample to circular buffer. If the buffer is full it drops // the oldest item. CaptureItem* capture_item = isr_data.capture_buffer.items.insert(); capture_item->v1 = v1; capture_item->v2 = v2; switch (isr_data.capture_state) { // In this sate we blindly fill half of the buffer. case CAPTURE_HALF_FILL: if (isr_data.capture_buffer.items.size() >= kCaptureBufferSize / 2) { isr_data.capture_state = CAPTURE_PRE_TRIGGER; } break; // In this state we look for a trigger event or a pre trigger timeout. case CAPTURE_PRE_TRIGGER: { // Pre trigger timeout? if (isr_data.capture_pre_trigger_items_left == 0) { // NOTE: if the buffer is full here we could terminate // the capture but we go through the normal motions for simplicity. isr_data.capture_state = CAPTURE_POST_TRIGER; isr_data.capture_buffer.trigger_found = false; break; } isr_data.capture_pre_trigger_items_left--; // Trigger event? const int16_t old_v1 = isr_data.capture_buffer.items.get_reversed(5)->v1; // Trigger criteria, up crossing of the zero line. if (old_v1 < -10 && v1 >= 0) { // Keep only the last n/2 points. This way the trigger will // always be in the middle of the buffer. isr_data.capture_buffer.items.keep_at_most(kCaptureBufferSize / 2); isr_data.capture_buffer.trigger_found = true; isr_data.capture_state = CAPTURE_POST_TRIGER; } } break; // In this state we blindly fill the rest of the buffer. case CAPTURE_POST_TRIGER: if (isr_data.capture_buffer.items.is_full()) { isr_data.capture_state = CAPTURE_IDLE; } break; // This one is non reachable but makes the compiler happy. case CAPTURE_IDLE: break; } } // Determine if motor is energized. Use hysteresis for noise rejection. // Release: 200ns. Debug: 600ns. const bool old_is_energized = isr_data.state.is_energized; const uint16_t total_current = abs(v1) + abs(v2); // Using histeresis. const uint16_t energized_threshold = old_is_energized ? kNonEnergizedThresholdCounts : kEnergizedThresholdCounts; const bool new_is_energized = total_current > energized_threshold; isr_data.state.is_energized = new_is_energized; // Handle the non energized case. No need to go through quadrant decoding. // Pass through case: Release: 110ns. Debug: 250ns. if (!new_is_energized) { if (old_is_energized) { // Becoming non energized. isr_data.state.last_step_direction = UNKNOWN_DIRECTION; isr_data.state.ticks_in_step = 0; isr_data.state.non_energized_count++; } else { // Staying non energized } return; } // Here when energized. Decode quadrant. // We now go through a decision tree to collect the new quadrant, sector // and max coil current. Optimized for speed. See quadrants_plot.png // for the individual cases. uint8_t new_quadrant; // set below to [0, 3] uint32_t max_current; // max coil current if (v2 >= 0) { if (v1 >= 0) { // Quadrant 0: v1 > 0, V2 > 0. new_quadrant = 0; if (v1 > v2) { // Sector 0: v1 > 0, V2 > 0. |v1| > |v2| max_current = v1; } else { // Sector 1: v1 > 0, V2 > 0. |v1| < |v2| max_current = v2; } } else { // Quadrant 1: v1 < 0, V2 > 0 new_quadrant = 1; if (-v1 < v2) { // Sector 2: v1 < 0, V2 > 0. |v1| < |v2| max_current = v2; } else { // Sector 3: v1 < 0, V2 > 0. |v1| > |v2| max_current = -v1; } } } else { if (v1 < 0) { // Quadrant 2: v1 < 0, V2 < 0 new_quadrant = 2; if (-v1 > -v2) { // Sector 4: v1 < 0, V2 < 0. |v1| > |v2| max_current = -v1; } else { // Sector 5: v1 < 0, V2 < 0. |v1| < |v2| max_current = -v2; } } else { // Quadrant 3 v1 > 0, V2 < 0. new_quadrant = 3; if (v1 < -v2) { // Sector 6: v1 > 1, V2 < 0. |v1| < |v2| max_current = -v2; } else { // Sector 7: v1 > 0, V2 < 0. |v1| > |v2| max_current = v1; } } } const int8_t old_quadrant = isr_data.state.quadrant; // old quadrant [0, 3] isr_data.state.quadrant = new_quadrant; // Track quadrant transitions and update steps. if (!old_is_energized) { // Case 1: motor just became energized. Direction is still not known. isr_data.state.last_step_direction = UNKNOWN_DIRECTION; isr_data.state.ticks_in_step = 1; isr_data.state.max_current_in_step = max_current; } else if (new_quadrant == old_quadrant) { // Case 2: staying in same quadrant isr_data.state.ticks_in_step++; if (max_current > isr_data.state.max_current_in_step) { isr_data.state.max_current_in_step = max_current; } } else if (new_quadrant == ((old_quadrant + 1) & 0x03)) { // Case 3: Moved to next quadrant. isr_update_full_steps_counter(+1); isr_add_step_to_histogram(old_quadrant, isr_data.state.last_step_direction, FORWARD, isr_data.state.ticks_in_step, isr_data.state.max_current_in_step); isr_data.state.last_step_direction = FORWARD; isr_data.state.ticks_in_step = 1; isr_data.state.max_current_in_step = max_current; } else if (new_quadrant == ((old_quadrant - 1) & 0x03)) { // Case 4: Moved to previous quadrant. isr_update_full_steps_counter(-1); isr_add_step_to_histogram(old_quadrant, isr_data.state.last_step_direction, BACKWARD, isr_data.state.ticks_in_step, isr_data.state.max_current_in_step); isr_data.state.last_step_direction = BACKWARD; isr_data.state.ticks_in_step = 1; isr_data.state.max_current_in_step = max_current; } else { // Case 5: Invalid quadrant transition. // TODO: count and report errors. isr_data.state.quadrature_errors++; isr_data.state.last_step_direction = UNKNOWN_DIRECTION; isr_data.state.ticks_in_step = 1; isr_data.state.max_current_in_step = max_current; } } // Handle the first or second ADC/DMA buffer with collected // samples. void isr_handle_dma_buffer(const dma::AdcPoint* bfr, int n) { for (int i = 0; i < n; i++) { LED2_ON; const dma::AdcPoint& adc_point = bfr[i]; isr_handle_one_sample(adc_point.v1, adc_point.v2); LED2_OFF; } } // HAL interrupt handler for the ADC/DMA 'half' completion. // We process the data in buffer 1. extern ""C"" void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc) { isr_handle_dma_buffer(dma::kDmaAdcPointBuffer1, dma::kDmaAdcPointBufferSize); } // HAL interrupt handler for the ADC/DMA 'full' completion. // We process the data in buffer 2. extern ""C"" void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) { isr_handle_dma_buffer(dma::kDmaAdcPointBuffer2, dma::kDmaAdcPointBufferSize); } // Force a valid settings offset value. static int clip_offset(int requested_offset) { return max(kMinOffset, min(kMaxOffset, requested_offset)); } // Call once on program initialization. void setup(const Settings& settings) { isr_data.settings = settings; isr_data.settings.offset1 = clip_offset(isr_data.settings.offset1); isr_data.settings.offset2 = clip_offset(isr_data.settings.offset2); } // This involves floating point operations and thus slow. Do not // call from the interrupt routine. double state_steps(const State& state) { // If not energized, we can't compute fractional steps. if (!state.is_energized) { return state.full_steps; } // Compute fractional stept. We use the abs() to avoid // the discontinuity near -180 degrees. It provides better safety with // the non determinism of floating point values. // Range is in [0, PI]; const double abs_radians = abs(atan2(state.v2, state.v1)); // Rel radians in [-PI/4, PI/4]. double rel_radians = 0; switch (state.quadrant) { case 0: rel_radians = abs_radians - (PI / 4); break; case 1: rel_radians = abs_radians - (3 * PI / 4); break; case 2: rel_radians = (3 * PI / 4) - abs_radians; break; case 3: rel_radians = (PI / 4) - abs_radians; break; } // Fraction is in the range [-0.5, 0.5] const double fraction = rel_radians * (2 / PI); // NOTE: this is a little bit hacky since we don't know the direction // flag setting at the time this sample was captured but should // be good enough for now. // // TODO: record last direction flag value in the state. const double result = isr_data.settings.reverse_direction ? state.full_steps - fraction : state.full_steps + fraction; // Serial.printf(""%d, %hu, (%hd, %hd), %d, "", state.full_steps, // state.quadrant, // state.v1, state.v2, isr_data.settings.reverse_direction); // Serial.print(abs_radians); // Serial.print("", ""); // Serial.print(rel_radians); // Serial.print("", ""); // Serial.println(fraction); return result; } } // namespace acquisition ",bucket_index 366,"#include #include #include #include /* 1. Set up your firebase project, enable authentication through Google 2. Create a Oauth2.0-Client-ID in developers console and copy Client-ID and Client-Secret into this sketch. 3. Replace """" in this URL with your client_id and open it in your browser: https://accounts.google.com/o/oauth2/auth?redirect_uri=https://localhost&response_type=code&client_id=&scope=https://www.googleapis.com/auth/firebase.database+https://www.googleapis.com/auth/userinfo.email&approval_prompt=force&access_type=offline 4. Log-in/select with the Google User you would like to authorize. 5. Copy the code after ""?code="" from the URL of your browser into this sketch. (without the # at the end) This code works only once, if you try to use it in Oauthplayground or somewhere else it wont work here anymore. (open URL again and get new code if you used it already) 4. Run the sketch. 5. Save all data printed to Serial, it is the access_token and the refresh_token you will need. */ #define WIFI_SSID ""ssid"" #define WIFI_PASSWORD """" String client_id = """"; //enter your Oauth2 account client id String client_secret = """"; //enter your Oauth2 account client secret String code = """"; //enter the code you recieved in the browser url field (only code, without beginning https://... or &code=...) String message = ""redirect_uri=https://localhost&client_id="" + client_id + ""&client_secret="" + client_secret + ""&code="" + code + ""&grant_type=authorization_code""; WiFiClientSecure client; void connectWifi(){ Serial.print(""Connecting to ""); Serial.println(WIFI_SSID); WiFi.mode(WIFI_STA); if(WiFi.status() != WL_CONNECTED){ WiFi.begin(WIFI_SSID, WIFI_PASSWORD); } while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("".""); } Serial.println(""\nConnected""); Serial.print(""IP Address: ""); Serial.println(WiFi.localIP()); } void setup() { DynamicJsonBuffer jsonBuffer; String response; Serial.begin(9600); delay(5000); connectWifi(); Serial.println(""Starting to redeem token from code...""); if(!client.connect(""accounts.google.com"", 443)){ Serial.println(""Could not connect to accounts.google.com""); } client.print( String(""POST /o/oauth2/token HTTP/1.1\r\n"") + String(""Host: accounts.google.com\r\n"") + String(""Content-Type: application/x-www-form-urlencoded\r\n"") + String(""Content-Length: "" + String(message.length()) + ""\r\n\r\n"") + message ); unsigned long [MASK] = millis(); while(client.available() == 0){ if(millis() - [MASK] > 5000){ client.stop(); Serial.println(""Failed to recieve response after 5 seconds, aborting""); break; } } while(client.available()){ response = client.readString(); int payloadStart = response.indexOf(""\r\n\r\n""); int payloadEnd = response.indexOf(""\r\n\r\n"", payloadStart+1); response = response.substring(payloadStart, payloadEnd); payloadStart = response.indexOf('{'); payloadEnd = response.indexOf('}'); response = response.substring(payloadStart, payloadEnd+1); response.trim(); } JsonObject& responseJson = jsonBuffer.parseObject(response); if(responseJson.containsKey(""error"")){ responseJson.printTo(Serial); } else { Serial.println(""Your Oauth2 token from google:""); Serial.println(""Access Token: "" + responseJson[""access_token""].as()); Serial.println(""Refresh Token: "" + responseJson[""refresh_token""].as()); Serial.println(""Token Type: "" + responseJson[""token_type""].as()); Serial.println(""Expires in (seconds): "" + responseJson[""expires_in""].as()); Serial.println(""ID Token: "" + responseJson[""id_token""].as()); } } void loop() { // nothing to do... } ",sendTime 367,"#include #include #include #include #include #include void setDarkBlueColor() { textcolor(RED); textbackground(BLUE); } void resetColor() { textcolor(RED); textbackground(BLUE); } void displayMenu() { clrscr(); setDarkBlueColor(); cout << ""===| TouchOS CE 4 |===\n""; cout << ""1 - Getting Started\n""; cout << ""2 - Text\n""; cout << ""3 - Clock\n""; cout << ""4 - Echo\n""; cout << ""5 - Changelog\n""; cout << ""6 - Exit\n""; cout << ""Enter an option: ""; resetColor(); } void openGettingStarted() { clrscr(); ifstream inputFile(""D:\\TOUCHOS\\GETTINGSTARTED.TXT""); if (inputFile) { cout << ""Opening Getting Started document...\n""; char data[100]; while (inputFile.getline(data, 100)) { cout << data << ""\n""; } inputFile.close(); } else { cout << ""Error: Unable to open Getting Started document\n""; } getch(); } void displayClock() { clrscr(); time_t now = time(0); tm* ltm = localtime(&now); cout << ""Date: "" << ltm->tm_mday << ""/"" << 1 + ltm->tm_mon << ""/"" << 1900 + ltm->tm_year << ""\n""; cout << ""Time: "" << ltm->tm_hour << "":"" << ltm->tm_min << "":"" << ltm->tm_sec << ""\n""; getch(); } void echoUserInput() { clrscr(); char userInput[100]; cin.ignore(); cout << ""Enter text: ""; cin.getline(userInput, 100); cout << ""ECHO-$ "" << userInput << ""\n""; getch(); } void displayChangelog() { clrscr(); cout << ""***| Changelog |***\n""; cout << ""- Added Getting Started\n""; cout << ""- Improved Text Manager\n""; cout << ""- Red text\n""; cout << ""- More stable build\n""; getch(); } void displayTextMenu() { clrscr(); setDarkBlueColor(); cout << ""***| Text |***\n""; cout << ""1 - Open Document\n""; cout << ""2 - Edit Document\n""; cout << ""3 - List Documents\n""; cout << ""4 - Rename Document\n""; cout << ""5 - Back to Main Menu\n""; cout << ""Enter an option: ""; resetColor(); } void openDocument() { clrscr(); char filename[100]; cout << ""Enter document name: ""; cin >> filename; ifstream inputFile((string(""D:\\TOUCHOS\\TEXT\\"") + filename).c_str()); if (inputFile) { cout << ""Opening document...\n""; char data[100]; while (inputFile.getline(data, 100)) { cout << data << ""\n""; } inputFile.close(); } else { cout << ""Error: Unable to open document\n""; } getch(); } void editDocument() { clrscr(); char filename[100]; cout << ""Enter document name: ""; cin >> filename; ofstream [MASK] ((string(""D:\\TOUCHOS\\TEXT\\"") + filename).c_str(), ios::app); if ( [MASK] ) { char userData[100]; cin.ignore(); cout << ""Enter document contents: ""; cin.getline(userData, 100); [MASK] << userData << ""\n""; cout << ""Saved to document\n""; [MASK] .close(); } else { cout << ""Error: Unable to edit document\n""; } getch(); } void listDocuments() { clrscr(); cout << ""Listing documents in D:\\TOUCHOS\\TEXT\\...\n""; system(""dir D:\\TOUCHOS\\TEXT\\ /b""); getch(); } void renameDocument() { clrscr(); char oldName[100], newName[100]; cout << ""Enter current document name: ""; cin >> oldName; cout << ""Enter new document name: ""; cin >> newName; if (rename((string(""D:\\TOUCHOS\\TEXT\\"") + oldName).c_str(), (string(""D:\\TOUCHOS\\TEXT\\"") + newName).c_str()) == 0) { cout << ""Document renamed successfully\n""; } else { cout << ""Error: Unable to rename document\n""; } getch(); } int main() { int choice; do { displayMenu(); cin >> choice; switch (choice) { case 1: openGettingStarted(); break; case 2: int textChoice; do { displayTextMenu(); cin >> textChoice; switch (textChoice) { case 1: openDocument(); break; case 2: editDocument(); break; case 3: listDocuments(); break; case 4: renameDocument(); break; case 5: break; default: cout << ""Invalid choice. Please try again.\n""; getch(); } } while (textChoice != 5); break; case 3: displayClock(); break; case 4: echoUserInput(); break; case 5: displayChangelog(); break; case 6: cout << ""Exiting TouchOS CE...\n""; break; default: cout << ""Invalid choice. Please try again.\n""; getch(); } } while (choice != 6); return 0; } ",outputFile 368,"#include ""connectdialog.h"" #include ""ui_connectdialog.h"" #include #include ConnectDialog::ConnectDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ConnectDialog) { ui->setupUi(this); QSignalMapper *mapper = new QSignalMapper(this); for(int i=0; i<10; i++){ QPushButton *pBtn = new QPushButton(QString::number(i),this); connect(pBtn, SIGNAL(clicked()), mapper, SLOT(map())); mapper->setMapping(pBtn, pBtn->text()); ui->gridLayout_2->addWidget(pBtn,i,0); } QPushButton *pBtn = new QPushButton(""."",this); connect(pBtn, SIGNAL(clicked()), mapper, SLOT(map())); mapper->setMapping(pBtn, pBtn->text()); ui->gridLayout_2->addWidget(pBtn,10,0); connect(mapper,SIGNAL(mapped(QString)),this,SLOT(appendtext(QString))); } ConnectDialog::~ConnectDialog() { delete ui; } void ConnectDialog::on_YesBtn_clicked(){ QString IP = ui->IPLineEdit->text(); this->close(); emit sendData(IP); } void ConnectDialog::on_RedoBtn_clicked(){ ui->IPLineEdit->clear(); } void ConnectDialog::appendtext(QString a){ QString [MASK] = ui->IPLineEdit->text()+a; ui->IPLineEdit->setText( [MASK] ); repaint(); } ",temp 369,"#include ""encoder_funcs.hpp"" #include namespace enc_f { // Teensy has its own version of pi in its libraries. // const int PI = numbers::pi_v; /** * @brief Get ticks elapsed from an encoder read * * @param e Encoder object to read * @param d Time to read encoder * @return long number of ticks per CPU cycle */ long get_ticks(Encoder& e, int d = 0) { e.write(0); delay(d); return e.read(); } /** * @brief Report speed of encoder (in in/s) * * @param e Encoder object to report * @param d Time taken to read encoder (ms) * @return float */ int get_speed_inch(Encoder& e, int d = 50) { long ticks = get_ticks(e,d); int [MASK] = floor( ((float) ticks / d) * (float) (25/3) * 1.49606 * PI); return [MASK] ; } /** * @brief Report speed of encoder (in mm/s) * * @param e Encoder object * @param d Time taken to read encoder (in ms) * @return float */ int get_speed_mm(Encoder& e, int d = 50) { long ticks = get_ticks(e,d); int mm_speed = floor( ((float) ticks / d) * (float) (25/3) * 38.0 * PI); return mm_speed; } } // enc_f namespace ",in_speed 370,"// // Created by zheng on 2020/4/8. // #include #include #include #include #include #include #include #include #include ""SocketClient.h"" #define SA struct sockaddr SocketClient::SocketClient(char *addr, int port) { int ret; strncpy(this->addr, addr, 99); this->port=port; msg_size = 0; ret = this->connect_to_server(); } int SocketClient::connect_to_server() { struct sockaddr_in [MASK] ; // socket create and varification sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { printf(""socket creation failed...\n""); return -1; } else printf(""Socket successfully created..\n""); bzero(& [MASK] , sizeof( [MASK] )); // assign IP, PORT [MASK] .sin_family = AF_INET; [MASK] .sin_addr.s_addr = inet_addr(addr); [MASK] .sin_port = htons(port); // connect_to_server the client socket to server socket if (::connect(sockfd, (SA *) & [MASK] , sizeof( [MASK] )) != 0) { printf(""connection with the server failed...\n""); return -1; } else printf(""connected to the server..\n""); return 0; } int SocketClient::send() { assert(msg_size>0); ssize_t ret = write(sockfd, buf, msg_size); if (ret(buf + sizeof(Header)); header.rank = rank, header.begin = begin, header.end = end; int cnt_key=0, cnt_value=0; for (const auto &kv:graph_calc) { // buffer size limit if (sizeof(Header) + sizeof(SGraphKey) * (cnt_key + 1) + sizeof(SGraphValue) * (cnt_value + kv.second.size()) >= MAXBUFSIZ) { // fprintf(stderr, ""Send buf truncated. c_k=%d c_v=%d\n"", cnt_key, // cnt_value); break; } sGraphKey[cnt_key].first = kv.first.first; sGraphKey[cnt_key].second = kv.first.second; sGraphKey[cnt_key].num=kv.second.size(); cnt_key++; cnt_value+=kv.second.size(); } int i_key=0; auto *sDataType = reinterpret_cast(buf + sizeof(Header) + sizeof(SGraphKey) * cnt_key); header.n_keys = cnt_key; this->msg_size = header.msg_size = sizeof(Header) + sizeof(SGraphKey) * cnt_key + sizeof(SGraphValue) * cnt_value; memcpy(buf, &header, sizeof(Header)); for (const auto &kv:graph_calc) { if (i_key >= cnt_key) { // fprintf(stderr, ""Warning: exceed buf %d/%d\n"", i_key, cnt_key); break; } memcpy(sDataType, kv.second.data(), sizeof(DataType) * kv.second.size()); sDataType += kv.second.size(); i_key++; } // fprintf(stderr, ""Msgsize=%d Header rk=%d nkeys=%d nval=%d\n"", // this->msg_size, header.rank, header.n_keys, cnt_value); return 0; } //void SGraphValue::load_from_DataType(const DataType &dataType) //{ // this->timestamp=dataType.timestamp; // this->elapsed=dataType.elapsed; //} ",servaddr 371,"#pragma once #include #include #include #include #include #include #include #include ""Logger.h"" #include ""Utility.h"" #include ""Signature.h"" namespace _gem { class File { public: File(std::filesystem::path path, std::string source) : path(getRelativePath(path, source)), name(path.stem().string()), extension(path.extension().string()) { /* namespace sf = std::filesystem; sf::path dir = std::filesystem::path(Configuration::getSourceDirectory()); std::string fileName = sf::relative(dir, path).replace_extension("""").string(); */ std::ifstream file(path); std::ostringstream ss; ss << file.rdbuf(); content = ss.str(); file.close(); Logger::log(Logger::GEM, ""Loading file: "", path.string()); std::unordered_set duplicateChecker; std::regex macroRegex(""%%\\[([a-zA-Z][a-zA-Z0-9_/-]*):?([a-zA-Z][a-zA-Z0-9_.-]*)?\\]""); std::smatch macroMatches; std::string toSearchMacro = content; //Get all macros while (std::regex_search(toSearchMacro, macroMatches, macroRegex)) { auto pair = duplicateChecker.emplace(macroMatches[1].str()); macros.emplace_back(macroMatches[0].str()); if (!pair.second) { Logger::log(Logger::GEM, ""Macro: "" + macroMatches[1].str() + "" duplicate found in file: "" + path.string(), ""...""); } toSearchMacro = macroMatches.suffix().str(); } if (duplicateChecker.size() == 0) { processFile(); } duplicateChecker.clear(); std::regex includeRegex(""##\\[([a-zA-Z][a-zA-Z0-9_/-]*):?([a-zA-Z][a-zA-Z0-9_.-]*)?\\]""); std::smatch includeMatches; std::string [MASK] = content; //Get all includes while (std::regex_search( [MASK] , includeMatches, includeRegex)) { auto pair = duplicateChecker.emplace(includeMatches[0].str()); includes.emplace_back(includeMatches[0].str()); if (!pair.second) { Logger::log(Logger::GEM, ""Include: "" + includeMatches[1].str() + "" duplicate found in file: "" + path.string(), ""...""); } [MASK] = includeMatches.suffix().str(); } } template size_t processFile(Args... args) { std::vector arguments({ castToString(args)... }); std::string processedContent = content; for (size_t i = 0; i < macros.size(); i++) { processedContent = std::regex_replace(processedContent, sanitizeForRegex(macros[i].signature), arguments[i]); } processedContents.emplace_back(processedContent); return processedContents.size() - 1; } std::string content; std::string path; std::string name; std::string extension; std::vector macros; std::vector includes; std::vector processedContents; }; }",toSearchInclude 372,"/* * @lc app=leetcode id=119 lang=cpp * * [119] Pascal's Triangle II * * https://leetcode.com/problems/pascals-triangle-ii/description/ * * algorithms * Easy (48.78%) * Likes: 987 * Dislikes: 201 * Total Accepted: 316.3K * Total Submissions: 626.2K * Testcase Example: '3' * * Given a non-negative index k where k ≤ 33, return the k^th index row of the * Pascal's triangle. * * Note that the row index starts from 0. * * * In Pascal's triangle, each number is the sum of the two numbers directly * above it. * * Example: * * * Input: 3 * Output: [1,3,3,1] * * * Follow up: * * Could you optimize your algorithm to use only O(k) extra space? * */ // @lc code=start #include class Solution { public: std::vector getRow(int [MASK] ) { std::vector row; for (int i = 0; i <= [MASK] ; i++) { std::vector nextRow(i + 1, 1); for (int j = 1; j < nextRow.size() - 1; j++) { nextRow[j] = row[j - 1] + row[j]; } row = nextRow; } return row; } }; // @lc code=end ",rowIndex 373,"#include #include #include #include #include #include #include #include bool g_continue = true; int sighandler(int [MASK] ) { (void) [MASK] ; g_continue = false; return 1; } void fatal(const char* msg) { perror(msg); exit(EXIT_FAILURE); } int main() { while(1){ int listener = socket(AF_INET, SOCK_STREAM, 0); if (listener == -1) fatal(""socket""); struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons(8080) }; addr.sin_addr.s_addr = INADDR_ANY; if (bind(listener, (struct sockaddr*)&addr, sizeof(struct sockaddr_in)) < 0) fatal(""bind""); if (listen(listener, SOMAXCONN) < 0) fatal(""listen""); printf(""Listening on %s:%d\n"", inet_ntoa(addr.sin_addr), 8080); struct sockaddr_in client_name; socklen_t client_len = sizeof(struct sockaddr_in); int client = accept(listener, (struct sockaddr*)&client_name, &client_len); if (client == -1) fatal(""accept""); printf(""Received connection from %s\n"", inet_ntoa(client_name.sin_addr)); char buffer[8192] = {0}; while (g_continue) { int bytes = read(client, buffer, sizeof(buffer)); if (bytes < 0) fatal(""read""); else if (bytes == 0) break ; buffer[bytes] = '\0'; printf(""Received message: %s\n"", buffer); write(client, buffer, bytes); } close(client); close(listener);} return 0; }",signum 374,"#pragma once #ifdef _WIN32 #include ""Core/Platform/Windows/WindowsHandles.h"" #include ""Core/Graphics/GraphicsRenderer.h"" #include ""DX12_Handles.h"" #include #ifdef new #pragma push_macro(""new"") #undef new #endif #pragma warning( push ) #pragma warning( disable : 4244 ) // conversion from 'wchar_t' to 'char', possible loss of data #pragma warning( disable : 5204 ) // class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly #pragma warning( disable : 4265 ) // class has virtual functions, but its non-trivial destructor is not virtual; instances of this class may not be destructed correctly #pragma warning( disable : 6387 ) // could be '0' does not adhere to the specification for the function #pragma warning( disable : 4365 ) // conversion from 'LONG' to 'UINT', signed/unsigned mismatch // controls whether all the display information is displayed or not // #define VERBOSE_DISPLAY_INFO namespace ATGE { using Microsoft::WRL::ComPtr; bool GraphicsRenderer::initGraphics(const void* pPlatform) { Logger::debug(""Starting DirectX12...\n""); DXHandles* handles = new DXHandles(); this->m_pGraphicsHandles = handles; #pragma region InitDirect3D HRESULT result; #pragma region Enable the D3D12 debug layer. #ifdef _DEBUG { ComPtr debugController; result = D3D12GetDebugInterface(IID_PPV_ARGS(&debugController)); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to get DebugInterface.\n""); debugController->EnableDebugLayer(); } #endif #pragma endregion #pragma region Try to create hardware device. result = CreateDXGIFactory1(IID_PPV_ARGS(&handles->m_dxgiFactory)); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to create DXGI Factory.\n""); result = D3D12CreateDevice( nullptr, // default adapter D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&handles->m_d3dDevice)); // Fallback to WARP device. if (FAILED(result)) { ComPtr pWarpAdapter; result = handles->m_dxgiFactory->EnumWarpAdapter(IID_PPV_ARGS(&pWarpAdapter)); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to init Adapter.\n""); result = D3D12CreateDevice( pWarpAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&handles->m_d3dDevice)); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to init dx Device.\n""); } #pragma endregion #pragma region Create Fence result = handles->m_d3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&handles->m_Fence)); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to create fence.\n""); handles->m_RtvDescriptorSize = handles->m_d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); handles->m_DsvDescriptorSize = handles->m_d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); handles->m_CbvSrvUavDescriptorSize = handles->m_d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); #pragma endregion #pragma region Check 4X MSAA quality support for our back buffer format. // Check 4X MSAA quality support for our back buffer format. // All Direct3D 11 capable devices support 4X MSAA for all render // target formats, so we only need to check quality support. D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS msQualityLevels; msQualityLevels.Format = handles->m_BackBufferFormat; msQualityLevels.SampleCount = 4; msQualityLevels.Flags = D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE; msQualityLevels.NumQualityLevels = 0; result = handles->m_d3dDevice->CheckFeatureSupport( D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &msQualityLevels, sizeof(msQualityLevels)); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to check feature support""); handles->m_4xMsaaQuality = msQualityLevels.NumQualityLevels; ATGE_ASSERT_MSG(handles->m_4xMsaaQuality > 0, ""Unexpected MSAA quality level.""); #pragma endregion #pragma region Log Adapters #ifdef _DEBUG std::vector adapterList; { UINT i = 0; IDXGIAdapter* adapter = nullptr; while (handles->m_dxgiFactory->EnumAdapters(i, &adapter) != DXGI_ERROR_NOT_FOUND) { DXGI_ADAPTER_DESC desc; adapter->GetDesc(&desc); std::wstring wText = L""***Adapter: ""; wText += desc.Description; wText += L""\n""; std::string text = std::string(wText.begin(), wText.end()); Logger::log(LogLevel::LEVEL_DEBUG, text.c_str()); adapterList.push_back(adapter); ++i; } } for (const auto& adapter : adapterList) { { UINT i = 0; IDXGIOutput* output = nullptr; while (adapter->EnumOutputs(i, &output) != DXGI_ERROR_NOT_FOUND) { DXGI_OUTPUT_DESC desc; output->GetDesc(&desc); // log device name { std::wstring wText = L""***Output: ""; wText += desc.DeviceName; wText += L""\n""; std::string text = std::string(wText.begin(), wText.end()); Logger::log(LogLevel::LEVEL_DEBUG, text.c_str()); } #ifdef VERBOSE_DISPLAY_INFO { UINT count = 0; UINT flags = 0; // Call with nullptr to get list count. output->GetDisplayModeList(handles->m_BackBufferFormat, flags, &count, nullptr); std::vector modeList(count); output->GetDisplayModeList(handles->m_BackBufferFormat, flags, &count, &modeList[0]); for (auto& x : modeList) { UINT n = x.RefreshRate.Numerator; UINT d = x.RefreshRate.Denominator; std::wstring wText = L""Width = "" + std::to_wstring(x.Width) + L"" "" + L""Height = "" + std::to_wstring(x.Height) + L"" "" + L""Refresh = "" + std::to_wstring(n) + L""/"" + std::to_wstring(d) + L""\n""; std::string text = std::string(wText.begin(), wText.end()); Logger::log(LogLevel::LEVEL_DEBUG, text.c_str()); } } #endif output->Release(); i++; } } adapter->Release(); } #endif #pragma endregion #pragma region Create Command Objects D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; result = handles->m_d3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&handles->m_CommandQueue)); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to create command queue""); result = handles->m_d3dDevice->CreateCommandAllocator( D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(handles->m_DirectCmdListAlloc.GetAddressOf())); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to create command allocator""); result = handles->m_d3dDevice->CreateCommandList( 0, D3D12_COMMAND_LIST_TYPE_DIRECT, handles->m_DirectCmdListAlloc.Get(), // Associated command allocator nullptr, // Initial PipelineStateObject IID_PPV_ARGS(handles->m_CommandList.GetAddressOf())); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to create command list""); // Start off in a closed state. This is because the first time we refer // to the command list we will Reset it, and it needs to be closed before // calling Reset. handles->m_CommandList->Close(); #pragma endregion #pragma region Create Swap Chain // Release the previous swapchain we will be recreating. handles->m_SwapChain.Reset(); DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = handles->m_ClientWidth; sd.BufferDesc.Height = handles->m_ClientHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = handles->m_BackBufferFormat; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; sd.SampleDesc.Count = handles->m_4xMsaaState ? 4u : 1u; sd.SampleDesc.Quality = handles->m_4xMsaaState ? (handles->m_4xMsaaQuality - 1) : 0; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = DXHandles::SwapChainBufferCount; sd.OutputWindow = ((PS_WindowsState*)pPlatform)->hwnd; sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // Note: Swap chain uses queue to perform flush. result = handles->m_dxgiFactory->CreateSwapChain( handles->m_CommandQueue.Get(), &sd, handles->m_SwapChain.GetAddressOf()); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to create swap chain""); #pragma endregion #pragma region Create Rtv And Dsv Descriptor Heaps D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc; rtvHeapDesc.NumDescriptors = DXHandles::SwapChainBufferCount; rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; rtvHeapDesc.NodeMask = 0; result = handles->m_d3dDevice->CreateDescriptorHeap( &rtvHeapDesc, IID_PPV_ARGS(handles->m_RtvHeap.GetAddressOf())); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to create rtv descriptor heap""); D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc; dsvHeapDesc.NumDescriptors = 1; dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV; dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; dsvHeapDesc.NodeMask = 0; result = handles->m_d3dDevice->CreateDescriptorHeap( &dsvHeapDesc, IID_PPV_ARGS(handles->m_DsvHeap.GetAddressOf())); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to create dsv descriptor heap""); #pragma endregion #pragma endregion this->onResize(); Logger::debug(""DirectX12 Initialized!!\n""); return true; } void GraphicsRenderer::shutdown() { if (((DXHandles*)this->m_pGraphicsHandles)->m_d3dDevice != nullptr) this->flush(); delete this->m_pGraphicsHandles; Logger::debug(""DirectX12 Successfully Shutdown!!\n""); } void GraphicsRenderer::renderFrame() { DXHandles* handles = static_cast(m_pGraphicsHandles); HRESULT result = S_OK; // Reset the command allocator. result = handles->m_DirectCmdListAlloc->Reset(); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to reset command allocator.""); // Reset the command list; no initial pipeline state object. result = handles->m_CommandList->Reset(handles->m_DirectCmdListAlloc.Get(), nullptr); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to reset command list.""); // Set the viewport and scissor rectangle. handles->m_CommandList->RSSetViewports(1, &handles->m_ScreenViewport); handles->m_CommandList->RSSetScissorRects(1, &handles->m_ScissorRect); // Get the current back buffer resource. ID3D12Resource* currBackBuffer = handles->m_SwapChainBuffer[handles->m_CurrBackBuffer].Get(); // Transition the back buffer from PRESENT to RENDER_TARGET. auto barrier = CD3DX12_RESOURCE_BARRIER::Transition( currBackBuffer, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); handles->m_CommandList->ResourceBarrier(1, &barrier); // Obtain the current render target view handle. CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(handles->m_RtvHeap->GetCPUDescriptorHandleForHeapStart()); rtvHandle.Offset(handles->m_CurrBackBuffer, handles->m_RtvDescriptorSize); // Clear the render target view with a solid background color. const float clearColor[4] = { 0.69f, 0.77f, 0.87f, 1.0f }; // LightSteelBlue. handles->m_CommandList->ClearRenderTargetView(rtvHandle, clearColor, 0, nullptr); // Clear the depth/stencil view. handles->m_CommandList->ClearDepthStencilView( handles->m_DsvHeap->GetCPUDescriptorHandleForHeapStart(), D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr); // Set the render target. auto [MASK] = handles->m_DsvHeap->GetCPUDescriptorHandleForHeapStart(); handles->m_CommandList->OMSetRenderTargets(1, &rtvHandle, true, & [MASK] ); // [Mesh rendering code would normally go here, but it is omitted for now.] // Transition the back buffer from RENDER_TARGET back to PRESENT. barrier = CD3DX12_RESOURCE_BARRIER::Transition( currBackBuffer, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); handles->m_CommandList->ResourceBarrier(1, &barrier); // Close the command list. result = handles->m_CommandList->Close(); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to close command list.""); // Execute the command list. ID3D12CommandList* cmdLists[] = { handles->m_CommandList.Get() }; handles->m_CommandQueue->ExecuteCommandLists(_countof(cmdLists), cmdLists); // Present the swap chain. result = handles->m_SwapChain->Present(0, 0); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to present swap chain.""); // Update the current back buffer index. handles->m_CurrBackBuffer = (handles->m_CurrBackBuffer + 1) % DXHandles::SwapChainBufferCount; // Wait until frame commands are complete. this->flush(); } void GraphicsRenderer::onResize() { // Retrieve our DX12 handles. DXHandles* handles = static_cast(m_pGraphicsHandles); ATGE_ASSERT_MSG(handles->m_d3dDevice, ""DirectX device not initialized.""); ATGE_ASSERT_MSG(handles->m_SwapChain, ""Swap chain not initialized.""); ATGE_ASSERT_MSG(handles->m_DirectCmdListAlloc, ""Command allocator not initialized.""); // Flush the GPU queue before changing any resources. this->flush(); HRESULT result = S_OK; // Reset the command list to prepare for resource changes. result = handles->m_CommandList->Reset(handles->m_DirectCmdListAlloc.Get(), nullptr); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to reset command list.""); // Release previous render target resources. for (auto& buff : handles->m_SwapChainBuffer) { buff.Reset(); } handles->m_DepthStencilBuffer.Reset(); // Resize the swap chain buffers. result = handles->m_SwapChain->ResizeBuffers( DXHandles::SwapChainBufferCount, handles->m_ClientWidth, handles->m_ClientHeight, handles->m_BackBufferFormat, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to resize swap chain buffers.""); handles->m_CurrBackBuffer = 0; // Recreate render target views. CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHeapHandle(handles->m_RtvHeap->GetCPUDescriptorHandleForHeapStart()); for (UINT i = 0; i < DXHandles::SwapChainBufferCount; i++) { result = handles->m_SwapChain->GetBuffer(i, IID_PPV_ARGS(&handles->m_SwapChainBuffer[i])); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to get swap chain buffer.""); handles->m_d3dDevice->CreateRenderTargetView(handles->m_SwapChainBuffer[i].Get(), nullptr, rtvHeapHandle); rtvHeapHandle.Offset(1, handles->m_RtvDescriptorSize); } // Set up the depth/stencil buffer description. D3D12_RESOURCE_DESC depthStencilDesc = {}; depthStencilDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; depthStencilDesc.Alignment = 0; depthStencilDesc.Width = handles->m_ClientWidth; depthStencilDesc.Height = handles->m_ClientHeight; depthStencilDesc.DepthOrArraySize = 1; depthStencilDesc.MipLevels = 1; // Use a typeless format so that both SRV and DSV can be created. depthStencilDesc.Format = DXGI_FORMAT_R24G8_TYPELESS; depthStencilDesc.SampleDesc.Count = handles->m_4xMsaaState ? 4 : 1; depthStencilDesc.SampleDesc.Quality = handles->m_4xMsaaState ? (handles->m_4xMsaaQuality - 1) : 0; depthStencilDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; depthStencilDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; // Set the clear value. D3D12_CLEAR_VALUE optClear = {}; optClear.Format = handles->m_DepthStencilFormat; optClear.DepthStencil.Depth = 1.0f; optClear.DepthStencil.Stencil = 0; CD3DX12_HEAP_PROPERTIES heapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT); // Create the depth/stencil buffer resource. result = handles->m_d3dDevice->CreateCommittedResource( &heapProperties, D3D12_HEAP_FLAG_NONE, &depthStencilDesc, D3D12_RESOURCE_STATE_COMMON, &optClear, IID_PPV_ARGS(handles->m_DepthStencilBuffer.GetAddressOf())); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to create depth/stencil buffer resource.""); // Create the depth/stencil view. D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {}; dsvDesc.Flags = D3D12_DSV_FLAG_NONE; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; dsvDesc.Format = handles->m_DepthStencilFormat; dsvDesc.Texture2D.MipSlice = 0; handles->m_d3dDevice->CreateDepthStencilView( handles->m_DepthStencilBuffer.Get(), &dsvDesc, handles->m_DsvHeap->GetCPUDescriptorHandleForHeapStart()); auto barrier = CD3DX12_RESOURCE_BARRIER::Transition(handles->m_DepthStencilBuffer.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE); // Transition the depth/stencil buffer to a writable state. handles->m_CommandList->ResourceBarrier(1, &barrier); // Close the command list and execute the resize commands. result = handles->m_CommandList->Close(); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to close command list.""); ID3D12CommandList* cmdLists[] = { handles->m_CommandList.Get() }; handles->m_CommandQueue->ExecuteCommandLists(_countof(cmdLists), cmdLists); // Wait until the GPU has completed the resize operations. this->flush(); // Update the viewport and scissor rectangle to match the new window size. handles->m_ScreenViewport.TopLeftX = 0; handles->m_ScreenViewport.TopLeftY = 0; handles->m_ScreenViewport.Width = static_cast(handles->m_ClientWidth); handles->m_ScreenViewport.Height = static_cast(handles->m_ClientHeight); handles->m_ScreenViewport.MinDepth = 0.0f; handles->m_ScreenViewport.MaxDepth = 1.0f; handles->m_ScissorRect = { 0, 0, static_cast(handles->m_ClientWidth), static_cast(handles->m_ClientHeight) }; } void GraphicsRenderer::flush() { DXHandles* handles = static_cast(m_pGraphicsHandles); HRESULT result = S_OK; // Advance the fence value to mark commands up to this fence point. handles->m_CurrentFence++; // Signal the command queue with the new fence value. result = handles->m_CommandQueue->Signal(handles->m_Fence.Get(), handles->m_CurrentFence); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to signal fence.""); // If the GPU hasn't finished processing commands up to this fence point, wait. if (handles->m_Fence->GetCompletedValue() < handles->m_CurrentFence) { HANDLE eventHandle = CreateEventEx(nullptr, 0, 0, EVENT_ALL_ACCESS); result = handles->m_Fence->SetEventOnCompletion(handles->m_CurrentFence, eventHandle); ATGE_ASSERT_MSG(SUCCEEDED(result), ""Failed to set event on fence completion.""); // Wait until the GPU has completed processing. WaitForSingleObject(eventHandle, INFINITE); CloseHandle(eventHandle); } } } #pragma warning( pop ) #endif",cpuDesc 375,"//Written by and //Created on January 16 at 9:40am PST //This program has a handful of fun short games to play #include #include #include #include #include #include #include #include #include #include using namespace std; //vector to store hangman pictographs const vector hangmanPics = {""\n +---+\n |\n |\n |\n ==="", ""\n +---+\n O |\n |\n |\n ==="", ""\n +---+\n O |\n | |\n |\n ==="", ""\n +---+\n O |\n /| |\n |\n ==="", ""\n +---+\n O |\n /|\\ |\n |\n ==="", ""\n +---+\n O |\n /|\\ |\n / |\n ==="", ""\n +---+\n O |\n /|\\ |\n / \\ |\n ===""}; //structure for saving team information struct teamInfo_t { string teamName = """"; int totalWins = 0; }; //function to get the teams in the game vector getTeamNames() { int [MASK] = 0; while (true) { cout << ""How many teams will be playing today? ""; cin >> [MASK] ; //check to make sure only integers are used if (cin.fail()) { cin.clear(); cin.ignore(); cout << ""Enter a valid number! \n""; } else { break; } } cout << ""Very cool! We have got "" << [MASK] << "" playing today!\nNow how about we get some names?""; //create vector to store teams vector teamList = {}; for (int i = 1; i <= [MASK] ; i++) { //as teams are added ask for their names cout << ""\nName for Team "" << i << "": ""; teamInfo_t newTeam; string teamInput = """"; cin >> teamInput; newTeam.teamName = teamInput; teamList.push_back(newTeam); } cout << ""So for review, today our competing teams will be ""; //if only playing one team if ( [MASK] == 1) { cout << ""just you!""; } else { //print for multiple teams for (int i = 0; i < teamList.size(); i++) { if (i == (teamList.size() - 1)) { cout << ""and "" << teamList.at(teamList.size() - 1).teamName << ""!""; } else { cout << teamList.at(i).teamName << "", ""; } } } return teamList; } //function to read the wordlist vector readHangmanWords() { string fileName; cout << (""\n\nPlease give the file name that your word list is stored in: ""); cin >> fileName; ifstream wordlistFile(fileName); //check if the file exists, if it doesn't quit the program if (wordlistFile.fail()) { cout << ""There is no such file. ""; exit(EXIT_FAILURE); } //get the wordlist and format it to be all upper case vector wordlist = {}; string word; while (true) { getline(wordlistFile, word); string upper_word = """"; for (char x : word) { x = toupper(x); upper_word += x; } wordlist.push_back(upper_word); if (wordlistFile.fail()) { break; } } wordlistFile.close(); return wordlist; } //choosing the random word for the hangman string getRandomWord(const vector &wordList) { return wordList.at(rand() % wordList.size()); } //interpreting the inputs of the user char getGuess(vector guesses) { char guess = ' '; while (true) { //prompt the user cout << ""\nGuess a letter: ""; //capitalize the input cin >> guess; guess = toupper(guess); //check if the user is going to guess the entire word if (guess == '!') { cout << ""You must now guess the whole word: ""; return guess; //check if that letter has already been guessed } else if (count(guesses.begin(), guesses.end(), guess)) { cout << ""\nYou have already guessed that letter.""; //check if the input is actually a letter } else if (guess < 65 || guess > 132) { cout << ""\nPlease enter a LETTER.""; } else { //if it passses through everthing return it return guess; } } } void displayHangman(vector badGuesses, vector guesses, string word, bool &gameDone) { //display the hangman picture corresponding to how many incorrect guesses have been made cout << hangmanPics.at(badGuesses.size()); cout << ""\nMissed guesses: ""; //display all the incorrect guesses for (char guess : badGuesses) { cout << guess << "", ""; } cout << '\n'; //display the underlines to show how many letters, but replace them with the letter if it has been guessed for (char letter : word) { if (count(guesses.begin(), guesses.end(), letter)) { cout << letter << ' '; } else if (letter == ' ') { cout << ' '; } else { cout << ""_ ""; } } } bool hangmanRound(vector &wordBank, vector &teams) { //initiate a list for bad guesses and total guesses, including space so the player doesn't have to vector badGuesses = {}; vector guesses = {' '}; //pick a random word from the word bank string word = getRandomWord(wordBank); bool gameDone = false; for (int turn = (rand() % teams.size());; turn++) { //determine the team here int currentTeam = turn % teams.size(); cout << ""\nIt is "" << teams.at(currentTeam).teamName << ""'s turn\n\n""; displayHangman(badGuesses, guesses, word, gameDone); //get the player's guess char guess = getGuess(guesses); guesses.push_back(guess); //! indicates that a player is ready to guess the whole word if (guess == '!') { string wholeWord = """"; cin.ignore(); //getline the answer (including spaces) getline(cin, wholeWord); string upper_word = """"; for (char x : wholeWord) { x = toupper(x); upper_word += x; } //if the word is correct, the game is over if (upper_word == word) { cout << ""Congratulations! The word was "" << word << "".""; cout << "" \nThe winner is "" << teams.at(currentTeam).teamName << ""!\n""; teams.at(currentTeam).totalWins++; return true; } //if the word is not correct, count it as a bad guess and continue else { cout << ""\nNo, "" << upper_word << "" is not correct.\n""; } } //if the guess is not in the word, add it to the list of bad guesses if (!(count(word.begin(), word.end(), guess))) { badGuesses.push_back(guess); } //check if the players have reached the max amount of guesses if (badGuesses.size() == hangmanPics.size()) { cout << ""You are out of guesses! The word was "" << word << "".""; gameDone = true; } //check if all letters are present bool allLetters = true; for (char letter : word) { if (!count(guesses.begin(), guesses.end(), letter)) { allLetters = false; break; } } //if all letters are present, then the game is over if (allLetters) { gameDone = true; displayHangman(badGuesses, guesses, word, gameDone); cout << ""\n\nCongratulations! The word was "" << word; cout << "" \nThe winner is "" << teams.at(currentTeam).teamName << ""!\n""; teams.at(currentTeam).totalWins++; } //return if the game is done if (gameDone) { return true; } } } void playHangman() { cout << ""Welcome to Hangman!\nYou may supply your own vocabulary by putting words (no punctuation) in a .txt file.\nIf you are ready to guess the whole word, press enter !""; //initiate and fill the word bank vector wordBank = {}; wordBank = readHangmanWords(); //get team names vector teams = getTeamNames(); //play hangman infinitely until the players stop while (hangmanRound(wordBank, teams)) { cout << ""\nScoreboard\n----------\n""; //display scores for (teamInfo_t team : teams) { cout << team.teamName << "": "" << team.totalWins << ""\n""; } //prompt them to play again, quit if their answer doesn't start with y cout << ""Type yes if you would like to play again: ""; string answer = "" ""; cin >> answer; if (!(answer.at(0) == 'y' || answer.at(0) == 'Y')) { break; } //ask them to reselect a category wordBank = readHangmanWords(); } } int main() { //seed the random and start the game srand(time(nullptr)); playHangman(); }",numberOfTeams 376,"// // Created by   on 22.10.2024. // #include #include #include ""magma.hpp"" using namespace std; int main(int argc, const char *argv[]) { ifstream envs(""../.env""); if (!envs.is_open()) { cout << ""Error opening envs file"" << endl; } auto *key_name = new char[4]; auto *key = new uint32_t[8]; envs.read(key_name, 4); envs.read(reinterpret_cast(key), sizeof(key)*4); envs.close(); Magma alg(key); cout << ""ENCRYPT"" << endl; ifstream inputfile(""../input.txt"", ios::binary); ofstream outputfile(""../encrypt.txt"", ios::binary); if (inputfile.is_open() && outputfile.is_open()) { auto *line = new uint32_t[2]; uint32_t init_vec[2] {0xffff, 0xffff}; while ( inputfile.read(reinterpret_cast(&line[0]), sizeof(line[0])) && inputfile.read(reinterpret_cast(&line[1]), sizeof(line[0])) ) { cout << ""INP LINE "" << line[0] << "" "" << line[1] << endl; line[0] ^= init_vec[0]; line[1] ^= init_vec[1]; alg.encrypt_block(line); cout << ""ENC LINE "" << line[0] << "" "" << line[1] << endl; init_vec[0] = line[0]; init_vec[1] = line[1]; outputfile.write(reinterpret_cast(&line[0]), sizeof(line[0])); outputfile.write(reinterpret_cast(&line[1]), sizeof(line[0])); } inputfile.close(); outputfile.close(); delete[] line; } cout << ""DECRYPT"" << endl; ifstream enc_file(""../encrypt.txt"", ios::binary); ofstream [MASK] (""../decrypt.txt"", ios::binary); if (enc_file.is_open() && [MASK] .is_open()) { auto *line = new uint32_t[2]; uint32_t init_vec[2] {0xffff, 0xffff}; uint32_t cbc_vec[2]; while ( enc_file.read(reinterpret_cast(&line[0]), sizeof(line[0])) && enc_file.read(reinterpret_cast(&line[1]), sizeof(line[0])) ) { cout << ""ENC LINE "" << line[0] << "" "" << line[1] << endl; cbc_vec[0] = line[0]; cbc_vec[1] = line[1]; alg.decrypt_block(line); line[0] ^= init_vec[0]; line[1] ^= init_vec[1]; init_vec[0] = cbc_vec[0]; init_vec[1] = cbc_vec[1]; cout << ""DEC LINE "" << line[0] << "" "" << line[1] << endl; [MASK] .write(reinterpret_cast(&line[0]), sizeof(line[0])); [MASK] .write(reinterpret_cast(&line[1]), sizeof(line[0])); } delete[] line; enc_file.close(); [MASK] .close(); } delete[] key; return 0; }",dec_file 377,"#include ""ContentBrowserPanel.h"" #include ""Mirage/Definitions/FileExtensions.h"" #include ""Mirage/Definitions/DragnDropPayloads.h"" #include ""Mirage/Definitions/Icons.h"" #include ""ImGui/imgui.h"" #include ""ImGui/imgui_internal.h"" #include ""Mirage/Core/Log.h"" #include ""Mirage/Core/Time.h"" #include ""Mirage/ImGui/Extensions/DrawingAPI.h"" #include ""Mirage/ImGui/Extensions/Splitter.h"" namespace Mirage { // TODO: Change when Project is implemented static const std::filesystem::path s_AssetsPath = ""Assets""; static Timer s_BrowserUpdateTimer; static Timer s_HierarchyUpdateTimer; static float s_BrowserUpdateInterval = 1.0f; ContentBrowserPanel::ContentBrowserPanel() : m_CurrentDirectory(s_AssetsPath) { MarkUpdateContents(); m_DirectoryIcon = Texture2D::Create(Icons::Folder); m_FileIcon = Texture2D::Create(Icons::File); m_MirageIcon = Texture2D::Create(Icons::Mirage); } void ContentBrowserPanel::OnImGuiRender() { if(ImGui::Begin(""Content Browser"", nullptr, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { if (!exists(m_CurrentDirectory)) { m_CurrentDirectory = s_AssetsPath; MarkUpdateContents(); } UpdateBrowser(); DrawHeader(); m_RightPanelSize = ImGui::GetContentRegionAvail().x - m_LeftPanelSize - m_SeparatorThickness; ImGui::DrawSplitter(0, m_SeparatorThickness, &m_LeftPanelSize, &m_RightPanelSize, 50.0f, 100.0f); DrawDirectoryHierarchy(); ImGui::SameLine(); DrawContents(); DrawStatusBar(); ImGui::End(); } else { ImGui::End(); } } void ContentBrowserPanel::DrawHeader() { bool backward = !m_BackWardNavigation.empty(); bool forward = !m_ForwardNavigation.empty(); ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 12.0f); if (!backward) { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.3f); } if (ImGui::Button(""<<"", ImVec2{0.0f, 25.0f}) || ImGui::IsMouseClicked(3)) { NavigateBackward(); } if (!backward) { ImGui::PopItemFlag(); ImGui::PopStyleVar(); } ImGui::SameLine(); if (!forward) { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.3f); } if (ImGui::Button("">>"", ImVec2{0.0f, 25.0f}) || ImGui::IsMouseClicked(4)) { NavigateForward(); } if (!forward) { ImGui::PopItemFlag(); ImGui::PopStyleVar(); } ImGui::PopStyleVar(); ImGui::SameLine(); static char* pathBuf = new char[512]; static bool pathBufDirty = false; strcpy_s(pathBuf, 512, m_CurrentDirectory.string().c_str()); ImGui::PushItemWidth(-1); pathBufDirty |= ImGui::InputText(""##PathHeader"", pathBuf, 512); ImGui::PopItemWidth(); if (pathBufDirty && !ImGui::IsItemActive()) { std::filesystem::path newPath = pathBuf; if (std::filesystem::exists(newPath)) { pathBufDirty = false; NavigateTo(pathBuf); } } } void ContentBrowserPanel::DrawDirectoryHierarchy() { ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4{0.12f, 0.12f, 0.12f, 1.0f}); ImGui::BeginChild(""VerticalView"", ImVec2{m_LeftPanelSize, -1}, false, ImGuiWindowFlags_HorizontalScrollbar); DrawDirectoryNode(s_AssetsPath, ""Assets""); ImGui::EndChild(); ImGui::PopStyleColor(); } void ContentBrowserPanel::DrawContents() { ImGui::BeginGroup(); auto& style = ImGui::GetStyle(); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{0.0f, 0.0f, 0.0f, 0.0f}); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2{m_itemSpacing, style.ItemSpacing.y}); ImGui::BeginChild(""ContentView"", ImVec2{ m_RightPanelSize, ImGui::GetContentRegionAvail().y - ImGui::GetFrameHeight() - style.WindowPadding.y * 2.0f }, false); if (ImGui::IsMouseClicked(0) && ImGui::IsWindowHovered()) m_SelectedPath = m_CurrentDirectory; float cellSize = m_thumbnailSize + (style.ItemSpacing.x + style.FramePadding.x) * 2.0f; float panelWidth = ImGui::GetContentRegionAvail().x; int [MASK] = (int)(panelWidth / cellSize); if ( [MASK] < 1) [MASK] = 1; ImGui::Columns( [MASK] , 0, false); int id= 0; for (auto& path : m_Entries) { ImGui::PushID(id++); float cellStartX = ImGui::GetCursorPosX(); float cellWidth = ImGui::GetColumnWidth(); ImGui::SetCursorPosX( cellStartX + (cellWidth - style.FramePadding.x * 2.0f - m_thumbnailSize - style.ItemSpacing.x * 2.0f) / 2); bool isSelected = m_SelectedPath == path; if (isSelected) { ImGui::PushStyleColor(ImGuiCol_Button, m_SelectedBGColor); } if (is_directory(path)) { ImGui::ImageButton((ImTextureID)m_DirectoryIcon->GetRendererID(), {(float)m_thumbnailSize, (float)m_thumbnailSize}, {0, 1}, {1, 0}, -1, ImVec4{0.0f, 0.0f, 0.0f, 0.0f}, m_DirectoryTintColor); if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { NavigateTo(path); } } else { ImGui::ImageButton((ImTextureID)SetIcon(path)->GetRendererID(), {(float)m_thumbnailSize, (float)m_thumbnailSize}, {0, 1}, {1, 0}, -1, ImVec4{0.0f, 0.0f, 0.0f, 0.0f}, m_FileTintColor); if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { MRG_CORE_WARN(""double clicked file""); OnFileDoubleClick(path); } } if (isSelected) { ImGui::PopStyleColor(); } if (ImGui::IsItemClicked()) { m_SelectedPath = path; } if (ImGui::BeginDragDropSource()) { SetPayload(); ImGui::BeginTooltip(); SetTooltip(); ImGui::EndTooltip(); ImGui::EndDragDropSource(); } std::string fName = path.filename().string(); float textSize = ImGui::CalcTextSize(fName.c_str()).x; float textZoneWidth = cellWidth - style.ItemSpacing.x * 2.0f; ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + cellWidth - style.ItemSpacing.x); if (textSize < textZoneWidth) { ImGui::SetCursorPosX(cellStartX + (textZoneWidth - textSize) / 2); } else { ImGui::SetCursorPosX(cellStartX - m_itemSpacing + style.ItemSpacing.x / 2); } if (ImGui::IsItemHovered()) { ImGui::SetTooltip(fName.c_str()); } // Set text max width to cell width - item spacing ImGui::Text(fName.c_str()); ImGui::PopTextWrapPos(); if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { // TODO: Rename } ImGui::PopID(); ImGui::NextColumn(); } ImGui::Columns(1); ImGui::PopStyleVar(1); ImGui::PopStyleColor(); ImGui::EndChild(); } void ContentBrowserPanel::DrawStatusBar() { auto& style = ImGui::GetStyle(); float settingsWidth = ImGui::CalcTextSize(""Thumbnail size: "").x + ImGui::CalcTextSize(""Padding: "").x + ImGui::GetStyle().ItemSpacing.x * 5.0f + 240.0f; float pathWidth = ImGui::GetContentRegionAvail().x - settingsWidth; ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4{0.12f, 0.12f, 0.12f, 1.0f}); ImGui::BeginChild(""StatusSelectedPath"", ImVec2{pathWidth, -1}, false, ImGuiWindowFlags_HorizontalScrollbar); ImGui::SetCursorPos(ImVec2{style.WindowPadding.x, style.WindowPadding.y}); ImGui::Text(m_SelectedPath.string().c_str()); ImGui::EndChild(); ImGui::PopStyleColor(); ImGui::SameLine(); ImGui::SetCursorPos(ImVec2{ ImGui::GetCursorPosX() + style.ItemSpacing.x, ImGui::GetCursorPosY() + style.WindowPadding.y }); ImGui::BeginGroup(); ImGui::AlignTextToFramePadding(); ImGui::Text(""Thumbnail size: ""); ImGui::SameLine(); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + style.WindowPadding.y); ImGui::PushItemWidth(120); ImGui::SliderInt(""##Thumbnail Size"", &m_thumbnailSize, 16, 512); ImGui::PopItemWidth(); ImGui::SameLine(); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + style.WindowPadding.y); ImGui::Text(""Padding: ""); ImGui::SameLine(); ImGui::PushItemWidth(120); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + style.WindowPadding.y); ImGui::SliderFloat(""##Padding"", &m_itemSpacing, 0, 32); ImGui::PopItemWidth(); ImGui::EndGroup(); ImGui::EndGroup(); } Ref ContentBrowserPanel::SetIcon(std::filesystem::path path) { if (path.extension().string() == Extensions::scene) { return m_MirageIcon; } return m_FileIcon; } void ContentBrowserPanel::DrawDirectoryNode(std::filesystem::path path, const char* filename) { if (is_directory(path)) { ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_OpenOnArrow; bool opened = ImGui::TreeNodeEx(filename, flags); if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) { m_SelectedPath = path; NavigateTo(path); } if (opened) { if (ImGui::IsItemToggledOpen()) { MarkUpdateTree(); } // std::vector vec = m_BrowseCache[ImGui::GetID(filename)]; std::vector vec = Browse(path); for (auto& p : vec) { std::string fStr = p.filename().string(); DrawDirectoryNode(p, fStr.c_str()); } ImGui::TreePop(); } } } void ContentBrowserPanel::UpdateBrowser() { if (s_BrowserUpdateTimer.Elapsed() < s_BrowserUpdateInterval && !m_MarkUpdateContents) { return; } unsigned int dirs = 0; m_Entries.clear(); for (auto& directoryEntry : std::filesystem::directory_iterator(m_CurrentDirectory)) { const auto& path = directoryEntry.path(); if (directoryEntry.is_directory()) { m_Entries.emplace(m_Entries.begin() + dirs++, path); } else { m_Entries.emplace_back(path); } } m_MarkUpdateContents = false; s_BrowserUpdateTimer.Reset(); } std::vector ContentBrowserPanel::Browse(const std::filesystem::path& path) { if (s_HierarchyUpdateTimer.Elapsed() < s_BrowserUpdateInterval && !m_MarkUpdateTree) { return m_BrowseCache[ImGui::GetID(path.filename().string().c_str())]; } std::vector result; for (auto& directoryEntry : std::filesystem::directory_iterator(path)) { const auto& p = directoryEntry.path(); if (directoryEntry.is_directory()) result.emplace_back(p); } m_BrowseCache[ImGui::GetID(path.filename().string().c_str())] = result; s_HierarchyUpdateTimer.Reset(); m_MarkUpdateTree = false; return result; } void ContentBrowserPanel::NavigateTo(const std::filesystem::path& path) { if (m_CurrentDirectory == path) return; m_BackWardNavigation.emplace(m_CurrentDirectory); m_ForwardNavigation = std::stack(); if (is_directory(path)) { m_CurrentDirectory = path; } else { std::filesystem::path dir = path.parent_path(); m_CurrentDirectory = dir; } m_SelectedPath = path; MarkUpdateContents(); } void ContentBrowserPanel::NavigateBackward() { if (ImGui::IsAnyItemActive()) { ImGui::ClearActiveID(); } if (!m_BackWardNavigation.empty()) { m_ForwardNavigation.emplace(m_CurrentDirectory); m_CurrentDirectory = m_BackWardNavigation.top(); m_SelectedPath = m_CurrentDirectory; m_BackWardNavigation.pop(); MarkUpdateContents(); } } void ContentBrowserPanel::NavigateForward() { if (ImGui::IsAnyItemActive()) { ImGui::ClearActiveID(); } if (!m_ForwardNavigation.empty()) { m_BackWardNavigation.emplace(m_CurrentDirectory); m_CurrentDirectory = m_ForwardNavigation.top(); m_SelectedPath = m_CurrentDirectory; m_ForwardNavigation.pop(); MarkUpdateContents(); } } void ContentBrowserPanel::SetPayload() { std::string itemPath = m_SelectedPath.string(); const std::string extension = m_SelectedPath.extension().string(); if ( extension == Extensions::scene) { ImGui::SetDragDropPayload(Payloads::scene.c_str(), itemPath.c_str(), sizeof(char) * itemPath.size(), ImGuiCond_Once); } if ( extension == Extensions::texture) { ImGui::SetDragDropPayload(Payloads::texture.c_str(), itemPath.c_str(), sizeof(char) * itemPath.size()); } } void ContentBrowserPanel::SetTooltip() { bool isDirectory = is_directory(m_SelectedPath); const std::string extension = m_SelectedPath.extension().string(); ImGui::Text(""Dragging :""); ImGui::Image( (isDirectory ? (ImTextureID)m_DirectoryIcon->GetRendererID() : (ImTextureID)m_FileIcon->GetRendererID()), ImVec2{32, 32}, {0, 1}, {1, 0}, isDirectory ? m_DirectoryTintColor : m_FileTintColor); ImGui::SameLine(); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 16 - ImGui::GetTextLineHeight() / 2); ImGui::Text(""%s"", m_SelectedPath.filename().string().c_str()); } void ContentBrowserPanel::OnFileDoubleClick(std::filesystem::path path) { const std::string extension = path.extension().string(); if (extension == Extensions::scene) { m_RequestedScenePath = path; m_IsSceneRequested = true; } } } ",columnCount 378,"#include #include #include #include #include #include std::pair select_by_index( const torch::Tensor &vertices, const torch::Tensor &triangles, const std::vector &vertex_indices) { std::unordered_map new_vertex_map; std::vector new_vertex_indices; for (size_t i = 0; i < vertex_indices.size(); ++i) { int64_t old_index = vertex_indices[i]; if (new_vertex_map.find(old_index) == new_vertex_map.end()) { int64_t new_index = new_vertex_indices.size(); new_vertex_indices.push_back(old_index); new_vertex_map[old_index] = new_index; } } torch::Tensor new_vertices = vertices.index_select( 0, torch::tensor(new_vertex_indices, torch::kInt64)); std::vector new_triangle_indices; auto triangles_accessor = triangles.accessor(); for (int64_t i = 0; i < triangles.size(0); ++i) { int64_t v0 = triangles_accessor[i][0]; int64_t v1 = triangles_accessor[i][1]; int64_t v2 = triangles_accessor[i][2]; if (new_vertex_map.find(v0) != new_vertex_map.end() && new_vertex_map.find(v1) != new_vertex_map.end() && new_vertex_map.find(v2) != new_vertex_map.end()) { new_triangle_indices.push_back(i); } } torch::Tensor new_triangles = torch::empty({static_cast(new_triangle_indices.size()), 3}, triangles.options()); auto new_triangles_accessor = new_triangles.accessor(); for (size_t i = 0; i < new_triangle_indices.size(); ++i) { int64_t idx = new_triangle_indices[i]; new_triangles_accessor[i][0] = new_vertex_map[triangles_accessor[idx][0]]; new_triangles_accessor[i][1] = new_vertex_map[triangles_accessor[idx][1]]; new_triangles_accessor[i][2] = new_vertex_map[triangles_accessor[idx][2]]; } return std::make_pair(new_vertices, new_triangles); } std::vector> split_mesh_by_cc( const torch::Tensor &vertices, const torch::Tensor &triangles) { AT_ASSERT(vertices.dtype() == torch::kFloat32, ""Vertices must be float32""); AT_ASSERT(triangles.dtype() == torch::kInt64, ""Triangles must be int64""); AT_ASSERT(vertices.dim() == 2 && vertices.size(1) == 3, ""Vertices must have a shape of (N, 3)""); AT_ASSERT(triangles.dim() == 2 && triangles.size(1) == 3, ""Triangles must have a shape of (M, 3)""); // Ensure tensors are on CPU auto cpu_vertices = vertices.to(torch::kCPU); auto [MASK] = triangles.to(torch::kCPU); auto vertices_accessor = cpu_vertices.accessor(); auto triangles_accessor = [MASK] .accessor(); int64_t n_vertices = cpu_vertices.size(0); int64_t n_triangles = [MASK] .size(0); // Build adjacency list std::vector> adjacency(n_vertices); for (int64_t i = 0; i < n_triangles; ++i) { adjacency[triangles_accessor[i][0]].insert(triangles_accessor[i][1]); adjacency[triangles_accessor[i][1]].insert(triangles_accessor[i][2]); adjacency[triangles_accessor[i][2]].insert(triangles_accessor[i][0]); } // Find connected components using BFS std::vector visited(n_vertices, false); std::vector> components; for (int64_t i = 0; i < n_vertices; ++i) { if (!visited[i]) { std::vector component; std::queue queue; queue.push(i); visited[i] = true; while (!queue.empty()) { int64_t v = queue.front(); queue.pop(); component.push_back(v); for (auto adj_v : adjacency[v]) { if (!visited[adj_v]) { queue.push(adj_v); visited[adj_v] = true; } } } components.push_back(component); } } // Split meshes std::vector> split_meshes; for (const auto &comp : components) { auto split_mesh = select_by_index(cpu_vertices, [MASK] , comp); split_meshes.push_back(split_mesh); } return split_meshes; } ",cpu_triangles 379,"#include ""AdresatMenedzer.h"" Adresat AdresatMenedzer::podajDaneNowegoAdresata() { Adresat adresat; if (plikZAdresatami.pobierzIdOstatniegoAdresata() == 0 && plikZAdresatami.pobierzIdUsunietegoAdresata() == 0) { adresat.ustawId(1); } else if (plikZAdresatami.pobierzIdUsunietegoAdresata() == plikZAdresatami.pobierzIdOstatniegoAdresata()) { adresat.ustawId(plikZAdresatami.pobierzIdUsunietegoAdresata()); } else { adresat.ustawId(plikZAdresatami.pobierzIdOstatniegoAdresata() + 1); } adresat.ustawIdUzytkownika(ID_ZALOGOWANEGO_UZYTKOWNIKA); cout << ""Podaj imie: ""; adresat.ustawImie(MetodyPomocnicze::wczytajLinie()); adresat.ustawImie(zamienPierwszaLitereNaDuzaAPozostaleNaMale(adresat.pobierzImie())); cout << ""Podaj nazwisko: ""; adresat.ustawNazwisko(MetodyPomocnicze::wczytajLinie()); adresat.ustawNazwisko(zamienPierwszaLitereNaDuzaAPozostaleNaMale(adresat.pobierzNazwisko())); cout << ""Podaj numer telefonu: ""; adresat.ustawNumerTelefonu(MetodyPomocnicze::wczytajLinie()); cout << ""Podaj email: ""; adresat.ustawEmail(MetodyPomocnicze::wczytajLinie()); cout << ""Podaj adres: ""; adresat.ustawAdres(MetodyPomocnicze::wczytajLinie()); return adresat; } void AdresatMenedzer::dodajAdresata() { Adresat adresat; system(""cls""); cout << "" >>> DODAWANIE NOWEGO ADRESATA <<<"" << endl << endl; adresat = podajDaneNowegoAdresata(); adresaci.push_back(adresat); plikZAdresatami.dopiszAdresataDoPliku(adresat); } string AdresatMenedzer::zamienPierwszaLitereNaDuzaAPozostaleNaMale(string [MASK] ) { if (! [MASK] .empty()) { transform( [MASK] .begin(), [MASK] .end(), [MASK] .begin(), ::tolower); [MASK] [0] = toupper( [MASK] [0]); } return [MASK] ; } void AdresatMenedzer::wyswietlWszystkichAdresatow() { system(""cls""); if (!adresaci.empty()) { cout << "" >>> ADRESACI <<<"" << endl; cout << ""-----------------------------------------------"" << endl; for (vector :: iterator itr = adresaci.begin(); itr != adresaci.end(); itr++) { wyswietlDaneAdresata(*itr); } cout << endl; } else { cout << endl << ""Ksiazka adresowa jest pusta."" << endl << endl; } system(""pause""); } void AdresatMenedzer::wyswietlDaneAdresata(Adresat adresat) { cout << endl << ""Id: "" << adresat.pobierzId() << endl; cout << ""Imie: "" << adresat.pobierzImie() << endl; cout << ""Nazwisko: "" << adresat.pobierzNazwisko() << endl; cout << ""Numer telefonu: "" << adresat.pobierzNumerTelefonu() << endl; cout << ""Email: "" << adresat.pobierzEmail() << endl; cout << ""Adres: "" << adresat.pobierzAdres() << endl; } void AdresatMenedzer::wyszukajAdresatowPoImieniu() { string imiePoszukiwanegoAdresata = """"; int iloscAdresatow = 0; system(""cls""); if (!adresaci.empty()) { cout << "">>> WYSZUKIWANIE ADRESATOW O IMIENIU <<<"" << endl << endl; cout << ""Wyszukaj adresatow o imieniu: ""; imiePoszukiwanegoAdresata = MetodyPomocnicze::wczytajLinie(); imiePoszukiwanegoAdresata = zamienPierwszaLitereNaDuzaAPozostaleNaMale(imiePoszukiwanegoAdresata); for (vector ::iterator itr = adresaci.begin(); itr != adresaci.end(); itr++) { if (itr -> Adresat::pobierzImie() == imiePoszukiwanegoAdresata) { wyswietlDaneAdresata(*itr); iloscAdresatow++; } } wyswietlIloscWyszukanychAdresatow(iloscAdresatow); } else { cout << endl << ""Ksiazka adresowa jest pusta"" << endl << endl; } cout << endl; system(""pause""); } void AdresatMenedzer::wyswietlIloscWyszukanychAdresatow(int iloscAdresatow) { if (iloscAdresatow == 0) cout << endl << ""W ksiazce adresowej nie ma adresatow z tymi danymi."" << endl; else cout << endl << ""Ilosc adresatow w ksiazce adresowej wynosi: "" << iloscAdresatow << endl << endl; } void AdresatMenedzer::wyszukajAdresatowPoNazwisku() { string nazwiskoPoszukiwanegoAdresata; int iloscAdresatow = 0; system(""cls""); if (!adresaci.empty()) { cout << "">>> WYSZUKIWANIE ADRESATOW O NAZWISKU <<<"" << endl << endl; cout << ""Wyszukaj adresatow o nazwisku: ""; nazwiskoPoszukiwanegoAdresata = MetodyPomocnicze::wczytajLinie(); nazwiskoPoszukiwanegoAdresata = zamienPierwszaLitereNaDuzaAPozostaleNaMale(nazwiskoPoszukiwanegoAdresata); for (vector ::iterator itr = adresaci.begin(); itr != adresaci.end(); itr++) { if (itr -> Adresat::pobierzNazwisko() == nazwiskoPoszukiwanegoAdresata) { wyswietlDaneAdresata(*itr); iloscAdresatow++; } } wyswietlIloscWyszukanychAdresatow(iloscAdresatow); } else { cout << endl << ""Ksiazka adresowa jest pusta."" << endl << endl; } cout << endl; system(""pause""); } void AdresatMenedzer::usunAdresata() { int idUsuwanegoAdresata = 0, brakZgodnosci = 0, dlugoscWektora = adresaci.size(); string idStr = """"; char wybor; system(""cls""); cout << "" >>> Usun adresata <<<"" << endl << endl; if (dlugoscWektora == 0) { cout << ""Ksiazka adresowa jest pusta!"" << endl << endl; } else { cout << ""Podaj numer identyfikacyjny osoby, ktora chcesz usunac: ""; idStr = MetodyPomocnicze::wczytajLinie(); idUsuwanegoAdresata = MetodyPomocnicze::konwersjaStringNaInt(idStr); for (vector ::iterator itr = adresaci.begin(); itr != adresaci.end(); itr++) { if (itr -> Adresat::pobierzId() == idUsuwanegoAdresata) { wyswietlDaneAdresata(*itr); cout << endl; cout << ""Czy na pewno chcesz usunac dana osobe? [t/n] ""; wybor = MetodyPomocnicze::wczytajZnak(); if (wybor == 't') { adresaci.erase(itr); plikZAdresatami.usunAdresataZPliku(idUsuwanegoAdresata); plikZAdresatami.ustawIdUsunietegoAdresata(idUsuwanegoAdresata); cout << endl << ""Usuwanie danych zakonczone powodzeniem!"" << endl << endl; system(""pause""); break; } else if (wybor == 'n') { cout << endl << ""Wstrzymano usuwanie danych!"" << endl << endl; system(""pause""); break; } else { cout << endl << ""Musisz wpisac tak[t] lub nie[n]!"" << endl << endl; system(""pause""); } } else { brakZgodnosci++; } } if (brakZgodnosci == dlugoscWektora) { cout << endl << ""W ksiazce adresowej nie ma osoby o podanym numerze identyfikacyjnym!"" << endl << endl; system(""pause""); } else if (adresaci.size() == 0) { cout << ""Ksiazka adresowa jest teraz pusta!"" << endl << endl; system(""pause""); } } } void AdresatMenedzer::edytujDaneAdresata() { string idString = """"; int idAdresataDoEdycji, brakZgodnosci = 0, dlugoscWektora = adresaci.size(); char wybor; system(""cls""); cout << "" >>> Edytuj dane adresata <<<"" << endl << endl; if (dlugoscWektora == 0) { cout << ""Ksiazka adresowa jest pusta!"" << endl << endl; system(""pause""); } else { cout << ""Podaj numer identyfikacyjny osoby, ktorej chcesz edytowac dane: ""; idString = MetodyPomocnicze::wczytajLinie(); idAdresataDoEdycji = MetodyPomocnicze::konwersjaStringNaInt(idString); for (vector ::iterator itr = adresaci.begin(); itr != adresaci.end(); itr++) { if (itr -> Adresat::pobierzId() == idAdresataDoEdycji) { wyswietlDaneAdresata(*itr); cout << endl; cout << ""Czy chcesz edytowac dane podanej osoby? [t/n] ""; wybor = MetodyPomocnicze::wczytajZnak(); if (wybor == 't') { wybierzDaneDoEdycji(idAdresataDoEdycji); break; } else if (wybor == 'n') { cout << endl << ""Wstrzymano edycje danych!"" << endl << endl; system(""pause""); break; } else { cout << endl << ""Musisz wpisac tak[t] lub nie[n]!"" << endl << endl; Sleep(1500); } } else { brakZgodnosci++; } } if (brakZgodnosci == dlugoscWektora) { cout << endl << ""W ksiazce adresowej nie ma osoby o podanym numerze identyfikacyjnym!"" << endl << endl; system(""pause""); } } } void AdresatMenedzer::wybierzDaneDoEdycji(int idAdresataDoEdycji) { char wybor; string imie, nazwisko, numerTelefonu, email, adres; vector daneDoEdycji; system (""cls""); cout << "" >>> Edytuj dana adresata <<<"" << endl << endl; cout << ""Wybierz dane do edycji: "" << endl; cout << ""1. Imie"" << endl; cout << ""2. Nazwisko"" << endl; cout << ""3. Numer telefonu"" << endl; cout << ""4. Email"" << endl; cout << ""5. Adres"" << endl; cout << ""6. Powrot do menu"" << endl; cout << endl << ""Twoj wybor: ""; wybor = MetodyPomocnicze::wczytajZnak(); cout << endl; switch (wybor) { case '1': system(""cls""); cout << "" > Imie <"" << endl << endl; for (vector ::iterator itr = adresaci.begin(); itr != adresaci.end(); itr++) { if (itr -> Adresat::pobierzId() == idAdresataDoEdycji) { cout << ""Stare: "" << itr -> Adresat::pobierzImie() << endl; cout << ""Nowe: ""; imie = MetodyPomocnicze::wczytajLinie(); imie = zamienPierwszaLitereNaDuzaAPozostaleNaMale(imie); daneDoEdycji.push_back(itr -> Adresat::pobierzImie()); daneDoEdycji.push_back(imie); itr -> Adresat::ustawImie(imie); } } plikZAdresatami.zmienDaneAdresataWPliku(daneDoEdycji, idAdresataDoEdycji); cout << endl << ""Edycja danych zakonczona powodzeniem!"" << endl << endl; system(""pause""); break; case '2': system(""cls""); cout << "" > Nazwisko <"" << endl << endl; for (vector ::iterator itr = adresaci.begin(); itr != adresaci.end(); itr++) { if (itr -> Adresat::pobierzId() == idAdresataDoEdycji) { cout << ""Stare: "" << itr -> Adresat::pobierzNazwisko() << endl; cout << ""Nowe: ""; nazwisko = MetodyPomocnicze::wczytajLinie(); nazwisko = zamienPierwszaLitereNaDuzaAPozostaleNaMale(nazwisko); daneDoEdycji.push_back(itr -> Adresat::pobierzNazwisko()); daneDoEdycji.push_back(nazwisko); itr -> Adresat::ustawNazwisko(nazwisko); } } plikZAdresatami.zmienDaneAdresataWPliku(daneDoEdycji, idAdresataDoEdycji); cout << endl << ""Edycja danych zakonczona powodzeniem!"" << endl << endl; system(""pause""); break; case '3': system(""cls""); cout << "" > Numer telefonu <"" << endl << endl; for (vector ::iterator itr = adresaci.begin(); itr != adresaci.end(); itr++) { if (itr -> Adresat::pobierzId() == idAdresataDoEdycji) { cout << ""Stary: "" << itr -> Adresat::pobierzNumerTelefonu() << endl; cout << ""Nowy: ""; numerTelefonu = MetodyPomocnicze::wczytajLinie(); daneDoEdycji.push_back(itr -> Adresat::pobierzNumerTelefonu()); daneDoEdycji.push_back(numerTelefonu); itr -> Adresat::ustawNumerTelefonu(numerTelefonu); } } plikZAdresatami.zmienDaneAdresataWPliku(daneDoEdycji, idAdresataDoEdycji); cout << endl << ""Edycja danych zakonczona powodzeniem!"" << endl << endl; system(""pause""); break; case '4': system(""cls""); cout << "" > Email <"" << endl << endl; for (vector ::iterator itr = adresaci.begin(); itr != adresaci.end(); itr++) { if (itr -> Adresat::pobierzId() == idAdresataDoEdycji) { cout << ""Stary: "" << itr -> Adresat::pobierzEmail() << endl; cout << ""Nowy: ""; email = MetodyPomocnicze::wczytajLinie(); daneDoEdycji.push_back(itr -> Adresat::pobierzEmail()); daneDoEdycji.push_back(email); itr -> Adresat::ustawEmail(email); } } plikZAdresatami.zmienDaneAdresataWPliku(daneDoEdycji, idAdresataDoEdycji); cout << endl << ""Edycja danych zakonczona powodzeniem!"" << endl << endl; system(""pause""); break; case '5': system(""cls""); cout << "" > Adres <"" << endl << endl; for (vector ::iterator itr = adresaci.begin(); itr != adresaci.end(); itr++) { if (itr -> Adresat::pobierzId() == idAdresataDoEdycji) { cout << ""Stary: "" << itr -> Adresat::pobierzAdres() << endl; cout << ""Nowy: ""; adres = MetodyPomocnicze::wczytajLinie(); daneDoEdycji.push_back(itr -> Adresat::pobierzAdres()); daneDoEdycji.push_back(adres); itr -> Adresat::ustawAdres(adres); } } plikZAdresatami.zmienDaneAdresataWPliku(daneDoEdycji, idAdresataDoEdycji); cout << endl << ""Edycja danych zakonczona powodzeniem!"" << endl << endl; system(""pause""); break; case '6': break; default: cout << ""Musisz wybrac cyfre od 1 do 6!"" << endl; Sleep(1500); break; } } ",tekst 380,"#include #include #include std::vector> matrixMult2D(const std::vector>& A, const std::vector>& B) { // Check if the matrices have compatible dimensions if (A[0].size() != B.size()) { return {}; } // Create the result matrix std::vector> C(A.size(), std::vector(B[0].size())); // Multiply the matrices for (int i = 0; i < A.size(); i++) { for (int j = 0; j < B[0].size(); j++) { for (int k = 0; k < A[0].size(); k++) { C[i][j] += A[i][k] * B[k][j]; } } } return C; } std::vector> createFibonacciBasisMatrix() { std::vector> fibonacciBasis = { {1, 1}, {1, 0} }; return fibonacciBasis; } int main() { std::vector> [MASK] = createFibonacciBasisMatrix(); std::vector> fibn_iter = createFibonacciBasisMatrix(); unsigned int sum = 0; while (fibn_iter[0][0] < 4000000) { fibn_iter = matrixMult2D( [MASK] , fibn_iter); sum += (fibn_iter[0][0]%2 == 0) ? fibn_iter[0][0] : 0; } std::cout << sum << std::endl; return 0; } ",fibn_basis 381,"// ====================================================================== // \title Main.cpp // \brief main program for the F' application. // // ====================================================================== // Used to access topology functions #include #include // Used for Task Runner #include // Used for logging #include #include /** * \brief setup the program */ void setup() { // Setup Serial Serial.begin(115200); //Uart Comm and logging static_cast(Os::Console::getSingleton().getHandle())->setStreamHandler(Serial); delay(1000); Fw::Logger::log(""Program Started\n""); // Object for communicating state to the reference topology BaremetalReference::TopologyState [MASK] ; [MASK] .uartNumber = 0; [MASK] .uartBaud = 115200; // Setup, cycle, and teardown topology BaremetalReference::setupTopology( [MASK] ); } void loop() { #ifdef USE_BASIC_TIMER rateDriver.cycle(); #endif Os::Baremetal::TaskRunner::getSingleton().run(); } ",inputs 382,"#include #include #include #include #include std::vector ip_adress(const std::string& ip_str) { std::vector ip; size_t start = 0; size_t end = ip_str.find('.'); while (end != std::string::npos) { ip.push_back(ip_str.substr(start, end - start)); start = end + 1; end = ip_str.find('.', start); } ip.push_back(ip_str.substr(start)); return ip; } int main() { auto [MASK] =[](const std::vector &a, const std::vector &b)->bool{ for(size_t i=0;i> ip_list; std::string line; std::ifstream in(""C:\\proga_sem3\\lab2\\ip_filter.tsv""); while (std::getline(in, line)) { size_t tabul = line.find('\t'); std::string ip_str = line.substr(0, tabul); ip_list.push_back(ip_adress(ip_str)); } std::sort(ip_list.begin(), ip_list.end(), [MASK] ); for(auto ip : ip_list) { std::cout << ip[0] << ""."" << ip[1] << ""."" << ip[2] << ""."" <setTimeout(boost::posix_time::seconds(5)); open(devname); } /************************************************************************************************ * PCBMotor::~PCBMotor * ************************************************************************************************/ PCBMotor::~PCBMotor() { close(); } /************************************************************************************************ * PCBMotor::home * ************************************************************************************************/ void PCBMotor::home(uint8_t mnum) { std::string cmd = ""M"" + std::to_string(mnum) + "",s-2880\r""; write(cmd.data()); } void PCBMotor::home(std::vector mnum) { std::string cmd = """"; for (size_t i=0; i mnum) { std::string cmd = """"; for (size_t i=0; i mnum) { std::string cmd = """"; for (size_t i=0; i mnum, std::vector nummpulses, std::vector edge) { std::string cmd = """"; std::string basecmd = """"; for (size_t i=0; i mnum, std::vector nummpulses, std::vector edge) { std::string cmd = """"; std::string basecmd = """"; for (size_t i=0; i mnum, std::vector numsteps) { std::string cmd = """"; for (size_t i=0; i 4096)) { throw std::invalid_argument(""angle needs to be < 4096deg""); } std::string cmd = ""M""+std::to_string(mnum)+"",s-2880,s""+std::to_string(ang*8)+""\r""; write(cmd.data()); } void PCBMotor::moveabsolute(std::vector mnum, std::vector ang) { if (std::any_of(ang.cbegin(), ang.cend(), [](double i){ return i > 4096; })) { throw std::invalid_argument(""angle needs to be < 4096deg""); } std::string cmd; for (size_t i=0; i 360) { ang -= 360; } std::string basecmd = restrack ? ""G"" : ""GN""; std::string cmd = ""M""+std::to_string(mnum)+"",""+ basecmd+std::to_string(ang*8)+""\r""; write(cmd.data()); } void PCBMotor::goto_pos(std::vector mnum, std::vector ang, std::vector restrack) { std::string cmd; std::string basecmd = """"; for (size_t i=0; i 360) { ang[i] -= 360; } basecmd = restrack[i] ? ""G"" : ""GN""; cmd.append(""M""+std::to_string(mnum[i])+"",""+basecmd+std::to_string(ang[i]*8)); if (!((i+1)==mnum.size())) { cmd.append("",""); } } cmd.append(""\r""); write(cmd.data()); } /************************************************************************************************ * PCBMotor::moverelative * ************************************************************************************************/ void PCBMotor::moverelative(uint8_t mnum, double ang) { if (std::abs(ang > 4096)) { throw std::invalid_argument(""angle needs to be < 4096deg""); } std::string cmd = ""M""+std::to_string(mnum)+"",s""+std::to_string(ang*8)+""\r""; write(cmd.data()); } void PCBMotor::moverelative(std::vector mnum, std::vector ang) { std::string cmd; if (std::any_of(ang.cbegin(), ang.cend(), [](double i){ return i > 4096; })) { throw std::invalid_argument(""angle needs to be < 4096deg""); } for (size_t i=0; i 5000) { throw std::invalid_argument(""Voltage needs to be 0...5000mV""); } std::string cmd = ""M""+std::to_string(mnum)+"",V""+std::to_string(mV)+""\r""; write(cmd.data()); } void PCBMotor::set_voltage(std::vector mnum, std::vector mV) { for (uint16_t v : mV) { if (v > 5000) { throw std::invalid_argument(""Voltage needs to be 0...5000mV""); } } std::string cmd; for (size_t i=0; i PCBMotor::get_voltage(std::vector mnum) { std::vector mV_vec; std::string cmd; for (uint8_t m : mnum) { cmd = ""M""+std::to_string(m)+"",V\r""; write(cmd.data()); std::string res = read(); //TODO: process and return result uint16_t mV = 0; mV_vec.push_back(mV); } return mV_vec; } /************************************************************************************************ * PCBMotor::set_min_voltage * ************************************************************************************************/ void PCBMotor::set_min_voltage(uint8_t mnum, uint16_t mV) { if (mV > 5000) { throw std::invalid_argument(""Voltage needs to be 0...5000mV""); } std::string cmd = ""M""+std::to_string(mnum)+"",Vmin""+std::to_string(mV)+""\r""; write(cmd.data()); } void PCBMotor::set_min_voltage(std::vector mnum, std::vector mV) { for (uint16_t v : mV) { if (v > 5000) { throw std::invalid_argument(""Voltage needs to be 0...5000mV""); } } std::string cmd; for (size_t i=0; i PCBMotor::get_min_voltage(std::vector mnum) { std::vector mV_vec; std::string cmd; for (uint8_t m : mnum) { cmd = ""M""+std::to_string(m)+"",Vmin\r""; write(cmd.data()); std::string res = read(); //TODO: process and return result uint16_t mV = 0; mV_vec.push_back(mV); } return mV_vec; } /************************************************************************************************ * PCBMotor::set_max_voltage * ************************************************************************************************/ void PCBMotor::set_max_voltage(uint8_t mnum, uint16_t mV) { if (mV > 5000) { throw std::invalid_argument(""Voltage needs to be 0...5000mV""); } std::string cmd = ""M""+std::to_string(mnum)+"",Vmax""+std::to_string(mV)+""\r""; write(cmd.data()); } void PCBMotor::set_max_voltage(std::vector mnum, std::vector mV) { for (uint16_t v : mV) { if (v > 5000) { throw std::invalid_argument(""Voltage needs to be 0...5000mV""); } } std::string cmd; for (size_t i=0; i PCBMotor::get_max_voltage(std::vector mnum) { std::vector mV_vec; std::string cmd; for (uint8_t m : mnum) { cmd = ""M""+std::to_string(m)+"",Vmax\r""; write(cmd.data()); std::string res = read(); //TODO: process and return result uint16_t mV = 0; mV_vec.push_back(mV); } return mV_vec; } /************************************************************************************************ * PCBMotor::optimize_sensor_current * ************************************************************************************************/ void PCBMotor::optimize_sensor_current(uint8_t mnum) { std::string cmd = ""M""+std::to_string(mnum)+"",LS\r""; write(cmd.data()); } void PCBMotor::optimize_sensor_current(std::vector mnum) { std::string cmd = """"; for (size_t i=0; i 200) { throw std::invalid_argument(""Sensor current needs to be 0...200""); } std::string cmd = ""M""+std::to_string(mnum)+"",L""+std::to_string(cur)+""\r""; write(cmd.data()); } void PCBMotor::set_sensor_current(std::vector mnum, std::vector cur) { for (uint16_t c : cur) { if (c > 200) { throw std::invalid_argument(""Sensor current needs to be 0...200""); } } std::string cmd = """"; for (size_t i=0; i PCBMotor::get_sensor_current(std::vector mnum) { std::vector [MASK] ; std::string cmd; for (uint8_t m : mnum) { cmd = ""M""+std::to_string(m)+"",L\r""; write(cmd.data()); std::string res = read(); //TODO: process and return result uint8_t c = 0; [MASK] .push_back(c); } return [MASK] ; } /************************************************************************************************ * PCBMotor::resonance_sweep * ************************************************************************************************/ void PCBMotor::resonance_sweep(uint8_t mnum, std::string mode) { std::string basecmd = ""P""; if (mode.compare(""reverse"")) { basecmd = ""PR""; } else if (mode.compare(""alternating"")) { basecmd = ""PA""; } std::string cmd = ""M""+std::to_string(mnum)+"",""+basecmd+""\r""; write(cmd.data()); } void PCBMotor::resonance_sweep(std::vector mnum, std::vector mode) { std::string cmd = """"; std::string basecmd = ""P""; for (size_t i=0; i mnum, std::vector dir, std::vector scale) { std::string cmd = """"; std::string basecmd = """"; for (size_t i=0; i PCBMotor::get_voltage_scaling(std::vector mnum, std::vector dir) { std::string cmd = """"; std::string basecmd = """"; std::string res = """"; uint8_t scale = 0; std::vector scale_vec = std::vector(); for (size_t i=0; i mnum) { std::string cmd = """"; for (size_t i=0; i mnum) { std::string cmd = """"; for (size_t i=0; i 125000) { throw std::invalid_argument(""Frequency needs to be 0...125000Hz""); } std::string cmd = ""M""+std::to_string(mnum)+"",F""+std::to_string(Hz)+""\r""; write(cmd.data()); } void PCBMotor::set_vco_freq(std::vector mnum, std::vector Hz) { for (uint32_t h : Hz) { if (h > 125000) { throw std::invalid_argument(""Frequency needs to be 0...125000Hz""); } } std::string cmd; for (size_t i=0; i PCBMotor::get_vco_freq(std::vector mnum) { std::vector Hz_vec; std::string cmd; for (uint8_t m : mnum) { cmd = ""M""+std::to_string(m)+"",F\r""; write(cmd.data()); std::string res = read(); //TODO: process and return result uint32_t Hz = 0; Hz_vec.push_back(Hz); } return Hz_vec; } ",c_vec 384,"#include #include #include #include #include #include #include ""stopwatch.h"" std::uniform_int_distribution ud; std::default_random_engine re{ static_cast(std::chrono::steady_clock::now().time_since_epoch().count()) }; template void time_container(Container&& cont) noexcept { } int main() { constexpr auto count = 50000u; constexpr auto [MASK] = 100u; auto vec = std::vector(count); // auto vec = std::array{}; auto sw = Stopwatch{""std::sort"", false}; auto total = 0u; for (unsigned i = 0; i < [MASK] ; ++i) { std::generate(vec.begin(), vec.end(), []{return ud(re);}); sw.start(); std::sort(vec.begin(), vec.end()); total += sw.stop(); } std::cout << ""Performance of std::sort on a vector of "" << count << "" elements,\n"" << ""measured over "" << [MASK] << "" iterations:\n""; std::cout << ""Total time = "" << total << ""ms\n"" << ""Average = "" << static_cast(total) / [MASK] << ""ms\n""; } ",iters 385,"#include ""MyDatatables.h"" /************************************************ * @brief My Datatables Constructor. * MyDatatables ***********************************************/ MyDatatables::MyDatatables(MyLanguageModel *thisLanguageModel, MyConstants *thisConstant, QObject *parent) : QObject(parent), myLanguageModel(thisLanguageModel), myConstants(thisConstant) { mySqlModel = new MySqlDbtModel(thisLanguageModel, thisConstant, this); // Create Variable Trackers and Set to Empty myProject = new MyProjectClass("""", """", """", """", """", """", """", """", """"); } /************************************************ * @brief My Datatables Deconstructor. * MyDatatables ***********************************************/ MyDatatables::~MyDatatables() { } /************************************************ * @brief set Debug Message. * setDebugMessage ***********************************************/ void MyDatatables::setDebugMessage(bool [MASK] ) { isDebugMessage = [MASK] ; setMessage(""setDebugMessage""); } /************************************************ * @brief get Debug Message. * getDebugMessage ***********************************************/ bool MyDatatables::getDebugMessage() { setMessage(""getDebugMessage""); return isDebugMessage; } /************************************************ * @brief set Project Folder. * setProjectFolder ***********************************************/ void MyDatatables::setProjectFolder(const QString &thisProjectFolder) { setMessage(""setProjectFolder""); myProjectFolder = thisProjectFolder; } /************************************************ * @brief get Project Folder. * getProjectFolder ***********************************************/ QString MyDatatables::getProjectFolder() { setMessage(""getProjectFolder""); return myProjectFolder; } /************************************************ * @brief set Project Name. * setProjectName ***********************************************/ void MyDatatables::setProjectName(const QString &thisProjectName) { setMessage(""setProjectName""); myProjectName = thisProjectName; } /************************************************ * @brief get Project Name. * getProjectName ***********************************************/ QString MyDatatables::getProjectName() { setMessage(""getProjectName""); return myProjectName; } /************************************************ * @brief set Project ID. * setProjectID ***********************************************/ void MyDatatables::setProjectID(const QString &thisProjectID) { setMessage(""setProjectID""); myProjectID = thisProjectID; } /************************************************ * @brief get Project ID. * getProjectID ***********************************************/ QString MyDatatables::getProjectID() { setMessage(""getProjectID""); return myProjectID; } /************************************************ * @brief set ComboBox Sql Value. * setComboBoxSqlValue ***********************************************/ void MyDatatables::setComboBoxSqlValue(const QString &thisComboBoxSqlValue) { setMessage(""setComboBoxSqlValue""); myComboBoxSqlValue = thisComboBoxSqlValue; } /************************************************ * @brief get ComboBox Sql Value. * getComboBoxSqlValue ***********************************************/ QString MyDatatables::getComboBoxSqlValue() { setMessage(""getComboBoxSqlValue""); return myComboBoxSqlValue; } /************************************************ * @brief check Database. * checkDatabase ***********************************************/ bool MyDatatables::checkDatabase() { setMessage(""checkDatabase""); #ifdef USE_SQL_FLAG // Database mySqlModel->setSqlDriver(myComboBoxSqlValue); if (!mySqlModel->createDataBaseConnection()) { return false; } // // Configuration // if (!mySqlModel->isDbTable(""Projects"")) { /* * Table Projects holds the name of the Qt Project * id integer PRIMARY KEY autoincrement, * id, QtProjectName, QtProjectFolder, SourceFolder, DoxyfileFolder, HelpFolder, SourceLanguage, LanguageIDs, Make */ if (mySqlModel->runQuery(QLatin1String(R""(CREATE TABLE Projects(id integer PRIMARY KEY autoincrement, QtProjectName, QtProjectFolder, SourceFolder, DoxyfileFolder, HelpFolder, SourceLanguage, LanguageIDs, Make))""))) { QString theQtProjectName = myConstants->MY_QT_PROJECT_NAME; QString theQtProjectFolder = myConstants->MY_QT_PROJECT_FOLDER; QString theSource = myConstants->MY_SOURCE_FOLDER; QString theDoxyfile = myConstants->MY_DOXYFILE_FOLDER; QString theHelpFolder = myConstants->MY_HELP_FOLDER; QString theSourceLanguage = myConstants->MY_SOURCE_LANGUAGE; QString theMake = myConstants->MY_MAKE; QString theLanguageIDs = myConstants->MY_LANGUAGE_IDs; setProject(theQtProjectName, theQtProjectFolder, theSource, theDoxyfile, theHelpFolder, theSourceLanguage, theLanguageIDs, theMake); if (insertQtProjects()) { myProjectID = mySqlModel->getRecordID(); myLanguageModel->mySetting->writeSettings(myConstants->MY_SQL_PROJECT_ID, myProjectID); } else { qCritical() << mySqlModel->getSqlDriver() << "" INSERT TABLE Projects error:""; } } // } // end if (!isDbTable(""Projects"")) // #endif return true; } /************************************************ * @brief insert Qt Projects into SQL Database. * insertQtProjects ***********************************************/ bool MyDatatables::insertQtProjects() { setMessage(""insertProjects""); // QtProjectName, QtProjectFolder, SourceFolder, DoxyfileFolder, HelpFolder, LanguageIDs, Make QString theQuery = QLatin1String(R""(INSERT INTO Projects (QtProjectName, QtProjectFolder, SourceFolder, DoxyfileFolder, HelpFolder, SourceLanguage, LanguageIDs, Make) values('%1', '%2', '%3', '%4', '%5', '%6', '%7', '%8'))"").arg(myProject->getQtProjectName(), myProject->getQtProjectFolder(), myProject->getSourceFolder(), myProject->getDoxyfileFolder(), myProject->getHelpFolder(), myProject->getSourceLanguage(), myProject->getLanguageIDs(), myProject->getMake()); setMessage(""insertProjects: "" + theQuery); // if (!mySqlModel->runQuery(theQuery)) { qCritical() << ""INSERT Projects error: "" << theQuery; return false; } setProjectID(mySqlModel->getRecordID()); return true; } /************************************************ * @brief addQtProject Assumes you have ran setProject: QtProjectName, QtProjectFolder, SourceFolder, DoxyfileFolder, HelpFolder, LanguageIDs. * addQtProject ***********************************************/ bool MyDatatables::addQtProject() { setMessage(""addQtProject""); #ifdef USE_SQL_FLAG // SELECT id, QtProjectName FROM Projects WHERE QtProject = if (isQtProjectNameQuery(myProject->getQtProjectName())) { myLanguageModel->mySetting->showMessageBox(QObject::tr(""Record found!"").toLocal8Bit(), QString(""%1: %2"").arg(tr(""Not adding: Record found in database""), myProject->getQtProjectName()).toLocal8Bit(), myLanguageModel->mySetting->Warning); return false; } return insertQtProjects(); #else return true; #endif } /************************************************ * @brief delete Project. * deleteProject ***********************************************/ void MyDatatables::deleteQtProject(const QString &thisID) { setMessage(""deleteQtProject""); #ifdef USE_SQL_FLAG QSqlQuery query; //!< SQL Query QString theQuery = QString(""DELETE FROM Projects WHERE id = "").append(thisID); setMessage(""thisQuery: "" + theQuery); if (!query.exec(theQuery)) { qCritical() << ""SqLite error:"" << query.lastError().text() << "", SqLite error code:"" << query.lastError(); } #endif } /************************************************ * @brief get Qt Project Name Select Query SELECT id, QtProjectName FROM Projects. * getQtProjectNameSelectQuery ***********************************************/ QString MyDatatables::getQtProjectNameSelectQuery() { setMessage(""getQtProjectNameSelectQuery""); return QString(""SELECT id, QtProjectName FROM Projects""); } /************************************************ * @brief get Qt Project Name By Name Query SELECT id, QtProjectName FROM Projects WHERE QtProjectFolder =. * getQtProjectNameByNameQuery ***********************************************/ QString MyDatatables::getQtProjectNameByNameQuery(const QString &thisProject) { setMessage(""getQtProjectNameByNameQuery""); return QString(""SELECT id, QtProjectName FROM Projects WHERE QtProjectName = '%1'"").arg(thisProject); } /************************************************ * @brief is Project Folder Query myAccessSqlDbtModel->isProjectQuery(ui->lineEditSettingsProjectBin->text());. * isProjectFolderQuery ***********************************************/ bool MyDatatables::isQtProjectNameQuery(const QString &thisProjectName) { setMessage(""isQtProjectNameQuery""); #ifdef USE_SQL_FLAG QSqlQuery theQuery; //!< SQL Query QString theQueryCommand = getQtProjectNameByNameQuery(thisProjectName); if (theQuery.exec(theQueryCommand)) { if (theQuery.first()) { return true; } else { return false; } } else { qCritical() << ""SqLite error isProjectQuery:"" << theQuery.lastError().text() << "", SqLite error code:"" << theQuery.lastError(); } #endif return false; } /************************************************ * @brief get Qt Project Full Select Query ID SELECT * FROM Projects WHERE id =. * getQtProjectFullSelectQueryID ***********************************************/ QString MyDatatables::getQtProjectFullSelectQueryID(const QString &thisWhereID) { setMessage(""getProjectFolderFullSelectQueryID""); return QString(""SELECT * FROM Projects WHERE id = "").append(thisWhereID); } /************************************************ * @brief get Qt Project Name Select Query ID SELECT id, QtProjectName FROM Projects WHERE id. * getQtProjectNameSelectQueryID ***********************************************/ QString MyDatatables::getQtProjectNameSelectQueryID(const QString &thisWhereID) { setMessage(""getQtProjectNameSelectQueryID""); return QString(""SELECT id, QtProjectName FROM Projects WHERE id = "").append(thisWhereID); } /************************************************ * @brief save Project Projects: id, QtProjectName QtProjectFolder, SourceFolder, DoxyfileFolder, HelpFolder, SourceLanguage, LanguageIDs, Make * saveProject ***********************************************/ void MyDatatables::saveQtProject() { setMessage(""saveProject""); #ifdef USE_SQL_FLAG QSqlQuery theQuery; //!< SQL Query QString theQueryString = QString(""UPDATE Projects set QtProjectName = '%1', QtProjectFolder = '%2', SourceFolder = '%3', DoxyfileFolder = '%4', HelpFolder = '%5', SourceLanguage = '%6', LanguageIDs = '%7', Make = '%8' WHERE id = %9"").arg(myProject->getQtProjectName(), myProject->getQtProjectFolder(), myProject->getSourceFolder(), myProject->getDoxyfileFolder(), myProject->getHelpFolder(), myProject->getSourceLanguage(), myProject->getLanguageIDs(), myProject->getMake(), myProject->getID()); setMessage(""thisQuery: |"" + theQueryString + ""| getQtProjectName = "" + myProject->getQtProjectName() + ""| getQtProjectFolder = "" + myProject->getQtProjectFolder() + ""| getSourceFolder="" + myProject->getSourceFolder() + ""| getDoxyfileFolder="" + myProject->getDoxyfileFolder() + ""| getHelpFolder="" + myProject->getHelpFolder() + ""| getSourceLanguage="" + myProject->getSourceLanguage() + ""| getLanguageIDs="" + myProject->getLanguageIDs() + ""| getMake="" + myProject->getMake() + ""| ID="" + myProject->getID() + ""|""); if (!theQuery.exec(theQueryString)) { qCritical() << ""SqLite error saveProject:"" << theQuery.lastError().text() << "", SqLite error code:"" << theQuery.lastError(); } isSaveSettings = false; #endif } /************************************************ * @brief set Project Sets all Variables used in the Configuarion Database in one Place: * QtProjectFolder, SourceFolder, DoxyfileFolder, HelpFolder, SourceLanguage, LanguageIDs, Make. * setProject ***********************************************/ void MyDatatables::setProject(const QString &thisQtProjectName, const QString &thisQtProjectFolder, const QString &thisSourceFolder, const QString &thisDoxyfileFolder, const QString &thisHelpFolder, const QString &thisSourceLanguage, const QString &thisLanguageIDs, const QString &thisMake) { setMessage(""setProject""); myProject->setQtProjectName(thisQtProjectName); myProject->setQtProjectFolder(thisQtProjectFolder); myProject->setSourceFolder(thisSourceFolder); myProject->setDoxyfileFolder(thisDoxyfileFolder); myProject->setHelpFolder(thisHelpFolder); myProject->setSourceLanguage(thisSourceLanguage); myProject->setLanguageIDs(thisLanguageIDs); myProject->setMake(thisMake); } /************************************************ * @brief set Message. * setMessage ***********************************************/ void MyDatatables::setMessage(const QString &thisMessage) { if (isDebugMessage) { qDebug() << thisMessage; //std::cout << thisMessage.toStdString() << std::endl; } } /*** ************************* End of File ***********************************/ ",thisState 386,"#include #include #include int main(int argc, char** argv){ ros::init(argc, argv, ""odometry_publisher""); ros::NodeHandle n; ros::Publisher odom_pub = n.advertise(""odom"", 50); tf::TransformBroadcaster odom_broadcaster; // send message out using ROS and tf respectively double x = 0.0; double y = 0.0; double th = 0.0; // robot start at the origin of the ""odom"" coordinate frame initially double vx = 0.1; // fake robot move in the odome frame at a rate of 0.1m/s in x, -0.1m/s in y, double vy = -0.1; // 0.1rad/s in the h direction, which will cause the robot drive in a circle. double [MASK] = 0.1; ros::Time current_time, last_time; current_time = ros::Time::now(); last_time = ros::Time::now(); ros::Rate r(5); // publish the odometry information at a rate of 5Hz while(n.ok()){ ros::spinOnce(); // check for incoming messages current_time = ros::Time::now(); // compute odometry in a typical way given the velocities of the robot double dt = (current_time - last_time).toSec(); double delta_x = (vx * cos(th) - vy * sin(th)) * dt; double delta_y = (vx * sin(th) + vy * cos(th)) * dt; double delta_th = [MASK] * dt; // A real odometry system would, of course, integrate computed velocities instead. x += delta_x; y += delta_y; th += delta_th; // since all odometry is 6DOF we'll need a quaternion created from yaw geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th); //first, we'll publish the transform over tf geometry_msgs::TransformStamped odom_trans; odom_trans.header.stamp = current_time; odom_trans.header.frame_id = ""odom""; odom_trans.child_frame_id = ""base_link""; odom_trans.transform.translation.x = x; odom_trans.transform.translation.y = y; odom_trans.transform.translation.z = 0.0; odom_trans.transform.rotation = odom_quat; //send the transform odom_broadcaster.sendTransform(odom_trans); //next, we'll publish the odometry message over ROS nav_msgs::Odometry odom; odom.header.stamp = current_time; odom.header.frame_id = ""odom""; //set the position odom.pose.pose.position.x = x; odom.pose.pose.position.y = y; odom.pose.pose.position.z = 0.0; odom.pose.pose.orientation = odom_quat; //set the velocity odom.child_frame_id = ""base_link""; odom.twist.twist.linear.x = vx; odom.twist.twist.linear.y = vy; odom.twist.twist.angular.z = [MASK] ; //publish the message odom_pub.publish(odom); last_time = current_time; r.sleep(); } } ",vth 387,"#include ""recast-sys/include/detour.h"" #include ""recast-sys/src/lib.rs.h"" std::unique_ptr newDtNavMesh() { return std::make_unique(); } std::unique_ptr newDtNavMeshQuery() { return std::make_unique(); } std::unique_ptr newDtQueryFilter() { return std::make_unique(); } std::unique_ptr newDtPathCorridor() { return std::make_unique(); } bool createNavMeshData(NavMeshCreateParams* params, std::uint8_t **outData, std::int32_t *outDataSize) { auto [MASK] = dtNavMeshCreateParams(); [MASK] .verts = params->vertices; [MASK] .vertCount = params->num_vertices; [MASK] .polys = params->polygons; [MASK] .polyFlags = params->polygon_flags; [MASK] .polyAreas = params->polygon_areas; [MASK] .polyCount = params->num_polys; [MASK] .nvp = params->max_vertices_per_poly; [MASK] .detailMeshes = params->detail_meshes; [MASK] .detailVerts = params->detail_vertices; [MASK] .detailVertsCount = params->num_detail_vertices; [MASK] .detailTris = params->detail_triangles; [MASK] .detailTriCount = params->num_detail_triangles; [MASK] .offMeshConVerts = params->off_mesh_conn_vertices; [MASK] .offMeshConRad = params->off_mesh_conn_radii; [MASK] .offMeshConFlags = params->off_mesh_conn_flags; [MASK] .offMeshConAreas = params->off_mesh_conn_areas; [MASK] .offMeshConDir = params->off_mesh_conn_dir; [MASK] .offMeshConUserID = params->off_mesh_conn_ids; [MASK] .offMeshConCount = params->off_mesh_conn_count; [MASK] .userId = params->user_id; [MASK] .tileX = params->tile_x; [MASK] .tileY = params->tile_y; [MASK] .tileLayer = params->tile_layer; std::copy(params->b_min.begin(), params->b_min.end(), [MASK] .bmin); std::copy(params->b_max.begin(), params->b_max.end(), [MASK] .bmax); [MASK] .walkableHeight = params->walkable_height; [MASK] .walkableRadius = params->walkable_radius; [MASK] .walkableClimb = params->walkable_climb; [MASK] .cs = params->cs; [MASK] .ch = params->ch; [MASK] .buildBvTree = params->build_bv_tree; return dtCreateNavMeshData(& [MASK] , outData, outDataSize); } ",dtParams 388,"/** Copyright 2024 Sil3ntStorm https://github.com/sil3ntstorm 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 ""formatters.hpp"" #include #include std::string human_time_diff(std::chrono::nanoseconds duration, std::streamsize precision) { #if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907L std::stringstream os; using namespace std::chrono; auto y = duration_cast(duration); duration -= y; auto mn = duration_cast(duration); duration -= mn; auto d = duration_cast(duration); duration -= d; auto h = duration_cast(duration); duration -= h; auto m = duration_cast(duration); duration -= m; auto s = duration_cast(duration); duration -= s; std::optional [MASK] ; if (precision > os.precision()) { precision = os.precision(); } if (precision > 6) { precision = 9; } else if (precision > 3) { precision = 6; } else if (precision > 0) { precision = 3; } switch (precision) { case 9: [MASK] = duration.count(); break; case 6: [MASK] = duration_cast(duration).count(); break; case 3: [MASK] = duration_cast(duration).count(); break; } char fill = os.fill('0'); if (y.count()) os << y.count() << "" year"" << (y.count() > 1 ? ""s"" : """") << "" ""; if (mn.count()) os << mn.count() << "" month"" << (mn.count() > 1 ? ""s"" : """") << "" ""; if (y.count() || mn.count() || d.count()) os << d.count() << ""d ""; if (y.count() || mn.count() || d.count() || h.count()) os << std::setw(2) << h.count() << "":""; if (y.count() || mn.count() || d.count() || h.count() || m.count()) os << std::setw(d.count() || h.count() ? 2 : 1) << m.count() << "":""; os << std::setw(d.count() || h.count() || m.count() ? 2 : 1) << s.count(); if ( [MASK] .has_value() && [MASK] .value() > 0) os << ""."" << std::setw(precision) << [MASK] .value(); if (!d.count() && !h.count() && !m.count()) os << ""s""; os.fill(fill); return os.str(); #else return {}; #endif } ",fs_count 389,"// Copyright 2016 <> // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #define OLED_SCL 13 #define OLED_SDA 12 #define OLED_RES 11 #define OLED_DC 10 #define SPI_fps 12 #define I2C_fps 9 #include unsigned long last_SPI_refresh = 0; unsigned long last_I2C_refresh = 0; unsigned long SPI_interval = 1000 / SPI_fps; unsigned long I2C_interval = 1000 / I2C_fps; int SPI_angle = 0; int I2C_angle = 0; // SPI // http://www.banggood.com/0_96-Inch-6Pin-12864-SPI-Blue-Yellow-OLED-Display-Module-For-Arduino-p-969145.html U8GLIB_SSD1306_128X64 u8g_spi(OLED_SCL, OLED_SDA, U8G_PIN_NONE, OLED_DC, OLED_RES); // I2C // http://www.banggood.com/0_96-Inch-4Pin-White-IIC-I2C-OLED-Display-Module-12864-LED-For-Arduino-p-958196.html // SDA = A4 // SCL = A5 U8GLIB_SSD1306_128X64 u8g_i2c(U8G_I2C_OPT_FAST); void setup() { } unsigned int SPI_maxfps = 0; unsigned int I2C_maxfps = 0; void loop() { // SPI DISPLAY if ((unsigned long)(millis() - last_SPI_refresh) >= SPI_interval) { SPI_angle -= 6; if (SPI_angle <= 0) { SPI_angle = 360 + SPI_angle; } last_SPI_refresh = millis(); u8g_spi.firstPage(); do { draw(u8g_spi, SPI_angle, SPI_maxfps); } while( u8g_spi.nextPage() ); SPI_maxfps = 1000 / (millis() - last_SPI_refresh); } // I2C DISPLAY if ((unsigned long)(millis() - last_I2C_refresh) >= I2C_interval) { I2C_angle -= 6; if(I2C_angle <= 0) { I2C_angle = 360 + I2C_angle; } last_I2C_refresh = millis(); u8g_i2c.firstPage(); do { draw(u8g_i2c, I2C_angle, I2C_maxfps); } while( u8g_i2c.nextPage() ); I2C_maxfps = 1000 / (millis() - last_I2C_refresh); } } const int cx = 64; const int cy = 42; const int r = 20; const int x = cx + 0; const int y = cy - r + 3; void draw(U8GLIB u8g, int angle, int maxfps) { // graphic commands to redraw the complete screen should be placed here u8g.setFont(u8g_font_unifont); u8g.drawStr(0, 20, ""MAX FPS: ""); u8g.setPrintPos(70, 20); u8g.print(maxfps); u8g.drawCircle(cx, cy, r); float [MASK] = 0.01745329251 * angle; // Pi/180 * angle float c = cos( [MASK] ); float s = sin( [MASK] ); int nx = (c * (x - cx)) + (s * (y - cy)) + cx; int ny = (c * (y - cy)) - (s * (x - cx)) + cy; u8g.drawLine(cx, cy, nx, ny); } ",radians 390,"/* Copyright 2015 Concurrent Computer Corporation 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 #include #include #include #include #include #include #include ""../util_source/io_rtns.h"" #include ""tcache_agentx.h"" #include ""clientRedirectTable.h"" #define HANDLER_NAME ""clientRedirectTable"" using namespace std; static vector g_clientRedirectTable; static Netsnmp_Node_Handler handler; static netsnmp_variable_list * first_datapt(void ** loop_context, void ** data_context, netsnmp_variable_list * put_index_data, netsnmp_iterator_info * data); static netsnmp_variable_list * next_datapt(void ** loop_context, void ** data_context, netsnmp_variable_list * put_index_data, netsnmp_iterator_info * data); static void load_table(void); static void delayed_response(unsigned int clientreg, void * clientarg); //******************************************************************************** // Function: init_clientRedirectTable // // Description: clientRedirectTable initialization for mib. //******************************************************************************** bool init_clientRedirectTable(void) { syslog(LOG_DEBUG, ""Enter: %s."", __FUNCTION__); static oid clientRedirectTableOID[] = { 1, 3, 6, 1, 4, 1, 1457, 4, 1, 1, 10 }; netsnmp_handler_registration * reg{}; reg = netsnmp_create_handler_registration(HANDLER_NAME, handler, clientRedirectTableOID, OID_LENGTH(clientRedirectTableOID), HANDLER_CAN_RONLY); netsnmp_table_registration_info * table_info{}; table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info); if(!table_info) { syslog(LOG_CRIT, ""ERROR: SNMP_MALLOC_TYPEDEF.""); return false; } netsnmp_table_helper_add_indexes(table_info, ASN_INTEGER, 0); table_info->min_column = COLUMN_CLIENT_REDIRECT; table_info->max_column = COLUMN_CLIENT_REDIRECT_COUNT; netsnmp_iterator_info *iinfo{}; iinfo = SNMP_MALLOC_TYPEDEF(netsnmp_iterator_info); iinfo->get_first_data_point = (Netsnmp_First_Data_Point *) first_datapt; iinfo->get_next_data_point = (Netsnmp_Next_Data_Point *) next_datapt; iinfo->table_reginfo = table_info; if(netsnmp_register_table_iterator(reg, iinfo) != SNMPERR_SUCCESS) { syslog(LOG_CRIT, ""ERROR: netsnmp_register_table_iterator.""); return false; } syslog(LOG_DEBUG, ""Exit: %s."", __FUNCTION__); return true; } //******************************************************************************** // Function: first_datapt // // Description: Returns first data point of clientRedirectTable. //******************************************************************************** static netsnmp_variable_list * first_datapt(void ** loop_context, void **data_context, netsnmp_variable_list * put_index_data, netsnmp_iterator_info * data) { load_table(); if(!g_clientRedirectTable.size()) { *data_context = (void*) 0; *loop_context = (void*) 0; return NULL; } *loop_context = (void*) g_clientRedirectTable.data(); return next_datapt(loop_context, data_context, put_index_data, data); } //******************************************************************************** // Function: next_datapt // // Description: Returns next data point of clientRedirectTable. //******************************************************************************** static netsnmp_variable_list * next_datapt(void ** loop_context, void ** data_context, netsnmp_variable_list * put_index_data, netsnmp_iterator_info * data) { if(!g_clientRedirectTable.size()) return NULL; clientRedirectTable_t * pd = (clientRedirectTable_t *) *loop_context; clientRedirectTable_t * end = g_clientRedirectTable.data(); end += g_clientRedirectTable.size(); if(pd == end) return NULL; netsnmp_variable_list *idx = put_index_data; snmp_set_var_typed_integer(idx, ASN_INTEGER, pd->clientRedirectIdx); *data_context = (void*) pd; *loop_context = (void*) ++pd; return put_index_data; } //******************************************************************************** // Function: handler // // Description: Handle clientRedirectTable get request. //******************************************************************************** static int handler(netsnmp_mib_handler * handler, netsnmp_handler_registration * reginfo, netsnmp_agent_request_info * reqinfo, netsnmp_request_info * requests) { syslog(LOG_DEBUG, ""Enter: handler, %s."", HANDLER_NAME); syslog(LOG_DEBUG, ""handler, continuing delayed request, mode = %d."", reqinfo->mode); requests->delegated = 1; snmp_alarm_register(0, 0, delayed_response, (void *) netsnmp_create_delegated_cache(handler, reginfo, reqinfo, requests, NULL)); syslog(LOG_DEBUG, ""Exit: handler, %s."", HANDLER_NAME); return SNMP_ERR_NOERROR; } //******************************************************************************** // Function: delayed_response // // Description: handle table query in callback. //******************************************************************************** static void delayed_response(unsigned int clientreg, void * clientarg) { syslog(LOG_DEBUG, ""Enter: delayed_response, %s."", HANDLER_NAME); netsnmp_delegated_cache *cache = (netsnmp_delegated_cache *) clientarg; if(!netsnmp_handler_check_cache(cache)) { syslog(LOG_ERR, ""%s %s: bad_cache."", HANDLER_NAME, __FUNCTION__); return; } syslog(LOG_DEBUG, ""delayed_instance, continuing delayed request, mode = %d."", cache->reqinfo->mode); cache->requests->delegated = 0; if(cache->reqinfo->mode != MODE_GET && cache->reqinfo->mode != MODE_GETNEXT) return; for(netsnmp_request_info * request = cache->requests; request; request = request->next) { clientRedirectTable_t * c = (clientRedirectTable_t *) netsnmp_extract_iterator_context(request); if(!c) { netsnmp_set_request_error(cache->reqinfo, request, SNMP_NOSUCHINSTANCE); g_clientRedirectTable.clear(); continue; } netsnmp_table_request_info *table_info = netsnmp_extract_table_info(request); if(!table_info) { syslog(LOG_CRIT, ""ERROR: netsnmp_tdata_extract_table_info""); continue; } switch (table_info->colnum) { case COLUMN_CLIENT_REDIRECT: snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR, (unsigned char*) c->clientRedirect, strlen(c->clientRedirect)); break; case COLUMN_CLIENT_REDIRECT_COUNT: snmp_set_var_typed_integer(request->requestvb, ASN_COUNTER, c->clientRedirectCount); break; default: netsnmp_set_request_error(cache->reqinfo, request, SNMP_NOSUCHOBJECT); } } netsnmp_free_delegated_cache(cache); syslog(LOG_DEBUG, ""Exit: delayed_response, %s."", HANDLER_NAME); syslog(LOG_DEBUG,""%s"", ""===============================================================""); return; } //******************************************************************************** // Function: load_table // // Description: Pull elements from tcache_plane into clientRedirectTable. //******************************************************************************** static void load_table(void) { if(g_clientRedirectTable.size()) return; void *context = zmq_ctx_new(); void *requester = zmq_socket(context, ZMQ_REQ); int32_t [MASK] {}; zmq_setsockopt(requester, ZMQ_LINGER, (void*) & [MASK] , sizeof( [MASK] )); char buffer[64]; sprintf(buffer, ""tcp://localhost:%d"", TCPLANE_SERVICE); zmq_connect(requester, buffer); sprintf(buffer, ""%d"", clientRedirectTable); zmq_send(requester, buffer, strlen(buffer), 0); int idx = 0; while(true) { size_t size = timed_read(requester, buffer, sizeof(buffer), READ_TIMEOUT); if(!size) break; if(strcmp(buffer, ""END"") == 0) break; char * key, * value; key = strtok_r(buffer, ""|"", &value); if(value) { clientRedirectTable_t c; c.clientRedirectIdx = idx++; strcpy(c.clientRedirect, key); c.clientRedirectCount = atoi(value); g_clientRedirectTable.push_back(c); } size = sizeof(size_t); int rcvmore{}; zmq_getsockopt(requester, ZMQ_RCVMORE, (void*) &rcvmore, &size); if(!rcvmore) break; } zmq_close(requester); zmq_ctx_destroy(context); return; } ",timeo 391,"#include #include ""../include/ptx_builder.h"" // Build a simple AXPY kernel using the PTX builder API. // The kernel performs: y = a * x + y for a single element. // This example generates PTX text and prints it to stdout. std::string build_axpy_kernel() { using namespace ptx; Builder b; Reg rA(""%f0""); Reg rX(""%f1""); Reg rY(""%f2""); // rY = a * x + y b.mad(rY, rA, rX, rY); b.ret(); std::ostringstream [MASK] ; [MASK] << "".version 8.7\n""; [MASK] << "".target sm_80\n""; [MASK] << "".address_size 64\n\n""; [MASK] << "".visible .entry axpy_one(\n""; [MASK] << "" .param .f32 a,\n""; [MASK] << "" .param .f32 x,\n""; [MASK] << "" .param .f32 y\n""; [MASK] << "")\n""; [MASK] << ""{\n""; [MASK] << "" .reg .f32 %f0, %f1, %f2;\n""; [MASK] << b.str(); [MASK] << ""}\n""; return [MASK] .str(); } int main() { std::cout << build_axpy_kernel(); return 0; } ",oss 392,"#ifndef _ADX_NET_H_ #define _ADX_NET_H_ #include ""net.h"" #include ""util.h"" #include ""message_types.h"" #include #define SELLER_IDX 0 #define ALL_BIDDERS -1 // Macro that simplifies writing read_cb() functions #define PROCESS_REQ(type_name) \ do { \ type_name req; \ ret = parse_message(data, &req); \ check_ret(ret, ""parse_message()""); \ process_##type_name(conn_idx, req); \ } while (0); struct auction_context { uint32_t id; std::map bids; // map from conn_idx to bid std::map ad_tags; std::pair outcome; // conn_idx and price }; class adx_server { public: adx_server() : conn_(), auctions_ctx_() {} ~adx_server() {} //----- Initialization functions -----// // Initialize net objects for seller and bidders // Also initializes the connection for the bidders, but not // the seller (call init_seller_conn to do that). void init_conn(int num, str hosts[], int ports[]); // Initializes the connection to the seller. void init_seller_conn(str host, int port); //----- Handle events ------// // Handle writing from msgpack structures template void a_write(int conn_idx, uint8_t type, const T &req) { msgpack::sbuffer buf; msgpack::pack(&buf, req); strbuf [MASK] ; [MASK] << str((char*) &type, 1) << str(buf.data(), buf.size()); if (conn_idx == ALL_BIDDERS) { for (int i = 1; i < (int) conn_.size(); ++i) conn_[i]->a_write( [MASK] ); } else { conn_[conn_idx]->a_write( [MASK] ); } } // Read callback // conn_idx can be thought of as a ""bidder_id"" // conn_idx = 0 implies the seller. void read_cb(int conn_idx, strbuf data); // Handle requests void process_a_req(int conn_idx, const a_req &req); void process_b_sub(int conn_idx, const b_sub &req); // Compute the auction std::pair compute_auction(auction_context *ctx); // Report the outcome void report_outcome(auction_context *ctx); private: vec > conn_; std::map auctions_ctx_; }; #endif ",send_data 393,"/* Copyright Acrolinx GmbH */ // CheckOptions.cpp : Implementation of CCheckOptions #include ""stdafx.h"" #include ""CheckOptions.h"" // CCheckOptions using namespace Acrolinx_Sdk_Sidebar_Util; STDMETHODIMP CCheckOptions::GetSelection(VARIANT_BOOL* selection) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); ACROASSERT(m_isInstanceCreated == TRUE, ""Initialize Checkoptions object by calling InitInstance() before using it""); BOOL [MASK] = m_checkOptions.HasMember(_T(""selection"")) ? m_checkOptions[_T(""selection"")].GetBool() : FALSE; if(selection == nullptr) { LOGE << ""Create out bool var before calling GetSelection()""; } else { *selection = (VARIANT_BOOL) [MASK] ; } return S_OK; } STDMETHODIMP CCheckOptions::InitInstance(BSTR checkOptions) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); if(!Instantiate()) { return S_FALSE; } ASSERT(checkOptions != nullptr); CString jsonString(checkOptions); if( jsonString.IsEmpty()) { jsonString = _T(""{}""); } CJsonUtil::Parse(jsonString, m_checkOptions); return S_OK; } ",retVal 394,"#include""misc.h"" /* for version-control appl'n: binary to hex.. .. ideally would use stdin instead of file for version control: generate hexdiffs so we don't lose any special characters, etc. */ int main(int argc, char ** argv){ str fn; str fnf_fn(""./.b2h""); str fnf_fnp(fnf_fn + str(""p"")); unsigned char c; const char * f_n; size_t i = 0; size_t f_p = 0; if(argc > 1){ f_n, fn = argv[1], str(argv[1]); ofstream f(fnf_fn); f << fn; f.close(); ofstream g(fnf_fnp); g << 0; g.close(); } else{ ifstream g(fnf_fnp); g >> f_p; g.close(); } if(fsize(fnf_fn) == (size_t)0) err(""b2h [file name]""); ifstream fnf(fnf_fn); fnf >> fn; fnf.close(); f_n = fn.c_str(); FILE * f = fopen(f_n, ""rb""); if(!f) err(str(""failed to open file: "") + str(f_n)); size_t [MASK] = size(f); if(f_p >= [MASK] - 1){ system((str(""rm -f "") + fnf_fn).c_str()); system((str(""rm -f "") + fnf_fnp).c_str()); exit(0); } printf(""%s%d%s\n\n "", KNRM, f_p, KGRN); unsigned long int l_i, c_i; l_i = c_i = 0; fseek(f, f_p, SEEK_SET); for(i = f_p; i < [MASK] ; i++){ c = fgetc(f); printf(""%.2X"", (unsigned char)c); if(++c_i % 32 == 0){ if(++ l_i > 32) break; printf(""\n ""); } } ofstream g(fnf_fnp); g << string(to_string(++i)); g.close(); printf(""\n\n%s%d\n"", KNRM, i); return 0; }",f_s 395,"/* * Copyright (C) 2024 Microchip Technology Inc. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __MAINWIN_H__ #define __MAINWIN_H__ #include #include #include ""version.h"" #include ""libconfig.h++"" #include ""libuboot.h"" using namespace std; using namespace egt; using namespace egt::experimental; static const std::string EGT_SWUPDATE_VERSION = std::to_string(EGT_SWUPDATE_VERSION_MAJOR) + ""."" + std::to_string(EGT_SWUPDATE_VERSION_MINOR) + ""."" + std::to_string(EGT_SWUPDATE_VERSION_PATCH); inline static const std::vector ubootEnvVars = {""upgrade_available"", ""bootcount"", ""ustate""}; inline static const std::vector ustateVal = {""0"", ""1"", ""2"", ""3"", ""4"", ""5"", ""6"", ""7""}; #define HASH_CHUNK_SIZE 4096 typedef enum ubootEnvVars_t { ENV_UPGRADE = 0, ENV_BOOTCNT, ENV_USTATE, ENV_MAX, } ubootEnvVars_t; typedef enum ustate_t { STATE_OK = 0, STATE_INSTALLED = 1, STATE_TESTING = 2, STATE_FAILED = 3, STATE_NOT_AVAILABLE = 4, STATE_ERROR = 5, STATE_WAIT = 6, STATE_IN_PROGRESS = 7, STATE_LAST = STATE_IN_PROGRESS } ustate_t; class RebootWindow : public egt::Popup { public: explicit RebootWindow() : egt::Popup(egt::Application::instance().screen()->size() / 2) { colorSwitch = 0; this->color(Palette::ColorId::bg, Palette::red); rebootCnt = 30; rebootWarn = Label(""Update Available! Rebooting in "" + std::to_string(rebootCnt)); add(egt::center(rebootWarn)); cancel = Button(""Cancel""); cancel.align(egt::AlignFlag::right | egt::AlignFlag::bottom); add(cancel); cancel.on_click([this](egt::Event&) { cout << ""Cancelling reboot..."" << endl; rebootTimer.stop(); this->hide(); }); rebootTimer = PeriodicTimer(std::chrono::seconds(1)); rebootTimer.on_timeout([this]() { if (colorSwitch) { colorSwitch ^= 1; this->color(Palette::ColorId::bg, Palette::red); } else { colorSwitch ^= 1; this->color(Palette::ColorId::bg, Palette::yellow); } if (rebootCnt-- == 0) { system(""/usr/sbin/reboot""); } else { rebootWarn.text(""Update Available! Rebooting in "" + std::to_string(rebootCnt)); } }); } void startRebootTimer(size_t [MASK] ) { rebootCnt = [MASK] ; rebootWarn.text(""Rebooting in "" + std::to_string(rebootCnt)); rebootTimer.start(); } protected: Label rebootWarn; Button cancel; size_t rebootCnt; PeriodicTimer rebootTimer; size_t colorSwitch; private: }; class MainWindow : public TopWindow { public: MainWindow(std::string const cfg); virtual ~MainWindow(); private: std::string getTime(void); std::string getTime(ssize_t future); bool readConfigFile(std::string cfgFile); bool getAttrFromCfg(std::string node, std::string attr, std::string& val); bool getAttrFromCfg(std::string node, std::string subnode, std::string key, std::string& val); void getServerAttrs(void); size_t initUbootEnvAccess(void); size_t setUbootEnvVar(ubootEnvVars_t var, std::string val); size_t writeUbootVarToEnv(ubootEnvVars_t var, std::string val); size_t setUpdateAvailableInUbootEnv(void); void checkIfUpdated(void); bool hashAppData(std::string file, std::string& digest); bool pollHawkbitServer(void); bool sendMsgToHawkbitServer(void); PeriodicTimer cpuTimer; CPUMonitorUsage cpuMon; std::shared_ptr