hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
e6561561ff1441ce3424dcc2ce02511e2e8d0c9c
757
cc
C++
ps-lite/guide/example_d.cc
CNevd/SVDFeature
2ac6d94e8b885d4f36178ab544f1c605c22656e8
[ "Apache-2.0" ]
8
2016-06-12T08:06:46.000Z
2018-04-11T20:34:50.000Z
ps-lite/guide/example_d.cc
CNevd/SVDFeature
2ac6d94e8b885d4f36178ab544f1c605c22656e8
[ "Apache-2.0" ]
null
null
null
ps-lite/guide/example_d.cc
CNevd/SVDFeature
2ac6d94e8b885d4f36178ab544f1c605c22656e8
[ "Apache-2.0" ]
9
2016-08-01T05:58:28.000Z
2020-05-06T11:09:53.000Z
#include "ps.h" typedef float Val; DEFINE_int32(nt, 1, "num of server threads"); int CreateServerNode(int argc, char *argv[]) { ps::OnlineServer<Val> server(ps::IOnlineHandle<Val>(), 1, FLAGS_nt); return 0; } int WorkerNodeMain(int argc, char *argv[]) { using namespace ps; int n = 1000000; auto key = std::make_shared<std::vector<Key>>(n); for (int i = 0; i < n; ++i) (*key)[i] = kMaxKey / n * i; auto val = std::make_shared<std::vector<Val>>(n, 1.0); KVWorker<Val> wk; std::vector<Val> recv_val; for (int i = 0; i < 10; ++i) { SyncOpts opts; opts.AddFilter(Filter::KEY_CACHING); opts.AddFilter(Filter::COMPRESSING); wk.Wait(wk.ZPush(key, val, opts)); wk.Wait(wk.ZPull(key, &recv_val, opts)); } return 0; }
25.233333
70
0.630119
CNevd
e65e16c48f7fd9ad68a9176a47e4333fa2b20780
8,098
cpp
C++
src/FMILP.cpp
KohlbacherLab/libgrbfrc
068bb77941d101d3864702db04afa5df6b9a4579
[ "BSD-3-Clause" ]
null
null
null
src/FMILP.cpp
KohlbacherLab/libgrbfrc
068bb77941d101d3864702db04afa5df6b9a4579
[ "BSD-3-Clause" ]
null
null
null
src/FMILP.cpp
KohlbacherLab/libgrbfrc
068bb77941d101d3864702db04afa5df6b9a4579
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <cmath> #include "CharnesCooper.hpp" #include "Dinkelbach.hpp" #include "YGGY.hpp" #include "FMILP.hpp" namespace grbfrc { FMILP::FMILP(GRBEnv& env, GRBLinExpr objNumerator, GRBLinExpr objDenominator, int objSense) : baseModel { new GRBModel(env) } { objective.numerator = objNumerator; objective.denominator = objDenominator; baseModel->setObjective(objDenominator); objective.sense = objSense; objective.uniSign = UniSignStatus::maybe; solution = nullptr; } FMILP::FMILP(GRBEnv& grbEnv) : FMILP(grbEnv, 0.0, 0.0, GRB_MAXIMIZE) { objective.uniSign = UniSignStatus::yes; } FMILP::FMILP(GRBEnv& grbEnv, GRBLinExpr objNumerator, GRBLinExpr objDenominator) : FMILP(grbEnv, objNumerator, objDenominator, GRB_MAXIMIZE) { } FMILP::FMILP(GRBEnv& grbEnv, int objSense) : FMILP(grbEnv, 0.0, 0.0, objSense) { objective.uniSign = UniSignStatus::yes; } GRBModel FMILP::baseModelCopy() { return *baseModel; } FMILP FMILP::copy() { return *this; } int FMILP::get(GRB_IntAttr attr) { return baseModel->get(attr); } double FMILP::get(GRB_DoubleAttr attr) { return baseModel->get(attr); } std::string FMILP::get(GRB_StringAttr attr) { return baseModel->get(attr); } void FMILP::set(GRB_IntAttr attr, int val) { baseModel->set(attr, val); } void FMILP::set(GRB_DoubleAttr attr, double val) { baseModel->set(attr, val); } void FMILP::set(GRB_StringAttr attr, std::string val) { baseModel->set(attr, val); } void FMILP::set(GRB_IntParam param, int val) { baseModel->set(param, val); } void FMILP::set(GRB_DoubleParam param, double val) { baseModel->set(param, val); } void FMILP::set(GRB_StringParam param, std::string val) { baseModel->set(param, val); } void FMILP::setEnv(GRB_IntParam para, int val) { (baseModel->getEnv()).set(para, val); } GRBVar& FMILP::addVar(double lowerBound, double upperBound, char type, std::string name) { vars.push_back(new GRBVar(baseModel->addVar(lowerBound, upperBound, 0.0, type, name))); return *(vars.back()); } GRBVar& FMILP::addVar(double lowerBound, double upperBound, double numeratorCoeff, double denominatorCoeff, char type, std::string name) { vars.push_back(new GRBVar(baseModel->addVar(lowerBound, upperBound, denominatorCoeff, type, name))); objective.numerator += numeratorCoeff * (*(vars.back())); objective.denominator += denominatorCoeff * (*(vars.back())); return *(vars.back()); } void FMILP::setStartSolution(GRBVar& var, double val) { if (!startSol) startSol = new std::vector<double>(vars.size()); else startSol->resize(vars.size()); int index { 0 }; for (GRBVar* varp : vars) { if (varp->sameAs(var)) (*startSol)[index] = val; index++; } } GRBVar* FMILP::getVars() { return baseModel->getVars(); } void FMILP::update() { baseModel->update(); } void FMILP::setObjNumerator(GRBLinExpr& objNumerator) { objective.numerator = objNumerator; } void FMILP::setObjDenominator(GRBLinExpr& objDenominator) { objective.denominator = objDenominator; } int FMILP::getObjSense() { return objective.sense; } void FMILP::setObjSense(int objSense) { objective.sense = objSense; baseModel->set(GRB_IntAttr_ModelSense, objSense); } void FMILP::addConstr(const GRBLinExpr lhsExpr, char sense, const GRBLinExpr rhsExpr, std::string name) { baseModel->addConstr(lhsExpr, sense, rhsExpr, name); } void FMILP::addConstr(const GRBLinExpr lhsExpr, char sense, GRBVar rhsVar, std::string name) { baseModel->addConstr(lhsExpr, sense, rhsVar, name); } void FMILP::addConstr(const GRBLinExpr lhsExpr, char sense, double rhsVal, std::string name) { baseModel->addConstr(lhsExpr, sense, rhsVal, name); } void FMILP::addConstr(GRBVar lhsVar, char sense, GRBVar rhsVar, std::string name) { baseModel->addConstr(lhsVar, sense, rhsVar, name); } void FMILP::addConstr(GRBVar lhsVar, char sense, double rhsVal, std::string name) { baseModel->addConstr(lhsVar, sense, rhsVal, name); } void FMILP::addConstr(GRBTempConstr tc, std::string name) { baseModel->addConstr(tc, name); } void FMILP::addConstr(const GRBLinExpr expr, double lower, double upper) { baseModel->addConstr(expr, GRB_GREATER_EQUAL, lower); baseModel->addConstr(expr, GRB_LESS_EQUAL, upper); } GRBConstr* FMILP::getConstrs() { return baseModel->getConstrs(); } GRBLinExpr FMILP::getRow(GRBConstr& constr) { return baseModel->getRow(constr); } bool FMILP::isFLP() { if (baseModel->get(GRB_IntAttr_NumIntVars) == 0) return true; else return false; } bool FMILP::checkUnisignance(std::string sign) { /** * * test */ if (sign == "positive") baseModel->setObjective(objective.denominator, GRB_MINIMIZE); else if (sign == "negative") baseModel->setObjective(objective.denominator, GRB_MAXIMIZE); baseModel->optimize(); if (sign == "positive" && baseModel->get(GRB_IntAttr_Status) == GRB_OPTIMAL) { if (baseModel->get(GRB_DoubleAttr_ObjVal) > 0) { objective.uniSign = UniSignStatus::yes; return true; } else return false ; } else return false; if (sign == "negative" && baseModel->get(GRB_IntAttr_Status) == GRB_OPTIMAL) { if (baseModel->get(GRB_DoubleAttr_ObjVal) < 0) { objective.uniSign = UniSignStatus::yes; return true; } else return false; } else return false; } bool FMILP::isUnisignant() { /** test * \callgraph * * */ if (checkUnisignance("positive")) { objective.uniSign = UniSignStatus::yes; return true; } else if (checkUnisignance("negative")) { objective.uniSign = UniSignStatus::yes; return true; } else { objective.uniSign = UniSignStatus::no; return false; } } double FMILP::getObjVal() { return solution->objVal; } double FMILP::getVal(GRBVar& var) { int index { 0 }; for (GRBVar* varp : vars) { if (varp->sameAs(var)) return (solution->varVals)[index]; index++; } return 0.0; // bad } /* void FMILP::runCharnesCooper(int time_limit) { baseModel->update(); CharnesCooper chaco(*this); chaco.run(time_limit); chaco.writeSolution(); } void FMILP::runCharnesCooper(GRBCallback& callback, int time_limit) { baseModel->update(); CharnesCooper chaco(*this); chaco.run(callback, time_limit); chaco.writeSolution(); } */ /* GRBModel FMILP::getCharnesCooperTransform() { CharnesCooper chaco(*this); return chaco.getTransform(); } GRBModel FMILP::getYGGYTransform() { GRBModel model(baseModel->getEnv()); return model; } */ void FMILP::printSolution() { if (solution) { std::cout << "\n########################### Solution ############################\n\n"; for (int i = 0; i < baseModel->get(GRB_IntAttr_NumVars); i++) { double varval { solution->varVals[i] }; if (varval == 0.0) varval = std::abs(varval); std::cout << vars[i]->get(GRB_StringAttr_VarName) << ": " << varval << std::endl; } std::cout << std::endl; std::cout << "ObjVal: " << solution->objVal << std::endl; std::cout << "\n#################################################################\n\n"; } else std::cout << "There is no solution to print!" << std::endl; } } // namespace grbfrc
25.071207
102
0.602371
KohlbacherLab
e65e64412899cc51eff7f71926b4944f7b717f37
66,428
cpp
C++
Util/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp
ianloic/unladen-swallow
28148f4ddbb3d519042de1f9fc9f1356fdd31e31
[ "PSF-2.0" ]
5
2020-06-30T05:06:40.000Z
2021-05-24T08:38:33.000Z
Util/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp
ianloic/unladen-swallow
28148f4ddbb3d519042de1f9fc9f1356fdd31e31
[ "PSF-2.0" ]
null
null
null
Util/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp
ianloic/unladen-swallow
28148f4ddbb3d519042de1f9fc9f1356fdd31e31
[ "PSF-2.0" ]
2
2015-10-01T18:28:20.000Z
2020-09-09T16:25:27.000Z
//===- PPCRegisterInfo.cpp - PowerPC Register Information -------*- C++ -*-===// // // 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 PowerPC implementation of the TargetRegisterInfo // class. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "reginfo" #include "PPC.h" #include "PPCInstrBuilder.h" #include "PPCMachineFunctionInfo.h" #include "PPCRegisterInfo.h" #include "PPCFrameInfo.h" #include "PPCSubtarget.h" #include "llvm/CallingConv.h" #include "llvm/Constants.h" #include "llvm/Function.h" #include "llvm/Type.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineLocation.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/BitVector.h" #include "llvm/ADT/STLExtras.h" #include <cstdlib> using namespace llvm; // FIXME This disables some code that aligns the stack to a boundary // bigger than the default (16 bytes on Darwin) when there is a stack local // of greater alignment. This does not currently work, because the delta // between old and new stack pointers is added to offsets that reference // incoming parameters after the prolog is generated, and the code that // does that doesn't handle a variable delta. You don't want to do that // anyway; a better approach is to reserve another register that retains // to the incoming stack pointer, and reference parameters relative to that. #define ALIGN_STACK 0 // FIXME (64-bit): Eventually enable by default. cl::opt<bool> EnablePPC32RS("enable-ppc32-regscavenger", cl::init(false), cl::desc("Enable PPC32 register scavenger"), cl::Hidden); cl::opt<bool> EnablePPC64RS("enable-ppc64-regscavenger", cl::init(false), cl::desc("Enable PPC64 register scavenger"), cl::Hidden); #define EnableRegisterScavenging \ ((EnablePPC32RS && !Subtarget.isPPC64()) || \ (EnablePPC64RS && Subtarget.isPPC64())) // FIXME (64-bit): Should be inlined. bool PPCRegisterInfo::requiresRegisterScavenging(const MachineFunction &) const { return EnableRegisterScavenging; } /// getRegisterNumbering - Given the enum value for some register, e.g. /// PPC::F14, return the number that it corresponds to (e.g. 14). unsigned PPCRegisterInfo::getRegisterNumbering(unsigned RegEnum) { using namespace PPC; switch (RegEnum) { case 0: return 0; case R0 : case X0 : case F0 : case V0 : case CR0: case CR0LT: return 0; case R1 : case X1 : case F1 : case V1 : case CR1: case CR0GT: return 1; case R2 : case X2 : case F2 : case V2 : case CR2: case CR0EQ: return 2; case R3 : case X3 : case F3 : case V3 : case CR3: case CR0UN: return 3; case R4 : case X4 : case F4 : case V4 : case CR4: case CR1LT: return 4; case R5 : case X5 : case F5 : case V5 : case CR5: case CR1GT: return 5; case R6 : case X6 : case F6 : case V6 : case CR6: case CR1EQ: return 6; case R7 : case X7 : case F7 : case V7 : case CR7: case CR1UN: return 7; case R8 : case X8 : case F8 : case V8 : case CR2LT: return 8; case R9 : case X9 : case F9 : case V9 : case CR2GT: return 9; case R10: case X10: case F10: case V10: case CR2EQ: return 10; case R11: case X11: case F11: case V11: case CR2UN: return 11; case R12: case X12: case F12: case V12: case CR3LT: return 12; case R13: case X13: case F13: case V13: case CR3GT: return 13; case R14: case X14: case F14: case V14: case CR3EQ: return 14; case R15: case X15: case F15: case V15: case CR3UN: return 15; case R16: case X16: case F16: case V16: case CR4LT: return 16; case R17: case X17: case F17: case V17: case CR4GT: return 17; case R18: case X18: case F18: case V18: case CR4EQ: return 18; case R19: case X19: case F19: case V19: case CR4UN: return 19; case R20: case X20: case F20: case V20: case CR5LT: return 20; case R21: case X21: case F21: case V21: case CR5GT: return 21; case R22: case X22: case F22: case V22: case CR5EQ: return 22; case R23: case X23: case F23: case V23: case CR5UN: return 23; case R24: case X24: case F24: case V24: case CR6LT: return 24; case R25: case X25: case F25: case V25: case CR6GT: return 25; case R26: case X26: case F26: case V26: case CR6EQ: return 26; case R27: case X27: case F27: case V27: case CR6UN: return 27; case R28: case X28: case F28: case V28: case CR7LT: return 28; case R29: case X29: case F29: case V29: case CR7GT: return 29; case R30: case X30: case F30: case V30: case CR7EQ: return 30; case R31: case X31: case F31: case V31: case CR7UN: return 31; default: llvm_unreachable("Unhandled reg in PPCRegisterInfo::getRegisterNumbering!"); } } PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST, const TargetInstrInfo &tii) : PPCGenRegisterInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP), Subtarget(ST), TII(tii) { ImmToIdxMap[PPC::LD] = PPC::LDX; ImmToIdxMap[PPC::STD] = PPC::STDX; ImmToIdxMap[PPC::LBZ] = PPC::LBZX; ImmToIdxMap[PPC::STB] = PPC::STBX; ImmToIdxMap[PPC::LHZ] = PPC::LHZX; ImmToIdxMap[PPC::LHA] = PPC::LHAX; ImmToIdxMap[PPC::LWZ] = PPC::LWZX; ImmToIdxMap[PPC::LWA] = PPC::LWAX; ImmToIdxMap[PPC::LFS] = PPC::LFSX; ImmToIdxMap[PPC::LFD] = PPC::LFDX; ImmToIdxMap[PPC::STH] = PPC::STHX; ImmToIdxMap[PPC::STW] = PPC::STWX; ImmToIdxMap[PPC::STFS] = PPC::STFSX; ImmToIdxMap[PPC::STFD] = PPC::STFDX; ImmToIdxMap[PPC::ADDI] = PPC::ADD4; // 64-bit ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8; ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8; ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8; ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX; ImmToIdxMap[PPC::ADDI8] = PPC::ADD8; ImmToIdxMap[PPC::STD_32] = PPC::STDX_32; } /// getPointerRegClass - Return the register class to use to hold pointers. /// This is used for addressing modes. const TargetRegisterClass * PPCRegisterInfo::getPointerRegClass(unsigned Kind) const { if (Subtarget.isPPC64()) return &PPC::G8RCRegClass; return &PPC::GPRCRegClass; } const unsigned* PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { // 32-bit Darwin calling convention. static const unsigned Darwin32_CalleeSavedRegs[] = { PPC::R13, PPC::R14, PPC::R15, PPC::R16, PPC::R17, PPC::R18, PPC::R19, PPC::R20, PPC::R21, PPC::R22, PPC::R23, PPC::R24, PPC::R25, PPC::R26, PPC::R27, PPC::R28, PPC::R29, PPC::R30, PPC::R31, PPC::F14, PPC::F15, PPC::F16, PPC::F17, PPC::F18, PPC::F19, PPC::F20, PPC::F21, PPC::F22, PPC::F23, PPC::F24, PPC::F25, PPC::F26, PPC::F27, PPC::F28, PPC::F29, PPC::F30, PPC::F31, PPC::CR2, PPC::CR3, PPC::CR4, PPC::V20, PPC::V21, PPC::V22, PPC::V23, PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31, PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN, PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN, PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN, PPC::LR, 0 }; // 32-bit SVR4 calling convention. static const unsigned SVR4_CalleeSavedRegs[] = { PPC::R14, PPC::R15, PPC::R16, PPC::R17, PPC::R18, PPC::R19, PPC::R20, PPC::R21, PPC::R22, PPC::R23, PPC::R24, PPC::R25, PPC::R26, PPC::R27, PPC::R28, PPC::R29, PPC::R30, PPC::R31, PPC::F14, PPC::F15, PPC::F16, PPC::F17, PPC::F18, PPC::F19, PPC::F20, PPC::F21, PPC::F22, PPC::F23, PPC::F24, PPC::F25, PPC::F26, PPC::F27, PPC::F28, PPC::F29, PPC::F30, PPC::F31, PPC::CR2, PPC::CR3, PPC::CR4, PPC::VRSAVE, PPC::V20, PPC::V21, PPC::V22, PPC::V23, PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31, PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN, PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN, PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN, 0 }; // 64-bit Darwin calling convention. static const unsigned Darwin64_CalleeSavedRegs[] = { PPC::X14, PPC::X15, PPC::X16, PPC::X17, PPC::X18, PPC::X19, PPC::X20, PPC::X21, PPC::X22, PPC::X23, PPC::X24, PPC::X25, PPC::X26, PPC::X27, PPC::X28, PPC::X29, PPC::X30, PPC::X31, PPC::F14, PPC::F15, PPC::F16, PPC::F17, PPC::F18, PPC::F19, PPC::F20, PPC::F21, PPC::F22, PPC::F23, PPC::F24, PPC::F25, PPC::F26, PPC::F27, PPC::F28, PPC::F29, PPC::F30, PPC::F31, PPC::CR2, PPC::CR3, PPC::CR4, PPC::V20, PPC::V21, PPC::V22, PPC::V23, PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31, PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN, PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN, PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN, PPC::LR8, 0 }; // 64-bit SVR4 calling convention. static const unsigned SVR4_64_CalleeSavedRegs[] = { PPC::X14, PPC::X15, PPC::X16, PPC::X17, PPC::X18, PPC::X19, PPC::X20, PPC::X21, PPC::X22, PPC::X23, PPC::X24, PPC::X25, PPC::X26, PPC::X27, PPC::X28, PPC::X29, PPC::X30, PPC::X31, PPC::F14, PPC::F15, PPC::F16, PPC::F17, PPC::F18, PPC::F19, PPC::F20, PPC::F21, PPC::F22, PPC::F23, PPC::F24, PPC::F25, PPC::F26, PPC::F27, PPC::F28, PPC::F29, PPC::F30, PPC::F31, PPC::CR2, PPC::CR3, PPC::CR4, PPC::VRSAVE, PPC::V20, PPC::V21, PPC::V22, PPC::V23, PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31, PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN, PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN, PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN, 0 }; if (Subtarget.isDarwinABI()) return Subtarget.isPPC64() ? Darwin64_CalleeSavedRegs : Darwin32_CalleeSavedRegs; return Subtarget.isPPC64() ? SVR4_64_CalleeSavedRegs : SVR4_CalleeSavedRegs; } const TargetRegisterClass* const* PPCRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const { // 32-bit Darwin calling convention. static const TargetRegisterClass * const Darwin32_CalleeSavedRegClasses[] = { &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass, &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass, &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass, &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass, &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, &PPC::GPRCRegClass, 0 }; // 32-bit SVR4 calling convention. static const TargetRegisterClass * const SVR4_CalleeSavedRegClasses[] = { &PPC::GPRCRegClass,&PPC::GPRCRegClass, &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass, &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass, &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass, &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass, &PPC::VRSAVERCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, 0 }; // 64-bit Darwin calling convention. static const TargetRegisterClass * const Darwin64_CalleeSavedRegClasses[] = { &PPC::G8RCRegClass,&PPC::G8RCRegClass, &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass, &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass, &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass, &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, &PPC::G8RCRegClass, 0 }; // 64-bit SVR4 calling convention. static const TargetRegisterClass * const SVR4_64_CalleeSavedRegClasses[] = { &PPC::G8RCRegClass,&PPC::G8RCRegClass, &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass, &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass, &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass, &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::F8RCRegClass,&PPC::F8RCRegClass, &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass, &PPC::VRSAVERCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass, &PPC::CRBITRCRegClass, 0 }; if (Subtarget.isDarwinABI()) return Subtarget.isPPC64() ? Darwin64_CalleeSavedRegClasses : Darwin32_CalleeSavedRegClasses; return Subtarget.isPPC64() ? SVR4_64_CalleeSavedRegClasses : SVR4_CalleeSavedRegClasses; } // needsFP - Return true if the specified function should have a dedicated frame // pointer register. This is true if the function has variable sized allocas or // if frame pointer elimination is disabled. // static bool needsFP(const MachineFunction &MF) { const MachineFrameInfo *MFI = MF.getFrameInfo(); return NoFramePointerElim || MFI->hasVarSizedObjects() || (PerformTailCallOpt && MF.getInfo<PPCFunctionInfo>()->hasFastCall()); } static bool spillsCR(const MachineFunction &MF) { const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); return FuncInfo->isCRSpilled(); } BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const { BitVector Reserved(getNumRegs()); Reserved.set(PPC::R0); Reserved.set(PPC::R1); Reserved.set(PPC::LR); Reserved.set(PPC::LR8); Reserved.set(PPC::RM); // The SVR4 ABI reserves r2 and r13 if (Subtarget.isSVR4ABI()) { Reserved.set(PPC::R2); // System-reserved register Reserved.set(PPC::R13); // Small Data Area pointer register } // On PPC64, r13 is the thread pointer. Never allocate this register. // Note that this is over conservative, as it also prevents allocation of R31 // when the FP is not needed. if (Subtarget.isPPC64()) { Reserved.set(PPC::R13); Reserved.set(PPC::R31); if (!EnableRegisterScavenging) Reserved.set(PPC::R0); // FIXME (64-bit): Remove Reserved.set(PPC::X0); Reserved.set(PPC::X1); Reserved.set(PPC::X13); Reserved.set(PPC::X31); // The 64-bit SVR4 ABI reserves r2 for the TOC pointer. if (Subtarget.isSVR4ABI()) { Reserved.set(PPC::X2); } } if (needsFP(MF)) Reserved.set(PPC::R31); return Reserved; } //===----------------------------------------------------------------------===// // Stack Frame Processing methods //===----------------------------------------------------------------------===// // hasFP - Return true if the specified function actually has a dedicated frame // pointer register. This is true if the function needs a frame pointer and has // a non-zero stack size. bool PPCRegisterInfo::hasFP(const MachineFunction &MF) const { const MachineFrameInfo *MFI = MF.getFrameInfo(); return MFI->getStackSize() && needsFP(MF); } /// MustSaveLR - Return true if this function requires that we save the LR /// register onto the stack in the prolog and restore it in the epilog of the /// function. static bool MustSaveLR(const MachineFunction &MF, unsigned LR) { const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>(); // We need a save/restore of LR if there is any def of LR (which is // defined by calls, including the PIC setup sequence), or if there is // some use of the LR stack slot (e.g. for builtin_return_address). // (LR comes in 32 and 64 bit versions.) MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR); return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired(); } void PPCRegisterInfo:: eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const { if (PerformTailCallOpt && I->getOpcode() == PPC::ADJCALLSTACKUP) { // Add (actually subtract) back the amount the callee popped on return. if (int CalleeAmt = I->getOperand(1).getImm()) { bool is64Bit = Subtarget.isPPC64(); CalleeAmt *= -1; unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1; unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0; unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI; unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4; unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS; unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI; MachineInstr *MI = I; DebugLoc dl = MI->getDebugLoc(); if (isInt16(CalleeAmt)) { BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg).addReg(StackReg). addImm(CalleeAmt); } else { MachineBasicBlock::iterator MBBI = I; BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg) .addImm(CalleeAmt >> 16); BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg) .addReg(TmpReg, RegState::Kill) .addImm(CalleeAmt & 0xFFFF); BuildMI(MBB, MBBI, dl, TII.get(ADDInstr)) .addReg(StackReg) .addReg(StackReg) .addReg(TmpReg); } } } // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions. MBB.erase(I); } /// findScratchRegister - Find a 'free' PPC register. Try for a call-clobbered /// register first and then a spilled callee-saved register if that fails. static unsigned findScratchRegister(MachineBasicBlock::iterator II, RegScavenger *RS, const TargetRegisterClass *RC, int SPAdj) { assert(RS && "Register scavenging must be on"); unsigned Reg = RS->FindUnusedReg(RC); // FIXME: move ARM callee-saved reg scan to target independent code, then // search for already spilled CS register here. if (Reg == 0) Reg = RS->scavengeRegister(RC, II, SPAdj); return Reg; } /// lowerDynamicAlloc - Generate the code for allocating an object in the /// current frame. The sequence of code with be in the general form /// /// addi R0, SP, \#frameSize ; get the address of the previous frame /// stwxu R0, SP, Rnegsize ; add and update the SP with the negated size /// addi Rnew, SP, \#maxCalFrameSize ; get the top of the allocation /// void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II, int SPAdj, RegScavenger *RS) const { // Get the instruction. MachineInstr &MI = *II; // Get the instruction's basic block. MachineBasicBlock &MBB = *MI.getParent(); // Get the basic block's function. MachineFunction &MF = *MBB.getParent(); // Get the frame info. MachineFrameInfo *MFI = MF.getFrameInfo(); // Determine whether 64-bit pointers are used. bool LP64 = Subtarget.isPPC64(); DebugLoc dl = MI.getDebugLoc(); // Get the maximum call stack size. unsigned maxCallFrameSize = MFI->getMaxCallFrameSize(); // Get the total frame size. unsigned FrameSize = MFI->getStackSize(); // Get stack alignments. unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment(); unsigned MaxAlign = MFI->getMaxAlignment(); assert(MaxAlign <= TargetAlign && "Dynamic alloca with large aligns not supported"); // Determine the previous frame's address. If FrameSize can't be // represented as 16 bits or we need special alignment, then we load the // previous frame's address from 0(SP). Why not do an addis of the hi? // Because R0 is our only safe tmp register and addi/addis treat R0 as zero. // Constructing the constant and adding would take 3 instructions. // Fortunately, a frame greater than 32K is rare. const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; const TargetRegisterClass *RC = LP64 ? G8RC : GPRC; // FIXME (64-bit): Use "findScratchRegister" unsigned Reg; if (EnableRegisterScavenging) Reg = findScratchRegister(II, RS, RC, SPAdj); else Reg = PPC::R0; if (MaxAlign < TargetAlign && isInt16(FrameSize)) { BuildMI(MBB, II, dl, TII.get(PPC::ADDI), Reg) .addReg(PPC::R31) .addImm(FrameSize); } else if (LP64) { if (EnableRegisterScavenging) // FIXME (64-bit): Use "true" part. BuildMI(MBB, II, dl, TII.get(PPC::LD), Reg) .addImm(0) .addReg(PPC::X1); else BuildMI(MBB, II, dl, TII.get(PPC::LD), PPC::X0) .addImm(0) .addReg(PPC::X1); } else { BuildMI(MBB, II, dl, TII.get(PPC::LWZ), Reg) .addImm(0) .addReg(PPC::R1); } // Grow the stack and update the stack pointer link, then determine the // address of new allocated space. if (LP64) { if (EnableRegisterScavenging) // FIXME (64-bit): Use "true" part. BuildMI(MBB, II, dl, TII.get(PPC::STDUX)) .addReg(Reg, RegState::Kill) .addReg(PPC::X1) .addReg(MI.getOperand(1).getReg()); else BuildMI(MBB, II, dl, TII.get(PPC::STDUX)) .addReg(PPC::X0, RegState::Kill) .addReg(PPC::X1) .addReg(MI.getOperand(1).getReg()); if (!MI.getOperand(1).isKill()) BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg()) .addReg(PPC::X1) .addImm(maxCallFrameSize); else // Implicitly kill the register. BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg()) .addReg(PPC::X1) .addImm(maxCallFrameSize) .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill); } else { BuildMI(MBB, II, dl, TII.get(PPC::STWUX)) .addReg(Reg, RegState::Kill) .addReg(PPC::R1) .addReg(MI.getOperand(1).getReg()); if (!MI.getOperand(1).isKill()) BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg()) .addReg(PPC::R1) .addImm(maxCallFrameSize); else // Implicitly kill the register. BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg()) .addReg(PPC::R1) .addImm(maxCallFrameSize) .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill); } // Discard the DYNALLOC instruction. MBB.erase(II); } /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of /// reserving a whole register (R0), we scrounge for one here. This generates /// code like this: /// /// mfcr rA ; Move the conditional register into GPR rA. /// rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot. /// stw rA, FI ; Store rA to the frame. /// void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II, unsigned FrameIndex, int SPAdj, RegScavenger *RS) const { // Get the instruction. MachineInstr &MI = *II; // ; SPILL_CR <SrcReg>, <offset>, <FI> // Get the instruction's basic block. MachineBasicBlock &MBB = *MI.getParent(); DebugLoc dl = MI.getDebugLoc(); const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC; unsigned Reg = findScratchRegister(II, RS, RC, SPAdj); // We need to store the CR in the low 4-bits of the saved value. First, issue // an MFCR to save all of the CRBits. Add an implicit kill of the CR. if (!MI.getOperand(0).isKill()) BuildMI(MBB, II, dl, TII.get(PPC::MFCR), Reg); else // Implicitly kill the CR register. BuildMI(MBB, II, dl, TII.get(PPC::MFCR), Reg) .addReg(MI.getOperand(0).getReg(), RegState::ImplicitKill); // If the saved register wasn't CR0, shift the bits left so that they are in // CR0's slot. unsigned SrcReg = MI.getOperand(0).getReg(); if (SrcReg != PPC::CR0) // rlwinm rA, rA, ShiftBits, 0, 31. BuildMI(MBB, II, dl, TII.get(PPC::RLWINM), Reg) .addReg(Reg, RegState::Kill) .addImm(PPCRegisterInfo::getRegisterNumbering(SrcReg) * 4) .addImm(0) .addImm(31); addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::STW)) .addReg(Reg, getKillRegState(MI.getOperand(1).getImm())), FrameIndex); // Discard the pseudo instruction. MBB.erase(II); } unsigned PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, int *Value, RegScavenger *RS) const { assert(SPAdj == 0 && "Unexpected"); // Get the instruction. MachineInstr &MI = *II; // Get the instruction's basic block. MachineBasicBlock &MBB = *MI.getParent(); // Get the basic block's function. MachineFunction &MF = *MBB.getParent(); // Get the frame info. MachineFrameInfo *MFI = MF.getFrameInfo(); DebugLoc dl = MI.getDebugLoc(); // Find out which operand is the frame index. unsigned FIOperandNo = 0; while (!MI.getOperand(FIOperandNo).isFI()) { ++FIOperandNo; assert(FIOperandNo != MI.getNumOperands() && "Instr doesn't have FrameIndex operand!"); } // Take into account whether it's an add or mem instruction unsigned OffsetOperandNo = (FIOperandNo == 2) ? 1 : 2; if (MI.getOpcode() == TargetInstrInfo::INLINEASM) OffsetOperandNo = FIOperandNo-1; // Get the frame index. int FrameIndex = MI.getOperand(FIOperandNo).getIndex(); // Get the frame pointer save index. Users of this index are primarily // DYNALLOC instructions. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); int FPSI = FI->getFramePointerSaveIndex(); // Get the instruction opcode. unsigned OpC = MI.getOpcode(); // Special case for dynamic alloca. if (FPSI && FrameIndex == FPSI && (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) { lowerDynamicAlloc(II, SPAdj, RS); return 0; } // Special case for pseudo-op SPILL_CR. if (EnableRegisterScavenging) // FIXME (64-bit): Enable by default. if (OpC == PPC::SPILL_CR) { lowerCRSpilling(II, FrameIndex, SPAdj, RS); return 0; } // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP). MI.getOperand(FIOperandNo).ChangeToRegister(hasFP(MF) ? PPC::R31 : PPC::R1, false); // Figure out if the offset in the instruction is shifted right two bits. This // is true for instructions like "STD", which the machine implicitly adds two // low zeros to. bool isIXAddr = false; switch (OpC) { case PPC::LWA: case PPC::LD: case PPC::STD: case PPC::STD_32: isIXAddr = true; break; } // Now add the frame object offset to the offset from r1. int Offset = MFI->getObjectOffset(FrameIndex); if (!isIXAddr) Offset += MI.getOperand(OffsetOperandNo).getImm(); else Offset += MI.getOperand(OffsetOperandNo).getImm() << 2; // If we're not using a Frame Pointer that has been set to the value of the // SP before having the stack size subtracted from it, then add the stack size // to Offset to get the correct offset. Offset += MFI->getStackSize(); // If we can, encode the offset directly into the instruction. If this is a // normal PPC "ri" instruction, any 16-bit value can be safely encoded. If // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits // clear can be encoded. This is extremely uncommon, because normally you // only "std" to a stack slot that is at least 4-byte aligned, but it can // happen in invalid code. if (isInt16(Offset) && (!isIXAddr || (Offset & 3) == 0)) { if (isIXAddr) Offset >>= 2; // The actual encoded value has the low two bits zero. MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset); return 0; } // The offset doesn't fit into a single register, scavenge one to build the // offset in. // FIXME: figure out what SPAdj is doing here. // FIXME (64-bit): Use "findScratchRegister". unsigned SReg; if (EnableRegisterScavenging) SReg = findScratchRegister(II, RS, &PPC::GPRCRegClass, SPAdj); else SReg = PPC::R0; // Insert a set of rA with the full offset value before the ld, st, or add BuildMI(MBB, II, dl, TII.get(PPC::LIS), SReg) .addImm(Offset >> 16); BuildMI(MBB, II, dl, TII.get(PPC::ORI), SReg) .addReg(SReg, RegState::Kill) .addImm(Offset); // Convert into indexed form of the instruction: // // sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0 // addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0 unsigned OperandBase; if (OpC != TargetInstrInfo::INLINEASM) { assert(ImmToIdxMap.count(OpC) && "No indexed form of load or store available!"); unsigned NewOpcode = ImmToIdxMap.find(OpC)->second; MI.setDesc(TII.get(NewOpcode)); OperandBase = 1; } else { OperandBase = OffsetOperandNo; } unsigned StackReg = MI.getOperand(FIOperandNo).getReg(); MI.getOperand(OperandBase).ChangeToRegister(StackReg, false); MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false); return 0; } /// VRRegNo - Map from a numbered VR register to its enum value. /// static const unsigned short VRRegNo[] = { PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 , PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15, PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23, PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31 }; /// RemoveVRSaveCode - We have found that this function does not need any code /// to manipulate the VRSAVE register, even though it uses vector registers. /// This can happen when the only registers used are known to be live in or out /// of the function. Remove all of the VRSAVE related code from the function. static void RemoveVRSaveCode(MachineInstr *MI) { MachineBasicBlock *Entry = MI->getParent(); MachineFunction *MF = Entry->getParent(); // We know that the MTVRSAVE instruction immediately follows MI. Remove it. MachineBasicBlock::iterator MBBI = MI; ++MBBI; assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE); MBBI->eraseFromParent(); bool RemovedAllMTVRSAVEs = true; // See if we can find and remove the MTVRSAVE instruction from all of the // epilog blocks. for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) { // If last instruction is a return instruction, add an epilogue if (!I->empty() && I->back().getDesc().isReturn()) { bool FoundIt = false; for (MBBI = I->end(); MBBI != I->begin(); ) { --MBBI; if (MBBI->getOpcode() == PPC::MTVRSAVE) { MBBI->eraseFromParent(); // remove it. FoundIt = true; break; } } RemovedAllMTVRSAVEs &= FoundIt; } } // If we found and removed all MTVRSAVE instructions, remove the read of // VRSAVE as well. if (RemovedAllMTVRSAVEs) { MBBI = MI; assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?"); --MBBI; assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?"); MBBI->eraseFromParent(); } // Finally, nuke the UPDATE_VRSAVE. MI->eraseFromParent(); } // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the // instruction selector. Based on the vector registers that have been used, // transform this into the appropriate ORI instruction. static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) { MachineFunction *MF = MI->getParent()->getParent(); DebugLoc dl = MI->getDebugLoc(); unsigned UsedRegMask = 0; for (unsigned i = 0; i != 32; ++i) if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i])) UsedRegMask |= 1 << (31-i); // Live in and live out values already must be in the mask, so don't bother // marking them. for (MachineRegisterInfo::livein_iterator I = MF->getRegInfo().livein_begin(), E = MF->getRegInfo().livein_end(); I != E; ++I) { unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(I->first); if (VRRegNo[RegNo] == I->first) // If this really is a vector reg. UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked. } for (MachineRegisterInfo::liveout_iterator I = MF->getRegInfo().liveout_begin(), E = MF->getRegInfo().liveout_end(); I != E; ++I) { unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(*I); if (VRRegNo[RegNo] == *I) // If this really is a vector reg. UsedRegMask &= ~(1 << (31-RegNo)); // Doesn't need to be marked. } // If no registers are used, turn this into a copy. if (UsedRegMask == 0) { // Remove all VRSAVE code. RemoveVRSaveCode(MI); return; } unsigned SrcReg = MI->getOperand(1).getReg(); unsigned DstReg = MI->getOperand(0).getReg(); if ((UsedRegMask & 0xFFFF) == UsedRegMask) { if (DstReg != SrcReg) BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg) .addReg(SrcReg) .addImm(UsedRegMask); else BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg) .addReg(SrcReg, RegState::Kill) .addImm(UsedRegMask); } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) { if (DstReg != SrcReg) BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg) .addReg(SrcReg) .addImm(UsedRegMask >> 16); else BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg) .addReg(SrcReg, RegState::Kill) .addImm(UsedRegMask >> 16); } else { if (DstReg != SrcReg) BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg) .addReg(SrcReg) .addImm(UsedRegMask >> 16); else BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg) .addReg(SrcReg, RegState::Kill) .addImm(UsedRegMask >> 16); BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg) .addReg(DstReg, RegState::Kill) .addImm(UsedRegMask & 0xFFFF); } // Remove the old UPDATE_VRSAVE instruction. MI->eraseFromParent(); } /// determineFrameLayout - Determine the size of the frame and maximum call /// frame size. void PPCRegisterInfo::determineFrameLayout(MachineFunction &MF) const { MachineFrameInfo *MFI = MF.getFrameInfo(); // Get the number of bytes to allocate from the FrameInfo unsigned FrameSize = MFI->getStackSize(); // Get the alignments provided by the target, and the maximum alignment // (if any) of the fixed frame objects. unsigned MaxAlign = MFI->getMaxAlignment(); unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment(); unsigned AlignMask = TargetAlign - 1; // // If we are a leaf function, and use up to 224 bytes of stack space, // don't have a frame pointer, calls, or dynamic alloca then we do not need // to adjust the stack pointer (we fit in the Red Zone). bool DisableRedZone = MF.getFunction()->hasFnAttr(Attribute::NoRedZone); // FIXME SVR4 The 32-bit SVR4 ABI has no red zone. if (!DisableRedZone && FrameSize <= 224 && // Fits in red zone. !MFI->hasVarSizedObjects() && // No dynamic alloca. !MFI->hasCalls() && // No calls. (!ALIGN_STACK || MaxAlign <= TargetAlign)) { // No special alignment. // No need for frame MFI->setStackSize(0); return; } // Get the maximum call frame size of all the calls. unsigned maxCallFrameSize = MFI->getMaxCallFrameSize(); // Maximum call frame needs to be at least big enough for linkage and 8 args. unsigned minCallFrameSize = PPCFrameInfo::getMinCallFrameSize(Subtarget.isPPC64(), Subtarget.isDarwinABI()); maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize); // If we have dynamic alloca then maxCallFrameSize needs to be aligned so // that allocations will be aligned. if (MFI->hasVarSizedObjects()) maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask; // Update maximum call frame size. MFI->setMaxCallFrameSize(maxCallFrameSize); // Include call frame size in total. FrameSize += maxCallFrameSize; // Make sure the frame is aligned. FrameSize = (FrameSize + AlignMask) & ~AlignMask; // Update frame info. MFI->setStackSize(FrameSize); } void PPCRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF, RegScavenger *RS) const { // Save and clear the LR state. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); unsigned LR = getRARegister(); FI->setMustSaveLR(MustSaveLR(MF, LR)); MF.getRegInfo().setPhysRegUnused(LR); // Save R31 if necessary int FPSI = FI->getFramePointerSaveIndex(); bool IsPPC64 = Subtarget.isPPC64(); bool IsSVR4ABI = Subtarget.isSVR4ABI(); bool isDarwinABI = Subtarget.isDarwinABI(); MachineFrameInfo *MFI = MF.getFrameInfo(); // If the frame pointer save index hasn't been defined yet. if (!FPSI && needsFP(MF) && IsSVR4ABI) { // Find out what the fix offset of the frame pointer save area. int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, isDarwinABI); // Allocate the frame index for frame pointer save area. FPSI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, FPOffset, true, false); // Save the result. FI->setFramePointerSaveIndex(FPSI); } // Reserve stack space to move the linkage area to in case of a tail call. int TCSPDelta = 0; if (PerformTailCallOpt && (TCSPDelta = FI->getTailCallSPDelta()) < 0) { MF.getFrameInfo()->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true, false); } // Reserve a slot closest to SP or frame pointer if we have a dynalloc or // a large stack, which will require scavenging a register to materialize a // large offset. // FIXME: this doesn't actually check stack size, so is a bit pessimistic // FIXME: doesn't detect whether or not we need to spill vXX, which requires // r0 for now. if (EnableRegisterScavenging) // FIXME (64-bit): Enable. if (needsFP(MF) || spillsCR(MF)) { const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; const TargetRegisterClass *RC = IsPPC64 ? G8RC : GPRC; RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(), RC->getAlignment(), false)); } } void PPCRegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF) const { // Early exit if not using the SVR4 ABI. if (!Subtarget.isSVR4ABI()) { return; } // Get callee saved register information. MachineFrameInfo *FFI = MF.getFrameInfo(); const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo(); // Early exit if no callee saved registers are modified! if (CSI.empty() && !needsFP(MF)) { return; } unsigned MinGPR = PPC::R31; unsigned MinG8R = PPC::X31; unsigned MinFPR = PPC::F31; unsigned MinVR = PPC::V31; bool HasGPSaveArea = false; bool HasG8SaveArea = false; bool HasFPSaveArea = false; bool HasCRSaveArea = false; bool HasVRSAVESaveArea = false; bool HasVRSaveArea = false; SmallVector<CalleeSavedInfo, 18> GPRegs; SmallVector<CalleeSavedInfo, 18> G8Regs; SmallVector<CalleeSavedInfo, 18> FPRegs; SmallVector<CalleeSavedInfo, 18> VRegs; for (unsigned i = 0, e = CSI.size(); i != e; ++i) { unsigned Reg = CSI[i].getReg(); const TargetRegisterClass *RC = CSI[i].getRegClass(); if (RC == PPC::GPRCRegisterClass) { HasGPSaveArea = true; GPRegs.push_back(CSI[i]); if (Reg < MinGPR) { MinGPR = Reg; } } else if (RC == PPC::G8RCRegisterClass) { HasG8SaveArea = true; G8Regs.push_back(CSI[i]); if (Reg < MinG8R) { MinG8R = Reg; } } else if (RC == PPC::F8RCRegisterClass) { HasFPSaveArea = true; FPRegs.push_back(CSI[i]); if (Reg < MinFPR) { MinFPR = Reg; } // FIXME SVR4: Disable CR save area for now. } else if ( RC == PPC::CRBITRCRegisterClass || RC == PPC::CRRCRegisterClass) { // HasCRSaveArea = true; } else if (RC == PPC::VRSAVERCRegisterClass) { HasVRSAVESaveArea = true; } else if (RC == PPC::VRRCRegisterClass) { HasVRSaveArea = true; VRegs.push_back(CSI[i]); if (Reg < MinVR) { MinVR = Reg; } } else { llvm_unreachable("Unknown RegisterClass!"); } } PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>(); int64_t LowerBound = 0; // Take into account stack space reserved for tail calls. int TCSPDelta = 0; if (PerformTailCallOpt && (TCSPDelta = PFI->getTailCallSPDelta()) < 0) { LowerBound = TCSPDelta; } // The Floating-point register save area is right below the back chain word // of the previous stack frame. if (HasFPSaveArea) { for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) { int FI = FPRegs[i].getFrameIdx(); FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI)); } LowerBound -= (31 - getRegisterNumbering(MinFPR) + 1) * 8; } // Check whether the frame pointer register is allocated. If so, make sure it // is spilled to the correct offset. if (needsFP(MF)) { HasGPSaveArea = true; int FI = PFI->getFramePointerSaveIndex(); assert(FI && "No Frame Pointer Save Slot!"); FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI)); } // General register save area starts right below the Floating-point // register save area. if (HasGPSaveArea || HasG8SaveArea) { // Move general register save area spill slots down, taking into account // the size of the Floating-point register save area. for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) { int FI = GPRegs[i].getFrameIdx(); FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI)); } // Move general register save area spill slots down, taking into account // the size of the Floating-point register save area. for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) { int FI = G8Regs[i].getFrameIdx(); FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI)); } unsigned MinReg = std::min<unsigned>(getRegisterNumbering(MinGPR), getRegisterNumbering(MinG8R)); if (Subtarget.isPPC64()) { LowerBound -= (31 - MinReg + 1) * 8; } else { LowerBound -= (31 - MinReg + 1) * 4; } } // The CR save area is below the general register save area. if (HasCRSaveArea) { // FIXME SVR4: Is it actually possible to have multiple elements in CSI // which have the CR/CRBIT register class? // Adjust the frame index of the CR spill slot. for (unsigned i = 0, e = CSI.size(); i != e; ++i) { const TargetRegisterClass *RC = CSI[i].getRegClass(); if (RC == PPC::CRBITRCRegisterClass || RC == PPC::CRRCRegisterClass) { int FI = CSI[i].getFrameIdx(); FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI)); } } LowerBound -= 4; // The CR save area is always 4 bytes long. } if (HasVRSAVESaveArea) { // FIXME SVR4: Is it actually possible to have multiple elements in CSI // which have the VRSAVE register class? // Adjust the frame index of the VRSAVE spill slot. for (unsigned i = 0, e = CSI.size(); i != e; ++i) { const TargetRegisterClass *RC = CSI[i].getRegClass(); if (RC == PPC::VRSAVERCRegisterClass) { int FI = CSI[i].getFrameIdx(); FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI)); } } LowerBound -= 4; // The VRSAVE save area is always 4 bytes long. } if (HasVRSaveArea) { // Insert alignment padding, we need 16-byte alignment. LowerBound = (LowerBound - 15) & ~(15); for (unsigned i = 0, e = VRegs.size(); i != e; ++i) { int FI = VRegs[i].getFrameIdx(); FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI)); } } } void PPCRegisterInfo::emitPrologue(MachineFunction &MF) const { MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB MachineBasicBlock::iterator MBBI = MBB.begin(); MachineFrameInfo *MFI = MF.getFrameInfo(); MachineModuleInfo *MMI = MFI->getMachineModuleInfo(); DebugLoc dl = DebugLoc::getUnknownLoc(); bool needsFrameMoves = (MMI && MMI->hasDebugInfo()) || !MF.getFunction()->doesNotThrow() || UnwindTablesMandatory; // Prepare for frame info. unsigned FrameLabelId = 0; // Scan the prolog, looking for an UPDATE_VRSAVE instruction. If we find it, // process it. for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) { if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) { HandleVRSaveUpdate(MBBI, TII); break; } } // Move MBBI back to the beginning of the function. MBBI = MBB.begin(); // Work out frame sizes. determineFrameLayout(MF); unsigned FrameSize = MFI->getStackSize(); int NegFrameSize = -FrameSize; // Get processor type. bool IsPPC64 = Subtarget.isPPC64(); // Get operating system bool isDarwinABI = Subtarget.isDarwinABI(); // Check if the link register (LR) must be saved. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); bool MustSaveLR = FI->mustSaveLR(); // Do we have a frame pointer for this function? bool HasFP = hasFP(MF) && FrameSize; int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, isDarwinABI); int FPOffset = 0; if (HasFP) { if (Subtarget.isSVR4ABI()) { MachineFrameInfo *FFI = MF.getFrameInfo(); int FPIndex = FI->getFramePointerSaveIndex(); assert(FPIndex && "No Frame Pointer Save Slot!"); FPOffset = FFI->getObjectOffset(FPIndex); } else { FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, isDarwinABI); } } if (IsPPC64) { if (MustSaveLR) BuildMI(MBB, MBBI, dl, TII.get(PPC::MFLR8), PPC::X0); if (HasFP) BuildMI(MBB, MBBI, dl, TII.get(PPC::STD)) .addReg(PPC::X31) .addImm(FPOffset/4) .addReg(PPC::X1); if (MustSaveLR) BuildMI(MBB, MBBI, dl, TII.get(PPC::STD)) .addReg(PPC::X0) .addImm(LROffset / 4) .addReg(PPC::X1); } else { if (MustSaveLR) BuildMI(MBB, MBBI, dl, TII.get(PPC::MFLR), PPC::R0); if (HasFP) BuildMI(MBB, MBBI, dl, TII.get(PPC::STW)) .addReg(PPC::R31) .addImm(FPOffset) .addReg(PPC::R1); if (MustSaveLR) BuildMI(MBB, MBBI, dl, TII.get(PPC::STW)) .addReg(PPC::R0) .addImm(LROffset) .addReg(PPC::R1); } // Skip if a leaf routine. if (!FrameSize) return; // Get stack alignments. unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment(); unsigned MaxAlign = MFI->getMaxAlignment(); // Adjust stack pointer: r1 += NegFrameSize. // If there is a preferred stack alignment, align R1 now if (!IsPPC64) { // PPC32. if (ALIGN_STACK && MaxAlign > TargetAlign) { assert(isPowerOf2_32(MaxAlign)&&isInt16(MaxAlign)&&"Invalid alignment!"); assert(isInt16(NegFrameSize) && "Unhandled stack size and alignment!"); BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), PPC::R0) .addReg(PPC::R1) .addImm(0) .addImm(32 - Log2_32(MaxAlign)) .addImm(31); BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBFIC) ,PPC::R0) .addReg(PPC::R0, RegState::Kill) .addImm(NegFrameSize); BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX)) .addReg(PPC::R1) .addReg(PPC::R1) .addReg(PPC::R0); } else if (isInt16(NegFrameSize)) { BuildMI(MBB, MBBI, dl, TII.get(PPC::STWU), PPC::R1) .addReg(PPC::R1) .addImm(NegFrameSize) .addReg(PPC::R1); } else { BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS), PPC::R0) .addImm(NegFrameSize >> 16); BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI), PPC::R0) .addReg(PPC::R0, RegState::Kill) .addImm(NegFrameSize & 0xFFFF); BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX)) .addReg(PPC::R1) .addReg(PPC::R1) .addReg(PPC::R0); } } else { // PPC64. if (ALIGN_STACK && MaxAlign > TargetAlign) { assert(isPowerOf2_32(MaxAlign)&&isInt16(MaxAlign)&&"Invalid alignment!"); assert(isInt16(NegFrameSize) && "Unhandled stack size and alignment!"); BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), PPC::X0) .addReg(PPC::X1) .addImm(0) .addImm(64 - Log2_32(MaxAlign)); BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBFIC8), PPC::X0) .addReg(PPC::X0) .addImm(NegFrameSize); BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX)) .addReg(PPC::X1) .addReg(PPC::X1) .addReg(PPC::X0); } else if (isInt16(NegFrameSize)) { BuildMI(MBB, MBBI, dl, TII.get(PPC::STDU), PPC::X1) .addReg(PPC::X1) .addImm(NegFrameSize / 4) .addReg(PPC::X1); } else { BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS8), PPC::X0) .addImm(NegFrameSize >> 16); BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI8), PPC::X0) .addReg(PPC::X0, RegState::Kill) .addImm(NegFrameSize & 0xFFFF); BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX)) .addReg(PPC::X1) .addReg(PPC::X1) .addReg(PPC::X0); } } std::vector<MachineMove> &Moves = MMI->getFrameMoves(); // Add the "machine moves" for the instructions we generated above, but in // reverse order. if (needsFrameMoves) { // Mark effective beginning of when frame pointer becomes valid. FrameLabelId = MMI->NextLabelID(); BuildMI(MBB, MBBI, dl, TII.get(PPC::DBG_LABEL)).addImm(FrameLabelId); // Show update of SP. if (NegFrameSize) { MachineLocation SPDst(MachineLocation::VirtualFP); MachineLocation SPSrc(MachineLocation::VirtualFP, NegFrameSize); Moves.push_back(MachineMove(FrameLabelId, SPDst, SPSrc)); } else { MachineLocation SP(IsPPC64 ? PPC::X31 : PPC::R31); Moves.push_back(MachineMove(FrameLabelId, SP, SP)); } if (HasFP) { MachineLocation FPDst(MachineLocation::VirtualFP, FPOffset); MachineLocation FPSrc(IsPPC64 ? PPC::X31 : PPC::R31); Moves.push_back(MachineMove(FrameLabelId, FPDst, FPSrc)); } if (MustSaveLR) { MachineLocation LRDst(MachineLocation::VirtualFP, LROffset); MachineLocation LRSrc(IsPPC64 ? PPC::LR8 : PPC::LR); Moves.push_back(MachineMove(FrameLabelId, LRDst, LRSrc)); } } unsigned ReadyLabelId = 0; // If there is a frame pointer, copy R1 into R31 if (HasFP) { if (!IsPPC64) { BuildMI(MBB, MBBI, dl, TII.get(PPC::OR), PPC::R31) .addReg(PPC::R1) .addReg(PPC::R1); } else { BuildMI(MBB, MBBI, dl, TII.get(PPC::OR8), PPC::X31) .addReg(PPC::X1) .addReg(PPC::X1); } if (needsFrameMoves) { ReadyLabelId = MMI->NextLabelID(); // Mark effective beginning of when frame pointer is ready. BuildMI(MBB, MBBI, dl, TII.get(PPC::DBG_LABEL)).addImm(ReadyLabelId); MachineLocation FPDst(HasFP ? (IsPPC64 ? PPC::X31 : PPC::R31) : (IsPPC64 ? PPC::X1 : PPC::R1)); MachineLocation FPSrc(MachineLocation::VirtualFP); Moves.push_back(MachineMove(ReadyLabelId, FPDst, FPSrc)); } } if (needsFrameMoves) { unsigned LabelId = HasFP ? ReadyLabelId : FrameLabelId; // Add callee saved registers to move list. const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); for (unsigned I = 0, E = CSI.size(); I != E; ++I) { int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx()); unsigned Reg = CSI[I].getReg(); if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue; MachineLocation CSDst(MachineLocation::VirtualFP, Offset); MachineLocation CSSrc(Reg); Moves.push_back(MachineMove(LabelId, CSDst, CSSrc)); } } } void PPCRegisterInfo::emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const { MachineBasicBlock::iterator MBBI = prior(MBB.end()); unsigned RetOpcode = MBBI->getOpcode(); DebugLoc dl = DebugLoc::getUnknownLoc(); assert( (RetOpcode == PPC::BLR || RetOpcode == PPC::TCRETURNri || RetOpcode == PPC::TCRETURNdi || RetOpcode == PPC::TCRETURNai || RetOpcode == PPC::TCRETURNri8 || RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNai8) && "Can only insert epilog into returning blocks"); // Get alignment info so we know how to restore r1 const MachineFrameInfo *MFI = MF.getFrameInfo(); unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment(); unsigned MaxAlign = MFI->getMaxAlignment(); // Get the number of bytes allocated from the FrameInfo. int FrameSize = MFI->getStackSize(); // Get processor type. bool IsPPC64 = Subtarget.isPPC64(); // Get operating system bool isDarwinABI = Subtarget.isDarwinABI(); // Check if the link register (LR) has been saved. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); bool MustSaveLR = FI->mustSaveLR(); // Do we have a frame pointer for this function? bool HasFP = hasFP(MF) && FrameSize; int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, isDarwinABI); int FPOffset = 0; if (HasFP) { if (Subtarget.isSVR4ABI()) { MachineFrameInfo *FFI = MF.getFrameInfo(); int FPIndex = FI->getFramePointerSaveIndex(); assert(FPIndex && "No Frame Pointer Save Slot!"); FPOffset = FFI->getObjectOffset(FPIndex); } else { FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, isDarwinABI); } } bool UsesTCRet = RetOpcode == PPC::TCRETURNri || RetOpcode == PPC::TCRETURNdi || RetOpcode == PPC::TCRETURNai || RetOpcode == PPC::TCRETURNri8 || RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNai8; if (UsesTCRet) { int MaxTCRetDelta = FI->getTailCallSPDelta(); MachineOperand &StackAdjust = MBBI->getOperand(1); assert(StackAdjust.isImm() && "Expecting immediate value."); // Adjust stack pointer. int StackAdj = StackAdjust.getImm(); int Delta = StackAdj - MaxTCRetDelta; assert((Delta >= 0) && "Delta must be positive"); if (MaxTCRetDelta>0) FrameSize += (StackAdj +Delta); else FrameSize += StackAdj; } if (FrameSize) { // The loaded (or persistent) stack pointer value is offset by the 'stwu' // on entry to the function. Add this offset back now. if (!IsPPC64) { // If this function contained a fastcc call and PerformTailCallOpt is // enabled (=> hasFastCall()==true) the fastcc call might contain a tail // call which invalidates the stack pointer value in SP(0). So we use the // value of R31 in this case. if (FI->hasFastCall() && isInt16(FrameSize)) { assert(hasFP(MF) && "Expecting a valid the frame pointer."); BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), PPC::R1) .addReg(PPC::R31).addImm(FrameSize); } else if(FI->hasFastCall()) { BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS), PPC::R0) .addImm(FrameSize >> 16); BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI), PPC::R0) .addReg(PPC::R0, RegState::Kill) .addImm(FrameSize & 0xFFFF); BuildMI(MBB, MBBI, dl, TII.get(PPC::ADD4)) .addReg(PPC::R1) .addReg(PPC::R31) .addReg(PPC::R0); } else if (isInt16(FrameSize) && (!ALIGN_STACK || TargetAlign >= MaxAlign) && !MFI->hasVarSizedObjects()) { BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), PPC::R1) .addReg(PPC::R1).addImm(FrameSize); } else { BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ),PPC::R1) .addImm(0).addReg(PPC::R1); } } else { if (FI->hasFastCall() && isInt16(FrameSize)) { assert(hasFP(MF) && "Expecting a valid the frame pointer."); BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI8), PPC::X1) .addReg(PPC::X31).addImm(FrameSize); } else if(FI->hasFastCall()) { BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS8), PPC::X0) .addImm(FrameSize >> 16); BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI8), PPC::X0) .addReg(PPC::X0, RegState::Kill) .addImm(FrameSize & 0xFFFF); BuildMI(MBB, MBBI, dl, TII.get(PPC::ADD8)) .addReg(PPC::X1) .addReg(PPC::X31) .addReg(PPC::X0); } else if (isInt16(FrameSize) && TargetAlign >= MaxAlign && !MFI->hasVarSizedObjects()) { BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI8), PPC::X1) .addReg(PPC::X1).addImm(FrameSize); } else { BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X1) .addImm(0).addReg(PPC::X1); } } } if (IsPPC64) { if (MustSaveLR) BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X0) .addImm(LROffset/4).addReg(PPC::X1); if (HasFP) BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X31) .addImm(FPOffset/4).addReg(PPC::X1); if (MustSaveLR) BuildMI(MBB, MBBI, dl, TII.get(PPC::MTLR8)).addReg(PPC::X0); } else { if (MustSaveLR) BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ), PPC::R0) .addImm(LROffset).addReg(PPC::R1); if (HasFP) BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ), PPC::R31) .addImm(FPOffset).addReg(PPC::R1); if (MustSaveLR) BuildMI(MBB, MBBI, dl, TII.get(PPC::MTLR)).addReg(PPC::R0); } // Callee pop calling convention. Pop parameter/linkage area. Used for tail // call optimization if (PerformTailCallOpt && RetOpcode == PPC::BLR && MF.getFunction()->getCallingConv() == CallingConv::Fast) { PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); unsigned CallerAllocatedAmt = FI->getMinReservedArea(); unsigned StackReg = IsPPC64 ? PPC::X1 : PPC::R1; unsigned FPReg = IsPPC64 ? PPC::X31 : PPC::R31; unsigned TmpReg = IsPPC64 ? PPC::X0 : PPC::R0; unsigned ADDIInstr = IsPPC64 ? PPC::ADDI8 : PPC::ADDI; unsigned ADDInstr = IsPPC64 ? PPC::ADD8 : PPC::ADD4; unsigned LISInstr = IsPPC64 ? PPC::LIS8 : PPC::LIS; unsigned ORIInstr = IsPPC64 ? PPC::ORI8 : PPC::ORI; if (CallerAllocatedAmt && isInt16(CallerAllocatedAmt)) { BuildMI(MBB, MBBI, dl, TII.get(ADDIInstr), StackReg) .addReg(StackReg).addImm(CallerAllocatedAmt); } else { BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg) .addImm(CallerAllocatedAmt >> 16); BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg) .addReg(TmpReg, RegState::Kill) .addImm(CallerAllocatedAmt & 0xFFFF); BuildMI(MBB, MBBI, dl, TII.get(ADDInstr)) .addReg(StackReg) .addReg(FPReg) .addReg(TmpReg); } } else if (RetOpcode == PPC::TCRETURNdi) { MBBI = prior(MBB.end()); MachineOperand &JumpTarget = MBBI->getOperand(0); BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)). addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset()); } else if (RetOpcode == PPC::TCRETURNri) { MBBI = prior(MBB.end()); assert(MBBI->getOperand(0).isReg() && "Expecting register operand."); BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR)); } else if (RetOpcode == PPC::TCRETURNai) { MBBI = prior(MBB.end()); MachineOperand &JumpTarget = MBBI->getOperand(0); BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm()); } else if (RetOpcode == PPC::TCRETURNdi8) { MBBI = prior(MBB.end()); MachineOperand &JumpTarget = MBBI->getOperand(0); BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)). addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset()); } else if (RetOpcode == PPC::TCRETURNri8) { MBBI = prior(MBB.end()); assert(MBBI->getOperand(0).isReg() && "Expecting register operand."); BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8)); } else if (RetOpcode == PPC::TCRETURNai8) { MBBI = prior(MBB.end()); MachineOperand &JumpTarget = MBBI->getOperand(0); BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm()); } } unsigned PPCRegisterInfo::getRARegister() const { return !Subtarget.isPPC64() ? PPC::LR : PPC::LR8; } unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const { if (!Subtarget.isPPC64()) return hasFP(MF) ? PPC::R31 : PPC::R1; else return hasFP(MF) ? PPC::X31 : PPC::X1; } void PPCRegisterInfo::getInitialFrameState(std::vector<MachineMove> &Moves) const { // Initial state of the frame pointer is R1. MachineLocation Dst(MachineLocation::VirtualFP); MachineLocation Src(PPC::R1, 0); Moves.push_back(MachineMove(0, Dst, Src)); } unsigned PPCRegisterInfo::getEHExceptionRegister() const { return !Subtarget.isPPC64() ? PPC::R3 : PPC::X3; } unsigned PPCRegisterInfo::getEHHandlerRegister() const { return !Subtarget.isPPC64() ? PPC::R4 : PPC::X4; } int PPCRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const { // FIXME: Most probably dwarf numbers differs for Linux and Darwin return PPCGenRegisterInfo::getDwarfRegNumFull(RegNum, 0); } #include "PPCGenRegisterInfo.inc"
38.024041
80
0.637126
ianloic
e660afeb2dec147f02b43842d7a6ca6fa7b8366e
6,739
cpp
C++
Tools/Tools/record-memory-win/main.cpp
VincentWei/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
Tools/Tools/record-memory-win/main.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
null
null
null
Tools/Tools/record-memory-win/main.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-17T06:02:42.000Z
2018-09-19T10:08:38.000Z
#include <windows.h> #include <assert.h> #include <psapi.h> #include <stdio.h> #include <tchar.h> #include <time.h> #include "Shlwapi.h" #pragma comment(lib, "psapi.lib") #pragma comment(lib, "shlwapi.lib") bool gSingleProcess = true; int gQueryInterval = 5; // seconds time_t gDuration = 0; // seconds LPTSTR gCommandLine; HRESULT ProcessArgs(int argc, TCHAR *argv[]); HRESULT PrintUsage(); void UseImage(void (functionForQueryType(HANDLE))); void QueryContinuously(HANDLE hProcess); time_t ElapsedTime(time_t startTime); unsigned int OneQuery(HANDLE hProcess); unsigned int OneQueryMP(HANDLE hProcess); int __cdecl _tmain (int argc, TCHAR *argv[]) { HRESULT result = ProcessArgs(argc, argv); if (FAILED(result)) return result; UseImage(QueryContinuously); return S_OK; } HRESULT ProcessArgs(int argc, TCHAR *argv[]) { LPTSTR argument; for( int count = 1; count < argc; count++ ) { argument = argv[count] ; if (wcsstr(argument, _T("-h")) || wcsstr(argument, _T("--help"))) return PrintUsage(); else if (wcsstr(argument, _T("--exe"))) { gCommandLine = argv[++count]; if (wcsstr(gCommandLine, _T("chrome.exe"))) gSingleProcess = false; } else if (wcsstr(argument, _T("-i")) || wcsstr(argument, _T("--interval"))) { gQueryInterval = _wtoi(argv[++count]); if (gQueryInterval < 1) { printf("ERROR: invalid interval\n"); return E_INVALIDARG; } } else if (wcsstr(argument, _T("-d")) || wcsstr(argument, _T("--duration"))) { gDuration = _wtoi(argv[++count]); if (gDuration < 1) { printf("ERROR: invalid duration\n"); return E_INVALIDARG; } } else { _tprintf(_T("ERROR: unrecognized argument \"%s\"\n"), (LPCTSTR)argument); return PrintUsage(); } } if (argc < 2 || !wcslen(gCommandLine) ) { printf("ERROR: executable path is required\n"); return PrintUsage(); } return S_OK; } HRESULT PrintUsage() { printf("record-memory-win --exe EXE_PATH\n"); printf(" Launch an executable and print the memory usage (in Private Bytes)\n"); printf(" of the process.\n\n"); printf("Usage:\n"); printf("-h [--help] : Print usage\n"); printf("--exe arg : Launch specified image. Required\n"); printf("-i [--interval] arg : Print memory usage every arg seconds. Default: 5 seconds\n"); printf("-d [--duration] arg : Run for up to arg seconds. Default: no limit\n\n"); printf("Examples:\n"); printf(" record-memory-win --exe \"C:\\Program Files\\Safari\\Safari.exe\"\n"); printf(" record-memory-win --exe Safari.exe -i 10 -d 7200\n"); return E_FAIL; } void UseImage(void (functionForQueryType(HANDLE))) { STARTUPINFO si = {0}; si.cb = sizeof(STARTUPINFO); PROCESS_INFORMATION pi = {0}; // Start the child process. if(!CreateProcess( NULL, // No module name (use command line) gCommandLine, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi )) // Pointer to PROCESS_INFORMATION structure printf("CreateProcess failed (%d)\n", GetLastError()); else { printf("Created process\n"); functionForQueryType(pi.hProcess); // Close process and thread handles. CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); } } void QueryContinuously(HANDLE hProcess) { Sleep(2000); // give the process some time to launch bool pastDuration = false; time_t startTime = time(NULL); unsigned int memUsage = gSingleProcess ? OneQuery(hProcess) : OneQueryMP(hProcess); while(memUsage && !pastDuration) { printf( "%u\n", memUsage ); Sleep(gQueryInterval*1000); memUsage = gSingleProcess ? OneQuery(hProcess) : OneQueryMP(hProcess); pastDuration = gDuration > 0 ? ElapsedTime(startTime) > gDuration : false; } } // returns elapsed time in seconds time_t ElapsedTime(time_t startTime) { time_t currentTime = time(NULL); return currentTime - startTime; } // returns Commit Size (Private Bytes) in bytes unsigned int OneQuery(HANDLE hProcess) { PROCESS_MEMORY_COUNTERS_EX pmc; if (NULL == hProcess) return 0; if (GetProcessMemoryInfo(hProcess, (PPROCESS_MEMORY_COUNTERS)&pmc, sizeof(pmc))) return (unsigned)pmc.PrivateUsage; return 0; } // returns Commit Size (Private Bytes) in bytes for multi-process executables unsigned int OneQueryMP(HANDLE hProcess) { unsigned int memUsage = 0; TCHAR monitoredProcessName[MAX_PATH]; GetProcessImageFileName(hProcess, monitoredProcessName, sizeof(monitoredProcessName)/sizeof(TCHAR)); LPTSTR shortProcessName = PathFindFileName(monitoredProcessName); DWORD aProcesses[1024], cbNeeded, cProcesses; HANDLE hFoundProcess; if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded)) return 0; // Calculate how many process identifiers were returned. cProcesses = cbNeeded / sizeof(DWORD); // find existing process for (unsigned int i = 0; i < cProcesses; i++) if (aProcesses[i] != 0) { DWORD retVal = 0; TCHAR foundProcessName[MAX_PATH]; // Get a handle to the process. hFoundProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i]); // Get the process name. if (NULL != hFoundProcess) { HMODULE hMod; DWORD cbNeeded; if (EnumProcessModules(hFoundProcess, &hMod, sizeof(hMod), &cbNeeded)) { GetModuleBaseName(hFoundProcess, hMod, foundProcessName, sizeof(foundProcessName)/sizeof(TCHAR)); if (wcsstr(foundProcessName, shortProcessName)) memUsage += OneQuery(hFoundProcess); } } CloseHandle(hFoundProcess); } return memUsage; }
35.845745
118
0.589405
VincentWei
e662ea83482d29724f2bd177093ab2d257bbff8a
4,185
cpp
C++
private/shell/ext/systray/dll/stobject.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/ext/systray/dll/stobject.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/ext/systray/dll/stobject.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
#include "stdafx.h" #include "stobject.h" extern "C" int PASCAL SysTrayMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow); extern "C" const TCHAR g_szWindowClassName[]; /************************************************************************************ IUnknown Implementation ************************************************************************************/ HRESULT CSysTray::QueryInterface(REFIID iid, void** ppvObject) { HRESULT hr = S_OK; if ((iid == IID_IOleCommandTarget) || (iid == IID_IUnknown)) { *ppvObject = (IOleCommandTarget*) this; } else { *ppvObject = NULL; hr = E_NOINTERFACE; } if (hr == S_OK) { ((IUnknown*) (*ppvObject))->AddRef(); } return hr; } ULONG CSysTray::AddRef() { return InterlockedIncrement(&m_cRef); } ULONG CSysTray::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this; return 0; } return m_cRef; } /************************************************************************************ IOleCommandTarget Implementation ************************************************************************************/ HRESULT CSysTray::QueryStatus(const GUID* pguidCmdGroup, ULONG cCmds, OLECMD prgCmds[], OLECMDTEXT* pCmdText) { HRESULT hr = OLECMDERR_E_UNKNOWNGROUP; if (*pguidCmdGroup == CGID_ShellServiceObject) { // We like Shell Service Object notifications... hr = S_OK; } return hr; } HRESULT CSysTray::Exec(const GUID* pguidCmdGroup, DWORD nCmdID, DWORD nCmdExecOpt, VARIANTARG* pvaIn, VARIANTARG* pvaOut) { HRESULT hr = OLECMDERR_E_UNKNOWNGROUP; if (*pguidCmdGroup == CGID_ShellServiceObject) { // Handle Shell Service Object notifications here. switch (nCmdID) { case SSOCMDID_OPEN: hr = CreateSysTrayThread(); break; case SSOCMDID_CLOSE: hr = DestroySysTrayWindow(); break; default: hr = S_OK; break; } } return hr; } /************************************************************************************ Constructor/Destructor Implementation ************************************************************************************/ CSysTray::CSysTray(BOOL fRunTrayOnConstruct) { m_cRef = 1; InterlockedIncrement(&g_cLocks); if (fRunTrayOnConstruct) { // We are being called through SHLoadInProc - Launch the systray thread immediately CreateSysTrayThread(); } } CSysTray::~CSysTray() { InterlockedDecrement(&g_cLocks); } /************************************************************************************ Private Function Implementation ************************************************************************************/ HRESULT CSysTray::CreateSysTrayThread() { HRESULT hr = S_OK; HANDLE hThread; DWORD dwThreadId; hThread = CreateThread(NULL, 0, CSysTray::SysTrayThreadProc, NULL, 0, &dwThreadId); if (hThread != NULL) { CloseHandle(hThread); } else hr = E_FAIL; return hr; } DWORD CSysTray::SysTrayThreadProc(void* lpv) { // We pass a "" for the command line to so that the tray applets dont' start. TCHAR szModule[MAX_PATH]; GetModuleFileName(g_hinstDll, szModule, ARRAYSIZE(szModule)); HINSTANCE hInstThis = LoadLibrary(szModule); int Result = SysTrayMain(g_hinstDll, NULL, "", SW_SHOWNORMAL); FreeLibraryAndExitThread(hInstThis, (DWORD) Result); // Never gets here return 0; } HRESULT CSysTray::DestroySysTrayWindow() { HWND hExistWnd = FindWindow(g_szWindowClassName, NULL); if (hExistWnd) { // Destroy the window. Note that we can't use DestroyWindow since // the window is on a different thread and DestroyWindow fails. SendMessage(hExistWnd, WM_CLOSE, 0, 0); } return S_OK; }
25.210843
122
0.507049
King0987654
e666d0e98ccec9274120bbefe284ad1d6224d4a3
2,194
cpp
C++
src/LuaPlugins/LuaPluginHandler.cpp
GiantCrocodile/MCHawk
495d0519ed8d9d88d050e9dfcbb026d43aa7d3ff
[ "MIT" ]
8
2018-07-29T17:17:22.000Z
2021-11-23T02:45:54.000Z
src/LuaPlugins/LuaPluginHandler.cpp
GiantCrocodile/MCHawk
495d0519ed8d9d88d050e9dfcbb026d43aa7d3ff
[ "MIT" ]
68
2018-04-20T16:38:10.000Z
2019-01-04T19:32:38.000Z
src/LuaPlugins/LuaPluginHandler.cpp
GiantCrocodile/MCHawk
495d0519ed8d9d88d050e9dfcbb026d43aa7d3ff
[ "MIT" ]
4
2018-08-19T00:03:42.000Z
2021-07-13T16:56:05.000Z
#include "LuaPluginHandler.hpp" #include "LuaPluginAPI.hpp" #include <iostream> lua_State* LuaPluginHandler::L = nullptr; LuaPluginHandler::LuaPluginHandler() { Init(); } LuaPluginHandler::~LuaPluginHandler() { Cleanup(); } void LuaPluginHandler::Init() { L = luaL_newstate(); assert(L != nullptr); luaL_openlibs(L); LuaServer::Init(L); } void LuaPluginHandler::Cleanup() { for (int i = 0; i < kEventTypeEnd; ++i) { m_signalMap[i].disconnect_all_slots(); assert(m_signalMap[i].empty()); } for (auto& obj : m_plugins) delete obj; lua_close(L); L = nullptr; } void LuaPluginHandler::Reset() { Cleanup(); m_plugins.clear(); m_pluginQueue.clear(); Init(); } void LuaPluginHandler::AddPlugin(LuaPlugin* plugin) { m_plugins.push_back(plugin); } void LuaPluginHandler::LoadPlugin(std::string filename) { LuaPlugin* plugin = new LuaPlugin; try { plugin->LoadScript(L, filename); plugin->Init(); } catch(std::runtime_error const& e) { LOG(LogLevel::kWarning, "LuaPluginHandler exception in LoadPlugin(): %s", e.what()); delete plugin; return; } AddPlugin(plugin); auto table = make_luatable(); table["name"] = plugin->GetName(); TriggerEvent(EventType::kOnPluginLoaded, nullptr, table); } void LuaPluginHandler::QueuePlugin(std::string filename) { m_pluginQueue.push_back(filename); } void LuaPluginHandler::FlushPluginQueue() { for (auto& filename : m_pluginQueue) LoadPlugin(filename); m_pluginQueue.clear(); } void LuaPluginHandler::RegisterEvent(int type, luabridge::LuaRef func) { if (func.isFunction()) { try { m_signalMap[type].connect(boost::bind((std::function<void(Client*, luabridge::LuaRef)>)func, _1, _2)); } catch (luabridge::LuaException const& e) { LOG(LogLevel::kWarning, "LuaPluginHandler exception in RegisterEvent(): %s", e.what()); } } } void LuaPluginHandler::TriggerEvent(int type, Client* client, luabridge::LuaRef table) { try { m_signalMap[type](client, table); } catch (luabridge::LuaException const& e) { LOG(LogLevel::kWarning, "LuaPluginHandler exception in TriggerEvent(): %s", e.what()); } } void LuaPluginHandler::TickPlugins() { for (auto& obj : m_plugins) obj->Tick(); }
18.59322
105
0.704193
GiantCrocodile
e673f66218dba5f03459dc4447ab2cafb83ff7c1
4,405
cpp
C++
lib/door/utils.cpp
robyu/door
8892fb8cb1f6aa55cca7fa5d04507971115400f2
[ "MIT" ]
null
null
null
lib/door/utils.cpp
robyu/door
8892fb8cb1f6aa55cca7fa5d04507971115400f2
[ "MIT" ]
null
null
null
lib/door/utils.cpp
robyu/door
8892fb8cb1f6aa55cca7fa5d04507971115400f2
[ "MIT" ]
null
null
null
#include <stdarg.h> #include <stdlib.h> #include <Arduino.h> #include <limits.h> #include "gpio_pins.h" #include "utils.h" /* reset the esp8266 also make sure to pull D3 and D0 high and D8 pull down see https://github.com/esp8266/Arduino/issues/1017 */ void utils_restart(void) { delay(500); ESP.restart(); delay(500); } /* on_off is 1 or 0 not HIGH or LOW */ void utils_set_led(int led_pin, int on_off) { int on_value = -1; // agh, fucking LEDs have different polarities UTILS_ASSERT(LED_DOOR==LED_BUILTIN_ESP); switch(led_pin) { case LED_BUILTIN_PCB: case LED_DOOR: on_value = LOW; break; case LED_WIFI: on_value = HIGH; break; default: UTILS_ASSERT(0); } if (on_off==1) { digitalWrite(led_pin, on_value); } else { digitalWrite(led_pin, on_value ^ 0x1); } } /* given baseline time (event_time_ms), get elapsed time. reset event_time_ms if the elapsed time wraps */ long utils_get_elapsed_msec_and_reset(long* pevent_time_ms) { long elapsed_ms; elapsed_ms = millis() - *pevent_time_ms; if (elapsed_ms < 0) { elapsed_ms = LONG_MAX; *pevent_time_ms = millis(); // reset } return elapsed_ms; } // from http://playground.arduino.cc/Code/PrintFloats // printFloat prints out the float 'value' rounded to 'places' places after the decimal point void utils_print_float(float value, int places) { // this is used to cast digits int digit; float tens = 0.1; int tenscount = 0; int i; float tempfloat = value; // make sure we round properly. this could use pow from <math.h>, but doesn't seem worth the import // if this rounding step isn't here, the value 54.321 prints as 54.3209 // calculate rounding term d: 0.5/pow(10,places) float d = 0.5; if (value < 0) d *= -1.0; // divide by ten for each decimal place for (i = 0; i < places; i++) d/= 10.0; // this small addition, combined with truncation will round our values properly tempfloat += d; // first get value tens to be the large power of ten less than value // tenscount isn't necessary but it would be useful if you wanted to know after this how many chars the number will take if (value < 0) tempfloat *= -1.0; while ((tens * 10.0) <= tempfloat) { tens *= 10.0; tenscount += 1; } // write out the negative if needed if (value < 0) Serial.print('-'); if (tenscount == 0) Serial.print(0, DEC); for (i=0; i< tenscount; i++) { digit = (int) (tempfloat/tens); Serial.print(digit, DEC); tempfloat = tempfloat - ((float)digit * tens); tens /= 10.0; } // if no places after decimal, stop now and return if (places <= 0) return; // otherwise, write the point and continue on Serial.print('.'); // now write out each decimal place by shifting digits one by one into the ones place and writing the truncated value for (i = 0; i < places; i++) { tempfloat *= 10.0; digit = (int) tempfloat; Serial.print(digit,DEC); // once written, subtract off that digit tempfloat = tempfloat - (float) digit; } //Serial.flush(); // don't flush because it screws up interrupt!! } // // enabling serial output slows down everything, can screw up mic readings #define ENABLE_OUTPUT 1 // printf-like fcn for debug void utils_log(const char *fmt, ... ) { #if ENABLE_OUTPUT char tmp[128]; // resulting string limited to 128 chars va_list args; va_start (args, fmt ); vsnprintf(tmp, 128, fmt, args); va_end (args); Serial.print(tmp); //Serial.flush(); // don't flush because it screws up interrupt!! #endif } void utils_assert(const char* pfilename, int line_number, int arg) { int blink = 1; if (arg) { return; } { char tmp[128]; // resulting string limited to 128 chars char fmt[] = "assertion at %s:%d\n"; sprintf(tmp, fmt, pfilename, line_number); Serial.print(tmp); Serial.flush(); } while(1) { digitalWrite(LED_BUILTIN_ESP, blink); digitalWrite(LED_BUILTIN_PCB, blink); digitalWrite(LED_WIFI, blink); blink ^= 0x1; delay(250); } }
23.940217
124
0.609762
robyu
e674401b9653f9b61ee6a01ef7e421a7f4ceb02a
268
cpp
C++
clang/test/Refactor/LocalRename/Field.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
clang/test/Refactor/LocalRename/Field.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/Refactor/LocalRename/Field.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
// RUN: clang-refactor local-rename -selection=test:%s -new-name=Bar %s -- | grep -v CHECK | FileCheck %s class Baz { int /*range=*/Foo; // CHECK: int /*range=*/Bar; public: Baz(); }; Baz::Baz() : /*range=*/Foo(0) {} // CHECK: Baz::Baz() : /*range=*/Bar(0) {}
22.333333
105
0.563433
medismailben
e67a970382a73baf94e8b29adccc21962818f947
1,661
cpp
C++
LeetCode/C++/General/Easy/GoatLatin/main.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
LeetCode/C++/General/Easy/GoatLatin/main.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
LeetCode/C++/General/Easy/GoatLatin/main.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> using namespace std; /* * Approach: follow the rules of goat latin provided below * * The rules of Goat Latin are as follows If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of the word. For example, the word 'apple' becomes 'applema'. If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add "ma". For example, the word "goat" becomes "oatgma". Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1. For example, the first word gets "a" added to the end, the second word gets "aa" added to the end and so on. * * * Time complexity: O(n) [where n is the length of the input string] * Space complexity: O(n) * */ bool isVowel(char c) { c=char(tolower(c)); return c=='a' || c=='e' || c=='i' || c=='o' || c=='u'; } string toGoatLatin(string S) { if(S.empty()) { return S; } string result{}; stringstream ss(S); string buffer{}; int count=1; while(ss >> buffer) { if(isVowel(buffer[0])) { buffer+="ma"; } else { reverse(buffer.begin(), buffer.end()); char c=buffer.back(); buffer.pop_back(); reverse(buffer.begin(), buffer.end()); buffer+=c; buffer+="ma"; } for(int i=0;i<count;++i) { buffer+='a'; } count++; result+=buffer; result+=" "; } result.pop_back(); return result; }
19.77381
122
0.545455
busebd12
e67b7a3ed7d58ac2d1b56263b10e099ca46e4cbc
24,954
cc
C++
dsmeLayer/messageDispatcher/MessageDispatcher.cc
sqf-ice/openDSME
2deeaa670136556517c49870ab0bd428f42b7a7a
[ "BSD-3-Clause" ]
null
null
null
dsmeLayer/messageDispatcher/MessageDispatcher.cc
sqf-ice/openDSME
2deeaa670136556517c49870ab0bd428f42b7a7a
[ "BSD-3-Clause" ]
null
null
null
dsmeLayer/messageDispatcher/MessageDispatcher.cc
sqf-ice/openDSME
2deeaa670136556517c49870ab0bd428f42b7a7a
[ "BSD-3-Clause" ]
1
2021-06-26T06:33:41.000Z
2021-06-26T06:33:41.000Z
/* * openDSME * * Implementation of the Deterministic & Synchronous Multi-channel Extension (DSME) * described in the IEEE 802.15.4-2015 standard * * Authors: Florian Kauer <florian.kauer@tuhh.de> * Maximilian Koestler <maximilian.koestler@tuhh.de> * Sandrina Backhauss <sandrina.backhauss@tuhh.de> * * Based on * DSME Implementation for the INET Framework * Tobias Luebkert <tobias.luebkert@tuhh.de> * * Copyright (c) 2015, Institute of Telematics, Hamburg University of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "./MessageDispatcher.h" #include "../../../dsme_platform.h" #include "../../../dsme_settings.h" #include "../../helper/DSMEDelegate.h" #include "../../helper/Integers.h" #include "../../interfaces/IDSMEMessage.h" #include "../../interfaces/IDSMEPlatform.h" #include "../../mac_services/DSME_Common.h" #include "../../mac_services/MacDataStructures.h" #include "../../mac_services/dataStructures/DSMEAllocationCounterTable.h" #include "../../mac_services/dataStructures/IEEE802154MacAddress.h" #include "../../mac_services/mcps_sap/DATA.h" #include "../../mac_services/mcps_sap/MCPS_SAP.h" #include "../../mac_services/pib/MAC_PIB.h" #include "../../mac_services/pib/PHY_PIB.h" #include "../../mac_services/pib/PIBHelper.h" #include "../DSMELayer.h" #include "../ackLayer/AckLayer.h" #include "../associationManager/AssociationManager.h" #include "../beaconManager/BeaconManager.h" #include "../capLayer/CAPLayer.h" #include "../gtsManager/GTSManager.h" #include "../messages/IEEE802154eMACHeader.h" #include "../messages/MACCommand.h" uint8_t mCh; namespace dsme { MessageDispatcher::MessageDispatcher(DSMELayer& dsme) : dsme(dsme), currentACTElement(nullptr, nullptr), doneGTS(DELEGATE(&MessageDispatcher::sendDoneGTS, *this)), dsmeAckFrame(nullptr), lastSendGTSNeighbor(neighborQueue.end()) { } MessageDispatcher::~MessageDispatcher() { for(NeighborQueue<MAX_NEIGHBORS>::iterator it = neighborQueue.begin(); it != neighborQueue.end(); ++it) { while(!this->neighborQueue.isQueueEmpty(it)) { IDSMEMessage* msg = neighborQueue.popFront(it); this->dsme.getPlatform().releaseMessage(msg); } } } void MessageDispatcher::initialize(void) { currentACTElement = dsme.getMAC_PIB().macDSMEACT.end(); return; } void MessageDispatcher::reset(void) { currentACTElement = dsme.getMAC_PIB().macDSMEACT.end(); for(NeighborQueue<MAX_NEIGHBORS>::iterator it = neighborQueue.begin(); it != neighborQueue.end(); ++it) { while(!this->neighborQueue.isQueueEmpty(it)) { IDSMEMessage* msg = neighborQueue.popFront(it); mcps_sap::DATA_confirm_parameters params; params.msduHandle = msg; params.timestamp = 0; params.rangingReceived = false; params.gtsTX = true; params.status = DataStatus::TRANSACTION_EXPIRED; params.numBackoffs = 0; this->dsme.getMCPS_SAP().getDATA().notify_confirm(params); } } while(this->neighborQueue.getNumNeighbors() > 0) { NeighborQueue<MAX_NEIGHBORS>::iterator it = this->neighborQueue.begin(); this->neighborQueue.eraseNeighbor(it); } return; } void MessageDispatcher::finalizeGTSTransmission() { transceiverOffIfAssociated(); this->lastSendGTSNeighbor = this->neighborQueue.end(); this->currentACTElement = this->dsme.getMAC_PIB().macDSMEACT.end(); } void MessageDispatcher::transceiverOffIfAssociated() { if(this->dsme.getMAC_PIB().macAssociatedPANCoord) { this->dsme.getPlatform().turnTransceiverOff(); } else { /* '-> do not turn off the transceiver while we might be scanning */ } } bool MessageDispatcher::handlePreSlotEvent(uint8_t nextSlot, uint8_t nextSuperframe, uint8_t nextMultiSuperframe) { // Prepare next slot // Switch to next slot channel and radio mode DSMEAllocationCounterTable& act = this->dsme.getMAC_PIB().macDSMEACT; if(this->currentACTElement != act.end()) { if(this->currentACTElement->getDirection() == Direction::RX) { this->currentACTElement = act.end(); } else { // Rarely happens, only if the sendDoneGTS is delayed // Then skip this preSlotEvent DSME_SIM_ASSERT(false); return false; } } if(nextSlot > this->dsme.getMAC_PIB().helper.getFinalCAPSlot(nextSuperframe)) { /* '-> next slot will be GTS */ unsigned nextGTS = nextSlot - (this->dsme.getMAC_PIB().helper.getFinalCAPSlot(nextSuperframe) + 1); if(act.isAllocated(nextSuperframe, nextGTS)) { /* '-> this slot might be used */ this->currentACTElement = act.find(nextSuperframe, nextGTS); DSME_ASSERT(this->currentACTElement != act.end()); // For TX currentACTElement will be reset in finalizeGTSTransmission, called by // either handleGTS if nothing is to send or by sendDoneGTS. // For RX it is reset in the next handlePreSlotEvent. // For RX also if INVALID or UNCONFIRMED! if((this->currentACTElement->getState() == VALID) || (this->currentACTElement->getDirection() == Direction::RX)) { this->dsme.getPlatform().turnTransceiverOn(); if(dsme.getMAC_PIB().macChannelDiversityMode == Channel_Diversity_Mode::CHANNEL_ADAPTATION) { this->dsme.getPlatform().setChannelNumber(this->dsme.getMAC_PIB().helper.getChannels()[this->currentACTElement->getChannel()]); mCh = this->currentACTElement->getChannel(); } else { /* Channel hopping: Calculate channel for given slotID */ uint16_t hoppingSequenceLength = this->dsme.getMAC_PIB().macHoppingSequenceLength; uint8_t ebsn = 0; // this->dsme.getMAC_PIB().macPanCoordinatorBsn; //TODO is this set correctly uint16_t sdIndex = nextSuperframe + this->dsme.getMAC_PIB().helper.getNumberSuperframesPerMultiSuperframe() * nextMultiSuperframe; uint8_t numGTSlots = this->dsme.getMAC_PIB().helper.getNumGTSlots(sdIndex); uint8_t slotId = this->currentACTElement->getGTSlotID(); uint16_t channelOffset = this->currentACTElement->getChannel(); // holds the channel offset in channel hopping mode uint8_t channel = this->dsme.getMAC_PIB().macHoppingSequenceList[(sdIndex * numGTSlots + slotId + channelOffset + ebsn) % hoppingSequenceLength]; LOG_INFO("Using channel " << channel << " - numGTSlots: " << numGTSlots << " EBSN: " << ebsn << " sdIndex: " << sdIndex << " slot: " << slotId << " Superframe " << nextSuperframe << " channelOffset: " << channelOffset << " Direction: " << currentACTElement->getDirection()); this->dsme.getPlatform().setChannelNumber(channel); mCh = channel; } } // statistic if(this->currentACTElement->getDirection() == RX) { this->numUnusedRxGts++; // gets PURGE.cc decremented on actual reception } } else { /* '-> nothing to do during this slot */ DSME_ASSERT(this->currentACTElement == act.end()); transceiverOffIfAssociated(); } } else if(nextSlot == 0) { /* '-> beacon slots are handled by the BeaconManager */ DSME_ASSERT(this->currentACTElement == act.end()); } else if(nextSlot == 1) { /* '-> next slot will be CAP */ if(!this->dsme.getMAC_PIB().macCapReduction || nextSuperframe == 0) { /* '-> active CAP slot */ this->dsme.getPlatform().turnTransceiverOn(); this->dsme.getPlatform().setChannelNumber(this->dsme.getPHY_PIB().phyCurrentChannel); } else { /* '-> CAP reduction */ transceiverOffIfAssociated(); } } return true; } bool MessageDispatcher::handleSlotEvent(uint8_t slot, uint8_t superframe, int32_t lateness) { if(slot > dsme.getMAC_PIB().helper.getFinalCAPSlot(superframe)) { handleGTS(lateness); } return true; } void MessageDispatcher::receive(IDSMEMessage* msg) { IEEE802154eMACHeader macHdr = msg->getHeader(); switch(macHdr.getFrameType()) { case IEEE802154eMACHeader::FrameType::BEACON: { LOG_INFO("BEACON from " << macHdr.getSrcAddr().getShortAddress() << " " << macHdr.getSrcPANId() << "."); this->dsme.getBeaconManager().handleBeacon(msg); this->dsme.getPlatform().releaseMessage(msg); break; } case IEEE802154eMACHeader::FrameType::COMMAND: { MACCommand cmd; cmd.decapsulateFrom(msg); switch(cmd.getCmdId()) { case CommandFrameIdentifier::DSME_GTS_REQUEST: LOG_INFO("DSME-GTS-REQUEST from " << macHdr.getSrcAddr().getShortAddress() << "."); dsme.getGTSManager().handleGTSRequest(msg); break; case CommandFrameIdentifier::DSME_GTS_REPLY: LOG_INFO("DSME-GTS-REPLY from " << macHdr.getSrcAddr().getShortAddress() << "."); dsme.getGTSManager().handleGTSResponse(msg); break; case CommandFrameIdentifier::DSME_GTS_NOTIFY: LOG_INFO("DSME-GTS-NOTIFY from " << macHdr.getSrcAddr().getShortAddress() << "."); dsme.getGTSManager().handleGTSNotify(msg); break; case CommandFrameIdentifier::ASSOCIATION_REQUEST: LOG_INFO("ASSOCIATION-REQUEST from " << macHdr.getSrcAddr().getShortAddress() << "."); dsme.getAssociationManager().handleAssociationRequest(msg); break; case CommandFrameIdentifier::ASSOCIATION_RESPONSE: LOG_INFO("ASSOCIATION-RESPONSE from " << macHdr.getSrcAddr().getShortAddress() << "."); dsme.getAssociationManager().handleAssociationReply(msg); break; case CommandFrameIdentifier::DISASSOCIATION_NOTIFICATION: LOG_INFO("DISASSOCIATION-NOTIFICATION from " << macHdr.getSrcAddr().getShortAddress() << "."); dsme.getAssociationManager().handleDisassociationRequest(msg); break; case CommandFrameIdentifier::DATA_REQUEST: /* Not implemented */ break; case CommandFrameIdentifier::DSME_BEACON_ALLOCATION_NOTIFICATION: LOG_INFO("DSME-BEACON-ALLOCATION-NOTIFICATION from " << macHdr.getSrcAddr().getShortAddress() << "."); dsme.getBeaconManager().handleBeaconAllocation(msg); break; case CommandFrameIdentifier::DSME_BEACON_COLLISION_NOTIFICATION: LOG_INFO("DSME-BEACON-COLLISION-NOTIFICATION from " << macHdr.getSrcAddr().getShortAddress() << "."); dsme.getBeaconManager().handleBeaconCollision(msg); break; case CommandFrameIdentifier::BEACON_REQUEST: LOG_INFO("BEACON_REQUEST from " << macHdr.getSrcAddr().getShortAddress() << "."); dsme.getBeaconManager().handleBeaconRequest(msg); break; default: LOG_ERROR("Invalid cmd ID " << (uint16_t)cmd.getCmdId()); // DSME_ASSERT(false); } dsme.getPlatform().releaseMessage(msg); break; } case IEEE802154eMACHeader::FrameType::DATA: { if(currentACTElement != dsme.getMAC_PIB().macDSMEACT.end()) { handleGTSFrame(msg); } else { createDataIndication(msg); } break; } default: { LOG_ERROR((uint16_t)macHdr.getFrameType()); dsme.getPlatform().releaseMessage(msg); } } return; } void MessageDispatcher::createDataIndication(IDSMEMessage* msg) { IEEE802154eMACHeader& header = msg->getHeader(); mcps_sap::DATA_indication_parameters params; params.msdu = msg; params.mpduLinkQuality = 0; // TODO link quality? params.dsn = header.getSequenceNumber(); params.timestamp = msg->getStartOfFrameDelimiterSymbolCounter(); params.securityLevel = header.isSecurityEnabled(); params.dataRate = 0; // DSSS -> 0 params.rangingReceived = NO_RANGING_REQUESTED; params.rangingCounterStart = 0; params.rangingCounterStop = 0; params.rangingTrackingInterval = 0; params.rangingOffset = 0; params.rangingFom = 0; this->dsme.getMCPS_SAP().getDATA().notify_indication(params); } bool MessageDispatcher::sendInGTS(IDSMEMessage* msg, NeighborQueue<MAX_NEIGHBORS>::iterator destIt) { DSME_ASSERT(!msg->getHeader().getDestAddr().isBroadcast()); DSME_ASSERT(this->dsme.getMAC_PIB().macAssociatedPANCoord); DSME_ASSERT(destIt != neighborQueue.end()); numUpperPacketsForGTS++; if(!neighborQueue.isQueueFull()) { /* push into queue */ // TODO implement TRANSACTION_EXPIRED uint16_t totalSize = 0; for(NeighborQueue<MAX_NEIGHBORS>::iterator it = neighborQueue.begin(); it != neighborQueue.end(); ++it) { totalSize += it->queueSize; } LOG_INFO("NeighborQueue is at " << totalSize << "/" << TOTAL_GTS_QUEUE_SIZE << "."); neighborQueue.pushBack(destIt, msg); return true; } else { /* queue full */ LOG_INFO("NeighborQueue is full!"); numUpperPacketsDroppedFullQueue++; return false; } } bool MessageDispatcher::sendInCAP(IDSMEMessage* msg) { numUpperPacketsForCAP++; LOG_INFO("Inserting message into CAP queue."); if(msg->getHeader().getSrcAddrMode() != EXTENDED_ADDRESS && !(this->dsme.getMAC_PIB().macAssociatedPANCoord)) { LOG_INFO("Message dropped due to missing association!"); // TODO document this behaviour // TODO send appropriate MCPS confirm or better remove this handling and implement TRANSACTION_EXPIRED return false; } if(!this->dsme.getCapLayer().pushMessage(msg)) { LOG_INFO("CAP queue full!"); return false; } return true; } void MessageDispatcher::handleGTS(int32_t lateness) { if(this->currentACTElement != this->dsme.getMAC_PIB().macDSMEACT.end() && this->currentACTElement->getSuperframeID() == this->dsme.getCurrentSuperframe() && this->currentACTElement->getGTSlotID() == this->dsme.getCurrentSlot() - (this->dsme.getMAC_PIB().helper.getFinalCAPSlot(dsme.getCurrentSuperframe()) + 1)) { /* '-> this slot matches the prepared ACT element */ if(this->currentACTElement->getDirection() == RX) { // also if INVALID or UNCONFIRMED! /* '-> a message may be received during this slot */ } else if(this->currentACTElement->getState() == VALID) { /* '-> if any messages are queued for this link, send one */ DSME_ASSERT(this->lastSendGTSNeighbor == this->neighborQueue.end()); IEEE802154MacAddress adr = IEEE802154MacAddress(this->currentACTElement->getAddress()); this->lastSendGTSNeighbor = this->neighborQueue.findByAddress(IEEE802154MacAddress(this->currentACTElement->getAddress())); if(this->lastSendGTSNeighbor == this->neighborQueue.end()) { /* '-> the neighbor associated with the current slot does not exist */ LOG_ERROR("neighborQueue.size: " << ((uint8_t)this->neighborQueue.getNumNeighbors())); LOG_ERROR("neighbor address: " << HEXOUT << adr.a1() << ":" << adr.a2() << ":" << adr.a3() << ":" << adr.a4() << DECOUT); for(auto it : this->neighborQueue) { LOG_ERROR("neighbor address: " << HEXOUT << it.address.a1() << ":" << it.address.a2() << ":" << it.address.a3() << ":" << it.address.a4() << DECOUT); } DSME_ASSERT(false); } if(this->neighborQueue.isQueueEmpty(this->lastSendGTSNeighbor)) { /* '-> no message to be sent */ finalizeGTSTransmission(); this->numUnusedTxGts++; } else { /* '-> a message is queued for transmission */ IDSMEMessage* msg = neighborQueue.front(this->lastSendGTSNeighbor); DSME_ASSERT(this->dsme.getMAC_PIB().helper.getSymbolsPerSlot() >= lateness + msg->getTotalSymbols() + this->dsme.getMAC_PIB().helper.getAckWaitDuration() + 10 /* arbitrary processing delay */ + PRE_EVENT_SHIFT); bool result = this->dsme.getAckLayer().prepareSendingCopy(msg, this->doneGTS); if(result) { /* '-> ACK-layer was ready, send message now * sendDoneGTS might have already been called, then sendNowIfPending does nothing! */ this->dsme.getAckLayer().sendNowIfPending(); } else { /* '-> message could not be sent -> probably currently receiving external interference */ sendDoneGTS(AckLayerResponse::SEND_FAILED, msg); } // statistics this->numTxGtsFrames++; } } else { finalizeGTSTransmission(); } } } void MessageDispatcher::handleGTSFrame(IDSMEMessage* msg) { DSME_ASSERT(currentACTElement != dsme.getMAC_PIB().macDSMEACT.end()); numRxGtsFrames++; numUnusedRxGts--; if(currentACTElement->getSuperframeID() == dsme.getCurrentSuperframe() && currentACTElement->getGTSlotID() == dsme.getCurrentSlot() - (dsme.getMAC_PIB().helper.getFinalCAPSlot(dsme.getCurrentSuperframe()) + 1)) { // According to 5.1.10.5.3 currentACTElement->resetIdleCounter(); } createDataIndication(msg); } void MessageDispatcher::onCSMASent(IDSMEMessage* msg, DataStatus::Data_Status status, uint8_t numBackoffs, uint8_t transmissionAttempts) { if(status == DataStatus::Data_Status::NO_ACK || status == DataStatus::Data_Status::SUCCESS) { if(msg->getHeader().isAckRequested() && !msg->getHeader().getDestAddr().isBroadcast()) { this->dsme.getPlatform().signalAckedTransmissionResult(status == DataStatus::Data_Status::SUCCESS,transmissionAttempts,msg->getHeader().getDestAddr()); } } if(msg->getReceivedViaMCPS()) { mcps_sap::DATA_confirm_parameters params; params.msduHandle = msg; params.timestamp = 0; // TODO params.rangingReceived = false; params.status = status; params.numBackoffs = numBackoffs; params.gtsTX = false; this->dsme.getMCPS_SAP().getDATA().notify_confirm(params); } else { if(msg->getHeader().getFrameType() == IEEE802154eMACHeader::FrameType::COMMAND) { MACCommand cmd; cmd.decapsulateFrom(msg); LOG_DEBUG("cmdID " << (uint16_t)cmd.getCmdId()); switch(cmd.getCmdId()) { case ASSOCIATION_REQUEST: case ASSOCIATION_RESPONSE: case DISASSOCIATION_NOTIFICATION: this->dsme.getAssociationManager().onCSMASent(msg, cmd.getCmdId(), status, numBackoffs); break; case DATA_REQUEST: case DSME_ASSOCIATION_REQUEST: case DSME_ASSOCIATION_RESPONSE: DSME_ASSERT(false); // TODO handle correctly this->dsme.getPlatform().releaseMessage(msg); break; case BEACON_REQUEST: case DSME_BEACON_ALLOCATION_NOTIFICATION: case DSME_BEACON_COLLISION_NOTIFICATION: this->dsme.getBeaconManager().onCSMASent(msg, cmd.getCmdId(), status, numBackoffs); break; case DSME_GTS_REQUEST: case DSME_GTS_REPLY: case DSME_GTS_NOTIFY: this->dsme.getGTSManager().onCSMASent(msg, cmd.getCmdId(), status, numBackoffs); break; } } else { this->dsme.getPlatform().releaseMessage(msg); } } } void MessageDispatcher::sendDoneGTS(enum AckLayerResponse response, IDSMEMessage* msg) { LOG_DEBUG("sendDoneGTS"); DSME_ASSERT(lastSendGTSNeighbor != neighborQueue.end()); DSME_ASSERT(msg == neighborQueue.front(lastSendGTSNeighbor)); DSMEAllocationCounterTable& act = this->dsme.getMAC_PIB().macDSMEACT; DSME_ASSERT(this->currentACTElement != act.end()); if(response != AckLayerResponse::NO_ACK_REQUESTED && response != AckLayerResponse::ACK_SUCCESSFUL) { currentACTElement->incrementIdleCounter(); // not successful -> retry? if(msg->getRetryCounter() < dsme.getMAC_PIB().macMaxFrameRetries) { msg->increaseRetryCounter(); finalizeGTSTransmission(); LOG_DEBUG("sendDoneGTS - retry"); return; // will stay at front of queue } } if(response == AckLayerResponse::ACK_FAILED || response == AckLayerResponse::ACK_SUCCESSFUL) { this->dsme.getPlatform().signalAckedTransmissionResult(response == AckLayerResponse::ACK_SUCCESSFUL,msg->getRetryCounter()+1,msg->getHeader().getDestAddr()); } neighborQueue.popFront(lastSendGTSNeighbor); lastSendGTSNeighbor = neighborQueue.end(); mcps_sap::DATA_confirm_parameters params; params.msduHandle = msg; params.timestamp = 0; // TODO params.rangingReceived = false; params.gtsTX = true; switch(response) { case AckLayerResponse::NO_ACK_REQUESTED: case AckLayerResponse::ACK_SUCCESSFUL: LOG_DEBUG("sendDoneGTS - success"); params.status = DataStatus::SUCCESS; break; case AckLayerResponse::ACK_FAILED: DSME_ASSERT(this->currentACTElement != this->dsme.getMAC_PIB().macDSMEACT.end()); currentACTElement->incrementIdleCounter(); params.status = DataStatus::NO_ACK; break; case AckLayerResponse::SEND_FAILED: LOG_DEBUG("SEND_FAILED during GTS"); DSME_ASSERT(this->currentACTElement != this->dsme.getMAC_PIB().macDSMEACT.end()); currentACTElement->incrementIdleCounter(); params.status = DataStatus::CHANNEL_ACCESS_FAILURE; break; case AckLayerResponse::SEND_ABORTED: LOG_DEBUG("SEND_ABORTED during GTS"); params.status = DataStatus::TRANSACTION_EXPIRED; break; default: DSME_ASSERT(false); } params.numBackoffs = 0; this->dsme.getMCPS_SAP().getDATA().notify_confirm(params); finalizeGTSTransmission(); } } /* namespace dsme */
44.010582
165
0.621463
sqf-ice
e68128e1ee6ef3659e28c5e3098c6c928d81fe97
2,484
cxx
C++
gastpc/psreco/NeutrinoEnergy.cxx
LBNE/wp1-neardetector
729c30532670679b7c87131ec70b4141d04a3ede
[ "BSD-3-Clause" ]
3
2016-04-13T12:14:53.000Z
2017-03-28T22:46:03.000Z
gastpc/psreco/NeutrinoEnergy.cxx
DUNE/wp1-neardetector
729c30532670679b7c87131ec70b4141d04a3ede
[ "BSD-3-Clause" ]
null
null
null
gastpc/psreco/NeutrinoEnergy.cxx
DUNE/wp1-neardetector
729c30532670679b7c87131ec70b4141d04a3ede
[ "BSD-3-Clause" ]
1
2015-03-03T10:32:47.000Z
2015-03-03T10:32:47.000Z
// ------------------------------------------------------------------- /// \file NeutrinoEnergy.cxx /// \brief /// /// \author <justo.martin-albo@physics.ox.ac.uk> /// \date Creation: 21 Feb 2017 // ------------------------------------------------------------------- #include "NeutrinoEnergy.h" #include "MCGenInfo.h" #include "MCParticle.h" #include "RecoParticle.h" #include "Units.h" #include "Utils.h" #include <Ntuple/NtpMCEventRecord.h> #include <Interaction/Interaction.h> #include <Interaction/Kinematics.h> #include <cmath> NeutrinoEnergy::NeutrinoEnergy(std::vector<std::pair<gastpc::MCParticle*, gastpc::RecoParticle*>> v): true_energy_(0.), reco_energy_(0.), true_y_(0.), reco_y_(0.) { for (auto particle: v) { if (!particle.first || !particle.second) continue; int reco_pdg = std::abs(particle.second->GetPDGCode()); double momentum = Utils::Magnitude(particle.second->GetInitialMomentum()); if (reco_pdg == 11) { double mass_e = 0.5109989461 * gastpc::MeV; reco_energy_ += std::sqrt(momentum*momentum + mass_e*mass_e); reco_y_ = std::sqrt(momentum*momentum + mass_e*mass_e); } else if (reco_pdg == 13) { double mass_mu = 105.6583745 * gastpc::MeV; reco_energy_ += std::sqrt(momentum*momentum + mass_mu*mass_mu); reco_y_ = std::sqrt(momentum*momentum + mass_mu*mass_mu); } else if (reco_pdg == 211) { double mass_pi = 139.57018 * gastpc::MeV; reco_energy_ += std::sqrt(momentum*momentum + mass_pi*mass_pi); } else if (reco_pdg == 2212) { reco_energy_ += momentum; } else if (reco_pdg == 111) { reco_energy_ += momentum; } } // Use first element of vector (any would do) to extract the true // neutrino energy and inelasticity from genie record gastpc::MCGenInfo* mcgi = v[0].first->GetMCGenInfo(); genie::NtpMCEventRecord* gmcrec = mcgi->GetGeneratorRecord(); genie::Interaction* interaction = (gmcrec->event)->Summary(); true_energy_ = (interaction->InitState().ProbeE(genie::kRfLab)) * gastpc::GeV; // Calculate inelasticity reco_y_ = 1. - reco_y_ / reco_energy_; true_y_ = (interaction->KinePtr()->y(true)); } NeutrinoEnergy::~NeutrinoEnergy() { } double NeutrinoEnergy::RecoEnergy() const { return reco_energy_; } double NeutrinoEnergy::TrueEnergy() const { return true_energy_; } double NeutrinoEnergy::RecoY() const { return reco_y_; } double NeutrinoEnergy::TrueY() const { return true_y_; }
25.608247
101
0.638486
LBNE
e6846dfa782c1192b7fd803f4d28908922313f6b
1,222
cpp
C++
src/mayaToCorona/src/shaders/TestShader.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
42
2015-01-03T15:07:25.000Z
2021-12-09T03:56:59.000Z
src/mayaToCorona/src/shaders/TestShader.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
66
2015-01-02T13:28:44.000Z
2022-03-16T14:00:57.000Z
src/mayaToCorona/src/shaders/TestShader.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
12
2015-02-07T05:02:17.000Z
2020-07-10T17:21:44.000Z
#include "TestShader.h" MTypeId TestShader::id(0x81000); void TestShader::postConstructor() { setMPSafe(true); } MObject TestShader::aColor; MObject TestShader::aOutColor; TestShader::TestShader(){} TestShader::~TestShader(){} void* TestShader::creator() { return new TestShader(); } MStatus TestShader::initialize() { MFnNumericAttribute nAttr; MStatus status; aColor = nAttr.createColor("color", "color"); CHECK_MSTATUS(addAttribute(aColor)); aOutColor = nAttr.createColor("outColor", "oc"); CHECK_MSTATUS(addAttribute(aOutColor)); CHECK_MSTATUS( attributeAffects( aColor, aOutColor ) ); return(MS::kSuccess); } MStatus TestShader::compute(const MPlug& plug, MDataBlock& block) { MStatus status; if (plug == aOutColor || plug.parent() == aOutColor) { MDataHandle outColorHandle = block.outputValue(aOutColor, &status); CHECK_MSTATUS(status); MFloatVector& outColor = outColorHandle.asFloatVector(); MDataHandle iColor = block.inputValue(aColor, &status); MFloatVector& inColor = iColor.asFloatVector(); outColor = inColor; outColorHandle.setClean(); return(MS::kSuccess); } else { return(MS::kUnknownParameter); // We got an unexpected plug } return(MS::kSuccess); }
20.711864
69
0.731588
haggi
e687ad1ca9524ae5ad13e11e2a854149310d8744
726
cpp
C++
framework/src/platform/windows/network/windows_socket_api.cpp
jesseroffel/Rakas
1bb7200f43c1a3cf5ffb7d27c200cc97717c9d8f
[ "MIT" ]
null
null
null
framework/src/platform/windows/network/windows_socket_api.cpp
jesseroffel/Rakas
1bb7200f43c1a3cf5ffb7d27c200cc97717c9d8f
[ "MIT" ]
null
null
null
framework/src/platform/windows/network/windows_socket_api.cpp
jesseroffel/Rakas
1bb7200f43c1a3cf5ffb7d27c200cc97717c9d8f
[ "MIT" ]
null
null
null
#include "sampo_pch.hpp" #include "platform/windows/network/windows_socket_api.hpp" #include <WinSock2.h> namespace Sampo { void WindowsSocketAPI::Init() { WSADATA startupResultData; int error = WSAStartup(MAKEWORD(2, 2), &startupResultData); if (error != 0) { SAMPO_CORE_CRITICAL("WSAStartup error: ({0})", WSAGetLastError()); } s_Running = true; } void WindowsSocketAPI::Shutdown() { if (s_Running) { s_Running = false; int error = WSACleanup(); if (error != 0) { SAMPO_CORE_ERROR("WSACleanup error: ({0})", WSAGetLastError()); } } } }
22
79
0.535813
jesseroffel
e689ae5c2e118018376af25033897d7b771220b3
1,261
cpp
C++
modules/boost/simd/sdk/unit/memory/utility/allocator.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/sdk/unit/memory/utility/allocator.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/sdk/unit/memory/utility/allocator.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <boost/simd/memory/allocator.hpp> #include <boost/simd/memory/is_aligned.hpp> #include <vector> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/unit/tests/relation.hpp> #include <nt2/sdk/unit/tests/basic.hpp> NT2_TEST_CASE_TPL(vector, BOOST_SIMD_TYPES) { using boost::simd::is_aligned; std::vector<T, boost::simd::allocator<T> > p(5); NT2_TEST( is_aligned( &p[0] ) ); for(int i=0;i<5;++i) p[i] = T(10)*i; for(int i=0;i<5;++i) NT2_TEST_EQUAL(p[i],T(10)*i); } NT2_TEST_CASE_TPL(vector_n, BOOST_SIMD_TYPES) { using boost::simd::is_aligned; std::vector<T, boost::simd::allocator<T, 4> > p(5); NT2_TEST( is_aligned( &p[0],4 ) ); for(int i=0;i<5;++i) p[i] = T(10)*i; for(int i=0;i<5;++i) NT2_TEST_EQUAL(p[i],T(10)*i); }
35.027778
80
0.559873
psiha
e68d8d80fd2ef5c4213afd8d966f4d905ea98169
1,962
cpp
C++
day3/3b.cpp
ympek/aoc2021
54a1c60273907183afdcf716b1eed1dc24024b29
[ "MIT" ]
null
null
null
day3/3b.cpp
ympek/aoc2021
54a1c60273907183afdcf716b1eed1dc24024b29
[ "MIT" ]
null
null
null
day3/3b.cpp
ympek/aoc2021
54a1c60273907183afdcf716b1eed1dc24024b29
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <string> #include <bitset> #include <algorithm> constexpr int BIT_COUNT = 12; enum RatingType { OXYGEN_RATING, CO2_RATING }; int calculateNumberOfOnesAtColumn(std::vector<std::string>& bitsets, int columnIndex) { int result = 0; for (auto& bset : bitsets) { if (bset[columnIndex] == '1') { result++; } } return result; } int calculateRating(std::vector<std::string> bitsets, RatingType type) { int index = 0; while(true) { int onesInColumn = calculateNumberOfOnesAtColumn(bitsets, index); int zeroesInColumn = bitsets.size() - onesInColumn; char mostCommonBit = (onesInColumn >= zeroesInColumn) ? '1' : '0'; auto oxygenCriteria = [=](auto bset) -> bool { return bset[index] != mostCommonBit; }; bitsets.erase( std::remove_if( bitsets.begin(), bitsets.end(), [=](auto bset) -> bool { if (type == RatingType::OXYGEN_RATING) { return bset[index] != mostCommonBit; } else { return bset[index] == mostCommonBit; } }), bitsets.end()); index++; if (index == BIT_COUNT || bitsets.size() == 1) { break; } } auto onlyNumberLeft = bitsets[0]; long rating = 0; for (int i = 0; i < BIT_COUNT; i++) { int bitValue = (onlyNumberLeft[i] == '1') ? 1 : 0; rating |= bitValue << (BIT_COUNT - 1 - i); } return rating; } int main() { std::ifstream inputStream("./input"); std::string bits; long oxygenGeneratorRating = 0; long co2ScrubberRating = 0; std::vector<std::string> bitsets; while(inputStream >> bits) { bitsets.emplace_back(bits); } oxygenGeneratorRating = calculateRating(bitsets, RatingType::OXYGEN_RATING); co2ScrubberRating = calculateRating(bitsets, RatingType::CO2_RATING); std::cout << "Result: " << oxygenGeneratorRating * co2ScrubberRating << "\n"; }
24.222222
90
0.616718
ympek
e68dfc1d775b77a2be6b347fa2224175c93b64f7
853
cpp
C++
Codeforces/Edu Codeforces Round 100 (div2)/A.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
4
2021-01-27T11:51:30.000Z
2021-01-30T17:02:55.000Z
Codeforces/Edu Codeforces Round 100 (div2)/A.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
null
null
null
Codeforces/Edu Codeforces Round 100 (div2)/A.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
5
2021-01-27T11:46:12.000Z
2021-05-06T05:37:47.000Z
#include <bits/stdc++.h> #define x first #define y second #define pb push_back #define all(v) v.begin(),v.end() #pragma gcc optimize("O3") #pragma gcc optimize("Ofast") #pragma gcc optimize("unroll-loops") using namespace std; const int INF = 1e9; const int TMX = 1 << 18; const long long llINF = 2e18; const long long mod = 1e18; const long long hashmod = 100003; typedef long long ll; typedef long double ld; typedef pair <int,int> pi; typedef pair <ll,ll> pl; typedef vector <int> vec; typedef vector <pi> vecpi; typedef long long ll; int a,b,c; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int T; cin >> T; while(T--) { cin >> a >> b >> c; if(a > b) swap(a,b); if(b > c) swap(b,c); if(a > b) swap(a,b); if((a+b+c) % 9 == 0) { if((a+b+c)/9 > a) cout << "NO\n"; else cout << "YES\n"; } else cout << "NO\n"; } }
21.871795
46
0.621336
python-programmer1512
e6945f88d0f7b5316ca794741eae10f8494740cf
383
cpp
C++
HackerRank/Algorithms/Implementation/Find Digits.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
HackerRank/Algorithms/Implementation/Find Digits.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
HackerRank/Algorithms/Implementation/Find Digits.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <iostream> using namespace std; int divisors(int n){ int count=0; int num = n; while(n>0){ int digit = n%10; if(digit!=0 && num%digit==0){ count++; } n=n/10; } return count; } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; cout<<divisors(n)<<endl; } }
16.652174
38
0.428198
Ashwanigupta9125
e694da08754a7e9fe2f91053a5d44cdfc8f09b42
4,303
cpp
C++
src/main.cpp
vaefremov/otus_hw_09
de6c0634f344179a0a40b20f276ea08190059b5e
[ "BSD-2-Clause" ]
1
2020-07-02T13:13:36.000Z
2020-07-02T13:13:36.000Z
src/main.cpp
vaefremov/otus_hw_09
de6c0634f344179a0a40b20f276ea08190059b5e
[ "BSD-2-Clause" ]
null
null
null
src/main.cpp
vaefremov/otus_hw_09
de6c0634f344179a0a40b20f276ea08190059b5e
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include <ostream> #include <cstdlib> #include <string> #include <vector> #include <algorithm> #include <boost/program_options.hpp> #include "files_comparator.h" #include "scanner.h" namespace po = boost::program_options; using str_vector=std::vector<std::string>; size_t const DEFAULT_BLOCK_SZ = 1024UL; // Default block size std::ostream& operator<<(std::ostream& out, std::vector<std::string> const vect) { for(auto e: vect) { out << " " << e; } return out; } void output_report(std::ostream& out, OTUS::FilesComparator::Report_t const& report, bool isVerbose=false) { if(isVerbose) { out << "=========================================" << std::endl; out << "== Report: total of " << report.size() << " groups of identical files" << std::endl; out << "=========================================" << std::endl; } for(auto& files_group: report) { for (auto& f: files_group) { out << f << std::endl; } out << std::endl; } } std::vector<OTUS::Scanner::fspath> convert_paths(std::vector<std::string> arg) { std::vector<OTUS::Scanner::fspath> res; std::transform(arg.begin(), arg.end(), std::back_inserter(res), [](auto s){return boost::filesystem::path(s);}); // @TODO: Check if paths are valid! return res; } int main(int argc, const char** argv) { po::options_description desc("Finding the identical files"); desc.add_options() ("help,h", "this help") ("path,I", po::value<std::vector<std::string>>(), "search paths") ("exclude,x", po::value<std::vector<std::string>>(), "exclude directories from search, optional") ("depth,d", po::value<size_t>()->default_value(OTUS::DEF_MAX_DEPTH), "depth of recursive search") ("verbose,v", po::bool_switch(), "verbose output") ("block_sz,b", po::value<size_t>()->default_value(DEFAULT_BLOCK_SZ), "block size") ("mask,m", po::value<std::vector<std::string>>(), "masks (regexp), optional") ("hash,H", po::value<std::string>()->default_value("crc32"), "hash method, options are: crc32 (default), md5") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; return EXIT_SUCCESS; } bool isVerbose = vm["verbose"].as<bool>(); if(isVerbose) std::cout << "Verbose: " << isVerbose << std::endl; size_t max_depth = vm["depth"].as<size_t>(); if(isVerbose) std::cout << "Max depth: " << vm["depth"].as<size_t>() << std::endl; size_t block_sz = vm["block_sz"].as<size_t>(); if(isVerbose) std::cout << "Block sz: " << block_sz << std::endl; str_vector paths{"./"}; if(vm.count("path")) paths = vm["path"].as<std::vector<std::string>>(); if(isVerbose) std::cout << "Paths: " << paths << std::endl; if (vm.count("exclude") && isVerbose) std::cout << "Exclude: " << vm["exclude"].as<std::vector<std::string>>() << std::endl; if (vm.count("mask") && isVerbose) std::cout << "Masks: " << vm["mask"].as<std::vector<std::string>>() << std::endl; if(isVerbose) std::cout << "Hash: " << vm["hash"].as<std::string>() << std::endl; try { OTUS::HashKind hash_kind = OTUS::hash_name_from_string(vm["hash"].as<std::string>()); OTUS::Scanner scanner(convert_paths(paths)); scanner.set_verbose(vm["verbose"].as<bool>()); if(vm.count("exclude")) scanner.exclude_paths(convert_paths(vm["exclude"].as<std::vector<std::string>>())); if(vm.count("mask")) scanner.masks(vm["mask"].as<std::vector<std::string>>()); scanner.set_depth(max_depth); auto comparator = OTUS::FilesComparator::create_subscribed(scanner, block_sz, hash_kind, isVerbose); scanner.run(); OTUS::FilesComparator::Report_t report = comparator->report(); output_report(std::cout, report, isVerbose); } catch(const std::exception& e) { std::cout << "Error: " << e.what() << std::endl; std::cout << desc << "\n"; return EXIT_SUCCESS; } return EXIT_SUCCESS; }
33.356589
118
0.571462
vaefremov
e69cba15c43aff44e72649283e229b1050cb163b
1,052
cpp
C++
test/common.cpp
mark-grimes/Palgo
c9ef617f71c10575f035ccee97f445c6d9baccca
[ "Apache-2.0" ]
null
null
null
test/common.cpp
mark-grimes/Palgo
c9ef617f71c10575f035ccee97f445c6d9baccca
[ "Apache-2.0" ]
null
null
null
test/common.cpp
mark-grimes/Palgo
c9ef617f71c10575f035ccee97f445c6d9baccca
[ "Apache-2.0" ]
null
null
null
#include "common.h" #include <random> // // Unnamed namespace for things only used in this file // namespace { /** @brief a global pseudo-random number generator so that I don't have repeats of number sequences * * Gets set in the first call to "nextRandomNumber". */ std::function<float()> globalRandomGenerator; } // end of the unnamed namespace float test::nextRandomNumber() { if( ! ::globalRandomGenerator ) { std::default_random_engine engine; typename std::uniform_real_distribution<float> random(0,100); ::globalRandomGenerator=std::bind( random, engine ); } return ::globalRandomGenerator(); } bool test::Point3D::operator==( const Point3D& other ) { return x==other.x && y==other.y && z==other.z; } template<> void test::setRandom( test::Point3D& point ) { point.x=nextRandomNumber(); point.y=nextRandomNumber(); point.z=nextRandomNumber(); } std::ostream& test::operator<<( std::ostream& output, const test::Point3D& point ) { output << "[" << point.x << "," << point.y << "," << point.z << "]"; return output; }
23.377778
100
0.686312
mark-grimes
e6a2197b7e42dadfdb3816dbdad9d88dd303f1c2
2,047
cpp
C++
test/kumi/map.cpp
kitegi/ofw
3c25d24b221a945b3e7edbcf0367bb0873ea0e50
[ "MIT" ]
1
2021-07-16T18:17:24.000Z
2021-07-16T18:17:24.000Z
test/kumi/map.cpp
kitegi/ofw
3c25d24b221a945b3e7edbcf0367bb0873ea0e50
[ "MIT" ]
null
null
null
test/kumi/map.cpp
kitegi/ofw
3c25d24b221a945b3e7edbcf0367bb0873ea0e50
[ "MIT" ]
null
null
null
//================================================================================================== /** RABERU - Fancy Parameters Library Copyright : RABERU Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #define TTS_MAIN #include <tts/tts.hpp> #include <kumi.hpp> TTS_CASE("Check map(f, tuple) behavior") { TTS_WHEN("Given a tuple t") { auto t = kumi::tuple{1,2.,3.4f,'5'}; TTS_AND_THEN(" - we call map(f,t)") { auto s = map( [](auto m) { return sizeof(m); }, t ); auto[m0,m1,m2,m3] = s; TTS_EQUAL(m0, sizeof(int) ); TTS_EQUAL(m1, sizeof(double)); TTS_EQUAL(m2, sizeof(float) ); TTS_EQUAL(m3, sizeof(char) ); } TTS_AND_THEN(" - we call map(f,t,u)") { auto u = kumi::tuple{2,3,4,5}; auto s = map( [](auto m, auto n) { return n * sizeof(m); }, t, u ); auto[m0,m1,m2,m3] = s; TTS_EQUAL(m0, 2*sizeof(int) ); TTS_EQUAL(m1, 3*sizeof(double)); TTS_EQUAL(m2, 4*sizeof(float) ); TTS_EQUAL(m3, 5*sizeof(char) ); } } } TTS_CASE("Check map(f, tuple) constexpr behavior") { TTS_WHEN("Given a tuple t") { constexpr auto t = kumi::tuple{1,2.,3.4f,'5'}; TTS_AND_THEN(" - we call t.map(f)") { constexpr auto s = map( [](auto m) { return sizeof(m); }, t ); TTS_CONSTEXPR_EQUAL(get<0>(s), sizeof(int) ); TTS_CONSTEXPR_EQUAL(get<1>(s), sizeof(double)); TTS_CONSTEXPR_EQUAL(get<2>(s), sizeof(float) ); TTS_CONSTEXPR_EQUAL(get<3>(s), sizeof(char) ); } TTS_AND_THEN(" - we call t.map(f,u)") { constexpr auto u = kumi::tuple{2,3,4,5}; constexpr auto s = map( [](auto m, auto n) { return n * sizeof(m); }, t, u ); TTS_CONSTEXPR_EQUAL(get<0>(s), 2*sizeof(int) ); TTS_CONSTEXPR_EQUAL(get<1>(s), 3*sizeof(double)); TTS_CONSTEXPR_EQUAL(get<2>(s), 4*sizeof(float) ); TTS_CONSTEXPR_EQUAL(get<3>(s), 5*sizeof(char) ); } } }
28.830986
100
0.514411
kitegi
e6a3c7dbac938d5541069a0df784319199747752
8,566
cc
C++
hoomd/md/ActiveForceComputeGPU.cc
jglaser/hoomd-blue
c21ae2b48314dcb7ac03fc1b23baf70879cc6709
[ "BSD-3-Clause" ]
null
null
null
hoomd/md/ActiveForceComputeGPU.cc
jglaser/hoomd-blue
c21ae2b48314dcb7ac03fc1b23baf70879cc6709
[ "BSD-3-Clause" ]
null
null
null
hoomd/md/ActiveForceComputeGPU.cc
jglaser/hoomd-blue
c21ae2b48314dcb7ac03fc1b23baf70879cc6709
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2009-2021 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainer: joaander #include "ActiveForceComputeGPU.h" #include "ActiveForceComputeGPU.cuh" #include <vector> namespace py = pybind11; using namespace std; /*! \file ActiveForceComputeGPU.cc \brief Contains code for the ActiveForceComputeGPU class */ /*! \param f_list An array of (x,y,z) tuples for the active force vector for each individual particle. \param orientation_link if True then forces and torques are applied in the particle's reference frame. If false, then the box reference fra me is used. Only relevant for non-point-like anisotropic particles. /param orientation_reverse_link When True, the particle's orientation is set to match the active force vector. Useful for for using a particle's orientation to log the active force vector. Not recommended for anisotropic particles \param rotation_diff rotational diffusion constant for all particles. \param constraint specifies a constraint surface, to which particles are confined, such as update.constraint_ellipsoid. */ ActiveForceComputeGPU::ActiveForceComputeGPU(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ParticleGroup> group, Scalar rotation_diff, Scalar3 P, Scalar rx, Scalar ry, Scalar rz) : ActiveForceCompute(sysdef, group, rotation_diff, P, rx, ry, rz), m_block_size(256) { if (!m_exec_conf->isCUDAEnabled()) { m_exec_conf->msg->error() << "Creating a ActiveForceComputeGPU with no GPU in the execution configuration" << endl; throw std::runtime_error("Error initializing ActiveForceComputeGPU"); } //unsigned int N = m_pdata->getNGlobal(); //unsigned int group_size = m_group->getNumMembersGlobal(); unsigned int type = m_pdata->getNTypes(); GlobalVector<Scalar4> tmp_f_activeVec(type, m_exec_conf); GlobalVector<Scalar4> tmp_t_activeVec(type, m_exec_conf); { ArrayHandle<Scalar4> old_f_activeVec(m_f_activeVec, access_location::host); ArrayHandle<Scalar4> old_t_activeVec(m_t_activeVec, access_location::host); ArrayHandle<Scalar4> f_activeVec(tmp_f_activeVec, access_location::host); ArrayHandle<Scalar4> t_activeVec(tmp_t_activeVec, access_location::host); // for each type of the particles in the group for (unsigned int i = 0; i < type; i++) { f_activeVec.data[i] = old_f_activeVec.data[i]; t_activeVec.data[i] = old_t_activeVec.data[i]; } last_computed = 10; } m_f_activeVec.swap(tmp_f_activeVec); m_t_activeVec.swap(tmp_t_activeVec); } /*! This function sets appropriate active forces and torques on all active particles. */ void ActiveForceComputeGPU::setForces() { // array handles ArrayHandle<Scalar4> d_f_actVec(m_f_activeVec, access_location::device, access_mode::read); ArrayHandle<Scalar4> d_force(m_force, access_location::device, access_mode::overwrite); ArrayHandle<Scalar4> d_t_actVec(m_t_activeVec, access_location::device, access_mode::read); ArrayHandle<Scalar4> d_torque(m_torque, access_location::device, access_mode::overwrite); ArrayHandle<Scalar4> d_pos(m_pdata -> getPositions(), access_location::device, access_mode::read); ArrayHandle<Scalar4> d_orientation(m_pdata->getOrientationArray(), access_location::device, access_mode::read); ArrayHandle<unsigned int> d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read); // sanity check assert(d_force.data != NULL); assert(d_f_actVec.data != NULL); assert(d_t_actVec.data != NULL); assert(d_pos.data != NULL); assert(d_orientation.data != NULL); assert(d_index_array.data != NULL); unsigned int group_size = m_group->getNumMembers(); unsigned int N = m_pdata->getN(); gpu_compute_active_force_set_forces(group_size, d_index_array.data, d_force.data, d_torque.data, d_pos.data, d_orientation.data, d_f_actVec.data, d_t_actVec.data, m_P, m_rx, m_ry, m_rz, N, m_block_size); } /*! This function applies rotational diffusion to all active particles. The angle between the torque vector and * force vector does not change \param timestep Current timestep */ void ActiveForceComputeGPU::rotationalDiffusion(uint64_t timestep) { // array handles ArrayHandle<Scalar4> d_f_actVec(m_f_activeVec, access_location::device, access_mode::readwrite); ArrayHandle<Scalar4> d_pos(m_pdata -> getPositions(), access_location::device, access_mode::read); ArrayHandle<Scalar4> d_orientation(m_pdata->getOrientationArray(), access_location::device, access_mode::readwrite); ArrayHandle<unsigned int> d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read); ArrayHandle<unsigned int> d_tag(m_pdata->getTags(), access_location::device, access_mode::read); assert(d_pos.data != NULL); bool is2D = (m_sysdef->getNDimensions() == 2); unsigned int group_size = m_group->getNumMembers(); gpu_compute_active_force_rotational_diffusion(group_size, d_tag.data, d_index_array.data, d_pos.data, d_orientation.data, d_f_actVec.data, m_P, m_rx, m_ry, m_rz, is2D, m_rotationConst, timestep, m_sysdef->getSeed(), m_block_size); } /*! This function sets an ellipsoid surface constraint for all active particles */ void ActiveForceComputeGPU::setConstraint() { EvaluatorConstraintEllipsoid Ellipsoid(m_P, m_rx, m_ry, m_rz); // array handles ArrayHandle<Scalar4> d_f_actVec(m_f_activeVec, access_location::device, access_mode::readwrite); ArrayHandle<Scalar4> d_pos(m_pdata -> getPositions(), access_location::device, access_mode::read); ArrayHandle<Scalar4> d_orientation(m_pdata->getOrientationArray(), access_location::device, access_mode::readwrite); ArrayHandle<unsigned int> d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read); assert(d_pos.data != NULL); unsigned int group_size = m_group->getNumMembers(); gpu_compute_active_force_set_constraints(group_size, d_index_array.data, d_pos.data, d_orientation.data, d_f_actVec.data, m_P, m_rx, m_ry, m_rz, m_block_size); } void export_ActiveForceComputeGPU(py::module& m) { py::class_< ActiveForceComputeGPU, ActiveForceCompute, std::shared_ptr<ActiveForceComputeGPU> >(m, "ActiveForceComputeGPU") .def(py::init< std::shared_ptr<SystemDefinition>, std::shared_ptr<ParticleGroup>, Scalar, Scalar3, Scalar, Scalar, Scalar >()) ; }
46.053763
214
0.574714
jglaser
e6a4453a4a7f687ba271e8577e9b8498ab986ffb
7,380
cpp
C++
flir_lepton_image_processing/src/utils/parameters.cpp
angetria/flir_lepton_rpi2
46b1de815e2bfb752954fb2c3648d416f56e6c93
[ "BSD-3-Clause" ]
15
2015-11-10T10:39:53.000Z
2022-03-29T07:07:53.000Z
flir_lepton_image_processing/src/utils/parameters.cpp
angetria/flir_lepton
46b1de815e2bfb752954fb2c3648d416f56e6c93
[ "BSD-3-Clause" ]
6
2015-10-23T12:18:45.000Z
2019-07-02T09:55:46.000Z
flir_lepton_image_processing/src/utils/parameters.cpp
angetria/flir_lepton_rpi2
46b1de815e2bfb752954fb2c3648d416f56e6c93
[ "BSD-3-Clause" ]
6
2017-04-13T12:28:38.000Z
2019-07-03T21:58:51.000Z
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2015, P.A.N.D.O.R.A. Team. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the P.A.N.D.O.R.A. Team nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Authors: Alexandros Philotheou, Manos Tsardoulias * Angelos Triantafyllidis <aggelostriadafillidis@gmail.com> *********************************************************************/ #include "utils/parameters.h" /** @brief The namespaces for this package **/ namespace flir_lepton { namespace flir_lepton_image_processing { //////////////////// Blob detection - specific parameters //////////////////// int Parameters::Blob::min_threshold = 0; int Parameters::Blob::max_threshold = 200; int Parameters::Blob::threshold_step = 100; int Parameters::Blob::min_area = 550; int Parameters::Blob::max_area = 300000; double Parameters::Blob::min_convexity = 0; double Parameters::Blob::max_convexity = 100; double Parameters::Blob::min_inertia_ratio = 0; double Parameters::Blob::max_circularity = 1.0; double Parameters::Blob::min_circularity = 0.3; bool Parameters::Blob::filter_by_color = 0; bool Parameters::Blob::filter_by_circularity = 1; ///////////////////////// Debug-specific parameters ////////////////////////// // Show the thermal image that arrives in the thermal node bool Parameters::Debug::show_thermal_image = false; // In the terminal's window, show the probabilities of candidate holes bool Parameters::Debug::show_probabilities = false; bool Parameters::Debug::show_find_rois = false; int Parameters::Debug::show_find_rois_size = 1000; bool Parameters::Debug::show_denoise_edges = false; int Parameters::Debug::show_denoise_edges_size = 900; bool Parameters::Debug::show_connect_pairs = false; int Parameters::Debug::show_connect_pairs_size = 1200; bool Parameters::Debug::show_get_shapes_clear_border = false; int Parameters::Debug::show_get_shapes_clear_border_size = 1200; ////////////////// Parameters specific to the Thermal node //////////////////// // The thermal detection method // If set to 0 process the binary image acquired from temperatures MultiArray // If set to 1 process the sensor/Image from thermal sensor int Parameters::Thermal::detection_method = 0; // The probability extraction method // 0 for Gaussian function // 1 for Logistic function int Parameters::Thermal::probability_method = 1; float Parameters::Thermal::min_thermal_probability = 0.3; // Gausian variables float Parameters::Thermal::optimal_temperature = 35; float Parameters::Thermal::tolerance = 10; // Logistic variables float Parameters::Thermal::low_acceptable_temperature = 32; float Parameters::Thermal::high_acceptable_temperature = 38; float Parameters::Thermal::left_tolerance = 4; float Parameters::Thermal::right_tolerance = 8; ///////////// Parameters of acceptable temperature for threshold ///////////// float Parameters::Thermal::low_temperature = 28; float Parameters::Thermal::high_temperature = 40; ////////////////////// Parameters of the thermal image /////////////////////// int Parameters::ThermalImage::WIDTH = 80; int Parameters::ThermalImage::HEIGHT = 60; ///////////////////// Edge detection specific parameters ///////////////////// // canny parameters int Parameters::Edge::canny_ratio = 3; int Parameters::Edge::canny_kernel_size = 3; int Parameters::Edge::canny_low_threshold = 50; int Parameters::Edge::canny_blur_noise_kernel_size = 3; // The opencv edge detection method: // 0 for the Canny edge detector // 1 for the Scharr edge detector // 2 for the Sobel edge detector // 3 for the Laplacian edge detector // 4 for mixed Scharr / Sobel edge detection int Parameters::Edge::edge_detection_method = 2; // Threshold parameters int Parameters::Edge::denoised_edges_threshold = 10; // When mixed edge detection is selected, this toggle switch // is needed in order to shift execution from one edge detector // to the other. // 1 for the Scharr edge detector, // 2 for the Sobel edge detector int Parameters::Edge::mixed_edges_toggle_switch = 1; ////////////////// Image representation specific parameters ////////////////// // The depth sensor's horizontal field of view in rads float Parameters::Image::horizontal_field_of_view = static_cast<float>(58) / 180 * M_PI; // The depth sensor's vertical field of view in rads float Parameters::Image::vertical_field_of_view = static_cast<float>(45) / 180 * M_PI; // Depth and RGB images' representation method. // 0 if image used is used as obtained from the image sensor // 1 through wavelet analysis int Parameters::Image::image_representation_method = 0; // Method to scale the CV_32F image to CV_8UC1 int Parameters::Image::scale_method = 0; // Term criteria for segmentation purposes int Parameters::Image::term_criteria_max_iterations = 5; double Parameters::Image::term_criteria_max_epsilon = 1; /////////////////// Outline discovery specific parameters //////////////////// // The detection method used to obtain the outline of a blob // 0 for detecting by means of brushfire // 1 for detecting by means of raycasting int Parameters::Outline::outline_detection_method = 0; // When using raycast instead of brushfire to find the (approximate here) // outline of blobs, raycast_keypoint_partitions dictates the number of // rays, or equivalently, the number of partitions in which the blob is // partitioned in search of the blob's borders int Parameters::Outline::raycast_keypoint_partitions = 32; // Loose ends connection parameters int Parameters::Outline::AB_to_MO_ratio = 4; int Parameters::Outline::minimum_curve_points = 50; } // namespace flir_lepton_image_processing } // namespace flir_lepton
39.891892
81
0.702981
angetria
e6a549ac9e60654755928fbf79dec92943890818
16,051
cpp
C++
MonoNative.Tests/mscorlib/System/Security/Cryptography/X509Certificates/mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/Security/Cryptography/X509Certificates/mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/Security/Cryptography/X509Certificates/mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Security.Cryptography.X509Certificates // Name: X509Certificate // C++ Typed Name: mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate #include <gtest/gtest.h> #include <mscorlib/System/Security/Cryptography/X509Certificates/mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { namespace Security { namespace Cryptography { namespace X509Certificates { //Constructors Tests //X509Certificate(std::vector<mscorlib::System::Byte*> data) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_1) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::IntPtr handle) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_2) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate &cert) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_3) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate() TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,DefaultConstructor) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::String password) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_5) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::Security::SecureString password) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_6) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::String password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_7) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::Security::SecureString password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_8) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::String fileName) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_9) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::String fileName, mscorlib::System::String password) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_10) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::String fileName, mscorlib::System::Security::SecureString password) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_11) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::String fileName, mscorlib::System::String password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_12) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::String fileName, mscorlib::System::Security::SecureString password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_13) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //X509Certificate(mscorlib::System::Runtime::Serialization::SerializationInfo info, mscorlib::System::Runtime::Serialization::StreamingContext context) TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Constructor_14) { mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate *value = new mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate(); EXPECT_NE(NULL, value->GetNativeObject()); } //Public Methods Tests // Method Equals // Signature: mscorlib::System::Security::Cryptography::X509Certificates::X509Certificate other TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Equals_1_Test) { } // Method GetCertHash // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetCertHash_Test) { } // Method GetCertHashString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetCertHashString_Test) { } // Method GetEffectiveDateString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetEffectiveDateString_Test) { } // Method GetExpirationDateString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetExpirationDateString_Test) { } // Method GetFormat // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetFormat_Test) { } // Method GetHashCode // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetHashCode_Test) { } // Method GetIssuerName // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetIssuerName_Test) { } // Method GetKeyAlgorithm // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetKeyAlgorithm_Test) { } // Method GetKeyAlgorithmParameters // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetKeyAlgorithmParameters_Test) { } // Method GetKeyAlgorithmParametersString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetKeyAlgorithmParametersString_Test) { } // Method GetName // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetName_Test) { } // Method GetPublicKey // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetPublicKey_Test) { } // Method GetPublicKeyString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetPublicKeyString_Test) { } // Method GetRawCertData // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetRawCertData_Test) { } // Method GetRawCertDataString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetRawCertDataString_Test) { } // Method GetSerialNumber // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetSerialNumber_Test) { } // Method GetSerialNumberString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,GetSerialNumberString_Test) { } // Method ToString // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,ToString_1_Test) { } // Method ToString // Signature: mscorlib::System::Boolean fVerbose TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,ToString_2_Test) { } // Method Equals // Signature: mscorlib::System::Object obj TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Equals_2_Test) { } // Method Export // Signature: mscorlib::System::Security::Cryptography::X509Certificates::X509ContentType::__ENUM__ contentType TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Export_1_Test) { } // Method Export // Signature: mscorlib::System::Security::Cryptography::X509Certificates::X509ContentType::__ENUM__ contentType, mscorlib::System::String password TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Export_2_Test) { } // Method Export // Signature: mscorlib::System::Security::Cryptography::X509Certificates::X509ContentType::__ENUM__ contentType, mscorlib::System::Security::SecureString password TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Export_3_Test) { } // Method Import // Signature: std::vector<mscorlib::System::Byte*> rawData TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_1_Test) { } // Method Import // Signature: std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::String password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_2_Test) { } // Method Import // Signature: std::vector<mscorlib::System::Byte*> rawData, mscorlib::System::Security::SecureString password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_3_Test) { } // Method Import // Signature: mscorlib::System::String fileName TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_4_Test) { } // Method Import // Signature: mscorlib::System::String fileName, mscorlib::System::String password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_5_Test) { } // Method Import // Signature: mscorlib::System::String fileName, mscorlib::System::Security::SecureString password, mscorlib::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags::__ENUM__ keyStorageFlags TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Import_6_Test) { } // Method Reset // Signature: TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,Reset_Test) { } //Public Static Methods Tests // Method CreateFromCertFile // Signature: mscorlib::System::String filename TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,CreateFromCertFile_StaticTest) { } // Method CreateFromSignedFile // Signature: mscorlib::System::String filename TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,CreateFromSignedFile_StaticTest) { } //Public Properties Tests // Property Issuer // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,get_Issuer_Test) { } // Property Subject // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,get_Subject_Test) { } // Property Handle // Return Type: mscorlib::System::IntPtr // Property Get Method TEST(mscorlib_System_Security_Cryptography_X509Certificates_X509Certificate_Fixture,get_Handle_Test) { } } } } } }
34.151064
226
0.722323
brunolauze
e6a6096dc9c35918ce09bdd653dc04af88d9c0ac
4,250
cpp
C++
tc 160+/CrazyComponents.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/CrazyComponents.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/CrazyComponents.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; bool done[50][1<<15]; double dp[50][1<<15]; int N; vector<int> I, E, M; double go(int k, int have) { if (k == -1) return 0.0; if (done[k][have]) return dp[k][have]; done[k][have] = 1; double &ret = dp[k][have]; ret = 0.0; for (int i=0; i<N; ++i) if ((have & M[i]) == M[i]) ret += max(go(k-1, have), I[i]-E[i] + go(k-1, (have | (1<<i)))); else ret += go(k-1, have); ret /= N; return ret; } class CrazyComponents { public: double expectedProfit(int k, vector <string> components, vector <int> income, vector <int> expense) { N = components.size(); I = income; E = expense; memset(done, 0, sizeof done); M.assign(N, 0); for (int i=0; i<N; ++i) { istringstream is(components[i]); int x; while (is >> x) M[i] |= (1<<x); } return go(k-1, 0); } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 1; string Arr1[] = { "", "" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 1, 2 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = { 0, 0 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); double Arg4 = 1.5; verify_case(0, Arg4, expectedProfit(Arg0, Arg1, Arg2, Arg3)); } void test_case_1() { int Arg0 = 2; string Arr1[] = { "1", "" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 10, 0 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = { 0, 2 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); double Arg4 = 1.5; verify_case(1, Arg4, expectedProfit(Arg0, Arg1, Arg2, Arg3)); } void test_case_2() { int Arg0 = 3; string Arr1[] = { "1 2", "", "" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 100, 0, 0 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = { 0, 0, 0 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); double Arg4 = 7.407407407407408; verify_case(2, Arg4, expectedProfit(Arg0, Arg1, Arg2, Arg3)); } void test_case_3() { int Arg0 = 5; string Arr1[] = { "1", "2", "0", "" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 4, 5, 6, 7 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = { 0, 0, 0, 8 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); double Arg4 = 0.0; verify_case(3, Arg4, expectedProfit(Arg0, Arg1, Arg2, Arg3)); } void test_case_4() { int Arg0 = 10; string Arr1[] = { "", "", "", "", "", "", "", "", "", "" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 142352, 2342, 34534, 2344, 12346, 7589, 79872, 973453, 96233, 34567 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = { 12432, 2345, 3678, 456, 345, 457, 56758, 4564, 774, 34567 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); double Arg4 = 1269258.9999999998; verify_case(4, Arg4, expectedProfit(Arg0, Arg1, Arg2, Arg3)); } // END CUT HERE }; // BEGIN CUT HERE int main() { CrazyComponents ___test; ___test.run_test(-1); } // END CUT HERE
48.850575
558
0.571529
ibudiselic
e6a799067dc2efa0333720915a68138f7731ed44
669
hpp
C++
src/cpp/Module/Filter/Filter_FIR/Filter_FIR_ccr/Filter_FIR_ccr_fast.hpp
rtajan/eirballoon
0eded8f86174a9e5ed38297fa26c7f5a53b5ea53
[ "MIT" ]
null
null
null
src/cpp/Module/Filter/Filter_FIR/Filter_FIR_ccr/Filter_FIR_ccr_fast.hpp
rtajan/eirballoon
0eded8f86174a9e5ed38297fa26c7f5a53b5ea53
[ "MIT" ]
null
null
null
src/cpp/Module/Filter/Filter_FIR/Filter_FIR_ccr/Filter_FIR_ccr_fast.hpp
rtajan/eirballoon
0eded8f86174a9e5ed38297fa26c7f5a53b5ea53
[ "MIT" ]
null
null
null
#ifndef FILTER_FIR_CCR_FAST_HPP #define FILTER_FIR_CCR_FAST_HPP #include <vector> #include <complex> #include "Module/Filter/Filter_FIR/Filter_FIR_ccr/Filter_FIR_ccr.hpp" namespace aff3ct { namespace module { template <typename R = float> class Filter_FIR_ccr_fast : public Filter_FIR_ccr<R> { protected: int M; int P; public: Filter_FIR_ccr_fast (const int N, const std::vector<R> b); virtual ~Filter_FIR_ccr_fast(); virtual Filter_FIR_ccr_fast<R>* clone() const; protected: virtual void _filter(const R *X_N1, R *Y_N2, const int frame_id); virtual void _filter_old(const R *X_N1, R *Y_N2, const int frame_id); }; } } #endif //FILTER_FIR_CCR_FAST_HPP
19.114286
71
0.763827
rtajan
e6a828118b7a73876b5ecdd2059681963b4f2006
14,566
cc
C++
chaps/opencryptoki_importer_test.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
chaps/opencryptoki_importer_test.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
chaps/opencryptoki_importer_test.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chaps/opencryptoki_importer.h" #include <stdlib.h> #include <map> #include <memory> #include <string> #include <vector> #include <base/files/scoped_temp_dir.h> #include <base/logging.h> #include <base/stl_util.h> #include <base/strings/stringprintf.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "chaps/chaps_factory_mock.h" #include "chaps/object_mock.h" #include "chaps/object_pool_mock.h" #include "chaps/tpm_utility_mock.h" using base::FilePath; using std::map; using std::string; using std::vector; using testing::_; using testing::AnyNumber; using testing::DoAll; using testing::Invoke; using testing::Return; using testing::SetArgPointee; using testing::Values; namespace chaps { const unsigned char kSampleMasterKeyEncrypted[] = { 80, 118, 191, 150, 143, 171, 162, 61, 89, 32, 95, 219, 44, 244, 51, 84, 117, 228, 36, 225, 240, 122, 234, 92, 182, 224, 133, 238, 100, 18, 116, 130, 166, 177, 7, 103, 223, 122, 112, 136, 126, 30, 191, 253, 137, 85, 70, 187, 220, 137, 248, 155, 89, 152, 113, 153, 113, 48, 59, 148, 246, 114, 146, 13, 86, 254, 227, 3, 229, 70, 247, 165, 101, 76, 3, 58, 134, 230, 84, 113, 94, 226, 134, 130, 34, 100, 56, 157, 5, 255, 127, 180, 147, 56, 43, 233, 32, 254, 209, 52, 41, 48, 15, 127, 110, 187, 183, 254, 123, 20, 182, 153, 107, 192, 136, 229, 72, 243, 38, 238, 155, 59, 216, 15, 17, 72, 39, 209, 196, 66, 53, 140, 236, 132, 19, 69, 58, 107, 103, 22, 19, 70, 175, 35, 126, 16, 56, 132, 150, 89, 182, 12, 3, 166, 206, 160, 194, 12, 250, 211, 141, 73, 109, 83, 144, 253, 166, 71, 109, 219, 143, 202, 237, 89, 185, 136, 249, 104, 78, 68, 11, 169, 144, 194, 57, 140, 147, 104, 175, 229, 20, 223, 98, 109, 187, 120, 200, 126, 81, 147, 31, 13, 239, 36, 233, 221, 78, 117, 59, 248, 156, 231, 189, 232, 48, 128, 150, 128, 84, 244, 30, 117, 183, 150, 70, 30, 234, 2, 233, 161, 120, 96, 185, 155, 34, 75, 173, 200, 78, 183, 66, 8, 144, 72, 20, 92, 246, 229, 255, 55, 148, 160, 153, 9, 150, 16}; const unsigned char kSampleMasterKey[] = { 116, 62, 77, 252, 196, 57, 225, 14, 115, 52, 68, 60, 227, 254, 22, 162, 163, 22, 186, 125, 203, 138, 205, 98, 151, 202, 179, 203, 86, 98, 149, 208}; const unsigned char kSampleAuthDataEncrypted[] = { 37, 239, 160, 111, 19, 123, 167, 118, 161, 223, 61, 242, 63, 146, 22, 223, 100, 79, 178, 52, 206, 121, 155, 88, 23, 68, 144, 66, 167, 187, 83, 13, 101, 221, 218, 185, 99, 23, 149, 3, 239, 142, 78, 62, 239, 155, 114, 83, 106, 108, 168, 225, 241, 58, 49, 59, 235, 234, 51, 92, 241, 75, 120, 26, 8, 36, 238, 241, 33, 192, 170, 136, 138, 57, 87, 210, 181, 143, 111, 181, 251, 30, 50, 64, 48, 96, 195, 223, 172, 221, 19, 127, 253, 182, 102, 219, 36, 245, 246, 106, 157, 177, 230, 129, 130, 253, 51, 91, 214, 35, 221, 43, 174, 7, 185, 169, 92, 126, 52, 160, 212, 233, 158, 142, 120, 255, 212, 32, 10, 176, 112, 73, 71, 51, 72, 143, 218, 157, 186, 106, 146, 71, 24, 94, 216, 98, 114, 127, 56, 47, 38, 35, 63, 141, 193, 82, 107, 240, 39, 154, 28, 134, 32, 96, 16, 32, 54, 233, 74, 242, 136, 178, 236, 0, 243, 5, 78, 98, 219, 0, 104, 70, 235, 248, 169, 38, 88, 129, 219, 84, 197, 53, 232, 186, 157, 6, 24, 161, 86, 118, 85, 227, 72, 215, 30, 64, 236, 224, 234, 168, 16, 118, 4, 154, 170, 157, 85, 80, 158, 87, 14, 17, 76, 15, 11, 151, 157, 15, 42, 92, 34, 255, 244, 162, 195, 158, 162, 207, 167, 119, 9, 218, 218, 148, 33, 54, 131, 66, 125, 12, 141, 245, 162, 229, 134, 227}; const unsigned char kSampleAuthData[] = {29, 230, 13, 53, 202, 172, 136, 59, 83, 139, 43, 154, 175, 183, 163, 205, 110, 117, 149, 144}; const char kTokenPath[] = ".tpm"; const char kTokenObjectPath[] = "TOK_OBJ"; const char kSampleToken[] = "opencryptoki_sample_token.tgz"; const int kPublicSampleObjects = 3; const int kPrivateSampleObjects = 2; string Bytes2String(const unsigned char* bytes, size_t num_bytes) { return string(reinterpret_cast<const char*>(bytes), num_bytes); } void RunCommand(string command) { int status = system(command.c_str()); ASSERT_EQ(0, WEXITSTATUS(status)); } // Performs hard-coded transformations as a TPM would do. These match the // sample token data for this test, they are not useful in general. bool MockUnbind(int key, const string& input, string* output) { map<string, string> transforms; string encrypted = Bytes2String(kSampleMasterKeyEncrypted, base::size(kSampleMasterKeyEncrypted)); string decrypted = Bytes2String(kSampleMasterKey, base::size(kSampleMasterKey)); transforms[encrypted] = decrypted; encrypted = Bytes2String(kSampleAuthDataEncrypted, base::size(kSampleAuthDataEncrypted)); decrypted = Bytes2String(kSampleAuthData, base::size(kSampleAuthData)); transforms[encrypted] = decrypted; map<string, string>::iterator iter = transforms.find(input); if (iter != transforms.end()) { *output = iter->second; return true; } return false; } // Creates a very 'nice' object mock. Object* CreateObjectMock() { ObjectMock* o = new ObjectMock(); o->SetupFake(); EXPECT_CALL(*o, GetObjectClass()).Times(AnyNumber()); EXPECT_CALL(*o, SetAttributes(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, FinalizeNewObject()).WillRepeatedly(Return(CKR_OK)); EXPECT_CALL(*o, Copy(_)).WillRepeatedly(Return(CKR_OK)); EXPECT_CALL(*o, IsTokenObject()).Times(AnyNumber()); EXPECT_CALL(*o, IsPrivate()).Times(AnyNumber()); EXPECT_CALL(*o, IsAttributePresent(_)).Times(AnyNumber()); EXPECT_CALL(*o, GetAttributeString(_)).Times(AnyNumber()); EXPECT_CALL(*o, GetAttributeInt(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, GetAttributeBool(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, SetAttributeString(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, SetAttributeInt(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, SetAttributeBool(_, _)).Times(AnyNumber()); EXPECT_CALL(*o, GetAttributeMap()).Times(AnyNumber()); EXPECT_CALL(*o, set_handle(_)).Times(AnyNumber()); EXPECT_CALL(*o, set_store_id(_)).Times(AnyNumber()); EXPECT_CALL(*o, handle()).Times(AnyNumber()); EXPECT_CALL(*o, store_id()).Times(AnyNumber()); return o; } // A test fixture base class for testing the importer. class TestImporterBase { public: TestImporterBase() { CHECK(temp_dir_.CreateUniqueTempDir()); importer_.reset(new OpencryptokiImporter( 0, temp_dir_.GetPath().Append(kTokenPath), &tpm_, &factory_)); // Set expectations for the TPM utility mock. EXPECT_CALL(tpm_, Unbind(_, _, _)).WillRepeatedly(Invoke(MockUnbind)); EXPECT_CALL(tpm_, LoadKey(_, _, _, _)) .WillRepeatedly(DoAll(SetArgPointee<3>(1), Return(true))); EXPECT_CALL(tpm_, LoadKeyWithParent(_, _, _, _, _)) .WillRepeatedly(DoAll(SetArgPointee<4>(1), Return(true))); // Set expectations for the factory mock. EXPECT_CALL(factory_, CreateObject()) .WillRepeatedly(Invoke(CreateObjectMock)); // Set expectations for the object pool mock. pool_.SetupFake(0); EXPECT_CALL(pool_, Insert(_)).Times(AnyNumber()); EXPECT_CALL(pool_, Import(_)).Times(AnyNumber()); EXPECT_CALL(pool_, Find(_, _)).Times(AnyNumber()); EXPECT_CALL(pool_, SetInternalBlob(3, _)).WillRepeatedly(Return(true)); EXPECT_CALL(pool_, SetInternalBlob(4, _)).WillRepeatedly(Return(true)); } protected: void PrepareSampleToken() { CHECK(temp_dir_.IsValid()); RunCommand(base::StringPrintf("tar -xzf %s -C %s", kSampleToken, temp_dir_.GetPath().value().c_str())); } ChapsFactoryMock factory_; ObjectPoolMock pool_; std::unique_ptr<OpencryptokiImporter> importer_; TPMUtilityMock tpm_; base::ScopedTempDir temp_dir_; }; // A function that returns the number of objects expected to be imported. // Returns -1 if a failure is expected. struct ModifierResult { bool import_public_result; bool import_private_result; int num_public_objects; int num_private_objects; }; typedef ModifierResult (*ModifierCallback)(const char* object_path); const ModifierResult kModifierSuccess = {true, true, kPublicSampleObjects, kPrivateSampleObjects}; const ModifierResult kModifierNone = {true, true, 0, 0}; const ModifierResult kModifierPublicOnly = {true, true, kPublicSampleObjects, 0}; const ModifierResult kModifierOneBadPublic = { true, true, kPublicSampleObjects - 1, kPrivateSampleObjects}; const ModifierResult kModifierOneBadPrivate = {true, true, kPublicSampleObjects, kPrivateSampleObjects - 1}; // A parameterized fixture so we can run the same test(s) with multiple modifier // functions. class TestImporterWithModifier : public TestImporterBase, public testing::TestWithParam<ModifierCallback> {}; // This test attempts to import a sample token after it has been modified by a // modifier function. TEST_P(TestImporterWithModifier, ImportSample) { PrepareSampleToken(); FilePath object_path = temp_dir_.GetPath().Append(kTokenPath).Append(kTokenObjectPath); ModifierCallback modifier = GetParam(); ModifierResult expected_result = modifier(object_path.value().c_str()); EXPECT_EQ(expected_result.import_public_result, importer_->ImportObjects(&pool_)); vector<const Object*> objects; pool_.Find(NULL, &objects); EXPECT_EQ(expected_result.num_public_objects, objects.size()); EXPECT_EQ(expected_result.import_private_result, importer_->FinishImportAsync(&pool_)); objects.clear(); pool_.Find(NULL, &objects); int total_objects = expected_result.num_public_objects + expected_result.num_private_objects; EXPECT_EQ(total_objects, objects.size()); } ModifierResult NoModify(const char* object_path) { // If we don't modify anything, the import should succeed. return kModifierSuccess; } ModifierResult DeleteAll(const char* object_path) { FilePath token_path = FilePath(object_path).DirName(); RunCommand(base::StringPrintf("rm -rf %s", token_path.value().c_str())); return kModifierNone; } ModifierResult DeleteAllObjectFiles(const char* object_path) { RunCommand(base::StringPrintf("rm -f %s/*", object_path)); return kModifierNone; } ModifierResult DeleteMasterKey(const char* object_path) { FilePath token_path = FilePath(object_path).DirName(); RunCommand( base::StringPrintf("rm -f %s/MK_PRIVATE", token_path.value().c_str())); return kModifierPublicOnly; } ModifierResult DeleteObjectIndex(const char* object_path) { RunCommand(base::StringPrintf("rm -f %s/OBJ.IDX", object_path)); return kModifierNone; } ModifierResult DeleteAllButIndex(const char* object_path) { RunCommand(base::StringPrintf("rm -f %s/*0000", object_path)); return kModifierNone; } ModifierResult DeleteHierarchyFile(const char* object_path) { RunCommand(base::StringPrintf("rm -f %s/50000000", object_path)); return kModifierPublicOnly; } ModifierResult TruncateFile0(const char* object_path) { RunCommand(base::StringPrintf(":> %s/B0000000", object_path)); return kModifierOneBadPublic; } ModifierResult TruncateFile5(const char* object_path) { RunCommand(base::StringPrintf("truncate -s 5 %s/B0000000", object_path)); return kModifierOneBadPublic; } ModifierResult TruncateFile21(const char* object_path) { RunCommand(base::StringPrintf("truncate -s 21 %s/B0000000", object_path)); return kModifierOneBadPublic; } ModifierResult TruncateFile80(const char* object_path) { RunCommand(base::StringPrintf("truncate -s 80 %s/B0000000", object_path)); return kModifierOneBadPublic; } ModifierResult TruncateEncrypted(const char* object_path) { RunCommand(base::StringPrintf("truncate -s 80 %s/C0000000", object_path)); return kModifierOneBadPrivate; } ModifierResult AddNotIndexed(const char* object_path) { RunCommand(base::StringPrintf(":> %s/D0000000", object_path)); return kModifierSuccess; } ModifierResult AppendJunk(const char* object_path) { RunCommand(base::StringPrintf("head -c 100 < /dev/urandom >> %s/B0000000", object_path)); return kModifierOneBadPublic; } ModifierResult AppendJunkEncrypted(const char* object_path) { RunCommand(base::StringPrintf("head -c 100 < /dev/urandom >> %s/C0000000", object_path)); return kModifierOneBadPrivate; } // List of parameterized test cases. INSTANTIATE_TEST_SUITE_P(ModifierTests, TestImporterWithModifier, Values(NoModify, DeleteAll, DeleteAllObjectFiles, DeleteMasterKey, DeleteObjectIndex, DeleteAllButIndex, DeleteHierarchyFile, TruncateFile0, TruncateFile5, TruncateFile21, TruncateFile80, TruncateEncrypted, AddNotIndexed, AppendJunk, AppendJunkEncrypted)); ModifierResult RandomizeFile(const char* object_path) { RunCommand(base::StringPrintf("head -c 1000 < /dev/urandom > %s/C0000000", object_path)); return kModifierOneBadPrivate; } ModifierResult RandomizeObjectAttributes(const char* object_path) { RunCommand(base::StringPrintf("truncate -s 21 %s/B0000000", object_path)); RunCommand(base::StringPrintf("head -c 1000 < /dev/urandom >> %s/B0000000", object_path)); return kModifierOneBadPublic; } // List of test cases that involve randomization; these are listed separately // for easy filtering. INSTANTIATE_TEST_SUITE_P(RandomizedTests, TestImporterWithModifier, Values(RandomizeFile, RandomizeObjectAttributes)); } // namespace chaps
40.687151
80
0.650076
strassek
e6ab81000a8c5f072d041835ff9887b24ded1e64
42
cpp
C++
src/trade.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
1
2021-11-19T02:56:04.000Z
2021-11-19T02:56:04.000Z
src/trade.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
null
null
null
src/trade.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
null
null
null
#include "trade.h" Trade::Trade() { }
6
18
0.547619
joestilin
e6b0e1cc12facd8462d70acacc250ca1de37ab14
630
cpp
C++
src/engine/core/src/dummy/dummy_network.cpp
sunhay/halley
fc4f153956cc34d7fa02b76850e22183b8e30e25
[ "Apache-2.0" ]
3,262
2016-04-10T15:24:10.000Z
2022-03-31T17:47:08.000Z
src/engine/core/src/dummy/dummy_network.cpp
sunhay/halley
fc4f153956cc34d7fa02b76850e22183b8e30e25
[ "Apache-2.0" ]
53
2016-10-09T16:25:04.000Z
2022-01-10T13:52:37.000Z
src/engine/core/src/dummy/dummy_network.cpp
sunhay/halley
fc4f153956cc34d7fa02b76850e22183b8e30e25
[ "Apache-2.0" ]
193
2017-10-23T06:08:41.000Z
2022-03-22T12:59:58.000Z
#include "dummy_network.h" using namespace Halley; void DummyNetworkAPI::init() {} void DummyNetworkAPI::deInit() {} std::unique_ptr<NetworkService> DummyNetworkAPI::createService(NetworkProtocol protocol, int port) { return std::make_unique<DummyNetworkService>(); } void DummyNetworkService::update() { } void DummyNetworkService::setAcceptingConnections(bool accepting) { } std::shared_ptr<IConnection> DummyNetworkService::tryAcceptConnection() { return std::shared_ptr<IConnection>(); } std::shared_ptr<IConnection> DummyNetworkService::connect(String address, int port) { return std::shared_ptr<IConnection>(); }
21
98
0.78254
sunhay
e6b2e92d70eb468c2a908dff0bb9cd0472b0c42e
1,355
hpp
C++
include/metall/utility/metall_mpi_datastore.hpp
dice-group/metall
1b899e7d28264ecf937cf848e934eccadc581783
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
37
2019-07-03T05:48:42.000Z
2022-03-10T20:41:53.000Z
include/metall/utility/metall_mpi_datastore.hpp
dice-group/metall
1b899e7d28264ecf937cf848e934eccadc581783
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
19
2019-05-29T07:56:45.000Z
2022-02-02T07:13:46.000Z
include/metall/utility/metall_mpi_datastore.hpp
dice-group/metall
1b899e7d28264ecf937cf848e934eccadc581783
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
12
2019-06-11T21:56:37.000Z
2022-01-20T15:51:28.000Z
// Copyright 2020 Lawrence Livermore National Security, LLC and other Metall Project Developers. // See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (Apache-2.0 OR MIT) #ifndef METALL_UTILITY_METALL_MPI_DATASTORE_HPP #define METALL_UTILITY_METALL_MPI_DATASTORE_HPP #include <string> /// \namespace metall::utility::mpi_datastore /// \brief Namespace for MPI datastore namespace metall::utility::mpi_datastore { /// \brief Makes a path of a root directory. /// The MPI ranks that share the same storage space create their data stores under the root directory. /// \param root_dir_prefix A prefix of a root directory path. /// \return A path of a root directory. inline std::string make_root_dir_path(const std::string &root_dir_prefix) { return root_dir_prefix + "/"; } /// \brief Makes the data store path of a MPI rank. /// \param root_dir_prefix A prefix of a root directory path. /// \param rank A MPI rank. /// \return A path to a local data store directory. /// The path can be passed to, for example, metall::manager to perform operations. inline std::string make_local_dir_path(const std::string &root_dir_prefix, const int rank) { return make_root_dir_path(root_dir_prefix) + "/subdir-" + std::to_string(rank); } } // namespace metall::utility::mpi_datastore #endif //METALL_UTILITY_METALL_MPI_DATASTORE_HPP
38.714286
102
0.764576
dice-group
e6b46421afa7268e026cfb79438f59a2c5457cdf
3,513
cc
C++
paddle/fluid/operators/clip_by_norm_op_npu.cc
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
11
2016-08-29T07:43:26.000Z
2016-08-29T07:51:24.000Z
paddle/fluid/operators/clip_by_norm_op_npu.cc
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
null
null
null
paddle/fluid/operators/clip_by_norm_op_npu.cc
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
1
2021-12-09T08:59:17.000Z
2021-12-09T08:59:17.000Z
/* Copyright (c) 2022 PaddlePaddle 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. */ #include "paddle/fluid/operators/clip_by_norm_op.h" #include "paddle/fluid/platform/device/npu/npu_op_runner.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; template <typename DeviceContext, typename T> class NPUClipByNormKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto max_norm = context.Attr<float>("max_norm"); auto in_var = context.InputVar("X"); if (!(in_var->IsType<framework::LoDTensor>())) { PADDLE_THROW(platform::errors::InvalidArgument( "Invalid input variable type, only support LodTensor" "type, but got type is %s.", framework::ToTypeName(in_var->Type()))); } auto place = context.GetPlace(); auto& dev_ctx = context.template device_context<paddle::platform::NPUDeviceContext>(); auto stream = dev_ctx.stream(); auto* input = context.Input<Tensor>("X"); auto* output = context.Output<Tensor>("Out"); output->mutable_data<T>(place); PADDLE_ENFORCE_NOT_NULL(input, platform::errors::InvalidArgument( "Input(X) of ClipByNormOp should not be null. " "Please check if it is created correctly.")); Tensor square_sum(input->type()); square_sum.mutable_data<T>(framework::DDim({1}), place); const auto& x_dims = input->dims(); std::vector<int> axis; for (int i = 0; i < x_dims.size(); ++i) { axis.push_back(i); } const auto& square_sum_runner = NpuOpRunner("SquareSumV1", {*input}, {square_sum}, {{"axis", axis}, {"keep_dims", false}}); square_sum_runner.Run(stream); Tensor x_norm(input->type()); x_norm.mutable_data<T>(framework::DDim({1}), place); const auto& x_norm_runner = NpuOpRunner("Sqrt", {square_sum}, {x_norm}, {}); x_norm_runner.Run(stream); Tensor x_norm_t; framework::TensorCopySync(x_norm, platform::CPUPlace(), &x_norm_t); auto x_norm_v = static_cast<float>(*x_norm_t.data<T>()); if (x_norm_v <= max_norm) { framework::TensorCopy(*input, place, dev_ctx, output); } else { auto epsilon = x_norm_v <= static_cast<float>(1e-30) ? static_cast<float>(1e-6) : static_cast<float>(0); float scaling = max_norm / (x_norm_v + epsilon); const auto& muls_runner = NpuOpRunner("Muls", {*input}, {*output}, {{"value", scaling}}); muls_runner.Run(stream); } } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; namespace plat = paddle::platform; REGISTER_OP_NPU_KERNEL( clip_by_norm, ops::NPUClipByNormKernel<paddle::platform::NPUDeviceContext, float>, ops::NPUClipByNormKernel<paddle::platform::NPUDeviceContext, plat::float16>);
36.978947
80
0.656988
RangeKing
e6b6fe8b805312934bd44da71c48d5238f644536
150,137
cpp
C++
tests/DLXLibTest/src/Processor.test.cpp
AMS21/DLXEmu
9b5d40b68dcac0281bed7ed8157fc2b868d4de8e
[ "MIT" ]
null
null
null
tests/DLXLibTest/src/Processor.test.cpp
AMS21/DLXEmu
9b5d40b68dcac0281bed7ed8157fc2b868d4de8e
[ "MIT" ]
53
2021-02-01T22:31:16.000Z
2022-03-01T04:01:47.000Z
tests/DLXLibTest/src/Processor.test.cpp
AMS21/DLXEmu
9b5d40b68dcac0281bed7ed8157fc2b868d4de8e
[ "MIT" ]
1
2021-02-03T13:54:23.000Z
2021-02-03T13:54:23.000Z
#include "DLX/RegisterNames.hpp" #include <catch2/catch_test_macros.hpp> #include <DLX/InstructionLibrary.hpp> #include <DLX/Parser.hpp> #include <DLX/Processor.hpp> static dlx::InstructionLibrary lib; static dlx::Processor proc; static dlx::ParsedProgram res; TEST_CASE("Operation exceptions") { constexpr std::int32_t signed_min = phi::i32::limits_type::min(); constexpr std::int32_t signed_max = phi::i32::limits_type::max(); constexpr std::uint32_t unsigned_max = phi::u32::limits_type::max(); SECTION("Signed addition overflow") { res = dlx::Parser::Parse(lib, "ADD R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 5); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min + 4); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 5); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); } SECTION("Signed addition underflow") { res = dlx::Parser::Parse(lib, "ADD R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -1); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max - 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -2); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); } SECTION("Unsigned addition overflow") { res = dlx::Parser::Parse(lib, "ADDU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, unsigned_max); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 0u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == unsigned_max); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == unsigned_max); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 0u); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, unsigned_max); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 5u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 4u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == unsigned_max); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 5u); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); } SECTION("Signed subtraction overflow") { res = dlx::Parser::Parse(lib, "SUB R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -5); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min + 4); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -5); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); } SECTION("Signed subtraction underflow") { res = dlx::Parser::Parse(lib, "SUB R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max - 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 2); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); } SECTION("Unsigned subtraction underflow") { res = dlx::Parser::Parse(lib, "SUBU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 0u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 0u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 0u); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 0u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 1u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == unsigned_max); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 1u); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 0u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 5u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == unsigned_max - 4u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 5u); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); } SECTION("Signed multiplication overflow") { res = dlx::Parser::Parse(lib, "MULT R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); CHECK(proc.GetLastRaisedException() == dlx::Exception::None); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 2); proc.ExecuteCurrentProgram(); //CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == -2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 2); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, signed_max); proc.ExecuteCurrentProgram(); //CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == signed_max); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); } SECTION("Signed multiplication underflow") { res = dlx::Parser::Parse(lib, "MULT R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_min); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); //CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, signed_max); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, signed_min); proc.ExecuteCurrentProgram(); //CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == signed_min); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == signed_max); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == signed_min); CHECK(proc.GetLastRaisedException() == dlx::Exception::Underflow); } SECTION("Unsigned multiplication overflow") { res = dlx::Parser::Parse(lib, "MULTU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, unsigned_max); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); //CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == unsigned_max); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3); CHECK(proc.GetLastRaisedException() == dlx::Exception::Overflow); } SECTION("Signed division by zero") { res = dlx::Parser::Parse(lib, "DIV R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); res = dlx::Parser::Parse(lib, "DIVI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 5); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); } SECTION("Unsigned division by zero") { res = dlx::Parser::Parse(lib, "DIVU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 5u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 0u); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); res = dlx::Parser::Parse(lib, "DIVUI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 5u); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); } SECTION("Float division by zero") { res = dlx::Parser::Parse(lib, "DIVF F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F4, 0.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); } SECTION("Double division by zero") { res = dlx::Parser::Parse(lib, "DIVD F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0f); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 0.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetLastRaisedException() == dlx::Exception::DivideByZero); CHECK(proc.IsHalted()); } SECTION("Shift left bad shift") { // Logical res = dlx::Parser::Parse(lib, "SLL R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 32); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 32); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 999999); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -1); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); // Arithmetic res = dlx::Parser::Parse(lib, "SLA R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 32); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 32); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 999999); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -1); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); } SECTION("Shift right bad shift") { // Logical res = dlx::Parser::Parse(lib, "SRL R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 32); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 32); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 999999); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -1); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); // Arithmetic res = dlx::Parser::Parse(lib, "SRA R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 32); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == -1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 32); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 999999); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == -1); CHECK(proc.GetLastRaisedException() == dlx::Exception::BadShift); } SECTION("Jump to non existing label") { // J res = dlx::Parser::Parse(lib, "J label"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::UnknownLabel); // JAL res = dlx::Parser::Parse(lib, "JAL label"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::UnknownLabel); } SECTION("Invalid jump register") { // JR res = dlx::Parser::Parse(lib, "JR R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, -5); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); // JALR res = dlx::Parser::Parse(lib, "JALR R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, -5); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("Loading invalid address") { SECTION("LB") { res = dlx::Parser::Parse(lib, "LB R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LB R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LB R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LB R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LB R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LB R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LBU") { res = dlx::Parser::Parse(lib, "LBU R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LBU R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LBU R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LBU R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LBU R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LH") { res = dlx::Parser::Parse(lib, "LH R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LHU") { res = dlx::Parser::Parse(lib, "LHU R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LW") { res = dlx::Parser::Parse(lib, "LW R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LWU") { res = dlx::Parser::Parse(lib, "LWU R1 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LF") { res = dlx::Parser::Parse(lib, "LF F0 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LF F0 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LF F0 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LF F0 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LF F0 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LF F0 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("LD") { res = dlx::Parser::Parse(lib, "LD F0 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LD F0 #-4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LD F0 #5000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LD F0 4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LD F0 -4(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LD F0 5000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } } SECTION("Storing invalid address") { SECTION("SB") { res = dlx::Parser::Parse(lib, "SB #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SB #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SB #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SB 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SB -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SB 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SBU") { res = dlx::Parser::Parse(lib, "SBU #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SBU #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SBU #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SBU 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SBU -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SBU 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SH") { res = dlx::Parser::Parse(lib, "SH #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SH #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SH #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SH 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SH -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SH 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SHU") { res = dlx::Parser::Parse(lib, "SHU #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SHU #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SHU #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SHU 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SHU -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SHU 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SW") { res = dlx::Parser::Parse(lib, "SW #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SW #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SW #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SW 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SW -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SW 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SWU") { res = dlx::Parser::Parse(lib, "SWU #4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SWU #-4 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SWU #5000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SWU 4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SWU -4(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SWU 5000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SF") { res = dlx::Parser::Parse(lib, "SF #4 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SF #-4 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SF #5000 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SF 4(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SF -4(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SF 5000(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } SECTION("SD") { res = dlx::Parser::Parse(lib, "SD #4 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SD #-4 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SD #5000 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SD 4(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SD -4(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "SD 5000(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); } } } TEST_CASE("ADD") { res = dlx::Parser::Parse(lib, "ADD R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 6); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 6); } TEST_CASE("ADDI") { res = dlx::Parser::Parse(lib, "ADDI R1 R2 #30"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 32); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("ADDU") { res = dlx::Parser::Parse(lib, "ADDU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 19u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 19u); } TEST_CASE("ADDUI") { res = dlx::Parser::Parse(lib, "ADDUI R1 R2 #19"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("ADDF") { res = dlx::Parser::Parse(lib, "ADDF F1 F2 F3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F3, 2.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f + 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F3).get() == 2.0f); } TEST_CASE("ADDD") { res = dlx::Parser::Parse(lib, "ADDD F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 1.0 + 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("SUB") { res = dlx::Parser::Parse(lib, "SUB R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 50); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 30); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 20); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 50); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 30); } TEST_CASE("SUBI") { res = dlx::Parser::Parse(lib, "SUBI R1 R2 #25"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 50); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 25); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 50); } TEST_CASE("SUBU") { res = dlx::Parser::Parse(lib, "SUBU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 50u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 30u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 20u); } TEST_CASE("SUBUI") { res = dlx::Parser::Parse(lib, "SUBUI R1 R2 #25"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 50u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 25u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 50u); } TEST_CASE("SUBF") { res = dlx::Parser::Parse(lib, "SUBF F1 F2 F3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F3, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f - 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F3).get() == 1.0f); } TEST_CASE("SUBD") { res = dlx::Parser::Parse(lib, "SUBD F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 2.0 - 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); } TEST_CASE("MULT") { res = dlx::Parser::Parse(lib, "MULT R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 6); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("MULTI") { res = dlx::Parser::Parse(lib, "MULTI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 6); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("MULTU") { res = dlx::Parser::Parse(lib, "MULTU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 6u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("MULTUI") { res = dlx::Parser::Parse(lib, "MULTUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 6u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("MULTF") { res = dlx::Parser::Parse(lib, "MULTF F1 F2 F3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 3.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F3, 2.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 3.0f * 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 3.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F3).get() == 2.0f); } TEST_CASE("MULTD") { res = dlx::Parser::Parse(lib, "MULTD F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 3.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 3.0 * 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 3.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("DIV") { res = dlx::Parser::Parse(lib, "DIV R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 6); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 6); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 2); // Divide by zero proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("DIVI") { res = dlx::Parser::Parse(lib, "DIVI R1 R2 #2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 6); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 6); // Divide by zero res = dlx::Parser::Parse(lib, "DIVI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 6); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("DIVU") { res = dlx::Parser::Parse(lib, "DIVU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 6u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 6u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 2u); // Divide by zero proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 0u); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("DIVUI") { res = dlx::Parser::Parse(lib, "DIVUI R1 R2 #2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 6u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 6u); // Divide by zero res = dlx::Parser::Parse(lib, "DIVUI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("DIVF") { res = dlx::Parser::Parse(lib, "DIVF F1 F2 F3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 12.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F3, 2.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 12.0f / 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 12.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F3).get() == 2.0f); } TEST_CASE("DIVD") { res = dlx::Parser::Parse(lib, "DIVD F0 F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 12.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 12.0 / 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 12.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("SLL") { res = dlx::Parser::Parse(lib, "SLL R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 16); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); } TEST_CASE("SLLI") { res = dlx::Parser::Parse(lib, "SLLI R1 R2 #2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 32); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); res = dlx::Parser::Parse(lib, "SLLI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); } TEST_CASE("SRL") { res = dlx::Parser::Parse(lib, "SRL R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 4); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 2147483647); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == -1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); } TEST_CASE("SRLI") { res = dlx::Parser::Parse(lib, "SRLI R1 R2 #2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1073741823); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -1); res = dlx::Parser::Parse(lib, "SRLI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); } TEST_CASE("SLA") { res = dlx::Parser::Parse(lib, "SLA R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 16); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); } TEST_CASE("SLAI") { res = dlx::Parser::Parse(lib, "SLAI R1 R2 #2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 32); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); res = dlx::Parser::Parse(lib, "SLAI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); } TEST_CASE("SRA") { res = dlx::Parser::Parse(lib, "SRA R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -2147483647); // 0b10000000'00000000'00000000'00000001 proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); // 0b11000000'00000000'00000000'00000000 CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == -1073741824); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -2147483647); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1073741825); // 0b01000000'00000000'00000000'00000001 proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 1); proc.ExecuteCurrentProgram(); // 0b00100000'00000000'00000000'00000000 CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 536870912); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1073741825); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 0); } TEST_CASE("SRAI") { res = dlx::Parser::Parse(lib, "SRAI R1 R2 #1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, -2147483647); // 0b10000000'00000000'00000000'00000001 proc.ExecuteCurrentProgram(); // 0b11000000'00000000'00000000'00000000 CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == -1073741824); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == -2147483647); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1073741825); // 0b01000000'00000000'00000000'00000001 proc.ExecuteCurrentProgram(); // 0b00100000'00000000'00000000'00000000 CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 536870912); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1073741825); res = dlx::Parser::Parse(lib, "SRAI R1 R2 #0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 8); proc.ExecuteCurrentProgram(); // 0b11000000'00000000'00000000'00000000 CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 8); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 8); } TEST_CASE("AND") { res = dlx::Parser::Parse(lib, "AND R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("ANDI") { res = dlx::Parser::Parse(lib, "ANDI R1 R2 #5"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); } TEST_CASE("OR") { res = dlx::Parser::Parse(lib, "OR R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("ORI") { res = dlx::Parser::Parse(lib, "ORI R1 R2 #8"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 9); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); } TEST_CASE("XOR") { res = dlx::Parser::Parse(lib, "XOR R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 7); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 6); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 7); } TEST_CASE("XORI") { res = dlx::Parser::Parse(lib, "XORI R1 R2 #7"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 6); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); } TEST_CASE("SLT") { res = dlx::Parser::Parse(lib, "SLT R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 5); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("SLTI") { res = dlx::Parser::Parse(lib, "SLTI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 4); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 4); } TEST_CASE("SLTU") { res = dlx::Parser::Parse(lib, "SLTU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 5u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 5u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 5u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 5u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("SLTUI") { res = dlx::Parser::Parse(lib, "SLTUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 4u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 4u); } TEST_CASE("LTF") { res = dlx::Parser::Parse(lib, "LTF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); proc.SetFPSRValue(true); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); } TEST_CASE("LTD") { res = dlx::Parser::Parse(lib, "LTD F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); } TEST_CASE("SGT") { res = dlx::Parser::Parse(lib, "SGT R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("SGTI") { res = dlx::Parser::Parse(lib, "SGTI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 4); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 4); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("SGTU") { res = dlx::Parser::Parse(lib, "SGTU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("SGTUI") { res = dlx::Parser::Parse(lib, "SGTUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 4u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 4u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("GTF") { res = dlx::Parser::Parse(lib, "GTF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(true); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); } TEST_CASE("GTD") { res = dlx::Parser::Parse(lib, "GTD F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("SLE") { res = dlx::Parser::Parse(lib, "SLE R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 5); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("SLEI") { res = dlx::Parser::Parse(lib, "SLEI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 4); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 4); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("SLEU") { res = dlx::Parser::Parse(lib, "SLEU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 5u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 5u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("SLEUI") { res = dlx::Parser::Parse(lib, "SLEUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 4u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 4u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("LEF") { res = dlx::Parser::Parse(lib, "LEF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(true); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); } TEST_CASE("LED") { res = dlx::Parser::Parse(lib, "LED F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); } TEST_CASE("SGE") { res = dlx::Parser::Parse(lib, "SGE R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 5); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 5); } TEST_CASE("SGEI") { res = dlx::Parser::Parse(lib, "SGEI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 4); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 4); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("SGEU") { res = dlx::Parser::Parse(lib, "SGEU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 5u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 5u); } TEST_CASE("SGEUI") { res = dlx::Parser::Parse(lib, "SGEUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 4u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 4u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("GEF") { res = dlx::Parser::Parse(lib, "GEF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(true); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); } TEST_CASE("GED") { res = dlx::Parser::Parse(lib, "GED F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("SEQ") { res = dlx::Parser::Parse(lib, "SEQ R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("SEQI") { res = dlx::Parser::Parse(lib, "SEQI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); } TEST_CASE("SEQU") { res = dlx::Parser::Parse(lib, "SEQU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("SEQUI") { res = dlx::Parser::Parse(lib, "SEQUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); } TEST_CASE("EQF") { res = dlx::Parser::Parse(lib, "EQF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 2.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 2.0f); } TEST_CASE("EQD") { res = dlx::Parser::Parse(lib, "EQD F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 2.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 2.0); } TEST_CASE("SNE") { res = dlx::Parser::Parse(lib, "SNE R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R3).get() == 3); } TEST_CASE("SNEI") { res = dlx::Parser::Parse(lib, "SNEI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R3, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 3); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 3); } TEST_CASE("SNEU") { res = dlx::Parser::Parse(lib, "SNEU R1 R2 R3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R3).get() == 3u); } TEST_CASE("SNEUI") { res = dlx::Parser::Parse(lib, "SNEUI R1 R2 #3"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R3, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 1u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 2u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R2, 3u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 0u); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R2).get() == 3u); } TEST_CASE("NEF") { res = dlx::Parser::Parse(lib, "NEF F1 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 2.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 2.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); proc.SetFPSRValue(true); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); } TEST_CASE("NED") { res = dlx::Parser::Parse(lib, "NED F2 F4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.SetFPSRValue(false); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 2.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 2.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); proc.SetFPSRValue(true); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F4, 1.0); proc.ExecuteCurrentProgram(); CHECK_FALSE(proc.GetFPSRValue()); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F4).get() == 1.0); } TEST_CASE("BEQZ") { const char* data = R"( BEQZ R1 true HALT true: ADDI R2 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 0); } TEST_CASE("BNEZ") { const char* data = R"( BNEZ R1 true HALT true: ADDI R2 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 5); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 1); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 0); } TEST_CASE("BFPT") { const char* data = R"( BFPT true HALT true: ADDI R1 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.SetFPSRValue(true); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.SetFPSRValue(false); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); } TEST_CASE("BFPF") { const char* data = R"( BFPF false HALT false: ADDI R1 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.SetFPSRValue(false); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.SetFPSRValue(true); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 0); } TEST_CASE("J") { const char* data = R"( J jump_label HALT jump_label: ADDI R1 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 0); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); } TEST_CASE("JR") { const char* data = R"( JR R1 HALT ADDI R2 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 9999999); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); } TEST_CASE("JAL") { const char* data = R"( JAL jump_label HALT jump_label: ADDI R1 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R31, 9999999); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R31).get() == 1); } TEST_CASE("JALR") { const char* data = R"( JALR R1 HALT ADDI R2 R0 #1 )"; res = dlx::Parser::Parse(lib, data); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 2); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R2, 9999999); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 2); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R2).get() == 1); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R31).get() == 1); } TEST_CASE("LHI") { res = dlx::Parser::Parse(lib, "LHI R1 #1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == (1 << 16)); } TEST_CASE("LB") { res = dlx::Parser::Parse(lib, "LB R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreByte(1000u, static_cast<std::int8_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); res = dlx::Parser::Parse(lib, "LB R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreByte(1000u, static_cast<std::int8_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LBU") { res = dlx::Parser::Parse(lib, "LBU R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedByte(1000u, static_cast<std::uint8_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21u); res = dlx::Parser::Parse(lib, "LBU R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedByte(1000u, static_cast<std::uint8_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LH") { res = dlx::Parser::Parse(lib, "LH R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreHalfWord(1000u, static_cast<std::int16_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); res = dlx::Parser::Parse(lib, "LH R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreHalfWord(1000u, static_cast<std::int16_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LHU") { res = dlx::Parser::Parse(lib, "LHU R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedHalfWord(1000u, static_cast<std::uint16_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21u); res = dlx::Parser::Parse(lib, "LHU R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedHalfWord(1000u, static_cast<std::uint16_t>(21)); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LW") { res = dlx::Parser::Parse(lib, "LW R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreWord(1000u, 21); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); res = dlx::Parser::Parse(lib, "LW R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 9999999); proc.ClearMemory(); proc.GetMemory().StoreWord(1000u, 21); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LWU") { res = dlx::Parser::Parse(lib, "LWU R1 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedWord(1000u, 21u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21u); res = dlx::Parser::Parse(lib, "LWU R1 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 9999999u); proc.ClearMemory(); proc.GetMemory().StoreUnsignedWord(1000u, 21u); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetUnsignedValue(dlx::IntRegisterID::R1).get() == 21); } TEST_CASE("LF") { res = dlx::Parser::Parse(lib, "LF F0 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.ClearMemory(); proc.GetMemory().StoreFloat(1000u, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() == 1.0f); res = dlx::Parser::Parse(lib, "LF F0 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.ClearMemory(); proc.GetMemory().StoreFloat(1000u, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() == 1.0f); } TEST_CASE("LD") { res = dlx::Parser::Parse(lib, "LD F0 #1000"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.ClearMemory(); proc.GetMemory().StoreDouble(1000u, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 1.0); res = dlx::Parser::Parse(lib, "LD F0 1000(R0)"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.ClearMemory(); proc.GetMemory().StoreDouble(1000u, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 1.0); } TEST_CASE("SB") { res = dlx::Parser::Parse(lib, "SB #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadByte(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); res = dlx::Parser::Parse(lib, "SB 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadByte(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); } TEST_CASE("SBU") { res = dlx::Parser::Parse(lib, "SBU #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadUnsignedByte(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); res = dlx::Parser::Parse(lib, "SBU 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadUnsignedByte(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); } TEST_CASE("SH") { res = dlx::Parser::Parse(lib, "SH #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadHalfWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); res = dlx::Parser::Parse(lib, "SH 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadHalfWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); } TEST_CASE("SHU") { res = dlx::Parser::Parse(lib, "SHU #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadUnsignedHalfWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); res = dlx::Parser::Parse(lib, "SHU 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadUnsignedHalfWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); } TEST_CASE("SW") { res = dlx::Parser::Parse(lib, "SW #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); res = dlx::Parser::Parse(lib, "SW 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 21); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21); } TEST_CASE("SWU") { res = dlx::Parser::Parse(lib, "SWU #1000 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadUnsignedWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); res = dlx::Parser::Parse(lib, "SWU 1000(R0) R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetUnsignedValue(dlx::IntRegisterID::R1, 21u); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadUnsignedWord(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 21u); } TEST_CASE("SF") { res = dlx::Parser::Parse(lib, "SF #1000 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, 1.0f); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadFloat(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 1.0f); res = dlx::Parser::Parse(lib, "SF 1000(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, 1.0f); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadFloat(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 1.0f); } TEST_CASE("SD") { res = dlx::Parser::Parse(lib, "SD #1000 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, 1.0); proc.ClearMemory(); proc.ExecuteCurrentProgram(); auto val = proc.GetMemory().LoadDouble(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 1.0); res = dlx::Parser::Parse(lib, "SD 1000(R0) F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, 1.0); proc.ClearMemory(); proc.ExecuteCurrentProgram(); val = proc.GetMemory().LoadDouble(1000u); REQUIRE(val.has_value()); CHECK(val->get() == 1.0); } TEST_CASE("MOVF") { res = dlx::Parser::Parse(lib, "MOVF F0 F1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F1, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() == 1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F1).get() == 1.0f); } TEST_CASE("MOVD") { res = dlx::Parser::Parse(lib, "MOVD F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 1.0); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); } TEST_CASE("MOVFP2I") { res = dlx::Parser::Parse(lib, "MOVFP2I R1 F0"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, 1.0f); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, -1); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() == 1.0f); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() != -1); } TEST_CASE("MOVI2FP") { res = dlx::Parser::Parse(lib, "MOVI2FP F0 R1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.IntRegisterSetSignedValue(dlx::IntRegisterID::R1, 1); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R1).get() == 1); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() != -1.0f); } TEST_CASE("CVTF2D") { res = dlx::Parser::Parse(lib, "CVTF2D F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F0, -1.0); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F0).get() == 1.0); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); } TEST_CASE("CVTF2I") { res = dlx::Parser::Parse(lib, "CVTF2I F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() != -1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0f); } TEST_CASE("CVTD2F") { res = dlx::Parser::Parse(lib, "CVTD2F F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() == 1.0f); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); } TEST_CASE("CVTD2I") { res = dlx::Parser::Parse(lib, "CVTD2I F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() != -1.0f); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); } TEST_CASE("CVTI2F") { res = dlx::Parser::Parse(lib, "CVTI2F F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() != -1.0f); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F2).get() == 1.0); } TEST_CASE("CVTI2D") { res = dlx::Parser::Parse(lib, "CVTI2D F0 F2"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.FloatRegisterSetFloatValue(dlx::FloatRegisterID::F0, -1.0f); proc.FloatRegisterSetDoubleValue(dlx::FloatRegisterID::F2, 1.0f); proc.ExecuteCurrentProgram(); CHECK(proc.FloatRegisterGetFloatValue(dlx::FloatRegisterID::F0).get() != 1.0f); CHECK(proc.FloatRegisterGetDoubleValue(dlx::FloatRegisterID::F2).get() == 1.0); } TEST_CASE("TRAP") { res = dlx::Parser::Parse(lib, "TRAP #1"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("HALT") { res = dlx::Parser::Parse(lib, "HALT"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("NOP") { res = dlx::Parser::Parse(lib, "NOP"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("R0 is read only") { res = dlx::Parser::Parse(lib, "ADDI R0 R0 #4"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IntRegisterGetSignedValue(dlx::IntRegisterID::R0).get() == 0); } TEST_CASE("Empty source code") { res = dlx::Parser::Parse(lib, ""); REQUIRE(res.m_ParseErrors.empty()); CHECK(res.m_Instructions.empty()); CHECK(res.m_JumpData.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); } TEST_CASE("Misaligned addresses - Crash-8cb7670c0bacefed7af9ea62bcb5a03b95296b8e") { // Signed half words res = dlx::Parser::Parse(lib, "LH R1 #1001"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LH R1 #1003"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); // Unsigned half words res = dlx::Parser::Parse(lib, "LHU R1 #1001"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LHU R1 #1003"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); // Signed words res = dlx::Parser::Parse(lib, "LW R1 #1001"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 #1002"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LW R1 #1003"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); // Unsigned words res = dlx::Parser::Parse(lib, "LWU R1 #1001"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 #1002"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); res = dlx::Parser::Parse(lib, "LWU R1 #1003"); REQUIRE(res.m_ParseErrors.empty()); proc.LoadProgram(res); proc.ExecuteCurrentProgram(); CHECK(proc.IsHalted()); CHECK(proc.GetLastRaisedException() == dlx::Exception::AddressOutOfBounds); }
32.888719
99
0.668716
AMS21
e6ba69ec8d219d9ea1fc3f561aee804957bc9cac
2,175
cpp
C++
ScrapEngine/ScrapEngine/Engine/Rendering/Base/Vertex.cpp
alundb/ScrapEngine
755416a2b2b072a8713f5a6b669f2379608bbab0
[ "MIT" ]
118
2019-10-12T01:29:07.000Z
2022-02-22T08:08:18.000Z
ScrapEngine/ScrapEngine/Engine/Rendering/Base/Vertex.cpp
alundb/ScrapEngine
755416a2b2b072a8713f5a6b669f2379608bbab0
[ "MIT" ]
15
2019-09-02T16:51:39.000Z
2021-02-21T20:03:58.000Z
ScrapEngine/ScrapEngine/Engine/Rendering/Base/Vertex.cpp
alundb/ScrapEngine
755416a2b2b072a8713f5a6b669f2379608bbab0
[ "MIT" ]
11
2019-10-21T15:53:23.000Z
2022-02-20T20:56:39.000Z
#include <Engine/Rendering/Base/Vertex.h> vk::VertexInputBindingDescription ScrapEngine::Render::Vertex::get_binding_description() { return vk::VertexInputBindingDescription(0, sizeof(Vertex), vk::VertexInputRate::eVertex); } std::array<vk::VertexInputAttributeDescription, 4> ScrapEngine::Render::Vertex::get_attribute_descriptions() { const std::array<vk::VertexInputAttributeDescription, 4> attribute_descriptions = { vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, pos)), vk::VertexInputAttributeDescription(1, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, color)), vk::VertexInputAttributeDescription(2, 0, vk::Format::eR32G32Sfloat, offsetof(Vertex, tex_coord)), vk::VertexInputAttributeDescription(3, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, normal)), }; return attribute_descriptions; } vk::VertexInputBindingDescription ScrapEngine::Render::SkyboxVertex::get_binding_description() { return vk::VertexInputBindingDescription(0, sizeof(SkyboxVertex), vk::VertexInputRate::eVertex); } std::array<vk::VertexInputAttributeDescription, 3> ScrapEngine::Render::SkyboxVertex::get_attribute_descriptions() { const std::array<vk::VertexInputAttributeDescription, 3> attribute_descriptions = { vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32Sfloat, offsetof(SkyboxVertex, pos)), vk::VertexInputAttributeDescription(1, 0, vk::Format::eR32G32B32Sfloat, offsetof(SkyboxVertex, color)), vk::VertexInputAttributeDescription(2, 0, vk::Format::eR32G32Sfloat, offsetof(SkyboxVertex, tex_coord)) }; return attribute_descriptions; } vk::VertexInputBindingDescription ScrapEngine::Render::OffscreenVertex::get_binding_description() { return vk::VertexInputBindingDescription(0, sizeof(OffscreenVertex), vk::VertexInputRate::eVertex); } std::array<vk::VertexInputAttributeDescription, 1> ScrapEngine::Render::OffscreenVertex::get_attribute_descriptions() { const std::array<vk::VertexInputAttributeDescription, 1> attribute_descriptions = { vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32Sfloat, offsetof(OffscreenVertex, pos)) }; return attribute_descriptions; }
44.387755
117
0.801379
alundb
e6ba9fb34a3095e3715519a6e0d47c83ad3d7242
4,508
cpp
C++
CardGame/Classes/Layer/HelpLayer.cpp
AdamFeher2400/CardGame
e14c71b9833b38d97266678810d1800cb7880ea6
[ "MIT" ]
2
2019-06-23T12:30:39.000Z
2019-08-31T23:17:42.000Z
CardGame/Classes/Layer/HelpLayer.cpp
GuruDev0807/CardGame
e14c71b9833b38d97266678810d1800cb7880ea6
[ "MIT" ]
null
null
null
CardGame/Classes/Layer/HelpLayer.cpp
GuruDev0807/CardGame
e14c71b9833b38d97266678810d1800cb7880ea6
[ "MIT" ]
2
2019-12-18T15:55:48.000Z
2020-02-16T15:02:10.000Z
#include "HelpLayer.h" #include "SettingLayer.h" #include "../Common/GameData.h" #include "../Widget/MyMenuItem.h" std::string help = "CrazyBlackjack is about getting rid of all of your cards in order to be the last person left. It is called crazy blackjack as this game is commonly referred to as crazy 8s and blackjack.\n\nDue to blackjack varying rules this form of blackjack has a fixed set of rules so that there is no more confusion when CrazyBlackjack is played and one set of rules can be established.\n\nA - Changes the suit and can be placed on anything\n\n2 - Pickup two cards (unless you have a 2 to put on it which will therefore make the next person pickup\n\n8 - Miss a turn, misses the next person in rotation\n\n10 - Reverses the direction, this reverses the direction the game is going, if it's between two people then it is similar properties to an 8\n\nBlackjack - This means pickup 5 cards\n\nRedjack - This stops the blackjack and stops the person from picking up 5 if they have been made to do so\n\nKnocking - This will appear when a player is able to go out on their next turn\n\nruns - Runs are aloud and must follow a consistency, there is no number of how many your aloud in a run as long as the numbers and suits all follow EG: 5 of spades, 6 of spades and 6 of hearts"; Scene* HelpLayer::createScene() { Scene* scene = Scene::create(); HelpLayer* layer = HelpLayer::create(); scene->addChild(layer); return scene; } HelpLayer::~HelpLayer() { } bool HelpLayer::init() { if ( !BaseLayer::init() ) return false; m_nType = LAYER_HELP; g_pCurrentLayer = this; createSprites(); createLabels(); createMenu(); return true; } void HelpLayer::onEnter() { BaseLayer::onEnter(); } void HelpLayer::OnBack(Ref* pSender) { CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("sound/Click.wav"); Director::getInstance()->replaceScene(TransitionFade::create(0.5f, SettingLayer::createScene(), Color3B(0, 0, 0))); } void HelpLayer::createSprites() { auto sprBackground = Sprite::create("img/lobby/lobby_bg.png"); sprBackground->setAnchorPoint(Vec2(0.5f, 0.5f)); sprBackground->setScale(m_fLargeScale); sprBackground->setPosition(Vec2(m_szDevice.width / 2, m_szDevice.height / 2)); addChild(sprBackground, LAYER_ZORDER1); auto sprTitle = Sprite::create("img/setting/title_how_to_play.png"); sprTitle->setAnchorPoint(Vec2(0.5f, 0.5f)); sprTitle->setScale(m_fSmallScale); sprTitle->setPosition(Vec2(m_szDevice.width / 2, m_szDevice.height - 80.0f * m_fSmallScale)); addChild(sprTitle, LAYER_ZORDER1); } void HelpLayer::createLabels() { TTFConfig ttfConfig("fonts/ImperialStd-Regular.ttf", 40.0f * m_fSmallScale); Color3B color = Color3B(255, 255, 255); auto pHelpScrollView = ui::ScrollView::create(); pHelpScrollView->setContentSize(Size(1200.0f * m_fSmallScale, m_szDevice.height - 197.0f * m_fSmallScale)); pHelpScrollView->setPosition(Vec2(m_szDevice.width / 2 - 600.0f * m_fSmallScale, 40.0f * m_fSmallScale)); pHelpScrollView->setScrollBarAutoHideTime(0.0); pHelpScrollView->setScrollBarColor(Color3B::WHITE); pHelpScrollView->setScrollBarWidth(8 * m_fSmallScale); pHelpScrollView->setScrollBarPositionFromCorner(Vec2(12 * m_fSmallScale, 3 * m_fSmallScale)); pHelpScrollView->setScrollBarOpacity(230); pHelpScrollView->setBounceEnabled(true); pHelpScrollView->setCascadeOpacityEnabled(true); pHelpScrollView->setInnerContainerSize(Size(1200.0f * m_fSmallScale, 1470.0f * m_fSmallScale)); addChild(pHelpScrollView, LAYER_ZORDER2); auto description = Label::createWithTTF(ttfConfig, help, TextHAlignment::LEFT, 1160.0f * m_fSmallScale); description->setAnchorPoint(Vec2(0.0f, 1.0f)); description->setPosition(Vec2(20.0f * m_fSmallScale, pHelpScrollView->getInnerContainerSize().height - 8.0f * m_fSmallScale)); description->setColor(color); pHelpScrollView->addChild(description); } void HelpLayer::createMenu() { auto btnBack = MyMenuItem::create("img/match/btn_back_nor.png", "img/match/btn_back_act.png", "", CC_CALLBACK_1(HelpLayer::OnBack, this)); btnBack->setScale(m_fSmallScale); btnBack->setAnchorPoint(Vec2(0.5f, 0.5f)); btnBack->setPosition(Vec2(108.0f * m_fSmallScale, m_szDevice.height - 80.0f * m_fSmallScale)); auto menu = Menu::create(btnBack, nullptr); menu->setPosition(Vec2(0.0f, 0.0f)); addChild(menu, LAYER_ZORDER2); }
46.474227
1,184
0.731366
AdamFeher2400
e6c20bc3db3f3b92a52a2e760821e2c56b449d98
1,122
cpp
C++
test/unit-tests/device/base/io_context_test.cpp
YongJin-Cho/poseidonos
c07a0240316d4536aa09f22d7977604f3650d752
[ "BSD-3-Clause" ]
null
null
null
test/unit-tests/device/base/io_context_test.cpp
YongJin-Cho/poseidonos
c07a0240316d4536aa09f22d7977604f3650d752
[ "BSD-3-Clause" ]
null
null
null
test/unit-tests/device/base/io_context_test.cpp
YongJin-Cho/poseidonos
c07a0240316d4536aa09f22d7977604f3650d752
[ "BSD-3-Clause" ]
null
null
null
#include "src/device/base/io_context.h" #include <gtest/gtest.h> namespace pos { TEST(IOContext, IOContext_) { } TEST(IOContext, SetIOKey_) { } TEST(IOContext, GetIOKey_) { } TEST(IOContext, SetErrorKey_) { } TEST(IOContext, GetErrorKey_) { } TEST(IOContext, GetDeviceName_) { } TEST(IOContext, GetOpcode_) { } TEST(IOContext, GetBuffer_) { } TEST(IOContext, GetStartByteOffset_) { } TEST(IOContext, GetByteCount_) { } TEST(IOContext, GetStartSectorOffset_) { } TEST(IOContext, GetSectorCount_) { } TEST(IOContext, AddPendingErrorCount_) { } TEST(IOContext, SubtractPendingErrorCount_) { } TEST(IOContext, CheckErrorDisregard_) { } TEST(IOContext, CompleteIo_) { } TEST(IOContext, SetAsyncIOCompleted_) { } TEST(IOContext, ClearAsyncIOCompleted_) { } TEST(IOContext, IsAsyncIOCompleted_) { } TEST(IOContext, CheckAndDecreaseRetryCount_) { } TEST(IOContext, ClearRetryCount_) { } TEST(IOContext, IncSubmitRetryCount_) { } TEST(IOContext, ClearSubmitRetryCount_) { } TEST(IOContext, GetSubmitRetryCount_) { } TEST(IOContext, SetAdminCommand_) { } TEST(IOContext, GetUbio_) { } } // namespace pos
10.017857
44
0.742424
YongJin-Cho
e6c2d82b75336758e82b25efa3b6fb390287e316
939
cpp
C++
AtCoder/ABC 235/C.cpp
Sansiff/Coding-Practice
b76f5a403c478abedc7bf22acb314b6cebb538ea
[ "MIT" ]
1
2021-09-14T11:25:21.000Z
2021-09-14T11:25:21.000Z
AtCoder/ABC 235/C.cpp
Sansiff/Coding-Practice
b76f5a403c478abedc7bf22acb314b6cebb538ea
[ "MIT" ]
null
null
null
AtCoder/ABC 235/C.cpp
Sansiff/Coding-Practice
b76f5a403c478abedc7bf22acb314b6cebb538ea
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long #define lowbit(x) (x&-x) #define rep(i, l, r) for(int i = l; i < r; i ++) #define all(x) (x).begin(),(x).end() #define fi first #define se second using namespace std; typedef long long LL; typedef pair<int,int> PII; typedef vector<int> VI; typedef vector<vector<int>> VII; typedef vector<PII> VPII; void read(VI& a){ for(int& x : a) cin >> x; } signed main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n, q; cin >> n >> q; VI arr(n); map<int, int> mp; VII po(n + 10); int cnt = 0, idx = 1; for(int& x : arr){ cin >> x; if(!mp[x]) mp[x] = ++ cnt; po[mp[x]].push_back(idx ++); } while(q --){ int a, k; cin >> a >> k; if(!mp[a]) cout << -1; else{ if(k > po[mp[a]].size()) cout << -1; else cout << po[mp[a]][k - 1]; } cout << '\n'; } return 0; }
22.902439
48
0.496273
Sansiff
e6c4cd92efd92423aeef514615fa23a57c6c2aa9
5,598
cpp
C++
tests/std/tests/Dev11_0343056_pair_tuple_ctor_sfinae/test.cpp
Weheineman/STL
2f4c5792b2be4f56b4130817803ca21f7a3ee8f4
[ "Apache-2.0" ]
2
2021-01-19T02:43:19.000Z
2021-11-20T05:21:42.000Z
tests/std/tests/Dev11_0343056_pair_tuple_ctor_sfinae/test.cpp
tapaswenipathak/STL
0d75fc5ab6684d4f6239879a6ec162aad0da860d
[ "Apache-2.0" ]
null
null
null
tests/std/tests/Dev11_0343056_pair_tuple_ctor_sfinae/test.cpp
tapaswenipathak/STL
0d75fc5ab6684d4f6239879a6ec162aad0da860d
[ "Apache-2.0" ]
4
2020-04-24T05:04:54.000Z
2020-05-17T22:48:58.000Z
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include <memory> #include <tuple> #include <utility> using namespace std; #ifdef __clang__ #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // This test intentionally uses 0 as null. #endif // __clang__ struct A {}; struct B : public A {}; struct X {}; struct Y : public X {}; void cat(pair<A*, A*>) {} void cat(pair<A*, X*>) {} void cat(pair<X*, A*>) {} void cat(pair<X*, X*>) {} void dog(tuple<A*, A*>) {} void dog(tuple<A*, X*>) {} void dog(tuple<X*, A*>) {} void dog(tuple<X*, X*>) {} struct Quark {}; struct Proton { Proton(Quark&) {} }; struct Neutron { Neutron(const Quark&) {} }; void takes_pair(pair<Proton, Proton>) {} void takes_pair(pair<Proton, Neutron>) {} void takes_pair(pair<Neutron, Proton>) {} void takes_pair(pair<Neutron, Neutron>) {} void takes_tuple(tuple<Proton, Proton>) {} void takes_tuple(tuple<Proton, Neutron>) {} void takes_tuple(tuple<Neutron, Proton>) {} void takes_tuple(tuple<Neutron, Neutron>) {} void test_alloc(); int main() { B* b = nullptr; Y* y = nullptr; pair<B*, B*> pbb(b, b); pair<B*, Y*> pby(b, y); pair<Y*, B*> pyb(y, b); pair<Y*, Y*> pyy(y, y); tuple<B*, B*> tbb(b, b); tuple<B*, Y*> tby(b, y); tuple<Y*, B*> tyb(y, b); tuple<Y*, Y*> tyy(y, y); // template <class U, class V> pair(U&& x, V&& y); pair<A*, X*> p1(b, y); pair<A*, X*> p2(b, 0); pair<A*, X*> p3(0, y); pair<A*, X*> p4(0, 0); (void) p4; // template <class... UTypes> explicit tuple(UTypes&&... u); tuple<A*, X*> t1(b, y); tuple<A*, X*> t2(b, 0); tuple<A*, X*> t3(0, y); tuple<A*, X*> t4(0, 0); (void) t4; // template <class U, class V> pair(const pair<U, V>& p); cat(pbb); cat(pby); cat(pyb); cat(pyy); // template <class U, class V> pair(pair<U, V>&& p); cat(move(pbb)); cat(move(pby)); cat(move(pyb)); cat(move(pyy)); // template <class U1, class U2> tuple(const pair<U1, U2>& u); dog(pbb); dog(pby); dog(pyb); dog(pyy); // template <class U1, class U2> tuple(pair<U1, U2>&& u); dog(move(pbb)); dog(move(pby)); dog(move(pyb)); dog(move(pyy)); // template <class... UTypes> tuple(const tuple<UTypes...>& u); dog(tbb); dog(tby); dog(tyb); dog(tyy); // template <class... UTypes> tuple(tuple<UTypes...>&& u); dog(move(tbb)); dog(move(tby)); dog(move(tyb)); dog(move(tyy)); const pair<Quark, Quark> meow; const tuple<Quark, Quark> purr; // template <class U, class V> pair(const pair<U, V>& p); takes_pair(meow); // template <class U1, class U2> tuple(const pair<U1, U2>& u); takes_tuple(meow); // template <class... UTypes> tuple(const tuple<UTypes...>& u); takes_tuple(purr); test_alloc(); } struct Meow { Meow(const tuple<int>&) {} Meow(const pair<int, int>&) {} }; void test_alloc() { { allocator<int> al; // template <class Alloc> tuple(allocator_arg_t, const Alloc& a); tuple<A*> t1(allocator_arg, al); // template <class Alloc> tuple(allocator_arg_t, const Alloc& a, const Types&...); tuple<A*> t2(allocator_arg, al, 0); // template <class Alloc, class... UTypes> tuple(allocator_arg_t, const Alloc& a, const UTypes&&...); tuple<A*> t3(allocator_arg, al, nullptr); // template <class Alloc> tuple(allocator_arg_t, const Alloc& a, const tuple&); tuple<A*> t4(allocator_arg, al, t2); // template <class Alloc> tuple(allocator_arg_t, const Alloc& a, tuple&&); tuple<A*> t5(allocator_arg, al, move(t2)); tuple<B*> b(nullptr); // template <class Alloc, class... UTypes> tuple(allocator_arg_t, const Alloc& a, const tuple<UTypes...>&); tuple<A*> t6(allocator_arg, al, b); // template <class Alloc, class... UTypes> tuple(allocator_arg_t, const Alloc& a, tuple<UTypes...>&&); tuple<A*> t7(allocator_arg, al, move(b)); pair<B*, Y*> by(nullptr, nullptr); // template <class Alloc, class U1, class U2> tuple(allocator_arg_t, const Alloc& a, const pair<U1, U2>&); tuple<A*, X*> t8(allocator_arg, al, by); // template <class Alloc, class U1, class U2> tuple(allocator_arg_t, const Alloc& a, pair<U1, U2>&&); tuple<A*, X*> t9(allocator_arg, al, move(by)); // const UTypes&&... tuple<int> ti(0); tuple<Meow> t10(allocator_arg, al, ti); tuple<Meow> t11(allocator_arg, al, move(ti)); pair<int, int> pii(0, 0); tuple<Meow> t12(allocator_arg, al, pii); tuple<Meow> t13(allocator_arg, al, move(pii)); } { tuple<A*> t1; (void) t1; tuple<A*> t2(0); tuple<A*> t3(nullptr); (void) t3; tuple<A*> t4(t2); (void) t4; tuple<A*> t5(move(t2)); (void) t5; tuple<B*> b(nullptr); tuple<A*> t6(b); tuple<A*> t7(move(b)); pair<B*, Y*> by(nullptr, nullptr); tuple<A*, X*> t8(by); tuple<A*, X*> t9(move(by)); tuple<int> ti(0); tuple<Meow> t10(ti); tuple<Meow> t11(move(ti)); pair<int, int> pii(0, 0); tuple<Meow> t12(pii); tuple<Meow> t13(move(pii)); } }
25.445455
116
0.535191
Weheineman
e6c82103c4ac637802c2f235e4fe96c575168d86
206
cc
C++
06/11/11.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
5
2019-08-01T07:52:27.000Z
2022-03-27T08:09:35.000Z
06/11/11.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
1
2020-10-03T17:29:59.000Z
2020-11-17T10:03:10.000Z
06/11/11.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
6
2019-08-24T08:55:56.000Z
2022-02-09T08:41:44.000Z
#include <iostream> void reset(int &i) { i = 0; } int main(void) { int i = 100; std::cout << "i = " << i << std::endl; reset(i); std::cout << "i = " << i << std::endl; return 0; }
12.875
42
0.451456
williamgherman
e6c9943df590160cb29f48598b6ee1265749f3ae
9,922
cpp
C++
sdktools/depends/src/exe/childfrm.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
sdktools/depends/src/exe/childfrm.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
sdktools/depends/src/exe/childfrm.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//****************************************************************************** // // File: CHILDFRM.CPP // // Description: Implementation file for the Child Frame window. // // Classes: CChildFrame // // Disclaimer: All source code for Dependency Walker is provided "as is" with // no guarantee of its correctness or accuracy. The source is // public to help provide an understanding of Dependency Walker's // implementation. You may use this source as a reference, but you // may not alter Dependency Walker itself without written consent // from Microsoft Corporation. For comments, suggestions, and bug // reports, please write to Steve Miller at stevemil@microsoft.com. // // // Date Name History // -------- -------- --------------------------------------------------------- // 10/15/96 stevemil Created (version 1.0) // 07/25/97 stevemil Modified (version 2.0) // 06/03/01 stevemil Modified (version 2.1) // //****************************************************************************** #include "stdafx.h" #include "depends.h" #include "dbgthread.h" #include "session.h" #include "document.h" #include "splitter.h" #include "listview.h" #include "modtview.h" #include "modlview.h" #include "funcview.h" #include "profview.h" #include "childfrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //****************************************************************************** //***** CChildFrame //****************************************************************************** /*static*/ int CChildFrame::ms_cChildFrames = 0; /*static*/ LPCSTR CChildFrame::ms_szChildFrameClass = NULL; //****************************************************************************** IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd) BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWnd) //{{AFX_MSG_MAP(CChildFrame) //}}AFX_MSG_MAP END_MESSAGE_MAP() //****************************************************************************** // CChildFrame :: Constructor/Destructor //****************************************************************************** CChildFrame::CChildFrame() : m_pDoc(g_theApp.m_pNewDoc), m_fActivated(false) // m_SplitterH2(g_theApp.m_pNewDoc) { ms_cChildFrames++; m_pDoc->m_pChildFrame = this; } //****************************************************************************** CChildFrame::~CChildFrame() { ms_cChildFrames--; } //****************************************************************************** // CChildFrame :: Overridden functions //****************************************************************************** BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs) { // Create a class for our child frame to use that does not have the // CS_VREDRAW or CS_HREDRAW flags. This prevents flicker. if (!ms_szChildFrameClass) { ms_szChildFrameClass = AfxRegisterWndClass(0); } // Use our flicker-free class instead of the default class. cs.lpszClass = ms_szChildFrameClass; return CMDIChildWnd::PreCreateWindow(cs); } //****************************************************************************** BOOL CChildFrame::OnCreateClient(LPCREATESTRUCT, CCreateContext *pContext) { // V = H-0 (#2) // +------------+------------+ // | | H2-0 (#5) | // | V-0 (#3) +------------+ H2 = V-1 (#4) // | | H2-1 (#6) | // +------------+------------+ H (#1) // | H3-0 (#8) | // +-------------------------+ H3 = H-2 (#7) // | H3-1 (#9) | // +-------------------------+ // (#1) Create our main horizontal splitter. if (!m_SplitterH.CreateStatic(this, 2, 1, 5000)) { return FALSE; } // (#2) Create our vertical splitter in pane 0 of our main horizontal splitter. if (!m_SplitterV.CreateStatic(&m_SplitterH, 1, 2, 3333, WS_CHILD | WS_VISIBLE, m_SplitterH.IdFromRowCol(0, 0))) { return FALSE; } // (#3) Create the module tree view in pane 0 of our vertical splitter. if (!m_SplitterV.CreateView(0, 0, RUNTIME_CLASS(CTreeViewModules), CSize(0, 0), pContext)) { return FALSE; } m_pDoc->m_pTreeViewModules = (CTreeViewModules*)m_SplitterV.GetPane(0, 0); // (#4) Create our 2nd horizontal splitter in pane 1 of our vertical splitter. if (!m_SplitterH2.CreateStatic(&m_SplitterV, 2, 1, 5000, WS_CHILD | WS_VISIBLE, m_SplitterV.IdFromRowCol(0, 1))) { return FALSE; } // (#5) Create the import function list view in pane 0 of our 2nd horizontal splitter. if (!m_SplitterH2.CreateView(0, 0, RUNTIME_CLASS(CListViewImports), CSize(0, 0), pContext)) { return FALSE; } m_pDoc->m_pListViewImports = (CListViewImports*)m_SplitterH2.GetPane(0, 0); // (#6) Create the export function list view in pane 0 of our 2nd horizontal splitter. if (!m_SplitterH2.CreateView(1, 0, RUNTIME_CLASS(CListViewExports), CSize(0, 0), pContext)) { return FALSE; } m_pDoc->m_pListViewExports = (CListViewExports*)m_SplitterH2.GetPane(1, 0); #if 0 //{{AFX // (#6.5) Create our richedit detail view which is a sibling to #4 if (!(m_pDoc->m_pRichViewDetails = new CRichViewDetails())) { RaiseException(STATUS_NO_MEMORY, EXCEPTION_NONCONTINUABLE, 0, NULL); } if (!m_pDoc->m_pRichViewDetails->Create( NULL, NULL, AFX_WS_DEFAULT_VIEW & ~WS_BORDER, CRect(0, 0, 0, 0), &m_SplitterV, 999, pContext)) { return FALSE; } #endif //}}AFX // (#7) Create our 3nd horizontal splitter in pane 1 of our main horizontal splitter. if (!m_SplitterH3.CreateStatic(&m_SplitterH, 2, 1, 5000, WS_CHILD | WS_VISIBLE, m_SplitterH.IdFromRowCol(1, 0))) { return FALSE; } // (#8) Create the module list view in pane 0 of our 3nd horizontal splitter. if (!m_SplitterH3.CreateView(0, 0, RUNTIME_CLASS(CListViewModules), CSize(0, 0), pContext)) { return FALSE; } m_pDoc->m_pListViewModules = (CListViewModules*)m_SplitterH3.GetPane(0, 0); // (#9) Create the runtime profiler log view pane 1 of our 3nd horizontal splitter. if (!m_SplitterH3.CreateView(1, 0, RUNTIME_CLASS(CRichViewProfile), CSize(0, 0), pContext)) { return FALSE; } m_pDoc->m_pRichViewProfile = (CRichViewProfile*)m_SplitterH3.GetPane(1, 0); #if 0 //{{AFX // Set our edit control's font to the same font as our list control. m_pDoc->m_pRichViewDetails->SetFont(m_pDoc->m_pListViewModules->GetFont(), FALSE); #endif //}}AFX // Set our edit control's font to the same font as our list control. m_pDoc->m_pRichViewProfile->SetFont(m_pDoc->m_pListViewModules->GetFont(), FALSE); return TRUE; } //****************************************************************************** void CChildFrame::ActivateFrame(int nCmdShow) { // If no particular show flag is specified (-1) and this is our first frame, // we create the frame maximized since that is most likely what the would // prefer. if (!m_fActivated && (nCmdShow == -1) && (ms_cChildFrames == 1)) { nCmdShow = SW_SHOWMAXIMIZED; } // Tell our document to do the things it wants to do just before becoming // visible, such as populated our views. if (!m_fActivated && m_pDoc) { m_pDoc->BeforeVisible(); } // Call the base class to continue displaying the frame. After this call // returns, our frame and views will be visible (assuming our main frame is // visible). CMDIChildWnd::ActivateFrame(nCmdShow); // Tell our document to do the things it wants to do just after becoming // visible, such as displaying any errors it may have. The only time we // will not be visible at this point is when a user opens a file from the // command line, since the main frame is not visible yet. In that case, // we will call AfterVisible at the end of InitInstanceWrapped, since the // main frame will be visible then. if (!m_fActivated && g_theApp.m_fVisible && m_pDoc) { m_pDoc->AfterVisible(); } // Set our activated flag in case we ever get called again (not sure if we ever do). m_fActivated = true; } //****************************************************************************** BOOL CChildFrame::DestroyWindow() { m_pDoc->m_pTreeViewModules = NULL; m_pDoc->m_pListViewImports = NULL; m_pDoc->m_pListViewExports = NULL; m_pDoc->m_pListViewModules = NULL; m_pDoc->m_pRichViewProfile = NULL; m_pDoc->m_pChildFrame = NULL; return CMDIChildWnd::DestroyWindow(); } //****************************************************************************** #if 0 //{{AFX BOOL CChildFrame::CreateFunctionsView() { m_SplitterH2.ShowWindow(SW_SHOWNOACTIVATE); m_pDoc->m_pRichViewDetails->ShowWindow(SW_HIDE); return TRUE; } #endif //}}AFX //****************************************************************************** #if 0 //{{AFX BOOL CChildFrame::CreateDetailView() { m_pDoc->m_pRichViewDetails->ShowWindow(SW_SHOWNOACTIVATE); m_SplitterH2.ShowWindow(SW_HIDE); return TRUE; } #endif //}}AFX
35.690647
108
0.526608
npocmaka
e6ce736d68bf7cb04368e6302e243e2d21e118e2
3,856
hpp
C++
lab_control_center/ui/lcc_errors/LCCErrorViewUI.hpp
Durrrr95/cpm_lab
e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67
[ "MIT" ]
9
2020-06-24T11:22:15.000Z
2022-01-13T14:14:13.000Z
lab_control_center/ui/lcc_errors/LCCErrorViewUI.hpp
Durrrr95/cpm_lab
e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67
[ "MIT" ]
1
2021-05-10T13:48:04.000Z
2021-05-10T13:48:04.000Z
lab_control_center/ui/lcc_errors/LCCErrorViewUI.hpp
Durrrr95/cpm_lab
e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67
[ "MIT" ]
2
2021-11-08T11:59:29.000Z
2022-03-15T13:50:54.000Z
#pragma once #include "defaults.hpp" #include <algorithm> #include <atomic> #include <cassert> #include <chrono> #include <ctime> #include <future> #include <map> #include <memory> #include <mutex> #include <sstream> #include <string> #include <thread> #include <gtkmm/builder.h> #include <gtkmm.h> #include <glib.h> #include "LCCErrorModelRecord.hpp" #include "LCCErrorLogger.hpp" /** * \brief UI Class for the internal Errors that occured within the LCC, mostly Commonroad-related, that do not lead to crashes and are shown to the user * \ingroup lcc_ui */ class LCCErrorViewUI { private: //! GTK builder for the UI Glib::RefPtr<Gtk::Builder> ui_builder; //! Parent box of the view, to integrate it into the overall UI Gtk::Box* parent; //! TreeView that contains the LCC error messages Gtk::TreeView* error_treeview; //! Label for the treeview Gtk::Label* error_label_header; //! Window that contains error_treeview to make it scrollable Gtk::ScrolledWindow* error_scrolled_window; //! Check button to automatically scroll to the latest error message when active Gtk::CheckButton* autoscroll_check_button; //! Reset button to reset/clear the currently shown error messages Gtk::Button* error_button_reset; //! Defines the TreeView layout LCCErrorModelRecord error_record; //! Status storage for the UI, contains all entries of error_treeview Glib::RefPtr<Gtk::ListStore> error_list_store; //UI update functions and objects /** * \brief Function called by ui_thread to periodically activate the dispatcher that in turn calls GTK's UI thread, to perform UI updates */ void update_ui(); /** * \brief Callback for GTK's UI dispatcher, all UI changes done during runtime should be performed within this function */ void dispatcher_callback(); //! To communicate between the current thread and GTK's UI thread Glib::Dispatcher ui_dispatcher; //! UI thread that periodically ativates the GTK dispatcher to perform an update in the UI std::thread ui_thread; //! Tells ui_thread if it should still be running std::atomic_bool run_thread; /** * \brief Callback function to enable autoscroll if autoscroll_check_button is used * \param allocation Irrelevant parameter that is part of the callback */ void on_size_change_autoscroll(Gtk::Allocation& allocation); /** * \brief Delete all currently shown error logs */ void reset_list_store(); /** * \brief Check for scroll event to turn off automatic scrolling in case the user scrolls manually through the error list * \param scroll_event The scroll event */ bool scroll_callback(GdkEventScroll* scroll_event); /** * \brief Callback for tooltip (to show full message on mouse hover) * \param x x coordinate e.g. of the mouse pointer * \param y y coordinate e.g. of the mouse pointer * \param keyboard_tooltip If the tooltip was triggered by the keyboard * \param tooltip Reference to the tooltip to be shown */ bool tooltip_callback(int x, int y, bool keyboard_tooltip, const Glib::RefPtr<Gtk::Tooltip>& tooltip); //! Variable for the reset action - if true, reset the logs (is performed within the UI) std::atomic_bool reset_logs; public: /** * \brief Constructor to create the UI element */ LCCErrorViewUI(); /** * \brief Destructor to destroy the UI thread on object destruction */ ~LCCErrorViewUI(); /** * \brief Function to get the parent widget, so that this UI element can be placed within another UI element */ Gtk::Widget* get_parent(); /** * \brief Might be called from outside, e.g. when a new 'simulation' is run, to reset the current error messages */ void reset(); };
33.824561
152
0.699689
Durrrr95
e6d02cd27f2410ff894e4f29876fe87754a18442
3,004
cpp
C++
pgf+/src/parser/ActiveItem.cpp
egladil/mscthesis
d6f0c9b1b1e73b749894405372f2edf01e746920
[ "BSD-2-Clause" ]
1
2019-05-03T18:00:39.000Z
2019-05-03T18:00:39.000Z
pgf+/src/parser/ActiveItem.cpp
egladil/mscthesis
d6f0c9b1b1e73b749894405372f2edf01e746920
[ "BSD-2-Clause" ]
null
null
null
pgf+/src/parser/ActiveItem.cpp
egladil/mscthesis
d6f0c9b1b1e73b749894405372f2edf01e746920
[ "BSD-2-Clause" ]
null
null
null
// // ActiveItem.cpp // pgf+ // // Created by Emil Djupfeldt on 2012-07-04. // Copyright (c) 2012 Chalmers University of Technology. All rights reserved. // #include <gf/stringutil.h> #include <gf/parser/ActiveItem.h> namespace gf { namespace parser { ActiveItem::ActiveItem(uint32_t begin, uint32_t category, gf::reader::CncFun* cncFun, const std::vector<uint32_t>& domain, uint32_t constituent, uint32_t position) : begin(begin), category(category), cncFun(cncFun), domain(domain), constituent(constituent), position(position) { } ActiveItem::~ActiveItem() { gf::release(cncFun); } uint32_t ActiveItem::getBegin() const { return begin; } uint32_t ActiveItem::getCategory() const { return category; } gf::reader::CncFun* ActiveItem::getFunction() const { return cncFun; } const std::vector<uint32_t>& ActiveItem::getDomain() const { return domain; } uint32_t ActiveItem::getConstituent() const { return constituent; } uint32_t ActiveItem::getPosition() const { return position; } gf::reader::Symbol* ActiveItem::nextSymbol() const { if (hasNextSymbol()) { return cncFun->getSequences().at(constituent)->getSymbols().at(position); } return NULL; } bool ActiveItem::hasNextSymbol() const { return position < cncFun->getSequences().at(constituent)->getSymbols().size(); } bool ActiveItem::operator==(const ActiveItem& other) const { return begin == other.begin && category == other.category && cncFun == other.cncFun && domain == other.domain && constituent == other.constituent && position == other.position; } bool ActiveItem::operator!=(const ActiveItem& other) const { return !(*this == other); } std::string ActiveItem::toString() const { std::string ret; ret = "["; ret+= gf::toString(begin) + ";"; ret+= gf::toString(category) + "->" + cncFun->getName(); ret+= "[" + domainToString() + "];"; ret+= gf::toString(constituent) + ";"; ret+= gf::toString(position); ret+= "]"; return ret; } std::string ActiveItem::domainToString() const { std::string ret; for (std::vector<uint32_t>::const_iterator it = domain.begin(); it != domain.end(); it++) { ret+= (it == domain.begin() ? "" : ", ") + gf::toString(*it); } return ret; } } }
30.969072
171
0.500333
egladil
e6d2da9d3ea57374b0bbbddfb8561453a8f34803
4,162
hpp
C++
ext/src/java/io/PrintStream.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/java/io/PrintStream.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/java/io/PrintStream.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #pragma once #include <fwd-POI.hpp> #include <java/io/fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <java/nio/charset/fwd-POI.hpp> #include <java/util/fwd-POI.hpp> #include <java/io/FilterOutputStream.hpp> #include <java/lang/Appendable.hpp> #include <java/io/Closeable.hpp> struct default_init_tag; class java::io::PrintStream : public FilterOutputStream , public virtual ::java::lang::Appendable , public virtual Closeable { public: typedef FilterOutputStream super; private: bool autoFlush { }; OutputStreamWriter* charOut { }; bool closing { }; ::java::util::Formatter* formatter { }; BufferedWriter* textOut { }; bool trouble { }; protected: void ctor(OutputStream* out); void ctor(::java::lang::String* fileName); void ctor(File* file); /*void ctor(bool autoFlush, OutputStream* out); (private) */ void ctor(OutputStream* out, bool autoFlush); void ctor(::java::lang::String* fileName, ::java::lang::String* csn); void ctor(File* file, ::java::lang::String* csn); /*void ctor(bool autoFlush, OutputStream* out, ::java::nio::charset::Charset* charset); (private) */ /*void ctor(bool autoFlush, ::java::nio::charset::Charset* charset, OutputStream* out); (private) */ void ctor(OutputStream* out, bool autoFlush, ::java::lang::String* encoding); public: PrintStream* append(::java::lang::CharSequence* csq) override; PrintStream* append(char16_t c) override; PrintStream* append(::java::lang::CharSequence* csq, int32_t start, int32_t end) override; virtual bool checkError(); public: /* protected */ virtual void clearError(); public: void close() override; /*void ensureOpen(); (private) */ void flush() override; virtual PrintStream* format(::java::lang::String* format, ::java::lang::ObjectArray* args); virtual PrintStream* format(::java::util::Locale* l, ::java::lang::String* format, ::java::lang::ObjectArray* args); /*void newLine(); (private) */ virtual void print(bool b); virtual void print(char16_t c); virtual void print(int32_t i); virtual void print(int64_t l); virtual void print(float f); virtual void print(double d); virtual void print(::char16_tArray* s); virtual void print(::java::lang::String* s); virtual void print(::java::lang::Object* obj); virtual PrintStream* printf(::java::lang::String* format, ::java::lang::ObjectArray* args); virtual PrintStream* printf(::java::util::Locale* l, ::java::lang::String* format, ::java::lang::ObjectArray* args); virtual void println(); virtual void println(bool x); virtual void println(char16_t x); virtual void println(int32_t x); virtual void println(int64_t x); virtual void println(float x); virtual void println(double x); virtual void println(::char16_tArray* x); virtual void println(::java::lang::String* x); virtual void println(::java::lang::Object* x); /*static ::java::lang::Object* requireNonNull(::java::lang::Object* obj, ::java::lang::String* message); (private) */ public: /* protected */ virtual void setError(); /*static ::java::nio::charset::Charset* toCharset(::java::lang::String* csn); (private) */ public: void write(int32_t b) override; /*void write(::char16_tArray* buf); (private) */ /*void write(::java::lang::String* s); (private) */ void write(::int8_tArray* buf, int32_t off, int32_t len) override; // Generated PrintStream(OutputStream* out); PrintStream(::java::lang::String* fileName); PrintStream(File* file); PrintStream(OutputStream* out, bool autoFlush); PrintStream(::java::lang::String* fileName, ::java::lang::String* csn); PrintStream(File* file, ::java::lang::String* csn); PrintStream(OutputStream* out, bool autoFlush, ::java::lang::String* encoding); protected: PrintStream(const ::default_init_tag&); public: static ::java::lang::Class *class_(); void write(::int8_tArray* b); private: virtual ::java::lang::Class* getClass0(); };
36.831858
121
0.675637
pebble2015
e6d40f263bbf8da0859afd7806c2c86c29614225
48,381
cxx
C++
model_server/project_file/src/projModule.cxx
kit-transue/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
2
2015-11-24T03:31:12.000Z
2015-11-24T16:01:57.000Z
model_server/project_file/src/projModule.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
null
null
null
model_server/project_file/src/projModule.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
1
2019-05-19T02:26:08.000Z
2019-05-19T02:26:08.000Z
/************************************************************************* * Copyright (c) 2015, Synopsys, Inc. * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are * * met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ //------------------------------------------ // synopsis: // define the member functions for the class projModule // //------------------------------------------ // INCLUDE FILES #include <cLibraryFunctions.h> #include <msg.h> #include <prompt.h> #include <machdep.h> #include <saveXref.h> //#include <top_widgets.h> // for push_busy_cursor, pop_cursor #include <gtDisplay.h> #include <app.h> #include <db_intern.h> #include <cmd.h> #include <cmd_enums.h> //#include <viewUIexterns.h> #ifndef _question_h #include <Question.h> #endif #include <ddict.h> #ifndef _ddL_boil_h #include <dd_boil.h> #endif #ifndef _gtRTL_boil_h #include <gtRTL_boil.h> #endif #include <XrefTable.h> #include <transaction.h> #include <fileEntry.h> #include <feedback.h> #include <proj.h> #include <timer.h> #include <driver_mode.h> #include <disbuild_analysis.h> #undef MAX void update_path_hash_tables(char *, projMap *, projNode *); void backup_the_files(char const *, char const *, char); int outdated_pset(char const *, char const *, char const *); int char_based_merge (app *app_h, char const *srcf, char const *psetf, int unload_flag, int& do_not_save_flag); bool is_forgiving(); #include <errorBrowser.h> #include <proj_save.h> #define NULL_NAME "NULL" #include <vpopen.h> #include <customize.h> #include <messages.h> #include <objOper.h> #include <objRawApp.h> #include <proj.h> #include <tpopen.h> #include <ddKind.h> #include <path.h> #include <pdf_tree.h> #include <targetProject.h> #include <xref.h> #include <db.h> #include <save.h> #include <projBackEnd.h> #include <fileCache.h> #include <db_intern.h> #include <RTL_externs.h> #include <merge_dialog.h> #include <NewPrompt.h> #include <genTmpfile.h> #include <scopeMgr.h> #include <shell_calls.h> #include <disbuild_analysis.h> #define MRG_NOREVISION "no revision" // this variable is used to synchronize crash rec of files when // exiting paraset // assuming projModule::put_module is always called by child process static int calling_put = 0; int call_from_put() { return calling_put; } void call_from_put(int n) { calling_put = n; } extern void fine_grained_dependency_analysis(projNode*); extern bool browser_delete_module(gtBase* parent, projModule *module, bool yes_to_all, char const *msg); //extern "C" int browser_import(...); void get_pset_fn (char const*, genString&); static int check_out_pset_special(projModule*,char *,char *,char *,char const*,char const*,char const *,int); void proj_path_report_app(app *, projNode *prj = NULL); bool els_parse_edg(projModule *); int els_parse_file(const Relational*); void proj_create_ctl_pm(); int get_file_names (char const *ln, projNode* src_proj, projNode* dst_proj, genString& src_file, genString& dst_file, genString& src_paraset_file, genString& dst_paraset_file); bool do_delete_pset(); void ste_smart_view_update (smtHeaderPtr, int with_text = 1); int ste_temp_view_suspend (smtHeaderPtr); int ignore_prop; void obj_delete_or_unload(Obj *root, int delete_flag); static int delete_module_internal(projModule* This, int new_flag, int type); projModule * symbol_get_module( symbolPtr& sym); //boris: remove references to ddElement extern int module_get_dds (projModule *mod, objSet& dd_set); extern int dd_set_aname (app *app_head, genString& aname); extern int dd_get_aname (app *ah, genString& aname); extern int dd_contain_ddKind (app *app_head, ddKind ki); extern int dd_dependency_analysis (app *head, char& save_flag); extern "C" void push_busy_cursor(); extern "C" void pop_cursor(); // pn == 0: pm is for this module // pn != 0: pm is for pn not for this module void projModule::update_path_hash_tables(projMap *pm, projNode *pn) { Initialize(projModule::update_path_hash_tables); char const *name = get_name(); // logical name should be identical genString fn; genString proj_n; if (pn) { pm->ln_to_fn(name, pn->get_ln(), FILE_TYPE, fn, 0, 1, pn); pm->fn_to_ln_imp(fn, pn->get_ln(), FILE_TYPE, proj_n, 0, 1); } else { projNode *proj = get_project_internal (); if (pm->is_script()) { pm->ln_to_fn(name, proj->get_ln(), FILE_TYPE, fn, 0, 1, proj); pm->fn_to_ln_imp(fn, proj->get_ln(), FILE_TYPE, proj_n, 0, 1); } else { proj->ln_to_fn(name, fn, FILE_TYPE); proj->fn_to_ln_imp(fn, proj_n, FILE_TYPE); } } pm->insert_hash(fn, proj_n, name, FILE_TYPE, LOGIC_NAME_RULE, FNTOLN); pm->insert_hash(fn, proj_n, proj_n, FILE_TYPE, PROJECT_NAME_RULE, FNTOLN); pm->insert_hash(name, proj_n, fn, FILE_TYPE, LOGIC_NAME_RULE, LNTOFN); pm->insert_hash(proj_n, proj_n, fn, FILE_TYPE, PROJECT_NAME_RULE, LNTOFN); } void update_path_hash_tables(char *name, projMap *pm, projNode *pn) { Initialize(update_path_hash_tables); genString fn; genString proj_n; if (pn) { pm->ln_to_fn(name, pn->get_ln(), FILE_TYPE, fn, 0, 1, pn); pm->fn_to_ln_imp(fn, pn->get_ln(), FILE_TYPE, proj_n, 0, 1); pm->insert_hash(fn, proj_n, name, FILE_TYPE, LOGIC_NAME_RULE, FNTOLN); pm->insert_hash(fn, proj_n, proj_n, FILE_TYPE, PROJECT_NAME_RULE, FNTOLN); pm->insert_hash(name, proj_n, fn, FILE_TYPE, LOGIC_NAME_RULE, LNTOFN); pm->insert_hash(proj_n, proj_n, fn, FILE_TYPE, PROJECT_NAME_RULE, LNTOFN); } } int projModule::check_write_priv(int the_type) // check the write privilege of file // // the_type == 0: check both file and pset // 1: check only file // 2: check only pset { Initialize(projModule::check_write_priv); genString fn; get_phys_filename(fn); struct OStype_stat buf0; int status0; int own_flag; if (the_type == 0 || the_type == 1) { status0 = global_cache.stat(fn.str(),&buf0); if (status0 == 0) { own_flag = OSapi_chmod(fn.str(),buf0.st_mode) == 0; #ifndef _WIN32 if (!(own_flag || !own_flag && (S_IWGRP&buf0.st_mode))) #else if (!own_flag) #endif /*_WIN32*/ return 0; // no write priviledge for the source file } else return 0; if (the_type == 1) return 1; } if (the_type == 0 || the_type == 2) { char const *paraset_file = paraset_file_name(); status0 = global_cache.stat(paraset_file,&buf0); if (status0 != 0) // the paraset file not exist return 1; own_flag = OSapi_chmod(paraset_file,buf0.st_mode | S_IWRITE) == 0; #ifndef _WIN32 if (!(own_flag || !own_flag && (S_IWGRP&(buf0.st_mode)))) #else if (!own_flag) #endif /*_WIN32*/ return 0; // no write priviledge for the paraset file return 1; } return 0; // bad the_type } void projModule::invalidate_cache() // clean the stat data in the cache table for the source file and the pset file // such that the next it will call OSapi_lstat() for these two files { projNode* project = get_project_internal(); // After delete the whole directory tree // project might be deleted // projModeule destructor is calle at end_transaction() // lets check if project is NULL if (project) { genString fn; if (projfile_name) projfile_name->reset(); if (!psetfile_name) paraset_file_name(); if (psetfile_name) psetfile_name->reset(); } cache_valid = 0; } bool has_paraset_file(char const * pset_file) { struct OStype_stat stat_buf; bool hpf = (global_cache.stat(pset_file, &stat_buf) == 0); return hpf; } bool projModule::is_paraset_file () { Initialize (projModule::is_paraset_file); if (!cache_valid) { cache_paraset_file = 0; struct OStype_stat stat_buf; char const *pset_fname = projModulePtr(this)->paraset_file_name(); if (pset_fname && pset_fname[0]) { if ( (global_cache.stat (pset_fname, &stat_buf) == 0) ) cache_paraset_file = 1; cache_valid = 1; } } return cache_paraset_file; } void projModule::set_target_project(projNode *pn) { Initialize(projModule::set_target_project); target_proj = pn; } appPtr projModule::get_app() // Get the module's corresponding app header { appPtr ah = projectModule_get_appHeader (this); if (ah) return ah; char const *ln = get_name(); genString pn; projNode *proj = get_project(); get_phys_filename(pn); if (get_app_ln()) ln = get_app_ln(); ah = get_app(ln, pn); if (ah) { projectNode_put_appHeader (proj, ah); projectModule_put_appHeader (this, ah); } return ah; } appPtr projModule::get_app(char const *ln, char const *pn) // return app header for this module // // ln: is the logic name to be compared // pn: is the physical name to be compared { Initialize(projModule::get_app); if (ln == 0) return 0; objArr* list = app::get_app_list(); Obj *el; ForEach (el, *list) { appPtr ah = checked_cast(app,el); char const* log_name = ah->get_filename(); if(log_name && strcmp(log_name, ln) == 0) { if (!pn) return ah; // match physical name too before making decision char const *phy_name = ah->get_phys_name(); if (phy_name && !strcmp (phy_name, pn)) return(ah); } } return(0); } appPtr projModule::get_app(char const* ln) { return get_app (ln, 0); } bool projModule::is_good_paraset_file() { Initialize(projModule::is_good_paraset_file); if (is_paraset_file() && !outdated_pset()) return 1; else return 0; } int outdated_pset_time(char const * src_file, char const *pset_file) // nonzero means the pset is outdated, or that it got a status error { Initialize(outdated_pset_time); struct OStype_stat pset_stat_buf, stat_buf; if (OSapi_stat((char *)pset_file, &pset_stat_buf) != 0) return 1; if (OSapi_stat((char *)src_file, &stat_buf) != 0) return 0; return pset_stat_buf.st_mtime < stat_buf.st_mtime; } // pset_file = fn + ".pset" int outdated_pset(char const * src_file, char const *pset_file, char const *fn) { if (!has_paraset_file (pset_file)) return 0; if (!db_get_db_format((char *)fn) || global_cache.is_frame(fn)) return ::outdated_pset_time(src_file, pset_file); genTmpfile tnm("pset"); int status; // -1 : fail // -2 : pset does not have source status = db_read_src_from_pset ((char *)pset_file, (char *)tnm.name()); if (status == -2) return FALSE; else if (status < 0) return status; status = paraset_cmp((char *)src_file, (char *)tnm.name()); tnm.unlink(); if (status == 0) // identical return FALSE; return TRUE; } int projModule::outdated_pset() // to compare the source in the .pset file and the source file // // If they are identical, return FALSE; otherwise return TRUE. // If it is loaded, it is identical. { Initialize (projModule::outdated_pset); #ifndef _WIN32 if (get_app()) return FALSE; #endif char const* pset_file = paraset_file_name(); char const* src_file = get_phys_filename(); return ::outdated_pset(src_file, pset_file, src_file); } void projModule::touch_module(int delete_pset) { Initialize(projModule::touch_module); if (!is_project_writable()) return; char *pset_file = (char *)paraset_file_name(); if (!has_paraset_file(pset_file)) return; if(OSapi_access(pset_file, W_OK) < 0) { struct OStype_stat buf0; OSapi_stat(pset_file, &buf0); if(OSapi_chmod(pset_file, 0666) != 0){ if (!db_change_to_writable(pset_file)){ msg("Cannot change_to_writable $1", error_sev) << pset_file << eom; return; } } else { OSapi_chmod(pset_file, buf0.st_mode); } } if(delete_pset) OSapi_unlink(pset_file); else db_set_bit_need_reparse(pset_file, 1); } static int insert_pset_in_xref(projModule*module, projNode* proj, int is_header, int do_insert) { int status = 0; app *head = module->restore_module(); if (head) { if(is_header) module->dependency_analysis(head, proj, 1); if(do_insert){ Xref * xr = proj->get_xref(); if (xr){ xr->insert_module_in_lxref(head); xr->save_lxref_by_module(head->get_filename()); } } obj_unload(head); module->invalidate_cache(); status = 1; } return status; } static void rm_pset_and_mod(projModule *pm, char const*pset_file, projNode *proj) { Initialize(rm_pset_and_mod); IF (pm == NULL) return; if (proj == NULL) proj = pm->get_project(); if(!pset_file) pset_file = pm->paraset_file_name(); Assert(pset_file); // OSapi_unlink(pset_file); // boris: it is possible that the pset_file is not writable // MG's touch_module() will check out and delete the file char const * fn = pm->get_phys_filename(); if ( !fn || !fn[0] ) fn = pm->get_name(); msg(" touch(undo_forgive) $1 $2\n") << fn << eoarg << pm->get_name() << eom; int delete_pset = 1; pm->touch_module(delete_pset); Xref *xref = proj->get_xref(); if (xref) xref->remove_module (pm->get_name()); } int module_needs_reparse(projModule *module) { Initialize(module_needs_reparse); char *pset_file = (char *)module->paraset_file_name(); IF(!pset_file) return 0; int need_reparse = 1; int db_format = 0; bool has_pset = has_paraset_file(pset_file); if (has_pset){ need_reparse = db_get_pset_need_reparse_no_forgive(pset_file); } int outdated_pset_flag = module->outdated_pset(); if(need_reparse || outdated_pset_flag){ return 1; } return 0; } void add_outdated_module(projModule*); void projModule::update_xref() // pass 1 for -batch // // Dependency analysis from all header files to all source files. // It requires the restore and merge of the header files. // // 0. If it satisfies the following four conditions // // . a source file (*.[cC]) // . is updated (the need_reparse bit in the header of the .pset file is 0) // . is not outofdated (the source in the .pset file and the source are identical) // . its pset is newer than the pmod // // do the restore to update the pmod and go to pass 2. // // 1. Check out the .pset file for the head or source file (*.[cChH]) // which requires reparsed if // . the .pset file dose not exist OR // . the .pset exists but // . no write permission AND // . need_parse_bit is set OR the source is outofdated // // 2. Do the restore and/or merge for this .pset file. // 3. Check out the .pset files for the touched source files. // 4. Delete the .pset file for the head file. { Initialize (projModule::update_xref); projNode *proj = get_project(); char *path = (char *)get_phys_filename(); IF (!path) return; char *pset_file = (char *)paraset_file_name(); IF(!pset_file) return; timer::init (1, "update_xref", path); int need_reparse = 1; int db_format = 0; bool has_pset = has_paraset_file(pset_file); if (has_pset){ need_reparse = db_get_pset_need_reparse_no_forgive(pset_file); db_format = db_get_pset_format(pset_file); } int outdated_pset_flag = outdated_pset(); if (!is_forgiving() && do_delete_pset() && db_get_pset_forgive(pset_file)){ rm_pset_and_mod(this, pset_file, proj); timer::showtime (1, "update_xref", path); return; } if(need_reparse || outdated_pset_flag) add_outdated_module(this); int is_header = ! xref_not_header_file(path); if (!need_reparse && !outdated_pset_flag){ // boris 090298; disbuils analysis pass skips everything but outdated header files if (!disbuild_analysis_mode()) { symbolPtr tsp = Xref_file_is_newer((char *)ln_name, (char *)path); bool do_the_update = tsp.xrisnull(); if (do_the_update) insert_pset_in_xref(this, proj, is_header, 1); } } else if (is_header) { if(outdated_pset_flag){ int late_save = 1; // boris 970514 char file_type = -1; // Ignore read/write permitions. We merge in memory only. char do_backup = 0; // Do not do backup, because we do not save the file. char do_unload = 0; // Do not unload after merge projModule::merge_module(this, path, pset_file, file_type, do_backup, do_unload, late_save); // boris 090298; in disbuild analysis pass just do dependency if (disbuild_analysis_mode()) { app *head = restore_module(); if (head) dependency_analysis(head, proj, 1); } } // boris 090298; disbuild analysis pass does not change pmod if (!disbuild_analysis_mode()) insert_pset_in_xref(this, proj, is_header, 0); unload_module(); } timer::showtime (1, "update_xref", path); show_arena(path); } static app * last_inserted_app; static Xref * last_inserted_Xref; void proj_set_app_insert_Xref (app* h, Xref* xr) { last_inserted_app = h; last_inserted_Xref = xr; } extern "C" void cmd_journal_dump_pset(app *); bool projModule_dump_pset(projModule *mod) { app *head = NULL; bool val = false; if (has_paraset_file(mod->paraset_file_name())) { head = mod->restore_module(); if (head) { cmd_journal_dump_pset(head); val = true; } } return val; } app* projModule_try_to_restore(projModule* mod) { app* head = NULL; char *path = (char *)mod->get_phys_filename(); char *pset_file = (char *)mod->paraset_file_name(); char const * ln_name = mod->get_name(); projNode* proj_node = mod->get_project(); if(has_paraset_file(pset_file) && !mod->outdated_pset()){ if(!db_get_pset_need_reparse_no_forgive(pset_file)){ symbolPtr tsp = Xref_file_is_newer(ln_name, path); bool do_the_update = tsp.xrisnull(); if(do_the_update){ proj_set_app_insert_Xref (NULL, NULL); head = mod->restore_module(); if (head){ Xref * xr = proj_node->get_xref(); if (xr) if (xr != last_inserted_Xref || head != last_inserted_app) xr->insert_module_in_lxref(head); save_cur_xref (head); } } } } return head; } // projModule::load_module // // Load the module into memory - restore if needed otherwise import it appPtr projModule::load_module() { return load_module_internal (1); } // projModule::load_module_internal // // Load the module into memory - restore if needed otherwise import it appPtr projModule::load_module_internal(int do_import) { Initialize (projModule::load_module_internal); appPtr ah = get_app(); if (ah) { if (is_smtHeader(ah)) { smtHeaderPtr smt = smtHeaderPtr(ah); if (smt->foreign && smt->parsed == 0) { obj_unload (smt); smt = NULL; ah = NULL; } else return ah; } else return ah; } ah = restore_module(); if (!ah && do_import) ah = import_module(); if (ah) { projNode* proj_node = get_project(); if(proj_node) { projHeaderPtr proj_hdr = checked_cast(projHeader, proj_node->get_header()); if (proj_hdr) obj_insert(proj_hdr, REPLACE,proj_node,proj_node,NULL); } xref_notifier_report(0, this); } return ah; } appPtr projModule::import_module() // import module { Initialize(projModule::import_module); appPtr ah = get_app(); if (ah) { if (is_smtHeader(ah)) { smtHeaderPtr smt = (smtHeader*)ah; if (smt->foreign && smt->parsed == 0) { obj_unload (ah); smt = NULL; ah = NULL; } else return ah; } else return ah; } projNode* proj_node = get_project_internal(); char const * filename = get_phys_filename(); if (OSapi_access(filename, R_OK)) { msg("ERROR: Cannot open \"$1\":$2") << filename << eoarg << OSapi_strerror(errno) << eom; return NULL; } if (!global_cache.is_ascii(filename)) return NULL; char const *ftype; switch (language()) { case FILE_LANGUAGE_C: ftype = "c"; break; case FILE_LANGUAGE_CPP: ftype = "cplusplus"; break; case FILE_LANGUAGE_ESQL_C: ftype = "esql-c"; break; case FILE_LANGUAGE_ESQL_CPP: ftype = "esql-cplusplus"; break; case FILE_LANGUAGE_RAW: ftype = "raw"; break; case FILE_LANGUAGE_UNKNOWN: ftype = "unknown"; break; case FILE_LANGUAGE_MAKEFILE: ftype = "makefile"; break; case FILE_LANGUAGE_ELS: ftype = "els"; break; default: ftype = "unknown"; break; } int write_on = (proj_node->get_xref()) ? proj_node->get_xref()->is_writable(): 0; projNode* old_proj = projNode::get_current_proj (); if (write_on) projNode::set_current_proj (proj_node); else projNode::set_current_proj (projNode::get_control_project()); if (language() == FILE_LANGUAGE_ELS) { int els_parse_file(const Relational*); int res = els_parse_file(this); } #ifdef XXX_non_ELS_lang // else browser_import (NULL, filename, ftype); #endif // XXX: should throw projNode::set_current_proj (old_proj); if ( (ah = get_app()) ) { if (write_on) ah->set_read_only(0); else ah->set_read_only(1); ah->set_phys_name ((char *)filename); ah->set_imported(); } return ah; } void obj_unload(Obj*); int projModule::unload_module() // Unload the module from memory { Initialize(projModule::unload_module); // Unload raw version // projNode* project = get_project_internal(); // genString fn; // project->ln_to_fn (ln_name, fn); genString fn = get_phys_filename(); if (fn.length()) { genString path; project_convert_filename(fn, path); appPtr raw_app; while (raw_app = app::get_header (App_RAW, path)) obj_unload (raw_app); } // Unload paraset model appPtr ah = get_app(); if (!ah) { update_module(); return 0; } obj_unload (ah); invalidate_cache(); if (ah){ projNode* proj_node = get_project(); projHeaderPtr proj_hdr = checked_cast(projHeader, proj_node->get_header()); if (proj_hdr) obj_insert(proj_hdr, REPLACE,proj_node,proj_node,NULL); } if (!get_delete_flag()) { symbolPtr xsym = this; xsym = xsym.get_xrefSymbol(); xref_notifier_report(0, xsym); } update_module(); return 1; } projModule * app_get_mod(appPtr ah) /* does not handle raw header */ { if (ah == 0) return 0; projModule *mod = appHeader_get_projectModule(ah); if (mod == 0) { projNode *pr = app_get_proj(ah); if (pr) { char const *nm = (ah->get_type() != App_RAW) ? ah->get_filename() :0; if (nm) mod = pr->find_module(nm); } } return mod; } //-------------------------------------------------------- int get_file_names (char const *ln, projNode* src_proj, projNode* dst_proj, genString& src_file, genString& dst_file, genString& src_paraset_file, genString& dst_paraset_file) // get_file_names by logic name ln, the local project src_proj and the system project dst_proj // // returns the source file name: src_file // the system file name: dst_file // the source pset name: src_paraset_file // the system pset name: dst_paraset_file { src_proj->ln_to_fn (ln, src_file); if (!src_file.length() && src_proj->is_script()) src_proj->ln_to_fn(ln, src_file, FILE_TYPE, 0, 1); if (!src_file.length()) { msg("ERROR: No file mapping for logical name $1 in project $2") << ln << eoarg << src_proj->get_ln() << eom; return 0; } src_paraset_file = get_paraset_file_name (src_file, src_proj); if (!src_paraset_file.length()) { msg("ERROR: No DISCOVER file mapping for logical name $1") << ln << eom; return 0; } dst_proj->ln_to_fn (ln, dst_file); if (!dst_file.length()) dst_proj->ln_to_fn(ln, dst_file, FILE_TYPE, 1, 1); if (!dst_file.length()) { msg("ERROR: No file mapping for logical name $1 in project $2") << ln << eoarg << dst_proj->get_ln() << eom; return 0; } dst_paraset_file = get_paraset_file_name (dst_file, dst_proj); if (!dst_paraset_file.length()) { msg("ERROR: No DISCOVER file mapping for logical name $1") << ln << eom; return 0; } return 1; } static void report_merge_error(char const *file, char const * /* paraset_file */ ) // print the warning for the merge error // // file: the source file name // paraset_file: the pset file name { Initialize(report_merge_error); msg("ERROR: Merge of file '$1' failed. Its pset file might be out of sync.") << file << eom; } static void backup_one_file(char const *file) // create backup file for "file" { Initialize(backup_one_file); genString s = OSPATH(file); genString cmd; char *q = (char *)strrchr(s.str(),'/'); genString cp_from; genString cp_to; if (q) { *q = '\0'; cp_to.printf ("%s/##%s#~", s.str(),q+1); cp_from.printf ("%s/%s", s.str(),q+1); } else { cp_to.printf ("##%s#~",s.str()); cp_from = s.str(); } shell_cp (cp_from, cp_to); } void backup_the_files(char const *file, char const *paraset_file, char func) // create backup file for merge // // file: the source file name // paraset_file: the pset file name // func = 0: for merge // func = 1: for get, copy, get old module // func = 2: for 3 file merge { Initialize(backup_the_files); if (!customize::configurator_do_backups() && func != 1) return; if (file && func != 0) // for 2-file merge no backup for source file backup_one_file(file); if (paraset_file) backup_one_file(paraset_file); } extern bool is_els_non_ascii_suffix(char const *); int merge_file_type(char const *file) // check if the file is source file that includes head files { Initialize(merge_file_type); int res = 0; if (!file || !file[0]) return res; fileLanguage lang = guess_file_language (file); if (lang == FILE_LANGUAGE_UNKNOWN || lang == FILE_LANGUAGE_EXT || lang == FILE_LANGUAGE_EXT_I || lang == FILE_LANGUAGE_EXT_X ) res = 0; else if (lang == FILE_LANGUAGE_ELS) { res = (is_els_non_ascii_suffix(file)) ? 0 : 1; } else res = 1; return res; } extern appPtr db_restore_update_xref(projModule *pm); int projModule::merge_module(projModule *pm, char const *file, char const *paraset_file, char type, char backup_flag, char unload_flag, int &do_not_save_flag) // set up to merge 2 files: file and paraset_file (when C & pset files are out of sync) // // pm: is the projmodule for this file // // file: is the source file name // // paraset_file: is the source pset file name // // type = 0 from paraset interactive // = 1 from -batch mode // // backup flag: create backup copy of both // // unload_flag: unload pm after merge. // // do_not_save_flag: if 0, and it needs save, do the save at the end of merge // : if 1, and it needs save, set do_not_save_flag to 2 and don\'t do the save { Initialize(projModule::merge_module); if (!merge_file_type(file)) return 0; genString fn; pm->get_phys_filename(fn); // == 0 identical // == -2 no source file // == -1 fail to read source file if ((::outdated_pset(file, paraset_file, fn)) <= 0) return 0; // check if empty token table app* app_h = pm->get_app(); if (!app_h) { if (disbuild_analysis_mode()) { genString pn; pm->get_phys_filename(pn); if (pn.str()) app_h = ::db_restore(pn, pm->get_name()); } else { app_h = db_restore_update_xref(pm); // ::db_restore(fn); } } if (!app_h) return 0; if (is_smtHeader(app_h)) { smtHeader *sh = checked_cast(smtHeader, app_h); sh->get_root(); IF (sh->ttablth == 0 && sh->src_asize != 0) return 0; } // check if empty token table struct OStype_stat buf0; int status0 = global_cache.stat(file,&buf0); int chmod_status0=0; int chmod_status1=0; if (status0 == 0) { chmod_status0 = OSapi_chmod(fn.str(),buf0.st_mode|S_IWRITE); } struct OStype_stat buf1; int status1 = global_cache.stat(paraset_file,&buf1); if (status1 == 0) { if (chmod_status1 = OSapi_chmod(paraset_file,buf1.st_mode|S_IWRITE) < 0) { if (chmod_status0 == 0) OSapi_chmod(fn.str(),buf0.st_mode); } } push_busy_cursor(); // copy the backup file if (backup_flag) backup_the_files(file,paraset_file,0); smtHeader *sh = checked_cast(smtHeader,app_h); int merge_status = char_based_merge (app_h, file, paraset_file, unload_flag, do_not_save_flag); if (status0 == 0 && chmod_status0 == 0) OSapi_chmod(fn.str(),buf0.st_mode); if (!merge_status) // fail { // remove the pset if (!backup_flag) backup_the_files(0,paraset_file,0); OSapi_unlink(paraset_file); // give an warning report_merge_error(file, paraset_file); } else // succeed { if (status1 == 0 && chmod_status1 == 0) OSapi_chmod(paraset_file,buf1.st_mode); } pop_cursor(); if (pm) pm->invalidate_cache(); return 1; } char const *projModule::get_app_ln() { Initialize(projModule::get_app_ln); return app_ln; } projModule *projModule::create_script_module(projNode *pn, char const *ln) { Initialize(projModule::create_script_module); projNode *cur = pn; while(cur && !cur->get_map()) cur = cur->find_parent(); if (!cur) return 0; projMap *pm = cur->get_map(); update_path_hash_tables(pm, pn); genString fn; pn->ln_to_fn(ln, fn); projModule *dst_mod = proj_make_module(fn, pn, ln); pn->insert_module_hash(dst_mod); return dst_mod; } void projModule::setup_SWT_Entity_Status(app *ah) { Initialize(projModule::setup_SWT_Entity_Status); if (ah == 0) ah = get_app(); if (ah == 0) return; projNode *proj = get_project(); ddRoot * dr = checked_cast(ddRoot, get_relation(ddRoot_of_smtHeader, app_head)); if (dr == 0) return; dr->setup_SWT_Entity_Status(1); Xref * Xr = proj->get_xref(); if (Xr) Xr->insert_SWT_Entity_Status(ah); } void projModule::get_destination_candidates(objArr& dst_projs) { Initialize(projModule::get_destination_candidates); projNode* this_proj = this->get_project(); projNode* proj; for (int i=1; proj = projList::search_list->get_proj(i); i++) { projNode *parent; for (parent = this_proj; parent; parent = parent->find_parent()) { if (proj == parent) break; } if (parent) continue; genString fn; proj->ln_to_fn (ln_name, fn); if (fn.length()) dst_projs.insert_last (proj); } if (dst_projs.size() == 0) dst_projs.insert_last (this_proj); } void projModule::dependency_analysis(app* head, projNode *dst_proj, int not_save_flag) // collect the changed ddElements // // head: the app header for this module // dst_proj: the projnode this module belongs to // not_save_flag: if set, don"t save the changess because the .pset file will be // deleted. { Initialize(projModule::dependency_analysis); if (head && XREF_check_files_including(ln_name)) { char save_flag = 0; int res = dd_dependency_analysis (head, save_flag); if (res == -1) { msg("Cannot do dependency analysis for file $1") << (char *)ln_name << eom; msg(" Affected files should be examined manually") << eom; } else { if (save_flag && !not_save_flag) ::db_save(head, NULL); // update the pset file. fine_grained_dependency_analysis(dst_proj); } } } // projModule::save_module // // Saves the module to disk - translates to writable project int projModule::save_module() { appPtr ah = get_app(); bool flag = false; if (ah) { if (ah->is_modified()) flag = true; int status = ::db_save (ah, NULL); // second parameter can be // physical name for saved file invalidate_cache(); return status; } else return 0; } int projModule::delete_module() // delete a module { Initialize(projModule::delete_module); projNode *par = get_project(); genString fn; get_phys_filename(fn); int status = delete_module(0, 0); if (par && par->is_script()) { struct OStype_stat stat_buf; if (global_cache.stat(fn.str(),&stat_buf) != 0) { // file not exist. It is not an element yet before it is deleted. projNode *proj; for (int i=1; proj = projList::search_list->get_proj(i); i++) { if (proj == par) continue; projModule *mod = proj->find_module(ln_name); if (mod) mod->delete_module(1, 0); } } } return status; } int projModule::delete_module (int new_flag) // delete a module // // new_flag = 0: deletes project module, app, and disk file // new_flag = 1: force_refresh_flag (file is deleted before come here) // new_flag = 2: 3 file merge for put and for 2 file merge { Initialize(projModule::delete_module); return delete_module (new_flag, 0); } int projModule::delete_module (int new_flag, int tp) { return delete_module_internal(this, new_flag, tp); } bool delete_module_internal_call_cm (projModule *, int, genString, genString, genString, genString); void delete_module_internal_call_triggers (projModule *, int, int); void delete_module_internal_finish (char const *, projNode *); static int delete_module_internal(projModule* This, int new_flag, int type) // delete a module // // new_flag = 0: deletes project module, app, and disk file // new_flag = 1: force_refresh_flag (file is deleted before come here) // new_flag = 2: 3 file merge for put and for 2 file merge // new_flag = 3: same as 1 and don"t remove from pmod which is for reloading pdf // // type = 0: delete_module // type = 1: unget_module { Initialize(delete_module_internal); char const *name = This->get_name(); projNode* dest_proj = This->get_project(); projNode* non_home_proj = projHeader::non_current_project(name); if (!dest_proj) return 0; if (!non_home_proj) non_home_proj = dest_proj; genString src_file; genString src_paraset_file; genString dst_file; genString dst_paraset_file; if (!get_file_names (name, non_home_proj, dest_proj , src_file, dst_file, src_paraset_file, dst_paraset_file)) return 0; if (new_flag == 2 || (new_flag == 0 && (customize::no_cm() || !is_aset()))) { OSapi_unlink(dst_file); OSapi_unlink(dst_paraset_file); } else if (new_flag == 0) { if (new_flag == 2 || customize::no_cm()) { OSapi_unlink(dst_file); OSapi_unlink(dst_paraset_file); } else { if (delete_module_internal_call_cm (This, type, src_file, dst_file, src_paraset_file, dst_paraset_file)) { return 1; } } } // remove paraset file start_transaction() { This->set_delete_flag(1); This->unload_module(); // -1 for delete, remove from view This->set_delete_flag(0); This->invalidate_cache(); obj_delete(This); if (new_flag != 3) { // must remove from xrefs after deleting app and module Xref *xref = dest_proj->get_xref(); if (xref) { delete_module_internal_call_triggers (This, new_flag, type); xref->remove_module (name); if (new_flag != 2) xref->remove_module_from_xref (name); } } } end_transaction(); delete_module_internal_finish (name, dest_proj); return 1; } // projModule::language // // Sets the module's language type void projModule::language (fileLanguage new_lang) { Initialize(projModule::language__fileLanguage); if (new_lang == commonTree::language) return; if (disbuild_analysis_mode()) { commonTree::language = new_lang; return; } projNode *pr = this->get_project(); if (!pr || pr->root_project() != projNode::get_home_proj()->root_project()) { msg("You can only change modules belonging to your home project.", error_sev) << eom; return; } symbolPtr syminxref = NULL_symbolPtr; app *ah = this->get_app(); int symbol_found = 0; Xref* xr = pr->get_xref(1); if (xr) { symbolArr res; syminxref = lookup_file_symbol_in_xref(this->get_name(), xr); if (syminxref.xrisnotnull()) symbol_found = 1; } symbolPtr xref_symb = pr->lookup_symbol (DD_MODULE, (char *)ln_name); symbolPtr xref_syminxrefb = syminxref.get_xrefSymbol(); switch (commonTree::language) { case FILE_LANGUAGE_C: case FILE_LANGUAGE_CPP: case FILE_LANGUAGE_FORTRAN: case FILE_LANGUAGE_COBOL: case FILE_LANGUAGE_ESQL_C: case FILE_LANGUAGE_ESQL_CPP: case FILE_LANGUAGE_UNKNOWN: switch (new_lang) { case FILE_LANGUAGE_C: case FILE_LANGUAGE_CPP: case FILE_LANGUAGE_FORTRAN: case FILE_LANGUAGE_COBOL: case FILE_LANGUAGE_ESQL_C: case FILE_LANGUAGE_ESQL_CPP: break; default: { if (this->get_app() || this->is_paraset_file()) { int unload_flag = dis_question (T_CHANGELANG, B_CHANGEANYWAY, B_CANCEL, Q_LOSEASSOCCHANGE, get_name()); if (unload_flag == 1) { unload_module(); OSapi_unlink (paraset_file_name()); invalidate_cache(); xr->remove_module (ln_name); xr->remove_module_from_xref (ln_name); } } } break; } break; case FILE_LANGUAGE_RAW: { if (this->get_app() || this->is_paraset_file()) { int unload_flag = dis_question (T_CHANGELANG, B_CHANGEANYWAY, B_CANCEL, Q_LOSEASSOCCHANGE, get_name()); if (unload_flag == 1) { unload_module(); OSapi_unlink (paraset_file_name()); invalidate_cache(); xr->remove_module (ln_name); xr->remove_module_from_xref (ln_name); } } } break; } if (symbol_found) xref_syminxrefb->set_language (new_lang, xr->get_lxref()); if (xref_symb.xrisnotnull()) xref_symb->set_language (new_lang, xr->get_lxref()); if (ah) ah->language = new_lang; commonTree::language = new_lang; projHeader* h = this->get_header(); obj_insert (h, REPLACE, pr, pr, NULL); } // projModule::is_home_project() // // Test to see if module is the home project bool projModule::is_home_project() const { projNode* proj = get_project(); projNode* proj_root = proj->root_project(); projNode* home = projNode::get_home_proj(); projNode* home_root = home->root_project(); return (proj_root==home_root); } bool projModule::is_project_writable() const // check if this module belongs to a writable projnode { projNode *pn = get_project(); if (pn) { Xref *xr = pn->get_xref(); if (xr && xr->is_project_writable()) return TRUE; } return FALSE; } // projModule::is_loaded // // Test to see if the module is loaded into memory bool projModule::is_loaded() { if (get_app()) return 1; else return 0; } // projModule::is_modified // // Test to see if the memory copy of the app has been modified bool projModule::is_modified() { appPtr ah = get_app(); if (ah) return ah->is_modified(); else return 0; } // projModule::is_parsed // // ??? appPtr projModule::find_app () // return app header for this module { appPtr app_ptr = get_app(); if (app_ptr) return app_ptr; genString fn; get_phys_filename(fn) ; app_ptr = app::find_from_phys_name(fn); return app_ptr; } app *projModule::get_symbolPtr_def_app () { Initialize(projModule::get_symbolPtr_def_app); app *prh = get_app(); return prh; } void propagate_modified_headers() { Initialize(propagate_modified_headers); symbolArr hdrs = Hierarchical::prop_rtl_contents(); Hierarchical::clear_prop_rtl(); symbolPtr hdr; ForEachS(hdr, hdrs) { if (hdr.relationalp()) { RelationalPtr objp = hdr; if (is_app(objp)) { projModulePtr mod = appHeader_get_projectModule( (app *)objp ); /* projModulePtr mod = appPtr(objp)->get_module(); */ if (mod) { obj_insert(checked_cast(app, mod->get_header()), REPLACE, (appTree*) mod, (appTree*) mod, (void*) NULL); } } } } } //----------------------------------------------------------------------------- // // Set of functions for processing CM-events receiving from NT // // All functions have 1 parameter: // char const* fname_list // null terminate string contaned list of full phisical file names // separated by `\n` // // All functions must return 0 in case of success // typedef projModule* (*projModuleptr_func) (symbolPtr&); int cli_question_save_all(symbolArr&); int dis_confirm_and_save_for_reparse(symbolArr& apps) { int answer = 1; if (apps.size() == 0) return answer; answer = cli_question_save_all(apps); if (answer != 1) return answer; symbolPtr sym; ForEachS(sym,apps) { app* ah = (app*)sym; ::db_save(ah,NULL); } return answer; } void ste_interface_modified( HierarchicalPtr, boolean ); int els_reparse_modules(symbolArr& modules, symbolArr& rest) { Initialize(els_reparse_modules(symbolArr&,symbolArr&)); int retval = 0; objArr* apps = app::get_modified_headers(); symbolArr modified; { Obj* el; ForEach (el,*apps) { appPtr appptr = checked_cast(app,el); if (is_objRawApp(appptr) && appptr->is_modified() || is_smtHeader(appptr) && appptr->is_src_modified()) modified.insert_last (appptr); } } if (dis_confirm_and_save_for_reparse(modified) == 1) { start_transaction() { errorBrowserClear(); symbolPtr sym; int flag_suspend = 0; ForEachS(sym,modules) { projModule *pm = symbol_get_module(sym); fileLanguage type = pm->language(); app* ah = pm->get_app(); if (ah && is_smtHeader(ah)) { ste_temp_view_suspend ((smtHeader*)ah); flag_suspend = 1; } bool code = true; if (type == FILE_LANGUAGE_ELS) { els_parse_file(pm); code = false; } else if (type == FILE_LANGUAGE_C || type == FILE_LANGUAGE_CPP || type == FILE_LANGUAGE_ESQL_C || type == FILE_LANGUAGE_ESQL_CPP) code = els_parse_edg(pm); if (code) rest.insert_last(sym); else { ah = pm->get_app(); if (ah && is_smtHeader(ah) && flag_suspend) { ste_smart_view_update ((smtHeader*)ah ); ste_interface_modified (ah, 0); } } } retval = rest.size(); } // errorBrowser_show_errors(); end_transaction(); } delete apps; return retval; } //=========================================================== #ifdef NEW_UI #include <Application.h> #include <DIS_ui/interface.h> #include "tcl.h" #include "Interpreter.h" #ifndef ISO_CPP_HEADERS #include <iostream.h> #include <fstream.h> #else /* ISO_CPP_HEADERS */ #include <iostream> using namespace std; #include <fstream> #endif /* ISO_CPP_HEADERS */ //-------------------- // int cli_process_input(char *data, ostream&, Interpreter *, int do_prompt_and_print); static char szClientFileName[257] = ""; static ofstream null_stream("nul", ios::out); static Interpreter* interpClient; //$ideHandle $back $wv $cmd $arg int dis_ide_command_event(int argc, char *argv[] ) { Initialize(dis_ide_proj_event); genString res; if ( argc >= 6 ) { if ( OSapi_strcmp( argv[4], "init") == 0 ) { char const *pszTemp = OSapi_getenv("TEMP"); if ( pszTemp && *pszTemp ) { interpClient = Interpreter::Create(); res = OSPATH(pszTemp); } } else { genString command = argv[4]; for (int i=5 ; i< argc; i++ ) { command += " "; command += argv[i]; } command += "\n"; cli_process_input(command, null_stream, interpClient, 1); if( interpClient->command.length()==0) interpClient->GetResult(res); } if ( res.length() && strcmp( argv[2], "no_cmd") !=0 ) { genString str; str.printf ("dis_ide_send_command {dis_ide_command_answer %s %s %s \"%s\"}", argv[1], argv[2], argv[3], res.str() ); rcall_dis_DISui_eval_async (Application::findApplication("DISui"), (vchar *)(char *)str); } } return 0; } #endif //boris created hash for realOSPATH //----------------------------------------------------------------- #ifdef _WIN32 #include <Hash.h> class realosItem : public namedObject { genString realosFName; public: realosItem(char const *phy, char const *rn) : namedObject(phy), realosFName(rn) { } char const *get_realosFName() { return (char const *)realosFName; } }; class realosHash : public nameHash { public: virtual char const* name(const Object*)const; virtual bool isEqualObjects(const Object&, const Object&) const; }; bool realosHash::isEqualObjects(const Object& o1, const Object& o2) const { realosItem *f1 = (realosItem *)&o1; realosItem *f2 = (realosItem *)&o2; char const *n1 = f1->get_name(); char const *n2 = f2->get_name(); bool res = (strcmp(n1,n2) == 0) ? 1 : 0; return res; } char const *realosHash::name (const Object*o)const { realosItem *f = (realosItem *)o; return (char const *)f->get_name(); } static realosHash realosNames; static char const *get_realos_name (char const *phy) { char const *line = 0; Object *found = 0; int x = 0; realosNames.find (phy, x, found); if (found) { realosItem *f = (realosItem *)found; line = f->get_realosFName (); } return line; } char *DisFN_realOSPATH(char *path); char const *realOSPATH_hashed(char const *path) { if ( !path || !*path || *path == '*' || (*path == '('&& *(path+1) == '*') ) return path; char const * realos = get_realos_name (path); if (realos && realos[0]) return (char *) realos; // returning permanent char const * from hash table char *ret_path = DisFN_realOSPATH( (char *)path ); realosItem *ri = new realosItem(path, ret_path); realosNames.add(*ri); return (char *)ri->get_realosFName(); } #endif
25.490516
111
0.635291
kit-transue
e6d745196d151d41dd1541723ccf20c32233acab
2,572
cpp
C++
Online Judges/UVA/10106-Product.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/UVA/10106-Product.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/UVA/10106-Product.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; char res[100000]; void addString(char *pro) { int len1=strlen(res); int len2=strlen(pro); int l_low,l_high; // cout<<len1<<" "<<len2<<endl; if(len1<=len2) { l_low=len1; l_high=len2; } else { l_low=len2; l_high=len1; } int temp=0; for(int i=1;i<=l_low;i++) { temp=((res[len1-i]-'0')+(pro[len2-i])-'0')+temp; // cout<<temp<<endl; res[(l_high+1)-i]=(temp%10)+'0'; // cout<<sum[i]<<endl; temp=temp/10; } // cout<<sum[2]<<endl; if(l_low==len1) { //cout<<"in if: "<<sum<<endl; int k; for(k=len2-len1-1;k>=0;k--) { temp=pro[k]-'0'+temp; res[k+1]=(temp%10)+'0'; temp=temp/10; } if(temp>0) { res[k+1]=temp+'0'; } else res[k+1]='0'; res[len2+1]='\0'; } else if(l_low==len2) { // cout<<"in else: "<<sum<<endl; int k; for(k=len1-len2-1;k>=0;k--) { temp=res[k]-'0'+temp; res[k+1]=(temp%10)+'0'; temp=temp/10; } if(temp>0) { res[k+1]=temp+'0'; } else res[k+1]='0'; res[len1+1]='\0'; } //cout<<sum<<endl; } int main() { char str1[500]; char str2[500]; while(gets(str1)) { gets(str2); res[0]='0'; res[1]='\0'; int len1 = strlen(str1); int len2 = strlen(str2); int k=0; for(int i=len2-1;i>=0;i--) { char pro[100000]; int temp=0; int n= str2[i]-'0'; for(int j=len1-1;j>=0;j--) { temp = (str1[j]-'0')*n+temp; pro[j+1]= temp%10+'0'; temp/=10; } // cout<<pro<<endl; pro[0]=temp+'0'; for(int a=0;a<k;a++) { pro[len1+1+a]='0'; } pro[len1+1+k]='\0'; // cout<<pro<<endl; // cout<<res<<endl; addString(pro); k++; } int len=strlen(res); int flag=0; for(int i=0;i<len;i++) { if(flag==0&&res[i]=='0') continue; else { flag=1; printf("%c",res[i]); } } cout<<"\n"; } return 0; }
16.921053
56
0.360031
akazad13
e6d7c8919db6687721d54bc0bfc9b2d8589e34e9
84,275
cpp
C++
src/restsrv.cpp
grodansparadis/vscl2drv-websock1
5f5345c25fae4f8c6f591a8bafef3cb8c829e027
[ "MIT" ]
1
2021-05-18T11:24:30.000Z
2021-05-18T11:24:30.000Z
src/restsrv.cpp
grodansparadis/vscl2drv-websock1
5f5345c25fae4f8c6f591a8bafef3cb8c829e027
[ "MIT" ]
3
2021-06-30T21:25:21.000Z
2021-06-30T21:28:36.000Z
src/restsrv.cpp
grodansparadis/vscpl2drv-websrv
5f5345c25fae4f8c6f591a8bafef3cb8c829e027
[ "MIT" ]
null
null
null
// restsrv.cpp // // This file is part of the VSCP (https://www.vscp.org) // // The MIT License (MIT) // // Copyright © 2000-2021 Ake Hedman, the VSCP project // <akhe@vscp.org> // // 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. // #ifdef __GNUG__ //#pragma implementation #endif #define _POSIX #include <algorithm> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <arpa/inet.h> #include <errno.h> #include <linux/if_ether.h> #include <linux/if_packet.h> #include <linux/sockios.h> #include <net/if.h> #include <net/if_arp.h> #include <netdb.h> #include <netinet/in.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/msg.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include "web_css.h" #include "web_js.h" #include "web_template.h" #include <json.hpp> // Needs C++11 -std=c++11 #include <actioncodes.h> #include <civetweb.h> #include <mdf.h> #include <version.h> #include <vscp.h> #include <vscp_aes.h> #include <vscp_debug.h> #include <vscphelper.h> #include <webobj.h> #include <websrv.h> #include "restsrv.h" #include <json.hpp> // Needs C++11 -std=c++11 #include <mustache.hpp> #include <spdlog/async.h> #include <spdlog/sinks/rotating_file_sink.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/spdlog.h> // https://github.com/nlohmann/json using json = nlohmann::json; using namespace kainjow::mustache; #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif // Prototypes void restsrv_doStatus(struct mg_connection* conn, struct restsrv_session* pSession, int format, void* cbdata); void restsrv_doOpen(struct mg_connection* conn, struct restsrv_session* pSession, int format, void* cbdata); void restsrv_doClose(struct mg_connection* conn, struct restsrv_session* pSession, int format, void* cbdata); void restsrv_doSendEvent(struct mg_connection* conn, struct restsrv_session* pSession, int format, vscpEvent* pEvent, void* cbdata); void restsrv_doReceiveEvent(struct mg_connection* conn, struct restsrv_session* pSession, int format, size_t count, void* cbdata); void restsrv_doReceiveEvent(struct mg_connection* conn, struct restsrv_session* pSession, int format, size_t count, void* cbdata); void restsrv_doSetFilter(struct mg_connection* conn, struct restsrv_session* pSession, int format, vscpEventFilter& vscpfilter, void* cbdata); void restsrv_doClearQueue(struct mg_connection* conn, struct restsrv_session* pSession, int format, void* cbdata); void restsrv_doListVariable(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strRegEx, bool bShort, void* cbdata); void restsrv_doListVariable(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strRegEx, bool bShort, void* cbdata); void restsrv_doReadVariable(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strVariableName, void* cbdata); void restsrv_doWriteVariable(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strVariableName, std::string& strValue, void* cbdata); void restsrv_doCreateVariable(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strVariable, std::string& strType, std::string& strValue, std::string& strPersistent, std::string& strAccessRight, std::string& strNote, void* cbdata); void restsrv_doDeleteVariable(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strVariable, void* cbdata); void restsrv_doWriteMeasurement(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strDateTime, std::string& strGuid, std::string& strLevel, std::string& strType, std::string& strValue, std::string& strUnit, std::string& strSensorIdx, std::string& strZone, std::string& strSubZone, std::string& strEventFormat, void* cbdata); void websrc_renderTableData(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strName, struct _vscpFileRecord* pRecords, long nfetchedRecords, void* cbdata); void restsrv_doFetchMDF(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strURL, void* cbdata); void websrc_renderTableData(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strName, struct _vscpFileRecord* pRecords, long nfetchedRecords, void* cbdata); void restsrv_doGetTableData(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strName, std::string& strFrom, std::string& strTo, void* cbdata); const char* rest_errors[][REST_FORMAT_COUNT + 1] = { { REST_PLAIN_ERROR_SUCCESS, REST_CSV_ERROR_SUCCESS, REST_XML_ERROR_SUCCESS, REST_JSON_ERROR_SUCCESS, REST_JSONP_ERROR_SUCCESS }, { REST_PLAIN_ERROR_GENERAL_FAILURE, REST_CSV_ERROR_GENERAL_FAILURE, REST_XML_ERROR_GENERAL_FAILURE, REST_JSON_ERROR_GENERAL_FAILURE, REST_JSONP_ERROR_GENERAL_FAILURE }, { REST_PLAIN_ERROR_INVALID_SESSION, REST_CSV_ERROR_INVALID_SESSION, REST_XML_ERROR_INVALID_SESSION, REST_JSON_ERROR_INVALID_SESSION, REST_JSONP_ERROR_INVALID_SESSION }, { REST_PLAIN_ERROR_UNSUPPORTED_FORMAT, REST_CSV_ERROR_UNSUPPORTED_FORMAT, REST_XML_ERROR_UNSUPPORTED_FORMAT, REST_JSON_ERROR_UNSUPPORTED_FORMAT, REST_JSONP_ERROR_UNSUPPORTED_FORMAT }, { REST_PLAIN_ERROR_COULD_NOT_OPEN_SESSION, REST_CSV_ERROR_COULD_NOT_OPEN_SESSION, REST_XML_ERROR_COULD_NOT_OPEN_SESSION, REST_JSON_ERROR_COULD_NOT_OPEN_SESSION, REST_JSONP_ERROR_COULD_NOT_OPEN_SESSION }, { REST_PLAIN_ERROR_MISSING_DATA, REST_CSV_ERROR_MISSING_DATA, REST_XML_ERROR_MISSING_DATA, REST_JSON_ERROR_MISSING_DATA, REST_JSONP_ERROR_MISSING_DATA }, { REST_PLAIN_ERROR_INPUT_QUEUE_EMPTY, REST_CSV_ERROR_INPUT_QUEUE_EMPTY, REST_XML_ERROR_INPUT_QUEUE_EMPTY, REST_JSON_ERROR_INPUT_QUEUE_EMPTY, REST_JSONP_ERROR_INPUT_QUEUE_EMPTY }, { REST_PLAIN_ERROR_VARIABLE_NOT_FOUND, REST_CSV_ERROR_VARIABLE_NOT_FOUND, REST_XML_ERROR_VARIABLE_NOT_FOUND, REST_JSON_ERROR_VARIABLE_NOT_FOUND, REST_JSONP_ERROR_VARIABLE_NOT_FOUND }, { REST_PLAIN_ERROR_VARIABLE_NOT_CREATED, REST_CSV_ERROR_VARIABLE_NOT_CREATED, REST_XML_ERROR_VARIABLE_NOT_CREATED, REST_JSON_ERROR_VARIABLE_NOT_CREATED, REST_JSONP_ERROR_VARIABLE_NOT_CREATED }, { REST_PLAIN_ERROR_VARIABLE_FAIL_UPDATE, REST_CSV_ERROR_VARIABLE_FAIL_UPDATE, REST_XML_ERROR_VARIABLE_FAIL_UPDATE, REST_JSON_ERROR_VARIABLE_FAIL_UPDATE, REST_JSONP_ERROR_VARIABLE_FAIL_UPDATE }, { REST_PLAIN_ERROR_NO_ROOM, REST_CSV_ERROR_NO_ROOM, REST_XML_ERROR_NO_ROOM, REST_JSON_ERROR_NO_ROOM, REST_JSONP_ERROR_NO_ROOM }, { REST_PLAIN_ERROR_TABLE_NOT_FOUND, REST_CSV_ERROR_TABLE_NOT_FOUND, REST_XML_ERROR_TABLE_NOT_FOUND, REST_JSON_ERROR_TABLE_NOT_FOUND, REST_JSONP_ERROR_TABLE_NOT_FOUND, }, { REST_PLAIN_ERROR_TABLE_NO_DATA, REST_CSV_ERROR_TABLE_NO_DATA, REST_XML_ERROR_TABLE_NO_DATA, REST_JSON_ERROR_TABLE_NO_DATA, REST_JSONP_ERROR_TABLE_NO_DATA }, { REST_PLAIN_ERROR_TABLE_RANGE, REST_CSV_ERROR_TABLE_RANGE, REST_XML_ERROR_TABLE_RANGE, REST_JSON_ERROR_TABLE_RANGE, REST_JSONP_ERROR_TABLE_RANGE }, { REST_PLAIN_ERROR_INVALID_USER, REST_CSV_ERROR_INVALID_USER, REST_XML_ERROR_INVALID_USER, REST_JSON_ERROR_INVALID_USER, REST_JSONP_ERROR_INVALID_USER }, { REST_PLAIN_ERROR_INVALID_ORIGIN, REST_CSV_ERROR_INVALID_ORIGIN, REST_XML_ERROR_INVALID_ORIGIN, REST_JSON_ERROR_INVALID_ORIGIN, REST_JSONP_ERROR_INVALID_ORIGIN }, { REST_PLAIN_ERROR_INVALID_PASSWORD, REST_CSV_ERROR_INVALID_PASSWORD, REST_XML_ERROR_INVALID_PASSWORD, REST_JSON_ERROR_INVALID_PASSWORD, REST_JSONP_ERROR_INVALID_PASSWORD }, { REST_PLAIN_ERROR_MEMORY, REST_CSV_ERROR_MEMORY, REST_XML_ERROR_MEMORY, REST_JSON_ERROR_MEMORY, REST_JSONP_ERROR_MEMORY }, { REST_PLAIN_ERROR_VARIABLE_NOT_DELETE, REST_CSV_ERROR_VARIABLE_NOT_DELETE, REST_XML_ERROR_VARIABLE_NOT_DELETE, REST_JSON_ERROR_VARIABLE_NOT_DELETE, REST_JSONP_ERROR_VARIABLE_NOT_DELETE }, }; //----------------------------------------------------------------------------- // REST //----------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////// // restsrv_error // void restsrv_error(struct mg_connection* conn, struct restsrv_session* pSession, int format, int errorcode, void* cbdata) { int returncode = 200; CWebObj* pObj = (CWebObj*)cbdata; if (NULL == pObj) { return; } spdlog::get("logger")->debug("[REST] error format={} errorcode={}", format, errorcode); if (REST_FORMAT_PLAIN == format) { websrv_sendheader(conn, returncode, REST_MIME_TYPE_PLAIN); mg_write(conn, rest_errors[errorcode][REST_FORMAT_PLAIN], strlen(rest_errors[errorcode][REST_FORMAT_PLAIN])); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_CSV == format) { websrv_sendheader(conn, returncode, REST_MIME_TYPE_CSV); mg_write(conn, rest_errors[errorcode][REST_FORMAT_CSV], strlen(rest_errors[errorcode][REST_FORMAT_CSV])); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_XML == format) { websrv_sendheader(conn, returncode, REST_MIME_TYPE_XML); mg_write(conn, XML_HEADER, strlen(XML_HEADER)); mg_write(conn, rest_errors[errorcode][REST_FORMAT_XML], strlen(rest_errors[errorcode][REST_FORMAT_XML])); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_JSON == format) { websrv_sendheader(conn, returncode, REST_MIME_TYPE_JSON); mg_write(conn, rest_errors[errorcode][REST_FORMAT_JSON], strlen(rest_errors[errorcode][REST_FORMAT_JSON])); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_JSONP == format) { websrv_sendheader(conn, returncode, REST_MIME_TYPE_JSONP); mg_write(conn, rest_errors[errorcode][REST_FORMAT_JSONP], strlen(rest_errors[errorcode][REST_FORMAT_JSONP])); mg_write(conn, "", 0); // Terminator return; } else { websrv_sendheader(conn, returncode, REST_MIME_TYPE_PLAIN); mg_write(conn, REST_PLAIN_ERROR_UNSUPPORTED_FORMAT, strlen(REST_PLAIN_ERROR_UNSUPPORTED_FORMAT)); mg_write(conn, "", 0); // Terminator return; } } /////////////////////////////////////////////////////////////////////////////// // restsrv_sendHeader // void restsrv_sendHeader(struct mg_connection* conn, int format, int returncode) { if (REST_FORMAT_PLAIN == format) { websrv_sendheader(conn, returncode, REST_MIME_TYPE_PLAIN); } else if (REST_FORMAT_CSV == format) { websrv_sendheader(conn, returncode, REST_MIME_TYPE_CSV); } else if (REST_FORMAT_XML == format) { websrv_sendheader(conn, returncode, REST_MIME_TYPE_XML); } else if (REST_FORMAT_JSON == format) { websrv_sendheader(conn, returncode, REST_MIME_TYPE_JSON); } else if (REST_FORMAT_JSONP == format) { websrv_sendheader(conn, returncode, REST_MIME_TYPE_JSONP); } } /////////////////////////////////////////////////////////////////////////////// // restsrv_get_session // struct restsrv_session* restsrv_get_session(struct mg_connection* conn, std::string& sid, void* cbdata) { const struct mg_request_info* reqinfo; CWebObj* pObj = (CWebObj*)cbdata; if (NULL == pObj) { return NULL; } // Check pointers if (!conn || !(reqinfo = mg_get_request_info(conn))) { spdlog::get("logger")->error("[REST] get_session, Pointer error."); return NULL; } if (0 == sid.length()) { spdlog::get("logger")->error("[REST] get_session, sid length is zero."); return NULL; } // find existing session pthread_mutex_lock(&pObj->m_mutex_restSession); std::list<struct restsrv_session*>::iterator iter; for (iter = pObj->m_rest_sessions.begin(); iter != pObj->m_rest_sessions.end(); ++iter) { struct restsrv_session* pSession = *iter; if (0 == strcmp((const char*)sid.c_str(), pSession->m_sid)) { pSession->m_lastActiveTime = time(NULL); pthread_mutex_unlock(&pObj->m_mutex_restSession); spdlog::get("logger")->debug("[REST] get_session, Session found."); return pSession; } } pthread_mutex_unlock(&pObj->m_mutex_restSession); spdlog::get("logger")->error("[REST] get_session, Session not found."); return NULL; } /////////////////////////////////////////////////////////////////////////////// // restsrv_add_session // restsrv_session* restsrv_add_session(struct mg_connection* conn, CUserItem* pUserItem, void* cbdata) { std::string user; struct restsrv_session* pSession; const struct mg_request_info* reqinfo; // Check pointers if (!conn || !(reqinfo = mg_get_request_info(conn))) { spdlog::get("logger")->error("[REST] add_session, Pointer error."); return 0; } CWebObj* pObj = (CWebObj*)cbdata; if (NULL == pObj) { return NULL; } // !!!!! This blokc is not used at the moment !!! // Parse "Authorization:" header, fail fast on parse error if (0) { const char* pheader = mg_get_header(conn, "Authorization"); if (NULL == pheader) { spdlog::get("logger")->error( "[REST] add_session, No 'Authorization' header."); return NULL; } std::map<std::string, std::string> hdrmap; std::string header = std::string(pheader); websrv_parseHeader(hdrmap, header); // Get username if (!websrv_getHeaderElement(hdrmap, "username", user)) { spdlog::get("logger")->error( "[REST] add_session, no 'username' in header."); return NULL; } } // Create fresh session pSession = new struct restsrv_session; if (NULL == pSession) { spdlog::get("logger")->error( "[REST] add_session, unable to create session object."); return NULL; } memset(pSession, 0, sizeof(websrv_session)); // Generate a random session ID unsigned char iv[16]; char hexiv[33]; getRandomIV(iv, 16); // Generate 16 random bytes memset(hexiv, 0, sizeof(hexiv)); vscp_byteArray2HexStr(hexiv, iv, 16); memset(pSession->m_sid, 0, sizeof(pSession->m_sid)); memcpy(pSession->m_sid, hexiv, 32); pSession->m_lastActiveTime = time(NULL); pSession->m_pClientItem = new CClientItem(); // Create client if (NULL == pSession->m_pClientItem) { spdlog::get("logger")->error( "[REST] New session: Unable to create client object."); delete pSession; return NULL; } // Set client data pSession->m_pClientItem->bAuthenticated = true; // Authenticated pSession->m_pClientItem->m_pUserItem = pUserItem; vscp_clearVSCPFilter(&pSession->m_pClientItem->m_filter); // Clear filter pSession->m_pClientItem->m_bOpen = false; // Start out closed pSession->m_pClientItem->m_dtutc = vscpdatetime::Now(); pSession->m_pClientItem->m_type = CLIENT_ITEM_INTERFACE_TYPE_CLIENT_WEBSOCKET; pSession->m_pClientItem->m_strDeviceName = ("Internal REST server client."); // Add the client to the Client List pthread_mutex_lock(&pObj->m_clientList.m_mutexItemList); if (!pObj->m_clientList.addClient(pSession->m_pClientItem)) { // Failed to add client delete pSession->m_pClientItem; pSession->m_pClientItem = NULL; pthread_mutex_unlock(&pObj->m_clientList.m_mutexItemList); spdlog::get("logger")->error( "[REST] new session, Failed to add client. Terminating thread."); return NULL; } pthread_mutex_unlock(&pObj->m_clientList.m_mutexItemList); // Add to linked list pthread_mutex_lock(&pObj->m_mutex_restSession); pObj->m_rest_sessions.push_back(pSession); pthread_mutex_unlock(&pObj->m_mutex_restSession); return pSession; } /////////////////////////////////////////////////////////////////////////////// // websrv_expire_sessions // void restsrv_expire_sessions(struct mg_connection* conn, void* cbdata) { time_t now; CWebObj* pObj = (CWebObj*)cbdata; if (NULL == pObj) { return; } now = time(NULL); pthread_mutex_lock(&pObj->m_mutex_restSession); std::list<struct restsrv_session*>::iterator it; try { for (it = pObj->m_rest_sessions.begin(); it != pObj->m_rest_sessions.end(); /* inline */) { struct restsrv_session* pSession = *it; if ((now - pSession->m_lastActiveTime) > (60 * 60)) { it = pObj->m_rest_sessions.erase(it); spdlog::get("logger")->debug("[REST] Session expired"); delete pSession; } else { ++it; } } } catch (...) { spdlog::get("logger")->error("[REST] Exception expire_session"); } pthread_mutex_unlock(&pObj->m_mutex_restSession); } /////////////////////////////////////////////////////////////////////////////// // websrv_restapi // int websrv_restapi(struct mg_connection* conn, void* cbdata) { char bufBody[32000]; // Buffer for body (POST) data int len_post_data; const char* pParams = NULL; // Pointer to query data or POST data int lenParam = 0; char buf[2048]; char date[64]; std::string str; time_t curtime = time(NULL); long format = REST_FORMAT_PLAIN; std::map<std::string, std::string> keypairs; struct mg_context* ctx; const struct mg_request_info* reqinfo; struct restsrv_session* pSession = NULL; CUserItem* pUserItem = NULL; CWebObj* pObj = (CWebObj*)cbdata; if (NULL == pObj) { return WEB_ERROR; } memset(bufBody, 0, sizeof(bufBody)); // Check pointer if (!conn || !(ctx = mg_get_context(conn)) || !(reqinfo = mg_get_request_info(conn))) { spdlog::get("logger")->error("[REST] - invalid pointers"); return WEB_ERROR; } // Get method char method[33]; memset(method, 0, sizeof(method)); strncpy(method, reqinfo->request_method, std::min((int)strlen(reqinfo->request_method), 32)); // Make string with GMT time vscp_getTimeString(date, sizeof(date), &curtime); // Set defaults keypairs["FORMAT"] = "plain"; keypairs["OP"] = "open"; if (NULL != strstr(method, "POST")) { const char* pHeader; // read POST data len_post_data = mg_read(conn, bufBody, sizeof(bufBody)); // user if (NULL != (pHeader = mg_get_header(conn, "vscpuser"))) { memset(buf, 0, sizeof(buf)); strncpy(buf, pHeader, std::min(sizeof(buf) - 1, strlen(pHeader))); keypairs["VSCPUSER"] = std::string(buf); } // password if (NULL != (pHeader = mg_get_header(conn, "vscpsecret"))) { memset(buf, 0, sizeof(buf)); strncpy(buf, pHeader, std::min(sizeof(buf) - 1, strlen(pHeader))); keypairs["VSCPSECRET"] = std::string(buf); } // session if (NULL != (pHeader = mg_get_header(conn, "vscpsession"))) { memset(buf, 0, sizeof(buf)); strncpy(buf, pHeader, std::min(sizeof(buf) - 1, strlen(pHeader))); keypairs["VSCPSESSION"] = std::string(buf); } pParams = bufBody; // Parameters is in the body lenParam = len_post_data; } else { // get parameters for get if (NULL != reqinfo->query_string) { if (0 < mg_get_var(reqinfo->query_string, strlen(reqinfo->query_string), "vscpuser", buf, sizeof(buf))) { keypairs["VSCPUSER"] = std::string(buf); } if (0 < mg_get_var(reqinfo->query_string, strlen(reqinfo->query_string), "vscpsecret", buf, sizeof(buf))) { keypairs["VSCPSECRET"] = std::string(buf); } if (0 < mg_get_var(reqinfo->query_string, strlen(reqinfo->query_string), "vscpsession", buf, sizeof(buf))) { keypairs["VSCPSESSION"] = std::string(buf); } pParams = reqinfo->query_string; // Parameters is in query string lenParam = strlen(reqinfo->query_string); } } // format if (0 < mg_get_var(pParams, lenParam, "format", buf, sizeof(buf))) { keypairs["FORMAT"] = vscp_upper(std::string(buf)); } // op if (0 < mg_get_var(pParams, lenParam, "op", buf, sizeof(buf))) { keypairs["OP"] = vscp_makeUpper_copy(std::string(buf)); } // vscpevent if (0 < mg_get_var(pParams, lenParam, "vscpevent", buf, sizeof(buf))) { keypairs["VSCPEVENT"] = std::string(buf); } // count if (0 < mg_get_var(pParams, lenParam, "count", buf, sizeof(buf))) { keypairs["COUNT"] = std::string(buf); } // vscpfilter if (0 < mg_get_var(pParams, lenParam, "vscpfilter", buf, sizeof(buf))) { keypairs["VSCPFILTER"] = std::string(buf); } // vscpmask if (0 < mg_get_var(pParams, lenParam, "vscpmask", buf, sizeof(buf))) { keypairs["VSCPMASK"] = std::string(buf); } // variable if (0 < mg_get_var(pParams, lenParam, "variable", buf, sizeof(buf))) { keypairs["VARIABLE"] = std::string(buf); } // value if (0 < mg_get_var(pParams, lenParam, "value", buf, sizeof(buf))) { keypairs["VALUE"] = std::string(buf); } // type (number or string) if (0 < mg_get_var(pParams, lenParam, "type", buf, sizeof(buf))) { keypairs["TYPE"] = std::string(buf); } // persistent if (0 < mg_get_var(pParams, lenParam, "persistent", buf, sizeof(buf))) { keypairs["PERSISTENT"] = std::string(buf); } // access-right (hex or decimal) if (0 < mg_get_var(pParams, lenParam, "accessright", buf, sizeof(buf))) { keypairs["ACCESSRIGHT"] = std::string(buf); } // note if (0 < mg_get_var(pParams, lenParam, "note", buf, sizeof(buf))) { keypairs["NOTE"] = std::string(buf); } // listlong if (0 < mg_get_var(pParams, lenParam, "listlong", buf, sizeof(buf))) { keypairs["LISTLONG"] = std::string(buf); } // regex if (0 < mg_get_var(pParams, lenParam, "regex", buf, sizeof(buf))) { keypairs[("REGEX")] = std::string(buf); } // unit if (0 < mg_get_var(pParams, lenParam, "unit", buf, sizeof(buf))) { keypairs["UNIT"] = std::string(buf); } // sensoridx if (0 < mg_get_var(pParams, lenParam, "sensoridx", buf, sizeof(buf))) { keypairs["SENSORINDEX"] = std::string(buf); } // level ( VSCP level 1 or 2 ) if (0 < mg_get_var(pParams, lenParam, "level", buf, sizeof(buf))) { keypairs["LEVEL"] = std::string(buf); } // zone if (0 < mg_get_var(pParams, lenParam, "zone", buf, sizeof(buf))) { keypairs["ZONE"] = std::string(buf); } // subzone if (0 < mg_get_var(pParams, lenParam, "subzone", buf, sizeof(buf))) { keypairs["SUBZONE"] = std::string(buf); } // guid if (0 < mg_get_var(pParams, lenParam, "guid", buf, sizeof(buf))) { keypairs["GUID"] = std::string(buf); } // name if (0 < mg_get_var(pParams, lenParam, "name", buf, sizeof(buf))) { keypairs["NAME"] = std::string(buf); } // from if (0 < mg_get_var(pParams, lenParam, "from", buf, sizeof(buf))) { keypairs["FROM"] = std::string(buf); } // to if (0 < mg_get_var(pParams, lenParam, "to", buf, sizeof(buf))) { keypairs["TO"] = std::string(buf); } // url if (0 < mg_get_var(pParams, lenParam, "url", buf, sizeof(buf))) { keypairs["URL"] = std::string(buf); } // eventformat if (0 < mg_get_var(pParams, lenParam, "eventformat", buf, sizeof(buf))) { keypairs["EVENTFORMAT"] = std::string(buf); } // datetime if (0 < mg_get_var(pParams, lenParam, "datetime", buf, sizeof(buf))) { keypairs["DATETIME"] = std::string(buf); } // Get format if ("PLAIN" == keypairs["FORMAT"]) { format = REST_FORMAT_PLAIN; } else if ("CSV" == keypairs["FORMAT"]) { format = REST_FORMAT_CSV; } else if ("XML" == keypairs["FORMAT"]) { format = REST_FORMAT_XML; } else if ("JSON" == keypairs["FORMAT"]) { format = REST_FORMAT_JSON; } else if ("JSONP" == keypairs["FORMAT"]) { format = REST_FORMAT_JSONP; } else { websrv_sendheader(conn, 400, "text/plain"); mg_write(conn, REST_PLAIN_ERROR_UNSUPPORTED_FORMAT, strlen(REST_PLAIN_ERROR_UNSUPPORTED_FORMAT)); mg_write(conn, "", 0); // Terminator spdlog::get("logger")->debug("[REST] - invalid format "); return WEB_ERROR; } // If we have a session key we try to get the session if (("") != keypairs["VSCPSESSION"]) { // Get session pSession = restsrv_get_session(conn, keypairs["VSCPSESSION"], cbdata); } if (NULL == pSession) { // Get user pUserItem = pObj->m_userList.getUser(keypairs["VSCPUSER"]); // Check if user is valid if (NULL == pUserItem) { std::string strErr = vscp_str_format("[REST Client] Host [%s] Invalid user [%s]", std::string(reqinfo->remote_addr).c_str(), (const char*)keypairs[("VSCPUSER")].c_str()); spdlog::get("logger")->error("[REST] {}", strErr); restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_USER, cbdata); return WEB_ERROR; } // Check if remote ip is valid bool bValidHost; pthread_mutex_lock(&pObj->m_mutex_UserList); bValidHost = (1 == pUserItem->isAllowedToConnect(inet_addr(reqinfo->remote_addr))); pthread_mutex_unlock(&pObj->m_mutex_UserList); if (!bValidHost) { std::string strErr = vscp_str_format( "[REST Client] Host [%s] NOT allowed to connect. User [%s]", reqinfo->remote_addr, (const char*)keypairs["VSCPUSER"].c_str()); spdlog::get("logger")->error("[REST] {}", strErr); restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_ORIGIN, cbdata); return WEB_ERROR; } // Is this an authorised user? pthread_mutex_lock(&pObj->m_mutex_UserList); CUserItem* pValidUser = pObj->m_userList.validateUser(keypairs["VSCPUSER"], keypairs["VSCPSECRET"]); pthread_mutex_unlock(&pObj->m_mutex_UserList); if (NULL == pValidUser) { std::string strErr = vscp_str_format( "[REST Client] User [%s] NOT allowed to connect. Client [%s]", (const char*)keypairs["VSCPUSER"].c_str(), reqinfo->remote_addr); spdlog::get("logger")->error("[REST] {}", strErr); restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_PASSWORD, cbdata); return WEB_ERROR; } if (NULL == (pSession = restsrv_add_session(conn, pUserItem, cbdata))) { // Hm,,, did not work out well... std::string strErr = vscp_str_format( ("[REST Client] Unable to create new session for user [%s]\n"), (const char*)keypairs[("VSCPUSER")].c_str()); spdlog::get("logger")->error("[REST] {}", strErr); restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_ORIGIN, cbdata); return WEB_ERROR; } // Only the "open" command is allowed here if (("1" == keypairs["OP"]) || ("OPEN" == keypairs["OP"])) { spdlog::get("logger")->debug("[REST] - doOpen format={}", format); restsrv_doOpen(conn, pSession, format, cbdata); return WEB_OK; } // !!! No meaning to go further - end it here !!! std::string strErr = vscp_str_format( "[REST Client] Unable to create new session for user [%s]", (const char*)keypairs[("VSCPUSER")].c_str()); spdlog::get("logger")->error("[REST] {}", strErr); restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_ORIGIN, cbdata); return WEB_ERROR; } // Check if remote ip is valid bool bValidHost; pthread_mutex_lock(&pObj->m_mutex_UserList); bValidHost = (1 == pSession->m_pClientItem->m_pUserItem->isAllowedToConnect( inet_addr(reqinfo->remote_addr))); pthread_mutex_unlock(&pObj->m_mutex_UserList); if (!bValidHost) { std::string strErr = vscp_str_format( ("[REST Client] Host [%s] NOT allowed to connect. User [%s]\n"), std::string(reqinfo->remote_addr).c_str(), (const char*)keypairs[("VSCPUSER")].c_str()); spdlog::get("logger")->error("[REST] {}", strErr); restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_ORIGIN, cbdata); return WEB_ERROR; } // ------------------------------------------------------------------------ // * * * User is validated * * * // ------------------------------------------------------------------------ std::string strErr = vscp_str_format( ("[REST Client] User [%s] Host [%s] allowed to connect. \n"), (const char*)keypairs[("VSCPUSER")].c_str(), std::string(reqinfo->remote_addr).c_str()); spdlog::get("logger")->debug("[REST] {}", strErr); // ************************************************************* // * * * * * * * * Status (hold session open) * * * * * * * * // ************************************************************* if ((("0") == keypairs[("OP")]) || (("STATUS") == keypairs[("OP")])) { try { restsrv_doStatus(conn, pSession, format, cbdata); } catch (...) { spdlog::get("logger")->error( "[REST] Exception occurred doing restsrv_doStatus"); } } // ******************************************** // * * * * * * * * open session * * * * * * * * // ******************************************** else if ((("1") == keypairs[("OP")]) || (("OPEN") == keypairs[("OP")])) { try { restsrv_doOpen(conn, pSession, format, cbdata); } catch (...) { spdlog::get("logger")->error( "[REST] Exception occurred doing restsrv_doOpen"); } } // ********************************************** // * * * * * * * * close session * * * * * * * * // ********************************************** else if ((("2") == keypairs[("OP")]) || (("CLOSE") == keypairs[("OP")])) { try { restsrv_doClose(conn, pSession, format, cbdata); } catch (...) { spdlog::get("logger")->error( "[REST] Exception occurred doing restsrv_doClose"); } } // ******************************************** // * * * * * * * * Send event * * * * * * * * // ******************************************** else if ((("3") == keypairs[("OP")]) || (("SENDEVENT") == keypairs[("OP")])) { vscpEvent vscpevent; if (("") != keypairs[("VSCPEVENT")]) { try { vscp_convertStringToEvent(&vscpevent, keypairs[("VSCPEVENT")]); restsrv_doSendEvent(conn, pSession, format, &vscpevent, cbdata); } catch (...) { spdlog::get("logger")->error( "[REST] Exception occurred doing restsrv_doSendEvent"); } } else { // Parameter missing - No Event restsrv_error(conn, pSession, format, REST_ERROR_CODE_MISSING_DATA, cbdata); } } // ******************************************** // * * * * * * * * Read event * * * * * * * * // ******************************************** else if ((("4") == keypairs[("OP")]) || (("READEVENT") == keypairs[("OP")])) { long count = 1; if (("") != keypairs[("COUNT")]) { count = std::stoul(keypairs["COUNT"]); } try { restsrv_doReceiveEvent(conn, pSession, format, count, cbdata); } catch (...) { spdlog::get("logger")->error( "[REST] Exception occurred doing restsrv_doReceiveEvent"); } } // ************************************************** // * * * * * * * * Set filter * * * * * * * * // ************************************************** else if ((("5") == keypairs[("OP")]) || (("SETFILTER") == keypairs[("OP")])) { vscpEventFilter vscpfilter; vscp_clearVSCPFilter(&vscpfilter); if (("") != keypairs[("VSCPFILTER")]) { vscp_readFilterFromString(&vscpfilter, keypairs[("VSCPFILTER")]); } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_MISSING_DATA, cbdata); } if (("") != keypairs[("VSCPMASK")]) { vscp_readMaskFromString(&vscpfilter, keypairs[("VSCPMASK")]); } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_MISSING_DATA, cbdata); } try { restsrv_doSetFilter(conn, pSession, format, vscpfilter, cbdata); } catch (...) { spdlog::get("logger")->error( "[REST] Exception occurred doing restsrv_doSetFilter"); } } // **************************************************** // * * * * * * * * clear input queue * * * * * * * * // **************************************************** else if ((("6") == keypairs[("OP")]) || (("CLEARQUEUE") == keypairs[("OP")])) { try { restsrv_doClearQueue(conn, pSession, format, cbdata); } catch (...) { spdlog::get("logger")->error( "[REST] Exception occurred doing restsrv_doClearQueue"); } } // ************************************************* // * * * * * * * * Send measurement * * * * * * * * // ************************************************* // value,unit=0,sensor=0 // else if ((("10") == keypairs[("OP")]) || (("MEASUREMENT") == keypairs[("OP")])) { if ((("") != keypairs[("VALUE")]) && (("") != keypairs[("TYPE")])) { try { restsrv_doWriteMeasurement(conn, pSession, format, keypairs[("DATETIME")], keypairs[("GUID")], keypairs[("LEVEL")], keypairs[("TYPE")], keypairs[("VALUE")], keypairs[("UNIT")], keypairs[("SENSORIDX")], keypairs[("ZONE")], keypairs[("SUBZONE")], keypairs[("SUBZONE")], cbdata); } catch (...) { spdlog::get("logger")->error( "[REST] Exception occurred doing restsrv_doWriteMeasurement"); } } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_MISSING_DATA, cbdata); } } // ******************************************* // * * * * * * * * Fetch MDF * * * * * * * * // ******************************************* else if ((("12") == keypairs[("OP")]) || (("MDF") == keypairs[("OP")])) { if (("") != keypairs[("URL")]) { try { restsrv_doFetchMDF(conn, pSession, format, keypairs[("URL")], cbdata); } catch (...) { spdlog::get("logger")->error( "[REST] Exception occurred doing restsrv_doFetchMDF"); } } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_MISSING_DATA, cbdata); } } // Unrecognised operation else { spdlog::get("logger")->error("[REST] restapi - Missing data."); restsrv_error(conn, pSession, format, REST_ERROR_CODE_MISSING_DATA, cbdata); } return WEB_OK; } /////////////////////////////////////////////////////////////////////////////// // restsrv_doOpen // void restsrv_doOpen(struct mg_connection* conn, struct restsrv_session* pSession, int format, void* cbdata) { char wrkbuf[256]; CWebObj* pObj = (CWebObj*)cbdata; if (NULL == pObj) { return; } if (NULL != pSession) { // OK session // Note activity pSession->m_lastActiveTime = time(NULL); // Mark interface as open pSession->m_pClientItem->m_bOpen = true; if (REST_FORMAT_PLAIN == format) { websrv_sendSetCookieHeader(conn, 200, REST_MIME_TYPE_PLAIN, pSession->m_sid); #ifdef WIN32 int n = _snprintf(wrkbuf, sizeof(wrkbuf), "1 1 Success vscpsession=%s nEvents=%zd", pSession->sid, pSession->pClientItem->m_clientInputQueue.size()); #else int n = snprintf(wrkbuf, sizeof(wrkbuf), "1 1 Success vscpsession=%s nEvents=%zu", pSession->m_sid, pSession->m_pClientItem->m_clientInputQueue.size()); #endif mg_write(conn, wrkbuf, n); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_CSV == format) { websrv_sendSetCookieHeader(conn, 200, REST_MIME_TYPE_CSV, pSession->m_sid); #ifdef WIN32 _snprintf(wrkbuf, sizeof(wrkbuf), "success-code,error-code,message,description," "vscpsession,nEvents\r\n1,1,Success,Success. 1,1" ",Success,Success,%s,%zd", pSession->sid, pSession->pClientItem->m_clientInputQueue.size()); #else snprintf(wrkbuf, sizeof(wrkbuf), "success-code,error-code,message,description," "vscpsession,nEvents\r\n1,1,Success,Success. 1,1," "Success,Success,%s,%zu", pSession->m_sid, pSession->m_pClientItem->m_clientInputQueue.size()); #endif mg_write(conn, wrkbuf, strlen(wrkbuf)); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_XML == format) { websrv_sendSetCookieHeader(conn, 200, REST_MIME_TYPE_XML, pSession->m_sid); #ifdef WIN32 nprintf(wrkbuf, sizeof(wrkbuf), "<vscp-rest success = \"true\" code = " "\"1\" message = \"Success.\" description = " "\"Success.\" ><vscpsession>%s</vscpsession>" "<nEvents>%zd</nEvents></vscp-rest>", pSession->sid, pSession->pClientItem->m_clientInputQueue.size()); #else snprintf(wrkbuf, sizeof(wrkbuf), "<vscp-rest success = \"true\" code = \"1\" " "message = \"Success.\" description = \"Success.\" " "><vscpsession>%s</vscpsession><nEvents>%zu" "</nEvents></vscp-rest>", pSession->m_sid, pSession->m_pClientItem->m_clientInputQueue.size()); #endif mg_write(conn, wrkbuf, strlen(wrkbuf)); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_JSON == format) { json output; websrv_sendSetCookieHeader(conn, 200, REST_MIME_TYPE_JSON, pSession->m_sid); output["success"] = true; output["code"] = 1; output["message"] = "success"; output["description"] = "Success"; output["vscpsession"] = pSession->m_sid; output["nEvents"] = pSession->m_pClientItem->m_clientInputQueue.size(); std::string s = output.dump(); mg_write(conn, s.c_str(), s.length()); return; } else if (REST_FORMAT_JSONP == format) { json output; websrv_sendSetCookieHeader(conn, 200, REST_MIME_TYPE_JSONP, pSession->m_sid); // Write JSONP start block mg_write(conn, REST_JSONP_START, strlen(REST_JSONP_START)); output["success"] = true; output["code"] = 1; output["message"] = "success"; output["description"] = "Success"; output["vscpsession"] = pSession->m_sid; output["nEvents"] = pSession->m_pClientItem->m_clientInputQueue.size(); std::string s = output.dump(); mg_write(conn, s.c_str(), s.length()); // Write JSONP end block mg_write(conn, REST_JSONP_END, strlen(REST_JSONP_END)); return; } else { websrv_sendheader(conn, 400, REST_MIME_TYPE_PLAIN); mg_write(conn, REST_PLAIN_ERROR_UNSUPPORTED_FORMAT, strlen(REST_PLAIN_ERROR_UNSUPPORTED_FORMAT)); return; } } else { // Unable to create session restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION, cbdata); } return; } /////////////////////////////////////////////////////////////////////////////// // restsrv_doClose // void restsrv_doClose(struct mg_connection* conn, struct restsrv_session* pSession, int format, void* cbdata) { char wrkbuf[256]; CWebObj* pObj = (CWebObj*)cbdata; if (NULL == pObj) { return; } if (NULL != pSession) { char sid[32 + 1]; memset(sid, 0, sizeof(sid)); memcpy(sid, pSession->m_sid, sizeof(sid)); // We should close the session // Mark as closed pSession->m_pClientItem->m_bOpen = false; // Note activity pSession->m_lastActiveTime = time(NULL); if (REST_FORMAT_PLAIN == format) { websrv_sendheader(conn, 200, REST_MIME_TYPE_PLAIN); mg_write(conn, REST_PLAIN_ERROR_SUCCESS, strlen(REST_PLAIN_ERROR_SUCCESS)); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_CSV == format) { websrv_sendheader(conn, 200, REST_MIME_TYPE_CSV); #ifdef WIN32 _snprintf(wrkbuf, sizeof(wrkbuf), REST_CSV_ERROR_SUCCESS); #else snprintf(wrkbuf, sizeof(wrkbuf), REST_CSV_ERROR_SUCCESS); #endif mg_write(conn, wrkbuf, strlen(wrkbuf)); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_XML == format) { websrv_sendheader(conn, 200, REST_MIME_TYPE_XML); #ifdef WIN32 _snprintf(wrkbuf, sizeof(wrkbuf), REST_XML_ERROR_SUCCESS); #else snprintf(wrkbuf, sizeof(wrkbuf), REST_XML_ERROR_SUCCESS); #endif mg_write(conn, wrkbuf, strlen(wrkbuf)); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_JSON == format) { websrv_sendheader(conn, 200, REST_MIME_TYPE_JSON); #ifdef WIN32 _snprintf(wrkbuf, sizeof(wrkbuf), REST_JSON_ERROR_SUCCESS); #else snprintf(wrkbuf, sizeof(wrkbuf), REST_JSON_ERROR_SUCCESS); #endif mg_write(conn, wrkbuf, strlen(wrkbuf)); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_JSONP == format) { websrv_sendheader(conn, 200, REST_MIME_TYPE_JSONP); #ifdef WIN32 _snprintf(wrkbuf, sizeof(wrkbuf), REST_JSONP_ERROR_SUCCESS); #else snprintf(wrkbuf, sizeof(wrkbuf), REST_JSONP_ERROR_SUCCESS); #endif mg_write(conn, wrkbuf, strlen(wrkbuf)); mg_write(conn, "", 0); // Terminator return; } else { websrv_sendheader(conn, 400, REST_MIME_TYPE_PLAIN); mg_write(conn, REST_PLAIN_ERROR_UNSUPPORTED_FORMAT, strlen(REST_PLAIN_ERROR_UNSUPPORTED_FORMAT)); mg_write(conn, "", 0); // Terminator return; } } else { // session not found restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION, cbdata); } return; } /////////////////////////////////////////////////////////////////////////////// // restsrv_doStatus // void restsrv_doStatus(struct mg_connection* conn, struct restsrv_session* pSession, int format, void* cbdata) { char buf[2048]; char wrkbuf[256]; CWebObj* pObj = (CWebObj*)cbdata; if (NULL == pObj) { return; } if (NULL != pSession) { // Note activity pSession->m_lastActiveTime = time(NULL); if (REST_FORMAT_PLAIN == format) { websrv_sendheader(conn, 200, REST_MIME_TYPE_PLAIN); mg_write(conn, REST_PLAIN_ERROR_SUCCESS, strlen(REST_PLAIN_ERROR_SUCCESS)); memset(buf, 0, sizeof(buf)); #ifdef WIN32 _snprintf(wrkbuf, sizeof(wrkbuf), "vscpsession=%s nEvents=%zd", pSession->sid, pSession->pClientItem->m_clientInputQueue.size()); #else snprintf(wrkbuf, sizeof(wrkbuf), "1 1 Success vscpsession=%s nEvents=%zu", pSession->m_sid, pSession->m_pClientItem->m_clientInputQueue.size()); #endif mg_write(conn, wrkbuf, strlen(wrkbuf)); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_CSV == format) { websrv_sendheader(conn, 200, REST_MIME_TYPE_CSV); #ifdef WIN32 _snprintf(wrkbuf, sizeof(wrkbuf), "success-code,error-code,message,description,vscpsession," "nEvents\r\n1,1,Success,Success. 1,1,Success,Sucess,%s,%zd", pSession->sid, pSession->pClientItem->m_clientInputQueue.size()); #else snprintf(wrkbuf, sizeof(wrkbuf), "success-code,error-code,message,description,vscpsession," "nEvents\r\n1,1,Success,Success. 1,1,Success,Sucess,%s,%zu", pSession->m_sid, pSession->m_pClientItem->m_clientInputQueue.size()); #endif mg_write(conn, wrkbuf, strlen(wrkbuf)); mg_write(conn, "", 0); // Terminator return; } else if (REST_FORMAT_XML == format) { websrv_sendheader(conn, 200, REST_MIME_TYPE_XML); #ifdef WIN32 _snprintf(wrkbuf, sizeof(wrkbuf), "<vscp-rest success = \"true\" code = \"1\" message = " "\"Success.\" description = \"Success.\" " "><vscpsession>%s</vscpsession><nEvents>%zd</nEvents></" "vscp-rest>", pSession->sid, pSession->pClientItem->m_clientInputQueue.size()); #else snprintf(wrkbuf, sizeof(wrkbuf), "<vscp-rest success = \"true\" code = \"1\" message = " "\"Success.\" description = \"Success.\" " "><vscpsession>%s</vscpsession><nEvents>%zu</nEvents></" "vscp-rest>", pSession->m_sid, pSession->m_pClientItem->m_clientInputQueue.size()); #endif mg_write(conn, wrkbuf, strlen(wrkbuf)); mg_write(conn, "", 0); // Terminator return; } else if ((REST_FORMAT_JSON == format) || (REST_FORMAT_JSONP == format)) { json output; if (REST_FORMAT_JSON == format) { websrv_sendheader(conn, 200, REST_MIME_TYPE_JSON); } else { websrv_sendheader(conn, 200, REST_MIME_TYPE_JSONP); // Write JSONP start block mg_write(conn, REST_JSONP_START, strlen(REST_JSONP_START)); } output["success"] = true; output["code"] = 1; output["message"] = "success"; output["description"] = "Success"; output["vscpsession"] = pSession->m_sid; output["nEvents"] = pSession->m_pClientItem->m_clientInputQueue.size(); std::string s = output.dump(); mg_write(conn, s.c_str(), s.length()); if (REST_FORMAT_JSONP == format) { // Write JSONP end block mg_write(conn, REST_JSONP_END, strlen(REST_JSONP_END)); } return; } else { websrv_sendheader(conn, 400, REST_MIME_TYPE_PLAIN); mg_write(conn, REST_PLAIN_ERROR_UNSUPPORTED_FORMAT, strlen(REST_PLAIN_ERROR_UNSUPPORTED_FORMAT)); mg_write(conn, "", 0); // Terminator return; } } // No session else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION, cbdata); } return; } /////////////////////////////////////////////////////////////////////////////// // restsrv_doSendEvent // void restsrv_doSendEvent(struct mg_connection* conn, struct restsrv_session* pSession, int format, vscpEvent* pEvent, void* cbdata) { bool bSent = false; // Check pointer if (NULL == conn) { return; } CWebObj* pObj = (CWebObj*)cbdata; if (NULL == pObj) { return; } if (NULL != pSession) { // Level II events between 512-1023 is recognised by the daemon and // sent to the correct interface as Level I events if the interface // is addressed by the client. if ((pEvent->vscp_class <= 1023) && (pEvent->vscp_class >= 512) && (pEvent->sizeData >= 16)) { // This event should be sent to the correct interface if it is // available on this machine. If not it should be sent to // the rest of the network as normal cguid destguid; destguid.getFromArray(pEvent->pdata); destguid.setAt(0, 0); destguid.setAt(1, 0); if (NULL != pSession->m_pClientItem) { // Set client id pEvent->obid = pSession->m_pClientItem->m_clientID; // Check if filtered out if (vscp_doLevel2Filter(pEvent, &pSession->m_pClientItem->m_filter)) { // Lock client pthread_mutex_lock(&pObj->m_clientList.m_mutexItemList); // If the client queue is full for this client then the // client will not receive the message if (pSession->m_pClientItem->m_clientInputQueue.size() <= pObj->m_maxItemsInClientReceiveQueue) { vscpEvent* pNewEvent = new (vscpEvent); if (NULL != pNewEvent) { vscp_copyEvent(pNewEvent, pEvent); // Add the new event to the input queue // pthread_mutex_lock( // &pSession->m_pClientItem->m_mutexClientInputQueue); // pSession->m_pClientItem->m_clientInputQueue.push_back(pNewEvent); // pthread_mutex_unlock( // &pSession->m_pClientItem->m_mutexClientInputQueue); // sem_post(&pSession->m_pClientItem->m_semClientInputQueue); if (!pObj->eventToReceiveQueue(pNewEvent)) { spdlog::get("logger")->error("[REST] Failed to send event"); } bSent = true; } else { bSent = false; } } else { // Overrun - No room for event // vscp_deleteEvent( pEvent ); bSent = true; } // Unlock client pthread_mutex_unlock(&pObj->m_clientList.m_mutexItemList); } // filter } // Client found } if (!bSent) { if (NULL != pSession->m_pClientItem) { // Set client id pEvent->obid = pSession->m_pClientItem->m_clientID; // There must be room in the send queue if (pObj->m_maxItemsInClientReceiveQueue > /*pObj->m_mutexSendQueue.size() TODO:*/ 0) { vscpEvent* pNewEvent = new (vscpEvent); if (NULL != pNewEvent) { vscp_copyEvent(pNewEvent, pEvent); // TODO // pthread_mutex_lock(&pObj->m_mutexSendQueue); // pObj->m_mutexSendQueue.push_back(pNewEvent); // pthread_mutex_unlock(&pObj->m_mutexSendQueue); // sem_post(&pObj->m_semSendQueue); bSent = true; } else { bSent = false; } restsrv_error(conn, pSession, format, REST_ERROR_CODE_SUCCESS, cbdata); } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_NO_ROOM, cbdata); vscp_deleteEvent(pEvent); bSent = false; } } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); vscp_deleteEvent(pEvent); bSent = false; } } // not sent } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION, cbdata); bSent = false; } return; } /////////////////////////////////////////////////////////////////////////////// // restsrv_doReceiveEvent // void restsrv_doReceiveEvent(struct mg_connection* conn, struct restsrv_session* pSession, int format, size_t count, void* cbdata) { // Check pointer if (NULL == conn) return; if (NULL != pSession) { if (!pSession->m_pClientItem->m_clientInputQueue.empty()) { char wrkbuf[32000]; std::string out; size_t cntAvailable = pSession->m_pClientItem->m_clientInputQueue.size(); // Plain if (REST_FORMAT_PLAIN == format) { // Send header websrv_sendheader(conn, 200, REST_MIME_TYPE_PLAIN); if (pSession->m_pClientItem->m_bOpen && cntAvailable) { sprintf(wrkbuf, "1 1 Success \r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); sprintf(wrkbuf, #if WIN32 "%zd events requested of %zd available " "(unfiltered) %zu will be retrieved\r\n", #else "%zd events requested of %zd available " "(unfiltered) %zu will be retrieved\r\n", #endif count, pSession->m_pClientItem->m_clientInputQueue.size(), std::min(count, cntAvailable)); mg_write(conn, wrkbuf, strlen(wrkbuf)); for (unsigned int i = 0; i < std::min(count, cntAvailable); i++) { vscpEvent* pEvent; pthread_mutex_lock( &pSession->m_pClientItem->m_mutexClientInputQueue); pEvent = pSession->m_pClientItem->m_clientInputQueue.front(); pSession->m_pClientItem->m_clientInputQueue.pop_front(); pthread_mutex_unlock( &pSession->m_pClientItem->m_mutexClientInputQueue); if (NULL != pEvent) { if (vscp_doLevel2Filter(pEvent, &pSession->m_pClientItem->m_filter)) { std::string str; if (vscp_convertEventToString(str, pEvent)) { // Write it out strcpy((char*)wrkbuf, (const char*)"- "); strcat((char*)wrkbuf, (const char*)str.c_str()); strcat((char*)wrkbuf, "\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } else { strcpy((char*)wrkbuf, "- Malformed event (internal error)\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } } else { strcpy((char*)wrkbuf, "- Event filtered out\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } // Remove the event vscp_deleteEvent(pEvent); } // Valid pEvent pointer else { strcpy((char*)wrkbuf, "- Event could not be fetched (internal " "error)\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } } // for } else { // no events available sprintf(wrkbuf, REST_PLAIN_ERROR_INPUT_QUEUE_EMPTY "\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } } // CSV else if (REST_FORMAT_CSV == format) { // Send header websrv_sendheader(conn, 200, /*REST_MIME_TYPE_CSV*/ REST_MIME_TYPE_PLAIN); if (pSession->m_pClientItem->m_bOpen && cntAvailable) { sprintf(wrkbuf, "success-code,error-code,message," "description,Event\r\n1,1,Success,Success." ",NULL\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); sprintf(wrkbuf, #if WIN32 "1,2,Info,%zd events requested of %d available " "(unfiltered) %zu will be retrieved,NULL\r\n", #else "1,2,Info,%zd events requested of %lu available " "(unfiltered) %lu will be retrieved,NULL\r\n", #endif count, (unsigned long)cntAvailable, (unsigned long)std::min(count, cntAvailable)); mg_write(conn, wrkbuf, strlen(wrkbuf)); sprintf(wrkbuf, "1,4,Count,%zu,NULL\r\n", std::min(count, cntAvailable)); mg_write(conn, wrkbuf, strlen(wrkbuf)); for (unsigned int i = 0; i < std::min(count, cntAvailable); i++) { vscpEvent* pEvent; pthread_mutex_lock( &pSession->m_pClientItem->m_mutexClientInputQueue); pEvent = pSession->m_pClientItem->m_clientInputQueue.front(); pSession->m_pClientItem->m_clientInputQueue.pop_front(); pthread_mutex_unlock( &pSession->m_pClientItem->m_mutexClientInputQueue); if (NULL != pEvent) { if (vscp_doLevel2Filter(pEvent, &pSession->m_pClientItem->m_filter)) { std::string str; if (vscp_convertEventToString(str, pEvent)) { // Write it out memset((char*)wrkbuf, 0, sizeof(wrkbuf)); strcpy((char*)wrkbuf, (const char*)"1,3,Data,Event,"); strcat((char*)wrkbuf, (const char*)str.c_str()); strcat((char*)wrkbuf, "\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } else { strcpy((char*)wrkbuf, "1,2,Info,Malformed event (internal " "error)\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } } else { strcpy((char*)wrkbuf, "1,2,Info,Event filtered out\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } // Remove the event vscp_deleteEvent(pEvent); } // Valid pEvent pointer else { strcpy((char*)wrkbuf, "1,2,Info,Event could not be fetched " "(internal error)\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } } // for } else { // no events available sprintf(wrkbuf, REST_CSV_ERROR_INPUT_QUEUE_EMPTY "\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } } // XML else if (REST_FORMAT_XML == format) { int filtered = 0; int errors = 0; // Send header websrv_sendheader(conn, 200, REST_MIME_TYPE_XML); if (pSession->m_pClientItem->m_bOpen && cntAvailable) { sprintf(wrkbuf, XML_HEADER "<vscp-rest success = \"true\" " "code = \"1\" message = \"Success\" " "description = \"Success.\" >"); mg_write(conn, wrkbuf, strlen(wrkbuf)); sprintf(wrkbuf, "<info>%zd events requested of %zu available " "(unfiltered) %zu will be retrieved</info>", count, cntAvailable, std::min(count, cntAvailable)); mg_write(conn, wrkbuf, strlen(wrkbuf)); sprintf(wrkbuf, "<count>%zu</count>", std::min(count, cntAvailable)); mg_write(conn, wrkbuf, strlen(wrkbuf)); for (unsigned int i = 0; i < std::min(count, cntAvailable); i++) { vscpEvent* pEvent; pthread_mutex_lock( &pSession->m_pClientItem->m_mutexClientInputQueue); pEvent = pSession->m_pClientItem->m_clientInputQueue.front(); pSession->m_pClientItem->m_clientInputQueue.pop_front(); pthread_mutex_unlock( &pSession->m_pClientItem->m_mutexClientInputQueue); if (NULL != pEvent) { if (vscp_doLevel2Filter(pEvent, &pSession->m_pClientItem->m_filter)) { std::string str; // Write it out strcpy((char*)wrkbuf, (const char*)"<event>"); // head strcat((char*)wrkbuf, (const char*)"<head>"); strcat((char*)wrkbuf, vscp_str_format(("%d"), pEvent->head).c_str()); strcat((char*)wrkbuf, (const char*)"</head>"); // class strcat((char*)wrkbuf, (const char*)"<vscpclass>"); strcat((char*)wrkbuf, vscp_str_format(("%d"), pEvent->vscp_class).c_str()); strcat((char*)wrkbuf, (const char*)"</vscpclass>"); // type strcat((char*)wrkbuf, (const char*)"<vscptype>"); strcat((char*)wrkbuf, vscp_str_format(("%d"), pEvent->vscp_type).c_str()); strcat((char*)wrkbuf, (const char*)"</vscptype>"); // obid strcat((char*)wrkbuf, (const char*)"<obid>"); strcat((char*)wrkbuf, vscp_str_format(("%lu"), pEvent->obid).c_str()); strcat((char*)wrkbuf, (const char*)"</obid>"); // datetime strcat((char*)wrkbuf, (const char*)"<datetime>"); std::string dt; vscp_getDateStringFromEvent(dt, pEvent); strcat((char*)wrkbuf, vscp_str_format("%s", dt.c_str()).c_str()); strcat((char*)wrkbuf, (const char*)"</datetime>"); // timestamp strcat((char*)wrkbuf, (const char*)"<timestamp>"); strcat((char*)wrkbuf, vscp_str_format(("%lu"), pEvent->timestamp).c_str()); strcat((char*)wrkbuf, (const char*)"</timestamp>"); // guid strcat((char*)wrkbuf, (const char*)"<guid>"); vscp_writeGuidToString(str, pEvent); strcat((char*)wrkbuf, (const char*)str.c_str()); strcat((char*)wrkbuf, (const char*)"</guid>"); // sizedate strcat((char*)wrkbuf, (const char*)"<sizedata>"); strcat((char*)wrkbuf, vscp_str_format(("%d"), pEvent->sizeData).c_str()); strcat((char*)wrkbuf, (const char*)"</sizedata>"); // data strcat((char*)wrkbuf, (const char*)"<data>"); vscp_writeDataToString(str, pEvent); strcat((char*)wrkbuf, (const char*)str.c_str()); strcat((char*)wrkbuf, (const char*)"</data>"); if (vscp_convertEventToString(str, pEvent)) { strcat((char*)wrkbuf, (const char*)"<raw>"); strcat((char*)wrkbuf, (const char*)str.c_str()); strcat((char*)wrkbuf, (const char*)"</raw>"); } strcat((char*)wrkbuf, "</event>"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } else { filtered++; } // Remove the event vscp_deleteEvent(pEvent); } // Valid pEvent pointer else { errors++; } } // for strcpy((char*)wrkbuf, (const char*)"<filtered>"); strcat((char*)wrkbuf, vscp_str_format(("%d"), filtered).c_str()); strcat((char*)wrkbuf, (const char*)"</filtered>"); strcat((char*)wrkbuf, (const char*)"<errors>"); strcat((char*)wrkbuf, vscp_str_format(("%d"), errors).c_str()); strcat((char*)wrkbuf, (const char*)"</errors>"); mg_write(conn, wrkbuf, strlen(wrkbuf)); // End tag strcpy((char*)wrkbuf, "</vscp-rest>"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } else { // no events available sprintf(wrkbuf, REST_XML_ERROR_INPUT_QUEUE_EMPTY "\r\n"); mg_write(conn, wrkbuf, strlen(wrkbuf)); } } // JSON / JSONP else if ((REST_FORMAT_JSON == format) || (REST_FORMAT_JSONP == format)) { int sentEvents = 0; int filtered = 0; int errors = 0; json output; // Send header if (REST_FORMAT_JSONP == format) { websrv_sendheader(conn, 200, REST_MIME_TYPE_JSONP); } else { websrv_sendheader(conn, 200, REST_MIME_TYPE_JSON); } if (pSession->m_pClientItem->m_bOpen && cntAvailable) { // typeof handler === 'function' && if (REST_FORMAT_JSONP == format) { std::string str = ("typeof handler === 'function' && handler("); mg_write(conn, (const char*)str.c_str(), str.length()); } output["success"] = true; output["code"] = 1; output["message"] = "success"; output["description"] = "Success"; output["info"] = (const char*)vscp_str_format( "%zd events requested of %lu available " "(unfiltered) %zd will be retrieved", count, cntAvailable, std::min(count, cntAvailable)) .c_str(); for (unsigned int i = 0; i < std::min(count, cntAvailable); i++) { vscpEvent* pEvent; pthread_mutex_lock( &pSession->m_pClientItem->m_mutexClientInputQueue); pEvent = pSession->m_pClientItem->m_clientInputQueue.front(); pSession->m_pClientItem->m_clientInputQueue.pop_front(); pthread_mutex_unlock( &pSession->m_pClientItem->m_mutexClientInputQueue); if (NULL != pEvent) { if (vscp_doLevel2Filter(pEvent, &pSession->m_pClientItem->m_filter)) { std::string str; json ev; ev["head"] = pEvent->head; ev["vscpclass"] = pEvent->vscp_class; ev["vscptype"] = pEvent->vscp_type; vscp_getDateStringFromEvent(str, pEvent); ev["datetime"] = (const char*)str.c_str(); ev["timestamp"] = pEvent->timestamp; ev["obid"] = pEvent->obid; vscp_writeGuidToString(str, pEvent); ev["guid"] = (const char*)str.c_str(); ev["sizedata"] = pEvent->sizeData; ev["data"] = json::array(); for (uint16_t j = 0; j < pEvent->sizeData; j++) { ev["data"].push_back(pEvent->pdata[j]); } // Add event to event array output["event"].push_back(ev); sentEvents++; } else { filtered++; } // Remove the event vscp_deleteEvent(pEvent); } // Valid pEvent pointer else { errors++; } } // for // Mark end output["count"] = sentEvents; output["filtered"] = filtered; output["errors"] = errors; std::string s = output.dump(); mg_write(conn, s.c_str(), s.length()); if (REST_FORMAT_JSONP == format) { mg_write(conn, ");", 2); } } // if open and data else { // no events available if (REST_FORMAT_JSON == format) { sprintf(wrkbuf, REST_JSON_ERROR_INPUT_QUEUE_EMPTY "\r\n"); } else { sprintf(wrkbuf, REST_JSONP_ERROR_INPUT_QUEUE_EMPTY "\r\n"); } mg_write(conn, wrkbuf, strlen(wrkbuf)); } } // format mg_write(conn, "", 0); } else { // Queue is empty restsrv_error(conn, pSession, format, REST_ERROR_CODE_INPUT_QUEUE_EMPTY, cbdata); } } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION, cbdata); } return; } /////////////////////////////////////////////////////////////////////////////// // restsrv_doSetFilter // void restsrv_doSetFilter(struct mg_connection* conn, struct restsrv_session* pSession, int format, vscpEventFilter& vscpfilter, void* cbdata) { if (NULL != pSession) { pthread_mutex_lock(&pSession->m_pClientItem->m_mutexClientInputQueue); memcpy(&pSession->m_pClientItem->m_filter, &vscpfilter, sizeof(vscpEventFilter)); pthread_mutex_unlock(&pSession->m_pClientItem->m_mutexClientInputQueue); restsrv_error(conn, pSession, format, REST_ERROR_CODE_SUCCESS, cbdata); } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION, cbdata); } return; } /////////////////////////////////////////////////////////////////////////////// // restsrv_doClearQueue // void restsrv_doClearQueue(struct mg_connection* conn, struct restsrv_session* pSession, int format, void* cbdata) { // Check pointer if (NULL == conn) return; if (NULL != pSession) { std::deque<vscpEvent*>::iterator it; pthread_mutex_lock(&pSession->m_pClientItem->m_mutexClientInputQueue); for (it = pSession->m_pClientItem->m_clientInputQueue.begin(); it != pSession->m_pClientItem->m_clientInputQueue.end(); ++it) { vscpEvent* pEvent = *it; vscp_deleteEvent_v2(&pEvent); } pSession->m_pClientItem->m_clientInputQueue.clear(); pthread_mutex_unlock(&pSession->m_pClientItem->m_mutexClientInputQueue); restsrv_error(conn, pSession, format, REST_ERROR_CODE_SUCCESS, cbdata); } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION, cbdata); } return; } /////////////////////////////////////////////////////////////////////////////// // restsrv_doWriteMeasurement // void restsrv_doWriteMeasurement(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strDateTime, std::string& strGuid, std::string& strLevel, std::string& strType, std::string& strValue, std::string& strUnit, std::string& strSensorIdx, std::string& strZone, std::string& strSubZone, std::string& strEventFormat, void* cbdata) { if (NULL != pSession) { double value = 0; uint8_t guid[16]; long level = 2; long unit; long vscptype; long sensoridx; long zone; long subzone; long eventFormat = 0; // float uint8_t data[VSCP_MAX_DATA]; uint16_t sizeData; memset(guid, 0, 16); vscp_getGuidFromStringToArray(guid, strGuid); value = std::stod(strValue); // Measurement value unit = vscp_readStringValue(strUnit); // Measurement unit sensoridx = vscp_readStringValue(strSensorIdx); // Sensor index vscptype = vscp_readStringValue(strType); // VSCP event type zone = vscp_readStringValue(strZone); // VSCP event type zone &= 0xff; subzone = vscp_readStringValue(strSubZone); // VSCP event type subzone &= 0xff; // datetime vscpdatetime dt; if (!dt.set(strDateTime)) { dt = vscpdatetime::UTCNow(); } level = vscp_readStringValue(strLevel); // Level I or Level II (default) if ((level > 2) || (level < 1)) { level = 2; } vscp_trim(strEventFormat); if (0 != vscp_strcasecmp(strEventFormat.c_str(), "STRING")) { eventFormat = 1; } // Range checks if (1 == level) { if (unit > 3) unit = 0; if (sensoridx > 7) sensoridx = 0; if (vscptype > 512) vscptype -= 512; } else if (2 == level) { if (unit > 255) unit &= 0xff; if (sensoridx > 255) sensoridx &= 0xff; } if (1 == level) { if (0 == eventFormat) { // Floating point if (vscp_convertFloatToFloatEventData(data, &sizeData, value, unit, sensoridx)) { if (sizeData > 8) sizeData = 8; vscpEvent* pEvent = new vscpEvent; if (NULL == pEvent) { restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); return; } pEvent->pdata = NULL; pEvent->head = VSCP_PRIORITY_NORMAL; pEvent->timestamp = 0; // Let interface fill in memcpy(pEvent->GUID, guid, 16); pEvent->sizeData = sizeData; if (sizeData > 0) { pEvent->pdata = new uint8_t[sizeData]; memcpy(pEvent->pdata, data, sizeData); } pEvent->vscp_class = VSCP_CLASS1_MEASUREMENT; pEvent->vscp_type = vscptype; restsrv_doSendEvent(conn, pSession, format, pEvent, cbdata); } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); } } else { // String vscpEvent* pEvent = new vscpEvent; if (NULL == pEvent) { restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); return; } pEvent->pdata = NULL; if (vscp_makeStringMeasurementEvent(pEvent, value, unit, sensoridx)) { } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); } } } else { // Level II if (0 == eventFormat) { // Floating point vscpEvent* pEvent = new vscpEvent; if (NULL == pEvent) { restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); return; } pEvent->pdata = NULL; pEvent->obid = 0; pEvent->head = VSCP_PRIORITY_NORMAL; pEvent->timestamp = 0; // Let interface fill in memcpy(pEvent->GUID, guid, 16); pEvent->head = 0; pEvent->vscp_class = VSCP_CLASS2_MEASUREMENT_FLOAT; pEvent->vscp_type = vscptype; pEvent->timestamp = 0; pEvent->sizeData = 12; data[0] = sensoridx; data[1] = zone; data[2] = subzone; data[3] = unit; memcpy(data + 4, (uint8_t*)&value, 8); // copy in double uint64_t temp = VSCP_UINT64_SWAP_ON_LE(*(data + 4)); memcpy(data + 4, (void*)&temp, 8); // Copy in data pEvent->pdata = new uint8_t[4 + 8]; if (NULL == pEvent->pdata) { restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); delete pEvent; return; } memcpy(pEvent->pdata, data, 4 + 8); restsrv_doSendEvent(conn, pSession, format, pEvent, cbdata); } else { // String vscpEvent* pEvent = new vscpEvent; pEvent->pdata = NULL; pEvent->obid = 0; pEvent->head = VSCP_PRIORITY_NORMAL; pEvent->timestamp = 0; // Let interface fill in memcpy(pEvent->GUID, guid, 16); pEvent->head = 0; pEvent->vscp_class = VSCP_CLASS2_MEASUREMENT_STR; pEvent->vscp_type = vscptype; pEvent->timestamp = 0; pEvent->sizeData = 12; data[0] = sensoridx; data[1] = zone; data[2] = subzone; data[3] = unit; pEvent->pdata = new uint8_t[4 + strValue.length()]; if (NULL == pEvent->pdata) { restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); delete pEvent; return; } memcpy(data + 4, strValue.c_str(), strValue.length()); // copy in double restsrv_doSendEvent(conn, pSession, format, pEvent, cbdata); } } restsrv_error(conn, pSession, format, REST_ERROR_CODE_SUCCESS, cbdata); } else { restsrv_error(conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION, cbdata); } return; } /////////////////////////////////////////////////////////////////////////////// // restsrv_doFetchMDF // void restsrv_doFetchMDF(struct mg_connection* conn, struct restsrv_session* pSession, int format, std::string& strURL, void* cbdata) { CMDF mdf; if (mdf.load(strURL, false)) { // Loaded OK if (REST_FORMAT_PLAIN == format) { restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); } else if (REST_FORMAT_CSV == format) { restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); } else if (REST_FORMAT_XML == format) { // Send header websrv_sendheader(conn, 200, REST_MIME_TYPE_XML); std::string line; std::ifstream file(mdf.getTempFilePath()); if (file.is_open()) { while (!file.fail() && !file.eof() && getline(file, line)) { line += "\n"; mg_write(conn, line.c_str(), line.length()); } file.close(); } file.close(); mg_write(conn, "", 0); // Terminator } else if ((REST_FORMAT_JSON == format) || (REST_FORMAT_JSONP == format)) { restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); } } else { // Failed to load restsrv_error(conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE, cbdata); } return; }
30.802266
82
0.531629
grodansparadis
e6daaeae978fb7901e8a4730c14c67f9e1c05706
8,142
cpp
C++
src/Main.cpp
eugen-bondarev/BLL
2cc6579207133f00c79794f97e4ae9e993e6141c
[ "MIT" ]
1
2021-12-10T09:27:45.000Z
2021-12-10T09:27:45.000Z
src/Main.cpp
eugen-bondarev/BLL
2cc6579207133f00c79794f97e4ae9e993e6141c
[ "MIT" ]
null
null
null
src/Main.cpp
eugen-bondarev/BLL
2cc6579207133f00c79794f97e4ae9e993e6141c
[ "MIT" ]
null
null
null
#include "MNIST/MNISTHelper.h" #include "Window/Window.h" #include "AI/Util/Random.h" #include "AI/Util/Util.h" #include "AI/Util/ImGuiMatrixRenderer.h" #include "AI/Network.h" #include "AI/Math.h" #include "AI/Metrics.h" #include "AI/Console.h" #include <future> int main() { try { // Zufallszahlengenerator zurücksetzen, um bei jedem // Neustart neue Gewichtungen und Bias zu erzeugen. AI::Util::Random::Reset(); // Der Datensatz, mit welchem das Netz getestet wird (enthält andere Samples). const AI::TrainingData testData{MNIST::Load( "dataset/test-images", "dataset/test-labels")}; // Der Datensatz, mit welchem das Netz trainiert wird. const AI::TrainingData trainingData{MNIST::Load( "dataset/train-images", "dataset/train-labels")}; AI::Network network({{784}, {16}, {16}, {10}}); std::future<void> trainingFuture; Window window{1024, 768}; AI::Matrix mat{784, 1}; mat.setZero(); while (window.IsRunning()) { window.BeginFrame(); AI::Console::ClearMessages(); // ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); ImVec2 v = ImGui::GetMainViewport()->Pos; ImVec2 s = ImGui::GetMainViewport()->Size; ImGui::SetNextWindowPos(v); ImGui::SetNextWindowSize(s); ImGui::Begin("Docking", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); ImGui::DockSpace(ImGui::GetID("DockSpace")); ImGui::End(); ImGui::Begin("Training"); static int numEpochs = 30; ImGui::Text("Anzahl der Epochen"); ImGui::InputInt("##numEpochs", &numEpochs); static int miniBatchSize = 20; ImGui::Text("Größe der Mini-Batches"); ImGui::InputInt("##miniBatchSize", &miniBatchSize); static float eta = 3.f; ImGui::Text("Lernrate"); ImGui::InputFloat("##eta", &eta); ImGui::Separator(); if (!network.IsTrainingRunning() && ImGui::Button("Trainieren")) { trainingFuture = std::async(std::launch::async, [&]() { network.SGD(trainingData, numEpochs, miniBatchSize, eta, testData); }); } if (network.IsTrainingRunning()) { if (ImGui::Button("Fertigstellen")) { network.StopTraining(); } ImGui::Text("Trainingsfortschritt:"); ImGui::ProgressBar(network.GetCurrentSGDProgress()); ImGui::Text("Aktuelle Epoche:"); ImGui::ProgressBar(network.GetCurrentEpochProgress()); } ImGui::End(); ImGui::Begin("Zeichnen", nullptr, ImGuiWindowFlags_NoMove); { ImVec2 vMin = ImGui::GetWindowContentRegionMin(); ImVec2 vMax = ImGui::GetWindowContentRegionMax(); vMin.x += ImGui::GetWindowPos().x; vMin.y += ImGui::GetWindowPos().y; vMax.x += ImGui::GetWindowPos().x; vMax.y += ImGui::GetWindowPos().y; float mousePosInWindowX = ImGui::GetIO().MousePos.x - vMin.x; float mousePosInWindowY = ImGui::GetIO().MousePos.y - vMin.y; std::function<void(int j, int i, float val)> set = [&](int j, int i, float val) { if (j < 28 && i < 28 && j >= 0 && i >= 0) { float &var = mat(j * 28 + i); var += val; if (var > 1.f) var = 1.f; } }; if (mousePosInWindowX >= 0 && mousePosInWindowX < vMax.x) { if (mousePosInWindowY >= 0 && mousePosInWindowY < vMax.y) { if (ImGui::IsMouseDragging(ImGuiMouseButton_Left) && ImGui::IsWindowHovered()) { int i = mousePosInWindowX / 10; int j = mousePosInWindowY / 10; float factor = 1.f; set(j, i, 1.f); for (int x = -1; x <= 1; ++x) { set(j, i + x, 0.3f); } for (int y = -1; y <= 1; ++y) { set(j + y, i, 0.3f); } } } } } ImGui::RenderMatrix(mat); ImGui::End(); ImGui::Begin("Steuerung"); static AI::Matrix res; static int right = 0; static int total = 0; if (ImGui::Button("Testen")) { res = network.Feedforward(mat); total++; } if (total != 0) { ImGui::SameLine(); if (ImGui::Button("Zurücksetzen")) { res.setZero(); right = 0; total = 0; } } if (!res.isZero()) { size_t greatestIndex = AI::Util::FindGreatestIndex(res); for (size_t i = 0; i < 10; ++i) { float num = res(i, 0); int color = 255 * num; if (greatestIndex == i) { ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f); ImGui::PushStyleColor(ImGuiCol_Border, IM_COL32(255, 255, 0, 255)); } ImGui::PushStyleColor(ImGuiCol_Button, IM_COL32(color, color, color, 255)); ImGui::Button(AI::StringFormat("%i %.3f", i, num).c_str()); if (greatestIndex == i) { ImGui::PopStyleVar(); ImGui::PopStyleColor(); } ImGui::PopStyleColor(); } if (ImGui::Button("Ja")) { mat.setZero(); res.setZero(); right++; } ImGui::SameLine(); if (ImGui::Button("Nein")) { mat.setZero(); res.setZero(); } } if (total != 0) { ImGui::Text("Genauigkeit: %.2f%%", right / static_cast<float>(total) * 100.f); } ImGui::End(); ImGui::Begin("Samples"); static int sample = 0; static AI::Matrix matrix = testData[sample].input; ImGui::RenderMatrix(matrix); if (ImGui::DragInt("Sample", &sample, 1.f, 0, testData.size() - 1)) { matrix = testData[sample].input; } if (ImGui::Button("Test")) { res = network.Feedforward(matrix); } ImGui::End(); ImGui::Begin("Konsole"); for (int i = 0; i < AI::Console::GetMessages().size(); ++i) { ImGui::Text(AI::Console::GetMessages()[i].c_str()); } ImGui::End(); window.EndFrame(); } trainingFuture.wait(); } catch (const std::runtime_error &error) { LINE_OUT("[Exception] " + std::string{error.what()}); } return 0; }
34.066946
261
0.436748
eugen-bondarev
5c7922737adf0a6bfed77e962d6922dd305a7f70
984
hpp
C++
Server/Monsters/includes/MonsterInfo.hpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
1
2019-08-14T12:31:50.000Z
2019-08-14T12:31:50.000Z
Server/Monsters/includes/MonsterInfo.hpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
null
null
null
Server/Monsters/includes/MonsterInfo.hpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
null
null
null
// // Created by nhyarlathotep on 30/11/18. // #pragma once #include <string> #include "../../includes/Utils.hpp" namespace Game { struct MonsterInfo { public: MonsterInfo() : _type(""), _pos{0, 0}, _timer(0), _endGame(false) {} MonsterInfo(std::string &&type, float x, float y, float setTimer) : _type(type), _pos{x, y}, _timer(setTimer), _endGame(false) {} MonsterInfo(std::string &&type, Game::vector2f sPos, float setTimer = 0) : _type(type), _pos(sPos), _timer(setTimer), _endGame(false) {} friend std::istream &operator>>(std::istream &is, MonsterInfo &mInfo) { is >> mInfo._type; is >> mInfo._pos.x; is >> mInfo._pos.y; is >> mInfo._timer; mInfo._endGame = is.eof(); return is; } public: std::string _type; Game::vector2f _pos; float _timer; bool _endGame; }; }
25.894737
82
0.537602
KillianG
5c7b9e56bc2e1e64d4c40eff512cbf20fd251d09
14,565
cpp
C++
src/socket.cpp
Harrand/Amethyst
0e107bbddf9ca85025fe7ff4b2a5cd684f9cac5d
[ "MIT" ]
null
null
null
src/socket.cpp
Harrand/Amethyst
0e107bbddf9ca85025fe7ff4b2a5cd684f9cac5d
[ "MIT" ]
null
null
null
src/socket.cpp
Harrand/Amethyst
0e107bbddf9ca85025fe7ff4b2a5cd684f9cac5d
[ "MIT" ]
null
null
null
// // Created by Harrand on 14/12/2018. // #include "socket.hpp" #include "amethyst.hpp" bool am::detail::is_initialised = false; SocketDescriptor::SocketDescriptor(am::net::transmission::protocol transmission_protocol, am::net::internet::protocol internet_protocol): transmission_protocol(transmission_protocol), internet_protocol(internet_protocol){} ISocket::ISocket(SocketDescriptor descriptor): descriptor(descriptor), bound(false), port(std::nullopt), destination_address(std::nullopt) { if(!am::detail::is_initialised) std::cerr << "ISocket::ISocket(...): Amethyst not initialised.\n"; } const SocketDescriptor& ISocket::get_info() const { return this->descriptor; } #ifdef AMETHYST_WINDOWS SocketWindows::SocketWindows(SocketDescriptor descriptor): ISocket(descriptor), socket_handle(INVALID_SOCKET), connection_handle(INVALID_SOCKET) { using namespace am::net; int af; switch(this->descriptor.internet_protocol) { default: case internet::protocol::IPV4: af = AF_INET; break; case internet::protocol::IPV6: af = AF_INET6; break; } int type, protocol; switch(this->descriptor.transmission_protocol) { default: case transmission::protocol::TCP: type = SOCK_STREAM; protocol = IPPROTO_TCP; break; case transmission::protocol::UDP: type = SOCK_DGRAM; protocol = IPPROTO_UDP; break; } this->socket_handle = socket(af, type, protocol); auto error = WSAGetLastError(); if(error != 0) am::debug::print("SocketWindows::SocketWindows(...) Initialisation Error Code: ", error, "\n"); } SocketWindows::~SocketWindows() { this->unbind(); closesocket(this->socket_handle); } bool SocketWindows::bind(unsigned int port) { using namespace am::net::internet; int result; switch(this->descriptor.internet_protocol) { case protocol::IPV6: { sockaddr_in6 address; memset(&address, 0, sizeof(address)); address.sin6_family = AF_INET6; address.sin6_port = htons(port); //address.sin6_addr.s_addr = inet_addr("0.0.0.0"); result = ::bind(this->socket_handle, reinterpret_cast<sockaddr*>(&address), sizeof(address)); } break; case protocol::IPV4: default: { sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons(port); address.sin_addr.s_addr = inet_addr("0.0.0.0"); result = ::bind(this->socket_handle, reinterpret_cast<sockaddr*>(&address), sizeof(address)); } break; } if(result == -1) { am::debug::print("SocketWindows::bind(...) could not bind correctly and produced error code: ", WSAGetLastError(), "\n"); //std::cerr << "SocketWindows::bind(...) produced error code " << WSAGetLastError() << "\n"; return false; } this->bound = true; this->port = {port}; return true; } bool SocketWindows::listen(std::size_t maximum_queue_length) { if(!this->bound) { am::debug::print("SocketWindows::listen(...) invoked but the Socket is not bound! Aborting.\n"); return false; } int result = ::listen(this->socket_handle, maximum_queue_length); if(result == -1) { am::debug::print("SocketWindows::listen(...) produced error code ", WSAGetLastError(), "\n"); return false; } return true; } bool SocketWindows::connect(const std::string& address, unsigned int port) { using namespace am::net::transmission; if(this->get_info().transmission_protocol == protocol::TCP) { addrinfo connection_info; addrinfo *response = nullptr; memset(&connection_info, 0, sizeof(connection_info)); connection_info.ai_family = AF_UNSPEC; switch (this->get_info().transmission_protocol) { case protocol::TCP: connection_info.ai_socktype = SOCK_STREAM; connection_info.ai_protocol = IPPROTO_TCP; break; case protocol::UDP: connection_info.ai_socktype = SOCK_DGRAM; connection_info.ai_protocol = IPPROTO_UDP; break; } if (getaddrinfo(address.c_str(), std::to_string(port).c_str(), &connection_info, &response) != 0) { /*AMETHYST_DEBUG_PRINT((std::string( "SocketWindows::connect(...) could not resolve the target address. It produced error ") + std::to_string(WSAGetLastError()) + ".\n").c_str());*/ am::debug::print("SocketWindows::connect(...) could not resolve the target address. It produced error code: ", WSAGetLastError(), "\n"); return false; } addrinfo *response_pointer = nullptr; for (response_pointer = response; response_pointer != nullptr; response_pointer = response_pointer->ai_next) { if (::connect(this->socket_handle, response_pointer->ai_addr, static_cast<int>(response_pointer->ai_addrlen)) == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::connect(...) could not connect to the target address. It produced error ") +std::to_string(WSAGetLastError()) + ".\n").c_str()); am::debug::print("SocketWindows::connect(...) could not connect to the target address. It produced error code: ", WSAGetLastError(), "\n"); return false; } } freeaddrinfo(response); } this->destination_address = {{{this->get_info().internet_protocol}, address}}; this->port = {port}; return true; } std::optional<Address> SocketWindows::accept() { this->connection_handle = ::accept(this->socket_handle, nullptr, nullptr); if(this->connection_handle == INVALID_SOCKET) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::accept(...) did not connect to a valid socket and produced error code ") + std::to_string(WSAGetLastError())).c_str()) am::debug::print("SocketWindows::accept(...) did not connect to a valid socket and produced error code: ", WSAGetLastError(), "\n"); return std::nullopt; } sockaddr_in other_socket; socklen_t len = sizeof(other_socket); getpeername(this->connection_handle, (sockaddr*)&other_socket, &len); AddressWindows other_socket_address{other_socket}; this->destination_address = {static_cast<Address>(other_socket_address)}; return this->destination_address; } bool SocketWindows::send(const std::string& data) { using namespace am::net::transmission; if(this->get_info().transmission_protocol == protocol::TCP) { int result = ::send(this->socket_handle, data.c_str(), data.size(), 0); if (result == SOCKET_ERROR) { /*AMETHYST_DEBUG_PRINT((std::string( "SocketWindows::send(...) could not send data correctly (TCP) and produced error code ") + std::to_string(WSAGetLastError())).c_str());*/ am::debug::print("SocketWindows::send(...) could not send data correctly (TCP) and produced error code: ", WSAGetLastError(), "\n"); return false; } return true; } else // UDP Send { if(!this->destination_address.has_value() || !this->port.has_value()) { // Never connected. //AMETHYST_DEBUG_PRINT("SocketWindows::send(...) invoked (UDP) but there is no destination address!"); am::debug::print("SocketWindows::send(...) invoked (UDP) but there is no destination address.\n"); return false; } AddressWindows dest_address = {this->destination_address.value()}; sockaddr_in win_address = dest_address.get_winsock_address_ipv4(this->port.value()); int result = sendto(this->socket_handle, data.c_str(), data.size(), 0, reinterpret_cast<sockaddr*>(&win_address), sizeof(win_address)); if(result == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::send(...) could not send data correctly (UDP) and produced error code") + std::to_string(WSAGetLastError())).c_str()); am::debug::print("SocketWindows::send(...) could not send data correctly (UDP) and produced error code: ", WSAGetLastError(), "\n"); return false; } return true; } } std::size_t SocketWindows::peek_receive_size() { using namespace am::net::transmission; std::string buffer; if(this->get_info().transmission_protocol == protocol::TCP) { if (this->connection_handle == INVALID_SOCKET) { /*AMETHYST_DEBUG_PRINT( "SocketWindows::receive(...) was invoked (TCP) but has not accepted an incoming connection. Aborting...");*/ am::debug::print("SocketWindows::receive(...) was invoked (TCP) but has not accepted an incoming connection.\n"); return 0; } buffer.resize(am::net::consts::maximum_tcp_packet_size); int result = ::recv(this->connection_handle, buffer.data(), buffer.size(), MSG_PEEK); if (result == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::receive(...) could not receive data properly (TCP) and produced error code ") + std::to_string(WSAGetLastError())).c_str()); am::debug::print("SocketWindows::receive(...) could not receive data properly (TCP) and produced error code: ", WSAGetLastError(), "\n"); return 0; } return result; } else // UDP Receive { buffer.resize(am::net::consts::maximum_udp_packet_size); int result = recvfrom(this->socket_handle, buffer.data(), buffer.size(), MSG_PEEK, nullptr, nullptr); if(result == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::receive(...) could not receive data properly (UDP) and produced error code ") + std::to_string(WSAGetLastError())).c_str()); am::debug::print("SocketWindows::receive(...) could not receive data properly (UDP) and produced error code: ", WSAGetLastError(), "\n"); return 0; } return result; } } std::optional<std::string> SocketWindows::receive(std::size_t buffer_size) { using namespace am::net::transmission; std::string buffer; buffer.resize(buffer_size); if(this->get_info().transmission_protocol == protocol::TCP) { if (this->connection_handle == INVALID_SOCKET) { /*AMETHYST_DEBUG_PRINT( "SocketWindows::receive(...) was invoked (TCP) but has not accepted an incoming connection. Aborting...");*/ am::debug::print("SocketWindows::receive(...) was invoked (TCP) but has not accepted an incoming connection.\n"); return std::nullopt; } int result = ::recv(this->connection_handle, buffer.data(), buffer_size, 0); if (result == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::receive(...) could not receive data properly (TCP) and produced error code ") + std::to_string(WSAGetLastError())).c_str()); am::debug::print("SocketWindows::receive(...) could not receive data properly (TCP) and produced error code: ", WSAGetLastError(), "\n"); return std::nullopt; } return buffer; } else // UDP Receive { int result = recvfrom(this->socket_handle, buffer.data(), buffer_size, 0, nullptr, nullptr); if(result == SOCKET_ERROR) { //AMETHYST_DEBUG_PRINT((std::string("SocketWindows::receive(...) could not receive data properly (UDP) and produced error code ") + std::to_string(WSAGetLastError())).c_str()); am::debug::print("SocketWindows::receive(...) could not receive data properly (UDP) and produced error code: ", WSAGetLastError(), "\n"); return std::nullopt; } return buffer; } } std::optional<std::string> SocketWindows::receive_boundless() { return this->receive(this->peek_receive_size()); } bool SocketWindows::unbind() { return closesocket(this->socket_handle) == 0; } #elif AMETHYST_UNIX SocketUnix::SocketUnix(SocketDescriptor descriptor): ISocket(descriptor), socket_handle(-1) { using namespace am::net; int af; switch(this->descriptor.internet_protocol) { case internet::protocol::IPV4: default: af = AF_INET; break; case internet::protocol::IPV6: af = AF_INET6; break; } int type; switch(this->descriptor.transmission_protocol) { case transmission::protocol::TCP: default: type = SOCK_STREAM; break; case transmission::protocol::UDP: type = SOCK_DGRAM; break; } this->socket_handle = socket(af, type, 0); AMETHYST_DEBUG_PRINT((std::string("SocketUnix::SocketUnix(...) Initialisation Error Code: ") + strerror(errno)).c_str()); } bool SocketUnix::bind(unsigned int port) { // TODO: Implement } #endif
43.477612
222
0.57082
Harrand
5c7bb3a079dcd91bec6adbbfd9be63e19f32225e
9,550
cpp
C++
mbed-glove-firmware/drivers/at42qt1070.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
null
null
null
mbed-glove-firmware/drivers/at42qt1070.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
null
null
null
mbed-glove-firmware/drivers/at42qt1070.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
1
2019-01-09T05:16:42.000Z
2019-01-09T05:16:42.000Z
/* * Author: Jon Trulson <jtrulson@ics.com> * Copyright (c) 2015 Intel Corporation. * * 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. */ //#include <unistd.h> #include <math.h> #include <string> #include <stdexcept> #include "at42qt1070.h" using namespace std; const uint8_t AVE_KEY_MAX = 6; const uint8_t AKS_KEY_MAX = 3; const uint8_t NO_GUARD_KEY = 7; AT42QT1070::AT42QT1070(PinName sda, PinName scl, uint8_t address) : _i2c(sda, scl), _addr(address << 1) { initialize(); } AT42QT1070::AT42QT1070(I2C& i2c, uint8_t address) : _i2c(i2c), _addr(address << 1) { initialize(); } void AT42QT1070::initialize() { _i2c.frequency(AT42QT1070_I2C_MAX_FREQUENCY); // spec list <230ms as boot up time, wait here to be sure wait_ms(230); reset(); wait_ms(230); if (readChipID() != 0x2E) { return; // throw std::runtime_error("Chip ID does not match the // expected value (2Eh)"); } _buttonStates = 0; _calibrating = false; _overflow = false; } //-------------------------------------------------------------------------------- AT42QT1070::~AT42QT1070() { _i2c.stop(); } //-------------------------------------------------------------------------------- bool AT42QT1070::writeByte(uint8_t reg, uint8_t byte) { const char cmd[] = { reg, byte }; if (0 == _i2c.write(_addr, cmd, 2)) return true; else return false; } //-------------------------------------------------------------------------------- bool AT42QT1070::writeWord(uint8_t reg, uint16_t word) { const char cmd[] = { reg, word & 0xff, (word & 0xff00) >> 8 }; if (0 == _i2c.write(_addr, cmd, 3)) return true; else return false; } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::readByte(uint8_t reg) { char data = 0; const char cmd = reg; _i2c.write(_addr, &cmd, 1); _i2c.read(_addr, &data, 1); return data; } //-------------------------------------------------------------------------------- uint16_t AT42QT1070::readWord(uint8_t reg) { uint16_t res = 0; char data[] = { 0, 0 }; const char cmd = reg; _i2c.write(_addr, &cmd, 1); _i2c.read(_addr, data, 2); res = data[1] << 8 & data[0]; return res; } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::readChipID(void) { return readByte(REG_CHIPID); } //-------------------------------------------------------------------------------- void AT42QT1070::updateState() { uint8_t status = readByte(REG_DETSTATUS); // if we are calibrating, don't change anything if (status & DET_CALIBRATE) { _calibrating = true; return; } else { _calibrating = false; } if (status & DET_OVERFLOW) _overflow = true; else _overflow = false; // if a touch is occurring, read the button states if (status & DET_TOUCH) { uint8_t keys = readByte(REG_KEYSTATUS); // high bit is reserved, filter it out _buttonStates = keys & ~0x80; } else { _buttonStates = 0; } } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getButtonsState() { uint8_t status = readByte(REG_DETSTATUS); uint8_t keys = readByte(REG_KEYSTATUS); // if we are calibrating, don't change anything if (status & DET_CALIBRATE) { _calibrating = true; return 0; } // Old library only read buttons if one of them was touched. // We want to read either way so that change line gets reset. // Therefore read command has been moved outside of if statement. if (status & DET_TOUCH) { // high bit is reserved, filter it out _buttonStates = keys & ~0x80; } else { _buttonStates = 0; } // set the top bit in _buttonStates to signal overflow if (status & DET_OVERFLOW) { _buttonStates |= 0x80; } return _buttonStates; } //-------------------------------------------------------------------------------- bool AT42QT1070::isButtonPressed(const uint8_t button) { uint8_t buttonsState = 0; if (button <= 6) { buttonsState = getButtonsState(); } return (buttonsState & (0x1 << button)); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getLowPowerMode(void) { return readByte(REG_LP); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setLowPowerMode(uint8_t mode) { writeByte(REG_LP, mode); return getLowPowerMode(); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getMaxOn(void) { return readByte(REG_MAXON); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setMaxOn(uint8_t maxon) { writeByte(REG_MAXON, maxon); return getMaxOn(); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getAVE(uint8_t key) { uint8_t value = 0; uint8_t ave = 0; if (key <= AVE_KEY_MAX) { value = readByte(REG_AVE0 + key); ave = (value & 0xFC) >> 2; } return ave; } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setAVE(uint8_t key, uint8_t ave) { uint8_t value = 0; // if (key > AVE_KEY_MAX) { // throw std::invalid_argument("Only keys 0-6 are allowed"); // } // switch (ave) { // case 1: // case 2: // case 4: // case 8: // case 16: // case 32: // break; // default: // throw std::invalid_argument("Invalid averaging factor"); // } value = readByte(REG_AVE0 + key); value = value & 0x03; value = value | (ave << 2); writeByte(REG_AVE0 + key, value); return getAVE(key); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getAKSGroup(uint8_t key) { uint8_t value = 0; uint8_t aks = 0; if (key <= AKS_KEY_MAX) { value = readByte(REG_AVE0 + key); aks = value & 0x03; } return aks; } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setAKSGroup(uint8_t key, uint8_t group) { uint8_t value = 0; if (key <= AVE_KEY_MAX && group <= AKS_KEY_MAX) { value = readByte(REG_AVE0 + key); value = value & 0xFC; value = value | group; writeByte(REG_AVE0 + key, value); } return getAKSGroup(key); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getDetectionIntegrator(uint8_t key) { if (key <= AKS_KEY_MAX) { return readByte(REG_DI0 + key); } } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setDetectionIntegrator(uint8_t key, uint8_t di) { if (key <= AVE_KEY_MAX) { writeByte(REG_DI0 + key, di); } return getDetectionIntegrator(key); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::getThreshold(uint8_t key) { if (key <= AKS_KEY_MAX) { return readByte(REG_NTHR0 + key); } } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setThreshold(uint8_t key, uint8_t nthr) { if (key <= AVE_KEY_MAX) { writeByte(REG_NTHR0 + key, nthr); } return getThreshold(key); } //-------------------------------------------------------------------------------- uint8_t AT42QT1070::setGuard(uint8_t key=NO_GUARD_KEY) { // TODO add setters for FO/MaxCal instead of clearing here if (key <= AVE_KEY_MAX || key == NO_GUARD_KEY) { writeByte(REG_GUARD, (0x0f) & key); } return (0x0f) & readByte(REG_GUARD); } //-------------------------------------------------------------------------------- bool AT42QT1070::reset() { // write a non-zero value to the reset register return writeByte(REG_RESET, 0xff); } //-------------------------------------------------------------------------------- bool AT42QT1070::calibrate() { // write a non-zero value to the calibrate register return writeByte(REG_CALIBRATE, 0xff); }
28.939394
82
0.500942
apadin1
5c7ddbf91283a9e5d26814228365b6123f003308
18
cpp
C++
old/dpd_cpp/dpdIn.cpp
brix4dayz/dpd_cpp
6156b9011f7fa529972620a9e949f1ff858f3a28
[ "MIT" ]
null
null
null
old/dpd_cpp/dpdIn.cpp
brix4dayz/dpd_cpp
6156b9011f7fa529972620a9e949f1ff858f3a28
[ "MIT" ]
7
2015-11-23T19:17:06.000Z
2016-03-02T20:55:29.000Z
old/dpd_cpp/dpdIn.cpp
brix4dayz/dpd_cpp
6156b9011f7fa529972620a9e949f1ff858f3a28
[ "MIT" ]
null
null
null
#include "dpdIn.h"
18
18
0.722222
brix4dayz
5c7f01471c4e4eddbeff7cc9d5213d0319069cd2
1,443
hh
C++
XRADBasic/Sources/Containers/RealFunction.hh
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
1
2021-04-02T16:47:00.000Z
2021-04-02T16:47:00.000Z
XRADBasic/Sources/Containers/RealFunction.hh
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
null
null
null
XRADBasic/Sources/Containers/RealFunction.hh
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
3
2021-08-30T11:26:23.000Z
2021-09-23T09:39:56.000Z
/* Copyright (c) 2021, Moscow Center for Diagnostics & Telemedicine All rights reserved. This file is licensed under BSD-3-Clause license. See LICENSE file for details. */ // file RealFunction.hh //-------------------------------------------------------------- #ifndef XRAD__File_RealFunction_cc #define XRAD__File_RealFunction_cc //-------------------------------------------------------------- #include "UniversalInterpolation.h" XRAD_BEGIN //-------------------------------------------------------------- // // Интерполяция // //-------------------------------------------------------------- template<XRAD__RealFunction_template> auto RealFunction<XRAD__RealFunction_template_args>::in(double x) const -> floating64_type<value_type> { interpolators::icubic.ApplyOffsetCorrection(x); const FilterKernelReal *filter = interpolators::icubic.GetNeededFilter(x); return filter->Apply((*this), integral_part(x)); } template<XRAD__RealFunction_template> auto RealFunction<XRAD__RealFunction_template_args>::d_dx(double x) const -> floating64_type<value_type> { interpolators::sinc_derivative.ApplyOffsetCorrection(x); const FilterKernelReal *filter = interpolators::sinc_derivative.GetNeededFilter(x); return filter->Apply((*this), integral_part(x)); } //-------------------------------------------------------------- XRAD_END //-------------------------------------------------------------- #endif // XRAD__File_RealFunction_cc
32.795455
104
0.586279
n-kulberg
5c8205a2eaadae8a73b6b9947801857862681897
11,036
hpp
C++
include/reactive/json/parser.hpp
ReactiveFramework/Reactive
b1e7e2a7d1dfaaef6cc372ae88111f36a42a304a
[ "MIT" ]
3
2015-03-31T23:09:12.000Z
2017-05-17T07:23:53.000Z
include/reactive/json/parser.hpp
ReactiveFramework/Reactive
b1e7e2a7d1dfaaef6cc372ae88111f36a42a304a
[ "MIT" ]
null
null
null
include/reactive/json/parser.hpp
ReactiveFramework/Reactive
b1e7e2a7d1dfaaef6cc372ae88111f36a42a304a
[ "MIT" ]
2
2015-11-06T20:29:49.000Z
2021-09-07T11:08:08.000Z
/** * Reactive * * (c) 2012-2014 Axel Etcheverry * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #pragma once #include <limits> #include <string> #include <inttypes.h> #include <reactive/json/func.hpp> namespace reactive { namespace json { template <typename Iter> class parser { protected: Iter m_cur; Iter m_end; int m_last_ch; bool m_ungot; int m_line; public: parser(const Iter& first_, const Iter& last_) : m_cur(first_), m_end(last_), m_last_ch(-1), m_ungot(false), m_line(1) { } int getc() { if (m_ungot) { m_ungot = false; return m_last_ch; } if (m_cur == m_end) { m_last_ch = -1; return -1; } if (m_last_ch == '\n') { m_line++; } m_last_ch = *m_cur & 0xff; ++m_cur; return m_last_ch; } void ungetc() { if (m_last_ch != -1) { JSON_ASSERT(!m_ungot); m_ungot = true; } } inline Iter cur() const { return m_cur; } inline int line() const { return m_line; } void skipWs() { while (1) { int ch = getc(); if (! (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) { ungetc(); break; } } } bool expect(int expect_) { skipWs(); if (getc() != expect_) { ungetc(); return false; } return true; } bool match(const std::string& pattern_) { for (std::string::const_iterator pi(pattern_.begin()); pi != pattern_.end(); ++pi) { if (getc() != *pi) { ungetc(); return false; } } return true; } }; template<typename Iter> inline int _parse_quadhex(parser<Iter> &in_) { int uni_ch = 0, hex; for (int i = 0; i < 4; i++) { if ((hex = in_.getc()) == -1) { return -1; } if ('0' <= hex && hex <= '9') { hex -= '0'; } else if ('A' <= hex && hex <= 'F') { hex -= 'A' - 0xa; } else if ('a' <= hex && hex <= 'f') { hex -= 'a' - 0xa; } else { in_.ungetc(); return -1; } uni_ch = uni_ch * 16 + hex; } return uni_ch; } template<typename String, typename Iter> inline bool _parse_codepoint(String& out, parser<Iter>& in) { int uni_ch; if ((uni_ch = _parse_quadhex(in)) == -1) { return false; } if (0xd800 <= uni_ch && uni_ch <= 0xdfff) { if (0xdc00 <= uni_ch) { // a second 16-bit of a surrogate pair appeared return false; } // first 16-bit of surrogate pair, get the next one if (in.getc() != '\\' || in.getc() != 'u') { in.ungetc(); return false; } int second = _parse_quadhex(in); if (!(0xdc00 <= second && second <= 0xdfff)) { return false; } uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff); uni_ch += 0x10000; } if (uni_ch < 0x80) { out.push_back(uni_ch); } else { if (uni_ch < 0x800) { out.push_back(0xc0 | (uni_ch >> 6)); } else { if (uni_ch < 0x10000) { out.push_back(0xe0 | (uni_ch >> 12)); } else { out.push_back(0xf0 | (uni_ch >> 18)); out.push_back(0x80 | ((uni_ch >> 12) & 0x3f)); } out.push_back(0x80 | ((uni_ch >> 6) & 0x3f)); } out.push_back(0x80 | (uni_ch & 0x3f)); } return true; } template<typename String, typename Iter> inline bool _parse_string(String& out, parser<Iter>& in) { while (1) { int ch = in.getc(); if (ch < ' ') { in.ungetc(); return false; } else if (ch == '"') { return true; } else if (ch == '\\') { if ((ch = in.getc()) == -1) { return false; } switch (ch) { #define MAP(sym, val) case sym: out.push_back(val); break MAP('"', '\"'); MAP('\\', '\\'); MAP('/', '/'); MAP('b', '\b'); MAP('f', '\f'); MAP('n', '\n'); MAP('r', '\r'); MAP('t', '\t'); #undef MAP case 'u': if (!_parse_codepoint(out, in)) { return false; } break; default: return false; } } else { out.push_back(ch); } } return false; } template <typename Context, typename Iter> inline bool _parse_array(Context& ctx, parser<Iter>& in) { if (!ctx.parseArrayStart()) { return false; } std::size_t idx = 0; if (in.expect(']')) { return ctx.parseArrayStop(idx); } do { if (!ctx.parseArrayItem(in, idx)) { return false; } idx++; } while (in.expect(',')); return in.expect(']') && ctx.parseArrayStop(idx); } template <typename Context, typename Iter> inline bool _parse_object(Context& ctx, parser<Iter>& in) { if (!ctx.parseObjectStart()) { return false; } if (in.expect('}')) { return true; } do { std::string key; if (!in.expect('"') || !_parse_string(key, in) || !in.expect(':')) { return false; } if (!ctx.parseObjectItem(in, key)) { return false; } } while (in.expect(',')); return in.expect('}'); } template <typename Iter> inline std::string _parse_number(parser<Iter>& in) { std::string num_str; while (1) { int ch = in.getc(); if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' || ch == 'e' || ch == 'E') { num_str.push_back(ch); } else if (ch == '.') { num_str.push_back('.'); } else { in.ungetc(); break; } } return num_str; } template <typename Context, typename Iter> inline bool _parse(Context& ctx, parser<Iter>& in) { in.skipWs(); int ch = in.getc(); switch (ch) { #define IS(ch, text, op) case ch: \ if (in.match(text) && op) \ { \ return true; \ } \ else \ { \ return false; \ } IS('n', "ull", ctx.setNull()); IS('f', "alse", ctx.setBool(false)); IS('t', "rue", ctx.setBool(true)); #undef IS case '"': return ctx.parseString(in); case '[': return _parse_array(ctx, in); case '{': return _parse_object(ctx, in); default: if (('0' <= ch && ch <= '9') || ch == '-') { double f; char *endp; in.ungetc(); std::string num_str = _parse_number(in); if (num_str.empty()) { return false; } { errno = 0; intmax_t ival = strtoimax(num_str.c_str(), &endp, 10); if ( (errno == 0) && (std::numeric_limits<int64_t>::min() <= ival) && (ival <= std::numeric_limits<int64_t>::max()) && (endp == (num_str.c_str() + num_str.size())) ) { ctx.setInt64(ival); return true; } } f = strtod(num_str.c_str(), &endp); if (endp == (num_str.c_str() + num_str.size())) { ctx.setNumber(f); return true; } return false; } break; } in.ungetc(); return false; } template <typename Context, typename Iter> inline Iter _parse(Context& ctx, const Iter& first, const Iter& last, std::string* err) { parser<Iter> in(first, last); if (!_parse(ctx, in) && err != NULL) { char buf[64]; snprintf(buf, sizeof(buf), "syntax error at line %d near: ", in.line()); *err = buf; while (1) { int ch = in.getc(); if (ch == -1 || ch == '\n') { break; } else if (ch >= ' ') { err->push_back(ch); } } } return in.cur(); } } // end of json namespace } // end of reactive namespace
23.682403
94
0.339888
ReactiveFramework
5c828294f4a2698817b3347908ef9d7678707e70
6,796
cpp
C++
Engine/Source/Runtime/Renderer/Private/PostProcess/PostProcessNoiseBlur.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/Renderer/Private/PostProcess/PostProcessNoiseBlur.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/Renderer/Private/PostProcess/PostProcessNoiseBlur.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*============================================================================= PostProcessNoiseBlur.cpp: Post processing down sample implementation. =============================================================================*/ #include "PostProcess/PostProcessNoiseBlur.h" #include "StaticBoundShaderState.h" #include "SceneUtils.h" #include "PostProcess/SceneRenderTargets.h" #include "PostProcess/SceneFilterRendering.h" #include "SceneRenderTargetParameters.h" #include "PostProcess/PostProcessing.h" #include "ClearQuad.h" #include "PipelineStateCache.h" /** Encapsulates the post processing noise blur shader. */ template <uint32 Method> class FPostProcessNoiseBlurPS : public FGlobalShader { DECLARE_SHADER_TYPE(FPostProcessNoiseBlurPS, Global); static bool ShouldCache(EShaderPlatform Platform) { return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4); } static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment) { FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment); OutEnvironment.SetDefine(TEXT("METHOD"), Method); } /** Default constructor. */ FPostProcessNoiseBlurPS() {} public: FPostProcessPassParameters PostprocessParameter; FDeferredPixelShaderParameters DeferredParameters; FShaderParameter NoiseParams; /** Initialization constructor. */ FPostProcessNoiseBlurPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FGlobalShader(Initializer) { PostprocessParameter.Bind(Initializer.ParameterMap); DeferredParameters.Bind(Initializer.ParameterMap); NoiseParams.Bind(Initializer.ParameterMap, TEXT("NoiseParams")); } // FShader interface. virtual bool Serialize(FArchive& Ar) override { bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar); Ar << PostprocessParameter << DeferredParameters << NoiseParams; return bShaderHasOutdatedParameters; } template <typename TRHICmdList> void SetParameters(TRHICmdList& RHICmdList, const FRenderingCompositePassContext& Context, float InRadius) { const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader(); FGlobalShader::SetParameters<FViewUniformShaderParameters>(RHICmdList, ShaderRHI, Context.View.ViewUniformBuffer); DeferredParameters.Set(RHICmdList, ShaderRHI, Context.View, MD_PostProcess); PostprocessParameter.SetPS(RHICmdList, ShaderRHI, Context, TStaticSamplerState<SF_Bilinear, AM_Border, AM_Border, AM_Border>::GetRHI()); { FVector4 ColorScale(InRadius, 0, 0, 0); SetShaderValue(RHICmdList, ShaderRHI, NoiseParams, ColorScale); } } static const TCHAR* GetSourceFilename() { return TEXT("/Engine/Private/PostProcessNoiseBlur.usf"); } static const TCHAR* GetFunctionName() { return TEXT("MainPS"); } }; // #define avoids a lot of code duplication #define VARIATION1(A) typedef FPostProcessNoiseBlurPS<A> FPostProcessNoiseBlurPS##A; \ IMPLEMENT_SHADER_TYPE2(FPostProcessNoiseBlurPS##A, SF_Pixel); VARIATION1(0) VARIATION1(1) VARIATION1(2) #undef VARIATION1 FRCPassPostProcessNoiseBlur::FRCPassPostProcessNoiseBlur(float InRadius, EPixelFormat InOverrideFormat, uint32 InQuality) : Radius(InRadius) , Quality(InQuality) , OverrideFormat(InOverrideFormat) { } template <uint32 Method> static void SetNoiseBlurShader(const FRenderingCompositePassContext& Context, float InRadius) { FGraphicsPipelineStateInitializer GraphicsPSOInit; Context.RHICmdList.ApplyCachedRenderTargets(GraphicsPSOInit); GraphicsPSOInit.BlendState = TStaticBlendState<>::GetRHI(); GraphicsPSOInit.RasterizerState = TStaticRasterizerState<>::GetRHI(); GraphicsPSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_Always>::GetRHI(); TShaderMapRef<FPostProcessVS> VertexShader(Context.GetShaderMap()); TShaderMapRef<FPostProcessNoiseBlurPS<Method> > PixelShader(Context.GetShaderMap()); GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = GFilterVertexDeclaration.VertexDeclarationRHI; GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader); GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader); GraphicsPSOInit.PrimitiveType = PT_TriangleList; SetGraphicsPipelineState(Context.RHICmdList, GraphicsPSOInit); PixelShader->SetParameters(Context.RHICmdList, Context, InRadius); VertexShader->SetParameters(Context); } void FRCPassPostProcessNoiseBlur::Process(FRenderingCompositePassContext& Context) { SCOPED_DRAW_EVENT(Context.RHICmdList, NoiseBlur); const FPooledRenderTargetDesc* InputDesc = GetInputDesc(ePId_Input0); if(!InputDesc) { // input is not hooked up correctly return; } const FSceneView& View = Context.View; const FSceneViewFamily& ViewFamily = *(View.Family); FIntPoint SrcSize = InputDesc->Extent; FIntPoint DestSize = PassOutputs[0].RenderTargetDesc.Extent; // e.g. 4 means the input texture is 4x smaller than the buffer size uint32 ScaleFactor = FSceneRenderTargets::Get(Context.RHICmdList).GetBufferSizeXY().X / SrcSize.X; FIntRect SrcRect = View.ViewRect / ScaleFactor; FIntRect DestRect = SrcRect; const FSceneRenderTargetItem& DestRenderTarget = PassOutputs[0].RequestSurface(Context); // Set the view family's render target/viewport. SetRenderTarget(Context.RHICmdList, DestRenderTarget.TargetableTexture, FTextureRHIRef()); // is optimized away if possible (RT size=view size, ) DrawClearQuad(Context.RHICmdList, true, FLinearColor(0, 0, 0, 0), false, 0, false, 0, PassOutputs[0].RenderTargetDesc.Extent, DestRect); Context.SetViewportAndCallRHI(0, 0, 0.0f, DestSize.X, DestSize.Y, 1.0f ); if(Quality == 0) { SetNoiseBlurShader<0>(Context, Radius); } else if(Quality == 1) { SetNoiseBlurShader<1>(Context, Radius); } else { SetNoiseBlurShader<2>(Context, Radius); } TShaderMapRef<FPostProcessVS> VertexShader(Context.GetShaderMap()); DrawPostProcessPass( Context.RHICmdList, DestRect.Min.X, DestRect.Min.Y, DestRect.Width(), DestRect.Height(), SrcRect.Min.X, SrcRect.Min.Y, SrcRect.Width(), SrcRect.Height(), DestSize, SrcSize, *VertexShader, View.StereoPass, Context.HasHmdMesh(), EDRF_UseTriangleOptimization); Context.RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams()); } FPooledRenderTargetDesc FRCPassPostProcessNoiseBlur::ComputeOutputDesc(EPassOutputId InPassOutputId) const { FPooledRenderTargetDesc Ret = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc; Ret.Reset(); if(OverrideFormat != PF_Unknown) { Ret.Format = OverrideFormat; } Ret.TargetableFlags &= ~TexCreate_UAV; Ret.TargetableFlags |= TexCreate_RenderTargetable; Ret.DebugName = TEXT("NoiseBlur"); return Ret; }
32.673077
141
0.779429
windystrife
5c8882edac9f0e74dddd984188bd1ce83f1b1144
543
cpp
C++
LeetCode/921.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
7
2019-02-25T13:15:00.000Z
2021-12-21T22:08:39.000Z
LeetCode/921.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
null
null
null
LeetCode/921.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
1
2019-04-03T06:12:46.000Z
2019-04-03T06:12:46.000Z
class Solution { public: int minAddToMakeValid(string S) { int len = S.size(); int leftAns = 0;//左侧添加左括号数量 int stack = 0;//模拟栈,栈里放左括号,遇到右括号就出栈一个 for(int i=0;i<len;i++) { if(S[i]=='(') { stack++; } else { if(stack==0) leftAns++; else stack--; } } stack = 0;//清空模拟栈,栈里放右括号,遇到左括号就出栈一个 int rightAns = 0;//右侧添加右括号数量 for(int i=len-1;i>=0;i--) { if(S[i]==')') { stack++; } else { if(stack==0) rightAns++; else stack--; } } return leftAns + rightAns; } };
17.516129
39
0.508287
LauZyHou
5c8af8e5c95364b69a355d9d39cc1ac9ee93bd89
6,391
cpp
C++
lib/ESP8266Audio-master/src/AudioOutputFilterBiquad.cpp
ChSt98/KraftPad
2f1d60893ded6d0f079e8067980016992a72794b
[ "BSD-3-Clause" ]
null
null
null
lib/ESP8266Audio-master/src/AudioOutputFilterBiquad.cpp
ChSt98/KraftPad
2f1d60893ded6d0f079e8067980016992a72794b
[ "BSD-3-Clause" ]
null
null
null
lib/ESP8266Audio-master/src/AudioOutputFilterBiquad.cpp
ChSt98/KraftPad
2f1d60893ded6d0f079e8067980016992a72794b
[ "BSD-3-Clause" ]
null
null
null
/* AudioOutputFilterBiquad Implements a Biquad filter Copyright (C) 2012 Nigel Redmon Copyright (C) 2021 William Bérubé 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 <http://www.gnu.org/licenses/>. */ #include <Arduino.h> #include "AudioOutputFilterBiquad.h" AudioOutputFilterBiquad::AudioOutputFilterBiquad(AudioOutput *sink) { this->sink = sink; type = bq_type_lowpass; a0 = 1.0; a1 = a2 = b1 = b2 = 0.0; Fc = 0.50; Q = 0.707; peakGain = 0.0; z1 = z2 = 0.0; } AudioOutputFilterBiquad::AudioOutputFilterBiquad(int type, float Fc, float Q, float peakGain, AudioOutput *sink) { this->sink = sink; SetBiquad(type, Fc, Q, peakGain); z1 = z2 = 0.0; } AudioOutputFilterBiquad::~AudioOutputFilterBiquad() {} bool AudioOutputFilterBiquad::SetRate(int hz) { return sink->SetRate(hz); } bool AudioOutputFilterBiquad::SetBitsPerSample(int bits) { return sink->SetBitsPerSample(bits); } bool AudioOutputFilterBiquad::SetChannels(int channels) { return sink->SetChannels(channels); } bool AudioOutputFilterBiquad::SetGain(float gain) { return sink->SetGain(gain); } void AudioOutputFilterBiquad::SetType(int type) { this->type = type; CalcBiquad(); } void AudioOutputFilterBiquad::SetFc(float Fc) { this->Fc = Fc; CalcBiquad(); } void AudioOutputFilterBiquad::SetQ(float Q) { this->Q = Q; CalcBiquad(); } void AudioOutputFilterBiquad::SetPeakGain(float peakGain) { this->peakGain = peakGain; CalcBiquad(); } void AudioOutputFilterBiquad::SetBiquad(int type, float Fc, float Q, float peakGain) { this->type = type; this->Fc = Fc; this->Q = Q; this->peakGain = peakGain; CalcBiquad(); } void AudioOutputFilterBiquad::CalcBiquad() { float norm; float V = pow(10, fabs(peakGain) / 20.0); float K = tan(M_PI * Fc); switch (this->type) { case bq_type_lowpass: norm = 1 / (1 + K / Q + K * K); a0 = K * K * norm; a1 = 2 * a0; a2 = a0; b1 = 2 * (K * K - 1) * norm; b2 = (1 - K / Q + K * K) * norm; break; case bq_type_highpass: norm = 1 / (1 + K / Q + K * K); a0 = 1 * norm; a1 = -2 * a0; a2 = a0; b1 = 2 * (K * K - 1) * norm; b2 = (1 - K / Q + K * K) * norm; break; case bq_type_bandpass: norm = 1 / (1 + K / Q + K * K); a0 = K / Q * norm; a1 = 0; a2 = -a0; b1 = 2 * (K * K - 1) * norm; b2 = (1 - K / Q + K * K) * norm; break; case bq_type_notch: norm = 1 / (1 + K / Q + K * K); a0 = (1 + K * K) * norm; a1 = 2 * (K * K - 1) * norm; a2 = a0; b1 = a1; b2 = (1 - K / Q + K * K) * norm; break; case bq_type_peak: if (peakGain >= 0) { // boost norm = 1 / (1 + 1/Q * K + K * K); a0 = (1 + V/Q * K + K * K) * norm; a1 = 2 * (K * K - 1) * norm; a2 = (1 - V/Q * K + K * K) * norm; b1 = a1; b2 = (1 - 1/Q * K + K * K) * norm; } else { // cut norm = 1 / (1 + V/Q * K + K * K); a0 = (1 + 1/Q * K + K * K) * norm; a1 = 2 * (K * K - 1) * norm; a2 = (1 - 1/Q * K + K * K) * norm; b1 = a1; b2 = (1 - V/Q * K + K * K) * norm; } break; case bq_type_lowshelf: if (peakGain >= 0) { // boost norm = 1 / (1 + sqrt(2) * K + K * K); a0 = (1 + sqrt(2*V) * K + V * K * K) * norm; a1 = 2 * (V * K * K - 1) * norm; a2 = (1 - sqrt(2*V) * K + V * K * K) * norm; b1 = 2 * (K * K - 1) * norm; b2 = (1 - sqrt(2) * K + K * K) * norm; } else { // cut norm = 1 / (1 + sqrt(2*V) * K + V * K * K); a0 = (1 + sqrt(2) * K + K * K) * norm; a1 = 2 * (K * K - 1) * norm; a2 = (1 - sqrt(2) * K + K * K) * norm; b1 = 2 * (V * K * K - 1) * norm; b2 = (1 - sqrt(2*V) * K + V * K * K) * norm; } break; case bq_type_highshelf: if (peakGain >= 0) { // boost norm = 1 / (1 + sqrt(2) * K + K * K); a0 = (V + sqrt(2*V) * K + K * K) * norm; a1 = 2 * (K * K - V) * norm; a2 = (V - sqrt(2*V) * K + K * K) * norm; b1 = 2 * (K * K - 1) * norm; b2 = (1 - sqrt(2) * K + K * K) * norm; } else { // cut norm = 1 / (V + sqrt(2*V) * K + K * K); a0 = (1 + sqrt(2) * K + K * K) * norm; a1 = 2 * (K * K - 1) * norm; a2 = (1 - sqrt(2) * K + K * K) * norm; b1 = 2 * (K * K - V) * norm; b2 = (V - sqrt(2*V) * K + K * K) * norm; } break; } i_a0 = a0 * BQ_DECAL; i_a1 = a1 * BQ_DECAL; i_a2 = a2 * BQ_DECAL; i_b1 = b1 * BQ_DECAL; i_b2 = b2 * BQ_DECAL; i_lz1 = i_rz1 = z1 * BQ_DECAL; i_lz2 = i_rz2 = z2 * BQ_DECAL; i_Fc = Fc * BQ_DECAL; i_Q = Q * BQ_DECAL; i_peakGain = peakGain * BQ_DECAL; } bool AudioOutputFilterBiquad::begin() { return sink->begin(); } bool AudioOutputFilterBiquad::ConsumeSample(int16_t sample[2]) { int32_t leftSample = (sample[LEFTCHANNEL] << BQ_SHIFT) / 2; int32_t rightSample = (sample[RIGHTCHANNEL] << BQ_SHIFT) / 2; int64_t leftOutput = ((leftSample * i_a0) >> BQ_SHIFT) + i_lz1; i_lz1 = ((leftSample * i_a1) >> BQ_SHIFT) + i_lz2 - ((i_b1 * leftOutput) >> BQ_SHIFT); i_lz2 = ((leftSample * i_a2) >> BQ_SHIFT) - ((i_b2 * leftOutput) >> BQ_SHIFT); int64_t rightOutput = ((rightSample * i_a0) >> BQ_SHIFT) + i_rz1; i_rz1 = ((rightSample * i_a1) >> BQ_SHIFT) + i_rz2 - ((i_b1 * rightOutput) >> BQ_SHIFT); i_rz2 = ((rightSample * i_a2) >> BQ_SHIFT) - ((i_b2 * rightOutput) >> BQ_SHIFT); int16_t out[2]; out[LEFTCHANNEL] = (int16_t)(leftOutput >> BQ_SHIFT); out[RIGHTCHANNEL] = (int16_t)(rightOutput >> BQ_SHIFT); return sink->ConsumeSample(out); } bool AudioOutputFilterBiquad::stop() { return sink->stop(); }
25.979675
112
0.531216
ChSt98
5c8c9e8e71dc7e6470f831d96531d1c2f58990d0
493
cpp
C++
Strings - Interview Problems/RemoveDuplicateCharacters.cpp
gulatigaurav/Essential-Coding-Problems
6cba54cb4e20ddc44a49f9e7d07eb293c39aa128
[ "MIT" ]
1
2020-07-05T06:30:32.000Z
2020-07-05T06:30:32.000Z
Strings - Interview Problems/RemoveDuplicateCharacters.cpp
gulatigaurav/Essential-Coding-Problems
6cba54cb4e20ddc44a49f9e7d07eb293c39aa128
[ "MIT" ]
null
null
null
Strings - Interview Problems/RemoveDuplicateCharacters.cpp
gulatigaurav/Essential-Coding-Problems
6cba54cb4e20ddc44a49f9e7d07eb293c39aa128
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <unordered_set> using namespace std; string longestSubstring(string s) { unordered_set<int> elements; string out = ""; for (int i = 0; i < s.length(); i++) { if (elements.find(s[i]) == elements.end()) { elements.insert(s[i]); out += s[i]; } } return out; } int main() { string s = "aababcda"; string ans = longestSubstring(s); cout << ans; }
17.607143
50
0.545639
gulatigaurav
5c8d79e38b1f1ef107ff8d6f5f75a83f37d1eab8
635
cpp
C++
Recursion/Recursive Digit Sum.cpp
jordantonni/HackerRank_Algorithms
48c6df9688d4d45e7249c29fd70aba67234c74cd
[ "MIT" ]
null
null
null
Recursion/Recursive Digit Sum.cpp
jordantonni/HackerRank_Algorithms
48c6df9688d4d45e7249c29fd70aba67234c74cd
[ "MIT" ]
null
null
null
Recursion/Recursive Digit Sum.cpp
jordantonni/HackerRank_Algorithms
48c6df9688d4d45e7249c29fd70aba67234c74cd
[ "MIT" ]
null
null
null
// https://www.hackerrank.com/challenges/recursive-digit-sum/problem // Jordan Tonni #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <string> using namespace std; int superDigit(string str) { if(str.length() <= 1) return std::stoi(str); int sd = 0; for(const auto c : str) sd += c - '0'; return superDigit(to_string(sd)); } int main() { string n, p; int k; cin >> n >> k; if(k % 10 != 0){ while(k--) p += n; } else p += n; cout << superDigit(p); return 0; }
15.119048
68
0.525984
jordantonni
5c8e42f0c97aefc173a81baf4072566075df7734
8,944
cpp
C++
audioserver/src/audsrv-conn.cpp
rdkcmf/rdk-audioserver
4a6dcf24161427676359205280c12853e991e6ab
[ "Apache-2.0" ]
null
null
null
audioserver/src/audsrv-conn.cpp
rdkcmf/rdk-audioserver
4a6dcf24161427676359205280c12853e991e6ab
[ "Apache-2.0" ]
null
null
null
audioserver/src/audsrv-conn.cpp
rdkcmf/rdk-audioserver
4a6dcf24161427676359205280c12853e991e6ab
[ "Apache-2.0" ]
null
null
null
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2017 RDK Management * * 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. */ /** * @defgroup audioserver * @{ * @defgroup audsrv-conn * @{ **/ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <pthread.h> #include <unistd.h> #include <sys/file.h> #include <sys/socket.h> #include "audsrv-conn.h" #include "audsrv-logger.h" #include "audsrv-protocol.h" //#define AUDSRV_DUMP_TRAFFIC static void dumpBuffer( unsigned char *p, int len ); AudsrvConn* audsrv_conn_init( int fd, unsigned sendBufferSize, unsigned recvBufferSize ) { AudsrvConn *conn= 0; bool error= true; conn= (AudsrvConn*)calloc( 1, sizeof(AudsrvConn) ); if ( conn ) { conn->fdSocket= fd; conn->sendbuff= (unsigned char*)malloc( sendBufferSize ); if ( !conn->sendbuff ) { ERROR("unable to allocate AudsrvConn send buffer, size %d bytes", sendBufferSize ); goto exit; } conn->sendCapacity= sendBufferSize; conn->recvbuff= (unsigned char*)malloc( recvBufferSize ); if ( !conn->recvbuff ) { ERROR("unable to allocate AudsrvConn receive buffer, size %d bytes", recvBufferSize ); goto exit; } conn->recvCapacity= recvBufferSize; error= false; } else { ERROR("unable allocate new AudsrvConn"); } exit: if ( error ) { audsrv_conn_term( conn ); conn= 0; } return conn; } void audsrv_conn_term( AudsrvConn *conn ) { if ( conn ) { if ( conn->sendbuff ) { free( conn->sendbuff ); conn->sendbuff= 0; } if ( conn->recvbuff ) { free( conn->recvbuff ); conn->recvbuff= 0; } free( conn ); } } int audsrv_conn_put_u16( unsigned char *p, unsigned short n ) { p[0]= (n>>8); p[1]= (n&0xFF); p[2]= 0x00; p[3]= 0x00; return 4; } int audsrv_conn_put_u32( unsigned char *p, unsigned n ) { p[0]= (n>>24); p[1]= (n>>16); p[2]= (n>>8); p[3]= (n&0xFF); return 4; } int audsrv_conn_put_u64( unsigned char *p, unsigned long long n ) { p[0]= (n>>56); p[1]= (n>>48); p[2]= (n>>40); p[3]= (n>>32); p[4]= (n>>24); p[5]= (n>>16); p[6]= (n>>8); p[7]= (n&0xFF); return 8; } int audsrv_conn_put_string( unsigned char *p, const char *s ) { int len= strlen(s)+1; strcpy( (char*)p, s ); return ( (len+3)&~3 ); } int audsrv_conn_send( AudsrvConn *conn, unsigned char *data1, int len1, unsigned char *data2, int len2 ) { int sentLen= 0; if ( data1 && len1 ) { struct msghdr msg; struct iovec iov[2]; int vcount= 1; dumpBuffer( data1, len1 ); iov[0].iov_base= data1; iov[0].iov_len= len1; if ( data2 && len2 ) { vcount= 2; iov[1].iov_base= data2; iov[1].iov_len= len2; } msg.msg_name= NULL; msg.msg_namelen= 0; msg.msg_iov= iov; msg.msg_iovlen= vcount; msg.msg_control= NULL; msg.msg_controllen= 0; msg.msg_flags= 0; do { sentLen= sendmsg( conn->fdSocket, &msg, 0 ); } while ( (sentLen < 0) && (errno == EINTR)); } return sentLen; } void audsrv_conn_get_buffer( AudsrvConn *conn, int maxlen, unsigned char **data, unsigned *datalen ) { unsigned char *start; unsigned avail= 0; if ( conn->count ) { if ( conn->head < conn->tail ) { avail= conn->tail-conn->head; } else { avail= conn->recvCapacity-conn->head; } start= &conn->recvbuff[conn->head]; } if ( avail > 0 ) { if ( avail > maxlen ) avail= maxlen; *data= start; *datalen= avail; conn->head= ((conn->head+avail)%conn->recvCapacity); conn->count -= avail; } else { *data= 0; *datalen= 0; } } void audsrv_conn_get_string( AudsrvConn *conn, char *s ) { unsigned char c; int head= conn->head; int len= 0; int paddedLen, padCount; do { c= conn->recvbuff[head]; head= ((head+1)%conn->recvCapacity); *(s++)= c; ++len; } while( c != 0 ); paddedLen= ((len+3)&~3); padCount= paddedLen-len; head= ((head+padCount)%conn->recvCapacity); conn->head= head; conn->count -= paddedLen; } unsigned audsrv_conn_get_u16( AudsrvConn *conn ) { unsigned n; int head= conn->head; n= conn->recvbuff[head]; head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+3)%conn->recvCapacity); conn->head= head; conn->count -= 4; return n; } unsigned audsrv_conn_get_u32( AudsrvConn *conn ) { unsigned n; int head= conn->head; n= conn->recvbuff[head]; head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); conn->head= head; conn->count -= 4; return n; } unsigned audsrv_conn_peek_u32( AudsrvConn *conn ) { unsigned n; int head= conn->head; n= conn->recvbuff[head]; head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); return n; } unsigned long long audsrv_conn_get_u64( AudsrvConn *conn ) { unsigned long long n; int head= conn->head; n= conn->recvbuff[head]; head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); n= ((n << 8) | conn->recvbuff[head]); head= ((head+1)%conn->recvCapacity); conn->head= head; conn->count -= 8; return n; } void audsrv_conn_skip( AudsrvConn *conn, int n ) { conn->head= ((conn->head+n)%conn->recvCapacity); conn->count -= n; } int audsrv_conn_recv( AudsrvConn *conn ) { struct msghdr msg; struct iovec iov[2]; int vcount; int len= -1; if ( !conn->peerDisconnected && (conn->count < conn->recvCapacity) ) { vcount= 1; if ( conn->tail < conn->head ) { iov[0].iov_base= &conn->recvbuff[conn->tail]; iov[0].iov_len= conn->head-conn->tail; } else if ( conn->tail >= conn->head ) { iov[0].iov_base= &conn->recvbuff[conn->tail]; iov[0].iov_len= conn->recvCapacity-conn->tail; if ( conn->head ) { vcount= 2; iov[1].iov_base= &conn->recvbuff[0]; iov[1].iov_len= conn->head; } } msg.msg_name= NULL; msg.msg_namelen= 0; msg.msg_iov= iov; msg.msg_iovlen= vcount; msg.msg_control= NULL; msg.msg_controllen= 0; msg.msg_flags= 0; do { len= recvmsg( conn->fdSocket, &msg, 0 ); } while ( (len < 0) && (errno == EINTR)); if ( len > 0 ) { conn->count += len; conn->tail= ((conn->tail + len) % conn->recvCapacity); } else { conn->peerDisconnected= true; } } return len; } static void dumpBuffer( unsigned char *p, int len ) { #ifdef AUDSRV_DUMP_TRAFFIC int i, c, col; col= 0; for( i= 0; i < len; ++i ) { if ( col == 0 ) printf("%04X: ", i); c= p[i]; printf("%02X ", c); if ( col == 7 ) printf( " - " ); if ( col == 15 ) printf( "\n" ); ++col; if ( col >= 16 ) col= 0; } if ( col > 0 ) printf("\n"); #else (void)(p); (void)(len); #endif } /** @} */ /** @} */
21.144208
104
0.547742
rdkcmf
5c9bc277b1e705ee679b8e4911895c3e545b7f16
448
cpp
C++
codeforces/1088A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1088A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1088A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// A. Ehab and another construction problem #include <stdio.h> int main(){ int x; scanf("%d\n", &x); bool found = false; for (int b = x; b > 0; --b){ for (int a = b; !found && a > 0; --a){ if (b % a == 0 && a * b > x && a / b < x){ printf("%d %d\n", a, b); found = true; break; } } } if (!found) printf("-1\n"); return 0; }
16.592593
54
0.368304
sgrade
5c9d4c0133a90cd5864de8751376a7d63ec5e2cd
12,129
cpp
C++
src/alarms/Daemon.cpp
CESNET/sysrepo-ietf-alarms
a831b7171724d064e7bc489ecd24a64a25025b26
[ "Apache-2.0" ]
null
null
null
src/alarms/Daemon.cpp
CESNET/sysrepo-ietf-alarms
a831b7171724d064e7bc489ecd24a64a25025b26
[ "Apache-2.0" ]
null
null
null
src/alarms/Daemon.cpp
CESNET/sysrepo-ietf-alarms
a831b7171724d064e7bc489ecd24a64a25025b26
[ "Apache-2.0" ]
null
null
null
#include <string> #include "Daemon.h" #include "Key.h" #include "PurgeFilter.h" #include "ShelfMatch.h" #include "utils/libyang.h" #include "utils/log.h" #include "utils/sysrepo.h" #include "utils/time.h" using namespace std::string_literals; namespace { const auto rpcPrefix = "/sysrepo-ietf-alarms:create-or-update-alarm"; const auto ietfAlarmsModule = "ietf-alarms"; const auto alarmList = "/ietf-alarms:alarms/alarm-list"; const auto alarmListInstances = "/ietf-alarms:alarms/alarm-list/alarm"; const auto purgeRpcPrefix = "/ietf-alarms:alarms/alarm-list/purge-alarms"; const auto alarmInventoryPrefix = "/ietf-alarms:alarms/alarm-inventory"; const auto controlPrefix = "/ietf-alarms:alarms/control"; /** @brief returns number of list instances in the list specified by xPath */ size_t numberOfListInstances(sysrepo::Session& session, const std::string& xPath) { auto data = session.getData(xPath); return data ? data->findXPath(xPath).size() : 0; } void updateAlarmListStats(libyang::DataNode& edit, size_t alarmCount, const std::chrono::time_point<std::chrono::system_clock>& lastChanged) { // number-of-alarms is of type yang:gauge32. If we ever support more than 2^32-1 alarms then we will have to deal with cropping the value. edit.newPath("/ietf-alarms:alarms/alarm-list/number-of-alarms", std::to_string(alarmCount)); edit.newPath("/ietf-alarms:alarms/alarm-list/last-changed", alarms::utils::yangTimeFormat(lastChanged)); } /** @brief Returns node specified by xpath in the tree */ std::optional<libyang::DataNode> activeAlarmExist(sysrepo::Session& session, const std::string& path) { if (auto data = session.getData(path)) { return data->findPath(path); } return std::nullopt; } bool valueChanged(const std::optional<libyang::DataNode>& oldNode, const libyang::DataNode& newNode, const char* leafName) { bool oldLeafExists = oldNode && oldNode->findPath(leafName); bool newLeafExists = newNode.findPath(leafName).has_value(); // leaf was deleted or created if (oldLeafExists != newLeafExists) { return true; } else if (!oldLeafExists && !newLeafExists) { return false; } else { return alarms::utils::childValue(*oldNode, leafName) != alarms::utils::childValue(newNode, leafName); } } /** @brief Checks if we should notify about changes made based on the values changed and current settings in control container */ bool shouldNotifyStatusChange(sysrepo::Session session, const std::optional<libyang::DataNode>& oldNode, const libyang::DataNode& edit) { std::optional<libyang::DataNode> data; std::optional<libyang::DataNode> notifyStatusChangesNode; { alarms::utils::ScopedDatastoreSwitch s(session, sysrepo::Datastore::Running); data = session.getData(controlPrefix); notifyStatusChangesNode = data->findPath(controlPrefix + "/notify-status-changes"s); } bool raised = edit.findPath("is-cleared") && alarms::utils::childValue(edit, "is-cleared") == "false" && valueChanged(oldNode, edit, "is-cleared"); bool cleared = edit.findPath("is-cleared") && alarms::utils::childValue(edit, "is-cleared") == "true" && valueChanged(oldNode, edit, "is-cleared"); auto notifyStatusChangesValue = notifyStatusChangesNode->asTerm().valueStr(); if (cleared || notifyStatusChangesValue == "all-state-changes") { return true; } if (notifyStatusChangesValue == "raise-and-clear") { return raised || cleared; } /* Notifications are sent for status changes equal to or above the specified severity level. * Notifications shall also be sent for state changes that make an alarm less severe than the specified level. */ auto notifySeverityLevelValue = std::get<libyang::Enum>(data->findPath(controlPrefix + "/notify-severity-level"s)->asTerm().value()).value; auto newSeverity = std::get<libyang::Enum>(edit.findPath("perceived-severity")->asTerm().value()).value; if (!oldNode) { return newSeverity >= notifySeverityLevelValue; } auto oldSeverity = std::get<libyang::Enum>(oldNode->findPath("perceived-severity")->asTerm().value()).value; return newSeverity >= notifySeverityLevelValue || (oldSeverity >= notifySeverityLevelValue && newSeverity < notifySeverityLevelValue); } /* @brief Checks if the alarm keys match any entry in ietf-alarms:alarms/control/alarm-shelving. If so, return name of the matched shelf */ std::optional<std::string> shouldBeShelved(sysrepo::Session session, const alarms::Key& key) { alarms::utils::ScopedDatastoreSwitch s(session, sysrepo::Datastore::Running); std::optional<std::string> shelfName; if (auto data = session.getData("/ietf-alarms:alarms/control/alarm-shelving")) { shelfName = findMatchingShelf(key, data->findXPath("/ietf-alarms:alarms/control/alarm-shelving/shelf")); } return shelfName; } } namespace alarms { Daemon::Daemon() : m_connection(sysrepo::Connection{}) , m_session(m_connection.sessionStart(sysrepo::Datastore::Operational)) , m_log(spdlog::get("main")) { utils::ensureModuleImplemented(m_session, ietfAlarmsModule, "2019-09-11", {"alarm-shelving"}); utils::ensureModuleImplemented(m_session, "sysrepo-ietf-alarms", "2022-02-17"); { auto edit = m_session.getContext().newPath(alarmList); updateAlarmListStats(edit, 0, std::chrono::system_clock::now()); m_session.editBatch(edit, sysrepo::DefaultOperation::Merge); m_session.applyChanges(); } m_rpcSub = m_session.onRPCAction(rpcPrefix, [&](sysrepo::Session session, auto, auto, const libyang::DataNode input, auto, auto, auto) { return submitAlarm(session, input); }); m_rpcSub->onRPCAction(purgeRpcPrefix, [&](auto, auto, auto, const libyang::DataNode input, auto, auto, libyang::DataNode output) { return purgeAlarms(input, output); }); m_inventorySub = m_session.onModuleChange( ietfAlarmsModule, [&](auto, auto, auto, auto, auto, auto) { m_session.sendNotification(m_session.getContext().newPath("/ietf-alarms:alarm-inventory-changed", std::nullopt), sysrepo::Wait::No); return sysrepo::ErrorCode::Ok; }, alarmInventoryPrefix, 0, sysrepo::SubscribeOptions::DoneOnly | sysrepo::SubscribeOptions::Passive); } sysrepo::ErrorCode Daemon::submitAlarm(sysrepo::Session rpcSession, const libyang::DataNode& input) { const auto& alarmKey = Key::fromNode(input); const auto severity = std::string(input.findPath("severity").value().asTerm().valueStr()); const bool is_cleared = severity == "cleared"; const auto now = std::chrono::system_clock::now(); auto matchedShelf = shouldBeShelved(m_session, alarmKey); std::string alarmNodePath; if (matchedShelf) { alarmNodePath = "/ietf-alarms:alarms/shelved-alarms/shelved-alarm"; } else { alarmNodePath = "/ietf-alarms:alarms/alarm-list/alarm"; } try { alarmNodePath = matchedShelf ? alarmKey.shelvedAlarmPath() : alarmKey.alarmPath(); m_log->trace("Alarm node: {}", alarmNodePath); } catch (const std::invalid_argument& e) { m_log->debug("submitAlarm exception: {}", e.what()); rpcSession.setErrorMessage(e.what()); return sysrepo::ErrorCode::InvalidArgument; } const auto existingAlarmNode = activeAlarmExist(m_session, alarmNodePath); auto edit = m_session.getContext().newPath(alarmNodePath, std::nullopt, libyang::CreationOptions::Update); if (is_cleared && (!existingAlarmNode || (existingAlarmNode && utils::childValue(*existingAlarmNode, "is-cleared") == "true"))) { // if passing is-cleared=true the alarm either doesn't exist or exists but is inactive (is-cleared=true), do nothing, it's a NOOP return sysrepo::ErrorCode::Ok; } else if (!existingAlarmNode && !matchedShelf) { edit.newPath(alarmNodePath + "/time-created", utils::yangTimeFormat(now)); } edit.newPath(alarmNodePath + "/is-cleared", is_cleared ? "true" : "false", libyang::CreationOptions::Update); if (!is_cleared && (!existingAlarmNode || (existingAlarmNode && utils::childValue(*existingAlarmNode, "is-cleared") == "true"))) { edit.newPath(alarmNodePath + "/last-raised", utils::yangTimeFormat(now)); } if (!is_cleared) { edit.newPath(alarmNodePath + "/perceived-severity", severity, libyang::CreationOptions::Update); } edit.newPath(alarmNodePath + "/alarm-text", std::string{input.findPath("alarm-text").value().asTerm().valueStr()}, libyang::CreationOptions::Update); const auto& editAlarmNode = edit.findPath(alarmNodePath); if (valueChanged(existingAlarmNode, *editAlarmNode, "alarm-text") || valueChanged(existingAlarmNode, *editAlarmNode, "is-cleared") || valueChanged(existingAlarmNode, *editAlarmNode, "perceived-severity")) { edit.newPath(alarmNodePath + "/last-changed", utils::yangTimeFormat(now)); } m_log->trace("Update: {}", std::string(*edit.printStr(libyang::DataFormat::JSON, libyang::PrintFlags::Shrink))); if (!matchedShelf) { updateAlarmListStats(edit, numberOfListInstances(m_session, alarmListInstances) + static_cast<int>(editAlarmNode->findPath("time-created").has_value()), now); } else { edit.newPath(alarmNodePath + "/shelf-name", matchedShelf); } m_session.editBatch(edit, sysrepo::DefaultOperation::Merge); m_session.applyChanges(); if (shouldNotifyStatusChange(m_session, existingAlarmNode, *editAlarmNode)) { m_session.sendNotification(createStatusChangeNotification(alarmNodePath), sysrepo::Wait::No); } return sysrepo::ErrorCode::Ok; } libyang::DataNode Daemon::createStatusChangeNotification(const std::string& alarmNodePath) { static const std::string prefix = "/ietf-alarms:alarm-notification"; libyang::DataNode alarmNode = activeAlarmExist(m_session, alarmNodePath).value(); auto notification = m_session.getContext().newPath(prefix + "/resource", utils::childValue(alarmNode, "resource")); notification.newPath(prefix + "/alarm-type-id", utils::childValue(alarmNode, "alarm-type-id")); notification.newPath(prefix + "/time", utils::childValue(alarmNode, "last-changed")); notification.newPath(prefix + "/alarm-text", utils::childValue(alarmNode, "alarm-text")); if (auto qualifier = utils::childValue(alarmNode, "alarm-type-qualifier"); !qualifier.empty()) { notification.newPath(prefix + "/alarm-type-qualifier", qualifier); } notification.newPath(prefix + "/perceived-severity", utils::childValue(alarmNode, "is-cleared") == "true" ? "cleared" : utils::childValue(alarmNode, "perceived-severity")); return notification; } sysrepo::ErrorCode Daemon::purgeAlarms(const libyang::DataNode& rpcInput, libyang::DataNode output) { const auto now = std::chrono::system_clock::now(); PurgeFilter filter(rpcInput); std::vector<std::string> toDelete; if (auto rootNode = m_session.getData("/ietf-alarms:alarms")) { for (const auto& alarmNode : rootNode->findXPath("/ietf-alarms:alarms/alarm-list/alarm")) { if (filter.matches(alarmNode)) { toDelete.push_back(std::string(alarmNode.path())); } } } if (!toDelete.empty()) { /* FIXME: This does not ensure atomicity of the operation, i.e., keeping alarm-list's number-of-alarms leaf up to date is not synced with the deletion. * At first, the alarms are removed one-by-one and only after all alarms are deleted we update the alarm counter and commit the edit with updated counter. */ utils::removeFromOperationalDS(m_connection, toDelete); auto edit = m_session.getContext().newPath(alarmList); updateAlarmListStats(edit, numberOfListInstances(m_session, alarmListInstances), now); m_session.editBatch(edit, sysrepo::DefaultOperation::Merge); m_session.applyChanges(); } output.newPath(purgeRpcPrefix + "/purged-alarms"s, std::to_string(toDelete.size()), libyang::CreationOptions::Output); return sysrepo::ErrorCode::Ok; } }
46.471264
210
0.704675
CESNET
5c9f3244ed7d678a5693bbf38ff79d7d5ff02087
503
hpp
C++
addons/ai/CfgWaypoints.hpp
Drofseh/TMF
0733ad565b2aeee0ccf0340282ff784ff7f5c39c
[ "Naumen", "Condor-1.1", "MS-PL" ]
43
2016-08-02T19:50:34.000Z
2022-01-29T01:33:35.000Z
addons/ai/CfgWaypoints.hpp
Drofseh/TMF
0733ad565b2aeee0ccf0340282ff784ff7f5c39c
[ "Naumen", "Condor-1.1", "MS-PL" ]
232
2016-08-05T07:57:59.000Z
2022-03-31T01:50:23.000Z
addons/ai/CfgWaypoints.hpp
Drofseh/TMF
0733ad565b2aeee0ccf0340282ff784ff7f5c39c
[ "Naumen", "Condor-1.1", "MS-PL" ]
41
2016-08-03T19:16:40.000Z
2022-01-24T19:11:29.000Z
class CfgWaypoints { class Teamwork { class Fortify { displayName = "Fortify"; file = "\x\tmf\addons\AI\functions\fnc_fortify.sqf"; /* 0: GROUP 1: ARRAY - Waypoint position 2: OBJECT - Target to which waypoint is attached to */ icon = "a3\ui_f\data\igui\cfg\simpletasks\types\defend_ca.paa"; class Attributes { }; }; }; };
23.952381
75
0.459245
Drofseh
5ca1ee8d60fd07cb6eb6a3ad106950b5cef4914d
1,278
cpp
C++
out/production/leetcode/io/github/zhengyhn/leetcode/candy/candy.cpp
zhengyhn/leetcode
2e5e618dd7c964c8e983b187c6b1762cbe1764de
[ "MIT" ]
null
null
null
out/production/leetcode/io/github/zhengyhn/leetcode/candy/candy.cpp
zhengyhn/leetcode
2e5e618dd7c964c8e983b187c6b1762cbe1764de
[ "MIT" ]
null
null
null
out/production/leetcode/io/github/zhengyhn/leetcode/candy/candy.cpp
zhengyhn/leetcode
2e5e618dd7c964c8e983b187c6b1762cbe1764de
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int candy(vector<int>& ratings) { ratings.push_back(ratings[ratings.size() - 1]); int ret = 0; int next = 1; int last = 1; for (int i = 1; i < ratings.size(); ++i) { if (ratings[i] == ratings[i - 1]) { ret += next; next = 1; } else if (ratings[i] < ratings[i - 1]) { int k = i; while (k < ratings.size() && ratings[k] < ratings[k - 1]) { k++; } ret += (1 + k - i + 1) * (k - i + 1) / 2; if (i >= 2 && ratings[i - 2] > ratings[i - 1] && (k - i + 1) >= last) { ret += k - i + 1 + 1 - last; } i = k; if (ratings[i] == ratings[i - 1]) { next = 1; } else { next = 2; } } else if (ratings[i] > ratings[i - 1]) { int k = i; while (k < ratings.size() && ratings[k] > ratings[k - 1]) { k++; } ret += (next + k - i + next) * (k - i + 1) / 2; last = k - i + next; i = k; next = 1; } } return ret; } }; int main() { Solution sln; vector<int> ratings; ratings = {25, 94, 89, 54, 26, 54, 54, 99, 64}; cout << sln.candy(ratings) << endl; }
24.576923
79
0.418623
zhengyhn
5cab68a0049564f99d1ea69987754f7b088a621e
3,722
cpp
C++
source/helloworld.cpp
LS060598/programmiersprachen-aufgabe-1.
f08c20f2027f442a8fab1770d50e33a247bb3a49
[ "MIT" ]
null
null
null
source/helloworld.cpp
LS060598/programmiersprachen-aufgabe-1.
f08c20f2027f442a8fab1770d50e33a247bb3a49
[ "MIT" ]
null
null
null
source/helloworld.cpp
LS060598/programmiersprachen-aufgabe-1.
f08c20f2027f442a8fab1770d50e33a247bb3a49
[ "MIT" ]
null
null
null
#include <iostream> # include <cmath> int factorial(int x){ if(x<=1){ return 1; } else{ return factorial(x-1)*x; } } double binomial(int n, int k){ if(k==0 || n==k){ return -1; } else{ return factorial(n)/(factorial(k)*(factorial (n-k))); } } double mileToKilometer(){ double mile; std::cout<<"Geben Sie die Meilen an!\n"; std::cin >> mile; double kilometer; kilometer = mile * 1.6 ; std::cout << "Kilometer sind " << kilometer << std::endl; return kilometer; } bool is_prime(){ int x; std::cout<<"Geben Sie eine ganze Zahl ein!\n"; std::cin >> x; int i=2; while (i<x){ if(x % i == 0){ std::cout << "Zahl ist nicht prim!\n "; return false; } else{ ++i; } std::cout << "Zahl ist prim!\n "; return true; } } double surface(){ double radius; double hight; std::cout<<"Geben Sie den Radius an!\n"; std::cin >> radius; std::cout<<"Geben Sie die Höhe an!\n"; std::cin >> hight; double surface; surface = 2 * M_PI * radius + (radius + hight); std::cout << "Oberfläche betraegt " << surface << std::endl; return surface; } double capacity(){ double radius; double hight; std::cout<<"Geben Sie den Radius an!\n"; std::cin >> radius; std::cout<<"Geben Sie die Höhe an!\n"; std::cin >> hight; double capacity; capacity = M_PI * pow(radius,2) * hight; std::cout << "Volumen betraegt " << capacity << std::endl; return capacity; } int checksum (){ int a; std::cout << "Geben Sie eine Zahl ein!\n "; std::cin >> a; int checksum=0; while (a>0){ checksum += a%10; a/=10; } std::cout <<" Quersumme ist " << checksum << std::endl; return checksum; } int gcd(){ int p; std::cout<<"Geben sie eine ganze Zahl ein!\n"; std::cin >> p ; int q; std::cout<<"Geben sie eine ganze Zahl ein!\n"; std::cin >> q ; int r = 0; while (q != 0){ r= p % q; p = q; q = r; } std::cout << "Der ggT ist " << p << std::endl; } long int aufgabe1_10() { long int sumMultiples = 0; long int x=0; while (x<=1000) { if(x % 3 ==0 || x % 5 == 0){ sumMultiples += x; } ++x; } std::cout << "Zahl ist " << sumMultiples << std::endl; return sumMultiples; } long int aufgabe1_3() { long int zahl = 20; long int x=1; while(x<=20) { if(zahl % x != 0) { zahl += 20; // zahl = zahl + 20; x=0; } ++x; } std::cout << "Zahl ist " << zahl << std::endl; return zahl; } int main() { std::cout << "Hello, World!\n"; aufgabe1_3(); aufgabe1_10(); checksum(); gcd(); capacity(); surface(); is_prime(); std::cout<<"Geben sie eine ganze Zahl ein!\n"; int x; std::cin >> x; if(x<=0){ std::cout<<"X muss größer 0 sein\n"; } else{ std::cout<<"Die Zahl ist"<< factorial(x)<<std::endl; } std::cout<<"Geben sie eine n und k ein!\n" ; int n; int k; std::cin >> n >> k; if(n<k){ std::cout<<"n muss größer k sein!"; } else{ std::cout << "Binomialkoeffizient ist " << binomial << std::endl; } return 0; }
18.334975
73
0.448684
LS060598
5cac06e0afb16c27faa7bed19172db28783bc870
3,334
cpp
C++
src/OSCBundle.cpp
ssilverman/LiteOSCParser
37d0c1451e3d3f59b91bdc54ce6b985f265b4bb0
[ "BSD-3-Clause-Clear" ]
2
2019-06-16T13:27:42.000Z
2020-09-01T14:33:04.000Z
src/OSCBundle.cpp
ssilverman/LiteOSCParser
37d0c1451e3d3f59b91bdc54ce6b985f265b4bb0
[ "BSD-3-Clause-Clear" ]
1
2018-05-02T19:52:12.000Z
2018-05-02T19:52:12.000Z
src/OSCBundle.cpp
ssilverman/LiteOSCParser
37d0c1451e3d3f59b91bdc54ce6b985f265b4bb0
[ "BSD-3-Clause-Clear" ]
null
null
null
// OSCBundle.cpp is part of LiteOSCParser. // (c) 2018-2019 Shawn Silverman #include "LiteOSCParser.h" // C++ includes #ifdef __has_include #if __has_include(<cstdlib>) #include <cstdlib> #else #include <stdlib.h> #endif #if __has_include(<cstring>) #include <cstring> #else #include <string.h> #endif #else #include <cstdlib> #include <cstring> #endif namespace qindesign { namespace osc { OSCBundle::OSCBundle(int bufCapacity) : buf_(nullptr), bufSize_(0), bufCapacity_(0), dynamicBuf_(true), memoryErr_(false), isInitted_(false) { static_assert(sizeof(uint8_t) == 1, "sizeof(uint8_t) == 1"); if (bufCapacity > 0) { dynamicBuf_ = false; if (bufCapacity < 16) { bufCapacity = 16; } buf_ = static_cast<uint8_t*>(malloc(bufCapacity)); if (buf_ == nullptr) { memoryErr_ = true; } else { bufCapacity_ = bufCapacity; } } } OSCBundle::~OSCBundle() { if (buf_ != nullptr) { free(buf_); } } bool OSCBundle::init(uint64_t time) { if (!ensureCapacity(16)) { return false; } memcpy(buf_, "#bundle", 8); // Use 32-bit values uint32_t t = time >> 32; buf_[8] = t >> 24; buf_[9] = t >> 16; buf_[10] = t >> 8; buf_[11] = t; t = time; buf_[12] = t >> 24; buf_[13] = t >> 16; buf_[14] = t >> 8; buf_[15] = t; bufSize_ = 16; isInitted_ = true; return true; } bool OSCBundle::addMessage(const LiteOSCParser &osc) { return add(osc.getMessageBuf(), osc.getMessageSize()); } bool OSCBundle::addBundle(const OSCBundle &bundle) { return add(bundle.buf(), bundle.size()); } bool OSCBundle::parse(const uint8_t *buf, int32_t len) { if (len < 16 || (len & 0x03) != 0) { return false; } if (memcmp(buf, "#bundle", 8) != 0) { return false; } int index = 16; while (index < len) { int32_t size = static_cast<int32_t>( uint32_t{buf[index]} << 24 | uint32_t{buf[index + 1]} << 16 | uint32_t{buf[index + 2]} << 8 | uint32_t{buf[index + 3]}); index += 4; if (size <= 0 || (size & 0x03) != 0 || index + size > len) { return false; } if (size >= 8 && memcmp(&buf[index], "#bundle", 8) == 0) { if (!parse(&buf[index], size)) { return false; } } else if (buf[index] != '/') { // Rudimentary check for an OSC message return false; } index += size; } return true; } // -------------------------------------------------------------------------- // Private functions // -------------------------------------------------------------------------- bool OSCBundle::add(const uint8_t *buf, int32_t size) { if (!isInitted_) { return false; } if (!ensureCapacity(bufSize_ + 4 + size)) { return false; } uint32_t u = static_cast<uint32_t>(size); buf_[bufSize_++] = u >> 24; buf_[bufSize_++] = u >> 16; buf_[bufSize_++] = u >> 8; buf_[bufSize_++] = u; memcpy(&buf_[bufSize_], buf, size); bufSize_ += size; return true; } bool OSCBundle::ensureCapacity(int size) { if (size <= bufCapacity_) { return true; } if (!dynamicBuf_) { memoryErr_ = true; return false; } buf_ = static_cast<uint8_t*>(realloc(buf_, size)); if (buf_ == nullptr) { memoryErr_ = true; return false; } bufCapacity_ = size; return true; } } // namespace osc } // namespace qindesign
21.235669
77
0.564787
ssilverman
5cb0851f56d134d2cf19e6c4cccc526a8b8bec94
8,353
cpp
C++
src/PreviewData.cpp
rc2server/compute
cf9fc90d5cc7ad12fb666e03f5c7f0e419748ccc
[ "0BSD" ]
1
2021-08-20T06:44:10.000Z
2021-08-20T06:44:10.000Z
src/PreviewData.cpp
rc2server/compute
cf9fc90d5cc7ad12fb666e03f5c7f0e419748ccc
[ "0BSD" ]
4
2017-03-27T17:55:29.000Z
2018-01-29T22:51:40.000Z
src/PreviewData.cpp
rc2server/compute
cf9fc90d5cc7ad12fb666e03f5c7f0e419748ccc
[ "0BSD" ]
1
2021-08-20T06:44:10.000Z
2021-08-20T06:44:10.000Z
#include "FileManager.hpp" #include "parser/RmdParser.hpp" #include "PreviewData.hpp" #include "common/RC2Utils.hpp" #include "common/FormattedException.hpp" #include <cassert> #include <algorithm> #include <RInside.h> #include <boost/algorithm/string/trim.hpp> #include <boost/bind.hpp> #include <sstream> #include "Errors.hpp" #include "RC2Logging.h" #include <nlohmann/json.hpp> #include "vendor/cpp-base64/base64.h" /* * 1. if the source file hasn't changed, nothing to do. Note if data files have changed, need to update any chunks that refer to them * 2. reparse source file * 3. figure out which chunks need updating * 4. execute the code * 5. create cache entry * 6. return results for chunk */ using std::unique_ptr; using std::endl; using json = nlohmann::json; //void handleFileChange(PreviewData *data, bool isSpaceOrTab ( char c ) { return c == 32 || c == 9; } namespace RC2 { RC2::PreviewData::PreviewData ( int pid, FileManager* fmanager, FileInfo& finfo, EnvironmentWatcher* globalEnv, PreviewDelegate *delegate ) : previewId ( pid ), fileManager ( fmanager ), fileInfo ( finfo ), delegate_( delegate ), previewEnv ( globalEnv ) { long fid = fileInfo.id; fileManager->addChangeListener ( fid, boost::bind ( &PreviewData::fileChanged, this, fid, ALL ), &fileConnection ); } RC2::PreviewData::~PreviewData() { // FIXME: is this a memory leak? // fileConnection->disconnect(); } void RC2::PreviewData::update ( FileInfo& updatedInfo, string& updateIdent, int targetChunkId, bool includePrevious ) { assert ( updatedInfo.id == fileInfo.id ); currentUpdateIdentifier_ = updateIdent; LOG_INFO << "got update request ident:" << updateIdent; fileInfo = updatedInfo; string contents = SlurpFile ( fileInfo.name.c_str() ); currentChunks_ = parser.parseRmdSource ( contents ); bool usePrevious = includePrevious; int targetId = targetChunkId; // if target is less than zero, execute all chunks if ( targetId < 0) { targetId = currentChunks_.size() - 1; usePrevious = true; } auto chunks2Update = whichChunksNeedUpdate ( targetId, usePrevious ); // send update started message nlohmann::json results; results["msg"] = "previewUpdateStarted"; results["updateIdentifier"] = currentUpdateIdentifier_; results["activeChunks"] = chunks2Update; results["previewId"] = previewId; delegate_->sendPreviewJson(results.dump()); // start execution executeChunks ( chunks2Update ); currentUpdateIdentifier_ = ""; } void RC2::PreviewData::fileChanged ( long changedId, ChangeType type ) { LOG_INFO << "fileChanged called:" << changedId << endl; } void RC2::PreviewData::executeChunks ( vector<int> chunksToUpdate ) { // 1. create cache entry- // 2. evaluate // 3. turn results into json // 4. send results LOG_INFO << "executing " << chunksToUpdate.size() << " chunks"; // TODO: handle exceptions for ( auto idx: chunksToUpdate ) { Chunk* aChunk = currentChunks_[idx]; if ( aChunk->type() == markdown ) continue; // TODO: handle inline code chunks auto cacheEntry = chunkMap[idx].get(); auto oldCrc = cacheEntry->crc; try { LOG_INFO << "executing " << aChunk->content() << std::endl; executeChunk ( aChunk, cacheEntry ); nlohmann::json results; results["msg"] = "previewUpdated"; results["chunkId"] = idx; results["updateIdentifier"] = currentUpdateIdentifier_; results["previewId"] = previewId; results["content"] = cacheEntry->lastOutput; results["complete"] = false; string str = results.dump(2); delegate_->sendPreviewJson(str); } catch ( GenericException& e ) { LOG_INFO << "generic exception: " << e.code(); } } json finalResults; finalResults["chunkId"] = -1; finalResults["msg"] = "previewUpdated"; finalResults["updateIdentifier"] = currentUpdateIdentifier_; finalResults["previewId"] = previewId; finalResults["complete"] = true; finalResults["content"] = ""; delegate_->sendPreviewJson(finalResults.dump(2)); } string RC2::PreviewData::executeChunk ( Chunk* chunk, ChunkCacheEntry* cacheEntry ) { SEXP answer; Rcpp::Environment env; // TODO: use environment from cacheEntry previewEnv.captureEnvironment(); previewEnv.getEnvironment ( env ); string userCode = chunk->innerContent(); boost::algorithm::trim_if ( userCode, &isSpaceOrTab ); env.assign ( "rc2.code", userCode ); env.assign ( "rc2.env", env ); // watch for files fileManager->resetWatch(); string code = "rc2.evaluateCode(rc2.code, parent = rc2.env)"; try { delegate_->executePreviewCode(code, answer, &env); } catch (const RException& e) { LOG_INFO << "preview query failed:" << e.getCode(); return ""; // FIXME: should get error message from sexp, use that as what() } catch (const std::exception& e) { LOG_WARNING << "error executing code"; } env.remove("rc2.code"); env.remove("rc2.env"); env.remove("allItems"); // should have been removed by R package. wasn't for some reason if ( (answer == nullptr) || Rf_isVector(answer) == FALSE) { Rcpp::StringVector emsg = Rcpp::as<Rcpp::StringVector>(answer); LOG_INFO << "type=" << TYPEOF(answer) << " error; " << emsg[0]; throw GenericException ( "query failed", kError_QueryFailed ); } std::stringstream outStr; Rcpp::List results ( answer ); for ( auto itr = results.begin(); itr != results.end(); ++itr ) { Rcpp::List curList ( *itr ); string elType = curList.attr ( "class" ); if ( elType == "rc2src" ) { Rcpp::StringVector strs ( Rcpp::as<Rcpp::StringVector> ( curList["src"] ) ); outStr << "<div style=\"rc2-preview-src\">" << strs[0] << "</div>" << endl; } else if ( elType == "rc2value" ) { Rcpp::StringVector strs ( Rcpp::as<Rcpp::StringVector> ( curList["str"] ) ); outStr << "<div style=\"rc2-preview-out\">" << strs[0] << "</div>" << endl; } else if ( elType == "rc2err" ) { Rcpp::StringVector strs ( Rcpp::as<Rcpp::StringVector> ( curList["message"] ) ); Rcpp::StringVector calls ( Rcpp::as<Rcpp::StringVector> ( curList["call"] ) ); outStr << "<div style=\"rc2-error\">" << strs[0] << "(location: " << calls[0] << ")</div>" << endl; } else if ( elType == "rc2plot") { BinaryData imgData; Rcpp::StringVector names ( Rcpp::as<Rcpp::StringVector> ( curList["fname"] ) ); string fname(names[0]); SlurpBinaryFile(fname, imgData); string encodedStr = base64_encode((unsigned char*)imgData.data.get(), imgData.getSize(), false); outStr << "<div style=\"rc2-plot\"><img src=\"data:image/png;base64," << encodedStr << "\"></div>" << endl; } else { LOG_INFO << "unsupported ype returned from evaluate: " << elType; } } auto output = outStr.str(); cacheEntry->cacheOutput(output); cacheEntry->crc = cacheEntry->generateCRC(); return output; } void RC2::PreviewData::checkCache() { EnvironmentWatcher* parent = &previewEnv; for ( int i=0; i < currentChunks().size(); ++i ) { if ( chunkMap.count ( i ) > 0 ) continue; chunkMap[i] = std::make_unique<ChunkCacheEntry> ( i, parent ); parent = &chunkMap[i]->envWatcher; } } vector<int> RC2::PreviewData::whichChunksNeedUpdate ( int targetChunkId, bool includePrevious ) { // TODO: implement more intelligent checking vector<int> toExecute; int startIndex = targetChunkId; // if the number of chunks changed, we'll invalidate everything for now // TODO: use the ChunkCacheEntry(s) to determine if the cache can be used if ( currentChunks_.size() != chunkMap.size() ) { chunkMap.clear(); // insert new cache entries checkCache(); } if ( includePrevious ) { startIndex = 0; } else { // adjust targetId if any previous chunks need to be executed for ( int i = startIndex - 1; i >= 0; --i ) { // TODO: to support inline chunks, need to see if mdown chunk has inline code and if the cache of it is empty auto centry = chunkMap[i].get(); auto chunk = currentChunks_[i]; if ( chunk->type() == code && !centry->outputCached ) { startIndex = i; } } } for ( int i=startIndex; i <= targetChunkId; ++i ) { auto chunk = currentChunks_[i]; // include all markdowns, will ignore ones with no inline code chunks if ( chunk->type() == code ) { toExecute.push_back ( i ); } else if ( chunk->type() == markdown ) { auto mchunk = dynamic_cast<MarkdownChunk*> ( chunk ); if ( mchunk == nullptr || mchunk->inlineChunkCount() < 1 ) { continue; } toExecute.push_back ( i ); } } return toExecute; } }; //end namespace
35.696581
140
0.681552
rc2server
5cb2d65e6986f1bcc82f1b380e6d8c103ad389c4
4,917
cpp
C++
src/brov2_odometry/src/odom.cpp
bjornrho/Navigation-brov2
a7104803099159f4f27a1e83d733ba2e0dd75c2e
[ "MIT" ]
2
2022-01-22T10:02:07.000Z
2022-02-16T19:30:17.000Z
src/brov2_odometry/src/odom.cpp
bjornrho/Navigation-brov2
a7104803099159f4f27a1e83d733ba2e0dd75c2e
[ "MIT" ]
null
null
null
src/brov2_odometry/src/odom.cpp
bjornrho/Navigation-brov2
a7104803099159f4f27a1e83d733ba2e0dd75c2e
[ "MIT" ]
null
null
null
#include "odom.hpp" using std::placeholders::_1; SimpleOdom::SimpleOdom() : Node{"odom_node"} { // get params std::string imu_topic = "INSERT IMU TOPIC"; std::string dvl_topic = "INSERT DVL TOPIC"; std::string odom_topic = "INSERT ESTIMATED ODOMETRY TOPIC"; std::string mocap_topic; std::string imu_link; std::string dvl_link; //if (!nh.getParam("simple_odom/imu_topic", imu_topic)) // imu_topic = "/auv/imu"; //if (!nh.getParam("simple_odom/dvl_topic", dvl_topic)) // dvl_topic = "/auv/odom"; //if (!nh.getParam("simple_odom/mocap_topic", mocap_topic)) // mocap_topic = "/qualisys/Body_1/pose"; //if (!nh.getParam("simple_odom/odom_topic", odom_topic)) // odom_topic = "/odometry/filtered"; //if (!nh.getParam("simple_odom/imu_link", imu_link)) // imu_link = "imu_0"; //if (!nh.getParam("simple_odom/dvl_link", dvl_link)) // dvl_link = "dvl_link"; //if (!nh.getParam("simple_odom/publish_rate", update_rate)) // update_rate = 20; // set up IMU and DVL transforms tf2_ros::Buffer tf_buffer(); tf2_ros::TransformListener tf_listener(tf_buffer); double timeout = 10; // seconds to wait for transforms to become available RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "Waiting for IMU and DVL transforms.."); geometry_msgs::msg::TransformStamped imu_transform = tf_buffer.lookupTransform("base_link", imu_link, rclcpp::Time(0), rclcpp::Duration(timeout)); //rclcpp::Time is forced to wall time and is not recommended for general use. geometry_msgs::msg::TransformStamped dvl_transform = tf_buffer.lookupTransform("base_link", dvl_link, rclcpp::Time(0), rclcpp::Duration(timeout)); tf2::fromMsg(imu_transform.transform.rotation, imu_rotation); tf2::fromMsg(dvl_transform.transform.rotation, dvl_rotation); tf2::fromMsg(dvl_transform.transform.translation, dvl_translation); // subscribers and publishers auto imu_sub = node->create_subscription<sensor_msgs::msg::Imu>(imu_topic, 1, std::bind(&SimpleOdom::imuCallback, this, _1)); auto dvl_sub = node->create_subscription<geometry_msgs::msg::TwistWithCovarianceStamped>(dvl_topic, 1, std::bind(&SimpleOdom::dvlCallback, this, _1)); auto mocap_sub = node->create_subscription<geometry_msgs::msg::PoseStamped>(mocap_topic, 1, std::bind(&SimpleOdom::mocapCallback, this, _1)); auto odom_pub = node->create_publisher<nav_msgs::msg::Odometry>(odom_topic, 1); //imu_sub = nh.subscribe(imu_topic, 1, &SimpleOdom::imuCallback, this); //dvl_sub = nh.subscribe(dvl_topic, 1, &SimpleOdom::dvlCallback, this); //mocap_sub = nh.subscribe(mocap_topic, 1, &SimpleOdom::mocapCallback, this); //odom_pub = nh.advertise<nav_msgs::Odometry>(odom_topic, 1); // wait for first imu, dvl and mocap msg //ROS_INFO("Waiting for initial IMU, DVL and MOCAP msgs.."); //ros::topic::waitForMessage<sensor_msgs::Imu>(imu_topic, nh); //ros::topic::waitForMessage<geometry_msgs::TwistWithCovarianceStamped>(dvl_topic, nh); //ros::topic::waitForMessage<geometry_msgs::PoseStamped>(mocap_topic, nh); // There is no waitForMessage-equivalent in ROS2, https://answers.ros.org/question/378693/waitformessage-ros2-equivalent/ RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "SimpleOdom initialized"); } void SimpleOdom::spin() { rclcpp::Rate rate(update_rate); while (rclcpp::ok()) { auto node = std::make_shared<SimpleOdom>(); // execute waiting callbacks rclcpp::spin_some(node); // create odom msg nav_msgs::msg::Odometry odometry_msg; odometry_msg.pose.pose.position = tf2::toMsg(position); // Might need to convert this to stamped versions odometry_msg.pose.pose.orientation = tf2::toMsg(orientation); odometry_msg.twist.twist.angular.x = angular_vel[0]; odometry_msg.twist.twist.angular.y = angular_vel[1]; odometry_msg.twist.twist.angular.z = angular_vel[2]; odometry_msg.twist.twist.linear.x = linear_vel[0]; odometry_msg.twist.twist.linear.y = linear_vel[1]; odometry_msg.twist.twist.linear.z = linear_vel[2]; // publish odom_pub->publish(odometry_msg); loop_rate.sleep(); } } void SimpleOdom::imuCallback(const sensor_msgs::msg::Imu& imu_msg) { tf2::Vector3 angular_vel_imu; tf2::fromMsg(imu_msg.angular_velocity, angular_vel_imu); angular_vel = tf2::quatRotate(imu_rotation, angular_vel_imu); } void SimpleOdom::dvlCallback(const geometry_msgs::msg::TwistWithCovarianceStamped& twist_msg) { tf2::Vector3 linear_vel_dvl, linear_vel_uncorrected; tf2::fromMsg(twist_msg.twist.twist.linear, linear_vel_dvl); linear_vel_uncorrected = tf2::quatRotate(dvl_rotation, linear_vel_dvl); // compensate for translation of DVL linear_vel = linear_vel_uncorrected + angular_vel.cross(dvl_translation); // from fossen2021 eq 14.3 } void SimpleOdom::mocapCallback(const geometry_msgs::msg::PoseStamped& msg) { tf2::fromMsg(msg.pose.position, position); tf2::fromMsg(msg.pose.orientation, orientation); }
43.513274
226
0.736221
bjornrho
5cbae0a72d1758e5044bdca6d3541255440b565e
4,619
cpp
C++
VariableDragManager.cpp
fredenigma/VesselBuilder1
4f332ec4e6fa80e1a63d8d920bb50e033c5b67f6
[ "MIT" ]
null
null
null
VariableDragManager.cpp
fredenigma/VesselBuilder1
4f332ec4e6fa80e1a63d8d920bb50e033c5b67f6
[ "MIT" ]
null
null
null
VariableDragManager.cpp
fredenigma/VesselBuilder1
4f332ec4e6fa80e1a63d8d920bb50e033c5b67f6
[ "MIT" ]
null
null
null
#include "VesselBuilder1.h" #include "DialogControl.h" #include "VariableDragManager.h" #include "AnimationManager.h" #define LogV(x,...) VB1->Log->Log(x,##__VA_ARGS__) VariableDragManager::VariableDragManager(VesselBuilder1* _VB1) { VB1 = _VB1; vard_def.clear(); return; } VariableDragManager::~VariableDragManager() { VB1 = NULL; return; } void VariableDragManager::AddUndefinedVardDef() { VARD_DEF vd = VARD_DEF(); vd.defined = false; UINT index = vard_def.size(); char nbuf[256] = { '\0' }; sprintf(nbuf, "VariableDrag_%i", index); vd.name.assign(nbuf); vard_def.push_back(vd); return; } UINT VariableDragManager::AddVardDef(string name, UINT anim_idx, double factor, VECTOR3 ref) { VARD_DEF vd = VARD_DEF(); vd.name = name; vd.ref = ref; vd.factor = factor; vd.anim_idx = anim_idx; vd.defined = true; UINT index = vard_def.size(); vard_def.push_back(vd); DefineVarDef(index); return index; } void VariableDragManager::DefineVarDef(def_idx d_idx) { double *state_ptr = VB1->AnimMng->GetAnimStatePtr(vard_def[d_idx].anim_idx); VB1->CreateVariableDragElement(state_ptr, vard_def[d_idx].factor, vard_def[d_idx].ref); // LogV("state pointer value:%.3f", *state_ptr); vard_def[d_idx].defined = true; return; } void VariableDragManager::DefineAll() { for (UINT i = 0; i < GetVardDefCount(); i++) { if (IsVardDefDefined(i)) { DefineVarDef(i); } } return; } void VariableDragManager::UnDefineVardDef(def_idx d_idx) { vard_def[d_idx].defined = false; VB1->ClearVariableDragElements(); DefineAll(); return; } void VariableDragManager::DeleteVarDef(def_idx d_idx) { vard_def.erase(vard_def.begin() + d_idx); VB1->ClearVariableDragElements(); DefineAll(); return; } string VariableDragManager::GetVardName(def_idx d_idx) { return vard_def[d_idx].name; } void VariableDragManager::SetVardName(def_idx d_idx, string newname) { vard_def[d_idx].name = newname; return; } UINT VariableDragManager::GetVardDefCount() { return vard_def.size(); } void VariableDragManager::Clear() { vard_def.clear(); VB1->ClearVariableDragElements(); return; } void VariableDragManager::GetVardParams(def_idx d_idx, double &factor, VECTOR3 &ref, UINT &anim_idx) { factor = vard_def[d_idx].factor; ref = vard_def[d_idx].ref; anim_idx = vard_def[d_idx].anim_idx; return; } void VariableDragManager::SetVardParams(def_idx d_idx, double factor, VECTOR3 ref, UINT anim_index) { vard_def[d_idx].factor = factor; vard_def[d_idx].ref = ref; vard_def[d_idx].anim_idx = anim_index; return; } bool VariableDragManager::IsVardDefDefined(def_idx d_idx) { return vard_def[d_idx].defined; } void VariableDragManager::ParseCfgFile(FILEHANDLE fh) { LogV("Parsing Variable Drag Section"); UINT vard_counter = 0; char cbuf[256] = { '\0' }; int id; sprintf(cbuf, "VARIABLEDRAG_%i_ID", vard_counter); while (oapiReadItem_int(fh, cbuf, id)) { char namebuf[256] = { '\0' }; sprintf(cbuf, "VARIABLEDRAG_%i_NAME", vard_counter); oapiReadItem_string(fh, cbuf, namebuf); string name(namebuf); double factor; int anim_idx; VECTOR3 ref; sprintf(cbuf, "VARIABLEDRAG_%i_FACTOR", vard_counter); oapiReadItem_float(fh, cbuf, factor); sprintf(cbuf, "VARIABLEDRAG_%i_REF", vard_counter); oapiReadItem_vec(fh, cbuf, ref); sprintf(cbuf, "VARIABLEDRAG_%i_ANIM", vard_counter); oapiReadItem_int(fh, cbuf, anim_idx); AddVardDef(name, anim_idx, factor, ref); vard_counter++; sprintf(cbuf, "VARIABLEDRAG_%i_ID", vard_counter); } LogV("Parsing Variable Drag Section Completed, found %i definitions",vard_counter); return; } void VariableDragManager::WriteCfg(FILEHANDLE fh) { oapiWriteLine(fh, " "); oapiWriteLine(fh, ";<-------------------------VARIABLE DRAG ITEMS DEFINITIONS------------------------->"); oapiWriteLine(fh, " "); UINT vard_counter = 0; for (UINT i = 0; i < GetVardDefCount(); i++) { if (!IsVardDefDefined(i)) { continue; } char cbuf[256] = { '\0' }; sprintf(cbuf, "VARIABLEDRAG_%i_ID", vard_counter); oapiWriteItem_int(fh, cbuf, vard_counter); sprintf(cbuf, "VARIABLEDRAG_%i_NAME", vard_counter); char namebuf[256] = { '\0' }; sprintf(namebuf, "%s", GetVardName(i).c_str()); oapiWriteItem_string(fh, cbuf, namebuf); double factor; UINT anim_idx; VECTOR3 ref; GetVardParams(i, factor, ref, anim_idx); sprintf(cbuf, "VARIABLEDRAG_%i_FACTOR", vard_counter); oapiWriteItem_float(fh, cbuf, factor); sprintf(cbuf, "VARIABLEDRAG_%i_REF", vard_counter); oapiWriteItem_vec(fh, cbuf, ref); sprintf(cbuf, "VARIABLEDRAG_%i_ANIM", vard_counter); oapiWriteItem_int(fh, cbuf, anim_idx); oapiWriteLine(fh, " "); vard_counter++; } return; }
30.589404
107
0.720935
fredenigma
5cbc08086b52406335f93c7ce9191a7df6735618
1,865
cpp
C++
base/TextureCommons.cpp
wessles/vkmerc
cb087f425cdbc0b204298833474cf62874505388
[ "Unlicense" ]
6
2020-10-09T02:48:54.000Z
2021-07-30T06:31:20.000Z
base/TextureCommons.cpp
wessles/vkmerc
cb087f425cdbc0b204298833474cf62874505388
[ "Unlicense" ]
null
null
null
base/TextureCommons.cpp
wessles/vkmerc
cb087f425cdbc0b204298833474cf62874505388
[ "Unlicense" ]
null
null
null
#include "TextureCommons.h" #include "VulkanTexture.h" #include "VulkanDevice.h" namespace vku { void createSinglePixelTexture(VulkanDevice* device, unsigned char *pixels, VulkanTexture **texture) { *texture = new VulkanTexture(); VulkanTexture* pixTex = *texture; pixTex->image = new VulkanImage(device, VulkanImageInfo{ .width = 1, .height = 1, .format = VK_FORMAT_R8G8B8A8_UNORM, .usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT }); VkDeviceSize imageSize = 1 * 1 * 4; VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; device->createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(*device, stagingBufferMemory, 0, imageSize, 0, &data); memcpy(data, pixels, static_cast<size_t>(imageSize)); vkUnmapMemory(*device, stagingBufferMemory); // create image and load from buffer pixTex->image->loadFromBuffer(stagingBuffer); vkDestroyBuffer(*device, stagingBuffer, nullptr); vkFreeMemory(*device, stagingBufferMemory, nullptr); VulkanImageViewInfo viewInfo{}; pixTex->image->writeImageViewInfo(&viewInfo); pixTex->view = new VulkanImageView(device, viewInfo); pixTex->sampler = new VulkanSampler(device, VulkanSamplerInfo{}); } TextureCommons::TextureCommons(VulkanDevice* device) { // make 1x1 white texture unsigned char white[] = { 0xff,0xff,0xff,0xff }; unsigned char black[] = { 0x00,0x00,0x00,0x00 }; unsigned char norm[] = { 0x00,0x00,0xff,0x00 }; createSinglePixelTexture(device, white, &white1x1); createSinglePixelTexture(device, black, &black1x1); createSinglePixelTexture(device, norm, &zNorm); } TextureCommons::~TextureCommons() { delete white1x1; delete black1x1; delete zNorm; } }
30.57377
102
0.751743
wessles
5cbd35a8861ec48d4e96b30d2078f4b40717e42f
28,087
cc
C++
src/LSLib/DensOp.cc
pygamma-mrs/gamma
c83a7c242c481d2ecdfd49ba394fea3d5816bccb
[ "BSD-3-Clause" ]
4
2021-03-15T10:02:13.000Z
2022-01-16T11:06:28.000Z
src/LSLib/DensOp.cc
pygamma-mrs/gamma
c83a7c242c481d2ecdfd49ba394fea3d5816bccb
[ "BSD-3-Clause" ]
1
2022-01-27T15:35:03.000Z
2022-01-27T15:35:03.000Z
src/LSLib/DensOp.cc
pygamma-mrs/gamma
c83a7c242c481d2ecdfd49ba394fea3d5816bccb
[ "BSD-3-Clause" ]
null
null
null
/* DensOp.cc ****************************************************-*-c++-*- ** ** ** G A M M A ** ** ** ** Density Operator Implementation ** ** ** ** Copyright (c) 1998 ** ** Dr. Scott A. Smith ** ** National High Magnetic Field Laboratory ** ** 1800 E. Paul Dirac Drive ** ** Box 4005 ** ** Tallahassee, FL 32306 ** ** ** ** $Header: $ ** ** *************************************************************************/ /************************************************************************* ** ** ** Description ** ** ** ** The class densop defines a density operator. This operator is by & ** ** large a general operator. As such it normally resides in Hilbert ** ** space or a composite Hilbert space. In additon to general operator ** ** activity, density operators track their time since "equilibrium" and ** ** "rotating frames". They also allow themselves to to be evolved by ** ** GAMMA's Hilbert space density operators &/or Liouville space ** ** propagators. ** ** ** *************************************************************************/ #ifndef _densop_cc_ // Is file already included? # define _densop_cc_ 1 // If no, then remember it # if defined(GAMPRAGMA) // Using the GNU compiler? # pragma implementation // this is the implementation # endif #include <LSLib/DensOp.h> // Include the header #include <LSLib/LSAux.h> // Know about LU decomposition #include <HSLib/GenOp.h> // Must know operators #include <LSLib/SuperOp.h> // Must know superoperators #include <HSLib/SpinOpCmp.h> // Must know Fz operator #include <string> // Must know about strings #include <HSLib/SpinSys.h> // Know about spin systems #include <Basics/StringCut.h> // Know about the Gdec functio #include <stdlib.h> // ---------------------------------------------------------------------------- // --------------------------- PRIVATE FUNCTIONS ------------------------------ // ---------------------------------------------------------------------------- // ____________________________________________________________________________ // i CLASS DENSITY OPERATOR ERROR HANDLING // ____________________________________________________________________________ void densop::SIGMAerror(int eidx, int noret) const // Input Sigma : Density operator (this) // eidx : Error flag // noret : Return flag // Output none : Error Message Output { std::cout << "\nClass Density Operator: "; switch(eidx) { case 0: // (0) std::cout << "Program Aborting...."; break; case 1: // (1) std::cout << "Error During Construction"; break; case 10: // (10) std::cout << "Steady State Does Not Exist"; break; default: std::cout << "Unknown Error (Number " << eidx << ")"; } if(!noret) std::cout << ".\n"; else std::cout << "."; } void volatile densop::SIGMAfatality(int eidx) const { SIGMAerror(eidx); if(eidx) SIGMAerror(0); std::cout << "\n"; exit(-1); } // ---------------------------------------------------------------------------- // ---------------------------- PUBLIC FUNCTIONS ------------------------------ // ---------------------------------------------------------------------------- // ____________________________________________________________________________ // A CLASS DENSITY OPERATOR CONSTRUCTION, DESTRUCTION // ____________________________________________________________________________ densop::densop() { Sigmat = 0; } // Input none : // Output Sigma : A NULL density operator (this) ///F_list densop - Constructor densop::densop(const spin_sys& sys) : gen_op(SigmaEq(sys)) { Sigmat = 0; } // Input sys : A spin system // Output Op : The density matrix describing // the system under a high-temp // approximation. // Note : The identity matrix is subtracted // out, leaving the operator traceless // (normally Tr{density matrix} = 1) // Note : The density matrix is scaled by a // constant scaling factor. This does // not change the relative intensities // of any observed transitions /* By definition 1 [ -H ] 1 [ 2 3 ] -H sigmaeq = - exp|----| = - | 1 + X + X + X + .... | where X = -- Z [ kT ] Z [ ] kT When kT >> ||H||, the powers of X become small very quickly. Under such circumstances we can drop all powers higher than 1. Furthermore, the 1 is just along for the ride (under most density operator evolutions) so we can just remove it. Lastly, the factors Z & kT are just scaling contants which one may leave out since the global scaling is not terribly important. These may be removed too: ~ 1 [ -H ] -H sigmaeq = - | 1 + -- | --> --- --> -H Z [ kT ] ZkT A few points: 1.) We are usually in the high temperature limit 2.) The 1 is needed in some relaxation treatments 3.) The value of Z (partition function) is simply the sytsem spin Hilbert space. 4.) The factor Z should be used when comparing magnetization intensities in systems of different Hilbert space dimensions. For the isotropic static Hamiltonian in NMR, neglecting chemical shifts and coupling constants (e.g. energy level populations are insignificantly affected by these contributions, so H is the Zeeman Hamiltonian) --- --- gamma ~ \ \ i homonuclear sigmaeq = - / - hbar * gamma * Iz --> / ------ Iz -----------> Fz --- i i --- gamma i i i 0 where the operator has be again rescaled by hbar*gamma 0 */ // Input sys : Spin system // Input L : Full Liouvillian (rad/sec) // R : Relaxation Superoperator (rad/sec) // sigmaeq : Equilibrium density operator // Return sss : Steady state density matrix // Note : Careful R & L units, usually Ho is Hz! // Note : L is singular, thus steady state must // be determined in a reduced Liouville // space. Best done with matrix routines // not (code simple) superop. functions! // Note : Algorithm needs density matrix trace = 1 // Function insures this then returns trace // back to the original value. // L|s > = R|s > -------> [L - L|S><E|]|s > = R|s > - |L1> // ss eq ss eq densop::densop(const spin_sys& sys, super_op& L, super_op& R) :gen_op(SigmaSS(sys, L, R)) { Sigmat = 0; } densop::densop(super_op& L, super_op& R, gen_op& sigmaeq) :gen_op(SigmaSS(L, R, sigmaeq)) { Sigmat = 0; } densop::densop(gen_op& Op, double tevol) : gen_op(Op) { Sigmat = tevol; } // Op : An operator // tevol : Evolution time (seconds) // Output densop : Sigma set to Op at time tevol densop::densop(const densop& Sigma) : gen_op(Sigma) { Sigmat = Sigma.Sigmat; } // Input none : // Output Sigma : A NULL density operator (this) densop::~densop() { } // Input Sigma : A density operator (this) // Output void : Density operator destructed // Input Sigma : A density operator (this) // Sigma1 : Another density operator // Output void : Sigma is set equal to Sigma1 densop & densop::operator= (const densop& Sigma1) { gen_op::operator=(Sigma1); Sigmat = Sigma1.Sigmat; return (*this); } // ____________________________________________________________________________ // B DENSITY OPERATOR ACCESS FUNCTIONS // ____________________________________________________________________________ double densop::length() const { return Sigmat; } // Input Sigma : A density operator (this) // Output Sigmat : Time of the density operator // ____________________________________________________________________________ // D DENSITY OPERATOR AUXILIARY FUNCTIONS // ____________________________________________________________________________ // Input Sigma : A density operator (this) // tr : Value for Sigma trace // Output void : Sets Sigma trace to be tr void densop::SetTrace(double tr) { double acttr = Re(trace(*this)); // Get current trace double difftr = acttr - tr; // Get trace adjustment int hs = size(); // Get Sigma Hilbert space complex z; // Temp value double fact; // Temp value int i; // Temp value if(difftr) // Adjust all diagonal { // elements to fix trace fact = difftr/double(hs); for(i=0; i<hs; i++) { z = get(i,i) - fact; put(z, i,i); } } } // ____________________________________________________________________________ // C PROPAGATOR FUNCTIONS, PROPAGATOR WITH PROPAGATOR // ____________________________________________________________________________ // ____________________________________________________________________________ // X DENSITY OPERATOR FRIEND FUNCTIONS // ____________________________________________________________________________ /* By definition 1 [ -H ] 1 [ 2 3 ] -H sigmaeq = - exp|----] = - | 1 + X + X + X + .... | where X = -- Z [ kT ] Z [ ] kT When kT >> -H, the identity matrix is neglected, and the factor ZkT removed, ~ 1 [ -H ] -H sigmaeq = - | 1 + -- | --> --- --> -H Z [ kT ] ZkT For the isotropic static Hamiltonian in NMR, neglecting chemical shifts and coupling constants (e.g. energy level populations are insignificantly affected by these contributions, so H is the Zeeman Hamiltonian) --- --- gamma ~ \ \ i homonuclear sigmaeq = - / - hbar * gamma * Iz --> / ------ Iz -----------> Fz --- i i --- gamma i i i 0 where the operator has be again rescaled by hbar*gamma 0 */ // Input sys : A spin system // Output Sigma : An operator representing the // spin system sys at equilibrium gen_op SigmaEq(const spin_sys& sys) { gen_op Op; if(sys.homonuclear()) Op = Fz(sys); else { double gamma0, gammai; gamma0 = sys.gamma(0); Op = Iz(sys,0); for(int i=1; i<sys.spins(); i++) { gammai = sys.gamma(i); Op += (gammai/gamma0)*Iz(sys,i); } } // spin_op Z = Fz(sys); // Op = gen_op(Z.matrix()); // Op = gen_op(Z.matrix(), sys.get_basis()); return Op; } //gen_op sigma_eq(spin_sys& sys, basis& bs) //return Op; // Input bs : basis // Output Op : high temperature equilibrium // density matrix in basis bs //{ // spin_op Z = Fz(sys); // Op = gen_op(Z.matrix(), bs); // return; //} // replaced by new routine from Riccardo Balzan balzan.riccardo@parisdescartes.fr // since this routine give different results if the operators are in different // bases. New routine seems to work well. // 11/2014 MAER //gen_op SigmaSS(const spin_sys& sys, super_op& L, super_op& R, int warn) // // // Input sys : Spin system // // L : Full Liouvillian (rad/sec) // // R : Relaxation Superoperator (rad/sec) // // Return sss : Steady state density matrix // // Note : Careful R & L units, usually Ho is Hz! // // Note : L is singular, thus steady state must // // be determined in a reduced Liouville // // space. Best done with matrix routines // // not (code simple) superop. functions! // // Note : Algorithm needs density matrix trace = 1 // // Function insures this then returns trace // // back to the original value. // //// L|s > = R|s > -------> [L - L|S><E|]|s > = R|s > - |L1> //// ss eq ss eq // // { // gen_op seq; // double d = 1.e-9; // R.LOp_base(L); // Insure R in Liouville base of L // if(R.below(d)) // If R==0, |s > = 0 // { // ss // densop X; // if(warn) // { // densop X; // X.SIGMAerror(10); // } // return seq; // } // else if(L == R) // If R==L, |s > = s > // return SigmaEq(sys); // ss eq // else // { // basis Lbs = L.get_basis(); // Store the Hilbert basis of L // seq = SigmaEq(sys); // Equilibrium density matrix // int hs = seq.dim(); // Get the Hilbert space size // int ls = hs*hs; // Compute the Liouville space // matrix Emx(hs,hs,i_matrix_type); // Temporary Identity matrix // matrix trace1 = Emx/complex(hs); // Scale by dimension // seq += trace1; // Set trace to 1 for this // seq.Op_base(Lbs); // Put operator into L basis // //// Calculate Equation Right Hand Side of Steady State Equation //// //// ' //// |s > = R|s > - |L1> //// eq eq // // matrix L1, ssp, sub_ssp; // L1=(L.get_mx()).get_block(0,0,ls,1);// L1 matrix = 1st column of L // ssp=((R*seq).get_mx()).resize(ls,1);// Modified seq, basis of R // ssp -= L1; // |ssp> = R|seq> - |L1> // sub_ssp = ssp.get_block(1,0,ls-1,1);// Reduced space seq (as matrix) // //// Calculate Equation Left Hand Side of Steady State Equation //// //// X = L - L|S><E| //// // // matrix Smx(hs, hs, 0.0); // Temproray Null matrix // Smx.put(1.0, 0, 0); // 1st element of Smx set to 1 // gen_op S(Smx, Lbs); // Create the S operator // gen_op E(Emx, Lbs); // Create the S operator // super_op SE(S,E); // SE = |S><E| // super_op X = L; // X -= L*SE; // X = L - L|S><E| // matrix sub_X((X.get_mx()). // Reduced space X // get_block(1,1,ls-1,ls-1)); // //// Form the LU Decomposition of the Reduced & Modified Liouville Matrix // ///* ' -1 ' // X|s > = |s > ----> |s > = X |s > // - -ss -eq -ss - -eq // // ' -1 ' // LU|s > = |s > ----> |s > = (LU) |s > // -- -ss -eq -ss -- -eq //*/ // // matrix ALU = sub_X; // int *indx; // indx = new int[ls-1]; // LU_decomp(ALU,indx); // ///* Calculate the Steady State Density Matrix // // -1 ' trace // |s > = (LU) |s > ; |s > ------> |s > // -ss -- -eq -ss ss //*/ // // // matrix sub_sss = sub_ssp; // Steady state in subspace // LU_backsub(ALU,indx,sub_sss); // Back solve for steady state // matrix sssmx(hs, hs, 0.0); // Reform the full steady state // int k=0; // density matrix in Hilbert // for(int i=0; i<hs; i++) // space. // for(int j=0; j<hs; j++) // if(i!=0 || j!=0) // All but first element // { // sssmx.put(sub_sss.get(k,0),i,j); // k++; // } // sssmx.put(1.0-trace(sssmx),0,0); // First element from trace // sssmx.resize(hs,hs); // Back to a square array // sssmx -= trace1; // Set trace back to 0 // gen_op sss(sssmx, seq.get_basis()); // Put this into a gen. op. // delete [] indx; // return sss; // } // } // // //gen_op SigmaSS(super_op& L, super_op& R, gen_op& seq, int warn) // // // Input L : Full Liouvillian (rad/sec) // // R : Relaxation Superoperator (rad/sec) // // seq : Equilibrium density operator // // Return sss : Steady state density matrix // // Note : Careful R & L units, usually Ho is Hz! // // Note : L is singular, thus steady state must // // be determined in a reduced Liouville // // space. Best done with matrix routines // // not (code simple) superop. functions! // // Note : Algorithm needs density matrix trace = 1 // // Function insures this then returns trace // // back to the original value. // // L|s > = R|s > -------> [L - L|S><E|]|s > = R|s > - |L1> // ss eq ss eq // // { // double d = 1.e-9; // R.LOp_base(L); // Insure R in Liouville base of L // if(R.below(d)) // If R==0, |s > = 0 // { // ss // if(warn) // { // densop X; // X.SIGMAerror(10); // } // return gen_op(); // } // else if(L == R) // If R==L, |s > = s > // return seq; // ss eq // else // { // basis Lbs = L.get_basis(); // Store the Hilbert basis of L // int hs = seq.dim(); // Get the Hilbert space size // int ls = hs*hs; // Compute the Liouville space // matrix Emx(hs,hs,i_matrix_type); // Temporary Identity matrix // matrix trace1 = Emx/complex(hs); // Scale by dimension // seq += trace1; // Set trace to 1 for this // seq.Op_base(Lbs); // Put operator into L basis // //// Calculate Equation Right Hand Side of Steady State Equation //// //// ' //// |s > = R|s > - |L1> //// eq eq // // matrix L1, ssp, sub_ssp; // L1=(L.get_mx()).get_block(0,0,ls,1);// L1 matrix = 1st column of L // ssp=((R*seq).get_mx()).resize(ls,1);// Modified seq, basis of R // ssp -= L1; // |ssp> = R|seq> - |L1> // sub_ssp = ssp.get_block(1,0,ls-1,1);// Reduced space seq (as matrix) // //// Calculate Equation Left Hand Side of Steady State Equation //// //// X = L - L|S><E| //// // // matrix Smx(hs, hs, 0.0); // Temproray Null matrix // Smx.put(1.0, 0, 0); // 1st element of Smx set to 1 // gen_op S(Smx, Lbs); // Create the S operator // gen_op E(Emx, Lbs); // Create the S operator // super_op SE(S,E); // SE = |S><E| // super_op X = L; // X -= L*SE; // X = L - L|S><E| // matrix sub_X((X.get_mx()). // Reduced space X // get_block(1,1,ls-1,ls-1)); // //// Form the LU Decomposition of the Reduced & Modified Liouville Matrix //// //// ' -1 ' // X|s > = |s > ----> |s > = X |s > // - -ss -eq -ss - -eq // // ' -1 ' // LU|s > = |s > ----> |s > = (LU) |s > // -- -ss -eq -ss -- -eq // // matrix ALU = sub_X; // int *indx; // indx = new int[ls-1]; // LU_decomp(ALU,indx); // //// Calculate the Steady State Density Matrix //// //// -1 ' trace //// |s > = (LU) |s > ; |s > ------> |s > //// -ss -- -eq -ss ss // // // matrix sub_sss = sub_ssp; // Steady state in subspace // LU_backsub(ALU,indx,sub_sss); // Back solve for steady state // matrix sssmx(hs, hs, 0.0); // Reform the full steady state // int k=0; // density matrix in Hilbert // for(int i=0; i<hs; i++) // space. // for(int j=0; j<hs; j++) // if(i!=0 || j!=0) // All but first element // { // sssmx.put(sub_sss.get(k,0),i,j); // k++; // } // sssmx.put(1.0-trace(sssmx),0,0); // First element from trace // sssmx.resize(hs,hs); // Back to a square array // sssmx -= trace1; // Set trace back to 0 // gen_op sss(sssmx, seq.get_basis()); // Put this into a gen. op. // delete [] indx; // return sss; // } // } gen_op SigmaSS(super_op& L, super_op& R, gen_op& s_eq, int warn){ // Input L : Full Liouvillian (rad/sec) // R : Relaxation Superoperator (rad/sec) // seq : Equilibrium density operator // Return sss : Steady state density matrix // Note : Careful R & L units, usually Ho is Hz! // Note : Direct calculation in Liouvillian eigenbasis //Note : Solving L|s_ss>=R|s_eq> for |s_ss> //Note : L is set to eigenbasis //Note : R is modified to same Hilbert space as L and default Liouvillian space //Note : s_eq is not modified (copied to seq) //Note : sss has the same hilbert space as s_eq const double dm = 1.e-9; // Threshold to determine if a Liouvillian matrix is negligible const double dv = 1.e-9; // Threshold to determine if an eigenvalue is null const int ls=L.LS(); //Liouville space dimension const int hs=L.HS(); //Hilbert space dimension //0) Quick dimensional check if((R.HS()!=hs)||(s_eq.HS()!=hs)){ if(warn){ densop X; // X.SIGMAerror(10); } return s_eq; } //CASE 1: negligible relaxation; steady state is null if(R.below(dm)) { // If R==0, |s > = 0 if(warn){ // ss densop X; // X.SIGMAerror(10); } return gen_op(); } //CASE 2: negligible evolution; steady state is equilibrium if((L-R).below(dm)){ // If (L-R)==0, |s > = s > return s_eq; // ss eq } //CASE 3: calculation of steady state operators gen_op seq=s_eq; //copy of equilibrium density matrix //1) Ensure all of relevant operators in correct basis L.set_EBR(); //Set L in eigenbasis representation R.LOp_base(L); R.set_HBR(); //Set R to same Hilbert base of L and then to default Liouvillian representation seq.Op_base(L.get_basis()); //Set equilibrium density matrix to same Hilbert space as L //NOTE: In equations R'|s'_eq>=(B^-1)R|s_eq> so no need to calculate //|s'_eq> if R is in HBR //2) Extraction of relevant matrices matrix mL=L.get_mx(); //Diagonal Liouvillian matrix mR=R.get_mx(); //Relaxation term matrix mB=L.get_Lbasis().get_mx(); //Transformation to Diagonal Liouvillian basis matrix mB_inv(ls,ls,i_matrix_type);mB_inv/=mB; //Inverse transformation matrix vseq=seq.get_mx().resize(ls,1); //Equilibrium density matrix in vector form matrix vI(ls, 1, complex(1,0)); //Identity vector //3) Performing calculations matrix vR=mB_inv*mR*vseq; //Right hand side of equation R'|s'_eq> = (B^-1)R|s_eq> matrix vL=mL*vI; //vector containing the eigenvalues on the diagonal of L' //4) Determining vsss' (in L eigenbasis) matrix vsss(ls,1); //Steady state vector in Liouvillian eigenbasis for(int i=0; i<ls; i++){ //for every eigenvalue if(norm(vL.get(i,0))<dv){ //If it is null if(norm(vR.get(i,0))<dv){ //And if also the right hand side term (R'|s_eq>) is null vsss.put(complex(0,0),i,0); //The element of the vsss vector is null } else{ //Otherwise (null eigenvalue && non-null right hand side) a problem appeared if(warn){ //Throws an error "steady state does not exist" densop X; // X.SIGMAerror(10); } //the impossibility to determine the steady state (divergent evolution) return gen_op(); //And returns a null generic_operator } } else{vsss.put(vR.get(i,0)/vL.get(i,0),i,0);} //Otherwise, if the eigenvalue is non-null then calculates the relative steady state element } //5) Arranging for gen_op output matrix msss=(mB*vsss).resize(hs,hs); //calculatin |s_ss>=B|s'_ss> (default Liouvillian representation) in matrix form gen_op sss=seq; //creating output operator in same hilbert basis as all the previous calculations sss.put_mx(msss); //placing matrix in operator sss.Op_base(s_eq); //Setting output density matrix in input basis return sss; //output operator } gen_op SigmaSS(const spin_sys& sys, super_op& L, super_op& R, int warn) { gen_op seq = SigmaEq(sys); return SigmaSS(L, R, seq, warn); } // ____________________________________________________________________________ // Y DENSITY OPERATOR AUXILIARY FUNCTIONS // ____________________________________________________________________________ /* ostream& densop::printMQC(const spin_system& sys, ostream& ostr) const // Input Sigma : A density operator (this) // ostr : An output stream // Output ostr : Output stream that has had // Sigma written into it { int ns = sys.spins(); // Spins in the sytsem String labels[ns+1]; // Allocate space for labels for(int i=0; i<ns; i++) { switch(i) { case 0: label[i] = "ZQC"; break; case 1: label[i] = "SQC"; break; case 2: label[i] = "DQC"; break; case 3: label[i] = "TQC"; break; default: label[i] = Gdec(i) + String("QC"); break; } } label[ns] = "POP"; return ostr; } */ // ____________________________________________________________________________ // Z DENSITY OPERATOR OUTPUT FUNCTIONS // ____________________________________________________________________________ std::ostream& densop::print(std::ostream& ostr, int full) const // Input Sigma : A density operator (this) // ostr : An output stream // full : Flag for amount of output // Output ostr : Output stream that has had // Sigma written into it { ostr << "\nDensity Operator Time: " << Sigmat << " s\n"; if(full >= 0) gen_op::print(ostr, full); return ostr; } std::ostream &operator << (std::ostream &ostr, const densop &Sigma) // Input Sigma : A density operator // ostr : Output stream // Output none : Density operator info is sent // to the output stream { Sigma.print(ostr); return ostr; } #endif // DensOp.cc
38.528121
142
0.499982
pygamma-mrs
5cbfb57dbf158fd18afd8345200ef56aa1a67373
141
cpp
C++
Source/SGame/iTween/iTAux.cpp
ZDron3/SimpleGame-Match-
427040e3dce0e76c710e0baab021f9a9ae2a8530
[ "MIT" ]
null
null
null
Source/SGame/iTween/iTAux.cpp
ZDron3/SimpleGame-Match-
427040e3dce0e76c710e0baab021f9a9ae2a8530
[ "MIT" ]
null
null
null
Source/SGame/iTween/iTAux.cpp
ZDron3/SimpleGame-Match-
427040e3dce0e76c710e0baab021f9a9ae2a8530
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "SGame.h" #include "iTweenPCH.h" #include "iTAux.h"
23.5
78
0.751773
ZDron3
5cc0ef5df34f47f89c08726ab7e1c8117c6210cb
13,688
cpp
C++
cs163-data-structure/Homework/HW2/class.cpp
tavioalves/computerscience-psu
2d36bd46383a92c3fd3b4b17e8efb7313e657789
[ "MIT" ]
null
null
null
cs163-data-structure/Homework/HW2/class.cpp
tavioalves/computerscience-psu
2d36bd46383a92c3fd3b4b17e8efb7313e657789
[ "MIT" ]
null
null
null
cs163-data-structure/Homework/HW2/class.cpp
tavioalves/computerscience-psu
2d36bd46383a92c3fd3b4b17e8efb7313e657789
[ "MIT" ]
null
null
null
/* Filename: class.cpp Created by Alves Silva, Otavio Augusto Date: 05/02/2015 Class: CS 163 - Program #2 Description: This file contains the functions of the class.h */ #include "class.h" // --------------------------- CLASS Customer ---------------------------- // Constructor customer::customer() { name = NULL; order_number = 0; order_time = NULL; } // Destructor customer::~customer() { delete name; name = NULL; delete order_time; order_time = NULL; } // Create a customer with the provided arguments int customer::create_customer(char * new_name, int new_order_number, tm * & new_order_time) { name = new char[strlen(new_name)+1]; strcpy(name, new_name); order_number = new_order_number; order_time = new tm; order_time->tm_hour = new_order_time->tm_hour; order_time->tm_min = new_order_time->tm_min; order_time->tm_sec = new_order_time->tm_sec; order_time->tm_mday = new_order_time->tm_mday; order_time->tm_mon = new_order_time->tm_mon; order_time->tm_year = new_order_time->tm_year; order_time->tm_wday = new_order_time->tm_wday; order_time->tm_yday = new_order_time->tm_yday; order_time->tm_isdst = new_order_time->tm_isdst; return 1; } // This function takes the argument and copies it into the customer's data members int customer::copy_info(const customer & copy_from) { // If the argument doesn't have data if(!copy_from.name) return 0; // Return failed // If the data members already have some thing, // we have to deallocate any memory if(name) delete [] name; if(order_time) delete order_time; // Setting pointers to NULL for safety name = NULL; order_time = NULL; // Starting perform a deep copy name = new char[strlen(copy_from.name)+1]; strcpy(name, copy_from.name); order_number = copy_from.order_number; order_time = new tm; order_time->tm_hour = copy_from.order_time->tm_hour; order_time->tm_min = copy_from.order_time->tm_min; order_time->tm_sec = copy_from.order_time->tm_sec; order_time->tm_mday = copy_from.order_time->tm_mday; order_time->tm_mon = copy_from.order_time->tm_mon; order_time->tm_year = copy_from.order_time->tm_year; order_time->tm_wday = copy_from.order_time->tm_wday; order_time->tm_yday = copy_from.order_time->tm_yday; order_time->tm_isdst = copy_from.order_time->tm_isdst; return 1; // Return success } // This function displays the customer information int customer::display_info() { if(!name) return 0; time_t arrival; arrival = mktime(order_time); // Transform the tm struct in a time_t cout << "Customer name: " << name << endl; cout << "Order number: " << order_number << endl; cout << "Arrival date and time: " << ctime(&arrival) << endl; cout << "---------------------------------------------------" << endl; return 1; } // Retrieve the tm time struct int customer::get_time(tm & to_get)const { if(!order_time) return 0; to_get.tm_hour = order_time->tm_hour; to_get.tm_min = order_time->tm_min; to_get.tm_sec = order_time->tm_sec; to_get.tm_mday = order_time->tm_mday; to_get.tm_mon = order_time->tm_mon; to_get.tm_year = order_time->tm_year; to_get.tm_wday = order_time->tm_wday; to_get.tm_yday = order_time->tm_yday; to_get.tm_isdst = order_time->tm_isdst; return 1; } // ---------------------------- CLASS Queue ------------------------------ // Constructor queue::queue() { rear = NULL; } // Destructor queue::~queue() { while(dequeue()); // While we can dequeue, continue removing rear = NULL; // Point to null for safety } // Add a customer in the queue int queue::enqueue(const customer & to_add) { int success = 0; // If the there is no customer in the queue if(!rear) { rear = new q_node; // Create a rear rear->next = rear; // Point to itself success = rear->a_customer.copy_info(to_add); // Deep copy } else { q_node * temp = new q_node; // Create a new node temp->next = rear->next; // Point to the finish of the queue rear->next = temp; // Linking the queue rear = temp; // Rear is the new node success = rear->a_customer.copy_info(to_add); // Deep copy } return success; // Return the success } int queue::dequeue() { if(!rear) // If there isn't any customers return 0; // Return failed if(rear == rear->next) // If there is just one node left { delete rear; // Delete rear rear = NULL; // Point to null for safety return 1; // Return success } else { q_node * temp = rear->next->next; // Take the penult node delete rear->next; // Delete the first node in the queue rear->next = temp; // Temp is the new rear return 1; // Return success } } // Retrieve information about the first node in the queue int queue::peek(customer & to_peek)const { if(!rear) // If there isn't any node to retrieve return 0; // Return failed else { to_peek.copy_info((rear->next)->a_customer); // Deep copy to the argument return 1; // Return success } } // Display all nodes int queue::display_all() { if(!rear) // If the queue is empty return 0; // Return failed else { q_node * temp = rear->next; // Take the head int count = 0; // Count of customers while(temp != rear) { count += 1; cout << "-------------------- "<< count <<"# Order ---------------------"<< endl; temp->a_customer.display_info(); temp = temp->next; } count += 1; cout << "-------------------- "<< count <<"# Order ---------------------"<< endl; rear->a_customer.display_info(); return 1; // Return success } } // Check if the queue is empty int queue::is_empty() { if(!rear) // If there isn't any node return 1; // Return true else return 0; // Return false } // --------------------------- CLASS Statistic ----------------------------- // Constructor statistic::statistic() { spent_time = 0; average_time = 0; } // Create a statistic with the provided arguments int statistic::create_statistic(float new_spent_time, float new_average_time) { spent_time = new_spent_time; average_time = new_average_time; return 1; // Return success } // Copy the argument informations to the statistic data members int statistic::copy_info(const statistic & copy_from) { // If the argument doesn't have data if(!copy_from.spent_time) return 0; // Return failed // Starting perform a deep copy spent_time = copy_from.spent_time; average_time = copy_from.average_time; return 1; // Return success } // Return the average time to deliver a order int statistic::get_average() { return average_time; } // Return the time to deliver this order int statistic::get_time() { return spent_time; } // Display the data members of a statistic int statistic::display_info() { if(!spent_time) return 0; cout << "The worst time to deliver was: " << spent_time << " secs."<< endl; cout << "The average time to deliver a order is: " << average_time <<" secs."<< endl; cout << "---------------------------------------------------" << endl; return 1; } // ----------------------------- CLASS Stack ------------------------------- // Constructor stack::stack() { head = NULL; top_index = 0; } // Destructor stack::~stack() { while(pop()); // While there is node to pop, continue removing head = NULL; // Set head to NULL for safety } // Push a statistic in the stack int stack::push(const statistic & to_push) { int success = 0; node * current = head; // If the stack is empty if(!current) { current = new node; // Create a new node current->a_statistic = new statistic[MAX]; // Allocate the array for this node current->next = NULL; // Point the next node to null head = current; // Head is the new node success = current->a_statistic[top_index].copy_info(to_push); // Copy information ++top_index; // Increase the top index } else // If there already have more than one node { if(top_index < MAX) // If the array can have more elements { success = current->a_statistic[top_index].copy_info(to_push); // Copy information ++top_index; // Increase the top index } else { node * current = new node; // Create a new node current->a_statistic = new statistic[MAX]; // Allocate the array for this node current->next = head; // Linking the list head = current; // Head is the new node top_index = 0; // Start the top index to zero success = current->a_statistic[top_index].copy_info(to_push); // Copy information ++top_index; // Increase the top index } } return success; // Return success } // Pop a statistic in the stack int stack::pop() { // If the stack is empty if(!head) return 0; // Return failed else { // If top index is bigger than zero if(top_index > 0) { --top_index; // Just decrease the index return 1; // Return success } else // If there is already a node with top index equal to zero { node * temp = head->next; // Keep the next node of head delete head; // Delete head head = NULL; // Point to NULL head = temp; // Temp is the new head if(head) // If there is node top_index = MAX; // Set the top index to the begginer else top_index = 0; // Set the top index to zero } return 1; // Return success } } // Retrieve information of the first statistic in the list int stack::peek(statistic & to_peek)const { if(!head) // If there stack is empty return 0; // Return failed int success = to_peek.copy_info(head->a_statistic[top_index-1]); // Copy information of the statistic in the top return success; // Return success } // Display all nodes in the tack int stack::display_all() { if(!head) // If there stack is empty return 0; // Return failed else { node * current = head; int count = top_index; // Loop for the nodes while(current) { count = top_index; // Loop for the array while(count >= 0) { current->a_statistic[count].display_info(); // Display the content --count; // Decrease the number of elements to display } current = current->next; // Traverse through the list } return 1; // Return success } } // ---------------------------- CLASS Service ------------------------------ // Constructor service::service() { order_queue = new queue; statistic_stack = new stack; customers = 0; } // Destructor service::~service() { delete order_queue; order_queue = NULL; delete statistic_stack; statistic_stack = NULL; } // Add a order in the service system int service::add_order(const customer & to_add) { if(order_queue->enqueue(to_add)) { customers += 1; // Increase the number of customers attended return 1; // Return success } else return 0; // Return failed } // Deliver a order in the service system int service::deliver_order() { if(!order_queue->is_empty()) // If the service queue isn't empty { customer a_customer; // Customer ADT to retrieve statistic a_statistic; // Statistic ADT to push in the stack time_t currentTime; // Auxiliar variable to take the current time tm arrival_time; // tm structure to hold the order's arrival time tm * deliver_time; // tm structure to hold the order's deliver time float average_time; // Average time float last_order_time; // Last amount of time to deliver a order float order_time; // Current order time // Retrive the customer arrival order time order_queue->peek(a_customer); a_customer.get_time(arrival_time); // Take the current time time(&currentTime); deliver_time = localtime(&currentTime); // Transform the tm structures in time_t time_t deliver = mktime(deliver_time); time_t arrival = mktime(&arrival_time); // Calculate the amount of seconds to deliver a order order_time = difftime(deliver, arrival); // Retrieve the last statistic order statistic_stack->peek(a_statistic); last_order_time = a_statistic.get_time(); average_time = a_statistic.get_average(); // With these informations calculate the new average average_time = ((average_time * (customers-1)) + order_time)/customers; // If the last order time is bigger than the current if(last_order_time >= order_time) { // Pop the first statistic // Create a new statistic and update the average // And push in the stack statistic_stack->pop(); a_statistic.create_statistic(last_order_time, average_time); statistic_stack->push(a_statistic); } else { // Create a new statistic with the average and new time worst time // And push in the stack a_statistic.create_statistic(order_time, average_time); statistic_stack->push(a_statistic); } order_queue->dequeue(); // Remove the order in the food cart return 1; // Return success } else return 0; // Return failed } // Display all orders in the food cart int service::display_orders() { if(order_queue->display_all()) return 1; else return 0; } // Display all statistic in the system int service::display_statistics() { if(statistic_stack->display_all()) return 1; else return 0; }
25.681051
113
0.627776
tavioalves
5cc264622f7cfd4487387e6b7699b8960507b69c
14,948
cc
C++
test/test_script_parse.cc
pekdon/plux
74d7dd1e4bd57dda0b2a3754e77af068205dabe1
[ "MIT" ]
null
null
null
test/test_script_parse.cc
pekdon/plux
74d7dd1e4bd57dda0b2a3754e77af068205dabe1
[ "MIT" ]
null
null
null
test/test_script_parse.cc
pekdon/plux
74d7dd1e4bd57dda0b2a3754e77af068205dabe1
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include "test.hh" #include "script_parse.hh" class TestScriptParseCtx : public plux::ScriptParseCtx, public TestSuite { public: TestScriptParseCtx() : plux::ScriptParseCtx(), TestSuite("ScriptParseCtx") { register_test("starts_with", std::bind(&TestScriptParseCtx::test_starts_with, this)); register_test("ends_with", std::bind(&TestScriptParseCtx::test_ends_with, this)); register_test("substr", std::bind(&TestScriptParseCtx::test_substr, this)); } virtual ~TestScriptParseCtx() { } void test_starts_with() { do_test_starts_with("my full line", 0); do_test_starts_with(" my full line", 2); } void do_test_starts_with(const std::string& line, unsigned int start) { this->line = line; this->start = start; ASSERT_EQUAL("starts_with, full line", true, starts_with("my full line")); ASSERT_EQUAL("starts_with, prefix", true, starts_with("my ")); ASSERT_EQUAL("starts_with, other prefix", false, starts_with("their")); ASSERT_EQUAL("starts_with, long line", false, starts_with("my full line, long")); } void test_ends_with() { do_test_ends_with("my full line", 0); do_test_ends_with(" my full line", 2); } void do_test_ends_with(const std::string& line, unsigned int start) { this->line = line; this->start = start; ASSERT_EQUAL("ends_with, full line", true, ends_with("my full line")); ASSERT_EQUAL("ends_with, suffix", true, ends_with(" line")); ASSERT_EQUAL("ends_with, other suffix", false, ends_with("word")); ASSERT_EQUAL("ends_with, long line", false, ends_with("my full line, long")); } void test_substr() { do_test_substr("my full line", 0); do_test_substr(" my full line", 2); } void do_test_substr(const std::string& line, unsigned int start) { this->line = line; this->start = start; ASSERT_EQUAL("substr, full line", "my full line", substr(0, 0)); ASSERT_EQUAL("substr, prefix", "my", substr(0, 10)); ASSERT_EQUAL("substr, suffix", "line", substr(8, 0)); ASSERT_EQUAL("substr, middle", "full", substr(3, 5)); } }; class TestScriptParse : public plux::ScriptParse, public TestSuite { public: TestScriptParse(std::istream* is) : plux::ScriptParse(":memory:", is), TestSuite("ScriptParse") { register_test("next_line", std::bind(&TestScriptParse::test_next_line, this)); register_test("parse", std::bind(&TestScriptParse::test_parse, this)); register_test("parse_function", std::bind(&TestScriptParse::test_parse_function, this)); register_test("parse_header_require", std::bind(&TestScriptParse::test_parse_config, this)); register_test("parse_shell", std::bind(&TestScriptParse::test_parse_shell, this)); register_test("parse_call", std::bind(&TestScriptParse::test_parse_line_call, this)); register_test("parse_line_cmd_output", std::bind(&TestScriptParse::test_parse_line_cmd_output, this)); register_test("parse_line_cmd_error", std::bind(&TestScriptParse::test_parse_line_cmd_error, this)); register_test("parse_line_cmd_match", std::bind(&TestScriptParse::test_parse_line_cmd_match, this)); register_test("parse_line_cmd_global", std::bind(&TestScriptParse::test_parse_line_cmd_global, this)); register_test("parse_line_cmd_local", std::bind(&TestScriptParse::test_parse_line_cmd_local, this)); register_test("parse_line_cmd_timeout", std::bind(&TestScriptParse::test_parse_line_cmd_timeout, this)); register_test("parse_line_cmd_unknown", std::bind(&TestScriptParse::test_parse_line_cmd_unknown, this)); } void test_next_line() { plux::ScriptParseCtx ctx; // ensure that last line (without newline) is parsed std::istringstream is1("last line"); set_is(&is1); ASSERT_EQUAL("last line", true, next_line(ctx)); ASSERT_EQUAL("last line", "last line", ctx.line); ASSERT_EQUAL("last line", false, next_line(ctx)); // parse line with only - on it std::istringstream is2(" -\n !test\n"); set_is(&is2); ASSERT_EQUAL("only -", true, next_line(ctx)); ASSERT_EQUAL("only -", " -", ctx.line); ASSERT_EQUAL("only -", true, next_line(ctx)); ASSERT_EQUAL("only -", " !test", ctx.line); ASSERT_EQUAL("only -", false, next_line(ctx)); // skip blank/empty lines and comments std::istringstream is3("\n \n #test\nlast"); set_is(&is3); ASSERT_EQUAL("skip blank", true, next_line(ctx)); ASSERT_EQUAL("skip blank", "last", ctx.line); ASSERT_EQUAL("skip blank", false, next_line(ctx)); } void test_parse() { // FIXME: script does not start with [doc] // FIXME: not [enddoc] as first [ after [doc] // FIXME: unexpected content in headers // FIXME: unexpected content in shell // FIXME: unexpected content in cleanup // FIXME: verify shell is cleanup after [cleanup] } void test_parse_function() { std::istringstream is1("!echo true\n" "?true\n" "[endfunction]\n"); set_is(&is1); auto line = parse_function(ctx("[function no-args]")); auto fun = dynamic_cast<plux::Function*>(line); ASSERT_EQUAL("no args", true, fun != nullptr); ASSERT_EQUAL("no args", "no-args", fun->name()); ASSERT_EQUAL("no args", 0, fun->num_args()); ASSERT_EQUAL("no args", 2, fun->line_end() - fun->line_begin()); delete line; std::istringstream is2("!echo $arg1 $arg2\n" "[endfunction]\n"); set_is(&is2); line = parse_function(ctx("[function args arg1 arg2]")); fun = dynamic_cast<plux::Function*>(line); ASSERT_EQUAL("args", true, fun != nullptr); ASSERT_EQUAL("args", "args", fun->name()); ASSERT_EQUAL("args", 2, fun->num_args()); ASSERT_EQUAL("args", "arg1", *fun->args_begin()); ASSERT_EQUAL("args", "arg2", *(fun->args_begin() + 1)); ASSERT_EQUAL("args", 1, fun->line_end() - fun->line_begin()); delete line; } void test_parse_config() { auto line = parse_config(ctx("[config require=V1]")); auto hdr = dynamic_cast<plux::HeaderConfigRequire*>(line); ASSERT_EQUAL("var only", true, hdr != nullptr); ASSERT_EQUAL("var only", "V1", hdr->key()); ASSERT_EQUAL("var only", "", hdr->val()); delete line; line = parse_config(ctx("[config require=V1=V2]")); hdr = dynamic_cast<plux::HeaderConfigRequire*>(line); ASSERT_EQUAL("var only", true, hdr != nullptr); ASSERT_EQUAL("var only", "V1", hdr->key()); ASSERT_EQUAL("var only", "V2", hdr->val()); delete line; } void test_parse_shell() { std::string name; ASSERT_EQUAL("valid", true, parse_shell(ctx("[shell test]"), name)); ASSERT_EQUAL("valid", std::string("test"), name); ASSERT_EQUAL("valid with offset", true, parse_shell(ctx("[shell with-dash]"), name)); ASSERT_EQUAL("valid with offset", "with-dash", name); try { parse_shell(ctx("[shell missing-end"), name); ASSERT_EQUAL("missing end", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("missing end", "shell command does not end with ]", ex.error()); } try { parse_shell(ctx("[shell invalid/char]"), name); ASSERT_EQUAL("invalid char", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("invalid char", "invalid shell name: invalid/char. only " "A-Z, a-z, 0-9, - and _ allowed", ex.error()); } try { parse_shell(ctx("[shell cleanup]"), name); ASSERT_EQUAL("reserved name (cleanup)", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("reserved name (cleanup)", "invalid shell name: cleanup. only " "A-Z, a-z, 0-9, - and _ allowed", ex.error()); } ASSERT_EQUAL("not shell", false, parse_shell(ctx("[cleanup]"), name)); } void test_parse_line_call() { plux::Line* line; line = parse_line_cmd(ctx("[call no-args]")); auto cline = dynamic_cast<plux::LineCall*>(line); ASSERT_EQUAL("call", true, cline != nullptr); ASSERT_EQUAL("call", "no-args", cline->name()); ASSERT_EQUAL("call", 0, cline->num_args()); delete line; line = parse_line_cmd(ctx("[call args one two]")); cline = dynamic_cast<plux::LineCall*>(line); ASSERT_EQUAL("call, args", true, cline != nullptr); ASSERT_EQUAL("call, args", "args", cline->name()); ASSERT_EQUAL("call, args", 2, cline->num_args()); delete line; } void test_parse_line_cmd_output() { plux::Line* line; line = parse_line_cmd(ctx("!echo 'test'")); auto oline = dynamic_cast<plux::LineOutput*>(line); ASSERT_EQUAL("output", true, oline != nullptr); ASSERT_EQUAL("output", std::string("echo 'test'\n"), oline->output()); delete line; } void test_parse_line_cmd_error() { plux::Line* line; line = parse_line_cmd(ctx("-")); auto eline = dynamic_cast<plux::LineSetErrorPattern*>(line); ASSERT_EQUAL("clear error", true, eline != nullptr); ASSERT_EQUAL("clear error", "", eline->pattern()); delete line; line = parse_line_cmd(ctx("-error")); eline = dynamic_cast<plux::LineSetErrorPattern*>(line); ASSERT_EQUAL("set error", true, eline != nullptr); ASSERT_EQUAL("set error", "error", eline->pattern()); delete line; } void test_parse_line_cmd_match() { plux::Line* line; line = parse_line_cmd(ctx("???exact match")); auto eline = dynamic_cast<plux::LineExactMatch*>(line); ASSERT_EQUAL("exact match", true, eline != nullptr); ASSERT_EQUAL("exact match", "exact match", eline->pattern()); delete line; line = parse_line_cmd(ctx("??match $HOME")); auto vline = dynamic_cast<plux::LineVarMatch*>(line); ASSERT_EQUAL("var match", true, vline != nullptr); ASSERT_EQUAL("var match", "match $HOME", vline->pattern()); delete line; line = parse_line_cmd(ctx("?^A.*$var$")); auto rline = dynamic_cast<plux::LineRegexMatch*>(line); ASSERT_EQUAL("regex match", true, rline != nullptr); ASSERT_EQUAL("regex match", "^A.*$var$", rline->pattern()); delete line; } void test_parse_line_cmd_global() { plux::Line* line; line = parse_line_cmd(ctx("[global my=value]")); auto gline = dynamic_cast<plux::LineVarAssignGlobal*>(line); ASSERT_EQUAL("global", true, gline != nullptr); ASSERT_EQUAL("global", "my", gline->key()); ASSERT_EQUAL("global", "value", gline->val()); delete line; } void test_parse_line_cmd_local() { plux::Line* line; line = parse_line_cmd(ctx("[local my=value]")); auto lline = dynamic_cast<plux::LineVarAssignShell*>(line); ASSERT_EQUAL("local", true, lline != nullptr); ASSERT_EQUAL("local", "my-shell", lline->shell()); ASSERT_EQUAL("local", "my", lline->key()); ASSERT_EQUAL("local", "value", lline->val()); delete line; } void test_parse_line_cmd_timeout() { plux::Line* line; line = parse_line_cmd(ctx("[timeout]")); auto tline = dynamic_cast<plux::LineTimeout*>(line); ASSERT_EQUAL("timeout default", true, tline != nullptr); ASSERT_EQUAL("timeout default", plux::default_timeout_ms, tline->timeout()); delete line; line = parse_line_cmd(ctx("[timeout 2]")); tline = dynamic_cast<plux::LineTimeout*>(line); ASSERT_EQUAL("timeout 2s", true, tline != nullptr); ASSERT_EQUAL("timeout 2s", 2000, tline->timeout()); delete line; try { parse_line_cmd(ctx("[timeout nan]")); ASSERT_EQUAL("timeout nan", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("timeout nan", "invalid timeout, not a valid number", ex.error()); } } void test_parse_line_cmd_unknown() { try { parse_line_cmd(ctx("% unknown command")); ASSERT_EQUAL("unknown", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("unknown", "unexpected content", ex.error()); } try { parse_line_cmd(ctx("[unknown]")); ASSERT_EQUAL("unknown", false, true); } catch (plux::ScriptParseError& ex) { ASSERT_EQUAL("unknown", "unexpected content, unsupported function", ex.error()); } } plux::ScriptParseCtx& ctx(const std::string& line) { _ctx.shell = "my-shell"; _ctx.start = 2; _ctx.line = " " + line; return _ctx; } private: plux::ScriptParseCtx _ctx; }; int main(int argc, char* argv[]) { TestScriptParseCtx test_script_parse_ctx; std::istringstream is(""); TestScriptParse test_script_parse(&is); try { return TestSuite::main(argc, argv); } catch (plux::PluxException& ex) { std::cerr << ex.to_string() << std::endl; return 1; } }
35.254717
79
0.549906
pekdon
5cc4f924f678b5da011b1e6ab201cb0f04b1e7a3
576
cpp
C++
Week-2/Editorials/Contest_2/problem-4/solution.cpp
tanayduggad0299/CP-Buddy-Series
29b85801f216e10e1817ce0769dd2d9d98856163
[ "MIT" ]
58
2020-08-02T16:38:43.000Z
2021-04-11T15:17:07.000Z
Week-2/Editorials/Contest_2/problem-4/solution.cpp
tanayduggad0299/CP-Buddy-Series
29b85801f216e10e1817ce0769dd2d9d98856163
[ "MIT" ]
29
2020-08-03T08:48:05.000Z
2020-10-05T08:25:09.000Z
Week-2/Editorials/Contest_2/problem-4/solution.cpp
tanayduggad0299/CP-Buddy-Series
29b85801f216e10e1817ce0769dd2d9d98856163
[ "MIT" ]
44
2020-08-02T16:51:08.000Z
2021-03-04T13:51:01.000Z
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #define ll long long int int p = 1; using namespace std; void fun(ll x, ll n){ cout << x << " "; x = p > 0 ? x - 5 : x + 5; if(x != n){ if(x <= 0){ p = 0; } fun(x,n); }else{ cout << x << endl; } } int main() { ll t; cin >> t; while(t--){ ll n; cin >> n; p = 1; if(n == 0){ cout << n << endl; }else{ fun(n,n); } } return 0; }
15.567568
30
0.383681
tanayduggad0299
5cc5e1da71c980fbeb0ec7091c2ad1f8a1fe881c
2,384
cc
C++
chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/chromeos/assistant_optin/value_prop_screen_handler.h" #include "chrome/browser/browser_process.h" #include "chrome/grit/generated_resources.h" #include "components/login/localized_values_builder.h" namespace { const char kJsScreenPath[] = "AssistantValuePropScreen"; constexpr const char kUserActionSkipPressed[] = "skip-pressed"; constexpr const char kUserActionNextPressed[] = "next-pressed"; } // namespace namespace chromeos { ValuePropScreenHandler::ValuePropScreenHandler( OnAssistantOptInScreenExitCallback callback) : BaseWebUIHandler(), exit_callback_(std::move(callback)) { set_call_js_prefix(kJsScreenPath); } ValuePropScreenHandler::~ValuePropScreenHandler() = default; void ValuePropScreenHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) { builder->Add("locale", g_browser_process->GetApplicationLocale()); // TODO(updowndota) Replace this with new string constants. // Use string constant for old flow for now before we have final UX. builder->Add("valuePropLoading", IDS_VOICE_INTERACTION_VALUE_PROP_LOADING); builder->Add("valuePropLoadErrorTitle", IDS_VOICE_INTERACTION_VALUE_PROP_LOAD_ERROR_TITLE); builder->Add("valuePropLoadErrorMessage", IDS_VOICE_INTERACTION_VALUE_PROP_LOAD_ERROR_MESSAGE); builder->Add("valuePropRetryButton", IDS_VOICE_INTERACTION_VALUE_PROP_RETRY_BUTTON); builder->Add("valuePropMoreButton", IDS_VOICE_INTERACTION_VALUE_PROP_MORE_BUTTION); builder->Add("back", IDS_EULA_BACK_BUTTON); builder->Add("next", IDS_EULA_NEXT_BUTTON); } void ValuePropScreenHandler::RegisterMessages() { AddPrefixedCallback("userActed", &ValuePropScreenHandler::HandleUserAction); } void ValuePropScreenHandler::Initialize() {} void ValuePropScreenHandler::HandleUserAction(const std::string& action) { DCHECK(exit_callback_); if (action == kUserActionSkipPressed) std::move(exit_callback_) .Run(AssistantOptInScreenExitCode::VALUE_PROP_SKIPPED); else if (action == kUserActionNextPressed) std::move(exit_callback_) .Run(AssistantOptInScreenExitCode::VALUE_PROP_ACCEPTED); } } // namespace chromeos
36.676923
87
0.776007
zipated
5cc92b4690bd96ef62a0acfafa82483ca2617abc
49,629
cpp
C++
cubicvr/source/datatree/DataTree.cpp
cjcliffe/CubicVR
2f833c61eb045ff845d2b3b001a02a258337f15c
[ "MIT" ]
48
2015-02-04T09:43:20.000Z
2021-09-29T00:45:28.000Z
cubicvr/source/datatree/DataTree.cpp
mcanthony/CubicVR
2f833c61eb045ff845d2b3b001a02a258337f15c
[ "MIT" ]
2
2016-06-08T09:03:52.000Z
2021-04-09T01:01:47.000Z
cubicvr/source/datatree/DataTree.cpp
mcanthony/CubicVR
2f833c61eb045ff845d2b3b001a02a258337f15c
[ "MIT" ]
17
2015-07-24T08:28:44.000Z
2021-04-09T02:14:21.000Z
/* * DataElement/DataNode/DataTree -- structured serialization/unserialization system * designed for the CoolMule project :) * Copyright (C) 2003 by Charles J. Cliffe 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. */ #include <CubicVR/datatree/DataTree.h> #include <CubicVR/StringUtil.h> #include <CubicVR/Logger.h> #include <fstream> /* DataElement class */ DataElement::DataElement() { data_type = DATA_NULL; data_val = NULL; data_size = 0; } DataElement::~DataElement() { if (data_val) delete data_val; } void DataElement::data_init(long data_size_in) { if (data_val) delete data_val; data_size = data_size_in; data_val = new char[data_size]; } int DataElement::getDataType() { return data_type; } long DataElement::getDataSize() { return data_size; } //void DataElement::set(const bool &bool_in) //{ // data_type = DATA_BOOL; // data_init(sizeof(bool)); // memcpy(data_val,&bool_in,data_size); //} void DataElement::set(const int &int_in) { data_type = DATA_INT; data_init(sizeof(int)); memcpy(data_val,&int_in,data_size); } void DataElement::set(const long &long_in) { data_type = DATA_LONG; data_init(sizeof(long)); memcpy(data_val,&long_in,data_size); } void DataElement::set(const float &float_in) { data_type = DATA_FLOAT; data_init(sizeof(float)); memcpy(data_val,&float_in,data_size); } void DataElement::set(const double &double_in) { data_type = DATA_DOUBLE; data_init(sizeof(double)); memcpy(data_val,&double_in,data_size); } void DataElement::set(const char *data_in, long size_in) { data_type = DATA_FLOAT; data_init(size_in); memcpy(data_val,data_in,data_size); } void DataElement::set(const char *data_in) { data_type = DATA_CHAR; data_init(strlen(data_in)+1); memcpy(data_val,data_in,data_size); } void DataElement::set(const string &str_in) { data_type = DATA_STRING; data_init(str_in.length()+1); memcpy(data_val,str_in.c_str(),data_size); } void DataElement::set(const XYZ &xyz_in) { data_type = DATA_XYZ; data_init(sizeof(cvrFloat)*3); cvrFloat xyz_dbl[3]; xyz_dbl[0] = xyz_in.x; xyz_dbl[1] = xyz_in.y; xyz_dbl[2] = xyz_in.z; memcpy(data_val,xyz_dbl,data_size); } void DataElement::set(vector<XYZ> &xyzvect_in) { vector<XYZ>::iterator i; long vectsize; long ptr; data_type = DATA_XYZVECTOR; vectsize = xyzvect_in.size()*sizeof(cvrFloat)*3; data_init(vectsize); ptr = 0; cvrFloat xyz_dbl[3]; for (i = xyzvect_in.begin(); i != xyzvect_in.end(); i++) { xyz_dbl[0] = (*i).x; xyz_dbl[1] = (*i).y; xyz_dbl[2] = (*i).z; memcpy(data_val+ptr, xyz_dbl, sizeof(cvrFloat)*3); ptr += sizeof(cvrFloat)*3; } } void DataElement::set(vector<string> &strvect_in) { vector<string>::iterator i; long vectsize; long ptr; data_type = DATA_STRVECTOR; vectsize = 0; for (i = strvect_in.begin(); i != strvect_in.end(); i++) { vectsize += (*i).length()+1; } data_init(vectsize); ptr = 0; for (i = strvect_in.begin(); i != strvect_in.end(); i++) { int str_length; str_length = (*i).length()+1; memcpy(data_val+ptr, (*i).c_str(), str_length); ptr += str_length; } } void DataElement::set(std::set<string> &strset_in) { std::set<string>::iterator i; vector<string> tmp_vect; for (i = strset_in.begin(); i != strset_in.end(); i++) { tmp_vect.push_back(*i); } set(tmp_vect); } void DataElement::set(vector<int> &intvect_in) { long ptr; int temp_int; data_type = DATA_INTVECTOR; data_init(sizeof(int)*intvect_in.size()); vector<int>::iterator i; ptr = 0; for (i = intvect_in.begin(); i != intvect_in.end(); i++) { temp_int = *i; memcpy(data_val+ptr, &temp_int, sizeof(int)); ptr += sizeof(int); } } void DataElement::set(vector<long> &longvect_in) { long ptr; long temp_long; data_type = DATA_LONGVECTOR; data_init(sizeof(long)*longvect_in.size()); vector<long>::iterator i; ptr = 0; for (i = longvect_in.begin(); i != longvect_in.end(); i++) { temp_long = *i; memcpy(data_val+ptr, &temp_long, sizeof(long)); ptr += sizeof(long); } } void DataElement::set(vector<float> &floatvect_in) { long ptr; float temp_float; data_type = DATA_FLOATVECTOR; data_init(sizeof(float)*floatvect_in.size()); // vector<float>::iterator i; // // ptr = 0; // // for (i = floatvect_in.begin(); i != floatvect_in.end(); i++) // { // temp_float = *i; // memcpy(data_val+ptr, &temp_float, sizeof(float)); // ptr += sizeof(float); // } memcpy(data_val,&floatvect_in[0],sizeof(float)*floatvect_in.size()); } void DataElement::set(vector<double> &doublevect_in) { long ptr; double temp_double; data_type = DATA_DOUBLEVECTOR; data_init(sizeof(double)*doublevect_in.size()); vector<double>::iterator i; ptr = 0; for (i = doublevect_in.begin(); i != doublevect_in.end(); i++) { temp_double = *i; memcpy(data_val+ptr, &temp_double, sizeof(double)); ptr += sizeof(double); } } //void DataElement::get(bool &bool_in) throw (DataTypeMismatchException) //{ // if (!data_type) return; // if (data_type != DATA_BOOL) throw(new DataTypeMismatchException("Type mismatch, not a BOOL")); // // memcpy(&bool_in, data_val, data_size); //} void DataElement::get(int &int_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_INT && data_type != DATA_LONG) throw(new DataTypeMismatchException("Type mismatch, not a INT")); if (data_type == DATA_LONG) { long tmp_long; memcpy(&tmp_long, data_val, data_size); int_in = (int)tmp_long; } else { memcpy(&int_in, data_val, data_size); } } void DataElement::get(long &long_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_LONG && data_type != DATA_INT) throw(new DataTypeMismatchException("Type mismatch, not a LONG")); if (data_type == DATA_INT) { int tmp_int; memcpy(&tmp_int, data_val, data_size); long_in = (long)tmp_int; } else { memcpy(&long_in, data_val, data_size); } } void DataElement::get(float &float_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_FLOAT && data_type != DATA_DOUBLE && data_type != DATA_INT && data_type != DATA_LONG) throw(new DataTypeMismatchException("Type mismatch, not a FLOAT")); if (data_type == DATA_DOUBLE) { float tmp_double; memcpy(&tmp_double, data_val, data_size); float_in = (float)tmp_double; } else if (data_type == DATA_LONG) { long tmpInt; get(tmpInt); float_in = (float)tmpInt; } else if (data_type == DATA_INT) { int tmpInt; get(tmpInt); float_in = (float)tmpInt; } else { memcpy(&float_in, data_val, data_size); } } void DataElement::get(double &double_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_DOUBLE && data_type != DATA_FLOAT) throw(new DataTypeMismatchException("Type mismatch, not a DOUBLE")); if (data_type == DATA_FLOAT) { float tmp_float; memcpy(&tmp_float, data_val, data_size); double_in = (double)tmp_float; } else { memcpy(&double_in, data_val, data_size); } } void DataElement::get(char **data_in) throw (DataTypeMismatchException) { if (data_type != DATA_CHAR) throw(new DataTypeMismatchException("Type mismatch, not a CHAR")); *data_in = new char[data_size]; memcpy(*data_in, data_val, data_size); } void DataElement::get(string &str_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_STRING && data_type != DATA_CHAR) throw(new DataTypeMismatchException("Type mismatch, not a STRING")); if (!str_in.empty()) // flush the string { str_in.erase(str_in.begin(),str_in.end()); } str_in.append(data_val); } void DataElement::get(vector<string> &strvect_in) throw (DataTypeMismatchException) { long ptr; if (!data_type) return; if (data_type != DATA_STRVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a STRING VECTOR")); ptr = 0; while (ptr != data_size) { strvect_in.push_back(string(data_val+ptr)); ptr += strlen(data_val+ptr)+1; } } void DataElement::get(std::set<string> &strset_in) throw (DataTypeMismatchException) { if (!data_type) return; if (data_type != DATA_STRVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a STRING VECTOR/SET")); std::vector<string> tmp_vect; std::vector<string>::iterator i; get(tmp_vect); for (i = tmp_vect.begin(); i != tmp_vect.end(); i++) { strset_in.insert(*i); } } void DataElement::get(vector<int> &intvect_in) throw (DataTypeMismatchException) { long ptr; if (!data_type) return; if (data_type != DATA_INTVECTOR && data_type != DATA_LONGVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a INT VECTOR")); ptr = 0; if (data_type == DATA_LONGVECTOR) { long temp_long; while (ptr < data_size) { temp_long = 0; memcpy(&temp_long,data_val+ptr,sizeof(long)); intvect_in.push_back((int)temp_long); ptr += sizeof(long); } } else { int temp_int; while (ptr < data_size) { temp_int = 0; memcpy(&temp_int,data_val+ptr,sizeof(int)); intvect_in.push_back(temp_int); ptr += sizeof(int); } } } void DataElement::get(vector<long> &longvect_in) throw (DataTypeMismatchException) { long ptr; if (!data_type) return; if (data_type != DATA_LONGVECTOR && data_type != DATA_INTVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a LONG VECTOR")); ptr = 0; if (data_type == DATA_LONGVECTOR) { long temp_long; while (ptr < data_size) { temp_long = 0; memcpy(&temp_long,data_val+ptr,sizeof(long)); longvect_in.push_back(temp_long); ptr += sizeof(long); } } else { int temp_int; while (ptr < data_size) { temp_int = 0; memcpy(&temp_int,data_val+ptr,sizeof(int)); longvect_in.push_back((long)temp_int); ptr += sizeof(int); } } } void DataElement::get(vector<float> &floatvect_in) throw (DataTypeMismatchException) { long ptr; if (!data_type) return; if (data_type != DATA_FLOATVECTOR && data_type != DATA_DOUBLEVECTOR && data_type != DATA_INTVECTOR && data_type != DATA_LONGVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a FLOAT VECTOR")); ptr = 0; if (data_type == DATA_DOUBLEVECTOR) { float temp_double; while (ptr < data_size) { temp_double = 0; memcpy(&temp_double,data_val+ptr,sizeof(double)); floatvect_in.push_back((float)temp_double); ptr += sizeof(double); } } if (data_type == DATA_INTVECTOR) { int temp_int; while (ptr < data_size) { temp_int = 0; memcpy(&temp_int,data_val+ptr,sizeof(int)); floatvect_in.push_back((float)temp_int); ptr += sizeof(int); } } else { float temp_float; while (ptr < data_size) { temp_float = 0; memcpy(&temp_float,data_val+ptr,sizeof(float)); floatvect_in.push_back(temp_float); ptr += sizeof(float); } } } void DataElement::get(vector<double> &doublevect_in) throw (DataTypeMismatchException) { long ptr; if (!data_type) return; if (data_type != DATA_DOUBLEVECTOR && data_type != DATA_FLOATVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a DOUBLE VECTOR")); ptr = 0; if (data_type == DATA_FLOATVECTOR) { float temp_float; while (ptr < data_size) { temp_float = 0; memcpy(&temp_float,data_val+ptr,sizeof(float)); doublevect_in.push_back((double)temp_float); ptr += sizeof(float); } } else { double temp_double; while (ptr < data_size) { temp_double = 0; memcpy(&temp_double,data_val+ptr,sizeof(double)); doublevect_in.push_back(temp_double); ptr += sizeof(double); } } } void DataElement::get(XYZ &xyz_in) throw (DataTypeMismatchException) { if (!data_type) return; cvrFloat xyz_dbl[3]; if (data_type != DATA_XYZ) throw(new DataTypeMismatchException("Type mismatch, not a XYZ")); memcpy(&xyz_dbl, data_val, data_size); xyz_in = XYZ(xyz_dbl[0],xyz_dbl[1],xyz_dbl[2]); } void DataElement::get(vector<XYZ> &xyzvect_in) throw (DataTypeMismatchException) { if (!data_type) return; XYZ temp_xyz; cvrFloat dbl_xyz[3]; long ptr; if (data_type != DATA_XYZVECTOR) throw(new DataTypeMismatchException("Type mismatch, not a XYZ VECTOR")); ptr = 0; while (ptr < data_size) { memcpy(&dbl_xyz,data_val+ptr,sizeof(cvrFloat)*3); xyzvect_in.push_back(XYZ(dbl_xyz[0],dbl_xyz[1],dbl_xyz[2])); ptr += sizeof(cvrFloat)*3; } } long DataElement::getSerializedSize() { return sizeof(unsigned char)+sizeof(unsigned int)+data_size; } long DataElement::getSerialized(char **ser_str) { long ser_size = getSerializedSize(); *ser_str = new char[ser_size]; char *ser_pointer; ser_pointer = *ser_str; memcpy(ser_pointer, &data_type, sizeof(unsigned char)); ser_pointer+=sizeof(unsigned char); memcpy(ser_pointer, &data_size, sizeof(unsigned int)); ser_pointer+=sizeof(unsigned int); memcpy(ser_pointer, data_val, data_size); return ser_size; } void DataElement::setSerialized(char *ser_str) { char *ser_pointer = ser_str; memcpy(&data_type,ser_pointer,sizeof(unsigned char)); ser_pointer+=sizeof(unsigned char); memcpy(&data_size,ser_pointer,sizeof(unsigned int)); ser_pointer+=sizeof(unsigned int); data_init(data_size); memcpy(data_val,ser_pointer,data_size); } /* DataNode class */ DataNode::DataNode() { ptr = 0; parentNode = NULL; } DataNode::DataNode(const char *name_in) { ptr = 0; node_name = name_in; parentNode = NULL; } DataNode::~DataNode() { for (vector<DataNode *>::iterator i = children.begin(); i != children.end(); i++) { delete *i; } } void DataNode::setName(const char *name_in) { node_name = name_in; } DataElement &DataNode::element() { return data_elem; } DataNode &DataNode::newChild(const char *name_in) { children.push_back(new DataNode(name_in)); childmap[name_in].push_back(children.back()); children.back()->setParentNode(*this); return *children.back(); } DataNode &DataNode::child(const char *name_in, int index) throw (DataInvalidChildException) { DataNode *child_ret; child_ret = childmap[name_in][index]; if (!child_ret) { stringstream error_str; error_str << "no child '" << index << "' in DataNode '" << node_name << "'"; throw (DataInvalidChildException(error_str.str().c_str())); } return *child_ret; } DataNode &DataNode::child(int index) throw (DataInvalidChildException) { DataNode *child_ret; child_ret = children[index]; if (!child_ret) { stringstream error_str; error_str << "no child '" << index << "' in DataNode '" << node_name << "'"; throw (DataInvalidChildException(error_str.str().c_str())); } return *child_ret; } int DataNode::numChildren() { return children.size(); } int DataNode::numChildren(const char *name_in) { return childmap[name_in].size(); } bool DataNode::hasAnother() { return children.size() != ptr; } bool DataNode::hasAnother(const char *name_in) { return childmap[name_in].size() != childmap_ptr[name_in]; } DataNode &DataNode::getNext() throw (DataInvalidChildException) { return child(ptr++); } DataNode &DataNode::getNext(const char *name_in) throw (DataInvalidChildException) { return child(name_in,childmap_ptr[name_in]++); } void DataNode::rewind() { ptr = 0; } void DataNode::rewind(const char *name_in) { childmap_ptr[name_in] = 0; } /* DataTree class */ DataTree::DataTree(const char *name_in) { dn_root.setName(name_in); } DataTree::DataTree() { } DataTree::~DataTree() { }; DataNode &DataTree::rootNode() { return dn_root; } /* GameObject *newGO = createGO(filename); if(newGO) { printf("Loading GameObject from XML\n"); TiXmlDocument doc( filename.c_str() ); if(doc.LoadFile()) { printf("Loaded XML\n"); TiXmlNode *root = doc.FirstChild( "gameobject" ); if(root) { printf("Found root\n"); TiXmlNode *goc = root->FirstChild( "goc" ); while(goc) { printf("Game object\n"); TiXmlElement *gocEl = goc->ToElement(); std::string type = gocEl->Attribute("type"); if(type == "gocMesh") { printf("MESH COMPONENT!\n"); GameObjectComponent *gocComponent = new gocMesh(); newGO->addGOC(gocComponent); gocMesh *mesh = static_cast<gocMesh *>(gocComponent); mesh->load_xml(goc); mesh->bind(scene); } else if(type == "gocRigid") { printf("RIGID COMPONENT!\n"); GameObjectComponent *mRigid = new gocRigid(); newGO->addGOC(mRigid); gocRigid *rigid = static_cast<gocRigid *>(mRigid); rigid->load_xml(goc); rigid->bind((RigidScene *)scene); } else if(type == "gocLight") { printf("LIGHT COMPONENT!\n"); GameObjectComponent *mLight = new gocLight(); newGO->addGOC(mLight); gocLight *light = static_cast<gocLight *>(mLight); light->load_xml(goc); light->bind(scene); } else if(type == "gocCamera") { printf("CAMERA COMPONENT!\n"); GameObjectComponent *mCamera = new gocCamera(); newGO->addGOC(mCamera); gocCamera *camera = static_cast<gocCamera *>(mCamera); camera->load_xml(goc); camera->bind(scene); } else if(type == "gocTerrain") { printf("TERRAIN COMPONENT!\n"); GameObjectComponent *mTerrain = new gocTerrain(); newGO->addGOC(mTerrain); gocTerrain *terrain = static_cast<gocTerrain *>(mTerrain); terrain->load_xml(goc); terrain->bind((RigidScene *)scene); } else if(type == "gocScript") { printf("SCRIPT COMPONENT!\n"); GameObjectComponent *mScript = new gocScript(); newGO->addGOC(mScript); gocScript *script = static_cast<gocScript *>(mScript); script->load_xml(goc); //script->bind(scene); } printf("Type: %s\n", type.c_str()); goc = goc->NextSibling(); } } else { printf("No root\n"); } //printf("%s\n", root->Value()); } else { printf("Couldn't load: %s\n", filename.c_str()); } void write_simple_doc2( ) { // same as write_simple_doc1 but add each node // as early as possible into the tree. TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" ); doc.LinkEndChild( decl ); TiXmlElement * element = new TiXmlElement( "Hello" ); doc.LinkEndChild( element ); TiXmlText * text = new TiXmlText( "World" ); element->LinkEndChild( text ); dump_to_stdout( &doc ); doc.SaveFile( "madeByHand2.xml" ); } */ std::string trim(std::string& s,const std::string& drop = " ") { std::string r=s.erase(s.find_last_not_of(drop)+1); return r.erase(0,r.find_first_not_of(drop)); } void DataTree::decodeXMLText(DataNode *elem, const char *src_text, DT_FloatingPointPolicy fpp) { long tmp_long; int tmp_int; double tmp_double; float tmp_float; string tmp_str; string tmp_str2; std::stringstream tmp_stream; std::stringstream tmp_stream2; XYZ tmp_xyz; vector<long> tmp_longvect; vector<long>::iterator tmp_longvect_i; vector<int> tmp_intvect; vector<double> tmp_doublevect; vector<double>::iterator tmp_doublevect_i; vector<float> tmp_floatvect; vector<XYZ> tmp_xyzvect; bool vInts = false; string in_text = src_text; trim(in_text); trim(in_text,"\r\n"); tmp_stream.clear(); tmp_stream2.clear(); if (in_text.find_first_not_of("0123456789-") == string::npos) { tmp_stream << in_text; tmp_stream >> tmp_long; tmp_int = tmp_long; if (tmp_int == tmp_long) { elem->element().set((int)tmp_int); } else { elem->element().set((long)tmp_long); } } else if (in_text.find_first_not_of("0123456789.e+-") == string::npos) { tmp_stream << in_text; if (fpp == USE_FLOAT) { tmp_stream >> tmp_float; elem->element().set((float)tmp_float); } else { tmp_stream >> tmp_double; elem->element().set((double)tmp_double); } } else if (in_text.find_first_not_of("0123456789.,e+-") == string::npos) { str_replace(","," ",in_text); tmp_stream << in_text; tmp_stream >> tmp_xyz.x; tmp_stream >> tmp_xyz.y; tmp_stream >> tmp_xyz.z; elem->element().set(tmp_xyz); } else if (in_text.find_first_not_of("0123456789- ") == string::npos) { tmp_stream << in_text; vInts = true; while (!tmp_stream.eof()) { tmp_stream >> tmp_long; tmp_int = tmp_long; if (tmp_int != tmp_long) { vInts = false; // printf("Failed int: [%d] != [%ld]\n",tmp_int,tmp_long); } tmp_longvect.push_back((long)tmp_long); } if (vInts) { tmp_intvect.clear(); for (tmp_longvect_i = tmp_longvect.begin(); tmp_longvect_i != tmp_longvect.end(); tmp_longvect_i++) { tmp_intvect.push_back(*tmp_longvect_i); } tmp_longvect.clear(); elem->element().set(tmp_intvect); } else { elem->element().set(tmp_longvect); } } else if (in_text.find_first_not_of("0123456789.e-+ ") == string::npos) { tmp_stream << in_text; if (fpp == USE_FLOAT) { tmp_floatvect.clear(); } else { tmp_doublevect.clear(); } while (!tmp_stream.eof()) { if (fpp == USE_FLOAT) { tmp_stream >> tmp_float; tmp_floatvect.push_back(tmp_float); } else { tmp_stream >> tmp_double; tmp_doublevect.push_back(tmp_double); } } if (fpp == USE_FLOAT) { elem->element().set(tmp_floatvect); } else { elem->element().set(tmp_doublevect); } } else if (in_text.find_first_not_of("0123456789.,e-+ ") == string::npos) { tmp_stream << in_text; while (!tmp_stream.eof()) { tmp_stream >> tmp_str2; str_replace(","," ",tmp_str2); tmp_stream2 << tmp_str2; tmp_stream2 >> tmp_xyz.x; tmp_stream2 >> tmp_xyz.y; tmp_stream2 >> tmp_xyz.z; tmp_stream2.clear(); tmp_xyzvect.push_back(tmp_xyz); } elem->element().set(tmp_xyzvect); } else { elem->element().set(src_text); // printf( "Unhandled DataTree XML Field: [%s]", tmp_str.c_str() ); } } void DataTree::setFromXML(DataNode *elem, TiXmlNode *elxml, bool root_node, DT_FloatingPointPolicy fpp) { TiXmlText *pText; int t = elxml->Type(); string tmp_str; switch ( t ) { case TiXmlNode::DOCUMENT: // printf( "Document" ); break; case TiXmlNode::ELEMENT: if (!root_node) elem = &elem->newChild(elxml->Value()); const TiXmlAttribute *attribs; attribs = elxml->ToElement()->FirstAttribute(); while (attribs) { //Logger::log(LOG_DEBUG,"attrib value: @%s = %s\n\n",attribs->Name(), attribs->Value()); // following badgerfish xml->json and xml->ruby convention for attributes.. string attrName("@"); attrName.append(attribs->Name()); decodeXMLText(&elem->newChild(attrName.c_str()), attribs->Value(), fpp); attribs = attribs->Next(); } // printf( "Element \"%s\"", elxml->Value()); break; case TiXmlNode::COMMENT: // printf( "Comment: \"%s\"", elxml->Value()); break; case TiXmlNode::UNKNOWN: // printf( "Unknown" ); break; case TiXmlNode::TEXT: pText = elxml->ToText(); decodeXMLText(elem, pText->Value(), fpp); // pText = elxml->ToText(); // printf( "Text: [%s]", pText->Value() ); break; case TiXmlNode::DECLARATION: // printf( "Declaration" ); break; default: break; } // printf( "\n" ); TiXmlNode * pChild; if (!elxml->NoChildren()) { if (elxml->FirstChild()->Type() == TiXmlNode::ELEMENT) { if (elxml->FirstChild()->Value() == TIXML_STRING("str")) { std::vector<std::string> tmp_strvect; for ( pChild = elxml->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { if (pChild->Value() == TIXML_STRING("str")) { if (!pChild->FirstChild()) { tmp_strvect.push_back(""); continue; } pText = pChild->FirstChild()->ToText(); if (pText) { tmp_str = pText->Value(); tmp_strvect.push_back(tmp_str); } } } elem->element().set(tmp_strvect); return; } } } for ( pChild = elxml->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { setFromXML( elem, pChild, false, fpp ); } } void DataTree::nodeToXML(DataNode *elem, TiXmlElement *elxml) { DataNode *child; elem->rewind(); while (elem->hasAnother()) { child = &elem->getNext(); std::string nodeName = child->getName(); TiXmlElement *element; element = new TiXmlElement(nodeName.length()?nodeName.c_str():"node"); std::string tmp; std::stringstream tmp_stream; TiXmlText *text; XYZ tmp_xyz; std::vector<XYZ> tmp_xyzvect; std::vector<XYZ>::iterator tmp_xyzvect_i; std::vector<float> tmp_floatvect; std::vector<float>::iterator tmp_floatvect_i; std::vector<double> tmp_doublevect; std::vector<double>::iterator tmp_doublevect_i; std::vector<int> tmp_intvect; std::vector<int>::iterator tmp_intvect_i; std::vector<long> tmp_longvect; std::vector<long>::iterator tmp_longvect_i; std::vector<string> tmp_stringvect; std::vector<string>::iterator tmp_stringvect_i; TiXmlElement *tmp_node; char *tmp_pstr; double tmp_double; float tmp_float; long tmp_long; int tmp_int; switch (child->element().getDataType()) { case DATA_NULL: break; case DATA_INT: child->element().get(tmp_int); tmp_stream.clear(); tmp_stream << tmp_int; text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); break; case DATA_LONG: child->element().get(tmp_long); tmp_stream.clear(); tmp_stream << tmp_long; text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); break; case DATA_FLOAT: child->element().get(tmp_float); tmp_stream.clear(); tmp_stream << tmp_float; text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); break; case DATA_DOUBLE: child->element().get(tmp_double); tmp_stream.clear(); tmp_stream << tmp_double; text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); break; case DATA_CHAR: child->element().get(&tmp_pstr); // following badgerfish xml->json and xml->ruby convention for attributes.. if (nodeName.substr(0,1)==string("@")) { elxml->SetAttribute(nodeName.substr(1).c_str(), tmp_pstr); delete element; element = NULL; } else { text = new TiXmlText(tmp_pstr); element->LinkEndChild(text); } delete tmp_pstr; break; case DATA_STRING: child->element().get(tmp); if (nodeName.substr(0,1)==string("@")) { elxml->SetAttribute(nodeName.substr(1).c_str(), tmp.c_str()); delete element; element = NULL; } else { text = new TiXmlText(tmp.c_str()); element->LinkEndChild(text); } break; case DATA_STRVECTOR: child->element().get(tmp_stringvect); tmp_stream.clear(); for (tmp_stringvect_i = tmp_stringvect.begin(); tmp_stringvect_i != tmp_stringvect.end(); tmp_stringvect_i++) { tmp_node = new TiXmlElement("str"); text = new TiXmlText((*tmp_stringvect_i).c_str()); tmp_node->LinkEndChild(text); element->LinkEndChild(tmp_node); } tmp_stringvect.clear(); break; case DATA_INTVECTOR: child->element().get(tmp_intvect); tmp_stream.clear(); for (tmp_intvect_i = tmp_intvect.begin(); tmp_intvect_i != tmp_intvect.end(); tmp_intvect_i++) { tmp_stream << (*tmp_intvect_i); if (tmp_intvect_i != tmp_intvect.end()-1) tmp_stream << " "; } text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); tmp_intvect.clear(); break; case DATA_LONGVECTOR: child->element().get(tmp_longvect); tmp_stream.clear(); for (tmp_longvect_i = tmp_longvect.begin(); tmp_longvect_i != tmp_longvect.end(); tmp_longvect_i++) { tmp_stream << (*tmp_longvect_i); if (tmp_longvect_i != tmp_longvect.end()-1) tmp_stream << " "; } text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); tmp_longvect.clear(); break; case DATA_FLOATVECTOR: child->element().get(tmp_floatvect); tmp_stream.clear(); for (tmp_floatvect_i = tmp_floatvect.begin(); tmp_floatvect_i != tmp_floatvect.end(); tmp_floatvect_i++) { tmp_stream << (*tmp_floatvect_i); if (tmp_floatvect_i != tmp_floatvect.end()-1) tmp_stream << " "; } text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); tmp_floatvect.clear(); break; case DATA_DOUBLEVECTOR: child->element().get(tmp_doublevect); tmp_stream.clear(); for (tmp_doublevect_i = tmp_doublevect.begin(); tmp_doublevect_i != tmp_doublevect.end(); tmp_doublevect_i++) { tmp_stream << (*tmp_doublevect_i); if (tmp_doublevect_i != tmp_doublevect.end()-1) tmp_stream << " "; } text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); tmp_doublevect.clear(); break; case DATA_XYZ: child->element().get(tmp_xyz); tmp_stream.clear(); tmp_stream << tmp_xyz.x; tmp_stream << ","; tmp_stream << tmp_xyz.y; tmp_stream << ","; tmp_stream << tmp_xyz.z; text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); break; case DATA_XYZVECTOR: child->element().get(tmp_xyzvect); tmp_stream.clear(); for (tmp_xyzvect_i = tmp_xyzvect.begin(); tmp_xyzvect_i != tmp_xyzvect.end(); tmp_xyzvect_i++) { tmp_stream << (*tmp_xyzvect_i).x; tmp_stream << ","; tmp_stream << (*tmp_xyzvect_i).y; tmp_stream << ","; tmp_stream << (*tmp_xyzvect_i).z; if (tmp_xyzvect_i != tmp_xyzvect.end()-1) tmp_stream << " "; } text = new TiXmlText(tmp_stream.str().c_str()); element->LinkEndChild(text); tmp_xyzvect.clear(); break; } if (element) { elxml->LinkEndChild(element); if (child->numChildren()) { nodeToXML(child,element); } } } elem->rewind(); } void DataTree::printXML() /* get serialized size + return node names header */ { TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" ); doc.LinkEndChild( decl ); DataNode *root = &rootNode(); string rootName = root->getName(); TiXmlElement *element = new TiXmlElement(rootName.empty()?"root":rootName.c_str()); doc.LinkEndChild( element ); if (!root->numChildren()) doc.Print(); nodeToXML(root,element); root->rewind(); doc.Print(); } long DataTree::getSerializedSize(DataElement &de_node_names, bool debug) /* get serialized size + return node names header */ { long total_size = 0; stack<DataNode *> dn_stack; vector<string> node_names; map<string, int, string_less> node_name_index_map; DataElement de_name_index; // just used for sizing purposes DataElement de_num_children; de_name_index.set((int)0); de_num_children.set((int)0); int de_name_index_size = de_name_index.getSerializedSize(); int de_num_children_size = de_num_children.getSerializedSize(); dn_stack.push(&dn_root); while (!dn_stack.empty()) { int name_index; // int num_children; /* build the name list */ if (dn_stack.top()->getName().empty()) { name_index = 0; /* empty string */ } else if (node_name_index_map[dn_stack.top()->getName().c_str()] == 0) { node_names.push_back(string(dn_stack.top()->getName())); name_index = node_names.size(); node_name_index_map[dn_stack.top()->getName().c_str()] = name_index; } else { name_index = node_name_index_map[dn_stack.top()->getName().c_str()]; } /* add on the size of the name index and number of children */ total_size += de_name_index_size; total_size += de_num_children_size; total_size += dn_stack.top()->element().getSerializedSize(); /* debug output */ if (debug) { for (unsigned int i = 0; i < dn_stack.size()-1; i++) cout << "--"; cout << (dn_stack.top()->getName().empty()?"NULL":dn_stack.top()->getName()) << "(" << dn_stack.top()->element().getSerializedSize() << ")"; cout << " type: " << dn_stack.top()->element().getDataType() << endl; //cout << " index: " << name_index << endl; } /* end debug output */ /* if it has children, traverse into them */ if (dn_stack.top()->hasAnother()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } else { /* no more children, back out until we have children, then add next child to the top */ while (!dn_stack.empty()) { if (!dn_stack.top()->hasAnother()) { dn_stack.top()->rewind(); dn_stack.pop(); } else break; } if (!dn_stack.empty()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } } } /* set the header for use in serialization */ de_node_names.set(node_names); total_size += de_node_names.getSerializedSize(); return total_size; } void DataNode::findAll(const char *name_in, vector<DataNode *> &node_list_out) { stack<DataNode *> dn_stack; /* start at the root */ dn_stack.push(this); if (string(getName()) == string(name_in)) node_list_out.push_back(this); while (!dn_stack.empty()) { while (dn_stack.top()->hasAnother(name_in)) { node_list_out.push_back(&dn_stack.top()->getNext(name_in)); } /* if it has children, traverse into them */ if (dn_stack.top()->hasAnother()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } else { /* no more children, back out until we have children, then add next child to the top */ while (!dn_stack.empty()) { if (!dn_stack.top()->hasAnother()) { dn_stack.top()->rewind(); dn_stack.pop(); } else break; } if (!dn_stack.empty()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } } } } long DataTree::getSerialized(char **ser_str, bool debug) { long data_ptr = 0; long data_size = 0; stack<DataNode *> dn_stack; vector<string> node_names; map<string, int, string_less> node_name_index_map; /* header of node names, grabbed from getserializedsize to avoid having to memmove() or realloc() */ DataElement de_node_names; data_size = getSerializedSize(de_node_names,debug); *ser_str = (char *)malloc(data_size); char *data_out = *ser_str; /* name list header */ char *de_node_names_serialized; long de_node_names_serialized_size; de_node_names.getSerialized(&de_node_names_serialized); de_node_names_serialized_size = de_node_names.getSerializedSize(); /* copy the header and increase the pointer */ memcpy(data_out,de_node_names_serialized,de_node_names_serialized_size); data_ptr += de_node_names_serialized_size; // if (debug) Logger::log(LOG_DEBUG,"serialized header size: %d",de_node_names_serialized_size); /* start at the root */ dn_stack.push(&dn_root); while (!dn_stack.empty()) { int name_index; int num_children; DataElement de_name_index; DataElement de_num_children; char *de_name_index_serialized; char *de_num_children_serialized; char *element_serialized; long de_name_index_serialized_size; long de_num_children_serialized_size; long element_serialized_size; /* build the name list */ if (dn_stack.top()->getName().empty()) { name_index = 0; /* empty string */ } else if (node_name_index_map[dn_stack.top()->getName().c_str()] == 0) { node_names.push_back(string(dn_stack.top()->getName())); name_index = node_names.size(); node_name_index_map[dn_stack.top()->getName().c_str()] = name_index; } else { name_index = node_name_index_map[dn_stack.top()->getName().c_str()]; } num_children = dn_stack.top()->numChildren(); de_name_index.set(name_index); de_num_children.set(num_children); de_name_index_serialized_size = de_name_index.getSerializedSize(); de_num_children_serialized_size = de_num_children.getSerializedSize(); element_serialized_size = dn_stack.top()->element().getSerializedSize(); de_name_index.getSerialized(&de_name_index_serialized); de_num_children.getSerialized(&de_num_children_serialized); dn_stack.top()->element().getSerialized(&element_serialized); /* add on the name index and number of children */ memcpy(data_out+data_ptr,de_name_index_serialized,de_name_index_serialized_size); data_ptr += de_name_index_serialized_size; memcpy(data_out+data_ptr,de_num_children_serialized,de_num_children_serialized_size); data_ptr += de_num_children_serialized_size; /* add on the data element */ memcpy(data_out+data_ptr,element_serialized,element_serialized_size); data_ptr += element_serialized_size; delete de_name_index_serialized; delete de_num_children_serialized; delete element_serialized; /* if it has children, traverse into them */ if (dn_stack.top()->hasAnother()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } else { /* no more children, back out until we have children, then add next child to the top */ while (!dn_stack.empty()) { if (!dn_stack.top()->hasAnother()) { dn_stack.top()->rewind(); dn_stack.pop(); } else break; } if (!dn_stack.empty()) { dn_stack.push(&dn_stack.top()->getNext()); dn_stack.top()->rewind(); } } } return data_size; } void DataTree::setSerialized(char *ser_str, bool debug) { long data_ptr = 0; // long data_size = 0; stack<DataNode *> dn_stack; stack<int> dn_childcount_stack; vector<string> node_names; DataElement de_node_names; de_node_names.setSerialized(ser_str); data_ptr+=de_node_names.getSerializedSize(); de_node_names.get(node_names); DataElement de_name_index; DataElement de_num_children; DataElement de_element; dn_stack.push(&dn_root); dn_childcount_stack.push(0); /* root (parent null) has no siblings */ /* unserialization is a little less straightforward since we have to do a countdown of remaining children */ while (!dn_stack.empty()) { int name_index; int num_children; /* pull the index of the name of this node */ de_name_index.setSerialized(ser_str+data_ptr); data_ptr += de_name_index.getSerializedSize(); /* pull the number of children this node has */ de_num_children.setSerialized(ser_str+data_ptr); data_ptr += de_num_children.getSerializedSize(); /* get values from the temp dataelements */ de_name_index.get(name_index); de_num_children.get(num_children); /* pull the node's element */ dn_stack.top()->element().setSerialized(ser_str+data_ptr); data_ptr += dn_stack.top()->element().getSerializedSize(); /* debug output */ if (debug) { for (unsigned int i = 0; i < dn_stack.size()-1; i++) cout << "--"; cout << (name_index?node_names[name_index-1]:"NULL") << "(" << dn_stack.top()->element().getSerializedSize() << ")"; cout << " index: " << name_index << endl; } /* end debug output */ /* name index >= 1 means it has a name */ if (name_index) { dn_stack.top()->setName(node_names[name_index-1].c_str()); } else /* name is nil */ { dn_stack.top()->setName(""); } if (num_children) /* Has children, create first child and push it to the top */ { dn_childcount_stack.push(num_children); /* push the child count onto the stack */ de_name_index.setSerialized(ser_str+data_ptr); /* peek at the new child name but don't increment pointer */ de_name_index.get(name_index); /* add this child onto the top of the stack */ dn_stack.push(&dn_stack.top()->newChild((name_index?node_names[name_index-1]:string("")).c_str())); dn_childcount_stack.top()--; /* decrement to count the new child */ } else /* No children, move on to the next sibling */ { if (dn_childcount_stack.top()) /* any siblings remaining? */ { de_name_index.setSerialized(ser_str+data_ptr); /* peek at the new child name but don't increment pointer */ de_name_index.get(name_index); dn_stack.pop(); dn_stack.push(&dn_stack.top()->newChild((name_index?node_names[name_index-1]:string("")).c_str())); /* create the next sibling and throw it on the stack */ dn_childcount_stack.top()--; /* decrement to count the new sibling */ } else /* This is the last sibling, move up the stack and find the next */ { while (!dn_stack.empty()) /* move up the stack until we find the next sibling */ { if (dn_childcount_stack.top()) { de_name_index.setSerialized(ser_str+data_ptr); /* peek at the new child name but don't increment pointer */ de_name_index.get(name_index); dn_stack.pop(); dn_stack.push(&dn_stack.top()->newChild((name_index?node_names[name_index-1]:string("")).c_str())); /* throw it on the stack */ dn_childcount_stack.top()--; /* count it */ break; } else { dn_childcount_stack.pop(); dn_stack.pop(); /* if no more siblings found the stack will empty naturally */ } } } } } } bool DataTree::LoadFromFileXML(const std::string& filename, DT_FloatingPointPolicy fpp) { TiXmlDocument doc(filename.c_str()); bool loadOkay = doc.LoadFile(); if (!loadOkay) { Logger::log(LOG_ERROR,"LoadFromFileXML[error loading]: \"%s\"\n",filename.c_str()); return false; } TiXmlNode *xml_root_node = doc.RootElement(); if (!xml_root_node) { Logger::log(LOG_ERROR,"LoadFromFileXML[error no root]: \"%s\"\n",filename.c_str()); return false; } rootNode().setName(xml_root_node->ToElement()->Value()); setFromXML(&rootNode(),xml_root_node,true,fpp); return true; } bool DataTree::SaveToFileXML(const std::string& filename) { TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" ); doc.LinkEndChild( decl ); string rootName = rootNode().getName(); TiXmlElement *element = new TiXmlElement(rootName.empty()?"root":rootName.c_str()); doc.LinkEndChild( element ); nodeToXML(&rootNode(),element); doc.SaveFile(filename.c_str()); return true; } /* bool DataTree::SaveToFile(const std::string& filename) { char *serialized; long dataSize = getSerialized(&serialized); std::ofstream fout(filename.c_str(), ios::binary); fout.write(serialized, dataSize); fout << flush; fout.close(); delete serialized; return true; } bool DataTree::LoadFromFile(const std::string& filename) { char *serialized; long dataSize; ifstream fin(filename.c_str(), ios::binary); fin.seekg (0, ios::end); dataSize = fin.tellg(); fin.seekg (0, ios::beg); serialized = new char[dataSize]; fin.read(serialized,dataSize); fin.close(); setSerialized(serialized); delete serialized; return true; } */ bool DataTree::SaveToFile(const std::string& filename, bool compress, int compress_level) { long dataSize, compressedSize, headerSize; char *serialized, *hdr_serialized, *compressed; DataTree dtHeader; dataSize = getSerialized(&serialized); if (compress) { compressed = new char[(int)ceil(dataSize*1.5)]; compressedSize = fastlz_compress_level(compress_level, serialized, dataSize, compressed); compressed = (char *)realloc(compressed, compressedSize); delete serialized; } DataNode &header = dtHeader.rootNode(); header^"version" = 1.0f; header^"compression" = string(compress?"FastLZ":"none"); header^"uncompressed_size" = dataSize; headerSize = dtHeader.getSerialized(&hdr_serialized); std::ofstream fout(filename.c_str(), ios::binary); fout.write((char *) &headerSize, sizeof(long)); fout.write((char *) &(compress?compressedSize:dataSize), sizeof(long)); fout.write(hdr_serialized, headerSize); fout.write(compress?compressed:serialized, compress?compressedSize:dataSize); fout << flush; fout.close(); delete hdr_serialized; if (!compress) { delete serialized; } else { delete compressed; } return true; } bool DataTree::LoadFromFile(const std::string& filename) { char *compressed,*serialized,*hdr_serialized; long dataSize,headerSize,compressedSize; ifstream fin(filename.c_str(), ios::binary); fin.read((char *)&headerSize, sizeof(long)); fin.read((char *)&compressedSize, sizeof(long)); hdr_serialized = new char[headerSize]; fin.read(hdr_serialized,headerSize); DataTree dtHeader; dtHeader.setSerialized(hdr_serialized); DataNode &header = dtHeader.rootNode(); string compressionType = header["compression"]; dataSize = header["uncompressed_size"]; bool uncompress = false; if (compressionType=="FastLZ") { uncompress = true; } if (uncompress) { compressed = new char[compressedSize]; fin.read(compressed,compressedSize); serialized = new char[dataSize]; fastlz_decompress(compressed, compressedSize, serialized, dataSize); delete compressed; } else { serialized = new char[dataSize]; fin.read(serialized,dataSize); } fin.close(); setSerialized(serialized); delete serialized; delete hdr_serialized; return true; }
24.150365
208
0.61998
cjcliffe
5cc9830d8a598a57784aac82606672e206400e0d
491
cpp
C++
UCTooth_Linux/src/Main.cpp
jcs090218/UCTooth
c53871242cf8fdc9ab67609e212f93ce5fb8cd76
[ "MIT" ]
3
2020-10-09T10:48:15.000Z
2022-01-17T22:01:23.000Z
UCTooth_Linux/src/Main.cpp
jcs090218/UCTooth
c53871242cf8fdc9ab67609e212f93ce5fb8cd76
[ "MIT" ]
null
null
null
UCTooth_Linux/src/Main.cpp
jcs090218/UCTooth
c53871242cf8fdc9ab67609e212f93ce5fb8cd76
[ "MIT" ]
null
null
null
/** * $File: Main.cpp $ * $Date: 2020-07-30 22:47:46 $ * $Revision: $ * $Creator: Jen-Chieh Shen $ * $Notice: See LICENSE.txt for modification and distribution information * Copyright © 2020 by Shen, Jen-Chieh $ */ /** * @func main * @brief Program entry point. */ void main() { long btAddr = 0xB827EB651B47; UCTooth::Connect(btAddr); char msg[] = "Hello World"; UCTooth::Send(msg); UCTooth::Recv(msg); printf("Data is: %s\n", msg); }
18.884615
73
0.584521
jcs090218
5ccaa325836b93a5ff0d33f132e41ce37c1035e8
4,684
hpp
C++
include/gptTracer.hpp
Galfurian/GnuplotTracer
b31db32f9e201616729d0f7bbfbd519ac9ffcc0f
[ "BSD-3-Clause" ]
null
null
null
include/gptTracer.hpp
Galfurian/GnuplotTracer
b31db32f9e201616729d0f7bbfbd519ac9ffcc0f
[ "BSD-3-Clause" ]
null
null
null
include/gptTracer.hpp
Galfurian/GnuplotTracer
b31db32f9e201616729d0f7bbfbd519ac9ffcc0f
[ "BSD-3-Clause" ]
null
null
null
/// @file gnuplotHelper.hpp /// @author Enrico Fraccaroli /// @date Oct 02 2017 /// @copyright /// Copyright (c) 2017 Enrico Fraccaroli <enrico.fraccaroli@univr.it> #pragma once #include "gptValue.hpp" #include "gptBound.hpp" #include <iostream> #ifdef WIN32 #define GNUPLOT_NAME "pgnuplot -persistent" #else #define GNUPLOT_NAME "gnuplot" #endif /// @brief Gnuplot trace generation tracer. class GPTTracer { private: /// The title of the trace. std::string _title; /// The type of terminal. std::string _terminal; /// The background color. std::string _background; /// The foreground color. std::string _foreground; /// The font dimension of the keys. unsigned int _font_key; /// The font dimension for the x axis label. unsigned int _font_size_x_axis; /// The font dimension for the y axis label. unsigned int _font_size_y_axis; /// The boundaries for the x axis. GPTBound * _bound_x; /// The boundaries for the y axis. GPTBound * _bound_y; /// Pipe used to communicate with gnuplot. FILE * _pipe; /// The x axis variable. GPTVariable * _x_variable; /// The y axis variables. std::vector<GPTVariable *> _y_variables; public: /// @brief Constructor. GPTTracer(); /// @brief Constructor. GPTTracer(std::string title, std::string terminal, std::string background, std::string foreground, const unsigned int & font_key, const unsigned int & font_size_x_axis, const unsigned int & font_size_y_axis); /// @brief Destructor. ~GPTTracer(); /// @brief Open the pipe to gnuplot. inline void open() { this->close(); #ifdef WIN32 _pipe = _popen(GNUPLOT_NAME, "w"); #else _pipe = popen(GNUPLOT_NAME, "w"); #endif } /// @brief Checks whether the pipe is open. inline bool isOpened() const { return _pipe != nullptr; } /// @brief Closes the pipe. inline void close() { if (this->isOpened()) { #ifdef WIN32 _pclose(_pipe); #else pclose(_pipe); #endif _pipe = nullptr; } } /// @brief Flushes data on pipe. inline void flush() { if (this->isOpened()) { fflush(_pipe); } } /// @brief Allows to set the boundaries for the x axis. inline void setBoundX(double _lower_bound, double _upper_bound) { _bound_x = new GPTBound(_lower_bound, _upper_bound); } /// @brief Allows to set the boundaries for the y axis. inline void setBoundY(double _lower_bound, double _upper_bound) { _bound_y = new GPTBound(_lower_bound, _upper_bound); } /// @brief Allows to set the variable for the x axis. template<typename T> inline void setVariableX(T * _variable, const std::string & _name, const std::string & _format, const unsigned int & _lineWidth) { assert(_variable); _x_variable = new GPTGenericVariable<T>(_variable, _name, _format, _lineWidth); } /// @brief Allows to add a variable on the y axis. template<typename T> inline void addVariableY(T * _variable, const std::string & _name, const std::string & _format, const unsigned int & _lineWidth) { assert(_variable); _y_variables.emplace_back( new GPTGenericVariable<T>(_variable, _name, _format, _lineWidth)); } /// @brief Prints the data. inline void printData(const bool & visualize) { this->open(); this->setup(); this->addPlotLine(); this->addDataPoints(); this->flush(); // Waits for the user to look at the graph. if (visualize) { std::cin.clear(); std::cin.ignore(std::cin.rdbuf()->in_avail()); std::cin.get(); } } /// @brief Samples the data. inline void sampleData() { _x_variable->sampleValue(); for (auto value : _y_variables) { value->sampleValue(); } } private: void addPlotLine(); void addDataPoints(); void setup(); };
25.736264
69
0.538002
Galfurian
5ccd42bdd220904da181e9a6038210af00f3fc75
2,834
cpp
C++
Source/ZJoy/Private/NetPlayGameState.cpp
avrcolak/ZJoy
32215b739b0f7b394d8ebd0e5ea1da00e595e3f2
[ "Unlicense" ]
null
null
null
Source/ZJoy/Private/NetPlayGameState.cpp
avrcolak/ZJoy
32215b739b0f7b394d8ebd0e5ea1da00e595e3f2
[ "Unlicense" ]
null
null
null
Source/ZJoy/Private/NetPlayGameState.cpp
avrcolak/ZJoy
32215b739b0f7b394d8ebd0e5ea1da00e595e3f2
[ "Unlicense" ]
null
null
null
// This is free and unencumbered software released into the public domain. #include "NetPlayGameState.h" #include "NetPlayPlayerController.h" #include "GameFramework/PlayerState.h" #include "Engine/World.h" #include "Engine/LocalPlayer.h" ANetPlayGameState::ANetPlayGameState() { PrimaryActorTick.bStartWithTickEnabled = false; } void ANetPlayGameState::BeginPlay() { Super::BeginPlay(); ANetPlayPlayerController* FirstLocalPlayerController = nullptr; for (auto Iterator = GetWorld()->GetPlayerControllerIterator(); Iterator; ++Iterator) { auto PlayerController = Cast<ANetPlayPlayerController>(Iterator->Get()); if (PlayerController) { AddTickPrerequisiteActor(PlayerController); ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(PlayerController->Player); if (LocalPlayer && FirstLocalPlayerController == nullptr) { FirstLocalPlayerController = PlayerController; } } } if (FirstLocalPlayerController != nullptr) { FirstLocalPlayerController->ServerSync(); } } void ANetPlayGameState::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); auto Unread = EarliestUnread(); if (Unread <= CurrentFrame) { auto OneBeforeUnread = Unread - 1; for (auto& Relevant : NetPlayRelevant) { auto RollsBack = Cast<IRollsBack>(Relevant); RollsBack->Rollback(CurrentFrame - OneBeforeUnread); } auto ReplayFrame = CurrentFrame; for (CurrentFrame = Unread; CurrentFrame <= ReplayFrame; CurrentFrame++) { for (auto& Relevant : NetPlayRelevant) { Relevant->Tick(DeltaSeconds); } } } else { CurrentFrame++; } } TArray<uint8> ANetPlayGameState::State() { return TArray<uint8>(); } void ANetPlayGameState::SyncState(const TArray<uint8>& State) { return; } void ANetPlayGameState::Sync(const TArray<uint8>& State, int Seed, int PlayerId, int Frame) { SetActorTickEnabled(true); SyncState(State); CurrentFrame = Frame; RandomStream.Initialize(Seed); ReceiveSync(); } void ANetPlayGameState::PeerSync(int Frame, int PlayerId) { ReceivePeerSync(PlayerId); } void ANetPlayGameState::PeerInput(const TArray<uint8>& Input, int PlayerId, int Frame) { // This needs to be handled more gracefully at some point. check(Frame < MinimumRead() + NETPLAY_HISTORY); ReadAndRecievedForPlayer[PlayerId].Recieved = Frame; } int ANetPlayGameState::MinimumRead() { int Min = INT_MAX; for (auto& Pair : ReadAndRecievedForPlayer) { Min = FMath::Min(Pair.Value.Read, Min); } return Min; } int ANetPlayGameState::EarliestUnread() { int Min = INT_MAX; for (auto& Pair : ReadAndRecievedForPlayer) { if (Pair.Value.Recieved > Pair.Value.Read) { Min = FMath::Min(Pair.Value.Read + 1, Min); } } return Min; } void ANetPlayGameState::RegisterForRollback(AActor* Actor) { NetPlayRelevant.Add(Actor); Actor->AddTickPrerequisiteActor(this); }
19.680556
91
0.732534
avrcolak
5cce960449eee7db899f7ae6645e096442c3665b
385
hpp
C++
Source/Arbiter/Graphics/API/Opengl/GLVertexBufferObject.hpp
cookieniffler/Arbiter
271fe56cb9379d9c76704e028e07dfdb9693bd54
[ "BSD-3-Clause" ]
null
null
null
Source/Arbiter/Graphics/API/Opengl/GLVertexBufferObject.hpp
cookieniffler/Arbiter
271fe56cb9379d9c76704e028e07dfdb9693bd54
[ "BSD-3-Clause" ]
null
null
null
Source/Arbiter/Graphics/API/Opengl/GLVertexBufferObject.hpp
cookieniffler/Arbiter
271fe56cb9379d9c76704e028e07dfdb9693bd54
[ "BSD-3-Clause" ]
null
null
null
#pragma once #ifndef __VERTEXBUFFER_HPP__ #define __VERTEXBUFFER_HPP__ #include <Arbiter/Core/Common/Base.hpp> ARBITER_NAMESPACE_BEGIN OPENGL_NAMESPACE_BEGIN class VertexBuffer : public std::enable_shared_from_this<VertexBuffer> { private: public: VertexBuffer(); virtual ~VertexBuffer() = default; }; OPENGL_NAMESPACE_END ARBITER_NAMESPACE_END #endif // __VERTEXBUFFER_HPP__
16.73913
70
0.820779
cookieniffler
5cceb2450ee4b50e0e6b6ed4cda07357e228ef7a
2,237
hpp
C++
gecode/string/rel-op/lcase.hpp
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
1
2021-05-26T13:27:00.000Z
2021-05-26T13:27:00.000Z
gecode/string/rel-op/lcase.hpp
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
gecode/string/rel-op/lcase.hpp
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
namespace Gecode { namespace String { forceinline ExecStatus LowerCase::post(Home home, StringView x0, StringView x1) { if (x0.same(x1)) { StringVar y(home, x0.may_chars(), x0.min_length(), x0.max_length()); (void) new (home) LowerCase(home, x0, y); rel (home, x1, STRT_EQ, y); } else (void) new (home) LowerCase(home, x0, x1); return ES_OK; } forceinline Actor* LowerCase::copy(Space& home) { return new (home) LowerCase(home, *this); } forceinline LowerCase::LowerCase(Home home, StringView y0, StringView y1) : MixBinaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM> (home, y0, y1) {} forceinline LowerCase::LowerCase(Space& home, LowerCase& p) : MixBinaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM>(home, p) {} forceinline ExecStatus LowerCase::propagate(Space& home, const ModEventDelta&) { // std::cerr<<"LowerCase::propagate "<<x1<<" = lcase("<<x0<<")\n"; int n = x0.pdomain()->length(); NSBlocks lx(n); bool changed = false; for (int i = 0; i < n; ++i) { const DSBlock& bi = x0.pdomain()->at(i); NSIntSet si(bi.S); if (!(bi.S.disjoint(String::UpperCase::_UCASE_SET))) { NSIntSet ti(si); ti.intersect(String::UpperCase::_UCASE_SET); si.exclude(ti); ti.shift(32); si.include(ti); changed = true; } lx[i] = NSBlock(si, bi.l, bi.u); } if (changed) lx.normalize(); GECODE_ME_CHECK(x1.dom(home, lx)); changed = false; n = x1.pdomain()->length(); NSBlocks uy(n); for (int i = 0; i < n; ++i) { const DSBlock& bi = x1.pdomain()->at(i); NSIntSet si(bi.S); if (!(bi.S.disjoint(String::UpperCase::_LCASE_SET))) { NSIntSet ti(si); ti.intersect(String::UpperCase::_LCASE_SET); ti.shift(-32); si.include(ti); changed = true; } uy[i] = NSBlock(si, bi.l, bi.u); } if (changed) uy.normalize(); GECODE_ME_CHECK(x0.dom(home, uy)); // std::cerr<<"LowerCase::propagated "<<x1<<" = lcase("<<x0<<")\n"; assert (x0.pdomain()->is_normalized() && x1.pdomain()->is_normalized()); return ES_FIX; } }}
29.434211
77
0.589629
ramadini
5cd3cba9c9a6bccc9fc7b507b1f7c64f73c48bd2
3,039
cpp
C++
test/unit/models/PlayerFilterTest.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
12
2021-09-28T14:37:22.000Z
2022-03-04T17:54:11.000Z
test/unit/models/PlayerFilterTest.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
null
null
null
test/unit/models/PlayerFilterTest.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
8
2021-11-05T18:56:55.000Z
2022-01-10T11:14:24.000Z
/* Copyright 2021 Enjin Pte. 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 "gtest/gtest.h" #include "JsonTestSuite.hpp" #include "enjinsdk/models/PlayerFilter.hpp" #include <string> #include <vector> using namespace enjin::sdk::models; using namespace enjin::test::suites; class PlayerFilterTest : public JsonTestSuite, public testing::Test { public: PlayerFilter class_under_test; constexpr static char POPULATED_JSON_OBJECT[] = R"({"and":[],"or":[],"id":"1","id_in":[]})"; static PlayerFilter create_default_filter() { return PlayerFilter().set_and(std::vector<PlayerFilter>()) .set_or(std::vector<PlayerFilter>()) .set_id("1") .set_id_in(std::vector<std::string>()); } }; TEST_F(PlayerFilterTest, SerializeNoSetFieldsReturnsEmptyJsonObject) { // Arrange const std::string expected(EMPTY_JSON_OBJECT); // Act std::string actual = class_under_test.serialize(); // Assert ASSERT_EQ(expected, actual); } TEST_F(PlayerFilterTest, SerializeSetFieldsReturnsExpectedJsonObject) { // Arrange const std::string expected(POPULATED_JSON_OBJECT); class_under_test.set_and(std::vector<PlayerFilter>()) .set_or(std::vector<PlayerFilter>()) .set_id("1") .set_id_in(std::vector<std::string>()); // Act std::string actual = class_under_test.serialize(); // Assert ASSERT_EQ(expected, actual); } TEST_F(PlayerFilterTest, EqualityNeitherSideIsPopulatedReturnsTrue) { // Arrange PlayerFilter lhs; PlayerFilter rhs; // Act bool actual = lhs == rhs; // Assert ASSERT_TRUE(actual); } TEST_F(PlayerFilterTest, EqualityBothSidesArePopulatedReturnsTrue) { // Arrange PlayerFilter lhs = create_default_filter(); PlayerFilter rhs = create_default_filter(); // Act bool actual = lhs == rhs; // Assert ASSERT_TRUE(actual); } TEST_F(PlayerFilterTest, EqualityLeftSideIsPopulatedReturnsFalse) { // Arrange PlayerFilter lhs = create_default_filter(); PlayerFilter rhs; // Act bool actual = lhs == rhs; // Assert ASSERT_FALSE(actual); } TEST_F(PlayerFilterTest, EqualityRightSideIsPopulatedReturnsFalse) { // Arrange PlayerFilter lhs; PlayerFilter rhs = create_default_filter(); // Act bool actual = lhs == rhs; // Assert ASSERT_FALSE(actual); }
26.657895
75
0.663047
BlockChain-Station
5cd406d58760cf9d9e8efdeb2542dc5789565895
3,885
cc
C++
src/utils/SplinedCurve.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
37
2017-04-26T16:27:07.000Z
2022-03-01T07:38:57.000Z
src/utils/SplinedCurve.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
494
2016-09-14T02:31:13.000Z
2022-03-13T18:57:05.000Z
src/utils/SplinedCurve.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
43
2016-09-26T17:58:40.000Z
2022-03-25T02:29:59.000Z
/* ------------------------------------------------------------------------- Spline Author: Ethan Coon (coonet@ornl.gov) Spline fit of a curve, given points, values, and derivatives of those values. If needed, this could easily provide a constructor without derivatives, and use an algorithm to construct these derivatives. Provides options for monotonicity preservation. ------------------------------------------------------------------------- */ #include <algorithm> #include "SplinedCurve.hh" namespace Amanzi { namespace Utils { SplinedCurve::SplinedCurve(std::vector<double> x, std::vector<double> y, std::vector<double> dydx, SplineEndpoints_t endpoints, bool enforce_monotonicity) : x_(x), y_(y), dy_(dydx), left_(endpoints.first), right_(endpoints.second), mono_(enforce_monotonicity) { Setup_(); }; void SplinedCurve::Setup(std::vector<double> x, std::vector<double> y, std::vector<double> dydx, SplineEndpoints_t endpoints, bool enforce_monotonicity) { x_ = x; y_ = y; dy_ = dydx; left_ = endpoints.first; right_ = endpoints.second; mono_ = enforce_monotonicity; Setup_(); } void SplinedCurve::Setup_() { if (x_.size() < 2) { Errors::Message msg("SplinedCurve must get arrays of length 2 or greater."); Exceptions::amanzi_throw(msg); } if (x_.size() != y_.size() || x_.size() != dy_.size()) { Errors::Message msg("SplinedCurve must get arrays of equal length."); Exceptions::amanzi_throw(msg); } dx_.resize(x_.size()-1,0.); for (int i=0; i!=dx_.size(); ++i) { dx_[i] = x_[i+1] - x_[i]; if (dx_[i] <= 0.) { Errors::Message msg("SplinedCurve independent variable x must be monotonically increasing."); Exceptions::amanzi_throw(msg); } } // enforce monotonicity using the approach of Hyman '83 Accurate // Mono. Pres. Cubic Interp. if (mono_) { // determine whether monotonically increasing, decreasing, or zero double mean_slope = (y_[y_.size()-1] - y_[0]); // calculate the finite difference slopes std::vector<double> dy_fd(dx_.size(),0.); for (int i=0; i!=dx_.size(); ++i) { dy_fd[i] = (y_[i+1] - y_[i]) / dx_[i]; } // enforce sufficient monotonicity constraint on slopes if (mean_slope > 0.) { double min_slope = *std::min_element(dy_.begin(), dy_.end()); if (min_slope < 0.) { Errors::Message msg("SplinedCurve requested monotonicity_preserving with postive mean slope but slopes provided are not uniformly non-negative."); Exceptions::amanzi_throw(msg); } // dy = min( 3*min(S-1/2, S+1/2), dy) for (int i=1; i!=dy_.size()-1; ++i) { dy_[i] = std::min( 3*std::min(dy_fd[i-1], dy_fd[i]), dy_[i]); } } else if (mean_slope < 0.) { double max_slope = *std::max_element(dy_.begin(), dy_.end()); if (max_slope > 0.) { Errors::Message msg("SplinedCurve requested monotonicity_preserving with negative mean slope but slopes provided are not uniformly non-positive."); Exceptions::amanzi_throw(msg); } // dy = max( 3*max(S-1/2, S+1/2), dy) for (int i=1; i!=dy_.size()-1; ++i) { dy_[i] = std::max( 3*std::max(dy_fd[i-1], dy_fd[i]), dy_[i]); } } else { double min_slope = *std::min_element(dy_.begin(), dy_.end()); double max_slope = *std::max_element(dy_.begin(), dy_.end()); if (min_slope != 0.0 || max_slope != 0.0) { Errors::Message msg("SplinedCurve requested monotonicity_preserving with zero mean slope but slopes provided are not uniformly zero."); Exceptions::amanzi_throw(msg); } } } } } // namespace } // namespace
29.884615
155
0.578121
fmyuan
5cda6079665f1ebe1e439c0679a8f1472e87f266
9,069
cpp
C++
src/Font.cpp
santa01/graphene
754ca37aec379241bb36eca9b625bd6c47e89381
[ "MIT" ]
3
2016-01-27T00:34:21.000Z
2019-08-14T07:13:09.000Z
src/Font.cpp
santa01/graphene
754ca37aec379241bb36eca9b625bd6c47e89381
[ "MIT" ]
null
null
null
src/Font.cpp
santa01/graphene
754ca37aec379241bb36eca9b625bd6c47e89381
[ "MIT" ]
1
2019-09-05T04:59:59.000Z
2019-09-05T04:59:59.000Z
/* * Copyright (c) 2013 Pavlo Lavrenenko * * 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. */ #include <Font.h> #include <Logger.h> #include <stdexcept> #include <algorithm> #include <vector> #include <cstring> #include <cassert> #include <stdexcept> #include <ft2build.h> #include FT_FREETYPE_H #include FT_GLYPH_H namespace Graphene { void Font::initFreeType() { if (Font::library == nullptr) { FT_Library library; if (FT_Init_FreeType(&library) != FT_Err_Ok) { throw std::runtime_error(LogFormat("FT_Init_FreeType()")); } Font::library.reset(library, FT_Done_FreeType); } } std::shared_ptr<FT_LibraryRec> Font::library; Font::Font(const std::string& filename, int size, int dpi): filename(filename), size(size), dpi(dpi) { Font::initFreeType(); FT_Face face; if (FT_New_Face(Font::library.get(), this->filename.c_str(), 0, &face) != FT_Err_Ok) { throw std::runtime_error(LogFormat("FT_New_Face()")); } this->face.reset(face, FT_Done_Face); FT_F26Dot6 fontSize = this->size << 6; // Size in 1/64th of a pixel if (FT_Set_Char_Size(this->face.get(), fontSize, 0, this->dpi, 0) != FT_Err_Ok) { throw std::runtime_error(LogFormat("FT_Set_Char_Size()")); } } const std::string& Font::getFilename() const { return this->filename; } int Font::getSize() const { return this->size; } int Font::getDPI() const { return this->dpi; } void Font::renderChar(wchar_t charCode, const std::shared_ptr<RawImage>& image) { int imagePixelBytes = image->getPixelDepth() >> 3; if (imagePixelBytes != 4) { throw std::invalid_argument(LogFormat("Image should have 32 bits per pixel")); } auto& charGlyph = this->getCharGlyph(charCode); FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(charGlyph->record.get()); FT_Bitmap charBitmap = bitmapGlyph->bitmap; int imageWidth = image->getWidth(); if (static_cast<unsigned int>(imageWidth) < charBitmap.width) { throw std::runtime_error(LogFormat("Image width is %d but character requires %d", imageWidth, charBitmap.width)); } int imageHeight = image->getHeight(); if (static_cast<unsigned int>(imageHeight) < charBitmap.rows) { throw std::runtime_error(LogFormat("Image height is %d but character requires %d", imageHeight, charBitmap.rows)); } int imagePixelsSize = image->getPixelsSize(); int imageRowSize = imageWidth * imagePixelBytes; int charRowSize = charBitmap.width; // Single byte (alpha) unsigned char* imagePixels = reinterpret_cast<unsigned char*>(image->getPixels()); const unsigned char* charPixels = charGlyph->pixels.get(); for (unsigned int charRow = 0; charRow < charBitmap.rows; charRow++) { int imageRowOffset = charRow * imageRowSize; int charRowOffset = charRow * charRowSize; for (unsigned int alphaPixel = 0; alphaPixel < charBitmap.width; alphaPixel++) { int alphaOffset = (alphaPixel * imagePixelBytes) + 3; // Offset to RGB[A] alpha assert(imageRowOffset + alphaOffset < imagePixelsSize); imagePixels[imageRowOffset + alphaOffset] = charPixels[charRowOffset + alphaPixel]; } } } void Font::renderString(const std::wstring& stringText, const std::shared_ptr<RawImage>& image) { int imagePixelBytes = image->getPixelDepth() >> 3; if (imagePixelBytes != 4) { throw std::invalid_argument(LogFormat("RawImage should have 32 bits per pixel")); } FT_BBox stringBox = { }; std::vector<std::shared_ptr<CharGlyph>> stringGlyphs; for (auto charCode: stringText) { auto& charGlyph = this->getCharGlyph(charCode); stringBox.yMin = std::min<int>(stringBox.yMin, charGlyph->box->yMin); stringBox.yMax = std::max<int>(stringBox.yMax, charGlyph->box->yMax); stringBox.xMax += charGlyph->record->advance.x >> 16; // 16.16 fixed float format stringGlyphs.emplace_back(charGlyph); } int stringWidth = stringBox.xMax + 1; // Extra pixel in case string box is miscalculated int stringHeight = stringBox.yMax - stringBox.yMin; int stringAdvance = 0; int imageWidth = image->getWidth(); if (imageWidth < stringWidth) { throw std::runtime_error(LogFormat("Image width is %d but string requires %d", imageWidth, stringWidth)); } int imageHeight = image->getHeight(); if (imageHeight < stringHeight) { throw std::runtime_error(LogFormat("Image height is %d but string requires %d", imageHeight, stringHeight)); } int imagePixelsSize = image->getPixelsSize(); unsigned char* imagePixels = reinterpret_cast<unsigned char*>(image->getPixels()); for (auto& charGlyph: stringGlyphs) { FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(charGlyph->record.get()); FT_Bitmap charBitmap = bitmapGlyph->bitmap; unsigned char* charPixels = charGlyph->pixels.get(); int stringRow = stringBox.yMax - charGlyph->box->yMax; // Character Y offset in string int charRowSize = charBitmap.width; // Single byte (alpha) for (unsigned int charRow = 0; charRow < charBitmap.rows; charRow++, stringRow++) { int imagePixelsOffset = (stringRow * imageWidth + stringAdvance) * imagePixelBytes; int charRowOffset = charRow * charRowSize; for (unsigned int alphaPixel = 0; alphaPixel < charBitmap.width; alphaPixel++) { int alphaOffset = (alphaPixel * imagePixelBytes) + 3; // Offset to RGB[A] alpha assert(imagePixelsOffset + alphaOffset < imagePixelsSize); imagePixels[imagePixelsOffset + alphaOffset] = charPixels[charRowOffset + alphaPixel]; } } stringAdvance += charGlyph->record->advance.x >> 16; // 16.16 fixed float format } } const std::shared_ptr<Font::CharGlyph>& Font::getCharGlyph(wchar_t charCode) { auto charGlyphIt = this->charGlyphs.find(charCode); if (charGlyphIt != this->charGlyphs.end()) { return charGlyphIt->second; } FT_UInt charIndex = FT_Get_Char_Index(this->face.get(), charCode); if (FT_Load_Glyph(this->face.get(), charIndex, FT_LOAD_RENDER) != FT_Err_Ok) { throw std::runtime_error(LogFormat("FT_Load_Glyph()")); } FT_GlyphSlot glyphSlot = this->face->glyph; if (glyphSlot->format != FT_GLYPH_FORMAT_BITMAP) { throw std::runtime_error(LogFormat("Invalid glyph format")); } FT_Glyph glyph; if (FT_Get_Glyph(glyphSlot, &glyph)) { throw std::runtime_error(LogFormat("FT_Get_Glyph()")); } auto charGlyph = std::make_shared<CharGlyph>(); charGlyph->record = std::shared_ptr<FT_GlyphRec>(glyph, FT_Done_Glyph); charGlyph->box = std::make_shared<FT_BBox>(); FT_Glyph_Get_CBox(glyph, FT_GLYPH_BBOX_PIXELS, charGlyph->box.get()); // Invert the control box Y coordinates to reposition inverted bitmap int yMin = charGlyph->box->yMin; int yMax = charGlyph->box->yMax; charGlyph->box->yMin = -yMax; charGlyph->box->yMax = -yMin; FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(glyph); FT_Bitmap charBitmap = bitmapGlyph->bitmap; int bitmapSize = charBitmap.width * charBitmap.rows; charGlyph->pixels = std::shared_ptr<unsigned char[]>(new unsigned char[bitmapSize]); unsigned char* pixels = charGlyph->pixels.get(); // Bitmap is inverted vertically relative to the texture coordinates space // and contains alpha (transparency) values only (no color information). for (unsigned int charRow = 0; charRow < charBitmap.rows; charRow++) { int pixelsRowOffset = charRow * charBitmap.width; int charRowOffset = (charBitmap.rows - charRow - 1) * charBitmap.width; std::memcpy(pixels + pixelsRowOffset, charBitmap.buffer + charRowOffset, charBitmap.width); } return this->charGlyphs.emplace(charCode, charGlyph).first->second; } } // namespace Graphene
39.090517
122
0.685522
santa01
5cdb9e56c7b928ae8ee77ae76099f5bd30ee0fbc
1,368
cpp
C++
codechef/GUESSRT/Partially Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codechef/GUESSRT/Partially Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codechef/GUESSRT/Partially Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: 01-02-2019 16:56:20 * solution_verdict: Partially Accepted language: C++14 * run_time: 0.00 sec memory_used: 14.9M * problem: https://www.codechef.com/FEB19B/problems/GUESSRT ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; const long mod=1e9+7; long bigmod(long b,long p,long mod) { long ret=1LL; while(p) { if(p%2)ret=(ret*b)%mod; b=(b*b)%mod;p/=2; } return ret; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int t;cin>>t; while(t--) { int n,k,m;cin>>n>>k>>m; long up=1,dw=1;long ans=0; while(m--) { if(!m) { ans=(ans+(up*bigmod((dw*n%mod),mod-2,mod))%mod)%mod; } else { if(n>k)n%=k; else { ans=(ans+(up*bigmod((dw*n%mod),mod-2,mod))%mod)%mod; dw=(dw*n)%mod;up=(up*(n-1))%mod; n+=k; } } } //cout<<n<<" "<<up<<" "<<dw<<endl; cout<<ans<<"\n"; } return 0; }
26.823529
111
0.384503
kzvd4729
5cdbcfda8170a4e834375ebcb4b6b8cf4e0b9bbe
1,195
cpp
C++
src/reverse-linked-list-ii.cpp
Liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
9
2015-09-09T20:28:31.000Z
2019-05-15T09:13:07.000Z
src/reverse-linked-list-ii.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2015-02-25T13:10:09.000Z
2015-02-25T13:10:09.000Z
src/reverse-linked-list-ii.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2016-08-31T19:14:52.000Z
2016-08-31T19:14:52.000Z
#include <iostream> #include <algorithm> #include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if (m >= n) return head; ListNode* dummyHead = new ListNode(-1); dummyHead->next = head; int cur = 1; ListNode *mHead, *nHead, *mPreHead; ListNode *pre = dummyHead; for (ListNode* p=head; p!=NULL; p=p->next, pre=pre->next) { if (cur == m) { mPreHead = pre; mHead = p; } if (cur == n) { nHead = p; break; } cur ++; } // reverse ListNode *p1, *p2; p1 = mHead; p2 = mHead->next; while (p1!=nHead) { ListNode* tmp = p2->next; p2->next = p1; p1 = p2; p2 = tmp; } ListNode* tmp = mPreHead->next; tmp->next = p2; mPreHead->next = p1; return dummyHead->next; } };
21.339286
65
0.43431
Liuchang0812
5cdc8c96401b0adfad7ac71605778bbbb36ede23
7,673
hpp
C++
src/ttauri/widgets/abstract_button_widget.hpp
PinkFlufflyLlama/ttauri
7badcfbe792932ebb912d54d1062d8fc820c40a7
[ "BSL-1.0" ]
null
null
null
src/ttauri/widgets/abstract_button_widget.hpp
PinkFlufflyLlama/ttauri
7badcfbe792932ebb912d54d1062d8fc820c40a7
[ "BSL-1.0" ]
null
null
null
src/ttauri/widgets/abstract_button_widget.hpp
PinkFlufflyLlama/ttauri
7badcfbe792932ebb912d54d1062d8fc820c40a7
[ "BSL-1.0" ]
null
null
null
// Copyright Take Vos 2019-2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #pragma once #include "widget.hpp" #include "button_delegate.hpp" #include "label_widget.hpp" #include "button_type.hpp" #include "../animator.hpp" #include "../l10n.hpp" #include "../notifier.hpp" #include <memory> #include <string> #include <array> #include <optional> #include <future> namespace tt { class abstract_button_widget : public widget { public: using super = widget; using delegate_type = button_delegate; using callback_ptr_type = typename delegate_type::callback_ptr_type; observable<label> on_label = l10n("on"); observable<label> off_label = l10n("off"); observable<label> other_label = l10n("other"); observable<alignment> label_alignment; abstract_button_widget( gui_window &window, std::shared_ptr<widget> parent, std::shared_ptr<delegate_type> delegate = std::make_shared<delegate_type>()) noexcept : super(window, std::move(parent)), _delegate(std::move(delegate)) { _delegate->subscribe(*this, _relayout_callback); } void init() noexcept override { super::init(); _on_label_widget = this->make_widget<label_widget>(); _off_label_widget = this->make_widget<label_widget>(); _other_label_widget = this->make_widget<label_widget>(); _on_label_widget->alignment = label_alignment; _off_label_widget->alignment = label_alignment; _other_label_widget->alignment = label_alignment; _on_label_widget->label = on_label; _off_label_widget->label = off_label; _other_label_widget->label = other_label; _delegate->init(*this); } void deinit() noexcept override { _delegate->deinit(*this); super::deinit(); } template<typename Label> void set_label(Label const &rhs) noexcept { tt_axiom(gui_system_mutex.recurse_lock_count()); on_label = rhs; off_label = rhs; other_label = rhs; } [[nodiscard]] button_state state() const noexcept { tt_axiom(gui_system_mutex.recurse_lock_count()); return _delegate->state(*this); } /** Subscribe a callback to call when the button is activated. */ template<typename Callback> [[nodiscard]] callback_ptr_type subscribe(Callback &&callback) noexcept { ttlet lock = std::scoped_lock(gui_system_mutex); return _notifier.subscribe(std::forward<Callback>(callback)); } /** Unsubscribe a callback. */ void unsubscribe(callback_ptr_type &callback_ptr) noexcept { ttlet lock = std::scoped_lock(gui_system_mutex); return _notifier.unsubscribe(callback_ptr); } [[nodiscard]] bool update_constraints(hires_utc_clock::time_point display_time_point, bool need_reconstrain) noexcept override { tt_axiom(gui_system_mutex.recurse_lock_count()); if (super::update_constraints(display_time_point, need_reconstrain)) { this->_minimum_size = _on_label_widget->minimum_size(); this->_preferred_size = _on_label_widget->preferred_size(); this->_maximum_size = _on_label_widget->maximum_size(); this->_minimum_size = max(this->_minimum_size, _off_label_widget->minimum_size()); this->_preferred_size = max(this->_preferred_size, _off_label_widget->preferred_size()); this->_maximum_size = max(this->_maximum_size, _off_label_widget->maximum_size()); this->_minimum_size = max(this->_minimum_size, _other_label_widget->minimum_size()); this->_preferred_size = max(this->_preferred_size, _other_label_widget->preferred_size()); this->_maximum_size = max(this->_maximum_size, _other_label_widget->maximum_size()); tt_axiom(this->_minimum_size <= this->_preferred_size && this->_preferred_size <= this->_maximum_size); return true; } else { return false; } } [[nodiscard]] void update_layout(hires_utc_clock::time_point displayTimePoint, bool need_layout) noexcept override { tt_axiom(gui_system_mutex.recurse_lock_count()); need_layout |= std::exchange(this->_request_relayout, false); if (need_layout) { auto state_ = state(); this->_on_label_widget->visible = state_ == button_state::on; this->_off_label_widget->visible = state_ == button_state::off; this->_other_label_widget->visible = state_ == button_state::other; this->_on_label_widget->set_layout_parameters_from_parent(_label_rectangle); this->_off_label_widget->set_layout_parameters_from_parent(_label_rectangle); this->_other_label_widget->set_layout_parameters_from_parent(_label_rectangle); } widget::update_layout(displayTimePoint, need_layout); } [[nodiscard]] color background_color() const noexcept override { tt_axiom(gui_system_mutex.recurse_lock_count()); if (_pressed) { return theme::global(theme_color::fill, this->_semantic_layer + 2); } else { return super::background_color(); } } [[nodiscard]] hit_box hitbox_test(point2 position) const noexcept final { tt_axiom(gui_system_mutex.recurse_lock_count()); if (_visible_rectangle.contains(position)) { return hit_box{weak_from_this(), _draw_layer, enabled ? hit_box::Type::Button : hit_box::Type::Default}; } else { return hit_box{}; } } [[nodiscard]] bool accepts_keyboard_focus(keyboard_focus_group group) const noexcept override { tt_axiom(gui_system_mutex.recurse_lock_count()); return is_normal(group) and enabled; } void activate() noexcept { _delegate->activate(*this); run_from_main_loop([this]() { this->_notifier(); }); } [[nodiscard]] bool handle_event(command command) noexcept override { ttlet lock = std::scoped_lock(gui_system_mutex); if (enabled) { switch (command) { case command::gui_activate: activate(); return true; case command::gui_enter: activate(); this->window.update_keyboard_target(keyboard_focus_group::normal, keyboard_focus_direction::forward); return true; default:; } } return super::handle_event(command); } [[nodiscard]] bool handle_event(mouse_event const &event) noexcept final { ttlet lock = std::scoped_lock(gui_system_mutex); auto handled = super::handle_event(event); if (event.cause.leftButton) { handled = true; if (enabled) { if (compare_then_assign(_pressed, static_cast<bool>(event.down.leftButton))) { request_redraw(); } if (event.type == mouse_event::Type::ButtonUp && rectangle().contains(event.position)) { handled |= handle_event(command::gui_activate); } } } return handled; } protected: aarectangle _label_rectangle; std::shared_ptr<label_widget> _on_label_widget; std::shared_ptr<label_widget> _off_label_widget; std::shared_ptr<label_widget> _other_label_widget; bool _pressed = false; notifier<void()> _notifier; std::shared_ptr<delegate_type> _delegate; }; } // namespace tt
33.801762
130
0.652418
PinkFlufflyLlama
5cdf2b6a1306c7ced727a0796dd0bd65b5e6589f
484
hpp
C++
include/Sprite/UIString.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
2
2020-05-05T13:31:55.000Z
2022-01-16T15:38:00.000Z
include/Sprite/UIString.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
null
null
null
include/Sprite/UIString.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
1
2021-11-27T02:32:24.000Z
2021-11-27T02:32:24.000Z
#ifndef UISPRITE_HPP #define UISPRITE_HPP #include "TextureSheet.hpp" #include "GameObject.hpp" #include <string> using namespace std; /** * @brief 表示英文字符 * @warn 不管给如的字符大小写,绘制的一律大写 */ class UIString : public GameObject{ public: static UIString* Create(); void SetText(string t); string GetText() const; void Scale(float sx, float sy); private: void draw() override; void update() override; UIString(); TextureSheet ts; string text; }; #endif
17.925926
35
0.68595
VisualGMQ
5ce321d77260253fb2b20e0777822726db4abedb
824
cpp
C++
ttgo/src/app/WatchButton.cpp
peteh/ttgo
62a39a2e27eafabb6eac448b92b6837817d9f96a
[ "MIT" ]
null
null
null
ttgo/src/app/WatchButton.cpp
peteh/ttgo
62a39a2e27eafabb6eac448b92b6837817d9f96a
[ "MIT" ]
null
null
null
ttgo/src/app/WatchButton.cpp
peteh/ttgo
62a39a2e27eafabb6eac448b92b6837817d9f96a
[ "MIT" ]
null
null
null
#include "WatchButton.h" #include <Log.h> namespace app { const long WatchButton::PRESS_DELAY = 300; const long WatchButton::MAX_CLICKS = 2; WatchButton::WatchButton() : m_presses(0), m_pressTS(0) { } uint WatchButton::evaluate(bool pressed) { if (pressed) { if (millis() - m_pressTS < PRESS_DELAY) { m_presses++; } else { m_presses = 1; } m_pressTS = millis(); Log::debug("Counting up"); return 0; } if (millis() - m_pressTS > PRESS_DELAY || m_presses >= MAX_CLICKS) { uint presses = m_presses; m_presses = 0; return presses; } return 0; } }
20.6
74
0.461165
peteh
5ce59e33cc592a3407f0e9dd072ad153623052b9
1,527
cpp
C++
src/string_tests.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
src/string_tests.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
src/string_tests.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
// // Created by tyoun on 10/24/2021. // #include <catch2/catch.hpp> #include <string> #include <iostream> using std::string; TEST_CASE("String operations ") { string s{"a dog"}; s += " is a dog"; SECTION("Test concatenation") { REQUIRE(s == "a dog is a dog"); } SECTION("String find method") { //Return the index of first occurance of string p in s REQUIRE(s.find("dog")== 2); REQUIRE(s.find("dog", 3) == 11); } SECTION("npos? what even is this") { REQUIRE(s.find("doug") == string::npos); } SECTION("substring function") { REQUIRE(s.substr(7, 5) == "s a d"); } SECTION("replace function") { REQUIRE(s.replace(2, 3,"frog") == "a frog is a dog"); } SECTION("erase and insert function ") { s.replace(2, 3,"frog"); REQUIRE(s.erase(6, 3) == "a frog a dog"); s.insert(0, "is "); REQUIRE(s == "is a frog a dog"); REQUIRE(s < "is a frog a toad"); REQUIRE((s < "is a frog a cat") == false); } SECTION("Don't forget about string.append") { string sentence{"She"}; sentence.append(" Is playing"); sentence += " the piano"; std::cout << sentence << "\n"; } SECTION("More concatenation") { string subject{ "She"}; string verb {"is playing"}; string object {"the piano"}; string sentence = subject + " " + verb + " " + object + "."; std::cout << sentence << "\n"; } }
23.492308
98
0.518009
tyoungjr
5ce82c5014b4101d41dee1a7f051794d378edf5e
999
cpp
C++
net/AsioTlsTcpSocket.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
net/AsioTlsTcpSocket.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
net/AsioTlsTcpSocket.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#include "AsioTlsTcpSocket.hpp" #include "AsioBaseTcpSocket.ipp" #include "AsioService.hpp" BEGIN_INANITY_NET template class AsioBaseTcpSocket<Botan::TLS::Stream<boost::asio::ip::tcp::socket> >; AsioTlsTcpSocket::AsioTlsTcpSocket(ptr<AsioService> service, std::unique_ptr<Botan::TLS::Context>&& tlsContext) : AsioBaseTcpSocket(service, service->GetIoService(), *tlsContext), tlsContext(std::move(tlsContext)) {} void AsioTlsTcpSocket::ShutdownNonSynced() { try { socket.lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_send); } catch(boost::system::system_error) { } } void AsioTlsTcpSocket::CloseNonSynced() { try { socket.lowest_layer().close(); } catch(boost::system::system_error error) { } } boost::asio::basic_socket<boost::asio::ip::tcp>& AsioTlsTcpSocket::GetLowestSocket() { return socket.lowest_layer(); } void AsioTlsTcpSocket::SetNoDelay(bool noDelay) { socket.lowest_layer().set_option(boost::asio::ip::tcp::no_delay(noDelay)); } END_INANITY_NET
22.2
111
0.74975
quyse
5ce8ff0732486f241dbe06166e5543ad5c5a88fd
26,297
cpp
C++
Classes/data/Guid.cpp
thales-vogso/deer
f3492538881f632b55be657bb9529027897b0e63
[ "Apache-2.0" ]
null
null
null
Classes/data/Guid.cpp
thales-vogso/deer
f3492538881f632b55be657bb9529027897b0e63
[ "Apache-2.0" ]
null
null
null
Classes/data/Guid.cpp
thales-vogso/deer
f3492538881f632b55be657bb9529027897b0e63
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** * @desc 新手引导信息 * @date 2015-06-30 * @author 120103 * @file data/User.h ******************************************************************************/ #include "Guid.h" #include "Item.h" #include "Building.h" #include "Crusade.h" #include "GlobalMacros.h" #include "DestroyData.h" namespace data { static Guid* _instance = nullptr; const std::string Guid::TABLE_GUID = "user_guid"; const std::string Guid::GUID_USER_OPERATION = "userOperation"; const std::string Guid::UPDATE_GUID = "updateGuid"; const std::string Guid::DELETE_GUID = "deleteGuid"; Guid::Guid() { this->init(); } Guid::~Guid() { } Guid* Guid::getInstance() { if (!_instance) { _instance = new Guid(); } return _instance; } void Guid::destroyInstance() { if (_instance) { CC_SAFE_DELETE(_instance); } } void Guid::init() { _db = DBConnector::getInstance()->open(); std::stringstream sql; sql << "SELECT COUNT(*) AS `num` FROM `" << Guid::TABLE_GUID.c_str() << "` LIMIT 1"; /*int num = _db->getOne(sql.str()).asInt(); if (num == 0) { }*/ _db->upgrade(TABLE_GUID, Table::getInstance()->getTableByName(TABLE_GUID), Table::getInstance()->getCSVByName(TABLE_GUID)); _maxGuidNum = 0; _guidFinishNum = 0; //如果战斗引导未完成重置并重新引导.. isFinishBattleGuide(); //计算剩余没完成引导任务数.. sql.clear(); sql.str(""); sql << "SELECT * FROM `" << TABLE_GUID.c_str()<< "`WHERE `cstep`< `tstep`"; cocos2d::Value all = _db->getAll(sql.str()); for(int i = 0 ; i < all.asValueVector().size();i++) { cocos2d::ValueMap map =all.asValueVector().at(i).asValueMap(); if(map["cstep"].asInt() < map["tstep"].asInt()) { _maxGuidNum++; } } } bool Guid::isFinishBattleGuide() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { if(getGuideTaskFinishState(ATTACK1)&& getGuideTaskFinishState(ATTACK2) &&getGuideTaskFinishState(AUTO_ATTACK)&& getGuideTaskFinishState(FOOD_BACK)) { return true; } else { setStepByGuidId(ATTACK1,STEP0); setStepByGuidId(ATTACK2, STEP0); setStepByGuidId(AUTO_ATTACK, STEP0); setStepByGuidId(FOOD_BACK, STEP0); if(getGuideTaskFinishState(EXPLORE)) { data::User::getInstance()->setGuideID(EXPLORE); } data::User::getInstance()->setAutoBattle(false); return false; } } return true; } bool Guid::FinishBattleGuide() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { setStepByGuidId(ATTACK1,STEP1); setStepByGuidId(ATTACK2, STEP1); setStepByGuidId(AUTO_ATTACK, STEP1); setStepByGuidId(FOOD_BACK, STEP1); } return false; } bool Guid::isNeedClearData() { //如果玩家上次进行了新手引导,但是并没有完成,对不起请重新来过,就是这么任性.. if(DEBUG_SHOW_GUID&&!isGuidFinish()) { int currentID =getCurrentGuidId(); if (currentID== GOLD) { if(getStepByGuidId(GOLD) < getMaxStepByGuidId(GOLD) && getStepByGuidId(GOLD)>0) { return true; } } else if(currentID > GOLD && currentID <WAR) { return true; } else if(currentID == WAR) { if(getStepByGuidId(WAR) < getMaxStepByGuidId(WAR)) { return true; } } } return false; } int Guid::getCurrentGuidId() { return User::getInstance()->getGuideID(); } bool Guid::isCanFastOperateWorkers() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { int currentID = getCurrentGuidId(); if(currentID == WORKERS_USER1||currentID == WORKERS_USE1|| currentID == WORKERS_USE2|| currentID == WORKERS_USE3) { if(getGuideTaskFinishState(currentID)) { return true; } return false; } } return true; } int Guid::getGuideLayer() { if(!isGuidFinish()&& DEBUG_SHOW_GUID) { int guideID = getCurrentGuidId(); int currentStep = getStepByGuidId(guideID); if(guideID == GOLD && currentStep == STEP0) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_BUILD && currentStep == STEP0) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_BUILD&& currentStep == STEP1) { return BUID_LAYER; } else if(guideID == COLLECTION&& currentStep == STEP0) { return BUID_LAYER; } else if(guideID == COLLECTION&& currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == COLLECTION&& currentStep == STEP2) { return COLLECTION_LAYER; } else if(guideID == WAREHOUSE_USE1&& currentStep == STEP0) { return COLLECTION_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP2) { return RESOUCE_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP3) { return RESOUCE_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP4) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP5) { return BUID_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP6) { return BUID_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP7) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP8) { return MAIN_LAYER; } else if(guideID == WAREHOUSE_USE1 && currentStep == STEP9) { return BUID_LAYER; } else if(guideID == SHELTER_BUILD && currentStep == STEP0) { return BUID_LAYER; } else if(guideID == SHELTER_BUILD && currentStep == STEP1) { return BUID_LAYER; } else if(guideID == SHELTER_BUILD && currentStep == STEP2) { return MAIN_LAYER; } else if(guideID == SHELTER_BUILD && currentStep == STEP3) { return MAIN_LAYER; } else if(guideID == SHELTER_BUILD && currentStep == STEP4) { return BUID_LAYER; } else if(guideID == WORKERS_USER1 && currentStep == STEP0) { return BUID_LAYER; } else if(guideID == WORKERS_USER1 && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == WORKERS_USER1 && currentStep == STEP2) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USER1 && currentStep == STEP3) { return COLLECTION_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP0) { return MAIN_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP1) { return BUID_LAYER; } else if(guideID == STORE_BUILD&& currentStep == STEP2) { return BUID_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP3) { return MAIN_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP4) { return MAIN_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP5) { return COLLECTION_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP6) { return COLLECTION_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP7) { return MAIN_LAYER; } else if(guideID == STORE_BUILD && currentStep == STEP8) { return BUID_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP0) { return BUID_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP2) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP3) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP4) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE1 && currentStep == STEP5) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE2 && currentStep == STEP0) { return BUID_LAYER; } else if(guideID == WORKERS_USE2 && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == WORKERS_USE2 && currentStep == STEP2) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE3 && currentStep == STEP0) { return BUID_LAYER; } else if(guideID == WORKERS_USE3 && currentStep == STEP1) { return COLLECTION_LAYER; } else if(guideID == WORKERS_USE3 && currentStep == STEP2) { return COLLECTION_LAYER; } else if(guideID == SOLDIERS_BUILD&&currentStep == STEP0) { return BUID_LAYER; } else if(guideID == SOLDIERS_BUILD && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == SOLDIERS_BUILD && currentStep == STEP2) { return VENTURE_LAYER; } else if(guideID == SOLDIERS_BUILD && currentStep == STEP3) { return VENTURE_LAYER; } else if(guideID == SOLDIERS_BUILD && currentStep == STEP4) { return MAIN_LAYER; } else if(guideID == SOLDIERS_BUILD && currentStep == STEP5) { return BUID_LAYER; } else if(guideID == TRAINING && currentStep == STEP0 ) { return BUID_LAYER; } else if(guideID == TRAINING && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == TRAINING && currentStep == STEP2) { return HERO_LAYER; } else if(guideID == TRAINING && currentStep == STEP3) { char comment[200]; sprintf(comment, "/* %s, %d */", __FILE__, __LINE__); std::stringstream sql; sql << "UPDATE `" << TABLE_GUID << "` SET `cstep`='" << STEP2 <<"' WHERE `gid` = '" << TRAINING << "'" << comment; _db->query(sql.str()); return HERO_LAYER; } else if(guideID == WAR && currentStep == STEP0) { return HERO_LAYER; } else if(guideID == WAR && currentStep == STEP1) { return MAIN_LAYER; } else if(guideID == WAR && currentStep == STEP2) { return VENTURE_LAYER; } else if(guideID == WAR && currentStep == STEP3) { return VENTURE_LAYER; } else if(guideID == WAR && currentStep == STEP4) { return VENTURE_LAYER; } else if(guideID == WAREHOUSE_USE2&&currentStep == STEP0) { return RESOUCE_LAYER; } else if(guideID == MOVE && currentStep == STEP0) { return MAP_LAYER; } else if(guideID == CITY && currentStep == STEP0) { return MAP_LAYER; } else if(guideID == FOOD && currentStep == STEP0) { return MAP_LAYER; } else if(guideID == EXPLORE && currentStep == STEP0) { return MAP_LAYER; } else if(guideID == ATTACK1 && currentStep == STEP0) { return -1; } else if(guideID == ATTACK2 && currentStep == STEP0) { return -1; } else if(guideID == AUTO_ATTACK && currentStep == STEP0) { return -1; } else if(guideID == FOOD_BACK && currentStep == STEP0) { return -1; } else if(guideID == DROP_GET && currentStep == STEP0) { return -1; } else if(guideID == DROP_GET && currentStep == STEP1) { return -1; } } return -1; } int Guid::getStepByGuidId(int GuidID) { std::stringstream sql; sql << "SELECT `cstep` FROM `" << TABLE_GUID.c_str() << "` WHERE `gid`=" << GuidID << " LIMIT 1"; int date = _db->getOne(sql.str()).asInt(); return date; } void Guid::setStepByGuidId(int GuidID,int nStep) { char comment[200]; sprintf(comment, "/* %s, %d */", __FILE__, __LINE__); std::stringstream sql; sql << "UPDATE `" << TABLE_GUID.c_str() << "` SET `cstep`='" << nStep <<"' WHERE `gid` = '" << GuidID << "'" << comment; _db->query(sql.str()); } cocos2d::ValueMap Guid::getInfoByGuidId(int GuidID) { std::stringstream sql; sql << "SELECT `cstep` FROM `" << TABLE_GUID.c_str() << "` WHERE `gid`=" << GuidID << " LIMIT 1"; int date = _db->getOne(sql.str()).asInt(); cocos2d::ValueMap info; info["guidId"] =GuidID; info["step"] =date; return info; } int Guid::getMaxStepByGuidId(int GuidID) { std::stringstream sql; sql << "SELECT `tstep` FROM `" << TABLE_GUID.c_str() << "` WHERE `gid`=" << GuidID << " LIMIT 1"; int date = _db->getOne(sql.str()).asInt(); return date; } cocos2d::ValueMap Guid::getGuidInfo() { std::stringstream sql; sql << "SELECT `cstep` FROM `" << TABLE_GUID.c_str() << "` WHERE `gid`=" << getCurrentGuidId() << " LIMIT 1"; int date = _db->getOne(sql.str()).asInt(); cocos2d::ValueMap info; info["guidId"] =getCurrentGuidId(); info["step"] =date; return info; } bool Guid::showGuid(int GuidId) { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { if(GuidId == FOOD_BACK) { if(getGuideTaskFinishState(AUTO_ATTACK)) { User::getInstance()->setGuideID(GuidId); } } else if(GuidId == ATTACK1) { if(!getGuideTaskFinishState(ATTACK1)) { User::getInstance()->setGuideID(GuidId); } else { if(!getGuideTaskFinishState(ATTACK2)) { User::getInstance()->setGuideID(ATTACK2); } else { if(!getGuideTaskFinishState(AUTO_ATTACK)) { User::getInstance()->setGuideID(AUTO_ATTACK); } } } } else if(GuidId == SHELTER_GUID) { cocos2d::Value row = data::Crusade::getInstance()->fieldView(); if(row.asValueMap()["fid"].asInt() == 110202) { if(!getGuideTaskFinishState(SHELTER_GUID)&& getGuideTaskFinishState(EXPLORE)) { User::getInstance()->setGuideID(SHELTER_GUID); } } } else { if(GuidId != 0) { User::getInstance()->setGuideID(GuidId); } else { if(getCurrentGuidId() == WAREHOUSE_USE2) { //不需要重复显示仓库卖出引导.. return false; } } } int currentID = getCurrentGuidId(); if(getStepByGuidId(currentID) < getMaxStepByGuidId(currentID)) { if(currentID == SHELTER_GUID) { cocos2d::Value row = data::Crusade::getInstance()->fieldView(); if(row.asValueMap()["fid"].asInt() == 110202) { cocos2d::ValueMap info; info["step"] = getStepByGuidId(currentID)+1; info["guidId"] = currentID; dispatch(UPDATE_GUID,&info); return true; } } else { cocos2d::ValueMap info; info["step"] = getStepByGuidId(currentID)+1; info["guidId"] = currentID; dispatch(UPDATE_GUID,&info); return true; } } } return false; } void Guid::showBattleSelectGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { cocos2d::ValueMap info; info["step"] = 1; info["guidId"] = BATTLE_SELECT; dispatch(UPDATE_GUID,&info); } } void Guid::showHomeGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { cocos2d::ValueMap info; info["step"] = 1; info["guidId"] = HOME_GUID; dispatch(UPDATE_GUID,&info); } } void Guid::showBattleChoiceGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { cocos2d::ValueMap info; info["step"] = 1; info["guidId"] = BATTLE_CHOICE; dispatch(UPDATE_GUID,&info); } } bool Guid::isCanShowShelterGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { cocos2d::Value row = data::Crusade::getInstance()->fieldView(); if(row.asValueMap()["fid"].asInt() == 110202) { if(!getGuideTaskFinishState(SHELTER_GUID)&& getGuideTaskFinishState(EXPLORE)) { return true; } } return false; } return false; } bool Guid::isCanShowMapGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { if(!getGuideTaskFinishState(MOVE)) { data::User::getInstance()->setGuideID(MOVE); return true; } else if(!getGuideTaskFinishState(CITY)) { data::User::getInstance()->setGuideID(CITY); return true; } else if(!getGuideTaskFinishState(FOOD)) { data::User::getInstance()->setGuideID(FOOD); return true; } else if(!getGuideTaskFinishState(EXPLORE)) { data::User::getInstance()->setGuideID(EXPLORE); return true; } else if(!getGuideTaskFinishState(MOVE1)) { data::User::getInstance()->setGuideID(MOVE1); return true; } else if(!getGuideTaskFinishState(MOVE2)) { data::User::getInstance()->setGuideID(MOVE2); return true; } else { return false; } } return false; } bool Guid::isCanShowHomeGuid() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { int breadnum = data::Crusade::getInstance()->getPackageCurrent(data::Item::FOOD); if(isCanShowShelterGuid()||isCanShowMapGuid()) { return false; } else if(breadnum <= 2 && _homeGuid == false) { return true; } } return false; } bool Guid::isCanMoveOtherDirection() { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { if(getGuideTaskFinishState(MOVE2)) { return true; } return false; } return true; } bool Guid::getGuideTaskFinishState(int GuidID) { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { if(getStepByGuidId(GuidID) >= getMaxStepByGuidId(GuidID)) { return true; } return false; } return true; } void Guid::clearAllGuid() { User::getInstance()->setGuide(true); dispatch(DELETE_GUID, NULL); } void Guid::updateGuidInfo(int operationType) { if(!isGuidFinish()&&DEBUG_SHOW_GUID) { int currentID = getCurrentGuidId(); int nStep = getStepByGuidId(currentID); //战斗选择界面引导不需要进行记录,只要条件合适就引导.. if(operationType == data::Guid::BATTLE_SELECT_SURE) { battleSelectSure(); } else if(operationType == data::Guid::BATTLE_CHOICE_SURE) { battleChoiceSure(); } else if(getStepByGuidId(currentID) < getMaxStepByGuidId(currentID)) { if(currentID == WAREHOUSE_USE1 && nStep == STEP7)//非一次点击就完成的新手引导.. { if (Item::getInstance()->getUserItemAmountByIID(Item::ItemID::COIN) < 10) { restartTask(); } else { nextTask(operationType); } } else if(currentID == SHELTER_BUILD && nStep == STEP2) { if (Item::getInstance()->getUserItemAmountByIID(Item::ItemID::COIN) < 5) { restartTask(); } else { nextTask(operationType); } } else if(currentID == WORKERS_USER1 && nStep == STEP2) { if (Building::getInstance()->getUserWorkerAmountByWID(Building::PLANT_WORKERID) < 5) { restartTask(); } else { nextTask(operationType); } } else if(currentID == STORE_BUILD && nStep == STEP3) { if (Item::getInstance()->getUserItemAmountByIID(Item::ItemID::COIN) < 5) { restartTask(); } else { nextTask(operationType); } } else if(currentID == WAR && nStep == STEP2) { if (Crusade::getInstance()->getPackageCurrent(Item::ItemID::FOOD) < Item::getInstance()->getUserItemAmountByIID(Item::ItemID::FOOD)&&Crusade::getInstance()->getPackageCurrent(Item::ItemID::FOOD)<15 &&Crusade::getInstance()->getPackageSpace()<15) { restartTask(); } else { nextTask(operationType); } } else //一次点击就完成的新手引导.. { nextTask(operationType); } } } } void Guid::restartTask() { //未完成继续当前任务.. cocos2d::ValueMap info; info["step"] = getStepByGuidId(getCurrentGuidId())+1; info["guidId"] = getCurrentGuidId(); dispatch(UPDATE_GUID,&info); } void Guid::nextTask(int operationType) { int currentID = getCurrentGuidId(); //未进行同一项操作.. if (_preOperationType != operationType||_preOperationType == ATTACK1||currentID == MOVE1||currentID == MOVE2) { _preOperationType = operationType; char comment[200]; sprintf(comment, "/* %s, %d */", __FILE__, __LINE__); std::stringstream sql; sql << "UPDATE `" << TABLE_GUID << "` SET `cstep`='" << getStepByGuidId(currentID) +1 <<"' WHERE `gid` = '" << currentID << "'" << comment; _db->query(sql.str()); int nstep = getStepByGuidId(currentID); //是否完成了该引导任务.. if(nstep < getMaxStepByGuidId(currentID)) { //未完成继续.. cocos2d::ValueMap info; info["step"] = nstep+1; info["guidId"] = currentID; dispatch(UPDATE_GUID,&info); } else { cocos2d::ValueMap info; info["step"] = nstep+1; info["guidId"] = currentID; dispatch(UPDATE_GUID,&info); //完成了完成度加1.. _guidFinishNum++; if(_guidFinishNum >= _maxGuidNum) { User::getInstance()->setGuide(true); } //更新当前执行的新手任务引导.. if (currentID < STORE_BUILD || (currentID >= WAR&& currentID < MOVE2)) { User::getInstance()->setGuideID(currentID + 1); currentID = getCurrentGuidId(); if (currentID == STORE_BUILD) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } else if (currentID == MOVE) { //这一步需要手动显示下一步引导.. //data::Guid::getInstance()->showGuid(); } else if (currentID == CITY) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } else if (currentID == FOOD) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } else if (currentID == EXPLORE) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } else if(currentID == MOVE1) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } else if(currentID == MOVE2) { //这一步需要手动显示下一步引导.. data::Guid::getInstance()->showGuid(); } } else if(currentID == WAREHOUSE_USE2) { User::getInstance()->setGuideID(currentID + 1); } } } } void Guid::battleSelectSure() { //未完成继续.. cocos2d::ValueMap info; info["step"] = 2; info["guidId"] = BATTLE_SELECT; dispatch(UPDATE_GUID,&info); } void Guid::battleChoiceSure() { //未完成继续.. cocos2d::ValueMap info; info["step"] = 2; info["guidId"] = BATTLE_CHOICE; dispatch(UPDATE_GUID,&info); } bool Guid::isGuidFinish() { return User::getInstance()->getGuide(); } }
28.306781
213
0.493745
thales-vogso
5ceab5aa4910df6bb9f11de46f0f9acbee827ba9
1,787
cpp
C++
coast/foundation/io/cuteTest/ConnectorArgsTest.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/foundation/io/cuteTest/ConnectorArgsTest.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/foundation/io/cuteTest/ConnectorArgsTest.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * Copyright (c) 2015, David Tran, Faculty of Computer Science, * University of Applied Sciences Rapperswil (HSR), * 8640 Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "ConnectorArgsTest.h" #include "Socket.h" #include "Tracer.h" ConnectorArgsTest::ConnectorArgsTest() { } ConnectorArgsTest::~ConnectorArgsTest() { StartTrace(ConnectorArgsTest.Dtor); } void ConnectorArgsTest::ArgsTest() { StartTrace(ConnectorArgsTest.ArgsTest); ConnectorArgs ca("192.168.1.1", 9999, 40); ASSERT_EQUAL(ca.IPAddress(), "192.168.1.1"); ASSERT_EQUAL(ca.Port(), 9999); ASSERT_EQUAL(ca.ConnectTimeout(), 40); ConnectorArgs ca1("", 9999, 40); ASSERT_EQUAL(ca1.IPAddress(), "127.0.0.1"); ASSERT_EQUAL(ca1.Port(), 9999); ASSERT_EQUAL(ca1.ConnectTimeout(), 40); // Default constructor ConnectorArgs ca2; ASSERT_EQUAL(ca2.IPAddress(), "127.0.0.1"); ASSERT_EQUAL(ca2.Port(), 80); ASSERT_EQUAL(ca2.ConnectTimeout(), 0); // assignment operator ConnectorArgs ca3; ca3 = ca; ASSERT_EQUAL(ca3.IPAddress(), "192.168.1.1"); ASSERT_EQUAL(ca3.Port(), 9999); ASSERT_EQUAL(ca3.ConnectTimeout(), 40); // copy constructor ConnectorArgs ca4(ca); ASSERT_EQUAL(ca4.IPAddress(), "192.168.1.1"); ASSERT_EQUAL(ca4.Port(), 9999); ASSERT_EQUAL(ca4.ConnectTimeout(), 40); } // builds up a suite of tests, add a line for each testmethod void ConnectorArgsTest::runAllTests(cute::suite &s) { StartTrace(ConnectorArgsTest.suite); s.push_back(CUTE_SMEMFUN(ConnectorArgsTest, ArgsTest)); }
28.822581
102
0.738668
zer0infinity
5ced779dec0001f9d5535a8b85d6ef0d009c7891
1,980
cpp
C++
subset/bench_subset_BF.cpp
DandyForever/np-complete
9a8912706a85425f9da284173ce09c7eedbf7db0
[ "MIT" ]
null
null
null
subset/bench_subset_BF.cpp
DandyForever/np-complete
9a8912706a85425f9da284173ce09c7eedbf7db0
[ "MIT" ]
6
2020-11-29T18:27:05.000Z
2021-12-24T13:14:47.000Z
subset/bench_subset_BF.cpp
DandyForever/np-complete
9a8912706a85425f9da284173ce09c7eedbf7db0
[ "MIT" ]
8
2020-11-03T17:09:11.000Z
2021-12-04T14:24:49.000Z
#include "SSet.h" #include "benchmark/benchmark.h" #include <iostream> #include <sstream> static void BM_subsetBruteFromFile10T(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_true_10.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile10F(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_false_10.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile15T(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_true_15.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile15F(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_false_15.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile20T(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_true_20.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile20F(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_false_20.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile25T(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_true_25.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } static void BM_subsetBruteFromFile25F(benchmark::State& state) { SSet set; set.loadFromFile("../tests/input_sets/set_false_25.txt"); for (auto _ : state) { set.checkZeroSumSlow(); } } BENCHMARK(BM_subsetBruteFromFile10T); BENCHMARK(BM_subsetBruteFromFile10F); BENCHMARK(BM_subsetBruteFromFile15T); BENCHMARK(BM_subsetBruteFromFile15F); BENCHMARK(BM_subsetBruteFromFile20T); BENCHMARK(BM_subsetBruteFromFile20F); BENCHMARK(BM_subsetBruteFromFile25T); BENCHMARK(BM_subsetBruteFromFile25F); BENCHMARK_MAIN();
26.756757
64
0.733838
DandyForever
5cefa78e5d383773238ce9f7714f4fc64f3c7781
3,767
cpp
C++
MathTL/algebra/symmetric_matrix.cpp
kedingagnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
3
2018-05-20T15:25:58.000Z
2021-01-19T18:46:48.000Z
MathTL/algebra/symmetric_matrix.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
null
null
null
MathTL/algebra/symmetric_matrix.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
2
2019-04-24T18:23:26.000Z
2020-09-17T10:00:27.000Z
// implementation of MathTL::*TriangularMatrix inline functions #include <algorithm> #include <cassert> namespace MathTL { template <class C> inline SymmetricMatrix<C>::SymmetricMatrix(const size_type n) : LowerTriangularMatrix<C>(n) { } template <class C> inline SymmetricMatrix<C>::SymmetricMatrix(const SymmetricMatrix<C>& M) : LowerTriangularMatrix<C>(M) { } template <class C> SymmetricMatrix<C>::SymmetricMatrix(const size_type n, const char* str, const bool byrow) : LowerTriangularMatrix<C>(n,n,str,byrow) { } template <class C> inline void SymmetricMatrix<C>::resize(const size_type n) { LowerTriangularMatrix<C>::resize(n); } template <class C> inline const C SymmetricMatrix<C>::operator () (const size_type row, const size_type column) const { return LowerTriangularMatrix<C>::entries_[LowerTriangularMatrix<C>::triangle_index(row,column, LowerTriangularMatrix<C>::rowdim_, LowerTriangularMatrix<C>::coldim_)]; } template <class C> inline const C SymmetricMatrix<C>::get_entry(const size_type row, const size_type column) const { return this->operator () (row, column); } template <class C> inline C& SymmetricMatrix<C>::operator () (const size_type row, const size_type column) { return LowerTriangularMatrix<C>::entries_[LowerTriangularMatrix<C>::triangle_index(row,column, LowerTriangularMatrix<C>::rowdim_, LowerTriangularMatrix<C>::coldim_)]; } template <class C> inline void SymmetricMatrix<C>::set_entry(const size_type row, const size_type column, const C value) { this->operator () (row, column) = value; } template <class C> template <class C2> inline bool SymmetricMatrix<C>::operator == (const SymmetricMatrix<C2>& M) const { return LowerTriangularMatrix<C>::operator == (M); } template <class C> template <class C2> inline bool SymmetricMatrix<C>::operator != (const SymmetricMatrix<C2>& M) const { return !((*this) == M); } template <class C> SymmetricMatrix<C>& SymmetricMatrix<C>::operator = (const SymmetricMatrix<C>& M) { LowerTriangularMatrix<C>::operator = (M); return *this; } template <class C> template <class VECTOR> void SymmetricMatrix<C>::apply(const VECTOR& x, VECTOR& Mx) const { assert(Mx.size() == LowerTriangularMatrix<C>::rowdim_); for (typename SymmetricMatrix<C>::size_type i(0); i < LowerTriangularMatrix<C>::rowdim_; i++) { Mx[i] = 0; for (typename SymmetricMatrix<C>::size_type j(0); j < LowerTriangularMatrix<C>::coldim_; j++) Mx[i] += this->operator () (i, j) * x[j]; } } template <class C> template <class VECTOR> void SymmetricMatrix<C>::apply_transposed(const VECTOR& x, VECTOR& Mtx) const { apply(x, Mtx); } template <class C> void SymmetricMatrix<C>::print(std::ostream &os, const unsigned int tabwidth, const unsigned int precision) const { if (LowerTriangularMatrix<C>::empty()) os << "[]" << std::endl; // Matlab style else { unsigned int old_precision = os.precision(precision); for (typename SymmetricMatrix<C>::size_type i(0); i < SymmetricMatrix<C>::row_dimension(); ++i) { for (typename SymmetricMatrix<C>::size_type j(0); j < SymmetricMatrix<C>::column_dimension(); ++j) os << std::setw(tabwidth) << std::setprecision(precision) << this->operator () (i, j); os << std::endl; } os.precision(old_precision); } } template <class C> inline std::ostream& operator << (std::ostream& os, const SymmetricMatrix<C>& M) { M.print(os); return os; } }
24.782895
98
0.647996
kedingagnumerikunimarburg
5cf0f864adf77272d6b56750cf859873dcadb025
3,165
cxx
C++
main/autodoc/source/parser/cpp/pe_tydef.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/autodoc/source/parser/cpp/pe_tydef.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/autodoc/source/parser/cpp/pe_tydef.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include <precomp.h> #include "pe_tydef.hxx" // NOT FULLY DECLARED SERVICES #include <ary/cpp/c_gate.hxx> #include <ary/cpp/c_type.hxx> #include <ary/cpp/cp_ce.hxx> #include <all_toks.hxx> #include "pe_type.hxx" namespace cpp { PE_Typedef::PE_Typedef(Cpp_PE * i_pParent ) : Cpp_PE(i_pParent), pStati( new PeStatusArray<PE_Typedef> ), // pSpType, // pSpuType, // sName nType(0) { Setup_StatusFunctions(); pSpType = new SP_Type(*this); pSpuType = new SPU_Type(*pSpType, 0, &PE_Typedef::SpReturn_Type); } PE_Typedef::~PE_Typedef() { } void PE_Typedef::Call_Handler( const cpp::Token & i_rTok ) { pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text()); } void PE_Typedef::Setup_StatusFunctions() { typedef CallFunction<PE_Typedef>::F_Tok F_Tok; static F_Tok stateF_start[] = { &PE_Typedef::On_start_typedef }; static INT16 stateT_start[] = { Tid_typedef }; static F_Tok stateF_expectName[] = { &PE_Typedef::On_expectName_Identifier }; static INT16 stateT_expectName[] = { Tid_Identifier }; static F_Tok stateF_afterName[] = { &PE_Typedef::On_afterName_Semicolon }; static INT16 stateT_afterName[] = { Tid_Semicolon }; SEMPARSE_CREATE_STATUS(PE_Typedef, start, Hdl_SyntaxError); SEMPARSE_CREATE_STATUS(PE_Typedef, expectName, Hdl_SyntaxError); SEMPARSE_CREATE_STATUS(PE_Typedef, afterName, Hdl_SyntaxError); } void PE_Typedef::InitData() { pStati->SetCur(start); sName.clear(); nType = 0; } void PE_Typedef::TransferData() { pStati->SetCur(size_of_states); ary::cpp::Typedef & rTypedef = Env().AryGate().Ces().Store_Typedef( Env().Context(), sName, nType ); Env().Event_Store_Typedef(rTypedef); } void PE_Typedef::Hdl_SyntaxError( const char * i_sText) { StdHandlingOfSyntaxError(i_sText); } void PE_Typedef::SpReturn_Type() { pStati->SetCur(expectName); nType = pSpuType->Child().Result_Type().Id(); } void PE_Typedef::On_start_typedef( const char * ) { pSpuType->Push(done); } void PE_Typedef::On_expectName_Identifier( const char * i_sText ) { SetTokenResult(done, stay); pStati->SetCur(afterName); sName = i_sText; } void PE_Typedef::On_afterName_Semicolon( const char * ) { SetTokenResult(done, pop_success); } } // namespace cpp
22.934783
78
0.701106
Grosskopf
5cf0fd512ce372f381352717a818f7fab7f03081
1,619
cpp
C++
Connector/BillCmdMsg_KOR.cpp
Light-Games-Ink/LMLastChaosSource
ff3f1988590dfd441824832d9c242fb51eb2c318
[ "Unlicense" ]
3
2016-05-22T16:44:18.000Z
2021-06-12T00:38:59.000Z
Connector/BillCmdMsg_KOR.cpp
Light-Games-Ink/LMLastChaosSource
ff3f1988590dfd441824832d9c242fb51eb2c318
[ "Unlicense" ]
null
null
null
Connector/BillCmdMsg_KOR.cpp
Light-Games-Ink/LMLastChaosSource
ff3f1988590dfd441824832d9c242fb51eb2c318
[ "Unlicense" ]
1
2021-01-16T23:15:30.000Z
2021-01-16T23:15:30.000Z
#include "stdhdrs.h" #ifndef USE_TENTER_BILLING #include "Server.h" #include "../ShareLib/DBCmd.h" #include "CmdMsg.h" void BillConnectMsg(CBPacket::SP& msg) { CLCString protocolVersion(17); protocolVersion.Format("%s", BILL_SERVER_VERSION); msg->Init(BM_CONNECT); RefMsg(msg) << protocolVersion << (unsigned char) gserver.m_serverno << (unsigned char) GAMEID; } void BillBalanceReqMsg(CBPacket::SP& msg, int userindex, const char* idname) { CLCString id(51); id.Format("%s", idname); msg->Init(MSG_BILLITEM_CASHBALANCE_REQ); RefMsg(msg) << id << (unsigned char) CPID << userindex; } void BillCanbuyReqMsg(CBPacket::SP& msg, int userindex, const char* idname, int ctid[], char count, const char* ip) { CLCString id(51); id.Format("%s", idname); CLCString lcIP(16); lcIP.Format("%s", ip); msg->Init(MSG_BILLITEM_CANBUY_REQ); RefMsg(msg) << id << (unsigned char) CPID << userindex << lcIP << (unsigned char) count; for(int i = 0; i < MAX_PURCHASEITEM && i < count; i++) { RefMsg(msg) << ctid[i]; } } void BillBuyReqMsg(CBPacket::SP& msg, int userindex, const char* userid, int serial, int ctid[], const char* ip, char count) { msg->Init(MSG_BILLITEM_BUY_REQ); msg->m_serial = serial; CLCString id(51); id.Format("%s", userid); CLCString lcIP(16); lcIP.Format("%s", ip); RefMsg(msg) << id << (unsigned char) CPID << userindex << lcIP << (unsigned char) count; for(int i = 0; i < MAX_PURCHASEITEM && i < count; i++) { RefMsg(msg) << ctid[i]; } } #endif
21.302632
125
0.62446
Light-Games-Ink
5cf471474d44b363b6e0371ec4f7fe80040962f0
978
cc
C++
src/jumandic/shared/jumandic_debug_dump_test.cc
wrightak/jumanpp
49784bac7ee9562f1839aa12c780b019a1cb0e03
[ "Apache-2.0" ]
300
2016-10-19T02:20:39.000Z
2022-02-23T19:58:04.000Z
src/jumandic/shared/jumandic_debug_dump_test.cc
wrightak/jumanpp
49784bac7ee9562f1839aa12c780b019a1cb0e03
[ "Apache-2.0" ]
130
2016-10-17T07:57:14.000Z
2022-03-20T17:37:13.000Z
src/jumandic/shared/jumandic_debug_dump_test.cc
wrightak/jumanpp
49784bac7ee9562f1839aa12c780b019a1cb0e03
[ "Apache-2.0" ]
36
2016-10-19T11:47:05.000Z
2022-01-25T09:36:12.000Z
// // Created by Arseny Tolmachev on 2017/12/08. // #include "core/proto/lattice_dump_output.h" #include "jumandic/shared/jumandic_test_env.h" using namespace jumanpp; TEST_CASE("debug dump works with jumandic and full beam") { JumandicTrainingTestEnv env{"jumandic/codegen.mdic"}; core::analysis::Analyzer an; core::analysis::AnalyzerConfig analyzerConfig; analyzerConfig.storeAllPatterns = true; analyzerConfig.globalBeamSize = 0; env.initialize(); core::ScoringConfig sconf; sconf.numScorers = 1; sconf.beamSize = 5; REQUIRE(an.initialize(env.jppEnv.coreHolder(), analyzerConfig, sconf, env.trainEnv.value().scorerDef())); an.impl()->setStoreAllPatterns(true); REQUIRE(an.analyze("551年もガラフケマペが兵をつの〜ってたな!")); core::output::LatticeDumpOutput output{true, true}; auto& weights = env.trainEnv.value().scorerDef()->feature->weights(); REQUIRE(output.initialize(an.impl(), &weights)); REQUIRE(output.format(an, "test")); }
34.928571
71
0.725971
wrightak
5cf65a31c0bfabb00320ec9f264e7d52a2c9ba75
2,933
cpp
C++
Fog.NET/SvgDocument.cpp
Rungee/Fog.NET
b95ab0a6ae9a466825505ca4346133a1004cf333
[ "MIT" ]
3
2015-01-28T17:51:34.000Z
2016-09-01T01:53:19.000Z
Fog.NET/SvgDocument.cpp
Rungee/Fog.NET
b95ab0a6ae9a466825505ca4346133a1004cf333
[ "MIT" ]
1
2015-05-07T15:47:16.000Z
2015-05-07T15:47:16.000Z
Fog.NET/SvgDocument.cpp
Rungee/Fog.NET
b95ab0a6ae9a466825505ca4346133a1004cf333
[ "MIT" ]
null
null
null
/****************************************************************************** * * Name: SvgDocument.cpp * Project: Fog-Framework (Copyright (c) 2006-2011, Petr Kobalicek <kobalicek.petr@gmail.com>) C++/CLI Interface * Author: Maxim Rylov * ****************************************************************************** * The MIT License (MIT) * * Copyright (C) 2012, Maxim Rylov * * 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. *****************************************************************************/ #include "stdafx.h" #include "SvgDocument.h" #include "Enums.h" #include "clix.h" #include "ManagedStreamDevice.h" #include "Fog/Core/Tools/Stream.h" #include "Fog/G2d/Svg/SvgDom.h" namespace FogNET { using namespace clix; SvgDocument::SvgDocument(void) { m_svgDocument = new Fog::SvgDocument(); } SvgDocument::~SvgDocument() { delete m_svgDocument; m_svgDocument = NULL; } SizeF SvgDocument::GetSize() { Fog::SizeF size = m_svgDocument->getDocumentSize(); return SizeF(size.w, size.h); } SvgDocument^ SvgDocument::FromFile(String ^fileName) { std::string str = marshalString<E_UTF8>(fileName); Fog::StringW fileNameW = Fog::StringW::fromUtf8(str.c_str(), str.length()); SvgDocument ^doc = gcnew SvgDocument(); doc->m_svgDocument->readFromFile(fileNameW); return doc; } SvgDocument^ SvgDocument::FromStream(Stream ^stream) { if (!stream->CanRead) throw gcnew IOException("stream is closed"); ManagedStreamDevice* msd = new ManagedStreamDevice(stream); Fog::Stream* fStream = new Fog::Stream((Fog::StreamDevice*)msd); SvgDocument ^doc = gcnew SvgDocument(); doc->m_svgDocument->readFromStream(*fStream); return doc; } void SvgDocument::Render(Painter ^painter) { m_svgDocument->render((Fog::Painter*)painter->GetNativePointer()); } }
32.230769
113
0.652915
Rungee
5cf8ffa2a5ef989284712425c4c6c48b43a4694b
904
cpp
C++
catkin_ws/src/srrg2_solver/srrg2_solver/src/srrg_solver/variables_and_factors/types_2d/variable_se2_ad.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
124
2020-02-26T14:40:45.000Z
2022-03-29T11:11:48.000Z
catkin_ws/src/srrg2_solver/srrg2_solver/src/srrg_solver/variables_and_factors/types_2d/variable_se2_ad.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
null
null
null
catkin_ws/src/srrg2_solver/srrg2_solver/src/srrg_solver/variables_and_factors/types_2d/variable_se2_ad.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
16
2020-03-03T00:57:43.000Z
2022-03-15T00:50:12.000Z
#include "variable_se2_ad.h" #include "srrg_solver/solver_core/instance_macros.h" #include "srrg_solver/solver_core/variable_impl.cpp" namespace srrg2_solver { using namespace srrg2_core; template <typename VariableSE2_> VariableSE2AD_<VariableSE2_>::~VariableSE2AD_(){} template <typename VariableSE2_> void VariableSE2AD_<VariableSE2_>::applyPerturbationAD(const ADPerturbationVectorType& pert) { ADEstimateType pert_m; pert_m = geometry2d::v2t(pert); switch (VariableType::PerturbationSide) { case VariableSE2Base::Left: ADVariableType::_ad_estimate = pert_m * ADVariableType::_ad_estimate; break; case VariableSE2Base::Right: ADVariableType::_ad_estimate = ADVariableType::_ad_estimate * pert_m; break; default: assert(0); } } INSTANTIATE(VariableSE2RightAD) INSTANTIATE(VariableSE2LeftAD) } // namespace srrg2_solver
28.25
96
0.75
laaners
9dc718db7c954e7c425e24963ed9b7d28279db8d
102,450
cpp
C++
ssrounding.cpp
xmuriqui/muriqui
ff1492c70e297077c9450ef9175e5a80c6627140
[ "MIT" ]
5
2021-12-04T04:42:32.000Z
2022-01-21T13:23:47.000Z
ssrounding.cpp
xmuriqui/muriqui
ff1492c70e297077c9450ef9175e5a80c6627140
[ "MIT" ]
null
null
null
ssrounding.cpp
xmuriqui/muriqui
ff1492c70e297077c9450ef9175e5a80c6627140
[ "MIT" ]
null
null
null
/* * This file implements the structured stochastic rounding heurist. An experimental feasibility heuristic from our heads * * 02, September, 2020 * * Author: Wendel Melo */ #include <cassert> #include <cstdlib> #include <cmath> #include <ctime> #include <iostream> #include <new> #include "MRQ_algClasses.hpp" #include "MRQ_solvers.hpp" #include "MRQ_tools.hpp" #include "MRQ_ssrounding.hpp" #include "MRQ_rens.hpp" using namespace muriqui; using namespace optsolvers; using namespace minlpproblem; #define MRQ_TRY_FIX_FLOW_CONSTRAINTS_AT_1 0 int MRQ_SSRCore::fixFirstVarsAt0( const int nVarsToFix, const int sizea, const int *acols, double *lx, double *ux ) { int nfixed = 0; if( nVarsToFix > 0 ) { for(int j = 0; j < sizea; j++) { const int ind = acols[j]; if( lx[ind] != ux[ind] ) { #if MRQ_DEBUG_MODE assert( lx[ind] == 0.0 ); assert( ux[ind] == 1.0 ); #endif ux[ind] = 0.0; nfixed++; if( nfixed >= nVarsToFix ) break; } } } return nfixed; } int MRQ_SSRCore::fixFirstVarsAt1( const int nVarsToFix, const int sizea, const int *acols, double *lx, double *ux, const bool updateVarBoundsByKnapsackConstrs, const MRQ_MINLPProb *prob, const double *uc, const MIP_BinSumConstrsIndsByClass *binSumConstrInds, const int *reverseIntVars ) { int nfixed = 0; if( nVarsToFix > 0 ) { for(int j = 0; j < sizea; j++) { const int ind = acols[j]; if( lx[ind] != ux[ind] ) { #if MRQ_DEBUG_MODE assert( lx[ind] == 0.0 ); assert( ux[ind] == 1.0 ); #endif //lx[ind] = 1.0; fixVarAt1(ind, lx, ux, updateVarBoundsByKnapsackConstrs, prob, uc, binSumConstrInds, reverseIntVars); nfixed++; if( nfixed >= nVarsToFix ) break; } } } return nfixed; } //Returns number of variables fixed int MRQ_SSRCore::fixRandomVarsAt0(MRQ_Random &random, const int nVarsToFix, const int sizea, const int *acols, double *lx, double *ux, const int *reverseIntVars) { return fixRandomVarsAt01(random, nVarsToFix, sizea, acols, lx, ux, true, false, nullptr, nullptr, nullptr, reverseIntVars); } //Returns number of variables fixed int MRQ_SSRCore::fixRandomVarsAt1(MRQ_Random &random, const int nVarsToFix, const int sizea, const int *acols, double *lx, double *ux, const bool updateVarBoundsByKnapsackConstrs, const MRQ_MINLPProb *prob, const double *uc, const MIP_BinSumConstrsIndsByClass *binSumConstrInds, const int *reverseIntVars ) { return fixRandomVarsAt01(random, nVarsToFix, sizea, acols, lx, ux, false, updateVarBoundsByKnapsackConstrs, prob, uc, binSumConstrInds, reverseIntVars ); } /*if fixAt0 == true,variables will be fixed on 0. Otherwise, variables will be fixed on 1. * Returns number of variables fixed */ int MRQ_SSRCore::fixRandomVarsAt01(MRQ_Random &random, const int nVarsToFix, const int sizea, const int *acols, double *lx, double *ux, const bool fixAt0, const bool updateVarBoundsByKnapsackConstrs, const MRQ_MINLPProb *prob, const double *uc, const MIP_BinSumConstrsIndsByClass *binSumConstrInds, const int *reverseIntVars ) { const int maxRandonsFails = 1000 + nVarsToFix; int nRandomFails = 0; int nFixed = 0; while( nFixed < nVarsToFix ) { const int randValue = random.randInt(0, sizea-1); const int col = acols[ randValue ]; if( lx[col] != ux[col] ) { //we assume binary vars in this constraints #if MRQ_DEBUG_MODE //assert( avalues[randValue] == 1.0 ); assert( lx[col] == 0.0 && ux[col] == 1.0 ); #endif if( fixAt0 ) ux[col] = 0.0; else fixVarAt1(col, lx, ux, updateVarBoundsByKnapsackConstrs, prob, uc, binSumConstrInds, reverseIntVars); nFixed++; } else { nRandomFails++; if( nRandomFails >= maxRandonsFails ) { //so, we give up the random indices, and set by order if( fixAt0 ) nFixed += fixFirstVarsAt0(nVarsToFix-nFixed, sizea, acols, lx, ux); else nFixed += fixFirstVarsAt1(nVarsToFix-nFixed, sizea, acols, lx, ux, updateVarBoundsByKnapsackConstrs, prob, uc, binSumConstrInds, reverseIntVars); #if MRQ_DEBUG_MODE assert( nFixed <= nVarsToFix ); #endif break; } } } return nFixed; } int MRQ_SSRCore:: fixAllNonFixedVarsByStochRounding(const int n, const int nI, const int *intVars, const double *startSol_, const double minimumProbToRound, const int print_level, MRQ_Random &random, int *auxInds, int &nVarsFixed, double *lx, double *ux, MRQ_Preprocessor *preprocessor, const minlpproblem::MIP_ConstraintsByColumnsStorager *ccstorager, MRQ_BoundsUpdaterSolver *boundsUpdaterSolver, double *currlc, double *curruc, const int contRelaxStrategy, optsolvers::OPT_LPSolver *nlpSolver) { nVarsFixed = 0; const int *myIntVars; const bool preproc_quad = true; bool solveContRelax = contRelaxStrategy != MRQ_SSR_CRSSR_NO_CONTINUOUS_RELAXATION; bool solverBoundsInitialized = false; int retCode; if( preprocessor ) { //if we preprocess, maybe is a good idea to run integer variables in a random order MRQ_copyArray(nI, intVars, auxInds); MRQ_shuffleArray(nI, auxInds, random); myIntVars = auxInds; } else { myIntVars = intVars; } for(int i = 0; i < nI; i++) { int ind = myIntVars[i]; //std::cout << "i: " << i << " ind: " << ind << "\n"; if(lx[ind] != ux[ind]) { double startSolInd = startSol_[ind]; if( boundsUpdaterSolver ) { bool infeas; int r = boundsUpdaterSolver->calculateNewVarBounds(n, 1, &ind, lx, ux, true, infeas ); MRQ_IFERRORRETURN(r, MRQ_NLP_SOLVER_ERROR); /*printf("lx[%d]: %0.2f ux[%d]: %0.2f\n", ind, lx[ind], ind, ux[ind]); MRQ_getchar(); */ if(infeas) { if(print_level > 5) std::cout << MRQ_PREPRINT "Bounds updater sover detected infeasbility in stochastic rounding \n"; return MRQ_HEURISTIC_FAIL; } if( lx[ind] == ux[ind] ) continue; } if( solveContRelax ) { //if( !solverBoundsInitialized ) { //int r = nlpSolver->setnVariablesBounds(n, lx, ux); for(int j = 0; j < nI; j++) { const int jind = intVars[j]; int r = nlpSolver->setVariableBounds( jind, lx[jind], ux[jind] ); #if MRQ_DEBUG_MODE MRQ_IFERRORGOTOLABEL(r, retCode, MRQ_NLP_SOLVER_ERROR, termination); #endif } solverBoundsInitialized = true; } nlpSolver->solve(false, true, false, false); /* std::cout << "i: " << i << " nI: " << nI << " Resolvi relaxação continua para arredondamento. feas: " << nlpSolver->feasSol << " obj: " << nlpSolver->objValue << " minimumProbToRound: " << minimumProbToRound << "\n" ; for(int j = 0; j < nI; j++) std::cout << "x_" << intVars[j] << ": " << nlpSolver->sol[ intVars[j] ] << "\t"; */ if( nlpSolver->retCode == OPT_INFEASIBLE_PROBLEM ) { //MRQ_getchar(); retCode = MRQ_HEURISTIC_FAIL; goto termination; } if( nlpSolver->feasSol ) { const double *sol = nlpSolver->sol; const double integerTol = 1e-4; const bool intSol = MRQ_isIntegerSol( nI, intVars, sol, integerTol); if( intSol ) { //we found a feasible solution for(int j = 0; j < nI; j++) { const int jind = intVars[j]; ux[jind] = lx[jind] = round( sol[jind] ); } retCode = 0; goto termination; } startSolInd = sol[ind]; } else { // threating the general integer case: we guarantee some value having 0.5 of integer gap. startSolInd = (lx[ind] + ux[ind])/2.0 ; startSolInd = ((int) startSolInd) + 0.5; } if( contRelaxStrategy == MRQ_SSR_CRSSR_ONLY_BEFORE_STARTING ) { solveContRelax = false; if( nlpSolver->feasSol ) startSol_ = nlpSolver->sol ; } } double prob = startSolInd - floor(startSolInd); //we must let a minimum probability to value be rounded to up and to down if( prob < minimumProbToRound ) prob = minimumProbToRound; else if( prob > 1 - minimumProbToRound ) prob = 1 - minimumProbToRound; if( random.random() < prob ) lx[ind] = ux[ind] = ceil( startSolInd ); else lx[ind] = ux[ind] = floor( startSolInd ); //std::cout<< "\ni: " << i <<" var: " << ind << " prob: " << prob << " fixed: " << lx[ind] << "\n"; if( solveContRelax ) { int r = nlpSolver->setVariableBounds( ind, lx[ind], ux[ind] ); MRQ_IFERRORGOTOLABEL(r, retCode, MRQ_NLP_SOLVER_ERROR, termination); } nVarsFixed++; //this count can be wrong because preprocessor can fix vars also if( preprocessor ) { bool updtVarBounds, updtConstrBounds; int r; //r = preprocessor->preprocess(false, false, INFINITY, lx, ux, updtVarBounds, updtConstrBounds); r = preprocessor->preprocess(1, &ind, *ccstorager, preproc_quad, false, INFINITY, lx, ux, updtVarBounds, updtConstrBounds, currlc, curruc, currlc, curruc ); //MRQ_getchar(); if(r == MIP_INFEASIBILITY) { //we got a failure //we try to round to the other side: if( ux[ind] == ceil( startSolInd ) ) lx[ind] = ux[ind] = floor( startSolInd ); else lx[ind] = ux[ind] = ceil( startSolInd ); r = preprocessor->preprocess(1, &ind, *ccstorager, preproc_quad, false, INFINITY, lx, ux, updtVarBounds, updtConstrBounds, currlc, curruc, currlc, curruc ); if( r == MIP_INFEASIBILITY ) { if(print_level > 5) std::cout << MRQ_PREPRINT "Preprocessor detected infeasbility in stochastic rounding \n"; retCode = MRQ_HEURISTIC_FAIL; goto termination; } } } } } retCode = 0; termination: return retCode; } void MRQ_SSRCore::fixAllNonFixedAt0(const int sizea, const int *acols, double *lx, double *ux) { for(int j = 0; j < sizea; j++) { const int ind = acols[j]; if( lx[ind] != ux[ind] ) { #if MRQ_DEBUG_MODE assert( lx[ind] == 0.0 ); assert( ux[ind] == 1.0 ); #endif ux[ind] = 0.0; } } } //new version where we let some variables free in <= constraints int MRQ_SSRCore::class0_3_4Handle(const int sizea, const int *acols, const double *avalues, const double lc, const double uc, MRQ_Random &random, int *auxInds, double *lx, double *ux, const bool updateVarBoundsByKnapsackConstrs, const MRQ_MINLPProb *prob, const double *ubc, const minlpproblem::MIP_BinSumConstrsIndsByClass *binSumConstrInds, const int *reverseIntVars, MRQ_Preprocessor *preprocessor, const minlpproblem::MIP_ConstraintsByColumnsStorager *ccstorager ) { int *nonFixed = auxInds; int nToFixAt1, nToFixAt0 = 0, nNonFixed = 0; double rhs = uc < MIP_INFINITY ? uc : lc; #if MRQ_DEBUG_MODE assert(sizea > 0); #endif for(int j = 0; j < sizea; j++) { const int col = acols[j]; const double coef = avalues[j]; if( lx[col] == ux[col] ) { if( ux[col] != 0.0 ) rhs -= ux[col] * coef; } else { nonFixed[nNonFixed] = col; nNonFixed++; } } #if MRQ_DEBUG_MODE assert( MRQ_isIntegerDouble(rhs) ); #endif if( rhs < 0.0 && lc <= -MIP_INFINITY ) return MRQ_BAD_PARAMETER_VALUES; //we cannot satisfy this constraint if(lc == uc) { nToFixAt1 = rhs; if(nToFixAt1 == 0) nToFixAt0 = nNonFixed; //if we have nToFixAt1 > 0, we will fix the remanider variables to 0 after fix variables to 1. } else if(lc <= -MIP_INFINITY) { // we have a less than contsraint ... <= b. //nToFix = random.randInt(0, nToFix); #if MRQ_DEBUG_MODE assert(rhs >= 0.0); #endif //now, we let rhs variables free to be set by other constraints. We must fix all remainder variables to 0. So, we do not fix variables to 1, but we allow until rhs variables can be fix in the future letting those variable free. nToFixAt1 = 0; nToFixAt0 = MRQ_max<int>( nNonFixed - rhs, 0 ); } else { #if MRQ_DEBUG_MODE assert( uc >= MIP_INFINITY ); #endif // we have a greater than constraint ... >= b. // here, we do not fix variables to 0 nToFixAt1 = MRQ_max<int>(rhs, 0); } if(nToFixAt1 > 0) { if( nToFixAt1 > nNonFixed ) { //we cannot satisfy this constraint return MRQ_BAD_PARAMETER_VALUES; } else if( nToFixAt1 == nNonFixed ) { int r = fixFirstVarsAt1(nToFixAt1, sizea, acols, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if(r < nToFixAt1) return MRQ_BAD_PARAMETER_VALUES; } else { int r = fixRandomVarsAt1(random, nToFixAt1, nNonFixed, nonFixed, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if(r < nToFixAt1) return MRQ_BAD_PARAMETER_VALUES; //fixing the remainder variables to 0, but we do noc fix class 4, because if constraint is >= b, it is already satisfied. if( uc < MIP_INFINITY ) fixAllNonFixedAt0(sizea, acols, lx, ux); } } else { if( nToFixAt0 > 0 ) { if( nToFixAt0 == nNonFixed ) { fixFirstVarsAt0( nToFixAt0, sizea, acols, lx, ux); //I think we do not have to test returned value here. } else { //we assume nToFixAt0 < nNonFixed fixRandomVarsAt0(random, nToFixAt0, sizea, acols, lx, ux, reverseIntVars); } } } return 0; } //new version where we let some variables free in <= constraints int MRQ_SSRCore::class1_2_5_6Handle( const int sizea, const int *acols, const double *avalues, const double lc, const double uc, MRQ_Random &random, int *auxInds1, int *auxInds2, double *lx, double *ux, const bool updateVarBoundsByKnapsackConstrs, const MRQ_MINLPProb *prob, const double *ubc, const minlpproblem::MIP_BinSumConstrsIndsByClass *binSumConstrInds, const int *reverseIntVars, MRQ_Preprocessor *preprocessor, const minlpproblem::MIP_ConstraintsByColumnsStorager *ccstorager ) { int *pCoefInds = auxInds1, *negCoefInds = auxInds2; int nPCoefInds = 0, nNegCoefInds = 0; int nFixPCoefs, nFixNegCoefs; int nVarsFixed1 = 0, nVarsNegCoef = 0, nVarsPosCoef = 0; double rhs = uc; for(int j = 0; j < sizea; j++) { const int ind = acols[j]; const double val = avalues[j]; if( lx[ind] == ux[ind] ) { if( lx[ind] != 0.0 ) { rhs -= lx[ind] * val ; nVarsFixed1++; } } else { if( val == 1.0 ) { pCoefInds[ nPCoefInds ] = ind; nPCoefInds++; } else if( val == -1.0 ) { negCoefInds[ nNegCoefInds ] = ind; nNegCoefInds++; } #if MRQ_DEBUG_MODE else assert(false); //coeficient should be 1 or -1 #endif } #if MRQ_TRY_FIX_FLOW_CONSTRAINTS_AT_1 if( val > 0.0 ) nVarsPosCoef++; else if ( val < 0.0 ) nVarsNegCoef++; #endif } /*std::cout << "nPCoefInds: " << nPCoefInds << " nNegCoefInds: " << nNegCoefInds << " rhs: " << rhs << "\n"; for(unsigned int w = 0; w < MRQ_max(nPCoefInds, nNegCoefInds) ; w++) { if(w < nPCoefInds) std::cout << "\tpCoefInds["<<w<<"]:" << pCoefInds[w]; if(w < nNegCoefInds) std::cout << "\t\tnegCoefInds["<<w<<"]:" << negCoefInds[w]; std::cout << "\n"; }*/ #if MRQ_DEBUG_MODE assert(MRQ_isIntegerDouble(rhs)); #endif if( rhs == 0.0) { int maxFix = MRQ_min( nNegCoefInds, nPCoefInds ); nFixNegCoefs = random.randInt(0, maxFix); #if MRQ_TRY_FIX_FLOW_CONSTRAINTS_AT_1 if( nVarsPosCoef > 1 && nVarsNegCoef > 1 ) { /*we assume we have a flow constraint: x_{p_1} + x_{p_2} + x_{p_3} + ... + x_{p_k} - x_{n_1} - x_{n_2} - x_{n_3} - ... - x_{n_q} {=, <=} b */ if( nVarsFixed1 > 0 ) { /*since rhs is zero and nVarsFixed1 > 0, we assume constraints is already satisfied */ nFixNegCoefs = 0; } else { if(maxFix > 0) nFixNegCoefs = 1; //since we do not have variables fixed at 1, and that is a flow constraint, we try enforce the flow as 1, since the most pat of flux constraints is just to pass 1 by the flow. } } #endif if( lc == uc ) {//classes 1 and 5 //if( maxFix > 0) nFixNegCoefs = 1; //TODO: THIS IS A TEST REMOVE THAT nFixPCoefs = nFixNegCoefs; } else // we have a less than contsraint ... <= b. So, we can have more variables with coefficient -1 fixed at 1. We define a number possible lower to fix in nFixPCoefs { #if MRQ_DEBUG_MODE assert(lc <= -MIP_INFINITY); #endif //now, we let nFixNegCoefs free to be fixed by other contsraints... nFixPCoefs = nFixNegCoefs; //nFixPCoefs = random.randInt(0, nFixNegCoefs); } } else if( rhs > 0.0 ) { //we have more variables having coeficient -1 fixed at 1. So, we need to fix rhs more variables having coefficient 1 at 1 in equalities constraints. int maxFix = MRQ_min( nNegCoefInds, nPCoefInds - (int) rhs ); if( maxFix < 0 ) { //rhs is positive and we cannot fix any variable here. If constraint is <=, it is ok, constraint is guaranteed be satisfied. if( lc <= -MIP_INFINITY ) return 0; else { #if MRQ_DEBUG_MODE assert( lc == uc ); #endif return MRQ_BAD_PARAMETER_VALUES; //equality constraint. In this case, we cannot satisfy this constraint with current set of variables fiexd } } nFixNegCoefs = random.randInt(0, maxFix); #if MRQ_TRY_FIX_FLOW_CONSTRAINTS_AT_1 if( rhs == 1.0 ) { if(nVarsPosCoef > 1 && nVarsNegCoef > 1) { /*we assume we have a flow constraint: x_{p_1} + x_{p_2} + x_{p_3} + ... + x_{p_k} - x_{n_1} - x_{n_2} - x_{n_3} - ... - x_{n_q} {=, <=} b */ //we do not let more variables having negative coefs being fixed at 1, since the most part of flow constraints has 1 as flow nFixNegCoefs = 0; } } #endif if( lc == uc ) { nFixPCoefs = nFixNegCoefs + rhs; } else { // we have a less than contsraint ... <= b. So, we can have more variables with coefficient -1 fixed at 1. We define a number possible lower to fix in nFixPCoefs #if MRQ_DEBUG_MODE assert(lc <= -MIP_INFINITY); #endif //nFixPCoefs = random.randInt(0, nFixNegCoefs + rhs); //now, we let nFixNegCoefs free to be fixed by other contsraints... nFixPCoefs = nFixNegCoefs + rhs; } } else //rhs < 0 { //we have more variables having coeficient 1 fixed at 1. So, we need to fix rhs more variables having coefficient -1 at 1. int maxFix = MRQ_min( nNegCoefInds + (int) rhs, nPCoefInds ); //remember: here, rhs is negative, so we have to sum instead of subtrate, since -rhs has the number of variables having positive coefs above the numver of variables having negative coefs. if( maxFix < 0 ) return MRQ_BAD_PARAMETER_VALUES; //we cannot satisfy this constraint with currentset of variables fiexd nFixPCoefs = random.randInt(0, maxFix); #if MRQ_TRY_FIX_FLOW_CONSTRAINTS_AT_1 if( rhs == -1.0 ) { if(nVarsPosCoef > 1 && nVarsNegCoef > 1) { /*we assume we have a flow constraint: x_{p_1} + x_{p_2} + x_{p_3} + ... + x_{p_k} - x_{n_1} - x_{n_2} - x_{n_3} - ... - x_{n_q} {=, <=} b */ //we do not let more variables having positive coefs being fixed at 1, since the most part of flow constraints has 1 as flow nFixPCoefs = 0; } } #endif if( lc == uc ) { nFixNegCoefs = nFixPCoefs - rhs; //here, rhs is negative, so we have to sum instead of subtrate } else { // we have a less than contsraint ... <= b. So, we can have more variables with coefficient 1 fixed at 1. We define a number possible lower to fix in nFixPCoefs #if MRQ_DEBUG_MODE assert(lc <= -MIP_INFINITY); assert(nFixPCoefs + rhs <= nNegCoefInds); #endif //nFixNegCoefs = random.randInt(nFixPCoefs - rhs, nNegCoefInds); //remember: here, rhs is negative //now, we let nFixNegCoefs free to be fixed by other constraints... nFixNegCoefs = nFixPCoefs - rhs; //remember: here, rhs is negative } } #if MRQ_DEBUG_MODE assert( nFixPCoefs >= 0 ); assert( nFixNegCoefs >= 0 ); #endif if( nFixPCoefs == nPCoefInds ) { if( lc == uc ) //equality constraints { int r = fixFirstVarsAt1(nFixPCoefs, nPCoefInds, pCoefInds, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if( r < nFixPCoefs) return MRQ_BAD_PARAMETER_VALUES; } else { //at less than constraints ( <= ), we dot not fix variables having positive coefficients at 1 #if MRQ_DEBUG_MODE assert( lc <= -MIP_INFINITY ); #endif } } else { #if MRQ_DEBUG_MODE assert( nFixPCoefs < nPCoefInds ); #endif if( lc == uc ) { int r = fixRandomVarsAt1(random, nFixPCoefs, nPCoefInds, pCoefInds, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if( r < nFixPCoefs ) return MRQ_BAD_PARAMETER_VALUES; fixAllNonFixedAt0(nPCoefInds, pCoefInds, lx, ux); } else { //at less than constraints ( <= ), we dot not fix variables having positive coefficients at 1. We only fix remainder variable to 0 and let nFixPCoefs variables free to be fixed by other constraints. #if MRQ_DEBUG_MODE assert( lc <= -MIP_INFINITY ); #endif int nFixTo0 = nPCoefInds - nFixPCoefs; //remainder coefficients to be fixed on zero. So, at most, nFixPCoefs variables could be fixed at 1 in the future int r = fixRandomVarsAt0( random, nFixTo0, nPCoefInds, pCoefInds, lx, ux, reverseIntVars ); if( r != nFixTo0 ) return MRQ_UNDEFINED_ERROR; } } if( nFixNegCoefs == nNegCoefInds ) { int r = fixFirstVarsAt1(nFixNegCoefs, nNegCoefInds, negCoefInds, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if( r < nFixNegCoefs ) return MRQ_BAD_PARAMETER_VALUES; } else { #if MRQ_DEBUG_MODE assert( nFixNegCoefs < nNegCoefInds ); #endif int r = fixRandomVarsAt1(random, nFixNegCoefs, nNegCoefInds, negCoefInds, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if( r < nFixNegCoefs ) return MRQ_BAD_PARAMETER_VALUES; //now, for <= constraints, we do not fix variables having negative coefficient to 0. We let them free to possibly be fixed by other constraints' handlres if(lc == uc) fixAllNonFixedAt0(nNegCoefInds, negCoefInds, lx, ux); } return 0; } int MRQ_SSRCore::class8Handle(const int sizea, const int *acols, const double *avalues, const double lc, const double uc, MRQ_Random &random, int *auxInds, double *lx, double *ux, const bool updateVarBoundsByKnapsackConstrs, const MRQ_MINLPProb *prob, const double *ubc, const minlpproblem::MIP_BinSumConstrsIndsByClass *binSumConstrInds, const int *reverseIntVars) { /*int *nonFixed = auxInds; int nNonFixed = 0; */ int nRandomFails = 0; const int maxRandonsFails = 1000; double rhs = uc < MIP_INFINITY ? uc : lc; #if MRQ_DEBUG_MODE assert(sizea > 0); #endif for(int j = 0; j < sizea; j++) { const int col = acols[j]; if( lx[col] == ux[col] ) { const double coef = avalues[j]; if( ux[col] != 0.0 ) rhs -= coef * ux[col]; } /*else { nonFixed[nNonFixed] = col; nNonFixed++; }*/ } #if MRQ_DEBUG_MODE assert( MRQ_isIntegerDouble(rhs) ); #endif /*std::cout << "nNonFixed: " << nNonFixed << " rhs: " << rhs << "\n"; for( int w = 0; w < nNonFixed; w++ ) std::cout << "nonFixed["<<w<<"]: " << nonFixed[w] << "\n"; */ while(rhs > 0.0) { const int rind = random.randInt(0, sizea-1); //we must pick indices in the costraint array because we wiill need get the coeficient also const int rcol = acols[rind]; if( lx[rcol] != ux[rcol] ) { #if MRQ_DEBUG_MODE assert(lx[rcol] == 0.0 && ux[rcol] == 1.0); #endif fixVarAt1(rcol, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); rhs -= avalues[rind]; //we are fixing at 1 } else { nRandomFails++; if( nRandomFails >= maxRandonsFails ) { //so, we give up the random indices, and set by order for(int j = 0; j < sizea; j++) { const int col = acols[j]; if( lx[col] != ux[col] ) { const double coef = avalues[j]; rhs -= coef; if( rhs <= 0.0) break; } } break; } } } if( rhs <= 0.0 ) return 0; else return MRQ_BAD_PARAMETER_VALUES; //we could not satisfy this constraint } int MRQ_SSRCore::strucStochRounding(const MRQ_MINLPProb &prob, const double *startSol, const double *lx, const double *ux, const double *lc, const double *uc, const int nI, const int *intVars, const int *reverseIntVars, const bool randomOrderToThreatClasses, const bool randomOrderInsideClasses, const double minimumProbToRound, const int print_level, const minlpproblem::MIP_BinSumConstrsIndsByClass &binSumConstrInds, MRQ_Random &random, int *auxInds1, int *auxInds2, unsigned int *auxConstrInds, double *auxConstrs1, double *auxConstrs2, double *outlx, double *outux, int &nVarsFixedByStochRounding, MRQ_SSR_VARIABLES_ADDITIONAL_FIXING_STRATEGY in_vars_additional_fixing_strategy, MRQ_SSR_PREPROCESSING_STRATEGY preprocStrategy, MRQ_Preprocessor *preprocessor, const minlpproblem::MIP_ConstraintsByColumnsStorager *ccstorager, const bool preprocessAfterVarRounding, const int contRelaxStrategy, optsolvers::OPT_LPSolver &nlpSolver, MRQ_BoundsUpdaterSolver *boundsUpdaterSolver) { const int m = prob.m; const int n = prob.n; int r, retCode; int *myAuxInds1 = nullptr, *myAuxInds2 = nullptr; double *myAuxConstrs1 = nullptr, *myAuxConstrs2; double *auxlc, *auxuc; //we use auxlc and auxuc to get results from preprocessor and store the redundant constraints... const int nConstrClassOrder = 8; //Test that: THE BALANCE FLOW CONSTRAINTS SHOULD BE THE LAST! int constrClassOrder[nConstrClassOrder] = {0, 3, 4, 8, 1, 2, 5, 6}; //order to threat classes constraints const MIP_SparseMatrix &A = prob.A; const bool updtByKnapacks = true; const bool preproc_quad = true; nVarsFixedByStochRounding = 0; if(lc == NULL) lc = prob.lc; if(uc == NULL) uc = prob.uc; if(!auxInds1) { MRQ_malloc(myAuxInds1, n); MRQ_IFMEMERRORGOTOLABEL(!myAuxInds1, retCode, termination); auxInds1 = myAuxInds1; } if(!auxInds2) { MRQ_malloc(myAuxInds2, n); MRQ_IFMEMERRORGOTOLABEL(!myAuxInds2, retCode, termination); auxInds2 = myAuxInds2; } if(!auxConstrs1) { MRQ_malloc(myAuxConstrs1, 2*m); MRQ_IFMEMERRORGOTOLABEL(!myAuxConstrs1, retCode, termination); myAuxConstrs2 = &myAuxConstrs1[m]; auxConstrs1 = myAuxConstrs1; auxConstrs2 = myAuxConstrs2; } auxlc = auxConstrs1; auxuc = auxConstrs2; MRQ_copyArray(m, lc, auxlc); MRQ_copyArray(m, uc, auxuc); MRQ_copyArray(n, lx, outlx); MRQ_copyArray(n, ux, outux); if(randomOrderToThreatClasses) { MRQ_shuffleArray(nConstrClassOrder, constrClassOrder, random ); } for(int j = 0; j < nConstrClassOrder; j++ ) { const int classNumber = constrClassOrder[j]; //treating constraints class 0 const unsigned int nClassc = binSumConstrInds.nClasses[ classNumber ]; const unsigned *classcInds = binSumConstrInds.classes[ classNumber ]; if(randomOrderInsideClasses && nClassc > 1) { //we put indices in a random order MRQ_copyArray( nClassc, classcInds, auxConstrInds ); MRQ_shuffleArray(nClassc, auxConstrInds, random); classcInds = auxConstrInds; } for(unsigned int k = 0; k < nClassc; k++) { auto cind = classcInds[k]; if( lc[cind] <= -MIP_INFINITY && uc[cind] >= MIP_INFINITY ) continue; //this constraint is disabled const int* acols = A[cind]; const double* avalues = A(cind); const unsigned int nel = A.getNumberOfElementsAtRow(cind); r = classXHandle(classNumber, nel, acols, avalues, lc[cind], uc[cind], random, auxInds1, auxInds2, outlx, outux, updtByKnapacks, &prob, uc, &binSumConstrInds, reverseIntVars, preprocessor, ccstorager); /*std::cout << "j: " << j << " k: " << k << " class: " << classNumber << " constraint: " << cind; std::cout << " return: " << r << "\n"; for(unsigned int i = 0; i < n; i++) { std::cout << "outlx["<<i<<"]: " << outlx[i] << " outux["<<i<<"]: " << outux[i] << " \t"; if( i%2 == 1 ) std::cout << "\n"; } //MRQ_getchar(); */ if(r != 0) { //we got a failure if(print_level > 10) { std::cout << MRQ_PREPRINT "Failure to satisfy constraint " << cind << "\n"; } retCode = MRQ_HEURISTIC_FAIL; goto termination; } auxlc[cind] = -MIP_INFINITY; //we do not need preprocess more this constraint auxuc[cind] = MIP_INFINITY; //we do not need preprocess more this constraint if(preprocStrategy == MRQ_SSRPS_AFTER_EACH_CONSTRAINT) { /*std::cout << "########################################\nAntes de preprocessar\n"; for(unsigned int i = 0; i < n; i++) { std::cout << "outlx["<<i<<"]: " << outlx[i] << " outux["<<i<<"]: " << outux[i] << " \t"; if( i%2 == 1 ) std::cout << "\n"; } */ #if 1 if(in_vars_additional_fixing_strategy == MRQ_SSR_VAFS_PREPROCESSING ) { bool updtVarBounds, updtConstrBounds; int r; r = preprocessor->preprocess(nel, acols, *ccstorager, preproc_quad, false, INFINITY, outlx, outux, updtVarBounds, updtConstrBounds, auxlc, auxuc, auxlc, auxuc); if(r == MIP_INFEASIBILITY) { //we got a failure if(print_level > 10) std::cout << MRQ_PREPRINT "Preprocessor detect infeasbility after constraint " << cind << " in SSR heuristic\n"; //MRQ_getchar(); retCode = MRQ_HEURISTIC_FAIL; goto termination; } /*if(updtVarBounds) { std::cout << MRQ_PREPRINT "Bounds updated by ssr preprocssing after handling constraint " << cind << "\n"; for(unsigned int i = 0; i < n; i++) { std::cout << "outlx["<<i<<"]: " << outlx[i] << " outux["<<i<<"]: " << outux[i] << " \t"; if( i%2 == 1 ) std::cout << "\n"; } MRQ_getchar(); }*/ } #endif #if 0 else if( in_vars_additional_fixing_strategy == MRQ_SSRVAFS_LINEAR_AUXILIAR_PROBLEM || in_vars_additional_fixing_strategy == MRQ_SSRVAFS_AUXILIAR_PROBLEM ) { bool infeas; r = boundsUpdaterSolver->calculateNewVarBounds(n, nI, intVars, outlx, outux, true, infeas ); MRQ_IFERRORGOTOLABEL(r, retCode, MRQ_NLP_SOLVER_ERROR, termination); if( infeas ) { //we got a failure if(print_level > 5) std::cout << MRQ_PREPRINT "Bounds updater detected infeasbility after constraint class " << classNumber << "\n"; retCode = MRQ_HEURISTIC_FAIL; goto termination; } } #endif /*std::cout << "########################################\nApós preprocessar\n"; for(unsigned int i = 0; i < n; i++) { std::cout << "outlx["<<i<<"]: " << outlx[i] << " outux["<<i<<"]: " << outux[i] << " \t"; if( i%2 == 1 ) std::cout << "\n"; } MRQ_getchar();*/ } } if(nClassc > 0 && preprocStrategy == MRQ_SSRPS_AFTER_EACH_CONSTRAINT_CLASS ) { if( in_vars_additional_fixing_strategy == MRQ_SSR_VAFS_PREPROCESSING ) { bool updtVarBounds, updtConstrBounds; int r; //r = preprocessor->preprocess(false, false, INFINITY, outlx, outux, updtVarBounds, updtConstrBounds); r = preprocessor->preprocess(0, nullptr, *ccstorager, preproc_quad, false, INFINITY, outlx, outux, updtVarBounds, updtConstrBounds, auxlc, auxuc, auxlc, auxuc); //here, we preprocess for all variables if(r == MIP_INFEASIBILITY) { //we got a failure if(print_level > 5) std::cout << MRQ_PREPRINT "Preprocessor detected infeasbility after constraint class " << classNumber << "\n"; retCode = MRQ_HEURISTIC_FAIL; goto termination; } } #if 0 else if( in_vars_additional_fixing_strategy == MRQ_SSRVAFS_LINEAR_AUXILIAR_PROBLEM || in_vars_additional_fixing_strategy == MRQ_SSRVAFS_AUXILIAR_PROBLEM ) { bool infeas; r = boundsUpdaterSolver->calculateNewVarBounds(n, nI, intVars, outlx, outux, true, infeas ); MRQ_IFERRORGOTOLABEL(r, retCode, MRQ_NLP_SOLVER_ERROR, termination); if( infeas ) { //we got a failure if(print_level > 5) std::cout << MRQ_PREPRINT "Bounds updater detected infeasbility after constraint class " << classNumber << "\n"; retCode = MRQ_HEURISTIC_FAIL; goto termination; } } #endif } } { r = fixAllNonFixedVarsByStochRounding(n, nI, intVars, startSol, minimumProbToRound, print_level, random, auxInds1, nVarsFixedByStochRounding, outlx, outux, preprocessAfterVarRounding ? preprocessor : nullptr, ccstorager, boundsUpdaterSolver, auxlc, auxuc, contRelaxStrategy, &nlpSolver); /*std::cout << "after stochastic rounding: \n"; for(unsigned int i = 0; i < n; i++) { std::cout << "outlx["<<i<<"]: " << outlx[i] << " outux["<<i<<"]: " << outux[i] << "\n"; } MRQ_getchar(); */ if( r != 0 ) { if( r != MRQ_HEURISTIC_FAIL ) { MRQ_PRINTERRORNUMBER(r); } retCode = r; goto termination; } } retCode = 0; termination: if(myAuxConstrs1) free(myAuxConstrs1); if(myAuxInds1) free(myAuxInds1); if(myAuxInds2) free(myAuxInds2); return retCode; } /* this function returns number of variable fixed in the variable nVarsFixed. This function tries fix variables in the array candidateVars aplying preprocessing after each fixing. If after fixing some variable, preprocessing fix any additional variables, this function abort the fixing returning the number of variabless fixed in the array candidateVars */ static inline int MRQ_tryFixRandomVariablesWithPreprocessWithouAditionalBoundsFixing(int nCandidateVars, int *candidateVars, int nVarsToFix, double valueToFix, double *lx, double *ux, MRQ_Random &random, MRQ_Preprocessor *preprocessor, const minlpproblem::MIP_ConstraintsByColumnsStorager *ccstorager, int &nVarsFixed, bool &additionalVarFixed) { bool updtVarBounds = false; bool updtConstrBounds; int r, randInd, col; nVarsFixed = 0; additionalVarFixed = false; while( nVarsFixed < nVarsToFix && !updtVarBounds ) { long unsigned int ntries = 0; do { if( ntries > 100lu*nCandidateVars ) { int w; //we tried a lot get a random variable to fix... so, we run in the order for(w = 0; w < nCandidateVars; w++) { col = candidateVars[w]; if( lx[col] != ux[col] ) break; } if( w == nCandidateVars ) { std::cout << "nCandidateVars: " << nCandidateVars << "\n"; for(w = 0; w < nCandidateVars; w++) std::cout << "var: " << candidateVars[w] << " lx: " << lx[candidateVars[w]] << " ux: " << ux[candidateVars[w]] << "\n" ; //if we reah this pointsomethig is wrong. we do not have variables to fix. Some counting is wrong, or maybe preprocessing is not flaging a variable bound changing assert(false); } } randInd = random.randInt(0, nCandidateVars-1); col = candidateVars[randInd]; ntries++; }while( lx[col] == ux[col] ); #if MRQ_DEBUG_MODE assert( lx[col] != ux[col] ); #endif lx[col] = ux[col] = valueToFix; nVarsFixed++; r = preprocessor->preprocess(1, &col, *ccstorager, true, false, INFINITY, lx, ux, updtVarBounds, updtConstrBounds); if(r != 0) { if(r !=MIP_INFEASIBILITY ) { MRQ_PRINTERRORNUMBER(r); } else { //we try fix variable in the other side if( lx[col] == 0.0 ) lx[col] = ux[col] = 1.0; else if( lx[col] == 1.0 ) lx[col] = ux[col] = 0.0; additionalVarFixed = true; return 0; } return MRQ_HEURISTIC_FAIL; } additionalVarFixed = additionalVarFixed || updtVarBounds; } return 0; } /* CLASS 0: x_{p_1} + x_{p_2} + x_{p_3} + ... + x_{p_k} = b * CLASS 3: x_{p_1} + x_{p_2} + x_{p_3} + ... + x_{p_k} <= b * CLASS 4: x_{p_1} + x_{p_2} + x_{p_3} + ... + x_{p_k} >= b * * Here, all variables have coefficient +1 in the constraints */ int MRQ_SSRCore2::class0_3_4Handle(const int sizea, const int *acols, const double *avalues, const double lc, const double uc, MRQ_Random &random, int *auxInds, double *lx, double *ux, const bool updateVarBoundsByKnapsackConstrs, const MRQ_MINLPProb *prob, const double *ubc, const minlpproblem::MIP_BinSumConstrsIndsByClass *binSumConstrInds, const int *reverseIntVars, MRQ_Preprocessor *preprocessor, const minlpproblem::MIP_ConstraintsByColumnsStorager *ccstorager ) { int *nonFixed = auxInds; #if MRQ_DEBUG_MODE assert(sizea > 0); #endif int nToFixAt1, nToFixAt0, nNonFixed; int nfixed0, nfixed1; do { double rhs = uc < MIP_INFINITY ? uc : lc; nToFixAt0 = 0; nToFixAt1 = 0; nNonFixed = 0; nfixed0 = 0; nfixed1 = 0; for(int j = 0; j < sizea; j++) { const int col = acols[j]; const double coef = avalues[j]; if( lx[col] == ux[col] ) { if( ux[col] != 0.0 ) rhs -= ux[col] * coef; } else { nonFixed[nNonFixed] = col; nNonFixed++; } } #if MRQ_DEBUG_MODE assert( MRQ_isIntegerDouble(rhs) ); #endif if( rhs < 0.0 && lc <= -MIP_INFINITY ) return MRQ_BAD_PARAMETER_VALUES; //we cannot satisfy this constraint if(lc == uc) { nToFixAt1 = rhs; if(nToFixAt1 == 0) nToFixAt0 = nNonFixed; //if we have nToFixAt1 > 0, we will fix the remanider variables to 0 after fix variables to 1. } else if(lc <= -MIP_INFINITY) { // we have a less than contsraint ... <= b. //nToFix = random.randInt(0, nToFix); #if MRQ_DEBUG_MODE assert(rhs >= 0.0); #endif //now, we let rhs variables free to be set by other constraints. We must fix all remainder variables to 0. So, we do not fix variables to 1, but we allow until rhs variables can be fix in the future letting those variable free. nToFixAt1 = 0; nToFixAt0 = MRQ_max<int>( nNonFixed - rhs, 0 ); } else { #if MRQ_DEBUG_MODE assert( uc >= MIP_INFINITY ); #endif // we have a greater than constraint ... >= b. // here, we do not fix variables to 0 nToFixAt1 = MRQ_max<int>(rhs, 0); } if(nToFixAt1 > 0) { if( nToFixAt1 > nNonFixed ) { //we cannot satisfy this constraint return MRQ_BAD_PARAMETER_VALUES; } /*else if( nToFixAt1 == nNonFixed ) { int r = fixFirstVarsAt1(nToFixAt1, sizea, acols, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if(r < nToFixAt1) return MRQ_BAD_PARAMETER_VALUES; } else */ { bool additionalVarFixed; //fixing variables to 1 int r = MRQ_tryFixRandomVariablesWithPreprocessWithouAditionalBoundsFixing(nNonFixed, nonFixed, nToFixAt1, 1.0, lx, ux, random, preprocessor, ccstorager, nfixed1, additionalVarFixed ); if( r != 0 ) { if(r != MRQ_HEURISTIC_FAIL) MRQ_PRINTERRORNUMBER(r); return r; } if( nfixed1 < nToFixAt1 || additionalVarFixed ) { continue; } else if( nfixed1 == nToFixAt1 && uc < MIP_INFINITY ) { //we have to fix all remainder nonfixed vars to zero. bool updtVarBounds, updtConstrBounds; fixAllNonFixedAt0(nNonFixed, nonFixed, lx, ux); //fixing the remainder variables to 0, but we do noc fix class 4, because if constraint is >= b, it is already satisfied. int r = preprocessor->preprocess(nNonFixed, nonFixed, *ccstorager, true, false, INFINITY, lx, ux, updtVarBounds, updtConstrBounds); if( r != 0 ) { if( r != MIP_INFEASIBILITY ) { MRQ_PRINTERRORNUMBER(r); return MRQ_UNDEFINED_ERROR; } return MRQ_HEURISTIC_FAIL; } } /*int r = fixRandomVarsAt1(random, nToFixAt1, nNonFixed, nonFixed, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if(r < nToFixAt1) return MRQ_BAD_PARAMETER_VALUES; //fixing the remainder variables to 0, but we do noc fix class 4, because if constraint is >= b, it is already satisfied. if( uc < MIP_INFINITY ) fixAllNonFixedAt0(sizea, acols, lx, ux);*/ } } //else { if( nToFixAt0 > 0 ) { /*if( nToFixAt0 == nNonFixed ) { fixFirstVarsAt0( nToFixAt0, sizea, acols, lx, ux); //I think we do not have to test returned value here. } else */ { bool additionalVarFixed; //fixing variables to 0 int r = MRQ_tryFixRandomVariablesWithPreprocessWithouAditionalBoundsFixing( nNonFixed, nonFixed, nToFixAt0, 0.0, lx, ux, random, preprocessor, ccstorager, nfixed0, additionalVarFixed ); if( r != 0 ) { if(r != MRQ_HEURISTIC_FAIL) MRQ_PRINTERRORNUMBER(r); return r; } if( nfixed0 < nToFixAt0 || additionalVarFixed) continue; //fixRandomVarsAt0(random, nToFixAt0, sizea, acols, lx, ux, reverseIntVars); } } } } while (nfixed0 < nToFixAt0 && nfixed1 < nToFixAt1 ); return 0; } /* * CLASS 1: x_{p_1} + x_{p_2} + ... + x_{p_k} - x_{n_1} = b * CLASS 2: x_{p_1} + x_{p_2} + ... + x_{p_k} - x_{n_1} <= b * CLASS 5: x_{p_1} + x_{p_2} + ... + x_{p_k} - x_{n_1} - x_{n_2} - ... - x_{n_q} = b * CLASS 6: x_{p_1} + x_{p_2} + ... + x_{p_k} - x_{n_1} - x_{n_2} - ... - x_{n_q} <= b */ int MRQ_SSRCore2::class1_2_5_6Handle( const int sizea, const int *acols, const double *avalues, const double lc, const double uc, MRQ_Random &random, int *auxInds1, int *auxInds2, double *lx, double *ux, const bool updateVarBoundsByKnapsackConstrs, const MRQ_MINLPProb *prob, const double *ubc, const minlpproblem::MIP_BinSumConstrsIndsByClass *binSumConstrInds, const int *reverseIntVars, MRQ_Preprocessor *preprocessor, const minlpproblem::MIP_ConstraintsByColumnsStorager *ccstorager ) { int *pCoefInds = auxInds1, *negCoefInds = auxInds2; int nPCoefInds, nNegCoefInds; int nFixPCoefs, nFixNegCoefs; int nVarsFixed1, nVarsNegCoef, nVarsPosCoef; int nPCoefFixed, nNegCoefFixed; double rhs; do { nPCoefInds = 0; nNegCoefInds = 0; nVarsFixed1 = 0; nVarsNegCoef = 0; nVarsPosCoef = 0; nPCoefFixed = 0; nNegCoefFixed = 0; rhs = uc; for(int j = 0; j < sizea; j++) { const int ind = acols[j]; const double val = avalues[j]; if( lx[ind] == ux[ind] ) { if( lx[ind] != 0.0 ) { rhs -= lx[ind] * val ; nVarsFixed1++; } } else { if( val == 1.0 ) { pCoefInds[ nPCoefInds ] = ind; nPCoefInds++; } else if( val == -1.0 ) { negCoefInds[ nNegCoefInds ] = ind; nNegCoefInds++; } #if MRQ_DEBUG_MODE else assert(false); //coeficient should be 1 or -1 #endif } #if MRQ_TRY_FIX_FLOW_CONSTRAINTS_AT_1 if( val > 0.0 ) nVarsPosCoef++; else if ( val < 0.0 ) nVarsNegCoef++; #endif } /*std::cout << "nPCoefInds: " << nPCoefInds << " nNegCoefInds: " << nNegCoefInds << " rhs: " << rhs << "\n"; for(unsigned int w = 0; w < MRQ_max(nPCoefInds, nNegCoefInds) ; w++) { if(w < nPCoefInds) std::cout << "\tpCoefInds["<<w<<"]:" << pCoefInds[w]; if(w < nNegCoefInds) std::cout << "\t\tnegCoefInds["<<w<<"]:" << negCoefInds[w]; std::cout << "\n"; }*/ #if MRQ_DEBUG_MODE assert(MRQ_isIntegerDouble(rhs)); #endif if( rhs == 0.0) { int maxFix = MRQ_min( nNegCoefInds, nPCoefInds ); nFixNegCoefs = random.randInt(0, maxFix); #if MRQ_TRY_FIX_FLOW_CONSTRAINTS_AT_1 if( nVarsPosCoef > 1 && nVarsNegCoef > 1 ) { /*we assume we have a flow constraint: x_{p_1} + x_{p_2} + x_{p_3} + ... + x_{p_k} - x_{n_1} - x_{n_2} - x_{n_3} - ... - x_{n_q} {=, <=} b */ if( nVarsFixed1 > 0 ) { /*since rhs is zero and nVarsFixed1 > 0, we assume constraints is already satisfied */ nFixNegCoefs = 0; } else { if(maxFix > 0) nFixNegCoefs = 1; //since we do not have variables fixed at 1, and that is a flow constraint, we try enforce the flow as 1, since the most pat of flux constraints is just to pass 1 by the flow. } } #endif if( lc == uc ) {//classes 1 and 5 //if( maxFix > 0) nFixNegCoefs = 1; //TODO: THIS IS A TEST REMOVE THAT nFixPCoefs = nFixNegCoefs; } else // we have a less than contsraint ... <= b. So, we can have more variables with coefficient -1 fixed at 1. We define a number possible lower to fix in nFixPCoefs { #if MRQ_DEBUG_MODE assert(lc <= -MIP_INFINITY); #endif //now, we let nFixNegCoefs free to be fixed by other contsraints... nFixPCoefs = nFixNegCoefs; //nFixPCoefs = random.randInt(0, nFixNegCoefs); } } else if( rhs > 0.0 ) { //we have more variables having coeficient -1 fixed at 1. So, we need to fix rhs more variables having coefficient 1 at 1 in equalities constraints. int maxFix = MRQ_min( nNegCoefInds, nPCoefInds - (int) rhs ); if( maxFix < 0 ) { //rhs is positive and we cannot fix any variable here. If constraint is <=, it is ok, constraint is guaranteed be satisfied. if( lc <= -MIP_INFINITY ) return 0; else { #if MRQ_DEBUG_MODE assert( lc == uc ); #endif return MRQ_BAD_PARAMETER_VALUES; //equality constraint. In this case, we cannot satisfy this constraint with current set of variables fiexd } } nFixNegCoefs = random.randInt(0, maxFix); #if MRQ_TRY_FIX_FLOW_CONSTRAINTS_AT_1 if( rhs == 1.0 ) { if(nVarsPosCoef > 1 && nVarsNegCoef > 1) { /*we assume we have a flow constraint: x_{p_1} + x_{p_2} + x_{p_3} + ... + x_{p_k} - x_{n_1} - x_{n_2} - x_{n_3} - ... - x_{n_q} {=, <=} b */ //we do not let more variables having negative coefs being fixed at 1, since the most part of flow constraints has 1 as flow nFixNegCoefs = 0; } } #endif if( lc == uc ) { nFixPCoefs = nFixNegCoefs + rhs; } else { // we have a less than contsraint ... <= b. So, we can have more variables with coefficient -1 fixed at 1. We define a number possible lower to fix in nFixPCoefs #if MRQ_DEBUG_MODE assert(lc <= -MIP_INFINITY); #endif //nFixPCoefs = random.randInt(0, nFixNegCoefs + rhs); //now, we let nFixNegCoefs free to be fixed by other contsraints... nFixPCoefs = nFixNegCoefs + rhs; } } else //rhs < 0 { //we have more variables having coeficient 1 fixed at 1. So, we need to fix rhs more variables having coefficient -1 at 1. int maxFix = MRQ_min( nNegCoefInds + (int) rhs, nPCoefInds ); //remember: here, rhs is negative, so we have to sum instead of subtrate, since -rhs has the number of variables having positive coefs above the numver of variables having negative coefs. if( maxFix < 0 ) return MRQ_BAD_PARAMETER_VALUES; //we cannot satisfy this constraint with currentset of variables fiexd nFixPCoefs = random.randInt(0, maxFix); #if MRQ_TRY_FIX_FLOW_CONSTRAINTS_AT_1 if( rhs == -1.0 ) { if(nVarsPosCoef > 1 && nVarsNegCoef > 1) { /*we assume we have a flow constraint: x_{p_1} + x_{p_2} + x_{p_3} + ... + x_{p_k} - x_{n_1} - x_{n_2} - x_{n_3} - ... - x_{n_q} {=, <=} b */ //we do not let more variables having positive coefs being fixed at 1, since the most part of flow constraints has 1 as flow nFixPCoefs = 0; } } #endif if( lc == uc ) { nFixNegCoefs = nFixPCoefs - rhs; //here, rhs is negative, so we have to sum instead of subtrate } else { // we have a less than constraint ... <= b. So, we can have more variables with coefficient 1 fixed at 1. We define a number possible lower to fix in nFixPCoefs #if MRQ_DEBUG_MODE assert(lc <= -MIP_INFINITY); assert(nFixPCoefs + rhs <= nNegCoefInds); #endif //nFixNegCoefs = random.randInt(nFixPCoefs - rhs, nNegCoefInds); //remember: here, rhs is negative //now, we let nFixNegCoefs free to be fixed by other constraints... nFixNegCoefs = nFixPCoefs - rhs; //remember: here, rhs is negative } } #if MRQ_DEBUG_MODE assert( nFixPCoefs >= 0 ); assert( nFixNegCoefs >= 0 ); #endif /*if( nFixPCoefs == nPCoefInds ) { if( lc == uc ) //equality constraints { int r = fixFirstVarsAt1(nFixPCoefs, nPCoefInds, pCoefInds, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if( r < nFixPCoefs) return MRQ_BAD_PARAMETER_VALUES; } else { //at less than constraints ( <= ), we dot not fix variables having positive coefficients at 1 #if MRQ_DEBUG_MODE assert( lc <= -MIP_INFINITY ); #endif } } else */ { if( lc == uc ) { bool additionalVarFixed; bool updtVarBounds, updtConstrBounds; //fixing variables at 1 int r = MRQ_tryFixRandomVariablesWithPreprocessWithouAditionalBoundsFixing(nPCoefInds, pCoefInds, nFixPCoefs, 1.0, lx, ux, random, preprocessor, ccstorager, nPCoefFixed, additionalVarFixed ); if( r != 0 ) { if(r != MRQ_HEURISTIC_FAIL) MRQ_PRINTERRORNUMBER(r); return r; } if( nPCoefFixed < nFixPCoefs || additionalVarFixed ) continue; /*int r = fixRandomVarsAt1(random, nFixPCoefs, nPCoefInds, pCoefInds, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if( r < nFixPCoefs ) return MRQ_BAD_PARAMETER_VALUES; */ fixAllNonFixedAt0(nPCoefInds, pCoefInds, lx, ux); r = preprocessor->preprocess( nPCoefInds, pCoefInds, *ccstorager, true, false, INFINITY, lx, ux, updtVarBounds, updtConstrBounds ); if( r != 0 ) { if( r != MIP_INFEASIBILITY ) { MRQ_PRINTERRORNUMBER(r); return MRQ_UNDEFINED_ERROR; } return MRQ_HEURISTIC_FAIL; } if(updtVarBounds) continue; } else { //at less than constraints ( <= ), we dot not fix variables having positive coefficients at 1. We only fix remainder variable to 0 and let nFixPCoefs variables free to be fixed by other constraints. #if MRQ_DEBUG_MODE assert( lc <= -MIP_INFINITY ); #endif bool additionalVarFixed; int nfixed; int nFixTo0 = nPCoefInds - nFixPCoefs; //remainder coefficients to be fixed on zero. So, at most, nFixPCoefs variables could be fixed at 1 in the future //fixing variables at 0 int r = MRQ_tryFixRandomVariablesWithPreprocessWithouAditionalBoundsFixing( nPCoefInds, pCoefInds, nFixTo0, 0.0, lx, ux, random, preprocessor, ccstorager, nfixed, additionalVarFixed); if( r != 0 ) { if(r != MRQ_HEURISTIC_FAIL) MRQ_PRINTERRORNUMBER(r); return r; } if( nfixed < nFixTo0 || additionalVarFixed) continue; //if we reach here, we consider we fix variables to 1 to let the do while loop ends... nPCoefFixed = nFixPCoefs; /*int r = fixRandomVarsAt0( random, nFixTo0, nPCoefInds, pCoefInds, lx, ux, reverseIntVars ); if( r != nFixTo0 ) return MRQ_UNDEFINED_ERROR;*/ } } /*if( nFixNegCoefs == nNegCoefInds ) { int r = fixFirstVarsAt1(nFixNegCoefs, nNegCoefInds, negCoefInds, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if( r < nFixNegCoefs ) return MRQ_BAD_PARAMETER_VALUES; } else */ { //fixing vars to 1 bool additionalVarFixed; int r = MRQ_tryFixRandomVariablesWithPreprocessWithouAditionalBoundsFixing( nNegCoefInds, negCoefInds, nFixNegCoefs, 1.0, lx, ux, random, preprocessor, ccstorager, nNegCoefFixed, additionalVarFixed ); if( r != 0 ) { if(r != MRQ_HEURISTIC_FAIL) MRQ_PRINTERRORNUMBER(r); return r; } if( nNegCoefFixed < nFixNegCoefs || additionalVarFixed ) continue; /*int r = fixRandomVarsAt1(random, nFixNegCoefs, nNegCoefInds, negCoefInds, lx, ux, updateVarBoundsByKnapsackConstrs, prob, ubc, binSumConstrInds, reverseIntVars); if( r < nFixNegCoefs ) return MRQ_BAD_PARAMETER_VALUES;*/ //now, for <= constraints, we do not fix variables having negative coefficient to 0. We let them free to possibly be fixed by other constraints' handlres if(lc == uc) { bool updtVarBounds, updtConstrBounds; fixAllNonFixedAt0(nNegCoefInds, negCoefInds, lx, ux); r = preprocessor->preprocess( nNegCoefInds, negCoefInds, *ccstorager, true, false, INFINITY, lx, ux, updtVarBounds, updtConstrBounds ); if( r != 0 ) { if( r != MIP_INFEASIBILITY ) { MRQ_PRINTERRORNUMBER(r); return MRQ_UNDEFINED_ERROR; } return MRQ_HEURISTIC_FAIL; } } } }while( nPCoefFixed < nFixPCoefs || nNegCoefFixed < nFixNegCoefs ); return 0; } MRQ_SSRoundingExecutor::MRQ_SSRoundingExecutor() { resetParameters(); resetOutput(); auxConstrInds = nullptr; auxVarInds1 = nullptr; auxVarInds2 = nullptr; auxVarValues1 = nullptr; roundedLx = nullptr; roundedUx = nullptr; auxConstrs1 = nullptr; auxConstrs2 = nullptr; boundsUpdaterSolver = nullptr; subProb = nullptr; } MRQ_SSRoundingExecutor::~MRQ_SSRoundingExecutor() { deallocate(); } void MRQ_SSRoundingExecutor::resetOutput() { //out_alg = nullptr; out_vars_fixed_by_stoch_rounding = false; out_number_of_main_iterations = 0; out_number_of_improvments = 0; out_local_search_alg_code = MRQ_UNDEFINED_ALG; out_cpu_time_at_nlp_integer_fixed_sol = NAN; out_obj_at_nlp_integer_fixed_sol = NAN; } void MRQ_SSRoundingExecutor::resetParameters() { //in_preprocess_after_handling_constraints = false; in_preprocess_after_variable_rounding = true; in_random_order_to_threat_classes = false; in_random_order_to_threat_constraints_in_each_class = true; in_solve_minlp_as_local_search = true; in_stop_local_search_solving_on_first_improvment_solution = false; in_max_number_of_main_iterations = 1000; in_max_number_of_improvments = 10; in_print_level = 4; in_milp_solver = MRQ_getDefaultMILPSolverCode(); in_nlp_solver = MRQ_getDefaultNLPSolverCode(); in_neighborhood_strategy = MRQ_SNS_LOCAL_BRANCHING_NEIGHBORHOOD; in_preprocessing_point_strategy = MRQ_SSRPS_AFTER_EACH_CONSTRAINT; in_additional_vars_fixing_strategy = MRQ_SSR_VAFS_PREPROCESSING; in_rounding_var_bounds_updt_strategy = MRQ_SSR_VBUS_NO_UPDATING; in_cont_relax_strategy_to_stoch_rounding = MRQ_SSR_CRSSR_ONLY_BEFORE_STARTING; in_absolute_feasibility_tol = 1e-3; in_relative_feasibility_tol = 1e-6; in_integer_tol = 1e-3; in_integer_neighborhood_factor = 0.3; in_continuous_neighborhood_factor = 0.1; in_relative_convergence_tol_to_local_search = 0.2; in_max_cpu_time = INFINITY; in_max_time = INFINITY; in_min_probability_to_round = 0.5; in_local_search_algorithm = MRQ_UNDEFINED_ALG; in_milp_solver_params = nullptr; in_nlp_solver_params = nullptr; in_alg_params = nullptr; in_alg = nullptr; } int MRQ_SSRoundingExecutor::allocateAuxMemory(const unsigned int n, const unsigned int m, const unsigned int sizeAuxConstrIndex) { MRQ_malloc(auxConstrInds, sizeAuxConstrIndex); MRQ_malloc(auxVarInds1, n); MRQ_malloc(auxVarInds2, n); MRQ_malloc(auxVarValues1, n); MRQ_malloc(roundedLx, n); MRQ_malloc(roundedUx, n); MRQ_malloc(auxConstrs1, m); MRQ_malloc(auxConstrs2, m); MRQ_IFMEMERRORRETURN( !auxConstrInds || !auxVarInds1 || !auxVarInds2 || !auxVarValues1 || !roundedLx || !roundedUx || !auxConstrs1 || !auxConstrs2 ); return 0; } void MRQ_SSRoundingExecutor::deallocate() { MRQ_secFree(auxConstrInds); MRQ_secFree(auxVarInds1); MRQ_secFree(auxVarInds2); MRQ_secFree(auxVarValues1); MRQ_secFree(roundedLx); MRQ_secFree(roundedUx); MRQ_secFree(auxConstrs1); MRQ_secFree(auxConstrs2); MRQ_secDelete(subProb); MRQ_secDelete(boundsUpdaterSolver); } int MRQ_SSRoundingExecutor::run(const MRQ_MINLPProb &prob, const minlpproblem::MIP_BinSumConstrsIndsByClass &binSumConstrInds, const minlpproblem::MIP_ConstraintsByColumnsStorager *ccstorager, MRQ_Random &random, optsolvers::OPT_LPSolver &nlpSolver, unsigned int thnumber, unsigned int nThreads, double insideSolverMaxTime, const double *lc, const double *uc, double *lx, double *ux, const int nI, const int *intVars, const int *reverseIntVars, const int nC, const int *contVars, const double *relaxSol, int &algReturnCode, double &outObj, double *outSol) { const double timeStart = MRQ_getTime(); const clock_t clockStart = clock(); const int n = prob.n; const int m = prob.m; int r, myRetCode = MRQ_UNDEFINED_ERROR; int nVarsFixedByStochRounding; unsigned int j; MRQ_SSRCore2 core; MRQ_Algorithm *pAlg, *myAlg = nullptr; MRQ_Preprocessor *preprocessor = nullptr; algReturnCode = MRQ_UNDEFINED_ERROR; outObj = INFINITY; resetOutput(); if( in_additional_vars_fixing_strategy == MRQ_SSR_VAFS_PREPROCESSING ) { if(in_preprocessing_point_strategy != MRQ_SSRPS_NO_PREPROCESSING) { preprocessor = new (std::nothrow) MRQ_Preprocessor(&prob); MRQ_IFMEMERRORGOTOLABEL(!preprocessor, myRetCode, termination); r = preprocessor->allocateMemory(n, m); MRQ_IFMEMERRORGOTOLABEL(r, myRetCode, termination); } } if( in_rounding_var_bounds_updt_strategy == MRQ_SSR_VBUS_LINEAR_AUXILIAR_PROBLEM || in_rounding_var_bounds_updt_strategy == MRQ_SSR_VBUS_AUXILIAR_PROBLEM ) { if( !boundsUpdaterSolver ) { const bool setLinearProblem = in_rounding_var_bounds_updt_strategy == MRQ_SSR_VBUS_LINEAR_AUXILIAR_PROBLEM; const int solverCode = in_rounding_var_bounds_updt_strategy == MRQ_SSR_VBUS_LINEAR_AUXILIAR_PROBLEM || prob.getProblemType() == MIP_PT_MILP ? (int) in_milp_solver : (int) in_nlp_solver ; boundsUpdaterSolver = new (std::nothrow) MRQ_BoundsUpdaterSolver(); MRQ_IFMEMERRORGOTOLABEL( !boundsUpdaterSolver, myRetCode, termination ); //NOTE: by now, we are not recieving solver parameter to set r = boundsUpdaterSolver->buildProblem( solverCode, prob, setLinearProblem, false, NAN, thnumber, 1, NULL, NULL, NULL, false ); MRQ_IFMEMERRORGOTOLABEL(r, myRetCode, termination); } } if(!auxVarInds1) { unsigned int maxSizeMClasses = 0; for(unsigned int k = 0; k < binSumConstrInds.nBinSumConstrClasses; k++) { if( binSumConstrInds.nClasses[k] > maxSizeMClasses ) maxSizeMClasses = binSumConstrInds.nClasses[k]; } r = allocateAuxMemory(n, m, maxSizeMClasses); MRQ_IFERRORGOTOLABEL(r, myRetCode, r, termination); } for(out_number_of_main_iterations = 1; out_number_of_main_iterations <= in_max_number_of_main_iterations; out_number_of_main_iterations++) { //printf("iter: %u\n", out_number_of_main_iterations); int ret = core.strucStochRounding(prob, relaxSol, lx, ux, lc, uc, nI, intVars, reverseIntVars, in_random_order_to_threat_classes, in_random_order_to_threat_constraints_in_each_class, in_min_probability_to_round, in_print_level, binSumConstrInds, random, auxVarInds1, auxVarInds2, auxConstrInds, auxConstrs1, auxConstrs2, roundedLx, roundedUx, nVarsFixedByStochRounding, in_additional_vars_fixing_strategy, in_preprocessing_point_strategy, preprocessor, ccstorager, in_preprocess_after_variable_rounding, in_cont_relax_strategy_to_stoch_rounding, nlpSolver, boundsUpdaterSolver ); if( in_max_cpu_time < INFINITY ) { const double cpuTime = MRQ_calcCPUTtime(clockStart, clock()); if( cpuTime >= in_max_cpu_time) { myRetCode = MRQ_HEURISTIC_FAIL; break; } } if( in_max_time < INFINITY ) { const double wallTime = MRQ_getTime() - timeStart; if( wallTime >= in_max_time ) { myRetCode = MRQ_HEURISTIC_FAIL; //we return heuristic fail because here we do not have feasible solution break; } } if( ret == MRQ_HEURISTIC_FAIL ) //if we get heuristic failure, we just try again in another iteration. continue; MRQ_IFERRORGOTOLABEL(ret, myRetCode, MRQ_HEURISTIC_FAIL, termination); out_vars_fixed_by_stoch_rounding = nVarsFixedByStochRounding > 0; if( nC == 0) { bool feasSol = false; prob.isFeasibleToConstraints(thnumber, roundedLx, true, nullptr, in_absolute_feasibility_tol, in_relative_feasibility_tol, feasSol); if( feasSol ) { r = prob.objEval(thnumber, prob.hasNLConstraints(), roundedLx, outObj); MRQ_IFERRORGOTOLABEL(r, myRetCode, MRQ_CALLBACK_FUNCTION_ERROR, termination); out_obj_at_nlp_integer_fixed_sol = outObj; MRQ_copyArray(n, (const double *) roundedLx, outSol); out_cpu_time_at_nlp_integer_fixed_sol = MRQ_calcCPUTtime(clockStart); break; } } else { //MRQ_getchar(); r = MRQ_fixIntVarsOnSolByList(nI, intVars, roundedLx, nlpSolver); MRQ_IFERRORGOTOLABEL(r, myRetCode, r, termination); //do not store contsraints value and dual solution because we can use ssr inside a branch-and-bound procedure, and so, we would have to backup the values from continuous relaxation nlpSolver.solve(false, true, false, false); r = MRQ_unfixIntegerVarsByList(nI, intVars, lx, ux, nlpSolver); //std::cout << "nlp local search - ret: " << nlpSolver.retCode << " obj: " << nlpSolver.objValue << "\n"; /*for(unsigned int w = 0; w < n; w++) std::cout << "\tsol["<<w<<"]: " << nlpSolver.sol[w] << "\n"; */ //MRQ_getchar(); if( nlpSolver.feasSol ) { MRQ_copyArray( n, nlpSolver.sol, outSol ); outObj = nlpSolver.objValue; out_obj_at_nlp_integer_fixed_sol = nlpSolver.objValue; out_cpu_time_at_nlp_integer_fixed_sol = MRQ_calcCPUTtime(clockStart); break; } } } if( !std::isinf(outObj) && in_solve_minlp_as_local_search ) { const int neighConstrIndex = prob.m; double *auxValues = auxVarValues1; double *nlx = roundedLx, *nux = roundedUx; if(in_neighborhood_strategy == MRQ_SNS_ORIGINAL) { MRQ_PRINTERRORMSG( MRQ_STRPARINTVALUE(MRQ_SNS_ORIGINAL) " cannot be used like neighborhood strategy in SSR. Changing to " MRQ_STRPARINTVALUE(MRQ_SNS_LOCAL_BRANCHING_NEIGHBORHOOD) "!"); in_neighborhood_strategy = MRQ_SNS_LOCAL_BRANCHING_NEIGHBORHOOD; } if(!subProb) { const int nnewConstraints = (in_neighborhood_strategy == MRQ_SNS_EUCLIDEAN_NEIGHBORHOOD && nI < n) ? 2 : 1; //to set the continuous euclidean neighborhood, we must have at least one continuous var subProb = new (std::nothrow) MRQ_MINLPProb; MRQ_IFMEMERRORGOTOLABEL(!subProb, myRetCode, termination); r = subProb->copyProblemFrom(prob); MRQ_IFERRORGOTOLABEL(r, myRetCode, MRQ_MEMORY_ERROR, termination); r = subProb->addConstraints(nnewConstraints); MRQ_IFERRORGOTOLABEL(r, myRetCode, MRQ_MEMORY_ERROR, termination); } if(in_alg) { pAlg = in_alg; } else { if(in_local_search_algorithm == MRQ_SSR_HEUR_ALG) in_local_search_algorithm = MRQ_UNDEFINED_ALG; //we would have a infinite recursion... myAlg = MRQ_newAlgorithm(in_local_search_algorithm, subProb->getNumberOfNLEqualityConstraints() ); MRQ_IFMEMERRORGOTOLABEL(!myAlg, myRetCode, termination); if(in_alg_params) myAlg->setParameters(*in_alg_params); pAlg = myAlg; } out_local_search_alg_code = pAlg->out_algorithm; pAlg->in_number_of_threads = nThreads; pAlg->in_print_level = in_print_level - 2; pAlg->in_milp_solver = in_milp_solver; pAlg->in_nlp_solver = in_nlp_solver; if(in_print_level > 2) printf( MRQ_PREPRINT "best objective: %0.10lf\n", outObj); pAlg->in_relative_convergence_tol = in_relative_convergence_tol_to_local_search; for(j = 0; j < in_max_number_of_improvments; j++) { r = MRQ_setSubproblemNeighborhood(lx, ux, outSol, nI, intVars, nC, contVars, in_neighborhood_strategy, in_integer_neighborhood_factor, in_continuous_neighborhood_factor, in_integer_tol, neighConstrIndex, auxVarInds1, auxValues, subProb, nlx, nux); MRQ_IFERRORGOTOLABEL(r, myRetCode, r, termination); if( !std::isinf(in_max_cpu_time) ) pAlg->in_max_cpu_time = in_max_cpu_time - MRQ_calcCPUTtime(clockStart); if( !std::isinf(in_max_time) ) pAlg->in_max_time = in_max_time - (MRQ_getTime() - timeStart); pAlg->in_upper_bound = outObj; if( pAlg->isLinearApproximationAlgorithm() ) { MRQ_LinearApproxAlgorithm *pLA = (MRQ_LinearApproxAlgorithm*) pAlg; pLA->deletePointsToLinearisation(); r = pLA->addPointsToLinearisation(1, n, &outSol); MRQ_IFERRORGOTOLABEL(r, myRetCode, r, termination); } else { r = pAlg->setInitialSolution(n, outSol); MRQ_IFERRORGOTOLABEL(r, myRetCode, r, termination); } if( in_stop_local_search_solving_on_first_improvment_solution ) { //here, we imposing a solution at least 10% better to stop on first improvment pAlg->in_lower_bound = outObj - 0.1*MRQ_abs(outObj) - 0.1; } /*std::cout << "in_integer_neighborhood_factor: " << in_integer_neighborhood_factor << " n diff: " << (int) ceil(in_integer_neighborhood_factor*n) << "\n"; for(int w = 0; w < n; w++) std:: cout << "sol["<<w<<"]: " << outSol[w] << "\n"; subProb->print();*/ MRQ_insideRun(pAlg, *subProb, in_milp_solver_params, in_nlp_solver_params, thnumber, insideSolverMaxTime, nlx, nux); if(in_print_level > 2) printf( MRQ_PREPRINT "Local search subproblem %d - return code: %d best objective: %0.10lf\n", j+1, pAlg->out_return_code, pAlg->out_best_obj); if(pAlg->out_feasible_solution && pAlg->out_best_obj < outObj) { outObj = pAlg->out_best_obj; MRQ_copyArray(n, pAlg->out_best_sol, outSol ); out_number_of_improvments++; } else { break; } if( !std::isinf(in_max_cpu_time) ) { if( MRQ_calcCPUTtime(clockStart) >= in_max_cpu_time ) { //algReturnCode = MRQ_MAX_TIME_STOP; //this will be overwritten, but ok... break; } } if( !std::isinf(in_max_time) ) { if( MRQ_getTime() - timeStart >= in_max_time ) break; } } } termination: if( std::isinf(outObj) ) algReturnCode = MRQ_HEURISTIC_FAIL; else algReturnCode = MRQ_HEURISTIC_SUCCESS; if(myAlg) delete myAlg; if(preprocessor) delete preprocessor; return myRetCode; } MRQ_StructuredStochasticRounding:: MRQ_StructuredStochasticRounding() { resetParameters(); resetOutput(); out_algorithm = MRQ_SSR_HEUR_ALG; } MRQ_StructuredStochasticRounding:: ~MRQ_StructuredStochasticRounding() { } int MRQ_StructuredStochasticRounding:: checkAlgorithmRequirements( MRQ_MINLPProb &prob, const double *lx, const double *ux) { if( !MRQ_isBinarieProblemAtRegion(prob, lx, ux) ) { if( in_print_level > 4 ) MRQ_PRINTERRORMSG("We are sorry, but Sturctured Stochastic Rounding only can be applyed to Binary Problems."); return MRQ_ALG_NOT_APPLICABLE; } return 0; } void MRQ_StructuredStochasticRounding:: printParameters( std::ostream &out) const { char strValue[100]; MRQ_Heuristic::printParameters(out); out << "\n" //MRQ_STRFFATT(in_preprocess_after_handling_constraints) << "\n" MRQ_STRFFATT(in_preprocess_after_variable_rounding) << "\n" MRQ_STRFFATT(in_random_order_to_threat_classes) << "\n" MRQ_STRFFATT(in_random_order_to_threat_constraints_in_each_class) << "\n" MRQ_STRFFATT(in_solve_continuous_relaxation) << "\n" MRQ_STRFFATT(in_solve_minlp_as_local_search) << "\n" MRQ_STRFFATT(in_stop_local_search_solving_on_first_improvment_solution) << "\n" MRQ_STRFFATT(in_max_number_of_improvments) << "\n" MRQ_STRFFATT(in_integer_neighborhood_factor) << "\n" MRQ_STRFFATT(in_continuous_neighborhood_factor) << "\n" MRQ_STRFFATT(in_relative_convergence_tol_to_local_search) << "\n" MRQ_STRFFATT(in_min_probability_to_round) << "\n" ; MRQ_enumToStr(in_neighborhood_strategy, strValue); out << MRQ_STRPARINTVALUE(in_neighborhood_strategy) " " << strValue << "\n"; MRQ_enumToStr(in_preprocessing_point_strategy, strValue); out << MRQ_STRPARINTVALUE(in_preprocessing_point_strategy) " " << strValue << "\n"; MRQ_enumToStr(in_additional_vars_fixing_strategy, strValue); out << MRQ_STRPARINTVALUE(in_additional_vars_fixing_strategy) " " << strValue << "\n"; MRQ_enumToStr(in_rounding_var_bounds_updt_strategy, strValue); out << MRQ_STRPARINTVALUE(in_rounding_var_bounds_updt_strategy) " " << strValue << "\n"; MRQ_enumToStr(in_cont_relax_strategy_to_stoch_rounding, strValue); out << MRQ_STRPARINTVALUE(in_cont_relax_strategy_to_stoch_rounding) " " << strValue << "\n"; MRQ_enumToStr(in_local_search_algorithm, strValue); out << MRQ_STRPARINTVALUE(in_local_search_algorithm) " " << strValue << "\n"; } void MRQ_StructuredStochasticRounding:: resetParameters() { MRQ_Heuristic::resetParameters(); //in_preprocess_after_handling_constraints = false; in_preprocess_after_variable_rounding = true; in_random_order_to_threat_classes = false; in_random_order_to_threat_constraints_in_each_class = true; in_solve_continuous_relaxation = true; in_solve_minlp_as_local_search = true; in_stop_local_search_solving_on_first_improvment_solution = false; in_max_iterations = 1000; in_max_number_of_improvments = 10; in_print_level = 4; in_milp_solver = MRQ_getDefaultMILPSolverCode(); in_nlp_solver = MRQ_getDefaultNLPSolverCode(); in_neighborhood_strategy = MRQ_SNS_LOCAL_BRANCHING_NEIGHBORHOOD; in_preprocessing_point_strategy = MRQ_SSRPS_AFTER_EACH_CONSTRAINT; in_additional_vars_fixing_strategy = MRQ_SSR_VAFS_PREPROCESSING; in_rounding_var_bounds_updt_strategy = MRQ_SSR_VBUS_NO_UPDATING; in_cont_relax_strategy_to_stoch_rounding = MRQ_SSR_CRSSR_ONLY_BEFORE_STARTING; in_integer_tol = 1e-3; in_integer_neighborhood_factor = 0.3; in_continuous_neighborhood_factor = 0.1; in_relative_convergence_tol_to_local_search = 0.2; in_min_probability_to_round = 0.1; in_max_cpu_time = INFINITY; in_max_time = INFINITY; in_local_search_algorithm = MRQ_UNDEFINED_ALG; in_alg_params = nullptr; in_alg = nullptr; } void MRQ_StructuredStochasticRounding:: resetOutput() { out_vars_fixed_by_stoch_rounding = false; out_cpu_time_at_nlp_integer_fixed_sol = NAN; out_obj_at_nlp_integer_fixed_sol = NAN; out_obj_at_first_sol = NAN; out_local_search_alg_code = MRQ_UNDEFINED_ALG; MRQ_Heuristic::resetOutput(); } int MRQ_StructuredStochasticRounding:: setIntegerParameter( const char *name, const long int value) { int ret = MRQ_Heuristic::setIntegerParameter(name, value); if( ret == 0 ) return 0; ret = 0; if( MRQ_setAtt<bool>( MRQ_STRATT(in_preprocess_after_variable_rounding), name, value ) == 0 ); else if( MRQ_setAtt<bool>( MRQ_STRATT(in_random_order_to_threat_classes), name, value ) == 0 ); else if( MRQ_setAtt<bool>( MRQ_STRATT(in_random_order_to_threat_constraints_in_each_class), name, value ) == 0 ); else if( MRQ_setAtt<bool>( MRQ_STRATT(in_solve_continuous_relaxation), name, value ) == 0 ); else if( MRQ_setAtt<bool>( MRQ_STRATT(in_solve_minlp_as_local_search), name, value ) == 0 ); else if( MRQ_setAtt<bool>( MRQ_STRATT(in_stop_local_search_solving_on_first_improvment_solution), name, value ) == 0 ); else if( MRQ_setAtt<unsigned int>( MRQ_STRATT(in_max_number_of_improvments), name, value) == 0 ); else ret = MRQ_NAME_ERROR; return ret; } int MRQ_StructuredStochasticRounding:: setDoubleParameter( const char *name, const double value) { int ret = MRQ_Algorithm::setDoubleParameter(name, value); if( ret == 0 ) return 0; ret = 0; if( MRQ_setAtt( MRQ_STRATT(in_integer_neighborhood_factor), name, value ) == 0 ); else if( MRQ_setAtt( MRQ_STRATT(in_continuous_neighborhood_factor), name, value ) == 0 ); else if( MRQ_setAtt( MRQ_STRATT(in_relative_convergence_tol_to_local_search), name, value ) == 0 ); else if( MRQ_setAtt( MRQ_STRATT(in_min_probability_to_round), name, value ) == 0 ); else ret = MRQ_NAME_ERROR; return ret; } int MRQ_StructuredStochasticRounding:: setStringParameter( const char *name, const char *value) { int r; int ret = MRQ_Algorithm::setStringParameter(name, value); if( ret == 0 ) return 0; ret = 0; if( (r = MRQ_setStrAtt( MRQ_STRATT(in_neighborhood_strategy), name, value ) ) >= 0 ) ret = r == 0 ? 0 : MRQ_VALUE_ERROR; else if( (r = MRQ_setStrAtt( MRQ_STRATT(in_preprocessing_point_strategy), name, value ) ) >= 0 ) ret = r == 0 ? 0 : MRQ_VALUE_ERROR; else if( (r = MRQ_setStrAtt( MRQ_STRATT(in_additional_vars_fixing_strategy), name, value ) ) >= 0 ) ret = r == 0 ? 0 : MRQ_VALUE_ERROR; else if( (r = MRQ_setStrAtt( MRQ_STRATT(in_rounding_var_bounds_updt_strategy), name, value ) ) >= 0 ) ret = r == 0 ? 0 : MRQ_VALUE_ERROR; else if( (r = MRQ_setStrAtt( MRQ_STRATT(in_cont_relax_strategy_to_stoch_rounding), name, value ) ) >= 0 ) ret = r == 0 ? 0 : MRQ_VALUE_ERROR; else if( (r = MRQ_setStrAtt( MRQ_STRATT(in_local_search_algorithm), name, value ) ) >= 0 ) ret = r == 0 ? 0 : MRQ_VALUE_ERROR; else ret = MRQ_NAME_ERROR; return ret; } int MRQ_StructuredStochasticRounding:: run(MRQ_MINLPProb &prob, MRQ_GeneralSolverParams* milpSolverParams, MRQ_GeneralSolverParams* nlpSolverParams ) { return run(prob, milpSolverParams, nlpSolverParams, nullptr); } int MRQ_StructuredStochasticRounding:: run(MRQ_MINLPProb &prob, MRQ_GeneralSolverParams* milpSolverParams, MRQ_GeneralSolverParams* nlpSolverParams, MRQ_GeneralSolverParams* algParams) { const double timeStart = MRQ_getTime(); const clock_t clockStart = clock(); const int n = prob.n; //const int m = prob.m; int nI, nC; double outObj; double *plc = NULL, *puc = NULL; // do not free puc, because we take advantage the malloc of plc. We just put NULL because we should sinalize if there is new bounds or no to other procedures like MRQ_BinSumConstrs::calculateIndices when we do not preprocess... int *intVars = NULL, *reverseIntVars = NULL; int *contVars; double *constrValues = NULL; double *initSol = NULL; int r, algRetCod; unsigned int nthreads; //double NLPCpuTime, NLPClockTime; MIP_BinSumConstrsIndsByClass binSumConstrs; MRQ_SSRoundingExecutor ssrExecutor; MRQ_Random random; double *lx = run_by_inside ? nlx : prob.lx; double *ux = run_by_inside ? nux : prob.ux; OPT_LPSolver *nlp = NULL; MRQ_Preprocessor *preprocessor = NULL; minlpproblem::MIP_ConstraintsByColumnsStorager ccstorager; nthreads = in_number_of_threads <= 0 ? MRQ_getNumCores() : in_number_of_threads; if( in_preprocess_lin_constr || in_preprocess_quad_constrs || in_preprocess_obj_function ) { preprocessor = new (std::nothrow) MRQ_Preprocessor(&prob); MRQ_IFMEMERRORGOTOLABEL(!preprocessor, out_return_code, termination); } { auto ret = algorithmInitialization( nthreads, true, milpSolverParams, nlpSolverParams, prob, lx, ux, preprocessor, NULL, &plc, &puc ); if( ret != MRQ_SUCCESS) { if( in_print_level > 0 ) { if( ret == MRQ_ALG_NOT_APPLICABLE && (out_algorithm == MRQ_IGMA1_ALG || out_algorithm == MRQ_IGMA2_ALG) ) MRQ_PRINTERRORMSG("Error: Integrality Gap Minimization Algorithm only hands binary problems"); else MRQ_PRINTERRORNUMBER(ret); } out_return_code = ret; goto termination; } } if(in_print_level > 1) { std::cout << "\n"; MRQ_PRINTMSG("Starting Structured Stochastic Rounding Heuristic\n\n"); printSubSolvers(true, true, false); } MRQ_malloc(intVars, n); MRQ_malloc(reverseIntVars, n); MRQ_malloc(initSol, n); if( prob.getProblemType() == minlpproblem::MIP_PT_MILP ) { //we try use a linear solver here nlp = OPT_newLPSolver(in_milp_solver); } if(!nlp) nlp = OPT_newNLPSolver(in_nlp_solver); //we got a failure to instantiate a linear solver. So, we try instantiate a NLP solver. MRQ_IFMEMERRORGOTOLABEL(!intVars || !reverseIntVars || !initSol || !nlp, out_return_code, termination ); nI = prob.getIntegerIndices(intVars); contVars = &intVars[nI]; nC = prob.getContinuousIndices(contVars); #if MRQ_DEBUG_MODE assert(n == nI + nC); #endif prob.getReverseIntegerIndices(reverseIntVars); r = MRQ_setNLPRelaxProb( prob, lx, ux, plc, puc, nlp, true, true, true, false, thnumber, in_set_special_nlp_solver_params, nlpSolverParams, in_number_of_threads, in_max_cpu_time, in_max_time, 0, 0 ); MRQ_IFERRORGOTOLABEL(r, out_return_code, (MRQ_RETURN_CODE) r, termination); if( in_solve_continuous_relaxation ) { if(in_print_level > 2) std::cout << MRQ_PREPRINT "Solving NLP relaxation\n"; nlp->solve( false ); if(in_print_level > 4) { std::cout << MRQ_PREPRINT "Continuous relaxation. ret: " << nlp->retCode << " feasSol: " << nlp->feasSol << "\n"; if( nlp->feasSol ) { for(int i = 0; i < n; i++) std::cout << "x[" << i << "]: " << nlp->sol[i] << "\n"; } } if( nlp->retCode == OPT_OPTIMAL_SOLUTION || nlp->feasSol ) { const double minGap = 0.1; if( nlp->retCode == OPT_OPTIMAL_SOLUTION ) { out_obj_opt_at_continuous_relax = nlp->objValue; zl = MRQ_max(zl, nlp->objValue); if( zl > zu ) { if(in_print_level > 0) MRQ_PRINTMSG("Solution of NLP relaxation is greater than upper_bound "); out_return_code = MRQ_INFEASIBLE_PROBLEM; goto termination; } } if( MRQ_isIntegerSol(nI,intVars, nlp->sol, in_integer_tol) ) { out_cpu_time_to_first_feas_sol = MRQ_calcCPUTtime( clockStart ); out_clock_time_to_first_feas_sol = MRQ_getTime() - timeStart; out_obj_at_first_sol = nlp->objValue; if( in_print_level > 1 ) MRQ_PRINTMSG("An integer optimal solution was gotten as NLP relaxation solution\n"); tryUpdateBestSolution( thnumber, n, nlp->sol, nlp->objValue, 0, clockStart, timeStart, in_store_history_solutions ); if( nlp->retCode == OPT_OPTIMAL_SOLUTION ) { out_return_code = MRQ_OPTIMAL_SOLUTION; } else { out_return_code = MRQ_HEURISTIC_SUCCESS; } goto termination; /*std::cout << "UNCOMENT THE GOTO ABOVE!\n"; MRQ_getchar();*/ } MRQ_copyArray(n, nlp->sol, initSol); for(int i = 0; i < nI; i++) { const auto ind = intVars[i]; if( MRQ_gap(initSol[ind]) < minGap ) { if(initSol[ind] - lx[ind] < minGap) { initSol[ind] += minGap; } else { #if MRQ_DEBUG_MODE assert( ux[ind] - initSol[ind] < minGap ); #endif initSol[ind] -= minGap; } } } } else if( nlp->retCode == OPT_INFEASIBLE_PROBLEM ) { if( in_print_level > 1 ) MRQ_PRINTMSG("Infeasible NLP relaxation\n"); out_return_code = MRQ_INFEASIBLE_PROBLEM; goto termination; } } else { if( in_use_initial_solution && xInit ) { MRQ_copyArray(n, xInit, initSol); } else { //we just put 0.5 as a gap to get the rounding probability //note, we do not set initial values for continue variables (we do not need this) for(int k = 0; k < nI; k++) { const int i = intVars[k]; initSol[i] = lx[i] == ux[i] ? lx[i] : lx[i] + 0.5; } } } random.setSeed( &in_seed_to_random_numbers ); r = binSumConstrs.calculateIndices(prob, lx, ux, plc, puc, reverseIntVars, true, true, true); MRQ_IFERRORGOTOLABEL(r, out_return_code, MRQ_UNDEFINED_ERROR, termination ); r = ccstorager.storageConstraintsByColumns(prob, in_preprocess_quad_constrs); MRQ_IFERRORGOTOLABEL(r, out_return_code, MRQ_UNDEFINED_ERROR, termination ); //ssrExecutor.in_preprocess_after_handling_constraints = in_preprocess_after_handling_constraints; ssrExecutor.in_preprocess_after_variable_rounding = in_preprocess_after_variable_rounding; ssrExecutor.in_random_order_to_threat_classes = in_random_order_to_threat_classes; ssrExecutor.in_random_order_to_threat_constraints_in_each_class = in_random_order_to_threat_constraints_in_each_class; ssrExecutor.in_solve_minlp_as_local_search = in_solve_minlp_as_local_search; ssrExecutor.in_stop_local_search_solving_on_first_improvment_solution = in_stop_local_search_solving_on_first_improvment_solution; ssrExecutor.in_max_number_of_main_iterations = in_max_iterations; ssrExecutor.in_max_number_of_improvments = in_max_number_of_improvments; ssrExecutor.in_print_level = in_print_level; ssrExecutor.in_nlp_solver = in_nlp_solver; ssrExecutor.in_milp_solver = in_milp_solver; ssrExecutor.in_neighborhood_strategy = in_neighborhood_strategy; ssrExecutor.in_preprocessing_point_strategy = in_preprocessing_point_strategy; ssrExecutor.in_additional_vars_fixing_strategy = in_additional_vars_fixing_strategy; ssrExecutor.in_rounding_var_bounds_updt_strategy = in_rounding_var_bounds_updt_strategy; ssrExecutor.in_cont_relax_strategy_to_stoch_rounding = in_cont_relax_strategy_to_stoch_rounding; ssrExecutor.in_absolute_feasibility_tol = in_absolute_feasibility_tol; ssrExecutor.in_relative_feasibility_tol = in_relative_feasibility_tol; ssrExecutor.in_integer_tol = in_integer_tol; ssrExecutor.in_integer_neighborhood_factor = in_integer_neighborhood_factor; ssrExecutor.in_continuous_neighborhood_factor = in_continuous_neighborhood_factor; ssrExecutor.in_relative_convergence_tol_to_local_search = in_relative_convergence_tol_to_local_search; ssrExecutor.in_max_cpu_time = in_max_cpu_time; ssrExecutor.in_max_time = in_max_time; ssrExecutor.in_min_probability_to_round = in_min_probability_to_round; ssrExecutor.in_local_search_algorithm = in_local_search_algorithm; ssrExecutor.in_milp_solver_params = milpSolverParams; ssrExecutor.in_nlp_solver_params = nlpSolverParams; ssrExecutor.in_alg_params = algParams; ssrExecutor.in_alg = in_alg; r = ssrExecutor.run(prob, binSumConstrs, &ccstorager, random, *nlp, thnumber, nthreads, INFINITY, plc, puc, lx, ux, nI, intVars, reverseIntVars, nC, contVars, initSol , algRetCod, outObj, out_best_sol ); if( !std::isinf(outObj) ) { #if MRQ_DEBUG_MODE assert(algRetCod == MRQ_HEURISTIC_SUCCESS); #endif out_best_obj = outObj; out_return_code = MRQ_HEURISTIC_SUCCESS; out_obj_at_nlp_integer_fixed_sol = ssrExecutor.out_obj_at_nlp_integer_fixed_sol; out_obj_at_first_sol = out_obj_at_nlp_integer_fixed_sol; out_cpu_time_at_nlp_integer_fixed_sol = ssrExecutor.out_cpu_time_at_nlp_integer_fixed_sol; out_cpu_time_to_first_feas_sol = out_cpu_time_at_nlp_integer_fixed_sol; } else { #if MRQ_DEBUG_MODE assert(algRetCod == MRQ_HEURISTIC_FAIL); #endif out_return_code = MRQ_HEURISTIC_FAIL; } out_vars_fixed_by_stoch_rounding = ssrExecutor.out_vars_fixed_by_stoch_rounding; out_local_search_alg_code = ssrExecutor.out_local_search_alg_code; out_number_of_iterations = ssrExecutor.out_number_of_main_iterations; termination: if(plc) free(plc); if(intVars) free(intVars); if(reverseIntVars) free(reverseIntVars); if(initSol) free(initSol); if(constrValues) free(constrValues); if(nlp) delete nlp; if(preprocessor) delete preprocessor; algorithmFinalization(nthreads, prob, lx, ux); out_number_of_threads = nthreads; out_cpu_time = ( (double) (clock() - clockStart) )/CLOCKS_PER_SEC; out_clock_time = MRQ_getTime() - timeStart; if(in_print_level > 1) std::cout << MRQ_PREPRINT "cpu time: " << out_cpu_time << "\n"; return out_return_code; }
36.394316
980
0.552025
xmuriqui
9dc8b48e6aa09b35926cb782ca3655d61830c83c
807
hpp
C++
src/core/lib/core_serialization/fixed_memory_stream.hpp
wgsyd/wgtf
d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed
[ "BSD-3-Clause" ]
28
2016-06-03T05:28:25.000Z
2019-02-14T12:04:31.000Z
src/core/lib/core_serialization/fixed_memory_stream.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
null
null
null
src/core/lib/core_serialization/fixed_memory_stream.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
14
2016-06-03T05:52:27.000Z
2019-03-21T09:56:03.000Z
#ifndef FIXED_MEMORY_STREAM_HPP #define FIXED_MEMORY_STREAM_HPP #include "i_datastream.hpp" #include "serialization_dll.hpp" namespace wgt { class SERIALIZATION_DLL FixedMemoryStream : public IDataStream { public: FixedMemoryStream(void* buffer, std::streamsize size); FixedMemoryStream(const void* buffer, std::streamsize size); explicit FixedMemoryStream(const char* buffer); std::streamoff seek(std::streamoff offset, std::ios_base::seekdir dir = std::ios_base::beg) override; std::streamsize read(void* destination, std::streamsize size) override; std::streamsize write(const void* source, std::streamsize size) override; bool sync() override; private: char* buffer_; bool readOnly_; std::streamoff pos_; std::streamsize size_; }; } // end namespace wgt #endif // FIXED_MEMORY_STREAM_HPP
27.827586
102
0.780669
wgsyd