hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
f7469e5417a8f33a50284c86f9afc5f6645c102e
828
cpp
C++
dynamic_programming/lis.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
13
2018-08-23T22:11:23.000Z
2021-06-10T04:15:09.000Z
dynamic_programming/lis.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
null
null
null
dynamic_programming/lis.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
3
2019-09-06T17:44:38.000Z
2019-09-10T12:41:35.000Z
#include <bits/stdc++.h> using namespace std; template <int sz> struct Bit { int b[sz]; void upd(int x, int val) { for (int i = x; i < sz; i += i&-i) b[i] = max(b[i], val); } int get(int x) { int ans = 0; for (int i = x; i; i -= i&-i) ans = max(ans, b[i]); return ans; } }; template <typename T> void compress(T* v, int n) { vector<T> vv(n+1); for (int i = 1; i <= n; i++) vv[i] = v[i]; sort(vv.begin()+1, vv.end()); for (int i = 1; i <= n; i++) v[i] = lower_bound(vv.begin()+1, vv.end(), v[i]) - vv.begin(); } const int maxn = 101010; int v[maxn]; Bit<maxn> bt; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) cin >> v[i]; compress(v, n); for (int i = 1; i <= n; i++) { int x = bt.get(v[i]-1); bt.upd(v[i], x+1); } int ans = bt.get(n); cout << ans << "\n"; }
13.57377
64
0.487923
fredbr
f749d19fea660e971067395201e90459581e3ebd
81,525
cpp
C++
lib/vdc/DerivedVar.cpp
gaybro8777/VAPOR
13919120a0b6fef39fde18bc49b7a04171e0c6cf
[ "BSD-3-Clause" ]
120
2017-07-31T08:40:34.000Z
2022-03-24T03:57:35.000Z
lib/vdc/DerivedVar.cpp
gaybro8777/VAPOR
13919120a0b6fef39fde18bc49b7a04171e0c6cf
[ "BSD-3-Clause" ]
2,215
2017-06-21T20:47:30.000Z
2022-03-31T22:41:38.000Z
lib/vdc/DerivedVar.cpp
gaybro8777/VAPOR
13919120a0b6fef39fde18bc49b7a04171e0c6cf
[ "BSD-3-Clause" ]
48
2017-08-02T22:56:40.000Z
2022-02-12T13:44:51.000Z
#include "vapor/VAssert.h" #include <sstream> #include <algorithm> #include <set> #include <vapor/UDUnitsClass.h> #include <vapor/NetCDFCollection.h> #include <vapor/utils.h> #include <vapor/WASP.h> #include <vapor/DerivedVar.h> #include <vapor/GeoUtil.h> using namespace VAPoR; using namespace Wasp; namespace { #ifdef UNUSED_FUNCTION size_t numBlocks(size_t min, size_t max, size_t bs) { size_t b0 = min / bs; size_t b1 = max / bs; return (b1 - b0 + 1); } #endif #ifdef UNUSED_FUNCTION size_t numBlocks(const vector<size_t> &min, const vector<size_t> &max, const vector<size_t> &bs) { VAssert(min.size() == max.size()); VAssert(min.size() == bs.size()); size_t nblocks = 1; for (int i = 0; i < bs.size(); i++) { nblocks *= numBlocks(min[i], max[i], bs[i]); } return (nblocks); } #endif #ifdef UNUSED_FUNCTION size_t numBlocks(const vector<size_t> &dims, const vector<size_t> &bs) { VAssert(dims.size() == bs.size()); size_t nblocks = 1; for (int i = 0; i < bs.size(); i++) { VAssert(dims[i] != 0); nblocks *= (((dims[i] - 1) / bs[i]) + 1); } return (nblocks); } #endif size_t numElements(const vector<size_t> &min, const vector<size_t> &max) { VAssert(min.size() == max.size()); size_t nElements = 1; for (int i = 0; i < min.size(); i++) { nElements *= (max[i] - min[i] + 1); } return (nElements); } #ifdef UNUSED_FUNCTION size_t blockSize(const vector<size_t> &bs) { size_t sz = 1; for (int i = 0; i < bs.size(); i++) { sz *= bs[i]; } return (sz); } #endif #ifdef UNUSED_FUNCTION vector<size_t> increment(vector<size_t> dims, vector<size_t> coord) { VAssert(dims.size() == coord.size()); for (int i = 0; i < coord.size(); i++) { coord[i] += 1; if (coord[i] < (dims[i])) { break; } coord[i] = 0; } return (coord); } #endif // Product of elements in a vector // size_t vproduct(vector<size_t> a) { size_t ntotal = 1; for (int i = 0; i < a.size(); i++) ntotal *= a[i]; return (ntotal); } #ifdef UNUSED_FUNCTION void extractBlock(const float *data, const vector<size_t> &dims, const vector<size_t> &bcoords, const vector<size_t> &bs, float *block) { VAssert(dims.size() == bcoords.size()); VAssert(dims.size() == bs.size()); // Block dimensions // size_t bz = bs.size() > 2 ? bs[2] : 1; size_t by = bs.size() > 1 ? bs[1] : 1; size_t bx = bs.size() > 0 ? bs[0] : 1; // Data dimensions // size_t nz = dims.size() > 2 ? dims[2] : 1; size_t ny = dims.size() > 1 ? dims[1] : 1; size_t nx = dims.size() > 0 ? dims[0] : 1; // Data dimensions // size_t bcz = bcoords.size() > 2 ? bcoords[2] : 0; size_t bcy = bcoords.size() > 1 ? bcoords[1] : 0; size_t bcx = bcoords.size() > 0 ? bcoords[0] : 0; size_t z = bcz * bz; for (size_t zb = 0; zb < bz && z < nz; zb++, z++) { size_t y = bcy * by; for (size_t yb = 0; yb < by && y < ny; yb++, y++) { size_t x = bcx * bx; for (size_t xb = 0; xb < bx && x < nx; xb++, x++) { block[bx * by * zb + bx * yb + xb] = data[nx * ny * z + nx * y + x]; } } } } #endif #ifdef UNUSED_FUNCTION void blockit(const float *data, const vector<size_t> &dims, const vector<size_t> &bs, float *blocks) { VAssert(dims.size() == bs.size()); size_t block_size = vproduct(bs); vector<size_t> bdims; for (int i = 0; i < bs.size(); i++) { VAssert(dims[i] > 0); bdims.push_back(((dims[i] - 1) / bs[i]) + 1); } size_t nbz = bdims.size() > 2 ? bdims[2] : 1; size_t nby = bdims.size() > 1 ? bdims[1] : 1; size_t nbx = bdims.size() > 0 ? bdims[0] : 1; float * blockptr = blocks; vector<size_t> bcoord(bdims.size(), 0); for (size_t zb = 0; zb < nbz; zb++) { for (size_t yb = 0; yb < nby; yb++) { for (size_t xb = 0; xb < nbx; xb++) { extractBlock(data, dims, bcoord, bs, blockptr); blockptr += block_size; bcoord = increment(bdims, bcoord); } } } } #endif // make 2D lat and lon arrays from 1D arrays by replication, in place // void make2D(float *lonBuf, float *latBuf, vector<size_t> dims) { VAssert(dims.size() == 2); size_t nx = dims[0]; size_t ny = dims[1]; // longitude // for (int j = 1; j < ny; j++) { for (int i = 0; i < nx; i++) { lonBuf[j * nx + i] = lonBuf[i]; } } // latitude requires a transpose first // for (int i = 0; i < ny; i++) { latBuf[i * nx] = latBuf[i]; } for (int j = 0; j < ny; j++) { for (int i = 1; i < nx; i++) { latBuf[j * nx + i] = latBuf[j * nx]; } } } // Transpose a 1D, 2D, or 3D array. For 1D 'a' is simply copied // to 'b'. Otherwise 'b' contains a permuted version of 'a' as follows: // // axis 1D 2D 3D // ---- -- -- -- // 0 (0) (0,1) (0,1,2) // 1 N/A (1,0) (1,0,2) // 2 N/A N/A (2,0,1) // // where the numbers in parenthesis indicate the permutation of the // axes. // // NOTE: The contents of 'a' are overwritten // void transpose(float *a, float *b, vector<size_t> inDims, int axis) { VAssert(inDims.size() < 4); VAssert(axis >= 0 && axis < inDims.size()); size_t sz = vproduct(inDims); // No-op if axis is 0 // if (axis == 0) { // 1D, 2D, and 3D case for (size_t i = 0; i < sz; i++) { b[i] = a[i]; } return; } if (inDims.size() == 2) { VAssert(axis == 1); Wasp::Transpose(a, b, inDims[0], inDims[1]); } else if (inDims.size() == 3) { VAssert(axis == 1 || axis == 2); size_t stride = inDims[0] * inDims[1]; ; const float *aptr = a; float * bptr = b; for (size_t i = 0; i < inDims[2]; i++) { Wasp::Transpose(aptr, bptr, inDims[0], inDims[1]); aptr += stride; bptr += stride; } // For (2,1,0) permutation we do (0,1,2) -> (1,0,2) -> (2,1,0) // if (axis == 2) { // We can treat 3D array as 2D in this case, linearizing X and Y // Wasp::Transpose(b, a, inDims[0] * inDims[1], inDims[2]); // Ugh need to copy data from a back to b // for (size_t i = 0; i < vproduct(inDims); i++) { b[i] = a[i]; } } } } void transpose(vector<size_t> inDims, int axis, vector<size_t> &outDims) { outDims = inDims; if (axis == 1) { size_t tmp = outDims[0]; outDims[0] = outDims[1]; outDims[1] = tmp; } else if (axis == 2) { size_t tmp = outDims[0]; outDims[0] = outDims[2]; outDims[2] = tmp; } } void resampleToStaggered(float *src, const vector<size_t> &inMin, const vector<size_t> &inMax, float *dst, const vector<size_t> &outMin, const vector<size_t> &outMax, int stagDim) { VAssert(inMin.size() == inMax.size()); VAssert(inMin.size() == outMax.size()); VAssert(inMin.size() == outMax.size()); vector<size_t> inDims, outDims; for (size_t i = 0; i < outMin.size(); i++) { inDims.push_back(inMax[i] - inMin[i] + 1); outDims.push_back(outMax[i] - outMin[i] + 1); } size_t sz = std::max(vproduct(outDims), vproduct(inDims)); float *buf = new float[sz]; // Tranpose the dimensions and array so that we always interpolate // with unit stride // vector<size_t> inDimsT; // transposed input dimensions vector<size_t> outDimsT; // transposed output dimensions transpose(inDims, stagDim, inDimsT); transpose(outDims, stagDim, outDimsT); transpose(src, buf, inDims, stagDim); size_t nz = inDimsT.size() >= 3 ? inDimsT[2] : 1; size_t ny = inDimsT.size() >= 2 ? inDimsT[1] : 1; size_t nx = inDimsT.size() >= 1 ? inDimsT[0] : 1; // Interpolate interior // size_t nxs = outDimsT[0]; // staggered dimension size_t i0 = outMin[stagDim] > inMin[stagDim] ? 0 : 1; for (size_t k = 0; k < nz; k++) { for (size_t j = 0; j < ny; j++) { for (size_t i = 0, ii = i0; i < nx - 1; i++, ii++) { src[k * nxs * ny + j * nxs + ii] = 0.5 * (buf[k * nx * ny + j * nx + i] + buf[k * nx * ny + j * nx + i + 1]); } } } // Next extrapolate boundary points if needed // // left boundary // if (outMin[stagDim] <= inMin[stagDim]) { if (inMin[stagDim] < inMax[stagDim]) { for (size_t k = 0; k < nz; k++) { for (size_t j = 0; j < ny; j++) { src[k * nxs * ny + j * nxs] = buf[k * nx * ny + j * nx + 0] + (-0.5 * (buf[k * nx * ny + j * nx + 1] - buf[k * nx * ny + j * nx + 0])); } } } else { for (size_t k = 0; k < nz; k++) { for (size_t j = 0; j < ny; j++) { src[k * nxs * ny + j * nxs] = buf[k * nx * ny + j * nx + 0]; } } } } // right boundary // if (outMax[stagDim] > inMax[stagDim]) { if (inMin[stagDim] < inMax[stagDim]) { for (size_t k = 0; k < nz; k++) { for (size_t j = 0; j < ny; j++) { src[k * nxs * ny + j * nxs + nxs - 1] = buf[k * nx * ny + j * nx + nx - 1] + (0.5 * (buf[k * nx * ny + j * nx + nx - 1] - buf[k * nx * ny + j * nx + nx - 2])); } } } else { for (size_t k = 0; k < nz; k++) { for (size_t j = 0; j < ny; j++) { src[k * nxs * ny + j * nxs + nxs - 1] = buf[k * nx * ny + j * nx + nx - 1]; } } } } // Undo tranpose // transpose(src, dst, outDimsT, stagDim); delete[] buf; } void resampleToUnStaggered(float *src, const vector<size_t> &inMin, const vector<size_t> &inMax, float *dst, const vector<size_t> &outMin, const vector<size_t> &outMax, int stagDim) { VAssert(inMin.size() == inMax.size()); VAssert(inMin.size() == outMax.size()); VAssert(inMin.size() == outMax.size()); vector<size_t> myOutMax = outMax; vector<size_t> myOutMin = outMin; myOutMin[stagDim] += 1; myOutMax[stagDim] += 1; resampleToStaggered(src, inMin, inMax, dst, myOutMin, myOutMax, stagDim); } #ifdef UNIT_TEST void print_matrix(const float *a, const vector<size_t> &dims) { size_t nz = dims.size() >= 3 ? dims[2] : 1; size_t ny = dims.size() >= 2 ? dims[1] : 1; size_t nx = dims.size() >= 1 ? dims[0] : 1; for (int k = 0; k < nz; k++) { for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { cout << a[k * nx * ny + j * nx + i] << " "; } cout << endl; } cout << endl; } } void test_resample(int stagDim) { vector<size_t> inMin = {0, 0, 0}; vector<size_t> inMax = {1, 2, 3}; vector<size_t> outMin = inMin; vector<size_t> outMax = inMax; outMax[stagDim] += 1; vector<size_t> inDims, outDims; for (int i = 0; i < inMax.size(); i++) { inDims.push_back(inMax[i] - inMin[i] + 1); outDims.push_back(outMax[i] - outMin[i] + 1); } size_t nz = inDims.size() >= 3 ? inDims[2] : 1; size_t ny = inDims.size() >= 2 ? inDims[1] : 1; size_t nx = inDims.size() >= 1 ? inDims[0] : 1; size_t nzs = outDims.size() >= 3 ? outDims[2] : 1; size_t nys = outDims.size() >= 2 ? outDims[1] : 1; size_t nxs = outDims.size() >= 1 ? outDims[0] : 1; size_t sz = std::max(vproduct(outDims), vproduct(inDims)); float *src = new float[sz]; float *dst = new float[sz]; for (int k = 0; k < nz; k++) { for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { src[k * nx * ny + j * nx + i] = k * nx * ny + j * nx + i; } } } for (int k = 0; k < nzs; k++) { for (int j = 0; j < nys; j++) { for (int i = 0; i < nxs; i++) { dst[k * nxs * nys + j * nxs + i] = 99; } } } cout << "original array" << endl; print_matrix(src, inDims); resampleToStaggered(src, inMin, inMax, dst, outMin, outMax, stagDim); cout << endl << endl; cout << "staggered array" << endl; print_matrix(dst, outDims); resampleToUnStaggered(dst, outMin, outMax, src, inMin, inMax, stagDim); cout << "reconstructed unstaggered array" << endl; print_matrix(src, inDims); } int main(int argc, char **argv) { VAssert(argc == 2); int stagDim = atoi(argv[1]); test_resample(stagDim); } #endif }; // namespace int DerivedVar::_getVar(DC *dc, size_t ts, string varname, int level, int lod, const vector<size_t> &min, const vector<size_t> &max, float *region) const { int fd = dc->OpenVariableRead(ts, varname, level, lod); if (fd < 0) return (-1); int rc = dc->ReadRegion(fd, min, max, region); if (rc < 0) { dc->CloseVariable(fd); return (-1); } return (dc->CloseVariable(fd)); } int DerivedVar::_getVarDestagger(DC *dc, size_t ts, string varname, int level, int lod, const vector<size_t> &min, const vector<size_t> &max, float *region, int stagDim) const { VAssert(stagDim >= 0 && stagDim < max.size()); VAssert(min.size() == max.size()); vector<size_t> maxIn = max; maxIn[stagDim]++; vector<size_t> dimsIn; for (int i = 0; i < min.size(); i++) { dimsIn.push_back(max[i] - min[i] + 1); } vector<float> buf(vproduct(dimsIn)); int rc = _getVar(dc, ts, varname, level, lod, min, maxIn, buf.data()); if (rc < 0) return (rc); resampleToUnStaggered(buf.data(), min, maxIn, region, min, max, stagDim); return (0); } int DerivedVar::_getVarBlock(DC *dc, size_t ts, string varname, int level, int lod, const vector<size_t> &min, const vector<size_t> &max, float *region) const { int fd = dc->OpenVariableRead(ts, varname, level, lod); if (fd < 0) return (-1); int rc = dc->ReadRegionBlock(fd, min, max, region); if (rc < 0) { dc->CloseVariable(fd); return (-1); } return (dc->CloseVariable(fd)); } ////////////////////////////////////////////////////////////////////////////// // // DerivedCoordVar_PCSFromLatLon // ////////////////////////////////////////////////////////////////////////////// DerivedCoordVar_PCSFromLatLon::DerivedCoordVar_PCSFromLatLon(string derivedVarName, DC *dc, vector<string> inNames, string proj4String, bool uGridFlag, bool lonFlag) : DerivedCoordVar(derivedVarName) { VAssert(inNames.size() == 2); _dc = dc; _proj4String = proj4String; _lonName = inNames[0]; _latName = inNames[1]; _make2DFlag = false; _uGridFlag = uGridFlag; _lonFlag = lonFlag; _dimLens.clear(); } int DerivedCoordVar_PCSFromLatLon::Initialize() { int rc = _proj4API.Initialize("", _proj4String); if (rc < 0) { SetErrMsg("Invalid map projection : %s", _proj4String.c_str()); return (-1); } rc = _setupVar(); if (rc < 0) return (-1); return (0); } bool DerivedCoordVar_PCSFromLatLon::GetBaseVarInfo(DC::BaseVar &var) const { var = _coordVarInfo; return (true); } bool DerivedCoordVar_PCSFromLatLon::GetCoordVarInfo(DC::CoordVar &cvar) const { cvar = _coordVarInfo; return (true); } int DerivedCoordVar_PCSFromLatLon::GetDimLensAtLevel(int, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level) const { dims_at_level.clear(); bs_at_level.clear(); dims_at_level = _dimLens; // No blocking // bs_at_level = vector<size_t>(dims_at_level.size(), 1); return (0); } int DerivedCoordVar_PCSFromLatLon::OpenVariableRead(size_t ts, int, int) { DC::FileTable::FileObject *f = new DC::FileTable::FileObject(ts, _derivedVarName, -1, -1); return (_fileTable.AddEntry(f)); } int DerivedCoordVar_PCSFromLatLon::CloseVariable(int fd) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } _fileTable.RemoveEntry(fd); delete f; return (0); } int DerivedCoordVar_PCSFromLatLon::_readRegionHelperCylindrical(DC::FileTable::FileObject *f, const vector<size_t> &min, const vector<size_t> &max, float *region) { VAssert(min.size() == 1); VAssert(min.size() == max.size()); size_t ts = f->GetTS(); string varname = f->GetVarname(); int lod = f->GetLOD(); size_t nElements = max[0] - min[0] + 1; vector<float> buf(nElements, 0.0); string geoCoordVar; if (_lonFlag) { geoCoordVar = _lonName; } else { geoCoordVar = _latName; } int rc = _getVar(_dc, ts, geoCoordVar, -1, lod, min, max, region); if (rc < 0) { return (rc); } if (_lonFlag) { if (_proj4API.IsCylindrical()) { GeoUtil::UnwrapLongitude(region, region + nElements); GeoUtil::ShiftLon(region, region + nElements); } rc = _proj4API.Transform(region, buf.data(), nElements); } else { rc = _proj4API.Transform(buf.data(), region, nElements); } return (rc); } int DerivedCoordVar_PCSFromLatLon::_readRegionHelper1D(DC::FileTable::FileObject *f, const vector<size_t> &min, const vector<size_t> &max, float *region) { size_t ts = f->GetTS(); string varname = f->GetVarname(); int lod = f->GetLOD(); // Need temporary buffer space for the X or Y coordinate // NOT being returned (we still need to calculate it) // size_t nElements = numElements(min, max); vector<float> buf(nElements); vector<size_t> roidims; for (int i = 0; i < min.size(); i++) { roidims.push_back(max[i] - min[i] + 1); } // Assign temporary buffer 'buf' as appropriate // float *lonBufPtr; float *latBufPtr; if (_lonFlag) { lonBufPtr = region; latBufPtr = buf.data(); } else { lonBufPtr = buf.data(); latBufPtr = region; } // Reading 1D data so no blocking // vector<size_t> lonMin = {min[0]}; vector<size_t> lonMax = {max[0]}; int rc = _getVar(_dc, ts, _lonName, -1, lod, lonMin, lonMax, lonBufPtr); if (rc < 0) { return (rc); } vector<size_t> latMin = {min[1]}; vector<size_t> latMax = {max[1]}; rc = _getVar(_dc, ts, _latName, -1, lod, latMin, latMax, latBufPtr); if (rc < 0) { return (rc); } // Combine the 2 1D arrays into a 2D array // make2D(lonBufPtr, latBufPtr, roidims); if (_proj4API.IsCylindrical()) { size_t nx = max[0] - min[0] + 1; size_t ny = max[1] - min[1] + 1; for (size_t j = 0; j < ny; j++) { GeoUtil::UnwrapLongitude(lonBufPtr + (j * nx), lonBufPtr + (j * nx) + nx); GeoUtil::ShiftLon(lonBufPtr + (j * nx), lonBufPtr + (j * nx) + nx); } } rc = _proj4API.Transform(lonBufPtr, latBufPtr, vproduct(roidims)); return (rc); } int DerivedCoordVar_PCSFromLatLon::_readRegionHelper2D(DC::FileTable::FileObject *f, const vector<size_t> &min, const vector<size_t> &max, float *region) { size_t ts = f->GetTS(); string varname = f->GetVarname(); int lod = f->GetLOD(); // Need temporary buffer space for the X or Y coordinate // NOT being returned (we still need to calculate it) // size_t nElements = numElements(min, max); vector<float> buf(nElements); // Assign temporary buffer 'buf' as appropriate // float *lonBufPtr; float *latBufPtr; if (_lonFlag) { lonBufPtr = region; latBufPtr = buf.data(); } else { lonBufPtr = buf.data(); latBufPtr = region; } int rc = _getVar(_dc, ts, _lonName, -1, lod, min, max, lonBufPtr); if (rc < 0) { return (rc); } if (_proj4API.IsCylindrical()) { size_t nx = max[0] - min[0] + 1; size_t ny = max[1] - min[1] + 1; for (size_t j = 0; j < ny; j++) { GeoUtil::UnwrapLongitude(lonBufPtr + (j * nx), lonBufPtr + (j * nx) + nx); GeoUtil::ShiftLon(lonBufPtr + (j * nx), lonBufPtr + (j * nx) + nx); } } rc = _getVar(_dc, ts, _latName, -1, lod, min, max, latBufPtr); if (rc < 0) { return (rc); } rc = _proj4API.Transform(lonBufPtr, latBufPtr, nElements); return (rc); } int DerivedCoordVar_PCSFromLatLon::ReadRegion(int fd, const vector<size_t> &min, const vector<size_t> &max, float *region) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor: %d", fd); return (-1); } if (min.size() == 1) { // Lat and Lon are 1D variables // return (_readRegionHelperCylindrical(f, min, max, region)); } else { if (_make2DFlag) { // Lat and Lon are 1D variables but projections to PCS // result in X and Y coordinate variables that are 2D // return (_readRegionHelper1D(f, min, max, region)); } else { return (_readRegionHelper2D(f, min, max, region)); } } } bool DerivedCoordVar_PCSFromLatLon::VariableExists(size_t ts, int, int) const { return (_dc->VariableExists(ts, _lonName, -1, -1) && _dc->VariableExists(ts, _latName, -1, -1)); } int DerivedCoordVar_PCSFromLatLon::_setupVar() { DC::CoordVar lonVar; bool ok = _dc->GetCoordVarInfo(_lonName, lonVar); if (!ok) return (-1); DC::CoordVar latVar; ok = _dc->GetCoordVarInfo(_latName, latVar); if (!ok) return (-1); vector<size_t> lonDims; ok = _dc->GetVarDimLens(_lonName, true, lonDims, -1); if (!ok) { SetErrMsg("GetVarDimLens(%s) failed", _lonName.c_str()); return (-1); } vector<size_t> latDims; ok = _dc->GetVarDimLens(_latName, true, latDims, -1); if (!ok) { SetErrMsg("GetVarDimLens(%s) failed", _lonName.c_str()); return (-1); } if (lonDims.size() != latDims.size()) { SetErrMsg("Incompatible block size"); return (-1); } bool cylProj = _proj4API.IsCylindrical(); vector<string> dimNames; if (lonVar.GetDimNames().size() == 1 && !_uGridFlag) { if (cylProj) { if (_lonFlag) { dimNames.push_back(lonVar.GetDimNames()[0]); _dimLens.push_back(lonDims[0]); } else { dimNames.push_back(latVar.GetDimNames()[0]); _dimLens.push_back(latDims[0]); } } else { dimNames.push_back(lonVar.GetDimNames()[0]); dimNames.push_back(latVar.GetDimNames()[0]); _dimLens.push_back(lonDims[0]); _dimLens.push_back(latDims[0]); _make2DFlag = true; } } else if (lonVar.GetDimNames().size() == 2 && !_uGridFlag) { if (lonDims[0] != latDims[0] && lonDims[1] != latDims[1]) { SetErrMsg("Incompatible dimensions "); return (-1); } dimNames.push_back(lonVar.GetDimNames()[0]); dimNames.push_back(lonVar.GetDimNames()[1]); _dimLens.push_back(lonDims[0]); _dimLens.push_back(lonDims[1]); _make2DFlag = false; } else { VAssert(lonVar.GetDimNames().size() == 1 && _uGridFlag); dimNames = lonVar.GetDimNames(); _dimLens = lonDims; } if (lonVar.GetTimeDimName() != latVar.GetTimeDimName()) { SetErrMsg("Incompatible time dimensions"); return (-1); } string timeDimName = lonVar.GetTimeDimName(); DC::XType xtype = lonVar.GetXType(); vector<bool> periodic = lonVar.GetPeriodic(); _coordVarInfo.SetName(_derivedVarName); _coordVarInfo.SetUnits("meters"); _coordVarInfo.SetXType(xtype); _coordVarInfo.SetWName(""); _coordVarInfo.SetCRatios(vector<size_t>()); _coordVarInfo.SetPeriodic(periodic); _coordVarInfo.SetUniform(false); _coordVarInfo.SetDimNames(dimNames); _coordVarInfo.SetTimeDimName(timeDimName); _coordVarInfo.SetAxis(_lonFlag ? 0 : 1); return (0); } ////////////////////////////////////////////////////////////////////////////// // // DerivedCoordVar_CF1D // ////////////////////////////////////////////////////////////////////////////// DerivedCoordVar_CF1D::DerivedCoordVar_CF1D(string derivedVarName, DC *dc, string dimName, int axis, string units) : DerivedCoordVar(derivedVarName) { _dc = dc; _dimName = dimName; _coordVarInfo = DC::CoordVar(_derivedVarName, units, DC::XType::FLOAT, vector<bool>(1, false), axis, true, vector<string>(1, dimName), ""); } int DerivedCoordVar_CF1D::Initialize() { return (0); } bool DerivedCoordVar_CF1D::GetBaseVarInfo(DC::BaseVar &var) const { var = _coordVarInfo; return (true); } bool DerivedCoordVar_CF1D::GetCoordVarInfo(DC::CoordVar &cvar) const { cvar = _coordVarInfo; return (true); } int DerivedCoordVar_CF1D::GetDimLensAtLevel(int level, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level) const { return GetDimLensAtLevel(level, dims_at_level, bs_at_level, -1); } int DerivedCoordVar_CF1D::GetDimLensAtLevel(int level, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level, long ts) const { dims_at_level.clear(); bs_at_level.clear(); DC::Dimension dimension; int rc = _dc->GetDimension(_dimName, dimension, ts); if (rc < 0) return (-1); dims_at_level.push_back(dimension.GetLength()); // No blocking // bs_at_level = vector<size_t>(dims_at_level.size(), 1); return (0); } int DerivedCoordVar_CF1D::OpenVariableRead(size_t ts, int level, int lod) { DC::FileTable::FileObject *f = new DC::FileTable::FileObject(ts, _derivedVarName, level, lod); return (_fileTable.AddEntry(f)); } int DerivedCoordVar_CF1D::CloseVariable(int fd) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } _fileTable.RemoveEntry(fd); delete f; return (0); } int DerivedCoordVar_CF1D::ReadRegion(int fd, const vector<size_t> &min, const vector<size_t> &max, float *region) { VAssert(min.size() == 1); VAssert(max.size() == 1); float *regptr = region; for (size_t i = min[0]; i <= max[0]; i++) { *regptr++ = (float)i; } return (0); } bool DerivedCoordVar_CF1D::VariableExists(size_t ts, int reflevel, int lod) const { if (reflevel != 0) return (false); if (lod != 0) return (false); return (true); } ////////////////////////////////////////////////////////////////////////////// // // DerivedCoordVar_CF2D // ////////////////////////////////////////////////////////////////////////////// DerivedCoordVar_CF2D::DerivedCoordVar_CF2D(string derivedVarName, vector<string> dimNames, vector<size_t> dimLens, int axis, string units, const vector<float> &data) : DerivedCoordVar(derivedVarName) { VAssert(dimNames.size() == 2); VAssert(dimLens.size() == 2); VAssert(dimLens[0] * dimLens[1] <= data.size()); _dimNames = dimNames; _dimLens = dimLens; _data = data; _coordVarInfo = DC::CoordVar(_derivedVarName, units, DC::XType::FLOAT, vector<bool>(2, false), axis, false, dimNames, ""); } int DerivedCoordVar_CF2D::Initialize() { return (0); } bool DerivedCoordVar_CF2D::GetBaseVarInfo(DC::BaseVar &var) const { var = _coordVarInfo; return (true); } bool DerivedCoordVar_CF2D::GetCoordVarInfo(DC::CoordVar &cvar) const { cvar = _coordVarInfo; return (true); } int DerivedCoordVar_CF2D::GetDimLensAtLevel(int level, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level) const { dims_at_level.clear(); bs_at_level.clear(); dims_at_level = _dimLens; // No blocking // bs_at_level = vector<size_t>(dims_at_level.size(), 1); return (0); } int DerivedCoordVar_CF2D::OpenVariableRead(size_t ts, int level, int lod) { return (0); } int DerivedCoordVar_CF2D::CloseVariable(int fd) { return (0); } int DerivedCoordVar_CF2D::ReadRegion(int fd, const vector<size_t> &min, const vector<size_t> &max, float *region) { VAssert(min.size() == 2); VAssert(max.size() == 2); float *regptr = region; for (size_t j = min[1]; j <= max[1]; j++) { for (size_t i = min[0]; i <= max[0]; i++) { *regptr++ = (float)_data[j * _dimLens[0] + i]; } } return (0); } bool DerivedCoordVar_CF2D::VariableExists(size_t ts, int reflevel, int lod) const { if (reflevel != 0) return (false); if (lod != 0) return (false); return (true); } ////////////////////////////////////////////////////////////////////////////// // // DerivedCoordVar_WRFTime // ////////////////////////////////////////////////////////////////////////////// DerivedCoordVar_WRFTime::DerivedCoordVar_WRFTime(string derivedVarName, NetCDFCollection *ncdfc, string wrfTimeVar, string dimName, float p2si) : DerivedCoordVar(derivedVarName) { _ncdfc = ncdfc; _times.clear(); _timePerm.clear(); _wrfTimeVar = wrfTimeVar; _p2si = p2si; _ovr_ts = 0; string units = "seconds"; int axis = 3; _coordVarInfo = DC::CoordVar(_derivedVarName, units, DC::XType::FLOAT, vector<bool>(), axis, false, vector<string>(), dimName); } int DerivedCoordVar_WRFTime::_encodeTime(UDUnits &udunits, const vector<string> &timeStrings, vector<double> &times) const { times.clear(); for (int i = 0; i < timeStrings.size(); i++) { const string &s = timeStrings[i]; const char *format6 = "%4d-%2d-%2d_%2d:%2d:%2d"; int year, mon, mday, hour, min, sec; int rc = sscanf(s.data(), format6, &year, &mon, &mday, &hour, &min, &sec); if (rc != 6) { // Alternate date format // const char *format5 = "%4d-%5d_%2d:%2d:%2d"; rc = sscanf(s.data(), format5, &year, &mday, &hour, &min, &sec); if (rc != 5) { SetErrMsg("Unrecognized time stamp: %s", s.data()); return (-1); } mon = 1; } times.push_back(udunits.EncodeTime(year, mon, mday, hour, min, sec) * _p2si); } return (0); } int DerivedCoordVar_WRFTime::Initialize() { _times.clear(); _timePerm.clear(); // Use UDUnits for unit conversion // UDUnits udunits; int rc = udunits.Initialize(); if (rc < 0) { SetErrMsg("Failed to initialize udunits2 library : %s", udunits.GetErrMsg().c_str()); return (-1); } size_t numTS = _ncdfc->GetNumTimeSteps(); if (numTS < 1) return (0); vector<size_t> dims = _ncdfc->GetSpatialDims(_wrfTimeVar); if (dims.size() != 1) { SetErrMsg("Invalid WRF time variable : %s", _wrfTimeVar.c_str()); return (-1); } // Read all of the formatted time strings up front - it's a 1D array // so we can simply store the results in memory - and convert from // a formatted time string to seconds since the EPOCH // vector<string> timeStrings; char * buf = new char[dims[0] + 1]; buf[dims[0]] = '\0'; for (size_t ts = 0; ts < numTS; ts++) { int fd = _ncdfc->OpenRead(ts, _wrfTimeVar); if (fd < 0) { SetErrMsg("Can't read time variable"); return (-1); } int rc = _ncdfc->Read(buf, fd); if (rc < 0) { SetErrMsg("Can't read time variable"); _ncdfc->Close(fd); delete[] buf; return (-1); } _ncdfc->Close(fd); timeStrings.push_back(buf); } delete[] buf; // Encode time stamp string as double precision float // vector<double> timesD; rc = _encodeTime(udunits, timeStrings, timesD); if (rc < 0) return (rc); // Convert to single precision because that's what the API supports // for (int i = 0; i < timesD.size(); i++) { _times.push_back((float)timesD[i]); } // For high temporal resolution single precision may be insufficient: // converting from double to single may result in non-unique values. // Check to see that the number of unique values is the same for the // double and float vectors. If not, change the year to 2000 to reduce // the precision needed. // if (std::set<double>(timesD.begin(), timesD.end()).size() != std::set<double>(_times.begin(), _times.end()).size()) { _times.clear(); for (int i = 0; i < timeStrings.size(); i++) { timeStrings[i].replace(0, 4, "2000"); } rc = _encodeTime(udunits, timeStrings, timesD); if (rc < 0) return (rc); for (int i = 0; i < timesD.size(); i++) { _times.push_back((float)timesD[i]); } } // The NetCDFCollection class doesn't handle the WRF time // variable. Hence, the time steps aren't sorted. Sort them now and // create a lookup table to map a time index to the correct time step // in the WRF data collection. N.B. this is only necessary if multiple // WRF files are present and they're not passed to Initialize() in // the correct order. // _timePerm.clear(); for (int i = 0; i != _times.size(); i++) { _timePerm.push_back(i); } sort(_timePerm.begin(), _timePerm.end(), [&](const int &a, const int &b) { return (_times[a] < _times[b]); }); return (0); } bool DerivedCoordVar_WRFTime::GetBaseVarInfo(DC::BaseVar &var) const { var = _coordVarInfo; return (true); } bool DerivedCoordVar_WRFTime::GetCoordVarInfo(DC::CoordVar &cvar) const { cvar = _coordVarInfo; return (true); } int DerivedCoordVar_WRFTime::GetDimLensAtLevel(int level, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level) const { dims_at_level.clear(); bs_at_level.clear(); return (0); } int DerivedCoordVar_WRFTime::OpenVariableRead(size_t ts, int level, int lod) { ts = ts < _times.size() ? ts : _times.size() - 1; DC::FileTable::FileObject *f = new DC::FileTable::FileObject(ts, _derivedVarName, level, lod); return (_fileTable.AddEntry(f)); } int DerivedCoordVar_WRFTime::CloseVariable(int fd) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } _fileTable.RemoveEntry(fd); delete f; return (0); } int DerivedCoordVar_WRFTime::ReadRegion(int fd, const vector<size_t> &min, const vector<size_t> &max, float *region) { VAssert(min.size() == 0); VAssert(max.size() == 0); DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor: %d", fd); return (-1); } size_t ts = f->GetTS(); *region = _times[ts]; return (0); } bool DerivedCoordVar_WRFTime::VariableExists(size_t ts, int reflevel, int lod) const { return (ts < _times.size()); } ////////////////////////////////////////////////////////////////////////////// // // DerivedCoordVar_TimeInSeconds // ////////////////////////////////////////////////////////////////////////////// DerivedCoordVar_TimeInSeconds::DerivedCoordVar_TimeInSeconds(string derivedVarName, DC *dc, string nativeTimeVar, string dimName) : DerivedCoordVar(derivedVarName) { _dc = dc; _times.clear(); _nativeTimeVar = nativeTimeVar; string units = "seconds"; int axis = 3; _coordVarInfo = DC::CoordVar(_derivedVarName, units, DC::XType::FLOAT, vector<bool>(), axis, false, vector<string>(), dimName); } int DerivedCoordVar_TimeInSeconds::Initialize() { // Use UDUnits for unit conversion // UDUnits udunits; int rc = udunits.Initialize(); if (rc < 0) { SetErrMsg("Failed to initialize udunits2 library : %s", udunits.GetErrMsg().c_str()); return (-1); } DC::CoordVar cvar; bool status = _dc->GetCoordVarInfo(_nativeTimeVar, cvar); if (!status) { SetErrMsg("Invalid coordinate variable %s", _nativeTimeVar.c_str()); return (-1); } if (!udunits.IsTimeUnit(cvar.GetUnits())) { SetErrMsg("Invalid coordinate variable %s", _nativeTimeVar.c_str()); return (-1); } size_t numTS = _dc->GetNumTimeSteps(_nativeTimeVar); // Need a single precision and double precision buffer. Single for GetVar, // double for udunits.Convert :-( // float * buf = new float[numTS]; double *dbuf = new double[2 * numTS]; double *dbufptr1 = dbuf; double *dbufptr2 = dbuf + numTS; rc = _dc->GetVar(_nativeTimeVar, -1, -1, buf); if (rc < 0) { SetErrMsg("Can't read time variable"); return (-1); } for (int i = 0; i < numTS; i++) { dbufptr1[i] = (double)buf[i]; } status = udunits.Convert(cvar.GetUnits(), "seconds", dbufptr1, dbufptr2, numTS); if (!status) { SetErrMsg("Invalid coordinate variable %s", _nativeTimeVar.c_str()); return (-1); } _times.clear(); for (int i = 0; i < numTS; i++) { _times.push_back(dbufptr2[i]); } delete[] buf; delete[] dbuf; return (0); } bool DerivedCoordVar_TimeInSeconds::GetBaseVarInfo(DC::BaseVar &var) const { var = _coordVarInfo; return (true); } bool DerivedCoordVar_TimeInSeconds::GetCoordVarInfo(DC::CoordVar &cvar) const { cvar = _coordVarInfo; return (true); } int DerivedCoordVar_TimeInSeconds::GetDimLensAtLevel(int level, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level) const { dims_at_level.clear(); bs_at_level.clear(); return (0); } int DerivedCoordVar_TimeInSeconds::OpenVariableRead(size_t ts, int level, int lod) { ts = ts < _times.size() ? ts : _times.size() - 1; DC::FileTable::FileObject *f = new DC::FileTable::FileObject(ts, _derivedVarName, level, lod); return (_fileTable.AddEntry(f)); } int DerivedCoordVar_TimeInSeconds::CloseVariable(int fd) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } _fileTable.RemoveEntry(fd); delete f; return (0); } int DerivedCoordVar_TimeInSeconds::ReadRegion(int fd, const vector<size_t> &min, const vector<size_t> &max, float *region) { VAssert(min.size() == 0); VAssert(max.size() == 0); DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor: %d", fd); return (-1); } size_t ts = f->GetTS(); *region = _times[ts]; return (0); } bool DerivedCoordVar_TimeInSeconds::VariableExists(size_t ts, int reflevel, int lod) const { return (ts < _times.size()); } ////////////////////////////////////////////////////////////////////////////// // // DerivedCoordVar_Time // ////////////////////////////////////////////////////////////////////////////// DerivedCoordVar_Time::DerivedCoordVar_Time(string derivedVarName, string dimName, size_t n) : DerivedCoordVar(derivedVarName) { _times.clear(); for (size_t i = 0; i < n; i++) _times.push_back((float)i); string units = "seconds"; int axis = 3; _coordVarInfo = DC::CoordVar(_derivedVarName, units, DC::XType::FLOAT, vector<bool>(), axis, false, vector<string>(), dimName); } int DerivedCoordVar_Time::Initialize() { return (0); } bool DerivedCoordVar_Time::GetBaseVarInfo(DC::BaseVar &var) const { var = _coordVarInfo; return (true); } bool DerivedCoordVar_Time::GetCoordVarInfo(DC::CoordVar &cvar) const { cvar = _coordVarInfo; return (true); } int DerivedCoordVar_Time::GetDimLensAtLevel(int level, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level) const { dims_at_level.clear(); bs_at_level.clear(); return (0); } int DerivedCoordVar_Time::OpenVariableRead(size_t ts, int level, int lod) { ts = ts < _times.size() ? ts : _times.size() - 1; DC::FileTable::FileObject *f = new DC::FileTable::FileObject(ts, _derivedVarName, level, lod); return (_fileTable.AddEntry(f)); } int DerivedCoordVar_Time::CloseVariable(int fd) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } _fileTable.RemoveEntry(fd); delete f; return (0); } int DerivedCoordVar_Time::ReadRegion(int fd, const vector<size_t> &min, const vector<size_t> &max, float *region) { VAssert(min.size() == 0); VAssert(max.size() == 0); DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor: %d", fd); return (-1); } size_t ts = f->GetTS(); *region = _times[ts]; return (0); } bool DerivedCoordVar_Time::VariableExists(size_t ts, int reflevel, int lod) const { return (ts < _times.size()); } ////////////////////////////////////////////////////////////////////////////// // // DerivedCoordVar_Staggered // ////////////////////////////////////////////////////////////////////////////// DerivedCoordVar_Staggered::DerivedCoordVar_Staggered(string derivedVarName, string stagDimName, DC *dc, string inName, string dimName) : DerivedCoordVar(derivedVarName) { _stagDimName = stagDimName; _inName = inName; _dimName = dimName; _dc = dc; } int DerivedCoordVar_Staggered::Initialize() { bool ok = _dc->GetCoordVarInfo(_inName, _coordVarInfo); if (!ok) return (-1); vector<string> dimNames = _coordVarInfo.GetDimNames(); _stagDim = -1; for (int i = 0; i < dimNames.size(); i++) { if (dimNames[i] == _dimName) { _stagDim = i; dimNames[i] = _stagDimName; break; } } if (_stagDim < 0) { SetErrMsg("Dimension %s not found", _dimName.c_str()); return (-1); } // Change the name of the staggered dimension // _coordVarInfo.SetDimNames(dimNames); return (0); } bool DerivedCoordVar_Staggered::GetBaseVarInfo(DC::BaseVar &var) const { var = _coordVarInfo; return (true); } bool DerivedCoordVar_Staggered::GetCoordVarInfo(DC::CoordVar &cvar) const { cvar = _coordVarInfo; return (true); } int DerivedCoordVar_Staggered::GetDimLensAtLevel(int level, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level) const { dims_at_level.clear(); bs_at_level.clear(); vector<size_t> dummy; int rc = _dc->GetDimLensAtLevel(_inName, level, dims_at_level, dummy, -1); if (rc < 0) return (-1); dims_at_level[_stagDim] += 1; bs_at_level = vector<size_t>(dims_at_level.size(), 1); return (0); } int DerivedCoordVar_Staggered::OpenVariableRead(size_t ts, int level, int lod) { int fd = _dc->OpenVariableRead(ts, _inName, level, lod); if (fd < 0) return (fd); DC::FileTable::FileObject *f = new DC::FileTable::FileObject(ts, _derivedVarName, level, lod, fd); return (_fileTable.AddEntry(f)); } int DerivedCoordVar_Staggered::CloseVariable(int fd) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } int rc = _dc->CloseVariable(f->GetAux()); _fileTable.RemoveEntry(fd); delete f; return (rc); } int DerivedCoordVar_Staggered::ReadRegion(int fd, const vector<size_t> &min, const vector<size_t> &max, float *region) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } vector<size_t> dims, dummy; int rc = GetDimLensAtLevel(f->GetLevel(), dims, dummy); if (rc < 0) return (-1); vector<size_t> inMin = min; vector<size_t> inMax = max; // adjust coords for native data so that we have what we // need for interpolation or extrapolation. // // Adjust min max boundaries to handle 4 case (below) where X's // are samples on the destination grid (staggered) and O's are samples // on the source grid (unstaggered) and the numbers represent // the address of the samples in their respective arrays // // X O X O X O X // 0 0 1 1 2 2 3 // // O X O X O X // 0 1 1 2 2 3 // // X O X O X O // 0 0 1 1 2 2 // // O X O X O // 0 1 1 2 2 // Adjust input min so we can interpolate interior. // if (min[_stagDim] > 0) { inMin[_stagDim] -= 1; } // input dimensions are one less then output // if (max[_stagDim] >= (dims[_stagDim] - 1)) { inMax[_stagDim] -= 1; } // Adjust min and max for edge cases // if (max[_stagDim] == 0 && (dims[_stagDim] - 1) > 1) { inMax[_stagDim] += 1; } if (min[_stagDim] == dims[_stagDim] - 1 && min[_stagDim] > 0) { inMin[_stagDim] -= 1; } vector<size_t> inDims, outDims; for (size_t i = 0; i < min.size(); i++) { inDims.push_back(inMax[i] - inMin[i] + 1); outDims.push_back(max[i] - min[i] + 1); } size_t sz = std::max(vproduct(outDims), vproduct(inDims)); float *buf = new float[sz]; // Read unstaggered data // rc = _dc->ReadRegion(f->GetAux(), inMin, inMax, buf); if (rc < 0) return (-1); resampleToStaggered(buf, inMin, inMax, region, min, max, _stagDim); delete[] buf; return (0); } bool DerivedCoordVar_Staggered::VariableExists(size_t ts, int reflevel, int lod) const { return (_dc->VariableExists(ts, _inName, reflevel, lod)); } ////////////////////////////////////////////////////////////////////////////// // // DerivedCoordVar_UnStaggered // ////////////////////////////////////////////////////////////////////////////// DerivedCoordVar_UnStaggered::DerivedCoordVar_UnStaggered(string derivedVarName, string unstagDimName, DC *dc, string inName, string dimName) : DerivedCoordVar(derivedVarName) { _unstagDimName = unstagDimName; _inName = inName; _dimName = dimName; _dc = dc; } int DerivedCoordVar_UnStaggered::Initialize() { bool ok = _dc->GetCoordVarInfo(_inName, _coordVarInfo); if (!ok) return (-1); vector<string> dimNames = _coordVarInfo.GetDimNames(); _stagDim = -1; for (int i = 0; i < dimNames.size(); i++) { if (dimNames[i] == _dimName) { _stagDim = i; dimNames[i] = _unstagDimName; break; } } if (_stagDim < 0) { SetErrMsg("Dimension %s not found", _dimName.c_str()); return (-1); } // Change the name of the staggered dimension // _coordVarInfo.SetDimNames(dimNames); return (0); } bool DerivedCoordVar_UnStaggered::GetBaseVarInfo(DC::BaseVar &var) const { var = _coordVarInfo; return (true); } bool DerivedCoordVar_UnStaggered::GetCoordVarInfo(DC::CoordVar &cvar) const { cvar = _coordVarInfo; return (true); } int DerivedCoordVar_UnStaggered::GetDimLensAtLevel(int level, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level) const { dims_at_level.clear(); bs_at_level.clear(); int rc = _dc->GetDimLensAtLevel(_inName, level, dims_at_level, bs_at_level, -1); if (rc < 0) return (-1); dims_at_level[_stagDim] -= 1; bs_at_level = vector<size_t>(dims_at_level.size(), 1); return (0); } int DerivedCoordVar_UnStaggered::OpenVariableRead(size_t ts, int level, int lod) { int fd = _dc->OpenVariableRead(ts, _inName, level, lod); if (fd < 0) return (fd); DC::FileTable::FileObject *f = new DC::FileTable::FileObject(ts, _derivedVarName, level, lod, fd); return (_fileTable.AddEntry(f)); } int DerivedCoordVar_UnStaggered::CloseVariable(int fd) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } int rc = _dc->CloseVariable(f->GetAux()); _fileTable.RemoveEntry(fd); delete f; return (rc); } int DerivedCoordVar_UnStaggered::ReadRegion(int fd, const vector<size_t> &min, const vector<size_t> &max, float *region) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } vector<size_t> dims, dummy; int rc = GetDimLensAtLevel(f->GetLevel(), dims, dummy); if (rc < 0) return (-1); vector<size_t> inMin = min; vector<size_t> inMax = max; // adjust coords for native data so that we have what we // need for interpolation . // inMax[_stagDim] += 1; vector<size_t> inDims, outDims; for (size_t i = 0; i < min.size(); i++) { inDims.push_back(inMax[i] - inMin[i] + 1); outDims.push_back(max[i] - min[i] + 1); } size_t sz = std::max(vproduct(outDims), vproduct(inDims)); float *buf = new float[sz]; // Read staggered data // rc = _dc->ReadRegion(f->GetAux(), inMin, inMax, buf); if (rc < 0) return (-1); resampleToUnStaggered(buf, inMin, inMax, region, min, max, _stagDim); delete[] buf; return (0); } bool DerivedCoordVar_UnStaggered::VariableExists(size_t ts, int reflevel, int lod) const { return (_dc->VariableExists(ts, _inName, reflevel, lod)); } ////////////////////////////////////////////////////////////////////////////// // // DerivedCFVertCoordVar // ////////////////////////////////////////////////////////////////////////////// bool DerivedCFVertCoordVar::ParseFormula(string formula_terms, map<string, string> &parsed_terms) { parsed_terms.clear(); // Remove ":" to ease parsing. It's superflous // replace(formula_terms.begin(), formula_terms.end(), ':', ' '); string buf; // Have a buffer string stringstream ss(formula_terms); // Insert the string into a stream vector<string> tokens; // Create vector to hold our words while (ss >> buf) { tokens.push_back(buf); } if (tokens.size() % 2) return (false); for (int i = 0; i < tokens.size(); i += 2) { parsed_terms[tokens[i]] = tokens[i + 1]; if (parsed_terms[tokens[i]].empty()) return (false); } return (true); } bool DerivedCFVertCoordVar::ValidFormula(const vector<string> &required_terms, string formula) { map<string, string> formulaMap; if (!ParseFormula(formula, formulaMap)) { return (false); } for (int i = 0; i < required_terms.size(); i++) { map<string, string>::const_iterator itr; itr = formulaMap.find(required_terms[i]); if (itr == formulaMap.end()) return (false); } return (true); } ////////////////////////////////////////////////////////////////////////// // // DerivedCFVertCoordVarFactory Class // ///////////////////////////////////////////////////////////////////////// DerivedCFVertCoordVar *DerivedCFVertCoordVarFactory::CreateInstance(string standard_name, DC *dc, string mesh, string formula) { DerivedCFVertCoordVar *instance = NULL; // find standard_name in the registry and call factory method. // auto it = _factoryFunctionRegistry.find(standard_name); if (it != _factoryFunctionRegistry.end()) { instance = it->second(dc, mesh, formula); } return instance; } vector<string> DerivedCFVertCoordVarFactory::GetFactoryNames() const { vector<string> names; map<string, function<DerivedCFVertCoordVar *(DC *, string, string)>>::const_iterator itr; for (const auto &itr : _factoryFunctionRegistry) { names.push_back(itr.first); } return (names); } ////////////////////////////////////////////////////////////////////////////// // // DerivedCoordVarStandardWRF_Terrain // ////////////////////////////////////////////////////////////////////////////// static DerivedCFVertCoordVarFactoryRegistrar<DerivedCoordVarStandardWRF_Terrain> registrar_wrf_terrain("wrf_terrain"); DerivedCoordVarStandardWRF_Terrain::DerivedCoordVarStandardWRF_Terrain(DC *dc, string mesh, string formula) : DerivedCFVertCoordVar("", dc, mesh, formula) { _PHVar.clear(); _PHBVar.clear(); _grav = 9.80665; } int DerivedCoordVarStandardWRF_Terrain::Initialize() { map<string, string> formulaMap; if (!ParseFormula(_formula, formulaMap)) { SetErrMsg("Invalid conversion formula \"%s\"", _formula.c_str()); return (-1); } map<string, string>::const_iterator itr; itr = formulaMap.find("PH"); if (itr != formulaMap.end()) { _PHVar = itr->second; } itr = formulaMap.find("PHB"); if (itr != formulaMap.end()) { _PHBVar = itr->second; } if (_PHVar.empty() || _PHBVar.empty()) { SetErrMsg("Invalid conversion formula \"%s\"", _formula.c_str()); return (-1); } DC::DataVar dvarInfo; bool status = _dc->GetDataVarInfo(_PHVar, dvarInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", _PHVar.c_str()); return (-1); } string timeCoordVar = dvarInfo.GetTimeCoordVar(); string timeDimName; if (!timeCoordVar.empty()) { DC::CoordVar cvarInfo; bool status = _dc->GetCoordVarInfo(timeCoordVar, cvarInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", timeCoordVar.c_str()); return (-1); } timeDimName = cvarInfo.GetTimeDimName(); } DC::Mesh m; status = _dc->GetMesh(_mesh, m); if (!status) { SetErrMsg("Invalid mesh \"%s\"", _mesh.c_str()); return (-1); } // Elevation variable // vector<string> dimnames = m.GetDimNames(); VAssert(dimnames.size() == 3); if (dimnames[0] == "west_east" && dimnames[1] == "south_north" && dimnames[2] == "bottom_top") { _derivedVarName = "Elevation"; } else if (dimnames[0] == "west_east_stag" && dimnames[1] == "south_north" && dimnames[2] == "bottom_top") { _derivedVarName = "ElevationU"; } else if (dimnames[0] == "west_east" && dimnames[1] == "south_north_stag" && dimnames[2] == "bottom_top") { _derivedVarName = "ElevationV"; } else if (dimnames[0] == "west_east" && dimnames[1] == "south_north" && dimnames[2] == "bottom_top_stag") { _derivedVarName = "ElevationW"; } else { SetErrMsg("Invalid mesh \"%s\"", _mesh.c_str()); return (-1); } _coordVarInfo = DC::CoordVar(_derivedVarName, "m", DC::XType::FLOAT, dvarInfo.GetWName(), dvarInfo.GetCRatios(), vector<bool>(3, false), dimnames, timeDimName, 2, false); return (0); } bool DerivedCoordVarStandardWRF_Terrain::GetBaseVarInfo(DC::BaseVar &var) const { var = _coordVarInfo; return (true); } bool DerivedCoordVarStandardWRF_Terrain::GetCoordVarInfo(DC::CoordVar &cvar) const { cvar = _coordVarInfo; return (true); } int DerivedCoordVarStandardWRF_Terrain::GetDimLensAtLevel(int level, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level) const { dims_at_level.clear(); bs_at_level.clear(); vector<size_t> dims, bs; int rc = _dc->GetDimLensAtLevel(_PHVar, -1, dims, bs, -1); if (rc < 0) return (-1); if (_derivedVarName == "Elevation") { if (dims[2] > 1) dims[2]--; } else if (_derivedVarName == "ElevationU") { dims[0]++; if (dims[2] > 1) dims[2]--; } else if (_derivedVarName == "ElevationV") { dims[1]++; if (dims[2] > 1) dims[2]--; } else if (_derivedVarName == "ElevationW") { } else { SetErrMsg("Invalid variable name: %s", _derivedVarName.c_str()); return (-1); } int nlevels = _dc->GetNumRefLevels(_PHVar); if (level < 0) level = nlevels + level; WASP::InqDimsAtLevel(_coordVarInfo.GetWName(), level, dims, bs, dims_at_level, bs_at_level); // No blocking // // bs_at_level = vector <size_t> (dims_at_level.size(), 1); return (0); } int DerivedCoordVarStandardWRF_Terrain::OpenVariableRead(size_t ts, int level, int lod) { DC::FileTable::FileObject *f = new DC::FileTable::FileObject(ts, _derivedVarName, level, lod); return (_fileTable.AddEntry(f)); } int DerivedCoordVarStandardWRF_Terrain::CloseVariable(int fd) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } _fileTable.RemoveEntry(fd); delete f; return (0); } int DerivedCoordVarStandardWRF_Terrain::ReadRegion(int fd, const vector<size_t> &min, const vector<size_t> &max, float *region) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); string varname = f->GetVarname(); // Dimensions of "W" grid: PH and PHB variables are sampled on the // same grid as the W component of velocity // vector<size_t> wDims, dummy; int rc = _dc->GetDimLensAtLevel(_PHVar, f->GetLevel(), wDims, dummy, -1); if (rc < 0) return (-1); vector<size_t> myDims; rc = DerivedCoordVarStandardWRF_Terrain::GetDimLensAtLevel(f->GetLevel(), myDims, dummy); if (rc < 0) return (-1); // coordinates of "W" grid. // vector<size_t> wMin = min; vector<size_t> wMax = max; // coordinates of base (Elevation) grid. // if (varname == "Elevation") { // In general myDims[2] != wDims[2]. However, for multiresolution // data the two can be equal // if (myDims[2] != wDims[2]) { wMax[2] += 1; } } else if (varname == "ElevationU") { if (myDims[2] != wDims[2]) { wMax[2] += 1; } if (min[0] > 0) { wMin[0] -= 1; } if (max[0] >= (wDims[0] - 1)) { wMax[0] -= 1; } } else if (varname == "ElevationV") { if (myDims[2] != wDims[2]) { wMax[2] += 1; } if (min[1] > 0) { wMin[1] -= 1; } if (max[1] >= (wDims[1] - 1)) { wMax[1] -= 1; } } // Base grid dimensions // vector<size_t> bMin = wMin; vector<size_t> bMax = wMax; if (myDims[2] != wDims[2]) { bMax[2] -= 1; } size_t nElements = std::max(numElements(wMin, wMax), numElements(min, max)); vector<float> buf1(nElements); rc = _getVar(_dc, f->GetTS(), _PHVar, f->GetLevel(), f->GetLOD(), wMin, wMax, buf1.data()); if (rc < 0) { return (rc); } vector<float> buf2(nElements); rc = _getVar(_dc, f->GetTS(), _PHBVar, f->GetLevel(), f->GetLOD(), wMin, wMax, buf2.data()); if (rc < 0) { return (rc); } float *dst = region; if (varname != "ElevationW" && wDims[2] > 1) { dst = buf1.data(); } // Compute elevation on the W grid // for (size_t i = 0; i < nElements; i++) { dst[i] = (buf1.data()[i] + buf2.data()[i]) / _grav; } if (wDims[2] < 2) return (0); // Elevation is correct for W grid. If we want Elevation, ElevationU, or // Elevation V grid we need to interpolate // if (varname == "Elevation") { // Resample stagged W grid to base grid // resampleToUnStaggered(buf1.data(), wMin, wMax, region, min, max, 2); } else if (varname == "ElevationU") { // Resample stagged W grid to base grid // resampleToUnStaggered(buf1.data(), wMin, wMax, buf2.data(), bMin, bMax, 2); resampleToStaggered(buf2.data(), bMin, bMax, region, min, max, 0); } else if (varname == "ElevationV") { // Resample stagged W grid to base grid // resampleToUnStaggered(buf1.data(), wMin, wMax, buf2.data(), bMin, bMax, 2); resampleToStaggered(buf2.data(), bMin, bMax, region, min, max, 1); } return (0); } bool DerivedCoordVarStandardWRF_Terrain::VariableExists(size_t ts, int reflevel, int lod) const { return (_dc->VariableExists(ts, _PHVar, reflevel, lod) && _dc->VariableExists(ts, _PHBVar, reflevel, lod)); } bool DerivedCoordVarStandardWRF_Terrain::ValidFormula(string formula) { return (DerivedCFVertCoordVar::ValidFormula(vector<string>{"PH", "PHB"}, formula)); } ////////////////////////////////////////////////////////////////////////////// // // DerivedCoordVarStandardOceanSCoordinate // ////////////////////////////////////////////////////////////////////////////// // // Register class with object factory!!! // static DerivedCFVertCoordVarFactoryRegistrar<DerivedCoordVarStandardOceanSCoordinate> registrar_ocean_s_coordinate_g1("ocean_s_coordinate_g1"); static DerivedCFVertCoordVarFactoryRegistrar<DerivedCoordVarStandardOceanSCoordinate> registrar_ocean_s_coordinate_g2("ocean_s_coordinate_g2"); DerivedCoordVarStandardOceanSCoordinate::DerivedCoordVarStandardOceanSCoordinate(DC *dc, string mesh, string formula) : DerivedCFVertCoordVar("", dc, mesh, formula) { _standard_name = "ocean_s_coordinate_g1"; _sVar.clear(); _CVar.clear(); _etaVar.clear(); _depthVar.clear(); _depth_cVar.clear(); _CVarMV = std::numeric_limits<double>::infinity(); _etaVarMV = std::numeric_limits<double>::infinity(); _depthVarMV = std::numeric_limits<double>::infinity(); _destaggerEtaXDim = false; _destaggerEtaYDim = false; _destaggerDepthXDim = false; _destaggerDepthYDim = false; } int DerivedCoordVarStandardOceanSCoordinate::initialize_missing_values() { DC::DataVar dataInfo; bool status = _dc->GetDataVarInfo(_CVar, dataInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", _CVar.c_str()); return (-1); } if (dataInfo.GetHasMissing()) _CVarMV = dataInfo.GetMissingValue(); status = _dc->GetDataVarInfo(_etaVar, dataInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", _etaVar.c_str()); return (-1); } if (dataInfo.GetHasMissing()) _etaVarMV = dataInfo.GetMissingValue(); status = _dc->GetDataVarInfo(_depthVar, dataInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", _depthVar.c_str()); return (-1); } if (dataInfo.GetHasMissing()) _depthVarMV = dataInfo.GetMissingValue(); return (0); } int DerivedCoordVarStandardOceanSCoordinate::initialize_stagger_flags() { vector<size_t> derivedDims; bool status = _dc->GetMeshDimLens(_mesh, derivedDims); if (!status) { SetErrMsg("Invalid mesh \"%s\"", _mesh.c_str()); return (-1); } vector<size_t> nativeDims; int rc = _dc->GetDimLens(_etaVar, nativeDims); if (rc < 0) return (-1); if (nativeDims[0] == derivedDims[0] - 1) _destaggerEtaXDim = true; if (nativeDims[1] == derivedDims[1] - 1) _destaggerEtaYDim = true; rc = _dc->GetDimLens(_depthVar, nativeDims); if (rc < 0) return (-1); if (nativeDims[0] == derivedDims[0] - 1) _destaggerDepthXDim = true; if (nativeDims[1] == derivedDims[1] - 1) _destaggerDepthYDim = true; return (0); } int DerivedCoordVarStandardOceanSCoordinate::Initialize() { map<string, string> formulaMap; if (!ParseFormula(_formula, formulaMap)) { SetErrMsg("Invalid conversion formula \"%s\"", _formula.c_str()); return (-1); } map<string, string>::const_iterator itr; VAssert((itr = formulaMap.find("s")) != formulaMap.end()); _sVar = itr->second; VAssert((itr = formulaMap.find("C")) != formulaMap.end()); _CVar = itr->second; VAssert((itr = formulaMap.find("eta")) != formulaMap.end()); _etaVar = itr->second; VAssert((itr = formulaMap.find("depth")) != formulaMap.end()); _depthVar = itr->second; VAssert((itr = formulaMap.find("depth_c")) != formulaMap.end()); _depth_cVar = itr->second; if (initialize_missing_values() < 0) return (-1); if (initialize_stagger_flags() < 0) return (-1); // Figure out if this is a Ocean s-coordinate, generic form 1, or // Ocean s-coordinate, generic form 2 // DC::CoordVar sInfo; bool status = _dc->GetCoordVarInfo(_sVar, sInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", _sVar.c_str()); return (-1); } DC::Attribute attr_name; if (!sInfo.GetAttribute("standard_name", attr_name)) { // Default to generic form 1 // _standard_name = "ocean_s_coordinate_g1"; } else { attr_name.GetValues(_standard_name); } // Use the eta variable to set up metadata for the derived variable // DC::DataVar etaInfo; status = _dc->GetDataVarInfo(_etaVar, etaInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", _etaVar.c_str()); return (-1); } string timeCoordVar = etaInfo.GetTimeCoordVar(); string timeDimName; if (!timeCoordVar.empty()) { DC::CoordVar cvarInfo; bool status = _dc->GetCoordVarInfo(timeCoordVar, cvarInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", timeCoordVar.c_str()); return (-1); } timeDimName = cvarInfo.GetTimeDimName(); } _derivedVarName = "Z_" + _sVar; vector<string> dimnames; status = _dc->GetMeshDimNames(_mesh, dimnames); if (!status) { SetErrMsg("Invalid mesh \"%s\"", _mesh.c_str()); return (-1); } VAssert(dimnames.size() == 3); // We're deriving a 3D varible from 1D and 2D varibles. We arbitarily // use one of the 2D variables to configure metadata such as the // available compression ratios // _coordVarInfo = DC::CoordVar(_derivedVarName, "m", DC::XType::FLOAT, vector<bool>(3, false), 2, false, dimnames, timeDimName); return (0); } bool DerivedCoordVarStandardOceanSCoordinate::GetBaseVarInfo(DC::BaseVar &var) const { var = _coordVarInfo; return (true); } bool DerivedCoordVarStandardOceanSCoordinate::GetCoordVarInfo(DC::CoordVar &cvar) const { cvar = _coordVarInfo; return (true); } vector<string> DerivedCoordVarStandardOceanSCoordinate::GetInputs() const { map<string, string> formulaMap; bool ok = ParseFormula(_formula, formulaMap); VAssert(ok); vector<string> inputs; for (auto it = formulaMap.begin(); it != formulaMap.end(); ++it) { inputs.push_back(it->second); } return (inputs); } int DerivedCoordVarStandardOceanSCoordinate::GetDimLensAtLevel(int level, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level) const { dims_at_level.clear(); bs_at_level.clear(); vector<size_t> dims2d, bs2d; int rc = _dc->GetDimLensAtLevel(_etaVar, -1, dims2d, bs2d); if (rc < 0) return (-1); vector<size_t> dims1d, bs1d; rc = _dc->GetDimLensAtLevel(_sVar, -1, dims1d, bs1d); if (rc < 0) return (-1); dims_at_level = {dims2d[0], dims2d[1], dims1d[0]}; bs_at_level = {bs2d[0], bs2d[1], bs1d[0]}; return (0); } int DerivedCoordVarStandardOceanSCoordinate::OpenVariableRead(size_t ts, int level, int lod) { // Compression not supported // level = -1; lod = -1; DC::FileTable::FileObject *f = new DC::FileTable::FileObject(ts, _derivedVarName, level, lod); return (_fileTable.AddEntry(f)); } int DerivedCoordVarStandardOceanSCoordinate::CloseVariable(int fd) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } _fileTable.RemoveEntry(fd); delete f; return (0); } int DerivedCoordVarStandardOceanSCoordinate::ReadRegion(int fd, const vector<size_t> &min, const vector<size_t> &max, float *region) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); string varname = f->GetVarname(); vector<size_t> dims, dummy; int rc = GetDimLensAtLevel(f->GetLevel(), dims, dummy); if (rc < 0) return (-1); vector<float> s(dims[2]); vector<size_t> myMin = {min[2]}; vector<size_t> myMax = {max[2]}; rc = _getVar(_dc, f->GetTS(), _sVar, f->GetLevel(), f->GetLOD(), myMin, myMax, s.data()); if (rc < 0) return (rc); vector<float> C(dims[2]); myMin = {min[2]}; myMax = {max[2]}; rc = _getVar(_dc, f->GetTS(), _CVar, f->GetLevel(), f->GetLOD(), myMin, myMax, C.data()); if (rc < 0) return (rc); vector<float> eta(dims[0] * dims[1]); myMin = {min[0], min[1]}; myMax = {max[0], max[1]}; if (_destaggerEtaXDim) { rc = _getVarDestagger(_dc, f->GetTS(), _etaVar, f->GetLevel(), f->GetLOD(), myMin, myMax, eta.data(), 0); } else if (_destaggerEtaYDim) { rc = _getVarDestagger(_dc, f->GetTS(), _etaVar, f->GetLevel(), f->GetLOD(), myMin, myMax, eta.data(), 1); } else { rc = _getVar(_dc, f->GetTS(), _etaVar, f->GetLevel(), f->GetLOD(), myMin, myMax, eta.data()); } if (rc < 0) return (rc); vector<float> depth(dims[0] * dims[1]); myMin = {min[0], min[1]}; myMax = {max[0], max[1]}; if (_destaggerDepthXDim) { rc = _getVarDestagger(_dc, f->GetTS(), _depthVar, f->GetLevel(), f->GetLOD(), myMin, myMax, depth.data(), 0); } else if (_destaggerDepthYDim) { rc = _getVarDestagger(_dc, f->GetTS(), _depthVar, f->GetLevel(), f->GetLOD(), myMin, myMax, depth.data(), 1); } else { rc = _getVar(_dc, f->GetTS(), _depthVar, f->GetLevel(), f->GetLOD(), myMin, myMax, depth.data()); } float depth_c; myMin = {}; myMax = {}; rc = _getVar(_dc, f->GetTS(), _depth_cVar, f->GetLevel(), f->GetLOD(), myMin, myMax, &depth_c); if (_standard_name == "ocean_s_coordinate_g1") { compute_g1(min, max, s.data(), C.data(), eta.data(), depth.data(), depth_c, region); } else { compute_g2(min, max, s.data(), C.data(), eta.data(), depth.data(), depth_c, region); } return (0); } bool DerivedCoordVarStandardOceanSCoordinate::VariableExists(size_t ts, int reflevel, int lod) const { return (_dc->VariableExists(ts, _sVar, reflevel, lod) && _dc->VariableExists(ts, _CVar, reflevel, lod) && _dc->VariableExists(ts, _etaVar, reflevel, lod) && _dc->VariableExists(ts, _depthVar, reflevel, lod) && _dc->VariableExists(ts, _depth_cVar, reflevel, lod)); } bool DerivedCoordVarStandardOceanSCoordinate::ValidFormula(string formula) { return (DerivedCFVertCoordVar::ValidFormula(vector<string>{"s", "C", "eta", "depth", "depth_c"}, formula)); } void DerivedCoordVarStandardOceanSCoordinate::compute_g1(const vector<size_t> &min, const vector<size_t> &max, const float *s, const float *C, const float *eta, const float *depth, float depth_c, float *region) const { vector<size_t> rDims; for (int i = 0; i < 3; i++) { rDims.push_back(max[i] - min[i] + 1); } for (size_t k = 0; k < max[2] - min[2] + 1; k++) { for (size_t j = 0; j < max[1] - min[1] + 1; j++) { for (size_t i = 0; i < max[0] - min[0] + 1; i++) { if (depth[j * rDims[0]] == 0.0) { region[k * rDims[0] * rDims[1] + j * rDims[0] + i] = 0.0; continue; } // We are deriving coordinate values from data values, so missing // values may be present // if (C[k] == _CVarMV || eta[j * rDims[0] + i] == _etaVarMV || depth[j * rDims[0] + i] == _depthVarMV) { region[k * rDims[0] * rDims[1] + j * rDims[0] + i] = 0.0; continue; } float tmp = depth_c * s[k] + (depth[j * rDims[0] + i] - depth_c) * C[k]; region[k * rDims[0] * rDims[1] + j * rDims[0] + i] = tmp + eta[j * rDims[0] + i] * (1 + tmp / depth[j * rDims[0] + i]); } } } } void DerivedCoordVarStandardOceanSCoordinate::compute_g2(const vector<size_t> &min, const vector<size_t> &max, const float *s, const float *C, const float *eta, const float *depth, float depth_c, float *region) const { vector<size_t> rDims; for (int i = 0; i < 3; i++) { rDims.push_back(max[i] - min[i] + 1); } for (size_t k = 0; k < max[2] - min[2] + 1; k++) { for (size_t j = 0; j < max[1] - min[1] + 1; j++) { for (size_t i = 0; i < max[0] - min[0] + 1; i++) { if ((depth_c + depth[j * rDims[0]]) == 0.0) { region[k * rDims[0] * rDims[1] + j * rDims[0] + i] = 0.0; continue; } // We are deriving coordinate values from data values, so missing // values may be present // if (C[k] == _CVarMV || eta[j * rDims[0] + i] == _etaVarMV || depth[j * rDims[0] + i] == _depthVarMV) { region[k * rDims[0] * rDims[1] + j * rDims[0] + i] = 0.0; continue; } float tmp = (depth_c * s[k] + depth[j * rDims[0] + i] * C[k]) / (depth_c + depth[j * rDims[0] + i]); region[k * rDims[0] * rDims[1] + j * rDims[0] + i] = eta[j * rDims[0] + i] + (eta[j * rDims[0] + i] + depth[j * rDims[0] + i]) * tmp; } } } } ////////////////////////////////////////////////////////////////////////////// // // DerivedCoordVarStandardAHSPC // // Atmosphere Hybrid Sigma Pressure Coordinate // ////////////////////////////////////////////////////////////////////////////// // // Register class with object factory!!! // static DerivedCFVertCoordVarFactoryRegistrar<DerivedCoordVarStandardAHSPC> registrar_atmosphere_hybrid_sigma_pressure_coordinate("atmosphere_hybrid_sigma_pressure_coordinate"); DerivedCoordVarStandardAHSPC::DerivedCoordVarStandardAHSPC(DC *dc, string mesh, string formula) : DerivedCFVertCoordVar("", dc, mesh, formula) { _standard_name = "atmosphere_hybrid_sigma_pressure_coordinate"; _aVar.clear(); _apVar.clear(); _bVar.clear(); _p0Var.clear(); _psVar.clear(); _psVarMV = std::numeric_limits<double>::infinity(); } int DerivedCoordVarStandardAHSPC::initialize_missing_values() { DC::DataVar dataInfo; bool status = _dc->GetDataVarInfo(_psVar, dataInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", _psVar.c_str()); return (-1); } if (dataInfo.GetHasMissing()) _psVarMV = dataInfo.GetMissingValue(); return (0); } int DerivedCoordVarStandardAHSPC::Initialize() { map<string, string> formulaMap; if (!ParseFormula(_formula, formulaMap)) { SetErrMsg("Invalid conversion formula \"%s\"", _formula.c_str()); return (-1); } // There are two possible formulations, one with 'ap', and one // with 'a' and 'p0' // map<string, string>::const_iterator itr; VAssert((itr = formulaMap.find("a")) != formulaMap.end()); if (itr != formulaMap.end()) { _aVar = itr->second; VAssert((itr = formulaMap.find("p0")) != formulaMap.end()); _p0Var = itr->second; } else { VAssert((itr = formulaMap.find("ap")) != formulaMap.end()); _apVar = itr->second; } VAssert((itr = formulaMap.find("b")) != formulaMap.end()); _bVar = itr->second; VAssert((itr = formulaMap.find("ps")) != formulaMap.end()); _psVar = itr->second; if (initialize_missing_values() < 0) return (-1); // Use the 'b' and 'ps' variables to set up metadata for the derived // variable // DC::DataVar bInfo; bool status = _dc->GetDataVarInfo(_bVar, bInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", _bVar.c_str()); return (-1); } DC::DataVar psInfo; status = _dc->GetDataVarInfo(_psVar, psInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", _psVar.c_str()); return (-1); } // Construct spatial and temporal dimensions from the 1D 'b' // variable and 2D, time-varying 'ps' variable // DC::Mesh m; status = _dc->GetMesh(psInfo.GetMeshName(), m); if (!status) { SetErrMsg("Invalid mesh \"%s\"", _mesh.c_str()); return (-1); } vector<string> dimnames = m.GetDimNames(); status = _dc->GetMesh(bInfo.GetMeshName(), m); if (!status) { SetErrMsg("Invalid mesh \"%s\"", _mesh.c_str()); return (-1); } dimnames.push_back(m.GetDimNames()[0]); string timeCoordVar = psInfo.GetTimeCoordVar(); string timeDimName; if (!timeCoordVar.empty()) { DC::CoordVar cvarInfo; bool status = _dc->GetCoordVarInfo(timeCoordVar, cvarInfo); if (!status) { SetErrMsg("Invalid variable \"%s\"", timeCoordVar.c_str()); return (-1); } timeDimName = cvarInfo.GetTimeDimName(); } // We're deriving a 3D varible from 1D and 2D varibles. We arbitarily // use one of the 2D variables to configure metadata such as the // available compression ratios // _derivedVarName = "Z_" + _bVar; _coordVarInfo = DC::CoordVar(_derivedVarName, "m", DC::XType::FLOAT, vector<bool>(3, false), 2, false, dimnames, timeDimName); return (0); } bool DerivedCoordVarStandardAHSPC::GetBaseVarInfo(DC::BaseVar &var) const { var = _coordVarInfo; return (true); } bool DerivedCoordVarStandardAHSPC::GetCoordVarInfo(DC::CoordVar &cvar) const { cvar = _coordVarInfo; return (true); } vector<string> DerivedCoordVarStandardAHSPC::GetInputs() const { map<string, string> formulaMap; bool ok = ParseFormula(_formula, formulaMap); VAssert(ok); vector<string> inputs; for (auto it = formulaMap.begin(); it != formulaMap.end(); ++it) { inputs.push_back(it->second); } return (inputs); } int DerivedCoordVarStandardAHSPC::GetDimLensAtLevel(int level, std::vector<size_t> &dims_at_level, std::vector<size_t> &bs_at_level) const { dims_at_level.clear(); bs_at_level.clear(); vector<size_t> dims2d, bs2d; int rc = _dc->GetDimLensAtLevel(_psVar, -1, dims2d, bs2d); if (rc < 0) return (-1); vector<size_t> dims1d, bs1d; rc = _dc->GetDimLensAtLevel(_bVar, -1, dims1d, bs1d); if (rc < 0) return (-1); dims_at_level = {dims2d[0], dims2d[1], dims1d[0]}; bs_at_level = {bs2d[0], bs2d[1], bs1d[0]}; return (0); } int DerivedCoordVarStandardAHSPC::OpenVariableRead(size_t ts, int level, int lod) { // We don't support compressed data // level = -1; lod = -1; DC::FileTable::FileObject *f = new DC::FileTable::FileObject(ts, _derivedVarName, level, lod); return (_fileTable.AddEntry(f)); } int DerivedCoordVarStandardAHSPC::CloseVariable(int fd) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); if (!f) { SetErrMsg("Invalid file descriptor : %d", fd); return (-1); } _fileTable.RemoveEntry(fd); delete f; return (0); } int DerivedCoordVarStandardAHSPC::ReadRegion(int fd, const vector<size_t> &min, const vector<size_t> &max, float *region) { DC::FileTable::FileObject *f = _fileTable.GetEntry(fd); vector<size_t> dims, dummy; int rc = GetDimLensAtLevel(f->GetLevel(), dims, dummy); if (rc < 0) return (-1); string aVar = _aVar.empty() ? _apVar : _aVar; vector<float> a(dims[2]); vector<size_t> myMin = {min[2]}; vector<size_t> myMax = {max[2]}; rc = _getVar(_dc, f->GetTS(), aVar, f->GetLevel(), f->GetLOD(), myMin, myMax, a.data()); if (rc < 0) return (rc); vector<float> b(dims[2]); myMin = {min[2]}; myMax = {max[2]}; rc = _getVar(_dc, f->GetTS(), _bVar, f->GetLevel(), f->GetLOD(), myMin, myMax, b.data()); if (rc < 0) return (rc); vector<float> ps(dims[0] * dims[1]); myMin = {min[0], min[1]}; myMax = {max[0], max[1]}; rc = _getVar(_dc, f->GetTS(), _psVar, f->GetLevel(), f->GetLOD(), myMin, myMax, ps.data()); if (rc < 0) return (rc); float p0 = 1.0; if (!_aVar.empty()) { myMin = {}; myMax = {}; rc = _getVar(_dc, f->GetTS(), _p0Var, f->GetLevel(), f->GetLOD(), myMin, myMax, &p0); } compute_a(min, max, a.data(), b.data(), ps.data(), p0, region); return (0); } bool DerivedCoordVarStandardAHSPC::VariableExists(size_t ts, int reflevel, int lod) const { if (!_aVar.empty()) { return (_dc->VariableExists(ts, _aVar, reflevel, lod) && _dc->VariableExists(ts, _bVar, reflevel, lod) && _dc->VariableExists(ts, _psVar, reflevel, lod)); } else { return (_dc->VariableExists(ts, _apVar, reflevel, lod) && _dc->VariableExists(ts, _bVar, reflevel, lod) && _dc->VariableExists(ts, _psVar, reflevel, lod) && _dc->VariableExists(ts, _p0Var, reflevel, lod)); } } bool DerivedCoordVarStandardAHSPC::ValidFormula(string formula) { return (DerivedCFVertCoordVar::ValidFormula(vector<string>{"a", "b", "p0", "ps"}, formula) || DerivedCFVertCoordVar::ValidFormula(vector<string>{"ap", "b", "ps"}, formula)); } void DerivedCoordVarStandardAHSPC::compute_a(const vector<size_t> &min, const vector<size_t> &max, const float *a, const float *b, const float *ps, float p0, float *region) const { vector<size_t> rDims; for (int i = 0; i < 3; i++) { rDims.push_back(max[i] - min[i] + 1); } for (size_t k = 0; k < max[2] - min[2] + 1; k++) { for (size_t j = 0; j < max[1] - min[1] + 1; j++) { for (size_t i = 0; i < max[0] - min[0] + 1; i++) { // We are deriving coordinate values from data values, so missing // values may be present // float l_ps = ps[j * rDims[0] + i]; if (l_ps == _psVarMV) l_ps = 0; float pressure = (a[k] * p0) + (b[k] * l_ps); // Convert from pressure to meters above the ground: // [1] "A Quick Derivation relating altitude to air pressure" from // Portland State Aerospace Society, Version 1.03, 12/22/2004. // region[k * rDims[0] * rDims[1] + j * rDims[0] + i] = 44331.5 - (4946.62 * std::pow(pressure, 0.190263)); } } } }
30.568054
199
0.584079
gaybro8777
f749e3d3d41dd78a9d9ab0ab2eab30651c9d0bee
4,522
cpp
C++
Core/JPetParamAndDataFactory/JPetParamAndDataFactory.cpp
Alvarness/j-pet-framework
899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd
[ "Apache-2.0" ]
null
null
null
Core/JPetParamAndDataFactory/JPetParamAndDataFactory.cpp
Alvarness/j-pet-framework
899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd
[ "Apache-2.0" ]
null
null
null
Core/JPetParamAndDataFactory/JPetParamAndDataFactory.cpp
Alvarness/j-pet-framework
899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd
[ "Apache-2.0" ]
null
null
null
/** * @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetParamAndDataFactory.cpp */ #include "./JPetParamAndDataFactory.h" namespace param_and_data_factory { JPetScin makeScin(int id, float attenLen, float length, float height, float width, JPetBarrelSlot& p_barrelSlot ) { JPetScin scinObject(id, attenLen, length, height, width); scinObject.setBarrelSlot(p_barrelSlot); return scinObject; } JPetFEB makeFEB(int p_id, bool p_isActive, const std::string& p_status, const std::string& p_description, int p_version, int p_userId, int p_n_time_outputs_per_input, int p_n_notime_outputs_per_input, JPetTRB& p_TRB) { JPetFEB objectFEB(p_id, p_isActive, p_status, p_description, p_version, p_userId, p_n_time_outputs_per_input, p_n_notime_outputs_per_input); objectFEB.setTRB(p_TRB); return objectFEB; } JPetLayer makeLayer(int id, bool isActive, const std::string& name, float radius, JPetFrame& frame) { JPetLayer objectLayer(id, isActive, name, radius); objectLayer.setFrame(frame); return objectLayer; } JPetHit makeHit(float e, float qe, float t, float qt, TVector3& pos, JPetPhysSignal& siga, JPetPhysSignal& sigb, JPetBarrelSlot& bslot, JPetScin& scin, float qtd, float td) { JPetHit hitObject(e, qe, t, qt, pos, siga, sigb, bslot, scin); hitObject.setQualityOfTimeDiff(qtd); hitObject.setTimeDiff(td); return hitObject; } JPetSigCh makeSigCh(JPetPM& pm, JPetTRB& trb, JPetFEB& feb, JPetTOMBChannel& channel, float val, JPetSigCh::EdgeType type, float thr, Int_t daqch, unsigned int threshold_number) { JPetSigCh sigChObject(type, val ); sigChObject.setPM(pm); sigChObject.setTRB(trb); sigChObject.setFEB(feb); sigChObject.setTOMBChannel(channel); sigChObject.setThreshold(thr); sigChObject.setDAQch(daqch); sigChObject.setThresholdNumber(threshold_number); return sigChObject; } JPetBarrelSlot makeBarrelSlot(JPetLayer& p_layer, int id, bool isActive, const std::string& name, float theta, int inFrameID) { JPetBarrelSlot barrelSlotObject(id, isActive, name, theta, inFrameID); barrelSlotObject.setLayer(p_layer); return barrelSlotObject; } JPetTimeWindow makeTimeWindow(const std::vector<JPetSigCh>& vec) { JPetTimeWindow timeWindowObject; for (auto sigch : vec) { timeWindowObject.add<JPetSigCh>(sigch); } return timeWindowObject; } JPetPM makePM(JPetPM::Side side, int id, int set, int opt, std::pair<float, float>& gain, std::string description, JPetFEB& p_FEB, JPetScin& p_scin, JPetBarrelSlot& p_barrelSlot) { JPetPM pmObject(side, id, set, opt, gain, description); pmObject.setFEB(p_FEB); pmObject.setScin(p_scin); pmObject.setBarrelSlot(p_barrelSlot); return pmObject; } JPetBaseSignal makeBaseSignal(JPetPM& pm, JPetBarrelSlot& bs) { JPetBaseSignal baseSignalObject; baseSignalObject.setPM(pm); baseSignalObject.setBarrelSlot(bs); return baseSignalObject; } JPetPhysSignal makePhysSignal(float time, float qualityOfTime, double phe, double qualityOfPhe, JPetRecoSignal& recoSignal) { JPetPhysSignal physSignalObject; physSignalObject.setTime(time); physSignalObject.setQualityOfTime(qualityOfTime); physSignalObject.setPhe(phe); physSignalObject.setQualityOfPhe(qualityOfPhe); physSignalObject.setRecoSignal(recoSignal); return physSignalObject; } JPetRawSignal makeRawSignal(const std::vector<JPetSigCh>& vec) { JPetRawSignal rawSignalObject(vec.size()); for (const auto& sigch : vec) { rawSignalObject.addPoint(sigch); } return rawSignalObject; } JPetTOMBChannel makeTOMBChannel(int p_channel, JPetFEB& p_FEB, JPetTRB& p_TRB, JPetPM& p_PM, float p_threshold, unsigned int lcn, unsigned int fin) { JPetTOMBChannel tombChannelObject(p_channel); tombChannelObject.setFEB(p_FEB); tombChannelObject.setTRB(p_TRB); tombChannelObject.setPM(p_PM); tombChannelObject.setThreshold(p_threshold); tombChannelObject.setLocalChannelNumber(lcn); tombChannelObject.setFEBInputNumber(fin); return tombChannelObject; } }
35.606299
216
0.776648
Alvarness
f74ea99d4c989d55cac6a245af0ad5e75f2ecb0d
3,451
cpp
C++
day3/src/p2.cpp
aeden/aoc2021
ca0e796169d5ca86f899e72d0754914445aacfb0
[ "MIT" ]
1
2021-12-01T13:08:14.000Z
2021-12-01T13:08:14.000Z
day3/src/p2.cpp
aeden/aoc2021
ca0e796169d5ca86f899e72d0754914445aacfb0
[ "MIT" ]
null
null
null
day3/src/p2.cpp
aeden/aoc2021
ca0e796169d5ca86f899e72d0754914445aacfb0
[ "MIT" ]
1
2021-12-07T21:12:57.000Z
2021-12-07T21:12:57.000Z
#include <iostream> #include <fstream> #include <string> #include <vector> #include <bitset> using namespace std; const int SAMPLE_BITS= 5; const int DATA_BITS = 12; const int BIT_LENGTH = DATA_BITS; vector<string> read_data(string filename) { ifstream infile; infile.open(filename); vector<string> data; if (infile.is_open()) { string line; while(getline(infile, line)) { data.push_back(line); } return data; } else { cout << "Failed to read data" << endl; return data; } } void print_bitsets(vector<bitset<BIT_LENGTH> > bitsets) { for (int i = 0; i < bitsets.size(); i++) { cout << bitsets[i]; if (i < bitsets.size() - 1) { cout << ","; } } cout << endl; } vector<bitset<BIT_LENGTH> > strings_to_bitsets(vector<string> data) { vector<bitset<BIT_LENGTH> > bitsets; for (int i = 0; i < data.size(); i++) { bitset<BIT_LENGTH> bits (data[i]); bitsets.push_back(bits); } return bitsets; } vector<bitset<BIT_LENGTH> > oxygen_generator_rating(int column_number, vector<bitset<BIT_LENGTH> > bitsets) { vector<bitset<BIT_LENGTH> > on; vector<bitset<BIT_LENGTH> > off; for (int i = 0; i < bitsets.size(); i++) { string bitstring = bitsets[i].to_string(); if (bitstring[column_number] == '1') { on.push_back(bitsets[i]); } else { off.push_back(bitsets[i]); } } if (on.size() > off.size()) { return on; } else if (on.size() == off.size()) { return on; } else { return off; } } vector<bitset<BIT_LENGTH> > co2_scrubber_rating(int column_number, vector<bitset<BIT_LENGTH> > bitsets) { vector<bitset<BIT_LENGTH> > on; vector<bitset<BIT_LENGTH> > off; for (int i = 0; i < bitsets.size(); i++) { string bitstring = bitsets[i].to_string(); if (bitstring[column_number] == '1') { on.push_back(bitsets[i]); } else { off.push_back(bitsets[i]); } } if (on.size() > off.size()) { return off; } else if (on.size() == off.size()) { return off; } else { return on; } } int calculate_oxygen_generator_rating(vector<string> data) { vector<bitset<BIT_LENGTH> > bitsets = strings_to_bitsets(data); cout << "Processing " << bitsets.size() << " rows for oxygen generator rating" << endl; for (int h = 0; h < BIT_LENGTH; h++) { bitsets = oxygen_generator_rating(h, bitsets); } return bitsets[0].to_ulong(); } int calculate_co2_scrubber_rating(vector<string> data) { vector<bitset<BIT_LENGTH> > bitsets = strings_to_bitsets(data); cout << "Processing " << bitsets.size() << " rows for CO2 scrubber rating" << endl; for (int h = 0; h < BIT_LENGTH; h++) { bitsets = co2_scrubber_rating(h, bitsets); } return bitsets[0].to_ulong(); } int main (int argc, char** argv) { string filename; if (argc != 2) { cout << "Usage: " << argv[0] << " datafile" << endl; return 1; } else { filename = argv[1]; } vector<string> data = read_data(filename); cout << "Loaded " << data.size() << " data lines" << endl; int oxygen_generator_rating = calculate_oxygen_generator_rating(data); int co2_scrubber_rating = calculate_co2_scrubber_rating(data); cout << "Oxygen generator rating: " << oxygen_generator_rating << endl; cout << "CO2 scrubber rating: " << co2_scrubber_rating << endl; cout << "Life support rating: " << oxygen_generator_rating * co2_scrubber_rating << endl; cout << "Done" << endl; return 0; }
24.475177
109
0.631991
aeden
f750452af42344d188eeaf8749b027c3a3cb454b
1,503
cpp
C++
src/c/basetypes/CData.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
3
2019-07-16T13:19:50.000Z
2020-01-06T10:42:23.000Z
src/c/basetypes/CData.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
15
2018-12-11T14:00:48.000Z
2021-12-21T17:42:42.000Z
src/c/basetypes/CData.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
2
2015-05-26T18:07:22.000Z
2017-04-04T10:01:17.000Z
#include "CData.h" #include "MailCore/MCCore.h" #include "CBase+Private.h" #include <typeinfo> #define nativeType mailcore::Data #define structName CData C_SYNTHESIZE_CONSTRUCTOR() C_SYNTHESIZE_COBJECT_CAST() CData CData_dataWithBytes(const char* bytes, unsigned int length) { CData result; result.instance = mailcore::Data::dataWithBytes(bytes, length); return result; } C_SYNTHESIZE_FUNC_WITH_SCALAR(const char*, bytes) C_SYNTHESIZE_FUNC_WITH_SCALAR(unsigned int, length) C_SYNTHESIZE_FUNC_WITH_VOID(destructiveDataClear) bool CData_externallyAllocatedMemory(CData self) { return self.instance->externallyAllocatedMemory(); } CBytesDeallocator CData_bytesDeallocator(CData self) { return self.instance->bytesDeallocator(); } CData Value_mailCoreTypeInfo() { return getTypeNameFromObject(&typeid(mailcore::Value)); } CData getTypeNameFromObject(CObject obj) { const std::type_info * info = &typeid(* obj.instance); return getTypeNameFromObject(info); } CData getTypeNameFromObject(const std::type_info * info) { CData result; #ifdef __LIBCPP_TYPEINFO size_t hash_value = info->hash_code(); const char* bytes = (char*)&hash_value; unsigned int length = sizeof(hash_value); result.instance = mailcore::Data::dataWithBytes(bytes, length); #else const char* bytes = info->name(); unsigned int length = (unsigned int) strlen(info->name()); result.instance = mailcore::Data::dataWithBytes(bytes, length); #endif return result; }
27.327273
67
0.754491
readdle
f75289ecfd13cf42799d165a0e9318b229e0ff27
678
cpp
C++
HackerRank Solutions/Algorithms/Arrays And Sorting/The Full Counting Sort.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
13
2021-09-02T07:30:02.000Z
2022-03-22T19:32:03.000Z
HackerRank Solutions/Algorithms/Arrays And Sorting/The Full Counting Sort.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
null
null
null
HackerRank Solutions/Algorithms/Arrays And Sorting/The Full Counting Sort.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
3
2021-08-24T16:06:22.000Z
2021-09-17T15:39:53.000Z
#include <bits/stdc++.h> using namespace std; int main (void) { int n, temp; cin >> n; vector< pair<int, string> > data, output; string str; int Count[100] = {0}; for (int i = 0; i < n; i++) { cin >> temp >> str; Count[temp] += 1; if (i < (n / 2)) { data.push_back(make_pair(temp, "-")); } else { data.push_back(make_pair(temp, str)); } output.push_back(make_pair(-1, "")); } for (int i = 1; i < 100; i++) { Count[i] += Count[i - 1]; } for (int i = n - 1; i >= 0; i--) { output[Count[data[i].first] - 1] = data[i]; Count[data[i].first] -= 1; } for (int i = 0; i < n; i++) { cout << output[i].second << " "; } cout << endl; return 0; }
19.941176
45
0.516224
UtkarshPathrabe
f754cb95c833b09b3c816ce4c13d717bb9752ab5
1,923
cpp
C++
src/device/Device.cpp
open-aquarium/open-aquarium-embedded
04470926ae052b862c87340560335032e8c30be4
[ "MIT" ]
null
null
null
src/device/Device.cpp
open-aquarium/open-aquarium-embedded
04470926ae052b862c87340560335032e8c30be4
[ "MIT" ]
1
2021-03-14T23:57:56.000Z
2021-03-14T23:57:56.000Z
src/device/Device.cpp
open-aquarium/open-aquarium-embedded
04470926ae052b862c87340560335032e8c30be4
[ "MIT" ]
null
null
null
#include "Device.h" /*Device::Device() { }*/ uint16_t Device::getFreeSRAM() { return (int) SP - (int) (__brkval == 0 ? (int)&__heap_start : (int)__brkval); } uint16_t Device::getSRAMUsage() { return this->getTotalSRAM() - this->getFreeSRAM(); } uint16_t Device::getTotalSRAM() { // return 8192; // 8 KB return (int) RAMEND - (int) &__data_start; } /*int Device::getFreeFlash() { return -1; } int Device::getFreeEEPROM() { return -1; }*/ float Device::getDeviceInbuiltTemperature() { // https://playground.arduino.cc/Main/InternalTemperatureSensor/ #if defined(__AVR_ATmega168A__) || defined(__ATmega168P__) || defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega32U4__) unsigned int wADC; double t; // The internal temperature has to be used // with the internal reference of 1.1V. // Channel 8 can not be selected with // the analogRead function yet. // Set the internal reference and mux. ADMUX = (_BV(REFS1) | _BV(REFS0) | _BV(MUX3)); ADCSRA |= _BV(ADEN); // enable the ADC delay(20); // wait for voltages to become stable. ADCSRA |= _BV(ADSC); // Start the ADC // Detect end-of-conversion while (bit_is_set(ADCSRA,ADSC)); // Reading register "ADCW" takes care of how to read ADCL and ADCH. wADC = ADCW; // The offset of 324.31 could be wrong. It is just an indication. t = (wADC - 324.31 ) / 1.22; return t; #else return -273.15; // Absolute Zero Celcius //OA_MIN_FLOAT; //std::numeric_limits<float>::lowest(); #endif } String Device::getCPU() { return F("ATmega2560"); } uint8_t Device::getCPUSpeed() { return 16; // MHz } uint8_t Device::getAnalogIO() { return 16; } uint8_t Device::getDigitalIO() { return 54; } uint8_t Device::getDigitalPWM() { return 15; } uint16_t Device::getTotalEEPROM() { return 4096; // 4KB } uint32_t Device::getTotalFlash() { return 33554432; // 32MB }
21.852273
152
0.668747
open-aquarium
f7558001903771191e2bf744b722fa48b5f0e02b
46,654
cpp
C++
source/runtime/heap.cpp
edmundmk/kenaf
6a4dcdac581346b6e1e8b2fcc53fa50d7a06d1f9
[ "MIT" ]
8
2020-03-19T22:07:08.000Z
2022-03-28T21:52:35.000Z
source/runtime/heap.cpp
edmundmk/kenaf
6a4dcdac581346b6e1e8b2fcc53fa50d7a06d1f9
[ "MIT" ]
null
null
null
source/runtime/heap.cpp
edmundmk/kenaf
6a4dcdac581346b6e1e8b2fcc53fa50d7a06d1f9
[ "MIT" ]
null
null
null
// // heap.cpp // // Created by Edmund Kapusniak on 02/10/2019. // Copyright © 2019 Edmund Kapusniak. // // Licensed under the MIT License. See LICENSE file in the project root for // full license information. // #include "heap.h" #include <stdint.h> #include <limits.h> #include <assert.h> #include <stdio.h> #include <new> #include <functional> #ifdef _WIN32 #include <windows.h> #else #include <sys/mman.h> #endif #ifdef _MSC_VER #include <intrin.h> #endif namespace kf { /* Count leading and trailing zeroes. */ static inline uint32_t clz( uint32_t x ) { #ifdef _MSC_VER unsigned long result; return _BitScanReverse( &result, x ) ? 31 - result : 32; #else return __builtin_clz( x ); #endif } static inline uint32_t ctz( uint32_t x ) { #ifdef _MSC_VER unsigned long result; return _BitScanForward( &result, x ) ? result : 32; #else return __builtin_ctz( x ); #endif } /* Allocate and free virtual memory from the system. */ const size_t HEAP_INITIAL_SIZE = 1024 * 1024; const size_t HEAP_VM_GRANULARITY = 1024 * 1024; #ifdef _WIN32 void* heap_vmalloc( size_t size ) { void* p = VirtualAlloc( NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE ); if ( p == NULL ) { throw std::bad_alloc(); } return p; } void heap_vmfree( void* p, size_t size ) { VirtualFree( p, 0, MEM_RELEASE ); } #else void* heap_vmalloc( size_t size ) { void* p = mmap( nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 ); if ( p == MAP_FAILED ) { throw std::bad_alloc(); } return p; } void heap_vmfree( void* p, size_t size ) { munmap( p, size ); } #endif /* An allocated chunk looks like this: --> u32 size of chunk / 1 / P u32 word & ... --- next chunk / U / 1 A free chunk which is too small to link into a bin (i.e. smaller than a header + three pointers) looks like this: --> u32 size of chunk / 0 / P ... u32 size of chunk --> next chunk / U / 0 For the very tiniest chunks, this is the same size as a header on its own. These tiny free chunks are not binned, and the memory is unrecoverable until adjacent allocations are merged. A small free chunk looks like this: --> u32 size of chunk / 0 / P u32 ... & chunk* next chunk* prev ... u32 size of chunk --- next chunk / U / 0 A large free chunk looks like this: --> u32 size of chunk / 0 / P u32 ... & chunk* next chunk* prev chunk* left chunk* right chunk* parent ... u32 size of chunk --- next chunk / U / 0 As in dlmalloc, the P bit indicates whether or not the previous chunk is allocated. The U bit indicates whether or not the current chunk is allocated. Chunks are 8-byte aligned with a maximum size of just under 4GiB. */ const size_t HEAP_CHUNK_ALIGNMENT = 8; const size_t HEAP_MIN_BINNED_SIZE = 8 + sizeof( void* ) * 3; const uint32_t HEAP_WORD_INTERNAL = 0xDEFDEF; const uint32_t HEAP_WORD_FREE = 0xFEEFEE; struct heap_chunk_header { uint32_t p_u_size; uint32_t word; heap_chunk_header( bool p, bool u, size_t size, uint32_t word ); size_t size() const; bool p() const; bool u() const; void set_p(); void clear_p(); }; inline heap_chunk_header::heap_chunk_header( bool p, bool u, size_t size, uint32_t word ) : p_u_size( (uint32_t)size |( u ? 2 : 0 )|( p ? 1 : 0 ) ) , word( word ) { assert( ( size & 3 ) == 0 ); assert( this->size() == size ); } inline size_t heap_chunk_header::size() const { return p_u_size & ~3; } inline bool heap_chunk_header::p() const { return p_u_size & 1; } inline bool heap_chunk_header::u() const { return p_u_size & 2; } inline void heap_chunk_header::set_p() { p_u_size |= 1; } inline void heap_chunk_header::clear_p() { p_u_size &= ~(uint32_t)1; } struct heap_chunk { heap_chunk_header header; // Used for free chunks. heap_chunk* next; heap_chunk* prev; // Used for large free chunks. heap_chunk* parent; heap_chunk* child[ 2 ]; size_t index; }; struct heap_chunk_footer { uint32_t size; }; /* Navigating chunks in memory. */ inline heap_chunk* heap_chunk_head( void* p ) { return (heap_chunk*)( (heap_chunk_header*)p - 1 ); } inline void* heap_chunk_data( heap_chunk* p ) { return &p->header + 1; } inline heap_chunk_footer* heap_chunk_prev_footer( heap_chunk* chunk ) { assert( ! chunk->header.p() ); return (heap_chunk_footer*)chunk - 1; } inline heap_chunk* heap_chunk_prev( heap_chunk* chunk ) { return (heap_chunk*)( (char*)chunk - heap_chunk_prev_footer( chunk )->size ); } inline heap_chunk* heap_chunk_next( heap_chunk* chunk, size_t size ) { return (heap_chunk*)( (char*)chunk + size ); } /* Setting chunk headers and footers. */ inline void heap_chunk_set_free( heap_chunk* chunk, size_t size ) { assert( size >= 8 ); chunk->header = { true, false, size, HEAP_WORD_FREE }; heap_chunk_footer* footer = (heap_chunk_footer*)( (char*)chunk + size ) - 1; footer->size = size; } inline void heap_chunk_set_allocated( heap_chunk* chunk, size_t size ) { assert( size > 0 ); chunk->header = { true, true, size, 0 }; } inline void heap_chunk_set_segment( heap_chunk* chunk ) { chunk->header = { false, true, 0, HEAP_WORD_INTERNAL }; } /* An entry in a linked list of memory segments allocated from the system. The initial segment looks like this: --- heap_state --- heap_chunk : u32 size / U / 1 ... --- heap_segment : 0 / 1 / P Subsequently allocated segments look like this: --- heap_chunk : u32 size / U / 1 ... --- heap_segment : 0 / 1 / P The heap_segment structure is always placed at the end of the segment, and is treated as an allocated chunk. This means we can guarantee that valid chunks are always followed by an allocated chunk. The heap_segment chunk has a size of zero, to indicate that it is the end of the segment. */ const size_t HEAP_MAX_CHUNK_SIZE = 0xFFFFFFE0; struct heap_segment { heap_chunk_header header; void* base; heap_segment* next; }; inline size_t heap_segment_size( heap_segment* segment ) { return (char*)( segment + 1 ) - (char*)segment->base; } inline bool heap_segment_can_merge( heap_segment* prev, heap_segment* next ) { if ( prev + 1 != next->base ) return false; size_t total_size = heap_segment_size( prev ) + heap_segment_size( next ); return total_size - sizeof( heap_segment ) <= HEAP_MAX_CHUNK_SIZE; } /* Small bin sizes, == index * 8 [ 0 ] -> == 0 [ 1 ] -> == 16 [ 2 ] -> == 24 [ 3 ] -> == 32 [ 4 ] -> == 40 ... [ 30 ] -> == 240 [ 31 ] -> == 248 Each small bin is a list of free chunks of exactly the given size. Large bin sizes, >= ( 256 << index/2 ) + index%2 ? 128 << index/2 : 0 [ 0 ] -> >= 256 [ 1 ] -> >= 384 [ 2 ] -> >= 512 [ 3 ] -> >= 768 [ 4 ] -> >= 1024 ... [ 30 ] -> >= 8MiB [ 31 ] -> >= 12MiB Large bins are trees stored in a specific way that minimises insertion cost while allowing us to quickly locate best fit chunks. */ const size_t HEAP_SMALLBIN_COUNT = 32; const size_t HEAP_LARGEBIN_COUNT = 32; const size_t HEAP_LARGE_SIZE = 256; inline size_t heap_smallbin_index( size_t size ) { assert( size < HEAP_LARGE_SIZE ); return size / 8; } inline size_t heap_largebin_index( size_t size ) { if ( size < 256 ) { return 0; } else if ( size < ( 12 << 20 ) ) { size_t log2size = sizeof( uint32_t ) * CHAR_BIT - 1 - clz( (uint32_t)size ); size_t index = ( log2size - 8 ) * 2; size_t ihalf = ( size >> ( log2size - 1 ) ) & 1; return index + ihalf; } else { return 31; } } /* Each large bin is a binary tree. The nodes of the tree are lists of chunks with the same size. Each tree is a 'not quite' prefix tree/bitwise trie keyed on the low bits of the chunk size. Let 'base' be the minimum size of chunk stored in this bin (the large bin size, above). The sizes of chunks in each bin are in the interval [ base, base + range ), where range is a power of two. For example: bin 4 base 0b0100_0000_0000 range 9 bits last 0b0101_1111_1111 bin 5 base 0b0110_0000_0000 range 9 bits last 0b0111_1111_1111 bin 6 base 0b1000_0000_0000 range 10 bits last 0b1011_1111_1111 Each node in the tree selects between its children using a bit from the range, with the root selecting using the high bit and subsequent levels using the next highest bit. However, instead of the linked list for each chunk size being stored in leaf nodes, each leaf of the tree is stored in one of its ancestors (it doesn't matter which one, it will depend on insertion order). For example, bin 1 has a range of 7 bits, and a bitwise trie might look like (with some chains of parent nodes elided): [..] .---------------'---------------. [0..] [1..] .-------'-------. .-------'-------. [00..] [01..] . [11..] .----'----. '----. 1010110 .----' . . . . 0001111 0010110 0110110 1100111 But our tree might instead look like this: [..] 1010110 .-----------'----------. [0..] 0001111 [1..] 1100111 .-------'-------. [00..] 0010110 [01..] 0110110 Since tree operations are complex, they are split out here so they can be tested indepedently. */ struct heap_largebin { heap_chunk* root; void insert( size_t index, size_t size, heap_chunk* chunk ); bool remove( size_t index, heap_chunk* chunk ); heap_chunk* smallest( size_t index ); heap_chunk* best_fit( size_t index, size_t size ); uint32_t trie_prefix( size_t index, size_t size ); heap_chunk* leftwards( heap_chunk* chunk ); heap_chunk* rightwards( heap_chunk* chunk ); void debug_print( size_t index ); void debug_print( size_t index, int level, uint32_t prefix, heap_chunk* chunk ); }; void heap_largebin::insert( size_t index, size_t size, heap_chunk* chunk ) { assert( heap_largebin_index( size ) == index ); uint32_t prefix = trie_prefix( index, size ); // Set tree node properties. chunk->child[ 0 ] = nullptr; chunk->child[ 1 ] = nullptr; chunk->index = index; // Link into tree. heap_chunk* parent = chunk; heap_chunk** link = &root; heap_chunk* node = *link; while ( true ) { if ( ! node ) { // Link new node into tree. *link = chunk; chunk->next = chunk; chunk->prev = chunk; chunk->parent = parent; break; } if ( node->header.size() == size ) { // Link new node into the linked list at this tree node. heap_chunk* next = node->next; node->next = chunk; next->prev = chunk; chunk->next = next; chunk->prev = node; chunk->parent = nullptr; break; } parent = node; link = &node->child[ prefix >> 31 ]; prefix <<= 1; node = *link; } } bool heap_largebin::remove( size_t index, heap_chunk* chunk ) { assert( chunk->index == index ); assert( heap_largebin_index( chunk->header.size() ) == index ); heap_chunk* replace = nullptr; heap_chunk* prev = chunk->prev; heap_chunk* next = chunk->next; heap_chunk* parent = chunk->parent; if ( next != chunk ) { // Chunk is part of a list. Unlink it. prev->next = next; next->prev = prev; // If original chunk wasn't a tree node, then we're done. if ( ! parent ) { return true; } // Otherwise replace the node with the next one in the list. replace = next; } else { assert( parent ); replace = rightwards( chunk ); if ( replace ) { // Search for rightmost leaf. heap_chunk* replace_parent = chunk; while ( heap_chunk* right = rightwards( replace ) ) { replace_parent = replace; replace = right; } // Unlink replacement node from its current position in the tree. assert( ! replace->child[ 0 ] && ! replace->child[ 1 ] ); assert( replace->parent == replace_parent ); if ( replace_parent->child[ 0 ] == replace ) replace_parent->child[ 0 ] = nullptr; if ( replace_parent->child[ 1 ] == replace ) replace_parent->child[ 1 ] = nullptr; } } if ( replace ) { replace->child[ 0 ] = chunk->child[ 0 ]; replace->child[ 1 ] = chunk->child[ 1 ]; if ( replace->child[ 0 ] ) replace->child[ 0 ]->parent = replace; if ( replace->child[ 1 ] ) replace->child[ 1 ]->parent = replace; } if ( parent != chunk ) { // Replacing a non-root node. if ( parent->child[ 0 ] == chunk ) parent->child[ 0 ] = replace; if ( parent->child[ 1 ] == chunk ) parent->child[ 1 ] = replace; if ( replace ) replace->parent = parent; return true; } else { // Replacing the root node of the tree. assert( root == chunk ); root = replace; if ( replace ) { // Mark as root by linking it back to itself. replace->parent = replace; return true; } else { // Bin is now empty. return false; } } } heap_chunk* heap_largebin::smallest( size_t index ) { assert( root ); heap_chunk* chunk = root; size_t chunk_size = chunk->header.size(); assert( heap_largebin_index( chunk_size ) == index ); heap_chunk* tree = leftwards( chunk ); while ( tree ) { size_t tree_size = tree->header.size(); if ( tree_size < chunk_size ) { chunk = tree->next; chunk_size = tree_size; } tree = leftwards( tree ); } return chunk; } heap_chunk* heap_largebin::best_fit( size_t index, size_t size ) { assert( heap_largebin_index( size ) == index ); assert( root ); heap_chunk* chunk = nullptr; size_t chunk_size = SIZE_MAX; // Search down tree limited by the size we're looking for. heap_chunk* right_tree = nullptr; heap_chunk* tree = root; uint32_t prefix = trie_prefix( index, size ); while ( true ) { size_t tree_size = tree->header.size(); if ( size <= tree_size && tree_size < chunk_size ) { chunk = tree->next; chunk_size = tree_size; if ( chunk_size == size ) { break; } } heap_chunk* right = tree->child[ 1 ]; tree = tree->child[ prefix >> 31 ]; prefix <<= 1; if ( right && right != tree ) { right_tree = right; } if ( ! tree ) { tree = right_tree; break; } } // Might not have found anything. if ( ! tree && ! chunk ) { return nullptr; } // Go down the left hand side to find smallest chunk. while ( tree ) { size_t tree_size = tree->header.size(); if ( size <= tree_size && tree_size < chunk_size ) { chunk = tree->next; chunk_size = tree_size; } tree = leftwards( tree ); } return chunk; } uint32_t heap_largebin::trie_prefix( size_t index, size_t size ) { // Shift bits of size so most significant bit is the top bit of our range. assert( heap_largebin_index( size ) == index ); uint32_t range_bits = 7 + index / 2; return (uint32_t)size << ( 32 - range_bits ); } inline heap_chunk* heap_largebin::leftwards( heap_chunk* chunk ) { heap_chunk* left = chunk->child[ 0 ]; return left ? left : chunk->child[ 1 ]; } inline heap_chunk* heap_largebin::rightwards( heap_chunk* chunk ) { heap_chunk* right = chunk->child[ 1 ]; return right ? right : chunk->child[ 0 ]; } void heap_largebin::debug_print( size_t index ) { printf( "LARGEBIN %zu: %p\n", index, root ); if ( root ) { debug_print( index, 0, 0, root ); } } void heap_largebin::debug_print( size_t index, int level, uint32_t prefix, heap_chunk* chunk ) { printf( "%*s[", ( level + 1 ) * 2, "" ); for ( int i = 0; i < level; ++i ) { printf( "%c", ( prefix << i ) >> 31 ? '1' : '0' ); } printf( "..] " ); size_t range_bits = 7 + index / 2; uint32_t size_bits = chunk->header.size() << ( 32 - range_bits ); for ( size_t i = 0; i < range_bits; ++i ) { printf( "%c", size_bits >> 31 ? '1' : '0' ); size_bits <<= 1; } printf( " -> %p/%s/%s:%zu i:%zu u:%p l:%p r:%p\n", chunk, chunk->header.u() ? "U" : "-", chunk->header.p() ? "P" : "-", chunk->header.size(), chunk->index, chunk->parent, chunk->child[ 0 ], chunk->child[ 1 ] ); heap_chunk* c = chunk; do { printf( "%*s%p/%s/%s:%zu i:%zu @:%p <-> %p\n", ( level + 3 ) * 2, "", c, c->header.u() ? "U" : "-", c->header.p() ? "P" : "-", c->header.size(), c->index, c->prev, c->next ); c = c->next; } while ( c != chunk ); if ( c->child[ 0 ] ) { debug_print( index, level + 1, prefix, c->child[ 0 ] ); } if ( c->child[ 1 ] ) { debug_print( index, level + 1, prefix | ( 1u << ( 31 - level ) ), c->child[ 1 ] ); } } /* Main heap data structure, at the start of the initial segment. Note that smallbin_anchors are the sentinel nodes in doubly-linked lists of chunks. However, we only store the next and prev pointers. */ struct heap_state { explicit heap_state( size_t segment_size ); ~heap_state(); heap_chunk_header header; uint32_t smallbin_map; uint32_t largebin_map; uint32_t victim_size; uint32_t segment_size; heap_segment* segments; heap_chunk* victim; heap_chunk* smallbin_anchors[ HEAP_SMALLBIN_COUNT * 2 ]; heap_largebin largebins[ HEAP_LARGEBIN_COUNT ]; void* malloc( size_t size ); void free( void* p ); heap_chunk* smallbin_anchor( size_t i ); void insert_chunk( size_t size, heap_chunk* chunk ); void remove_chunk( size_t size, heap_chunk* chunk ); heap_chunk* remove_small_chunk( size_t size, heap_chunk* chunk ); heap_chunk* remove_large_chunk( size_t index, heap_chunk* chunk ); heap_chunk* alloc_segment( size_t size ); void free_segment( heap_segment* segment ); void unlink_segment( heap_segment* segment ); void* sweep( void* p, bool free_chunk ); void debug_print(); }; heap_state::heap_state( size_t segment_size ) : header{ true, true, sizeof( heap_state ), 0 } , smallbin_map( 0 ) , largebin_map( 0 ) , victim_size( 0 ) , segment_size( segment_size ) , segments( nullptr ) , victim( nullptr ) , smallbin_anchors{} , largebins{} { // Initialize anchors. for ( size_t i = 0; i < HEAP_SMALLBIN_COUNT; ++i ) { heap_chunk* anchor = smallbin_anchor( i ); anchor->next = anchor; anchor->prev = anchor; } // Set up initial segment, containing this heap_state structure, then a // free chunk, then a heap_segment structure. assert( segment_size >= sizeof( heap_state ) + sizeof( heap_segment ) ); heap_chunk* free_chunk = (heap_chunk*)( this + 1 ); heap_chunk* segment_chunk = (heap_chunk*)( (char*)this + segment_size - sizeof( heap_segment ) ); if ( free_chunk < segment_chunk ) { size_t size = segment_size - sizeof( heap_state ) - sizeof( heap_segment ); assert( size <= HEAP_MAX_CHUNK_SIZE ); heap_chunk_set_free( free_chunk, size ); victim = free_chunk; victim_size = size; } heap_chunk_set_segment( segment_chunk ); // Link in the initial segment. segments = (heap_segment*)segment_chunk; segments->base = this; segments->next = nullptr; } heap_state::~heap_state() { heap_segment* s = segments; while ( s ) { heap_segment* next = s->next; if ( s->base != this ) { heap_vmfree( s->base, heap_segment_size( s ) ); } s = next; } } void* heap_state::malloc( size_t size ) { // Chunk size is larger due to overhead, and must be aligned. size = size + sizeof( heap_chunk_header ); size = ( size + ( HEAP_CHUNK_ALIGNMENT - 1 ) ) & ~( HEAP_CHUNK_ALIGNMENT - 1 ); if ( size > HEAP_MAX_CHUNK_SIZE ) { throw std::bad_alloc(); } heap_chunk* chunk = nullptr; size_t chunk_size = 0; if ( size < HEAP_LARGE_SIZE ) { // Small chunk. /* Use the entirety of a chunk in a smallbin of the correct size. */ size_t index = heap_smallbin_index( size ); uint32_t bin_map = smallbin_map & ~( ( 1u << index ) - 1 ); if ( bin_map & 1u << index ) { heap_chunk* anchor = smallbin_anchor( index ); chunk = remove_small_chunk( index, anchor->next ); assert( chunk != anchor ); heap_chunk_set_allocated( chunk, size ); heap_chunk_next( chunk, size )->header.set_p(); return heap_chunk_data( chunk ); } /* Locate a chunk to split. */ if ( size <= victim_size ) { // Use existing victim chunk. chunk = victim; chunk_size = victim_size; } else if ( bin_map ) { // Use smallest chunk in smallbins that can satisfy the request. index = ctz( bin_map ); chunk_size = index * 8; assert( heap_smallbin_index( chunk_size ) == index ); assert( index < HEAP_SMALLBIN_COUNT ); assert( smallbin_map & 1u << index ); heap_chunk* anchor = smallbin_anchor( index ); chunk = remove_small_chunk( index, anchor->next ); assert( chunk != anchor ); } else if ( largebin_map ) { // Pick smallest chunk in the first non-empty largebin. size_t index = ctz( largebin_map ); assert( index < HEAP_LARGEBIN_COUNT ); chunk = remove_large_chunk( index, largebins[ index ].smallest( index ) ); chunk_size = chunk->header.size(); } else { // Allocate new VM segment. chunk = alloc_segment( size ); chunk_size = chunk->header.size(); } } else { // Large chunk. /* Search for best fit in binned large chunks. */ size_t index = heap_largebin_index( size ); uint32_t bin_map = largebin_map & ~( ( 1u << index ) - 1 ); if ( bin_map ) { if ( bin_map & 1u << index ) { // Search bin of appropriate size for smallest chunk that fits. chunk = largebins[ index ].best_fit( index, size ); bin_map &= ~( 1u << index ); } if ( ! chunk && bin_map ) { // No chunks in that bin, or all chunks were too small, find // smallest chunk in a larger bin (if one exists). index = ctz( bin_map ); chunk = largebins[ index ].smallest( index ); } } if ( chunk ) { chunk_size = chunk->header.size(); assert( size <= chunk_size ); if ( victim_size >= chunk_size || size > victim_size ) { // Binned chunk will be split. remove_large_chunk( chunk->index, chunk ); } else { // Victim is a better fit. chunk = victim; chunk_size = victim_size; } } else if ( size <= victim_size ) { // Use existing victim chunk. chunk = victim; chunk_size = victim_size; } else { // Neither large chunks nor victim fit, allocate new VM segment. chunk = alloc_segment( size ); chunk_size = chunk->header.size(); } } assert( chunk ); assert( chunk->header.p() ); assert( ! chunk->header.u() ); assert( size <= chunk_size ); heap_chunk* split_chunk = nullptr; size_t split_chunk_size = 0; if ( chunk_size - size >= HEAP_MIN_BINNED_SIZE ) { // Allocate. heap_chunk_set_allocated( chunk, size ); // Set up split chunk in remaining space. split_chunk = heap_chunk_next( chunk, size ); split_chunk_size = chunk_size - size; heap_chunk_set_free( split_chunk, split_chunk_size ); } else { // Splitting the chunk will leave us with a free chunk that we cannot // link into a bin, so just use the entire chunk. heap_chunk_set_allocated( chunk, chunk_size ); heap_chunk_next( chunk, chunk_size )->header.set_p(); } if ( chunk == victim ) { // Update victim chunk. victim = split_chunk; victim_size = split_chunk_size; } else if ( size < HEAP_LARGE_SIZE ) { // Update victim chunk. heap_chunk* old_victim = victim; size_t old_victim_size = victim_size; victim = split_chunk; victim_size = split_chunk_size; if ( old_victim ) { insert_chunk( old_victim_size, old_victim ); } } else if ( split_chunk ) { // Add split chunk to bin. insert_chunk( split_chunk_size, split_chunk ); } return heap_chunk_data( chunk ); } void heap_state::free( void* p ) { // free( nullptr ) is valid. if ( ! p ) { return; } // We don't have much context, but assert that the chunk is allocated. heap_chunk* chunk = heap_chunk_head( p ); assert( chunk->header.u() ); size_t size = chunk->header.size(); // Attempt to merge with previous chunk. if ( ! chunk->header.p() ) { heap_chunk* prev = heap_chunk_prev( chunk ); assert( prev->header.p() ); assert( ! prev->header.u() ); if ( prev != victim ) { size_t prev_size = prev->header.size(); remove_chunk( prev_size, prev ); size += prev_size; } else { size += victim_size; } chunk = prev; } // Attempt to merge with following chunk. heap_chunk* next = heap_chunk_next( chunk, size ); if ( ! next->header.u() ) { assert( next->header.p() ); if ( next != victim ) { size_t next_size = next->header.size(); remove_chunk( next_size, next ); size += next_size; } else { victim = chunk; size += victim_size; } next = heap_chunk_next( chunk, size ); } if ( next->header.size() != 0 || chunk != ( (heap_segment*)next )->base ) { // This chunk is free. heap_chunk_set_free( chunk, size ); assert( next->header.u() ); next->header.clear_p(); if ( chunk != victim ) { insert_chunk( size, chunk ); } else { victim_size = size; } } else { // This chunk spans the entire segment, so free the segment. free_segment( (heap_segment*)next ); if ( chunk == victim ) { victim = nullptr; victim_size = 0; } } } heap_chunk* heap_state::smallbin_anchor( size_t i ) { assert( i < HEAP_SMALLBIN_COUNT ); return heap_chunk_head( &smallbin_anchors[ i * 2 ] ); } void heap_state::insert_chunk( size_t size, heap_chunk* chunk ) { assert( size > 0 ); assert( chunk ); assert( chunk != victim ); if ( size < HEAP_MIN_BINNED_SIZE ) { /* Chunk is too small to add to a free bin at all, since the required pointers won't fit. It'll be wasted until it can be merged with an adjacent chunk. */ } else if ( size < HEAP_LARGE_SIZE ) { size_t index = heap_smallbin_index( size ); // Insert at head of smallbin list of this size. heap_chunk* prev = smallbin_anchor( index ); heap_chunk* next = prev->next; prev->next = chunk; next->prev = chunk; chunk->next = next; chunk->prev = prev; // Mark smallbin map, as this smallbin is not empty. smallbin_map |= 1u << index; } else { // Insert into largebin. size_t index = heap_largebin_index( size ); largebins[ index ].insert( index, size, chunk ); // Mark largebin map, as this largebin is not empty. largebin_map |= 1u << index; } } void heap_state::remove_chunk( size_t size, heap_chunk* chunk ) { assert( chunk != victim ); if ( size < HEAP_MIN_BINNED_SIZE || chunk == victim ) { // Isn't in any bin. } else if ( size < HEAP_LARGE_SIZE ) { remove_small_chunk( heap_smallbin_index( size ), chunk ); } else { remove_large_chunk( chunk->index, chunk ); } } heap_chunk* heap_state::remove_small_chunk( size_t index, heap_chunk* chunk ) { heap_chunk* prev = chunk->prev; heap_chunk* next = chunk->next; // Unlink from list. prev->next = next; next->prev = prev; // Check if this bin is now empty. if ( next == prev ) { assert( prev == smallbin_anchor( index ) ); smallbin_map &= ~( 1u << index ); } return chunk; } heap_chunk* heap_state::remove_large_chunk( size_t index, heap_chunk* chunk ) { // Remove from largebin. bool nonempty = largebins[ index ].remove( index, chunk ); // Clear largebin map if the bin is empty. if ( ! nonempty ) { largebin_map &= ~( 1u << index ); } return chunk; } heap_chunk* heap_state::alloc_segment( size_t size ) { // Add space for segment header, and align to VM allocation granularity. size += sizeof( heap_segment ); size = ( size + ( HEAP_VM_GRANULARITY - 1 ) ) & ~( HEAP_VM_GRANULARITY - 1 ); // Make VM allocation. void* vmalloc = heap_vmalloc( size ); // Add segment. heap_chunk* segment_chunk = (heap_chunk*)( (char*)vmalloc + size - sizeof( heap_segment ) ); heap_chunk_set_segment( segment_chunk ); heap_segment* segment = (heap_segment*)segment_chunk; segment->base = vmalloc; // Add to segment list in memory address order. heap_segment* prev = nullptr; if ( std::less< void* >()( vmalloc, segments->base ) ) { segment->next = segments; segments = segment; } else { prev = segments; while ( true ) { heap_segment* next = prev->next; if ( ! next || std::less< void* >()( vmalloc, next->base ) ) break; prev = next; } assert( prev ); segment->next = prev->next; prev->next = segment; } // Create free chunk. size_t free_size = size - sizeof( heap_segment ); heap_chunk* free_chunk = (heap_chunk*)segment->base; // Attempt to merge with previous segment. if ( prev && heap_segment_can_merge( prev, segment ) ) { // Remove segment. unlink_segment( prev ); segment->base = prev->base; if ( segment->base == this ) { segment_size = heap_segment_size( segment ); } // Merge free space. heap_chunk* prev_chunk = (heap_chunk*)prev; assert( prev_chunk->header.u() ); assert( prev_chunk->header.size() == 0 ); free_size += sizeof( heap_segment ); free_chunk = prev_chunk; if ( ! free_chunk->header.p() ) { prev_chunk = heap_chunk_prev( free_chunk ); assert( prev_chunk->header.p() ); assert( ! prev_chunk->header.u() ); if ( prev_chunk != victim ) { size_t prev_chunk_size = prev_chunk->header.size(); remove_chunk( prev_chunk_size, prev_chunk ); free_size += prev_chunk_size; } else { free_size += victim_size; victim = nullptr; victim_size = 0; } free_chunk = prev_chunk; } } // And with next segment. heap_segment* next = segment->next; if ( next && heap_segment_can_merge( segment, next ) && next->base != this ) { // Merge free space. free_size += sizeof( heap_segment ); heap_chunk* next_chunk = (heap_chunk*)( segment + 1 ); assert( next_chunk->header.p() ); if ( ! next_chunk->header.u() ) { if ( next_chunk != victim ) { size_t next_chunk_size = next_chunk->header.size(); remove_chunk( next_chunk_size, next_chunk ); free_size += next_chunk_size; } else { free_size += victim_size; victim = nullptr; victim_size = 0; } } else { next_chunk->header.clear_p(); } // Remove segment. next->base = segment->base; unlink_segment( segment ); segment = next; } // Construct free chunk in space. heap_chunk_set_free( free_chunk, free_size ); return free_chunk; } void heap_state::free_segment( heap_segment* segment ) { assert( segment->base != this ); unlink_segment( segment ); heap_vmfree( segment->base, heap_segment_size( segment ) ); } void heap_state::unlink_segment( heap_segment* segment ) { heap_segment** link = &segments; while ( heap_segment* s = *link ) { if ( s == segment ) break; link = &s->next; } assert( *link == segment ); *link = segment->next; } void* heap_state::sweep( void* p, bool free_chunk ) { heap_chunk* c; if ( p ) { c = heap_chunk_head( p ); c = heap_chunk_next( c, c->header.size() ); } else { c = (heap_chunk*)segments->base; } void* q = nullptr; while ( true ) { // Check for end of segment. if ( c->header.size() == 0 ) { // Move to next segment. heap_segment* s = (heap_segment*)c; s = s->next; // Check if we've reached the end of the heap. if ( ! s ) { break; } // Consider first chunk in this segment. c = (heap_chunk*)s->base; } // Check for allocated chunk. if ( c->header.u() ) { q = heap_chunk_data( c ); break; } // Move to next chunk. c = heap_chunk_next( c, c->header.size() ); } // Free current chunk. if ( free_chunk ) { free( p ); } // return next allocated chunk, or nullptr at end of heap. return q; } void heap_state::debug_print() { printf( "HEAP %p:\n", this ); printf( " smallbin_map: %08X\n", smallbin_map ); for ( size_t index = 0; index < HEAP_SMALLBIN_COUNT; ++index ) { if ( smallbin_map & 1u << index ) { heap_chunk* anchor = smallbin_anchor( index ); printf( " %zu:%p <-> %p\n", index, anchor->prev, anchor->next ); } } printf( " largebin_map: %08X\n", largebin_map ); for ( size_t index = 0; index < HEAP_LARGEBIN_COUNT; ++index ) { if ( largebin_map & 1u << index ) { largebins[ index ].debug_print( index ); } } printf( " victim: %p:%zu\n", victim, (size_t)victim_size ); for ( heap_segment* s = segments; s; s = s->next ) { printf( "SEGMENT %p %p:%zu:\n", s, s->base, heap_segment_size( s ) ); heap_chunk* c = (heap_chunk*)s->base; while ( true ) { printf( " %p/%s/%s:%zu", c, c->header.u() ? "U" : "-", c->header.p() ? "P" : "-", c->header.size() ); if ( ! c->header.u() ) { if ( c == victim ) { printf( " VICTIM" ); } else if ( c->header.size() < HEAP_MIN_BINNED_SIZE ) { printf( " UNBINNED" ); } else if ( c->header.size() < HEAP_LARGE_SIZE ) { printf( " @:%p <-> %p", c->prev, c->next ); } else { printf( " i:%zu u:%p l:%p r:%p @:%p <-> %p", c->index, c->parent, c->child[ 0 ], c->child[ 1 ], c->prev, c->next ); } heap_chunk_footer* footer = (heap_chunk_footer*)( (char*)c + c->header.size() ) - 1; printf( " f:%zu\n", (size_t)footer->size ); } else { printf( "\n" ); } if ( c == (heap_chunk*)s ) { break; } c = heap_chunk_next( c, c->header.size() ); } } } /* Heap interface. */ heap_state* heap_create() { return new ( heap_vmalloc( HEAP_INITIAL_SIZE ) ) heap_state( HEAP_INITIAL_SIZE ); } void heap_destroy( heap_state* heap ) { size_t vmsize = heap->segment_size; heap->~heap_state(); heap_vmfree( heap, vmsize ); } void* heap_malloc( heap_state* heap, size_t size ) { return heap->malloc( size ); } size_t heap_malloc_size( void* p ) { heap_chunk* chunk = heap_chunk_head( p ); assert( chunk->header.u() ); return chunk->header.size() - sizeof( heap_chunk_header ); } void heap_free( heap_state* heap, void* p ) { heap->free( p ); } void* heap_sweep( heap_state* heap, void* p, bool free_chunk ) { return heap->sweep( p, free_chunk ); } void debug_print( heap_state* heap ) { heap->debug_print(); } } /* Testing of heap. */ #ifdef HEAP_TEST #include <string.h> #include <vector> #include <map> using namespace kf; bool visit_largebin( heap_state* heap, std::map< heap_chunk*, size_t >* bins, size_t index, heap_chunk* tree ) { bool ok = true; heap_chunk* chunk = tree; do { if ( chunk->index != index ) { printf( "******** LARGEBIN CHUNK %p HAS INCORRECT INDEX\n", chunk ); ok = false; } bins->emplace( chunk, 32 + index ); chunk = chunk->next; } while ( chunk != tree ); if ( tree->child[ 0 ] ) { if ( tree->child[ 0 ]->parent != tree ) { printf( "******** PARENT LINK IN LARGEBIN IS WRONG %p -> %p (wrong %p)\n", tree, tree->child[ 0 ], tree->child[ 0 ]->parent ); ok = false; } if ( ! visit_largebin( heap, bins, index, tree->child[ 0 ] ) ) ok = false; } if ( tree->child[ 1 ] ) { if ( tree->child[ 1 ]->parent != tree ) { printf( "******** PARENT LINK IN LARGEBIN IS WRONG %p -> %p (wrong %p)\n", tree, tree->child[ 1 ], tree->child[ 1 ]->parent ); ok = false; } if ( ! visit_largebin( heap, bins, index, tree->child[ 1 ] ) ) ok = false; } return ok; } bool visit_bins( heap_state* heap, std::map< heap_chunk*, size_t >* bins ) { bool ok = true; for ( size_t smi = 0; smi < HEAP_SMALLBIN_COUNT; ++smi ) { if ( !( heap->smallbin_map & 1u << smi ) ) continue; heap_chunk* anchor = heap->smallbin_anchor( smi ); heap_chunk* chunk = anchor->next; do { if ( smi != heap_smallbin_index( chunk->header.size() ) ) { printf( "******** SMALLBIN CHUNK %p HAS INCORRECT INDEX\n", chunk ); ok = false; } bins->emplace( chunk, smi ); chunk = chunk->next; } while ( chunk != anchor ); } for ( size_t lgi = 0; lgi < HEAP_LARGEBIN_COUNT; ++lgi ) { if ( !( heap->largebin_map & 1u << lgi ) ) continue; if ( ! visit_largebin( heap, bins, lgi, heap->largebins[ lgi ].root ) ) ok = false; } return ok; } bool check_bins( heap_state* heap ) { bool ok = true; std::map< heap_chunk*, size_t > bins; if ( ! visit_bins( heap, &bins ) ) ok = false; for ( heap_segment* s = heap->segments; s; s = s->next ) { heap_chunk* c = (heap_chunk*)s->base; bool was_u = true; while ( true ) { if ( was_u != c->header.p() ) { printf( "!!!!!!!! P/U MISMATCH: %p\n", c ); ok = false; } was_u = c->header.u(); if ( ! c->header.u() ) { if ( c == heap->victim ) { if ( bins.find( c ) != bins.end() ) { printf( "******** VICTIM CHUNK IS IN BIN\n" ); ok = false; } if ( c->header.size() != heap->victim_size ) { printf( "******** VICTIM SIZE MISMATCH\n" ); ok = false; } } else if ( c->header.size() < HEAP_MIN_BINNED_SIZE ) { if ( bins.find( c ) != bins.end() ) { printf( "******** UNBINNABLE CHUNK %p IS IN BIN\n", c ); ok = false; } } else if ( c->header.size() < HEAP_LARGE_SIZE ) { if ( bins.find( c ) == bins.end() ) { printf( "******** BINNED SMALL CHUNK %p IS NOT IN BIN\n", c ); ok = false; } bins.erase( c ); } else { if ( bins.find( c ) == bins.end() ) { printf( "******** BINNED LARGE CHUNK %p IS NOT IN BIN\n", c ); ok = false; } bins.erase( c ); } } if ( c == (heap_chunk*)s ) break; c = heap_chunk_next( c, c->header.size() ); } } if ( ! bins.empty() ) { printf( "******** BINS HAVE DEAD CHUNKS\n" ); for ( const auto& binned_chunk : bins ) { printf( " %p : %zu\n", binned_chunk.first, binned_chunk.second ); } ok = false; } return ok; } int main( int argc, char* argv[] ) { heap_state* state = heap_create(); srand( clock() ); struct alloc { void* p; size_t size; int b; }; std::vector< alloc > allocs; int b = 0; // Check allocations. for ( size_t i = 0; i < 100; ++i ) { printf( "-------- ALLOC\n" ); size_t alloc_count = rand() % 100; for ( size_t j = 0; j < alloc_count; ++j ) { size_t alloc_size = rand() % 512; if ( alloc_size >= 256 ) { alloc_size = rand() % ( 16 * 1024 * 1024 ); } void* p = heap_malloc( state, alloc_size ); memset( p, b, alloc_size ); allocs.push_back( { p, alloc_size, b } ); b = ( b + 1 ) % 256; printf( " -------- %p\n", heap_chunk_head( p ) ); debug_print( state ); bool ok = check_bins( state ); assert( ok ); } printf( "-------- FREE\n" ); size_t free_count = allocs.size() ? rand() % allocs.size() : 0; for ( size_t j = 0; j < free_count; ++j ) { bool ok = true; size_t alloc_index = rand() % allocs.size(); alloc a = allocs.at( alloc_index ); for ( size_t j = 0; j < a.size; ++j ) { if ( *( (char*)a.p + j ) != (char)a.b ) { printf( "******** BLOCK AT %p:%zu CORRUPT SHOULD BE %02X\n", a.p, a.size, a.b ); ok = false; break; } } assert( ok ); printf( "-------- FREE %p\n", heap_chunk_head( a.p ) ); heap_free( state, a.p ); allocs.erase( allocs.begin() + alloc_index ); debug_print( state ); if ( ! check_bins( state ) ) ok = false; assert( ok ); } } for ( const alloc& a : allocs ) { bool ok = true; for ( size_t j = 0; j < a.size; ++j ) { if ( *( (char*)a.p + j ) != (char)a.b ) { printf( "******** BLOCK AT %p:%zu CORRUPT SHOULD BE %02X\n", a.p, a.size, a.b ); ok = false; break; } } assert( ok ); printf( "-------- FREE %p\n", heap_chunk_head( a.p ) ); heap_free( state, a.p ); debug_print( state ); if ( ! check_bins( state ) ) ok = false; assert( ok ); } allocs.clear(); heap_destroy( state ); return EXIT_SUCCESS; } #endif
26.538111
214
0.521006
edmundmk
f755ba950f073011290e4045bc51832a4c1a1318
431
cpp
C++
binary_GA/binary_GA_utils.cpp
donRumata03/PowerfulGA
e4e2370287a7b654caf92adac8a64a39e23468c9
[ "MIT" ]
3
2020-04-11T10:48:01.000Z
2021-02-09T11:43:12.000Z
binary_GA/binary_GA_utils.cpp
donRumata03/PowerfulGA
e4e2370287a7b654caf92adac8a64a39e23468c9
[ "MIT" ]
6
2020-12-03T15:37:45.000Z
2020-12-09T11:02:37.000Z
binary_GA/binary_GA_utils.cpp
donRumata03/PowerfulGA
e4e2370287a7b654caf92adac8a64a39e23468c9
[ "MIT" ]
1
2021-04-25T21:50:09.000Z
2021-04-25T21:50:09.000Z
#include "binary_GA_utils.h" namespace binary_GA { population generate_population(const pms& ranges, size_t amount) { } void mutate(genome& target_genome, const vector<double>& sigmas, double target_gene_number) { } vector<vector<double>> select_matting_pool(const population& genomes, const vector<double>& fitnesses, size_t amount) { } population perform_crossover_matting(parents_t& parents) { } }
16.576923
118
0.742459
donRumata03
f755e81d8a9b88e30c1dfa753cc824d6548a9dca
35,989
hxx
C++
main/basic/source/inc/namecont.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/basic/source/inc/namecont.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/basic/source/inc/namecont.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef BASIC_NAMECONTAINER_HXX #define BASIC_NAMECONTAINER_HXX #include <hash_map> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/script/XStorageBasedLibraryContainer.hpp> #include <com/sun/star/script/XLibraryContainerPassword.hpp> #include <com/sun/star/script/XLibraryContainerExport.hpp> #include <com/sun/star/script/XLibraryContainer3.hpp> #include <com/sun/star/container/XNameContainer.hpp> #include <com/sun/star/container/XContainer.hpp> #include <com/sun/star/ucb/XSimpleFileAccess.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/util/XMacroExpander.hpp> #include <com/sun/star/util/XStringSubstitution.hpp> #include <com/sun/star/document/XStorageBasedDocument.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/frame/XModel.hpp> #include <com/sun/star/deployment/XPackage.hpp> #include <com/sun/star/script/vba/XVBACompatibility.hpp> #include <com/sun/star/script/vba/XVBAScriptListener.hpp> #include <com/sun/star/util/XChangesNotifier.hpp> #include <osl/mutex.hxx> #include <unotools/eventlisteneradapter.hxx> #include <cppuhelper/implbase3.hxx> #include <cppuhelper/compbase8.hxx> #include <cppuhelper/interfacecontainer.hxx> #include <cppuhelper/weakref.hxx> #include <cppuhelper/component.hxx> #include <cppuhelper/typeprovider.hxx> #include <cppuhelper/interfacecontainer.hxx> #include <cppuhelper/basemutex.hxx> #include <sot/storage.hxx> #include <comphelper/listenernotification.hxx> #include <xmlscript/xmllib_imexp.hxx> class BasicManager; namespace basic { //============================================================================ typedef ::cppu::WeakImplHelper3< ::com::sun::star::container::XNameContainer, ::com::sun::star::container::XContainer, ::com::sun::star::util::XChangesNotifier > NameContainer_BASE; class NameContainer : public ::cppu::BaseMutex, public NameContainer_BASE { typedef std::hash_map< ::rtl::OUString, sal_Int32, ::rtl::OUStringHash > NameContainerNameMap; NameContainerNameMap mHashMap; ::com::sun::star::uno::Sequence< ::rtl::OUString > mNames; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > mValues; sal_Int32 mnElementCount; ::com::sun::star::uno::Type mType; ::com::sun::star::uno::XInterface* mpxEventSource; ::cppu::OInterfaceContainerHelper maContainerListeners; ::cppu::OInterfaceContainerHelper maChangesListeners; public: NameContainer( const ::com::sun::star::uno::Type& rType ) : mnElementCount( 0 ) , mType( rType ) , mpxEventSource( NULL ) , maContainerListeners( m_aMutex ) , maChangesListeners( m_aMutex ) {} void setEventSource( ::com::sun::star::uno::XInterface* pxEventSource ) { mpxEventSource = pxEventSource; } // Methods XElementAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw(::com::sun::star::uno::RuntimeException); // Methods XNameAccess virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException); // Methods XNameReplace virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // Methods XNameContainer virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeByName( const ::rtl::OUString& Name ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // Methods XContainer virtual void SAL_CALL addContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); // Methods XChangesNotifier virtual void SAL_CALL addChangesListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XChangesListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeChangesListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XChangesListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); }; //============================================================================ class ModifiableHelper { private: ::cppu::OInterfaceContainerHelper m_aModifyListeners; ::cppu::OWeakObject& m_rEventSource; sal_Bool mbModified; public: ModifiableHelper( ::cppu::OWeakObject& _rEventSource, ::osl::Mutex& _rMutex ) :m_aModifyListeners( _rMutex ) ,m_rEventSource( _rEventSource ) ,mbModified( sal_False ) { } inline sal_Bool isModified() const { return mbModified; } void setModified( sal_Bool _bModified ); inline void addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& _rxListener ) { m_aModifyListeners.addInterface( _rxListener ); } inline void removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& _rxListener ) { m_aModifyListeners.removeInterface( _rxListener ); } }; //============================================================================ typedef ::comphelper::OListenerContainerBase< ::com::sun::star::script::vba::XVBAScriptListener, ::com::sun::star::script::vba::VBAScriptEvent > VBAScriptListenerContainer_BASE; class VBAScriptListenerContainer : public VBAScriptListenerContainer_BASE { public: explicit VBAScriptListenerContainer( ::osl::Mutex& rMutex ); private: virtual bool implTypedNotify( const ::com::sun::star::uno::Reference< ::com::sun::star::script::vba::XVBAScriptListener >& rxListener, const ::com::sun::star::script::vba::VBAScriptEvent& rEvent ) throw (::com::sun::star::uno::Exception); }; //============================================================================ class SfxLibrary; typedef ::cppu::WeakComponentImplHelper8< ::com::sun::star::lang::XInitialization, ::com::sun::star::script::XStorageBasedLibraryContainer, ::com::sun::star::script::XLibraryContainerPassword, ::com::sun::star::script::XLibraryContainerExport, ::com::sun::star::script::XLibraryContainer3, ::com::sun::star::container::XContainer, ::com::sun::star::script::vba::XVBACompatibility, ::com::sun::star::lang::XServiceInfo > SfxLibraryContainer_BASE; class SfxLibraryContainer : public SfxLibraryContainer_BASE, public ::utl::OEventListenerAdapter { VBAScriptListenerContainer maVBAScriptListeners; sal_Int32 mnRunningVBAScripts; sal_Bool mbVBACompat; protected: ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF; ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > mxSFI; ::com::sun::star::uno::Reference< ::com::sun::star::util::XMacroExpander > mxMacroExpander; ::com::sun::star::uno::Reference< ::com::sun::star::util::XStringSubstitution > mxStringSubstitution; ::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XModel > mxOwnerDocument; ::osl::Mutex maMutex; ModifiableHelper maModifiable; NameContainer maNameContainer; sal_Bool mbOldInfoFormat; sal_Bool mbOasis2OOoFormat; ::rtl::OUString maInitialDocumentURL; ::rtl::OUString maInfoFileName; ::rtl::OUString maOldInfoFileName; ::rtl::OUString maLibElementFileExtension; ::rtl::OUString maLibraryPath; ::rtl::OUString maLibrariesDir; ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > mxStorage; BasicManager* mpBasMgr; sal_Bool mbOwnBasMgr; enum InitMode { DEFAULT, CONTAINER_INIT_FILE, LIBRARY_INIT_FILE, OFFICE_DOCUMENT, OLD_BASIC_STORAGE } meInitMode; void implStoreLibrary( SfxLibrary* pLib, const ::rtl::OUString& aName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); // New variant for library export void implStoreLibrary( SfxLibrary* pLib, const ::rtl::OUString& aName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& aTargetURL, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > xToUseSFI, const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& xHandler ); void implStoreLibraryIndexFile( SfxLibrary* pLib, const ::xmlscript::LibDescriptor& rLib, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); // New variant for library export void implStoreLibraryIndexFile( SfxLibrary* pLib, const ::xmlscript::LibDescriptor& rLib, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& aTargetURL, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > xToUseSFI ); sal_Bool implLoadLibraryIndexFile( SfxLibrary* pLib, ::xmlscript::LibDescriptor& rLib, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& aIndexFileName ); void implImportLibDescriptor( SfxLibrary* pLib, ::xmlscript::LibDescriptor& rLib ); // Methods to distinguish between deffirent library types virtual SfxLibrary* SAL_CALL implCreateLibrary( const ::rtl::OUString& aName ) = 0; virtual SfxLibrary* SAL_CALL implCreateLibraryLink ( const ::rtl::OUString& aName, const ::rtl::OUString& aLibInfoFileURL, const ::rtl::OUString& StorageURL, sal_Bool ReadOnly ) = 0; virtual ::com::sun::star::uno::Any SAL_CALL createEmptyLibraryElement( void ) = 0; virtual bool SAL_CALL isLibraryElementValid( ::com::sun::star::uno::Any aElement ) const = 0; virtual void SAL_CALL writeLibraryElement ( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer>& xLibrary, const ::rtl::OUString& aElementName, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& xOutput ) throw(::com::sun::star::uno::Exception) = 0; virtual ::com::sun::star::uno::Any SAL_CALL importLibraryElement ( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer>& xLibrary, const ::rtl::OUString& aElementName, const ::rtl::OUString& aFile, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xElementStream ) = 0; virtual void SAL_CALL importFromOldStorage( const ::rtl::OUString& aFile ) = 0; // Password encryption virtual sal_Bool implStorePasswordLibrary( SfxLibrary* pLib, const ::rtl::OUString& aName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& Handler ); // New variant for library export virtual sal_Bool implStorePasswordLibrary( SfxLibrary* pLib, const ::rtl::OUString& aName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& aTargetURL, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > xToUseSFI, const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& Handler ); virtual sal_Bool implLoadPasswordLibrary( SfxLibrary* pLib, const ::rtl::OUString& Name, sal_Bool bVerifyPasswordOnly=false ) throw(::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void onNewRootStorage() = 0; // #56666, Creates another library container // instance of the same derived class virtual SfxLibraryContainer* createInstanceImpl( void ) = 0; // Interface to get the BasicManager (Hack for password implementation) BasicManager* getBasicManager( void ); ::rtl::OUString createAppLibraryFolder( SfxLibrary* pLib, const ::rtl::OUString& aName ); sal_Bool init( const ::rtl::OUString& rInitialDocumentURL, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxInitialStorage ); virtual const sal_Char* SAL_CALL getInfoFileName() const = 0; virtual const sal_Char* SAL_CALL getOldInfoFileName() const = 0; virtual const sal_Char* SAL_CALL getLibElementFileExtension() const = 0; virtual const sal_Char* SAL_CALL getLibrariesDir() const = 0; // Handle maLibInfoFileURL and maStorageURL correctly void checkStorageURL ( const ::rtl::OUString& aSourceURL, ::rtl::OUString& aLibInfoFileURL, ::rtl::OUString& aStorageURL, ::rtl::OUString& aUnexpandedStorageURL ); ::rtl::OUString expand_url( const ::rtl::OUString& url ) throw(::com::sun::star::uno::RuntimeException); SfxLibrary* getImplLib( const String& rLibraryName ); void storeLibraries_Impl( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, sal_Bool bComplete ); void SAL_CALL initializeFromDocumentURL( const ::rtl::OUString& _rInitialDocumentURL ); void SAL_CALL initializeFromDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::document::XStorageBasedDocument >& _rxDocument ); // OEventListenerAdapter virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource ); // OComponentHelper virtual void SAL_CALL disposing(); private: sal_Bool init_Impl( const ::rtl::OUString& rInitialDocumentURL, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxInitialStorage ); void implScanExtensions( void ); public: SfxLibraryContainer( void ); ~SfxLibraryContainer(); // Interface to set the BasicManager (Hack for password implementation) void setBasicManager( BasicManager* pBasMgr ) { mpBasMgr = pBasMgr; } void enterMethod(); void leaveMethod(); bool isDisposed() const { return rBHelper.bInDispose || rBHelper.bDisposed; } void checkDisposed() const; // Methods XElementAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements() throw(::com::sun::star::uno::RuntimeException); // Methods XNameAccess virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException); // Members XStorageBasedLibraryContainer virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > SAL_CALL getRootStorage() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setRootStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rootstorage ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL storeLibrariesToStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& RootStorage ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // Methods XModifiable (base of XPersistentLibraryContainer) virtual ::sal_Bool SAL_CALL isModified( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setModified( ::sal_Bool bModified ) throw (::com::sun::star::beans::PropertyVetoException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // Methods XPersistentLibraryContainer (base of XStorageBasedLibraryContainer) virtual ::com::sun::star::uno::Any SAL_CALL getRootLocation() throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getContainerLocationName() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL storeLibraries( ) throw (::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); //Methods XLibraryContainer3 virtual ::rtl::OUString SAL_CALL getOriginalLibraryLinkURL( const ::rtl::OUString& Name ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); // Methods XLibraryContainer2 (base of XPersistentLibraryContainer) virtual sal_Bool SAL_CALL isLibraryLink( const ::rtl::OUString& Name ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getLibraryLinkURL( const ::rtl::OUString& Name ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isLibraryReadOnly( const ::rtl::OUString& Name ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setLibraryReadOnly( const ::rtl::OUString& Name, sal_Bool bReadOnly ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL renameLibrary( const ::rtl::OUString& Name, const ::rtl::OUString& NewName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException); // Methods XLibraryContainer (base of XLibraryContainer2) virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > SAL_CALL createLibrary( const ::rtl::OUString& Name ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL createLibraryLink ( const ::rtl::OUString& Name, const ::rtl::OUString& StorageURL, sal_Bool ReadOnly ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeLibrary( const ::rtl::OUString& Name ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isLibraryLoaded( const ::rtl::OUString& Name ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL loadLibrary( const ::rtl::OUString& Name ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // Methods XInitialization virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); // Methods XLibraryContainerPassword virtual sal_Bool SAL_CALL isLibraryPasswordProtected( const ::rtl::OUString& Name ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isLibraryPasswordVerified( const ::rtl::OUString& Name ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL verifyLibraryPassword( const ::rtl::OUString& Name, const ::rtl::OUString& Password ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL changeLibraryPassword( const ::rtl::OUString& Name, const ::rtl::OUString& OldPassword, const ::rtl::OUString& NewPassword ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); // Methods XContainer virtual void SAL_CALL addContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); // Methods XLibraryContainerExport virtual void SAL_CALL exportLibrary( const ::rtl::OUString& Name, const ::rtl::OUString& URL, const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& Handler ) throw (::com::sun::star::uno::Exception, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); // Methods XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException) = 0; virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException) = 0; // Methods XVBACompatibility virtual ::sal_Bool SAL_CALL getVBACompatibilityMode() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setVBACompatibilityMode( ::sal_Bool _vbacompatmodeon ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getRunningVBAScripts() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVBAScriptListener( const ::com::sun::star::uno::Reference< ::com::sun::star::script::vba::XVBAScriptListener >& Listener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVBAScriptListener( const ::com::sun::star::uno::Reference< ::com::sun::star::script::vba::XVBAScriptListener >& Listener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL broadcastVBAScriptEvent( sal_Int32 nIdentifier, const ::rtl::OUString& rModuleName ) throw (::com::sun::star::uno::RuntimeException); }; //============================================================================ class LibraryContainerMethodGuard { private: SfxLibraryContainer& m_rContainer; public: LibraryContainerMethodGuard( SfxLibraryContainer& _rContainer ) :m_rContainer( _rContainer ) { m_rContainer.enterMethod(); } ~LibraryContainerMethodGuard() { m_rContainer.leaveMethod(); } }; //============================================================================ class SfxLibrary : public ::com::sun::star::container::XNameContainer , public ::com::sun::star::container::XContainer , public ::com::sun::star::util::XChangesNotifier , public ::cppu::BaseMutex , public ::cppu::OComponentHelper { friend class SfxLibraryContainer; friend class SfxDialogLibraryContainer; friend class SfxScriptLibraryContainer; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF; ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > mxSFI; ModifiableHelper& mrModifiable; NameContainer maNameContainer; sal_Bool mbLoaded; sal_Bool mbIsModified; sal_Bool mbInitialised; private: ::rtl::OUString maLibElementFileExtension; ::rtl::OUString maLibInfoFileURL; ::rtl::OUString maStorageURL; ::rtl::OUString maUnexpandedStorageURL; ::rtl::OUString maOrignialStorageURL; sal_Bool mbLink; sal_Bool mbReadOnly; sal_Bool mbReadOnlyLink; sal_Bool mbPreload; sal_Bool mbPasswordProtected; sal_Bool mbPasswordVerified; sal_Bool mbDoc50Password; ::rtl::OUString maPassword; sal_Bool mbSharedIndexFile; sal_Bool mbExtension; // Additional functionality for localisation // Provide modify state including resources virtual sal_Bool isModified( void ) = 0; virtual void storeResources( void ) = 0; virtual void storeResourcesAsURL( const ::rtl::OUString& URL, const ::rtl::OUString& NewName ) = 0; virtual void storeResourcesToURL( const ::rtl::OUString& URL, const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& xHandler ) = 0; virtual void storeResourcesToStorage( const ::com::sun::star::uno::Reference < ::com::sun::star::embed::XStorage >& xStorage ) = 0; protected: inline sal_Bool implIsModified() const { return mbIsModified; } void implSetModified( sal_Bool _bIsModified ); private: /** checks whether the lib is readonly, or a readonly link, throws an IllegalArgumentException if so */ void impl_checkReadOnly(); /** checks whether the library is loaded, throws a LibraryNotLoadedException (wrapped in a WrappedTargetException), if not. */ void impl_checkLoaded(); private: void impl_removeWithoutChecks( const ::rtl::OUString& _rElementName ); public: SfxLibrary( ModifiableHelper& _rModifiable, const ::com::sun::star::uno::Type& aType, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xMSF, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >& xSFI ); SfxLibrary( ModifiableHelper& _rModifiable, const ::com::sun::star::uno::Type& aType, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xMSF, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >& xSFI, const ::rtl::OUString& aLibInfoFileURL, const ::rtl::OUString& aStorageURL, sal_Bool ReadOnly ); // Methods XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& rType ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL acquire() throw() { OComponentHelper::acquire(); } virtual void SAL_CALL release() throw() { OComponentHelper::release(); } // Methods XElementAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw(::com::sun::star::uno::RuntimeException); // Methods XNameAccess virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException); // Methods XNameReplace virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // Methods XNameContainer virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeByName( const ::rtl::OUString& Name ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XTypeProvider ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw( ::com::sun::star::uno::RuntimeException ); ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL getImplementationId( ) throw( ::com::sun::star::uno::RuntimeException ); // Methods XContainer virtual void SAL_CALL addContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); // Methods XChangesNotifier virtual void SAL_CALL addChangesListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XChangesListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeChangesListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XChangesListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); public: struct LibraryContainerAccess { friend class SfxLibraryContainer; private: LibraryContainerAccess() { } }; void removeElementWithoutChecks( const ::rtl::OUString& _rElementName, LibraryContainerAccess ) { impl_removeWithoutChecks( _rElementName ); } protected: virtual bool SAL_CALL isLibraryElementValid( ::com::sun::star::uno::Any aElement ) const = 0; }; //============================================================================ class ScriptSubPackageIterator { com::sun::star::uno::Reference< com::sun::star::deployment::XPackage > m_xMainPackage; bool m_bIsValid; bool m_bIsBundle; com::sun::star::uno::Sequence< com::sun::star::uno::Reference < com::sun::star::deployment::XPackage > > m_aSubPkgSeq; sal_Int32 m_nSubPkgCount; sal_Int32 m_iNextSubPkg; com::sun::star::uno::Reference< com::sun::star::deployment::XPackage > implDetectScriptPackage( const com::sun::star::uno::Reference < com::sun::star::deployment::XPackage > xPackage, bool& rbPureDialogLib ); public: ScriptSubPackageIterator( com::sun::star::uno::Reference< com::sun::star::deployment::XPackage > xMainPackage ); com::sun::star::uno::Reference< com::sun::star::deployment::XPackage > getNextScriptSubPackage( bool& rbPureDialogLib ); }; //============================================================================ class ScriptExtensionIterator { public: ScriptExtensionIterator( void ); rtl::OUString nextBasicOrDialogLibrary( bool& rbPureDialogLib ); private: com::sun::star::uno::Reference< com::sun::star::deployment::XPackage > implGetScriptPackageFromPackage ( const com::sun::star::uno::Reference< com::sun::star::deployment::XPackage > xPackage, bool& rbPureDialogLib ); protected: com::sun::star::uno::Reference< com::sun::star::deployment::XPackage > implGetNextUserScriptPackage( bool& rbPureDialogLib ); com::sun::star::uno::Reference< com::sun::star::deployment::XPackage > implGetNextSharedScriptPackage( bool& rbPureDialogLib ); com::sun::star::uno::Reference< com::sun::star::deployment::XPackage > implGetNextBundledScriptPackage( bool& rbPureDialogLib ); com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > m_xContext; enum IteratorState { USER_EXTENSIONS, SHARED_EXTENSIONS, BUNDLED_EXTENSIONS, END_REACHED } m_eState; com::sun::star::uno::Sequence< com::sun::star::uno::Reference < com::sun::star::deployment::XPackage > > m_aUserPackagesSeq; bool m_bUserPackagesLoaded; com::sun::star::uno::Sequence< com::sun::star::uno::Reference < com::sun::star::deployment::XPackage > > m_aSharedPackagesSeq; bool m_bSharedPackagesLoaded; com::sun::star::uno::Sequence< com::sun::star::uno::Reference < com::sun::star::deployment::XPackage > > m_aBundledPackagesSeq; bool m_bBundledPackagesLoaded; int m_iUserPackage; int m_iSharedPackage; int m_iBundledPackage; ScriptSubPackageIterator* m_pScriptSubPackageIterator; }; // end class ScriptExtensionIterator //============================================================================ } // namespace basic #endif
45.383354
288
0.681931
Grosskopf
f756340b057918c4f1874c68657acdcd6657e851
14,521
cpp
C++
m2qt/m2qt_callback.cpp
ttuna/m2qt
614cc86765ccb2e096bf2bfbe12d03e311ec657f
[ "MIT" ]
null
null
null
m2qt/m2qt_callback.cpp
ttuna/m2qt
614cc86765ccb2e096bf2bfbe12d03e311ec657f
[ "MIT" ]
null
null
null
m2qt/m2qt_callback.cpp
ttuna/m2qt
614cc86765ccb2e096bf2bfbe12d03e311ec657f
[ "MIT" ]
null
null
null
#include "m2qt_callback.h" #include "m2qt_messageparser.h" #include <QCryptographicHash> #include <QJsonObject> #include <QTextStream> #include <QDebug> using namespace M2QT; namespace { static CallbackHelper* helper = new M2QT::CallbackHelper(); // ---------------------------------------------------------------------------- // // Handler callbacks ... // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- Response DebugOutputHandler(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; QByteArray debug_msg; QTextStream debug_stream(&debug_msg); // mongrel2 message ... debug_stream << "\n-------------------------" << endl; debug_stream << "DebugOutputHandler:\n" << endl; debug_stream << "\tuuid:" << uuid << endl; debug_stream << "\tid:" << id << endl; debug_stream << "\tpath:" << path << endl; debug_stream << "\tnetstring entries:" << net_strings.count() << endl; // json header ... debug_stream << "\n\tJson header:" << endl; QJsonObject jobj = M2QT::getJsonHeader(net_strings); QJsonObject::const_iterator iter = jobj.constBegin(); for ( ;iter!=jobj.constEnd(); ++iter ) { debug_stream << "\t\t" << left << iter.key() << ":" << iter.value().toString() << endl; } // netstring payload ... debug_stream << "\n\tPayload:" << endl; for(int i = 1; i<net_strings.size(); ++i) { debug_stream << "\t\t" << std::get<NS_SIZE>(net_strings[i]) << ":" << std::get<NS_DATA>(net_strings[i]) << endl; } debug_stream << "-------------------------" << endl; // remove \0 chars from debug_msg ... debug_msg.replace('\0', ""); helper->signalDebug(QLatin1String(debug_msg)); return Response(); } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- Response WebsocketHandshakeHandler(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; // get HEADER ... QJsonObject jobj = M2QT::getJsonHeader(net_strings); if (jobj.isEmpty()) { emit helper->signalError(QStringLiteral("WebsocketHandshakeHandler - No header available!")); return Response(); } // get SEC-WEBSOCKET-KEY ... QJsonValue val = jobj.value("sec-websocket-key"); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketHandshakeHandler - Couldn't find SEC-WEBSOCKET-KEY header!")); return Response(); } // calc SEC-WEBSOCKET-ACCEPT ... QByteArray key = val.toString().toLatin1() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; QByteArray accept = QCryptographicHash::hash(key, QCryptographicHash::Sha1).toBase64(); // TODO: consider SEC-WEBSOCKET-PROTOCOL ... (see https://tools.ietf.org/html/rfc6455#section-11.3.4) // TODO: consider SEC-WEBSOCKET-EXTENSIONS ... (see https://tools.ietf.org/html/rfc6455#section-11.3.2) // build response body ... QByteArray response_data("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: upgrade\r\nSec-WebSocket-Accept: "); response_data += accept + "\r\n\r\n"; NetString rep_id = std::make_tuple(static_cast<quint32>(id.size()), id); // build Response ... Response rep = std::make_tuple(uuid, rep_id, response_data); return rep; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- Response WebsocketCloseHandler(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; QByteArray response_data; QByteArray ws_header = M2QT::getWebSocketHeader(response_data.size(), 0x08, 0x00); response_data.prepend(ws_header); NetString rep_id = std::make_tuple(static_cast<quint32>(id.size()), id); // build Response ... Response rep = std::make_tuple(uuid, rep_id, response_data); return rep; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- Response WebsocketEchoHandler(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; QByteArray response_data; // = "HTTP/1.1 202 Accepted\r\n\r\n"; for (int i = 1; i<net_strings.size(); ++i) { response_data += std::get<NS_DATA>(net_strings[i]); } QByteArray ws_header = M2QT::getWebSocketHeader(response_data.size(), 0x01, 0x00); response_data.prepend(ws_header); NetString rep_id = std::make_tuple(static_cast<quint32>(id.size()), id); // build Response ... Response rep = std::make_tuple(uuid, rep_id, response_data); return rep; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- Response WebsocketPongHandler(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; QByteArray response_data; for (int i = 1; i<net_strings.size(); ++i) { response_data += std::get<NS_DATA>(net_strings[i]); } QByteArray ws_header = M2QT::getWebSocketHeader(response_data.size(), 0x0A, 0x00); response_data.prepend(ws_header); NetString rep_id = std::make_tuple(static_cast<quint32>(id.size()), id); // build Response ... Response rep = std::make_tuple(uuid, rep_id, response_data); return rep; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- #ifdef ENABLE_DEV_CALLBACKS Response HeavyDutyHandler(const Request &in_message) { Q_UNUSED(in_message) return Response(); } #endif // ---------------------------------------------------------------------------- // // Filter callbacks ... // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- bool WebsocketHandshakeFilter(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; // get HEADER - first NetString must be the header obj ... QJsonObject jobj = M2QT::getJsonHeader(net_strings); if (jobj.isEmpty()) { emit helper->signalError(QStringLiteral("WebsocketHandshakeFilter - No header available!")); return false; } // get METHOD ... QJsonValue val = jobj.value(QLatin1String("METHOD")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketHandshakeFilter - Couldn't find METHOD header!")); return false; } // must be "WEBSOCKET_HANDSHAKE" ... if (val.toString() != QLatin1String("WEBSOCKET_HANDSHAKE")) return false; return true; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- bool WebsocketCloseFilter(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; // get HEADER - first NetString must be the header obj ... QJsonObject jobj = M2QT::getJsonHeader(net_strings); if (jobj.isEmpty()) { emit helper->signalError(QStringLiteral("WebsocketCloseFilter - No header available!")); return false; } // get METHOD ... QJsonValue val = jobj.value(QLatin1String("METHOD")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketCloseFilter - Couldn't find METHOD header!")); return false; } // must be "WEBSOCKET" ... if (val.toString() != QLatin1String("WEBSOCKET")) return false; // get FLAGS ... val = jobj.value(QLatin1String("FLAGS")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketCloseFilter - Couldn't find FLAGS header!")); return false; } // req opcode must be 0x08 = close frame ... bool ok = false; quint8 value = val.toString().toInt(&ok, 16); if (ok == false || value == 0x0 || (value^(1<<7)) != 0x08) return false; return true; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- bool WebsocketEchoFilter(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; // get HEADER - first NetString must be the header obj ... QJsonObject jobj = M2QT::getJsonHeader(net_strings); if (jobj.isEmpty()) { emit helper->signalError(QStringLiteral("WebsocketEchoFilter - No header available!")); return false; } // get METHOD ... QJsonValue val = jobj.value(QLatin1String("METHOD")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketEchoFilter - Couldn't find METHOD header!")); return false; } // must be "WEBSOCKET" ... if (val.toString() != QLatin1String("WEBSOCKET")) return false; // get FLAGS ... val = jobj.value(QLatin1String("FLAGS")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketEchoFilter - Couldn't find FLAGS header!")); return false; } // req opcode must be 0x01 = text frame ... bool ok = false; quint8 value = val.toString().toInt(&ok, 16); if (ok == false || value == 0x0 || (value^(1<<7)) != 0x01) return false; return true; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- bool WebsocketPongFilter(const Request &in_message) { QByteArray uuid, id, path; QVector<NetString> net_strings; std::tie(uuid, id, path, net_strings) = in_message; // get HEADER - first NetString must be the header obj ... QJsonObject jobj = M2QT::getJsonHeader(net_strings); if (jobj.isEmpty()) { emit helper->signalError(QStringLiteral("WebsocketPongFilter - No header available!")); return false; } // get METHOD ... QJsonValue val = jobj.value(QLatin1String("METHOD")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketPongFilter - Couldn't find METHOD header!")); return false; } // must be "WEBSOCKET" ... if (val.toString() != QLatin1String("WEBSOCKET")) return false; // get FLAGS ... val = jobj.value(QLatin1String("FLAGS")); if (val.isUndefined()) { emit helper->signalError(QStringLiteral("WebsocketPongFilter - Couldn't find FLAGS header!")); return false; } // req opcode must be 0x09 = ping frame ... bool ok = false; quint8 value = val.toString().toInt(&ok, 16); if (ok == false || value == 0x0 || (value^(1<<7)) != 0x09) return false; return true; } } // namespace namespace M2Qt { const QString DEBUG_OUTPUT_NAME = "debug_output"; const QString WS_HANDSHAKE_NAME = "websocket_handshake"; const QString WS_CLOSE_NAME = "websocket_close"; const QString WS_ECHO_NAME = "websocket_echo"; const QString WS_PONG_NAME = "websocket_pong"; const QString HEAVY_DUTY_NAME = "heavy_duty"; } // ---------------------------------------------------------------------------- // // class CallbackManager // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // handler callback names and filter callback names must correspond if they have to work together ... // ---------------------------------------------------------------------------- QMap<QString, HandlerCallback> CallbackManager::m_handler_callback_map = { { M2Qt::DEBUG_OUTPUT_NAME, &DebugOutputHandler }, { M2Qt::WS_HANDSHAKE_NAME, &WebsocketHandshakeHandler }, { M2Qt::WS_CLOSE_NAME, &WebsocketCloseHandler }, { M2Qt::WS_ECHO_NAME, &WebsocketEchoHandler }, { M2Qt::WS_PONG_NAME, &WebsocketPongHandler }, #ifdef ENABLE_DEV_CALLBACKS { M2Qt::HEAVY_DUTY_NAME, &HeavyDutyHandler }, #endif }; QMap<QString, FilterCallback> CallbackManager::m_filter_callback_map = { { M2Qt::WS_HANDSHAKE_NAME, &WebsocketHandshakeFilter }, { M2Qt::WS_CLOSE_NAME, &WebsocketCloseFilter }, { M2Qt::WS_ECHO_NAME, &WebsocketEchoFilter }, { M2Qt::WS_PONG_NAME, &WebsocketPongFilter }, }; // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- CallbackManager::CallbackManager(QObject *parent) : QObject(parent) { m_p_static_cb_helper = helper; if (m_p_static_cb_helper != nullptr) { connect(m_p_static_cb_helper, &CallbackHelper::signalError, this, &CallbackManager::signalError); connect(m_p_static_cb_helper, &CallbackHelper::signalWarning, this, &CallbackManager::signalWarning); connect(m_p_static_cb_helper, &CallbackHelper::signalDebug, this, &CallbackManager::signalDebug); connect(m_p_static_cb_helper, &CallbackHelper::signalInfo, this, &CallbackManager::signalInfo); } } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- HandlerCallback CallbackManager::getHandlerCallback(const QString &in_name) { return m_handler_callback_map.value(in_name, nullptr); } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- FilterCallback CallbackManager::getFilterCallback(const QString &in_name) { return m_filter_callback_map.value(in_name, nullptr); }
38.930295
162
0.547621
ttuna
f75794bba4ddb699f8883e5ae6ed34ed924e46cb
1,893
cpp
C++
src/YoloNet.cpp
VasuGoel/object-detection-yolov3
949884a2981dc61fc0ebae6b1e851a24e05a326c
[ "MIT" ]
null
null
null
src/YoloNet.cpp
VasuGoel/object-detection-yolov3
949884a2981dc61fc0ebae6b1e851a24e05a326c
[ "MIT" ]
null
null
null
src/YoloNet.cpp
VasuGoel/object-detection-yolov3
949884a2981dc61fc0ebae6b1e851a24e05a326c
[ "MIT" ]
null
null
null
#include <string> #include <fstream> #include <sstream> #include <opencv2/dnn.hpp> #include "YoloNet.h" // Load the network void YoloNet::loadNetwork() { network_ = readNetFromDarknet(modelConfiguration_, modelWeights_); network_.setPreferableBackend(DNN_BACKEND_OPENCV); network_.setPreferableTarget(DNN_TARGET_CPU); } // Load class names used in COCO dataset void YoloNet::loadClasses(std::string classesFilePath) { std::string line; std::ifstream filestream(classesFilePath); while(getline(filestream, line)) classes_.push_back(line); } // Return the names of classes std::vector<std::string> YoloNet::getClasses() { return std::move(YoloNet::classes_); } // Set input for network void YoloNet::setInput(Mat blob) { network_.setInput(blob); } // Get the names of the output layers std::vector<std::string> YoloNet::getOutputsNames() { static std::vector<std::string> names; if (names.empty()) { //Get the indices of the output layers, i.e. the layers with unconnected outputs std::vector<int> outLayers = network_.getUnconnectedOutLayers(); //get the names of all the layers in the network std::vector<std::string> layersNames = network_.getLayerNames(); // Get the names of the output layers in names names.resize(outLayers.size()); for (size_t i = 0; i < outLayers.size(); ++i) names[i] = layersNames[outLayers[i] - 1]; } return names; } // Run forward pass to get output of output layers void YoloNet::runForwardPass(std::vector<Mat> &outs, std::vector<std::string> outnames) { network_.forward(outs, outnames); } // Return overall time for inference and timing for each layer (in layersTimes) double YoloNet::getInferenceTime(std::vector<double> &layersTimes) { double time = network_.getPerfProfile(layersTimes); return time; }
28.253731
88
0.696778
VasuGoel
f75962c5a91b1eaa3ded9cb44202c1a04b6fc051
22,725
cpp
C++
SimTKcommon/tests/StateTest.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
1,916
2015-01-01T09:35:21.000Z
2022-03-30T11:38:43.000Z
SimTKcommon/tests/StateTest.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
389
2015-01-01T01:13:51.000Z
2022-03-16T15:30:58.000Z
SimTKcommon/tests/StateTest.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
486
2015-01-02T10:25:49.000Z
2022-03-16T15:31:40.000Z
/* -------------------------------------------------------------------------- * * Simbody(tm): SimTKcommon * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2005-15 Stanford University and the Authors. * * Authors: Michael Sherman * * Contributors: * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ /**@file * Run the State class few some paces. */ #include "SimTKcommon.h" #include <string> #include <iostream> #include <exception> #include <cmath> using std::cout; using std::endl; using std::string; using namespace SimTK; //void testLowestModified() { // const SubsystemIndex Sub0(0), Sub1(1); // State s; // s.setNumSubsystems(2); // SimTK_TEST(s.getSystemStage()==Stage::Empty); // SimTK_TEST(s.getSubsystemStage(Sub0)==Stage::Empty && s.getSubsystemStage(Sub1)==Stage::Empty); // SimTK_TEST(s.getLowestStageModified()==Stage::Topology); // // const DiscreteVariableIndex dvxModel = s.allocateDiscreteVariable(Sub1, Stage::Model, new Value<Real>(2)); // // // "realize" Topology stage // s.advanceSubsystemToStage(Sub0, Stage::Topology); // s.advanceSubsystemToStage(Sub1, Stage::Topology); // s.advanceSystemToStage(Stage::Topology); // SimTK_TEST(s.getLowestStageModified()==Stage::Topology); // shouldn't have changed // // const DiscreteVariableIndex dvxInstance = s.allocateDiscreteVariable(Sub0, Stage::Instance, new Value<int>(-4)); // // // A Model-stage variable must be allocated before Topology is realized, and this condition // // should be tested even in Release mode. // try { // s.allocateDiscreteVariable(Sub0, Stage::Model, new Value<int>(0)); // SimTK_TEST(!"Shouldn't have allowed allocation of Model-stage var here"); // } catch (...) {} // // // "realize" Model stage // s.advanceSubsystemToStage(Sub0, Stage::Model); // s.advanceSubsystemToStage(Sub1, Stage::Model); // s.advanceSystemToStage(Stage::Model); // SimTK_TEST(s.getSystemStage() == Stage::Model); // // SimTK_TEST(s.getLowestStageModified()==Stage::Topology); // shouldn't have changed // s.resetLowestStageModified(); // SimTK_TEST(s.getLowestStageModified()==Stage::Instance); // i.e., lowest invalid stage // // // This variable invalidates Instance stage, so shouldn't change anything now. // SimTK_TEST(Value<int>::downcast(s.getDiscreteVariable(Sub0, dvxInstance))==-4); // Value<int>::downcast(s.updDiscreteVariable(Sub0, dvxInstance)) = 123; // SimTK_TEST(Value<int>::downcast(s.getDiscreteVariable(Sub0, dvxInstance))== 123); // // SimTK_TEST(s.getSystemStage()==Stage::Model); // SimTK_TEST(s.getLowestStageModified()==Stage::Instance); // // // This variable invalidates Model Stage, so should back up the stage to Topology, // // invalidating Model. // Value<Real>::downcast(s.updDiscreteVariable(Sub1, dvxModel)) = 29; // SimTK_TEST(s.getSubsystemStage(Sub1)==Stage::Topology); // SimTK_TEST(s.getLowestStageModified()==Stage::Model); // // // Now realize Model stage again; shouldn't affect lowestStageModified. // s.advanceSubsystemToStage(Sub0, Stage::Model); // s.advanceSubsystemToStage(Sub1, Stage::Model); // s.advanceSystemToStage(Stage::Model); // SimTK_TEST(s.getSystemStage() == Stage::Model); // // SimTK_TEST(s.getLowestStageModified()==Stage::Model); // shouldn't have changed //} // Advance State by one stage from stage-1 to stage. void advanceStage(State& state, Stage stage) { SimTK_TEST(state.getSystemStage() == stage.prev()); for (SubsystemIndex sx(0); sx <state.getNumSubsystems(); ++sx) state.advanceSubsystemToStage(sx, stage); state.advanceSystemToStage(stage); } void testCacheValidity() { const SubsystemIndex Sub0(0), Sub1(1); State s; s.setNumSubsystems(2); SimTK_TEST(s.getSystemStage() == Stage::Empty); //------------------------- // "realize" Topology stage // Allocate at Topology stage a Model stage-invalidating state variable. const DiscreteVariableIndex dvx1TopoModel = s.allocateDiscreteVariable(Sub1, Stage::Model, new Value<Real>(2)); SimTK_TEST(s.getDiscreteVarAllocationStage(Sub1,dvx1TopoModel) == Stage::Topology); SimTK_TEST(s.getDiscreteVarInvalidatesStage(Sub1,dvx1TopoModel) == Stage::Model); SimTK_TEST(Value<Real>::downcast(s.getDiscreteVariable(Sub1,dvx1TopoModel)) == Real(2)); // Allocate at Topology stage a cache entry that depends on Model stage // and is guaranteed to be valid at Time stage. In between (at Model or // Instance stage) it *may* be valid if explicitly marked so. const CacheEntryIndex cx0TopoModel = s.allocateCacheEntry(Sub0, Stage::Model, Stage::Time, new Value<int>(41)); SimTK_TEST(s.getCacheEntryAllocationStage(Sub0,cx0TopoModel) == Stage::Topology); // Here is a cache entry allocated at Topology stage, with depends-on // Velocity and no good-by guarantee. const CacheEntryIndex cx0TopoVelocity = s.allocateCacheEntry(Sub0, Stage::Velocity, Stage::Infinity, new Value<char>('v')); advanceStage(s, Stage::Topology); // Topology stage is realized. //---------------------------- // Shouldn't be able to access cache entry here because this is less than // its "depends on" stage. SimTK_TEST_MUST_THROW(s.getCacheEntry(Sub0, cx0TopoModel)); //------------------------- // "realize" Model stage // Allocate at Model stage, a Position-invalidating state variable. const DiscreteVariableIndex dvx0ModelPos = s.allocateDiscreteVariable(Sub0, Stage::Position, new Value<int>(31)); SimTK_TEST(s.getDiscreteVarAllocationStage(Sub0,dvx0ModelPos) == Stage::Model); SimTK_TEST(s.getDiscreteVarInvalidatesStage(Sub0,dvx0ModelPos) == Stage::Position); SimTK_TEST(Value<int>::downcast(s.getDiscreteVariable(Sub0,dvx0ModelPos)) == 31); advanceStage(s, Stage::Model); // Model stage is realized. //---------------------------- //---------------------------- // "realize" Instance stage // Allocate a cache entry at Instance stage that has Time as depends-on // and also has a cross-subsystem dependency on discrete variable // dvx0ModelPos. const CacheEntryIndex cx1InstanceTime = s.allocateCacheEntryWithPrerequisites(Sub1, Stage::Time, Stage::Velocity, false, false, true, // depends on z {DiscreteVarKey(Sub0,dvx0ModelPos)}, {CacheEntryKey(Sub0,cx0TopoModel)}, new Value<string>("hasPrereqs_Time")); // Same but had depends-on Instance. const CacheEntryIndex cx1InstInst = s.allocateCacheEntryWithPrerequisites(Sub1, Stage::Instance, Stage::Velocity, false, false, true, // depends on z {DiscreteVarKey(Sub0,dvx0ModelPos)}, {CacheEntryKey(Sub0,cx0TopoModel)}, new Value<string>("hasPrereqs_Instance")); // This attempt to create a cache-to-cache dependency should fail because // the prerequisite gets invalidated when Velocity stage changes but // the "dependent" doesn't get invalidated unless Position stage does. Thus // a velocity could change, invlidating the prereq, but the downstream // cache entry still looks valid. SimTK_TEST_MUST_THROW(s.allocateCacheEntryWithPrerequisites(Sub1, Stage::Position, Stage::Infinity, false, false, false, {}, {CacheEntryKey(Sub0,cx0TopoVelocity)}, new Value<int>(-1))); advanceStage(s, Stage::Instance); // Instance stage is realized. //---------------------------- // Check that the dependency lists are right. CacheEntryKey ckey1(Sub1,cx1InstanceTime); CacheEntryKey ckey2(Sub1,cx1InstInst); SimTK_TEST(s.getZDependents().size() == 2); SimTK_TEST(s.getZDependents().contains(ckey1)); SimTK_TEST(s.getZDependents().contains(ckey2)); const DiscreteVarInfo& dvinfo = s.getDiscreteVarInfo(DiscreteVarKey(Sub0,dvx0ModelPos)); SimTK_TEST(dvinfo.getDependents().size() == 2); SimTK_TEST(dvinfo.getDependents().contains(ckey1)); SimTK_TEST(dvinfo.getDependents().contains(ckey2)); const CacheEntryInfo& ceinfo = s.getCacheEntryInfo(CacheEntryKey(Sub0,cx0TopoModel)); SimTK_TEST(ceinfo.getDependents().size() == 2); SimTK_TEST(ceinfo.getDependents().contains(ckey1)); SimTK_TEST(ceinfo.getDependents().contains(ckey2)); // Although cx0TopoModel *could* be valid at this point, // no one has said so, so we expect it to throw. SimTK_TEST_MUST_THROW(s.getCacheEntry(Sub0, cx0TopoModel)); // If we say it is valid, we should be able to obtain its value. s.markCacheValueRealized(Sub0, cx0TopoModel); SimTK_TEST(Value<int>::downcast(s.getCacheEntry(Sub0, cx0TopoModel)) == 41); //---------------------------- // "realize" Time stage advanceStage(s, Stage::Time); // Time stage is realized. //---------------------------- // cx1InstanceTime isn't automatically valid but can be now. SimTK_TEST_MUST_THROW(s.getCacheEntry(Sub1, cx1InstanceTime)); SimTK_TEST_MUST_THROW(s.getCacheEntry(Sub1, cx1InstInst)); s.markCacheValueRealized(Sub1, cx1InstanceTime); s.markCacheValueRealized(Sub1, cx1InstInst); SimTK_TEST(Value<string>::downcast(s.getCacheEntry(Sub1,cx1InstanceTime)).get() == "hasPrereqs_Time"); SimTK_TEST(Value<string>::downcast(s.getCacheEntry(Sub1,cx1InstInst)).get() == "hasPrereqs_Instance"); // That cache entry does not depend on q or u so this should have no effect. s.updQ() = 0.; s.updU() = 0.; SimTK_TEST(s.getSystemStage() == Stage::Time); // unchanged SimTK_TEST(Value<string>::downcast(s.getCacheEntry(Sub1,cx1InstanceTime)).get() == "hasPrereqs_Time"); // Changing prerequisites should make the cache entry // inaccessible again, although the stage should not change and the cache // entry should not get deallocated. s.updZ() = 0.; // z is prerequisite SimTK_TEST(s.getSystemStage() == Stage::Time); // unchanged SimTK_TEST(s.hasCacheEntry(CacheEntryKey(Sub1,cx1InstanceTime))); SimTK_TEST_MUST_THROW(s.getCacheEntry(Sub1, cx1InstanceTime)); s.markCacheValueRealized(Sub1, cx1InstanceTime); // valid again SimTK_TEST(Value<string>::downcast(s.getCacheEntry(Sub1,cx1InstanceTime)).get() == "hasPrereqs_Time"); // Modify design var prerequisite. Value<int>::updDowncast(s.updDiscreteVariable(Sub0,dvx0ModelPos)).upd() = 99; SimTK_TEST(s.hasCacheEntry(CacheEntryKey(Sub1,cx1InstanceTime))); SimTK_TEST_MUST_THROW(s.getCacheEntry(Sub1, cx1InstanceTime)); SimTK_TEST_MUST_THROW(s.getCacheEntry(Sub1, cx1InstInst)); SimTK_TEST(s.getSystemStage() == Stage::Time); s.markCacheValueRealized(Sub1, cx1InstanceTime); // valid again SimTK_TEST(Value<string>::downcast(s.getCacheEntry(Sub1,cx1InstanceTime)).get() == "hasPrereqs_Time"); s.markCacheValueRealized(Sub1, cx1InstInst); SimTK_TEST(Value<string>::downcast(s.getCacheEntry(Sub1,cx1InstInst)).get() == "hasPrereqs_Instance"); // Test state copying. Should copy through at least Instance stage. State s2(s); // copy construction SimTK_TEST(s2.getNumSubsystems() == s.getNumSubsystems()); SimTK_TEST(s2.getSystemStage() >= Stage::Instance); SimTK_TEST(s2.hasCacheEntry(CacheEntryKey(Sub1,cx1InstanceTime))); SimTK_TEST(s2.hasCacheEntry(CacheEntryKey(Sub1,cx1InstInst))); // Dependency lists should have been reconstructed in the copy. SimTK_TEST(s2.getZDependents().size() == 2); SimTK_TEST(s2.getZDependents().contains(ckey1)); SimTK_TEST(s2.getZDependents().contains(ckey2)); const DiscreteVarInfo& dvinfo2 = s2.getDiscreteVarInfo(DiscreteVarKey(Sub0,dvx0ModelPos)); SimTK_TEST(dvinfo2.getDependents().size() == 2); SimTK_TEST(dvinfo2.getDependents().contains(ckey1)); SimTK_TEST(dvinfo2.getDependents().contains(ckey2)); const CacheEntryInfo& ceinfo2 = s2.getCacheEntryInfo(CacheEntryKey(Sub0,cx0TopoModel)); SimTK_TEST(ceinfo2.getDependents().size() == 2); SimTK_TEST(ceinfo2.getDependents().contains(ckey1)); SimTK_TEST(ceinfo2.getDependents().contains(ckey2)); s2.markCacheValueRealized(Sub1, cx1InstInst); SimTK_TEST(Value<string>::downcast(s2.getCacheEntry(Sub1,cx1InstInst)).get() == "hasPrereqs_Instance"); // Invalidate cache entry prerequisite (modifying value is not enough). s.markCacheValueNotRealized(Sub0,cx0TopoModel); SimTK_TEST_MUST_THROW(s.getCacheEntry(Sub1, cx1InstanceTime)); SimTK_TEST(s.getSystemStage() == Stage::Time); // unchanged // Now modify a Model-stage state variable and realize again. This // should have invalidated Model stage and hence cx0TopoModel. It should // also have un-allocated the Instance-stage cache entry. Value<Real>::updDowncast(s.updDiscreteVariable(Sub1, dvx1TopoModel)) = 9; SimTK_TEST(s.getSystemStage() == Stage::Topology); SimTK_TEST_MUST_THROW(s.getCacheEntry(Sub0, cx0TopoModel)); // Unallocating the cache entry should have removed it from its // prerequisite's dependency list. SimTK_TEST(!s.hasCacheEntry(CacheEntryKey(Sub1,cx1InstanceTime))); SimTK_TEST(s.getZDependents().empty()); SimTK_TEST(ceinfo.getDependents().empty()); //---------------------------- // "realize" Model stage advanceStage(s, Stage::Model); // Model stage is realized. //---------------------------- SimTK_TEST(!s.isCacheValueRealized(Sub0, cx0TopoModel)); SimTK_TEST_MUST_THROW(s.getCacheEntry(Sub0, cx0TopoModel)); // "calculate" the cache entry and mark it valid. Value<int>::updDowncast(s.updCacheEntry(Sub0,cx0TopoModel)) = (int)(2*Value<Real>::downcast(s.getDiscreteVariable(Sub1,dvx1TopoModel))); s.markCacheValueRealized(Sub0, cx0TopoModel); SimTK_TEST(Value<int>::downcast(s.getCacheEntry(Sub0, cx0TopoModel)) == 18); // Now modify the Model-stage variable again, but realize through // Time stage. We should be able to access the cache entry without // explicitly marking it valid. Value<Real>::updDowncast(s.updDiscreteVariable(Sub1, dvx1TopoModel)) = -100; advanceStage(s, Stage::Model); advanceStage(s, Stage::Instance); advanceStage(s, Stage::Time); SimTK_TEST(Value<int>::downcast(s.getCacheEntry(Sub0, cx0TopoModel)) == 18); } void testMisc() { State s; s.setNumSubsystems(1); s.advanceSubsystemToStage(SubsystemIndex(0), Stage::Topology); // Can't ask for the time before Stage::Topology, but if you could it would be NaN. s.advanceSystemToStage(Stage::Topology); // Advancing to Stage::Topology sets t=0. cout << "AFTER ADVANCE TO TOPOLOGY, t=" << s.getTime() << endl; SimTK_TEST(s.getTime()==0); Vector v3(3), v2(2); QIndex q1 = s.allocateQ(SubsystemIndex(0), v3); QIndex q2 = s.allocateQ(SubsystemIndex(0), v2); EventTriggerByStageIndex e1 = s.allocateEventTrigger(SubsystemIndex(0), Stage::Position, 3); EventTriggerByStageIndex e2 = s.allocateEventTrigger(SubsystemIndex(0), Stage::Instance, 2); printf("q1,2=%d,%d\n", (int)q1, (int)q2); printf("e1,2=%d,%d\n", (int)e1, (int)e2); //cout << s; DiscreteVariableIndex dv = s.allocateDiscreteVariable(SubsystemIndex(0), Stage::Dynamics, new Value<int>(5)); s.advanceSubsystemToStage(SubsystemIndex(0), Stage::Model); //long dv2 = s.allocateDiscreteVariable(SubsystemIndex(0), Stage::Position, new Value<int>(5)); Value<int>::updDowncast(s.updDiscreteVariable(SubsystemIndex(0), dv)) = 71; cout << s.getDiscreteVariable(SubsystemIndex(0), dv) << endl; s.advanceSystemToStage(Stage::Model); cout << "AFTER ADVANCE TO MODEL, t=" << s.getTime() << endl; // Event triggers are available at Instance stage. s.advanceSubsystemToStage(SubsystemIndex(0), Stage::Instance); s.advanceSystemToStage(Stage::Instance); printf("ntriggers=%d, by stage:\n", s.getNEventTriggers()); for (int j=0; j<Stage::NValid; ++j) { Stage g = Stage(j); cout << g.getName() << ": " << s.getNEventTriggersByStage(g) << endl; } printf("subsys 0 by stage:\n"); for (int j=0; j<Stage::NValid; ++j) { Stage g = Stage(j); cout << g.getName() << ": " << s.getNEventTriggersByStage(SubsystemIndex(0),g) << endl; } //cout << "State s=" << s; s.clear(); //cout << "after clear(), State s=" << s; } // Helper functions for testConsistent(). // Allocate some part of the state, and alter the stage accordingly. // For Q, U, Z. template <typename IDX> void allocate(State& state, Stage stage, IDX (State::*allocfun)(SubsystemIndex, const Vector&), int subsysIdx, int size) { state.invalidateAll(stage); (state.*allocfun)(SubsystemIndex(subsysIdx), Vector(size)); advanceStage(state, stage); } // For QErr, UErr, ZErr, and EventTriggers. template <typename IDX, typename ...ARGS> void allocate(State& state, Stage stage, IDX (State::*allocfun)(SubsystemIndex, ARGS...) const, int subsysIdx, ARGS... args) { state.invalidateAll(stage); (state.*allocfun)(SubsystemIndex(subsysIdx), args...); advanceStage(state, stage); } // Advance to Instance stage and test that the two states are NOT consistent. void isNotConsistent(State& sA, State& sB) { while (sA.getSystemStage() < Stage::Instance) advanceStage(sA, sA.getSystemStage().next()); while (sB.getSystemStage() < Stage::Instance) advanceStage(sB, sB.getSystemStage().next()); SimTK_TEST(!sA.isConsistent(sB)); SimTK_TEST(!sB.isConsistent(sA)); } // Advance to Instance stage and test that the two states are consistent. void isConsistent(State& sA, State& sB) { while (sA.getSystemStage() < Stage::Instance) advanceStage(sA, sA.getSystemStage().next()); while (sB.getSystemStage() < Stage::Instance) advanceStage(sB, sB.getSystemStage().next()); SimTK_TEST(sA.isConsistent(sB)); SimTK_TEST(sB.isConsistent(sA)); } void testConsistent() { State sA; State sB; int numSubsys = 3; sA.setNumSubsystems(numSubsys); sB.setNumSubsystems(numSubsys); // Must realize to Instance to check consistency. SimTK_TEST_MUST_THROW_EXC_DEBUG(sA.isConsistent(sB), Exception::StageTooLow); isConsistent(sA, sB); for (int i = 0; i < numSubsys; ++i) { // Also using `i` as a way to arbitrarily choose different Vector sizes. // Q allocate(sA, Stage::Model, &State::allocateQ, i, 5 + i); isNotConsistent(sA, sB); allocate(sB, Stage::Model, &State::allocateQ, i, 5 + i); isConsistent(sA, sB); // U allocate(sA, Stage::Model, &State::allocateU, i, 3 + i); isNotConsistent(sA, sB); allocate(sB, Stage::Model, &State::allocateU, i, 3 + i); isConsistent(sA, sB); // Z allocate(sA, Stage::Model, &State::allocateZ, i, 8 + i); isNotConsistent(sA, sB); allocate(sB, Stage::Model, &State::allocateZ, i, 8 + i); isConsistent(sA, sB); // QErr allocate(sA, Stage::Model, &State::allocateQErr, i, 2 + i); isNotConsistent(sA, sB); allocate(sB, Stage::Model, &State::allocateQErr, i, 2 + i); isConsistent(sA, sB); // UErr allocate(sA, Stage::Model, &State::allocateUErr, i, 7 + i); isNotConsistent(sA, sB); allocate(sB, Stage::Model, &State::allocateUErr, i, 7 + i); isConsistent(sA, sB); // UDotErr allocate(sA, Stage::Model, &State::allocateUDotErr, i, 1 + i); isNotConsistent(sA, sB); allocate(sB, Stage::Model, &State::allocateUDotErr, i, 1 + i); isConsistent(sA, sB); // EventTrigger for(SimTK::Stage stage = SimTK::Stage::LowestValid; stage <= SimTK::Stage::HighestRuntime; ++stage) { allocate(sA, Stage::Model, &State::allocateEventTrigger, i, stage, 12 + i); isNotConsistent(sA, sB); allocate(sB, Stage::Model, &State::allocateEventTrigger, i, stage, 12 + i); isConsistent(sA, sB); } } // Change the number of subsystems. numSubsys = 4; sA.setNumSubsystems(numSubsys); isNotConsistent(sA, sB); sB.setNumSubsystems(numSubsys); isConsistent(sA, sB); } int main() { int major,minor,build; char out[100]; const char* keylist[] = { "version", "library", "type", "debug", "authors", "copyright", "svn_revision", 0 }; SimTK_version_SimTKcommon(&major,&minor,&build); std::printf("==> SimTKcommon library version: %d.%d.%d\n", major, minor, build); std::printf(" SimTK_about_SimTKcommon():\n"); for (const char** p = keylist; *p; ++p) { SimTK_about_SimTKcommon(*p, 100, out); std::printf(" about(%s)='%s'\n", *p, out); } SimTK_START_TEST("StateTest"); //SimTK_SUBTEST(testLowestModified); SimTK_SUBTEST(testCacheValidity); SimTK_SUBTEST(testMisc); SimTK_SUBTEST(testConsistent); SimTK_END_TEST(); }
41.928044
118
0.647789
e-schumann
f75a88547ff2c8e57b03891097471c7d35f5d6bb
3,074
cpp
C++
ICPC_Mirrors/Nitc_8.0/j.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
ICPC_Mirrors/Nitc_8.0/j.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
ICPC_Mirrors/Nitc_8.0/j.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
// Optimise #include <bits/stdc++.h> using namespace std; #ifdef LOCAL #include "/home/shahraaz/bin/debug.h" #else #define db(...) #endif using ll = long long; #define f first #define s second #define pb push_back #define all(v) v.begin(), v.end() const int NAX = 2e5 + 5, MOD = 1000000007; string s; int sum[NAX], twig[NAX], ball[NAX], numNodes, totBalls; pair<int, int> child[NAX]; int parse(int start, int end) { int len = end - start + 1; if (len <= 3) { twig[start] = true; int bcnt = 0; for (size_t i = start; i <= end; i++) bcnt += s[i] == 'B'; ball[start] = bcnt; totBalls += bcnt; // sum[start] += bcnt; // numNodes++; child[start] = {-1, -1}; } else { // start++; int ptr; int ctr = 0; for (ptr = start + 1; ptr <= end; ptr++) { if (s[ptr] == '(') ctr++; else if (s[ptr] == ')') ctr--; if (ctr == 0) break; } child[start].f = parse(start + 1, ptr); child[start].s = parse(ptr + 1, end - 1); twig[start] = false; // sum[start] = sum[child[start].f] + sum[child[start].s]; ball[start] = 0; // numNodes++; } db(start, end, child[start], ball[start], sum[start], twig[start]); return start; } ll solve(int root, int given) { ll res = MOD; if (root == -1) { if (given == 0) res = 0; // return MOD; } else if (twig[root]) { if (given == 0) res = ball[root]; if (given == 1) res = 1 - ball[root]; } else if (given % 2 == 0) { auto l = solve(child[root].f, given / 2); auto r = solve(child[root].s, given / 2); res = min(res, l + r); } else { auto l = solve(child[root].f, given / 2); auto r = solve(child[root].s, given - given / 2); res = min(res, l + r); l = solve(child[root].f, given - given / 2); r = solve(child[root].s, given / 2); res = min(res, l + r); } db(root, given, res); return res; } struct Solution { Solution() {} void solveCase() { while (cin >> s) { db(s); totBalls = numNodes = 0; int root = parse(0, s.length() - 1); db("-----------------"); auto res = solve(root, totBalls); if (res < MOD) cout << res / 2 << '\n'; else cout << "impossible" << '\n'; } } }; int32_t main() { #ifndef LOCAL ios_base::sync_with_stdio(0); cin.tie(0); #endif int t = 1; // cin >> t; Solution mySolver; for (int i = 1; i <= t; ++i) { mySolver.solveCase(); #ifdef LOCAL cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n"; TimeStart = chrono::steady_clock::now(); #endif } return 0; }
22.437956
131
0.450553
Shahraaz
f75df7015a3e5ca381fb59d593d466148d724304
692
cpp
C++
Leetcode_challenges/Day15/canSquare.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
Leetcode_challenges/Day15/canSquare.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
Leetcode_challenges/Day15/canSquare.cpp
vishwajeet-hogale/LearnSTL
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; bool getSets(vector<int> &nums,vector<int> &r,int i){ if(i == nums.size()){ return !r[0] && !r[1] && !r[2] && !r[3]; } for(int j=0;j<r.size();j++){ r[j] -= nums[i]; if(getSets(nums,r,i+1)){ return true; } r[j] += nums[i]; } return false; } bool makesquare(vector<int> &nums){ int sum = 0; for(int i:nums) sum += i; if(sum % 4 == 0){ vector<int> r(4,sum/4); return getSets(nums,r,0); } return false; } int main(){ vector<int> nums({1,1,2,2,1}); cout<<makesquare(nums)<<endl; return 0; }
20.352941
53
0.479769
vishwajeet-hogale
f7644ae3353b6069e283868055d1de2a93e31879
1,795
cpp
C++
src/mame/drivers/digijet.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/digijet.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/digijet.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Ryan Holtz /************************************************************************* drivers/digijet.cpp Skeleton driver for the Volkswagen Digijet series of automotive ECUs The Digijet Engine Control Unit (ECU) was used in Volkswagen vehicles from the early 1980s. Currently, the only dump is from a 1985 Volkswagen Vanagon (USA CA). **************************************************************************/ /* TODO: - Everything */ #include "emu.h" #include "cpu/mcs48/mcs48.h" #define I8049_TAG "i8049" class digijet_state : public driver_device { public: digijet_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_maincpu(*this, I8049_TAG) { } void digijet(machine_config &config); private: required_device<cpu_device> m_maincpu; virtual void machine_start() override { } virtual void machine_reset() override { } void io_map(address_map &map); }; void digijet_state::io_map(address_map &map) { } static INPUT_PORTS_START( digijet ) INPUT_PORTS_END void digijet_state::digijet(machine_config &config) { /* basic machine hardware */ I8049(config, m_maincpu, XTAL(11'000'000)); m_maincpu->set_addrmap(AS_IO, &digijet_state::io_map); } ROM_START( digijet ) ROM_REGION( 0x800, I8049_TAG, 0 ) ROM_LOAD( "vanagon_85_usa_ca.bin", 0x000, 0x800, CRC(2ed7c4c5) SHA1(ae48d8892b44fe76b48bcefd293c15cd47af3fba) ) // Volkswagen Vanagon, 1985, USA, California ROM_END // YEAR NAME PARENT COMPAT MACHINE INPUT CLASS INIT COMPANY FULLNAME FLAGS CONS( 1985, digijet, 0, 0, digijet, digijet, digijet_state, empty_init, "Volkswagen", "Digijet", MACHINE_NOT_WORKING | MACHINE_NO_SOUND_HW )
26.791045
157
0.666295
Robbbert
f766180031763498659c8b4c461d6bad09bcfd61
3,079
cpp
C++
bridge/runtime/src/main/native/jni/InputReaderMirrorImpl.cpp
asakusafw/asakusafw-m3bp
ffb811da0055ff75f13e73ee4eedb261a46988e0
[ "Apache-2.0" ]
1
2016-12-13T07:50:36.000Z
2016-12-13T07:50:36.000Z
bridge/runtime/src/main/native/jni/InputReaderMirrorImpl.cpp
asakusafw/asakusafw-m3bp
ffb811da0055ff75f13e73ee4eedb261a46988e0
[ "Apache-2.0" ]
153
2016-04-01T08:20:15.000Z
2022-02-09T22:30:46.000Z
bridge/runtime/src/main/native/jni/InputReaderMirrorImpl.cpp
asakusafw/asakusafw-m3bp
ffb811da0055ff75f13e73ee4eedb261a46988e0
[ "Apache-2.0" ]
6
2016-04-01T07:31:57.000Z
2017-03-17T03:15:47.000Z
/* * Copyright 2011-2021 Asakusa Framework Team. * * 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 "com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl.h" #include "mirror.hpp" #include "jniutil.hpp" using namespace asakusafw::jni; /* * Class: com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl * Method: hasKey0 * Signature: (J)Z */ JNIEXPORT jboolean JNICALL Java_com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_hasKey0 (JNIEnv *env, jclass, jlong _self) { try { auto* self = reinterpret_cast<InputReaderMirror*>(_self); return self->has_key(); } catch (JavaException &e) { e.rethrow(env); return false; } catch (std::exception &e) { handle_native_exception(env, e); return false; } } /* * Class: com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl * Method: getInputBufferFragment0 * Signature: (JZ[J)V */ JNIEXPORT void JNICALL Java_com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_getInputBufferFragment0 (JNIEnv *env, jclass, jlong _self, jboolean is_key, jlongArray results) { try { auto* self = reinterpret_cast<InputReaderMirror*>(_self); jlong array[com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_VALUES_SIZE]; std::tuple<const void *, const void *, m3bp::size_type> buffer; if (is_key) { buffer = self->key_buffer(); } else { buffer = self->value_buffer(); } array[com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_INDEX_BUFFER_PTR] = to_pointer(std::get<0>(buffer)); array[com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_INDEX_OFFSET_TABLE_PTR] = to_pointer(std::get<1>(buffer)); array[com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_INDEX_RECORD_COUNT] = static_cast<jlong>(std::get<2>(buffer)); env->SetLongArrayRegion(results, 0, com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_VALUES_SIZE, &array[0]); } catch (JavaException &e) { e.rethrow(env); } catch (std::exception &e) { handle_native_exception(env, e); } } /* * Class: com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl * Method: close0 * Signature: (J)V */ JNIEXPORT void JNICALL Java_com_asakusafw_m3bp_mirror_jni_InputReaderMirrorImpl_close0 (JNIEnv *env, jclass, jlong _self) { try { auto* self = reinterpret_cast<InputReaderMirror*>(_self); delete self; } catch (JavaException &e) { e.rethrow(env); } catch (std::exception &e) { handle_native_exception(env, e); } }
36.654762
128
0.713868
asakusafw
f767aab25c1208e18c34c34ac7fe9d0e51834510
10,745
cpp
C++
src/software/test_util/test_util_test.cpp
EvanMorcom/Software
586fb3cf8dc2d93de194d9815af5de63caa7e318
[ "MIT" ]
null
null
null
src/software/test_util/test_util_test.cpp
EvanMorcom/Software
586fb3cf8dc2d93de194d9815af5de63caa7e318
[ "MIT" ]
null
null
null
src/software/test_util/test_util_test.cpp
EvanMorcom/Software
586fb3cf8dc2d93de194d9815af5de63caa7e318
[ "MIT" ]
null
null
null
#include "software/test_util/test_util.h" #include <gtest/gtest.h> #include <algorithm> /* * Unit tests for the unit test utilities */ TEST(TestUtilsTest, create_testing_world) { World world = ::TestUtil::createBlankTestingWorld(); EXPECT_EQ(Field::createSSLDivisionBField(), world.field()); EXPECT_EQ(Team(Duration::fromMilliseconds(1000)), world.friendlyTeam()); EXPECT_EQ(Team(Duration::fromMilliseconds(1000)), world.enemyTeam()); EXPECT_EQ(Ball(Point(), Vector(), Timestamp::fromSeconds(0)), world.ball()); } TEST(TestUtilsTest, set_friendly_robot_positions_in_world_with_positive_number_of_robots) { World world = ::TestUtil::createBlankTestingWorld(); world = ::TestUtil::setFriendlyRobotPositions( world, {Point(), Point(-4, 1.2), Point(2.2, -0.1)}, Timestamp::fromSeconds(0)); EXPECT_EQ(3, world.friendlyTeam().numRobots()); EXPECT_EQ(0, world.enemyTeam().numRobots()); EXPECT_EQ(Point(), (*world.friendlyTeam().getRobotById(0)).position()); EXPECT_EQ(Point(-4, 1.2), (*world.friendlyTeam().getRobotById(1)).position()); EXPECT_EQ(Point(2.2, -0.1), (*world.friendlyTeam().getRobotById(2)).position()); EXPECT_EQ(std::nullopt, world.friendlyTeam().getRobotById(3)); } TEST(TestUtilsTest, set_enemy_robot_positions_in_world_with_positive_number_of_robots) { World world = ::TestUtil::createBlankTestingWorld(); world = ::TestUtil::setEnemyRobotPositions( world, {world.field().enemyGoalCenter(), world.field().friendlyCornerPos()}, Timestamp::fromSeconds(0)); EXPECT_EQ(2, world.enemyTeam().numRobots()); EXPECT_EQ(world.field().enemyGoalCenter(), (*world.enemyTeam().getRobotById(0)).position()); EXPECT_EQ(world.field().friendlyCornerPos(), (*world.enemyTeam().getRobotById(1)).position()); EXPECT_EQ(Vector(), (*world.enemyTeam().getRobotById(0)).velocity()); EXPECT_EQ(Angle::zero(), (*world.enemyTeam().getRobotById(0)).orientation()); } TEST(TestUtilsTest, set_friendly_robot_positions_in_world_with_zero_robots) { World world = ::TestUtil::createBlankTestingWorld(); world = ::TestUtil::setFriendlyRobotPositions(world, {}, Timestamp::fromSeconds(0)); EXPECT_EQ(0, world.friendlyTeam().numRobots()); } TEST(TestUtilsTest, set_enemy_robot_positions_in_world_with_zero_robots) { World world = ::TestUtil::createBlankTestingWorld(); world = ::TestUtil::setEnemyRobotPositions(world, {}, Timestamp::fromSeconds(0)); EXPECT_EQ(0, world.enemyTeam().numRobots()); } TEST(TestUtilsTest, set_ball_position_in_world) { World world = ::TestUtil::createBlankTestingWorld(); world = ::TestUtil::setBallPosition(world, Point(-0.2, 3.11), Timestamp::fromSeconds(0)); EXPECT_EQ(Point(-0.2, 3.11), world.ball().position()); EXPECT_EQ(Vector(), world.ball().velocity()); } TEST(TestUtilsTest, set_ball_velocity_in_world) { World world = ::TestUtil::createBlankTestingWorld(); world = ::TestUtil::setBallVelocity(world, Vector(0, -2), Timestamp::fromSeconds(0)); EXPECT_EQ(Point(), world.ball().position()); EXPECT_EQ(Vector(0, -2), world.ball().velocity()); } TEST(TestUtilsTest, has_all_valid_refbox_game_states) { std::vector game_states = ::TestUtil::getAllRefboxGameStates(); // only way to test this getAllRefboxGameStates() without a literal copy-paste // of the implementation // note that this array does not contain RefboxGameState::REFBOX_GAME_STATE_COUNT, // this is intentional std::vector<RefboxGameState> expected_game_states = { RefboxGameState::HALT, RefboxGameState::STOP, RefboxGameState::NORMAL_START, RefboxGameState::FORCE_START, RefboxGameState::PREPARE_KICKOFF_US, RefboxGameState::PREPARE_KICKOFF_THEM, RefboxGameState::PREPARE_PENALTY_US, RefboxGameState::PREPARE_PENALTY_THEM, RefboxGameState::DIRECT_FREE_US, RefboxGameState::DIRECT_FREE_THEM, RefboxGameState::INDIRECT_FREE_US, RefboxGameState::INDIRECT_FREE_THEM, RefboxGameState::TIMEOUT_US, RefboxGameState::TIMEOUT_THEM, RefboxGameState::GOAL_US, RefboxGameState::GOAL_THEM, RefboxGameState::BALL_PLACEMENT_US, RefboxGameState::BALL_PLACEMENT_THEM}; for (RefboxGameState state : expected_game_states) { EXPECT_TRUE(std::find(game_states.begin(), game_states.end(), state) != game_states.end()); } } TEST(TestUtilsTest, polygon_check_if_equal_within_tolerance) { Polygon poly1({Point(2.323, 2.113), Point(4.567, 1.069), Point(9.245, 1.227)}); Polygon poly2({Point(2.324, 2.114), Point(4.568, 1.07), Point(9.246, 1.228)}); Polygon poly3({Point(2.325, 2.115), Point(4.569, 1.071), Point(9.247, 1.229)}); Polygon poly4( {Point(2.325, 2.115), Point(4.569, 1.071), Point(9.247, 1.229), Point(5, 5)}); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(poly1, poly2, 2 * METERS_PER_MILLIMETER)); EXPECT_FALSE(::TestUtil::equalWithinTolerance(poly1, poly3)); EXPECT_FALSE(::TestUtil::equalWithinTolerance(poly1, poly4)); } TEST(TestUtilsTest, point_check_if_equal_within_tolerance) { Point point1(8.423, 4.913); Point point2(8.4232391, 4.9139881); Point point3(8.424, 4.914); Point point4(8.425, 4.915); Point point5(5.393, 1.113); Point point6(5.394, 1.114); Point point7(9.245, 1.227); Point point8(9.246, 1.227); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(point1, point2, 2 * METERS_PER_MILLIMETER)); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(point1, point3, 2 * METERS_PER_MILLIMETER)); EXPECT_FALSE(::TestUtil::equalWithinTolerance(point1, point4)); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(point5, point6, 2 * METERS_PER_MILLIMETER)); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(point6, point5, 2 * METERS_PER_MILLIMETER)); EXPECT_TRUE(::TestUtil::equalWithinTolerance(point7, point8)); EXPECT_TRUE(::TestUtil::equalWithinTolerance(point8, point7)); } TEST(TestUtilsTest, circle_check_if_equal_within_tolerance) { Circle circle1(Point(5.393, 1.113), 6.567); Circle circle2(Point(5.394, 1.114), 6.568); Circle circle3(Point(5.395, 1.115), 6.569); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(circle1, circle2, 2 * METERS_PER_MILLIMETER)); EXPECT_FALSE(::TestUtil::equalWithinTolerance(circle1, circle2)); EXPECT_FALSE(::TestUtil::equalWithinTolerance(circle1, circle3)); } TEST(TestUtilsTest, vector_check_if_equal_within_tolerance) { Vector vector1(8.423, 4.913); Vector vector2(8.4232391, 4.9139881); Vector vector3(8.424, 4.914); Vector vector4(8.425, 4.915); Vector vector5(5.393, 1.113); Vector vector6(5.394, 1.114); Vector vector7(9.245, 1.227); Vector vector8(9.246, 1.227); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(vector1, vector2, 2 * METERS_PER_MILLIMETER)); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(vector1, vector3, 2 * METERS_PER_MILLIMETER)); EXPECT_FALSE(::TestUtil::equalWithinTolerance(vector1, vector4)); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(vector5, vector6, 2 * METERS_PER_MILLIMETER)); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(vector6, vector5, 2 * METERS_PER_MILLIMETER)); EXPECT_TRUE(::TestUtil::equalWithinTolerance(vector7, vector8)); EXPECT_TRUE(::TestUtil::equalWithinTolerance(vector8, vector7)); } TEST(TestUtilsTest, angle_check_if_equal_within_tolerance) { Angle angle1 = Angle::fromDegrees(5); Angle angle2 = Angle::fromDegrees(5.5); Angle angle3 = Angle::fromDegrees(189); Angle angle4 = Angle::fromDegrees(190); Angle angle5 = Angle::fromDegrees(-10); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(angle1, angle2, Angle::fromDegrees(0.5))); EXPECT_FALSE( ::TestUtil::equalWithinTolerance(angle1, angle2, Angle::fromDegrees(0.49))); EXPECT_TRUE(::TestUtil::equalWithinTolerance(angle3, angle4, Angle::fromDegrees(1))); EXPECT_FALSE( ::TestUtil::equalWithinTolerance(angle3, angle4, Angle::fromDegrees(0.99))); EXPECT_TRUE(::TestUtil::equalWithinTolerance(angle1, angle5, Angle::fromDegrees(15))); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(angle4, angle5, Angle::fromDegrees(180))); } TEST(TestUtilsTest, robot_state_check_if_equal_within_tolerance) { RobotState state1(Point(1.01, 2.58), Vector(0.0, -2.06), Angle::fromDegrees(4), AngularVelocity::fromDegrees(67.4)); RobotState state2(Point(1.01, 2.59), Vector(0.005, -2.05), Angle::fromDegrees(5), AngularVelocity::fromDegrees(67.6)); RobotState state3(Point(1.11, 2.59), Vector(0.0, -2.06), Angle::fromDegrees(4), AngularVelocity::fromDegrees(67.4)); RobotState state4(Point(1.01, 2.58), Vector(0.4, -2.58), Angle::fromDegrees(4), AngularVelocity::fromDegrees(67.4)); RobotState state5(Point(1.01, 2.58), Vector(0.0, -2.06), Angle::fromDegrees(6.4), AngularVelocity::fromDegrees(67.4)); RobotState state6(Point(1.01, 2.58), Vector(0.0, -2.06), Angle::fromDegrees(4), AngularVelocity::fromDegrees(70.02)); EXPECT_TRUE( ::TestUtil::equalWithinTolerance(state1, state2, 0.02, Angle::fromDegrees(1))); EXPECT_FALSE( ::TestUtil::equalWithinTolerance(state1, state3, 0.1, Angle::fromDegrees(1))); EXPECT_FALSE( ::TestUtil::equalWithinTolerance(state1, state4, 0.5, Angle::fromDegrees(1))); EXPECT_FALSE( ::TestUtil::equalWithinTolerance(state1, state5, 1e-3, Angle::fromDegrees(2))); EXPECT_FALSE( ::TestUtil::equalWithinTolerance(state1, state6, 1e-3, Angle::fromDegrees(2.5))); } TEST(TestUtilsTest, ball_state_check_if_equal_within_tolerance) { BallState state1(Point(1.01, 2.58), Vector(0.0, -2.06)); BallState state2(Point(1.01, 2.59), Vector(0.005, -2.05)); BallState state3(Point(1.11, 2.59), Vector(0.0, -2.06)); BallState state4(Point(1.01, 2.58), Vector(0.4, -2.58)); EXPECT_TRUE(::TestUtil::equalWithinTolerance(state1, state2, 0.02)); EXPECT_FALSE(::TestUtil::equalWithinTolerance(state1, state3, 0.1)); EXPECT_FALSE(::TestUtil::equalWithinTolerance(state1, state4, 0.5)); } TEST(TestUtilsTest, test_seconds_since) { const auto start_time = std::chrono::system_clock::now(); EXPECT_TRUE(::TestUtil::secondsSince(start_time) > 0); } TEST(TestUtilsTest, test_milliseconds_since) { const auto start_time = std::chrono::system_clock::now(); EXPECT_TRUE(::TestUtil::millisecondsSince(start_time) > 0); }
40.394737
90
0.694183
EvanMorcom
f768e730e3f441c605bfca00f3f57825f33554f4
2,691
cpp
C++
src/vectorMagnitudeDirection.cpp
D-K-E/udacity-linear-algebra
8494440627a48ca13e1d2ec166cb1939639155e0
[ "MIT" ]
null
null
null
src/vectorMagnitudeDirection.cpp
D-K-E/udacity-linear-algebra
8494440627a48ca13e1d2ec166cb1939639155e0
[ "MIT" ]
null
null
null
src/vectorMagnitudeDirection.cpp
D-K-E/udacity-linear-algebra
8494440627a48ca13e1d2ec166cb1939639155e0
[ "MIT" ]
null
null
null
/* Vector Operations Program Author: Kaan Purpose: Implement addition, subtraction, and scalar multiplication Usage: Run the program, enter the vectors. */ // Declare Packages ------------ #include <vector> #include <iostream> #include <assert.h> #include <math.h> // End of Declare Packages ----- // Functions ------------------- void print_vector(std::vector<double> vector_print){ int v_size; v_size = vector_print.size(); for(int i=0; i<v_size; i++){ std::cout << vector_print[i] << ", "; } std::cout << "\n"; } std::vector<double> vector_scalar_multiplication(std::vector<double> scaled_vector, double scalar, int vector_size){ std::vector<double> result_vector; for(int i=0; i<vector_size; i++){ double multiplication_result; multiplication_result = scaled_vector[i] * scalar; result_vector.push_back(multiplication_result); } return(result_vector); } double vector_magnitude(const std::vector<double> input_vector, int vector_size){ double magnitude;// stores the magnitude of the vector for(int i=0; i < vector_size; i++){ magnitude += pow(input_vector[i], 2.0); } magnitude = sqrt(magnitude); return(magnitude); } std::vector<double> vector_normaliser(std::vector<double> input_vector, int vector_size){ double scalar; // stores the magnitude of the vector double vec_magnitude; vec_magnitude = vector_magnitude(input_vector, vector_size); scalar = 1 / vec_magnitude; // std::vector<double> result_vector; result_vector = vector_scalar_multiplication(input_vector, scalar, vector_size); return(result_vector); } int main(){ // input vector double input; // input value which would be taken from the user std::cout << "Enter your numbers to be taken to the vector and 2.2 to quit: " << std::endl; std::vector<double> vector_1; // First vector for operations input = 0.2; while(input != -4.554){ std::cin >> input; vector_1.push_back(input); } int vec_size; // store the vector size vec_size = vector_1.size(); int vector_mag; // stores vector magnitude std::vector<double> norm_vector; // stores the unit vector vector_mag = vector_magnitude(vector_1, vec_size); norm_vector = vector_normaliser(vector_1, vec_size); std::cout << "Vector Magnitude: " << vector_mag << "\n" << "Unit Vector: " << std::endl; print_vector(norm_vector); return(0); }
28.935484
83
0.616128
D-K-E
f76ad5a740f87e4d795898f335907769b4d51388
945
cpp
C++
src/standard-release/commits/iconventional.cpp
Symbitic/standard-release
335cc62979be076f50c311336bb954fe0adc71c9
[ "MIT" ]
null
null
null
src/standard-release/commits/iconventional.cpp
Symbitic/standard-release
335cc62979be076f50c311336bb954fe0adc71c9
[ "MIT" ]
null
null
null
src/standard-release/commits/iconventional.cpp
Symbitic/standard-release
335cc62979be076f50c311336bb954fe0adc71c9
[ "MIT" ]
null
null
null
#include "iconventional.h" /* https://www.npmjs.com/package/conventional-changelog-writer */ using namespace StandardRelease; IConventionalCommit::IConventionalCommit() : m_valid(false) , m_error() , m_commits() , m_semver() { } IConventionalCommit::~IConventionalCommit() {} void IConventionalCommit::setVersion(const SemVer &semver) { m_semver = semver; } SemVer IConventionalCommit::version() const { return m_semver; } void IConventionalCommit::setValid(bool valid) { m_valid = valid; } void IConventionalCommit::setError(const Error error) { m_error = error; } void IConventionalCommit::setCommits(const IConventionalCommit::Commits commits) { m_commits = commits; } IConventionalCommit::Commits IConventionalCommit::commits() const { return m_commits; } bool IConventionalCommit::isValid() const { return m_valid; } Error IConventionalCommit::error() const { return m_error; }
17.830189
82
0.731217
Symbitic
f76d5ea071c8410b88c1139fca575396b32afdca
2,018
cpp
C++
modules/paint/actions/bucket_action.cpp
Relintai/pandemonium_engine
3de05db75a396b497f145411f71eb363572b38ae
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
modules/paint/actions/bucket_action.cpp
Relintai/pandemonium_engine
3de05db75a396b497f145411f71eb363572b38ae
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
modules/paint/actions/bucket_action.cpp
Relintai/pandemonium_engine
3de05db75a396b497f145411f71eb363572b38ae
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
/* Copyright (c) 2019 Flairieve Copyright (c) 2020-2022 cobrapitz Copyright (c) 2022 Péter Magyar Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "bucket_action.h" #include "../paint_canvas.h" #include "../paint_canvas_layer.h" #include "../paint_utilities.h" void BucketAction::do_action(PaintCanvas *canvas, const Array &data) { PaintAction::do_action(canvas, data); Vector2i pos = data[0]; Color col = canvas->get_pixel_v(pos); Color col2 = data[2]; if (col == col2) { return; } PoolVector2iArray pixels = canvas->select_same_color(pos.x, pos.y); for (int i = 0; i < pixels.size(); ++i) { Vector2i pixel = pixels[i]; if (undo_cells.contains(pixel)) { continue; } if (canvas->is_alpha_locked() && col.a < 0.00001) { continue; } undo_cells.append(pixel); undo_colors.append(col); canvas->set_pixel_v(pixel, col2); redo_cells.append(pixel); redo_colors.append(col2); } } BucketAction::BucketAction() { } BucketAction::~BucketAction() { } void BucketAction::_bind_methods() { }
27.27027
78
0.745292
Relintai
f76f7e85e16eba7251f8753db7c87381c118c128
4,395
hpp
C++
src/Cuda/Container/Array2DCudaHost.hpp
devshank3/Open3D
91611eb562680a41be8a52497bb45d278f2c9377
[ "MIT" ]
113
2018-11-12T03:32:52.000Z
2022-03-29T13:58:54.000Z
src/Cuda/Container/Array2DCudaHost.hpp
llp45135/Open3D
ff7003d542c4fcf88a2d9e7fe08508b3e52dc702
[ "MIT" ]
3
2018-10-19T12:09:57.000Z
2020-04-22T11:55:54.000Z
src/Cuda/Container/Array2DCudaHost.hpp
llp45135/Open3D
ff7003d542c4fcf88a2d9e7fe08508b3e52dc702
[ "MIT" ]
27
2018-10-16T20:01:18.000Z
2021-07-26T08:02:20.000Z
// // Created by wei on 1/14/19. // #include "Array2DCuda.h" #include <Cuda/Common/UtilsCuda.h> namespace open3d { namespace cuda { template<typename T> Array2DCuda<T>::Array2DCuda() { max_rows_ = max_cols_ = pitch_ = -1; } template<typename T> Array2DCuda<T>::Array2DCuda(int max_rows, int max_cols) { Create(max_rows, max_cols); } template<typename T> Array2DCuda<T>::Array2DCuda(const Array2DCuda<T> &other) { device_ = other.device_; max_rows_ = other.max_rows_; max_cols_ = other.max_cols_; pitch_ = other.pitch_; } template<typename T> Array2DCuda<T> &Array2DCuda<T>::operator=(const Array2DCuda<T> &other) { if (this != &other) { Release(); device_ = other.device_; max_rows_ = other.max_rows_; max_cols_ = other.max_cols_; pitch_ = other.pitch_; } return *this; } template<typename T> Array2DCuda<T>::~Array2DCuda() { Release(); } template<typename T> void Array2DCuda<T>::Create(int max_rows, int max_cols) { assert(max_rows > 0 && max_cols > 0); if (device_ != nullptr) { utility::LogError("[Array2DCuda]: Already created, abort!\n"); return; } device_ = std::make_shared<Array2DCudaDevice<T>>(); max_rows_ = max_rows; max_cols_ = max_cols; size_t pitch_size_t; CheckCuda(cudaMallocPitch(&device_->data_, &pitch_size_t, sizeof(T) * max_cols_, max_rows_)); pitch_ = (int) pitch_size_t; CheckCuda(cudaMalloc(&device_->iterator_rows_, sizeof(int))); CheckCuda(cudaMemset(device_->iterator_rows_, 0, sizeof(int))); UpdateDevice(); } template<typename T> void Array2DCuda<T>::Release() { if (device_ != nullptr && device_.use_count() == 1) { CheckCuda(cudaFree(device_->data_)); CheckCuda(cudaFree(device_->iterator_rows_)); } device_ = nullptr; max_rows_ = max_cols_ = pitch_ = -1; } template<typename T> void Array2DCuda<T>::UpdateDevice() { assert(device_ != nullptr); device_->max_rows_ = max_rows_; device_->max_cols_ = max_cols_; device_->pitch_ = pitch_; } template<typename T> void Array2DCuda<T>::CopyTo(Array2DCuda<T> &other) { assert(device_ != nullptr); if (this == &other) return; if (other.device_ == nullptr) { other.Create(max_rows_, max_cols_); } else if (other.max_rows_ < max_rows_ || other.max_cols_ < max_cols_) { utility::LogError("[Array2DCuda]: Dimension mismatch: ({} {}) vs ({} " "{})\n", other.max_rows_, other.max_cols_, max_rows_, max_cols_); return; } CheckCuda(cudaMemcpy2D(other.device_->data_, other.pitch_, device_->data_, pitch_, sizeof(T) * max_cols_, max_rows_, cudaMemcpyDeviceToDevice)); } template<typename T> void Array2DCuda<T>::Upload(Eigen::Matrix<T, -1, -1, Eigen::RowMajor> &matrix) { if (device_ != nullptr) { assert(matrix.rows() == max_rows_ && matrix.cols() == max_cols_); } else { Create(matrix.rows(), matrix.cols()); } CheckCuda(cudaMemcpy2D(device_->data_, pitch_, matrix.data(), sizeof(T) * max_cols_, sizeof(T) * max_cols_, max_rows_, cudaMemcpyHostToDevice)); } template<typename T> Eigen::Matrix<T, -1, -1, Eigen::RowMajor> Array2DCuda<T>::Download() { Eigen::Matrix<T, -1, -1, Eigen::RowMajor> matrix(max_rows_, max_cols_); CheckCuda(cudaMemcpy2D(matrix.data(), sizeof(T) * max_cols_, device_->data_, pitch_, sizeof(T) * max_cols_, max_rows_, cudaMemcpyDeviceToHost)); return matrix; } template<typename T> void Array2DCuda<T>::Fill(const T &val) {} template<typename T> void Array2DCuda<T>::Memset(int val) { CheckCuda(cudaMemset2D(device_->data_, pitch_, val, sizeof(T) * max_cols_, max_rows_)); } template<typename T> int Array2DCuda<T>::rows() const { int rows; CheckCuda(cudaMemcpy(&rows, device_->iterator_rows_, sizeof(int), cudaMemcpyDeviceToHost)); return rows; } template<typename T> void Array2DCuda<T>::set_iterator_rows(int row_position) { CheckCuda(cudaMemcpy(device_->iterator_rows_, &row_position, sizeof(int), cudaMemcpyHostToDevice)); } } }
27.993631
80
0.622753
devshank3
f7738133bf9137aae741ad00a0af999d084ecfdb
28,509
cpp
C++
StarEngine/jni/Helpers/Helpers.cpp
madhubandubey9/StarEngine
1d0adcf8cfd50bc223be6f333c4f2a0af5260b27
[ "MIT" ]
455
2015-02-04T01:39:12.000Z
2022-03-18T17:28:34.000Z
StarEngine/jni/Helpers/Helpers.cpp
madhubandubey9/StarEngine
1d0adcf8cfd50bc223be6f333c4f2a0af5260b27
[ "MIT" ]
1
2016-12-25T09:14:12.000Z
2016-12-25T14:48:27.000Z
StarEngine/jni/Helpers/Helpers.cpp
madhubandubey9/StarEngine
1d0adcf8cfd50bc223be6f333c4f2a0af5260b27
[ "MIT" ]
117
2015-01-30T10:13:54.000Z
2022-03-08T03:46:42.000Z
#include "Helpers.h" #include "..\Logger.h" #include "FilePath.h" #include <iostream> #include <fstream> #include <string> #include <locale> #include <clocale> #include <vector> #ifdef _WIN32 #include <windows.h> #endif #ifdef ANDROID #include "HelpersAndroid.h" #include "../StarEngine.h" #endif namespace star { const uint32 GenerateHash(const tstring & str) { uint32 hash(0); for(size_t i = 0; i < str.size(); ++i) { hash = 65599 * hash + str[i]; } return hash ^ (hash >> 16); } void LaunchWebpage(const tstring & page) { #ifdef _WIN32 ShellExecute(NULL, _T("open"), page.c_str(), NULL, NULL, SW_SHOWNORMAL); #endif } tstring GetFileName(const tstring & path) { auto index = path.find_last_of('/'); if(index == tstring::npos) { index = path.find_last_of('\\'); } if(index != tstring::npos) { index += 1; return path.substr(index, path.length() - index); } return path; } template <> sstring_16 string_cast<sstring_16, sstring_16> (const sstring_16 & value) { return value; } template <> sstring_16 string_cast<sstring_16, swstring> (const swstring & value) { sstring_16 str(value.begin(), value.end()); return str; } template <> sstring_16 string_cast<sstring_16, sstring> (const sstring & value) { sstring_16 str(value.begin(), value.end()); return str; } template <> swstring string_cast<swstring, sstring_16> (const sstring_16 & value) { swstring str(value.begin(), value.end()); return str; } template <> sstring string_cast<sstring, sstring_16> (const sstring_16 & value) { sstring str(value.begin(), value.end()); return str; } template <> swstring string_cast<swstring, swstring> (const swstring & value) { return value; } template <> sstring string_cast<sstring, sstring> (const sstring & value) { return value; } template <> sstring string_cast<sstring, swstring> (const swstring & value) { sstring str(value.begin(), value.end()); return str; } template <> swstring string_cast<swstring, sstring> (const sstring & value) { swstring str(value.begin(), value.end()); return str; } template <> sstring_16 string_cast<sstring_16, schar_16> (const schar_16 * value) { return sstring_16(value); } template <> sstring_16 string_cast<sstring_16, swchar> (const swchar * value) { return string_cast<sstring_16, swstring>(value); } template <> sstring_16 string_cast<sstring_16, schar> (const schar * value) { return string_cast<sstring_16, sstring>(value); } template <> schar_16 * string_cast<schar_16*, sstring_16> (const sstring_16 & value) { schar_16 * cstr = const_cast<schar_16*>( value.c_str() ); return cstr; } template <> swchar * string_cast<swchar*, sstring_16> (const sstring_16 & value) { swchar * cstr = const_cast<swchar*>( string_cast<swstring, sstring_16>( value ).c_str() ); return cstr; } template <> schar * string_cast<schar*, sstring_16> (const sstring_16 & value) { schar * cstr = const_cast<schar*>( string_cast<sstring, sstring_16>( value ).c_str() ); return cstr; } template <> sstring string_cast<sstring, schar_16> (const schar_16 * value) { return string_cast<sstring, sstring_16>(value); } template <> swstring string_cast<swstring, schar_16> (const schar_16 * value) { return string_cast<swstring, sstring_16>(value); } template <> schar_16* string_cast<schar_16*, sstring> (const sstring & value) { schar_16 * cstr = const_cast<schar_16*>( string_cast<sstring_16, sstring>(value).c_str() ); return cstr; } template <> schar_16* string_cast<schar_16*, swstring> (const swstring & value) { schar_16 * cstr = const_cast<schar_16*>( string_cast<sstring_16, swstring>(value).c_str() ); return cstr; } template <> swstring string_cast<swstring, swchar> (const swchar * value) { return string_cast<swstring, swstring>(value); } template <> sstring string_cast<sstring, schar> (const schar * value) { return string_cast<sstring, sstring>(value); } template <> sstring string_cast<sstring, swchar> (const swchar * value) { return string_cast<sstring, swstring>(value); } template <> swstring string_cast<swstring, schar> (const schar * value) { return string_cast<swstring, sstring>(value); } template <> schar* string_cast<schar*, swstring> (const swstring & value) { schar * result = const_cast<schar*>( string_cast<sstring, swstring>(value).c_str() ); return result; } template <> schar* string_cast<schar*, sstring> (const sstring & value) { schar * result = const_cast<schar*>(value.c_str()); return result; } template <> swchar* string_cast<swchar*, swstring> (const swstring & value) { swchar * result = const_cast<swchar*>(value.c_str()); return result; } template <> swchar* string_cast<swchar*, sstring> (const sstring & value) { swchar * result = const_cast<swchar*>( string_cast<swstring, sstring>(value).c_str() ); return result; } template <> swchar* string_cast<swchar*, schar> (const schar * value) { return string_cast<swchar*>( sstring(value) ); } template <> swchar* string_cast<swchar*, swchar> (const swchar * value) { return const_cast<swchar*>(value); } template <> schar* string_cast<schar*, swchar> (const swchar * value) { return string_cast<schar*>( swstring(value) ); } template <> schar* string_cast<schar*, schar> (const schar * value) { return const_cast<schar*>(value); } template <> schar_16* string_cast<schar_16*, schar> (const schar * value) { return string_cast<schar_16*, sstring>(value); } template <> schar_16* string_cast<schar_16*, swchar> (const swchar * value) { return string_cast<schar_16*, swstring>(value); } template <> schar* string_cast<schar*, schar_16> (const schar_16 * value) { return string_cast<schar*, sstring_16>(value); } template <> swchar* string_cast<swchar*, schar_16> (const schar_16 * value) { return string_cast<swchar*, sstring_16>(value); } template <> tstring string_cast<tstring, fvec2> (const fvec2 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y; return strstr.str(); } template <> tstring string_cast<tstring, pos> (const pos & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.l; return strstr.str(); } template <> tstring string_cast<tstring, fvec3> (const fvec3 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z; return strstr.str(); } template <> tstring string_cast<tstring, fvec4> (const fvec4 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, fquat> (const fquat & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, dvec2> (const dvec2 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y; return strstr.str(); } template <> tstring string_cast<tstring, dvec3> (const dvec3 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z; return strstr.str(); } template <> tstring string_cast<tstring, dvec4> (const dvec4 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, dquat> (const dquat & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, ivec2> (const ivec2 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y; return strstr.str(); } template <> tstring string_cast<tstring, ivec3> (const ivec3 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z; return strstr.str(); } template <> tstring string_cast<tstring, ivec4> (const ivec4 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, uvec2> (const uvec2 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y; return strstr.str(); } template <> tstring string_cast<tstring, uvec3> (const uvec3 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z; return strstr.str(); } template <> tstring string_cast<tstring, uvec4> (const uvec4 & value) { tstringstream strstr; strstr << value.x << _T(";"); strstr << value.y << _T(";"); strstr << value.z << _T(";"); strstr << value.w; return strstr.str(); } template <> tstring string_cast<tstring, Color> (const Color & value) { tstringstream strstr; strstr << value.r << _T(";"); strstr << value.g << _T(";"); strstr << value.b << _T(";"); strstr << value.a; return strstr.str(); } template <> bool string_cast<bool, tstring> (const tstring & value) { tstring val(value); transform(val.begin(), val.end(), val.begin(), ::tolower); return val[0] == _T('t'); } template <> int32 string_cast<int32, tstring> (const tstring & value) { return ttoi(value.c_str()); } template <> uint32 string_cast<uint32, tstring> (const tstring & value) { return uint32(string_cast<int32>(value)); } template <> long string_cast<long, tstring> (const tstring & value) { return static_cast<long>(ttoi(value.c_str())); } template <> float32 string_cast<float32, tstring> (const tstring & value) { return static_cast<float32>(ttof(value.c_str())); } template <> float64 string_cast<float64, tstring> (const tstring & value) { return ttof(value.c_str()); } template <> fvec2 string_cast<fvec2, tstring> (const tstring & value) { fvec2 vec; int32 index = value.find(';',0); vec.x = string_cast<float32>(value.substr(0, index)); vec.y = string_cast<float32>(value.substr(++index,value.size()-index)); return vec; } template <> pos string_cast<pos, tstring> (const tstring & value) { pos pos; int32 index = value.find(';', 0); pos.x = string_cast<float32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); pos.y = string_cast<float32>(value.substr(index, index2 - index)); pos.l = lay(string_cast<int32>(value.substr(++index2, value.size() - index2))); return pos; } template <> fvec3 string_cast<fvec3, tstring> (const tstring & value) { fvec3 vec; int32 index = value.find(';', 0); vec.x = string_cast<float32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<float32>(value.substr(index, index2 - index)); vec.z = string_cast<float32>(value.substr(++index2, value.size() - index2)); return vec; } template <> fvec4 string_cast<fvec4, tstring> (const tstring & value) { fvec4 vec; int32 index = value.find(';', 0); vec.x = string_cast<float32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<float32>(value.substr(index, index2 - index)); index = value.find(';', ++index2); vec.z = string_cast<float32>(value.substr(index2, index - index2)); vec.w = string_cast<float32>(value.substr(++index, value.size() - index)); return vec; } template <> fquat string_cast<fquat, tstring> (const tstring & value) { fquat quat; int32 index = value.find(';', 0); quat.x = string_cast<float32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); quat.y = string_cast<float32>(value.substr(index, index2 - index)); index = value.find(';', ++index2); quat.z = string_cast<float32>(value.substr(index2, index - index2)); quat.w = string_cast<float32>(value.substr(++index, value.size() - index)); return quat; } template <> dvec2 string_cast<dvec2, tstring> (const tstring & value) { dvec2 vec; int32 index = value.find(';', 0); vec.x = string_cast<float64>(value.substr(0, index)); vec.y = string_cast<float64>(value.substr(++index, value.size() - index)); return vec; } template <> dvec3 string_cast<dvec3, tstring> (const tstring & value) { dvec3 vec; int32 index = value.find(';', 0); vec.x = string_cast<float64>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<float64>(value.substr(index, index2 - index)); vec.z = string_cast<float64>(value.substr(++index2, value.size() - index2)); return vec; } template <> dvec4 string_cast<dvec4, tstring> (const tstring & value) { dvec4 vec; int32 index = value.find(';', 0); vec.x = string_cast<float64>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<float64>(value.substr(index, index2 - index)); index = value.find(';', ++index2); vec.z = string_cast<float64>(value.substr(index2, index - index2)); vec.w = string_cast<float64>(value.substr(++index, value.size() - index)); return vec; } template <> dquat string_cast<dquat, tstring> (const tstring & value) { dquat quat; int32 index = value.find(';', 0); quat.x = string_cast<float64>(value.substr(0, index)); int32 index2 = value.find(';', ++index); quat.y = string_cast<float64>(value.substr(index, index2 - index)); index = value.find(';', ++index2); quat.z = string_cast<float64>(value.substr(index2, index - index2)); quat.w = string_cast<float64>(value.substr(++index, value.size() - index)); return quat; } template <> ivec2 string_cast<ivec2, tstring> (const tstring & value) { ivec2 vec; int32 index = value.find(';', 0); vec.x = string_cast<int32>(value.substr(0, index)); vec.y = string_cast<int32>(value.substr(++index ,value.size() - index)); return vec; } template <> ivec3 string_cast<ivec3, tstring> (const tstring & value) { ivec3 vec; int32 index = value.find(';', 0); vec.x = string_cast<int32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<int32>(value.substr(index, index2 - index)); vec.z = string_cast<int32>(value.substr(++index2, value.size() - index2)); return vec; } template <> ivec4 string_cast<ivec4, tstring> (const tstring & value) { ivec4 vec; int32 index = value.find(';', 0); vec.x = string_cast<int32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<int32>(value.substr(index, index2 - index)); index = value.find(';', ++index2); vec.z = string_cast<int32>(value.substr(index2, index - index2)); vec.w = string_cast<int32>(value.substr(++index, value.size() - index)); return vec; } template <> uvec2 string_cast<uvec2, tstring> (const tstring & value) { uvec2 vec; int32 index = value.find(';', 0); vec.x = string_cast<uint32>(value.substr(0, index)); vec.y = string_cast<uint32>(value.substr(++index, value.size() - index)); return vec; } template <> uvec3 string_cast<uvec3, tstring> (const tstring & value) { uvec3 vec; int32 index = value.find(';', 0); vec.x = string_cast<uint32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<uint32>(value.substr(index, index2 - index)); vec.z = string_cast<uint32>(value.substr(++index2, value.size() - index2)); return vec; } template <> uvec4 string_cast<uvec4, tstring> (const tstring & value) { uvec4 vec; int32 index = value.find(';', 0); vec.x = string_cast<uint32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); vec.y = string_cast<uint32>(value.substr(index, index2 - index)); index = value.find(';', ++index2); vec.z = string_cast<uint32>(value.substr(index2, index - index2)); vec.w = string_cast<uint32>(value.substr(++index, value.size() - index)); return vec; } template <> Color string_cast<Color, tstring> (const tstring & value) { Color color; int32 index = value.find(';', 0); color.r = string_cast<float32>(value.substr(0, index)); int32 index2 = value.find(';', ++index); color.g = string_cast<float32>(value.substr(index, index2 - index)); index = value.find(';', ++index2); color.b = string_cast<float32>(value.substr(index2, index - index2)); color.a = string_cast<float32>(value.substr(++index, value.size() - index)); return color; } void ReadTextFile(const tstring & file, tstring & text, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID if(directory == DirectoryMode::assets) { SerializedData data; star_a::ReadFileAsset(file, data); text = string_cast<tstring>(data.data); delete [] data.data; } else { text = _T(""); sifstream myfile; myfile.open(string_cast<sstring>(file_path.GetFullPath()), std::ios::in); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); sstring str; while (std::getline(myfile, str)) { text += str; } myfile.close(); } #else tifstream myfile; myfile.open(file_path.GetFullPath(), std::ios::in); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); tstring str; while (std::getline(myfile,str)) { text += str; } myfile.close(); #endif text += _T('\0'); } bool ReadTextFileSafe(const tstring & file, tstring & text, DirectoryMode directory, bool logWarning) { FilePath file_path = FilePath(file, directory); bool succes(false); #ifdef ANDROID if(directory == DirectoryMode::assets) { SerializedData data; succes = star_a::ReadFileAssetSafe(file, data, logWarning); if(succes) { text = string_cast<tstring>(data.data); delete [] data.data; } else { text = EMPTY_STRING; } return succes; } else { text = EMPTY_STRING; sifstream myfile; myfile.open(string_cast<sstring>(file_path.GetFullPath()), std::ios::in); succes = myfile.is_open(); if(succes) { sstring str; while (std::getline(myfile,str)) { text += str; } myfile.close(); } else if(logWarning) { LOG(LogLevel::Warning, _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); } } #else tifstream myfile; myfile.open(file_path.GetFullPath(), std::ios::in); succes = myfile.is_open(); if(succes) { tstring str; while (std::getline(myfile,str)) { text += str; } myfile.close(); } else if(logWarning) { LOG(LogLevel::Warning, _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); } #endif text += _T('\0'); return succes; } tstring ReadTextFile(const tstring & file, DirectoryMode directory) { tstring text; ReadTextFile(file, text, directory); return text; } void WriteTextFile(const tstring & file, const tstring & text, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID ASSERT_LOG(directory != DirectoryMode::assets, _T("Android doesn't support writing to a text file in the assets directory."), STARENGINE_LOG_TAG); sofstream myfile(string_cast<sstring>(file_path.GetFullPath()), std::ios::out); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); myfile << text; myfile.close(); #else tofstream myfile(file_path.GetFullPath(), std::ios::out); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); myfile << text; myfile.close(); #endif } void AppendTextFile(const tstring & file, const tstring & text, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID ASSERT_LOG(directory != DirectoryMode::assets, _T("Android doesn't support writing to a text file in the assets directory."), STARENGINE_LOG_TAG); sofstream myfile(string_cast<sstring>(file_path.GetFullPath()), std::ios::out | std::ios::app); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); myfile << text; myfile.close(); #else tofstream myfile(file_path.GetFullPath(), std::ios::out | std::ios::app); ASSERT_LOG(myfile.is_open(), _T("Couldn't open the text file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); myfile << text; myfile.close(); #endif } schar * ReadBinaryFile(const tstring & file, uint32 & size, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID if(directory == DirectoryMode::assets) { SerializedData data; star_a::ReadFileAsset(file, data); size = data.size; return data.data; } else { sifstream binary_file; binary_file.open(string_cast<sstring>(file_path.GetFullPath()).c_str(), std::ios::in | std::ios::binary | std::ios::ate); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); schar * buffer(nullptr); size = uint32(binary_file.tellg()); buffer = new schar[size]; binary_file.seekg(0, std::ios::beg); binary_file.read(buffer, sizeof(schar) * size); binary_file.close(); return buffer; } #else sifstream binary_file; binary_file.open(file_path.GetFullPath(), std::ios::in | std::ios::binary | std::ios::ate); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); schar * buffer(nullptr); size = uint32(binary_file.tellg()); buffer = new schar[size]; binary_file.seekg(0, std::ios::beg); binary_file.read(buffer, sizeof(schar) * size); binary_file.close(); return buffer; #endif } bool ReadBinaryFileSafe(const tstring & file, schar *& buffer, uint32 & size, DirectoryMode directory, bool logWarning) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID if(directory == DirectoryMode::assets) { SerializedData data; bool result = star_a::ReadFileAssetSafe(file, data, logWarning); size = data.size; buffer = data.data; return result; } else { sifstream binary_file; binary_file.open(string_cast<sstring>(file_path.GetFullPath()).c_str(), std::ios::in | std::ios::binary | std::ios::ate); bool succes = binary_file.is_open(); if (succes) { size = uint32(binary_file.tellg()); buffer = new schar[size]; binary_file.seekg(0, std::ios::beg); binary_file.read(buffer, sizeof(schar) * size); binary_file.close(); } else if(logWarning) { LOG(LogLevel::Warning, _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); } return succes; } #else sifstream binary_file; binary_file.open(file_path.GetFullPath(), std::ios::in | std::ios::binary | std::ios::ate); bool succes = binary_file.is_open(); if (succes) { size = uint32(binary_file.tellg()); buffer = new schar[size]; binary_file.seekg(0, std::ios::beg); binary_file.read(buffer, sizeof(schar) * size); binary_file.close(); } else if(logWarning) { LOG(LogLevel::Warning, _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); } return succes; #endif } void WriteBinaryFile(const tstring & file, schar * buffer, uint32 size, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID ASSERT_LOG(directory != DirectoryMode::assets, _T("Android doesn't support writing to a binary file in the assets directory."), STARENGINE_LOG_TAG); sofstream binary_file; binary_file.open(string_cast<sstring>(file_path.GetFullPath()), std::ios::binary | std::ios::trunc); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); for(uint32 i = 0 ; i < size ; ++i) { binary_file << buffer[i]; } binary_file.close(); #else sofstream binary_file; binary_file.open(file_path.GetFullPath(), std::ios::binary | std::ios::trunc); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); for(uint32 i = 0 ; i < size ; ++i) { binary_file << buffer[i]; } binary_file.close(); #endif } void AppendBinaryFile(const tstring & file, schar * buffer, uint32 size, DirectoryMode directory) { FilePath file_path = FilePath(file, directory); #ifdef ANDROID ASSERT_LOG(directory != DirectoryMode::assets, _T("Android doesn't support writing to a binary file in the assets directory."), STARENGINE_LOG_TAG); sofstream binary_file(string_cast<sstring>(file_path.GetFullPath()), std::ios::out | std::ios::binary | std::ios::app); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); for(uint32 i = 0 ; i < size ; ++i) { binary_file << buffer[i]; } binary_file.close(); #else sofstream binary_file(file_path.GetFullPath(), std::ios::out | std::ios::binary | std::ios::app); ASSERT_LOG(binary_file.is_open(), _T("Couldn't open the binary file '") + file_path.GetFullPath() + _T("'."), STARENGINE_LOG_TAG); for(uint32 i = 0 ; i < size ; ++i) { binary_file << buffer[i]; } binary_file.close(); #endif } schar * DecryptBinaryFile(const tstring & file, uint32 & size, const std::function<schar*(const schar*, uint32&)> & decrypter, DirectoryMode directory) { schar * buffer = ReadBinaryFile(file, size, directory); schar * decryptedBuffer = decrypter(buffer, size); delete [] buffer; return decryptedBuffer; } bool DecryptBinaryFileSafe(const tstring & file, schar *& buffer, uint32 & size, const std::function<schar*(const schar*, uint32&)> & decrypter, DirectoryMode directory, bool logWarning) { schar * tempBuffer(nullptr); bool result = ReadBinaryFileSafe(file, tempBuffer, size, directory, logWarning); if(result) { buffer = decrypter(tempBuffer, size); if(tempBuffer != nullptr) { delete [] buffer; } } return result; } void EncryptBinaryFile(const tstring & file, schar * buffer, uint32 size, const std::function<schar*(const schar*, uint32&)> & encrypter, DirectoryMode directory) { schar * encryptedBuffer = encrypter(buffer, size); WriteBinaryFile(file, encryptedBuffer, size, directory); delete [] encryptedBuffer; } }
24.366667
98
0.627837
madhubandubey9
f773d8954bf9f8e6fb62b9055d5df53a3eaa91ad
10,893
cpp
C++
Source/Urho3D/Scene/CameraViewport.cpp
vinhig/rbfx
884de45c623d591f346a2abd5e52edaa84bcc137
[ "MIT" ]
441
2018-12-26T14:50:23.000Z
2021-11-05T03:13:27.000Z
Source/Urho3D/Scene/CameraViewport.cpp
vinhig/rbfx
884de45c623d591f346a2abd5e52edaa84bcc137
[ "MIT" ]
221
2018-12-29T17:40:23.000Z
2021-11-06T21:41:55.000Z
Source/Urho3D/Scene/CameraViewport.cpp
vinhig/rbfx
884de45c623d591f346a2abd5e52edaa84bcc137
[ "MIT" ]
101
2018-12-29T13:08:10.000Z
2021-11-02T09:58:37.000Z
// // Copyright (c) 2017-2020 the rbfx project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include <EASTL/sort.h> #include "../Core/CoreEvents.h" #include "../Core/StringUtils.h" #include "../Engine/PluginApplication.h" #include "../Graphics/Camera.h" #include "../Graphics/Graphics.h" #include "../Graphics/RenderPath.h" #include "../IO/FileSystem.h" #include "../IO/Log.h" #include "../Resource/ResourceCache.h" #include "../Resource/XMLFile.h" #include "../Scene/CameraViewport.h" #include "../Scene/Node.h" #include "../Scene/Scene.h" #include "../Scene/SceneEvents.h" namespace Urho3D { static ResourceRef defaultRenderPath{XMLFile::GetTypeStatic(), "RenderPaths/Forward.xml"}; CameraViewport::CameraViewport(Context* context) : Component(context) , viewport_(context->CreateObject<Viewport>()) , rect_(fullScreenViewport) , renderPath_(defaultRenderPath) , screenRect_{0, 0, 1920, 1080} { if (Graphics* graphics = context_->GetSubsystem<Graphics>()) screenRect_ = {0, 0, graphics->GetWidth(), graphics->GetHeight()}; } void CameraViewport::SetNormalizedRect(const Rect& rect) { rect_ = rect; IntRect viewportRect( static_cast<int>(screenRect_.Left() + screenRect_.Width() * rect.Left()), static_cast<int>(screenRect_.Top() + screenRect_.Height() * rect.Top()), static_cast<int>(screenRect_.Left() + screenRect_.Width() * rect.Right()), static_cast<int>(screenRect_.Top() + screenRect_.Height() * rect.Bottom()) ); viewport_->SetRect(viewportRect); using namespace CameraViewportResized; VariantMap args{}; args[P_VIEWPORT] = GetViewport(); args[P_CAMERA] = GetViewport()->GetCamera(); args[P_SIZE] = viewportRect; args[P_SIZENORM] = rect; SendEvent(E_CAMERAVIEWPORTRESIZED, args); } void CameraViewport::RegisterObject(Context* context) { context->RegisterFactory<CameraViewport>("Scene"); } void CameraViewport::OnNodeSet(Node* node) { if (node == nullptr) viewport_->SetCamera(nullptr); else { SubscribeToEvent(node, E_COMPONENTADDED, [this](StringHash, VariantMap& args) { using namespace ComponentAdded; if (Component* component = static_cast<Component*>(args[P_COMPONENT].GetPtr())) { if (Camera* camera = component->Cast<Camera>()) { viewport_->SetCamera(camera); camera->SetViewMask(camera->GetViewMask() & ~(1U << 31U)); // Do not render last layer. } } }); SubscribeToEvent(node, E_COMPONENTREMOVED, [this](StringHash, VariantMap& args) { using namespace ComponentRemoved; if (Component* component = static_cast<Component*>(args[P_COMPONENT].GetPtr())) { if (component->GetType() == Camera::GetTypeStatic()) viewport_->SetCamera(nullptr); } }); if (Camera* camera = node->GetComponent<Camera>()) { viewport_->SetCamera(camera); camera->SetViewMask(camera->GetViewMask() & ~(1U << 31U)); // Do not render last layer. } else { // If this node does not have a camera - get or create it on next frame. This is required because Camera may // be created later when deserializing node. SubscribeToEvent(E_BEGINFRAME, [this](StringHash, VariantMap& args) { if (Node* node = GetNode()) { if (Camera* camera = node->GetOrCreateComponent<Camera>()) { viewport_->SetCamera(camera); camera->SetViewMask(camera->GetViewMask() & ~(1U << 31U)); // Do not render last layer. } } UnsubscribeFromEvent(E_BEGINFRAME); }); } } } void CameraViewport::OnSceneSet(Scene* scene) { viewport_->SetScene(scene); } IntRect CameraViewport::GetScreenRect() const { return screenRect_; } const ea::vector<AttributeInfo>* CameraViewport::GetAttributes() const { if (attributesDirty_) const_cast<CameraViewport*>(this)->RebuildAttributes(); return &attributes_; } template<typename T> AttributeInfo& CameraViewport::RegisterAttribute(const AttributeInfo& attr) { attributes_.push_back(attr); return attributes_.back(); } void CameraViewport::RebuildAttributes() { auto* context = this; // Normal attributes. URHO3D_ACCESSOR_ATTRIBUTE("Viewport", GetNormalizedRect, SetNormalizedRect, Rect, fullScreenViewport, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("RenderPath", GetLastRenderPath, SetRenderPath, ResourceRef, defaultRenderPath, AM_DEFAULT); // PostProcess effects are special. One file may contain multiple effects that can be enabled or disabled. { effects_.clear(); for (const auto& dir: context_->GetSubsystem<ResourceCache>()->GetResourceDirs()) { ea::vector<ea::string> effects; ea::string resourcePath = "PostProcess/"; ea::string scanDir = AddTrailingSlash(dir) + resourcePath; context_->GetSubsystem<FileSystem>()->ScanDir(effects, scanDir, "*.xml", SCAN_FILES, false); for (const auto& effectFileName: effects) { auto effectPath = resourcePath + effectFileName; auto* effect = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(effectPath); auto root = effect->GetRoot(); ea::string tag; for (auto command = root.GetChild("command"); command.NotNull(); command = command.GetNext("command")) { tag = command.GetAttribute("tag"); if (tag.empty()) { URHO3D_LOGWARNING("Invalid PostProcess effect with empty tag"); continue; } if (effects_.find(tag) != effects_.end()) continue; effects_[tag] = resourcePath + effectFileName; } } } StringVector tags = effects_.keys(); ea::quick_sort(tags.begin(), tags.end()); for (auto& effect : effects_) { auto getter = [this, &effect](const CameraViewport&, Variant& value) { if (RenderPath* renderPath = viewport_->GetRenderPath()) value = renderPath->IsEnabled(effect.first); else value = false; }; auto setter = [this, &effect](const CameraViewport&, const Variant& value) { RenderPath* path = viewport_->GetRenderPath(); if (!path) return; if (!path->IsAdded(effect.first)) path->Append(context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(effect.second)); path->SetEnabled(effect.first, value.GetBool()); }; URHO3D_CUSTOM_ACCESSOR_ATTRIBUTE(effect.first.c_str(), getter, setter, bool, false, AM_DEFAULT); } } attributesDirty_ = false; } RenderPath* CameraViewport::RebuildRenderPath() { if (!viewport_) return nullptr; SharedPtr<RenderPath> oldRenderPath(viewport_->GetRenderPath()); if (XMLFile* renderPathFile = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(renderPath_.name_)) { viewport_->SetRenderPath(renderPathFile); RenderPath* newRenderPath = viewport_->GetRenderPath(); for (const auto& effect : effects_) { if (oldRenderPath->IsEnabled(effect.first)) { if (!newRenderPath->IsAdded(effect.first)) newRenderPath->Append(context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(effect.second)); newRenderPath->SetEnabled(effect.first, true); } } return newRenderPath; } return nullptr; } void CameraViewport::SetRenderPath(const ResourceRef& renderPathResource) { if (!viewport_ || !context_->GetSubsystem<Graphics>()) return; if (!renderPathResource.name_.empty() && renderPathResource.type_ != XMLFile::GetTypeStatic()) { URHO3D_LOGWARNINGF("Incorrect RenderPath file '%s' type.", renderPathResource.name_.c_str()); return; } SharedPtr<RenderPath> oldRenderPath(viewport_->GetRenderPath()); const ea::string& renderPathFileName = renderPathResource.name_.empty() ? defaultRenderPath.name_ : renderPathResource.name_; if (XMLFile* renderPathFile = context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(renderPathFileName)) { if (!viewport_->SetRenderPath(renderPathFile)) { URHO3D_LOGERRORF("Loading renderpath from %s failed. File probably is not a renderpath.", renderPathFileName.c_str()); return; } RenderPath* newRenderPath = viewport_->GetRenderPath(); for (const auto& effect : effects_) { if (oldRenderPath->IsEnabled(effect.first)) { if (!newRenderPath->IsAdded(effect.first)) newRenderPath->Append(context_->GetSubsystem<ResourceCache>()->GetResource<XMLFile>(effect.second)); newRenderPath->SetEnabled(effect.first, true); } } renderPath_.name_ = renderPathFileName; } else { URHO3D_LOGERRORF("Loading renderpath from %s failed. File is missing or you have no permissions to read it.", renderPathFileName.c_str()); } } void CameraViewport::UpdateViewport() { SetNormalizedRect(GetNormalizedRect()); } }
36.069536
129
0.623061
vinhig
f777337c6d45ab6c2c4ba104b4d345eb58a51e70
4,613
cpp
C++
3C1V_Donkey_Kong/DonkeyKong_Solution/Source/ModuleEnemies.cpp
unaidiaz/pryecto1
aa074c32587e8207cb89d6634391bb43aa9a4657
[ "BSD-3-Clause" ]
2
2020-05-20T15:48:29.000Z
2020-08-17T03:35:56.000Z
3C1V_Donkey_Kong/DonkeyKong_Solution/Source/ModuleEnemies.cpp
unaidiaz/proyecto1
aa074c32587e8207cb89d6634391bb43aa9a4657
[ "BSD-3-Clause" ]
null
null
null
3C1V_Donkey_Kong/DonkeyKong_Solution/Source/ModuleEnemies.cpp
unaidiaz/proyecto1
aa074c32587e8207cb89d6634391bb43aa9a4657
[ "BSD-3-Clause" ]
null
null
null
#include "ModuleEnemies.h" #include "Application.h" #include"ModulePlayer.h" #include "ModuleRender.h" #include "ModuleTextures.h" #include "ModuleAudio.h" #include "SceneLevel4.h" #include"Enemy_Barril.h" #include"Enemy_Barrilazul.h" #include "Enemy.h" #include "Enemy_Llama.h" #include "Enemy_Kong.h" #include "muelle.h" #include "SDL/include/SDL.h" #include "SDL_image/include/SDL_image.h" #include<time.h> #pragma comment( lib, "SDL_image/libx86/SDL2_image.lib" ) #define SPAWN_MARGIN 50 ModuleEnemies::ModuleEnemies(bool startEnabled) : Module(startEnabled) { for (uint i = 0; i < MAX_ENEMIES; ++i) enemies[i] = nullptr; } ModuleEnemies::~ModuleEnemies() { } bool ModuleEnemies::Start() { enemigos = App->textures->Load("Assets/objetosanimados.png"); kongs = App->textures->Load("Assets/sprites.png"); enemyDestroyedFx = App->audio->LoadFx("Assets/8. SFX (Kill).wav"); return true; } update_status ModuleEnemies::PreUpdate() { // Remove all enemies scheduled for deletion for (int i = 0; i < MAX_ENEMIES; i++) { if (enemies[i] != nullptr && enemies[i]->pendientedeelim == true) { delete enemies[i]; enemies[i] = nullptr; } } return update_status::UPDATE_CONTINUE; } update_status ModuleEnemies::Update() { HandleEnemiesSpawn(); for (uint i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] != nullptr) enemies[i]->Update(); } HandleEnemiesDespawn(); return update_status::UPDATE_CONTINUE; } update_status ModuleEnemies::PostUpdate() { for (uint i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] != nullptr) enemies[i]->Draw(); } return update_status::UPDATE_CONTINUE; } // Called before quitting bool ModuleEnemies::CleanUp() { LOG("Freeing all enemies"); App->textures->Unload(kongs); App->textures->Unload(enemigos); for (int i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] != nullptr) { delete enemies[i]; enemies[i] = nullptr; } } return true; } bool ModuleEnemies::AddEnemy(Enemy_Type type, int x, int y,int direccion) { bool ret = false; for (uint i = 0; i < MAX_ENEMIES; ++i) { if (spawnQueue[i].type == Enemy_Type::NO_TYPE) { spawnQueue[i].type = type; spawnQueue[i].x = x; spawnQueue[i].y = y; spawnQueue[i].direccion = direccion; ret = true; break; } } return ret; } void ModuleEnemies::HandleEnemiesSpawn() { // Iterate all the enemies queue for (int i = 0; i < MAX_ENEMIES; i++) { if (spawnQueue[i].type != Enemy_Type::NO_TYPE) { SpawnEnemy(spawnQueue[i]); spawnQueue[i].type = Enemy_Type::NO_TYPE; // Removing the newly spawned enemy from the queue } } } void ModuleEnemies::HandleEnemiesDespawn() { // Iterate existing enemies for (int i = 0; i < MAX_ENEMIES; i++) { if (enemies[i] != nullptr&&enemies[i]->pendientedeelim==true) { delete enemies[i]; enemies[i] = nullptr; } } } void ModuleEnemies::SpawnEnemy(const EnemySpawnpoint& info) { // Find an empty slot in the enemies array for (uint i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] == nullptr) { switch (info.type) { case Enemy_Type::LLAMA: enemies[i] = new Enemy_Llama(info.x, info.y, info.direccion); enemies[i]->enemigo = enemigos; enemies[i]->destroyedFx = enemyDestroyedFx; break; case Enemy_Type::KONG: enemies[i] = new Enemy_Kong(info.x, info.y, info.direccion); enemies[i]->kong = kongs; enemies[i]->destroyedFx = enemyDestroyedFx; break; case Enemy_Type::barril: enemies[i] = new Enemybarril(info.x, info.y, info.direccion); enemies[i]->barriltext = enemigos; enemies[i]->destroyedFx = enemyDestroyedFx; break; case Enemy_Type::barrilazul: enemies[i] = new Enemybarrilazul(info.x, info.y, info.direccion); enemies[i]->barriltext = enemigos; enemies[i]->destroyedFx = enemyDestroyedFx; break; case Enemy_Type::MUELLE: enemies[i] = new Muelle(info.x, info.y, info.direccion); enemies[i]->muelles = enemigos; enemies[i]->destroyedFx = enemyDestroyedFx; break; } break; } } } void ModuleEnemies::OnCollision(Collider* c1, Collider* c2) { for (uint i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] != nullptr) { if (c1->type == c1->Enemigo && c2->type == c2->martillo) { if (c1 == enemies[i]->GetCollider()) { App->audio->PlayFx(App->enemies->enemyDestroyedFx);//Notify the enemy of a collision enemies[i]->destr(); break; } } else { enemies[i]->OnCollision(c1, c2); } } } } bool ModuleEnemies::compene() { for (int i = 0; i < MAX_ENEMIES; i++) { if (enemies[i] != nullptr) { return false; } } return true; }
20.686099
95
0.656406
unaidiaz
f77a0206d669785a0f6b7d2be5174d9d9277d9de
2,728
hpp
C++
app/Snapper.hpp
isonil/survival
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
[ "MIT" ]
1
2017-05-12T10:12:41.000Z
2017-05-12T10:12:41.000Z
app/Snapper.hpp
isonil/Survival
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
[ "MIT" ]
null
null
null
app/Snapper.hpp
isonil/Survival
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
[ "MIT" ]
1
2019-01-09T04:05:36.000Z
2019-01-09T04:05:36.000Z
#ifndef APP_SNAPPER_HPP #define APP_SNAPPER_HPP #include "engine/util/Vec3.hpp" #include <array> namespace app { class Structure; class StructureDef; class Snapper { public: static std::vector <std::pair <engine::FloatVec3, engine::FloatVec3>> trySnap(const Structure &first, const StructureDef &secondDef, const engine::FloatVec3 &designatedPos); private: static std::vector <std::pair <engine::FloatVec3, engine::FloatVec3>> floorToFloor(const engine::FloatVec3 &firstSize, const engine::FloatVec3 &secondSize, const engine::FloatVec3 &designatedPos, const Structure &first, const engine::FloatVec3 &secondPosOffset); static std::vector <std::pair <engine::FloatVec3, engine::FloatVec3>> wallToWall(const engine::FloatVec3 &firstSize, const engine::FloatVec3 &secondSize, const engine::FloatVec3 &designatedPos, const Structure &first, const engine::FloatVec3 &secondPosOffset); static std::vector <std::pair <engine::FloatVec3, engine::FloatVec3>> floorToWall(const engine::FloatVec3 &firstSize, const engine::FloatVec3 &secondSize, const engine::FloatVec3 &designatedPos, const Structure &first, const engine::FloatVec3 &secondPosOffset); static std::vector <std::pair <engine::FloatVec3, engine::FloatVec3>> wallToFloor(const engine::FloatVec3 &firstSize, const engine::FloatVec3 &secondSize, const engine::FloatVec3 &designatedPos, const Structure &first, const engine::FloatVec3 &secondPosOffset); static engine::FloatVec3 relPosToWorldPos(const engine::FloatVec3 &relPos, const Structure &structure); template <std::size_t N> static std::vector <int> getBestHotspots(const engine::FloatVec3 &pos, const Structure &structure, const std::array <engine::FloatVec3, N> &hotspots); }; template <std::size_t N> std::vector <int> Snapper::getBestHotspots(const engine::FloatVec3 &pos, const Structure &structure, const std::array <engine::FloatVec3, N> &hotspots) { int minIndex{-1}; float minDist{}; int minSecondIndex{-1}; float minSecondDist{}; for(size_t i = 0; i < hotspots.size(); ++i) { const auto &inWorldPos = relPosToWorldPos(hotspots[i], structure); float dist{pos.getDistanceSq(inWorldPos)}; if(dist < minDist || minIndex < 0) { minSecondIndex = minIndex; minSecondDist = minDist; minIndex = i; minDist = dist; } else if(dist < minSecondDist || minSecondIndex < 0) { minSecondIndex = i; minSecondDist = dist; } } std::vector <int> ret; if(minIndex >= 0) ret.push_back(minIndex); if(minSecondIndex >= 0) ret.push_back(minSecondIndex); return ret; } } // namespace app #endif // APP_SNAPPER_HPP
40.117647
266
0.707845
isonil
f77bb556134507b59a45195ee52fbe40e52db717
1,131
cpp
C++
apple-1-replica/emulator/streamin.cpp
paulscottrobson/assorted-archives
87ce21ef1556bed441fffbb5c4c3c11c06324385
[ "MIT" ]
null
null
null
apple-1-replica/emulator/streamin.cpp
paulscottrobson/assorted-archives
87ce21ef1556bed441fffbb5c4c3c11c06324385
[ "MIT" ]
null
null
null
apple-1-replica/emulator/streamin.cpp
paulscottrobson/assorted-archives
87ce21ef1556bed441fffbb5c4c3c11c06324385
[ "MIT" ]
1
2020-01-02T13:54:19.000Z
2020-01-02T13:54:19.000Z
// ******************************************************************************************************************************* // ******************************************************************************************************************************* // // Name: streamin.cpp // Purpose: Input Stream for Emulator programs. // Created: 20th October 2015 // Author: Paul Robson (paul@robsons.org.uk) // // ******************************************************************************************************************************* // ******************************************************************************************************************************* #include <stdio.h> #include "sys_processor.h" FILE *fStream; static const char *fileName = NULL; void IOSetStreamFile(char *name) { fileName = name; } BYTE8 IOIsStreamLoading(void) { return fileName != NULL; } BYTE8 IOReadInputStream(void) { if (fileName == NULL) return 0; if (fStream == NULL) fStream = fopen(fileName,"r"); if (fStream == NULL || feof(fStream)) { fileName = NULL; return 0; } BYTE8 c = fgetc(fStream); return c; }
31.416667
130
0.362511
paulscottrobson
f77ff8aa7082cd461fe2b307bd8f25f60a792a47
6,971
cpp
C++
modules/web/fcgiCHAT.cpp
omnidynmc/openapi
7c28179859125efb8c945d0c44543194e6bcd09f
[ "MIT" ]
null
null
null
modules/web/fcgiCHAT.cpp
omnidynmc/openapi
7c28179859125efb8c945d0c44543194e6bcd09f
[ "MIT" ]
null
null
null
modules/web/fcgiCHAT.cpp
omnidynmc/openapi
7c28179859125efb8c945d0c44543194e6bcd09f
[ "MIT" ]
null
null
null
#include <fcgi_stdio.h> #include <list> #include <fstream> #include <queue> #include <cstdlib> #include <cstdio> #include <cstring> #include <new> #include <iostream> #include <string> #include <exception> #include <stdio.h> #include <unistd.h> #include <time.h> #include <mysql++.h> #include <openframe/openframe.h> #include "App.h" #include "EarthTools.h" #include "DBI_Web.h" #include "Tag.h" #include "Web.h" #include "webCommands.h" namespace modweb { using namespace mysqlpp; /************************************************************************** ** fcgiCHAT Class ** **************************************************************************/ bool isValidCallsign(const std::string &callsign) { openframe::StringTool::regexMatchListType rl; return openframe::StringTool::ereg("^([a-zA-Z0-9]{2,6})([-]{1}[0-9]+)?[*]*$", callsign, rl) > 0; } // isValidCallsign const int fcgiCHAT::Execute(COMMAND_ARGUMENTS) { openapi::App_Log *log = static_cast<openapi::App_Log *>( ePacket->getVariable("log") ); openframe::StringTool::regexMatchListType rl; openframe::Url *u = (openframe::Url *) ePacket->getVariable("url"); map<string, double> stats; openframe::Stopwatch sw_total; sw_total.Start(); // check for broken implementation if (!u->exists("chat_sequence")) return CMDERR_SYNTAX; std::string chat_sequence = (*u)["chat_sequence"]; bool ok = openframe::StringTool::ereg("^([0-9]+)$", chat_sequence, rl); if (!ok) { FCGI_printf("# ERROR: invalid chat sequence\n"); return CMDERR_SYNTAX; } // if openframe::Stopwatch sw; sw.Start(); // grab next chat sequence mysqlpp::StoreQueryResult res; ok = web->dbi_w()->get("getNextChatSeq", res); unsigned int next_sequence = 0; if (ok) next_sequence = atoi( res[0]["sequence"].c_str() ); stats["next_seq"] = sw.Time(); // process nick/ip std::string nick = u->exists("nick") ? (*u)["nick"] : ""; std::string ip = ePacket->getString("request.remote.addr"); bool is_user_call_valid = isValidCallsign(nick); if (!is_user_call_valid) { ok = openframe::StringTool::ereg("^([0-9]{1,3}[.][0-9]{1,3}[.])[0-9]{1,3}[.][0-9]{1,3}", ip, rl); if (!ok) return CMDERR_SYNTAX; nick = "[" + rl[1].matchString + "*]"; } // if sw.Start(); // process session if there std::string hash = u->exists("session") ? (*u)["session"] : ""; std::string timezone = u->exists("timezone") ? (*u)["timezone"] : "unknown"; std::string idle = u->exists("idle") && (*u)["idle"].length() ? (*u)["idle"] : "0"; ok = openframe::StringTool::ereg("^([0-9a-zA-Z]{32})$", hash, rl); if (ok) { web->dbi_w()->set("setWebWho", hash, "openapi", ip, nick, timezone, "0", idle); } // if else FCGI_printf("# ERROR: invalid or missing hash\n"); stats["set_who"] = sw.Time(); sw.Start(); // handle chat insertion std::string message = u->exists("message") ? (*u)["message"] : ""; if (is_user_call_valid && message.length()) { bool inserted = web->dbi_w()->set("setChat", ip, nick, message, stringify<unsigned int>(next_sequence) ); if (inserted) ++next_sequence; } // if else FCGI_printf("# ERROR: could not insert message, missing or invalid nick\n"); stats["set_chat"] = sw.Time(); sw.Start(); // get current sequence ok = web->dbi_r()->get("getChatBySequence", res, chat_sequence); if (ok) { for(DBI_Web::resultSizeType i=res.num_rows() - 1; ; i--) { openframe::Vars v; v.add("TY", "CH"); v.add("NK", res[i]["nick"].c_str()); v.add("MS", res[i]["message"].c_str()); v.add("SQ", res[i]["sequence"].c_str()); v.add("DT", res[i]["post_date"].c_str()); FCGI_printf("%s\n", v.compile().c_str()); if (i == 0) break; } // for } // if stats["get_chat"] = sw.Time(); sw.Start(); // process web who time_t active_ts = time(NULL) - 60; DBI_Web::resultSizeType num_users = web->dbi_r()->get("getWhoByTime", res, stringify<time_t>(active_ts) ); size_t hidden_count = 0; if (num_users) { for(DBI_Web::resultSizeType i=0; i < res.num_rows(); i++) { openframe::Vars v; v.add("TY", "OL"); time_t idle = atoi( res[i]["idle"].c_str() ); std::string css_class; if (idle < 300) { v.add("ISI", "0"); css_class = "chatHere"; } // if else { v.add("ISI", "1"); css_class = "chatIdle"; } // else std::stringstream url; std::string nick = openframe::Vars::Urlencode( res[i]["nick"].c_str(), false ); bool is_call_valid = isValidCallsign(res[i]["nick"].c_str() ); int count = atoi( res[i]["count"].c_str() ); if (is_call_valid) { url << "<span class=\"" << css_class << "\"><a " << "href=\"javascript:changeFieldById(\'openaprs_form_chat_message\',\'" << nick << ", \')\">" << nick << "</a>"; if (count > 1) url << " (" << count << ")"; url << "</span>"; } // if else { url << "<span class=\"" << css_class << "\">" << nick; if (count > 1) url << " (" << count << ")"; url << "</span>"; hidden_count++; } // if v.add("URL", url.str()); v.add("NK", nick); v.add("IDL", res[i]["idle"].c_str() ); FCGI_printf("%s\n", v.compile().c_str()); } //for } // if openframe::Vars v; v.add("TY", "ST"); v.add("NU", stringify<DBI_Web::resultSizeType>(num_users) ); v.add("HC", stringify<size_t>(hidden_count) ); v.add("SQ", stringify<unsigned int>(next_sequence) ); FCGI_printf("%s\n", v.compile().c_str()); stats["get_who"] = sw.Time(); stats["total"] = sw_total.Time(); std::stringstream s; s << std::fixed << std::setprecision(0) << "stats chat " << "seq " << (stats["next_seq"]*1000) << "ms" << ", who " << (stats["set_who"]*1000) << "ms" << ", post " << (stats["set_chat"]*1000) << "ms" << ", msgs " << (stats["get_chat"]*1000) << "ms" << ", whos " << (stats["get_who"]*1000) << "ms" << ", total " << (stats["total"]*1000) << "ms"; if (stats["total"] > 2.0) log->warn(s.str()); else log->info(s.str()); FCGI_printf("# Total getNextChatSeq %0.5fs\n", stats["next_seq"]); FCGI_printf("# Total setWho %0.5fs\n", stats["set_who"]); FCGI_printf("# Total setChat %0.5fs\n", stats["set_chat"]); FCGI_printf("# Total getChatBySequence %0.5fs\n", stats["get_chat"]); FCGI_printf("# Total %0.5f\n", sw_total.Time()); return CMDERR_SUCCESS; } // fcgiCHAT::Execute } // namespace modweb
32.273148
111
0.527901
omnidynmc
f7808a8aed1c5554630a1b3ad6cf8931cd32b74d
101,639
cpp
C++
SAVE/i2cbus.cpp
Kochise/parai2c
998457e85d0252dd6423efff94817445e5d77406
[ "MIT" ]
null
null
null
SAVE/i2cbus.cpp
Kochise/parai2c
998457e85d0252dd6423efff94817445e5d77406
[ "MIT" ]
null
null
null
SAVE/i2cbus.cpp
Kochise/parai2c
998457e85d0252dd6423efff94817445e5d77406
[ "MIT" ]
null
null
null
/******************************************************************************/ /* @F_NAME: i2cbus.cpp */ /* @F_PURPOSE: C++ I2C bus control manager (on parallel port) */ /* @F_CREATED_BY: D. KOCH (david.koch@libertysurf.fr) */ /* @F_CREATION_DATE: 2000/04/21 */ /* @F_MODIFIED_BY: D. KOCH (david.koch@libertysurf.fr) */ /* @F_MODIFICATION_DATE: 2001/11/23 - programmersheaven special version */ /* @F_LANGUAGE : ANSI C++ */ /* @F_MPROC_TYPE: ALL COMPUTER WITH PC-LIKE MAPPED PARALLEL DATA PORT */ /***** (C) Copyright 2001 Programmer's Heaven (info@programmersheaven.com) ****/ // IF your compiler encounter some troubles due to the comment frame's pattern, // just look for all ... and replace them by ... (JUST characters in brakets) ! // 1 : '/\' '**' // 2 : '/*\*' '/***' // 3 : '*/*/' '***/' // 4 : '/*\ ' '/* ' // 5 : '/*/ ' '/* ' // 6 : ' /*/' ' */' // 7 : ' \*/' ' */' /*/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\*/ /*\ A great thank for all who sent me any comment, GOOD or BAD... /*/ /*/ I changed many things, especialy the names of functions and variables ! \*/ /*\ I also changed the typing structure of the code, NOT the code structure /*/ /*/ itselves, in order to make it 'more readable' (see the IFs and RETURNs). \*/ /*\ /*/ /*/ THIS FILE ONLY COMPILE WITH BORLAND TURBO C++ (Visual C++ doesn't works) \*/ /*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*/ /*/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\*/ /*\ INFORMATIONS (SOME KINDA) /*/ /*/ \*/ /*\ ======================================================================== /*/ /*/ \*/ /*\ PARALLEL PORT AND CONVERTER STUDY /*/ /*/ \*/ /*\ | LPT1 | LPT2 WRITE D7 D6 D5 D4 D3 D2 D1 D0 /*/ /*/ -----+------+------ x x x x x /SCL /SDA PWR \*/ /*\ WRITE| 378h | 278h /*/ /*/ -----+------+------ READ D7 D6 D5 D4 D3 D2 D1 D0 \*/ /*\ READ | 379h | 279h x x SCL SDA x x x PWR /*/ /*/ \*/ /*\ ======================================================================== /*/ /*/ \*/ /*\ ETUDE DU BUS I2C de PHILIPS /*/ /*/ \*/ /*\ TRAME : {Sleep} SDA -------- 1 /*/ /*/ . 0 \*/ /*\ . SCL -------- 1 /*/ /*/ . 0 \*/ /*\ . /*/ /*/ . \*/ /*\ {Start} SDA --, 1 /*/ /*/ . |_____ 0 \*/ /*\ . SCL -----, 1 /*/ /*/ . |__ 0 \*/ /*\ . /*/ /*/ . \*/ /*\ {Active} SDA 1 /*/ /*/ . ________ 0 \*/ /*\ . SCL 1 /*/ /*/ . ________ 0 \*/ /*\ . /*/ /*/ . \*/ /*\ . {Adresse.7bits}{R/W.1bit} /*/ /*/ . {Ackowledge.1bit} \*/ /*\ . /*/ /*/ . \*/ /*\ . {Sending 0} SDA 1 Set by MASTER /*/ /*/ . ________ 0 \*/ /*\ . SCL ,--, 1 Set by MASTER /*/ /*/ . __| |__ 0 \*/ /*\ . /*/ /*/ . \*/ /*\ . {Sending 1} SDA ,----, 1 Set by MASTER /*/ /*/ . _| |_ 0 \*/ /*\ . SCL ,--, 1 Set by MASTER /*/ /*/ . __| |__ 0 \*/ /*\ . /*/ /*/ . \*/ /*\ . {Receiving 0} SDA ?? 1 Set by SLAVE !!! /*/ /*/ . ??______ 0 \*/ /*\ . SCL ,--, 1 Set by MASTER /*/ /*/ . __| |__ 0 \*/ /*\ . /*/ /*/ . \*/ /*\ . {Receiving 1} SDA ??------ 1 Set by SLAVE !!! /*/ /*/ . ?? 0 \*/ /*\ . SCL ,--, 1 Set by MASTER /*/ /*/ . __| |__ 0 \*/ /*\ . /*/ /*/ . \*/ /*\ . /*/ /*/ . {Donnee.8bits} \*/ /*\ . {Ackowledge.1bit} /*/ /*/ . \*/ /*/ . \*/ /*\ . {ACK OK to SLAVE} SDA 1 Set by MASTER /*/ /*/ . ________ 0---> OK when 0 \*/ /*\ . Always send OK (0) SCL ,--, 1 Set by MASTER /*/ /*/ . if you cannot check __| |__ 0 \*/ /*\ . if the transmition /*/ /*/ . was OK \*/ /*/ . \*/ /*\ . {ACK from SLAVE} SDA ,?????? 1---> ERROR when 1 /*/ /*/ . _|?????? 0---> OK when 0 \*/ /*\ . SCL ,--, 1 Set by MASTER /*/ /*/ . __| |__ 0 \*/ /*\ . /*/ /*/ . 1/ MASTER set SDA to 1 \*/ /*\ . 2/ MASTER Set SCL to 1 /*/ /*/ . 3/ On rising front of SCL, SLAVE reply on SDA \*/ /*\ . IF an error occured, SLAVE keep SDA to 1 /*/ /*/ . ELSE the SLAVE set SDA to 0 \*/ /*\ . /*/ /*/ . \*/ /*\ {Stop} SDA ,-- 1 /*/ /*/ . _____| 0 \*/ /*\ . SCL ,----- 1 /*/ /*/ . __| 0 \*/ /*\ . /*/ /*/ . \*/ /*\ {Sleep} SDA -------- 1 /*/ /*/ 0 \*/ /*\ SCL -------- 1 /*/ /*/ 0 \*/ /*\ /*/ /*/ \*/ /*\ ======================================================================== /*/ /*/ \*/ /*\ FRAMES STRUCTURES /*/ /*/ \*/ /*\ Frame offset /*/ /*/ \*/ /*\ Module | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 /*/ /*/ -------+------+-------+-------+-------+-------+-------+-------+------ \*/ /*\ Displ W 0x70 | 0 | 0x077 | Digi1 | Digi2 | Digi3 | Digi4 | /*/ /*/ -------+------+-------+-------+-------+-------+-------+-------+------ \*/ /*\ Clock W 0xA2 | SAh | W@SAh |W@SAh+1|W@SAh+2| | | /*/ /*/ R 0xA3 | R@00h | R@01h | ... | ... | ... | ... | ... \*/ /*\ /*/ /*/ \*/ /*\ ======================================================================== /*/ /*/ \*/ /*\ DISPLAY (ADRESS 0x070) /*/ /*/ \*/ /*\ bit0 /*/ /*/ ---- \*/ /*\ bit5| |bit1 /*/ /*/ |bit6| \*/ /*\ ---- /*/ /*/ bit4| |bit2 \*/ /*\ | | /*/ /*/ ---- o bit7 \*/ /*\ bit3 /*/ /*/ \*/ /*\ ======================================================================== /*/ /*/ Get more informations about the I2C bus on http://www.philips.com \*/ /*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*/ /*/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\*/ /*\ CODE OVERVIEW /*/ /*/ \*/ /*\ INCLUDES /*/ /*/ DEFINES (CONSTANTS, ...) \*/ /*\ CLASS oFI2C DEFINITION /*/ /*/ CONSTRUCTORS AND DESTRUCTORS \*/ /*\ LEVEL 0 METHODS (LOW LEVEL) /*/ /*/ oFI2C_BUS_Init \*/ /*\ oFI2C_BUS_Off /*/ /*/ oFI2C_BUS_Test \*/ /*\ oFI2C_BIT_Set /*/ /*/ oFI2C_BIT_Clear \*/ /*\ oFI2C_BIT_Test /*/ /*/ LEVEL 1 METHODS (LOGIC LEVEL) \*/ /*\ oFI2C_BUS_Start /*/ /*/ oFI2C_BUS_Stop \*/ /*\ oFI2C_ACK_Sending /*/ /*/ oFI2C_ACK_Receiving \*/ /*\ LEVEL 2 METHODS (MACRO LEVEL) /*/ /*/ oFI2C_DAT_Send \*/ /*\ oFI2C_DAT_Receive /*/ /*/ oFI2C_DAT_Convert \*/ /*\ LEVEL 3 METHODS (FUNCTIONNAL LEVEL) /*/ /*/ oFI2C_FRM_Send \*/ /*\ oFI2C_FRM_Receive /*/ /*/ \*/ /*\ MAIN PROGRAM /*/ /*/ \*/ /*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*/ /*/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\*/ /*\ 'INCLUDES' /*/ /*/ \*/ /*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*/ #include <conio.h> #include <stdio.h> #include <dos.h> // For 'delay' #include <iostream.h> // For 'cout' /*/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\*/ /*\ 'DEFINES' /*/ /*/ \*/ /*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*/ /*** cTRUE ********************************************************************/ /* Purpose : TRUE condition flag */ /* Unit : None */ /* Range : TRUE / FALSE */ /* List : None */ /* Example : None */ /* WARNING : ALWAYS (1==1) */ /******************************************************************************/ #define cTRUE (1==1) // ALWAYS generate a TRUE constant /*** cFALSE *******************************************************************/ /* Purpose : FALSE condition flag */ /* Unit : None */ /* Range : TRUE / FALSE */ /* List : None */ /* Example : None */ /* WARNING : ALWAYS (1==0) */ /******************************************************************************/ #define cFALSE (1==0) // ALWAYS generate a FALSE constant /*** tBIT *********************************************************************/ /* Purpose : BIT type definition */ /* Unit : None */ /* Range : [0-1] - LIMITED selection */ /* List : None */ /* Example : None */ /******************************************************************************/ typedef bool tBIT; /*** tUBYTE *******************************************************************/ /* Purpose : Unsigned BYTE type definition */ /* Unit : None */ /* Range : [0-255] - LIMITED selection */ /* List : None */ /* Example : None */ /******************************************************************************/ typedef unsigned char tUBYTE; /*** tSBYTE *******************************************************************/ /* Purpose : Signed BYTE type definition */ /* Unit : None */ /* Range : [-128 - +127] - LIMITED selection */ /* List : None */ /* Example : None */ /******************************************************************************/ typedef char tSBYTE; /*** tUWORD *******************************************************************/ /* Purpose : Unsigned WORD type definition */ /* Unit : None */ /* Range : [0-65535] - LIMITED selection */ /* List : None */ /* Example : None */ /******************************************************************************/ typedef unsigned int tUWORD; /*** tSWORD *******************************************************************/ /* Purpose : Signed WORD type definition */ /* Unit : None */ /* Range : [-32768 - +32767] - LIMITED selection */ /* List : None */ /* Example : None */ /******************************************************************************/ typedef int tSWORD; // Signed LOW gives tSLOW (ROTFL ;)=) /*** tULONG *******************************************************************/ /* Purpose : Unsigned LONG type definition */ /* Unit : None */ /* Range : [0-4294967296] - 'LIMITED' selection */ /* List : None */ /* Example : None */ /******************************************************************************/ typedef unsigned long tULONG; /*** tSLONG *******************************************************************/ /* Purpose : Signed LONG type definition */ /* Unit : None */ /* Range : [-2147483648 - +2147483647] - 'LIMITED' selection */ /* List : None */ /* Example : None */ /******************************************************************************/ typedef long tSLONG; /*** TEMPO ********************************************************************/ /* Purpose : Enable/Disable TEMPO */ /* Unit : DEFINE selection */ /* Range : None */ /* List : None */ /* Example : //#define TEMPO -> Disable TEMPO */ /******************************************************************************/ //#define TEMPO /*** DISPLAY ******************************************************************/ /* Purpose : Enable/Disable DISPLAY */ /* Unit : DEFINE selection */ /* Range : None */ /* List : None */ /* Example : #define DISPLAY -> Enable DISPLAY module */ /******************************************************************************/ #define DISPLAY /*** CLOCK ********************************************************************/ /* Purpose : Enable/Disable CLOCK */ /* Unit : DEFINE selection */ /* Range : None */ /* List : None */ /* Example : //#define CLOCK -> Disable CLOCK module */ /******************************************************************************/ //#define CLOCK /*** cI2C_BIT *****************************************************************/ /* Purpose : I2C bit selection */ /* Unit : None */ /* Range : enum LIST */ /* List : 0 = cPWR */ /* 1 = cSCL */ /* 2 = cSDA */ /* Example : None */ /******************************************************************************/ enum { cPWR, cSCL, cSDA }cI2C_BIT; /*** cI2C_ARRAY ***************************************************************/ /* Purpose : I2C bit bit array definition in oFI2C */ /* Unit : None */ /* Range : enum LIST */ /* List : 0 = RPWR_BIT 1 = RPWR_LVL */ /* 2 = RSCL_BIT 3 = RSCL_LVL */ /* 4 = RSDA_BIT 5 = RSDA_LVL */ /* 6 = WPWR_BIT 7 = WPWR_LVL */ /* 8 = WSCL_BIT 9 = WSCL_LVL */ /* 10 = WSDA_BIT 11 = WSDA_LVL */ /* Example : None */ /******************************************************************************/ enum { RPWR_BIT, RPWR_LVL, RSCL_BIT, RSCL_LVL, RSDA_BIT, RSDA_LVL, WPWR_BIT, WPWR_LVL, WSCL_BIT, WSCL_LVL, WSDA_BIT, WSDA_LVL }cI2C_ARRAY; /*** cADDR_BASE_WLPT **********************************************************/ /* Purpose : Base address of the LPT 1 port for writing */ /* Unit : None */ /* Range : Mem ADDR - FREE selection */ /* List : 0x0378 -> LPT1 */ /* 0x0278 -> LPT2 */ /* Example : #define cADDR_BASE_WLPT 0x0378 -> Writing addr of LPT1 */ /* WARNING : Due to the code structure, keep here >ALWAYS< 0x0378. */ /******************************************************************************/ #define cADDR_BASE_WLPT 0x0378 /*** cADDR_BASE_RLPT **********************************************************/ /* Purpose : Base address of the LPT 1 port for reading */ /* Unit : None */ /* Range : Mem ADDR - FREE selection */ /* List : 0x0379 -> LPT1 */ /* 0x0279 -> LPT2 */ /* Example : #define cADDR_BASE_RLPT 0x0379 -> Reading addr of LPT1 */ /* WARNING : Keep here >ALWAYS< cADDR_BASE_WLPT+1 (code structure) */ /******************************************************************************/ #define cADDR_BASE_RLPT cADDR_BASE_WLPT+1 /*** cDATA_LOOP_TRY ***********************************************************/ /* Purpose : Number of times the Receice routine will try to fetch the datas */ /* Unit : None */ /* Range : [0-3-...] - FREE selection */ /* List : 0 -> Only 1 try, else error */ /* 3 -> Will try 3 times before generating an error */ /* Example : #define cDATA_LOOP_TRY 3 */ /******************************************************************************/ #define cDATA_LOOP_TRY 3 /*** cDATA_TIME_TEMPO *********************************************************/ /* Purpose : Time between two I2C clock cycles */ /* Unit : 1/1000 s */ /* Range : [...-10-100-...] - FREE selection */ /* List : 10 -> 100 Bauds */ /* 100 -> 10 Bauds */ /* Example : #define cDATA_TIME_TEMPO 1 -> 1000 Bauds */ /* WARNING : 0 works fine ! */ /******************************************************************************/ #define cDATA_TIME_TEMPO 0 /*** cBITN_LPTP_POWER *********************************************************/ /* Purpose : Bit number of the Power line of the I2C Converter card */ /* Unit : Bit Number */ /* Range : [0-7] - LIMITED selection */ /* List : Depend of the conversion card plugged on the parallel data port */ /* Example : #define cBITN_LPTP_POWER 0 */ /******************************************************************************/ #define cBITN_LPTP_POWER 0 /*** cBITN_LPTP_WSDA **********************************************************/ /* Purpose : Bit number of the SDA line on the write port */ /* Unit : Bit Number */ /* Range : [0-7] - LIMITED selection */ /* List : Depend of the conversion card plugged on the parallel data port */ /* Example : #define cBITN_LPTP_WSDA 1 */ /******************************************************************************/ #define cBITN_LPTP_WSDA 1 /*** cBITN_LPTP_WSCL **********************************************************/ /* Purpose : Bit number of the SCL line on the write port */ /* Unit : Bit Number */ /* Range : [0-7] - LIMITED selection */ /* List : Depend of the conversion card plugged on the parallel data port */ /* Example : #define cBITN_LPTP_WSCL 2 */ /******************************************************************************/ #define cBITN_LPTP_WSCL 2 /*** cBITN_LPTP_RSDA **********************************************************/ /* Purpose : Bit number of the SDA line on the read port */ /* Unit : Bit Number */ /* Range : [0-7] - LIMITED selection */ /* List : Depend of the conversion card plugged on the parallel dat port */ /* Example : #define cBITN_LPTP_RSDA 4 */ /******************************************************************************/ #define cBITN_LPTP_RSDA 4 /*** cBITN_LPTP_RSCL **********************************************************/ /* Purpose : Bit number of the SCL line on the read port */ /* Unit : Bit Number */ /* Range : [0-7] - LIMITED selection */ /* List : Depend of the conversion card plugged on the parallel dat port */ /* Example : #define cBITN_LPTP_RSCL 5 */ /******************************************************************************/ #define cBITN_LPTP_RSCL 5 /*** cADDR_I2CM_DISP **********************************************************/ /* Purpose : I2C module address for the displayer */ /* Unit : None */ /* Range : Mem ADDR - FREE selection */ /* List : Depend on the displayer module configuration */ /* Example : #define cADDR_I2CM_DISP 0x070 */ /******************************************************************************/ #define cADDR_I2CM_DISP 0x070 /*** cADDR_I2CM_CLOCK *********************************************************/ /* Purpose : I2C module address for the Real-Time Clock */ /* Unit : None */ /* Range : Mem ADDR - FREE selection */ /* List : Depend on the RTC module configuration */ /* Example : #define cADDR_I2CM_CLOCK 0x0A2 */ /******************************************************************************/ #define cADDR_I2CM_CLOCK 0x0A2 /*/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\*/ /*\ 'CLASS/OBJECT' DEFINITION /*/ /*/ \*/ /*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*/ class oFI2C // oFI2C object { private: // Can ONLY be used in oFI2C's methods (as LOCAL variables) // 'Characteristics' of the oFI2C object ///////////////////////////// tUBYTE vFI2C_LPT_DATA; // DATA buffer tUBYTE vFI2C_LPT_MASK; // MASK (calculated once ! in oFI2C_BUS_Init) tUWORD vFI2C_LPT_RPORT; // READ address (calculated once ! in oFI2C_BUS_Init) tUWORD vFI2C_LPT_WPORT; // WRITE address (calculated once ! in oFI2C_BUS_Init) tUWORD vFI2C_LPT_NPORT; tUBYTE cFI2C_LPT_MAPPING[]={ // BIT NUMBER, ACTIVE LEVEL <- according to cBITN_LPTP_POWER, 1, // RPWR the conversion cBITN_LPTP_RSCL , 1, // RSCL card cBITN_LPTP_RSDA , 1, // RSDA cBITN_LPTP_POWER, 1, // WPWR cBITN_LPTP_WSCL , 0, // WSCL cBITN_LPTP_WSDA , 0 // WSDA }; public: // Can be used EVERYWHERE // 'Constructors/Destructors' //////////////////////////////////////// oFI2C (); oFI2C (int vPARAM_BUS_LPT_Port); ~oFI2C (); // 'Methods' ///////////////////////////////////////////////////////// // LEVEL 0 METHODS (LOW LEVEL) void oFI2C_BUS_Init (tUWORD vPARAM_BUS_LPT_Port); void oFI2C_BUS_Off (void); tBIT oFI2C_BUS_Test (void); void oFI2C_BIT_Set (tUWORD vPARAM_BIT_ID); void oFI2C_BIT_Clear (tUWORD vPARAM_BIT_ID); tBIT oFI2C_BIT_Test (tUWORD vPARAM_BIT_ID); // LEVEL 1 METHODS (LOGIC LEVEL) void oFI2C_BUS_Start (void); void oFI2C_BUS_Stop (void); tBIT oFI2C_ACK_Sending (void); void oFI2C_ACK_Receiving (void); // LEVEL 2 METHODS (MACRO LEVEL) void oFI2C_DAT_Send (tUBYTE vPARAM_DAT_Data_To_Send); tUBYTE oFI2C_DAT_Receive (void); tUBYTE oFI2C_DAT_Convert (tUBYTE vPARAM_DAT_ASCII_Char); // LEVEL 3 METHODS (FUNCTIONNAL LEVEL) tBIT oFI2C_FRM_Send (tUBYTE vPARAM_FRM_Frame_To_Send[]); tBIT oFI2C_FRM_Receive (tUBYTE vPARAM_FRM_Frame_To_Receive[]); }; /*/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\*/ /*\ 'CONSTRUCTORS/DESTRUCTORS' /*/ /*/ \*/ /*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*/ /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C */ /* Role : Default constructor, when no parameter is given */ /* Interface : None */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Configure the parallel port LPT 1] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Configure the parallel port LPT 1] = */ /* DO */ /* [Call the initialisation routine for the LPT1 port] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ oFI2C::oFI2C() { oFI2C_BUS_Init(1); // Port LPT1 par defaut } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C */ /* Role : Constructor with parameter */ /* Interface : None */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Configure the selected parallel port] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Configure the selected parallel port] = */ /* DO */ /* [Call the initialisation routine with the selected port as parameter] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ oFI2C::oFI2C(int vPARAM_BUS_LPT_Port) { oFI2C_BUS_Init(vPARAM_BUS_LPT_Port); } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C */ /* Role : Destructor automatically called at program exit */ /* Interface : None */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Restore the default/selected parallel port] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Restore the default/selected parallel port] = */ /* DO */ /* [Call the routine that will cut off the power of the conversion card] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ oFI2C::~oFI2C() { oFI2C_BUS_Off(); // A la fin, on COUPE tout... } /*/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\*/ /*\ 'METHODES' /*/ /*/ \*/ /*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*/ /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_BUS_Init */ /* Role : Switch on the card on and put it in STOP mode */ /* Interface : IN AskedLptPort */ /* 1 - LPT 1 */ /* 2 - LPT 2 */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Power ON and STOP condition] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_BUS_Init */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Power ON and STOP condition] = */ /* DO */ /* [Calculate the READ address according to the selected LPT port] */ /* [Calculate the WRITE address according to the selected LPT port] */ /* [Calculate the MASK for faster access] */ /* [Set SDA and SCL to '1'] */ /* [Power ON the conversion card, set POWER to '1'] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ void oFI2C::oFI2C_BUS_Init(tUWORD vPARAM_BUS_LPT_Port) { vFI2C_LPT_NPORT = (vPARAM_BUS_LPT_Port - 1) & 1; vFI2C_LPT_RPORT = cADDR_BASE_RLPT - (0x0100 * vFI2C_LPT_NPORT); vFI2C_LPT_WPORT = cADDR_BASE_WLPT - (0x0100 * vFI2C_LPT_NPORT); vFI2C_LPT_MASK = ((cFI2C_LPT_MAPPING[RPWR_LVL] & 1) << (cFI2C_LPT_MAPPING[RPWR_BIT] % 8)) // POWER | ((cFI2C_LPT_MAPPING[RSCL_LVL] & 1) << (cFI2C_LPT_MAPPING[RSCL_BIT] % 8)) // RSCL | ((cFI2C_LPT_MAPPING[RSDA_LVL] & 1) << (cFI2C_LPT_MAPPING[RSDA_BIT] % 8)); // RSDA | ((cFI2C_LPT_MAPPING[WSCL_LVL] & 1) << (cFI2C_LPT_MAPPING[WSCL_BIT] % 8)) // WSCL | ((cFI2C_LPT_MAPPING[WSDA_LVL] & 1) << (cFI2C_LPT_MAPPING[WSDA_BIT] % 8)); // WSDA vFI2C_LPT_DATA = (1 << (cFI2C_LPT_MAPPING[WSCL_BIT] % 8)) // WSCL == 1 | (1 << (cFI2C_LPT_MAPPING[WSDA_BIT] % 8)); // WSDA == 1 oFI2C_BIT_Set(cPWR); // Set PWR == 1, then put the whole BUFFER onto the PORT (WSCL, WSDA and WPWR) #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_BUS_Off */ /* Role : Restore I2C bus mode */ /* Interface : None */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Clear the I2C and switch off the power] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_BUS_Off */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Clear the I2C and switch off the power] = */ /* DO */ /* [Put the I2C bus lines to low level, set SDA and SCL to '0'] */ /* [Switch off the power, set POWER to '0'] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ void oFI2C::oFI2C_BUS_Off(void) { oFI2C_BIT_Clear(cSDA); oFI2C_BIT_Clear(cSCL); oFI2C_BIT_Clear(cPWR); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_BUS_Test */ /* Role : Test if the I2C bus is FREE, in STOP mode (SDA and SCL to '1') */ /* Interface : OUT oFI2C_BUS_Test */ /* cFALSE - Error */ /* cTRUE - OK, bus FREE */ /* Pre-condition : None */ /* Constraints : Cannot define in which context we are : Read, Write or Ack ? */ /* Behavior : */ /* DO */ /* [Test if the I2C bus is in STOP mode] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_BUS_Test */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Test if the I2C bus is in STOP mode] = */ /* IF [SDA and SCL to '1', then the I2C bus is FREE, return 1] THEN */ /* [The I2C is FREE, return cTRUE] */ /* ELSE */ /* [The I2C is NOT FREE, return cFALSE] */ /* FI */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ bool oFI2C::oFI2C_BUS_Test(void) { return( oFI2C_BIT_Test(cSDA) && oFI2C_BIT_Test(cSCL) ); } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_BIT_Set */ /* Role : Set a bit of the LPT data port to '1' */ /* Interface : IN NbBit */ /* [0-7] - Bit number to set to '1' */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Set the selected bit to '1'] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_BIT_Set */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Set the selected bit to '1'] = */ /* DO */ /* [Set the bit to '1' in the LPT data buffer, using OR and ROL modulo 8] */ /* [Output the buffer onto the selected LPT data port] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ void oFI2C::oFI2C_BIT_Set(tUWORD vPARAM_BIT_ID) { vFI2C_LPT_DATA |= ( 1 << ( cFI2C_LPT_MAPPING[(vPARAM_BIT_ID * 2) + 6] % 8 ) ); outportb( vFI2C_LPT_WPORT, ( ( vFI2C_LPT_DATA & vFI2C_LPT_MASK) // HIGH LEVEL | (~vFI2C_LPT_DATA & ~vFI2C_LPT_MASK) // LOW LEVEL ) ); } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_BIT_Clear */ /* Role : Set a bit of the LPT data port to '0' */ /* Interface : IN NbBit */ /* [0-7] - Bit number to set to '0' */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Set the selected bit to '0'] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_BIT_Clear */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Set the selected bit to '0'] = */ /* DO */ /* [Set the bit to '0' in the LPT data buffer, AND, XOR and ROL modulo 8] */ /* [Output the buffer onto the selected LPT data port] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ void oFI2C::oFI2C_BIT_Clear(tUWORD vPARAM_BIT_ID) { vFI2C_LPT_DATA &= ( (-1) ^ ( 1 << ( cFI2C_LPT_MAPPING[(vPARAM_BIT_ID * 2) + 6] % 8 ) ) ); outportb( vFI2C_LPT_WPORT, ( vFI2C_LPT_DATA & vFI2C_LPT_MASK) // HIGH LEVEL | (~vFI2C_LPT_DATA & ~vFI2C_LPT_MASK) // LOW LEVEL ); } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_BIT_Test */ /* Role : Return the state of a selected bit of the LPT data port */ /* Interface : IN NbBit */ /* [0-7] - Bit number to set to '0' */ /* OUT oFI2C_BIT_Test */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Test the status of the selected bit] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_BIT_Test */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Test the status of the selected bit] = */ /* DO */ /* [Return the selected bit state, using ROR modulo 8 and AND 1] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ tBIT oFI2C::oFI2C_BIT_Test(tUWORD vPARAM_BIT_ID) { register tUBYTE vLOCAL_BIT_Test; // Force REGISTER usage instead of STACK vLOCAL_BIT_Test = inportb(vFI2C_LPT_RPORT); return( ( ( ( vLOCAL_BIT_Test & vFI2C_LPT_MASK) // HIGH LEVEL | (~vLOCAL_BIT_Test & ~vFI2C_LPT_MASK) // LOW LEVEL ) >> ( cFI2C_LPT_MAPPING[vPARAM_BIT_ID * 2] % 8 ) ) & 1 ); } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_BUS_Start */ /* Role : Create a START condition on the I2C bus */ /* Interface : None */ /* Pre-condition : MUST be in STOP mode */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Put the I2C bus in START mode] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_BUS_Start */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Put the I2C bus in START mode] = */ /* DO */ /* [Put SDA to '0' and SCL to '1', falling edge of SDA first] */ /* [Put SDA to '0' and SCL to '0', falling edge of SCL then] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ void oFI2C::oFI2C_BUS_Start(void) { oFI2C_BIT_Clear(cSDA); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO oFI2C_BIT_Clear(cSCL); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_BUS_Stop */ /* Role : Create a STOP condition on the I2C bus */ /* Interface : None */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Put the I2C bus in STOP mode] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_BUS_Stop */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Put the I2C bus in STOP mode] = */ /* DO */ /* [Put SDA to '0' and SCL to '1', rising edge of SCL first] */ /* [Put SDA to '1' and SCL to '1', rising edge of SDA then] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ void oFI2C::oFI2C_BUS_Stop(void) { oFI2C_BIT_Set(cSCL); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO oFI2C_BIT_Set(cSDA); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_ACK_Sending */ /* Role : 'Acknowledge' condition returned by the Slave on emitting */ /* Interface : OUT oFI2C_ACK_Sending */ /* cFALSE - Error */ /* cTRUE - OK */ /* Pre-condition : A byte MUST have been sent to a slave */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Return Slave's 'Acknowledge'] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_ACK_Sending */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Return Slave's 'Acknowledge'] = */ /* DO */ /* [Set SDA to '1', and keep SCL to '0'] */ /* [Set SCL to '1', rising edge of SCL] */ /* [The Slave change the state of SDA according to the its receive state] */ /* [Set SDA and SCL to '0'] */ /* [Return the Slave's receive state] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /* Don't believe the WARNING issued there, da stuff is supposed to work FINE */ /*--- END FUNCTION HEADER ----------------------------------------------------*/ tBIT oFI2C::oFI2C_ACK_Sending(void) { tBIT vLOCAL_ACK_Slave_Reply; oFI2C_BIT_Set(cSDA); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO oFI2C_BIT_Set(cSCL); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO vLOCAL_ACK_Slave_Reply = (~oFI2C_BIT_Test(cSDA)) & 1; oFI2C_BIT_Clear(cSDA); oFI2C_BIT_Clear(cSCL); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO return vLOCAL_ACK_Slave_Reply; } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_ACK_Receiving */ /* Role : 'Acknowledge' condition returned TO the Slave on receiving from */ /* Interface : None */ /* Pre-condition : None */ /* Constraints : ALWAYS return OK ! */ /* Behavior : */ /* DO */ /* [Return OK to the Slave] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_ACK_Receiving */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Return OK to the Slave] = */ /* DO */ /* [Set SDA to '0', reception OK] */ /* [Validate with a complete clock cycle, SCL to '1', then '0'] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ void oFI2C::oFI2C_ACK_Receiving(void) { oFI2C_BIT_Clear(cSDA); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO oFI2C_BIT_Set(cSCL); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO oFI2C_BIT_Clear(cSCL); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_DAT_Send */ /* Role : Send 8 bits on the I2C bus */ /* Interface : IN Data2Send */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Send 8 bits, from MSB to LSB] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_DAT_Send */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Send 8 bits, from MSB to LSB] = */ /* DO */ /* WHILE [Counter = 7 to 0] */ /* DO */ /* [Set SDA to the bit number 'Counter' state] */ /* [Validate with a complete clock cycle, SCL to '1', then '0'] */ /* OD */ /* [At the end, set SDA and SCL to '0'] */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ void oFI2C::oFI2C_DAT_Send(tUBYTE vPARAM_DAT_Data_To_Send) { tUBYTE vLOCAL_DAT_Send_Loop; // MSB -> LSB for( vLOCAL_DAT_Send_Loop = 7; vLOCAL_DAT_Send_Loop >= 0; vLOCAL_DAT_Send_Loop -- ) { if( ( vPARAM_DAT_Data_To_Send >> vLOCAL_DAT_Send_Loop ) & 1 // KEEP and SEND the BIT 0 ) { oFI2C_BIT_Set(cSDA); } else { oFI2C_BIT_Clear(cSDA); } #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO oFI2C_BIT_Set(cSCL); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO oFI2C_BIT_Clear(cSCL); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO } oFI2C_BIT_Clear(cSDA); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_DAT_Receive */ /* Role : Receive 8 bits on the I2C bus */ /* Interface : OUT oFI2C_DAT_Receive */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Receive 8 bits, from MSB to LSB] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_DAT_Receive */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Receive 8 bits, from MSB to LSB] = */ /* DO */ /* WHILE [Counter = 7 to 0] */ /* DO */ /* [Set SCL to '1', rising edge of SCL] */ /* [Set the buffetr bit number 'Counter' to SDA state] */ /* [Set SCL to '0', falling edge of SCL] */ /* [Clear SDA and let the Slave set its state at the next loop] */ /* OD */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ tUBYTE oFI2C::oFI2C_DAT_Receive(void) { tUBYTE vLOCAL_DAT_Receive_Data = 0; tUWORD vLOCAL_DAT_Receive_Loop; // MSB -> LSB for( vLOCAL_DAT_Receive_Loop = 7; vLOCAL_DAT_Receive_Loop >= 0; vLOCAL_DAT_Receive_Loop -- ) { oFI2C_BIT_Set(cSCL); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO vLOCAL_DAT_Receive_Data |= ( oFI2C_BIT_Test(cSDA) << vLOCAL_DAT_Receive_Loop ); oFI2C_BIT_Clear(cSCL); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO } oFI2C_BIT_Clear(cSDA); #ifdef TEMPO delay(cDATA_TIME_TEMPO); #endif // TEMPO return vLOCAL_DAT_Receive_Data; } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_FRM_Send */ /* Role : Send a complete frame */ /* Interface : IN SendFlux's address (using pre-defined tables, see 'main') */ /* OUT oFI2C_FRM_Send */ /* cFALSE - Error */ /* cTRUE - OK */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Send a complete frame on the I2C bus] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_FRM_Send */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Send a complete frame on the I2C bus] = */ /* DO */ /* [Set the I2C bus in START mode] */ /* [Print the selected LPT data port on which the data will be sent] */ /* [Print the I2C module address and the number of parameters to send] */ /* WHILE [Counter = 1 to SizeOfFrame+1] (skip number of params to send) */ /* DO */ /* [Clear the Error Counter] */ /* DO */ /* [Send the byte number 'Counter' on the I2C bus] */ /* [Increase the Error Counter / Number of Try Counter] */ /* OD */ /* WHILE [(NO Ack from Slave) AND (Error Counter < Number of try)] */ /* [Print the byte number sent, its value, and the number of try] */ /* IF [Error Counter = Number of Try] THEN */ /* [Exit loop and finish the routine with a final test] */ /* ELSE */ /* [Increase the number of bytes really sent] */ /* FI */ /* OD */ /* [Set the I2C bus in STOP mode] */ /* IF [Number of bytes really sent = Number of byte to send] THEN */ /* [Return 'cTRUE'] */ /* ELSE */ /* [Return 'cFALSE'] */ /* FI */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ tBIT oFI2C::oFI2C_FRM_Send(tUBYTE vPARAM_FRM_Frame_To_Send[]) { tUWORD vLOCAL_FRM_Sent_Counter = 0; tUWORD vLOCAL_FRM_Sent_Loop; tUWORD vLOCAL_FRM_Sent_Error; oFI2C_BUS_Start(); printf( "Sending on LPT%d : ", (vFI2C_LPT_NPORT + 1) ); // {'I2C module address'['Data tail length']} printf( "{$%x[%d]} ", (vPARAM_FRM_Frame_To_Send[1]), (vPARAM_FRM_Frame_To_Send[0]) ); // '1' because we shouda start sending the I2C module address first // '+1', the end of the I2C frame... // IF 8 params, you have 10 bytes (+2 car TailLength + ModuleAddr), // and the array goes from 0 to 9, so end of params at 9 (8 + 1, TailLength + 1) !!! for( vLOCAL_FRM_Sent_Loop = 1; vLOCAL_FRM_Sent_Loop <= (vPARAM_FRM_Frame_To_Send[0] + 1); vLOCAL_FRM_Sent_Loop ++ ) { vLOCAL_FRM_Sent_Error = 0; do { oFI2C_DAT_Send(vPARAM_FRM_Frame_To_Send[vLOCAL_FRM_Sent_Loop]); vLOCAL_FRM_Sent_Error ++; } while( // IF error (!oFI2C_ACK_Sending()) && ( vLOCAL_FRM_Sent_Error < cDATA_LOOP_TRY ) ); // IF OK or TOO MUCH ERROR, exit loop // In CASE of TOO MUCH ERROR, the IF below will cheat the loop counter // ['ParamNumber'-$'HexByteValue'('ErrorNb')] // '-1' because ModuleAddr not took in account (9 - 1, 8 params, indexed on screen as byte 1 to 8) printf( "[%d-$%x(%d)]", (vLOCAL_FRM_Sent_Loop - 1), (vPARAM_FRM_Frame_To_Send[vLOCAL_FRM_Sent_Loop]), (vLOCAL_FRM_Sent_Error) ); if(vLOCAL_FRM_Sent_Error == cDATA_LOOP_TRY) { vLOCAL_FRM_Sent_Loop = vPARAM_FRM_Frame_To_Send[0] + 1; // Exit the loop by setting the loop counter at its maximum value } else { vLOCAL_FRM_Sent_Counter ++; // Number of byte sent } } oFI2C_BUS_Stop(); printf("\r\n"); // NbReallySent - 1 : '-1' because we skip the ModuleAddr... return( (vLOCAL_FRM_Sent_Counter - 1) == (vPARAM_FRM_Frame_To_Send[0]) ); } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_FRM_Receive */ /* Role : Receive a complete frame */ /* Interface : IN ReceiveFlux's address (see 'main' for tables structure) */ /* OUT oFI2C_FRM_Send */ /* cFALSE - Error */ /* cTRUE - OK */ /* Interface : None */ /* Pre-condition : None */ /* Constraints : ALWAYS return OK to the Slave ! */ /* Behavior : */ /* DO */ /* [Receive a complete frame on the I2C bus] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_FRM_Receive */ /* ( */ /* ) */ /* DATA */ /* ATAD */ /* */ /* DO */ /* [Receive a complete frame on the I2C bus] = */ /* DO */ /* [Set the I2C bus in START mode] */ /* [Print the selcted LPT data port on which the data will be received] */ /* [Print the I2C module address and the number of parameters to receive] */ /* [Send the module address with the read flag ON] */ /* IF [Ack from Slave, the Slave is OK with the data request] THEN */ /* WHILE [Counter = 2 to SizeOfFrame+1] (skip nb params and mod addr)] */ /* DO */ /* [Receive the byte number 'Counter' on the I2C bus] */ /* [Send OK Ack for the Slave] */ /* [Print the byte number received and its value] */ /* [Increase the number of bytes really received] */ /* OD */ /* FI */ /* [Set the I2C bus in STOP mode] */ /* IF [Number of bytes really received = Number of byte to receive] THEN */ /* [Return 'cTRUE'] */ /* ELSE */ /* [Return 'cFALSE'] */ /* FI */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ tBIT oFI2C::oFI2C_FRM_Receive(tUBYTE vPARAM_FRM_Frame_To_Receive[]) { tUWORD vLOCAL_FRM_Receive_Counter = 0; tUWORD vLOCAL_FRM_Receive_Loop; oFI2C_BUS_Start(); printf( "Receiving on LPT%d : ", (vFI2C_LPT_NPORT + 1) ); // {'I2C module address'['Data tail length']} printf( "{$%x[%d]} ", (vPARAM_FRM_Frame_To_Receive[1] | 1), (vPARAM_FRM_Frame_To_Receive[0]) ); oFI2C_DAT_Send(vPARAM_FRM_Frame_To_Receive[1] | 1); // '|1' set READ bit !! if(oFI2C_ACK_Sending()) { // '2', because we start receiving at offset 2 (at '0' TailLength, at '1' ModuleAddr) // '+1' because end of frame when receiving // IF 8 params, you have 10 bytes (+2 car TailLength + ModuleAddr), // and the array goes from 0 to 9, so end of params at 9 (8 + 1, TailLength + 1) !!! for( vLOCAL_FRM_Receive_Loop = 2; vLOCAL_FRM_Receive_Loop <= (vPARAM_FRM_Frame_To_Receive[0] + 1); vLOCAL_FRM_Receive_Loop ++ ) { vPARAM_FRM_Frame_To_Receive[vLOCAL_FRM_Receive_Loop] = oFI2C_DAT_Receive(); oFI2C_ACK_Receiving(); // ['ParamNumber'-$'HexByteValue'('ErrorNb')] // '-1' because ModuleAddr not took in account (9 - 1, 8 params, indexed on screen as byte 1 to 8) printf( "[%d-$%x(1)]", (vLOCAL_FRM_Receive_Loop - 1), (vPARAM_FRM_Frame_To_Receive[vLOCAL_FRM_Receive_Loop]) ); vLOCAL_FRM_Receive_Counter ++; } } oFI2C_BUS_Stop(); printf("\r\n"); // Normally, ALWAYS cTRUE... return( vLOCAL_FRM_Receive_Counter == (tUBYTE)vPARAM_FRM_Frame_To_Receive[0] ); } /*--- START FUNCTION HEADER --------------------------------------------------*/ /* Name : oFI2C_DAT_Convert */ /* Role : Convert ASCII character to a displayable character on the disp mod */ /* Interface : IN Caract */ /* OUT oFI2C_DAT_Convert */ /* Pre-condition : None */ /* Constraints : None */ /* Behavior : */ /* DO */ /* [Convert the character] */ /* OD */ /*----------------------------------------------------------------------------*/ /* PROC oFI2C_DAT_Convert */ /* ( */ /* ) */ /* DATA */ /* 0x077 for A */ /* 0x07C for b */ /* 0x039 for c */ /* 0x05E for d */ /* 0x079 for E */ /* 0x071 for F */ /* 0x03D for G */ /* 0x076 for H */ /* 0x030 for I */ /* 0x01E for J */ /* 0x075 for k */ /* 0x038 for L */ /* 0x037 for M */ /* 0x054 for n */ /* 0x05C for o */ /* 0x073 for P */ /* 0x067 for q */ /* 0x050 for r */ /* 0x06D for S */ /* 0x078 for t */ /* 0x03E for U */ /* 0x01C for v */ /* 0x07E for W */ /* 0x076 for X */ /* 0x06E for y */ /* 0x05B for Z */ /* 0x03F for 0 */ /* 0x006 for 1 */ /* 0x05B for 2 */ /* 0x04F for 3 */ /* 0x066 for 4 */ /* 0x06D for 5 */ /* 0x07D for 6 */ /* 0x007 for 7 */ /* 0x07F for 8 */ /* 0x06F for 9 */ /* ATAD */ /* */ /* DO */ /* [Convert the character] = */ /* DO */ /* IF [Caract = [A-Z]] THEN */ /* [Select a charactere in [A-Z] in the display font] */ /* ELSE IF [Caract = [a-z]] THEN */ /* [Select a charactere in [A-Z] in the display font] */ /* ELSE IF [Caract = [0-9]] THEN */ /* [Select a charactere in [0-9] in the display font] */ /* ELSE */ /* [Display a space charactere] */ /* FI */ /* OD */ /* OD */ /*----------------------------------------------------------------------------*/ /*--- END FUNCTION HEADER ----------------------------------------------------*/ tUBYTE oFI2C::oFI2C_DAT_Convert(tUBYTE vPARAM_DAT_ASCII_Char) { tUBYTE oFI2C_DAT_Convert[]={ 0x077, // A 0x07C, // b 0x039, // c 0x05E, // d 0x079, // E 0x071, // F 0x03D, // G 0x076, // H 0x030, // I 0x01E, // J 0x075, // k 0x038, // L 0x037, // M 0x054, // n 0x05C, // o 0x073, // P 0x067, // q 0x050, // r 0x06D, // S 0x078, // t 0x03E, // U 0x01C, // v 0x07E, // W 0x076, // X 0x06E, // y 0x05B, // Z 0x03F, // 0 0x006, // 1 0x05B, // 2 0x04F, // 3 0x066, // 4 0x06D, // 5 0x07D, // 6 0x007, // 7 0x07F, // 8 0x06F // 9 }; if( (vPARAM_DAT_ASCII_Char >= 'A') && (vPARAM_DAT_ASCII_Char <= 'Z') ) { return(oFI2C_DAT_Convert[vPARAM_DAT_ASCII_Char - 'A']); } else if( (vPARAM_DAT_ASCII_Char >= 'a') && (vPARAM_DAT_ASCII_Char <= 'z') ) { return(oFI2C_DAT_Convert[vPARAM_DAT_ASCII_Char - 'a']); } else if( (vPARAM_DAT_ASCII_Char >= '0') && (vPARAM_DAT_ASCII_Char <= '9') ) { return(oFI2C_DAT_Convert[vPARAM_DAT_ASCII_Char - '0' + 26]); } else { return(0); // Space } } /*/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\*/ /*\ MAIN CODE /*/ /*/ \*/ /*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/*/ int main(void) { // oFI2C FRAME STRUCTURE // As the STANDARD I2C FRAME STRUCTURE, but with a 'PASCAL-like' header giving // the length of the parameters tail of the I2C FRAME... // Structure of a I2C frame // offset 0 - Length of the data tail after the I2C module address // 1 - I2C module address (look into each I2C components documentation) // x - Data tail, module's parameters (look into each I2C components documentation) #ifdef DISPLAY tUBYTE vLOCAL_MAIN_Display[] = {6, cADDR_I2CM_DISP, 0, 0x077, 1, 2, 4, 8}; #endif // DISPLAY #ifdef CLOCK tUBYTE vLOCAL_MAIN_WClock[] = {2, cADDR_I2CM_CLOCK, 0, 0}; tUBYTE vLOCAL_MAIN_RClock[] = {8, cADDR_I2CM_CLOCK, 0, 0, 0, 0, 0, 0, 0, 0}; #endif // CLOCK tUBYTE vLOCAL_MAIN_Keyb; // Keyboard buffer oFI2C Flux1(1); // Creating object Flux1 on LPT1 // --------------------------------------------------------------------- clrscr(); if(Flux1.oFI2C_BUS_Test() == cTRUE) // If I2C bus free { #ifdef CLOCK // RTC Clock part if(Flux1.oFI2C_FRM_Send(vLOCAL_MAIN_WClock) == cTRUE) { do { if(Flux1.oFI2C_FRM_Receive(vLOCAL_MAIN_RClock) = cTRUE) { // Some people could fine this way of typing a bit strange but don't worry, // in a while you'll not be able to read in another way anymore ;) // Thanks Marga.FP for the idea, it really makes things easier to read ! vLOCAL_MAIN_Display[4]=Flux1.oFI2C_DAT_Convert( ( ( vLOCAL_MAIN_RClock[4] >> 4 ) & 3 ) + '0' ); vLOCAL_MAIN_Display[5]=Flux1.oFI2C_DAT_Convert( ( vLOCAL_MAIN_RClock[4] & 0x00F ) + '0' ); vLOCAL_MAIN_Display[6]=Flux1.oFI2C_DAT_Convert( ( ( vLOCAL_MAIN_RClock[2] >> 4 ) & 0x00F ) + '0' ); vLOCAL_MAIN_Display[7]=Flux1.oFI2C_DAT_Convert( ( vLOCAL_MAIN_RClock[2] & 0x00F ) + '0' ); if(Flux1.oFI2C_FRM_Send(cADDR_I2CM_DISP) == cTRUE) { cout << "CLCK SEND OK" << endl; } else { cout << "CLCK SEND KO" << endl; } } else { cout << "CLCK RECEIVE KO" << endl; } } while(!kbhit()); } else { cout << "CLCK RESET KO" << endl; } #endif // CLOCK #ifdef DISPLAY // 7 SEG Display part do { vLOCAL_MAIN_Keyb = getch(); vLOCAL_MAIN_Display[4] = vLOCAL_MAIN_Display[5]; vLOCAL_MAIN_Display[5] = vLOCAL_MAIN_Display[6]; vLOCAL_MAIN_Display[6] = vLOCAL_MAIN_Display[7]; vLOCAL_MAIN_Display[7] = Flux1.oFI2C_DAT_Convert(vLOCAL_MAIN_Keyb); if(Flux1.oFI2C_FRM_Send(vLOCAL_MAIN_Display) == cTRUE) { cout << "DISP SEND OK" << endl; } else { cout << "DISP SEND KO" << endl; } } while(vLOCAL_MAIN_Keyb != 27); // [Esc] #endif // DISPLAY } else { cout << "I2C bus already in use..." << endl; } #ifdef RECEIVE if(Flux1.oFI2C_BUS_Test() == cTRUE) { if(Flux1.oFI2C_FRM_Receive(Flux) == cTRUE) { cout << "RECEIVE OK" << endl; } else { cout << "RECEIVE KO" << endl; } } else { cout << "I2C bus already in use..." << endl; } #endif // RECEIVE getch(); // Exit on 2nd keypress (after [ESC]) return 0; }
58.750867
105
0.231201
Kochise
f782d31f58d0659025581dbf9d78ec3776d5b27b
1,404
hpp
C++
src/common/deserializer.hpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
2
2020-06-01T00:30:12.000Z
2020-06-05T18:41:48.000Z
src/common/deserializer.hpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
null
null
null
src/common/deserializer.hpp
adlerjohn/ech-cpp-dev
60584994266b1c83e997e831238d14f5bd015e5a
[ "Apache-2.0" ]
1
2020-06-05T18:33:28.000Z
2020-06-05T18:33:28.000Z
#pragma once // System includes #include <cstddef> // Library includes #include "crypto/byteset.hpp" namespace ech { namespace deserializer { /** * Move bytes from the serialized representation directly into a byteset container. * @tparam T Type of byteset. * @param serial Serialized representation (will get modified). * @return Instance of T. */ template<class T> [[nodiscard]] const T move(std::deque<std::byte>& serial) { constexpr auto N = T::size(); static_assert(std::is_base_of<crypto::ByteSet<N>, T>::value, "must move to byteset or child"); if (serial.size() < N) { throw std::runtime_error("too few bytes when moving"); } auto bytes = std::array<std::byte, N>(); std::copy_n(serial.begin(), N, bytes.begin()); serial.erase(serial.begin(), serial.begin() + N); return T(bytes); } // TODO change this to vector with index for beginning if benchmarking is slow /** * Deserialize a primitive integer type. * @tparam T Type of integer. * @tparam B Size of integer, in bytes. * @param serial Serialized representation (will get modified). * @return Instance of T. */ template<class T, size_t B> [[nodiscard]] const T deserialize(std::deque<std::byte>& serial) { const auto bytes = move<crypto::byteset<B>>(serial); T t; for (const auto& byte : bytes) { t <<= 8; t |= static_cast<uint8_t>(byte); } return t; } } // namespace deserializer } // namespace ech
22.645161
95
0.689459
adlerjohn
f7834188171a3a029dfcf4507babef66a70d580c
1,846
cc
C++
chrome/browser/sync/glue/bridged_sync_notifier.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
7
2015-05-20T22:41:35.000Z
2021-11-18T19:07:59.000Z
chrome/browser/sync/glue/bridged_sync_notifier.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
1
2015-02-02T06:55:08.000Z
2016-01-20T06:11:59.000Z
chrome/browser/sync/glue/bridged_sync_notifier.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
2
2015-12-08T00:37:41.000Z
2017-04-06T05:34:05.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/bridged_sync_notifier.h" #include "chrome/browser/sync/glue/chrome_sync_notification_bridge.h" namespace browser_sync { BridgedSyncNotifier::BridgedSyncNotifier( ChromeSyncNotificationBridge* bridge, syncer::SyncNotifier* delegate) : bridge_(bridge), delegate_(delegate) { DCHECK(bridge_); } BridgedSyncNotifier::~BridgedSyncNotifier() { } void BridgedSyncNotifier::RegisterHandler( syncer::SyncNotifierObserver* handler) { if (delegate_.get()) delegate_->RegisterHandler(handler); bridge_->RegisterHandler(handler); } void BridgedSyncNotifier::UpdateRegisteredIds( syncer::SyncNotifierObserver* handler, const syncer::ObjectIdSet& ids) { if (delegate_.get()) delegate_->UpdateRegisteredIds(handler, ids); bridge_->UpdateRegisteredIds(handler, ids); } void BridgedSyncNotifier::UnregisterHandler( syncer::SyncNotifierObserver* handler) { if (delegate_.get()) delegate_->UnregisterHandler(handler); bridge_->UnregisterHandler(handler); } void BridgedSyncNotifier::SetUniqueId(const std::string& unique_id) { if (delegate_.get()) delegate_->SetUniqueId(unique_id); } void BridgedSyncNotifier::SetStateDeprecated(const std::string& state) { if (delegate_.get()) delegate_->SetStateDeprecated(state); } void BridgedSyncNotifier::UpdateCredentials( const std::string& email, const std::string& token) { if (delegate_.get()) delegate_->UpdateCredentials(email, token); } void BridgedSyncNotifier::SendNotification( syncer::ModelTypeSet changed_types) { if (delegate_.get()) delegate_->SendNotification(changed_types); } } // namespace browser_sync
27.969697
73
0.756771
Crystalnix
f786d644e7ad3bc178847d7615ea71bb0031e382
1,637
cc
C++
dreal/util/math.cc
soonhokong/dreal4
573e613560f5dce9ad54a2f685e060fe447310c7
[ "Apache-2.0" ]
104
2017-12-07T18:17:35.000Z
2022-03-31T06:58:13.000Z
dreal/util/math.cc
soonhokong/dreal4
573e613560f5dce9ad54a2f685e060fe447310c7
[ "Apache-2.0" ]
250
2017-09-01T01:32:45.000Z
2022-03-29T04:08:00.000Z
dreal/util/math.cc
soonhokong/dreal4
573e613560f5dce9ad54a2f685e060fe447310c7
[ "Apache-2.0" ]
16
2018-01-07T07:40:11.000Z
2022-03-24T05:01:11.000Z
/* Copyright 2017 Toyota Research Institute 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 "dreal/util/math.h" #include <cmath> #include <iostream> #include <limits> #include "dreal/util/exception.h" using std::int64_t; using std::modf; using std::numeric_limits; namespace dreal { bool is_integer(const double v) { // v should be in [int_min, int_max]. if (!((numeric_limits<int>::lowest() <= v) && (v <= numeric_limits<int>::max()))) { return false; } double intpart{}; // dummy variable return modf(v, &intpart) == 0.0; } int convert_int64_to_int(const int64_t v) { if (numeric_limits<int>::min() <= v && v <= numeric_limits<int>::max()) { return v; } else { throw DREAL_RUNTIME_ERROR("Fail to convert a int64_t value {} to int", v); } } double convert_int64_to_double(const int64_t v) { constexpr int64_t m{ 1UL << static_cast<unsigned>(numeric_limits<double>::digits)}; if (-m <= v && v <= m) { return v; } else { throw DREAL_RUNTIME_ERROR("Fail to convert a int64_t value {} to double", v); } } } // namespace dreal
27.745763
78
0.672572
soonhokong
f789d012cdd9b34ab369479ed2d5fb485542781a
10,372
cpp
C++
src/tools/kdb/cmdline.cpp
0003088/libelektra-qt-gui-test
f127a7bd4daba1b70e1ea0ce13d8ff650beda5b6
[ "BSD-3-Clause" ]
null
null
null
src/tools/kdb/cmdline.cpp
0003088/libelektra-qt-gui-test
f127a7bd4daba1b70e1ea0ce13d8ff650beda5b6
[ "BSD-3-Clause" ]
null
null
null
src/tools/kdb/cmdline.cpp
0003088/libelektra-qt-gui-test
f127a7bd4daba1b70e1ea0ce13d8ff650beda5b6
[ "BSD-3-Clause" ]
null
null
null
#include <cmdline.hpp> #include <kdb.hpp> #include <keysetio.hpp> #include <kdbconfig.h> #include <iostream> #include <vector> #include <cstdio> #include <set> #include <getopt.h> #include <command.hpp> using namespace std; Cmdline::Cmdline (int argc, char** argv, Command *command ) : helpText(), invalidOpt(false), /*XXX: Step 2: initialise your option here.*/ debug(), force(), load(), humanReadable(), help(), interactive(), noNewline(), test(), recursive(), resolver(KDB_DEFAULT_RESOLVER), strategy("preserve"), verbose(), version(), withoutElektra(), null(), first(true), second(true), third(true), all(), format("dump"), plugins("sync"), pluginsConfig(""), ns("user"), executable(), commandName() { extern int optind; extern char *optarg; int index = 0; int opt; size_t optionPos; synopsis = command->getSynopsis(); helpText += command->getShortHelpText(); helpText += "\n"; helpText += command->getLongHelpText(); helpText += "\n"; string allOptions = command->getShortOptions(); allOptions += "HV"; std::set<string::value_type> unique_sorted_chars (allOptions.begin(), allOptions.end()); string acceptedOptions (unique_sorted_chars.begin(), unique_sorted_chars.end()); vector<option> long_options; /*XXX: Step 3: give it a long name.*/ if (acceptedOptions.find('a')!=string::npos) { option o = {"all", no_argument, 0, 'a'}; long_options.push_back(o); helpText += "-a --all Consider all of the keys.\n"; } if (acceptedOptions.find('d')!=string::npos) { option o = {"debug", no_argument, 0, 'd'}; long_options.push_back(o); helpText += "-d --debug Give debug information or ask debug questions (in interactive mode).\n"; } if (acceptedOptions.find('f')!=string::npos) { option o = {"force", no_argument, 0, 'f'}; long_options.push_back(o); helpText += "-f --force Force the action to be done.\n"; } if (acceptedOptions.find('l')!=string::npos) { option o = {"load", no_argument, 0, 'f'}; long_options.push_back(o); helpText += "-l --load Load plugin even if system/elektra is available\n"; } if (acceptedOptions.find('h')!=string::npos) { option o = {"human-readable", no_argument, 0, 'h'}; long_options.push_back(o); helpText += "-h --human-readable Print numbers in an human readable way\n"; } if (acceptedOptions.find('H')!=string::npos) { option o = {"help", no_argument, 0, 'H'}; long_options.push_back(o); helpText += "-H --help Print help text.\n"; } if (acceptedOptions.find('i')!=string::npos) { option o = {"interactive", no_argument, 0, 'i'}; long_options.push_back(o); helpText += "-i --interactive Instead of passing all information by parameters\n"; helpText += " ask the user interactively.\n"; } if (acceptedOptions.find('n')!=string::npos) { option o = {"no-newline", no_argument, 0, 'n'}; long_options.push_back(o); helpText += "-n --no-newline Suppress the newline at the end of the output.\n"; } if (acceptedOptions.find('t')!=string::npos) { option o = {"test", no_argument, 0, 't'}; long_options.push_back(o); helpText += "-t --test Test.\n"; } if (acceptedOptions.find('r')!=string::npos) { option o = {"recursive", no_argument, 0, 'r'}; long_options.push_back(o); helpText += "-r --recursive Work in a recursive mode.\n"; } optionPos = acceptedOptions.find('R'); if (optionPos!=string::npos) { acceptedOptions.insert(optionPos+1, ":"); option o = {"resolver", required_argument, 0, 'R'}; long_options.push_back (o); helpText += "-R --resolver <name> Specify the resolver plugin to use\n" " if no resolver is given, the default resolver is used.\n" ""; } optionPos = acceptedOptions.find('s'); if (optionPos!=string::npos) { acceptedOptions.insert(optionPos+1, ":"); option o = {"strategy", required_argument, 0, 's'}; long_options.push_back(o); helpText += "-s --strategy <name> Specify which strategy should be used to resolve conflicts.\n" " More precisely, strategies are used to handle deviations from the\n" " base version of a key.\n" " When and which strategies are used and what they do depends\n" " mostly on the used base KeySet.\n\n" " Note: For a two-way merge, the `ours` version of the keys is used\n" " in place of `base`\n\n" " Currently the following strategies exist\n" " preserve .. automerge only those keys where just one\n" " side deviates from base (default)\n" " ours .. like preserve, but in case of conflict use our version\n" " theirs .. like preserve, but in case of conflict use their version\n" " cut .. primarily used for import. removes existing keys below\n" " the import point and always takes the imported version\n" " import .. primarily used for import. preserves existing keys if\n" " they do not exist in the imported keyset. in all other\n" " cases the imported keys have precedence\n" ""; } if (acceptedOptions.find('v')!=string::npos) { option o = {"verbose", no_argument, 0, 'v'}; long_options.push_back(o); helpText += "-v --verbose Explain what is happening.\n"; } if (acceptedOptions.find('V')!=string::npos) { option o = {"version", no_argument, 0, 'V'}; long_options.push_back(o); helpText += "-V --version Print version info.\n"; } if (acceptedOptions.find('E')!=string::npos) { option o = {"without-elektra", no_argument, 0, 'E'}; long_options.push_back(o); helpText += "-E --without-elektra Omit the `system/elektra` directory.\n"; } if (acceptedOptions.find('0')!=string::npos) { option o = {"null", no_argument, 0, '0'}; long_options.push_back(o); helpText += "-0 --null Use binary 0 termination.\n"; } if (acceptedOptions.find('1')!=string::npos) { option o = {"first", no_argument, 0, '1'}; long_options.push_back(o); helpText += "-1 --first Suppress the first column.\n"; } if (acceptedOptions.find('2')!=string::npos) { option o = {"second", no_argument, 0, '2'}; long_options.push_back(o); helpText += "-2 --second Suppress the second column.\n"; } if (acceptedOptions.find('3')!=string::npos) { option o = {"third", no_argument, 0, '3'}; long_options.push_back(o); helpText += "-3 --third Suppress the third column.\n"; } optionPos = acceptedOptions.find('N'); if (acceptedOptions.find('N')!=string::npos) { acceptedOptions.insert(optionPos+1, ":"); option o = {"namespace", required_argument, 0, 'N'}; long_options.push_back(o); helpText += "-N --namespace ns Specify the namespace to use when writing cascading keys\n" " Default: value of /sw/kdb/current/namespace or user.\n"; } optionPos = acceptedOptions.find('c'); if (optionPos!=string::npos) { acceptedOptions.insert(optionPos+1, ":"); option o = {"plugins-config", no_argument, 0, 'c'}; long_options.push_back(o); helpText += "-c --plugins-config Add a plugin configuration.\n"; } { using namespace kdb; /*XXX: Step 4: use default from KDB, if available.*/ std::string dirname = "/sw/kdb/current/"; KDB kdb; KeySet conf; kdb.get(conf, std::string("user")+dirname); kdb.get(conf, std::string("system")+dirname); Key k; k = conf.lookup(dirname+"resolver"); if (k) resolver = k.get<string>(); k = conf.lookup(dirname+"format"); if (k) format = k.get<string>(); k = conf.lookup(dirname+"plugins"); if (k) plugins = k.get<string>(); k = conf.lookup(dirname+"namespace"); if (k) ns = k.get<string>(); } option o = {0, 0, 0, 0}; long_options.push_back(o); executable = argv[0]; commandName = argv[1]; while ((opt = getopt_long (argc, argv, acceptedOptions.c_str(), &long_options[0], &index)) != EOF) { switch (opt) { /*XXX: Step 5: and now process the option.*/ case 'a': all = true; break; case 'd': debug = true; break; case 'f': force = true; break; case 'h': humanReadable = true; break; case 'l': load= true; break; case 'H': help = true; break; case 'i': interactive = true; break; case 'n': noNewline = true; break; case 't': test = true; break; case 'r': recursive = true; break; case 'R': resolver = optarg; break; case 's': strategy = optarg; break; case 'v': verbose = true; break; case 'V': version = true; break; case 'E': withoutElektra= true; break; case '0': null= true; break; case '1': first= false; break; case '2': second= false; break; case '3': third= false; break; case 'N': ns = optarg; break; case 'c': pluginsConfig = optarg; break; default: invalidOpt = true; break; } } optind++; // skip the command name while (optind < argc) { arguments.push_back(argv[optind++]); } } kdb::KeySet Cmdline::getPluginsConfig(string basepath) const { using namespace kdb; string keyName; string value; KeySet ret; istringstream sstream(pluginsConfig); // read until the next '=', this will be the keyname while (std::getline (sstream, keyName, '=')) { // read until a ',' or the end of line // if nothing is read because the '=' is the last character // in the config string, consider the value empty if (!std::getline (sstream, value, ',')) value = ""; Key configKey = Key (basepath + keyName, KEY_END); configKey.setString (value); ret.append (configKey); } return ret; } std::ostream & operator<< (std::ostream & os, Cmdline & cl) { if (cl.invalidOpt) { os << "Invalid option given\n" << endl; } os << "Usage: " << cl.executable << " " << cl.commandName << " " << cl.synopsis; os << "\n\n" << cl.helpText; return os; }
30.505882
118
0.595546
0003088
f791bac48d9a86b81a4a355f9d91beaa51ed14db
7,146
hpp
C++
tests/performance/opencl/util/cl_tests.hpp
STEllAR-GROUP/hpxcl
1d5fd791016548856d65866f64ca169778402c4f
[ "BSL-1.0" ]
30
2015-10-01T16:15:02.000Z
2022-03-17T12:21:47.000Z
tests/performance/opencl/util/cl_tests.hpp
STEllAR-GROUP/hpxcl
1d5fd791016548856d65866f64ca169778402c4f
[ "BSL-1.0" ]
50
2015-06-21T01:05:34.000Z
2021-08-06T18:20:54.000Z
tests/performance/opencl/util/cl_tests.hpp
STEllAR-GROUP/hpxcl
1d5fd791016548856d65866f64ca169778402c4f
[ "BSL-1.0" ]
23
2015-03-18T11:18:36.000Z
2021-12-27T16:36:32.000Z
// Copyright (c) 2013 Martin Stumpf // // 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 <hpx/config.hpp> #include <hpx/hpx.hpp> #include <hpx/hpx_init.hpp> #include <hpx/util/lightweight_test.hpp> //#include <hpx/util/static.hpp> #include <hpx/include/iostreams.hpp> #include <hpxcl/opencl.hpp> #include "testresults.hpp" using boost::program_options::options_description; using boost::program_options::value; using boost::program_options::variables_map; // the formatter for the test results hpx::opencl::tests::performance::testresults results; // global variables static std::size_t num_iterations = 0; static std::size_t testdata_size = 0; // the main test function static void cl_test(hpx::opencl::device, hpx::opencl::device, bool distributed); #define die(message) \ { HPX_THROW_EXCEPTION(hpx::no_success, "die()", (message)); } #define CREATE_BUFFER(name, data) \ static const buffer_type name(data, sizeof(data), \ buffer_type::init_mode::reference) #define COMPARE_RESULT_INT(result_data, correct_result) \ { \ auto lhs = result_data; \ auto rhs = correct_result; \ if (lhs.size() != rhs.size()) { \ die("Result is incorrect! (Sizes don't match)"); \ } \ for (std::size_t i = 0; i < lhs.size(); i++) { \ std::cerr << std::hex << lhs[i] << "-" << rhs[i] << std::endl; \ if (lhs[i] != rhs[i]) { \ die("Result is incorrect!"); \ } \ } typedef hpx::serialization::serialize_buffer<char> buffer_type; typedef hpx::serialization::serialize_buffer<uint32_t> intbuffer_type; std::string to_string(buffer_type buf) { std::size_t length = 0; while (length < buf.size()) { if (buf[length] == '\0') break; length++; } return std::string(buf.data(), buf.data() + length); } #define COMPARE_RESULT(result_data, correct_result) \ { \ auto lhs = result_data; \ auto rhs = correct_result; \ if (lhs.size() != rhs.size()) { \ die("Result is incorrect! (Sizes don't match)"); \ } \ std::string correct_string = to_string(rhs); \ std::string result_string = to_string(lhs); \ if (correct_string != result_string) { \ die("Result is incorrect!"); \ } \ } static void print_testdevice_info(hpx::opencl::device& cldevice, std::size_t device_id, std::size_t num_devices) { // Test whether get_device_info works std::string version = cldevice.get_device_info<CL_DEVICE_VERSION>().get(); // Write Info Code std::cerr << "Device ID: " << device_id << " / " << num_devices << std::endl; std::cerr << "Device GID: " << cldevice.get_id() << std::endl; std::cerr << "Version: " << version << std::endl; std::cerr << "Name: " << cldevice.get_device_info<CL_DEVICE_NAME>().get() << std::endl; std::cerr << "Vendor: " << cldevice.get_device_info<CL_DEVICE_VENDOR>().get() << std::endl; std::cerr << "Profile: " << cldevice.get_device_info<CL_DEVICE_PROFILE>().get() << std::endl; } static std::vector<hpx::opencl::device> init(variables_map& vm) { std::size_t device_id = 0; if (vm.count("deviceid")) device_id = vm["deviceid"].as<std::size_t>(); // Try to get remote devices std::vector<hpx::opencl::device> remote_devices = hpx::opencl::create_remote_devices(CL_DEVICE_TYPE_ALL, "OpenCL 1.1") .get(); std::vector<hpx::opencl::device> local_devices = hpx::opencl::create_local_devices(CL_DEVICE_TYPE_ALL, "OpenCL 1.1").get(); if (remote_devices.empty()) { remote_devices = local_devices; std::cerr << "WARNING: no remote devices found!" << std::endl; } if (local_devices.empty()) die("No local devices found!"); if (remote_devices.empty()) die("No remote devices found!"); if (local_devices.size() <= device_id || remote_devices.size() <= device_id) die("deviceid is out of range!"); // Choose device hpx::opencl::device local_device = local_devices[device_id]; hpx::opencl::device remote_device = remote_devices[device_id]; // Print info std::cerr << "Local device:" << std::endl; print_testdevice_info(local_device, device_id, local_devices.size()); if (local_device.get_id() != remote_device.get_id()) { std::cerr << "Remote device:" << std::endl; print_testdevice_info(remote_device, device_id, remote_devices.size()); } // return the devices std::vector<hpx::opencl::device> devices; devices.push_back(local_device); devices.push_back(remote_device); return devices; } int hpx_main(variables_map& vm) { { if (vm.count("format")) { std::string format = vm["format"].as<std::string>(); if (format == "json") results.set_output_json(); else if (format == "tabbed") results.set_output_tabbed(); else die("Format '" + format + "' not supported!"); } if (vm.count("enable")) { results.set_enabled_tests(vm["enable"].as<std::vector<std::string> >()); } if (vm.count("size")) { testdata_size = vm["size"].as<std::size_t>(); } if (vm.count("iterations")) { num_iterations = vm["iterations"].as<std::size_t>(); } auto devices = init(vm); std::cerr << std::endl; cl_test(devices[0], devices[1], devices[0].get_id() != devices[1].get_id()); std::cerr << std::endl; std::cout << results; std::cerr << std::endl; } hpx::finalize(); return hpx::util::report_errors(); } /////////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { // Configure application-specific options options_description cmdline("Usage: " HPX_APPLICATION_STRING " [options]"); cmdline.add_options()("deviceid", value<std::size_t>()->default_value(0), "the ID of the device we will run our tests on")( "iterations", value<std::size_t>()->default_value(0), "the number of iterations every test shall get executed")( "size", value<std::size_t>()->default_value(0), "the size of the test data")( "format", value<std::string>(), "Formats the output in a certain way.\nSupports: json, tabbed")( "enable", value<std::vector<std::string> >(), "only enables certain tests"); return hpx::init(cmdline, argc, argv); }
37.809524
80
0.565911
STEllAR-GROUP
f7927b77ea3c9b173b3e2f973dff416745f85fa0
11,329
cpp
C++
implementations/ugene/src/plugins/biostruct3d_view/src/deprecated/BioStruct3DColorScheme.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/biostruct3d_view/src/deprecated/BioStruct3DColorScheme.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/biostruct3d_view/src/deprecated/BioStruct3DColorScheme.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BioStruct3DColorScheme.h" #include <QObject> #include <U2Core/AnnotationSettings.h> #include <U2Core/AnnotationTableObject.h> #include <U2Core/AppContext.h> #include <U2Core/BioStruct3DObject.h> #include <U2Core/DocumentModel.h> #include <U2Core/FeatureColors.h> #include <U2Core/GObjectRelationRoles.h> #include <U2Core/GObjectUtils.h> #include <U2Core/U2SafePoints.h> namespace U2 { /* class BioStruct3DColorSchemeRegistry */ const QString BioStruct3DColorSchemeRegistry::defaultFactoryName() { return SecStructColorScheme::schemeName; } const QList<QString> BioStruct3DColorSchemeRegistry::factoriesNames() { return getInstance()->factories.keys(); } const BioStruct3DColorSchemeFactory *BioStruct3DColorSchemeRegistry::getFactory(const QString &name) { return getInstance()->factories.value(name, 0); } BioStruct3DColorScheme *BioStruct3DColorSchemeRegistry::createColorScheme(const QString &name, const BioStruct3DObject *biostruct) { const BioStruct3DColorSchemeFactory *fact = getFactory(name); if (fact) { return fact->createInstance(biostruct); } return 0; } BioStruct3DColorSchemeRegistry::BioStruct3DColorSchemeRegistry() { registerFactories(); } BioStruct3DColorSchemeRegistry *BioStruct3DColorSchemeRegistry::getInstance() { static BioStruct3DColorSchemeRegistry *reg = new BioStruct3DColorSchemeRegistry(); return reg; } #define REGISTER_FACTORY(c) factories.insert(c::schemeName, new c::Factory) void BioStruct3DColorSchemeRegistry::registerFactories() { REGISTER_FACTORY(ChainsColorScheme); REGISTER_FACTORY(SecStructColorScheme); REGISTER_FACTORY(ChemicalElemColorScheme); REGISTER_FACTORY(SimpleColorScheme); } const QString ChainsColorScheme::schemeName(QObject::tr("Molecular Chains")); const QString ChemicalElemColorScheme::schemeName(QObject::tr("Chemical Elements")); const QString SecStructColorScheme::schemeName(QObject::tr("Secondary Structure")); const QString SimpleColorScheme::schemeName(QObject::tr("Simple colors")); /*class BioStruct3DColorScheme */ BioStruct3DColorScheme::BioStruct3DColorScheme(const BioStruct3DObject *biostruct) : defaultAtomColor(0.25f, 0.25f, 0.25f), selectionColor(1.0f, 1.0f, 0), selection(biostruct->getBioStruct3D()), unselectedShading(0.0) { } Color4f BioStruct3DColorScheme::getAtomColor(const SharedAtom &atom) const { Color4f c; if (isInSelection(atom)) { c = selectionColor; } else { c = getSchemeAtomColor(atom); if (!selection.isEmpty() && unselectedShading > 0.0) { // dim unselected c[3] *= (1.0 - unselectedShading); } } return c; } void BioStruct3DColorScheme::setSelectionColor(QColor color) { this->selectionColor = color; } void BioStruct3DColorScheme::setUnselectedShadingLevel(float shading) { assert(shading >= 0.0 && shading <= 1.0); unselectedShading = shading; } void BioStruct3DColorScheme::updateSelectionRegion(int chainId, const QVector<U2Region> &added, const QVector<U2Region> &removed) { selection.update(chainId, added, removed); } bool BioStruct3DColorScheme::isInSelection(const SharedAtom &atom) const { return selection.inSelection(atom->chainIndex, atom->residueIndex.toInt()); } Color4f BioStruct3DColorScheme::getSchemeAtomColor(const SharedAtom &) const { return defaultAtomColor; } /////////////////////////////////////////////////////////////////////////////////////////// // ChemicalElemColorScheme Color4f ChemicalElemColorScheme::getSchemeAtomColor(const SharedAtom &a) const { Color4f color; if (elementColorMap.contains(a->atomicNumber)) { return elementColorMap.value(a->atomicNumber); } else { return defaultAtomColor; } } ChemicalElemColorScheme::ChemicalElemColorScheme(const BioStruct3DObject *biostruct) : BioStruct3DColorScheme(biostruct) { //CPK colors elementColorMap.insert(1, Color4f(1.0f, 1.0f, 1.0f)); elementColorMap.insert(6, Color4f(0.8f, 0.8f, 0.8f)); elementColorMap.insert(7, Color4f(0.7f, 0.7f, 1.0f)); elementColorMap.insert(8, Color4f(0.95f, 0.0f, 0.0f)); elementColorMap.insert(11, Color4f(0.0f, 0.0f, 1.0f)); elementColorMap.insert(12, Color4f(0.16f, 0.5f, 0.16f)); elementColorMap.insert(15, Color4f(1.0f, 0.63f, 0.0f)); elementColorMap.insert(16, Color4f(1.0f, 0.8f, 0.2f)); elementColorMap.insert(17, Color4f(0.0f, 1.0f, 0.0f)); elementColorMap.insert(20, Color4f(0.5f, 0.5f, 0.5f)); elementColorMap.insert(26, Color4f(1.0f, 0.63f, 0.0f)); elementColorMap.insert(30, Color4f(0.63f, 0.2f, 0.2f)); elementColorMap.insert(35, Color4f(0.63f, 0.2f, 0.2f)); } /* class ChainsColorScheme : public BioStruct3DColorScheme */ const QMap<int, QColor> ChainsColorScheme::getChainColors(const BioStruct3DObject *biostructObj) { QMap<int, QColor> colorMap; if (NULL != biostructObj->getDocument()) { QList<GObject *> aObjs = GObjectUtils::selectRelationsFromParentDoc(biostructObj, GObjectTypes::ANNOTATION_TABLE, ObjectRole_AnnotationTable); foreach (GObject *obj, aObjs) { AnnotationTableObject *ao = qobject_cast<AnnotationTableObject *>(obj); SAFE_POINT(NULL != ao, "Invalid annotation table!", colorMap); foreach (Annotation *a, ao->getAnnotationsByName(BioStruct3D::MoleculeAnnotationTag)) { QString chainQualifier = a->findFirstQualifierValue(BioStruct3D::ChainIdQualifierName); SAFE_POINT(chainQualifier.size() == 1, "Invalid chain id qualifier", colorMap); const char chainId = chainQualifier.toLatin1().at(0); const int index = biostructObj->getBioStruct3D().getIndexByChainId(chainId); SAFE_POINT(index >= 0, QString("Invalid chain id: %1").arg(chainId), colorMap); const QColor color = FeatureColors::genLightColor(QString("chain_%1").arg(index)); colorMap.insert(index, color); } } } return colorMap; } ChainsColorScheme::ChainsColorScheme(const BioStruct3DObject *biostruct) : BioStruct3DColorScheme(biostruct) { const QMap<int, QColor> chainColors = getChainColors(biostruct); if (!chainColors.empty()) { QMapIterator<int, QColor> i(chainColors); while (i.hasNext()) { i.next(); chainColorMap.insert(i.key(), Color4f(i.value())); } } } Color4f ChainsColorScheme::getSchemeAtomColor(const SharedAtom &atom) const { Color4f color; if (chainColorMap.contains(atom->chainIndex)) { return chainColorMap.value(atom->chainIndex); } else { return defaultAtomColor; } } /* class SecStructColorScheme : public BioStruct3DColorScheme */ const QMap<QString, QColor> SecStructColorScheme::getSecStructAnnotationColors(const BioStruct3DObject *biostruct) { QMap<QString, QColor> colors; AnnotationSettingsRegistry *asr = AppContext::getAnnotationsSettingsRegistry(); Document *doc = biostruct->getDocument(); if (doc) { QList<GObject *> targetAnnotations = GObjectUtils::selectRelationsFromParentDoc(biostruct, GObjectTypes::ANNOTATION_TABLE, ObjectRole_AnnotationTable); foreach (GObject *obj, targetAnnotations) { AnnotationTableObject *ao = qobject_cast<AnnotationTableObject *>(obj); SAFE_POINT(NULL != ao, "Invalid annotation table!", colors); foreach (Annotation *a, ao->getAnnotationsByName(BioStruct3D::SecStructAnnotationTag)) { QString ssName = a->getQualifiers().first().value; AnnotationSettings *as = asr->getAnnotationSettings(ssName); colors.insert(ssName, as->color); } } } return colors; } SecStructColorScheme::SecStructColorScheme(const BioStruct3DObject *biostruct) : BioStruct3DColorScheme(biostruct) { defaultAtomColor = Color4f(0.5f, 0.9f, 0.9f); const QMap<QString, QColor> secStrucColors = getSecStructAnnotationColors(biostruct); if (!secStrucColors.isEmpty()) { QMapIterator<QString, QColor> i(secStrucColors); while (i.hasNext()) { i.next(); secStrucColorMap.insert(i.key().toLatin1(), Color4f(i.value())); } foreach (const SharedSecondaryStructure &struc, biostruct->getBioStruct3D().secondaryStructures) { for (int index = struc->startSequenceNumber; index <= struc->endSequenceNumber; ++index) { QByteArray type = BioStruct3D::getSecStructTypeName(struc->type).toLatin1(); Q_ASSERT(secStrucColorMap.contains(type)); Q_ASSERT(struc->chainIndex != 0); molMap[struc->chainIndex].strucResidueTable.insert(index, type); } } #ifdef _DEBUG // Verify indices with biostruct3d const BioStruct3D &bioStruc = biostruct->getBioStruct3D(); QMapIterator<int, MolStructs> iter(molMap); while (iter.hasNext()) { iter.next(); assert(bioStruc.moleculeMap.contains(iter.key())); } #endif } } Color4f SecStructColorScheme::getSchemeAtomColor(const SharedAtom &atom) const { Color4f c = defaultAtomColor; int residueIndex = atom->residueIndex.toInt(); if (molMap.contains(atom->chainIndex)) { const QHash<int, QByteArray> &residueTable = molMap.value(atom->chainIndex).strucResidueTable; if (residueTable.contains(residueIndex)) { QByteArray type = residueTable.value(residueIndex); c = secStrucColorMap.value(type); } } return c; } /* class SimpleColorScheme : public BioStruct3DColorScheme */ QVector<Color4f> SimpleColorScheme::colors; void SimpleColorScheme::createColors() { if (colors.isEmpty()) { // rainbow colors colors.append(Color4f(QColor(0xff, 0x00, 0x00))); colors.append(Color4f(QColor(0xff, 0x7f, 0x00))); colors.append(Color4f(QColor(0xff, 0xff, 0x00))); colors.append(Color4f(QColor(0x00, 0xff, 0x00))); colors.append(Color4f(QColor(0x00, 0xff, 0xff))); colors.append(Color4f(QColor(0x00, 0x00, 0xff))); colors.append(Color4f(QColor(0x8b, 0x00, 0xff))); } } SimpleColorScheme::SimpleColorScheme(const BioStruct3DObject *biostruct) : BioStruct3DColorScheme(biostruct) { createColors(); static int idx = 0; defaultAtomColor = colors[(idx++) % colors.size()]; } } // namespace U2
37.763333
159
0.696708
r-barnes
f7942f03328ecfd2ca4febc685efc7f233f1a4ed
964
cpp
C++
Codigos de ejercicios en cpp/Programa 12.cpp
EulisesBrazon/ejercicios-c-
700235bced91bc6f508ca6d203ea7ee7c241006c
[ "Apache-2.0" ]
null
null
null
Codigos de ejercicios en cpp/Programa 12.cpp
EulisesBrazon/ejercicios-c-
700235bced91bc6f508ca6d203ea7ee7c241006c
[ "Apache-2.0" ]
null
null
null
Codigos de ejercicios en cpp/Programa 12.cpp
EulisesBrazon/ejercicios-c-
700235bced91bc6f508ca6d203ea7ee7c241006c
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<stdio.h> #include<conio.h> using namespace std; int main() { double L1,L2,L3,n=1,Mayor; cout<<"Ingrese el primer lado del triangulo"<<endl; cin>>L1; cout<<"Ingrese el segundo lado del triangulo"<<endl; cin>>L2; cout<<"Ingrese el tercer lado del triangulo"<<endl; cin>>L3; if((L1>L2)&&(L1>L3)) Mayor=L1; else if(L2>L3) Mayor=L2; else Mayor=L3; if(Mayor==L1) { if((L2+L3)<=L1) { cout<<"el triangulo es invalido"<<endl; n=0; } }else if(Mayor==L2) { if((L1+L3)<=L2) { cout<<"el triangulo es invalido"<<endl; n=0; } }else if(Mayor==L3) { if((L1+L2)<=L3) { cout<<"el triangulo es invalido"<<endl; n=0; } } if (n==1) { if ((L1==L2)&&(L2==L3)) cout<<"Es un triangulo equilatero"<<endl; else if(L1!=L2&&L1!=L3&&L3!=L2) cout<<"Es un triangulo escaleno"<<endl; else cout<<"Es un triangulo isosceles"<<endl; } getch(); return 0; }
17.851852
53
0.572614
EulisesBrazon
f794806f6daf1d60c7d9ad9bdaf5dc58b2a5450f
393
cpp
C++
NaoTHSoccer/Source/Representations/Modeling/CollisionModel.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NaoTHSoccer/Source/Representations/Modeling/CollisionModel.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NaoTHSoccer/Source/Representations/Modeling/CollisionModel.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#include "CollisionModel.h" CollisionModel::CollisionModel() : isColliding(false) { } CollisionModel::~CollisionModel() { } void CollisionModel::print(std::ostream &stream) const { stream << "isColliding=" << (isColliding ? "true" : "false") << std::endl; if(isColliding) { stream << "collision start " << collisionStartTime.getTimeInSeconds() << std::endl; } }
16.375
76
0.651399
tarsoly
f79725302d4d94781cfb35fbb28fd721dc9a7216
6,422
hpp
C++
src/framework/utils/worker/worker.hpp
abelov-spirent/openperf
303b6b5534973ea145a8223a55ee7b65e7464e25
[ "Apache-2.0" ]
null
null
null
src/framework/utils/worker/worker.hpp
abelov-spirent/openperf
303b6b5534973ea145a8223a55ee7b65e7464e25
[ "Apache-2.0" ]
null
null
null
src/framework/utils/worker/worker.hpp
abelov-spirent/openperf
303b6b5534973ea145a8223a55ee7b65e7464e25
[ "Apache-2.0" ]
null
null
null
#ifndef _OP_UTILS_WORKER_HPP_ #define _OP_UTILS_WORKER_HPP_ #include <memory> #include <zmq.h> #include <thread> #include <forward_list> #include <atomic> #include <cstring> #include <optional> #include "core/op_core.h" #include "core/op_thread.h" #include "utils/worker/task.hpp" namespace openperf::utils::worker { class workable { public: virtual ~workable() = default; virtual void start() = 0; virtual void start(int core) = 0; virtual void stop() = 0; virtual void pause() = 0; virtual void resume() = 0; virtual bool is_paused() const = 0; virtual bool is_running() const = 0; virtual bool is_finished() const = 0; }; // Worker Template template <class T> class worker final : public workable { private: struct message { bool stop = true; bool pause = true; std::optional<typename T::config_t> config; }; private: constexpr static auto m_endpoint = "inproc://worker-p2p"; bool m_paused = true; bool m_stopped = true; typename T::config_t m_config; std::unique_ptr<T> m_task; void* m_zmq_context; std::unique_ptr<void, op_socket_deleter> m_zmq_socket; std::thread m_thread; std::string m_thread_name; int16_t m_core; public: worker(worker&&); worker(const worker&) = delete; explicit worker(const typename T::config_t&, std::string_view thread_name = "uworker"); ~worker(); void start() override; void start(int core_id) override; void stop() override; void pause() override; void resume() override; bool is_paused() const override { return m_paused; } bool is_running() const override { return !(m_paused || m_stopped); } bool is_finished() const override { return m_stopped; } typename T::config_t config() const { return m_task->config(); } typename T::stat_t stat() const { return m_task->stat(); }; void clear_stat() { m_task->clear_stat(); } void config(const typename T::config_t&); private: void loop(); void update(); void send_message(const worker::message&); }; // Constructors & Destructor template <class T> worker<T>::worker(const typename T::config_t& c, std::string_view name) : m_paused(true) , m_stopped(true) , m_config(c) , m_task(new T) , m_zmq_context(zmq_init(0)) , m_zmq_socket(op_socket_get_server(m_zmq_context, ZMQ_PUSH, m_endpoint)) , m_thread_name(name) , m_core(-1) {} template <class T> worker<T>::worker(worker&& w) : m_paused(w.m_paused) , m_stopped(w.m_stopped) , m_config(std::move(w.m_config)) , m_task(std::move(w.m_task)) , m_zmq_context(std::move(w.m_zmq_context)) , m_zmq_socket(std::move(w.m_zmq_socket)) , m_thread(std::move(w.m_thread)) , m_thread_name(std::move(w.m_thread_name)) , m_core(w.m_core) {} template <class T> worker<T>::~worker() { if (m_thread.joinable()) { m_stopped = true; m_paused = false; update(); m_thread.detach(); } zmq_close(m_zmq_socket.get()); zmq_ctx_shutdown(m_zmq_context); zmq_ctx_term(m_zmq_context); } // Methods : public template <class T> void worker<T>::start(int core_id) { m_core = core_id; start(); } template <class T> void worker<T>::start() { static std::atomic_uint thread_number = 0; if (!m_stopped) return; m_stopped = false; m_thread = std::thread([this]() { // Set Thread name op_thread_setname( ("op_" + m_thread_name + "_" + std::to_string(++thread_number)) .c_str()); // Set Thread core affinity, if specified if (m_core >= 0) if (auto err = op_thread_set_affinity(m_core)) OP_LOG(OP_LOG_ERROR, "Cannot set worker thread affinity: %s", std::strerror(err)); loop(); }); config(m_config); } template <class T> void worker<T>::stop() { if (m_stopped) return; send_message(worker::message{.stop = true, .pause = m_paused}); m_stopped = true; m_thread.join(); } template <class T> void worker<T>::pause() { if (m_paused) return; m_paused = true; update(); } template <class T> void worker<T>::resume() { if (!m_paused) return; m_paused = false; update(); } template <class T> void worker<T>::config(const typename T::config_t& c) { m_config = c; if (is_finished()) return; send_message( worker::message{.stop = m_stopped, .pause = m_paused, .config = c}); } // Methods : private template <class T> void worker<T>::loop() { auto socket = std::unique_ptr<void, op_socket_deleter>( op_socket_get_client(m_zmq_context, ZMQ_PULL, m_endpoint)); for (bool paused = true;;) { void* msg_ptr = nullptr; int recv = zmq_recv( socket.get(), &msg_ptr, sizeof(void*), paused ? 0 : ZMQ_NOBLOCK); if (recv < 0 && errno != EAGAIN) { OP_LOG(OP_LOG_ERROR, "Worker thread %s shutdown", m_thread_name.c_str()); break; } if (recv > 0) { // The thread takes ownership of the pointer to the message // and guarantees deleting message after processing. auto msg = std::unique_ptr<worker::message>( reinterpret_cast<worker::message*>(msg_ptr)); if (msg->config) m_task->config(msg->config.value()); if (paused && !(msg->pause || msg->stop)) m_task->resume(); if (!paused && (msg->pause || msg->stop)) m_task->pause(); paused = msg->pause; if (msg->stop) break; if (msg->pause) continue; } m_task->spin(); } } template <class T> void worker<T>::update() { if (is_finished()) return; send_message(worker::message{ .stop = m_stopped, .pause = m_paused, }); } template <class T> void worker<T>::send_message(const worker::message& msg) { if (is_finished()) return; // A copy of the message is created on the heap and its pointer // is passed through ZMQ to thread. The thread will take ownership of // this message and should delete it after processing. auto pointer = new worker::message(msg); zmq_send(m_zmq_socket.get(), &pointer, sizeof(pointer), 0); } } // namespace openperf::utils::worker #endif // _OP_UTILS_WORKER_HPP_
25.484127
77
0.61554
abelov-spirent
f799755e7e47dcb07d48be5193db428cbaf2a490
18,648
hpp
C++
c++/include/serial/objectiter.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/include/serial/objectiter.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/include/serial/objectiter.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
#ifndef OBJECTITER__HPP #define OBJECTITER__HPP /* $Id: objectiter.hpp 358154 2012-03-29 15:05:12Z gouriano $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Eugene Vasilchenko * * File Description: * Iterators, which work on object information data */ #include <corelib/ncbistd.hpp> #include <serial/objectinfo.hpp> /** @addtogroup ObjStreamSupport * * @{ */ BEGIN_NCBI_SCOPE ///////////////////////////////////////////////////////////////////////////// /// /// CConstObjectInfoEI -- /// /// Container iterator /// Provides read access to elements of container /// @sa CConstObjectInfo::BeginElements class NCBI_XSERIAL_EXPORT CConstObjectInfoEI { public: CConstObjectInfoEI(void); CConstObjectInfoEI(const CConstObjectInfo& object); CConstObjectInfoEI& operator=(const CConstObjectInfo& object); /// Is iterator valid bool Valid(void) const; /// Is iterator valid DECLARE_OPERATOR_BOOL(Valid()); bool operator==(const CConstObjectInfoEI& obj) const { return GetElement() == obj.GetElement(); } bool operator!=(const CConstObjectInfoEI& obj) const { return GetElement() != obj.GetElement(); } /// Get index of the element in the container TMemberIndex GetIndex(void) const { return m_Iterator.GetIndex(); } /// Advance to next element void Next(void); /// Advance to next element CConstObjectInfoEI& operator++(void); /// Get element data and type information CConstObjectInfo GetElement(void) const; /// Get element data and type information CConstObjectInfo operator*(void) const; bool CanGet(void) const { return true; } const CItemInfo* GetItemInfo(void) const { return 0; } protected: bool CheckValid(void) const; private: CConstContainerElementIterator m_Iterator; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectInfoEI -- /// /// Container iterator /// Provides read/write access to elements of container /// @sa CObjectInfo::BeginElements class NCBI_XSERIAL_EXPORT CObjectInfoEI { public: CObjectInfoEI(void); CObjectInfoEI(const CObjectInfo& object); CObjectInfoEI& operator=(const CObjectInfo& object); /// Is iterator valid bool Valid(void) const; /// Is iterator valid DECLARE_OPERATOR_BOOL(Valid()); bool operator==(const CObjectInfoEI& obj) const { return GetElement() == obj.GetElement(); } bool operator!=(const CObjectInfoEI& obj) const { return GetElement() != obj.GetElement(); } /// Get index of the element in the container TMemberIndex GetIndex(void) const { return m_Iterator.GetIndex(); } /// Advance to next element void Next(void); /// Advance to next element CObjectInfoEI& operator++(void); /// Get element data and type information CObjectInfo GetElement(void) const; /// Get element data and type information CObjectInfo operator*(void) const; void Erase(void); bool CanGet(void) const { return true; } const CItemInfo* GetItemInfo(void) const { return 0; } protected: bool CheckValid(void) const; private: CContainerElementIterator m_Iterator; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectTypeInfoII -- /// /// Item iterator (either class member or choice variant) /// provides access to the data type information. class NCBI_XSERIAL_EXPORT CObjectTypeInfoII { public: const string& GetAlias(void) const; /// Is iterator valid bool Valid(void) const; /// Is iterator valid DECLARE_OPERATOR_BOOL(Valid()); bool operator==(const CObjectTypeInfoII& iter) const; bool operator!=(const CObjectTypeInfoII& iter) const; /// Advance to next element void Next(void); const CItemInfo* GetItemInfo(void) const; /// Get index of the element in the container (class or choice) TMemberIndex GetIndex(void) const { return GetItemIndex(); } protected: CObjectTypeInfoII(void); CObjectTypeInfoII(const CClassTypeInfoBase* typeInfo); CObjectTypeInfoII(const CClassTypeInfoBase* typeInfo, TMemberIndex index); const CObjectTypeInfo& GetOwnerType(void) const; const CClassTypeInfoBase* GetClassTypeInfoBase(void) const; TMemberIndex GetItemIndex(void) const; void Init(const CClassTypeInfoBase* typeInfo); void Init(const CClassTypeInfoBase* typeInfo, TMemberIndex index); bool CanGet(void) const { return true; } bool CheckValid(void) const; private: CObjectTypeInfo m_OwnerType; TMemberIndex m_ItemIndex; TMemberIndex m_LastItemIndex; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectTypeInfoMI -- /// /// Class member iterator /// provides access to the data type information. class NCBI_XSERIAL_EXPORT CObjectTypeInfoMI : public CObjectTypeInfoII { typedef CObjectTypeInfoII CParent; public: CObjectTypeInfoMI(void); CObjectTypeInfoMI(const CObjectTypeInfo& info); CObjectTypeInfoMI(const CObjectTypeInfo& info, TMemberIndex index); /// Get index of the member in the class TMemberIndex GetMemberIndex(void) const; /// Advance to next element CObjectTypeInfoMI& operator++(void); CObjectTypeInfoMI& operator=(const CObjectTypeInfo& info); /// Get containing class type CObjectTypeInfo GetClassType(void) const; /// Get data type information operator CObjectTypeInfo(void) const; /// Get data type information CObjectTypeInfo GetMemberType(void) const; /// Get data type information CObjectTypeInfo operator*(void) const; void SetLocalReadHook(CObjectIStream& stream, CReadClassMemberHook* hook) const; void SetGlobalReadHook(CReadClassMemberHook* hook) const; void ResetLocalReadHook(CObjectIStream& stream) const; void ResetGlobalReadHook(void) const; void SetPathReadHook(CObjectIStream* in, const string& path, CReadClassMemberHook* hook) const; void SetLocalWriteHook(CObjectOStream& stream, CWriteClassMemberHook* hook) const; void SetGlobalWriteHook(CWriteClassMemberHook* hook) const; void ResetLocalWriteHook(CObjectOStream& stream) const; void ResetGlobalWriteHook(void) const; void SetPathWriteHook(CObjectOStream* stream, const string& path, CWriteClassMemberHook* hook) const; void SetLocalSkipHook(CObjectIStream& stream, CSkipClassMemberHook* hook) const; void ResetLocalSkipHook(CObjectIStream& stream) const; void SetPathSkipHook(CObjectIStream* stream, const string& path, CSkipClassMemberHook* hook) const; void SetLocalCopyHook(CObjectStreamCopier& stream, CCopyClassMemberHook* hook) const; void SetGlobalCopyHook(CCopyClassMemberHook* hook) const; void ResetLocalCopyHook(CObjectStreamCopier& stream) const; void ResetGlobalCopyHook(void) const; void SetPathCopyHook(CObjectStreamCopier* stream, const string& path, CCopyClassMemberHook* hook) const; public: // mostly for internal use const CMemberInfo* GetMemberInfo(void) const; protected: void Init(const CObjectTypeInfo& info); void Init(const CObjectTypeInfo& info, TMemberIndex index); const CClassTypeInfo* GetClassTypeInfo(void) const; bool IsSet(const CConstObjectInfo& object) const; private: CMemberInfo* GetNCMemberInfo(void) const; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectTypeInfoVI -- /// /// Choice variant iterator /// provides access to the data type information. class NCBI_XSERIAL_EXPORT CObjectTypeInfoVI : public CObjectTypeInfoII { typedef CObjectTypeInfoII CParent; public: CObjectTypeInfoVI(const CObjectTypeInfo& info); CObjectTypeInfoVI(const CObjectTypeInfo& info, TMemberIndex index); /// Get index of the variant in the choice TMemberIndex GetVariantIndex(void) const; /// Advance to next element CObjectTypeInfoVI& operator++(void); CObjectTypeInfoVI& operator=(const CObjectTypeInfo& info); /// Get containing choice type CObjectTypeInfo GetChoiceType(void) const; /// Get data type information CObjectTypeInfo GetVariantType(void) const; /// Get data type information CObjectTypeInfo operator*(void) const; void SetLocalReadHook(CObjectIStream& stream, CReadChoiceVariantHook* hook) const; void SetGlobalReadHook(CReadChoiceVariantHook* hook) const; void ResetLocalReadHook(CObjectIStream& stream) const; void ResetGlobalReadHook(void) const; void SetPathReadHook(CObjectIStream* stream, const string& path, CReadChoiceVariantHook* hook) const; void SetLocalWriteHook(CObjectOStream& stream, CWriteChoiceVariantHook* hook) const; void SetGlobalWriteHook(CWriteChoiceVariantHook* hook) const; void ResetLocalWriteHook(CObjectOStream& stream) const; void ResetGlobalWriteHook(void) const; void SetPathWriteHook(CObjectOStream* stream, const string& path, CWriteChoiceVariantHook* hook) const; void SetLocalSkipHook(CObjectIStream& stream, CSkipChoiceVariantHook* hook) const; void ResetLocalSkipHook(CObjectIStream& stream) const; void SetPathSkipHook(CObjectIStream* stream, const string& path, CSkipChoiceVariantHook* hook) const; void SetLocalCopyHook(CObjectStreamCopier& stream, CCopyChoiceVariantHook* hook) const; void SetGlobalCopyHook(CCopyChoiceVariantHook* hook) const; void ResetLocalCopyHook(CObjectStreamCopier& stream) const; void ResetGlobalCopyHook(void) const; void SetPathCopyHook(CObjectStreamCopier* stream, const string& path, CCopyChoiceVariantHook* hook) const; public: // mostly for internal use const CVariantInfo* GetVariantInfo(void) const; protected: void Init(const CObjectTypeInfo& info); void Init(const CObjectTypeInfo& info, TMemberIndex index); const CChoiceTypeInfo* GetChoiceTypeInfo(void) const; private: CVariantInfo* GetNCVariantInfo(void) const; }; ///////////////////////////////////////////////////////////////////////////// /// /// CConstObjectInfoMI -- /// /// Class member iterator /// provides read access to class member data. class NCBI_XSERIAL_EXPORT CConstObjectInfoMI : public CObjectTypeInfoMI { typedef CObjectTypeInfoMI CParent; public: CConstObjectInfoMI(void); CConstObjectInfoMI(const CConstObjectInfo& object); CConstObjectInfoMI(const CConstObjectInfo& object, TMemberIndex index); /// Get containing class data const CConstObjectInfo& GetClassObject(void) const; CConstObjectInfoMI& operator=(const CConstObjectInfo& object); /// Is member assigned a value bool IsSet(void) const; /// Get class member data CConstObjectInfo GetMember(void) const; /// Get class member data CConstObjectInfo operator*(void) const; bool CanGet(void) const; private: pair<TConstObjectPtr, TTypeInfo> GetMemberPair(void) const; CConstObjectInfo m_Object; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectInfoMI -- /// /// Class member iterator /// provides read/write access to class member data. class NCBI_XSERIAL_EXPORT CObjectInfoMI : public CObjectTypeInfoMI { typedef CObjectTypeInfoMI CParent; public: CObjectInfoMI(void); CObjectInfoMI(const CObjectInfo& object); CObjectInfoMI(const CObjectInfo& object, TMemberIndex index); /// Get containing class data const CObjectInfo& GetClassObject(void) const; CObjectInfoMI& operator=(const CObjectInfo& object); /// Is member assigned a value bool IsSet(void) const; /// Get class member data CObjectInfo GetMember(void) const; /// Get class member data CObjectInfo operator*(void) const; /// Erase types enum EEraseFlag { eErase_Optional, ///< default - erase optional member only eErase_Mandatory ///< allow erasing mandatory members, may be dangerous! }; /// Erase member value void Erase(EEraseFlag flag = eErase_Optional); /// Reset value of member to default state void Reset(void); bool CanGet(void) const; private: pair<TObjectPtr, TTypeInfo> GetMemberPair(void) const; CObjectInfo m_Object; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectTypeInfoCV -- /// /// Choice variant /// provides access to the data type information. class NCBI_XSERIAL_EXPORT CObjectTypeInfoCV { public: CObjectTypeInfoCV(void); CObjectTypeInfoCV(const CObjectTypeInfo& info); CObjectTypeInfoCV(const CObjectTypeInfo& info, TMemberIndex index); CObjectTypeInfoCV(const CConstObjectInfo& object); /// Get index of the variant in the choice TMemberIndex GetVariantIndex(void) const; const string& GetAlias(void) const; bool Valid(void) const; DECLARE_OPERATOR_BOOL(Valid()); bool operator==(const CObjectTypeInfoCV& iter) const; bool operator!=(const CObjectTypeInfoCV& iter) const; CObjectTypeInfoCV& operator=(const CObjectTypeInfo& info); CObjectTypeInfoCV& operator=(const CConstObjectInfo& object); /// Get containing choice CObjectTypeInfo GetChoiceType(void) const; /// Get variant data type CObjectTypeInfo GetVariantType(void) const; /// Get variant data type CObjectTypeInfo operator*(void) const; void SetLocalReadHook(CObjectIStream& stream, CReadChoiceVariantHook* hook) const; void SetGlobalReadHook(CReadChoiceVariantHook* hook) const; void ResetLocalReadHook(CObjectIStream& stream) const; void ResetGlobalReadHook(void) const; void SetPathReadHook(CObjectIStream* stream, const string& path, CReadChoiceVariantHook* hook) const; void SetLocalWriteHook(CObjectOStream& stream, CWriteChoiceVariantHook* hook) const; void SetGlobalWriteHook(CWriteChoiceVariantHook* hook) const; void ResetLocalWriteHook(CObjectOStream& stream) const; void ResetGlobalWriteHook(void) const; void SetPathWriteHook(CObjectOStream* stream, const string& path, CWriteChoiceVariantHook* hook) const; void SetLocalCopyHook(CObjectStreamCopier& stream, CCopyChoiceVariantHook* hook) const; void SetGlobalCopyHook(CCopyChoiceVariantHook* hook) const; void ResetLocalCopyHook(CObjectStreamCopier& stream) const; void ResetGlobalCopyHook(void) const; void SetPathCopyHook(CObjectStreamCopier* stream, const string& path, CCopyChoiceVariantHook* hook) const; public: // mostly for internal use const CVariantInfo* GetVariantInfo(void) const; protected: const CChoiceTypeInfo* GetChoiceTypeInfo(void) const; void Init(const CObjectTypeInfo& info); void Init(const CObjectTypeInfo& info, TMemberIndex index); void Init(const CConstObjectInfo& object); private: const CChoiceTypeInfo* m_ChoiceTypeInfo; TMemberIndex m_VariantIndex; private: CVariantInfo* GetNCVariantInfo(void) const; }; ///////////////////////////////////////////////////////////////////////////// /// /// CConstObjectInfoCV -- /// /// Choice variant /// provides read access to the variant data. class NCBI_XSERIAL_EXPORT CConstObjectInfoCV : public CObjectTypeInfoCV { typedef CObjectTypeInfoCV CParent; public: CConstObjectInfoCV(void); CConstObjectInfoCV(const CConstObjectInfo& object); CConstObjectInfoCV(const CConstObjectInfo& object, TMemberIndex index); /// Get containing choice const CConstObjectInfo& GetChoiceObject(void) const; CConstObjectInfoCV& operator=(const CConstObjectInfo& object); /// Get variant data CConstObjectInfo GetVariant(void) const; /// Get variant data CConstObjectInfo operator*(void) const; private: pair<TConstObjectPtr, TTypeInfo> GetVariantPair(void) const; CConstObjectInfo m_Object; TMemberIndex m_VariantIndex; }; ///////////////////////////////////////////////////////////////////////////// /// /// CObjectInfoCV -- /// /// Choice variant /// provides read/write access to the variant data. class NCBI_XSERIAL_EXPORT CObjectInfoCV : public CObjectTypeInfoCV { typedef CObjectTypeInfoCV CParent; public: CObjectInfoCV(void); CObjectInfoCV(const CObjectInfo& object); CObjectInfoCV(const CObjectInfo& object, TMemberIndex index); /// Get containing choice const CObjectInfo& GetChoiceObject(void) const; CObjectInfoCV& operator=(const CObjectInfo& object); /// Get variant data CObjectInfo GetVariant(void) const; /// Get variant data CObjectInfo operator*(void) const; private: pair<TObjectPtr, TTypeInfo> GetVariantPair(void) const; CObjectInfo m_Object; }; /* @} */ #include <serial/impl/objectiter.inl> END_NCBI_SCOPE #endif /* OBJECTITER__HPP */
30.321951
80
0.673155
OpenHero
f799a8c915ae41e0ff0af44cdfc237bb63a92df1
420
cpp
C++
LeetCode/DP/413. Arithmetic Slices.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
1
2019-11-12T13:40:44.000Z
2019-11-12T13:40:44.000Z
LeetCode/DP/413. Arithmetic Slices.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
LeetCode/DP/413. Arithmetic Slices.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
class Solution { public: int numberOfArithmeticSlices(vector<int>& nums) { if(nums.size()<3) return 0; int res=0; int dp = 0; for(int i=2;i<nums.size();i++){ if(nums[i]-nums[i-1]==nums[i-1]-nums[i-2]) dp++; else { dp = 0; } res+=dp; } return res; } };
19.090909
60
0.371429
Sowmik23
f799d73477a10af37ab1849fb862fe21f7584ba9
34,627
cc
C++
media/filters/video_frame_stream_unittest.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
1
2020-09-15T08:43:34.000Z
2020-09-15T08:43:34.000Z
media/filters/video_frame_stream_unittest.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
media/filters/video_frame_stream_unittest.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "media/base/fake_demuxer_stream.h" #include "media/base/gmock_callback_support.h" #include "media/base/mock_filters.h" #include "media/base/test_helpers.h" #include "media/base/timestamp_constants.h" #include "media/filters/decoder_stream.h" #include "media/filters/fake_video_decoder.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; using ::testing::AnyNumber; using ::testing::Assign; using ::testing::Invoke; using ::testing::InvokeWithoutArgs; using ::testing::NiceMock; using ::testing::Return; using ::testing::SaveArg; using ::testing::StrictMock; static const int kNumConfigs = 4; static const int kNumBuffersInOneConfig = 5; namespace media { struct VideoFrameStreamTestParams { VideoFrameStreamTestParams(bool is_encrypted, int decoding_delay, int parallel_decoding) : is_encrypted(is_encrypted), decoding_delay(decoding_delay), parallel_decoding(parallel_decoding) {} bool is_encrypted; int decoding_delay; int parallel_decoding; }; class VideoFrameStreamTest : public testing::Test, public testing::WithParamInterface<VideoFrameStreamTestParams> { public: VideoFrameStreamTest() : demuxer_stream_(new FakeDemuxerStream(kNumConfigs, kNumBuffersInOneConfig, GetParam().is_encrypted)), cdm_context_(new StrictMock<MockCdmContext>()), decryptor_(new NiceMock<MockDecryptor>()), decoder1_( new FakeVideoDecoder(GetParam().decoding_delay, GetParam().parallel_decoding, base::Bind( &VideoFrameStreamTest::OnBytesDecoded, base::Unretained(this)))), decoder2_( new FakeVideoDecoder(GetParam().decoding_delay, GetParam().parallel_decoding, base::Bind( &VideoFrameStreamTest::OnBytesDecoded, base::Unretained(this)))), decoder3_( new FakeVideoDecoder(GetParam().decoding_delay, GetParam().parallel_decoding, base::Bind( &VideoFrameStreamTest::OnBytesDecoded, base::Unretained(this)))), is_initialized_(false), num_decoded_frames_(0), pending_initialize_(false), pending_read_(false), pending_reset_(false), pending_stop_(false), num_decoded_bytes_unreported_(0), has_no_key_(false) { ScopedVector<VideoDecoder> decoders; decoders.push_back(decoder1_); decoders.push_back(decoder2_); decoders.push_back(decoder3_); video_frame_stream_.reset(new VideoFrameStream( message_loop_.task_runner(), std::move(decoders), new MediaLog())); EXPECT_CALL(*cdm_context_, GetDecryptor()) .WillRepeatedly(Return(decryptor_.get())); // Decryptor can only decrypt (not decrypt-and-decode) so that // DecryptingDemuxerStream will be used. EXPECT_CALL(*decryptor_, InitializeVideoDecoder(_, _)) .WillRepeatedly(RunCallback<1>(false)); EXPECT_CALL(*decryptor_, Decrypt(_, _, _)) .WillRepeatedly(Invoke(this, &VideoFrameStreamTest::Decrypt)); } ~VideoFrameStreamTest() { // Check that the pipeline statistics callback was fired correctly. EXPECT_EQ(num_decoded_bytes_unreported_, 0); is_initialized_ = false; decoder1_ = NULL; decoder2_ = NULL; decoder3_ = NULL; video_frame_stream_.reset(); message_loop_.RunUntilIdle(); DCHECK(!pending_initialize_); DCHECK(!pending_read_); DCHECK(!pending_reset_); DCHECK(!pending_stop_); } MOCK_METHOD1(OnNewSpliceBuffer, void(base::TimeDelta)); MOCK_METHOD0(OnWaitingForDecryptionKey, void(void)); void OnStatistics(const PipelineStatistics& statistics) { num_decoded_bytes_unreported_ -= statistics.video_bytes_decoded; } void OnBytesDecoded(int count) { num_decoded_bytes_unreported_ += count; } void OnInitialized(bool success) { DCHECK(!pending_read_); DCHECK(!pending_reset_); DCHECK(pending_initialize_); pending_initialize_ = false; is_initialized_ = success; if (!success) { decoder1_ = NULL; decoder2_ = NULL; decoder3_ = NULL; } } void InitializeVideoFrameStream() { pending_initialize_ = true; video_frame_stream_->Initialize( demuxer_stream_.get(), base::Bind(&VideoFrameStreamTest::OnInitialized, base::Unretained(this)), cdm_context_.get(), base::Bind(&VideoFrameStreamTest::OnStatistics, base::Unretained(this)), base::Bind(&VideoFrameStreamTest::OnWaitingForDecryptionKey, base::Unretained(this))); message_loop_.RunUntilIdle(); } // Fake Decrypt() function used by DecryptingDemuxerStream. It does nothing // but removes the DecryptConfig to make the buffer unencrypted. void Decrypt(Decryptor::StreamType stream_type, const scoped_refptr<DecoderBuffer>& encrypted, const Decryptor::DecryptCB& decrypt_cb) { DCHECK(encrypted->decrypt_config()); if (has_no_key_) { decrypt_cb.Run(Decryptor::kNoKey, NULL); return; } DCHECK_EQ(stream_type, Decryptor::kVideo); scoped_refptr<DecoderBuffer> decrypted = DecoderBuffer::CopyFrom(encrypted->data(), encrypted->data_size()); if (encrypted->is_key_frame()) decrypted->set_is_key_frame(true); decrypted->set_timestamp(encrypted->timestamp()); decrypted->set_duration(encrypted->duration()); decrypt_cb.Run(Decryptor::kSuccess, decrypted); } // Callback for VideoFrameStream::Read(). void FrameReady(VideoFrameStream::Status status, const scoped_refptr<VideoFrame>& frame) { DCHECK(pending_read_); frame_read_ = frame; last_read_status_ = status; if (frame.get() && !frame->metadata()->IsTrue(VideoFrameMetadata::END_OF_STREAM)) { num_decoded_frames_++; } pending_read_ = false; } void OnReset() { DCHECK(!pending_read_); DCHECK(pending_reset_); pending_reset_ = false; } void ReadOneFrame() { frame_read_ = NULL; pending_read_ = true; video_frame_stream_->Read(base::Bind( &VideoFrameStreamTest::FrameReady, base::Unretained(this))); message_loop_.RunUntilIdle(); } void ReadUntilPending() { do { ReadOneFrame(); } while (!pending_read_); } void ReadAllFrames(int expected_decoded_frames) { do { ReadOneFrame(); } while (frame_read_.get() && !frame_read_->metadata()->IsTrue( VideoFrameMetadata::END_OF_STREAM)); DCHECK_EQ(expected_decoded_frames, num_decoded_frames_); } void ReadAllFrames() { // No frames should have been dropped. ReadAllFrames(kNumConfigs * kNumBuffersInOneConfig); } enum PendingState { NOT_PENDING, DEMUXER_READ_NORMAL, DEMUXER_READ_CONFIG_CHANGE, DECRYPTOR_NO_KEY, DECODER_INIT, DECODER_REINIT, DECODER_DECODE, DECODER_RESET }; void EnterPendingState(PendingState state) { EnterPendingState(state, decoder1_); } void EnterPendingState(PendingState state, FakeVideoDecoder* decoder) { DCHECK_NE(state, NOT_PENDING); switch (state) { case DEMUXER_READ_NORMAL: demuxer_stream_->HoldNextRead(); ReadUntilPending(); break; case DEMUXER_READ_CONFIG_CHANGE: demuxer_stream_->HoldNextConfigChangeRead(); ReadUntilPending(); break; case DECRYPTOR_NO_KEY: if (GetParam().is_encrypted) EXPECT_CALL(*this, OnWaitingForDecryptionKey()); has_no_key_ = true; ReadOneFrame(); break; case DECODER_INIT: decoder->HoldNextInit(); InitializeVideoFrameStream(); break; case DECODER_REINIT: decoder->HoldNextInit(); ReadUntilPending(); break; case DECODER_DECODE: decoder->HoldDecode(); ReadUntilPending(); break; case DECODER_RESET: decoder->HoldNextReset(); pending_reset_ = true; video_frame_stream_->Reset(base::Bind(&VideoFrameStreamTest::OnReset, base::Unretained(this))); message_loop_.RunUntilIdle(); break; case NOT_PENDING: NOTREACHED(); break; } } void SatisfyPendingCallback(PendingState state) { SatisfyPendingCallback(state, decoder1_); } void SatisfyPendingCallback(PendingState state, FakeVideoDecoder* decoder) { DCHECK_NE(state, NOT_PENDING); switch (state) { case DEMUXER_READ_NORMAL: case DEMUXER_READ_CONFIG_CHANGE: demuxer_stream_->SatisfyRead(); break; // This is only interesting to test during VideoFrameStream destruction. // There's no need to satisfy a callback. case DECRYPTOR_NO_KEY: NOTREACHED(); break; case DECODER_INIT: decoder->SatisfyInit(); break; case DECODER_REINIT: decoder->SatisfyInit(); break; case DECODER_DECODE: decoder->SatisfyDecode(); break; case DECODER_RESET: decoder->SatisfyReset(); break; case NOT_PENDING: NOTREACHED(); break; } message_loop_.RunUntilIdle(); } void Initialize() { EnterPendingState(DECODER_INIT); SatisfyPendingCallback(DECODER_INIT); } void Read() { EnterPendingState(DECODER_DECODE); SatisfyPendingCallback(DECODER_DECODE); } void Reset() { EnterPendingState(DECODER_RESET); SatisfyPendingCallback(DECODER_RESET); } void ReadUntilDecoderReinitialized(FakeVideoDecoder* decoder) { EnterPendingState(DECODER_REINIT, decoder); SatisfyPendingCallback(DECODER_REINIT, decoder); } base::MessageLoop message_loop_; std::unique_ptr<VideoFrameStream> video_frame_stream_; std::unique_ptr<FakeDemuxerStream> demuxer_stream_; std::unique_ptr<StrictMock<MockCdmContext>> cdm_context_; // Use NiceMock since we don't care about most of calls on the decryptor, // e.g. RegisterNewKeyCB(). std::unique_ptr<NiceMock<MockDecryptor>> decryptor_; // Three decoders are needed to test that decoder fallback can occur more than // once on a config change. They are owned by |video_frame_stream_|. FakeVideoDecoder* decoder1_; FakeVideoDecoder* decoder2_; FakeVideoDecoder* decoder3_; bool is_initialized_; int num_decoded_frames_; bool pending_initialize_; bool pending_read_; bool pending_reset_; bool pending_stop_; int num_decoded_bytes_unreported_; scoped_refptr<VideoFrame> frame_read_; VideoFrameStream::Status last_read_status_; // Decryptor has no key to decrypt a frame. bool has_no_key_; private: DISALLOW_COPY_AND_ASSIGN(VideoFrameStreamTest); }; INSTANTIATE_TEST_CASE_P( Clear, VideoFrameStreamTest, ::testing::Values( VideoFrameStreamTestParams(false, 0, 1), VideoFrameStreamTestParams(false, 3, 1), VideoFrameStreamTestParams(false, 7, 1))); INSTANTIATE_TEST_CASE_P( Encrypted, VideoFrameStreamTest, ::testing::Values( VideoFrameStreamTestParams(true, 7, 1))); INSTANTIATE_TEST_CASE_P( Clear_Parallel, VideoFrameStreamTest, ::testing::Values( VideoFrameStreamTestParams(false, 0, 3), VideoFrameStreamTestParams(false, 2, 3))); TEST_P(VideoFrameStreamTest, Initialization) { Initialize(); } TEST_P(VideoFrameStreamTest, AllDecoderInitializationFails) { decoder1_->SimulateFailureToInit(); decoder2_->SimulateFailureToInit(); decoder3_->SimulateFailureToInit(); Initialize(); EXPECT_FALSE(is_initialized_); } TEST_P(VideoFrameStreamTest, PartialDecoderInitializationFails) { decoder1_->SimulateFailureToInit(); decoder2_->SimulateFailureToInit(); Initialize(); EXPECT_TRUE(is_initialized_); } TEST_P(VideoFrameStreamTest, ReadOneFrame) { Initialize(); Read(); } TEST_P(VideoFrameStreamTest, ReadAllFrames) { Initialize(); ReadAllFrames(); } TEST_P(VideoFrameStreamTest, Read_AfterReset) { Initialize(); Reset(); Read(); Reset(); Read(); } TEST_P(VideoFrameStreamTest, Read_BlockedDemuxer) { Initialize(); demuxer_stream_->HoldNextRead(); ReadOneFrame(); EXPECT_TRUE(pending_read_); int demuxed_buffers = 0; // Pass frames from the demuxer to the VideoFrameStream until the first read // request is satisfied. while (pending_read_) { ++demuxed_buffers; demuxer_stream_->SatisfyReadAndHoldNext(); message_loop_.RunUntilIdle(); } EXPECT_EQ(std::min(GetParam().decoding_delay + 1, kNumBuffersInOneConfig + 1), demuxed_buffers); // At this point the stream is waiting on read from the demuxer, but there is // no pending read from the stream. The stream should be blocked if we try // reading from it again. ReadUntilPending(); demuxer_stream_->SatisfyRead(); message_loop_.RunUntilIdle(); EXPECT_FALSE(pending_read_); } TEST_P(VideoFrameStreamTest, Read_BlockedDemuxerAndDecoder) { // Test applies only when the decoder allows multiple parallel requests. if (GetParam().parallel_decoding == 1) return; Initialize(); demuxer_stream_->HoldNextRead(); decoder1_->HoldDecode(); ReadOneFrame(); EXPECT_TRUE(pending_read_); int demuxed_buffers = 0; // Pass frames from the demuxer to the VideoFrameStream until the first read // request is satisfied, while always keeping one decode request pending. while (pending_read_) { ++demuxed_buffers; demuxer_stream_->SatisfyReadAndHoldNext(); message_loop_.RunUntilIdle(); // Always keep one decode request pending. if (demuxed_buffers > 1) { decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); } } ReadUntilPending(); EXPECT_TRUE(pending_read_); // Unblocking one decode request should unblock read even when demuxer is // still blocked. decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); EXPECT_FALSE(pending_read_); // Stream should still be blocked on the demuxer after unblocking the decoder. decoder1_->SatisfyDecode(); ReadUntilPending(); EXPECT_TRUE(pending_read_); // Verify that the stream has returned all frames that have been demuxed, // accounting for the decoder delay. EXPECT_EQ(demuxed_buffers - GetParam().decoding_delay, num_decoded_frames_); // Unblocking the demuxer will unblock the stream. demuxer_stream_->SatisfyRead(); message_loop_.RunUntilIdle(); EXPECT_FALSE(pending_read_); } TEST_P(VideoFrameStreamTest, Read_DuringEndOfStreamDecode) { // Test applies only when the decoder allows multiple parallel requests, and // they are not satisfied in a single batch. if (GetParam().parallel_decoding == 1 || GetParam().decoding_delay != 0) return; Initialize(); decoder1_->HoldDecode(); // Read all of the frames up to end of stream. Since parallel decoding is // enabled, the end of stream buffer will be sent to the decoder immediately, // but we don't satisfy it yet. for (int configuration = 0; configuration < kNumConfigs; configuration++) { for (int frame = 0; frame < kNumBuffersInOneConfig; frame++) { ReadOneFrame(); while (pending_read_) { decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); } } } // Read() again. The callback must be delayed until the decode completes. ReadOneFrame(); ASSERT_TRUE(pending_read_); // Satisfy decoding of the end of stream buffer. The read should complete. decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); ASSERT_FALSE(pending_read_); EXPECT_EQ(last_read_status_, VideoFrameStream::OK); // The read output should indicate end of stream. ASSERT_TRUE(frame_read_.get()); EXPECT_TRUE( frame_read_->metadata()->IsTrue(VideoFrameMetadata::END_OF_STREAM)); } // No Reset() before initialization is successfully completed. TEST_P(VideoFrameStreamTest, Reset_AfterInitialization) { Initialize(); Reset(); Read(); } TEST_P(VideoFrameStreamTest, Reset_DuringReinitialization) { Initialize(); EnterPendingState(DECODER_REINIT); // VideoDecoder::Reset() is not called when we reset during reinitialization. pending_reset_ = true; video_frame_stream_->Reset( base::Bind(&VideoFrameStreamTest::OnReset, base::Unretained(this))); SatisfyPendingCallback(DECODER_REINIT); Read(); } TEST_P(VideoFrameStreamTest, Reset_AfterReinitialization) { Initialize(); EnterPendingState(DECODER_REINIT); SatisfyPendingCallback(DECODER_REINIT); Reset(); Read(); } TEST_P(VideoFrameStreamTest, Reset_DuringDemuxerRead_Normal) { Initialize(); EnterPendingState(DEMUXER_READ_NORMAL); EnterPendingState(DECODER_RESET); SatisfyPendingCallback(DEMUXER_READ_NORMAL); SatisfyPendingCallback(DECODER_RESET); Read(); } TEST_P(VideoFrameStreamTest, Reset_DuringDemuxerRead_ConfigChange) { Initialize(); EnterPendingState(DEMUXER_READ_CONFIG_CHANGE); EnterPendingState(DECODER_RESET); SatisfyPendingCallback(DEMUXER_READ_CONFIG_CHANGE); SatisfyPendingCallback(DECODER_RESET); Read(); } TEST_P(VideoFrameStreamTest, Reset_DuringNormalDecoderDecode) { Initialize(); EnterPendingState(DECODER_DECODE); EnterPendingState(DECODER_RESET); SatisfyPendingCallback(DECODER_DECODE); SatisfyPendingCallback(DECODER_RESET); Read(); } TEST_P(VideoFrameStreamTest, Reset_AfterNormalRead) { Initialize(); Read(); Reset(); Read(); } TEST_P(VideoFrameStreamTest, Reset_AfterNormalReadWithActiveSplice) { video_frame_stream_->set_splice_observer(base::Bind( &VideoFrameStreamTest::OnNewSpliceBuffer, base::Unretained(this))); Initialize(); // Send buffers with a splice timestamp, which sets the active splice flag. const base::TimeDelta splice_timestamp = base::TimeDelta(); demuxer_stream_->set_splice_timestamp(splice_timestamp); EXPECT_CALL(*this, OnNewSpliceBuffer(splice_timestamp)).Times(AnyNumber()); Read(); // Issue an explicit Reset() and clear the splice timestamp. Reset(); demuxer_stream_->set_splice_timestamp(kNoTimestamp()); // Ensure none of the upcoming calls indicate they have a splice timestamp. EXPECT_CALL(*this, OnNewSpliceBuffer(_)).Times(0); Read(); } TEST_P(VideoFrameStreamTest, Reset_AfterDemuxerRead_ConfigChange) { Initialize(); EnterPendingState(DEMUXER_READ_CONFIG_CHANGE); SatisfyPendingCallback(DEMUXER_READ_CONFIG_CHANGE); Reset(); Read(); } TEST_P(VideoFrameStreamTest, Reset_AfterEndOfStream) { Initialize(); ReadAllFrames(); Reset(); num_decoded_frames_ = 0; demuxer_stream_->SeekToStart(); ReadAllFrames(); } TEST_P(VideoFrameStreamTest, Reset_DuringNoKeyRead) { Initialize(); EnterPendingState(DECRYPTOR_NO_KEY); Reset(); } // In the following Destroy_* tests, |video_frame_stream_| is destroyed in // VideoFrameStreamTest dtor. TEST_P(VideoFrameStreamTest, Destroy_BeforeInitialization) { } TEST_P(VideoFrameStreamTest, Destroy_DuringInitialization) { EnterPendingState(DECODER_INIT); } TEST_P(VideoFrameStreamTest, Destroy_AfterInitialization) { Initialize(); } TEST_P(VideoFrameStreamTest, Destroy_DuringReinitialization) { Initialize(); EnterPendingState(DECODER_REINIT); } TEST_P(VideoFrameStreamTest, Destroy_AfterReinitialization) { Initialize(); EnterPendingState(DECODER_REINIT); SatisfyPendingCallback(DECODER_REINIT); } TEST_P(VideoFrameStreamTest, Destroy_DuringDemuxerRead_Normal) { Initialize(); EnterPendingState(DEMUXER_READ_NORMAL); } TEST_P(VideoFrameStreamTest, Destroy_DuringDemuxerRead_ConfigChange) { Initialize(); EnterPendingState(DEMUXER_READ_CONFIG_CHANGE); } TEST_P(VideoFrameStreamTest, Destroy_DuringNormalDecoderDecode) { Initialize(); EnterPendingState(DECODER_DECODE); } TEST_P(VideoFrameStreamTest, Destroy_AfterNormalRead) { Initialize(); Read(); } TEST_P(VideoFrameStreamTest, Destroy_AfterConfigChangeRead) { Initialize(); EnterPendingState(DEMUXER_READ_CONFIG_CHANGE); SatisfyPendingCallback(DEMUXER_READ_CONFIG_CHANGE); } TEST_P(VideoFrameStreamTest, Destroy_DuringDecoderReinitialization) { Initialize(); EnterPendingState(DECODER_REINIT); } TEST_P(VideoFrameStreamTest, Destroy_DuringNoKeyRead) { Initialize(); EnterPendingState(DECRYPTOR_NO_KEY); } TEST_P(VideoFrameStreamTest, Destroy_DuringReset) { Initialize(); EnterPendingState(DECODER_RESET); } TEST_P(VideoFrameStreamTest, Destroy_AfterReset) { Initialize(); Reset(); } TEST_P(VideoFrameStreamTest, Destroy_DuringRead_DuringReset) { Initialize(); EnterPendingState(DECODER_DECODE); EnterPendingState(DECODER_RESET); } TEST_P(VideoFrameStreamTest, Destroy_AfterRead_DuringReset) { Initialize(); EnterPendingState(DECODER_DECODE); EnterPendingState(DECODER_RESET); SatisfyPendingCallback(DECODER_DECODE); } TEST_P(VideoFrameStreamTest, Destroy_AfterRead_AfterReset) { Initialize(); Read(); Reset(); } TEST_P(VideoFrameStreamTest, FallbackDecoder_SelectedOnInitialDecodeError) { Initialize(); decoder1_->SimulateError(); ReadOneFrame(); // |video_frame_stream_| should have fallen back to |decoder2_|. ASSERT_FALSE(pending_read_); ASSERT_EQ(VideoFrameStream::OK, last_read_status_); // Can't check |decoder1_| right now, it might have been destroyed already. ASSERT_GT(decoder2_->total_bytes_decoded(), 0); // Verify no frame was dropped. ReadAllFrames(); } TEST_P(VideoFrameStreamTest, FallbackDecoder_EndOfStreamReachedBeforeFallback) { // Only consider cases where there is a decoder delay. For test simplicity, // omit the parallel case. if (GetParam().decoding_delay == 0 || GetParam().parallel_decoding > 1) return; Initialize(); decoder1_->HoldDecode(); ReadOneFrame(); // One buffer should have already pulled from the demuxer stream. Set the next // one to be an EOS. demuxer_stream_->SeekToEndOfStream(); decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); // |video_frame_stream_| should not have emited a frame. EXPECT_TRUE(pending_read_); // Pending buffers should contain a regular buffer and an EOS buffer. EXPECT_EQ(video_frame_stream_->get_pending_buffers_size_for_testing(), 2); decoder1_->SimulateError(); message_loop_.RunUntilIdle(); // A frame should have been emited EXPECT_FALSE(pending_read_); EXPECT_EQ(last_read_status_, VideoFrameStream::OK); EXPECT_FALSE( frame_read_->metadata()->IsTrue(VideoFrameMetadata::END_OF_STREAM)); EXPECT_GT(decoder2_->total_bytes_decoded(), 0); ReadOneFrame(); EXPECT_FALSE(pending_read_); EXPECT_EQ(0, video_frame_stream_->get_fallback_buffers_size_for_testing()); EXPECT_TRUE( frame_read_->metadata()->IsTrue(VideoFrameMetadata::END_OF_STREAM)); } TEST_P(VideoFrameStreamTest, FallbackDecoder_DoesReinitializeStompPendingRead) { // Test only the case where there is no decoding delay and parallel decoding. if (GetParam().decoding_delay != 0 || GetParam().parallel_decoding <= 1) return; Initialize(); decoder1_->HoldDecode(); // Queue one read, defer the second. frame_read_ = nullptr; pending_read_ = true; video_frame_stream_->Read( base::Bind(&VideoFrameStreamTest::FrameReady, base::Unretained(this))); demuxer_stream_->HoldNextRead(); // Force an error to occur on the first decode, but ensure it isn't propagated // until after the next read has been started. decoder1_->SimulateError(); decoder2_->HoldDecode(); // Complete the fallback to the second decoder with the read still pending. base::RunLoop().RunUntilIdle(); // Can't check |decoder1_| right now, it might have been destroyed already. // Verify that there was nothing decoded until we kicked the decoder. EXPECT_EQ(decoder2_->total_bytes_decoded(), 0); decoder2_->SatisfyDecode(); const int first_decoded_bytes = decoder2_->total_bytes_decoded(); ASSERT_GT(first_decoded_bytes, 0); // Satisfy the previously pending read and ensure it is decoded. demuxer_stream_->SatisfyRead(); base::RunLoop().RunUntilIdle(); ASSERT_GT(decoder2_->total_bytes_decoded(), first_decoded_bytes); } TEST_P(VideoFrameStreamTest, FallbackDecoder_SelectedOnInitialDecodeError_Twice) { Initialize(); decoder1_->SimulateError(); decoder2_->HoldNextInit(); ReadOneFrame(); decoder2_->SatisfyInit(); decoder2_->SimulateError(); message_loop_.RunUntilIdle(); // |video_frame_stream_| should have fallen back to |decoder3_|. ASSERT_FALSE(pending_read_); ASSERT_EQ(VideoFrameStream::OK, last_read_status_); // Can't check |decoder1_| or |decoder2_| right now, they might have been // destroyed already. ASSERT_GT(decoder3_->total_bytes_decoded(), 0); // Verify no frame was dropped. ReadAllFrames(); } TEST_P(VideoFrameStreamTest, FallbackDecoder_ConfigChangeClearsPendingBuffers) { // Test case is only interesting if the decoder can receive a config change // before returning its first frame. if (GetParam().decoding_delay < kNumBuffersInOneConfig) return; Initialize(); EnterPendingState(DEMUXER_READ_CONFIG_CHANGE); ASSERT_GT(video_frame_stream_->get_pending_buffers_size_for_testing(), 0); SatisfyPendingCallback(DEMUXER_READ_CONFIG_CHANGE); ASSERT_EQ(video_frame_stream_->get_pending_buffers_size_for_testing(), 0); EXPECT_FALSE(pending_read_); ReadAllFrames(); } TEST_P(VideoFrameStreamTest, FallbackDecoder_ErrorDuringConfigChangeFlushing) { // Test case is only interesting if the decoder can receive a config change // before returning its first frame. if (GetParam().decoding_delay < kNumBuffersInOneConfig) return; Initialize(); EnterPendingState(DEMUXER_READ_CONFIG_CHANGE); EXPECT_GT(video_frame_stream_->get_pending_buffers_size_for_testing(), 0); decoder1_->HoldDecode(); SatisfyPendingCallback(DEMUXER_READ_CONFIG_CHANGE); // The flush request should have been sent and held. EXPECT_EQ(video_frame_stream_->get_pending_buffers_size_for_testing(), 0); EXPECT_TRUE(pending_read_); // Triggering an error here will cause the frames in |decoder1_| to be lost. // There are no pending buffers buffers to give to give to |decoder2_| due to // crbug.com/603713. decoder1_->SimulateError(); message_loop_.RunUntilIdle(); // We want to make sure that |decoder2_| can decode the rest of the frames // in the demuxer stream. ReadAllFrames(kNumBuffersInOneConfig * (kNumConfigs - 1)); } TEST_P(VideoFrameStreamTest, FallbackDecoder_PendingBuffersIsFilledAndCleared) { // Test applies only when there is a decoder delay, and the decoder will not // receive a config change before outputing its first frame. Parallel decoding // is also disabled in this test case, for readability and simplicity of the // unit test. if (GetParam().decoding_delay == 0 || GetParam().decoding_delay > kNumBuffersInOneConfig || GetParam().parallel_decoding > 1) { return; } Initialize(); // Block on demuxer read and decoder decode so we can step through. demuxer_stream_->HoldNextRead(); decoder1_->HoldDecode(); ReadOneFrame(); int demuxer_reads_satisfied = 0; // Send back and requests buffers until the next one would fill the decoder // delay. while (demuxer_reads_satisfied < GetParam().decoding_delay - 1) { // Send a buffer back. demuxer_stream_->SatisfyReadAndHoldNext(); message_loop_.RunUntilIdle(); ++demuxer_reads_satisfied; // Decode one buffer. decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); EXPECT_TRUE(pending_read_); EXPECT_EQ(demuxer_reads_satisfied, video_frame_stream_->get_pending_buffers_size_for_testing()); // No fallback buffers should be queued up yet. EXPECT_EQ(0, video_frame_stream_->get_fallback_buffers_size_for_testing()); } // Hold the init before triggering the error, to verify internal state. demuxer_stream_->SatisfyReadAndHoldNext(); ++demuxer_reads_satisfied; decoder2_->HoldNextInit(); decoder1_->SimulateError(); message_loop_.RunUntilIdle(); EXPECT_TRUE(pending_read_); EXPECT_EQ(demuxer_reads_satisfied, video_frame_stream_->get_pending_buffers_size_for_testing()); decoder2_->SatisfyInit(); decoder2_->HoldDecode(); message_loop_.RunUntilIdle(); // Make sure the pending buffers have been transfered to fallback buffers. // One call to Decode() during the initialization process, so we expect one // buffer to already have been consumed from the fallback buffers. // Pending buffers should never go down (unless we encounter a config change) EXPECT_EQ(demuxer_reads_satisfied - 1, video_frame_stream_->get_fallback_buffers_size_for_testing()); EXPECT_EQ(demuxer_reads_satisfied, video_frame_stream_->get_pending_buffers_size_for_testing()); decoder2_->SatisfyDecode(); message_loop_.RunUntilIdle(); // Make sure all buffers consumed by |decoder2_| have come from the fallback. // Pending buffers should not have been cleared yet. EXPECT_EQ(0, video_frame_stream_->get_fallback_buffers_size_for_testing()); EXPECT_EQ(demuxer_reads_satisfied, video_frame_stream_->get_pending_buffers_size_for_testing()); EXPECT_EQ(video_frame_stream_->get_previous_decoder_for_testing(), decoder1_); EXPECT_TRUE(pending_read_); // Give the decoder one more buffer, enough to release a frame. demuxer_stream_->SatisfyReadAndHoldNext(); message_loop_.RunUntilIdle(); // New buffers should not have been added after the frame was released. EXPECT_EQ(video_frame_stream_->get_pending_buffers_size_for_testing(), 0); EXPECT_FALSE(pending_read_); demuxer_stream_->SatisfyRead(); // Confirm no frames were dropped. ReadAllFrames(); } TEST_P(VideoFrameStreamTest, FallbackDecoder_SelectedOnDecodeThenInitErrors) { Initialize(); decoder1_->SimulateError(); decoder2_->SimulateFailureToInit(); ReadOneFrame(); // |video_frame_stream_| should have fallen back to |decoder3_| ASSERT_FALSE(pending_read_); ASSERT_EQ(VideoFrameStream::OK, last_read_status_); // Can't check |decoder1_| or |decoder2_| right now, they might have been // destroyed already. ASSERT_GT(decoder3_->total_bytes_decoded(), 0); // Verify no frame was dropped. ReadAllFrames(); } TEST_P(VideoFrameStreamTest, FallbackDecoder_SelectedOnInitThenDecodeErrors) { decoder1_->SimulateFailureToInit(); decoder2_->HoldDecode(); Initialize(); ReadOneFrame(); decoder2_->SimulateError(); message_loop_.RunUntilIdle(); // |video_frame_stream_| should have fallen back to |decoder3_| ASSERT_FALSE(pending_read_); ASSERT_EQ(VideoFrameStream::OK, last_read_status_); // Can't check |decoder1_| or |decoder2_| right now, they might have been // destroyed already. ASSERT_GT(decoder3_->total_bytes_decoded(), 0); // Verify no frame was dropped. ReadAllFrames(); } TEST_P(VideoFrameStreamTest, FallbackDecoder_NotSelectedOnMidstreamDecodeError) { Initialize(); ReadOneFrame(); // Successfully received a frame. EXPECT_FALSE(pending_read_); ASSERT_GT(decoder1_->total_bytes_decoded(), 0); decoder1_->SimulateError(); // The error must surface from Read() as DECODE_ERROR. while (last_read_status_ == VideoFrameStream::OK) { ReadOneFrame(); message_loop_.RunUntilIdle(); EXPECT_FALSE(pending_read_); } // Verify the error was surfaced, rather than falling back to |decoder2_|. EXPECT_FALSE(pending_read_); ASSERT_EQ(decoder2_->total_bytes_decoded(), 0); ASSERT_EQ(VideoFrameStream::DECODE_ERROR, last_read_status_); } TEST_P(VideoFrameStreamTest, DecoderErrorWhenNotReading) { Initialize(); decoder1_->HoldDecode(); ReadOneFrame(); EXPECT_TRUE(pending_read_); // Satisfy decode requests until we get the first frame out. while (pending_read_) { decoder1_->SatisfySingleDecode(); message_loop_.RunUntilIdle(); } // Trigger an error in the decoding. decoder1_->SimulateError(); // The error must surface from Read() as DECODE_ERROR. while (last_read_status_ == VideoFrameStream::OK) { ReadOneFrame(); message_loop_.RunUntilIdle(); EXPECT_FALSE(pending_read_); } EXPECT_EQ(VideoFrameStream::DECODE_ERROR, last_read_status_); } TEST_P(VideoFrameStreamTest, FallbackDecoderSelectedOnFailureToReinitialize) { Initialize(); decoder1_->SimulateFailureToInit(); // Holding decode, because large decoder delays might cause us to get rid of // |previous_decoder_| before we are in a pending state again. decoder2_->HoldDecode(); ReadUntilDecoderReinitialized(decoder1_); ASSERT_TRUE(video_frame_stream_->get_previous_decoder_for_testing()); decoder2_->SatisfyDecode(); message_loop_.RunUntilIdle(); ReadAllFrames(); ASSERT_FALSE(video_frame_stream_->get_previous_decoder_for_testing()); } TEST_P(VideoFrameStreamTest, FallbackDecoderSelectedOnFailureToReinitialize_Twice) { Initialize(); decoder1_->SimulateFailureToInit(); ReadUntilDecoderReinitialized(decoder1_); ReadOneFrame(); decoder2_->SimulateFailureToInit(); ReadUntilDecoderReinitialized(decoder2_); ReadAllFrames(); } TEST_P(VideoFrameStreamTest, DecodeErrorAfterFallbackDecoderSelectionFails) { Initialize(); decoder1_->SimulateFailureToInit(); decoder2_->SimulateFailureToInit(); decoder3_->SimulateFailureToInit(); ReadUntilDecoderReinitialized(decoder1_); // The error will surface from Read() as DECODE_ERROR. while (last_read_status_ == VideoFrameStream::OK) { ReadOneFrame(); message_loop_.RunUntilIdle(); EXPECT_FALSE(pending_read_); } EXPECT_EQ(VideoFrameStream::DECODE_ERROR, last_read_status_); } TEST_P(VideoFrameStreamTest, Destroy_DuringFallbackDecoderSelection) { Initialize(); decoder1_->SimulateFailureToInit(); EnterPendingState(DECODER_REINIT); decoder2_->HoldNextInit(); SatisfyPendingCallback(DECODER_REINIT); } } // namespace media
30.454705
80
0.727496
maidiHaitai
f79b3b17326575775c777a0575f8367f879ec7d0
79
cpp
C++
vendor/github.com/bep/golibsass/internal/libsass/stylesheet.cpp
f110/hugo
d99379094f1352ece8751b54ace8964d0811916e
[ "Apache-2.0" ]
17
2020-02-06T22:21:59.000Z
2022-02-17T09:14:36.000Z
vendor/github.com/bep/golibsass/internal/libsass/stylesheet.cpp
f110/hugo
d99379094f1352ece8751b54ace8964d0811916e
[ "Apache-2.0" ]
5
2020-02-12T14:41:49.000Z
2021-11-03T19:45:00.000Z
vendor/github.com/bep/golibsass/internal/libsass/stylesheet.cpp
f110/hugo
d99379094f1352ece8751b54ace8964d0811916e
[ "Apache-2.0" ]
5
2020-02-28T08:01:50.000Z
2021-06-14T14:28:58.000Z
#ifndef USE_LIBSASS_SRC #include "../../libsass_src/src/stylesheet.cpp" #endif
19.75
47
0.759494
f110
f79e4d3d0d08758c029c1a0777b72963507d59c7
480
cpp
C++
abc073/abc073_c.cpp
crazystylus/AtCoderPractice
8e0f56a9b3905e11f83f351af66af5bfed8606b2
[ "MIT" ]
null
null
null
abc073/abc073_c.cpp
crazystylus/AtCoderPractice
8e0f56a9b3905e11f83f351af66af5bfed8606b2
[ "MIT" ]
null
null
null
abc073/abc073_c.cpp
crazystylus/AtCoderPractice
8e0f56a9b3905e11f83f351af66af5bfed8606b2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define rep(i, n) for (int i = 0; i < n; i++) const int mod = 1e9 + 7; // 10^9 + 7; const int N = 1e5 + 1; /////////////////// int n; void solve() { int a; unordered_map<int, bool> hm; cin >> n; rep(i, n) { cin >> a; if (hm.find(a) == hm.end()) hm[a] = true; else hm.erase(a); } cout << hm.size() << "\n"; } int main() { solve(); return 0; }
17.777778
45
0.50625
crazystylus
f7a1768f3a9de02f8d54c2d4d98edc0f542d978a
38,078
cpp
C++
OCVWarp.cpp
hn-88/OCVWarp
8cae8dc544bad18bc91a2c6635b6edb96985b4bc
[ "MIT" ]
2
2020-04-01T02:43:13.000Z
2020-06-28T13:52:03.000Z
OCVWarp.cpp
hn-88/OCVWarp
8cae8dc544bad18bc91a2c6635b6edb96985b4bc
[ "MIT" ]
13
2020-04-01T08:06:50.000Z
2021-01-16T15:47:15.000Z
OCVWarp.cpp
hn-88/OCVWarp
8cae8dc544bad18bc91a2c6635b6edb96985b4bc
[ "MIT" ]
null
null
null
#ifdef _WIN64 #include "windows.h" #endif /* * OCVWarp.cpp * * Warps video files using the OpenCV framework. * Appends F to the filename and saves as default codec (DIVX avi) in the same folder. * * first commit: * Hari Nandakumar * 25 Jan 2020 * * */ //#define _WIN64 //#define __unix__ // references // http://paulbourke.net/geometry/transformationprojection/ // equations in figure at http://paulbourke.net/dome/dualfish2sphere/ // http://paulbourke.net/dome/dualfish2sphere/diagram.pdf // http://www.fmwconcepts.com/imagemagick/fisheye2pano/index.php // http://www.fmwconcepts.com/imagemagick/pano2fisheye/index.php // // https://docs.opencv.org/3.4/d8/dfe/classcv_1_1VideoCapture.html // https://docs.opencv.org/3.4/d7/d9e/tutorial_video_write.html // https://docs.opencv.org/3.4.9/d1/da0/tutorial_remap.html // https://stackoverflow.com/questions/60221/how-to-animate-the-command-line // https://stackoverflow.com/questions/11498169/dealing-with-angle-wrap-in-c-code // https://blog.kowalczyk.info/article/j/guide-to-predefined-macros-in-c-compilers-gcc-clang-msvc-etc..html // Pertinent equations from pano2fisheye: // fov=180 for fisheye // fov=2*phimax or phimax=fov/2 // note rmax=N/2; N=height of input // linear: r=f*phi; f=rmax/phimax; f=(N/2)/((fov/2)*(pi/180))=N*180/(fov*pi) // substitute fov=180 // linear: f=N/pi // linear: phi=r*pi/N // https://stackoverflow.com/questions/46883320/conversion-from-dual-fisheye-coordinates-to-equirectangular-coordinates // taking Paul's page as ref, http://paulbourke.net/dome/dualfish2sphere/diagram.pdf /* // 2D fisheye to 3D vector phi = r * aperture / 2 theta = atan2(y, x) // 3D vector to longitude/latitude longitude = atan2(Py, Px) latitude = atan2(Pz, (Px^2 + Py^2)^(0.5)) // 3D vector to 2D equirectangular x = longitude / PI y = 2 * latitude / PI * ***/ /* * https://groups.google.com/forum/#!topic/hugin-ptx/wB-4LJHH5QI * panotools code * */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ #include <unistd.h> #endif #include <string.h> #include <time.h> //#include <sys/stat.h> // this is for mkdir #include <opencv2/opencv.hpp> #include "tinyfiledialogs.h" #define CV_PI 3.1415926535897932384626433832795 using namespace cv; // some global variables std::string strpathtowarpfile; Mat meshu, meshv, meshx, meshy, meshi, I; Mat map2x, map2y; float maxx=0, minx=0; float maxu=0, minu=0, maxv=0, minv=0; // meshx is in the range [-aspectratio, aspectratio] // we assume meshy is in the range [-1,1] // meshu and meshv in [0,1] bool ReadMesh(std::string strpathtowarpfile) { //from https://github.com/hn-88/GL_warp2Avi/blob/master/GL2AviView.cpp // and http://paulbourke.net/dataformats/meshwarp/ FILE *input = NULL; input = fopen(strpathtowarpfile.c_str(), "r"); /* Set rows and columns to 2 initially, as this is the size of the default mesh. */ int dummy, rows = 2, cols = 2; if (input != NULL) { fscanf(input, " %d %d %d ", &dummy, &cols, &rows) ; float x, y, u, v, l; //meshrows=rows; //meshcolumns=cols; meshx = Mat(Size(cols,rows), CV_32FC1); meshy = Mat(Size(cols,rows), CV_32FC1); meshu = Mat(Size(cols,rows), CV_32FC1); meshv = Mat(Size(cols,rows), CV_32FC1); meshi = Mat(Size(cols,rows), CV_32FC1); for (int r = 0; r < rows ; r++) { for (int c = 0; c < cols ; c++) { fscanf(input, "%f %f %f %f %f", &x, &y, &u, &v, &l) ; if (x<minx) minx = x; else if (x>maxx) maxx = x; if (u<minu) minu = u; else if (u>maxu) maxu = u; if (v<minv) minv = v; else if (v>maxv) maxv = v; //~ mesh[cols*r+c].x = x; //~ mesh[cols*r+c].y = y; //~ mesh[cols*r+c].u = u; //~ mesh[cols*r+c].v = v; //~ mesh[cols*r+c].i = l; meshx.at<float>(r,c) = x; meshy.at<float>(r,c) = y; meshu.at<float>(r,c) = u; meshv.at<float>(r,c) = v; meshi.at<float>(r,c) = l; } } } else // unable to read mesh { std::cout << "Unable to read mesh data file (similar to EP_xyuv_1920.map), exiting!" << std::endl; exit(0); } return 1; } void update_map( double anglex, double angley, Mat &map_x, Mat &map_y, int transformtype ) { // explanation comments are most verbose in the last // default (transformtype == 0) section switch (transformtype) { case 5: // 360 to 180 fisheye and then to warped //if (transformtype == 5) { // create temp maps to the texture and then map from texture to output // this will need 2 remaps at the output side // and two sets of map files // the map file for the first remap has to change with change of anglex angley // the second one, for fisheye to warped, doesn't need to be recalculated. // so, update_map is called first to initialize map_x and map_y // using transformtype = 4 // and later, and at all other times, only the map to the texture is updated. update_map( anglex, angley, map2x, map2y, 1 ); } break; case 4: //if (transformtype == 4) // fisheye to warped { // similar to TGAWarp at http://paulbourke.net/dome/tgawarp/ // Mat U, V, X, Y, IC1; Mat indexu, indexv, indexx, indexy, temp; ReadMesh(strpathtowarpfile); //resize(meshx, X, map_x.size(), INTER_LINEAR); //resize(meshy, Y, map_x.size(), INTER_LINEAR); //debug - changed INTER_LINEAR to INTER_LANCZOS4 and later INTER_CUBIC // not much of a penalty, so we leave it in. // discard the top/bottom line of U and V, since they cause // the bottom of the image to be repeats of the same //~ Mat meshub, meshvb; //~ meshu(cv::Rect(0,0,meshu.cols,(meshu.rows-1))).copyTo(meshub); //~ meshv(cv::Rect(0,0,meshv.cols,(meshv.rows-1))).copyTo(meshvb); // this doesn't work // for per pixel equivalence with GL_warp, the following seems to be needed int extrarows = map_x.rows / meshu.rows ; int extracols = map_x.cols / meshu.cols; resize(meshu, U, Size(map_x.cols+extracols, (map_x.rows+extrarows)), INTER_CUBIC); resize(meshv, V, Size(map_x.cols+extracols, (map_x.rows+extrarows)), INTER_CUBIC); //resize(meshu, U, map_x.size(), INTER_CUBIC); //resize(meshv, V, map_x.size(), INTER_CUBIC); resize(meshi, IC1, map_x.size(), INTER_CUBIC); // I.convertTo(I, CV_32FC3); //this doesn't work //convert to 3 channel Mat, for later multiplication // https://stackoverflow.com/questions/23303305/opencv-element-wise-matrix-multiplication/23310109 Mat t[] = {IC1, IC1, IC1}; merge(t, 3, I); // map the values which are [minx,maxx] to [0,map_x.cols-1] //~ temp = (map_x.cols-1)*(X - minx)/(maxx-minx); //~ temp.convertTo(indexx, CV_32S); // this does the rounding to int //~ temp = (map_x.rows-1)*(Y+1)/2; // assuming miny=-1, maxy=1 //~ temp.convertTo(indexy, CV_32S); temp = (map_x.cols-1)*U; // assuming minu=0, maxu=1 temp.convertTo(indexu, CV_32S); // this does the rounding to int temp = (map_x.rows-1)*V; // assuming minv=0, maxv=1 //~ temp = (map_x.rows)*(V-minv)/(maxv-minv); temp.convertTo(indexv, CV_32S); int linestodiscard = map_x.rows / meshu.rows / 2; int colstodiscard = map_x.cols / meshu.cols / 2; for ( int i = 0; i < (map_x.rows); i++ ) // here, i is for y and j is for x { for ( int j = 0; j < map_x.cols; j++ ) { //~ map_x.at<float>(i, j) = (float)(j); // this just maps input to output //~ map_y.at<float>(i, j) = (float)(i); // in the following, we assume indexx.at<int>(i,j) = j // and indexy.at<int>(i,j) = i // otherwise, a mesh effect due to discontinuities in indexx and indexy. map_x.at<float>(i,j) = (float) indexu.at<int>(i+linestodiscard,j+colstodiscard); map_y.at<float>(i,j) = (float) indexv.at<int>(i+linestodiscard,j+colstodiscard); } //end for j } //end for i return; } break; case 3: //if (transformtype == 3) // fisheye to Equirectangular - dual output - using parallel projection { // int xcd = floor(map_x.cols/2) - 1 + anglex; // this just 'pans' the view // int ycd = floor(map_x.rows/2) - 1 + angley; int xcd = floor(map_x.cols/2) - 1 ; int ycd = floor(map_x.rows/2) - 1 ; float px_per_theta = map_x.cols * 2 / (2*CV_PI); // src width = map_x.cols * 2 float px_per_phi = map_x.rows / CV_PI; // src height = PI for equirect 360 float rad_per_px = CV_PI / map_x.rows; float theta; float longi, lat, Px, Py, Pz, R; // X and Y are map_x and map_y float PxR, PyR, PzR; float aperture = CV_PI; // this is the only change between type 2 & 3 float angleyrad = -angley*CV_PI/180; // made these minus for more intuitive feel float anglexrad = -anglex*CV_PI/180; for ( int i = 0; i < map_x.rows; i++ ) // here, i is for y and j is for x { for ( int j = 0; j < map_x.cols; j++ ) { longi = (CV_PI ) * (j - xcd) / (map_x.cols/2); // longi = x.pi for 360 image lat = (CV_PI / 2) * (i - ycd) / (map_x.rows/2); // lat = y.pi/2 Px = cos(lat)*cos(longi); Py = cos(lat)*sin(longi); Pz = sin(lat); if(angley!=0 || anglex!=0) { // cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); PxR = Px; PyR = cos(angleyrad) * Py - sin(angleyrad) * Pz; PzR = sin(angleyrad) * Py + cos(angleyrad) * Pz; Px = cos(anglexrad) * PxR - sin(anglexrad) * PyR; Py = sin(anglexrad) * PxR + cos(anglexrad) * PyR; Pz = PzR; } if (Px == 0 && Py == 0 && Pz == 0) R = 0; else R = 2 * atan2(sqrt(Px*Px + Pz*Pz), Py) / aperture; if (Px == 0 && Pz ==0) theta = 0; else theta = atan2(Pz, Px); // map_x.at<float>(i, j) = R * cos(theta); this maps to [-1, 1] //map_x.at<float>(i, j) = R * cos(theta) * map_x.cols / 2 + xcd; map_x.at<float>(i, j) = - Px * map_x.cols / 2 + xcd; // this gives two copies in final output, top one reasonably correct // map_y.at<float>(i, j) = R * sin(theta); this maps to [-1, 1] //map_y.at<float>(i, j) = R * sin(theta) * map_x.rows / 2 + ycd; map_y.at<float>(i, j) = Py * map_x.rows / 2 + ycd; } // for j } // for i } break; case 2: //if (transformtype == 2) // 360 degree fisheye to Equirectangular 360 { // int xcd = floor(map_x.cols/2) - 1 + anglex; // this just 'pans' the view // int ycd = floor(map_x.rows/2) - 1 + angley; int xcd = floor(map_x.cols/2) - 1 ; int ycd = floor(map_x.rows/2) - 1 ; float px_per_theta = map_x.cols / (2*CV_PI); // width = map_x.cols float px_per_phi = map_x.rows / CV_PI; // height = PI for equirect 360 float rad_per_px = CV_PI / map_x.rows; float theta; float longi, lat, Px, Py, Pz, R; // X and Y are map_x and map_y float PxR, PyR, PzR; float aperture = 2*CV_PI; float angleyrad = -angley*CV_PI/180; // made these minus for more intuitive feel float anglexrad = -anglex*CV_PI/180; for ( int i = 0; i < map_x.rows; i++ ) // here, i is for y and j is for x { for ( int j = 0; j < map_x.cols; j++ ) { longi = (CV_PI ) * (j - xcd) / (map_x.cols/2); // longi = x.pi for 360 image lat = (CV_PI / 2) * (i - ycd) / (map_x.rows/2); // lat = y.pi/2 Px = cos(lat)*cos(longi); Py = cos(lat)*sin(longi); Pz = sin(lat); if(angley!=0 || anglex!=0) { // cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); PxR = Px; PyR = cos(angleyrad) * Py - sin(angleyrad) * Pz; PzR = sin(angleyrad) * Py + cos(angleyrad) * Pz; Px = cos(anglexrad) * PxR - sin(anglexrad) * PyR; Py = sin(anglexrad) * PxR + cos(anglexrad) * PyR; Pz = PzR; } if (Px == 0 && Py == 0 && Pz == 0) R = 0; else R = 2 * atan2(sqrt(Px*Px + Py*Py), Pz) / aperture; // exchanged Py and Pz from Paul's co-ords, // from Perspective projection the wrong imaging model 10.1.1.52.8827.pdf // http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.52.8827&rep=rep1&type=pdf // Or else, Africa ends up sideways, and with the far east and west streched out on top and bottom if (Px == 0 && Pz ==0) theta = 0; else theta = atan2(Py, Px); // map_x.at<float>(i, j) = R * cos(theta); this maps to [-1, 1] map_x.at<float>(i, j) = R * cos(theta) * map_x.cols / 2 + xcd; // currently upside down // map_y.at<float>(i, j) = R * sin(theta); this maps to [-1, 1] map_y.at<float>(i, j) = R * sin(theta) * map_x.rows / 2 + ycd; } // for j } // for i } break; case 1: //if (transformtype == 1) // Equirectangular 360 to 180 degree fisheye { // using the transformations at // http://paulbourke.net/dome/dualfish2sphere/diagram.pdf int xcd = floor(map_x.cols/2) - 1 ; int ycd = floor(map_x.rows/2) - 1 ; float halfcols = map_x.cols/2; float halfrows = map_x.rows/2; float longi, lat, Px, Py, Pz, theta; // X and Y are map_x and map_y float xfish, yfish, rfish, phi, xequi, yequi; float PxR, PyR, PzR; float aperture = CV_PI; float angleyrad = -angley*CV_PI/180; // made these minus for more intuitive feel float anglexrad = -anglex*CV_PI/180; //Mat inputmatrix, rotationmatrix, outputmatrix; // https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations //rotationmatrix = (Mat_<float>(3,3) << cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); //y //rotationmatrix = (Mat_<float>(3,3) << 1, 0, 0, 0, cos(angleyrad), -sin(angleyrad), 0, sin(angleyrad), cos(angleyrad)); //x //rotationmatrix = (Mat_<float>(3,3) << cos(angleyrad), -sin(angleyrad), 0, sin(angleyrad), cos(angleyrad), 0, 0, 0, 1); //z for ( int i = 0; i < map_x.rows; i++ ) // here, i is for y and j is for x { for ( int j = 0; j < map_x.cols; j++ ) { // normalizing to [-1, 1] xfish = (j - xcd) / halfcols; yfish = (i - ycd) / halfrows; rfish = sqrt(xfish*xfish + yfish*yfish); theta = atan2(yfish, xfish); phi = rfish*aperture/2; // Paul's co-ords - this is suitable when phi=0 is Pz=0 //Px = cos(phi)*cos(theta); //Py = cos(phi)*sin(theta); //Pz = sin(phi); // standard co-ords - this is suitable when phi=pi/2 is Pz=0 Px = sin(phi)*cos(theta); Py = sin(phi)*sin(theta); Pz = cos(phi); if(angley!=0 || anglex!=0) { // cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); PxR = Px; PyR = cos(angleyrad) * Py - sin(angleyrad) * Pz; PzR = sin(angleyrad) * Py + cos(angleyrad) * Pz; Px = cos(anglexrad) * PxR - sin(anglexrad) * PyR; Py = sin(anglexrad) * PxR + cos(anglexrad) * PyR; Pz = PzR; } longi = atan2(Py, Px); lat = atan2(Pz,sqrt(Px*Px + Py*Py)); // this gives south pole centred, ie yequi goes from [-1, 0] // Made into north pole centred by - (minus) in the final map_y assignment xequi = longi / CV_PI; // this maps to [-1, 1] yequi = 2*lat / CV_PI; // this maps to [-1, 0] for south pole //if (rfish <= 1.0) // outside that circle, let it be black // removed the black circle to help transformtype=5 // avoid bottom pixels black { map_x.at<float>(i, j) = abs(xequi * map_x.cols / 2 + xcd); //map_y.at<float>(i, j) = yequi * map_x.rows / 2 + ycd; // this gets south pole centred view // the abs is to correct for -0.5 xequi value at longi=0 map_y.at<float>(i, j) = yequi * map_x.rows / 2 + ycd; //debug //~ if (rfish <= 1.0/500) //if ((longi==0)||(longi==CV_PI)||(longi==-CV_PI)) //if (lat==0) // since these are floats, probably doesn't work //~ { //~ std::cout << "i,j,mapx,mapy="; //~ std::cout << i << ", "; //~ std::cout << j << ", "; //~ std::cout << map_x.at<float>(i, j) << ", "; //~ std::cout << map_y.at<float>(i, j) << std::endl; //~ } } } // for j } // for i } break; case 0: default: //else //if (transformtype == 0) // the default // Equirectangular 360 to 360 degree fisheye { // using code adapted from http://www.fmwconcepts.com/imagemagick/pano2fisheye/index.php // set destination (output) centers //~ // changing this to code based on Paul's diagram in version 2.1 // so that anglex and angley both work ////////////////////////////////////////////////////////////// //~ int xcd = floor(map_x.cols/2) - 1; //~ int ycd = floor(map_x.rows/2) - 1; //~ int xd, yd; //~ //define destination (output) coordinates center relative xd,yd //~ // "xd= x - xcd;" //~ // "yd= y - ycd;" //~ // compute input pixels per angle in radians //~ // theta ranges from -180 to 180 = 360 = 2*pi //~ // phi ranges from 0 to 90 = pi/2 //~ float px_per_theta = map_x.cols / (2*CV_PI); //~ float px_per_phi = map_x.rows / (CV_PI/2); //~ // compute destination radius and theta //~ float rd; // = sqrt(x^2+y^2); //~ // set theta so original is north rather than east //~ float theta; //= atan2(y,x); //~ // convert radius to phiang according to fisheye mode //~ //if projection is linear then //~ // destination output diameter (dimensions) corresponds to 180 deg = pi (fov); angle is proportional to radius //~ float rad_per_px = CV_PI / map_x.rows; //~ float phiang; // = rad_per_px * rd; //~ // convert theta to source (input) xs and phi to source ys //~ // -rotate 90 aligns theta=0 with north and is faster than including in theta computation //~ // y corresponds to h-phi, so that bottom of the input is center of output //~ // xs = width + theta * px_per_theta; //~ // ys = height - phiang * px_per_phi; //~ for ( int i = 0; i < map_x.rows; i++ ) // here, i is for y and j is for x //~ { //~ for ( int j = 0; j < map_x.cols; j++ ) //~ { //~ xd = j - xcd; //~ yd = i - ycd; //~ if (xd == 0 && yd == 0) //~ { //~ theta = 0 + anglex*CV_PI/180; //~ rd = 0; //~ } //~ else //~ { //~ //theta = atan2(float(yd),float(xd)); // this sets orig to east //~ // so America, at left of globe, becomes centred //~ theta = atan2(xd,yd) + anglex*CV_PI/180;; // this sets orig to north //~ // makes the fisheye left/right flipped if atan2(-xd,yd) //~ // so that Africa is centred when anglex = 0. //~ rd = sqrt(float(xd*xd + yd*yd)); //~ } //~ // move theta to [-pi, pi] //~ theta = fmod(theta+CV_PI, 2*CV_PI); //~ if (theta < 0) //~ theta = theta + CV_PI; //~ theta = theta - CV_PI; //~ //phiang = rad_per_px * rd + angley*CV_PI/180; // this zooms in/out, not rotate cam //~ phiang = rad_per_px * rd; //~ map_x.at<float>(i, j) = (float)round((map_x.cols/2) + theta * px_per_theta); //~ //map_y.at<float>(i, j) = (float)round((map_x.rows) - phiang * px_per_phi); //~ // this above makes the south pole the centre. //~ map_y.at<float>(i, j) = phiang * px_per_phi; //~ // this above makes the north pole the centre of the fisheye //~ // map_y.at<float>(i, j) = phiang * px_per_phi - angley; //this just zooms out //~ // the following test mapping just makes the src upside down in dst //~ // map_x.at<float>(i, j) = (float)j; //~ // map_y.at<float>(i, j) = (float)( i); //~ } // for j //~ } // for i ////////////////////////////////////// // the following code is similar to transformtype=1 code // with only the "aperture" changed to 2pi int xcd = floor(map_x.cols/2) - 1 ; int ycd = floor(map_x.rows/2) - 1 ; float halfcols = map_x.cols/2; float halfrows = map_x.rows/2; float longi, lat, Px, Py, Pz, theta; // X and Y are map_x and map_y float xfish, yfish, rfish, phi, xequi, yequi; float PxR, PyR, PzR; float aperture = 2*CV_PI; float angleyrad = -angley*CV_PI/180; // made these minus for more intuitive feel float anglexrad = -anglex*CV_PI/180; //Mat inputmatrix, rotationmatrix, outputmatrix; // https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations //rotationmatrix = (Mat_<float>(3,3) << cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); //y //rotationmatrix = (Mat_<float>(3,3) << 1, 0, 0, 0, cos(angleyrad), -sin(angleyrad), 0, sin(angleyrad), cos(angleyrad)); //x //rotationmatrix = (Mat_<float>(3,3) << cos(angleyrad), -sin(angleyrad), 0, sin(angleyrad), cos(angleyrad), 0, 0, 0, 1); //z for ( int i = 0; i < map_x.rows; i++ ) // here, i is for y and j is for x { for ( int j = 0; j < map_x.cols; j++ ) { // normalizing to [-1, 1] xfish = (j - xcd) / halfcols; yfish = (i - ycd) / halfrows; rfish = sqrt(xfish*xfish + yfish*yfish); theta = atan2(yfish, xfish); phi = rfish*aperture/2; // Paul's co-ords - this is suitable when phi=0 is Pz=0 //Px = cos(phi)*cos(theta); //Py = cos(phi)*sin(theta); //Pz = sin(phi); // standard co-ords - this is suitable when phi=pi/2 is Pz=0 Px = sin(phi)*cos(theta); Py = sin(phi)*sin(theta); Pz = cos(phi); if(angley!=0 || anglex!=0) { // cos(angleyrad), 0, sin(angleyrad), 0, 1, 0, -sin(angleyrad), 0, cos(angleyrad)); PxR = Px; PyR = cos(angleyrad) * Py - sin(angleyrad) * Pz; PzR = sin(angleyrad) * Py + cos(angleyrad) * Pz; Px = cos(anglexrad) * PxR - sin(anglexrad) * PyR; Py = sin(anglexrad) * PxR + cos(anglexrad) * PyR; Pz = PzR; } longi = atan2(Py, Px); lat = atan2(Pz,sqrt(Px*Px + Py*Py)); // this gives south pole centred, ie yequi goes from [-1, 0] // Made into north pole centred by - (minus) in the final map_y assignment xequi = longi / CV_PI; // this maps to [-1, 1] yequi = 2*lat / CV_PI; // this maps to [-1, 0] for south pole //if (rfish <= 1.0) // outside that circle, let it be black // removed the black circle to help transformtype=5 // avoid bottom pixels black { map_x.at<float>(i, j) = abs(xequi * map_x.cols / 2 + xcd); //map_y.at<float>(i, j) = yequi * map_x.rows / 2 + ycd; // this gets south pole centred view // the abs is to correct for -0.5 xequi value at longi=0 map_y.at<float>(i, j) = yequi * map_x.rows / 2 + ycd; } } // for j } // for i } // end of if transformtype == 0 } // end switch case } // end function updatemap std::string escaped(const std::string& input) { // https://stackoverflow.com/questions/48260879/how-to-replace-with-in-c-string std::string output; output.reserve(input.size()); for (const char c: input) { switch (c) { case '\a': output += "\\a"; break; case '\b': output += "\\b"; break; case '\f': output += "\\f"; break; case '\n': output += "\\n"; break; case '\r': output += "\\r"; break; case '\t': output += "\\t"; break; case '\v': output += "\\v"; break; default: output += c; break; } } return output; } int main(int argc,char *argv[]) { //////////////////////////////////////////////////////////////////// // Initializing variables //////////////////////////////////////////////////////////////////// bool doneflag = 0, interactivemode = 0; bool showdisplay = 1; double anglex = 0; double angley = 0; int outputw = 1920; int outputh = 1080; int texturew = 2048; std::string tempstring; //std::string strpathtowarpfile; making this a global var strpathtowarpfile = "EP_xyuv_1920.map"; char anglexstr[40]; char angleystr[40]; char outputfourccstr[40]; // leaving extra chars for not overflowing too easily outputfourccstr[0] = 'N'; outputfourccstr[1] = 'U'; outputfourccstr[2] = 'L'; outputfourccstr[3] = 'L'; //const bool askOutputType = argv[3][0] =='Y'; // If false it will use the inputs codec type // this line above causes the windows build to not run! although it compiles ok. // askOutputType=1 works only on Windows (vfw?) currently const bool askOutputType = 0; std::ifstream infile("OCVWarp.ini"); int transformtype = 0; // 0 = Equirectangular to 360 degree fisheye // 1 = Equirectangular to 180 degree fisheye int ind = 1; // inputs from ini file if (infile.is_open()) { infile >> tempstring; infile >> tempstring; infile >> tempstring; // first three lines of ini file are comments infile >> anglexstr; infile >> tempstring; infile >> angleystr; infile >> tempstring; infile >> outputw; infile >> tempstring; infile >> outputh; infile >> tempstring; infile >> transformtype; infile >> tempstring; infile >> outputfourccstr; infile >> tempstring; infile >> strpathtowarpfile; infile.close(); anglex = atof(anglexstr); angley = atof(angleystr); } else std::cout << "Unable to open ini file, using defaults." << std::endl; std::cout << "Output codec type: " << outputfourccstr << std::endl; namedWindow("Display", WINDOW_NORMAL | WINDOW_KEEPRATIO); // 0 = WINDOW_NORMAL resizeWindow("Display", round((float)(outputw)/(float)(outputh)*600), 600); // this doesn't work? moveWindow("Display", 0, 0); char const * FilterPatterns[2] = { "*.avi","*.*" }; char const * OpenFileName = tinyfd_openFileDialog( "Open a video file", "", 2, FilterPatterns, NULL, 0); if (! OpenFileName) { tinyfd_messageBox( "Error", "No file chosen. ", "ok", "error", 1); return 1 ; } // reference: // https://docs.opencv.org/3.4/d7/d9e/tutorial_video_write.html #ifdef __unix__ VideoCapture inputVideo(OpenFileName); // Open input #else // #ifdef _WIN64 assuming Windows // otherwise, multiple definitions when building on Windows x64 // Here, OpenCV on Windows needs escaped file paths. // https://stackoverflow.com/questions/48260879/how-to-replace-with-in-c-string std::string escapedpath = escaped(std::string(OpenFileName)); VideoCapture inputVideo(escapedpath.c_str()); // Open input #endif //~ #ifdef _WIN32 //~ // Here, OpenCV on Windows needs escaped file paths. //~ // https://stackoverflow.com/questions/48260879/how-to-replace-with-in-c-string //~ std::string escapedpath = escaped(std::string(OpenFileName)); //~ VideoCapture inputVideo(escapedpath.c_str()); // Open input //~ #endif //~ #ifdef __MINGW32__ //~ // Here, OpenCV on Windows needs escaped file paths. //~ // https://stackoverflow.com/questions/48260879/how-to-replace-with-in-c-string //~ std::string escapedpath = escaped(std::string(OpenFileName)); //~ VideoCapture inputVideo(escapedpath.c_str()); // Open input //~ #endif //~ #ifdef __MINGW64__ //~ // Here, OpenCV on Windows needs escaped file paths. //~ // https://stackoverflow.com/questions/48260879/how-to-replace-with-in-c-string //~ std::string escapedpath = escaped(std::string(OpenFileName)); //~ VideoCapture inputVideo(escapedpath.c_str()); // Open input //~ #endif if (!inputVideo.isOpened()) { std::cout << "Could not open the input video: " << OpenFileName << std::endl; return -1; } #ifdef __unix__ std::string OpenFileNamestr = OpenFileName; #else //#ifdef _WIN64 // Here, OpenCV on Windows needs escaped file paths. std::string OpenFileNamestr = escapedpath; #endif //~ #ifdef _WIN32 //~ // Here, OpenCV on Windows needs escaped file paths. //~ std::string OpenFileNamestr = escapedpath; //~ #endif //~ #ifdef __MINGW32__ //~ // Here, OpenCV on Windows needs escaped file paths. //~ std::string OpenFileNamestr = escapedpath; //~ #endif //~ #ifdef __MINGW64__ //~ // Here, OpenCV on Windows needs escaped file paths. //~ std::string OpenFileNamestr = escapedpath; //~ #endif std::string::size_type pAt = OpenFileNamestr.find_last_of('.'); // Find extension point std::string NAME = OpenFileNamestr.substr(0, pAt) + "F" + ".avi"; // Form the new name with container // here, we give an option for the user to choose the output file // path as well as type (container, like mp4, mov, avi). char const * SaveFileName = tinyfd_saveFileDialog( "Now enter the output video file name, like output.mp4", "", 0, NULL, NULL); if (! SaveFileName) { tinyfd_messageBox( "No output file chosen.", "Will be saved as inputfilename + F.avi", "ok", "info", 1); } else { #ifdef __unix__ NAME = std::string(SaveFileName); #else // for Windows, escape the \ characters in the path escapedpath = escaped(std::string(SaveFileName)); NAME = escapedpath; #endif } int ex = static_cast<int>(inputVideo.get(CAP_PROP_FOURCC)); // Get Codec Type- Int form // Transform from int to char via Bitwise operators char EXT[] = {(char)(ex & 0XFF) , (char)((ex & 0XFF00) >> 8),(char)((ex & 0XFF0000) >> 16),(char)((ex & 0XFF000000) >> 24), 0}; Size S = Size((int) inputVideo.get(CAP_PROP_FRAME_WIDTH), // Acquire input size (int) inputVideo.get(CAP_PROP_FRAME_HEIGHT)); Size Sout = Size(outputw,outputh); VideoWriter outputVideo; // Open the output //#ifdef _WIN64 // OpenCV on Windows can ask for a suitable fourcc. //outputVideo.open(NAME, -1, inputVideo.get(CAP_PROP_FPS), Sout, true); // this doesn't work well with the ffmpeg dll - don't use this. //#endif if (!(outputfourccstr[0] == 'N' && outputfourccstr[1] == 'U' && outputfourccstr[2] == 'L' && outputfourccstr[3] == 'L')) outputVideo.open(NAME, outputVideo.fourcc(outputfourccstr[0], outputfourccstr[1], outputfourccstr[2], outputfourccstr[3]), inputVideo.get(CAP_PROP_FPS), Sout, true); else outputVideo.open(NAME, ex, inputVideo.get(CAP_PROP_FPS), Sout, true); if (!outputVideo.isOpened()) { std::cout << "Could not open the output video for write: " << NAME << std::endl; return -1; } std::cout << "Input frame resolution: Width=" << S.width << " Height=" << S.height << " of nr#: " << inputVideo.get(CAP_PROP_FRAME_COUNT) << std::endl; std::cout << "Input codec type: " << EXT << std::endl; int fps, key; int t_start, t_end; unsigned long long framenum = 0; Mat src, res, tmp; Mat dstfloat, dstmult, dstres, dstflip; std::vector<Mat> spl; Mat dst(Sout, CV_8UC3); // S = src.size, and src.type = CV_8UC3 Mat dst2; // temp dst, for double remap Mat map_x, map_y; if ((transformtype == 4) || (transformtype == 5) ) { //~ map_x = Mat(Size(outputw*2,outputh*2), CV_32FC1); // for 2x resampling //~ map_y = Mat(Size(outputw*2,outputh*2), CV_32FC1); // the above code causes gridlines to appear in output if (outputw<961) //1K texturew = 1024; // debug //texturew = outputw; else if (outputw<1921) //2K texturew = 2048; else if (outputw<3841) //4K texturew = 4096; else // (outputw<7681) //8K texturew = 8192; // debug - had set Size to outputw,h map_x = Mat(Size(texturew,texturew), CV_32FC1); // for upsampling map_y = Mat(Size(texturew,texturew), CV_32FC1); if (transformtype == 5) { dst2 = Mat(Size(texturew,texturew), CV_32FC1); } } else { map_x = Mat(Sout, CV_32FC1); map_y = Mat(Sout, CV_32FC1); } Mat dst_x, dst_y; // Mat map2x, map2y // these are made global vars Mat dst2x, dst2y; // for transformtype=5, double remap if (transformtype == 5) { map2x = Mat(Size(texturew,texturew), CV_32FC1); map2y = Mat(Size(texturew,texturew), CV_32FC1); map2x = Scalar((texturew+texturew)*10); map2y = Scalar((texturew+texturew)*10); // initializing so that it points outside the image // so that unavailable pixels will be black } map_x = Scalar((outputw+outputh)*10); map_y = Scalar((outputw+outputh)*10); // initializing so that it points outside the image // so that unavailable pixels will be black if (transformtype == 5) { update_map(anglex, angley, map_x, map_y, 4); // first initialize map_x and map_y for final warp, // which is exactly like transformtype=4 update_map(anglex, angley, map2x, map2y, 5); convertMaps(map_x, map_y, dst_x, dst_y, CV_16SC2); // supposed to make it faster to remap convertMaps(map2x, map2y, dst2x, dst2y, CV_16SC2); } else { update_map(anglex, angley, map_x, map_y, transformtype); // debug //~ dst_x = map_x; //~ dst_y = map_y; convertMaps(map_x, map_y, dst_x, dst_y, CV_16SC2); // supposed to make it faster to remap } t_start = time(NULL); fps = 0; for(;;) { inputVideo >> src; // read if (src.empty()) break; // check if at end //imshow("Display",src); key = waitKey(10); if(interactivemode) { if (transformtype==5) { // only map2 needs to be updated update_map(anglex, angley, map2x, map2y, 5); convertMaps(map2x, map2y, dst2x, dst2y, CV_16SC2); // supposed to make it faster to remap } else { update_map(anglex, angley, map_x, map_y, transformtype); convertMaps(map_x, map_y, dst_x, dst_y, CV_16SC2); // supposed to make it faster to remap } interactivemode = 0; } switch (transformtype) { case 5: // 360 to 180 fisheye and then to warped resize( src, res, Size(texturew, texturew), 0, 0, INTER_CUBIC); break; case 4: // 180 fisheye to warped // the transform needs a flipped source image, flipud flip(src, src, 0); // because the mesh assumes 0,0 is bottom left //debug - had changed to outputw, h resize( src, res, Size(texturew, texturew), 0, 0, INTER_CUBIC); break; case 3: // 360 fisheye to Equirect resize( src, res, Size(outputw, outputh), 0, 0, INTER_CUBIC); break; case 2: // 360 fisheye to Equirect resize( src, res, Size(outputw, outputh), 0, 0, INTER_CUBIC); break; case 1: // Equirect to 180 fisheye resize( src, res, Size(outputw, outputh), 0, 0, INTER_CUBIC); break; default: case 0: // Equirect to 360 fisheye resize( src, res, Size(outputw, outputh), 0, 0, INTER_CUBIC); break; } if (transformtype == 5) { // here we have two remaps remap( res, dst2, dst2x, dst2y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0) ); // the second remap needs flipping, like transformtype=4 flip(dst2, dst2, 0); // because the mesh assumes 0,0 is bottom left remap( dst2, dst, dst_x, dst_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0) ); } else { remap( res, dst, dst_x, dst_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0) ); } if ((transformtype == 4) || (transformtype == 5) ) { // multiply by the intensity Mat dst.convertTo(dstfloat, CV_32FC3); multiply(dstfloat, I, dstmult); //debug //dstmult = dstfloat; dstmult.convertTo(dstres, CV_8UC3); // this transform is 2x2 oversampled resize(dstres, dstflip, Size(outputw,outputh), 0, 0, INTER_AREA); flip(dstflip, dst, 0); // flip up down again } if(showdisplay) imshow("Display", dst); printf("\r"); fps++; t_end = time(NULL); if (t_end - t_start >= 5) { printf("Frame: %llu x: %.0f y: %.0f fps: %.1f \r", framenum++, anglex, angley, float(fps)/5 ); // extra spaces to delete previous line's characters if any fflush(stdout); t_start = time(NULL); fps = 0; } else { printf("Frame: %llu x: %.0f y: %.0f \r", framenum++, anglex, angley ); fflush(stdout); } //outputVideo.write(res); //save or outputVideo << dst; switch (key) { case 27: //ESC key case 'x': case 'X': doneflag = 1; break; case 'u': case '+': case '=': // increase angley angley = angley + 1.0; interactivemode = 1; break; case 'm': case '-': case '_': // decrease angley angley = angley - 1.0; interactivemode = 1; break; case 'k': case '}': case ']': // increase anglex anglex = anglex + 1.0; interactivemode = 1; break; case 'h': case '{': case '[': // decrease anglex anglex = anglex - 1.0; interactivemode = 1; break; case 'U': // increase angley angley = angley + 10.0; interactivemode = 1; break; case 'M': // decrease angley angley = angley - 10.0; interactivemode = 1; break; case 'K': // increase anglex anglex = anglex + 10.0; interactivemode = 1; break; case 'H': // decrease anglex anglex = anglex - 10.0; interactivemode = 1; break; case 'D': case 'd': // toggle display if(showdisplay) showdisplay=0; else showdisplay=1; break; default: break; } if (doneflag == 1) { break; } } // end for(;;) loop std::cout << std::endl << "Finished writing" << std::endl; return 0; } // end main
31.391591
131
0.582489
hn-88
f7a209035950c773455ca1b6e4c33fcd8dc85ae4
2,860
hxx
C++
engine/src/resources/memory_manager.hxx
Alabuta/VulkanIsland
f33a16fa163527270bc14d03bcfed06dbddbb416
[ "MIT" ]
null
null
null
engine/src/resources/memory_manager.hxx
Alabuta/VulkanIsland
f33a16fa163527270bc14d03bcfed06dbddbb416
[ "MIT" ]
null
null
null
engine/src/resources/memory_manager.hxx
Alabuta/VulkanIsland
f33a16fa163527270bc14d03bcfed06dbddbb416
[ "MIT" ]
1
2018-10-03T17:05:43.000Z
2018-10-03T17:05:43.000Z
#pragma once #include <memory> #include "main.hxx" #include "utility/mpl.hxx" #include "vulkan/device.hxx" namespace resource { class buffer; class image; class memory_manager; struct memory_allocator; } namespace resource { struct memory_requirements final { std::size_t size, alignment; std::uint32_t memory_type_bits; }; class memory_block final { public: VkDeviceMemory handle() const noexcept { return handle_; } std::size_t size() const noexcept { return size_; } std::size_t offset() const noexcept { return offset_; } std::uint32_t type_index() const noexcept { return type_index_; } graphics::MEMORY_PROPERTY_TYPE properties() const noexcept { return properties_; } bool is_linear() const noexcept { return is_linear_; } private: VkDeviceMemory handle_; std::size_t size_, offset_; std::uint32_t type_index_; graphics::MEMORY_PROPERTY_TYPE properties_; bool is_linear_; memory_block(VkDeviceMemory handle, std::size_t size, std::size_t offset, std::uint32_t type_index, graphics::MEMORY_PROPERTY_TYPE properties, bool is_linear) noexcept; friend resource::memory_allocator; }; class memory_manager final { public: static std::size_t constexpr kPAGE_ALLOCATION_SIZE{0x1000'0000}; // 256 MB explicit memory_manager(vulkan::device const &device); template<class T> requires mpl::is_one_of_v<std::remove_cvref_t<T>, resource::buffer, resource::image> std::shared_ptr<resource::memory_block> allocate_memory(T &&resource, graphics::MEMORY_PROPERTY_TYPE memory_property_types); private: vulkan::device const &device_; std::shared_ptr<resource::memory_allocator> allocator_; std::shared_ptr<resource::memory_block> allocate_buffer_memory(resource::buffer const &buffer, graphics::MEMORY_PROPERTY_TYPE memory_property_types); std::shared_ptr<resource::memory_block> allocate_image_memory(resource::image const &image, graphics::MEMORY_PROPERTY_TYPE memory_property_types); }; template<class T> requires mpl::is_one_of_v<std::remove_cvref_t<T>, resource::buffer, resource::image> std::shared_ptr<resource::memory_block> memory_manager::allocate_memory(T &&resource, graphics::MEMORY_PROPERTY_TYPE memory_property_types) { using resource_type = typename std::remove_cvref_t<T>; if constexpr (std::is_same_v<resource_type, resource::buffer>) return allocate_buffer_memory(resource, memory_property_types); else if constexpr (std::is_same_v<resource_type, resource::image>) return allocate_image_memory(resource, memory_property_types); else return { }; } }
29.484536
117
0.694755
Alabuta
f7a226310cc0c85788d78916241493e2048756e6
784
cpp
C++
doc/examples/judgegirl-20009/ISMQ-disjoint.cpp
morris821028/parallel-VGLCS
87fe1c71e14cf7ed6092f728b085b735cf683a4b
[ "Apache-2.0" ]
2
2017-02-11T08:45:21.000Z
2020-12-22T07:30:24.000Z
doc/examples/judgegirl-20009/ISMQ-disjoint.cpp
morris821028/parallel-VGLCS
87fe1c71e14cf7ed6092f728b085b735cf683a4b
[ "Apache-2.0" ]
2
2017-02-21T02:01:16.000Z
2017-02-24T00:13:34.000Z
doc/examples/judgegirl-20009/ISMQ-disjoint.cpp
morris821028/parallel-VGLCS
87fe1c71e14cf7ed6092f728b085b735cf683a4b
[ "Apache-2.0" ]
null
null
null
#include "ISMQ.h" #define MAXN (1<<24) static int32_t lIdx, x; static uint32_t value[MAXN], parent[MAXN]; static uint32_t weight[MAXN], leader[MAXN]; static uint32_t findp(uint32_t x) { return parent[x] == x ? x : (parent[x] = findp(parent[x])); } void init_ISMQ(int N) { x = -1, lIdx = -1; } void append_ISMQ(uint32_t V) { ++x; parent[x] = x; uint32_t u = x, weightR = 1; for (uint32_t *v = leader + lIdx; lIdx >= 0 && value[*v] <= V; v--, lIdx--) { if (weightR <= weight[lIdx]) u = (parent[u] = *v); else parent[*v] = u; weightR = weight[lIdx] + weightR; } ++lIdx; value[u] = V; leader[lIdx] = u; weight[lIdx] = weightR; } uint32_t query_ISMQ(uint32_t L) { return value[findp(L)]; }
24.5
81
0.552296
morris821028
f7a53650625e9d01c6746db137083a22d3293014
257
cpp
C++
answers/Jeevansh/Day1/question1.cpp
arc03/30-DaysOfCode-March-2021
6d6e11bf70280a578113f163352fa4fa8408baf6
[ "MIT" ]
22
2021-03-16T14:07:47.000Z
2021-08-13T08:52:50.000Z
answers/Jeevansh/Day1/question1.cpp
arc03/30-DaysOfCode-March-2021
6d6e11bf70280a578113f163352fa4fa8408baf6
[ "MIT" ]
174
2021-03-16T21:16:40.000Z
2021-06-12T05:19:51.000Z
answers/Jeevansh/Day1/question1.cpp
arc03/30-DaysOfCode-March-2021
6d6e11bf70280a578113f163352fa4fa8408baf6
[ "MIT" ]
135
2021-03-16T16:47:12.000Z
2021-06-27T14:22:38.000Z
#include<iostream> using namespace std; int main() { int n,i; cout<<"Enter value of n\n"; //number of times the loop needs to be executed cin>>n; for(i=1;i<=n;i++) { cout<<(i*i*i)+(2*i); cout<<" "; } return 0; }
17.133333
80
0.509728
arc03
f7a80c45731ec94d5a40e0d75f2160402e045f44
35,386
hpp
C++
src/include/core/smileComponent.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
245
2020-10-24T16:27:13.000Z
2022-03-31T03:01:11.000Z
src/include/core/smileComponent.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
41
2021-01-13T11:30:42.000Z
2022-01-14T14:36:11.000Z
src/include/core/smileComponent.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
43
2020-12-11T15:28:19.000Z
2022-03-20T11:55:58.000Z
/*F*************************************************************************** * This file is part of openSMILE. * * Copyright (c) audEERING GmbH. All rights reserved. * See the file COPYING for details on license terms. ***************************************************************************E*/ #ifndef __SMILE_COMPONENT_HPP #define __SMILE_COMPONENT_HPP #include <core/smileCommon.hpp> #include <core/configManager.hpp> #include <smileutil/JsonClasses.hpp> #include <chrono> #include <string> #define COMPONENT_DESCRIPTION_XXXX "example description" #define COMPONENT_NAME_XXXX "exampleName" #undef class class DLLEXPORT cComponentManager; class DLLEXPORT cSmileComponent; #define CMSG_textLen 64 #define CMSG_typenameLen 32 #define CMSG_nUserData 8 typedef enum { CUSTDATA_BINARY = 0, // unknown binary data CUSTDATA_TEXT = 100, // null terminated string CUSTDATA_JSONTEXT = 110, // json encoded as text CUSTDATA_CHAR = 110, // char array (size given in bytes by custDataSize) CUSTDATA_INT = 200, // array of ints (size given in bytes by custDataSize) CUSTDATA_FLOAT = 300, // array of floats (size given in bytes by custDataSize) CUSTDATA_DOUBLE = 400, // array of doubles (size given in bytes by custDataSize) CUSTDATA_FLOAT_DMEM = 500, // array of float_dmem (size given in bytes by custDataSize) CUSTDATA_CONTAINER = 1000 // container for object such as a JSON document, msgName will reveal details } eSmileMessageCustDataType; class DLLEXPORT cComponentMessage { public: // Note: since instances of this class may be accessed from other languages via the SMILEapi, // all fields must have types with fixed sizes on all supported platforms (e.g. use int instead of long). char msgtype[CMSG_typenameLen]; // message type name (used by receiver to identify message), set by constructor char msgname[CMSG_typenameLen]; // custom message name const char * sender; // name of sender component (filled in by sendComponentMessage in cSmileComponent) double smileTime; // seconds (accurate up to milliseconds) since componentManager startup (filled in by componentManager, TODO!) double userTime1; // user defined time double userTime2; // user defined time double readerTime; // readerTime in seconds (derived from vec->tmeta->vIdx and reader period in the tick the message ist sent), can also be -1.0 if not used! int msgid; // custom message id // -- message data -- double floatData[CMSG_nUserData]; // 8 freely usable doubles for message data, initialized with 0 int intData[CMSG_nUserData]; // 8 freely usable ints char msgtext[CMSG_textLen]; // 64 characters for message text, freely usable, initialized with all 0 int userflag1, userflag2, userflag3; void * custData; // pointer to custom message data (allocated by sender, to be freed by sender after call to sendComponentMessage) void * custData2; // pointer to custom message data (allocated by sender, to be freed by sender after call to sendComponentMessage) int custDataSize, custData2Size; // size (in bytes) of custData arrays. Used for network message senders (TODO: implement this properly in all components that allocate custData!) eSmileMessageCustDataType custDataType, custData2Type; // Type of custData arrays. Used for network message senders (TODO: implement this properly in all components that allocate custData!) cComponentMessage() { memset(this, 0, sizeof(cComponentMessage)); } cComponentMessage(const char *type, const char *name=NULL) : msgid(-1), sender(NULL), userflag1(0), userflag2(0), userflag3(0), smileTime(0.0), readerTime(-1.0), userTime1(0.0), userTime2(0.0), custData(NULL), custData2(NULL), custDataSize(0), custData2Size(0), custDataType(CUSTDATA_BINARY), custData2Type(CUSTDATA_BINARY) { if (type == NULL) memset(msgtype, 0, sizeof(char) * CMSG_typenameLen); else strncpy(msgtype, type, CMSG_typenameLen); if (name == NULL) memset(msgname, 0, sizeof(char) * CMSG_typenameLen); else strncpy(msgname, name, CMSG_typenameLen); memset(floatData, 0, sizeof(double) * CMSG_nUserData); memset(intData, 0, sizeof(int) * CMSG_nUserData); memset(msgtext, 0, sizeof(char) * CMSG_textLen); //printf("XXX: msgtype = '%s'\n", msgtype); //printf("XXX: msgname = '%s'\n", msgname); } char * createCustDataString(void * myCustData, int mySize, eSmileMessageCustDataType myType) { char * custDataText = NULL; if (myCustData != NULL) { if (myType == CUSTDATA_TEXT) { int strLength = mySize > 0 ? mySize : strlen((const char *)myCustData); custDataText = (char *)calloc(1, sizeof(char) * (strLength + 1)); strncpy(custDataText, (char *)myCustData, sizeof(char) * strLength); } else if (myType == CUSTDATA_CHAR) { custDataText = (char *)calloc(1, sizeof(char) * (mySize + 1)); strncpy(custDataText, (char *)myCustData, sizeof(char) * mySize); } else if (myType == CUSTDATA_FLOAT_DMEM) { std::string custDataFloats = "[ "; const FLOAT_DMEM *cdFloat = (const FLOAT_DMEM *)myCustData; int nSize = mySize / sizeof(FLOAT_DMEM); for (int i = 0; i < nSize - 1; i++) { char *tmp = myvprint("%f,", cdFloat[i]); custDataFloats += tmp; free(tmp); } if (nSize > 0) { char *tmp = myvprint("%f", cdFloat[nSize - 1]); custDataFloats += tmp; free(tmp); } custDataFloats += " ]"; custDataText = (char *)calloc(1, sizeof(char) * (custDataFloats.length() + 2) ); strncpy(custDataText, custDataFloats.c_str(), custDataFloats.length()); } } return custDataText; } // this function is outdated and will be removed in future releases... // it is advised to migrate to the new class // cSmileTcpJsonMessageFunctions /* * detail: * 0: print fewer fields, floatData 0 and intData 0 only * 10: print fewer fields, floatData 0-3 and intData 0-3 only * 20: print fewer field, float/int full * 30: print all fields, custData null * 40: print all fields, include custData */ // returned string must be freed by caller char * serializeToJson(int detail = 99, const char *recepient = NULL) { char msgtypeNullterminated[CMSG_typenameLen + 1]; char msgnameNullterminated[CMSG_typenameLen + 1]; strncpy(msgtypeNullterminated, msgtype, CMSG_typenameLen); strncpy(msgnameNullterminated, msgname, CMSG_typenameLen); msgtypeNullterminated[CMSG_typenameLen] = 0; msgnameNullterminated[CMSG_typenameLen] = 0; rapidjson::Document doc; doc.SetObject(); rapidjson::Document::AllocatorType &allocator = doc.GetAllocator(); if (recepient != NULL) { doc.AddMember("recepient", rapidjson::Value(recepient, allocator), allocator); } doc.AddMember("msgtype", rapidjson::Value(&msgtypeNullterminated[0], allocator), allocator); doc.AddMember("msgname", rapidjson::Value(&msgnameNullterminated[0], allocator), allocator); doc.AddMember("sender", rapidjson::Value(sender, allocator), allocator); doc.AddMember("smileTime", smileTime, allocator); doc.AddMember("userTime1", userTime1, allocator); if (detail >= 30) { doc.AddMember("userTime2", userTime2, allocator); doc.AddMember("readerTime", readerTime, allocator); } doc.AddMember("msgid", msgid, allocator); rapidjson::Value floatDataValue(rapidjson::kObjectType); for (int i = 0; i < CMSG_nUserData; i++) { std::string index = std::to_string(i); floatDataValue.AddMember(rapidjson::Value(index.c_str(), allocator).Move(), floatData[i], allocator); } doc.AddMember("floatData", floatDataValue, allocator); rapidjson::Value intDataValue(rapidjson::kObjectType); for (int i = 0; i < CMSG_nUserData; i++) { std::string index = std::to_string(i); intDataValue.AddMember(rapidjson::Value(index.c_str(), allocator).Move(), intData[i], allocator); } doc.AddMember("intData", intDataValue, allocator); doc.AddMember("msgtext", rapidjson::Value(msgtext, allocator), allocator); if (detail >= 30) { doc.AddMember("userflag1", userflag1, allocator); doc.AddMember("userflag2", userflag2, allocator); doc.AddMember("userflag3", userflag3, allocator); char *custDataText; char *custData2Text; if (detail >= 40) { custDataText = createCustDataString(custData, custDataSize, custDataType); // may return null custData2Text = createCustDataString(custData2, custData2Size, custData2Type); // may return null } else { custDataText = NULL; custData2Text = NULL; } if (custDataText != NULL) { doc.AddMember("custData", rapidjson::Value(custDataText, allocator), allocator); free(custDataText); } else { doc.AddMember("custData", rapidjson::Value(rapidjson::kNullType), allocator); } if (custData2Text != NULL) { doc.AddMember("custData2", rapidjson::Value(custData2Text, allocator), allocator); free(custData2Text); } else { doc.AddMember("custData2", rapidjson::Value(rapidjson::kNullType), allocator); } } rapidjson::StringBuffer str; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(str); writer.SetIndent(' ', 2); doc.Accept(writer); const char *jsonString = str.GetString(); return strdup(jsonString); } }; class DLLEXPORT sComponentInfo { public: int registerAgain; const char *componentName; const char *description; int abstract; // flag that indicates whether component is 'abstract' only (i.e. without practical functionality) int noDmem; int builtIn; // 1= built in component ; 0= dynamically linked component cSmileComponent * (*create) (const char *_instname); sComponentInfo * next; }; // create for a real class (which implements myFetchConfig() ) #define SMILECOMPONENT_CREATE(TP) cSmileComponent * TP::create(const char*_instname) { \ cSmileComponent *c = new TP(_instname); \ if (c!=NULL) c->setComponentInfo(scname,sdescription); \ return c; \ } // create for an abstract class #define SMILECOMPONENT_CREATE_ABSTRACT(TP) cSmileComponent * TP::create(const char*_instname) { return NULL; } // static declaration in Cpp file of derived class #define SMILECOMPONENT_STATICS(TP) const char *TP::scname; \ const char *TP::sdescription; // static declarations in derived class (public) #define SMILECOMPONENT_STATIC_DECL static sComponentInfo * registerComponent(cConfigManager *_confman, cComponentManager *_compman); \ static cSmileComponent * create(const char *_instname); // static declarations in derived class (protected) #define SMILECOMPONENT_STATIC_DECL_PR static const char *scname; \ static const char *sdescription; #define SMILECOMPONENT_REGCOMP(TP) sComponentInfo * TP::registerComponent(cConfigManager *_confman, cComponentManager *_compman) #define SMILECOMPONENT_REGCOMP_INIT if (_confman == NULL) return NULL; \ int rA = 0; #define SMILECOMPONENT_CREATE_CONFIGTYPE ConfigType *ct = new ConfigType(scname); \ if (ct == NULL) OUT_OF_MEMORY; #define SMILECOMPONENT_INHERIT_CONFIGTYPE(configtype) ConfigType *ct = NULL; \ const ConfigType *r = _confman->getTypeObj(configtype); \ if (r == NULL) { \ SMILE_WRN(4,"%s config Type not found!","configtype"); \ rA=1; \ } else { \ ct = new ConfigType( *(r) , scname ); \ } #define SMILECOMPONENT_REGISTER_CONFIGTYPE if (rA==0) { \ ConfigInstance *Tdflt = new ConfigInstance( scname, ct, 1 ); \ _confman->registerType(Tdflt); \ } #define SMILECOMPONENT_IFNOTREGAGAIN_BEGIN if (rA==0) { #define SMILECOMPONENT_IFNOTREGAGAIN_END SMILECOMPONENT_REGISTER_CONFIGTYPE } #define SMILECOMPONENT_IFNOTREGAGAIN(__code__) SMILECOMPONENT_IFNOTREGAGAIN_BEGIN __code__ ; SMILECOMPONENT_IFNOTREGAGAIN_END #define SMILECOMPONENT_MAKEINFO(TP) if ((rA!=0)&&(ct!=NULL)) delete ct; \ return makeInfo(_confman, scname, sdescription, TP::create, rA) #define SMILECOMPONENT_MAKEINFO_ABSTRACT(TP) if ((rA!=0)&&(ct!=NULL)) delete ct; \ return makeInfo(_confman, scname, sdescription, TP::create, rA, 1, 1) // make info for non-datamemory components (e.g. the cFunctionalXXXX components), e.g. components that are sub-components of other components #define SMILECOMPONENT_MAKEINFO_NODMEM(TP) if ((rA!=0)&&(ct!=NULL)) delete ct; \ return makeInfo(_confman, scname, sdescription, TP::create, rA, 0, 1) // make info for non-datamemory components (e.g. the cFunctionalXXXX components), e.g. components that are sub-components of other components #define SMILECOMPONENT_MAKEINFO_NODMEM_ABSTRACT(TP) if ((rA!=0)&&(ct!=NULL)) delete ct; \ return makeInfo(_confman, scname, sdescription, TP::create, rA, 1, 1) // return code of cSmileComponent::tick method typedef enum { TICK_INACTIVE = 0, // component did not perform any work in its tick method. If all other components also did not perform any work, component manager will exit the current tick loop TICK_SUCCESS = 1, // component did perform work. The tick loop is guaranteed to continue. TICK_SOURCE_NOT_AVAIL = 2, // component could not perform any work because it could not read required data from a source data memory level TICK_EXT_SOURCE_NOT_AVAIL = 3, // component could not perform any work because it could not read required data from an external source (e.g. sound device, network stream, etc.) TICK_DEST_NO_SPACE = 4, // component could not perform any work because there is not enough space in a destination data memory level where it could write its output TICK_EXT_DEST_NO_SPACE = 5 // component could not perform any work because there is not enough space in an external destination where it could write its output } eTickResult; constexpr int NUM_TICK_RESULTS = 6; // returns string representation of an eTickResult value const char *tickResultStr(eTickResult res); #undef class class DLLEXPORT cSmileComponent { private: int id_; // component ID in componentManager int EOI_; // EOI counter, 0 only in first loop, then +1 for every nonEOI/EOI loop pair int EOIcondition_; // flag that indicates end of input // i.e. if EOI is 1, myTick should show a different behaviour // esp. dataReaders should return right padded matrices, in getMatrix , getNextMatrix etc.. int EOIlevel_; // If set to >= 1, the isEOI will report EOI condition true only if EOI_ == EOIlevel_ ; int paused_; // flag that indicates whether processing (the tick loop) has been paused or is active smileMutex messageMtx_; cComponentManager *compman_; // pointer to component manager this component instance belongs to cSmileComponent *parent_; // pointer to parent component (for dataReaders, etc.) char *iname_; // name of component instance char *cfname_; // name of config instance associated with this component instance // variables used for component profiling int doProfile_, printProfile_; double profileCur_, profileSum_; // exec. time of last tick, exec time total std::chrono::time_point<std::chrono::high_resolution_clock> startTime_; std::chrono::time_point<std::chrono::high_resolution_clock> endTime_; eTickResult lastTickResult_; // return value of last call of myTick long lastNrun_; // the number of nRun in the last tick loop iteration protected: SMILECOMPONENT_STATIC_DECL_PR cConfigManager *confman_; // pointer to configManager const char *cname_; // name of the component (type) const char *description_; // component description and usage information // component state variables int isRegistered_, isConfigured_, isFinalised_, isReady_; int runMe_; int manualConfig_; int override_; static sComponentInfo * makeInfo(cConfigManager *_confman, const char *_name, const char *_description, cSmileComponent * (*create) (const char *_instname), int regAgain=0, int _abstract=0, int _nodmem=0); // Gets a pointer to the component instance *name via the component manager. cSmileComponent * getComponentInstance(const char * name) const; // Gets the component instance type of the instance *name as string via the component manager. const char * getComponentInstanceType(const char * name) const; // Create a component instance of given type with instance name "name" in the component manager. cSmileComponent * createComponent(const char *name, const char *component_type); // Gets the number of components ran during the last tick. long getLastNrun() const { return lastNrun_; } // Functions to get config values from the config manager from our config instance. // The _f functions internally free the string *name. Use these in conjunction with myvprint()... // NOTE: Yes, this is ineffective. TODO: smile memory manager, and fixed length text buffer which can be reused (can also grow if needed). void * getExternalPointer(const char *name) const { if (confman_ != NULL) { return confman_->getExternalPointer(name); } else { return NULL; } } void addExternalPointer(const char *name, void * ptr) { if (confman_ != NULL) { confman_->addExternalPointer(name, ptr); } } double getDouble(const char*name) const { return confman_->getDouble_f(myvprint("%s.%s",cfname_,name)); } double getDouble_f(char*name) const { double d = getDouble(name); if (name!=NULL) free(name); return d; } int getInt(const char*name) const { return confman_->getInt_f(myvprint("%s.%s",cfname_,name)); } int getInt_f(char*name) const { int d = getInt(name); if (name!=NULL) free(name); return d; } const char *getStr(const char*name) const { return confman_->getStr_f(myvprint("%s.%s",cfname_,name)); } const char * getStr_f(char*name) const { const char * s = getStr(name); if (name!=NULL) free(name); return s; } char getChar(const char*name) const { return confman_->getChar_f(myvprint("%s.%s",cfname_,name)); } const char getChar_f(char*name) const { const char c = getChar(name); if (name!=NULL) free(name); return c; } const ConfigValue *getValue(const char*name) const { return confman_->getValue_f(myvprint("%s.%s",cfname_,name)); } const ConfigValue * getValue_f(char*name) const { const ConfigValue * v = getValue(name); if (name!=NULL) free(name); return v; } const ConfigValueArr *getArray(const char*name) const { return (ConfigValueArr *)(confman_->getValue_f(myvprint("%s.%s",cfname_,name))); } const ConfigValueArr * getArray_f(char*name) const { const ConfigValueArr * a = getArray(name); if (name!=NULL) free(name); return a; } int getArraySize(const char*name) const { return (confman_->getArraySize_f(myvprint("%s.%s",cfname_,name))); } int getArraySize_f(char*name) const { int s = getArraySize(name); if (name!=NULL) free(name); return s; } char **getArrayKeys(const char*name, int*N = NULL) const { return confman_->getArrayKeys_f(myvprint("%s.%s",cfname_,name), N); } char **getArrayKeys_f(char*name, int*N = NULL) const { char **k = confman_->getArrayKeys(name, N); if (name!=NULL) free(name); return k; } int isSet(const char*name) const { return (confman_->isSet_f(myvprint("%s.%s",cfname_,name))); } int isSet_f(char*name) const { int s = isSet(name); if (name!=NULL) free(name); return s; } // Returns 1 if we are in an abort state (user requested abort). int isAbort() const; // Function that is called during initialisation. It should be used to fetch config variables // from the config manager and store them in local variables. // Each derived class is responsible for fetching configuration from confman or setting it manually BEFORE configureInstance is called! virtual void myFetchConfig() { } // Functions to be implemented by derived classes: // Sets the environment (pointers to parent, component manager, config manager). virtual void mySetEnvironment() { } // Registers the component instance after creation (by the component Manager). virtual int myRegisterInstance(int *runMe=NULL) { return 1; } // Configures the component instance. Data-memory levels and level parameters such as T are created and set here. virtual int myConfigureInstance() { return 1; } // Finalises the component instance. Data-memory level names (fields and elements) are set here. virtual int myFinaliseInstance() { return 1; } // Holds the actual implementation of the tick loop code for the derived component. // This function should return TICK_SUCCESS if the component did process data, // otherwise it should return the appropriate result code (see eTickResult definition). // If all components return non-success codes, the component manager will switch // to the EOI (end-of-input) state (or advance to the next tick loop iteration). virtual eTickResult myTick(long long t) { return TICK_INACTIVE; } // Called by the component manager when the tick loop is to be paused. // If the component needs to reject the pausing of the tick loop, it should return 0, otherwise always 1! virtual int pauseEvent() { return 1; } // Called by the component manager when the tick loop is to be resumed. virtual void resumeEvent() { } // Signals the component manager that this component has more data available to process. // If the tick loop is currently in a waiting state, this will wake it up to continue // processing. void signalDataAvailable(); // Checks if the given component message is of type "msgtype" (string name). int isMessageType(const cComponentMessage *msg, const char * msgtype) const { if (msg != NULL) { return (!strncmp(msg->msgtype, msgtype, CMSG_typenameLen)); } else { return 0; } } // Functions for component message handling. // Note on data synchronisation for messages: The messages can arrive at any time, if // they are sent from another thread. Thus, a mutex is used to prevent collision when // accessing variables from processComponentMessage and the rest of the component code // (especially myTick). The mutex is automatically locked before processComponentMessage // is called, and unlocked afterwards. In the rest of the code, however, lockMessageMemory() // and unlockMessageMemory() must be used. // This function is called by the component manager, if there is a new message for this component. // A derived component must override this to receive and process messages. // Do NOT call lockMessageMemory() in this function! The *msg pointer is always valid. // Return value: 0, message was not processed; != 0, message was processed. // The return value will be passed on to the sender (?). // NOTE: the custData pointer in cComponentMessage (as well as the whole cComponentMessage object) // is valid ONLY until processComponentMessage() returns! // Thus, you are advised to copy data to local memory // NOTE2: This function is called directly from the context of another component/thread. // Do NOT do anything here that is time consuming. It will block the other thread // or the execution of the tick loop. Esp. don't wait here until your own myTick() is called. // In single threaded mode this will never happen! // Always, only accept the message data and put it into a buffer. Process the buffer in myTick() // or in a background thread. virtual int processComponentMessage(cComponentMessage *msg) { return 0; } // this function forwards the message to the componentMananger and sets the *sender pointer correctly // Return value: 0, message was not processed; != 0, message was processed. // TODO: return value passing for multiple recepients? int sendComponentMessage(const char *recepient, cComponentMessage *msg); int sendJsonComponentMessage(const char * recepient, const rapidjson::Document& doc); char * jsonMessageToString(const rapidjson::Document& doc); rapidjson::Document * parseJsonMessage(const char *text, rapidjson::Document::AllocatorType * allocator); // Checks if the incoming message is a container for a JSON object message // and if yes, returns the JSON object message // otherwise, it returns NULL. rapidjson::Document * receiveJsonComponentMessage( cComponentMessage *msg); // Locks the "message memory" (variables that are accessed by processComponentMessage). // You must call this function prior to accessing variables you are accessing in processComponentMessage(). // Do not use this function in processComponentMessage() itself, though! void lockMessageMemory() { smileMutexLock(messageMtx_); } // Unlocks the "message memory" (variables that are accessed by processComponentMessage). void unlockMessageMemory() { smileMutexUnlock(messageMtx_); } // Gets the smile time from the component manager (time since start of the system). double getSmileTime() const; // Returns 1 if we are in an end-of-input condition. int isEOI() const { return EOIcondition_; } // Get the EOI counter, i.e. the number of repeated tick loop sequences. int getEOIcounter() const { return EOI_; } // Request stopping of processing in tickLoop of component manager. // Calling this will make openSMILE stop the processing. virtual void abortProcessing(); public: // Statics: // these two must be overridden in a base class: //static sComponentInfo * registerComponent(cConfigManager *_confman); //static cSmileComponent * create(const char *_instname); SMILECOMPONENT_STATIC_DECL // method for setting config... a base class may implement it with arbirtrary parameters // values set will override those obtained by myFetchConfig if override=1 // if override=0, then only those which are not set are updated // void setConfig(..., int override=1); int isManualConfigSet() const { return manualConfig_; } // Returns whether the tick loop is paused (1) or running (0). int isPaused() const { return paused_; } // Gets pointer to the associated component manager object, // i.e. the object that created this smile component instance. cComponentManager *getCompMan() const { return compman_; } // Gets pointer to the cSmileLogger associated with the component manager. cSmileLogger *getLogger() const; // Constructor that creates an instance of this component with instance name "instname". cSmileComponent(const char *instname); // Sets component name and description after component creation. virtual void setComponentInfo(const char *cname, const char *description) { cname_= cname; description_ = description; } // Sets component manager pointer and the component ID, as used by the component manager. // Called by the creator component (parent) or directly by the component manager. virtual void setComponentEnvironment(cComponentManager *compman, int id, cSmileComponent *parent=NULL); // Sets the name of the associated config instance this component instance is linked to. void setConfigInstanceName(const char *cfname) { if (cfname != NULL) { if ((cfname_ != NULL) && (cfname_ != iname_)) { free(cfname_); cfname_ = NULL; } cfname_ = strdup(cfname); } } // Gets the name of the associated config instance. const char * getConfigInstanceName() const { return cfname_; } void fetchConfig() { myFetchConfig(); } // Performs component specific register operation, e.g. write/read requests with dataMemory.. // *runMe return value for component manager : 0, don't call my tick of this component, 1, call myTick int registerInstance(int *runMe=NULL) { if (runMe != NULL) *runMe = runMe_; if (isRegistered_) return 1; isRegistered_ = myRegisterInstance(runMe); if (runMe != NULL) runMe_ = *runMe; return isRegistered_; } int isRegistered() const { return isRegistered_; } // Performs component configuration (data memory level configuration, creation of readers/writers etc.). int configureInstance() { if (isConfigured_) return 1; isConfigured_ = myConfigureInstance(); return isConfigured_; } int isConfigured() const { return isConfigured_; } // Performs component finalisation (loading of models, opening of files, data memory level names, ...). int finaliseInstance(); int isFinalised() const { return isFinalised_; } // Returns 1, if component has been finalised and is ready for the tick loop. Returns 0 otherwise. int isReady() const { return isReady_; } // This provides the possibility for components to indicate that they // are waiting for data (e.g. in live or streaming modes) and also // execute a sleep() or wait() in this method. // When an empty tick loop is encountered (all components return 0 in // componentManager), then this function is called for all components. // Normally the componentManager tick loop will exit in this case, and // the processing will enter the EOI (end of input) state. // If at least one component returns true, the tick loop will not enter EOI state // but continue as normal. Thus, the default is to return false. virtual bool notifyEmptyTickloop() { return false; } // The tick() function. This is called by the component manager, and internally executes myTick(), eTickResult tick(long long t, int EOIcond=0, long _lastNrun=-1) { lastNrun_ = _lastNrun; if (EOIcond) { if (!isEOI()) { setEOI(); return TICK_SUCCESS; // one "successful" tick to set up all components in EOI state } } else { unsetEOI(); } if (!isReady_) { return TICK_INACTIVE; } if (doProfile_) { startProfile(t, EOIcondition_); } lastTickResult_ = myTick(t); if (doProfile_) { endProfile(t, EOIcondition_); } return lastTickResult_; } eTickResult getLastTickResult() const { return lastTickResult_; } // Configures profiling (measuring of the time spent in each tick). void setProfiling(int enable=1, int print=0) { doProfile_ = enable; printProfile_ = print; } // Starts time measurement (called at the beginning of the tick). void startProfile(long long t, int EOI); // Ends time measurement (called at the end of the tick). void endProfile(long long t, int EOI); // Gets the current profiling statistics. // If sum == 1, it returns the accumulated run-time in seconds // (i.e. the time spent in tick() by this component). // If sum == 0, the duration of the last tick() is returned. // NOTE: For multi-threaded code this method of profiling is not exact. // The tick() function can be interrupted by other threads, but // time measurement is done via the system timer from start to end of tick(). double getProfile(int sum=1) const { if (!sum) return profileCur_; else return profileSum_; } // Gets the component instance name. const char *getInstName() const { return iname_; } // Gets the component type name. const char *getTypeName() const { return cname_; } // Sets the EOI counter. Used by the component manager once a new tick loop with EOIcondition=1 starts. // NOTE: it would be possible for the components to manage their own EOI counters, however, like this we ensure sync and better performance. // If derived components create sub-components internally (without tick function - e.g. dataReaders/Writers), // they must override this, in order to properly set the EOI status in the sub-components. virtual int setEOIcounter(int cnt) { EOI_ = cnt; return cnt; } // Sets and unsets the EOIcondition variable. This is called internally from tick() only. // If derived components create sub-components internally (without tick function - e.g. dataReaders/Writers), // they must override this, in order to properly set the EOI status in the sub-components. virtual void setEOI() { EOIcondition_ = 1; } virtual void unsetEOI() { EOIcondition_ = 0; } virtual void setEOIlevel(int level) { EOIlevel_ = level; } virtual int EOIlevelIsMatch() const { if (EOIlevel_ == EOI_ || EOIlevel_ <= 0) { return 1; } return 0; } virtual int getEOIlevel() const { return EOIlevel_; } // Called by the component manager. Notifies this component about a tick loop pause. virtual int pause() { if (!paused_) { paused_ = 1; return pauseEvent(); } return 1; } // Called by the component manager. Notifies this component about a tick loop resume. virtual void resume() { if (paused_) { paused_ = 0; resumeEvent(); } } // This function is called externally by the component manager, // if another component calls sendComponentMessage. // It receives the message, takes care of memory access synchronisation, and processes the message. int receiveComponentMessage(cComponentMessage *msg) { int ret = 0; if (msg != NULL) { lockMessageMemory(); ret = processComponentMessage(msg); unlockMessageMemory(); } return ret; } virtual ~cSmileComponent(); }; #endif //__SMILE_COMPONENT_HPP
44.122195
196
0.667072
elinjammal
f7a9ad7ffec282bf4bdb826d448eadc0c3adf4c5
5,960
hh
C++
openjdk11/src/java.desktop/share/native/libfontmanager/harfbuzz/hb-ot-os2-table.hh
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
null
null
null
openjdk11/src/java.desktop/share/native/libfontmanager/harfbuzz/hb-ot-os2-table.hh
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
null
null
null
openjdk11/src/java.desktop/share/native/libfontmanager/harfbuzz/hb-ot-os2-table.hh
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
null
null
null
/* * Copyright © 2011,2012 Google, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Google Author(s): Behdad Esfahbod */ #ifndef HB_OT_OS2_TABLE_HH #define HB_OT_OS2_TABLE_HH #include "hb-open-type-private.hh" #include "hb-ot-os2-unicode-ranges.hh" #include "hb-subset-plan.hh" namespace OT { /* * OS/2 and Windows Metrics * https://docs.microsoft.com/en-us/typography/opentype/spec/os2 */ #define HB_OT_TAG_os2 HB_TAG('O','S','/','2') struct os2 { static const hb_tag_t tableTag = HB_OT_TAG_os2; inline bool sanitize (hb_sanitize_context_t *c) const { TRACE_SANITIZE (this); return_trace (c->check_struct (this)); } inline bool subset (hb_subset_plan_t *plan) const { hb_blob_t *os2_blob = OT::Sanitizer<OT::os2>().sanitize (hb_face_reference_table (plan->source, HB_OT_TAG_os2)); hb_blob_t *os2_prime_blob = hb_blob_create_sub_blob (os2_blob, 0, -1); // TODO(grieger): move to hb_blob_copy_writable_or_fail hb_blob_destroy (os2_blob); OT::os2 *os2_prime = (OT::os2 *) hb_blob_get_data_writable (os2_prime_blob, nullptr); if (unlikely (!os2_prime)) { hb_blob_destroy (os2_prime_blob); return false; } uint16_t min_cp, max_cp; find_min_and_max_codepoint (plan->unicodes, &min_cp, &max_cp); os2_prime->usFirstCharIndex.set (min_cp); os2_prime->usLastCharIndex.set (max_cp); _update_unicode_ranges (plan->unicodes, os2_prime->ulUnicodeRange); bool result = plan->add_table (HB_OT_TAG_os2, os2_prime_blob); hb_blob_destroy (os2_prime_blob); return result; } inline void _update_unicode_ranges (const hb_set_t *codepoints, HBUINT32 ulUnicodeRange[4]) const { for (unsigned int i = 0; i < 4; i++) ulUnicodeRange[i].set (0); hb_codepoint_t cp = HB_SET_VALUE_INVALID; while (codepoints->next (&cp)) { unsigned int bit = hb_get_unicode_range_bit (cp); if (bit < 128) { unsigned int block = bit / 32; unsigned int bit_in_block = bit % 32; unsigned int mask = 1 << bit_in_block; ulUnicodeRange[block].set (ulUnicodeRange[block] | mask); } if (cp >= 0x10000 && cp <= 0x110000) { /* the spec says that bit 57 ("Non Plane 0") implies that there's at least one codepoint beyond the BMP; so I also include all the non-BMP codepoints here */ ulUnicodeRange[1].set (ulUnicodeRange[1] | (1 << 25)); } } } static inline void find_min_and_max_codepoint (const hb_set_t *codepoints, uint16_t *min_cp, /* OUT */ uint16_t *max_cp /* OUT */) { *min_cp = codepoints->get_min (); *max_cp = codepoints->get_max (); } enum font_page_t { HEBREW_FONT_PAGE = 0xB100, // Hebrew Windows 3.1 font page SIMP_ARABIC_FONT_PAGE = 0xB200, // Simplified Arabic Windows 3.1 font page TRAD_ARABIC_FONT_PAGE = 0xB300, // Traditional Arabic Windows 3.1 font page OEM_ARABIC_FONT_PAGE = 0xB400, // OEM Arabic Windows 3.1 font page SIMP_FARSI_FONT_PAGE = 0xBA00, // Simplified Farsi Windows 3.1 font page TRAD_FARSI_FONT_PAGE = 0xBB00, // Traditional Farsi Windows 3.1 font page THAI_FONT_PAGE = 0xDE00 // Thai Windows 3.1 font page }; // https://github.com/Microsoft/Font-Validator/blob/520aaae/OTFontFileVal/val_OS2.cs#L644-L681 inline font_page_t get_font_page () const { if (version != 0) return (font_page_t) 0; return (font_page_t) (fsSelection & 0xFF00); } public: HBUINT16 version; /* Version 0 */ HBINT16 xAvgCharWidth; HBUINT16 usWeightClass; HBUINT16 usWidthClass; HBUINT16 fsType; HBINT16 ySubscriptXSize; HBINT16 ySubscriptYSize; HBINT16 ySubscriptXOffset; HBINT16 ySubscriptYOffset; HBINT16 ySuperscriptXSize; HBINT16 ySuperscriptYSize; HBINT16 ySuperscriptXOffset; HBINT16 ySuperscriptYOffset; HBINT16 yStrikeoutSize; HBINT16 yStrikeoutPosition; HBINT16 sFamilyClass; HBUINT8 panose[10]; HBUINT32 ulUnicodeRange[4]; Tag achVendID; HBUINT16 fsSelection; HBUINT16 usFirstCharIndex; HBUINT16 usLastCharIndex; HBINT16 sTypoAscender; HBINT16 sTypoDescender; HBINT16 sTypoLineGap; HBUINT16 usWinAscent; HBUINT16 usWinDescent; /* Version 1 */ //HBUINT32 ulCodePageRange1; //HBUINT32 ulCodePageRange2; /* Version 2 */ //HBINT16 sxHeight; //HBINT16 sCapHeight; //HBUINT16 usDefaultChar; //HBUINT16 usBreakChar; //HBUINT16 usMaxContext; /* Version 5 */ //HBUINT16 usLowerOpticalPointSize; //HBUINT16 usUpperOpticalPointSize; public: DEFINE_SIZE_STATIC (78); }; } /* namespace OT */ #endif /* HB_OT_OS2_TABLE_HH */
32.568306
116
0.666611
iootclab
f7ac1e5c5a31bd4a849b3f88bd138a9e3dcc5a8b
2,065
cpp
C++
Camera.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
Camera.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
Camera.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
#include "Camera.h" #include "Graphics.h" #include "Mouse.h" #include "Keyboard.h" #include "Math.h" Camera::Camera(CoordinateTransformer& transformer) : transformer(transformer) { } Camera::Camera(CoordinateTransformer& transformer, float initScale, float fScaleRate) : scale(initScale), fScaleRate(fScaleRate), transformer(transformer) { } Vec2 Camera::GetPos() const { return pos; } float Camera::GetScale() const { return scale; } Rectf Camera::GetRect() const { const float zoom = 1.0f / scale; //This commented area would be the way to get the rect of the camera, but it requires a proper arbitrary rotation Rect implementation which is hard asf; put that shit off until later. //auto rect = Rectf({0.0f, 0.0f}, Graphics::ScreenWidth * zoom, Graphics::ScreenHeight * zoom).Rotate(rotation); //rect.Translate(pos); auto rect = Rectf(pos, Graphics::ScreenWidth * zoom, Graphics::ScreenHeight * zoom); return rect; } void Camera::SetPos(const Vec2& pos) { this->pos = pos; } void Camera::SetScale(float scale) { this->scale = scale; } void Camera::Translate(const Vec2& offset) { pos += offset; } void Camera::Update(const float fElapsedTime, const Mouse& mouse, const Keyboard& keyboard) { if (mouse.LeftDownEvent()) { lastMousePos = mouse.GetPos(); lastMousePos.y = -lastMousePos.y; } if (mouse.LeftIsPressed()) { Vec2 currMousePos = mouse.GetPos(); currMousePos.y = -currMousePos.y; Translate((lastMousePos - currMousePos) / GetScale()); lastMousePos = currMousePos; } if (mouse.WheelUp() || keyboard.KeyIsPressed(Key::UP)) SetScale(GetScale() + fScaleRate * fElapsedTime); if (mouse.WheelDown() || keyboard.KeyIsPressed(Key::DOWN)) SetScale(std::max(0.01f, GetScale() - fScaleRate * fElapsedTime)); } void Camera::Draw(Drawable& draw) const { draw.Transform( Mat3::Scale(scale) * Mat3::Translate((Vec3)-pos) ); transformer.Draw(draw); }
24.011628
187
0.658596
KarmaiSAYIn
f7ae0c8fd7880c2d6ad29f9153352aa439f2413f
5,073
cpp
C++
comms/Cluster.cpp
dehilsterlexis/eclide-1
0c1685cc7165191b5033d450c59aec479f01010a
[ "Apache-2.0" ]
8
2016-08-29T13:34:18.000Z
2020-12-04T15:20:36.000Z
comms/Cluster.cpp
dehilsterlexis/eclide-1
0c1685cc7165191b5033d450c59aec479f01010a
[ "Apache-2.0" ]
221
2016-06-20T19:51:48.000Z
2022-03-29T20:46:46.000Z
comms/Cluster.cpp
dehilsterlexis/eclide-1
0c1685cc7165191b5033d450c59aec479f01010a
[ "Apache-2.0" ]
13
2016-06-24T15:59:31.000Z
2022-01-01T11:48:20.000Z
#include "StdAfx.h" #include "cluster.h" #include "dali.h" #include "SoapUtil.h" #include "clib.h" #include "cache.h" #include "logger.h" #if _COMMS_VER < 68200 using namespace WsTopology; #elif _COMMS_VER < 700000 #else using namespace WsEnvironment; #endif namespace Topology { class CCluster : public ICluster, public CUnknown { protected: std::_tstring m_Name; std::_tstring m_Queue; std::_tstring m_Url; std::_tstring m_TypeStr; CLUSTERTYPE m_Type; std::_tstring m_Directory; std::_tstring m_Desc; std::_tstring m_Prefix; std::_tstring m_Path; std::_tstring m_DataModel; public: IMPLEMENT_CUNKNOWN; CCluster(const std::_tstring & url, const std::_tstring & name, const std::_tstring & queue = _T("")) : m_Url(url), m_Name(name), m_Queue(queue), m_Type(CLUSTERTYPE_UNKNOWN) { } virtual ~CCluster() { } const TCHAR *GetID() const { return m_Name.c_str(); } const TCHAR * GetCacheID() const { return m_Name.c_str(); } const TCHAR *GetName() const { return m_Name.c_str(); } const TCHAR *GetQueue() const { return m_Queue.c_str(); } CLUSTERTYPE GetType() const { return m_Type; } const TCHAR *GetTypeStr() const { return m_TypeStr.c_str(); } const TCHAR *GetDirectory() const { return m_Directory.c_str(); } const TCHAR *GetDesc() const { return m_Desc.c_str(); } const TCHAR *GetPrefix() const { return m_Prefix.c_str(); } const TCHAR *GetPath() const { return m_Path.c_str(); } const TCHAR *GetDataModel() const { return m_DataModel.c_str(); } #if _COMMS_VER < 68200 void Update(const TpLogicalCluster * c) { m_Name = CW2T(c->Name, CP_UTF8); #if _COMMS_VER < 55100 #else if(c->Queue) { m_Queue = CW2T(c->Queue, CP_UTF8); } #endif Refresh(); } void Update(const TpCluster * c) { m_Name = CW2T(c->Name, CP_UTF8); m_Type = CW2T(c->Type, CP_UTF8); m_Directory = CW2T(c->Directory, CP_UTF8); m_Desc = CW2T(c->Desc, CP_UTF8); m_Prefix = CW2T(c->Prefix, CP_UTF8); m_Path = CW2T(c->Path, CP_UTF8); m_DataModel = CW2T(c->DataModel, CP_UTF8); Refresh(); } #elif _COMMS_VER < 604000 void Update(const ns5__TpLogicalCluster * c) { SAFE_ASSIGN(m_Name, c->Name); SAFE_ASSIGN(m_Queue, c->Queue); Refresh(); } #elif _COMMS_VER < 700000 void Update(const ns5__TpLogicalCluster * c) { SAFE_ASSIGN(m_Name, c->Name); SAFE_ASSIGN(m_Queue, c->Queue); SAFE_ASSIGN(m_TypeStr, c->Type); if (boost::algorithm::iequals(m_TypeStr, _T("hthor"))) { m_Type = CLUSTERTYPE_HTHOR; } else if (boost::algorithm::iequals(m_TypeStr, _T("thor"))) { m_Type = CLUSTERTYPE_THOR; } else if (boost::algorithm::iequals(m_TypeStr, _T("roxie"))) { m_Type = CLUSTERTYPE_ROXIE; } else { m_Type = CLUSTERTYPE_UNKNOWN; } Refresh(); } #else void Update(const LogicalCluster * c) { m_Name = CW2T(c->Name, CP_UTF8); if(c->Queue) { m_Queue = CW2T(c->Queue, CP_UTF8); } Refresh(); } #endif void Refresh() { } }; CacheT<std::_tstring, CCluster> ClusterCache; void ClearClusterCache() { ClusterCache.Clear(); } CCluster * CreateClusterRaw(const CString & url, const CString & name, const std::_tstring & queue = _T("")) { return ClusterCache.Get(new CCluster(static_cast<const TCHAR *>(url), static_cast<const TCHAR *>(name), queue)); } #if _COMMS_VER < 68200 ICluster * CreateCluster(const CString & url, const TpLogicalCluster * data) { CCluster * attr = CreateClusterRaw(url, data->Name); ATLASSERT(attr); attr->Update(data); return attr; } ICluster * CreateCluster(const CString & url, const TpCluster * data) { ATLASSERT(!"This is not used any more - please tell Gordon"); //CCluster * attr = CreateClusterRaw(url, data->Name); //ATLASSERT(attr); //attr->Update(data); return NULL;//attr; } #elif _COMMS_VER < 700000 ICluster * CreateCluster(const CString & url, const ns5__TpLogicalCluster * data) { CCluster * attr = CreateClusterRaw(url, data->Name->c_str()); ATLASSERT(attr); attr->Update(data); return attr; } #else ICluster * CreateCluster(const CString & url, const LogicalCluster * data) { CCluster * attr = CreateClusterRaw(url, data->Name); ATLASSERT(attr); attr->Update(data); return attr; } ICluster * CreateCluster(const CString & url, const Cluster * data) { ATLASSERT(!"This is not used any more - please tell Gordon"); //CCluster * attr = CreateClusterRaw(url, data->Name); //ATLASSERT(attr); //attr->Update(data); return NULL;//attr; } #endif void ClearClusterSingletons() { ClusterCache.clear(); } }
23.705607
177
0.609698
dehilsterlexis
f7aff1b047ae5b6528120ba97234e36b3b80cd50
1,073
cpp
C++
leetcode/25-reverse-nodes-in-k-group.cpp
01nomagic/Algorithms
b184aa12141f5127baa55502d3ea47ccd1f97ba8
[ "MIT" ]
2
2021-03-27T03:23:20.000Z
2021-08-11T12:54:17.000Z
leetcode/25-reverse-nodes-in-k-group.cpp
01nomagic/Algorithms
b184aa12141f5127baa55502d3ea47ccd1f97ba8
[ "MIT" ]
null
null
null
leetcode/25-reverse-nodes-in-k-group.cpp
01nomagic/Algorithms
b184aa12141f5127baa55502d3ea47ccd1f97ba8
[ "MIT" ]
null
null
null
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { if (k <= 1) { return head; } int count = 0; ListNode* prev = nullptr; ListNode* curr = head; ListNode* start = nullptr; ListNode* end = nullptr; while (curr != nullptr) { count += 1; if (count == 1) { start = curr; } if (count == k) { end = curr; curr = curr->next; ListNode* next = end->next; ListNode* curr1 = start; // 反转 while (true) { ListNode* temp = curr1->next; curr1->next = next; if (curr1 == end) { break; } next = curr1; curr1 = temp; } if (prev == nullptr) { head = end; prev = start; } else { prev->next = end; prev = start; } count = 0; } else { curr = curr->next; } } return head; } };
20.634615
50
0.444548
01nomagic
f7b191c0ef7adf603aa7fcb49abf09598e10906f
1,407
hpp
C++
libs/ledger/include/ledger/chaincode/factory.hpp
cyenyxe/ledger
6b42c3a3a5c78d257a02634437f9e00d1439690b
[ "Apache-2.0" ]
null
null
null
libs/ledger/include/ledger/chaincode/factory.hpp
cyenyxe/ledger
6b42c3a3a5c78d257a02634437f9e00d1439690b
[ "Apache-2.0" ]
null
null
null
libs/ledger/include/ledger/chaincode/factory.hpp
cyenyxe/ledger
6b42c3a3a5c78d257a02634437f9e00d1439690b
[ "Apache-2.0" ]
null
null
null
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "core/byte_array/const_byte_array.hpp" #include <functional> #include <memory> #include <unordered_set> namespace fetch { namespace ledger { class Identifier; class Contract; class StorageInterface; class ChainCodeFactory { public: using ConstByteArray = byte_array::ConstByteArray; using ContractPtr = std::shared_ptr<Contract>; using ContractNameSet = std::unordered_set<ConstByteArray>; ContractPtr Create(Identifier const &contract_id, StorageInterface &storage) const; ContractNameSet const &GetChainCodeContracts() const; }; } // namespace ledger } // namespace fetch
29.93617
85
0.659559
cyenyxe
fc8d9cbb7ef7e5c5575973d96eb88c5f25affa9e
57,385
cpp
C++
src/Pegasus/ControlProviders/CertificateProvider/CertificateProvider.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/ControlProviders/CertificateProvider/CertificateProvider.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/ControlProviders/CertificateProvider/CertificateProvider.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
1
2022-03-07T22:54:02.000Z
2022-03-07T22:54:02.000Z
//%2005//////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development // Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems. // Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation, The Open Group. // Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group. // Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.; // EMC Corporation; VERITAS Software Corporation; The Open Group. // // 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. // //============================================================================== // // Author: Heather Sterling (hsterl@us.ibm.com), PEP187 // // Modified By: // Nag Boranna, Hewlett-Packard Company (nagaraja_boranna@hp.com) // //%//////////////////////////////////////////////////////////////////////////// #include "CertificateProvider.h" #define OPENSSL_NO_KRB5 1 #include <openssl/err.h> #include <openssl/ssl.h> #include <openssl/rand.h> #include <Pegasus/Common/Config.h> #include <Pegasus/Common/PegasusVersion.h> #include <cctype> #include <iostream> #include <Pegasus/Common/Constants.h> #include <Pegasus/Common/OperationContext.h> #include <Pegasus/Common/Logger.h> #include <Pegasus/Common/Tracer.h> #include <Pegasus/Common/System.h> #include <Pegasus/Common/FileSystem.h> #include <Pegasus/Common/XmlReader.h> #include <Pegasus/Common/XmlWriter.h> #include <Pegasus/Common/XmlParser.h> #ifdef PEGASUS_OS_OS400 #include <qycmutilu2.H> #include "OS400ConvertChar.h" #endif #include <stdlib.h> PEGASUS_USING_STD; PEGASUS_NAMESPACE_BEGIN //PG_SSLCertificate property names static const CIMName ISSUER_NAME_PROPERTY = "IssuerName"; static const CIMName SERIAL_NUMBER_PROPERTY = "SerialNumber"; static const CIMName SUBJECT_NAME_PROPERTY = "SubjectName"; static const CIMName USER_NAME_PROPERTY = "RegisteredUserName"; static const CIMName TRUSTSTORE_TYPE_PROPERTY = "TruststoreType"; static const CIMName FILE_NAME_PROPERTY = "TruststorePath"; static const CIMName NOT_BEFORE_PROPERTY = "NotBefore"; static const CIMName NOT_AFTER_PROPERTY = "NotAfter"; //PG_SSLCertificateRevocationList property names //also has IssuerName static const CIMName LAST_UPDATE_PROPERTY = "LastUpdate"; static const CIMName NEXT_UPDATE_PROPERTY = "NextUpdate"; static const CIMName REVOKED_SERIAL_NUMBERS_PROPERTY = "RevokedSerialNumbers"; static const CIMName REVOCATION_DATES_PROPERTY = "RevocationDates"; //method names for PG_SSLCertificate static const CIMName METHOD_ADD_CERTIFICATE = "addCertificate"; static const CIMName PARAMETER_CERT_CONTENTS = "certificateContents"; static const CIMName PARAMETER_USERNAME = "userName"; static const CIMName PARAMETER_TRUSTSTORE_TYPE = "truststoreType"; //method names for PG_SSLCertificateRevocationList static const CIMName METHOD_ADD_CRL = "addCertificateRevocationList"; static const CIMName PARAMETER_CRL_CONTENTS = "CRLContents"; //truststore and crlstore directory mutexes static Mutex _trustStoreMutex; static Mutex _crlStoreMutex; typedef struct Timestamp { char year[4]; char month[2]; char day[2]; char hour[2]; char minutes[2]; char seconds[2]; char dot; char microSeconds[6]; char plusOrMinus; char utcOffset[3]; char padding[3]; } Timestamp_t; /** Convert ASN1_UTCTIME to CIMDateTime */ inline CIMDateTime getDateTime(const ASN1_UTCTIME *utcTime) { struct tm time; int offset; Timestamp_t timeStamp; char tempString[80]; char plusOrMinus = '+'; unsigned char* utcTimeData = utcTime->data; memset(&time, '\0', sizeof(time)); #define g2(p) ( ( (p)[0] - '0' ) * 10 + (p)[1] - '0' ) if (utcTime->type == V_ASN1_GENERALIZEDTIME) { time.tm_year = g2(utcTimeData) * 100; utcTimeData += 2; // Remaining data is equivalent to ASN1_UTCTIME type time.tm_year += g2(utcTimeData); } else { time.tm_year = g2(utcTimeData); if (time.tm_year < 50) { time.tm_year += 2000; } else { time.tm_year += 1900; } } time.tm_mon = g2(utcTimeData + 2) - 1; time.tm_mday = g2(utcTimeData + 4); time.tm_hour = g2(utcTimeData + 6); time.tm_min = g2(utcTimeData + 8); time.tm_sec = g2(utcTimeData + 10); if (utcTimeData[12] == 'Z') { offset = 0; } else { offset = g2(utcTimeData + 13) * 60 + g2(utcTimeData + 15); if (utcTimeData[12] == '-') { plusOrMinus = '-'; } } #undef g2 memset((void *)&timeStamp, 0, sizeof(Timestamp_t)); // Format the date. sprintf((char *) &timeStamp,"%04d%02d%02d%02d%02d%02d.%06d%04d", time.tm_year, time.tm_mon + 1, time.tm_mday, time.tm_hour, time.tm_min, time.tm_sec, 0, offset); timeStamp.plusOrMinus = plusOrMinus; CIMDateTime dateTime; dateTime.clear(); strcpy(tempString, (char *)&timeStamp); dateTime.set(tempString); return (dateTime); } /** * The issuer name should be in the format /type0=value0/type1=value1/type2=... * where characters may be escaped by \ */ inline X509_NAME *getIssuerName(char *issuer, long chtype) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::getIssuerName"); //allocate buffers for type-value pairs size_t buflen = strlen(issuer)+1; char *buf = (char*) malloc(buflen); size_t maxPairs = buflen / 2 + 1; char **types = (char**) malloc(maxPairs * sizeof (char *)); //types char **values = (char**) malloc(maxPairs * sizeof (char *)); //values if (!buf || !types || !values) { return NULL; } char *sp = issuer, *bp = buf; int count = 0; while (*sp) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "CertificateProvider::getIssuerName WHILE"); if (*sp != '/') { break; } sp++; types[count] = bp; while (*sp) { if (*sp == '\\') { if (*++sp) { *bp++ = *sp++; } } else if (*sp == '=') { sp++; *bp++ = '\0'; break; } else { *bp++ = *sp++; } } values[count] = bp; while (*sp) { if (*sp == '\\') { if (*++sp) { *bp++ = *sp++; } } else if (*sp == '/') { break; } else { *bp++ = *sp++; } } *bp++ = '\0'; count++; } PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "CertificateProvider::getIssuerName WHILE EXIT"); //create the issuername object and add each type/value pair X509_NAME* issuerNameNew = X509_NAME_new(); int nid; for (int i = 0; i < count; i++) { nid = OBJ_txt2nid(types[i]); //if we don't recognize the name element or there is no corresponding value, continue to the next one if (nid == NID_undef || !*values[i]) { continue; } if (!X509_NAME_add_entry_by_NID(issuerNameNew, nid, chtype, (unsigned char*)values[i], -1, -1, 0)) { X509_NAME_free(issuerNameNew); issuerNameNew = NULL; break; } } free(types); free(values); free(buf); PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "Got issuerName successfully"); PEG_METHOD_EXIT(); return issuerNameNew; } /** Determines whether the user has sufficient access to perform a certificate operation. */ Boolean CertificateProvider::_verifyAuthorization(const String& userName) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::_verifyAuthorization"); if (_enableAuthentication) { #if !defined(PEGASUS_OS_OS400) if (!System::isPrivilegedUser(userName)) #else CString user = userName.getCString(); const char * tmp = (const char *)user; AtoE((char *)tmp); if (!ycmCheckUserSecurityAuthorities(tmp)) #endif { PEG_METHOD_EXIT(); return false; } } PEG_METHOD_EXIT(); return true; } /** Constructor */ CertificateProvider::CertificateProvider(CIMRepository* repository, SSLContextManager* sslContextMgr) : _cimom(0), _repository(repository), _sslContextMgr(sslContextMgr), _enableAuthentication(false) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::CertificateProvider"); ConfigManager* configManager = ConfigManager::getInstance(); //get config properties if (String::equalNoCase(configManager->getCurrentValue("enableAuthentication"), "true")) { _enableAuthentication = true; } _sslTrustStore = ConfigManager::getHomedPath(configManager->getCurrentValue("sslTrustStore")); _exportSSLTrustStore = ConfigManager::getHomedPath(configManager->getCurrentValue("exportSSLTrustStore")); _crlStore = ConfigManager::getHomedPath(configManager->getCurrentValue("crlStore")); PEG_METHOD_EXIT(); } /** Destructor */ CertificateProvider::~CertificateProvider(void) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::~CertificateProvider"); PEG_METHOD_EXIT(); } /** Called when a provider is loaded */ void CertificateProvider::initialize(CIMOMHandle & cimom) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::initialize"); // save the cimom handle in case it is needed to service and operation. _cimom = &cimom; PEG_METHOD_EXIT(); } /** Called before a provider is unloaded */ void CertificateProvider::terminate(void) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::terminate"); // delete self. this is necessary because the entry point for this object allocated it, and // the module is responsible for its memory management. delete this; PEG_METHOD_EXIT(); } /** Delivers a single instance to the CIMOM */ void CertificateProvider::getInstance( const OperationContext & context, const CIMObjectPath & cimObjectPath, const Boolean includeQualifiers, const Boolean includeClassOrigin, const CIMPropertyList & propertyList, InstanceResponseHandler & handler) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::getInstance"); //verify authorization const IdentityContainer container = context.get(IdentityContainer::NAME); if (!_verifyAuthorization(container.getUserName())) { MessageLoaderParms parms("ControlProviders.CertificateProvider.MUST_BE_PRIVILEGED_USER", "Superuser authority is required to run this CIM operation."); throw CIMException(CIM_ERR_ACCESS_DENIED, parms); } CIMName className(cimObjectPath.getClassName()); //verify classname if (className == PEGASUS_CLASSNAME_CERTIFICATE) { // process request handler.processing(); //verify the keys are set //ATTN: do we need to do this, or will the getInstance call handle it? Array<CIMKeyBinding> keyBindings = cimObjectPath.getKeyBindings(); String keyName; for (Uint32 i=0; i < keyBindings.size(); i++) { keyName = keyBindings[i].getName().getString(); if (!String::equal(keyName, ISSUER_NAME_PROPERTY.getString()) && !String::equal(keyName, SERIAL_NUMBER_PROPERTY.getString())) { throw CIMException(CIM_ERR_INVALID_PARAMETER, keyName); } } CIMInstance cimInstance = _repository->getInstance(cimObjectPath.getNameSpace(), cimObjectPath); PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "Returning certificate COP " + cimInstance.getPath().toString()); // deliver instance handler.deliver(cimInstance); // complete request handler.complete(); } else if (className == PEGASUS_CLASSNAME_CRL) { //ATTN: Fill in } else { throw CIMException(CIM_ERR_INVALID_CLASS, className.getString()); } PEG_METHOD_EXIT(); } /** Builds and returns a PG_SSLCertificateRevocationList from an X509_CRL object */ inline CIMInstance _getCRLInstance(X509_CRL* xCrl, String host, CIMNamespaceName nameSpace) { char issuerName[1024]; STACK_OF(X509_REVOKED) *revoked = NULL; X509_REVOKED *r = NULL; int numRevoked = -1; long rawSerialNumber; char serial[1024]; CIMDateTime revocationDate; PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::_getCRLInstance"); // build instance CIMInstance cimInstance(PEGASUS_CLASSNAME_CRL); // CA issuer name sprintf(issuerName, "%s", X509_NAME_oneline(X509_CRL_get_issuer(xCrl), NULL, 0)); cimInstance.addProperty(CIMProperty(ISSUER_NAME_PROPERTY, CIMValue(String(issuerName)))); // validity dates CIMDateTime lastUpdate = getDateTime(X509_CRL_get_lastUpdate(xCrl)); cimInstance.addProperty(CIMProperty(NEXT_UPDATE_PROPERTY, CIMValue(lastUpdate))); CIMDateTime nextUpdate = getDateTime(X509_CRL_get_nextUpdate(xCrl)); cimInstance.addProperty(CIMProperty(LAST_UPDATE_PROPERTY, CIMValue(nextUpdate))); Array<String> revokedSerialNumbers; Array<CIMDateTime> revocationDates; // get revoked certificate information revoked = X509_CRL_get_REVOKED(xCrl); numRevoked = sk_X509_REVOKED_num(revoked); for (int i = 0; i < numRevoked; i++) { r = sk_X509_REVOKED_value(revoked, i); rawSerialNumber = ASN1_INTEGER_get(r->serialNumber); sprintf(serial, "%lu", rawSerialNumber); revokedSerialNumbers.append(String(serial)); revocationDate = getDateTime(r->revocationDate); revocationDates.append(revocationDate); } cimInstance.addProperty(CIMProperty(REVOKED_SERIAL_NUMBERS_PROPERTY, CIMValue(revokedSerialNumbers))); cimInstance.addProperty(CIMProperty(REVOCATION_DATES_PROPERTY, CIMValue(revocationDates))); // set keys Array<CIMKeyBinding> keys; CIMKeyBinding key; key.setName(ISSUER_NAME_PROPERTY.getString()); key.setValue(issuerName); key.setType(CIMKeyBinding::STRING); keys.append(key); // set object path for instance cimInstance.setPath(CIMObjectPath(host, nameSpace, PEGASUS_CLASSNAME_CRL, keys)); PEG_METHOD_EXIT(); return (cimInstance); } /** Delivers the complete collection of instances to the CIMOM */ void CertificateProvider::enumerateInstances( const OperationContext & context, const CIMObjectPath & cimObjectPath, const Boolean includeQualifiers, const Boolean includeClassOrigin, const CIMPropertyList & propertyList, InstanceResponseHandler & handler) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::enumerateInstances"); //verify authorization const IdentityContainer container = context.get(IdentityContainer::NAME); if (!_verifyAuthorization(container.getUserName())) { MessageLoaderParms parms("ControlProviders.CertificateProvider.MUST_BE_PRIVILEGED_USER", "Superuser authority is required to run this CIM operation."); throw CIMException(CIM_ERR_ACCESS_DENIED, parms); } CIMName className(cimObjectPath.getClassName()); //verify classname if (className == PEGASUS_CLASSNAME_CERTIFICATE) { // process request handler.processing(); // get instances from the repository Array<CIMInstance> cimInstances; cimInstances = _repository->enumerateInstances(cimObjectPath.getNameSpace(), PEGASUS_CLASSNAME_CERTIFICATE); for (Uint32 i = 0, n = cimInstances.size(); i < n; i++) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "Delivering CIMInstance " + cimInstances[i].getPath().toString()); // deliver each instance handler.deliver(cimInstances[i]); } // complete request handler.complete(); } else if (className == PEGASUS_CLASSNAME_CRL) { // process request handler.processing(); FileSystem::translateSlashes(_crlStore); if (FileSystem::isDirectory(_crlStore) && FileSystem::canWrite(_crlStore)) { Array<String> crlFiles; if (FileSystem::getDirectoryContents(_crlStore, crlFiles)) { Uint32 count = crlFiles.size(); for (Uint32 i = 0; i < count; i++) { String filename = crlFiles[i]; PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "Filename " + filename); //ATTN: Is this a two-way hash? If so, I don't need to read in the CRL just to determine the issuer name BIO* inFile = BIO_new(BIO_s_file()); X509_CRL* xCrl = NULL; char fullPathName[1024]; sprintf(fullPathName, "%s/%s", (const char*)_crlStore.getCString(), (const char*)filename.getCString()); if (BIO_read_filename(inFile, fullPathName)) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "Successfully read filename"); if (PEM_read_bio_X509_CRL(inFile, &xCrl, NULL, NULL)) { // build instance CIMInstance cimInstance = _getCRLInstance(xCrl, cimObjectPath.getHost(), cimObjectPath.getNameSpace()); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4, "Delivering CIMInstance: " + cimInstance.getPath().toString()); // deliver instance handler.deliver(cimInstance); } } else { //error PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Error reading CRL file"); } BIO_free_all(inFile); } //end for // complete request handler.complete(); } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Error: Could not read sslCRLStore directory."); MessageLoaderParms parms("ControlProviders.CertificateProvider.COULD_NOT_READ_DIRECTORY", "Cannot read directory $0.", _crlStore); throw CIMException(CIM_ERR_FAILED, parms); } } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Error: sslCRLStore is not a valid directory."); MessageLoaderParms parms("ControlProviders.CertificateProvider.INVALID_DIRECTORY", "Invalid directory $0.", _crlStore); throw CIMException(CIM_ERR_FAILED, parms); } } else { throw CIMException(CIM_ERR_INVALID_CLASS, className.getString()); } PEG_METHOD_EXIT(); } /** Delivers the complete collection of instance names (CIMObjectPaths) to the CIMOM */ void CertificateProvider::enumerateInstanceNames( const OperationContext & context, const CIMObjectPath & cimObjectPath, ObjectPathResponseHandler & handler) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::enumerateInstanceNames"); //verify authorization const IdentityContainer container = context.get(IdentityContainer::NAME); if (!_verifyAuthorization(container.getUserName())) { MessageLoaderParms parms("ControlProviders.CertificateProvider.MUST_BE_PRIVILEGED_USER", "Superuser authority is required to run this CIM operation."); throw CIMException(CIM_ERR_ACCESS_DENIED, parms); } CIMName className(cimObjectPath.getClassName()); //verify classname if (className == PEGASUS_CLASSNAME_CERTIFICATE) { // process request handler.processing(); Array<CIMObjectPath> instanceNames = _repository->enumerateInstanceNames(cimObjectPath.getNameSpace(), PEGASUS_CLASSNAME_CERTIFICATE); for (Uint32 i = 0, n = instanceNames.size(); i < n; i++) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "Delivering CIMObjectPath: " + instanceNames[i].toString()); // deliver object path handler.deliver(instanceNames[i]); } // complete request handler.complete(); } else if (className == PEGASUS_CLASSNAME_CRL) { // process request handler.processing(); FileSystem::translateSlashes(_crlStore); if (FileSystem::isDirectory(_crlStore) && FileSystem::canWrite(_crlStore)) { Array<String> crlFiles; if (FileSystem::getDirectoryContents(_crlStore, crlFiles)) { Uint32 count = crlFiles.size(); for (Uint32 i = 0; i < count; i++) { String filename = crlFiles[i]; PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Filename " + filename); CIMObjectPath cimObjectPath; //ATTN: Is this a two-way hash? If so, I don't need to read in the CRL just to determine the issuer name BIO* inFile = BIO_new(BIO_s_file()); X509_CRL* xCrl = NULL; char issuerName[1024]; char fullPathName[1024]; sprintf(fullPathName, "%s/%s", (const char*)_crlStore.getCString(), (const char*)filename.getCString()); if (BIO_read_filename(inFile, fullPathName)) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Successfully read filename"); if (PEM_read_bio_X509_CRL(inFile, &xCrl, NULL, NULL)) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Successfully read CRL file"); sprintf(issuerName, "%s", X509_NAME_oneline(X509_CRL_get_issuer(xCrl), NULL, 0)); // build object path Array<CIMKeyBinding> keys; CIMKeyBinding key; key.setName(ISSUER_NAME_PROPERTY.getString()); key.setValue(issuerName); key.setType(CIMKeyBinding::STRING); keys.append(key); // set object path for instance CIMObjectPath instanceName(cimObjectPath.getHost(), cimObjectPath.getNameSpace(), PEGASUS_CLASSNAME_CRL, keys); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4, "Instance Name: " + instanceName.toString()); handler.deliver(instanceName); } } else { //error PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Error reading CRL file"); } BIO_free_all(inFile); } //end for // complete request handler.complete(); } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Error: Could not read sslCRLStore directory."); MessageLoaderParms parms("ControlProviders.CertificateProvider.COULD_NOT_READ_DIRECTORY", "Cannot read directory $0.", _crlStore); throw CIMException(CIM_ERR_FAILED, parms); } } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Error: sslCRLStore is not a valid directory."); MessageLoaderParms parms("ControlProviders.CertificateProvider.INVALID_DIRECTORY", "Invalid directory $0.", _crlStore); throw CIMException(CIM_ERR_FAILED, parms); } } else { throw CIMException(CIM_ERR_INVALID_CLASS, className.getString()); } PEG_METHOD_EXIT(); } /** Not supported. Use invokeMethod to create a certificate or CRL */ void CertificateProvider::createInstance( const OperationContext & context, const CIMObjectPath & cimObjectPath, const CIMInstance & cimInstance, ObjectPathResponseHandler & handler) { throw CIMException(CIM_ERR_NOT_SUPPORTED, "CertificateProvider::createInstance"); } /** Not supported. */ void CertificateProvider::modifyInstance( const OperationContext & context, const CIMObjectPath & cimObjectPath, const CIMInstance & cimInstance, const Boolean includeQualifiers, const CIMPropertyList & propertyList, ResponseHandler & handler) { throw CIMException(CIM_ERR_NOT_SUPPORTED, "CertificateProvider::modifyInstance"); } /** Deletes the internal object denoted by the specified CIMObjectPath */ void CertificateProvider::deleteInstance( const OperationContext & context, const CIMObjectPath & cimObjectPath, ResponseHandler & handler) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::deleteInstance"); //verify authorization const IdentityContainer container = context.get(IdentityContainer::NAME); if (!_verifyAuthorization(container.getUserName())) { MessageLoaderParms parms("ControlProviders.CertificateProvider.MUST_BE_PRIVILEGED_USER", "Superuser authority is required to run this CIM operation."); throw CIMException(CIM_ERR_ACCESS_DENIED, parms); } CIMName className(cimObjectPath.getClassName()); //verify classname if (className == PEGASUS_CLASSNAME_CERTIFICATE) { // process request handler.processing(); String certificateFileName = String::EMPTY; String issuerName = String::EMPTY; String userName = String::EMPTY; Uint16 truststoreType; CIMInstance cimInstance; try { cimInstance = _repository->getInstance(cimObjectPath.getNameSpace(), cimObjectPath); } catch (Exception& ex) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "The certificate does not exist."); MessageLoaderParms parms("ControlProviders.CertificateProvider.CERT_DNE", "The certificate does not exist."); throw CIMException(CIM_ERR_NOT_FOUND, parms); } CIMProperty cimProperty; //certificate file name cimProperty = cimInstance.getProperty(cimInstance.findProperty(FILE_NAME_PROPERTY)); cimProperty.getValue().get(certificateFileName); //issuer name cimProperty = cimInstance.getProperty(cimInstance.findProperty(ISSUER_NAME_PROPERTY)); cimProperty.getValue().get(issuerName); //user name cimProperty = cimInstance.getProperty(cimInstance.findProperty(USER_NAME_PROPERTY)); cimProperty.getValue().get(userName); cimProperty = cimInstance.getProperty(cimInstance.findProperty(TRUSTSTORE_TYPE_PROPERTY)); cimProperty.getValue().get(truststoreType); PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "Issuer name " + issuerName); PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "User name " + userName); PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "Truststore type: " + cimProperty.getValue().toString()); AutoMutex lock(_trustStoreMutex); if (FileSystem::exists(certificateFileName)) { if (FileSystem::removeFile(certificateFileName)) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Successfully deleted certificate file " + certificateFileName); // only delete from repository if we successfully deleted it from the truststore, otherwise it is still technically "trusted" _repository->deleteInstance(cimObjectPath.getNameSpace(), cimObjectPath); // // Request SSLContextManager to delete the certificate from the cache // try { switch (truststoreType) { case SERVER_TRUSTSTORE : _sslContextMgr->reloadTrustStore(SSLContextManager::SERVER_CONTEXT); break; case EXPORT_TRUSTSTORE : _sslContextMgr->reloadTrustStore(SSLContextManager::EXPORT_CONTEXT); break; default: break; } } catch (SSLException& ex) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Trust store reload failed, " + ex.getMessage()); MessageLoaderParms parms("ControlProviders.CertificateProvider.TRUSTSTORE_RELOAD_FAILED", "Trust store reload failed, certificate deletion will not be effective until cimserver restart."); throw CIMException(CIM_ERR_FAILED, parms); } Logger::put(Logger::STANDARD_LOG, System::CIMSERVER, Logger::TRACE, "The certificate registered to $0 from issuer $1 has been deleted from the truststore.", userName, issuerName); } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Could not delete file."); MessageLoaderParms parms("ControlProviders.CertificateProvider.DELETE_FAILED", "Could not delete file $0.", certificateFileName); throw CIMException(CIM_ERR_FAILED, parms); } } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "File does not exist."); MessageLoaderParms parms("ControlProviders.CertificateProvider.FILE_DNE", "File does not exist $0.", certificateFileName); throw CIMException(CIM_ERR_FAILED, parms); } // complete request handler.complete(); } else if (className == PEGASUS_CLASSNAME_CRL) { Array<CIMKeyBinding> keys; CIMKeyBinding key; String issuerName; keys = cimObjectPath.getKeyBindings(); if (keys.size() && String::equal(keys[0].getName().getString(), ISSUER_NAME_PROPERTY.getString())) { issuerName = keys[0].getValue(); } PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "CRL COP" + cimObjectPath.toString()); PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "Issuer Name " + issuerName); //ATTN: it would nice to be able to do this by getting the hash directly from the issuerName //unfortunately, there does not seem to be an easy way to achieve this //the closest I can get is to add the individual DN components using X509_NAME_add_entry_by_NID //which involves a lot of tedious parsing. //look in the do_subject method of apps.h for how this is done //X509_NAME* name = X509_name_new(); char issuerChar[1024]; sprintf(issuerChar, "%s", (const char*) issuerName.getCString()); X509_NAME* name = getIssuerName(issuerChar, MBSTRING_ASC); AutoMutex lock(_crlStoreMutex); String crlFileName = _getCRLFileName(_crlStore, X509_NAME_hash(name)); if (FileSystem::exists(crlFileName)) { if (FileSystem::removeFile(crlFileName)) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Successfully deleted CRL file " + crlFileName); // // reload the CRL store to refresh the cache // _sslContextMgr->reloadCRLStore(); Logger::put(Logger::STANDARD_LOG, System::CIMSERVER, Logger::TRACE, "The CRL from issuer $0 has been deleted.", issuerName); } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Could not delete file."); MessageLoaderParms parms("ControlProviders.CertificateProvider.DELETE_FAILED", "Could not delete file $0.", FileSystem::extractFileName(crlFileName)); throw CIMException(CIM_ERR_FAILED, parms); } } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "File does not exist."); MessageLoaderParms parms("ControlProviders.CertificateProvider.FILE_DNE", "File does not exist $0.", FileSystem::extractFileName(crlFileName)); throw CIMException(CIM_ERR_FAILED, parms); } X509_NAME_free(name); } else { throw CIMException(CIM_ERR_INVALID_CLASS, className.getString()); } PEG_METHOD_EXIT(); } /** Returns the CRL filename associated with the hashvalue that represents the issuer name. * There is only one CRL per issuer so the file name will always end in .r0 */ String CertificateProvider::_getCRLFileName(String crlStore, unsigned long hashVal) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::_getCRLFileName"); Uint32 index = 0; //The files are looked up by the CA issuer name hash value. //Since only one CRL should exist for a given CA, the extension .r0 is appended to the CA hash char hashBuffer[32]; sprintf(hashBuffer, "%lx", hashVal); String hashString = ""; for (int j = 0; j < 32; j++) { if (hashBuffer[j] != '\0') { hashString.append(hashBuffer[j]); } else { break; // end of hash string } } char filename[1024]; sprintf(filename, "%s/%s.r0", (const char*)crlStore.getCString(), (const char*)hashString.getCString()); PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "Searching for files like " + hashString + "in " + crlStore); FileSystem::translateSlashes(crlStore); if (FileSystem::isDirectory(crlStore) && FileSystem::canWrite(crlStore)) { if (FileSystem::exists(filename)) { //overwrite PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "CRL already exists, overwriting"); } else { //create PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "CRL does not exist, creating"); } } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Cannot add CRL to CRL store : CRL directory DNE or does not have write privileges"); MessageLoaderParms parms("ControlProviders.CertificateProvider.INVALID_DIRECTORY", "Invalid directory $0.", crlStore); throw CIMException(CIM_ERR_FAILED, parms); } PEG_METHOD_EXIT(); return (String(filename)); } /** Returns the new certificate filename for the hashvalue that represents the subject name. */ String CertificateProvider::_getNewCertificateFileName(String trustStore, unsigned long hashVal) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER, "CertificateProvider::_getNewCertificateFileName"); //The files are looked up by the CA subject name hash value. //If more than one CA certificate with the same name hash value exists, //the extension must be different (e.g. 9d66eef0.0, 9d66eef0.1 etc) char hashBuffer[32]; sprintf(hashBuffer, "%lx", hashVal); String hashString = ""; for (int j = 0; j < 32; j++) { if (hashBuffer[j] != '\0') { hashString.append(hashBuffer[j]); } else { break; // end of hash string } } PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL4, "Searching for files like " + hashString); Uint32 index = 0; FileSystem::translateSlashes(trustStore); if (FileSystem::isDirectory(trustStore) && FileSystem::canWrite(trustStore)) { Array<String> trustedCerts; if (FileSystem::getDirectoryContents(trustStore, trustedCerts)) { for (Uint32 i = 0; i < trustedCerts.size(); i++) { if (String::compare(trustedCerts[i], hashString, hashString.size()) == 0) { index++; } } } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Error: Could not read truststore directory."); MessageLoaderParms parms("ControlProviders.CertificateProvider.COULD_NOT_READ_DIRECTORY", "Cannot read directory $0.", trustStore); throw CIMException(CIM_ERR_FAILED, parms); } } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Error: sslCRLStore is not a valid directory."); MessageLoaderParms parms("ControlProviders.CertificateProvider.INVALID_DIRECTORY", "Invalid directory $0.", trustStore); throw CIMException(CIM_ERR_FAILED, parms); } char filename[1024]; sprintf(filename, "%s/%s.%d", (const char*)trustStore.getCString(), (const char*)hashString.getCString(), index); PEG_METHOD_EXIT(); return (String(filename)); } /** Calls an extrinsic method on the class. */ void CertificateProvider::invokeMethod( const OperationContext & context, const CIMObjectPath & cimObjectPath, const CIMName & methodName, const Array<CIMParamValue> & inParams, MethodResultResponseHandler & handler) { PEG_METHOD_ENTER(TRC_CONTROLPROVIDER,"CertificateProvider::invokeMethod"); //verify authorization const IdentityContainer container = context.get(IdentityContainer::NAME); if (!_verifyAuthorization(container.getUserName())) { MessageLoaderParms parms("ControlProviders.CertificateProvider.MUST_BE_PRIVILEGED_USER", "Superuser authority is required to run this CIM operation."); throw CIMException(CIM_ERR_ACCESS_DENIED, parms); } CIMName className(cimObjectPath.getClassName()); //verify classname if (className == PEGASUS_CLASSNAME_CERTIFICATE) { // process request handler.processing(); if (methodName == METHOD_ADD_CERTIFICATE) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4, "CertificateProvider::addCertificate()"); String certificateContents = String::EMPTY; String userName = String::EMPTY; Uint16 truststoreType; CIMValue cimValue; cimValue = inParams[0].getValue(); cimValue.get(certificateContents); cimValue = inParams[1].getValue(); cimValue.get(userName); cimValue = inParams[2].getValue(); cimValue.get(truststoreType); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"Certificate parameters:\n"); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"\tcertificateContents:" + certificateContents); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"\tuserName:" + userName); //check for a valid truststore if (truststoreType != SERVER_TRUSTSTORE && truststoreType != EXPORT_TRUSTSTORE) { throw CIMException(CIM_ERR_INVALID_PARAMETER, "The truststore specified by truststoreType is invalid."); } //check for a valid username if (!System::isSystemUser(userName.getCString())) { throw CIMException(CIM_ERR_INVALID_PARAMETER, "The user specified by userName is not a valid system user."); } //read in the certificate contents BIO *mem = BIO_new(BIO_s_mem()); char contents[2048]; sprintf(contents, "%s", (const char*) certificateContents.getCString()); BIO_puts(mem, contents); X509 *xCert = NULL; if (!PEM_read_bio_X509(mem, &xCert, 0, NULL)) { BIO_free(mem); PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Error: Could not read x509 PEM format."); MessageLoaderParms parms("ControlProviders.CertificateProvider.BAD_X509_FORMAT", "Could not read x509 PEM format."); throw CIMException(CIM_ERR_FAILED, parms); } BIO_free(mem); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"Read x509 certificate..."); char buf[256]; String issuerName = String::EMPTY; String serialNumber = String::EMPTY; String subjectName = String::EMPTY; CIMDateTime notBefore; CIMDateTime notAfter; //issuer name X509_NAME_oneline(X509_get_issuer_name(xCert), buf, 256); issuerName = String(buf); //serial number long rawSerialNumber = ASN1_INTEGER_get(X509_get_serialNumber(xCert)); char serial[256]; sprintf(serial, "%lu", rawSerialNumber); serialNumber = String(serial); //subject name X509_NAME_oneline(X509_get_subject_name(xCert), buf, 256); subjectName = String(buf); //validity dates notBefore = getDateTime(X509_get_notBefore(xCert)); notAfter = getDateTime(X509_get_notAfter(xCert)); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"IssuerName:" + issuerName); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"SerialNumber:" + serialNumber); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"SubjectName:" + subjectName); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"NotBefore:" + notBefore.toString()); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"NotAfter:" + notAfter.toString()); //check validity with current datetime //openssl will reject the certificate if it's not valid even if we add it to the truststore try { if ((CIMDateTime::getDifference(CIMDateTime::getCurrentDateTime(), notBefore) > 0)) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Certificate or CRL is not valid yet. Check the timestamps on your machine."); MessageLoaderParms parms("ControlProviders.CertificateProvider.CERT_NOT_VALID_YET", "The certificate is not valid yet. Check the timestamps on your machine."); throw CIMException(CIM_ERR_FAILED, parms); } if (CIMDateTime::getDifference(notAfter, CIMDateTime::getCurrentDateTime()) > 0) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Certificate or CRL is expired."); MessageLoaderParms parms("ControlProviders.CertificateProvider.CERT_EXPIRED", "The certificate has expired."); throw CIMException(CIM_ERR_FAILED, parms); } } catch (DateTimeOutOfRangeException& ex) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Certificate or CRL dates are out of range."); MessageLoaderParms parms("ControlProviders.CertificateProvider.BAD_DATE_FORMAT", "The validity dates are out of range."); throw CIMException(CIM_ERR_FAILED, parms); } String storePath = String::EMPTY; String storeId = String::EMPTY; switch (truststoreType) { case SERVER_TRUSTSTORE : storePath = _sslTrustStore; storeId = "server"; break; case EXPORT_TRUSTSTORE : storePath = _exportSSLTrustStore; storeId = "export"; break; default: break; } AutoMutex lock(_trustStoreMutex); //attempt to add cert to truststore String certificateFileName = _getNewCertificateFileName(storePath, X509_subject_name_hash(xCert)); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"Certificate " + certificateFileName + " registered to " + userName + "\n"); // build instance CIMInstance cimInstance(PEGASUS_CLASSNAME_CERTIFICATE); cimInstance.addProperty(CIMProperty(ISSUER_NAME_PROPERTY, CIMValue(issuerName))); cimInstance.addProperty(CIMProperty(SERIAL_NUMBER_PROPERTY, CIMValue(serialNumber))); cimInstance.addProperty(CIMProperty(SUBJECT_NAME_PROPERTY, CIMValue(subjectName))); cimInstance.addProperty(CIMProperty(USER_NAME_PROPERTY, CIMValue(userName))); cimInstance.addProperty(CIMProperty(TRUSTSTORE_TYPE_PROPERTY, CIMValue(truststoreType))); cimInstance.addProperty(CIMProperty(FILE_NAME_PROPERTY, CIMValue(certificateFileName))); cimInstance.addProperty(CIMProperty(NOT_BEFORE_PROPERTY, CIMValue(notBefore))); cimInstance.addProperty(CIMProperty(NOT_AFTER_PROPERTY, CIMValue(notAfter))); // set keys Array<CIMKeyBinding> keys; CIMKeyBinding key; key.setName(ISSUER_NAME_PROPERTY.getString()); key.setValue(issuerName); key.setType(CIMKeyBinding::STRING); keys.append(key); key.setName(SERIAL_NUMBER_PROPERTY.getString()); key.setType(CIMKeyBinding::STRING); key.setValue(String(serialNumber)); keys.append(key); key.setName(TRUSTSTORE_TYPE_PROPERTY.getString()); key.setType(CIMKeyBinding::NUMERIC); char tmp[10]; sprintf(tmp, "%d", truststoreType); key.setValue(String(tmp)); keys.append(key); // set object path for instance cimInstance.setPath(CIMObjectPath(cimObjectPath.getHost(), cimObjectPath.getNameSpace(), PEGASUS_CLASSNAME_CERTIFICATE, keys)); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"New certificate COP: " + cimInstance.getPath().toString()); //attempt to add the instance to the repository first; that way if this instance already exist it will take care of throwing //an error before we add the file to the truststore _repository->createInstance("root/PG_Internal", cimInstance); //ATTN: Take care of this conversion char newFileName[256]; sprintf(newFileName, "%s", (const char*) certificateFileName.getCString()); //use the ssl functions to write out the client x509 certificate //TODO: add some error checking here BIO* outFile = BIO_new(BIO_s_file()); BIO_write_filename(outFile, newFileName); int i = PEM_write_bio_X509(outFile, xCert); BIO_free_all(outFile); Logger::put(Logger::STANDARD_LOG, System::CIMSERVER, Logger::TRACE, "The certificate registered to $0 from issuer $1 has been added to the $2 truststore.", userName, issuerName, storeId); CIMValue returnValue(Boolean(true)); handler.deliver(returnValue); handler.complete(); } else { throw CIMException(CIM_ERR_METHOD_NOT_FOUND, methodName.getString()); } } else if (className == PEGASUS_CLASSNAME_CRL) { if (methodName == METHOD_ADD_CRL) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"CertificateProvider::addCertificateRevocationList"); String crlContents = String::EMPTY; CIMValue cimValue; cimValue = inParams[0].getValue(); cimValue.get(crlContents); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"inparam CRL contents:" + crlContents); //check for a valid CRL //read in the CRL contents BIO *mem = BIO_new(BIO_s_mem()); char contents[2048]; sprintf(contents, "%s", (const char*) crlContents.getCString()); BIO_puts(mem, contents); X509_CRL *xCrl = NULL; if (!PEM_read_bio_X509_CRL(mem, &xCrl, NULL, NULL)) { BIO_free(mem); PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Error: Could not read x509 PEM format."); MessageLoaderParms parms("ControlProviders.CertificateProvider.BAD_X509_FORMAT", "Could not read x509 PEM format."); throw CIMException(CIM_ERR_FAILED, parms); } BIO_free(mem); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"Successfully read x509 CRL..."); char buf[256]; String issuerName = String::EMPTY; CIMDateTime lastUpdate; CIMDateTime nextUpdate; Array<String> revokedSerialNumbers; Array<CIMDateTime> revocationDates; //issuer name X509_NAME_oneline(X509_CRL_get_issuer(xCrl), buf, 256); issuerName = String(buf); //check validity of CRL //openssl will only issue a warning if the CRL is expired //However, we still don't want to let them register an expired or invalid CRL lastUpdate = getDateTime(X509_CRL_get_lastUpdate(xCrl)); nextUpdate = getDateTime(X509_CRL_get_nextUpdate(xCrl)); try { if ((CIMDateTime::getDifference(CIMDateTime::getCurrentDateTime(), lastUpdate) > 0)) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "The CRL is not valid yet. Check the timestamps on your machine."); MessageLoaderParms parms("ControlProviders.CertificateProvider.CRL_NOT_VALID_YET", "The CRL is not valid yet. Check the timestamps on your machine."); throw CIMException(CIM_ERR_FAILED, parms); } if (CIMDateTime::getDifference(nextUpdate, CIMDateTime::getCurrentDateTime()) > 0) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "This CRL is not up-to-date. Check the CA for the latest one."); MessageLoaderParms parms("ControlProviders.CertificateProvider.CRL_EXPIRED", "The CRL is not up-to-date. Check with the issuing CA for the latest one."); throw CIMException(CIM_ERR_FAILED, parms); } } catch (DateTimeOutOfRangeException& ex) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Certificate or CRL dates are out of range."); MessageLoaderParms parms("ControlProviders.CertificateProvider.BAD_DATE_FORMAT", "Certificate or CRL dates are out of range."); throw CIMException(CIM_ERR_FAILED, parms); } STACK_OF(X509_REVOKED)* revokedCertificates = NULL; X509_REVOKED* revokedCertificate = NULL; int revokedCount = -1; revokedCertificates = X509_CRL_get_REVOKED(xCrl); revokedCount = sk_X509_REVOKED_num(revokedCertificates); char countStr[3]; sprintf(countStr, "%d", revokedCount); if (revokedCount > 0) { PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4, "CRL contains revoked certificate entries "); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4, countStr); } else { PEG_TRACE_STRING(TRC_CONTROLPROVIDER, Tracer::LEVEL3, "Error: CRL is empty."); MessageLoaderParms parms("ControlProviders.CertificateProvider.EMPTY_CRL", "The CRL is empty."); throw CIMException(CIM_ERR_FAILED, parms); } AutoMutex lock(_crlStoreMutex); String crlFileName = _getCRLFileName(_crlStore, X509_NAME_hash(X509_CRL_get_issuer(xCrl))); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4,"IssuerName:" + issuerName); PEG_TRACE_STRING(TRC_CONTROLPROVIDER,Tracer::LEVEL4, "FileName: " + crlFileName); //ATTN: Take care of this conversion //For some reason i cannot do this in the BIO_write_filename call char newFileName[256]; sprintf(newFileName, "%s", (const char*) crlFileName.getCString()); //use the ssl functions to write out the client x509 certificate //TODO: add some error checking here BIO* outFile = BIO_new(BIO_s_file()); BIO_write_filename(outFile, newFileName); int i = PEM_write_bio_X509_CRL(outFile, xCrl); BIO_free_all(outFile); Logger::put(Logger::STANDARD_LOG, System::CIMSERVER, Logger::TRACE, "The CRL for issuer $1 has been updated.", issuerName); //reload the CRL store PEG_TRACE_STRING(TRC_SSL, Tracer::LEVEL4, "Loading CRL store after an update"); _sslContextMgr->reloadCRLStore(); CIMValue returnValue(Boolean(true)); handler.deliver(returnValue); handler.complete(); } else { throw CIMException(CIM_ERR_METHOD_NOT_FOUND, methodName.getString()); } } else { throw CIMException(CIM_ERR_INVALID_CLASS, className.getString()); } } PEGASUS_NAMESPACE_END
38.513423
153
0.602962
ncultra
fc906a2bfe61ef2f84e65645354923805de7afcd
37,362
hpp
C++
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_TC.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_TC.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_TC.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _CISCO_TC_ #define _CISCO_TC_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> namespace cisco_ios_xe { namespace CISCO_TC { class CiscoPortListRange : public ydk::Enum { public: static const ydk::Enum::YLeaf oneto2k; static const ydk::Enum::YLeaf twoKto4K; static const ydk::Enum::YLeaf fourKto6K; static const ydk::Enum::YLeaf sixKto8K; static const ydk::Enum::YLeaf eightKto10K; static const ydk::Enum::YLeaf tenKto12K; static const ydk::Enum::YLeaf twelveKto14K; static const ydk::Enum::YLeaf fourteenKto16K; static int get_enum_value(const std::string & name) { if (name == "oneto2k") return 1; if (name == "twoKto4K") return 2; if (name == "fourKto6K") return 3; if (name == "sixKto8K") return 4; if (name == "eightKto10K") return 5; if (name == "tenKto12K") return 6; if (name == "twelveKto14K") return 7; if (name == "fourteenKto16K") return 8; return -1; } }; class CiscoNetworkProtocol : public ydk::Enum { public: static const ydk::Enum::YLeaf ip; static const ydk::Enum::YLeaf decnet; static const ydk::Enum::YLeaf pup; static const ydk::Enum::YLeaf chaos; static const ydk::Enum::YLeaf xns; static const ydk::Enum::YLeaf x121; static const ydk::Enum::YLeaf appletalk; static const ydk::Enum::YLeaf clns; static const ydk::Enum::YLeaf lat; static const ydk::Enum::YLeaf vines; static const ydk::Enum::YLeaf cons; static const ydk::Enum::YLeaf apollo; static const ydk::Enum::YLeaf stun; static const ydk::Enum::YLeaf novell; static const ydk::Enum::YLeaf qllc; static const ydk::Enum::YLeaf snapshot; static const ydk::Enum::YLeaf atmIlmi; static const ydk::Enum::YLeaf bstun; static const ydk::Enum::YLeaf x25pvc; static const ydk::Enum::YLeaf ipv6; static const ydk::Enum::YLeaf cdm; static const ydk::Enum::YLeaf nbf; static const ydk::Enum::YLeaf bpxIgx; static const ydk::Enum::YLeaf clnsPfx; static const ydk::Enum::YLeaf http; static const ydk::Enum::YLeaf unknown; static int get_enum_value(const std::string & name) { if (name == "ip") return 1; if (name == "decnet") return 2; if (name == "pup") return 3; if (name == "chaos") return 4; if (name == "xns") return 5; if (name == "x121") return 6; if (name == "appletalk") return 7; if (name == "clns") return 8; if (name == "lat") return 9; if (name == "vines") return 10; if (name == "cons") return 11; if (name == "apollo") return 12; if (name == "stun") return 13; if (name == "novell") return 14; if (name == "qllc") return 15; if (name == "snapshot") return 16; if (name == "atmIlmi") return 17; if (name == "bstun") return 18; if (name == "x25pvc") return 19; if (name == "ipv6") return 20; if (name == "cdm") return 21; if (name == "nbf") return 22; if (name == "bpxIgx") return 23; if (name == "clnsPfx") return 24; if (name == "http") return 25; if (name == "unknown") return 65535; return -1; } }; class CiscoRowOperStatus : public ydk::Enum { public: static const ydk::Enum::YLeaf active; static const ydk::Enum::YLeaf activeDependencies; static const ydk::Enum::YLeaf inactiveDependency; static const ydk::Enum::YLeaf missingDependency; static int get_enum_value(const std::string & name) { if (name == "active") return 1; if (name == "activeDependencies") return 2; if (name == "inactiveDependency") return 3; if (name == "missingDependency") return 4; return -1; } }; class CiscoLocationClass : public ydk::Enum { public: static const ydk::Enum::YLeaf chassis; static const ydk::Enum::YLeaf shelf; static const ydk::Enum::YLeaf slot; static const ydk::Enum::YLeaf subSlot; static const ydk::Enum::YLeaf port; static const ydk::Enum::YLeaf subPort; static const ydk::Enum::YLeaf channel; static const ydk::Enum::YLeaf subChannel; static int get_enum_value(const std::string & name) { if (name == "chassis") return 1; if (name == "shelf") return 2; if (name == "slot") return 3; if (name == "subSlot") return 4; if (name == "port") return 5; if (name == "subPort") return 6; if (name == "channel") return 7; if (name == "subChannel") return 8; return -1; } }; class IfOperStatusReason : public ydk::Enum { public: static const ydk::Enum::YLeaf other; static const ydk::Enum::YLeaf none; static const ydk::Enum::YLeaf hwFailure; static const ydk::Enum::YLeaf loopbackDiagFailure; static const ydk::Enum::YLeaf errorDisabled; static const ydk::Enum::YLeaf swFailure; static const ydk::Enum::YLeaf linkFailure; static const ydk::Enum::YLeaf offline; static const ydk::Enum::YLeaf nonParticipating; static const ydk::Enum::YLeaf initializing; static const ydk::Enum::YLeaf vsanInactive; static const ydk::Enum::YLeaf adminDown; static const ydk::Enum::YLeaf channelAdminDown; static const ydk::Enum::YLeaf channelOperSuspended; static const ydk::Enum::YLeaf channelConfigurationInProgress; static const ydk::Enum::YLeaf rcfInProgress; static const ydk::Enum::YLeaf elpFailureIsolation; static const ydk::Enum::YLeaf escFailureIsolation; static const ydk::Enum::YLeaf domainOverlapIsolation; static const ydk::Enum::YLeaf domainAddrAssignFailureIsolation; static const ydk::Enum::YLeaf domainOtherSideEportIsolation; static const ydk::Enum::YLeaf domainInvalidRcfReceived; static const ydk::Enum::YLeaf domainManagerDisabled; static const ydk::Enum::YLeaf zoneMergeFailureIsolation; static const ydk::Enum::YLeaf vsanMismatchIsolation; static const ydk::Enum::YLeaf parentDown; static const ydk::Enum::YLeaf srcPortNotBound; static const ydk::Enum::YLeaf interfaceRemoved; static const ydk::Enum::YLeaf fcotNotPresent; static const ydk::Enum::YLeaf fcotVendorNotSupported; static const ydk::Enum::YLeaf incompatibleAdminMode; static const ydk::Enum::YLeaf incompatibleAdminSpeed; static const ydk::Enum::YLeaf suspendedByMode; static const ydk::Enum::YLeaf suspendedBySpeed; static const ydk::Enum::YLeaf suspendedByWWN; static const ydk::Enum::YLeaf domainMaxReTxFailure; static const ydk::Enum::YLeaf eppFailure; static const ydk::Enum::YLeaf portVsanMismatchIsolation; static const ydk::Enum::YLeaf loopbackIsolation; static const ydk::Enum::YLeaf upgradeInProgress; static const ydk::Enum::YLeaf incompatibleAdminRxBbCredit; static const ydk::Enum::YLeaf incompatibleAdminRxBufferSize; static const ydk::Enum::YLeaf portChannelMembersDown; static const ydk::Enum::YLeaf zoneRemoteNoRespIsolation; static const ydk::Enum::YLeaf firstPortUpAsEport; static const ydk::Enum::YLeaf firstPortNotUp; static const ydk::Enum::YLeaf peerFCIPPortClosedConnection; static const ydk::Enum::YLeaf peerFCIPPortResetConnection; static const ydk::Enum::YLeaf fcipPortMaxReTx; static const ydk::Enum::YLeaf fcipPortKeepAliveTimerExpire; static const ydk::Enum::YLeaf fcipPortPersistTimerExpire; static const ydk::Enum::YLeaf fcipPortSrcLinkDown; static const ydk::Enum::YLeaf fcipPortSrcAdminDown; static const ydk::Enum::YLeaf fcipPortAdminCfgChange; static const ydk::Enum::YLeaf fcipSrcPortRemoved; static const ydk::Enum::YLeaf fcipSrcModuleNotOnline; static const ydk::Enum::YLeaf invalidConfig; static const ydk::Enum::YLeaf portBindFailure; static const ydk::Enum::YLeaf portFabricBindFailure; static const ydk::Enum::YLeaf noCommonVsanIsolation; static const ydk::Enum::YLeaf ficonVsanDown; static const ydk::Enum::YLeaf invalidAttachment; static const ydk::Enum::YLeaf portBlocked; static const ydk::Enum::YLeaf incomAdminRxBbCreditPerBuf; static const ydk::Enum::YLeaf tooManyInvalidFlogis; static const ydk::Enum::YLeaf deniedDueToPortBinding; static const ydk::Enum::YLeaf elpFailureRevMismatch; static const ydk::Enum::YLeaf elpFailureClassFParamErr; static const ydk::Enum::YLeaf elpFailureClassNParamErr; static const ydk::Enum::YLeaf elpFailureUnknownFlowCtlCode; static const ydk::Enum::YLeaf elpFailureInvalidFlowCtlParam; static const ydk::Enum::YLeaf elpFailureInvalidPortName; static const ydk::Enum::YLeaf elpFailureInvalidSwitchName; static const ydk::Enum::YLeaf elpFailureRatovEdtovMismatch; static const ydk::Enum::YLeaf elpFailureLoopbackDetected; static const ydk::Enum::YLeaf elpFailureInvalidTxBbCredit; static const ydk::Enum::YLeaf elpFailureInvalidPayloadSize; static const ydk::Enum::YLeaf bundleMisCfg; static const ydk::Enum::YLeaf bitErrRuntimeThreshExceeded; static const ydk::Enum::YLeaf linkFailLinkReset; static const ydk::Enum::YLeaf linkFailPortInitFail; static const ydk::Enum::YLeaf linkFailPortUnusable; static const ydk::Enum::YLeaf linkFailLossOfSignal; static const ydk::Enum::YLeaf linkFailLossOfSync; static const ydk::Enum::YLeaf linkFailNosRcvd; static const ydk::Enum::YLeaf linkFailOLSRcvd; static const ydk::Enum::YLeaf linkFailDebounceTimeout; static const ydk::Enum::YLeaf linkFailLrRcvd; static const ydk::Enum::YLeaf linkFailCreditLoss; static const ydk::Enum::YLeaf linkFailRxQOverflow; static const ydk::Enum::YLeaf linkFailTooManyInterrupts; static const ydk::Enum::YLeaf linkFailLipRcvdBb; static const ydk::Enum::YLeaf linkFailBbCreditLoss; static const ydk::Enum::YLeaf linkFailOpenPrimSignalTimeout; static const ydk::Enum::YLeaf linkFailOpenPrimSignalReturned; static const ydk::Enum::YLeaf linkFailLipF8Rcvd; static const ydk::Enum::YLeaf linkFailLineCardPortShutdown; static const ydk::Enum::YLeaf fcspAuthenfailure; static const ydk::Enum::YLeaf fcotChecksumError; static const ydk::Enum::YLeaf ohmsExtLoopbackTest; static const ydk::Enum::YLeaf invalidFabricBindExchange; static const ydk::Enum::YLeaf tovMismatch; static const ydk::Enum::YLeaf ficonNotEnabled; static const ydk::Enum::YLeaf ficonNoPortNumber; static const ydk::Enum::YLeaf ficonBeingEnabled; static const ydk::Enum::YLeaf ePortProhibited; static const ydk::Enum::YLeaf portGracefulShutdown; static const ydk::Enum::YLeaf trunkNotFullyActive; static const ydk::Enum::YLeaf fabricBindingSwitchWwnNotFound; static const ydk::Enum::YLeaf fabricBindingDomainInvalid; static const ydk::Enum::YLeaf fabricBindingDbMismatch; static const ydk::Enum::YLeaf fabricBindingNoRspFromPeer; static const ydk::Enum::YLeaf dpvmVsanSuspended; static const ydk::Enum::YLeaf dpvmVsanNotFound; static const ydk::Enum::YLeaf trackedPortDown; static const ydk::Enum::YLeaf ecSuspendedOnLoop; static const ydk::Enum::YLeaf isolateBundleMisCfg; static const ydk::Enum::YLeaf noPeerBundleSupport; static const ydk::Enum::YLeaf portBringupIsolation; static const ydk::Enum::YLeaf domainNotAllowedIsolated; static const ydk::Enum::YLeaf virtualIvrDomainOverlapIsolation; static const ydk::Enum::YLeaf outOfService; static const ydk::Enum::YLeaf portAuthFailed; static const ydk::Enum::YLeaf bundleStandby; static const ydk::Enum::YLeaf portConnectorTypeErr; static const ydk::Enum::YLeaf errorDisabledReInitLmtReached; static const ydk::Enum::YLeaf ficonDupPortNum; static const ydk::Enum::YLeaf localRcf; static const ydk::Enum::YLeaf twoSwitchesWithSameWWN; static const ydk::Enum::YLeaf invalidOtherSidePrincEFPReqRecd; static const ydk::Enum::YLeaf domainOther; static const ydk::Enum::YLeaf elpFailureAllZeroPeerWWNRcvd; static const ydk::Enum::YLeaf preferredPathIsolation; static const ydk::Enum::YLeaf fcRedirectIsolation; static const ydk::Enum::YLeaf portActLicenseNotAvailable; static const ydk::Enum::YLeaf sdmIsolation; static const ydk::Enum::YLeaf fcidAllocationFailed; static const ydk::Enum::YLeaf externallyDisabled; static const ydk::Enum::YLeaf unavailableNPVUpstreamPort; static const ydk::Enum::YLeaf unavailableNPVPrefUpstreamPort; static const ydk::Enum::YLeaf sfpReadError; static const ydk::Enum::YLeaf stickyDownOnLinkFailure; static const ydk::Enum::YLeaf tooManyLinkFlapsErr; static const ydk::Enum::YLeaf unidirectionalUDLD; static const ydk::Enum::YLeaf txRxLoopUDLD; static const ydk::Enum::YLeaf neighborMismatchUDLD; static const ydk::Enum::YLeaf authzPending; static const ydk::Enum::YLeaf hotStdbyInBundle; static const ydk::Enum::YLeaf incompleteConfig; static const ydk::Enum::YLeaf incompleteTunnelCfg; static const ydk::Enum::YLeaf hwProgrammingFailed; static const ydk::Enum::YLeaf tunnelDstUnreachable; static const ydk::Enum::YLeaf suspendByMtu; static const ydk::Enum::YLeaf sfpInvalid; static const ydk::Enum::YLeaf sfpAbsent; static const ydk::Enum::YLeaf portCapabilitiesUnknown; static const ydk::Enum::YLeaf channelErrDisabled; static const ydk::Enum::YLeaf vrfMismatch; static const ydk::Enum::YLeaf vrfForwardReferencing; static const ydk::Enum::YLeaf dupTunnelConfigDetected; static const ydk::Enum::YLeaf primaryVLANDown; static const ydk::Enum::YLeaf vrfUnusable; static const ydk::Enum::YLeaf errDisableHandShkFailure; static const ydk::Enum::YLeaf errDisabledBPDUGuard; static const ydk::Enum::YLeaf dot1xSecViolationErrDisabled; static const ydk::Enum::YLeaf emptyEchoUDLD; static const ydk::Enum::YLeaf vfTaggingCapErr; static const ydk::Enum::YLeaf portDisabled; static const ydk::Enum::YLeaf tunnelModeNotConfigured; static const ydk::Enum::YLeaf tunnelSrcNotConfigured; static const ydk::Enum::YLeaf tunnelDstNotConfigured; static const ydk::Enum::YLeaf tunnelUnableToResolveSrcIP; static const ydk::Enum::YLeaf tunnelUnableToResolveDstIP; static const ydk::Enum::YLeaf tunnelVrfDown; static const ydk::Enum::YLeaf sifAdminDown; static const ydk::Enum::YLeaf phyIntfDown; static const ydk::Enum::YLeaf ifSifLimitExceeded; static const ydk::Enum::YLeaf sifHoldDown; static const ydk::Enum::YLeaf noFcoe; static const ydk::Enum::YLeaf dcxCompatMismatch; static const ydk::Enum::YLeaf isolateBundleLimitExceeded; static const ydk::Enum::YLeaf sifNotBound; static const ydk::Enum::YLeaf errDisabledLacpMiscfg; static const ydk::Enum::YLeaf satFabricIfDown; static const ydk::Enum::YLeaf invalidSatFabricIf; static const ydk::Enum::YLeaf noRemoteChassis; static const ydk::Enum::YLeaf vicEnableNotReceived; static const ydk::Enum::YLeaf vicDisableReceived; static const ydk::Enum::YLeaf vlanVsanMappingNotEnabled; static const ydk::Enum::YLeaf stpNotFwdingInFcoeMappedVlan; static const ydk::Enum::YLeaf moduleOffline; static const ydk::Enum::YLeaf udldAggModeLinkFailure; static const ydk::Enum::YLeaf stpInconsVpcPeerDisabled; static const ydk::Enum::YLeaf setPortStateFailed; static const ydk::Enum::YLeaf suspendedByVpc; static const ydk::Enum::YLeaf vpcCfgInProgress; static const ydk::Enum::YLeaf vpcPeerLinkDown; static const ydk::Enum::YLeaf vpcNoRspFromPeer; static const ydk::Enum::YLeaf protoPortSuspend; static const ydk::Enum::YLeaf tunnelSrcDown; static const ydk::Enum::YLeaf cdpInfoUnavailable; static const ydk::Enum::YLeaf fexSfpInvalid; static const ydk::Enum::YLeaf errDisabledIpConflict; static const ydk::Enum::YLeaf fcotClkRateMismatch; static const ydk::Enum::YLeaf portGuardTrustSecViolation; static const ydk::Enum::YLeaf sdpTimeout; static const ydk::Enum::YLeaf satIncompatTopo; static const ydk::Enum::YLeaf waitForFlogi; static const ydk::Enum::YLeaf satNotConfigured; static const ydk::Enum::YLeaf npivNotEnabledInUpstream; static const ydk::Enum::YLeaf vsanMismatchWithUpstreamSwPort; static const ydk::Enum::YLeaf portGuardBitErrRate; static const ydk::Enum::YLeaf portGuardSigLoss; static const ydk::Enum::YLeaf portGuardSyncLoss; static const ydk::Enum::YLeaf portGuardLinkReset; static const ydk::Enum::YLeaf portGuardCreditLoss; static const ydk::Enum::YLeaf ipQosMgrPolicyAppFailure; static const ydk::Enum::YLeaf pauseRateLimitErrDisabled; static const ydk::Enum::YLeaf lstGrpUplinkDown; static const ydk::Enum::YLeaf stickyDnLinkFailure; static const ydk::Enum::YLeaf routerMacFailure; static const ydk::Enum::YLeaf dcxMultipleMsapIds; static const ydk::Enum::YLeaf dcxHundredPdusRcvdNoAck; static const ydk::Enum::YLeaf enmSatIncompatibleUplink; static const ydk::Enum::YLeaf enmLoopDetected; static const ydk::Enum::YLeaf nonStickyExternallyDisabled; static const ydk::Enum::YLeaf subGroupIdNotAssigned; static const ydk::Enum::YLeaf vemUnlicensed; static const ydk::Enum::YLeaf profileNotFound; static const ydk::Enum::YLeaf nonExistentVlan; static const ydk::Enum::YLeaf vlanInvalidType; static const ydk::Enum::YLeaf vlanDown; static const ydk::Enum::YLeaf vpcPeerUpgrade; static const ydk::Enum::YLeaf ipQosDcbxpCompatFailure; static const ydk::Enum::YLeaf nonCiscoHbaVfTag; static const ydk::Enum::YLeaf domainIdConfigMismatch; static const ydk::Enum::YLeaf sfpSpeedMismatch; static const ydk::Enum::YLeaf xcvrInitializing; static const ydk::Enum::YLeaf xcvrAbsent; static const ydk::Enum::YLeaf xcvrInvalid; static const ydk::Enum::YLeaf vfcBindingInvalid; static const ydk::Enum::YLeaf vlanNotFcoeEnabled; static const ydk::Enum::YLeaf pvlanNativeVlanErr; static const ydk::Enum::YLeaf ethL2VlanDown; static const ydk::Enum::YLeaf ethIntfInvalidBinding; static const ydk::Enum::YLeaf pmonFailure; static const ydk::Enum::YLeaf l3NotReady; static const ydk::Enum::YLeaf speedMismatch; static const ydk::Enum::YLeaf flowControlMismatch; static const ydk::Enum::YLeaf vdcMode; static const ydk::Enum::YLeaf suspendedDueToMinLinks; static const ydk::Enum::YLeaf enmPinFailLinkDown; static const ydk::Enum::YLeaf inactiveM1PortFpathActiveVlan; static const ydk::Enum::YLeaf parentPortDown; static const ydk::Enum::YLeaf moduleRemoved; static const ydk::Enum::YLeaf corePortMct; static const ydk::Enum::YLeaf nonCorePortMct; static const ydk::Enum::YLeaf ficonInorderNotActive; static const ydk::Enum::YLeaf invalidEncapsulation; static const ydk::Enum::YLeaf modemLineDeasserted; static const ydk::Enum::YLeaf ipSecHndshkInProgress; static const ydk::Enum::YLeaf sfpEthCompliantErr; static const ydk::Enum::YLeaf cellularModemUnattached; static const ydk::Enum::YLeaf outOfGlblRxBuffers; static const ydk::Enum::YLeaf sfpFcCompliantErr; static const ydk::Enum::YLeaf ethIntfNotLicensed; static const ydk::Enum::YLeaf domainIdsInvalid; static const ydk::Enum::YLeaf fabricNameInvalid; static int get_enum_value(const std::string & name) { if (name == "other") return 1; if (name == "none") return 2; if (name == "hwFailure") return 3; if (name == "loopbackDiagFailure") return 4; if (name == "errorDisabled") return 5; if (name == "swFailure") return 6; if (name == "linkFailure") return 7; if (name == "offline") return 8; if (name == "nonParticipating") return 9; if (name == "initializing") return 10; if (name == "vsanInactive") return 11; if (name == "adminDown") return 12; if (name == "channelAdminDown") return 13; if (name == "channelOperSuspended") return 14; if (name == "channelConfigurationInProgress") return 15; if (name == "rcfInProgress") return 16; if (name == "elpFailureIsolation") return 17; if (name == "escFailureIsolation") return 18; if (name == "domainOverlapIsolation") return 19; if (name == "domainAddrAssignFailureIsolation") return 20; if (name == "domainOtherSideEportIsolation") return 21; if (name == "domainInvalidRcfReceived") return 22; if (name == "domainManagerDisabled") return 23; if (name == "zoneMergeFailureIsolation") return 24; if (name == "vsanMismatchIsolation") return 25; if (name == "parentDown") return 26; if (name == "srcPortNotBound") return 27; if (name == "interfaceRemoved") return 28; if (name == "fcotNotPresent") return 29; if (name == "fcotVendorNotSupported") return 30; if (name == "incompatibleAdminMode") return 31; if (name == "incompatibleAdminSpeed") return 32; if (name == "suspendedByMode") return 33; if (name == "suspendedBySpeed") return 34; if (name == "suspendedByWWN") return 35; if (name == "domainMaxReTxFailure") return 36; if (name == "eppFailure") return 37; if (name == "portVsanMismatchIsolation") return 38; if (name == "loopbackIsolation") return 39; if (name == "upgradeInProgress") return 40; if (name == "incompatibleAdminRxBbCredit") return 41; if (name == "incompatibleAdminRxBufferSize") return 42; if (name == "portChannelMembersDown") return 43; if (name == "zoneRemoteNoRespIsolation") return 44; if (name == "firstPortUpAsEport") return 45; if (name == "firstPortNotUp") return 46; if (name == "peerFCIPPortClosedConnection") return 47; if (name == "peerFCIPPortResetConnection") return 48; if (name == "fcipPortMaxReTx") return 49; if (name == "fcipPortKeepAliveTimerExpire") return 50; if (name == "fcipPortPersistTimerExpire") return 51; if (name == "fcipPortSrcLinkDown") return 52; if (name == "fcipPortSrcAdminDown") return 53; if (name == "fcipPortAdminCfgChange") return 54; if (name == "fcipSrcPortRemoved") return 55; if (name == "fcipSrcModuleNotOnline") return 56; if (name == "invalidConfig") return 57; if (name == "portBindFailure") return 58; if (name == "portFabricBindFailure") return 59; if (name == "noCommonVsanIsolation") return 60; if (name == "ficonVsanDown") return 61; if (name == "invalidAttachment") return 62; if (name == "portBlocked") return 63; if (name == "incomAdminRxBbCreditPerBuf") return 64; if (name == "tooManyInvalidFlogis") return 65; if (name == "deniedDueToPortBinding") return 66; if (name == "elpFailureRevMismatch") return 67; if (name == "elpFailureClassFParamErr") return 68; if (name == "elpFailureClassNParamErr") return 69; if (name == "elpFailureUnknownFlowCtlCode") return 70; if (name == "elpFailureInvalidFlowCtlParam") return 71; if (name == "elpFailureInvalidPortName") return 72; if (name == "elpFailureInvalidSwitchName") return 73; if (name == "elpFailureRatovEdtovMismatch") return 74; if (name == "elpFailureLoopbackDetected") return 75; if (name == "elpFailureInvalidTxBbCredit") return 76; if (name == "elpFailureInvalidPayloadSize") return 77; if (name == "bundleMisCfg") return 78; if (name == "bitErrRuntimeThreshExceeded") return 79; if (name == "linkFailLinkReset") return 80; if (name == "linkFailPortInitFail") return 81; if (name == "linkFailPortUnusable") return 82; if (name == "linkFailLossOfSignal") return 83; if (name == "linkFailLossOfSync") return 84; if (name == "linkFailNosRcvd") return 85; if (name == "linkFailOLSRcvd") return 86; if (name == "linkFailDebounceTimeout") return 87; if (name == "linkFailLrRcvd") return 88; if (name == "linkFailCreditLoss") return 89; if (name == "linkFailRxQOverflow") return 90; if (name == "linkFailTooManyInterrupts") return 91; if (name == "linkFailLipRcvdBb") return 92; if (name == "linkFailBbCreditLoss") return 93; if (name == "linkFailOpenPrimSignalTimeout") return 94; if (name == "linkFailOpenPrimSignalReturned") return 95; if (name == "linkFailLipF8Rcvd") return 96; if (name == "linkFailLineCardPortShutdown") return 97; if (name == "fcspAuthenfailure") return 98; if (name == "fcotChecksumError") return 99; if (name == "ohmsExtLoopbackTest") return 100; if (name == "invalidFabricBindExchange") return 101; if (name == "tovMismatch") return 102; if (name == "ficonNotEnabled") return 103; if (name == "ficonNoPortNumber") return 104; if (name == "ficonBeingEnabled") return 105; if (name == "ePortProhibited") return 106; if (name == "portGracefulShutdown") return 107; if (name == "trunkNotFullyActive") return 108; if (name == "fabricBindingSwitchWwnNotFound") return 109; if (name == "fabricBindingDomainInvalid") return 110; if (name == "fabricBindingDbMismatch") return 111; if (name == "fabricBindingNoRspFromPeer") return 112; if (name == "dpvmVsanSuspended") return 113; if (name == "dpvmVsanNotFound") return 114; if (name == "trackedPortDown") return 115; if (name == "ecSuspendedOnLoop") return 116; if (name == "isolateBundleMisCfg") return 117; if (name == "noPeerBundleSupport") return 118; if (name == "portBringupIsolation") return 119; if (name == "domainNotAllowedIsolated") return 120; if (name == "virtualIvrDomainOverlapIsolation") return 121; if (name == "outOfService") return 122; if (name == "portAuthFailed") return 123; if (name == "bundleStandby") return 124; if (name == "portConnectorTypeErr") return 125; if (name == "errorDisabledReInitLmtReached") return 126; if (name == "ficonDupPortNum") return 127; if (name == "localRcf") return 128; if (name == "twoSwitchesWithSameWWN") return 129; if (name == "invalidOtherSidePrincEFPReqRecd") return 130; if (name == "domainOther") return 131; if (name == "elpFailureAllZeroPeerWWNRcvd") return 132; if (name == "preferredPathIsolation") return 133; if (name == "fcRedirectIsolation") return 134; if (name == "portActLicenseNotAvailable") return 135; if (name == "sdmIsolation") return 136; if (name == "fcidAllocationFailed") return 137; if (name == "externallyDisabled") return 138; if (name == "unavailableNPVUpstreamPort") return 139; if (name == "unavailableNPVPrefUpstreamPort") return 140; if (name == "sfpReadError") return 141; if (name == "stickyDownOnLinkFailure") return 142; if (name == "tooManyLinkFlapsErr") return 143; if (name == "unidirectionalUDLD") return 144; if (name == "txRxLoopUDLD") return 145; if (name == "neighborMismatchUDLD") return 146; if (name == "authzPending") return 147; if (name == "hotStdbyInBundle") return 148; if (name == "incompleteConfig") return 149; if (name == "incompleteTunnelCfg") return 150; if (name == "hwProgrammingFailed") return 151; if (name == "tunnelDstUnreachable") return 152; if (name == "suspendByMtu") return 153; if (name == "sfpInvalid") return 154; if (name == "sfpAbsent") return 155; if (name == "portCapabilitiesUnknown") return 156; if (name == "channelErrDisabled") return 157; if (name == "vrfMismatch") return 158; if (name == "vrfForwardReferencing") return 159; if (name == "dupTunnelConfigDetected") return 160; if (name == "primaryVLANDown") return 161; if (name == "vrfUnusable") return 162; if (name == "errDisableHandShkFailure") return 163; if (name == "errDisabledBPDUGuard") return 164; if (name == "dot1xSecViolationErrDisabled") return 165; if (name == "emptyEchoUDLD") return 166; if (name == "vfTaggingCapErr") return 167; if (name == "portDisabled") return 168; if (name == "tunnelModeNotConfigured") return 169; if (name == "tunnelSrcNotConfigured") return 170; if (name == "tunnelDstNotConfigured") return 171; if (name == "tunnelUnableToResolveSrcIP") return 172; if (name == "tunnelUnableToResolveDstIP") return 173; if (name == "tunnelVrfDown") return 174; if (name == "sifAdminDown") return 175; if (name == "phyIntfDown") return 176; if (name == "ifSifLimitExceeded") return 177; if (name == "sifHoldDown") return 178; if (name == "noFcoe") return 179; if (name == "dcxCompatMismatch") return 180; if (name == "isolateBundleLimitExceeded") return 181; if (name == "sifNotBound") return 182; if (name == "errDisabledLacpMiscfg") return 183; if (name == "satFabricIfDown") return 184; if (name == "invalidSatFabricIf") return 185; if (name == "noRemoteChassis") return 186; if (name == "vicEnableNotReceived") return 187; if (name == "vicDisableReceived") return 188; if (name == "vlanVsanMappingNotEnabled") return 189; if (name == "stpNotFwdingInFcoeMappedVlan") return 190; if (name == "moduleOffline") return 191; if (name == "udldAggModeLinkFailure") return 192; if (name == "stpInconsVpcPeerDisabled") return 193; if (name == "setPortStateFailed") return 194; if (name == "suspendedByVpc") return 195; if (name == "vpcCfgInProgress") return 196; if (name == "vpcPeerLinkDown") return 197; if (name == "vpcNoRspFromPeer") return 198; if (name == "protoPortSuspend") return 199; if (name == "tunnelSrcDown") return 200; if (name == "cdpInfoUnavailable") return 201; if (name == "fexSfpInvalid") return 202; if (name == "errDisabledIpConflict") return 203; if (name == "fcotClkRateMismatch") return 204; if (name == "portGuardTrustSecViolation") return 205; if (name == "sdpTimeout") return 206; if (name == "satIncompatTopo") return 207; if (name == "waitForFlogi") return 208; if (name == "satNotConfigured") return 209; if (name == "npivNotEnabledInUpstream") return 210; if (name == "vsanMismatchWithUpstreamSwPort") return 211; if (name == "portGuardBitErrRate") return 212; if (name == "portGuardSigLoss") return 213; if (name == "portGuardSyncLoss") return 214; if (name == "portGuardLinkReset") return 215; if (name == "portGuardCreditLoss") return 216; if (name == "ipQosMgrPolicyAppFailure") return 217; if (name == "pauseRateLimitErrDisabled") return 218; if (name == "lstGrpUplinkDown") return 219; if (name == "stickyDnLinkFailure") return 220; if (name == "routerMacFailure") return 221; if (name == "dcxMultipleMsapIds") return 222; if (name == "dcxHundredPdusRcvdNoAck") return 223; if (name == "enmSatIncompatibleUplink") return 224; if (name == "enmLoopDetected") return 225; if (name == "nonStickyExternallyDisabled") return 226; if (name == "subGroupIdNotAssigned") return 227; if (name == "vemUnlicensed") return 228; if (name == "profileNotFound") return 229; if (name == "nonExistentVlan") return 230; if (name == "vlanInvalidType") return 231; if (name == "vlanDown") return 232; if (name == "vpcPeerUpgrade") return 233; if (name == "ipQosDcbxpCompatFailure") return 234; if (name == "nonCiscoHbaVfTag") return 235; if (name == "domainIdConfigMismatch") return 236; if (name == "sfpSpeedMismatch") return 237; if (name == "xcvrInitializing") return 238; if (name == "xcvrAbsent") return 239; if (name == "xcvrInvalid") return 240; if (name == "vfcBindingInvalid") return 241; if (name == "vlanNotFcoeEnabled") return 242; if (name == "pvlanNativeVlanErr") return 243; if (name == "ethL2VlanDown") return 244; if (name == "ethIntfInvalidBinding") return 245; if (name == "pmonFailure") return 246; if (name == "l3NotReady") return 247; if (name == "speedMismatch") return 248; if (name == "flowControlMismatch") return 249; if (name == "vdcMode") return 250; if (name == "suspendedDueToMinLinks") return 251; if (name == "enmPinFailLinkDown") return 252; if (name == "inactiveM1PortFpathActiveVlan") return 253; if (name == "parentPortDown") return 254; if (name == "moduleRemoved") return 255; if (name == "corePortMct") return 256; if (name == "nonCorePortMct") return 257; if (name == "ficonInorderNotActive") return 258; if (name == "invalidEncapsulation") return 259; if (name == "modemLineDeasserted") return 260; if (name == "ipSecHndshkInProgress") return 261; if (name == "sfpEthCompliantErr") return 262; if (name == "cellularModemUnattached") return 263; if (name == "outOfGlblRxBuffers") return 264; if (name == "sfpFcCompliantErr") return 265; if (name == "ethIntfNotLicensed") return 266; if (name == "domainIdsInvalid") return 267; if (name == "fabricNameInvalid") return 268; return -1; } }; class CiscoAlarmSeverity : public ydk::Enum { public: static const ydk::Enum::YLeaf cleared; static const ydk::Enum::YLeaf indeterminate; static const ydk::Enum::YLeaf critical; static const ydk::Enum::YLeaf major_; static const ydk::Enum::YLeaf minor; static const ydk::Enum::YLeaf warning; static const ydk::Enum::YLeaf info; static int get_enum_value(const std::string & name) { if (name == "cleared") return 1; if (name == "indeterminate") return 2; if (name == "critical") return 3; if (name == "major") return 4; if (name == "minor") return 5; if (name == "warning") return 6; if (name == "info") return 7; return -1; } }; } } #endif /* _CISCO_TC_ */
52.254545
71
0.626572
CiscoDevNet
fc92921f2bf8f6aa4b09393a636bf28f83f695f5
3,415
cpp
C++
Sources/Commands/command_gpt.cpp
c3358/ntfstool
08d6efc1298cb223fe9f24c3849e1aad08c5a45f
[ "MIT" ]
1
2021-07-28T12:54:08.000Z
2021-07-28T12:54:08.000Z
Sources/Commands/command_gpt.cpp
c3358/ntfstool
08d6efc1298cb223fe9f24c3849e1aad08c5a45f
[ "MIT" ]
null
null
null
Sources/Commands/command_gpt.cpp
c3358/ntfstool
08d6efc1298cb223fe9f24c3849e1aad08c5a45f
[ "MIT" ]
null
null
null
#include "Utils/buffer.h" #include "Drive/disk.h" #include "Utils/utils.h" #include "Utils/table.h" #include "options.h" #include "Utils/constant_names.h" #include <intrin.h> #include <distorm.h> #include <algorithm> #include <cstdint> #include <string> #include <iostream> #include <iomanip> #include <memory> #include <stdexcept> namespace commands { namespace gpt { int print_gpt(std::shared_ptr<Options> opts) { std::ios_base::fmtflags flag_backup(std::cout.flags()); std::shared_ptr<Disk> disk = get_disk(opts); if (disk != nullptr) { PGPT_HEADER pgpt = disk->gpt(); if (disk->has_protective_mbr()) { utils::ui::title("GPT from " + disk->name()); std::vector<GPT_PARTITION_ENTRY> gpt_entries = disk->gpt_entries(); std::cout << "Signature : " << pgpt->magic << std::endl; std::cout << "Revision : " << pgpt->revision_high << "." << pgpt->revision_low << std::endl; std::cout << "Header Size : " << pgpt->header_size << std::endl; std::cout << "Header CRC32 : " << std::setfill('0') << std::setw(8) << std::hex << _byteswap_ulong(pgpt->header_crc32) << std::endl; std::cout << "Reserved : " << std::setfill('0') << std::setw(8) << std::hex << pgpt->reserved1 << std::endl; std::cout << std::dec << std::setw(0); std::cout << "Current LBA : " << pgpt->current_lba << std::endl; std::cout << "Backup LBA : " << pgpt->backup_lba << std::endl; std::cout << "First Usable LBA : " << pgpt->first_usable_lba << std::endl; std::cout << "Last Usable LBA : " << pgpt->last_usable_lba << std::endl; std::cout << "GUID : " << utils::id::guid_to_string(pgpt->disk_guid) << std::endl; std::cout << "Entry LBA : " << pgpt->partition_entry_lba << std::endl; std::cout << "Entries Num : " << pgpt->num_partition_entries << std::endl; std::cout << "Entries Size : " << pgpt->sizeof_partition_entry << std::endl; std::cout << "Partitions CRC32 : " << std::setfill('0') << std::setw(8) << std::hex << _byteswap_ulong(pgpt->partition_entry_array_crc32) << std::endl; std::shared_ptr<utils::ui::Table> partitions = std::make_shared<utils::ui::Table>(); partitions->add_header_line("Id"); partitions->add_header_line("Name"); partitions->add_header_line("GUID"); partitions->add_header_line("First sector"); partitions->add_header_line("Last sector"); partitions->add_header_line("Flags"); unsigned int n_partitions = 0; for (GPT_PARTITION_ENTRY& entry : gpt_entries) { n_partitions++; partitions->add_item_line(std::to_string(n_partitions)); partitions->add_item_line(utils::strings::to_utf8(entry.PartitionName)); partitions->add_item_line(utils::id::guid_to_string(entry.UniquePartitionGUID)); partitions->add_item_line(std::to_string(entry.StartingLBA)); partitions->add_item_line(std::to_string(entry.EndingLBA)); partitions->add_item_line(utils::format::hex(entry.Attributes)); partitions->new_line(); } std::cout << std::endl << "Partition table : " << gpt_entries.size() << " entries" << std::endl; partitions->render(std::cout); std::cout << std::endl; } else { std::cerr << "[!] Invalid or non-GPT partition table"; return 1; } } std::cout.flags(flag_backup); return 0; } } }
39.252874
156
0.619619
c3358
fc95d88c1e1227417ac11a00c7d9757a09a2e68b
1,390
cpp
C++
chapter 8 exervise 12/chapter 8 exervise 12/DLL.cpp
DanBeckerich/Cpp-Homework
dc215e2e233f1672c9a16b318600cc4fcf3d1162
[ "Apache-2.0" ]
null
null
null
chapter 8 exervise 12/chapter 8 exervise 12/DLL.cpp
DanBeckerich/Cpp-Homework
dc215e2e233f1672c9a16b318600cc4fcf3d1162
[ "Apache-2.0" ]
null
null
null
chapter 8 exervise 12/chapter 8 exervise 12/DLL.cpp
DanBeckerich/Cpp-Homework
dc215e2e233f1672c9a16b318600cc4fcf3d1162
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <assert.h> class DLL { private: //struct that defines our nodes. struct Node { int data; struct Node *prev; struct Node *next; }; //define the head. Node* head; int Count; public: //basic constructor for the doubley linked list DLL() { head = NULL; Count = 0; } void insert(int newdata) { // allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // put in the data new_node->data = newdata; // link the old list // off the new node new_node->next = head; // move the head to point // to the new node head = new_node; Count++; } void display() { struct Node* ptr; ptr = head; while (ptr != NULL) { std::cout << ptr->data << " "; ptr = ptr->next; } } void setEntry(int loc, int newValue) { struct Node* current = head; // the index of the // node we're currently // looking at int count = 0; while (current != NULL) { if (count == loc) { current->data = newValue; } count++; current = current->next; } } int retrieve(int loc) { struct Node* current = head; // the index of the // node we're currently // looking at int count = 0; while (current != NULL) { if (count == loc) return(current->data); count++; current = current->next; } } int getLength() { return Count; } };
15.274725
69
0.58705
DanBeckerich
fca2d673f1bd6033962931ca4fb614844d32c1cb
1,203
cpp
C++
Advanced/AA1112/AA1112/main.cpp
Eric-Ma-C/PAT-Advanced
ea8b46a780a04b46ab35ebd06c4bf19c3a664380
[ "MIT" ]
null
null
null
Advanced/AA1112/AA1112/main.cpp
Eric-Ma-C/PAT-Advanced
ea8b46a780a04b46ab35ebd06c4bf19c3a664380
[ "MIT" ]
null
null
null
Advanced/AA1112/AA1112/main.cpp
Eric-Ma-C/PAT-Advanced
ea8b46a780a04b46ab35ebd06c4bf19c3a664380
[ "MIT" ]
null
null
null
#include<stdio.h> #include<string.h> #include<vector> #include<map> #include<algorithm> using namespace std; //33min typedef struct item{ int id; char c; }item; map<char,item> m; bool cmp(item i1,item i2){ return i1.id<i2.id; } int main(){ int k; scanf("%d",&k); char c[1100]; scanf("%s",c); int len=strlen(c); int index=0; for(int i=0;i<len;){ int count=0; for(int j=i;j<len&&c[j]==c[i];j++) count++; bool broken=false; if(count%k==0)broken=true; if(m.find(c[i])==m.end()){ item it; it.c=c[i]; if(broken) it.id=index++; else it.id=-1; m[c[i]]=it; }else{ if(m[c[i]].id>0&&!broken){ m[c[i]].id=-1; } } i+=count; } char ac[1100]={0}; int tmp=0; for(int i=0;i<len;){ int count=0; for(int j=i;j<len&&c[j]==c[i];j++) count++; if(m[c[i]].id<0){ for(int j=0;j<count;j++) ac[tmp++]=c[i]; }else{ for(int j=0;j<count/k;j++) ac[tmp++]=c[i]; } i+=count; } vector<item> ans; for(auto it=m.begin();it!=m.end();it++){ if(it->second.id>=0) ans.push_back(it->second); } sort(ans.begin(),ans.end(),cmp); for(int i=0;i<ans.size();i++){ printf("%c",ans[i].c); } printf("\n%s",ac); getchar(); getchar(); return 0; }
16.256757
41
0.545303
Eric-Ma-C
fca5f7db5e1d0888f1f6cb018a432e69d0cbae84
4,161
cpp
C++
pwiz/analysis/peakdetect/FeatureDetectorPeakel.cpp
edyp-lab/pwiz-mzdb
d13ce17f4061596c7e3daf9cf5671167b5996831
[ "Apache-2.0" ]
11
2015-01-08T08:33:44.000Z
2019-07-12T06:14:54.000Z
pwiz/analysis/peakdetect/FeatureDetectorPeakel.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
61
2015-05-27T11:20:11.000Z
2019-12-20T15:06:21.000Z
pwiz/analysis/peakdetect/FeatureDetectorPeakel.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
4
2016-02-03T09:41:16.000Z
2021-08-01T18:42:36.000Z
// // $Id: FeatureDetectorPeakel.cpp 2051 2010-06-15 18:39:13Z chambm $ // // // Original author: Darren Kessner <darren@proteowizard.org> // // Copyright 2009 Center for Applied Molecular Medicine // University of Southern California, Los Angeles, CA // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #define PWIZ_SOURCE #include "FeatureDetectorPeakel.hpp" #include "pwiz/analysis/passive/MSDataCache.hpp" #include "pwiz/utility/misc/Std.hpp" namespace pwiz { namespace analysis { using namespace pwiz::msdata; shared_ptr<FeatureDetectorPeakel> FeatureDetectorPeakel::create(FeatureDetectorPeakel::Config config) { // note: config passed by value, allowing us to propagate the log pointers if (config.log) { config.peakFinder_SNR.log = config.log; config.peakelGrower_Proximity.log = config.log; config.peakelPicker_Basic.log = config.log; } shared_ptr<NoiseCalculator> noiseCalculator( new NoiseCalculator_2Pass(config.noiseCalculator_2Pass)); shared_ptr<PeakFinder> peakFinder(new PeakFinder_SNR(noiseCalculator, config.peakFinder_SNR)); shared_ptr<PeakFitter> peakFitter(new PeakFitter_Parabola(config.peakFitter_Parabola)); shared_ptr<PeakExtractor> peakExtractor(new PeakExtractor(peakFinder, peakFitter)); shared_ptr<PeakelGrower> peakelGrower(new PeakelGrower_Proximity(config.peakelGrower_Proximity)); shared_ptr<PeakelPicker> peakelPicker(new PeakelPicker_Basic(config.peakelPicker_Basic)); return shared_ptr<FeatureDetectorPeakel>( new FeatureDetectorPeakel(peakExtractor, peakelGrower, peakelPicker)); } FeatureDetectorPeakel::FeatureDetectorPeakel(shared_ptr<PeakExtractor> peakExtractor, shared_ptr<PeakelGrower> peakelGrower, shared_ptr<PeakelPicker> peakelPicker) : peakExtractor_(peakExtractor), peakelGrower_(peakelGrower), peakelPicker_(peakelPicker) { if (!peakExtractor.get() || !peakelGrower.get() || !peakelPicker.get()) throw runtime_error("[FeatureDetectorPeakel] Null pointer"); } namespace { struct SetPeakMetadata { const SpectrumInfo& spectrumInfo; SetPeakMetadata(const SpectrumInfo& _spectrumInfo) : spectrumInfo(_spectrumInfo) {} void operator()(Peak& peak) { peak.id = spectrumInfo.scanNumber; peak.retentionTime = spectrumInfo.retentionTime; } }; vector< vector<Peak> > extractPeaks(const MSData& msd, const PeakExtractor& peakExtractor) { MSDataCache msdCache; msdCache.open(msd); const size_t spectrumCount = msdCache.size(); vector< vector<Peak> > result(spectrumCount); for (size_t index=0; index<spectrumCount; index++) { const SpectrumInfo& spectrumInfo = msdCache.spectrumInfo(index, true); vector<Peak>& peaks = result[index]; peakExtractor.extractPeaks(spectrumInfo.data, peaks); for_each(peaks.begin(), peaks.end(), SetPeakMetadata(spectrumInfo)); /* TODO: logging if (os_) { *os_ << "index: " << index << endl; *os_ << "peaks: " << peaks.size() << endl; copy(peaks.begin(), peaks.end(), ostream_iterator<Peak>(*os_, "\n")); } */ } return result; } } // namespace void FeatureDetectorPeakel::detect(const MSData& msd, FeatureField& result) const { vector< vector<Peak> > peaks = extractPeaks(msd, *peakExtractor_); PeakelField peakelField; peakelGrower_->sowPeaks(peakelField, peaks); peakelPicker_->pick(peakelField, result); } } // namespace analysis } // namespace pwiz
30.372263
101
0.703677
edyp-lab
fca6eb53e4acc53c16111809cb195aa591b11030
11,164
hpp
C++
ThirdParty-mod/java2cpp/java/io/StringWriter.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/java/io/StringWriter.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/java/io/StringWriter.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.io.StringWriter ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_IO_STRINGWRITER_HPP_DECL #define J2CPP_JAVA_IO_STRINGWRITER_HPP_DECL namespace j2cpp { namespace java { namespace io { class Writer; } } } namespace j2cpp { namespace java { namespace lang { class StringBuffer; } } } namespace j2cpp { namespace java { namespace lang { class Appendable; } } } namespace j2cpp { namespace java { namespace lang { class CharSequence; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } #include <java/io/Writer.hpp> #include <java/lang/Appendable.hpp> #include <java/lang/CharSequence.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuffer.hpp> namespace j2cpp { namespace java { namespace io { class StringWriter; class StringWriter : public object<StringWriter> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) J2CPP_DECLARE_METHOD(13) J2CPP_DECLARE_METHOD(14) J2CPP_DECLARE_METHOD(15) J2CPP_DECLARE_METHOD(16) J2CPP_DECLARE_METHOD(17) J2CPP_DECLARE_METHOD(18) explicit StringWriter(jobject jobj) : object<StringWriter>(jobj) { } operator local_ref<java::io::Writer>() const; StringWriter(); StringWriter(jint); void close(); void flush(); local_ref< java::lang::StringBuffer > getBuffer(); local_ref< java::lang::String > toString(); void write(local_ref< array<jchar,1> > const&, jint, jint); void write(jint); void write(local_ref< java::lang::String > const&); void write(local_ref< java::lang::String > const&, jint, jint); local_ref< java::io::StringWriter > append(jchar); local_ref< java::io::StringWriter > append(local_ref< java::lang::CharSequence > const&); local_ref< java::io::StringWriter > append(local_ref< java::lang::CharSequence > const&, jint, jint); local_ref< java::io::Writer > append_1(local_ref< java::lang::CharSequence > const&, jint, jint); local_ref< java::io::Writer > append_1(local_ref< java::lang::CharSequence > const&); local_ref< java::io::Writer > append_1(jchar); local_ref< java::lang::Appendable > append_2(local_ref< java::lang::CharSequence > const&, jint, jint); local_ref< java::lang::Appendable > append_2(local_ref< java::lang::CharSequence > const&); local_ref< java::lang::Appendable > append_2(jchar); }; //class StringWriter } //namespace io } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_IO_STRINGWRITER_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_IO_STRINGWRITER_HPP_IMPL #define J2CPP_JAVA_IO_STRINGWRITER_HPP_IMPL namespace j2cpp { java::io::StringWriter::operator local_ref<java::io::Writer>() const { return local_ref<java::io::Writer>(get_jobject()); } java::io::StringWriter::StringWriter() : object<java::io::StringWriter>( call_new_object< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(0), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(0) >() ) { } java::io::StringWriter::StringWriter(jint a0) : object<java::io::StringWriter>( call_new_object< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(1), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(1) >(a0) ) { } void java::io::StringWriter::close() { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(2), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(2), void >(get_jobject()); } void java::io::StringWriter::flush() { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(3), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(3), void >(get_jobject()); } local_ref< java::lang::StringBuffer > java::io::StringWriter::getBuffer() { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(4), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(4), local_ref< java::lang::StringBuffer > >(get_jobject()); } local_ref< java::lang::String > java::io::StringWriter::toString() { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(5), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(5), local_ref< java::lang::String > >(get_jobject()); } void java::io::StringWriter::write(local_ref< array<jchar,1> > const &a0, jint a1, jint a2) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(6), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(6), void >(get_jobject(), a0, a1, a2); } void java::io::StringWriter::write(jint a0) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(7), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(7), void >(get_jobject(), a0); } void java::io::StringWriter::write(local_ref< java::lang::String > const &a0) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(8), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(8), void >(get_jobject(), a0); } void java::io::StringWriter::write(local_ref< java::lang::String > const &a0, jint a1, jint a2) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(9), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(9), void >(get_jobject(), a0, a1, a2); } local_ref< java::io::StringWriter > java::io::StringWriter::append(jchar a0) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(10), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(10), local_ref< java::io::StringWriter > >(get_jobject(), a0); } local_ref< java::io::StringWriter > java::io::StringWriter::append(local_ref< java::lang::CharSequence > const &a0) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(11), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(11), local_ref< java::io::StringWriter > >(get_jobject(), a0); } local_ref< java::io::StringWriter > java::io::StringWriter::append(local_ref< java::lang::CharSequence > const &a0, jint a1, jint a2) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(12), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(12), local_ref< java::io::StringWriter > >(get_jobject(), a0, a1, a2); } local_ref< java::io::Writer > java::io::StringWriter::append_1(local_ref< java::lang::CharSequence > const &a0, jint a1, jint a2) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(13), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(13), local_ref< java::io::Writer > >(get_jobject(), a0, a1, a2); } local_ref< java::io::Writer > java::io::StringWriter::append_1(local_ref< java::lang::CharSequence > const &a0) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(14), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(14), local_ref< java::io::Writer > >(get_jobject(), a0); } local_ref< java::io::Writer > java::io::StringWriter::append_1(jchar a0) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(15), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(15), local_ref< java::io::Writer > >(get_jobject(), a0); } local_ref< java::lang::Appendable > java::io::StringWriter::append_2(local_ref< java::lang::CharSequence > const &a0, jint a1, jint a2) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(16), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(16), local_ref< java::lang::Appendable > >(get_jobject(), a0, a1, a2); } local_ref< java::lang::Appendable > java::io::StringWriter::append_2(local_ref< java::lang::CharSequence > const &a0) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(17), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(17), local_ref< java::lang::Appendable > >(get_jobject(), a0); } local_ref< java::lang::Appendable > java::io::StringWriter::append_2(jchar a0) { return call_method< java::io::StringWriter::J2CPP_CLASS_NAME, java::io::StringWriter::J2CPP_METHOD_NAME(18), java::io::StringWriter::J2CPP_METHOD_SIGNATURE(18), local_ref< java::lang::Appendable > >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(java::io::StringWriter,"java/io/StringWriter") J2CPP_DEFINE_METHOD(java::io::StringWriter,0,"<init>","()V") J2CPP_DEFINE_METHOD(java::io::StringWriter,1,"<init>","(I)V") J2CPP_DEFINE_METHOD(java::io::StringWriter,2,"close","()V") J2CPP_DEFINE_METHOD(java::io::StringWriter,3,"flush","()V") J2CPP_DEFINE_METHOD(java::io::StringWriter,4,"getBuffer","()Ljava/lang/StringBuffer;") J2CPP_DEFINE_METHOD(java::io::StringWriter,5,"toString","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(java::io::StringWriter,6,"write","([CII)V") J2CPP_DEFINE_METHOD(java::io::StringWriter,7,"write","(I)V") J2CPP_DEFINE_METHOD(java::io::StringWriter,8,"write","(Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(java::io::StringWriter,9,"write","(Ljava/lang/String;II)V") J2CPP_DEFINE_METHOD(java::io::StringWriter,10,"append","(C)Ljava/io/StringWriter;") J2CPP_DEFINE_METHOD(java::io::StringWriter,11,"append","(Ljava/lang/CharSequence;)Ljava/io/StringWriter;") J2CPP_DEFINE_METHOD(java::io::StringWriter,12,"append","(Ljava/lang/CharSequence;II)Ljava/io/StringWriter;") J2CPP_DEFINE_METHOD(java::io::StringWriter,13,"append","(Ljava/lang/CharSequence;II)Ljava/io/Writer;") J2CPP_DEFINE_METHOD(java::io::StringWriter,14,"append","(Ljava/lang/CharSequence;)Ljava/io/Writer;") J2CPP_DEFINE_METHOD(java::io::StringWriter,15,"append","(C)Ljava/io/Writer;") J2CPP_DEFINE_METHOD(java::io::StringWriter,16,"append","(Ljava/lang/CharSequence;II)Ljava/lang/Appendable;") J2CPP_DEFINE_METHOD(java::io::StringWriter,17,"append","(Ljava/lang/CharSequence;)Ljava/lang/Appendable;") J2CPP_DEFINE_METHOD(java::io::StringWriter,18,"append","(C)Ljava/lang/Appendable;") } //namespace j2cpp #endif //J2CPP_JAVA_IO_STRINGWRITER_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
33.525526
136
0.705392
kakashidinho
fcaa3a2c93594ac917a81701873ba6034802252b
605
cpp
C++
HurdleRace.cpp
d3cod3monk78/hackerrank
8f3174306754d04d07b42d5c7a95ab32abf17fa1
[ "MIT" ]
null
null
null
HurdleRace.cpp
d3cod3monk78/hackerrank
8f3174306754d04d07b42d5c7a95ab32abf17fa1
[ "MIT" ]
null
null
null
HurdleRace.cpp
d3cod3monk78/hackerrank
8f3174306754d04d07b42d5c7a95ab32abf17fa1
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <vector> #include <cstdlib> #include <string> #include <string.h> using namespace std; int getDose(vector<int> arr , int k) { int n = (int)arr.size(); sort(arr.begin() , arr.end()); int dose = 0; if(arr[n-1] < k) { return 0; } for(int i = 0; i < n; i++) { if(arr[i] > k && dose < arr[i] - k) { dose = arr[i] - k; } } return dose; } int main(int argc, char const *argv[]) { int n; int k; cin >> n >> k; vector<int> arr(n); int temp; for(int i = 0; i < n; i++) { cin >> temp; arr[i] = temp; } cout << getDose(arr , k) << endl; return 0; }
15.921053
40
0.538843
d3cod3monk78
fcab4e92faabc89cc4c415859b2405ba992271b6
475
cpp
C++
src/customlabel.cpp
cvlabbonn/hand_2d_gt_viewer
457e0929fdeee740b8940a791299ed8541124a83
[ "MIT" ]
1
2018-03-16T22:40:16.000Z
2018-03-16T22:40:16.000Z
src/customlabel.cpp
cvlabbonn/hand_2d_gt_viewer
457e0929fdeee740b8940a791299ed8541124a83
[ "MIT" ]
null
null
null
src/customlabel.cpp
cvlabbonn/hand_2d_gt_viewer
457e0929fdeee740b8940a791299ed8541124a83
[ "MIT" ]
3
2015-10-05T22:48:40.000Z
2018-06-28T11:51:09.000Z
#include "customlabel.h" CustomLabel::CustomLabel( QWidget *parent ) : QLabel( parent ){ } void CustomLabel::mouseMoveEvent( QMouseEvent *ev ){ this->mouse_X = ev->x(); this->mouse_Y = ev->y(); emit mouse_position(); } void CustomLabel::mousePressEvent( QMouseEvent *ev ){ emit mouse_pressed(); } void CustomLabel::leaveEvent( QEvent * ){ emit mouse_left(); } void CustomLabel::mouseReleaseEvent( QMouseEvent * ){ emit mouse_release(); }
16.964286
53
0.671579
cvlabbonn
fcabd41951052a1b7b4bbac628f49aa173b2857c
2,901
cpp
C++
src/tests/merger_tests/handleInputs.cpp
danguenther/spfe-framework
f1f91330e136727edc12b8b0a07723a4059fa039
[ "MIT" ]
null
null
null
src/tests/merger_tests/handleInputs.cpp
danguenther/spfe-framework
f1f91330e136727edc12b8b0a07723a4059fa039
[ "MIT" ]
null
null
null
src/tests/merger_tests/handleInputs.cpp
danguenther/spfe-framework
f1f91330e136727edc12b8b0a07723a4059fa039
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <merger.h> #include <fstream> #define OUTPUT_FILE_HANDLE_INPUTS "src/tests/merger_tests/test_files/output.txt" using namespace std; /** * tests if the testInputs function writes the correct line in the file on the given parameters * @param current S if it is Server input, C if it is Client input * @param iss stream of the range of the input numbers * @param minValue smalles wire id of the input * @param maxValue highest wire id of the input * @param filename name of the file * @param counter current number of wires * @param wires mapping from the wires in the mering file to the wires in the ABY format file (updated in this function) */ void testInputs(string current, istringstream &iss, int minValue, int maxValue, string filename, uint32_t counter, map<uint32_t, uint32_t> &wires) { fstream file(filename, ios::out); handleInputs(current, iss, file, wires, counter); file.close(); fstream file2(filename, ios::in); string line; getNextLine(file2, line); istringstream is(line); string cur; is >> cur; EXPECT_EQ(cur, current); for (int i = minValue; i <= maxValue; i++) { EXPECT_EQ(wires[i], i); is >> cur; EXPECT_TRUE(isNumber(cur)); long lvalue = stoul(cur, nullptr, 10); auto value = static_cast<uint32_t>(lvalue); EXPECT_EQ(value, i); } file2.close(); } /* * Tests for handleInputs() function */ /* * test for only client inputs */ TEST (handleInputs, clientInput) { string current = "C"; istringstream iss("[ 0 4 ]"); map<uint32_t, uint32_t> wires; testInputs(current, iss, 0, 4, OUTPUT_FILE_HANDLE_INPUTS, 0, wires); } /* * test for only server inputs */ TEST (handleInputs, serverInput) { string current = "S"; istringstream iss("[ 0 12 ]"); map<uint32_t, uint32_t> wires; testInputs(current, iss, 0, 12, OUTPUT_FILE_HANDLE_INPUTS, 0, wires); } /* * tests for client and server inputs. Client's inputs are specified first */ TEST (handleInputs, clientAndServerInput) { string current = "C"; istringstream iss("[ 0 5 ]"); map<uint32_t, uint32_t> wires; testInputs(current, iss, 0, 5, OUTPUT_FILE_HANDLE_INPUTS, 0, wires); current = "S"; istringstream iss2("[ 6 18 ]"); testInputs(current, iss2, 6, 18, OUTPUT_FILE_HANDLE_INPUTS, 6, wires); } /* * tests for server and client inputs. Server's inputs are specified first */ TEST (handleInputs, serverAndClientInput) { string current = "S"; istringstream iss("[ 0 5 ]"); map<uint32_t, uint32_t> wires; testInputs(current, iss, 0, 5, OUTPUT_FILE_HANDLE_INPUTS, 0, wires); current = "C"; istringstream iss2("[ 6 18 ]"); testInputs(current, iss2, 6, 18, OUTPUT_FILE_HANDLE_INPUTS, 6, wires); }
29.30303
120
0.653223
danguenther
fcad23e944161f11f6431ff1e042c7a230780bf4
1,576
cc
C++
Boss2D/addon/webrtc-jumpingyang001_for_boss/audio/time_interval_unittest.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/addon/webrtc-jumpingyang001_for_boss/audio/time_interval_unittest.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/addon/webrtc-jumpingyang001_for_boss/audio/time_interval_unittest.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
/* * Copyright 2017 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include BOSS_WEBRTC_U_audio__time_interval_h //original-code:"audio/time_interval.h" #include BOSS_WEBRTC_U_api__units__time_delta_h //original-code:"api/units/time_delta.h" #include BOSS_WEBRTC_U_rtc_base__fakeclock_h //original-code:"rtc_base/fakeclock.h" #include "test/gtest.h" namespace webrtc { TEST(TimeIntervalTest, TimeInMs) { rtc::ScopedFakeClock fake_clock; TimeInterval interval; interval.Extend(); fake_clock.AdvanceTime(TimeDelta::ms(100)); interval.Extend(); EXPECT_EQ(interval.Length(), 100); } TEST(TimeIntervalTest, Empty) { TimeInterval interval; EXPECT_TRUE(interval.Empty()); interval.Extend(); EXPECT_FALSE(interval.Empty()); interval.Extend(200); EXPECT_FALSE(interval.Empty()); } TEST(TimeIntervalTest, MonotoneIncreasing) { const size_t point_count = 7; const int64_t interval_points[] = {3, 2, 5, 0, 4, 1, 6}; const int64_t interval_differences[] = {0, 1, 3, 5, 5, 5, 6}; TimeInterval interval; EXPECT_TRUE(interval.Empty()); for (size_t i = 0; i < point_count; ++i) { interval.Extend(interval_points[i]); EXPECT_EQ(interval_differences[i], interval.Length()); } } } // namespace webrtc
32.163265
88
0.73731
Yash-Wasalwar-07
fcafece3bb6298fe79c3e6612780ec3dd6896c44
6,687
cpp
C++
src/shell/main.cpp
georgebrock/task
00204e01912aeb9e39b94ac7ba16562fdd5b5f2c
[ "MIT" ]
1
2017-10-13T06:00:59.000Z
2017-10-13T06:00:59.000Z
src/shell/main.cpp
georgebrock/task
00204e01912aeb9e39b94ac7ba16562fdd5b5f2c
[ "MIT" ]
null
null
null
src/shell/main.cpp
georgebrock/task
00204e01912aeb9e39b94ac7ba16562fdd5b5f2c
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006-2014, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <algorithm> #include <fstream> #include <iostream> #include <cstring> #include <string.h> #include <text.h> #include <i18n.h> #include <Color.h> #include <Context.h> #include <Readline.h> Context context; #define MAX_ARGUMENTS 256 //////////////////////////////////////////////////////////////////////////////// int main (int argc, const char** argv) { bool read_from_file = false; if (argc > 2) { std::cout << STRING_SHELL_USAGE << "\n"; return -1; } else if (argc == 2) { if (!strcmp (argv[1], "--version")) { std::cout << VERSION << "\n"; return 0; } else if (!strcmp (argv[1], "--help")) { std::cout << STRING_SHELL_USAGE << "\n"; return 0; } else { // The user has given tasksh a task commands file to execute File input_file = File (argv[1]); if (!input_file.exists ()) { std::cout << STRING_SHELL_NO_FILE; std::cout << STRING_SHELL_USAGE << "\n"; return -1; } read_from_file = true; } } // If a file is given, read from it std::ifstream fin; if (read_from_file) { fin.open (argv[1]); } // Commands may be redirected too std::istream &in = read_from_file ? fin : std::cin; if (Readline::interactiveMode (in)) { // Begining initilaization if (context.initialize (0, NULL)) { return -1; } // Display some kind of welcome message. Color bold (Color::nocolor, Color::nocolor, false, true, false); std::cout << (context.color () ? bold.colorize (PACKAGE_STRING) : PACKAGE_STRING) << " shell\n\n" << STRING_CMD_SHELL_HELP1 << '\n' << STRING_CMD_SHELL_HELP2 << '\n' << STRING_CMD_SHELL_HELP3 << "\n\n"; } // Make a copy because context.clear will delete them. std::string permanent_overrides; std::vector <Arg>::iterator i; for (i = context.a3.begin (); i != context.a3.end (); ++i) { if (i->_category == Arg::cat_rc || i->_category == Arg::cat_override) { if (i != context.a3.begin ()) permanent_overrides += " "; permanent_overrides += i->_raw; } } std::string input; std::vector <std::string> quit_commands; quit_commands.push_back ("quit"); quit_commands.push_back ("exit"); quit_commands.push_back ("bye"); // The event loop. while (in) { std::string prompt (context.config.get ("shell.prompt") + " "); context.clear (); if (Readline::interactiveMode (in)) { input = Readline::gets (prompt); // if a string has nothing but whitespaces, ignore it if (input.find_first_not_of (" \t") == std::string::npos) continue; } else { std::getline (in, input); // if a string has nothing but whitespaces, ignore it if (input.find_first_not_of (" \t") == std::string::npos) continue; std::cout << prompt << input << '\n'; } try { #ifdef HAVE_WORDEXP std::string command = "task " + trim (input + permanent_overrides); // Escape special chars. size_t i = 0; while ((i = command.find_first_of ("$*?!|&;<>(){}~#@", i)) != std::string::npos) { command.insert(i, 1, '\\'); i += 2; } // Perform expansion. wordexp_t p; wordexp (command.c_str (), &p, 0); char** w = p.we_wordv; for (int i = 0; i < p.we_wordc; ++i) { if (std::find (quit_commands.begin (), quit_commands.end (), lowerCase (w[i])) != quit_commands.end ()) { context.clearMessages (); return 0; } } // External calls. if (strcmp (w[1], "xc") == 0 && p.we_wordc > 2) { std::string combined = ""; for (int i = 2; i < p.we_wordc - 1 ; ++i) { combined += std::string (w[i]) + " "; } combined += w[p.we_wordc - 1]; // last goes without a blank system (combined.c_str ()); // not checked continue; } int status = context.initialize (p.we_wordc, (const char**)p.we_wordv); wordfree(&p); #else std::string command = "task " + trim (input + permanent_overrides); int arg_count = 0; char* arg_vector[MAX_ARGUMENTS]; char* arg = strtok ((char*)command.c_str (), " "); while (arg && arg_count < MAX_ARGUMENTS) { arg_vector[arg_count++] = arg; arg = strtok (0, " "); } for (int i = 1; i < arg_count; ++i) { if (std::find (quit_commands.begin (), quit_commands.end (), lowerCase (arg_vector[i])) != quit_commands.end ()) { context.clearMessages (); return 0; } } int status = context.initialize (arg_count, (const char**) arg_vector); #endif if (status == 0) context.run (); } catch (const std::string& error) { std::cerr << error << '\n'; return -1; } catch (...) { std::cerr << STRING_UNKNOWN_ERROR << '\n'; return -2; } } return 0; } ////////////////////////////////////////////////////////////////////////////////
27.072874
86
0.546583
georgebrock
fcb022b5d9b1a46de510e6f14086153f87db9889
10,495
cpp
C++
vcf/VCFBuilder2/NewProjectDlg.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
vcf/VCFBuilder2/NewProjectDlg.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
vcf/VCFBuilder2/NewProjectDlg.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
//NewProjectDlg.h #include "ApplicationKit.h" #include "NewProjectDlg.h" #include "Label.h" #include "TextControl.h" #include "VCFBuilderUI.h" #include "TreeControl.h" #include "ListViewControl.h" #include "Label.h" #include "Light3DBorder.h" #include "DefaultTreeItem.h" #include "XMLParser.h" #include "DefaultListItem.h" using namespace VCF; using namespace VCFBuilder; NewProjectDlg::NewProjectDlg() { m_projectName = "Project1"; m_projectPath = VCFBuilderUIApplication::getVCFBuilderUI()->getDefaultProjectPath(); setHeight( 355 ); setWidth( 550 ); setCaption( "New VCF Builder Project" ); double midx = getWidth() / 2.0; double qtrx = getWidth() / 4.0; double left = 10; double right = getWidth() - 10; Label* projectsLabel = new Label(); projectsLabel->setBounds( &Rect( left, 5, midx, 28 ) ); projectsLabel->setCaption( "Project Types" ); add( projectsLabel ); projectsLabel->setAnchor( ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT ); m_projectTypesTree = new TreeControl(); m_projectTypesTree->setBounds( &Rect( left, 30, midx, 155 ) ); add( m_projectTypesTree ); m_projectTypesTree->setAnchor( ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT ); m_projectTypesTree->setVisible( true ); m_projectTypesTree->addMouseClickedHandler( new MouseEventHandler<NewProjectDlg>( this, onProjectsTypesTreeClicked, "ProjectsTypesTreeClickedHandler" ) ); Label* projectTemplatesLabel = new Label(); projectTemplatesLabel->setCaption( "Templates" ); projectTemplatesLabel->setBounds( &Rect( midx+ 5, 5, right, 28 ) ); add( projectTemplatesLabel ); projectTemplatesLabel->setAnchor( ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT ); m_projectTemplates = new ListViewControl(); m_projectTemplates->setBounds( &Rect( midx+ 5, 30, right, 155 ) ); add( m_projectTemplates ); m_projectTemplates->setAnchor( ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT ); m_projectTemplates->setVisible( true ); m_projectTemplates->addItemSelectionChangedHandler( new ItemEventHandler<NewProjectDlg>( this, onProjectTemplateItemSelected, "ProjectTemplateItemSelectedHandler" ) ); m_projectDesciption = new Label(); m_projectDesciption->setBounds( &Rect( left, 160, right, 185 ) ); add( m_projectDesciption ); m_projectDesciption->setAnchor( ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT ); Light3DBorder* border = new Light3DBorder(); border->setInverted( true ); m_projectDesciption->setBorder( border ); m_projectDesciption->setCaption( "Select a project template to create a new project" ); Label* label1 = new Label(); label1->setCaption( "Name:" ); double top = 190; label1->setBounds( &Rect(left, top, qtrx, top + label1->getPreferredHeight() ) ); label1->setAnchor( ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT ); add( label1 ); TextControl* projName = new TextControl(); projName->getTextModel()->setText( m_projectName ); projName->setBounds( &Rect(qtrx + 8, top, right, top + label1->getPreferredHeight() ) ); projName->setVisible( true ); projName->setToolTip( "Project Name" ); add( projName ); top += label1->getPreferredHeight() + 8; Label* label2 = new Label(); label2->setCaption( "Directory Path:" ); label2->setBounds( &Rect(left, top, qtrx, top + label2->getPreferredHeight() ) ); label2->setAnchor( ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT ); add( label2 ); TextControl* projPath = new TextControl(); projPath->getTextModel()->setText( m_projectPath ); projPath->setBounds( &Rect(qtrx + 8, top, right - 30, top + label2->getPreferredHeight() ) ); projPath->setVisible( true ); projPath->setToolTip( "Project Directory Path" ); add( projPath ); CommandButton* browseBtn = new CommandButton(); browseBtn->setBounds( &Rect(right - 25, top, right, top + label2->getPreferredHeight() ) ); browseBtn->setCaption( "..." ); browseBtn->setToolTip( "Browse for Project Directory Path" ); add( browseBtn ); top += label2->getPreferredHeight() + 8; TextModelEventHandler<NewProjectDlg>* tmHandler = new TextModelEventHandler<NewProjectDlg>( this,NewProjectDlg::onProjectPathTextChanged,"projPathHandler" ); projPath->getTextModel()->addTextModelChangedHandler( tmHandler ); tmHandler = new TextModelEventHandler<NewProjectDlg>( this,NewProjectDlg::onProjectNameTextChanged,"projNameHandler" ); projName->getTextModel()->addTextModelChangedHandler( tmHandler ); m_projectLocation = new Label(); m_projectLocation->setBounds( &Rect( left, top, right, top + m_projectLocation->getPreferredHeight() ) ); m_projectLocation->setAnchor( ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT ); add( m_projectLocation ); top += m_projectLocation->getPreferredHeight() + 8; populateProjectTypes(); CommandButton* okBtn = new CommandButton(); double x = right - (okBtn->getPreferredWidth() * 2 + 10); okBtn->setBounds( &Rect( x, top, x + okBtn->getPreferredWidth(), top + okBtn->getPreferredHeight() ) ); okBtn->setCaption( "OK" ); okBtn->setCommandType( BC_OK ); add( okBtn ); okBtn->setAnchor( ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT ); x += okBtn->getPreferredWidth() + 10; CommandButton* cancelBtn = new CommandButton(); cancelBtn->setBounds( &Rect(x, top, x + cancelBtn->getPreferredWidth(), top + cancelBtn->getPreferredHeight() ) ); cancelBtn->setCaption( "Cancel" ); cancelBtn->setCommandType( BC_CANCEL ); add( cancelBtn ); cancelBtn->setAnchor( ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT ); } NewProjectDlg::~NewProjectDlg() { std::vector<ProjectListing*>::iterator it = m_projectListings.begin(); while ( it != m_projectListings.end() ) { ProjectListing* pl = *it; delete pl; pl = NULL; it ++; } m_projectListings.clear(); } String NewProjectDlg::getSelectedTemplateProjectPath() { String result; Item* item = m_projectTemplates->getSelectedItem(); if ( NULL != item ) { ProjectData* data = (ProjectData*)item->getData(); if ( NULL != data ) { result = data->m_filename; } } return result; } void NewProjectDlg::onProjectTemplateItemSelected( ItemEvent* e ) { m_projectDesciption->setCaption( "Select a project template to create a new project" ); Item* item = m_projectTemplates->getSelectedItem(); ProjectData* data = (ProjectData*)item->getData(); if ( NULL != data ) { if ( false == data->m_tooltip.empty() ) { m_projectDesciption->setCaption( data->m_tooltip ); } } m_projectDesciption->repaint(); } void NewProjectDlg::onProjectsTypesTreeClicked( MouseEvent* e ) { m_projectDesciption->setCaption( "Select a project template to create a new project" ); m_projectDesciption->repaint(); ListModel* lm = m_projectTemplates->getListModel(); lm->empty(); TreeItem* foundItem = m_projectTypesTree->findItem( e->getPoint() ); if ( NULL != foundItem ) { ProjectListing* projectListing = (ProjectListing*)foundItem->getData(); if ( NULL != projectListing ) { std::vector<ProjectData>::iterator it = projectListing->m_projects.begin(); while ( it != projectListing->m_projects.end() ) { ProjectData& data = *it; DefaultListItem* project = new DefaultListItem(); project->setCaption( data.m_name ); project->setData( (void*)&data ); lm->addItem( project ); it ++; } } } } void NewProjectDlg::onProjectPathTextChanged( TextEvent* event ) { m_projectPath = event->getTextModel()->getText(); String tmp = m_projectPath; if ( tmp[tmp.size()-1] != '\\' ) { tmp += "\\"; } m_projectLocation->setCaption( "Project created at: " + tmp + m_projectName + ".vcp" ); m_projectLocation->repaint(); } void NewProjectDlg::onProjectNameTextChanged( TextEvent* event ) { m_projectName = event->getTextModel()->getText(); String tmp = m_projectPath; if ( tmp[tmp.size()-1] != '\\' ) { tmp += "\\"; } m_projectLocation->setCaption( "Project created at: " + tmp + m_projectName + ".vcp" ); m_projectLocation->repaint(); } void NewProjectDlg::readProjectDir( String directoryName, TreeItem* parentItem ) { TreeModel* projectTypesTreeModel = m_projectTypesTree->getTreeModel(); if ( directoryName[directoryName.size()-1] == '\\' ){ directoryName.erase( directoryName.size()-1, 1 ); } String directoryShortName; int lastPos = String::npos; int pos = directoryName.find( "\\" ); while ( String::npos != pos ) { lastPos = pos; pos = directoryName.find( "\\", pos +1 ); } if ( String::npos != lastPos ) { directoryShortName = directoryName.substr( lastPos+1, directoryName.size() ); } if ( directoryName[directoryName.size()-1] != '\\' ){ directoryName += "\\"; } XMLParser parser; FileStream fs( directoryName + directoryShortName + ".vcfdir", FS_READ ); parser.parse( &fs ); Enumerator<XMLNode*>* parsedNodes = parser.getParsedNodes(); ProjectListing* projectListing = new ProjectListing (); parentItem->setData( (void*)projectListing ); while ( parsedNodes->hasMoreElements() ) { XMLNode* node = parsedNodes->nextElement(); if ( node->getName() == "project" ) { XMLAttr* attr = node->getAttrByName( "name" ); if ( NULL != attr ) { ProjectData data; data.m_name = "Unknown Project"; data.m_filename = directoryName + attr->getValue(); attr = node->getAttrByName( "displayName" ); if ( NULL != attr ) { data.m_name = attr->getValue(); } attr = node->getAttrByName( "tooltip" ); if ( NULL != attr ) { data.m_tooltip = attr->getValue(); } projectListing->m_projects.push_back( data ); } } else if ( node->getName() == "projectdir" ) { XMLAttr* attr = node->getAttrByName( "name" ); if ( NULL != attr ) { DefaultTreeItem* projectDirItem = new DefaultTreeItem( attr->getValue() ); projectTypesTreeModel->addNodeItem( projectDirItem, parentItem ); readProjectDir( directoryName + attr->getValue(), projectDirItem ); } } } } void NewProjectDlg::populateProjectTypes() { TreeModel* projectTypesTreeModel = m_projectTypesTree->getTreeModel(); DefaultTreeItem* vcfProjects = new DefaultTreeItem("VCF Builder Projects"); projectTypesTreeModel->addNodeItem( vcfProjects, NULL ); String objectRepos = VCFBuilderUIApplication::getVCFBuilderUI()->getObjectRepositoryPath(); readProjectDir( objectRepos, vcfProjects ); }
33.212025
116
0.685088
tharindusathis
fcb0c2424abe2a7ef31787022ff38f6ff3883b01
585
cpp
C++
part2/les_2/main.cpp
noelleclement/cplusplusclass
74952e204a702611e2aa82d780cbaa67d4b98b0e
[ "MIT" ]
null
null
null
part2/les_2/main.cpp
noelleclement/cplusplusclass
74952e204a702611e2aa82d780cbaa67d4b98b0e
[ "MIT" ]
null
null
null
part2/les_2/main.cpp
noelleclement/cplusplusclass
74952e204a702611e2aa82d780cbaa67d4b98b0e
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ int const size = 10; int intArray[size]; int *array = intArray; for(int i=0; i<10*size; i+=10){ *(array++) = i; } for(int i=0; i<size; i++){ cout << intArray[i] << endl; } cout << *(intArray+2) << endl; int *array2 = new int[size]; for(int i=0; i<10*size; i+=size){ *(array2++) = i; //make a copy, this increments the pointer location, so not really an array anymore } delete [] (array2-size); //dont do this int *pI; *pI = 3; cout << *pI << endl; return 0; } //my g++ isnt really safe
14.268293
105
0.574359
noelleclement
fcb2af36e9fbc3010949d35ecbaf2a91c66f9b99
6,668
hpp
C++
Yannq/GroundState/SRMat.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/GroundState/SRMat.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/GroundState/SRMat.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <Eigen/Core> #include <Eigen/Dense> #include <Eigen/IterativeLinearSolvers> #include <tbb/tbb.h> #include "Utilities/Utility.hpp" #include "Observables/Energy.hpp" #include "./utils.hpp" namespace yannq { template<typename Machine, typename Hamiltonian> class SRMat; } //namespace yannq namespace Eigen { //namespace Eigen namespace internal { template<typename Machine, typename Hamiltonian> struct traits<yannq::SRMat<Machine, Hamiltonian> > : public Eigen::internal::traits<Eigen::SparseMatrix<typename Machine::Scalar> > {}; } }// namespace Eigen; namespace yannq { //! \addtogroup GroundState //! \ingroup GroundState //! This class that generates the quantum Fisher matrix for the stochastic reconfiguration (SR) method. template<typename Machine, typename Hamiltonian> class SRMat : public Eigen::EigenBase<SRMat<Machine, Hamiltonian> > { public: using Scalar = typename Machine::Scalar; using RealScalar = typename remove_complex<Scalar>::type; using Matrix = typename Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>; using Vector = typename Eigen::Matrix<Scalar, Eigen::Dynamic, 1>; using VectorConstRef = typename Eigen::Ref<const Vector>; using RealMatrix = typename Eigen::Matrix<RealScalar, Eigen::Dynamic, Eigen::Dynamic>; using RealVector = typename Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>; using StorageIndex = uint32_t; enum { ColsAtCompileTime = Eigen::Dynamic, MaxColsAtCompileTime = Eigen::Dynamic, IsRowMajor = false }; private: uint32_t n_; const Machine& qs_; const Hamiltonian& ham_; Energy<Scalar, Hamiltonian> energy_; RealScalar shift_; Matrix deltas_; Vector deltaMean_; Vector energyGrad_; Vector weights_; public: //! \param qs Machine that describes quantum states //! \param ham Hamiltonian for SR SRMat(const Machine& qs, const Hamiltonian& ham) : n_{qs.getN()}, qs_(qs), ham_(ham), energy_(ham) { } Eigen::Index rows() const { return qs_.getDim(); } Eigen::Index cols() const { return qs_.getDim(); } template<typename Rhs> Eigen::Product<SRMat<Machine, Hamiltonian>, Rhs, Eigen::AliasFreeProduct> operator*(const Eigen::MatrixBase<Rhs>& x) const { return Eigen::Product<SRMat<Machine, Hamiltonian>, Rhs, Eigen::AliasFreeProduct>(*this, x.derived()); } //! \param rs Sampling results obtained from samplers. template<class SamplingResult> void constructFromSamples(SamplingResult&& sr) { weights_.resize(0); int nsmp = sr.size(); constructDelta(qs_, sr, deltas_); constructObs(qs_, sr, energy_); deltaMean_ = deltas_.colwise().mean(); deltas_ = deltas_.rowwise() - deltaMean_.transpose(); energyGrad_ = deltas_.adjoint() * energy_.elocs(); energyGrad_ /= nsmp; } template<class SamplingResult> void constructFromWeightSamples(const Eigen::Ref<const RealVector>& weights, SamplingResult&& sr) { weights_ = weights; constructDelta(qs_, sr, deltas_); constructObsWeights(qs_, std::forward<SamplingResult>(sr), weights, energy_); deltaMean_ = weights.transpose()*deltas_; deltas_ = deltas_.rowwise() - deltaMean_.transpose(); energyGrad_ = deltas_.adjoint() * weights.asDiagonal() * energy_.elocs(); } void setShift(RealScalar shift) { shift_ = shift; } RealScalar getShift() const { return shift_; } //! return \f$\langle \nabla_{\theta} \psi_\theta(\sigma) \rangle\f$ const Vector& oloc() const& { return deltaMean_; } Vector oloc() && { return deltaMean_; } Matrix corrMat() { int nsmp = deltas_.rows(); if(weights_.size() == 0) return (deltas_.adjoint() * deltas_)/nsmp; else return (deltas_.adjoint() * weights_.asDiagonal() * deltas_); } RealScalar eloc() const { return std::real(energy_.eloc()); } Scalar elocVar() const { return std::real(energy_.elocVar()); } const Vector& energyGrad() const& { return energyGrad_; } Vector energyGrad() && { return energyGrad_; } Vector apply(const Vector& rhs) const { assert(rhs.size() == qs_.getDim()); Vector r = deltas_*rhs; Vector res; if(weights_.size() == 0) { r /= r.rows(); res = deltas_.adjoint()*r; } else { r.array() *= weights_.array(); res = deltas_.adjoint() * r; } return res + Scalar(shift_)*rhs; } /*! \brief Use conjugate gradient solover to solve the optimizing vector. * * We solve \f$ (S + \epsilon \mathbb{1})v = f \f$ where \f$ f \f$ is the gradient of the energy expectation values. * \param shift \f$ \epsilon \f$ that controls regularization * \param tol tolerance for CG solver */ Vector solveCG(RealScalar shift, RealScalar tol = 1e-4) { setShift(shift); Eigen::ConjugateGradient< SRMat<Machine, Hamiltonian>, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner> cg; cg.compute(*this); cg.setTolerance(tol); return cg.solve(energyGrad_); } /** * Solve S^{-1}vec using conjugate gradient method */ Vector solveCG(const VectorConstRef& vec, double shift, double tol = 1e-4) { setShift(shift); Eigen::ConjugateGradient< SRMat<Machine, Hamiltonian>, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner> cg; cg.compute(*this); cg.setTolerance(tol); return cg.solve(vec); } /*! \brief Solve the optimizing vector by solving the linear equation exactly.. * * We solve \f$ (S + \epsilon \mathbb{1})v = f \f$ where \f$ f \f$ is the gradient of the energy expectation values. * \param shift \f$ \epsilon \f$ that controls regularization */ Vector solveExact(RealScalar shift) { Matrix mat = corrMat(); mat += shift*Matrix::Identity(mat.rows(),mat.cols()); Eigen::LLT<Matrix> llt{mat}; return llt.solve(energyGrad_); } }; } //namespace yannq namespace Eigen { namespace internal { template<typename Rhs, typename Machine, typename Hamiltonian> struct generic_product_impl<yannq::SRMat<Machine, Hamiltonian>, Rhs, SparseShape, DenseShape, GemvProduct> // GEMV stands for matrix-vector : generic_product_impl_base<yannq::SRMat<Machine, Hamiltonian>, Rhs, generic_product_impl<yannq::SRMat<Machine, Hamiltonian>, Rhs> > { typedef typename Product<yannq::SRMat<Machine, Hamiltonian>, Rhs>::Scalar Scalar; template<typename Dest> static void scaleAndAddTo(Dest& dst, const yannq::SRMat<Machine, Hamiltonian>& lhs, const Rhs& rhs, const Scalar& alpha) { // This method should implement "dst += alpha * lhs * rhs" inplace, // however, for iterative solvers, alpha is always equal to 1, so let's not bother about it. assert(alpha==Scalar(1) && "scaling is not implemented"); EIGEN_ONLY_USED_FOR_DEBUG(alpha); dst += lhs.apply(rhs); } }; } //namespace internal } //namespace Eigen
25.257576
140
0.704109
cecri
fcb2b695528efaafd63353eb176ce88b6ae988f1
6,497
cpp
C++
VisualGraph/src/VisualGraph.cpp
IKholopov/StudyingStuff
8e5d9b98431fcc439d246d499963c33c729d5474
[ "MIT" ]
null
null
null
VisualGraph/src/VisualGraph.cpp
IKholopov/StudyingStuff
8e5d9b98431fcc439d246d499963c33c729d5474
[ "MIT" ]
null
null
null
VisualGraph/src/VisualGraph.cpp
IKholopov/StudyingStuff
8e5d9b98431fcc439d246d499963c33c729d5474
[ "MIT" ]
null
null
null
#include "VisualGraph.h" #include <QFileDialog> #include <fstream> VisualGraph::VisualGraph(GraphScene* scene, GraphArea* view):scene_(scene), view_(view) { idVertexCounter_ = 0; idEdgeCounter_ = 0; } VisualGraph::VisualGraph(GraphScene* scene, GraphArea* view, const std::vector<std::vector<unsigned long long> >& graphData):scene_(scene), view_(view) { unsigned long long size = 1; idVertexCounter_ = 0; idEdgeCounter_ = 0; for(auto e: graphData) { if(e.at(0) > size - 1) size = e.at(0) + 1; if(e.at(1) > size - 1) size = e.at(1) + 1; } for(unsigned long long i = 0; i < size; ++i) this->addNode(QPointF(30 + rand() % 400, 30 + rand() % 300)); for(unsigned long long i = 0; i < graphData.size(); ++i) this->addEdge(graphData.at(i).at(0),graphData.at(i).at(1), graphData.at(i).at(2)); } VisualGraph::VisualGraph(GraphScene* scene, GraphArea* view, std::string filename):scene_(scene), view_(view) { std::ifstream stream(filename); unsigned long long numberOfVertices, numberOfEdges, from, to, capacity; stream >> numberOfVertices; stream >> numberOfEdges; idVertexCounter_ = 0; idEdgeCounter_ = 0; for(unsigned long long i = 0; i < numberOfVertices; ++i) this->addNode(QPointF(30 + rand() % 400, 30 + rand() % 300)); for(unsigned long long i = 0; i < numberOfEdges; ++i) { stream >> from; stream >> to; stream >> capacity; this->addEdge(from - 1, to - 1, capacity); } } VisualGraph::~VisualGraph() { for(auto v: verticies_) delete v; for(auto e: edges_) delete e; } std::vector<std::vector<unsigned long long>> VisualGraph::clone() { std::vector<std::vector<unsigned long long>> list; list.resize(edges_.size()); for(unsigned long long i = 0; i < edges_.size(); ++i) { list[i].push_back(edges_[i]->getFrom()->getId()); list[i].push_back(edges_[i]->getTo()->getId()); list[i].push_back(edges_[i]->getCapacity()); } return list; } void VisualGraph::addNode(QPointF position) { Vertex* v = new Vertex(idVertexCounter_++, this, position); scene_->addItem(v); int offsetLimit = 30; v->setPos(QPointF(qMin(qMax(position.x(), scene_->sceneRect().left() + offsetLimit), scene_->sceneRect().right() - offsetLimit), qMin(qMax(position.y(), scene_->sceneRect().top() + offsetLimit), scene_->sceneRect().bottom() - offsetLimit))); verticies_.push_back(v); } void VisualGraph::addEdge(unsigned long long from, unsigned long long to, unsigned long long capacity) { Vertex* source = NULL; Vertex* dest = NULL; for(auto v: verticies_) if(v->getId() == from) { source = v; break; } for(auto v: verticies_) if(v->getId() == to) { dest = v; break; } VisualEdge* edge = new VisualEdge(scene_, idEdgeCounter_++, source, dest, capacity); source->addEdge(edge); dest->addEdge(edge); edges_.push_back(edge); } VisualEdge* VisualGraph::getEdge(unsigned long long id) { for(auto e: edges_) if(e->getId() == id) return e; return NULL; } Vertex* VisualGraph::getNode(unsigned long long id) { for(auto v: verticies_) if(v->getId() == id) return v; return NULL; } unsigned long long VisualGraph::getSize() { return verticies_.size(); } void VisualGraph::hideEdge(unsigned long long id) { getEdge(id)->hideEdge(); } void VisualGraph::displayEdge(unsigned long long id) { getEdge(id)->showEdge(); } void VisualGraph::hideNode(unsigned long long id) { getNode(id)->hideNode(); } void VisualGraph::displayNode(unsigned long long id) { getNode(id)->showNode(); } void VisualGraph::update() { for(auto v: verticies_) v->update(); for(auto e: edges_) e->update(); bool moved = false; for(auto v: verticies_) { v->updatePosition(); moved |= v->advance(); } nodeMoved_ = moved; } void VisualGraph::movedGraph() { nodeMoved_ = true; if(!view_->getTimerId()) view_->setTimerId(view_->startTimer(1000/100)); } void VisualGraph::disableGraph() { for(auto v: verticies_) { v->hideNode();//scene->addItem(v); } for(auto e: edges_) { e->hideEdge(); } } void VisualGraph::displayGraph() { this->active_ = true; for(auto v: verticies_) { if(v->getActive()) v->showNode();//scene->addItem(v); } for(auto e: edges_) { if(e->getActive()) e->showEdge(); } } void VisualGraph::hideGraph() { this->active_ = false; for(auto e: edges_) { e->getInfo()->hide(); e->hide(); } for(auto v: verticies_) { v->hide(); } } void VisualGraph::setEdgeDisplayType(int dt) { for(auto e: edges_) e->setDisplayType(dt); } void VisualGraph::setNodeDisplayType(LayeredOptions dt) { for(auto v: verticies_) v->setDisplayType(dt); } void VisualGraph::removeGraph() { for(auto e: edges_) { scene_->removeItem(e->getInfo()); scene_->removeItem(e); delete e; } for(auto v: verticies_) { scene_->removeItem(v); delete v; } verticies_.clear(); edges_.clear(); this->idEdgeCounter_ = 0; this->idVertexCounter_ = 0; } void VisualGraph::save() const { QString filename = QFileDialog::getSaveFileName(this->view_, "Save Graph As", "~/", "All Files (*);;Graph Files (*.gr)"); if(filename.isEmpty()) return; std::ofstream stream(filename.toStdString()); stream << verticies_.size(); stream << " "; stream << edges_.size(); stream << std::endl; for(auto e: edges_) { stream << e->getFrom()->getId() + 1; stream << " "; stream << e->getTo()->getId() + 1; stream << " "; stream << e->getCapacity(); stream << "\n"; } stream.close(); } bool VisualGraph::isActive() const { return active_; } bool VisualGraph::isMoved() const { return nodeMoved_; } unsigned long long VisualGraph::size() const { return verticies_.size(); } const std::vector<Vertex*>*VisualGraph::verticies() const { return &(this->verticies_); } GraphScene* VisualGraph::scene() { return scene_; } GraphArea* VisualGraph::view() { return view_; }
26.303644
134
0.590426
IKholopov
fcb7afc3dd48dec66ac6bd54cf2bfb8bdf601d19
4,311
hh
C++
FTPD.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
1
2017-09-14T13:31:16.000Z
2017-09-14T13:31:16.000Z
FTPD.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
null
null
null
FTPD.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
5
2015-04-11T02:59:06.000Z
2021-03-03T19:45:39.000Z
// // Copyright 2009-2017 M. Shulhan (ms@kilabit.info). All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef _LIBVOS_FTP_DAEMON_HH #define _LIBVOS_FTP_DAEMON_HH 1 #include <signal.h> #include "List.hh" #include "FTPD_client.hh" #include "FTPD_user.hh" namespace vos { #define FTPD_DEF_ADDRESS "0.0.0.0" #define FTPD_DEF_PORT 21 #define FTPD_DEF_PATH "./" enum _FTP_reply_msg_idx { CODE_150 = 0 , CODE_200 , CODE_211 , CODE_213 , CODE_215 , CODE_220 , CODE_221 , CODE_226 , CODE_227 , CODE_230 , CODE_250 , CODE_257 , CODE_331 , CODE_350 , CODE_421 , CODE_425 , CODE_450 , CODE_451 , CODE_501 , CODE_502 , CODE_503 , CODE_530 , CODE_550 , CODE_553 , N_REPLY_CODE }; extern const char* _FTP_reply_msg[N_REPLY_CODE]; enum _FTP_add_reply_msg { NODE_NOT_FOUND = 0 , NODE_IS_DIR , NODE_IS_NOT_DIR , TYPE_ALWAYS_BIN , MODE_ALWAYS_STREAM , STRU_ALWAYS_FILE , N_ADD_REPLY_MSG }; extern const char* _FTP_add_reply_msg[N_ADD_REPLY_MSG]; enum _FTP_auth_mode { AUTH_NOLOGIN = 0 , AUTH_LOGIN , N_FTP_MODE }; extern const char* _FTP_month[12]; /** * @class : FTPD * @attr : * - _running : flag for checking if server still running. * - _auth_mode : authentication mode, login or without login. * - _maxfd : maximum file descriptor, used by 'select()'. * - _path : the real path to directory that the server serve to * the networks. * - _dir : Dir object, contain cache of all files in 'path'. * - _fd_all : all file descriptor in the server, used by * 'select()'. * - _fd_read : the change descriptor, file descriptor that has the * change flag on after 'select()'. * - _clients : list of all server client. * - _users : list of all server account. * @desc : * A simple FTP server module for serving a file system to the network. */ class FTPD : public SockServer { public: FTPD(); ~FTPD(); int init(const char* address = FTPD_DEF_ADDRESS , const uint16_t port = FTPD_DEF_PORT , const char* path = FTPD_DEF_PATH , const int auth_mode = AUTH_NOLOGIN); int user_add(const char* name, const char* pass); int user_is_exist(const char* name, const char* pass = NULL); int add_command(const int code, const char* cmd_name , void (*callback)(FTPD*, FTPD_client*)); int set_path(const char* path); void set_default_callback(); int set_callback(const int code, void (*callback)(FTPD*, FTPD_client*)); int run(); void client_process(); int client_get_command(Socket* c, FTPD_cmd* ftp_cmd); void client_add(FTPD_client* c); void client_del(FTPD_client *c); int client_get_path(FTPD_client* c, int check_parm = 1); int client_get_parent_path(FTPD_client* c); int _running; int _auth_mode; int _maxfd; Buffer _path; Dir _dir; fd_set _fd_all; fd_set _fd_read; List _clients; List _users; List _cmds; static void on_cmd_USER(FTPD* s, FTPD_client* c); static void on_cmd_PASS(FTPD* s, FTPD_client* c); static void on_cmd_SYST(FTPD* s, FTPD_client* c); static void on_cmd_TYPE(FTPD* s, FTPD_client* c); static void on_cmd_MODE(FTPD* s, FTPD_client* c); static void on_cmd_STRU(FTPD* s, FTPD_client* c); static void on_cmd_FEAT(FTPD* s, FTPD_client* c); static void on_cmd_SIZE(FTPD* s, FTPD_client* c); static void on_cmd_MDTM(FTPD* s, FTPD_client* c); static void on_cmd_CWD(FTPD* s, FTPD_client* c); static void on_cmd_CDUP(FTPD* s, FTPD_client* c); static void on_cmd_PWD(FTPD* s, FTPD_client* c); static uint16_t GET_PASV_PORT(); static void on_cmd_PASV(FTPD* s, FTPD_client* c); static void on_cmd_LIST(FTPD* s, FTPD_client* c); static void on_cmd_NLST(FTPD* s, FTPD_client* c); static void on_cmd_RETR(FTPD* s, FTPD_client* c); static void on_cmd_STOR(FTPD* s, FTPD_client* c); static void on_cmd_DELE(FTPD* s, FTPD_client* c); static void on_cmd_RNFR(FTPD* s, FTPD_client* c); static void on_cmd_RNTO(FTPD* s, FTPD_client* c); static void on_cmd_RMD(FTPD* s, FTPD_client* c); static void on_cmd_MKD(FTPD* s, FTPD_client* c); static void on_cmd_QUIT(FTPD* s, FTPD_client* c); static void on_cmd_unknown(FTPD_client* c); static const char* __cname; private: FTPD(const FTPD&); void operator=(const FTPD&); }; } /* namespace::vos */ #endif // vi: ts=8 sw=8 tw=78:
26.127273
73
0.714683
shuLhan
fcb7c71ade8b066b2108e8ae17af9841a8b8c8ad
833
cpp
C++
src/global/UsbId.cpp
Governikus/AusweisApp2-Omapi
0d563e61cb385492cef96c2542d50a467e003259
[ "Apache-2.0" ]
1
2019-06-06T11:58:51.000Z
2019-06-06T11:58:51.000Z
src/global/UsbId.cpp
ckahlo/AusweisApp2-Omapi
5141b82599f9f11ae32ff7221b6de3b885e6e5f9
[ "Apache-2.0" ]
1
2022-01-28T11:08:59.000Z
2022-01-28T12:05:33.000Z
src/global/UsbId.cpp
ckahlo/AusweisApp2-Omapi
5141b82599f9f11ae32ff7221b6de3b885e6e5f9
[ "Apache-2.0" ]
3
2019-06-06T11:58:14.000Z
2021-11-15T23:32:04.000Z
/*! * \copyright Copyright (c) 2017-2019 Governikus GmbH & Co. KG, Germany */ #include "UsbId.h" #include <QDebug> #include <QDebugStateSaver> using namespace governikus; UsbId::UsbId(unsigned int pVendorId, unsigned int pProductId) : mVendorId(pVendorId) , mProductId(pProductId) { } unsigned int UsbId::getVendorId() const { return mVendorId; } unsigned int UsbId::getProductId() const { return mProductId; } bool UsbId::operator==(const UsbId& pOther) const { return mVendorId == pOther.mVendorId && mProductId == pOther.mProductId; } QDebug operator <<(QDebug pDbg, const UsbId& pUsbId) { QDebugStateSaver saver(pDbg); pDbg << "USB Vendor ID:" << QStringLiteral("0x%1").arg(pUsbId.getVendorId(), 0, 16) << "USB Product ID:" << QStringLiteral("0x%1").arg(pUsbId.getProductId(), 0, 16); return pDbg; }
18.511111
87
0.704682
Governikus
fcbd46787c604435feefb34f3e5d2956c2767a25
1,251
hpp
C++
samal_lib/include/samal_lib/Forward.hpp
VayuDev/samal
edb67289b7a1160f917be9bd44cd734f9d865460
[ "MIT" ]
2
2021-02-26T07:39:08.000Z
2021-03-30T21:13:47.000Z
samal_lib/include/samal_lib/Forward.hpp
VayuDev/samal
edb67289b7a1160f917be9bd44cd734f9d865460
[ "MIT" ]
null
null
null
samal_lib/include/samal_lib/Forward.hpp
VayuDev/samal
edb67289b7a1160f917be9bd44cd734f9d865460
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <map> #include <string> namespace samal { class ASTNode; class DeclarationNode; class ModuleRootNode; class IdentifierNode; class ExpressionNode; class FunctionDeclarationNode; class ScopeNode; class BinaryExpressionNode; class IfExpressionNode; class FunctionCallExpressionNode; class FunctionChainExpressionNode; class TupleCreationNode; class TupleAccessExpressionNode; class AssignmentExpression; class LambdaCreationNode; class StackInformationTree; class CallableDeclarationNode; class NativeFunctionDeclarationNode; class ListCreationNode; class ListPropertyAccessExpression; class StructCreationNode; class StructFieldAccessExpression; class TailCallSelfStatementNode; class MatchExpression; class MoveToHeapExpression; class MoveToStackExpression; class CallableDeclarationNode; struct Parameter; using StructField = Parameter; struct EnumField; class Compiler; class Datatype; class ExternalVMValue; class VM; class Stack; struct Program; class VariableSearcher; class Parser; struct VMParameters; enum class CheckTypeRecursively; struct UndeterminedIdentifierReplacementMapValue; using UndeterminedIdentifierReplacementMap = std::map<std::string, UndeterminedIdentifierReplacementMapValue>; }
22.339286
110
0.86251
VayuDev
fcbe6c7c24d5dca28252388360e2e6bfd8eccff0
3,013
cpp
C++
src/beanmachine/graph/global/proposer/hmc_proposer.cpp
horizon-blue/beanmachine-1
b13e4e3e28ffb860947eb8046863b0cabb581222
[ "MIT" ]
177
2021-12-12T14:19:05.000Z
2022-03-24T05:48:10.000Z
src/beanmachine/graph/global/proposer/hmc_proposer.cpp
horizon-blue/beanmachine-1
b13e4e3e28ffb860947eb8046863b0cabb581222
[ "MIT" ]
171
2021-12-11T06:12:05.000Z
2022-03-31T20:26:29.000Z
src/beanmachine/graph/global/proposer/hmc_proposer.cpp
horizon-blue/beanmachine-1
b13e4e3e28ffb860947eb8046863b0cabb581222
[ "MIT" ]
31
2021-12-11T06:27:19.000Z
2022-03-25T13:31:56.000Z
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "beanmachine/graph/global/proposer/hmc_proposer.h" namespace beanmachine { namespace graph { HmcProposer::HmcProposer( double path_length, double step_size, double optimal_acceptance_prob) : GlobalProposer(), step_size_adapter(StepSizeAdapter(optimal_acceptance_prob)) { this->path_length = path_length; this->step_size = step_size; } void HmcProposer::initialize( GlobalState& /*state*/, std::mt19937& /*gen*/, int num_warmup_samples) { if (num_warmup_samples > 0) { step_size_adapter.initialize(step_size); } } double HmcProposer::compute_kinetic_energy(Eigen::VectorXd momentum) { return 0.5 * momentum.dot(momentum); } Eigen::VectorXd HmcProposer::compute_potential_gradient(GlobalState& state) { state.update_backgrad(); Eigen::VectorXd grad1; state.get_flattened_unconstrained_grads(grad1); return -grad1; } void HmcProposer::warmup( double acceptance_prob, int iteration, int num_warmup_samples) { if (iteration < num_warmup_samples) { step_size = step_size_adapter.update_step_size(acceptance_prob); } else { step_size = step_size_adapter.finalize_step_size(); } } Eigen::VectorXd HmcProposer::initialize_momentum( Eigen::VectorXd position, std::mt19937& gen) { Eigen::VectorXd momentum(position.size()); std::normal_distribution<double> normal_dist(0.0, 1.0); for (int i = 0; i < momentum.size(); i++) { momentum[i] = normal_dist(gen); } return momentum; } double HmcProposer::propose(GlobalState& state, std::mt19937& gen) { Eigen::VectorXd position; state.get_flattened_unconstrained_values(position); state.update_log_prob(); double initial_U = -state.get_log_prob(); Eigen::VectorXd momentum(position.size()); std::normal_distribution<double> dist(0.0, 1.0); for (int i = 0; i < momentum.size(); i++) { momentum[i] = dist(gen); } double initial_K = compute_kinetic_energy(momentum); int num_steps = static_cast<int>(ceil(path_length / step_size)); // momentum half-step Eigen::VectorXd grad_U = compute_potential_gradient(state); momentum = momentum - step_size * grad_U / 2; for (int i = 0; i < num_steps; i++) { // position full-step position = position + step_size * momentum; // momentum step state.set_flattened_unconstrained_values(position); grad_U = compute_potential_gradient(state); if (i < num_steps - 1) { // full-step momentum = momentum - step_size * grad_U; } else { // half-step at the last iteration momentum = momentum - step_size * grad_U / 2; } } double final_K = compute_kinetic_energy(momentum); state.update_log_prob(); double final_U = -state.get_log_prob(); return initial_U - final_U + initial_K - final_K; } } // namespace graph } // namespace beanmachine
27.898148
77
0.708264
horizon-blue
fcc1c532c62e71f6a7d57621b2ea985d06e10195
503
cpp
C++
contest/yukicoder/117.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
contest/yukicoder/117.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
contest/yukicoder/117.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "math/combination.hpp" #include "math/mint.hpp" int main() { Combination<Mint> comb(2000000); int t(in); for (int i = 0; i < t; ++i) { char c(in); in.ignore(); int n(in); in.ignore(); int k(in); in.ignore(); switch (c) { case 'C': cout << comb.combination(n, k) << endl; break; case 'P': cout << comb.partial_permutation(n, k) << endl; break; case 'H': cout << comb.repetition(n, k) << endl; break; } } }
18.62963
53
0.506958
not522
fcc874951263609627306df7a973d71e2876548d
1,912
cpp
C++
commXel_app/src/ap/usb_to_dxl/usb_to_dxl.cpp
ghsecuritylab/XelNetwork_CommXel
a695133a0a622edaa8c73a2cfb2592642529e29f
[ "Apache-2.0" ]
2
2018-09-18T08:59:20.000Z
2018-09-28T06:10:40.000Z
commXel_app/src/ap/usb_to_dxl/usb_to_dxl.cpp
ghsecuritylab/XelNetwork_CommXel
a695133a0a622edaa8c73a2cfb2592642529e29f
[ "Apache-2.0" ]
null
null
null
commXel_app/src/ap/usb_to_dxl/usb_to_dxl.cpp
ghsecuritylab/XelNetwork_CommXel
a695133a0a622edaa8c73a2cfb2592642529e29f
[ "Apache-2.0" ]
1
2020-03-08T00:22:00.000Z
2020-03-08T00:22:00.000Z
/* * usb_to_dxl.cpp * * Created on: Sep 3, 2018 * Author: kei */ #include "usb_to_dxl.hpp" static uint8_t dxl_ch = _DEF_DXL1; static uint32_t tx_time_total = 0, rx_time_total = 0, tx_length_total = 0, rx_length_total = 0; void u2dInit(void) { dxlportInit(); dxlportOpen(dxl_ch, 57600); } static uint8_t tx_buffer[256]; void u2dRun(void) { uint32_t length, i; uint32_t pre_time; uint32_t usb_baud, dxl_baud; usb_baud = vcpGetBaud(); dxl_baud = dxlportGetBaud(dxl_ch); if(usb_baud != dxl_baud) { dxlportOpen(dxl_ch, usb_baud); tx_time_total = 0; tx_length_total = 0; rx_time_total = 0; rx_length_total = 0; } // USB to DXL length = vcpAvailable(); if( length > 0 ) { if(length > (uint32_t)256) { length = 256; } for(i=0; i<length; i++ ) { tx_buffer[i] = vcpRead(); } pre_time = micros(); dxlportWrite(dxl_ch, tx_buffer, length); tx_time_total += (micros() - pre_time); tx_length_total += length; } // DXL to USB length = dxlportAvailable(dxl_ch); if( length > 0 ) { if(length > (uint32_t)256) { length = 256; } pre_time = micros(); for(i=0; i<length; i++ ) { tx_buffer[i] = dxlportRead(dxl_ch); } rx_time_total += (micros() - pre_time); rx_length_total += length; vcpWrite(tx_buffer, length); } } void u2dPrintDebugMessages(uint32_t interval_ms) { static uint32_t pre_time = 0; static char buf[256]; if(millis() - pre_time >= interval_ms) { pre_time = millis(); sprintf(buf, "[<< TX] %u (ns/Byte)\r\n[>> RX] %u (ns/Byte)\r\n", (unsigned int)(tx_time_total*1000/tx_length_total), (unsigned int)(rx_time_total*1000/rx_length_total)); uartWrite(_DEF_UART3, (uint8_t*) buf, strlen(buf)); } }
19.12
113
0.584728
ghsecuritylab
fcca9422e1650a79a21ea1229a005305f60a50a6
1,112
cpp
C++
volume_I/acm_1010.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
volume_I/acm_1010.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
volume_I/acm_1010.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
// acm.timus.ru 1010. Discrete Function. #include <cstdio> char buffer[ (1 << 21) ]; char const * o ; void initRead() { unsigned n; n = fread(buffer, 1, sizeof(buffer ) - 2, stdin); buffer[n] = '\0'; o = buffer; } unsigned readInt() { unsigned u = 0; while(*o && *o <= 32)++o; while(*o >='0' && *o <= '9') u = (u<<3) + (u<<1) + *o++ -'0'; return u; } int readInt_s() { unsigned u = 0, s = 0; while(*o && *o <= 32) ++o; if (*o == '+') ++o; else if (*o == '-') ++o, s = ~0; while(*o>='0' && *o <='9') u = (u<<3) + (u<<1) + *o++ -'0'; return (u ^ s ) + !!s; } int solve() { unsigned n; long long a, b, c, d = -1000000000000000000LL; unsigned j = 0; initRead(); n = readInt(); a = readInt_s(); for(unsigned i = 1; i != n; ++i, a = b) { b = readInt_s(); c = (b-a); if ( c > d ) { j = i; d = c; } else if (-c > d) { j = i; d = -c; } } printf("%u %u\n",j,j+1); return 0; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r", stdin); freopen("output.txt","w",stdout); #endif solve(); return 0; }
13.39759
62
0.455036
raidenluikang
fccca28a5643b69e643a2666a14bf429f75792dc
408
cpp
C++
src/handler/response.cpp
open-chat-org/upload-service
0652a17528798a6c24f9c0a6a6ccb86bb6609ea7
[ "MIT" ]
null
null
null
src/handler/response.cpp
open-chat-org/upload-service
0652a17528798a6c24f9c0a6a6ccb86bb6609ea7
[ "MIT" ]
null
null
null
src/handler/response.cpp
open-chat-org/upload-service
0652a17528798a6c24f9c0a6a6ccb86bb6609ea7
[ "MIT" ]
null
null
null
#include "response.h" httpserver::string_response *response::failure_response() { return new httpserver::string_response( "{\"code\": 400, \"message\": \"FAILURE\"}", 400, "application/json"); } httpserver::string_response *response::successful_response() { return new httpserver::string_response( "{\"code\": 200, \"message\": \"SUCCESSFUL\"}", 200, "application/json"); }
31.384615
78
0.651961
open-chat-org
fccea00583839fe6a84127c3388f49196d29f110
55,637
cpp
C++
B2G/gecko/netwerk/protocol/http/nsHttpConnection.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/netwerk/protocol/http/nsHttpConnection.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/netwerk/protocol/http/nsHttpConnection.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* vim:set ts=4 sw=4 sts=4 et cin: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsHttpConnection.h" #include "nsHttpTransaction.h" #include "nsHttpRequestHead.h" #include "nsHttpResponseHead.h" #include "nsHttpHandler.h" #include "nsIOService.h" #include "nsISocketTransportService.h" #include "nsISocketTransport.h" #include "nsIServiceManager.h" #include "nsISSLSocketControl.h" #include "nsStringStream.h" #include "netCore.h" #include "nsNetCID.h" #include "nsProxyRelease.h" #include "prmem.h" #include "nsPreloadedStream.h" #include "ASpdySession.h" #include "mozilla/Telemetry.h" #include "nsISupportsPriority.h" #include "nsHttpPipeline.h" #ifdef DEBUG // defined by the socket transport service while active extern PRThread *gSocketThread; #endif static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID); using namespace mozilla::net; //----------------------------------------------------------------------------- // nsHttpConnection <public> //----------------------------------------------------------------------------- nsHttpConnection::nsHttpConnection() : mTransaction(nullptr) , mIdleTimeout(0) , mConsiderReusedAfterInterval(0) , mConsiderReusedAfterEpoch(0) , mCurrentBytesRead(0) , mMaxBytesRead(0) , mTotalBytesRead(0) , mTotalBytesWritten(0) , mKeepAlive(true) // assume to keep-alive by default , mKeepAliveMask(true) , mDontReuse(false) , mSupportsPipelining(false) // assume low-grade server , mIsReused(false) , mCompletedProxyConnect(false) , mLastTransactionExpectedNoContent(false) , mIdleMonitoring(false) , mProxyConnectInProgress(false) , mHttp1xTransactionCount(0) , mRemainingConnectionUses(0xffffffff) , mClassification(nsAHttpTransaction::CLASS_GENERAL) , mNPNComplete(false) , mSetupNPNCalled(false) , mUsingSpdyVersion(0) , mPriority(nsISupportsPriority::PRIORITY_NORMAL) , mReportedSpdy(false) , mEverUsedSpdy(false) { LOG(("Creating nsHttpConnection @%x\n", this)); // grab a reference to the handler to ensure that it doesn't go away. nsHttpHandler *handler = gHttpHandler; NS_ADDREF(handler); } nsHttpConnection::~nsHttpConnection() { LOG(("Destroying nsHttpConnection @%x\n", this)); if (mCallbacks) { nsIInterfaceRequestor *cbs = nullptr; mCallbacks.swap(cbs); NS_ProxyRelease(mCallbackTarget, cbs); } // release our reference to the handler nsHttpHandler *handler = gHttpHandler; NS_RELEASE(handler); if (!mEverUsedSpdy) { LOG(("nsHttpConnection %p performed %d HTTP/1.x transactions\n", this, mHttp1xTransactionCount)); mozilla::Telemetry::Accumulate( mozilla::Telemetry::HTTP_REQUEST_PER_CONN, mHttp1xTransactionCount); } if (mTotalBytesRead) { uint32_t totalKBRead = static_cast<uint32_t>(mTotalBytesRead >> 10); LOG(("nsHttpConnection %p read %dkb on connection spdy=%d\n", this, totalKBRead, mEverUsedSpdy)); mozilla::Telemetry::Accumulate( mEverUsedSpdy ? mozilla::Telemetry::SPDY_KBREAD_PER_CONN : mozilla::Telemetry::HTTP_KBREAD_PER_CONN, totalKBRead); } } nsresult nsHttpConnection::Init(nsHttpConnectionInfo *info, uint16_t maxHangTime, nsISocketTransport *transport, nsIAsyncInputStream *instream, nsIAsyncOutputStream *outstream, nsIInterfaceRequestor *callbacks, nsIEventTarget *callbackTarget, PRIntervalTime rtt) { NS_ABORT_IF_FALSE(transport && instream && outstream, "invalid socket information"); LOG(("nsHttpConnection::Init [this=%p " "transport=%p instream=%p outstream=%p rtt=%d]\n", this, transport, instream, outstream, PR_IntervalToMilliseconds(rtt))); NS_ENSURE_ARG_POINTER(info); NS_ENSURE_TRUE(!mConnInfo, NS_ERROR_ALREADY_INITIALIZED); mConnInfo = info; mLastReadTime = PR_IntervalNow(); mSupportsPipelining = gHttpHandler->ConnMgr()->SupportsPipelining(mConnInfo); mRtt = rtt; mMaxHangTime = PR_SecondsToInterval(maxHangTime); mSocketTransport = transport; mSocketIn = instream; mSocketOut = outstream; nsresult rv = mSocketTransport->SetEventSink(this, nullptr); NS_ENSURE_SUCCESS(rv, rv); mCallbacks = callbacks; mCallbackTarget = callbackTarget; rv = mSocketTransport->SetSecurityCallbacks(this); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } void nsHttpConnection::StartSpdy(uint8_t spdyVersion) { LOG(("nsHttpConnection::StartSpdy [this=%p]\n", this)); NS_ABORT_IF_FALSE(!mSpdySession, "mSpdySession should be null"); mUsingSpdyVersion = spdyVersion; mEverUsedSpdy = true; // Setting the connection as reused allows some transactions that fail // with NS_ERROR_NET_RESET to be restarted and SPDY uses that code // to handle clean rejections (such as those that arrived after // a server goaway was generated). mIsReused = true; // If mTransaction is a pipeline object it might represent // several requests. If so, we need to unpack that and // pack them all into a new spdy session. nsTArray<nsRefPtr<nsAHttpTransaction> > list; nsresult rv = mTransaction->TakeSubTransactions(list); if (rv == NS_ERROR_ALREADY_OPENED) { // Has the interface for TakeSubTransactions() changed? LOG(("TakeSubTranscations somehow called after " "nsAHttpTransaction began processing\n")); NS_ABORT_IF_FALSE(false, "TakeSubTranscations somehow called after " "nsAHttpTransaction began processing"); mTransaction->Close(NS_ERROR_ABORT); return; } if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) { // Has the interface for TakeSubTransactions() changed? LOG(("unexpected rv from nnsAHttpTransaction::TakeSubTransactions()")); NS_ABORT_IF_FALSE(false, "unexpected result from " "nsAHttpTransaction::TakeSubTransactions()"); mTransaction->Close(NS_ERROR_ABORT); return; } if (NS_FAILED(rv)) { // includes NS_ERROR_NOT_IMPLEMENTED NS_ABORT_IF_FALSE(list.IsEmpty(), "sub transaction list not empty"); // This is ok - treat mTransaction as a single real request. // Wrap the old http transaction into the new spdy session // as the first stream. mSpdySession = ASpdySession::NewSpdySession(spdyVersion, mTransaction, mSocketTransport, mPriority); LOG(("nsHttpConnection::StartSpdy moves single transaction %p " "into SpdySession %p\n", mTransaction.get(), mSpdySession.get())); } else { int32_t count = list.Length(); LOG(("nsHttpConnection::StartSpdy moving transaction list len=%d " "into SpdySession %p\n", count, mSpdySession.get())); if (!count) { mTransaction->Close(NS_ERROR_ABORT); return; } for (int32_t index = 0; index < count; ++index) { if (!mSpdySession) { mSpdySession = ASpdySession::NewSpdySession(spdyVersion, list[index], mSocketTransport, mPriority); } else { // AddStream() cannot fail if (!mSpdySession->AddStream(list[index], mPriority)) { NS_ABORT_IF_FALSE(false, "SpdySession::AddStream failed"); LOG(("SpdySession::AddStream failed\n")); mTransaction->Close(NS_ERROR_ABORT); return; } } } } mSupportsPipelining = false; // dont use http/1 pipelines with spdy mTransaction = mSpdySession; mIdleTimeout = gHttpHandler->SpdyTimeout(); } bool nsHttpConnection::EnsureNPNComplete() { // NPN is only used by SPDY right now. // // If for some reason the components to check on NPN aren't available, // this function will just return true to continue on and disable SPDY if (!mSocketTransport) { // this cannot happen NS_ABORT_IF_FALSE(false, "EnsureNPNComplete socket transport precondition"); mNPNComplete = true; return true; } if (mNPNComplete) return true; nsresult rv; nsCOMPtr<nsISupports> securityInfo; nsCOMPtr<nsISSLSocketControl> ssl; nsAutoCString negotiatedNPN; rv = mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo)); if (NS_FAILED(rv)) goto npnComplete; ssl = do_QueryInterface(securityInfo, &rv); if (NS_FAILED(rv)) goto npnComplete; rv = ssl->GetNegotiatedNPN(negotiatedNPN); if (rv == NS_ERROR_NOT_CONNECTED) { // By writing 0 bytes to the socket the SSL handshake machine is // pushed forward. uint32_t count = 0; rv = mSocketOut->Write("", 0, &count); if (NS_FAILED(rv) && rv != NS_BASE_STREAM_WOULD_BLOCK) goto npnComplete; return false; } if (NS_FAILED(rv)) goto npnComplete; LOG(("nsHttpConnection::EnsureNPNComplete %p negotiated to '%s'", this, negotiatedNPN.get())); uint8_t spdyVersion; rv = gHttpHandler->SpdyInfo()->GetNPNVersionIndex(negotiatedNPN, &spdyVersion); if (NS_SUCCEEDED(rv)) StartSpdy(spdyVersion); mozilla::Telemetry::Accumulate(mozilla::Telemetry::SPDY_NPN_CONNECT, mUsingSpdyVersion); npnComplete: LOG(("nsHttpConnection::EnsureNPNComplete setting complete to true")); mNPNComplete = true; return true; } // called on the socket thread nsresult nsHttpConnection::Activate(nsAHttpTransaction *trans, uint8_t caps, int32_t pri) { nsresult rv; NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread"); LOG(("nsHttpConnection::Activate [this=%x trans=%x caps=%x]\n", this, trans, caps)); mPriority = pri; if (mTransaction && mUsingSpdyVersion) return AddTransaction(trans, pri); NS_ENSURE_ARG_POINTER(trans); NS_ENSURE_TRUE(!mTransaction, NS_ERROR_IN_PROGRESS); // reset the read timers to wash away any idle time mLastReadTime = PR_IntervalNow(); // Update security callbacks nsCOMPtr<nsIInterfaceRequestor> callbacks; nsCOMPtr<nsIEventTarget> callbackTarget; trans->GetSecurityCallbacks(getter_AddRefs(callbacks), getter_AddRefs(callbackTarget)); if (callbacks != mCallbacks) { mCallbacks.swap(callbacks); if (callbacks) NS_ProxyRelease(mCallbackTarget, callbacks); mCallbackTarget = callbackTarget; } SetupNPN(caps); // only for spdy // take ownership of the transaction mTransaction = trans; NS_ABORT_IF_FALSE(!mIdleMonitoring, "Activating a connection with an Idle Monitor"); mIdleMonitoring = false; // set mKeepAlive according to what will be requested mKeepAliveMask = mKeepAlive = (caps & NS_HTTP_ALLOW_KEEPALIVE); // need to handle HTTP CONNECT tunnels if this is the first time if // we are tunneling through a proxy if (mConnInfo->UsingConnect() && !mCompletedProxyConnect) { rv = SetupProxyConnect(); if (NS_FAILED(rv)) goto failed_activation; mProxyConnectInProgress = true; } // Clear the per activation counter mCurrentBytesRead = 0; // The overflow state is not needed between activations mInputOverflow = nullptr; rv = OnOutputStreamReady(mSocketOut); failed_activation: if (NS_FAILED(rv)) { mTransaction = nullptr; } return rv; } void nsHttpConnection::SetupNPN(uint8_t caps) { if (mSetupNPNCalled) /* do only once */ return; mSetupNPNCalled = true; // Setup NPN Negotiation if necessary (only for SPDY) if (!mNPNComplete) { mNPNComplete = true; if (mConnInfo->UsingSSL()) { LOG(("nsHttpConnection::SetupNPN Setting up " "Next Protocol Negotiation")); nsCOMPtr<nsISupports> securityInfo; nsresult rv = mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo)); if (NS_FAILED(rv)) return; nsCOMPtr<nsISSLSocketControl> ssl = do_QueryInterface(securityInfo, &rv); if (NS_FAILED(rv)) return; nsTArray<nsCString> protocolArray; if (gHttpHandler->IsSpdyEnabled() && !(caps & NS_HTTP_DISALLOW_SPDY)) { LOG(("nsHttpConnection::SetupNPN Allow SPDY NPN selection")); if (gHttpHandler->SpdyInfo()->ProtocolEnabled(0)) protocolArray.AppendElement( gHttpHandler->SpdyInfo()->VersionString[0]); if (gHttpHandler->SpdyInfo()->ProtocolEnabled(1)) protocolArray.AppendElement( gHttpHandler->SpdyInfo()->VersionString[1]); } protocolArray.AppendElement(NS_LITERAL_CSTRING("http/1.1")); if (NS_SUCCEEDED(ssl->SetNPNList(protocolArray))) { LOG(("nsHttpConnection::Init Setting up SPDY Negotiation OK")); mNPNComplete = false; } } } } void nsHttpConnection::HandleAlternateProtocol(nsHttpResponseHead *responseHead) { // Look for the Alternate-Protocol header. Alternate-Protocol is // essentially a way to rediect future transactions from http to // spdy. // if (!gHttpHandler->IsSpdyEnabled() || mUsingSpdyVersion) return; const char *val = responseHead->PeekHeader(nsHttp::Alternate_Protocol); if (!val) return; // The spec allows redirections to any port, but due to concerns over // silently redirecting to stealth ports we only allow port 443 // // Alternate-Protocol: 5678:somethingelse, 443:npn-spdy/2 uint8_t alternateProtocolVersion; if (NS_SUCCEEDED(gHttpHandler->SpdyInfo()-> GetAlternateProtocolVersionIndex(val, &alternateProtocolVersion))) { LOG(("Connection %p Transaction %p found Alternate-Protocol " "header %s", this, mTransaction.get(), val)); gHttpHandler->ConnMgr()->ReportSpdyAlternateProtocol(this); } } nsresult nsHttpConnection::AddTransaction(nsAHttpTransaction *httpTransaction, int32_t priority) { LOG(("nsHttpConnection::AddTransaction for SPDY")); NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread"); NS_ABORT_IF_FALSE(mSpdySession && mUsingSpdyVersion, "AddTransaction to live http connection without spdy"); NS_ABORT_IF_FALSE(mTransaction, "AddTransaction to idle http connection"); if (!mSpdySession->AddStream(httpTransaction, priority)) { NS_ABORT_IF_FALSE(0, "AddStream should never fail due to" "RoomForMore() admission check"); return NS_ERROR_FAILURE; } ResumeSend(); return NS_OK; } void nsHttpConnection::Close(nsresult reason) { LOG(("nsHttpConnection::Close [this=%x reason=%x]\n", this, reason)); NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread"); if (NS_FAILED(reason)) { if (mIdleMonitoring) EndIdleMonitoring(); if (mSocketTransport) { mSocketTransport->SetSecurityCallbacks(nullptr); mSocketTransport->SetEventSink(nullptr, nullptr); mSocketTransport->Close(reason); if (mSocketOut) mSocketOut->AsyncWait(nullptr, 0, 0, nullptr); } mKeepAlive = false; } } // called on the socket thread nsresult nsHttpConnection::ProxyStartSSL() { LOG(("nsHttpConnection::ProxyStartSSL [this=%x]\n", this)); #ifdef DEBUG NS_PRECONDITION(PR_GetCurrentThread() == gSocketThread, "wrong thread"); #endif nsCOMPtr<nsISupports> securityInfo; nsresult rv = mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsISSLSocketControl> ssl = do_QueryInterface(securityInfo, &rv); if (NS_FAILED(rv)) return rv; return ssl->ProxyStartSSL(); } void nsHttpConnection::DontReuse() { mKeepAliveMask = false; mKeepAlive = false; mDontReuse = true; mIdleTimeout = 0; if (mSpdySession) mSpdySession->DontReuse(); } // Checked by the Connection Manager before scheduling a pipelined transaction bool nsHttpConnection::SupportsPipelining() { if (mTransaction && mTransaction->PipelineDepth() >= mRemainingConnectionUses) { LOG(("nsHttpConnection::SupportsPipelining this=%p deny pipeline " "because current depth %d exceeds max remaining uses %d\n", this, mTransaction->PipelineDepth(), mRemainingConnectionUses)); return false; } return mSupportsPipelining && IsKeepAlive() && !mDontReuse; } bool nsHttpConnection::CanReuse() { if (mDontReuse) return false; if ((mTransaction ? mTransaction->PipelineDepth() : 0) >= mRemainingConnectionUses) { return false; } bool canReuse; if (mSpdySession) canReuse = mSpdySession->CanReuse(); else canReuse = IsKeepAlive(); canReuse = canReuse && (IdleTime() < mIdleTimeout) && IsAlive(); // An idle persistent connection should not have data waiting to be read // before a request is sent. Data here is likely a 408 timeout response // which we would deal with later on through the restart logic, but that // path is more expensive than just closing the socket now. uint64_t dataSize; if (canReuse && mSocketIn && !mUsingSpdyVersion && mHttp1xTransactionCount && NS_SUCCEEDED(mSocketIn->Available(&dataSize)) && dataSize) { LOG(("nsHttpConnection::CanReuse %p %s" "Socket not reusable because read data pending (%llu) on it.\n", this, mConnInfo->Host(), dataSize)); canReuse = false; } return canReuse; } bool nsHttpConnection::CanDirectlyActivate() { // return true if a new transaction can be addded to ths connection at any // time through Activate(). In practice this means this is a healthy SPDY // connection with room for more concurrent streams. return UsingSpdy() && CanReuse() && mSpdySession && mSpdySession->RoomForMoreStreams(); } PRIntervalTime nsHttpConnection::IdleTime() { return mSpdySession ? mSpdySession->IdleTime() : (PR_IntervalNow() - mLastReadTime); } // returns the number of seconds left before the allowable idle period // expires, or 0 if the period has already expied. uint32_t nsHttpConnection::TimeToLive() { if (IdleTime() >= mIdleTimeout) return 0; uint32_t timeToLive = PR_IntervalToSeconds(mIdleTimeout - IdleTime()); // a positive amount of time can be rounded to 0. Because 0 is used // as the expiration signal, round all values from 0 to 1 up to 1. if (!timeToLive) timeToLive = 1; return timeToLive; } bool nsHttpConnection::IsAlive() { if (!mSocketTransport) return false; // SocketTransport::IsAlive can run the SSL state machine, so make sure // the NPN options are set before that happens. SetupNPN(0); bool alive; nsresult rv = mSocketTransport->IsAlive(&alive); if (NS_FAILED(rv)) alive = false; //#define TEST_RESTART_LOGIC #ifdef TEST_RESTART_LOGIC if (!alive) { LOG(("pretending socket is still alive to test restart logic\n")); alive = true; } #endif return alive; } bool nsHttpConnection::SupportsPipelining(nsHttpResponseHead *responseHead) { // SPDY supports infinite parallelism, so no need to pipeline. if (mUsingSpdyVersion) return false; // assuming connection is HTTP/1.1 with keep-alive enabled if (mConnInfo->UsingHttpProxy() && !mConnInfo->UsingConnect()) { // XXX check for bad proxy servers... return true; } // check for bad origin servers const char *val = responseHead->PeekHeader(nsHttp::Server); // If there is no server header we will assume it should not be banned // as facebook and some other prominent sites do this if (!val) return true; // The blacklist is indexed by the first character. All of these servers are // known to return their identifier as the first thing in the server string, // so we can do a leading match. static const char *bad_servers[26][6] = { { nullptr }, { nullptr }, { nullptr }, { nullptr }, // a - d { "EFAServer/", nullptr }, // e { nullptr }, { nullptr }, { nullptr }, { nullptr }, // f - i { nullptr }, { nullptr }, { nullptr }, // j - l { "Microsoft-IIS/4.", "Microsoft-IIS/5.", nullptr }, // m { "Netscape-Enterprise/3.", "Netscape-Enterprise/4.", "Netscape-Enterprise/5.", "Netscape-Enterprise/6.", nullptr }, // n { nullptr }, { nullptr }, { nullptr }, { nullptr }, // o - r { nullptr }, { nullptr }, { nullptr }, { nullptr }, // s - v { "WebLogic 3.", "WebLogic 4.","WebLogic 5.", "WebLogic 6.", "Winstone Servlet Engine v0.", nullptr }, // w { nullptr }, { nullptr }, { nullptr } // x - z }; int index = val[0] - 'A'; // the whole table begins with capital letters if ((index >= 0) && (index <= 25)) { for (int i = 0; bad_servers[index][i] != nullptr; i++) { if (!PL_strncmp (val, bad_servers[index][i], strlen (bad_servers[index][i]))) { LOG(("looks like this server does not support pipelining")); gHttpHandler->ConnMgr()->PipelineFeedbackInfo( mConnInfo, nsHttpConnectionMgr::RedBannedServer, this , 0); return false; } } } // ok, let's allow pipelining to this server return true; } //---------------------------------------------------------------------------- // nsHttpConnection::nsAHttpConnection compatible methods //---------------------------------------------------------------------------- nsresult nsHttpConnection::OnHeadersAvailable(nsAHttpTransaction *trans, nsHttpRequestHead *requestHead, nsHttpResponseHead *responseHead, bool *reset) { LOG(("nsHttpConnection::OnHeadersAvailable [this=%p trans=%p response-head=%p]\n", this, trans, responseHead)); NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread"); NS_ENSURE_ARG_POINTER(trans); NS_ASSERTION(responseHead, "No response head?"); // If the server issued an explicit timeout, then we need to close down the // socket transport. We pass an error code of NS_ERROR_NET_RESET to // trigger the transactions 'restart' mechanism. We tell it to reset its // response headers so that it will be ready to receive the new response. uint16_t responseStatus = responseHead->Status(); if (responseStatus == 408) { Close(NS_ERROR_NET_RESET); *reset = true; return NS_OK; } // we won't change our keep-alive policy unless the server has explicitly // told us to do so. // inspect the connection headers for keep-alive info provided the // transaction completed successfully. const char *val = responseHead->PeekHeader(nsHttp::Connection); if (!val) val = responseHead->PeekHeader(nsHttp::Proxy_Connection); // reset to default (the server may have changed since we last checked) mSupportsPipelining = false; if ((responseHead->Version() < NS_HTTP_VERSION_1_1) || (requestHead->Version() < NS_HTTP_VERSION_1_1)) { // HTTP/1.0 connections are by default NOT persistent if (val && !PL_strcasecmp(val, "keep-alive")) mKeepAlive = true; else mKeepAlive = false; // We need at least version 1.1 to use pipelines gHttpHandler->ConnMgr()->PipelineFeedbackInfo( mConnInfo, nsHttpConnectionMgr::RedVersionTooLow, this, 0); } else { // HTTP/1.1 connections are by default persistent if (val && !PL_strcasecmp(val, "close")) { mKeepAlive = false; // persistent connections are required for pipelining to work - if // this close was not pre-announced then generate the negative // BadExplicitClose feedback if (mRemainingConnectionUses > 1) gHttpHandler->ConnMgr()->PipelineFeedbackInfo( mConnInfo, nsHttpConnectionMgr::BadExplicitClose, this, 0); } else { mKeepAlive = true; // Do not support pipelining when we are establishing // an SSL tunnel though an HTTP proxy. Pipelining support // determination must be based on comunication with the // target server in this case. See bug 422016 for futher // details. if (!mProxyConnectStream) mSupportsPipelining = SupportsPipelining(responseHead); } } mKeepAliveMask = mKeepAlive; // Update the pipelining status in the connection info object // and also read it back. It is possible the ci status is // locked to false if pipelining has been banned on this ci due to // some kind of observed flaky behavior if (mSupportsPipelining) { // report the pipelining-compatible header to the connection manager // as positive feedback. This will undo 1 penalty point the host // may have accumulated in the past. gHttpHandler->ConnMgr()->PipelineFeedbackInfo( mConnInfo, nsHttpConnectionMgr::NeutralExpectedOK, this, 0); mSupportsPipelining = gHttpHandler->ConnMgr()->SupportsPipelining(mConnInfo); } // If this connection is reserved for revalidations and we are // receiving a document that failed revalidation then switch the // classification to general to avoid pipelining more revalidations behind // it. if (mClassification == nsAHttpTransaction::CLASS_REVALIDATION && responseStatus != 304) { mClassification = nsAHttpTransaction::CLASS_GENERAL; } // if this connection is persistent, then the server may send a "Keep-Alive" // header specifying the maximum number of times the connection can be // reused as well as the maximum amount of time the connection can be idle // before the server will close it. we ignore the max reuse count, because // a "keep-alive" connection is by definition capable of being reused, and // we only care about being able to reuse it once. if a timeout is not // specified then we use our advertized timeout value. bool foundKeepAliveMax = false; if (mKeepAlive) { val = responseHead->PeekHeader(nsHttp::Keep_Alive); if (!mUsingSpdyVersion) { const char *cp = PL_strcasestr(val, "timeout="); if (cp) mIdleTimeout = PR_SecondsToInterval((uint32_t) atoi(cp + 8)); else mIdleTimeout = gHttpHandler->IdleTimeout(); cp = PL_strcasestr(val, "max="); if (cp) { int val = atoi(cp + 4); if (val > 0) { foundKeepAliveMax = true; mRemainingConnectionUses = static_cast<uint32_t>(val); } } } else { mIdleTimeout = gHttpHandler->SpdyTimeout(); } LOG(("Connection can be reused [this=%p idle-timeout=%usec]\n", this, PR_IntervalToSeconds(mIdleTimeout))); } if (!foundKeepAliveMax && mRemainingConnectionUses && !mUsingSpdyVersion) --mRemainingConnectionUses; if (!mProxyConnectStream) HandleAlternateProtocol(responseHead); // If we're doing a proxy connect, we need to check whether or not // it was successful. If so, we have to reset the transaction and step-up // the socket connection if using SSL. Finally, we have to wake up the // socket write request. if (mProxyConnectStream) { NS_ABORT_IF_FALSE(!mUsingSpdyVersion, "SPDY NPN Complete while using proxy connect stream"); mProxyConnectStream = 0; if (responseStatus == 200) { LOG(("proxy CONNECT succeeded! ssl=%s\n", mConnInfo->UsingSSL() ? "true" :"false")); *reset = true; nsresult rv; if (mConnInfo->UsingSSL()) { rv = ProxyStartSSL(); if (NS_FAILED(rv)) // XXX need to handle this for real LOG(("ProxyStartSSL failed [rv=%x]\n", rv)); } mCompletedProxyConnect = true; mProxyConnectInProgress = false; rv = mSocketOut->AsyncWait(this, 0, 0, nullptr); // XXX what if this fails -- need to handle this error NS_ASSERTION(NS_SUCCEEDED(rv), "mSocketOut->AsyncWait failed"); } else { LOG(("proxy CONNECT failed! ssl=%s\n", mConnInfo->UsingSSL() ? "true" :"false")); mTransaction->SetProxyConnectFailed(); } } const char *upgradeReq = requestHead->PeekHeader(nsHttp::Upgrade); // Don't use persistent connection for Upgrade unless there's an auth failure: // some proxies expect to see auth response on persistent connection. if (upgradeReq && responseStatus != 401 && responseStatus != 407) { LOG(("HTTP Upgrade in play - disable keepalive\n")); DontReuse(); } if (responseStatus == 101) { const char *upgradeResp = responseHead->PeekHeader(nsHttp::Upgrade); if (!upgradeReq || !upgradeResp || !nsHttp::FindToken(upgradeResp, upgradeReq, HTTP_HEADER_VALUE_SEPS)) { LOG(("HTTP 101 Upgrade header mismatch req = %s, resp = %s\n", upgradeReq, upgradeResp)); Close(NS_ERROR_ABORT); } else { LOG(("HTTP Upgrade Response to %s\n", upgradeResp)); } } return NS_OK; } bool nsHttpConnection::IsReused() { if (mIsReused) return true; if (!mConsiderReusedAfterInterval) return false; // ReusedAfter allows a socket to be consider reused only after a certain // interval of time has passed return (PR_IntervalNow() - mConsiderReusedAfterEpoch) >= mConsiderReusedAfterInterval; } void nsHttpConnection::SetIsReusedAfter(uint32_t afterMilliseconds) { mConsiderReusedAfterEpoch = PR_IntervalNow(); mConsiderReusedAfterInterval = PR_MillisecondsToInterval(afterMilliseconds); } nsresult nsHttpConnection::TakeTransport(nsISocketTransport **aTransport, nsIAsyncInputStream **aInputStream, nsIAsyncOutputStream **aOutputStream) { if (mUsingSpdyVersion) return NS_ERROR_FAILURE; if (mTransaction && !mTransaction->IsDone()) return NS_ERROR_IN_PROGRESS; if (!(mSocketTransport && mSocketIn && mSocketOut)) return NS_ERROR_NOT_INITIALIZED; if (mInputOverflow) mSocketIn = mInputOverflow.forget(); NS_IF_ADDREF(*aTransport = mSocketTransport); NS_IF_ADDREF(*aInputStream = mSocketIn); NS_IF_ADDREF(*aOutputStream = mSocketOut); mSocketTransport->SetSecurityCallbacks(nullptr); mSocketTransport->SetEventSink(nullptr, nullptr); mSocketTransport = nullptr; mSocketIn = nullptr; mSocketOut = nullptr; return NS_OK; } void nsHttpConnection::ReadTimeoutTick(PRIntervalTime now) { NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread"); // make sure timer didn't tick before Activate() if (!mTransaction) return; // Spdy implements some timeout handling using the SPDY ping frame. if (mSpdySession) { mSpdySession->ReadTimeoutTick(now); return; } if (!gHttpHandler->GetPipelineRescheduleOnTimeout()) return; PRIntervalTime delta = now - mLastReadTime; // we replicate some of the checks both here and in OnSocketReadable() as // they will be discovered under different conditions. The ones here // will generally be discovered if we are totally hung and OSR does // not get called at all, however OSR discovers them with lower latency // if the issue is just very slow (but not stalled) reading. // // Right now we only take action if pipelining is involved, but this would // be the place to add general read timeout handling if it is desired. uint32_t pipelineDepth = mTransaction->PipelineDepth(); if (delta >= gHttpHandler->GetPipelineRescheduleTimeout() && pipelineDepth > 1) { // this just reschedules blocked transactions. no transaction // is aborted completely. LOG(("cancelling pipeline due to a %ums stall - depth %d\n", PR_IntervalToMilliseconds(delta), pipelineDepth)); nsHttpPipeline *pipeline = mTransaction->QueryPipeline(); NS_ABORT_IF_FALSE(pipeline, "pipelinedepth > 1 without pipeline"); // code this defensively for the moment and check for null in opt build // This will reschedule blocked members of the pipeline, but the // blocking transaction (i.e. response 0) will not be changed. if (pipeline) { pipeline->CancelPipeline(NS_ERROR_NET_TIMEOUT); LOG(("Rescheduling the head of line blocked members of a pipeline " "because reschedule-timeout idle interval exceeded")); } } if (delta < gHttpHandler->GetPipelineTimeout()) return; if (pipelineDepth <= 1 && !mTransaction->PipelinePosition()) return; // nothing has transpired on this pipelined socket for many // seconds. Call that a total stall and close the transaction. // There is a chance the transaction will be restarted again // depending on its state.. that will come back araound // without pipelining on, so this won't loop. LOG(("canceling transaction stalled for %ums on a pipeline " "of depth %d and scheduled originally at pos %d\n", PR_IntervalToMilliseconds(delta), pipelineDepth, mTransaction->PipelinePosition())); // This will also close the connection CloseTransaction(mTransaction, NS_ERROR_NET_TIMEOUT); } void nsHttpConnection::GetSecurityInfo(nsISupports **secinfo) { NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread"); if (mSocketTransport) { if (NS_FAILED(mSocketTransport->GetSecurityInfo(secinfo))) *secinfo = nullptr; } } nsresult nsHttpConnection::PushBack(const char *data, uint32_t length) { LOG(("nsHttpConnection::PushBack [this=%p, length=%d]\n", this, length)); if (mInputOverflow) { NS_ERROR("nsHttpConnection::PushBack only one buffer supported"); return NS_ERROR_UNEXPECTED; } mInputOverflow = new nsPreloadedStream(mSocketIn, data, length); return NS_OK; } nsresult nsHttpConnection::ResumeSend() { LOG(("nsHttpConnection::ResumeSend [this=%p]\n", this)); NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread"); if (mSocketOut) return mSocketOut->AsyncWait(this, 0, 0, nullptr); NS_NOTREACHED("no socket output stream"); return NS_ERROR_UNEXPECTED; } nsresult nsHttpConnection::ResumeRecv() { LOG(("nsHttpConnection::ResumeRecv [this=%p]\n", this)); NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread"); // the mLastReadTime timestamp is used for finding slowish readers // and can be pretty sensitive. For that reason we actually reset it // when we ask to read (resume recv()) so that when we get called back // with actual read data in OnSocketReadable() we are only measuring // the latency between those two acts and not all the processing that // may get done before the ResumeRecv() call mLastReadTime = PR_IntervalNow(); if (mSocketIn) return mSocketIn->AsyncWait(this, 0, 0, nullptr); NS_NOTREACHED("no socket input stream"); return NS_ERROR_UNEXPECTED; } void nsHttpConnection::BeginIdleMonitoring() { LOG(("nsHttpConnection::BeginIdleMonitoring [this=%p]\n", this)); NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread"); NS_ABORT_IF_FALSE(!mTransaction, "BeginIdleMonitoring() while active"); NS_ABORT_IF_FALSE(!mUsingSpdyVersion, "Idle monitoring of spdy not allowed"); LOG(("Entering Idle Monitoring Mode [this=%p]", this)); mIdleMonitoring = true; if (mSocketIn) mSocketIn->AsyncWait(this, 0, 0, nullptr); } void nsHttpConnection::EndIdleMonitoring() { LOG(("nsHttpConnection::EndIdleMonitoring [this=%p]\n", this)); NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread"); NS_ABORT_IF_FALSE(!mTransaction, "EndIdleMonitoring() while active"); if (mIdleMonitoring) { LOG(("Leaving Idle Monitoring Mode [this=%p]", this)); mIdleMonitoring = false; if (mSocketIn) mSocketIn->AsyncWait(nullptr, 0, 0, nullptr); } } //----------------------------------------------------------------------------- // nsHttpConnection <private> //----------------------------------------------------------------------------- void nsHttpConnection::CloseTransaction(nsAHttpTransaction *trans, nsresult reason) { LOG(("nsHttpConnection::CloseTransaction[this=%x trans=%x reason=%x]\n", this, trans, reason)); NS_ASSERTION(trans == mTransaction, "wrong transaction"); NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread"); if (mCurrentBytesRead > mMaxBytesRead) mMaxBytesRead = mCurrentBytesRead; // mask this error code because its not a real error. if (reason == NS_BASE_STREAM_CLOSED) reason = NS_OK; if (mUsingSpdyVersion) { DontReuse(); // if !mSpdySession then mUsingSpdyVersion must be false for canreuse() mUsingSpdyVersion = 0; mSpdySession = nullptr; } if (mTransaction) { mHttp1xTransactionCount += mTransaction->Http1xTransactionCount(); mTransaction->Close(reason); mTransaction = nullptr; } if (mCallbacks) { nsIInterfaceRequestor *cbs = nullptr; mCallbacks.swap(cbs); NS_ProxyRelease(mCallbackTarget, cbs); } if (NS_FAILED(reason)) Close(reason); // flag the connection as reused here for convenience sake. certainly // it might be going away instead ;-) mIsReused = true; } NS_METHOD nsHttpConnection::ReadFromStream(nsIInputStream *input, void *closure, const char *buf, uint32_t offset, uint32_t count, uint32_t *countRead) { // thunk for nsIInputStream instance nsHttpConnection *conn = (nsHttpConnection *) closure; return conn->OnReadSegment(buf, count, countRead); } nsresult nsHttpConnection::OnReadSegment(const char *buf, uint32_t count, uint32_t *countRead) { if (count == 0) { // some ReadSegments implementations will erroneously call the writer // to consume 0 bytes worth of data. we must protect against this case // or else we'd end up closing the socket prematurely. NS_ERROR("bad ReadSegments implementation"); return NS_ERROR_FAILURE; // stop iterating } nsresult rv = mSocketOut->Write(buf, count, countRead); if (NS_FAILED(rv)) mSocketOutCondition = rv; else if (*countRead == 0) mSocketOutCondition = NS_BASE_STREAM_CLOSED; else { mSocketOutCondition = NS_OK; // reset condition if (!mProxyConnectInProgress) mTotalBytesWritten += *countRead; } return mSocketOutCondition; } nsresult nsHttpConnection::OnSocketWritable() { LOG(("nsHttpConnection::OnSocketWritable [this=%p] host=%s\n", this, mConnInfo->Host())); nsresult rv; uint32_t n; bool again = true; do { mSocketOutCondition = NS_OK; // If we're doing a proxy connect, then we need to bypass calling into // the transaction. // // NOTE: this code path can't be shared since the transaction doesn't // implement nsIInputStream. doing so is not worth the added cost of // extra indirections during normal reading. // if (mProxyConnectStream) { LOG((" writing CONNECT request stream\n")); rv = mProxyConnectStream->ReadSegments(ReadFromStream, this, nsIOService::gDefaultSegmentSize, &n); } else if (!EnsureNPNComplete()) { // When SPDY is disabled this branch is not executed because Activate() // sets mNPNComplete to true in that case. // We are ready to proceed with SSL but the handshake is not done. // When using NPN to negotiate between HTTPS and SPDY, we need to // see the results of the handshake to know what bytes to send, so // we cannot proceed with the request headers. rv = NS_OK; mSocketOutCondition = NS_BASE_STREAM_WOULD_BLOCK; n = 0; } else { if (!mReportedSpdy) { mReportedSpdy = true; gHttpHandler->ConnMgr()->ReportSpdyConnection(this, mUsingSpdyVersion); } LOG((" writing transaction request stream\n")); mProxyConnectInProgress = false; rv = mTransaction->ReadSegments(this, nsIOService::gDefaultSegmentSize, &n); } LOG((" ReadSegments returned [rv=%x read=%u sock-cond=%x]\n", rv, n, mSocketOutCondition)); // XXX some streams return NS_BASE_STREAM_CLOSED to indicate EOF. if (rv == NS_BASE_STREAM_CLOSED && !mTransaction->IsDone()) { rv = NS_OK; n = 0; } if (NS_FAILED(rv)) { // if the transaction didn't want to write any more data, then // wait for the transaction to call ResumeSend. if (rv == NS_BASE_STREAM_WOULD_BLOCK) rv = NS_OK; again = false; } else if (NS_FAILED(mSocketOutCondition)) { if (mSocketOutCondition == NS_BASE_STREAM_WOULD_BLOCK) rv = mSocketOut->AsyncWait(this, 0, 0, nullptr); // continue writing else rv = mSocketOutCondition; again = false; } else if (n == 0) { // // at this point we've written out the entire transaction, and now we // must wait for the server's response. we manufacture a status message // here to reflect the fact that we are waiting. this message will be // trumped (overwritten) if the server responds quickly. // mTransaction->OnTransportStatus(mSocketTransport, NS_NET_STATUS_WAITING_FOR, LL_ZERO); rv = ResumeRecv(); // start reading again = false; } // write more to the socket until error or end-of-request... } while (again); return rv; } nsresult nsHttpConnection::OnWriteSegment(char *buf, uint32_t count, uint32_t *countWritten) { if (count == 0) { // some WriteSegments implementations will erroneously call the reader // to provide 0 bytes worth of data. we must protect against this case // or else we'd end up closing the socket prematurely. NS_ERROR("bad WriteSegments implementation"); return NS_ERROR_FAILURE; // stop iterating } nsresult rv = mSocketIn->Read(buf, count, countWritten); if (NS_FAILED(rv)) mSocketInCondition = rv; else if (*countWritten == 0) mSocketInCondition = NS_BASE_STREAM_CLOSED; else mSocketInCondition = NS_OK; // reset condition return mSocketInCondition; } nsresult nsHttpConnection::OnSocketReadable() { LOG(("nsHttpConnection::OnSocketReadable [this=%x]\n", this)); PRIntervalTime now = PR_IntervalNow(); PRIntervalTime delta = now - mLastReadTime; if (mKeepAliveMask && (delta >= mMaxHangTime)) { LOG(("max hang time exceeded!\n")); // give the handler a chance to create a new persistent connection to // this host if we've been busy for too long. mKeepAliveMask = false; gHttpHandler->ProcessPendingQ(mConnInfo); } // Look for data being sent in bursts with large pauses. If the pauses // are caused by server bottlenecks such as think-time, disk i/o, or // cpu exhaustion (as opposed to network latency) then we generate negative // pipelining feedback to prevent head of line problems // Reduce the estimate of the time since last read by up to 1 RTT to // accommodate exhausted sender TCP congestion windows or minor I/O delays. if (delta > mRtt) delta -= mRtt; else delta = 0; static const PRIntervalTime k400ms = PR_MillisecondsToInterval(400); if (delta >= (mRtt + gHttpHandler->GetPipelineRescheduleTimeout())) { LOG(("Read delta ms of %u causing slow read major " "event and pipeline cancellation", PR_IntervalToMilliseconds(delta))); gHttpHandler->ConnMgr()->PipelineFeedbackInfo( mConnInfo, nsHttpConnectionMgr::BadSlowReadMajor, this, 0); if (gHttpHandler->GetPipelineRescheduleOnTimeout() && mTransaction->PipelineDepth() > 1) { nsHttpPipeline *pipeline = mTransaction->QueryPipeline(); NS_ABORT_IF_FALSE(pipeline, "pipelinedepth > 1 without pipeline"); // code this defensively for the moment and check for null // This will reschedule blocked members of the pipeline, but the // blocking transaction (i.e. response 0) will not be changed. if (pipeline) { pipeline->CancelPipeline(NS_ERROR_NET_TIMEOUT); LOG(("Rescheduling the head of line blocked members of a " "pipeline because reschedule-timeout idle interval " "exceeded")); } } } else if (delta > k400ms) { gHttpHandler->ConnMgr()->PipelineFeedbackInfo( mConnInfo, nsHttpConnectionMgr::BadSlowReadMinor, this, 0); } mLastReadTime = now; nsresult rv; uint32_t n; bool again = true; do { if (!mProxyConnectInProgress && !mNPNComplete) { // Unless we are setting up a tunnel via CONNECT, prevent reading // from the socket until the results of NPN // negotiation are known (which is determined from the write path). // If the server speaks SPDY it is likely the readable data here is // a spdy settings frame and without NPN it would be misinterpreted // as HTTP/* LOG(("nsHttpConnection::OnSocketReadable %p return due to inactive " "tunnel setup but incomplete NPN state\n", this)); rv = NS_OK; break; } rv = mTransaction->WriteSegments(this, nsIOService::gDefaultSegmentSize, &n); if (NS_FAILED(rv)) { // if the transaction didn't want to take any more data, then // wait for the transaction to call ResumeRecv. if (rv == NS_BASE_STREAM_WOULD_BLOCK) rv = NS_OK; again = false; } else { mCurrentBytesRead += n; mTotalBytesRead += n; if (NS_FAILED(mSocketInCondition)) { // continue waiting for the socket if necessary... if (mSocketInCondition == NS_BASE_STREAM_WOULD_BLOCK) rv = ResumeRecv(); else rv = mSocketInCondition; again = false; } } // read more from the socket until error... } while (again); return rv; } nsresult nsHttpConnection::SetupProxyConnect() { const char *val; LOG(("nsHttpConnection::SetupProxyConnect [this=%x]\n", this)); NS_ENSURE_TRUE(!mProxyConnectStream, NS_ERROR_ALREADY_INITIALIZED); NS_ABORT_IF_FALSE(!mUsingSpdyVersion, "SPDY NPN Complete while using proxy connect stream"); nsAutoCString buf; nsresult rv = nsHttpHandler::GenerateHostPort( nsDependentCString(mConnInfo->Host()), mConnInfo->Port(), buf); if (NS_FAILED(rv)) return rv; // CONNECT host:port HTTP/1.1 nsHttpRequestHead request; request.SetMethod(nsHttp::Connect); request.SetVersion(gHttpHandler->HttpVersion()); request.SetRequestURI(buf); request.SetHeader(nsHttp::User_Agent, gHttpHandler->UserAgent()); val = mTransaction->RequestHead()->PeekHeader(nsHttp::Host); if (val) { // all HTTP/1.1 requests must include a Host header (even though it // may seem redundant in this case; see bug 82388). request.SetHeader(nsHttp::Host, nsDependentCString(val)); } val = mTransaction->RequestHead()->PeekHeader(nsHttp::Proxy_Authorization); if (val) { // we don't know for sure if this authorization is intended for the // SSL proxy, so we add it just in case. request.SetHeader(nsHttp::Proxy_Authorization, nsDependentCString(val)); } buf.Truncate(); request.Flatten(buf, false); buf.AppendLiteral("\r\n"); return NS_NewCStringInputStream(getter_AddRefs(mProxyConnectStream), buf); } //----------------------------------------------------------------------------- // nsHttpConnection::nsISupports //----------------------------------------------------------------------------- NS_IMPL_THREADSAFE_ISUPPORTS4(nsHttpConnection, nsIInputStreamCallback, nsIOutputStreamCallback, nsITransportEventSink, nsIInterfaceRequestor) //----------------------------------------------------------------------------- // nsHttpConnection::nsIInputStreamCallback //----------------------------------------------------------------------------- // called on the socket transport thread NS_IMETHODIMP nsHttpConnection::OnInputStreamReady(nsIAsyncInputStream *in) { NS_ASSERTION(in == mSocketIn, "unexpected stream"); NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread"); if (mIdleMonitoring) { NS_ABORT_IF_FALSE(!mTransaction, "Idle Input Event While Active"); // The only read event that is protocol compliant for an idle connection // is an EOF, which we check for with CanReuse(). If the data is // something else then just ignore it and suspend checking for EOF - // our normal timers or protocol stack are the place to deal with // any exception logic. if (!CanReuse()) { LOG(("Server initiated close of idle conn %p\n", this)); gHttpHandler->ConnMgr()->CloseIdleConnection(this); return NS_OK; } LOG(("Input data on idle conn %p, but not closing yet\n", this)); return NS_OK; } // if the transaction was dropped... if (!mTransaction) { LOG((" no transaction; ignoring event\n")); return NS_OK; } nsresult rv = OnSocketReadable(); if (NS_FAILED(rv)) CloseTransaction(mTransaction, rv); return NS_OK; } //----------------------------------------------------------------------------- // nsHttpConnection::nsIOutputStreamCallback //----------------------------------------------------------------------------- NS_IMETHODIMP nsHttpConnection::OnOutputStreamReady(nsIAsyncOutputStream *out) { NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread"); NS_ABORT_IF_FALSE(out == mSocketOut, "unexpected socket"); // if the transaction was dropped... if (!mTransaction) { LOG((" no transaction; ignoring event\n")); return NS_OK; } nsresult rv = OnSocketWritable(); if (NS_FAILED(rv)) CloseTransaction(mTransaction, rv); return NS_OK; } //----------------------------------------------------------------------------- // nsHttpConnection::nsITransportEventSink //----------------------------------------------------------------------------- NS_IMETHODIMP nsHttpConnection::OnTransportStatus(nsITransport *trans, nsresult status, uint64_t progress, uint64_t progressMax) { if (mTransaction) mTransaction->OnTransportStatus(trans, status, progress); return NS_OK; } //----------------------------------------------------------------------------- // nsHttpConnection::nsIInterfaceRequestor //----------------------------------------------------------------------------- // not called on the socket transport thread NS_IMETHODIMP nsHttpConnection::GetInterface(const nsIID &iid, void **result) { // NOTE: This function is only called on the UI thread via sync proxy from // the socket transport thread. If that weren't the case, then we'd // have to worry about the possibility of mTransaction going away // part-way through this function call. See CloseTransaction. // NOTE - there is a bug here, the call to getinterface is proxied off the // nss thread, not the ui thread as the above comment says. So there is // indeed a chance of mTransaction going away. bug 615342 NS_ASSERTION(PR_GetCurrentThread() != gSocketThread, "wrong thread"); if (mCallbacks) return mCallbacks->GetInterface(iid, result); return NS_ERROR_NO_INTERFACE; }
35.280279
91
0.614933
wilebeast
fccf92f5d8996fcd1c01b9efc064ab47bf951e4c
803
cpp
C++
Day1/codeforce284A.cpp
tsung1271232/NCTU_PCCA
79dc16aa7f83c734b859e93cb06323c382a4d686
[ "MIT" ]
null
null
null
Day1/codeforce284A.cpp
tsung1271232/NCTU_PCCA
79dc16aa7f83c734b859e93cb06323c382a4d686
[ "MIT" ]
null
null
null
Day1/codeforce284A.cpp
tsung1271232/NCTU_PCCA
79dc16aa7f83c734b859e93cb06323c382a4d686
[ "MIT" ]
null
null
null
//Cows and Primitive Roots #include<bits/stdc++.h> using namespace std; int priRoot(int prime, int count) { // 1<= x < p for(int i = 1; i < prime; i++) { //do x-1 ~ x^p-2 can't be divisible by prime int temp = i; bool isAns = true; for(int p = 1; p <= prime - 2; p++) { if((temp - 1)%prime == 0) { isAns = false; break; } temp = (temp * i) % prime; } //x^p-1 can be divisible by prime if(isAns && (temp - 1)%prime != 0) isAns = false; if(isAns) count++; } return count; } int main() { int prime; int count; cin>>prime; count = 0; cout<<priRoot(prime, count)<<endl; }
20.589744
52
0.427148
tsung1271232
fcd0bd53e6a31ffdc00f954a632b961c9037ca56
20,689
cpp
C++
src/hkdevice/hikcontroller.cpp
escoffier/newmedia
f15aedae56a5b5c22c6451fa45b58ce108a58b9e
[ "Apache-2.0" ]
null
null
null
src/hkdevice/hikcontroller.cpp
escoffier/newmedia
f15aedae56a5b5c22c6451fa45b58ce108a58b9e
[ "Apache-2.0" ]
null
null
null
src/hkdevice/hikcontroller.cpp
escoffier/newmedia
f15aedae56a5b5c22c6451fa45b58ce108a58b9e
[ "Apache-2.0" ]
null
null
null
#include "hikcontroller.h" #ifdef WINDOWS #include <Windows.h> #include <BaseTsd.h> #include <WinNT.h> #endif #include "HCNetSDK.h" #include "glog/logging.h" #include<string> #include <mutex> //#include "camara.h" extern "C" EXPORT CamaraController* GetController() { LOG(INFO) << "Create HikDeviceProcesser"; NET_DVR_Init(); return new HikCamaraController; } HikCamaraController::HikCamaraController(): login_(false), sdkusers_() { } HikCamaraController::~HikCamaraController() { } bool HikCamaraController::Login(std::string id, std::string ip, int port, std::string name, std::string pwd) { NET_DVR_USER_LOGIN_INFO struLoginInfo = { 0 }; struLoginInfo.bUseAsynLogin = false; memcpy(struLoginInfo.sDeviceAddress, ip.c_str(), NET_DVR_DEV_ADDRESS_MAX_LEN); memcpy(struLoginInfo.sUserName, name.c_str(), NAME_LEN); memcpy(struLoginInfo.sPassword, pwd.c_str(), PASSWD_LEN); struLoginInfo.wPort = port; NET_DVR_DEVICEINFO_V40 struDeviceInfoV40 = { 0 }; LONG lUserID = NET_DVR_Login_V40(&struLoginInfo, &struDeviceInfoV40); if (lUserID < 0) { LOG(ERROR) << "ע���豸ʧ��:\r\n" << "�豸IP:[" << ip << "]\r\n" << "�豸�˿�:[" << port << "]\r\n" << "�û���:[" << name << "]\r\n" << "����:[" << pwd << "]\r\n" << "������: " << NET_DVR_GetLastError(); return false; } LOG(INFO) << "Login " << id <<" : " << ip <<" successfully"; NET_DVR_DEVICECFG_V40 devConfig; memset(&devConfig, 0, sizeof(devConfig)); DWORD dwBytesReturned = 0; BOOL ret = NET_DVR_GetDVRConfig(lUserID, NET_DVR_GET_DEVICECFG_V40, 0, &devConfig, sizeof(devConfig), &dwBytesReturned); LOG(INFO) << "device type : " << devConfig.byDevTypeName; std::shared_ptr<SdkUser> user = std::make_shared<SdkUser>(); user->SetUserId(lUserID); user->SetChannelId(0); user->Online(true); user->deviceid_ = id; user->ip_ = ip; user->port_ = port; user->userName_ = name; user->password_ = pwd; sdkusers_.emplace(id, user); return true; } bool HikCamaraController::Login(std::shared_ptr<SdkUser> user) { return Login(user->GetDeviceId(), user->ip_, user->port_, user->userName_, user->password_); } bool HikCamaraController::isLogin() const { return false; } static bool DecodePTZCommand(const std::string& id, std::string sCode, DWORD &dwPTZCommand, DWORD &dwStop, DWORD &dwSpeed) { #define GB_PTZ_RIGHT 1 //�� #define GB_PTZ_LEFT 2 //�� #define GB_PTZ_DOWN 4 //�� #define GB_PTZ_UP 8 //�� #define GB_PTZ_ZOOM_BIG 16 //�Ŵ� #define GB_PTZ_ZOOM_SMARLL 32 //��С #define GB_PTZ_CIRCLE_SMARLL 0x48 //��Ȧ��С #define GB_PTZ_CIRCLE_BIG 0x44 //��Ȧ��� #define GB_PTZ_CIRCLE_STOP 0x40 //��Ȧֹͣ #define GB_PTZ_FOCUS_NER 0x42 //����� #define GB_PTZ_FOCUS_FAR 0x41 //����Զ #define GB_PTZ_CIRCLE_FOCUS 0x49 //����Զ+��ȦС #define GB_PTZ_PRESET_ADD 0x81 //����Ԥ��λ #define GB_PTZ_PRESET_SET 0x82 //����Ԥ��λ #define GB_PTZ_PRESET_DEL 0x83 //ɾ��Ԥ��λ int ispeed = 0; std::string ptzcode = sCode; ptzcode = ptzcode.substr(6, 2); //int icmd = atoi(ptzcode.c_str()); int icmd = 0; sscanf(ptzcode.c_str(), "%x", &icmd); if (icmd == 0) { dwStop = 1; } else { ptzcode = sCode.substr(8, 2); //int param5 = atoi(ptzcode.c_str()); //ˮƽ�ٶ� int param5; sscanf(ptzcode.c_str(), "%x", &param5);//ˮƽ�ٶ� ptzcode = sCode.substr(10, 2); //int param6 = atoi(ptzcode.c_str()); //�����ٶ� int param6; sscanf(ptzcode.c_str(), "%x", &param6);//�����ٶ� ptzcode = sCode.substr(12, 2); //int param7 = atoi(ptzcode.c_str()); //�����ٶ� int param7; sscanf(ptzcode.c_str(), "%x", &param7);//�����ٶ� switch (icmd) { case GB_PTZ_RIGHT: //00000001 dwPTZCommand = PAN_RIGHT; ispeed = param5 & 0xFF; break; case GB_PTZ_LEFT: //00000010 dwPTZCommand = PAN_LEFT; ispeed = param5 & 0xFF; break; case GB_PTZ_DOWN: //00000100 dwPTZCommand = TILT_DOWN; ispeed = param6 & 0xFF; break; case GB_PTZ_UP: //00001000 dwPTZCommand = TILT_UP; ispeed = param6 & 0xFF; break; case GB_PTZ_DOWN + GB_PTZ_RIGHT: //00000101 dwPTZCommand = DOWN_RIGHT; ispeed = param5 & 0xFF; break; case GB_PTZ_DOWN + GB_PTZ_LEFT: //00000110 dwPTZCommand = DOWN_LEFT; ispeed = param5 & 0xFF; break; case GB_PTZ_UP + GB_PTZ_RIGHT: //00001001 dwPTZCommand = UP_RIGHT; ispeed = param5 & 0xFF; break; case GB_PTZ_UP + GB_PTZ_LEFT: //00001010 dwPTZCommand = UP_LEFT; ispeed = param5 & 0xFF; break; /*************************��ͷ����*********************************/ case GB_PTZ_ZOOM_BIG: //00010000 �䱶�Ŵ� dwPTZCommand = ZOOM_IN; ispeed = ((param7 & 0xF0) >> 4); break; case GB_PTZ_ZOOM_SMARLL: //00100000 �䱶��С dwPTZCommand = ZOOM_OUT; ispeed = ((param7 & 0xF0) >> 4); break; case GB_PTZ_CIRCLE_SMARLL: //0X48 ��Ȧ��С dwPTZCommand = IRIS_CLOSE; //m_pHikDevice->UpdateModel_LastFI(stsipid, IRIS_CLOSE); ispeed = param6 & 0xFF; break; case GB_PTZ_CIRCLE_BIG: // 0x44 ��Ȧ��� dwPTZCommand = IRIS_OPEN; //m_pHikDevice->UpdateModel_LastFI(stsipid, IRIS_OPEN); ispeed = param6 & 0xFF; break; case GB_PTZ_CIRCLE_STOP: //0x40 ����\��Ȧֹͣ { //BaseModel model; //if (m_pHikDevice->GetModel(stsipid, model)) //{ // dwPTZCommand = model.m_lastFI; //} dwPTZCommand = IRIS_OPEN; ispeed = 0; } break; case GB_PTZ_FOCUS_NER: //0x42 ����� dwPTZCommand = FOCUS_NEAR; //m_pHikDevice->UpdateModel_LastFI(stsipid, FOCUS_NEAR); ispeed = param5 & 0xFF; break; case GB_PTZ_CIRCLE_FOCUS: //0x49 ����Զ+��ȦС �豸��֧�ֵ�0x41���� case GB_PTZ_FOCUS_FAR: //0x41 ����Զ dwPTZCommand = FOCUS_FAR; //m_pHikDevice->UpdateModel_LastFI(stsipid, FOCUS_FAR); ispeed = param5 & 0xFF; break; default: LOG(WARNING) << "PTZCommand: " << icmd << "dose not exist"; /*************************��ͷ������С*********************************/ } } //dwSpeed = ispeed*7/255; if (ispeed > 7) { dwSpeed = 7; } else if (ispeed <= 0) { dwSpeed = 1; } else { dwSpeed = ispeed; } return true; } static bool DecodePTZPreset(std::string sCode, DWORD& dwPTZPresetCmd, DWORD& dwPresetIndex) { #define GB_PTZ_PRESET_ADD 0x81 //����Ԥ��λ #define GB_PTZ_PRESET_SET 0x82 //����Ԥ��λ #define GB_PTZ_PRESET_DEL 0x83 //ɾ��Ԥ��λ std::string ptzcode = sCode; ptzcode = sCode.substr(6, 2); //int icmd = atoi(ptzcode.c_str()); int icmd = 0; sscanf(ptzcode.c_str(), "%x", &icmd); ptzcode = sCode.substr(10, 2); sscanf(ptzcode.c_str(), "%x", &dwPresetIndex); dwPresetIndex = dwPresetIndex & 0xFF; switch (icmd) { case GB_PTZ_PRESET_ADD: dwPTZPresetCmd = SET_PRESET; break; case GB_PTZ_PRESET_SET: dwPTZPresetCmd = GOTO_PRESET; break; case GB_PTZ_PRESET_DEL: dwPTZPresetCmd = CLE_PRESET; break; default: LOG(WARNING) << "PTZCommand: " << icmd << "dose not exist"; //LOG_WARN(g_nLogID, "PTZCommand[" << icmd << "] PTZ_PRESET is not exist"); } return true; } static bool DecodePTZCruise(std::string scode, DWORD &dwPTZCruiseCmd, BYTE &byCruiseRoute, BYTE &byCruisePoint, WORD &wInput) { #define GB_PTZ_CRUISE_ADD 0x84 //����Ѳ���� #define GB_PTZ_CRUISE_DLL 0x85 //ɾ��Ѳ���� #define GB_PTZ_CRUISE_SPEED 0x86 //����Ѳ���ٶ� #define GB_PTZ_CRUISE_DWELL 0x87 //����Ѳ��ͣ��ʱ�� #define GB_PTZ_CRUISE_START 0x88 //��ʼѲ�� std::string ptzcode = scode; ptzcode = scode.substr(6, 2); //int icmd = atoi(ptzcode.c_str()); int icmd = 0; sscanf(ptzcode.c_str(), "%x", &icmd); ptzcode = scode.substr(8, 2); //int param5 = atoi(ptzcode.c_str()); int param5 = 0; sscanf(ptzcode.c_str(), "%x", &param5); ptzcode = scode.substr(10, 2); //int param6 = atoi(ptzcode.c_str()); int param6 = 0; sscanf(ptzcode.c_str(), "%x", &param6); ptzcode = scode.substr(12, 2); //int param7 = atoi(ptzcode.c_str()); int param7 = 0; sscanf(ptzcode.c_str(), "%x", &param7); int tmp = 0; switch (icmd) { case GB_PTZ_CRUISE_ADD: //0x84 ����Ѳ���� dwPTZCruiseCmd = FILL_PRE_SEQ; byCruiseRoute = param5 & 0xFF; byCruisePoint = param6 & 0xFF; wInput = param6 & 0xFF; break; case GB_PTZ_CRUISE_DLL: //0x85 ɾ��Ѳ���� dwPTZCruiseCmd = CLE_PRE_SEQ; byCruiseRoute = param5 & 0xFF; byCruisePoint = param6 & 0xFF; wInput = param6 & 0xFF; break; case GB_PTZ_CRUISE_SPEED: //0x86 ����Ѳ���ٶ� dwPTZCruiseCmd = SET_SEQ_SPEED; byCruiseRoute = param5 & 0xFF; tmp = param6 & 0xFF; wInput = (((param7 & 0xF0) << 4) + tmp) * 40 / 4095; //�����ٶ����40 ������� 0xfff if (wInput == 0) { wInput = 1; } break; case GB_PTZ_CRUISE_DWELL: //0x87 ����Ѳ��ͣ��ʱ�� dwPTZCruiseCmd = SET_SEQ_DWELL; byCruiseRoute = param5 & 0xFF; tmp = param6 & 0xFF; wInput = (((param7 & 0xF0) << 4) + tmp) * 255 / 4095; //�����ٶ����40 ������� 0xfff if (wInput == 0) { wInput = 1; } break; case GB_PTZ_CRUISE_START: //0x88 ��ʼѲ�� ֹͣѲ����PTZֹͣ���� dwPTZCruiseCmd = RUN_SEQ; byCruiseRoute = param5 & 0xFF; break; default: LOG(WARNING) << "PTZCommand: " << icmd << "dose not exist"; //LOG_WARN(g_nLogID, "PTZCommand[" << icmd << "] PTZ_CRUISE is not exist"); } return true; } void HikCamaraController::ptzControl(std::string id, std::string cmd) { LOG(INFO) << "HikCamaraController ptzControl"; auto search = sdkusers_.find(id); if (search == sdkusers_.end()) { if (!Login(search->second)) { return; } } else { std::string ptzcode = cmd.substr(6, 2); int icmd = atoi(ptzcode.c_str()); if (icmd < 0x4A) { DWORD dwPTZCommand = PAN_RIGHT;//��ʼ����ֵ�������ֹͣ����dwPTZCommand������ֵ DWORD dwStop = 0;//1ֹͣ��̨���� DWORD dwSpeed = 1;//�ٶȡ�1-7�� if (!DecodePTZCommand(id, cmd, dwPTZCommand, dwStop, dwSpeed)) { LOG(ERROR) << "������̨�������,SIPID:" << id; return; } //NET_DVR_PTZControlWithSpeed(Model.m_nRealHandle, dwPTZCommand, dwStop, dwSpeed)) if (!NET_DVR_PTZControlWithSpeed_Other(search->second->GetUserId(), 1, dwPTZCommand, dwStop, dwSpeed)) { LOG(ERROR) << "��̨���Ƴ���,SIPID:" << id << "����ԭ��:" << NET_DVR_GetLastError(); return; } LOG(INFO) << "����ptz�ɹ�,SIPID:" << id << " cmd = " << icmd << " HKcmd =" << dwPTZCommand << " stop=" << dwStop << " speed=" << dwSpeed; } else if ((0x80 < icmd) && (icmd < 0x84)) { DWORD dwPTZPresetCmd = SET_PRESET; DWORD dwPresetIndex = 0; if (!DecodePTZPreset(cmd, dwPTZPresetCmd, dwPresetIndex)) { LOG(ERROR) << "������̨Ԥ�õ��������,SIPID:" <<id; return; } if (!NET_DVR_PTZPreset_Other(search->second->GetUserId(), 1, dwPTZPresetCmd, dwPresetIndex)) { LOG(ERROR) << "������̨Ԥ�õ��������,SIPID:" << id << "����ԭ��:" << NET_DVR_GetLastError(); return; } LOG(INFO) << "����Ԥ�õ�ɹ�,SIPID:" << id << " cmd = " << icmd << " HKcmd =" << dwPTZPresetCmd << " INDEX=" << dwPresetIndex; } else if ((0x83 < icmd) && (icmd < 0x89)) { DWORD dwPTZCruiseCmd = SET_PRESET; BYTE byCruiseRoute = 0; BYTE byCruisePoint = 0; WORD wInput = 0; if (!DecodePTZCruise(cmd, dwPTZCruiseCmd, byCruiseRoute, byCruisePoint, wInput)) { LOG(ERROR) << "������̨Ԥ�õ��������,SIPID:" << id; return; } if (!NET_DVR_PTZCruise_Other(search->second->GetUserId(), 1, dwPTZCruiseCmd, byCruiseRoute, byCruisePoint, wInput)) { LOG(ERROR) << "������̨Cruise�������,SIPID:" << id << "����ԭ��:" << NET_DVR_GetLastError(); return; } LOG(INFO) << "����Cruise�ɹ�,SIPID:" << id << " cmd = " << icmd << " HKcmd =" << dwPTZCruiseCmd << " rute=" << byCruiseRoute << " point=" << byCruisePoint << " input=" << wInput; } else if ((0x88 < icmd) && (icmd < 0x8B)) { LOG(WARNING) << "������̨ɨ�躣����֧��,SIPID:" << id << " cmd = " << icmd; } else { LOG(WARNING) << "������̨������귶Χ,SIPID:" << id << " cmd = " << icmd; } } return; } void HikCamaraController::getDeviceStatusAsync(std::string id, std::function<void(int)> cb) { auto search = sdkusers_.find(id); if (search == sdkusers_.end()) { if (!Login(search->second)) { cb(0); return; } } else { NET_DVR_WORKSTATE_V40 *pStruWorkStateV40 = new NET_DVR_WORKSTATE_V40; DWORD dwList = 0; memset(pStruWorkStateV40, 0, sizeof(NET_DVR_WORKSTATE_V40)); NET_DVR_GETWORKSTATE_COND struWorkStateCond = { 0 }; struWorkStateCond.dwSize = sizeof(NET_DVR_GETWORKSTATE_COND); struWorkStateCond.byFindChanByCond = 0; struWorkStateCond.byFindHardByCond = 0; if (!NET_DVR_GetDeviceConfig(search->second->GetUserId(), NET_DVR_GET_WORK_STATUS, 1, \ &struWorkStateCond, sizeof(NET_DVR_GETWORKSTATE_COND), &dwList, pStruWorkStateV40, sizeof(NET_DVR_WORKSTATE_V40)) || (dwList != 0)) { cb(0); return; } if (0 == pStruWorkStateV40->dwDeviceStatic) { cb(0); } else { cb(1); } } } void HikCamaraController::getDeviceStatus(std::string id, dt::DeviceStatus & st) { auto search = sdkusers_.find(id); if (search == sdkusers_.end()) { if (!Login(search->second)) { //cb(0); st.status = 0; return; } } else { NET_DVR_WORKSTATE_V40 *pStruWorkStateV40 = new NET_DVR_WORKSTATE_V40; DWORD dwList = 0; memset(pStruWorkStateV40, 0, sizeof(NET_DVR_WORKSTATE_V40)); NET_DVR_GETWORKSTATE_COND struWorkStateCond = { 0 }; struWorkStateCond.dwSize = sizeof(NET_DVR_GETWORKSTATE_COND); struWorkStateCond.byFindChanByCond = 0; struWorkStateCond.byFindHardByCond = 0; if (!NET_DVR_GetDeviceConfig(search->second->GetUserId(), NET_DVR_GET_WORK_STATUS, 1, \ &struWorkStateCond, sizeof(NET_DVR_GETWORKSTATE_COND), &dwList, pStruWorkStateV40, sizeof(NET_DVR_WORKSTATE_V40)) || (dwList != 0)) { st.status = 0; return; } if (0 == pStruWorkStateV40->dwDeviceStatic) { st.status = 0; } else { st.status = 1; } } } void HikCamaraController::processData(long hd, char *data , uint32_t len) { // streamMutex_.lock(); // auto cb = cbMap_.find(hd); // if (cb != cbMap_.end()) // { // streamMutex_.unlock(); // cb->second(data, len); // } // else // { // streamMutex_.lock(); // return; // } } bool HikCamaraController::logIn(std::string id, std::string ip, int port, std::string userName, std::string pwd) { NET_DVR_USER_LOGIN_INFO struLoginInfo = { 0 }; struLoginInfo.bUseAsynLogin = false; memcpy(struLoginInfo.sDeviceAddress, ip.c_str(), NET_DVR_DEV_ADDRESS_MAX_LEN); memcpy(struLoginInfo.sUserName, userName.c_str(), NAME_LEN); memcpy(struLoginInfo.sPassword, pwd.c_str(), PASSWD_LEN); struLoginInfo.wPort = port; NET_DVR_DEVICEINFO_V40 struDeviceInfoV40 = { 0 }; LONG lUserID = NET_DVR_Login_V40(&struLoginInfo, &struDeviceInfoV40); if (lUserID < 0) { LOG(ERROR) << "ע���豸ʧ��:\r\n" << "�豸IP:[" << ip << "]\r\n" << "�豸�˿�:[" << port << "]\r\n" << "�û���:[" << userName << "]\r\n" << "����:[" << pwd << "]\r\n" << "������: " << NET_DVR_GetLastError(); return false; } LOG(INFO) << "Login " << ip << " successfully"; NET_DVR_DEVICECFG_V40 devConfig; memset(&devConfig, 0, sizeof(devConfig)); DWORD dwBytesReturned = 0; BOOL ret = NET_DVR_GetDVRConfig(lUserID, NET_DVR_GET_DEVICECFG_V40, 0, &devConfig, sizeof(devConfig), &dwBytesReturned); LOG(INFO) << "device type : " << devConfig.byDevTypeName; std::shared_ptr<SdkUser> user = std::make_shared<SdkUser>(); user->SetUserId(lUserID); user->SetChannelId(0); user->Online(true); user->deviceid_ = id; user->ip_ = ip; user->port_ = port; user->userName_ =userName; user->password_ = pwd; sdkusers_.emplace(id, user); return true; } static void __stdcall RealDataCallBack(LONG lPlayHandle, DWORD dwDataType, BYTE *pBuffer, DWORD dwBufSize, void* pUser) { //std::cout<<"receive data: "<< dwBufSize <<" type: "<< dwDataType <<std::endl; if (pUser == nullptr) { return; } HikCamaraController * controller = (HikCamaraController*)pUser; //std::shared_ptr<PSBuffer> buf = ((PSBuffer *)pUser)->getPtr(); char *id = (char *)pUser; switch (dwDataType) { case NET_DVR_SYSHEAD: break; case NET_DVR_STREAMDATA: { auto start = std::chrono::high_resolution_clock::now(); //StreamManager::getInstance()->putDatatoBuffer("60000000001310001430", pBuffer, dwBufSize); controller->processData(lPlayHandle, (char *)pBuffer, dwBufSize); auto elapsed = std::chrono::high_resolution_clock::now() - start; //LOG(INFO) << "elapse " << std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count() << " microseconds"; } break; default: break; } } static void __stdcall newRealDataCallBack(LONG lPlayHandle, DWORD dwDataType, BYTE *pBuffer, DWORD dwBufSize, void* pUser) { if (pUser == nullptr) { return; } std::function<void(char *, uint32_t)> *cb = (std::function<void(char *, uint32_t)> *)pUser; switch (dwDataType) { case NET_DVR_SYSHEAD: break; case NET_DVR_STREAMDATA: { auto start = std::chrono::high_resolution_clock::now(); //StreamManager::getInstance()->putDatatoBuffer("60000000001310001430", pBuffer, dwBufSize); //controller->processData(lPlayHandle, (char *)pBuffer, dwBufSize); (*cb)((char *)pBuffer, dwBufSize); auto elapsed = std::chrono::high_resolution_clock::now() - start; //LOG(INFO) << "elapse " << std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count() << " microseconds"; } break; default: break; } } //bool HikCamaraController::openRealStream(const dt::OpenRealStream& param) bool HikCamaraController::openRealStream(std::string id, std::string ip, int port, std::string user, std::string pwd, std::function<void(char *, uint32_t)> datacb) { auto search = sdkusers_.find(id); if (search == sdkusers_.end()) { if (!logIn(id, ip, port, user, pwd)) { LOG(ERROR) << "Hik sdk login camara failed when opening stream"; return false; } } LOG(ERROR) << "Hik sdk login camara {"<< ip<<" : "<<port<<"} successfully!"; auto sdkuser = sdkusers_.find(id); if (sdkuser == sdkusers_.end()) { LOG(ERROR) << "Hik opening stream failed"; return false; } dataCallBack *dtcb = new dataCallBack(datacb); //sdkuser->second->SetCallBack(dtcb); //HWND hWnd = NULL; NET_DVR_PREVIEWINFO struPlayInfo = { 0 }; #if (defined(_WIN32) || defined(_WIN_WCE)) struPlayInfo.hPlayWnd = NULL; #elif defined(__linux__) struPlayInfo.hPlayWnd = 0; #endif //struPlayInfo.hPlayWnd = NULL; //��Ҫ SDK ����ʱ�����Ϊ��Чֵ����ȡ��������ʱ����Ϊ�� struPlayInfo.lChannel = 1;// struPlayInfo.dwLinkMode = 0;//0- TCP ��ʽ�� 1- UDP ��ʽ�� 2- �ಥ��ʽ�� 3- RTP ��ʽ�� 4-RTP/RTSP�� 5-RSTP/HTTP struPlayInfo.dwStreamType = 0;//0-�������� 1-�������� 2-���� 3�� 3-���� 4���Դ����� // struPlayInfo.byPreviewMode = 0;//����Ԥ�� struPlayInfo.bBlocked = 1;//0- ������ȡ���� 1- ����ȡ�� struPlayInfo.bPassbackRecord = 0;//������¼��ش�; struPlayInfo.byProtoType = 0;//˽��Э�� //long playHandle_ = NET_DVR_RealPlay_V40(sdkuser->second->GetUserId(), &struPlayInfo, RealDataCallBack, (void *)this); long playHandle_ = NET_DVR_RealPlay_V40(sdkuser->second->GetUserId(), &struPlayInfo, newRealDataCallBack, dtcb); if (playHandle_ < 0) { LOG(ERROR) << "Hik sdk open stream failed, error code: " << NET_DVR_GetLastError(); return false; } else { //int iRet = NET_DVR_SetRealDataCallBack(playHandle_, RealDataCallBack, this); sdkuser->second->SetPlayHandle(playHandle_); std::lock_guard<std::mutex> lk(streamMutex_); //cbMap_.emplace(playHandle_, datacb); cbMap_.emplace(playHandle_, dtcb); LOG(INFO) << "Hik sdk open stream successfully!"; return true; } } bool HikCamaraController::closeRealStream(const std::string & id) { auto search = sdkusers_.find(id); if (search == sdkusers_.end()) { LOG(ERROR) << "Hik sdk close stream failed: not find camara " << id; return false; } auto sdksuer = search->second; LOG(ERROR) << "hik sdk PlayHandle: " << sdksuer->GetPlayHandle(); int ret = NET_DVR_SetRealDataCallBack(search->second->GetPlayHandle(), NULL, 0); if(!ret) { LOG(ERROR) << "NET_DVR_SetRealDataCallBack error: " << NET_DVR_GetLastError(); } if(!NET_DVR_StopRealPlay(search->second->GetPlayHandle())) { LOG(ERROR) << "Hik sdk close stream failed, error code: " << NET_DVR_GetLastError(); } std::lock_guard<std::mutex> lk(streamMutex_); auto cb = cbMap_.find(search->second->GetPlayHandle()); if (cb == cbMap_.end()) { return true; } auto c = cb->second; delete c; cbMap_.erase(cb); return true; }
28.263661
182
0.624776
escoffier
fcdbac754c5429628bd2f72b02c424173a5b478b
819
cc
C++
Laboratorio/Esercitazione 3/310-equazione.cc
alessiamarcolini/Programmazione1UniTN
fd1cbd54b9510e1ec7efb185b727a6fd49dd32f1
[ "MIT" ]
3
2021-11-05T16:25:50.000Z
2022-02-10T14:06:00.000Z
Laboratorio/Esercitazione 3/310-equazione.cc
alessiamarcolini/Programmazione1UniTN
fd1cbd54b9510e1ec7efb185b727a6fd49dd32f1
[ "MIT" ]
null
null
null
Laboratorio/Esercitazione 3/310-equazione.cc
alessiamarcolini/Programmazione1UniTN
fd1cbd54b9510e1ec7efb185b727a6fd49dd32f1
[ "MIT" ]
2
2018-10-31T14:53:40.000Z
2020-01-09T22:34:37.000Z
// // Dati 3 interi a, b, c che corrispondono // ai termini noti di un'equazione di // secondo grado, calcolare le soluzioni // #include <cmath> #include <iostream> using namespace std; int main() { int a, b, c; float x1, x2, delta; cout << "Inserisci un numero: "; cin >> a; cout << "Inserisci un numero: "; cin >> b; cout << "Inserisci un numero: "; cin >> c; delta = ((b * b) - (4 * a * c)); if (delta < 0) { cout << "ATTENZIONE: delta minore di 0" << endl; } else { if (a == 0) { cout << "ATTENZIONE: non e' un'equazione do secondo grado" << endl; } else { x1 = (-b + sqrt(delta)) / (2 * a); x2 = (-b - sqrt(delta)) / (2 * a); cout << x1 << " " << x2 << endl; } } return (0); }
22.135135
79
0.478632
alessiamarcolini
fcdddbe53f12e9c893f9c69c6640f84b8ee5bdc3
8,490
cpp
C++
source/deps/illa/filter_bilinear.cpp
poppeman/Pictus
0e58285b89292d0b221ab4d09911ef439711cc59
[ "MIT" ]
73
2015-01-19T17:38:26.000Z
2022-02-15T06:16:08.000Z
source/deps/illa/filter_bilinear.cpp
poppeman/Pictus
0e58285b89292d0b221ab4d09911ef439711cc59
[ "MIT" ]
75
2015-01-01T17:32:24.000Z
2018-10-18T08:19:08.000Z
source/deps/illa/filter_bilinear.cpp
poppeman/Pictus
0e58285b89292d0b221ab4d09911ef439711cc59
[ "MIT" ]
18
2015-01-05T04:57:18.000Z
2022-03-06T01:35:10.000Z
#include "filter_bilinear.h" #include "filter_int.h" #define BSHIFT 11 #define BSHIFTx2 22 #define BMUL 2048 namespace Filter { namespace Scale { using namespace Geom; namespace Internal { void set_contrib(std::vector<Contrib>& contrib, uint32_t i, uint32_t max_i, uint32_t max_coord, uint32_t ofs) { uint32_t floor = ofs >> BSHIFT; if (i < max_i) { contrib[i].floor = floor; if ((contrib[i].floor + 1) >= max_coord) { contrib[i].floor = std::max<uint32_t>(2, max_coord) - 2; ofs = (contrib[i].floor << BSHIFT) + BMUL - 2; } } contrib[i].frac = ofs - (contrib[i].floor << BSHIFT); contrib[i].frac_inv = BMUL - contrib[i].frac; } } struct PaletteToDWord { PaletteToDWord(const Img::Palette& p) :m_p(p) {} uint32_t Assemble(uint8_t ul, uint32_t fUL, uint8_t ur, uint32_t fUR, uint8_t bl, uint32_t fBL, uint8_t br, uint32_t fBR) const { const Img::Color& cUL = m_p.Color(ul); const Img::Color& cUR = m_p.Color(ur); const Img::Color& cBL = m_p.Color(bl); const Img::Color& cBR = m_p.Color(br); uint32_t A = (cUL.A * fUL + cUR.A * fUR + cBL.A * fBL + cBR.A * fBR) >> BSHIFTx2; uint32_t R = (cUL.R * fUL + cUR.R * fUR + cBL.R * fBL + cBR.R * fBR) >> BSHIFTx2; uint32_t G = (cUL.G * fUL + cUR.G * fUR + cBL.G * fBL + cBR.G * fBR) >> BSHIFTx2; uint32_t B = (cUL.B * fUL + cUR.B * fUR + cBL.B * fBL + cBR.B * fBR) >> BSHIFTx2; return Img::ToARGBDWORD(A, R, G, B); } const Img::Palette& m_p; void operator=(const PaletteToDWord&) = delete; }; template <typename T, class U> void performBilinear(const FilterBuffer& source, FilterBuffer& dest, const Geom::RectInt& region, float zoom, U pixelConverter) { int width = region.Width(); int height = region.Height(); using namespace Internal; // Precalculate stuff std::vector<Contrib> x_contrib(width); std::vector<Contrib> y_contrib(height); for(int i = 0; i < width; ++i) { set_contrib(x_contrib, i, width, source.Dimensions.Width, static_cast<uint32_t>(((region.Left() + i + 0.25f) / zoom) * BMUL)); } for(int i = 0; i < height; ++i) { set_contrib(y_contrib, i, height, source.Dimensions.Height, static_cast<uint32_t>(((region.Top() + i + 0.25f) / zoom) * BMUL)); } uint8_t* destCurrentScanlinePtr = dest.BufferData; int rw = region.Width(); for (int y = 0; y < region.Height(); ++y) { uint32_t floorY = y_contrib[y].floor; uint32_t iFracY = y_contrib[y].frac; uint32_t iFracYinv = y_contrib[y].frac_inv; const T* currSourceScanUpper = reinterpret_cast<T*>(source.BufferData + floorY * source.Stride); const T* currSourceScanLower = reinterpret_cast<T*>(source.BufferData + (floorY + 1) * source.Stride); uint32_t* currDestPixel = reinterpret_cast<uint32_t*>(destCurrentScanlinePtr); for(int x = 0; x < rw; ++x) { uint32_t iFracX = x_contrib[x].frac; uint32_t iFracXinv = x_contrib[x].frac_inv; uint32_t fUL = (iFracXinv * iFracYinv); uint32_t fUR = (iFracX * iFracYinv); uint32_t fBL = (iFracXinv * iFracY); uint32_t fBR = (iFracX * iFracY); *(currDestPixel++) = pixelConverter.Assemble( currSourceScanUpper[x_contrib[x].floor], fUL, currSourceScanUpper[x_contrib[x].floor + 1], fUR, currSourceScanLower[x_contrib[x].floor], fBL, currSourceScanLower[x_contrib[x].floor + 1], fBR); } destCurrentScanlinePtr += dest.Stride; } } void Bilinear(const FilterBuffer& source, FilterBuffer& dest, const Geom::RectInt& region, Img::Format format, float zoom) { if (format == Img::Format::XRGB8888) { struct DWordToDWord { uint32_t Assemble(uint32_t ul, uint32_t fUL, uint32_t ur, uint32_t fUR, uint32_t bl, uint32_t fBL, uint32_t br, uint32_t fBR) const { return Img::ToARGBDWORD( 0xff, (Img::ChannelARGB8888Red(ul) * fUL + Img::ChannelARGB8888Red(ur) * fUR + Img::ChannelARGB8888Red(bl) * fBL + Img::ChannelARGB8888Red(br) * fBR) >> BSHIFTx2, (Img::ChannelARGB8888Green(ul) * fUL + Img::ChannelARGB8888Green(ur) * fUR + Img::ChannelARGB8888Green(bl) * fBL + Img::ChannelARGB8888Green(br) * fBR) >> BSHIFTx2, (Img::ChannelARGB8888Blue(ul) * fUL + Img::ChannelARGB8888Blue(ur) * fUR + Img::ChannelARGB8888Blue(bl) * fBL + Img::ChannelARGB8888Blue(br) * fBR) >> BSHIFTx2); } }; performBilinear<uint32_t>(source, dest, region, zoom, DWordToDWord()); } else if (format == Img::Format::ARGB8888) { struct DWordToDWord { uint32_t Assemble(uint32_t ul, uint32_t fUL, uint32_t ur, uint32_t fUR, uint32_t bl, uint32_t fBL, uint32_t br, uint32_t fBR) const { return Img::ToARGBDWORD( (Img::ChannelARGB8888Alpha(ul) * fUL + Img::ChannelARGB8888Alpha(ur) * fUR + Img::ChannelARGB8888Alpha(bl) * fBL + Img::ChannelARGB8888Alpha(br) * fBR) >> BSHIFTx2, (Img::ChannelARGB8888Red(ul) * fUL + Img::ChannelARGB8888Red(ur) * fUR + Img::ChannelARGB8888Red(bl) * fBL + Img::ChannelARGB8888Red(br) * fBR) >> BSHIFTx2, (Img::ChannelARGB8888Green(ul) * fUL + Img::ChannelARGB8888Green(ur) * fUR + Img::ChannelARGB8888Green(bl) * fBL + Img::ChannelARGB8888Green(br) * fBR) >> BSHIFTx2, (Img::ChannelARGB8888Blue(ul) * fUL + Img::ChannelARGB8888Blue(ur) * fUR + Img::ChannelARGB8888Blue(bl) * fBL + Img::ChannelARGB8888Blue(br) * fBR) >> BSHIFTx2); } }; performBilinear<uint32_t>(source, dest, region, zoom, DWordToDWord()); } else if (format == Img::Format::XRGB1555) { struct WordToDWord { uint32_t Assemble(uint16_t ul, uint32_t fUL, uint16_t ur, uint32_t fUR, uint16_t bl, uint32_t fBL, uint16_t br, uint32_t fBR) const { return Img::ToARGBDWORD( 0xff, ((Img::ChannelARGB1555Red(ul) * fUL + Img::ChannelARGB1555Red(ur) * fUR + Img::ChannelARGB1555Red(bl) * fBL + Img::ChannelARGB1555Red(br) * fBR) >> BSHIFTx2) << 3, ((Img::ChannelARGB1555Green(ul) * fUL + Img::ChannelARGB1555Green(ur) * fUR + Img::ChannelARGB1555Green(bl) * fBL + Img::ChannelARGB1555Green(br) * fBR) >> BSHIFTx2) << 3, ((Img::ChannelARGB1555Blue(ul) * fUL + Img::ChannelARGB1555Blue(ur) * fUR + Img::ChannelARGB1555Blue(bl) * fBL + Img::ChannelARGB1555Blue(br) * fBR) >> BSHIFTx2) << 3); } }; performBilinear<uint16_t>(source, dest, region, zoom, WordToDWord()); } else if (format == Img::Format::ARGB1555) { struct WordToDWord { uint32_t Assemble(uint16_t ul, uint32_t fUL, uint16_t ur, uint32_t fUR, uint16_t bl, uint32_t fBL, uint16_t br, uint32_t fBR) const { return Img::ToARGBDWORD( 255 * ((Img::ChannelARGB1555Alpha(ul) * fUL + Img::ChannelARGB1555Alpha(ur) * fUR + Img::ChannelARGB1555Alpha(bl) * fBL + Img::ChannelARGB1555Alpha(br) * fBR) >> BSHIFTx2), ((Img::ChannelARGB1555Red(ul) * fUL + Img::ChannelARGB1555Red(ur) * fUR + Img::ChannelARGB1555Red(bl) * fBL + Img::ChannelARGB1555Red(br) * fBR) >> BSHIFTx2) << 3, ((Img::ChannelARGB1555Green(ul) * fUL + Img::ChannelARGB1555Green(ur) * fUR + Img::ChannelARGB1555Green(bl) * fBL + Img::ChannelARGB1555Green(br) * fBR) >> BSHIFTx2) << 3, ((Img::ChannelARGB1555Blue(ul) * fUL + Img::ChannelARGB1555Blue(ur) * fUR + Img::ChannelARGB1555Blue(bl) * fBL + Img::ChannelARGB1555Blue(br) * fBR) >> BSHIFTx2) << 3); } }; performBilinear<uint16_t>(source, dest, region, zoom, WordToDWord()); } else if (format == Img::Format::RGB565) { struct WordToDWord { uint32_t Assemble(uint16_t ul, uint32_t fUL, uint16_t ur, uint32_t fUR, uint16_t bl, uint32_t fBL, uint16_t br, uint32_t fBR) const { return Img::ToARGBDWORD( 0xff, ((Img::ChannelRGB565Red(ul) * fUL + Img::ChannelRGB565Red(ur) * fUR + Img::ChannelRGB565Red(bl) * fBL + Img::ChannelRGB565Red(br) * fBR) >> BSHIFTx2) << 3, ((Img::ChannelRGB565Green(ul) * fUL + Img::ChannelRGB565Green(ur) * fUR + Img::ChannelRGB565Green(bl) * fBL + Img::ChannelRGB565Green(br) * fBR) >> BSHIFTx2) << 2, ((Img::ChannelRGB565Blue(ul) * fUL + Img::ChannelRGB565Blue(ur) * fUR + Img::ChannelRGB565Blue(bl) * fBL + Img::ChannelRGB565Blue(br) * fBR) >> BSHIFTx2)) << 3; } }; performBilinear<uint16_t>(source, dest, region, zoom, WordToDWord()); } else if (format == Img::Format::Index8) { performBilinear<uint8_t>(source, dest, region, zoom, PaletteToDWord(source.Palette)); } else DO_THROW(Err::InvalidParam, "Format not supported:" + ToAString(format)); } } }
50.236686
179
0.657362
poppeman
fce29fe5e9f876739d36fa0853a43ddc055a1797
1,686
cpp
C++
Design_patterns_in_modern_cpp/src/020_Chapter_2/Workspace.cpp
NaPiZip/Programming_basics_c-
d84bf4baa25fbcf28b12fb06be7a6270c143effc
[ "MIT" ]
null
null
null
Design_patterns_in_modern_cpp/src/020_Chapter_2/Workspace.cpp
NaPiZip/Programming_basics_c-
d84bf4baa25fbcf28b12fb06be7a6270c143effc
[ "MIT" ]
null
null
null
Design_patterns_in_modern_cpp/src/020_Chapter_2/Workspace.cpp
NaPiZip/Programming_basics_c-
d84bf4baa25fbcf28b12fb06be7a6270c143effc
[ "MIT" ]
null
null
null
// Copyright 2019, Nawin #include "Workspace.h" std::string HtmlElement::str(int indent) const { std::string result; for (auto e : elements_) result += e.name_ + e.text_; return result; } HtmlBuilder::HtmlBuilder(std::string root_name) { root_.name_ = root_name; } HtmlBuilder& HtmlBuilder::add_child(std::string child_name, std::string child_text) { HtmlElement e{ child_name, child_text }; root_.elements_.emplace_back(e); return *this; } std::string HtmlBuilder::str() const { return root_.str(); } std::unique_ptr<HtmlBuilder> HtmlElemenUpdated::build(const std::string& s) { return std::make_unique<HtmlBuilder>(s); } std::ostream& operator<<(std::ostream& os, const Tag& t) { os << '<' << t.name_ << '>' << t.text_ << std::endl; for (auto e : t.children_) { os << '<' << e.name_ << ' '; for (auto attrib : e.attributes_) os << attrib.first << "=\"" << attrib.second; os << "\">" << std::endl; } os << "</" << t.name_ << '>' << std::endl; return os; } PersonAddressBuilder PersonBuilderBase::lives(void) { return PersonAddressBuilder{ person_ }; }; PersonJobBuilder PersonBuilderBase::works(void) { return PersonJobBuilder{ person_ }; } PersonBuilder Person::create() { return PersonBuilder(); } std::ostream& operator<<(std::ostream& os, const Person& obj) { return os << "street_address: " << obj.street_address_ << " post_code: " << obj.post_code_ << " city: " << obj.city_ << " company_name: " << obj.company_name_ << " position: " << obj.position_ << " annual_income: " << obj.annual_income_; }
28.1
86
0.607355
NaPiZip
fce2ba2d11295ef16a7744294498e654ed490a72
30,867
cpp
C++
miniapps/shifted/sbm_solver.cpp
xj361685640/mfem
0843a87d7953cf23e556dcfd426d27bd9cfb3e21
[ "BSD-3-Clause" ]
null
null
null
miniapps/shifted/sbm_solver.cpp
xj361685640/mfem
0843a87d7953cf23e556dcfd426d27bd9cfb3e21
[ "BSD-3-Clause" ]
null
null
null
miniapps/shifted/sbm_solver.cpp
xj361685640/mfem
0843a87d7953cf23e556dcfd426d27bd9cfb3e21
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2010-2021, 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 "sbm_solver.hpp" namespace mfem { double ShiftedFunctionCoefficient::Eval(ElementTransformation & T, const IntegrationPoint & ip, const Vector &D) { if (constantcoefficient) { return constant; } Vector transip; T.Transform(ip, transip); for (int i = 0; i < D.Size(); i++) { transip(i) += D(i); } return Function(transip); } void ShiftedVectorFunctionCoefficient::Eval(Vector &V, ElementTransformation & T, const IntegrationPoint & ip, const Vector &D) { Vector transip; T.Transform(ip, transip); for (int i = 0; i < D.Size(); i++) { transip(i) += D(i); } Function(transip, V); } void SBM2DirichletIntegrator::AssembleFaceMatrix( const FiniteElement &el1, const FiniteElement &el2, FaceElementTransformations &Trans, DenseMatrix &elmat) { int dim, ndof1, ndof2, ndof, ndoftotal; double w; DenseMatrix temp_elmat; dim = el1.GetDim(); ndof1 = el1.GetDof(); ndof2 = el2.GetDof(); ndoftotal = Trans.ElementType == ElementTransformation::BDR_FACE ? ndof1 : ndof1 + ndof2; elmat.SetSize(ndoftotal); elmat = 0.0; bool elem1f = true; // flag indicating whether Trans.Elem1No is part of the // surrogate domain or not. int elem1 = Trans.Elem1No, elem2 = Trans.Elem2No, marker1 = (*elem_marker)[elem1]; int marker2; if (Trans.Elem2No >= NEproc) { marker2 = (*elem_marker)[NEproc+par_shared_face_count]; par_shared_face_count++; } else if (Trans.ElementType == ElementTransformation::BDR_FACE) { marker2 = marker1; } else { marker2 = (*elem_marker)[elem2]; } if (!include_cut_cell) { // 1 is inside and 2 is cut or 1 is a boundary element. if (marker1 == ShiftedFaceMarker::SBElementType::INSIDE && (cut_marker.Find(marker2) != -1 || Trans.ElementType == ElementTransformation::BDR_FACE)) { elem1f = true; } // 1 is cut, 2 is inside else if (cut_marker.Find(marker1) != -1 && marker2 == ShiftedFaceMarker::SBElementType::INSIDE) { if (Trans.Elem2No >= NEproc) { return; } elem1f = false; } else { return; } } else { // 1 is cut and 2 is outside or 1 is a boundary element. if (cut_marker.Find(marker1) != -1 && (marker2 == ShiftedFaceMarker::SBElementType::OUTSIDE || Trans.ElementType == ElementTransformation::BDR_FACE)) { elem1f = true; } // 1 is outside, 2 is cut else if (marker1 == ShiftedFaceMarker::SBElementType::OUTSIDE && cut_marker.Find(marker2) != -1) { if (Trans.Elem2No >= NEproc) { return; } elem1f = false; } else { return; } } ndof = elem1f ? ndof1 : ndof2; temp_elmat.SetSize(ndof); temp_elmat = 0.; nor.SetSize(dim); nh.SetSize(dim); ni.SetSize(dim); adjJ.SetSize(dim); shape.SetSize(ndof); dshape.SetSize(ndof, dim); dshapephys.SetSize(ndof, dim); Vector dshapephysdd(ndof); dshapedn.SetSize(ndof); Vector wrk = shape; const IntegrationRule *ir = IntRule; if (ir == NULL) { int order = elem1f ? 4*el1.GetOrder() : 4*el2.GetOrder(); ir = &IntRules.Get(Trans.GetGeometryType(), order); } Array<DenseMatrix *> dkphi_dxk; DenseMatrix grad_phys; Vector Factorial; Array<DenseMatrix *> grad_phys_dir; if (nterms > 0) { if (elem1f) { el1.ProjectGrad(el1, *Trans.Elem1, grad_phys); } else { el2.ProjectGrad(el2, *Trans.Elem2, grad_phys); } DenseMatrix grad_work; grad_phys_dir.SetSize(dim); // NxN matrices for derivative in each direction for (int i = 0; i < dim; i++) { grad_phys_dir[i] = new DenseMatrix(ndof, ndof); grad_phys_dir[i]->CopyRows(grad_phys, i*ndof, (i+1)*ndof-1); } DenseMatrix grad_phys_work = grad_phys; grad_phys_work.SetSize(ndof, ndof*dim); dkphi_dxk.SetSize(nterms); for (int i = 0; i < nterms; i++) { int sz1 = pow(dim, i+1); dkphi_dxk[i] = new DenseMatrix(ndof, ndof*sz1*dim); int loc_col_per_dof = sz1; int tot_col_per_dof = loc_col_per_dof*dim; for (int k = 0; k < dim; k++) { grad_work.SetSize(ndof, ndof*sz1); // grad_work[k] has derivative in kth direction for each DOF. // grad_work[0] has d^2phi/dx^2 and d^2phi/dxdy terms and // grad_work[1] has d^2phi/dydx and d^2phi/dy2 terms for each dof if (i == 0) { Mult(*grad_phys_dir[k], grad_phys_work, grad_work); } else { Mult(*grad_phys_dir[k], *dkphi_dxk[i-1], grad_work); } // Now we must place columns for each dof together so that they are // in order: d^2phi/dx^2, d^2phi/dxdy, d^2phi/dydx, d^2phi/dy2. for (int j = 0; j < ndof; j++) { for (int d = 0; d < loc_col_per_dof; d++) { Vector col; grad_work.GetColumn(j*loc_col_per_dof+d, col); dkphi_dxk[i]->SetCol(j*tot_col_per_dof+k*loc_col_per_dof+d, col); } } } } for (int i = 0; i < grad_phys_dir.Size(); i++) { delete grad_phys_dir[i]; } Factorial.SetSize(nterms); Factorial(0) = 2; for (int i = 1; i < nterms; i++) { Factorial(i) = Factorial(i-1)*(i+2); } } DenseMatrix q_hess_dn(dim, ndof); Vector q_hess_dn_work(q_hess_dn.GetData(), ndof*dim); Vector q_hess_dot_d(ndof); Vector D(vD->GetVDim()); // Assemble: -< \nabla u.n, w > // -< u + \nabla u.d + h.o.t, \nabla w.n> // -<alpha h^{-1} (u + \nabla u.d + h.o.t), w + \nabla w.d + h.o.t> for (int p = 0; p < ir->GetNPoints(); p++) { const IntegrationPoint &ip = ir->IntPoint(p); // Set the integration point in the face and the neighboring elements Trans.SetAllIntPoints(&ip); // Access the neighboring elements' integration points // Note: eip2 will only contain valid data if Elem2 exists const IntegrationPoint &eip1 = Trans.GetElement1IntPoint(); const IntegrationPoint &eip2 = Trans.GetElement2IntPoint(); if (dim == 1) { nor(0) = 2*eip1.x - 1.0; } else { // Note: this normal accounts for the weight of the surface transformation // Jacobian i.e. nor = nhat*det(J) CalcOrtho(Trans.Jacobian(), nor); } vD->Eval(D, Trans, ip); // Make sure the normal vector is pointing outside the domain. if (!elem1f) { nor *= -1; } if (elem1f) { el1.CalcShape(eip1, shape); el1.CalcDShape(eip1, dshape); w = ip.weight/Trans.Elem1->Weight(); CalcAdjugate(Trans.Elem1->Jacobian(), adjJ); } else { el1.CalcShape(eip2, shape); el1.CalcDShape(eip2, dshape); w = ip.weight/Trans.Elem2->Weight(); CalcAdjugate(Trans.Elem2->Jacobian(), adjJ); } ni.Set(w, nor); // alpha_k*nor/det(J) adjJ.Mult(ni, nh); dshape.Mult(nh, dshapedn); // dphi/dn * Jinv * alpha_k * nor // <grad u.n, w> - Term 2 AddMult_a_VWt(-1., shape, dshapedn, temp_elmat); if (elem1f) { el1.CalcPhysDShape(*(Trans.Elem1), dshapephys); } else { el1.CalcPhysDShape(*(Trans.Elem2), dshapephys); } // dphi/dx dshapephys.Mult(D, dshapephysdd); // dphi/dx.D); q_hess_dot_d = 0.; for (int i = 0; i < nterms; i++) { int sz1 = pow(dim, i+1); DenseMatrix T1(dim, ndof*sz1); Vector T1_wrk(T1.GetData(), dim*ndof*sz1); dkphi_dxk[i]->MultTranspose(shape, T1_wrk); DenseMatrix T2; Vector T2_wrk; for (int j = 0; j < i+1; j++) { int sz2 = pow(dim, i-j); T2.SetSize(dim, ndof*sz2); T2_wrk.SetDataAndSize(T2.GetData(), dim*ndof*sz2); T1.MultTranspose(D, T2_wrk); T1 = T2; } Vector q_hess_dot_d_work(ndof); T1.MultTranspose(D, q_hess_dot_d_work); q_hess_dot_d_work *= 1./Factorial(i); q_hess_dot_d += q_hess_dot_d_work; } wrk = shape; wrk += dshapephysdd; wrk += q_hess_dot_d; // <u + grad u.d + h.o.t, grad w.n> - Term 3 AddMult_a_VWt(-1., dshapedn, wrk, temp_elmat); double hinvdx; if (elem1f) { hinvdx = nor*nor/Trans.Elem1->Weight(); } else { hinvdx = nor*nor/Trans.Elem2->Weight(); } w = ip.weight*alpha*hinvdx; // + <alpha * hinv * u + grad u.d + h.o.t, w + grad w.d + h.o.t> - Term 4 AddMult_a_VVt(w, wrk, temp_elmat); int offset = elem1f ? 0 : ndof1; elmat.CopyMN(temp_elmat, offset, offset); } // p < ir->GetNPoints() for (int i = 0; i < dkphi_dxk.Size(); i++) { delete dkphi_dxk[i]; } } void SBM2DirichletLFIntegrator::AssembleRHSElementVect( const FiniteElement &el, ElementTransformation &Tr, Vector &elvect) { mfem_error("SBM2DirichletLFIntegrator::AssembleRHSElementVect"); } void SBM2DirichletLFIntegrator::AssembleRHSElementVect( const FiniteElement &el, FaceElementTransformations &Tr, Vector &elvect) { AssembleRHSElementVect(el, el, Tr, elvect); } void SBM2DirichletLFIntegrator::AssembleRHSElementVect( const FiniteElement &el1, const FiniteElement &el2, FaceElementTransformations &Tr, Vector &elvect) { int dim, ndof1, ndof2, ndof, ndoftotal; double w; Vector temp_elvect; dim = el1.GetDim(); ndof1 = el1.GetDof(); ndof2 = el2.GetDof(); ndoftotal = ndof1 + ndof2; if (Tr.Elem2No >= NEproc || Tr.ElementType == ElementTransformation::BDR_FACE) { ndoftotal = ndof1; } elvect.SetSize(ndoftotal); elvect = 0.0; bool elem1f = true; int elem1 = Tr.Elem1No, elem2 = Tr.Elem2No, marker1 = (*elem_marker)[elem1]; int marker2; if (Tr.Elem2No >= NEproc) { marker2 = (*elem_marker)[NEproc+par_shared_face_count]; par_shared_face_count++; } else if (Tr.ElementType == ElementTransformation::BDR_FACE) { marker2 = marker1; } else { marker2 = (*elem_marker)[elem2]; } if (!include_cut_cell) { // 1 is inside and 2 is cut or 1 is a boundary element. if ( marker1 == ShiftedFaceMarker::SBElementType::INSIDE && (marker2 == ls_cut_marker || Tr.ElementType == ElementTransformation::BDR_FACE)) { elem1f = true; ndof = ndof1; } // 1 is cut, 2 is inside else if (marker1 == ls_cut_marker && marker2 == ShiftedFaceMarker::SBElementType::INSIDE) { if (Tr.Elem2No >= NEproc) { return; } elem1f = false; ndof = ndof2; } else { return; } } else { // 1 is cut and 2 is outside or 1 is a boundary element. if (marker1 == ls_cut_marker && (marker2 == ShiftedFaceMarker::SBElementType::OUTSIDE || Tr.ElementType == ElementTransformation::BDR_FACE)) { elem1f = true; ndof = ndof1; } // 1 is outside, 2 is cut else if (marker1 == ShiftedFaceMarker::SBElementType::OUTSIDE && marker2 == ls_cut_marker) { if (Tr.Elem2No >= NEproc) { return; } elem1f = false; ndof = ndof2; } else { return; } } temp_elvect.SetSize(ndof); temp_elvect = 0.0; nor.SetSize(dim); nh.SetSize(dim); ni.SetSize(dim); adjJ.SetSize(dim); shape.SetSize(ndof); dshape.SetSize(ndof, dim); dshape_dd.SetSize(ndof); dshape_dn.SetSize(ndof); const IntegrationRule *ir = IntRule; if (ir == NULL) { // a simple choice for the integration order; is this OK? int order = elem1f ? 4*el1.GetOrder() : 4*el2.GetOrder(); ir = &IntRules.Get(Tr.GetGeometryType(), order); } Array<DenseMatrix *> dkphi_dxk; DenseMatrix grad_phys; Vector Factorial; Array<DenseMatrix *> grad_phys_dir; if (nterms > 0) { if (elem1f) { el1.ProjectGrad(el1, *Tr.Elem1, grad_phys); } else { el2.ProjectGrad(el2, *Tr.Elem2, grad_phys); } DenseMatrix grad_work; grad_phys_dir.SetSize(dim); // NxN matrix for derivative in each direction for (int i = 0; i < dim; i++) { grad_phys_dir[i] = new DenseMatrix(ndof, ndof); grad_phys_dir[i]->CopyRows(grad_phys, i*ndof, (i+1)*ndof-1); } DenseMatrix grad_phys_work = grad_phys; grad_phys_work.SetSize(ndof, ndof*dim); dkphi_dxk.SetSize(nterms); for (int i = 0; i < nterms; i++) { int sz1 = pow(dim, i+1); dkphi_dxk[i] = new DenseMatrix(ndof, ndof*sz1*dim); int loc_col_per_dof = sz1; for (int k = 0; k < dim; k++) { grad_work.SetSize(ndof, ndof*sz1); // grad_work[k] has derivative in kth direction for each DOF. // grad_work[0] has d^2phi/dx^2 and d^2phi/dxdy terms and // grad_work[1] has d^2phi/dydx and d^2phi/dy2 terms for each dof if (i == 0) { Mult(*grad_phys_dir[k], grad_phys_work, grad_work); } else { Mult(*grad_phys_dir[k], *dkphi_dxk[i-1], grad_work); } // Now we must place columns for each dof together so that they are // in order: d^2phi/dx^2, d^2phi/dxdy, d^2phi/dydx, d^2phi/dy2. for (int j = 0; j < ndof; j++) { for (int d = 0; d < loc_col_per_dof; d++) { Vector col; int tot_col_per_dof = loc_col_per_dof*dim; grad_work.GetColumn(j*loc_col_per_dof+d, col); dkphi_dxk[i]->SetCol(j*tot_col_per_dof+k*loc_col_per_dof+d, col); } } } } for (int i = 0; i < grad_phys_dir.Size(); i++) { delete grad_phys_dir[i]; } Factorial.SetSize(nterms); Factorial(0) = 2; for (int i = 1; i < nterms; i++) { Factorial(i) = Factorial(i-1)*(i+2); } } DenseMatrix q_hess_dn(dim, ndof); Vector q_hess_dn_work(q_hess_dn.GetData(), ndof*dim); Vector q_hess_dot_d(ndof); Vector D(vD->GetVDim()); Vector wrk = shape; // Assemble: -< u_D, \nabla w.n > // -<alpha h^{-1} u_D, w + \nabla w.d + h.o.t> for (int p = 0; p < ir->GetNPoints(); p++) { const IntegrationPoint &ip = ir->IntPoint(p); // Set the integration point in the face and the neighboring element Tr.SetAllIntPoints(&ip); // Access the neighboring element's integration point const IntegrationPoint &eip = Tr.GetElement1IntPoint(); const IntegrationPoint &eip1 = Tr.GetElement1IntPoint(); const IntegrationPoint &eip2 = Tr.GetElement2IntPoint(); if (dim == 1) { nor(0) = 2*eip.x - 1.0; } else { CalcOrtho(Tr.Jacobian(), nor); } vD->Eval(D, Tr, ip); // Make sure the normal vector is pointing outside the domain. if (!elem1f) { nor *= -1; } double hinvdx; if (elem1f) { el1.CalcShape(eip1, shape); el1.CalcDShape(eip1, dshape); hinvdx =nor*nor/Tr.Elem1->Weight(); w = ip.weight * uD->Eval(Tr, ip, D) / Tr.Elem1->Weight(); CalcAdjugate(Tr.Elem1->Jacobian(), adjJ); } else { el2.CalcShape(eip2, shape); el2.CalcDShape(eip2, dshape); hinvdx = nor*nor/Tr.Elem2->Weight(); w = ip.weight * uD->Eval(Tr, ip, D) / Tr.Elem2->Weight(); CalcAdjugate(Tr.Elem2->Jacobian(), adjJ); } ni.Set(w, nor); adjJ.Mult(ni, nh); dshape.Mult(nh, dshape_dn); temp_elvect.Add(-1., dshape_dn); // T2 double jinv; if (elem1f) { w = ip.weight * uD->Eval(Tr, ip, D) * alpha * hinvdx; jinv = 1./Tr.Elem1->Weight(); } else { w = ip.weight * uD->Eval(Tr, ip, D) * alpha * hinvdx; jinv = 1./Tr.Elem2->Weight(); } adjJ.Mult(D, nh); nh *= jinv; dshape.Mult(nh, dshape_dd); q_hess_dot_d = 0.; for (int i = 0; i < nterms; i++) { int sz1 = pow(dim, i+1); DenseMatrix T1(dim, ndof*sz1); Vector T1_wrk(T1.GetData(), dim*ndof*sz1); dkphi_dxk[i]->MultTranspose(shape, T1_wrk); DenseMatrix T2; Vector T2_wrk; for (int j = 0; j < i+1; j++) { int sz2 = pow(dim, i-j); T2.SetSize(dim, ndof*sz2); T2_wrk.SetDataAndSize(T2.GetData(), dim*ndof*sz2); T1.MultTranspose(D, T2_wrk); T1 = T2; } Vector q_hess_dot_d_work(ndof); T1.MultTranspose(D, q_hess_dot_d_work); q_hess_dot_d_work *= 1./Factorial(i); q_hess_dot_d += q_hess_dot_d_work; } wrk = shape; wrk += dshape_dd; // \grad w .d wrk += q_hess_dot_d; temp_elvect.Add(w, wrk); // <u, gradw.d> int offset = elem1f ? 0 : ndof1; for (int i = 0; i < temp_elvect.Size(); i++) { elvect(i+offset) = temp_elvect(i); } } for (int i = 0; i < dkphi_dxk.Size(); i++) { delete dkphi_dxk[i]; } } void SBM2NeumannIntegrator::AssembleFaceMatrix( const FiniteElement &el1, const FiniteElement &el2, FaceElementTransformations &Trans, DenseMatrix &elmat) { int dim, ndof1, ndof2, ndof, ndoftotal; double w; DenseMatrix temp_elmat; dim = el1.GetDim(); ndof1 = el1.GetDof(); ndof2 = el2.GetDof(); ndoftotal = Trans.ElementType == ElementTransformation::BDR_FACE ? ndof1 : ndof1 + ndof2; elmat.SetSize(ndoftotal); elmat = 0.0; bool elem1f = true; // flag indicating whether Trans.Elem1No is part of the // surrogate domain or not. int elem1 = Trans.Elem1No, elem2 = Trans.Elem2No, marker1 = (*elem_marker)[elem1]; int marker2; if (Trans.Elem2No >= NEproc) { marker2 = (*elem_marker)[NEproc+par_shared_face_count]; par_shared_face_count++; } else if (Trans.ElementType == ElementTransformation::BDR_FACE) { marker2 = marker1; } else { marker2 = (*elem_marker)[elem2]; } if (!include_cut_cell) { // 1 is inside and 2 is cut or 1 is a boundary element. if (marker1 == ShiftedFaceMarker::SBElementType::INSIDE && (cut_marker.Find(marker2) != -1 || Trans.ElementType == ElementTransformation::BDR_FACE)) { elem1f = true; } // 1 is cut, 2 is inside else if (cut_marker.Find(marker1) != -1 && marker2 == ShiftedFaceMarker::SBElementType::INSIDE) { if (Trans.Elem2No >= NEproc) { return; } elem1f = false; } else { return; } } else { // 1 is cut and 2 is outside or 1 is a boundary element. if (cut_marker.Find(marker1) != -1 && (marker2 == ShiftedFaceMarker::SBElementType::OUTSIDE || Trans.ElementType == ElementTransformation::BDR_FACE)) { elem1f = true; } // 1 is outside, 2 is cut else if (marker1 == ShiftedFaceMarker::SBElementType::OUTSIDE && cut_marker.Find(marker2) != -1) { if (Trans.Elem2No >= NEproc) { return; } elem1f = false; } else { return; } } ndof = elem1f ? ndof1 : ndof2; temp_elmat.SetSize(ndof); temp_elmat = 0.; nor.SetSize(dim); nh.SetSize(dim); ni.SetSize(dim); adjJ.SetSize(dim); shape.SetSize(ndof); dshape.SetSize(ndof, dim); dshapedn.SetSize(ndof); Vector wrk = shape; const IntegrationRule *ir = IntRule; if (ir == NULL) { int order = elem1f ? 4*el1.GetOrder() : 4*el2.GetOrder(); ir = &IntRules.Get(Trans.GetGeometryType(), order); } Array<DenseMatrix *> dkphi_dxk; DenseMatrix grad_phys; Vector Factorial; Array<DenseMatrix *> grad_phys_dir; if (nterms > 0) { if (elem1f) { el1.ProjectGrad(el1, *Trans.Elem1, grad_phys); } else { el2.ProjectGrad(el2, *Trans.Elem2, grad_phys); } DenseMatrix grad_work; grad_phys_dir.SetSize(dim); // NxN matrices for derivative in each direction for (int i = 0; i < dim; i++) { grad_phys_dir[i] = new DenseMatrix(ndof, ndof); grad_phys_dir[i]->CopyRows(grad_phys, i*ndof, (i+1)*ndof-1); } DenseMatrix grad_phys_work = grad_phys; grad_phys_work.SetSize(ndof, ndof*dim); dkphi_dxk.SetSize(nterms); for (int i = 0; i < nterms; i++) { int sz1 = pow(dim, i+1); dkphi_dxk[i] = new DenseMatrix(ndof, ndof*sz1*dim); int loc_col_per_dof = sz1; int tot_col_per_dof = loc_col_per_dof*dim; for (int k = 0; k < dim; k++) { grad_work.SetSize(ndof, ndof*sz1); // grad_work[k] has derivative in kth direction for each DOF. // grad_work[0] has d^2phi/dx^2 and d^2phi/dxdy terms and // grad_work[1] has d^2phi/dydx and d^2phi/dy2 terms for each dof if (i == 0) { Mult(*grad_phys_dir[k], grad_phys_work, grad_work); } else { Mult(*grad_phys_dir[k], *dkphi_dxk[i-1], grad_work); } // Now we must place columns for each dof together so that they are // in order: d^2phi/dx^2, d^2phi/dxdy, d^2phi/dydx, d^2phi/dy2. for (int j = 0; j < ndof; j++) { for (int d = 0; d < loc_col_per_dof; d++) { Vector col; grad_work.GetColumn(j*loc_col_per_dof+d, col); dkphi_dxk[i]->SetCol(j*tot_col_per_dof+k*loc_col_per_dof+d, col); } } } } for (int i = 0; i < grad_phys_dir.Size(); i++) { delete grad_phys_dir[i]; } Factorial.SetSize(nterms); Factorial(0) = 1; for (int i = 1; i < nterms; i++) { Factorial(i) = Factorial(i-1)*(i+1); } } DenseMatrix q_hess_dn(dim, ndof); Vector q_hess_dn_work(q_hess_dn.GetData(), ndof*dim); Vector q_hess_dot_d_nhat(ndof); Vector D(vD->GetVDim()); Vector Nhat(vN->GetVDim()); // Assemble: <nabla(nabla u).d.nhat (n.nhat), w> for (int p = 0; p < ir->GetNPoints(); p++) { const IntegrationPoint &ip = ir->IntPoint(p); // Set the integration point in the face and the neighboring elements Trans.SetAllIntPoints(&ip); // Access the neighboring elements' integration points // Note: eip2 will only contain valid data if Elem2 exists const IntegrationPoint &eip1 = Trans.GetElement1IntPoint(); const IntegrationPoint &eip2 = Trans.GetElement2IntPoint(); if (dim == 1) { nor(0) = 2*eip1.x - 1.0; } else { // Note: this normal accounts for the weight of the surface transformation // Jacobian i.e. nor = nhat*det(J) CalcOrtho(Trans.Jacobian(), nor); } vD->Eval(D, Trans, ip); vN->Eval(Nhat, Trans, ip, D); // Make sure the normal vector is pointing outside the domain. if (!elem1f) { nor *= -1; } if (elem1f) { el1.CalcShape(eip1, shape); el1.CalcDShape(eip1, dshape); w = ip.weight/Trans.Elem1->Weight(); CalcAdjugate(Trans.Elem1->Jacobian(), adjJ); } else { el1.CalcShape(eip2, shape); el1.CalcDShape(eip2, dshape); w = ip.weight/Trans.Elem2->Weight(); CalcAdjugate(Trans.Elem2->Jacobian(), adjJ); } ni.Set(w, nor); // nor/det(J) adjJ.Mult(ni, nh); dshape.Mult(nh, dshapedn); //dphi/dn * Jinv * nor // -<w, grad u.n> - Term 2 AddMult_a_VWt(-1., shape, dshapedn, temp_elmat); // <w, (grad u.nhat)nhat.n // Here nhat is the normal vector at true boundary and n is the normal // vector at shifted boundary double n_dot_ntilde = nor*Nhat; ni.Set(w, Nhat); adjJ.Mult(ni, nh); dshape.Mult(nh, dshapedn); dshapedn *= n_dot_ntilde; AddMult_a_VWt(1., shape, dshapedn, temp_elmat); q_hess_dot_d_nhat = 0.; for (int i = 0; i < nterms; i++) { int sz1 = pow(dim, i+1); DenseMatrix T1(dim, ndof*sz1); Vector T1_wrk(T1.GetData(), dim*ndof*sz1); dkphi_dxk[i]->MultTranspose(shape, T1_wrk); DenseMatrix T2; Vector T2_wrk; for (int j = 0; j < i+1; j++) { int sz2 = pow(dim, i-j); T2.SetSize(dim, ndof*sz2); T2_wrk.SetDataAndSize(T2.GetData(), dim*ndof*sz2); T1.MultTranspose(D, T2_wrk); T1 = T2; } Vector q_hess_dot_d_work(ndof); T1.MultTranspose(Nhat, q_hess_dot_d_work); q_hess_dot_d_work *= 1./Factorial(i); q_hess_dot_d_nhat += q_hess_dot_d_work; } wrk = q_hess_dot_d_nhat; wrk *= ip.weight * n_dot_ntilde; AddMult_a_VWt(1., shape, wrk, temp_elmat); int offset = elem1f ? 0 : ndof1; elmat.CopyMN(temp_elmat, offset, offset); } //p < ir->GetNPoints() for (int i = 0; i < dkphi_dxk.Size(); i++) { delete dkphi_dxk[i]; } } void SBM2NeumannLFIntegrator::AssembleRHSElementVect( const FiniteElement &el, ElementTransformation &Tr, Vector &elvect) { mfem_error("SBM2NeumannLFIntegrator::AssembleRHSElementVect"); } void SBM2NeumannLFIntegrator::AssembleRHSElementVect( const FiniteElement &el, FaceElementTransformations &Tr, Vector &elvect) { AssembleRHSElementVect(el, el, Tr, elvect); } void SBM2NeumannLFIntegrator::AssembleRHSElementVect( const FiniteElement &el1, const FiniteElement &el2, FaceElementTransformations &Tr, Vector &elvect) { int dim, ndof1, ndof2, ndof, ndoftotal; double w; Vector temp_elvect; dim = el1.GetDim(); ndof1 = el1.GetDof(); ndof2 = el2.GetDof(); ndoftotal = ndof1 + ndof2; if (Tr.Elem2No >= NEproc || Tr.ElementType == ElementTransformation::BDR_FACE) { ndoftotal = ndof1; } elvect.SetSize(ndoftotal); elvect = 0.0; bool elem1f = true; int elem1 = Tr.Elem1No, elem2 = Tr.Elem2No, marker1 = (*elem_marker)[elem1]; int marker2; if (Tr.Elem2No >= NEproc) { marker2 = (*elem_marker)[NEproc+par_shared_face_count]; par_shared_face_count++; } else if (Tr.ElementType == ElementTransformation::BDR_FACE) { marker2 = marker1; } else { marker2 = (*elem_marker)[elem2]; } if (!include_cut_cell) { // 1 is inside and 2 is cut or 1 is a boundary element. if ( marker1 == ShiftedFaceMarker::SBElementType::INSIDE && (marker2 == ls_cut_marker || Tr.ElementType == ElementTransformation::BDR_FACE)) { elem1f = true; ndof = ndof1; } // 1 is cut, 2 is inside else if (marker1 == ls_cut_marker && marker2 == ShiftedFaceMarker::SBElementType::INSIDE) { if (Tr.Elem2No >= NEproc) { return; } elem1f = false; ndof = ndof2; } else { return; } } else { // 1 is cut and 2 is outside or 1 is a boundary element. if (marker1 == ls_cut_marker && (marker2 == ShiftedFaceMarker::SBElementType::OUTSIDE || Tr.ElementType == ElementTransformation::BDR_FACE)) { elem1f = true; ndof = ndof1; } // 1 is outside, 2 is cut else if (marker1 == ShiftedFaceMarker::SBElementType::OUTSIDE && marker2 == ls_cut_marker) { if (Tr.Elem2No >= NEproc) { return; } elem1f = false; ndof = ndof2; } else { return; } } temp_elvect.SetSize(ndof); temp_elvect = 0.0; nor.SetSize(dim); shape.SetSize(ndof); const IntegrationRule *ir = IntRule; if (ir == NULL) { // a simple choice for the integration order; is this OK? int order = elem1f ? 4*el1.GetOrder() : 4*el2.GetOrder(); ir = &IntRules.Get(Tr.GetGeometryType(), order); } Vector D(vD->GetVDim()); Vector Nhat(vN->GetVDim()); Vector wrk = shape; for (int p = 0; p < ir->GetNPoints(); p++) { const IntegrationPoint &ip = ir->IntPoint(p); // Set the integration point in the face and the neighboring element Tr.SetAllIntPoints(&ip); // Access the neighboring element's integration point const IntegrationPoint &eip = Tr.GetElement1IntPoint(); const IntegrationPoint &eip1 = Tr.GetElement1IntPoint(); const IntegrationPoint &eip2 = Tr.GetElement2IntPoint(); if (dim == 1) { nor(0) = 2*eip.x - 1.0; } else { CalcOrtho(Tr.Jacobian(), nor); } vD->Eval(D, Tr, ip); vN->Eval(Nhat, Tr, ip, D); // Make sure the normal vector is pointing outside the domain. if (!elem1f) { nor *= -1; } if (elem1f) { el1.CalcShape(eip1, shape); w = ip.weight * uN->Eval(Tr, ip, D); } else { el2.CalcShape(eip2, shape); w = ip.weight * uN->Eval(Tr, ip, D); } double n_dot_ntilde = nor*Nhat; wrk.Set(n_dot_ntilde*w, shape); //<w, (nhat.n)t_n) temp_elvect.Add(1., wrk); int offset = elem1f ? 0 : ndof1; for (int i = 0; i < temp_elvect.Size(); i++) { elvect(i+offset) = temp_elvect(i); } } } }
27.883469
83
0.558137
xj361685640
fce371d8f99c59106fb017341ccbaab53401636d
7,529
cc
C++
content/browser/renderer_host/pepper/pepper_file_system_browser_host.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/renderer_host/pepper/pepper_file_system_browser_host.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/renderer_host/pepper/pepper_file_system_browser_host.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/pepper/pepper_file_system_browser_host.h" #include "base/bind.h" #include "base/callback.h" #include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/storage_partition.h" #include "ppapi/c/pp_errors.h" #include "ppapi/host/dispatch_host_message.h" #include "ppapi/host/ppapi_host.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/shared_impl/file_type_conversion.h" #include "webkit/browser/fileapi/file_system_context.h" #include "webkit/browser/fileapi/file_system_operation_runner.h" #include "webkit/common/fileapi/file_system_util.h" namespace content { namespace { // TODO(teravest): Move this function to be shared and public in fileapi. bool LooksLikeAGuid(const std::string& fsid) { const size_t kExpectedFsIdSize = 32; if (fsid.size() != kExpectedFsIdSize) return false; for (std::string::const_iterator it = fsid.begin(); it != fsid.end(); ++it) { if (('A' <= *it && *it <= 'F') || ('0' <= *it && *it <= '9')) continue; return false; } return true; } scoped_refptr<fileapi::FileSystemContext> GetFileSystemContextFromRenderId(int render_process_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); RenderProcessHost* render_process_host = RenderProcessHost::FromID(render_process_id); if (!render_process_host) return NULL; StoragePartition* storage_partition = render_process_host->GetStoragePartition(); if (!storage_partition) return NULL; return storage_partition->GetFileSystemContext(); } } // namespace PepperFileSystemBrowserHost::PepperFileSystemBrowserHost(BrowserPpapiHost* host, PP_Instance instance, PP_Resource resource, PP_FileSystemType type) : ResourceHost(host->GetPpapiHost(), instance, resource), browser_ppapi_host_(host), type_(type), opened_(false), fs_context_(NULL), called_open_(false), weak_factory_(this) { } PepperFileSystemBrowserHost::~PepperFileSystemBrowserHost() { // TODO(teravest): Create a FileSystemOperationRunner // per-PepperFileSystemBrowserHost, force users of this FileSystem to use it, // and call Shutdown() on it here. } int32_t PepperFileSystemBrowserHost::OnResourceMessageReceived( const IPC::Message& msg, ppapi::host::HostMessageContext* context) { IPC_BEGIN_MESSAGE_MAP(PepperFileSystemBrowserHost, msg) PPAPI_DISPATCH_HOST_RESOURCE_CALL( PpapiHostMsg_FileSystem_Open, OnHostMsgOpen) PPAPI_DISPATCH_HOST_RESOURCE_CALL( PpapiHostMsg_FileSystem_InitIsolatedFileSystem, OnHostMsgInitIsolatedFileSystem) IPC_END_MESSAGE_MAP() return PP_ERROR_FAILED; } bool PepperFileSystemBrowserHost::IsFileSystemHost() { return true; } int32_t PepperFileSystemBrowserHost::OnHostMsgOpen( ppapi::host::HostMessageContext* context, int64_t /* unused */) { // TODO(raymes): The file system size is now unused by FileSystemDispatcher. // Figure out why. Why is the file system size signed? // Not allow multiple opens. if (called_open_) return PP_ERROR_INPROGRESS; called_open_ = true; fileapi::FileSystemType file_system_type; switch (type_) { case PP_FILESYSTEMTYPE_LOCALTEMPORARY: file_system_type = fileapi::kFileSystemTypeTemporary; break; case PP_FILESYSTEMTYPE_LOCALPERSISTENT: file_system_type = fileapi::kFileSystemTypePersistent; break; case PP_FILESYSTEMTYPE_EXTERNAL: file_system_type = fileapi::kFileSystemTypeExternal; break; default: return PP_ERROR_FAILED; } int render_process_id = 0; int unused; if (!browser_ppapi_host_->GetRenderViewIDsForInstance(pp_instance(), &render_process_id, &unused)) { return PP_ERROR_FAILED; } BrowserThread::PostTaskAndReplyWithResult( BrowserThread::UI, FROM_HERE, base::Bind(&GetFileSystemContextFromRenderId, render_process_id), base::Bind(&PepperFileSystemBrowserHost::GotFileSystemContext, weak_factory_.GetWeakPtr(), context->MakeReplyMessageContext(), file_system_type)); return PP_OK_COMPLETIONPENDING; } void PepperFileSystemBrowserHost::GotFileSystemContext( ppapi::host::ReplyMessageContext reply_context, fileapi::FileSystemType file_system_type, scoped_refptr<fileapi::FileSystemContext> fs_context) { if (!fs_context.get()) { OpenFileSystemComplete( reply_context, base::PLATFORM_FILE_ERROR_FAILED, std::string(), GURL()); return; } GURL origin = browser_ppapi_host_->GetDocumentURLForInstance( pp_instance()).GetOrigin(); fs_context->OpenFileSystem(origin, file_system_type, fileapi::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, base::Bind(&PepperFileSystemBrowserHost::OpenFileSystemComplete, weak_factory_.GetWeakPtr(), reply_context)); fs_context_ = fs_context; } void PepperFileSystemBrowserHost::GotIsolatedFileSystemContext( ppapi::host::ReplyMessageContext reply_context, scoped_refptr<fileapi::FileSystemContext> fs_context) { fs_context_ = fs_context; if (fs_context.get()) reply_context.params.set_result(PP_OK); else reply_context.params.set_result(PP_ERROR_FAILED); host()->SendReply(reply_context, PpapiPluginMsg_FileSystem_InitIsolatedFileSystemReply()); } void PepperFileSystemBrowserHost::OpenFileSystemComplete( ppapi::host::ReplyMessageContext reply_context, base::PlatformFileError error, const std::string& /* unused */, const GURL& root) { int32 pp_error = ppapi::PlatformFileErrorToPepperError(error); if (pp_error == PP_OK) { opened_ = true; root_url_ = root; } reply_context.params.set_result(pp_error); host()->SendReply(reply_context, PpapiPluginMsg_FileSystem_OpenReply()); } int32_t PepperFileSystemBrowserHost::OnHostMsgInitIsolatedFileSystem( ppapi::host::HostMessageContext* context, const std::string& fsid) { called_open_ = true; // Do a sanity check. if (!LooksLikeAGuid(fsid)) return PP_ERROR_BADARGUMENT; const GURL& url = browser_ppapi_host_->GetDocumentURLForInstance(pp_instance()); root_url_ = GURL(fileapi::GetIsolatedFileSystemRootURIString( url.GetOrigin(), fsid, "crxfs")); opened_ = true; int render_process_id = 0; int unused; if (!browser_ppapi_host_->GetRenderViewIDsForInstance(pp_instance(), &render_process_id, &unused)) { return PP_ERROR_FAILED; } BrowserThread::PostTaskAndReplyWithResult( BrowserThread::UI, FROM_HERE, base::Bind(&GetFileSystemContextFromRenderId, render_process_id), base::Bind(&PepperFileSystemBrowserHost::GotIsolatedFileSystemContext, weak_factory_.GetWeakPtr(), context->MakeReplyMessageContext())); return PP_OK_COMPLETIONPENDING; } } // namespace content
35.514151
81
0.704078
kurli
fce515526f796e03db673d3b9aafc044fb77f35e
233
cpp
C++
test/main.cpp
MaLarsson/umlaut
b02222127a9e7362b57403f58a8519cd8b6bf826
[ "BSL-1.0" ]
1
2018-06-24T13:47:42.000Z
2018-06-24T13:47:42.000Z
test/main.cpp
MaLarsson/umlaut
b02222127a9e7362b57403f58a8519cd8b6bf826
[ "BSL-1.0" ]
6
2018-09-25T10:56:38.000Z
2018-11-01T15:30:08.000Z
test/main.cpp
MaLarsson/umlaut
b02222127a9e7362b57403f58a8519cd8b6bf826
[ "BSL-1.0" ]
null
null
null
// Copyright Marcus Larsson 2018 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp>
29.125
81
0.772532
MaLarsson
fce574e659d0b82b5776bc44304c12270e0f1fde
598
cpp
C++
test/srpc/RpcCommandTest.cpp
mark-online/sne
92190c78a1710778acf16dd3a83af064db5c269b
[ "MIT" ]
null
null
null
test/srpc/RpcCommandTest.cpp
mark-online/sne
92190c78a1710778acf16dd3a83af064db5c269b
[ "MIT" ]
null
null
null
test/srpc/RpcCommandTest.cpp
mark-online/sne
92190c78a1710778acf16dd3a83af064db5c269b
[ "MIT" ]
null
null
null
#include "SrpcTestPCH.h" #include "DummyRpcCommand.h" #include <sne/test/StreamFixture.h> using namespace sne; using namespace sne::srpc; /** * @class RpcCommandTest * * RpcCommand test */ class RpcCommandTest : public test::BitStreamFixture { }; TEST_F(RpcCommandTest, testMarshal) { DummyRpcCommand rpcCommand(100, -100); rpcCommand.marshal(*ostream_); RRpcId id; id.serialize(*istream_); ASSERT_EQ(rpcCommand.getRpcId().get(), id.get()); int32_t p1; istream_->read(p1); ASSERT_EQ(100, p1); int32_t p2; istream_->read(p2); ASSERT_EQ(-100, p2); }
18.121212
53
0.683946
mark-online
fce84a743286189e8b4c054c752a7df8d32bb883
1,595
cpp
C++
tests/test_bhtool.cpp
butchhoward/bhtool
9d8099aafacb9aeb619298e63c5858ea1f1a5ea4
[ "MIT" ]
null
null
null
tests/test_bhtool.cpp
butchhoward/bhtool
9d8099aafacb9aeb619298e63c5858ea1f1a5ea4
[ "MIT" ]
null
null
null
tests/test_bhtool.cpp
butchhoward/bhtool
9d8099aafacb9aeb619298e63c5858ea1f1a5ea4
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include <bhtool/bhtool.hpp> #include <bhtool/stderrred.hpp> #include <bhtool/repo.hpp> #include "utils_test.hpp" using namespace bhtool; int some_command_fn(int, char *[]) { return 99; }; TEST( utilities, find_cmd_function_from_command ) { Commands cmds = { {std::string("some_command"), some_command_fn} }; auto actual = find_command("some_command", cmds); EXPECT_EQ(getStdFnAddress(actual), (size_t)&some_command_fn); } TEST( utilities, find_cmd_function_invalid_command_gives_usage ) { Commands cmds = { {std::string("some_command"), some_command_fn} }; auto actual = find_command("some_other_command", cmds); EXPECT_EQ(getStdFnAddress(actual), (size_t)&last_ditch_usage); } TEST( utilities, help_cmd_is_usage ) { auto actual = find_command("help", bhtool::command_map()); EXPECT_EQ(getStdFnAddress(actual), (size_t)&last_ditch_usage); } TEST( utilities, stderrred_cmd_is_stderrred ) { auto actual = find_command(stderrred::CMD_NAME, bhtool::command_map()); EXPECT_EQ(getStdFnAddress(actual), (size_t)&stderrred::stderrred); } TEST( utilities, repo_cmd_is_repo ) { auto actual = find_command(repo::CMD_NAME, bhtool::command_map()); EXPECT_EQ(getStdFnAddress(actual), (size_t)&repo::repo); } TEST( utilities, venv_cmd_is_not_implemented ) { auto actual = find_command("venv", bhtool::command_map()); EXPECT_EQ(getStdFnAddress(actual), (size_t)&not_implemented_yet); } TEST( bhtool, not_implemented_returns_86 ) { EXPECT_EQ(not_implemented_yet(0, nullptr), 86 ); }
26.583333
75
0.721003
butchhoward
fce867ac3e96f919d6c81e19bebcaaebaaea5805
3,790
cpp
C++
src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/symbol_tables_json_getter.cpp
lukasdurfina/retdec
7d6b8882690ff73c2bd7f209db10c5c091fa0359
[ "MIT", "Zlib", "BSD-3-Clause" ]
1
2020-03-28T02:38:53.000Z
2020-03-28T02:38:53.000Z
src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/symbol_tables_json_getter.cpp
lukasdurfina/retdec
7d6b8882690ff73c2bd7f209db10c5c091fa0359
[ "MIT", "Zlib", "BSD-3-Clause" ]
null
null
null
src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/symbol_tables_json_getter.cpp
lukasdurfina/retdec
7d6b8882690ff73c2bd7f209db10c5c091fa0359
[ "MIT", "Zlib", "BSD-3-Clause" ]
null
null
null
/** * @file src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/symbol_tables_json_getter.cpp * @brief Methods of SymbolTablesJsonGetter class. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include "retdec/utils/string.h" #include "retdec/fileformat/utils/conversions.h" #include "fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/symbol_tables_json_getter.h" using namespace retdec::utils; using namespace retdec::fileformat; namespace fileinfo { /** * Constructor * @param fileInfo Information about file */ SymbolTablesJsonGetter::SymbolTablesJsonGetter(FileInformation &fileInfo) : IterativeSubtitleGetter(fileInfo) { numberOfStructures = fileinfo.getNumberOfStoredSymbolTables(); for(std::size_t i = 0; i < numberOfStructures; ++i) { numberOfStoredRecords.push_back(fileinfo.getNumberOfStoredSymbolsInTable(i)); const auto noOfSpecInfo = fileinfo.getSymbolTableNumberOfStoredSpecialInformation(i); numberOfExtraElements.push_back(noOfSpecInfo); std::vector<std::string> abbv; for(std::size_t j = 0; j < noOfSpecInfo; ++j) { abbv.push_back(fileinfo.getSymbolTableSpecialInformationAbbreviation(i, j)); } extraHeaderElements.push_back(abbv); } header = "symbolTables"; title = "symbolTable"; subtitle = "symbols"; commonHeaderElements.push_back("index"); commonHeaderElements.push_back("name"); commonHeaderElements.push_back("type"); commonHeaderElements.push_back("bind"); commonHeaderElements.push_back("other"); commonHeaderElements.push_back("associatedSectionIndex"); commonHeaderElements.push_back("value"); commonHeaderElements.push_back("address"); commonHeaderElements.push_back("associatedSize"); } std::size_t SymbolTablesJsonGetter::getBasicInfo(std::size_t structIndex, std::vector<std::string> &desc, std::vector<std::string> &info) const { if(structIndex >= numberOfStructures) { return 0; } desc.clear(); info.clear(); desc.push_back("name"); desc.push_back("offset"); desc.push_back("numberOfSymbols"); info.push_back(replaceNonprintableChars(fileinfo.getSymbolTableName(structIndex))); info.push_back(fileinfo.getSymbolTableOffsetStr(structIndex, hexWithPrefix)); info.push_back(fileinfo.getNumberOfDeclaredSymbolsInTableStr(structIndex)); return info.size(); } bool SymbolTablesJsonGetter::getRecord(std::size_t structIndex, std::size_t recIndex, std::vector<std::string> &record) const { if(structIndex >= numberOfStructures || recIndex >= numberOfStoredRecords[structIndex]) { return false; } record.clear(); record.push_back(fileinfo.getSymbolIndexStr(structIndex, recIndex)); record.push_back(replaceNonprintableChars(fileinfo.getSymbolName(structIndex, recIndex))); record.push_back(fileinfo.getSymbolType(structIndex, recIndex)); record.push_back(fileinfo.getSymbolBind(structIndex, recIndex)); record.push_back(fileinfo.getSymbolOther(structIndex, recIndex)); record.push_back(fileinfo.getSymbolLinkToSection(structIndex, recIndex)); record.push_back(fileinfo.getSymbolValueStr(structIndex, recIndex)); record.push_back(fileinfo.getSymbolAddressStr(structIndex, recIndex, hexWithPrefix)); record.push_back(fileinfo.getSymbolSizeStr(structIndex, recIndex)); for(std::size_t i = 0, e = numberOfExtraElements[structIndex]; i < e; ++i) { record.push_back(fileinfo.getSymbolTableSpecialInformationValue(structIndex, i, recIndex)); } return true; } bool SymbolTablesJsonGetter::getFlags(std::size_t structIndex, std::size_t recIndex, std::string &flagsValue, std::vector<std::string> &desc) const { if(structIndex >= numberOfStructures || recIndex >= numberOfStoredRecords[structIndex]) { return false; } flagsValue.clear(); desc.clear(); return true; } } // namespace fileinfo
34.144144
147
0.789446
lukasdurfina
fce99c5e9f0386684f89ca864f27f96e4fbd93a2
2,062
cpp
C++
data/test/cpp/fce99c5e9f0386684f89ca864f27f96e4fbd93a2commands.cpp
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/test/cpp/fce99c5e9f0386684f89ca864f27f96e4fbd93a2commands.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/test/cpp/fce99c5e9f0386684f89ca864f27f96e4fbd93a2commands.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
#include "commands.h" AddModelCommand::AddModelCommand(Model *model) { this->modelIndex = ModelManager::getInstance ()->size(); this->model = model; } void AddModelCommand::undo() { ModelManager::getInstance ()->removeAt(this->modelIndex); } void AddModelCommand::redo() { ModelManager::getInstance ()->insert(this->modelIndex, this->model); } DeleteModelsCommand::DeleteModelsCommand(QList<int> *modelsIndices) { this->modelsIndices = modelsIndices; for(int i = 0; i < modelsIndices->size(); i++) this->modelList.append(ModelManager::getInstance ()->at(modelsIndices->at(i))); } void DeleteModelsCommand::undo() { for(int i = 0; i < modelsIndices->size(); i++) { ModelManager::getInstance ()->insert(modelsIndices->at(i), modelList.at(i)); } } void DeleteModelsCommand::redo() { int iterator = modelsIndices->size(); for(int i = 0; i < iterator; i++) { ModelManager::getInstance ()->removeAt(modelsIndices->at(i)); iterator--; i--; } } MoveModelCommand::MoveModelCommand(Model *model, float xMovement, float yMovement) { this->model = model; this->xMovement = xMovement; this->yMovement = yMovement; } void MoveModelCommand::undo() { this->model->move(-this->xMovement, -this->yMovement, -this->zMovement); } void MoveModelCommand::redo() { this->model->move(this->xMovement, this->yMovement, this->zMovement); } RotateModelCommand::RotateModelCommand(Model *model, float angle) { this->model = model; this->angle = angle; } void RotateModelCommand::undo() { // this->model->rotate(-this->angle); } void RotateModelCommand::redo() { // this->model->rotate(this->angle); } ScaleModelCommand::ScaleModelCommand(Model *model, float xScale, float yScale) { this->model = model; this->xScale = xScale; this->yScale = yScale; } void ScaleModelCommand::undo() { // this->model->scale(1 / this->xScale, 1 / this->yScale); } void ScaleModelCommand::redo() { // this->model->scale(this->xScale, this->yScale); }
21.93617
87
0.662464
harshp8l
fcef673f4dbffb2b5c8405cd483ffefbcadffbeb
1,984
cpp
C++
proton-c/bindings/cpp/src/reactor.cpp
Azure/qpid-proton
fa784b1f3c4f3dbd6b143d5cceda10bf76da23a5
[ "Apache-2.0" ]
2
2020-04-28T13:33:06.000Z
2020-06-01T14:51:05.000Z
proton-c/bindings/cpp/src/reactor.cpp
Azure/qpid-proton
fa784b1f3c4f3dbd6b143d5cceda10bf76da23a5
[ "Apache-2.0" ]
null
null
null
proton-c/bindings/cpp/src/reactor.cpp
Azure/qpid-proton
fa784b1f3c4f3dbd6b143d5cceda10bf76da23a5
[ "Apache-2.0" ]
4
2015-10-17T20:44:45.000Z
2021-06-08T19:00:56.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "proton/reactor.hpp" #include <proton/reactor.h> namespace proton { pn_unique_ptr<reactor> reactor::create() { return pn_unique_ptr<reactor>(reactor::cast(pn_reactor())); } void reactor::run() { pn_reactor_run(pn_cast(this)); } void reactor::start() { pn_reactor_start(pn_cast(this)); } bool reactor::process() { return pn_reactor_process(pn_cast(this)); } void reactor::stop() { pn_reactor_stop(pn_cast(this)); } void reactor::wakeup() { pn_reactor_wakeup(pn_cast(this)); } bool reactor::quiesced() { return pn_reactor_quiesced(pn_cast(this)); } void reactor::yield() { pn_reactor_yield(pn_cast(this)); } duration reactor::timeout() { pn_millis_t tmo = pn_reactor_get_timeout(pn_cast(this)); if (tmo == PN_MILLIS_MAX) return duration::FOREVER; return duration(tmo); } void reactor::timeout(duration timeout) { if (timeout == duration::FOREVER || timeout.milliseconds > PN_MILLIS_MAX) pn_reactor_set_timeout(pn_cast(this), PN_MILLIS_MAX); else pn_reactor_set_timeout(pn_cast(this), timeout.milliseconds); } void reactor::operator delete(void* p) { pn_reactor_free(reinterpret_cast<pn_reactor_t*>(p)); } }
34.206897
77
0.733367
Azure
fcf2d2fc5bb54a81ccb16b50204549b899d35625
2,752
hpp
C++
include/alflib/core/common.hpp
Alfret/AlfLibCpp
15bf07d31b0772a23904967f85495cbb2121f391
[ "MIT" ]
null
null
null
include/alflib/core/common.hpp
Alfret/AlfLibCpp
15bf07d31b0772a23904967f85495cbb2121f391
[ "MIT" ]
9
2019-06-19T19:35:34.000Z
2019-07-03T16:10:20.000Z
include/alflib/core/common.hpp
Alfret/AlfLibCpp
15bf07d31b0772a23904967f85495cbb2121f391
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2019 Filip Björklund // // 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. #pragma once // ========================================================================== // // Headers // ========================================================================== // #include <cstdint> #include <string> // ========================================================================== // // Types // ========================================================================== // /** 8-bit character type **/ using char8 = char; static_assert(sizeof(char8) == 1, "Size of char8 expected to be 1"); #if defined(_WIN32) /** 16-bit character type **/ using char16 = wchar_t; #else /** 16-bit character type **/ using char16 = uint16_t; #endif static_assert(sizeof(char16) == 2, "Size of char8 expected to be 2"); /** 8-bit signed type **/ using s8 = int8_t; /** 8-bit unsigned type **/ using u8 = uint8_t; /** 16-bit signed type **/ using s16 = int16_t; /** 16-bit unsigned type **/ using u16 = uint16_t; /** 32-bit signed type **/ using s32 = int32_t; /** 32-bit unsigned type **/ using u32 = uint32_t; /** 64-bit signed type **/ using s64 = int64_t; /** 8-bit unsigned type **/ using u64 = uint64_t; /** 32-bit floating-point type **/ using f32 = float; /** 64-bit floating-point type **/ using f64 = double; // ========================================================================== // // Functions // ========================================================================== // namespace alflib { /** Returns the value of the specified bit. * \brief Returns bit value. * \param index Index of bit. * \return Value of bit. */ constexpr u64 Bit(u64 index) { return 1ull << index; } }
30.241758
80
0.583576
Alfret
fcf45f872213ed73003eda32c58d01fe6e9e9e6f
36,241
cpp
C++
gb++/src/Sharp/Sharp.cpp
dfrias100/gb-plus-plus
e5c48f18ab24315f1a5c70789cd3c1cae9428baf
[ "MIT" ]
null
null
null
gb++/src/Sharp/Sharp.cpp
dfrias100/gb-plus-plus
e5c48f18ab24315f1a5c70789cd3c1cae9428baf
[ "MIT" ]
null
null
null
gb++/src/Sharp/Sharp.cpp
dfrias100/gb-plus-plus
e5c48f18ab24315f1a5c70789cd3c1cae9428baf
[ "MIT" ]
null
null
null
#include "Sharp.hpp" #include "../Memory/Memory.hpp" #include <iostream> #include <iomanip> Sharp::Sharp(Memory* _MemoryBus) { MemoryBus = _MemoryBus; Suspended = false; HaltBug = false; // These are the register values when the PC is at // $0100 after the boot ROM is unmapped from memory PC = 0x0100; AF = 0x01B0; BC = 0x0013; DE = 0x00D8; HL = 0x014D; SP = 0xFFFE; InterruptMasterEnable = 0x01; //Log.open("execlog.txt", std::ios::trunc | std::ios::binary); } void Sharp::SetFlag(SharpFlags flag, bool set) { if (set) { F |= flag; } else { F &= ~flag; } } uint8_t Sharp::GetFlag(SharpFlags flag) { return (F & flag) > 0 ? 1 : 0; } // Helper Functions void Sharp::DecrementRegister(uint8_t& reg) { if ((reg & 0xF) == 0) { SetFlag(h, 1); } else { SetFlag(h, 0); } reg--; if (reg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 1); } void Sharp::IncrementRegister(uint8_t& reg) { if ((reg & 0xF) == 0xF) { SetFlag(h, 1); } else { SetFlag(h, 0); } reg++; if (reg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); } void Sharp::UnsignedAdd(uint8_t& dest, uint8_t src) { if (src > (0xFF - dest)) { SetFlag(c, 1); } else { SetFlag(c, 0); } temp = (dest & 0xF) + (src & 0xF); if ((temp & 0x10) == 0x10) { SetFlag(h, 1); } else { SetFlag(h, 0); } dest += src; if (dest == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); } void Sharp::UnsignedAddCarry(uint8_t& dest, uint8_t src) { temp = GetFlag(c); if (src > (0xFF - dest) || (temp && (src + dest) == 0xFF)) { SetFlag(c, 1); } else { SetFlag(c, 0); } temp2 = (dest & 0xF) + (src & 0xF) + temp; if ((temp2 & 0x10) == 0x10) { SetFlag(h, 1); } else { SetFlag(h, 0); } dest += src + temp; if (dest == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); } void Sharp::UnsignedAdd16(uint16_t& dest, uint16_t src) { if (src > (0xFFFF - dest)) { SetFlag(c, 1); } else { SetFlag(c, 0); } temp3 = (dest & 0x0FFF) + (src & 0x0FFF); if ((temp3 & 0x1000) == 0x1000) { SetFlag(h, 1); } else { SetFlag(h, 0); } dest += src; SetFlag(n, 0); } void Sharp::Subtract(uint8_t& dest, uint8_t src) { if (src > dest) { SetFlag(c, 1); } else { SetFlag(c, 0); } if ((src & 0xF) > (dest & 0xF)) { SetFlag(h, 1); } else { SetFlag(h, 0); } dest -= src; if (dest == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 1); } void Sharp::SubtractWithCarry(uint8_t& dest, uint8_t src) { temp = GetFlag(c); if (src > dest || (temp && (dest - src) == 0x0)) { SetFlag(c, 1); } else { SetFlag(c, 0); } if ((src & 0xF) > (dest & 0xF) || (temp && ((src & 0xF) - (dest & 0xF)) == 0)) { SetFlag(h, 1); } else { SetFlag(h, 0); } dest -= (src + temp); if (dest == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 1); } void Sharp::RotateLeftCircular(uint8_t& arg) { SetFlag(c, (arg & 0x80) >> 7); arg <<= 1; arg += GetFlag(c); if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::RotateRightCircular(uint8_t& arg) { SetFlag(c, arg & 0x1); arg >>= 1; arg += (GetFlag(c) << 7); if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::RotateLeft(uint8_t& arg) { temp2 = GetFlag(c); SetFlag(c, (arg & 0x80) >> 7); arg <<= 1; arg += temp2; if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::RotateRight(uint8_t& arg) { temp2 = GetFlag(c); SetFlag(c, arg & 0x1); arg >>= 1; arg += (temp2 << 7); if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::ShiftLeft(uint8_t& arg) { SetFlag(c, (arg & 0x80) >> 7); arg <<= 1; if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::ShiftRightArithmetic(uint8_t& arg) { SetFlag(c, arg & 0x01); arg = (arg & 0x80) | (arg >> 1); if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::ShiftRight(uint8_t& arg) { SetFlag(c, arg & 0x01); arg >>= 1; if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); } void Sharp::Swap(uint8_t& arg) { temp2 = arg & 0xF; arg &= 0xF0; arg >>= 4; arg |= (temp2 << 4); if (arg == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); SetFlag(c, 0); } void Sharp::And(uint8_t arg) { A &= arg; if (A == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 1); SetFlag(c, 0); } void Sharp::Xor(uint8_t arg) { A ^= arg; if (A == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); SetFlag(c, 0); } void Sharp::Or(uint8_t arg) { A |= arg; if (A == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(n, 0); SetFlag(h, 0); SetFlag(c, 0); } void Sharp::Bit(uint8_t pos, uint8_t arg) { SetFlag(z, ~(arg >> pos) & 0x1); SetFlag(n, 0); SetFlag(h, 1); } void Sharp::SetBit(uint8_t pos, uint8_t& arg) { arg |= 0x01 << pos; } void Sharp::ResetBit(uint8_t pos, uint8_t& arg) { arg = arg & ~(0x01 << pos); } void Sharp::UNOP() { } // Non 0xCB instructions void Sharp::NOP() { } void Sharp::LD_BC_DW() { BC = CurrOperand; } void Sharp::LD_ADDR_BC_A() { MemoryBus->WriteWord(BC, A); } void Sharp::INC_BC() { BC++; } void Sharp::INC_B() { IncrementRegister(B); } void Sharp::DEC_B() { DecrementRegister(B); } void Sharp::LD_B_W() { B = (uint8_t) CurrOperand; } void Sharp::RLCA() { RotateLeftCircular(A); SetFlag(z, 0); } void Sharp::LD_ADDR_DW_SP() { MemoryBus->WriteDoubleWord(CurrOperand, SP); } void Sharp::ADD_HL_BC() { UnsignedAdd16(HL, BC); } void Sharp::LD_A_ADDR_BC() { A = MemoryBus->ReadWord(BC); } void Sharp::DEC_BC() { BC--; } void Sharp::INC_C() { IncrementRegister(C); } void Sharp::DEC_C() { DecrementRegister(C); } void Sharp::LD_C_W() { C = (uint8_t) CurrOperand; } void Sharp::RRCA() { RotateRightCircular(A); SetFlag(z, 0); } void Sharp::STOP() { // I will ignore this instruction for now } void Sharp::LD_DE_DW() { DE = CurrOperand; } void Sharp::LD_ADDR_DE_A() { MemoryBus->WriteWord(DE, A); } void Sharp::INC_DE(){ DE++; } void Sharp::INC_D() { IncrementRegister(D); } void Sharp::DEC_D() { DecrementRegister(D); } void Sharp::LD_D_W() { D = (uint8_t) CurrOperand; } void Sharp::RLA() { RotateLeft(A); SetFlag(z, 0); } void Sharp::JR_SW() { PC = PC + (int8_t) (CurrOperand); } void Sharp::ADD_HL_DE() { UnsignedAdd16(HL, DE); } void Sharp::LD_A_ADDR_DE() { A = MemoryBus->ReadWord(DE); } void Sharp::DEC_DE() { DE--; } void Sharp::INC_E() { IncrementRegister(E); } void Sharp::DEC_E() { DecrementRegister(E); } void Sharp::LD_E_W() { E = (uint8_t) CurrOperand; } void Sharp::RRA() { RotateRight(A); SetFlag(z, 0); } void Sharp::JR_NZ_SW() { if (!GetFlag(z)) { PC += (int8_t) CurrOperand; CurrCycles += 4; } } void Sharp::LD_HL_DW() { HL = CurrOperand; } void Sharp::LD_ADDR_HL_PI_A() { MemoryBus->WriteWord(HL++, A); } void Sharp::INC_HL() { HL++; } void Sharp::INC_H() { IncrementRegister(H); } void Sharp::DEC_H() { DecrementRegister(H); } void Sharp::LD_H_W() { H = (uint8_t) CurrOperand; } void Sharp::DAA() { temp = 0x0; if (GetFlag(h) || (!GetFlag(n) && ((A & 0xF) > 0x9))) { temp |= 0x06; } if (GetFlag(c) || (!GetFlag(n) && (A > 0x99))) { temp |= 0x60; // Set the flag to 1 if and only if the previous instruction // Was an addition and either: // - A carry occurred // - Register A was bigger than 0x99 SetFlag(c, GetFlag(c) | (!GetFlag(n) && (GetFlag(c) || (A > 0x99)) ) ); } A += GetFlag(n) ? -temp : temp; if (A == 0) { SetFlag(z, 1); } else { SetFlag(z, 0); } SetFlag(h, 0); } void Sharp::JR_Z_SW() { if (GetFlag(z)) { PC += (int8_t) CurrOperand; CurrCycles += 4; } } void Sharp::ADD_HL_HL() { UnsignedAdd16(HL, HL); } void Sharp::LD_A_ADDR_HL_PI() { A = MemoryBus->ReadWord(HL++); } void Sharp::DEC_HL() { HL--; } void Sharp::INC_L() { IncrementRegister(L); } void Sharp::DEC_L() { DecrementRegister(L); } void Sharp::LD_L_W() { L = (uint8_t) CurrOperand; } void Sharp::CPL() { A = ~A; SetFlag(n, 1); SetFlag(h, 1); } void Sharp::JR_NC_SW() { if (!GetFlag(c)) { PC += (int8_t) CurrOperand; CurrCycles += 4; } } void Sharp::LD_SP_DW() { SP = CurrOperand; } void Sharp::LD_ADDR_HL_PD_A() { MemoryBus->WriteWord(HL--, A); } void Sharp::INC_SP() { SP++; } void Sharp::INC_ADDR_HL() { temp = MemoryBus->ReadWord(HL); IncrementRegister(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::DEC_ADDR_HL() { temp = MemoryBus->ReadWord(HL); DecrementRegister(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::LD_ADDR_HL_W() { MemoryBus->WriteWord(HL, (uint8_t) CurrOperand); } void Sharp::SCF() { SetFlag(n, 0); SetFlag(h, 0); SetFlag(c, 1); } void Sharp::JR_C_SW() { if (GetFlag(c)) { PC += (int8_t) CurrOperand; CurrCycles += 4; } } void Sharp::ADD_HL_SP() { UnsignedAdd16(HL, SP); } void Sharp::LD_A_ADDR_HL_PD() { A = MemoryBus->ReadWord(HL--); } void Sharp::DEC_SP() { SP--; } void Sharp::INC_A() { IncrementRegister(A); } void Sharp::DEC_A() { DecrementRegister(A); } void Sharp::LD_A_W() { A = (uint8_t) CurrOperand; } void Sharp::CCF() { SetFlag(n, 0); SetFlag(h, 0); SetFlag(c, !GetFlag(c)); } void Sharp::LD_B_B() { } void Sharp::LD_B_C() { B = C; } void Sharp::LD_B_D() { B = D; } void Sharp::LD_B_E() { B = E; } void Sharp::LD_B_H() { B = H; } void Sharp::LD_B_L() { B = L; } void Sharp::LD_B_ADDR_HL() { B = MemoryBus->ReadWord(HL); } void Sharp::LD_B_A() { B = A; } void Sharp::LD_C_B() { C = B; } void Sharp::LD_C_C() { } void Sharp::LD_C_D() { C = D; } void Sharp::LD_C_E() { C = E; } void Sharp::LD_C_H() { C = H; } void Sharp::LD_C_L() { C = L; } void Sharp::LD_C_ADDR_HL() { C = MemoryBus->ReadWord(HL); } void Sharp::LD_C_A() { C = A; } void Sharp::LD_D_B() { D = B; } void Sharp::LD_D_C() { D = C; } void Sharp::LD_D_D() { } void Sharp::LD_D_E() { D = E; } void Sharp::LD_D_H() { D = H; } void Sharp::LD_D_L() { D = L; } void Sharp::LD_D_ADDR_HL() { D = MemoryBus->ReadWord(HL); } void Sharp::LD_D_A() { D = A; } void Sharp::LD_E_B() { E = B; } void Sharp::LD_E_C() { E = C; } void Sharp::LD_E_D() { E = D; } void Sharp::LD_E_E() { } void Sharp::LD_E_H() { E = H; } void Sharp::LD_E_L() { E = L; } void Sharp::LD_E_ADDR_HL() { E = MemoryBus->ReadWord(HL); } void Sharp::LD_E_A() { E = A; } void Sharp::LD_H_B() { H = B; } void Sharp::LD_H_C() { H = C; } void Sharp::LD_H_D() { H = D; } void Sharp::LD_H_E() { H = E; } void Sharp::LD_H_H() { } void Sharp::LD_H_L() { H = L; } void Sharp::LD_H_ADDR_HL() { H = MemoryBus->ReadWord(HL); } void Sharp::LD_H_A() { H = A; } void Sharp::LD_L_B() { L = B; } void Sharp::LD_L_C() { L = C; } void Sharp::LD_L_D() { L = D; } void Sharp::LD_L_E() { L = E; } void Sharp::LD_L_H() { L = H; } void Sharp::LD_L_L() { } void Sharp::LD_L_ADDR_HL() { L = MemoryBus->ReadWord(HL); } void Sharp::LD_L_A() { L = A; } void Sharp::LD_ADDR_HL_B() { MemoryBus->WriteWord(HL, B); } void Sharp::LD_ADDR_HL_C() { MemoryBus->WriteWord(HL, C); } void Sharp::LD_ADDR_HL_D() { MemoryBus->WriteWord(HL, D); } void Sharp::LD_ADDR_HL_E() { MemoryBus->WriteWord(HL, E); } void Sharp::LD_ADDR_HL_H() { MemoryBus->WriteWord(HL, H); } void Sharp::LD_ADDR_HL_L() { MemoryBus->WriteWord(HL, L); } void Sharp::HALT() { // We only want to enter halt mode if the IME is enabled or we do not have a pending interrupt // Otherwise, we trigger the halt bug if (InterruptMasterEnable) { Suspended = true; } else { if ((MemoryBus->InterruptEnableRegister & *(MemoryBus->InterruptFlags) & 0x1F) == 0) { Suspended = true; } else { HaltBug = true; } } } void Sharp::LD_ADDR_HL_A() { MemoryBus->WriteWord(HL, A); } void Sharp::LD_A_B() { A = B; } void Sharp::LD_A_C() { A = C; } void Sharp::LD_A_D() { A = D; } void Sharp::LD_A_E() { A = E; } void Sharp::LD_A_H() { A = H; } void Sharp::LD_A_L() { A = L; } void Sharp::LD_A_ADDR_HL() { A = MemoryBus->ReadWord(HL); } void Sharp::LD_A_A() { } void Sharp::ADD_A_B() { UnsignedAdd(A, B); } void Sharp::ADD_A_C() { UnsignedAdd(A, C); } void Sharp::ADD_A_D() { UnsignedAdd(A, D); } void Sharp::ADD_A_E() { UnsignedAdd(A, E); } void Sharp::ADD_A_H() { UnsignedAdd(A, H); } void Sharp::ADD_A_L() { UnsignedAdd(A, L); } void Sharp::ADD_A_ADDR_HL() { temp = MemoryBus->ReadWord(HL); UnsignedAdd(A, temp); } void Sharp::ADD_A_A() { UnsignedAdd(A, A); } void Sharp::ADC_A_B() { UnsignedAddCarry(A, B); } void Sharp::ADC_A_C() { UnsignedAddCarry(A, C); } void Sharp::ADC_A_D() { UnsignedAddCarry(A, D); } void Sharp::ADC_A_E() { UnsignedAddCarry(A, E); } void Sharp::ADC_A_H() { UnsignedAddCarry(A, H); } void Sharp::ADC_A_L() { UnsignedAddCarry(A, L); } void Sharp::ADC_A_ADDR_HL() { temp = MemoryBus->ReadWord(HL); UnsignedAddCarry(A, temp); } void Sharp::ADC_A_A() { UnsignedAddCarry(A, A); } void Sharp::SUB_B() { Subtract(A, B); } void Sharp::SUB_C() { Subtract(A, C); } void Sharp::SUB_D() { Subtract(A, D); } void Sharp::SUB_E() { Subtract(A, E); } void Sharp::SUB_H() { Subtract(A, H); } void Sharp::SUB_L() { Subtract(A, L); } void Sharp::SUB_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Subtract(A, temp); } void Sharp::SUB_A() { Subtract(A, A); } void Sharp::SBC_A_B() { SubtractWithCarry(A, B); } void Sharp::SBC_A_C() { SubtractWithCarry(A, C); } void Sharp::SBC_A_D() { SubtractWithCarry(A, D); } void Sharp::SBC_A_E() { SubtractWithCarry(A, E); } void Sharp::SBC_A_H() { SubtractWithCarry(A, H); } void Sharp::SBC_A_L() { SubtractWithCarry(A, L); } void Sharp::SBC_A_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SubtractWithCarry(A, temp); } void Sharp::SBC_A_A() { SubtractWithCarry(A, A); } void Sharp::AND_B() { And(B); } void Sharp::AND_C() { And(C); } void Sharp::AND_D() { And(D); } void Sharp::AND_E() { And(E); } void Sharp::AND_H() { And(H); } void Sharp::AND_L() { And(L); } void Sharp::AND_ADDR_HL() { temp = MemoryBus->ReadWord(HL); And(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::AND_A() { And(A); } void Sharp::XOR_B() { Xor(B); } void Sharp::XOR_C() { Xor(C); } void Sharp::XOR_D() { Xor(D); } void Sharp::XOR_E() { Xor(E); } void Sharp::XOR_H() { Xor(H); } void Sharp::XOR_L() { Xor(L); } void Sharp::XOR_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Xor(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::XOR_A() { Xor(A); } void Sharp::OR_B() { Or(B); } void Sharp::OR_C() { Or(C); } void Sharp::OR_D() { Or(D); } void Sharp::OR_E() { Or(E); } void Sharp::OR_H() { Or(H); } void Sharp::OR_L() { Or(L); } void Sharp::OR_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Or(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::OR_A() { Or(A); } void Sharp::CP_B() { temp = A; Subtract(temp, B); } void Sharp::CP_C() { temp = A; Subtract(temp, C); } void Sharp::CP_D() { temp = A; Subtract(temp, D); } void Sharp::CP_E() { temp = A; Subtract(temp, E); } void Sharp::CP_H() { temp = A; Subtract(temp, H); } void Sharp::CP_L() { temp = A; Subtract(temp, L); } void Sharp::CP_ADDR_HL() { temp = A; temp2 = MemoryBus->ReadWord(HL); Subtract(temp, temp2); } void Sharp::CP_A() { temp = A; Subtract(temp, A); } void Sharp::RET_NZ() { if (!GetFlag(z)) { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; CurrCycles += 12; } } void Sharp::POP_BC() { BC = MemoryBus->ReadDoubleWord(SP); SP += 2; } void Sharp::JP_NZ_ADDR_DW() { if (!GetFlag(z)) { PC = CurrOperand; CurrCycles += 4; } } void Sharp::JP_ADDR_DW() { PC = CurrOperand; } void Sharp::CALL_NZ_ADDR_DW() { if (!GetFlag(z)) { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = CurrOperand; CurrCycles += 12; } } void Sharp::PUSH_BC() { SP -= 2; MemoryBus->WriteDoubleWord(SP, BC); } void Sharp::ADD_A_W() { UnsignedAdd(A, (uint8_t) CurrOperand); } void Sharp::RST_00H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0000; } void Sharp::RET_Z() { if (GetFlag(z)) { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; CurrCycles += 12; } } void Sharp::RET() { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; } void Sharp::JP_Z_ADDR_DW() { if (GetFlag(z)) { PC = CurrOperand; CurrCycles += 4; } } void Sharp::PREFIX_CB() { Opcode = MemoryBus->ReadWord(PC++); DecodedInstr = SHARPINSTRS_CB[Opcode]; CurrCycles = DecodedInstr.Cycles; CurrArgSize = DecodedInstr.ArgSize; (this->*DecodedInstr.Instruction)(); } void Sharp::CALL_Z_ADDR_DW() { if (GetFlag(z)) { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = CurrOperand; CurrCycles += 12; } } void Sharp::CALL_ADDR_DW() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = CurrOperand; } void Sharp::ADC_A_W() { UnsignedAddCarry(A, (uint8_t) CurrOperand); } void Sharp::RST_08H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0008; } void Sharp::RET_NC() { if (!GetFlag(c)) { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; CurrCycles += 12; } } void Sharp::POP_DE() { DE = MemoryBus->ReadDoubleWord(SP); SP += 2; } void Sharp::JP_NC_ADDR_DW() { if (!GetFlag(c)) { PC = CurrOperand; CurrCycles += 4; } } void Sharp::CALL_NC_ADDR_DW() { if (!GetFlag(c)) { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = CurrOperand; CurrCycles += 12; } } void Sharp::PUSH_DE() { SP -= 2; MemoryBus->WriteDoubleWord(SP, DE); } void Sharp::SUB_W() { Subtract(A, (uint8_t)CurrOperand); } void Sharp::RST_10H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0010; } void Sharp::RET_C() { if (GetFlag(c)) { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; CurrCycles += 12; } } void Sharp::RETI() { PC = MemoryBus->ReadDoubleWord(SP); SP += 2; InterruptMasterEnable = 0x1; } void Sharp::JP_C_ADDR_DW() { if (GetFlag(c)) { PC = CurrOperand; CurrCycles += 4; } } void Sharp::CALL_C_ADDR_DW() { if (GetFlag(c)) { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = CurrOperand; CurrCycles += 12; } } void Sharp::SBC_A_W() { SubtractWithCarry(A, (uint8_t) CurrOperand); } void Sharp::RST_18H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0018; } void Sharp::LDH_ADDR_W_A() { MemoryBus->WriteWord(0xFF00 | (uint8_t)CurrOperand, A); } void Sharp::POP_HL() { HL = MemoryBus->ReadDoubleWord(SP); SP += 2; } void Sharp::LD_ADDR_C_A() { MemoryBus->WriteWord(0xFF00 | C, A); } void Sharp::PUSH_HL() { SP -= 2; MemoryBus->WriteDoubleWord(SP, HL); } void Sharp::AND_W() { And((uint8_t)CurrOperand); } void Sharp::RST_20H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0020; } void Sharp::ADD_SP_SW() { temp3 = CurrOperand & 0x80 ? 0xFF00 | CurrOperand : CurrOperand & 0xFF; if ((temp3 & 0xFF) > (0xFF - (SP & 0xFF))) { SetFlag(c, 1); } else { SetFlag(c, 0); } temp3 = (SP & 0xF) + (temp3 & 0xF); if ((temp3 & 0x10) == 0x10) { SetFlag(h, 1); } else { SetFlag(h, 0); } SP += (int8_t) CurrOperand; SetFlag(z, 0); SetFlag(n, 0); } void Sharp::JP_HL() { PC = HL; } void Sharp::LD_ADDR_DW_A() { MemoryBus->WriteWord(CurrOperand, A); } void Sharp::XOR_W() { Xor((uint8_t) CurrOperand); } void Sharp::RST_28H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0028; } void Sharp::LDH_A_ADDR_W() { A = MemoryBus->ReadWord(0xFF00 | (uint8_t) CurrOperand); } void Sharp::POP_AF() { AF = MemoryBus->ReadDoubleWord(SP) & 0xFFF0; SP += 2; } void Sharp::LD_A_ADDR_C() { A = MemoryBus->ReadWord(0xFF00 | C); } // Blargg's ROMs seem to conclude the behavior of these instructions are O.K. void Sharp::DI() { PendingIMEChange = 0x10 | 0x02; } void Sharp::PUSH_AF() { SP -= 2; MemoryBus->WriteDoubleWord(SP, AF); } void Sharp::OR_W() { Or((uint8_t) CurrOperand); } void Sharp::RST_30H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0030; } void Sharp::LD_HL_SP_PLUS_SW() { CurrOperand = CurrOperand & 0x80 ? 0xFF00 | CurrOperand : CurrOperand & 0xFF; temp = SP; UnsignedAdd(temp, CurrOperand); HL = SP + (int8_t) CurrOperand; SetFlag(z, 0); SetFlag(n, 0); } void Sharp::LD_SP_HL() { SP = HL; } void Sharp::LD_A_ADDR_DW() { A = MemoryBus->ReadWord(CurrOperand); } void Sharp::EI() { PendingIMEChange = 0x90 | 0x02; } void Sharp::CP_W() { temp = A; Subtract(temp, (uint8_t) CurrOperand); } void Sharp::RST_38H() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x0038; } void Sharp::RLC_B() { RotateLeftCircular(B); } void Sharp::RLC_C() { RotateLeftCircular(C); } void Sharp::RLC_D() { RotateLeftCircular(D); } void Sharp::RLC_E() { RotateLeftCircular(E); } void Sharp::RLC_H() { RotateLeftCircular(H); } void Sharp::RLC_L() { RotateLeftCircular(L); } void Sharp::RLC_ADDR_HL() { temp = MemoryBus->ReadWord(HL); RotateLeftCircular(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RLC_A() { RotateLeftCircular(A); } void Sharp::RRC_B() { RotateRightCircular(B); } void Sharp::RRC_C() { RotateRightCircular(C); } void Sharp::RRC_D() { RotateRightCircular(D); } void Sharp::RRC_E() { RotateRightCircular(E); } void Sharp::RRC_H() { RotateRightCircular(H); } void Sharp::RRC_L() { RotateRightCircular(L); } void Sharp::RRC_ADDR_HL() { temp = MemoryBus->ReadWord(HL); RotateRightCircular(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RRC_A() { RotateRightCircular(A); } void Sharp::RL_B() { RotateLeft(B); } void Sharp::RL_C() { RotateLeft(C); } void Sharp::RL_D() { RotateLeft(D); } void Sharp::RL_E() { RotateLeft(E); } void Sharp::RL_H() { RotateLeft(H); } void Sharp::RL_L() { RotateLeft(L); } void Sharp::RL_ADDR_HL() { temp = MemoryBus->ReadWord(HL); RotateLeft(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RL_A() { RotateLeft(A); } void Sharp::RR_B() { RotateRight(B); } void Sharp::RR_C() { RotateRight(C); } void Sharp::RR_D() { RotateRight(D); } void Sharp::RR_E() { RotateRight(E); } void Sharp::RR_H() { RotateRight(H); } void Sharp::RR_L() { RotateRight(L); } void Sharp::RR_ADDR_HL() { temp = MemoryBus->ReadWord(HL); RotateRight(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RR_A() { RotateRight(A); } void Sharp::SLA_B() { ShiftLeft(B); } void Sharp::SLA_C() { ShiftLeft(C); } void Sharp::SLA_D() { ShiftLeft(D); } void Sharp::SLA_E() { ShiftLeft(E); } void Sharp::SLA_H() { ShiftLeft(H); } void Sharp::SLA_L() { ShiftLeft(L); } void Sharp::SLA_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ShiftLeft(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SLA_A() { ShiftLeft(A); } void Sharp::SRA_B() { ShiftRightArithmetic(B); } void Sharp::SRA_C() { ShiftRightArithmetic(C); } void Sharp::SRA_D() { ShiftRightArithmetic(D); } void Sharp::SRA_E() { ShiftRightArithmetic(E); } void Sharp::SRA_H() { ShiftRightArithmetic(H); } void Sharp::SRA_L() { ShiftRightArithmetic(L); } void Sharp::SRA_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ShiftRightArithmetic(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SRA_A() { ShiftRightArithmetic(A); } void Sharp::SWAP_B() { Swap(B); } void Sharp::SWAP_C() { Swap(C); } void Sharp::SWAP_D() { Swap(D); } void Sharp::SWAP_E() { Swap(E); } void Sharp::SWAP_H() { Swap(H); } void Sharp::SWAP_L() { Swap(L); } void Sharp::SWAP_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Swap(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SWAP_A() { Swap(A); } void Sharp::SRL_B() { ShiftRight(B); } void Sharp::SRL_C() { ShiftRight(C); } void Sharp::SRL_D() { ShiftRight(D); } void Sharp::SRL_E() { ShiftRight(E); } void Sharp::SRL_H() { ShiftRight(H); } void Sharp::SRL_L() { ShiftRight(L); } void Sharp::SRL_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ShiftRight(temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SRL_A() { ShiftRight(A); } void Sharp::BIT_0_B() { Bit(0, B); } void Sharp::BIT_0_C() { Bit(0, C); } void Sharp::BIT_0_D() { Bit(0, D); } void Sharp::BIT_0_E() { Bit(0, E); } void Sharp::BIT_0_H() { Bit(0, H); } void Sharp::BIT_0_L() { Bit(0, L); } void Sharp::BIT_0_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(0, temp); } void Sharp::BIT_0_A() { Bit(0, A); } void Sharp::BIT_1_B() { Bit(1, B); } void Sharp::BIT_1_C() { Bit(1, C); } void Sharp::BIT_1_D() { Bit(1, D); } void Sharp::BIT_1_E() { Bit(1, E); } void Sharp::BIT_1_H() { Bit(1, H); } void Sharp::BIT_1_L() { Bit(1, L); } void Sharp::BIT_1_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(1, temp); } void Sharp::BIT_1_A() { Bit(1, A); } void Sharp::BIT_2_B() { Bit(2, B); } void Sharp::BIT_2_C() { Bit(2, C); } void Sharp::BIT_2_D() { Bit(2, D); } void Sharp::BIT_2_E() { Bit(2, E); } void Sharp::BIT_2_H() { Bit(2, H); } void Sharp::BIT_2_L() { Bit(2, L); } void Sharp::BIT_2_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(2, temp); } void Sharp::BIT_2_A() { Bit(2, A); } void Sharp::BIT_3_B() { Bit(3, B); } void Sharp::BIT_3_C() { Bit(3, C); } void Sharp::BIT_3_D() { Bit(3, D); } void Sharp::BIT_3_E() { Bit(3, E); } void Sharp::BIT_3_H() { Bit(3, H); } void Sharp::BIT_3_L() { Bit(3, L); } void Sharp::BIT_3_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(3, temp); } void Sharp::BIT_3_A() { Bit(3, A); } void Sharp::BIT_4_B() { Bit(4, B); } void Sharp::BIT_4_C() { Bit(4, C); } void Sharp::BIT_4_D() { Bit(4, D); } void Sharp::BIT_4_E() { Bit(4, E); } void Sharp::BIT_4_H() { Bit(4, H); } void Sharp::BIT_4_L() { Bit(4, L); } void Sharp::BIT_4_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(4, temp); } void Sharp::BIT_4_A() { Bit(4, A); } void Sharp::BIT_5_B() { Bit(5, B); } void Sharp::BIT_5_C() { Bit(5, C); } void Sharp::BIT_5_D() { Bit(5, D); } void Sharp::BIT_5_E() { Bit(5, E); } void Sharp::BIT_5_H() { Bit(5, H); } void Sharp::BIT_5_L() { Bit(5, L); } void Sharp::BIT_5_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(5, temp); } void Sharp::BIT_5_A() { Bit(5, A); } void Sharp::BIT_6_B() { Bit(6, B); } void Sharp::BIT_6_C() { Bit(6, C); } void Sharp::BIT_6_D() { Bit(6, D); } void Sharp::BIT_6_E() { Bit(6, E); } void Sharp::BIT_6_H() { Bit(6, H); } void Sharp::BIT_6_L() { Bit(6, L); } void Sharp::BIT_6_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(6, temp); } void Sharp::BIT_6_A() { Bit(6, A); } void Sharp::BIT_7_B() { Bit(7, B); } void Sharp::BIT_7_C() { Bit(7, C); } void Sharp::BIT_7_D() { Bit(7, D); } void Sharp::BIT_7_E() { Bit(7, E); } void Sharp::BIT_7_H() { Bit(7, H); } void Sharp::BIT_7_L() { Bit(7, L); } void Sharp::BIT_7_ADDR_HL() { temp = MemoryBus->ReadWord(HL); Bit(7, temp); } void Sharp::BIT_7_A() { Bit(7, A); } void Sharp::RES_0_B() { ResetBit(0, B); } void Sharp::RES_0_C() { ResetBit(0, C); } void Sharp::RES_0_D() { ResetBit(0, D); } void Sharp::RES_0_E() { ResetBit(0, E); } void Sharp::RES_0_H() { ResetBit(0, H); } void Sharp::RES_0_L() { ResetBit(0, L); } void Sharp::RES_0_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(0, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_0_A() { ResetBit(0, A); } void Sharp::RES_1_B() { ResetBit(1, B); } void Sharp::RES_1_C() { ResetBit(1, C); } void Sharp::RES_1_D() { ResetBit(1, D); } void Sharp::RES_1_E() { ResetBit(1, E); } void Sharp::RES_1_H() { ResetBit(1, H); } void Sharp::RES_1_L() { ResetBit(1, L); } void Sharp::RES_1_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(1, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_1_A() { ResetBit(1, A); } void Sharp::RES_2_B() { ResetBit(2, B); } void Sharp::RES_2_C() { ResetBit(2, C); } void Sharp::RES_2_D() { ResetBit(2, D); } void Sharp::RES_2_E() { ResetBit(2, E); } void Sharp::RES_2_H() { ResetBit(2, H); } void Sharp::RES_2_L() { ResetBit(2, L); } void Sharp::RES_2_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(2, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_2_A() { ResetBit(2, A); } void Sharp::RES_3_B() { ResetBit(3, B); } void Sharp::RES_3_C() { ResetBit(3, C); } void Sharp::RES_3_D() { ResetBit(3, D); } void Sharp::RES_3_E() { ResetBit(3, E); } void Sharp::RES_3_H() { ResetBit(3, H); } void Sharp::RES_3_L() { ResetBit(3, L); } void Sharp::RES_3_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(3, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_3_A() { ResetBit(3, A); } void Sharp::RES_4_B() { ResetBit(4, B); } void Sharp::RES_4_C() { ResetBit(4, C); } void Sharp::RES_4_D() { ResetBit(4, D); } void Sharp::RES_4_E() { ResetBit(4, E); } void Sharp::RES_4_H() { ResetBit(4, H); } void Sharp::RES_4_L() { ResetBit(4, L); } void Sharp::RES_4_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(4, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_4_A() { ResetBit(4, A); } void Sharp::RES_5_B() { ResetBit(5, B); } void Sharp::RES_5_C() { ResetBit(5, C); } void Sharp::RES_5_D() { ResetBit(5, D); } void Sharp::RES_5_E() { ResetBit(5, E); } void Sharp::RES_5_H() { ResetBit(5, H); } void Sharp::RES_5_L() { ResetBit(5, L); } void Sharp::RES_5_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(5, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_5_A() { ResetBit(5, A); } void Sharp::RES_6_B() { ResetBit(6, B); } void Sharp::RES_6_C() { ResetBit(6, C); } void Sharp::RES_6_D() { ResetBit(6, D); } void Sharp::RES_6_E() { ResetBit(6, E); } void Sharp::RES_6_H() { ResetBit(6, H); } void Sharp::RES_6_L() { ResetBit(6, L); } void Sharp::RES_6_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(6, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_6_A() { ResetBit(6, A); } void Sharp::RES_7_B() { ResetBit(7, B); } void Sharp::RES_7_C() { ResetBit(7, C); } void Sharp::RES_7_D() { ResetBit(7, D); } void Sharp::RES_7_E() { ResetBit(7, E); } void Sharp::RES_7_H() { ResetBit(7, H); } void Sharp::RES_7_L() { ResetBit(7, L); } void Sharp::RES_7_ADDR_HL() { temp = MemoryBus->ReadWord(HL); ResetBit(7, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::RES_7_A() { ResetBit(7, A); } void Sharp::SET_0_B() { SetBit(0, B); } void Sharp::SET_0_C() { SetBit(0, C); } void Sharp::SET_0_D() { SetBit(0, D); } void Sharp::SET_0_E() { SetBit(0, E); } void Sharp::SET_0_H() { SetBit(0, H); } void Sharp::SET_0_L() { SetBit(0, L); } void Sharp::SET_0_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(0, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_0_A() { SetBit(0, A); } void Sharp::SET_1_B() { SetBit(1, B); } void Sharp::SET_1_C() { SetBit(1, C); } void Sharp::SET_1_D() { SetBit(1, D); } void Sharp::SET_1_E() { SetBit(1, E); } void Sharp::SET_1_H() { SetBit(1, H); } void Sharp::SET_1_L() { SetBit(1, L); } void Sharp::SET_1_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(1, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_1_A() { SetBit(1, A); } void Sharp::SET_2_B() { SetBit(2, B); } void Sharp::SET_2_C() { SetBit(2, C); } void Sharp::SET_2_D() { SetBit(2, D); } void Sharp::SET_2_E() { SetBit(2, E); } void Sharp::SET_2_H() { SetBit(2, H); } void Sharp::SET_2_L() { SetBit(2, L); } void Sharp::SET_2_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(2, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_2_A() { SetBit(2, A); } void Sharp::SET_3_B() { SetBit(3, B); } void Sharp::SET_3_C() { SetBit(3, C); } void Sharp::SET_3_D() { SetBit(3, D); } void Sharp::SET_3_E() { SetBit(3, E); } void Sharp::SET_3_H() { SetBit(3, H); } void Sharp::SET_3_L() { SetBit(3, L); } void Sharp::SET_3_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(3, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_3_A() { SetBit(3, A); } void Sharp::SET_4_B() { SetBit(4, B); } void Sharp::SET_4_C() { SetBit(4, C); } void Sharp::SET_4_D() { SetBit(4, D); } void Sharp::SET_4_E() { SetBit(4, E); } void Sharp::SET_4_H() { SetBit(4, H); } void Sharp::SET_4_L() { SetBit(4, L); } void Sharp::SET_4_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(4, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_4_A() { SetBit(4, A); } void Sharp::SET_5_B() { SetBit(5, B); } void Sharp::SET_5_C() { SetBit(5, C); } void Sharp::SET_5_D() { SetBit(5, D); } void Sharp::SET_5_E() { SetBit(5, E); } void Sharp::SET_5_H() { SetBit(5, H); } void Sharp::SET_5_L() { SetBit(5, L); } void Sharp::SET_5_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(5, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_5_A() { SetBit(5, A); } void Sharp::SET_6_B() { SetBit(6, B); } void Sharp::SET_6_C() { SetBit(6, C); } void Sharp::SET_6_D() { SetBit(6, D); } void Sharp::SET_6_E() { SetBit(6, E); } void Sharp::SET_6_H() { SetBit(6, H); } void Sharp::SET_6_L() { SetBit(6, L); } void Sharp::SET_6_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(6, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_6_A() { SetBit(6, A); } void Sharp::SET_7_B() { SetBit(7, B); } void Sharp::SET_7_C() { SetBit(7, C); } void Sharp::SET_7_D() { SetBit(7, D); } void Sharp::SET_7_E() { SetBit(7, E); } void Sharp::SET_7_H() { SetBit(7, H); } void Sharp::SET_7_L() { SetBit(7, L); } void Sharp::SET_7_ADDR_HL() { temp = MemoryBus->ReadWord(HL); SetBit(7, temp); MemoryBus->WriteWord(HL, temp); } void Sharp::SET_7_A() { SetBit(7, A); } void Sharp::INT_40() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x40; CurrCycles += 12; } void Sharp::INT_48() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x48; CurrCycles += 12; } void Sharp::INT_50() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x50; CurrCycles += 12; } void Sharp::INT_58() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x58; CurrCycles += 12; } void Sharp::INT_60() { SP -= 2; MemoryBus->WriteDoubleWord(SP, PC); PC = 0x60; CurrCycles += 12; } Sharp::~Sharp() { Log.close(); } // This is kind of a mess, but looking past all the pointer dereferencing // we exit halt (if any) and service the ISR based on the bits set void Sharp::InterruptHandler() { if (MemoryBus->InterruptEnableRegister & *(MemoryBus->InterruptFlags) & 0x1F) { Suspended = false; } if (InterruptMasterEnable && MemoryBus->InterruptEnableRegister && *(MemoryBus->InterruptFlags)) { temp = MemoryBus->InterruptEnableRegister & *(MemoryBus->InterruptFlags) & 0x1F; if (temp & VBLANK) { *(MemoryBus->InterruptFlags) &= ~VBLANK; INT_40(); } if (temp & LCDSTAT) { *(MemoryBus->InterruptFlags) &= ~LCDSTAT; INT_48(); } if (temp & TIMER) { *(MemoryBus->InterruptFlags) &= ~TIMER; INT_50(); } if (temp & SERIAL) { *(MemoryBus->InterruptFlags) &= ~SERIAL; INT_58(); } if (temp & JOYPAD) { *(MemoryBus->InterruptFlags) &= ~JOYPAD; INT_60(); } } } void Sharp::Clock() { if (!Suspended) { if (CurrCycles == 0) { switch(HaltBug) { case false: Opcode = MemoryBus->ReadWord(PC++); break; case true: Opcode = MemoryBus->ReadWord(PC); HaltBug = false; break; } DecodedInstr = SHARPINSTRS[Opcode]; CurrCycles = DecodedInstr.Cycles; CurrArgSize = DecodedInstr.ArgSize; switch (CurrArgSize) { case 1: CurrOperand = (uint16_t) MemoryBus->ReadWord(PC++); break; case 2: CurrOperand = MemoryBus->ReadDoubleWord(PC); PC += 2; break; } (this->*DecodedInstr.Instruction)(); if ((PendingIMEChange & 0x10) && ((PendingIMEChange & 0x0F) > 0)) { PendingIMEChange--; if ((PendingIMEChange & 0x0F) == 0) { InterruptMasterEnable = (PendingIMEChange & 0x80) >> 7; PendingIMEChange = 0x00; } } } CurrCycles--; } } /*/ Should the emulator report to the CPU that it will be loading the boot ROM, these values should be zero iniialized; we will let the code from the boot ROM set the registers when as it reaches PC = $0100 */ void Sharp::SetupBootRom() { PC = 0x0000; AF = 0x0000; BC = 0x0000; DE = 0x0000; HL = 0x0000; SP = 0xFFFE; }
13.145085
99
0.603101
dfrias100
fcf7dd033191d34e26c8ff85621d5edfd177377f
178
hpp
C++
src/parser/sql-stmt/NotImplemented/CreateIndex.hpp
TrueFinch/KappaDBMS
f4f9e91c52ae33f929e6db458a713a98a9958da3
[ "Apache-2.0" ]
2
2018-10-29T05:38:27.000Z
2018-12-05T15:32:16.000Z
src/parser/sql-stmt/NotImplemented/CreateIndex.hpp
TrueFinch/KappaDBMS
f4f9e91c52ae33f929e6db458a713a98a9958da3
[ "Apache-2.0" ]
null
null
null
src/parser/sql-stmt/NotImplemented/CreateIndex.hpp
TrueFinch/KappaDBMS
f4f9e91c52ae33f929e6db458a713a98a9958da3
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Instruction.hpp" namespace cmd { class CreateIndex : public Instruction { public: CreateIndex() : Instruction(CREATE_INDEX) {} }; } // namespace cmd
12.714286
46
0.719101
TrueFinch
fcf9c0989db87b36253c8b95da452444ca04816e
363
cpp
C++
Common/ThreadBase.cpp
Addision/EventServer
2fd13eb5440769da6fb19c6540fb25db09b8cc75
[ "MIT" ]
15
2020-04-22T04:32:12.000Z
2022-01-06T12:40:44.000Z
SeFNet/common/ThreadBase.cpp
Addision/SeNet
7b40cffd7f961b1706e79d9cebd8fee58d1af58e
[ "MIT" ]
1
2020-11-30T07:20:17.000Z
2020-11-30T07:20:17.000Z
Common/ThreadBase.cpp
Addision/EventServer
2fd13eb5440769da6fb19c6540fb25db09b8cc75
[ "MIT" ]
8
2020-04-21T02:15:04.000Z
2021-12-31T17:34:02.000Z
#include "ThreadBase.h" bool ThreadBase::Start() { Init(); //call thread init m_thread = std::thread(std::bind(&ThreadBase::ThreadLoop, this)); m_bActive = true; return true; } bool ThreadBase::Stop() { m_bActive = false; Join(); return true; } void ThreadBase::Join() { if(m_thread.joinable()) { m_thread.join(); } }
13.961538
69
0.606061
Addision
fcfc146114073eed0b5c33f3e1197d85925cfbad
546
cpp
C++
side_projects/meh.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
side_projects/meh.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
side_projects/meh.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
/* * meh */ #include <iostream> #include <cstdint> using namespace std; int main(int argc, char **argv) { uint64_t meh = 0xFFFFFFFFFFFFFFFF; uint64_t age; cout << "meh = " << meh << endl; cout << "How old are you? "; cin >> age; cout << "meh per year = " << meh / age << endl; cout << "meh per month = " << meh / (age * 12) << endl; cout << "meh per day = " << meh / (age * 365) << endl; cout << "meh per hour = " << meh / (age * 365 * 24) << endl; cout << "meh per second = " << meh / (age * 365 * 24 * 3600) << endl; return 0; }
23.73913
70
0.540293
mohsend
fcfcb12990a02ce4a9227554af03bb56abd58491
1,223
cpp
C++
ToDoTick/MainPage.xaml.cpp
HumorLogic/To-Do-Tick
377c651f63b51f64178b42121e71961f9df26e99
[ "Apache-2.0" ]
null
null
null
ToDoTick/MainPage.xaml.cpp
HumorLogic/To-Do-Tick
377c651f63b51f64178b42121e71961f9df26e99
[ "Apache-2.0" ]
null
null
null
ToDoTick/MainPage.xaml.cpp
HumorLogic/To-Do-Tick
377c651f63b51f64178b42121e71961f9df26e99
[ "Apache-2.0" ]
null
null
null
// // MainPage.xaml.cpp // MainPage 类的实现。 // #include "pch.h" #include "MainPage.xaml.h" #include<chrono> #include<thread> using namespace ToDoTick; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; // https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x804 上介绍了“空白页”项模板 MainPage::MainPage() { InitializeComponent(); } void ToDoTick::MainPage::startPauseBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { //TickTime(); //timeText->Text =time; TickTime(timeText); } void MainPage::TickTime(TextBlock^ timeText) { auto start =chrono::system_clock::now(); this_thread::sleep_for(chrono::seconds(3)); auto end = chrono::system_clock::now(); chrono::duration<double> elapsed = end - start; time = elapsed.count().ToString(); timeText->Text = time; //throw ref new Platform::NotImplementedException(); }
23.519231
109
0.740801
HumorLogic
1e01dd6fa61eee60c906dc22edb364794e675b1a
10,563
hpp
C++
src/eyelib/window/event.hpp
lucas137/eyelib
e88eaea6dd2c2e4b365d178f67869a3cd47751a5
[ "MIT" ]
null
null
null
src/eyelib/window/event.hpp
lucas137/eyelib
e88eaea6dd2c2e4b365d178f67869a3cd47751a5
[ "MIT" ]
null
null
null
src/eyelib/window/event.hpp
lucas137/eyelib
e88eaea6dd2c2e4b365d178f67869a3cd47751a5
[ "MIT" ]
null
null
null
//===========================================================================// /* MIT License Copyright (c) 2019 Nathan Lucas 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. */ //===========================================================================// /// @file /// @brief FLTK window event. /// @author Nathan Lucas //===========================================================================// #ifndef EYLIB_WINDOW_EVENT_HPP #define EYLIB_WINDOW_EVENT_HPP #include <string> // std::string namespace eye { namespace window { /// @ingroup window /// @addtogroup event Window Events /// @{ //--------------------------------------------------------------------------- /// Event data. struct Event { // Event handler return values for FLTK static constexpr int HANDLED = 1; ///< Event was handled. static constexpr int NOT_HANDLED = 0; ///< Event was not handled. //----------------------------------------------------------- /// Key event. struct Key { /// Non-printable keys. enum class Special { unrecognized = 0x0000, ///< Unrecognized event key. button = 0xfee8, ///< Mouse button; use Fl_Button + n for button n. backspace = 0xff08, ///< Backspace key. tab = 0xff09, ///< Tab key. enter = 0xff0d, ///< Enter key. pause = 0xff13, ///< Pause key. scroll_lock = 0xff14, ///< Scroll lock key. escape = 0xff1b, ///< Escape key. home = 0xff50, ///< Home key. left = 0xff51, ///< Left arrow key. up = 0xff52, ///< Up arrow key. right = 0xff53, ///< Right arrow key. down = 0xff54, ///< Down arrow key. page_up = 0xff55, ///< Page-up key. page_down = 0xff56, ///< Page-down key. end = 0xff57, ///< End key. print = 0xff61, ///< Print (or print-screen) key. insert = 0xff63, ///< Insert key. menu = 0xff67, ///< Menu key. num_lock = 0xff7f, ///< Num lock key. keypad = 0xff80, ///< Keypad number; use FL_KP + 'n' for digit n. keypad_enter = 0xff8d, ///< Enter key on the keypad, same as Fl_KP+'\\r'. keypad_last = 0xffbd, ///< Last keypad key; use to range-check keypad. function = 0xffbd, ///< Function key; use FL_F + n for function key n. function_last = 0xffe0, ///< Last function key; use to range-check keys. shift_left = 0xffe1, ///< Lefthand shift key. shift_right = 0xffe2, ///< Righthand shift key. control_left = 0xffe3, ///< Lefthand control key. control_right = 0xffe4, ///< Righthand control key. caps_lock = 0xffe5, ///< Caps lock key. meta_left = 0xffe7, ///< Left meta/Windows key. meta_right = 0xffe8, ///< Right meta/Windows key. alt_left = 0xffe9, ///< Left alt key. alt_right = 0xffea, ///< Right alt key. delete_key = 0xffff, ///< Delete key. }; int event_code{0}; ///< Event code. int key_code{0}; ///< Valid for key events only. Key(int event_code); ///< Constructor. // Member functions ------ /// @name Key Press and Release /// @{ bool is_press() const; ///< `true` if key was pressed. bool is_release() const; ///< `true` if key was released. /// @} /// @name Inspection. /// @{ bool is_alt() const; ///< 'true' if left or right alt key. bool is_control() const; ///< 'true' if left or right control key. bool is_enter() const; ///< `true` if enter key. bool is_function() const; ///< `true` if numbered function key. bool is_meta() const; ///< 'true' if left or right meta key. bool is_numpad() const; ///< `true` if numeric keypad key. bool is_printable() const; ///< `true` if printable ASCII character. bool is_shift() const; ///< 'true' if left or right shift key. bool is_special() const; ///< `true` if printable ASCII character. /// @} /// @name Get key. /// @{ /// Return function key number, or `0` if event was not a function key. unsigned function() const; /// Return non-printable key, or Special::unrecognized. Special special() const; /// Return a string representation a key. std::string to_string() const; /// @} }; //----------------------------------------------------------- struct Mouse { /// Mouse button. enum class Button : unsigned { none = 0, left = 1, middle = 2, right = 3 }; int event_code{0}; ///< Event code. Mouse(int event_code); ///< Constructor. // Member functions ------ /// @name Mouse Button /// @{ bool is_click() const; ///< `true` if button was clicked. bool is_release() const; ///< `true` if button was released. static bool is_button_left(); ///< `true` if left button click/release. static bool is_button_middle(); ///< `true` if middle button click/release. static bool is_button_right(); ///< `true` if right button click/release. static Button button(); ///< Button that was clicked or released. static unsigned clicks(); ///< Return N-1 for N clicks. /// @} /// @name Mouse Position /// @{ bool is_drag() const; ///< `true` if moved with a button held down. bool is_move() const; ///< `true` if moved without a button held down. /// @} /// @name Mouse Scroll Wheel /// @{ bool is_scroll() const; ///< `true` if mouse scroll wheel moved. /// @} //----------------------------------------------------------- // /// @name Mouse Events // /// @{ // static constexpr int Button = 0xfee8; ///< Mouse button; use `Button` + n. // /// @} //----------------------------------------------------------- }; //----------------------------------------------------------- /// Key and mouse states during most recent event. struct State { /// Key event states. struct Key { /// @name Key event. /// @{ static bool is_key(); ///< `true` if last event was key press or release. static int key_code(); ///< Key code of last event, or `0` if no key. static bool is_press(int Key); /// `true` if pressed during last event. static bool is_press_now(int Key); /// `true` if key is held down now. /// @} /// @name Modifier keys. /// @{ static bool alt(); ///< `true` if Alt key is pressed. static bool ctrl(); ///< `true` if Ctrl key is pressed. static bool shift(); ///< `true` if Shift key is pressed. /// @} /// @name Lock keys. /// @{ static bool caps_lock(); ///< `true` if Caps Lock is on. static bool num_lock(); ///< `true` if Num Lock is on. static bool scroll_lock(); ///< `true` if Scroll Lock is on. /// @} }; /// Mouse event states. struct Mouse { /// @name Mouse buttons. /// @{ static bool button_left(); ///< `true` if left button click or release. static bool button_middle(); ///< `true` if middle button click or release. static bool button_right(); ///< `true` if right button click or release. /// @} /// @name Mouse position. /// @{ static int x_screen(); ///< Horizontal position on the screen. static int y_screen(); ///< Vertical position on the screen. static int x_window(); ///< Horizontal position relative to window. static int y_window(); ///< Vertical position relative to window. /// `true` if mouse event is inside a given rectangle. static bool is_inside(int x, int y, int w, int h); // /// `true` if mouse event is inside a given child widget. // static bool is_inside(Fl_Widget const* w); /// @} /// @name Mouse scroll. /// @{ static int scroll_dx(); ///< Horizontal scroll -- right is positive. static int scroll_dy(); ///< Vertical scroll -- down is positive. /// @} }; static std::string text(); ///< Text assocatied with event. static unsigned last_event(); ///< Return last event processed. }; //----------------------------------------------------------- // Member variables int code{0}; ///< Event code. Key key{code}; ///< Key event. Mouse mouse{code}; ///< Mouse event. std::string name{}; ///< Event name. State state{}; ///< Current event states. unsigned time_ms{0}; ///< Timestamp in milliseconds. // Constructors Event() = default; ///< Default construct event object. Event(unsigned time_ms, int code); ///< Construct event object. //----------------------------------------------------------- bool is_focus() const; ///< `true` if focus/unfocus event. bool is_key() const; ///< `true` if key was pressed or released. bool is_mouse() const; ///< `true` if mouse event occurred. }; //--------------------------------------------------------------------------- /// @} } } // eye::window #endif // EYLIB_WINDOW_EVENT_HPP //===========================================================================//
39.710526
83
0.518981
lucas137
1e02ca9b8056fc8b124314f2c323d84edcdfcaaa
13,537
cc
C++
content/browser/renderer_host/render_view_host_manager_browsertest.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2015-10-12T09:14:22.000Z
2015-10-12T09:14:22.000Z
content/browser/renderer_host/render_view_host_manager_browsertest.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
null
null
null
content/browser/renderer_host/render_view_host_manager_browsertest.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2020-11-04T07:22:28.000Z
2020-11-04T07:22:28.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/memory/ref_counted.h" #include "base/path_service.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/site_instance.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/notification_details.h" #include "content/common/notification_observer.h" #include "content/common/notification_registrar.h" #include "content/common/notification_type.h" #include "net/base/net_util.h" #include "net/test/test_server.h" class RenderViewHostManagerTest : public InProcessBrowserTest { public: RenderViewHostManagerTest() { EnableDOMAutomation(); } static bool GetFilePathWithHostAndPortReplacement( const std::string& original_file_path, const net::HostPortPair& host_port_pair, std::string* replacement_path) { std::vector<net::TestServer::StringPair> replacement_text; replacement_text.push_back( make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString())); return net::TestServer::GetFilePathWithReplacements( original_file_path, replacement_text, replacement_path); } }; // Test for crbug.com/24447. Following a cross-site link with rel=noreferrer // and target=_blank should create a new SiteInstance. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, SwapProcessWithRelNoreferrerAndTargetBlank) { // Start two servers with different sites. ASSERT_TRUE(test_server()->Start()); net::TestServer https_server( net::TestServer::TYPE_HTTPS, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(https_server.Start()); // Load a page with links that open in a new window. std::string replacement_path; ASSERT_TRUE(GetFilePathWithHostAndPortReplacement( "files/click-noreferrer-links.html", https_server.host_port_pair(), &replacement_path)); ui_test_utils::NavigateToURL(browser(), test_server()->GetURL(replacement_path)); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance != NULL); // Test clicking a rel=noreferrer + target=blank link. bool success = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(clickNoRefTargetBlankLink());", &success)); EXPECT_TRUE(success); // Wait for the tab to open. if (browser()->tab_count() < 2) ui_test_utils::WaitForNewTab(browser()); // Opens in new tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(1, browser()->active_index()); EXPECT_EQ("/files/title2.html", browser()->GetSelectedTabContents()->GetURL().path()); // Wait for the cross-site transition in the new tab to finish. ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents()); EXPECT_FALSE(browser()->GetSelectedTabContents()->render_manager()-> pending_render_view_host()); // Should have a new SiteInstance. scoped_refptr<SiteInstance> noref_blank_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, noref_blank_site_instance); } // Test for crbug.com/24447. Following a cross-site link with just // target=_blank should not create a new SiteInstance. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, DontSwapProcessWithOnlyTargetBlank) { // Start two servers with different sites. ASSERT_TRUE(test_server()->Start()); net::TestServer https_server( net::TestServer::TYPE_HTTPS, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(https_server.Start()); // Load a page with links that open in a new window. std::string replacement_path; ASSERT_TRUE(GetFilePathWithHostAndPortReplacement( "files/click-noreferrer-links.html", https_server.host_port_pair(), &replacement_path)); ui_test_utils::NavigateToURL(browser(), test_server()->GetURL(replacement_path)); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance != NULL); // Test clicking a target=blank link. bool success = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(clickTargetBlankLink());", &success)); EXPECT_TRUE(success); // Wait for the tab to open. if (browser()->tab_count() < 2) ui_test_utils::WaitForNewTab(browser()); // Opens in new tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(1, browser()->active_index()); // Wait for the cross-site transition in the new tab to finish. ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents()); EXPECT_EQ("/files/title2.html", browser()->GetSelectedTabContents()->GetURL().path()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> blank_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, blank_site_instance); } // Test for crbug.com/24447. Following a cross-site link with rel=noreferrer // and no target=_blank should not create a new SiteInstance. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, DontSwapProcessWithOnlyRelNoreferrer) { // Start two servers with different sites. ASSERT_TRUE(test_server()->Start()); net::TestServer https_server( net::TestServer::TYPE_HTTPS, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(https_server.Start()); // Load a page with links that open in a new window. std::string replacement_path; ASSERT_TRUE(GetFilePathWithHostAndPortReplacement( "files/click-noreferrer-links.html", https_server.host_port_pair(), &replacement_path)); ui_test_utils::NavigateToURL(browser(), test_server()->GetURL(replacement_path)); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance != NULL); // Test clicking a rel=noreferrer link. bool success = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(clickNoRefLink());", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition in the current tab to finish. ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents()); // Opens in same tab. EXPECT_EQ(1, browser()->tab_count()); EXPECT_EQ(0, browser()->active_index()); EXPECT_EQ("/files/title2.html", browser()->GetSelectedTabContents()->GetURL().path()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> noref_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, noref_site_instance); } // Test for crbug.com/14505. This tests that chrome:// urls are still functional // after download of a file while viewing another chrome://. // Hangs flakily in Win, http://crbug.com/45040, and started hanging on Linux, // Mac and ChromeOS, http://crbug.com/77762. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, DISABLED_ChromeURLAfterDownload) { GURL downloads_url("chrome://downloads"); GURL extensions_url("chrome://extensions"); FilePath zip_download; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download)); zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip"); GURL zip_url = net::FilePathToFileURL(zip_download); ui_test_utils::NavigateToURL(browser(), downloads_url); ui_test_utils::NavigateToURL(browser(), zip_url); ui_test_utils::WaitForDownloadCount( browser()->profile()->GetDownloadManager(), 1); ui_test_utils::NavigateToURL(browser(), extensions_url); TabContents *contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(contents); bool webui_responded = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( contents->render_view_host(), L"", L"window.domAutomationController.send(window.webui_responded_);", &webui_responded)); EXPECT_TRUE(webui_responded); } class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } // NotificationObserver virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::BROWSER_CLOSED: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } private: NotificationRegistrar registrar_; }; // Test for crbug.com/12745. This tests that if a download is initiated from // a chrome:// page that has registered and onunload handler, the browser // will be able to close. // TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix // must be found before this can be re-enabled. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, DISABLED_BrowserCloseAfterDownload) { GURL downloads_url("chrome://downloads"); FilePath zip_download; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download)); zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip"); ASSERT_TRUE(file_util::PathExists(zip_download)); GURL zip_url = net::FilePathToFileURL(zip_download); ui_test_utils::NavigateToURL(browser(), downloads_url); TabContents *contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(contents); bool result = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( contents->render_view_host(), L"", L"window.onunload = function() { var do_nothing = 0; }; " L"window.domAutomationController.send(true);", &result)); EXPECT_TRUE(result); ui_test_utils::NavigateToURL(browser(), zip_url); ui_test_utils::WaitForDownloadCount( browser()->profile()->GetDownloadManager(), 1); browser()->CloseWindow(); BrowserClosedObserver wait_for_close(browser()); } // Test for crbug.com/76666. A cross-site navigation that fails with a 204 // error should not make us ignore future renderer-initiated navigations. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, ClickLinkAfter204Error) { // Start two servers with different sites. ASSERT_TRUE(test_server()->Start()); net::TestServer https_server( net::TestServer::TYPE_HTTPS, FilePath(FILE_PATH_LITERAL("chrome/test/data"))); ASSERT_TRUE(https_server.Start()); // Load a page with links that open in a new window. // The links will point to the HTTPS server. std::string replacement_path; ASSERT_TRUE(GetFilePathWithHostAndPortReplacement( "files/click-noreferrer-links.html", https_server.host_port_pair(), &replacement_path)); ui_test_utils::NavigateToURL(browser(), test_server()->GetURL(replacement_path)); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance != NULL); // Load a cross-site page that fails with a 204 error. ui_test_utils::NavigateToURL(browser(), https_server.GetURL("nocontent")); // We should still be looking at the normal page. scoped_refptr<SiteInstance> post_nav_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, post_nav_site_instance); EXPECT_EQ("/files/click-noreferrer-links.html", browser()->GetSelectedTabContents()->GetURL().path()); // Renderer-initiated navigations should work. bool success = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(clickNoRefLink());", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition in the current tab to finish. ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents()); // Opens in same tab. EXPECT_EQ(1, browser()->tab_count()); EXPECT_EQ(0, browser()->active_index()); EXPECT_EQ("/files/title2.html", browser()->GetSelectedTabContents()->GetURL().path()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> noref_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, noref_site_instance); }
39.581871
80
0.729039
meego-tablet-ux
1e038e139bc61d954514cfba10c7e37cafe361b8
1,303
cpp
C++
src/reflection/parser/api/core/clang/visitor.cpp
roscopecoltran/siplasplas
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
[ "MIT" ]
182
2016-07-19T19:31:47.000Z
2022-02-22T13:54:25.000Z
src/reflection/parser/api/core/clang/visitor.cpp
roscopecoltran/siplasplas
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
[ "MIT" ]
50
2016-07-13T16:49:31.000Z
2018-06-15T13:39:49.000Z
src/reflection/parser/api/core/clang/visitor.cpp
GueimUCM/ceplusplus
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
[ "MIT" ]
26
2015-12-14T11:35:41.000Z
2022-02-22T19:13:48.000Z
#include "visitor.hpp" using namespace ::cpp::reflection::parser::api::core::clang; bool Visitor::visit(const Cursor& cursor) const { return ::clang_visitChildren( cursor.cxCursor(), +[](::CXCursor current, ::CXCursor parent, CXClientData userData) { const auto* self = const_cast<const Visitor*>(reinterpret_cast<Visitor*>(userData)); return static_cast<::CXChildVisitResult>(self->onCursor( Tag(), Cursor{current}, Cursor{parent} )); }, reinterpret_cast<void*>(const_cast<Visitor*>(this)) ); } bool Visitor::visit(const Cursor& cursor) { return ::clang_visitChildren( cursor.cxCursor(), +[](::CXCursor current, ::CXCursor parent, CXClientData userData) { auto* self = reinterpret_cast<Visitor*>(userData); return static_cast<::CXChildVisitResult>(self->onCursor( Tag(), Cursor{current}, Cursor{parent} )); }, reinterpret_cast<void*>(this) ); } Visitor::Result Visitor::onCursor(Visitor::Tag, const Cursor& current, const Cursor& parent) const { return Result::Break; } Visitor::Result Visitor::onCursor(Visitor::Tag, const Cursor& current, const Cursor& parent) { return Result::Break; }
29.613636
98
0.624712
roscopecoltran