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
eaaee55d560d16a2957b2c5fb53f02afae059dec
2,406
cpp
C++
src/zmqConsumerPoll.cpp
tompatman/zmqplus
efea491f2e9ca8f531ec7e102564fb56b1d62e0f
[ "MIT" ]
null
null
null
src/zmqConsumerPoll.cpp
tompatman/zmqplus
efea491f2e9ca8f531ec7e102564fb56b1d62e0f
[ "MIT" ]
null
null
null
src/zmqConsumerPoll.cpp
tompatman/zmqplus
efea491f2e9ca8f531ec7e102564fb56b1d62e0f
[ "MIT" ]
null
null
null
/* * zmqConsumerPoll.cpp * * Created on: May 31, 2013 * Author: service */ #include "../include/zmqConsumerPoll.h" using std::string; zmqConsumerPoll::zmqConsumerPoll(ppcLogger *log, uint num_consumers_to_poll, int timeout_ms) : _log(log) , _num_consumers(num_consumers_to_poll) , _timeout_ms(timeout_ms) { _items = (zmq::pollitem_t *) new zmq::pollitem_t[_num_consumers]; } zmqConsumerPoll::~zmqConsumerPoll() { delete[] _items; } void zmqConsumerPoll::Add(iConsumer *a_consumer) { uint idx = _consumer_list.size(); poco_assert(idx < _num_consumers); _consumer_list.push_back(a_consumer); _items[idx].events = ZMQ_POLLIN; _items[idx].fd = 0; _items[idx].socket = a_consumer->get_sub_socket_for_poll(); } int zmqConsumerPoll::Poll() { poco_assert(_consumer_list.size() == _num_consumers); int number_signaled = zmq::poll(_items, _num_consumers, _timeout_ms); if(number_signaled > 0) // Any updates { int count = 0; for (uint i = 0; i < _num_consumers; ++i) { if(_items[i].revents & ZMQ_POLLIN) { if(!_consumer_list[i]->update_data_share()) _items[i].revents = 0; // Remove the signal if it does not return true. count++; } } poco_assert(count == number_signaled); // Better be the same. } if(number_signaled < 0) { _log->log(LG_ERR, "zmq::poll returned error[%d]:", zmq_errno(), zmq_strerror(zmq_errno())); throw Poco::RuntimeException(string("zmq::poll returned error[]:") + zmq_strerror(zmq_errno())); } return number_signaled; } bool zmqConsumerPoll::WasSignaled(uint consumer_idx) { poco_assert(consumer_idx < _num_consumers); return (_items[consumer_idx].revents & ZMQ_POLLIN); } bool zmqConsumerPoll::WasSignaled(iConsumer *a_consumer) { bool was_signaled = false; uint i = 0; for (; i < _num_consumers; ++i) { if(_consumer_list[i] == a_consumer) { was_signaled = (_items[i].revents & ZMQ_POLLIN); break; } } if(i == _num_consumers) { _log->log(LG_ERR, "The consumer was not found in the list!"); throw Poco::RuntimeException("WasSignaled() : The consumer was not found in the list!"); } return was_signaled; }
23.588235
112
0.620116
tompatman
eaaf2f4745d98ff1b2d861e75db041301a3a0122
2,341
cpp
C++
midterm_mbghazi.cpp
mbghazi/Data-Structures
4703488686d2a78267fcd5a6adcbeda36ac10703
[ "MIT" ]
null
null
null
midterm_mbghazi.cpp
mbghazi/Data-Structures
4703488686d2a78267fcd5a6adcbeda36ac10703
[ "MIT" ]
null
null
null
midterm_mbghazi.cpp
mbghazi/Data-Structures
4703488686d2a78267fcd5a6adcbeda36ac10703
[ "MIT" ]
null
null
null
/* ** PROGRAM: Matrix Multiply ** ** PURPOSE: This is a simple matrix multiply program. ** It will compute the product ** ** C = A * B ** ** A and B are set to constant matrices so we ** can make a quick test of the multiplication. ** ** USAGE: Right now, I hardwire the martix dimensions. ** later, I'll take them from the command line. ** ** HISTORY: Written by Tim Mattson, Nov 1999. */ #include <iostream> #include <omp.h> using namespace std; #define ORDER 500 #define AVAL 3.0 #define BVAL 5.0 #define TOL 0.001 #define Ndim ORDER #define Pdim ORDER #define Mdim ORDER #define NUM_THREADS 4//added int main(int argc, char **argv) { double A[Ndim][Pdim], B[Pdim][Mdim], C[Ndim][Mdim]; int i,j,k; //double *A, *B, *C, double cval, tmp, err, errsq; double dN, mflops; double start_time, run_time; double sum; omp_set_num_threads(NUM_THREADS); start_time = omp_get_wtime(); /* Initialize matrices */ for (i=0; i<Ndim; i++) for (j=0; j<Pdim; j++) A[i][j] = AVAL; for (i=0; i<Pdim; i++) for (j=0; j<Mdim; j++) B[i][j] = BVAL; for (i=0; i<Ndim; i++) for (j=0; j<Mdim; j++) C[i][j] = 0.0; /* Do the matrix product */ #pragma parallel for schedule(dynamic) lastprivate(sum) red(-tmp) for (i=0; i<Ndim; i++){ //added //#pragma parallel for for (j=0; j<Mdim; j++){ tmp = 0.0; //#pragma parallel for schedule(dynamic) lastprivate(tmp) for(k=0;k<Pdim;k++){ /* C(i,j) = sum(over k) A(i,k) * B(k,j) */ tmp += A[i][k] * B[k][j]; } C[i][j] = tmp; sum += tmp; } } /* Check the answer */ cout << "Summary is " << sum << endl; cval = Pdim * AVAL * BVAL; errsq = 0.0; for (i=0; i<Ndim; i++){ for (j=0; j<Mdim; j++){ err = C[i][j] - cval; errsq += err * err; } } errsq += sum - cval*Ndim*Mdim; if (errsq > TOL) cout << "Errors in multiplication: "<< errsq<< endl; else cout << "Hey, it worked! Error is: " << errsq << endl; run_time = omp_get_wtime() - start_time; cout << "Order " << ORDER << " multiplication in " << run_time << " seconds "<< endl; dN = (double)ORDER; mflops = 2.0 * dN * dN * dN/(1000000.0* run_time); cout << "Order " << " multiplication at " << mflops << " mflops" << endl; cout << "All done "<< endl; return 0; }
22.509615
86
0.564289
mbghazi
eab068770436f9db993275b1ce35ad8d8dba1c8d
1,444
cc
C++
src/boson/test/queues_weakrb.cc
duckie/boson
f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a
[ "MIT" ]
174
2016-10-10T12:47:01.000Z
2022-03-09T16:06:59.000Z
src/boson/test/queues_weakrb.cc
duckie/boson
f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a
[ "MIT" ]
5
2017-02-01T21:30:14.000Z
2018-09-09T10:02:00.000Z
src/boson/test/queues_weakrb.cc
duckie/boson
f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a
[ "MIT" ]
13
2016-10-10T12:19:14.000Z
2021-12-04T08:23:26.000Z
#include <iostream> #include <limits> #include <random> #include <thread> #include "boson/queues/weakrb.h" #include "catch.hpp" TEST_CASE("Queues - WeakRB - serial random integers", "[queues][weakrb]") { constexpr size_t const sample_size = 1e4; std::random_device seed; std::mt19937_64 generator{seed()}; std::uniform_int_distribution<int> distribution(std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); std::vector<int> sample; sample.reserve(sample_size); for (size_t index = 0; index < sample_size; ++index) sample.emplace_back(distribution(generator)); // Create the buffer std::vector<int> destination; destination.reserve(sample_size); boson::queues::weakrb<int> queue(1); std::thread t1([&sample, &queue]() { for (auto v : sample) { bool success = false; int value = v; // Ugly spin lock, osef while (!success) { success = queue.write(value); std::this_thread::yield(); } } }); std::thread t2([&destination, &queue]() { for (size_t index = 0; index < sample_size; ++index) { bool success = false; int result{}; // Ugly spin lock, osef while (!success) { success = queue.read(result); std::this_thread::yield(); } destination.emplace_back(result); } }); t1.join(); t2.join(); CHECK(sample == destination); }
25.333333
83
0.605956
duckie
eab334692c7e899abd7ef97fc35637752d552cba
64,611
cpp
C++
src/slg/film/film.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
src/slg/film/film.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
src/slg/film/film.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * Copyright 1998-2015 by authors (see AUTHORS.txt) * * * * This file is part of LuxRender. * * * * 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 <limits> #include <algorithm> #include <exception> #include <boost/lexical_cast.hpp> #include <boost/foreach.hpp> #include <OpenImageIO/imageio.h> #include <OpenImageIO/imagebuf.h> OIIO_NAMESPACE_USING #include "luxrays/core/geometry/point.h" #include "luxrays/utils/properties.h" #include "slg/film/film.h" #include "slg/film/filters/gaussian.h" #include "slg/editaction.h" using namespace std; using namespace luxrays; using namespace slg; typedef unsigned char BYTE; //------------------------------------------------------------------------------ // FilmOutput //------------------------------------------------------------------------------ void FilmOutputs::Add(const FilmOutputType type, const string &fileName, const Properties *p) { types.push_back(type); fileNames.push_back(fileName); if (p) props.push_back(*p); else props.push_back(Properties()); } //------------------------------------------------------------------------------ // Film //------------------------------------------------------------------------------ Film::Film(const u_int w, const u_int h) { initialized = false; width = w; height = h; radianceGroupCount = 1; channel_ALPHA = NULL; channel_RGB_TONEMAPPED = NULL; channel_DEPTH = NULL; channel_POSITION = NULL; channel_GEOMETRY_NORMAL = NULL; channel_SHADING_NORMAL = NULL; channel_MATERIAL_ID = NULL; channel_DIRECT_DIFFUSE = NULL; channel_DIRECT_GLOSSY = NULL; channel_EMISSION = NULL; channel_INDIRECT_DIFFUSE = NULL; channel_INDIRECT_GLOSSY = NULL; channel_INDIRECT_SPECULAR = NULL; channel_DIRECT_SHADOW_MASK = NULL; channel_INDIRECT_SHADOW_MASK = NULL; channel_UV = NULL; channel_RAYCOUNT = NULL; channel_IRRADIANCE = NULL; convTest = NULL; enabledOverlappedScreenBufferUpdate = true; rgbTonemapUpdate = true; imagePipeline = NULL; filter = NULL; filterLUTs = NULL; SetFilter(new GaussianFilter(1.5f, 1.5f, 2.f)); } Film::~Film() { delete imagePipeline; delete convTest; for (u_int i = 0; i < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size(); ++i) delete channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]; for (u_int i = 0; i < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size(); ++i) delete channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]; delete channel_ALPHA; delete channel_RGB_TONEMAPPED; delete channel_DEPTH; delete channel_POSITION; delete channel_GEOMETRY_NORMAL; delete channel_SHADING_NORMAL; delete channel_MATERIAL_ID; delete channel_DIRECT_DIFFUSE; delete channel_DIRECT_GLOSSY; delete channel_EMISSION; delete channel_INDIRECT_DIFFUSE; delete channel_INDIRECT_GLOSSY; delete channel_INDIRECT_SPECULAR; for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i) delete channel_MATERIAL_ID_MASKs[i]; delete channel_DIRECT_SHADOW_MASK; delete channel_INDIRECT_SHADOW_MASK; delete channel_UV; delete channel_RAYCOUNT; for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i) delete channel_BY_MATERIAL_IDs[i]; delete channel_IRRADIANCE; delete filterLUTs; delete filter; } void Film::AddChannel(const FilmChannelType type, const Properties *prop) { if (initialized) throw runtime_error("It is only possible to add a channel to a Film before initialization"); channels.insert(type); switch (type) { case MATERIAL_ID_MASK: { const u_int id = prop->Get(Property("id")(255)).Get<u_int>(); if (count(maskMaterialIDs.begin(), maskMaterialIDs.end(), id) == 0) maskMaterialIDs.push_back(id); break; } case BY_MATERIAL_ID: { const u_int id = prop->Get(Property("id")(255)).Get<u_int>(); if (count(byMaterialIDs.begin(), byMaterialIDs.end(), id) == 0) byMaterialIDs.push_back(id); break; } default: break; } } void Film::RemoveChannel(const FilmChannelType type) { if (initialized) throw runtime_error("It is only possible to remove a channel from a Film before initialization"); channels.erase(type); } void Film::Init() { if (initialized) throw runtime_error("A Film can not be initialized multiple times"); initialized = true; Resize(width, height); } void Film::Resize(const u_int w, const u_int h) { width = w; height = h; pixelCount = w * h; delete convTest; convTest = NULL; // Delete all already allocated channels for (u_int i = 0; i < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size(); ++i) delete channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]; channel_RADIANCE_PER_PIXEL_NORMALIZEDs.clear(); for (u_int i = 0; i < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size(); ++i) delete channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]; channel_RADIANCE_PER_SCREEN_NORMALIZEDs.clear(); delete channel_ALPHA; delete channel_RGB_TONEMAPPED; delete channel_DEPTH; delete channel_POSITION; delete channel_GEOMETRY_NORMAL; delete channel_SHADING_NORMAL; delete channel_MATERIAL_ID; delete channel_DIRECT_DIFFUSE; delete channel_DIRECT_GLOSSY; delete channel_EMISSION; delete channel_INDIRECT_DIFFUSE; delete channel_INDIRECT_GLOSSY; delete channel_INDIRECT_SPECULAR; for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i) delete channel_MATERIAL_ID_MASKs[i]; channel_MATERIAL_ID_MASKs.clear(); delete channel_DIRECT_SHADOW_MASK; delete channel_INDIRECT_SHADOW_MASK; delete channel_UV; delete channel_RAYCOUNT; for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i) delete channel_BY_MATERIAL_IDs[i]; channel_BY_MATERIAL_IDs.clear(); delete channel_IRRADIANCE; // Allocate all required channels hasDataChannel = false; hasComposingChannel = false; if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { channel_RADIANCE_PER_PIXEL_NORMALIZEDs.resize(radianceGroupCount, NULL); for (u_int i = 0; i < radianceGroupCount; ++i) { channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i] = new GenericFrameBuffer<4, 1, float>(width, height); channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->Clear(); } } if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) { channel_RADIANCE_PER_SCREEN_NORMALIZEDs.resize(radianceGroupCount, NULL); for (u_int i = 0; i < radianceGroupCount; ++i) { channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i] = new GenericFrameBuffer<3, 0, float>(width, height); channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->Clear(); } } if (HasChannel(ALPHA)) { channel_ALPHA = new GenericFrameBuffer<2, 1, float>(width, height); channel_ALPHA->Clear(); } if (HasChannel(RGB_TONEMAPPED)) { channel_RGB_TONEMAPPED = new GenericFrameBuffer<3, 0, float>(width, height); channel_RGB_TONEMAPPED->Clear(); convTest = new ConvergenceTest(width, height); } if (HasChannel(DEPTH)) { channel_DEPTH = new GenericFrameBuffer<1, 0, float>(width, height); channel_DEPTH->Clear(numeric_limits<float>::infinity()); hasDataChannel = true; } if (HasChannel(POSITION)) { channel_POSITION = new GenericFrameBuffer<3, 0, float>(width, height); channel_POSITION->Clear(numeric_limits<float>::infinity()); hasDataChannel = true; } if (HasChannel(GEOMETRY_NORMAL)) { channel_GEOMETRY_NORMAL = new GenericFrameBuffer<3, 0, float>(width, height); channel_GEOMETRY_NORMAL->Clear(numeric_limits<float>::infinity()); hasDataChannel = true; } if (HasChannel(SHADING_NORMAL)) { channel_SHADING_NORMAL = new GenericFrameBuffer<3, 0, float>(width, height); channel_SHADING_NORMAL->Clear(numeric_limits<float>::infinity()); hasDataChannel = true; } if (HasChannel(MATERIAL_ID)) { channel_MATERIAL_ID = new GenericFrameBuffer<1, 0, u_int>(width, height); channel_MATERIAL_ID->Clear(numeric_limits<u_int>::max()); hasDataChannel = true; } if (HasChannel(DIRECT_DIFFUSE)) { channel_DIRECT_DIFFUSE = new GenericFrameBuffer<4, 1, float>(width, height); channel_DIRECT_DIFFUSE->Clear(); hasComposingChannel = true; } if (HasChannel(DIRECT_GLOSSY)) { channel_DIRECT_GLOSSY = new GenericFrameBuffer<4, 1, float>(width, height); channel_DIRECT_GLOSSY->Clear(); hasComposingChannel = true; } if (HasChannel(EMISSION)) { channel_EMISSION = new GenericFrameBuffer<4, 1, float>(width, height); channel_EMISSION->Clear(); hasComposingChannel = true; } if (HasChannel(INDIRECT_DIFFUSE)) { channel_INDIRECT_DIFFUSE = new GenericFrameBuffer<4, 1, float>(width, height); channel_INDIRECT_DIFFUSE->Clear(); hasComposingChannel = true; } if (HasChannel(INDIRECT_GLOSSY)) { channel_INDIRECT_GLOSSY = new GenericFrameBuffer<4, 1, float>(width, height); channel_INDIRECT_GLOSSY->Clear(); hasComposingChannel = true; } if (HasChannel(INDIRECT_SPECULAR)) { channel_INDIRECT_SPECULAR = new GenericFrameBuffer<4, 1, float>(width, height); channel_INDIRECT_SPECULAR->Clear(); hasComposingChannel = true; } if (HasChannel(MATERIAL_ID_MASK)) { for (u_int i = 0; i < maskMaterialIDs.size(); ++i) { GenericFrameBuffer<2, 1, float> *buf = new GenericFrameBuffer<2, 1, float>(width, height); buf->Clear(); channel_MATERIAL_ID_MASKs.push_back(buf); } hasComposingChannel = true; } if (HasChannel(DIRECT_SHADOW_MASK)) { channel_DIRECT_SHADOW_MASK = new GenericFrameBuffer<2, 1, float>(width, height); channel_DIRECT_SHADOW_MASK->Clear(); hasComposingChannel = true; } if (HasChannel(INDIRECT_SHADOW_MASK)) { channel_INDIRECT_SHADOW_MASK = new GenericFrameBuffer<2, 1, float>(width, height); channel_INDIRECT_SHADOW_MASK->Clear(); hasComposingChannel = true; } if (HasChannel(UV)) { channel_UV = new GenericFrameBuffer<2, 0, float>(width, height); channel_UV->Clear(numeric_limits<float>::infinity()); hasDataChannel = true; } if (HasChannel(RAYCOUNT)) { channel_RAYCOUNT = new GenericFrameBuffer<1, 0, float>(width, height); channel_RAYCOUNT->Clear(); hasDataChannel = true; } if (HasChannel(BY_MATERIAL_ID)) { for (u_int i = 0; i < byMaterialIDs.size(); ++i) { GenericFrameBuffer<4, 1, float> *buf = new GenericFrameBuffer<4, 1, float>(width, height); buf->Clear(); channel_BY_MATERIAL_IDs.push_back(buf); } hasComposingChannel = true; } if (HasChannel(IRRADIANCE)) { channel_IRRADIANCE = new GenericFrameBuffer<4, 1, float>(width, height); channel_IRRADIANCE->Clear(); hasComposingChannel = true; } // Initialize the stats statsTotalSampleCount = 0.0; statsAvgSampleSec = 0.0; statsStartSampleTime = WallClockTime(); } void Film::SetFilter(Filter *flt) { delete filterLUTs; filterLUTs = NULL; delete filter; filter = flt; if (filter) { const u_int size = Max<u_int>(4, Max(filter->xWidth, filter->yWidth) + 1); filterLUTs = new FilterLUTs(*filter, size); } } void Film::Reset() { if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { for (u_int i = 0; i < radianceGroupCount; ++i) channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->Clear(); } if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) { for (u_int i = 0; i < radianceGroupCount; ++i) channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->Clear(); } if (HasChannel(ALPHA)) channel_ALPHA->Clear(); if (HasChannel(DEPTH)) channel_DEPTH->Clear(numeric_limits<float>::infinity()); if (HasChannel(POSITION)) channel_POSITION->Clear(numeric_limits<float>::infinity()); if (HasChannel(GEOMETRY_NORMAL)) channel_GEOMETRY_NORMAL->Clear(numeric_limits<float>::infinity()); if (HasChannel(SHADING_NORMAL)) channel_SHADING_NORMAL->Clear(numeric_limits<float>::infinity()); if (HasChannel(MATERIAL_ID)) channel_MATERIAL_ID->Clear(numeric_limits<float>::max()); if (HasChannel(DIRECT_DIFFUSE)) channel_DIRECT_DIFFUSE->Clear(); if (HasChannel(DIRECT_GLOSSY)) channel_DIRECT_GLOSSY->Clear(); if (HasChannel(EMISSION)) channel_EMISSION->Clear(); if (HasChannel(INDIRECT_DIFFUSE)) channel_INDIRECT_DIFFUSE->Clear(); if (HasChannel(INDIRECT_GLOSSY)) channel_INDIRECT_GLOSSY->Clear(); if (HasChannel(INDIRECT_SPECULAR)) channel_INDIRECT_SPECULAR->Clear(); if (HasChannel(MATERIAL_ID_MASK)) { for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i) channel_MATERIAL_ID_MASKs[i]->Clear(); } if (HasChannel(DIRECT_SHADOW_MASK)) channel_DIRECT_SHADOW_MASK->Clear(); if (HasChannel(INDIRECT_SHADOW_MASK)) channel_INDIRECT_SHADOW_MASK->Clear(); if (HasChannel(UV)) channel_UV->Clear(); if (HasChannel(RAYCOUNT)) channel_RAYCOUNT->Clear(); if (HasChannel(BY_MATERIAL_ID)) { for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i) channel_BY_MATERIAL_IDs[i]->Clear(); } if (HasChannel(IRRADIANCE)) channel_IRRADIANCE->Clear(); // convTest has to be reset explicitly statsTotalSampleCount = 0.0; statsAvgSampleSec = 0.0; statsStartSampleTime = WallClockTime(); } void Film::AddFilm(const Film &film, const u_int srcOffsetX, const u_int srcOffsetY, const u_int srcWidth, const u_int srcHeight, const u_int dstOffsetX, const u_int dstOffsetY) { statsTotalSampleCount += film.statsTotalSampleCount; if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && film.HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { for (u_int i = 0; i < Min(radianceGroupCount, film.radianceGroupCount); ++i) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED) && film.HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) { for (u_int i = 0; i < Min(radianceGroupCount, film.radianceGroupCount); ++i) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(ALPHA) && film.HasChannel(ALPHA)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_ALPHA->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_ALPHA->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(POSITION) && film.HasChannel(POSITION)) { if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { // Used DEPTH information to merge Films for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) { const float *srcPixel = film.channel_POSITION->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_POSITION->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } else { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_POSITION->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_POSITION->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(GEOMETRY_NORMAL) && film.HasChannel(GEOMETRY_NORMAL)) { if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { // Used DEPTH information to merge Films for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) { const float *srcPixel = film.channel_GEOMETRY_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_GEOMETRY_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } else { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_GEOMETRY_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_GEOMETRY_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(SHADING_NORMAL) && film.HasChannel(SHADING_NORMAL)) { if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { // Used DEPTH information to merge Films for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) { const float *srcPixel = film.channel_SHADING_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_SHADING_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } else { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_SHADING_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_SHADING_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(MATERIAL_ID) && film.HasChannel(MATERIAL_ID)) { if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { // Used DEPTH information to merge Films for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) { const u_int *srcPixel = film.channel_MATERIAL_ID->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_MATERIAL_ID->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } else { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const u_int *srcPixel = film.channel_MATERIAL_ID->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_MATERIAL_ID->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(DIRECT_DIFFUSE) && film.HasChannel(DIRECT_DIFFUSE)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_DIRECT_DIFFUSE->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_DIRECT_DIFFUSE->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(DIRECT_GLOSSY) && film.HasChannel(DIRECT_GLOSSY)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_DIRECT_GLOSSY->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_DIRECT_GLOSSY->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(EMISSION) && film.HasChannel(EMISSION)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_EMISSION->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_EMISSION->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(INDIRECT_DIFFUSE) && film.HasChannel(INDIRECT_DIFFUSE)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_INDIRECT_DIFFUSE->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_INDIRECT_DIFFUSE->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(INDIRECT_GLOSSY) && film.HasChannel(INDIRECT_GLOSSY)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_INDIRECT_GLOSSY->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_INDIRECT_GLOSSY->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(INDIRECT_SPECULAR) && film.HasChannel(INDIRECT_SPECULAR)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_INDIRECT_SPECULAR->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_INDIRECT_SPECULAR->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(MATERIAL_ID_MASK) && film.HasChannel(MATERIAL_ID_MASK)) { for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i) { for (u_int j = 0; j < film.maskMaterialIDs.size(); ++j) { if (maskMaterialIDs[i] == film.maskMaterialIDs[j]) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_MATERIAL_ID_MASKs[j]->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_MATERIAL_ID_MASKs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } } } if (HasChannel(DIRECT_SHADOW_MASK) && film.HasChannel(DIRECT_SHADOW_MASK)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_DIRECT_SHADOW_MASK->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_DIRECT_SHADOW_MASK->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(INDIRECT_SHADOW_MASK) && film.HasChannel(INDIRECT_SHADOW_MASK)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_INDIRECT_SHADOW_MASK->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_INDIRECT_SHADOW_MASK->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(UV) && film.HasChannel(UV)) { if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { // Used DEPTH information to merge Films for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) { const float *srcPixel = film.channel_UV->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_UV->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } else { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_UV->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_UV->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(RAYCOUNT) && film.HasChannel(RAYCOUNT)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_RAYCOUNT->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_RAYCOUNT->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(BY_MATERIAL_ID) && film.HasChannel(BY_MATERIAL_ID)) { for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i) { for (u_int j = 0; j < film.byMaterialIDs.size(); ++j) { if (byMaterialIDs[i] == film.byMaterialIDs[j]) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_BY_MATERIAL_IDs[j]->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_BY_MATERIAL_IDs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } } } if (HasChannel(IRRADIANCE) && film.HasChannel(IRRADIANCE)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_IRRADIANCE->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_IRRADIANCE->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } // NOTE: update DEPTH channel last because it is used to merge other channels if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_DEPTH->MinPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } u_int Film::GetChannelCount(const FilmChannelType type) const { switch (type) { case RADIANCE_PER_PIXEL_NORMALIZED: return channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size(); case RADIANCE_PER_SCREEN_NORMALIZED: return channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size(); case ALPHA: return channel_ALPHA ? 1 : 0; case RGB_TONEMAPPED: return channel_RGB_TONEMAPPED ? 1 : 0; case DEPTH: return channel_DEPTH ? 1 : 0; case POSITION: return channel_POSITION ? 1 : 0; case GEOMETRY_NORMAL: return channel_GEOMETRY_NORMAL ? 1 : 0; case SHADING_NORMAL: return channel_SHADING_NORMAL ? 1 : 0; case MATERIAL_ID: return channel_MATERIAL_ID ? 1 : 0; case DIRECT_DIFFUSE: return channel_DIRECT_DIFFUSE ? 1 : 0; case DIRECT_GLOSSY: return channel_DIRECT_GLOSSY ? 1 : 0; case EMISSION: return channel_EMISSION ? 1 : 0; case INDIRECT_DIFFUSE: return channel_INDIRECT_DIFFUSE ? 1 : 0; case INDIRECT_GLOSSY: return channel_INDIRECT_GLOSSY ? 1 : 0; case INDIRECT_SPECULAR: return channel_INDIRECT_SPECULAR ? 1 : 0; case MATERIAL_ID_MASK: return channel_MATERIAL_ID_MASKs.size(); case DIRECT_SHADOW_MASK: return channel_DIRECT_SHADOW_MASK ? 1 : 0; case INDIRECT_SHADOW_MASK: return channel_INDIRECT_SHADOW_MASK ? 1 : 0; case UV: return channel_UV ? 1 : 0; case RAYCOUNT: return channel_RAYCOUNT ? 1 : 0; case BY_MATERIAL_ID: return channel_BY_MATERIAL_IDs.size(); case IRRADIANCE: return channel_IRRADIANCE ? 1 : 0; default: throw runtime_error("Unknown FilmOutputType in Film::GetChannelCount>(): " + ToString(type)); } } size_t Film::GetOutputSize(const FilmOutputs::FilmOutputType type) const { switch (type) { case FilmOutputs::RGB: return 3 * pixelCount; case FilmOutputs::RGBA: return 4 * pixelCount; case FilmOutputs::RGB_TONEMAPPED: return 3 * pixelCount; case FilmOutputs::RGBA_TONEMAPPED: return 4 * pixelCount; case FilmOutputs::ALPHA: return pixelCount; case FilmOutputs::DEPTH: return pixelCount; case FilmOutputs::POSITION: return 3 * pixelCount; case FilmOutputs::GEOMETRY_NORMAL: return 3 * pixelCount; case FilmOutputs::SHADING_NORMAL: return 3 * pixelCount; case FilmOutputs::MATERIAL_ID: return pixelCount; case FilmOutputs::DIRECT_DIFFUSE: return 3 * pixelCount; case FilmOutputs::DIRECT_GLOSSY: return 3 * pixelCount; case FilmOutputs::EMISSION: return 3 * pixelCount; case FilmOutputs::INDIRECT_DIFFUSE: return 3 * pixelCount; case FilmOutputs::INDIRECT_GLOSSY: return 3 * pixelCount; case FilmOutputs::INDIRECT_SPECULAR: return 3 * pixelCount; case FilmOutputs::MATERIAL_ID_MASK: return pixelCount; case FilmOutputs::DIRECT_SHADOW_MASK: return pixelCount; case FilmOutputs::INDIRECT_SHADOW_MASK: return pixelCount; case FilmOutputs::RADIANCE_GROUP: return 3 * pixelCount; case FilmOutputs::UV: return 2 * pixelCount; case FilmOutputs::RAYCOUNT: return pixelCount; case FilmOutputs::BY_MATERIAL_ID: return 3 * pixelCount; case FilmOutputs::IRRADIANCE: return 3 * pixelCount; default: throw runtime_error("Unknown FilmOutputType in Film::GetOutputSize(): " + ToString(type)); } } bool Film::HasOutput(const FilmOutputs::FilmOutputType type) const { switch (type) { case FilmOutputs::RGB: return HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) || HasChannel(RADIANCE_PER_SCREEN_NORMALIZED); case FilmOutputs::RGB_TONEMAPPED: return HasChannel(RGB_TONEMAPPED); case FilmOutputs::RGBA: return (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) || HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) && HasChannel(ALPHA); case FilmOutputs::RGBA_TONEMAPPED: return HasChannel(RGB_TONEMAPPED) && HasChannel(ALPHA); case FilmOutputs::ALPHA: return HasChannel(ALPHA); case FilmOutputs::DEPTH: return HasChannel(DEPTH); case FilmOutputs::POSITION: return HasChannel(POSITION); case FilmOutputs::GEOMETRY_NORMAL: return HasChannel(GEOMETRY_NORMAL); case FilmOutputs::SHADING_NORMAL: return HasChannel(SHADING_NORMAL); case FilmOutputs::MATERIAL_ID: return HasChannel(MATERIAL_ID); case FilmOutputs::DIRECT_DIFFUSE: return HasChannel(DIRECT_DIFFUSE); case FilmOutputs::DIRECT_GLOSSY: return HasChannel(DIRECT_GLOSSY); case FilmOutputs::EMISSION: return HasChannel(EMISSION); case FilmOutputs::INDIRECT_DIFFUSE: return HasChannel(INDIRECT_DIFFUSE); case FilmOutputs::INDIRECT_GLOSSY: return HasChannel(INDIRECT_GLOSSY); case FilmOutputs::INDIRECT_SPECULAR: return HasChannel(INDIRECT_SPECULAR); case FilmOutputs::MATERIAL_ID_MASK: return HasChannel(MATERIAL_ID_MASK); case FilmOutputs::DIRECT_SHADOW_MASK: return HasChannel(DIRECT_SHADOW_MASK); case FilmOutputs::INDIRECT_SHADOW_MASK: return HasChannel(INDIRECT_SHADOW_MASK); case FilmOutputs::RADIANCE_GROUP: return true; case FilmOutputs::UV: return HasChannel(UV); case FilmOutputs::RAYCOUNT: return HasChannel(RAYCOUNT); case FilmOutputs::BY_MATERIAL_ID: return HasChannel(BY_MATERIAL_ID); case FilmOutputs::IRRADIANCE: return HasChannel(IRRADIANCE); default: throw runtime_error("Unknown film output type in Film::HasOutput(): " + ToString(type)); } } void Film::Output(const FilmOutputs &filmOutputs) { for (u_int i = 0; i < filmOutputs.GetCount(); ++i) Output(filmOutputs.GetType(i), filmOutputs.GetFileName(i), &filmOutputs.GetProperties(i)); } void Film::Output(const FilmOutputs::FilmOutputType type, const string &fileName, const Properties *props) { u_int maskMaterialIDsIndex = 0; u_int byMaterialIDsIndex = 0; u_int radianceGroupIndex = 0; u_int channelCount = 3; switch (type) { case FilmOutputs::RGB: if (!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) return; break; case FilmOutputs::RGB_TONEMAPPED: if (!HasChannel(RGB_TONEMAPPED)) return; ExecuteImagePipeline(); break; case FilmOutputs::RGBA: if ((!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) || !HasChannel(ALPHA)) return; channelCount = 4; break; case FilmOutputs::RGBA_TONEMAPPED: if (!HasChannel(RGB_TONEMAPPED) || !HasChannel(ALPHA)) return; ExecuteImagePipeline(); channelCount = 4; break; case FilmOutputs::ALPHA: if (!HasChannel(ALPHA)) return; channelCount = 1; break; case FilmOutputs::DEPTH: if (!HasChannel(DEPTH)) return; channelCount = 1; break; case FilmOutputs::POSITION: if (!HasChannel(POSITION)) return; break; case FilmOutputs::GEOMETRY_NORMAL: if (!HasChannel(GEOMETRY_NORMAL)) return; break; case FilmOutputs::SHADING_NORMAL: if (!HasChannel(SHADING_NORMAL)) return; break; case FilmOutputs::MATERIAL_ID: if (!HasChannel(MATERIAL_ID)) return; break; case FilmOutputs::DIRECT_DIFFUSE: if (!HasChannel(DIRECT_DIFFUSE)) return; break; case FilmOutputs::DIRECT_GLOSSY: if (!HasChannel(DIRECT_GLOSSY)) return; break; case FilmOutputs::EMISSION: if (!HasChannel(EMISSION)) return; break; case FilmOutputs::INDIRECT_DIFFUSE: if (!HasChannel(INDIRECT_DIFFUSE)) return; break; case FilmOutputs::INDIRECT_GLOSSY: if (!HasChannel(INDIRECT_GLOSSY)) return; break; case FilmOutputs::INDIRECT_SPECULAR: if (!HasChannel(INDIRECT_SPECULAR)) return; break; case FilmOutputs::MATERIAL_ID_MASK: if (HasChannel(MATERIAL_ID_MASK) && props) { channelCount = 1; // Look for the material mask ID index const u_int id = props->Get(Property("id")(255)).Get<u_int>(); bool found = false; for (u_int i = 0; i < maskMaterialIDs.size(); ++i) { if (maskMaterialIDs[i] == id) { maskMaterialIDsIndex = i; found = true; break; } } if (!found) return; } else return; break; case FilmOutputs::DIRECT_SHADOW_MASK: if (!HasChannel(DIRECT_SHADOW_MASK)) return; channelCount = 1; break; case FilmOutputs::INDIRECT_SHADOW_MASK: if (!HasChannel(INDIRECT_SHADOW_MASK)) return; channelCount = 1; break; case FilmOutputs::RADIANCE_GROUP: if (!props) return; radianceGroupIndex = props->Get(Property("id")(0)).Get<u_int>(); if (radianceGroupIndex >= radianceGroupCount) return; break; case FilmOutputs::UV: if (!HasChannel(UV)) return; break; case FilmOutputs::RAYCOUNT: if (!HasChannel(RAYCOUNT)) return; channelCount = 1; break; case FilmOutputs::BY_MATERIAL_ID: if (HasChannel(BY_MATERIAL_ID) && props) { // Look for the material mask ID index const u_int id = props->Get(Property("id")(255)).Get<u_int>(); bool found = false; for (u_int i = 0; i < byMaterialIDs.size(); ++i) { if (byMaterialIDs[i] == id) { byMaterialIDsIndex = i; found = true; break; } } if (!found) return; } else return; break; case FilmOutputs::IRRADIANCE: if (!HasChannel(IRRADIANCE)) return; break; default: throw runtime_error("Unknown film output type in Film::Output(): " + ToString(type)); } ImageBuf buffer; SLG_LOG("Outputting film: " << fileName << " type: " << ToString(type)); if (type == FilmOutputs::MATERIAL_ID) { // For material IDs we must copy into int buffer first or risk screwing up the ID ImageSpec spec(width, height, channelCount, TypeDesc::UINT8); buffer.reset(spec); for (ImageBuf::ConstIterator<BYTE> it(buffer); !it.done(); ++it) { u_int x = it.x(); u_int y = it.y(); BYTE *pixel = (BYTE *)buffer.pixeladdr(x, y, 0); y = height - y - 1; if (pixel == NULL) throw runtime_error("Error while unpacking film data, could not address buffer!"); const u_int *src = channel_MATERIAL_ID->GetPixel(x, y); pixel[0] = (BYTE)src[0]; pixel[1] = (BYTE)src[1]; pixel[2] = (BYTE)src[2]; } } else { // OIIO 1 channel EXR output is apparently not working, I write 3 channels as // temporary workaround // For all others copy into float buffer first and let OIIO figure out the conversion on write ImageSpec spec(width, height, (channelCount == 1) ? 3 : channelCount, TypeDesc::FLOAT); buffer.reset(spec); for (ImageBuf::ConstIterator<float> it(buffer); !it.done(); ++it) { u_int x = it.x(); u_int y = it.y(); float *pixel = (float *)buffer.pixeladdr(x, y, 0); y = height - y - 1; if (pixel == NULL) throw runtime_error("Error while unpacking film data, could not address buffer!"); switch (type) { case FilmOutputs::RGB: { // Accumulate all light groups GetPixelFromMergedSampleBuffers(x, y, pixel); break; } case FilmOutputs::RGB_TONEMAPPED: { channel_RGB_TONEMAPPED->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::RGBA: { // Accumulate all light groups GetPixelFromMergedSampleBuffers(x, y, pixel); channel_ALPHA->GetWeightedPixel(x, y, &pixel[3]); break; } case FilmOutputs::RGBA_TONEMAPPED: { channel_RGB_TONEMAPPED->GetWeightedPixel(x, y, pixel); channel_ALPHA->GetWeightedPixel(x, y, &pixel[3]); break; } case FilmOutputs::ALPHA: { channel_ALPHA->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::DEPTH: { channel_DEPTH->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::POSITION: { channel_POSITION->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::GEOMETRY_NORMAL: { channel_GEOMETRY_NORMAL->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::SHADING_NORMAL: { channel_SHADING_NORMAL->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::DIRECT_DIFFUSE: { channel_DIRECT_DIFFUSE->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::DIRECT_GLOSSY: { channel_DIRECT_GLOSSY->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::EMISSION: { channel_EMISSION->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::INDIRECT_DIFFUSE: { channel_INDIRECT_DIFFUSE->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::INDIRECT_GLOSSY: { channel_INDIRECT_GLOSSY->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::INDIRECT_SPECULAR: { channel_INDIRECT_SPECULAR->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::MATERIAL_ID_MASK: { channel_MATERIAL_ID_MASKs[maskMaterialIDsIndex]->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::DIRECT_SHADOW_MASK: { channel_DIRECT_SHADOW_MASK->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::INDIRECT_SHADOW_MASK: { channel_INDIRECT_SHADOW_MASK->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::RADIANCE_GROUP: { // Accumulate all light groups if (radianceGroupIndex < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()) channel_RADIANCE_PER_PIXEL_NORMALIZEDs[radianceGroupIndex]->AccumulateWeightedPixel(x, y, pixel); if (radianceGroupIndex < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()) channel_RADIANCE_PER_SCREEN_NORMALIZEDs[radianceGroupIndex]->AccumulateWeightedPixel(x, y, pixel); break; } case FilmOutputs::UV: { channel_UV->GetWeightedPixel(x, y, pixel); pixel[2] = 0.f; break; } case FilmOutputs::RAYCOUNT: { channel_RAYCOUNT->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::BY_MATERIAL_ID: { channel_BY_MATERIAL_IDs[byMaterialIDsIndex]->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::IRRADIANCE: { channel_IRRADIANCE->GetWeightedPixel(x, y, pixel); break; } default: throw runtime_error("Unknown film output type in Film::Output(): " + ToString(type)); } // OIIO 1 channel EXR output is apparently not working, I write 3 channels as // temporary workaround if (channelCount == 1) { pixel[1] = pixel[0]; pixel[2] = pixel[0]; } } } buffer.write(fileName); } template<> const float *Film::GetChannel<float>(const FilmChannelType type, const u_int index) { switch (type) { case RADIANCE_PER_PIXEL_NORMALIZED: return channel_RADIANCE_PER_PIXEL_NORMALIZEDs[index]->GetPixels(); case RADIANCE_PER_SCREEN_NORMALIZED: return channel_RADIANCE_PER_SCREEN_NORMALIZEDs[index]->GetPixels(); case ALPHA: return channel_ALPHA->GetPixels(); case RGB_TONEMAPPED: { ExecuteImagePipeline(); return channel_RGB_TONEMAPPED->GetPixels(); } case DEPTH: return channel_DEPTH->GetPixels(); case POSITION: return channel_POSITION->GetPixels(); case GEOMETRY_NORMAL: return channel_GEOMETRY_NORMAL->GetPixels(); case SHADING_NORMAL: return channel_SHADING_NORMAL->GetPixels(); case DIRECT_DIFFUSE: return channel_DIRECT_DIFFUSE->GetPixels(); case DIRECT_GLOSSY: return channel_DIRECT_GLOSSY->GetPixels(); case EMISSION: return channel_EMISSION->GetPixels(); case INDIRECT_DIFFUSE: return channel_INDIRECT_DIFFUSE->GetPixels(); case INDIRECT_GLOSSY: return channel_INDIRECT_GLOSSY->GetPixels(); case INDIRECT_SPECULAR: return channel_INDIRECT_SPECULAR->GetPixels(); case MATERIAL_ID_MASK: return channel_MATERIAL_ID_MASKs[index]->GetPixels(); case DIRECT_SHADOW_MASK: return channel_DIRECT_SHADOW_MASK->GetPixels(); case INDIRECT_SHADOW_MASK: return channel_INDIRECT_SHADOW_MASK->GetPixels(); case UV: return channel_UV->GetPixels(); case RAYCOUNT: return channel_RAYCOUNT->GetPixels(); case BY_MATERIAL_ID: return channel_BY_MATERIAL_IDs[index]->GetPixels(); case IRRADIANCE: return channel_IRRADIANCE->GetPixels(); default: throw runtime_error("Unknown FilmOutputType in Film::GetChannel<float>(): " + ToString(type)); } } template<> const u_int *Film::GetChannel<u_int>(const FilmChannelType type, const u_int index) { switch (type) { case MATERIAL_ID: return channel_MATERIAL_ID->GetPixels(); default: throw runtime_error("Unknown FilmOutputType in Film::GetChannel<u_int>(): " + ToString(type)); } } template<> void Film::GetOutput<float>(const FilmOutputs::FilmOutputType type, float *buffer, const u_int index) { switch (type) { case FilmOutputs::RGB: { for (u_int i = 0; i < pixelCount; ++i) GetPixelFromMergedSampleBuffers(i, &buffer[i * 3]); break; } case FilmOutputs::RGB_TONEMAPPED: ExecuteImagePipeline(); copy(channel_RGB_TONEMAPPED->GetPixels(), channel_RGB_TONEMAPPED->GetPixels() + pixelCount * 3, buffer); break; case FilmOutputs::RGBA: { for (u_int i = 0; i < pixelCount; ++i) { const u_int offset = i * 4; GetPixelFromMergedSampleBuffers(i, &buffer[offset]); channel_ALPHA->GetWeightedPixel(i, &buffer[offset + 3]); } break; } case FilmOutputs::RGBA_TONEMAPPED: { ExecuteImagePipeline(); float *srcRGB = channel_RGB_TONEMAPPED->GetPixels(); float *dst = buffer; for (u_int i = 0; i < pixelCount; ++i) { *dst++ = *srcRGB++; *dst++ = *srcRGB++; *dst++ = *srcRGB++; channel_ALPHA->GetWeightedPixel(i, dst++); } break; } case FilmOutputs::ALPHA: { for (u_int i = 0; i < pixelCount; ++i) channel_ALPHA->GetWeightedPixel(i, &buffer[i]); break; } case FilmOutputs::DEPTH: copy(channel_DEPTH->GetPixels(), channel_DEPTH->GetPixels() + pixelCount, buffer); break; case FilmOutputs::POSITION: copy(channel_POSITION->GetPixels(), channel_POSITION->GetPixels() + pixelCount * 3, buffer); break; case FilmOutputs::GEOMETRY_NORMAL: copy(channel_GEOMETRY_NORMAL->GetPixels(), channel_GEOMETRY_NORMAL->GetPixels() + pixelCount * 3, buffer); break; case FilmOutputs::SHADING_NORMAL: copy(channel_SHADING_NORMAL->GetPixels(), channel_SHADING_NORMAL->GetPixels() + pixelCount * 3, buffer); break; case FilmOutputs::DIRECT_DIFFUSE: { for (u_int i = 0; i < pixelCount; ++i) channel_DIRECT_DIFFUSE->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::DIRECT_GLOSSY: { for (u_int i = 0; i < pixelCount; ++i) channel_DIRECT_GLOSSY->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::EMISSION: { for (u_int i = 0; i < pixelCount; ++i) channel_EMISSION->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::INDIRECT_DIFFUSE: { for (u_int i = 0; i < pixelCount; ++i) channel_INDIRECT_DIFFUSE->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::INDIRECT_GLOSSY: { for (u_int i = 0; i < pixelCount; ++i) channel_INDIRECT_GLOSSY->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::INDIRECT_SPECULAR: { for (u_int i = 0; i < pixelCount; ++i) channel_INDIRECT_SPECULAR->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::MATERIAL_ID_MASK: { for (u_int i = 0; i < pixelCount; ++i) channel_MATERIAL_ID_MASKs[index]->GetWeightedPixel(i, &buffer[i]); break; } case FilmOutputs::DIRECT_SHADOW_MASK: { for (u_int i = 0; i < pixelCount; ++i) channel_DIRECT_SHADOW_MASK->GetWeightedPixel(i, &buffer[i]); break; } case FilmOutputs::INDIRECT_SHADOW_MASK: { for (u_int i = 0; i < pixelCount; ++i) channel_INDIRECT_SHADOW_MASK->GetWeightedPixel(i, &buffer[i]); break; } case FilmOutputs::RADIANCE_GROUP: { fill(buffer, buffer + 3 * pixelCount, 0.f); if (index < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()) { float *dst = buffer; for (u_int i = 0; i < pixelCount; ++i) { Spectrum c; channel_RADIANCE_PER_PIXEL_NORMALIZEDs[index]->AccumulateWeightedPixel(i, c.c); *dst++ += c.c[0]; *dst++ += c.c[1]; *dst++ += c.c[2]; } } if (index < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()) { float *dst = buffer; for (u_int i = 0; i < pixelCount; ++i) { Spectrum c; channel_RADIANCE_PER_SCREEN_NORMALIZEDs[index]->AccumulateWeightedPixel(i, c.c); *dst++ += c.c[0]; *dst++ += c.c[1]; *dst++ += c.c[2]; } } break; } case FilmOutputs::UV: copy(channel_UV->GetPixels(), channel_UV->GetPixels() + pixelCount * 2, buffer); break; case FilmOutputs::RAYCOUNT: copy(channel_RAYCOUNT->GetPixels(), channel_RAYCOUNT->GetPixels() + pixelCount, buffer); break; case FilmOutputs::BY_MATERIAL_ID: { for (u_int i = 0; i < pixelCount; ++i) channel_BY_MATERIAL_IDs[index]->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::IRRADIANCE: { for (u_int i = 0; i < pixelCount; ++i) channel_IRRADIANCE->GetWeightedPixel(i, &buffer[i]); break; } default: throw runtime_error("Unknown film output type in Film::GetOutput<float>(): " + ToString(type)); } } template<> void Film::GetOutput<u_int>(const FilmOutputs::FilmOutputType type, u_int *buffer, const u_int index) { switch (type) { case FilmOutputs::MATERIAL_ID: copy(channel_MATERIAL_ID->GetPixels(), channel_MATERIAL_ID->GetPixels() + pixelCount, buffer); break; default: throw runtime_error("Unknown film output type in Film::GetOutput<u_int>(): " + ToString(type)); } } void Film::GetPixelFromMergedSampleBuffers(const u_int index, float *c) const { c[0] = 0.f; c[1] = 0.f; c[2] = 0.f; for (u_int i = 0; i < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size(); ++i) channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->AccumulateWeightedPixel(index, c); if (channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size() > 0) { const float factor = statsTotalSampleCount / pixelCount; for (u_int i = 0; i < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size(); ++i) { const float *src = channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->GetPixel(index); c[0] += src[0] * factor; c[1] += src[1] * factor; c[2] += src[2] * factor; } } } void Film::ExecuteImagePipeline() { if (!rgbTonemapUpdate || (!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) || !HasChannel(RGB_TONEMAPPED)) { // Nothing to do return; } // Merge all buffers Spectrum *p = (Spectrum *)channel_RGB_TONEMAPPED->GetPixels(); const u_int pixelCount = width * height; vector<bool> frameBufferMask(pixelCount, false); MergeSampleBuffers(p, frameBufferMask); // Apply the image pipeline if I have one if (imagePipeline) imagePipeline->Apply(*this, p, frameBufferMask); } void Film::MergeSampleBuffers(Spectrum *p, vector<bool> &frameBufferMask) const { const u_int pixelCount = width * height; // Merge RADIANCE_PER_PIXEL_NORMALIZED and RADIANCE_PER_SCREEN_NORMALIZED buffers if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { for (u_int i = 0; i < radianceGroupCount; ++i) { for (u_int j = 0; j < pixelCount; ++j) { const float *sp = channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->GetPixel(j); if (sp[3] > 0.f) { if (frameBufferMask[j]) p[j] += Spectrum(sp) / sp[3]; else p[j] = Spectrum(sp) / sp[3]; frameBufferMask[j] = true; } } } } if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) { const float factor = pixelCount / statsTotalSampleCount; for (u_int i = 0; i < radianceGroupCount; ++i) { for (u_int j = 0; j < pixelCount; ++j) { const Spectrum s(channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->GetPixel(j)); if (!s.Black()) { if (frameBufferMask[j]) p[j] += s * factor; else p[j] = s * factor; frameBufferMask[j] = true; } } } } if (!enabledOverlappedScreenBufferUpdate) { for (u_int i = 0; i < pixelCount; ++i) { if (!frameBufferMask[i]) p[i] = Spectrum(); } } } void Film::AddSampleResultColor(const u_int x, const u_int y, const SampleResult &sampleResult, const float weight) { if ((channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size() > 0) && sampleResult.HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { for (u_int i = 0; i < Min(sampleResult.radiancePerPixelNormalized.size(), channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()); ++i) { if (sampleResult.radiancePerPixelNormalized[i].IsNaN() || sampleResult.radiancePerPixelNormalized[i].IsInf()) continue; channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->AddWeightedPixel(x, y, sampleResult.radiancePerPixelNormalized[i].c, weight); } } // Faster than HasChannel(channel_RADIANCE_PER_SCREEN_NORMALIZED) if ((channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size() > 0) && sampleResult.HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) { for (u_int i = 0; i < Min(sampleResult.radiancePerScreenNormalized.size(), channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()); ++i) { if (sampleResult.radiancePerScreenNormalized[i].IsNaN() || sampleResult.radiancePerScreenNormalized[i].IsInf()) continue; channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->AddWeightedPixel(x, y, sampleResult.radiancePerScreenNormalized[i].c, weight); } } // Faster than HasChannel(ALPHA) if (channel_ALPHA && sampleResult.HasChannel(ALPHA)) channel_ALPHA->AddWeightedPixel(x, y, &sampleResult.alpha, weight); if (hasComposingChannel) { // Faster than HasChannel(DIRECT_DIFFUSE) if (channel_DIRECT_DIFFUSE && sampleResult.HasChannel(DIRECT_DIFFUSE)) channel_DIRECT_DIFFUSE->AddWeightedPixel(x, y, sampleResult.directDiffuse.c, weight); // Faster than HasChannel(DIRECT_GLOSSY) if (channel_DIRECT_GLOSSY && sampleResult.HasChannel(DIRECT_GLOSSY)) channel_DIRECT_GLOSSY->AddWeightedPixel(x, y, sampleResult.directGlossy.c, weight); // Faster than HasChannel(EMISSION) if (channel_EMISSION && sampleResult.HasChannel(EMISSION)) channel_EMISSION->AddWeightedPixel(x, y, sampleResult.emission.c, weight); // Faster than HasChannel(INDIRECT_DIFFUSE) if (channel_INDIRECT_DIFFUSE && sampleResult.HasChannel(INDIRECT_DIFFUSE)) channel_INDIRECT_DIFFUSE->AddWeightedPixel(x, y, sampleResult.indirectDiffuse.c, weight); // Faster than HasChannel(INDIRECT_GLOSSY) if (channel_INDIRECT_GLOSSY && sampleResult.HasChannel(INDIRECT_GLOSSY)) channel_INDIRECT_GLOSSY->AddWeightedPixel(x, y, sampleResult.indirectGlossy.c, weight); // Faster than HasChannel(INDIRECT_SPECULAR) if (channel_INDIRECT_SPECULAR && sampleResult.HasChannel(INDIRECT_SPECULAR)) channel_INDIRECT_SPECULAR->AddWeightedPixel(x, y, sampleResult.indirectSpecular.c, weight); // This is MATERIAL_ID_MASK and BY_MATERIAL_ID if (sampleResult.HasChannel(MATERIAL_ID)) { // MATERIAL_ID_MASK for (u_int i = 0; i < maskMaterialIDs.size(); ++i) { float pixel[2]; pixel[0] = (sampleResult.materialID == maskMaterialIDs[i]) ? weight : 0.f; pixel[1] = weight; channel_MATERIAL_ID_MASKs[i]->AddPixel(x, y, pixel); } // BY_MATERIAL_ID if ((channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size() > 0) && sampleResult.HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { for (u_int index = 0; index < byMaterialIDs.size(); ++index) { Spectrum c; if (sampleResult.materialID == byMaterialIDs[index]) { // Merge all radiance groups for (u_int i = 0; i < Min(sampleResult.radiancePerPixelNormalized.size(), channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()); ++i) { if (sampleResult.radiancePerPixelNormalized[i].IsNaN() || sampleResult.radiancePerPixelNormalized[i].IsInf()) continue; c += sampleResult.radiancePerPixelNormalized[i]; } } channel_BY_MATERIAL_IDs[index]->AddWeightedPixel(x, y, c.c, weight); } } } // Faster than HasChannel(DIRECT_SHADOW) if (channel_DIRECT_SHADOW_MASK && sampleResult.HasChannel(DIRECT_SHADOW_MASK)) channel_DIRECT_SHADOW_MASK->AddWeightedPixel(x, y, &sampleResult.directShadowMask, weight); // Faster than HasChannel(INDIRECT_SHADOW_MASK) if (channel_INDIRECT_SHADOW_MASK && sampleResult.HasChannel(INDIRECT_SHADOW_MASK)) channel_INDIRECT_SHADOW_MASK->AddWeightedPixel(x, y, &sampleResult.indirectShadowMask, weight); // Faster than HasChannel(IRRADIANCE) if (channel_IRRADIANCE && sampleResult.HasChannel(IRRADIANCE)) channel_IRRADIANCE->AddWeightedPixel(x, y, sampleResult.irradiance.c, weight); } } void Film::AddSampleResultData(const u_int x, const u_int y, const SampleResult &sampleResult) { bool depthWrite = true; // Faster than HasChannel(DEPTH) if (channel_DEPTH && sampleResult.HasChannel(DEPTH)) depthWrite = channel_DEPTH->MinPixel(x, y, &sampleResult.depth); if (depthWrite) { // Faster than HasChannel(POSITION) if (channel_POSITION && sampleResult.HasChannel(POSITION)) channel_POSITION->SetPixel(x, y, &sampleResult.position.x); // Faster than HasChannel(GEOMETRY_NORMAL) if (channel_GEOMETRY_NORMAL && sampleResult.HasChannel(GEOMETRY_NORMAL)) channel_GEOMETRY_NORMAL->SetPixel(x, y, &sampleResult.geometryNormal.x); // Faster than HasChannel(SHADING_NORMAL) if (channel_SHADING_NORMAL && sampleResult.HasChannel(SHADING_NORMAL)) channel_SHADING_NORMAL->SetPixel(x, y, &sampleResult.shadingNormal.x); // Faster than HasChannel(MATERIAL_ID) if (channel_MATERIAL_ID && sampleResult.HasChannel(MATERIAL_ID)) channel_MATERIAL_ID->SetPixel(x, y, &sampleResult.materialID); // Faster than HasChannel(UV) if (channel_UV && sampleResult.HasChannel(UV)) channel_UV->SetPixel(x, y, &sampleResult.uv.u); } if (channel_RAYCOUNT && sampleResult.HasChannel(RAYCOUNT)) channel_RAYCOUNT->AddPixel(x, y, &sampleResult.rayCount); } void Film::AddSample(const u_int x, const u_int y, const SampleResult &sampleResult, const float weight) { AddSampleResultColor(x, y, sampleResult, weight); if (hasDataChannel) AddSampleResultData(x, y, sampleResult); } void Film::SplatSample(const SampleResult &sampleResult, const float weight) { if (!filter) { const int x = Ceil2Int(sampleResult.filmX - .5f); const int y = Ceil2Int(sampleResult.filmY - .5f); if ((x >= 0) && (x < (int)width) && (y >= 0) && (y < (int)height)) { AddSampleResultColor(x, y, sampleResult, weight); if (hasDataChannel) AddSampleResultData(x, y, sampleResult); } } else { //---------------------------------------------------------------------- // Add all data related information (not filtered) //---------------------------------------------------------------------- if (hasDataChannel) { const int x = Ceil2Int(sampleResult.filmX - .5f); const int y = Ceil2Int(sampleResult.filmY - .5f); if ((x >= 0.f) && (x < (int)width) && (y >= 0.f) && (y < (int)height)) AddSampleResultData(x, y, sampleResult); } //---------------------------------------------------------------------- // Add all color related information (filtered) //---------------------------------------------------------------------- // Compute sample's raster extent const float dImageX = sampleResult.filmX - .5f; const float dImageY = sampleResult.filmY - .5f; const FilterLUT *filterLUT = filterLUTs->GetLUT(dImageX - floorf(sampleResult.filmX), dImageY - floorf(sampleResult.filmY)); const float *lut = filterLUT->GetLUT(); const int x0 = Ceil2Int(dImageX - filter->xWidth); const int x1 = x0 + filterLUT->GetWidth(); const int y0 = Ceil2Int(dImageY - filter->yWidth); const int y1 = y0 + filterLUT->GetHeight(); for (int iy = y0; iy < y1; ++iy) { if (iy < 0) { lut += filterLUT->GetWidth(); continue; } else if(iy >= (int)height) break; for (int ix = x0; ix < x1; ++ix) { const float filterWeight = *lut++; if ((ix < 0) || (ix >= (int)width)) continue; const float filteredWeight = weight * filterWeight; AddSampleResultColor(ix, iy, sampleResult, filteredWeight); } } } } void Film::ResetConvergenceTest() { if (convTest) convTest->Reset(); } u_int Film::RunConvergenceTest() { // Required in order to have a valid convergence test ExecuteImagePipeline(); return convTest->Test((const float *)channel_RGB_TONEMAPPED->GetPixels()); } Film::FilmChannelType Film::String2FilmChannelType(const std::string &type) { if (type == "RADIANCE_PER_PIXEL_NORMALIZED") return RADIANCE_PER_PIXEL_NORMALIZED; else if (type == "RADIANCE_PER_SCREEN_NORMALIZED") return RADIANCE_PER_SCREEN_NORMALIZED; else if (type == "ALPHA") return ALPHA; else if (type == "DEPTH") return DEPTH; else if (type == "POSITION") return POSITION; else if (type == "GEOMETRY_NORMAL") return GEOMETRY_NORMAL; else if (type == "SHADING_NORMAL") return SHADING_NORMAL; else if (type == "MATERIAL_ID") return MATERIAL_ID; else if (type == "DIRECT_DIFFUSE") return DIRECT_DIFFUSE; else if (type == "DIRECT_GLOSSY") return DIRECT_GLOSSY; else if (type == "EMISSION") return EMISSION; else if (type == "INDIRECT_DIFFUSE") return INDIRECT_DIFFUSE; else if (type == "INDIRECT_GLOSSY") return INDIRECT_GLOSSY; else if (type == "INDIRECT_SPECULAR") return INDIRECT_SPECULAR; else if (type == "INDIRECT_SPECULAR") return INDIRECT_SPECULAR; else if (type == "MATERIAL_ID_MASK") return MATERIAL_ID_MASK; else if (type == "DIRECT_SHADOW_MASK") return DIRECT_SHADOW_MASK; else if (type == "INDIRECT_SHADOW_MASK") return INDIRECT_SHADOW_MASK; else if (type == "UV") return UV; else if (type == "RAYCOUNT") return RAYCOUNT; else if (type == "BY_MATERIAL_ID") return BY_MATERIAL_ID; else if (type == "IRRADIANCE") return IRRADIANCE; else throw runtime_error("Unknown film output type in Film::String2FilmChannelType(): " + type); } const std::string Film::FilmChannelType2String(const Film::FilmChannelType type) { switch (type) { case Film::RADIANCE_PER_PIXEL_NORMALIZED: return "RADIANCE_PER_PIXEL_NORMALIZED"; case Film::RADIANCE_PER_SCREEN_NORMALIZED: return "RADIANCE_PER_SCREEN_NORMALIZED"; case Film::ALPHA: return "ALPHA"; case Film::DEPTH: return "DEPTH"; case Film::POSITION: return "POSITION"; case Film::GEOMETRY_NORMAL: return "GEOMETRY_NORMAL"; case Film::SHADING_NORMAL: return "SHADING_NORMAL"; case Film::MATERIAL_ID: return "MATERIAL_ID"; case Film::DIRECT_DIFFUSE: return "DIRECT_DIFFUSE"; case Film::DIRECT_GLOSSY: return "DIRECT_GLOSSY"; case Film::EMISSION: return "EMISSION"; case Film::INDIRECT_DIFFUSE: return "INDIRECT_DIFFUSE"; case Film::INDIRECT_GLOSSY: return "INDIRECT_GLOSSY"; case Film::INDIRECT_SPECULAR: return "INDIRECT_SPECULAR"; case Film::MATERIAL_ID_MASK: return "MATERIAL_ID_MASK"; case Film::DIRECT_SHADOW_MASK: return "DIRECT_SHADOW_MASK"; case Film::INDIRECT_SHADOW_MASK: return "INDIRECT_SHADOW_MASK"; case Film::UV: return "UV"; case Film::RAYCOUNT: return "RAYCOUNT"; case Film::BY_MATERIAL_ID: return "BY_MATERIAL_ID"; case Film::IRRADIANCE: return "IRRADIANCE"; default: throw runtime_error("Unknown film output type in Film::FilmChannelType2String(): " + ToString(type)); } } template<> void Film::load<boost::archive::binary_iarchive>(boost::archive::binary_iarchive &ar, const u_int version) { ar >> channel_RADIANCE_PER_PIXEL_NORMALIZEDs; ar >> channel_RADIANCE_PER_SCREEN_NORMALIZEDs; ar >> channel_ALPHA; ar >> channel_RGB_TONEMAPPED; ar >> channel_DEPTH; ar >> channel_POSITION; ar >> channel_GEOMETRY_NORMAL; ar >> channel_SHADING_NORMAL; ar >> channel_MATERIAL_ID; ar >> channel_DIRECT_DIFFUSE; ar >> channel_DIRECT_GLOSSY; ar >> channel_EMISSION; ar >> channel_INDIRECT_DIFFUSE; ar >> channel_INDIRECT_GLOSSY; ar >> channel_INDIRECT_SPECULAR; ar >> channel_MATERIAL_ID_MASKs; ar >> channel_DIRECT_SHADOW_MASK; ar >> channel_INDIRECT_SHADOW_MASK; ar >> channel_UV; ar >> channel_RAYCOUNT; ar >> channel_BY_MATERIAL_IDs; ar >> channel_IRRADIANCE; ar >> channels; ar >> width; ar >> height; ar >> pixelCount; ar >> radianceGroupCount; ar >> maskMaterialIDs; ar >> byMaterialIDs; ar >> statsTotalSampleCount; ar >> statsStartSampleTime; ar >> statsAvgSampleSec; ar >> imagePipeline; ar >> convTest; ar >> filter; // filterLUTs is re-built at load time if (filter) { const u_int size = Max<u_int>(4, Max(filter->xWidth, filter->yWidth) + 1); filterLUTs = new FilterLUTs(*filter, size); } else filterLUTs = NULL; ar >> initialized; ar >> enabledOverlappedScreenBufferUpdate; ar >> rgbTonemapUpdate; } template<> void Film::save<boost::archive::binary_oarchive>(boost::archive::binary_oarchive &ar, const u_int version) const { ar << channel_RADIANCE_PER_PIXEL_NORMALIZEDs; ar << channel_RADIANCE_PER_SCREEN_NORMALIZEDs; ar << channel_ALPHA; ar << channel_RGB_TONEMAPPED; ar << channel_DEPTH; ar << channel_POSITION; ar << channel_GEOMETRY_NORMAL; ar << channel_SHADING_NORMAL; ar << channel_MATERIAL_ID; ar << channel_DIRECT_DIFFUSE; ar << channel_DIRECT_GLOSSY; ar << channel_EMISSION; ar << channel_INDIRECT_DIFFUSE; ar << channel_INDIRECT_GLOSSY; ar << channel_INDIRECT_SPECULAR; ar << channel_MATERIAL_ID_MASKs; ar << channel_DIRECT_SHADOW_MASK; ar << channel_INDIRECT_SHADOW_MASK; ar << channel_UV; ar << channel_RAYCOUNT; ar << channel_BY_MATERIAL_IDs; ar << channel_IRRADIANCE; ar << channels; ar << width; ar << height; ar << pixelCount; ar << radianceGroupCount; ar << maskMaterialIDs; ar << byMaterialIDs; ar << statsTotalSampleCount; ar << statsStartSampleTime; ar << statsAvgSampleSec; ar << imagePipeline; ar << convTest; ar << filter; // filterLUTs is re-built at load time ar << initialized; ar << enabledOverlappedScreenBufferUpdate; ar << rgbTonemapUpdate; } //------------------------------------------------------------------------------ // SampleResult //------------------------------------------------------------------------------ void SampleResult::AddEmission(const u_int lightID, const Spectrum &pathThroughput, const Spectrum &incomingRadiance) { const Spectrum radiance = pathThroughput * incomingRadiance; radiancePerPixelNormalized[lightID] += radiance; if (firstPathVertex) emission += radiance; else { indirectShadowMask = 0.f; if (firstPathVertexEvent & DIFFUSE) indirectDiffuse += radiance; else if (firstPathVertexEvent & GLOSSY) indirectGlossy += radiance; else if (firstPathVertexEvent & SPECULAR) indirectSpecular += radiance; } } void SampleResult::AddDirectLight(const u_int lightID, const BSDFEvent bsdfEvent, const Spectrum &pathThroughput, const Spectrum &incomingRadiance, const float lightScale) { const Spectrum radiance = pathThroughput * incomingRadiance; radiancePerPixelNormalized[lightID] += radiance; if (firstPathVertex) { // directShadowMask is supposed to be initialized to 1.0 directShadowMask = Max(0.f, directShadowMask - lightScale); if (bsdfEvent & DIFFUSE) directDiffuse += radiance; else directGlossy += radiance; } else { // indirectShadowMask is supposed to be initialized to 1.0 indirectShadowMask = Max(0.f, indirectShadowMask - lightScale); if (firstPathVertexEvent & DIFFUSE) indirectDiffuse += radiance; else if (firstPathVertexEvent & GLOSSY) indirectGlossy += radiance; else if (firstPathVertexEvent & SPECULAR) indirectSpecular += radiance; irradiance += irradiancePathThroughput * incomingRadiance; } } void SampleResult::AddSampleResult(std::vector<SampleResult> &sampleResults, const float filmX, const float filmY, const Spectrum &radiancePPN, const float alpha) { assert(!radiancePPN.IsInf() || !radiancePPN.IsNaN()); assert(!isinf(alpha) || !isnan(alpha)); const u_int size = sampleResults.size(); sampleResults.resize(size + 1); sampleResults[size].Init(Film::RADIANCE_PER_PIXEL_NORMALIZED | Film::ALPHA, 1); sampleResults[size].filmX = filmX; sampleResults[size].filmY = filmY; sampleResults[size].radiancePerPixelNormalized[0] = radiancePPN; sampleResults[size].alpha = alpha; } void SampleResult::AddSampleResult(std::vector<SampleResult> &sampleResults, const float filmX, const float filmY, const Spectrum &radiancePSN) { assert(!radiancePSN.IsInf() || !radiancePSN.IsNaN()); const u_int size = sampleResults.size(); sampleResults.resize(size + 1); sampleResults[size].Init(Film::RADIANCE_PER_SCREEN_NORMALIZED, 1); sampleResults[size].filmX = filmX; sampleResults[size].filmY = filmY; sampleResults[size].radiancePerScreenNormalized[0] = radiancePSN; }
33.339009
136
0.693148
DavidBluecame
eab95df009eeed45149bf914d5a1f84f0370f35c
934
cpp
C++
src/071.simplify_path/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2016-07-02T17:44:10.000Z
2016-07-02T17:44:10.000Z
src/071.simplify_path/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
null
null
null
src/071.simplify_path/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2019-12-21T04:57:15.000Z
2019-12-21T04:57:15.000Z
class Solution { public: string simplifyPath(string path) { stack<string> s; string ans; int len = path.length(); if (len == 0) return ans; int start, end; for (int i = 0; i < len; i++) { if (i > 0 && path[i] != '/' && path[i - 1] == '/') { start = i - 1; } if (path[i] != '/' && ((i + 1 < len && path[i + 1] == '/') || (i == len - 1))) { end = i; string tmp = path.substr(start, end - start + 1); if (tmp == "/.") continue; else if (tmp == "/..") { if (!s.empty()) s.pop(); } else { s.push(tmp); } } } while(!s.empty()) { ans = s.top() + ans; s.pop(); } if (ans == "") ans = "/"; return ans; } };
28.30303
92
0.313704
cloudzfy
eab9870e3fd5d0d35a46824b7c7a469cf4a9f334
362
cpp
C++
array/Kth Row of Pascal's Triangle.cpp
1aman1/practice-InterviewBit
cafb841bd57f74f8fc3690a7f7830e6ca9fda916
[ "MIT" ]
1
2019-08-14T05:46:57.000Z
2019-08-14T05:46:57.000Z
array/Kth Row of Pascal's Triangle.cpp
1aman1/practice
cafb841bd57f74f8fc3690a7f7830e6ca9fda916
[ "MIT" ]
null
null
null
array/Kth Row of Pascal's Triangle.cpp
1aman1/practice
cafb841bd57f74f8fc3690a7f7830e6ca9fda916
[ "MIT" ]
null
null
null
/* A0-> 1 A1-> 1 1 A2-> 1 2 1 A3-> 1 3 3 1 for A, pascal triangle will have A+1 elements */ vector<int> Solution::getRow(int A) { vector<int> result; int value = 1, index; for( index = 0; index <= A ; index++){ result.push_back(value); value = value * (A - index)/(index + 1); } return result; }
21.294118
52
0.508287
1aman1
eab9ea26b789a8deb87fcc31f169ada82a197dc8
44,492
cpp
C++
core/sql/parser/StmtDDLNode.cpp
sandhyasun/trafodion
db1a8a73b7b3b4767d5dec60ae091df891cfceee
[ "Apache-2.0" ]
null
null
null
core/sql/parser/StmtDDLNode.cpp
sandhyasun/trafodion
db1a8a73b7b3b4767d5dec60ae091df891cfceee
[ "Apache-2.0" ]
null
null
null
core/sql/parser/StmtDDLNode.cpp
sandhyasun/trafodion
db1a8a73b7b3b4767d5dec60ae091df891cfceee
[ "Apache-2.0" ]
null
null
null
/* -*-C++-*- // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ ***************************************************************************** * * File: StmtDDLNode.C * Description: member functions for classes StmtDDLNode, StmtDDLGrant, * StmtDDLGrantArray, StmtDDLInitializeSQL, StmtDDLRevoke, * StmtDDLSchRevoke, StmtDDLPublish * * Created: 3/9/95 * Language: C++ * * * * ***************************************************************************** */ #include "BaseTypes.h" #include "ComOperators.h" #include "ElemDDLPrivileges.h" #include "ElemDDLGrantee.h" #include "StmtDDLNode.h" #include "StmtDDLGrant.h" #include "StmtDDLGrantComponentPrivilege.h" #include "StmtDDLGrantArray.h" #include "StmtDDLSchGrant.h" #include "StmtDDLSchGrantArray.h" #include "StmtDDLPublish.h" #include "StmtDDLInitializeSQL.h" #include "StmtDDLRevoke.h" #include "StmtDDLSchRevoke.h" #include "StmtDDLReInitializeSQL.h" void StmtDDLInitializeSQL_visitRegisterUserElement(ElemDDLNode * pInitSQLNode, CollIndex /* index */, ElemDDLNode * pElement); // ----------------------------------------------------------------------- // member functions for class StmtDDLNode // ----------------------------------------------------------------------- StmtDDLNode::StmtDDLNode(OperatorTypeEnum otype) : ElemDDLNode(otype), tableType_(COM_REGULAR_TABLE), objectClass_(COM_CLASS_USER_TABLE), isVolatile_(FALSE), exeUtil_(FALSE), isGhostObject_(FALSE), inMemoryObjectDefn_(FALSE), isExternal_(FALSE), ddlXns_(FALSE) { ddlXns_ = (CmpCommon::getDefault(DDL_TRANSACTIONS) == DF_ON); } // virtual destructor // To improve performance, do not use inline with virtual destructor StmtDDLNode::~StmtDDLNode() { } // // cast virtual functions // StmtDDLNode * StmtDDLNode::castToStmtDDLNode() { return this; } const StmtDDLNode * StmtDDLNode::castToStmtDDLNode() const { return this; } // // methods for tracing // const NAString StmtDDLNode::getText() const { NAAbort("StmtDDLNode.C", __LINE__, "internal logic error"); return "StmtDDLNode"; } void StmtDDLNode::unparse(NAString &result, PhaseEnum /*phase*/, UnparseFormatEnum /*form*/, TableDesc * tabId) const { result += "a DDL statement"; } NABoolean StmtDDLNode::performParallelOp(Lng32 numPartitions) { // PerformParallelOp NABoolean ppo = FALSE; // The CQD USE_PARALLEL_FOR_NUM_PARTITIONS specifies the number of // partitions that must exist before // performing the create in parallel. Lng32 numParts = CmpCommon::getDefaultLong(USE_PARALLEL_FOR_NUM_PARTITIONS); NAString pos; CmpCommon::getDefault(POS, pos, 0); // Parallel Create logic should be executed only if POS and // ATTEMPT_ESP_PARALLELISM are not turned OFF and table involved has // multiple partitions. if ((CmpCommon::getDefault(POS) != DF_OFF) && (!IsNAStringSpaceOrEmpty(pos)) && (CmpCommon::getDefault(ATTEMPT_ESP_PARALLELISM) != DF_OFF) && (numPartitions >= numParts) && (numPartitions > 1)) { // Check to see if parallel creation of labels is required // Parallel creations should not happen if POS_NUM_OF_PARTNS is set // to 1 ( single partition table). if (CmpCommon::getDefault(POS_NUM_OF_PARTNS,0) == DF_SYSTEM ) ppo = TRUE; else { // Not DF_SYSTEM - get numeric POS_NUM_OF_PARTNS Lng32 posnumpartns = CmpCommon::getDefaultLong(POS_NUM_OF_PARTNS); if (posnumpartns > 1) ppo = TRUE; } } return ppo; } // ----------------------------------------------------------------------- // member functions for class StmtDDLGrant // ----------------------------------------------------------------------- // // constructor // StmtDDLGrant::StmtDDLGrant(ElemDDLNode * pPrivileges, const QualifiedName & objectName, ElemDDLNode * pGranteeList, ElemDDLNode * pWithGrantOption, ElemDDLNode * pByGrantorOption, QualifiedName * actionName, CollHeap * heap) : StmtDDLNode(DDL_GRANT), objectName_(heap), objectQualName_(objectName, heap), isAllPrivileges_(FALSE), isWithGrantOptionSpec_(FALSE), privActArray_(heap), actionQualName_(actionName), granteeArray_(heap), isByGrantorOptionSpec_(FALSE), byGrantor_(NULL) { setChild(INDEX_PRIVILEGES, pPrivileges); setChild(INDEX_GRANTEE_LIST, pGranteeList); setChild(INDEX_WITH_GRANT_OPTION, pWithGrantOption); setChild(INDEX_BY_GRANTOR_OPTION, pByGrantorOption); objectName_ = objectQualName_.getQualifiedNameAsAnsiString(); // // inserts pointers to parse nodes representing privilege // actions to privActArray_ so the user can access the // information about privilege actions easier. // ComASSERT(pPrivileges NEQ NULL); ElemDDLPrivileges * pPrivsNode = pPrivileges->castToElemDDLPrivileges(); ComASSERT(pPrivsNode NEQ NULL); if (pPrivsNode->isAllPrivileges()) { isAllPrivileges_ = TRUE; } else { ElemDDLNode * pPrivActs = pPrivsNode->getPrivilegeActionList(); for (CollIndex i = 0; i < pPrivActs->entries(); i++) { ElemDDLPrivAct *pPrivAct = (*pPrivActs)[i]->castToElemDDLPrivAct(); privActArray_.insert(pPrivAct); if (pPrivAct->isDDLPriv()) privActArray_.setHasDDLPriv(TRUE); } } // // copies pointers to parse nodes representing grantee // to granteeArray_ so the user can access the information // easier. // ComASSERT(pGranteeList NEQ NULL); for (CollIndex i = 0; i < pGranteeList->entries(); i++) { granteeArray_.insert((*pGranteeList)[i]->castToElemDDLGrantee()); } // // looks for With Grant option phrase // if (pWithGrantOption NEQ NULL) { isWithGrantOptionSpec_ = TRUE; } if ( pByGrantorOption NEQ NULL ) { isByGrantorOptionSpec_ = TRUE; byGrantor_ = pByGrantorOption->castToElemDDLGrantee(); } } // StmtDDLGrant::StmtDDLGrant() // virtual destructor StmtDDLGrant::~StmtDDLGrant() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // cast StmtDDLGrant * StmtDDLGrant::castToStmtDDLGrant() { return this; } // // accessors // Int32 StmtDDLGrant::getArity() const { return MAX_STMT_DDL_GRANT_ARITY; } ExprNode * StmtDDLGrant::getChild(Lng32 index) { ComASSERT(index >= 0 AND index < getArity()); return children_[index]; } // // mutators // void StmtDDLGrant::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT(index >= 0 AND index < getArity()); if (pChildNode NEQ NULL) { ComASSERT(pChildNode->castToElemDDLNode() NEQ NULL); children_[index] = pChildNode->castToElemDDLNode(); } else { children_[index] = NULL; } } // // methods for tracing // const NAString StmtDDLGrant::displayLabel1() const { return NAString("Object name: ") + getObjectName(); } NATraceList StmtDDLGrant::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // object name // detailTextList.append(displayLabel1()); // object name // // privileges // StmtDDLGrant * localThis = (StmtDDLGrant *)this; detailTextList.append(localThis->getChild(INDEX_PRIVILEGES) ->castToElemDDLNode() ->castToElemDDLPrivileges() ->getDetailInfo()); // // grantee list // const ElemDDLGranteeArray & granteeArray = getGranteeArray(); detailText = "Grantee list ["; detailText += LongToNAString((Lng32)granteeArray.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < granteeArray.entries(); i++) { detailText = "[grantee "; detailText += LongToNAString((Lng32)i); detailText += "]"; detailTextList.append(detailText); ComASSERT(granteeArray[i] NEQ NULL AND granteeArray[i]->castToElemDDLGrantee() NEQ NULL); detailTextList.append(" ", granteeArray[i]->castToElemDDLGrantee() ->getDetailInfo()); } // // with grant option // detailText = "is with grant option? "; detailText += YesNo(localThis->getChild(INDEX_WITH_GRANT_OPTION) NEQ NULL); detailTextList.append(detailText); return detailTextList; } // StmtDDLGrant::getDetailInfo const NAString StmtDDLGrant::getText() const { return "StmtDDLGrant"; } // ----------------------------------------------------------------------- // methods for class StmtDDLGrantArray // ----------------------------------------------------------------------- // virtual destructor StmtDDLGrantArray::~StmtDDLGrantArray() { } // ----------------------------------------------------------------------- // member functions for class StmtDDLSchGrant // ----------------------------------------------------------------------- StmtDDLSchGrant::StmtDDLSchGrant(ElemDDLNode * pPrivileges, const ElemDDLSchemaName & aSchemaNameParseNode, ElemDDLNode * pGranteeList, ElemDDLNode * pWithGrantOption, ElemDDLNode * pByGrantorOption, CollHeap * heap) : StmtDDLNode(DDL_GRANT_SCHEMA), schemaName_(heap), schemaQualName_(aSchemaNameParseNode.getSchemaName(), heap), isAllDMLPrivileges_(FALSE), isAllDDLPrivileges_(FALSE), isAllOtherPrivileges_(FALSE), isWithGrantOptionSpec_(FALSE), privActArray_(heap), granteeArray_(heap), isByGrantorOptionSpec_(FALSE), byGrantor_(NULL) { if (schemaQualName_.getSchemaName().isNull()) { schemaQualName_ = ActiveSchemaDB()->getDefaultSchema(); } setChild(INDEX_PRIVILEGES, pPrivileges); setChild(INDEX_GRANTEE_LIST, pGranteeList); setChild(INDEX_WITH_GRANT_OPTION, pWithGrantOption); setChild(INDEX_BY_GRANTOR_OPTION, pByGrantorOption); //objectName_ = objectQualName_.getQualifiedNameAsAnsiString(); // // inserts pointers to parse nodes representing privilege // actions to privActArray_ so the user can access the // information about privilege actions easier. // ComASSERT(pPrivileges NEQ NULL); ElemDDLPrivileges * pPrivsNode = pPrivileges->castToElemDDLPrivileges(); ComASSERT(pPrivsNode NEQ NULL); if (pPrivsNode->isAllPrivileges()) { isAllDMLPrivileges_ = TRUE; isAllDDLPrivileges_ = TRUE; isAllOtherPrivileges_ = TRUE; } if (pPrivsNode->isAllDMLPrivileges()) { isAllDMLPrivileges_ = TRUE; } if (pPrivsNode->isAllDDLPrivileges()) { isAllDDLPrivileges_ = TRUE; } if (pPrivsNode->isAllOtherPrivileges()) { isAllOtherPrivileges_ = TRUE; } ElemDDLNode * pPrivActs = pPrivsNode->getPrivilegeActionList(); if (pPrivActs) { for (CollIndex i = 0; i < pPrivActs->entries(); i++) { privActArray_.insert((*pPrivActs)[i]->castToElemDDLPrivAct()); } } // // copies pointers to parse nodes representing grantee // to granteeArray_ so the user can access the information // easier. // ComASSERT(pGranteeList NEQ NULL); for (CollIndex i = 0; i < pGranteeList->entries(); i++) { granteeArray_.insert((*pGranteeList)[i]->castToElemDDLGrantee()); } // // looks for With Grant option phrase // if (pWithGrantOption NEQ NULL) { isWithGrantOptionSpec_ = TRUE; } if ( pByGrantorOption NEQ NULL ) { isByGrantorOptionSpec_ = TRUE; byGrantor_ = pByGrantorOption->castToElemDDLGrantee(); } } // StmtDDLSchGrant::StmtDDLSchGrant() // virtual destructor StmtDDLSchGrant::~StmtDDLSchGrant() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // cast StmtDDLSchGrant * StmtDDLSchGrant::castToStmtDDLSchGrant() { return this; } // // accessors // Int32 StmtDDLSchGrant::getArity() const { return MAX_STMT_DDL_GRANT_ARITY; } ExprNode * StmtDDLSchGrant::getChild(Lng32 index) { ComASSERT(index >= 0 AND index < getArity()); return children_[index]; } // // mutators // void StmtDDLSchGrant::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT(index >= 0 AND index < getArity()); if (pChildNode NEQ NULL) { ComASSERT(pChildNode->castToElemDDLNode() NEQ NULL); children_[index] = pChildNode->castToElemDDLNode(); } else { children_[index] = NULL; } } // // methods for tracing // const NAString StmtDDLSchGrant::displayLabel1() const { return NAString("Schema Name ") + getSchemaName(); } NATraceList StmtDDLSchGrant::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // object name // detailTextList.append(displayLabel1()); // object name // // privileges // StmtDDLSchGrant * localThis = (StmtDDLSchGrant *)this; detailTextList.append(localThis->getChild(INDEX_PRIVILEGES) ->castToElemDDLNode() ->castToElemDDLPrivileges() ->getDetailInfo()); // // grantee list // const ElemDDLGranteeArray & granteeArray = getGranteeArray(); detailText = "Grantee list ["; detailText += LongToNAString((Lng32)granteeArray.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < granteeArray.entries(); i++) { detailText = "[grantee "; detailText += LongToNAString((Lng32)i); detailText += "]"; detailTextList.append(detailText); ComASSERT(granteeArray[i] NEQ NULL AND granteeArray[i]->castToElemDDLGrantee() NEQ NULL); detailTextList.append(" ", granteeArray[i]->castToElemDDLGrantee() ->getDetailInfo()); } // // with grant option // detailText = "is with grant option? "; detailText += YesNo(localThis->getChild(INDEX_WITH_GRANT_OPTION) NEQ NULL); detailTextList.append(detailText); return detailTextList; } // StmtDDLGrant::getDetailInfo const NAString StmtDDLSchGrant::getText() const { return "StmtDDLSchGrant"; } // ----------------------------------------------------------------------- // methods for class StmtDDLSchGrantArray // ----------------------------------------------------------------------- // virtual destructor StmtDDLSchGrantArray::~StmtDDLSchGrantArray() { } // ----------------------------------------------------------------------- // methods for class StmtDDLGrantComponentPrivilege // ----------------------------------------------------------------------- // // constructor // StmtDDLGrantComponentPrivilege::StmtDDLGrantComponentPrivilege (const ConstStringList * pComponentPrivilegeNameList, const NAString & componentName, const NAString & userRoleName, const NABoolean isWithGrantOptionClauseSpecified, ElemDDLNode * pOptionalGrantedBy, CollHeap * heap) // default is PARSERHEAP() : StmtDDLNode(DDL_GRANT_COMPONENT_PRIVILEGE), pComponentPrivilegeNameList_(pComponentPrivilegeNameList), componentName_(componentName, heap), userRoleName_(userRoleName, heap), isWithGrantOptionSpec_(isWithGrantOptionClauseSpecified), grantedBy_(NULL) { if ( pOptionalGrantedBy NEQ NULL ) { grantedBy_ = pOptionalGrantedBy->castToElemDDLGrantee(); } } // // virtual destructor // StmtDDLGrantComponentPrivilege::~StmtDDLGrantComponentPrivilege() { if (pComponentPrivilegeNameList_ NEQ NULL) delete pComponentPrivilegeNameList_; } // virtual safe cast-down function StmtDDLGrantComponentPrivilege * StmtDDLGrantComponentPrivilege::castToStmtDDLGrantComponentPrivilege() { return this; } // // methods for tracing // // LCOV_EXCL_START const NAString StmtDDLGrantComponentPrivilege::displayLabel1() const { NAString aLabel("Component name: "); aLabel += getComponentName(); return aLabel; } const NAString StmtDDLGrantComponentPrivilege::displayLabel2() const { NAString aLabel("User role name: "); aLabel += getUserRoleName(); return aLabel; } NATraceList StmtDDLGrantComponentPrivilege::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // component name // detailTextList.append(displayLabel1()); // component name // // user role name // detailTextList.append(displayLabel2()); // user role name // // component privilege name list // const ConstStringList & privs = getComponentPrivilegeNameList(); detailText = "Component Privilege Name List ["; detailText += LongToNAString((Lng32)privs.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < privs.entries(); i++) { detailText = "["; detailText += LongToNAString((Lng32)i); detailText += "] "; detailText += *privs[i]; detailTextList.append(detailText); } // // with grant option // detailText = "is with grant option? "; detailText += YesNo(isWithGrantOptionSpecified()); detailTextList.append(detailText); return detailTextList; } // StmtDDLGrantComponentPrivilege::getDetailInfo const NAString StmtDDLGrantComponentPrivilege::getText() { return "StmtDDLGrantComponentPrivilege"; } // LCOV_EXCL_STOP // ----------------------------------------------------------------------- // methods for class StmtDDLRevokeComponentPrivilege // ----------------------------------------------------------------------- // // constructor // StmtDDLRevokeComponentPrivilege::StmtDDLRevokeComponentPrivilege (const ConstStringList * pComponentPrivilegeNameList, const NAString & componentName, const NAString & userRoleName, const NABoolean isGrantOptionForClauseSpecified, ElemDDLNode * pOptionalGrantedBy, CollHeap * heap) // default is PARSERHEAP() : StmtDDLNode(DDL_REVOKE_COMPONENT_PRIVILEGE), pComponentPrivilegeNameList_(pComponentPrivilegeNameList), // shallow copy componentName_(componentName, heap), // deep copy userRoleName_(userRoleName, heap), // deep copy isGrantOptionForSpec_(isGrantOptionForClauseSpecified), grantedBy_(NULL) { if ( pOptionalGrantedBy NEQ NULL ) { grantedBy_ = pOptionalGrantedBy->castToElemDDLGrantee(); } } // // virtual destructor // StmtDDLRevokeComponentPrivilege::~StmtDDLRevokeComponentPrivilege() { if (pComponentPrivilegeNameList_ NEQ NULL) delete pComponentPrivilegeNameList_; } // virtual safe cast-down function StmtDDLRevokeComponentPrivilege * StmtDDLRevokeComponentPrivilege::castToStmtDDLRevokeComponentPrivilege() { return this; } // // methods for tracing // // LCOV_EXCL_START const NAString StmtDDLRevokeComponentPrivilege::displayLabel1() const { NAString aLabel("Component name: "); aLabel += getComponentName(); return aLabel; } const NAString StmtDDLRevokeComponentPrivilege::displayLabel2() const { NAString aLabel("User rol name: "); aLabel += getUserRoleName(); return aLabel; } NATraceList StmtDDLRevokeComponentPrivilege::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // component name // detailTextList.append(displayLabel1()); // component name // // user role name // detailTextList.append(displayLabel2()); // user role name // // component privilege name list // const ConstStringList & privs = getComponentPrivilegeNameList(); detailText = "Component Privilege Name List ["; detailText += LongToNAString((Lng32)privs.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < privs.entries(); i++) { detailText = "["; detailText += LongToNAString((Lng32)i); detailText += "] "; detailText += *privs[i]; detailTextList.append(detailText); } // // with revoke option // detailText = "is Grant Option For clause specified? "; detailText += YesNo(isGrantOptionForSpecified()); detailTextList.append(detailText); return detailTextList; } // StmtDDLRevokeComponentPrivilege::getDetailInfo const NAString StmtDDLRevokeComponentPrivilege::getText() { return "StmtDDLRevokeComponentPrivilege"; } // LCOV_EXCL_STOP // ----------------------------------------------------------------------- // methodsn for class StmtDDLReInitializeSQL // ----------------------------------------------------------------------- // // constructor // StmtDDLReInitializeSQL::StmtDDLReInitializeSQL() : StmtDDLNode(DDL_REINITIALIZE_SQL) {} StmtDDLReInitializeSQL::~StmtDDLReInitializeSQL() {} const NAString StmtDDLReInitializeSQL::getText() const { return "StmtDDLReInitializeSQL"; } // // cast // StmtDDLReInitializeSQL * StmtDDLReInitializeSQL::castToStmtDDLReInitializeSQL() { return this; } // ----------------------------------------------------------------------- // member functions for class StmtDDLInitializeSQL // ----------------------------------------------------------------------- // // constructor // StmtDDLInitializeSQL::StmtDDLInitializeSQL( ElemDDLNode *pCreateRoleList, ElemDDLNode *pRegisterUserList, CollHeap *heap) : StmtDDLNode(DDL_INITIALIZE_SQL) , registerUserArray_(heap) , createRoleArray_(heap) { setChild(INDEX_REGISTER_USER_LIST, pRegisterUserList); setChild(INDEX_CREATE_ROLE_LIST, pCreateRoleList); } // // virtual destructor // StmtDDLInitializeSQL::~StmtDDLInitializeSQL() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // // cast // StmtDDLInitializeSQL * StmtDDLInitializeSQL::castToStmtDDLInitializeSQL() { return this; } Int32 StmtDDLInitializeSQL::getArity() const { return MAX_STMT_DDL_INITIALIZE_SQL_ARITY; } ExprNode * StmtDDLInitializeSQL::getChild(Lng32 index) { ComASSERT ((index >= 0) && index < getArity()); return children_[index]; } // // mutators // void StmtDDLInitializeSQL::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT ((index >= 0) && index < getArity()); if (pChildNode NEQ NULL) children_[index] = pChildNode->castToElemDDLNode(); else children_[index] = NULL; } void StmtDDLInitializeSQL_visitRegisterUserElement(ElemDDLNode * pInitSQLNode, CollIndex /* index */, ElemDDLNode * pElement) { ComASSERT(pInitSQLNode NEQ NULL AND pInitSQLNode->castToStmtDDLInitializeSQL() NEQ NULL AND pElement NEQ NULL AND pElement->getOperatorType() == DDL_REGISTER_USER); StmtDDLInitializeSQL * pInitializeSQL = pInitSQLNode->castToStmtDDLInitializeSQL(); StmtDDLRegisterUser *pRegisterUser = pElement->castToStmtDDLRegisterUser(); ComASSERT(pRegisterUser NEQ NULL); pInitializeSQL->registerUserArray_.insert(pRegisterUser); } void StmtDDLInitializeSQL_visitCreateRoleElement(ElemDDLNode * pInitSQLNode, CollIndex /* index */, ElemDDLNode * pElement) { ComASSERT(pInitSQLNode NEQ NULL AND pInitSQLNode->castToStmtDDLInitializeSQL() NEQ NULL AND pElement NEQ NULL AND pElement->getOperatorType() == DDL_CREATE_ROLE); StmtDDLInitializeSQL * pInitializeSQL = pInitSQLNode->castToStmtDDLInitializeSQL(); StmtDDLCreateRole *pCreateRole = pElement->castToStmtDDLCreateRole(); ComASSERT(pCreateRole NEQ NULL); pInitializeSQL->createRoleArray_.insert(pCreateRole); } void StmtDDLInitializeSQL::synthesize(void) { // Traverses the element list that contains parse nodes // representing register user commands. Collects pointers to // these parse nodes and saves them in the corresponding array. if (getChild(INDEX_REGISTER_USER_LIST) NEQ NULL) { ElemDDLNode *pElemList = getChild(INDEX_REGISTER_USER_LIST)->castToElemDDLNode(); ComASSERT(pElemList NEQ NULL); pElemList->traverseList(this, StmtDDLInitializeSQL_visitRegisterUserElement); } if (getChild(INDEX_CREATE_ROLE_LIST) NEQ NULL) { ElemDDLNode *pElemList = getChild(INDEX_CREATE_ROLE_LIST)->castToElemDDLNode(); ComASSERT(pElemList NEQ NULL); pElemList->traverseList(this, StmtDDLInitializeSQL_visitCreateRoleElement); } } // // methods for tracing // NATraceList StmtDDLInitializeSQL::getDetailInfo() const { NATraceList detailTextList; return detailTextList; } // StmtDDLInitializeSQL::getDetailInfo() const NAString StmtDDLInitializeSQL::getText() const { return "StmtDDLInitializeSQL"; } // ----------------------------------------------------------------------- // member functions for class StmtDDLRevoke // ----------------------------------------------------------------------- // // constructor // StmtDDLRevoke::StmtDDLRevoke(NABoolean isGrantOptionFor, ElemDDLNode * pPrivileges, const QualifiedName & objectName, ElemDDLNode * pGranteeList, ComDropBehavior dropBehavior, ElemDDLNode * pByGrantorOption, QualifiedName * actionName, CollHeap * heap) : StmtDDLNode(DDL_REVOKE), objectName_(heap), objectQualName_(objectName, heap), isAllPrivileges_(FALSE), isGrantOptionForSpec_(isGrantOptionFor), dropBehavior_(dropBehavior), privActArray_(heap), actionQualName_(actionName), granteeArray_(heap), isByGrantorOptionSpec_(FALSE), byGrantor_(NULL) { setChild(INDEX_PRIVILEGES, pPrivileges); setChild(INDEX_GRANTEE_LIST, pGranteeList); setChild(INDEX_BY_GRANTOR_OPTION, pByGrantorOption); // // Fully expand the name. // objectName_ = objectQualName_.getQualifiedNameAsAnsiString(); // // inserts pointers to parse nodes representing privilege // actions to privActArray_ so the user can access the // information about privilege actions easier. // ComASSERT(pPrivileges NEQ NULL); ElemDDLPrivileges * pPrivsNode = pPrivileges->castToElemDDLPrivileges(); ComASSERT(pPrivsNode NEQ NULL); if (pPrivsNode->isAllPrivileges()) { isAllPrivileges_ = TRUE; } else { ElemDDLNode * pPrivActs = pPrivsNode->getPrivilegeActionList(); for (CollIndex i = 0; i < pPrivActs->entries(); i++) { ElemDDLPrivAct *pPrivAct = (*pPrivActs)[i]->castToElemDDLPrivAct(); privActArray_.insert(pPrivAct); if (pPrivAct->isDDLPriv()) privActArray_.setHasDDLPriv(TRUE); } } // // copies pointers to parse nodes representing grantee // to granteeArray_ so the user can access the information // easier. // ComASSERT(pGranteeList NEQ NULL); for (CollIndex i = 0; i < pGranteeList->entries(); i++) { granteeArray_.insert((*pGranteeList)[i]->castToElemDDLGrantee()); } if ( pByGrantorOption NEQ NULL ) { isByGrantorOptionSpec_ = TRUE; byGrantor_ = pByGrantorOption->castToElemDDLGrantee(); } } // StmtDDLRevoke::StmtDDLRevoke() // virtual destructor StmtDDLRevoke::~StmtDDLRevoke() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // cast StmtDDLRevoke * StmtDDLRevoke::castToStmtDDLRevoke() { return this; } // // accessors // Int32 StmtDDLRevoke::getArity() const { return MAX_STMT_DDL_REVOKE_ARITY; } ExprNode * StmtDDLRevoke::getChild(Lng32 index) { ComASSERT(index >= 0 AND index < getArity()); return children_[index]; } // // mutators // void StmtDDLRevoke::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT(index >= 0 AND index < getArity()); if (pChildNode NEQ NULL) { ComASSERT(pChildNode->castToElemDDLNode() NEQ NULL); children_[index] = pChildNode->castToElemDDLNode(); } else { children_[index] = NULL; } } // // methods for tracing // const NAString StmtDDLRevoke::displayLabel1() const { return NAString("Object name: ") + getObjectName(); } const NAString StmtDDLRevoke::displayLabel2() const { NAString label2("Drop behavior: "); switch (getDropBehavior()) { case COM_CASCADE_DROP_BEHAVIOR : return label2 + "Cascade"; case COM_RESTRICT_DROP_BEHAVIOR : return label2 + "Restrict"; default : ABORT("internal logic error"); return NAString(); } } NATraceList StmtDDLRevoke::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // object name // detailTextList.append(displayLabel1()); // object name // // privileges // StmtDDLRevoke * localThis = (StmtDDLRevoke *)this; detailTextList.append(localThis->getChild(INDEX_PRIVILEGES) ->castToElemDDLNode() ->castToElemDDLPrivileges() ->getDetailInfo()); // // grantee list // const ElemDDLGranteeArray & granteeArray = getGranteeArray(); detailText = "Grantee list ["; detailText += LongToNAString((Lng32)granteeArray.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < granteeArray.entries(); i++) { detailText = "[grantee "; detailText += LongToNAString((Lng32)i); detailText += "]"; detailTextList.append(detailText); ComASSERT(granteeArray[i] NEQ NULL AND granteeArray[i]->castToElemDDLGrantee() NEQ NULL); detailTextList.append(" ", granteeArray[i]->castToElemDDLGrantee() ->getDetailInfo()); } // // grant option for // detailText = "is grant option for? "; detailText += YesNo(isGrantOptionForSpecified()); detailTextList.append(detailText); // // drop behavior // detailTextList.append(displayLabel2()); // drop behavior return detailTextList; } // StmtDDLRevoke::getDetailInfo const NAString StmtDDLRevoke::getText() const { return "StmtDDLRevoke"; } // ----------------------------------------------------------------------- // member functions for class StmtDDLSchRevoke // ----------------------------------------------------------------------- // // constructor // StmtDDLSchRevoke::StmtDDLSchRevoke(NABoolean isGrantOptionFor, ElemDDLNode * pPrivileges, const ElemDDLSchemaName & aSchemaNameParseNode, ElemDDLNode * pGranteeList, ComDropBehavior dropBehavior, ElemDDLNode * pByGrantorOption, CollHeap * heap) : StmtDDLNode(DDL_REVOKE_SCHEMA), schemaName_(heap), schemaQualName_(aSchemaNameParseNode.getSchemaName(), heap), isAllDDLPrivileges_(FALSE), isAllDMLPrivileges_(FALSE), isAllOtherPrivileges_(FALSE), isGrantOptionForSpec_(isGrantOptionFor), dropBehavior_(dropBehavior), privActArray_(heap), granteeArray_(heap), isByGrantorOptionSpec_(FALSE), byGrantor_(NULL) { setChild(INDEX_PRIVILEGES, pPrivileges); setChild(INDEX_GRANTEE_LIST, pGranteeList); setChild(INDEX_BY_GRANTOR_OPTION, pByGrantorOption); // // inserts pointers to parse nodes representing privilege // actions to privActArray_ so the user can access the // information about privilege actions easier. // ComASSERT(pPrivileges NEQ NULL); ElemDDLPrivileges * pPrivsNode = pPrivileges->castToElemDDLPrivileges(); ComASSERT(pPrivsNode NEQ NULL); if (pPrivsNode->isAllPrivileges()) { isAllDDLPrivileges_ = TRUE; isAllDMLPrivileges_ = TRUE; isAllOtherPrivileges_ = TRUE; } if (pPrivsNode->isAllDDLPrivileges()) { isAllDDLPrivileges_ = TRUE; } if (pPrivsNode->isAllDMLPrivileges()) { isAllDMLPrivileges_ = TRUE; } if (pPrivsNode->isAllOtherPrivileges()) { isAllOtherPrivileges_ = TRUE; } ElemDDLNode * pPrivActs = pPrivsNode->getPrivilegeActionList(); if (pPrivActs) { for (CollIndex i = 0; i < pPrivActs->entries(); i++) { privActArray_.insert((*pPrivActs)[i]->castToElemDDLPrivAct()); } } // // copies pointers to parse nodes representing grantee // to granteeArray_ so the user can access the information // easier. // ComASSERT(pGranteeList NEQ NULL); for (CollIndex i = 0; i < pGranteeList->entries(); i++) { granteeArray_.insert((*pGranteeList)[i]->castToElemDDLGrantee()); } if ( pByGrantorOption NEQ NULL ) { isByGrantorOptionSpec_ = TRUE; byGrantor_ = pByGrantorOption->castToElemDDLGrantee(); } } // StmtDDLSchRevoke::StmtDDLSchRevoke() // virtual destructor StmtDDLSchRevoke::~StmtDDLSchRevoke() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // cast StmtDDLSchRevoke * StmtDDLSchRevoke::castToStmtDDLSchRevoke() { return this; } // // accessors // Int32 StmtDDLSchRevoke::getArity() const { return MAX_STMT_DDL_REVOKE_ARITY; } ExprNode * StmtDDLSchRevoke::getChild(Lng32 index) { ComASSERT(index >= 0 AND index < getArity()); return children_[index]; } // // mutators // void StmtDDLSchRevoke::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT(index >= 0 AND index < getArity()); if (pChildNode NEQ NULL) { ComASSERT(pChildNode->castToElemDDLNode() NEQ NULL); children_[index] = pChildNode->castToElemDDLNode(); } else { children_[index] = NULL; } } // // methods for tracing // // LCOV_EXCL_START const NAString StmtDDLSchRevoke::displayLabel1() const { return NAString("Schema name: ") + getSchemaName(); } const NAString StmtDDLSchRevoke::displayLabel2() const { NAString label2("Drop behavior: "); switch (getDropBehavior()) { case COM_CASCADE_DROP_BEHAVIOR : return label2 + "Cascade"; case COM_RESTRICT_DROP_BEHAVIOR : return label2 + "Restrict"; default : ABORT("internal logic error"); return NAString(); } } NATraceList StmtDDLSchRevoke::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // object name // detailTextList.append(displayLabel1()); // object name // // privileges // StmtDDLSchRevoke * localThis = (StmtDDLSchRevoke *)this; detailTextList.append(localThis->getChild(INDEX_PRIVILEGES) ->castToElemDDLNode() ->castToElemDDLPrivileges() ->getDetailInfo()); // // grantee list // const ElemDDLGranteeArray & granteeArray = getGranteeArray(); detailText = "Grantee list ["; detailText += LongToNAString((Lng32)granteeArray.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < granteeArray.entries(); i++) { detailText = "[grantee "; detailText += LongToNAString((Lng32)i); detailText += "]"; detailTextList.append(detailText); ComASSERT(granteeArray[i] NEQ NULL AND granteeArray[i]->castToElemDDLGrantee() NEQ NULL); detailTextList.append(" ", granteeArray[i]->castToElemDDLGrantee() ->getDetailInfo()); } // // grant option for // detailText = "is grant option for? "; detailText += YesNo(isGrantOptionForSpecified()); detailTextList.append(detailText); // // drop behavior // detailTextList.append(displayLabel2()); // drop behavior return detailTextList; } // StmtDDLSchRevoke::getDetailInfo const NAString StmtDDLSchRevoke::getText() const { return "StmtDDLSchRevoke"; } // LCOV_EXCL_STOP // ----------------------------------------------------------------------- // member functions for class StmtDDLPublish // ----------------------------------------------------------------------- // // constructor // StmtDDLPublish::StmtDDLPublish(ElemDDLNode * pPrivileges, const QualifiedName & objectName, const NAString & synonymName, ComBoolean isRole, ElemDDLNode * pGranteeList, ComBoolean isPublish, CollHeap * heap) : StmtDDLNode(DDL_PUBLISH), objectName_(heap), objectQualName_(objectName, heap), synonymName_(synonymName, heap), isSynonymNameSpec_(FALSE), isRoleList_(isRole), isPublish_(isPublish), isAllPrivileges_(FALSE), privActArray_(heap), granteeArray_(heap) { setChild(PUBLISH_PRIVILEGES, pPrivileges); setChild(PUBLISH_GRANTEE_LIST, pGranteeList); objectName_ = objectQualName_.getQualifiedNameAsAnsiString(); if (!synonymName.isNull()) isSynonymNameSpec_ = TRUE; // // inserts pointers to parse nodes representing privilege // actions to privActArray_ so the user can access the // information about privilege actions easier. // ComASSERT(pPrivileges NEQ NULL); ElemDDLPrivileges * pPrivsNode = pPrivileges->castToElemDDLPrivileges(); ComASSERT(pPrivsNode NEQ NULL); if (pPrivsNode->isAllPrivileges()) { isAllPrivileges_ = TRUE; } else { ElemDDLNode * pPrivActs = pPrivsNode->getPrivilegeActionList(); for (CollIndex i = 0; i < pPrivActs->entries(); i++) { ElemDDLPrivAct *pPrivAct = (*pPrivActs)[i]->castToElemDDLPrivAct(); privActArray_.insert(pPrivAct); } } // // copies pointers to parse nodes representing grantee // to granteeArray_ so the user can access the information // easier. // ComASSERT(pGranteeList NEQ NULL); for (CollIndex i = 0; i < pGranteeList->entries(); i++) { granteeArray_.insert((*pGranteeList)[i]->castToElemDDLGrantee()); } } // StmtDDLPublish::StmtDDLPublish() // virtual destructor StmtDDLPublish::~StmtDDLPublish() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // cast StmtDDLPublish * StmtDDLPublish::castToStmtDDLPublish() { return this; } // // accessors // Int32 StmtDDLPublish::getArity() const { return MAX_STMT_DDL_PUBLISH_ARITY; } ExprNode * StmtDDLPublish::getChild(Lng32 index) { ComASSERT(index >= 0 AND index < getArity()); return children_[index]; } // // mutators // void StmtDDLPublish::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT(index >= 0 AND index < getArity()); if (pChildNode NEQ NULL) { ComASSERT(pChildNode->castToElemDDLNode() NEQ NULL); children_[index] = pChildNode->castToElemDDLNode(); } else { children_[index] = NULL; } } // // methods for tracing // // LCOV_EXCL_START const NAString StmtDDLPublish::displayLabel1() const { return NAString("Object name: ") + getObjectName(); } NATraceList StmtDDLPublish::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // object name // detailTextList.append(displayLabel1()); // object name // // privileges // StmtDDLPublish * localThis = (StmtDDLPublish *)this; detailTextList.append(localThis->getChild(PUBLISH_PRIVILEGES) ->castToElemDDLNode() ->castToElemDDLPrivileges() ->getDetailInfo()); // grantee list // const ElemDDLGranteeArray & granteeArray = getGranteeArray(); detailText = "Grantee list ["; detailText += LongToNAString((Lng32)granteeArray.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < granteeArray.entries(); i++) { detailText = "[grantee "; detailText += LongToNAString((Lng32)i); detailText += "]"; detailTextList.append(detailText); ComASSERT(granteeArray[i] NEQ NULL AND granteeArray[i]->castToElemDDLGrantee() NEQ NULL); detailTextList.append(" ", granteeArray[i]->castToElemDDLGrantee() ->getDetailInfo()); } return detailTextList; } // StmtDDLPublish::getDetailInfo const NAString StmtDDLPublish::getText() const { return "StmtDDLPublish"; } // LCOV_EXCL_STOP // ----------------------------------------------------------------------- // methods for class StmtDDLRegisterComponent // ----------------------------------------------------------------------- // // constructors used for (UN)REGISTER COMPONENT // StmtDDLRegisterComponent::StmtDDLRegisterComponent(StmtDDLRegisterComponent::RegisterComponentType eRegComponentParseNodeType, const NAString & sComponentName, const NABoolean isSystem, const NAString & sDetailInfo, CollHeap * heap) : StmtDDLNode(DDL_REGISTER_COMPONENT), registerComponentType_(eRegComponentParseNodeType), componentName_(sComponentName, heap), isSystem_(isSystem), componentDetailInfo_(sDetailInfo, heap) { } StmtDDLRegisterComponent::StmtDDLRegisterComponent(StmtDDLRegisterComponent::RegisterComponentType eRegComponentParseNodeType, const NAString & sComponentName, ComDropBehavior dropBehavior, CollHeap * heap) : StmtDDLNode(DDL_REGISTER_COMPONENT), registerComponentType_(eRegComponentParseNodeType), componentName_(sComponentName, heap), dropBehavior_(dropBehavior), componentDetailInfo_(heap) { } // // virtual destructor // StmtDDLRegisterComponent::~StmtDDLRegisterComponent() { } // // cast // StmtDDLRegisterComponent * StmtDDLRegisterComponent::castToStmtDDLRegisterComponent() { return this; } // // methods for tracing // // LCOV_EXCL_START const NAString StmtDDLRegisterComponent::displayLabel1() const { NAString aLabel("UNREGISTER COMPONENT"); if (getRegisterComponentType() == StmtDDLRegisterComponent::REGISTER_COMPONENT) { aLabel = "REGISTER COMPONENT"; if (isSystem()) aLabel += " (SYSTEM)"; } aLabel += " - External Component name: "; aLabel += getExternalComponentName(); if (getRegisterComponentType() == StmtDDLRegisterComponent::UNREGISTER_COMPONENT) { aLabel += " Drop behavior: "; if (dropBehavior_ == COM_CASCADE_DROP_BEHAVIOR) aLabel += "CASCADE"; else aLabel += "RESTRICT"; } return aLabel; } const NAString StmtDDLRegisterComponent::displayLabel2() const { if (NOT getRegisterComponentDetailInfo().isNull()) { return NAString("Detail Information: ") + getRegisterComponentDetailInfo(); } else { return NAString("No Detail Information (i.e., an empty string)."); } } const NAString StmtDDLRegisterComponent::getText() const { return "StmtDDLRegisterComponent"; } // LCOV_EXCL_STOP // // End of File //
24.540541
126
0.634384
sandhyasun
eabc05816776c1a659881280881d2cda272183b6
5,497
cpp
C++
STM32_Resources/Default/NES/mapper/083.cpp
Shuzhengz/Projects-Code
1b9608004a682b1da4e31f3160736e5b2c52fb33
[ "MIT" ]
14
2019-01-14T08:16:55.000Z
2021-06-14T11:56:56.000Z
STM32_Resources/Default/NES/mapper/083.cpp
Shuzhengz/Projects-Code
1b9608004a682b1da4e31f3160736e5b2c52fb33
[ "MIT" ]
null
null
null
STM32_Resources/Default/NES/mapper/083.cpp
Shuzhengz/Projects-Code
1b9608004a682b1da4e31f3160736e5b2c52fb33
[ "MIT" ]
4
2019-01-14T08:16:32.000Z
2021-12-05T05:53:06.000Z
///////////////////////////////////////////////////////////////////// // Mapper 83 void NES_mapper83::Reset() { regs[0] = regs[1] = regs[2] = 0; // set CPU bank pointers if(num_8k_ROM_banks >= 32) { set_CPU_banks(0,1,30,31); regs[1] = 0x30; } else { set_CPU_banks(0,1,num_8k_ROM_banks-2,num_8k_ROM_banks-1); } // set PPU bank pointers if(num_1k_VROM_banks) { set_PPU_banks(0,1,2,3,4,5,6,7); } irq_enabled = 0; irq_counter = 0; } uint8 NES_mapper83::MemoryReadLow(uint32 addr) { if((addr & 0x5100) == 0x5100) { return regs[2]; } else { return addr >> 8; } } void NES_mapper83::MemoryWriteLow(uint32 addr, uint8 data) { switch(addr) { case 0x5101: case 0x5102: case 0x5103: { regs[2] = data; } break; } } void NES_mapper83::MemoryWrite(uint32 addr, uint8 data) { switch(addr) { case 0x8000: case 0xB000: case 0xB0FF: case 0xB1FF: { regs[0] = data; set_CPU_bank4(data*2+0); set_CPU_bank5(data*2+1); set_CPU_bank6(((data&0x30)|0x0F)*2+0); set_CPU_bank7(((data&0x30)|0x0F)*2+1); } break; case 0x8100: { if(num_1k_VROM_banks <= 32*8) { regs[1] = data; } if((data & 0x03) == 0x00) { set_mirroring(NES_PPU::MIRROR_VERT); } else if((data & 0x03) == 0x01) { set_mirroring(NES_PPU::MIRROR_HORIZ); } else if((data & 0x03) == 0x02) { set_mirroring(0,0,0,0); } else { set_mirroring(1,1,1,1); } } break; case 0x8200: { irq_counter = (irq_counter & 0xFF00) | (uint32)data; } break; case 0x8201: { irq_counter = (irq_counter & 0x00FF) | ((uint32)data << 8); irq_enabled = data; } break; case 0x8300: { set_CPU_bank4(data); } break; case 0x8301: { set_CPU_bank5(data); } break; case 0x8302: { set_CPU_bank6(data); } break; case 0x8310: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank0(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank0((((data & 0x30) << 4)^data)*2+0); set_PPU_bank1((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8311: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank1(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank2((((data & 0x30) << 4)^data)*2+0); set_PPU_bank3((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8312: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank2(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank4((((data & 0x30) << 4)^data)*2+0); set_PPU_bank5((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8313: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank3(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank6((((data & 0x30) << 4)^data)*2+0); set_PPU_bank7((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8314: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank4(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank4((((data & 0x30) << 4)^data)*2+0); set_PPU_bank5((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8315: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank5(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank6((((data & 0x30) << 4)^data)*2+0); set_PPU_bank7((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8316: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank6(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank4((((data & 0x30) << 4)^data)*2+0); set_PPU_bank5((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8317: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank7(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank6((((data & 0x30) << 4)^data)*2+0); set_PPU_bank7((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8318: { set_CPU_bank4(((regs[0]&0x30)|data)*2+0); set_CPU_bank5(((regs[0]&0x30)|data)*2+1); } break; } } void NES_mapper83::HSync(uint32 scanline) { if(irq_enabled) { if(irq_counter <= 114) { parent_NES->cpu->DoIRQ(); irq_enabled = 0; } else { irq_counter -= 114; } } } /////////////////////////////////////////////////////////////////////
20.588015
69
0.433873
Shuzhengz
eabef1dd8733d3b75f83cffbbeb0509d369503f5
103
cpp
C++
addresslab.cpp
CaQtiml/CaQ-s-NOOB-LAB
a6cd2a730f2b2e6a834b1b39521052c5125150b5
[ "MIT" ]
null
null
null
addresslab.cpp
CaQtiml/CaQ-s-NOOB-LAB
a6cd2a730f2b2e6a834b1b39521052c5125150b5
[ "MIT" ]
null
null
null
addresslab.cpp
CaQtiml/CaQ-s-NOOB-LAB
a6cd2a730f2b2e6a834b1b39521052c5125150b5
[ "MIT" ]
null
null
null
#include "stdio.h" int main() { int b=8; int &a=b; printf("%d",a); b+=2; printf("%d",a); }
11.444444
19
0.466019
CaQtiml
eac4248c774fa43b3fac2efa59431b406736dfbb
8,112
cpp
C++
aws-cpp-sdk-securityhub/source/model/AwsEc2VpcEndpointServiceDetails.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-securityhub/source/model/AwsEc2VpcEndpointServiceDetails.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-securityhub/source/model/AwsEc2VpcEndpointServiceDetails.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/securityhub/model/AwsEc2VpcEndpointServiceDetails.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SecurityHub { namespace Model { AwsEc2VpcEndpointServiceDetails::AwsEc2VpcEndpointServiceDetails() : m_acceptanceRequired(false), m_acceptanceRequiredHasBeenSet(false), m_availabilityZonesHasBeenSet(false), m_baseEndpointDnsNamesHasBeenSet(false), m_managesVpcEndpoints(false), m_managesVpcEndpointsHasBeenSet(false), m_gatewayLoadBalancerArnsHasBeenSet(false), m_networkLoadBalancerArnsHasBeenSet(false), m_privateDnsNameHasBeenSet(false), m_serviceIdHasBeenSet(false), m_serviceNameHasBeenSet(false), m_serviceStateHasBeenSet(false), m_serviceTypeHasBeenSet(false) { } AwsEc2VpcEndpointServiceDetails::AwsEc2VpcEndpointServiceDetails(JsonView jsonValue) : m_acceptanceRequired(false), m_acceptanceRequiredHasBeenSet(false), m_availabilityZonesHasBeenSet(false), m_baseEndpointDnsNamesHasBeenSet(false), m_managesVpcEndpoints(false), m_managesVpcEndpointsHasBeenSet(false), m_gatewayLoadBalancerArnsHasBeenSet(false), m_networkLoadBalancerArnsHasBeenSet(false), m_privateDnsNameHasBeenSet(false), m_serviceIdHasBeenSet(false), m_serviceNameHasBeenSet(false), m_serviceStateHasBeenSet(false), m_serviceTypeHasBeenSet(false) { *this = jsonValue; } AwsEc2VpcEndpointServiceDetails& AwsEc2VpcEndpointServiceDetails::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("AcceptanceRequired")) { m_acceptanceRequired = jsonValue.GetBool("AcceptanceRequired"); m_acceptanceRequiredHasBeenSet = true; } if(jsonValue.ValueExists("AvailabilityZones")) { Array<JsonView> availabilityZonesJsonList = jsonValue.GetArray("AvailabilityZones"); for(unsigned availabilityZonesIndex = 0; availabilityZonesIndex < availabilityZonesJsonList.GetLength(); ++availabilityZonesIndex) { m_availabilityZones.push_back(availabilityZonesJsonList[availabilityZonesIndex].AsString()); } m_availabilityZonesHasBeenSet = true; } if(jsonValue.ValueExists("BaseEndpointDnsNames")) { Array<JsonView> baseEndpointDnsNamesJsonList = jsonValue.GetArray("BaseEndpointDnsNames"); for(unsigned baseEndpointDnsNamesIndex = 0; baseEndpointDnsNamesIndex < baseEndpointDnsNamesJsonList.GetLength(); ++baseEndpointDnsNamesIndex) { m_baseEndpointDnsNames.push_back(baseEndpointDnsNamesJsonList[baseEndpointDnsNamesIndex].AsString()); } m_baseEndpointDnsNamesHasBeenSet = true; } if(jsonValue.ValueExists("ManagesVpcEndpoints")) { m_managesVpcEndpoints = jsonValue.GetBool("ManagesVpcEndpoints"); m_managesVpcEndpointsHasBeenSet = true; } if(jsonValue.ValueExists("GatewayLoadBalancerArns")) { Array<JsonView> gatewayLoadBalancerArnsJsonList = jsonValue.GetArray("GatewayLoadBalancerArns"); for(unsigned gatewayLoadBalancerArnsIndex = 0; gatewayLoadBalancerArnsIndex < gatewayLoadBalancerArnsJsonList.GetLength(); ++gatewayLoadBalancerArnsIndex) { m_gatewayLoadBalancerArns.push_back(gatewayLoadBalancerArnsJsonList[gatewayLoadBalancerArnsIndex].AsString()); } m_gatewayLoadBalancerArnsHasBeenSet = true; } if(jsonValue.ValueExists("NetworkLoadBalancerArns")) { Array<JsonView> networkLoadBalancerArnsJsonList = jsonValue.GetArray("NetworkLoadBalancerArns"); for(unsigned networkLoadBalancerArnsIndex = 0; networkLoadBalancerArnsIndex < networkLoadBalancerArnsJsonList.GetLength(); ++networkLoadBalancerArnsIndex) { m_networkLoadBalancerArns.push_back(networkLoadBalancerArnsJsonList[networkLoadBalancerArnsIndex].AsString()); } m_networkLoadBalancerArnsHasBeenSet = true; } if(jsonValue.ValueExists("PrivateDnsName")) { m_privateDnsName = jsonValue.GetString("PrivateDnsName"); m_privateDnsNameHasBeenSet = true; } if(jsonValue.ValueExists("ServiceId")) { m_serviceId = jsonValue.GetString("ServiceId"); m_serviceIdHasBeenSet = true; } if(jsonValue.ValueExists("ServiceName")) { m_serviceName = jsonValue.GetString("ServiceName"); m_serviceNameHasBeenSet = true; } if(jsonValue.ValueExists("ServiceState")) { m_serviceState = jsonValue.GetString("ServiceState"); m_serviceStateHasBeenSet = true; } if(jsonValue.ValueExists("ServiceType")) { Array<JsonView> serviceTypeJsonList = jsonValue.GetArray("ServiceType"); for(unsigned serviceTypeIndex = 0; serviceTypeIndex < serviceTypeJsonList.GetLength(); ++serviceTypeIndex) { m_serviceType.push_back(serviceTypeJsonList[serviceTypeIndex].AsObject()); } m_serviceTypeHasBeenSet = true; } return *this; } JsonValue AwsEc2VpcEndpointServiceDetails::Jsonize() const { JsonValue payload; if(m_acceptanceRequiredHasBeenSet) { payload.WithBool("AcceptanceRequired", m_acceptanceRequired); } if(m_availabilityZonesHasBeenSet) { Array<JsonValue> availabilityZonesJsonList(m_availabilityZones.size()); for(unsigned availabilityZonesIndex = 0; availabilityZonesIndex < availabilityZonesJsonList.GetLength(); ++availabilityZonesIndex) { availabilityZonesJsonList[availabilityZonesIndex].AsString(m_availabilityZones[availabilityZonesIndex]); } payload.WithArray("AvailabilityZones", std::move(availabilityZonesJsonList)); } if(m_baseEndpointDnsNamesHasBeenSet) { Array<JsonValue> baseEndpointDnsNamesJsonList(m_baseEndpointDnsNames.size()); for(unsigned baseEndpointDnsNamesIndex = 0; baseEndpointDnsNamesIndex < baseEndpointDnsNamesJsonList.GetLength(); ++baseEndpointDnsNamesIndex) { baseEndpointDnsNamesJsonList[baseEndpointDnsNamesIndex].AsString(m_baseEndpointDnsNames[baseEndpointDnsNamesIndex]); } payload.WithArray("BaseEndpointDnsNames", std::move(baseEndpointDnsNamesJsonList)); } if(m_managesVpcEndpointsHasBeenSet) { payload.WithBool("ManagesVpcEndpoints", m_managesVpcEndpoints); } if(m_gatewayLoadBalancerArnsHasBeenSet) { Array<JsonValue> gatewayLoadBalancerArnsJsonList(m_gatewayLoadBalancerArns.size()); for(unsigned gatewayLoadBalancerArnsIndex = 0; gatewayLoadBalancerArnsIndex < gatewayLoadBalancerArnsJsonList.GetLength(); ++gatewayLoadBalancerArnsIndex) { gatewayLoadBalancerArnsJsonList[gatewayLoadBalancerArnsIndex].AsString(m_gatewayLoadBalancerArns[gatewayLoadBalancerArnsIndex]); } payload.WithArray("GatewayLoadBalancerArns", std::move(gatewayLoadBalancerArnsJsonList)); } if(m_networkLoadBalancerArnsHasBeenSet) { Array<JsonValue> networkLoadBalancerArnsJsonList(m_networkLoadBalancerArns.size()); for(unsigned networkLoadBalancerArnsIndex = 0; networkLoadBalancerArnsIndex < networkLoadBalancerArnsJsonList.GetLength(); ++networkLoadBalancerArnsIndex) { networkLoadBalancerArnsJsonList[networkLoadBalancerArnsIndex].AsString(m_networkLoadBalancerArns[networkLoadBalancerArnsIndex]); } payload.WithArray("NetworkLoadBalancerArns", std::move(networkLoadBalancerArnsJsonList)); } if(m_privateDnsNameHasBeenSet) { payload.WithString("PrivateDnsName", m_privateDnsName); } if(m_serviceIdHasBeenSet) { payload.WithString("ServiceId", m_serviceId); } if(m_serviceNameHasBeenSet) { payload.WithString("ServiceName", m_serviceName); } if(m_serviceStateHasBeenSet) { payload.WithString("ServiceState", m_serviceState); } if(m_serviceTypeHasBeenSet) { Array<JsonValue> serviceTypeJsonList(m_serviceType.size()); for(unsigned serviceTypeIndex = 0; serviceTypeIndex < serviceTypeJsonList.GetLength(); ++serviceTypeIndex) { serviceTypeJsonList[serviceTypeIndex].AsObject(m_serviceType[serviceTypeIndex].Jsonize()); } payload.WithArray("ServiceType", std::move(serviceTypeJsonList)); } return payload; } } // namespace Model } // namespace SecurityHub } // namespace Aws
31.937008
158
0.784147
perfectrecall
eac6d42b898df62950c863b4f09fa22c958e6892
1,974
cpp
C++
PnC/DracoPnC/DracoStateMachine/Initialize.cpp
BharathMasetty/PnC
3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f
[ "MIT" ]
null
null
null
PnC/DracoPnC/DracoStateMachine/Initialize.cpp
BharathMasetty/PnC
3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f
[ "MIT" ]
null
null
null
PnC/DracoPnC/DracoStateMachine/Initialize.cpp
BharathMasetty/PnC
3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f
[ "MIT" ]
null
null
null
#include <PnC/DracoPnC/DracoCtrlArchitecture/DracoCtrlArchitecture.hpp> #include <PnC/DracoPnC/DracoStateMachine/Initialize.hpp> Initialize::Initialize(const StateIdentifier state_identifier_in, DracoControlArchitecture* _ctrl_arch, RobotSystem* _robot) : StateMachine(state_identifier_in, _robot) { myUtils::pretty_constructor(2, "SM: Initialize"); // Set Pointer to Control Architecture ctrl_arch_ = ((DracoControlArchitecture*)_ctrl_arch); taf_container_ = ctrl_arch_->taf_container_; // Get State Provider sp_ = DracoStateProvider::getStateProvider(robot_); } Initialize::~Initialize() {} void Initialize::firstVisit() { std::cout << "[Initialize]" << std::endl; ctrl_start_time_ = sp_->curr_time; ctrl_arch_->joint_trajectory_manager_->initializeJointTrajectory( 0., end_time_, target_pos_); } void Initialize::_taskUpdate() { // ========================================================================= // Joint // ========================================================================= ctrl_arch_->joint_trajectory_manager_->updateJointDesired( state_machine_time_); } void Initialize::oneStep() { state_machine_time_ = sp_->curr_time - ctrl_start_time_; _taskUpdate(); } void Initialize::lastVisit() {} bool Initialize::endOfState() { if (state_machine_time_ > end_time_) { return true; } return false; } StateIdentifier Initialize::getNextState() { return DRACO_STATES::STAND; } void Initialize::initialization(const YAML::Node& node) { try { myUtils::readParameter(node, "target_pos_duration", end_time_); myUtils::readParameter(node, "smoothing_duration", smoothing_dur_); myUtils::readParameter(node, "target_pos", target_pos_); } catch (std::runtime_error& e) { std::cout << "Error reading parameter [" << e.what() << "] at file: [" << __FILE__ << "]" << std::endl << std::endl; exit(0); } }
31.333333
78
0.644883
BharathMasetty
ead1b640546a3846870ddb6afb1cc99741fe7a51
1,788
cc
C++
core/user.cc
DaYeSquad/worktiledemo
1dd0a14255fc006824c896ea236120cd3ce32a6c
[ "MIT" ]
36
2016-04-04T03:10:45.000Z
2020-12-31T07:03:28.000Z
core/user.cc
DaYeSquad/worktiledemo
1dd0a14255fc006824c896ea236120cd3ce32a6c
[ "MIT" ]
null
null
null
core/user.cc
DaYeSquad/worktiledemo
1dd0a14255fc006824c896ea236120cd3ce32a6c
[ "MIT" ]
6
2016-04-12T08:48:17.000Z
2021-07-24T08:15:00.000Z
// // user.cpp // HelloWorktile // // Created by Frank Lin on 3/23/16. // Copyright © 2016 Frank Lin. All rights reserved. // #include "user.h" #include "json11/json11.hpp" using std::string; using std::unique_ptr; NS_WTC_BEGIN //////////////////////////////////////////////////////////////////////////////// // User, public: // Creation and lifetime -------------------------------------------------------- void User::Init(const std::string &uid, const std::string &username, const std::string &display_name, worktile::User::Status status) { uid_ = uid; username_ = username; display_name_ = display_name; status_ = status; } bool User::InitWithJsonOrDie(const std::string& json) { /* worktile 示例中的 json (https://open.worktile.com/wiki/user_info.html#/user) { "uid":"679efdf3960d45a0b8679693098135ff", "name":"gonglinjie", "display_name":"龚林杰", "email":"gonglinjie@worktile.com", "desc":"", "avatar":"https://api.worktile.com/avatar/80/ae2805fc-9aca-4f3b-8ac4-320c5d664db7.png", "status":3, "online":0 } */ string error; json11::Json json_obj = json11::Json::parse(json, error); if (!error.empty()) { return false; } uid_ = json_obj["uid"].string_value(); username_ = json_obj["name"].string_value(); display_name_ = json_obj["display_name"].string_value(); status_ = static_cast<User::Status>(json_obj["status"].int_value()); return true; } std::unique_ptr<User> User::Clone() const { unique_ptr<User> user(new User()); user->Init(uid_, username_, display_name_, status_); return user; } // Utils -------------------------------------------------------- std::string User::StatusDescription() const { return display_name_ + " is " + std::to_string(static_cast<int>(status_)); } NS_WTC_END
25.183099
134
0.604586
DaYeSquad
ead37173e91c5524dd8f41d266b05b0590ff2d40
5,763
cpp
C++
emulator/src/mame/video/pcw.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/video/pcw.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/video/pcw.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:GPL-2.0+ // copyright-holders:Kevin Thacker /*************************************************************************** pcw.c Functions to emulate the video hardware of the Amstrad PCW. ***************************************************************************/ #include "emu.h" #include "includes/pcw.h" #include "machine/ram.h" inline void pcw_state::pcw_plot_pixel(bitmap_ind16 &bitmap, int x, int y, uint32_t color) { bitmap.pix16(y, x) = (uint16_t)color; } /*************************************************************************** Start the video hardware emulation. ***************************************************************************/ void pcw_state::video_start() { rectangle rect(0, PCW_PRINTER_WIDTH - 1, 0, PCW_PRINTER_HEIGHT - 1); m_prn_output = std::make_unique<bitmap_ind16>(PCW_PRINTER_WIDTH,PCW_PRINTER_HEIGHT); m_prn_output->fill(1, rect); } #if 0 /* two colours */ static const unsigned short pcw_colour_table[PCW_NUM_COLOURS] = { 0, 1 }; #endif /* black/white */ static const rgb_t pcw_palette[PCW_NUM_COLOURS] = { rgb_t(0x000, 0x000, 0x000), rgb_t(0x0ff, 0x0ff, 0x0ff) }; /* Initialise the palette */ PALETTE_INIT_MEMBER(pcw_state, pcw) { palette.set_pen_colors(0, pcw_palette, ARRAY_LENGTH(pcw_palette)); } /*************************************************************************** Draw the game screen in the given bitmap_ind16. Do NOT call osd_update_display() from this function, it will be called by the main emulation engine. ***************************************************************************/ uint32_t pcw_state::screen_update_pcw(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { int x,y,b; unsigned short roller_ram_offs; unsigned char *roller_ram_ptr; int pen0,pen1; pen0 = 0; pen1 = 1; /* invert? */ if (m_vdu_video_control_register & (1<<7)) { /* yes */ pen1^=1; pen0^=1; } /* video enable? */ if ((m_vdu_video_control_register & (1<<6))!=0) { /* render top border */ rectangle rect(0, PCW_SCREEN_WIDTH, 0, PCW_BORDER_HEIGHT); bitmap.fill(pen0, rect); /* render bottom border */ rect.set(0, PCW_SCREEN_WIDTH, PCW_BORDER_HEIGHT + PCW_DISPLAY_HEIGHT, PCW_BORDER_HEIGHT + PCW_DISPLAY_HEIGHT + PCW_BORDER_HEIGHT); bitmap.fill(pen0, rect); /* offset to start in table */ roller_ram_offs = (m_roller_ram_offset<<1); for (y=0; y<256; y++) { int by; unsigned short line_data; unsigned char *line_ptr; x = PCW_BORDER_WIDTH; roller_ram_ptr = m_ram->pointer() + m_roller_ram_addr + roller_ram_offs; /* get line address */ /* b16-14 control which bank the line is to be found in, b13-3 the address in the bank (in 16-byte units), and b2-0 the offset. Thus a roller RAM address bbbxxxxxxxxxxxyyy indicates bank bbb, address 00xxxxxxxxxxx0yyy. */ line_data = ((unsigned char *)roller_ram_ptr)[0] | (((unsigned char *)roller_ram_ptr)[1]<<8); /* calculate address of pixel data */ line_ptr = m_ram->pointer() + ((line_data & 0x0e000)<<1) + ((line_data & 0x01ff8)<<1) + (line_data & 0x07); for (by=0; by<90; by++) { unsigned char byte; byte = line_ptr[0]; for (b=0; b<8; b++) { if (byte & 0x080) { pcw_plot_pixel(bitmap,x+b, y+PCW_BORDER_HEIGHT, pen1); } else { pcw_plot_pixel(bitmap,x+b, y+PCW_BORDER_HEIGHT, pen0); } byte = byte<<1; } x = x + 8; line_ptr = line_ptr+8; } /* update offset, wrap within 512 byte range */ roller_ram_offs+=2; roller_ram_offs&=511; } /* render border */ /* 8 pixels either side of display */ for (y=0; y<256; y++) { pcw_plot_pixel(bitmap, 0, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 1, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 2, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 3, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 4, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 5, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 6, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 7, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+0, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+1, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+2, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+3, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+4, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+5, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+6, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+7, y+PCW_BORDER_HEIGHT, pen0); } } else { /* not video - render whole lot in pen 0 */ rectangle rect(0, PCW_SCREEN_WIDTH, 0, PCW_SCREEN_HEIGHT); bitmap.fill(pen0, rect); } return 0; } uint32_t pcw_state::screen_update_pcw_printer(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { // printer output int32_t feed; rectangle rect(0, PCW_PRINTER_WIDTH - 1, 0, PCW_PRINTER_HEIGHT - 1); feed = -(m_paper_feed / 2); copyscrollbitmap(bitmap,*m_prn_output,0,nullptr,1,&feed,rect); bitmap.pix16(PCW_PRINTER_HEIGHT-1, m_printer_headpos) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-2, m_printer_headpos) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-3, m_printer_headpos) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-1, m_printer_headpos-1) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-2, m_printer_headpos-1) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-1, m_printer_headpos+1) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-2, m_printer_headpos+1) = 0; return 0; }
30.654255
224
0.660246
rjw57
ead3d66d94475c5d960d55fe1aeb92b8886dbad6
127
hpp
C++
KGE/Core/Audio/ComponentAudioClip.hpp
jkeywo/KGE
5ad2619a4e205dd549cdf638854db356a80694ea
[ "MIT" ]
1
2016-08-10T14:03:29.000Z
2016-08-10T14:03:29.000Z
KGE/Core/Audio/ComponentAudioClip.hpp
jkeywo/KGE
5ad2619a4e205dd549cdf638854db356a80694ea
[ "MIT" ]
null
null
null
KGE/Core/Audio/ComponentAudioClip.hpp
jkeywo/KGE
5ad2619a4e205dd549cdf638854db356a80694ea
[ "MIT" ]
null
null
null
#pragma once #include "Core/Components/Component.hpp" namespace KGE { class ComponentAudioClip : public Component { }; };
11.545455
44
0.732283
jkeywo
ead4598d77cfe0fbd446e38a2eafd58c6ec87e49
4,866
cc
C++
training/mr_em_map_adapter.cc
agesmundo/FasterCubePruning
f80150140b5273fd1eb0dfb34bdd789c4cbd35e6
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
1
2019-06-03T00:44:01.000Z
2019-06-03T00:44:01.000Z
training/mr_em_map_adapter.cc
jhclark/cdec
237ddc67ffa61da310e19710f902d4771dc323c2
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
null
null
null
training/mr_em_map_adapter.cc
jhclark/cdec
237ddc67ffa61da310e19710f902d4771dc323c2
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
1
2021-02-19T12:44:54.000Z
2021-02-19T12:44:54.000Z
#include <iostream> #include <fstream> #include <cassert> #include <cmath> #include <boost/utility.hpp> #include <boost/program_options.hpp> #include <boost/program_options/variables_map.hpp> #include "boost/tuple/tuple.hpp" #include "fdict.h" #include "sparse_vector.h" using namespace std; namespace po = boost::program_options; // useful for EM models parameterized by a bunch of multinomials // this converts event counts (returned from cdec as feature expectations) // into different keys and values (which are lists of all the events, // conditioned on the key) for summing and normalization by a reducer void InitCommandLine(int argc, char** argv, po::variables_map* conf) { po::options_description opts("Configuration options"); opts.add_options() ("buffer_size,b", po::value<int>()->default_value(1), "Buffer size (in # of counts) before emitting counts") ("format,f",po::value<string>()->default_value("b64"), "Encoding of the input (b64 or text)"); po::options_description clo("Command line options"); clo.add_options() ("config", po::value<string>(), "Configuration file") ("help,h", "Print this help message and exit"); po::options_description dconfig_options, dcmdline_options; dconfig_options.add(opts); dcmdline_options.add(opts).add(clo); po::store(parse_command_line(argc, argv, dcmdline_options), *conf); if (conf->count("config")) { ifstream config((*conf)["config"].as<string>().c_str()); po::store(po::parse_config_file(config, dconfig_options), *conf); } po::notify(*conf); if (conf->count("help")) { cerr << dcmdline_options << endl; exit(1); } } struct EventMapper { int Map(int fid) { int& cv = map_[fid]; if (!cv) { cv = GetConditioningVariable(fid); } return cv; } void Clear() { map_.clear(); } protected: virtual int GetConditioningVariable(int fid) const = 0; private: map<int, int> map_; }; struct LexAlignEventMapper : public EventMapper { protected: virtual int GetConditioningVariable(int fid) const { const string& str = FD::Convert(fid); size_t pos = str.rfind("_"); if (pos == string::npos || pos == 0 || pos >= str.size() - 1) { cerr << "Bad feature for EM adapter: " << str << endl; abort(); } return FD::Convert(str.substr(0, pos)); } }; int main(int argc, char** argv) { po::variables_map conf; InitCommandLine(argc, argv, &conf); const bool use_b64 = conf["format"].as<string>() == "b64"; const int buffer_size = conf["buffer_size"].as<int>(); const string s_obj = "**OBJ**"; // 0<TAB>**OBJ**=12.2;Feat1=2.3;Feat2=-0.2; // 0<TAB>**OBJ**=1.1;Feat1=1.0; EventMapper* event_mapper = new LexAlignEventMapper; map<int, SparseVector<double> > counts; size_t total = 0; while(cin) { string line; getline(cin, line); if (line.empty()) continue; int feat; double val; size_t i = line.find("\t"); assert(i != string::npos); ++i; SparseVector<double> g; double obj = 0; if (use_b64) { if (!B64::Decode(&obj, &g, &line[i], line.size() - i)) { cerr << "B64 decoder returned error, skipping!\n"; continue; } } else { // text encoding - your counts will not be accurate! while (i < line.size()) { size_t start = i; while (line[i] != '=' && i < line.size()) ++i; if (i == line.size()) { cerr << "FORMAT ERROR\n"; break; } string fname = line.substr(start, i - start); if (fname == s_obj) { feat = -1; } else { feat = FD::Convert(line.substr(start, i - start)); } ++i; start = i; while (line[i] != ';' && i < line.size()) ++i; if (i - start == 0) continue; val = atof(line.substr(start, i - start).c_str()); ++i; if (feat == -1) { obj = val; } else { g.set_value(feat, val); } } } //cerr << "OBJ: " << obj << endl; const SparseVector<double>& cg = g; for (SparseVector<double>::const_iterator it = cg.begin(); it != cg.end(); ++it) { const int cond_var = event_mapper->Map(it->first); SparseVector<double>& cond_counts = counts[cond_var]; int delta = cond_counts.size(); cond_counts.add_value(it->first, it->second); delta = cond_counts.size() - delta; total += delta; } if (total > buffer_size) { for (map<int, SparseVector<double> >::iterator it = counts.begin(); it != counts.end(); ++it) { const SparseVector<double>& cc = it->second; cout << FD::Convert(it->first) << '\t'; if (use_b64) { B64::Encode(0.0, cc, &cout); } else { abort(); } cout << endl; } cout << flush; total = 0; counts.clear(); } } return 0; }
30.223602
116
0.59104
agesmundo
ead6a6563593a425e9fc1fd361c2c6fc2abc5b05
1,404
cpp
C++
thirdparty/sfs2x/Bitswarm/BBox/BBEvent.cpp
godot-addons/godot-sfs2x
a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1
[ "MIT" ]
2
2020-05-14T07:48:32.000Z
2021-02-03T14:58:11.000Z
thirdparty/sfs2x/Bitswarm/BBox/BBEvent.cpp
godot-addons/godot-sfs2x
a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1
[ "MIT" ]
1
2020-05-28T16:39:20.000Z
2020-05-28T16:39:20.000Z
thirdparty/sfs2x/Bitswarm/BBox/BBEvent.cpp
godot-addons/godot-sfs2x
a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1
[ "MIT" ]
2
2018-07-07T20:15:00.000Z
2018-10-26T05:18:30.000Z
// =================================================================== // // Description // Contains the implementation of BBEvent // // Revision history // Date Description // 30-Nov-2012 First version // // =================================================================== #include "BBEvent.h" namespace Sfs2X { namespace Bitswarm { namespace BBox { boost::shared_ptr<string> BBEvent::CONNECT (new string("bb-connect")); boost::shared_ptr<string> BBEvent::DISCONNECT (new string("bb-disconnect")); boost::shared_ptr<string> BBEvent::DATA (new string("bb-data")); boost::shared_ptr<string> BBEvent::IO_ERROR (new string("bb-ioError")); boost::shared_ptr<string> BBEvent::SECURITY_ERROR (new string("bb-securityError")); // ------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------- BBEvent::BBEvent(boost::shared_ptr<string> type) : BaseEvent (type, boost::shared_ptr<map<string, boost::shared_ptr<void> > >()) { } // ------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------- BBEvent::BBEvent(boost::shared_ptr<string> type, boost::shared_ptr<map<string, boost::shared_ptr<void> > > arguments) : BaseEvent (type, arguments) { } } // namespace BBox } // namespace Bitswarm } // namespace Sfs2X
31.909091
117
0.504274
godot-addons
ead740e181fb132ccf2430f21f427346276b1b97
1,883
hpp
C++
include/IStreamSocket.hpp
lordio/insanity
7dfbf398fe08968f40a32280bf2b16cca2b476a1
[ "MIT" ]
1
2015-02-05T10:41:14.000Z
2015-02-05T10:41:14.000Z
include/IStreamSocket.hpp
lordio/insanity
7dfbf398fe08968f40a32280bf2b16cca2b476a1
[ "MIT" ]
1
2015-02-04T20:47:52.000Z
2015-02-05T07:43:05.000Z
include/IStreamSocket.hpp
lordio/insanity
7dfbf398fe08968f40a32280bf2b16cca2b476a1
[ "MIT" ]
null
null
null
#ifndef INSANITY_INTERFACE_STREAM_SOCKET #define INSANITY_INTERFACE_STREAM_SOCKET #include "Constants.hpp" #include "IObject.hpp" namespace Insanity { class IByteArray; class INSANITY_API IStreamSocket : public virtual IObject { public: //================================================= //Create a new StreamSocket // Attempts to connect to host, at port. // Will return an unconnected IStreamSocket if connection fails. //================================================= static IStreamSocket * Create(char const * host, u16 port); //================================================= //Communicate with remote peer. // Silently ignores request if unconnected. //================================================= virtual void Send(IByteArray const * arr) = 0; virtual void Receive(IByteArray * arr) = 0; //================================================= //Attempt to connect to host, at port. // Returns false if the connection fails, true otherwise. // Will Close() the socket if it is open. //================================================= virtual bool Connect(const char * host, u16 port) = 0; //================================================= //Stops communications on the socket. // Returns false if socket was already not open, true otherwise. //================================================= virtual bool Close() = 0; //================================================= //Returns false if the socket is not open, or if there is no pending data. // True otherwise. //================================================= virtual bool HasPendingData() const = 0; //================================================= //Returns true if the socket is connected to a server // false otherwise. //================================================= virtual bool IsConnected() const = 0; }; } #endif
34.236364
76
0.478492
lordio
ead785b9cb2a4cac33dff6d2858fa848750a70e0
344
cpp
C++
projects/client/input/haft/source/haft/Input_Configuration.cpp
silentorb/mythic-cpp
97319d158800d77e1a944c47c13523662bc07e08
[ "MIT" ]
null
null
null
projects/client/input/haft/source/haft/Input_Configuration.cpp
silentorb/mythic-cpp
97319d158800d77e1a944c47c13523662bc07e08
[ "MIT" ]
null
null
null
projects/client/input/haft/source/haft/Input_Configuration.cpp
silentorb/mythic-cpp
97319d158800d77e1a944c47c13523662bc07e08
[ "MIT" ]
null
null
null
#include "Input_Configuration.h" namespace haft { Device *Input_Configuration::get_device(const std::string name) const { for (auto &device: devices) { if (device->get_name() == name) return device.get(); } return nullptr; // throw runtime_error(string("Invalid device name ") + name + "."); } }
24.571429
74
0.613372
silentorb
ead7da1fbb8c0d130dd44346123a6ba87c889f8b
1,276
cc
C++
chrome/browser/commerce/coupons/coupon_service_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
chrome/browser/commerce/coupons/coupon_service_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
chrome/browser/commerce/coupons/coupon_service_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2021 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/commerce/coupons/coupon_service_factory.h" #include "chrome/browser/commerce/coupons/coupon_db.h" #include "chrome/browser/commerce/coupons/coupon_service.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "content/public/browser/storage_partition.h" // static CouponServiceFactory* CouponServiceFactory::GetInstance() { static base::NoDestructor<CouponServiceFactory> factory; return factory.get(); } // static CouponService* CouponServiceFactory::GetForProfile(Profile* profile) { return static_cast<CouponService*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } CouponServiceFactory::CouponServiceFactory() : BrowserContextKeyedServiceFactory( "CouponService", BrowserContextDependencyManager::GetInstance()) {} CouponServiceFactory::~CouponServiceFactory() = default; KeyedService* CouponServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { DCHECK(!context->IsOffTheRecord()); return new CouponService(std::make_unique<CouponDB>(context)); }
34.486486
80
0.78605
zealoussnow
eae6573fae791d2658baadcd206a819f238030ff
5,179
hxx
C++
main/sc/inc/hints.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sc/inc/hints.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sc/inc/hints.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 SC_HINTS_HXX #define SC_HINTS_HXX #include "global.hxx" #include "address.hxx" #include <svl/hint.hxx> // --------------------------------------------------------------------------- class ScPaintHint : public SfxHint { ScRange aRange; sal_uInt16 nParts; sal_Bool bPrint; // Flag, ob auch Druck/Vorschau betroffen ist ScPaintHint(); // disabled public: TYPEINFO(); ScPaintHint( const ScRange& rRng, sal_uInt16 nPaint = PAINT_ALL ); ~ScPaintHint(); void SetPrintFlag(sal_Bool bSet) { bPrint = bSet; } const ScRange& GetRange() const { return aRange; } SCCOL GetStartCol() const { return aRange.aStart.Col(); } SCROW GetStartRow() const { return aRange.aStart.Row(); } SCTAB GetStartTab() const { return aRange.aStart.Tab(); } SCCOL GetEndCol() const { return aRange.aEnd.Col(); } SCROW GetEndRow() const { return aRange.aEnd.Row(); } SCTAB GetEndTab() const { return aRange.aEnd.Tab(); } sal_uInt16 GetParts() const { return nParts; } sal_Bool GetPrintFlag() const { return bPrint; } }; class ScUpdateRefHint : public SfxHint { UpdateRefMode eUpdateRefMode; ScRange aRange; SCsCOL nDx; SCsROW nDy; SCsTAB nDz; public: TYPEINFO(); ScUpdateRefHint( UpdateRefMode eMode, const ScRange& rR, SCsCOL nX, SCsROW nY, SCsTAB nZ ); ~ScUpdateRefHint(); UpdateRefMode GetMode() const { return eUpdateRefMode; } const ScRange& GetRange() const { return aRange; } SCsCOL GetDx() const { return nDx; } SCsROW GetDy() const { return nDy; } SCsTAB GetDz() const { return nDz; } }; #define SC_POINTERCHANGED_NUMFMT 1 class ScPointerChangedHint : public SfxHint { sal_uInt16 nFlags; public: TYPEINFO(); //UNUSED2008-05 ScPointerChangedHint( sal_uInt16 nF ); ~ScPointerChangedHint(); sal_uInt16 GetFlags() const { return nFlags; } }; //! move ScLinkRefreshedHint to a different file? #define SC_LINKREFTYPE_NONE 0 #define SC_LINKREFTYPE_SHEET 1 #define SC_LINKREFTYPE_AREA 2 #define SC_LINKREFTYPE_DDE 3 class ScLinkRefreshedHint : public SfxHint { sal_uInt16 nLinkType; // SC_LINKREFTYPE_... String aUrl; // used for sheet links String aDdeAppl; // used for dde links: String aDdeTopic; String aDdeItem; sal_uInt8 nDdeMode; ScAddress aDestPos; // used to identify area links //! also use source data for area links? public: TYPEINFO(); ScLinkRefreshedHint(); ~ScLinkRefreshedHint(); void SetSheetLink( const String& rSourceUrl ); void SetDdeLink( const String& rA, const String& rT, const String& rI, sal_uInt8 nM ); void SetAreaLink( const ScAddress& rPos ); sal_uInt16 GetLinkType() const { return nLinkType; } const String& GetUrl() const { return aUrl; } const String& GetDdeAppl() const { return aDdeAppl; } const String& GetDdeTopic() const { return aDdeTopic; } const String& GetDdeItem() const { return aDdeItem; } sal_uInt8 GetDdeMode() const { return nDdeMode; } const ScAddress& GetDestPos() const { return aDestPos; } }; //! move ScAutoStyleHint to a different file? class ScAutoStyleHint : public SfxHint { ScRange aRange; String aStyle1; String aStyle2; sal_uLong nTimeout; public: TYPEINFO(); ScAutoStyleHint( const ScRange& rR, const String& rSt1, sal_uLong nT, const String& rSt2 ); ~ScAutoStyleHint(); const ScRange& GetRange() const { return aRange; } const String& GetStyle1() const { return aStyle1; } sal_uInt32 GetTimeout() const { return nTimeout; } const String& GetStyle2() const { return aStyle2; } }; class ScDBRangeRefreshedHint : public SfxHint { ScImportParam aParam; public: TYPEINFO(); ScDBRangeRefreshedHint( const ScImportParam& rP ); ~ScDBRangeRefreshedHint(); const ScImportParam& GetImportParam() const { return aParam; } }; class ScDataPilotModifiedHint : public SfxHint { String maName; public: TYPEINFO(); ScDataPilotModifiedHint( const String& rName ); ~ScDataPilotModifiedHint(); const String& GetName() const { return maName; } }; #endif
28.456044
89
0.659394
Grosskopf
eae87783473a79a689454e4b2011efe263c479f9
726
cpp
C++
Flinty/Flinty/src/fl/Core.cpp
TheCherno/AnimatedSpriteCompression
012dc267c59a7921defed868d235533afa630b6b
[ "Apache-2.0" ]
11
2016-08-10T18:16:29.000Z
2021-11-20T12:09:28.000Z
Flinty/Flinty/src/fl/Core.cpp
TheCherno/AnimatedSpriteCompression
012dc267c59a7921defed868d235533afa630b6b
[ "Apache-2.0" ]
null
null
null
Flinty/Flinty/src/fl/Core.cpp
TheCherno/AnimatedSpriteCompression
012dc267c59a7921defed868d235533afa630b6b
[ "Apache-2.0" ]
3
2019-05-16T15:37:34.000Z
2020-04-10T01:05:03.000Z
#include "Core.h" #include <iostream> #include "gl.h" #if defined(FL_PLATFORM_ANDROID) #include "platform/android/AndroidSystem.h" #endif namespace fl { #if defined(FL_PLATFORM_WINDOWS) void Init() { } #elif defined(FL_PLATFORM_ANDROID) void Init(void* env, void* mainView) { AndroidSystem::Init((JNIEnv*)env, (jobject)mainView); } #endif inline GLenum GLCheckError() { return glGetError(); } void GLClearError() { GLCheckError(); } bool GLLogCall(const char* function, const char* file, int line) { while (GLenum error = GLCheckError()) { std::cout << "[OpenGL Error] (" << error << "): " << function << " " << file << ":" << line << std::endl; return false; } return true; } }
15.446809
109
0.646006
TheCherno
eaea8280c75f22a6557e0fc2c795457539db1e20
2,044
hpp
C++
GazeEstimationCpp/PinholeCameraModel.hpp
dmikushin/RemoteEye
f467594e8d0246d7cc87bf843da1d09e105fcca7
[ "MIT" ]
9
2020-05-10T15:40:10.000Z
2022-01-26T19:58:55.000Z
GazeEstimationCpp/PinholeCameraModel.hpp
dmikushin/RemoteEye
f467594e8d0246d7cc87bf843da1d09e105fcca7
[ "MIT" ]
5
2020-08-08T22:22:51.000Z
2021-01-18T12:18:37.000Z
GazeEstimationCpp/PinholeCameraModel.hpp
dmikushin/RemoteEye
f467594e8d0246d7cc87bf843da1d09e105fcca7
[ "MIT" ]
2
2020-08-08T09:31:59.000Z
2020-12-14T05:49:33.000Z
#ifndef PINHOLE_CAMERA_MODEL_HPP_INCLUDED #define PINHOLE_CAMERA_MODEL_HPP_INCLUDED #include "MathTypes.hpp" namespace gazeestimation{ class PinholeCameraModel { private: Vec3 camera_angles; Mat3x3 actual_rotation_matrix; public: // camera intrinsic double principal_point_x; double principal_point_y; double pixel_size_cm_x; double pixel_size_cm_y; double effective_focal_length_cm; /// the position in WCS Vec3 position; PinholeCameraModel(): camera_angles(make_vec3(0,0,0)), actual_rotation_matrix(identity_matrix3x3()), principal_point_x(0), principal_point_y(0), pixel_size_cm_x(0), pixel_size_cm_y(0), effective_focal_length_cm(0) { } void set_camera_angles(double x, double y, double z) { camera_angles = make_vec3(x, y, z); actual_rotation_matrix = calculate_extrinsic_rotation_matrix(camera_angles[0], camera_angles[1], camera_angles[2]); } /// Returns the rotation matrix for this camera. Mat3x3 rotation_matrix() const { return actual_rotation_matrix; } /// Transforms the given vector in this camera's image coordinate system to /// the camera coordinate system Vec3 ics_to_ccs(const Vec2& pos) const { return make_vec3( (pos[0] - principal_point_x) * pixel_size_cm_x, (pos[1] - principal_point_y) * pixel_size_cm_y, -effective_focal_length_cm ); } Vec3 ccs_to_wcs(const Vec3& pos) const { return rotation_matrix() * pos + position; } Vec3 ics_to_wcs(const Vec2& pos) const { return ccs_to_wcs(ics_to_ccs(pos)); } double camera_angle_x() const { return camera_angles[0]; } double camera_angle_y() const { return camera_angles[1]; } double camera_angle_z() const { return camera_angles[2]; } void set_camera_angle_x(double angle) { set_camera_angles(angle, camera_angles[1], camera_angles[2]); } void set_camera_angle_y(double angle) { set_camera_angles(camera_angles[0], angle, camera_angles[2]); } void set_camera_angle_z(double angle) { set_camera_angles(camera_angles[0], camera_angles[1], angle); } }; } #endif
20.44
117
0.751957
dmikushin
eaeaee7f2c260beb4af190c606e353fb56f190f5
1,356
cpp
C++
IndependentSet.cpp
manoelstilpen/clique_problem
bf1c9711128b9173301d9ff4d1ad2f837f7f523e
[ "MIT" ]
null
null
null
IndependentSet.cpp
manoelstilpen/clique_problem
bf1c9711128b9173301d9ff4d1ad2f837f7f523e
[ "MIT" ]
null
null
null
IndependentSet.cpp
manoelstilpen/clique_problem
bf1c9711128b9173301d9ff4d1ad2f837f7f523e
[ "MIT" ]
1
2019-07-02T13:55:23.000Z
2019-07-02T13:55:23.000Z
#include "IndependentSet.hpp" IndependentSet::IndependentSet(){ definedGraph = false; } IndependentSet::IndependentSet(Graph _graph){ setGraph(_graph); } int IndependentSet::searchLargestIndependentSet(){ for(int k=0 ; k<graph.getNVertex() ; k++){ vector<int> vertex_list(graph.getNVertex()); iota(vertex_list.begin(), vertex_list.end(), 0); // crescent ordering sort(vertex_list.begin(), vertex_list.end(), [&](const int& a, const int& b){ return graph.getNAdjacencyOf(a) > graph.getNAdjacencyOf(b); }); for(int i=k ; i<vertex_list.size()+k ; i++){ int index; if(i >= vertex_list.size()) index = vertex_list[i-vertex_list.size()]; else index = vertex_list[i]; for(int j=0 ; j<vertex_list.size() ; j++){ } } /* for(int j=0 ; j<tam_list ; j++){ if(graph->complement[index][vertex_list[j]] == 1){ if(j < i) i--; remove_index(vertex_list,tam_list,j); graph->nAdjacencies[vertex_list[j]]--; tam_list--; j--; } } } if(tam_list > max){ max = tam_list; history = copy_array(vertex_list, tam_list); } free(vertex_list); */ } } void IndependentSet::setGraph(Graph _graph){ graph = _graph; }
22.229508
85
0.558997
manoelstilpen
eaeb3528d0718695e61d2dc99b3bd35a908a30d4
225
hpp
C++
include/LIEF/span.hpp
rafael-santiago/LIEF
f230094d5877dd63d40915dc944c53c2a4be5ed9
[ "Apache-2.0" ]
1
2022-02-26T00:28:52.000Z
2022-02-26T00:28:52.000Z
include/LIEF/span.hpp
rafael-santiago/LIEF
f230094d5877dd63d40915dc944c53c2a4be5ed9
[ "Apache-2.0" ]
null
null
null
include/LIEF/span.hpp
rafael-santiago/LIEF
f230094d5877dd63d40915dc944c53c2a4be5ed9
[ "Apache-2.0" ]
null
null
null
#ifndef LIEF_SPAN_H #define LIEF_SPAN_H #include <LIEF/third-party/span.hpp> namespace LIEF { template <typename ElementType, std::size_t Extent = tcb::dynamic_extent> using span = tcb::span<ElementType, Extent>; } #endif
18.75
73
0.764444
rafael-santiago
eaebe3caf007b66f13294eaa39c997be945f32c1
1,067
cc
C++
chrome/browser/locale_tests_uitest.cc
zachlatta/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
1
2021-09-24T22:49:10.000Z
2021-09-24T22:49:10.000Z
chrome/browser/locale_tests_uitest.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/locale_tests_uitest.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2006-2008 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/test/ui/ui_test.h" class LocaleTestsDa : public UITest { public: LocaleTestsDa() : UITest() { launch_arguments_.AppendSwitchWithValue(L"lang", L"da"); } }; class LocaleTestsHe : public UITest { public: LocaleTestsHe() : UITest() { launch_arguments_.AppendSwitchWithValue(L"lang", L"he"); } }; class LocaleTestsZhTw : public UITest { public: LocaleTestsZhTw() : UITest() { launch_arguments_.AppendSwitchWithValue(L"lang", L"zh-TW"); } }; #if defined(OS_WIN) || defined(OS_LINUX) // These 3 tests started failing between revisions 13115 and 13120. // See bug 9758. TEST_F(LocaleTestsDa, TestStart) { // Just making sure we can start/shutdown cleanly. } TEST_F(LocaleTestsHe, TestStart) { // Just making sure we can start/shutdown cleanly. } TEST_F(LocaleTestsZhTw, TestStart) { // Just making sure we can start/shutdown cleanly. } #endif
24.813953
73
0.719775
zachlatta
eaf0865ae2f420e0b3dd47bcee0fa3c845fbd082
953
cpp
C++
Ruminate/src/HelperFiles/a_funcs.cpp
Riku32/Ruminate
0855384c2abb24f2552688561ff90bd555ef3c07
[ "MIT" ]
null
null
null
Ruminate/src/HelperFiles/a_funcs.cpp
Riku32/Ruminate
0855384c2abb24f2552688561ff90bd555ef3c07
[ "MIT" ]
null
null
null
Ruminate/src/HelperFiles/a_funcs.cpp
Riku32/Ruminate
0855384c2abb24f2552688561ff90bd555ef3c07
[ "MIT" ]
null
null
null
#include "HelperFiles/a_funcs.hpp" //relu inline float Relu(float x) { return (x > 0) * x; } inline float ReluPrime(float x) { return x > 0; } //leaky relu inline float ReluLeaky(float x) { if (x < 0) { return x * A; } else { return x; } } inline float ReluLeakyPrime(float x) { if (x < 0) { return A; } else { return 1; } } //tanh inline float Tanh(float x) { return tanh(x); } inline float TanhPrime(float x) { return sinh(x) / cosh(x); } //sigmoid inline float Sigmoid(float x) { return 1 / (1 + exp(-x)); } inline float SigmoidPrime(float x) { return exp(-x) / std::pow(1 + exp(-x), 2); } //swish inline float Swish(float x) { return x * Sigmoid(x); } inline float SwishPrime(float x) { return (exp(x) * (exp(x) + x + 1)) / std::pow(exp(x) + 1, 2); }
12.878378
66
0.499475
Riku32
eaf608c4845378c97f1a955f5533efa1e5c2b962
8,845
cpp
C++
src/corder.cpp
Cetus-K/corder
cd635c3bf49f578952d65393270a9a980841299e
[ "MIT" ]
null
null
null
src/corder.cpp
Cetus-K/corder
cd635c3bf49f578952d65393270a9a980841299e
[ "MIT" ]
null
null
null
src/corder.cpp
Cetus-K/corder
cd635c3bf49f578952d65393270a9a980841299e
[ "MIT" ]
null
null
null
#include "corder.h" // corder destructor corder::~corder() { vector < int > ().swap(l); vector < int > ().swap(item); vector < int > ().swap(sitem); vector < vector < int > > ().swap(stypeindex); vector < vector < int > > ().swap(stypelist); vector < string > ().swap(mode); vector < string > ().swap(type); vector < vector < string > > ().swap(stype); stypelist.clear(); } // the type of i-th index ion int corder::mytype ( int idx ) { int itype,cnt = 0; for ( itype=0; itype<ntypes; itype++ ) { cnt += item[itype]; if ( idx < cnt ) break; } return itype; } // the address that start itype ion indices // range: [ mystart(a), mystart(a)+item[a] ) int corder::mystart ( int itype ) { int cnt = 0; for ( int a=0; a<itype; a++ ) cnt += item[a]; return cnt; } // update double corder::update ( double prev, double add ) { return ( (double)(itr-f0)/df*prev+add )/((double)(itr-f0)/df+1.0); } // main control int main(int argc, char* argv[]){ // declare int rank,nmpi; // mpi rank ans its size double scale; // lattice scale double beg,time,prog; // progress map < string,bool > mode; // calc mode vec cfg(3); // vector and matrix class ifstream ifs; // fstream istringstream iss; string str; corder co; // corder basis class // set corder parameter co.set_param(); // calculation mode mode["gofr"] = false; // g(r),gab(r) mode["sofq"] = false; // s(q),sab(q) mode["dfc"] = false; // msd,msda,<v>,<va> mode["lboo"] = false; // ql,wl,qlab,wlab mode["bacf"] = false; // gl(r),glabab(r) mode["pofqw"] = false; // p(ql),p(wl),p(qlab),p(wlab) mode["bofree"] = false; // f,fl,fll,fab,flab,fllab mode["povoro"] = false; // dump trajectory as pov-ray format mode["csform"] = false; // counting each sharing formations // dependence parameter mode["covoro"] = false; // engine for lboo/bacf/pofqw/bofree/voro mode["coqhull"] = false; // engine for ... mode["instant"] = false; // instantsneous calculation for write out for ( int i=0; i<(int)co.mode.size(); i++ ) mode[co.mode[i]] = true; // dependency mode["sofq"] = mode["sofq"] and mode["gofr"]; mode["covoro"] = mode["lboo"] or mode["bacf"] or mode["pofqw"] or mode["bofree"] or mode["csform"] or mode["povoro"] or mode["csform"]; mode["instant"] = !( mode["bacf"] or mode["pofqw"] or mode["bofree"] or mode["csform"] ); // check read if ( co.f1 < co.f0 ) co.f1 = grep_c("XDATCAR","Direct"); // memory allocation: co.config.resize(co.nions); for ( int i=0; i<co.nions; i++ ) co.config[i].resize(3); // initialize // each class related to mode // create copy constructor by refference handling gofr co_gofr(co); co_gofr.init(); sofq co_sofq(co); co_sofq.init(); dfc co_dfc(co); co_dfc.init(); covoro co_covoro(co); co_covoro.init(); lboo co_lboo(co,co_covoro); co_lboo.init(); bacf co_bacf(co,co_covoro); co_bacf.init(); pofqw co_pofqw(co,co_covoro); co_pofqw.init(); bofree co_bofree(co,co_covoro); co_bofree.init(); povoro co_povoro(co,co_covoro); coqhull co_coqhull(co); co_coqhull.init(); coqhull co_cv_coqhull(co,co_covoro); co_cv_coqhull.init(); csform co_csform(co,co_covoro,co_cv_coqhull); co_csform.init(); // MPI environment MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD,&nmpi); MPI_Barrier(MPI_COMM_WORLD); beg = prog = MPI_Wtime(); // read XDATCAR and skip initial lines without axis at latdyn = false ifs.open("XDATCAR",ios::in); if ( !co.latdyn ) for ( int i=0; i<7; i++ ) getline(ifs,str); // dump system information if ( rank == 0 ) { co.info(); cout << endl; cout << "------------------" << endl; cout << " Progress" << endl; cout << "------------------" << endl; cout << endl; cout << "Iteration ( completion [%] ) : 1 dump-step cpu time ( total ) [s]" << endl; cout << "-----------------------------------------------------------------" << endl; } MPI_Barrier(MPI_COMM_WORLD); // iterator init co.itr = 0; while ( co.itr<=co.f1 && !ifs.eof() ) { co.itr ++; if ( ( co.f0<=co.itr && co.itr<=co.f1 && (co.itr-co.f0)%co.df==0 ) || co.itr==co.f1 ) { // if lattice dynamics is true // read lattice system if ( co.latdyn ) { // label getline(ifs,str); // scale getline(ifs,str); iss.str(str); iss >> scale; iss.clear(); // lattice vector >> transform matrix getline(ifs,str); iss.str(str); iss >> co.a1(0) >> co.a1(1) >> co.a1(2); iss.clear(); co.a1 *= scale; getline(ifs,str); iss.str(str); iss >> co.a2(0) >> co.a2(1) >> co.a2(2); iss.clear(); co.a2 *= scale; getline(ifs,str); iss.str(str); iss >> co.a3(0) >> co.a3(1) >> co.a3(2); iss.clear(); co.a3 *= scale; for ( int i=0; i<3; i++ ) co.latmat(i,0) = co.a1(i); for ( int i=0; i<3; i++ ) co.latmat(i,1) = co.a2(i); for ( int i=0; i<3; i++ ) co.latmat(i,2) = co.a3(i); // type ands item for ( int i=0; i<2; i++ ) getline(ifs,str); } // axis line getline(ifs,str); // configuration for ( int i=0; i<co.nions; i++ ) { getline(ifs,str); iss.str(str); for ( int j=0; j<3; j++ ) iss >> cfg(j); co.config[i] = co.latmat*cfg; iss.clear(); } MPI_Barrier(MPI_COMM_WORLD); // update mode if ( mode["gofr"] ) { co_gofr.set(co); co_gofr.update(rank,nmpi); } MPI_Barrier(MPI_COMM_WORLD); // not using so far // if ( mode["sofq"] ) { // co_sofq.set(co); // MPI_Barrier(MPI_COMM_WORLD); // } if ( mode["dfc"] && rank == 0 ) { co_dfc.set(co); co_dfc.update(); } MPI_Barrier(MPI_COMM_WORLD); if ( mode["covoro"] && !mode["instant"] ) { co_covoro.set(co); co_covoro.get(); for ( int a=0; a<co.ntypes; a++ ) { for ( int b=0; b<co.ntypes; b++ ) { co_covoro.pget(a,b); } } for ( int spa=0; spa<co.nstypes; spa++ ) { for ( int spb=0; spb<co.nstypes; spb++ ) { co_covoro.spget(spa,spb); } } } MPI_Barrier(MPI_COMM_WORLD); // not using so far // if ( mode["lboo"] && rank == 0 ) { // co_lboo.set(co,co_covoro); // MPI_Barrier(MPI_COMM_WORLD); // } if ( mode["bacf"] ) { co_bacf.set(co,co_covoro); co_bacf.update(rank,nmpi); } MPI_Barrier(MPI_COMM_WORLD); if ( mode["pofqw"] && rank == 0 ) { co_pofqw.set(co,co_covoro); co_pofqw.update(); } MPI_Barrier(MPI_COMM_WORLD); if ( mode["bofree"] && ( (co.itr-co.f0) % (co.df*co.dump) == 0 || co.itr==co.f1 ) ) { co_bofree.set(co,co_covoro); co_bofree.update(rank,nmpi); } MPI_Barrier(MPI_COMM_WORLD); if ( mode["csform"] ) { co_cv_coqhull.set(co,co_covoro); co_csform.get(); co_csform.pget(); co_csform.spget(); co_csform.update(rank,nmpi); } MPI_Barrier(MPI_COMM_WORLD); // write out if ( ( (co.itr-co.f0) % (co.df*co.dump) == 0 || co.itr==co.f1 ) && rank == 0 ) { // write out if ( mode["gofr"] ) co_gofr.write("gofr"); if ( mode["sofq"] ) { co_sofq.set(co); co_sofq.write("sofq",&co_gofr); } if ( mode["dfc"] ) co_dfc.write("dfc"); if ( mode["lboo"] ) { if ( mode["covoro"] && mode["instant"] ) { co_covoro.set(co); co_covoro.get(); for ( int a=0; a<co.ntypes; a++ ) { for ( int b=0; b<co.ntypes; b++ ) { co_covoro.pget(a,b); } } for ( int spa=0; spa<co.nstypes; spa++ ) { for ( int spb=0; spb<co.nstypes; spb++ ) { co_covoro.spget(spa,spb); } } } co_lboo.set(co,co_covoro); co_lboo.write("lboo"); } if ( mode["bacf"] ) co_bacf.write("bacf"); if ( mode["pofqw"] ) co_pofqw.write("pofqw"); if ( mode["bofree"] ) co_bofree.write("bofree"); if ( mode["povoro"] ) { if ( mode["covoro"] && mode["instant"] ) { co_covoro.set(co); co_covoro.get(); for ( int a=0; a<co.ntypes; a++ ) { for ( int b=0; b<co.ntypes; b++ ) { co_covoro.pget(a,b); } } for ( int spa=0; spa<co.nstypes; spa++ ) { for ( int spb=0; spb<co.nstypes; spb++ ) { co_covoro.spget(spa,spb); } } } co_povoro.set(co,co_covoro); co_povoro.write("povoro"); for ( int a=0; a<co.ntypes; a++ ) { for ( int b=0; b<co.ntypes; b++ ) { co_povoro.pwrite("povoro",a,b); } } } if ( mode["csform"] ) { co_csform.write("csform"); } // dump progress time = MPI_Wtime(); cout << co.itr << " ( " << (double)(co.itr-co.f0+1)/(double)(co.f1-co.f0+1)*100.0 << " )"; cout << " : " << time-prog << " ( " << time-beg << " )" << endl; prog = time; } MPI_Barrier(MPI_COMM_WORLD); } else { // skip if ( co.latdyn ) for ( int i=0; i<7; i++ ) getline(ifs,str); getline(ifs,str); // axis for ( int i=0; i<co.nions; i++ ) getline(ifs,str); } } MPI_Barrier(MPI_COMM_WORLD); ifs.close(); MPI_Finalize(); // free mode.clear(); return 0; }
28.905229
136
0.5645
Cetus-K
46aeb29ba723d04d05eb80ed696f5532ce9ed1c5
767
cpp
C++
intermediate/funciones/vectorAddFunctions.cpp
eduardorasgado/CppZerotoAdvance2018
909cc0f0e1521fd9ca83795bf84cbb9f725d9d4f
[ "MIT" ]
1
2019-06-20T17:51:10.000Z
2019-06-20T17:51:10.000Z
intermediate/funciones/vectorAddFunctions.cpp
eduardorasgado/CppZerotoAdvance2018
909cc0f0e1521fd9ca83795bf84cbb9f725d9d4f
[ "MIT" ]
2
2018-10-01T08:14:01.000Z
2018-10-06T05:27:26.000Z
intermediate/funciones/vectorAddFunctions.cpp
eduardorasgado/CppZerotoAdvance2018
909cc0f0e1521fd9ca83795bf84cbb9f725d9d4f
[ "MIT" ]
1
2018-10-05T10:54:10.000Z
2018-10-05T10:54:10.000Z
#include <iostream> using namespace std; int suma(int vector1[], int N); void dataRequest(); void showVector(); int N, vector[100]; int main(int argc, char** argv) { // pidiendo los datos al usuario dataRequest(); showVector(); int addition = suma(vector, N); cout << "La suma de todos los numeros del vector es: " << addition << endl; return 0; } int suma(int vector1[], int N) { int addition = 0; for(int i = 0;i < N;i++) addition += vector[i]; return addition; } void dataRequest() { cout << "De que tamaño es su vector: ", cin >> N; for(int i = 0;i < N;i++) cout << "vector[" << i << "]: ", cin >> vector[i]; cout << endl; } void showVector() { for(int i = 0;i < N;i++) cout << "vector[" << i << "]: " << vector[i] << endl; cout << endl; }
18.707317
79
0.591917
eduardorasgado
46b1ee6ba3c748a62174ce31a4ffc4613f29cef5
13,087
cpp
C++
fileAudioEncoder.cpp
rzumer/BeatFinder
ef1c4e9f48c8524d0980d650d58e66ec75afa13a
[ "MIT" ]
5
2019-02-18T01:17:27.000Z
2020-02-17T01:50:11.000Z
fileAudioEncoder.cpp
rzumer/BeatFinder
ef1c4e9f48c8524d0980d650d58e66ec75afa13a
[ "MIT" ]
null
null
null
fileAudioEncoder.cpp
rzumer/BeatFinder
ef1c4e9f48c8524d0980d650d58e66ec75afa13a
[ "MIT" ]
1
2019-02-22T01:32:20.000Z
2019-02-22T01:32:20.000Z
#pragma comment (lib, "avfilter.lib") #pragma comment (lib, "avformat.lib") #pragma comment (lib, "avcodec.lib") #pragma comment (lib, "avutil.lib") #include "fileAudioEncoder.h"; using namespace std; void fileAudioEncoder::cleanUp() { if (this->codecContext) { avcodec_close(this->codecContext); avcodec_free_context(&this->codecContext); } // Causes access exceptions /*if (this->ioContext) { avio_close(this->ioContext); avio_context_free(&this->ioContext); } if (this->formatContext) { avformat_free_context(this->formatContext); }*/ if (this->filterGraph) { avfilter_free(this->filterSource); avfilter_free(this->filterSink); avfilter_graph_free(&filterGraph); } if (this->frame) { av_frame_free(&this->frame); } if (this->packet) { av_packet_free(&this->packet); } } int fileAudioEncoder::encodeFrame(AVFrame *frame) { this->frame = frame; int gotPacket = -1; int gotFrame = -1; if (!(this->packet = av_packet_alloc())) { cout << "Error allocating packet memory." << endl; return -1; } if (this->frame) { this->frame->format = this->codecParameters->format; this->frame->channels = this->codecParameters->channels; this->frame->channel_layout = this->codecParameters->channel_layout; this->frame->sample_rate = this->codecParameters->sample_rate; if (this->filterGraph) { if (av_buffersrc_add_frame(this->filterSource, this->frame) < 0) { // Need more frames. return 0; } gotFrame = av_buffersink_get_frame(this->filterSink, this->frame); if (gotFrame == AVERROR(EAGAIN)) { // Need more frames. return 0; } if (!avcodec_is_open(this->codecContext)) { this->codecContext->sample_fmt = (AVSampleFormat)this->frame->format; this->codecContext->channel_layout = this->frame->channel_layout; this->codecContext->channels = this->frame->channels; this->codecContext->sample_rate = this->frame->sample_rate; if (avcodec_open2(this->codecContext, this->codec, NULL) < 0) { cout << "Error opening the codec." << endl; this->cleanUp(); return -1; } #ifdef _DEBUG char channelLayout[64]; av_get_channel_layout_string(channelLayout, sizeof(channelLayout), 0, this->codecContext->channel_layout); cout << "Negotiated channel layout: " << channelLayout << endl; cout << "Negotiated sample format: " << av_get_sample_fmt_name(this->codecContext->sample_fmt) << endl; cout << "Negotiated sample rate: " << this->codecContext->sample_rate << endl; #endif } } gotFrame = avcodec_send_frame(this->codecContext, this->frame); if (gotFrame != 0) { cout << "Error sending frame to encoder." << endl; return -1; } } gotPacket = avcodec_receive_packet(this->codecContext, this->packet); if (gotPacket == 0) { return 0; } else if (gotPacket == AVERROR(EAGAIN)) { // Need more frames. return 0; } else if (gotPacket = AVERROR_EOF) { this->finished = 1; return 1; } else { #if _DEBUG char errbuf[AV_ERROR_MAX_STRING_SIZE]; char *err = av_make_error_string(errbuf, AV_ERROR_MAX_STRING_SIZE, gotPacket); cout << err << endl; #endif cout << "Error receiving decoded frame." << endl; return -1; } } int fileAudioEncoder::init(const char *filePath, const vector<AVCodecID> *codecIDs, AVCodecParameters *parameters) { this->codecID = AV_CODEC_ID_NONE; this->finished = 0; this->codecParameters = parameters; this->frame = NULL; this->packet = av_packet_alloc(); this->filterGraph = NULL; this->filterSource = NULL; this->filterSink = NULL; // Initialize output format context if an output file name was provided. if (filePath) { if (avio_open2(&this->ioContext, filePath, AVIO_FLAG_WRITE, NULL, NULL) < 0) { cout << "Error opening file for writing." << endl; this->cleanUp(); return -1; } const size_t fileExtensionLength = 16; const size_t fileNameLength = 1024 - fileExtensionLength; char *fileName = new char[fileNameLength + fileExtensionLength]; char *fileExtension = new char[fileExtensionLength]; _splitpath_s(filePath, NULL, 0, NULL, 0, fileName, fileNameLength, fileExtension, fileExtensionLength); sprintf(fileName + strlen(fileName), "%s", fileExtension); if (avformat_alloc_output_context2(&this->formatContext, NULL, NULL, fileName) < 0) { cout << "Error allocating output format context." << endl; this->cleanUp(); return -1; } this->formatContext->pb = ioContext; for (int i = 0; i < codecIDs->size(); i++) { if (avformat_query_codec(this->formatContext->oformat, codecIDs->at(i), FF_COMPLIANCE_NORMAL)) { #ifdef _DEBUG cout << "Negotiated codec: " << avcodec_get_name(codecIDs->at(i)) << endl; #endif this->codecID = codecIDs->at(i); break; } } if (this->codecID == AV_CODEC_ID_NONE) { cout << "Unsupported codecs offered for the given output format." << endl; this->cleanUp(); return -1; } this->formatContext->oformat->audio_codec = this->codecID; this->codec = avcodec_find_encoder(this->codecID); this->codecContext = avcodec_alloc_context3(this->codec); if (this->formatContext->oformat->flags & AVFMT_GLOBALHEADER) { this->formatContext->flags |= CODEC_FLAG_GLOBAL_HEADER; } if (!(this->stream = avformat_new_stream(this->formatContext, this->codec))) { cout << "Error allocating output stream." << endl; this->cleanUp(); return -1; } this->codecContext = avcodec_alloc_context3(this->codec); this->codecContext->bit_rate = parameters->bit_rate; this->codecContext->channels = parameters->channels; this->codecContext->channel_layout = parameters->channel_layout; this->codecContext->sample_fmt = (AVSampleFormat)parameters->format; this->codecContext->sample_rate = parameters->sample_rate; avcodec_parameters_from_context(this->stream->codecpar, this->codecContext); if (avformat_init_output(this->formatContext, NULL) < 0) { cout << "Error initializing output format context." << endl; this->cleanUp(); return -1; } } else { this->codecID = codecIDs->at(0); this->codec = avcodec_find_encoder(this->codecID); this->codecContext = avcodec_alloc_context3(this->codec); this->codecContext->bit_rate = parameters->bit_rate; this->codecContext->channels = parameters->channels; this->codecContext->channel_layout = parameters->channel_layout; this->codecContext->sample_fmt = (AVSampleFormat)parameters->format; this->codecContext->sample_rate = parameters->sample_rate; } if (!codec) { cout << "Error finding encoder." << endl; this->cleanUp(); return -1; } const enum AVSampleFormat *format = this->codec->sample_fmts; AVSampleFormat requestedFormat = (AVSampleFormat)parameters->format; while (*format != AV_SAMPLE_FMT_NONE) { if (*format == requestedFormat) { this->codecContext->sample_fmt = requestedFormat; break; } format++; } // If no viable codec was found for encoding, set up a filtergraph for format conversion. if (*format == AV_SAMPLE_FMT_NONE) { avfilter_register_all(); AVFilterGraph *filterGraph = avfilter_graph_alloc(); if (!filterGraph) { cout << "Error allocating memory for the filter graph." << endl; this->cleanUp(); return -1; } AVFilter *bufferFilter = avfilter_get_by_name("abuffer"); AVFilter *formatFilter = avfilter_get_by_name("aformat"); AVFilter *bufferSinkFilter = avfilter_get_by_name("abuffersink"); if (!bufferFilter || !formatFilter || !bufferSinkFilter) { cout << "Error retrieving filter." << endl; this->cleanUp(); return -1; } AVFilterContext *bufferContext = avfilter_graph_alloc_filter(filterGraph, bufferFilter, "abuffer"); AVFilterContext *formatContext = avfilter_graph_alloc_filter(filterGraph, formatFilter, "aformat"); AVFilterContext *bufferSinkContext = avfilter_graph_alloc_filter(filterGraph, bufferSinkFilter, "abuffersink"); if (!bufferContext || !formatContext || !bufferSinkContext) { cout << "Error allocating format filter context." << endl; this->cleanUp(); return -1; } char channelLayout[64]; av_get_channel_layout_string(channelLayout, sizeof(channelLayout), 0, this->codecParameters->channel_layout); av_opt_set(bufferContext, "channel_layout", channelLayout, AV_OPT_SEARCH_CHILDREN); av_opt_set_sample_fmt(bufferContext, "sample_fmt", (AVSampleFormat)this->codecParameters->format, AV_OPT_SEARCH_CHILDREN); av_opt_set_q(bufferContext, "time_base", AVRational{ 1, this->codecParameters->sample_rate }, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(bufferContext, "sample_rate", this->codecParameters->sample_rate, AV_OPT_SEARCH_CHILDREN); if (avfilter_init_str(bufferContext, NULL)) { cout << "Error initializing the buffer filter." << endl; this->cleanUp(); return -1; } char channelLayouts[3072] = {}; const uint64_t *layout = this->codec->channel_layouts; if (layout) { while (*layout) { av_get_channel_layout_string(channelLayout, sizeof(channelLayout), 0, *layout); sprintf(channelLayouts + strlen(channelLayouts), "%s|", channelLayout); layout++; } // Erase the last separator. sprintf(channelLayouts + strlen(channelLayouts) - 1, "\0"); } else { av_get_channel_layout_string(channelLayout, sizeof(channelLayout), 0, this->codecParameters->channel_layout); sprintf(channelLayouts, "%s", channelLayout); } #ifdef _DEBUG cout << "Negotiated channel layouts: " << channelLayouts << endl; #endif char sampleFormats[3072] = {}; const enum AVSampleFormat *sampleFormat = this->codec->sample_fmts; if (sampleFormat) { while (*sampleFormat != -1) { sprintf(sampleFormats + strlen(sampleFormats), "%s|", av_get_sample_fmt_name(*sampleFormat)); sampleFormat++; } // Erase the last separator. sprintf(sampleFormats + strlen(sampleFormats) - 1, "\0"); } else { sprintf(sampleFormats, "%s", av_get_sample_fmt_name((AVSampleFormat)this->codecParameters->format)); } #ifdef _DEBUG cout << "Negotiated sample formats: " << sampleFormats << endl; #endif char sampleRates[3072] = {}; const int *sampleRate = this->codec->supported_samplerates; if (sampleRate) { while (*sampleRate) { sprintf(sampleRates + strlen(sampleRates), "%i|", *sampleRate); sampleRate++; } // Erase the last separator. sprintf(sampleRates + strlen(sampleRates) - 1, "\0"); } else { sprintf(sampleRates, "%i", this->codecParameters->sample_rate); } #ifdef _DEBUG cout << "Negotiated sample rates: " << sampleRates << endl; #endif av_opt_set(formatContext, "channel_layouts", channelLayouts, AV_OPT_SEARCH_CHILDREN); av_opt_set(formatContext, "sample_fmts", sampleFormats, AV_OPT_SEARCH_CHILDREN); av_opt_set_q(formatContext, "time_base", AVRational{ 1, this->codecParameters->sample_rate }, AV_OPT_SEARCH_CHILDREN); av_opt_set(formatContext, "sample_rates", sampleRates, AV_OPT_SEARCH_CHILDREN); if (avfilter_init_str(formatContext, NULL)) { cout << "Error initializing the format filter." << endl; this->cleanUp(); return -1; } if (avfilter_init_str(bufferSinkContext, NULL)) { cout << "Error initializing the buffer sink filter." << endl; this->cleanUp(); return -1; } if (avfilter_link(bufferContext, 0, formatContext, 0) < 0 || avfilter_link(formatContext, 0, bufferSinkContext, 0) < 0) { cout << "Error connecting filters." << endl; this->cleanUp(); return -1; } if (avfilter_graph_config(filterGraph, NULL) < 0) { cout << "Error configuring filter graph." << endl; this->cleanUp(); return -1; } this->filterGraph = filterGraph; this->filterSource = bufferContext; this->filterSink = bufferSinkContext; } else { if (avcodec_open2(this->codecContext, this->codec, NULL) < 0) { cout << "Error opening the codec." << endl; this->cleanUp(); return -1; } } return 0; } int fileAudioEncoder::writeHeader() { if (!avcodec_is_open(this->codecContext)) { cout << "Codec context is closed." << endl; return -1; } if (avformat_write_header(this->formatContext, NULL) < 0) { cout << "Error writing output file header." << endl; return -1; } return 0; } int fileAudioEncoder::writeEncodedPacket(AVPacket *toWrite) { if (!avcodec_is_open(this->codecContext)) { cout << "Codec context is closed." << endl; return -1; } int result = av_interleaved_write_frame(this->formatContext, toWrite); if (result < 0) { cout << "Error writing encoded packet." << endl; return -1; } return result; } int fileAudioEncoder::writeTrailer() { if (!avcodec_is_open(this->codecContext)) { cout << "Codec context is closed." << endl; return -1; } if (av_write_trailer(this->formatContext) < 0) { cout << "Error writing output file trailer." << endl; return -1; } return 0; } AVPacket *fileAudioEncoder::getEncodedPacket(AVFrame *toEncode) { if (!finished) { int state = this->encodeFrame(toEncode); if (state != 0) { this->cleanUp(); } if (state >= 0) { return this->packet; } } return NULL; }
25.41165
124
0.693818
rzumer
46b43bc1bab7a5347fc5971471ee38be4705587b
1,072
cc
C++
Fireworks/Core/src/FWParameterizable.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
Fireworks/Core/src/FWParameterizable.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
Fireworks/Core/src/FWParameterizable.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
// -*- C++ -*- // // Package: Core // Class : FWParameterizable // // Implementation: // <Notes on implementation> // // Original Author: Chris Jones // Created: Sat Feb 23 13:36:27 EST 2008 // // system include files // user include files #include "Fireworks/Core/interface/FWParameterizable.h" // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // FWParameterizable::FWParameterizable() { } // FWParameterizable::FWParameterizable(const FWParameterizable& rhs) // { // // do actual copying here; // } FWParameterizable::~FWParameterizable() { } // // assignment operators // // const FWParameterizable& FWParameterizable::operator=(const FWParameterizable& rhs) // { // //An exception safe implementation is // FWParameterizable temp(rhs); // swap(rhs); // // return *this; // } // // member functions // void FWParameterizable::add(FWParameterBase* iParam) { m_parameters.push_back(iParam); } // // const member functions // // // static member functions //
15.098592
86
0.66791
nistefan
46b5d3784f9e433cd01c0fbe1309174e2bf29a04
2,093
cc
C++
src/ui/scenic/lib/gfx/tests/has_renderable_content_visitor_unittest.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
src/ui/scenic/lib/gfx/tests/has_renderable_content_visitor_unittest.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
1
2022-01-14T23:38:40.000Z
2022-01-14T23:38:40.000Z
src/ui/scenic/lib/gfx/tests/has_renderable_content_visitor_unittest.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
4
2020-12-28T17:04:45.000Z
2022-03-12T03:20:44.000Z
// Copyright 2020 The Fuchsia 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 "src/ui/scenic/lib/gfx/resources/has_renderable_content_visitor.h" #include <lib/ui/scenic/cpp/commands.h> #include <gtest/gtest.h> #include "src/ui/scenic/lib/gfx/resources/camera.h" #include "src/ui/scenic/lib/gfx/resources/compositor/layer.h" #include "src/ui/scenic/lib/gfx/resources/material.h" #include "src/ui/scenic/lib/gfx/resources/nodes/entity_node.h" #include "src/ui/scenic/lib/gfx/resources/nodes/scene.h" #include "src/ui/scenic/lib/gfx/resources/nodes/shape_node.h" #include "src/ui/scenic/lib/gfx/resources/renderers/renderer.h" #include "src/ui/scenic/lib/gfx/tests/session_test.h" namespace scenic_impl::gfx::test { using HasRenderableContentUnittest = SessionTest; TEST_F(HasRenderableContentUnittest, ReturnsTrueForShapeNodeWithMaterial) { HasRenderableContentVisitor visitor; ResourceId next_id = 1; auto layer = fxl::MakeRefCounted<Layer>(session(), session()->id(), next_id++); auto renderer = fxl::MakeRefCounted<Renderer>(session(), session()->id(), next_id++); layer->SetRenderer(renderer); auto scene = fxl::MakeRefCounted<Scene>(session(), session()->id(), next_id++, fxl::WeakPtr<ViewTreeUpdater>(), event_reporter()->GetWeakPtr()); auto camera = fxl::MakeRefCounted<Camera>(session(), session()->id(), next_id++, scene); renderer->SetCamera(camera); auto node = fxl::MakeRefCounted<EntityNode>(session(), session()->id(), next_id++); scene->AddChild(node, error_reporter()); auto shape_node = fxl::MakeRefCounted<ShapeNode>(session(), session()->id(), next_id++); node->AddChild(shape_node, error_reporter()); visitor.Visit(layer.get()); EXPECT_FALSE(visitor.HasRenderableContent()); auto material = fxl::MakeRefCounted<Material>(session(), next_id++); shape_node->SetMaterial(material); visitor.Visit(layer.get()); EXPECT_TRUE(visitor.HasRenderableContent()); } } // namespace scenic_impl::gfx::test
40.25
98
0.731964
casey
46bf4a0966c2e91a134128a667d39e6c9919746f
8,978
cpp
C++
src/terark/io/MemStream.cpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
44
2020-12-21T05:14:38.000Z
2022-03-15T11:27:32.000Z
src/terark/io/MemStream.cpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
2
2020-12-28T10:42:03.000Z
2021-05-21T07:22:47.000Z
src/terark/io/MemStream.cpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
21
2020-12-22T09:40:16.000Z
2021-12-07T18:16:00.000Z
/* vim: set tabstop=4 : */ #include "MemStream.hpp" #include <stdlib.h> #include <algorithm> #include <stdexcept> #include <typeinfo> #include <errno.h> #if defined(_MSC_VER) # include <intrin.h> #pragma intrinsic(_BitScanReverse) //#pragma intrinsic(_BitScanReverse64) #endif #include <boost/predef/other/endian.h> #include <terark/num_to_str.hpp> #include <stdarg.h> #include "var_int.hpp" namespace terark { //void MemIO_Base::skip(ptrdiff_t diff) void throw_EndOfFile(const char* func, size_t want, size_t available) { string_appender<> oss; oss << "in " << func << ", want=" << want << ", available=" << available // << ", tell=" << tell() << ", size=" << size() ; throw EndOfFileException(oss.str().c_str()); } void throw_OutOfSpace(const char* func, size_t want, size_t available) { string_appender<> oss; oss << "in " << func << ", want=" << want << ", available=" << available // << ", tell=" << tell() << ", size=" << size() ; throw OutOfSpaceException(oss.str().c_str()); } void MemIO::throw_EndOfFile(const char* func, size_t want) { terark::throw_EndOfFile(func, want, remain()); } void MemIO::throw_OutOfSpace(const char* func, size_t want) { terark::throw_OutOfSpace(func, want, remain()); } ////////////////////////////////////////////////////////////////////////// void SeekableMemIO::seek(ptrdiff_t newPos) { assert(newPos >= 0); if (newPos < 0 || newPos > m_end - m_beg) { string_appender<> oss; size_t curr_size = m_end - m_beg; oss << "in " << BOOST_CURRENT_FUNCTION << "[newPos=" << newPos << ", size=" << curr_size << "]"; // errno = EINVAL; throw std::invalid_argument(oss.str()); } m_pos = m_beg + newPos; } void SeekableMemIO::seek(ptrdiff_t offset, int origin) { size_t pos; switch (origin) { default: { string_appender<> oss; oss << "in " << BOOST_CURRENT_FUNCTION << "[offset=" << offset << ", origin=" << origin << "(invalid)]"; // errno = EINVAL; throw std::invalid_argument(oss.str().c_str()); } case 0: pos = (size_t)(0 + offset); break; case 1: pos = (size_t)(tell() + offset); break; case 2: pos = (size_t)(size() + offset); break; } seek(pos); } // rarely used methods.... // std::pair<byte*, byte*> SeekableMemIO::range(size_t ibeg, size_t iend) const { assert(ibeg <= iend); assert(ibeg <= size()); assert(iend <= size()); if (ibeg <= iend && ibeg <= size() && iend <= size()) { return std::pair<byte*, byte*>(m_beg + ibeg, m_beg + iend); } string_appender<> oss; oss << BOOST_CURRENT_FUNCTION << ": size=" << size() << ", tell=" << tell() << ", ibeg=" << ibeg << ", iend=" << iend ; throw std::invalid_argument(oss.str()); } ////////////////////////////////////////////////////////////////////////// AutoGrownMemIO::AutoGrownMemIO(size_t size) { if (size) { m_beg = (byte*)malloc(size); if (NULL == m_beg) { #ifdef _MSC_VER_FUCK char szMsg[128]; sprintf(szMsg , "AutoGrownMemIO::AutoGrownMemIO(size=%lu)" , (unsigned long)size ); throw std::bad_alloc(szMsg); #else throw std::bad_alloc(); #endif } m_end = m_beg + size; m_pos = m_beg; } else m_pos = m_end = m_beg = NULL; } AutoGrownMemIO::~AutoGrownMemIO() { if (m_beg) free(m_beg); } void AutoGrownMemIO::clone(const AutoGrownMemIO& src) { AutoGrownMemIO t(src.size()); memcpy(t.begin(), src.begin(), src.size()); this->swap(t); } /** @brief 改变 buffer 尺寸 不改变 buffer 中的已存内容,不改变 pos @note must m_pos <= newsize */ void AutoGrownMemIO::resize(size_t newsize) { assert(tell() <= newsize); if (newsize < tell()) { THROW_STD(length_error, "newsize=%zd is less than tell()=%zd", newsize, tell()); } #ifdef _MSC_VER size_t oldsize = size(); #endif byte* newbeg = (byte*)realloc(m_beg, newsize); if (newbeg) { m_pos = newbeg + (m_pos - m_beg); m_end = newbeg + newsize; m_beg = newbeg; } else { #ifdef _MSC_VER_FUCK string_appender<> oss; oss << "realloc failed in \"void AutoGrownMemIO::resize(size[new=" << newsize << ", old=" << oldsize << "])\", the AutoGrownMemIO object is not mutated!"; throw std::bad_alloc(oss.str().c_str()); #else throw std::bad_alloc(); #endif } } void AutoGrownMemIO::grow(size_t nGrow) { size_t oldsize = m_end - m_beg; size_t newsize = oldsize + nGrow; size_t newcap = std::max<size_t>(32, oldsize); while (newcap < newsize) newcap *= 2; resize(newcap); } /** @brief 释放原先的空间并重新分配 相当于按新尺寸重新构造一个新 AutoGrownMemIO 不需要把旧内容拷贝到新地址 */ void AutoGrownMemIO::init(size_t newsize) { #ifdef _MSC_VER size_t oldsize = (size_t)(m_beg - m_beg); #endif if (m_beg) ::free(m_beg); if (newsize) { m_beg = (byte*)::malloc(newsize); if (NULL == m_beg) { m_pos = m_end = NULL; #ifdef _MSC_VER_FUCK char szMsg[128]; sprintf(szMsg , "malloc failed in AutoGrownMemIO::init(newsize=%lu), oldsize=%lu" , (unsigned long)newsize , (unsigned long)oldsize ); throw std::bad_alloc(szMsg); #else throw std::bad_alloc(); #endif } m_pos = m_beg; m_end = m_beg + newsize; } else m_pos = m_end = m_beg = NULL; } void AutoGrownMemIO::growAndWrite(const void* data, size_t length) { using namespace std; size_t nSize = size(); size_t nGrow = max(length, nSize); resize(max(nSize + nGrow, (size_t)64u)); memcpy(m_pos, data, length); m_pos += length; } void AutoGrownMemIO::growAndWriteByte(byte b) { using namespace std; resize(max(2u * size(), (size_t)64u)); *m_pos++ = b; } void AutoGrownMemIO::clear() { if (this->m_beg) { ::free(this->m_beg); this->m_beg = NULL; this->m_end = NULL; this->m_pos = NULL; } else { assert(NULL == this->m_end); assert(NULL == this->m_pos); } } /** * shrink allocated memory to fit this->tell() */ void AutoGrownMemIO::shrink_to_fit() { if (NULL == m_beg) { assert(NULL == m_pos); assert(NULL == m_end); } else { assert(m_beg <= m_pos); assert(m_pos <= m_end); size_t realsize = m_pos - m_beg; if (0 == realsize) { ::free(m_beg); m_beg = m_end = m_pos = NULL; } else { byte* newbeg = (byte*)realloc(m_beg, realsize); assert(NULL != newbeg); if (NULL == newbeg) { // realloc should always success on shrink abort(); } m_end = m_pos = newbeg + realsize; m_beg = newbeg; } } } size_t AutoGrownMemIO::printf(const char* format, ...) { va_list ap; size_t n; va_start(ap, format); n = this->vprintf(format, ap); va_end(ap); return n; } size_t AutoGrownMemIO::vprintf(const char* format, va_list ap) { if (m_end - m_pos < 64) { this->resize(std::max<size_t>(64, (m_end-m_beg)*2)); } while (1) { ptrdiff_t n, size = m_end - m_pos; #if defined(va_copy) va_list ap_copy; va_copy(ap_copy, ap); n = ::vsnprintf((char*)m_pos, size, format, ap_copy); va_end(ap_copy); #else n = ::vsnprintf((char*)m_pos, size, format, ap); #endif /* If that worked, return the written bytes. */ if (n > -1 && n < size) { m_pos += n; return n; } /* Else try again with more space. */ if (n > -1) /* glibc 2.1 */ size = n+1; /* precisely what is needed */ else /* glibc 2.0 */ size *= 2; /* twice the old size */ this->resize((m_pos - m_beg + size) * 2); } } /////////////////////////////////////////////////////// // #if defined(__GLIBC__) || defined(__CYGWIN__) ssize_t MemIO_FILE_read(void *cookie, char *buf, size_t size) { MemIO* input = (MemIO*)cookie; return input->read(buf, size); } ssize_t AutoGrownMemIO_FILE_write(void *cookie, const char *buf, size_t size) { AutoGrownMemIO* output = (AutoGrownMemIO*)cookie; return output->write(buf, size); } #if defined(__CYGWIN__) int AutoGrownMemIO_FILE_seek(void* cookie, _off64_t* offset, int whence) #else int AutoGrownMemIO_FILE_seek(void* cookie, off64_t* offset, int whence) #endif { AutoGrownMemIO* output = (AutoGrownMemIO*)cookie; try { output->seek(*offset, whence); *offset = output->tell(); return 0; } catch (const std::exception& e) { errno = EINVAL; return -1; } } /** * @note must call fclose after use of returned FILE */ FILE* MemIO::forInputFILE() { cookie_io_functions_t func = { MemIO_FILE_read, NULL, NULL, NULL }; void* cookie = this; assert(cookie); FILE* fp = fopencookie(cookie,"r", func); if (fp == NULL) { perror("fopencookie@MemIO::getInputFILE"); return NULL; } return fp; } /** * @note must call fclose after use of returned FILE */ FILE* AutoGrownMemIO::forFILE(const char* mode) { cookie_io_functions_t func = { MemIO_FILE_read, AutoGrownMemIO_FILE_write, AutoGrownMemIO_FILE_seek, NULL }; void* cookie = this; assert(cookie); FILE* fp = fopencookie(cookie, mode, func); if (fp == NULL) { perror("fopencookie@AutoGrownMemIO::forOutputFILE"); return NULL; } return fp; } #endif #define STREAM_READER MinMemIO #define STREAM_WRITER MinMemIO #include "var_int_io.hpp" #define STREAM_READER MemIO #define STREAM_WRITER MemIO #include "var_int_io.hpp" #define STREAM_WRITER AutoGrownMemIO #include "var_int_io.hpp" } // namespace terark
21.124706
102
0.631989
rockeet
46c1b7bcb666e58c1852e1291d3dcfb7d7afb797
5,706
cpp
C++
BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
1
2017-03-05T05:29:32.000Z
2017-03-05T05:29:32.000Z
BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
null
null
null
BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
2
2020-10-27T06:51:00.000Z
2020-10-27T06:51:01.000Z
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryTestExpression.h" #include "berryExpressions.h" #include "berryPlatform.h" #include <berryObjectString.h> #include <Poco/Hash.h> namespace berry { const char TestExpression::PROP_SEP = '.'; const std::string TestExpression::ATT_PROPERTY = "property"; const std::string TestExpression::ATT_ARGS = "args"; const std::string TestExpression::ATT_FORCE_PLUGIN_ACTIVATION = "forcePluginActivation"; TypeExtensionManager TestExpression::fgTypeExtensionManager("propertyTesters"); const std::size_t TestExpression::HASH_INITIAL= Poco::hash("berry::TextExpression"); TestExpression::TestExpression(IConfigurationElement::Pointer element) { std::string property; element->GetAttribute(ATT_PROPERTY, property); std::size_t pos = property.find_last_of(PROP_SEP); if (pos == std::string::npos) { throw CoreException("No namespace provided"); } fNamespace = property.substr(0, pos); fProperty = property.substr(pos + 1); Expressions::GetArguments(fArgs, element, ATT_ARGS); std::string arg = ""; bool result = element->GetAttribute(ATT_VALUE, arg); fExpectedValue = Expressions::ConvertArgument(arg, result); fForcePluginActivation = Expressions::GetOptionalBooleanAttribute(element, ATT_FORCE_PLUGIN_ACTIVATION); } TestExpression::TestExpression(Poco::XML::Element* element) { std::string property= element->getAttribute(ATT_PROPERTY); std::size_t pos = property.find_last_of(PROP_SEP); if (pos == std::string::npos) { throw CoreException("No namespace provided"); } fNamespace = property.substr(0, pos); fProperty = property.substr(pos + 1); Expressions::GetArguments(fArgs, element, ATT_ARGS); std::string value = element->getAttribute(ATT_VALUE); fExpectedValue = Expressions::ConvertArgument(value, value.size() > 0); fForcePluginActivation= Expressions::GetOptionalBooleanAttribute(element, ATT_FORCE_PLUGIN_ACTIVATION); } TestExpression::TestExpression(const std::string& namespaze, const std::string& property, std::vector<Object::Pointer>& args, Object::Pointer expectedValue) { TestExpression(namespaze, property, args, expectedValue, false); } TestExpression::TestExpression(const std::string& namespaze, const std::string& property, std::vector<Object::Pointer>& args, Object::Pointer expectedValue, bool forcePluginActivation) : fNamespace(namespaze), fProperty(property), fArgs(args), fExpectedValue(expectedValue), fForcePluginActivation(forcePluginActivation) { } EvaluationResult TestExpression::Evaluate(IEvaluationContext* context) { Object::Pointer element = context->GetDefaultVariable(); if (typeid(Platform) == typeid(element.GetPointer())) { std::string str = Platform::GetProperty(fProperty); if (str.size() == 0) { return EvaluationResult::FALSE_EVAL; } ObjectString::Pointer var = fArgs[0].Cast<ObjectString>(); if (var) return EvaluationResult::ValueOf(*var == str); return EvaluationResult::FALSE_EVAL; } Property::Pointer property= fgTypeExtensionManager.GetProperty(element, fNamespace, fProperty, context->GetAllowPluginActivation() && fForcePluginActivation); if (!property->IsInstantiated()) return EvaluationResult::NOT_LOADED; return EvaluationResult::ValueOf(property->Test(element, fArgs, fExpectedValue)); } void TestExpression::CollectExpressionInfo(ExpressionInfo* info) { info->MarkDefaultVariableAccessed(); info->AddAccessedPropertyName(fNamespace + PROP_SEP + fProperty); } bool TestExpression::operator==(Expression& object) { try { TestExpression& that = dynamic_cast<TestExpression&>(object); return this->fNamespace == that.fNamespace && this->fProperty == that.fProperty && this->fForcePluginActivation == that.fForcePluginActivation && this->Equals(this->fArgs, that.fArgs) && this->fExpectedValue == that.fExpectedValue; } catch (std::bad_cast) { return false; } } std::size_t TestExpression::ComputeHashCode() { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fArgs) * HASH_FACTOR + fExpectedValue->HashCode() * HASH_FACTOR + Poco::hash(fNamespace) * HASH_FACTOR + Poco::hash(fProperty) * HASH_FACTOR + (fForcePluginActivation ? 1 : 0); } std::string TestExpression::ToString() { std::string args(""); for (unsigned int i= 0; i < fArgs.size(); i++) { Object::Pointer arg= fArgs[i]; ObjectString::Pointer strarg = arg.Cast<ObjectString>(); if (strarg) { args.append(1,'\''); args.append(*strarg); args.append(1,'\''); } else { args.append(arg->ToString()); } if (i < fArgs.size() - 1) args.append(", "); //$NON-NLS-1$ } return "<test property=\"" + fProperty + (fArgs.size() != 0 ? "\" args=\"" + args + "\"" : "\"") + (!fExpectedValue.IsNull() ? "\" value=\"" + fExpectedValue->ToString() + "\"" : "\"") + " plug-in activation: " + (fForcePluginActivation ? "eager" : "lazy") + "/>"; //$NON-NLS-1$ } //---- testing --------------------------------------------------- bool TestExpression::TestGetForcePluginActivation() { return fForcePluginActivation; } TypeExtensionManager& TestExpression::TestGetTypeExtensionManager() { return fgTypeExtensionManager; } }
30.190476
184
0.695233
danielknorr
46c7a76985f5d3f9668922bd594d87318ead7fe1
1,040
cpp
C++
AtCoder/abc161/E.cpp
noobie7/Codes
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
[ "MIT" ]
2
2021-09-14T15:57:24.000Z
2022-03-18T14:11:04.000Z
AtCoder/abc161/E.cpp
noobie7/Codes
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
[ "MIT" ]
null
null
null
AtCoder/abc161/E.cpp
noobie7/Codes
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
[ "MIT" ]
null
null
null
/* "Do I really belong in this game I ponder, I just wanna play my part." - Guts over fear, Eminem */ #pragma GCC optimize ("O3") #pragma GCC target ("sse4") #include<bits/stdc++.h> using namespace std; typedef long long int ll; #define ff first #define Shazam ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #define ss second #define all(c) c.begin(),c.end() #define endl "\n" #define test() int t; cin>>t; while(t--) #define fl(i,a,b) for(int i = a ; i <b ;i++) #define get(a) fl(i,0,a.size()) cin>>a[i]; #define pra(a) fl(i,0,a.size()) cout<<a[i]<<" "; cout<<endl; #define pr(a,n) fl(i,0,n) cout<<a[i]<<" "; cout<<endl; const ll INF = 2e18; const int inf = 2e9; const int mod1 = 1e9 + 7; int main(){ Shazam; int n,c,k; cin>>n>>k>>c; string s; cin>>s; vector<int> a,b; for(int i = 0 ; i < n ; i++) if(s[i]=='o'){a.push_back(i); i+=c;} for(int i = n-1; i >=0; i--) if(s[i]=='o'){b.push_back(i); i-=c;} for(int i = 0 ; i < k ; i++) {if(a[i]==b[k-1-i]) cout<<a[i]+1<<endl;} return 0; }
29.714286
81
0.575962
noobie7
46ca9a317c482ebdc784219d9ead089b15fdd056
8,788
cpp
C++
test/src/tc/pm/gtest/cpp/src/helper/PMCppUtilityHelper.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
301
2015-01-20T16:11:32.000Z
2021-11-25T04:29:36.000Z
test/src/tc/pm/gtest/cpp/src/helper/PMCppUtilityHelper.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
13
2015-06-04T09:55:15.000Z
2020-09-23T00:38:07.000Z
test/src/tc/pm/gtest/cpp/src/helper/PMCppUtilityHelper.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
233
2015-01-26T03:41:59.000Z
2022-03-18T23:54:04.000Z
/****************************************************************** * * Copyright 2016 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * LICENSE-2.0" target="_blank">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 "PMCppHelper.h" #include "PMCppUtilityHelper.h" bool PMCppUtilityHelper::readFile(const char *name, OCByteString *out) { FILE *file = NULL; int length = 0; uint8_t *buffer = NULL; bool result = false; size_t count, realCount; //Open file file = fopen(name, "rb"); if (!file) { OIC_LOG_V(ERROR, TAG, "Unable to open file %s", name); return result; } //Get file length if (fseek(file, 0, SEEK_END)) { OIC_LOG(ERROR, TAG, "Failed to SEEK_END"); goto exit; } length = ftell(file); if (length < 0) { OIC_LOG(ERROR, TAG, "Failed to ftell"); goto exit; } if (fseek(file, 0, SEEK_SET)) { OIC_LOG(ERROR, TAG, "Failed to SEEK_SET"); goto exit; } //Allocate memory buffer = (uint8_t *) malloc(length); if (!buffer) { OIC_LOG(ERROR, TAG, "Failed to allocate buffer"); goto exit; } //Read file contents into buffer count = 1; realCount = fread(buffer, length, count, file); if (realCount != count) { OIC_LOG_V(ERROR, TAG, "Read %d bytes %zu times instead of %zu", length, realCount, count); goto exit; } out->bytes = buffer; out->len = length; result = true; exit: fclose(file); return result; } void PMCppUtilityHelper::printDevices(DeviceList_t &list) { for (unsigned int i = 0; i < list.size(); i++) { std::cout << "Device " << i + 1 << " ID: "; std::cout << list[i]->getDeviceID() << " From IP: "; std::cout << list[i]->getDevAddr() << " Device Status(On/ Off) "; std::cout << list[i]->getDeviceStatus() << " Owned Status: "; std::cout << list[i]->getOwnedStatus() << std::endl; } } char* PMCppUtilityHelper::getOxmType(OicSecOxm_t oxmType) { char* resultString = NULL; switch (oxmType) { case OIC_JUST_WORKS: resultString = (char*) "OIC_JUST_WORKS"; break; case OIC_RANDOM_DEVICE_PIN: resultString = (char*) "OIC_RANDOM_DEVICE_PIN"; break; case OIC_MANUFACTURER_CERTIFICATE: resultString = (char*) "OIC_MANUFACTURER_CERTIFICATE"; break; case OIC_DECENTRALIZED_PUBLIC_KEY: resultString = (char*) "OIC_DECENTRALIZED_PUBLIC_KEY"; break; case OIC_OXM_COUNT: resultString = (char*) "OIC_OXM_COUNT"; break; case OIC_PRECONFIG_PIN: resultString = (char*) "OIC_PRECONFIG_PIN"; break; case OIC_MV_JUST_WORKS: resultString = (char*) "OC_STACK_RESOURCE_CREATED"; break; case OIC_CON_MFG_CERT: resultString = (char*) "OIC_CON_MFG_CERT"; break; default: resultString = (char*) "UNKNOWN_OXM_TYPE"; } return resultString; } void PMCppUtilityHelper::printUuid(OicUuid_t uuid) { for (int i = 0; i < UUID_LENGTH; i++) { std::cout << std::hex << uuid.id[i] << " "; } std::cout << std::endl; } void PMCppUtilityHelper::removeAllResFile() { CommonUtil::rmFile(JUSTWORKS_SERVER1_CBOR); CommonUtil::rmFile(JUSTWORKS_SERVER2_CBOR); CommonUtil::rmFile(RANDOMPIN_SERVER_CBOR); CommonUtil::rmFile(PRECONFIG_SERVER1_CBOR); CommonUtil::rmFile(PRECONFIG_SERVER2_CBOR); CommonUtil::rmFile(JUSTWORKS_SERVER7_CBOR); CommonUtil::rmFile(MV_JUSTWORKS_SERVER_CBOR); CommonUtil::rmFile(CLIENT_DATABASE); CommonUtil::rmFile(CLIENT_CBOR); CommonUtil::rmFile(MOT_CLIENT_DATABASE); CommonUtil::rmFile(MOT_CLIENT_CBOR); CommonUtil::rmFile(DEVICE_PROPERTIES); CommonUtil::rmFile(ROOT_CERT_FILE_TMP); } OCProvisionDev_t* PMCppUtilityHelper::getDevInst(OCProvisionDev_t* dev_lst, const int dev_num) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] getDevInst IN"); if (!dev_lst || 0 >= dev_num) { IOTIVITYTEST_LOG(ERROR, "[PMHelper] Device List is Empty"); return NULL; } OCProvisionDev_t* lst = (OCProvisionDev_t*) dev_lst; for (int i = 0; lst;) { if (dev_num == ++i) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] getDevInst OUT"); return lst; } lst = lst->next; } IOTIVITYTEST_LOG(DEBUG, "[PMHelper] getDevInst OUT"); return NULL; // in here |lst| is always |NULL| } int PMCppUtilityHelper::printDevList(OCProvisionDev_t* dev_lst) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printDevList IN"); if (!dev_lst) { IOTIVITYTEST_LOG(INFO, "[PMHelper] Device List is Empty..."); return 0; } OCProvisionDev_t* lst = (OCProvisionDev_t*) dev_lst; int lst_cnt = 0; for (; lst;) { printf(" [%d] ", ++lst_cnt); printUuid((const OicUuid_t*) &lst->doxm->deviceID); printf("\n"); lst = lst->next; } printf("\n"); IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printDevList OUT"); return lst_cnt; } size_t PMCppUtilityHelper::printUuidList(const OCUuidList_t* uid_lst) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printUuidList IN"); if (!uid_lst) { IOTIVITYTEST_LOG(INFO, "[PMHelper] Device List is Empty..."); return 0; } OCUuidList_t* lst = (OCUuidList_t*) uid_lst; size_t lst_cnt = 0; for (; lst;) { printf(" [%zu] ", ++lst_cnt); printUuid((const OicUuid_t*) &lst->dev); printf("\n"); lst = lst->next; } printf("\n"); IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printUuidList OUT"); return lst_cnt; } int PMCppUtilityHelper::printResultList(const OCProvisionResult_t* rslt_lst, const int rslt_cnt) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printResultList IN"); if (!rslt_lst || 0 >= rslt_cnt) { IOTIVITYTEST_LOG(INFO, "[PMHelper] Device List is Empty..."); return 0; } int lst_cnt = 0; for (; rslt_cnt > lst_cnt; ++lst_cnt) { printf(" [%d] ", lst_cnt + 1); printUuid((const OicUuid_t*) &rslt_lst[lst_cnt].deviceId); printf(" - result: %s\n", CommonUtil::getOCStackResult(rslt_lst[lst_cnt].res)); } printf("\n"); IOTIVITYTEST_LOG(INFO, "[PMHelper] printResultList IN"); return lst_cnt; } void PMCppUtilityHelper::printUuid(const OicUuid_t* uid) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printUuid IN"); for (int i = 0; i < UUID_LENGTH;) { printf("%02X", (*uid).id[i++]); if (i == 4 || i == 6 || i == 8 || i == 10) // canonical format for UUID has '8-4-4-4-12' { printf("%c", DASH); } } printf("\n"); IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printUuid OUT"); } /** * Function to set failure message */ std::string PMCppUtilityHelper::setFailureMessage(OCStackResult expectedResult, OCStackResult actualResult) { std::string errorMessage("\033[1;31m[Error] Expected : "); errorMessage.append(CommonUtil::getOCStackResult(expectedResult)); errorMessage.append("\033[0m \033[1;31mActual : "); errorMessage.append(CommonUtil::getOCStackResult(actualResult)); errorMessage.append("\033[0m"); return errorMessage; } /** * Function to set failure message */ std::string PMCppUtilityHelper::setFailureMessage(OicSecOxm_t expectedResult, OicSecOxm_t actualResult) { std::string errorMessage("\033[1;31m[Error] Expected : "); errorMessage.append(PMCppUtilityHelper::getOxmType(expectedResult)); errorMessage.append("\033[0m \033[1;31mActual : "); errorMessage.append(PMCppUtilityHelper::getOxmType(actualResult)); errorMessage.append("\033[0m"); return errorMessage; } /** * Function to set failure message */ std::string PMCppUtilityHelper::setFailureMessage(std::string errorMessage) { std::string retErrorMessage("\033[1;31m[Error] Expected : "); retErrorMessage.append(errorMessage); retErrorMessage.append("\033[0m"); return retErrorMessage; }
27.20743
98
0.612995
jonghenhan
46cdd8004bd7e3f2911eb9073495f88913ee36c7
2,051
cpp
C++
LeetCode/Hash/LongestSubstringWithoutRepeatingCharacters_f.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
3
2021-07-26T15:58:45.000Z
2021-09-08T14:55:11.000Z
LeetCode/Hash/LongestSubstringWithoutRepeatingCharacters_f.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
null
null
null
LeetCode/Hash/LongestSubstringWithoutRepeatingCharacters_f.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
2
2021-05-31T11:27:59.000Z
2021-10-03T13:26:00.000Z
/* * LeetCode 3 Longest Substring Without Repeating Characters * Medium * Shuo Feng * 2021.9.15 */ /* * Solution 1: * Begin with a starting point and check characters after, update a set and record the maximum size. * When meet a repeating character, remove the previous point in set till there have not repeat, change starting point in " s ". * * a b c a b c b b Longest Substring: * Begin ↑(Find repeat) (abc) * a b c a b c b b * Begin ↑ (bca) * a b c a b c b b * Begin ↑ (cab) * a b c a b c b b * Begin ↑ (abc) * a b c a b c b b * Begin ↑ (bc) * a b c a b c b b * Begin ↑ (cb) * a b c a b c b b * Begin ↑ (b) * a b c a b c b b * Begin (b) */ #include<iostream> #include<string> #include<utility> #include<unordered_set> using namespace std; class Solution { public: int lengthOfLongestSubstring(string s) { int size = s.size(); if (size < 2) return size; int max_size = 0; int Begin = 0; // Begining place. unordered_set <char> search; for (int i = 0; i < size; ++i) { // Search in set. // Repetitive. while (search.find(s[i]) != search.end()) { search.erase(s[Begin]); Begin += 1; // Begin with next point. } // non_Repetitive. search.insert(s[i]); max_size = max(max_size, i - Begin + 1); } return max_size; } };
32.046875
130
0.387128
a4org
46cf676f19bb9b2850daf5c31dd6fa692a4b68ff
2,789
cpp
C++
sources/Page.cpp
khsabrina/notebook-b
5ab09040f7b3658314239148a54a45747a918b22
[ "MIT" ]
null
null
null
sources/Page.cpp
khsabrina/notebook-b
5ab09040f7b3658314239148a54a45747a918b22
[ "MIT" ]
null
null
null
sources/Page.cpp
khsabrina/notebook-b
5ab09040f7b3658314239148a54a45747a918b22
[ "MIT" ]
null
null
null
#include "Row.hpp" #include "Page.hpp" using namespace std; #include <iostream> #include <iterator> #include <map> const int LENGHT_ROW=100; Page::Page(){ } void Page::add(int col,int row,Direction dir, string str){ if(dir == Direction::Horizontal){ int size = str.size(); if (col + size > LENGHT_ROW){ throw invalid_argument{"You can't write here1"}; } if (!rows.contains(row)){ Row New; rows.insert({row, New}); rows[row].add(col,str); } else{ rows[row].check_horizontal(col, str.size()); //if(!check){return;} rows[row].add(col,str); } } if(dir == Direction::Vertical){ for(int i= 0; i<str.size();i++){ if(!rows.contains(row+i)){ Row New; rows.insert({row+i, New}); } else{ rows[row+i].check_vertical(col); //if(!check){return;} } } for(int i=0; i<str.size();i++){ string c(1, (char)str[(unsigned long)i]); rows[row+i].add(col,c); } } } string Page::read(int col,int row,Direction dir, int size){ string ans; if(dir == Direction::Horizontal){ if (col + size > LENGHT_ROW){ throw invalid_argument{"You can't write here"}; } if(!rows.contains(row)){ Row New; rows.insert({row, New}); } ans = rows[row].read(col,size); } else{ if (col > LENGHT_ROW){ throw invalid_argument{"You can't write here"}; } for(int i=0; i<size; i++){ if(!rows.contains(row+i)){ Row New; rows.insert({row+i, New}); } ans += rows[row+i].read(col,1); } } return ans; } void Page::erase(int col,int row, Direction dir , int size){ if(dir == Direction::Horizontal){ if (col + size > LENGHT_ROW){ cout << "here5"; throw invalid_argument{"You can't write here4"}; return; } if(!rows.contains(row)){ Row New; rows.insert({row, New}); } rows[row].erase(col,size); } else{ for(int i=0; i<size; i++){ if(!rows.contains(row+i)){ Row New; rows.insert({row+i, New}); } rows[row+i].erase(col,1); } } } void Page::show(){ map<int, Row>::iterator itr; for (itr = rows.begin(); itr != rows.end(); ++itr) { cout << itr->first << "."; itr->second.show(); cout << '\n'; } } // Page::~Page(){ // return; // }
24.901786
64
0.453926
khsabrina
46d4d4e5eb5f615fc8966b8330dc7b0a6e138afc
130
cpp
C++
src/CMake/Testftimeprototype.cpp
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
226
2018-12-29T01:13:49.000Z
2022-03-30T19:16:31.000Z
src/CMake/Testftimeprototype.cpp
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
5,100
2019-01-14T18:19:25.000Z
2022-03-31T23:08:36.000Z
src/CMake/Testftimeprototype.cpp
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
84
2019-01-24T17:41:50.000Z
2022-03-10T10:01:46.000Z
#include <sys/time.h> #include <sys/timeb.h> int main(int argc, char *argv[]) { struct timeb *tp; ftime(tp); return 0; }
13
32
0.615385
visit-dav
46d53436f721cfb55f85f51e483ddd0174db7856
3,866
cpp
C++
src/desktop/panes/fspane.cpp
KDE/kookbook
522ca12ebdf386cd3ca52d03fbf1b022c9e5e1b9
[ "MIT" ]
8
2018-12-18T20:49:56.000Z
2022-01-11T07:40:56.000Z
src/desktop/panes/fspane.cpp
KDE/kookbook
522ca12ebdf386cd3ca52d03fbf1b022c9e5e1b9
[ "MIT" ]
null
null
null
src/desktop/panes/fspane.cpp
KDE/kookbook
522ca12ebdf386cd3ca52d03fbf1b022c9e5e1b9
[ "MIT" ]
2
2019-02-18T17:08:49.000Z
2020-10-08T06:01:03.000Z
/* * Copyright (c) 2018 Sune Vuorela <sune@vuorela.dk> * * 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 "fspane.h" #include <memory> #include <QTreeView> #include <QFileSystemModel> #include <QVBoxLayout> #include <QIdentityProxyModel> #include <QDebug> class OneColumnProxy : public QIdentityProxyModel { public: OneColumnProxy(QObject* parent = nullptr) : QIdentityProxyModel(parent) {} int columnCount(const QModelIndex& ) const override { return 1; } }; class FileNameTitleMapper : public QIdentityProxyModel { public: FileNameTitleMapper(QObject* parent = nullptr) : QIdentityProxyModel(parent) {} void setFileNameTitleMap(QHash<QString,QString> map) { beginResetModel(); m_map = map; endResetModel(); } QHash<QString,QString> m_map; QVariant data(const QModelIndex& idx, int role) const override { if(role == Qt::DisplayRole) { QVariant d = QIdentityProxyModel::data(idx,QFileSystemModel::FilePathRole); QString str = d.toString(); auto it = m_map.constFind(str); if (it != m_map.constEnd()) { return it.value(); } } return QIdentityProxyModel::data(idx,role); } }; FsPane::FsPane(QWidget* parent) : QWidget(parent) { auto layout = std::make_unique<QVBoxLayout>(); auto tree = std::make_unique<QTreeView>(); m_dirModel = std::make_unique<QFileSystemModel>(); m_dirModel->setNameFilters(QStringList() << QStringLiteral("*.recipe.md")); m_dirModel->setNameFilterDisables(false); m_filenamemapper = std::make_unique<FileNameTitleMapper>(); m_filenamemapper->setSourceModel(m_dirModel.get()); m_proxy = std::make_unique<OneColumnProxy>(); m_proxy->setSourceModel(m_filenamemapper.get()); tree->setModel(m_proxy.get()); tree->setHeaderHidden(true); connect(tree.get(), &QTreeView::clicked, [this] (const QModelIndex& idx) { auto var = idx.data(QFileSystemModel::FilePathRole); emit this->fileSelected(var.toString()); }); m_tree = tree.get(); layout->addWidget(tree.release()); setLayout(layout.release()); } FsPane::~FsPane() { // for smart pointers } void FsPane::setRootPath(const QString& string) { auto path = m_dirModel->setRootPath(string); path = m_filenamemapper->mapFromSource(path); path = m_proxy->mapFromSource(path); if (path.isValid()) { m_tree->setModel(m_proxy.get()); m_tree->setRootIndex(path); m_rootPath = string; } else { m_tree->setModel(nullptr); m_rootPath = QString(); } } void FsPane::setFileNameTitleMap(QHash<QString, QString> titlemap) { m_filenamemapper->setFileNameTitleMap(titlemap); setRootPath(m_rootPath); }
31.430894
87
0.685722
KDE
46d9f66e3002849d353f2a3c08eb1ff530d8bd2a
334
hpp
C++
include/Btk/impl/mixer.hpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
2
2021-06-19T08:21:38.000Z
2021-08-15T21:37:30.000Z
include/Btk/impl/mixer.hpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
null
null
null
include/Btk/impl/mixer.hpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
1
2021-04-03T14:27:39.000Z
2021-04-03T14:27:39.000Z
#if !defined(_BTK_IMPL_MIXER) #define _BTK_IMPL_MIXER //Implment for mixer #include <SDL2/SDL_audio.h> #include <SDL2/SDL_error.h> #include <SDL2/SDL_rwops.h> #include "../mixer.hpp" #include "../rwops.hpp" #include "../function.hpp" #include "atomic.hpp" #include <vector> #include <mutex> #include <list> #endif // _BTK_IMPL_MIXER
20.875
29
0.730539
BusyStudent
46da70a73467334640434461461fe89eaf2ba08b
5,631
cc
C++
apps/rwh/arguments.cc
OSADP/Pikalert-Vehicle-Data-Translator-
295da604408f6f13af0301b55476a81311459386
[ "Apache-2.0" ]
2
2020-06-03T15:59:50.000Z
2020-12-21T11:11:57.000Z
apps/rwh/arguments.cc
OSADP/Pikalert-Vehicle-Data-Translator-
295da604408f6f13af0301b55476a81311459386
[ "Apache-2.0" ]
null
null
null
apps/rwh/arguments.cc
OSADP/Pikalert-Vehicle-Data-Translator-
295da604408f6f13af0301b55476a81311459386
[ "Apache-2.0" ]
2
2019-10-02T06:47:23.000Z
2020-02-02T18:32:23.000Z
//============================================================================== // // (c) Copyright, 2013 University Corporation for Atmospheric Research (UCAR). // All rights reserved. // // File: $RCSfile: arguments.cc,v $ // Version: $Revision: 1.2 $ Dated: $Date: 2013/09/27 16:47:01 $ // //============================================================================== /** * * @file apps/probe_message_dataset_manager/arguments.cc * * Implementation for simple class that parses command line arguments. * */ // Include files #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <boost/format.hpp> #include "arguments.hh" using boost::format; // Constant and macros // Types, structures and classes // Global variables // Functions void get_command_string(int argc, char **argv, string &command_string) { for (int i=0; i<argc-1; i++) { command_string += string(argv[i]) + string(" "); } command_string += string(argv[argc-1]); } arguments::arguments(int argc, char **argv) { int c = 0; char *ptr = 0; int errflg = 0; begin_time = 0; begin_time_string = ""; end_time = 0; end_time_string = ""; error = ""; debug = 0; log_file = ""; road_wx_fcst_file = ""; road_cond_fcst_file = ""; vdt_seg_stats_file = ""; vdt_seg_assign_wx_file = ""; prev_rwh_conf_file = ""; test = false; // Parse command line options while ((c = getopt(argc, argv, "a:d:l:n:p:s:r:w:t")) != EOF) { switch (c) { case 'a': vdt_seg_assign_wx_file = optarg; break; case 'd': debug = (int)strtol(optarg, &ptr, 10); if (debug == 0 && ptr == optarg) { error = string("bad debug level"); return; } break; case 'l': log_file = optarg; break; case 's': vdt_seg_stats_file = optarg; break; case 'r': road_cond_fcst_file = optarg; break; case 'w': road_wx_fcst_file = optarg; break; case 'p': prev_rwh_conf_file = optarg; break; case 't': test = true; break; case '?': errflg = 1; break; } } if (errflg) { error = "bad command line option"; return; } ptr = strrchr(argv[0], '/'); if (ptr == NULL) ptr = argv[0]; else ptr++; program_name = string(ptr); if (test && (argc - optind) < 1) { fprintf(stderr, "Error: when specifying the -t option, you also need to specify a configuration file\n"); usage(argv[0]); exit(2); } else if (!test && (argc - optind) < 6) { usage(argv[0]); exit(2); } cfg_file = string(argv[optind++]); if (!test) { // Assign names to command line parameters begin_time_string = string(argv[optind++]); end_time_string = string(argv[optind++]); begin_time = datetime_2_utime((char *)(begin_time_string.c_str()) ); end_time = datetime_2_utime((char *)(end_time_string.c_str())); fcst_road_seg_site_list_file = string(argv[optind++]); vdt_road_seg_file = string(argv[optind++]); output_file = string(argv[optind++]); } get_command_string(argc, argv, command_string); } void arguments::usage(char *program_name) { fprintf(stderr, "usage: %s [-w road_wx_fcst_file] [-r road_cond_fcst_file] [-s vdt_seg_stats_file] [-a vdt_seg_assign_wx_file] [-p prev_rwh_conf_file] [-l log_file] [-d debug_level] [-t] config_file begin_time_string end_time_string fcst_road_seg_site_list_file vdt_road_seg_file rwh_output_file \n", program_name); fprintf(stderr, "config_file : configuration file for road weather hazzard application\n"); fprintf(stderr, "begin_time_string : begin time string in form yyyymmddhhmm of time window of interest\n"); fprintf(stderr, "end_time_string : end time string in form yyyymmddhhmm of time window of interest\n"); fprintf(stderr, "fcst_road_seg_site_list_file : ascii file with road segment site list entries for retrieving forecast data\n"); fprintf(stderr, "vdt_road_seg_file : netcdf file with road segments data\n"); fprintf(stderr, "output_file : output file with road weather hazard data\n"); fprintf(stderr, "-w road_wx_fcst_file : input file with road segment weather forecast data\n"); fprintf(stderr, "-r road_cond_fcst_file : input file with road segment conditions forecast data\n"); fprintf(stderr, "-s vdt_seg_stats_file : input file with VDT Stage II Segment Statistics data\n"); fprintf(stderr, "-a vdt_seg_assign_wx_file : input file with VDT Stage II Road-Weather Assignment data\n"); fprintf(stderr, "-p prev_rwh_conf_file : input file with a list of prevoius RWH files\n"); fprintf(stderr, "-l log_file: write log messages to log_file\n"); fprintf(stderr, "-d debug_level: set debug diagnostic level\n"); fprintf(stderr, "-t: run tests dictated by configuration file. Note if -t is specified, the configuration file is the only other command line parameter needed.\n"); } time_t arguments::datetime_2_utime(char *datetime) { struct tm time_tm; int ret = sscanf(datetime, "%4d%02d%02d%02d%02d", &time_tm.tm_year, &time_tm.tm_mon, &time_tm.tm_mday, &time_tm.tm_hour, &time_tm.tm_min); if(ret != 5) { fprintf(stderr, "Error: invalid date: %s, format must be YYYYMMDDHHMM\n", datetime); return -1; } time_tm.tm_year -= 1900; time_tm.tm_mon -= 1; time_tm.tm_sec = 0; time_t utime = timegm(&time_tm); return utime; }
28.439394
317
0.618007
OSADP
46e75db4cb5af3abca61418168d8641ca99693c5
285
cpp
C++
chapter_2/section_x/io.cpp
martindes01/learncpp
50c500b0cf03c9520eab0a6bdeb4556da7d13bbf
[ "MIT" ]
4
2020-08-03T15:00:00.000Z
2022-01-08T20:22:55.000Z
chapter_2/section_x/io.cpp
martindes01/learncpp
50c500b0cf03c9520eab0a6bdeb4556da7d13bbf
[ "MIT" ]
null
null
null
chapter_2/section_x/io.cpp
martindes01/learncpp
50c500b0cf03c9520eab0a6bdeb4556da7d13bbf
[ "MIT" ]
null
null
null
// Include custom headers #include "io.h" // Include standard library headers #include <iostream> int readNumber() { std::cout << "Enter an integer: "; int x{ }; std::cin >> x; return x; } void writeAnswer(int answer) { std::cout << "The answer is " << answer << '\n'; }
14.25
50
0.614035
martindes01
46ef9733080898aed1ced4a6f987e79f1a761388
3,766
cpp
C++
src/network/socket.cpp
leezhenghui/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
351
2016-10-12T14:06:09.000Z
2022-03-24T14:53:54.000Z
src/network/socket.cpp
leezhenghui/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
7
2017-03-07T01:49:16.000Z
2018-07-27T08:51:54.000Z
src/network/socket.cpp
UncP/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
62
2016-10-31T12:46:45.000Z
2021-12-28T11:25:26.000Z
/** * > Author: UncP * > Github: www.github.com/UncP/Mushroom * > License: BSD-3 * > Time: 2017-04-23 10:23:53 **/ #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> #include <cstring> #include <cassert> #include <cerrno> #include "socket.hpp" namespace Mushroom { Socket::Socket():fd_(-1) { } Socket::Socket(int fd):fd_(fd) { } Socket::~Socket() { } int Socket::fd() const { return fd_; } bool Socket::Valid() const { return fd_ != -1; } bool Socket::Create() { fd_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); return fd_ != -1; } bool Socket::Close() { bool flag = true; if (fd_ != -1) { flag = !close(fd_); fd_ = -1; } return flag; } bool Socket::Connect(const EndPoint &end_point) { struct sockaddr_in server; memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(end_point.Port()); server.sin_addr.s_addr = end_point.Address(); return !connect(fd_, (const struct sockaddr *)&server, sizeof(server)); } bool Socket::Bind(uint16_t port) { struct sockaddr_in server; memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(port); server.sin_addr.s_addr = htonl(INADDR_ANY); return !bind(fd_, (const struct sockaddr *)&server, sizeof(server)); } bool Socket::Listen() { return !listen(fd_, 32); } int Socket::Accept() { struct sockaddr_in client; memset(&client, 0, sizeof(client)); socklen_t len = sizeof(client); int fd = accept(fd_, (struct sockaddr *)&client, &len); return fd; } bool Socket::SetOption(int value, bool flag) { return !setsockopt(fd_, SOL_SOCKET, value, &flag, sizeof(flag)); } bool Socket::GetOption(int value, int *ret) { socklen_t len = sizeof(*ret); return !getsockopt(fd_, SOL_SOCKET, value, ret, &len); } bool Socket::SetResuseAddress() { int flag = 1; return !setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); } bool Socket::GetPeerName(EndPoint *endpoint) { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); socklen_t len = sizeof(addr); if (!getsockname(fd_, (struct sockaddr *)&addr, &len)) { *endpoint = EndPoint(ntohs(addr.sin_port), addr.sin_addr.s_addr); return true; } return false; } bool Socket::GetSockName(EndPoint *endpoint) { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); socklen_t len = sizeof(addr); if (!getpeername(fd_, (struct sockaddr *)&addr, &len)) { *endpoint = EndPoint(ntohs(addr.sin_port), addr.sin_addr.s_addr); return true; } return false; } bool Socket::AddFlag(int flag) { int value = fcntl(fd_, F_GETFL, 0); assert(value != -1); return !fcntl(fd_, F_SETFL, value | flag); } bool Socket::SetNonBlock() { int value = fcntl(fd_, F_GETFL, 0); assert(value != -1); return !fcntl(fd_, F_SETFL, value | O_NONBLOCK); } uint32_t Socket::Write(const char *data, uint32_t len, bool *blocked) { uint32_t written = 0; for (; written < len;) { ssize_t r = write(fd_, data + written, len - written); if (r > 0) { written += r; continue; } else if (r == -1) { if (errno == EINTR) continue; if (errno == EAGAIN || errno == EWOULDBLOCK) { *blocked = true; break; } } printf("write error, %s :(\n", strerror(errno)); break; } return written; } uint32_t Socket::Read(char *data, uint32_t len, bool *blocked) { uint32_t has_read = 0; ssize_t r; for (; has_read < len && (r = read(fd_, data + has_read, len - has_read));) { if (r == -1) { if (errno == EINTR) continue; if (errno == EAGAIN || errno == EWOULDBLOCK) *blocked = true; else printf("read error, %s :(\n", strerror(errno)); break; } has_read += r; } return has_read; } } // namespace Mushroom
20.467391
78
0.648168
leezhenghui
46f35ad0d1bfa320692ae6d13de0007a229878f3
130
cpp
C++
nano/src/nano/nano.cpp
lyLoveSharon/nano
aa768a241a4ea282f83ccd088561a5eefd59d342
[ "Apache-2.0" ]
null
null
null
nano/src/nano/nano.cpp
lyLoveSharon/nano
aa768a241a4ea282f83ccd088561a5eefd59d342
[ "Apache-2.0" ]
null
null
null
nano/src/nano/nano.cpp
lyLoveSharon/nano
aa768a241a4ea282f83ccd088561a5eefd59d342
[ "Apache-2.0" ]
null
null
null
#include "nano/nano.h" const char *nano_version() { return "0.0.1"; } const char *nano_module_name() { return "nano"; }
10.833333
30
0.623077
lyLoveSharon
46f7ea9131f1e0f8f0ac7885da9e48173eabfb30
1,208
cpp
C++
ModeChoice/Household_List.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
ModeChoice/Household_List.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
ModeChoice/Household_List.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Household_List.cpp - read the household list file //********************************************************* #include "ModeChoice.hpp" #include "Utility.hpp" //--------------------------------------------------------- // Household_List //--------------------------------------------------------- void ModeChoice::Household_List (void) { int hhold, nfile; for (nfile=0; ; nfile++) { if (hhlist_file.Extend ()) { if (nfile > 0) { if (!hhlist_file.Open (nfile)) return; } Show_Message ("Reading %s %s -- Record", hhlist_file.File_Type (), hhlist_file.Extension ()); } else { if (nfile > 0) return; Show_Message ("Reading %s -- Record", hhlist_file.File_Type ()); } Set_Progress (); //---- store the household list ---- while (hhlist_file.Read ()) { Show_Progress (); Get_Integer (hhlist_file.Record (), &hhold); if (hhold <= 0) continue; if (!hhold_list.Add (hhold)) { Error ("Adding Household %d to the List", hhold); } } End_Progress (); } hhlist_file.Close (); Print (2, "Total Number of Household List Records = %d", hhold_list.Num_Records ()); hhold_list.Optimize (); }
24.16
96
0.508278
kravitz
46fb1480e4ec109476ab56bb8b7429d68d7b3a9d
2,824
cpp
C++
examples/basin.cpp
danielelinaro/BAL
d735048d9962a0c424c29db93f774494c67b12a9
[ "MIT" ]
1
2020-02-02T22:30:37.000Z
2020-02-02T22:30:37.000Z
examples/basin.cpp
danielelinaro/BAL
d735048d9962a0c424c29db93f774494c67b12a9
[ "MIT" ]
null
null
null
examples/basin.cpp
danielelinaro/BAL
d735048d9962a0c424c29db93f774494c67b12a9
[ "MIT" ]
null
null
null
/*========================================================================= * * Program: Bifurcation Analysis Library * Module: basin.cpp * * Copyright (C) 2009 Daniele Linaro * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * *=========================================================================*/ #include <cstdio> #include <cstdlib> #include <nvector/nvector_serial.h> #include "balObject.h" #include "balDynamicalSystem.h" #include "balHindmarshRose.h" #include "balODESolver.h" #include "balBifurcationDiagram.h" #include "balParameters.h" using namespace bal; // TEST BifurcationDiagram int main(int argc, char *argv[]) { Parameters * par = Parameters::Create(); par->SetNumber(4); par->At(0) = 2.88; par->At(1) = 2.6; par->At(2) = 0.01; par->At(3) = 4.0; HindmarshRose * hr = HindmarshRose::Create(); hr->SetParameters(par); BifurcationDiagram * bifd = BifurcationDiagram::Create(); bifd->SetDynamicalSystem(hr); bifd->SetFilename("hr-basin.h5"); bifd->GetODESolver()->SetIntegrationMode(EVENTS); bifd->GetODESolver()->HaltAtEquilibrium(true); bifd->GetODESolver()->HaltAtCycle(true); bifd->GetODESolver()->SetTransientDuration(0e3); bifd->GetODESolver()->SetFinalTime(5e3); bifd->GetODESolver()->SetTimeStep(0.1); bifd->GetODESolver()->SetMaxNumberOfIntersections(300); bifd->SetNumberOfThreads(argc > 1 ? atoi(argv[1]) : 2); //double x0_chaos[] = {-0.882461371550183,-3.661932217696160,2.870154513826437}; int nX0 = 1000; double **X0 = new double*[nX0]; for(int i=0; i<nX0; i++) { X0[i] = new double[3]; /* X0[i][0] = 2.5*((double) random()/RAND_MAX); X0[i][1] = -10 + 12*((double) random()/RAND_MAX); X0[i][2] = 1.5; */ /* X0[i][0] = 2.5*((double) random()/RAND_MAX); X0[i][1] = -5; X0[i][2] = -1+3.0*((double) random()/RAND_MAX); */ X0[i][0] = 1.; X0[i][1] = -10 + 12*((double) random()/RAND_MAX); X0[i][2] = -1+3.0*((double) random()/RAND_MAX); } bifd->SetMode(IC); bifd->SetInitialConditions(nX0,X0); bifd->ComputeDiagram(); bifd->SaveSummaryData("hr-basin.classified"); bifd->Destroy(); hr->Destroy(); par->Destroy(); return 0; }
31.377778
82
0.621459
danielelinaro
46fbdb4f601bffcca5874cf6df7c961fe59c9af8
1,342
cc
C++
packager/media/base/proto_json_util.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1,288
2016-05-25T01:20:31.000Z
2022-03-02T23:56:56.000Z
packager/media/base/proto_json_util.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
894
2016-05-17T00:39:30.000Z
2022-03-02T18:46:21.000Z
packager/media/base/proto_json_util.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
400
2016-05-25T01:20:35.000Z
2022-03-03T02:12:00.000Z
// Copyright 2018 Google LLC. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "packager/media/base/proto_json_util.h" #include <google/protobuf/util/json_util.h> #include "packager/base/logging.h" namespace shaka { namespace media { std::string MessageToJsonString(const google::protobuf::Message& message) { google::protobuf::util::JsonPrintOptions json_print_options; json_print_options.preserve_proto_field_names = true; std::string result; GOOGLE_CHECK_OK(google::protobuf::util::MessageToJsonString( message, &result, json_print_options)); return result; } bool JsonStringToMessage(const std::string& input, google::protobuf::Message* message) { google::protobuf::util::JsonParseOptions json_parse_options; json_parse_options.ignore_unknown_fields = true; auto status = google::protobuf::util::JsonStringToMessage(input, message, json_parse_options); if (!status.ok()) { LOG(ERROR) << "Failed to parse from JSON: " << input << " error: " << status.error_message(); return false; } return true; } } // namespace media } // namespace shaka
31.209302
80
0.68927
koln67
46fc87995f5fde8b171405aa8a3901dc788264c8
1,186
cpp
C++
SRC/2018ICPC/Web_XuZhou/H.cpp
YouDad/ACM
ac26e0b360267943af32692629d6c34e739ee70d
[ "MIT" ]
2
2018-07-27T08:09:48.000Z
2018-09-26T16:36:37.000Z
SRC/2018ICPC/Web_XuZhou/H.cpp
YouDad/ACM
ac26e0b360267943af32692629d6c34e739ee70d
[ "MIT" ]
null
null
null
SRC/2018ICPC/Web_XuZhou/H.cpp
YouDad/ACM
ac26e0b360267943af32692629d6c34e739ee70d
[ "MIT" ]
null
null
null
// https://nanti.jisuanke.com/t/31460 #include<stdio.h> #include<string.h> typedef long long ll; const int maxn=100005; ll arr[(1<<18)+2],iarr[(1<<18)+2],M; void update(ll*a,int x,ll val){ for(a[x+=M]=val,x/=2;x;x/=2) a[x]=a[2*x]+a[2*x+1]; } ll query(ll*a,int l,int r){ ll ans=0; for(l+=M-1,r+=M+1;l^r^1;l/=2,r/=2){ if(~l&1)ans+=a[l^1]; if( r&1)ans+=a[r^1]; } return ans; } int main(){ #ifdef LOCAL_DEBUG freopen("E:/ACM/SRC/1.txt","r",stdin); #endif for(int n,q;~scanf("%d%d",&n,&q);){ M=1;while(M-2<n)M*=2; for(int i=M+1;i<=M+n;i++) scanf("%lld",arr+i); for(int i=M+1;i<=M+n;i++) iarr[i]=arr[i]*(M+n+1-i); for(int i=M;i;i--) arr[i]=arr[i*2]+arr[i*2+1], iarr[i]=iarr[i*2]+iarr[i*2+1]; for(int op,l;q--;){ ll r; scanf("%d%d%lld",&op,&l,&r); if(op==1){ ll ret1=query(arr,l,r); ll ret2=query(iarr,l,r); printf("%lld\n",ret2-ret1*(n-r)); }else{ update(arr,l,r); update(iarr,l,(n+1-l)*r); } } } return 0; }
25.782609
49
0.436762
YouDad
46fd94f34eb507d75cdb0864c86d48bb91ffe0fc
1,936
cc
C++
app/oxs/base/lock.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
app/oxs/base/lock.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
app/oxs/base/lock.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
/* FILE: lock.cc -*-Mode: c++-*- * * Data structure locking class * */ #include "oc.h" #include "lock.h" #include "oxsexcept.h" OC_USE_STD_NAMESPACE; // Specify std namespace, if supported /* End includes */ OC_UINT4m Oxs_Lock::id_count=0; Oxs_Lock::~Oxs_Lock() { if(write_lock>0) OXS_THROW(Oxs_BadLock,"Delete with open write lock"); if(read_lock>0) OXS_THROW(Oxs_BadLock,"Delete with open read lock(s)"); if(dep_lock>0) OXS_THROW(Oxs_BadLock,"Delete with open dep lock(s)"); obj_id=0; } // Assignment operator does not copy lock counts, but // does check access restrictions. obj_id is copied // if there are no outstanding locks and obj_id>0. Oxs_Lock& Oxs_Lock::operator=(const Oxs_Lock& other) { if(read_lock>0) OXS_THROW(Oxs_BadLock,"Assignment attempt over open read lock(s)"); if(write_lock==0) { // This is the no-lock situation if(other.obj_id!=0) { obj_id = other.obj_id; } else { // Take the next valid id if((obj_id = ++id_count)==0) { obj_id = ++id_count; // Safety // Wrap around. For now make this fatal. OXS_THROW(Oxs_BadLock,"Lock count id overflow."); } } } // if write_lock>0, then presumably obj_id is already 0. return *this; } OC_BOOL Oxs_Lock::SetDepLock() { ++dep_lock; return 1; } OC_BOOL Oxs_Lock::ReleaseDepLock() { if(dep_lock<1) return 0; --dep_lock; return 1; } OC_BOOL Oxs_Lock::SetReadLock() { if(write_lock) return 0; ++read_lock; return 1; } OC_BOOL Oxs_Lock::ReleaseReadLock() { if(read_lock<1) return 0; --read_lock; return 1; } OC_BOOL Oxs_Lock::SetWriteLock() { if(read_lock>0 || write_lock>0) return 0; write_lock=1; obj_id=0; return 1; } OC_BOOL Oxs_Lock::ReleaseWriteLock() { if(write_lock!=1) return 0; if((obj_id = ++id_count)==0) { // Wrap around. Might want to issue a warning. obj_id = ++id_count; } write_lock=0; return 1; }
19.555556
71
0.658058
ViennaNovoFlop
46fe7414e6a5c9bc077c601133632078f87b21aa
6,197
cc
C++
libsrc/pylith/faults/FaultCohesiveTract.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
1
2021-01-20T17:18:28.000Z
2021-01-20T17:18:28.000Z
libsrc/pylith/faults/FaultCohesiveTract.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
libsrc/pylith/faults/FaultCohesiveTract.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "FaultCohesiveTract.hh" // implementation of object methods #include "CohesiveTopology.hh" // USES CohesiveTopology #include "pylith/topology/Fields.hh" // USES Fields #include "pylith/topology/Field.hh" // USES Field #include "pylith/topology/Stratum.hh" // USES StratumIS #include "pylith/feassemble/Quadrature.hh" // USES Quadrature #include <cassert> // USES assert() #include <sstream> // USES std::ostringstream #include <stdexcept> // USES std::runtime_error // ---------------------------------------------------------------------- // Default constructor. pylith::faults::FaultCohesiveTract::FaultCohesiveTract(void) { // constructor _useLagrangeConstraints = false; } // constructor // ---------------------------------------------------------------------- // Destructor. pylith::faults::FaultCohesiveTract::~FaultCohesiveTract(void) { // destructor deallocate(); } // destructor // ---------------------------------------------------------------------- // Deallocate PETSc and local data structures. void pylith::faults::FaultCohesiveTract::deallocate(void) { // deallocate PYLITH_METHOD_BEGIN; FaultCohesive::deallocate(); PYLITH_METHOD_END; } // deallocate // ---------------------------------------------------------------------- // Initialize fault. Determine orientation and setup boundary void pylith::faults::FaultCohesiveTract::initialize(const topology::Mesh& mesh, const PylithScalar upDir[3]) { // initialize PYLITH_METHOD_BEGIN; assert(upDir); assert(_quadrature); delete _faultMesh; _faultMesh = new topology::Mesh(); CohesiveTopology::createFaultParallel(_faultMesh, mesh, id(), label(), useLagrangeConstraints()); // Reset fields. delete _fields; _fields = new topology::Fields(*_faultMesh);assert(_fields); // Initialize quadrature geometry. _quadrature->initializeGeometry(); PYLITH_METHOD_END; } // initialize // ---------------------------------------------------------------------- // Integrate contribution of cohesive cells to residual term. void pylith::faults::FaultCohesiveTract::integrateResidual(const topology::Field& residual, const PylithScalar t, topology::SolutionFields* const fields) { // integrateResidual throw std::logic_error("FaultCohesiveTract::integrateResidual() not implemented."); } // integrateResidual // ---------------------------------------------------------------------- // Compute Jacobian matrix (A) associated with operator. void pylith::faults::FaultCohesiveTract::integrateJacobian(topology::Jacobian* jacobian, const PylithScalar t, topology::SolutionFields* const fields) { // integrateJacobian throw std::logic_error("FaultCohesiveTract::integrateJacobian() not implemented."); _needNewJacobian = false; } // integrateJacobian // ---------------------------------------------------------------------- // Verify configuration is acceptable. void pylith::faults::FaultCohesiveTract::verifyConfiguration(const topology::Mesh& mesh) const { // verifyConfiguration PYLITH_METHOD_BEGIN; assert(_quadrature); const PetscDM dmMesh = mesh.dmMesh();assert(dmMesh); PetscBool hasLabel = PETSC_FALSE; PetscErrorCode err = DMHasLabel(dmMesh, label(), &hasLabel);PYLITH_CHECK_ERROR(err); if (!hasLabel) { std::ostringstream msg; msg << "Mesh missing group of vertices '" << label() << " for boundary condition."; throw std::runtime_error(msg.str()); } // if // check compatibility of mesh and quadrature scheme const int dimension = mesh.dimension()-1; if (_quadrature->cellDim() != dimension) { std::ostringstream msg; msg << "Dimension of reference cell in quadrature scheme (" << _quadrature->cellDim() << ") does not match dimension of cells in mesh (" << dimension << ") for fault '" << label() << "'."; throw std::runtime_error(msg.str()); } // if const int numCorners = _quadrature->refGeometry().numCorners(); const bool includeOnlyCells = true; topology::StratumIS cohesiveIS(dmMesh, "material-id", id(), includeOnlyCells); const PetscInt* cells = cohesiveIS.points(); const PetscInt ncells = cohesiveIS.size(); PetscInt coneSize = 0; for (PetscInt i=0; i < ncells; ++i) { err = DMPlexGetConeSize(dmMesh, cells[i], &coneSize);PYLITH_CHECK_ERROR(err); // TODO: Should be changed to Closure() if (2*numCorners != coneSize) { // No Lagrange vertices, just negative and positive sides of the // fault, so coneSize is 2*numCorners. std::ostringstream msg; msg << "Number of vertices in reference cell (" << numCorners << ") is not compatible with number of vertices (" << coneSize << ") in cohesive cell " << cells[i] << " for fault '" << label() << "'."; throw std::runtime_error(msg.str()); } // if } // for PYLITH_METHOD_END; } // verifyConfiguration // ---------------------------------------------------------------------- // Get vertex field associated with integrator. const pylith::topology::Field& pylith::faults::FaultCohesiveTract::vertexField(const char* name, const topology::SolutionFields* fields) { // vertexField throw std::logic_error("FaultCohesiveTract::vertexField() not implemented."); } // vertexField // ---------------------------------------------------------------------- // Get cell field associated with integrator. const pylith::topology::Field& pylith::faults::FaultCohesiveTract::cellField(const char* name, const topology::SolutionFields* fields) { // cellField throw std::logic_error("FaultCohesiveTract::cellField() not implemented."); } // cellField // End of file
34.237569
99
0.619977
joegeisz
46ffcc9c9c990a00d3ce0571090b9f9ef3d5f5e1
507
cpp
C++
p205/p205.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
1
2019-10-07T05:00:21.000Z
2019-10-07T05:00:21.000Z
p205/p205.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
null
null
null
p205/p205.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
null
null
null
class Solution { public: bool isIsomorphic(string s, string t) { if (s.length() != t.length()) return false; int n = s.length(); vector<char> from(260,'#'),to(260,'#'); for (int i = 0; i < n; ++i) { if (from[t[i]] == '#' && to[s[i]] == '#') { from[t[i]] = s[i]; to[s[i]] = t[i]; } else if (from[t[i]] != s[i] || to[s[i]] != t[i]) return false; } return true; } };
22.043478
52
0.368836
suzyz
2000447c0fe485a0d3201f67bb26167f3660ef5a
1,036
cpp
C++
platform/android/src/geojson/point.cpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
316
2021-02-05T10:34:35.000Z
2022-03-23T21:58:39.000Z
platform/android/src/geojson/point.cpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
187
2021-02-11T10:39:30.000Z
2022-03-31T21:59:47.000Z
platform/android/src/geojson/point.cpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
93
2021-02-04T09:39:14.000Z
2022-03-31T04:03:56.000Z
#include "point.hpp" namespace mbgl { namespace android { namespace geojson { jni::Local<jni::Object<Point>> Point::New(jni::JNIEnv& env, const mbgl::Point<double>& point) { static auto& javaClass = jni::Class<Point>::Singleton(env); static auto method = javaClass.GetStaticMethod<jni::Object<Point> (jni::jdouble, jni::jdouble)>(env, "fromLngLat"); return javaClass.Call(env, method, point.x, point.y); } mbgl::Point<double> Point::convert(jni::JNIEnv &env, const jni::Object<Point>& jPoint) { static auto& javaClass = jni::Class<Point>::Singleton(env); static auto longitude = javaClass.GetMethod<jni::jdouble ()>(env, "longitude"); static auto latitude = javaClass.GetMethod<jni::jdouble ()>(env, "latitude"); if (!jPoint) { return {}; } return { jPoint.Call(env, longitude), jPoint.Call(env, latitude) }; } void Point::registerNative(jni::JNIEnv &env) { jni::Class<Point>::Singleton(env); } } // namespace geojson } // namespace android } // namespace mbgl
29.6
119
0.666023
mueschm
200102719300a9f6475e961079b2674f4ca4c645
781
cpp
C++
c/tests/max_points_on_a_line_test.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
4
2018-03-05T02:27:16.000Z
2021-03-15T14:19:44.000Z
c/tests/max_points_on_a_line_test.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
null
null
null
c/tests/max_points_on_a_line_test.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
2
2018-07-22T10:32:10.000Z
2018-10-20T03:14:28.000Z
#include <gtest/gtest.h> extern "C" { #include "max_points_on_a_line.h" } #define ARR_SIZE(a) (sizeof(a) / sizeof((a)[0])) typedef struct Point point; static point point_create(int x, int y) { point p; p.x = x; p.y = y; return p; } TEST(max_points_on_a_line_test, maxPoints_149_1) { point points1[] = { point_create(1, 1), point_create(2, 2), point_create(3, 3) }; EXPECT_EQ(maxPoints_149_1(points1, ARR_SIZE(points1)), 3); point points2[] = { point_create(1, 1), point_create(3, 2), point_create(5, 3), point_create(4, 1), point_create(2, 3), point_create(1, 4) }; EXPECT_EQ(maxPoints_149_1(points2, ARR_SIZE(points2)), 4); }
21.694444
62
0.568502
qianbinbin
20018b19d78840a26a6af63ad75e218a8eba73cd
5,266
cc
C++
third_party/blink/renderer/modules/mediastream/input_device_info.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/modules/mediastream/input_device_info.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/modules/mediastream/input_device_info.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/mediastream/input_device_info.h" #include <algorithm> #include "third_party/blink/renderer/modules/mediastream/media_track_capabilities.h" namespace blink { namespace { // TODO(c.padhi): Merge this method with ToWebFacingMode() in // media_stream_constraints_util_video_device.h, see https://crbug.com/821668. WebMediaStreamTrack::FacingMode ToWebFacingMode(mojom::FacingMode facing_mode) { switch (facing_mode) { case mojom::FacingMode::NONE: return WebMediaStreamTrack::FacingMode::kNone; case mojom::FacingMode::USER: return WebMediaStreamTrack::FacingMode::kUser; case mojom::FacingMode::ENVIRONMENT: return WebMediaStreamTrack::FacingMode::kEnvironment; case mojom::FacingMode::LEFT: return WebMediaStreamTrack::FacingMode::kLeft; case mojom::FacingMode::RIGHT: return WebMediaStreamTrack::FacingMode::kRight; } NOTREACHED(); return WebMediaStreamTrack::FacingMode::kNone; } } // namespace InputDeviceInfo* InputDeviceInfo::Create(const String& device_id, const String& label, const String& group_id, MediaDeviceType device_type) { return new InputDeviceInfo(device_id, label, group_id, device_type); } InputDeviceInfo::InputDeviceInfo(const String& device_id, const String& label, const String& group_id, MediaDeviceType device_type) : MediaDeviceInfo(device_id, label, group_id, device_type) {} void InputDeviceInfo::SetVideoInputCapabilities( mojom::blink::VideoInputDeviceCapabilitiesPtr video_input_capabilities) { DCHECK_EQ(deviceId(), video_input_capabilities->device_id); // TODO(c.padhi): Merge the common logic below with // ComputeCapabilitiesForVideoSource() in media_stream_constraints_util.h, see // https://crbug.com/821668. platform_capabilities_.facing_mode = ToWebFacingMode(video_input_capabilities->facing_mode); if (!video_input_capabilities->formats.IsEmpty()) { int max_width = 1; int max_height = 1; float min_frame_rate = 1.0f; float max_frame_rate = min_frame_rate; for (const auto& format : video_input_capabilities->formats) { max_width = std::max(max_width, format->frame_size.width); max_height = std::max(max_height, format->frame_size.height); max_frame_rate = std::max(max_frame_rate, format->frame_rate); } platform_capabilities_.width = {1, max_width}; platform_capabilities_.height = {1, max_height}; platform_capabilities_.aspect_ratio = {1.0 / max_height, static_cast<double>(max_width)}; platform_capabilities_.frame_rate = {min_frame_rate, max_frame_rate}; } } void InputDeviceInfo::getCapabilities(MediaTrackCapabilities& capabilities) { // If label is null, permissions have not been given and no capabilities // should be returned. if (label().IsEmpty()) return; capabilities.setDeviceId(deviceId()); capabilities.setGroupId(groupId()); if (DeviceType() == MediaDeviceType::MEDIA_AUDIO_INPUT) { capabilities.setEchoCancellation({true, false}); capabilities.setAutoGainControl({true, false}); capabilities.setNoiseSuppression({true, false}); } if (DeviceType() == MediaDeviceType::MEDIA_VIDEO_INPUT) { if (!platform_capabilities_.width.empty()) { LongRange width; width.setMin(platform_capabilities_.width[0]); width.setMax(platform_capabilities_.width[1]); capabilities.setWidth(width); } if (!platform_capabilities_.height.empty()) { LongRange height; height.setMin(platform_capabilities_.height[0]); height.setMax(platform_capabilities_.height[1]); capabilities.setHeight(height); } if (!platform_capabilities_.aspect_ratio.empty()) { DoubleRange aspect_ratio; aspect_ratio.setMin(platform_capabilities_.aspect_ratio[0]); aspect_ratio.setMax(platform_capabilities_.aspect_ratio[1]); capabilities.setAspectRatio(aspect_ratio); } if (!platform_capabilities_.frame_rate.empty()) { DoubleRange frame_rate; frame_rate.setMin(platform_capabilities_.frame_rate[0]); frame_rate.setMax(platform_capabilities_.frame_rate[1]); capabilities.setFrameRate(frame_rate); } Vector<String> facing_mode; switch (platform_capabilities_.facing_mode) { case WebMediaStreamTrack::FacingMode::kUser: facing_mode.push_back("user"); break; case WebMediaStreamTrack::FacingMode::kEnvironment: facing_mode.push_back("environment"); break; case WebMediaStreamTrack::FacingMode::kLeft: facing_mode.push_back("left"); break; case WebMediaStreamTrack::FacingMode::kRight: facing_mode.push_back("right"); break; case WebMediaStreamTrack::FacingMode::kNone: break; } capabilities.setFacingMode(facing_mode); } } } // namespace blink
38.720588
84
0.701101
zipated
2002db0faa04c7cbb83a2d9acf6bcb78b4a028bd
2,966
cpp
C++
06-class-design/readerEx.06.06/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
81
2018-11-15T21:23:19.000Z
2022-03-06T09:46:36.000Z
06-class-design/readerEx.06.06/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
null
null
null
06-class-design/readerEx.06.06/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
41
2018-11-15T21:23:24.000Z
2022-02-24T03:02:26.000Z
// TODO: FIX ME! Does not handle delta between dates correctly. // // main.cpp // // This program exercises the Calendar interface exported in calendar.h. // // -------------------------------------------------------------------------- // Attribution: "Programming Abstractions in C++" by Eric Roberts // Chapter 6, Exercise 6 // Stanford University, Autumn Quarter 2012 // http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1136/materials/CS106BX-Reader.pdf // -------------------------------------------------------------------------- // // Created by Glenn Streiff on 12/17/15. // Copyright © 2015 Glenn Streiff. All rights reserved. // #include <iostream> #include "calendar.h" const std::string HEADER = "CS106B Programming Abstractions in C++: Ex 6.6\n"; const std::string DETAIL = "Extend the calendar.h interface even more."; const std::string BANNER = HEADER + DETAIL; int main(int argc, char * argv[]) { std::cout << BANNER << std::endl << std::endl; Date moonLanding1(JULY, 20, 1969); Date moonLanding2(20, JULY, 1969); Date earlier(JULY, 20, 1969); Date sameAsEarlier(JULY, 20, 1969); Date later(JULY, 21, 1969); Date later2(AUGUST, 19, 1969); if (earlier < later) { std::cout << "[PASS] " << earlier << " is earlier than " << later << std::endl; } else { std::cout << "[FAIL] " << earlier << " is later than " << later << std::endl; } if (earlier < later2) { std::cout << "[PASS] " << earlier << " is earlier than " << later2 << std::endl; } else { std::cout << "[FAIL] " << earlier << " is later than " << later2 << std::endl; } if (earlier == sameAsEarlier) { std::cout << "[PASS] " << earlier << " is same as " << sameAsEarlier << std::endl; } else { std::cout << "[FAIL] " << earlier << " is later than " << sameAsEarlier << std::endl; } if (later > earlier) { std::cout << "[PASS] " << later << " is later than " << earlier << std::endl; } else { std::cout << "[FAIL] " << later << " is earlier than " << earlier << std::endl; } if (earlier != later) { std::cout << "[PASS] " << earlier << " is not equal to " << later << std::endl; } else { std::cout << "[FAIL] " << earlier << " is equal to " << later << std::endl; } // Add overloaded '<<' operator. std::cout << std::endl << moonLanding1 << std::endl; std::cout << moonLanding2 << std::endl; Date date(DECEMBER, 31, 1898); //Date date(FEBRUARY, 28, 1900); std::cout << toEpochDay(date) << std::endl; std::cout << toDate(1) << std::endl; std::cout << toDate(2) << std::endl; std::cout << toDate(0) << std::endl; std::cout << toDate(-1) << std::endl; return 0; }
31.892473
91
0.50472
heavy3
200ad447b6ce9a7cbfba11e1533a560bb8b364fc
8,702
cpp
C++
Geometry/Geomlib_TriMeshPlaneIntersection.cpp
elix22/IogramSource
3a4ce55d94920e060776b4aa4db710f57a4280bc
[ "MIT" ]
28
2017-03-01T04:09:18.000Z
2022-02-01T13:33:50.000Z
Geometry/Geomlib_TriMeshPlaneIntersection.cpp
elix22/IogramSource
3a4ce55d94920e060776b4aa4db710f57a4280bc
[ "MIT" ]
3
2017-03-09T05:22:49.000Z
2017-08-02T18:38:05.000Z
Geometry/Geomlib_TriMeshPlaneIntersection.cpp
elix22/IogramSource
3a4ce55d94920e060776b4aa4db710f57a4280bc
[ "MIT" ]
17
2017-03-01T14:00:01.000Z
2022-02-08T06:36:54.000Z
// // Copyright (c) 2016 - 2017 Mesh Consultants Inc. // 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 "Geomlib_TriMeshPlaneIntersection.h" #include <assert.h> #include "TriMesh.h" #include "Geomlib_RemoveDuplicates.h" namespace { using Urho3D::Vector; using Urho3D::Vector3; typedef Vector<Vector3> tri_; const double kSmallNum = 0.00000001; // Inputs: // tri: stores 3 vertices of the triangle // point, normal: point and normal defining the plane // Outputs: // num_normal_side: number of vertices on same side of plane as normal (vertices inside plane are counted here) // num_non_normal_side: number of vertices on opposite side of plane as normal void TriVertexSplit( const tri_& tri, const Vector3& point, const Vector3& normal, int& num_normal_side, int& num_non_normal_side ) { if (tri.Size() != 3) { // invalid triangle return; } num_normal_side = 0; num_non_normal_side = 0; for (int i = 0; i < 3; ++i) { Vector3 w = tri[i] - point; float val = w.DotProduct(normal); if (val >= 0) { ++num_normal_side; } else { ++num_non_normal_side; } } //assert(num_normal_side + num_non_normal_side == 3); } // Stores vertices v0, v1, v2 as triangle tri. void PushVertsOntoTri( const Vector3& v0, const Vector3& v1, const Vector3& v2, tri_& tri ) { tri.Push(v0); tri.Push(v1); tri.Push(v2); } // Outputs: // t: If there is a unique intersection, it is: (1 - t) * A + t * B // Returns: // 0: 0 intersection points // 1: 1 intersection point // 2: segment lies inside plane int SegmentPlaneIntersection( const Vector3& A, const Vector3& B, const Vector3& P, const Vector3& N, float& t ) { Vector3 U = B - A; Vector3 W = A - P; float dd = N.DotProduct(U); float nn = -1 * N.DotProduct(W); if (abs(dd) < kSmallNum) { if (abs(nn) < kSmallNum) { return 2; // segment lies in plane } else { return 0; // segment is parallel to plane but outside plane } } float sI = nn / dd; if (sI < 0 || sI > 1) { return 0; // intersection occurs beyond segment } t = sI; return 1; } // Preconditions: // (1) tri has exactly 2 vertices on normal side of plane (normal side includes inside plane) and 1 vertex on non-normal side of plane. // TriVertexSplit (above) can be used to confirm this condition. // Inputs: // tri: triangle being split // P, N: point and normal of plane // Outputs: // w0, w1: Store coordinates of the 2 vertices on normal side of plane. // w2: Stores coordinates of the 1 vertex on non-normal side of plane. // w3: Stores coordinates of edge [w0, w2] intersection with plane. // w4: Stores coordinates of edge [w1, w2] intersection with plane. // Postcondition: // (1) Triangle [w0, w1, w2] has the same orientation as tri. void TriPlaneIntersection_aux( const tri_& tri, const Vector3& P, const Vector3& N, Vector3& w0, Vector3& w1, Vector3& w2, Vector3& w3, Vector3& w4 ) { //assert(tri.Size() == 3); if (tri.Size() != 3) { return; } Vector<int> normal_side_indices, non_normal_side_indices; for (int i = 0; i < 3; ++i) { Vector3 v = tri[i]; Vector3 w = v - P; float val = w.DotProduct(N); if (val >= 0) { normal_side_indices.Push(i); } else { non_normal_side_indices.Push(i); } } if (normal_side_indices.Size() != 2 || non_normal_side_indices.Size() != 1) { // return; } //assert(normal_side_indices.Size() == 2 && non_normal_side_indices.Size() == 1); int ind = non_normal_side_indices[0]; if (ind == 0) { w0 = tri[1]; w1 = tri[2]; w2 = tri[0]; } else if (ind == 1) { w0 = tri[2]; w1 = tri[0]; w2 = tri[1]; } else if (ind == 2) { w0 = tri[0]; w1 = tri[1]; w2 = tri[2]; } float t; int flag = SegmentPlaneIntersection(w0, w2, P, N, t); int num_intersections = 0; if (flag == 1) { w3 = (1 - t) * w0 + t * w2; ++num_intersections; } flag = SegmentPlaneIntersection(w1, w2, P, N, t); if (flag == 1) { w4 = (1 - t) * w1 + t * w2; ++num_intersections; } //assert(num_intersections == 2); } void TriPlaneIntersection( const tri_& tri, const Vector3& P, const Vector3& N, Vector<tri_>& normal_side_tris, Vector<tri_>& non_normal_side_tris ) { int num_normal_side = 0; int num_non_normal_side = 0; TriVertexSplit(tri, P, N, num_normal_side, num_non_normal_side); int total_verts = num_normal_side + num_non_normal_side; if (total_verts != 3) { // intersection failed return; } // 3 verts on one side of plane if (num_normal_side == 3) { normal_side_tris.Push(tri); } else if (num_non_normal_side == 3) { non_normal_side_tris.Push(tri); } // 2 verts on one side, 1 on the other if (num_non_normal_side == 1 || num_non_normal_side == 2) { Vector3 w0, w1, w2, w3, w4; if (num_non_normal_side == 1) { TriPlaneIntersection_aux(tri, P, N, w0, w1, w2, w3, w4); tri_ non_norm, norm_1, norm_2; //tri_ tri_nns_1, tri_nns_2, tri_ns_1; PushVertsOntoTri(w0, w1, w3, norm_1); PushVertsOntoTri(w3, w1, w4, norm_2); PushVertsOntoTri(w3, w4, w2, non_norm); normal_side_tris.Push(norm_1); normal_side_tris.Push(norm_2); non_normal_side_tris.Push(non_norm); } else if (num_non_normal_side == 2) { TriPlaneIntersection_aux(tri, P, -1 * N, w0, w1, w2, w3, w4); tri_ non_norm_1, non_norm_2, norm; //tri_ tri_ns_1, tri_ns_2, tri_nns_1; PushVertsOntoTri(w0, w1, w3, non_norm_1); PushVertsOntoTri(w3, w1, w4, non_norm_2); PushVertsOntoTri(w3, w4, w2, norm); non_normal_side_tris.Push(non_norm_1); non_normal_side_tris.Push(non_norm_2); normal_side_tris.Push(norm); } } } }; // namespace bool Geomlib::TriMeshPlaneIntersection( const Urho3D::Variant& mesh, const Urho3D::Vector3& point, const Urho3D::Vector3& normal, Urho3D::Variant& mesh_normal_side, Urho3D::Variant& mesh_non_normal_side ) { using Urho3D::Variant; using Urho3D::VariantVector; using Urho3D::Vector; // Verify mesh and extract required mesh data if (!TriMesh_Verify(mesh)) { return false; } VariantVector vertex_list = TriMesh_GetVertexList(mesh); VariantVector face_list = TriMesh_GetFaceList(mesh); // Verify normal is not the zero Vector3 if (!(normal.LengthSquared() > 0.0f)) { return false; } // Store two bags of triangles Vector<tri_> normal_side_tris; Vector<tri_> non_normal_side_tris; // Loop over faces, splitting each one for (unsigned i = 0; i < face_list.Size(); i += 3) { tri_ tri; int i0 = face_list[i].GetInt(); int i1 = face_list[i + 1].GetInt(); int i2 = face_list[i + 2].GetInt(); tri.Push(vertex_list[i0].GetVector3()); tri.Push(vertex_list[i1].GetVector3()); tri.Push(vertex_list[i2].GetVector3()); TriPlaneIntersection( tri, point, normal, normal_side_tris, non_normal_side_tris ); } // Reconstruct normal side mesh from normal side bag of triangles Vector<Vector3> ns_vertex_list; for (unsigned i = 0; i < normal_side_tris.Size(); ++i) { tri_ tri = normal_side_tris[i]; ns_vertex_list.Push(tri[0]); ns_vertex_list.Push(tri[1]); ns_vertex_list.Push(tri[2]); } Variant ns_vertices, ns_faces; RemoveDuplicates(ns_vertex_list, ns_vertices, ns_faces); mesh_normal_side = TriMesh_Make(ns_vertices, ns_faces); // Reconstruct non-normal side mesh from non-normal side bag of triangles Vector<Vector3> nns_vertex_list; for (unsigned i = 0; i < non_normal_side_tris.Size(); ++i) { tri_ tri = non_normal_side_tris[i]; nns_vertex_list.Push(tri[0]); nns_vertex_list.Push(tri[1]); nns_vertex_list.Push(tri[2]); } Variant nns_vertices, nns_faces; RemoveDuplicates(nns_vertex_list, nns_vertices, nns_faces); mesh_non_normal_side = TriMesh_Make(nns_vertices, nns_faces); return true; }
25.976119
137
0.688348
elix22
200ae272cc1adb37009bf64dc648c03075bdad2c
8,195
cpp
C++
src/rotoSolver/fileUtils.cpp
vinben/Rotopp
f0c25db5bd25074c55ff0f67539a2452d92aaf72
[ "Unlicense" ]
47
2016-07-27T07:22:06.000Z
2021-08-17T13:08:19.000Z
src/rotoSolver/fileUtils.cpp
vinben/Rotopp
f0c25db5bd25074c55ff0f67539a2452d92aaf72
[ "Unlicense" ]
1
2016-09-24T06:04:39.000Z
2016-09-25T10:34:19.000Z
src/rotoSolver/fileUtils.cpp
vinben/Rotopp
f0c25db5bd25074c55ff0f67539a2452d92aaf72
[ "Unlicense" ]
13
2016-07-27T10:44:35.000Z
2020-07-01T21:08:33.000Z
/************************************************************************** ** This file is a part of our work (Siggraph'16 paper, binary, code and dataset): ** ** Roto++: Accelerating Professional Rotoscoping using Shape Manifolds ** Wenbin Li, Fabio Viola, Jonathan Starck, Gabriel J. Brostow and Neill D.F. Campbell ** ** w.li AT cs.ucl.ac.uk ** http://visual.cs.ucl.ac.uk/pubs/rotopp ** ** Copyright (c) 2016, Wenbin Li ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are met: ** ** -- Redistributions of source code and data must retain the above ** copyright notice, this list of conditions and the following disclaimer. ** -- Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** ** THIS WORK AND THE RELATED SOFTWARE, SOURCE CODE AND DATA IS PROVIDED BY ** THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED ** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF ** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN ** NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ** INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, ** BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF ** USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, ** EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************/ #include "include/rotoSolver/fileUtils.hpp" #include "include/rotoSolver/eigenUtils.hpp" #include <gflags/gflags.h> #include <fstream> DECLARE_bool(use_planar_tracker_weights); // The missing string trim function - v. useful.. // Taken from http://www.codeproject.com/KB/stl/stdstringtrim.aspx void trim( string& str ) { string::size_type pos = str.find_last_not_of(' '); if (pos != string::npos) { str.erase(pos + 1); pos = str.find_first_not_of(' '); if (pos != string::npos) str.erase(0, pos); } else { str.erase(str.begin(), str.end()); } } void removeWhiteSpace(string& str) { trim(str); std::vector<char> charsToRemove({'\t', '\r', '\n'}); //for (const char c : charsToRemove) for (int i = 0; i < charsToRemove.size(); i++) { const char c = charsToRemove[i]; str.erase(std::remove(str.begin(), str.end(), c), str.end()); } trim(str); } string readLineFromFile(FilePtr& fp) { const int maxLen = 2048; char buffer[maxLen]; if(std::fgets(buffer, maxLen, fp)==NULL) cout << ""; buffer[maxLen-1] = '\0'; string line(buffer); removeWhiteSpace(line); return line; } void SaveSolverOutputFile(string textFilename, const Matrix& Data, const int startIdx, const int stopIdx) { const int NUM_VALUES_PER_ROTO_POINT = 6; int D = Data.cols(); nassert (remainder(D, NUM_VALUES_PER_ROTO_POINT) == 0); D /= NUM_VALUES_PER_ROTO_POINT; std::ofstream ofs(textFilename.c_str()); ofs << D << "\n"; ofs << startIdx << " " << stopIdx << "\n"; ofs << Data.transpose(); ofs.close(); std::cout << "Saved output to \"" << textFilename << "\"." << std::endl; } TrackingDataType TrackingDataTypeMapper(string str) { removeWhiteSpace(str); if (str.compare("forward") == 0) return ForwardPlanar; else if (str.compare("backward") == 0) return BackwardPlanar; else if (str.compare("point") == 0) return Point; return Unknown; } string TrackingDataTypeToString(const TrackingDataType& t) { switch (t) { case (ForwardPlanar): return "ForwardPlanar"; break; case (BackwardPlanar): return "BackwardPlanar"; break; case (Point): return "Point"; break; case (Unknown): default: return "Unknown"; break; } } PlanarTrackingData::PlanarTrackingData(string txtFilename) { DataType = Unknown; FilePtr fp(txtFilename.c_str(), "r"); OrigFileName = txtFilename; ShapeName = readLineFromFile(fp); KeyFrames.clear(); std::stringstream keyFramesStr(readLineFromFile(fp)); while (!keyFramesStr.eof()) { try { int i = -1; keyFramesStr >> i; if (i > 0) KeyFrames.push_back(i); } catch (...) {} } std::sort(KeyFrames.begin(), KeyFrames.end()); StartIndex = *(std::min_element(KeyFrames.begin(), KeyFrames.end())); EndIndex = *(std::max_element(KeyFrames.begin(), KeyFrames.end())); NumFrames = EndIndex - StartIndex + 1; //std::vector<int> ptID; std::vector<Eigen::VectorXd> data; std::stringstream sstream; int numFramesOfData = -1; while (!feof(fp)) { Eigen::VectorXd v(NumFrames); int pt = -1; int numRead = 0; std::stringstream s(readLineFromFile(fp)); s.exceptions(std::stringstream::failbit | std::stringstream::badbit); try { if (feof(fp)) { break; } s >> pt; if (pt < 0) { break; } for (int i = 0; i < NumFrames; ++i) { s >> v[i]; ++numRead; } if (s.bad()) { break; } } catch (...) { } if (numFramesOfData < 0) numFramesOfData = numRead; if (numRead == numFramesOfData) { PointIDs.push_back(pt); data.push_back(v.head(numFramesOfData)); } else { break; } } DataType = TrackingDataTypeMapper(sstream.str()); vdbg(DataType); vdbg(numFramesOfData); vdbg(data.size()); TrackingData.resize(numFramesOfData, data.size()); for(int i = 0; i < data.size(); i++){ Eigen::VectorXd v = data[i]; TrackingData.col(i) = v; } FrameWeights = Eigen::VectorXd::Ones(NumFrames); vdbg(FLAGS_use_planar_tracker_weights); if (FLAGS_use_planar_tracker_weights) { SetFrameWeights(); } } void PlanarTrackingData::SaveToOutputFile(const string textFilename) const { SaveSolverOutputFile(textFilename, TrackingData, StartIndex, EndIndex); } void PlanarTrackingData::SetFrameWeights() { typedef Eigen::Matrix<double, 1, 1> Vector1d; double startWeight = 0.0; double stopWeight = 0.0; switch (DataType) { case Unknown: case Point: return; break; case ForwardPlanar: startWeight = 1.0; stopWeight = 0.0; break; case BackwardPlanar: startWeight = 0.0; stopWeight = 1.0; break; } // REMEMBER TO TAKE THE SQUARING OF THE COST INTO ACCOUNT.. for (int i = 0, I = KeyFrames.size() - 1; i < I; ++i) { const int a = KeyFrames[i] - StartIndex; const int b = KeyFrames[i+1] - StartIndex; Interpolator<int> interp(a, b, Vector1d::Constant(startWeight), Vector1d::Constant(stopWeight)); for (int k = a+1; k < b; ++k) { nassert (k < NumFrames); FrameWeights.row(k) = interp.get(k); } } vdbg(FrameWeights.transpose()); } void PlanarTrackingData::Print() const { vdbg(ShapeName); vdbg(NumFrames); vdbg(StartIndex); vdbg(EndIndex); vdbg(TrackingData.rows()); vdbg(TrackingData.cols()); vdbg(TrackingData(0,0)); vdbg(TrackingData(0,1)); vdbg(TrackingData(1,0)); vdbg(TrackingData(TrackingData.rows()-1, TrackingData.cols()-1)); }
25.29321
104
0.587065
vinben
200aeed19c847f9e7f6959f2f19a9af7eee99f9e
2,251
cpp
C++
questions/68721681/app/main.cpp
xGreat/stackoverflow
b9a404a5c93eb764dc58a57484d7b86dc5016579
[ "MIT" ]
302
2017-03-04T00:05:23.000Z
2022-03-28T22:51:29.000Z
questions/68721681/app/main.cpp
xGreat/stackoverflow
b9a404a5c93eb764dc58a57484d7b86dc5016579
[ "MIT" ]
30
2017-12-02T19:26:43.000Z
2022-03-28T07:40:36.000Z
questions/68721681/app/main.cpp
xGreat/stackoverflow
b9a404a5c93eb764dc58a57484d7b86dc5016579
[ "MIT" ]
388
2017-07-04T16:53:12.000Z
2022-03-18T22:20:19.000Z
#include "foointerface.h" #include <QDir> #include <QGuiApplication> #include <QPluginLoader> #include <QQmlApplicationEngine> #include <QTimer> #include <QTranslator> int main(int argc, char *argv[]) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QGuiApplication app(argc, argv); QTranslator appTranslator; qDebug() << "appTranslator Loaded?:" << appTranslator.load(":/languages/app.qm"); QTranslator pluginTranslator; qDebug() << "pluginTranslator Loaded?:" << pluginTranslator.load(":/languages/plugin.qm"); FooInterface *fooInterface = nullptr; QDir pluginsDir(QCoreApplication::applicationDirPath()); #if defined(Q_OS_WIN) if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") pluginsDir.cdUp(); #elif defined(Q_OS_MAC) if (pluginsDir.dirName() == "MacOS") { pluginsDir.cdUp(); pluginsDir.cdUp(); pluginsDir.cdUp(); } #endif pluginsDir.cd("plugins"); const QStringList entries = pluginsDir.entryList(QDir::Files); for (const QString &fileName : entries) { QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName)); QObject *plugin = pluginLoader.instance(); if (plugin) { fooInterface = qobject_cast<FooInterface *>(plugin); if (fooInterface) break; pluginLoader.unload(); } } QTimer timer; QObject::connect(&timer, &QTimer::timeout, [fooInterface](){ qDebug() << fooInterface->print(); }); timer.start(1000); QQmlApplicationEngine engine; const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); QTimer::singleShot(1000, &engine, [&](){ QCoreApplication::instance()->installTranslator(&appTranslator); QCoreApplication::instance()->installTranslator(&pluginTranslator); engine.retranslate(); }); return app.exec(); }
30.013333
97
0.646379
xGreat
200d9fcf6cacbb73137ca211017c7b3b49bc9990
54,260
inl
C++
Code/Engine/Foundation/Basics/Platform/Android/AndroidJni.inl
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
703
2015-03-07T15:30:40.000Z
2022-03-30T00:12:40.000Z
Code/Engine/Foundation/Basics/Platform/Android/AndroidJni.inl
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
233
2015-01-11T16:54:32.000Z
2022-03-19T18:00:47.000Z
Code/Engine/Foundation/Basics/Platform/Android/AndroidJni.inl
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
101
2016-10-28T14:05:10.000Z
2022-03-30T19:00:59.000Z
struct ezJniModifiers { enum Enum { PUBLIC = 1, PRIVATE = 2, PROTECTED = 4, STATIC = 8, FINAL = 16, SYNCHRONIZED = 32, VOLATILE = 64, TRANSIENT = 128, NATIVE = 256, INTERFACE = 512, ABSTRACT = 1024, STRICT = 2048, }; }; ezJniObject::ezJniObject(jobject object, ezJniOwnerShip ownerShip) : m_class(nullptr) { switch (ownerShip) { case ezJniOwnerShip::OWN: m_object = object; m_own = true; break; case ezJniOwnerShip::COPY: m_object = ezJniAttachment::GetEnv()->NewLocalRef(object); m_own = true; break; case ezJniOwnerShip::BORROW: m_object = object; m_own = false; break; } } ezJniObject::ezJniObject(const ezJniObject& other) : m_class(nullptr) { m_object = ezJniAttachment::GetEnv()->NewLocalRef(other.m_object); m_own = true; } ezJniObject::ezJniObject(ezJniObject&& other) { m_object = other.m_object; m_class = other.m_class; m_own = other.m_own; other.m_object = nullptr; other.m_class = nullptr; other.m_own = false; } ezJniObject& ezJniObject::operator=(const ezJniObject& other) { if (this == &other) return *this; Reset(); m_object = ezJniAttachment::GetEnv()->NewLocalRef(other.m_object); m_own = true; return *this; } ezJniObject& ezJniObject::operator=(ezJniObject&& other) { if (this == &other) return *this; Reset(); m_object = other.m_object; m_class = other.m_class; m_own = other.m_own; other.m_object = nullptr; other.m_class = nullptr; other.m_own = false; return *this; } ezJniObject::~ezJniObject() { Reset(); } void ezJniObject::Reset() { if (m_object && m_own) { ezJniAttachment::GetEnv()->DeleteLocalRef(m_object); m_object = nullptr; m_own = false; } if (m_class) { ezJniAttachment::GetEnv()->DeleteLocalRef(m_class); m_class = nullptr; } } jobject ezJniObject::GetJObject() const { return m_object; } bool ezJniObject::operator==(const ezJniObject& other) const { return ezJniAttachment::GetEnv()->IsSameObject(m_object, other.m_object) == JNI_TRUE; } bool ezJniObject::operator!=(const ezJniObject& other) const { return !operator==(other); } // Template specializations to dispatch to the correct JNI method for each C++ type. template <typename T, bool unused = false> struct ezJniTraits { static_assert(unused, "The passed C++ type is not supported by the JNI wrapper. Arguments and returns types must be one of bool, signed char/jbyte, unsigned short/jchar, short/jshort, int/jint, long long/jlong, float/jfloat, double/jdouble, ezJniObject, ezJniString or ezJniClass."); // Places the argument inside a jvalue union. static jvalue ToValue(T); // Retrieves the Java class static type of the argument. For primitives, this is not the boxed type, but the primitive type. static ezJniClass GetStaticType(); // Retrieves the Java class dynamic type of the argument. For primitives, this is not the boxed type, but the primitive type. static ezJniClass GetRuntimeType(T); // Creates an invalid/null object to return in case of errors. static T GetEmptyObject(); // Call an instance method with the return type. template <typename... Args> static T CallInstanceMethod(jobject self, jmethodID method, const Args&... args); // Call a static method with the return type. template <typename... Args> static T CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); // Sets/gets a field of the type. static void SetField(jobject self, jfieldID field, T); static T GetField(jobject self, jfieldID field); // Sets/gets a static field of the type. static void SetStaticField(jclass clazz, jfieldID field, T); static T GetStaticField(jclass clazz, jfieldID field); // Appends the JNI type signature of this type to the string buf static bool AppendSignature(const T& obj, ezStringBuilder& str); static const char* GetSignatureStatic(); }; template <> struct ezJniTraits<bool> { static inline jvalue ToValue(bool value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(bool); static inline bool GetEmptyObject(); template <typename... Args> static bool CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static bool CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, bool arg); static inline bool GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, bool arg); static inline bool GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(bool, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jbyte> { static inline jvalue ToValue(jbyte value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jbyte); static inline jbyte GetEmptyObject(); template <typename... Args> static jbyte CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jbyte CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jbyte arg); static inline jbyte GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jbyte arg); static inline jbyte GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jbyte, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jchar> { static inline jvalue ToValue(jchar value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jchar); static inline jchar GetEmptyObject(); template <typename... Args> static jchar CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jchar CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jchar arg); static inline jchar GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jchar arg); static inline jchar GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jchar, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jshort> { static inline jvalue ToValue(jshort value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jshort); static inline jshort GetEmptyObject(); template <typename... Args> static jshort CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jshort CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jshort arg); static inline jshort GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jshort arg); static inline jshort GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jshort, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jint> { static inline jvalue ToValue(jint value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jint); static inline jint GetEmptyObject(); template <typename... Args> static jint CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jint CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jint arg); static inline jint GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jint arg); static inline jint GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jint, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jlong> { static inline jvalue ToValue(jlong value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jlong); static inline jlong GetEmptyObject(); template <typename... Args> static jlong CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jlong CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jlong arg); static inline jlong GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jlong arg); static inline jlong GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jlong, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jfloat> { static inline jvalue ToValue(jfloat value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jfloat); static inline jfloat GetEmptyObject(); template <typename... Args> static jfloat CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jfloat CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jfloat arg); static inline jfloat GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jfloat arg); static inline jfloat GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jfloat, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<jdouble> { static inline jvalue ToValue(jdouble value); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(jdouble); static inline jdouble GetEmptyObject(); template <typename... Args> static jdouble CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static jdouble CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, jdouble arg); static inline jdouble GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, jdouble arg); static inline jdouble GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(jdouble, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<ezJniObject> { static inline jvalue ToValue(const ezJniObject& object); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(const ezJniObject& object); static inline ezJniObject GetEmptyObject(); template <typename... Args> static ezJniObject CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static ezJniObject CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, const ezJniObject& arg); static inline ezJniObject GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, const ezJniObject& arg); static inline ezJniObject GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(const ezJniObject& obj, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<ezJniClass> { static inline jvalue ToValue(const ezJniClass& object); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(const ezJniClass& object); static inline ezJniClass GetEmptyObject(); template <typename... Args> static ezJniClass CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static ezJniClass CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, const ezJniClass& arg); static inline ezJniClass GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, const ezJniClass& arg); static inline ezJniClass GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(const ezJniClass& obj, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<ezJniString> { static inline jvalue ToValue(const ezJniString& object); static inline ezJniClass GetStaticType(); static inline ezJniClass GetRuntimeType(const ezJniString& object); static inline ezJniString GetEmptyObject(); template <typename... Args> static ezJniString CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static ezJniString CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline void SetField(jobject self, jfieldID field, const ezJniString& arg); static inline ezJniString GetField(jobject self, jfieldID field); static inline void SetStaticField(jclass clazz, jfieldID field, const ezJniString& arg); static inline ezJniString GetStaticField(jclass clazz, jfieldID field); static inline bool AppendSignature(const ezJniString& obj, ezStringBuilder& str); static inline const char* GetSignatureStatic(); }; template <> struct ezJniTraits<void> { static inline ezJniClass GetStaticType(); static inline void GetEmptyObject(); template <typename... Args> static void CallInstanceMethod(jobject self, jmethodID method, const Args&... args); template <typename... Args> static void CallStaticMethod(jclass clazz, jmethodID method, const Args&... args); static inline const char* GetSignatureStatic(); }; // Helpers to unpack variadic templates. struct ezJniImpl { static void CollectArgumentTypes(ezJniClass* target) { } template <typename T, typename... Tail> static void CollectArgumentTypes(ezJniClass* target, const T& arg, const Tail&... tail) { *target = ezJniTraits<T>::GetRuntimeType(arg); return ezJniImpl::CollectArgumentTypes(target + 1, tail...); } static void UnpackArgs(jvalue* target) { } template <typename T, typename... Tail> static void UnpackArgs(jvalue* target, const T& arg, const Tail&... tail) { *target = ezJniTraits<T>::ToValue(arg); return UnpackArgs(target + 1, tail...); } template <typename Ret, typename... Args> static bool BuildMethodSignature(ezStringBuilder& signature, const Args&... args) { signature.Append("("); if (!ezJniImpl::AppendSignature(signature, args...)) { return false; } signature.Append(")"); signature.Append(ezJniTraits<Ret>::GetSignatureStatic()); return true; } static bool AppendSignature(ezStringBuilder& signature) { return true; } template <typename T, typename... Tail> static bool AppendSignature(ezStringBuilder& str, const T& arg, const Tail&... tail) { return ezJniTraits<T>::AppendSignature(arg, str) && AppendSignature(str, tail...); } }; jvalue ezJniTraits<bool>::ToValue(bool value) { jvalue result; result.z = value ? JNI_TRUE : JNI_FALSE; return result; } ezJniClass ezJniTraits<bool>::GetStaticType() { return ezJniClass("java/lang/Boolean").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<bool>::GetRuntimeType(bool) { return GetStaticType(); } bool ezJniTraits<bool>::GetEmptyObject() { return false; } template <typename... Args> bool ezJniTraits<bool>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallBooleanMethodA(self, method, array) == JNI_TRUE; } template <typename... Args> bool ezJniTraits<bool>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticBooleanMethodA(clazz, method, array) == JNI_TRUE; } void ezJniTraits<bool>::SetField(jobject self, jfieldID field, bool arg) { return ezJniAttachment::GetEnv()->SetBooleanField(self, field, arg ? JNI_TRUE : JNI_FALSE); } bool ezJniTraits<bool>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetBooleanField(self, field) == JNI_TRUE; } void ezJniTraits<bool>::SetStaticField(jclass clazz, jfieldID field, bool arg) { return ezJniAttachment::GetEnv()->SetStaticBooleanField(clazz, field, arg ? JNI_TRUE : JNI_FALSE); } bool ezJniTraits<bool>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticBooleanField(clazz, field) == JNI_TRUE; } bool ezJniTraits<bool>::AppendSignature(bool, ezStringBuilder& str) { str.Append("Z"); return true; } const char* ezJniTraits<bool>::GetSignatureStatic() { return "Z"; } jvalue ezJniTraits<jbyte>::ToValue(jbyte value) { jvalue result; result.b = value; return result; } ezJniClass ezJniTraits<jbyte>::GetStaticType() { return ezJniClass("java/lang/Byte").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jbyte>::GetRuntimeType(jbyte) { return GetStaticType(); } jbyte ezJniTraits<jbyte>::GetEmptyObject() { return 0; } template <typename... Args> jbyte ezJniTraits<jbyte>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallByteMethodA(self, method, array); } template <typename... Args> jbyte ezJniTraits<jbyte>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticByteMethodA(clazz, method, array); } void ezJniTraits<jbyte>::SetField(jobject self, jfieldID field, jbyte arg) { return ezJniAttachment::GetEnv()->SetByteField(self, field, arg); } jbyte ezJniTraits<jbyte>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetByteField(self, field); } void ezJniTraits<jbyte>::SetStaticField(jclass clazz, jfieldID field, jbyte arg) { return ezJniAttachment::GetEnv()->SetStaticByteField(clazz, field, arg); } jbyte ezJniTraits<jbyte>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticByteField(clazz, field); } bool ezJniTraits<jbyte>::AppendSignature(jbyte, ezStringBuilder& str) { str.Append("B"); return true; } const char* ezJniTraits<jbyte>::GetSignatureStatic() { return "B"; } jvalue ezJniTraits<jchar>::ToValue(jchar value) { jvalue result; result.c = value; return result; } ezJniClass ezJniTraits<jchar>::GetStaticType() { return ezJniClass("java/lang/Character").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jchar>::GetRuntimeType(jchar) { return GetStaticType(); } jchar ezJniTraits<jchar>::GetEmptyObject() { return 0; } template <typename... Args> jchar ezJniTraits<jchar>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallCharMethodA(self, method, array); } template <typename... Args> jchar ezJniTraits<jchar>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticCharMethodA(clazz, method, array); } void ezJniTraits<jchar>::SetField(jobject self, jfieldID field, jchar arg) { return ezJniAttachment::GetEnv()->SetCharField(self, field, arg); } jchar ezJniTraits<jchar>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetCharField(self, field); } void ezJniTraits<jchar>::SetStaticField(jclass clazz, jfieldID field, jchar arg) { return ezJniAttachment::GetEnv()->SetStaticCharField(clazz, field, arg); } jchar ezJniTraits<jchar>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticCharField(clazz, field); } bool ezJniTraits<jchar>::AppendSignature(jchar, ezStringBuilder& str) { str.Append("C"); return true; } const char* ezJniTraits<jchar>::GetSignatureStatic() { return "C"; } jvalue ezJniTraits<jshort>::ToValue(jshort value) { jvalue result; result.s = value; return result; } ezJniClass ezJniTraits<jshort>::GetStaticType() { return ezJniClass("java/lang/Short").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jshort>::GetRuntimeType(jshort) { return GetStaticType(); } jshort ezJniTraits<jshort>::GetEmptyObject() { return 0; } template <typename... Args> jshort ezJniTraits<jshort>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallShortMethodA(self, method, array); } template <typename... Args> jshort ezJniTraits<jshort>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticShortMethodA(clazz, method, array); } void ezJniTraits<jshort>::SetField(jobject self, jfieldID field, jshort arg) { return ezJniAttachment::GetEnv()->SetShortField(self, field, arg); } jshort ezJniTraits<jshort>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetShortField(self, field); } void ezJniTraits<jshort>::SetStaticField(jclass clazz, jfieldID field, jshort arg) { return ezJniAttachment::GetEnv()->SetStaticShortField(clazz, field, arg); } jshort ezJniTraits<jshort>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticShortField(clazz, field); } bool ezJniTraits<jshort>::AppendSignature(jshort, ezStringBuilder& str) { str.Append("S"); return true; } const char* ezJniTraits<jshort>::GetSignatureStatic() { return "S"; } jvalue ezJniTraits<jint>::ToValue(jint value) { jvalue result; result.i = value; return result; } ezJniClass ezJniTraits<jint>::GetStaticType() { return ezJniClass("java/lang/Integer").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jint>::GetRuntimeType(jint) { return GetStaticType(); } jint ezJniTraits<jint>::GetEmptyObject() { return 0; } template <typename... Args> jint ezJniTraits<jint>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallIntMethodA(self, method, array); } template <typename... Args> jint ezJniTraits<jint>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticIntMethodA(clazz, method, array); } void ezJniTraits<jint>::SetField(jobject self, jfieldID field, jint arg) { return ezJniAttachment::GetEnv()->SetIntField(self, field, arg); } jint ezJniTraits<jint>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetIntField(self, field); } void ezJniTraits<jint>::SetStaticField(jclass clazz, jfieldID field, jint arg) { return ezJniAttachment::GetEnv()->SetStaticIntField(clazz, field, arg); } jint ezJniTraits<jint>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticIntField(clazz, field); } bool ezJniTraits<jint>::AppendSignature(jint, ezStringBuilder& str) { str.Append("I"); return true; } const char* ezJniTraits<jint>::GetSignatureStatic() { return "I"; } jvalue ezJniTraits<jlong>::ToValue(jlong value) { jvalue result; result.j = value; return result; } ezJniClass ezJniTraits<jlong>::GetStaticType() { return ezJniClass("java/lang/Long").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jlong>::GetRuntimeType(jlong) { return GetStaticType(); } jlong ezJniTraits<jlong>::GetEmptyObject() { return 0; } template <typename... Args> jlong ezJniTraits<jlong>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallLongMethodA(self, method, array); } template <typename... Args> jlong ezJniTraits<jlong>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticLongMethodA(clazz, method, array); } void ezJniTraits<jlong>::SetField(jobject self, jfieldID field, jlong arg) { return ezJniAttachment::GetEnv()->SetLongField(self, field, arg); } jlong ezJniTraits<jlong>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetLongField(self, field); } void ezJniTraits<jlong>::SetStaticField(jclass clazz, jfieldID field, jlong arg) { return ezJniAttachment::GetEnv()->SetStaticLongField(clazz, field, arg); } jlong ezJniTraits<jlong>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticLongField(clazz, field); } bool ezJniTraits<jlong>::AppendSignature(jlong, ezStringBuilder& str) { str.Append("J"); return true; } const char* ezJniTraits<jlong>::GetSignatureStatic() { return "J"; } jvalue ezJniTraits<jfloat>::ToValue(jfloat value) { jvalue result; result.f = value; return result; } ezJniClass ezJniTraits<jfloat>::GetStaticType() { return ezJniClass("java/lang/Float").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jfloat>::GetRuntimeType(jfloat) { return GetStaticType(); } jfloat ezJniTraits<jfloat>::GetEmptyObject() { return nanf(""); } template <typename... Args> jfloat ezJniTraits<jfloat>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallFloatMethodA(self, method, array); } template <typename... Args> jfloat ezJniTraits<jfloat>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticFloatMethodA(clazz, method, array); } void ezJniTraits<jfloat>::SetField(jobject self, jfieldID field, jfloat arg) { return ezJniAttachment::GetEnv()->SetFloatField(self, field, arg); } jfloat ezJniTraits<jfloat>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetFloatField(self, field); } void ezJniTraits<jfloat>::SetStaticField(jclass clazz, jfieldID field, jfloat arg) { return ezJniAttachment::GetEnv()->SetStaticFloatField(clazz, field, arg); } jfloat ezJniTraits<jfloat>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticFloatField(clazz, field); } bool ezJniTraits<jfloat>::AppendSignature(jfloat, ezStringBuilder& str) { str.Append("F"); return true; } const char* ezJniTraits<jfloat>::GetSignatureStatic() { return "F"; } jvalue ezJniTraits<jdouble>::ToValue(jdouble value) { jvalue result; result.d = value; return result; } ezJniClass ezJniTraits<jdouble>::GetStaticType() { return ezJniClass("java/lang/Double").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } ezJniClass ezJniTraits<jdouble>::GetRuntimeType(jdouble) { return GetStaticType(); } jdouble ezJniTraits<jdouble>::GetEmptyObject() { return nan(""); } template <typename... Args> jdouble ezJniTraits<jdouble>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallDoubleMethodA(self, method, array); } template <typename... Args> jdouble ezJniTraits<jdouble>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticDoubleMethodA(clazz, method, array); } void ezJniTraits<jdouble>::SetField(jobject self, jfieldID field, jdouble arg) { return ezJniAttachment::GetEnv()->SetDoubleField(self, field, arg); } jdouble ezJniTraits<jdouble>::GetField(jobject self, jfieldID field) { return ezJniAttachment::GetEnv()->GetDoubleField(self, field); } void ezJniTraits<jdouble>::SetStaticField(jclass clazz, jfieldID field, jdouble arg) { return ezJniAttachment::GetEnv()->SetStaticDoubleField(clazz, field, arg); } jdouble ezJniTraits<jdouble>::GetStaticField(jclass clazz, jfieldID field) { return ezJniAttachment::GetEnv()->GetStaticDoubleField(clazz, field); } bool ezJniTraits<jdouble>::AppendSignature(jdouble, ezStringBuilder& str) { str.Append("D"); return true; } const char* ezJniTraits<jdouble>::GetSignatureStatic() { return "D"; } jvalue ezJniTraits<ezJniObject>::ToValue(const ezJniObject& value) { jvalue result; result.l = value.GetHandle(); return result; } ezJniClass ezJniTraits<ezJniObject>::GetStaticType() { return ezJniClass("java/lang/Object"); } ezJniClass ezJniTraits<ezJniObject>::GetRuntimeType(const ezJniObject& arg) { return arg.GetClass(); } ezJniObject ezJniTraits<ezJniObject>::GetEmptyObject() { return ezJniObject(); } template <typename... Args> ezJniObject ezJniTraits<ezJniObject>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniObject(ezJniAttachment::GetEnv()->CallObjectMethodA(self, method, array), ezJniOwnerShip::OWN); } template <typename... Args> ezJniObject ezJniTraits<ezJniObject>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniObject(ezJniAttachment::GetEnv()->CallStaticObjectMethodA(clazz, method, array), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniObject>::SetField(jobject self, jfieldID field, const ezJniObject& arg) { return ezJniAttachment::GetEnv()->SetObjectField(self, field, arg.GetHandle()); } ezJniObject ezJniTraits<ezJniObject>::GetField(jobject self, jfieldID field) { return ezJniObject(ezJniAttachment::GetEnv()->GetObjectField(self, field), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniObject>::SetStaticField(jclass clazz, jfieldID field, const ezJniObject& arg) { return ezJniAttachment::GetEnv()->SetStaticObjectField(clazz, field, arg.GetHandle()); } ezJniObject ezJniTraits<ezJniObject>::GetStaticField(jclass clazz, jfieldID field) { return ezJniObject(ezJniAttachment::GetEnv()->GetStaticObjectField(clazz, field), ezJniOwnerShip::OWN); } bool ezJniTraits<ezJniObject>::AppendSignature(const ezJniObject& obj, ezStringBuilder& str) { if (obj.IsNull()) { // Ensure null objects never generate valid signatures in order to force using the reflection path return false; } else { str.Append("L"); str.Append(obj.GetClass().UnsafeCall<ezJniString>("getName", "()Ljava/lang/String;").GetData()); str.ReplaceAll(".", "/"); str.Append(";"); return true; } } const char* ezJniTraits<ezJniObject>::GetSignatureStatic() { return "Ljava/lang/Object;"; } jvalue ezJniTraits<ezJniClass>::ToValue(const ezJniClass& value) { jvalue result; result.l = value.GetHandle(); return result; } ezJniClass ezJniTraits<ezJniClass>::GetStaticType() { return ezJniClass("java/lang/Class"); } ezJniClass ezJniTraits<ezJniClass>::GetRuntimeType(const ezJniClass& arg) { // Assume there are no types derived from Class return GetStaticType(); } ezJniClass ezJniTraits<ezJniClass>::GetEmptyObject() { return ezJniClass(); } template <typename... Args> ezJniClass ezJniTraits<ezJniClass>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniClass(jclass(ezJniAttachment::GetEnv()->CallObjectMethodA(self, method, array)), ezJniOwnerShip::OWN); } template <typename... Args> ezJniClass ezJniTraits<ezJniClass>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniClass(jclass(ezJniAttachment::GetEnv()->CallStaticObjectMethodA(clazz, method, array)), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniClass>::SetField(jobject self, jfieldID field, const ezJniClass& arg) { return ezJniAttachment::GetEnv()->SetObjectField(self, field, arg.GetHandle()); } ezJniClass ezJniTraits<ezJniClass>::GetField(jobject self, jfieldID field) { return ezJniClass(jclass(ezJniAttachment::GetEnv()->GetObjectField(self, field)), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniClass>::SetStaticField(jclass clazz, jfieldID field, const ezJniClass& arg) { return ezJniAttachment::GetEnv()->SetStaticObjectField(clazz, field, arg.GetHandle()); } ezJniClass ezJniTraits<ezJniClass>::GetStaticField(jclass clazz, jfieldID field) { return ezJniClass(jclass(ezJniAttachment::GetEnv()->GetStaticObjectField(clazz, field)), ezJniOwnerShip::OWN); } bool ezJniTraits<ezJniClass>::AppendSignature(const ezJniClass& obj, ezStringBuilder& str) { str.Append("Ljava/lang/Class;"); return true; } const char* ezJniTraits<ezJniClass>::GetSignatureStatic() { return "Ljava/lang/Class;"; } jvalue ezJniTraits<ezJniString>::ToValue(const ezJniString& value) { jvalue result; result.l = value.GetHandle(); return result; } ezJniClass ezJniTraits<ezJniString>::GetStaticType() { return ezJniClass("java/lang/String"); } ezJniClass ezJniTraits<ezJniString>::GetRuntimeType(const ezJniString& arg) { // Assume there are no types derived from String return GetStaticType(); } ezJniString ezJniTraits<ezJniString>::GetEmptyObject() { return ezJniString(); } template <typename... Args> ezJniString ezJniTraits<ezJniString>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniString(jstring(ezJniAttachment::GetEnv()->CallObjectMethodA(self, method, array)), ezJniOwnerShip::OWN); } template <typename... Args> ezJniString ezJniTraits<ezJniString>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniString(jstring(ezJniAttachment::GetEnv()->CallStaticObjectMethodA(clazz, method, array)), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniString>::SetField(jobject self, jfieldID field, const ezJniString& arg) { return ezJniAttachment::GetEnv()->SetObjectField(self, field, arg.GetHandle()); } ezJniString ezJniTraits<ezJniString>::GetField(jobject self, jfieldID field) { return ezJniString(jstring(ezJniAttachment::GetEnv()->GetObjectField(self, field)), ezJniOwnerShip::OWN); } void ezJniTraits<ezJniString>::SetStaticField(jclass clazz, jfieldID field, const ezJniString& arg) { return ezJniAttachment::GetEnv()->SetStaticObjectField(clazz, field, arg.GetHandle()); } ezJniString ezJniTraits<ezJniString>::GetStaticField(jclass clazz, jfieldID field) { return ezJniString(jstring(ezJniAttachment::GetEnv()->GetStaticObjectField(clazz, field)), ezJniOwnerShip::OWN); } bool ezJniTraits<ezJniString>::AppendSignature(const ezJniString& obj, ezStringBuilder& str) { str.Append("Ljava/lang/String;"); return true; } const char* ezJniTraits<ezJniString>::GetSignatureStatic() { return "Ljava/lang/String;"; } ezJniClass ezJniTraits<void>::GetStaticType() { return ezJniClass("java/lang/Void").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;"); } void ezJniTraits<void>::GetEmptyObject() { return; } template <typename... Args> void ezJniTraits<void>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallVoidMethodA(self, method, array); } template <typename... Args> void ezJniTraits<void>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args) { jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniAttachment::GetEnv()->CallStaticVoidMethodA(clazz, method, array); } const char* ezJniTraits<void>::GetSignatureStatic() { return "V"; } template <typename... Args> ezJniObject ezJniClass::CreateInstance(const Args&... args) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return ezJniObject(); } const size_t N = sizeof...(args); ezJniClass inputTypes[N]; ezJniImpl::CollectArgumentTypes(inputTypes, args...); ezJniObject foundMethod = FindConstructor(*this, inputTypes, N); if (foundMethod.IsNull()) { return ezJniObject(); } jmethodID method = ezJniAttachment::GetEnv()->FromReflectedMethod(foundMethod.GetHandle()); jvalue array[sizeof...(args)]; ezJniImpl::UnpackArgs(array, args...); return ezJniObject(ezJniAttachment::GetEnv()->NewObjectA(GetHandle(), method, array), ezJniOwnerShip::OWN); } template <typename Ret, typename... Args> Ret ezJniClass::CallStatic(const char* name, const Args&... args) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return ezJniTraits<Ret>::GetEmptyObject(); } if (!GetJObject()) { ezLog::Error("Attempting to call static method '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } ezStringBuilder signature; if (ezJniImpl::BuildMethodSignature<Ret>(signature, args...)) { jmethodID method = ezJniAttachment::GetEnv()->GetStaticMethodID(GetHandle(), name, signature.GetData()); if (method) { return ezJniTraits<Ret>::CallStaticMethod(GetHandle(), method, args...); } else { ezJniAttachment::GetEnv()->ExceptionClear(); } } const size_t N = sizeof...(args); ezJniClass returnType = ezJniTraits<Ret>::GetStaticType(); ezJniClass inputTypes[N]; ezJniImpl::CollectArgumentTypes(inputTypes, args...); ezJniObject foundMethod = FindMethod(true, name, *this, returnType, inputTypes, N); if (foundMethod.IsNull()) { return ezJniTraits<Ret>::GetEmptyObject(); } jmethodID method = ezJniAttachment::GetEnv()->FromReflectedMethod(foundMethod.GetHandle()); return ezJniTraits<Ret>::CallStaticMethod(GetHandle(), method, args...); } template <typename Ret, typename... Args> Ret ezJniClass::UnsafeCallStatic(const char* name, const char* signature, const Args&... args) const { if (!GetJObject()) { ezLog::Error("Attempting to call static method '{}' on null class.", name); ezLog::Error("Attempting to call static method '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } jmethodID method = ezJniAttachment::GetEnv()->GetStaticMethodID(GetHandle(), name, signature); if (!method) { ezLog::Error("No such static method: '{}' with signature '{}' in class '{}'.", name, signature, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_METHOD); return ezJniTraits<Ret>::GetEmptyObject(); } else { return ezJniTraits<Ret>::CallStaticMethod(GetHandle(), method, args...); } } template <typename Ret> Ret ezJniClass::GetStaticField(const char* name) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return ezJniTraits<Ret>::GetEmptyObject(); } if (!GetJObject()) { ezLog::Error("Attempting to get static field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } jfieldID fieldID = ezJniAttachment::GetEnv()->GetStaticFieldID(GetHandle(), name, ezJniTraits<Ret>::GetSignatureStatic()); if (fieldID) { return ezJniTraits<Ret>::GetStaticField(GetHandle(), fieldID); } else { ezJniAttachment::GetEnv()->ExceptionClear(); } ezJniObject field = UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name)); if (ezJniAttachment::GetEnv()->ExceptionOccurred()) { ezJniAttachment::GetEnv()->ExceptionClear(); ezLog::Error("No field named '{}' found in class '{}'.", name, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } if ((field.UnsafeCall<jint>("getModifiers", "()I") & ezJniModifiers::STATIC) == 0) { ezLog::Error("Field named '{}' in class '{}' isn't static.", name, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;"); ezJniClass returnType = ezJniTraits<Ret>::GetStaticType(); if (!returnType.IsAssignableFrom(fieldType)) { ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned to return type '{}'.", name, fieldType.ToString().GetData(), ToString().GetData(), returnType.ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } return ezJniTraits<Ret>::GetStaticField(GetHandle(), ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle())); } template <typename Ret> Ret ezJniClass::UnsafeGetStaticField(const char* name, const char* signature) const { if (!GetJObject()) { ezLog::Error("Attempting to get static field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } jfieldID field = ezJniAttachment::GetEnv()->GetStaticFieldID(GetHandle(), name, signature); if (!field) { ezLog::Error("No such field: '{}' with signature '{}'.", name, signature); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } else { return ezJniTraits<Ret>::GetStaticField(GetHandle(), field); } } template <typename T> void ezJniClass::SetStaticField(const char* name, const T& arg) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return; } if (!GetJObject()) { ezLog::Error("Attempting to set static field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return; } ezJniObject field = UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name)); if (ezJniAttachment::GetEnv()->ExceptionOccurred()) { ezJniAttachment::GetEnv()->ExceptionClear(); ezLog::Error("No field named '{}' found in class '{}'.", name, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } ezJniClass modifierClass("java/lang/reflect/Modifier"); jint modifiers = field.UnsafeCall<jint>("getModifiers", "()I"); if ((modifiers & ezJniModifiers::STATIC) == 0) { ezLog::Error("Field named '{}' in class '{}' isn't static.", name, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } if ((modifiers & ezJniModifiers::FINAL) != 0) { ezLog::Error("Field named '{}' in class '{}' is final.", name, ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;"); ezJniClass argType = ezJniTraits<T>::GetRuntimeType(arg); if (argType.IsNull()) { if (fieldType.IsPrimitive()) { ezLog::Error("Field '{}' of type '{}' can't be assigned null because it is a primitive type.", name, fieldType.ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } } else { if (!fieldType.IsAssignableFrom(argType)) { ezLog::Error("Field '{}' of type '{}' can't be assigned from type '{}'.", name, fieldType.ToString().GetData(), argType.ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } } return ezJniTraits<T>::SetStaticField(GetHandle(), ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle()), arg); } template <typename T> void ezJniClass::UnsafeSetStaticField(const char* name, const char* signature, const T& arg) const { if (!GetJObject()) { ezLog::Error("Attempting to set static field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return; } jfieldID field = ezJniAttachment::GetEnv()->GetStaticFieldID(GetHandle(), name, signature); if (!field) { ezLog::Error("No such field: '{}' with signature '{}'.", name, signature); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } else { return ezJniTraits<T>::SetStaticField(GetHandle(), field, arg); } } template <typename Ret, typename... Args> Ret ezJniObject::Call(const char* name, const Args&... args) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return ezJniTraits<Ret>::GetEmptyObject(); } if (!m_object) { ezLog::Error("Attempting to call method '{}' on null object.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } // Fast path: Lookup method via signature built from parameters. // This only works for exact matches, but is roughly 50 times faster. ezStringBuilder signature; if (ezJniImpl::BuildMethodSignature<Ret>(signature, args...)) { jmethodID method = ezJniAttachment::GetEnv()->GetMethodID(reinterpret_cast<jclass>(GetClass().GetHandle()), name, signature.GetData()); if (method) { return ezJniTraits<Ret>::CallInstanceMethod(m_object, method, args...); } else { ezJniAttachment::GetEnv()->ExceptionClear(); } } // Fallback to slow path using reflection const size_t N = sizeof...(args); ezJniClass returnType = ezJniTraits<Ret>::GetStaticType(); ezJniClass inputTypes[N]; ezJniImpl::CollectArgumentTypes(inputTypes, args...); ezJniObject foundMethod = FindMethod(false, name, GetClass(), returnType, inputTypes, N); if (foundMethod.IsNull()) { return ezJniTraits<Ret>::GetEmptyObject(); } jmethodID method = ezJniAttachment::GetEnv()->FromReflectedMethod(foundMethod.m_object); return ezJniTraits<Ret>::CallInstanceMethod(m_object, method, args...); } template <typename Ret, typename... Args> Ret ezJniObject::UnsafeCall(const char* name, const char* signature, const Args&... args) const { if (!m_object) { ezLog::Error("Attempting to call method '{}' on null object.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } jmethodID method = ezJniAttachment::GetEnv()->GetMethodID(jclass(GetClass().m_object), name, signature); if (!method) { ezLog::Error("No such method: '{}' with signature '{}' in class '{}'.", name, signature, GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_METHOD); return ezJniTraits<Ret>::GetEmptyObject(); } else { return ezJniTraits<Ret>::CallInstanceMethod(m_object, method, args...); } } template <typename T> void ezJniObject::SetField(const char* name, const T& arg) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return; } if (!m_object) { ezLog::Error("Attempting to set field '{}' on null object.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return; } // No fast path here since we need to be able to report failures when attempting // to set final fields, which we can only do using reflection. ezJniObject field = GetClass().UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name)); if (ezJniAttachment::GetEnv()->ExceptionOccurred()) { ezJniAttachment::GetEnv()->ExceptionClear(); ezLog::Error("No field named '{}' found.", name); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } ezJniClass modifierClass("java/lang/reflect/Modifier"); jint modifiers = field.UnsafeCall<jint>("getModifiers", "()I"); if ((modifiers & ezJniModifiers::STATIC) != 0) { ezLog::Error("Field named '{}' in class '{}' is static.", name, GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } if ((modifiers & ezJniModifiers::FINAL) != 0) { ezLog::Error("Field named '{}' in class '{}' is final.", name, GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;"); ezJniClass argType = ezJniTraits<T>::GetRuntimeType(arg); if (argType.IsNull()) { if (fieldType.IsPrimitive()) { ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned null because it is a primitive type.", name, fieldType.ToString().GetData(), GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } } else { if (!fieldType.IsAssignableFrom(argType)) { ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned from type '{}'.", name, fieldType.ToString().GetData(), GetClass().ToString().GetData(), argType.ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } } return ezJniTraits<T>::SetField(m_object, ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle()), arg); } template <typename T> void ezJniObject::UnsafeSetField(const char* name, const char* signature, const T& arg) const { if (!m_object) { ezLog::Error("Attempting to set field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return; } jfieldID field = ezJniAttachment::GetEnv()->GetFieldID(jclass(GetClass().GetHandle()), name, signature); if (!field) { ezLog::Error("No such field: '{}' with signature '{}'.", name, signature); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } else { return ezJniTraits<T>::SetField(m_object, field, arg); } } template <typename Ret> Ret ezJniObject::GetField(const char* name) const { if (ezJniAttachment::FailOnPendingErrorOrException()) { return ezJniTraits<Ret>::GetEmptyObject(); } if (!m_object) { ezLog::Error("Attempting to get field '{}' on null object.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return ezJniTraits<Ret>::GetEmptyObject(); } jfieldID fieldID = ezJniAttachment::GetEnv()->GetFieldID(GetClass().GetHandle(), name, ezJniTraits<Ret>::GetSignatureStatic()); if (fieldID) { return ezJniTraits<Ret>::GetField(m_object, fieldID); } else { ezJniAttachment::GetEnv()->ExceptionClear(); } ezJniObject field = GetClass().UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name)); if (ezJniAttachment::GetEnv()->ExceptionOccurred()) { ezJniAttachment::GetEnv()->ExceptionClear(); ezLog::Error("No field named '{}' found in class '{}'.", name, GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } if ((field.UnsafeCall<jint>("getModifiers", "()I") & ezJniModifiers::STATIC) != 0) { ezLog::Error("Field named '{}' in class '{}' is static.", name, GetClass().ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;"); ezJniClass returnType = ezJniTraits<Ret>::GetStaticType(); if (!returnType.IsAssignableFrom(fieldType)) { ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned to return type '{}'.", name, fieldType.ToString().GetData(), GetClass().ToString().GetData(), returnType.ToString().GetData()); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return ezJniTraits<Ret>::GetEmptyObject(); } return ezJniTraits<Ret>::GetField(m_object, ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle())); } template <typename Ret> Ret ezJniObject::UnsafeGetField(const char* name, const char* signature) const { if (!m_object) { ezLog::Error("Attempting to get field '{}' on null class.", name); ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT); return; } jfieldID field = ezJniAttachment::GetEnv()->GetFieldID(GetClass().GetHandle(), name, signature); if (!field) { ezLog::Error("No such field: '{}' with signature '{}'.", name, signature); ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD); return; } else { return ezJniTraits<Ret>::GetField(m_object, field); } }
29.298056
285
0.729414
Tekh-ops
201039418cb79f69a96c443540e3dd27e909876a
3,458
cpp
C++
source/LibFgBase/src/FgSerial.cpp
SingularInversions/FaceGenBaseLibrary
e928b482fa78597cfcf3923f7252f7902ec0dfa9
[ "MIT" ]
41
2016-04-09T07:48:10.000Z
2022-03-01T15:46:08.000Z
source/LibFgBase/src/FgSerial.cpp
SingularInversions/FaceGenBaseLibrary
e928b482fa78597cfcf3923f7252f7902ec0dfa9
[ "MIT" ]
9
2015-09-23T10:54:50.000Z
2020-01-04T21:16:57.000Z
source/LibFgBase/src/FgSerial.cpp
SingularInversions/FaceGenBaseLibrary
e928b482fa78597cfcf3923f7252f7902ec0dfa9
[ "MIT" ]
29
2015-10-01T14:44:42.000Z
2022-01-05T01:28:43.000Z
// // Coypright (c) 2021 Singular Inversions Inc. (facegen.com) // Use, modification and distribution is subject to the MIT License, // see accompanying file LICENSE.txt or facegen.com/base_library_license.txt // #include "stdafx.h" #include "FgSerial.hpp" #include "FgCommand.hpp" using namespace std; namespace Fg { void srlz_(bool v,String & s) { uchar b = v ? 1 : 0; srlz_(b,s); } void dsrlz_(String const & s,size_t & p,bool & v) { uchar b; dsrlz_(s,p,b); v = (b == 1); } void dsrlz_(String const & s,size_t & p,long & v) { int64 t; dsrlzRaw_(s,p,t); FGASSERT(t >= std::numeric_limits<long>::lowest()); FGASSERT(t <= std::numeric_limits<long>::max()); v = static_cast<long>(t); } void dsrlz_(String const & s,size_t & p,unsigned long & v) { uint64 t; dsrlzRaw_(s,p,t); FGASSERT(t <= std::numeric_limits<unsigned long>::max()); v = static_cast<unsigned long>(t); } void srlz_(String const & v,String & s) { srlz_(uint64(v.size()),s); s.append(v); } void dsrlz_(String const & s,size_t & p,String & v) { uint64 sz; dsrlz_(s,p,sz); FGASSERT(p+sz <= s.size()); v.assign(s,p,size_t(sz)); p += sz; } namespace { void test0() { int i = 42; FGASSERT(i == dsrlz<int>(srlz(i))); uint u = 42U; FGASSERT(u == dsrlz<uint>(srlz(u))); long l = 42L; FGASSERT(l == dsrlz<long>(srlz(l))); long long ll = 42LL; FGASSERT(ll == dsrlz<long long>(srlz(ll))); unsigned long long ull = 42ULL; FGASSERT(ull == dsrlz<unsigned long long>(srlz(ull))); String s = "Test String"; FGASSERT(s == dsrlz<String>(srlz(s))); } void test1() { Strings tns; int a = 5; double b = 3.14; typeNames_(tns,a,b); fgout << fgnl << tns; } } struct A { int i; float f; }; FG_SERIAL_2(A,i,f) struct B { A a; double d; }; FG_SERIAL_2(B,a,d) struct Op { double acc {0}; template<typename T> void operator()(T r) {acc += double(r); } }; void traverseMembers_(Op & op,int s) {op(s); } void traverseMembers_(Op & op,float s) {op(s); } void traverseMembers_(Op & op,double s) {op(s); } void test2() { Strings names; reflectNames_<B>(names); fgout << fgnl << names; A a {3,0.1f}; B b {a,2.7}; Op op; traverseMembers_(op,b); fgout << fgnl << "Acc: " << op.acc; } void testSerial(CLArgs const &) { test0(); test1(); test2(); { Svec<string> in {"first","second"}, out = dsrlz<Strings>(srlz(in)); FGASSERT(in == out); } { String8 dd = dataDir() + "base/test/"; String msg = "This is a test", ser = srlz(msg); //saveRaw(ser,dd+"serial32"); //saveRaw(ser,dd+"serial64"); String msg32 = dsrlz<String>(loadRaw(dd+"serial32")), msg64 = dsrlz<String>(loadRaw(dd+"serial64")); FGASSERT(msg32 == msg); FGASSERT(msg64 == msg); } } }
21.214724
79
0.484095
SingularInversions
2010aeff4c31c302980dd1eb4e0e5ecc25b2f041
3,544
hpp
C++
include/strict_variant/variant_storage.hpp
reuk/strict-variant
7d0f1433d5126951b1af350213a0c7e75575fab0
[ "BSL-1.0" ]
62
2016-08-02T05:15:16.000Z
2020-02-14T18:02:34.000Z
include/strict_variant/variant_storage.hpp
reuk/strict-variant
7d0f1433d5126951b1af350213a0c7e75575fab0
[ "BSL-1.0" ]
6
2016-12-07T03:00:46.000Z
2018-12-03T22:03:27.000Z
include/strict_variant/variant_storage.hpp
reuk/strict-variant
7d0f1433d5126951b1af350213a0c7e75575fab0
[ "BSL-1.0" ]
6
2016-12-10T18:59:18.000Z
2019-11-05T08:11:11.000Z
// (C) Copyright 2016 - 2018 Christopher Beck // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <new> #include <strict_variant/mpl/max.hpp> #include <strict_variant/mpl/typelist.hpp> #include <strict_variant/wrapper.hpp> #include <utility> namespace strict_variant { namespace detail { // Implementation note: // Internal visitors need to be able to access the "true" type, the // reference_wrapper<T> when it is within the variant, to implement ctors // and special memeber functions. // External visitors are supposed to have this elided. // The `get_value` function uses tag dispatch to do the right thing. struct true_ {}; struct false_ {}; // Storage for the types in a list of types. // Provides typed access using the index within the list as a template parameter. // And some facilities for piercing recursive_wrapper template <typename First, typename... Types> struct storage { /*** * Determine size and alignment of our storage */ template <typename T> struct Sizeof { static constexpr size_t value = sizeof(T); }; template <typename T> struct Alignof { static constexpr size_t value = alignof(T); }; // size = max of size of each thing static constexpr size_t m_size = mpl::max<Sizeof, First, Types...>::value; // align = max align of each thing static constexpr size_t m_align = mpl::max<Alignof, First, Types...>::value; /*** * Storage */ // alignas(m_align) char m_storage[m_size]; using aligned_storage_t = typename std::aligned_storage<m_size, m_align>::type; aligned_storage_t m_storage; void * address() { return reinterpret_cast<void *>(&m_storage); } const void * address() const { return reinterpret_cast<const void *>(&m_storage); } /*** * Index -> Type */ using my_types = mpl::TypeList<First, Types...>; template <size_t index> using value_t = mpl::Index_At<my_types, index>; /*** * Initialize to the type at a particular value */ template <size_t index, typename... Args> void initialize(Args &&... args) noexcept( noexcept(value_t<index>(std::forward<Args>(std::declval<Args>())...))) { new (this->address()) value_t<index>(std::forward<Args>(args)...); } /*** * Typed access which pierces recursive_wrapper if detail::false_ is passed * "Internal" (non-piercing) access is achieved if detail::true_ is passed */ template <size_t index> value_t<index> & get_value(detail::true_) & { return *reinterpret_cast<value_t<index> *>(this->address()); } template <size_t index> const value_t<index> & get_value(detail::true_) const & { return *reinterpret_cast<const value_t<index> *>(this->address()); } template <size_t index> value_t<index> && get_value(detail::true_) && { return std::move(*reinterpret_cast<value_t<index> *>(this->address())); } template <size_t index> unwrap_type_t<value_t<index>> & get_value(detail::false_) & { return detail::pierce_wrapper(this->get_value<index>(detail::true_{})); } template <size_t index> const unwrap_type_t<value_t<index>> & get_value(detail::false_) const & { return detail::pierce_wrapper(this->get_value<index>(detail::true_{})); } template <size_t index> unwrap_type_t<value_t<index>> && get_value(detail::false_) && { return std::move(detail::pierce_wrapper(this->get_value<index>(detail::true_{}))); } }; } // end namespace detail } // end namespace strict_variant
30.033898
86
0.696106
reuk
2011bd7f6599a1e61221fc4920e97ecc36e522d7
25,689
cc
C++
zircon/system/fidl/fuchsia-blobfs/gen/llcpp/fidl.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
zircon/system/fidl/fuchsia-blobfs/gen/llcpp/fidl.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
zircon/system/fidl/fuchsia-blobfs/gen/llcpp/fidl.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
// WARNING: This file is machine generated by fidlgen. #include <fuchsia/blobfs/llcpp/fidl.h> #include <memory> namespace llcpp { namespace fuchsia { namespace blobfs { namespace { [[maybe_unused]] constexpr uint64_t kCorruptBlobHandler_CorruptBlob_Ordinal = 0x432ee88e00000000lu; [[maybe_unused]] constexpr uint64_t kCorruptBlobHandler_CorruptBlob_GenOrdinal = 0x264e37ffa416cdf1lu; extern "C" const fidl_type_t fuchsia_blobfs_CorruptBlobHandlerCorruptBlobRequestTable; extern "C" const fidl_type_t fuchsia_blobfs_CorruptBlobHandlerCorruptBlobResponseTable; extern "C" const fidl_type_t v1_fuchsia_blobfs_CorruptBlobHandlerCorruptBlobResponseTable; } // namespace template <> CorruptBlobHandler::ResultOf::CorruptBlob_Impl<CorruptBlobHandler::CorruptBlobResponse>::CorruptBlob_Impl(::zx::unowned_channel _client_end, ::fidl::VectorView<uint8_t> merkleroot) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<CorruptBlobRequest, ::fidl::MessageDirection::kSending>(); ::fidl::internal::AlignedBuffer<_kWriteAllocSize> _write_bytes_inlined; auto& _write_bytes_array = _write_bytes_inlined; CorruptBlobRequest _request = {}; _request.merkleroot = std::move(merkleroot); auto _linearize_result = ::fidl::Linearize(&_request, _write_bytes_array.view()); if (_linearize_result.status != ZX_OK) { Super::SetFailure(std::move(_linearize_result)); return; } ::fidl::DecodedMessage<CorruptBlobRequest> _decoded_request = std::move(_linearize_result.message); Super::SetResult( CorruptBlobHandler::InPlace::CorruptBlob(std::move(_client_end), std::move(_decoded_request), Super::response_buffer())); } CorruptBlobHandler::ResultOf::CorruptBlob CorruptBlobHandler::SyncClient::CorruptBlob(::fidl::VectorView<uint8_t> merkleroot) { return ResultOf::CorruptBlob(::zx::unowned_channel(this->channel_), std::move(merkleroot)); } CorruptBlobHandler::ResultOf::CorruptBlob CorruptBlobHandler::Call::CorruptBlob(::zx::unowned_channel _client_end, ::fidl::VectorView<uint8_t> merkleroot) { return ResultOf::CorruptBlob(std::move(_client_end), std::move(merkleroot)); } template <> CorruptBlobHandler::UnownedResultOf::CorruptBlob_Impl<CorruptBlobHandler::CorruptBlobResponse>::CorruptBlob_Impl(::zx::unowned_channel _client_end, ::fidl::BytePart _request_buffer, ::fidl::VectorView<uint8_t> merkleroot, ::fidl::BytePart _response_buffer) { if (_request_buffer.capacity() < CorruptBlobRequest::PrimarySize) { Super::SetFailure(::fidl::DecodeResult<CorruptBlobResponse>(ZX_ERR_BUFFER_TOO_SMALL, ::fidl::internal::kErrorRequestBufferTooSmall)); return; } CorruptBlobRequest _request = {}; _request.merkleroot = std::move(merkleroot); auto _linearize_result = ::fidl::Linearize(&_request, std::move(_request_buffer)); if (_linearize_result.status != ZX_OK) { Super::SetFailure(std::move(_linearize_result)); return; } ::fidl::DecodedMessage<CorruptBlobRequest> _decoded_request = std::move(_linearize_result.message); Super::SetResult( CorruptBlobHandler::InPlace::CorruptBlob(std::move(_client_end), std::move(_decoded_request), std::move(_response_buffer))); } CorruptBlobHandler::UnownedResultOf::CorruptBlob CorruptBlobHandler::SyncClient::CorruptBlob(::fidl::BytePart _request_buffer, ::fidl::VectorView<uint8_t> merkleroot, ::fidl::BytePart _response_buffer) { return UnownedResultOf::CorruptBlob(::zx::unowned_channel(this->channel_), std::move(_request_buffer), std::move(merkleroot), std::move(_response_buffer)); } CorruptBlobHandler::UnownedResultOf::CorruptBlob CorruptBlobHandler::Call::CorruptBlob(::zx::unowned_channel _client_end, ::fidl::BytePart _request_buffer, ::fidl::VectorView<uint8_t> merkleroot, ::fidl::BytePart _response_buffer) { return UnownedResultOf::CorruptBlob(std::move(_client_end), std::move(_request_buffer), std::move(merkleroot), std::move(_response_buffer)); } ::fidl::DecodeResult<CorruptBlobHandler::CorruptBlobResponse> CorruptBlobHandler::InPlace::CorruptBlob(::zx::unowned_channel _client_end, ::fidl::DecodedMessage<CorruptBlobRequest> params, ::fidl::BytePart response_buffer) { CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobRequest(params); auto _encode_request_result = ::fidl::Encode(std::move(params)); if (_encode_request_result.status != ZX_OK) { return ::fidl::DecodeResult<CorruptBlobHandler::CorruptBlobResponse>::FromFailure( std::move(_encode_request_result)); } auto _call_result = ::fidl::Call<CorruptBlobRequest, CorruptBlobResponse>( std::move(_client_end), std::move(_encode_request_result.message), std::move(response_buffer)); if (_call_result.status != ZX_OK) { return ::fidl::DecodeResult<CorruptBlobHandler::CorruptBlobResponse>::FromFailure( std::move(_call_result)); } return ::fidl::Decode(std::move(_call_result.message)); } bool CorruptBlobHandler::TryDispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { if (msg->num_bytes < sizeof(fidl_message_header_t)) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_INVALID_ARGS); return true; } fidl_message_header_t* hdr = reinterpret_cast<fidl_message_header_t*>(msg->bytes); zx_status_t status = fidl_validate_txn_header(hdr); if (status != ZX_OK) { txn->Close(status); return true; } switch (hdr->ordinal) { case kCorruptBlobHandler_CorruptBlob_Ordinal: case kCorruptBlobHandler_CorruptBlob_GenOrdinal: { auto result = ::fidl::DecodeAs<CorruptBlobRequest>(msg); if (result.status != ZX_OK) { txn->Close(ZX_ERR_INVALID_ARGS); return true; } auto message = result.message.message(); impl->CorruptBlob(std::move(message->merkleroot), Interface::CorruptBlobCompleter::Sync(txn)); return true; } default: { return false; } } } bool CorruptBlobHandler::Dispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { bool found = TryDispatch(impl, msg, txn); if (!found) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_NOT_SUPPORTED); } return found; } void CorruptBlobHandler::Interface::CorruptBlobCompleterBase::Reply(::llcpp::fuchsia::blobfs::TakeAction action) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<CorruptBlobResponse, ::fidl::MessageDirection::kSending>(); FIDL_ALIGNDECL uint8_t _write_bytes[_kWriteAllocSize] = {}; auto& _response = *reinterpret_cast<CorruptBlobResponse*>(_write_bytes); CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobResponse( ::fidl::DecodedMessage<CorruptBlobResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), CorruptBlobResponse::PrimarySize, CorruptBlobResponse::PrimarySize))); _response.action = std::move(action); ::fidl::BytePart _response_bytes(_write_bytes, _kWriteAllocSize, sizeof(CorruptBlobResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<CorruptBlobResponse>(std::move(_response_bytes))); } void CorruptBlobHandler::Interface::CorruptBlobCompleterBase::Reply(::fidl::BytePart _buffer, ::llcpp::fuchsia::blobfs::TakeAction action) { if (_buffer.capacity() < CorruptBlobResponse::PrimarySize) { CompleterBase::Close(ZX_ERR_INTERNAL); return; } auto& _response = *reinterpret_cast<CorruptBlobResponse*>(_buffer.data()); CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobResponse( ::fidl::DecodedMessage<CorruptBlobResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), CorruptBlobResponse::PrimarySize, CorruptBlobResponse::PrimarySize))); _response.action = std::move(action); _buffer.set_actual(sizeof(CorruptBlobResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<CorruptBlobResponse>(std::move(_buffer))); } void CorruptBlobHandler::Interface::CorruptBlobCompleterBase::Reply(::fidl::DecodedMessage<CorruptBlobResponse> params) { CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobResponse(params); CompleterBase::SendReply(std::move(params)); } void CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobRequest(const ::fidl::DecodedMessage<CorruptBlobHandler::CorruptBlobRequest>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kCorruptBlobHandler_CorruptBlob_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } void CorruptBlobHandler::SetTransactionHeaderFor::CorruptBlobResponse(const ::fidl::DecodedMessage<CorruptBlobHandler::CorruptBlobResponse>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kCorruptBlobHandler_CorruptBlob_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } namespace { [[maybe_unused]] constexpr uint64_t kBlobfsAdmin_HandleCorruptBlobs_Ordinal = 0x22c0c04c00000000lu; [[maybe_unused]] constexpr uint64_t kBlobfsAdmin_HandleCorruptBlobs_GenOrdinal = 0x5f405690ad00f87elu; extern "C" const fidl_type_t fuchsia_blobfs_BlobfsAdminHandleCorruptBlobsRequestTable; extern "C" const fidl_type_t fuchsia_blobfs_BlobfsAdminHandleCorruptBlobsResponseTable; extern "C" const fidl_type_t v1_fuchsia_blobfs_BlobfsAdminHandleCorruptBlobsResponseTable; } // namespace template <> BlobfsAdmin::ResultOf::HandleCorruptBlobs_Impl<BlobfsAdmin::HandleCorruptBlobsResponse>::HandleCorruptBlobs_Impl(::zx::unowned_channel _client_end, ::zx::channel handler) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<HandleCorruptBlobsRequest, ::fidl::MessageDirection::kSending>(); ::fidl::internal::AlignedBuffer<_kWriteAllocSize> _write_bytes_inlined; auto& _write_bytes_array = _write_bytes_inlined; uint8_t* _write_bytes = _write_bytes_array.view().data(); memset(_write_bytes, 0, HandleCorruptBlobsRequest::PrimarySize); auto& _request = *reinterpret_cast<HandleCorruptBlobsRequest*>(_write_bytes); _request.handler = std::move(handler); ::fidl::BytePart _request_bytes(_write_bytes, _kWriteAllocSize, sizeof(HandleCorruptBlobsRequest)); ::fidl::DecodedMessage<HandleCorruptBlobsRequest> _decoded_request(std::move(_request_bytes)); Super::SetResult( BlobfsAdmin::InPlace::HandleCorruptBlobs(std::move(_client_end), std::move(_decoded_request), Super::response_buffer())); } BlobfsAdmin::ResultOf::HandleCorruptBlobs BlobfsAdmin::SyncClient::HandleCorruptBlobs(::zx::channel handler) { return ResultOf::HandleCorruptBlobs(::zx::unowned_channel(this->channel_), std::move(handler)); } BlobfsAdmin::ResultOf::HandleCorruptBlobs BlobfsAdmin::Call::HandleCorruptBlobs(::zx::unowned_channel _client_end, ::zx::channel handler) { return ResultOf::HandleCorruptBlobs(std::move(_client_end), std::move(handler)); } template <> BlobfsAdmin::UnownedResultOf::HandleCorruptBlobs_Impl<BlobfsAdmin::HandleCorruptBlobsResponse>::HandleCorruptBlobs_Impl(::zx::unowned_channel _client_end, ::fidl::BytePart _request_buffer, ::zx::channel handler, ::fidl::BytePart _response_buffer) { if (_request_buffer.capacity() < HandleCorruptBlobsRequest::PrimarySize) { Super::SetFailure(::fidl::DecodeResult<HandleCorruptBlobsResponse>(ZX_ERR_BUFFER_TOO_SMALL, ::fidl::internal::kErrorRequestBufferTooSmall)); return; } memset(_request_buffer.data(), 0, HandleCorruptBlobsRequest::PrimarySize); auto& _request = *reinterpret_cast<HandleCorruptBlobsRequest*>(_request_buffer.data()); _request.handler = std::move(handler); _request_buffer.set_actual(sizeof(HandleCorruptBlobsRequest)); ::fidl::DecodedMessage<HandleCorruptBlobsRequest> _decoded_request(std::move(_request_buffer)); Super::SetResult( BlobfsAdmin::InPlace::HandleCorruptBlobs(std::move(_client_end), std::move(_decoded_request), std::move(_response_buffer))); } BlobfsAdmin::UnownedResultOf::HandleCorruptBlobs BlobfsAdmin::SyncClient::HandleCorruptBlobs(::fidl::BytePart _request_buffer, ::zx::channel handler, ::fidl::BytePart _response_buffer) { return UnownedResultOf::HandleCorruptBlobs(::zx::unowned_channel(this->channel_), std::move(_request_buffer), std::move(handler), std::move(_response_buffer)); } BlobfsAdmin::UnownedResultOf::HandleCorruptBlobs BlobfsAdmin::Call::HandleCorruptBlobs(::zx::unowned_channel _client_end, ::fidl::BytePart _request_buffer, ::zx::channel handler, ::fidl::BytePart _response_buffer) { return UnownedResultOf::HandleCorruptBlobs(std::move(_client_end), std::move(_request_buffer), std::move(handler), std::move(_response_buffer)); } ::fidl::DecodeResult<BlobfsAdmin::HandleCorruptBlobsResponse> BlobfsAdmin::InPlace::HandleCorruptBlobs(::zx::unowned_channel _client_end, ::fidl::DecodedMessage<HandleCorruptBlobsRequest> params, ::fidl::BytePart response_buffer) { BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsRequest(params); auto _encode_request_result = ::fidl::Encode(std::move(params)); if (_encode_request_result.status != ZX_OK) { return ::fidl::DecodeResult<BlobfsAdmin::HandleCorruptBlobsResponse>::FromFailure( std::move(_encode_request_result)); } auto _call_result = ::fidl::Call<HandleCorruptBlobsRequest, HandleCorruptBlobsResponse>( std::move(_client_end), std::move(_encode_request_result.message), std::move(response_buffer)); if (_call_result.status != ZX_OK) { return ::fidl::DecodeResult<BlobfsAdmin::HandleCorruptBlobsResponse>::FromFailure( std::move(_call_result)); } return ::fidl::Decode(std::move(_call_result.message)); } bool BlobfsAdmin::TryDispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { if (msg->num_bytes < sizeof(fidl_message_header_t)) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_INVALID_ARGS); return true; } fidl_message_header_t* hdr = reinterpret_cast<fidl_message_header_t*>(msg->bytes); zx_status_t status = fidl_validate_txn_header(hdr); if (status != ZX_OK) { txn->Close(status); return true; } switch (hdr->ordinal) { case kBlobfsAdmin_HandleCorruptBlobs_Ordinal: case kBlobfsAdmin_HandleCorruptBlobs_GenOrdinal: { auto result = ::fidl::DecodeAs<HandleCorruptBlobsRequest>(msg); if (result.status != ZX_OK) { txn->Close(ZX_ERR_INVALID_ARGS); return true; } auto message = result.message.message(); impl->HandleCorruptBlobs(std::move(message->handler), Interface::HandleCorruptBlobsCompleter::Sync(txn)); return true; } default: { return false; } } } bool BlobfsAdmin::Dispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { bool found = TryDispatch(impl, msg, txn); if (!found) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_NOT_SUPPORTED); } return found; } void BlobfsAdmin::Interface::HandleCorruptBlobsCompleterBase::Reply(int32_t status) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<HandleCorruptBlobsResponse, ::fidl::MessageDirection::kSending>(); FIDL_ALIGNDECL uint8_t _write_bytes[_kWriteAllocSize] = {}; auto& _response = *reinterpret_cast<HandleCorruptBlobsResponse*>(_write_bytes); BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsResponse( ::fidl::DecodedMessage<HandleCorruptBlobsResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), HandleCorruptBlobsResponse::PrimarySize, HandleCorruptBlobsResponse::PrimarySize))); _response.status = std::move(status); ::fidl::BytePart _response_bytes(_write_bytes, _kWriteAllocSize, sizeof(HandleCorruptBlobsResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<HandleCorruptBlobsResponse>(std::move(_response_bytes))); } void BlobfsAdmin::Interface::HandleCorruptBlobsCompleterBase::Reply(::fidl::BytePart _buffer, int32_t status) { if (_buffer.capacity() < HandleCorruptBlobsResponse::PrimarySize) { CompleterBase::Close(ZX_ERR_INTERNAL); return; } auto& _response = *reinterpret_cast<HandleCorruptBlobsResponse*>(_buffer.data()); BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsResponse( ::fidl::DecodedMessage<HandleCorruptBlobsResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), HandleCorruptBlobsResponse::PrimarySize, HandleCorruptBlobsResponse::PrimarySize))); _response.status = std::move(status); _buffer.set_actual(sizeof(HandleCorruptBlobsResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<HandleCorruptBlobsResponse>(std::move(_buffer))); } void BlobfsAdmin::Interface::HandleCorruptBlobsCompleterBase::Reply(::fidl::DecodedMessage<HandleCorruptBlobsResponse> params) { BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsResponse(params); CompleterBase::SendReply(std::move(params)); } void BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsRequest(const ::fidl::DecodedMessage<BlobfsAdmin::HandleCorruptBlobsRequest>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kBlobfsAdmin_HandleCorruptBlobs_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } void BlobfsAdmin::SetTransactionHeaderFor::HandleCorruptBlobsResponse(const ::fidl::DecodedMessage<BlobfsAdmin::HandleCorruptBlobsResponse>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kBlobfsAdmin_HandleCorruptBlobs_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } namespace { [[maybe_unused]] constexpr uint64_t kBlobfs_GetAllocatedRegions_Ordinal = 0xf6a24a800000000lu; [[maybe_unused]] constexpr uint64_t kBlobfs_GetAllocatedRegions_GenOrdinal = 0x3e4b9606dbb8073dlu; extern "C" const fidl_type_t fuchsia_blobfs_BlobfsGetAllocatedRegionsRequestTable; extern "C" const fidl_type_t fuchsia_blobfs_BlobfsGetAllocatedRegionsResponseTable; extern "C" const fidl_type_t v1_fuchsia_blobfs_BlobfsGetAllocatedRegionsResponseTable; } // namespace template <> Blobfs::ResultOf::GetAllocatedRegions_Impl<Blobfs::GetAllocatedRegionsResponse>::GetAllocatedRegions_Impl(::zx::unowned_channel _client_end) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<GetAllocatedRegionsRequest, ::fidl::MessageDirection::kSending>(); ::fidl::internal::AlignedBuffer<_kWriteAllocSize> _write_bytes_inlined; auto& _write_bytes_array = _write_bytes_inlined; uint8_t* _write_bytes = _write_bytes_array.view().data(); memset(_write_bytes, 0, GetAllocatedRegionsRequest::PrimarySize); ::fidl::BytePart _request_bytes(_write_bytes, _kWriteAllocSize, sizeof(GetAllocatedRegionsRequest)); ::fidl::DecodedMessage<GetAllocatedRegionsRequest> _decoded_request(std::move(_request_bytes)); Super::SetResult( Blobfs::InPlace::GetAllocatedRegions(std::move(_client_end), Super::response_buffer())); } Blobfs::ResultOf::GetAllocatedRegions Blobfs::SyncClient::GetAllocatedRegions() { return ResultOf::GetAllocatedRegions(::zx::unowned_channel(this->channel_)); } Blobfs::ResultOf::GetAllocatedRegions Blobfs::Call::GetAllocatedRegions(::zx::unowned_channel _client_end) { return ResultOf::GetAllocatedRegions(std::move(_client_end)); } template <> Blobfs::UnownedResultOf::GetAllocatedRegions_Impl<Blobfs::GetAllocatedRegionsResponse>::GetAllocatedRegions_Impl(::zx::unowned_channel _client_end, ::fidl::BytePart _response_buffer) { FIDL_ALIGNDECL uint8_t _write_bytes[sizeof(GetAllocatedRegionsRequest)] = {}; ::fidl::BytePart _request_buffer(_write_bytes, sizeof(_write_bytes)); memset(_request_buffer.data(), 0, GetAllocatedRegionsRequest::PrimarySize); _request_buffer.set_actual(sizeof(GetAllocatedRegionsRequest)); ::fidl::DecodedMessage<GetAllocatedRegionsRequest> _decoded_request(std::move(_request_buffer)); Super::SetResult( Blobfs::InPlace::GetAllocatedRegions(std::move(_client_end), std::move(_response_buffer))); } Blobfs::UnownedResultOf::GetAllocatedRegions Blobfs::SyncClient::GetAllocatedRegions(::fidl::BytePart _response_buffer) { return UnownedResultOf::GetAllocatedRegions(::zx::unowned_channel(this->channel_), std::move(_response_buffer)); } Blobfs::UnownedResultOf::GetAllocatedRegions Blobfs::Call::GetAllocatedRegions(::zx::unowned_channel _client_end, ::fidl::BytePart _response_buffer) { return UnownedResultOf::GetAllocatedRegions(std::move(_client_end), std::move(_response_buffer)); } ::fidl::DecodeResult<Blobfs::GetAllocatedRegionsResponse> Blobfs::InPlace::GetAllocatedRegions(::zx::unowned_channel _client_end, ::fidl::BytePart response_buffer) { constexpr uint32_t _write_num_bytes = sizeof(GetAllocatedRegionsRequest); ::fidl::internal::AlignedBuffer<_write_num_bytes> _write_bytes; ::fidl::BytePart _request_buffer = _write_bytes.view(); _request_buffer.set_actual(_write_num_bytes); ::fidl::DecodedMessage<GetAllocatedRegionsRequest> params(std::move(_request_buffer)); Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsRequest(params); auto _encode_request_result = ::fidl::Encode(std::move(params)); if (_encode_request_result.status != ZX_OK) { return ::fidl::DecodeResult<Blobfs::GetAllocatedRegionsResponse>::FromFailure( std::move(_encode_request_result)); } auto _call_result = ::fidl::Call<GetAllocatedRegionsRequest, GetAllocatedRegionsResponse>( std::move(_client_end), std::move(_encode_request_result.message), std::move(response_buffer)); if (_call_result.status != ZX_OK) { return ::fidl::DecodeResult<Blobfs::GetAllocatedRegionsResponse>::FromFailure( std::move(_call_result)); } return ::fidl::Decode(std::move(_call_result.message)); } bool Blobfs::TryDispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { if (msg->num_bytes < sizeof(fidl_message_header_t)) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_INVALID_ARGS); return true; } fidl_message_header_t* hdr = reinterpret_cast<fidl_message_header_t*>(msg->bytes); zx_status_t status = fidl_validate_txn_header(hdr); if (status != ZX_OK) { txn->Close(status); return true; } switch (hdr->ordinal) { case kBlobfs_GetAllocatedRegions_Ordinal: case kBlobfs_GetAllocatedRegions_GenOrdinal: { auto result = ::fidl::DecodeAs<GetAllocatedRegionsRequest>(msg); if (result.status != ZX_OK) { txn->Close(ZX_ERR_INVALID_ARGS); return true; } impl->GetAllocatedRegions( Interface::GetAllocatedRegionsCompleter::Sync(txn)); return true; } default: { return false; } } } bool Blobfs::Dispatch(Interface* impl, fidl_msg_t* msg, ::fidl::Transaction* txn) { bool found = TryDispatch(impl, msg, txn); if (!found) { zx_handle_close_many(msg->handles, msg->num_handles); txn->Close(ZX_ERR_NOT_SUPPORTED); } return found; } void Blobfs::Interface::GetAllocatedRegionsCompleterBase::Reply(int32_t status, ::zx::vmo regions, uint64_t count) { constexpr uint32_t _kWriteAllocSize = ::fidl::internal::ClampedMessageSize<GetAllocatedRegionsResponse, ::fidl::MessageDirection::kSending>(); FIDL_ALIGNDECL uint8_t _write_bytes[_kWriteAllocSize] = {}; auto& _response = *reinterpret_cast<GetAllocatedRegionsResponse*>(_write_bytes); Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsResponse( ::fidl::DecodedMessage<GetAllocatedRegionsResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), GetAllocatedRegionsResponse::PrimarySize, GetAllocatedRegionsResponse::PrimarySize))); _response.status = std::move(status); _response.regions = std::move(regions); _response.count = std::move(count); ::fidl::BytePart _response_bytes(_write_bytes, _kWriteAllocSize, sizeof(GetAllocatedRegionsResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<GetAllocatedRegionsResponse>(std::move(_response_bytes))); } void Blobfs::Interface::GetAllocatedRegionsCompleterBase::Reply(::fidl::BytePart _buffer, int32_t status, ::zx::vmo regions, uint64_t count) { if (_buffer.capacity() < GetAllocatedRegionsResponse::PrimarySize) { CompleterBase::Close(ZX_ERR_INTERNAL); return; } auto& _response = *reinterpret_cast<GetAllocatedRegionsResponse*>(_buffer.data()); Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsResponse( ::fidl::DecodedMessage<GetAllocatedRegionsResponse>( ::fidl::BytePart(reinterpret_cast<uint8_t*>(&_response), GetAllocatedRegionsResponse::PrimarySize, GetAllocatedRegionsResponse::PrimarySize))); _response.status = std::move(status); _response.regions = std::move(regions); _response.count = std::move(count); _buffer.set_actual(sizeof(GetAllocatedRegionsResponse)); CompleterBase::SendReply(::fidl::DecodedMessage<GetAllocatedRegionsResponse>(std::move(_buffer))); } void Blobfs::Interface::GetAllocatedRegionsCompleterBase::Reply(::fidl::DecodedMessage<GetAllocatedRegionsResponse> params) { Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsResponse(params); CompleterBase::SendReply(std::move(params)); } void Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsRequest(const ::fidl::DecodedMessage<Blobfs::GetAllocatedRegionsRequest>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kBlobfs_GetAllocatedRegions_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } void Blobfs::SetTransactionHeaderFor::GetAllocatedRegionsResponse(const ::fidl::DecodedMessage<Blobfs::GetAllocatedRegionsResponse>& _msg) { fidl_init_txn_header(&_msg.message()->_hdr, 0, kBlobfs_GetAllocatedRegions_GenOrdinal); _msg.message()->_hdr.flags[0] |= FIDL_TXN_HEADER_UNION_FROM_XUNION_FLAG; } } // namespace blobfs } // namespace fuchsia } // namespace llcpp
50.668639
258
0.774767
opensource-assist
2015aff915e56298a3280bbb6ab5fdeccd658cd5
5,772
cxx
C++
main/sd/source/ui/view/sdruler.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sd/source/ui/view/sdruler.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sd/source/ui/view/sdruler.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "Ruler.hxx" #include <svl/ptitem.hxx> #include <svx/ruler.hxx> #ifndef _SVXIDS_HXX //autogen #include <svx/svxids.hrc> #endif #include <sfx2/ctrlitem.hxx> #include <sfx2/bindings.hxx> #include "View.hxx" #include "DrawViewShell.hxx" #include "Window.hxx" #include "helpids.h" namespace sd { /************************************************************************* |* |* Controller-Item fuer Ruler |* \************************************************************************/ class RulerCtrlItem : public SfxControllerItem { Ruler &rRuler; protected: virtual void StateChanged( sal_uInt16 nSId, SfxItemState eState, const SfxPoolItem* pItem ); public: RulerCtrlItem(sal_uInt16 nId, Ruler& rRlr, SfxBindings& rBind); }; /************************************************************************* |* \************************************************************************/ RulerCtrlItem::RulerCtrlItem(sal_uInt16 _nId, Ruler& rRlr, SfxBindings& rBind) : SfxControllerItem(_nId, rBind) , rRuler(rRlr) { } /************************************************************************* |* \************************************************************************/ void RulerCtrlItem::StateChanged( sal_uInt16 nSId, SfxItemState, const SfxPoolItem* pState ) { switch( nSId ) { case SID_RULER_NULL_OFFSET: { const SfxPointItem* pItem = dynamic_cast< const SfxPointItem* >(pState); DBG_ASSERT(pState ? pItem != NULL : sal_True, "SfxPointItem erwartet"); if ( pItem ) rRuler.SetNullOffset(pItem->GetValue()); } break; } } /************************************************************************* |* |* Konstruktor |* \************************************************************************/ Ruler::Ruler( DrawViewShell& rViewSh, ::Window* pParent, ::sd::Window* pWin, sal_uInt16 nRulerFlags, SfxBindings& rBindings, WinBits nWinStyle) : SvxRuler(pParent, pWin, nRulerFlags, rBindings, nWinStyle) , pSdWin(pWin) , pDrViewShell(&rViewSh) { rBindings.EnterRegistrations(); pCtrlItem = new RulerCtrlItem(SID_RULER_NULL_OFFSET, *this, rBindings); rBindings.LeaveRegistrations(); if ( nWinStyle & WB_HSCROLL ) { bHorz = sal_True; SetHelpId( HID_SD_RULER_HORIZONTAL ); } else { bHorz = sal_False; SetHelpId( HID_SD_RULER_VERTICAL ); } } /************************************************************************* |* |* Destruktor |* \************************************************************************/ Ruler::~Ruler() { SfxBindings& rBindings = pCtrlItem->GetBindings(); rBindings.EnterRegistrations(); delete pCtrlItem; rBindings.LeaveRegistrations(); } /************************************************************************* |* |* MouseButtonDown-Handler |* \************************************************************************/ void Ruler::MouseButtonDown(const MouseEvent& rMEvt) { Point aMPos = rMEvt.GetPosPixel(); RulerType eType = GetType(aMPos); if ( !pDrViewShell->GetView()->IsTextEdit() && rMEvt.IsLeft() && rMEvt.GetClicks() == 1 && (eType == RULER_TYPE_DONTKNOW || eType == RULER_TYPE_OUTSIDE) ) { pDrViewShell->StartRulerDrag(*this, rMEvt); } else SvxRuler::MouseButtonDown(rMEvt); } /************************************************************************* |* |* MouseMove-Handler |* \************************************************************************/ void Ruler::MouseMove(const MouseEvent& rMEvt) { SvxRuler::MouseMove(rMEvt); } /************************************************************************* |* |* MouseButtonUp-Handler |* \************************************************************************/ void Ruler::MouseButtonUp(const MouseEvent& rMEvt) { SvxRuler::MouseButtonUp(rMEvt); } /************************************************************************* |* |* NullOffset setzen |* \************************************************************************/ void Ruler::SetNullOffset(const Point& rOffset) { long nOffset; if ( bHorz ) nOffset = rOffset.X(); else nOffset = rOffset.Y(); SetNullOffsetLogic(nOffset); } /************************************************************************* |* |* Command event |* \************************************************************************/ void Ruler::Command(const CommandEvent& rCEvt) { if( rCEvt.GetCommand() == COMMAND_CONTEXTMENU && !pDrViewShell->GetView()->IsTextEdit() ) { SvxRuler::Command( rCEvt ); } } /************************************************************************* |* |* ExtraDown |* \************************************************************************/ void Ruler::ExtraDown() { if( !pDrViewShell->GetView()->IsTextEdit() ) SvxRuler::ExtraDown(); } } // end of namespace sd
25.883408
145
0.495669
Grosskopf
2016fc451b4a8820fea9720af0f7d82da85c557c
6,850
cpp
C++
src/render/OGLES1_0/CShaderProgramOGLES1_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
4
2015-08-13T08:25:36.000Z
2017-04-07T21:33:10.000Z
src/render/OGLES1_0/CShaderProgramOGLES1_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
null
null
null
src/render/OGLES1_0/CShaderProgramOGLES1_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
null
null
null
// // CShaderProgramOGLES1_0.h // OpenJam // // Created by Yevgeniy Logachev // Copyright (c) 2014 yev. All rights reserved. // #if defined(RENDER_OGLES1_0) #include "CShaderProgramOGLES1_0.h" using namespace jam; // ***************************************************************************** // Constants // ***************************************************************************** // ***************************************************************************** // Public Methods // ***************************************************************************** CShaderProgramOGLES1_0::CShaderProgramOGLES1_0() : m_ProectionMatrixHadle(-1u) , m_ModelMatrixHadle(-1u) , m_VertexCoordHandle(-1u) , m_VertexNormalHandle(-1u) , m_TextureCoordHandle(-1u) , m_VertexColorHandle(-1u) , m_ColorHandle(-1u) , m_IsLinked(false) { } CShaderProgramOGLES1_0::~CShaderProgramOGLES1_0() { } void CShaderProgramOGLES1_0::Bind() { } void CShaderProgramOGLES1_0::Unbind() { } void CShaderProgramOGLES1_0::AttachShader(IShaderPtr shader) { std::map<IShader::ShaderType, IShaderPtr>::const_iterator it = m_AttachedShaders.find(shader->Type()); if (it != m_AttachedShaders.end()) { m_AttachedShaders.erase(it); } m_AttachedShaders[shader->Type()] = shader; } void CShaderProgramOGLES1_0::DetachShader(IShader::ShaderType shaderType) { std::map<IShader::ShaderType, IShaderPtr>::const_iterator it = m_AttachedShaders.find(shaderType); if (it != m_AttachedShaders.end()) { m_AttachedShaders.erase(it); } } bool CShaderProgramOGLES1_0::IsShaderAttached(IShader::ShaderType shaderType) { std::map<IShader::ShaderType, IShaderPtr>::const_iterator it = m_AttachedShaders.find(shaderType); return (it != m_AttachedShaders.end()); } bool CShaderProgramOGLES1_0::IsValid() { return (IsShaderAttached(IShader::Vertex) && IsShaderAttached(IShader::Fragment)); } bool CShaderProgramOGLES1_0::Link() { m_VertexCoordHandle = Attribute("MainVertexPosition"); m_TextureCoordHandle = Attribute("MainVertexUV"); m_VertexColorHandle = Attribute("MainVertexColor"); m_TextureDataHadle.resize(6); for (size_t i = 0; i < m_TextureDataHadle.size(); ++i) { m_TextureDataHadle[i] = -1u; } m_TextureDataHadle[0] = Uniform("MainTexture0"); m_TextureDataHadle[1] = Uniform("MainTexture1"); m_TextureDataHadle[2] = Uniform("MainTexture2"); m_TextureDataHadle[3] = Uniform("MainTexture3"); m_TextureDataHadle[4] = Uniform("MainTexture4"); m_TextureDataHadle[5] = Uniform("MainTexture5"); m_ColorHandle = Uniform("MainColor"); m_ProectionMatrixHadle = Uniform("MainProjectionMatrix"); m_ModelMatrixHadle = Uniform("MainModelMatrix"); m_IsLinked = true; return m_IsLinked; } bool CShaderProgramOGLES1_0::IsLinked() const { return m_IsLinked; } uint32_t CShaderProgramOGLES1_0::Attribute(const std::string& name) { static std::unordered_map<std::string, int> attributes = { { "MainVertexPosition", 0 }, { "MainVertexUV", 1 }, { "MainVertexColor", 2 } }; if (attributes.find(name) != attributes.end()) { return attributes[name]; } return -1u; } uint32_t CShaderProgramOGLES1_0::Uniform(const std::string& name) { static std::unordered_map<std::string, int> uniforms = { { "MainTexture0", 0 }, { "MainTexture1", 1 }, { "MainTexture2", 2 }, { "MainTexture3", 3 }, { "MainTexture4", 4 }, { "MainTexture5", 5 }, { "MainColor", 6 }, { "MainProjectionMatrix", 7 }, { "MainModelMatrix", 8 }, }; if (uniforms.find(name) != uniforms.end()) { return uniforms[name]; } return -1u; } uint32_t CShaderProgramOGLES1_0::VertexPosition() { return m_VertexCoordHandle; } uint32_t CShaderProgramOGLES1_0::VertexNormal() { return m_VertexNormalHandle; } uint32_t CShaderProgramOGLES1_0::VertexUV() { return m_TextureCoordHandle; } uint32_t CShaderProgramOGLES1_0::VertexColor() { return m_VertexColorHandle; } uint32_t CShaderProgramOGLES1_0::MainTexture() { return m_TextureDataHadle[0]; } uint32_t CShaderProgramOGLES1_0::MainColor() { return m_ColorHandle; } uint32_t CShaderProgramOGLES1_0::ProjectionMatrix() { return m_ProectionMatrixHadle; } uint32_t CShaderProgramOGLES1_0::ModelMatrix() { return m_ModelMatrixHadle; } uint32_t CShaderProgramOGLES1_0::Texture(uint32_t index) { if (index < 5) { return m_TextureDataHadle[index]; } return -1u; } uint32_t CShaderProgramOGLES1_0::DiffuseTexture() { return m_TextureDataHadle[0]; } uint32_t CShaderProgramOGLES1_0::NormalTexture() { return m_TextureDataHadle[1]; } uint32_t CShaderProgramOGLES1_0::SpecularTexture() { return m_TextureDataHadle[2]; } uint32_t CShaderProgramOGLES1_0::EnvironmentTexture() { return m_TextureDataHadle[3]; } bool CShaderProgramOGLES1_0::BindUniform1i(const std::string& uniform, int value) { m_UniInt[Uniform(uniform)] = { value }; return true; } bool CShaderProgramOGLES1_0::BindUniform1f(const std::string& uniform, float value) { m_UniFloat[Uniform(uniform)] = { value }; return true; } bool CShaderProgramOGLES1_0::BindUniform2i(const std::string& uniform, int value1, int value2) { m_UniInt[Uniform(uniform)] = { value1, value2 }; return true; } bool CShaderProgramOGLES1_0::BindUniform2f(const std::string& uniform, float value1, float value2) { m_UniFloat[Uniform(uniform)] = { value1, value2 }; return true; } bool CShaderProgramOGLES1_0::BindUniformfv(const std::string& uniform, const std::vector<float>& value) { m_UniFloatVec[Uniform(uniform)] = value; return true; } bool CShaderProgramOGLES1_0::BindUniformMatrix4x4f(const std::string& uniform, const glm::mat4x4& value) { m_UniMatrixFloat[Uniform(uniform)] = value; return true; } const IShaderProgram::TUniInt& CShaderProgramOGLES1_0::Uniformsi() const { return m_UniInt; } const IShaderProgram::TUniFloat& CShaderProgramOGLES1_0::Uniformsf() const { return m_UniFloat; } const IShaderProgram::TUniFloat& CShaderProgramOGLES1_0::Uniformsfv() const { return m_UniFloatVec; } const IShaderProgram::TUniMatrix4Float& CShaderProgramOGLES1_0::UniformsMatrix4x4f() const { return m_UniMatrixFloat; } void CShaderProgramOGLES1_0::UpdateUniforms() const { } // ***************************************************************************** // Protected Methods // ***************************************************************************** // ***************************************************************************** // Private Methods // ***************************************************************************** #endif /* defined(RENDER_OGLES1_0) */
24.035088
106
0.643212
opengamejam
2017699eeb176419aca9a82faff09c4c27796912
38,496
cpp
C++
build/linux-build/Sources/src/zpp_nape/util/ZNPList_ZPP_CutVert.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/util/ZNPList_ZPP_CutVert.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/util/ZNPList_ZPP_CutVert.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
// Generated by Haxe 4.0.0-preview.5 #include <hxcpp.h> #ifndef INCLUDED_zpp_nape_geom_ZPP_CutVert #include <hxinc/zpp_nape/geom/ZPP_CutVert.h> #endif #ifndef INCLUDED_zpp_nape_util_ZNPList_ZPP_CutVert #include <hxinc/zpp_nape/util/ZNPList_ZPP_CutVert.h> #endif #ifndef INCLUDED_zpp_nape_util_ZNPNode_ZPP_CutVert #include <hxinc/zpp_nape/util/ZNPNode_ZPP_CutVert.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_378a7638927e1295_6013_new,"zpp_nape.util.ZNPList_ZPP_CutVert","new",0x362d64b0,"zpp_nape.util.ZNPList_ZPP_CutVert.new","zpp_nape/util/Lists.hx",6013,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6019_begin,"zpp_nape.util.ZNPList_ZPP_CutVert","begin",0x3ef93279,"zpp_nape.util.ZNPList_ZPP_CutVert.begin","zpp_nape/util/Lists.hx",6019,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6026_setbegin,"zpp_nape.util.ZNPList_ZPP_CutVert","setbegin",0xf0d7acf7,"zpp_nape.util.ZNPList_ZPP_CutVert.setbegin","zpp_nape/util/Lists.hx",6026,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6032_add,"zpp_nape.util.ZNPList_ZPP_CutVert","add",0x36238671,"zpp_nape.util.ZNPList_ZPP_CutVert.add","zpp_nape/util/Lists.hx",6032,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6036_inlined_add,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_add",0xb52cb0dd,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_add","zpp_nape/util/Lists.hx",6036,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6082_addAll,"zpp_nape.util.ZNPList_ZPP_CutVert","addAll",0xdf370730,"zpp_nape.util.ZNPList_ZPP_CutVert.addAll","zpp_nape/util/Lists.hx",6082,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6092_insert,"zpp_nape.util.ZNPList_ZPP_CutVert","insert",0xde1940e9,"zpp_nape.util.ZNPList_ZPP_CutVert.insert","zpp_nape/util/Lists.hx",6092,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6096_inlined_insert,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_insert",0xb50961fd,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_insert","zpp_nape/util/Lists.hx",6096,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6140_pop,"zpp_nape.util.ZNPList_ZPP_CutVert","pop",0x362ef1e1,"zpp_nape.util.ZNPList_ZPP_CutVert.pop","zpp_nape/util/Lists.hx",6140,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6144_inlined_pop,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_pop",0xb5381c4d,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_pop","zpp_nape/util/Lists.hx",6144,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6178_pop_unsafe,"zpp_nape.util.ZNPList_ZPP_CutVert","pop_unsafe",0xa6f11204,"zpp_nape.util.ZNPList_ZPP_CutVert.pop_unsafe","zpp_nape/util/Lists.hx",6178,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6182_inlined_pop_unsafe,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_pop_unsafe",0x73094d18,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_pop_unsafe","zpp_nape/util/Lists.hx",6182,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6204_remove,"zpp_nape.util.ZNPList_ZPP_CutVert","remove",0x44c499f4,"zpp_nape.util.ZNPList_ZPP_CutVert.remove","zpp_nape/util/Lists.hx",6204,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6206_try_remove,"zpp_nape.util.ZNPList_ZPP_CutVert","try_remove",0xbe1b47b8,"zpp_nape.util.ZNPList_ZPP_CutVert.try_remove","zpp_nape/util/Lists.hx",6206,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6240_inlined_remove,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_remove",0x1bb4bb08,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_remove","zpp_nape/util/Lists.hx",6240,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6244_inlined_try_remove,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_try_remove",0x8a3382cc,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_try_remove","zpp_nape/util/Lists.hx",6244,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6268_erase,"zpp_nape.util.ZNPList_ZPP_CutVert","erase",0x01c03136,"zpp_nape.util.ZNPList_ZPP_CutVert.erase","zpp_nape/util/Lists.hx",6268,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6272_inlined_erase,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_erase",0x3539cea2,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_erase","zpp_nape/util/Lists.hx",6272,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6318_splice,"zpp_nape.util.ZNPList_ZPP_CutVert","splice",0xffda832c,"zpp_nape.util.ZNPList_ZPP_CutVert.splice","zpp_nape/util/Lists.hx",6318,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6323_clear,"zpp_nape.util.ZNPList_ZPP_CutVert","clear",0xd6feb9dd,"zpp_nape.util.ZNPList_ZPP_CutVert.clear","zpp_nape/util/Lists.hx",6323,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6328_inlined_clear,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_clear",0x0a785749,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_clear","zpp_nape/util/Lists.hx",6328,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6333_reverse,"zpp_nape.util.ZNPList_ZPP_CutVert","reverse",0x0f3e3572,"zpp_nape.util.ZNPList_ZPP_CutVert.reverse","zpp_nape/util/Lists.hx",6333,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6349_empty,"zpp_nape.util.ZNPList_ZPP_CutVert","empty",0xfe7d82dd,"zpp_nape.util.ZNPList_ZPP_CutVert.empty","zpp_nape/util/Lists.hx",6349,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6354_size,"zpp_nape.util.ZNPList_ZPP_CutVert","size",0x34dbd271,"zpp_nape.util.ZNPList_ZPP_CutVert.size","zpp_nape/util/Lists.hx",6354,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6357_has,"zpp_nape.util.ZNPList_ZPP_CutVert","has",0x3628d3aa,"zpp_nape.util.ZNPList_ZPP_CutVert.has","zpp_nape/util/Lists.hx",6357,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6361_inlined_has,"zpp_nape.util.ZNPList_ZPP_CutVert","inlined_has",0xb531fe16,"zpp_nape.util.ZNPList_ZPP_CutVert.inlined_has","zpp_nape/util/Lists.hx",6361,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6392_front,"zpp_nape.util.ZNPList_ZPP_CutVert","front",0x953160f9,"zpp_nape.util.ZNPList_ZPP_CutVert.front","zpp_nape/util/Lists.hx",6392,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6394_back,"zpp_nape.util.ZNPList_ZPP_CutVert","back",0x29990bd7,"zpp_nape.util.ZNPList_ZPP_CutVert.back","zpp_nape/util/Lists.hx",6394,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6403_iterator_at,"zpp_nape.util.ZNPList_ZPP_CutVert","iterator_at",0xb9d0ee34,"zpp_nape.util.ZNPList_ZPP_CutVert.iterator_at","zpp_nape/util/Lists.hx",6403,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_378a7638927e1295_6416_at,"zpp_nape.util.ZNPList_ZPP_CutVert","at",0xb59fbaa3,"zpp_nape.util.ZNPList_ZPP_CutVert.at","zpp_nape/util/Lists.hx",6416,0x9f4e6754) namespace zpp_nape{ namespace util{ void ZNPList_ZPP_CutVert_obj::__construct(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6013_new) HXLINE(6023) this->length = 0; HXLINE(6022) this->pushmod = false; HXLINE(6021) this->modified = false; HXLINE(6014) this->head = null(); } Dynamic ZNPList_ZPP_CutVert_obj::__CreateEmpty() { return new ZNPList_ZPP_CutVert_obj; } void *ZNPList_ZPP_CutVert_obj::_hx_vtable = 0; Dynamic ZNPList_ZPP_CutVert_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ZNPList_ZPP_CutVert_obj > _hx_result = new ZNPList_ZPP_CutVert_obj(); _hx_result->__construct(); return _hx_result; } bool ZNPList_ZPP_CutVert_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x1d171732; } ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::begin(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6019_begin) HXDLIN(6019) return this->head; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,begin,return ) void ZNPList_ZPP_CutVert_obj::setbegin( ::zpp_nape::util::ZNPNode_ZPP_CutVert i){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6026_setbegin) HXLINE(6027) this->head = i; HXLINE(6028) this->modified = true; HXLINE(6029) this->pushmod = true; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,setbegin,(void)) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::add( ::zpp_nape::geom::ZPP_CutVert o){ HX_GC_STACKFRAME(&_hx_pos_378a7638927e1295_6032_add) HXDLIN(6032) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXDLIN(6032) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool )) { HXDLIN(6032) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::__alloc( HX_CTX ); } else { HXDLIN(6032) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6032) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = ret->next; HXDLIN(6032) ret->next = null(); } HXDLIN(6032) ret->elt = o; HXDLIN(6032) ::zpp_nape::util::ZNPNode_ZPP_CutVert temp = ret; HXDLIN(6032) temp->next = this->head; HXDLIN(6032) this->head = temp; HXDLIN(6032) this->modified = true; HXDLIN(6032) this->length++; HXDLIN(6032) return o; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,add,return ) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::inlined_add( ::zpp_nape::geom::ZPP_CutVert o){ HX_GC_STACKFRAME(&_hx_pos_378a7638927e1295_6036_inlined_add) HXLINE(6046) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXLINE(6048) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool )) { HXLINE(6049) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::__alloc( HX_CTX ); } else { HXLINE(6055) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXLINE(6056) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = ret->next; HXLINE(6057) ret->next = null(); } HXLINE(6064) ret->elt = o; HXLINE(6045) ::zpp_nape::util::ZNPNode_ZPP_CutVert temp = ret; HXLINE(6067) temp->next = this->head; HXLINE(6068) this->head = temp; HXLINE(6069) this->modified = true; HXLINE(6070) this->length++; HXLINE(6071) return o; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,inlined_add,return ) void ZNPList_ZPP_CutVert_obj::addAll( ::zpp_nape::util::ZNPList_ZPP_CutVert x){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6082_addAll) HXLINE(6083) ::zpp_nape::util::ZNPNode_ZPP_CutVert cx_ite = x->head; HXLINE(6084) while(hx::IsNotNull( cx_ite )){ HXLINE(6085) ::zpp_nape::geom::ZPP_CutVert i = cx_ite->elt; HXLINE(6086) this->add(i); HXLINE(6087) cx_ite = cx_ite->next; } } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,addAll,(void)) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::insert( ::zpp_nape::util::ZNPNode_ZPP_CutVert cur, ::zpp_nape::geom::ZPP_CutVert o){ HX_GC_STACKFRAME(&_hx_pos_378a7638927e1295_6092_insert) HXDLIN(6092) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXDLIN(6092) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool )) { HXDLIN(6092) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::__alloc( HX_CTX ); } else { HXDLIN(6092) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6092) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = ret->next; HXDLIN(6092) ret->next = null(); } HXDLIN(6092) ret->elt = o; HXDLIN(6092) ::zpp_nape::util::ZNPNode_ZPP_CutVert temp = ret; HXDLIN(6092) if (hx::IsNull( cur )) { HXDLIN(6092) temp->next = this->head; HXDLIN(6092) this->head = temp; } else { HXDLIN(6092) temp->next = cur->next; HXDLIN(6092) cur->next = temp; } HXDLIN(6092) this->pushmod = (this->modified = true); HXDLIN(6092) this->length++; HXDLIN(6092) return temp; } HX_DEFINE_DYNAMIC_FUNC2(ZNPList_ZPP_CutVert_obj,insert,return ) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::inlined_insert( ::zpp_nape::util::ZNPNode_ZPP_CutVert cur, ::zpp_nape::geom::ZPP_CutVert o){ HX_GC_STACKFRAME(&_hx_pos_378a7638927e1295_6096_inlined_insert) HXLINE(6106) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXLINE(6108) if (hx::IsNull( ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool )) { HXLINE(6109) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::__alloc( HX_CTX ); } else { HXLINE(6115) ret = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXLINE(6116) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = ret->next; HXLINE(6117) ret->next = null(); } HXLINE(6124) ret->elt = o; HXLINE(6105) ::zpp_nape::util::ZNPNode_ZPP_CutVert temp = ret; HXLINE(6127) if (hx::IsNull( cur )) { HXLINE(6128) temp->next = this->head; HXLINE(6129) this->head = temp; } else { HXLINE(6132) temp->next = cur->next; HXLINE(6133) cur->next = temp; } HXLINE(6135) this->pushmod = (this->modified = true); HXLINE(6136) this->length++; HXLINE(6137) return temp; } HX_DEFINE_DYNAMIC_FUNC2(ZNPList_ZPP_CutVert_obj,inlined_insert,return ) void ZNPList_ZPP_CutVert_obj::pop(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6140_pop) HXDLIN(6140) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXDLIN(6140) this->head = ret->next; HXDLIN(6140) { HXDLIN(6140) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = ret; HXDLIN(6140) o->elt = null(); HXDLIN(6140) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6140) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6140) if (hx::IsNull( this->head )) { HXDLIN(6140) this->pushmod = true; } HXDLIN(6140) this->modified = true; HXDLIN(6140) this->length--; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,pop,(void)) void ZNPList_ZPP_CutVert_obj::inlined_pop(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6144_inlined_pop) HXLINE(6153) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXLINE(6154) this->head = ret->next; HXLINE(6156) { HXLINE(6157) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = ret; HXLINE(6166) o->elt = null(); HXLINE(6167) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXLINE(6168) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXLINE(6173) if (hx::IsNull( this->head )) { HXLINE(6173) this->pushmod = true; } HXLINE(6174) this->modified = true; HXLINE(6175) this->length--; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,inlined_pop,(void)) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::pop_unsafe(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6178_pop_unsafe) HXDLIN(6178) ::zpp_nape::geom::ZPP_CutVert ret = this->head->elt; HXDLIN(6178) this->pop(); HXDLIN(6178) return ret; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,pop_unsafe,return ) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::inlined_pop_unsafe(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6182_inlined_pop_unsafe) HXLINE(6191) ::zpp_nape::geom::ZPP_CutVert ret = this->head->elt; HXLINE(6192) this->pop(); HXLINE(6193) return ret; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,inlined_pop_unsafe,return ) void ZNPList_ZPP_CutVert_obj::remove( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6204_remove) HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert pre = null(); HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = this->head; HXDLIN(6204) bool ret = false; HXDLIN(6204) while(hx::IsNotNull( cur )){ HXDLIN(6204) if (hx::IsEq( cur->elt,obj )) { HXDLIN(6204) { HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert old; HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret1; HXDLIN(6204) if (hx::IsNull( pre )) { HXDLIN(6204) old = this->head; HXDLIN(6204) ret1 = old->next; HXDLIN(6204) this->head = ret1; HXDLIN(6204) if (hx::IsNull( this->head )) { HXDLIN(6204) this->pushmod = true; } } else { HXDLIN(6204) old = pre->next; HXDLIN(6204) ret1 = old->next; HXDLIN(6204) pre->next = ret1; HXDLIN(6204) if (hx::IsNull( ret1 )) { HXDLIN(6204) this->pushmod = true; } } HXDLIN(6204) { HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = old; HXDLIN(6204) o->elt = null(); HXDLIN(6204) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6204) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6204) this->modified = true; HXDLIN(6204) this->length--; HXDLIN(6204) this->pushmod = true; } HXDLIN(6204) ret = true; HXDLIN(6204) goto _hx_goto_13; } HXDLIN(6204) pre = cur; HXDLIN(6204) cur = cur->next; } _hx_goto_13:; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,remove,(void)) bool ZNPList_ZPP_CutVert_obj::try_remove( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6206_try_remove) HXLINE(6215) ::zpp_nape::util::ZNPNode_ZPP_CutVert pre = null(); HXLINE(6216) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = this->head; HXLINE(6217) bool ret = false; HXLINE(6218) while(hx::IsNotNull( cur )){ HXLINE(6219) if (hx::IsEq( cur->elt,obj )) { HXLINE(6220) this->erase(pre); HXLINE(6221) ret = true; HXLINE(6222) goto _hx_goto_15; } HXLINE(6224) pre = cur; HXLINE(6225) cur = cur->next; } _hx_goto_15:; HXLINE(6227) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,try_remove,return ) void ZNPList_ZPP_CutVert_obj::inlined_remove( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6240_inlined_remove) HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert pre = null(); HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = this->head; HXDLIN(6240) bool ret = false; HXDLIN(6240) while(hx::IsNotNull( cur )){ HXDLIN(6240) if (hx::IsEq( cur->elt,obj )) { HXDLIN(6240) { HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert old; HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret1; HXDLIN(6240) if (hx::IsNull( pre )) { HXDLIN(6240) old = this->head; HXDLIN(6240) ret1 = old->next; HXDLIN(6240) this->head = ret1; HXDLIN(6240) if (hx::IsNull( this->head )) { HXDLIN(6240) this->pushmod = true; } } else { HXDLIN(6240) old = pre->next; HXDLIN(6240) ret1 = old->next; HXDLIN(6240) pre->next = ret1; HXDLIN(6240) if (hx::IsNull( ret1 )) { HXDLIN(6240) this->pushmod = true; } } HXDLIN(6240) { HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = old; HXDLIN(6240) o->elt = null(); HXDLIN(6240) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6240) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6240) this->modified = true; HXDLIN(6240) this->length--; HXDLIN(6240) this->pushmod = true; } HXDLIN(6240) ret = true; HXDLIN(6240) goto _hx_goto_17; } HXDLIN(6240) pre = cur; HXDLIN(6240) cur = cur->next; } _hx_goto_17:; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,inlined_remove,(void)) bool ZNPList_ZPP_CutVert_obj::inlined_try_remove( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6244_inlined_try_remove) HXLINE(6253) ::zpp_nape::util::ZNPNode_ZPP_CutVert pre = null(); HXLINE(6254) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = this->head; HXLINE(6255) bool ret = false; HXLINE(6256) while(hx::IsNotNull( cur )){ HXLINE(6257) if (hx::IsEq( cur->elt,obj )) { HXLINE(6258) { HXLINE(6258) ::zpp_nape::util::ZNPNode_ZPP_CutVert old; HXDLIN(6258) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret1; HXDLIN(6258) if (hx::IsNull( pre )) { HXLINE(6258) old = this->head; HXDLIN(6258) ret1 = old->next; HXDLIN(6258) this->head = ret1; HXDLIN(6258) if (hx::IsNull( this->head )) { HXLINE(6258) this->pushmod = true; } } else { HXLINE(6258) old = pre->next; HXDLIN(6258) ret1 = old->next; HXDLIN(6258) pre->next = ret1; HXDLIN(6258) if (hx::IsNull( ret1 )) { HXLINE(6258) this->pushmod = true; } } HXDLIN(6258) { HXLINE(6258) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = old; HXDLIN(6258) o->elt = null(); HXDLIN(6258) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6258) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6258) this->modified = true; HXDLIN(6258) this->length--; HXDLIN(6258) this->pushmod = true; } HXLINE(6259) ret = true; HXLINE(6260) goto _hx_goto_19; } HXLINE(6262) pre = cur; HXLINE(6263) cur = cur->next; } _hx_goto_19:; HXLINE(6265) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,inlined_try_remove,return ) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::erase( ::zpp_nape::util::ZNPNode_ZPP_CutVert pre){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6268_erase) HXDLIN(6268) ::zpp_nape::util::ZNPNode_ZPP_CutVert old; HXDLIN(6268) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXDLIN(6268) if (hx::IsNull( pre )) { HXDLIN(6268) old = this->head; HXDLIN(6268) ret = old->next; HXDLIN(6268) this->head = ret; HXDLIN(6268) if (hx::IsNull( this->head )) { HXDLIN(6268) this->pushmod = true; } } else { HXDLIN(6268) old = pre->next; HXDLIN(6268) ret = old->next; HXDLIN(6268) pre->next = ret; HXDLIN(6268) if (hx::IsNull( ret )) { HXDLIN(6268) this->pushmod = true; } } HXDLIN(6268) { HXDLIN(6268) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = old; HXDLIN(6268) o->elt = null(); HXDLIN(6268) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6268) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6268) this->modified = true; HXDLIN(6268) this->length--; HXDLIN(6268) this->pushmod = true; HXDLIN(6268) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,erase,return ) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::inlined_erase( ::zpp_nape::util::ZNPNode_ZPP_CutVert pre){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6272_inlined_erase) HXLINE(6281) ::zpp_nape::util::ZNPNode_ZPP_CutVert old; HXLINE(6282) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret; HXLINE(6283) if (hx::IsNull( pre )) { HXLINE(6284) old = this->head; HXLINE(6285) ret = old->next; HXLINE(6286) this->head = ret; HXLINE(6287) if (hx::IsNull( this->head )) { HXLINE(6287) this->pushmod = true; } } else { HXLINE(6290) old = pre->next; HXLINE(6291) ret = old->next; HXLINE(6292) pre->next = ret; HXLINE(6293) if (hx::IsNull( ret )) { HXLINE(6293) this->pushmod = true; } } HXLINE(6296) { HXLINE(6297) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = old; HXLINE(6306) o->elt = null(); HXLINE(6307) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXLINE(6308) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXLINE(6313) this->modified = true; HXLINE(6314) this->length--; HXLINE(6315) this->pushmod = true; HXLINE(6316) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,inlined_erase,return ) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::splice( ::zpp_nape::util::ZNPNode_ZPP_CutVert pre,int n){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6318_splice) HXLINE(6319) while(true){ HXLINE(6319) bool _hx_tmp; HXDLIN(6319) n = (n - 1); HXDLIN(6319) if (((n + 1) > 0)) { HXLINE(6319) _hx_tmp = hx::IsNotNull( pre->next ); } else { HXLINE(6319) _hx_tmp = false; } HXDLIN(6319) if (!(_hx_tmp)) { HXLINE(6319) goto _hx_goto_23; } HXDLIN(6319) this->erase(pre); } _hx_goto_23:; HXLINE(6320) return pre->next; } HX_DEFINE_DYNAMIC_FUNC2(ZNPList_ZPP_CutVert_obj,splice,return ) void ZNPList_ZPP_CutVert_obj::clear(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6323_clear) HXDLIN(6323) while(hx::IsNotNull( this->head )){ HXDLIN(6323) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXDLIN(6323) this->head = ret->next; HXDLIN(6323) { HXDLIN(6323) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = ret; HXDLIN(6323) o->elt = null(); HXDLIN(6323) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6323) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6323) if (hx::IsNull( this->head )) { HXDLIN(6323) this->pushmod = true; } HXDLIN(6323) this->modified = true; HXDLIN(6323) this->length--; } HXDLIN(6323) this->pushmod = true; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,clear,(void)) void ZNPList_ZPP_CutVert_obj::inlined_clear(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6328_inlined_clear) HXLINE(6329) while(hx::IsNotNull( this->head )){ HXLINE(6329) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXDLIN(6329) this->head = ret->next; HXDLIN(6329) { HXLINE(6329) ::zpp_nape::util::ZNPNode_ZPP_CutVert o = ret; HXDLIN(6329) o->elt = null(); HXDLIN(6329) o->next = ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool; HXDLIN(6329) ::zpp_nape::util::ZNPNode_ZPP_CutVert_obj::zpp_pool = o; } HXDLIN(6329) if (hx::IsNull( this->head )) { HXLINE(6329) this->pushmod = true; } HXDLIN(6329) this->modified = true; HXDLIN(6329) this->length--; } HXLINE(6330) this->pushmod = true; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,inlined_clear,(void)) void ZNPList_ZPP_CutVert_obj::reverse(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6333_reverse) HXLINE(6334) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = this->head; HXLINE(6335) ::zpp_nape::util::ZNPNode_ZPP_CutVert pre = null(); HXLINE(6336) while(hx::IsNotNull( cur )){ HXLINE(6337) ::zpp_nape::util::ZNPNode_ZPP_CutVert nx = cur->next; HXLINE(6338) cur->next = pre; HXLINE(6339) this->head = cur; HXLINE(6340) pre = cur; HXLINE(6341) cur = nx; } HXLINE(6343) this->modified = true; HXLINE(6344) this->pushmod = true; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,reverse,(void)) bool ZNPList_ZPP_CutVert_obj::empty(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6349_empty) HXDLIN(6349) return hx::IsNull( this->head ); } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,empty,return ) int ZNPList_ZPP_CutVert_obj::size(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6354_size) HXDLIN(6354) return this->length; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,size,return ) bool ZNPList_ZPP_CutVert_obj::has( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6357_has) HXDLIN(6357) bool ret; HXDLIN(6357) { HXDLIN(6357) ret = false; HXDLIN(6357) { HXDLIN(6357) ::zpp_nape::util::ZNPNode_ZPP_CutVert cx_ite = this->head; HXDLIN(6357) while(hx::IsNotNull( cx_ite )){ HXDLIN(6357) ::zpp_nape::geom::ZPP_CutVert npite = cx_ite->elt; HXDLIN(6357) if (hx::IsEq( npite,obj )) { HXDLIN(6357) ret = true; HXDLIN(6357) goto _hx_goto_33; } HXDLIN(6357) cx_ite = cx_ite->next; } _hx_goto_33:; } } HXDLIN(6357) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,has,return ) bool ZNPList_ZPP_CutVert_obj::inlined_has( ::zpp_nape::geom::ZPP_CutVert obj){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6361_inlined_has) HXLINE(6370) bool ret; HXLINE(6371) { HXLINE(6372) ret = false; HXLINE(6373) { HXLINE(6374) ::zpp_nape::util::ZNPNode_ZPP_CutVert cx_ite = this->head; HXLINE(6375) while(hx::IsNotNull( cx_ite )){ HXLINE(6376) ::zpp_nape::geom::ZPP_CutVert npite = cx_ite->elt; HXLINE(6378) if (hx::IsEq( npite,obj )) { HXLINE(6379) ret = true; HXLINE(6380) goto _hx_goto_35; } HXLINE(6383) cx_ite = cx_ite->next; } _hx_goto_35:; } } HXLINE(6387) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,inlined_has,return ) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::front(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6392_front) HXDLIN(6392) return this->head->elt; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,front,return ) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::back(){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6394_back) HXLINE(6395) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXLINE(6396) ::zpp_nape::util::ZNPNode_ZPP_CutVert cur = ret; HXLINE(6397) while(hx::IsNotNull( cur )){ HXLINE(6398) ret = cur; HXLINE(6399) cur = cur->next; } HXLINE(6401) return ret->elt; } HX_DEFINE_DYNAMIC_FUNC0(ZNPList_ZPP_CutVert_obj,back,return ) ::zpp_nape::util::ZNPNode_ZPP_CutVert ZNPList_ZPP_CutVert_obj::iterator_at(int ind){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6403_iterator_at) HXLINE(6412) ::zpp_nape::util::ZNPNode_ZPP_CutVert ret = this->head; HXLINE(6413) while(true){ HXLINE(6413) bool _hx_tmp; HXDLIN(6413) ind = (ind - 1); HXDLIN(6413) if (((ind + 1) > 0)) { HXLINE(6413) _hx_tmp = hx::IsNotNull( ret ); } else { HXLINE(6413) _hx_tmp = false; } HXDLIN(6413) if (!(_hx_tmp)) { HXLINE(6413) goto _hx_goto_40; } HXDLIN(6413) ret = ret->next; } _hx_goto_40:; HXLINE(6414) return ret; } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,iterator_at,return ) ::zpp_nape::geom::ZPP_CutVert ZNPList_ZPP_CutVert_obj::at(int ind){ HX_STACKFRAME(&_hx_pos_378a7638927e1295_6416_at) HXLINE(6425) ::zpp_nape::util::ZNPNode_ZPP_CutVert it = this->iterator_at(ind); HXLINE(6426) if (hx::IsNotNull( it )) { HXLINE(6426) return it->elt; } else { HXLINE(6426) return null(); } HXDLIN(6426) return null(); } HX_DEFINE_DYNAMIC_FUNC1(ZNPList_ZPP_CutVert_obj,at,return ) hx::ObjectPtr< ZNPList_ZPP_CutVert_obj > ZNPList_ZPP_CutVert_obj::__new() { hx::ObjectPtr< ZNPList_ZPP_CutVert_obj > __this = new ZNPList_ZPP_CutVert_obj(); __this->__construct(); return __this; } hx::ObjectPtr< ZNPList_ZPP_CutVert_obj > ZNPList_ZPP_CutVert_obj::__alloc(hx::Ctx *_hx_ctx) { ZNPList_ZPP_CutVert_obj *__this = (ZNPList_ZPP_CutVert_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ZNPList_ZPP_CutVert_obj), true, "zpp_nape.util.ZNPList_ZPP_CutVert")); *(void **)__this = ZNPList_ZPP_CutVert_obj::_hx_vtable; __this->__construct(); return __this; } ZNPList_ZPP_CutVert_obj::ZNPList_ZPP_CutVert_obj() { } void ZNPList_ZPP_CutVert_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ZNPList_ZPP_CutVert); HX_MARK_MEMBER_NAME(head,"head"); HX_MARK_MEMBER_NAME(modified,"modified"); HX_MARK_MEMBER_NAME(pushmod,"pushmod"); HX_MARK_MEMBER_NAME(length,"length"); HX_MARK_END_CLASS(); } void ZNPList_ZPP_CutVert_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(head,"head"); HX_VISIT_MEMBER_NAME(modified,"modified"); HX_VISIT_MEMBER_NAME(pushmod,"pushmod"); HX_VISIT_MEMBER_NAME(length,"length"); } hx::Val ZNPList_ZPP_CutVert_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"at") ) { return hx::Val( at_dyn() ); } break; case 3: if (HX_FIELD_EQ(inName,"add") ) { return hx::Val( add_dyn() ); } if (HX_FIELD_EQ(inName,"pop") ) { return hx::Val( pop_dyn() ); } if (HX_FIELD_EQ(inName,"has") ) { return hx::Val( has_dyn() ); } break; case 4: if (HX_FIELD_EQ(inName,"head") ) { return hx::Val( head ); } if (HX_FIELD_EQ(inName,"size") ) { return hx::Val( size_dyn() ); } if (HX_FIELD_EQ(inName,"back") ) { return hx::Val( back_dyn() ); } break; case 5: if (HX_FIELD_EQ(inName,"begin") ) { return hx::Val( begin_dyn() ); } if (HX_FIELD_EQ(inName,"erase") ) { return hx::Val( erase_dyn() ); } if (HX_FIELD_EQ(inName,"clear") ) { return hx::Val( clear_dyn() ); } if (HX_FIELD_EQ(inName,"empty") ) { return hx::Val( empty_dyn() ); } if (HX_FIELD_EQ(inName,"front") ) { return hx::Val( front_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"length") ) { return hx::Val( length ); } if (HX_FIELD_EQ(inName,"addAll") ) { return hx::Val( addAll_dyn() ); } if (HX_FIELD_EQ(inName,"insert") ) { return hx::Val( insert_dyn() ); } if (HX_FIELD_EQ(inName,"remove") ) { return hx::Val( remove_dyn() ); } if (HX_FIELD_EQ(inName,"splice") ) { return hx::Val( splice_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"pushmod") ) { return hx::Val( pushmod ); } if (HX_FIELD_EQ(inName,"reverse") ) { return hx::Val( reverse_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"modified") ) { return hx::Val( modified ); } if (HX_FIELD_EQ(inName,"setbegin") ) { return hx::Val( setbegin_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"pop_unsafe") ) { return hx::Val( pop_unsafe_dyn() ); } if (HX_FIELD_EQ(inName,"try_remove") ) { return hx::Val( try_remove_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"inlined_add") ) { return hx::Val( inlined_add_dyn() ); } if (HX_FIELD_EQ(inName,"inlined_pop") ) { return hx::Val( inlined_pop_dyn() ); } if (HX_FIELD_EQ(inName,"inlined_has") ) { return hx::Val( inlined_has_dyn() ); } if (HX_FIELD_EQ(inName,"iterator_at") ) { return hx::Val( iterator_at_dyn() ); } break; case 13: if (HX_FIELD_EQ(inName,"inlined_erase") ) { return hx::Val( inlined_erase_dyn() ); } if (HX_FIELD_EQ(inName,"inlined_clear") ) { return hx::Val( inlined_clear_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"inlined_insert") ) { return hx::Val( inlined_insert_dyn() ); } if (HX_FIELD_EQ(inName,"inlined_remove") ) { return hx::Val( inlined_remove_dyn() ); } break; case 18: if (HX_FIELD_EQ(inName,"inlined_pop_unsafe") ) { return hx::Val( inlined_pop_unsafe_dyn() ); } if (HX_FIELD_EQ(inName,"inlined_try_remove") ) { return hx::Val( inlined_try_remove_dyn() ); } } return super::__Field(inName,inCallProp); } hx::Val ZNPList_ZPP_CutVert_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"head") ) { head=inValue.Cast< ::zpp_nape::util::ZNPNode_ZPP_CutVert >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"length") ) { length=inValue.Cast< int >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"pushmod") ) { pushmod=inValue.Cast< bool >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"modified") ) { modified=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void ZNPList_ZPP_CutVert_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("head",20,29,0b,45)); outFields->push(HX_("modified",49,db,c7,16)); outFields->push(HX_("pushmod",28,29,4b,75)); outFields->push(HX_("length",e6,94,07,9f)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo ZNPList_ZPP_CutVert_obj_sMemberStorageInfo[] = { {hx::fsObject /* ::zpp_nape::util::ZNPNode_ZPP_CutVert */ ,(int)offsetof(ZNPList_ZPP_CutVert_obj,head),HX_("head",20,29,0b,45)}, {hx::fsBool,(int)offsetof(ZNPList_ZPP_CutVert_obj,modified),HX_("modified",49,db,c7,16)}, {hx::fsBool,(int)offsetof(ZNPList_ZPP_CutVert_obj,pushmod),HX_("pushmod",28,29,4b,75)}, {hx::fsInt,(int)offsetof(ZNPList_ZPP_CutVert_obj,length),HX_("length",e6,94,07,9f)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *ZNPList_ZPP_CutVert_obj_sStaticStorageInfo = 0; #endif static ::String ZNPList_ZPP_CutVert_obj_sMemberFields[] = { HX_("head",20,29,0b,45), HX_("begin",29,ea,55,b0), HX_("modified",49,db,c7,16), HX_("pushmod",28,29,4b,75), HX_("length",e6,94,07,9f), HX_("setbegin",47,e3,5c,2b), HX_("add",21,f2,49,00), HX_("inlined_add",8d,4c,2e,02), HX_("addAll",80,09,fb,9e), HX_("insert",39,43,dd,9d), HX_("inlined_insert",4d,34,10,a7), HX_("pop",91,5d,55,00), HX_("inlined_pop",fd,b7,39,02), HX_("pop_unsafe",54,7c,ec,75), HX_("inlined_pop_unsafe",68,87,ef,15), HX_("remove",44,9c,88,04), HX_("try_remove",08,b2,16,8d), HX_("inlined_remove",58,8d,bb,0d), HX_("inlined_try_remove",1c,bd,19,2d), HX_("erase",e6,e8,1c,73), HX_("inlined_erase",52,b6,9d,fa), HX_("splice",7c,85,9e,bf), HX_("clear",8d,71,5b,48), HX_("inlined_clear",f9,3e,dc,cf), HX_("reverse",22,39,fc,1a), HX_("empty",8d,3a,da,6f), HX_("size",c1,a0,53,4c), HX_("has",5a,3f,4f,00), HX_("inlined_has",c6,99,33,02), HX_("front",a9,18,8e,06), HX_("back",27,da,10,41), HX_("iterator_at",e4,89,d2,06), HX_("at",f3,54,00,00), ::String(null()) }; hx::Class ZNPList_ZPP_CutVert_obj::__mClass; void ZNPList_ZPP_CutVert_obj::__register() { ZNPList_ZPP_CutVert_obj _hx_dummy; ZNPList_ZPP_CutVert_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("zpp_nape.util.ZNPList_ZPP_CutVert",be,8c,99,57); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(ZNPList_ZPP_CutVert_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< ZNPList_ZPP_CutVert_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ZNPList_ZPP_CutVert_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ZNPList_ZPP_CutVert_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace zpp_nape } // end namespace util
42.164294
234
0.699891
HedgehogFog
2017a1208d51761c56fe70dcbfeb96ec5d0085d4
7,961
hpp
C++
src/utilities/OStream/multiOStream.hpp
lhb8125/unstructure_frame_home_0218
e543850413879f120ce68d2c786002b166a62fe5
[ "Apache-2.0" ]
null
null
null
src/utilities/OStream/multiOStream.hpp
lhb8125/unstructure_frame_home_0218
e543850413879f120ce68d2c786002b166a62fe5
[ "Apache-2.0" ]
1
2020-09-10T01:17:13.000Z
2020-09-10T01:17:13.000Z
src/utilities/OStream/multiOStream.hpp
lhb8125/unstructure_frame_home_0218
e543850413879f120ce68d2c786002b166a62fe5
[ "Apache-2.0" ]
2
2019-11-29T08:00:29.000Z
2019-11-29T08:26:13.000Z
/* Copyright (C) * 2019 - Hu Ren, rh890127a@163.com * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ /** * @file MultiOStream.hpp * @brief class MultiOStream will linked with multiple files, and output * contents to those files simutaneously. * * @author Hu Ren, rh890127a@163.com * @version v0.1 * @date 2019-08-13 */ #include "OStream.hpp" #include <stdlib.h> #ifndef HSF_MULTIOSTREAM_HPP #define HSF_MULTIOSTREAM_HPP namespace HSF { class MultiOStream : public OStream { // core file stream vector<ostream*> files_; // if it is redirected vector<bool> redirected_; // original stream buffer holder in case redirected vector<StrBuf*> buffers_; public: //-------------------------------------------------------------- // construct & deconstruct //-------------------------------------------------------------- // construct empty MultiOStream() : files_(0),redirected_(0), buffers_(0) {} // construct from file name MultiOStream(const string* filename, int num = 1) : files_(num, NULL), redirected_(num, false), buffers_(num, NULL) { for(int i = 0; i < num; i++) files_[i] = new ofstream(filename[i].c_str()); } // construct from file buffer MultiOStream(StrBuf** rbuf, int num = 1) : files_(num, NULL), redirected_(num, true), buffers_(num, NULL) { for(int i = 0; i < num ; i++) { files_[i] = new ofstream(); buffers_[i] = files_[i]->rdbuf(); files_[i]->ostream::rdbuf(rbuf[i]); } } // No clone or operator= (before C++11) for ostream /* // copy constructor MultiOStream( const MultiOStream& ref ) : OStream(ref), files_(0), redirected_(0), buffers_(0) { // copy data size_t size = ref.getFileNum(); for(size_t i = 0; i < size; i++) { this->files_.push_back(ref.getRawStream(i)->clone() ); this->redirected_.push_back(ref.redirected(i) ); this->buffers_.push_back(ref.getStrBuf(i)->clone() ); } } // clone virtual MultiOStream* clone() { return new MultiOStream(*this) }; // assign operator void operator = ( const MultiOStream& ref ) { // deconstruct the older first to close file for(int i = 0; i < files_.size(); i++) { if( redirected_[i] ) files_[i]->ostream::rdbuf(buffers_[i]); if( files_[i]->rdbuf() != cout.rdbuf() && files_[i]->rdbuf() != NULL ) ((ofstream*) files_[i] )->close(); delete files_[i]; } // clear containers files_.resize(0); redirected_.resize(0); buffers_.resize(0); // copy data size_t size = ref.getFileNum(); for(size_t i = 0; i < size; i++) { this->files_.push_back(ref.getRawStream(i)->clone() ); this->redirected_.push_back(ref.redirected(i) ); this->buffers_.push_back(ref.getStrBuf(i)->clone() ); } } */ // deconstruct virtual ~MultiOStream() { for(int i = 0; i < files_.size(); i++) { if( redirected_[i] ) files_[i]->ostream::rdbuf(buffers_[i]); if( files_[i]->rdbuf() != cout.rdbuf() && files_[i]->rdbuf() != NULL ) ((ofstream*) files_[i] )->close(); delete files_[i]; } } //-------------------------------------------------------------- // redirecting & access //-------------------------------------------------------------- virtual int redirect(StrBuf* rbuf, int pos = 0) { if(pos >= files_.size()) { cerr<<__FILE__<<" + "<<__LINE__<<": "<<endl <<__FUNCTION__<<": "<<endl <<"Error: manipulation on an undefined object!"<<endl; exit( -1 ); } if(redirected_[pos]) files_[pos]->ostream::rdbuf(rbuf); else { redirected_[pos] = true; buffers_[pos] = files_[pos]->rdbuf(); files_[pos]->ostream::rdbuf(rbuf); } } virtual int reset(int pos = 0) { if(pos >= files_.size()) { cerr<<__FILE__<<" + "<<__LINE__<<": "<<endl <<__FUNCTION__<<": "<<endl <<"Error: manipulation on an undefined object!"<<endl; exit( -1 ); } if(redirected_[pos]) { files_[pos]->ostream::rdbuf(buffers_[pos]); redirected_[pos] = false; } } virtual const ostream* getRawStream(int pos = 0) { return files_[pos]; } virtual StrBuf* getStrBuf(int pos = 0) { return files_[pos]->rdbuf(); } virtual bool redirected(int pos = 0) { return redirected_[pos]; } virtual size_t getFileNum() { return files_.size(); } // add new file virtual int addFile(const string& filename) { files_.push_back(NULL); *(files_.end() - 1 )= new ofstream(filename.c_str()); redirected_.push_back(false); buffers_.push_back(NULL); } // add new buffer virtual int addBuffer(StrBuf* buf) { files_.push_back(NULL); files_[files_.size() - 1 ] = new ofstream(); redirected_.push_back(true); buffers_.push_back(files_[files_.size() - 1 ]->rdbuf() ); files_[files_.size() - 1 ]->ostream::rdbuf(buf); } // erase last file virtual int closeLast() { if(files_.size() > 0 ) { int pos = files_.size() - 1; if( redirected_[pos] ) files_[pos]->ostream::rdbuf(buffers_[pos]); if( files_[pos]->rdbuf() != cout.rdbuf() && files_[pos]->rdbuf() != NULL ) ((ofstream*) files_[pos] )->close(); delete files_[pos]; files_.pop_back(); buffers_.pop_back(); redirected_.pop_back(); } else return 0; } //-------------------------------------------------------------- // streaming operator //-------------------------------------------------------------- virtual MultiOStream & operator<<(char chrt) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<chrt; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(string str) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<str; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(int64_t val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(int32_t val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(unsigned long val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(unsigned int val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(double val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } virtual MultiOStream & operator<<(float val) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<val; return (MultiOStream &) *this; } /** * @brief operator<<, interface accept OsOp type parameters * @param[in] opt, represent parameter like "ENDL" and "FLUSH". * @return */ virtual MultiOStream & operator<<(OsOp opt) { for(int i = 0; i < files_.size(); i++ ) *(this->files_[i])<<opt; return (MultiOStream &) *this; } }; }// namespace HSF #endif // HSF_MULTIOSTREAM_HPP
26.273927
78
0.570908
lhb8125
201c495ed49f29a8dad3964eeaa9fbbbb834c07f
417
cpp
C++
projects/engine/src/rendering/viewport.cpp
zCubed3/Silica
c4aa6d8e204b96320ad092e324930b3ef0e26aaa
[ "BSD-3-Clause" ]
null
null
null
projects/engine/src/rendering/viewport.cpp
zCubed3/Silica
c4aa6d8e204b96320ad092e324930b3ef0e26aaa
[ "BSD-3-Clause" ]
null
null
null
projects/engine/src/rendering/viewport.cpp
zCubed3/Silica
c4aa6d8e204b96320ad092e324930b3ef0e26aaa
[ "BSD-3-Clause" ]
null
null
null
#include "viewport.hpp" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/quaternion.hpp> #include "render_target.hpp" namespace Manta::Rendering { void Viewport::UpdateViewport() { float aspect = (float)rect.width / (float)rect.height; perspective = glm::perspective(glm::radians(fov), aspect, z_near, z_far); eye = perspective * view; } }
26.0625
81
0.685851
zCubed3
201dce607c0f5c17539aa648b73aa59c1be9f0d9
270
hpp
C++
src/android/jni/Cube.hpp
ZKing1000/cordova-plugin-coventina-native
d704e5cfe4c4427a53b245eeb397a8c694235dfe
[ "Apache-2.0" ]
1
2019-06-20T16:57:43.000Z
2019-06-20T16:57:43.000Z
src/android/jni/Cube.hpp
ZKing1000/cordova-plugin-coventina-native
d704e5cfe4c4427a53b245eeb397a8c694235dfe
[ "Apache-2.0" ]
null
null
null
src/android/jni/Cube.hpp
ZKing1000/cordova-plugin-coventina-native
d704e5cfe4c4427a53b245eeb397a8c694235dfe
[ "Apache-2.0" ]
null
null
null
// vim: sw=4 expandtab #ifndef CUBE_HPP_ #define CUBE_HPP_ #include "MeshItem.hpp" #include <glm/vec3.hpp> #include <cstdint> namespace game { class Cube : public MeshItem { public: static void genGraphics(); void draw(); }; } #endif
12.857143
34
0.62963
ZKing1000
2021c46c575e7a0155786e48ce2decf3cc4ad868
12,855
hpp
C++
SDK/ARKSurvivalEvolved_Deinonychus_AnimBP_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Deinonychus_AnimBP_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Deinonychus_AnimBP_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Deinonychus_AnimBP_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.BlueprintPlayAnimationEvent struct UDeinonychus_AnimBP_C_BlueprintPlayAnimationEvent_Params { class UAnimMontage** AnimationMontage; // (Parm, ZeroConstructor, IsPlainOldData) float* PlayRate; // (Parm, ZeroConstructor, IsPlainOldData) float playedAnimLength; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7418 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7418_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5892 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5892_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7417 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7417_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ModifyBone_1048 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ModifyBone_1048_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5891 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5891_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5890 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5890_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5889 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5889_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5888 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5888_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7416 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7416_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7415 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7415_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5887 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5887_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5886 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5886_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7412 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7412_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7411 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7411_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5885 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5885_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5884 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5884_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7410 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7410_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7409 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7409_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5883 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5883_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5882 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5882_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5881 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5881_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ModifyBone_1047 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ModifyBone_1047_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5880 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5880_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5879 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5879_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5878 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5878_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_GroundBones_334 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_GroundBones_334_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_GroundBones_333 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_GroundBones_333_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ApplyAdditive_578 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ApplyAdditive_578_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5877 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5877_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_RotationOffsetBlendSpace_362 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_RotationOffsetBlendSpace_362_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_TwoWayBlend_114 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_TwoWayBlend_114_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7404 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7404_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_TwoWayBlend_113 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_TwoWayBlend_113_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7403 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7403_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5876 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5876_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7402 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7402_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5875 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_BlendListByBool_5875_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7401 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_SequencePlayer_7401_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ApplyAdditive_577 struct UDeinonychus_AnimBP_C_EvaluateGraphExposedInputs_ExecuteUbergraph_Deinonychus_AnimBP_AnimGraphNode_ApplyAdditive_577_Params { }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.BlueprintUpdateAnimation struct UDeinonychus_AnimBP_C_BlueprintUpdateAnimation_Params { float* DeltaTimeX; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Deinonychus_AnimBP.Deinonychus_AnimBP_C.ExecuteUbergraph_Deinonychus_AnimBP struct UDeinonychus_AnimBP_C_ExecuteUbergraph_Deinonychus_AnimBP_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
54.240506
161
0.894982
2bite
202204da367db1c8429deed9c79627e93bc34540
6,663
cpp
C++
Development-Delivery/Motor2D/j1Scene.cpp
MarcArizaAlborni/Development_Plataformas
44815d8581738977d20cb1be2b0481adef53c8d1
[ "Unlicense" ]
null
null
null
Development-Delivery/Motor2D/j1Scene.cpp
MarcArizaAlborni/Development_Plataformas
44815d8581738977d20cb1be2b0481adef53c8d1
[ "Unlicense" ]
null
null
null
Development-Delivery/Motor2D/j1Scene.cpp
MarcArizaAlborni/Development_Plataformas
44815d8581738977d20cb1be2b0481adef53c8d1
[ "Unlicense" ]
null
null
null
#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Map.h" #include "j1Scene.h" #include "j1FadeToBlack.h" #include "j1Pathfinding.h" #include "j1EntityManager.h" #include "j1Player.h" #include "j1Skeleton.h" #include "j1SceneUI.h" #include "Brofiler/Brofiler.h" j1Scene::j1Scene() : j1Module() { name.create("scene"); debug_path = false; } // Destructor j1Scene::~j1Scene() {} // Called before render is available bool j1Scene::Awake(pugi::xml_node& config) { LOG("Loading Scene"); bool ret = true; pugi::xml_node spawn = config.child("spawn"); Skeleton1.x = spawn.child("Skeleton1").attribute("x").as_int(); Skeleton1.y = spawn.child("Skeleton1").attribute("y").as_int(); Skeleton2.x = spawn.child("Skeleton2").attribute("x").as_int(); Skeleton2.y = spawn.child("Skeleton2").attribute("y").as_int(); Skeleton3.x = spawn.child("Skeleton3").attribute("x").as_int(); Skeleton3.y = spawn.child("Skeleton3").attribute("y").as_int(); Skull1.x = spawn.child("Skull1").attribute("x").as_int(); Skull1.y = spawn.child("Skull1").attribute("y").as_int(); Bee1.x = spawn.child("Bee1").attribute("x").as_int(); Bee1.y = spawn.child("Bee1").attribute("y").as_int(); MapItem1.x = spawn.child("Map1").attribute("x").as_int(); MapItem1.y = spawn.child("Map1").attribute("y").as_int(); MapItem2.x = spawn.child("Map2").attribute("x").as_int(); MapItem2.y = spawn.child("Map2").attribute("y").as_int(); MapItem3.x = spawn.child("Map3").attribute("x").as_int(); MapItem3.y = spawn.child("Map3").attribute("y").as_int(); MapItem4.x = spawn.child("Map4").attribute("x").as_int(); MapItem4.y = spawn.child("Map4").attribute("y").as_int(); IngameMenuOFFb = false; IngameMenuONb = false; return ret; } // Called before the first frame bool j1Scene::Start() { BROFILER_CATEGORY("Scene Start();", Profiler::Color::SkyBlue) if (App->map->Load("SimpleLevel1.tmx") == true) { StartMap1(); //CREEM UN BOO, QUE DETECTI QUIN NIVELL S'HA CARREGAT I DESPRES CREI ELS OBJECTES QUE SIGUIN D'AQUELL MAPA } debug_tex = App->tex->Load("maps/rosa.png"); App->audio->PlayMusic(App->map->data.MusicAudio_Files.GetString()); /*if (App->map->Load("SimpleLevel2.tmx") == true) { StartMap2(); }*/ return true; } // Called each loop iteration bool j1Scene::PreUpdate() { BROFILER_CATEGORY("Scene PreUpdate();", Profiler::Color::Brown) return true; } // Called each loop iteration bool j1Scene::Update(float dt) { //OPEN CLOSE INGAME MENU if (App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN && App->scene_ui->OnMainMenu!=true && App->scene_ui->OnSettingsMenu!=true && App->scene_ui->OnCreditsMenu!=true) { if (App->scene_ui->OnIngameMenu == false) { App->scene_ui->IngameMenuON(); App->scene_ui->OnIngameMenu = true; if (App->scene_ui->bMuteIngameOFF == true) { App->scene_ui->MuteIngameOFF(); App->scene_ui->UnMuteIngameON(); } else { App->scene_ui->MuteIngameON(); App->scene_ui->UnMuteIngameOFF(); } } else { App->scene_ui->IngameMenuOFF(); App->scene_ui->OnIngameMenu = false; App->scene_ui->MuteIngameOFF(); App->scene_ui->UnMuteIngameOFF(); } } if (App->input->GetKey(SDL_SCANCODE_GRAVE) == KEY_DOWN) { LOG("CONSOLE OPENED"); if (App->scene_ui->OnConsole == false) { App->scene_ui->ConsoleON(); App->scene_ui->OnConsole = true; } else { LOG("CONSOLE CLOSED"); App->scene_ui->ConsoleOFF(); App->scene_ui->OnConsole = false; } } /*if (App->input->GetKey(SDL_SCANCODE_Y) == KEY_DOWN) { App->scene_ui->MainMenuON(); }*/ /*if ((App->input->GetKey(SDL_SCANCODE_L) == KEY_DOWN)) { if (App->scene_ui->OnSettingsMenu == false) { App->scene_ui->SettingsMenuON(); App->scene_ui->OnSettingsMenu = true; LOG("SETTINGS MENU WITH L ON"); } else { App->scene_ui->SettingsMenuOFF(); App->scene_ui->OnSettingsMenu = false; LOG("SETTINGS MENU WITH L OFF"); } }*/ BROFILER_CATEGORY("Scene Update();", Profiler::Color::Thistle) if (App->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN) App->LoadGame(); if (App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN) App->SaveGame("save_game.xml"); //App->SaveGame(); /*if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN) { App->fade->FadeToBlack("SimpleLevel1.tmx"); StartMap1(); } if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN) { App->fade->FadeToBlack("SimpleLevel2.tmx"); StartMap2(); }*/ App->map->Draw(); if (App->input->keyboard[SDL_SCANCODE_F9] == KEY_DOWN) { if (debug_path) { debug_path = false; } else { debug_path = true; } } if (debug_path == false) return true; int x, y; App->input->GetMousePosition(x, y); return true; } // Called each loop iteration bool j1Scene::PostUpdate() { BROFILER_CATEGORY("Scene PostUpdate();", Profiler::Color::DarkBlue) //VOLUMEN /*if (App->input->GetKey(SDL_SCANCODE_KP_PLUS) == KEY_DOWN) { App->audio->general_volume += 5; App->audio->SetVolumeMusic(); } if (App->input->GetKey(SDL_SCANCODE_KP_MINUS) == KEY_DOWN) { App->audio->general_volume -= 5; App->audio->SetVolumeMusic(); }*/ bool ret = true; /*if (App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false;*/ return ret; } // Called before quitting bool j1Scene::CleanUp() { BROFILER_CATEGORY("Scene Start();", Profiler::Color::PeachPuff) LOG("Freeing scene"); return true; } bool j1Scene::Save(pugi::xml_node& data)const { pugi::xml_node mapname = data.append_child(""); return true; } void j1Scene::StartMap1() { Map1Loaded = true; int w, h; uchar* data = NULL; if (App->map->CreateWalkabilityMap(w, h, &data)) App->pathfinding->SetMap(w, h, data); RELEASE_ARRAY(data); // ENEMY SPAWNS LEVEL 1 App->entityManager->AddEnemies(Skeleton1, SKELETON); App->entityManager->AddEnemies(Bee1, BEE); App->entityManager->AddEnemies(Skeleton2, SKELETON); App->entityManager->AddEnemies(Skull1, SKULL); App->entityManager->AddEnemies(Skeleton3, SKELETON); App->entityManager->CreateEntity(PLAYER); //MAP ITEM ENTITY SPAWN App->entityManager->AddEnemies(MapItem1, MAP); App->entityManager->AddEnemies(MapItem2, MAP); App->entityManager->AddEnemies(MapItem3, MAP); App->entityManager->AddEnemies(MapItem4, MAP); } void j1Scene::StartMap2() { App->entityManager->AddEnemies(MapItem1, MAP); App->entityManager->AddEnemies(MapItem2, MAP); App->entityManager->AddEnemies(MapItem3, MAP); App->entityManager->AddEnemies(MapItem4, MAP); App->entityManager->CreateEntity(PLAYER); } void j1Scene::RestartLevelEntitiesL1() { }
22.818493
171
0.679124
MarcArizaAlborni
2024c3d98a97d73df5bdaebbde964bdd00b622e3
612
hpp
C++
external/keko_ctab/ctab/shared/cTab_markerMenu_macros.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
6
2018-05-05T22:28:57.000Z
2019-07-06T08:46:51.000Z
external/keko_ctab/ctab/shared/cTab_markerMenu_macros.hpp
Schwaggot/kellerkompanie-mods
7a389e49e3675866dbde1b317a44892926976e9d
[ "MIT" ]
107
2018-04-11T19:42:27.000Z
2019-09-13T19:05:31.000Z
external/keko_ctab/ctab/shared/cTab_markerMenu_macros.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
3
2018-10-03T11:54:46.000Z
2019-02-28T13:30:16.000Z
/* Required defines: MENU_sizeEx - Menu text size (height) */ // place the menu outside of the visible area #define MENU_X safeZoneXAbs + safeZoneWAbs #define MENU_Y safeZoneY + safeZoneH #define MENU_maxChars 12 // used to determine the necessary width of the menu #define MENU_wPerChar MENU_sizeEx * 3/4 * 0.5 // assume characters 50% width relative to height #define MENU_W (MENU_maxChars + 1.5) * MENU_wPerChar // add 1.5 characters for padding #define MENU_elementH MENU_sizeEx / 0.8 #define MENU_elementY(item) MENU_elementH * (item - 1) #define MENU_H(noOfElements) (noOfElements + 0.5) * MENU_elementH
38.25
95
0.76634
kellerkompanie
202a482a2227101c86d65a83181d73fe1ccaee9f
983
cpp
C++
Microsoft.Toolkit.Uwp.Input.GazeInteraction/GazeStats.cpp
paulcam206/WindowsCommunityToolkit
eb20ae30788f320127b2c809cad5c8bbfbd9e663
[ "MIT" ]
3
2021-05-27T00:29:00.000Z
2021-05-27T13:10:00.000Z
Microsoft.Toolkit.Uwp.Input.GazeInteraction/GazeStats.cpp
DLozanoNavas/UWPCommunityToolkit
e58479b546cbc264d391de214f3a17557088e109
[ "MIT" ]
9
2018-04-11T21:05:47.000Z
2018-05-04T03:02:07.000Z
Microsoft.Toolkit.Uwp.Input.GazeInteraction/GazeStats.cpp
DLozanoNavas/UWPCommunityToolkit
e58479b546cbc264d391de214f3a17557088e109
[ "MIT" ]
1
2020-07-31T11:15:48.000Z
2020-07-31T11:15:48.000Z
//Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. //See LICENSE in the project root for license information. #include "pch.h" #include "GazeStats.h" using namespace Platform::Collections; BEGIN_NAMESPACE_GAZE_INPUT GazeStats::GazeStats(int maxHistoryLen) { _maxHistoryLen = maxHistoryLen; _history = ref new Vector<Point>(); } void GazeStats::Reset() { _sumX = 0; _sumY = 0; _sumSquaredX = 0; _sumSquaredY = 0; _history->Clear(); } void GazeStats::Update(float x, float y) { Point pt(x, y); _history->Append(pt); if (_history->Size > _maxHistoryLen) { auto oldest = _history->GetAt(0); _history->RemoveAt(0); _sumX -= oldest.X; _sumY -= oldest.Y; _sumSquaredX -= oldest.X * oldest.X; _sumSquaredY -= oldest.Y * oldest.Y; } _sumX += x; _sumY += y; _sumSquaredX += x * x; _sumSquaredY += y * y; } END_NAMESPACE_GAZE_INPUT
20.479167
79
0.626653
paulcam206
202bb71b0d6fadd105929e02716275e4755984d7
833
cpp
C++
ZeldaClone/src/main.cpp
dwjclark11/ZeldaClone_NES
5d91cad0e071b45dfb10a6b86ac11a26642ad037
[ "MIT" ]
7
2021-08-23T09:56:00.000Z
2022-03-21T15:29:15.000Z
ZeldaClone/src/main.cpp
dwjclark11/ZeldaClone_NES
5d91cad0e071b45dfb10a6b86ac11a26642ad037
[ "MIT" ]
null
null
null
ZeldaClone/src/main.cpp
dwjclark11/ZeldaClone_NES
5d91cad0e071b45dfb10a6b86ac11a26642ad037
[ "MIT" ]
null
null
null
#include "Game/Game.h" #include "Systems/CameraMovementSystem.h" #include "Systems/NameSystems/NameSelectKeyboardControlSystem.h" int main() { if (!Registry::Instance()->HasSystem<SoundFXSystem>()) Registry::Instance()->AddSystem<SoundFXSystem>(); if (!Registry::Instance()->HasSystem<MusicPlayerSystem>()) Registry::Instance()->AddSystem<MusicPlayerSystem>(); if (!Registry::Instance()->HasSystem<CameraMovementSystem>()) Registry::Instance()->AddSystem<CameraMovementSystem>(); // Is this needed here? if (!Registry::Instance()->HasSystem<NameSelectKeyboardControlSystem>()) Registry::Instance()->AddSystem<NameSelectKeyboardControlSystem>(); // Turn music volume down Mix_VolumeMusic(10); // Run the game Instance--> There is a loop inside this Game::Instance()->Run(); Game::Instance()->Shutdown(); }
33.32
73
0.734694
dwjclark11
202c2c9366707524fef063fbd7870343aa657e4f
725
hpp
C++
src/cmd/definition.hpp
moralismercatus/kmap
6887780c2fbe795f07a81808ef31f11dad4f5043
[ "MIT" ]
1
2021-06-28T00:31:08.000Z
2021-06-28T00:31:08.000Z
src/cmd/definition.hpp
moralismercatus/kmap
6887780c2fbe795f07a81808ef31f11dad4f5043
[ "MIT" ]
null
null
null
src/cmd/definition.hpp
moralismercatus/kmap
6887780c2fbe795f07a81808ef31f11dad4f5043
[ "MIT" ]
null
null
null
/****************************************************************************** * Author(s): Christopher J. Havlicek * * See LICENSE and CONTACTS. ******************************************************************************/ #pragma once #ifndef KMAP_CMD_DEFINITION_HPP #define KMAP_CMD_DEFINITION_HPP #include "../cli.hpp" #include <functional> namespace kmap { class Kmap; } namespace kmap::cmd { auto create_definition( Kmap& kmap ) -> std::function< Result< std::string >( CliCommand::Args const& args ) >; auto add_definition( Kmap& kmap ) -> std::function< Result< std::string >( CliCommand::Args const& args ) >; } // namespace kmap::cmd #endif // KMAP_CMD_DEFINITION_HPP
26.851852
81
0.525517
moralismercatus
202c37dbbcb20fcc3d5d3400975e2a43475cb403
14,241
hpp
C++
ThirdParty-mod/java2cpp/android/os/Process.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/android/os/Process.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/android/os/Process.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: android.os.Process ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_OS_PROCESS_HPP_DECL #define J2CPP_ANDROID_OS_PROCESS_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } #include <java/lang/Object.hpp> #include <java/lang/String.hpp> namespace j2cpp { namespace android { namespace os { class Process; class Process : public object<Process> { 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_FIELD(0) J2CPP_DECLARE_FIELD(1) J2CPP_DECLARE_FIELD(2) J2CPP_DECLARE_FIELD(3) J2CPP_DECLARE_FIELD(4) J2CPP_DECLARE_FIELD(5) J2CPP_DECLARE_FIELD(6) J2CPP_DECLARE_FIELD(7) J2CPP_DECLARE_FIELD(8) J2CPP_DECLARE_FIELD(9) J2CPP_DECLARE_FIELD(10) J2CPP_DECLARE_FIELD(11) J2CPP_DECLARE_FIELD(12) J2CPP_DECLARE_FIELD(13) J2CPP_DECLARE_FIELD(14) J2CPP_DECLARE_FIELD(15) J2CPP_DECLARE_FIELD(16) J2CPP_DECLARE_FIELD(17) explicit Process(jobject jobj) : object<Process>(jobj) { } operator local_ref<java::lang::Object>() const; Process(); static jlong getElapsedCpuTime(); static jint myPid(); static jint myTid(); static jint myUid(); static jint getUidForName(local_ref< java::lang::String > const&); static jint getGidForName(local_ref< java::lang::String > const&); static void setThreadPriority(jint, jint); static void setThreadPriority(jint); static jint getThreadPriority(jint); static jboolean supportsProcesses(); static void killProcess(jint); static void sendSignal(jint, jint); static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > SYSTEM_UID; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > PHONE_UID; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > FIRST_APPLICATION_UID; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), jint > LAST_APPLICATION_UID; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), jint > BLUETOOTH_GID; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(5), J2CPP_FIELD_SIGNATURE(5), jint > THREAD_PRIORITY_DEFAULT; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(6), J2CPP_FIELD_SIGNATURE(6), jint > THREAD_PRIORITY_LOWEST; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(7), J2CPP_FIELD_SIGNATURE(7), jint > THREAD_PRIORITY_BACKGROUND; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(8), J2CPP_FIELD_SIGNATURE(8), jint > THREAD_PRIORITY_FOREGROUND; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(9), J2CPP_FIELD_SIGNATURE(9), jint > THREAD_PRIORITY_DISPLAY; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(10), J2CPP_FIELD_SIGNATURE(10), jint > THREAD_PRIORITY_URGENT_DISPLAY; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(11), J2CPP_FIELD_SIGNATURE(11), jint > THREAD_PRIORITY_AUDIO; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(12), J2CPP_FIELD_SIGNATURE(12), jint > THREAD_PRIORITY_URGENT_AUDIO; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(13), J2CPP_FIELD_SIGNATURE(13), jint > THREAD_PRIORITY_MORE_FAVORABLE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(14), J2CPP_FIELD_SIGNATURE(14), jint > THREAD_PRIORITY_LESS_FAVORABLE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(15), J2CPP_FIELD_SIGNATURE(15), jint > SIGNAL_QUIT; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(16), J2CPP_FIELD_SIGNATURE(16), jint > SIGNAL_KILL; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(17), J2CPP_FIELD_SIGNATURE(17), jint > SIGNAL_USR1; }; //class Process } //namespace os } //namespace android } //namespace j2cpp #endif //J2CPP_ANDROID_OS_PROCESS_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_OS_PROCESS_HPP_IMPL #define J2CPP_ANDROID_OS_PROCESS_HPP_IMPL namespace j2cpp { android::os::Process::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } android::os::Process::Process() : object<android::os::Process>( call_new_object< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(0), android::os::Process::J2CPP_METHOD_SIGNATURE(0) >() ) { } jlong android::os::Process::getElapsedCpuTime() { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(1), android::os::Process::J2CPP_METHOD_SIGNATURE(1), jlong >(); } jint android::os::Process::myPid() { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(2), android::os::Process::J2CPP_METHOD_SIGNATURE(2), jint >(); } jint android::os::Process::myTid() { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(3), android::os::Process::J2CPP_METHOD_SIGNATURE(3), jint >(); } jint android::os::Process::myUid() { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(4), android::os::Process::J2CPP_METHOD_SIGNATURE(4), jint >(); } jint android::os::Process::getUidForName(local_ref< java::lang::String > const &a0) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(5), android::os::Process::J2CPP_METHOD_SIGNATURE(5), jint >(a0); } jint android::os::Process::getGidForName(local_ref< java::lang::String > const &a0) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(6), android::os::Process::J2CPP_METHOD_SIGNATURE(6), jint >(a0); } void android::os::Process::setThreadPriority(jint a0, jint a1) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(7), android::os::Process::J2CPP_METHOD_SIGNATURE(7), void >(a0, a1); } void android::os::Process::setThreadPriority(jint a0) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(8), android::os::Process::J2CPP_METHOD_SIGNATURE(8), void >(a0); } jint android::os::Process::getThreadPriority(jint a0) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(9), android::os::Process::J2CPP_METHOD_SIGNATURE(9), jint >(a0); } jboolean android::os::Process::supportsProcesses() { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(10), android::os::Process::J2CPP_METHOD_SIGNATURE(10), jboolean >(); } void android::os::Process::killProcess(jint a0) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(11), android::os::Process::J2CPP_METHOD_SIGNATURE(11), void >(a0); } void android::os::Process::sendSignal(jint a0, jint a1) { return call_static_method< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_METHOD_NAME(12), android::os::Process::J2CPP_METHOD_SIGNATURE(12), void >(a0, a1); } static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(0), android::os::Process::J2CPP_FIELD_SIGNATURE(0), jint > android::os::Process::SYSTEM_UID; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(1), android::os::Process::J2CPP_FIELD_SIGNATURE(1), jint > android::os::Process::PHONE_UID; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(2), android::os::Process::J2CPP_FIELD_SIGNATURE(2), jint > android::os::Process::FIRST_APPLICATION_UID; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(3), android::os::Process::J2CPP_FIELD_SIGNATURE(3), jint > android::os::Process::LAST_APPLICATION_UID; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(4), android::os::Process::J2CPP_FIELD_SIGNATURE(4), jint > android::os::Process::BLUETOOTH_GID; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(5), android::os::Process::J2CPP_FIELD_SIGNATURE(5), jint > android::os::Process::THREAD_PRIORITY_DEFAULT; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(6), android::os::Process::J2CPP_FIELD_SIGNATURE(6), jint > android::os::Process::THREAD_PRIORITY_LOWEST; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(7), android::os::Process::J2CPP_FIELD_SIGNATURE(7), jint > android::os::Process::THREAD_PRIORITY_BACKGROUND; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(8), android::os::Process::J2CPP_FIELD_SIGNATURE(8), jint > android::os::Process::THREAD_PRIORITY_FOREGROUND; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(9), android::os::Process::J2CPP_FIELD_SIGNATURE(9), jint > android::os::Process::THREAD_PRIORITY_DISPLAY; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(10), android::os::Process::J2CPP_FIELD_SIGNATURE(10), jint > android::os::Process::THREAD_PRIORITY_URGENT_DISPLAY; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(11), android::os::Process::J2CPP_FIELD_SIGNATURE(11), jint > android::os::Process::THREAD_PRIORITY_AUDIO; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(12), android::os::Process::J2CPP_FIELD_SIGNATURE(12), jint > android::os::Process::THREAD_PRIORITY_URGENT_AUDIO; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(13), android::os::Process::J2CPP_FIELD_SIGNATURE(13), jint > android::os::Process::THREAD_PRIORITY_MORE_FAVORABLE; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(14), android::os::Process::J2CPP_FIELD_SIGNATURE(14), jint > android::os::Process::THREAD_PRIORITY_LESS_FAVORABLE; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(15), android::os::Process::J2CPP_FIELD_SIGNATURE(15), jint > android::os::Process::SIGNAL_QUIT; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(16), android::os::Process::J2CPP_FIELD_SIGNATURE(16), jint > android::os::Process::SIGNAL_KILL; static_field< android::os::Process::J2CPP_CLASS_NAME, android::os::Process::J2CPP_FIELD_NAME(17), android::os::Process::J2CPP_FIELD_SIGNATURE(17), jint > android::os::Process::SIGNAL_USR1; J2CPP_DEFINE_CLASS(android::os::Process,"android/os/Process") J2CPP_DEFINE_METHOD(android::os::Process,0,"<init>","()V") J2CPP_DEFINE_METHOD(android::os::Process,1,"getElapsedCpuTime","()J") J2CPP_DEFINE_METHOD(android::os::Process,2,"myPid","()I") J2CPP_DEFINE_METHOD(android::os::Process,3,"myTid","()I") J2CPP_DEFINE_METHOD(android::os::Process,4,"myUid","()I") J2CPP_DEFINE_METHOD(android::os::Process,5,"getUidForName","(Ljava/lang/String;)I") J2CPP_DEFINE_METHOD(android::os::Process,6,"getGidForName","(Ljava/lang/String;)I") J2CPP_DEFINE_METHOD(android::os::Process,7,"setThreadPriority","(II)V") J2CPP_DEFINE_METHOD(android::os::Process,8,"setThreadPriority","(I)V") J2CPP_DEFINE_METHOD(android::os::Process,9,"getThreadPriority","(I)I") J2CPP_DEFINE_METHOD(android::os::Process,10,"supportsProcesses","()Z") J2CPP_DEFINE_METHOD(android::os::Process,11,"killProcess","(I)V") J2CPP_DEFINE_METHOD(android::os::Process,12,"sendSignal","(II)V") J2CPP_DEFINE_FIELD(android::os::Process,0,"SYSTEM_UID","I") J2CPP_DEFINE_FIELD(android::os::Process,1,"PHONE_UID","I") J2CPP_DEFINE_FIELD(android::os::Process,2,"FIRST_APPLICATION_UID","I") J2CPP_DEFINE_FIELD(android::os::Process,3,"LAST_APPLICATION_UID","I") J2CPP_DEFINE_FIELD(android::os::Process,4,"BLUETOOTH_GID","I") J2CPP_DEFINE_FIELD(android::os::Process,5,"THREAD_PRIORITY_DEFAULT","I") J2CPP_DEFINE_FIELD(android::os::Process,6,"THREAD_PRIORITY_LOWEST","I") J2CPP_DEFINE_FIELD(android::os::Process,7,"THREAD_PRIORITY_BACKGROUND","I") J2CPP_DEFINE_FIELD(android::os::Process,8,"THREAD_PRIORITY_FOREGROUND","I") J2CPP_DEFINE_FIELD(android::os::Process,9,"THREAD_PRIORITY_DISPLAY","I") J2CPP_DEFINE_FIELD(android::os::Process,10,"THREAD_PRIORITY_URGENT_DISPLAY","I") J2CPP_DEFINE_FIELD(android::os::Process,11,"THREAD_PRIORITY_AUDIO","I") J2CPP_DEFINE_FIELD(android::os::Process,12,"THREAD_PRIORITY_URGENT_AUDIO","I") J2CPP_DEFINE_FIELD(android::os::Process,13,"THREAD_PRIORITY_MORE_FAVORABLE","I") J2CPP_DEFINE_FIELD(android::os::Process,14,"THREAD_PRIORITY_LESS_FAVORABLE","I") J2CPP_DEFINE_FIELD(android::os::Process,15,"SIGNAL_QUIT","I") J2CPP_DEFINE_FIELD(android::os::Process,16,"SIGNAL_KILL","I") J2CPP_DEFINE_FIELD(android::os::Process,17,"SIGNAL_USR1","I") } //namespace j2cpp #endif //J2CPP_ANDROID_OS_PROCESS_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
33.273364
129
0.739906
kakashidinho
45c8b72a9b627d263b27df6309d722f9c1676ff9
5,591
cxx
C++
src/MergeAlgs/DoMergeAlg.cxx
fermi-lat/Overlay
2cf0c53ba565ceb6f768434874c148777c804c58
[ "BSD-3-Clause" ]
null
null
null
src/MergeAlgs/DoMergeAlg.cxx
fermi-lat/Overlay
2cf0c53ba565ceb6f768434874c148777c804c58
[ "BSD-3-Clause" ]
null
null
null
src/MergeAlgs/DoMergeAlg.cxx
fermi-lat/Overlay
2cf0c53ba565ceb6f768434874c148777c804c58
[ "BSD-3-Clause" ]
null
null
null
/* * @file DoMergeAlg.cxx * * @brief Decides whether or not to read an overlay event * * @author Tracy Usher * * $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/Overlay/src/MergeAlgs/DoMergeAlg.cxx,v 1.4 2011/11/03 18:13:50 usher Exp $ */ #include "GaudiKernel/Algorithm.h" #include "GaudiKernel/MsgStream.h" #include "GaudiKernel/AlgFactory.h" #include "GaudiKernel/SmartDataPtr.h" #include "GaudiKernel/ConversionSvc.h" #include "GaudiKernel/DataSvc.h" #include "GaudiKernel/GenericAddress.h" #include "Event/TopLevel/EventModel.h" #include "Event/MonteCarlo/McPositionHit.h" #include "Event/MonteCarlo/McIntegratingHit.h" #include "OverlayEvent/OverlayEventModel.h" #include "OverlayEvent/EventOverlay.h" #include "Overlay/IOverlayDataSvc.h" #include <map> class DoMergeAlg : public Algorithm { public: DoMergeAlg(const std::string&, ISvcLocator*); StatusCode initialize(); StatusCode execute(); StatusCode finalize(); private: StatusCode setRootEvent(); bool m_mergeAll; IOverlayDataSvc* m_dataSvc; }; // Used by Gaudi for identifying this algorithm //static const AlgFactory<DoMergeAlg> Factory; //const IAlgFactory& DoMergeAlgFactory = Factory; DECLARE_ALGORITHM_FACTORY(DoMergeAlg); DoMergeAlg::DoMergeAlg(const std::string& name, ISvcLocator* pSvcLocator) : Algorithm(name, pSvcLocator) { // variable to bypass if not wanted declareProperty("MergeAll", m_mergeAll = false); } StatusCode DoMergeAlg::initialize() { // Purpose and Method: initializes DoMergeAlg // Inputs: none // Outputs: a status code // Dependencies: value of m_type determining the type of tool to run // Restrictions and Caveats: none StatusCode sc = StatusCode::SUCCESS; MsgStream log(msgSvc(), name()); log << MSG::INFO << "initialize" << endreq; if ( setProperties().isFailure() ) { log << MSG::ERROR << "setProperties() failed" << endreq; return StatusCode::FAILURE; } // Convention for multiple input overlay files is that there will be separate OverlayDataSvc's with // names appended by "_xx", for example OverlayDataSvc_1 for the second input file. // In order to ensure the data read in goes into a unique section of the TDS we need to modify the // base root path, which we do by examining the name of the service std::string dataSvcName = "OverlayDataSvc"; int subPos = name().rfind("_"); std::string nameEnding = subPos > 0 ? name().substr(subPos, name().length() - subPos) : ""; if (nameEnding != "") dataSvcName += nameEnding; IService* dataSvc = 0; sc = service(dataSvcName, dataSvc); if (sc.isFailure() ) { log << MSG::ERROR << " can't get OverlayDataSvc " << endreq; return sc; } // Caste back to the "correct" pointer m_dataSvc = dynamic_cast<IOverlayDataSvc*>(dataSvc); return sc; } StatusCode DoMergeAlg::execute() { // Purpose and Method: execution method (called once for every event) // Doesn't do anything but calls the chosen tool. // Inputs: none // Outputs: a status code // Dependencies: none // Restrictions and Caveats: none StatusCode sc = StatusCode::SUCCESS; MsgStream log(msgSvc(), name()); log << MSG::DEBUG << "execute" << endreq; // Since our overlay stuff is not stored in the /Event section of the TDS, we need // to explicitly "set the root" each event - or risk it not getting cleared. sc = setRootEvent(); if (sc.isFailure()) { log << MSG::ERROR << "Clearing of the Overlay section of TDS failed" << endreq; return sc; } if (m_mergeAll) { log << MSG::DEBUG << "Merging all events, skipping DoMergeAlg" << endreq; return sc; } // How many hits in ACD, TKR or CAL? int numPosHits = 0; int numIntHits = 0; // Recover the McPositionHits for this event SmartDataPtr<Event::McPositionHitCol> posHitCol(eventSvc(), EventModel::MC::McPositionHitCol); if (posHitCol) numPosHits = posHitCol->size(); // Recover the McIntegratingHits for this event SmartDataPtr<Event::McIntegratingHitCol> intHitCol(eventSvc(), EventModel::MC::McIntegratingHitCol); if (intHitCol) numIntHits = intHitCol->size(); // if there are no McPositionHits AND no McIntegratingHits then the simulated particle did not interact if (!(numPosHits > 0 || numIntHits > 0)) setFilterPassed(false); return sc; } StatusCode DoMergeAlg::finalize() { MsgStream log(msgSvc(), name()); log << MSG::INFO << "finalize" << endreq; return StatusCode::SUCCESS; } StatusCode DoMergeAlg::setRootEvent() { StatusCode sc = StatusCode::SUCCESS; // Set up the root event object Event::EventOverlay overObj; // Caste the data service into the input data service pointer DataSvc* dataProviderSvc = dynamic_cast<DataSvc*>(m_dataSvc); // Create a "simple" generic opaque address to go with this IOpaqueAddress* refpAddress = new GenericAddress(EXCEL_StorageType, overObj.clID(), dataProviderSvc->rootName()); sc = dataProviderSvc->setRoot(dataProviderSvc->rootName(), refpAddress); // This is the magic incantation to trigger the building of the directory tree... SmartDataPtr<Event::EventOverlay> overHeader(dataProviderSvc, dataProviderSvc->rootName()); if (!overHeader) sc = StatusCode::FAILURE; return sc; }
30.551913
134
0.669469
fermi-lat
45cc65e0fcf35ac3154d9cf252f9279adb6c6dfe
672
hpp
C++
shared_model/backend/protobuf/util.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
1,467
2016-10-25T12:27:19.000Z
2022-03-28T04:32:05.000Z
shared_model/backend/protobuf/util.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
2,366
2016-10-25T10:07:57.000Z
2022-03-31T22:03:24.000Z
shared_model/backend/protobuf/util.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
662
2016-10-26T04:41:22.000Z
2022-03-31T04:15:02.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_SHARED_MODEL_PROTO_UTIL_HPP #define IROHA_SHARED_MODEL_PROTO_UTIL_HPP #include <google/protobuf/message.h> #include <vector> #include "cryptography/blob.hpp" namespace shared_model { namespace proto { template <typename T> crypto::Blob makeBlob(T &&message) { crypto::Blob::Bytes data; data.resize(message.ByteSizeLong()); message.SerializeToArray(data.data(), data.size()); return crypto::Blob(std::move(data)); } } // namespace proto } // namespace shared_model #endif // IROHA_SHARED_MODEL_PROTO_UTIL_HPP
24
57
0.714286
akshatkarani
45d1dbb8b6e694baaa42ed82da757e23199ab54b
2,765
cpp
C++
ball.cpp
aczapi/PingPong
5f0df3c5453d73181fffc7d96c813c3eb296ddfd
[ "Unlicense" ]
null
null
null
ball.cpp
aczapi/PingPong
5f0df3c5453d73181fffc7d96c813c3eb296ddfd
[ "Unlicense" ]
null
null
null
ball.cpp
aczapi/PingPong
5f0df3c5453d73181fffc7d96c813c3eb296ddfd
[ "Unlicense" ]
null
null
null
#include "ball.hpp" #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include "gameStates.hpp" #include "headers.hpp" #include "mainMenu.hpp" Ball::Ball(std::shared_ptr<Paddle> player1, std::shared_ptr<Paddle> player2, std::shared_ptr<Score> scorePlayer1, std::shared_ptr<Score> scorePlayer2) { this->player1_ = player1; this->player2_ = player2; this->scorePlayer1_ = scorePlayer1; this->scorePlayer2_ = scorePlayer2; this->load("../assets/graphics/ball2.png"); this->buffer_ = new sf::SoundBuffer(); this->buffer_->loadFromFile("../assets/sounds/bounce.wav"); this->sound_ = new sf::Sound(*this->buffer_); this->scoreBuffer_ = new sf::SoundBuffer(); this->scoreBuffer_->loadFromFile("../assets/sounds/glass.wav"); this->scoreSound_ = new sf::Sound(*this->scoreBuffer_); this->scoreSound_->setVolume(50); } void Ball::addVelocity(std::shared_ptr<Paddle> paddle) { if (this->velocity_.y > 0) { if (paddle->velocity_.y > 0) { this->velocity_.y *= 1.30f; } else if (paddle->velocity_.y < 0 && this->velocity_.y != 5.5f) { this->velocity_.y = 5.5f; } } else if (this->velocity_.y < 0) { if (paddle->velocity_.y < 0) { this->velocity_.y *= 1.30f; } else if (paddle->velocity_.y > 0 && this->velocity_.y != -5.5f) { this->velocity_.y = -5.5f; } } } void Ball::update(sf::RenderWindow* window) { if (this->checkCollision(this->player1_)) { this->velocity_.x *= -1; addVelocity(player1_); this->sound_->play(); } if (this->checkCollision(this->player2_)) { this->velocity_.x *= -1; addVelocity(player2_); this->sound_->play(); } if (this->getPosition().y < 0 || this->getPosition().y + this->getGlobalBounds().height > window->getSize().y) { this->velocity_.y *= -1; this->sound_->play(); } if (this->getPosition().x < this->player1_->getGlobalBounds().width - 5) { this->scoreSound_->play(); this->scorePlayer2_->incrementScore(); this->reset(window); } if (this->getPosition().x > window->getSize().x - this->player2_->getGlobalBounds().width + 5) { this->scoreSound_->play(); this->scorePlayer1_->incrementScore(); this->reset(window); } Entity::update(); } void Ball::reset(sf::RenderWindow* window) { this->velocity_.x = ((rand() % 2) == 0) ? 6.5f : -6.5f; this->velocity_.y = ((rand() % 2) == 0) ? 6.5f : -6.5f; this->setPosition(window->getSize().x / 2 - 14, window->getSize().y / 2 - 10); } Ball::~Ball() { delete (this->scoreSound_); delete (this->scoreBuffer_); delete (this->buffer_); delete (this->sound_); }
34.135802
152
0.595298
aczapi
45d3a9ee4be841f88fdd08ec47f1e8588fd35f75
2,306
hxx
C++
main/sd/source/ui/inc/fuformatpaintbrush.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sd/source/ui/inc/fuformatpaintbrush.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sd/source/ui/inc/fuformatpaintbrush.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 SD_FU_FORMATPAINTBRUSH_HXX #define SD_FU_FORMATPAINTBRUSH_HXX #include "futext.hxx" // header for class SfxItemSet #include <svl/itemset.hxx> #include <boost/scoped_ptr.hpp> namespace sd { class DrawViewShell; class FuFormatPaintBrush : public FuText { public: TYPEINFO(); static FunctionReference Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ); virtual sal_Bool MouseMove(const MouseEvent& rMEvt); virtual sal_Bool MouseButtonUp(const MouseEvent& rMEvt); virtual sal_Bool MouseButtonDown(const MouseEvent& rMEvt); virtual sal_Bool KeyInput(const KeyEvent& rKEvt); virtual void Activate(); virtual void Deactivate(); static void GetMenuState( DrawViewShell& rDrawViewShell, SfxItemSet &rSet ); static bool CanCopyThisType( sal_uInt32 nObjectInventor, sal_uInt16 nObjectIdentifier ); private: FuFormatPaintBrush ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq); void DoExecute( SfxRequest& rReq ); bool HasContentForThisType( sal_uInt32 nObjectInventor, sal_uInt16 nObjectIdentifier ) const; void Paste( bool, bool ); void implcancel(); ::boost::shared_ptr<SfxItemSet> mpItemSet; bool mbPermanent; bool mbOldIsQuickTextEditMode; }; } // end of namespace sd #endif
31.589041
134
0.707285
Grosskopf
45dc62b034f9da99c95d3406fc9c14a09226c20a
2,407
cpp
C++
UOJ/62.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
UOJ/62.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
EZOJ/Contests/1425/C.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-07-26T05:54:06.000Z
2020-09-30T13:35:38.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> #include <cctype> using namespace std; typedef long long lint; #define cout cerr #define ni (next_num<int>()) template<class T>inline T next_num(){ T i=0;char c; while(!isdigit(c=getchar())&&c!='-'); bool neg=c=='-'; neg?c=getchar():0; while(i=i*10-'0'+c,isdigit(c=getchar())); return neg?-i:i; } template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){if(a<b)a=b;} template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){if(b<a)a=b;} template<class T>inline void mset(T a,int v,int n){memset(a,v,n*sizeof(a[0]));} const int N=100010,O=998244353; inline int fpow(int x,int n){ int a=1; for(;n;n>>=1,x=(lint)x*x%O){ if(n&1){ a=(lint)a*x%O; } } return a; } inline int mod_inv(int x){ return fpow(x,O-2); } namespace sieve{ int n; int pri[N],ps=0; bool np[N]; int mu[N]; inline void main(int _n){ n=_n; mu[1]=1; for(int i=2;i<=n;i++){ if(!np[i]){ pri[ps++]=i; mu[i]=-1; } for(int j=0,p,t;j<ps&&(p=pri[j],t=i*p,t<=n);j++){ np[t]=true; if(i%p){ mu[t]=-mu[i]; }else{ mu[t]=0; break; } } } } inline void gpw(int pw[],int e){ e=(e%(O-1)+O-1)%(O-1); pw[1]=1; for(int i=2;i<=n;i++){ if(!np[i]){ pw[i]=fpow(i,e); } for(int j=0,p,t;j<ps&&(p=pri[j],t=i*p,t<=n);j++){ pw[t]=(lint)pw[i]*pw[p]%O; if(i%p==0)break; } } } } using sieve::mu; int g[N]; int invpwd[N],pwe[N]; lint b[N]; inline void Main(int n){ mset(b+1,0,n); for(int i=1;i<=n;i++){ int a=next_num<lint>()*invpwd[i]%O; for(int j=1,k=i;k<=n;j++,k+=i){ if(mu[j]){ b[k]+=a*mu[j]; } } } for(int i=1;i<=n;i++){ b[i]%=O; if(b[i]<0){ b[i]+=O; } if(b[i]!=0&&g[i]==0){ puts("-1"); return; } b[i]=(lint)b[i]*g[i]%O; } for(int i=1;i<=n;i++){ lint x=0; for(int j=1,k=i;k<=n;j++,k+=i){ if(mu[j]){ x+=b[k]*mu[j]; } } x=((lint)x%O*invpwd[i]%O+O)%O; printf("%lld ",x); } putchar('\n'); } int main(){ #ifndef ONLINE_JUDGE freopen("round.in","r",stdin); freopen("round.out","w",stdout); #endif int n=ni,c=ni,d=ni; sieve::main(n); sieve::gpw(pwe,c-d); sieve::gpw(invpwd,-d); {//g mset(g+1,0,n); for(int i=1;i<=n;i++){ for(int j=1,k=i;k<=n;j++,k+=i){ if(mu[j]){ g[k]=((lint)g[k]+O+pwe[i]*mu[j])%O; } } g[i]=mod_inv(g[i]); } } for(int tot=ni;tot--;Main(n)); return 0; }
18.234848
79
0.522227
sshockwave
45de1a5eb2b9ca60d7094a034aa0b05e639de2f0
2,630
cpp
C++
libs/input/impl/src/input/impl/multi_system.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/input/impl/src/input/impl/multi_system.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/input/impl/src/input/impl/multi_system.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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 <sge/input/capabilities_field.hpp> #include <sge/input/processor.hpp> #include <sge/input/processor_unique_ptr.hpp> #include <sge/input/system.hpp> #include <sge/input/system_unique_ptr.hpp> #include <sge/input/impl/log_name.hpp> #include <sge/input/impl/multi_processor.hpp> #include <sge/input/impl/multi_system.hpp> #include <sge/input/impl/system_ptr_vector.hpp> #include <sge/input/plugin/collection.hpp> #include <sge/input/plugin/context.hpp> #include <sge/input/plugin/iterator.hpp> #include <sge/input/plugin/object.hpp> #include <sge/input/plugin/traits.hpp> #include <sge/log/default_parameters.hpp> #include <sge/log/location.hpp> #include <sge/window/object_ref.hpp> #include <fcppt/make_unique_ptr.hpp> #include <fcppt/unique_ptr_to_base.hpp> #include <fcppt/algorithm/fold.hpp> #include <fcppt/algorithm/map.hpp> #include <fcppt/container/bitfield/operators.hpp> #include <fcppt/log/context_reference.hpp> sge::input::impl::multi_system::multi_system( fcppt::log::context_reference const _log_context, sge::input::plugin::collection const &_collection) : sge::input::system(), log_{ _log_context, sge::log::location(), sge::log::default_parameters(sge::input::impl::log_name())}, plugins_(fcppt::algorithm::map<sge::input::impl::multi_system::plugin_vector>( _collection, [](sge::input::plugin::context const &_context) { return _context.load(); })), systems_(fcppt::algorithm::map<sge::input::impl::system_ptr_vector>( plugins_, [&_log_context](sge::input::plugin::object const &_plugin) { return _plugin.get()(_log_context); })), capabilities_(fcppt::algorithm::fold( systems_, sge::input::capabilities_field::null(), [](sge::input::system_unique_ptr const &_system, sge::input::capabilities_field const &_state) { return _state | _system->capabilities(); })) { } sge::input::impl::multi_system::~multi_system() = default; sge::input::processor_unique_ptr sge::input::impl::multi_system::create_processor(sge::window::object_ref const _window) { return fcppt::unique_ptr_to_base<sge::input::processor>( fcppt::make_unique_ptr<sge::input::impl::multi_processor>(log_, _window, systems_)); } sge::input::capabilities_field sge::input::impl::multi_system::capabilities() const { return capabilities_; }
39.253731
90
0.709506
cpreh
45e0feccd1590d52dd7d0b56eff3f1f121c66890
12,642
cpp
C++
test/module/irohad/ametsuchi/block_query_test.cpp
truongnmt/iroha
e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1
[ "Apache-2.0" ]
null
null
null
test/module/irohad/ametsuchi/block_query_test.cpp
truongnmt/iroha
e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1
[ "Apache-2.0" ]
null
null
null
test/module/irohad/ametsuchi/block_query_test.cpp
truongnmt/iroha
e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved. * http://soramitsu.co.jp * * 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 <boost/filesystem.hpp> #include <boost/optional.hpp> #include "ametsuchi/impl/postgres_block_index.hpp" #include "ametsuchi/impl/postgres_block_query.hpp" #include "converters/protobuf/json_proto_converter.hpp" #include "framework/result_fixture.hpp" #include "module/irohad/ametsuchi/ametsuchi_fixture.hpp" #include "module/irohad/ametsuchi/ametsuchi_mocks.hpp" #include "module/shared_model/builders/protobuf/test_block_builder.hpp" #include "module/shared_model/builders/protobuf/test_transaction_builder.hpp" using namespace iroha::ametsuchi; using testing::Return; class BlockQueryTest : public AmetsuchiTest { protected: void SetUp() override { AmetsuchiTest::SetUp(); auto tmp = FlatFile::create(block_store_path); ASSERT_TRUE(tmp); file = std::move(*tmp); mock_file = std::make_shared<MockKeyValueStorage>(); sql = std::make_unique<soci::session>(soci::postgresql, pgopt_); index = std::make_shared<PostgresBlockIndex>(*sql); blocks = std::make_shared<PostgresBlockQuery>(*sql, *file); empty_blocks = std::make_shared<PostgresBlockQuery>(*sql, *mock_file); *sql << init_; // First transaction in block1 auto txn1_1 = TestTransactionBuilder().creatorAccountId(creator1).build(); tx_hashes.push_back(txn1_1.hash()); // Second transaction in block1 auto txn1_2 = TestTransactionBuilder().creatorAccountId(creator1).build(); tx_hashes.push_back(txn1_2.hash()); auto block1 = TestBlockBuilder() .height(1) .transactions( std::vector<shared_model::proto::Transaction>({txn1_1, txn1_2})) .prevHash(shared_model::crypto::Hash(zero_string)) .build(); // First tx in block 1 auto txn2_1 = TestTransactionBuilder().creatorAccountId(creator1).build(); tx_hashes.push_back(txn2_1.hash()); // Second tx in block 2 auto txn2_2 = TestTransactionBuilder().creatorAccountId(creator2).build(); tx_hashes.push_back(txn2_2.hash()); auto block2 = TestBlockBuilder() .height(2) .transactions( std::vector<shared_model::proto::Transaction>({txn2_1, txn2_2})) .prevHash(block1.hash()) .build(); for (const auto &b : {std::move(block1), std::move(block2)}) { file->add(b.height(), iroha::stringToBytes( shared_model::converters::protobuf::modelToJson(b))); index->index(b); blocks_total++; } } std::unique_ptr<soci::session> sql; std::vector<shared_model::crypto::Hash> tx_hashes; std::shared_ptr<BlockQuery> blocks; std::shared_ptr<BlockQuery> empty_blocks; std::shared_ptr<BlockIndex> index; std::unique_ptr<FlatFile> file; std::shared_ptr<MockKeyValueStorage> mock_file; std::string creator1 = "user1@test"; std::string creator2 = "user2@test"; std::size_t blocks_total{0}; std::string zero_string = std::string(32, '0'); }; /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions created by user1@test is invoked * @then query over user1@test returns 3 txs */ TEST_F(BlockQueryTest, GetAccountTransactionsFromSeveralBlocks) { // Check that creator1 has created 3 transactions auto txs = blocks->getAccountTransactions(creator1); ASSERT_EQ(txs.size(), 3); std::for_each(txs.begin(), txs.end(), [&](const auto &tx) { EXPECT_EQ(tx->creatorAccountId(), creator1); }); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions created by user2@test is invoked * @then query over user2@test returns 1 tx */ TEST_F(BlockQueryTest, GetAccountTransactionsFromSingleBlock) { // Check that creator1 has created 1 transaction auto txs = blocks->getAccountTransactions(creator2); ASSERT_EQ(txs.size(), 1); std::for_each(txs.begin(), txs.end(), [&](const auto &tx) { EXPECT_EQ(tx->creatorAccountId(), creator2); }); } /** * @given block store * @when query to get transactions created by user with id not registered in the * system is invoked * @then query returns empty result */ TEST_F(BlockQueryTest, GetAccountTransactionsNonExistingUser) { // Check that "nonexisting" user has no transaction auto txs = blocks->getAccountTransactions("nonexisting user"); ASSERT_EQ(txs.size(), 0); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions with existing transaction hashes * @then queried transactions */ TEST_F(BlockQueryTest, GetTransactionsExistingTxHashes) { auto txs = blocks->getTransactions({tx_hashes[1], tx_hashes[3]}); ASSERT_EQ(txs.size(), 2); ASSERT_TRUE(txs[0]); ASSERT_TRUE(txs[1]); ASSERT_EQ(txs[0].get()->hash(), tx_hashes[1]); ASSERT_EQ(txs[1].get()->hash(), tx_hashes[3]); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions with non-existing transaction hashes * @then nullopt values are retrieved */ TEST_F(BlockQueryTest, GetTransactionsIncludesNonExistingTxHashes) { shared_model::crypto::Hash invalid_tx_hash_1(zero_string), invalid_tx_hash_2(std::string( shared_model::crypto::DefaultCryptoAlgorithmType::kHashLength, '9')); auto txs = blocks->getTransactions({invalid_tx_hash_1, invalid_tx_hash_2}); ASSERT_EQ(txs.size(), 2); ASSERT_FALSE(txs[0]); ASSERT_FALSE(txs[1]); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions with empty vector * @then no transactions are retrieved */ TEST_F(BlockQueryTest, GetTransactionsWithEmpty) { // transactions' hashes are empty. auto txs = blocks->getTransactions({}); ASSERT_EQ(txs.size(), 0); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test * AND 1 tx created by user2@test * @when query to get transactions with non-existing txhash and existing txhash * @then queried transactions and empty transaction */ TEST_F(BlockQueryTest, GetTransactionsWithInvalidTxAndValidTx) { // TODO 15/11/17 motxx - Use EqualList VerificationStrategy shared_model::crypto::Hash invalid_tx_hash_1(zero_string); auto txs = blocks->getTransactions({invalid_tx_hash_1, tx_hashes[0]}); ASSERT_EQ(txs.size(), 2); ASSERT_FALSE(txs[0]); ASSERT_TRUE(txs[1]); ASSERT_EQ(txs[1].get()->hash(), tx_hashes[0]); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when get non-existent 1000th block * @then nothing is returned */ TEST_F(BlockQueryTest, GetNonExistentBlock) { auto stored_blocks = blocks->getBlocks(1000, 1); ASSERT_TRUE(stored_blocks.empty()); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when height=1, count=1 * @then returned exactly 1 block */ TEST_F(BlockQueryTest, GetExactlyOneBlock) { auto stored_blocks = blocks->getBlocks(1, 1); ASSERT_EQ(stored_blocks.size(), 1); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when count=0 * @then no blocks returned */ TEST_F(BlockQueryTest, GetBlocks_Count0) { auto stored_blocks = blocks->getBlocks(1, 0); ASSERT_TRUE(stored_blocks.empty()); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when get zero block * @then no blocks returned */ TEST_F(BlockQueryTest, GetZeroBlock) { auto stored_blocks = blocks->getBlocks(0, 1); ASSERT_TRUE(stored_blocks.empty()); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when get all blocks starting from 1 * @then returned all blocks (2) */ TEST_F(BlockQueryTest, GetBlocksFrom1) { auto stored_blocks = blocks->getBlocksFrom(1); ASSERT_EQ(stored_blocks.size(), blocks_total); for (size_t i = 0; i < stored_blocks.size(); i++) { auto b = stored_blocks[i]; ASSERT_EQ(b->height(), i + 1) << "block height: " << b->height() << "counter: " << i; } } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test. Block #1 is filled with trash data * (NOT JSON). * @when read block #1 * @then get no blocks */ TEST_F(BlockQueryTest, GetBlockButItIsNotJSON) { namespace fs = boost::filesystem; size_t block_n = 1; // write something that is NOT JSON to block #1 auto block_path = fs::path{block_store_path} / FlatFile::id_to_name(block_n); fs::ofstream block_file(block_path); std::string content = R"(this is definitely not json)"; block_file << content; block_file.close(); auto stored_blocks = blocks->getBlocks(block_n, 1); ASSERT_TRUE(stored_blocks.empty()); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test. Block #1 is filled with trash data * (NOT JSON). * @when read block #1 * @then get no blocks */ TEST_F(BlockQueryTest, GetBlockButItIsInvalidBlock) { namespace fs = boost::filesystem; size_t block_n = 1; // write bad block instead of block #1 auto block_path = fs::path{block_store_path} / FlatFile::id_to_name(block_n); fs::ofstream block_file(block_path); std::string content = R"({ "testcase": [], "description": "make sure this is valid json, but definitely not a block" })"; block_file << content; block_file.close(); auto stored_blocks = blocks->getBlocks(block_n, 1); ASSERT_TRUE(stored_blocks.empty()); } /** * @given block store with 2 blocks totally containing 3 txs created by * user1@test AND 1 tx created by user2@test * @when get top 2 blocks * @then last 2 blocks returned with correct height */ TEST_F(BlockQueryTest, GetTop2Blocks) { size_t blocks_n = 2; // top 2 blocks auto stored_blocks = blocks->getTopBlocks(blocks_n); ASSERT_EQ(stored_blocks.size(), blocks_n); for (size_t i = 0; i < blocks_n; i++) { auto b = stored_blocks[i]; ASSERT_EQ(b->height(), i + 1); } } /** * @given block store with preinserted blocks * @when hasTxWithHash is invoked on existing transaction hash * @then True is returned */ TEST_F(BlockQueryTest, HasTxWithExistingHash) { for (const auto &hash : tx_hashes) { EXPECT_TRUE(blocks->hasTxWithHash(hash)); } } /** * @given block store with preinserted blocks * user1@test AND 1 tx created by user2@test * @when hasTxWithHash is invoked on non-existing hash * @then False is returned */ TEST_F(BlockQueryTest, HasTxWithInvalidHash) { shared_model::crypto::Hash invalid_tx_hash(zero_string); EXPECT_FALSE(blocks->hasTxWithHash(invalid_tx_hash)); } /** * @given block store with preinserted blocks * @when getTopBlock is invoked on this block store * @then returned top block's height is equal to the inserted one's */ TEST_F(BlockQueryTest, GetTopBlockSuccess) { auto top_block_opt = framework::expected::val(blocks->getTopBlock()); ASSERT_TRUE(top_block_opt); ASSERT_EQ(top_block_opt.value().value->height(), 2); } /** * @given empty block store * @when getTopBlock is invoked on this block store * @then result must be a string error, because no block was fetched */ TEST_F(BlockQueryTest, GetTopBlockFail) { EXPECT_CALL(*mock_file, last_id()).WillRepeatedly(Return(0)); EXPECT_CALL(*mock_file, get(mock_file->last_id())) .WillOnce(Return(boost::none)); auto top_block_error = framework::expected::err(empty_blocks->getTopBlock()); ASSERT_TRUE(top_block_error); ASSERT_EQ(top_block_error.value().error, "error while fetching the last block"); }
32.836364
80
0.712308
truongnmt
45e29e1ccb8f2c0cff0d09f10b218564737845f7
2,481
cpp
C++
Tools/ExtractStrain/SnapFileHelp.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
Tools/ExtractStrain/SnapFileHelp.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
Tools/ExtractStrain/SnapFileHelp.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////// // // // Copyright (c) 2003-2017 by The University of Queensland // // Centre for Geoscience Computing // // http://earth.uq.edu.au/centre-geoscience-computing // // // // Primary Business: Brisbane, Queensland, Australia // // Licensed under the Open Software License version 3.0 // // http://www.apache.org/licenses/LICENSE-2.0 // // // ///////////////////////////////////////////////////////////// #include "SnapFileHelp.h" // --- Project includes --- #include "Foundation/vec3.h" // --- STL includes --- #include <iterator> #include <fstream> #include <set> using std::istream_iterator; using std::back_inserter; using std::ifstream; using std::make_pair; using std::set; int get_version(const string& infilename) { string dummystring; int version; ifstream headerfile(infilename.c_str()); // read token headerfile >> dummystring; if(dummystring=="V"){ // if V -> new version headerfile >> version ; cout << "version : " << version << endl; } else { cout << "pre- V.1 version" << endl; version=0; } headerfile.close(); return version; } vector<string> get_filenames(const string& infilename, int version) { cout << "infilename : " << infilename << endl; ifstream headerfile(infilename.c_str()); float dummy,xmax,ymax,zmax,xmin,ymin,zmin; vector<string> filenames; string dummystring; if(version==0){ headerfile >> dummy >> dummy >> dummy; headerfile >> dummystring >> dummy; } else if ((version==1) || (version==2) || (version==3)){ headerfile >> dummystring >> dummy; headerfile >> dummy >> dummy >> dummy; headerfile >> dummystring >> dummy; } else { cerr << "unknown checkpoint version " << version << endl; } // get bounding box headerfile >> dummystring; headerfile >> xmin >> ymin >> zmin >> xmax >> ymax >> zmax ; // ignore periodic bdry headerfile >> dummystring >> dummy >> dummy >> dummy; // ignore dimension headerfile >> dummystring >> dummystring; // get file names copy(istream_iterator<string>(headerfile),istream_iterator<string>(),back_inserter(filenames)); headerfile.close(); cout << "nr. of filenames: " << filenames.size() << endl; return filenames; }
29.188235
97
0.566707
danielfrascarelli
45e42a1025c8adc217a96c371d3bb00ac639fb17
1,112
cpp
C++
LuoguCodes/P1968.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/P1968.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/P1968.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
//【P1968】美元汇率 - 洛谷 - 10 #include <iostream> #include <cstdio> #include <iomanip> #include <algorithm> struct Income { double dollar, mark; Income() {} } *f; int n, *a; void input() { std::cin >> n; a = new int[n + 1]; for (int i = 1; i <= n; ++i) { std::cin >> a[i]; } } int main() { input(); f = new Income[n + 1]; f[1].dollar = 100.0, f[1].mark = a[1]; for (int i = 2; i <= n; ++i) { f[i].dollar = std::max(f[i - 1].dollar, f[i - 1].mark / a[i] * 100.0); f[i].mark = std::max(f[i - 1].mark, f[i - 1].dollar * a[i] / 100.0); } printf("%.2f", (f[n].dollar > f[n].mark ? f[n].dollar : f[n].mark / a[n] * 100.0)); /* double now_my = 100.0, now_mk = 0.0, max_hl = 0.0, min_hl = 2147483647.0; for (int i = 0; i < n; ++i) { if (i + 1 == n) { now_my += now_mk * 100.0 / a[i]; now_mk = 0.0; } else if (a[i] > max_hl) { now_mk += a[i] / 100.0 * now_my; now_my = 0.0; } else if (a[i] < min_hl) { now_my += now_mk * 100.0 / a[i]; now_mk = 0.0; } max_hl = std::max(max_hl, double(a[i])); min_hl = std::min(min_hl, double(a[i])); } printf("%.2f", now_my); */ }
21.803922
84
0.502698
Anguei
45e610bb53c08e45b75bd5842dd978d69f9c3ce6
2,158
cpp
C++
Shared/Io/Timer.cpp
Joon-Jung/HoloLensForCV
fad1818ff1e6afd8bae3a91b710c23a653cbd722
[ "MIT" ]
250
2017-07-26T20:54:22.000Z
2019-05-03T09:21:12.000Z
Shared/Io/Timer.cpp
Joon-Jung/HoloLensForCV
fad1818ff1e6afd8bae3a91b710c23a653cbd722
[ "MIT" ]
79
2017-08-08T20:08:02.000Z
2019-05-06T14:32:45.000Z
Shared/Io/Timer.cpp
Joon-Jung/HoloLensForCV
fad1818ff1e6afd8bae3a91b710c23a653cbd722
[ "MIT" ]
88
2017-07-28T09:11:51.000Z
2019-05-04T03:48:44.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" namespace Io { namespace Internal { // Gets the current number of ticks from QueryPerformanceCounter. Throws an // exception if the call to QueryPerformanceCounter fails. int64_t GetPerformanceCounter() { LARGE_INTEGER counter; ASSERT(QueryPerformanceCounter( &counter)); return counter.QuadPart; } } Timer::Timer() { _qpcTotalStartTime = Internal::GetPerformanceCounter(); _qpcElapsedStartTime = _qpcTotalStartTime; } HundredsOfNanoseconds Timer::GetElapsedTime() const { const int64_t qpcCurrentTime = Internal::GetPerformanceCounter(); const int64_t qpcElapsedTime = qpcCurrentTime - _qpcElapsedStartTime; return _timeConverter.QpcToRelativeTicks( qpcCurrentTime - _qpcElapsedStartTime); } double Timer::GetElapsedSeconds() const { return std::chrono::duration_cast<std::chrono::duration<double>>( GetElapsedTime()).count(); } HundredsOfNanoseconds Timer::GetTotalTime() const { const int64_t qpcCurrentTime = Internal::GetPerformanceCounter(); return _timeConverter.QpcToRelativeTicks( qpcCurrentTime); } double Timer::GetTotalSeconds() const { return std::chrono::duration_cast<std::chrono::duration<double>>( GetTotalTime()).count(); } void Timer::ResetElapsedTime() { _qpcElapsedStartTime = Internal::GetPerformanceCounter(); } }
27.316456
84
0.57507
Joon-Jung
45e648661e82340b235cd566b3b0fa122864856d
425
cpp
C++
GFX/Vulkan/API_without_Secrets/Tutorial01/main.cpp
longlongwaytogo/Learning.test
ded9a25ba789c153d69b2d216599eda962ef83e9
[ "MIT" ]
null
null
null
GFX/Vulkan/API_without_Secrets/Tutorial01/main.cpp
longlongwaytogo/Learning.test
ded9a25ba789c153d69b2d216599eda962ef83e9
[ "MIT" ]
null
null
null
GFX/Vulkan/API_without_Secrets/Tutorial01/main.cpp
longlongwaytogo/Learning.test
ded9a25ba789c153d69b2d216599eda962ef83e9
[ "MIT" ]
null
null
null
#include "Tutorial01.h" int main( int argc, char ** argv ) { ApiWithoutSecrets::OS::Window window; ApiWithoutSecrets::Tutorial01 tutorial01; // window creation if(! window.Create("01-The Beginning") ) { return -1; } // Vulkan preparations and initialization if( !tutorial01.PrepareVulkan() ) { return -1; } // Rendering Loop if(!window.RenderingLoop(tutorial01) ) { return -1; } return 0; }
14.655172
43
0.663529
longlongwaytogo
45e94b3dfd7697ee37a539956a2ef6eade97b84f
1,583
hpp
C++
core/utilities/string.hpp
fritzio/libstl
0709e54e4b13576edf84e393db211fb77efd7f72
[ "MIT" ]
null
null
null
core/utilities/string.hpp
fritzio/libstl
0709e54e4b13576edf84e393db211fb77efd7f72
[ "MIT" ]
null
null
null
core/utilities/string.hpp
fritzio/libstl
0709e54e4b13576edf84e393db211fb77efd7f72
[ "MIT" ]
null
null
null
#ifndef LIBSTL_UTLITIES_STRING_HPP #define LIBSTL_UTLITIES_STRING_HPP #include <array> #include <string> #include <vector> namespace libstl { namespace utilities { namespace string { std::string erase(const std::string& string, const std::string& substring) { std::string s = string; return s.erase(string.find(substring), substring.length()); } std::string trim_leading_whitespace(const std::string& string, const std::string whitespace = " ") { return string.substr(string.find_first_not_of(whitespace)); } std::string trim_trailing_whitespace(const std::string& string, const std::string whitespace = " ") { return string.substr(0, string.find_last_not_of(whitespace) + 1); } std::vector<std::string> split(const std::string& string, const std::string delimiter = " ") { std::vector<std::string> splitted_string; std::string s = string; std::size_t pos = 0; while ((pos = s.find(delimiter)) != std::string::npos) { std::string token = s.substr(0, pos); splitted_string.push_back(token); s.erase(0, pos + delimiter.length()); } splitted_string.push_back(s); return splitted_string; } std::vector<std::string> trim_and_split(const std::string& string, const std::string delimiter = " ", const std::string whitespace = " ") { return split(trim_trailing_whitespace(trim_leading_whitespace(string, whitespace), whitespace), delimiter); } } // namespace string } // namespace utilities } // namespace libstl #endif // LIBSTL_UTLITIES_STRING_HPP
26.830508
111
0.684776
fritzio
45e9bbade0ee125116c9f34aaa3263b5f7990dd2
2,148
cpp
C++
src/jet/live/LiveDelegate.cpp
cpei-avalara/jet-live
27593e29606456e822aee49384aafce97d914acd
[ "MIT" ]
null
null
null
src/jet/live/LiveDelegate.cpp
cpei-avalara/jet-live
27593e29606456e822aee49384aafce97d914acd
[ "MIT" ]
null
null
null
src/jet/live/LiveDelegate.cpp
cpei-avalara/jet-live
27593e29606456e822aee49384aafce97d914acd
[ "MIT" ]
null
null
null
#include "LiveDelegate.hpp" #include "jet/live/CompileCommandsCompilationUnitsParser.hpp" #include "jet/live/DefaultProgramInfoLoader.hpp" #include "jet/live/DepfileDependenciesHandler.hpp" #include "jet/live/Utility.hpp" namespace jet { void LiveDelegate::onLog(LogSeverity, const std::string&) {} void LiveDelegate::onCodePreLoad() {} void LiveDelegate::onCodePostLoad() {} size_t LiveDelegate::getWorkerThreadsCount() { return 4; } std::vector<std::string> LiveDelegate::getDirectoriesToMonitor() { return {}; } bool LiveDelegate::shouldReloadMachoSymbol(const MachoContext& context, const MachoSymbol& symbol) { return (symbol.external && symbol.type == MachoSymbolType::kSection && symbol.sectionIndex == context.textSectionIndex && !symbol.weakDef); } bool LiveDelegate::shouldReloadElfSymbol(const ElfContext& context, const ElfSymbol& symbol) { static const std::string textSectionName = ".text"; return (symbol.type == ElfSymbolType::kFunction && symbol.size != 0 && symbol.sectionIndex < context.sectionNames.size() // Some sections has reserved indices && context.sectionNames[symbol.sectionIndex] == textSectionName); } bool LiveDelegate::shouldTransferMachoSymbol(const MachoContext&, const MachoSymbol&) { return false; } bool LiveDelegate::shouldTransferElfSymbol(const ElfContext& context, const ElfSymbol& symbol) { static const std::string bssSectionName = ".bss"; return (symbol.type == ElfSymbolType::kObject && context.sectionNames[symbol.sectionIndex] == bssSectionName); } std::unique_ptr<ICompilationUnitsParser> LiveDelegate::createCompilationUnitsParser() { return jet::make_unique<CompileCommandsCompilationUnitsParser>(); } std::unique_ptr<IDependenciesHandler> LiveDelegate::createDependenciesHandler() { return jet::make_unique<DepfileDependenciesHandler>(); } std::unique_ptr<IProgramInfoLoader> LiveDelegate::createProgramInfoLoader() { return jet::make_unique<DefaultProgramInfoLoader>(); } }
37.684211
118
0.715549
cpei-avalara
45e9fcf091bd54c2bb4aead9abc73d7963ab7383
620
cpp
C++
contest/1119/d/d.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1119/d/d.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1119/d/d.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; using LL = long long; int main(){ //freopen("in","r",stdin) std::ios::sync_with_stdio(false);std::cin.tie(nullptr); int n; cin>>n; LL a[n]; for(int i=0;i<n;++i) cin>>a[i]; sort(a,a+n); LL b[n]={LL(2e18)}; for(int i=1;i<n;++i) b[i] = a[i]-a[i-1]; sort(b,b+n); LL s[n+1]={0}; for(int i=1;i<=n;++i) s[i]=s[i-1]+b[i-1]; auto f = [&](LL len) -> LL{ int id = upper_bound(b,b+n,len)-b; //cout<<id<<" "<<b[id]<<" "<<len<<endl; return s[id]+(len+1)*(n-id); }; int q; cin>>q; while(q--){ LL l,r; cin>>l>>r; cout<<f(r-l)<<" "; } cout<<endl; return 0; }
19.375
56
0.514516
GoatGirl98
45ec06000883e8f101cf780bfce66c6253b2d5d2
209
cpp
C++
Oficina/CrazyCards/CrazyCards/Hero.cpp
boveloco/Puc
cbc3308fac104098b030dadebdd036fe288bbe0c
[ "MIT" ]
null
null
null
Oficina/CrazyCards/CrazyCards/Hero.cpp
boveloco/Puc
cbc3308fac104098b030dadebdd036fe288bbe0c
[ "MIT" ]
null
null
null
Oficina/CrazyCards/CrazyCards/Hero.cpp
boveloco/Puc
cbc3308fac104098b030dadebdd036fe288bbe0c
[ "MIT" ]
null
null
null
#include "Hero.h" Hero::Hero(int attack, int defense, int life) { this->attack = attack; this->defense = defense; this->life = life; this->debuffAttack = 0; this->debuffDefense = 0; } Hero::~Hero() { }
13.933333
45
0.645933
boveloco
45ec4eec8930c64c8fcb1910df45d16cbfbef69c
938
cpp
C++
backup/2/interviewbit/c++/majority-element.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/interviewbit/c++/majority-element.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/interviewbit/c++/majority-element.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/interviewbit/majority-element.html . int Solution::majorityElement(const vector<int> &A) { int major = A[0], count = 1; for (int i = 1; i < A.size(); i++) { int num = A[i]; if (count == 0) { major = num; count = 1; } else if (major == num) { count++; } else { count--; } } return major; }
44.666667
345
0.630064
yangyanzhan
45eee7518b94d3bd5cfe5e48481db702e775c7da
494
cpp
C++
BaseDataStructure/array/JavaObject.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
39
2020-05-31T06:14:39.000Z
2021-01-09T11:06:39.000Z
BaseDataStructure/array/JavaObject.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
7
2020-06-02T11:04:14.000Z
2020-06-11T14:11:58.000Z
BaseDataStructure/array/JavaObject.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
20
2020-05-31T06:21:57.000Z
2020-10-01T04:48:38.000Z
// // Created by Jesson on 2020/7/18. // #include <cstdio> //#include <malloc.h> #include <cstdlib> #include "JavaObject.h" void objectRetain(JavaObject *obj) { obj->retainCount ++; printf("retain计数+1 = %d\n",obj->retainCount); } void objectRelease(JavaObject *obj) { obj->retainCount --; if (obj->retainCount <= 0) { free(obj); } printf("retain计数-1 = %d\n",obj->retainCount); } //获得当前计数 int getRetainCount(JavaObject *obj) { return obj->retainCount; }
17.642857
49
0.631579
JessonYue
45f884f94ce01ba6ede76e1851e83ac115c28edf
281
hpp
C++
include/generic/geometry/range_space.hpp
shikanle/gfx
772db3ddd66c294beaf17319f6b3803abe3ce0df
[ "Apache-2.0" ]
4
2022-01-06T14:06:03.000Z
2022-01-07T01:13:58.000Z
include/generic/geometry/range_space.hpp
shikanle/gfx
772db3ddd66c294beaf17319f6b3803abe3ce0df
[ "Apache-2.0" ]
null
null
null
include/generic/geometry/range_space.hpp
shikanle/gfx
772db3ddd66c294beaf17319f6b3803abe3ce0df
[ "Apache-2.0" ]
null
null
null
#pragma once namespace gfx { namespace generic { template <typename float_system> class range_space : public object { public: typedef float_system float_system_t; typedef typename float_system_t::float_t float_t; public: dynamic_reflectible(range_space, {}); }; } }
16.529412
53
0.754448
shikanle
45fb63f68cf38af8aec14b27a9d9dfa1e0a12c53
32,363
cc
C++
tensorstore/driver/zarr/spec_test.cc
google/tensorstore
8df16a67553debaec098698ceaa5404eaf79634a
[ "BSD-2-Clause" ]
106
2020-04-02T20:00:18.000Z
2022-03-23T20:27:31.000Z
tensorstore/driver/zarr/spec_test.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
28
2020-04-12T02:04:47.000Z
2022-03-23T20:27:03.000Z
tensorstore/driver/zarr/spec_test.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
18
2020-04-08T06:41:30.000Z
2022-02-18T03:05:49.000Z
// Copyright 2020 The TensorStore Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "tensorstore/driver/zarr/spec.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include <nlohmann/json.hpp> #include "tensorstore/codec_spec.h" #include "tensorstore/driver/zarr/metadata.h" #include "tensorstore/index_space/index_domain_builder.h" #include "tensorstore/internal/json_gtest.h" #include "tensorstore/util/status.h" #include "tensorstore/util/status_testutil.h" namespace { using tensorstore::ChunkLayout; using tensorstore::CodecSpec; using tensorstore::dtype_v; using tensorstore::MatchesJson; using tensorstore::MatchesStatus; using tensorstore::Schema; using tensorstore::internal_zarr::GetFieldIndex; using tensorstore::internal_zarr::ParseDType; using tensorstore::internal_zarr::ParseSelectedField; using tensorstore::internal_zarr::SelectedField; using tensorstore::internal_zarr::ZarrMetadata; using tensorstore::internal_zarr::ZarrPartialMetadata; TEST(ParsePartialMetadataTest, InvalidZarrFormat) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"zarr_format", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"zarr_format\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidChunks) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"chunks", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"chunks\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidShape) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"shape", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"shape\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidCompressor) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"compressor", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"compressor\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidOrder) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"order", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"order\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidDType) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"dtype", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"dtype\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidFilters) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"filters", "x"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"filters\": .*")}, }); } TEST(ParsePartialMetadataTest, Empty) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto result, ZarrPartialMetadata::FromJson(::nlohmann::json::object_t{})); EXPECT_EQ(std::nullopt, result.zarr_format); EXPECT_EQ(std::nullopt, result.order); EXPECT_EQ(std::nullopt, result.compressor); EXPECT_EQ(std::nullopt, result.filters); EXPECT_EQ(std::nullopt, result.dtype); EXPECT_EQ(std::nullopt, result.fill_value); EXPECT_EQ(std::nullopt, result.shape); EXPECT_EQ(std::nullopt, result.chunks); } ::nlohmann::json GetMetadataSpec() { return {{"zarr_format", 2}, {"chunks", {3, 2}}, {"shape", {100, 100}}, {"order", "C"}, {"filters", nullptr}, {"fill_value", nullptr}, {"dtype", "<i2"}, {"compressor", {{"id", "blosc"}, {"blocksize", 0}, {"clevel", 5}, {"cname", "lz4"}, {"shuffle", -1}}}}; } TEST(ParsePartialMetadataTest, Complete) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto result, ZarrPartialMetadata::FromJson(GetMetadataSpec())); EXPECT_EQ(2, result.zarr_format); EXPECT_EQ(tensorstore::c_order, result.order); ASSERT_TRUE(result.compressor); EXPECT_EQ((::nlohmann::json{{"id", "blosc"}, {"blocksize", 0}, {"clevel", 5}, {"cname", "lz4"}, {"shuffle", -1}}), ::nlohmann::json(*result.compressor)); ASSERT_TRUE(result.dtype); EXPECT_EQ("<i2", ::nlohmann::json(*result.dtype)); ASSERT_TRUE(result.fill_value); ASSERT_EQ(1, result.fill_value->size()); EXPECT_FALSE((*result.fill_value)[0].valid()); ASSERT_TRUE(result.shape); EXPECT_THAT(*result.shape, ::testing::ElementsAre(100, 100)); ASSERT_TRUE(result.chunks); EXPECT_THAT(*result.chunks, ::testing::ElementsAre(3, 2)); } TEST(ParseSelectedFieldTest, Null) { EXPECT_EQ(SelectedField(), ParseSelectedField(nullptr)); } TEST(ParseSelectedFieldTest, InvalidString) { EXPECT_THAT( ParseSelectedField(""), MatchesStatus(absl::StatusCode::kInvalidArgument, "Expected null or non-empty string, but received: \"\"")); } TEST(ParseSelectedFieldTest, String) { EXPECT_EQ(SelectedField("label"), ParseSelectedField("label")); } TEST(ParseSelectedFieldTest, InvalidType) { EXPECT_THAT( ParseSelectedField(true), MatchesStatus(absl::StatusCode::kInvalidArgument, "Expected null or non-empty string, but received: true")); } TEST(GetFieldIndexTest, Null) { EXPECT_EQ(0u, GetFieldIndex(ParseDType("<i4").value(), SelectedField())); EXPECT_THAT( GetFieldIndex( ParseDType(::nlohmann::json::array_t{{"x", "<i4"}, {"y", "<u2"}}) .value(), SelectedField()), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Must specify a \"field\" that is one of: \\[\"x\",\"y\"\\]")); } TEST(GetFieldIndexTest, String) { EXPECT_THAT( GetFieldIndex(ParseDType("<i4").value(), "x"), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Requested field \"x\" but dtype does not have named fields")); EXPECT_EQ(0u, GetFieldIndex(ParseDType(::nlohmann::json::array_t{ {"x", "<i4"}, {"y", "<u2"}}) .value(), "x")); EXPECT_EQ(1u, GetFieldIndex(ParseDType(::nlohmann::json::array_t{ {"x", "<i4"}, {"y", "<u2"}}) .value(), "y")); EXPECT_THAT( GetFieldIndex( ParseDType(::nlohmann::json::array_t{{"x", "<i4"}, {"y", "<u2"}}) .value(), "z"), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Requested field \"z\" is not one of: \\[\"x\",\"y\"\\]")); } TEST(EncodeSelectedFieldTest, NonEmpty) { auto dtype = ParseDType(::nlohmann::json::array_t{{"x", "<i4"}, {"y", "<u2"}}).value(); EXPECT_EQ("x", EncodeSelectedField(0, dtype)); EXPECT_EQ("y", EncodeSelectedField(1, dtype)); } TEST(EncodeSelectedFieldTest, Empty) { auto dtype = ParseDType("<i4").value(); // dtype does not have multiple fields. `EncodeSelectedField` returns the // empty string to indicate that. EXPECT_EQ("", EncodeSelectedField(0, dtype)); } template <typename... Option> tensorstore::Result<::nlohmann::json> GetNewMetadataFromOptions( ::nlohmann::json partial_metadata_json, std::string selected_field, Option&&... option) { Schema schema; if (absl::Status status; !((status = schema.Set(std::forward<Option>(option))).ok() && ...)) { return status; } TENSORSTORE_ASSIGN_OR_RETURN( auto partial_metadata, ZarrPartialMetadata::FromJson(partial_metadata_json)); TENSORSTORE_ASSIGN_OR_RETURN( auto new_metadata, GetNewMetadata(partial_metadata, selected_field, schema)); return new_metadata->ToJson(); } TEST(GetNewMetadataTest, FullMetadata) { EXPECT_THAT(GetNewMetadataFromOptions({{"chunks", {8, 10}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"shape", {5, 6}}}, /*selected_field=*/{}), ::testing::Optional(MatchesJson({ {"chunks", {8, 10}}, {"compressor", nullptr}, {"dtype", "<i4"}, {"fill_value", nullptr}, {"filters", nullptr}, {"order", "C"}, {"shape", {5, 6}}, {"zarr_format", 2}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, NoShape) { EXPECT_THAT( GetNewMetadataFromOptions( {{"chunks", {2, 3}}, {"dtype", "<i4"}, {"compressor", nullptr}}, /*selected_field=*/{}), MatchesStatus(absl::StatusCode::kInvalidArgument, "domain must be specified")); } TEST(GetNewMetadataTest, AutomaticChunks) { EXPECT_THAT( GetNewMetadataFromOptions( {{"shape", {2, 3}}, {"dtype", "<i4"}, {"compressor", nullptr}}, /*selected_field=*/{}), ::testing::Optional(MatchesJson({ {"chunks", {2, 3}}, {"compressor", nullptr}, {"dtype", "<i4"}, {"fill_value", nullptr}, {"filters", nullptr}, {"order", "C"}, {"shape", {2, 3}}, {"zarr_format", 2}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, NoDtype) { EXPECT_THAT( GetNewMetadataFromOptions( {{"shape", {2, 3}}, {"chunks", {2, 3}}, {"compressor", nullptr}}, /*selected_field=*/{}), MatchesStatus(absl::StatusCode::kInvalidArgument, "\"dtype\" must be specified")); } TEST(GetNewMetadataTest, NoCompressor) { EXPECT_THAT(GetNewMetadataFromOptions( {{"shape", {2, 3}}, {"chunks", {2, 3}}, {"dtype", "<i4"}}, /*selected_field=*/{}), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {2, 3}}, {"chunks", {2, 3}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, IntegerOverflow) { EXPECT_THAT( GetNewMetadataFromOptions( {{"shape", {4611686018427387903, 4611686018427387903}}, {"chunks", {4611686018427387903, 4611686018427387903}}, {"dtype", "<i4"}, {"compressor", nullptr}}, /*selected_field=*/{}), MatchesStatus( absl::StatusCode::kInvalidArgument, "Product of chunk dimensions " "\\{4611686018427387903, 4611686018427387903\\} is too large")); } TEST(GetNewMetadataTest, SchemaDomainDtype) { EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/{}, tensorstore::IndexDomainBuilder(3) .shape({1000, 2000, 3000}) .Finalize() .value(), dtype_v<int32_t>), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {1000, 2000, 3000}}, {"chunks", {102, 102, 102}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDomainDtypeFillValue) { EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t(), /*selected_field=*/{}, tensorstore::IndexDomainBuilder(3) .shape({1000, 2000, 3000}) .Finalize() .value(), dtype_v<int32_t>, Schema::FillValue{tensorstore::MakeScalarArray<int32_t>(5)}), ::testing::Optional(MatchesJson({ {"fill_value", 5}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {1000, 2000, 3000}}, {"chunks", {102, 102, 102}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaObjectWithDomainDtypeFillValue) { Schema schema; TENSORSTORE_ASSERT_OK(schema.Set(tensorstore::IndexDomainBuilder(3) .shape({1000, 2000, 3000}) .Finalize() .value())); TENSORSTORE_ASSERT_OK(schema.Set(dtype_v<int32_t>)); TENSORSTORE_ASSERT_OK( schema.Set(Schema::FillValue{tensorstore::MakeScalarArray<int32_t>(5)})); EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/{}, schema), ::testing::Optional(MatchesJson({ {"fill_value", 5}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {1000, 2000, 3000}}, {"chunks", {102, 102, 102}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeShapeCodec) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/{}, Schema::Shape({100, 200}), dtype_v<int32_t>, codec), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderC) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t(), /*selected_field=*/{}, Schema::Shape({100, 200}), ChunkLayout::InnerOrder({0, 1}), dtype_v<int32_t>, codec), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderFortran) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t(), /*selected_field=*/{}, Schema::Shape({100, 200}), ChunkLayout::InnerOrder({1, 0}), dtype_v<int32_t>, codec), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "F"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderFortranFieldShape) { EXPECT_THAT(GetNewMetadataFromOptions( { {"compressor", nullptr}, {"dtype", {{"x", "<u4", {2, 3}}}}, }, /*selected_field=*/"x", Schema::Shape({100, 200, 2, 3}), ChunkLayout::InnerOrder({1, 0, 2, 3})), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "F"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", {{"x", "<u4", {2, 3}}}}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderInvalid) { EXPECT_THAT( GetNewMetadataFromOptions( ::nlohmann::json::object_t(), /*selected_field=*/{}, Schema::Shape({100, 200, 300}), ChunkLayout::InnerOrder({2, 0, 1}), dtype_v<int32_t>), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid \"inner_order\" constraint: \\{2, 0, 1\\}")); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderInvalidSoft) { EXPECT_THAT(GetNewMetadataFromOptions( {{"compressor", nullptr}}, /*selected_field=*/{}, Schema::Shape({100, 200, 300}), ChunkLayout::InnerOrder({2, 0, 1}, /*hard_constraint=*/false), dtype_v<int32_t>), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200, 300}}, {"chunks", {100, 102, 102}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaStructuredDtypeInvalidFillValue) { EXPECT_THAT( GetNewMetadataFromOptions( {{"dtype", ::nlohmann::json::array_t{{"x", "<u4"}, {"y", "<i4"}}}}, /*selected_field=*/"x", Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(42))), MatchesStatus( absl::StatusCode::kInvalidArgument, "Invalid fill_value: Cannot specify fill_value through schema for " "structured zarr data type \\[.*")); } TEST(GetNewMetadataTest, SchemaFillValueMismatch) { EXPECT_THAT( GetNewMetadataFromOptions( {{"dtype", "<u4"}, {"fill_value", 42}}, /*selected_field=*/{}, Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(43))), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid fill_value: .*")); } TEST(GetNewMetadataTest, SchemaFillValueMismatchNull) { EXPECT_THAT( GetNewMetadataFromOptions( {{"dtype", "<u4"}, {"fill_value", nullptr}}, /*selected_field=*/{}, Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(42))), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid fill_value: .*")); } TEST(GetNewMetadataTest, SchemaFillValueRedundant) { EXPECT_THAT( GetNewMetadataFromOptions( { {"dtype", "<u4"}, {"fill_value", 42}, {"compressor", nullptr}, }, /*selected_field=*/{}, Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(42))), ::testing::Optional(MatchesJson({ {"fill_value", 42}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<u4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaCodecChunkShape) { EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t{}, /*selected_field=*/{}, Schema::Shape({100, 200}), dtype_v<uint32_t>, ChunkLayout::CodecChunkShape({5, 6})), MatchesStatus(absl::StatusCode::kInvalidArgument, "codec_chunk_shape not supported")); } TEST(GetNewMetadataTest, CodecMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT( GetNewMetadataFromOptions({{"compressor", {{"id", "blosc"}}}}, /*selected_field=*/{}, Schema::Shape({100, 200}), dtype_v<int32_t>, codec), MatchesStatus( absl::StatusCode::kInvalidArgument, "Cannot merge codec spec .* with .*: \"compressor\" does not match")); } TEST(GetNewMetadataTest, SelectedFieldDtypeNotSpecified) { EXPECT_THAT( GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/"x", Schema::Shape({100, 200}), dtype_v<int32_t>), MatchesStatus(absl::StatusCode::kInvalidArgument, "\"dtype\" must be specified in \"metadata\" if " "\"field\" is specified")); } TEST(GetNewMetadataTest, SelectedFieldInvalid) { EXPECT_THAT( GetNewMetadataFromOptions({{"dtype", {{"x", "<u4", {2}}, {"y", "<i4"}}}}, /*selected_field=*/"z", Schema::Shape({100, 200})), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Requested field \"z\" is not one of: \\[\"x\",\"y\"\\]")); } TEST(GetNewMetadataTest, InvalidDtype) { EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/{}, dtype_v<tensorstore::json_t>, Schema::Shape({100, 200})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Data type not supported: json")); } TEST(GetNewMetadataTest, InvalidDomain) { EXPECT_THAT( GetNewMetadataFromOptions(::nlohmann::json::object_t(), /*selected_field=*/{}, dtype_v<tensorstore::int32_t>, tensorstore::IndexDomainBuilder(2) .origin({1, 2}) .shape({100, 200}) .Finalize() .value()), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid domain: .*")); } TEST(GetNewMetadataTest, DomainIncompatibleWithFieldShape) { EXPECT_THAT( GetNewMetadataFromOptions({{"dtype", {{"x", "<u4", {2, 3}}}}}, /*selected_field=*/"x", Schema::Shape({100, 200, 2, 4})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid domain: .*")); } TEST(GetNewMetadataTest, DomainIncompatibleWithMetadataRank) { EXPECT_THAT( GetNewMetadataFromOptions({{"chunks", {100, 100}}}, /*selected_field=*/{}, dtype_v<tensorstore::int32_t>, Schema::Shape({100, 200, 300})), MatchesStatus( absl::StatusCode::kInvalidArgument, "Rank specified by schema \\(3\\) is not compatible with metadata")); } TEST(ValidateMetadataTest, Success) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto partial_metadata, ZarrPartialMetadata::FromJson(GetMetadataSpec())); TENSORSTORE_EXPECT_OK(ValidateMetadata(metadata, partial_metadata)); } TEST(ValidateMetadataTest, Unconstrained) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto partial_metadata, ZarrPartialMetadata::FromJson(::nlohmann::json::object_t{})); TENSORSTORE_EXPECT_OK(ValidateMetadata(metadata, partial_metadata)); } TEST(ValidateMetadataTest, ShapeMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["shape"] = {7, 8}; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT( ValidateMetadata(metadata, partial_metadata), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Expected \"shape\" of \\[7,8\\] but received: \\[100,100\\]")); } TEST(ValidateMetadataTest, ChunksMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["chunks"] = {1, 1}; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Expected \"chunks\" of \\[1,1\\] but received: \\[3,2\\]")); } TEST(ValidateMetadataTest, OrderMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["order"] = "F"; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"order\" of \"F\" but received: \"C\"")); } TEST(ValidateMetadataTest, CompressorMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["compressor"] = nullptr; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"compressor\" of null but received: " "\\{\"blocksize\":0,\"clevel\":5,\"cname\":\"lz4\"," "\"id\":\"blosc\",\"shuffle\":-1\\}")); } TEST(ValidateMetadataTest, DTypeMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["dtype"] = ">i4"; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT( ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"dtype\" of \">i4\" but received: \"<i2\"")); } TEST(ValidateMetadataTest, FillValueMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["fill_value"] = 1; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"fill_value\" of 1 but received: null")); } TEST(ZarrCodecSpecTest, Merge) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec1, CodecSpec::Ptr::FromJson({{"driver", "zarr"}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec2, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"filters", nullptr}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec3, CodecSpec::Ptr::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec4, CodecSpec::Ptr::FromJson( {{"driver", "zarr"}, {"compressor", {{"id", "blosc"}}}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec5, CodecSpec::Ptr::FromJson( {{"driver", "zarr"}, {"compressor", nullptr}, {"filters", nullptr}})); EXPECT_THAT(CodecSpec::Merge(codec1, codec1), ::testing::Optional(codec1)); EXPECT_THAT(CodecSpec::Merge(codec3, codec3), ::testing::Optional(codec3)); EXPECT_THAT(CodecSpec::Merge(codec1, CodecSpec::Ptr()), ::testing::Optional(codec1)); EXPECT_THAT(CodecSpec::Merge(CodecSpec::Ptr(), codec1), ::testing::Optional(codec1)); EXPECT_THAT(CodecSpec::Merge(CodecSpec::Ptr(), CodecSpec::Ptr()), ::testing::Optional(CodecSpec::Ptr())); EXPECT_THAT(CodecSpec::Merge(codec1, codec2), ::testing::Optional(codec2)); EXPECT_THAT(CodecSpec::Merge(codec1, codec3), ::testing::Optional(codec3)); EXPECT_THAT(CodecSpec::Merge(codec2, codec3), ::testing::Optional(codec5)); EXPECT_THAT( CodecSpec::Merge(codec3, codec4), MatchesStatus( absl::StatusCode::kInvalidArgument, "Cannot merge codec spec .* with .*: \"compressor\" does not match")); } TEST(ZarrCodecSpecTest, RoundTrip) { tensorstore::TestJsonBinderRoundTripJsonOnly<tensorstore::CodecSpec::Ptr>({ ::nlohmann::json::value_t::discarded, { {"driver", "zarr"}, {"compressor", nullptr}, {"filters", nullptr}, }, { {"driver", "zarr"}, {"compressor", {{"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}}}, {"filters", nullptr}, }, }); } } // namespace
39.180387
80
0.541513
google
45fc2c960ca416349005f51c9a48b3b7ebc6b602
864
cpp
C++
zoo_test.cpp
keychera/VirtualZOOP
893bbca25da0770504dc67c98adb526aee980237
[ "MIT" ]
null
null
null
zoo_test.cpp
keychera/VirtualZOOP
893bbca25da0770504dc67c98adb526aee980237
[ "MIT" ]
null
null
null
zoo_test.cpp
keychera/VirtualZOOP
893bbca25da0770504dc67c98adb526aee980237
[ "MIT" ]
null
null
null
#include "zoo.h" #include <gtest/gtest.h> #include <iostream> using namespace std; class ZooTest : public ::testing::Test { protected: ZooTest(){} }; TEST(ZooTest, Test1) { string filename="map.txt"; Zoo Z; Z.ReadZoo(filename.c_str()); ASSERT_EQ(21,Z.GetWidth()); ASSERT_EQ(21,Z.GetLength()); cout<<"width: "<<Z.GetWidth()<<endl; cout<<"length: "<<Z.GetLength()<<endl; for(int i=0;i<Z.GetWidth();i++) { for(int j=0;j<Z.GetLength();j++) { //cout<<i<<j<<(i*Z.GetLength()+j); //cout<<Z.GetCells()[i*Z.GetLength()+j]->GetX()<<Z.GetCells()[i*Z.GetLength()+j]->GetY()<<endl; ASSERT_EQ((i),Z.GetCells()[i*Z.GetLength()+j]->GetX()); ASSERT_EQ((j),Z.GetCells()[i*Z.GetLength()+j]->GetY()); } //cout<<endl; } Z.MakeCage(); ASSERT_EQ(17,Z.GetNCages()); }
26.181818
97
0.552083
keychera
3400b7fe0e4d35c15ef8c18b5b35a8a4fb0a140f
1,819
cc
C++
onnxruntime/core/providers/cuda/generator/constant_of_shape.cc
csteegz/onnxruntime
a36810471b346ec862ac6e4de7f877653f49525e
[ "MIT" ]
1
2020-07-12T15:23:49.000Z
2020-07-12T15:23:49.000Z
onnxruntime/core/providers/cuda/generator/constant_of_shape.cc
ajinkya933/onnxruntime
0e799a03f2a99da6a1b87a2cd37facb420c482aa
[ "MIT" ]
null
null
null
onnxruntime/core/providers/cuda/generator/constant_of_shape.cc
ajinkya933/onnxruntime
0e799a03f2a99da6a1b87a2cd37facb420c482aa
[ "MIT" ]
1
2020-09-09T06:55:51.000Z
2020-09-09T06:55:51.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "constant_of_shape.h" #include "core/providers/common.h" #include "gsl/gsl" using namespace ::onnxruntime::common; using namespace ONNX_NAMESPACE; namespace onnxruntime { namespace cuda { ONNX_OPERATOR_KERNEL_EX( ConstantOfShape, kOnnxDomain, 9, kCudaExecutionProvider, KernelDefBuilder() .InputMemoryType<OrtMemTypeCPUInput>(0) .TypeConstraint("T1", DataTypeImpl::GetTensorType<int64_t>()) .TypeConstraint("T2", DataTypeImpl::AllFixedSizeTensorTypes()), ConstantOfShape); Status ConstantOfShape::Compute(OpKernelContext* ctx) const { Tensor* output_tensor = nullptr; ORT_RETURN_IF_ERROR(PrepareCompute(ctx, &output_tensor)); auto output_data = output_tensor->MutableDataRaw(); const auto size = output_tensor->Shape().Size(); const void* value_ptr = GetValuePtr(); const auto element_size = output_tensor->DataType()->Size(); switch (element_size) { case sizeof(int8_t): cuda::Fill(reinterpret_cast<int8_t*>(output_data), *(reinterpret_cast<const int8_t*>(value_ptr)), size); break; case sizeof(int16_t): cuda::Fill(reinterpret_cast<int16_t*>(output_data), *(reinterpret_cast<const int16_t*>(value_ptr)), size); break; case sizeof(int32_t): cuda::Fill(reinterpret_cast<int32_t*>(output_data), *(reinterpret_cast<const int32_t*>(value_ptr)), size); break; case sizeof(int64_t): cuda::Fill(reinterpret_cast<int64_t*>(output_data), *(reinterpret_cast<const int64_t*>(value_ptr)), size); break; default: ORT_THROW("Unsupported value attribute datatype with sizeof=: ", element_size); break; } return Status::OK(); } } // namespace cuda } // namespace onnxruntime
33.685185
112
0.715778
csteegz
340bb6123443172507c1477d203f1661a213c5d8
20,770
cpp
C++
admin/wmi/wbem/common/containers/cache.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/common/containers/cache.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/common/containers/cache.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#ifndef __CACHE_CPP #define __CACHE_CPP /*++ Copyright (C) 1996-2001 Microsoft Corporation Module Name: Thread.cpp Abstract: Enhancements to current functionality: Timeout mechanism should track across waits. AddRef/Release on task when scheduling. Enhancement Ticker logic. History: --*/ #include <HelperFuncs.h> /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ #if 0 // // The template argument for the below two operator functions // can never be deduced so I'm moving them to class WmiUniqueTimeout // // [TGani] // template <class WmiKey> bool operator == ( const typename WmiCacheController <WmiKey> :: WmiUniqueTimeout &a_Arg1 , const typename WmiCacheController <WmiKey> :: WmiUniqueTimeout &a_Arg2 ) { LONG t_Compare ; if ( ( t_Compare = a_Arg1.GetTicks () - a_Arg2.GetTicks () ) == 0 ) { t_Compare = a_Arg1.GetCounter () - a_Arg2.GetCounter () ; } return t_Compare == 0 ? true : false ; } template <class WmiKey> bool operator < ( const typename WmiCacheController <WmiKey> :: WmiUniqueTimeout &a_Arg1 , const typename WmiCacheController <WmiKey> :: WmiUniqueTimeout &a_Arg2 ) { LONG t_Compare ; if ( ( t_Compare = a_Arg1.GetTicks () - a_Arg2.GetTicks () ) == 0 ) { t_Compare = a_Arg1.GetCounter () - a_Arg2.GetCounter () ; } return t_Compare < 0 ? true : false ; } #endif //0 /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiCacheController <WmiKey> :: WmiCacheController ( WmiAllocator &a_Allocator ) : m_Allocator ( a_Allocator ) , m_Cache ( a_Allocator ) , m_CacheDecay ( a_Allocator ) , m_ReferenceCount ( 0 ) , m_Counter ( 0 ), m_CriticalSection(NOTHROW_LOCK) { } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiCacheController <WmiKey> :: ~WmiCacheController () { } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP_( ULONG ) WmiCacheController <WmiKey> :: AddRef () { return InterlockedIncrement ( & m_ReferenceCount ) ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP_( ULONG ) WmiCacheController <WmiKey> :: Release () { ULONG t_ReferenceCount = InterlockedDecrement ( & m_ReferenceCount ) ; if ( t_ReferenceCount == 0 ) { delete this ; } return t_ReferenceCount ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP WmiCacheController <WmiKey> :: QueryInterface ( REFIID , LPVOID FAR * ) { return E_NOINTERFACE ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Initialize () { WmiStatusCode t_StatusCode = m_Cache.Initialize () ; if ( t_StatusCode == e_StatusCode_Success ) { t_StatusCode = m_CacheDecay.Initialize () ; if ( t_StatusCode == e_StatusCode_Success ) { t_StatusCode = WmiHelper :: InitializeCriticalSection ( & m_CriticalSection ) ; } } return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: UnInitialize () { WmiStatusCode t_StatusCode = m_Cache.UnInitialize () ; if ( t_StatusCode == e_StatusCode_Success ) { t_StatusCode = m_CacheDecay.UnInitialize () ; } WmiHelper :: DeleteCriticalSection ( & m_CriticalSection ) ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Insert ( WmiCacheElement &a_Element , Cache_Iterator &a_Iterator ) { WmiStatusCode t_StatusCode = e_StatusCode_Success ; Lock () ; Cache_Iterator t_Iterator ; t_StatusCode = m_Cache.Insert ( a_Element.GetKey () , & a_Element , t_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { a_Element.InternalAddRef () ; a_Element.SetCached ( TRUE ) ; } UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Delete ( const WmiKey &a_Key ) { Lock () ; WmiStatusCode t_StatusCode = m_Cache.Delete ( a_Key ) ; UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Find ( const WmiKey &a_Key , Cache_Iterator &a_Iterator ) { Lock () ; WmiStatusCode t_StatusCode = m_Cache.Find ( a_Key , a_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { a_Iterator.GetElement ()->AddRef ( ) ; } UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Lock () { WmiStatusCode t_StatusCode = WmiHelper :: EnterCriticalSection ( & m_CriticalSection ) ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: UnLock () { WmiStatusCode t_StatusCode = WmiHelper :: LeaveCriticalSection ( & m_CriticalSection ) ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Shutdown () { Lock () ; ULONG t_Index = 0 ; while ( true ) { WmiUniqueTimeout t_Key ; WmiCacheElement *t_Element = NULL ; WmiStatusCode t_StatusCode = m_CacheDecay.Top ( t_Key , t_Element ) ; if ( t_StatusCode == e_StatusCode_Success ) { t_Index ++ ; t_StatusCode = m_CacheDecay.DeQueue () ; } else { break ; } } ULONG t_ElementCount = m_Cache.Size () ; WmiCacheElement **t_Elements = NULL ; WmiStatusCode t_StatusCode = m_Allocator.New ( ( void ** ) & t_Elements , sizeof ( WmiCacheElement ) * t_ElementCount ) ; if ( t_StatusCode == e_StatusCode_Success ) { for ( ULONG t_Index = 0 ; t_Index < t_ElementCount ; t_Index ++ ) { t_Elements [ t_Index ] = NULL ; } ULONG t_ElementIndex = 0 ; Cache_Iterator t_Iterator = m_Cache.Root (); while ( ! t_Iterator.Null () ) { if ( t_Iterator.GetElement ()->GetDecayed () == FALSE ) { WmiCacheElement *t_Element = t_Iterator.GetElement () ; t_Elements [ t_ElementIndex ] = t_Element ; t_Element->SetDecayed ( TRUE ) ; t_Element->SetDecaying ( FALSE ) ; t_Element->SetCached ( FALSE ) ; m_Cache.Delete ( t_Iterator.GetKey () ) ; } else { m_Cache.Delete ( t_Iterator.GetKey () ) ; } t_ElementIndex ++ ; t_Iterator = m_Cache.Root () ; } } UnLock () ; if ( t_Elements ) { for ( ULONG t_Index = 0 ; t_Index < t_ElementCount ; t_Index ++ ) { if ( t_Elements [ t_Index ] ) { t_Elements [ t_Index ]->InternalRelease () ; } } m_Allocator.Delete ( t_Elements ) ; } return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Shutdown ( const WmiKey &a_Key ) { Lock () ; Cache_Iterator t_Iterator ; WmiStatusCode t_StatusCode = m_Cache.Find ( a_Key , t_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { if ( t_Iterator.GetElement ()->GetDecayed () == FALSE ) { CacheDecay_Iterator t_QueueIterator = m_CacheDecay.Begin () ; while ( ! t_QueueIterator.Null () ) { WmiCacheElement *t_Element = t_QueueIterator.GetElement () ; if ( t_Element == t_Iterator.GetElement () ) { m_CacheDecay.Delete ( t_QueueIterator.GetKey () ) ; break ; } t_QueueIterator.Increment () ; } WmiCacheElement *t_Element = t_Iterator.GetElement () ; t_Element->SetDecayed ( TRUE ) ; t_Element->SetDecaying ( FALSE ) ; t_Element->SetCached ( FALSE ) ; m_Cache.Delete ( a_Key ) ; UnLock () ; t_Element->InternalRelease () ; } else { m_Cache.Delete ( a_Key ) ; UnLock () ; } } else { UnLock () ; } return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: StrobeBegin ( const ULONG &a_Timeout ) { return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Strobe ( ULONG &a_NextStrobeDelta ) { while ( true ) { Lock () ; WmiUniqueTimeout t_Key ; WmiCacheElement *t_Element = NULL ; WmiStatusCode t_StatusCode = m_CacheDecay.Top ( t_Key , t_Element ) ; if ( t_StatusCode == e_StatusCode_Success ) { a_NextStrobeDelta = ( a_NextStrobeDelta < t_Element->GetPeriod () ) ? a_NextStrobeDelta : t_Element->GetPeriod () ; ULONG t_Ticks = GetTickCount () ; #if 0 wchar_t t_Buffer [ 128 ] ; wsprintf ( t_Buffer , L"\n%lx - Checking ( %lx , %lx ) " , t_Ticks , t_Element , t_Key.GetTicks () ) ; OutputDebugString ( t_Buffer ) ; #endif if ( t_Ticks >= t_Key.GetTicks () ) { if ( t_Element->GetDecaying () ) { #if 0 wchar_t t_Buffer [ 128 ] ; wsprintf ( t_Buffer , L"\n%lx - Strobe ( %lx , %lx ) " , t_Ticks , t_Element , t_Key.GetTicks () ) ; OutputDebugString ( t_Buffer ) ; #endif t_Element->SetDecaying ( FALSE ) ; t_Element->SetDecayed ( TRUE ) ; t_StatusCode = m_CacheDecay.DeQueue () ; UnLock () ; t_Element->InternalRelease () ; } else { t_StatusCode = m_CacheDecay.DeQueue () ; UnLock () ; } } else { UnLock () ; break ; } } else { UnLock () ; break ; } } return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiCacheController <WmiKey> :: Decay ( WmiCacheElement &a_Element ) { Lock () ; ULONG t_Size = m_CacheDecay.Size () ; Cache_Iterator t_Iterator ; WmiStatusCode t_StatusCode = m_Cache.Find ( a_Element.GetKey () , t_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { BOOL t_Found = FALSE ; CacheDecay_Iterator t_QueueIterator = m_CacheDecay.Begin () ; while ( ! t_QueueIterator.Null () ) { WmiCacheElement *t_Element = t_QueueIterator.GetElement () ; if ( t_Element == & a_Element ) { m_CacheDecay.Delete ( t_QueueIterator.GetKey () ) ; break ; } t_QueueIterator.Increment () ; } ULONG t_Ticks = GetTickCount () ; WmiUniqueTimeout t_Key ( t_Ticks + a_Element.GetPeriod () , InterlockedIncrement ( & m_Counter ) ) ; #if 0 wchar_t t_Buffer [ 128 ] ; wsprintf ( t_Buffer , L"\n%lx - Decaying ( %lx , %lx , %lx ) " , t_Ticks , & a_Element , t_Ticks + a_Element.GetPeriod () , a_Element.GetPeriod () ) ; OutputDebugString ( t_Buffer ) ; #endif t_StatusCode = m_CacheDecay.EnQueue ( t_Key , t_Iterator.GetElement () ) ; UnLock () ; if ( t_Size == 0 ) { StrobeBegin ( a_Element.GetPeriod () ) ; } if ( t_StatusCode != e_StatusCode_Success ) { a_Element.InternalRelease () ; } } else { UnLock () ; } return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiContainerController <WmiKey> :: WmiContainerController ( WmiAllocator &a_Allocator ) : m_Container ( a_Allocator ) , m_ReferenceCount ( 0 ), m_CriticalSection(NOTHROW_LOCK) { } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiContainerController <WmiKey> :: ~WmiContainerController () { } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP_( ULONG ) WmiContainerController <WmiKey> :: AddRef () { return InterlockedIncrement ( & m_ReferenceCount ) ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP_( ULONG ) WmiContainerController <WmiKey> :: Release () { ULONG t_ReferenceCount = InterlockedDecrement ( & m_ReferenceCount ) ; if ( t_ReferenceCount == 0 ) { delete this ; } return t_ReferenceCount ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> STDMETHODIMP WmiContainerController <WmiKey> :: QueryInterface ( REFIID , LPVOID FAR * ) { return E_NOINTERFACE ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Initialize () { WmiStatusCode t_StatusCode = m_Container.Initialize () ; if ( t_StatusCode == e_StatusCode_Success ) { t_StatusCode = WmiHelper :: InitializeCriticalSection ( & m_CriticalSection ) ; } return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: UnInitialize () { WmiStatusCode t_StatusCode = m_Container.UnInitialize () ; if ( t_StatusCode == e_StatusCode_Success ) { t_StatusCode = WmiHelper :: DeleteCriticalSection ( & m_CriticalSection ) ; } return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Insert ( WmiContainerElement &a_Element , Container_Iterator &a_Iterator ) { WmiStatusCode t_StatusCode = e_StatusCode_Success ; Lock () ; Container_Iterator t_Iterator ; t_StatusCode = m_Container.Insert ( a_Element.GetKey () , & a_Element , t_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { a_Element.InternalAddRef () ; a_Element.SetCached ( TRUE ) ; } UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Delete ( const WmiKey &a_Key ) { Lock () ; WmiStatusCode t_StatusCode = m_Container.Delete ( a_Key ) ; UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Find ( const WmiKey &a_Key , Container_Iterator &a_Iterator ) { Lock () ; WmiStatusCode t_StatusCode = m_Container.Find ( a_Key , a_Iterator ) ; if ( t_StatusCode == e_StatusCode_Success ) { a_Iterator.GetElement ()->AddRef ( ) ; } UnLock () ; return t_StatusCode ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Lock () { return WmiHelper :: EnterCriticalSection ( & m_CriticalSection ) ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: UnLock () { WmiHelper :: LeaveCriticalSection ( & m_CriticalSection ) ; return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Shutdown () { Lock () ; Container_Iterator t_Iterator = m_Container.Root (); while ( ! t_Iterator.Null () ) { m_Container.Delete ( t_Iterator.GetKey () ) ; t_Iterator = m_Container.Root () ; } UnLock () ; return e_StatusCode_Success ; } /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ template <class WmiKey> WmiStatusCode WmiContainerController <WmiKey> :: Strobe ( ULONG &a_NextStrobeDelta ) { return e_StatusCode_Success ; } #endif __CACHE_CPP
21.568017
166
0.463361
npocmaka
340d8d8c9c06398aa863a0fa2d11b0c4615c77c5
35,044
cpp
C++
test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp
openharmony-gitee-mirror/appexecfwk_standard
0edd750ed64940531881e0bb113a84155ac056d0
[ "Apache-2.0" ]
1
2021-11-23T08:13:14.000Z
2021-11-23T08:13:14.000Z
test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp
openharmony-gitee-mirror/appexecfwk_standard
0edd750ed64940531881e0bb113a84155ac056d0
[ "Apache-2.0" ]
null
null
null
test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp
openharmony-gitee-mirror/appexecfwk_standard
0edd750ed64940531881e0bb113a84155ac056d0
[ "Apache-2.0" ]
1
2021-09-13T11:17:54.000Z
2021-09-13T11:17:54.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fcntl.h> #include <fstream> #include <future> #include <gtest/gtest.h> #include "ability_handler.h" #include "ability_info.h" #include "ability_local_record.h" #include "ability_start_setting.h" #include "app_log_wrapper.h" #include "common_event.h" #include "common_event_manager.h" #include "context_deal.h" #include "form_event.h" #include "form_st_common_info.h" #include "iservice_registry.h" #include "nlohmann/json.hpp" #include "system_ability_definition.h" #include "system_test_form_util.h" using OHOS::AAFwk::Want; using namespace testing::ext; using namespace std::chrono_literals; using namespace OHOS::STtools; namespace { const int FORM_COUNT_200 = 200; const int FORM_COUNT_112 = 112; const int TEMP_FORM_COUNT_256 = 256; const int TEMP_FORM_COUNT_128 = 128; std::vector<std::string> bundleNameList = { "com.form.formsystemtestservicea", "com.form.formsystemtestserviceb", }; std::vector<std::string> hapNameList = { "formSystemTestServiceA-signed", "formSystemTestServiceB-signed", }; std::vector<std::string> normalFormsMaxA; std::vector<std::string> normalFormsMaxB; std::vector<std::string> normalFormsMaxC; std::vector<std::string> tempFormsMaxA; std::vector<std::string> tempFormsMaxB; } // namespace namespace OHOS { namespace AppExecFwk { class FmsAcquireFormTestMax : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); static bool SubscribeEvent(); void SetUp(); void TearDown(); void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); void TerminateAbility(const std::string &eventName, const std::string &abilityName); class FormEventSubscriber : public CommonEventSubscriber { public: explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; virtual void OnReceiveEvent(const CommonEventData &data) override; ~FormEventSubscriber() = default; }; static sptr<AAFwk::IAbilityManager> abilityMs; static FormEvent event; static std::vector<std::string> eventList; static std::shared_ptr<FormEventSubscriber> subscriber; void FmsAcquireForm2700(std::string strFormId); std::string FmsAcquireForm2900A(); std::string FmsAcquireForm2900B(); void FmsAcquireForm3000(); std::string FmsAcquireForm3100(const std::string &bundleName, const std::string &abilityName); void FmsAcquireForm2800(std::string strFormId); void FmsAcquireForm3200(); void FmsAcquireFormDeleteA(const std::string &strFormId); void FmsAcquireFormDeleteB(const std::string &strFormId); void FmsAcquireFormDeleteC(const std::string &strFormId); std::string FmsAcquireFormTemp(const std::string &bundleName, const std::string &abilityName); bool FmsAcquireFormTempForFailed(const std::string &bundleName, const std::string &abilityName); }; std::vector<std::string> FmsAcquireFormTestMax::eventList = { FORM_EVENT_RECV_DELETE_FORM_COMMON, FORM_EVENT_ABILITY_ONACTIVED, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, FORM_EVENT_RECV_ACQUIRE_FORM_2700, FORM_EVENT_RECV_ACQUIRE_FORM_2800, FORM_EVENT_RECV_ACQUIRE_FORM_2900, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, FORM_EVENT_RECV_ACQUIRE_FORM_3000, FORM_EVENT_RECV_ACQUIRE_FORM_3100, FORM_EVENT_RECV_ACQUIRE_FORM_3200, }; FormEvent FmsAcquireFormTestMax::event = FormEvent(); sptr<AAFwk::IAbilityManager> FmsAcquireFormTestMax::abilityMs = nullptr; std::shared_ptr<FmsAcquireFormTestMax::FormEventSubscriber> FmsAcquireFormTestMax::subscriber = nullptr; void FmsAcquireFormTestMax::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data) { GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData()); } void FmsAcquireFormTestMax::SetUpTestCase() { if (!SubscribeEvent()) { GTEST_LOG_(INFO) << "SubscribeEvent error"; } } void FmsAcquireFormTestMax::TearDownTestCase() { GTEST_LOG_(INFO) << "UnSubscribeCommonEvent calld"; CommonEventManager::UnSubscribeCommonEvent(subscriber); } void FmsAcquireFormTestMax::SetUp() { } void FmsAcquireFormTestMax::TearDown() { GTEST_LOG_(INFO) << "CleanMsg calld"; SystemTestFormUtil::CleanMsg(event); } bool FmsAcquireFormTestMax::SubscribeEvent() { GTEST_LOG_(INFO) << "SubscribeEvent calld"; MatchingSkills matchingSkills; for (const auto &e : eventList) { matchingSkills.AddEvent(e); } CommonEventSubscribeInfo subscribeInfo(matchingSkills); subscribeInfo.SetPriority(1); subscriber = std::make_shared<FormEventSubscriber>(subscribeInfo); return CommonEventManager::SubscribeCommonEvent(subscriber); } /** * @tc.number: FMS_acquireForm_2900 * @tc.name: A single host creates 256 different provider forms. * @tc.desc: The single host can successfully create 256 different provider forms. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_2900, Function | MediumTest | Level1) { std::cout << "START FMS_acquireForm_2900" << std::endl; for (int count = 0; count < Constants::MAX_RECORD_PER_APP/2; count++) { sleep(7); std::string strFormId1 = FmsAcquireForm2900A(); normalFormsMaxA.emplace_back(strFormId1); std::cout << "FMS_acquireForm_2900, form size of the host A:" << normalFormsMaxA.size() << std::endl; sleep(7); std::string strFormId2 = FmsAcquireForm2900B(); normalFormsMaxA.emplace_back(strFormId2); std::cout << "FMS_acquireForm_2900, form size of the host A:" << normalFormsMaxA.size() << std::endl; } std::cout << "END FMS_acquireForm_2900" << std::endl; } /** * @tc.number: FMS_acquireForm_3000 * @tc.name: Create limit value verification using single party form. * @tc.desc: Failed to create the 257th host form. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3000, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3000" << std::endl; std::cout << "FMS_acquireForm_3000, form size of the host A:" << normalFormsMaxA.size() << std::endl; FmsAcquireForm3000(); std::cout << "END FMS_acquireForm_3000" << std::endl; } /** * @tc.number: FMS_acquireForm_2700 * @tc.name: When the normal form reaches the maximum value (256) created by the host, * the temporary form is transferred to the normal form. * @tc.desc: Verify that when the normal form reaches the maximum value (256) created by the single host, * the conversion of the temporary form to the normal form fails. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_2700, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_2700" << std::endl; std::cout << "FMS_acquireForm_2700, form size of the host A:" << normalFormsMaxA.size() << std::endl; std::string bundleNameA = "com.ohos.form.manager.normal"; std::string abilityNameA = "FormAbilityA"; std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); sleep(7); FmsAcquireForm2700(strFormId); std::cout << "END FMS_acquireForm_2700" << std::endl; std::cout << "the host A, dlete form start" << std::endl; for (int count = 0; count < normalFormsMaxA.size(); count++) { sleep(7); FmsAcquireFormDeleteA(normalFormsMaxA[count]); std::cout << "delete form count:" << count + 1 << std::endl; } normalFormsMaxA.clear(); std::cout << "the host A, dlete form end" << std::endl; } /** * @tc.number: FMS_acquireForm_3100 * @tc.name: Multiple hosts create 512 forms respectively. * @tc.desc: Verify that multiple hosts can create 512 forms. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3100, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3100" << std::endl; std::cout << "START add form to the host A" << std::endl; std::string bundleNameA = "com.ohos.form.manager.normal"; std::string abilityNameA = "FormAbilityA"; std::cout << "bundleName: " << bundleNameA << std::endl; std::cout << "abilityName: " << abilityNameA << std::endl; for (int count = 0; count < FORM_COUNT_200; count++) { sleep(7); std::string strFormId = FmsAcquireForm3100(bundleNameA, abilityNameA); normalFormsMaxA.emplace_back(strFormId); std::cout << "add form count:" << count + 1 << std::endl; } std::cout << "END add form to the host A" << std::endl; std::cout << "START add form to the host B" << std::endl; std::string bundleNameB = "com.ohos.form.manager.normalb"; std::string abilityNameB = "FormAbilityB"; std::cout << "bundleName: " << bundleNameB << std::endl; std::cout << "abilityName: " << abilityNameB << std::endl; for (int count = 0; count < FORM_COUNT_200; count++) { sleep(7); std::string strFormId = FmsAcquireForm3100(bundleNameB, abilityNameB); normalFormsMaxB.emplace_back(strFormId); std::cout << "add form count:" << count + 1 << std::endl; } std::cout << "END add form to the host B" << std::endl; std::cout << "START add form to the host C" << std::endl; std::string bundleNameC = "com.ohos.form.manager.normalc"; std::string abilityNameC = "FormAbilityC"; std::cout << "bundleName: " << bundleNameC << std::endl; std::cout << "abilityName: " << abilityNameC << std::endl; for (int count = 0; count < FORM_COUNT_112; count++) { sleep(7); std::string strFormId = FmsAcquireForm3100(bundleNameC, abilityNameC); normalFormsMaxC.emplace_back(strFormId); std::cout << "add form count:" << count + 1 << std::endl; } std::cout << "END add form to the host C" << std::endl; std::cout << "END FMS_acquireForm_3100" << std::endl; } /** * @tc.number: FMS_acquireForm_2800 * @tc.name: When the normal form reaches the maximum value (512) of the form created by FMS, * the temporary form will be transferred to the normal form. * @tc.desc: When the normal form reaches the maximum value (512) created by FMS, * the conversion of temporary form to normal form fails. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_2800, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_2800" << std::endl; std::cout << "FMS_acquireForm_2800, form size of the host A:" << normalFormsMaxA.size() << std::endl; std::cout << "FMS_acquireForm_2800, form size of the host B:" << normalFormsMaxB.size() << std::endl; std::cout << "FMS_acquireForm_2800, form size of the host C:" << normalFormsMaxC.size() << std::endl; std::string bundleNameA = "com.ohos.form.manager.normal"; std::string abilityNameA = "FormAbilityA"; std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); sleep(7); FmsAcquireForm2800(strFormId); std::cout << "END FMS_acquireForm_2800" << std::endl; } /** * @tc.number: FMS_acquireForm_2800 * @tc.name: When the normal form reaches the maximum value (512) of the form created by FMS, * the temporary form will be transferred to the normal form. * @tc.desc: When the normal form reaches the maximum value (512) created by FMS, * the conversion of temporary form to normal form fails. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3200, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3200" << std::endl; std::cout << "FMS_acquireForm_3200, form size of the host A:" << normalFormsMaxA.size() << std::endl; std::cout << "FMS_acquireForm_3200, form size of the host B:" << normalFormsMaxB.size() << std::endl; std::cout << "FMS_acquireForm_3200, form size of the host C:" << normalFormsMaxC.size() << std::endl; FmsAcquireForm3200(); std::cout << "END FMS_acquireForm_3200" << std::endl; std::cout << "the host A, dlete form start" << std::endl; for (int count = 0; count < normalFormsMaxA.size(); count++) { sleep(7); FmsAcquireFormDeleteA(normalFormsMaxA[count]); std::cout << "delete form count:" << count + 1 << std::endl; } normalFormsMaxA.clear(); std::cout << "the host A, dlete form end" << std::endl; std::cout << "the host B, dlete form start" << std::endl; for (int count = 0; count < normalFormsMaxB.size(); count++) { sleep(7); FmsAcquireFormDeleteB(normalFormsMaxB[count]); std::cout << "delete form count:" << count + 1 << std::endl; } normalFormsMaxB.clear(); std::cout << "the host B, dlete form end" << std::endl; std::cout << "the host C, dlete form start" << std::endl; for (int count = 0; count < normalFormsMaxC.size(); count++) { sleep(7); FmsAcquireFormDeleteC(normalFormsMaxC[count]); std::cout << "delete form count:" << count + 1 << std::endl; } normalFormsMaxC.clear(); std::cout << "the host C, dlete form end" << std::endl; } /** * @tc.number: FMS_acquireForm_3300 * @tc.name: A single host can create 256 temporary forms. * @tc.desc: The host of the verification form can successfully create 256 temporary forms. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3300, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3300" << std::endl; std::cout << "START add temp form to the host A" << std::endl; std::string bundleNameA = "com.ohos.form.manager.normal"; std::string abilityNameA = "FormAbilityA"; std::cout << "bundleName: " << bundleNameA << std::endl; std::cout << "abilityName: " << abilityNameA << std::endl; for (int count = 0; count < TEMP_FORM_COUNT_256; count++) { sleep(7); std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); tempFormsMaxA.emplace_back(strFormId); std::cout << "FMS_acquireForm_3300, form size of the host A:" << tempFormsMaxA.size() << std::endl; } std::cout << "END add temp form to the host A" << std::endl; std::cout << "END FMS_acquireForm_3300" << std::endl; std::cout << "the host A, dlete temp form start" << std::endl; for (int count = 0; count < tempFormsMaxA.size(); count++) { sleep(7); FmsAcquireFormDeleteA(tempFormsMaxA[count]); std::cout << "delete temp form count:" << count + 1 << std::endl; } tempFormsMaxA.clear(); std::cout << "the host A, dlete temp form end" << std::endl; } /** * @tc.number: FMS_acquireForm_3400 * @tc.name: 256 temporary forms can be created by multiple hosts. * @tc.desc: Verify that multiple hosts can successfully create 256 temporary forms. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3400, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3400" << std::endl; std::cout << "START add temp form to the host A" << std::endl; std::string bundleNameA = "com.ohos.form.manager.normal"; std::string abilityNameA = "FormAbilityA"; std::cout << "bundleName: " << bundleNameA << std::endl; std::cout << "abilityName: " << abilityNameA << std::endl; for (int count = 0; count < TEMP_FORM_COUNT_128; count++) { sleep(7); std::string strFormId = FmsAcquireFormTemp(bundleNameA, abilityNameA); tempFormsMaxA.emplace_back(strFormId); std::cout << "FMS_acquireForm_3400, temp form size of the host A:" << tempFormsMaxA.size() << std::endl; } std::cout << "END add temp form to the host A" << std::endl; std::cout << "START add temp form to the host B" << std::endl; std::string bundleNameB = "com.ohos.form.manager.normalb"; std::string abilityNameB = "FormAbilityB"; std::cout << "bundleName: " << bundleNameB << std::endl; std::cout << "abilityName: " << abilityNameB << std::endl; for (int count = 0; count < TEMP_FORM_COUNT_128; count++) { sleep(7); std::string strFormId = FmsAcquireFormTemp(bundleNameB, abilityNameB); tempFormsMaxB.emplace_back(strFormId); std::cout << "FMS_acquireForm_3400, temp form size of the host B:" << tempFormsMaxB.size() << std::endl; } std::cout << "END add temp form to the host B" << std::endl; std::cout << "END FMS_acquireForm_3400" << std::endl; } /** * @tc.number: FMS_acquireForm_3500 * @tc.name: Create temporary form limit value (256) verification. * @tc.desc: Failed to create the 257th temporary form for multiple users. */ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3500, Function | MediumTest | Level1) { sleep(7); std::cout << "START FMS_acquireForm_3500" << std::endl; std::cout << "START add temp form to the host B" << std::endl; std::string bundleNameB = "com.ohos.form.manager.normalb"; std::string abilityNameB = "FormAbilityB"; std::cout << "bundleName: " << bundleNameB << std::endl; std::cout << "abilityName: " << abilityNameB << std::endl; bool result = FmsAcquireFormTempForFailed(bundleNameB, abilityNameB); EXPECT_TRUE(result); if (result) { std::cout << "END add temp form to the host B, Failed to create the 257th temporary form." << std::endl; } std::cout << "END FMS_acquireForm_3500" << std::endl; std::cout << "the host A, dlete temp form start" << std::endl; for (int count = 0; count < tempFormsMaxA.size(); count++) { sleep(7); FmsAcquireFormDeleteA(tempFormsMaxA[count]); std::cout << "delete temp form count:" << count + 1 << std::endl; } tempFormsMaxA.clear(); std::cout << "the host A, dlete temp form end" << std::endl; std::cout << "the host B, dlete temp form start" << std::endl; for (int count = 0; count < tempFormsMaxB.size(); count++) { sleep(7); FmsAcquireFormDeleteB(tempFormsMaxB[count]); std::cout << "delete temp form count:" << count + 1 << std::endl; } tempFormsMaxB.clear(); std::cout << "the host B, dlete temp form end" << std::endl; } std::string FmsAcquireFormTestMax::FmsAcquireForm3100(const std::string &bundleName, const std::string &abilityName) { MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3100; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3100, EVENT_CODE_3100, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100)); std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3100); bool result = !strFormId.empty(); EXPECT_TRUE(result); if (!result) { GTEST_LOG_(INFO) << "FmsAcquireForm3100, result:" << result; } else { GTEST_LOG_(INFO) << "FmsAcquireForm3100, formId:" << strFormId; } EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3101)); std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3100, EVENT_CODE_3101); bool result2 = !data2.empty(); EXPECT_TRUE(result2); GTEST_LOG_(INFO) << "FmsAcquireForm3100, result:" << result2; return strFormId; } void FmsAcquireFormTestMax::FmsAcquireForm2700(std::string strFormId) { std::cout << "START FmsAcquireForm2700, cast temp form" << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData1 = strFormId; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2700, EVENT_CODE_2700, eventData1); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2700, EVENT_CODE_2700)); std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2700, EVENT_CODE_2700); bool result3 = data3 == "false"; EXPECT_TRUE(result3); GTEST_LOG_(INFO) << "FmsAcquireForm2700, result:" << result3; // wait delete form EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); bool result4 = data4 == "true"; EXPECT_TRUE(result4); GTEST_LOG_(INFO) << "FmsAcquireForm2700, delete form, result:" << result4; std::cout << "END FmsAcquireForm2700, cast temp form" << std::endl; } void FmsAcquireFormTestMax::FmsAcquireForm3200() { std::cout << "START FmsAcquireForm3200" << std::endl; std::string bundleName = "com.ohos.form.manager.normalc"; std::string abilityName = "FormAbilityC"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3200; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3200, EVENT_CODE_3200, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3200, EVENT_CODE_3200)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3200, EVENT_CODE_3200); bool result = data == "false"; EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireForm3200, result:" << result; std::cout << "END FmsAcquireForm3200" << std::endl; } void FmsAcquireFormTestMax::FmsAcquireForm2800(std::string strFormId) { std::cout << "START FmsAcquireForm2800, cast temp form" << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData1 = strFormId; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2800, EVENT_CODE_2800, eventData1); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2800, EVENT_CODE_2800)); std::string data3 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2800, EVENT_CODE_2800); bool result3 = data3 == "false"; EXPECT_TRUE(result3); GTEST_LOG_(INFO) << "FmsAcquireForm2800, result:" << result3; // wait delete form EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); std::string data4 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); bool result4 = data4 == "true"; EXPECT_TRUE(result4); GTEST_LOG_(INFO) << "FmsAcquireForm2800, delete form, result:" << result4; std::cout << "END FmsAcquireForm2800, cast temp form" << std::endl; } std::string FmsAcquireFormTestMax::FmsAcquireForm2900A() { std::cout << "START FmsAcquireForm2900A, Provider A" << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2900; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2900, EVENT_CODE_2900, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2900)); std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2900); bool result = !strFormId.empty(); EXPECT_TRUE(result); if (!result) { GTEST_LOG_(INFO) << "FmsAcquireForm2900A, result:" << result; } else { GTEST_LOG_(INFO) << "FmsAcquireForm2900A, formId:" << strFormId; } EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2901)); std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900, EVENT_CODE_2901); bool result2 = !data2.empty(); EXPECT_TRUE(result2); GTEST_LOG_(INFO) << "FmsAcquireForm2900A, result:" << result2; std::cout << "END FmsAcquireForm2900A, Provider A" << std::endl; return strFormId; } std::string FmsAcquireFormTestMax::FmsAcquireForm2900B() { std::cout << "START FmsAcquireForm2900B, Provider B" << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_2900_1; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_2900_1, EVENT_CODE_2910, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2910)); std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2910); bool result = !strFormId.empty(); EXPECT_TRUE(result); if (!result) { GTEST_LOG_(INFO) << "FmsAcquireForm2900B, result:" << result; } else { GTEST_LOG_(INFO) << "FmsAcquireForm2900B, formId:" << strFormId; } EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2911)); std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_2900_1, EVENT_CODE_2911); bool result2 = !data2.empty(); EXPECT_TRUE(result2); GTEST_LOG_(INFO) << "FmsAcquireForm2900B, result:" << result2; std::cout << "END FmsAcquireForm2900B, Provider B" << std::endl; return strFormId; } void FmsAcquireFormTestMax::FmsAcquireForm3000() { std::cout << "START FmsAcquireForm3000" << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_3000; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_3000, EVENT_CODE_3000, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_3000, EVENT_CODE_3000)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_3000, EVENT_CODE_3000); bool result = data == "false"; EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireForm3000, result:" << result; std::cout << "END FmsAcquireForm3000" << std::endl; } std::string FmsAcquireFormTestMax::FmsAcquireFormTemp(const std::string &bundleName, const std::string &abilityName) { std::cout << "START FmsAcquireFormTemp, add temp form" << std::endl; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_TEMP; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP)); std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP); bool result = !strFormId.empty(); EXPECT_TRUE(result); if (!result) { GTEST_LOG_(INFO) << "FmsAcquireFormTemp, result:" << result; } else { GTEST_LOG_(INFO) << "FmsAcquireFormTemp, formId:" << strFormId; } EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP_1)); std::string data2 = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP_1); bool result2 = !data2.empty(); EXPECT_TRUE(result2); if (!result2) { GTEST_LOG_(INFO) << "FmsAcquireFormTemp, result:" << result2; } else { GTEST_LOG_(INFO) << "FmsAcquireFormTemp, formData:" << data2; } std::cout << "END FmsAcquireFormTemp, add temp form" << std::endl; return strFormId; } bool FmsAcquireFormTestMax::FmsAcquireFormTempForFailed(const std::string &bundleName, const std::string &abilityName) { std::cout << "START FmsAcquireFormTempForFailed, add temp form" << std::endl; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = FORM_EVENT_REQ_ACQUIRE_FORM_TEMP; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP)); std::string strFormId = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ACQUIRE_FORM_TEMP, EVENT_CODE_TEMP); bool result = strFormId.empty(); EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireFormTempForFailed, result:" << result; std::cout << "END FmsAcquireFormTempForFailed, add temp form" << std::endl; return result; } void FmsAcquireFormTestMax::FmsAcquireFormDeleteA(const std::string &strFormId) { std::cout << "START FmsAcquireFormDeleteA, start." << std::endl; std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityA"; std::cout << "START FmsAcquireFormDeleteA, bundleName: " << bundleName << std::endl; std::cout << "START FmsAcquireFormDeleteA, abilityName: " << abilityName << std::endl; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = strFormId; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); // wait delete form EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); bool result = data == "true"; EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireFormDeleteA, delete form, result:" << result; std::cout << "END FmsAcquireFormDeleteA end" << std::endl; } void FmsAcquireFormTestMax::FmsAcquireFormDeleteB(const std::string &strFormId) { std::cout << "START FmsAcquireFormDeleteB, start." << std::endl; std::string bundleName = "com.ohos.form.manager.normalb"; std::string abilityName = "FormAbilityB"; std::cout << "START FmsAcquireFormDeleteB, bundleName: " << bundleName << std::endl; std::cout << "START FmsAcquireFormDeleteB, abilityName: " << abilityName << std::endl; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = strFormId; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); // wait delete form EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); bool result = data == "true"; EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireFormDeleteB, delete form, result:" << result; std::cout << "END FmsAcquireFormDeleteB end" << std::endl; } void FmsAcquireFormTestMax::FmsAcquireFormDeleteC(const std::string &strFormId) { std::cout << "START FmsAcquireFormDeleteC, start." << std::endl; std::string bundleName = "com.ohos.form.manager.normalc"; std::string abilityName = "FormAbilityC"; std::cout << "START FmsAcquireFormDeleteC, bundleName: " << bundleName << std::endl; std::cout << "START FmsAcquireFormDeleteC, abilityName: " << abilityName << std::endl; MAP_STR_STR params; Want want = SystemTestFormUtil::MakeWant("device", abilityName, bundleName, params); SystemTestFormUtil::StartAbility(want, abilityMs); EXPECT_EQ(SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_ABILITY_ONACTIVED, 0), 0); std::string eventData = strFormId; SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_DELETE_FORM_COMMON, EVENT_CODE_999, eventData); // wait delete form EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999); bool result = data == "true"; EXPECT_TRUE(result); GTEST_LOG_(INFO) << "FmsAcquireFormDeleteC, delete form, result:" << result; std::cout << "END FmsAcquireFormDeleteC end" << std::endl; } } // namespace AppExecFwk } // namespace OHOS
45.929227
118
0.712561
openharmony-gitee-mirror
340e6371cfab072dd0358adeb73a5d20197bc9ca
701
cc
C++
algorithms/image/threshold/boost_python/unimodal.cc
TiankunZhou/dials
bd5c95b73c442cceb1c61b1690fd4562acf4e337
[ "BSD-3-Clause" ]
58
2015-10-15T09:28:20.000Z
2022-03-28T20:09:38.000Z
algorithms/image/threshold/boost_python/unimodal.cc
TiankunZhou/dials
bd5c95b73c442cceb1c61b1690fd4562acf4e337
[ "BSD-3-Clause" ]
1,741
2015-11-24T08:17:02.000Z
2022-03-31T15:46:42.000Z
algorithms/image/threshold/boost_python/unimodal.cc
TiankunZhou/dials
bd5c95b73c442cceb1c61b1690fd4562acf4e337
[ "BSD-3-Clause" ]
45
2015-10-14T13:44:16.000Z
2022-03-22T14:45:56.000Z
/* * unimodal.cc * * Copyright (C) 2013 Diamond Light Source * * Author: James Parkhurst * * This code is distributed under the BSD license, a copy of which is * included in the root directory of this package. */ #include <boost/python.hpp> #include <boost/python/def.hpp> #include <dials/algorithms/image/threshold/unimodal.h> namespace dials { namespace algorithms { namespace boost_python { using namespace boost::python; void export_unimodal() { def("maximum_deviation", &maximum_deviation, (arg("histo"))); def("probability_distribution", &probability_distribution, (arg("image"), arg("range"))); } }}} // namespace dials::algorithms::boost_python
25.962963
70
0.699001
TiankunZhou
3413fcae1164f05e6869430c9c549bdc3b7a6e7c
6,668
hpp
C++
cpp/include/rapids_triton/model/model.hpp
divyegala/rapids-triton
8ff2a8dbad029e9379d9e7808d868924c4b60590
[ "Apache-2.0" ]
1
2022-02-23T23:38:40.000Z
2022-02-23T23:38:40.000Z
cpp/include/rapids_triton/model/model.hpp
divyegala/rapids-triton
8ff2a8dbad029e9379d9e7808d868924c4b60590
[ "Apache-2.0" ]
12
2021-09-20T21:23:27.000Z
2022-03-31T22:53:30.000Z
cpp/include/rapids_triton/model/model.hpp
divyegala/rapids-triton
8ff2a8dbad029e9379d9e7808d868924c4b60590
[ "Apache-2.0" ]
2
2022-01-27T20:58:07.000Z
2022-02-09T23:07:41.000Z
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifdef TRITON_ENABLE_GPU #include <cuda_runtime_api.h> #else #include <rapids_triton/cpu_only/cuda_runtime_replacement.hpp> #endif #include <cstddef> #include <rapids_triton/batch/batch.hpp> #include <rapids_triton/memory/resource.hpp> #include <rapids_triton/model/shared_state.hpp> #include <rapids_triton/tensor/tensor.hpp> #include <rapids_triton/triton/deployment.hpp> #include <rapids_triton/triton/device.hpp> #include <rapids_triton/utils/narrow.hpp> #include <string> #include <vector> namespace triton { namespace backend { namespace rapids { template <typename SharedState = SharedModelState> struct Model { virtual void predict(Batch& batch) const = 0; virtual void load() {} virtual void unload() {} /** * @brief Return the preferred memory type in which to store data for this * batch or std::nullopt to accept whatever Triton returns * * The base implementation of this method will require data on-host if the * model itself is deployed on the host OR if this backend has not been * compiled with GPU support. Otherwise, models deployed on device will * receive memory on device. Overriding this method will allow derived * model classes to select a preferred memory location based on properties * of the batch or to simply return std::nullopt if device memory or host * memory will do equally well. */ virtual std::optional<MemoryType> preferred_mem_type(Batch& batch) const { return (IS_GPU_BUILD && deployment_type_ == GPUDeployment) ? DeviceMemory : HostMemory; } virtual std::optional<MemoryType> preferred_mem_type_in(Batch& batch) const { return preferred_mem_type(batch); } virtual std::optional<MemoryType> preferred_mem_type_out(Batch& batch) const { return preferred_mem_type(batch); } /** * @brief Retrieve a stream used to set up batches for this model * * The base implementation of this method simply returns the default stream * provided by Triton for use with this model. Child classes may choose to * override this in order to provide different streams for use with * successive incoming batches. For instance, one might cycle through * several streams in order to distribute batches across them, but care * should be taken to ensure proper synchronization in this case. */ virtual cudaStream_t get_stream() const { return default_stream_; } /** * @brief Get input tensor of a particular named input for an entire batch */ template <typename T> auto get_input(Batch& batch, std::string const& name, std::optional<MemoryType> const& mem_type, cudaStream_t stream) const { return batch.get_input<T const>(name, mem_type, device_id_, stream); } template <typename T> auto get_input(Batch& batch, std::string const& name, std::optional<MemoryType> const& mem_type) const { return get_input<T>(batch, name, mem_type, default_stream_); } template <typename T> auto get_input(Batch& batch, std::string const& name) const { return get_input<T>(batch, name, preferred_mem_type(batch), default_stream_); } /** * @brief Get output tensor of a particular named output for an entire batch */ template <typename T> auto get_output(Batch& batch, std::string const& name, std::optional<MemoryType> const& mem_type, device_id_t device_id, cudaStream_t stream) const { return batch.get_output<T>(name, mem_type, device_id, stream); } template <typename T> auto get_output(Batch& batch, std::string const& name, std::optional<MemoryType> const& mem_type, cudaStream_t stream) const { return get_output<T>(batch, name, mem_type, device_id_, stream); } template <typename T> auto get_output(Batch& batch, std::string const& name, std::optional<MemoryType> const& mem_type) const { return get_output<T>(batch, name, mem_type, device_id_, default_stream_); } template <typename T> auto get_output(Batch& batch, std::string const& name) const { return get_output<T>(batch, name, preferred_mem_type(batch), device_id_, default_stream_); } /** * @brief Retrieve value of configuration parameter */ template <typename T> auto get_config_param(std::string const& name) const { return shared_state_->template get_config_param<T>(name); } template <typename T> auto get_config_param(std::string const& name, T default_value) const { return shared_state_->template get_config_param<T>(name, default_value); } template <typename T> auto get_config_param(char const* name) const { return get_config_param<T>(std::string(name)); } template <typename T> auto get_config_param(char const* name, T default_value) const { return get_config_param<T>(std::string(name), default_value); } Model(std::shared_ptr<SharedState> shared_state, device_id_t device_id, cudaStream_t default_stream, DeploymentType deployment_type, std::string const& filepath) : shared_state_{shared_state}, device_id_{device_id}, default_stream_{default_stream}, deployment_type_{deployment_type}, filepath_{filepath} { if constexpr (IS_GPU_BUILD) { setup_memory_resource(device_id_); } } auto get_device_id() const { return device_id_; } auto get_deployment_type() const { return deployment_type_; } auto const& get_filepath() const { return filepath_; } auto get_output_shape(std::string const& name) const { return shared_state_->get_output_shape(name); } protected: auto get_shared_state() const { return shared_state_; } private: std::shared_ptr<SharedState> shared_state_; device_id_t device_id_; cudaStream_t default_stream_; DeploymentType deployment_type_; std::string filepath_; }; } // namespace rapids } // namespace backend } // namespace triton
33.676768
94
0.707858
divyegala