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
109
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
48.5k
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
54dede18f9e4d8c3f394ca7e5d128d6c53f234ef
770
cpp
C++
CO2003/2_Recursion/q15/main.cpp
Smithienious/hcmut-201
be16b77831aae83ff42e656a181881686c74e674
[ "MIT" ]
null
null
null
CO2003/2_Recursion/q15/main.cpp
Smithienious/hcmut-201
be16b77831aae83ff42e656a181881686c74e674
[ "MIT" ]
2
2020-10-12T09:57:12.000Z
2020-11-09T11:05:01.000Z
CO2003/2_Recursion/q15/main.cpp
Smithienious/hcmut-201
be16b77831aae83ff42e656a181881686c74e674
[ "MIT" ]
4
2020-10-12T10:30:56.000Z
2020-12-15T14:46:04.000Z
#include <iostream> using namespace std; bool matchPattern(char *text, char *pattern) { if (*text == '\0' && *pattern != '\0') return false; if (*pattern == '\0') return true; if (*text == *pattern) return matchPattern(text + 1, pattern + 1); return false; } bool containsPattern(char *text, char *pattern) { /* * STUDENT ANSWER */ if (*text == '\0') return false; if (*text == *pattern) { if (matchPattern(text, pattern)) return true; else return containsPattern(text + 1, pattern); } return containsPattern(text + 1, pattern); } int main() { cout << containsPattern((char *)"Dai hoc Bach Khoa", (char *)"Bach Khoa"); return 0; }
17.906977
78
0.542857
Smithienious
54e0d1d56cb470aaac31d42c386b2ab307e95d80
674
hpp
C++
NWNXLib/API/Linux/API/CExoArrayListTemplatedunsignedshort.hpp
acaos/nwnxee-unified
0e4c318ede64028c1825319f39c012e168e0482c
[ "MIT" ]
1
2019-06-04T04:30:24.000Z
2019-06-04T04:30:24.000Z
NWNXLib/API/Linux/API/CExoArrayListTemplatedunsignedshort.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
null
null
null
NWNXLib/API/Linux/API/CExoArrayListTemplatedunsignedshort.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
1
2019-10-20T07:54:45.000Z
2019-10-20T07:54:45.000Z
#pragma once #include <cstdint> namespace NWNXLib { namespace API { struct CExoArrayListTemplatedunsignedshort { void Add(uint16_t); void Allocate(int32_t); void Insert(uint16_t, int32_t); void SetSize(int32_t); }; void CExoArrayListTemplatedunsignedshort__Add(CExoArrayListTemplatedunsignedshort* thisPtr, uint16_t); void CExoArrayListTemplatedunsignedshort__Allocate(CExoArrayListTemplatedunsignedshort* thisPtr, int32_t); void CExoArrayListTemplatedunsignedshort__Insert(CExoArrayListTemplatedunsignedshort* thisPtr, uint16_t, int32_t); void CExoArrayListTemplatedunsignedshort__SetSize(CExoArrayListTemplatedunsignedshort* thisPtr, int32_t); } }
25.923077
114
0.835312
acaos
54e30925c615ac4f64ef4d9a33c003ec5dc0ddec
1,315
cpp
C++
Crypt/CHARSTAT/test.cpp
mjohne/Turbo-Pascal-Apps
2b0b20ead9a6feaef5a6afbbd7616cd29b7a934f
[ "Unlicense" ]
null
null
null
Crypt/CHARSTAT/test.cpp
mjohne/Turbo-Pascal-Apps
2b0b20ead9a6feaef5a6afbbd7616cd29b7a934f
[ "Unlicense" ]
null
null
null
Crypt/CHARSTAT/test.cpp
mjohne/Turbo-Pascal-Apps
2b0b20ead9a6feaef5a6afbbd7616cd29b7a934f
[ "Unlicense" ]
null
null
null
#include <fstream> #include <iostream> #include <iomanip> #include <math.h> #include <stdlib.h> #include <string> #include <time.h> using namespace std; char ch,ch2; unsigned int i,n,Characters[256] = {0}, Letters[26],MaxChars = 0; ifstream IFile; ofstream StatisticsFile; string IFilename, StatisticsFilename; int main() { for (i = 1; i <= 26; i++) { Letters[i] = 0; } for (i = 1; i <= 256; i++) { Characters[i]; } cout << "Datei zum Einlesen: "; getline(cin,IFilename); IFile.open(IFilename.c_str(),ios::binary | ios::in); if (!IFile) cout << "\nDatei nicht gefunden!!!\n"; StatisticsFilename = "stat.txt"; StatisticsFile.open(StatisticsFilename.c_str(),ios::out); if (!StatisticsFile) cout << "\nDatei nicht ausgegeben!!!\n"; while(IFile.get(ch)) { //StatisticsFile.put(ch); MaxChars++; if (ch >= 'a' && ch <= 'z') { n = int(ch)-96; Letters[n]++; } } for (i = 1; i <= 26; i++) { cout << char(i+96) << " (" << int(i+96) << ") " << Letters[i] << " " << MaxChars/Letters[i] << "%\n"; } IFile.close(); IFile.clear(); StatisticsFile.close(); StatisticsFile.clear(); cout << "\n\n" << MaxChars; system("pause"); return 0; } zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
22.672414
106
0.565019
mjohne
54e931306e018128bcbdffd5ba156723280f6917
33,952
cc
C++
src/gpu-compute/schedule_stage.cc
jyhuang91/gem5-avx
f988da46080f8db49beb39e20af437219f3aa4cb
[ "BSD-3-Clause" ]
2
2021-01-15T17:32:18.000Z
2021-12-21T02:53:58.000Z
src/gpu-compute/schedule_stage.cc
jyhuang91/gem5-avx
f988da46080f8db49beb39e20af437219f3aa4cb
[ "BSD-3-Clause" ]
3
2021-03-26T20:33:59.000Z
2022-01-24T22:54:03.000Z
src/gpu-compute/schedule_stage.cc
jyhuang91/gem5-avx
f988da46080f8db49beb39e20af437219f3aa4cb
[ "BSD-3-Clause" ]
3
2021-03-27T16:36:19.000Z
2022-03-28T18:32:57.000Z
/* * Copyright (c) 2014-2015 Advanced Micro Devices, Inc. * All rights reserved. * * For use for simulation and test purposes only * * 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 copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "gpu-compute/schedule_stage.hh" #include <unordered_set> #include "debug/GPUSched.hh" #include "debug/GPUVRF.hh" #include "gpu-compute/compute_unit.hh" #include "gpu-compute/gpu_static_inst.hh" #include "gpu-compute/scalar_register_file.hh" #include "gpu-compute/vector_register_file.hh" #include "gpu-compute/wavefront.hh" ScheduleStage::ScheduleStage(const ComputeUnitParams &p, ComputeUnit &cu, ScoreboardCheckToSchedule &from_scoreboard_check, ScheduleToExecute &to_execute) : computeUnit(cu), fromScoreboardCheck(from_scoreboard_check), toExecute(to_execute), _name(cu.name() + ".ScheduleStage"), vectorAluRdy(false), scalarAluRdy(false), scalarMemBusRdy(false), scalarMemIssueRdy(false), glbMemBusRdy(false), glbMemIssueRdy(false), locMemBusRdy(false), locMemIssueRdy(false) { for (int j = 0; j < cu.numExeUnits(); ++j) { scheduler.emplace_back(p); } wavesInSch.clear(); schList.resize(cu.numExeUnits()); for (auto &dq : schList) { dq.clear(); } } ScheduleStage::~ScheduleStage() { scheduler.clear(); wavesInSch.clear(); schList.clear(); } void ScheduleStage::init() { fatal_if(scheduler.size() != fromScoreboardCheck.numReadyLists(), "Scheduler should have same number of entries as CU's readyList"); for (int j = 0; j < computeUnit.numExeUnits(); ++j) { scheduler[j].bindList(&fromScoreboardCheck.readyWFs(j)); } assert(computeUnit.numVectorGlobalMemUnits == 1); assert(computeUnit.numVectorSharedMemUnits == 1); } void ScheduleStage::exec() { toExecute.reset(); // Update readyList for (int j = 0; j < computeUnit.numExeUnits(); ++j) { /** * Remove any wave that already has an instruction present in SCH * waiting for RF reads to complete. This prevents out of order * execution within a wave. */ fromScoreboardCheck.updateReadyList(j); for (auto wIt = fromScoreboardCheck.readyWFs(j).begin(); wIt != fromScoreboardCheck.readyWFs(j).end();) { if (wavesInSch.find((*wIt)->wfDynId) != wavesInSch.end()) { *wIt = nullptr; wIt = fromScoreboardCheck.readyWFs(j).erase(wIt); } else { wIt++; } } } // Attempt to add another wave for each EXE type to schList queues // VMEM resources are iterated first, effectively giving priority // to VMEM over VALU for scheduling read of operands to the RFs. // Scalar Memory are iterated after VMEM // Iterate VMEM and SMEM int firstMemUnit = computeUnit.firstMemUnit(); int lastMemUnit = computeUnit.lastMemUnit(); for (int j = firstMemUnit; j <= lastMemUnit; j++) { int readyListSize = fromScoreboardCheck.readyWFs(j).size(); // If no wave is ready to be scheduled on the execution resource // then skip scheduling for this execution resource if (!readyListSize) { rdyListEmpty[j]++; continue; } rdyListNotEmpty[j]++; // Pick a wave and attempt to add it to schList Wavefront *wf = scheduler[j].chooseWave(); GPUDynInstPtr &gpu_dyn_inst = wf->instructionBuffer.front(); assert(gpu_dyn_inst); if (!addToSchList(j, gpu_dyn_inst)) { // For waves not added to schList, increment count of cycles // this wave spends in SCH stage. wf->schCycles++; addToSchListStalls[j]++; } else { if (gpu_dyn_inst->isScalar() || gpu_dyn_inst->isGroupSeg()) { wf->incLGKMInstsIssued(); } else { wf->incVMemInstsIssued(); if (gpu_dyn_inst->isFlat()) { wf->incLGKMInstsIssued(); } } if (gpu_dyn_inst->isStore() && gpu_dyn_inst->isGlobalSeg()) { wf->incExpInstsIssued(); } } } // Iterate everything else for (int j = 0; j < computeUnit.numExeUnits(); ++j) { // skip the VMEM resources if (j >= firstMemUnit && j <= lastMemUnit) { continue; } int readyListSize = fromScoreboardCheck.readyWFs(j).size(); // If no wave is ready to be scheduled on the execution resource // then skip scheduling for this execution resource if (!readyListSize) { rdyListEmpty[j]++; continue; } rdyListNotEmpty[j]++; // Pick a wave and attempt to add it to schList Wavefront *wf = scheduler[j].chooseWave(); GPUDynInstPtr &gpu_dyn_inst = wf->instructionBuffer.front(); assert(gpu_dyn_inst); if (!addToSchList(j, gpu_dyn_inst)) { // For waves not added to schList, increment count of cycles // this wave spends in SCH stage. wf->schCycles++; addToSchListStalls[j]++; } } // At this point, the schList queue per EXE type may contain // multiple waves, in order of age (oldest to youngest). // Wave may be in RFBUSY, indicating they are waiting for registers // to be read, or in RFREADY, indicating they are candidates for // the dispatchList and execution // Iterate schList queues and check if any of the waves have finished // reading their operands, moving those waves to RFREADY status checkRfOperandReadComplete(); // Fill the dispatch list with the oldest wave of each EXE type that // is ready to execute // Wave is picked if status in schList is RFREADY and it passes resource // ready checks similar to those currently in SCB fillDispatchList(); // Resource arbitration on waves in dispatchList // Losing waves are re-inserted to the schList at a location determined // by wave age // Arbitrate access to the VRF->LDS bus arbitrateVrfToLdsBus(); // Schedule write operations to the register files scheduleRfDestOperands(); // Lastly, reserve resources for waves that are ready to execute. reserveResources(); } void ScheduleStage::doDispatchListTransition(int unitId, DISPATCH_STATUS s, const GPUDynInstPtr &gpu_dyn_inst) { toExecute.dispatchTransition(gpu_dyn_inst, unitId, s); } void ScheduleStage::doDispatchListTransition(int unitId, DISPATCH_STATUS s) { toExecute.dispatchTransition(unitId, s); } bool ScheduleStage::schedRfWrites(int exeType, const GPUDynInstPtr &gpu_dyn_inst) { assert(gpu_dyn_inst); Wavefront *wf = gpu_dyn_inst->wavefront(); bool accessVrfWr = true; if (!gpu_dyn_inst->isScalar()) { accessVrfWr = computeUnit.vrf[wf->simdId] ->canScheduleWriteOperands(wf, gpu_dyn_inst); } bool accessSrfWr = computeUnit.srf[wf->simdId] ->canScheduleWriteOperands(wf, gpu_dyn_inst); bool accessRf = accessVrfWr && accessSrfWr; if (accessRf) { if (!gpu_dyn_inst->isScalar()) { computeUnit.vrf[wf->simdId]->scheduleWriteOperands(wf, gpu_dyn_inst); } computeUnit.srf[wf->simdId]->scheduleWriteOperands(wf, gpu_dyn_inst); return true; } else { rfAccessStalls[SCH_RF_ACCESS_NRDY]++; if (!accessSrfWr) { rfAccessStalls[SCH_SRF_WR_ACCESS_NRDY]++; } if (!accessVrfWr) { rfAccessStalls[SCH_VRF_WR_ACCESS_NRDY]++; } // Increment stall counts for WF wf->schStalls++; wf->schRfAccessStalls++; } return false; } void ScheduleStage::scheduleRfDestOperands() { for (int j = 0; j < computeUnit.numExeUnits(); ++j) { if (toExecute.dispatchStatus(j) == EMPTY || toExecute.dispatchStatus(j) == SKIP) { continue; } // get the wave on dispatch list and attempt to allocate write // resources in the RFs const GPUDynInstPtr &gpu_dyn_inst = toExecute.readyInst(j); assert(gpu_dyn_inst); Wavefront *wf = gpu_dyn_inst->wavefront(); if (!schedRfWrites(j, gpu_dyn_inst)) { reinsertToSchList(j, gpu_dyn_inst); doDispatchListTransition(j, EMPTY); // if this is a flat inst, also transition the LM pipe to empty // Note: since FLAT/LM arbitration occurs before scheduling // destination operands to the RFs, it is possible that a LM // instruction lost arbitration, but would have been able to // pass the RF destination operand check here, and execute // instead of the FLAT. if (wf->instructionBuffer.front()->isFlat()) { assert(toExecute.dispatchStatus(wf->localMem) == SKIP); doDispatchListTransition(wf->localMem, EMPTY); } } } } bool ScheduleStage::addToSchList(int exeType, const GPUDynInstPtr &gpu_dyn_inst) { // Attempt to add the wave to the schList if the VRF can support the // wave's next instruction assert(gpu_dyn_inst); Wavefront *wf = gpu_dyn_inst->wavefront(); bool accessVrf = true; if (!gpu_dyn_inst->isScalar()) { accessVrf = computeUnit.vrf[wf->simdId] ->canScheduleReadOperands(wf, gpu_dyn_inst); } bool accessSrf = computeUnit.srf[wf->simdId] ->canScheduleReadOperands(wf, gpu_dyn_inst); // If RFs can support instruction, add to schList in RFBUSY state, // place wave in wavesInSch and pipeMap, and schedule Rd/Wr operands // to the VRF bool accessRf = accessVrf && accessSrf; if (accessRf) { DPRINTF(GPUSched, "schList[%d]: Adding: SIMD[%d] WV[%d]: %d: %s\n", exeType, wf->simdId, wf->wfDynId, gpu_dyn_inst->seqNum(), gpu_dyn_inst->disassemble()); computeUnit.insertInPipeMap(wf); wavesInSch.emplace(wf->wfDynId); schList.at(exeType).push_back(std::make_pair(gpu_dyn_inst, RFBUSY)); if (wf->isOldestInstWaitcnt()) { wf->setStatus(Wavefront::S_WAITCNT); } if (!gpu_dyn_inst->isScalar()) { computeUnit.vrf[wf->simdId] ->scheduleReadOperands(wf, gpu_dyn_inst); } computeUnit.srf[wf->simdId]->scheduleReadOperands(wf, gpu_dyn_inst); DPRINTF(GPUSched, "schList[%d]: Added: SIMD[%d] WV[%d]: %d: %s\n", exeType, wf->simdId, wf->wfDynId, gpu_dyn_inst->seqNum(), gpu_dyn_inst->disassemble()); return true; } else { // Number of stall cycles due to RF access denied rfAccessStalls[SCH_RF_ACCESS_NRDY]++; // Count number of denials due to each reason // Multiple items may contribute to the denied request if (!accessVrf) { rfAccessStalls[SCH_VRF_RD_ACCESS_NRDY]++; } if (!accessSrf) { rfAccessStalls[SCH_SRF_RD_ACCESS_NRDY]++; } // Increment stall counts for WF wf->schStalls++; wf->schRfAccessStalls++; DPRINTF(GPUSched, "schList[%d]: Could not add: " "SIMD[%d] WV[%d]: %d: %s\n", exeType, wf->simdId, wf->wfDynId, gpu_dyn_inst->seqNum(), gpu_dyn_inst->disassemble()); } return false; } void ScheduleStage::reinsertToSchList(int exeType, const GPUDynInstPtr &gpu_dyn_inst) { // Insert wave w into schList for specified exeType. // Wave is inserted in age order, with oldest wave being at the // front of the schList assert(gpu_dyn_inst); auto schIter = schList.at(exeType).begin(); while (schIter != schList.at(exeType).end() && schIter->first->wfDynId < gpu_dyn_inst->wfDynId) { schIter++; } schList.at(exeType).insert(schIter, std::make_pair(gpu_dyn_inst, RFREADY)); } void ScheduleStage::checkMemResources() { // Check for resource availability in the next cycle scalarMemBusRdy = false; scalarMemIssueRdy = false; // check if there is a SRF->Global Memory bus available and if (computeUnit.srfToScalarMemPipeBus.rdy(Cycles(1))) { scalarMemBusRdy = true; } // check if we can issue a scalar memory instruction if (computeUnit.scalarMemUnit.rdy(Cycles(1))) { scalarMemIssueRdy = true; } glbMemBusRdy = false; glbMemIssueRdy = false; // check if there is a VRF->Global Memory bus available if (computeUnit.vrfToGlobalMemPipeBus.rdy(Cycles(1))) { glbMemBusRdy = true; } // check if we can issue a Global memory instruction if (computeUnit.vectorGlobalMemUnit.rdy(Cycles(1))) { glbMemIssueRdy = true; } locMemBusRdy = false; locMemIssueRdy = false; // check if there is a VRF->LDS bus available if (computeUnit.vrfToLocalMemPipeBus.rdy(Cycles(1))) { locMemBusRdy = true; } // check if we can issue a LDS instruction if (computeUnit.vectorSharedMemUnit.rdy(Cycles(1))) { locMemIssueRdy = true; } } bool ScheduleStage::dispatchReady(const GPUDynInstPtr &gpu_dyn_inst) { assert(gpu_dyn_inst); Wavefront *wf = gpu_dyn_inst->wavefront(); vectorAluRdy = false; scalarAluRdy = false; // check for available vector/scalar ALUs in the next cycle if (computeUnit.vectorALUs[wf->simdId].rdy(Cycles(1))) { vectorAluRdy = true; } if (computeUnit.scalarALUs[wf->scalarAlu].rdy(Cycles(1))) { scalarAluRdy = true; } if (gpu_dyn_inst->isNop()) { // S_NOP requires SALU. V_NOP requires VALU. // TODO: Scalar NOP does not require SALU in hardware, // and is executed out of IB directly. if (gpu_dyn_inst->isScalar() && !scalarAluRdy) { dispNrdyStalls[SCH_SCALAR_ALU_NRDY]++; return false; } else if (!gpu_dyn_inst->isScalar() && !vectorAluRdy) { dispNrdyStalls[SCH_VECTOR_ALU_NRDY]++; return false; } } else if (gpu_dyn_inst->isEndOfKernel()) { // EndPgm instruction if (gpu_dyn_inst->isScalar() && !scalarAluRdy) { dispNrdyStalls[SCH_SCALAR_ALU_NRDY]++; return false; } } else if (gpu_dyn_inst->isBarrier() || gpu_dyn_inst->isBranch() || gpu_dyn_inst->isALU()) { // Barrier, Branch, or ALU instruction if (gpu_dyn_inst->isScalar() && !scalarAluRdy) { dispNrdyStalls[SCH_SCALAR_ALU_NRDY]++; return false; } else if (!gpu_dyn_inst->isScalar() && !vectorAluRdy) { dispNrdyStalls[SCH_VECTOR_ALU_NRDY]++; return false; } } else if (!gpu_dyn_inst->isScalar() && gpu_dyn_inst->isGlobalMem()) { // Vector Global Memory instruction bool rdy = true; if (!glbMemIssueRdy) { rdy = false; dispNrdyStalls[SCH_VECTOR_MEM_ISSUE_NRDY]++; } if (!glbMemBusRdy) { rdy = false; dispNrdyStalls[SCH_VECTOR_MEM_BUS_BUSY_NRDY]++; } if (!computeUnit.globalMemoryPipe.coalescerReady(gpu_dyn_inst)) { rdy = false; dispNrdyStalls[SCH_VECTOR_MEM_COALESCER_NRDY]++; } if (!computeUnit.globalMemoryPipe.outstandingReqsCheck(gpu_dyn_inst)) { rdy = false; dispNrdyStalls[SCH_VECTOR_MEM_REQS_NRDY]++; } if (!rdy) { return false; } } else if (gpu_dyn_inst->isScalar() && gpu_dyn_inst->isGlobalMem()) { // Scalar Global Memory instruction bool rdy = true; if (!scalarMemIssueRdy) { rdy = false; dispNrdyStalls[SCH_SCALAR_MEM_ISSUE_NRDY]++; } if (!scalarMemBusRdy) { rdy = false; dispNrdyStalls[SCH_SCALAR_MEM_BUS_BUSY_NRDY]++; } if (!computeUnit.scalarMemoryPipe .isGMReqFIFOWrRdy(wf->scalarRdGmReqsInPipe + wf->scalarWrGmReqsInPipe)) { rdy = false; dispNrdyStalls[SCH_SCALAR_MEM_FIFO_NRDY]++; } if (!rdy) { return false; } } else if (!gpu_dyn_inst->isScalar() && gpu_dyn_inst->isLocalMem()) { // Vector Local Memory instruction bool rdy = true; if (!locMemIssueRdy) { rdy = false; dispNrdyStalls[SCH_LOCAL_MEM_ISSUE_NRDY]++; } if (!locMemBusRdy) { rdy = false; dispNrdyStalls[SCH_LOCAL_MEM_BUS_BUSY_NRDY]++; } if (!computeUnit.localMemoryPipe. isLMReqFIFOWrRdy(wf->rdLmReqsInPipe + wf->wrLmReqsInPipe)) { rdy = false; dispNrdyStalls[SCH_LOCAL_MEM_FIFO_NRDY]++; } if (!rdy) { return false; } } else if (!gpu_dyn_inst->isScalar() && gpu_dyn_inst->isFlat()) { // Vector Flat memory instruction bool rdy = true; if (!glbMemIssueRdy || !locMemIssueRdy) { rdy = false; dispNrdyStalls[SCH_FLAT_MEM_ISSUE_NRDY]++; } if (!glbMemBusRdy || !locMemBusRdy) { rdy = false; dispNrdyStalls[SCH_FLAT_MEM_BUS_BUSY_NRDY]++; } if (!computeUnit.globalMemoryPipe.coalescerReady(gpu_dyn_inst)) { rdy = false; dispNrdyStalls[SCH_FLAT_MEM_COALESCER_NRDY]++; } if (!computeUnit.globalMemoryPipe.outstandingReqsCheck(gpu_dyn_inst)) { rdy = false; dispNrdyStalls[SCH_FLAT_MEM_REQS_NRDY]++; } if (!computeUnit.localMemoryPipe. isLMReqFIFOWrRdy(wf->rdLmReqsInPipe + wf->wrLmReqsInPipe)) { rdy = false; dispNrdyStalls[SCH_FLAT_MEM_FIFO_NRDY]++; } if (!rdy) { return false; } } else { panic("%s: unknown instr checked for readiness", gpu_dyn_inst->disassemble()); return false; } dispNrdyStalls[SCH_RDY]++; return true; } void ScheduleStage::fillDispatchList() { // update execution resource status checkMemResources(); // iterate execution resources for (int j = 0; j < computeUnit.numExeUnits(); j++) { assert(toExecute.dispatchStatus(j) == EMPTY); // iterate waves in schList to pick one for dispatch auto schIter = schList.at(j).begin(); bool dispatched = false; while (schIter != schList.at(j).end()) { // only attempt to dispatch if status is RFREADY if (schIter->second == RFREADY) { // Check if this wave is ready for dispatch bool dispRdy = dispatchReady(schIter->first); if (!dispatched && dispRdy) { // No other wave has been dispatched for this exe // resource, and this wave is ready. Place this wave // on dispatchList and make it ready for execution // next cycle. // Acquire a coalescer token if it is a global mem // operation. GPUDynInstPtr mp = schIter->first; if (!mp->isMemSync() && !mp->isScalar() && (mp->isGlobalMem() || mp->isFlat())) { computeUnit.globalMemoryPipe.acqCoalescerToken(mp); } doDispatchListTransition(j, EXREADY, schIter->first); DPRINTF(GPUSched, "dispatchList[%d]: fillDispatchList: " "EMPTY->EXREADY\n", j); schIter->first = nullptr; schIter = schList.at(j).erase(schIter); dispatched = true; } else { // Either another wave has been dispatched, or this wave // was not ready, so it is stalled this cycle schIter->first->wavefront()->schStalls++; if (!dispRdy) { // not ready for dispatch, increment stall stat schIter->first->wavefront()->schResourceStalls++; } // Examine next wave for this resource schIter++; } } else { // Wave not in RFREADY, try next wave schIter++; } } // Increment stall count if no wave sent to dispatchList for // current execution resource if (!dispatched) { schListToDispListStalls[j]++; } else { schListToDispList[j]++; } } } void ScheduleStage::arbitrateVrfToLdsBus() { // Arbitrate the VRF->GM and VRF->LDS buses for Flat memory ops // Note: a Flat instruction in GFx8 reserves both VRF->Glb memory bus // and a VRF->LDS bus. In GFx9, this is not the case. // iterate the GM pipelines for (int i = 0; i < computeUnit.numVectorGlobalMemUnits; i++) { // get the GM pipe index in the dispatchList int gm_exe_unit = computeUnit.firstMemUnit() + i; // get the wave in the dispatchList GPUDynInstPtr &gpu_dyn_inst = toExecute.readyInst(gm_exe_unit); // If the WF is valid, ready to execute, and the instruction // is a flat access, arbitrate with the WF's assigned LM pipe if (gpu_dyn_inst && toExecute.dispatchStatus(gm_exe_unit) == EXREADY && gpu_dyn_inst->isFlat()) { Wavefront *wf = gpu_dyn_inst->wavefront(); // If the associated LM pipe also has a wave selected, block // that wave and let the Flat instruction issue. The WF in the // LM pipe is added back to the schList for consideration next // cycle. if (toExecute.dispatchStatus(wf->localMem) == EXREADY) { reinsertToSchList(wf->localMem, toExecute .readyInst(wf->localMem)); // Increment stall stats for LDS-VRF arbitration ldsBusArbStalls++; toExecute.readyInst(wf->localMem) ->wavefront()->schLdsArbStalls++; } // With arbitration of LM pipe complete, transition the // LM pipe to SKIP state in the dispatchList to inform EX stage // that a Flat instruction is executing next cycle doDispatchListTransition(wf->localMem, SKIP, gpu_dyn_inst); DPRINTF(GPUSched, "dispatchList[%d]: arbVrfLds: " "EXREADY->SKIP\n", wf->localMem); } } } void ScheduleStage::checkRfOperandReadComplete() { // Iterate the schList queues and check if operand reads // have completed in the RFs. If so, mark the wave as ready for // selection for dispatchList for (int j = 0; j < computeUnit.numExeUnits(); ++j) { for (auto &p : schList.at(j)) { const GPUDynInstPtr &gpu_dyn_inst = p.first; assert(gpu_dyn_inst); Wavefront *wf = gpu_dyn_inst->wavefront(); // Increment the number of cycles the wave spends in the // SCH stage, since this loop visits every wave in SCH. wf->schCycles++; bool vrfRdy = true; if (!gpu_dyn_inst->isScalar()) { vrfRdy = computeUnit.vrf[wf->simdId] ->operandReadComplete(wf, gpu_dyn_inst); } bool srfRdy = computeUnit.srf[wf->simdId] ->operandReadComplete(wf, gpu_dyn_inst); bool operandsReady = vrfRdy && srfRdy; if (operandsReady) { DPRINTF(GPUSched, "schList[%d]: WV[%d] operands ready for: " "%d: %s\n", j, wf->wfDynId, gpu_dyn_inst->seqNum(), gpu_dyn_inst->disassemble()); DPRINTF(GPUSched, "schList[%d]: WV[%d] RFBUSY->RFREADY\n", j, wf->wfDynId); p.second = RFREADY; } else { DPRINTF(GPUSched, "schList[%d]: WV[%d] operands not ready " "for: %d: %s\n", j, wf->wfDynId, gpu_dyn_inst->seqNum(), gpu_dyn_inst->disassemble()); // operands not ready yet, increment SCH stage stats // aggregate to all wavefronts on the CU p.second = RFBUSY; // Increment stall stats wf->schStalls++; wf->schOpdNrdyStalls++; opdNrdyStalls[SCH_RF_OPD_NRDY]++; if (!vrfRdy) { opdNrdyStalls[SCH_VRF_OPD_NRDY]++; } if (!srfRdy) { opdNrdyStalls[SCH_SRF_OPD_NRDY]++; } } } } } void ScheduleStage::reserveResources() { std::vector<bool> exeUnitReservations; exeUnitReservations.resize(computeUnit.numExeUnits(), false); for (int j = 0; j < computeUnit.numExeUnits(); ++j) { GPUDynInstPtr &gpu_dyn_inst = toExecute.readyInst(j); if (gpu_dyn_inst) { DISPATCH_STATUS s = toExecute.dispatchStatus(j); Wavefront *wf = gpu_dyn_inst->wavefront(); if (s == EMPTY) { continue; } else if (s == EXREADY) { // Wave is ready for execution std::vector<int> execUnitIds = wf->reserveResources(); if (!gpu_dyn_inst->isScalar()) { computeUnit.vrf[wf->simdId] ->dispatchInstruction(gpu_dyn_inst); } computeUnit.srf[wf->simdId]->dispatchInstruction(gpu_dyn_inst); std::stringstream ss; for (auto id : execUnitIds) { ss << id << " "; } DPRINTF(GPUSched, "dispatchList[%d]: SIMD[%d] WV[%d]: %d: %s" " Reserving ExeRes[ %s]\n", j, wf->simdId, wf->wfDynId, gpu_dyn_inst->seqNum(), gpu_dyn_inst->disassemble(), ss.str()); // mark the resources as reserved for this cycle for (auto execUnitId : execUnitIds) { panic_if(exeUnitReservations.at(execUnitId), "Execution unit %d is reserved!!!\n" "SIMD[%d] WV[%d]: %d: %s", execUnitId, wf->simdId, wf->wfDynId, gpu_dyn_inst->seqNum(), gpu_dyn_inst->disassemble()); exeUnitReservations.at(execUnitId) = true; } // If wavefront::reserveResources reserved multiple resources, // then we're executing a flat memory instruction. This means // that we've reserved a global and local memory unit. Thus, // we need to mark the latter execution unit as not available. if (execUnitIds.size() > 1) { M5_VAR_USED int lm_exec_unit = wf->localMem; assert(toExecute.dispatchStatus(lm_exec_unit) == SKIP); } } else if (s == SKIP) { // Shared Memory pipe reserved for FLAT instruction. // Verify the GM pipe for this wave is ready to execute // and the wave in the GM pipe is the same as the wave // in the LM pipe M5_VAR_USED int gm_exec_unit = wf->globalMem; assert(wf->wfDynId == toExecute .readyInst(gm_exec_unit)->wfDynId); assert(toExecute.dispatchStatus(gm_exec_unit) == EXREADY); } } } } void ScheduleStage::deleteFromSch(Wavefront *w) { wavesInSch.erase(w->wfDynId); } void ScheduleStage::regStats() { rdyListNotEmpty .init(computeUnit.numExeUnits()) .name(name() + ".rdy_list_not_empty") .desc("number of cycles one or more wave on ready list per " "execution resource") ; rdyListEmpty .init(computeUnit.numExeUnits()) .name(name() + ".rdy_list_empty") .desc("number of cycles no wave on ready list per " "execution resource") ; addToSchListStalls .init(computeUnit.numExeUnits()) .name(name() + ".sch_list_add_stalls") .desc("number of cycles a wave is not added to schList per " "execution resource when ready list is not empty") ; schListToDispList .init(computeUnit.numExeUnits()) .name(name() + ".sch_list_to_disp_list") .desc("number of cycles a wave is added to dispatchList per " "execution resource") ; schListToDispListStalls .init(computeUnit.numExeUnits()) .name(name() + ".sch_list_to_disp_list_stalls") .desc("number of cycles no wave is added to dispatchList per " "execution resource") ; // Operand Readiness Stall Cycles opdNrdyStalls .init(SCH_RF_OPD_NRDY_CONDITIONS) .name(name() + ".opd_nrdy_stalls") .desc("number of stalls in SCH due to operands not ready") ; opdNrdyStalls.subname(SCH_VRF_OPD_NRDY, csprintf("VRF")); opdNrdyStalls.subname(SCH_SRF_OPD_NRDY, csprintf("SRF")); opdNrdyStalls.subname(SCH_RF_OPD_NRDY, csprintf("RF")); // dispatchReady Stall Cycles dispNrdyStalls .init(SCH_NRDY_CONDITIONS) .name(name() + ".disp_nrdy_stalls") .desc("number of stalls in SCH due to resource not ready") ; dispNrdyStalls.subname(SCH_SCALAR_ALU_NRDY, csprintf("ScalarAlu")); dispNrdyStalls.subname(SCH_VECTOR_ALU_NRDY, csprintf("VectorAlu")); dispNrdyStalls.subname(SCH_VECTOR_MEM_ISSUE_NRDY, csprintf("VectorMemIssue")); dispNrdyStalls.subname(SCH_VECTOR_MEM_BUS_BUSY_NRDY, csprintf("VectorMemBusBusy")); dispNrdyStalls.subname(SCH_VECTOR_MEM_COALESCER_NRDY, csprintf("VectorMemCoalescer")); dispNrdyStalls.subname(SCH_CEDE_SIMD_NRDY, csprintf("CedeSimd")); dispNrdyStalls.subname(SCH_SCALAR_MEM_ISSUE_NRDY, csprintf("ScalarMemIssue")); dispNrdyStalls.subname(SCH_SCALAR_MEM_BUS_BUSY_NRDY, csprintf("ScalarMemBusBusy")); dispNrdyStalls.subname(SCH_SCALAR_MEM_FIFO_NRDY, csprintf("ScalarMemFIFO")); dispNrdyStalls.subname(SCH_LOCAL_MEM_ISSUE_NRDY, csprintf("LocalMemIssue")); dispNrdyStalls.subname(SCH_LOCAL_MEM_BUS_BUSY_NRDY, csprintf("LocalMemBusBusy")); dispNrdyStalls.subname(SCH_LOCAL_MEM_FIFO_NRDY, csprintf("LocalMemFIFO")); dispNrdyStalls.subname(SCH_FLAT_MEM_ISSUE_NRDY, csprintf("FlatMemIssue")); dispNrdyStalls.subname(SCH_FLAT_MEM_BUS_BUSY_NRDY, csprintf("FlatMemBusBusy")); dispNrdyStalls.subname(SCH_FLAT_MEM_COALESCER_NRDY, csprintf("FlatMemCoalescer")); dispNrdyStalls.subname(SCH_FLAT_MEM_FIFO_NRDY, csprintf("FlatMemFIFO")); dispNrdyStalls.subname(SCH_RDY, csprintf("Ready")); // RF Access Stall Cycles rfAccessStalls .init(SCH_RF_ACCESS_NRDY_CONDITIONS) .name(name() + ".rf_access_stalls") .desc("number of stalls due to RF access denied") ; rfAccessStalls.subname(SCH_VRF_RD_ACCESS_NRDY, csprintf("VrfRd")); rfAccessStalls.subname(SCH_VRF_WR_ACCESS_NRDY, csprintf("VrfWr")); rfAccessStalls.subname(SCH_SRF_RD_ACCESS_NRDY, csprintf("SrfRd")); rfAccessStalls.subname(SCH_SRF_WR_ACCESS_NRDY, csprintf("SrfWr")); rfAccessStalls.subname(SCH_RF_ACCESS_NRDY, csprintf("Any")); // Stall cycles due to wave losing LDS bus arbitration ldsBusArbStalls .name(name() + ".lds_bus_arb_stalls") .desc("number of stalls due to VRF->LDS bus conflicts") ; }
38.450736
79
0.591423
jyhuang91
54f432b6682071df308f2e53c807f7de4a6aef77
889
ipp
C++
libs/config/test/boost_no_cv_void_spec.ipp
zyiacas/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/config/test/boost_no_cv_void_spec.ipp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/config/test/boost_no_cv_void_spec.ipp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
// (C) Copyright John Maddock 2001. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for most recent version. // MACRO: BOOST_NO_CV_VOID_SPECIALIZATIONS // TITLE: template specialisations of cv-qualified void // DESCRIPTION: If template specialisations for cv-void types // conflict with a specialisation for void. namespace boost_no_cv_void_specializations{ template <class T> struct is_void { }; template <> struct is_void<void> {}; template <> struct is_void<const void> {}; template <> struct is_void<volatile void> {}; template <> struct is_void<const volatile void> {}; int test() { return 0; } }
19.326087
69
0.664792
zyiacas
54f500fa906b623036656adc354d277d039a3533
1,502
cc
C++
squid/squid3-3.3.8.spaceify/src/CpuAffinity.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/CpuAffinity.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/CpuAffinity.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
/* * DEBUG: section 54 Interprocess Communication */ #include "squid.h" #include "base/TextException.h" #include "CpuAffinity.h" #include "CpuAffinityMap.h" #include "CpuAffinitySet.h" #include "Debug.h" #include "globals.h" #include "SquidConfig.h" #include "tools.h" #include <algorithm> static CpuAffinitySet *TheCpuAffinitySet = NULL; void CpuAffinityInit() { Must(!TheCpuAffinitySet); if (Config.cpuAffinityMap) { const int processNumber = InDaemonMode() ? KidIdentifier : 1; TheCpuAffinitySet = Config.cpuAffinityMap->calculateSet(processNumber); if (TheCpuAffinitySet) TheCpuAffinitySet->apply(); } } void CpuAffinityReconfigure() { if (TheCpuAffinitySet) { TheCpuAffinitySet->undo(); delete TheCpuAffinitySet; TheCpuAffinitySet = NULL; } CpuAffinityInit(); } void CpuAffinityCheck() { if (Config.cpuAffinityMap) { Must(!Config.cpuAffinityMap->processes().empty()); const int maxProcess = *std::max_element(Config.cpuAffinityMap->processes().begin(), Config.cpuAffinityMap->processes().end()); // in no-deamon mode, there is one process regardless of squid.conf const int numberOfProcesses = InDaemonMode() ? NumberOfKids() : 1; if (maxProcess > numberOfProcesses) { debugs(54, DBG_IMPORTANT, "WARNING: 'cpu_affinity_map' has " "non-existing process number(s)"); } } }
25.033333
79
0.649134
spaceify
54f58550e698a79503e2c23dd9847580a5517079
1,436
cpp
C++
snippets/cpp/VS_Snippets_CLR/ADSetAppDomainPolicy/CPP/adsetappdomainpolicy.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-03-12T19:26:36.000Z
2022-01-10T21:45:33.000Z
snippets/cpp/VS_Snippets_CLR/ADSetAppDomainPolicy/CPP/adsetappdomainpolicy.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_CLR/ADSetAppDomainPolicy/CPP/adsetappdomainpolicy.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// <SNIPPET1> using namespace System; using namespace System::Threading; using namespace System::Security; using namespace System::Security::Policy; using namespace System::Security::Permissions; int main() { // Create a new application domain. AppDomain^ domain = System::AppDomain::CreateDomain( "MyDomain" ); // Create a new AppDomain PolicyLevel. PolicyLevel^ polLevel = PolicyLevel::CreateAppDomainLevel(); // Create a new, empty permission set. PermissionSet^ permSet = gcnew PermissionSet( PermissionState::None ); // Add permission to execute code to the permission set. permSet->AddPermission( gcnew SecurityPermission( SecurityPermissionFlag::Execution ) ); // Give the policy level's root code group a new policy statement based // on the new permission set. polLevel->RootCodeGroup->PolicyStatement = gcnew PolicyStatement( permSet ); // Give the new policy level to the application domain. domain->SetAppDomainPolicy( polLevel ); // Try to execute the assembly. try { // This will throw a PolicyException if the executable tries to // access any resources like file I/O or tries to create a window. domain->ExecuteAssembly( "Assemblies\\MyWindowsExe.exe" ); } catch ( PolicyException^ e ) { Console::WriteLine( "PolicyException: {0}", e->Message ); } AppDomain::Unload( domain ); } // </SNIPPET1>
30.553191
91
0.698468
BohdanMosiyuk
54f6072aae3a4b33ad4ca7790e63ace81cc31f67
918
cpp
C++
solution088.cpp
white-shark/leetcode-cpp
ba1389d3083ee2a2bb0a232672ee316afc125b58
[ "MIT" ]
31
2016-08-18T16:30:59.000Z
2022-02-15T11:21:39.000Z
solution088.cpp
runguanner/Leetcode
ba1389d3083ee2a2bb0a232672ee316afc125b58
[ "MIT" ]
null
null
null
solution088.cpp
runguanner/Leetcode
ba1389d3083ee2a2bb0a232672ee316afc125b58
[ "MIT" ]
22
2017-07-17T07:30:00.000Z
2022-01-24T08:37:15.000Z
/** * Merge Sorted Array * From right most to left. * * cpselvis ([email protected]) * August 30th, 2016 */ #include<iostream> #include<vector> using namespace std; class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int i = m - 1, j = n - 1, p = m + n - 1; while (p >= 0) { if (i < 0) { nums1[p] = nums2[j --]; } else if (j < 0) { nums1[p] = nums1[i --]; } else if (nums1[i] >= nums2[j]) { nums1[p] = nums1[i --]; } else { nums1[p] = nums2[j --]; } p --; } } }; int main(int argc, char **argv) { Solution s; int a[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; int b[] = {2, 4, 6, 8, 10}; vector<int> vec1(a + 0, a + 10); vector<int> vec2(b + 0, b + 5); s.merge(vec1, 5, vec2, 5); for (auto i : vec1) { cout << i << endl; } }
16.105263
68
0.454248
white-shark
54f70c5d529d8ce17ab96cd43b0e0643029521e9
23,033
cpp
C++
demos/demo_imgui/main.cpp
cmaughan/picovim
ebf7c29c4da417ca6fed232099cb58e06ce41f58
[ "MIT" ]
null
null
null
demos/demo_imgui/main.cpp
cmaughan/picovim
ebf7c29c4da417ca6fed232099cb58e06ce41f58
[ "MIT" ]
null
null
null
demos/demo_imgui/main.cpp
cmaughan/picovim
ebf7c29c4da417ca6fed232099cb58e06ce41f58
[ "MIT" ]
null
null
null
// ImGui - standalone example application for SDL2 + OpenGL // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) // (GL3W is a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc.) #include <SDL.h> #include <stdio.h> #include <thread> #include <imgui/imgui.h> #include <imgui/imgui_freetype.h> #include <imgui/imgui_impl_opengl3.h> #include <imgui/imgui_impl_sdl.h> #include <clip/clip.h> #include <mutils/time/time_provider.h> #include <clipp.h> #include <mutils/chibi/chibi.h> #include <mutils/file/file.h> #include <mutils/time/profiler.h> #include <mutils/ui/dpi.h> #include <zep/mcommon/animation/timer.h> #include "config_app.h" // About OpenGL function loaders: modern OpenGL doesn't have a standard header file and requires individual function pointers to be loaded manually. // Helper libraries are often used for this purpose! Here we are supporting a few common ones: gl3w, glew, glad. // You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own. #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) #include <GL/gl3w.h> // Initialize with gl3wInit() #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) #include <GL/glew.h> // Initialize with glewInit() #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) #include <glad/glad.h> // Initialize with gladLoadGL() #else #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM #endif #include "zep/mcommon/animation/timer.h" #undef max #include "zep/filesystem.h" #include "zep/imgui/display_imgui.h" #include "zep/imgui/editor_imgui.h" #include "zep/mode_standard.h" #include "zep/mode_vim.h" #include "zep/tab_window.h" #include "zep/theme.h" #include "zep/window.h" #include "orca/mode_orca.h" #include "repl/mode_repl.h" #include "zep/regress.h" #include <tinyfiledialogs/tinyfiledialogs.h> #ifndef __APPLE__ //#define WATCHER 1 #endif #ifdef WATCHER #include <FileWatcher/watcher.h> #endif #define _MATH_DEFINES_DEFINED #include "chibi/eval.h" #include "demo_common.h" using namespace Zep; using namespace MUtils; namespace { Chibi scheme; const std::string shader = R"R( #version 330 core uniform mat4 Projection; // Coordinates of the geometry layout(location = 0) in vec3 in_position; layout(location = 1) in vec2 in_tex_coord; layout(location = 2) in vec4 in_color; // Outputs to the pixel shader out vec2 frag_tex_coord; out vec4 frag_color; void main() { gl_Position = Projection * vec4(in_position.xyz, 1.0); frag_tex_coord = in_tex_coord; frag_color = in_color; } )R"; std::string startupFile; Zep::NVec2f GetPixelScale() { float ddpi = 0.0f; float hdpi = 0.0f; float vdpi = 0.0f; auto window = SDL_GL_GetCurrentWindow(); auto index = window ? SDL_GetWindowDisplayIndex(window) : 0; auto res = SDL_GetDisplayDPI(index, &ddpi, &hdpi, &vdpi); if (res == 0 && hdpi != 0) { return Zep::NVec2f(hdpi, vdpi) / 96.0f; } return Zep::NVec2f(1.0f); } } // namespace using namespace clipp; bool ReadCommandLine(int argc, char* argv[], int& exitCode) { startupFile = ""; auto cli = group(opt_value("input file", startupFile)); if (!parse(argc, argv, cli)) { //ZLOG(INFO, "Failed parse: " << make_man_page(cli, argv[0])); return false; } return true; } // A helper struct to init the editor and handle callbacks struct ZepContainerImGui : public IZepComponent, public IZepReplProvider { ZepContainerImGui(const std::string& startupFilePath, const std::string& configPath) : spEditor(std::make_unique<ZepEditor_ImGui>(configPath, GetPixelScale())) //, fileWatcher(spEditor->GetFileSystem().GetConfigPath(), std::chrono::seconds(2)) { chibi_init(scheme, SDL_GetBasePath()); // ZepEditor_ImGui will have created the fonts for us; but we need to build // the font atlas auto fontPath = std::string(SDL_GetBasePath()) + "Cousine-Regular.ttf"; auto& display = static_cast<ZepDisplay_ImGui&>(spEditor->GetDisplay()); int fontPixelHeight = (int)dpi_pixel_height_from_point_size(DemoFontPtSize, GetPixelScale().y); auto& io = ImGui::GetIO(); ImVector<ImWchar> ranges; ImFontGlyphRangesBuilder builder; builder.AddRanges(io.Fonts->GetGlyphRangesDefault()); // Add one of the default ranges builder.AddRanges(io.Fonts->GetGlyphRangesCyrillic()); // Add one of the default ranges builder.AddRanges(greek_range); builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) ImFontConfig cfg; cfg.OversampleH = 4; cfg.OversampleV = 4; auto pImFont = ImGui::GetIO().Fonts->AddFontFromFileTTF(fontPath.c_str(), float(fontPixelHeight), &cfg, ranges.Data); display.SetFont(ZepTextType::UI, std::make_shared<ZepFont_ImGui>(display, pImFont, fontPixelHeight)); display.SetFont(ZepTextType::Text, std::make_shared<ZepFont_ImGui>(display, pImFont, fontPixelHeight)); display.SetFont(ZepTextType::Heading1, std::make_shared<ZepFont_ImGui>(display, pImFont, int(fontPixelHeight * 1.75))); display.SetFont(ZepTextType::Heading2, std::make_shared<ZepFont_ImGui>(display, pImFont, int(fontPixelHeight * 1.5))); display.SetFont(ZepTextType::Heading3, std::make_shared<ZepFont_ImGui>(display, pImFont, int(fontPixelHeight * 1.25))); unsigned int flags = 0; // ImGuiFreeType::NoHinting; ImGuiFreeType::BuildFontAtlas(ImGui::GetIO().Fonts, flags); spEditor->RegisterCallback(this); ZepMode_Orca::Register(*spEditor); ZepRegressExCommand::Register(*spEditor); // Repl ZepReplExCommand::Register(*spEditor, this); ZepReplEvaluateOuterCommand::Register(*spEditor, this); ZepReplEvaluateInnerCommand::Register(*spEditor, this); ZepReplEvaluateCommand::Register(*spEditor, this); if (!startupFilePath.empty()) { spEditor->InitWithFileOrDir(startupFilePath); } else { spEditor->InitWithText("Shader.vert", shader); } // File watcher not used on apple yet ; needs investigating as to why it doesn't compile/run // The watcher is being used currently to update the config path, but clients may want to do more interesting things // by setting up watches for the current dir, etc. /*fileWatcher.start([=](std::string path, FileStatus status) { if (spEditor) { ZLOG(DBG, "Config File Change: " << path); spEditor->OnFileChanged(spEditor->GetFileSystem().GetConfigPath() / path); } });*/ } ~ZepContainerImGui() { } void Destroy() { spEditor->UnRegisterCallback(this); spEditor.reset(); } virtual std::string ReplParse(ZepBuffer& buffer, const GlyphIterator& cursorOffset, ReplParseType type) override { ZEP_UNUSED(cursorOffset); ZEP_UNUSED(type); GlyphRange range; if (type == ReplParseType::OuterExpression) { range = buffer.GetExpression(ExpressionType::Outer, cursorOffset, { '(' }, { ')' }); } else if (type == ReplParseType::SubExpression) { range = buffer.GetExpression(ExpressionType::Inner, cursorOffset, { '(' }, { ')' }); } else { range = GlyphRange(buffer.Begin(), buffer.End()); } if (range.first >= range.second) return "<No Expression>"; const auto& text = buffer.GetWorkingBuffer(); auto eval = std::string(text.begin() + range.first.Index(), text.begin() + range.second.Index()); // Flash the evaluated expression FlashType flashType = FlashType::Flash; float time = 1.0f; buffer.BeginFlash(time, flashType, range); auto ret = chibi_repl(scheme, NULL, eval); ret = RTrim(ret); GetEditor().SetCommandText(ret); return ret; } virtual std::string ReplParse(const std::string& str) override { auto ret = chibi_repl(scheme, NULL, str); ret = RTrim(ret); return ret; } virtual bool ReplIsFormComplete(const std::string& str, int& indent) override { int count = 0; for (auto& ch : str) { if (ch == '(') count++; if (ch == ')') count--; } if (count < 0) { indent = -1; return false; } else if (count == 0) { return true; } int count2 = 0; indent = 1; for (auto& ch : str) { if (ch == '(') count2++; if (ch == ')') count2--; if (count2 == count) { break; } indent++; } return false; } // Inherited via IZepComponent virtual void Notify(std::shared_ptr<ZepMessage> message) override { if (message->messageId == Msg::GetClipBoard) { clip::get_text(message->str); message->handled = true; } else if (message->messageId == Msg::SetClipBoard) { clip::set_text(message->str); message->handled = true; } else if (message->messageId == Msg::RequestQuit) { quit = true; } else if (message->messageId == Msg::ToolTip) { auto spTipMsg = std::static_pointer_cast<ToolTipMessage>(message); if (spTipMsg->location.Valid() && spTipMsg->pBuffer) { auto pSyntax = spTipMsg->pBuffer->GetSyntax(); if (pSyntax) { if (pSyntax->GetSyntaxAt(spTipMsg->location).foreground == ThemeColor::Identifier) { auto spMarker = std::make_shared<RangeMarker>(*spTipMsg->pBuffer); spMarker->SetDescription("This is an identifier"); spMarker->SetHighlightColor(ThemeColor::Identifier); spMarker->SetTextColor(ThemeColor::Text); spTipMsg->spMarker = spMarker; spTipMsg->handled = true; } else if (pSyntax->GetSyntaxAt(spTipMsg->location).foreground == ThemeColor::Keyword) { auto spMarker = std::make_shared<RangeMarker>(*spTipMsg->pBuffer); spMarker->SetDescription("This is a keyword"); spMarker->SetHighlightColor(ThemeColor::Keyword); spMarker->SetTextColor(ThemeColor::Text); spTipMsg->spMarker = spMarker; spTipMsg->handled = true; } } } } } virtual ZepEditor& GetEditor() const override { return *spEditor; } bool quit = false; std::unique_ptr<ZepEditor_ImGui> spEditor; //FileWatcher fileWatcher; }; int main(int argc, char* argv[]) { //::AllocConsole(); int code = 0; if (!ReadCommandLine(argc, argv, code)) { if (code != 0) return code; } // Setup SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; } // Decide GL+GLSL versions #if __APPLE__ // GL 3.2 Core + GLSL 150 const char* glsl_version = "#version 150"; SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); // Always required on Mac SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); #else // GL 3.0 + GLSL 130 const char* glsl_version = "#version 130"; SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #endif // Create window with graphics context SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_DisplayMode current; SDL_GetCurrentDisplayMode(0, &current); float ratio = current.w / (float)current.h; int startWidth = uint32_t(current.w * .6666); int startHeight = uint32_t(startWidth / ratio); ZLOG(INFO, "Start Size: " << Zep::NVec2i(startWidth, startHeight)); SDL_Window* window = SDL_CreateWindow("Zep", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, startWidth, startHeight, SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); SDL_GLContext gl_context = SDL_GL_CreateContext(window); SDL_GL_SetSwapInterval(0); // Enable vsync MUtils::NVec2i winSize; MUtils::NVec2i targetSize; SDL_GetWindowSize(window, &winSize.x, &winSize.y); SDL_GL_GetDrawableSize(window, &targetSize.x, &targetSize.y); ZLOG(INFO, "Screen Window Size: " << winSize); ZLOG(INFO, "Drawable Size: " << targetSize); // Initialize OpenGL loader #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) bool err = gl3wInit() != 0; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) bool err = glewInit() != GLEW_OK; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) bool err = gladLoadGL() == 0; #endif if (err) { fprintf(stderr, "Failed to initialize OpenGL loader!\n"); return 1; } // Setup Dear ImGui binding IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls ImGui_ImplSDL2_InitForOpenGL(window, gl_context); ImGui_ImplOpenGL3_Init(glsl_version); // ** Zep specific code, before Initializing font map ZepContainerImGui zep(startupFile, SDL_GetBasePath()); // Setup style ImGui::StyleColorsDark(); ZLOG(INFO, "DPI Scale: " << MUtils::NVec2f(GetPixelScale().x, GetPixelScale().y)); bool show_demo_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); MUtils::TimeProvider::Instance().StartThread(); // Main loop bool done = false; while (!done && !zep.quit) { Profiler::NewFrame(); // Poll and handle events (inputs, window resize, etc.) // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. SDL_Event event; if (SDL_WaitEventTimeout(&event, 10)) { ImGui_ImplSDL2_ProcessEvent(&event); if (event.type == SDL_QUIT) done = true; if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window)) done = true; // Keep consuming events if they are stacked up // Bug #39. // This stops keyboard events filling up the queue and replaying after you release the key. // It also makes things more snappy if (SDL_PollEvent(nullptr) == 1) { continue; } } else { // Save battery by skipping display if not required. // This will check for cursor flash, for example, to keep that updated. if (!zep.spEditor->RefreshRequired()) { continue; } } TIME_SCOPE(Frame); // Start the Dear ImGui frame ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(window); ImGui::NewFrame(); if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Open")) { auto openFileName = tinyfd_openFileDialog( "Choose a file", "", 0, nullptr, nullptr, 0); if (openFileName != nullptr) { auto pBuffer = zep.GetEditor().GetFileBuffer(openFileName); if (pBuffer) { zep.GetEditor().EnsureWindow(*pBuffer); } } } ImGui::EndMenu(); } const auto pBuffer = zep.GetEditor().GetActiveBuffer(); if (ImGui::BeginMenu("Settings")) { if (ImGui::BeginMenu("Editor Mode", pBuffer)) { bool enabledVim = strcmp(pBuffer->GetMode()->Name(), Zep::ZepMode_Vim::StaticName()) == 0; bool enabledNormal = !enabledVim; if (ImGui::MenuItem("Vim", "CTRL+2", &enabledVim)) { zep.GetEditor().SetGlobalMode(Zep::ZepMode_Vim::StaticName()); } else if (ImGui::MenuItem("Standard", "CTRL+1", &enabledNormal)) { zep.GetEditor().SetGlobalMode(Zep::ZepMode_Standard::StaticName()); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Theme")) { bool enabledDark = zep.GetEditor().GetTheme().GetThemeType() == ThemeType::Dark ? true : false; bool enabledLight = !enabledDark; if (ImGui::MenuItem("Dark", "", &enabledDark)) { zep.GetEditor().GetTheme().SetThemeType(ThemeType::Dark); } else if (ImGui::MenuItem("Light", "", &enabledLight)) { zep.GetEditor().GetTheme().SetThemeType(ThemeType::Light); } ImGui::EndMenu(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Window")) { auto pTabWindow = zep.GetEditor().GetActiveTabWindow(); bool selected = false; if (ImGui::MenuItem("Horizontal Split", "", &selected, pBuffer != nullptr)) { pTabWindow->AddWindow(pBuffer, pTabWindow->GetActiveWindow(), RegionLayoutType::VBox); } else if (ImGui::MenuItem("Vertical Split", "", &selected, pBuffer != nullptr)) { pTabWindow->AddWindow(pBuffer, pTabWindow->GetActiveWindow(), RegionLayoutType::HBox); } ImGui::EndMenu(); } // Helpful for diagnostics // Make sure you run a release build; iterator debugging makes the debug build much slower // Currently on a typical file, editor display time is < 1ms, and editor editor time is < 2ms if (ImGui::BeginMenu("Timings")) { for (auto& p : globalProfiler.timerData) { std::ostringstream strval; strval << p.first << " : " << p.second.current / 1000.0 << "ms"; // << " Last: " << p.second.current / 1000.0 << "ms"; ImGui::MenuItem(strval.str().c_str()); } ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } int w, h; SDL_GetWindowSize(window, &w, &h); // This is a bit messy; and I have no idea why I don't need to remove the menu fixed_size from the calculation! // The point of this code is to fill the main window with the Zep window // It is only done once so the user can play with the window if they want to for testing auto menuSize = ImGui::GetStyle().FramePadding.y * 2 + ImGui::GetFontSize(); ImGui::SetNextWindowPos(ImVec2(0, menuSize), ImGuiCond_Always); ImGui::SetNextWindowSize(ImVec2(float(w), float(h - menuSize)), ImGuiCond_Always); ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); ImGui::Begin("Zep", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoScrollbar); auto min = ImGui::GetCursorScreenPos(); auto max = ImGui::GetContentRegionAvail(); max.x = std::max(1.0f, max.x); max.y = std::max(1.0f, max.y); // Fill the window max.x = min.x + max.x; max.y = min.y + max.y; zep.spEditor->SetDisplayRegion(Zep::NVec2f(min.x, min.y), Zep::NVec2f(max.x, max.y)); // Display the editor inside this window zep.spEditor->Display(); zep.spEditor->HandleInput(); ImGui::End(); ImGui::PopStyleVar(4); ImGui::PopStyleColor(1); // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); // Rendering ImGui::Render(); SDL_GL_MakeCurrent(window, gl_context); glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); SDL_GL_SwapWindow(window); } // Quit the ticker MUtils::TimeProvider::Instance().Free(); zep.Destroy(); chibi_destroy(scheme); // Cleanup ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); SDL_GL_DeleteContext(gl_context); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
34.845688
191
0.598923
cmaughan
54fa487bcc7b3e832a331c1df6064396bd906875
5,109
hpp
C++
source/include/coffee/dbms/datatype/Set.hpp
ciscoruiz/wepa
e6d922157543c91b6804f11073424a0a9c6e8f51
[ "MIT" ]
2
2018-02-03T06:56:29.000Z
2021-04-20T10:28:32.000Z
source/include/coffee/dbms/datatype/Set.hpp
ciscoruiz/wepa
e6d922157543c91b6804f11073424a0a9c6e8f51
[ "MIT" ]
8
2018-02-18T21:00:07.000Z
2018-02-20T15:31:24.000Z
source/include/coffee/dbms/datatype/Set.hpp
ciscoruiz/wepa
e6d922157543c91b6804f11073424a0a9c6e8f51
[ "MIT" ]
1
2018-02-09T07:09:26.000Z
2018-02-09T07:09:26.000Z
// MIT License // // Copyright (c) 2018 Francisco Ruiz ([email protected]) // // 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. // #ifndef _coffee_dbms_datatype_Set_h #define _coffee_dbms_datatype_Set_h #include <memory> #include <unordered_map> #include <vector> #include <chrono> #include <coffee/basis/RuntimeException.hpp> #include <coffee/dbms/DatabaseException.hpp> #include <coffee/dbms/InvalidDataException.hpp> #include <coffee/dbms/datatype/Abstract.hpp> namespace coffee { namespace basis { class Date; class DataBlock; class Second; } namespace dbms { namespace datatype { class Set { public: typedef std::unordered_map<std::string, std::shared_ptr<Abstract> > Datas; typedef Datas::iterator data_iterator; typedef Datas::const_iterator const_data_iterator; typedef std::vector<data_iterator> CreationOrderAccess; Set() {;} Set(const Set& other); virtual ~Set() { m_datas.clear(); } void clear() { m_datas.clear(); } void insert(std::shared_ptr<Abstract> data) throw (basis::RuntimeException); std::shared_ptr<Abstract>& find(const std::string& name) throw (basis::RuntimeException); const std::shared_ptr<Abstract>& find(const std::string& name) const throw (basis::RuntimeException); bool constains(const std::string& name) const noexcept { return m_datas.find(name) != end(); } size_t size() const noexcept { return m_datas.size(); } bool empty() const noexcept { return m_datas.empty(); } data_iterator begin() noexcept { return m_datas.begin(); } data_iterator end() noexcept { return m_datas.end(); } static const std::string& name(data_iterator ii) { return ii->first; } static std::shared_ptr<Abstract>& data(data_iterator ii) { return ii->second; } const_data_iterator begin() const noexcept { return m_datas.begin(); } const_data_iterator end() const noexcept { return m_datas.end(); } static const std::string& name(const_data_iterator ii) { return ii->first; } static const std::shared_ptr<Abstract>& data(const_data_iterator ii) { return ii->second; } const_data_iterator search(const std::string& name) const noexcept { return m_datas.find(name); } Set& operator=(const Set& other) throw(basis::RuntimeException); int compare(const Set& other) const throw (basis::RuntimeException); int compare(const std::shared_ptr<Set>& other) const throw (basis::RuntimeException) { return compare(*other.get()); } bool operator==(const Set& other) const noexcept; bool operator< (const Set& other) const throw (basis::RuntimeException){ return compare(other) < 0; } bool operator!=(const Set& other) const noexcept { return !operator==(other); } int getInteger(const std::string& columnName) const throw(basis::RuntimeException, dbms::InvalidDataException); std::string getString(const std::string& columnName) const throw(basis::RuntimeException, dbms::InvalidDataException); float getFloat(const std::string& columnName) const throw(basis::RuntimeException, dbms::InvalidDataException); const basis::DataBlock& getDataBlock(const std::string& columnName) const throw(basis::RuntimeException, dbms::InvalidDataException); const std::chrono::seconds& getDate(const std::string& columnName) const throw(basis::RuntimeException, dbms::InvalidDataException); void setInteger(const std::string& columnName, const int value) throw(basis::RuntimeException,dbms::InvalidDataException); void setString(const std::string& columnName, const std::string& value) throw(basis::RuntimeException, dbms::InvalidDataException); void setFloat(const std::string& columnName, const float value) throw(basis::RuntimeException,dbms::InvalidDataException); void setDataBlock(const std::string& columnName, const basis::DataBlock& value) throw(basis::RuntimeException,dbms::InvalidDataException); void setDate(const std::string& columnName, const std::chrono::seconds& date) throw(basis::RuntimeException, dbms::InvalidDataException); private: Datas m_datas; CreationOrderAccess m_creationOrder; }; } } } #endif
42.575
141
0.749853
ciscoruiz
54fb89ba0af0d6dcf716f01eb0e19a505b6e803b
1,891
cpp
C++
Userland/Utilities/uniq.cpp
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
2
2022-02-16T02:12:38.000Z
2022-02-20T18:40:41.000Z
Userland/Utilities/uniq.cpp
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
null
null
null
Userland/Utilities/uniq.cpp
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2020, Matthew L. Curry <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/RefPtr.h> #include <LibCore/ArgsParser.h> #include <LibCore/System.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> struct linebuf { char* buf = NULL; size_t len = 0; }; static FILE* get_stream(char const* filepath, char const* perms) { FILE* ret; if (filepath == nullptr) { if (perms[0] == 'r') return stdin; return stdout; } ret = fopen(filepath, perms); if (ret == nullptr) { perror("fopen"); exit(1); } return ret; } ErrorOr<int> serenity_main(Main::Arguments arguments) { TRY(Core::System::pledge("stdio rpath wpath cpath")); char const* inpath = nullptr; char const* outpath = nullptr; Core::ArgsParser args_parser; args_parser.add_positional_argument(inpath, "Input file", "input", Core::ArgsParser::Required::No); args_parser.add_positional_argument(outpath, "Output file", "output", Core::ArgsParser::Required::No); args_parser.parse(arguments); FILE* infile = get_stream(inpath, "r"); FILE* outfile = get_stream(outpath, "w"); struct linebuf buffers[2]; struct linebuf* previous = &(buffers[0]); struct linebuf* current = &(buffers[1]); bool first_run = true; for (;;) { errno = 0; ssize_t rc = getline(&(current->buf), &(current->len), infile); if (rc < 0 && errno != 0) { perror("getline"); exit(1); } if (rc < 0) break; if (!first_run && strcmp(current->buf, previous->buf) == 0) continue; fputs(current->buf, outfile); swap(current, previous); first_run = false; } fclose(infile); fclose(outfile); return 0; }
23.6375
106
0.592279
densogiaichned
0702b69d65b38892c01ddd8c121498f9c11a5455
1,911
cpp
C++
Frame3.cpp
Svengali/cblib
77ddfd452cff842575750b9e6d792790f5ec5fee
[ "Zlib" ]
1
2021-05-01T04:34:24.000Z
2021-05-01T04:34:24.000Z
Frame3.cpp
Svengali/cblib
77ddfd452cff842575750b9e6d792790f5ec5fee
[ "Zlib" ]
null
null
null
Frame3.cpp
Svengali/cblib
77ddfd452cff842575750b9e6d792790f5ec5fee
[ "Zlib" ]
null
null
null
#include "Base.h" #include "Frame3.h" #include "Vec3U.h" START_CB ////////////////////////////////////////// // NOTEZ : IMPORTANT WARNING // the order of initialization of static class variables is // undefined !! // that means you CANNOT use things like Vec3::zero to initialize here !! const Frame3 Frame3::identity(Frame3::eIdentity); const Frame3 Frame3::zero(Frame3::eZero); //-------------------------------------------------------------------------------- /*static*/ bool Frame3::Equals(const Frame3 &a,const Frame3 &b,const float tolerance /*= EPSILON*/) { return Mat3::Equals( a.GetMatrix(), b.GetMatrix(), tolerance) && Vec3::Equals( a.GetTranslation(), b.GetTranslation(), tolerance ); } //-------------------------------------------------------------------------------- bool Frame3::IsValid() const { ASSERT( m_mat.IsValid() && m_t.IsValid() ); return true; } bool Frame3::IsIdentity(const float tolerance /*= EPSILON*/) const { return ( m_mat.IsIdentity(tolerance) && Vec3::Equals(m_t,Vec3::zero,tolerance) ); } //-------------------------------------------------------------------------------- void Frame3::SetAverage(const Frame3 &v1,const Frame3 &v2) { ASSERT( v1.IsValid() && v2.IsValid() ); m_mat.SetAverage(v1.GetMatrix(),v2.GetMatrix()); m_t = MakeAverage(v1.m_t,v2.m_t); } void Frame3::SetLerp(const Frame3 &v1,const Frame3 &v2,const float t) { ASSERT( v1.IsValid() && v2.IsValid() && fisvalid(t) ); m_mat.SetLerp(v1.GetMatrix(),v2.GetMatrix(),t); m_t = MakeLerp(v1.m_t,v2.m_t,t); } //------------------------------------------------------------------- #pragma warning(disable : 4505) // unreferenced static removed static void Frame3Test() { Frame3 xf(Frame3::eIdentity); Vec3 v = xf.GetMatrix().GetRowX(); xf.MutableMatrix().SetRowY(v); xf.MutableMatrix().SetRowZ(0,1,2); } //------------------------------------------------------------------- END_CB
26.915493
99
0.540555
Svengali
0702f49c16d491783d894b4156f9f9f0d958b8fd
7,696
cpp
C++
electroslag/application/loading_screen.cpp
jwb1/electroslag
a0f81ec6f8f8485c2418193b2e3d3f5347c92df5
[ "Apache-2.0" ]
1
2018-08-19T11:06:17.000Z
2018-08-19T11:06:17.000Z
electroslag/application/loading_screen.cpp
jwb1/electroslag
a0f81ec6f8f8485c2418193b2e3d3f5347c92df5
[ "Apache-2.0" ]
null
null
null
electroslag/application/loading_screen.cpp
jwb1/electroslag
a0f81ec6f8f8485c2418193b2e3d3f5347c92df5
[ "Apache-2.0" ]
null
null
null
// Electroslag Interactive Graphics System // Copyright 2018 Joshua Buckman // // 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 "electroslag/precomp.hpp" #include "electroslag/application/loading_screen.hpp" #include "electroslag/resource.hpp" #include "electroslag/resource_id.hpp" #include "electroslag/serialize/database.hpp" #include "electroslag/ui/ui_interface.hpp" #include "electroslag/graphics/context_interface.hpp" #if !defined(ELECTROSLAG_BUILD_SHIP) #include "electroslag/texture/gli_importer.hpp" #endif namespace electroslag { namespace application { loading_screen::loading_screen() : m_uniform_buffer_binding(-1) , m_frame_delegate(0) , m_visible(false) {} loading_screen::~loading_screen() {} void loading_screen::shutdown() { hide(); if (m_frame_delegate) { ui::get_ui()->get_window()->frame.unbind(m_frame_delegate); delete m_frame_delegate; m_frame_delegate = 0; } m_draw_queue.reset(); m_prim_stream.reset(); m_shader.reset(); m_texture.reset(); m_uniform_buffer.reset(); if (m_loaded_objects.is_valid()) { serialize::get_database()->clear_objects(m_loaded_objects); m_loaded_objects.reset(); } } void loading_screen::load( #if !defined(ELECTROSLAG_BUILD_SHIP) bool dump_content #endif ) { #if !defined(ELECTROSLAG_BUILD_SHIP) std::string const bin_path("loading_screen.bin"); std::string const json_path("..\\..\\..\\electroslag\\resources\\content\\loading_screen.json"); #endif // Load the necessary objects. serialize::database* d = serialize::get_database(); resource::ref loading_screen_resource(resource::create(ID_LOADING_SCREEN)); if (loading_screen_resource.is_valid()) { m_loaded_objects = d->load_objects(loading_screen_resource, std::string(".")); } #if !defined(ELECTROSLAG_BUILD_SHIP) else if (std::filesystem::exists(bin_path)) { m_loaded_objects = d->load_objects(bin_path); } else if (std::filesystem::exists(json_path)) { m_loaded_objects = d->load_objects_json(json_path); } ELECTROSLAG_CHECK(m_loaded_objects.is_valid()); if (dump_content) { d->dump_objects(m_loaded_objects); } #endif } #if !defined(ELECTROSLAG_BUILD_SHIP) void loading_screen::save(std::string const& file_name) { ELECTROSLAG_CHECK(m_loaded_objects.is_valid()); serialize::get_database()->save_objects(file_name, m_loaded_objects); } #endif void loading_screen::show() { serialize::database* d = serialize::get_database(); // Get references to graphics object descriptors. graphics::primitive_stream_descriptor::ref prim_stream_desc( d->find_object_ref<graphics::primitive_stream_descriptor>( hash_string("loading_screen::prim_stream") )); graphics::shader_program_descriptor::ref shader_desc( d->find_object_ref<graphics::shader_program_descriptor>( hash_string("loading_screen::shader") )); graphics::texture_descriptor::ref texture_desc( d->locate_object_ref<graphics::texture_descriptor>( hash_string("loading_screen::texture") )); #if !defined(ELECTROSLAG_BUILD_SHIP) if (!texture_desc.is_valid()) { texture::gli_importer::ref texture_importer( d->find_object_ref<texture::gli_importer>( hash_string("loading_screen::texture::importer") )); texture_desc = texture_importer->get_future()->get_wait(); } #endif // Create the real graphics objects. graphics::graphics_interface* g = graphics::get_graphics(); g->check_initialized(); m_draw_queue = g->create_command_queue(ELECTROSLAG_STRING_AND_HASH("cq:loading_screen")); m_prim_stream = g->create_primitive_stream(prim_stream_desc); m_shader = g->create_shader_program(shader_desc, prim_stream_desc->get_fields()); m_texture = g->create_texture(texture_desc); // The size parameter for the UBO descriptor is determined by the render thread, so we need to wait // for it to be computed. graphics::get_graphics()->finish_commands(); graphics::uniform_buffer_descriptor::ref uniform_buffer( m_shader->get_descriptor()->get_fragment_shader()->find_uniform_buffer(hash_string("_f_uniforms")) ); graphics::buffer_descriptor::ref uniform_desc(graphics::buffer_descriptor::create()); uniform_desc->set_buffer_memory_map(graphics::buffer_memory_map_write); uniform_desc->set_buffer_memory_caching(graphics::buffer_memory_caching_coherent); uniform_desc->set_uninitialized_data_size(uniform_buffer->get_size()); m_uniform_buffer = g->create_buffer(uniform_desc); m_uniform_buffer_binding = uniform_buffer->get_binding(); // Write the texture handle into the uniform buffer. // The buffer isn't mappable until after the render thread has handled the creation, so wait. graphics::get_graphics()->finish_commands(); byte* ubo_memory = m_uniform_buffer->map(); graphics::field_structs::texture_handle h(m_texture->get_handle()); uniform_buffer->get_fields()->find(hash_string("texture"))->write_uniform(ubo_memory, &h); m_uniform_buffer->unmap(); // Hook up listener m_frame_delegate = ui::window_interface::frame_delegate::create_from_method<loading_screen, &loading_screen::on_window_frame>(this); ui::get_ui()->get_window()->frame.bind(m_frame_delegate, event_bind_mode_reference_listener); m_visible = true; } void loading_screen::hide() { m_visible = false; } void loading_screen::on_window_frame(int /*millisec_elapsed*/) { if (m_visible) { m_draw_queue->enqueue_command<draw_command>(this); graphics::get_graphics()->flush_commands(); } } void loading_screen::draw_command::execute(graphics::context_interface* context) { context->clear_color(0.0f, 0.0f, 0.0f, 1.0f); context->bind_shader_program(m_this->m_shader); context->bind_primitive_stream(m_this->m_prim_stream); context->bind_uniform_buffer(m_this->m_uniform_buffer, m_this->m_uniform_buffer_binding); context->draw(); context->swap(); } } }
39.265306
144
0.62578
jwb1
07062eaf2dfa690cb911d2211a355d9974198c61
627
cpp
C++
artery_tree/validate_tree.cpp
ncrookston/liver_source
9876ac4e9ea57d8e23767af9be061a9b10c6f1e5
[ "BSL-1.0" ]
null
null
null
artery_tree/validate_tree.cpp
ncrookston/liver_source
9876ac4e9ea57d8e23767af9be061a9b10c6f1e5
[ "BSL-1.0" ]
null
null
null
artery_tree/validate_tree.cpp
ncrookston/liver_source
9876ac4e9ea57d8e23767af9be061a9b10c6f1e5
[ "BSL-1.0" ]
null
null
null
#include "liver/macrocell_tree.hpp" #include "utility/options.hpp" #include <boost/filesystem.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; using namespace jhmi; int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; try { auto opts = options<treefile_option>{}; if (!opts.parse(argc, argv)) return 1; auto tree = macrocell_tree{load_tree, opts.treefile().string()}; tree.validate(); google::protobuf::ShutdownProtobufLibrary(); } catch (std::exception const& e) { fmt::print("Failed with exception: {}\n", e.what()); } return 0; }
22.392857
68
0.684211
ncrookston
070b800765bbc4cb9c1983518e34cf039b379193
970
hpp
C++
include/ftl/platform/avr/utils/setbaud.hpp
nnarain/ftl
18cb39b8214bab76e42f5fea48810279114b7e70
[ "MIT" ]
null
null
null
include/ftl/platform/avr/utils/setbaud.hpp
nnarain/ftl
18cb39b8214bab76e42f5fea48810279114b7e70
[ "MIT" ]
23
2021-02-14T21:26:27.000Z
2021-06-29T23:53:51.000Z
include/ftl/platform/avr/utils/setbaud.hpp
nnarain/ftl
18cb39b8214bab76e42f5fea48810279114b7e70
[ "MIT" ]
null
null
null
// // setbaud.hpp // // @author Natesh Narain <[email protected]> // @date Oct 30 2020 // #ifndef FTL_PLATFORM_AVR_SETBAUD_HPP #define FTL_PLATFORM_AVR_SETBAUD_HPP #include <avr/io.h> namespace ftl { namespace platform { namespace avr { struct BaudConfig { BaudConfig(uint16_t b, bool u) : baud_value{b}, use_2x{u} {} BaudConfig() : BaudConfig(0, false) {} uint16_t baud_value; bool use_2x; }; static BaudConfig configUart9600() { #define BAUD 9600 #include <util/setbaud.h> constexpr auto b = UBRR_VALUE; constexpr auto u = #if USE_2X true; #else false; #endif return BaudConfig{b, u}; #undef BAUD } static BaudConfig configUart115200() { #define BAUD 115200 #include <util/setbaud.h> constexpr auto b = UBRR_VALUE; constexpr auto u = #if USE_2X true; #else false; #endif return BaudConfig{b, u}; #undef BAUD } } } } #endif
16.166667
66
0.628866
nnarain
070df54df488dfb8e42548d041f7de60977c279d
4,563
cc
C++
power/libperfmgr/FileNode.cc
Micha-Btz/device_xiaomi_grus
d516af03a8e7a73a34e72ef882fa6869e8ef34c3
[ "Apache-2.0" ]
6
2020-09-11T14:24:20.000Z
2020-11-11T17:59:34.000Z
power/libperfmgr/FileNode.cc
Micha-Btz/device_xiaomi_grus
d516af03a8e7a73a34e72ef882fa6869e8ef34c3
[ "Apache-2.0" ]
1
2021-01-17T22:26:47.000Z
2021-01-18T13:23:20.000Z
power/libperfmgr/FileNode.cc
Micha-Btz/device_xiaomi_grus
d516af03a8e7a73a34e72ef882fa6869e8ef34c3
[ "Apache-2.0" ]
24
2020-04-22T09:22:31.000Z
2021-07-23T23:35:37.000Z
/* * Copyright (C) 2017 The Android Open Source Project * * 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 specic language governing permissions and * limitations under the License. */ #define ATRACE_TAG (ATRACE_TAG_POWER | ATRACE_TAG_HAL) #define LOG_TAG "libperfmgr" #include "perfmgr/FileNode.h" #include <android-base/chrono_utils.h> #include <android-base/file.h> #include <android-base/logging.h> #include <android-base/properties.h> #include <android-base/stringprintf.h> #include <android-base/strings.h> #include <utils/Trace.h> namespace android { namespace perfmgr { FileNode::FileNode(std::string name, std::string node_path, std::vector<RequestGroup> req_sorted, std::size_t default_val_index, bool reset_on_init, bool hold_fd) : Node(std::move(name), std::move(node_path), std::move(req_sorted), default_val_index, reset_on_init), hold_fd_(hold_fd), warn_timeout_( android::base::GetBoolProperty("ro.debuggable", false) ? 5ms : 50ms) { } std::chrono::milliseconds FileNode::Update(bool log_error) { std::size_t value_index = default_val_index_; std::chrono::milliseconds expire_time = std::chrono::milliseconds::max(); // Find the highest outstanding request's expire time for (std::size_t i = 0; i < req_sorted_.size(); i++) { if (req_sorted_[i].GetExpireTime(&expire_time)) { value_index = i; break; } } // Update node only if request index changes if (value_index != current_val_index_ || reset_on_init_) { ATRACE_BEGIN(GetName().c_str()); const std::string& req_value = req_sorted_[value_index].GetRequestValue(); android::base::Timer t; fd_.reset(TEMP_FAILURE_RETRY( open(node_path_.c_str(), O_WRONLY | O_CLOEXEC | O_TRUNC))); if (fd_ == -1 || !android::base::WriteStringToFd(req_value, fd_)) { if (log_error) { LOG(WARNING) << "Failed to write to node: " << node_path_ << " with value: " << req_value << ", fd: " << fd_; } // Retry in 500ms or sooner expire_time = std::min(expire_time, std::chrono::milliseconds(500)); } else { // For regular file system, we need fsync fsync(fd_); // Some dev node requires file to remain open during the entire hint // duration e.g. /dev/cpu_dma_latency, so fd_ is intentionally kept // open during any requested value other than default one. If // request a default value, node will write the value and then // release the fd. if ((!hold_fd_) || value_index == default_val_index_) { fd_.reset(); } auto duration = t.duration(); if (duration > warn_timeout_) { LOG(WARNING) << "Slow writing to file: '" << node_path_ << "' with value: '" << req_value << "' took: " << duration.count() << " ms"; } // Update current index only when succeed current_val_index_ = value_index; reset_on_init_ = false; } ATRACE_END(); } return expire_time; } bool FileNode::GetHoldFd() const { return hold_fd_; } void FileNode::DumpToFd(int fd) const { std::string node_value; if (!android::base::ReadFileToString(node_path_, &node_value)) { LOG(ERROR) << "Failed to read node path: " << node_path_; } node_value = android::base::Trim(node_value); std::string buf(android::base::StringPrintf( "%s\t%s\t%zu\t%s\n", name_.c_str(), node_path_.c_str(), current_val_index_, node_value.c_str())); if (!android::base::WriteStringToFd(buf, fd)) { LOG(ERROR) << "Failed to dump fd: " << fd; } for (std::size_t i = 0; i < req_sorted_.size(); i++) { req_sorted_[i].DumpToFd( fd, android::base::StringPrintf("\t\tReq%zu:\t", i)); } } } // namespace perfmgr } // namespace android
37.097561
80
0.60881
Micha-Btz
07118dc51b0e9178e490f5bd0010f0a306835df1
862
cpp
C++
265B.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
265B.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
265B.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #include <map> #define fi first #define se second #define pb push_back #define mp make_pair #define pi 2*acos(0.0) #define eps 1e-9 #define PII pair<int,int> #define PDD pair<double,double> #define LL long long #define INF 1000000000 using namespace std; int N, h[100010], i, pos; LL ans; int main() { scanf("%d",&N); for(i = 0 ; i < N; i++) scanf("%d", &h[i]); pos = ans = 0; for(i = 0; i < N; i++) { ans += (LL)(h[i] - pos + 1); pos = h[i]; if(i < N - 1 && h[i] > h[i + 1]) { ans += (LL)(pos - h[i + 1]); pos = h[i + 1]; } if(i < N - 1) ans++; } printf("%I64d\n",ans); return 0; }
16.264151
45
0.539443
felikjunvianto
071a2bfe8f8f8718f2a40aa85c459cc111a3a0a7
5,054
cpp
C++
src/protocols/pppoe/CPPPOESessionHandler.cpp
vBRAS/OpenBRAS
cb227f48c5839ec95296c532b177a6639bfbd657
[ "BSD-3-Clause" ]
8
2017-06-05T08:56:27.000Z
2020-04-08T16:50:11.000Z
src/protocols/pppoe/CPPPOESessionHandler.cpp
vBRAS/OpenBRAS
cb227f48c5839ec95296c532b177a6639bfbd657
[ "BSD-3-Clause" ]
2
2018-12-30T10:37:53.000Z
2019-04-16T21:29:53.000Z
src/protocols/pppoe/CPPPOESessionHandler.cpp
vBRAS/OpenBRAS
cb227f48c5839ec95296c532b177a6639bfbd657
[ "BSD-3-Clause" ]
17
2017-06-05T08:54:27.000Z
2021-08-29T14:19:12.000Z
/*********************************************************************** Copyright (c) 2017, The OpenBRAS project authors. 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 OpenBRAS nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ #include "CPPPOESessionHandler.h" #include "CPPPOE.h" #include "CSession.h" CPPPOESessionHandler::CPPPOESessionHandler(CPPPOE &pppoe) :m_pppoe(pppoe) { } CPPPOESessionHandler::~CPPPOESessionHandler() { } int CPPPOESessionHandler::ProcessPacket(const char *packet, ssize_t size) { if (NULL == packet) { ACE_DEBUG ((LM_ERROR, "CPPPOESessionHandler::ProcessPacket(), packet NULL\n")); return -1; } #ifdef DEBUG_PKT static CHAR buffer[4*1024]; memset(buffer, 0, sizeof buffer); const BYTE *printPkt = (const BYTE *)packet; if (3 * size < 4 * 1024) { ACE_DEBUG((LM_INFO, "CPPPOESessionHandler::ProcessPacket(), dump packet:\n")); ssize_t i; for (i = 0; i < size; ++i) { snprintf(buffer + strlen(buffer), 4, "%02x ", printPkt[i]); } ACE_DEBUG((LM_INFO, "%s\n", buffer)); } #endif if (size < HDR_SIZE) { /* Impossible - ignore */ ACE_DEBUG ((LM_ERROR, "CPPPOESessionHandler::ProcessPacket(), packet size too short(%d), less than HDR_SIZE(%u)\n", size, HDR_SIZE)); return -1; } PPPoEPacket *pkt = (PPPoEPacket *)packet; /* Sanity check on packet */ if (pkt->ver != 1 || pkt->type != 1) { ACE_DEBUG ((LM_ERROR, "CPPPOESessionHandler::ProcessPacket(), packet version(%u) or type(%u) wrong.\n", pkt->ver, pkt->type)); return -1; } if (pkt->code != CODE_SESS) { ACE_DEBUG ((LM_ERROR, "CPPPOESessionHandler::ProcessPacket(), Bogus PPPoE code field (%#x).\n", pkt->code)); return -1; } /* Check length */ if (ntohs(pkt->length) + HDR_SIZE > size) { ACE_DEBUG ((LM_ERROR, "CPPPOESessionHandler::ProcessPacket(), Bogus PPPoE length field (%u). size=%d\n", (unsigned int) ntohs(pkt->length), size)); return -1; } /* Dispatch the packet to the associated PPP entity. */ CSession * session = GetPppoe().FindSession(ntohs(pkt->session)); if (NULL == session) { ACE_DEBUG ((LM_ERROR, "CPPPOESessionHandler::ProcessPacket(), Bogus PPPoE sessionId field (%#x)\n", (unsigned int) ntohs(pkt->session))); return -1; } return session->ProcessSessData(pkt, size); } int CPPPOESessionHandler::Init() { int ret = CPPPOEPacketHandler::OpenX(ETH_PPPOE_SESSION); if (-1 == ret) { ACE_DEBUG((LM_ERROR, "CPPPOESessionHandler::Init(), CPPPOEPacketHandler::OpenX(ETH_PPPOE_SESSION) failed. ret=%d\n", ret)); return -1; } CHAR intfName[ETHER_INTF_NAME_SIZE+1] = {0}; GetPppoe().GetEtherIntf().GetIntfName(intfName); ret = CPPPOEPacketHandler::BindInterface(intfName, ETH_PPPOE_SESSION); if (-1 == ret) { ACE_DEBUG((LM_ERROR, "CPPPOESessionHandler::Init(), CPPPOEPacketHandler::BindInterface(ETH_PPPOE_SESSION) failed. " "intfName=%s ret=%d\n", intfName, ret)); return -1; } return 0; } CPPPOE &CPPPOESessionHandler::GetPppoe() { return m_pppoe; }
31.006135
115
0.608231
vBRAS
0722d13e06ad7e03738f80ad8f8a7b426be62ceb
1,832
hpp
C++
complete_token_stream.hpp
CobaltXII/cxci
e8f7dc10ab954de504f10fca76121d0ce9de9e15
[ "MIT" ]
null
null
null
complete_token_stream.hpp
CobaltXII/cxci
e8f7dc10ab954de504f10fca76121d0ce9de9e15
[ "MIT" ]
null
null
null
complete_token_stream.hpp
CobaltXII/cxci
e8f7dc10ab954de504f10fca76121d0ce9de9e15
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <sstream> #include <iostream> #include "ansi_colors.hpp" #include "token_stream.hpp" // A completed token stream. struct complete_token_stream_t { std::string filename; token_stream_t input; std::vector<token_t> tokens; long cursor = 0; // Default constructor. complete_token_stream_t(std::string filename = "", token_stream_t buffer = token_stream_t("")) { this->filename = filename; input = buffer; token_t token; while ((token = input.next()).type != tk_eof) { tokens.push_back(token); } tokens.push_back(token); } // Get the next token in the stream and increment the cursor. token_t next() { return tokens[cursor++]; } // Peek the next token in the stream. token_t peek() { return tokens[cursor]; } // Check if the end-of-file has been reached. bool eof() { return tokens[cursor].type == tk_eof; } // Print an error message, then exit. void die(std::string error, token_t token) { std::cerr << set_color(bold_white) << filename << ":"; std::cerr << token.lineno + 1 << ":" << token.colno + 1 - token.text.length() << ": "; std::cerr << set_color(bold_red) << "error: "; std::cerr << set_color(bold_white) << error << set_color(reset) << std::endl; // Print the line where the error occurred. std::stringstream in(input.input.buffer); std::string line; for (int i = 0; i < token.lineno; i++) { std::getline(in, line); } std::getline(in, line); std::cerr << line << std::endl; // Print an indicator pointing to the column where the error occurred. for (int i = 0; i < token.colno - token.text.length(); i++) { if (line[i] == '\t') { std::cerr << '\t'; } else { std::cerr << ' '; } } std::cerr << set_color(bold_green) << '^' << set_color(reset) << std::endl; exit(2); } };
26.941176
97
0.639192
CobaltXII
072377f5b45681f1d6137894ceecbb56a836635f
412
hpp
C++
logos/wallet_server/client/callback_manager.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
3
2020-01-17T18:05:19.000Z
2021-12-29T04:21:59.000Z
logos/wallet_server/client/callback_manager.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
null
null
null
logos/wallet_server/client/callback_manager.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
2
2020-12-22T05:51:53.000Z
2021-06-08T00:27:46.000Z
#pragma once #include <logos/wallet_server/client/callback_handler.hpp> #include <logos/wallet_server/client/common.hpp> #include <mutex> class CallbackManager { using Handlers = wallet_server::client::callback::Handlers; using Handle = wallet_server::client::callback::Handle; public: void OnCallbackDone(const Handle handle); protected: std::mutex _mutex; Handlers _handlers; };
18.727273
63
0.740291
LogosNetwork
0725ee7006458581314e05229d89b3b5256db8a9
6,757
cpp
C++
NeuralNetworkCode/src/Synapse/MongilloSynapse.cpp
SFB1089/BrainCode
d7fab1f455c2c58f9be73be47e9f4538b426155c
[ "MIT" ]
null
null
null
NeuralNetworkCode/src/Synapse/MongilloSynapse.cpp
SFB1089/BrainCode
d7fab1f455c2c58f9be73be47e9f4538b426155c
[ "MIT" ]
null
null
null
NeuralNetworkCode/src/Synapse/MongilloSynapse.cpp
SFB1089/BrainCode
d7fab1f455c2c58f9be73be47e9f4538b426155c
[ "MIT" ]
null
null
null
#include "MongilloSynapse.hpp" MongilloSynapse::MongilloSynapse(NeuronPop * postNeurons,NeuronPop * preNeurons,GlobalSimInfo * info):Synapse(postNeurons,preNeurons,info) { u = 0; tau_f = 0; tau_d = 0; SetSeed(0); x.resize(GetNoNeuronsPre()); y.resize(GetNoNeuronsPre()); spike_submitted.resize(GetNoNeuronsPre()); uni_distribution = std::uniform_real_distribution<double>(0.0,1.0); } void MongilloSynapse::advect_spikers (std::vector<double> * currents, long spiker) { double dt_lastSpike = neuronsPre->GetTimeSinceLastSpike(spiker); //double(info->time_step - neuronsPre->get_previous_spike_step(spiker))*dt; double exptf = exp(-dt_lastSpike/tau_f); double exptd = exp(-dt_lastSpike/tau_d); for(std::size_t target_counter = 0;target_counter<x[spiker].size();target_counter++) { //SynapseData_STP * syn = &(synapseData[spiker][target_counter]); //In between spikes: unbind Calcium with rate 1/tau_f if((y[spiker][target_counter]) && (uni_distribution(generator) < (1.0-exptf))) y[spiker][target_counter] = false; //In between spikes: refill neurotransmitter with rate 1/tauD if((!x[spiker][target_counter]) && (uni_distribution(generator) < (1.0-exptd))) x[spiker][target_counter] = true; //Upon presynaptic spike: bind Calcium with probability u if(((!y[spiker][target_counter])) && (uni_distribution(generator) < u)) y[spiker][target_counter] = true; //std::cout << "x = " << std::to_string(x[spiker][target_counter]) << "\n"; //std::cout << "y = " << std::to_string(y[spiker][target_counter]) << "\n"; //Spike transmission if(x[spiker][target_counter] && y[spiker][target_counter]) TransmitSpike(currents, target_counter,spiker); else spike_submitted[spiker][target_counter] = false; } } void MongilloSynapse::TransmitSpike(std::vector<double> * currents, long targetId,long spikerId){ // long target = geometry->GetTargetList(spikerId)->at(targetId); //double J_ij = GetCouplingStrength(); double J_ij = GetCouplingStrength(spikerId, targetId); x[spikerId][targetId] = false; //Neurotransmitter release spike_submitted[spikerId][targetId] = true; this->cumulatedDV += J_ij; //double(spike_submitted[spiker].sum()) (*currents)[targetId] += J_ij; } void MongilloSynapse::ConnectNeurons() { Synapse::ConnectNeurons(); for(unsigned long source = 0;source < GetNoNeuronsPre();source ++){ long n = geometry->GetTargetList(source)->size(); x[source].resize(n); y[source].resize(n); spike_submitted[source].resize(n); } } void MongilloSynapse::LoadParameters(std::vector<std::string> *input){ Synapse::LoadParameters(input); std::string name; std::vector<std::string> values; for(std::vector<std::string>::iterator it = (*input).begin(); it != (*input).end(); ++it) { SplitString(&(*it),&name,&values); if(name.find("mongillo_tauF") != std::string::npos){ tau_f = std::stod(values.at(0)); } else if(name.find("mongillo_tauD") != std::string::npos){ tau_d = std::stod(values.at(0)); } else if(name.find("mongillo_U") != std::string::npos){ u = std::stod(values.at(0)); } else if(name.find("mongillo_seed") != std::string::npos){ SetSeed(std::stod(values.at(0))); } } } void MongilloSynapse::SaveParameters(std::ofstream * stream,std::string id_str){ Synapse::SaveParameters(stream,id_str); *stream << id_str << "mongillo_tauF\t\t\t\t\t" << std::to_string(tau_f) << " seconds\n"; *stream << id_str << "mongillo_tauD\t\t\t\t\t" << std::to_string(tau_d) << " seconds\n"; *stream << id_str << "mongillo_U\t\t\t\t\t\t" << std::to_string(this->u) << "\n"; if (info->globalSeed == -1) { *stream << id_str << "mongillo_seed\t\t\t\t\t" << std::to_string(this->seed) << "\n"; } } std::string MongilloSynapse::GetDataHeader(int data_column) { return "#" + std::to_string(data_column) + " J_" + GetIdStr() + " (mV)\n" + "#" + std::to_string(data_column+1) + " <x>_" + GetIdStr() + " ( x is given pre-spike : x = x_postspike + Spikesubmitted ) \n" + "#" + std::to_string(data_column+2) + " <y>_" + GetIdStr() + " ( y is given pre-spike : y = (y_postspike - U)/(1-U) ) \n" + "#" + std::to_string(data_column+3) + " <pR>_" + GetIdStr() + "\n"; //+ "#" + std::to_string(data_column+4) + " <xy>_" + GetIdStr() + "\n" XY will always return 0 since it is calculated after spiking } std::string MongilloSynapse::GetUnhashedDataHeader() { return "J_" + GetIdStr() + "\t<x>_" + GetIdStr() + "\t<y>_" + GetIdStr() + "\t<pR>_" + GetIdStr() + "\t"; } std::valarray<double> MongilloSynapse::GetSynapticState(int pre_neuron) { std::valarray<double> val; val.resize(GetNumberOfDataColumns()); int X=0; int Y=0; // int XY=0; int SpikeSubmitted=0; int N_post = x[pre_neuron].size(); for(int i = 0;i<N_post;i++){ X += x[pre_neuron][i]; Y += y[pre_neuron][i]; SpikeSubmitted += spike_submitted[pre_neuron][i]; //XY += x[pre_neuron][i] * y[pre_neuron][i]; } // get average coupling strength double Jsum = 0; for(unsigned int target=0; target < this->GetNumberOfPostsynapticTargets(pre_neuron); target++){ Jsum += *(geometry->GetDistributionJ(pre_neuron,target)); } val[0] = Jsum/double(this->GetNumberOfPostsynapticTargets(pre_neuron)); //val[0]= GetCouplingStrength()*double(this->GetNumberOfPostsynapticTargets(pre_neuron)); val[1]= double(X+SpikeSubmitted);//the synapses where the spike was transmitted a neurotransmitter count reset to 0 val[2]= double((Y-u*N_post)/(1-u));//expected value of y before the spike-induced increase in bound calcium probability val[3]= double(SpikeSubmitted); // val[4] = double(XY); return val; } MongilloSynapse::~MongilloSynapse(){} void MongilloSynapse::SetSeed(int s){ seed = s; generator = std::default_random_engine(seed); } void MongilloSynapse::SetSeed(std::default_random_engine *generator){ std::uniform_int_distribution<int> distribution(0,INT32_MAX); SetSeed(distribution(*generator)); Synapse::SetSeed(generator); }
37.960674
148
0.602634
SFB1089
072a49d88c309999af85346f19ac1000166215e7
756
cpp
C++
tools/xml/XSDCacheAdd.cpp
nakkim/smartmet-plugin-wfs
851334dd3be1a24b9708f66696f088fdc857a999
[ "MIT" ]
null
null
null
tools/xml/XSDCacheAdd.cpp
nakkim/smartmet-plugin-wfs
851334dd3be1a24b9708f66696f088fdc857a999
[ "MIT" ]
2
2018-04-17T10:02:46.000Z
2019-10-21T08:57:55.000Z
tools/xml/XSDCacheAdd.cpp
nakkim/smartmet-plugin-wfs
851334dd3be1a24b9708f66696f088fdc857a999
[ "MIT" ]
2
2017-05-10T12:03:51.000Z
2021-07-06T07:05:25.000Z
#include <cassert> #include <iostream> #include <sstream> #include <boost/filesystem.hpp> #include <openssl/sha.h> namespace fs = boost::filesystem; int main(int argc, char* argv[]) { assert(argc == 3); const std::string fn = argv[1]; const std::string uri = argv[2]; std::ostringstream fn_str; unsigned char md[SHA256_DIGEST_LENGTH]; SHA256(reinterpret_cast<const unsigned char*>(uri.c_str()), uri.length(), md); fn_str << "local_cache/"; for (unsigned i = 0; i < SHA256_DIGEST_LENGTH; i++) { char tmp[3]; snprintf(tmp, 3, "%02X", md[i]); fn_str << tmp; } const std::string output = fn_str.str(); fs::create_directories("local_cache"); fs::copy_file(fn, output); return 0; }
25.2
82
0.628307
nakkim
072d9956d942d886efe79033af00a14700d2436c
7,921
hpp
C++
POC/gazebo_ros_ws/src/gazebo_ros/include/gazebo_ros/conversions/geometry_msgs.hpp
antarikshnarain/ArtemisLeapFrog
4bfdad2f7696d5ce3de419abbd82e9a3d659ce5a
[ "BSD-3-Clause" ]
3
2021-02-23T05:23:48.000Z
2021-03-23T07:53:58.000Z
POC/gazebo_ros_ws/src/gazebo_ros/include/gazebo_ros/conversions/geometry_msgs.hpp
antarikshnarain/ArtemisLeapFrog
4bfdad2f7696d5ce3de419abbd82e9a3d659ce5a
[ "BSD-3-Clause" ]
1
2021-04-23T01:23:19.000Z
2021-04-23T01:23:19.000Z
POC/gazebo_ros_ws/src/gazebo_ros/include/gazebo_ros/conversions/geometry_msgs.hpp
antarikshnarain/ArtemisLeapFrog
4bfdad2f7696d5ce3de419abbd82e9a3d659ce5a
[ "BSD-3-Clause" ]
1
2021-04-01T21:45:40.000Z
2021-04-01T21:45:40.000Z
// Copyright 2018 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GAZEBO_ROS__CONVERSIONS__GEOMETRY_MSGS_HPP_ #define GAZEBO_ROS__CONVERSIONS__GEOMETRY_MSGS_HPP_ #include <geometry_msgs/msg/point.hpp> #include <geometry_msgs/msg/point32.hpp> #include <geometry_msgs/msg/pose.hpp> #include <geometry_msgs/msg/quaternion.hpp> #include <geometry_msgs/msg/transform.hpp> #include <geometry_msgs/msg/vector3.hpp> #include <ignition/math/Pose3.hh> #include <ignition/math/Quaternion.hh> #include <ignition/math/Vector3.hh> #include "gazebo_ros/conversions/generic.hpp" namespace gazebo_ros { /// Generic conversion from a ROS geometry vector message to another type. /// \param[in] in Input message. /// \return Conversion result /// \tparam T Output type template<class T> T Convert(const geometry_msgs::msg::Vector3 &) { T::ConversionNotImplemented; } /// \brief Specialized conversion from a ROS vector message to an Ignition Math vector. /// \param[in] msg ROS message to convert. /// \return An Ignition Math vector. template<> ignition::math::Vector3d Convert(const geometry_msgs::msg::Vector3 & msg) { ignition::math::Vector3d vec; vec.X(msg.x); vec.Y(msg.y); vec.Z(msg.z); return vec; } /// Generic conversion from a ROS geometry point32 message to another type. /// \param[in] in Input message. /// \return Conversion result /// \tparam T Output type template<class T> T Convert(const geometry_msgs::msg::Point32 &) { T::ConversionNotImplemented; } /// \brief Specialized conversion from a ROS point32 message to an Ignition Math vector. /// \param[in] in ROS message to convert. /// \return An Ignition Math vector. template<> ignition::math::Vector3d Convert(const geometry_msgs::msg::Point32 & in) { ignition::math::Vector3d vec; vec.X(in.x); vec.Y(in.y); vec.Z(in.z); return vec; } /// Generic conversion from a ROS geometry point message to another type. /// \param[in] in Input message. /// \return Conversion result /// \tparam T Output type template<class T> T Convert(const geometry_msgs::msg::Point &) { T::ConversionNotImplemented; } /// TODO(louise) This may already exist somewhere else, since it's within the same lib /// \brief Specialized conversion from a ROS point message to a ROS vector message. /// \param[in] in ROS message to convert. /// \return A ROS vector message. template<> geometry_msgs::msg::Vector3 Convert(const geometry_msgs::msg::Point & in) { geometry_msgs::msg::Vector3 msg; msg.x = in.x; msg.y = in.y; msg.z = in.z; return msg; } /// \brief Specialized conversion from a ROS point message to an Ignition math vector. /// \param[in] in ROS message to convert. /// \return A ROS vector message. template<> ignition::math::Vector3d Convert(const geometry_msgs::msg::Point & in) { ignition::math::Vector3d out; out.X(in.x); out.Y(in.y); out.Z(in.z); return out; } /// \brief Specialized conversion from an Ignition Math vector to a ROS message. /// \param[in] vec Ignition vector to convert. /// \return ROS geometry vector message template<> geometry_msgs::msg::Vector3 Convert(const ignition::math::Vector3d & vec) { geometry_msgs::msg::Vector3 msg; msg.x = vec.X(); msg.y = vec.Y(); msg.z = vec.Z(); return msg; } /// \brief Specialized conversion from an Ignition Math vector to a ROS message. /// \param[in] vec Ignition vector to convert. /// \return ROS geometry point message template<> geometry_msgs::msg::Point Convert(const ignition::math::Vector3d & vec) { geometry_msgs::msg::Point msg; msg.x = vec.X(); msg.y = vec.Y(); msg.z = vec.Z(); return msg; } /// \brief Specialized conversion from an Ignition Math Quaternion to a ROS message. /// \param[in] in Ignition Quaternion to convert. /// \return ROS geometry quaternion message template<> geometry_msgs::msg::Quaternion Convert(const ignition::math::Quaterniond & in) { geometry_msgs::msg::Quaternion msg; msg.x = in.X(); msg.y = in.Y(); msg.z = in.Z(); msg.w = in.W(); return msg; } /// \brief Specialized conversion from an Ignition Math Pose3d to a ROS geometry transform message. /// \param[in] in Ignition Pose3d to convert. /// \return ROS geometry transform message template<> geometry_msgs::msg::Transform Convert(const ignition::math::Pose3d & in) { geometry_msgs::msg::Transform msg; msg.translation = Convert<geometry_msgs::msg::Vector3>(in.Pos()); msg.rotation = Convert<geometry_msgs::msg::Quaternion>(in.Rot()); return msg; } /// \brief Specialized conversion from an Ignition Math Pose3d to a ROS geometry pose message. /// \param[in] in Ignition Pose3d to convert. /// \return ROS geometry pose message template<> geometry_msgs::msg::Pose Convert(const ignition::math::Pose3d & in) { geometry_msgs::msg::Pose msg; msg.position = Convert<geometry_msgs::msg::Point>(in.Pos()); msg.orientation = Convert<geometry_msgs::msg::Quaternion>(in.Rot()); return msg; } /// Generic conversion from a ROS Quaternion message to another type /// \param[in] in Input quaternion /// \return Conversion result /// \tparam T Output type template<class T> T Convert(const geometry_msgs::msg::Quaternion &) { T::ConversionNotImplemented; } /// \brief Specialized conversion from a ROS quaternion message to ignition quaternion /// \param[in] in Input quaternion message /// \return Ignition math quaternion with same values as the input message template<> ignition::math::Quaterniond Convert(const geometry_msgs::msg::Quaternion & in) { return ignition::math::Quaterniond(in.w, in.x, in.y, in.z); } /// Generic conversion from a ROS geometry transform message to another type. /// \param[in] in Input message. /// \return Conversion result /// \tparam T Output type template<class T> T Convert(const geometry_msgs::msg::Transform &) { T::ConversionNotImplemented; } /// \brief Specialized conversion from a ROS geometry transform message to an Ignition math pose3d. /// \param[in] in ROS message to convert. /// \return A Ignition Math pose3d. template<> ignition::math::Pose3d Convert(const geometry_msgs::msg::Transform & in) { ignition::math::Pose3d msg; msg.Pos() = Convert<ignition::math::Vector3d>(in.translation); msg.Rot() = Convert<ignition::math::Quaterniond>(in.rotation); return msg; } /// Generic conversion from a ROS geometry pose message to another type. /// \param[in] in Input message. /// \return Conversion result /// \tparam T Output type template<class T> T Convert(const geometry_msgs::msg::Pose &) { T::ConversionNotImplemented; } /// \brief Specialized conversion from a ROS pose message to a ROS geometry transform message. /// \param[in] in ROS pose message to convert. /// \return A ROS geometry transform message. template<> geometry_msgs::msg::Transform Convert(const geometry_msgs::msg::Pose & in) { geometry_msgs::msg::Transform msg; msg.translation = Convert<geometry_msgs::msg::Vector3>(in.position); msg.rotation = in.orientation; return msg; } /// \brief Specialized conversion from a ROS pose message to an Ignition Math pose. /// \param[in] in ROS pose message to convert. /// \return Ignition Math pose. template<> ignition::math::Pose3d Convert(const geometry_msgs::msg::Pose & in) { return {Convert<ignition::math::Vector3d>(in.position), Convert<ignition::math::Quaterniond>(in.orientation)}; } } // namespace gazebo_ros #endif // GAZEBO_ROS__CONVERSIONS__GEOMETRY_MSGS_HPP_
31.062745
99
0.729201
antarikshnarain
072f73c771e6d77aa7e04753c36cf023299d4aff
2,460
cpp
C++
Proj_Android/app/src/main/cpp/FColor.cpp
nraptis/Metal_OpenGL_MobileGameEngine
cc36682676a9797df8b3a7ee235b99be3ae2f666
[ "MIT" ]
3
2019-10-10T19:25:42.000Z
2019-12-17T10:51:23.000Z
Framework/[C++ Core]/FColor.cpp
nraptis/Metal_OpenGL_MobileGameEngine
cc36682676a9797df8b3a7ee235b99be3ae2f666
[ "MIT" ]
null
null
null
Framework/[C++ Core]/FColor.cpp
nraptis/Metal_OpenGL_MobileGameEngine
cc36682676a9797df8b3a7ee235b99be3ae2f666
[ "MIT" ]
1
2021-11-16T15:29:40.000Z
2021-11-16T15:29:40.000Z
#include "FColor.hpp" #include "core_includes.h" FColor::FColor(const char *pRGBAString) { mRed = 1.0f; mGreen = 1.0f; mBlue = 1.0f; mAlpha = 1.0f; const char *aPtr = pRGBAString; bool aFoundHex = false; if(aPtr) { while(*aPtr) { if((*aPtr>='0'&&*aPtr<='9')||(*aPtr>='a'&&*aPtr<='f')||(*aPtr>='A'&&*aPtr<='F')) { aFoundHex=true; } else { if(aFoundHex) { break; } else { pRGBAString++; } } aPtr++; } int aLength=(int)(aPtr-pRGBAString); if(aLength==2||aLength==6||aLength==8) { int aNumber[8]; for(int i=0;i<aLength;i++) { aNumber[i]=0; if(pRGBAString[i]>='0'&&pRGBAString[i]<='9') { aNumber[i]=pRGBAString[i]-'0'; } else if(pRGBAString[i]>='a'&&pRGBAString[i]<='f') { aNumber[i]=pRGBAString[i]-('a'-10); } else if(pRGBAString[i]>='A'&&pRGBAString[i]<='F') { aNumber[i]=pRGBAString[i]-('A'-10); } if(!(i&1)) { aNumber[i]=(aNumber[i]<<4); } } if(aLength==2) { mRed=1; mGreen=1; mBlue=1; mAlpha=(float)(aNumber[0]+aNumber[1])/255.0f; } else if(aLength==6) { mRed=(float)(aNumber[0]+aNumber[1])/255.0f; mGreen=(float)(aNumber[2]+aNumber[3])/255.0f; mBlue=(float)(aNumber[4]+aNumber[5])/255.0f; mAlpha=1.0f; } else { mRed=(float)(aNumber[0]+aNumber[1])/255.0f; mGreen=(float)(aNumber[2]+aNumber[3])/255.0f; mBlue=(float)(aNumber[4]+aNumber[5])/255.0f; mAlpha=(float)(aNumber[6]+aNumber[7])/255.0f; } } } } void FColor::Print(const char *pName) { Log("[%s] FColor(%s, %s, %s, %s);\n", FString(pName).c(), FString(mRed).c(), FString(mGreen).c(), FString(mBlue).c(), FString(mRed).c()); }
26.170213
141
0.376829
nraptis
0737004046b1864fa2c96acbd9b8ffff1be1e7b8
1,185
cpp
C++
DeviceCode/GHI/Libraries/GHI.OSHW.Hardware/Managed/stubs/HAL_GHI_OSHW_Hardware_LowLevel_Register.cpp
valoni/STM32F103
75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc
[ "Apache-2.0" ]
null
null
null
DeviceCode/GHI/Libraries/GHI.OSHW.Hardware/Managed/stubs/HAL_GHI_OSHW_Hardware_LowLevel_Register.cpp
valoni/STM32F103
75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc
[ "Apache-2.0" ]
null
null
null
DeviceCode/GHI/Libraries/GHI.OSHW.Hardware/Managed/stubs/HAL_GHI_OSHW_Hardware_LowLevel_Register.cpp
valoni/STM32F103
75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc
[ "Apache-2.0" ]
1
2019-12-03T05:37:43.000Z
2019-12-03T05:37:43.000Z
//----------------------------------------------------------------------------- // // ** WARNING! ** // This file was generated automatically by a tool. // Re-running the tool will overwrite this file. // You should copy this file to a custom location // before adding any customization in the copy to // prevent loss of your changes when the tool is // re-run. // //----------------------------------------------------------------------------- #include "HAL.h" #include "HAL_GHI_OSHW_Hardware_LowLevel_Register.h" using namespace GHI::OSHW::Hardware::LowLevel; void Register::_ctor( CLR_RT_HeapBlock* pMngObj, UINT32 param0, HRESULT &hr ) { } void Register::Write( CLR_RT_HeapBlock* pMngObj, UINT32 param0, HRESULT &hr ) { } UINT32 Register::Read( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { UINT32 retVal = 0; return retVal; } void Register::SetBits( CLR_RT_HeapBlock* pMngObj, UINT32 param0, HRESULT &hr ) { } void Register::ClearBits( CLR_RT_HeapBlock* pMngObj, UINT32 param0, HRESULT &hr ) { } void Register::ToggleBits( CLR_RT_HeapBlock* pMngObj, UINT32 param0, HRESULT &hr ) { }
26.333333
83
0.581435
valoni
07374202a97900ae656de6164961a67e3bf2e120
489
hpp
C++
5_Processes_Signals_Files_Pipes/4_Pipes/3_Process-with-workers/src/AWorker/AWorker.hpp
PP189B/Multithreaded-programming-practice
f80378343824e51a164241289399ec92150852e8
[ "MIT" ]
null
null
null
5_Processes_Signals_Files_Pipes/4_Pipes/3_Process-with-workers/src/AWorker/AWorker.hpp
PP189B/Multithreaded-programming-practice
f80378343824e51a164241289399ec92150852e8
[ "MIT" ]
null
null
null
5_Processes_Signals_Files_Pipes/4_Pipes/3_Process-with-workers/src/AWorker/AWorker.hpp
PP189B/Multithreaded-programming-practice
f80378343824e51a164241289399ec92150852e8
[ "MIT" ]
null
null
null
#pragma once #include <vector> namespace App { class AWorker { // Fields private: static std::vector<int> opened_sockets_; protected: int pid_; int socket_; // Constructors and destructor public: AWorker(); AWorker(const AWorker& other) = delete; AWorker(AWorker&& old) = delete; virtual ~AWorker(); // Logic public: void exec(); protected: virtual void workerFunction() = 0; }; //! AWorker } //!namespace App
13.583333
44
0.607362
PP189B
073b4edfb7d5c65ba6509a0b0a5ae8010b1a704c
302
cxx
C++
source/game/host_system/SceneManager.cxx
stblr/mkw-cs
520254ee41c262332fd2fe429a9364202fd02dc0
[ "MIT" ]
12
2021-06-30T20:05:33.000Z
2022-01-15T23:10:53.000Z
source/game/host_system/SceneManager.cxx
stblr/mkw-cs
520254ee41c262332fd2fe429a9364202fd02dc0
[ "MIT" ]
13
2021-07-04T10:06:07.000Z
2021-11-07T22:41:34.000Z
source/game/host_system/SceneManager.cxx
stblr/mkw-cs
520254ee41c262332fd2fe429a9364202fd02dc0
[ "MIT" ]
null
null
null
#include "SceneManager.hxx" namespace System { void SceneManager::my_changeSceneWithCreator(s32 sceneId, EGG::SceneCreator *creator) { m_creator = creator; changeSiblingScene(sceneId); } } // namespace System REPLACE(changeSceneWithCreator__Q26System12SceneManagerFlPQ23EGG12SceneCreator);
23.230769
87
0.804636
stblr
073bbe665f0eb80791d35a3390cbca720c51f76f
1,683
cpp
C++
LAB6/LAB6/Circuit.cpp
florinERotaru/oop-et-al
750af01be09967e4112e7c783439fe2bdc0a11ce
[ "MIT" ]
null
null
null
LAB6/LAB6/Circuit.cpp
florinERotaru/oop-et-al
750af01be09967e4112e7c783439fe2bdc0a11ce
[ "MIT" ]
null
null
null
LAB6/LAB6/Circuit.cpp
florinERotaru/oop-et-al
750af01be09967e4112e7c783439fe2bdc0a11ce
[ "MIT" ]
null
null
null
#include "Circuit.h" #include <iostream> Circuit::Circuit() { carsNumber = 0; // stoppedNumber = 0; } void Circuit::AddCar(Car* model) { cars[carsNumber++] = model; //pun adresa direct } //void Circuit::AddStopped(Car* model) { // stopped[stoppedNumber++] = model; //} void Circuit::SetWeather(int weather) { this->weather= weather; } void Circuit::SetLength(int length) { this->length = length; } void Circuit::Race() { int last = carsNumber; while (last != 0) { int n = last; last = 0; for (int i = 0; i < n - 1; i++) if ((Result(cars[i]) > 0) && Result(cars[i]) > Result(cars[i + 1])) { Car* temp; temp = cars[i]; cars[i] = cars[i + 1]; cars[i + 1] = temp; last=i; } } } void Circuit::ShowFinalRanks() { int poz = 1; for (int i = 0; i < carsNumber; i++) if (Result(cars[i]) > 0) std::cout << "Pe locul " << poz++ << " "<< cars[i]->name << " timp: " << Result(cars[i])<<" ore " << std::endl; } float Circuit::Result(Car* candidate) { float consum = length / 100; int fuelUsed = candidate->getFuelCons()*consum; if (fuelUsed > candidate->getFuelCap()) return -1; return (float)(length / candidate->avgSpeed(weather)); } void Circuit::ShowWhoDidNotFinish() { std::cout << "Nu au reusit:" << std::endl; for (int i = 0; i < carsNumber; i++) if (Result(cars[i]) < 0) std::cout << cars[i]->name << "(capac.: " << cars[i]->getFuelCap() << "litri, are nevoide de "<<(float)cars[i]->getFuelCons()*(length/100)<<")"<<std::endl; }
26.714286
167
0.52347
florinERotaru
074357f99cac48070d29f37d6bdf8191dbe7d9e3
65,289
cpp
C++
src/Backends/Helmholtz/TransportRoutines.cpp
friederikeboehm/CoolProp
44325d9e6abd9e6f88f428720f4f64a0c1962784
[ "MIT" ]
null
null
null
src/Backends/Helmholtz/TransportRoutines.cpp
friederikeboehm/CoolProp
44325d9e6abd9e6f88f428720f4f64a0c1962784
[ "MIT" ]
null
null
null
src/Backends/Helmholtz/TransportRoutines.cpp
friederikeboehm/CoolProp
44325d9e6abd9e6f88f428720f4f64a0c1962784
[ "MIT" ]
null
null
null
#include "TransportRoutines.h" #include "CoolPropFluid.h" namespace CoolProp { CoolPropDbl TransportRoutines::viscosity_dilute_kinetic_theory(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { CoolPropDbl Tstar = HEOS.T() / HEOS.components[0].transport.epsilon_over_k; CoolPropDbl sigma_nm = HEOS.components[0].transport.sigma_eta * 1e9; // 1e9 to convert from m to nm CoolPropDbl molar_mass_kgkmol = HEOS.molar_mass() * 1000; // 1000 to convert from kg/mol to kg/kmol // The nondimensional empirical collision integral from Neufeld // Neufeld, P. D.; Janzen, A. R.; Aziz, R. A. Empirical Equations to Calculate 16 of the Transport Collision Integrals (l,s)* // for the Lennard-Jones (12-6) Potential. J. Chem. Phys. 1972, 57, 1100-1102 CoolPropDbl OMEGA22 = 1.16145 * pow(Tstar, static_cast<CoolPropDbl>(-0.14874)) + 0.52487 * exp(-0.77320 * Tstar) + 2.16178 * exp(-2.43787 * Tstar); // The dilute gas component - return 26.692e-9 * sqrt(molar_mass_kgkmol * HEOS.T()) / (pow(sigma_nm, 2) * OMEGA22); // Pa-s } else { throw NotImplementedError("TransportRoutines::viscosity_dilute_kinetic_theory is only for pure and pseudo-pure"); } } CoolPropDbl TransportRoutines::viscosity_dilute_collision_integral(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { // Retrieve values from the state class CoolProp::ViscosityDiluteGasCollisionIntegralData& data = HEOS.components[0].transport.viscosity_dilute.collision_integral; const std::vector<CoolPropDbl>&a = data.a, &t = data.t; const CoolPropDbl C = data.C, molar_mass = data.molar_mass; CoolPropDbl S; // Unit conversions and variable definitions const CoolPropDbl Tstar = HEOS.T() / HEOS.components[0].transport.epsilon_over_k; const CoolPropDbl sigma_nm = HEOS.components[0].transport.sigma_eta * 1e9; // 1e9 to convert from m to nm const CoolPropDbl molar_mass_kgkmol = molar_mass * 1000; // 1000 to convert from kg/mol to kg/kmol /// Both the collision integral \f$\mathfrak{S}^*\f$ and effective cross section \f$\Omega^{(2,2)}\f$ have the same form, /// in general we don't care which is used. The are related through \f$\Omega^{(2,2)} = (5/4)\mathfrak{S}^*\f$ /// see Vesovic(JPCRD, 1990) for CO\f$_2\f$ for further information CoolPropDbl summer = 0, lnTstar = log(Tstar); for (std::size_t i = 0; i < a.size(); ++i) { summer += a[i] * pow(lnTstar, t[i]); } S = exp(summer); // The dilute gas component return C * sqrt(molar_mass_kgkmol * HEOS.T()) / (pow(sigma_nm, 2) * S); // Pa-s } else { throw NotImplementedError("TransportRoutines::viscosity_dilute_collision_integral is only for pure and pseudo-pure"); } } CoolPropDbl TransportRoutines::viscosity_dilute_powers_of_T(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { // Retrieve values from the state class CoolProp::ViscosityDiluteGasPowersOfT& data = HEOS.components[0].transport.viscosity_dilute.powers_of_T; const std::vector<CoolPropDbl>&a = data.a, &t = data.t; CoolPropDbl summer = 0, T = HEOS.T(); for (std::size_t i = 0; i < a.size(); ++i) { summer += a[i] * pow(T, t[i]); } return summer; } else { throw NotImplementedError("TransportRoutines::viscosity_dilute_powers_of_T is only for pure and pseudo-pure"); } } CoolPropDbl TransportRoutines::viscosity_dilute_powers_of_Tr(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { // Retrieve values from the state class CoolProp::ViscosityDiluteGasPowersOfTr& data = HEOS.components[0].transport.viscosity_dilute.powers_of_Tr; const std::vector<CoolPropDbl>&a = data.a, &t = data.t; CoolPropDbl summer = 0, Tr = HEOS.T() / data.T_reducing; for (std::size_t i = 0; i < a.size(); ++i) { summer += a[i] * pow(Tr, t[i]); } return summer; } else { throw NotImplementedError("TransportRoutines::viscosity_dilute_powers_of_Tr is only for pure and pseudo-pure"); } } CoolPropDbl TransportRoutines::viscosity_dilute_collision_integral_powers_of_T(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { // Retrieve values from the state class CoolProp::ViscosityDiluteCollisionIntegralPowersOfTstarData& data = HEOS.components[0].transport.viscosity_dilute.collision_integral_powers_of_Tstar; const std::vector<CoolPropDbl>&a = data.a, &t = data.t; CoolPropDbl summer = 0, Tstar = HEOS.T() / data.T_reducing; for (std::size_t i = 0; i < a.size(); ++i) { summer += a[i] * pow(Tstar, t[i]); } return data.C * sqrt(HEOS.T()) / summer; } else { throw NotImplementedError("TransportRoutines::viscosity_dilute_collision_integral_powers_of_T is only for pure and pseudo-pure"); } } CoolPropDbl TransportRoutines::viscosity_higher_order_modified_Batschinski_Hildebrand(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { CoolProp::ViscosityModifiedBatschinskiHildebrandData& HO = HEOS.components[0].transport.viscosity_higher_order.modified_Batschinski_Hildebrand; CoolPropDbl delta = HEOS.rhomolar() / HO.rhomolar_reduce, tau = HO.T_reduce / HEOS.T(); // The first term that is formed of powers of tau (Tc/T) and delta (rho/rhoc) CoolPropDbl S = 0; for (unsigned int i = 0; i < HO.a.size(); ++i) { S += HO.a[i] * pow(delta, HO.d1[i]) * pow(tau, HO.t1[i]) * exp(HO.gamma[i] * pow(delta, HO.l[i])); } // For the terms that multiplies the bracketed term with delta and delta0 CoolPropDbl F = 0; for (unsigned int i = 0; i < HO.f.size(); ++i) { F += HO.f[i] * pow(delta, HO.d2[i]) * pow(tau, HO.t2[i]); } // for delta_0 CoolPropDbl summer_numer = 0; for (unsigned int i = 0; i < HO.g.size(); ++i) { summer_numer += HO.g[i] * pow(tau, HO.h[i]); } CoolPropDbl summer_denom = 0; for (unsigned int i = 0; i < HO.p.size(); ++i) { summer_denom += HO.p[i] * pow(tau, HO.q[i]); } CoolPropDbl delta0 = summer_numer / summer_denom; // The higher-order-term component return S + F * (1 / (delta0 - delta) - 1 / delta0); // Pa-s } else { throw NotImplementedError("TransportRoutines::viscosity_higher_order_modified_Batschinski_Hildebrand is only for pure and pseudo-pure"); } } CoolPropDbl TransportRoutines::viscosity_initial_density_dependence_Rainwater_Friend(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { // Retrieve values from the state class CoolProp::ViscosityRainWaterFriendData& data = HEOS.components[0].transport.viscosity_initial.rainwater_friend; const std::vector<CoolPropDbl>&b = data.b, &t = data.t; CoolPropDbl B_eta, B_eta_star; CoolPropDbl Tstar = HEOS.T() / HEOS.components[0].transport.epsilon_over_k; // [no units] CoolPropDbl sigma = HEOS.components[0].transport.sigma_eta; // [m] CoolPropDbl summer = 0; for (unsigned int i = 0; i < b.size(); ++i) { summer += b[i] * pow(Tstar, t[i]); } B_eta_star = summer; // [no units] B_eta = 6.02214129e23 * pow(sigma, 3) * B_eta_star; // [m^3/mol] return B_eta; // [m^3/mol] } else { throw NotImplementedError("TransportRoutines::viscosity_initial_density_dependence_Rainwater_Friend is only for pure and pseudo-pure"); } } CoolPropDbl TransportRoutines::viscosity_initial_density_dependence_empirical(HelmholtzEOSMixtureBackend& HEOS) { // Inspired by the form from Tariq, JPCRD, 2014 if (HEOS.is_pure_or_pseudopure) { // Retrieve values from the state class CoolProp::ViscosityInitialDensityEmpiricalData& data = HEOS.components[0].transport.viscosity_initial.empirical; const std::vector<CoolPropDbl>&n = data.n, &d = data.d, &t = data.t; CoolPropDbl tau = data.T_reducing / HEOS.T(); // [no units] CoolPropDbl delta = HEOS.rhomolar() / data.rhomolar_reducing; // [no units] CoolPropDbl summer = 0; for (unsigned int i = 0; i < n.size(); ++i) { summer += n[i] * pow(delta, d[i]) * pow(tau, t[i]); } return summer; // [Pa-s] } else { throw NotImplementedError("TransportRoutines::viscosity_initial_density_dependence_empirical is only for pure and pseudo-pure"); } } static void visc_Helper(double Tbar, double rhobar, double* mubar_0, double* mubar_1) { std::vector<std::vector<CoolPropDbl>> H(6, std::vector<CoolPropDbl>(7, 0)); double sum; int i, j; // Dilute-gas component *mubar_0 = 100.0 * sqrt(Tbar) / (1.67752 + 2.20462 / Tbar + 0.6366564 / powInt(Tbar, 2) - 0.241605 / powInt(Tbar, 3)); //Fill in zeros in H for (i = 0; i <= 5; i++) { for (j = 0; j <= 6; j++) { H[i][j] = 0; } } //Set non-zero parameters of H H[0][0] = 5.20094e-1; H[1][0] = 8.50895e-2; H[2][0] = -1.08374; H[3][0] = -2.89555e-1; H[0][1] = 2.22531e-1; H[1][1] = 9.99115e-1; H[2][1] = 1.88797; H[3][1] = 1.26613; H[5][1] = 1.20573e-1; H[0][2] = -2.81378e-1; H[1][2] = -9.06851e-1; H[2][2] = -7.72479e-1; H[3][2] = -4.89837e-1; H[4][2] = -2.57040e-1; H[0][3] = 1.61913e-1; H[1][3] = 2.57399e-1; H[0][4] = -3.25372e-2; H[3][4] = 6.98452e-2; H[4][5] = 8.72102e-3; H[3][6] = -4.35673e-3; H[5][6] = -5.93264e-4; // Finite density component sum = 0; for (i = 0; i <= 5; i++) { for (j = 0; j <= 6; j++) { sum += powInt(1 / Tbar - 1, i) * (H[i][j] * powInt(rhobar - 1, j)); } } *mubar_1 = exp(rhobar * sum); } CoolPropDbl TransportRoutines::viscosity_heavywater_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { double Tbar = HEOS.T() / 643.847, rhobar = HEOS.rhomass() / 358; double A[] = {1.000000, 0.940695, 0.578377, -0.202044}; int I[] = {0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 0, 1, 2, 5, 0, 1, 2, 3, 0, 1, 3, 5, 0, 1, 5, 3}; int J[] = {0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6}; double Bij[] = {0.4864192, -0.2448372, -0.8702035, 0.8716056, -1.051126, 0.3458395, 0.3509007, 1.315436, 1.297752, 1.353448, -0.2847572, -1.037026, -1.287846, -0.02148229, 0.07013759, 0.4660127, 0.2292075, -0.4857462, 0.01641220, -0.02884911, 0.1607171, -0.009603846, -0.01163815, -0.008239587, 0.004559914, -0.003886659}; double mu0 = sqrt(Tbar) / (A[0] + A[1] / Tbar + A[2] / POW2(Tbar) + A[3] / POW3(Tbar)); double summer = 0; for (int i = 0; i < 26; ++i) { summer += Bij[i] * pow(1 / Tbar - 1, I[i]) * pow(rhobar - 1, J[i]); } double mu1 = exp(rhobar * summer); double mubar = mu0 * mu1; return 55.2651e-6 * mubar; } CoolPropDbl TransportRoutines::viscosity_water_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { double x_mu = 0.068, qc = 1 / 1.9, qd = 1 / 1.1, nu = 0.630, gamma = 1.239, zeta_0 = 0.13, LAMBDA_0 = 0.06, Tbar_R = 1.5, pstar, Tstar, rhostar; double delta, tau, mubar_0, mubar_1, mubar_2, drhodp, drhodp_R, DeltaChibar, zeta, w, L, Y, psi_D, Tbar, rhobar; double drhobar_dpbar, drhobar_dpbar_R, R_Water; pstar = 22.064e6; // [Pa] Tstar = 647.096; // [K] rhostar = 322; // [kg/m^3] Tbar = HEOS.T() / Tstar; rhobar = HEOS.rhomass() / rhostar; R_Water = HEOS.gas_constant() / HEOS.molar_mass(); // [J/kg/K] // Dilute and finite gas portions visc_Helper(Tbar, rhobar, &mubar_0, &mubar_1); // ********************************************************************** // ************************ Critical Enhancement ************************ // ********************************************************************** delta = rhobar; // "Normal" calculation drhodp = 1 / (R_Water * HEOS.T() * (1 + 2 * delta * HEOS.dalphar_dDelta() + delta * delta * HEOS.d2alphar_dDelta2())); drhobar_dpbar = pstar / rhostar * drhodp; // "Reducing" calculation tau = 1 / Tbar_R; drhodp_R = 1 / (R_Water * Tbar_R * Tstar * (1 + 2 * rhobar * HEOS.calc_alphar_deriv_nocache(0, 1, HEOS.mole_fractions, tau, delta) + delta * delta * HEOS.calc_alphar_deriv_nocache(0, 2, HEOS.mole_fractions, tau, delta))); drhobar_dpbar_R = pstar / rhostar * drhodp_R; DeltaChibar = rhobar * (drhobar_dpbar - drhobar_dpbar_R * Tbar_R / Tbar); if (DeltaChibar < 0) DeltaChibar = 0; zeta = zeta_0 * pow(DeltaChibar / LAMBDA_0, nu / gamma); if (zeta < 0.3817016416) { Y = 1.0 / 5.0 * qc * zeta * powInt(qd * zeta, 5) * (1 - qc * zeta + powInt(qc * zeta, 2) - 765.0 / 504.0 * powInt(qd * zeta, 2)); } else { psi_D = acos(pow(1 + powInt(qd * zeta, 2), -1.0 / 2.0)); w = sqrt(std::abs((qc * zeta - 1) / (qc * zeta + 1))) * tan(psi_D / 2.0); if (qc * zeta > 1) { L = log((1 + w) / (1 - w)); } else { L = 2 * atan(std::abs(w)); } Y = 1.0 / 12.0 * sin(3 * psi_D) - 1 / (4 * qc * zeta) * sin(2 * psi_D) + 1.0 / powInt(qc * zeta, 2) * (1 - 5.0 / 4.0 * powInt(qc * zeta, 2)) * sin(psi_D) - 1.0 / powInt(qc * zeta, 3) * ((1 - 3.0 / 2.0 * powInt(qc * zeta, 2)) * psi_D - pow(std::abs(powInt(qc * zeta, 2) - 1), 3.0 / 2.0) * L); } mubar_2 = exp(x_mu * Y); return (mubar_0 * mubar_1 * mubar_2) / 1e6; } CoolPropDbl TransportRoutines::viscosity_toluene_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { CoolPropDbl Tr = HEOS.T() / 591.75, rhor = HEOS.keyed_output(CoolProp::iDmass) / 291.987; CoolPropDbl c[] = {19.919216, -2.6557905, -135.904211, -7.9962719, -11.014795, -10.113817}; return 1e-6 * pow(static_cast<double>(rhor), 2.0 / 3.0) * sqrt(Tr) * ((c[0] * rhor + c[1] * pow(rhor, 4)) / Tr + c[2] * rhor * rhor * rhor / (rhor * rhor + c[3] + c[4] * Tr) + c[5] * rhor); } CoolPropDbl TransportRoutines::viscosity_hydrogen_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { CoolPropDbl Tr = HEOS.T() / 33.145, rhor = HEOS.keyed_output(CoolProp::iDmass) * 0.011; CoolPropDbl c[] = {0, 6.43449673e-6, 4.56334068e-2, 2.32797868e-1, 9.58326120e-1, 1.27941189e-1, 3.63576595e-1}; return c[1] * pow(rhor, 2) * exp(c[2] * Tr + c[3] / Tr + c[4] * pow(rhor, 2) / (c[5] + Tr) + c[6] * pow(rhor, 6)); } CoolPropDbl TransportRoutines::viscosity_benzene_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { CoolPropDbl Tr = HEOS.T() / 562.02, rhor = HEOS.rhomass() / 304.792; CoolPropDbl c[] = {-9.98945, 86.06260, 2.74872, 1.11130, -1.0, -134.1330, -352.473, 6.60989, 88.4174}; return 1e-6 * pow(rhor, static_cast<CoolPropDbl>(2.0 / 3.0)) * sqrt(Tr) * (c[0] * pow(rhor, 2) + c[1] * rhor / (c[2] + c[3] * Tr + c[4] * rhor) + (c[5] * rhor + c[6] * pow(rhor, 2)) / (c[7] + c[8] * pow(rhor, 2))); } CoolPropDbl TransportRoutines::viscosity_hexane_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { CoolPropDbl Tr = HEOS.T() / 507.82, rhor = HEOS.keyed_output(CoolProp::iDmass) / 233.182; // Output is in Pa-s double c[] = {2.53402335 / 1e6, -9.724061002 / 1e6, 0.469437316, 158.5571631, 72.42916856 / 1e6, 10.60751253, 8.628373915, -6.61346441, -2.212724566}; return pow(rhor, static_cast<CoolPropDbl>(2.0 / 3.0)) * sqrt(Tr) * (c[0] / Tr + c[1] / (c[2] + Tr + c[3] * rhor * rhor) + c[4] * (1 + rhor) / (c[5] + c[6] * Tr + c[7] * rhor + rhor * rhor + c[8] * rhor * Tr)); } CoolPropDbl TransportRoutines::viscosity_heptane_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { /// From Michailidou-JPCRD-2014-Heptane CoolPropDbl Tr = HEOS.T() / 540.13, rhor = HEOS.rhomass() / 232; // Output is in Pa-s double c[] = {0, 22.15000 / 1e6, -15.00870 / 1e6, 3.71791 / 1e6, 77.72818 / 1e6, 9.73449, 9.51900, -6.34076, -2.51909}; return pow(rhor, static_cast<CoolPropDbl>(2.0L / 3.0L)) * sqrt(Tr) * (c[1] * rhor + c[2] * pow(rhor, 2) + c[3] * pow(rhor, 3) + c[4] * rhor / (c[5] + c[6] * Tr + c[7] * rhor + rhor * rhor + c[8] * rhor * Tr)); } CoolPropDbl TransportRoutines::viscosity_higher_order_friction_theory(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { CoolProp::ViscosityFrictionTheoryData& F = HEOS.components[0].transport.viscosity_higher_order.friction_theory; CoolPropDbl tau = F.T_reduce / HEOS.T(), kii = 0, krrr = 0, kaaa = 0, krr, kdrdr; double psi1 = exp(tau) - F.c1; double psi2 = exp(pow(tau, 2)) - F.c2; double ki = (F.Ai[0] + F.Ai[1] * psi1 + F.Ai[2] * psi2) * tau; double ka = (F.Aa[0] + F.Aa[1] * psi1 + F.Aa[2] * psi2) * pow(tau, F.Na); double kr = (F.Ar[0] + F.Ar[1] * psi1 + F.Ar[2] * psi2) * pow(tau, F.Nr); double kaa = (F.Aaa[0] + F.Aaa[1] * psi1 + F.Aaa[2] * psi2) * pow(tau, F.Naa); if (F.Arr.empty()) { krr = 0; kdrdr = (F.Adrdr[0] + F.Adrdr[1] * psi1 + F.Adrdr[2] * psi2) * pow(tau, F.Nrr); } else { krr = (F.Arr[0] + F.Arr[1] * psi1 + F.Arr[2] * psi2) * pow(tau, F.Nrr); kdrdr = 0; } if (!F.Aii.empty()) { kii = (F.Aii[0] + F.Aii[1] * psi1 + F.Aii[2] * psi2) * pow(tau, F.Nii); } if (!F.Arrr.empty() && !F.Aaaa.empty()) { krrr = (F.Arrr[0] + F.Arrr[1] * psi1 + F.Arrr[2] * psi2) * pow(tau, F.Nrrr); kaaa = (F.Aaaa[0] + F.Aaaa[1] * psi1 + F.Aaaa[2] * psi2) * pow(tau, F.Naaa); } double p = HEOS.p() / 1e5; // [bar]; 1e5 for conversion from Pa -> bar double pr = HEOS.T() * HEOS.first_partial_deriv(CoolProp::iP, CoolProp::iT, CoolProp::iDmolar) / 1e5; // [bar/K]; 1e5 for conversion from Pa -> bar double pa = p - pr; //[bar] double pid = HEOS.rhomolar() * HEOS.gas_constant() * HEOS.T() / 1e5; // [bar]; 1e5 for conversion from Pa -> bar double deltapr = pr - pid; double eta_f = ka * pa + kr * deltapr + ki * pid + kaa * pa * pa + kdrdr * deltapr * deltapr + krr * pr * pr + kii * pid * pid + krrr * pr * pr * pr + kaaa * pa * pa * pa; return eta_f; //[Pa-s] } else { throw NotImplementedError("TransportRoutines::viscosity_higher_order_friction_theory is only for pure and pseudo-pure"); } } CoolPropDbl TransportRoutines::viscosity_helium_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { double eta_0, eta_0_slash, eta_E_slash, B, C, D, ln_eta, x; // // Arp, V.D., McCarty, R.D., and Friend, D.G., // "Thermophysical Properties of Helium-4 from 0.8 to 1500 K with Pressures to 2000 MPa", // NIST Technical Note 1334 (revised), 1998. // // Using Arp NIST report // Report is not clear on viscosity, referring to REFPROP source code for clarity // Correlation wants density in g/cm^3; kg/m^3 --> g/cm^3, divide by 1000 CoolPropDbl rho = HEOS.keyed_output(CoolProp::iDmass) / 1000.0, T = HEOS.T(); if (T <= 300) { x = log(T); } else { x = log(300.0); } // Evaluate the terms B,C,D B = -47.5295259 / x + 87.6799309 - 42.0741589 * x + 8.33128289 * x * x - 0.589252385 * x * x * x; C = 547.309267 / x - 904.870586 + 431.404928 * x - 81.4504854 * x * x + 5.37008433 * x * x * x; D = -1684.39324 / x + 3331.08630 - 1632.19172 * x + 308.804413 * x * x - 20.2936367 * x * x * x; eta_0_slash = -0.135311743 / x + 1.00347841 + 1.20654649 * x - 0.149564551 * x * x + 0.012520841 * x * x * x; eta_E_slash = rho * B + rho * rho * C + rho * rho * rho * D; if (T <= 100) { ln_eta = eta_0_slash + eta_E_slash; // Correlation yields viscosity in micro g/(cm-s); to get Pa-s, divide by 10 to get micro Pa-s, then another 1e6 to get Pa-s return exp(ln_eta) / 10.0 / 1e6; } else { ln_eta = eta_0_slash + eta_E_slash; eta_0 = 196 * pow(T, static_cast<CoolPropDbl>(0.71938)) * exp(12.451 / T - 295.67 / T / T - 4.1249); // Correlation yields viscosity in micro g/(cm-s); to get Pa-s, divide by 10 to get micro Pa-s, then another 1e6 to get Pa-s return (exp(ln_eta) + eta_0 - exp(eta_0_slash)) / 10.0 / 1e6; } } CoolPropDbl TransportRoutines::viscosity_methanol_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { CoolPropDbl B_eta, C_eta, epsilon_over_k = 577.87, /* [K]*/ sigma0 = 0.3408e-9, /* [m] */ delta = 0.4575, /* NOT the reduced density, that is rhor here*/ N_A = 6.02214129e23, M = 32.04216, /* kg/kmol */ T = HEOS.T(); CoolPropDbl rhomolar = HEOS.rhomolar(); CoolPropDbl B_eta_star, C_eta_star; CoolPropDbl Tstar = T / epsilon_over_k; // [no units] CoolPropDbl rhor = HEOS.rhomass() / 273; CoolPropDbl Tr = T / 512.6; // Rainwater-Friend initial density terms { // Scoped here so that we can re-use the b variable CoolPropDbl b[9] = {-19.572881, 219.73999, -1015.3226, 2471.01251, -3375.1717, 2491.6597, -787.26086, 14.085455, -0.34664158}; CoolPropDbl t[9] = {0, -0.25, -0.5, -0.75, -1.0, -1.25, -1.5, -2.5, -5.5}; CoolPropDbl summer = 0; for (unsigned int i = 0; i < 9; ++i) { summer += b[i] * pow(Tstar, t[i]); } B_eta_star = summer; // [no units] B_eta = N_A * pow(sigma0, 3) * B_eta_star; // [m^3/mol] CoolPropDbl c[2] = {1.86222085e-3, 9.990338}; C_eta_star = c[0] * pow(Tstar, 3) * exp(c[1] * pow(Tstar, static_cast<CoolPropDbl>(-0.5))); // [no units] C_eta = pow(N_A * pow(sigma0, 3), 2) * C_eta_star; // [m^6/mol^2] } CoolPropDbl eta_g = 1 + B_eta * rhomolar + C_eta * rhomolar * rhomolar; CoolPropDbl a[13] = {1.16145, -0.14874, 0.52487, -0.77320, 2.16178, -2.43787, 0.95976e-3, 0.10225, -0.97346, 0.10657, -0.34528, -0.44557, -2.58055}; CoolPropDbl d[7] = {-1.181909, 0.5031030, -0.6268461, 0.5169312, -0.2351349, 5.3980235e-2, -4.9069617e-3}; CoolPropDbl e[10] = {0, 4.018368, -4.239180, 2.245110, -0.5750698, 2.3021026e-2, 2.5696775e-2, -6.8372749e-3, 7.2707189e-4, -2.9255711e-5}; CoolPropDbl OMEGA_22_star_LJ = a[0] * pow(Tstar, a[1]) + a[2] * exp(a[3] * Tstar) + a[4] * exp(a[5] * Tstar); CoolPropDbl OMEGA_22_star_delta = a[7] * pow(Tstar, a[8]) + a[9] * exp(a[10] * Tstar) + a[11] * exp(a[12] * Tstar); CoolPropDbl OMEGA_22_star_SM = OMEGA_22_star_LJ * (1 + pow(delta, 2) / (1 + a[6] * pow(delta, 6)) * OMEGA_22_star_delta); CoolPropDbl eta_0 = 2.66957e-26 * sqrt(M * T) / (pow(sigma0, 2) * OMEGA_22_star_SM); CoolPropDbl summerd = 0; for (int i = 0; i < 7; ++i) { summerd += d[i] / pow(Tr, i); } for (int j = 1; j < 10; ++j) { summerd += e[j] * pow(rhor, j); } CoolPropDbl sigmac = 0.7193422e-9; // [m] CoolPropDbl sigma_HS = summerd * sigmac; // [m] CoolPropDbl b = 2 * M_PI * N_A * pow(sigma_HS, 3) / 3; // [m^3/mol] CoolPropDbl zeta = b * rhomolar / 4; // [-] CoolPropDbl g_sigma_HS = (1 - 0.5 * zeta) / pow(1 - zeta, 3); // [-] CoolPropDbl eta_E = 1 / g_sigma_HS + 0.8 * b * rhomolar + 0.761 * g_sigma_HS * pow(b * rhomolar, 2); // [-] CoolPropDbl f = 1 / (1 + exp(5 * (rhor - 1))); return eta_0 * (f * eta_g + (1 - f) * eta_E); } CoolPropDbl TransportRoutines::viscosity_R23_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { double C1 = 1.3163, // C2 = 0.1832, DeltaGstar = 771.23, rhoL = 32.174, rhocbar = 7.5114, Tc = 299.2793, DELTAeta_max = 3.967, Ru = 8.31451, molar_mass = 70.014; double a[] = {0.4425728, -0.5138403, 0.1547566, -0.02821844, 0.001578286}; double e_k = 243.91, sigma = 0.4278; double Tstar = HEOS.T() / e_k; double logTstar = log(Tstar); double Omega = exp(a[0] + a[1] * logTstar + a[2] * pow(logTstar, 2) + a[3] * pow(logTstar, 3) + a[4] * pow(logTstar, 4)); double eta_DG = 1.25 * 0.021357 * sqrt(molar_mass * HEOS.T()) / (sigma * sigma * Omega); // uPa-s double rhobar = HEOS.rhomolar() / 1000; // [mol/L] double eta_L = C2 * (rhoL * rhoL) / (rhoL - rhobar) * sqrt(HEOS.T()) * exp(rhobar / (rhoL - rhobar) * DeltaGstar / (Ru * HEOS.T())); double chi = rhobar - rhocbar; double tau = HEOS.T() - Tc; double DELTAeta_c = 4 * DELTAeta_max / ((exp(chi) + exp(-chi)) * (exp(tau) + exp(-tau))); return (pow((rhoL - rhobar) / rhoL, C1) * eta_DG + pow(rhobar / rhoL, C1) * eta_L + DELTAeta_c) / 1e6; } CoolPropDbl TransportRoutines::viscosity_o_xylene_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { // From CAO, JPCRD, 2016 double D[] = {-2.05581e-3, 2.38762, 0, 10.4497, 15.9587}; double n[] = {10.3, 3.3, 25, 0.7, 0.4}; double E[] = {2.65651e-3, 0, 1.77616e-12, -18.2446, 0}; double k[] = {0.8, 0, 4.4}; double Tr = HEOS.T() / 630.259, rhor = HEOS.rhomolar() / 1000.0 / 2.6845; double A0 = -1.4933, B0 = 473.2, C0 = -57033, T = HEOS.T(); double ln_Seta = A0 + B0 / T + C0 / (T * T); double eta0 = 0.22225 * sqrt(T) / exp(ln_Seta); // [uPa-s] double A1 = 13.2814, B1 = -10862.4, C1 = 1664060, rho_molL = HEOS.rhomolar() / 1000.0; double eta1 = (A1 + B1 / T + C1 / (T * T)) * rho_molL; // [uPa-s] double f = (D[0] + E[0] * pow(Tr, -k[0])) * pow(rhor, n[0]) + D[1] * pow(rhor, n[1]) + E[2] * pow(rhor, n[2]) / pow(Tr, k[2]) + (D[3] * rhor + E[3] * Tr) * pow(rhor, n[3]) + D[4] * pow(rhor, n[4]); double DELTAeta = pow(rhor, 2.0 / 3.0) * sqrt(Tr) * f; // [uPa-s] return (eta0 + eta1 + DELTAeta) / 1e6; } CoolPropDbl TransportRoutines::viscosity_m_xylene_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { // From CAO, JPCRD, 2016 double D[] = {-0.268950, -0.0290018, 0, 14.7728, 17.1128}; double n[] = {6.8, 3.3, 22.0, 0.6, 0.4}; double E[] = {0.320971, 0, 1.72866e-10, -18.9852, 0}; double k[] = {0.3, 0, 3.2}; double Tr = HEOS.T() / 616.89, rhor = HEOS.rhomolar() / 1000.0 / 2.665; double A0 = -1.4933, B0 = 473.2, C0 = -57033, T = HEOS.T(); double ln_Seta = A0 + B0 / T + C0 / (T * T); double eta0 = 0.22115 * sqrt(T) / exp(ln_Seta); // [uPa-s] double A1 = 13.2814, B1 = -10862.4, C1 = 1664060, rho_molL = HEOS.rhomolar() / 1000.0; double eta1 = (A1 + B1 / T + C1 / (T * T)) * rho_molL; // [uPa-s] double f = (D[0] + E[0] * pow(Tr, -k[0])) * pow(rhor, n[0]) + D[1] * pow(rhor, n[1]) + E[2] * pow(rhor, n[2]) / pow(Tr, k[2]) + (D[3] * rhor + E[3] * Tr) * pow(rhor, n[3]) + D[4] * pow(rhor, n[4]); double DELTAeta = pow(rhor, 2.0 / 3.0) * sqrt(Tr) * f; // [uPa-s] return (eta0 + eta1 + DELTAeta) / 1e6; // [Pa-s] } CoolPropDbl TransportRoutines::viscosity_p_xylene_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { // From Balogun, JPCRD, 2016 double Tr = HEOS.T() / 616.168, rhor = HEOS.rhomolar() / 1000.0 / 2.69392; double A0 = -1.4933, B0 = 473.2, C0 = -57033, T = HEOS.T(); double ln_Seta = A0 + B0 / T + C0 / (T * T); double eta0 = 0.22005 * sqrt(T) / exp(ln_Seta); // [uPa-s] double A1 = 13.2814, B1 = -10862.4, C1 = 1664060, rho_molL = HEOS.rhomolar() / 1000.0; double eta1 = (A1 + B1 / T + C1 / (T * T)) * rho_molL; // [uPa-s] double sum1 = 122.919 * pow(rhor, 1.5) - 282.329 * pow(rhor, 2) + 279.348 * pow(rhor, 3) - 146.776 * pow(rhor, 4) + 28.361 * pow(rhor, 5) - 0.004585 * pow(rhor, 11); double sum2 = 15.337 * pow(rhor, 1.5) - 0.0004382 * pow(rhor, 11) + 0.00002307 * pow(rhor, 15); double DELTAeta = pow(rhor, 2.0 / 3.0) * (sum1 + 1 / sqrt(Tr) * sum2); return (eta0 + eta1 + DELTAeta) / 1e6; // [Pa-s] } CoolPropDbl TransportRoutines::viscosity_dilute_ethane(HelmholtzEOSMixtureBackend& HEOS) { double C[] = { 0, -3.0328138281, 16.918880086, -37.189364917, 41.288861858, -24.615921140, 8.9488430959, -1.8739245042, 0.20966101390, -9.6570437074e-3}; double OMEGA_2_2 = 0, e_k = 245, Tstar; Tstar = HEOS.T() / e_k; for (int i = 1; i <= 9; i++) { OMEGA_2_2 += C[i] * pow(Tstar, (i - 1) / 3.0 - 1); } return 12.0085 * sqrt(Tstar) * OMEGA_2_2 / 1e6; //[Pa-s] } CoolPropDbl TransportRoutines::viscosity_dilute_cyclohexane(HelmholtzEOSMixtureBackend& HEOS) { // From Tariq, JPCRD, 2014 CoolPropDbl T = HEOS.T(); CoolPropDbl S_eta = exp(-1.5093 + 364.87 / T - 39537 / pow(T, 2)); //[nm^2] return 0.19592 * sqrt(T) / S_eta / 1e6; //[Pa-s] } CoolPropDbl TransportRoutines::viscosity_ethane_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) { double r[] = {0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 1, 1}; double s[] = {0, 0, 1, 0, 1, 1.5, 0, 2, 0, 1, 0, 1}; double g[] = {0, 0.47177003, -0.23950311, 0.39808301, -0.27343335, 0.35192260, -0.21101308, -0.00478579, 0.07378129, -0.030435255, -0.30435286, 0.001215675}; double sum1 = 0, sum2 = 0, tau = 305.33 / HEOS.T(), delta = HEOS.rhomolar() / 6870; for (int i = 1; i <= 9; ++i) { sum1 += g[i] * pow(delta, r[i]) * pow(tau, s[i]); } for (int i = 10; i <= 11; ++i) { sum2 += g[i] * pow(delta, r[i]) * pow(tau, s[i]); } return 15.977 * sum1 / (1 + sum2) / 1e6; } CoolPropDbl TransportRoutines::viscosity_Chung(HelmholtzEOSMixtureBackend& HEOS) { // Retrieve values from the state class CoolProp::ViscosityChungData& data = HEOS.components[0].transport.viscosity_Chung; double a0[] = {0, 6.32402, 0.12102e-2, 5.28346, 6.62263, 19.74540, -1.89992, 24.27450, 0.79716, -0.23816, 0.68629e-1}; double a1[] = {0, 50.41190, -0.11536e-2, 254.20900, 38.09570, 7.63034, -12.53670, 3.44945, 1.11764, 0.67695e-1, 0.34793}; double a2[] = {0, -51.68010, -0.62571e-2, -168.48100, -8.46414, -14.35440, 4.98529, -11.29130, 0.12348e-1, -0.81630, 0.59256}; double a3[] = {0, 1189.02000, 0.37283e-1, 3898.27000, 31.41780, 31.52670, -18.15070, 69.34660, -4.11661, 4.02528, -0.72663}; double A[11]; if (HEOS.is_pure_or_pseudopure) { double Vc_cm3mol = 1 / (data.rhomolar_critical / 1e6); // [cm^3/mol] double acentric = data.acentric; // [-] double M_gmol = data.molar_mass * 1000.0; // [g/mol] double Tc = data.T_critical; // [K] double mu_D = data.dipole_moment_D; // [D] double kappa = 0; double mu_r = 131.3 * mu_D / sqrt(Vc_cm3mol * Tc); // [-] for (int i = 1; i <= 10; ++i) { A[i] = a0[i] + a1[i] * acentric + a2[i] * pow(mu_r, 4) + a3[i] * kappa; } double F_c = 1 - 0.2756 * acentric + 0.059035 * pow(mu_r, 4) + kappa; // [-] double epsilon_over_k = Tc / 1.2593; // [K] double rho_molcm3 = HEOS.rhomolar() / 1e6; double T = HEOS.T(); double Tstar = T / epsilon_over_k; double Omega_2_2 = 1.16145 * pow(Tstar, -0.14874) + 0.52487 * exp(-0.77320 * Tstar) + 2.16178 * exp(-2.43787 * Tstar) - 6.435e-4 * pow(Tstar, 0.14874) * sin(18.0323 * pow(Tstar, -0.76830) - 7.27371); // [-] double eta0_P = 4.0785e-5 * sqrt(M_gmol * T) / (pow(Vc_cm3mol, 2.0 / 3.0) * Omega_2_2) * F_c; // [P] double Y = rho_molcm3 * Vc_cm3mol / 6.0; double G_1 = (1.0 - 0.5 * Y) / pow(1 - Y, 3); double G_2 = (A[1] * (1 - exp(-A[4] * Y)) / Y + A[2] * G_1 * exp(A[5] * Y) + A[3] * G_1) / (A[1] * A[4] + A[2] + A[3]); double eta_k_P = eta0_P * (1 / G_2 + A[6] * Y); // [P] double eta_p_P = (36.344e-6 * sqrt(M_gmol * Tc) / pow(Vc_cm3mol, 2.0 / 3.0)) * A[7] * pow(Y, 2) * G_2 * exp(A[8] + A[9] / Tstar + A[10] / pow(Tstar, 2)); // [P] return (eta_k_P + eta_p_P) / 10.0; // [P] -> [Pa*s] } else { throw NotImplementedError("TransportRoutines::viscosity_Chung is only for pure and pseudo-pure"); } } CoolPropDbl TransportRoutines::conductivity_dilute_ratio_polynomials(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { // Retrieve values from the state class CoolProp::ConductivityDiluteRatioPolynomialsData& data = HEOS.components[0].transport.conductivity_dilute.ratio_polynomials; CoolPropDbl summer1 = 0, summer2 = 0, Tr = HEOS.T() / data.T_reducing; for (std::size_t i = 0; i < data.A.size(); ++i) { summer1 += data.A[i] * pow(Tr, data.n[i]); } for (std::size_t i = 0; i < data.B.size(); ++i) { summer2 += data.B[i] * pow(Tr, data.m[i]); } return summer1 / summer2; } else { throw NotImplementedError("TransportRoutines::conductivity_dilute_ratio_polynomials is only for pure and pseudo-pure"); } }; CoolPropDbl TransportRoutines::conductivity_residual_polynomial(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { // Retrieve values from the state class CoolProp::ConductivityResidualPolynomialData& data = HEOS.components[0].transport.conductivity_residual.polynomials; CoolPropDbl summer = 0, tau = data.T_reducing / HEOS.T(), delta = HEOS.keyed_output(CoolProp::iDmass) / data.rhomass_reducing; for (std::size_t i = 0; i < data.B.size(); ++i) { summer += data.B[i] * pow(tau, data.t[i]) * pow(delta, data.d[i]); } return summer; } else { throw NotImplementedError("TransportRoutines::conductivity_residual_polynomial is only for pure and pseudo-pure"); } }; CoolPropDbl TransportRoutines::conductivity_residual_polynomial_and_exponential(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { // Retrieve values from the state class CoolProp::ConductivityResidualPolynomialAndExponentialData& data = HEOS.components[0].transport.conductivity_residual.polynomial_and_exponential; CoolPropDbl summer = 0, tau = HEOS.tau(), delta = HEOS.delta(); for (std::size_t i = 0; i < data.A.size(); ++i) { summer += data.A[i] * pow(tau, data.t[i]) * pow(delta, data.d[i]) * exp(-data.gamma[i] * pow(delta, data.l[i])); } return summer; } else { throw NotImplementedError("TransportRoutines::conductivity_residual_polynomial_and_exponential is only for pure and pseudo-pure"); } }; CoolPropDbl TransportRoutines::conductivity_critical_simplified_Olchowy_Sengers(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { // Olchowy and Sengers cross-over term // Retrieve values from the state class CoolProp::ConductivityCriticalSimplifiedOlchowySengersData& data = HEOS.components[0].transport.conductivity_critical.Olchowy_Sengers; double k = data.k, R0 = data.R0, nu = data.nu, gamma = data.gamma, GAMMA = data.GAMMA, zeta0 = data.zeta0, qD = data.qD, Tc = HEOS.get_reducing_state().T, // [K] rhoc = HEOS.get_reducing_state().rhomolar, // [mol/m^3] Pcrit = HEOS.get_reducing_state().p, // [Pa] Tref, // [K] cp, cv, delta, num, zeta, mu, pi = M_PI, OMEGA_tilde, OMEGA_tilde0; if (ValidNumber(data.T_ref)) Tref = data.T_ref; else Tref = 1.5 * Tc; delta = HEOS.delta(); double dp_drho = HEOS.gas_constant() * HEOS.T() * (1 + 2 * delta * HEOS.dalphar_dDelta() + delta * delta * HEOS.d2alphar_dDelta2()); double X = Pcrit / pow(rhoc, 2) * HEOS.rhomolar() / dp_drho; double tau_ref = Tc / Tref; double dp_drho_ref = HEOS.gas_constant() * Tref * (1 + 2 * delta * HEOS.calc_alphar_deriv_nocache(0, 1, HEOS.mole_fractions, tau_ref, delta) + delta * delta * HEOS.calc_alphar_deriv_nocache(0, 2, HEOS.mole_fractions, tau_ref, delta)); double Xref = Pcrit / pow(rhoc, 2) * HEOS.rhomolar() / dp_drho_ref * Tref / HEOS.T(); num = X - Xref; // No critical enhancement if numerator is negative, zero, or just a tiny bit positive due to roundoff // See also Lemmon, IJT, 2004, page 27 if (num < DBL_EPSILON * 10) return 0.0; else zeta = zeta0 * pow(num / GAMMA, nu / gamma); //[m] cp = HEOS.cpmolar(); //[J/mol/K] cv = HEOS.cvmolar(); //[J/mol/K] mu = HEOS.viscosity(); //[Pa-s] OMEGA_tilde = 2.0 / pi * ((cp - cv) / cp * atan(zeta * qD) + cv / cp * (zeta * qD)); //[-] OMEGA_tilde0 = 2.0 / pi * (1.0 - exp(-1.0 / (1.0 / (qD * zeta) + 1.0 / 3.0 * (zeta * qD) * (zeta * qD) / delta / delta))); //[-] double lambda = HEOS.rhomolar() * cp * R0 * k * HEOS.T() / (6 * pi * mu * zeta) * (OMEGA_tilde - OMEGA_tilde0); //[W/m/K] return lambda; //[W/m/K] } else { throw NotImplementedError("TransportRoutines::conductivity_critical_simplified_Olchowy_Sengers is only for pure and pseudo-pure"); } }; CoolPropDbl TransportRoutines::conductivity_critical_hardcoded_R123(HelmholtzEOSMixtureBackend& HEOS) { double a13 = 0.486742e-2, a14 = -100, a15 = -7.08535; return a13 * exp(a14 * pow(HEOS.tau() - 1, 4) + a15 * pow(HEOS.delta() - 1, 2)); }; CoolPropDbl TransportRoutines::conductivity_critical_hardcoded_CO2_ScalabrinJPCRD2006(HelmholtzEOSMixtureBackend& HEOS) { CoolPropDbl nc = 0.775547504e-3 * 4.81384, Tr = HEOS.T() / 304.1282, alpha, rhor = HEOS.keyed_output(iDmass) / 467.6; static CoolPropDbl a[] = {0.0, 3.0, 6.70697, 0.94604, 0.30, 0.30, 0.39751, 0.33791, 0.77963, 0.79857, 0.90, 0.02, 0.20}; // Equation 6 from Scalabrin alpha = 1 - a[10] * acosh(1 + a[11] * pow(pow(1 - Tr, 2), a[12])); // Equation 5 from Scalabrin CoolPropDbl numer = rhor * exp(-pow(rhor, a[1]) / a[1] - pow(a[2] * (Tr - 1), 2) - pow(a[3] * (rhor - 1), 2)); CoolPropDbl braced = (1 - 1 / Tr) + a[4] * pow(pow(rhor - 1, 2), 0.5 / a[5]); CoolPropDbl denom = pow(pow(pow(braced, 2), a[6]) + pow(pow(a[7] * (rhor - alpha), 2), a[8]), a[9]); return nc * numer / denom; } CoolPropDbl TransportRoutines::conductivity_dilute_hardcoded_CO2(HelmholtzEOSMixtureBackend& HEOS) { double e_k = 251.196, Tstar; double b[] = {0.4226159, 0.6280115, -0.5387661, 0.6735941, 0, 0, -0.4362677, 0.2255388}; double c[] = {0, 2.387869e-2, 4.350794, -10.33404, 7.981590, -1.940558}; //Vesovic Eq. 31 [no units] double summer = 0; for (int i = 1; i <= 5; i++) summer += c[i] * pow(HEOS.T() / 100.0, 2 - i); double cint_k = 1.0 + exp(-183.5 / HEOS.T()) * summer; //Vesovic Eq. 12 [no units] double r = sqrt(2.0 / 5.0 * cint_k); // According to REFPROP, 1+r^2 = cp-2.5R. This is unclear to me but seems to suggest that cint/k is the difference // between the ideal gas specific heat and a monatomic specific heat of 5/2*R. Using the form of cint/k from Vesovic // does not yield exactly the correct values Tstar = HEOS.T() / e_k; //Vesovic Eq. 30 [no units] summer = 0; for (int i = 0; i <= 7; i++) summer += b[i] / pow(Tstar, i); double Gstar_lambda = summer; //Vesovic Eq. 29 [W/m/K] double lambda_0 = 0.475598e-3 * sqrt(HEOS.T()) * (1 + r * r) / Gstar_lambda; return lambda_0; } CoolPropDbl TransportRoutines::conductivity_dilute_hardcoded_ethane(HelmholtzEOSMixtureBackend& HEOS) { double e_k = 245.0; double tau = 305.33 / HEOS.T(), Tstar = HEOS.T() / e_k; double fint = 1.7104147 - 0.6936482 / Tstar; double lambda_0 = 0.276505e-3 * (HEOS.calc_viscosity_dilute() * 1e6) * (3.75 - fint * (tau * tau * HEOS.d2alpha0_dTau2() + 1.5)); //[W/m/K] return lambda_0; } CoolPropDbl TransportRoutines::conductivity_dilute_eta0_and_poly(HelmholtzEOSMixtureBackend& HEOS) { if (HEOS.is_pure_or_pseudopure) { CoolProp::ConductivityDiluteEta0AndPolyData& E = HEOS.components[0].transport.conductivity_dilute.eta0_and_poly; double eta0_uPas = HEOS.calc_viscosity_dilute() * 1e6; // [uPa-s] double summer = E.A[0] * eta0_uPas; for (std::size_t i = 1; i < E.A.size(); ++i) summer += E.A[i] * pow(static_cast<CoolPropDbl>(HEOS.tau()), E.t[i]); return summer; } else { throw NotImplementedError("TransportRoutines::conductivity_dilute_eta0_and_poly is only for pure and pseudo-pure"); } } CoolPropDbl TransportRoutines::conductivity_hardcoded_heavywater(HelmholtzEOSMixtureBackend& HEOS) { double Tbar = HEOS.T() / 643.847, rhobar = HEOS.rhomass() / 358; double A[] = {1.00000, 37.3223, 22.5485, 13.0465, 0, -2.60735}; double lambda0 = A[0] + A[1] * Tbar + A[2] * POW2(Tbar) + A[3] * POW3(Tbar) + A[4] * POW4(Tbar) + A[5] * POW5(Tbar); double Be = -2.506, B[] = {-167.310, 483.656, -191.039, 73.0358, -7.57467}; double DELTAlambda = B[0] * (1 - exp(Be * rhobar)) + B[1] * rhobar + B[2] * POW2(rhobar) + B[3] * POW3(rhobar) + B[4] * POW4(rhobar); double f_1 = exp(0.144847 * Tbar + -5.64493 * POW2(Tbar)); double f_2 = exp(-2.80000 * POW2(rhobar - 1)) - 0.080738543 * exp(-17.9430 * POW2(rhobar - 0.125698)); double tau = Tbar / (std::abs(Tbar - 1.1) + 1.1); double f_3 = 1 + exp(60 * (tau - 1) + 20); double f_4 = 1 + exp(100 * (tau - 1) + 15); double DELTAlambda_c = 35429.6 * f_1 * f_2 * (1 + POW2(f_2) * (5000.0e6 * POW4(f_1) / f_3 + 3.5 * f_2 / f_4)); double DELTAlambda_L = -741.112 * pow(f_1, 1.2) * (1 - exp(-pow(rhobar / 2.5, 10))); double lambdabar = lambda0 + DELTAlambda + DELTAlambda_c + DELTAlambda_L; return lambdabar * 0.742128e-3; } CoolPropDbl TransportRoutines::conductivity_hardcoded_water(HelmholtzEOSMixtureBackend& HEOS) { double L[5][6] = {{1.60397357, -0.646013523, 0.111443906, 0.102997357, -0.0504123634, 0.00609859258}, {2.33771842, -2.78843778, 1.53616167, -0.463045512, 0.0832827019, -0.00719201245}, {2.19650529, -4.54580785, 3.55777244, -1.40944978, 0.275418278, -0.0205938816}, {-1.21051378, 1.60812989, -0.621178141, 0.0716373224, 0, 0}, {-2.7203370, 4.57586331, -3.18369245, 1.1168348, -0.19268305, 0.012913842}}; double lambdabar_0, lambdabar_1, lambdabar_2, rhobar, Tbar, sum; double Tstar = 647.096, rhostar = 322, pstar = 22064000, lambdastar = 1e-3, mustar = 1e-6; double xi; int i, j; double R = 461.51805; //[J/kg/K] Tbar = HEOS.T() / Tstar; rhobar = HEOS.keyed_output(CoolProp::iDmass) / rhostar; // Dilute gas contribution lambdabar_0 = sqrt(Tbar) / (2.443221e-3 + 1.323095e-2 / Tbar + 6.770357e-3 / pow(Tbar, 2) - 3.454586e-3 / pow(Tbar, 3) + 4.096266e-4 / pow(Tbar, 4)); sum = 0; for (i = 0; i <= 4; i++) { for (j = 0; j <= 5; j++) { sum += L[i][j] * powInt(1.0 / Tbar - 1.0, i) * powInt(rhobar - 1, j); } } // Finite density contribution lambdabar_1 = exp(rhobar * sum); double nu = 0.630, GAMMA = 177.8514, gamma = 1.239, xi_0 = 0.13, Lambda_0 = 0.06, Tr_bar = 1.5, qd_bar = 1 / 0.4, pi = 3.141592654, delta = HEOS.delta(); double drhodp = 1 / (R * HEOS.T() * (1 + 2 * rhobar * HEOS.dalphar_dDelta() + rhobar * rhobar * HEOS.d2alphar_dDelta2())); double drhobar_dpbar = pstar / rhostar * drhodp; double drhodp_Trbar = 1 / (R * Tr_bar * Tstar * (1 + 2 * rhobar * HEOS.calc_alphar_deriv_nocache(0, 1, HEOS.mole_fractions, 1 / Tr_bar, delta) + delta * delta * HEOS.calc_alphar_deriv_nocache(0, 2, HEOS.mole_fractions, 1 / Tr_bar, delta))); double drhobar_dpbar_Trbar = pstar / rhostar * drhodp_Trbar; double cp = HEOS.cpmass(); // [J/kg/K] double cv = HEOS.cvmass(); // [J/kg/K] double cpbar = cp / R; //[-] double mubar = HEOS.viscosity() / mustar; double DELTAchibar_T = rhobar * (drhobar_dpbar - drhobar_dpbar_Trbar * Tr_bar / Tbar); if (DELTAchibar_T < 0) xi = 0; else xi = xi_0 * pow(DELTAchibar_T / Lambda_0, nu / gamma); double y = qd_bar * xi; double Z; double kappa = cp / cv; if (y < 1.2e-7) Z = 0; else Z = 2 / (pi * y) * (((1 - 1 / kappa) * atan(y) + y / kappa) - (1 - exp(-1 / (1 / y + y * y / 3 / rhobar / rhobar)))); lambdabar_2 = GAMMA * rhobar * cpbar * Tbar / mubar * Z; return (lambdabar_0 * lambdabar_1 + lambdabar_2) * lambdastar; } CoolPropDbl TransportRoutines::conductivity_hardcoded_R23(HelmholtzEOSMixtureBackend& HEOS) { double B1 = -2.5370, // [mW/m/K] B2 = 0.05366, // [mW/m/K^2] C1 = 0.94215, // [-] C2 = 0.14914, // [mW/m/K^2] DeltaGstar = 2508.58, //[J/mol] rhoL = 68.345, // [mol/dm^3] = [mol/L] rhocbar = 7.5114, // [mol/dm^3] DELTAlambda_max = 25, //[mW/m/K] Ru = 8.31451, // [J/mol/K] Tc = 299.2793, //[K] T = HEOS.T(); //[K] double lambda_DG = B1 + B2 * T; double rhobar = HEOS.rhomolar() / 1000; // [mol/L] double lambda_L = C2 * (rhoL * rhoL) / (rhoL - rhobar) * sqrt(T) * exp(rhobar / (rhoL - rhobar) * DeltaGstar / (Ru * T)); double chi = rhobar - rhocbar; double tau = T - Tc; double DELTAlambda_c = 4 * DELTAlambda_max / ((exp(chi) + exp(-chi)) * (exp(tau) + exp(-tau))); return (pow((rhoL - rhobar) / rhoL, C1) * lambda_DG + pow(rhobar / rhoL, C1) * lambda_L + DELTAlambda_c) / 1e3; } CoolPropDbl TransportRoutines::conductivity_critical_hardcoded_ammonia(HelmholtzEOSMixtureBackend& HEOS) { /* From "Thermal Conductivity of Ammonia in a Large Temperature and Pressure Range Including the Critical Region" by R. Tufeu, D.Y. Ivanov, Y. Garrabos, B. Le Neindre, Bereicht der Bunsengesellschaft Phys. Chem. 88 (1984) 422-427 */ double T = HEOS.T(), Tc = 405.4, rhoc = 235, rho; double LAMBDA = 1.2, nu = 0.63, gamma = 1.24, DELTA = 0.50, t, zeta_0_plus = 1.34e-10, a_zeta = 1, GAMMA_0_plus = 0.423e-8; double pi = 3.141592654, a_chi, k_B = 1.3806504e-23, X_T, DELTA_lambda, dPdT, eta_B, DELTA_lambda_id, DELTA_lambda_i; rho = HEOS.keyed_output(CoolProp::iDmass); t = std::abs((T - Tc) / Tc); a_chi = a_zeta / 0.7; eta_B = (2.60 + 1.6 * t) * 1e-5; dPdT = (2.18 - 0.12 / exp(17.8 * t)) * 1e5; // [Pa-K] X_T = 0.61 * rhoc + 16.5 * log(t); // Along the critical isochore (only a function of temperature) (Eq. 9) DELTA_lambda_i = LAMBDA * (k_B * T * T) / (6 * pi * eta_B * (zeta_0_plus * pow(t, -nu) * (1 + a_zeta * pow(t, DELTA)))) * dPdT * dPdT * GAMMA_0_plus * pow(t, -gamma) * (1 + a_chi * pow(t, DELTA)); DELTA_lambda_id = DELTA_lambda_i * exp(-36 * t * t); if (rho < 0.6 * rhoc) { DELTA_lambda = DELTA_lambda_id * (X_T * X_T) / (X_T * X_T + powInt(0.6 * rhoc - 0.96 * rhoc, 2)) * powInt(rho, 2) / powInt(0.6 * rhoc, 2); } else { DELTA_lambda = DELTA_lambda_id * (X_T * X_T) / (X_T * X_T + powInt(rho - 0.96 * rhoc, 2)); } return DELTA_lambda; } CoolPropDbl TransportRoutines::conductivity_hardcoded_helium(HelmholtzEOSMixtureBackend& HEOS) { /* What an incredibly annoying formulation! Implied coefficients?? Not cool. */ double rhoc = 68.0, lambda_e, lambda_c, T = HEOS.T(), rho = HEOS.rhomass(); double summer = 3.739232544 / T - 2.620316969e1 / T / T + 5.982252246e1 / T / T / T - 4.926397634e1 / T / T / T / T; double lambda_0 = 2.7870034e-3 * pow(T, 7.034007057e-1) * exp(summer); double c[] = {1.862970530e-4, -7.275964435e-7, -1.427549651e-4, 3.290833592e-5, -5.213335363e-8, 4.492659933e-8, -5.924416513e-9, 7.087321137e-6, -6.013335678e-6, 8.067145814e-7, 3.995125013e-7}; // Equation 17 lambda_e = (c[0] + c[1] * T + c[2] * pow(T, 1 / 3.0) + c[3] * pow(T, 2.0 / 3.0)) * rho + (c[4] + c[5] * pow(T, 1.0 / 3.0) + c[6] * pow(T, 2.0 / 3.0)) * rho * rho * rho + (c[7] + c[8] * pow(T, 1.0 / 3.0) + c[9] * pow(T, 2.0 / 3.0) + c[10] / T) * rho * rho * log(rho / rhoc); // Critical component lambda_c = 0.0; if (3.5 < T && T < 12) { double x0 = 0.392, E1 = 2.8461, E2 = 0.27156, beta = 0.3554, gamma = 1.1743, delta = 4.304, rhoc_crit = 69.158, Tc = 5.18992, pc = 2.2746e5; double DeltaT = std::abs(1 - T / Tc), DeltaRho = std::abs(1 - rho / rhoc_crit); double eta = HEOS.viscosity(); // [Pa-s] double K_T = HEOS.isothermal_compressibility(), K_Tprime, K_Tbar; double dpdT = HEOS.first_partial_deriv(CoolProp::iP, CoolProp::iT, CoolProp::iDmolar); double W = pow(DeltaT / 0.2, 2) + pow(DeltaRho / 0.25, 2); if (W > 1) { K_Tbar = K_T; } else { double x = pow(DeltaT / DeltaRho, 1 / beta); double h = E1 * (1 + x / x0) * pow(1 + E2 * pow(1 + x / x0, 2 / beta), (gamma - 1) / (2 * beta)); /** dh/dx derived using sympy: E1,x,x0,E2,beta,gamma = symbols('E1,x,x0,E2,beta,gamma') h = E1*(1 + x/x0)*pow(1 + E2*pow(1 + x/x0, 2/beta), (gamma-1)/(2*beta)) ccode(simplify(diff(h,x))) */ double dhdx = E1 * (E2 * pow((x + x0) / x0, 2 / beta) * (gamma - 1) * pow(E2 * pow((x + x0) / x0, 2 / beta) + 1, (1.0 / 2.0) * (gamma - 1) / beta) + pow(beta, 2) * pow(E2 * pow((x + x0) / x0, 2 / beta) + 1, (1.0 / 2.0) * (2 * beta + gamma - 1) / beta)) / (pow(beta, 2) * x0 * (E2 * pow((x + x0) / x0, 2 / beta) + 1)); // Right-hand-side of Equation 9 double RHS = pow(DeltaRho, delta - 1) * (delta * h - x / beta * dhdx); K_Tprime = 1 / (RHS * pow(rho / rhoc_crit, 2) * pc); K_Tbar = W * K_T + (1 - W) * K_Tprime; } // 3.4685233d-17 and 3.726229668d0 are "magical" coefficients that are present in the REFPROP source to yield the right values. Not clear why these values are needed. // Also, the form of the critical term in REFPROP does not agree with Hands paper. EL and MH from NIST are not sure where these coefficients come from. lambda_c = 3.4685233e-17 * 3.726229668 * sqrt(K_Tbar) * pow(T, 2) / rho / eta * pow(dpdT, 2) * exp(-18.66 * pow(DeltaT, 2) - 4.25 * pow(DeltaRho, 4)); } return lambda_0 + lambda_e + lambda_c; } CoolPropDbl TransportRoutines::conductivity_hardcoded_methane(HelmholtzEOSMixtureBackend& HEOS) { double delta = HEOS.rhomolar() / 10139.0, tau = 190.55 / HEOS.T(); double lambda_dilute, lambda_residual, lambda_critical; // Viscosity formulation from Friend, JPCRD, 1989 // Dilute double C[] = { 0, -3.0328138281, 16.918880086, -37.189364917, 41.288861858, -24.615921140, 8.9488430959, -1.8739245042, 0.20966101390, -9.6570437074e-3}; double OMEGA22_summer = 0; double t = HEOS.T() / 174.0; for (int i = 1; i <= 9; ++i) { OMEGA22_summer += C[i] * pow(t, (i - 1.0) / 3.0 - 1.0); } double eta_dilute = 10.50 * sqrt(t) * OMEGA22_summer; double re[] = {0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 1, 1}; double se[] = {0, 0, 1, 0, 1, 1.5, 0, 2, 0, 1, 0, 1}; double ge[] = {0, 0.41250137, -0.14390912, 0.10366993, 0.40287464, -0.24903524, -0.12953131, 0.06575776, 0.02566628, -0.03716526, -0.38798341, 0.03533815}; double summer1 = 0, summer2 = 0; for (int i = 1; i <= 9; ++i) { summer1 += ge[i] * pow(delta, re[i]) * pow(tau, se[i]); } for (int i = 10; i <= 11; ++i) { summer2 += ge[i] * pow(delta, re[i]) * pow(tau, se[i]); } double eta_residual = 12.149 * summer1 / (1 + summer2); double eta = eta_residual + eta_dilute; // Dilute double f_int = 1.458850 - 0.4377162 / t; lambda_dilute = 0.51828 * eta_dilute * (3.75 - f_int * (POW2(HEOS.tau()) * HEOS.d2alpha0_dTau2() + 1.5)); // [mW/m/K] // Residual double rl[] = {0, 1, 3, 4, 4, 5, 5, 2}; double sl[] = {0, 0, 0, 0, 1, 0, 1, 0}; double jl[] = {0, 2.4149207, 0.55166331, -0.52837734, 0.073809553, 0.24465507, -0.047613626, 1.5554612}; double summer = 0; for (int i = 1; i <= 6; ++i) { summer += jl[i] * pow(delta, rl[i]) * pow(tau, sl[i]); } double delta_sigma_star = 1.0; // Looks like a typo in Friend - should be 1 instead of 11 if (HEOS.T() < HEOS.T_critical() && HEOS.rhomolar() < HEOS.rhomolar_critical()) { delta_sigma_star = HEOS.saturation_ancillary(iDmolar, 1, iT, HEOS.T()) / HEOS.keyed_output(CoolProp::irhomolar_critical); } lambda_residual = 6.29638 * (summer + jl[7] * POW2(delta) / delta_sigma_star); // [mW/m/K] // Critical region double Tstar = 1 - 1 / tau; double rhostar = 1 - delta; double F_T = 2.646, F_rho = 2.678, F_A = -0.637; double F = exp(-F_T * sqrt(std::abs(Tstar)) - F_rho * POW2(rhostar) - F_A * rhostar); double CHI_T_star; if (std::abs(Tstar) < 0.03) { if (std::abs(rhostar) < 1e-16) { // Equation 26 const double LAMBDA = 0.0801, gamma = 1.190; CHI_T_star = LAMBDA * pow(std::abs(Tstar), -gamma); } else if (std::abs(rhostar) < 0.03) { // Equation 23 const double beta = 0.355, W = -1.401, S = -6.098, E = 0.287, a = 3.352, b = 0.732, R = 0.535, Q = 0.1133; double OMEGA = W * Tstar * pow(std::abs(rhostar), -1 / beta); double theta = 1; if (Tstar < -pow(std::abs(rhostar), -1 / beta) / S) { theta = 1 + E * pow(1 + S * Tstar * pow(std::abs(rhostar), -1 / beta), 2 * beta); } CHI_T_star = Q * pow(std::abs(rhostar), -a) * pow(theta, b) / (theta + OMEGA * (theta + R)); } else { // Equation 19a CHI_T_star = 0.28631 * delta * tau / (1 + 2 * delta * HEOS.dalphar_dDelta() + POW2(delta) * HEOS.d2alphar_dDelta2()); } } else { // Equation 19a CHI_T_star = 0.28631 * delta * tau / (1 + 2 * delta * HEOS.dalphar_dDelta() + POW2(delta) * HEOS.d2alphar_dDelta2()); } lambda_critical = 91.855 / (eta * POW2(tau)) * POW2(1 + delta * HEOS.dalphar_dDelta() - delta * tau * HEOS.d2alphar_dDelta_dTau()) * pow(CHI_T_star, 0.4681) * F; //[mW/m/K] return (lambda_dilute + lambda_residual + lambda_critical) * 0.001; } void TransportRoutines::conformal_state_solver(HelmholtzEOSMixtureBackend& HEOS, HelmholtzEOSMixtureBackend& HEOS_Reference, CoolPropDbl& T0, CoolPropDbl& rhomolar0) { int iter = 0; double resid = 9e30, resid_old = 9e30; CoolPropDbl alphar = HEOS.alphar(); CoolPropDbl Z = HEOS.keyed_output(iZ); Eigen::Vector2d r; Eigen::Matrix2d J; HEOS_Reference.specify_phase(iphase_gas); // Something homogeneous, not checked // Update the reference fluid with the conformal state HEOS_Reference.update_DmolarT_direct(rhomolar0, T0); do { CoolPropDbl dtau_dT = -HEOS_Reference.T_critical() / (T0 * T0); CoolPropDbl ddelta_drho = 1 / HEOS_Reference.rhomolar_critical(); // Independent variables are T0 and rhomolar0, residuals are matching alphar and Z r(0) = HEOS_Reference.alphar() - alphar; r(1) = HEOS_Reference.keyed_output(iZ) - Z; J(0, 0) = HEOS_Reference.dalphar_dTau() * dtau_dT; J(0, 1) = HEOS_Reference.dalphar_dDelta() * ddelta_drho; // Z = 1+delta*dalphar_ddelta(tau,delta) // dZ_dT J(1, 0) = HEOS_Reference.delta() * HEOS_Reference.d2alphar_dDelta_dTau() * dtau_dT; // dZ_drho J(1, 1) = (HEOS_Reference.delta() * HEOS_Reference.d2alphar_dDelta2() + HEOS_Reference.dalphar_dDelta()) * ddelta_drho; // Step in v obtained from Jv = -r Eigen::Vector2d v = J.colPivHouseholderQr().solve(-r); bool good_solution = false; double T0_init = HEOS_Reference.T(), rhomolar0_init = HEOS_Reference.rhomolar(); // Calculate the old residual after the last step resid_old = sqrt(POW2(r(0)) + POW2(r(1))); for (double frac = 1.0; frac > 0.001; frac /= 2) { try { // Calculate new values double T_new = T0_init + frac * v(0); double rhomolar_new = rhomolar0_init + frac * v(1); // Update state with step HEOS_Reference.update_DmolarT_direct(rhomolar_new, T_new); resid = sqrt(POW2(HEOS_Reference.alphar() - alphar) + POW2(HEOS_Reference.keyed_output(iZ) - Z)); if (resid > resid_old) { continue; } good_solution = true; T0 = T_new; rhomolar0 = rhomolar_new; break; } catch (...) { continue; } } if (!good_solution) { throw ValueError(format("Not able to get a solution")); } iter++; if (iter > 50) { throw ValueError(format("conformal_state_solver took too many iterations; residual is %g; prior was %g", resid, resid_old)); } } while (std::abs(resid) > 1e-9); } CoolPropDbl TransportRoutines::viscosity_ECS(HelmholtzEOSMixtureBackend& HEOS, HelmholtzEOSMixtureBackend& HEOS_Reference) { // Collect some parameters CoolPropDbl M = HEOS.molar_mass(), M0 = HEOS_Reference.molar_mass(), Tc = HEOS.T_critical(), Tc0 = HEOS_Reference.T_critical(), rhocmolar = HEOS.rhomolar_critical(), rhocmolar0 = HEOS_Reference.rhomolar_critical(); // Get a reference to the ECS data CoolProp::ViscosityECSVariables& ECS = HEOS.components[0].transport.viscosity_ecs; // The correction polynomial psi_eta double psi = 0; for (std::size_t i = 0; i < ECS.psi_a.size(); i++) { psi += ECS.psi_a[i] * pow(HEOS.rhomolar() / ECS.psi_rhomolar_reducing, ECS.psi_t[i]); } // The dilute gas portion for the fluid of interest [Pa-s] CoolPropDbl eta_dilute = viscosity_dilute_kinetic_theory(HEOS); // ************************************ // Start with a guess for theta and phi // ************************************ CoolPropDbl theta = 1; CoolPropDbl phi = 1; // The equivalent substance reducing ratios CoolPropDbl f = Tc / Tc0 * theta; CoolPropDbl h = rhocmolar0 / rhocmolar * phi; // Must be the ratio of MOLAR densities!! // To be solved for CoolPropDbl T0 = HEOS.T() / f; CoolPropDbl rhomolar0 = HEOS.rhomolar() * h; // ************************** // Solver for conformal state // ************************** // HEOS_Reference.specify_phase(iphase_gas); // something homogeneous conformal_state_solver(HEOS, HEOS_Reference, T0, rhomolar0); // Update the reference fluid with the updated conformal state HEOS_Reference.update_DmolarT_direct(rhomolar0 * psi, T0); // Recalculate ESRR f = HEOS.T() / T0; h = rhomolar0 / HEOS.rhomolar(); // Must be the ratio of MOLAR densities!! // ********************** // Remaining calculations // ********************** // The reference fluid's contribution to the viscosity [Pa-s] CoolPropDbl eta_resid = HEOS_Reference.calc_viscosity_background(); // The F factor CoolPropDbl F_eta = sqrt(f) * pow(h, -static_cast<CoolPropDbl>(2.0L / 3.0L)) * sqrt(M / M0); // The total viscosity considering the contributions of the fluid of interest and the reference fluid [Pa-s] CoolPropDbl eta = eta_dilute + eta_resid * F_eta; return eta; } CoolPropDbl TransportRoutines::viscosity_rhosr(HelmholtzEOSMixtureBackend& HEOS) { // Get a reference to the data const CoolProp::ViscosityRhoSrVariables& data = HEOS.components[0].transport.viscosity_rhosr; // The dilute gas portion for the fluid of interest [Pa-s] CoolPropDbl eta_dilute = viscosity_dilute_kinetic_theory(HEOS); // Calculate x double x = HEOS.rhomolar() * HEOS.gas_constant() * (HEOS.tau() * HEOS.dalphar_dTau() - HEOS.alphar()) / data.rhosr_critical; // Crossover variable double psi_liq = 1 / (1 + exp(-100.0 * (x - 2))); // Evaluated using Horner's method const std::vector<double>&cL = data.c_liq, cV = data.c_vap; double f_liq = cL[0] + x * (cL[1] + x * (cL[2] + x * (cL[3]))); double f_vap = cV[0] + x * (cV[1] + x * (cV[2] + x * (cV[3]))); // Evaluate the reference fluid double etastar_ref = exp(psi_liq * f_liq + (1 - psi_liq) * f_vap); // Get the non-dimensionalized viscosity double etastar_fluid = 1 + data.C * (etastar_ref - 1); return etastar_fluid * eta_dilute; } CoolPropDbl TransportRoutines::conductivity_ECS(HelmholtzEOSMixtureBackend& HEOS, HelmholtzEOSMixtureBackend& HEOS_Reference) { // Collect some parameters CoolPropDbl M = HEOS.molar_mass(), M_kmol = M * 1000, M0 = HEOS_Reference.molar_mass(), Tc = HEOS.T_critical(), Tc0 = HEOS_Reference.T_critical(), rhocmolar = HEOS.rhomolar_critical(), rhocmolar0 = HEOS_Reference.rhomolar_critical(), R_u = HEOS.gas_constant(), R = HEOS.gas_constant() / HEOS.molar_mass(), //[J/kg/K] R_kJkgK = R_u / M_kmol; // Get a reference to the ECS data CoolProp::ConductivityECSVariables& ECS = HEOS.components[0].transport.conductivity_ecs; // The correction polynomial psi_eta in rho/rho_red double psi = 0; for (std::size_t i = 0; i < ECS.psi_a.size(); ++i) { psi += ECS.psi_a[i] * pow(HEOS.rhomolar() / ECS.psi_rhomolar_reducing, ECS.psi_t[i]); } // The correction polynomial f_int in T/T_red double fint = 0; for (std::size_t i = 0; i < ECS.f_int_a.size(); ++i) { fint += ECS.f_int_a[i] * pow(HEOS.T() / ECS.f_int_T_reducing, ECS.f_int_t[i]); } // The dilute gas density for the fluid of interest [uPa-s] CoolPropDbl eta_dilute = viscosity_dilute_kinetic_theory(HEOS) * 1e6; // The mass specific ideal gas constant-pressure specific heat [J/kg/K] CoolPropDbl cp0 = HEOS.calc_cpmolar_idealgas() / HEOS.molar_mass(); // The internal contribution to the thermal conductivity [W/m/K] CoolPropDbl lambda_int = fint * eta_dilute * (cp0 - 2.5 * R) / 1e3; // The dilute gas contribution to the thermal conductivity [W/m/K] CoolPropDbl lambda_dilute = 15.0e-3 / 4.0 * R_kJkgK * eta_dilute; // ************************************ // Start with a guess for theta and phi // ************************************ CoolPropDbl theta = 1; CoolPropDbl phi = 1; // The equivalent substance reducing ratios CoolPropDbl f = Tc / Tc0 * theta; CoolPropDbl h = rhocmolar0 / rhocmolar * phi; // Must be the ratio of MOLAR densities!! // Initial values for the conformal state CoolPropDbl T0 = HEOS.T() / f; CoolPropDbl rhomolar0 = HEOS.rhomolar() * h; // ************************** // Solver for conformal state // ************************** try { conformal_state_solver(HEOS, HEOS_Reference, T0, rhomolar0); } catch (std::exception& e) { throw ValueError(format("Conformal state solver failed; error was %s", e.what())); } // Update the reference fluid with the conformal state HEOS_Reference.update(DmolarT_INPUTS, rhomolar0 * psi, T0); // Recalculate ESRR f = HEOS.T() / T0; h = rhomolar0 / HEOS.rhomolar(); // Must be the ratio of MOLAR densities!! // The reference fluid's contribution to the conductivity [W/m/K] CoolPropDbl lambda_resid = HEOS_Reference.calc_conductivity_background(); // The F factor CoolPropDbl F_lambda = sqrt(f) * pow(h, static_cast<CoolPropDbl>(-2.0 / 3.0)) * sqrt(M0 / M); // The critical contribution from the fluid of interest [W/m/K] CoolPropDbl lambda_critical = conductivity_critical_simplified_Olchowy_Sengers(HEOS); // The total thermal conductivity considering the contributions of the fluid of interest and the reference fluid [Pa-s] CoolPropDbl lambda = lambda_int + lambda_dilute + lambda_resid * F_lambda + lambda_critical; return lambda; } }; /* namespace CoolProp */
48.942279
174
0.578489
friederikeboehm
07435cfeb75f5c3e1334bad63d90566a9506acfc
7,109
cpp
C++
test/moddims.cpp
ckeitz/arrayfire
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
[ "BSD-3-Clause" ]
null
null
null
test/moddims.cpp
ckeitz/arrayfire
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
[ "BSD-3-Clause" ]
null
null
null
test/moddims.cpp
ckeitz/arrayfire
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
[ "BSD-3-Clause" ]
null
null
null
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <gtest/gtest.h> #include <arrayfire.h> #include <af/dim4.hpp> #include <af/traits.hpp> #include <vector> #include <iostream> #include <string> #include <testHelpers.hpp> using std::vector; using std::string; using std::cout; using std::endl; using af::cfloat; using af::cdouble; template<typename T> class Moddims : public ::testing::Test { public: virtual void SetUp() { subMat.push_back({1,2,1}); subMat.push_back({1,3,1}); } vector<af_seq> subMat; }; // create a list of types to be tested // TODO: complex types tests have to be added typedef ::testing::Types<float, double, int, unsigned, char, unsigned char> TestTypes; // register the type list TYPED_TEST_CASE(Moddims, TestTypes); template<typename T> void moddimsTest(string pTestFile, bool isSubRef=false, const vector<af_seq> *seqv=nullptr) { if (noDoubleTests<T>()) return; vector<af::dim4> numDims; vector<vector<T>> in; vector<vector<T>> tests; readTests<T,T,int>(pTestFile,numDims,in,tests); af::dim4 dims = numDims[0]; T *outData; if (isSubRef) { af_array inArray = 0; af_array subArray = 0; af_array outArray = 0; ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type)); ASSERT_EQ(AF_SUCCESS, af_index(&subArray,inArray,seqv->size(),&seqv->front())); af::dim4 newDims(1); newDims[0] = 2; newDims[1] = 3; ASSERT_EQ(AF_SUCCESS, af_moddims(&outArray,subArray,newDims.ndims(),newDims.get())); dim_type nElems; ASSERT_EQ(AF_SUCCESS, af_get_elements(&nElems,outArray)); outData = new T[nElems]; ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(subArray)); } else { af_array inArray = 0; af_array outArray = 0; ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type)); af::dim4 newDims(1); newDims[0] = dims[1]; newDims[1] = dims[0]*dims[2]; ASSERT_EQ(AF_SUCCESS, af_moddims(&outArray,inArray,newDims.ndims(),newDims.get())); outData = new T[dims.elements()]; ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray)); } for (size_t testIter=0; testIter<tests.size(); ++testIter) { vector<T> currGoldBar = tests[testIter]; size_t nElems = currGoldBar.size(); for (size_t elIter=0; elIter<nElems; ++elIter) { ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl; } } delete[] outData; } TYPED_TEST(Moddims,Basic) { moddimsTest<TypeParam>(string(TEST_DIR"/moddims/basic.test")); } TYPED_TEST(Moddims,Subref) { moddimsTest<TypeParam>(string(TEST_DIR"/moddims/subref.test"),true,&(this->subMat)); } template<typename T> void moddimsArgsTest(string pTestFile) { if (noDoubleTests<T>()) return; vector<af::dim4> numDims; vector<vector<T>> in; vector<vector<T>> tests; readTests<T,T,int>(pTestFile,numDims,in,tests); af::dim4 dims = numDims[0]; af_array inArray = 0; af_array outArray = 0; ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type)); af::dim4 newDims(1); newDims[0] = dims[1]; newDims[1] = dims[0]*dims[2]; ASSERT_EQ(AF_ERR_ARG, af_moddims(&outArray,inArray,0,newDims.get())); ASSERT_EQ(AF_ERR_ARG, af_moddims(&outArray,inArray,newDims.ndims(),nullptr)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); } TYPED_TEST(Moddims,InvalidArgs) { moddimsArgsTest<TypeParam>(string(TEST_DIR"/moddims/basic.test")); } template<typename T> void moddimsMismatchTest(string pTestFile) { if (noDoubleTests<T>()) return; vector<af::dim4> numDims; vector<vector<T>> in; vector<vector<T>> tests; readTests<T,T,int>(pTestFile,numDims,in,tests); af::dim4 dims = numDims[0]; af_array inArray = 0; af_array outArray = 0; ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type)); af::dim4 newDims(1); newDims[0] = dims[1]-1; newDims[1] = (dims[0]-1)*dims[2]; ASSERT_EQ(AF_ERR_SIZE, af_moddims(&outArray,inArray,newDims.ndims(),newDims.get())); ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); } TYPED_TEST(Moddims,Mismatch) { moddimsMismatchTest<TypeParam>(string(TEST_DIR"/moddims/basic.test")); } /////////////////////////////////// CPP /////////////////////////////////// // template<typename T> void cppModdimsTest(string pTestFile, bool isSubRef=false, const vector<af_seq> *seqv=nullptr) { if (noDoubleTests<T>()) return; vector<af::dim4> numDims; vector<vector<T>> in; vector<vector<T>> tests; readTests<T,T,int>(pTestFile,numDims,in,tests); af::dim4 dims = numDims[0]; T *outData; if (isSubRef) { af::array input(dims, &(in[0].front())); af::array subArray = input(seqv->at(0), seqv->at(1)); af::dim4 newDims(1); newDims[0] = 2; newDims[1] = 3; af::array output = af::moddims(subArray, newDims.ndims(), newDims.get()); dim_type nElems = output.elements(); outData = new T[nElems]; output.host((void*)outData); } else { af::array input(dims, &(in[0].front())); af::dim4 newDims(1); newDims[0] = dims[1]; newDims[1] = dims[0]*dims[2]; af::array output = af::moddims(input, newDims.ndims(), newDims.get()); outData = new T[dims.elements()]; output.host((void*)outData); } for (size_t testIter=0; testIter<tests.size(); ++testIter) { vector<T> currGoldBar = tests[testIter]; size_t nElems = currGoldBar.size(); for (size_t elIter=0; elIter<nElems; ++elIter) { ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl; } } delete[] outData; } TEST(Moddims,Basic_CPP) { cppModdimsTest<float>(string(TEST_DIR"/moddims/basic.test")); } TEST(Moddims,Subref_CPP) { vector<af_seq> subMat; subMat.push_back({1,2,1}); subMat.push_back({1,3,1}); cppModdimsTest<float>(string(TEST_DIR"/moddims/subref.test"),true,&subMat); }
29.135246
142
0.620059
ckeitz
07439ae178f5d7834cc88f2c47ef09141dc3f310
1,644
cpp
C++
work/day14_figure.cpp
eatyouzi/AH
2beb8252f967d8492a63498c5866d5268eaed4af
[ "Unlicense" ]
null
null
null
work/day14_figure.cpp
eatyouzi/AH
2beb8252f967d8492a63498c5866d5268eaed4af
[ "Unlicense" ]
null
null
null
work/day14_figure.cpp
eatyouzi/AH
2beb8252f967d8492a63498c5866d5268eaed4af
[ "Unlicense" ]
null
null
null
#include<iostream> #include <cstdio> #include <fstream> #include <stdlib.h> using namespace std; class Figure{ public: Figure(); Figure(string name) :_typename(name) { } virtual double getArea( )=0; virtual string getName( )=0; virtual void show()=0; //打印图形的相关信息 protected: string _typename ; }; class Cicle :virtual public Figure { public: Cicle():_radix(0.0){} //初始化为0 Cicle(double radix) :_radix(radix) ,Figure("Cicle") { } double getRadius( ) { return _radix; }//获取圆的半径 double getPerimeter(){ return 2*3.14*_radix; } //获取圆的周长 virtual double getArea() { return 3.14*_radix*_radix; } //获取圆的面积 virtual string getName(){ return _typename; } //获取圆的名字 virtual void show(){ cout<<"name "<<getName() <<" radix "<<getRadius() <<" perimeter "<<getPerimeter() <<" area "<<getArea() <<endl; } protected: double _radix ; }; class Cylinder :public Cicle { public: Cylinder(double r, double h) :Cicle(r) ,Figure("Cylinder") ,_high(h) { } virtual double getArea(){ return 2 *Cicle::getArea()+ getPerimeter()*_high; } virtual string getName(){ return _typename; } double getHeight(){ return _high; } //获取圆柱体的高 double getVolume(){ return Cicle::getArea()*_high; } //获取圆柱体的体积 void show(){ cout<<"name "<<_typename <<" high "<<_high <<" area "<<getArea() <<" volume "<<getVolume() <<endl; } //将圆柱体的高、表面积、体积输出到屏幕 private: double _high; }; int main(){ Figure *f1, *f2; Cicle ci1(10.0); Cylinder cy1(10.0, 2.0); f1 = &ci1; f2 = &cy1; f1->show(); f2->show(); system("pause"); return 0; }
15.807692
51
0.607664
eatyouzi
0743b6b5e08885bcbeeb031436fd67c4ba897a65
124
cpp
C++
vortex/assert.cpp
LeDYoM/sgh
66a56d0df5c0acc8a3f47212a91da7ea889695de
[ "MIT" ]
null
null
null
vortex/assert.cpp
LeDYoM/sgh
66a56d0df5c0acc8a3f47212a91da7ea889695de
[ "MIT" ]
null
null
null
vortex/assert.cpp
LeDYoM/sgh
66a56d0df5c0acc8a3f47212a91da7ea889695de
[ "MIT" ]
null
null
null
#include "include/assert.hpp" #include "common_def_priv.hpp" namespace vtx { Assert::Assert() {} Assert::~Assert() {} }
12.4
30
0.677419
LeDYoM
0745802cf61c83a6b3b707eb4973f77385475d5a
836
cpp
C++
external/FW1FontWrapper/Source/FW1FontWrapper.cpp
CptLucky8/OpenXR-Toolkit
82bfe926d64faa119556725ab5e8bcd2cd7dbab5
[ "MIT" ]
54
2018-12-18T01:43:15.000Z
2022-02-13T09:37:41.000Z
external/FW1FontWrapper/Source/FW1FontWrapper.cpp
CptLucky8/OpenXR-Toolkit
82bfe926d64faa119556725ab5e8bcd2cd7dbab5
[ "MIT" ]
162
2021-12-29T09:27:33.000Z
2022-03-31T02:59:04.000Z
external/FW1FontWrapper/Source/FW1FontWrapper.cpp
CptLucky8/OpenXR-Toolkit
82bfe926d64faa119556725ab5e8bcd2cd7dbab5
[ "MIT" ]
17
2018-12-16T12:16:35.000Z
2022-02-15T18:58:01.000Z
// FW1FontWrapper.cpp #include "FW1Precompiled.h" #include "CFW1Factory.h" #ifndef FW1_DELAYLOAD_DWRITE_DLL #pragma comment (lib, "DWrite.lib") #endif #ifndef FW1_DELAYLOAD_D3DCOMPILER_XX_DLL #pragma comment (lib, "DWrite.lib") #endif #ifdef FW1_COMPILETODLL #ifndef _M_X64 #pragma comment (linker, "/EXPORT:FW1CreateFactory=_FW1CreateFactory@8,@1") #endif #endif // Create FW1 factory extern "C" HRESULT STDMETHODCALLTYPE FW1CreateFactory(UINT32 Version, IFW1Factory **ppFactory) { if(Version != FW1_VERSION) return E_FAIL; if(ppFactory == NULL) return E_INVALIDARG; FW1FontWrapper::CFW1Factory *pFactory = new FW1FontWrapper::CFW1Factory; HRESULT hResult = pFactory->initFactory(); if(FAILED(hResult)) { pFactory->Release(); } else { *ppFactory = pFactory; hResult = S_OK; } return hResult; }
19.44186
96
0.740431
CptLucky8
074aa629651f56e34920eceb191d702d723480cf
10,284
cpp
C++
src/d_effect.cpp
Krzysiek-K/dxfw
ca8010fd1dc3969a5cdeee062c4ca43090b0815a
[ "BSD-4-Clause" ]
1
2019-01-17T22:57:40.000Z
2019-01-17T22:57:40.000Z
src/d_effect.cpp
Krzysiek-K/dxfw
ca8010fd1dc3969a5cdeee062c4ca43090b0815a
[ "BSD-4-Clause" ]
null
null
null
src/d_effect.cpp
Krzysiek-K/dxfw
ca8010fd1dc3969a5cdeee062c4ca43090b0815a
[ "BSD-4-Clause" ]
null
null
null
#include "dxfw.h" using namespace std; using namespace base; static bool _load_scrambled(const char *path,vector<byte> &data) { if(!NFS.GetFileBytes(path,data)) return false; unsigned int key = 1716253875; for(int i=0;i<(int)data.size();i++) { data[i] ^= (key>>24); key = key*134775813 + 13; } return true; } static bool _save_scrambled(const char *path,const vector<byte> &data) { vector<byte> cdata = data; if(cdata.size()<=0) return false; unsigned int key = 1716253875; for(int i=0;i<(int)cdata.size();i++) { cdata[i] ^= (key>>24); key = key*134775813 + 13; } return NFS.DumpRawVector(path,cdata); } // **************** DevEffect **************** DevEffect::DevEffect(const char *path,DevEffect::DefGenerator *dg,int _flags) : fx(NULL), pool(NULL) { do_preload = false; pass = -2; def_generator = dg; flags = _flags; file_time = 0; compile_flags = D3DXSHADER_AVOID_FLOW_CONTROL; if( flags & FXF_FLOW_CONTROL_MEDIUM ) compile_flags &= ~D3DXSHADER_AVOID_FLOW_CONTROL; if( flags & FXF_FLOW_CONTROL_HIGH ) compile_flags |= D3DXSHADER_PREFER_FLOW_CONTROL; if( flags & FXF_PARTIAL_PRECISION ) compile_flags |= D3DXSHADER_PARTIALPRECISION; if( flags & FXF_OPTIMIZATION_3 ) compile_flags |= D3DXSHADER_OPTIMIZATION_LEVEL3; else if( flags & FXF_OPTIMIZATION_0 ) compile_flags |= D3DXSHADER_OPTIMIZATION_LEVEL0; else if( flags & FXF_OPTIMIZATION_1 ) compile_flags |= D3DXSHADER_OPTIMIZATION_LEVEL1; else if( flags & FXF_OPTIMIZATION_2 ) compile_flags |= D3DXSHADER_OPTIMIZATION_LEVEL2; if( flags & FXF_LEGACY ) compile_flags |= D3DXSHADER_USE_LEGACY_D3DX9_31_DLL; if(Dev.GetIsReady()) Load(path,dg); else do_preload = true, p_path = path; } bool DevEffect::Load(const char *path,DevEffect::DefGenerator *dg) { // clear effect ClearEffect(); file_time = GetFileTime(path); p_path = string(path).c_str(); // load file vector<char> data; if(!ScrambleLoad(path,data)) return false; // compute partial hash MD5Hash md5; md5.Update((byte*)&data[0],(int)data.size()); // build skip list string skip_list; BuildSkipList(&data[0],skip_list); // build defines vector<string> defs; if(dg) dg(defs); else defs.push_back(":"); // create pool if(defs.size()>=2) { if(FAILED(D3DXCreateEffectPool(&pool))) { return false; } } // compile for(int i=0;i<(int)defs.size();i++) { vector<D3DXMACRO> macros; vector<byte> bin; MD5Hash hash = md5; byte bhash[16]; // build final hash defs[i].push_back(0); hash.Update((byte*)&defs[i][0],(int)defs.size()); hash.Final(bhash); // get macros ShatterDefsList(&defs[i][0],macros); // build binary path string bpath = FilePathGetPart((string("shaders/")+path).c_str(),true,true,false); if(defs[i].c_str()[0]) { bpath += "-"; bpath += defs[i].c_str(); } bpath += ".fxx"; // precompile effect if(!GetPrecompiledBinary(data,defs[i].c_str(),path,bpath.c_str(),macros,bhash,bin)) return false; if(!CompileVersion(defs[i].c_str(),path,bin,macros,skip_list.c_str())) return false; } if(fx_list.size()<=0) return false; fx = fx_list[0]; // load textures D3DXHANDLE h, ha; const char *str; int id = 0; while( (h = fx->GetParameter(NULL,id)) ) { ha = fx->GetAnnotationByName(h,"Load"); if(ha) if(SUCCEEDED(fx->GetString(ha,&str))) { DevTexture *t = new DevTexture(); t->Load(str); fx->SetTexture(h,t->GetTexture()); textures.push_back(t); } id++; } return true; } const char *DevEffect::GetTechniqueName(int id) { D3DXHANDLE h; D3DXTECHNIQUE_DESC desc; if(!fx) return NULL; h = fx->GetTechnique(id); if(!h) return NULL; if(SUCCEEDED(fx->GetTechniqueDesc(h,&desc))) return desc.Name; return NULL; } const char *DevEffect::GetTechniqueInfo(const char *name,const char *param) { D3DXHANDLE h, ha; const char *str; if(!fx) return NULL; h = fx->GetTechniqueByName(name); if(!h) return ""; ha = fx->GetAnnotationByName(h,param); if(!ha) return ""; if(SUCCEEDED(fx->GetString(ha,&str))) return str; return ""; } bool DevEffect::SelectVersionStr(const char *version) { map<string,int>::iterator p = version_index.find(version); if(p==version_index.end()) { fx = NULL; return false; } fx = fx_list[p->second]; return true; } bool DevEffect::SelectVersion(int version) { if(version<0 || version>=(int)fx_list.size()) { fx = NULL; return false; } fx = fx_list[version]; return true; } int DevEffect::GetVersionIndex(const char *version) { map<string,int>::iterator p = version_index.find(version); if(p==version_index.end()) return -1; return p->second; } bool DevEffect::StartTechnique(const char *name) { if(!fx) return false; if(FAILED(fx->SetTechnique(name))) { pass = -2; return false; } pass = -1; return true; } bool DevEffect::StartPass() { if(!fx || pass==-2) return false; if(pass<0) fx->Begin((UINT*)&n_passes,0); else fx->EndPass(); pass++; if(pass>=n_passes) { fx->End(); pass = -2; return false; } fx->BeginPass(pass); return true; } void DevEffect::OnBeforeReset() { for(int i=0;i<(int)fx_list.size();i++) fx_list[i]->OnLostDevice(); } void DevEffect::OnAfterReset() { for(int i=0;i<(int)fx_list.size();i++) fx_list[i]->OnResetDevice(); } void DevEffect::ClearEffect() { for(int i=0;i<(int)fx_list.size();i++) fx_list[i]->Release(); fx_list.clear(); fx = NULL; if(pool) { pool->Release(); pool = NULL; } version_index.clear(); do_preload = false; pass = -2; last_error.clear(); } bool DevEffect::ScrambleLoad(const char *path,vector<char> &data) { bool scrambled = false; if(!NFS.GetFileBytes(path,*(vector<byte>*)&data) || data.size()==0) { if(!_load_scrambled(format("shaders/%ss",path).c_str(),*(vector<byte>*)&data) || data.size()==0) { last_error = format("Can't find file %s!",path); if(!(flags&FXF_NO_ERROR_POPUPS)) if(MessageBox(NULL,last_error.c_str(),path,MB_OKCANCEL)==IDCANCEL) ExitProcess(0); return false; } else scrambled = true; } if(!scrambled) _save_scrambled(format("shaders/%ss",path).c_str(),*(vector<byte>*)&data); data.push_back(0); return true; } void DevEffect::BuildSkipList(const char *d,string &skip_list) { while(*d) { if(d[0]=='/' && d[1]=='*' && d[2]=='$' && d[3]=='*' && d[4]=='/' && d[5]==' ') { const char *p = d+6; if(skip_list.size()>0) skip_list.push_back(';'); while((*p>='a' && *p<='z') || (*p>='A' && *p<='Z') || (*p>='0' && *p<='9') || *p=='_') skip_list.push_back(*p++); } d++; } } void DevEffect::ShatterDefsList(char *s,vector<D3DXMACRO> &macros) { // parse version identifier const char *id = s; while(*s && *s!=':') s++; // parse macros while(*s) { D3DXMACRO m = { NULL, NULL }; // terminate previous string *s++ = 0; // read name m.Name = s; while(*s && *s!='=') s++; if(!*s) break; *s++ = 0; // read definition m.Definition = s; while(*s && *s!=';') s++; macros.push_back(m); } // terminate macro list D3DXMACRO m = { NULL, NULL }; macros.push_back(m); } bool DevEffect::GetPrecompiledBinary( vector<char> &data, const char *id, const char *path, const char *bpath, vector<D3DXMACRO> &macros, byte hash[16], vector<byte> &bin) { ID3DXEffectCompiler *fxc = NULL; ID3DXBuffer *binbuff = NULL; ID3DXBuffer *errors = NULL; if(_load_scrambled(bpath,*(vector<byte>*)&bin) && bin.size()>16) { if(memcmp(&bin[0],hash,16)==0) { bin.erase(bin.begin(),bin.begin()+16); return true; } } for(int pass=0;pass<2;pass++) { HRESULT r; bool error; if( pass == 0 ) { r = D3DXCreateEffectCompiler(&data[0],(DWORD)data.size(),&macros[0],NULL, compile_flags,&fxc,&errors); error = !fxc; } else { r = fxc->CompileEffect(compile_flags,&binbuff,&errors); error = !binbuff; } if(FAILED(r) || errors || error) { if(errors) { last_error = format("%s:%s: %s",path,id,(char*)errors->GetBufferPointer()); if(!(flags&FXF_NO_ERROR_POPUPS)) if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL) ExitProcess(0); errors->Release(); if(fxc) fxc->Release(); if(binbuff) binbuff->Release(); return false; } else { last_error = format("%s:%s: Unknown error!",path,id); if(!(flags&FXF_NO_ERROR_POPUPS)) if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL) ExitProcess(0); if(fxc) fxc->Release(); if(binbuff) binbuff->Release(); return false; } } } bin.clear(); bin.insert(bin.end(),hash,hash+16); bin.insert(bin.end(),(byte*)binbuff->GetBufferPointer(),((byte*)binbuff->GetBufferPointer())+binbuff->GetBufferSize()); fxc->Release(); binbuff->Release(); _save_scrambled(bpath,bin); bin.erase(bin.begin(),bin.begin()+16); return true; } bool DevEffect::CompileVersion( const char *id, const char *path, vector<byte> &bin, vector<D3DXMACRO> &macros, const char *skip_list ) { ID3DXEffect *fx = NULL; ID3DXBuffer *errors = NULL; HRESULT r = D3DXCreateEffectEx(Dev.GetDevice(),&bin[0],(DWORD)bin.size(),&macros[0],NULL,skip_list, compile_flags,pool,&fx,&errors); if(FAILED(r) || errors) { if(errors) { last_error = format("%s:%s: %s",path,id,(char*)errors->GetBufferPointer()); if(!(flags&FXF_NO_ERROR_POPUPS)) if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL) ExitProcess(0); errors->Release(); return false; } else { last_error = format("%s:%s: Unknown error!",path,id); if(!(flags&FXF_NO_ERROR_POPUPS)) if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL) ExitProcess(0); return false; } } version_index[id] = (int)fx_list.size(); fx_list.push_back(fx); return true; }
22.405229
121
0.615908
Krzysiek-K
074aba4ac8cd17f5b576a985f4a93691da34d019
8,760
cpp
C++
game/bg_slidemove.cpp
kugelrund/Elite-Reinforce
a2fe0c0480ff2d9cdc241b9e5416ee7f298f00ca
[ "DOC" ]
10
2017-07-04T14:38:48.000Z
2022-03-08T22:46:39.000Z
game/bg_slidemove.cpp
UberGames/SP-Mod-Source-Code
04e0e618d1ee57a2919f1a852a688c03b1aa155d
[ "DOC" ]
null
null
null
game/bg_slidemove.cpp
UberGames/SP-Mod-Source-Code
04e0e618d1ee57a2919f1a852a688c03b1aa155d
[ "DOC" ]
2
2017-04-23T18:24:44.000Z
2021-11-19T23:27:03.000Z
#include "q_shared.h" #include "bg_public.h" #include "bg_local.h" /* input: origin, velocity, bounds, groundPlane, trace function output: origin, velocity, impacts, stairup boolean */ /* ================== PM_SlideMove Returns qtrue if the velocity was clipped in some way ================== */ #define MAX_CLIP_PLANES 5 qboolean PM_SlideMove( qboolean gravity ) { int bumpcount, numbumps; vec3_t dir; float d; int numplanes; vec3_t planes[MAX_CLIP_PLANES]; vec3_t primal_velocity; vec3_t clipVelocity; int i, j, k; trace_t trace; vec3_t end; float time_left; float into; vec3_t endVelocity; vec3_t endClipVelocity; numbumps = 4; VectorCopy (pm->ps->velocity, primal_velocity); if ( gravity ) { VectorCopy( pm->ps->velocity, endVelocity ); endVelocity[2] -= pm->ps->gravity * pml.frametime; pm->ps->velocity[2] = ( pm->ps->velocity[2] + endVelocity[2] ) * 0.5; primal_velocity[2] = endVelocity[2]; if ( pml.groundPlane ) { // slide along the ground plane PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP ); } } time_left = pml.frametime; // never turn against the ground plane if ( pml.groundPlane ) { numplanes = 1; VectorCopy( pml.groundTrace.plane.normal, planes[0] ); } else { numplanes = 0; } // never turn against original velocity VectorNormalize2( pm->ps->velocity, planes[numplanes] ); numplanes++; for ( bumpcount=0 ; bumpcount < numbumps ; bumpcount++ ) { // calculate position we are trying to move to VectorMA( pm->ps->origin, time_left, pm->ps->velocity, end ); // see if we can make it there pm->trace ( &trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, pm->tracemask); if (trace.allsolid) { // entity is completely trapped in another solid pm->ps->velocity[2] = 0; // don't build up falling damage, but allow sideways acceleration return qtrue; } if (trace.fraction > 0) { // actually covered some distance VectorCopy (trace.endpos, pm->ps->origin); } if (trace.fraction == 1) { break; // moved the entire distance } pm->ps->pm_flags |= PMF_BUMPED; // save entity for contact PM_AddTouchEnt( trace.entityNum ); time_left -= time_left * trace.fraction; if (numplanes >= MAX_CLIP_PLANES) { // this shouldn't really happen VectorClear( pm->ps->velocity ); return qtrue; } // // if this is the same plane we hit before, nudge velocity // out along it, which fixes some epsilon issues with // non-axial planes // for ( i = 0 ; i < numplanes ; i++ ) { if ( DotProduct( trace.plane.normal, planes[i] ) > 0.99 ) { VectorAdd( trace.plane.normal, pm->ps->velocity, pm->ps->velocity ); break; } } if ( i < numplanes ) { continue; } VectorCopy (trace.plane.normal, planes[numplanes]); numplanes++; // // modify velocity so it parallels all of the clip planes // // find a plane that it enters for ( i = 0 ; i < numplanes ; i++ ) { into = DotProduct( pm->ps->velocity, planes[i] ); if ( into >= 0.1 ) { continue; // move doesn't interact with the plane } // see how hard we are hitting things if ( -into > pml.impactSpeed ) { pml.impactSpeed = -into; } // slide along the plane PM_ClipVelocity (pm->ps->velocity, planes[i], clipVelocity, OVERCLIP ); // slide along the plane PM_ClipVelocity (endVelocity, planes[i], endClipVelocity, OVERCLIP ); // see if there is a second plane that the new move enters for ( j = 0 ; j < numplanes ; j++ ) { if ( j == i ) { continue; } if ( DotProduct( clipVelocity, planes[j] ) >= 0.1 ) { continue; // move doesn't interact with the plane } // try clipping the move to the plane PM_ClipVelocity( clipVelocity, planes[j], clipVelocity, OVERCLIP ); PM_ClipVelocity( endClipVelocity, planes[j], endClipVelocity, OVERCLIP ); // see if it goes back into the first clip plane if ( DotProduct( clipVelocity, planes[i] ) >= 0 ) { continue; } // slide the original velocity along the crease CrossProduct (planes[i], planes[j], dir); VectorNormalize( dir ); d = DotProduct( dir, pm->ps->velocity ); VectorScale( dir, d, clipVelocity ); CrossProduct (planes[i], planes[j], dir); VectorNormalize( dir ); d = DotProduct( dir, endVelocity ); VectorScale( dir, d, endClipVelocity ); // see if there is a third plane the the new move enters for ( k = 0 ; k < numplanes ; k++ ) { if ( k == i || k == j ) { continue; } if ( DotProduct( clipVelocity, planes[k] ) >= 0.1 ) { continue; // move doesn't interact with the plane } // stop dead at a tripple plane interaction VectorClear( pm->ps->velocity ); return qtrue; } } // if we have fixed all interactions, try another move VectorCopy( clipVelocity, pm->ps->velocity ); VectorCopy( endClipVelocity, endVelocity ); break; } } if ( gravity ) { VectorCopy( endVelocity, pm->ps->velocity ); } // don't change velocity if in a timer (FIXME: is this correct?) if ( pm->ps->pm_time ) { VectorCopy( primal_velocity, pm->ps->velocity ); } return ( bumpcount != 0 ); } /* ================== PM_StepSlideMove ================== */ void PM_StepSlideMove( qboolean gravity ) { vec3_t start_o, start_v; vec3_t down_o, down_v; vec3_t slideMove, stepUpMove; trace_t trace; vec3_t up, down; qboolean cantStepUpFwd; VectorCopy (pm->ps->origin, start_o); VectorCopy (pm->ps->velocity, start_v); if ( PM_SlideMove( gravity ) == 0 ) { return; // we got exactly where we wanted to go first try }//else Bumped into something, see if we can step over it //Q3Final addition... VectorCopy(start_o, down); down[2] -= STEPSIZE; pm->trace (&trace, start_o, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask); VectorSet(up, 0, 0, 1); // never step up when you still have up velocity if ( pm->ps->velocity[2] > 0 && (trace.fraction == 1.0 || DotProduct(trace.plane.normal, up) < 0.7)) { return; } if ( !pm->ps->velocity[0] && !pm->ps->velocity[1] ) {//All our velocity was cancelled sliding return; } VectorCopy (pm->ps->origin, down_o); VectorCopy (pm->ps->velocity, down_v); VectorCopy (start_o, up); up[2] += STEPSIZE; // test the player position if they were a stepheight higher pm->trace (&trace, start_o, pm->mins, pm->maxs, up, pm->ps->clientNum, pm->tracemask); if ( trace.allsolid || trace.startsolid || trace.fraction == 0) { if ( pm->debugLevel ) { Com_Printf("%i:bend can't step\n", c_pmove); } return; // can't step up } // try slidemove from this position VectorCopy (trace.endpos, pm->ps->origin); VectorCopy (start_v, pm->ps->velocity); cantStepUpFwd = PM_SlideMove( gravity ); //compare the initial slidemove and this slidemove from a step up position VectorSubtract( down_o, start_o, slideMove ); VectorSubtract( trace.endpos, pm->ps->origin, stepUpMove ); if ( fabs(stepUpMove[0]) < 0.1 && fabs(stepUpMove[1]) < 0.1 && VectorLengthSquared( slideMove ) > VectorLengthSquared( stepUpMove ) ) { //slideMove was better, use it VectorCopy (down_o, pm->ps->origin); VectorCopy (down_v, pm->ps->velocity); } else { // push down the final amount VectorCopy (pm->ps->origin, down); down[2] -= STEPSIZE; pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask); if ( !trace.allsolid ) { VectorCopy (trace.endpos, pm->ps->origin); } if ( trace.fraction < 1.0 ) { PM_ClipVelocity( pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP ); } } if(cantStepUpFwd && pm->ps->origin[2] < start_o[2] + STEPSIZE && pm->ps->origin[2] >= start_o[2]) {//We bumped into something we could not step up pm->ps->pm_flags |= PMF_BLOCKED; } else {//We did step up, clear the bumped flag pm->ps->pm_flags &= ~PMF_BUMPED; } #if 0 // if the down trace can trace back to the original position directly, don't step pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, start_o, pm->ps->clientNum, pm->tracemask); if ( trace.fraction == 1.0 ) { // use the original move VectorCopy (down_o, pm->ps->origin); VectorCopy (down_v, pm->ps->velocity); if ( pm->debugLevel ) { Com_Printf("%i:bend\n", c_pmove); } } else #endif { // use the step move float delta; delta = pm->ps->origin[2] - start_o[2]; if ( delta > 2 ) { if ( delta < 7 ) { PM_AddEvent( EV_STEP_4 ); } else if ( delta < 11 ) { PM_AddEvent( EV_STEP_8 ); } else if ( delta < 15 ) { PM_AddEvent( EV_STEP_12 ); } else { PM_AddEvent( EV_STEP_16 ); } } if ( pm->debugLevel ) { Com_Printf("%i:stepped\n", c_pmove); } } }
26.465257
134
0.638128
kugelrund
074bda5fb0986fa2c221fd1829df4b2502550247
9,107
cpp
C++
PIPS-IPM/Drivers/statgdx/p3Custom2.cpp
dRehfeldt/PIPS
24d3ea89a0a1aa77c133cfc698a568eb685c9fdb
[ "BSD-3-Clause-LBNL" ]
6
2020-10-29T15:14:14.000Z
2021-07-14T13:31:54.000Z
PIPS-IPM/Drivers/statgdx/p3Custom2.cpp
dRehfeldt/PIPS
24d3ea89a0a1aa77c133cfc698a568eb685c9fdb
[ "BSD-3-Clause-LBNL" ]
null
null
null
PIPS-IPM/Drivers/statgdx/p3Custom2.cpp
dRehfeldt/PIPS
24d3ea89a0a1aa77c133cfc698a568eb685c9fdb
[ "BSD-3-Clause-LBNL" ]
1
2019-02-15T16:30:44.000Z
2019-02-15T16:30:44.000Z
/* $Id: p3Custom2.cpp 52165 2015-05-19 13:33:37Z sdirkse $ * This code is sensitive to the order of the #defines, so inlining is not OK */ #if defined(__linux) && ! defined(_GNU_SOURCE) # define _GNU_SOURCE /* required for dladdr() but no desired globally */ #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN /* google it */ # include <windows.h> # define snprintf _snprintf #else # include <unistd.h> #endif #if defined(__linux) || defined(__sun) # include <dlfcn.h> #endif #if defined(__APPLE__) # include <dlfcn.h> # include <libproc.h> #endif #if defined(__HOS_AIX__) # include <procinfo.h> # include <sys/procfs.h> # include <dlfcn.h> # include <sys/types.h> # include <sys/ldr.h> #endif #include "p3Custom2.h" /* local use only: be sure to call with enough space for the sprintf */ static void myStrError (int n, char *buf, size_t bufSiz) { #if defined(_WIN32) if (strerror_s (buf, bufSiz, n)) (void) sprintf (buf, "errno = %d", n); #else if (strerror_r (n, buf, bufSiz)) (void) sprintf (buf, "errno = %d", n); #endif } /* myStrError */ static void pchar2SS (unsigned char *ss, const char *p) { char *d = (char *)ss+1; const char *s = p; const char *end = s + 255; while (*s && (s < end)) *d++ = *s++; *ss = (unsigned char) (s - p); } /* pchar2SS */ int xGetExecName (unsigned char *execName, unsigned char *msg) { char execBuf[4096]; char msgBuf[2048]; char tmpBuf[2048]; int rc; *msgBuf = '\0'; rc = 8; #if defined(__APPLE__) { int k; pid_t pid = getpid(); k = proc_pidpath (pid, execBuf, sizeof(execBuf)); if (k <= 0) { myStrError (errno, tmpBuf, sizeof(tmpBuf)); (void) snprintf (msgBuf, sizeof(msgBuf), "proc_pidpath(pid=%ld) failed: %s", (long int) pid, tmpBuf); msgBuf[sizeof(msgBuf)-1] = '\0'; *execBuf = '\0'; rc = 4; } else rc = 0; } #elif defined(__HOS_AIX__) { char procPath[128]; struct stat statData; struct psinfo psinfoData; ssize_t ssz; pid_t pid; int k, fd; pid = getpid(); sprintf (procPath, "/proc/%ld/psinfo", (long int) pid); k = stat (procPath, &statData); if (k) { /* error */ myStrError (errno, tmpBuf, sizeof(tmpBuf)); (void) snprintf (msgBuf, sizeof(msgBuf), "stat(%s,...) failure: %s", procPath, tmpBuf); msgBuf[sizeof(msgBuf)-1] = '\0'; *execBuf = '\0'; rc = 4; } else { fd = open (procPath, O_RDONLY); if (fd <= 0) { /* error */ myStrError (errno, tmpBuf, sizeof(tmpBuf)); (void) snprintf (msgBuf, sizeof(msgBuf), "open(%s, O_RDONLY) failure: %s", procPath, tmpBuf); msgBuf[sizeof(msgBuf)-1] = '\0'; *execBuf = '\0'; rc = 5; } else { ssz = read (fd, &psinfoData, sizeof(psinfoData)); close (fd); if (ssz < 0) { /* error */ myStrError (errno, tmpBuf, sizeof(tmpBuf)); (void) snprintf (msgBuf, sizeof(msgBuf), "reading %ld bytes of psinfoData from %s failed: %s", sizeof(psinfoData), procPath, tmpBuf); msgBuf[sizeof(msgBuf)-1] = '\0'; *execBuf = '\0'; rc = 6; } else { const char *argv0; argv0 = ((const char ***) psinfoData.pr_argv)[0][0]; if (realpath(argv0,execBuf)) /* success */ rc = 0; else { myStrError (errno, tmpBuf, sizeof(tmpBuf)); (void) snprintf (msgBuf, sizeof(msgBuf), "realpath() failure: %s", tmpBuf); msgBuf[sizeof(msgBuf)-1] = '\0'; *execBuf = '\0'; rc = 7; } } /* read worked OK */ } /* open worked OK */ } /* stat worked OK */ } #elif defined(__linux) { ssize_t ssz; ssz = readlink ("/proc/self/exe", execBuf, sizeof(execBuf)); if (ssz < 0) { myStrError (errno, tmpBuf, sizeof(tmpBuf)); (void) snprintf (msgBuf, sizeof(msgBuf), "readlink(/proc/self/exe,...) failure: %s", tmpBuf); msgBuf[sizeof(msgBuf)-1] = '\0'; *execBuf = '\0'; rc = 4; } else { if (ssz >= (ssize_t) sizeof(execBuf)) ssz = (ssize_t) sizeof(execBuf) - 1; execBuf[ssz] = '\0'; rc = 0; } } #elif defined(__sun) { const char *execname; execname = getexecname(); if (NULL == execname) { sprintf (msgBuf, "getexecname() failure"); *execBuf = '\0'; rc = 4; } else { if (realpath(execname,execBuf)) rc = 0; else { myStrError (errno, tmpBuf, sizeof(tmpBuf)); (void) snprintf (msgBuf, sizeof(msgBuf), "realpath() failure: %s", tmpBuf); msgBuf[sizeof(msgBuf)-1] = '\0'; *execBuf = '\0'; rc = 5; } } } #elif defined(_WIN32) { HMODULE h; int k = GetModuleFileName (NULL, execBuf, sizeof(execBuf)); if (0 == k) { sprintf (msgBuf, "GetModuleFileName() failure: rc=%d", k); *execBuf = '\0'; rc = 4; } else rc = 0; } #else *execBuf = '\0'; (void) strcpy (msgBuf, "not implemented for this platform"); rc = 8; #endif pchar2SS (execName, execBuf); pchar2SS (msg, msgBuf); if ((0 == rc) && (strlen(execBuf) > 255)) rc = 1; return rc; } /* xGetExecName */ int xGetLibName (unsigned char *libName, unsigned char *msg) { char libBuf[4096]; char msgBuf[2048+20]; char tmpBuf[2048]; int rc, k; *msgBuf = '\0'; rc = 8; #if defined(__linux) || defined(__sun) || defined(__APPLE__) { Dl_info dlInfo; k = dladdr((void *)(&xGetLibName), &dlInfo); if (k > 0) { strncpy (tmpBuf, dlInfo.dli_fname, sizeof(tmpBuf)); tmpBuf[sizeof(tmpBuf)-1] = '\0'; if (realpath(tmpBuf,libBuf)) rc = 0; else { myStrError (errno, tmpBuf, sizeof(tmpBuf)); sprintf (msgBuf, "realpath() failure: %s", tmpBuf); *libBuf = '\0'; rc = 5; } } else { sprintf (msgBuf, "dladdr() failure"); *libBuf = '\0'; rc = 4; } } #elif defined(__HOS_AIX__) { /* some truly ugly code to get the shared library name: * so ugly it's beautiful */ const size_t bufSize = 8192; char buf[bufSize], *pBuf; struct ld_info *pldi = (struct ld_info *) buf; void *pMe, *pLo, *pUp; k = loadquery (L_GETINFO, pldi, bufSize); if (k) { myStrError (errno, tmpBuf, sizeof(tmpBuf)); (void) snprintf (msgBuf, sizeof(msgBuf), "loadquery() failure: %s", tmpBuf); msgBuf[sizeof(msgBuf)-1] = '\0'; *libBuf = '\0'; rc = 4; } else { /* loadquery OK */ int done = 0; /* pMe = &xGetLibName; */ /* on AIX &xGetLibName is a TOC (Table-Of-Contents) pointer, must dereference * For more on this, I found this URL helpful: * http://physinfo.ulb.ac.be/divers_html/powerpc_programming_info/intro_to_ppc/ppc4_runtime4.html */ pMe = (void *) * (unsigned long *) (void *) &xGetLibName; pBuf = buf; while (! done) { pLo = pldi->ldinfo_textorg; pUp = (void *) ((char *)pLo + pldi->ldinfo_textsize); /* printf ("DEBUG AIX dllPath: rng= [%p %p] : %s len=%ld\n", pLo, pUp, pldi->ldinfo_filename, pldi->ldinfo_next); */ if ((pLo <= pMe) && (pMe < pUp)) { if (realpath(pldi->ldinfo_filename,libBuf)) rc = 0; else { myStrError (errno, tmpBuf, sizeof(tmpBuf)); (void) snprintf (msgBuf, sizeof(msgBuf), "realpath() failure: %s", tmpBuf); msgBuf[sizeof(msgBuf)-1] = '\0'; *libBuf = '\0'; rc = 5; } done = 1; } if (0 == pldi->ldinfo_next) done = 1; else { pBuf += pldi->ldinfo_next; pldi = (struct ld_info *) pBuf; } } /* while not done */ } /* loadquery OK */ } #elif defined(_WIN32) { HMODULE h; k = GetModuleHandleEx (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)&xGetLibName, &h); if (k) { /* OK: got a handle */ k = GetModuleFileName (h, libBuf, sizeof(libBuf)); if (0 == k) { sprintf (msgBuf, "GetModuleFileName() failure: rc=%d", k); *libBuf = '\0'; rc = 5; } else { rc = 0; } } else { sprintf (msgBuf, "GetModuleHandleEx() failure: rc=%d", k); *libBuf = '\0'; rc = 4; } } #else *libBuf = '\0'; (void) strcpy (msgBuf, "not implemented for this platform"); rc = 8; #endif pchar2SS (libName, libBuf); pchar2SS (msg, msgBuf); if ((0 == rc) && (strlen(libBuf) > 255)) rc = 1; return rc; } /* xGetLibName */
26.16954
103
0.527616
dRehfeldt
074ef64e1adb81315179e0c97678b58f80be9f71
8,342
cpp
C++
arimaa_com.cpp
TFiFiE/4steps
fa0830bea3187dd49d5e8ad1476a8ad29a676cdf
[ "Apache-2.0" ]
9
2018-01-12T08:22:35.000Z
2022-01-05T01:31:39.000Z
arimaa_com.cpp
TFiFiE/4steps
fa0830bea3187dd49d5e8ad1476a8ad29a676cdf
[ "Apache-2.0" ]
4
2018-02-05T21:57:39.000Z
2018-12-01T23:38:31.000Z
arimaa_com.cpp
TFiFiE/4steps
fa0830bea3187dd49d5e8ad1476a8ad29a676cdf
[ "Apache-2.0" ]
2
2018-02-05T23:18:51.000Z
2021-12-17T18:42:02.000Z
#include <QNetworkReply> #include <QNetworkCookieJar> #include <QNetworkCookie> #include <QCheckBox> #include <QDesktopServices> #include "arimaa_com.hpp" #include "asip1.hpp" #include "asip2.hpp" #include "server.hpp" #include "io.hpp" #include "bots.hpp" template<class Base> Arimaa_com<Base>::Arimaa_com(QNetworkAccessManager& networkAccessManager,const QString& serverURL,QObject* const parent,typename Base::Data startingData) : Base(networkAccessManager,serverURL,parent,startingData), ratedMode(true) { Base::connect(this,&Base::sendGameList,[this](const typename Base::GameListCategory gameListCategory,const std::vector<typename Base::GameInfo>& games) { auto& fixedCatGames=fixedGames[gameListCategory]; fixedCatGames.clear(); const bool alreadyJoined=(gameListCategory!=Base::INVITED_GAMES && gameListCategory!=Base::OPEN_GAMES); for (const auto& game:games) { if (alreadyJoined || !game.rated || std::none_of(std::begin(game.players),std::end(game.players),isBotName)) fixedCatGames.emplace(game.id); } }); } template<class Base> std::unique_ptr<::ASIP> Arimaa_com<Base>::create(QNetworkAccessManager& networkAccessManager,const QString& serverURL,QObject* const parent,typename Base::Data startingData) const { using namespace std; return make_unique<Arimaa_com<Base> >(networkAccessManager,serverURL,parent,startingData); } template<class Base> typename Base::Data Arimaa_com<Base>::processReply(QNetworkReply& networkReply) { return Base::processReply(networkReply); } template<> typename ASIP::Data Arimaa_com<ASIP2>::processReply(QNetworkReply& networkReply) { try { return ASIP::processReply(networkReply); } catch (const std::exception&) { if (networkReply.property("action")=="cancelopengame") // SERVER BUG: Cancelling with ASIP 2.0 triggers error. return ASIP::Data({{"ok","1"}}); throw; } } template<class Base> void Arimaa_com<Base>::enterGame(QObject* const requester,const QString& gameID,const Side side,const std::function<void(QNetworkReply*)> networkReplyAction) { Base::enterGame(requester,gameID,side,networkReplyAction); } template<> void Arimaa_com<ASIP2>::enterGame(QObject* const requester,const QString& gameID,const Side side,const std::function<void(QNetworkReply*)> networkReplyAction) { if (side==NO_SIDE) { // SERVER BUG: Can't spectate with ASIP 2.0. QReadLocker readLocker(&mostRecentData_mutex); ASIP1 asip1(networkAccessManager,serverDirectory().toString()+"client1gr.cgi",nullptr,mostRecentData); readLocker.unlock(); asip1.enterGame(requester,gameID,side,networkReplyAction); synchronizeData(asip1); return; } else if (possiblyDerateable(gameID)) { const auto possible=doMeDependingAction([=] { QReadLocker readLocker(&mostRecentData_mutex); const auto me=mostRecentData.value("me").value<QVariantHash>(); const auto sid=mostRecentData.value("sid"); readLocker.unlock(); const auto server=serverDirectory(); const auto cookieJar=networkAccessManager.cookieJar(); const auto oldCookies=cookieJar->cookiesForUrl(server); cookieJar->setCookiesFromUrl({QNetworkCookie("unrated"+me["id"].toByteArray(),"1"),QNetworkCookie("sid",sid.toByteArray())},server); const auto networkReply=networkAccessManager.get(QNetworkRequest(QUrl(server.toString()+"opengamewin.cgi?gameid="+gameID+"&side="+QString(toLetter(side))))); networkReply->setParent(this); for (const auto& cookie:cookieJar->cookiesForUrl(server)) cookieJar->deleteCookie(cookie); cookieJar->setCookiesFromUrl(oldCookies,server); connect(networkReply,&QNetworkReply::finished,this,[=] { networkReply->deleteLater(); ASIP::enterGame(requester,gameID,side,networkReplyAction); }); }); if (possible) return; } ASIP::enterGame(requester,gameID,side,networkReplyAction); } template<class Base> std::unique_ptr<::ASIP> Arimaa_com<Base>::getGame(QNetworkReply& networkReply) { return Base::getGame(networkReply); } template<> std::unique_ptr<::ASIP> Arimaa_com<ASIP2>::getGame(QNetworkReply& networkReply) { if (networkReply.property("role")=="v" && networkReply.property("action")=="reserveseat") { // SERVER BUG: Can't spectate with ASIP 2.0. QReadLocker readLocker(&mostRecentData_mutex); ASIP1 asip1(networkAccessManager,serverDirectory().toString()+"client1gr.cgi",nullptr,mostRecentData); readLocker.unlock(); asip1.processReply(networkReply); synchronizeData(asip1); } else processReply(networkReply); QWriteLocker writeLocker(&mostRecentData_mutex); auto gsurl=mostRecentData.value("gsurl").toString(); if (QUrl(gsurl).isRelative()) // SERVER BUG: Joining with ASIP 2.0 returns partial game server URL. gsurl=serverDirectory().toString()+"../java/ys/ms4/v5/"+gsurl; gsurl=QUrl(gsurl).adjusted(QUrl::RemoveFilename).toString()+"client2gs.cgi"; // SERVER BUG: Returned game server always uses ASIP 1.0. mostRecentData.insert("gsurl",gsurl); writeLocker.unlock(); return ASIP::getGame(); } template<class Base> bool Arimaa_com<Base>::possiblyDerateable(const QString& gameID) const { if (ratedMode) return false; for (const auto& category:fixedGames) if (category.second.find(gameID)!=category.second.end()) return false; return true; } template<class Base> std::unique_ptr<QWidget> Arimaa_com<Base>::siteWidget(Server& server) { const auto mainLayout=new QHBoxLayout; mainLayout->addWidget(botWidget(server.mainWindow).release()); if (std::is_same<Base,ASIP2>::value) { const auto ratedBox=new QCheckBox("Keep joined bot games rated"); mainLayout->addWidget(ratedBox,0,Qt::AlignCenter); ratedBox->setChecked(ratedMode); Base::connect(ratedBox,&QCheckBox::toggled,[this](const bool checked) {ratedMode=checked;}); mainLayout->addWidget(chatroomWidget().release()); } using namespace std; auto widget=make_unique<QWidget>(); widget->setLayout(mainLayout); return widget; } template<class Base> bool Arimaa_com<Base>::isBotName(const QString& playerName) { return playerName.indexOf("bot_")==0; } template<class Base> QUrl Arimaa_com<Base>::serverDirectory() const { return Base::serverURL().adjusted(QUrl::RemoveFilename); } template<class Base> template<class Function> bool Arimaa_com<Base>::doMeDependingAction(Function action) { static_cast<void>(action); return false; } template<> template<class Function> bool Arimaa_com<ASIP2>::doMeDependingAction(Function action) { QReadLocker readLocker(&mostRecentData_mutex); if (mostRecentData.contains("me")) { readLocker.unlock(); action(); } else { readLocker.unlock(); const auto networkReplies=state(); connect(networkReplies.front(),&QNetworkReply::finished,this,[this,action] { const QReadLocker readLocker(&mostRecentData_mutex); action(); }); } return true; } template<class Base> std::unique_ptr<QWidget> Arimaa_com<Base>::chatroomWidget() { return nullptr; } template<> std::unique_ptr<QWidget> Arimaa_com<ASIP2>::chatroomWidget() { using namespace std; auto chatroom=make_unique<QPushButton>("Enter chat room"); connect(chatroom.get(),&QPushButton::clicked,this,[this] { doMeDependingAction([this] { const auto me=mostRecentData.value("me").value<QVariantHash>(); const auto url=serverDirectory().toString()+"../chat/chat.php?user="+username()+"&auth="+me["auth"].toString(); QDesktopServices::openUrl(url); }); }); return chatroom; } template<class Base> std::unique_ptr<QWidget> Arimaa_com<Base>::botWidget(MainWindow& mainWindow) { using namespace std; auto bots=make_unique<QPushButton>("Bot launcher"); const auto url=serverDirectory().toString()+"botLadderAll.cgi"; Base::connect(bots.get(),&QPushButton::clicked,this,[this,url,&mainWindow] { #if 1 new Bots(*this,url+"?u="+Base::username(),mainWindow); #else const bool possible=doMeDependingAction([this,url,&mainWindow] { const auto me=Base::mostRecentData.value("me").template value<QVariantHash>(); new Bots(*this,url+"?u="+me["id"].toString(),mainWindow); }); if (!possible) new Bots(*this,url,mainWindow); #endif }); return bots; } template class Arimaa_com<ASIP1>; template class Arimaa_com<ASIP2>;
33.502008
179
0.729921
TFiFiE
0754f28f523f0241dceb47eec5faa20c19e5dd21
484
cpp
C++
src/utils.cpp
KarateSnoopy/vcv-karatesnoopy
4168a22c4fd90790697f8a2416472fe257153294
[ "MIT" ]
25
2017-10-26T12:44:09.000Z
2019-11-19T16:56:05.000Z
src/utils.cpp
KarateSnoopy/vcv-snoopy
4168a22c4fd90790697f8a2416472fe257153294
[ "MIT" ]
10
2017-10-27T06:17:58.000Z
2021-02-05T15:42:43.000Z
src/utils.cpp
KarateSnoopy/vcv-snoopy
4168a22c4fd90790697f8a2416472fe257153294
[ "MIT" ]
2
2017-11-09T09:06:23.000Z
2018-03-01T00:32:33.000Z
#include "utils.h" static long _stepCount = 0; void log_increase_step_number() { _stepCount++; } void write_log(long freq, const char *format, ...) { if (freq == 0) freq++; if (_stepCount % freq == 0) // log every "freq". eg pass in 10000 to issue this log every 10k steps { va_list args; va_start(args, format); printf("%ld: ", _stepCount); vprintf(format, args); fflush(stdout); va_end(args); } }
16.689655
104
0.566116
KarateSnoopy
075c6da5785e389ddbebf04c64bf0e0eb79df09e
640
hpp
C++
test/vector/vml/v_max.hpp
rigarash/monolish-debian-package
70b4917370184bcf07378e1907c5239a1ad9579b
[ "Apache-2.0" ]
172
2021-04-05T10:04:40.000Z
2022-03-28T14:30:38.000Z
test/vector/vml/v_max.hpp
rigarash/monolish-debian-package
70b4917370184bcf07378e1907c5239a1ad9579b
[ "Apache-2.0" ]
96
2021-04-06T01:53:44.000Z
2022-03-09T07:27:09.000Z
test/vector/vml/v_max.hpp
termoshtt/monolish
1cba60864002b55bc666da9baa0f8c2273578e01
[ "Apache-2.0" ]
8
2021-04-05T13:21:07.000Z
2022-03-09T23:24:06.000Z
#include "../../test_utils.hpp" template <typename T> T ans_vmax(monolish::vector<T> &ans) { return *(std::max_element(ans.begin(), ans.end())); } template <typename T> bool test_send_vmax(const size_t size, double tol) { monolish::vector<T> x(size, 0.1, 10.0); T ans = ans_vmax(x); monolish::util::send(x); T result = monolish::vml::max(x); return ans_check<T>(__func__, result, ans, tol); } template <typename T> bool test_vmax(const size_t size, double tol) { monolish::vector<T> x(size, 0.1, 10.0); T ans = ans_vmax(x); T result = monolish::vml::max(x); return ans_check<T>(__func__, result, ans, tol); }
22.068966
74
0.65625
rigarash
075f30d00377f3e0a27342f4fdf1ab7d5535e71b
2,829
cpp
C++
Source/Objects/Shop.cpp
DrStrangelove42/DearmOfaRidiculousMan
a19af08c0a044ed4a30194ffdfac912475618b14
[ "MIT" ]
null
null
null
Source/Objects/Shop.cpp
DrStrangelove42/DearmOfaRidiculousMan
a19af08c0a044ed4a30194ffdfac912475618b14
[ "MIT" ]
7
2020-11-20T08:57:10.000Z
2021-03-22T20:40:04.000Z
Source/Objects/Shop.cpp
DrStrangelove42/DreamOfaRidiculousMan
a19af08c0a044ed4a30194ffdfac912475618b14
[ "MIT" ]
null
null
null
#include "Shop.h" //#include "../Characters/Player.h" Shop::Shop(string id, string name, string speech, int posx, int posy, RenderContext& renderer, Map* map) : NPC(id, name, speech, posx, posy, "shop", renderer, map, false), player(NULL) { } Shop::~Shop() { for (auto& entry : contents) { delete entry.first; } contents.clear(); } Shop::Shop(string headerline, int* uniqueId, int posx, int posy, RenderContext& renderer) : Shop("", "", "", posx, posy, renderer, NULL) { size_t pos = headerline.find(" "); id = headerline.substr(0, pos); headerline.erase(0, pos + 1); name = EatToken(headerline); speech = EatToken(headerline); setTexture(renderer); // After the identifier, the items in the chest are described between brackets [ and ] with count and price, one after the other. while (headerline.length() > 0 && headerline[0] == '[') { size_t nextpar = headerline.find('[', 1); string currentObject = headerline.substr(1, nextpar - 1); headerline.erase(0, nextpar); nextpar = currentObject.find(']'); string objString = currentObject.substr(0, nextpar); currentObject.erase(0, nextpar + 1); PickableObject* obj = (PickableObject*)Map::parseObject(objString, renderer, uniqueId, -1, -1); size_t a; int count = stoi(currentObject, &a); currentObject.erase(0, a + 1); int price = stoi(currentObject); addObjectToSell(obj, count, price); } buildButtons(renderer); } bool Shop::updateObject(GAME* g) { if (player == NULL) player = g->player; if (!isPlayerNearby(g->player)) { g->currentMap->unregisterTopMostTexture("ShopBtnInfoTip"); } return NPC::updateObject(g); } string Shop::objectToString() const { string text = id; for (auto& entry : contents) { text += "[" + entry.first->objectToString() + "] " + to_string(entry.second.first) + " " + to_string(entry.second.second) + " "; } return text; } void Shop::buildButtons(RenderContext& r) { int id = 0; for (auto& entry : contents) { //todo image+text Button* b = new InfoTipButton( r.LoadStringWithIcon("x" + to_string(entry.second.first) + " : " + to_string(entry.second.second) + " gold", entry.first->getTextureID(), 0xD39206FF), r, -1, -1 /*x and y will be set with addChoice()*/, id, [this, entry](int i) { if (player != NULL) { if (player->getMoney() >= entry.second.second) { //the player can buy the object player->addMoney(-entry.second.second); //Clone the object PickableObject* p = entry.first->clone(); //Add the cloned object to the player player->pickUpObject(p, entry.second.first); } } }, entry.first->getInfo() ); addChoice(b); index.push_back(entry.first); id++; } } void Shop::addObjectToSell(PickableObject* pObj, int count, int price) { contents[pObj] = { count,price }; }
24.179487
153
0.653588
DrStrangelove42
076188d3b38034867405a8190c6ff683f53f0bf6
2,177
cpp
C++
ex01-09.cpp
GabrielScalici/UVA
e5a56b1ad10df8f1e3d1d6f8fd6d32348a16349f
[ "MIT" ]
null
null
null
ex01-09.cpp
GabrielScalici/UVA
e5a56b1ad10df8f1e3d1d6f8fd6d32348a16349f
[ "MIT" ]
null
null
null
ex01-09.cpp
GabrielScalici/UVA
e5a56b1ad10df8f1e3d1d6f8fd6d32348a16349f
[ "MIT" ]
null
null
null
#include <iostream> #include <string.h> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <vector> #include <stack> #include <queue> #include <math.h> #define MAX 100 #define GRANDE 100000.0 #define TAM 2 using namespace std; int main(int argc, char const *argv[]){ double P[MAX][TAM]; int i; int T, n; //Pegando a quantidade scanf("%d", &T); //Pegsndo a quantidade de casos scanf("%d", &n); //Percorrendo a quantidade de casos for(int i = 0; i < n; i++){ //pegando os valores float num1; scanf("%f\n", &num1); P[i][0] = num1; float num2; scanf("%f\n", &num2); P[i][1] = num2; } //Fazendo Dijkstra float dist[MAX]; int arv[MAX]; memset(arv, 0, sizeof(arv)); //iniciando com uma distancia grande for(i = 0; i < MAX; i++){ if(i == 0){ dist[i] = 0; }else{ dist[i] = GRANDE; } } //variaveis para o codigo abaixo int aux = 0; double total = 0; //percorrendo enquanto for valido (nao visitado) while(arv[aux] == 0){ arv[aux] = 1; total = total + dist[aux]; //percorrendo n vezes para ver todos os nos for(i = 0; i < n; i++){ if(arv[i] == 0){ //variaveis com as contas int resul1 = pow(P[aux][0]-P[i][0],2); int resul2 = pow(P[aux][1]-P[i][1],2); //realizando as contas float resul_total = sqrt(resul1 + resul2); //analisando a dist minima if(resul_total < dist[i]){ dist[i] = resul_total; } } } //inicia com valor grande para analise int min = GRANDE; //percorrendo todos os possiveis (n) for(i = 0; i < n; i++){ if(arv[i] == 0){ if(min > dist[i]){ //atualizando o aux e o valor min aux = i; min = dist[i]; } } } } //imprimindo para o usuario printf("%.2f\n",total); return 0; }
21.989899
58
0.47175
GabrielScalici
79e45a3459f7bccf1f06af827911d93a3425021c
233
cpp
C++
0744_find_smallest_letter_greater_than_target.cpp
fxshan/LeetCode
a54bbe22bc335dcb3c7efffcc34357cab7641492
[ "Apache-2.0" ]
2
2020-06-04T13:20:20.000Z
2020-06-04T14:49:10.000Z
0744_find_smallest_letter_greater_than_target.cpp
fxshan/LeetCode
a54bbe22bc335dcb3c7efffcc34357cab7641492
[ "Apache-2.0" ]
null
null
null
0744_find_smallest_letter_greater_than_target.cpp
fxshan/LeetCode
a54bbe22bc335dcb3c7efffcc34357cab7641492
[ "Apache-2.0" ]
null
null
null
class Solution { public: char nextGreatestLetter(vector<char>& letters, char target) { for (int i = 0; i < letters.size(); i++) { if ((int)target < (int)letters[i]) return letters[i]; } return letters[0]; } };
23.3
63
0.596567
fxshan
79ed1e5b281d02b10c8e8d7bb46485a4f357abdf
86,647
cc
C++
src/app/common/proto/data.pb.cc
mloves0824/Antalk
fdca57697fb69a6e14bfc12ff2878da419aef793
[ "MIT" ]
null
null
null
src/app/common/proto/data.pb.cc
mloves0824/Antalk
fdca57697fb69a6e14bfc12ff2878da419aef793
[ "MIT" ]
null
null
null
src/app/common/proto/data.pb.cc
mloves0824/Antalk
fdca57697fb69a6e14bfc12ff2878da419aef793
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: data.proto #include "data.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace antalk { namespace data { class GetUserInfoReqDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<GetUserInfoReq> _instance; } _GetUserInfoReq_default_instance_; class GetUserInfoResDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<GetUserInfoRes> _instance; } _GetUserInfoRes_default_instance_; class SetUserStatusReqDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<SetUserStatusReq> _instance; } _SetUserStatusReq_default_instance_; class SetUserStatusRespDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<SetUserStatusResp> _instance; } _SetUserStatusResp_default_instance_; class SaveMsgReqDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<SaveMsgReq> _instance; } _SaveMsgReq_default_instance_; class SaveMsgRespDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<SaveMsgResp> _instance; } _SaveMsgResp_default_instance_; } // namespace data } // namespace antalk namespace protobuf_data_2eproto { void InitDefaultsGetUserInfoReqImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::antalk::data::_GetUserInfoReq_default_instance_; new (ptr) ::antalk::data::GetUserInfoReq(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::antalk::data::GetUserInfoReq::InitAsDefaultInstance(); } void InitDefaultsGetUserInfoReq() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGetUserInfoReqImpl); } void InitDefaultsGetUserInfoResImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS protobuf_common_2eproto::InitDefaultsUserInfo(); { void* ptr = &::antalk::data::_GetUserInfoRes_default_instance_; new (ptr) ::antalk::data::GetUserInfoRes(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::antalk::data::GetUserInfoRes::InitAsDefaultInstance(); } void InitDefaultsGetUserInfoRes() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGetUserInfoResImpl); } void InitDefaultsSetUserStatusReqImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::antalk::data::_SetUserStatusReq_default_instance_; new (ptr) ::antalk::data::SetUserStatusReq(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::antalk::data::SetUserStatusReq::InitAsDefaultInstance(); } void InitDefaultsSetUserStatusReq() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSetUserStatusReqImpl); } void InitDefaultsSetUserStatusRespImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::antalk::data::_SetUserStatusResp_default_instance_; new (ptr) ::antalk::data::SetUserStatusResp(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::antalk::data::SetUserStatusResp::InitAsDefaultInstance(); } void InitDefaultsSetUserStatusResp() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSetUserStatusRespImpl); } void InitDefaultsSaveMsgReqImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS protobuf_common_2eproto::InitDefaultsMsgInfo(); { void* ptr = &::antalk::data::_SaveMsgReq_default_instance_; new (ptr) ::antalk::data::SaveMsgReq(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::antalk::data::SaveMsgReq::InitAsDefaultInstance(); } void InitDefaultsSaveMsgReq() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSaveMsgReqImpl); } void InitDefaultsSaveMsgRespImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); #else ::google::protobuf::internal::InitProtobufDefaults(); #endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::antalk::data::_SaveMsgResp_default_instance_; new (ptr) ::antalk::data::SaveMsgResp(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::antalk::data::SaveMsgResp::InitAsDefaultInstance(); } void InitDefaultsSaveMsgResp() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSaveMsgRespImpl); } ::google::protobuf::Metadata file_level_metadata[6]; const ::google::protobuf::ServiceDescriptor* file_level_service_descriptors[2]; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoReq, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoReq, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoReq, saas_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoReq, uid_), 1, 0, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoRes, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoRes, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoRes, user_info_), 0, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, uid_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, dev_type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, session_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, status_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, login_info_), 0, 3, 1, 4, 2, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusResp, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusResp, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusResp, result_), 0, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgReq, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgReq, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgReq, msg_info_), 0, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgResp, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgResp, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgResp, msg_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgResp, result_code_), 0, 1, }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, 7, sizeof(::antalk::data::GetUserInfoReq)}, { 9, 15, sizeof(::antalk::data::GetUserInfoRes)}, { 16, 26, sizeof(::antalk::data::SetUserStatusReq)}, { 31, 37, sizeof(::antalk::data::SetUserStatusResp)}, { 38, 44, sizeof(::antalk::data::SaveMsgReq)}, { 45, 52, sizeof(::antalk::data::SaveMsgResp)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_GetUserInfoReq_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_GetUserInfoRes_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_SetUserStatusReq_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_SetUserStatusResp_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_SaveMsgReq_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_SaveMsgResp_default_instance_), }; void protobuf_AssignDescriptors() { AddDescriptors(); ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( "data.proto", schemas, file_default_instances, TableStruct::offsets, factory, file_level_metadata, NULL, file_level_service_descriptors); } void protobuf_AssignDescriptorsOnce() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 6); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\ndata.proto\022\013antalk.data\032\014common.proto\"" ".\n\016GetUserInfoReq\022\017\n\007saas_id\030\001 \001(\r\022\013\n\003ui" "d\030\002 \001(\t\"<\n\016GetUserInfoRes\022*\n\tuser_info\030\001" " \001(\0132\027.antalk.common.UserInfo\"f\n\020SetUser" "StatusReq\022\013\n\003uid\030\001 \001(\t\022\020\n\010dev_type\030\002 \001(\005" "\022\017\n\007session\030\003 \001(\t\022\016\n\006status\030\004 \001(\005\022\022\n\nlog" "in_info\030\005 \001(\t\">\n\021SetUserStatusResp\022)\n\006re" "sult\030\001 \001(\0162\031.antalk.common.ResultType\"6\n" "\nSaveMsgReq\022(\n\010msg_info\030\001 \001(\0132\026.antalk.c" "ommon.MsgInfo\"M\n\013SaveMsgResp\022\016\n\006msg_id\030\001" " \001(\003\022.\n\013result_code\030\002 \001(\0162\031.antalk.commo" "n.ResultType2\254\001\n\021UserStatusService\022G\n\013Ge" "tUserInfo\022\033.antalk.data.GetUserInfoReq\032\033" ".antalk.data.GetUserInfoRes\022N\n\rSetUserSt" "atus\022\035.antalk.data.SetUserStatusReq\032\036.an" "talk.data.SetUserStatusResp2J\n\nMsgServic" "e\022<\n\007SaveMsg\022\027.antalk.data.SaveMsgReq\032\030." "antalk.data.SaveMsgRespB\022\n\rcom.antalk.pb" "\200\001\001" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 723); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "data.proto", &protobuf_RegisterTypes); ::protobuf_common_2eproto::AddDescriptors(); } void AddDescriptors() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_data_2eproto namespace antalk { namespace data { // =================================================================== void GetUserInfoReq::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int GetUserInfoReq::kSaasIdFieldNumber; const int GetUserInfoReq::kUidFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 GetUserInfoReq::GetUserInfoReq() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_data_2eproto::InitDefaultsGetUserInfoReq(); } SharedCtor(); // @@protoc_insertion_point(constructor:antalk.data.GetUserInfoReq) } GetUserInfoReq::GetUserInfoReq(const GetUserInfoReq& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); uid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_uid()) { uid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.uid_); } saas_id_ = from.saas_id_; // @@protoc_insertion_point(copy_constructor:antalk.data.GetUserInfoReq) } void GetUserInfoReq::SharedCtor() { _cached_size_ = 0; uid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); saas_id_ = 0u; } GetUserInfoReq::~GetUserInfoReq() { // @@protoc_insertion_point(destructor:antalk.data.GetUserInfoReq) SharedDtor(); } void GetUserInfoReq::SharedDtor() { uid_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void GetUserInfoReq::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* GetUserInfoReq::descriptor() { ::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const GetUserInfoReq& GetUserInfoReq::default_instance() { ::protobuf_data_2eproto::InitDefaultsGetUserInfoReq(); return *internal_default_instance(); } GetUserInfoReq* GetUserInfoReq::New(::google::protobuf::Arena* arena) const { GetUserInfoReq* n = new GetUserInfoReq; if (arena != NULL) { arena->Own(n); } return n; } void GetUserInfoReq::Clear() { // @@protoc_insertion_point(message_clear_start:antalk.data.GetUserInfoReq) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(!uid_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); (*uid_.UnsafeRawStringPointer())->clear(); } saas_id_ = 0u; _has_bits_.Clear(); _internal_metadata_.Clear(); } bool GetUserInfoReq::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:antalk.data.GetUserInfoReq) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional uint32 saas_id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { set_has_saas_id(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &saas_id_))); } else { goto handle_unusual; } break; } // optional string uid = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_uid())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->uid().data(), static_cast<int>(this->uid().length()), ::google::protobuf::internal::WireFormat::PARSE, "antalk.data.GetUserInfoReq.uid"); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:antalk.data.GetUserInfoReq) return true; failure: // @@protoc_insertion_point(parse_failure:antalk.data.GetUserInfoReq) return false; #undef DO_ } void GetUserInfoReq::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:antalk.data.GetUserInfoReq) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional uint32 saas_id = 1; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->saas_id(), output); } // optional string uid = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->uid().data(), static_cast<int>(this->uid().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "antalk.data.GetUserInfoReq.uid"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->uid(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:antalk.data.GetUserInfoReq) } ::google::protobuf::uint8* GetUserInfoReq::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:antalk.data.GetUserInfoReq) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional uint32 saas_id = 1; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->saas_id(), target); } // optional string uid = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->uid().data(), static_cast<int>(this->uid().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "antalk.data.GetUserInfoReq.uid"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->uid(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:antalk.data.GetUserInfoReq) return target; } size_t GetUserInfoReq::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:antalk.data.GetUserInfoReq) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (_has_bits_[0 / 32] & 3u) { // optional string uid = 2; if (has_uid()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->uid()); } // optional uint32 saas_id = 1; if (has_saas_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->saas_id()); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void GetUserInfoReq::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:antalk.data.GetUserInfoReq) GOOGLE_DCHECK_NE(&from, this); const GetUserInfoReq* source = ::google::protobuf::internal::DynamicCastToGenerated<const GetUserInfoReq>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.GetUserInfoReq) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.GetUserInfoReq) MergeFrom(*source); } } void GetUserInfoReq::MergeFrom(const GetUserInfoReq& from) { // @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.GetUserInfoReq) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { set_has_uid(); uid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.uid_); } if (cached_has_bits & 0x00000002u) { saas_id_ = from.saas_id_; } _has_bits_[0] |= cached_has_bits; } } void GetUserInfoReq::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:antalk.data.GetUserInfoReq) if (&from == this) return; Clear(); MergeFrom(from); } void GetUserInfoReq::CopyFrom(const GetUserInfoReq& from) { // @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.GetUserInfoReq) if (&from == this) return; Clear(); MergeFrom(from); } bool GetUserInfoReq::IsInitialized() const { return true; } void GetUserInfoReq::Swap(GetUserInfoReq* other) { if (other == this) return; InternalSwap(other); } void GetUserInfoReq::InternalSwap(GetUserInfoReq* other) { using std::swap; uid_.Swap(&other->uid_); swap(saas_id_, other->saas_id_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata GetUserInfoReq::GetMetadata() const { protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void GetUserInfoRes::InitAsDefaultInstance() { ::antalk::data::_GetUserInfoRes_default_instance_._instance.get_mutable()->user_info_ = const_cast< ::antalk::common::UserInfo*>( ::antalk::common::UserInfo::internal_default_instance()); } void GetUserInfoRes::clear_user_info() { if (user_info_ != NULL) user_info_->Clear(); clear_has_user_info(); } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int GetUserInfoRes::kUserInfoFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 GetUserInfoRes::GetUserInfoRes() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_data_2eproto::InitDefaultsGetUserInfoRes(); } SharedCtor(); // @@protoc_insertion_point(constructor:antalk.data.GetUserInfoRes) } GetUserInfoRes::GetUserInfoRes(const GetUserInfoRes& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_user_info()) { user_info_ = new ::antalk::common::UserInfo(*from.user_info_); } else { user_info_ = NULL; } // @@protoc_insertion_point(copy_constructor:antalk.data.GetUserInfoRes) } void GetUserInfoRes::SharedCtor() { _cached_size_ = 0; user_info_ = NULL; } GetUserInfoRes::~GetUserInfoRes() { // @@protoc_insertion_point(destructor:antalk.data.GetUserInfoRes) SharedDtor(); } void GetUserInfoRes::SharedDtor() { if (this != internal_default_instance()) delete user_info_; } void GetUserInfoRes::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* GetUserInfoRes::descriptor() { ::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const GetUserInfoRes& GetUserInfoRes::default_instance() { ::protobuf_data_2eproto::InitDefaultsGetUserInfoRes(); return *internal_default_instance(); } GetUserInfoRes* GetUserInfoRes::New(::google::protobuf::Arena* arena) const { GetUserInfoRes* n = new GetUserInfoRes; if (arena != NULL) { arena->Own(n); } return n; } void GetUserInfoRes::Clear() { // @@protoc_insertion_point(message_clear_start:antalk.data.GetUserInfoRes) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(user_info_ != NULL); user_info_->Clear(); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool GetUserInfoRes::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:antalk.data.GetUserInfoRes) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .antalk.common.UserInfo user_info = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_user_info())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:antalk.data.GetUserInfoRes) return true; failure: // @@protoc_insertion_point(parse_failure:antalk.data.GetUserInfoRes) return false; #undef DO_ } void GetUserInfoRes::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:antalk.data.GetUserInfoRes) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .antalk.common.UserInfo user_info = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *this->user_info_, output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:antalk.data.GetUserInfoRes) } ::google::protobuf::uint8* GetUserInfoRes::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:antalk.data.GetUserInfoRes) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .antalk.common.UserInfo user_info = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, *this->user_info_, deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:antalk.data.GetUserInfoRes) return target; } size_t GetUserInfoRes::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:antalk.data.GetUserInfoRes) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } // optional .antalk.common.UserInfo user_info = 1; if (has_user_info()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *this->user_info_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void GetUserInfoRes::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:antalk.data.GetUserInfoRes) GOOGLE_DCHECK_NE(&from, this); const GetUserInfoRes* source = ::google::protobuf::internal::DynamicCastToGenerated<const GetUserInfoRes>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.GetUserInfoRes) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.GetUserInfoRes) MergeFrom(*source); } } void GetUserInfoRes::MergeFrom(const GetUserInfoRes& from) { // @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.GetUserInfoRes) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.has_user_info()) { mutable_user_info()->::antalk::common::UserInfo::MergeFrom(from.user_info()); } } void GetUserInfoRes::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:antalk.data.GetUserInfoRes) if (&from == this) return; Clear(); MergeFrom(from); } void GetUserInfoRes::CopyFrom(const GetUserInfoRes& from) { // @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.GetUserInfoRes) if (&from == this) return; Clear(); MergeFrom(from); } bool GetUserInfoRes::IsInitialized() const { return true; } void GetUserInfoRes::Swap(GetUserInfoRes* other) { if (other == this) return; InternalSwap(other); } void GetUserInfoRes::InternalSwap(GetUserInfoRes* other) { using std::swap; swap(user_info_, other->user_info_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata GetUserInfoRes::GetMetadata() const { protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void SetUserStatusReq::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SetUserStatusReq::kUidFieldNumber; const int SetUserStatusReq::kDevTypeFieldNumber; const int SetUserStatusReq::kSessionFieldNumber; const int SetUserStatusReq::kStatusFieldNumber; const int SetUserStatusReq::kLoginInfoFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SetUserStatusReq::SetUserStatusReq() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_data_2eproto::InitDefaultsSetUserStatusReq(); } SharedCtor(); // @@protoc_insertion_point(constructor:antalk.data.SetUserStatusReq) } SetUserStatusReq::SetUserStatusReq(const SetUserStatusReq& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); uid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_uid()) { uid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.uid_); } session_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_session()) { session_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.session_); } login_info_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_login_info()) { login_info_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.login_info_); } ::memcpy(&dev_type_, &from.dev_type_, static_cast<size_t>(reinterpret_cast<char*>(&status_) - reinterpret_cast<char*>(&dev_type_)) + sizeof(status_)); // @@protoc_insertion_point(copy_constructor:antalk.data.SetUserStatusReq) } void SetUserStatusReq::SharedCtor() { _cached_size_ = 0; uid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); session_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); login_info_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&dev_type_, 0, static_cast<size_t>( reinterpret_cast<char*>(&status_) - reinterpret_cast<char*>(&dev_type_)) + sizeof(status_)); } SetUserStatusReq::~SetUserStatusReq() { // @@protoc_insertion_point(destructor:antalk.data.SetUserStatusReq) SharedDtor(); } void SetUserStatusReq::SharedDtor() { uid_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); session_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); login_info_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void SetUserStatusReq::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* SetUserStatusReq::descriptor() { ::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const SetUserStatusReq& SetUserStatusReq::default_instance() { ::protobuf_data_2eproto::InitDefaultsSetUserStatusReq(); return *internal_default_instance(); } SetUserStatusReq* SetUserStatusReq::New(::google::protobuf::Arena* arena) const { SetUserStatusReq* n = new SetUserStatusReq; if (arena != NULL) { arena->Own(n); } return n; } void SetUserStatusReq::Clear() { // @@protoc_insertion_point(message_clear_start:antalk.data.SetUserStatusReq) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 7u) { if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(!uid_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); (*uid_.UnsafeRawStringPointer())->clear(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(!session_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); (*session_.UnsafeRawStringPointer())->clear(); } if (cached_has_bits & 0x00000004u) { GOOGLE_DCHECK(!login_info_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); (*login_info_.UnsafeRawStringPointer())->clear(); } } if (cached_has_bits & 24u) { ::memset(&dev_type_, 0, static_cast<size_t>( reinterpret_cast<char*>(&status_) - reinterpret_cast<char*>(&dev_type_)) + sizeof(status_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool SetUserStatusReq::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:antalk.data.SetUserStatusReq) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string uid = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_uid())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->uid().data(), static_cast<int>(this->uid().length()), ::google::protobuf::internal::WireFormat::PARSE, "antalk.data.SetUserStatusReq.uid"); } else { goto handle_unusual; } break; } // optional int32 dev_type = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { set_has_dev_type(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &dev_type_))); } else { goto handle_unusual; } break; } // optional string session = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_session())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->session().data(), static_cast<int>(this->session().length()), ::google::protobuf::internal::WireFormat::PARSE, "antalk.data.SetUserStatusReq.session"); } else { goto handle_unusual; } break; } // optional int32 status = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { set_has_status(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &status_))); } else { goto handle_unusual; } break; } // optional string login_info = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_login_info())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->login_info().data(), static_cast<int>(this->login_info().length()), ::google::protobuf::internal::WireFormat::PARSE, "antalk.data.SetUserStatusReq.login_info"); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:antalk.data.SetUserStatusReq) return true; failure: // @@protoc_insertion_point(parse_failure:antalk.data.SetUserStatusReq) return false; #undef DO_ } void SetUserStatusReq::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:antalk.data.SetUserStatusReq) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string uid = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->uid().data(), static_cast<int>(this->uid().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "antalk.data.SetUserStatusReq.uid"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->uid(), output); } // optional int32 dev_type = 2; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->dev_type(), output); } // optional string session = 3; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->session().data(), static_cast<int>(this->session().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "antalk.data.SetUserStatusReq.session"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->session(), output); } // optional int32 status = 4; if (cached_has_bits & 0x00000010u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->status(), output); } // optional string login_info = 5; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->login_info().data(), static_cast<int>(this->login_info().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "antalk.data.SetUserStatusReq.login_info"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 5, this->login_info(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:antalk.data.SetUserStatusReq) } ::google::protobuf::uint8* SetUserStatusReq::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:antalk.data.SetUserStatusReq) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string uid = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->uid().data(), static_cast<int>(this->uid().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "antalk.data.SetUserStatusReq.uid"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->uid(), target); } // optional int32 dev_type = 2; if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->dev_type(), target); } // optional string session = 3; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->session().data(), static_cast<int>(this->session().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "antalk.data.SetUserStatusReq.session"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->session(), target); } // optional int32 status = 4; if (cached_has_bits & 0x00000010u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->status(), target); } // optional string login_info = 5; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->login_info().data(), static_cast<int>(this->login_info().length()), ::google::protobuf::internal::WireFormat::SERIALIZE, "antalk.data.SetUserStatusReq.login_info"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 5, this->login_info(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:antalk.data.SetUserStatusReq) return target; } size_t SetUserStatusReq::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:antalk.data.SetUserStatusReq) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (_has_bits_[0 / 32] & 31u) { // optional string uid = 1; if (has_uid()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->uid()); } // optional string session = 3; if (has_session()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->session()); } // optional string login_info = 5; if (has_login_info()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->login_info()); } // optional int32 dev_type = 2; if (has_dev_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->dev_type()); } // optional int32 status = 4; if (has_status()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->status()); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void SetUserStatusReq::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:antalk.data.SetUserStatusReq) GOOGLE_DCHECK_NE(&from, this); const SetUserStatusReq* source = ::google::protobuf::internal::DynamicCastToGenerated<const SetUserStatusReq>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.SetUserStatusReq) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.SetUserStatusReq) MergeFrom(*source); } } void SetUserStatusReq::MergeFrom(const SetUserStatusReq& from) { // @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.SetUserStatusReq) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 31u) { if (cached_has_bits & 0x00000001u) { set_has_uid(); uid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.uid_); } if (cached_has_bits & 0x00000002u) { set_has_session(); session_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.session_); } if (cached_has_bits & 0x00000004u) { set_has_login_info(); login_info_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.login_info_); } if (cached_has_bits & 0x00000008u) { dev_type_ = from.dev_type_; } if (cached_has_bits & 0x00000010u) { status_ = from.status_; } _has_bits_[0] |= cached_has_bits; } } void SetUserStatusReq::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:antalk.data.SetUserStatusReq) if (&from == this) return; Clear(); MergeFrom(from); } void SetUserStatusReq::CopyFrom(const SetUserStatusReq& from) { // @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.SetUserStatusReq) if (&from == this) return; Clear(); MergeFrom(from); } bool SetUserStatusReq::IsInitialized() const { return true; } void SetUserStatusReq::Swap(SetUserStatusReq* other) { if (other == this) return; InternalSwap(other); } void SetUserStatusReq::InternalSwap(SetUserStatusReq* other) { using std::swap; uid_.Swap(&other->uid_); session_.Swap(&other->session_); login_info_.Swap(&other->login_info_); swap(dev_type_, other->dev_type_); swap(status_, other->status_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SetUserStatusReq::GetMetadata() const { protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void SetUserStatusResp::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SetUserStatusResp::kResultFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SetUserStatusResp::SetUserStatusResp() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_data_2eproto::InitDefaultsSetUserStatusResp(); } SharedCtor(); // @@protoc_insertion_point(constructor:antalk.data.SetUserStatusResp) } SetUserStatusResp::SetUserStatusResp(const SetUserStatusResp& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); result_ = from.result_; // @@protoc_insertion_point(copy_constructor:antalk.data.SetUserStatusResp) } void SetUserStatusResp::SharedCtor() { _cached_size_ = 0; result_ = 0; } SetUserStatusResp::~SetUserStatusResp() { // @@protoc_insertion_point(destructor:antalk.data.SetUserStatusResp) SharedDtor(); } void SetUserStatusResp::SharedDtor() { } void SetUserStatusResp::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* SetUserStatusResp::descriptor() { ::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const SetUserStatusResp& SetUserStatusResp::default_instance() { ::protobuf_data_2eproto::InitDefaultsSetUserStatusResp(); return *internal_default_instance(); } SetUserStatusResp* SetUserStatusResp::New(::google::protobuf::Arena* arena) const { SetUserStatusResp* n = new SetUserStatusResp; if (arena != NULL) { arena->Own(n); } return n; } void SetUserStatusResp::Clear() { // @@protoc_insertion_point(message_clear_start:antalk.data.SetUserStatusResp) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; result_ = 0; _has_bits_.Clear(); _internal_metadata_.Clear(); } bool SetUserStatusResp::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:antalk.data.SetUserStatusResp) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .antalk.common.ResultType result = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::antalk::common::ResultType_IsValid(value)) { set_result(static_cast< ::antalk::common::ResultType >(value)); } else { mutable_unknown_fields()->AddVarint( 1, static_cast< ::google::protobuf::uint64>(value)); } } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:antalk.data.SetUserStatusResp) return true; failure: // @@protoc_insertion_point(parse_failure:antalk.data.SetUserStatusResp) return false; #undef DO_ } void SetUserStatusResp::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:antalk.data.SetUserStatusResp) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .antalk.common.ResultType result = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->result(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:antalk.data.SetUserStatusResp) } ::google::protobuf::uint8* SetUserStatusResp::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:antalk.data.SetUserStatusResp) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .antalk.common.ResultType result = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->result(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:antalk.data.SetUserStatusResp) return target; } size_t SetUserStatusResp::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:antalk.data.SetUserStatusResp) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } // optional .antalk.common.ResultType result = 1; if (has_result()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->result()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void SetUserStatusResp::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:antalk.data.SetUserStatusResp) GOOGLE_DCHECK_NE(&from, this); const SetUserStatusResp* source = ::google::protobuf::internal::DynamicCastToGenerated<const SetUserStatusResp>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.SetUserStatusResp) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.SetUserStatusResp) MergeFrom(*source); } } void SetUserStatusResp::MergeFrom(const SetUserStatusResp& from) { // @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.SetUserStatusResp) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.has_result()) { set_result(from.result()); } } void SetUserStatusResp::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:antalk.data.SetUserStatusResp) if (&from == this) return; Clear(); MergeFrom(from); } void SetUserStatusResp::CopyFrom(const SetUserStatusResp& from) { // @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.SetUserStatusResp) if (&from == this) return; Clear(); MergeFrom(from); } bool SetUserStatusResp::IsInitialized() const { return true; } void SetUserStatusResp::Swap(SetUserStatusResp* other) { if (other == this) return; InternalSwap(other); } void SetUserStatusResp::InternalSwap(SetUserStatusResp* other) { using std::swap; swap(result_, other->result_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SetUserStatusResp::GetMetadata() const { protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void SaveMsgReq::InitAsDefaultInstance() { ::antalk::data::_SaveMsgReq_default_instance_._instance.get_mutable()->msg_info_ = const_cast< ::antalk::common::MsgInfo*>( ::antalk::common::MsgInfo::internal_default_instance()); } void SaveMsgReq::clear_msg_info() { if (msg_info_ != NULL) msg_info_->Clear(); clear_has_msg_info(); } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SaveMsgReq::kMsgInfoFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SaveMsgReq::SaveMsgReq() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_data_2eproto::InitDefaultsSaveMsgReq(); } SharedCtor(); // @@protoc_insertion_point(constructor:antalk.data.SaveMsgReq) } SaveMsgReq::SaveMsgReq(const SaveMsgReq& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_msg_info()) { msg_info_ = new ::antalk::common::MsgInfo(*from.msg_info_); } else { msg_info_ = NULL; } // @@protoc_insertion_point(copy_constructor:antalk.data.SaveMsgReq) } void SaveMsgReq::SharedCtor() { _cached_size_ = 0; msg_info_ = NULL; } SaveMsgReq::~SaveMsgReq() { // @@protoc_insertion_point(destructor:antalk.data.SaveMsgReq) SharedDtor(); } void SaveMsgReq::SharedDtor() { if (this != internal_default_instance()) delete msg_info_; } void SaveMsgReq::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* SaveMsgReq::descriptor() { ::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const SaveMsgReq& SaveMsgReq::default_instance() { ::protobuf_data_2eproto::InitDefaultsSaveMsgReq(); return *internal_default_instance(); } SaveMsgReq* SaveMsgReq::New(::google::protobuf::Arena* arena) const { SaveMsgReq* n = new SaveMsgReq; if (arena != NULL) { arena->Own(n); } return n; } void SaveMsgReq::Clear() { // @@protoc_insertion_point(message_clear_start:antalk.data.SaveMsgReq) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(msg_info_ != NULL); msg_info_->Clear(); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool SaveMsgReq::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:antalk.data.SaveMsgReq) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .antalk.common.MsgInfo msg_info = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_msg_info())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:antalk.data.SaveMsgReq) return true; failure: // @@protoc_insertion_point(parse_failure:antalk.data.SaveMsgReq) return false; #undef DO_ } void SaveMsgReq::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:antalk.data.SaveMsgReq) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .antalk.common.MsgInfo msg_info = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *this->msg_info_, output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:antalk.data.SaveMsgReq) } ::google::protobuf::uint8* SaveMsgReq::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:antalk.data.SaveMsgReq) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .antalk.common.MsgInfo msg_info = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, *this->msg_info_, deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:antalk.data.SaveMsgReq) return target; } size_t SaveMsgReq::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:antalk.data.SaveMsgReq) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } // optional .antalk.common.MsgInfo msg_info = 1; if (has_msg_info()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *this->msg_info_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void SaveMsgReq::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:antalk.data.SaveMsgReq) GOOGLE_DCHECK_NE(&from, this); const SaveMsgReq* source = ::google::protobuf::internal::DynamicCastToGenerated<const SaveMsgReq>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.SaveMsgReq) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.SaveMsgReq) MergeFrom(*source); } } void SaveMsgReq::MergeFrom(const SaveMsgReq& from) { // @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.SaveMsgReq) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.has_msg_info()) { mutable_msg_info()->::antalk::common::MsgInfo::MergeFrom(from.msg_info()); } } void SaveMsgReq::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:antalk.data.SaveMsgReq) if (&from == this) return; Clear(); MergeFrom(from); } void SaveMsgReq::CopyFrom(const SaveMsgReq& from) { // @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.SaveMsgReq) if (&from == this) return; Clear(); MergeFrom(from); } bool SaveMsgReq::IsInitialized() const { return true; } void SaveMsgReq::Swap(SaveMsgReq* other) { if (other == this) return; InternalSwap(other); } void SaveMsgReq::InternalSwap(SaveMsgReq* other) { using std::swap; swap(msg_info_, other->msg_info_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SaveMsgReq::GetMetadata() const { protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void SaveMsgResp::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SaveMsgResp::kMsgIdFieldNumber; const int SaveMsgResp::kResultCodeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SaveMsgResp::SaveMsgResp() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { ::protobuf_data_2eproto::InitDefaultsSaveMsgResp(); } SharedCtor(); // @@protoc_insertion_point(constructor:antalk.data.SaveMsgResp) } SaveMsgResp::SaveMsgResp(const SaveMsgResp& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&msg_id_, &from.msg_id_, static_cast<size_t>(reinterpret_cast<char*>(&result_code_) - reinterpret_cast<char*>(&msg_id_)) + sizeof(result_code_)); // @@protoc_insertion_point(copy_constructor:antalk.data.SaveMsgResp) } void SaveMsgResp::SharedCtor() { _cached_size_ = 0; ::memset(&msg_id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&result_code_) - reinterpret_cast<char*>(&msg_id_)) + sizeof(result_code_)); } SaveMsgResp::~SaveMsgResp() { // @@protoc_insertion_point(destructor:antalk.data.SaveMsgResp) SharedDtor(); } void SaveMsgResp::SharedDtor() { } void SaveMsgResp::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* SaveMsgResp::descriptor() { ::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const SaveMsgResp& SaveMsgResp::default_instance() { ::protobuf_data_2eproto::InitDefaultsSaveMsgResp(); return *internal_default_instance(); } SaveMsgResp* SaveMsgResp::New(::google::protobuf::Arena* arena) const { SaveMsgResp* n = new SaveMsgResp; if (arena != NULL) { arena->Own(n); } return n; } void SaveMsgResp::Clear() { // @@protoc_insertion_point(message_clear_start:antalk.data.SaveMsgResp) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { ::memset(&msg_id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&result_code_) - reinterpret_cast<char*>(&msg_id_)) + sizeof(result_code_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool SaveMsgResp::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:antalk.data.SaveMsgResp) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional int64 msg_id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { set_has_msg_id(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &msg_id_))); } else { goto handle_unusual; } break; } // optional .antalk.common.ResultType result_code = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::antalk::common::ResultType_IsValid(value)) { set_result_code(static_cast< ::antalk::common::ResultType >(value)); } else { mutable_unknown_fields()->AddVarint( 2, static_cast< ::google::protobuf::uint64>(value)); } } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:antalk.data.SaveMsgResp) return true; failure: // @@protoc_insertion_point(parse_failure:antalk.data.SaveMsgResp) return false; #undef DO_ } void SaveMsgResp::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:antalk.data.SaveMsgResp) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int64 msg_id = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->msg_id(), output); } // optional .antalk.common.ResultType result_code = 2; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 2, this->result_code(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:antalk.data.SaveMsgResp) } ::google::protobuf::uint8* SaveMsgResp::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:antalk.data.SaveMsgResp) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int64 msg_id = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->msg_id(), target); } // optional .antalk.common.ResultType result_code = 2; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 2, this->result_code(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:antalk.data.SaveMsgResp) return target; } size_t SaveMsgResp::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:antalk.data.SaveMsgResp) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } if (_has_bits_[0 / 32] & 3u) { // optional int64 msg_id = 1; if (has_msg_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->msg_id()); } // optional .antalk.common.ResultType result_code = 2; if (has_result_code()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->result_code()); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void SaveMsgResp::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:antalk.data.SaveMsgResp) GOOGLE_DCHECK_NE(&from, this); const SaveMsgResp* source = ::google::protobuf::internal::DynamicCastToGenerated<const SaveMsgResp>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.SaveMsgResp) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.SaveMsgResp) MergeFrom(*source); } } void SaveMsgResp::MergeFrom(const SaveMsgResp& from) { // @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.SaveMsgResp) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { msg_id_ = from.msg_id_; } if (cached_has_bits & 0x00000002u) { result_code_ = from.result_code_; } _has_bits_[0] |= cached_has_bits; } } void SaveMsgResp::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:antalk.data.SaveMsgResp) if (&from == this) return; Clear(); MergeFrom(from); } void SaveMsgResp::CopyFrom(const SaveMsgResp& from) { // @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.SaveMsgResp) if (&from == this) return; Clear(); MergeFrom(from); } bool SaveMsgResp::IsInitialized() const { return true; } void SaveMsgResp::Swap(SaveMsgResp* other) { if (other == this) return; InternalSwap(other); } void SaveMsgResp::InternalSwap(SaveMsgResp* other) { using std::swap; swap(msg_id_, other->msg_id_); swap(result_code_, other->result_code_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SaveMsgResp::GetMetadata() const { protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== UserStatusService::~UserStatusService() {} const ::google::protobuf::ServiceDescriptor* UserStatusService::descriptor() { protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_data_2eproto::file_level_service_descriptors[0]; } const ::google::protobuf::ServiceDescriptor* UserStatusService::GetDescriptor() { return descriptor(); } void UserStatusService::GetUserInfo(::google::protobuf::RpcController* controller, const ::antalk::data::GetUserInfoReq*, ::antalk::data::GetUserInfoRes*, ::google::protobuf::Closure* done) { controller->SetFailed("Method GetUserInfo() not implemented."); done->Run(); } void UserStatusService::SetUserStatus(::google::protobuf::RpcController* controller, const ::antalk::data::SetUserStatusReq*, ::antalk::data::SetUserStatusResp*, ::google::protobuf::Closure* done) { controller->SetFailed("Method SetUserStatus() not implemented."); done->Run(); } void UserStatusService::CallMethod(const ::google::protobuf::MethodDescriptor* method, ::google::protobuf::RpcController* controller, const ::google::protobuf::Message* request, ::google::protobuf::Message* response, ::google::protobuf::Closure* done) { GOOGLE_DCHECK_EQ(method->service(), protobuf_data_2eproto::file_level_service_descriptors[0]); switch(method->index()) { case 0: GetUserInfo(controller, ::google::protobuf::down_cast<const ::antalk::data::GetUserInfoReq*>(request), ::google::protobuf::down_cast< ::antalk::data::GetUserInfoRes*>(response), done); break; case 1: SetUserStatus(controller, ::google::protobuf::down_cast<const ::antalk::data::SetUserStatusReq*>(request), ::google::protobuf::down_cast< ::antalk::data::SetUserStatusResp*>(response), done); break; default: GOOGLE_LOG(FATAL) << "Bad method index; this should never happen."; break; } } const ::google::protobuf::Message& UserStatusService::GetRequestPrototype( const ::google::protobuf::MethodDescriptor* method) const { GOOGLE_DCHECK_EQ(method->service(), descriptor()); switch(method->index()) { case 0: return ::antalk::data::GetUserInfoReq::default_instance(); case 1: return ::antalk::data::SetUserStatusReq::default_instance(); default: GOOGLE_LOG(FATAL) << "Bad method index; this should never happen."; return *::google::protobuf::MessageFactory::generated_factory() ->GetPrototype(method->input_type()); } } const ::google::protobuf::Message& UserStatusService::GetResponsePrototype( const ::google::protobuf::MethodDescriptor* method) const { GOOGLE_DCHECK_EQ(method->service(), descriptor()); switch(method->index()) { case 0: return ::antalk::data::GetUserInfoRes::default_instance(); case 1: return ::antalk::data::SetUserStatusResp::default_instance(); default: GOOGLE_LOG(FATAL) << "Bad method index; this should never happen."; return *::google::protobuf::MessageFactory::generated_factory() ->GetPrototype(method->output_type()); } } UserStatusService_Stub::UserStatusService_Stub(::google::protobuf::RpcChannel* channel) : channel_(channel), owns_channel_(false) {} UserStatusService_Stub::UserStatusService_Stub( ::google::protobuf::RpcChannel* channel, ::google::protobuf::Service::ChannelOwnership ownership) : channel_(channel), owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {} UserStatusService_Stub::~UserStatusService_Stub() { if (owns_channel_) delete channel_; } void UserStatusService_Stub::GetUserInfo(::google::protobuf::RpcController* controller, const ::antalk::data::GetUserInfoReq* request, ::antalk::data::GetUserInfoRes* response, ::google::protobuf::Closure* done) { channel_->CallMethod(descriptor()->method(0), controller, request, response, done); } void UserStatusService_Stub::SetUserStatus(::google::protobuf::RpcController* controller, const ::antalk::data::SetUserStatusReq* request, ::antalk::data::SetUserStatusResp* response, ::google::protobuf::Closure* done) { channel_->CallMethod(descriptor()->method(1), controller, request, response, done); } // =================================================================== MsgService::~MsgService() {} const ::google::protobuf::ServiceDescriptor* MsgService::descriptor() { protobuf_data_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_data_2eproto::file_level_service_descriptors[1]; } const ::google::protobuf::ServiceDescriptor* MsgService::GetDescriptor() { return descriptor(); } void MsgService::SaveMsg(::google::protobuf::RpcController* controller, const ::antalk::data::SaveMsgReq*, ::antalk::data::SaveMsgResp*, ::google::protobuf::Closure* done) { controller->SetFailed("Method SaveMsg() not implemented."); done->Run(); } void MsgService::CallMethod(const ::google::protobuf::MethodDescriptor* method, ::google::protobuf::RpcController* controller, const ::google::protobuf::Message* request, ::google::protobuf::Message* response, ::google::protobuf::Closure* done) { GOOGLE_DCHECK_EQ(method->service(), protobuf_data_2eproto::file_level_service_descriptors[1]); switch(method->index()) { case 0: SaveMsg(controller, ::google::protobuf::down_cast<const ::antalk::data::SaveMsgReq*>(request), ::google::protobuf::down_cast< ::antalk::data::SaveMsgResp*>(response), done); break; default: GOOGLE_LOG(FATAL) << "Bad method index; this should never happen."; break; } } const ::google::protobuf::Message& MsgService::GetRequestPrototype( const ::google::protobuf::MethodDescriptor* method) const { GOOGLE_DCHECK_EQ(method->service(), descriptor()); switch(method->index()) { case 0: return ::antalk::data::SaveMsgReq::default_instance(); default: GOOGLE_LOG(FATAL) << "Bad method index; this should never happen."; return *::google::protobuf::MessageFactory::generated_factory() ->GetPrototype(method->input_type()); } } const ::google::protobuf::Message& MsgService::GetResponsePrototype( const ::google::protobuf::MethodDescriptor* method) const { GOOGLE_DCHECK_EQ(method->service(), descriptor()); switch(method->index()) { case 0: return ::antalk::data::SaveMsgResp::default_instance(); default: GOOGLE_LOG(FATAL) << "Bad method index; this should never happen."; return *::google::protobuf::MessageFactory::generated_factory() ->GetPrototype(method->output_type()); } } MsgService_Stub::MsgService_Stub(::google::protobuf::RpcChannel* channel) : channel_(channel), owns_channel_(false) {} MsgService_Stub::MsgService_Stub( ::google::protobuf::RpcChannel* channel, ::google::protobuf::Service::ChannelOwnership ownership) : channel_(channel), owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {} MsgService_Stub::~MsgService_Stub() { if (owns_channel_) delete channel_; } void MsgService_Stub::SaveMsg(::google::protobuf::RpcController* controller, const ::antalk::data::SaveMsgReq* request, ::antalk::data::SaveMsgResp* response, ::google::protobuf::Closure* done) { channel_->CallMethod(descriptor()->method(0), controller, request, response, done); } // @@protoc_insertion_point(namespace_scope) } // namespace data } // namespace antalk // @@protoc_insertion_point(global_scope)
36.421606
131
0.708057
mloves0824
79ef41d0c35c576c2f0aad5e54868f50983bad0e
897
cpp
C++
src/Protein.cpp
pelafustan/aed_u1g0
69342941c1dc22f6641b39a80ce35e2fe9076fbd
[ "MIT" ]
null
null
null
src/Protein.cpp
pelafustan/aed_u1g0
69342941c1dc22f6641b39a80ce35e2fe9076fbd
[ "MIT" ]
null
null
null
src/Protein.cpp
pelafustan/aed_u1g0
69342941c1dc22f6641b39a80ce35e2fe9076fbd
[ "MIT" ]
null
null
null
#include "../include/Protein.h" // default constructor Protein::Protein() { // default attributes this->Name = ""; this->ID = ""; } // specific constructor Protein::Protein(std::string name, std::string id) { // user defined attributes this->Name = name; this->ID = id; } // overloaded specific constructor Protein::Protein(std::string name, std::string id, std::list<Chain> chains) { // user defined attributes this->Name = name; this->ID = id; this->Chains = chains; } // mutators void Protein::setName(std::string name) { this->Name = name; } void Protein::setID(std::string id) { this->ID = id; } void Protein::addChain(Chain chain) { this->Chains.push_back(chain); } // accessors std::string Protein::getName() { return this->Name; } std::string Protein::getID() { return this->ID; } std::list<Chain> Protein::getChains() { return this->Chains; }
26.382353
77
0.654404
pelafustan
79f4c2940f75053ea6f5a9d091814cfbf11c2d42
4,748
cpp
C++
Doom/src/Doom/Doom.cpp
Shturm0weak/OpenGL_Engine
6e6570f8dd9000724274942fff5a100f0998b780
[ "MIT" ]
126
2020-10-20T21:39:53.000Z
2022-01-25T14:43:44.000Z
Doom/src/Doom/Doom.cpp
Shturm0weak/2D_OpenGL_Engine
6e6570f8dd9000724274942fff5a100f0998b780
[ "MIT" ]
2
2021-01-07T17:29:19.000Z
2021-08-14T14:04:28.000Z
Doom/src/Doom/Doom.cpp
Shturm0weak/2D_OpenGL_Engine
6e6570f8dd9000724274942fff5a100f0998b780
[ "MIT" ]
16
2021-01-09T09:08:40.000Z
2022-01-25T14:43:46.000Z
#include "pch.h" #include "Core/World.h" #include "Core/Core.h" #include "Render/Renderer.h" #include "Text/Character.h" #include "Core/Timer.h" #include "Render/Batch.h" #include "Objects/Line.h" #include "Objects/ParticleSystem.h" #include "Audio/SoundManager.h" #include "Core/Editor.h" #include "Components/RectangleCollider2D.h" #include "Components/PointLight.h" #include "Lua/LuaState.h" #include "Core/SceneSerializer.h" #include "Input/Input.h" #include "Rays/Ray3D.h" #include "EntryPoint.h" #include "Objects/GridLayOut.h" #include "Objects/SkyBox.h" #include "Core/Logger.h" #include "Render/Mesh.h" using namespace Doom; DOOM_API std::mutex Mesh::s_Mtx; DOOM_API std::unordered_map<std::string, Mesh*> Mesh::s_Meshes; DOOM_API std::multimap<std::string, std::function<void(Mesh* m)>> Mesh::s_MeshQueue; DOOM_API const char** Mesh::s_NamesOfMeshes; DOOM_API std::tm* Logger::s_CurrentTime; DOOM_API std::string Logger::s_TimeString; DOOM_API std::vector<LuaState*> LuaState::s_LuaStates; DOOM_API std::vector<CubeCollider3D*> CubeCollider3D::s_Colliders; DOOM_API std::vector<SphereCollider*> SphereCollider::s_Spheres; DOOM_API std::vector <SpriteRenderer*> Renderer::s_Objects2d; DOOM_API std::vector <Renderer3D*> Renderer::s_Objects3d; DOOM_API std::vector <Renderer3D*> Renderer::s_Objects3dTransparent; DOOM_API std::vector <Renderer3D*> Renderer::s_OutLined3dObjects; DOOM_API std::vector<std::string> SkyBox::s_Faces; DOOM_API std::vector <char*> GameObject::s_FreeMemory; DOOM_API std::map <char*, uint64_t> GameObject::s_MemoryPool; DOOM_API std::vector <char*> Renderer3D::s_FreeMemory; DOOM_API std::map <char*, uint64_t> Renderer3D::s_MemoryPool; DOOM_API std::vector <char*> CubeCollider3D::s_FreeMemory; DOOM_API std::map <char*, uint64_t> CubeCollider3D::s_MemoryPool; DOOM_API std::vector <char*> RectangleCollider2D::s_FreeMemory; DOOM_API std::map <char*, uint64_t> RectangleCollider2D::s_MemoryPool; DOOM_API std::vector <char*> SpriteRenderer::s_FreeMemory; DOOM_API std::map <char*, uint64_t> SpriteRenderer::s_MemoryPool; DOOM_API std::vector <RectangleCollider2D*> RectangleCollider2D::s_Collision2d; DOOM_API bool Renderer::s_PolygonMode = false; DOOM_API Renderer::Stats Renderer::s_Stats; DOOM_API Renderer::Bloom Renderer::s_Bloom; DOOM_API Renderer::ShadowMap Renderer::s_ShadowMap; DOOM_API std::vector<std::string> Editor::s_TexturesPath; DOOM_API std::vector<Texture*> Editor::s_Texture; DOOM_API std::vector<Texture*> Editor::s_TextureVecTemp; DOOM_API std::vector<TexParameteri> Texture::s_TexParameters; DOOM_API std::vector<Texture*> Texture::s_LoadedTextures; DOOM_API std::multimap<std::string, std::function<void(Texture* t)>> Texture::s_WaitingForTextures; DOOM_API std::mutex Texture::s_LockTextureLoadingMtx; DOOM_API Texture* Texture::s_WhiteTexture; DOOM_API std::unordered_map<std::string, Texture*> Texture::s_Textures; DOOM_API double Timer::s_OutTime = 0; DOOM_API ThreadPool* ThreadPool::s_Instance = nullptr; DOOM_API bool ThreadPool::m_IsInitialized; DOOM_API std::unordered_map<int, int> Input::s_Keys; DOOM_API float DeltaTime::s_Time; DOOM_API float DeltaTime::s_Lasttime = (float)glfwGetTime(); DOOM_API float DeltaTime::s_Deltatime = 1.0 / 1e8; DOOM_API std::mutex DeltaTime::s_Mtx; DOOM_API bool RectangleCollider2D::s_IsVisible = false; DOOM_API vec4 COLORS::Red(1, 0, 0, 1); DOOM_API vec4 COLORS::Yellow(1, 1, 0, 1); DOOM_API vec4 COLORS::Blue(0, 0, 1, 1); DOOM_API vec4 COLORS::Green(0, 1, 0, 1); DOOM_API vec4 COLORS::Brown(0.5, 0.3, 0.1, 1); DOOM_API vec4 COLORS::White(1, 1, 1, 1); DOOM_API vec4 COLORS::Orange(1, 0.31, 0, 1); DOOM_API vec4 COLORS::Gray(0.86, 0.86, 0.86, 1); DOOM_API vec4 COLORS::Silver(0.75, 0.75, 0.75, 1); DOOM_API vec4 COLORS::DarkGray(0.4, 0.4, 0.4, 1); DOOM_API std::vector<Line*> Line::s_Lines; DOOM_API float Line::s_Width = 1.0f; DOOM_API std::unordered_map<std::string, TextureAtlas*> TextureAtlas::s_TextureAtlases; DOOM_API const char** TextureAtlas::s_NamesOfTextureAtlases; DOOM_API std::unordered_map<std::string, Shader*> Shader::s_Shaders; DOOM_API std::vector<Particle*> Particle::s_Particles; DOOM_API const char** Shader::s_NamesOfShaders; DOOM_API std::vector<PointLight*> PointLight::s_PointLights; DOOM_API std::vector<DirectionalLight*> DirectionalLight::s_DirLights; DOOM_API std::vector<SpotLight*> SpotLight::s_SpotLights; DOOM_API unsigned int SpriteRenderer::s_Indices2D[6] = { 0,1,2,3,2,0 }; DOOM_API float RectangleCollider2D::m_Vertices[8] = {-0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f }; DOOM_API std::vector<std::string> Ray3D::m_IgnoreMask; DOOM_API std::vector<Line*> GridLayOut::s_GridLines; DOOM_API std::string SceneSerializer::s_CurrentSceneFilePath = "src/Scenes/scene.yaml";
38.290323
108
0.771693
Shturm0weak
79fa92b27f3137bfbed6662649626a55c9f6671a
9,104
cpp
C++
Mercury3/src/renderer/OpenVRRenderTarget.cpp
axlecrusher/hgengine3
7eed878015e47a3275e2dae53cac00e93b74dc19
[ "MIT" ]
4
2018-05-27T18:56:59.000Z
2020-08-02T21:41:30.000Z
Mercury3/src/renderer/OpenVRRenderTarget.cpp
axlecrusher/hgengine3
7eed878015e47a3275e2dae53cac00e93b74dc19
[ "MIT" ]
null
null
null
Mercury3/src/renderer/OpenVRRenderTarget.cpp
axlecrusher/hgengine3
7eed878015e47a3275e2dae53cac00e93b74dc19
[ "MIT" ]
2
2019-05-16T05:23:12.000Z
2020-04-17T10:16:04.000Z
#include <OpenVRRenderTarget.h> #include <HgUtils.h> #include <HgCamera.h> #include <MercuryWindow.h> #include <RenderBackend.h> #include <Win32Window.h> #include <OGLFramebuffer.h> #include <EventSystem.h> #include <Logging.h> OpenVRRenderTarget::OpenVRRenderTarget(OpenVrProxy* openvr) :m_openvr(openvr), m_initalized(false), m_timerInited(false) { m_HMDPose = vectorial::mat4f::identity(); m_projectionLeftEye = vectorial::mat4f::identity(); m_projectionRightEye = vectorial::mat4f::identity(); //m_leftEyePos = vectorial::mat4f::identity(); //m_rightEyePos = vectorial::mat4f::identity(); memset(m_deviceClass, 0, sizeof(m_deviceClass)); } bool OpenVRRenderTarget::Init() { // if (!m_openvr->Init()) return false; auto strDriver = GetTrackedDeviceString(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_TrackingSystemName_String); auto strDisplay = GetTrackedDeviceString(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_SerialNumber_String); ENGINE::StartWindowSystem(MercuryWindow::Dimensions(1280, 720)); auto window = MercuryWindow::GetCurrentWindow(); int width = window->CurrentWidth(); int height = window->CurrentHeight(); float projection[16]; m_windowViewport.width = width; m_windowViewport.height = height; double renderWidth = width; double renderHeight = height; double aspect = renderWidth / renderHeight; Perspective2(60, aspect, 0.03f, 100.0f, projection); m_projection.load(projection); m_openvr->InitCompositor(); initEyeFramebuffers(); m_projectionLeftEye = getHMDProjectionEye(vr::Eye_Left); m_projectionRightEye = getHMDProjectionEye(vr::Eye_Right); //m_leftEyePos = getHMDEyeTransform(vr::Eye_Left); //m_rightEyePos = getHMDEyeTransform(vr::Eye_Right); m_timerInited = false; m_initalized = true; return true; } void OpenVRRenderTarget::initEyeFramebuffers() { auto hmd = m_openvr->getDevice(); if (hmd == nullptr) return; uint32_t width, height; hmd->GetRecommendedRenderTargetSize(&width, &height); m_framebufferViewport.width = width; m_framebufferViewport.height = height; m_leftEye = RENDERER()->CreateFrameBuffer(); m_leftEye->Init(width, height); m_rightEye = RENDERER()->CreateFrameBuffer(); m_rightEye->Init(width, height); } void OpenVRRenderTarget::updateHMD() { auto hmd = m_openvr->getDevice(); if (hmd == nullptr) return; vr::VRCompositor()->WaitGetPoses(m_rTrackedDevicePose, vr::k_unMaxTrackedDeviceCount, NULL, 0); if (m_timerInited == false) { m_timerInited = true; m_timer.start(); m_timeSinceLastPose = m_timeOfPose.msec(0); } else { const auto time = m_timer.getElasped(); m_timeSinceLastPose = time - m_timeOfPose; m_timeOfPose = time; } for (int nDevice = 1; nDevice < vr::k_unMaxTrackedDeviceCount; ++nDevice) { if (m_rTrackedDevicePose[nDevice].bPoseIsValid) { const auto pose = ConvertToMat4f(m_rTrackedDevicePose[nDevice].mDeviceToAbsoluteTracking); if (m_deviceClass[nDevice] == vr::ETrackedDeviceClass::TrackedDeviceClass_Invalid) { auto type = hmd->GetTrackedDeviceClass(nDevice); m_deviceClass[nDevice] = type; } if (m_deviceClass[nDevice] == vr::ETrackedDeviceClass::TrackedDeviceClass_Controller) { Events::VrControllerPoseUpdated poseUpdated; ConstructPositionOrientationFromVrDevice(m_rTrackedDevicePose[nDevice].mDeviceToAbsoluteTracking, poseUpdated.position, poseUpdated.orientation); poseUpdated.deviceIndex = nDevice; EventSystem::PublishEvent(poseUpdated); } } } if (m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].bPoseIsValid) { m_HMDPose = ConvertToMat4f(m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking); m_hmdCamera = ConstructCameraFromVrDevice(m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking); Events::HMDPoseUpdated poseUpdated; poseUpdated.position = m_hmdCamera.getWorldSpacePosition(); poseUpdated.orientation = m_hmdCamera.getWorldSpaceOrientation(); EventSystem::PublishEvent(poseUpdated); } } HgMath::mat4f OpenVRRenderTarget::getWindowProjectionMatrix() { HgMath::mat4f projectionMatrix; float projection[16]; const double width = m_windowViewport.width; const double height = m_windowViewport.height; const double aspect = width / height; Perspective2(60, aspect, 0.1f, 100.0f, projection); projectionMatrix.load(projection); return projectionMatrix; } //const RenderParamsList& l //void OpenVRRenderTarget::Render(HgCamera* camera, RenderQueue* queue, const HgMath::mat4f& projection) void OpenVRRenderTarget::Render(const RenderParamsList& l) { if (!m_initalized) return; RENDERER()->Clear(); RENDERER()->BeginFrame(); ViewportRenderTarget vprt(&m_windowViewport); for (const RenderParams& i : l) { const auto hdmCamMatrix = i.camera->toViewMatrix(); const auto projection = i.projection->getProjectionMatrix(vprt); Renderer::Render(m_windowViewport, hdmCamMatrix, projection, i.queue); } auto left = dynamic_cast<OGLFramebuffer*>(m_leftEye.get()); auto right = dynamic_cast<OGLFramebuffer*>(m_rightEye.get()); { left->Enable(); RENDERER()->Clear(); RENDERER()->BeginFrame(); const auto eyeTtransform = getHMDEyeTransform(vr::Eye_Left); VrEyeRenderTarget rt(this, vr::EVREye::Eye_Left); for (const RenderParams& i : l) { const auto projection = i.projection->getProjectionMatrix(rt); RenderToEye(left, eyeTtransform, projection, i); } left->Disable(); left->Copy(); } { right->Enable(); RENDERER()->Clear(); RENDERER()->BeginFrame(); const auto eyeTtransform = getHMDEyeTransform(vr::Eye_Right); VrEyeRenderTarget rt(this, vr::EVREye::Eye_Right); for (const RenderParams& i : l) { const auto projection = i.projection->getProjectionMatrix(rt); RenderToEye(left, eyeTtransform, projection, i); } right->Disable(); right->Copy(); } ////updateHMD(); //auto right = dynamic_cast<OGLFramebuffer*>(m_rightEye.get()); ////auto camMat = camera->toViewMatrix(); //replace with head matrix //const auto hdmCamMatrix = m_hmdCamera.toViewMatrix(); //const auto leftEyeMat = m_leftEyePos * hdmCamMatrix; //const auto rightEyeMat = m_rightEyePos * hdmCamMatrix; //const auto leftProjection = m_projectionLeftEye * projection; //const auto rightProjection = m_projectionRightEye * projection; ////render to window first //Renderer::Render(m_windowViewport, hdmCamMatrix, projection, queue); //m_leftEye->Enable(); //RENDERER()->Clear(); //RENDERER()->BeginFrame(); //Renderer::Render(m_framebufferViewport, leftEyeMat, leftProjection, queue); //eye 1 //m_leftEye->Disable(); //left->Copy(); //m_rightEye->Enable(); //RENDERER()->Clear(); //RENDERER()->BeginFrame(); //Renderer::Render(m_framebufferViewport, rightEyeMat, rightProjection, queue); //eye 2 //m_rightEye->Disable(); //right->Copy(); //auto left = dynamic_cast<OGLFramebuffer*>(m_leftEye.get()); //auto right = dynamic_cast<OGLFramebuffer*>(m_rightEye.get()); vr::Texture_t leftEyeTexture = { (void*)(uintptr_t)left->getResolveTextureID(), vr::TextureType_OpenGL, vr::ColorSpace_Gamma }; auto e1 = vr::VRCompositor()->Submit(vr::Eye_Left, &leftEyeTexture); if (e1 != vr::VRInitError_None) { LOG_ERROR("Failed to submit left eye: %d", e1); } vr::Texture_t rightEyeTexture = { (void*)(uintptr_t)right->getResolveTextureID(), vr::TextureType_OpenGL, vr::ColorSpace_Gamma }; auto e2 = vr::VRCompositor()->Submit(vr::Eye_Right, &rightEyeTexture); if (e2 != vr::VRInitError_None) { LOG_ERROR("Failed to submit right eye: %d", e2); } } void OpenVRRenderTarget::RenderToEye(IFramebuffer* eyeBuffer, const HgMath::mat4f& eyePosTransform, const HgMath::mat4f& eyeProjection, const RenderParams& p) { const auto hdmCamMatrix = p.camera->toViewMatrix(); const auto eyeMatrix = eyePosTransform * hdmCamMatrix; //const auto projection = eyeProjection * (*p.projection); //frameBuffer->Enable(); //RENDERER()->Clear(); //RENDERER()->BeginFrame(); Renderer::Render(m_framebufferViewport, eyeMatrix, eyeProjection, p.queue); //frameBuffer->Disable(); //frameBuffer->Copy(); } void OpenVRRenderTarget::Finish() { } HgMath::mat4f OpenVRRenderTarget::getOrthoMatrix() const { //return vectorial::transpose(HgMath::mat4f::translation(vectorial::vec3f(0, 0, 1))); return HgMath::mat4f::translation(vectorial::vec3f(0, 0, 1)); // return vectorial::mat4f::identity(); } //returns a projection matrix for the specified eye HgMath::mat4f OpenVRRenderTarget::getHMDProjectionEye(vr::EVREye eye) const { auto hmd = m_openvr->getDevice(); if (!hmd) return HgMath::mat4f(); const vr::HmdMatrix44_t mat = hmd->GetProjectionMatrix(eye, 0.1, 100); const auto r = vectorial::transpose(ConvertToMat4f(mat)); return r; } HgMath::mat4f OpenVRRenderTarget::getHMDEyeTransform(vr::EVREye eye) { auto hmd = m_openvr->getDevice(); if (!hmd) return HgMath::mat4f(); vr::HmdMatrix34_t mat = hmd->GetEyeToHeadTransform(eye); //unsure why this is messed up mat.m[0][3] *= -1.0; return vectorial::transpose(ConvertToMat4f(mat)); } REGISTER_EVENT_TYPE(Events::HMDPoseUpdated) REGISTER_EVENT_TYPE(Events::VrControllerPoseUpdated)
29.462783
149
0.745826
axlecrusher
79ff22d850d7e3df640a66fcaa1eb9c2a8b5e3e3
3,352
cpp
C++
src/LuminoEngine/src/Graphics/RHIs/RHIResource.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
113
2020-03-05T01:27:59.000Z
2022-03-28T13:20:51.000Z
src/LuminoEngine/src/Graphics/RHIs/RHIResource.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
13
2020-03-23T20:36:44.000Z
2022-02-28T11:07:32.000Z
src/LuminoEngine/src/Graphics/RHIs/RHIResource.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
12
2020-12-21T12:03:59.000Z
2021-12-15T02:07:49.000Z
 #include "Internal.hpp" #include "GraphicsDeviceContext.hpp" #include "RHIProfiler.hpp" #include "RHIResource.hpp" namespace ln { namespace detail { //============================================================================= // RHIResource RHIResource::RHIResource() : m_type(RHIResourceType::Unknown) , m_usage(GraphicsResourceUsage::Static) , m_memorySize(0) , m_extentSize{0, 0} , m_textureFormat(TextureFormat::Unknown) , m_mipmap(false) , m_msaa(false) { LN_LOG_VERBOSE << "RHIResource [0x" << this << "] constructed."; } RHIResource::~RHIResource() { if (IGraphicsDevice* d = device()) { switch (m_type) { case RHIResourceType::VertexBuffer: d->profiler()->removeVertexBuffer(this); break; case RHIResourceType::IndexBuffer: d->profiler()->removeIndexBuffer(this); break; case RHIResourceType::UniformBuffer: d->profiler()->removeUniformBuffer(this); break; case RHIResourceType::Texture2D: d->profiler()->removeTexture2D(this); break; case RHIResourceType::RenderTarget: d->renderPassCache()->invalidate(static_cast<RHIResource*>(this)); d->profiler()->removeRenderTarget(this); break; default: break; } } } bool RHIResource::initAsVertexBuffer(GraphicsResourceUsage usage, uint64_t memorySize) { m_type = RHIResourceType::VertexBuffer; m_usage = usage; m_memorySize = memorySize; return true; } bool RHIResource::initAsIndexBuffer(GraphicsResourceUsage usage, IndexBufferFormat format, uint32_t indexCount) { m_type = RHIResourceType::IndexBuffer; m_usage = usage; int stride = 0; if (format == IndexBufferFormat::UInt16) { stride = 2; } else if (format == IndexBufferFormat::UInt32) { stride = 4; } else { LN_UNREACHABLE(); return false; } m_memorySize = stride * indexCount; return true; } bool RHIResource::initAsUniformBuffer(GraphicsResourceUsage usage, uint64_t memorySize) { // 今のところ UniformBuffer は Dynamic (複数 DrawCall で共有しない) 前提 // TODO: OpenGL の Streaming みたいにもうひとつ用意して区別したほうがいいかも if (LN_REQUIRE(usage == GraphicsResourceUsage::Dynamic)) return false; m_type = RHIResourceType::UniformBuffer; m_usage = usage; m_memorySize = memorySize; return true; } bool RHIResource::initAsTexture2D(GraphicsResourceUsage usage, uint32_t width, uint32_t height, TextureFormat format, bool mipmap) { //if (LN_REQUIRE(format == TextureFormat::Unknown)) return false; m_type = RHIResourceType::Texture2D; m_usage = usage; m_extentSize.width = width; m_extentSize.height = height; m_memorySize = width * height * GraphicsHelper::getPixelSize(format); m_textureFormat = format; m_mipmap = mipmap; return true; } bool RHIResource::initAsRenderTarget(uint32_t width, uint32_t height, TextureFormat format, bool mipmap, bool msaa) { //if (LN_REQUIRE(format == TextureFormat::Unknown)) return false; m_type = RHIResourceType::RenderTarget; m_usage = GraphicsResourceUsage::Static; m_extentSize.width = width; m_extentSize.height = height; m_memorySize = width * height * GraphicsHelper::getPixelSize(format); m_textureFormat = format; m_mipmap = mipmap; m_msaa = msaa; return true; } void* RHIResource::map() { LN_UNREACHABLE(); return nullptr; } void RHIResource::unmap() { LN_UNREACHABLE(); } RHIRef<RHIBitmap> RHIResource::readData() { LN_UNREACHABLE(); return nullptr; } } // namespace detail } // namespace ln
24.115108
130
0.724642
infinnie
0301d55e286597f3520052d182d8971d0afa307d
871
cpp
C++
standalone/main.cpp
sirofen/read-memory-dll
035b008cdb6ffbf2d00f30234f9ef976c04eee1e
[ "MIT" ]
null
null
null
standalone/main.cpp
sirofen/read-memory-dll
035b008cdb6ffbf2d00f30234f9ef976c04eee1e
[ "MIT" ]
null
null
null
standalone/main.cpp
sirofen/read-memory-dll
035b008cdb6ffbf2d00f30234f9ef976c04eee1e
[ "MIT" ]
null
null
null
// spdlog #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_color_sinks.h> // module #include <module/base_listener.hpp> #include <module/internal/kbd_remap_pointer_dep.hpp> #include <module/module_run.hpp> // C++ STL #include <iostream> class listener : public module::base_listener { public: void value_accessible_string(const std::string& _val) override { SPDLOG_INFO("value_accessible"); } void value_changed_string(const std::string& _val) override { SPDLOG_INFO("value_changed"); } }; int main() { /* spdlog setup */ spdlog::set_level(spdlog::level::trace); uintptr_t addr = 0x0; module::internal::module_run _module; _module.add_listener(std::make_shared<listener>()); _module.set_pointer(addr); _module.set_address(addr); _module.run(); }
24.194444
68
0.711825
sirofen
030760168ca9cfa92c8fa38ddbdbeadc8472a4dd
32,100
cpp
C++
kernel/thor/generic/address-space.cpp
64/managarm
8250ae9110703e5db796011078d8d856b8119f3c
[ "MIT" ]
1
2021-02-03T09:21:08.000Z
2021-02-03T09:21:08.000Z
kernel/thor/generic/address-space.cpp
MichaelTrikergiotis/managarm
7966d1ca02bf5295a51c56dbb5496c4ad4de9730
[ "MIT" ]
null
null
null
kernel/thor/generic/address-space.cpp
MichaelTrikergiotis/managarm
7966d1ca02bf5295a51c56dbb5496c4ad4de9730
[ "MIT" ]
null
null
null
#include <type_traits> #include <thor-internal/coroutine.hpp> #include <thor-internal/physical.hpp> #include <thor-internal/fiber.hpp> #include <frg/container_of.hpp> #include <thor-internal/types.hpp> namespace thor { extern size_t kernelMemoryUsage; namespace { constexpr bool logCleanup = false; constexpr bool logUsage = false; void logRss(VirtualSpace *space) { if(!logUsage) return; auto rss = space->rss(); if(!rss) return; auto b = 63 -__builtin_clz(rss); if(b < 1) return; if(rss & ((1 << (b - 1)) - 1)) return; infoLogger() << "thor: RSS of " << space << " increases above " << (rss / 1024) << " KiB" << frg::endlog; infoLogger() << "thor: Physical usage: " << (physicalAllocator->numUsedPages() * 4) << " KiB, kernel usage: " << (kernelMemoryUsage / 1024) << " KiB" << frg::endlog; } } MemorySlice::MemorySlice(smarter::shared_ptr<MemoryView> view, ptrdiff_t view_offset, size_t view_size) : _view{std::move(view)}, _viewOffset{view_offset}, _viewSize{view_size} { assert(!(_viewOffset & (kPageSize - 1))); assert(!(_viewSize & (kPageSize - 1))); } // -------------------------------------------------------- // HoleAggregator // -------------------------------------------------------- bool HoleAggregator::aggregate(Hole *hole) { size_t size = hole->length(); if(HoleTree::get_left(hole) && HoleTree::get_left(hole)->largestHole > size) size = HoleTree::get_left(hole)->largestHole; if(HoleTree::get_right(hole) && HoleTree::get_right(hole)->largestHole > size) size = HoleTree::get_right(hole)->largestHole; if(hole->largestHole == size) return false; hole->largestHole = size; return true; } bool HoleAggregator::check_invariant(HoleTree &tree, Hole *hole) { auto pred = tree.predecessor(hole); auto succ = tree.successor(hole); // Check largest hole invariant. size_t size = hole->length(); if(tree.get_left(hole) && tree.get_left(hole)->largestHole > size) size = tree.get_left(hole)->largestHole; if(tree.get_right(hole) && tree.get_right(hole)->largestHole > size) size = tree.get_right(hole)->largestHole; if(hole->largestHole != size) { infoLogger() << "largestHole violation: " << "Expected " << size << ", got " << hole->largestHole << "." << frg::endlog; return false; } // Check non-overlapping memory areas invariant. if(pred && hole->address() < pred->address() + pred->length()) { infoLogger() << "Non-overlapping (left) violation" << frg::endlog; return false; } if(succ && hole->address() + hole->length() > succ->address()) { infoLogger() << "Non-overlapping (right) violation" << frg::endlog; return false; } return true; } // -------------------------------------------------------- // Mapping // -------------------------------------------------------- Mapping::Mapping(size_t length, MappingFlags flags, smarter::shared_ptr<MemorySlice> slice_, uintptr_t viewOffset) : length{length}, flags{flags}, slice{std::move(slice_)}, viewOffset{viewOffset} { assert(viewOffset >= slice->offset()); assert(viewOffset + length <= slice->offset() + slice->length()); view = slice->getView(); } Mapping::~Mapping() { assert(state == MappingState::retired); //infoLogger() << "\e[31mthor: Mapping is destructed\e[39m" << frg::endlog; } void Mapping::tie(smarter::shared_ptr<VirtualSpace> newOwner, VirtualAddr address) { assert(!owner); assert(newOwner); owner = std::move(newOwner); this->address = address; } void Mapping::protect(MappingFlags protectFlags) { std::underlying_type_t<MappingFlags> newFlags = flags; newFlags &= ~(MappingFlags::protRead | MappingFlags::protWrite | MappingFlags::protExecute); newFlags |= protectFlags; flags = static_cast<MappingFlags>(newFlags); } void Mapping::populateVirtualRange(uintptr_t offset, size_t size, smarter::shared_ptr<WorkQueue> wq, PopulateVirtualRangeNode *node) { async::detach_with_allocator(*kernelAlloc, [] (Mapping *self, uintptr_t offset, size_t size, smarter::shared_ptr<WorkQueue> wq, PopulateVirtualRangeNode *node) -> coroutine<void> { size_t progress = 0; while(progress < size) { auto outcome = co_await self->touchVirtualPage(offset + progress, wq); if(!outcome) { node->result = outcome.error(); node->resume(); co_return; } progress += outcome.value().range.get<1>(); } node->result = frg::success; node->resume(); }(this, offset, size, std::move(wq), node)); } uint32_t Mapping::compilePageFlags() { uint32_t pageFlags = 0; // TODO: Allow inaccessible mappings. assert(flags & MappingFlags::protRead); if(flags & MappingFlags::protWrite) pageFlags |= page_access::write; if(flags & MappingFlags::protExecute) pageFlags |= page_access::execute; return pageFlags; } void Mapping::lockVirtualRange(uintptr_t offset, size_t size, smarter::shared_ptr<WorkQueue> wq, LockVirtualRangeNode *node) { // This can be removed if we change the return type of asyncLockRange to frg::expected. auto transformError = [node] (Error e) { if(e == Error::success) { node->result = {}; }else{ node->result = e; } node->resume(); }; async::detach_with_allocator(*kernelAlloc, async::transform(view->asyncLockRange(viewOffset + offset, size, std::move(wq)), transformError)); } void Mapping::unlockVirtualRange(uintptr_t offset, size_t size) { view->unlockRange(viewOffset + offset, size); } frg::tuple<PhysicalAddr, CachingMode> Mapping::resolveRange(ptrdiff_t offset) { assert(state == MappingState::active); // TODO: This function should be rewritten. assert((size_t)offset + kPageSize <= length); auto bundle_range = view->peekRange(viewOffset + offset); return frg::tuple<PhysicalAddr, CachingMode>{bundle_range.get<0>(), bundle_range.get<1>()}; } void Mapping::touchVirtualPage(uintptr_t offset, smarter::shared_ptr<WorkQueue> wq, TouchVirtualPageNode *node) { assert(state == MappingState::active); async::detach_with_allocator(*kernelAlloc, [] (Mapping *self, uintptr_t offset, smarter::shared_ptr<WorkQueue> wq, TouchVirtualPageNode *node) -> coroutine<void> { FetchFlags fetchFlags = 0; if(self->flags & MappingFlags::dontRequireBacking) fetchFlags |= FetchNode::disallowBacking; if(auto e = co_await self->view->asyncLockRange( (self->viewOffset + offset) & ~(kPageSize - 1), kPageSize, wq); e != Error::success) assert(!"asyncLockRange() failed"); auto [error, range, rangeFlags] = co_await self->view->fetchRange( self->viewOffset + offset, wq); // TODO: Update RSS, handle dirty pages, etc. auto pageOffset = self->address + offset; self->owner->_ops->unmapSingle4k(pageOffset & ~(kPageSize - 1)); self->owner->_ops->mapSingle4k(pageOffset & ~(kPageSize - 1), range.get<0>() & ~(kPageSize - 1), self->compilePageFlags(), range.get<2>()); self->owner->_residuentSize += kPageSize; logRss(self->owner.get()); self->view->unlockRange((self->viewOffset + offset) & ~(kPageSize - 1), kPageSize); node->result = TouchVirtualResult{range, false}; node->resume(); }(this, offset, std::move(wq), node)); } coroutine<void> Mapping::runEvictionLoop() { while(true) { auto eviction = co_await view->pollEviction(&observer, cancelEviction); if(!eviction) break; if(eviction.offset() + eviction.size() <= viewOffset || eviction.offset() >= viewOffset + length) { eviction.done(); continue; } // Begin and end offsets of the region that we need to unmap. auto shootBegin = frg::max(eviction.offset(), viewOffset); auto shootEnd = frg::min(eviction.offset() + eviction.size(), viewOffset + length); // Offset from the beginning of the mapping. auto shootOffset = shootBegin - viewOffset; auto shootSize = shootEnd - shootBegin; assert(shootSize); assert(!(shootOffset & (kPageSize - 1))); assert(!(shootSize & (kPageSize - 1))); // Wait until we are allowed to evict existing pages. // TODO: invent a more specialized synchronization mechanism for this. { auto irq_lock = frg::guard(&irqMutex()); auto lock = frg::guard(&evictMutex); } // TODO: Perform proper locking here! // Unmap the memory range. for(size_t pg = 0; pg < shootSize; pg += kPageSize) { auto status = owner->_ops->unmapSingle4k(address + shootOffset + pg); if(!(status & page_status::present)) continue; if(status & page_status::dirty) view->markDirty(viewOffset + shootOffset + pg, kPageSize); owner->_residuentSize -= kPageSize; } co_await owner->_ops->shootdown(address + shootOffset, shootSize); eviction.done(); } evictionDoneEvent.raise(); } // -------------------------------------------------------- // CowMapping // -------------------------------------------------------- CowChain::CowChain(smarter::shared_ptr<CowChain> chain) : _superChain{std::move(chain)}, _pages{*kernelAlloc} { } CowChain::~CowChain() { if(logCleanup) infoLogger() << "thor: Releasing CowChain" << frg::endlog; for(auto it = _pages.begin(); it != _pages.end(); ++it) { auto physical = it->load(std::memory_order_relaxed); assert(physical != PhysicalAddr(-1)); physicalAllocator->free(physical, kPageSize); } } // -------------------------------------------------------- // VirtualSpace // -------------------------------------------------------- VirtualSpace::VirtualSpace(VirtualOperations *ops) : _ops{ops} { } void VirtualSpace::setupInitialHole(VirtualAddr address, size_t size) { auto hole = frg::construct<Hole>(*kernelAlloc, address, size); _holes.insert(hole); } VirtualSpace::~VirtualSpace() { if(logCleanup) infoLogger() << "\e[31mthor: VirtualSpace is destructed\e[39m" << frg::endlog; while(_holes.get_root()) { auto hole = _holes.get_root(); _holes.remove(hole); frg::destruct(*kernelAlloc, hole); } } void VirtualSpace::retire() { if(logCleanup) infoLogger() << "\e[31mthor: VirtualSpace is cleared\e[39m" << frg::endlog; // TODO: Set some flag to make sure that no mappings are added/deleted. auto mapping = _mappings.first(); while(mapping) { assert(mapping->state == MappingState::active); mapping->state = MappingState::zombie; for(size_t progress = 0; progress < mapping->length; progress += kPageSize) { VirtualAddr vaddr = mapping->address + progress; auto status = _ops->unmapSingle4k(vaddr); if(!(status & page_status::present)) continue; if(status & page_status::dirty) mapping->view->markDirty(mapping->viewOffset + progress, kPageSize); _residuentSize -= kPageSize; } mapping = MappingTree::successor(mapping); } // TODO: It would be less ugly to run this in a non-detached way. async::detach_with_allocator(*kernelAlloc, [] (smarter::shared_ptr<VirtualSpace> self) -> coroutine<void> { co_await self->_ops->retire(); while(self->_mappings.get_root()) { auto mapping = self->_mappings.get_root(); self->_mappings.remove(mapping); assert(mapping->state == MappingState::zombie); mapping->state = MappingState::retired; if(mapping->view->canEvictMemory()) { mapping->cancelEviction.cancel(); co_await mapping->evictionDoneEvent.wait(); } mapping->view->removeObserver(&mapping->observer); mapping->selfPtr.ctr()->decrement(); } }(selfPtr.lock())); } smarter::shared_ptr<Mapping> VirtualSpace::getMapping(VirtualAddr address) { auto irq_lock = frg::guard(&irqMutex()); auto space_guard = frg::guard(&_mutex); return _findMapping(address); } bool VirtualSpace::map(smarter::borrowed_ptr<MemorySlice> slice, VirtualAddr address, size_t offset, size_t length, uint32_t flags, MapNode *node) { assert(length); assert(!(length % kPageSize)); if(offset + length > slice->length()) { node->nodeResult_.emplace(Error::bufferTooSmall); return true; } VirtualAddr actualAddress; { auto irqLock = frg::guard(&irqMutex()); auto spaceLock = frg::guard(&_mutex); if(flags & kMapFixed) { assert(address); assert((address % kPageSize) == 0); actualAddress = _allocateAt(address, length); }else{ actualAddress = _allocate(length, flags); } assert(actualAddress); // infoLogger() << "Creating new mapping at " << (void *)actualAddress // << ", length: " << (void *)length << frg::endlog; // Setup a new Mapping object. std::underlying_type_t<MappingFlags> mappingFlags = 0; // TODO: The upgrading mechanism needs to be arch-specific: // Some archs might only support RX, while other support X. auto mask = kMapProtRead | kMapProtWrite | kMapProtExecute; if((flags & mask) == (kMapProtRead | kMapProtWrite | kMapProtExecute) || (flags & mask) == (kMapProtWrite | kMapProtExecute)) { // WX is upgraded to RWX. mappingFlags |= MappingFlags::protRead | MappingFlags::protWrite | MappingFlags::protExecute; }else if((flags & mask) == (kMapProtRead | kMapProtExecute) || (flags & mask) == kMapProtExecute) { // X is upgraded to RX. mappingFlags |= MappingFlags::protRead | MappingFlags::protExecute; }else if((flags & mask) == (kMapProtRead | kMapProtWrite) || (flags & mask) == kMapProtWrite) { // W is upgraded to RW. mappingFlags |= MappingFlags::protRead | MappingFlags::protWrite; }else if((flags & mask) == kMapProtRead) { mappingFlags |= MappingFlags::protRead; }else{ assert(!(flags & mask)); } if(flags & kMapDontRequireBacking) mappingFlags |= MappingFlags::dontRequireBacking; auto mapping = smarter::allocate_shared<Mapping>(Allocator{}, length, static_cast<MappingFlags>(mappingFlags), slice.lock(), slice->offset() + offset); mapping->selfPtr = mapping; assert(!(flags & kMapPopulate)); // Install the new mapping object. mapping->tie(selfPtr.lock(), actualAddress); _mappings.insert(mapping.get()); assert(mapping->state == MappingState::null); mapping->state = MappingState::active; mapping->view->addObserver(&mapping->observer); if(mapping->view->canEvictMemory()) async::detach_with_allocator(*kernelAlloc, mapping->runEvictionLoop()); uint32_t pageFlags = 0; if((mappingFlags & MappingFlags::permissionMask) & MappingFlags::protWrite) pageFlags |= page_access::write; if((mappingFlags & MappingFlags::permissionMask) & MappingFlags::protExecute) pageFlags |= page_access::execute; // TODO: Allow inaccessible mappings. assert((mappingFlags & MappingFlags::permissionMask) & MappingFlags::protRead); { // Synchronize with the eviction loop. auto irqLock = frg::guard(&irqMutex()); auto lock = frg::guard(&mapping->evictMutex); for(size_t progress = 0; progress < mapping->length; progress += kPageSize) { auto physicalRange = mapping->view->peekRange(mapping->viewOffset + progress); VirtualAddr vaddr = mapping->address + progress; assert(!_ops->isMapped(vaddr)); if(physicalRange.get<0>() != PhysicalAddr(-1)) { _ops->mapSingle4k(vaddr, physicalRange.get<0>(), pageFlags, physicalRange.get<1>()); _residuentSize += kPageSize; logRss(this); } } } mapping.release(); // VirtualSpace owns one reference. } node->nodeResult_.emplace(actualAddress); return true; } bool VirtualSpace::protect(VirtualAddr address, size_t length, uint32_t flags, AddressProtectNode *node) { std::underlying_type_t<MappingFlags> mappingFlags = 0; // TODO: The upgrading mechanism needs to be arch-specific: // Some archs might only support RX, while other support X. auto mask = kMapProtRead | kMapProtWrite | kMapProtExecute; if((flags & mask) == (kMapProtRead | kMapProtWrite | kMapProtExecute) || (flags & mask) == (kMapProtWrite | kMapProtExecute)) { // WX is upgraded to RWX. mappingFlags |= MappingFlags::protRead | MappingFlags::protWrite | MappingFlags::protExecute; }else if((flags & mask) == (kMapProtRead | kMapProtExecute) || (flags & mask) == kMapProtExecute) { // X is upgraded to RX. mappingFlags |= MappingFlags::protRead | MappingFlags::protExecute; }else if((flags & mask) == (kMapProtRead | kMapProtWrite) || (flags & mask) == kMapProtWrite) { // W is upgraded to RW. mappingFlags |= MappingFlags::protRead | MappingFlags::protWrite; }else if((flags & mask) == kMapProtRead) { mappingFlags |= MappingFlags::protRead; }else{ assert(!(flags & mask)); } auto irq_lock = frg::guard(&irqMutex()); auto space_guard = frg::guard(&_mutex); auto mapping = _findMapping(address); assert(mapping); // TODO: Allow shrinking of the mapping. assert(mapping->address == address); assert(mapping->length == length); mapping->protect(static_cast<MappingFlags>(mappingFlags)); assert(mapping->state == MappingState::active); uint32_t pageFlags = 0; if((mapping->flags & MappingFlags::permissionMask) & MappingFlags::protWrite) pageFlags |= page_access::write; if((mapping->flags & MappingFlags::permissionMask) & MappingFlags::protExecute) pageFlags |= page_access::execute; // TODO: Allow inaccessible mappings. assert((mapping->flags & MappingFlags::permissionMask) & MappingFlags::protRead); { // Synchronize with the eviction loop. auto irqLock = frg::guard(&irqMutex()); auto lock = frg::guard(&mapping->evictMutex); for(size_t progress = 0; progress < mapping->length; progress += kPageSize) { auto physicalRange = mapping->view->peekRange(mapping->viewOffset + progress); VirtualAddr vaddr = mapping->address + progress; auto status = _ops->unmapSingle4k(vaddr); if(!(status & page_status::present)) continue; if(status & page_status::dirty) mapping->view->markDirty(mapping->viewOffset + progress, kPageSize); if(physicalRange.get<0>() != PhysicalAddr(-1)) { _ops->mapSingle4k(vaddr, physicalRange.get<0>(), pageFlags, physicalRange.get<1>()); }else{ _residuentSize -= kPageSize; } } } async::detach_with_allocator(*kernelAlloc, async::transform(_ops->shootdown(address, length), [=] () { node->complete(); })); return false; } bool VirtualSpace::unmap(VirtualAddr address, size_t length, AddressUnmapNode *node) { smarter::shared_ptr<Mapping> mapping; { auto irqLock = frg::guard(&irqMutex()); auto lock = frg::guard(&_mutex); mapping = _findMapping(address); assert(mapping); // TODO: Allow shrinking of the mapping. assert(mapping->address == address); assert(mapping->length == length); assert(mapping->state == MappingState::active); mapping->state = MappingState::zombie; } // Mark pages as dirty and unmap without holding a lock. for(size_t progress = 0; progress < mapping->length; progress += kPageSize) { VirtualAddr vaddr = mapping->address + progress; auto status = _ops->unmapSingle4k(vaddr); if(!(status & page_status::present)) continue; if(status & page_status::dirty) mapping->view->markDirty(mapping->viewOffset + progress, kPageSize); _residuentSize -= kPageSize; } static constexpr auto deleteMapping = [] (VirtualSpace *space, Mapping *mapping) { space->_mappings.remove(mapping); assert(mapping->state == MappingState::zombie); mapping->state = MappingState::retired; if(mapping->view->canEvictMemory()) mapping->cancelEviction.cancel(); // TODO: It would be less ugly to run this in a non-detached way. auto cleanUpObserver = [] (Mapping *mapping) -> coroutine<void> { if(mapping->view->canEvictMemory()) co_await mapping->evictionDoneEvent.wait(); mapping->view->removeObserver(&mapping->observer); mapping->selfPtr.ctr()->decrement(); }; async::detach_with_allocator(*kernelAlloc, cleanUpObserver(mapping)); }; static constexpr auto closeHole = [] (VirtualSpace *space, VirtualAddr address, size_t length) { // Find the holes that preceede/succeede mapping. Hole *pre; Hole *succ; auto current = space->_holes.get_root(); while(true) { assert(current); if(address < current->address()) { if(HoleTree::get_left(current)) { current = HoleTree::get_left(current); }else{ pre = HoleTree::predecessor(current); succ = current; break; } }else{ assert(address >= current->address() + current->length()); if(HoleTree::get_right(current)) { current = HoleTree::get_right(current); }else{ pre = current; succ = HoleTree::successor(current); break; } } } // Try to merge the new hole and the existing ones. if(pre && pre->address() + pre->length() == address && succ && address + length == succ->address()) { auto hole = frg::construct<Hole>(*kernelAlloc, pre->address(), pre->length() + length + succ->length()); space->_holes.remove(pre); space->_holes.remove(succ); space->_holes.insert(hole); frg::destruct(*kernelAlloc, pre); frg::destruct(*kernelAlloc, succ); }else if(pre && pre->address() + pre->length() == address) { auto hole = frg::construct<Hole>(*kernelAlloc, pre->address(), pre->length() + length); space->_holes.remove(pre); space->_holes.insert(hole); frg::destruct(*kernelAlloc, pre); }else if(succ && address + length == succ->address()) { auto hole = frg::construct<Hole>(*kernelAlloc, address, length + succ->length()); space->_holes.remove(succ); space->_holes.insert(hole); frg::destruct(*kernelAlloc, succ); }else{ auto hole = frg::construct<Hole>(*kernelAlloc, address, length); space->_holes.insert(hole); } }; async::detach_with_allocator(*kernelAlloc, async::transform(_ops->shootdown(address, length), [=] () { deleteMapping(this, mapping.get()); closeHole(this, address, length); node->complete(); })); return false; } void VirtualSpace::synchronize(VirtualAddr address, size_t size, SynchronizeNode *node) { auto misalign = address & (kPageSize - 1); auto alignedAddress = address & ~(kPageSize - 1); auto alignedSize = (size + misalign + kPageSize - 1) & ~(kPageSize - 1); async::detach_with_allocator(*kernelAlloc, [] (VirtualSpace *self, VirtualAddr alignedAddress, size_t alignedSize, SynchronizeNode *node) -> coroutine<void> { size_t overallProgress = 0; while(overallProgress < alignedSize) { smarter::shared_ptr<Mapping> mapping; { auto irqLock = frg::guard(&irqMutex()); auto spaceGuard = frg::guard(&self->_mutex); mapping = self->_findMapping(alignedAddress + overallProgress); } assert(mapping); auto mappingOffset = alignedAddress + overallProgress - mapping->address; auto mappingChunk = frg::min(alignedSize - overallProgress, mapping->length - mappingOffset); assert(mapping->state == MappingState::active); assert(mappingOffset + mappingChunk <= mapping->length); // Synchronize with the eviction loop. { auto irqLock = frg::guard(&irqMutex()); auto lock = frg::guard(&mapping->evictMutex); for(size_t chunkProgress = 0; chunkProgress < mappingChunk; chunkProgress += kPageSize) { VirtualAddr vaddr = mapping->address + mappingOffset + chunkProgress; auto status = self->_ops->cleanSingle4k(vaddr); if(!(status & page_status::present)) continue; if(status & page_status::dirty) mapping->view->markDirty(mapping->viewOffset + chunkProgress, kPageSize); } } overallProgress += mappingChunk; } co_await self->_ops->shootdown(alignedAddress, alignedSize); node->resume(); }(this, alignedAddress, alignedSize, node)); } frg::optional<bool> VirtualSpace::handleFault(VirtualAddr address, uint32_t faultFlags, smarter::shared_ptr<WorkQueue> wq, FaultNode *node) { smarter::shared_ptr<Mapping> mapping; { auto irq_lock = frg::guard(&irqMutex()); auto space_guard = frg::guard(&_mutex); mapping = _findMapping(address); } if(!mapping) return false; // Here we do the mapping-based fault handling. if(faultFlags & VirtualSpace::kFaultWrite) if(!((mapping->flags & MappingFlags::permissionMask) & MappingFlags::protWrite)) { return true; } if(faultFlags & VirtualSpace::kFaultExecute) if(!((mapping->flags & MappingFlags::permissionMask) & MappingFlags::protExecute)) { return true; } async::detach_with_allocator(*kernelAlloc, [] (smarter::shared_ptr<Mapping> mapping, uintptr_t address, smarter::shared_ptr<WorkQueue> wq, FaultNode *node) -> coroutine<void> { auto faultPage = (address - mapping->address) & ~(kPageSize - 1); auto outcome = co_await mapping->touchVirtualPage(faultPage, std::move(wq)); if(!outcome) { node->complete(false); co_return; } // Spurious page faults are the result of race conditions. // They should be rare. If they happen too often, something is probably wrong! if(outcome.value().spurious) infoLogger() << "\e[33m" "thor: Spurious page fault" "\e[39m" << frg::endlog; node->complete(true); }(std::move(mapping), address, std::move(wq), node)); return {}; } smarter::shared_ptr<Mapping> VirtualSpace::_findMapping(VirtualAddr address) { auto current = _mappings.get_root(); while(current) { if(address < current->address) { current = MappingTree::get_left(current); }else if(address >= current->address + current->length) { current = MappingTree::get_right(current); }else{ assert(address >= current->address && address < current->address + current->length); return current->selfPtr.lock(); } } return nullptr; } VirtualAddr VirtualSpace::_allocate(size_t length, MapFlags flags) { assert(length > 0); assert((length % kPageSize) == 0); // infoLogger() << "Allocate virtual memory area" // << ", size: 0x" << frg::hex_fmt(length) << frg::endlog; if(_holes.get_root()->largestHole < length) return 0; // TODO: Return something else here? auto current = _holes.get_root(); while(true) { if(flags & kMapPreferBottom) { // Try to allocate memory at the bottom of the range. if(HoleTree::get_left(current) && HoleTree::get_left(current)->largestHole >= length) { current = HoleTree::get_left(current); continue; } if(current->length() >= length) { // Note that _splitHole can deallocate the hole! auto address = current->address(); _splitHole(current, 0, length); return address; } assert(HoleTree::get_right(current)); assert(HoleTree::get_right(current)->largestHole >= length); current = HoleTree::get_right(current); }else{ // Try to allocate memory at the top of the range. assert(flags & kMapPreferTop); if(HoleTree::get_right(current) && HoleTree::get_right(current)->largestHole >= length) { current = HoleTree::get_right(current); continue; } if(current->length() >= length) { // Note that _splitHole can deallocate the hole! auto offset = current->length() - length; auto address = current->address() + offset; _splitHole(current, offset, length); return address; } assert(HoleTree::get_left(current)); assert(HoleTree::get_left(current)->largestHole >= length); current = HoleTree::get_left(current); } } } VirtualAddr VirtualSpace::_allocateAt(VirtualAddr address, size_t length) { assert(!(address % kPageSize)); assert(!(length % kPageSize)); auto current = _holes.get_root(); while(true) { // TODO: Otherwise, this method fails. assert(current); if(address < current->address()) { current = HoleTree::get_left(current); }else if(address >= current->address() + current->length()) { current = HoleTree::get_right(current); }else{ assert(address >= current->address() && address < current->address() + current->length()); break; } } _splitHole(current, address - current->address(), length); return address; } void VirtualSpace::_splitHole(Hole *hole, VirtualAddr offset, size_t length) { assert(length); assert(offset + length <= hole->length()); _holes.remove(hole); if(offset) { auto predecessor = frg::construct<Hole>(*kernelAlloc, hole->address(), offset); _holes.insert(predecessor); } if(offset + length < hole->length()) { auto successor = frg::construct<Hole>(*kernelAlloc, hole->address() + offset + length, hole->length() - (offset + length)); _holes.insert(successor); } frg::destruct(*kernelAlloc, hole); } // -------------------------------------------------------- // AddressSpace // -------------------------------------------------------- void AddressSpace::activate(smarter::shared_ptr<AddressSpace, BindableHandle> space) { auto pageSpace = &space->pageSpace_; PageSpace::activate(smarter::shared_ptr<PageSpace>{space->selfPtr.lock(), pageSpace}); } AddressSpace::AddressSpace() : VirtualSpace{&ops_}, ops_{this} { } AddressSpace::~AddressSpace() { } void AddressSpace::dispose(BindableHandle) { retire(); } // -------------------------------------------------------- // MemoryViewLockHandle. // -------------------------------------------------------- MemoryViewLockHandle::~MemoryViewLockHandle() { if(_active) _view->unlockRange(_offset, _size); } // -------------------------------------------------------- // AddressSpaceLockHandle // -------------------------------------------------------- AddressSpaceLockHandle::AddressSpaceLockHandle(smarter::shared_ptr<AddressSpace, BindableHandle> space, void *pointer, size_t length) : _space{std::move(space)}, _address{reinterpret_cast<uintptr_t>(pointer)}, _length{length} { if(!_length) return; assert(_address); // TODO: Verify the mapping's size. _mapping = _space->getMapping(_address); assert(_mapping); } AddressSpaceLockHandle::~AddressSpaceLockHandle() { if(!_length) return; if(_active) _mapping->unlockVirtualRange(_address - _mapping->address, _length); } bool AddressSpaceLockHandle::acquire(smarter::shared_ptr<WorkQueue> wq, AcquireNode *node) { if(!_length) { _active = true; return true; } async::detach_with_allocator(*kernelAlloc, [] (AddressSpaceLockHandle *self, smarter::shared_ptr<WorkQueue> wq, AcquireNode *node) -> coroutine<void> { auto misalign = self->_address & (kPageSize - 1); auto lockOutcome = co_await self->_mapping->lockVirtualRange( (self->_address - self->_mapping->address) & ~(kPageSize - 1), (self->_length + misalign + kPageSize - 1) & ~(kPageSize - 1), wq); assert(lockOutcome); auto populateOutcome = co_await self->_mapping->populateVirtualRange( (self->_address - self->_mapping->address) & ~(kPageSize - 1), (self->_length + misalign + kPageSize - 1) & ~(kPageSize - 1), wq); assert(populateOutcome); self->_active = true; node->complete(); }(this, std::move(wq), node)); return false; } PhysicalAddr AddressSpaceLockHandle::getPhysical(size_t offset) { assert(_active); assert(offset < _length); return _resolvePhysical(_address + offset); } void AddressSpaceLockHandle::load(size_t offset, void *pointer, size_t size) { assert(_active); assert(offset + size <= _length); size_t progress = 0; while(progress < size) { VirtualAddr write = (VirtualAddr)_address + offset + progress; size_t misalign = (VirtualAddr)write % kPageSize; size_t chunk = frg::min(kPageSize - misalign, size - progress); PhysicalAddr page = _resolvePhysical(write - misalign); assert(page != PhysicalAddr(-1)); PageAccessor accessor{page}; memcpy((char *)pointer + progress, (char *)accessor.get() + misalign, chunk); progress += chunk; } } Error AddressSpaceLockHandle::write(size_t offset, const void *pointer, size_t size) { assert(_active); assert(offset + size <= _length); size_t progress = 0; while(progress < size) { VirtualAddr write = (VirtualAddr)_address + offset + progress; size_t misalign = (VirtualAddr)write % kPageSize; size_t chunk = frg::min(kPageSize - misalign, size - progress); PhysicalAddr page = _resolvePhysical(write - misalign); assert(page != PhysicalAddr(-1)); PageAccessor accessor{page}; memcpy((char *)accessor.get() + misalign, (char *)pointer + progress, chunk); progress += chunk; } return Error::success; } PhysicalAddr AddressSpaceLockHandle::_resolvePhysical(VirtualAddr vaddr) { auto range = _mapping->resolveRange(vaddr - _mapping->address); return range.get<0>(); } // -------------------------------------------------------- // NamedMemoryViewLock. // -------------------------------------------------------- NamedMemoryViewLock::~NamedMemoryViewLock() { } } // namespace thor
31.782178
103
0.673115
64
030c119e42ce28723ff3883ec3513ba8666b1d52
16,531
cpp
C++
dev/spark/Gem/Code/Components/GameManagerSystemComponent.cpp
chrisinajar/spark
3c6b30592c00bc38738cc3aaca2144edfc6cc8b2
[ "AML" ]
2
2020-08-20T03:40:24.000Z
2021-02-07T20:31:43.000Z
dev/spark/Gem/Code/Components/GameManagerSystemComponent.cpp
chrisinajar/spark
3c6b30592c00bc38738cc3aaca2144edfc6cc8b2
[ "AML" ]
null
null
null
dev/spark/Gem/Code/Components/GameManagerSystemComponent.cpp
chrisinajar/spark
3c6b30592c00bc38738cc3aaca2144edfc6cc8b2
[ "AML" ]
5
2020-08-27T20:44:18.000Z
2021-08-21T22:54:11.000Z
#include "spark_precompiled.h" #include <ISystem.h> #include <CryAction.h> #include <AzCore/Component/Component.h> #include <AzCore/Component/Entity.h> #include <AzFramework/Script/ScriptComponent.h> #include <AzCore/Asset/AssetManagerBus.h> #include <AzFramework/Entity/EntityContextBus.h> #include <AzFramework/Entity/EntityContext.h> #include <AzCore/Component/TransformBus.h> #include <AzCore/std/algorithm.h> #include "GameManagerSystemComponent.h" #include "Components/AbilityComponent.h" #include "Components/UnitComponent.h" #include "Components/GameManagerComponent.h" #include "Components/CameraControllerComponent.h" #include "Components/GameNetSyncComponent.h" #include "Components/ProjectileManagerSystemComponent.h" #include "Components/VariableManagerComponent.h" #include <AzFramework/Network/NetBindingComponent.h> #include "Busses/UnitBus.h" #include "Utils/StringUtils.h" #include "Utils/FileUtils.h" #include <AzFramework/Entity/GameEntityContextBus.h> #include <AzCore/Component/ComponentApplicationBus.h> #include "Utils/JsonUtils.h" #include "Utils/Log.h" using namespace spark; AZStd::vector<AZStd::string> GameManagerSystemComponent::s_filenames; AZStd::vector<AZStd::string> GameManagerSystemComponent::s_directories; void GameManagerSystemComponent::Reflect(AZ::ReflectContext* context) { if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context)) { serialize->Class<GameManagerSystemComponent, AZ::Component>() ->Version(0) ; if (AZ::EditContext* ec = serialize->GetEditContext()) { ec->Class<GameManagerSystemComponent>("GameManagerSystemComponent", "Game utilities and management") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") // ->Attribute(AZ::Edit::Attributes::Category, "spark") // ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game")); //; ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System")) ->Attribute(AZ::Edit::Attributes::AutoExpand, true); } } if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context)) { behaviorContext->EBus<GameManagerSystemRequestBus>("GameManagerSystemRequestBus") ->Event("ExecuteConsoleCommand", &GameManagerSystemRequestBus::Events::ExecuteConsoleCommand) ->Event("LoadGameFile", &GameManagerSystemRequestBus::Events::LoadGameFile) ->Event("LoadGameMode", &GameManagerSystemRequestBus::Events::LoadGameMode) ->Event("PlayGame", &GameManagerSystemRequestBus::Events::PlayGame); } } void GameManagerSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { provided.push_back(AZ_CRC("GameManagerSystemService")); } void GameManagerSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("GameManagerSystemService")); } void GameManagerSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) { (void)required; } void GameManagerSystemComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) { (void)dependent; } void GameManagerSystemComponent::Init() { } void GameManagerSystemComponent::Activate() { GameManagerSystemRequestBus::Handler::BusConnect(); GameManagerNotificationBus::Handler::BusConnect(); } void GameManagerSystemComponent::Deactivate() { GameManagerNotificationBus::Handler::BusDisconnect(); GameManagerSystemRequestBus::Handler::BusDisconnect(); } bool GameManagerSystemComponent::LoadGameFile(AZStd::string filename) { //"header" guard if (!FileUtils::FileExists(filename)) { // try some file extensions if (FileUtils::FileExists(filename + ".json")) { filename = filename + ".json"; } else if (FileUtils::FileExists(filename + ".txt")) { filename = filename + ".txt"; } } auto found = std::find(s_filenames.begin(), s_filenames.end(), filename); if (found != s_filenames.end()) { return false; } s_filenames.push_back(filename); auto result = FileUtils::ReadJsonFile(filename); if (!result.IsSuccess()) { sWARNING("Unable to read game file \""+filename +"\" error:"+ result.GetError()); return false; } auto document = result.TakeValue(); //libraries auto import = document.FindMember("import"); if (import != document.MemberEnd() && import->value.IsArray()) { for (auto it = import->value.Begin(); it != import->value.End(); ++it) { if (it->IsString()) { LoadGameMode(it->GetString()); } } document.EraseMember(import); } //other files auto include = document.FindMember("include"); if (include != document.MemberEnd() && include->value.IsArray()) { for (auto it = include->value.Begin(); it != include->value.End(); ++it) { if (it->IsString()) { AZStd::string newfile(it->GetString()); StringUtils::trim(newfile); AZStd::size_t found = filename.find_last_of("/\\"); AZStd::string path = filename.substr(0, found); LoadGameFile(AZStd::string::format("%s/%s", path.c_str() , newfile.c_str())); } } document.EraseMember(include); } JsonUtils::MergeObjects(document,m_gameDocument, document.GetAllocator()); m_gameDocument.Swap(document); sLOG("GameManagerSystemComponent::LoadGameFile file loaded correctly : "+filename); sLOG(JsonUtils::ToString(m_gameDocument)); return true; } bool GameManagerSystemComponent::LoadGameMode(AZStd::string gamemodeName) { AZStd::string gamemodePath = AZStd::string::format("%s/gamemode/%s", gEnv->pFileIO->GetAlias("@assets@"), gamemodeName.c_str()); bool result = LoadGameFile( gamemodePath + "/game.txt"); if (result) { s_directories.push_back(gamemodePath); } return result; } void GameManagerSystemComponent::PlayGame() { using namespace rapidjson; if (!m_gameDocument.IsObject() || !m_gameDocument.HasMember("gamemode")) { sWARNING("gamemode was not defined"); return; } rapidjson::Value &info = m_gameDocument["gamemode"]; //load map AZStd::string map_name = info.HasMember("map") ? info["map"].GetString() : "emptylevel"; //todo check for injection attack ExecuteConsoleCommand(AZStd::string::format("map %s", map_name.c_str())); ////create camera //const AZ::Data::AssetType& dynamicSliceAssetType = azrtti_typeid<AZ::DynamicPrefabAsset>(); //{ // AZ::Data::AssetId assetId; // AZStd::string str = AZStd::string::format("%s/Slices/Camera.slice", gEnv->pFileIO->GetAlias("@assets@")); // CryLog("dynamicSlice Path: %s", str.c_str()); // EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), dynamicSliceAssetType, true); // if (assetId.IsValid()) { // CryLog("Loading dynamicSlice"); // AZ::Data::Asset<AZ::DynamicPrefabAsset> dynamicSliceAsset(assetId, dynamicSliceAssetType); // AzFramework::SliceInstantiationTicket ticket; // AZ::Transform transform; // transform.SetFromEulerDegrees(AZ::Vector3(305, 0, 0)); // transform.SetPosition(500, 500, 50); // EBUS_EVENT_RESULT(ticket, AzFramework::GameEntityContextRequestBus, InstantiateDynamicSlice, dynamicSliceAsset, transform, nullptr); // } // else // { // AZ_Error(0, false, "cannot instantiate camera slice"); // } //} m_tickCounter = 300; AZ::SystemTickBus::Handler::BusConnect(); } void GameManagerSystemComponent::CreateGameManager() { bool gameManagerAlreadyExists = false; EBUS_EVENT_RESULT(gameManagerAlreadyExists, GameManagerRequestBus, GameManagerAlreadyExists); if (gameManagerAlreadyExists) { AZ_Printf(0, "GameManager already exists"); } else { AZ_Printf(0, "GameManager is missing : creating the default one"); rapidjson::Value &info = m_gameDocument["gamemode"]; //create game manager AZ::Entity *gameManager = aznew AZ::Entity("GameManager"); if (gameManager) { GameManagerComponent* gm = gameManager->CreateComponent<GameManagerComponent>(); gameManager->CreateComponent<ProjectileManagerSystemComponent>(); gameManager->CreateComponent<GameNetSyncComponent>(); gameManager->CreateComponent<AzFramework::NetBindingComponent>(); const AZ::Data::AssetType& scriptAssetType = azrtti_typeid<AZ::ScriptAsset>(); ////script for showing cursor //AzFramework::ScriptComponent *cursor = gameManager->CreateComponent<AzFramework::ScriptComponent>(); //{ // AZ::Data::AssetId assetId; // AZStd::string str = AZStd::string::format("%s/scripts/ShowCursor.lua", gEnv->pFileIO->GetAlias("@assets@")); // CryLog("Script Path: %s", str.c_str()); // EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), scriptAssetType, true); // //EBUS_EVENT( AZ::Data::AssetCatalogRequestBus, UnregisterAsset, assetId); // //EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), scriptAssetType, true); // if (assetId.IsValid()) { // CryLog("Setting Script."); // AZ::Data::Asset<AZ::ScriptAsset> scriptAsset(assetId, scriptAssetType); // cursor->SetScript(scriptAsset); // } //} //script for handling modifiers AzFramework::ScriptComponent *modifiers = gameManager->CreateComponent<AzFramework::ScriptComponent>(); { AZ::Data::AssetId assetId; AZStd::string str = AZStd::string::format("%s/scripts/modifier.lua", gEnv->pFileIO->GetAlias("@assets@")); CryLog("Script Path: %s", str.c_str()); EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), scriptAssetType, true); if (assetId.IsValid()) { CryLog("Setting Script."); AZ::Data::Asset<AZ::ScriptAsset> scriptAsset(assetId, scriptAssetType); modifiers->SetScript(scriptAsset); } } //script for handling game mode if (info.HasMember("lua-file")) { AzFramework::ScriptComponent *scriptComponent = gameManager->CreateComponent<AzFramework::ScriptComponent>(); AZ::Data::AssetId assetId; AZStd::string str = AZStd::string::format("%s/scripts/%s", gEnv->pFileIO->GetAlias("@assets@"), info["lua-file"].GetString()); CryLog("Script Path: %s", str.c_str()); EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), scriptAssetType, true); if (assetId.IsValid()) { CryLog("Setting Script."); AZ::Data::Asset<AZ::ScriptAsset> scriptAsset(assetId, scriptAssetType); scriptComponent->SetScript(scriptAsset); } } ////script for loading the HUD canvas //AzFramework::ScriptComponent *canvas = gameManager->CreateComponent<AzFramework::ScriptComponent>(); //{ // AZ::Data::AssetId assetId; // AZStd::string str = AZStd::string::format("%s/scripts/LoadHUD.lua", gEnv->pFileIO->GetAlias("@assets@")); // CryLog("Script Path: %s", str.c_str()); // EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), scriptAssetType, true); // if (assetId.IsValid()) { // CryLog("Setting Script."); // AZ::Data::Asset<AZ::ScriptAsset> scriptAsset(assetId, scriptAssetType); // canvas->SetScript(scriptAsset); // } //} //gm->m_gameDocument.Swap(m_gameDocument); gameManager->Init(); gameManager->Activate(); } } } void GameManagerSystemComponent::OnSystemTick() { --m_tickCounter; if (m_tickCounter <= 0) { CreateGameManager(); AZ::SystemTickBus::Handler::BusDisconnect(); } } void GameManagerSystemComponent::ExecuteConsoleCommand(AZStd::string cmd) { //todo check for injection attack gEnv->pConsole->ExecuteString(cmd.c_str(), false, true); } struct DependeciesGraphNode { AZStd::vector<ItemTypeId> dependencies; AZStd::vector<ItemTypeId> required_for; }; void CalculateItemsDependencies(rapidjson::Document &document) { sLOG("CalculateItemsDependencies called"); if (!document.IsObject() || !document.HasMember("items"))return; auto &allocator = document.GetAllocator(); auto &items = document["items"]; AZStd::unordered_map<ItemTypeId, DependeciesGraphNode> graph; //get all node for (auto item = items.MemberBegin(); item != items.MemberEnd(); ++item) { graph[item->name.GetString()] = DependeciesGraphNode(); } //check and set dependencies and "required_for"( if the items in the dependency list exist ) for (auto item = items.MemberBegin(); item != items.MemberEnd(); ++item) { if (!item->value.IsObject() || !item->value.HasMember("dependencies"))continue; auto &dependencies = item->value["dependencies"]; if (!dependencies.IsArray())continue; AZStd::vector<ItemTypeId> dependencies_vector; for (auto itr = dependencies.Begin(); itr != dependencies.End(); ++itr) { if (itr->IsString() && graph.find(itr->GetString()) != graph.end()) { dependencies_vector.push_back(itr->GetString()); graph[itr->GetString()].required_for.push_back(item->name.GetString()); } } graph[item->name.GetString()].dependencies = dependencies_vector; } //update the json for (auto item = items.MemberBegin(); item != items.MemberEnd(); ++item) { //sLOG(item->name.GetString()+" is "+JsonUtils::ToString(item->value)); if (!item->value.IsObject())continue; rapidjson::Value dep(rapidjson::kArrayType); for (auto d : graph[item->name.GetString()].dependencies) { rapidjson::Value str; str.SetString(d.c_str(),allocator); dep.PushBack(str,allocator); } rapidjson::Value req(rapidjson::kArrayType); for (auto d : graph[item->name.GetString()].required_for) { rapidjson::Value str; str.SetString(d.c_str(),allocator); req.PushBack(str,allocator); } item->value.RemoveMember("dependencies"); item->value.RemoveMember("required_for"); item->value.AddMember("dependencies", dep, allocator); item->value.AddMember("required_for", req, allocator); } } void CalculateExtends(rapidjson::Value &object, rapidjson::Value &parent, rapidjson::Document &document) { if (!object.IsObject())return; AZStd::vector<AZStd::string> extends; auto extendsJson = object.FindMember("extends"); if (extendsJson != object.MemberEnd()) { if (extendsJson->value.IsArray()) { for (auto it = extendsJson->value.Begin(); it != extendsJson->value.End(); ++it) { if (it->IsString()) { extends.push_back(it->GetString()); } } } else if (extendsJson->value.IsString()) { extends.push_back(extendsJson->value.GetString()); } } if (extendsJson != object.MemberEnd()) { object.EraseMember(extendsJson); //so we don't create extend loops } for (auto e : extends) { auto path = StringUtils::SplitString(e, "/"); rapidjson::Value* root = &parent; rapidjson::Value* value = JsonUtils::FindValue(path, *root); //try the relative path root = &document; if (!value)value = JsonUtils::FindValue(path, *root); //try the absolute path if (value) { path.pop_back(); auto value_parent = JsonUtils::FindValue(path, *root); CalculateExtends(*value, *value_parent, document); JsonUtils::MergeObjects(object, *value, document.GetAllocator()); } } }; void CalculateExtends(rapidjson::Document &document) { sLOG("CalculateExtends called"); /* syntax is "something_else":{ ... }, "something" : { "extends" : "something_else", ... } */ JsonUtils::ForeachMemberWithParent(document, [&document](rapidjson::Value &member, rapidjson::Value &parent) { CalculateExtends(member, parent, document); }); } void GameManagerSystemComponent::OnGameManagerActivated(AZ::Entity* gameManager) { AZ_Printf(0,"GameManagerSystemComponent:OnGameManagerActivated called"); AZ_Error("GameManagerSystemComponent", gameManager, " OnGameManagerActivated with null entity pointer"); GameManagerComponent* gm = gameManager->FindComponent<GameManagerComponent>(); AZ_Error("GameManagerSystemComponent", gm, " OnGameManagerActivated called, but the entity is without a GameManagerComponent"); AZ::SystemTickBus::Handler::BusDisconnect(); if (!m_gameDocument.IsObject() || m_gameDocument.MemberCount()==0)// !gm->m_gameDocument.IsObject() || gm->m_gameDocument.ObjectEmpty()) { LoadGameMode(gm->GetGamemode()); } CalculateExtends(m_gameDocument); CalculateItemsDependencies(m_gameDocument); AZStd::reverse(s_directories.begin(), s_directories.end());//imported gamemodes are inserted before, so we need to reverse the vector to have the priorities right sLOG("final gamemode json is : "+JsonUtils::ToString(m_gameDocument)); gm->SetGameJson(m_gameDocument, s_directories); m_gameDocument.SetObject();//clear the document and all for the next gamemode s_filenames.clear(); s_directories.clear(); gm->StartGame(); }
30.443831
163
0.721432
chrisinajar
0310133372a8a8f1654321664c21e429d0545c45
930
cpp
C++
[376] Wiggle Subsequence/376.wiggle-subsequence.cpp
Coolzyh/Leetcode
4abf685501427be0ce36b83016c4fa774cdf1a1a
[ "MIT" ]
null
null
null
[376] Wiggle Subsequence/376.wiggle-subsequence.cpp
Coolzyh/Leetcode
4abf685501427be0ce36b83016c4fa774cdf1a1a
[ "MIT" ]
null
null
null
[376] Wiggle Subsequence/376.wiggle-subsequence.cpp
Coolzyh/Leetcode
4abf685501427be0ce36b83016c4fa774cdf1a1a
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=376 lang=cpp * * [376] Wiggle Subsequence */ // @lc code=start class Solution { public: int wiggleMaxLength(vector<int>& nums) { // O(n) dp method int n = nums.size(); if (n == 1) return 1; // up[] and down[] record the max wiggle sequence length so far at index i. // which don't have to end with nums[i] vector<int> up(n, 0); vector<int> down(n, 0); up[0] = 1; down[0] = 1; for (int i = 1; i < n; i++) { if (nums[i] > nums[i-1]) { up[i] = down[i-1]+1; down[i] = down[i-1]; } else if (nums[i] < nums[i-1]) { up[i] = up[i-1]; down[i] = up[i-1]+1; } else { up[i] = up[i-1]; down[i] = down[i-1]; } } return max(up[n-1], down[n-1]); } }; // @lc code=end
25.135135
83
0.416129
Coolzyh
03123a6d86ea7e87e1afe345039412b79c1ff84b
12,852
cpp
C++
src/gpu/gl/GrGLNameAllocator.cpp
Perspex/skia
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
[ "Apache-2.0" ]
7
2016-01-12T23:32:32.000Z
2021-12-03T11:21:26.000Z
src/gpu/gl/GrGLNameAllocator.cpp
AvaloniaUI/skia
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
[ "Apache-2.0" ]
null
null
null
src/gpu/gl/GrGLNameAllocator.cpp
AvaloniaUI/skia
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
[ "Apache-2.0" ]
6
2015-12-09T14:00:19.000Z
2021-12-06T03:08:43.000Z
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLNameAllocator.h" /** * This is the abstract base class for a nonempty AVL tree that tracks allocated * names within the half-open range [fFirst, fEnd). The inner nodes can be * sparse (meaning not every name within the range is necessarily allocated), * but the bounds are tight, so fFirst *is* guaranteed to be allocated, and so * is fEnd - 1. */ class GrGLNameAllocator::SparseNameRange : public SkRefCnt { public: virtual ~SparseNameRange() {} /** * Return the beginning of the range. first() is guaranteed to be allocated. * * @return The first name in the range. */ GrGLuint first() const { return fFirst; } /** * Return the end of the range. end() - 1 is guaranteed to be allocated. * * @return One plus the final name in the range. */ GrGLuint end() const { return fEnd; } /** * Return the height of the tree. This can only be nonzero at an inner node. * * @return 0 if the implementation is a leaf node, * The nonzero height of the tree otherwise. */ GrGLuint height() const { return fHeight; } /** * Allocate a name from strictly inside this range. The call will fail if * there is not a free name within. * * @param outName A pointer that receives the allocated name. outName will * be set to zero if there were no free names within the * range [fFirst, fEnd). * @return The resulting SparseNameRange after the allocation. Note that * this call is destructive, so the original SparseNameRange will no * longer be valid afterward. The caller must always update its * pointer with the new SparseNameRange. */ virtual SparseNameRange* SK_WARN_UNUSED_RESULT internalAllocate(GrGLuint* outName) = 0; /** * Remove the leftmost leaf node from this range (or the entire thing if it * *is* a leaf node). This is an internal helper method that is used after * an allocation if one contiguous range became adjacent to another. (The * range gets removed so the one immediately before can be extended, * collapsing the two into one.) * * @param removedCount A pointer that receives the size of the contiguous range that was removed. * @return The resulting SparseNameRange after the removal (or nullptr if it * became empty). Note that this call is destructive, so the * original SparseNameRange will no longer be valid afterward. The * caller must always update its pointer with the new * SparseNameRange. */ virtual SparseNameRange* SK_WARN_UNUSED_RESULT removeLeftmostContiguousRange(GrGLuint* removedCount) = 0; /** * Append adjacent allocated names to the end of this range. This operation * does not affect the structure of the tree. The caller is responsible for * ensuring the new names won't overlap sibling ranges, if any. * * @param count The number of adjacent names to append. * @return The first name appended. */ virtual GrGLuint appendNames(GrGLuint count) = 0; /** * Prepend adjacent allocated names behind the beginning of this range. This * operation does not affect the structure of the tree. The caller is * responsible for ensuring the new names won't overlap sibling ranges, if * any. * * @param count The number of adjacent names to prepend. * @return The final name prepended (the one with the lowest value). */ virtual GrGLuint prependNames(GrGLuint count) = 0; /** * Free a name so it is no longer tracked as allocated. If the name is at * the very beginning or very end of the range, the boundaries [fFirst, fEnd) * will be tightened. * * @param name The name to free. Not-allocated names are silently ignored * the same way they are in the OpenGL spec. * @return The resulting SparseNameRange after the free (or nullptr if it * became empty). Note that this call is destructive, so the * original SparseNameRange will no longer be valid afterward. The * caller must always update its pointer with the new * SparseNameRange. */ virtual SparseNameRange* SK_WARN_UNUSED_RESULT free(GrGLuint name) = 0; protected: SparseNameRange* takeRef() { this->ref(); return this; } GrGLuint fFirst; GrGLuint fEnd; GrGLuint fHeight; }; /** * This class is the SparseNameRange implementation for an inner node. It is an * AVL tree with non-null, non-adjacent left and right children. */ class GrGLNameAllocator::SparseNameTree : public SparseNameRange { public: SparseNameTree(SparseNameRange* left, SparseNameRange* right) : fLeft(left), fRight(right) { SkASSERT(fLeft.get()); SkASSERT(fRight.get()); this->updateStats(); } SparseNameRange* SK_WARN_UNUSED_RESULT internalAllocate(GrGLuint* outName) override { // Try allocating the range inside fLeft's internal gaps. fLeft.reset(fLeft->internalAllocate(outName)); if (0 != *outName) { this->updateStats(); return this->rebalance(); } if (fLeft->end() + 1 == fRight->first()) { // It closed the gap between fLeft and fRight; merge. GrGLuint removedCount; fRight.reset(fRight->removeLeftmostContiguousRange(&removedCount)); *outName = fLeft->appendNames(1 + removedCount); if (nullptr == fRight.get()) { return fLeft.detach(); } this->updateStats(); return this->rebalance(); } // There is guaranteed to be a gap between fLeft and fRight, and the // "size 1" case has already been covered. SkASSERT(fLeft->end() + 1 < fRight->first()); *outName = fLeft->appendNames(1); return this->takeRef(); } SparseNameRange* SK_WARN_UNUSED_RESULT removeLeftmostContiguousRange(GrGLuint* removedCount) override { fLeft.reset(fLeft->removeLeftmostContiguousRange(removedCount)); if (nullptr == fLeft) { return fRight.detach(); } this->updateStats(); return this->rebalance(); } GrGLuint appendNames(GrGLuint count) override { SkASSERT(fEnd + count > fEnd); // Check for integer wrap. GrGLuint name = fRight->appendNames(count); SkASSERT(fRight->end() == fEnd + count); this->updateStats(); return name; } GrGLuint prependNames(GrGLuint count) override { SkASSERT(fFirst > count); // We can't allocate at or below 0. GrGLuint name = fLeft->prependNames(count); SkASSERT(fLeft->first() == fFirst - count); this->updateStats(); return name; } SparseNameRange* SK_WARN_UNUSED_RESULT free(GrGLuint name) override { if (name < fLeft->end()) { fLeft.reset(fLeft->free(name)); if (nullptr == fLeft) { // fLeft became empty after the free. return fRight.detach(); } this->updateStats(); return this->rebalance(); } else { fRight.reset(fRight->free(name)); if (nullptr == fRight) { // fRight became empty after the free. return fLeft.detach(); } this->updateStats(); return this->rebalance(); } } private: typedef SkAutoTUnref<SparseNameRange> SparseNameTree::* ChildRange; SparseNameRange* SK_WARN_UNUSED_RESULT rebalance() { if (fLeft->height() > fRight->height() + 1) { return this->rebalanceImpl<&SparseNameTree::fLeft, &SparseNameTree::fRight>(); } if (fRight->height() > fLeft->height() + 1) { return this->rebalanceImpl<&SparseNameTree::fRight, &SparseNameTree::fLeft>(); } return this->takeRef(); } /** * Rebalance the tree using rotations, as described in the AVL algorithm: * http://en.wikipedia.org/wiki/AVL_tree#Insertion */ template<ChildRange Tall, ChildRange Short> SparseNameRange* SK_WARN_UNUSED_RESULT rebalanceImpl() { // We should be calling rebalance() enough that the tree never gets more // than one rotation off balance. SkASSERT(2 == (this->*Tall)->height() - (this->*Short)->height()); // Ensure we are in the 'Left Left' or 'Right Right' case: // http://en.wikipedia.org/wiki/AVL_tree#Insertion SparseNameTree* tallChild = static_cast<SparseNameTree*>((this->*Tall).get()); if ((tallChild->*Tall)->height() < (tallChild->*Short)->height()) { (this->*Tall).reset(tallChild->rotate<Short, Tall>()); } // Perform a rotation to balance the tree. return this->rotate<Tall, Short>(); } /** * Perform a node rotation, as described in the AVL algorithm: * http://en.wikipedia.org/wiki/AVL_tree#Insertion */ template<ChildRange Tall, ChildRange Short> SparseNameRange* SK_WARN_UNUSED_RESULT rotate() { SparseNameTree* newRoot = static_cast<SparseNameTree*>((this->*Tall).detach()); (this->*Tall).reset((newRoot->*Short).detach()); this->updateStats(); (newRoot->*Short).reset(this->takeRef()); newRoot->updateStats(); return newRoot; } void updateStats() { SkASSERT(fLeft->end() < fRight->first()); // There must be a gap between left and right. fFirst = fLeft->first(); fEnd = fRight->end(); fHeight = 1 + SkMax32(fLeft->height(), fRight->height()); } SkAutoTUnref<SparseNameRange> fLeft; SkAutoTUnref<SparseNameRange> fRight; }; /** * This class is the SparseNameRange implementation for a leaf node. It just a * contiguous range of allocated names. */ class GrGLNameAllocator::ContiguousNameRange : public SparseNameRange { public: ContiguousNameRange(GrGLuint first, GrGLuint end) { SkASSERT(first < end); fFirst = first; fEnd = end; fHeight = 0; } SparseNameRange* SK_WARN_UNUSED_RESULT internalAllocate(GrGLuint* outName) override { *outName = 0; // No internal gaps, we are contiguous. return this->takeRef(); } SparseNameRange* SK_WARN_UNUSED_RESULT removeLeftmostContiguousRange(GrGLuint* removedCount) override { *removedCount = fEnd - fFirst; return nullptr; } GrGLuint appendNames(GrGLuint count) override { SkASSERT(fEnd + count > fEnd); // Check for integer wrap. GrGLuint name = fEnd; fEnd += count; return name; } GrGLuint prependNames(GrGLuint count) override { SkASSERT(fFirst > count); // We can't allocate at or below 0. fFirst -= count; return fFirst; } SparseNameRange* SK_WARN_UNUSED_RESULT free(GrGLuint name) override { if (name < fFirst || name >= fEnd) { // Not-allocated names are silently ignored. return this->takeRef(); } if (fFirst == name) { ++fFirst; return (fEnd == fFirst) ? nullptr : this->takeRef(); } if (fEnd == name + 1) { --fEnd; return this->takeRef(); } SparseNameRange* left = new ContiguousNameRange(fFirst, name); SparseNameRange* right = this->takeRef(); fFirst = name + 1; return new SparseNameTree(left, right); } }; GrGLNameAllocator::GrGLNameAllocator(GrGLuint firstName, GrGLuint endName) : fFirstName(firstName), fEndName(endName) { SkASSERT(firstName > 0); SkASSERT(endName > firstName); } GrGLNameAllocator::~GrGLNameAllocator() { } GrGLuint GrGLNameAllocator::allocateName() { if (nullptr == fAllocatedNames.get()) { fAllocatedNames.reset(new ContiguousNameRange(fFirstName, fFirstName + 1)); return fFirstName; } if (fAllocatedNames->first() > fFirstName) { return fAllocatedNames->prependNames(1); } GrGLuint name; fAllocatedNames.reset(fAllocatedNames->internalAllocate(&name)); if (0 != name) { return name; } if (fAllocatedNames->end() < fEndName) { return fAllocatedNames->appendNames(1); } // Out of names. return 0; } void GrGLNameAllocator::free(GrGLuint name) { if (!fAllocatedNames.get()) { // Not-allocated names are silently ignored. return; } fAllocatedNames.reset(fAllocatedNames->free(name)); }
34.641509
109
0.625506
Perspex
0315b9a79c66e94e3b82f15fc90e4e3758bfaefd
2,112
cpp
C++
C++17TemplateFeatures/folding_basics.cpp
rostislav-nikitin/edu.cpp
3cbb87b32042cc24ebfc9937927ba86ca24a92aa
[ "MIT" ]
null
null
null
C++17TemplateFeatures/folding_basics.cpp
rostislav-nikitin/edu.cpp
3cbb87b32042cc24ebfc9937927ba86ca24a92aa
[ "MIT" ]
null
null
null
C++17TemplateFeatures/folding_basics.cpp
rostislav-nikitin/edu.cpp
3cbb87b32042cc24ebfc9937927ba86ca24a92aa
[ "MIT" ]
null
null
null
// Single-line comment /* * Multiple line comment */ #include <iostream> #include <sstream> using namespace std; // Variadic tempalte auto sum() { return 0; } template<typename T, typename...Args> auto sum(T current, Args ...args) { return current + sum(args...); } //C++17 fold expressions //Unary template <typename...Args> auto sum_unary_right(Args ...args) { return (args + ...); } template <typename...Args> auto sum_unary_left(Args ...args) { return (... + args); } template <typename...Args> auto sum_binary_right(Args ...args) { return (args + ... + 0); } template <typename...Args> auto sum_binary_left(Args ...args) { return (0 + ... + args); } /* * Fold expressions operators: * + - * / % ^ & | = < > << >> += - * = *= /= %= ^= &= |= <<= >>= == != <= >= && || , .* ->* */ /* If empty args pack list f(): * && - true * || - false * , - void * Other ill-formed */ // Unary: template<typename...Args> bool EvenAnyOf(Args ...args) { return (... || (args % 2 == 0)); } template<typename...Args> bool EvenAllOf(Args ...args) { return (... && (args % 2 == 0)); } template<typename Predicate, typename ...Args> bool AnyOf(Predicate p, Args ...args) { return (... || p(args)); } template<typename ...Args> cpp_printf(Args...args) { return (... << (out << args)); } int main() { cout << sum(1, 2, 3, 4, 5) << endl; cout << sum_unary_right(1, 2, 3, 4, 5) << endl; cout << sum_unary_left(1, 2, 3, 4, 5) << endl; // Error: //cout << sum_unary_left() << endl; cout << sum_binary_right() << endl; cout << sum_binary_left(1, 2, 3, 4) << endl; // Even: cout << "Event any of: " << boolalpha << EvenAnyOf(1, 5, 7) << endl; cout << "Event any of: " << boolalpha << EvenAnyOf(1, 5, 8) << endl; cout << "Event all of: " << boolalpha << EvenAllOf(1, 5, 8) << endl; cout << "Event all of: " << boolalpha << EvenAllOf(2, 4, 8) << endl; // Predicate: cout << "Any of: " << AnyOf([](int x){ return x % 2 == 0; }, 1, 1, 3) << endl; std::ostringstream out {}; cpp_printf(out, "Hello {0} {1}\n", "Rostislav", "Nikitin"); return 0; }
18.526316
79
0.552557
rostislav-nikitin
031b13288a44c73b9bb85d08c2c8372ed60e2bc4
2,259
cpp
C++
database/moviemodel.cpp
softmarch/learnqml
9aded6804e74f8f5383ab577437bc5c9dc4a0d56
[ "MIT" ]
3
2020-09-25T09:32:01.000Z
2021-07-10T05:17:39.000Z
database/moviemodel.cpp
heafox/learnqml
37f9d7a22dad03c0bb4b7bb036a4638a9a9e4354
[ "MIT" ]
null
null
null
database/moviemodel.cpp
heafox/learnqml
37f9d7a22dad03c0bb4b7bb036a4638a9a9e4354
[ "MIT" ]
5
2020-09-24T05:27:12.000Z
2022-02-22T17:44:29.000Z
#include "moviemodel.h" #include <QSqlQuery> #include <QVariant> MovieModel::MovieModel(QObject *parent) : QObject(parent) { } void MovieModel::create() { QSqlQuery q; q.exec("drop table Movies"); q.exec("drop table Names"); q.exec("create table Movies (id integer primary key, Title varchar, Director varchar, Rating number)"); insert(0, "Metropolis", "Fritz Lang", 8.4); insert(1, "Nosferatu, eine Symphonie des Grauens", "F.W. Murnau", 8.1); insert(2, "Bis ans Ende der Welt", "Wim Wenders", 6.5); insert(3, "Hardware", "Richard Stanley", 5.2); insert(4, "Mitchell", "Andrew V. McLaglen", 2.1); } bool MovieModel::insert(int id, const QString &title, const QString &director, double rating) { QSqlQuery q; q.prepare("insert into Movies values (?, ?, ?, ?)"); q.bindValue(0, id); q.bindValue(1, title); q.bindValue(2, director); q.bindValue(3, rating); return q.exec(); } QJsonArray MovieModel::get() { QSqlQuery q; // SELECT 列名称 FROM 表名称 q.prepare("select * from Movies"); QJsonArray array; if (!q.exec()) return array; while (q.next()) { QJsonObject o; o["id"] = q.value(0).toInt(); o["title"] = q.value(1).toString(); o["director"] = q.value(2).toString(); o["rating"] = q.value(3).toDouble(); array.append(o); } return array; } QJsonObject MovieModel::get(int id) { QSqlQuery q; q.prepare("select * from Movies where id = ?"); q.bindValue(0, id); QJsonObject o; if (!q.exec()) return o; while (q.next()) { o["id"] = q.value(0).toInt(); o["title"] = q.value(1).toString(); o["director"] = q.value(2).toString(); o["rating"] = q.value(3).toDouble(); } return o; } bool MovieModel::remove(int id) { QSqlQuery q; // DELETE FROM 表名称 WHERE 列名称 = 值 q.prepare("delete from Movies where id = ?"); q.bindValue(0, id); return q.exec(); } bool MovieModel::updateTitle(int id, const QString &title) { QSqlQuery q; // UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值 q.prepare("UPDATE Movies SET Title = ? where id = ?"); q.bindValue(0, title); q.bindValue(1, id); return q.exec(); }
22.147059
107
0.585215
softmarch
0320601242ad93efda44e5ebcbaee0ab884cf04e
1,447
cc
C++
Sandbox/src/MakeTestInputFile_module.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
9
2020-03-28T00:21:41.000Z
2021-12-09T20:53:26.000Z
Sandbox/src/MakeTestInputFile_module.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
684
2019-08-28T23:37:43.000Z
2022-03-31T22:47:45.000Z
Sandbox/src/MakeTestInputFile_module.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
61
2019-08-16T23:28:08.000Z
2021-12-20T08:29:48.000Z
// // Write a text file that can be used as input for the Source00 module. // // Original author Rob Kutschke // // The format of the file is one event per line: // runNumber subRunNumber eventNumber dataProduct // // where dataProduct is a trivial data product: it is a single // integer whose value is: // // 10000*runNumber + 100*subRunNumber + eventNumber // // Framework includes. #include "art/Framework/Core/EDAnalyzer.h" #include "art/Framework/Core/ModuleMacros.h" #include "art/Framework/Principal/Event.h" #include "art/Framework/Principal/SubRun.h" #include <iostream> #include <fstream> using namespace std; namespace mu2e { class MakeTestInputFile : public art::EDAnalyzer { public: explicit MakeTestInputFile(fhicl::ParameterSet const& pset); void analyze ( art::Event const& event) override; private: ofstream ofile_; }; MakeTestInputFile::MakeTestInputFile(fhicl::ParameterSet const& pset): EDAnalyzer(pset), ofile_( pset.get<std::string>("filename")){ } void MakeTestInputFile::analyze(art::Event const& event) { double dataProduct = 10000*event.id().run() + 100*event.id().subRun() + event.id().event(); ofile_ << event.id().run() << " " << event.id().subRun() << " " << event.id().event() << " " << dataProduct << endl; } } // end namespace mu2e using mu2e::MakeTestInputFile; DEFINE_ART_MODULE(MakeTestInputFile)
24.525424
95
0.67519
bonventre
032be2b0115cffea95fc220954cdd2f0b383a2ca
11,175
cpp
C++
src/Recording.cpp
JanitzaElectronics/umg801-recordings
39b39bcbe9dfcf1e7c5b31726951e5d00f2ba63a
[ "MIT" ]
null
null
null
src/Recording.cpp
JanitzaElectronics/umg801-recordings
39b39bcbe9dfcf1e7c5b31726951e5d00f2ba63a
[ "MIT" ]
null
null
null
src/Recording.cpp
JanitzaElectronics/umg801-recordings
39b39bcbe9dfcf1e7c5b31726951e5d00f2ba63a
[ "MIT" ]
null
null
null
/* * Recording.cpp * * Created on: 06.09.2021 * Copyright: 2021 by Janitza electronics GmbH */ #include "Recording.hpp" #include "Umg801.hpp" #include <iostream> #include <iomanip> #include <chrono> #include <ctime> Recording::Recording(Umg801& client, const uint32_t& id, const NodeId& nodeId) : m_client(client), m_id(id), m_nodeId(nodeId), m_dataId(), m_getRangeId(), m_countByRangeId(), m_readByStartAndCountIdId(), m_configIds() {} UA_StatusCode Recording::getNodeIds() { auto recordChilds = m_client.getHierarichalNodes(m_nodeId); m_dataId = recordChilds["Data"]; if(m_dataId.isNull()) { std::cerr << "NodeId of Node 'Data' of Recording"<<m_id<<" not found!" << std::endl; return UA_STATUSCODE_BADINTERNALERROR; } for(const auto c : recordChilds) { if(OpcUaUtil::isPrefix(c.first,"RecordingConfiguration")) { m_configIds.emplace(OpcUaUtil::getIdSuffix(c.first),c.second); } } m_getRangeId = m_client.browsePathToNodeId(NodeId(0,UA_NS0ID_BASEOBJECTTYPE), {{2,"RecordingType", UA_NS0ID_HASSUBTYPE}, {2,"Data", UA_NS0ID_HASCOMPONENT}, {2,"GetRange", UA_NS0ID_HASCOMPONENT}}); if(m_getRangeId.isNull()) { std::cerr << "Node BaseObjectType/RecordingType/Data/GetRange not found!" << std::endl; return UA_STATUSCODE_BADINTERNALERROR; } m_countByRangeId = m_client.browsePathToNodeId(NodeId(0,UA_NS0ID_BASEOBJECTTYPE), {{2,"RecordingType", UA_NS0ID_HASSUBTYPE}, {2,"Data", UA_NS0ID_HASCOMPONENT}, {2,"CountByRange", UA_NS0ID_HASCOMPONENT}}); if(m_countByRangeId.isNull()) { std::cerr << "Node BaseObjectType/RecordingType/Data/CountByRange not found!" << std::endl; return UA_STATUSCODE_BADINTERNALERROR; } m_readByStartAndCountIdId = m_client.browsePathToNodeId(NodeId(0, UA_NS0ID_BASEOBJECTTYPE), {{2,"RecordingType", UA_NS0ID_HASSUBTYPE}, {2,"Data", UA_NS0ID_HASCOMPONENT}, {2,"ReadByStartAndCount", UA_NS0ID_HASCOMPONENT}}); if(m_readByStartAndCountIdId.isNull()) { std::cerr << "Node BaseObjectType/RecordingType/Data/ReadByStartAndCount not found!" << std::endl; return UA_STATUSCODE_BADINTERNALERROR; } return UA_STATUSCODE_GOOD; } uint32_t Recording::getId() const { return m_id; } UA_StatusCode Recording::getRange(UA_DateTime& startTime, UA_DateTime& endTime) const { UA_StatusCode retval = UA_STATUSCODE_GOOD; size_t outputSize; UA_Variant *output; retval = m_client.clientCall(m_dataId, m_getRangeId, 0, nullptr, &outputSize, &output); if(retval != UA_STATUSCODE_GOOD) { std::cerr << "Method call to GetRange of Recording"<<m_id<<" was unsuccessful: " << UA_StatusCode_name(retval) << std::endl; } else { startTime = *(UA_DateTime*)output[0].data; endTime = *(UA_DateTime*)output[1].data; UA_Array_delete(output, outputSize, &UA_TYPES[UA_TYPES_VARIANT]); } return retval; } int Recording::countByRange(const UA_DateTime& startTime, const UA_DateTime& endTime) const { int retval = 0; UA_StatusCode status = UA_STATUSCODE_GOOD; UA_Variant input[2] = {0}; size_t outputSize; UA_Variant *output; UA_Variant_setScalarCopy(&input[0], &startTime, &UA_TYPES[UA_TYPES_DATETIME]); UA_Variant_setScalarCopy(&input[1], &endTime, &UA_TYPES[UA_TYPES_DATETIME]); status = m_client.clientCall(m_dataId, m_countByRangeId, 2, input, &outputSize, &output); if(status != UA_STATUSCODE_GOOD) { std::cerr << "Method call to CountByRange of Recording"<<m_id<<" was unsuccessful: " << UA_StatusCode_name(status) << std::endl; retval = -1; } else { retval = *(UA_UInt32*)output[0].data; UA_Array_delete(output, outputSize, &UA_TYPES[UA_TYPES_VARIANT]); } return retval; } UA_StatusCode Recording::readByStartAndCount(const UA_DateTime& startTime, const uint32_t& count) const { UA_StatusCode retval = UA_STATUSCODE_GOOD; int remian = count; UA_DateTime nextStartTime = startTime; std::list<std::pair<uint32_t, records::RecordedData>> data; while(remian > 0) { UA_Variant input[2] = {0}; size_t outputSize; UA_Variant *output; UA_Variant_setScalarCopy(&input[0], &nextStartTime, &UA_TYPES[UA_TYPES_DATETIME]); UA_Variant_setScalarCopy(&input[1], &count, &UA_TYPES[UA_TYPES_UINT32]); retval = m_client.clientCall(m_dataId, m_readByStartAndCountIdId, 2, input, &outputSize, &output); for(auto& inp : input) { UA_Variant_clear(&inp); } if(retval != UA_STATUSCODE_GOOD) { std::cerr << "Method call 'ReadByStartAndCount' was unsuccessful " << UA_StatusCode_name(retval) << std::endl; break; } else { if(nextStartTime >= *(UA_DateTime*)output[1].data) { std::cerr << "Warning: Read LastDateTime is not bigger than start-time from last read! Stopping here!"; remian = 0; } nextStartTime = *(UA_DateTime*)output[1].data; const size_t recordingPoints = output[2].arrayDimensions[0]; UA_RecordingPoint* p = (UA_RecordingPoint*)output[2].data; for(size_t i=0; i<recordingPoints; i++) { UA_ByteString* b = &(p[i].data); /* The received Data is stored in a google protobuf structure. * Parse the received Byte-String as protobuf here! */ records::RecordedData protobuf; if(!protobuf.ParseFromArray(b->data, b->length)) { std::cerr << "Failed to decode protobuffer of Recording-Point " << i << "(Recording" << m_id << ")" << std::endl; } else { data.emplace_back(p[i].configId, protobuf); } } UA_Array_delete(output, outputSize, &UA_TYPES[UA_TYPES_VARIANT]); if(recordingPoints == 0) { std::cerr << "Warning: no recording points returned while expecting " << remian << " more points! Stopping here!" << std::endl; remian = 0; } remian -= recordingPoints; } } retval = decodeData(data); return retval; } template<typename T> void Recording::printProtobuf(RecordingConfiguration& cfg, const T& protobuf, size_t& index, const std::string& browsename) const { std::cout << "\"" << browsename << "\" : { "; if(cfg.algorithm == UA_RECORDINGALGORITHM_AVERAGE) { std::cout << "\"avg\" : " << protobuf.avgvalue(index) << " "; } else { std::cout << "\"sample\" : " << protobuf.sample(index) << " "; } if(cfg.extremals.minimum) { std::cout << ", \"min\" : " << protobuf.minvalue(index) << " "; if(cfg.extremals.timestamps) { std::cout << ", \"min_time\" : " << protobuf.mintimestamp(index) << " "; } } if(cfg.extremals.maximum) { std::cout << ", \"max\" : " << protobuf.maxvalue(index) << " "; if(cfg.extremals.timestamps) { std::cout << ", \"max_time\" : " << protobuf.maxtimestamp(index) << " "; } } std::cout << " }, " << std::endl; /* Here we increment the index of the specific type-array in the protobuffer, * so the next call will fetch the next element. */ index++; } UA_StatusCode Recording::decodeData(std::list<std::pair<uint32_t, records::RecordedData>>& data) const { UA_StatusCode retval = UA_STATUSCODE_GOOD; std::map<uint32_t, RecordingConfiguration> configs; for(const auto& d : data) { // Get RecordingConfiguration from configs. Read from device if not known yet. auto it = configs.find(d.first); if(it == configs.end()) { RecordingConfiguration cfg; retval = readRecordingConfiguration(d.first, cfg); if(retval != UA_STATUSCODE_GOOD) { return retval; } it = configs.emplace(d.first, cfg).first; } RecordingConfiguration& cfg = it->second; // Convert and print timestamp. Protobuffer holds time in Seconds UTC (POSIX time) std::time_t time = d.second.starttimeutc(); std::cout << "{ \"time\" : \"" << std::put_time(std::localtime(&time), "%Y-%m-%d %X") << "\"" << std::endl; size_t counts[8] = {0}; /* The protobuffer holds arrays for each possible datatype that can be stored. * Depending of the configuration, the values are stored to the type-belonging arrays * in the same order as in configuration. To match values, we iterate throught the values in * configuration and fetch the next value from the array of the protobuffer. */ for(const auto& var : cfg.values) { if(var.info.status != UA_REFERENCESTATUS_AVAILABLE) { // ignore values that are not available. counts[var.info.typeInfo.dataType]++; continue; } std::string name = var.browsePath; if(var.info.typeInfo.array) { name += "[" + std::to_string(var.info.value.arrayIndex) + "]"; } switch(var.info.typeInfo.dataType) { case UA_RecordingDataType::UA_RECORDINGDATATYPE_BOOLEAN: printProtobuf(cfg, d.second.bool_(), counts[var.info.typeInfo.dataType], name); break; case UA_RecordingDataType::UA_RECORDINGDATATYPE_INT32: printProtobuf(cfg, d.second.sint32(), counts[var.info.typeInfo.dataType], name); break; case UA_RecordingDataType::UA_RECORDINGDATATYPE_UINT32: printProtobuf(cfg, d.second.uint32(), counts[var.info.typeInfo.dataType], name); break; case UA_RecordingDataType::UA_RECORDINGDATATYPE_INT64: printProtobuf(cfg, d.second.sint64(), counts[var.info.typeInfo.dataType], name); break; case UA_RecordingDataType::UA_RECORDINGDATATYPE_UINT64: printProtobuf(cfg, d.second.uint64(), counts[var.info.typeInfo.dataType], name); break; case UA_RecordingDataType::UA_RECORDINGDATATYPE_FLOAT: printProtobuf(cfg, d.second.float_(), counts[var.info.typeInfo.dataType], name); break; case UA_RecordingDataType::UA_RECORDINGDATATYPE_DOUBLE: printProtobuf(cfg, d.second.double_(), counts[var.info.typeInfo.dataType], name); break; case UA_RecordingDataType::UA_RECORDINGDATATYPE_UNDEFINED: default: std::cerr << "Found UNDEFINED datatype; this should _not_ happen!"; } } std::cout << "}," << std::endl; } return retval; } UA_StatusCode Recording::readRecordingConfiguration(const uint32_t& id, RecordingConfiguration& cfg) const { UA_StatusCode retval = UA_STATUSCODE_GOOD; const auto cfgIter = m_configIds.find(id); if(cfgIter == m_configIds.end()) { std::cerr << "Failed to get " << "RecordingConfiguration"+std::to_string(id) << " from node " << m_nodeId.toString() <<": NodeId not found!"<< std::endl; return UA_STATUSCODE_BADNOTFOUND; } auto nodes = m_client.getHierarichalNodes(cfgIter->second); cfg.id = id; cfg.algorithm = m_client.getVariantValue<UA_RecordingAlgorithm>(nodes["Algorithm"]); cfg.extremals = m_client.getVariantValue<UA_RecordingExtremals>(nodes["Extremals"]); cfg.interval_seconds = m_client.getVariantValue<UA_UInt32>(nodes["Interval"]); for(const auto& v : m_client.getVariantArrayValue<UA_RecordingValueInfo>(nodes["Values"])) { std::string browsepath = ""; if(v.status == UA_REFERENCESTATUS_AVAILABLE) { auto p = m_client.lookup(NodeId(v.value.node), UA_TAG_RECORDABLE); if(p) { browsepath = *p; } } cfg.values.emplace_back(RecordingValueInfo(v, browsepath)); } // Print configuration information std::cout << "RecordingConfig" << cfg.id << ": Algorithm="; if(cfg.algorithm == UA_RECORDINGALGORITHM_SAMPLE) std::cout << "Sample; Extremals:"; else std::cout << "Average; Extremals:"; if(cfg.extremals.maximum) std::cout << "max,"; if(cfg.extremals.minimum) std::cout << "min,"; if(cfg.extremals.timestamps) std::cout << "timestmaps"; std::cout << "; Interval=" << cfg.interval_seconds << "sec "; std::cout << "; Value-Count=" << cfg.values.size() << std::endl; return retval; }
38.270548
155
0.708993
JanitzaElectronics
033491cc97254a0ce5e5e614a7138c018d9fd099
12,229
cpp
C++
src/db/db_bookshelf.cpp
cuhk-eda/ripple-fpga
059646fcaa0c8d77e4283f55be2bd5692862a039
[ "Unlicense" ]
60
2019-05-15T13:21:40.000Z
2021-12-11T14:38:56.000Z
src/db/db_bookshelf.cpp
jordanpui/ripplefpga
059646fcaa0c8d77e4283f55be2bd5692862a039
[ "Unlicense" ]
3
2020-05-31T13:14:05.000Z
2021-12-11T14:27:59.000Z
src/db/db_bookshelf.cpp
cuhk-eda/ripple-fpga
059646fcaa0c8d77e4283f55be2bd5692862a039
[ "Unlicense" ]
16
2019-06-07T14:56:34.000Z
2022-03-29T20:22:38.000Z
#include "db.h" using namespace db; bool read_line_as_tokens(istream &is, vector<string> &tokens) { tokens.clear(); string line; getline(is, line); while (is && tokens.empty()) { string token = ""; for (unsigned i=0; i<line.size(); ++i) { char currChar = line[i]; if (isspace(currChar)) { if (!token.empty()) { // Add the current token to the list of tokens tokens.push_back(token); token.clear(); } }else{ // Add the char to the current token token.push_back(currChar); } } if(!token.empty()){ tokens.push_back(token); } if(tokens.empty()){ // Previous line read was empty. Read the next one. getline(is, line); } } return !tokens.empty(); } bool Database::readAux(string file){ string directory; size_t found=file.find_last_of("/\\"); if (found==file.npos) { directory="./"; }else{ directory=file.substr(0,found); directory+="/"; } ifstream fs(file); if (!fs.good()){ printlog(LOG_ERROR, "Cannot open %s to read", file.c_str()); return false; } string buffer; while (fs>>buffer) { if (buffer=="#") { //ignore comments fs.ignore(std::numeric_limits<streamsize>::max(), '\n'); continue; } size_t dot_pos = buffer.find_last_of("."); if ( dot_pos == string::npos) { //ignore words without "dot" continue; } string ext=buffer.substr(dot_pos); if (ext==".nodes") { setting.io_nodes = directory+buffer; }else if (ext==".nets") { setting.io_nets = directory+buffer; }else if (ext==".pl") { setting.io_pl = directory+buffer; }else if (ext==".wts") { setting.io_wts = directory+buffer; }else if (ext==".scl") { setting.io_scl = directory+buffer; }else if(ext==".lib"){ setting.io_lib = directory+buffer; }else { continue; } } printlog(LOG_VERBOSE, "nodes = %s", setting.io_nodes.c_str()); printlog(LOG_VERBOSE, "nets = %s", setting.io_nets.c_str()); printlog(LOG_VERBOSE, "pl = %s", setting.io_pl.c_str()); printlog(LOG_VERBOSE, "wts = %s", setting.io_wts.c_str()); printlog(LOG_VERBOSE, "scl = %s", setting.io_scl.c_str()); printlog(LOG_VERBOSE, "lib = %s", setting.io_lib.c_str()); fs.close(); return true; } bool Database::readNodes(string file){ ifstream fs(file); if (!fs.good()) { cerr<<"Read nodes file: "<<file<<" fail"<<endl; return false; } vector<string> tokens; while(read_line_as_tokens(fs, tokens)){ Instance *instance = database.getInstance(tokens[0]); if(instance != NULL){ printlog(LOG_ERROR, "Instance duplicated: %s", tokens[0].c_str()); }else{ Master *master = database.getMaster(Master::NameString2Enum(tokens[1])); if(master == NULL){ printlog(LOG_ERROR, "Master not found: %s", tokens[1].c_str()); }else{ Instance newinstance(tokens[0], master); instance = database.addInstance(newinstance); } } } fs.close(); return true; } bool Database::readNets(string file){ ifstream fs(file); if (!fs.good()) { cerr<<"Read net file: "<<file<<" fail"<<endl; return false; } vector<string> tokens; Net *net = NULL; while(read_line_as_tokens(fs, tokens)){ if(tokens[0][0] == '#'){ continue; } if(tokens[0] == "net"){ net = database.getNet(tokens[1]); if(net != NULL){ printlog(LOG_ERROR, "Net duplicated: %s", tokens[1].c_str()); }else{ Net newnet(tokens[1]); net = database.addNet(newnet); } }else if(tokens[0] == "endnet"){ net = NULL; }else{ Instance *instance = database.getInstance(tokens[0].c_str()); Pin *pin = NULL; if(instance != NULL){ pin = instance->getPin(tokens[1]); }else{ printlog(LOG_ERROR, "Instance not found: %s", tokens[0].c_str()); } if(pin == NULL){ printlog(LOG_ERROR, "Pin not found: %s", tokens[1].c_str()); }else{ net->addPin(pin); if (pin->type->type=='o' && pin->instance->master->name==Master::BUFGCE){ net->isClk=true; } } } } fs.close(); return false; } bool Database::readPl(string file){ ifstream fs(file); if (!fs.good()) { cerr<<"Read pl file: "<<file<<" fail"<<endl; return false; } vector<string> tokens; while(read_line_as_tokens(fs, tokens)){ Instance *instance = database.getInstance(tokens[0]); if(instance == NULL){ printlog(LOG_ERROR, "Instance not found: %s", tokens[0].c_str()); continue; } int x = atoi(tokens[1].c_str()); int y = atoi(tokens[2].c_str()); int slot = atoi(tokens[3].c_str()); instance->inputFixed = (tokens.size() >= 5 && tokens[4] == "FIXED"); instance->fixed = instance->inputFixed; if(instance->IsFF()) slot += 16; else if(instance->IsCARRY()) slot += 32; place(instance, x, y, slot); } fs.close(); return true; } bool Database::readScl(string file){ ifstream fs(file); if (!fs.good()) { printlog(LOG_ERROR, "Cannot open %s to read", file.c_str()); return false; } vector<string> tokens; while(read_line_as_tokens(fs, tokens)){ if(tokens[0] == "SITE"){ SiteType *sitetype = database.getSiteType(SiteType::NameString2Enum(tokens[1])); if(sitetype == NULL){ SiteType newsitetype(SiteType::NameString2Enum(tokens[1])); sitetype = database.addSiteType(newsitetype); }else{ printlog(LOG_WARN, "Duplicated site type: %s", sitetype->name); } while(read_line_as_tokens(fs, tokens)){ if(tokens[0] == "END" && tokens[1] == "SITE"){ break; } Resource *resource = database.getResource(Resource::NameString2Enum(tokens[0])); if(resource == NULL){ Resource newresource(Resource::NameString2Enum(tokens[0])); resource = database.addResource(newresource); } sitetype->addResource(resource, atoi(tokens[1].c_str())); } } if(tokens[0] == "RESOURCES"){ while(read_line_as_tokens(fs, tokens)){ if(tokens[0] == "END" && tokens[1] == "RESOURCES"){ break; } Resource *resource = database.getResource(Resource::NameString2Enum(tokens[0])); if(resource == NULL){ Resource newresource(Resource::NameString2Enum(tokens[0])); resource = database.addResource(newresource); } for(int i=1; i<(int)tokens.size(); i++){ Master *master = database.getMaster(Master::NameString2Enum(tokens[i])); if(master == NULL){ printlog(LOG_ERROR, "Master not found: %s", tokens[i].c_str()); }else{ resource->addMaster(master); } } } } if(tokens[0] == "SITEMAP"){ int nx = atoi(tokens[1].c_str()); int ny = atoi(tokens[2].c_str()); database.setSiteMap(nx, ny); database.setSwitchBoxes(nx/2-1, ny); while(read_line_as_tokens(fs, tokens)){ if(tokens[0] == "END" && tokens[1] == "SITEMAP"){ break; } int x = atoi(tokens[0].c_str()); int y = atoi(tokens[1].c_str()); SiteType *sitetype = database.getSiteType(SiteType::NameString2Enum(tokens[2])); if(sitetype == NULL){ printlog(LOG_ERROR, "Site type not found: %s", tokens[2].c_str()); }else{ database.addSite(x, y, sitetype); } } } if(tokens[0] == "CLOCKREGIONS"){ int nx = atoi(tokens[1].c_str()); int ny = atoi(tokens[2].c_str()); crmap_nx = nx; crmap_ny = ny; clkrgns.assign(nx, vector<ClkRgn*>(ny, NULL)); hfcols.assign(sitemap_nx,vector<HfCol*>(2*ny,NULL)); for (int x=0; x<nx; x++){ for (int y=0; y<ny; y++){ read_line_as_tokens(fs, tokens); string name = tokens[0]+tokens[1]; int lx = atoi(tokens[3].c_str()); int ly = atoi(tokens[4].c_str()); int hx = atoi(tokens[5].c_str()); int hy = atoi(tokens[6].c_str()); clkrgns[x][y]=new ClkRgn(name, lx, ly, hx, hy, x, y); } } } } fs.close(); return true; } bool Database::readLib(string file){ ifstream fs(file); if (!fs.good()) { printlog(LOG_ERROR, "Cannot open %s to read", file.c_str()); return false; } vector<string> tokens; Master *master = NULL; while(read_line_as_tokens(fs, tokens)){ if (tokens[0]=="CELL") { master = database.getMaster(Master::NameString2Enum(tokens[1])); if(master == NULL){ Master newmaster(Master::NameString2Enum(tokens[1])); master = database.addMaster(newmaster); }else{ printlog(LOG_WARN, "Duplicated master: %s", tokens[1].c_str()); } } else if (tokens[0]=="PIN") { char type = 'x'; if(tokens.size() >= 4){ if(tokens[3] == "CLOCK"){ type = 'c'; }else if(tokens[3] == "CTRL"){ type = 'e'; } }else if(tokens.size() >= 3){ if(tokens[2] == "OUTPUT"){ type = 'o'; }else if(tokens[2] == "INPUT"){ type = 'i'; } } PinType pintype(tokens[1], type); if(master != NULL){ master->addPin(pintype); } } else if (tokens[0]=="END") { } } fs.close(); return true; } bool Database::readWts(string file){ return false; } bool Database::writePl(string file){ ofstream fs(file); if(!fs.good()){ printlog(LOG_ERROR, "Cannot open %s to write", file.c_str()); return false; } vector<Instance*>::iterator ii = database.instances.begin(); vector<Instance*>::iterator ie = database.instances.end(); int nErrorLimit = 10; for(; ii!=ie; ++ii){ Instance *instance = *ii; if(instance->pack == NULL || instance->pack->site == NULL){ if(nErrorLimit > 0){ printlog(LOG_ERROR, "Instance not placed: %s", instance->name.c_str()); nErrorLimit--; }else if(nErrorLimit == 0){ printlog(LOG_ERROR, "(Remaining same errors are not shown)"); nErrorLimit--; } continue; } Site *site = instance->pack->site; int slot = instance->slot; if(instance->IsFF()) slot -= 16; else if(instance->IsCARRY()) slot -= 32; fs<<instance->name<<" "<<site->x<<" "<<site->y<<" "<<slot; if(instance->inputFixed) fs<<" FIXED"; fs<<endl; } return true; }
32.962264
96
0.485567
cuhk-eda
0335ed4041cad29100751e37044a798e3b592f78
8,910
cpp
C++
Beta 3 casi final/gestionarowner.cpp
roiso/unisys
f23f66ccb426a8127ebe79479953c7b4367121d8
[ "MIT" ]
null
null
null
Beta 3 casi final/gestionarowner.cpp
roiso/unisys
f23f66ccb426a8127ebe79479953c7b4367121d8
[ "MIT" ]
null
null
null
Beta 3 casi final/gestionarowner.cpp
roiso/unisys
f23f66ccb426a8127ebe79479953c7b4367121d8
[ "MIT" ]
null
null
null
#include "gestionarowner.h" #include "ui_gestionarowner.h" #include <qmessagebox.h> #include <QDebug> //Guillermo gestionarOwner::gestionarOwner(QWidget *parent) : QDialog(parent), ui(new Ui::gestionarOwner){ ui->setupUi(this); } gestionarOwner::~gestionarOwner() { compania v2; v2.setController(*controller_); v2.exec(); delete ui; } void gestionarOwner::setController (MainController &controller){ controller_=&controller; this->inicial(); } void gestionarOwner::inicial(){ this->showOwner(); ui->editOwner->setEnabled(false); ui->btnAcpetar->setEnabled(false); ui->btnCancelar->setEnabled(false); ui->btnModificar->setEnabled(false); ui->btnBorrar->setEnabled(false); ui->btnNuevo->setEnabled(true); ui->tableOwner->setEnabled(true); } void gestionarOwner::limpiarLabel(){ ui->txtOwner->clear(); ui->txtRazon->clear(); ui->txtTlfn->clear(); ui->txtNIF->clear(); ui->txtPoblacion->clear(); ui->txtProvincia->clear(); ui->txtCP->clear(); ui->txtPais->clear(); ui->txtDireccion->clear(); ui->plaintxtObservaciones->clear(); } void gestionarOwner::showOwner(){ rellenarTabla(controller_->getOwners(), ui->tableOwner, &criterio); } void gestionarOwner::showLabel(){ QString ID = ui->tableOwner->item(ui->tableOwner->currentRow(),4)->text(); int seleccionado = ID.toInt(); encontrarID(controller_->getOwners(), &seleccionado); ui->txtOwner->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).owner())); ui->txtRazon->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).razon())); ui->txtTlfn->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).tlfn())); ui->txtNIF->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).NIF())); ui->txtPoblacion->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).poblacion())); ui->txtProvincia->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).provincia())); ui->txtCP->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).CP())); ui->txtPais->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).pais())); ui->txtDireccion->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).direccion())); ui->plaintxtObservaciones->setPlainText(QString::fromStdString(controller_->getOwners().at(seleccionado).observaciones())); ui->btnModificar->setEnabled(true); ui->btnBorrar->setEnabled(true); } void gestionarOwner::nuevo(){ opcion=1; ui->editOwner->setEnabled(true); ui->tableOwner->clearSelection(); ui->tableOwner->setEnabled(false); ui->btnModificar->setEnabled(false); ui->btnBorrar->setEnabled(false); ui->btnAcpetar->setEnabled(true); ui->btnCancelar->setEnabled(true); ui->btnNuevo->setEnabled(false); this->limpiarLabel(); ui->txtOwner->setFocus(); } void gestionarOwner::modificar(){ QModelIndexList selectedList = ui->tableOwner->selectionModel()->selectedRows(); if (!selectedList.empty()){ opcion=2; ui->editOwner->setEnabled(true); ui->tableOwner->setEnabled(false); ui->txtOwner->setFocus(); ui->btnAcpetar->setEnabled(true); ui->btnCancelar->setEnabled(true); ui->btnModificar->setEnabled(false); ui->btnBorrar->setEnabled(false); ui->btnNuevo->setEnabled(false); } } void gestionarOwner::borrar(){ QString ID = ui->tableOwner->item(ui->tableOwner->currentRow(),4)->text(); int seleccionado = ID.toInt(); encontrarID(controller_->getNegos(), &seleccionado); ui->editOwner->setEnabled(false); ui->tableOwner->setEnabled(false); ui->btnAcpetar->setEnabled(false); ui->btnCancelar->setEnabled(false); ui->btnModificar->setEnabled(false); ui->btnBorrar->setEnabled(false); ui->btnNuevo->setEnabled(false); QMessageBox::StandardButton btnBorrar; btnBorrar = QMessageBox::question(this, "", "Está seguro que desea eliminar el Owner: " + QString::fromStdString(controller_->getOwners().at(seleccionado).owner()), QMessageBox::Yes | QMessageBox:: No); if(btnBorrar == QMessageBox::Yes){ c_owner copyBorrar = controller_->getOwners().at(seleccionado); copyBorrar.setBorrado(true); controller_->modificarOwner(seleccionado, copyBorrar); for (size_t i=0; i<controller_->getUsers().count(); i++){ if(controller_->getUsers().at(i).ID_owner()==ID.toInt()){ c_user copyUser = controller_->getUsers().at(i); copyUser.setBorrado(true); controller_->modificarUser(i,copyUser); } } for(size_t i=0; i<controller_->getOficinas().count(); i++){ if(controller_->getOficinas().at(i).ID_owner()==ID.toInt()){ c_oficina copyOficina = controller_->getOficinas().at(i); copyOficina.setBorrado(true); controller_->modificarOficina(i, copyOficina); } } for(size_t i=0; i<controller_->getNegos().count(); i++){ if(controller_->getNegos().at(i).ID_owner()==ID.toInt()){ c_nego copyNego = controller_->getNegos().at(i); copyNego.setBorrado(true); controller_->modificarNego(i, copyNego); } } this->inicial(); this->limpiarLabel(); }else if(btnBorrar == QMessageBox::No){ this->inicial(); this->limpiarLabel(); } } void gestionarOwner::aceptar(){ switch (opcion) { case 1:{ if(ui->txtOwner->text().isEmpty() || ui->txtRazon->text().isEmpty() || ui->txtCP->text().isEmpty() || ui->txtDireccion->text().isEmpty() || ui->txtNIF->text().isEmpty() || ui->txtPais->text().isEmpty() || ui->txtPoblacion->text().isEmpty() || ui->txtProvincia->text().isEmpty() || ui->txtTlfn->text().isEmpty()){ QMessageBox::information(this, "", "Debe rellenar todos los campos"); }else{ c_owner nuevo; controller_->setUltimoIDowners(); nuevo.setID(controller_->getUltimoIDowners()); nuevo.setBorrado(false); nuevo.setOwner(ui->txtOwner->text().toStdString()); nuevo.setRazon(ui->txtRazon->text().toStdString()); nuevo.setNIF(ui->txtNIF->text().toStdString()); nuevo.setTlfn(ui->txtTlfn->text().toStdString()); nuevo.setDireccion(ui->txtDireccion->text().toStdString()); nuevo.setCP(ui->txtCP->text().toStdString()); nuevo.setPoblacion(ui->txtPoblacion->text().toStdString()); nuevo.setProvincia(ui->txtProvincia->text().toStdString()); nuevo.setPais(ui->txtPais->text().toStdString()); nuevo.setObservaciones(ui->plaintxtObservaciones->toPlainText().toStdString()); controller_->setOwner(nuevo); this->inicial(); ui->tableOwner->selectRow(ui->tableOwner->rowCount()-1); } break; } case 2:{ QString ID = ui->tableOwner->item(ui->tableOwner->currentRow(),4)->text(); int seleccionado = ID.toInt(); encontrarID(controller_->getOwners(), &seleccionado); int fila = ui->tableOwner->currentRow(); if(ui->txtOwner->text().isEmpty() || ui->txtRazon->text().isEmpty() || ui->txtCP->text().isEmpty() || ui->txtDireccion->text().isEmpty() || ui->txtNIF->text().isEmpty() || ui->txtPais->text().isEmpty() || ui->txtPoblacion->text().isEmpty() || ui->txtProvincia->text().isEmpty() || ui->txtTlfn->text().isEmpty()){ QMessageBox::information(this, "", "Todos los campos deben estár rellenos"); }else{ c_owner modificado; modificado=controller_->getOwners().at(seleccionado); modificado.setOwner(ui->txtOwner->text().toStdString()); modificado.setRazon(ui->txtRazon->text().toStdString()); modificado.setNIF(ui->txtNIF->text().toStdString()); modificado.setTlfn(ui->txtTlfn->text().toStdString()); modificado.setDireccion(ui->txtDireccion->text().toStdString()); modificado.setCP(ui->txtCP->text().toStdString()); modificado.setPoblacion(ui->txtPoblacion->text().toStdString()); modificado.setProvincia(ui->txtProvincia->text().toStdString()); modificado.setPais(ui->txtPais->text().toStdString()); modificado.setObservaciones(ui->plaintxtObservaciones->toPlainText().toStdString()); controller_->modificarOwner(seleccionado, modificado); this->inicial(); ui->tableOwner->selectRow(fila); } break; } default: break; } } void gestionarOwner::cancelar(){ this->inicial(); this->limpiarLabel(); }
39.955157
320
0.63771
roiso
033f3439742b4c8100746e943d5ff7fcd865af51
339
hpp
C++
Server/include/Pages/ControlPannel.hpp
siisgoo/siisty
66103c54e0d1b35b88177c290e2bf60012607309
[ "MIT" ]
null
null
null
Server/include/Pages/ControlPannel.hpp
siisgoo/siisty
66103c54e0d1b35b88177c290e2bf60012607309
[ "MIT" ]
null
null
null
Server/include/Pages/ControlPannel.hpp
siisgoo/siisty
66103c54e0d1b35b88177c290e2bf60012607309
[ "MIT" ]
null
null
null
#ifndef CONTROLPANNEL_HPP #define CONTROLPANNEL_HPP #include <QWidget> namespace Ui { class ControlPannel; } class ControlPannel : public QWidget { Q_OBJECT public: explicit ControlPannel(QWidget *parent = nullptr); ~ControlPannel(); private: Ui::ControlPannel *ui; }; #endif // CONTROLPANNEL_HPP
15.409091
58
0.690265
siisgoo
034018a24168009ea6ac2846053c600e898da0fa
1,321
cpp
C++
Source/FactoryGame/FGTargetPointLinkedList.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
Source/FactoryGame/FGTargetPointLinkedList.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
Source/FactoryGame/FGTargetPointLinkedList.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
// This file has been automatically generated by the Unreal Header Implementation tool #include "FGTargetPointLinkedList.h" UFGTargetPointLinkedList::UFGTargetPointLinkedList(){ } void UFGTargetPointLinkedList::PreSaveGame_Implementation( int32 saveVersion, int32 gameVersion){ } void UFGTargetPointLinkedList::PostSaveGame_Implementation( int32 saveVersion, int32 gameVersion){ } void UFGTargetPointLinkedList::PreLoadGame_Implementation( int32 saveVersion, int32 gameVersion){ } void UFGTargetPointLinkedList::PostLoadGame_Implementation( int32 saveVersion, int32 gameVersion){ } void UFGTargetPointLinkedList::GatherDependencies_Implementation( TArray< UObject* >& out_dependentObjects){ } bool UFGTargetPointLinkedList::NeedTransform_Implementation(){ return bool(); } bool UFGTargetPointLinkedList::ShouldSave_Implementation() const{ return bool(); } void UFGTargetPointLinkedList::InsertItem( AFGTargetPoint* newTarget){ } void UFGTargetPointLinkedList::RemoveItem( AFGTargetPoint* targetToRemove){ } void UFGTargetPointLinkedList::SetCurrentTarget( AFGTargetPoint* newTarget){ } void UFGTargetPointLinkedList::SetPathVisibility( bool inVisible){ } void UFGTargetPointLinkedList::SetNextTarget(){ } void UFGTargetPointLinkedList::SetClosestPointAsTarget(){ } void UFGTargetPointLinkedList::ClearRecording(){ }
66.05
110
0.84103
iam-Legend
03409f67932eecc7dff926f199e2c962a793cf50
3,052
inl
C++
include/eagine/memory/alloc_arena.inl
matus-chochlik/eagine-core
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
[ "BSL-1.0" ]
1
2022-01-25T10:31:51.000Z
2022-01-25T10:31:51.000Z
include/eagine/memory/alloc_arena.inl
matus-chochlik/eagine-core
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
[ "BSL-1.0" ]
null
null
null
include/eagine/memory/alloc_arena.inl
matus-chochlik/eagine-core
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
[ "BSL-1.0" ]
null
null
null
/// @file /// /// Copyright Matus Chochlik. /// Distributed under the Boost Software License, Version 1.0. /// See accompanying file LICENSE_1_0.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt /// #include <eagine/assert.hpp> #include <cstdlib> namespace eagine::memory { //------------------------------------------------------------------------------ template <typename Alloc> inline auto basic_allocation_arena<Alloc>::_do_allocate( const span_size_t size, const span_size_t align) -> block { owned_block b = _alloc.allocate(size, align); if(b.empty()) { return {}; } EAGINE_ASSERT(is_aligned_to(b.addr(), align)); EAGINE_ASSERT(b.size() >= size); _blks.push_back(std::move(b)); _alns.push_back(align); return _blks.back(); } //------------------------------------------------------------------------------ template <typename Alloc> inline void basic_allocation_arena<Alloc>::clear() { EAGINE_ASSERT(_blks.size() == _alns.size()); for(std_size_t i = 0; i < _blks.size(); ++i) { _alloc.deallocate(std::move(_blks[i]), _alns[i]); } _blks.clear(); _alns.clear(); } //------------------------------------------------------------------------------ template <typename Alloc> template <typename T> inline auto basic_allocation_arena<Alloc>::_allocate( const span_size_t count, const span_size_t align) -> block { return _do_allocate( span_size_of<T>(count), std::max(align, span_align_of<T>())); } //------------------------------------------------------------------------------ template <typename Alloc> template <typename T> inline auto basic_allocation_arena<Alloc>::_make_n( const span_size_t count, const span_size_t align) -> T* { return new(_allocate<T>(count, align).data()) T[std_size(count)]{}; } //------------------------------------------------------------------------------ template <typename Alloc> template <typename T, typename... Args> inline auto basic_allocation_arena<Alloc>::_make_1( const span_size_t align, Args&&... a) -> T* { return new(_allocate<T>(1, align).data()) T(std::forward<Args>(a)...); } //------------------------------------------------------------------------------ template <typename Alloc> template <typename T> inline auto basic_allocation_arena<Alloc>::make_aligned_array( const span_size_t count, const span_size_t align) -> span<T> { if(count < 1) { return {}; } T* p = _make_n<T>(count, align); if(!p) { throw std::bad_alloc(); } return {p, count}; } //------------------------------------------------------------------------------ template <typename Alloc> template <typename T, typename... Args> inline auto basic_allocation_arena<Alloc>::make_aligned( const span_size_t align, Args&&... args) -> T& { T* p = _make_1<T>(align, std::forward<Args>(args)...); if(!p) { throw std::bad_alloc(); } return *p; } //------------------------------------------------------------------------------ } // namespace eagine::memory
31.142857
80
0.524574
matus-chochlik
034422cdc98a49c025a3585cef8bfe146bc259bf
1,383
cpp
C++
source/Cell.cpp
LgHS/GameOfLife-3DS-ClubMatrix
f3c73be09cb9ebeda7334679aa3b83df7dbb428e
[ "MIT" ]
null
null
null
source/Cell.cpp
LgHS/GameOfLife-3DS-ClubMatrix
f3c73be09cb9ebeda7334679aa3b83df7dbb428e
[ "MIT" ]
null
null
null
source/Cell.cpp
LgHS/GameOfLife-3DS-ClubMatrix
f3c73be09cb9ebeda7334679aa3b83df7dbb428e
[ "MIT" ]
null
null
null
#include <3ds.h> #include <stdio.h> #include <string.h> #include "Cell.h" #include <stdlib.h> Cell::Cell(Vector2* position, int isAlive, Vector2* worldSize) { this->IsAlive = isAlive; this->Position = position; this->newState = IsAlive; this->worldSize = worldSize; memset(neighbours, 0, (8 * sizeof(Cell*))); } void Cell::AddNeighbourgs(Cell* cell) { neighbours[currentNeighbors] = cell; currentNeighbors++; } void Cell::ComputeState() { // Compute alive cells int aliveCellCount = 0; for (int x = 0; x < currentNeighbors; x++) if (neighbours[x]->IsAlive) aliveCellCount++; // Apply Conways lay if(this->IsAlive) { if (aliveCellCount < 2) newState = 0; else if (aliveCellCount <= 3) newState = 1; else newState = 0; } else if (aliveCellCount == 3) newState = 1; } Vector2* Cell::AdjustCoordonates(Vector2* vector) { if (vector->X >= worldSize->X) vector->X = 0; else if (vector->X < 0) vector->X = worldSize->X - 1; if (vector->Y >= worldSize->Y) vector->Y = 0; else if (vector->Y < 0) vector->Y = worldSize->Y - 1; return vector; } void Cell::SetNewstate(int state) { this->IsAlive = state; this->newState = state; } void Cell::ApplyNewState() { this->IsAlive = this->newState; }
23.440678
63
0.587852
LgHS
034a73e43802c08ce8cdb045177e3d679765d325
302
hpp
C++
sources/CastlesStrategy/Server/Managers/Manager.hpp
KonstantinTomashevich/castles-strategy
5e57119ba7701e0f1f9c8d84ffb45abb6ad33a21
[ "MIT" ]
null
null
null
sources/CastlesStrategy/Server/Managers/Manager.hpp
KonstantinTomashevich/castles-strategy
5e57119ba7701e0f1f9c8d84ffb45abb6ad33a21
[ "MIT" ]
null
null
null
sources/CastlesStrategy/Server/Managers/Manager.hpp
KonstantinTomashevich/castles-strategy
5e57119ba7701e0f1f9c8d84ffb45abb6ad33a21
[ "MIT" ]
null
null
null
#pragma once namespace CastlesStrategy { class ManagersHub; class Manager { public: explicit Manager (ManagersHub *managersHub); virtual ~Manager (); ManagersHub * GetManagersHub () const; virtual void HandleUpdate (float timeStep) = 0; private: ManagersHub *managersHub_; }; }
15.1
51
0.715232
KonstantinTomashevich
034ae43994310df4301f805397fb442d10c7f6ff
12,728
cpp
C++
Homework/boilerplate/main.cpp
lflame/Router-Lab
58cbcf72fd8e86babbdb3abbe03b4eb23826b79b
[ "Linux-OpenIB" ]
1
2021-09-13T02:38:19.000Z
2021-09-13T02:38:19.000Z
Homework/boilerplate/main.cpp
lflame/Router-Lab
58cbcf72fd8e86babbdb3abbe03b4eb23826b79b
[ "Linux-OpenIB" ]
null
null
null
Homework/boilerplate/main.cpp
lflame/Router-Lab
58cbcf72fd8e86babbdb3abbe03b4eb23826b79b
[ "Linux-OpenIB" ]
1
2021-05-22T08:09:28.000Z
2021-05-22T08:09:28.000Z
#include "router_hal.h" #include "rip.h" #include "router.h" #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <vector> #define RIP_MAX_ENTRY 25 #define TICKS_PER_SEC 1000 #define TIMEOUT 60 // TODO 暂定为 60s 超时 // 注意1s有1000个TICKS extern bool validateIPChecksum(uint8_t *packet, size_t len); extern bool update(RoutingTableEntry entry); extern bool query(uint32_t addr, uint32_t *nexthop, uint32_t *if_index); extern bool forward(uint8_t *packet, size_t len); extern bool disassemble(const uint8_t *packet, uint32_t len, RipPacket *output); extern uint32_t assemble(const RipPacket *rip, uint8_t *buffer); extern uint32_t getFourByte(uint8_t *packet); extern void putFourByte(uint8_t *packet, uint32_t num); extern uint32_t convertBigSmallEndian32(uint32_t num); extern uint16_t calcIPChecksum(uint8_t *packet, size_t len); extern uint16_t calcUDPChecksum(uint8_t *packet, size_t len, in_addr_t srcAddr, in_addr_t dstAddr); extern uint32_t getMaskFromLen(uint32_t len); extern uint32_t getLenFromMask(uint32_t mask); extern bool isInSameNetworkSegment(in_addr_t addr1, in_addr_t addr2, uint32_t len); extern std::vector<RoutingTableEntry> table; extern void printAddr(const in_addr_t &addr, FILE *file); extern void printRouteEntry(const RoutingTableEntry &entry, FILE *file); extern void printRouteTable(uint64_t time, FILE *file); bool DEBUG = false; // 是否输出调试信息(总开关),不能关闭路由表打印 uint8_t packet[2048]; uint8_t output[2048]; uint16_t ipTag; // ip头中的16位标识 // 0: 10.0.0.1 // 1: 10.0.1.1 // 2: 10.0.2.1 // 3: 10.0.3.1 // 你可以按需进行修改,注意端序 // in_addr_t addrs[N_IFACE_ON_BOARD] = {0x0100000a, 0x0101000a, 0x0102000a, 0x0103000a}; // TODO: 记得更改正确的 IP 地址,以及对应的接口名称(在standard.h中修改) // 0: 192.168.3.2 // 1: 192.168.4.1 // 2: 10.0.2.1 // 3: 10.0.3.1 in_addr_t addrs[N_IFACE_ON_BOARD] = {0x0101A8C0, 0x0103A8C0, 0x0102A8C0}; const in_addr_t multicastAddr = 0x090000E0; // ripv2 的组播地址 224.0.0.9 macaddr_t multicastMac; void sendRipPacketByHAL(const uint32_t &if_index, const RipPacket &rip, in_addr_t dstAddr, macaddr_t dstMac) { // 将 rip 封装 UDP 和 IP 头,并从索引为 if_index 的网络接口发送出去,发送的目的 ip 地址为dstAddr。注意 rip 报文封装之后长度不会超过以太网的 MTU // assemble // 为了获得 rip_len, 先填入 rip 部分: uint32_t rip_len = assemble(&rip, &output[20 + 8]); in_addr_t srcAddr = addrs[if_index]; // IP ++ipTag; output[0] = 0x45; output[1] = 0xC0; // 此处设置为同抓包得到的相同,表示网间控制的一般服务 output[2] = ((rip_len + 20 + 8) >> 8) & 0xFF; output[3] = (rip_len + 20 + 8) & 0xFF; output[4] = (ipTag >> 8) & 0xFF; // IP 长度 output[5] = ipTag & 0xFF; output[6] = 0x00; // 不用考虑分片 output[7] = 0x00; output[8] = 0x01; // TTL为1,因为只向邻居发送rip报文 output[9] = 0x11; // 表示携带UDP协议 output[10] = 0x00; output[11] = 0x00; // 头部校验和留至填充头部完毕之后计算 putFourByte(output + 12, srcAddr); putFourByte(output + 16, dstAddr); uint16_t cksum = calcIPChecksum(output, rip_len + 20 + 8); // IP 头部校验和 output[10] = (cksum >> 8) & 0xFF; output[11] = cksum & 0xFF; // UDP // port = 520 output[20] = 0x02; output[21] = 0x08; // 源端口为 520 output[22] = 0x02; output[23] = 0x08; // 目的端口为 520 output[24] = ((rip_len + 8) >> 8) & 0xFF; output[25] = (rip_len + 8) & 0xFF; // UDP长度 output[26] = 0x00; output[27] = 0x00; // 待会计算校验和 cksum = calcUDPChecksum(output + 20, rip_len + 8, srcAddr, dstAddr); output[26] = (cksum >> 8) & 0xFF; output[27] = cksum & 0xFF; // RIP 在上面已经填过了 // checksum calculation for ip and udp // if you don't want to calculate udp checksum, set it to zero // send it back HAL_SendIPPacket(if_index, output, rip_len + 20 + 8, dstMac); } void sendRipUpdate(const RipPacket &upd) { // 向各个网口发送 rip 更新报文,更新报文从 upd 计算得到 // 注意计算时滤掉 addr 与出接口在同一网段的,并且对于 // nexthop 与出接口在同一网段的,发送的 metric 设为 16(毒逆) // NOTE: 这样的毒逆默认了路由器不会在同一接口上进行转发 // 也就是说默认同一网段可互达 if (DEBUG) printf("sendRipUpdate\n"); RipPacket resp; for (int i = 0; i < N_IFACE_ON_BOARD; ++i) { macaddr_t mac; resp.numEntries = 0; resp.command = 2; for (int j = 0; j < upd.numEntries; ++j) { // 毒性逆转 uint32_t len = getLenFromMask(convertBigSmallEndian32(upd.entries[j].mask)); if (!isInSameNetworkSegment(upd.entries[j].addr, addrs[i], len)) { uint32_t id = resp.numEntries++; resp.entries[id] = upd.entries[j]; // if (isInSameNetworkSegment(table[resp.entries[id].localTableInd].nexthop, addrs[i], len)) { if (i == table[resp.entries[id].localTableInd].if_index) { resp.entries[id].metric = convertBigSmallEndian32(16); } } } if (resp.numEntries) { sendRipPacketByHAL(i, resp, multicastAddr, multicastMac); } } } void sendRipRequest() { // 向各网口发送 rip 请求报文 RipPacket rip; rip.numEntries = 1; rip.command = 1; rip.entries[0].addr = 0; rip.entries[0].mask = 0; rip.entries[0].nexthop = 0; rip.entries[0].metric = convertBigSmallEndian32(16); for (int i = 0; i < RIP_MAX_ENTRY; ++i) { sendRipPacketByHAL(i, rip, multicastAddr, multicastMac); } } int main(int argc, char *argv[]) { freopen("nul", "w", stdout); // 用于不输出琐碎的信息 // freopen("nul", "w", stderr); // 用于不输出关键的信息 srand(time(NULL)); ipTag = (uint32_t)rand(); int res = HAL_Init(DEBUG, addrs); int messageId = 0; // for debug if (res < 0) { return res; } HAL_ArpGetMacAddress(0, multicastAddr, multicastMac); // 组播 ip 对应的组播 mac 地址,一定存在 // Add direct routes // For example: // 10.0.0.0/24 if 0 // 10.0.1.0/24 if 1 // 10.0.2.0/24 if 2 // 10.0.3.0/24 if 3 for (uint32_t i = 0; i < N_IFACE_ON_BOARD;i++) { RoutingTableEntry entry = { .addr = addrs[i], // big endian .len = 24, // small endian .if_index = i, // small endian .metric = 0, // small endian .timestamp = 0, // small endian 直连网络不需要timestamp .nexthop = 0 // big endian, means direct }; update(entry); } // 加入时向各网口发出请求报文 sendRipRequest(); uint64_t last_time = 0; int updCnt = 0; // 每计6次(5*6 = 30s)进行一次更新 bool first_send = false; while (1) { uint64_t time = HAL_GetTicks(); if (!first_send || time > last_time + 5 * TICKS_PER_SEC) { // 例行更新 // 发出响应报文之前记得确认timestamp if (!first_send || ++updCnt == 1) { fprintf(stderr, "Timer Fired: Send update\n"); first_send = true; updCnt = 0; RipPacket upd; upd.command = 2; upd.numEntries = 0; for (int i = 0; i < table.size(); ++i) { uint32_t id = upd.numEntries++; upd.entries[id].addr = table[i].addr; upd.entries[id].mask = convertBigSmallEndian32(getMaskFromLen(table[i].len)); upd.entries[id].nexthop = 0; upd.entries[id].metric = convertBigSmallEndian32(table[i].metric); upd.entries[id].localTableInd = i; if (table[i].nexthop != 0 && (double)(time - table[i].timestamp) / TICKS_PER_SEC > TIMEOUT) { // 非直连,且路由表项超时,这里采取简单的做法,直接发出报文——一个更好的做法是等待一段时间之后未被更新再发出报文 upd.entries[id].metric = convertBigSmallEndian32(16); table.erase(table.begin() + i); } if (upd.numEntries == RIP_MAX_ENTRY) { sendRipUpdate(upd); upd.numEntries = 0; } } if (upd.numEntries) { sendRipUpdate(upd); } } last_time = time; printRouteTable(time, stderr); } int mask = (1 << N_IFACE_ON_BOARD) - 1; macaddr_t srcMac; macaddr_t dstMac; int if_index; res = HAL_ReceiveIPPacket(mask, packet, sizeof(packet), srcMac, dstMac, 1000, &if_index); if (res == HAL_ERR_EOF) { break; } else if (res < 0) { return res; } else if (res == 0) { // Timeout continue; } else if (res > sizeof(packet)) { // packet is truncated, ignore it continue; } ++messageId; if (DEBUG) printf("%d:: Valid Message. res: %d\n", messageId, res); if (!validateIPChecksum(packet, res)) { if (DEBUG) printf("%d:: Invalid IP Checksum\n", messageId); continue; } in_addr_t srcAddr, dstAddr; // extract srcAddr and dstAddr from packet // big endian srcAddr = getFourByte(packet + 12); dstAddr = getFourByte(packet + 16); bool dst_is_me = false; for (int i = 0; i < N_IFACE_ON_BOARD;i++) { if (memcmp(&dstAddr, &addrs[i], sizeof(in_addr_t)) == 0) { dst_is_me = true; break; } } bool isMulti = (dstAddr == multicastAddr); if (isMulti || dst_is_me) { // 224.0.0.9 or me,进行接收处理 if (DEBUG) printf("%d:: Dst is me or multicast.\n", messageId); RipPacket rip; if (disassemble(packet, res, &rip)) { // 为 rip 数据报 if (rip.command == 1) { // request // 请求报文必须满足 metric 为 16,注意 metric 为大端序 // 注意若表项数目大于 25,则需要分开发送 if (DEBUG) printf("%d:: Received rip request.\n", messageId); uint32_t metricSmall = convertBigSmallEndian32(rip.entries[0].metric); if (metricSmall != 16) continue; RipPacket resp; // 封装响应报文,注意选择路由条目 resp.command = 2; // response resp.numEntries = 0; for (int j = 0; j < table.size(); ++j) { if (!isInSameNetworkSegment(table[j].addr, srcAddr, table[j].len)) { // 与来源ip的网段不同 uint32_t id = resp.numEntries++; resp.entries[id].addr = table[j].addr; resp.entries[id].mask = convertBigSmallEndian32(getMaskFromLen(table[j].len)); resp.entries[id].nexthop = 0; resp.entries[id].metric = convertBigSmallEndian32(table[j].metric); if (isInSameNetworkSegment(table[j].nexthop, addrs[if_index], table[j].len)) { // 毒性逆转 resp.entries[id].metric = convertBigSmallEndian32(16); } if (resp.numEntries == RIP_MAX_ENTRY) { // 满 25 条,进行一次发送 sendRipPacketByHAL(if_index, resp, srcAddr, srcMac); resp.numEntries = 0; } } } if (resp.numEntries) { sendRipPacketByHAL(if_index, resp, srcAddr, srcMac); } } else { // response if (DEBUG) printf("%d:: Received rip response.\n", messageId); RipPacket upd; upd.numEntries = 0; upd.command = 2; for (int i = 0; i < rip.numEntries; ++i) { RoutingTableEntry entry; entry.addr = rip.entries[i].addr; entry.len = getLenFromMask(convertBigSmallEndian32(rip.entries[i].mask)); entry.if_index = if_index; entry.metric = convertBigSmallEndian32(rip.entries[i].metric); entry.timestamp = HAL_GetTicks(); entry.nexthop = srcAddr; bool suc = update(entry); if (suc) { // 若更新路由表成功,触发更新 printf("%d:: Update router successfully.", messageId); printRouteEntry(entry, stdout); uint32_t id = upd.numEntries++; upd.entries[id] = rip.entries[i]; upd.entries[id].nexthop = 0; upd.entries[id].metric = convertBigSmallEndian32(entry.metric); upd.entries[id].localTableInd = i; } } if (upd.numEntries) { sendRipUpdate(upd); } } } else { // Target is me but not rip. } } else { // forward // beware of endianness if (DEBUG) printf("%d:: Forward.\n", messageId); uint32_t nexthop, dest_if; if (query(dstAddr, &nexthop, &dest_if)) { // found macaddr_t dest_mac; // direct routing if (nexthop == 0) { nexthop = dstAddr; } if (HAL_ArpGetMacAddress(dest_if, nexthop, dest_mac) == 0) { // found // update ttl and checksum forward(packet, res); // check ttl!=0 if (packet[8] != 0) { HAL_SendIPPacket(dest_if, packet, res, dest_mac); if (DEBUG) printf("%d:: Forward successfully. dest_if: %d Nexthop:", messageId, dest_if); if (DEBUG) printAddr(nexthop, stdout); if (DEBUG) printf("\n"); } else { // ttl == 0 if (DEBUG) printf("%d:: TTL is 0.\n", messageId); } } else { // not found if (DEBUG) printf("%d:: Failed to get mac address. dest_if: %d Nexthop:", messageId, dest_if); if (DEBUG) printAddr(nexthop, stdout); if (DEBUG) printf("\n"); } } else { // not found if (DEBUG) printf("%d:: No matching item in table.\n", messageId); } } } return 0; }
34.032086
110
0.594987
lflame
034fcc273045ccc0e78d1ab866f9407015901004
7,244
cpp
C++
src/Util/VRMLWriter.cpp
snozawa/choreonoid
12ab42ccbf287d68216637e55ddae8412771c752
[ "MIT" ]
null
null
null
src/Util/VRMLWriter.cpp
snozawa/choreonoid
12ab42ccbf287d68216637e55ddae8412771c752
[ "MIT" ]
null
null
null
src/Util/VRMLWriter.cpp
snozawa/choreonoid
12ab42ccbf287d68216637e55ddae8412771c752
[ "MIT" ]
null
null
null
/*! @file @author Shin'ichiro Nakaoka */ #include "VRMLWriter.h" using namespace std; using namespace boost; using namespace cnoid; namespace { typedef void (VRMLWriter::*VRMLWriterNodeMethod)(VRMLNodePtr node); typedef std::map<std::string, VRMLWriterNodeMethod> TNodeMethodMap; typedef std::pair<std::string, VRMLWriterNodeMethod> TNodeMethodPair; TNodeMethodMap nodeMethodMap; inline void registerNodeMethod(const std::type_info& t, VRMLWriterNodeMethod method) { nodeMethodMap.insert(TNodeMethodPair(t.name(), method)); } VRMLWriterNodeMethod getNodeMethod(VRMLNodePtr node) { TNodeMethodMap::iterator p = nodeMethodMap.find(typeid(*node).name()); return (p != nodeMethodMap.end()) ? p->second : 0; } inline std::ostream& operator<<(std::ostream& out, VRMLWriter::TIndent& indent) { return out << indent.spaces; } inline const char* boolstr(bool v) { if(v){ return "TRUE"; } else { return "FALSE"; } } ostream& operator<<(std::ostream& out, const SFVec2f& v) { return out << v[0] << " " << v[1]; } ostream& operator<<(std::ostream& out, const SFVec3f& v) { return out << v[0] << " " << v[1] << " " << v[2]; } ostream& operator<<(std::ostream& out, const SFColor& v) { return out << v[0] << " " << v[1] << " " << v[2]; } ostream& operator<<(std::ostream& out, const SFRotation& v) { const SFRotation::Vector3& a = v.axis(); return out << a[0] << " " << a[1] << " " << a[2] << " " << v.angle(); } } template <class MFValues> void VRMLWriter::writeMFValues(MFValues values, int numColumn) { out << ++indent << "[\n"; ++indent; out << indent; int col = 0; int n = values.size(); for(int i=0; i < n; i++){ out << values[i] << " "; col++; if(col == numColumn){ col = 0; out << "\n"; if(i < n-1){ out << indent; } } } out << --indent << "]\n"; --indent; } void VRMLWriter::writeMFInt32SeparatedByMinusValue(MFInt32& values) { out << ++indent << "[\n"; ++indent; out << indent; int n = values.size(); for(int i=0; i < n; i++){ out << values[i] << " "; if(values[i] < 0){ out << "\n"; if(i < n-1){ out << indent; } } } out << --indent << "]\n"; --indent; } VRMLWriter::VRMLWriter(std::ostream& out) : out(out) { if(nodeMethodMap.empty()){ registerNodeMethodMap(); } } void VRMLWriter::registerNodeMethodMap() { registerNodeMethod(typeid(VRMLGroup), &VRMLWriter::writeGroupNode); registerNodeMethod(typeid(VRMLTransform), &VRMLWriter::writeTransformNode); registerNodeMethod(typeid(VRMLShape), &VRMLWriter::writeShapeNode); registerNodeMethod(typeid(VRMLIndexedFaceSet), &VRMLWriter::writeIndexedFaceSetNode); } void VRMLWriter::writeHeader() { out << "#VRML V2.0 utf8\n"; } bool VRMLWriter::writeNode(VRMLNodePtr node) { indent.clear(); out << "\n"; writeNodeIter(node); return true; } void VRMLWriter::writeNodeIter(VRMLNodePtr node) { VRMLWriterNodeMethod method = getNodeMethod(node); if(method){ (this->*method)(node); } } void VRMLWriter::beginNode(const char* nodename, VRMLNodePtr node) { out << indent; if(node->defName.empty()){ out << nodename << " {\n"; } else { out << "DEF " << node->defName << " " << nodename << " {\n"; } ++indent; } void VRMLWriter::endNode() { out << --indent << "}\n"; } void VRMLWriter::writeGroupNode(VRMLNodePtr node) { VRMLGroupPtr group = static_pointer_cast<VRMLGroup>(node); beginNode("Group", group); writeGroupFields(group); endNode(); } void VRMLWriter::writeGroupFields(VRMLGroupPtr group) { if(group->bboxSize[0] >= 0){ out << indent << "bboxCenter " << group->bboxCenter << "\n"; out << indent << "bboxSize " << group->bboxSize << "\n"; } if(!group->children.empty()){ out << indent << "children [\n"; ++indent; for(size_t i=0; i < group->children.size(); i++){ writeNodeIter(group->children[i]); } out << --indent << "]\n"; } } void VRMLWriter::writeTransformNode(VRMLNodePtr node) { VRMLTransformPtr trans = static_pointer_cast<VRMLTransform>(node); beginNode("Transform", trans); out << indent << "center " << trans->center << "\n"; out << indent << "rotation " << trans->rotation << "\n"; out << indent << "scale " << trans->scale << "\n"; out << indent << "scaleOrientation " << trans->scaleOrientation << "\n"; out << indent << "translation " << trans->translation << "\n"; writeGroupFields(trans); endNode(); } void VRMLWriter::writeShapeNode(VRMLNodePtr node) { VRMLShapePtr shape = static_pointer_cast<VRMLShape>(node); beginNode("Shape", shape); if(shape->appearance){ out << indent << "appearance\n"; ++indent; writeAppearanceNode(shape->appearance); --indent; } if(shape->geometry){ out << indent << "geometry\n"; VRMLWriterNodeMethod method = getNodeMethod(shape->geometry); if(method){ ++indent; (this->*method)(shape->geometry); --indent; } } endNode(); } void VRMLWriter::writeAppearanceNode(VRMLAppearancePtr appearance) { beginNode("Appearance", appearance); if(appearance->material){ out << indent << "material\n"; ++indent; writeMaterialNode(appearance->material); --indent; } endNode(); } void VRMLWriter::writeMaterialNode(VRMLMaterialPtr material) { beginNode("Material", material); out << indent << "ambientIntensity " << material->ambientIntensity << "\n"; out << indent << "diffuseColor " << material->diffuseColor << "\n"; out << indent << "emissiveColor " << material->emissiveColor << "\n"; out << indent << "shininess " << material->shininess << "\n"; out << indent << "specularColor " << material->specularColor << "\n"; out << indent << "transparency " << material->transparency << "\n"; endNode(); } void VRMLWriter::writeIndexedFaceSetNode(VRMLNodePtr node) { VRMLIndexedFaceSetPtr faceset = static_pointer_cast<VRMLIndexedFaceSet>(node); beginNode("IndexedFaceSet", faceset); if(faceset->coord){ out << indent << "coord\n"; ++indent; writeCoordinateNode(faceset->coord); --indent; } if(!faceset->coordIndex.empty()){ out << indent << "coordIndex\n"; writeMFInt32SeparatedByMinusValue(faceset->coordIndex); } out << indent << "ccw " << boolstr(faceset->ccw) << "\n"; out << indent << "convex " << boolstr(faceset->convex) << "\n"; out << indent << "creaseAngle " << faceset->creaseAngle << "\n"; out << indent << "solid " << boolstr(faceset->solid) << "\n"; endNode(); } void VRMLWriter::writeCoordinateNode(VRMLCoordinatePtr coord) { beginNode("Coordinate", coord); if(!coord->point.empty()){ out << indent << "point\n"; writeMFValues(coord->point, 1); } endNode(); }
23.367742
89
0.583793
snozawa
0350f1705a77c68a74f42c0d54992730d42b45c3
1,580
hpp
C++
caffe/include/caffe/layers/sparse_histogram_extractor_layer.hpp
gustavla/autocolorizer
79d4ce1054d35c06bdfcc93236b71e161e082ebb
[ "BSD-3-Clause" ]
234
2016-04-04T15:12:24.000Z
2022-03-14T12:55:09.000Z
caffe/include/caffe/layers/sparse_histogram_extractor_layer.hpp
TrinhQuocNguyen/autocolorize
79d4ce1054d35c06bdfcc93236b71e161e082ebb
[ "BSD-3-Clause" ]
20
2016-04-05T12:44:04.000Z
2022-02-22T06:02:17.000Z
caffe/include/caffe/layers/sparse_histogram_extractor_layer.hpp
TrinhQuocNguyen/autocolorize
79d4ce1054d35c06bdfcc93236b71e161e082ebb
[ "BSD-3-Clause" ]
71
2016-07-12T15:28:16.000Z
2021-12-16T12:22:57.000Z
#ifndef CAFFE_SPARSE_PATCH_LAYER_HPP #define CAFFE_SPARSE_PATCH_LAYER_HPP #include <string> #include <utility> #include <vector> #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/layer.hpp" namespace caffe { /** * Takes locations and extracts a stack of histograms. */ template <typename Dtype> class SparseHistogramExtractorLayer : public Layer<Dtype> { public: explicit SparseHistogramExtractorLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "SparseHistogramExtractor"; } virtual inline int ExactNumBottomBlobs() const { return 2; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); int num_layers_; int num_channels_; int num_locations_; std::vector<int> sizes_; // Temporary storage for the summed area table Blob<Dtype> integral_histogram_; }; } // namespace caffe #endif // CAFFE_SPARSE_PATCH_LAYER_HPP
29.259259
80
0.729747
gustavla
03568559c8068436b36aa4d72dab560a5e174e05
2,939
cpp
C++
opcodes.cpp
stavros-avramidis/Assembler
5c061cfd7c98e1b607f024f30e2545a19d0a70ea
[ "MIT" ]
null
null
null
opcodes.cpp
stavros-avramidis/Assembler
5c061cfd7c98e1b607f024f30e2545a19d0a70ea
[ "MIT" ]
null
null
null
opcodes.cpp
stavros-avramidis/Assembler
5c061cfd7c98e1b607f024f30e2545a19d0a70ea
[ "MIT" ]
null
null
null
/* opcodes.cpp * * Created by purpl3f0x on 9/12/18. * Stavros Avramidis */ #include "opcodes.hpp" /*-------------------------------------------*/ /*-------------- OpCodes ---------------*/ unsigned int OpCodes::getBinary(std::string name) const { for (auto op: *this) if (op.name==name) return op.binary; return 0; // returns NOP } unsigned int OpCodes::numOfArgs(std::string name) const { for (auto op: *this) if (op.name==name) return op.numOfArgs; return 0; } std::string OpCodes::getName(unsigned short bin) const { for (auto op: *this) if (op.binary==bin) return op.name; return ""; } bool OpCodes::isOpCode(std::string name) const { for (auto op: *this) if (op.name==name) return true; return false; } opCode *OpCodes::find(std::string name) { for (auto &&op: *this) if (op.name==name) return &op; return nullptr; } std::string OpCodes::operator[](int bin) { return this->getName(bin); } int OpCodes::operator[](std::string name) { return this->getBinary(name); } /* Declare opCodes*/ OpCodes opCodes = { //Basic operations opCode("NOP", 0b0000000, 0), opCode("RI", 0b0000001, 0), opCode("LDA", 0b0000010, 1), opCode("LDI", 0b0000011, 1), opCode("STA", 0b0000100, 1), opCode("JMP", 0b0000101, 1), opCode("MI", 0b0000110, 2), opCode("MO", 0b0000111, 2), //Conditional Jumps opCode("JC", 0b0001000, 2), opCode("JO", 0b0001001, 2), opCode("JG", 0b0001010, 2), opCode("JGE", 0b0001011, 2), opCode("JE", 0b0001100, 2), opCode("JLE", 0b0001101, 2), opCode("JL", 0b0001110, 2), opCode("JNO", 0b0001111, 2), opCode("JZ", 0b0010000, 2), opCode("JNZ", 0b0010001, 2), opCode("JS", 0b0010010, 2), opCode("JNS", 0b0010011, 2), // ALU opCode("ADD", 0b1000000, 3), opCode("SUB", 0b1000001, 3), opCode("MUL", 0b1000010, 3), opCode("DIV", 0b1000011, 3), opCode("ADDI", 0b1000100, 3), opCode("SUBI", 0b1000101, 3), opCode("MULI", 0b1000110, 3), opCode("DIVI", 0b1000111, 3), //Complex ALU operations opCode("SQRT", 0b1001000, 2), opCode("MOD", 0b1001001, 3), // Bitwise operationns opCode("AND", 0b1100000, 3), opCode("OR", 0b11000001, 3), opCode("NAND", 0b1100010, 3), opCode("NOR", 0b1100011, 3), opCode("NOT", 0b1100100, 3), opCode("XOR", 0b1100101, 3), opCode("XOR", 0b1100110, 3), opCode("SHL", 0b1100111, 3), opCode("SHR", 0b1101000, 3), opCode("ROT", 0b1101001, 3), opCode("CMP", 0b1101010, 3), //FPU opCode("FADD", 0b1110000, 3), opCode("FSUB", 0b1110001, 3), opCode("FMUL", 0b1110010, 3), opCode("FDIV", 0b1110011, 3), opCode("FSQRT", 0b1110100, 3), opCode("ITOF", 0b1110101, 3), opCode("FTOI", 0b1110111, 3), opCode("FMOD", 0b1111000, 3), //HACF -- HALT AND CATCH FIRE opCode("HLT", 0b1111111, 0), };
22.265152
57
0.578088
stavros-avramidis
035d9bb4998f07127523f0ec169ac61e67a2b910
508
cpp
C++
UnitTest/IntentTest.cpp
omarekik/EmbeddedIntentRecognizer
dc3104702e1d3c572f62d9deb763a9b60f97e14e
[ "MIT" ]
null
null
null
UnitTest/IntentTest.cpp
omarekik/EmbeddedIntentRecognizer
dc3104702e1d3c572f62d9deb763a9b60f97e14e
[ "MIT" ]
null
null
null
UnitTest/IntentTest.cpp
omarekik/EmbeddedIntentRecognizer
dc3104702e1d3c572f62d9deb763a9b60f97e14e
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "Intent.h" TEST(Intent, canFindContextInSentence) { Intent intent({"HELLO", "HI", "MORNING"}, "GREETING"); EXPECT_FALSE(intent.find("IT WILL BE THE BEST DAY.")); EXPECT_TRUE(intent.find("GOOD MORNING MY CAR.")); } TEST(Intent, canFindExpressionContextInSentence) { Intent intent({"HELLO", "HI", "GOOD MORNING"}, "GREETING"); EXPECT_FALSE(intent.find("IT WILL BE THE BEST DAY.")); EXPECT_TRUE(intent.find("GOOD MORNING MY CAR.")); }
29.882353
64
0.661417
omarekik
035db36438e670f15e3f72d03de21b4be307d031
434
cpp
C++
src_compressible/conservedPrimitiveConversions.cpp
ckim103/FHDeX
9182d7589db7e7ee318ca2a0f343c378d9c120a0
[ "BSD-3-Clause-LBNL" ]
null
null
null
src_compressible/conservedPrimitiveConversions.cpp
ckim103/FHDeX
9182d7589db7e7ee318ca2a0f343c378d9c120a0
[ "BSD-3-Clause-LBNL" ]
null
null
null
src_compressible/conservedPrimitiveConversions.cpp
ckim103/FHDeX
9182d7589db7e7ee318ca2a0f343c378d9c120a0
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "compressible_functions.H" #include "compressible_functions_F.H" void conservedToPrimitive(MultiFab& prim, const MultiFab& cons) { // Loop over boxes for ( MFIter mfi(prim); mfi.isValid(); ++mfi) { const Box& bx = mfi.validbox(); cons_to_prim(ARLIM_3D(bx.loVect()), ARLIM_3D(bx.hiVect()), cons[mfi].dataPtr(), prim[mfi].dataPtr()); } }
27.125
68
0.576037
ckim103
035e3f6d11f0a2b7634651309c930cfacac9808e
2,953
cpp
C++
src/tasks.cpp
Algorithms-and-Data-Structures-2021/h00_cpp_basics-if-tim
f4e5c4959a4d8848823c1eccf85c53251962df3b
[ "MIT" ]
null
null
null
src/tasks.cpp
Algorithms-and-Data-Structures-2021/h00_cpp_basics-if-tim
f4e5c4959a4d8848823c1eccf85c53251962df3b
[ "MIT" ]
null
null
null
src/tasks.cpp
Algorithms-and-Data-Structures-2021/h00_cpp_basics-if-tim
f4e5c4959a4d8848823c1eccf85c53251962df3b
[ "MIT" ]
null
null
null
#include <iostream> // cout #include <algorithm> // copy, fill #include "tasks.hpp" // ИСПОЛЬЗОВАНИЕ ЛЮБЫХ ДРУГИХ БИБЛИОТЕК НЕ СОВЕТУЕТСЯ И МОЖЕТ ПОВЛИЯТЬ НА ВАШИ БАЛЛЫ using std::cout; using std::fill; using std::copy; // Задание 1 void swap_args(int *lhs, int *rhs) { if (lhs == nullptr || rhs == nullptr) { return; } int tmp = *lhs; *lhs = *rhs; *rhs = tmp; } // Задание 2 int **allocate_2d_array(int num_rows, int num_cols, int init_value) { if (num_rows < 1 || num_cols < 1) { return nullptr; } int **two_dimension_array = new int*[num_rows]; for (int row_index = 0; row_index < num_rows; row_index++) { two_dimension_array[row_index] = new int[num_cols]; } for (int row_index = 0; row_index < num_rows; row_index++) { for (int column_index = 0; column_index < num_cols; column_index++) { two_dimension_array[row_index][column_index] = init_value; } } return two_dimension_array; } // Задание 3 bool copy_2d_array(int **arr_2d_source, int **arr_2d_target, int num_rows, int num_cols) { if (arr_2d_source == nullptr || arr_2d_target == nullptr || num_rows < 1 || num_cols < 1) { return false; } for (int row_index = 0; row_index < num_rows; row_index++) { for (int column_index = 0; column_index < num_cols;column_index++) { int tmp = arr_2d_source[row_index][column_index]; arr_2d_target[row_index][column_index] = tmp; } } return true; } // Задание 4 void reverse_1d_array(vector<int> &arr) { for (int left = 0, right = arr.size() - 1; left < right; left++, right--) { int tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; } } // Задание 5 void reverse_1d_array(int *arr_begin, int *arr_end) { if (arr_begin == nullptr || arr_end == nullptr) { return; } for (int *left = arr_begin, *right = arr_end; left < right; left++, right--) { int tmp = * left; *left = *right; *right = tmp; } } // Задание 6 int *find_max_element(int *arr, int size) { if (arr == nullptr || size < 1) { return nullptr; } int *max = arr; for (int *iterator = arr; iterator <= arr + size - 1; iterator++) { if (*max < *iterator) { max = iterator; } } return max; } // Задание 7 vector<int> find_odd_numbers(vector<int> &arr) { vector<int> result; for (int i = 0; i < arr.size(); i++) { if (arr[i] % 2 != 0) { result.push_back(arr[i]); } } return result; } // Задание 8 vector<int> find_common_elements(vector<int> &arr_a, vector<int> &arr_b) { vector<int> result; for (int i = 0; i < arr_a.size(); i++) { for (int j = 0; j < arr_b.size(); j++) { if (arr_a[i] == arr_b[j]) { result.push_back(arr_a[i]); } } } return result; }
26.603604
95
0.568574
Algorithms-and-Data-Structures-2021
24e9d1f3329528c4b173fab20fa8988fea791da1
652
cpp
C++
windows/wrapper/impl_org_webRtc.cpp
webrtc-uwp/webrtc-windows-apis
accb133e195da9b0e77f59d749a282d133a80f24
[ "BSD-3-Clause" ]
9
2019-03-27T12:19:29.000Z
2022-01-25T05:13:55.000Z
windows/wrapper/impl_org_webRtc.cpp
webrtc-uwp/webrtc-windows-apis
accb133e195da9b0e77f59d749a282d133a80f24
[ "BSD-3-Clause" ]
8
2018-11-07T19:09:19.000Z
2019-11-27T15:20:08.000Z
windows/wrapper/impl_org_webRtc.cpp
webrtc-uwp/webrtc-windows-apis
accb133e195da9b0e77f59d749a282d133a80f24
[ "BSD-3-Clause" ]
12
2019-06-06T14:15:26.000Z
2022-01-24T13:35:30.000Z
#include <zsLib/Log.h> #include "Org.WebRtc.Glue.events.h" #include "Org.WebRtc.Glue.events.jman.h" namespace wrapper { namespace impl { namespace org { namespace webRtc { ZS_IMPLEMENT_SUBSYSTEM(wrapper_org_webRtc); } } } } ZS_EVENTING_SUBSYSTEM_DEFAULT_LEVEL(wrapper_org_webRtc, Debug) namespace wrapper { namespace impl { namespace org { namespace webRtc { void initSubsystems() noexcept { ZS_GET_SUBSYSTEM_LOG_LEVEL(ZS_GET_OTHER_SUBSYSTEM(wrapper::impl::org::webRtc, wrapper_org_webRtc)); ZS_EVENTING_REGISTER(Org_WebRtc_Glue); } } // namespace webRtc } // namespace impl } // namespace org } // namespace webRtc
25.076923
124
0.745399
webrtc-uwp
24eb934681d78000ad65cb9e4a4409f1e88088d8
4,340
cpp
C++
tools/jsoncons/tests/src/jsonpath/jsonpath_error_tests.cpp
SheldonHH/eosio.cdt
64448283307b2daebb7db4df947fafd3fc56a83c
[ "MIT" ]
476
2018-09-07T01:27:11.000Z
2022-03-21T05:16:50.000Z
tools/jsoncons/tests/src/jsonpath/jsonpath_error_tests.cpp
SheldonHH/eosio.cdt
64448283307b2daebb7db4df947fafd3fc56a83c
[ "MIT" ]
594
2018-09-06T02:03:01.000Z
2022-03-23T19:18:26.000Z
tools/jsoncons/tests/src/jsonpath/jsonpath_error_tests.cpp
SheldonHH/eosio.cdt
64448283307b2daebb7db4df947fafd3fc56a83c
[ "MIT" ]
349
2018-09-06T05:02:09.000Z
2022-03-12T11:07:17.000Z
// Copyright 2013 Daniel Parker // Distributed under Boost license #ifdef __linux__ #define BOOST_TEST_DYN_LINK #endif #include <boost/test/unit_test.hpp> #include <sstream> #include <vector> #include <utility> #include <ctime> #include <new> #include <jsoncons/json.hpp> #include <jsoncons_ext/jsonpath/json_query.hpp> using namespace jsoncons; using namespace jsoncons::jsonpath; BOOST_AUTO_TEST_SUITE(jsonpath_error_tests) struct jsonpath_fixture { static const char* store_text() { static const char* text = "{ \"store\": {\"book\": [ { \"category\": \"reference\",\"author\": \"Nigel Rees\",\"title\": \"Sayings of the Century\",\"price\": 8.95},{ \"category\": \"fiction\",\"author\": \"Evelyn Waugh\",\"title\": \"Sword of Honour\",\"price\": 12.99},{ \"category\": \"fiction\",\"author\": \"Herman Melville\",\"title\": \"Moby Dick\",\"isbn\": \"0-553-21311-3\",\"price\": 8.99},{ \"category\": \"fiction\",\"author\": \"J. R. R. Tolkien\",\"title\": \"The Lord of the Rings\",\"isbn\": \"0-395-19395-8\",\"price\": 22.99}],\"bicycle\": {\"color\": \"red\",\"price\": 19.95}}}"; return text; } static const char* store_text_empty_isbn() { static const char* text = "{ \"store\": {\"book\": [ { \"category\": \"reference\",\"author\": \"Nigel Rees\",\"title\": \"Sayings of the Century\",\"price\": 8.95},{ \"category\": \"fiction\",\"author\": \"Evelyn Waugh\",\"title\": \"Sword of Honour\",\"price\": 12.99},{ \"category\": \"fiction\",\"author\": \"Herman Melville\",\"title\": \"Moby Dick\",\"isbn\": \"0-553-21311-3\",\"price\": 8.99},{ \"category\": \"fiction\",\"author\": \"J. R. R. Tolkien\",\"title\": \"The Lord of the Rings\",\"isbn\": \"\",\"price\": 22.99}],\"bicycle\": {\"color\": \"red\",\"price\": 19.95}}}"; return text; } static const char* book_text() { static const char* text = "{ \"category\": \"reference\",\"author\": \"Nigel Rees\",\"title\": \"Sayings of the Century\",\"price\": 8.95}"; return text; } json book() { json root = json::parse(jsonpath_fixture::store_text()); json book = root["store"]["book"]; return book; } json bicycle() { json root = json::parse(jsonpath_fixture::store_text()); json bicycle = root["store"]["bicycle"]; return bicycle; } }; void test_error_code(const json& root, const std::string& path, int value, const std::error_category& category, size_t line, size_t column) { try { json result = json_query(root,path); BOOST_FAIL(path); } catch (const parse_error& e) { BOOST_CHECK_MESSAGE(e.code().value() == value && e.code().category() == category, e.what()); BOOST_CHECK_MESSAGE(e.line_number() == line, e.what()); BOOST_CHECK_MESSAGE(e.column_number() == column, e.what()); } } void test_error_code(const json& root, const std::string& path, std::error_code value, size_t line, size_t column) { try { json result = json_query(root,path); BOOST_FAIL(path); } catch (const parse_error& e) { BOOST_CHECK_MESSAGE(e.code() == value, e.what()); BOOST_CHECK_MESSAGE(e.line_number() == line, e.what()); BOOST_CHECK_MESSAGE(e.column_number() == column, e.what()); } } BOOST_AUTO_TEST_CASE(test_root_error) { json root = json::parse(jsonpath_fixture::store_text()); test_error_code(root, "..*", jsonpath_parser_errc::expected_root,1,1); } BOOST_AUTO_TEST_CASE(test_right_bracket_error) { json root = json::parse(jsonpath_fixture::store_text()); test_error_code(root, "$['store']['book'[*]", jsonpath_parser_errc::expected_right_bracket,1,18); } BOOST_AUTO_TEST_CASE(test_dot_dot_dot) { json root = json::parse(jsonpath_fixture::store_text()); test_error_code(root, "$.store...price", jsonpath_parser_errc::expected_name,1,10); } BOOST_AUTO_TEST_CASE(test_dot_star_name) { json root = json::parse(jsonpath_fixture::store_text()); test_error_code(root, "$.store.*price", jsonpath_parser_errc::expected_separator,1,10); } BOOST_AUTO_TEST_CASE(test_filter_error) { json root = json::parse(jsonpath_fixture::store_text()); test_error_code(root, "$..book[?(.price<10)]", json_parse_errc::invalid_json_text,1,17); } BOOST_AUTO_TEST_SUITE_END()
35.284553
608
0.62765
SheldonHH
24edf49e181944da98af31a868f2d29d7553e08a
1,387
cpp
C++
general/occa.cpp
benzwick/mfem
4d5fdfd553b24ff37716f736f83df2d238d9a696
[ "BSD-3-Clause" ]
1
2020-08-15T07:00:22.000Z
2020-08-15T07:00:22.000Z
general/occa.cpp
benzwick/mfem
4d5fdfd553b24ff37716f736f83df2d238d9a696
[ "BSD-3-Clause" ]
1
2019-04-24T21:18:24.000Z
2019-04-25T18:00:45.000Z
general/occa.cpp
benzwick/mfem
4d5fdfd553b24ff37716f736f83df2d238d9a696
[ "BSD-3-Clause" ]
1
2021-09-15T14:14:29.000Z
2021-09-15T14:14:29.000Z
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "occa.hpp" #ifdef MFEM_USE_OCCA #include "device.hpp" #if defined(MFEM_USE_CUDA) && OCCA_CUDA_ENABLED #include <occa/modes/cuda/utils.hpp> #endif namespace mfem { // This variable is defined in device.cpp: namespace internal { extern occa::device occaDevice; } occa::device &OccaDev() { return internal::occaDevice; } occa::memory OccaMemoryWrap(void *ptr, std::size_t bytes) { #if defined(MFEM_USE_CUDA) && OCCA_CUDA_ENABLED // If OCCA_CUDA is allowed, it will be used since it has the highest priority if (Device::Allows(Backend::OCCA_CUDA)) { return occa::cuda::wrapMemory(internal::occaDevice, ptr, bytes); } #endif // MFEM_USE_CUDA && OCCA_CUDA_ENABLED // otherwise, fallback to occa::cpu address space return occa::cpu::wrapMemory(internal::occaDevice, ptr, bytes); } } // namespace mfem #endif // MFEM_USE_OCCA
30.822222
80
0.740447
benzwick
24f2abc15752f49ebf22d4295f33d62b280dd16a
432
hpp
C++
src/gs/gsTundraTextureGenerator.hpp
frmr/gs
b9721ad27f59ca2e19f637bccd9eba32b663b6a3
[ "MIT" ]
2
2016-12-06T17:51:30.000Z
2018-06-21T08:52:58.000Z
src/gs/gsTundraTextureGenerator.hpp
frmr/gs
b9721ad27f59ca2e19f637bccd9eba32b663b6a3
[ "MIT" ]
null
null
null
src/gs/gsTundraTextureGenerator.hpp
frmr/gs
b9721ad27f59ca2e19f637bccd9eba32b663b6a3
[ "MIT" ]
null
null
null
#pragma once #include "gsLandTile.hpp" #include "gsColor.hpp" #include <vector> #include "../FastNoise/FastNoise.h" namespace gs { class TundraTextureGenerator { private: static const std::vector<gs::Vec3d> colors; static const std::vector<float> limits; FastNoise noiseA; FastNoise noiseB; public: gs::Color Sample(const gs::Vec3d& coord, const gs::LandTile::Terrain terrain); TundraTextureGenerator(); }; }
17.28
80
0.722222
frmr
24f4d724ede6f8e8482fe1bab8097ce7277e0eb2
3,237
hh
C++
ACAP_linux/3rd/CoMISo/NSolver/FiniteElementLogBarrier.hh
shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer
8c9afe017769f9554706bcd267b6861c4c144999
[ "MIT" ]
216
2018-09-09T11:53:56.000Z
2022-03-19T13:41:35.000Z
ACAP_linux/3rd/CoMISo/NSolver/FiniteElementLogBarrier.hh
gaolinorange/Automatic-Unpaired-Shape-Deformation-Transfer
8c9afe017769f9554706bcd267b6861c4c144999
[ "MIT" ]
13
2018-10-23T08:29:09.000Z
2021-09-08T06:45:34.000Z
ACAP_linux/3rd/CoMISo/NSolver/FiniteElementLogBarrier.hh
shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer
8c9afe017769f9554706bcd267b6861c4c144999
[ "MIT" ]
41
2018-09-13T08:50:41.000Z
2022-02-23T00:33:54.000Z
//============================================================================= // // CLASS FiniteElementLogBarrier // //============================================================================= #ifndef COMISO_FINITEELEMENTLOGBARRIER_HH #define COMISO_FINITEELEMENTLOGBARRIER_HH //== INCLUDES ================================================================= #include <CoMISo/Config/CoMISoDefines.hh> #include "NProblemInterface.hh" //== FORWARDDECLARATIONS ====================================================== //== NAMESPACES =============================================================== namespace COMISO { //== CLASS DEFINITION ========================================================= /** \class FiniteElementLogBarrierLowerBound Implements function of the type f(x) = -c1*log(x-c0) with constants (c0,c1) A more elaborate description follows. */ class FiniteElementLogBarrierLowerBound { public: // define dimensions const static int NV = 1; const static int NC = 2; typedef Eigen::Matrix<size_t,NV,1> VecI; typedef Eigen::Matrix<double,NV,1> VecV; typedef Eigen::Matrix<double,NC,1> VecC; typedef Eigen::Triplet<double> Triplet; inline double eval_f (const VecV& _x, const VecC& _c) const { return -_c[1]*std::log(_x[0]-_c[0]); } inline void eval_gradient(const VecV& _x, const VecC& _c, VecV& _g) const { _g[0] = -_c[1]/(_x[0]-_c[0]); } inline void eval_hessian (const VecV& _x, const VecC& _c, std::vector<Triplet>& _triplets) const { _triplets.clear(); _triplets.push_back(Triplet(0,0,_c[1]/std::pow(_x[0]-_c[0],2))); } inline double max_feasible_step(const VecV& _x, const VecV& _v, const VecC& _c) { if(_v[0] >=0.0) return DBL_MAX; else return 0.999*(_c[0]-_x[0])/_v[0]; } }; /** \class FiniteElementLogBarrierUpperBound Implements function of the type f(x) = -c1*log(c0-x) with constants (c0,c1) A more elaborate description follows. */ class FiniteElementLogBarrierUpperBound { public: // define dimensions const static int NV = 1; const static int NC = 2; typedef Eigen::Matrix<size_t,NV,1> VecI; typedef Eigen::Matrix<double,NV,1> VecV; typedef Eigen::Matrix<double,NC,1> VecC; typedef Eigen::Triplet<double> Triplet; inline double eval_f (const VecV& _x, const VecC& _c) const { return -_c[1]*std::log(_c[0]-_x[0]); } inline void eval_gradient(const VecV& _x, const VecC& _c, VecV& _g) const { _g[0] = _c[1]/(_c[0]-_x[0]); } inline void eval_hessian (const VecV& _x, const VecC& _c, std::vector<Triplet>& _triplets) const { _triplets.clear(); _triplets.push_back(Triplet(0,0,_c[1]/std::pow(_c[0]-_x[0],2))); } inline double max_feasible_step(const VecV& _x, const VecV& _v, const VecC& _c) { if(_v[0] <=0.0) return DBL_MAX; else return 0.999*(_c[0]-_x[0])/_v[0]; } }; //============================================================================= } // namespace COMISO //============================================================================= #endif // COMISO_FINITEELEMENTLOGBARRIER_HH defined //=============================================================================
25.488189
100
0.531047
shubhMaheshwari
24f4e64bc56fa15c9f344524594aacc9f448f597
2,464
cpp
C++
devices/GNSS/NMEA/src/GGAProcessor.cpp
gboyraz/macchina.io
3e26fea95e87512459693831242b297f0780cc21
[ "Apache-2.0" ]
2
2020-11-23T23:37:00.000Z
2020-12-22T04:02:41.000Z
devices/GNSS/NMEA/src/GGAProcessor.cpp
gboyraz/macchina.io
3e26fea95e87512459693831242b297f0780cc21
[ "Apache-2.0" ]
null
null
null
devices/GNSS/NMEA/src/GGAProcessor.cpp
gboyraz/macchina.io
3e26fea95e87512459693831242b297f0780cc21
[ "Apache-2.0" ]
1
2020-11-23T23:37:09.000Z
2020-11-23T23:37:09.000Z
// // GGAProcessor.cpp // // Library: IoT/GNSS/NMEA // Package: Sentences // Module: GGAProcessor // // Copyright (c) 2010-2015, Applied Informatics Software Engineering GmbH. // All rights reserved. // // SPDX-License-Identifier: Apache-2.0 // #include "IoT/GNSS/NMEA/GGAProcessor.h" #include "Poco/DateTimeParser.h" #include "Poco/DateTime.h" #include "Poco/NumberParser.h" #include <cmath> namespace IoT { namespace GNSS { namespace NMEA { GGAProcessor::GGAProcessor() { } GGAProcessor::~GGAProcessor() { } void GGAProcessor::processSentence(const Sentence& sentence) { if (sentence.type() == "GGA" && sentence.size() > 9) { bool valid = true; GGA gga; try { if (!sentence[0].empty()) { std::string timeStr = sentence[0]; int tzd; Poco::DateTime dt = Poco::DateTimeParser::parse("%H%M%s", timeStr, tzd); Poco::DateTime now; gga.utc = Poco::DateTime(now.year(), now.month(), now.day(), dt.hour(), dt.minute(), dt.second()).timestamp(); } else { gga.utc.update(); } if (!sentence[1].empty() && !sentence[3].empty()) { double lat = Poco::NumberParser::parseFloat(sentence[1]); double latDeg = std::floor(lat/100); double latMin = lat - 100*latDeg; latDeg += latMin/60; if (sentence[2] == "S") latDeg = -latDeg; double lon = Poco::NumberParser::parseFloat(sentence[3]); double lonDeg = std::floor(lon/100); double lonMin = lon - 100*lonDeg; lonDeg += lonMin/60; if (sentence[4] == "W") lonDeg = -lonDeg; gga.position.assign(Poco::Geo::Angle::fromDegreesLatitude(latDeg), Poco::Geo::Angle::fromDegreesLongitude(lonDeg)); } else { valid = false; } if (!sentence[5].empty()) { gga.quality = static_cast<FixQuality>(Poco::NumberParser::parseFloat(sentence[5])); } else { gga.quality = FIX_UNKNOWN; } if (!sentence[6].empty()) { gga.satellitesInView = Poco::NumberParser::parseFloat(sentence[6]); } else { gga.satellitesInView = 0; } if (!sentence[7].empty()) { gga.hdop = Poco::NumberParser::parseFloat(sentence[7]); } else { gga.hdop = -9999; } if (!sentence[8].empty()) { gga.altitude = Poco::NumberParser::parseFloat(sentence[8]); } else { gga.altitude = -9999; } } catch (Poco::Exception&) { valid = false; } if (valid) { ggaReceived(this, gga); } } } } } } // namespace IoT::GNSS::NMEA
19.25
119
0.609172
gboyraz
24faecdf69e9cb2a9a9a76567079c752184286af
27,128
cpp
C++
src/Kiln.cpp
0xc0dec/kiln
4fbaf31a2f9e07f1dca7af2bed86f479e0079fa5
[ "MIT" ]
null
null
null
src/Kiln.cpp
0xc0dec/kiln
4fbaf31a2f9e07f1dca7af2bed86f479e0079fa5
[ "MIT" ]
null
null
null
src/Kiln.cpp
0xc0dec/kiln
4fbaf31a2f9e07f1dca7af2bed86f479e0079fa5
[ "MIT" ]
null
null
null
// TODO Refactor ImageData/Font using pointers avoiding pimpl // TODO Font geometry and rendering // TODO Use shaderc (see Granite project on Github) /* Copyright (c) Aleksey Fedotov MIT license */ #include "Input.h" #include "FileSystem.h" #include "Spectator.h" #include "Camera.h" #include "Window.h" #include "ImageData.h" #include "MeshData.h" #include "Font.h" #include "Vulkan/Vulkan.h" #include "Vulkan/VulkanDevice.h" #include "Vulkan/VulkanRenderPass.h" #include "Vulkan/VulkanSwapchain.h" #include "Vulkan/VulkanDescriptorPool.h" #include "Vulkan/VulkanBuffer.h" #include "Vulkan/VulkanPipeline.h" #include "Vulkan/VulkanDescriptorSetLayoutBuilder.h" #include "Vulkan/VulkanImage.h" #include "Vulkan/VulkanDescriptorSetUpdater.h" #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/transform.inl> #include <glm/gtc/matrix_transform.inl> #include <vector> static const std::vector<float> xAxisVertexData = { 0, 0, 0, 1, 0, 0 }; static const std::vector<float> yAxisVertexData = { 0, 0, 0, 0, 1, 0 }; static const std::vector<float> zAxisVertexData = { 0, 0, 0, 0, 0, 1 }; static const std::vector<float> quadVertexData = { 1, 1, 0, 1, 0, -1, 1, 0, 0, 0, -1, -1, 0, 0, 1, 1, 1, 0, 1, 0, -1, -1, 0, 0, 1, 1, -1, 0, 1, 1 }; class Scene { public: Scene(const vk::Device &device) { viewMatricesBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(viewMatrices)); descPool = vk::DescriptorPool(device, 20, vk::DescriptorPoolConfig() .forDescriptors(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 20) .forDescriptors(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 20)); descSetLayout = vk::DescriptorSetLayoutBuilder(device) .withBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS) .build(); descSet = descPool.allocateSet(descSetLayout); vk::DescriptorSetUpdater(device) .forUniformBuffer(0, descSet, viewMatricesBuffer, 0, sizeof(viewMatrices)) .updateSets(); } void update(const Camera &cam) { viewMatrices.proj = cam.getProjectionMatrix(); viewMatrices.view = cam.getViewMatrix(); viewMatricesBuffer.update(&viewMatrices); } auto getDescPool() -> vk::DescriptorPool& { return descPool; } auto getDescSetLayout() const -> VkDescriptorSetLayout { return descSetLayout; } auto getDescSet() const -> VkDescriptorSet { return descSet; } private: vk::DescriptorPool descPool; vk::Resource<VkDescriptorSetLayout> descSetLayout; VkDescriptorSet descSet; struct { glm::mat4 proj; glm::mat4 view; } viewMatrices; vk::Buffer viewMatricesBuffer; }; class Offscreen { public: Offscreen(const vk::Device &device, uint32_t canvasWidth, uint32_t canvasHeight) { colorAttachment = vk::Image(device, canvasWidth, canvasHeight, 1, 1, VK_FORMAT_R8G8B8A8_UNORM, 0, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT); depthAttachment = vk::Image(device, canvasWidth, canvasHeight, 1, 1, device.getDepthFormat(), 0, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT); renderPass = vk::RenderPass(device, vk::RenderPassConfig() .withColorAttachment(VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, true, {0, 1, 1, 0}) .withDepthAttachment(device.getDepthFormat(), true, {1, 0})); frameBuffer = createFrameBuffer(device, colorAttachment.getView(), depthAttachment.getView(), renderPass, canvasWidth, canvasHeight); semaphore = createSemaphore(device); commandBuffer = createCommandBuffer(device, device.getCommandPool()); } auto getColorAttachment() -> vk::Image& { return colorAttachment; } auto getRenderPass() -> vk::RenderPass& { return renderPass; } auto getSemaphore() -> vk::Resource<VkSemaphore>& { return semaphore; } auto getCommandBuffer() -> vk::Resource<VkCommandBuffer>& { return commandBuffer; } auto getFrameBuffer() const -> VkFramebuffer { return frameBuffer; } private: vk::Image colorAttachment; vk::Image depthAttachment; vk::Resource<VkFramebuffer> frameBuffer; vk::RenderPass renderPass; vk::Resource<VkSemaphore> semaphore; vk::Resource<VkCommandBuffer> commandBuffer; }; class Mesh { public: Mesh(const vk::Device &device, VkRenderPass renderPass, Scene &scene): globalDescSet(scene.getDescSet()) { auto vsSrc = fs::readBytes("../../assets/shaders/Mesh.vert.spv"); auto fsSrc = fs::readBytes("../../assets/shaders/Mesh.frag.spv"); auto vs = createShader(device, vsSrc.data(), vsSrc.size()); auto fs = createShader(device, fsSrc.data(), fsSrc.size()); glm::mat4 modelMatrix{}; modelMatrixBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::mat4)); modelMatrixBuffer.update(&modelMatrix); auto data = MeshData::load("../../assets/meshes/Teapot.obj"); vertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * data.getVertexData().size(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, data.getVertexData().data()); indexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(uint32_t) * data.getIndexData().size(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT, data.getIndexData().data()); indexCount = data.getIndexData().size(); descSetLayout = vk::DescriptorSetLayoutBuilder(device) .withBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS) .withBinding(1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT) .build(); pipeline = vk::Pipeline(device, renderPass, vk::PipelineConfig(vs, fs) .withDescriptorSetLayout(scene.getDescSetLayout()) .withDescriptorSetLayout(descSetLayout) .withFrontFace(VK_FRONT_FACE_CLOCKWISE) .withCullMode(VK_CULL_MODE_NONE) .withTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST) .withVertexFormat(data.getFormat())); descSet = scene.getDescPool().allocateSet(descSetLayout); const auto textureData = ImageData::load2D("../../assets/textures/Cobblestone.png"); texture = vk::Image::create2D(device, textureData); vk::DescriptorSetUpdater(device) .forUniformBuffer(0, descSet, modelMatrixBuffer, 0, sizeof(modelMatrix)) .forTexture(1, descSet, texture.getView(), texture.getSampler(), texture.getLayout()) .updateSets(); } void render(VkCommandBuffer buf) { VkBuffer vertexBuffer = this->vertexBuffer; VkDeviceSize vertexBufferOffset = 0; std::vector<VkDescriptorSet> descSets = {globalDescSet, descSet}; vkCmdBindPipeline(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr); vkCmdBindVertexBuffers(buf, 0, 1, &vertexBuffer, &vertexBufferOffset); vkCmdBindIndexBuffer(buf, indexBuffer, 0, VK_INDEX_TYPE_UINT32); vkCmdDrawIndexed(buf, indexCount, 1, 0, 0, 0); } private: vk::Resource<VkDescriptorSetLayout> descSetLayout; vk::Pipeline pipeline; vk::Image texture; vk::Buffer modelMatrixBuffer; vk::Buffer vertexBuffer; vk::Buffer indexBuffer; uint32_t indexCount; VkDescriptorSet descSet; VkDescriptorSet globalDescSet; }; class PostProcessor { public: PostProcessor(const vk::Device &device, Offscreen &offscreen, Scene &scene) { auto vsSrc = fs::readBytes("../../assets/shaders/PostProcess.vert.spv"); auto fsSrc = fs::readBytes("../../assets/shaders/PostProcess.frag.spv"); const auto vs = createShader(device, vsSrc.data(), vsSrc.size()); const auto fs = createShader(device, fsSrc.data(), fsSrc.size()); vertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * quadVertexData.size(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, quadVertexData.data()); descSetLayout = vk::DescriptorSetLayoutBuilder(device) .withBinding(0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT) .build(); pipeline = vk::Pipeline(device, offscreen.getRenderPass(), vk::PipelineConfig(vs, fs) .withDepthTest(false, false) .withDescriptorSetLayout(descSetLayout) .withFrontFace(VK_FRONT_FACE_CLOCKWISE) .withCullMode(VK_CULL_MODE_NONE) .withTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST) .withVertexFormat(VertexFormat{{3, 2}})); descSet = scene.getDescPool().allocateSet(descSetLayout); auto &colorAttachment = offscreen.getColorAttachment(); vk::DescriptorSetUpdater(device) .forTexture(0, descSet, colorAttachment.getView(), colorAttachment.getSampler(), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) .updateSets(); } void render(VkCommandBuffer buf) { std::vector<VkBuffer> vertexBuffers = {vertexBuffer}; std::vector<VkDeviceSize> vertexBufferOffsets = {0}; std::vector<VkDescriptorSet> descSets = {descSet}; vkCmdBindPipeline(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 1, descSets.data(), 0, nullptr); vkCmdBindVertexBuffers(buf, 0, 1, vertexBuffers.data(), vertexBufferOffsets.data()); vkCmdDraw(buf, 6, 1, 0, 0); } private: vk::Resource<VkDescriptorSetLayout> descSetLayout; vk::Pipeline pipeline; vk::Image texture; vk::Buffer modelMatrixBuffer; vk::Buffer vertexBuffer; VkDescriptorSet descSet; }; class Skybox { public: Skybox(const vk::Device &device, Offscreen &offscreen, Scene &scene): globalDescSet(scene.getDescSet()) { auto vsSrc = fs::readBytes("../../assets/shaders/Skybox.vert.spv"); auto fsSrc = fs::readBytes("../../assets/shaders/Skybox.frag.spv"); const auto vs = createShader(device, vsSrc.data(), vsSrc.size()); const auto fs = createShader(device, fsSrc.data(), fsSrc.size()); glm::mat4 modelMatrix{}; modelMatrixBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::mat4)); modelMatrixBuffer.update(&modelMatrix); vertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * quadVertexData.size(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, quadVertexData.data()); descSetLayout = vk::DescriptorSetLayoutBuilder(device) .withBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS) .withBinding(1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT) .build(); pipeline = vk::Pipeline(device, offscreen.getRenderPass(), vk::PipelineConfig(vs, fs) .withDepthTest(false, false) .withDescriptorSetLayout(scene.getDescSetLayout()) .withDescriptorSetLayout(descSetLayout) .withFrontFace(VK_FRONT_FACE_CLOCKWISE) .withCullMode(VK_CULL_MODE_NONE) .withTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST) .withVertexBinding(0, sizeof(float) * 5, VK_VERTEX_INPUT_RATE_VERTEX) .withVertexAttribute(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0) .withVertexAttribute(1, 0, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 3)); descSet = scene.getDescPool().allocateSet(descSetLayout); const auto data = ImageData::loadCube("../../assets/textures/Cubemap_space.ktx"); texture = vk::Image::createCube(device, data); vk::DescriptorSetUpdater(device) .forUniformBuffer(0, descSet, modelMatrixBuffer, 0, sizeof(modelMatrix)) .forTexture(1, descSet, texture.getView(), texture.getSampler(), texture.getLayout()) .updateSets(); } void render(VkCommandBuffer buf) { std::vector<VkBuffer> vertexBuffers = {vertexBuffer}; std::vector<VkDeviceSize> vertexBufferOffsets = {0}; std::vector<VkDescriptorSet> descSets = {globalDescSet, descSet}; vkCmdBindPipeline(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr); vkCmdBindVertexBuffers(buf, 0, 1, vertexBuffers.data(), vertexBufferOffsets.data()); vkCmdDraw(buf, 6, 1, 0, 0); } private: vk::Resource<VkDescriptorSetLayout> descSetLayout; vk::Pipeline pipeline; vk::Image texture; vk::Buffer modelMatrixBuffer; vk::Buffer vertexBuffer; VkDescriptorSet descSet; VkDescriptorSet globalDescSet; }; class Axes { public: Axes(const vk::Device &device, Offscreen &offscreen, Scene &scene): globalDescSet(scene.getDescSet()) { Transform t; t.setLocalPosition({3, 0, 3}); auto modelMatrix = t.getWorldMatrix(); modelMatrixBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::mat4)); modelMatrixBuffer.update(&modelMatrix); glm::vec3 red{1.0f, 0, 0}; redColorUniformBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::vec3)); redColorUniformBuffer.update(&red); glm::vec3 green{0, 1.0f, 0}; greenColorUniformBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::vec3)); greenColorUniformBuffer.update(&green); glm::vec3 blue{0, 0, 1.0f}; blueColorUniformBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::vec3)); blueColorUniformBuffer.update(&blue); auto vsSrc = fs::readBytes("../../assets/shaders/Axis.vert.spv"); auto fsSrc = fs::readBytes("../../assets/shaders/Axis.frag.spv"); const auto vs = createShader(device, vsSrc.data(), vsSrc.size()); const auto fs = createShader(device, fsSrc.data(), fsSrc.size()); xAxisVertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * xAxisVertexData.size(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, xAxisVertexData.data()); yAxisVertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * yAxisVertexData.size(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, yAxisVertexData.data()); zAxisVertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * zAxisVertexData.size(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, zAxisVertexData.data()); descSetLayout = vk::DescriptorSetLayoutBuilder(device) .withBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS) .withBinding(1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS) .build(); pipeline = vk::Pipeline(device, offscreen.getRenderPass(), vk::PipelineConfig(vs, fs) .withDescriptorSetLayout(scene.getDescSetLayout()) .withDescriptorSetLayout(descSetLayout) .withFrontFace(VK_FRONT_FACE_CLOCKWISE) .withCullMode(VK_CULL_MODE_NONE) .withTopology(VK_PRIMITIVE_TOPOLOGY_LINE_LIST) .withVertexBinding(0, sizeof(float) * 3, VK_VERTEX_INPUT_RATE_VERTEX) .withVertexAttribute(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0)); redDescSet = scene.getDescPool().allocateSet(descSetLayout); greenDescSet = scene.getDescPool().allocateSet(descSetLayout); blueDescSet = scene.getDescPool().allocateSet(descSetLayout); vk::DescriptorSetUpdater(device) .forUniformBuffer(0, redDescSet, modelMatrixBuffer, 0, sizeof(modelMatrix)) .forUniformBuffer(1, redDescSet, redColorUniformBuffer, 0, sizeof(glm::vec3)) .updateSets(); vk::DescriptorSetUpdater(device) .forUniformBuffer(0, greenDescSet, modelMatrixBuffer, 0, sizeof(modelMatrix)) .forUniformBuffer(1, greenDescSet, greenColorUniformBuffer, 0, sizeof(glm::vec3)) .updateSets(); vk::DescriptorSetUpdater(device) .forUniformBuffer(0, blueDescSet, modelMatrixBuffer, 0, sizeof(modelMatrix)) .forUniformBuffer(1, blueDescSet, blueColorUniformBuffer, 0, sizeof(glm::vec3)) .updateSets(); } void render(VkCommandBuffer buf) { vkCmdBindPipeline(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); std::vector<VkDescriptorSet> descSets = {globalDescSet, redDescSet}; std::vector<VkDeviceSize> vertexBufferOffsets = {0}; // TODO bind all at once std::vector<VkBuffer> vertexBuffers = {xAxisVertexBuffer}; vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr); vkCmdBindVertexBuffers(buf, 0, 1, vertexBuffers.data(), vertexBufferOffsets.data()); vkCmdDraw(buf, 4, 1, 0, 0); vertexBuffers[0] = yAxisVertexBuffer; descSets[1] = greenDescSet; vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr); vkCmdBindVertexBuffers(buf, 0, 1, vertexBuffers.data(), vertexBufferOffsets.data()); vkCmdDraw(buf, 4, 1, 0, 0); vertexBuffers[0] = zAxisVertexBuffer; descSets[1] = blueDescSet; vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr); vkCmdBindVertexBuffers(buf, 0, 1, vertexBuffers.data(), vertexBufferOffsets.data()); vkCmdDraw(buf, 4, 1, 0, 0); } private: vk::Resource<VkDescriptorSetLayout> descSetLayout; vk::Pipeline pipeline; vk::Buffer redColorUniformBuffer; vk::Buffer greenColorUniformBuffer; vk::Buffer blueColorUniformBuffer; vk::Buffer xAxisVertexBuffer; vk::Buffer yAxisVertexBuffer; vk::Buffer zAxisVertexBuffer; vk::Buffer modelMatrixBuffer; VkDescriptorSet redDescSet; VkDescriptorSet greenDescSet; VkDescriptorSet blueDescSet; VkDescriptorSet globalDescSet; }; class Label { public: Label(const vk::Device &device, const std::string &text, VkRenderPass renderPass, Scene &scene): globalDescSet(scene.getDescSet()) { const auto fontData = fs::readBytes("../../assets/Aller.ttf"); font = Font::createTrueType(device, fontData, 100, 2048, 2048, ' ', '~' - ' ', 2, 2); std::vector<float> vertexData; std::vector<uint32_t> indexData; uint16_t lastIndex = 0; float offsetX = 0, offsetY = 0; for (auto c : text) { const auto glyphInfo = font.getGlyphInfo(c, offsetX, offsetY); offsetX = glyphInfo.offsetX; offsetY = glyphInfo.offsetY; vertexData.push_back(glyphInfo.positions[0].x); vertexData.push_back(glyphInfo.positions[0].y); vertexData.push_back(glyphInfo.positions[0].z); vertexData.push_back(glyphInfo.uvs[0].x); vertexData.push_back(glyphInfo.uvs[0].y); vertexData.push_back(glyphInfo.positions[1].x); vertexData.push_back(glyphInfo.positions[1].y); vertexData.push_back(glyphInfo.positions[1].z); vertexData.push_back(glyphInfo.uvs[1].x); vertexData.push_back(glyphInfo.uvs[1].y); vertexData.push_back(glyphInfo.positions[2].x); vertexData.push_back(glyphInfo.positions[2].y); vertexData.push_back(glyphInfo.positions[2].z); vertexData.push_back(glyphInfo.uvs[2].x); vertexData.push_back(glyphInfo.uvs[2].y); vertexData.push_back(glyphInfo.positions[3].x); vertexData.push_back(glyphInfo.positions[3].y); vertexData.push_back(glyphInfo.positions[3].z); vertexData.push_back(glyphInfo.uvs[3].x); vertexData.push_back(glyphInfo.uvs[3].y); indexData.push_back(lastIndex); indexData.push_back(lastIndex + 1); indexData.push_back(lastIndex + 2); indexData.push_back(lastIndex); indexData.push_back(lastIndex + 2); indexData.push_back(lastIndex + 3); lastIndex += 4; } auto vsSrc = fs::readBytes("../../assets/shaders/Font.vert.spv"); auto fsSrc = fs::readBytes("../../assets/shaders/Font.frag.spv"); const auto vs = createShader(device, vsSrc.data(), vsSrc.size()); const auto fs = createShader(device, fsSrc.data(), fsSrc.size()); Transform t; t.setLocalScale({0.05f, 0.05f, 0.05f}); t.setLocalPosition({0, 0, 4}); auto modelMatrix = t.getWorldMatrix(); modelMatrixBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::mat4)); modelMatrixBuffer.update(&modelMatrix); vertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * vertexData.size(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, vertexData.data()); indexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(uint32_t) * indexData.size(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT, indexData.data()); indexCount = indexData.size(); descSetLayout = vk::DescriptorSetLayoutBuilder(device) .withBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS) .withBinding(1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT) .build(); const auto vf = VertexFormat({3, 2}); pipeline = vk::Pipeline(device, renderPass, vk::PipelineConfig(vs, fs) .withDescriptorSetLayout(scene.getDescSetLayout()) .withDescriptorSetLayout(descSetLayout) .withFrontFace(VK_FRONT_FACE_CLOCKWISE) .withCullMode(VK_CULL_MODE_NONE) .withBlend(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE) .withTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST) .withVertexFormat(vf)); descSet = scene.getDescPool().allocateSet(descSetLayout); vk::DescriptorSetUpdater(device) .forUniformBuffer(0, descSet, modelMatrixBuffer, 0, sizeof(modelMatrix)) .forTexture(1, descSet, font.getAtlas().getView(), font.getAtlas().getSampler(), font.getAtlas().getLayout()) .updateSets(); } void render(VkCommandBuffer buf) { VkBuffer vertexBuffer = this->vertexBuffer; VkDeviceSize vertexBufferOffset = 0; std::vector<VkDescriptorSet> descSets = {globalDescSet, descSet}; vkCmdBindPipeline(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr); vkCmdBindVertexBuffers(buf, 0, 1, &vertexBuffer, &vertexBufferOffset); vkCmdBindIndexBuffer(buf, indexBuffer, 0, VK_INDEX_TYPE_UINT32); vkCmdDrawIndexed(buf, indexCount, 1, 0, 0, 0); } private: Font font; vk::Resource<VkDescriptorSetLayout> descSetLayout; vk::Pipeline pipeline; vk::Image texture; vk::Buffer modelMatrixBuffer; vk::Buffer vertexBuffer; vk::Buffer indexBuffer; uint32_t indexCount; VkDescriptorSet descSet; VkDescriptorSet globalDescSet; }; int main() { const uint32_t canvasWidth = 1366; const uint32_t canvasHeight = 768; Window window{canvasWidth, canvasHeight, "Demo"}; auto device = vk::Device::create(window.getPlatformHandle()); auto swapchain = vk::Swapchain(device, canvasWidth, canvasHeight, false); Camera cam; cam.setPerspective(glm::radians(45.0f), canvasWidth / (canvasHeight * 1.0f), 0.01f, 100); cam.getTransform().setLocalPosition({10, -5, 10}); cam.getTransform().lookAt({0, 0, 0}, {0, 1, 0}); Scene scene{device}; Offscreen offscreen{device, canvasWidth, canvasHeight}; Mesh mesh{device, offscreen.getRenderPass(), scene}; PostProcessor postProcessor{device, offscreen, scene}; Skybox skybox{device, offscreen, scene}; Axes axes{device, offscreen, scene}; Label label{device, "Test", offscreen.getRenderPass(), scene}; // Record command buffers { const VkCommandBuffer buf = offscreen.getCommandBuffer(); vk::beginCommandBuffer(buf, false); offscreen.getRenderPass().begin(buf, offscreen.getFrameBuffer(), canvasWidth, canvasHeight); auto vp = VkViewport{0, 0, canvasWidth, canvasHeight, 0, 1}; vkCmdSetViewport(buf, 0, 1, &vp); VkRect2D scissor{{0, 0}, {vp.width, vp.height}}; vkCmdSetScissor(buf, 0, 1, &scissor); skybox.render(buf); axes.render(buf); mesh.render(buf); label.render(buf); offscreen.getRenderPass().end(buf); KL_VK_CHECK_RESULT(vkEndCommandBuffer(buf)); } swapchain.recordCommandBuffers([&](VkFramebuffer fb, VkCommandBuffer buf) { swapchain.getRenderPass().begin(buf, fb, canvasWidth, canvasHeight); auto vp = VkViewport{0, 0, static_cast<float>(canvasWidth), static_cast<float>(canvasHeight), 0, 1}; vkCmdSetViewport(buf, 0, 1, &vp); VkRect2D scissor{{0, 0}, {vp.width, vp.height}}; vkCmdSetScissor(buf, 0, 1, &scissor); postProcessor.render(buf); swapchain.getRenderPass().end(buf); }); // Main loop Input input; while (!window.closeRequested() && !input.isKeyPressed(SDLK_ESCAPE, true)) { window.beginUpdate(input); const auto dt = window.getTimeDelta(); applySpectator(cam.getTransform(), input, dt, 1, 5); scene.update(cam); auto presentCompleteSemaphore = swapchain.acquireNext(); vk::queueSubmit(device.getQueue(), 1, &presentCompleteSemaphore, 1, &offscreen.getSemaphore(), 1, &offscreen.getCommandBuffer()); swapchain.presentNext(device.getQueue(), 1, &offscreen.getSemaphore()); KL_VK_CHECK_RESULT(vkQueueWaitIdle(device.getQueue())); window.endUpdate(); } return 0; }
40.855422
138
0.656812
0xc0dec
70053f070cef049d40b9d50d3bd58b4823cafb54
1,978
cpp
C++
test/main_gtest.cpp
Ali2500/nao_whole_body_ik
5955415c6a248eda2343098407ef0c080b7d60ec
[ "BSD-2-Clause" ]
null
null
null
test/main_gtest.cpp
Ali2500/nao_whole_body_ik
5955415c6a248eda2343098407ef0c080b7d60ec
[ "BSD-2-Clause" ]
null
null
null
test/main_gtest.cpp
Ali2500/nao_whole_body_ik
5955415c6a248eda2343098407ef0c080b7d60ec
[ "BSD-2-Clause" ]
null
null
null
#include "database_reader_test.h" #include "whole_body_ik_solver_test.h" nao_whole_body_ik::DatabaseReader2Ptr database_reader; TEST_F(DatabaseReaderTest, databaseLoadingTest) { ASSERT_TRUE(databaseLoadTest()); } TEST_F(DatabaseReaderTest, DefaultValuesRightArmKNNTest) { ASSERT_TRUE(knnDifferenceDefaultPositionRightArm()); } TEST_F(DatabaseReaderTest, DefaultValuesLeftArmKNNTest) { ASSERT_TRUE(knnDifferenceDefaultPositionLeftArm()); } TEST_F(DatabaseReaderTest, RandomValuesRightArmKNNTest) { ASSERT_TRUE(knnDifferenceRandomPositionRightArm()); } TEST_F(DatabaseReaderTest, RandomValuesLeftArmKNNTest) { ASSERT_TRUE(knnDifferenceRandomPositionLeftArm()); } TEST_F(WholeBodyIKSolverTest, RightArmIKFromDatabaseTest) { SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::RIGHT_ARM_ONLY); ASSERT_TRUE(rightArmIKFromDatabaseTest()); } TEST_F(WholeBodyIKSolverTest, RightArmIKFromSeedTest) { SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::RIGHT_ARM_ONLY); ASSERT_TRUE(rightArmIKSeedTest()); } TEST_F(WholeBodyIKSolverTest, LeftArmIKFromDatabaseTest) { SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::LEFT_ARM_ONLY); ASSERT_TRUE(leftArmIKFromDatabaseTest()); } TEST_F(WholeBodyIKSolverTest, LeftArmIKFromSeedTest) { SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::LEFT_ARM_ONLY); ASSERT_TRUE(leftArmIKSeedTest()); } TEST_F(WholeBodyIKSolverTest, BothArmsIKFromDatabaseTest) { SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::BOTH_ARMS); ASSERT_TRUE(bothArmsIKFromDatabaseTest()); } TEST_F(WholeBodyIKSolverTest, BothArmsIKFromSeedTest) { SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::BOTH_ARMS); ASSERT_TRUE(bothArmsIKSeedTest()); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "gtest_node"); int return_code RUN_ALL_TESTS(); ros::shutdown(); return return_code; }
26.026316
84
0.822042
Ali2500
7006c26b1c4d19162f5f98022c7e12137e9a43ab
4,872
hpp
C++
capo/sequence.hpp
mutouyun/capo
d90528cf5bb59bdf76cdf94dfa6a55bcb1bfdc13
[ "MIT" ]
58
2015-03-22T03:26:07.000Z
2022-03-30T05:15:22.000Z
capo/sequence.hpp
mutouyun/capo
d90528cf5bb59bdf76cdf94dfa6a55bcb1bfdc13
[ "MIT" ]
1
2019-03-07T12:32:41.000Z
2019-03-16T15:01:55.000Z
capo/sequence.hpp
mutouyun/capo
d90528cf5bb59bdf76cdf94dfa6a55bcb1bfdc13
[ "MIT" ]
21
2015-02-27T06:44:56.000Z
2022-03-05T15:53:30.000Z
/* The Capo Library Code covered by the MIT License Author: mutouyun (http://orzz.org) */ #pragma once #include "capo/assert.hpp" #include "capo/iterator.hpp" #include <type_traits> // std::add_const, std::add_lvalue_reference #include <tuple> // std::tuple, std::tie #include <stdexcept> // std::logic_error #include <utility> // std::forward, std::move, std::swap #include <cstddef> // size_t namespace capo { namespace use { //////////////////////////////////////////////////////////////// /// Sequence policies //////////////////////////////////////////////////////////////// /* Arithmetic sequence */ template <int D = 1> struct arithmetic { enum { StateSize = 1 }; template <typename T> static void next(T& a) { a += D; } template <typename T> static void prev(T& a) { a -= D; } template <typename T> static void at(T& a1, size_t n) { CAPO_ASSERT_(n); a1 += D * static_cast<T>(n - 1); } }; /* Geometric sequence */ template <int Q = 2> struct geometric { static_assert(Q != 0, "Q cannot be equal to 0!"); enum { StateSize = 1 }; template <typename T> static void next(T& a) { a *= Q; } template <typename T> static void prev(T& a) { a /= Q; } template <typename T> static void at(T& a1, size_t n) { CAPO_ASSERT_(n); a1 *= power<T>(Q, n - 1); } private: template <typename T> static T power(int x, size_t n) { if (n == 0) return 1; if (x == 0 || x == 1) return x; T k = 1; while (n > 1) { if (n & 0x01) k *= x; x *= x; n >>= 1; } return k *= x; } }; /* Fibonacci sequence */ struct fibonacci { enum { StateSize = 2 }; template <typename T> static void next(T& a1, T& a2) { std::swap(a1, a2); a2 += a1; } template <typename T> static void prev(T& a1, T& a2) { std::swap(a1, a2); a1 -= a2; } template <typename T> static void at(T& a0, T& a1, size_t n) { std::tie(a0, a1) = fib_two(a0, a1, n); } private: template <typename T> static std::tuple<T, T> fib_two(const T& a0, const T& a1, size_t n) { if (n == 1) return std::tuple<T, T>{ a1, a1 + a0 }; if (n == 0) return std::tuple<T, T>{ a0, a1 }; T i, j; if (n & 0x01) /* F(2n + 1) */ { std::tie(i, j) = fib_two(a0, a1, (n - 1) >> 1); // {F(n), F(n + 1)} return std::tuple<T, T> { i * i + j * j, // F(2n + 1) = F(n) ^ 2 + F(n + 1) ^ 2 j * (i * 2 + j) // F(2n + 2) = F(n + 1) * (F(n) * 2 + F(n + 1)) }; } else /* F(2n) */ { std::tie(i, j) = fib_two(a0, a1, n >> 1); // {F(n), F(n + 1)} return std::tuple<T, T> { i * (j * 2 - i), // F(2n) = F(n) * (F(n + 1) * 2 - F(n)) i * i + j * j // F(2n + 1) = F(n) ^ 2 + F(n + 1) ^ 2 }; } } }; } // namespace use namespace detail_sequence { //////////////////////////////////////////////////////////////// /// The impl class //////////////////////////////////////////////////////////////// template <class PolicyT, typename T, class IterT = capo::iterator<PolicyT, T>> class impl { public: using iterator = IterT; using const_iterator = const iterator; using value_type = T; using reference = typename std::add_lvalue_reference<T>::type; using const_reference = typename std::add_lvalue_reference<typename std::add_const<T>::type>::type; using size_type = typename iterator::size_type; private: size_type cur_begin_, cur_end_; typename iterator::tp_t state_; public: template <typename... U> impl(size_type begin, size_type end, U&&... args) : cur_begin_(begin) , cur_end_ (end) , state_ (std::forward<U>(args)...) { CAPO_ENSURE_(cur_begin_ < cur_end_)(cur_begin_)(cur_end_) .except(std::logic_error("End index must be greater than begin index.")); } size_type size(void) const { return (cur_end_ - cur_begin_); } const_iterator begin(void) const { return { state_, cur_begin_ }; } const_iterator end(void) const { return { state_, cur_end_ }; } }; } // namespace detail_sequence //////////////////////////////////////////////////////////////// /// Make a sequence of [begin-index, end-index) //////////////////////////////////////////////////////////////// template <class PolicyT, typename T, typename... U> auto sequence(size_t begin, size_t end, U&&... args) -> detail_sequence::impl<PolicyT, T> { return { begin, end, std::forward<U>(args)... }; } } // namespace capo
24.984615
103
0.476396
mutouyun
701178a3f85e3f48ee623745c6709532f279d4f5
766
cc
C++
2021_1004_1010/265.cc
guohaoqiang/leetcode
802447c029c36892e8dd7391c825bcfc7ac0fd0b
[ "MIT" ]
null
null
null
2021_1004_1010/265.cc
guohaoqiang/leetcode
802447c029c36892e8dd7391c825bcfc7ac0fd0b
[ "MIT" ]
null
null
null
2021_1004_1010/265.cc
guohaoqiang/leetcode
802447c029c36892e8dd7391c825bcfc7ac0fd0b
[ "MIT" ]
null
null
null
class Solution { public: int minCostII(vector<vector<int>>& costs) { int n = costs.size(); int k = costs.at(0).size(); vector<vector<int>> dp(n, vector<int>(k,2021)); for (int i=0; i<k; ++i){ dp.at(n-1).at(i) = costs.at(n-1).at(i); } for (int i=n-2; i>=0; --i){ for (int j=0; j<k; ++j){ for (int t=0; t<k; ++t){ if (j!=t){ dp.at(i).at(j) = min(dp.at(i+1).at(t)+costs.at(i).at(j), dp.at(i).at(j)); } } } } int ans = INT_MAX; for (int i=0; i<k; ++i){ ans = min(ans,dp.at(0).at(i)); } return ans; } };
26.413793
97
0.353786
guohaoqiang
7011b277bf89acabd297d37e10d5f82c30fe0216
2,494
cpp
C++
tests/data/ModelProperty_Tests.cpp
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
71
2018-04-15T13:02:43.000Z
2022-03-26T11:19:18.000Z
tests/data/ModelProperty_Tests.cpp
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
309
2018-04-15T12:10:59.000Z
2022-01-22T20:13:04.000Z
tests/data/ModelProperty_Tests.cpp
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
17
2018-04-17T16:09:31.000Z
2022-03-04T08:49:03.000Z
#include "data\ModelProperty.hh" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace ra { namespace data { namespace tests { TEST_CLASS(ModelProperty_Tests) { void AssertProperty(int nKey, const ModelPropertyBase* pExpected) { const ModelPropertyBase* pLookup = ModelPropertyBase::GetPropertyForKey(nKey); if (pLookup != pExpected) { if (pExpected) Assert::Fail(L"Found property when one wasn't expected"); else Assert::Fail(L"Did not find expected property"); } } public: TEST_METHOD(TestStringModelProperty) { int nKey; { StringModelProperty pProperty("Test", "Property", L"Default"); Assert::AreEqual("Test", pProperty.GetTypeName()); Assert::AreEqual("Property", pProperty.GetPropertyName()); Assert::AreEqual(std::wstring(L"Default"), pProperty.GetDefaultValue()); nKey = pProperty.GetKey(); AssertProperty(nKey, &pProperty); pProperty.SetDefaultValue(L"New Default"); Assert::AreEqual(std::wstring(L"New Default"), pProperty.GetDefaultValue()); } AssertProperty(nKey, nullptr); } TEST_METHOD(TestIntModelProperty) { int nKey; { IntModelProperty pProperty("Test", "Property", 8); Assert::AreEqual("Test", pProperty.GetTypeName()); Assert::AreEqual("Property", pProperty.GetPropertyName()); Assert::AreEqual(8, pProperty.GetDefaultValue()); nKey = pProperty.GetKey(); AssertProperty(nKey, &pProperty); pProperty.SetDefaultValue(13); Assert::AreEqual(13, pProperty.GetDefaultValue()); } AssertProperty(nKey, nullptr); } TEST_METHOD(TestBoolModelProperty) { int nKey; { BoolModelProperty pProperty("Test", "Property", true); Assert::AreEqual("Test", pProperty.GetTypeName()); Assert::AreEqual("Property", pProperty.GetPropertyName()); Assert::AreEqual(true, pProperty.GetDefaultValue()); nKey = pProperty.GetKey(); AssertProperty(nKey, &pProperty); pProperty.SetDefaultValue(false); Assert::AreEqual(false, pProperty.GetDefaultValue()); } AssertProperty(nKey, nullptr); } }; } // namespace tests } // namespace ui } // namespace ra
28.340909
88
0.60425
Jamiras
70150516962287d6c6cb22d764f61a1dbc4e9ec5
2,623
hpp
C++
include/codegen/include/RootMotion/FinalIK/InteractionSystem_InteractionDelegate.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/RootMotion/FinalIK/InteractionSystem_InteractionDelegate.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/RootMotion/FinalIK/InteractionSystem_InteractionDelegate.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:17 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" // Including type: RootMotion.FinalIK.InteractionSystem #include "RootMotion/FinalIK/InteractionSystem.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Forward declaring namespace: RootMotion::FinalIK namespace RootMotion::FinalIK { // Forward declaring type: FullBodyBipedEffector struct FullBodyBipedEffector; // Forward declaring type: InteractionObject class InteractionObject; } // Completed forward declares // Type namespace: RootMotion.FinalIK namespace RootMotion::FinalIK { // Autogenerated type: RootMotion.FinalIK.InteractionSystem/InteractionDelegate class InteractionSystem::InteractionDelegate : public System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x14391CC static InteractionSystem::InteractionDelegate* New_ctor(::Il2CppObject* object, System::IntPtr method); // public System.Void Invoke(RootMotion.FinalIK.FullBodyBipedEffector effectorType, RootMotion.FinalIK.InteractionObject interactionObject) // Offset: 0x1432B90 void Invoke(RootMotion::FinalIK::FullBodyBipedEffector effectorType, RootMotion::FinalIK::InteractionObject* interactionObject); // public System.IAsyncResult BeginInvoke(RootMotion.FinalIK.FullBodyBipedEffector effectorType, RootMotion.FinalIK.InteractionObject interactionObject, System.AsyncCallback callback, System.Object object) // Offset: 0x143A810 System::IAsyncResult* BeginInvoke(RootMotion::FinalIK::FullBodyBipedEffector effectorType, RootMotion::FinalIK::InteractionObject* interactionObject, System::AsyncCallback* callback, ::Il2CppObject* object); // public System.Void EndInvoke(System.IAsyncResult result) // Offset: 0x143A8A8 void EndInvoke(System::IAsyncResult* result); }; // RootMotion.FinalIK.InteractionSystem/InteractionDelegate } DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::InteractionSystem::InteractionDelegate*, "RootMotion.FinalIK", "InteractionSystem/InteractionDelegate"); #pragma pack(pop)
50.442308
211
0.775829
Futuremappermydud
70165506ceb745c49a5e850c651aa9f1618910c8
1,459
cpp
C++
src/stl_copy_it_insert/main.cpp
MaksimPopp/STL_practice_UNN_381906-3
83dedf756b170b4ce89e0c74e615bbfd72c4e0a7
[ "Apache-2.0" ]
null
null
null
src/stl_copy_it_insert/main.cpp
MaksimPopp/STL_practice_UNN_381906-3
83dedf756b170b4ce89e0c74e615bbfd72c4e0a7
[ "Apache-2.0" ]
1
2020-12-12T09:55:31.000Z
2020-12-12T11:04:55.000Z
src/stl_copy_it_insert/main.cpp
MaksimPopp/STL_practice_UNN_381906-3
83dedf756b170b4ce89e0c74e615bbfd72c4e0a7
[ "Apache-2.0" ]
12
2020-12-12T09:42:22.000Z
2020-12-19T11:44:27.000Z
#include <iostream> #include <vector> #include <list> using namespace std; #define COPY int main() { int a[4] = { 10,20,30,40 };//создаём массив a[] на 4 элемента //копируем массив a[] в вектор v(указатель на начало участка который нужно скопировать,конец участка копирования) vector<int> v(a, a + 4); #ifdef COPY list<int> L(4); //создаём список L типа int на 4 элемента list<int>::iterator i;//создаём итератор i для списка L //копируем вектор v в список L с помощью функции copy(<первый> ,<последний>,<операция>). copy-алгоритм,который позволяет копировать элемнты одного контейнера в другой. copy(v.begin(), v.end(), L.begin()); #endif // COPY #ifdef INSERT list<int> L(5, 123);////создаём список L типа int на 5 элемента и заполняем его значениями 123 list<int>::iterator i = L.begin();//создаём итератор i для списка L и устанавливаем его в начало списка i++; i++;//передвигаем итератор на 2 //вствляем в список L вектор v: для этого используем функцию copy,но в аргумент <операция> передаём //inserter-специальный тип итератора вывода который добавляет элементы из контейнера A в контейнер B. inserter(<имя контейнера>,<итератор>) у нес итератор равен 2 copy(v.begin(), v.end(),inserter(L,i)); //таким образом мы встявляем вектор v в список L между 2-ым и 3-ьим элементами списка #endif // INSERT //выврод полученного списка for (i = L.begin(); i != L.end(); ++i) { cout << *i << ' '; } cout << endl; return 0; }
31.717391
168
0.703221
MaksimPopp
701760b91996bb0439dd44c7fbde49cfa6a5a77b
103
hpp
C++
src/agl/opengl/function/sampler/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/opengl/function/sampler/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/opengl/function/sampler/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
#pragma once #include "bind.hpp" #include "create.hpp" #include "delete.hpp" #include "parameter.hpp"
14.714286
24
0.728155
the-last-willy
7019415f3760818b6829d9b312ba55aa882cef45
128
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/failtest/fullpivqr_int.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/failtest/fullpivqr_int.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/failtest/fullpivqr_int.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:b7c6229e11e2ea021cf66d05b528c35bf8936f5109e7bfb4413548b392e111d9 size 258
32
75
0.882813
initialz
702427a1dd34e78d8a72eb295907bde3d145dd98
5,229
cpp
C++
tests/spmc_fifo.cpp
drbobbeaty/DKit
b3ae323449a8ad6c93e46dd4d07443f8fcc1a001
[ "Unlicense" ]
19
2015-01-16T10:11:39.000Z
2022-02-17T01:48:25.000Z
tests/spmc_fifo.cpp
drbobbeaty/DKit
b3ae323449a8ad6c93e46dd4d07443f8fcc1a001
[ "Unlicense" ]
null
null
null
tests/spmc_fifo.cpp
drbobbeaty/DKit
b3ae323449a8ad6c93e46dd4d07443f8fcc1a001
[ "Unlicense" ]
3
2015-06-28T13:20:15.000Z
2015-12-01T08:35:35.000Z
/** * This is the tests for the SPMC CircularFIFO */ // System Headers #include <iostream> #include <string> // Third-Party Headers // Other Headers #include "spmc/CircularFIFO.h" #include "util/timer.h" #include "hammer.h" #include "drain.h" int main(int argc, char *argv[]) { bool error = false; // make a circular FIFO of 1024 int32_t values - max dkit::spmc::CircularFIFO<int32_t, 10> q; // put 500 values on the queue - and check the size if (!error) { std::cout << "=== Testing speed and correctness of CircularFIFO ===" << std::endl; // get the starting time uint64_t goTime = dkit::util::timer::usecStamp(); // do this often enough to rotate through the size of the values int32_t trips = 100000; for (int32_t cycle = 0; cycle < trips; ++cycle) { // put 500 values on the queue - and check the size for (int32_t i = 0; i < 500; ++i) { if (!q.push(i)) { error = true; std::cout << "ERROR - could not push the value " << i << std::endl; break; } } // now check the size if (!error) { if (q.size() != 500) { error = true; std::cout << "ERROR - pushed 500 integers, but size() reports only " << q.size() << std::endl; } else { if (cycle == 0) { std::cout << "Passed - pushed on 500 integers" << std::endl; } } } // pop off 500 integers and it should be empty if (!error) { int32_t v = 0; for (int32_t i = 0; i < 500; ++i) { if (!q.pop(v) || (v != i)) { error = true; std::cout << "ERROR - could not pop the value " << i << std::endl; break; } } } // now check the size if (!error) { if (!q.empty()) { error = true; std::cout << "ERROR - popped 500 integers, but size() reports " << q.size() << std::endl; } else { if (cycle == 0) { std::cout << "Passed - popped all 500 integers" << std::endl; } } } // now make sure we can't pop() anything if (!error) { int32_t v = 0; if (!q.pop(v)) { if (cycle == 0) { std::cout << "Passed - unable to pop from an empty queue" << std::endl; } } else { error = true; std::cout << "ERROR - popped " << v << " from an empty queue - shouldn't be possible" << std::endl; } } } // get the elapsed time goTime = dkit::util::timer::usecStamp() - goTime; std::cout << "Passed - did " << (trips * 500) << " push/pop pairs in " << (goTime/1000.0) << "ms = " << ((goTime * 1000.0)/(trips * 500.0)) << "ns/op" << std::endl; } // check on how the crash recovery works if (!error) { // make sure it's all cleared out for this test q.clear(); std::cout << "=== Testing crash surviveability CircularFIFO ===" << std::endl; // push values starting at 0 up until we can't push any more int32_t v = 0; int32_t lim = 0; while (q.push(lim)) { ++lim; } std::cout << "Passed - Failed on pushing " << lim << std::endl; for (int32_t i = 0; i < lim; ++i) { if (!q.pop(v) || (v != i)) { error = true; std::cout << "ERROR - could not pop the value " << i << std::endl; break; } } if (!error) { std::cout << "Passed - after crash, still able to recover all values" << std::endl; } } /** * Make a Hammer and a set of Drains and test threading */ if (!error) { Hammer src(0, &q, 1000); Drain *dest[] = { NULL, NULL, NULL, NULL }; for (uint32_t i = 0; i < 4; ++i) { if ((dest[i] = new Drain(i, &q)) == NULL) { std::cout << "PROBLEM - unable to make Drain #" << i << "!" << std::endl; break; } } // now start the drains then the hammer for (uint32_t i = 0; i < 4; ++i) { if (dest[i] != NULL) { dest[i]->start(); } } src.start(); // now let's wait for the hammer to be done while (!src.isDone()) { usleep(250000); } // now tell the drains to stop when the queue is empty for (uint32_t i = 0; i < 4; ++i) { if (dest[i] != NULL) { dest[i]->stopOnEmpty(); } } // wait for all the drains to be done bool allDone = false; uint32_t cnt[] = { 0, 0, 0, 0 }; uint32_t total = 0; while (!allDone) { // assume done, but check for the first failure allDone = true; // now let's check all the drains to see if they are done for (uint32_t i = 0; i < 4; ++i) { if (dest[i] != NULL) { if (!dest[i]->isDone()) { allDone = false; break; } // tally up the counts cnt[i] = dest[i]->getCount(); total += cnt[i]; } } // see if we need to wait a bit to try again if (!allDone) { usleep(250000); } } // now let's see what we have if (total == 1000) { std::cout << "Passed - popped " << total << " integers (" << cnt[0] << "+" << cnt[1] << "+" << cnt[2] << "+" << cnt[3] << "), with four drain threads" << std::endl; } else { std::cout << "ERROR - popped " << total << " integers (" << cnt[0] << "+" << cnt[1] << "+" << cnt[2] << "+" << cnt[3] << "), with four drain threads - but should have popped 1000" << std::endl; } // finally, clean things up for (uint32_t i = 0; i < 4; ++i) { if (dest[i] != NULL) { delete dest[i]; dest[i] = NULL; } } } std::cout << (error ? "FAILED!" : "SUCCESS") << std::endl; return (error ? 1 : 0); }
27.81383
196
0.536814
drbobbeaty
702ac5ddfe1b70c5668a5f3e1250734676e10b0c
2,054
cpp
C++
Source/Engine/Editor/Widgets/PropertyWidget.cpp
muit/FecoEngine
b2f8729c0bf0893b770434645c2a0fa8e7717cb7
[ "Apache-2.0" ]
3
2019-03-01T19:34:26.000Z
2021-03-31T09:25:16.000Z
Source/Engine/Editor/Widgets/PropertyWidget.cpp
muit/FecoEngine
b2f8729c0bf0893b770434645c2a0fa8e7717cb7
[ "Apache-2.0" ]
null
null
null
Source/Engine/Editor/Widgets/PropertyWidget.cpp
muit/FecoEngine
b2f8729c0bf0893b770434645c2a0fa8e7717cb7
[ "Apache-2.0" ]
1
2019-01-21T21:45:13.000Z
2019-01-21T21:45:13.000Z
// Copyright 2015-2019 Piperift - All rights reserved #include "PropertyWidget.h" #if WITH_EDITOR #include "Core/Reflection/Runtime/TPropertyHandle.h" #include "Properties/BoolPropertyWidget.h" #include "Properties/UInt8PropertyWidget.h" #include "Properties/Int32PropertyWidget.h" #include "Properties/FloatPropertyWidget.h" #include "Properties/NamePropertyWidget.h" #include "Properties/StringPropertyWidget.h" #include "Properties/V3PropertyWidget.h" #include "Properties/V2PropertyWidget.h" GlobalPtr<PropertyWidget> PropertyWidget::NewPropertyWidget(const Ptr<Widget>& owner, const eastl::shared_ptr<PropertyHandle>& prop) { if (prop && owner) { Class* customWidgetClass = prop->GetClassDefinedWidgetClass(); if (customWidgetClass) { return owner->New<PropertyWidget>(customWidgetClass, prop); } // Ordered by estimated usage // #TODO: Switch to native pointers if (auto propFloat = eastl::dynamic_pointer_cast<TPropertyHandle<float>>(prop)) { return owner->New<FloatPropertyWidget>(propFloat); } else if (auto propInt32 = eastl::dynamic_pointer_cast<TPropertyHandle<i32>>(prop)) { return owner->New<Int32PropertyWidget>(propInt32); } else if (auto propUInt8 = eastl::dynamic_pointer_cast<TPropertyHandle<u8>>(prop)) { return owner->New<UInt8PropertyWidget>(propUInt8); } else if (auto propBool = eastl::dynamic_pointer_cast<TPropertyHandle<bool>>(prop)) { return owner->New<BoolPropertyWidget>(propBool); } else if (auto propName = eastl::dynamic_pointer_cast<TPropertyHandle<Name>>(prop)) { return owner->New<NamePropertyWidget>(propName); } else if (auto propString = eastl::dynamic_pointer_cast<TPropertyHandle<String>>(prop)) { return owner->New<StringPropertyWidget>(propString); } else if (auto propV3 = eastl::dynamic_pointer_cast<TPropertyHandle<v3>>(prop)) { return owner->New<V3PropertyWidget>(propV3); } else if (auto propV2 = eastl::dynamic_pointer_cast<TPropertyHandle<v2>>(prop)) { return owner->New<V2PropertyWidget>(propV2); } } return {}; } #endif
34.813559
132
0.757059
muit
702c85fa25150642f93577e4c912e3b0ae9312bb
2,129
cpp
C++
Windows/Controls/DefinitionView.cpp
TrevorShelton/cplot
8bf40e94519cc4fd69b2e0677d3a3dcf8695245a
[ "MIT" ]
32
2017-11-27T03:04:44.000Z
2022-01-21T17:03:40.000Z
Windows/Controls/DefinitionView.cpp
TrevorShelton/cplot
8bf40e94519cc4fd69b2e0677d3a3dcf8695245a
[ "MIT" ]
30
2017-11-10T09:47:16.000Z
2018-11-21T22:36:47.000Z
Windows/Controls/DefinitionView.cpp
TrevorShelton/cplot
8bf40e94519cc4fd69b2e0677d3a3dcf8695245a
[ "MIT" ]
20
2018-01-05T17:15:11.000Z
2021-07-30T14:11:01.000Z
#include "../stdafx.h" #include "DefinitionView.h" #include "../Document.h" #include "../res/resource.h" #include "ViewUtil.h" #include "SideSectionDefs.h" #include "../MainWindow.h" #include "../MainView.h" #include "../CPlotApp.h" #ifdef _DEBUG #define new DEBUG_NEW #endif enum { ID_def = 2000 }; IMPLEMENT_DYNAMIC(DefinitionView, CWnd) BEGIN_MESSAGE_MAP(DefinitionView, CWnd) ON_WM_CREATE() ON_WM_SIZE() ON_BN_CLICKED(ID_def, OnEdit) END_MESSAGE_MAP() DefinitionView::DefinitionView(SideSectionDefs &parent, UserFunction &f) : parent(parent), f_id(f.oid()) { } BOOL DefinitionView::PreCreateWindow(CREATESTRUCT &cs) { cs.style |= WS_CHILD; cs.dwExStyle |= WS_EX_CONTROLPARENT | WS_EX_TRANSPARENT; return CWnd::PreCreateWindow(cs); } BOOL DefinitionView::Create(const RECT &rect, CWnd *parent, UINT ID) { static bool init = false; if (!init) { WNDCLASS wndcls; memset(&wndcls, 0, sizeof(WNDCLASS)); wndcls.style = CS_DBLCLKS; wndcls.lpfnWndProc = ::DefWindowProc; wndcls.hInstance = AfxGetInstanceHandle(); wndcls.hCursor = theApp.LoadStandardCursor(IDC_ARROW); wndcls.lpszMenuName = NULL; wndcls.lpszClassName = _T("DefinitionView"); wndcls.hbrBackground = NULL; if (!AfxRegisterClass(&wndcls)) throw std::runtime_error("AfxRegisterClass(DefinitionView) failed"); init = true; } return CWnd::Create(_T("DefinitionView"), NULL, WS_CHILD | WS_TABSTOP, rect, parent, ID); } int DefinitionView::OnCreate(LPCREATESTRUCT cs) { if (CWnd::OnCreate(cs) < 0) return -1; EnableScrollBarCtrl(SB_BOTH, FALSE); START_CREATE; BUTTONLABEL(def); return 0; } void DefinitionView::Update(bool full) { CRect bounds; GetClientRect(bounds); UserFunction *f = function(); if (!f) return; def.SetWindowText(Convert(f->formula())); if (!full) return; Layout layout(*this, 0, 20); SET(-1); USE(&def); } void DefinitionView::OnInitialUpdate() { Update(true); } void DefinitionView::OnSize(UINT type, int w, int h) { CWnd::OnSize(type, w, h); EnableScrollBarCtrl(SB_BOTH, FALSE); Update(true); } void DefinitionView::OnEdit() { auto *f = function(); if (!f) return; parent.OnEdit(f); }
21.29
102
0.721465
TrevorShelton
702ebc555e0536e62e3091d3c25c340bddce8033
878
hpp
C++
src/crossserver/crossserver/crossactivity/impl/crossactivitycrossboss.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
3
2021-12-16T13:57:28.000Z
2022-03-26T07:50:08.000Z
src/crossserver/crossserver/crossactivity/impl/crossactivitycrossboss.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
null
null
null
src/crossserver/crossserver/crossactivity/impl/crossactivitycrossboss.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
1
2022-03-26T07:50:11.000Z
2022-03-26T07:50:11.000Z
#ifndef __CROSS_ACTIVITY_CROSS_BOSS_HPP__ #define __CROSS_ACTIVITY_CROSS_BOSS_HPP__ #include "crossactivity/crossactivity.hpp" #include "servercommon/internalprotocal/crossgameprotocal.h" #include <map> class CrossActivityCrossBoss : public CrossActivity { public: CrossActivityCrossBoss(CrossActivityManager *cross_activity_manager); ~CrossActivityCrossBoss(); virtual void Init(const CrossActivityData &data); virtual void OnCrossUserLogin(CrossUser *cross_user); virtual bool CheckCanStartCross(const UniqueUserID &unique_user_id, int merge_server_id = 0) { return true; } void OnPlayerInfoResult(crossgameprotocal::GameCrossBossSyncPlayerInfo *tzsfr); private: virtual void OnChangeToNextStatus(); typedef std::map<long long, int> CrossBossSceneMap; typedef std::map<long long, int>::iterator CrossBossSceneMapIt; }; #endif // __CROSS_ACTIVITY_1V1_HPP__
29.266667
110
0.823462
mage-game
70319f9109bd638d460b7dc5701da2e20d4cc9f9
1,322
cpp
C++
CrimeEngine/source/Core/Input/Event.cpp
boschman32/Crime-Engine
128529634011d41a1f7fc1a356245d7f7ef77cb3
[ "MIT" ]
1
2021-07-21T17:14:35.000Z
2021-07-21T17:14:35.000Z
CrimeEngine/source/Core/Input/Event.cpp
boschman32/Crime-Engine
128529634011d41a1f7fc1a356245d7f7ef77cb3
[ "MIT" ]
null
null
null
CrimeEngine/source/Core/Input/Event.cpp
boschman32/Crime-Engine
128529634011d41a1f7fc1a356245d7f7ef77cb3
[ "MIT" ]
3
2021-03-07T15:51:03.000Z
2021-07-13T20:01:34.000Z
#include "cepch.h" #include "Core/Input/Event.h" #include "Core/Input/KeyEvent.h" void Event::NotifyHandlers(const KeyEvent& a_notifyKey) { std::vector<std::shared_ptr<EventHandler>>::iterator handle = m_handlers.begin(); for (; handle != m_handlers.end(); ++handle) { if (*handle != nullptr) { (*(*handle))(a_notifyKey); } } } void Event::AddHandler(EventHandler& a_newHandler) { m_handlers.push_back(std::make_shared<EventHandler>(a_newHandler)); } void Event::AddHandler(std::function<void(const KeyEvent&)> a_newHandler) { m_handlers.push_back(std::make_shared<EventHandler>(a_newHandler)); } void Event::RemoveHandler(EventHandler& a_handlerToRemove) { std::vector<std::shared_ptr<EventHandler>>::iterator handle = m_handlers.begin(); for (; handle != m_handlers.end(); ++handle) { if (*(*handle) == a_handlerToRemove) { m_handlers.erase(handle); } } } void Event::operator()(const KeyEvent& a_notifyKey) { NotifyHandlers(a_notifyKey); } Event& Event::operator+=(EventHandler& a_newHandler) { AddHandler(a_newHandler); return *this; } Event& Event::operator+=(std::function<void(const KeyEvent&)> a_newHandler) { AddHandler(EventHandler(a_newHandler)); return *this; } Event& Event::operator-=(EventHandler& a_handlerToRemove) { RemoveHandler(a_handlerToRemove); return *this; }
22.793103
82
0.728442
boschman32
70392118b102124f1f9745e03372a8deb357bbf9
1,249
cpp
C++
WRK-V1.2/TOOLS/TOOLSX/atlmfc/src/mfc/appdlg.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
WRK-V1.2/TOOLS/TOOLSX/atlmfc/src/mfc/appdlg.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
WRK-V1.2/TOOLS/TOOLSX/atlmfc/src/mfc/appdlg.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" ///////////////////////////////////////////////////////////////////////////// // WinApp features for new and open void CWinApp::OnFileNew() { if (m_pDocManager != NULL) m_pDocManager->OnFileNew(); } ///////////////////////////////////////////////////////////////////////////// void CWinApp::OnFileOpen() { ENSURE(m_pDocManager != NULL); m_pDocManager->OnFileOpen(); } // prompt for file name - used for open and save as BOOL CWinApp::DoPromptFileName(CString& fileName, UINT nIDSTitle, DWORD lFlags, BOOL bOpenFileDialog, CDocTemplate* pTemplate) // if pTemplate==NULL => all document templates { ENSURE(m_pDocManager != NULL); return m_pDocManager->DoPromptFileName(fileName, nIDSTitle, lFlags, bOpenFileDialog, pTemplate); } /////////////////////////////////////////////////////////////////////////////
29.046512
79
0.614091
intj-t
703b02d15777e9efc4672b462315d3c6ac932e11
3,064
hpp
C++
test/propertyaccess.hpp
IRCAD/camp
fbbada73d6fd25c30f22a69f195c871757e362dd
[ "MIT" ]
6
2017-12-27T03:13:29.000Z
2021-01-04T15:07:18.000Z
test/propertyaccess.hpp
fw4spl-org/camp
e70eca1d2bf7f20df782dacc5d6baa51ce364e12
[ "MIT" ]
1
2021-10-19T14:03:39.000Z
2021-10-19T14:03:39.000Z
test/propertyaccess.hpp
IRCAD/camp
fbbada73d6fd25c30f22a69f195c871757e362dd
[ "MIT" ]
1
2019-08-30T15:20:46.000Z
2019-08-30T15:20:46.000Z
/**************************************************************************** ** ** This file is part of the CAMP library. ** ** The MIT License (MIT) ** ** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company. ** Contact: Tegesoft Information ([email protected]) ** ** 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. ** ****************************************************************************/ #ifndef CAMPTEST_PROPERTYACCESS_HPP #define CAMPTEST_PROPERTYACCESS_HPP #include <camp/camptype.hpp> #include <camp/class.hpp> namespace PropertyAccessTest { struct MyClass { MyClass(bool b = true) : m_b(b) { } void set(int x) {p = x;} int get() const {return p;} int& ref() {return p;} int p; bool m_b; bool b1() {return true;} bool b2() const {return false;} }; void declare() { camp::Class::declare<MyClass>("PropertyAccessTest::MyClass") // ***** constant value ***** .property("p0", &MyClass::p).readable(false).writable(true) .property("p1", &MyClass::p).readable(true).writable(false) .property("p2", &MyClass::p).readable(false).writable(false) // ***** function ***** .property("p3", &MyClass::p).readable(&MyClass::b1) .property("p4", &MyClass::p).readable(&MyClass::b2) .property("p5", &MyClass::p).readable(boost::bind(&MyClass::b1, _1)) .property("p6", &MyClass::p).readable(&MyClass::m_b) .property("p7", &MyClass::p).readable(boost::function<bool (MyClass&)>(&MyClass::m_b)) // ***** implicit - based on the availability of a getter/setter ***** .property("p8", &MyClass::get) .property("p9", &MyClass::ref) .property("p10", &MyClass::get, &MyClass::set) ; } } CAMP_AUTO_TYPE(PropertyAccessTest::MyClass, &PropertyAccessTest::declare) #endif // CAMPTEST_PROPERTYACCESS_HPP
37.365854
98
0.613251
IRCAD
703d242e34177ae85614f512fc8a8780fe99174b
865
cc
C++
src/results/output.cc
SlaybaughLab/Transport
8eb32cb8ae50c92875526a7540350ef9a85bc050
[ "MIT" ]
12
2018-03-14T12:30:53.000Z
2022-01-23T14:46:44.000Z
src/results/output.cc
jsrehak/BART
0460dfffbcf5671a730448de7f45cce39fd4a485
[ "MIT" ]
194
2017-07-07T01:38:15.000Z
2021-05-19T18:21:19.000Z
src/results/output.cc
jsrehak/BART
0460dfffbcf5671a730448de7f45cce39fd4a485
[ "MIT" ]
10
2017-07-06T22:58:59.000Z
2021-03-15T07:01:21.000Z
#include "results/output.h" #include <deal.II/base/exceptions.h> namespace bart { namespace results { void Output::WriteVector(std::ostream &output_stream, const std::vector<double> to_write) const { for (std::vector<double>::size_type i =0 ; i < to_write.size(); ++i) output_stream << i << ", " << to_write.at(i) << "\n"; } void Output::WriteVector(std::ostream &output_stream, std::vector<double> to_write, std::vector<std::string> headers) const { AssertThrow(static_cast<int>(headers.size()) == 2, dealii::ExcMessage("Error in WriteVector, header size must be " "size 2")) output_stream << headers.at(0) << "," << headers.at(1) << "\n"; WriteVector(output_stream, to_write); } } // namespace results } // namespace bart
30.892857
77
0.587283
SlaybaughLab
703d7de100fc7ff71c7f7ff64f600c2140011fa0
11,355
cpp
C++
src/find_relatives_table.cpp
jjmccollum/open-cbgm
c231b1fa0b5ff86c0701c0f7f2b389c3a60434f4
[ "MIT" ]
21
2020-01-17T21:45:28.000Z
2022-03-29T07:24:45.000Z
src/find_relatives_table.cpp
jjmccollum/open-cbgm
c231b1fa0b5ff86c0701c0f7f2b389c3a60434f4
[ "MIT" ]
4
2020-03-05T03:33:44.000Z
2020-10-16T23:29:44.000Z
src/find_relatives_table.cpp
jjmccollum/open-cbgm
c231b1fa0b5ff86c0701c0f7f2b389c3a60434f4
[ "MIT" ]
1
2020-01-30T16:17:08.000Z
2020-01-30T16:17:08.000Z
/* * find_relatives_table.cpp * * Created on: Sept 18, 2020 * Author: jjmccollum */ #include <iostream> #include <iomanip> #include <string> #include <list> #include <set> #include <algorithm> #include <limits> #include "variation_unit.h" #include "witness.h" #include "find_relatives_table.h" using namespace std; /** * Default constructor. */ find_relatives_table::find_relatives_table() { } /** * Constructs a find relatives table relative to a given witness at a given variation unit, * given a list of witness IDs in input order and a set of readings by which to filter the rows. */ find_relatives_table::find_relatives_table(const witness & wit, const variation_unit & vu, const list<string> list_wit, const set<string> & filter_rdgs) { rows = list<find_relatives_table_row>(); id = wit.get_id(); label = vu.get_label(); connectivity = vu.get_connectivity(); unordered_map<string, string> reading_support = vu.get_reading_support(); primary_rdg = reading_support.find(id) != reading_support.end() ? reading_support.at(id) : "-"; //Start by populating the table completely with this witness's comparisons to all other witnesses: for (string secondary_wit_id : list_wit) { //Get the genealogical comparison of the primary witness to this witness: genealogical_comparison comp = wit.get_genealogical_comparison_for_witness(secondary_wit_id); //For the primary witness, copy the number of passages where it is extant and move on: if (secondary_wit_id == id) { primary_extant = (int) comp.extant.cardinality(); continue; } find_relatives_table_row row; row.id = secondary_wit_id; row.rdg = reading_support.find(row.id) != reading_support.end() ? reading_support.at(row.id) : "-"; row.pass = (int) comp.extant.cardinality(); row.eq = (int) comp.agreements.cardinality(); row.perc = row.pass > 0 ? (100 * float(row.eq) / float(row.pass)) : 0; row.prior = (int) comp.prior.cardinality(); row.posterior = (int) comp.posterior.cardinality(); row.norel = (int) comp.norel.cardinality(); row.uncl = (int) comp.unclear.cardinality(); row.expl = (int) comp.explained.cardinality(); row.cost = row.prior >= row.posterior ? -1 : comp.cost; rows.push_back(row); } //Sort the list of rows from highest number of agreements to lowest: rows.sort([](const find_relatives_table_row & r1, const find_relatives_table_row & r2) { return r1.eq > r2.eq; }); //Pass through the sorted list of comparisons to assign relationship directions and ancestral ranks: int nr = 0; int nr_value = numeric_limits<int>::max(); for (find_relatives_table_row & row : rows) { //Only assign positive ancestral ranks to witnesses prior to this one: if (row.posterior > row.prior) { //Only increment the rank if the number of agreements is lower than that of the previous potential ancestor: if (row.eq < nr_value) { nr_value = row.eq; nr++; } row.dir = 1; row.nr = nr; } else if (row.posterior == row.prior) { row.dir = 0; row.nr = 0; } else { row.dir = -1; row.nr = -1; } } //If the filter set is not empty, then filter the rows: if (!filter_rdgs.empty()) { rows.remove_if([&](const find_relatives_table_row & row) { return filter_rdgs.find(row.rdg) == filter_rdgs.end(); }); } } /** * Default destructor. */ find_relatives_table::~find_relatives_table() { } /** * Returns the ID of the primary witness for which this table provides comparisons. */ string find_relatives_table::get_id() const { return id; } /** * Returns the label of the variation unit at which this table provides comparisons. */ string find_relatives_table::get_label() const { return label; } /** * Returns the connectivity limit of the variation unit at which this table provides comparisons. */ int find_relatives_table::get_connectivity() const { return connectivity; } /** * Returns the number of passages at which this table's primary witness is extant. */ int find_relatives_table::get_primary_extant() const { return primary_extant; } /** * Returns the reading of the primary witness at the variation unit under consideration. */ string find_relatives_table::get_primary_rdg() const { return primary_rdg; } /** * Returns this table's list of rows. */ list<find_relatives_table_row> find_relatives_table::get_rows() const { return rows; } /** * Given an output stream, prints this find relatives table in fixed-width format. */ void find_relatives_table::to_fixed_width(ostream & out) { //Print the caption: out << "Genealogical comparisons for W1 = " << id << " (" << primary_extant << " extant passages):"; out << "\n\n"; //Print the header row: out << std::left << std::setw(8) << "W2"; out << std::left << std::setw(4) << "DIR"; out << std::right << std::setw(4) << "NR"; out << std::setw(4) << ""; //buffer space between right-aligned and left-aligned columns out << std::left << std::setw(8) << "RDG"; out << std::right << std::setw(8) << "PASS"; out << std::right << std::setw(8) << "EQ"; out << std::right << std::setw(12) << ""; //percentage of agreements among mutually extant passages out << std::right << std::setw(8) << "W1>W2"; out << std::right << std::setw(8) << "W1<W2"; out << std::right << std::setw(8) << "NOREL"; out << std::right << std::setw(8) << "UNCL"; out << std::right << std::setw(8) << "EXPL"; out << std::right << std::setw(12) << "COST"; out << "\n\n"; //Print the subsequent rows: for (find_relatives_table_row row : rows) { out << std::left << std::setw(8) << row.id; out << std::left << std::setw(4) << (row.dir == -1 ? "<" : (row.dir == 1 ? ">" : "=")); out << std::right << std::setw(4) << (row.nr > 0 ? to_string(row.nr) : ""); out << std::setw(4) << ""; //buffer space between right-aligned and left-aligned columns out << std::left << std::setw(8) << row.rdg; out << std::right << std::setw(8) << row.pass; out << std::right << std::setw(8) << row.eq; out << std::right << std::setw(3) << "(" << std::setw(7) << fixed << std::setprecision(3) << row.perc << std::setw(2) << "%)"; out << std::right << std::setw(8) << row.prior; out << std::right << std::setw(8) << row.posterior; out << std::right << std::setw(8) << row.norel; out << std::right << std::setw(8) << row.uncl; out << std::right << std::setw(8) << row.expl; if (row.cost >= 0) { out << std::right << std::setw(12) << fixed << std::setprecision(3) << row.cost; } else { out << std::right << std::setw(12) << ""; } out << "\n"; } out << endl; return; } /** * Given an output stream, prints this find relatives table in comma-separated value (CSV) format. * The witness IDs are assumed not to contain commas; if they do, then they will need to be manually escaped in the output. */ void find_relatives_table::to_csv(ostream & out) { //Print the header row: out << "W2" << ","; out << "DIR" << ","; out << "NR" << ","; out << "RDG" << ","; out << "PASS" << ","; out << "EQ" << ","; out << "" << ","; //percentage of agreements among mutually extant passages out << "W1>W2" << ","; out << "W1<W2" << ","; out << "NOREL" << ","; out << "UNCL" << ","; out << "EXPL" << ","; out << "COST" << "\n"; //Print the subsequent rows: for (find_relatives_table_row row : rows) { out << row.id << ","; out << (row.dir == -1 ? "<" : (row.dir == 1 ? ">" : "=")) << ","; out << (row.nr > 0 ? to_string(row.nr) : "") << ","; out << row.rdg << ","; out << row.pass << ","; out << row.eq << ","; out << "(" << row.perc << "%)" << ","; out << row.prior << ","; out << row.posterior << ","; out << row.norel << ","; out << row.uncl << ","; out << row.expl << ","; if (row.cost >= 0) { out << row.cost << "\n"; } else { out << "" << "\n"; } } out << endl; return; } /** * Given an output stream, prints this find relatives table in tab-separated value (TSV) format. * The witness IDs are assumed not to contain tabs; if they do, then they will need to be manually escaped in the output. */ void find_relatives_table::to_tsv(ostream & out) { //Print the header row: out << "W2" << "\t"; out << "DIR" << "\t"; out << "NR" << "\t"; out << "RDG" << "\t"; out << "PASS" << "\t"; out << "EQ" << "\t"; out << "" << "\t"; //percentage of agreements among mutually extant passages out << "W1>W2" << "\t"; out << "W1<W2" << "\t"; out << "NOREL" << "\t"; out << "UNCL" << "\t"; out << "EXPL" << "\t"; out << "COST" << "\n"; //Print the subsequent rows: for (find_relatives_table_row row : rows) { out << row.id << "\t"; out << (row.dir == -1 ? "<" : (row.dir == 1 ? ">" : "=")) << "\t"; out << (row.nr > 0 ? to_string(row.nr) : "") << "\t"; out << row.rdg << "\t"; out << row.pass << "\t"; out << row.eq << "\t"; out << "(" << row.perc << "%)" << "\t"; out << row.prior << "\t"; out << row.posterior << "\t"; out << row.norel << "\t"; out << row.uncl << "\t"; out << row.expl << "\t"; if (row.cost >= 0) { out << row.cost << "\n"; } else { out << "" << "\n"; } } out << endl; return; } /** * Given an output stream, prints this find relatives table in JavaScript Object Notation (JSON) format. * The witness IDs are assumed not to contain characters that need to be escaped in URLs. */ void find_relatives_table::to_json(ostream & out) { //Open the root object: out << "{"; //Add the metadata fields: out << "\"primary_wit\":" << "\"" << id << "\"" << ","; out << "\"primary_extant\":" << primary_extant << ","; out << "\"label\":" << "\"" << label << "\"" << ","; out << "\"connectivity\":" << connectivity << ","; out << "\"primary_rdg\":" << "\"" << primary_rdg << "\"" << ","; //Open the rows array: out << "\"rows\":" << "["; //Print each row as an object: unsigned int row_num = 0; for (find_relatives_table_row row : rows) { //Open the row object: out << "{"; //Add its key-value pairs: out << "\"id\":" << "\"" << row.id << "\"" << ","; out << "\"dir\":" << row.dir << ","; out << "\"nr\":" << "\"" << (row.nr > 0 ? to_string(row.nr) : "") << "\"" << ","; out << "\"rdg\":" << "\"" << row.rdg << "\"" << ","; out << "\"pass\":" << row.pass << ","; out << "\"eq\":" << row.eq << ","; out << "\"perc\":" << row.perc << ","; out << "\"prior\":" << row.prior << ","; out << "\"posterior\":" << row.posterior << ","; out << "\"norel\":" << row.norel << ","; out << "\"uncl\":" << row.uncl << ","; out << "\"expl\":" << row.expl << ","; if (row.cost >= 0) { out << "\"cost\":" << "\"" << row.cost << "\""; } else { out << "\"cost\":" << "\"" << "" << "\""; } //Close the row object: out << "}"; //Add a comma if this is not the last row: if (row_num < rows.size() - 1) { out << ","; } row_num++; } //Close the rows array: out << "]"; //Close the root object: out << "}"; return; }
33.594675
155
0.559401
jjmccollum
703d8f3b61a17e7b445f7c162fda17d78e4130b6
1,627
cpp
C++
NoteHandler/midi.cpp
vikbez/PlayerPianoController
098e0a9df2be3d029490986eedd1bf2eac0a44ca
[ "MIT" ]
27
2019-07-23T21:13:27.000Z
2022-03-26T09:51:58.000Z
ProMicro/midi.cpp
anodeaday/PianoProject
ff31af5d5eaa72ee6dbe8b1f445979bc1ab84e90
[ "MIT" ]
4
2020-11-05T16:41:14.000Z
2022-02-07T20:31:11.000Z
ProMicro/midi.cpp
anodeaday/PianoProject
ff31af5d5eaa72ee6dbe8b1f445979bc1ab84e90
[ "MIT" ]
10
2019-07-24T01:00:22.000Z
2022-02-09T17:36:04.000Z
#include <MIDIUSB.h> #include "midi.h" #include "shiftRegister.h" #include "serial.h" void decodeMidi(uint8_t header, uint8_t byte1, uint8_t byte2, uint8_t byte3); extern const bool DEBUG_MODE; void checkForMidiUSB() { midiEventPacket_t rx; //midi data struct from midiUSB libray do { rx = MidiUSB.read(); //get queued info from USB if(rx.header != 0) { decodeMidi(rx.header, rx.byte1, rx.byte2, rx.byte3); } } while(rx.header != 0); } void decodeMidi(uint8_t header, uint8_t byte1, uint8_t byte2, uint8_t byte3) { if(DEBUG_MODE) { String message[] = { "-----------", static_cast<String>(header), static_cast<String>(byte1), static_cast<String>(byte2), static_cast<String>(byte3), "-----------" }; sendSerialToUSB(message, 6); } const uint8_t NOTE_ON_HEADER = 9; const uint8_t NOTE_OFF_HEADER = 8; const uint8_t CONTROL_CHANGE_HEADER = 8; const uint8_t SUSTAIN_STATUS_BYTE = 176; const uint8_t MIN_NOTE_PITCH = 21; const uint8_t MAX_NOTE_PITCH = 108; switch(header) { case NOTE_ON_HEADER: if(byte2 >= MIN_NOTE_PITCH && byte2 <= MAX_NOTE_PITCH && byte3 >= 0 && byte3 <= 127) { uint8_t note = (byte2 - MIN_NOTE_PITCH) * -1 + 87; activateNote(note, byte3); } break; case NOTE_OFF_HEADER: if(byte2 >= MIN_NOTE_PITCH && byte2 <= MAX_NOTE_PITCH) { uint8_t note = (byte2 - MIN_NOTE_PITCH) * -1 + 87; activateNote(note, 0); } break; case SUSTAIN_STATUS_BYTE: if(byte1 == SUSTAIN_STATUS_BYTE) { extern const uint8_t SUSTAIN_HEADER; sendSerialToMain(SUSTAIN_HEADER, byte3, byte3); } break; } }
23.242857
77
0.664413
vikbez
703fa38c7280501c98858c29beec0029573ece45
6,475
cpp
C++
gSpiderMac/testv8/testv8/main.cpp
reichtiger/grampusSpider
d8ba6b96a7af085c7c2420a5bcb1fa35ee8b03b7
[ "Apache-2.0" ]
87
2015-08-05T12:49:16.000Z
2021-09-23T03:24:40.000Z
gSpiderMac/testv8/testv8/main.cpp
reichtiger/grampusSpider
d8ba6b96a7af085c7c2420a5bcb1fa35ee8b03b7
[ "Apache-2.0" ]
null
null
null
gSpiderMac/testv8/testv8/main.cpp
reichtiger/grampusSpider
d8ba6b96a7af085c7c2420a5bcb1fa35ee8b03b7
[ "Apache-2.0" ]
52
2015-09-24T05:19:29.000Z
2020-10-14T07:14:22.000Z
// // main.cpp // testv8 // // Created by reich on 14/11/18. // Copyright (c) 2014年 chupeng. All rights reserved. // #include <stdlib.h> #include <stdio.h> #include <string.h> #include <iostream> #include <string> #include <v8.h> #include <assert.h> #include <wchar.h> using namespace std; using namespace v8; /***************************************************************** * exception functions */ const char* ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; } void ReportException(Isolate* isolate, v8::TryCatch* try_catch) { HandleScope handle_scope(isolate); v8::String::Utf8Value exception(try_catch->Exception()); const char* exception_string = ToCString(exception); v8::Handle<v8::Message> message = try_catch->Message(); if (message.IsEmpty()) { // V8 didn""t provide any extra information about this error; just // print the exception. printf("%s\n", exception_string); } else { // Print (filename):(line number): (message). v8::String::Utf8Value filename(message->GetScriptResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); printf("%s:%i: %s\n", filename_string, linenum, exception_string); // Print line of source code. v8::String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = ToCString(sourceline); printf("%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { printf(" "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { printf("^"); } printf("\n"); v8::String::Utf8Value stack_trace(try_catch->StackTrace()); if (stack_trace.length() > 0) { const char* stack_trace_string = ToCString(stack_trace); printf("%s\n", stack_trace_string); } } } std::string executeString(v8::Isolate* isolate, v8::Handle<v8::String> source, v8::Handle<v8::Value> name, bool print_result, bool report_exceptions) { HandleScope handle_scope(isolate); v8::TryCatch try_catch; //’‚¿Ô…Ë÷√“Ï≥£ª˙÷∆ v8::ScriptOrigin origin(name); v8::Handle<v8::Script> script = v8::Script::Compile(source, &origin); if (script.IsEmpty()) { // Print errors that happened during compilation. if (report_exceptions) ReportException(isolate, &try_catch); return ""; } else { v8::Handle<v8::Value> result = script->Run(); if (result.IsEmpty()) { //ASSERT(try_catch.HasCaught()); // Print errors that happened during execution. if (report_exceptions) ReportException(isolate, &try_catch); return ""; } else { assert(!try_catch.HasCaught()); if (print_result && !result->IsUndefined()) { // If all went well and the result wasn""t undefined then print // the returned value. v8::String::Utf8Value ret(result); printf("%s\n", *ret); std::string gbk; //ConvertUtf8ToGBK(gbk, *ret); return gbk; } return ""; } } } void runJSCode(v8::Handle<v8::Context> context, char* jscode) { Local<String> source = String::NewFromUtf8(context->GetIsolate(), jscode); v8::Local<v8::String> name(v8::String::NewFromUtf8(context->GetIsolate(), "(tigerv8)")); v8::HandleScope handle_scope(context->GetIsolate()); std::string gbkStr3 = executeString(context->GetIsolate(), source, name, true, true); } static void log_Callback(const v8::FunctionCallbackInfo<v8::Value>& args) { bool first = true; for (int i = 0; i < args.Length(); i++) { if (first) { first = false; } else { printf(" "); } String::Utf8Value str(args[i]); if (args[i]->IsString()) { printf("LOG (string) --->%s\n", *str); } else if (args[i]->IsInt32()){ int x = args[i]->Int32Value(); printf("LOG (int) --> %d\n", x); } else if (args[i]->IsObject()){ printf("LOG (Object) --> %s\n", *str); } } printf("\n"); fflush(stdout); } static void win_Callback(const v8::FunctionCallbackInfo<v8::Value>& args){ } class HTMLWindow{ }; Handle<Object> WrapHTMLWindowObject(Isolate* isolate, HTMLWindow* htmlWin) { EscapableHandleScope handle_scope(isolate); Local<ObjectTemplate> templ = ObjectTemplate::New(); templ->SetInternalFieldCount(1); Local<Object> result = templ->NewInstance(); result->SetInternalField(0, External::New(isolate, htmlWin)); return handle_scope.Escape(result); } /****************************************************************************** * main func start * ******************************************************************************/ int main(int argc, const char * argv[]) { Isolate* isolate = Isolate::GetCurrent(); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Handle<ObjectTemplate> global = ObjectTemplate::New(isolate); v8::Handle<v8::FunctionTemplate> log_ft = v8::FunctionTemplate::New(isolate, log_Callback); log_ft->InstanceTemplate()->SetInternalFieldCount(1); global->Set(String::NewFromUtf8(isolate, "alert"), log_ft); Handle<Context> context = Context::New(isolate, NULL, global); v8::Handle<v8::Object> v8RealGlobal = v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype()); Context::Scope context_scope(context); HTMLWindow* htmWin = new HTMLWindow; Local<Object> jsWin = WrapHTMLWindowObject(isolate, htmWin); v8RealGlobal->Set(String::NewFromUtf8(isolate, "window"), jsWin); v8RealGlobal->SetPrototype(jsWin); // set global objects and functions runJSCode(context, (char*)"alert(window);window.asdf=44; alert(asdf);"); std::cout << "********* v8 executed finished !! ********** \n"; return 0; }
30.980861
106
0.567104
reichtiger
704687f51a5d25683a21da0cfe97488a3dc540d2
3,734
cpp
C++
samples/parser.cpp
tlammi/upp
480615e11b8dd12b36fee0e78b984e1b5051183d
[ "MIT" ]
null
null
null
samples/parser.cpp
tlammi/upp
480615e11b8dd12b36fee0e78b984e1b5051183d
[ "MIT" ]
null
null
null
samples/parser.cpp
tlammi/upp
480615e11b8dd12b36fee0e78b984e1b5051183d
[ "MIT" ]
null
null
null
#include "upp/parser.hpp" #include <iterator> #include <iostream> #include <fstream> #include <string_view> #include <map> #include <vector> #include <variant> struct Value; using Obj = std::map<std::string, Value>; // Deque to avoid relocation on assignment using List = std::deque<Value>; using ValueBase = std::variant<std::monostate, int, std::string, Obj, List>; struct Value: public ValueBase { using ValueBase::ValueBase; }; struct ObjFactory{ ObjFactory(){} void push_value(Value&& val){ if(current_key == ""){ std::get<List>(*stack.back()).push_back(std::move(val)); } else { std::get<Obj>(*stack.back())[current_key] = val; current_key = ""; } } void push_container(Value&& container){ if(!stack.size()){ root = std::move(container); stack.push_back(&root); } else if(current_key != ""){ auto& obj = std::get<Obj>(*stack.back()); obj[current_key] = std::move(container); stack.push_back(&obj.at(current_key)); current_key = ""; } else { auto& list = std::get<List>(*stack.back()); list.push_back(std::move(container)); stack.push_back(&list.back()); } } void push_key(std::string&& str){ current_key = str; } void move_up(){ stack.pop_back(); } Value root{}; std::deque<Value*> stack{}; std::string current_key{""}; }; namespace p = upp::parser; int main(int argc, char** argv){ if(argc != 2) throw std::runtime_error("Input JSON file required"); std::ifstream fs{argv[1]}; std::string str{std::istreambuf_iterator<char>(fs), std::istreambuf_iterator<char>()}; auto json = ObjFactory(); // Utility object so <Iter> does not need to be specified each time auto factory = p::Factory<std::string::const_iterator>(); // Matches literal '{' and invokes callback on match auto obj_begin = factory.lit('{', [&](auto begin, auto end){ (void)begin; (void)end; json.push_container(Obj()); }); auto obj_end = factory.lit('}', [&](auto begin, auto end){ (void)begin; (void)end; json.move_up(); }); auto list_begin = factory.lit('[', [&](auto begin, auto end){ (void)begin; (void)end; std::cerr << "list begin\n"; json.push_container(List()); }); auto list_end = factory.lit(']', [&](auto begin, auto end){ (void)begin; (void)end; std::cerr << "list end\n"; json.move_up(); }); // Regex for matching quoted strings auto quoted = factory.regex(R"(".*?[^\\]")", "quoted string", [&](auto begin, auto end){ json.push_value(std::string(begin+1, end-1)); }); // Copy matcher from quoted but override the callback auto key = factory.ast(quoted, [&](auto begin, auto end){ json.push_key(std::string(begin+1, end-1)); }); // Match integer auto integer = factory.regex(R"(0|[1-9][0-9]*)", "integer", [&](auto begin, auto end){ int i = std::stoi(std::string(begin, end)); json.push_value(i); }); // Forward declarations to allow recursive matching auto obj = factory.dyn_ast(); auto list = factory.dyn_ast([](auto begin, auto end){ std::cerr << "list: " << std::string(begin, end) << '\n'; }); // Match any of the alternatives auto value = (quoted | integer | obj | list); // Match "quoted str": <value> auto key_value = (key, factory.lit(':'), value); // Declaration of a JSON object // - -> zero or one // * -> zero to inf obj = (obj_begin, -(key_value), *(factory.lit(','), key_value), obj_end); list = (list_begin, -(value), *(factory.lit(','), value), list_end); auto obj_or_list = (obj | list); auto result = p::parse(str.cbegin(), str.cend(), obj_or_list, p::whitespaces); if(result) std::cerr << "Successfull parse\n"; else{ std::cerr << "failed to parse\n"; std::cerr << argv[1] << ":" << p::error_msg(str.cbegin(), str.cend(), result) << '\n'; } }
24.405229
89
0.633369
tlammi
704762ae42702157acd11411a5a7c08b295231cb
727
cpp
C++
Project_2DGameSDK/src/world/GameWorld.cpp
markoczy/2DGameSDK
53da378d604ace1d931dfe6ec336241045675667
[ "MIT" ]
1
2020-12-15T08:20:44.000Z
2020-12-15T08:20:44.000Z
Project_2DGameSDK/src/world/GameWorld.cpp
markoczy/2DGameSDK
53da378d604ace1d931dfe6ec336241045675667
[ "MIT" ]
8
2019-09-14T10:05:33.000Z
2019-09-25T18:47:59.000Z
Project_2DGameSDK/src/world/GameWorld.cpp
markoczy/2DGameSDK
53da378d604ace1d931dfe6ec336241045675667
[ "MIT" ]
null
null
null
#include <2DGameSDK/world/GameWorld.h> using namespace sf; namespace game { GameWorld::GameWorld(Game* game, Tilemap* tilemap, MaterialMap* materialMap) : mGame(game), mTilemap(tilemap), mMaterialMap(materialMap) { mBounds.width = mTilemap->TileWidth * mTilemap->TilesWide; mBounds.height = mTilemap->TileHeight * mTilemap->TilesHigh; loadTilemap(); } GameWorld::~GameWorld() { helpers::safeDelete(mTilemap); helpers::safeDelete(mMaterialMap); } sf::IntRect GameWorld::GetBounds() { return mBounds; } void GameWorld::loadTilemap() { for(auto layer : mTilemap->Layers) { mGame->GetStateManager()->AddVisualObject(layer); } } } // namespace game
27.961538
141
0.672627
markoczy
704b287c3fb15089d13601b52d15e9d22b1a8727
2,215
cpp
C++
leetcode/problems/hard/1293-shortest-path-in-a-grid-with-obstacles-elimination.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/hard/1293-shortest-path-in-a-grid-with-obstacles-elimination.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/hard/1293-shortest-path-in-a-grid-with-obstacles-elimination.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Shortest Path in a Grid with Obstacles Elimination https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/ You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1. Example 1: Input: grid = [[0,0,0], [1,1,0], [0,0,0], [0,1,1], [0,0,0]], k = 1 Output: 6 Explanation: The shortest path without eliminating any obstacle is 10. The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2). Example 2: Input: grid = [[0,1,1], [1,1,1], [1,0,0]], k = 1 Output: -1 Explanation: We need to eliminate at least two obstacles to find such a walk. Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 40 1 <= k <= m * n grid[i][j] == 0 or 1 grid[0][0] == grid[m - 1][n - 1] == 0 */ class Solution { public: int shortestPath(vector<vector<int>> &grid, int k) { const int dx[4] = {-1, 0, 0, 1}, dy[4] = {0, -1, 1, 0}; int m = grid.size(), n = grid[0].size(), step = 0; vector<vector<int>> remains(m, vector<int>(n, INT_MIN)); queue<vector<int>> q; q.push({0, 0, k}), remains[0][0] = k; while(!q.empty()) { for(int it = q.size(); it > 0; it--) { auto cur = q.front(); q.pop(); if(cur[0] == m - 1 && cur[1] == n - 1) return step; for(int i = 0; i < 4; i++) { int x = cur[0] + dx[i], y = cur[1] + dy[i]; if(x < 0 || x >= m || y < 0 || y >= n) continue; int remain = cur[2] - grid[x][y]; if(remain >= 0 && remain > remains[x][y]) { q.push({x, y, remain}); remains[x][y] = remain; } } } step++; } return -1; } };
28.766234
218
0.506998
wingkwong
704c0f47f9e2a1552f926a54281972ea39ee9ad8
1,380
cpp
C++
medium/5_longest_palindromic_substring.cpp
pdu/leetcode_cpp
c487df7561f92562b20a31317957f47e0a20c485
[ "Apache-2.0" ]
4
2019-07-22T03:53:23.000Z
2019-10-17T01:37:41.000Z
medium/5_longest_palindromic_substring.cpp
pdu/leetcode_cpp
c487df7561f92562b20a31317957f47e0a20c485
[ "Apache-2.0" ]
null
null
null
medium/5_longest_palindromic_substring.cpp
pdu/leetcode_cpp
c487df7561f92562b20a31317957f47e0a20c485
[ "Apache-2.0" ]
2
2020-03-10T03:30:41.000Z
2020-11-10T06:51:34.000Z
// step 1: clarify // // Q: how long is the string? // A: at most 1000 // // step 2: solutions // // the naive way is to enumate all the substrings, and check whether it's palindromic or not // time complexity: O(n^3) // space complexity: O(1) // // for the palindromic string, it's substring s[1, n-1) must be palindromic string and s[0] == s[n-1] // so we can use dynamic programming to solve the problem. // time complexity: O(n^2) // space complexity: O(n^2), can optimise to O(n) // // step 3: coding // // step 4: testing #include <string> #include <vector> using namespace std; class Solution { public: string longestPalindrome(string s) { if (s.empty()) return s; int n = s.length(); int ret_start = 0; int ret_len = 1; vector<vector<bool>> f(3, vector<bool>(n, true)); for (int len = 2; len <= n; ++len) { if (ret_len < len - 2) break; int row = len % 3; int prev_row = (len - 2) % 3; for (int start = 0, end = start + len - 1; end < n; ++start, ++end) { f[row][start] = s[start] == s[end] && f[prev_row][start + 1]; if (f[row][start]) { ret_len = len; ret_start = start; } } } return s.substr(ret_start, ret_len); } };
27.058824
101
0.521739
pdu