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 float64 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 float64 1 77k ⌀ | 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 float64 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 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f9567c21e5efba5d8f92be3281a01b12c87beb69 | 485 | cpp | C++ | src/tema fisa for/ex 4 e/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | 2 | 2021-11-27T18:29:32.000Z | 2021-11-28T14:35:47.000Z | src/tema fisa for/ex 4 e/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | null | null | null | src/tema fisa for/ex 4 e/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int a,b,x,i=0,cx;
cout<<"a= ";
cin>>a;
cout<<"b= ";
cin>>b;
x=a;
cx=x;
for(x; x<=b; x++)
{
cx=x;
while(cx!=0)
{
if(cx%10==0)
{
i=i+1;
cx=0;
}
else
{
cx=cx/10;
}
}
}
cout<<"Sunt "<<i<<" numere care contin cifra 0";
return 0;
}
| 13.472222 | 52 | 0.31134 |
f959521c5cbd6c7f161c30141344a94c747dfb63 | 10,586 | cpp | C++ | src/particle_filter.cpp | abcd-source/CarND-Kidnapped-Vehicle-Project | 2be015fba090fba589a86939e31d423ca17e7e65 | [
"MIT"
] | null | null | null | src/particle_filter.cpp | abcd-source/CarND-Kidnapped-Vehicle-Project | 2be015fba090fba589a86939e31d423ca17e7e65 | [
"MIT"
] | null | null | null | src/particle_filter.cpp | abcd-source/CarND-Kidnapped-Vehicle-Project | 2be015fba090fba589a86939e31d423ca17e7e65 | [
"MIT"
] | null | null | null | /**
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include "particle_filter.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <string>
#include <vector>
#include "helper_functions.h"
using std::string;
using std::vector;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
/**
* TODO: Set the number of particles. Initialize all particles to
* first position (based on estimates of x, y, theta and their uncertainties
* from GPS) and all weights to 1.
* TODO: Add random Gaussian noise to each particle.
* NOTE: Consult particle_filter.h for more information about this method
* (and others in this file).
*/
num_particles = 256; // TODO: Set the number of particles
std::normal_distribution<double> x_distribution(x, std[0]);
std::normal_distribution<double> y_distribution(y, std[1]);
std::normal_distribution<double> theta_distribution(theta, std[2]);
std::default_random_engine random;
for (int i = 0; i < num_particles; i++)
{
Particle p;
p.id = i;
p.x = x_distribution(random);
p.y = y_distribution(random);
p.theta = theta_distribution(random);
p.weight = 1.0;
particles.push_back(p);
}
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[],
double velocity, double yaw_rate) {
/**
* TODO: Add measurements to each particle and add random Gaussian noise.
* NOTE: When adding noise you may find std::normal_distribution
* and std::default_random_engine useful.
* http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
* http://www.cplusplus.com/reference/random/default_random_engine/
*/
std::default_random_engine random;
for (auto& p : particles)
{
// C1 and C2 are simply intermediate computations for ease
const double c1 = velocity / yaw_rate;
const double c2 = yaw_rate * delta_t;
// For (x,y,theta) transform the particle position by the velocity
// and yaw rate, and sample from the normal distribution defined
// by the standard deviations in std_pos[]
const double x = p.x + c1 * (sin(p.theta + c2) - sin(p.theta));
std::normal_distribution<double> x_dist(x, std_pos[0]);
p.x = x_dist(random);
const double y = p.y + c1 * (cos(p.theta) - cos(p.theta + c2));
std::normal_distribution<double> y_dist(y, std_pos[1]);
p.y = y_dist(random);
const double theta = p.theta + c2;
std::normal_distribution<double> theta_dist(theta, std_pos[2]);
p.theta = theta_dist(random);
}
}
void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted,
vector<LandmarkObs>& observations) {
/**
* TODO: Find the predicted measurement that is closest to each
* observed measurement and assign the observed measurement to this
* particular landmark.
* NOTE: this method will NOT be called by the grading code. But you will
* probably find it useful to implement this method and use it as a helper
* during the updateWeights phase.
*/
for (auto& o : observations) {
double min_dist = std::numeric_limits<double>::max();
int min_landmark_id = -1;
for (const auto& p : predicted)
{
// If the linear distance in either the x or y axis is greater
// than min_distance, don't calculate the quadratic distance
if (abs(o.x - p.x) > min_dist ||
abs(o.y - p.y) > min_dist)
{
continue;
}
// Distance between observation (x,y) and predicted (x,y)
const double distance = dist(o.x, o.y, p.x, p.y);
// Find the ID of the closest particle p to the landmark o
if (distance < min_dist) {
min_dist = distance;
min_landmark_id = p.id;
}
}
// Assign the predicted landmark ID to the observation ID
o.id = min_landmark_id;
}
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
const vector<LandmarkObs> &observations,
const Map &map_landmarks) {
/**
* TODO: Update the weights of each particle using a mult-variate Gaussian
* distribution. You can read more about this distribution here:
* https://en.wikipedia.org/wiki/Multivariate_normal_distribution
* NOTE: The observations are given in the VEHICLE'S coordinate system.
* Your particles are located according to the MAP'S coordinate system.
* You will need to transform between the two systems. Keep in mind that
* this transformation requires both rotation AND translation (but no scaling).
* The following is a good resource for the theory:
* https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
* and the following is a good resource for the actual equation to implement
* (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html
*/
for (auto& p : particles)
{
// Find the set of landmarks within the sensor range
// and add to a new vector "predicted"
vector<LandmarkObs> predicted;
for (const auto& lm : map_landmarks.landmark_list)
{
// If the linear distance in either axis is greater than
// the sensor range, do not calculate the quadratic distance
if (abs(p.x - lm.x) > sensor_range ||
abs(p.y - lm.y) > sensor_range)
{
continue;
}
if (dist(p.x, p.y, lm.x, lm.y) < sensor_range)
{
predicted.push_back(lm);
}
}
// Transform each of the observations from the vehicle coordinate
// system to the map coordinate system to be compared to particles
vector<LandmarkObs> transformed_observations;
for (const auto& o : observations)
{
const double x = p.x + cos(p.theta) * o.x - sin(p.theta) * o.y;
const double y = p.y + sin(p.theta) * o.x + cos(p.theta) * o.y;
transformed_observations.push_back(LandmarkObs{o.id, x, y});
}
// Find the nearest neighbors between the in-range landmarks (predicted)
// and the sensor observations in the global coordinate system
dataAssociation(predicted, transformed_observations);
// Create dummy vectors of ID associations and measurements
// which will be used for visualizations in the simulation
vector<int> associations;
vector<double> sense_x;
vector<double> sense_y;
double weight = 1.0;
const double std_x = std_landmark[0];
const double std_y = std_landmark[1];
for (const auto& o : transformed_observations)
{
for (const auto& lm : predicted)
{
if (o.id == lm.id)
{
// Find the association weight using the mult-variate Gaussian function
// using the function defined in the lesson.
const double x = (lm.x - o.x) * (lm.x - o.x) / (2.f * std_x * std_x);
const double y = (lm.y - o.y) * (lm.y - o.y) / (2.f * std_y * std_y);
weight *= exp(-(x+y)) / (2.f * M_PI * std_x * std_y);
// Add the associated landmark ID and (x,y) measurement to the
// visualization / debug vectors
associations.push_back((o.id));
sense_x.push_back((o.x));
sense_y.push_back((o.y));
}
}
}
// Update the particle's weight with the product of all the
// weights of each association to the observable landmarks
p.weight = weight;
// For debugging / visualization purposes add the associated
// observation vectors, and sense vectors
SetAssociations(p, associations, sense_x, sense_y);
}
}
void ParticleFilter::resample() {
/**
* TODO: Resample particles with replacement with probability proportional
* to their weight.
* NOTE: You may find std::discrete_distribution helpful here.
* http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
*/
// Create a stand-alone vector of weights from all the particles
std::vector<double> weights;
for (const auto& p : particles)
{
weights.push_back(p.weight);
}
// Create a random device to sample from the weight distribution
std::random_device rd;
std::mt19937 gen(rd());
// Use a discrete_distribution per cppreference.com to replace
// the particles vector with a new vector of sampled particles
// based on the particle weights
std::discrete_distribution<> d(weights.begin(), weights.end());
std::vector<Particle> samples;
for (int i = 0; i < num_particles; i++)
{
samples.push_back(particles[d(gen)]);
}
particles = samples;
}
void ParticleFilter::SetAssociations(Particle& particle,
const vector<int>& associations,
const vector<double>& sense_x,
const vector<double>& sense_y) {
// particle: the particle to which assign each listed association,
// and association's (x,y) world coordinates mapping
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
particle.associations= associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
}
string ParticleFilter::getAssociations(Particle best) {
vector<int> v = best.associations;
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseCoord(Particle best, string coord) {
vector<double> v;
if (coord == "X") {
v = best.sense_x;
} else {
v = best.sense_y;
}
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
} | 36.378007 | 91 | 0.623748 |
f959c903e7d50b358684b12ef918d3179555705b | 4,509 | cpp | C++ | unit_tests/main.cpp | obhi-d/hfn | 692203a25a13214ba8a0e2feddb8d6e78275c860 | [
"MIT"
] | null | null | null | unit_tests/main.cpp | obhi-d/hfn | 692203a25a13214ba8a0e2feddb8d6e78275c860 | [
"MIT"
] | null | null | null | unit_tests/main.cpp | obhi-d/hfn | 692203a25a13214ba8a0e2feddb8d6e78275c860 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include "hfn/config.hpp"
#include "hfn/cxstring.hpp"
#include "hfn/digest.hpp"
#include "hfn/fnv1a.hpp"
#include "hfn/murmur3.hpp"
#include "hfn/rhid.hpp"
#include "hfn/type_hash.hpp"
#include "hfn/wyhash.hpp"
#include "hfn/xxhash.hpp"
#include <catch2/catch.hpp>
#include <iostream>
class type_name_test
{};
TEST_CASE("Asserts", "[asserts]")
{
static_assert(sizeof(hfn::uhash128_t) == 16, "Size is incorrect");
CHECK(hfn::digest<std::uint64_t>(0) == "0");
CHECK(hfn::type_name<type_name_test>() == "class type_name_test");
constexpr std::uint32_t cth = hfn::type_hash<std::string_view>();
static_assert(cth == 787592100);
CHECK(hfn::digest<std::uint64_t>(0xff64ffaadd41) == "1anlqvjcv7");
}
TEST_CASE("Murmur3", "[murmur]")
{
std::string text = "The director instructed us to do batshit crazy things in the past.";
std::string first = "First string.";
std::string second = "Second string.";
std::string combined = text + first + second;
hfn::murmur3_32 hash32;
hash32(text.c_str(), text.length());
CHECK(hash32() == hfn::murmur3::compute32(text.c_str(), text.length()));
hfn::murmur3_128 hash128;
hash128(text.c_str(), text.length());
CHECK(hash128() == hfn::murmur3::compute128(text.c_str(), text.length()));
std::string_view conflict1 = "vertexColor";
std::string_view conflict2 = "userDefined";
CHECK(hfn::murmur3::compute32(conflict2.data(), conflict2.length()) !=
hfn::murmur3::compute32(conflict1.data(), conflict1.length()));
hfn::cxstring s = "fixdStrinTest";
CHECK(s.hash() == hfn::murmur3::compute32(s.data(), s.size()));
}
TEST_CASE("Fnv1a", "[fnv1a]")
{
std::string text = "The director instructed us to do batshit crazy things in the past.";
std::string first = "First string.";
std::string second = "Second string.";
std::string combined = text + first + second;
hfn::fnv1a_32 hash32;
hash32(text.c_str(), text.length());
CHECK(hash32() == hfn::fnv1a::compute32(text.c_str(), text.length()));
hfn::fnv1a_64 hash64;
hash64(text.c_str(), text.length());
CHECK(hash64() == hfn::fnv1a::compute64(text.c_str(), text.length()));
hash32(first.c_str(), first.length());
hash32(second.c_str(), second.length());
CHECK(hash32() == hfn::fnv1a::compute32(combined.c_str(), combined.length()));
hash64(first.c_str(), first.length());
hash64(second.c_str(), second.length());
CHECK(hash64() == hfn::fnv1a::compute64(combined.c_str(), combined.length()));
}
TEST_CASE("Wyhash", "[wyhash]")
{
std::string text = "The director instructed us to do batshit crazy things in the past.";
hfn::wyhash_32 hash32;
hash32(text.c_str(), text.length());
CHECK(hash32() == hfn::wyhash::compute32(text.c_str(), text.length()));
hfn::wyhash_64 hash64;
hash64(text.c_str(), text.length());
CHECK(hash64() == hfn::wyhash::compute64(text.c_str(), text.length()));
hash32 = hfn::wyhash_32();
hash32(text.c_str(), 10);
hash32(text.c_str() + 10, text.length() - 10);
// CHECK(hash32() == hfn::wyhash::compute32(text.c_str(), text.length()));
hash64 = hfn::wyhash_64();
hash64(text.c_str(), 10);
hash64(text.c_str() + 10, text.length() - 10);
// CHECK(hash64() == hfn::wyhash::compute64(text.c_str(), text.length()));
}
TEST_CASE("X3hash", "[xxhash]")
{
std::string text = "The director instructed us to do batshit crazy things in the past.";
std::string first = "First string.";
std::string second = "Second string.";
std::string combined = text + first + second;
hfn::xxhash_64 hash64;
hash64(text.c_str(), text.length());
CHECK(hash64() == hfn::xxhash::compute64(text.c_str(), text.length()));
hfn::xxhash_128 hash128;
hash64(text.c_str(), text.length());
// CHECK(hash128() == hfn::xxhash::compute128(text.c_str(), text.length()));
hash64(first.c_str(), first.length());
hash64(second.c_str(), second.length());
// CHECK(hash64() == hfn::xxhash::compute64(combined.c_str(), combined.length()));
hash128(first.c_str(), first.length());
hash128(second.c_str(), second.length());
// CHECK(hash128() == hfn::xxhash::compute128(combined.c_str(), combined.length()));
}
TEST_CASE("RHID", "[rhid]")
{
std::string text = "The director instructed us to do batshit crazy things in the past.";
std::string first = "First string.";
std::string second = "Second string.";
CHECK(hfn::rhid() == hfn::null_rhid);
hfn::rhid rhid;
rhid.update(text.c_str(), text.length());
CHECK((std::string)rhid == "mkjl131");
}
| 32.673913 | 92 | 0.664005 |
f959e804126995f18a040d22d82f3909666733f0 | 511 | cpp | C++ | Util/WebUrl.cpp | SoftlySpoken/gStore | b2cf71288ccef376640000965aff7c430101446a | [
"BSD-3-Clause"
] | 150 | 2015-01-14T15:06:38.000Z | 2018-08-28T09:34:17.000Z | Util/WebUrl.cpp | SoftlySpoken/gStore | b2cf71288ccef376640000965aff7c430101446a | [
"BSD-3-Clause"
] | 28 | 2015-05-11T02:45:39.000Z | 2018-08-24T11:43:17.000Z | Util/WebUrl.cpp | SoftlySpoken/gStore | b2cf71288ccef376640000965aff7c430101446a | [
"BSD-3-Clause"
] | 91 | 2015-05-04T09:52:41.000Z | 2018-08-18T13:02:15.000Z | #include "WebUrl.h"
using namespace std;
WebUrl::WebUrl() {}
WebUrl::~WebUrl() {}
string WebUrl::CutParam(string url, string param)
{
int index = url.find("?" + param + "=");
if (index < 0)
{
index = url.find("&" + param + "=");
}
if (index < 0)
return string();
int index2 = index + 1 + (param + "=").length();
string substr = url.substr(index2);
int endindex = substr.find("&");
if (endindex > 0)
{
string substr2 = substr.substr(0, endindex);
return substr2;
}
else
return substr;
} | 18.25 | 49 | 0.60274 |
f9601f472091e6a18894fa6522a21e9160e64b8c | 4,786 | cpp | C++ | PageRepository/Source/Page.cpp | DiplodocusDB/PhysicalStorage | 9b110471d14300873a9067b25b0825727c178549 | [
"MIT"
] | null | null | null | PageRepository/Source/Page.cpp | DiplodocusDB/PhysicalStorage | 9b110471d14300873a9067b25b0825727c178549 | [
"MIT"
] | 19 | 2018-01-20T14:38:20.000Z | 2018-01-26T22:58:52.000Z | PageRepository/Source/Page.cpp | DiplodocusDB/PhysicalStorage | 9b110471d14300873a9067b25b0825727c178549 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2018-2019 Xavier Leclercq
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 "Page.h"
#include "PageFileRepository.h"
#include "Ishiko/Errors/IOErrorExtension.h"
#include <sstream>
namespace DiplodocusDB
{
Page::Page(size_t index)
: m_index(index), m_dataSize(0), m_availableSpace(sm_size - sm_startMarkerSize - sm_endMarkerSize), m_nextPage(0)
{
}
void Page::init()
{
memset(m_buffer, 0, sm_size);
}
size_t Page::index() const
{
return m_index;
}
size_t Page::dataSize() const
{
return m_dataSize;
}
size_t Page::maxDataSize() const
{
return (sm_size - sm_startMarkerSize - sm_endMarkerSize);
}
size_t Page::availableSpace() const
{
return m_availableSpace;
}
size_t Page::nextPage() const
{
return m_nextPage;
}
void Page::setNextPage(size_t index)
{
m_nextPage = index;
}
void Page::get(char* buffer,
size_t pos,
size_t n,
Ishiko::Error& error) const
{
if ((pos + n) <= m_dataSize)
{
memcpy(buffer, m_buffer + sm_startMarkerSize + pos, n);
}
else
{
std::stringstream message;
message << "Page::get (m_index: " << m_index << ", pos:" << pos << ", n:" << n
<< ") exceeds data size (m_datasize: " << m_dataSize << ")";
error.fail(-1, message.str(), __FILE__, __LINE__);
}
}
void Page::insert(const char* buffer, size_t bufferSize, size_t pos, Ishiko::Error& error)
{
if (bufferSize <= m_availableSpace)
{
char* p = (m_buffer + sm_startMarkerSize);
if (pos != m_dataSize)
{
memmove(p + pos + bufferSize, p + pos, (m_dataSize - pos));
}
memcpy(p + pos, buffer, bufferSize);
m_dataSize += bufferSize;
m_availableSpace -= bufferSize;
}
else
{
// TODO : add page details
error.fail(-1, "Failed to insert page", __FILE__, __LINE__);
}
}
void Page::erase(size_t pos, size_t n, Ishiko::Error& error)
{
memmove(m_buffer + sm_startMarkerSize + pos, m_buffer + sm_startMarkerSize + pos + n,
m_dataSize + sm_endMarkerSize - pos - n);
memset(m_buffer + sm_startMarkerSize + m_dataSize + sm_endMarkerSize - n, 0, n);
m_dataSize -= n;
m_availableSpace += n;
}
void Page::moveTo(size_t pos, size_t n, Page& targetPage, Ishiko::Error& error)
{
targetPage.insert(m_buffer + sm_startMarkerSize + pos, n, 0, error);
if (!error)
{
erase(pos, n, error);
}
}
void Page::write(std::ostream& output, Ishiko::Error& error) const
{
output.seekp(m_index * sm_size);
Ishiko::IOErrorExtension::Fail(error, output, __FILE__, __LINE__);
if (!error)
{
memcpy(m_buffer, "\xF0\x06\x00\x00\x00\x00", 6);
*((uint16_t*)(m_buffer + 6)) = (uint16_t)m_dataSize;
memcpy(m_buffer + sm_startMarkerSize + m_dataSize, "\xF1\x06\x00\x00\x00\x00\x00\x00", 8);
*((uint32_t*)(m_buffer + sm_startMarkerSize + m_dataSize + 2)) = m_nextPage;
output.write(m_buffer, sm_size);
Ishiko::IOErrorExtension::Fail(error, output, __FILE__, __LINE__);
}
}
void Page::read(std::istream& input, Ishiko::Error& error)
{
input.seekg(m_index * sm_size);
Ishiko::IOErrorExtension::Fail(error, input, __FILE__, __LINE__);
if (!error)
{
input.read(m_buffer, sm_size);
Ishiko::IOErrorExtension::Fail(error, input, __FILE__, __LINE__);
if (!error)
{
m_dataSize = *((uint16_t*)(m_buffer + 6));
m_availableSpace = sm_size - sm_startMarkerSize - sm_endMarkerSize - m_dataSize;
uint32_t nextPage = *((uint32_t*)(m_buffer + sm_startMarkerSize + m_dataSize + 2));
m_nextPage = nextPage;
}
}
}
}
| 29.361963 | 117 | 0.649603 |
f96c117a5b81a2b6b456ee21a20b141634852997 | 8,129 | cpp | C++ | d20/a.cpp | webdeveloperukraine/adventofcode2020 | 4d4f36437da0fd4889f0fcbe28cad8fecb6f6f34 | [
"MIT"
] | null | null | null | d20/a.cpp | webdeveloperukraine/adventofcode2020 | 4d4f36437da0fd4889f0fcbe28cad8fecb6f6f34 | [
"MIT"
] | null | null | null | d20/a.cpp | webdeveloperukraine/adventofcode2020 | 4d4f36437da0fd4889f0fcbe28cad8fecb6f6f34 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#include "../helpers/string_helpers.cpp"
typedef long long int ll;
struct Tile{
ll id;
vector<string> pattern;
int width, height;
Tile(){ throw runtime_error("No Way!"); }
Tile(ll id, vector<string> pattern) : id(id), pattern(pattern){
height = pattern.size();
width = pattern[0].size();
}
void flipx(){
for(int i=0;i<height;i++){
for(int j=0;j<width/2;j++){
swap(pattern[i][j], pattern[i][width-j-1]);
}
}
}
void flipy(){
for(int i=0;i<height/2;i++){
swap(pattern[i], pattern[height-i-1]);
}
}
void rotate()
{
vector<string> res;
for(int i=0;i<width;i++){
string s;
for(int j=0;j<height;j++){
s.push_back(pattern[j][i]);
}
reverse(s.begin(), s.end());
res.push_back(s);
}
pattern = res;
}
};
unordered_map<ll, Tile> input;
void prepare()
{
string s;
vector<string> pat;
ll id;
while(getline(cin, s)){
if(s[0] == 'T'){
string str = split_line(s, " ")[1];
id = stoll(str.substr(0, str.size()-1));
continue;
}
if(s == ""){
input.insert(make_pair(id, Tile(id, pat)));
pat.resize(0);
continue;
}
pat.push_back(s);
}
input.insert(make_pair(id, Tile(id, pat)));
}
string get_top_line(Tile& t)
{
return t.pattern[0];
}
string get_left_line(Tile& t)
{
string s;
for(int i=t.height-1;i>=0;i--){
s.push_back(t.pattern[i][0]);
}
return s;
}
string get_bottom_line(Tile& t)
{
string s = t.pattern[t.pattern.size()-1];
reverse(s.begin(), s.end());
return s;
}
string get_right_line(Tile& t)
{
string s;
for(int i=0;i<t.height;i++){
s.push_back(t.pattern[i][9]);
}
return s;
}
ll line_to_num(string s)
{
ll n = 0;
for(int i=0;i<s.size();i++){
if(s[i] == '#') n = n | 1;
if(s.size()-1 != i) n <<= 1;
}
return n;
}
unordered_map<ll, ll> arr;
unordered_map<ll, vector<int>> cnts;
void prepare_other()
{
if(arr.size()) return;
string s;
for(auto& itt : input){
auto& it = itt.second;
s = get_top_line(it);
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
reverse(s.begin(), s.end());
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
s = get_bottom_line(it);
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
reverse(s.begin(), s.end());
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
s = get_left_line(it);
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
reverse(s.begin(), s.end());
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
s = get_right_line(it);
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
reverse(s.begin(), s.end());
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
}
}
ll first()
{
prepare_other();
unordered_map<ll, int> garr;
for(auto& it : cnts){
if(it.second.size() == 1){
garr[arr[it.first]]++;
}
}
ll res = 1;
for(auto& it : garr){
if(it.second == 4){
res *= it.first;
}
}
return res;
}
//////////////////////////////////////////////////////////
struct MT{
MT *top=nullptr, *right=nullptr, *bottom=nullptr, *left=nullptr;
ll id;
};
unordered_map<ll, MT*> mt_map;
ll get_else_id(ll a, ll id)
{
auto& v = cnts[a];
if(v[0] == id) return v[1];
return v[0];
}
void transform(ll id, ll a, string side)
{
Tile& t = input[id];
for(int i=0;i<8;i++){
ll b;
if(side == "top") b = line_to_num(get_top_line(t));
if(side == "right") b = line_to_num(get_right_line(t));
if(side == "bottom") b = line_to_num(get_bottom_line(t));
if(side == "left") b = line_to_num(get_left_line(t));
if(b == a){
if(side == "top" || side == "bottom"){
t.flipx();
} else {
t.flipy();
}
return;
}
t.rotate();
if(i == 3){
t.flipx();
}
}
throw runtime_error("No Way!");
}
unordered_set<ll> r_done;
void req(MT* a)
{
if(!a) return;
if(r_done.count(a->id)) return;
r_done.insert(a->id);
Tile& t = input[a->id];
ll top = line_to_num(get_top_line(t));
ll right = line_to_num(get_right_line(t));
ll bottom = line_to_num(get_bottom_line(t));
ll left = line_to_num(get_left_line(t));
MT *mt_top = nullptr, *mt_right = nullptr, *mt_bottom = nullptr, *mt_left = nullptr;
if(cnts[top].size() > 1){
ll id = get_else_id(top, a->id);
if(mt_map.count(id)){
a->top = mt_map[id];
} else {
mt_top = new MT;
mt_map[id] = mt_top;
mt_top->id = id;
a->top = mt_top;
transform(id, top, "bottom");
}
}
if(cnts[right].size() > 1){
ll id = get_else_id(right, a->id);
if(mt_map.count(id)){
a->right = mt_map[id];
} else {
mt_right = new MT;
mt_map[id] = mt_right;
mt_right->id = id;
a->right = mt_right;
transform(id, right, "left");
}
}
if(cnts[bottom].size() > 1){
ll id = get_else_id(bottom, a->id);
if(mt_map.count(id)){
a->bottom = mt_map[id];
} else {
mt_bottom = new MT;
mt_map[id] = mt_bottom;
mt_bottom->id = id;
a->bottom = mt_bottom;
transform(id, bottom, "top");
}
}
if(cnts[left].size() > 1){
ll id = get_else_id(left, a->id);
if(mt_map.count(id)){
a->left = mt_map[id];
} else {
mt_left = new MT;
mt_map[id] = mt_left;
mt_left->id = id;
a->left = mt_left;
transform(id, left, "right");
}
}
req(a->top);
req(a->right);
req(a->bottom);
req(a->left);
}
bool done[12][12];
char image[12*8][12*8];
void fill(Tile& t, int x, int y)
{
if(x > 11 || y > 11) throw runtime_error("No Way!");
for(int i=1;i<t.height-1;i++){
for(int j=1;j<t.width-1;j++){
image[y*8+i-1][x*8+j-1] = t.pattern[i][j];
}
}
}
void req_build(MT* a, int x, int y)
{
if(!a) return;
if(done[x][y]) return;
done[x][y] = true;
fill(input[a->id], x, y);
req_build(a->right, x+1, y);
req_build(a->bottom, x, y+1);
}
void print_image()
{
for(int i=0;i<12*8;i++){
cout << "_";
}
cout << endl;
for(int i=0;i<12*8;i++){
for(int j=0;j<12*8;j++){
cout << image[i][j];
}
cout << endl;
}
}
void rotate_image()
{
int W = 8*12;
char new_image[W][W];
for(int i=0;i<W;i++){
for(int j=0;j<W;j++){
new_image[i][j] = image[j][i];
}
for(int j=0;j<W/2;j++){
swap(new_image[i][j], new_image[i][W-j-1]);
}
}
for(int i=0;i<W;i++){
for(int j=0;j<W;j++){
image[i][j] = new_image[i][j];
}
}
}
void flip_image()
{
int W = 8*12;
for(int i=0;i<W;i++){
for(int j=0;j<W/2;j++){
swap(image[i][j], image[i][W-j-1]);
}
}
}
vector<string> monster = {
" # ",
"# ## ## ###",
" # # # # # # "
};
int find_monsters()
{
int res = 0;
int W = 8*12;
int MW = monster[0].size();
int MH = monster.size();
for(int i=0;i<W;i++){
for(int j=0;j<W;j++){
if(W-i >= MH && W-j >= MW){
bool found = true;
for(int ii=0;ii<MH;ii++){
for(int jj=0;jj<MW;jj++){
if(monster[ii][jj] == '#' && image[i+ii][j+jj] != '#'){
found = false;
break;
}
}
}
if(found){
res++;
for(int ii=0;ii<MH;ii++){
for(int jj=0;jj<MW;jj++){
if(monster[ii][jj] == '#'){
image[i+ii][j+jj] = 'O';
}
}
}
}
}
}
}
return res;
}
ll second()
{
// preapre other things
prepare_other();
// Build an image
ll one_id = input.begin()->first;
MT* part = new MT;
part->id = one_id;
mt_map[one_id] = part;
req(part);
// write image to array
while(part->top){ part = part->top; }
while(part->left){ part = part->left; }
req_build(part,0,0);
// Find monsters
bool found = false;
for(int i=0;i<10;i++){
if(find_monsters()){
found = true;
break;
}
rotate_image();
if(i == 4) flip_image();
}
if(!found){
throw runtime_error("Not Found Monsters :(");
}
int res = 0;
for(int i=0;i<8*12;i++){
for(int j=0;j<8*12;j++){
if(image[i][j] == '#') res++;
}
}
return res;
}
int main()
{
prepare();
cout << "First: " << first() << endl;
cout << "Second: " << second() << endl;
// Print image with monsters
print_image();
return 0;
}
| 17.905286 | 85 | 0.558986 |
f96c326286a20d184db4bb728848da1abf9f28fe | 2,663 | cpp | C++ | source/line.cpp | Zylon-D-Lite/drawingPrototype | 60caa86e72ad7fd36aed15679b003747c69e81c6 | [
"MIT"
] | null | null | null | source/line.cpp | Zylon-D-Lite/drawingPrototype | 60caa86e72ad7fd36aed15679b003747c69e81c6 | [
"MIT"
] | null | null | null | source/line.cpp | Zylon-D-Lite/drawingPrototype | 60caa86e72ad7fd36aed15679b003747c69e81c6 | [
"MIT"
] | null | null | null | #include "./line.hpp"
const png::rgba_pixel Line::WHITE_PIXEL = png::rgba_pixel(255, 255, 255, 255);
const png::rgba_pixel Line::BLACK_PIXEL = png::rgba_pixel(0, 0, 0, 255);
const png::rgba_pixel Line::TRANSPARENT_PIXEL = png::rgba_pixel(0, 0, 0, 0);
const png::rgba_pixel Line::RED_PIXEL = png::rgba_pixel(255, 0, 0, 255);
const png::rgba_pixel Line::GREEN_PIXEL = png::rgba_pixel(0, 255, 0, 255);
const png::rgba_pixel Line::BLUE_PIXEL = png::rgba_pixel(0, 0, 255, 255);
bool Line::isAdjacent(Coordinate i_curr, Coordinate i_adjacent) {
if (abs(i_curr.x - i_adjacent.x) <= 1 &&
abs(i_curr.y - i_adjacent.y) <= 1) {
return true;
}
return false;
}
std::pair<bool, std::string> Line::check(const png::image<png::rgba_pixel>& i_image,
png::rgba_pixel i_on_pixel) {
auto firstCheck = check();
bool noProblems = true;
if (firstCheck.first == true) {
return firstCheck;
}
std::string returnMessage{};
for (auto coordinate : lineData) {
if (i_image[coordinate.y][coordinate.x].red != i_on_pixel.red ||
i_image[coordinate.y][coordinate.x].green != i_on_pixel.green ||
i_image[coordinate.y][coordinate.x].blue != i_on_pixel.blue) {
returnMessage += "Pixel value mismatch at: x = "
+ std::to_string(coordinate.x) + ", y = "
+ std::to_string(coordinate.y) + "\n";
noProblems = false;
}
}
if (!noProblems)
return std::pair<bool, std::string>(false, firstCheck.second + returnMessage);
return std::pair<bool, std::string>(true, "No problems detected");
}
std::pair<bool, std::string> Line::check() {
bool noProblems = true;
std::string returnMessage{};
for (size_t i = 0; i < lineData.size() - 1; ++i) {
if (!isAdjacent(lineData[i], lineData[i+1])) {
returnMessage += "Discontinued line at: x1 = "
+ std::to_string(lineData[i].x) + ", y1 = "
+ std::to_string(lineData[i].y) + ", x2 = "
+ std::to_string(lineData[i + 1].x) + ", y2 = "
+ std::to_string(lineData[i + 1].y) + "\n";
noProblems = false;
}
}
if (!noProblems)
return std::pair<bool, std::string>(false, returnMessage);
return std::pair<bool, std::string>(true, "No problems detected");
}
inline void Line::insert(size_t offset, const Coordinate& input) {
lineData.insert(lineData.begin() + offset, input);
}
void Line::append(const std::vector<Coordinate>::iterator& beg_it,
const std::vector<Coordinate>::iterator& end_it)
{
lineData.insert(lineData.end(), beg_it, end_it);
}
| 39.161765 | 86 | 0.607585 |
f96d0aa3ae182e22ac149151167544afb5674954 | 15,323 | cpp | C++ | ppm_image.cpp | gulesh/pixmap-ops | 573afdd349d7e4913d7dbc60f0b9d3edd33b39ca | [
"MIT"
] | null | null | null | ppm_image.cpp | gulesh/pixmap-ops | 573afdd349d7e4913d7dbc60f0b9d3edd33b39ca | [
"MIT"
] | null | null | null | ppm_image.cpp | gulesh/pixmap-ops | 573afdd349d7e4913d7dbc60f0b9d3edd33b39ca | [
"MIT"
] | null | null | null | #include "ppm_image.h"
#include <string>
#include <fstream>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace agl;
using namespace std;
ppm_image::ppm_image()
{
imageWidth = 0;
imageHeight = 0;
pixelArray= nullptr;
}
ppm_image::ppm_image(int w, int h)
{
imageWidth = w;
imageHeight =h;
//clear();
pixelArray = new ppm_pixel*[h];
for (int i =0; i<h ;i++)
{
pixelArray[i] = new ppm_pixel[w];
}
}
ppm_image::ppm_image(const ppm_image& orig)
{
//clear();
imageWidth = orig.imageWidth;
imageHeight = orig.imageHeight;
pixelArray = new ppm_pixel*[imageHeight];
for (int i =0; i<imageHeight ;i++)
{
pixelArray[i] = new ppm_pixel[imageWidth];
}
for (int j = 0; j < imageHeight; j++) //rows
{
for (int k = 0; k < imageWidth; k++) //columns
{
pixelArray[j][k]= orig.pixelArray[j][k];
}
}
}
ppm_image& ppm_image::operator=(const ppm_image& orig)
{
if (&orig == this) // protect against self-assignment
{
return *this;
}
//clear();
imageHeight = orig.imageHeight;
imageWidth = orig.imageWidth;
pixelArray = new ppm_pixel*[imageHeight];
for (int i =0; i<imageHeight ;i++)
{
pixelArray[i] = new ppm_pixel[imageWidth];
}
for (int j = 0; j < imageHeight; j++) //rows
{
for (int k = 0; k < imageWidth; k++) //columns
{
pixelArray[j][k]= orig.pixelArray[j][k];
}
}
return *this;
}
void ppm_image::clear()
{
//pixelArray = nullptr;
}
ppm_image::~ppm_image()
{
for (int i = 0; i < imageHeight; i++)
{
delete[] pixelArray[i];
}
delete[] pixelArray;
}
bool ppm_image::load(const std::string& filename)
{
ifstream file(filename);
cout<<"filename " << filename <<endl;
string p3;
int value;
if (!file) // true if the file is valid
{
cout << "Cannot load file: " << filename << endl;
return 1;
}
file >> p3; //this will store "P3"
file >> value; //width
imageWidth = value;
file >> value; //height
imageHeight = value;
file >> value; //this will give the number 255
//memory cleaning
//clear();
pixelArray = new ppm_pixel*[imageHeight];
for (int i =0; i<imageHeight ;i++)
{
pixelArray[i] = new ppm_pixel[imageWidth];
}
while(file)
{
for (int j = 0; j < imageHeight; j++) //rows
{
for (int k = 0; k < imageWidth; k++) //columns
{
ppm_pixel tempPixel;
int pixel;
//r value of the pixel
file >> pixel ;
tempPixel.r = (unsigned char) pixel;
//g value of the pixel
file >> pixel ;
tempPixel.g = (unsigned char) pixel;
//b value of the pixel
file >> pixel ;
tempPixel.b = (unsigned char) pixel;
//pixel with r,g,b valus stored in the 2D array
pixelArray[j][k]= tempPixel;
}
}
return 0;
}
return 0;
}
bool ppm_image::save(const std::string& filename) const
{
ofstream file(filename);
if(!file)
{
return 1;
}
string p3 = "P3";
file << p3 << endl; //this will store "P3"
file << imageWidth << endl; //width
file << imageHeight << endl; //height
int value = 255;
file << value << endl;//this will give the number 255
for (int j = 0; j < imageHeight; j++) //rows
{
for (int k = 0; k < imageWidth; k++) //columns
{
ppm_pixel tempPixel;
tempPixel = pixelArray[j][k];
//r value of the pixel stored in the file
file << (int) tempPixel.r <<endl;
//cout << (int) tempPixel.r <<endl;
//g value of the pixel stored in the file
file << (int) tempPixel.g << endl;
//cout << (int) tempPixel.g <<endl;
//b value of the pixel stored in the file
file << (int) tempPixel.b << endl;
//cout << (int) tempPixel.b <<endl;
}
}
file.close();
return 0;
}
ppm_image ppm_image::resize(int w, int h) const
{
int oldPixelC, oldPixelR;
ppm_image result = ppm_image( w, h);
for (int i = 0 ; i < h; i++)
{
for (int j = 0; j < w ;j++)
{
oldPixelR = floor( (i * (imageHeight - 1))/(h-1) );
oldPixelC = floor( (j * (imageWidth - 1))/(w-1) );
result.pixelArray[i][j].r = pixelArray[oldPixelR][oldPixelC].r;
result.pixelArray[i][j].g = pixelArray[oldPixelR][oldPixelC].g;
result.pixelArray[i][j].b = pixelArray[oldPixelR][oldPixelC].b;
}
}
return result;
}
//got a unique image
// ppm_image ppm_image::flip_horizontal() const
// {
// ppm_image result = ppm_image(imageWidth,imageHeight);
// for (int i = 0 ; i <imageHeight; i++)
// {
// for (int j = 0 ; j < imageWidth ;j++)
// {
// result.pixelArray[i][j]= pixelArray[imageHeight - j - 1][j];
// }
// }
// return result;
// }
ppm_image ppm_image::flip_horizontal() const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i <imageHeight; i++)
{
for (int j = 0 ; j < imageWidth ;j++)
{
result.pixelArray[i][j]= pixelArray[imageHeight - i - 1][j];
}
}
return result;
}
ppm_image ppm_image::subimage(int startx, int starty, int w, int h) const
{
ppm_image result = ppm_image(w,h);
for (int i = 0 ; i < h; i++)
{
for (int j = 0; j < w ;j++)
{
result.pixelArray[i][j].r = pixelArray[i+startx][j+starty].r;
result.pixelArray[i][j].g = pixelArray[i+startx][j+starty].g;
result.pixelArray[i][j].b = pixelArray[i+startx][j+starty].b;
}
}
return result;
}
void ppm_image::replace(const ppm_image& image, int startx, int starty)
{
for (int i = 0 ; i < image.imageHeight; i++)
{
for (int j = 0; j < image.imageWidth ;j++)
{
pixelArray[i+starty][j+startx] = image.pixelArray[i][j];
}
}
}
ppm_image ppm_image::alpha_blend(const ppm_image& other, float alpha) const
{
int blendedR, blendedG, blendedB;
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
blendedR = (int) ( ((float) (pixelArray[i][j].r )) * (1 - alpha) + ((float) ( other.pixelArray[i][j].r)) * alpha ) ;
blendedG = (int) ( ((float) (pixelArray[i][j].g )) * (1 - alpha) + ((float) ( other.pixelArray[i][j].g)) * alpha ) ;
blendedB = (int) ( ((float) (pixelArray[i][j].b )) * (1 - alpha) + ((float) ( other.pixelArray[i][j].b)) * alpha ) ;
//setting new pixel color
result.pixelArray[i][j].r = (unsigned char) blendedR;
result.pixelArray[i][j].g = (unsigned char) blendedG;
result.pixelArray[i][j].b = (unsigned char) blendedB;
}
}
return result;
}
ppm_image ppm_image::gammaCorrect(float gamma) const
{
int gCorrectedR, gCorrectedG, gCorrectedB;
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
gCorrectedR = 255 * pow(((float) pixelArray[i][j].r)/255, 1/gamma);
gCorrectedG = 255 * pow(((float) pixelArray[i][j].g)/255, 1/gamma);
gCorrectedB = 255 * pow(((float) pixelArray[i][j].b)/255, 1/gamma);
//setting new pixel color
result.pixelArray[i][j].r = (unsigned char) gCorrectedR;
result.pixelArray[i][j].g = (unsigned char) gCorrectedG;
result.pixelArray[i][j].b = (unsigned char) gCorrectedB;
}
}
return result;
}
ppm_image ppm_image::grayscale() const
{
int r,g,b,weightedAvg;
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0 ; j < imageWidth ;j++)
{
ppm_pixel modifyingPixel = pixelArray[i][j];
r = modifyingPixel.r;
g = modifyingPixel.g;
b = modifyingPixel.b;
weightedAvg = 0.3 * r + 0.59 * g + 0.11 * b;
modifyingPixel.b = weightedAvg;
modifyingPixel.g = weightedAvg;
modifyingPixel.r = weightedAvg;
result.pixelArray[i][j] = modifyingPixel;
}
}
return result;
}
ppm_pixel ppm_image::get(int row, int col) const
{
return pixelArray[row][col];
}
void ppm_image::set(int row, int col, const ppm_pixel& c)
{
pixelArray[row][col].r = c.r;
pixelArray[row][col].g = c.g;
pixelArray[row][col].b = c.b;
}
int ppm_image::height() const
{
return imageHeight;
}
int ppm_image::width() const
{
return imageWidth;
}
ppm_image ppm_image::swirlColors() const
{
ppm_pixel tempPixel;
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j] = pixelArray[i][j];
tempPixel.r = result.pixelArray[i][j].r ;
result.pixelArray[i][j].r = result.pixelArray[i][j].g;
result.pixelArray[i][j].g = result.pixelArray[i][j].b;
result.pixelArray[i][j].b = tempPixel.r;
}
}
return result;
}
ppm_image ppm_image::distortImage() const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
int distorted_j = (j + (int) (20*sin(i/10)) + imageWidth) % imageWidth;
int distorted_i = (i + (int) (20*cos(j/10)) + imageHeight) % imageHeight;
result.pixelArray[i][j] = pixelArray[distorted_i][distorted_j];
}
}
return result;
}
ppm_image ppm_image::invertColor() const
{
int modifiedR, modifiedG, modifiedB;
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
modifiedR = 255 - (int) pixelArray[i][j].r ;
modifiedG = 255 - (int) pixelArray[i][j].g ;
modifiedB = 255 - (int) pixelArray[i][j].b ;
//setting new pixel color
result.pixelArray[i][j].r = (unsigned char) modifiedR;
result.pixelArray[i][j].g = (unsigned char) modifiedG;
result.pixelArray[i][j].b = (unsigned char) modifiedB;
}
}
return result;
}
ppm_image ppm_image::rotate90() const
{
int oldPixelC = 0;
ppm_image result = ppm_image(imageHeight,imageWidth);
for (int i = 0 ; i < imageWidth; i++)
{
int oldPixelR = imageHeight -1;
for (int j = 0; j < imageHeight ;j++)
{
result.pixelArray[i][j] = pixelArray[oldPixelR][oldPixelC];
oldPixelR -= 1;
}
oldPixelC += 1;
}
return result;
}
ppm_image ppm_image::lightest(const ppm_image& other) const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = std::max(pixelArray[i][j].r, other.pixelArray[i][j].r);
result.pixelArray[i][j].g = std::max(pixelArray[i][j].g, other.pixelArray[i][j].g);
result.pixelArray[i][j].b = std::max(pixelArray[i][j].b, other.pixelArray[i][j].b);
}
}
return result;
}
ppm_image ppm_image::darkest(const ppm_image& other) const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = std::min(pixelArray[i][j].r, other.pixelArray[i][j].r);
result.pixelArray[i][j].g = std::min(pixelArray[i][j].g, other.pixelArray[i][j].g);
result.pixelArray[i][j].b = std::min(pixelArray[i][j].b, other.pixelArray[i][j].b);
}
}
return result;
}
ppm_image ppm_image::difference(const ppm_image& other) const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = std::min(0, pixelArray[i][j].r - other.pixelArray[i][j].r);
result.pixelArray[i][j].r = std::min(0, pixelArray[i][j].r - other.pixelArray[i][j].r);
result.pixelArray[i][j].r = std::min(0, pixelArray[i][j].r - other.pixelArray[i][j].r);
}
}
return result;
}
ppm_image ppm_image::multiply(const ppm_image& other) const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = std::max(255, pixelArray[i][j].r * other.pixelArray[i][j].r);
result.pixelArray[i][j].r = std::max(255, pixelArray[i][j].g * other.pixelArray[i][j].g);
result.pixelArray[i][j].r = std::max(255, pixelArray[i][j].b * other.pixelArray[i][j].b);
}
}
return result;
}
ppm_image ppm_image::redOnly(const ppm_image& other) const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = std::max(pixelArray[i][j].r, other.pixelArray[i][j].r);
}
}
return result;
}
//not working as expected need to edit
ppm_image ppm_image::addBorder() const
{
int resultImageH = imageHeight+2;
int resultImageW = imageWidth+2 ;
ppm_pixel p{(unsigned char)255,(unsigned char) 255,(unsigned char) 255};
ppm_image result = ppm_image(resultImageW,resultImageH);
for (int i = 0 ; i < resultImageH; i++)
{
if(i == 0 || i == resultImageH -1)
{
for (int j = 0; j < resultImageW ;j++)
{
result.pixelArray[i][j] = p;
}
}
else
{
for (int j = 0; j < resultImageW ;j++)
{
if((j == 0) || (j == resultImageW-1))
{
result.pixelArray[i][j] = p;
}
else
{
result.pixelArray[i][j] = pixelArray[i+1][j+1];
}
}
}
}
return result;
}
ppm_image ppm_image::redExtract() const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = pixelArray[i][j].r;
result.pixelArray[i][j].g = 0;
result.pixelArray[i][j].b = 0;
}
}
return result;
}
ppm_image ppm_image::greenExtract() const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r =
result.pixelArray[i][j].g = pixelArray[i][j].g;
result.pixelArray[i][j].b = 0;
}
}
return result;
}
ppm_image ppm_image::blueExtract() const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = 0;
result.pixelArray[i][j].g = 0;
result.pixelArray[i][j].b = pixelArray[i][j].b;
}
}
return result;
}
| 26.835377 | 125 | 0.559812 |
f96f63c2c2a06f5743891f2fd243ece7b1615cb4 | 608 | cpp | C++ | server/src/extension_queue/queue.cpp | valmat/queueServer | 6626e99cd4fccca6f2ae17b8cc33ef151b651b5d | [
"BSD-3-Clause"
] | 4 | 2017-09-25T12:23:22.000Z | 2019-02-19T14:15:46.000Z | server/src/extension_queue/queue.cpp | valmat/queueServer | 6626e99cd4fccca6f2ae17b8cc33ef151b651b5d | [
"BSD-3-Clause"
] | 1 | 2019-02-25T17:53:32.000Z | 2019-02-27T06:57:35.000Z | server/src/extension_queue/queue.cpp | valmat/queueServer | 6626e99cd4fccca6f2ae17b8cc33ef151b651b5d | [
"BSD-3-Clause"
] | 1 | 2019-02-19T13:42:29.000Z | 2019-02-19T13:42:29.000Z | /**
* RocksServer plugin
* https://github.com/valmat/queueServer
*/
#include "../include.h"
#include "RequestMoveFirstPref.h"
#include "RequestFirstPref.h"
#include "RequestGetIncr.h"
using namespace RocksServer;
/*
* Create plugin
*
* @param extension object of Extension
* @param rdb wrapped object of RocksDB
*/
PLUGIN(Extension extension, RocksDBWrapper& rdb)
{
extension
.bind("/get-incr", new RequestGetIncr(rdb))
.bind("/first-pref", new RequestFirstPref(rdb))
.bind("/move-fpref", new RequestMoveFirstPref(rdb));
;
} | 20.266667 | 65 | 0.641447 |
f9711d8fdecf29560f186cbd4c4f86ee0342ff38 | 3,739 | cpp | C++ | Core-src/AnalyzeWindow.cpp | HaikuArchives/BeAE | b57860a81266dd465655ec98b7524406bfde27aa | [
"BSD-3-Clause"
] | 6 | 2015-03-04T19:41:12.000Z | 2022-03-27T09:44:25.000Z | Core-src/AnalyzeWindow.cpp | HaikuArchives/BeAE | b57860a81266dd465655ec98b7524406bfde27aa | [
"BSD-3-Clause"
] | 20 | 2015-03-03T21:02:20.000Z | 2021-08-02T13:26:59.000Z | Core-src/AnalyzeWindow.cpp | HaikuArchives/BeAE | b57860a81266dd465655ec98b7524406bfde27aa | [
"BSD-3-Clause"
] | 8 | 2015-02-23T19:10:32.000Z | 2020-10-26T08:03:00.000Z | /*
Copyright (c) 2003, Xentronix
Author: Frans van Nispen (frans@xentronix.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer. Redistributions in binary form must
reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of Xentronix nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Window.h>
#include <View.h>
#include <InterfaceKit.h>
#include <stdlib.h>
#include <stdio.h>
#include "Globals.h"
#include "AnalyzeWindow.h"
#include "main.h"
#define UPDATE 'updt'
#define QUIT 'quit'
#define SET 'setF'
/*******************************************************
*
*******************************************************/
AnalyzeWindow::AnalyzeWindow(BRect r, const char *name)
: BWindow(r,name, B_FLOATING_WINDOW_LOOK,B_FLOATING_APP_WINDOW_FEEL, B_NOT_ZOOMABLE | B_AVOID_FOCUS)
{
// 25 frames per second by default
m_frames = 25;
m_count = 0;
// set the playHook
m_index = Pool.SetPlayHook( _PlayBuffer, PLAY_HOOKS/2, (void*)this);
SetPulseRate(50000);
Run();
Show();
}
/*******************************************************
*
*******************************************************/
void AnalyzeWindow::PlayBuffer(float *buffer, size_t size)
{
}
/*******************************************************
*
*******************************************************/
void AnalyzeWindow::_PlayBuffer(float *buffer, size_t size, void *cookie)
{
AnalyzeWindow *win = (AnalyzeWindow*)cookie; // cast to our own clas
// process effect
win->PlayBuffer(buffer, size);
// update with frames/second
win->m_count -= size;
if (win->m_count <0){
win->m_count = (int)Pool.system_frequency*2/win->m_frames;
win->PostMessage(UPDATE);
}
}
/*******************************************************
*
*******************************************************/
int32 AnalyzeWindow::FramesPerSecond()
{
return m_frames;
}
void AnalyzeWindow::SetFramesPerSecond(int32 frames)
{
m_frames = frames;
}
/*******************************************************
*
*******************************************************/
bool AnalyzeWindow::QuitRequested(){
Pool.RemovePlayHook( _PlayBuffer, m_index );
return true;
}
/*******************************************************
*
*******************************************************/
void AnalyzeWindow::MessageReceived(BMessage* msg){
BView *view;
switch(msg->what){
case UPDATE:
view = ChildAt(0);
if (view) view->Invalidate();
break;
default:
BWindow::MessageReceived(msg);
}
}
| 30.647541 | 101 | 0.61487 |
f972af1ee36532247bf190e9808e6e5d4a624d8e | 708 | hpp | C++ | include/RadonFramework/IO/ConsoleUI/With.hpp | tak2004/RF_Console | b2a1114b4e948281c64b085eb407926704ecc7cb | [
"Apache-2.0"
] | null | null | null | include/RadonFramework/IO/ConsoleUI/With.hpp | tak2004/RF_Console | b2a1114b4e948281c64b085eb407926704ecc7cb | [
"Apache-2.0"
] | null | null | null | include/RadonFramework/IO/ConsoleUI/With.hpp | tak2004/RF_Console | b2a1114b4e948281c64b085eb407926704ecc7cb | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <RadonFramework/IO/ConsoleUI/Component.hpp>
#include <RadonFramework/IO/ConsoleUI/ComponentOperator.hpp>
#include <RadonFramework/IO/ConsoleUI/State.hpp>
namespace RadonFramework::IO::ConsoleUI
{
template <class T>
struct With : public ComponentOperator
{
template <int N>
With(char const (&CString)[N], T&& Value)
: m_Temporary(Value), m_State(RF_HASH(CString))
{
}
void operator()(Component& Receiver) override
{
void* result;
if(Receiver.States().Get(m_State, result))
{
(*reinterpret_cast<State<T>*>(result)) = m_Temporary;
}
}
const T m_Temporary;
const RF_Type::UInt64 m_State;
};
}
namespace RF_CUI = RadonFramework::IO::ConsoleUI; | 21.454545 | 60 | 0.710452 |
f976e1c6bc0d2cac86d70e577b4df9a1003f5863 | 4,967 | cc | C++ | pmem-mariadb/storage/tokudb/PerconaFT/src/tests/test_cursor_delete2.cc | wc222/pmdk-examples | 64aadc3a70471c469ac8e214eb1e04ff47cf18ff | [
"BSD-3-Clause"
] | 11 | 2017-10-28T08:41:08.000Z | 2021-06-24T07:24:21.000Z | pmem-mariadb/storage/tokudb/PerconaFT/src/tests/test_cursor_delete2.cc | WSCWDA/pmdk-examples | c3d079e52cd18b0e14836ef42bad9a995336bf90 | [
"BSD-3-Clause"
] | 1 | 2021-02-24T05:26:44.000Z | 2021-02-24T05:26:44.000Z | pmem-mariadb/storage/tokudb/PerconaFT/src/tests/test_cursor_delete2.cc | isabella232/pmdk-examples | be7a5a18ba7bb8931e512f6d552eadf820fa2235 | [
"BSD-3-Clause"
] | 4 | 2017-09-07T09:33:26.000Z | 2021-02-19T07:45:08.000Z | /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*======
This file is part of PerconaFT.
Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved.
PerconaFT is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2,
as published by the Free Software Foundation.
PerconaFT 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 PerconaFT. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------
PerconaFT is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License, version 3,
as published by the Free Software Foundation.
PerconaFT 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with PerconaFT. If not, see <http://www.gnu.org/licenses/>.
======= */
#ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved."
#include "test.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <memory.h>
#include <errno.h>
#include <sys/stat.h>
#include <db.h>
static DB_ENV *dbenv;
static DB *db;
static DB_TXN * txn;
static void
test_cursor_delete2 (void) {
int r;
DBT key,val;
r = db_env_create(&dbenv, 0); CKERR(r);
r = dbenv->open(dbenv, TOKU_TEST_FILENAME, DB_PRIVATE|DB_INIT_MPOOL|DB_CREATE|DB_INIT_TXN, 0); CKERR(r);
r = db_create(&db, dbenv, 0); CKERR(r);
r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r);
r = db->open(db, txn, "primary.db", NULL, DB_BTREE, DB_CREATE, 0600); CKERR(r);
r = txn->commit(txn, 0); CKERR(r);
r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r);
r = db->put(db, txn, dbt_init(&key, "a", 2), dbt_init(&val, "b", 2), 0); CKERR(r);
r = txn->commit(txn, 0); CKERR(r);
r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r);
r = db->del(db, txn, dbt_init(&key, "a", 2), 0); CKERR(r);
r = txn->commit(txn, 0); CKERR(r);
r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r);
r = db->del(db, txn, dbt_init(&key, "a", 2), DB_DELETE_ANY); CKERR(r);
r = txn->commit(txn, 0); CKERR(r);
r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r);
r = db->put(db, txn, dbt_init(&key, "a", 2), dbt_init(&val, "c", 2), 0); CKERR(r);
r = db->del(db, txn, dbt_init(&key, "a", 2), 0); CKERR(r);
r = txn->commit(txn, 0); CKERR(r);
r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r);
r = db->put(db, txn, dbt_init(&key, "a", 2), dbt_init(&val, "c", 2), 0); CKERR(r);
r = txn->commit(txn, 0); CKERR(r);
r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r);
r = db->del(db, txn, dbt_init(&key, "a", 2), 0); CKERR(r);
r = db->del(db, txn, dbt_init(&key, "a", 2), DB_DELETE_ANY); CKERR(r);
r = txn->commit(txn, 0); CKERR(r);
r = db->close(db, 0); CKERR(r);
r = dbenv->close(dbenv, 0); CKERR(r);
}
int
test_main(int argc, char *const argv[]) {
parse_args(argc, argv);
toku_os_recursive_delete(TOKU_TEST_FILENAME);
toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO);
test_cursor_delete2();
return 0;
}
| 45.154545 | 114 | 0.476545 |
f97a4336ab04e9446d773096c45ca5d954126da6 | 1,205 | cpp | C++ | Challenge-2021-04/08_letter_combinations_of_a_phone_number.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-04/08_letter_combinations_of_a_phone_number.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-04/08_letter_combinations_of_a_phone_number.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | #include "../header.h"
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.length() == 0) {
return {};
}
unordered_map<char, string> m;
m['2'] = "abc";
m['3'] = "def";
m['4'] = "ghi";
m['5'] = "jkl";
m['6'] = "mno";
m['7'] = "pqrs";
m['8'] = "tuv";
m['9'] = "wxyz";
vector<string> res;
int d_index = 0;
string current = "";
helper(digits, m, res, current, d_index);
return res;
}
private:
void helper(const string& digits, unordered_map<char, string>& m, vector<string>& res, string current, int d_index) {
if (current.length() == digits.length()) {
res.push_back(current);
return;
}
string candidate = m[digits[d_index]];
for (int i = 0; i < candidate.size(); ++i) {
current.push_back(candidate[i]);
helper(digits, m, res, current, d_index+1);
current.pop_back();
}
}
};
int main() {
string digits;
cin >> digits;
vector<string> res = Solution().letterCombinations(digits);
for (auto r: res) {
cout << r << endl;
}
return 0;
} | 25.104167 | 121 | 0.509544 |
f97d1a9270894f9dc0a87e4b98415bcd3e15cd13 | 2,071 | hpp | C++ | Libs/SceneGraph/PlantNode.hpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | Libs/SceneGraph/PlantNode.hpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | Libs/SceneGraph/PlantNode.hpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
#ifndef CAFU_TREE_NODE_HPP_INCLUDED
#define CAFU_TREE_NODE_HPP_INCLUDED
#include "Node.hpp"
#include "Plants/Tree.hpp"
struct PlantDescriptionT;
class PlantDescrManT;
namespace cf
{
namespace SceneGraph
{
class PlantNodeT : public GenericNodeT
{
public:
/// The constructor.
PlantNodeT();
/// Constructor for creating a PlantNodeT from parameters.
PlantNodeT(const PlantDescriptionT* PlantDescription, unsigned long RandomSeed, const Vector3dT& Position, const Vector3fT& Angles);
/// Named constructor.
static PlantNodeT* CreateFromFile_cw(std::istream& InFile, aux::PoolT& Pool, LightMapManT& LMM, SHLMapManT& SMM, PlantDescrManT& PDM);
/// The destructor.
~PlantNodeT();
// The NodeT interface.
void WriteTo(std::ostream& OutFile, aux::PoolT& Pool) const;
const BoundingBox3T<double>& GetBoundingBox() const;
// void InitDrawing();
bool IsOpaque() const { return false; };
void DrawAmbientContrib(const Vector3dT& ViewerPos) const;
//void DrawStencilShadowVolumes(const Vector3dT& LightPos, const float LightRadius) const;
//void DrawLightSourceContrib(const Vector3dT& ViewerPos, const Vector3dT& LightPos) const;
void DrawTranslucentContrib(const Vector3dT& ViewerPos) const;
private:
PlantNodeT(const PlantNodeT&); ///< Use of the Copy Constructor is not allowed.
void operator = (const PlantNodeT&); ///< Use of the Assignment Operator is not allowed.
TreeT m_Tree;
unsigned long m_RandomSeed;
Vector3dT m_Position;
Vector3fT m_Angles;
std::string m_DescrFileName;
BoundingBox3dT m_Bounds;
};
}
}
#endif
| 30.455882 | 146 | 0.633028 |
f97f1b80cd830250828379c88056dfae3aa0c8f6 | 3,247 | hpp | C++ | modules/engine/include/randar/Render/Geometry.hpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | 1 | 2016-11-12T02:43:29.000Z | 2016-11-12T02:43:29.000Z | modules/engine/include/randar/Render/Geometry.hpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | null | null | null | modules/engine/include/randar/Render/Geometry.hpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | null | null | null | #ifndef RANDAR_RENDER_GEOMETRY_HPP
#define RANDAR_RENDER_GEOMETRY_HPP
#include <randar/Render/Primitive.hpp>
#include <randar/Render/ShaderProgram.hpp>
#include <randar/Render/VertexBuffer.hpp>
namespace randar
{
class Geometry : public GraphicsContextResource
{
public:
VertexBuffer vertices;
IndexBuffer indices;
/**
* Primitive used by the geometry.
*
* Describes how vertices should be interpreted.
*/
Primitive primitive = randar::Primitive::Triangle;
/**
* Constructors.
*/
Geometry();
Geometry(GraphicsContext& context);
/**
* Assignment.
*/
Geometry(const Geometry& other);
Geometry& operator =(const Geometry& other);
Geometry copy();
/**
* Destructor.
*/
~Geometry();
/**
* Identifies the Randar object type.
*/
std::string kind() const;
/**
* Initializes the geometry on a context.
*/
using GraphicsContextResource::initialize;
virtual void initialize() override;
/**
* Uninitializes the geometry from a context.
*
* Nothing happens if the geometry is not initialized. No exceptions are
* thrown upon failure.
*/
virtual void uninitialize() override;
/**
* Whether the geometry is initialized on a context.
*/
bool isInitialized();
/**
* Syncs local data to OpenGL.
*/
void sync();
/**
* Clears vertices and indices of the geometry.
*
* Primitive remains unchanged.
*/
void clear();
/**
* Adds a vertex to the geometry's available vertices.
*
* Returns an index that identifies the vertex in this geometry's
* available vertices, which is later used to construct a shape.
*
* If the vertex already exists in the available geometry, it is not
* appended and the existing index is returned.
*
* This does not manipulate the shape of the geometry.
*
* In most cases, you can use the simplified append method instead.
*/
uint32_t useVertex(const Vertex& vertex);
/**
* Appends a vertex to the geometry shape.
*
* This method simply calls appendVertex, captures the index of the
* vertex in this geometry's available vertices, and calls appendIndex
* with it.
*
* This is the preferred way to append a vertex to geometry.
*/
void append(const Vertex& vertex);
/**
* Appends another geometry to this geometry.
*/
void append(Geometry& other);
void append(Geometry& other, const Transform& transform);
/**
* Saves and loads the geometry from disk.
*/
void save(const randar::Path& filepath);
void load(const randar::Path& filepath);
};
/**
* Node.js helper.
*/
#ifdef SWIG
%newobject geometry;
#endif
Geometry* geometry();
}
#endif
| 25.769841 | 80 | 0.558978 |
f97f4fbe581321f5293e8955e8f7d600fd259aba | 13,240 | cpp | C++ | dependencies/HDRTools/common/src/DisplayGammaAdjustHLG.cpp | rudals0215/AR-streaming-with-MPEG-DASH | 7c9f24a2eed7f756e51451670286a11351a6b877 | [
"MIT"
] | null | null | null | dependencies/HDRTools/common/src/DisplayGammaAdjustHLG.cpp | rudals0215/AR-streaming-with-MPEG-DASH | 7c9f24a2eed7f756e51451670286a11351a6b877 | [
"MIT"
] | null | null | null | dependencies/HDRTools/common/src/DisplayGammaAdjustHLG.cpp | rudals0215/AR-streaming-with-MPEG-DASH | 7c9f24a2eed7f756e51451670286a11351a6b877 | [
"MIT"
] | 1 | 2021-07-07T00:53:49.000Z | 2021-07-07T00:53:49.000Z | /* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* <OWNER> = British Broadcasting Corporation (BBC).
* <ORGANIZATION> = BBC.
* <YEAR> = 2015
*
* Copyright (c) 2015, BBC.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the <ORGANIZATION> nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
*************************************************************************************
* \file DisplayGammaAdjustHLG.cpp
*
* \brief
* DisplayGammaAdjustHLG class
* This is an implementation of the display gamma normalization process
* in BBC's Hybrid Log-Gamma system (HLG).
* A complete documentation of this process is available in
* the BBC's response to the MPEG call for evidence on HDR and WCG video coding
* (document m36249, available at:
* http://wg11.sc29.org/doc_end_user/documents/112_Warsaw/wg11/m36249-v2-m36249.zip)
*
* \author
* - Matteo Naccari <matteo.naccari@bbc.co.uk>
* - Manish Pindoria <manish.pindoria@bbc.co.uk>
*
*************************************************************************************
*/
#include "Global.H"
#include "DisplayGammaAdjustHLG.H"
#include "ColorTransformGeneric.H"
namespace hdrtoolslib {
//-----------------------------------------------------------------------------
// Constructor / destructor implementation
//-----------------------------------------------------------------------------
DisplayGammaAdjustHLG::DisplayGammaAdjustHLG(double gamma, double scale)
{
m_tfScale = 12.0; //19.6829249; // transfer function scaling - assuming super whites
m_linScale = scale;
m_gamma = gamma;
m_transformY = NULL;
}
DisplayGammaAdjustHLG::~DisplayGammaAdjustHLG()
{
m_transformY = NULL;
}
void DisplayGammaAdjustHLG::setup(Frame *frame) {
ColorTransformGeneric::setYConversion(frame->m_colorPrimaries, (const double **) &m_transformY);
}
void DisplayGammaAdjustHLG::forward(double &comp0, double &comp1, double &comp2)
{
double vComp0, vComp1, vComp2;
//vComp0 = comp0 / m_tfScale;
//vComp1 = comp1 / m_tfScale;
//vComp2 = comp2 / m_tfScale;
vComp0 = comp0;
vComp1 = comp1;
vComp2 = comp2;
double ySignal = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2);
double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal;
comp0 = (float) (vComp0 * yDisplay) ;
comp1 = (float) (vComp1 * yDisplay) ;
comp2 = (float) (vComp2 * yDisplay) ;
}
void DisplayGammaAdjustHLG::forward(const double iComp0, const double iComp1, const double iComp2, double *oComp0, double *oComp1, double *oComp2)
{
double vComp0, vComp1, vComp2;
//vComp0 = iComp0 / m_tfScale;
//vComp1 = iComp1 / m_tfScale;
//vComp2 = iComp2 / m_tfScale;
vComp0 = iComp0;
vComp1 = iComp1;
vComp2 = iComp2;
double ySignal = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2);
double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal;
*oComp0 = (float) (vComp0 * yDisplay) ;
*oComp1 = (float) (vComp1 * yDisplay) ;
*oComp2 = (float) (vComp2 * yDisplay) ;
}
void DisplayGammaAdjustHLG::inverse(double &comp0, double &comp1, double &comp2)
{
// 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light
// 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68)
// 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white)
// Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class.
double vComp0, vComp1, vComp2;
vComp0 = dMax(0.0, (double) comp0 / m_linScale);
vComp1 = dMax(0.0, (double) comp1 / m_linScale);
vComp2 = dMax(0.0, (double) comp2 / m_linScale);
double yDisplay = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2);
//double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma);
double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma);
comp0 = (float) (vComp0 * yDisplayGamma) ;
comp1 = (float) (vComp1 * yDisplayGamma) ;
comp2 = (float) (vComp2 * yDisplayGamma) ;
}
void DisplayGammaAdjustHLG::inverse(const double iComp0, const double iComp1, const double iComp2, double *oComp0, double *oComp1, double *oComp2)
{
// 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light
// 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68)
// 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white)
// Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class.
double vComp0, vComp1, vComp2;
vComp0 = dMax(0.0, (double) iComp0 / m_linScale);
vComp1 = dMax(0.0, (double) iComp1 / m_linScale);
vComp2 = dMax(0.0, (double) iComp2 / m_linScale);
double yDisplay = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2);
//double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma);
double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma);
*oComp0 = (float) (vComp0 * yDisplayGamma) ;
*oComp1 = (float) (vComp1 * yDisplayGamma) ;
*oComp2 = (float) (vComp2 * yDisplayGamma) ;
}
void DisplayGammaAdjustHLG::forward(Frame *frame)
{
if (frame->m_isFloat == TRUE && frame->m_compSize[Y_COMP] == frame->m_compSize[Cb_COMP]) {
if (frame->m_colorSpace == CM_RGB) {
double vComp[3];
const double *transformY = NULL;
ColorTransformGeneric::setYConversion(frame->m_colorPrimaries, &transformY);
for (int index = 0; index < frame->m_compSize[Y_COMP]; index++) {
for(int component = 0; component < 3; component++) {
//vComp[component] = frame->m_floatComp[component][index] / m_tfScale;
vComp[component] = frame->m_floatComp[component][index];
}
double ySignal = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]);
double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal;
for(int component = 0; component < 3; component++) {
frame->m_floatComp[component][index] = (float) (vComp[component] * yDisplay) ;
}
}
// reset the pointer (just for safety
transformY = NULL;
}
}
}
void DisplayGammaAdjustHLG::forward(Frame *out, const Frame *inp)
{
if (inp->m_isFloat == TRUE && out->m_isFloat == TRUE && inp->m_size == out->m_size && inp->m_compSize[Y_COMP] == inp->m_compSize[Cb_COMP]) {
if (inp->m_colorSpace == CM_RGB && out->m_colorSpace == CM_RGB) {
double vComp[3];
const double *transformY = NULL;
ColorTransformGeneric::setYConversion(inp->m_colorPrimaries, &transformY);
for (int index = 0; index < inp->m_compSize[Y_COMP]; index++) {
for(int component = 0; component < 3; component++) {
//vComp[component] = inp->m_floatComp[component][index] / m_tfScale;
vComp[component] = inp->m_floatComp[component][index];
}
double ySignal = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]);
double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal;
for(int component = 0; component < 3; component++) {
out->m_floatComp[component][index] = (float) (vComp[component] * yDisplay) ;
}
}
// reset the pointer (just for safety
transformY = NULL;
}
else {
out->copy((Frame *) inp);
}
}
else if (inp->m_isFloat == FALSE && out->m_isFloat == FALSE && inp->m_size == out->m_size && inp->m_bitDepth == out->m_bitDepth) {
out->copy((Frame *) inp);
}
}
void DisplayGammaAdjustHLG::inverse(Frame *frame)
{
// 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light
// 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68)
// 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white)
// Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class.
if (frame->m_isFloat == TRUE && frame->m_compSize[Y_COMP] == frame->m_compSize[Cb_COMP]) {
if (frame->m_colorSpace == CM_RGB) {
double vComp[3];
const double *transformY = NULL;
ColorTransformGeneric::setYConversion(frame->m_colorPrimaries, &transformY);
for (int index = 0; index < frame->m_compSize[Y_COMP]; index++) {
for(int component = 0; component < 3; component++) {
vComp[component] = dMax(0.0, (double) frame->m_floatComp[component][index] / m_linScale);
}
double yDisplay = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]);
//double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma);
double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma);
for(int component = 0; component < 3; component++) {
frame->m_floatComp[component][index] = (float) (vComp[component] * yDisplayGamma) ;
}
}
// reset the pointer (just for safety
transformY = NULL;
}
}
}
void DisplayGammaAdjustHLG::inverse(Frame *out, const Frame *inp)
{
// 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light
// 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68)
// 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white)
// Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class.
if (inp->m_isFloat == TRUE && out->m_isFloat == TRUE && inp->m_size == out->m_size && inp->m_compSize[Y_COMP] == inp->m_compSize[Cb_COMP]) {
if (inp->m_colorSpace == CM_RGB && out->m_colorSpace == CM_RGB) {
double vComp[3];
const double *transformY = NULL;
ColorTransformGeneric::setYConversion(inp->m_colorPrimaries, &transformY);
for (int index = 0; index < inp->m_compSize[Y_COMP]; index++) {
for(int component = 0; component < 3; component++) {
vComp[component] = dMax(0.0, (double) inp->m_floatComp[component][index] / m_linScale);
}
double yDisplay = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]);
//double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma);
double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma);
for(int component = 0; component < 3; component++) {
out->m_floatComp[component][index] = (float) (vComp[component] * yDisplayGamma) ;
}
}
// reset the pointer (just for safety
transformY = NULL;
}
}
else if (inp->m_isFloat == FALSE && out->m_isFloat == FALSE && inp->m_size == out->m_size && inp->m_bitDepth == out->m_bitDepth) {
out->copy((Frame *) inp);
}
}
} // namespace hdrtoolslib
//-----------------------------------------------------------------------------
// End of file
//-----------------------------------------------------------------------------
| 43.84106 | 151 | 0.649245 |
f98335835b564975be345d5087b058a382845d32 | 5,545 | cpp | C++ | src/TransitionHandler.cpp | MacaroniDamage/FabulousNeopixelFirmware | 4ebf638f9d053629dd2eb81039cc153755d55668 | [
"MIT"
] | 2 | 2021-06-05T15:26:29.000Z | 2021-06-05T23:50:09.000Z | src/TransitionHandler.cpp | MacaroniDamage/FabulousNeopixelFirmware | 4ebf638f9d053629dd2eb81039cc153755d55668 | [
"MIT"
] | null | null | null | src/TransitionHandler.cpp | MacaroniDamage/FabulousNeopixelFirmware | 4ebf638f9d053629dd2eb81039cc153755d55668 | [
"MIT"
] | null | null | null | /**
* @file TransitionHandler.cpp
* @author MacaroniDamage
* @brief Executes state machine that handel transitions to different
* stages
* @version 0.1
* @date 2020-12-18
*
*
*/
#include "TransitionHandler.h"
/** Configures the instace so that
* it triggers the wished state machine
**/
void TransitionHandler::playTransition(Transition transition, uint32_t targetColor)
{
this->targetColor = targetColor;
this->currentColor = _pController->getCurrentColor();
this->currentBrightness = _pController->getCurrentBrightness();
this->transition = transition;
this->transitionState = STATE_1;
}
//sets the target brightness and gets the current values from the controller
void TransitionHandler::playTransition(uint8_t targetBrightness, Transition transition)
{
this->targetBrightness = targetBrightness;
this->currentColor = _pController->getCurrentColor();
this->currentBrightness = _pController->getCurrentBrightness();
this->transition = transition;
this->transitionState = STATE_1;
}
//Just sets the transition values and gets the current values from the controller
void TransitionHandler::playTransition(Transition transition)
{
this->currentColor = _pController->getCurrentColor();
this->currentBrightness = _pController->getCurrentBrightness();
this->transition = transition;
this->transitionState = STATE_1;
Serial.println("Stage: " + String(transitionState));
}
void TransitionHandler::setTransitionMode(TransitionMode transitionMode)
{
this->transitionMode = transitionMode;
}
TransitionState TransitionHandler::getCurrentTransitionState()
{
return this->transitionState;
}
//Sets the targetBrightness to the minimun value sets the new color
//and set the targetBrigtness to the wished value
void TransitionHandler::Fade()
{
switch (transitionState)
{
case STDBY:
transitionState = STDBY;
break;
case STATE_1: //Fade_Out
//temporaily saves the brightness to set it later.
this->oldBrightness = this->currentBrightness;
//turns the brightness of the stripe to minimal brightness
this->targetBrightness = MIN_BRIGHTNESS;
//changes the state
transitionState = STATE_2;
break;
case STATE_2: //SET COLOR
if (currentBrightness <= targetBrightness)
{
//Tells the Controller what color is now the current one
//and dates the stripe up
transitionState = STATE_3;
//Dates the currentColor and currentBrightness up
this->currentColor = this->targetColor;
this->targetBrightness = this->oldBrightness;
//Executes the changeColor function if transitionMode is in
//a standart state so it won't be executed durig an animation
if (transitionMode == STANDARD)
_pController->changeColor(currentColor);
}
else
{
transitionState = STATE_2;
}
break;
case STATE_3: //Fade IN
if (currentBrightness < targetBrightness)
{
transitionState = STATE_3;
}
else
{
currentColor = targetColor;
transitionState = STDBY;
transitionisPlayed = false;
}
break;
default:
transitionState = STDBY;
}
}
// change to a target brightness
void TransitionHandler::gotoBrightness()
{
int16_t actBrightness = (int16_t)currentBrightness;
if (brightnessUpdateTimer.isTimerReady())
{
if (targetBrightness > currentBrightness)
{
actBrightness += BRIGHTNESS_STEP;
if (actBrightness > targetBrightness)
currentBrightness = targetBrightness;
else
currentBrightness = actBrightness;
}
else if (targetBrightness < currentBrightness)
{
actBrightness -= BRIGHTNESS_STEP;
if (actBrightness < targetBrightness)
currentBrightness = targetBrightness;
else
currentBrightness = (uint8_t)actBrightness;
}
//Refreshes the stripe
_pController->changeBrightness(currentBrightness);
//Refreshed the update timer
brightnessUpdateTimer.startTimer(BRIGHTNESS_UPDATE);
}
}
//Sets the targetBrightnes to the minimum brightness and waits until it is achieved
//set the transition state then to Standby
void TransitionHandler::FadeOut()
{
switch (transitionState)
{
case STATE_1:
this->targetBrightness = MIN_BRIGHTNESS;
this->transitionState = STATE_2;
break;
case STATE_2:
if (currentBrightness <= targetBrightness)
{
this->transitionState = STDBY;
}
break;
}
}
//Waits until the targetBrightness is equal or higher then the currentBrighness
//and the set the TargetHandler to Standby
void TransitionHandler::FadeIn()
{
switch (transitionState)
{
case STATE_1:
//Will be modified so the changeBrightness method
//refreshes the solid color
this->transitionState = STATE_3;
break;
case STATE_3:
if (currentBrightness >= targetBrightness)
{
this->transitionState = STDBY;
}
break;
}
}
uint8_t TransitionHandler::getCurrentBrightness(){
return currentBrightness;
}
uint8_t TransitionHandler::getTargetBrightness(){
return targetBrightness;
}
void TransitionHandler::loop()
{
if (transitionState != STDBY)
{
switch (transition)
{
case FADE_TO:
this->Fade();
this->gotoBrightness();
break;
case FADE_OUT:
this->FadeOut();
this->gotoBrightness();
break;
case FADE_IN:
this->FadeIn();
this->gotoBrightness();
break;
default:
_pController->changeColor(targetColor);
this->transitionState = STDBY;
break;
}
}
}
| 25.911215 | 87 | 0.70532 |
f9847bb79e52b2a28bc39127617f9544416c7709 | 7,076 | cp | C++ | Win32/Sources/Application/SMTP_Queue/CSMTPView.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Win32/Sources/Application/SMTP_Queue/CSMTPView.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Win32/Sources/Application/SMTP_Queue/CSMTPView.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Source for CSMTPView class
#include "CSMTPView.h"
#include "CFontCache.h"
#include "CMailboxWindow.h"
#include "CMbox.h"
#include "CMulberryApp.h"
#include "CMulberryCommon.h"
#include "CPreferences.h"
#include "CSMTPToolbar.h"
#include "CSplitterView.h"
#include "CToolbarView.h"
// Static members
BEGIN_MESSAGE_MAP(CSMTPView, CMailboxView)
ON_WM_CREATE()
ON_WM_DESTROY()
END_MESSAGE_MAP()
// C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S
// Default constructor
CSMTPView::CSMTPView()
{
mSender = NULL;
}
// Default destructor
CSMTPView::~CSMTPView()
{
}
// O T H E R M E T H O D S ____________________________________________________________________________
const int cTitleHeight = 16;
int CSMTPView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMailboxView::OnCreate(lpCreateStruct) == -1)
return -1;
int width = lpCreateStruct->cx;
int height = lpCreateStruct->cy;
UINT focus_indent = Is3Pane() ? 3 : 0;
// Create footer first so we get its scaled height
mFooter.CreateDialogItems(IDD_SMTPFOOTER, &mFocusRing);
mFooter.ModifyStyle(0, WS_CLIPSIBLINGS);
mFooter.ModifyStyleEx(0, WS_EX_DLGMODALFRAME);
CRect rect;
mFooter.GetWindowRect(rect);
mFooter.ExecuteDlgInit(MAKEINTRESOURCE(IDD_SMTPFOOTER));
mFooter.SetFont(CMulberryApp::sAppSmallFont);
mFooter.MoveWindow(CRect(focus_indent, height - focus_indent - rect.Height(), width - focus_indent, height - focus_indent));
mFooter.ShowWindow(SW_SHOW);
// Subclass footer controls for our use
mTotalText.SubclassDlgItem(IDC_SMTPTOTALTXT, &mFooter);
mTotalText.SetFont(CMulberryApp::sAppSmallFont);
// Server table
mSMTPTable.Create(NULL, NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP,
CRect(focus_indent, focus_indent + cTitleHeight, width - focus_indent, height - focus_indent - rect.Height()), &mFocusRing, IDC_MAILBOXTABLE);
mSMTPTable.ModifyStyleEx(0, WS_EX_NOPARENTNOTIFY, 0);
mSMTPTable.ResetFont(CFontCache::GetListFont());
mSMTPTable.SetColumnInfo(mColumnInfo);
mSMTPTable.SetContextMenuID(IDR_POPUP_CONTEXT_MAILBOX);
mSMTPTable.SetContextView(static_cast<CView*>(GetOwningWindow()));
// Get titles
mSMTPTitles.Create(NULL, NULL, WS_CHILD | WS_VISIBLE, CRect(focus_indent, focus_indent, width - focus_indent - 16, focus_indent + cTitleHeight), &mFocusRing, IDC_STATIC);
mSMTPTitles.SetFont(CFontCache::GetListFont());
mFocusRing.AddAlignment(new CWndAlignment(&mSMTPTitles, CWndAlignment::eAlign_TopWidth));
PostCreate(&mSMTPTable, &mSMTPTitles);
// Create alignment details
mFocusRing.AddAlignment(new CWndAlignment(&mFooter, CWndAlignment::eAlign_BottomWidth));
mFocusRing.AddAlignment(new CWndAlignment(&mSMTPTable, CWndAlignment::eAlign_WidthHeight));
// Set status
SetOpen();
return 0;
}
void CSMTPView::OnDestroy(void)
{
// Do standard close behaviour
DoClose();
// Do default action now
CMailboxView::OnDestroy();
}
// Make a toolbar appropriate for this view
void CSMTPView::MakeToolbars(CToolbarView* parent)
{
// Create a suitable toolbar
CSMTPToolbar* tb = new CSMTPToolbar;
mToolbar = tb;
tb->InitToolbar(Is3Pane(), parent);
// Toolbar must listen to view to get activate/deactive broadcast
Add_Listener(tb);
// Now give toolbar to its view as standard buttons
parent->AddToolbar(tb, GetTable(), CToolbarView::eStdButtonsGroup);
}
// Set window state
void CSMTPView::ResetState(bool force)
{
if (!GetMbox())
return;
// Get name as cstr
CString name(GetMbox()->GetAccountName());
// Get visible state
bool visible = GetParentFrame()->IsWindowVisible();
// Get default state
CMailboxWindowState* state = &CPreferences::sPrefs->mSMTPWindowDefault.Value();
// Do not set if empty
CRect set_rect = state->GetBestRect(CPreferences::sPrefs->mSMTPWindowDefault.GetValue());
if (!set_rect.IsRectNull())
{
// Clip to screen
::RectOnScreen(set_rect, NULL);
// Reset bounds
GetParentFrame()->SetWindowPos(nil, set_rect.left, set_rect.top, set_rect.Width(), set_rect.Height(), SWP_NOACTIVATE | SWP_NOZORDER | (visible ? 0 : SWP_NOREDRAW));
}
// Prevent window updating while column info is invalid
bool locked = GetParentFrame()->LockWindowUpdate();
// Adjust size of tables
ResetColumns(state->GetBestColumnInfo(CPreferences::sPrefs->mServerWindowDefault.GetValue()));
// Adjust menus
SetSortBy(state->GetSortBy());
GetMbox()->ShowBy(state->GetShowBy());
// Sorting button
//mSortBtn.SetPushed(state->GetShowBy() == cShowMessageDescending);
if (force)
SaveDefaultState();
if (locked)
GetParentFrame()->UnlockWindowUpdate();
// Do zoom
if (state->GetState() == eWindowStateMax)
GetParentFrame()->ShowWindow(SW_SHOWMAXIMIZED);
// Init the preview state once if we're in a window
if (!Is3Pane() && !mPreviewInit)
{
mMessageView->ResetState();
mPreviewInit = true;
}
// Init splitter pos
if (!Is3Pane() && (state->GetSplitterSize() != 0))
GetMailboxWindow()->GetSplitter()->SetRelativeSplitPos(state->GetSplitterSize());
if (!force)
{
if (!GetParentFrame()->IsWindowVisible())
GetParentFrame()->ActivateFrame();
RedrawWindow();
}
else
RedrawWindow();
}
// Save current state as default
void CSMTPView::SaveDefaultState(void)
{
// Only do this if a mailbox has been set
if (!GetMbox())
return;
// Get bounds
CRect bounds;
WINDOWPLACEMENT wp;
GetParentFrame()->GetWindowPlacement(&wp);
bool zoomed = (wp.showCmd == SW_SHOWMAXIMIZED);
bounds = wp.rcNormalPosition;
// Sync column widths
for(int i = 0; i < mColumnInfo.size(); i++)
mColumnInfo[i].column_width = GetTable()->GetColWidth(i + 1);
// Get current match item
CMatchItem match;
// Check whether quitting
bool is_quitting = CMulberryApp::sApp->IsQuitting();
// Add info to prefs
CMailboxWindowState state(nil, &bounds, zoomed ? eWindowStateMax : eWindowStateNormal, &mColumnInfo,
(ESortMessageBy) GetMbox()->GetSortBy(),
(EShowMessageBy) GetMbox()->GetShowBy(),
is_quitting ? NMbox::eViewMode_ShowMatch : NMbox::eViewMode_All,
&match,
Is3Pane() ? 0 : GetMailboxWindow()->GetSplitter()->GetRelativeSplitPos());
if (CPreferences::sPrefs->mSMTPWindowDefault.Value().Merge(state))
CPreferences::sPrefs->mSMTPWindowDefault.SetDirty();
}
| 30.110638 | 172 | 0.71368 |
f988503b86a58fce537ef8d81853b4f82278da5b | 111,478 | cpp | C++ | src/newsview.cpp | taviso/mpgravity | f6a2a7a02014b19047e44db76ae551bd689c16ac | [
"BSD-3-Clause"
] | 9 | 2020-04-01T04:15:22.000Z | 2021-09-26T21:03:47.000Z | src/newsview.cpp | taviso/mpgravity | f6a2a7a02014b19047e44db76ae551bd689c16ac | [
"BSD-3-Clause"
] | 17 | 2020-04-02T19:38:40.000Z | 2020-04-12T05:47:08.000Z | src/newsview.cpp | taviso/mpgravity | f6a2a7a02014b19047e44db76ae551bd689c16ac | [
"BSD-3-Clause"
] | null | null | null | /*****************************************************************************/
/* SOURCE CONTROL VERSIONS */
/*---------------------------------------------------------------------------*/
/* */
/* Version Date Time Author / Comment (optional) */
/* */
/* $Log: newsview.cpp,v $
/* Revision 1.1 2010/07/21 17:14:57 richard_wood
/* Initial checkin of V3.0.0 source code and other resources.
/* Initial code builds V3.0.0 RC1
/*
/* Revision 1.3 2010/04/11 13:47:40 richard_wood
/* FIXED - Export custom headers does not work, they are lost
/* FIXED - Foreign month names cause crash
/* FIXED - Bozo bin not being exported / imported
/* FIXED - Watch & ignore threads not being imported / exported
/* FIXED - Save article (append to existing file) missing delimiters between existing text in file and new article
/* ADDED - Add ability to customise signature font size + colour
/* First build for 2.9.15 candidate.
/*
/* Revision 1.2 2009/07/08 18:32:32 richard_wood
/* Fixed lots of new installer bugs, spell checker dialog bug, updated the vcredist file to 2008 SP1 version, plus lots of other bug fixes.
/*
/* Revision 1.1 2009/06/09 13:21:29 richard_wood
/* *** empty log message ***
/*
/* Revision 1.6 2009/01/29 17:22:35 richard_wood
/* Tidying up source code.
/* Removing dead classes.
/*
/* Revision 1.5 2009/01/02 13:34:33 richard_wood
/* Build 6 : BETA release
/*
/* [-] Fixed bug in Follow up dialog - Quoted text should be coloured.
/* [-] Fixed bug in New post/Follow up dialog - if more than 1 page of text
/* and typing at or near top the text would jump around.
/*
/* Revision 1.4 2008/10/15 23:30:23 richard_wood
/* Fixed bug in EMail reply dialog, if a ReplyTo header was present, the email field in the dialog picked up the address from the previous email sent.
/*
/* Revision 1.3 2008/09/19 14:51:35 richard_wood
/* Updated for VS 2005
/*
/* */
/*****************************************************************************/
/**********************************************************************************
Copyright (c) 2003, Albert M. Choy
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Microplanet, Inc. nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**********************************************************************************/
// Newsview.cpp : implementation of the CNewsView class
//
// 4-18-96 amc When an article is destroyed by the DEL key, the Flatview
// and the thread view update each other. I am no longer
// using the odb callback stuff
//
#include "stdafx.h"
#include "News.h"
#include "Newsdoc.h"
#include "Newsview.h"
#include "mainfrm.h"
#include "globals.h"
#include "hints.h"
#include "hourglas.h"
#include "tmutex.h"
#include "posttmpl.h"
#include "custmsg.h"
#include "tglobopt.h"
#include "pobject.h"
#include "names.h"
#include "tasker.h"
#include "nggenpg.h"
#include "ngoverpg.h" // TNewsGroupOverrideOptions
#include "ngfltpg.h" // TNewsGroupFilterPage
#include "tsigpage.h" // TSigPage (per newsgroup sigs)
#include "warndlg.h"
#include "gotoart.h"
#include "ngpurg.h"
#include "ngutil.h"
#include "tnews3md.h" // TNews3MDIChildWnd
#include "mlayout.h" // TMdiLayout
#include "artview.h" // TArticleFormView
#include "statunit.h" // TStatusUnit
#include "thrdlvw.h" // TThreadListView
#include "utilrout.h"
#include "rgbkgrnd.h"
#include "rgwarn.h"
#include "rgfont.h"
#include "rgui.h"
#include "rgswit.h"
#include "log.h"
#include "utilsize.h"
//#include "hctldrag.h"
#include "rules.h" // DoRuleSubstitution()
#include "TAskFol.h" // how to handle "followup-to: poster"
#include "fileutil.h" // UseProgramPath
#include "genutil.h" // GetThreadView()
#include "licutil.h"
#include "nglist.h" // TNewsGroupUseLock
#include "server.h"
#include "newsdb.h" // gpStore
#include "vfilter.h" // TViewFilter
#include "utilerr.h"
#include "servcp.h" // TServerCountedPtr
#include "limithdr.h" // CPromptLimitHeaders
#include "usrdisp.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
extern TGlobalOptions * gpGlobalOptions;
extern TNewsTasker* gpTasker;
const UINT CNewsView::idCaptionTimer = 32100;
const UINT CNewsView::idSelchangeTimer = 32101;
enum MessageType {MESSAGE_TYPE_BUG, MESSAGE_TYPE_SUGGESTION,
MESSAGE_TYPE_SEND_TO_FRIEND};
MessageType giMessageType; // what type of message are we composing?
#define FLATHDR_ID 9001
#define SCROLL_BMP_CX 15
#define BASE_CLASS CListView
/////////////////////////////////////////////////////////////////////////////
// CNewsView
IMPLEMENT_DYNCREATE(CNewsView, CListView)
BEGIN_MESSAGE_MAP(CNewsView, BASE_CLASS)
ON_WM_CREATE()
ON_WM_SIZE()
ON_COMMAND(IDR_NGPOPUP_OPEN, OnNgpopupOpen)
ON_COMMAND(IDR_NGPOPUP_UNSUBSCRIBE, OnNewsgroupUnsubscribe)
ON_COMMAND(IDR_NGPOPUP_CATCHUPALLARTICLES, OnNgpopupCatchupallarticles)
ON_COMMAND(IDC_NGPOPUP_MANUAL_RULE, OnNgpopupManualRule)
ON_COMMAND(ID_NEWSGROUP_POSTARTICLE, OnNewsgroupPostarticle)
ON_COMMAND(ID_ARTICLE_FOLLOWUP, OnArticleFollowup)
ON_COMMAND(ID_ARTICLE_REPLYBYMAIL, OnArticleReplybymail)
ON_COMMAND(ID_ARTICLE_MAILTOFRIEND, OnArticleForward)
ON_COMMAND(ID_FORWARD_SELECTED, OnForwardSelectedArticles)
ON_UPDATE_COMMAND_UI(ID_ARTICLE_REPLYBYMAIL, OnUpdateArticleReplybymail)
ON_UPDATE_COMMAND_UI(ID_FORWARD_SELECTED, OnUpdateForwardSelectedArticles)
// ON_UPDATE_COMMAND_UI(ID_HELP_SENDBUGREPORT, OnUpdateHelpSendBugReport)
// ON_UPDATE_COMMAND_UI(ID_HELP_SENDPRODUCTSUGGESTION, OnUpdateHelpSendSuggestion)
ON_UPDATE_COMMAND_UI(ID_FILE_SEND_MAIL, OnUpdateSendToFriend)
ON_WM_DESTROY()
ON_UPDATE_COMMAND_UI(ID_ARTICLE_FOLLOWUP, OnUpdateArticleFollowup)
ON_UPDATE_COMMAND_UI(ID_NEWSGROUP_POSTARTICLE, OnUpdateNewsgroupPostarticle)
ON_COMMAND(IDR_NGPOPUP_PROPERTIES, OnNgpopupProperties)
// ON_COMMAND(ID_HELP_SENDBUGREPORT, OnHelpSendBugReport)
// ON_COMMAND(ID_HELP_SENDPRODUCTSUGGESTION, OnHelpSendSuggestion)
ON_COMMAND(ID_FILE_SEND_MAIL, OnSendToFriend)
ON_WM_TIMER()
ON_MESSAGE (WMU_NEWSVIEW_GOTOARTICLE, GotoArticle)
ON_MESSAGE (WMU_NEWSVIEW_PROCESS_MAILTO, ProcessMailTo)
ON_MESSAGE (WMC_DISPLAY_ARTCOUNT, OnDisplayArtcount)
ON_COMMAND (ID_ARTICLE_SAVE_AS, OnSaveToFile)
ON_UPDATE_COMMAND_UI (ID_ARTICLE_SAVE_AS, OnUpdateSaveToFile)
ON_COMMAND (ID_THREAD_CHANGETHREADSTATUSTO_READ, OnThreadChangeToRead)
ON_UPDATE_COMMAND_UI (IDR_NGPOPUP_CATCHUPALLARTICLES, OnUpdateNewsgroupCatchup)
ON_UPDATE_COMMAND_UI (IDR_NGPOPUP_UNSUBSCRIBE, OnUpdateNewsgroupUnsubscribe)
ON_UPDATE_COMMAND_UI (IDR_NGPOPUP_PROPERTIES, OnUpdateNewsgroupProperties)
ON_UPDATE_COMMAND_UI (ID_THREAD_CHANGETHREADSTATUSTO_READ, OnUpdateThreadChangeToRead)
ON_UPDATE_COMMAND_UI (IDC_VIEW_BINARY, OnUpdateDisable)
ON_COMMAND(ID_CMD_TABAROUND, OnCmdTabaround)
ON_COMMAND(ID_CMD_TABBACK, OnCmdTabBack)
ON_COMMAND(ID_GETHEADERS_ALLGROUPS, OnGetheadersAllGroups)
ON_UPDATE_COMMAND_UI(ID_GETHEADERS_ALLGROUPS, OnUpdateGetheadersAllGroups)
ON_COMMAND(ID_GETHEADERS_MGROUPS, OnGetHeadersMultiGroup)
ON_UPDATE_COMMAND_UI(ID_GETHEADERS_MGROUPS, OnUpdateGetHeadersMultiGroup)
ON_COMMAND(ID_GETHEADER_LIMITED, OnGetheaderLimited)
ON_UPDATE_COMMAND_UI(ID_GETHEADER_LIMITED, OnUpdateGetheaderLimited)
ON_COMMAND(WMC_DISPLAYALL_ARTCOUNT, OnDisplayAllArticleCounts)
ON_MESSAGE(WMU_MODE1_HDRS_DONE, OnMode1HdrsDone)
ON_MESSAGE(WMU_NGROUP_HDRS_DONE, OnNewsgroupHdrsDone)
ON_WM_CONTEXTMENU()
ON_UPDATE_COMMAND_UI(ID_EDIT_SELECT_ALL, OnUpdateEditSelectAll)
ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateEditCopy)
ON_MESSAGE(WMU_ERROR_FROM_SERVER, OnErrorFromServer)
ON_MESSAGE(WMU_SELCHANGE_OPEN, OnSelChangeOpen)
ON_UPDATE_COMMAND_UI(ID_ARTICLE_DELETE_SELECTED, OnUpdateDeleteSelected)
ON_UPDATE_COMMAND_UI(IDC_NGPOPUP_MANUAL_RULE, OnUpdateNgpopupManualRule)
ON_UPDATE_COMMAND_UI(IDR_NGPOPUP_OPEN, OnUpdateNgpopupOpen)
ON_UPDATE_COMMAND_UI(ID_KEEP_SAMPLED, OnUpdateKeepSampled)
ON_COMMAND(ID_KEEP_SAMPLED, OnKeepSampled)
ON_UPDATE_COMMAND_UI(ID_KEEP_ALL_SAMPLED, OnUpdateKeepAllSampled)
ON_COMMAND(ID_KEEP_ALL_SAMPLED, OnKeepAllSampled)
ON_COMMAND(ID_EDIT_SELECT_ALL, OnEditSelectAll)
ON_UPDATE_COMMAND_UI(ID_POST_SELECTED, OnUpdatePostSelected)
ON_COMMAND(ID_POST_SELECTED, OnPostSelected)
ON_COMMAND(ID_ARTICLE_DELETE_SELECTED, OnArticleDeleteSelected)
ON_COMMAND(ID_VERIFY_HDRS, OnVerifyLocalHeaders)
ON_COMMAND(ID_HELP_RESYNC_STATI, OnHelpResyncStati)
ON_COMMAND(ID_NEWSGROUP_PINFILTER, OnNewsgroupPinfilter)
ON_UPDATE_COMMAND_UI(ID_NEWSGROUP_PINFILTER, OnUpdateNewsgroupPinfilter)
ON_UPDATE_COMMAND_UI(ID_ARTICLE_MORE, OnUpdateArticleMore)
ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnGetDisplayInfo)
ON_NOTIFY_REFLECT(NM_CLICK, OnClick)
ON_NOTIFY_REFLECT(NM_RETURN, OnReturn)
ON_NOTIFY_REFLECT(NM_RCLICK, OnRclick)
ON_NOTIFY_REFLECT(NM_DBLCLK, OnDblclk)
ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, OnItemChanged)
ON_WM_MOUSEWHEEL()
ON_UPDATE_COMMAND_UI(IDM_GETTAGGED_FORGROUPS, OnUpdateGettaggedForgroups)
ON_COMMAND(IDM_GETTAGGED_FORGROUPS, OnGettaggedForgroups)
ON_WM_VKEYTOITEM()
ON_WM_ERASEBKGND()
ON_COMMAND(ID_THREADLIST_REFRESH, OnRefreshCurrentNewsgroup)
ON_WM_LBUTTONDOWN()
ON_COMMAND(ID_NV_FORWARD_SELECTED, OnForwardSelectedArticles)
ON_UPDATE_COMMAND_UI(ID_THREADLIST_REPLYBYMAIL, OnUpdateArticleReplybymail)
ON_UPDATE_COMMAND_UI(ID_THREADLIST_POSTFOLLOWUP, OnUpdateArticleFollowup)
ON_UPDATE_COMMAND_UI(ID_THREADLIST_POSTNEWARTICLE, OnUpdateNewsgroupPostarticle)
ON_UPDATE_COMMAND_UI (IDC_DECODE, OnUpdateDisable)
ON_UPDATE_COMMAND_UI (IDC_MANUAL_DECODE, OnUpdateDisable)
ON_UPDATE_COMMAND_UI(ID_VERIFY_HDRS, OnUpdateGetHeadersMultiGroup)
ON_WM_MOUSEMOVE()
ON_NOTIFY_EX(TTN_NEEDTEXT, 0, OnNeedText)
END_MESSAGE_MAP()
// ---------------------------------------------------------------------------
// utility function
void FreeGroupIDPairs (CPtrArray* pVec)
{
int tot = pVec->GetSize();
for (--tot; tot >= 0; --tot)
delete ((TGroupIDPair*) pVec->GetAt(tot));
}
/////////////////////////////////////////////////////////////////////////////
// CNewsView construction/destruction
CNewsView::CNewsView()
{
InitializeCriticalSection(&m_dbCritSect);
iLocalOpen = 0;
m_ngPopupMenu.LoadMenu (IDR_NGPOPUP);
m_imageList.Create (IDB_SCROLL,
SCROLL_BMP_CX, // width of frame
1, // gro factor
RGB(255,0,255) // transparent color (hot purple)
);
// setup the 1st overlay image
VERIFY(m_imageList.SetOverlayImage (6, 1));
m_curNewsgroupID = 0;
m_pBrowsePaneHeader = 0;
m_pBrowsePaneText = 0;
m_fLoadFreshData = TRUE;
m_hCaptionTimer = 0;
m_hSelchangeTimer = 0;
m_GotoArticle.m_articleNumber = -1;
m_fPinFilter = FALSE;
m_fTrackZoom = false;
m_iOneClickInterference = 0;
}
/////////////////////////////////////////////////////////////////////////////
CNewsView::~CNewsView()
{
if (m_pBrowsePaneText)
{
delete m_pBrowsePaneText;
m_pBrowsePaneText = 0;
}
DeleteCriticalSection(&m_dbCritSect);
}
/////////////////////////////////////////////////////////////////////////////
// CNewsView drawing
void CNewsView::OnDraw(CDC* pDC)
{
CNewsDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
}
/////////////////////////////////////////////////////////////////////////////
// CNewsView printing
BOOL CNewsView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CNewsView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CNewsView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
#if defined(OLAY_CRAP)
/////////////////////////////////////////////////////////////////////////////
// OLE Server support
// The following command handler provides the standard keyboard
// user interface to cancel an in-place editing session. Here,
// the server (not the container) causes the deactivation.
void CNewsView::OnCancelEditSrvr()
{
GetDocument()->OnDeactivateUI(FALSE);
}
#endif
/////////////////////////////////////////////////////////////////////////////
// CNewsView diagnostics
#ifdef _DEBUG
void CNewsView::AssertValid() const
{
BASE_CLASS::AssertValid();
}
void CNewsView::Dump(CDumpContext& dc) const
{
BASE_CLASS::Dump(dc);
}
CNewsDoc* CNewsView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CNewsDoc)));
return (CNewsDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CNewsView message handlers
int CNewsView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
LogString("Newsview start create");
if (BASE_CLASS::OnCreate(lpCreateStruct) == -1)
return -1;
SetupFont ();
GetListCtrl().SetImageList (&m_imageList, LVSIL_SMALL);
GetListCtrl().SetCallbackMask (LVIS_OVERLAYMASK);
// Strip CS_HREDRAW and CS_VREDRAW. We don't need to repaint everytime we
// are sized. (Tip from 'PC Magazine' May 6,1997)
DWORD dwStyle = GetClassLong (m_hWnd, GCL_STYLE);
SetClassLong (m_hWnd, GCL_STYLE, dwStyle & ~(CS_HREDRAW | CS_VREDRAW));
// OnInitialUpdate will Setup the columns in the header ctrl
// after the size has settled down.
// read from registry
m_fPinFilter = gpGlobalOptions->GetRegUI()->GetPinFilter ();
((CMainFrame*) AfxGetMainWnd())->UpdatePinFilter ( m_fPinFilter );
LogString("Newsview end create");
return 0;
}
/////////////////////////////////////////////////////////////////////////////
void CNewsView::OnSize(UINT nType, int cx, int cy)
{
BASE_CLASS::OnSize(nType, cx, cy);
Resize ( cx, cy );
}
// called from OnSize, and OnInitialUpdate
void CNewsView::Resize(int cx, int cy)
{
}
// ------------------------------------------------------------------------
//
void CNewsView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint)
{
if (VIEWHINT_SERVER_SWITCH == lHint)
return;
if (VIEWHINT_UNZOOM == lHint)
{
handle_zoom (false, pHint);
return;
}
if (VIEWHINT_ZOOM == lHint)
{
handle_zoom (true, pHint);
return;
}
if (VIEWHINT_SHOWARTICLE == lHint)
return;
if (VIEWHINT_SHOWGROUP == lHint)
return;
if (VIEWHINT_SHOWGROUP_NOSEL == lHint)
return;
if (VIEWHINT_EMPTY == lHint)
{
EmptyBrowsePointers ();
GetDocument()->EmptyArticleStatusChange();
sync_caption();
return;
}
// if an article's status changes it means nothing to us
if (VIEWHINT_STATUS_CHANGE == lHint ||
VIEWHINT_ERASE_OLDTHREADS == lHint)
return;
//if (VIEWHINT_NEWSVIEW_UNSUBSCRIBE == lHint)
// {
// Unsubscribing ((TNewsGroup*) pHint);
// return;
// }
// remember selected group-id
LONG iSelGroupID = GetSelectedGroupID();
CListCtrl & lc = GetListCtrl();
lc.DeleteAllItems ();
TServerCountedPtr cpNewsServer;
TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray();
TNewsGroupArrayReadLock ngMgr(vNewsGroups);
int count = vNewsGroups->GetSize();
for (int j = 0; j < count; ++j)
{
TNewsGroup* pNG = vNewsGroups[j];
AddStringWithData ( pNG->GetBestname(), pNG->m_GroupID);
}
// restore selection
if (iSelGroupID)
{
if (0 != SetSelectedGroupID (iSelGroupID))
SetOneSelection (0);
}
}
// 5-8-96 change to fetch on zero
void CNewsView::OnNgpopupOpen()
{
OpenNewsgroup( kFetchOnZero, kPreferredFilter );
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateNgpopupOpen(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsExactlyOneNewsgroupSelected());
}
// ------------------------------------------------------------------------
// Returns -1 for failure
int CNewsView::GetSelectedIndex ()
{
CListCtrl & lc = GetListCtrl();
POSITION pos = lc.GetFirstSelectedItemPosition ();
if (pos)
return lc.GetNextSelectedItem (pos);
int iMark = lc.GetSelectionMark ();
if (-1 == iMark)
return -1;
return iMark;
}
// ------------------------------------------------------------------------
// Returns positive for success, 0 for failure
LONG CNewsView::GetSelectedGroupID ()
{
int idx = GetSelectedIndex ();
if (-1 == idx)
return 0;
return (LONG) GetListCtrl().GetItemData (idx);
}
// ------------------------------------------------------------------------
// Input: a group id
// Set the listbox selection to the newsgroup that has that id
// Returns: 0 for success, non-zero for error
int CNewsView::SetSelectedGroupID (int iGroupID)
{
CListCtrl & lc = GetListCtrl();
int idx = lc.GetItemCount();
for (--idx; idx >= 0; --idx)
{
if (iGroupID == (LONG) lc.GetItemData(idx))
{
SetOneSelection (idx);
return 0;
}
}
return 1;
}
// ------------------------------------------------------------------------
void CNewsView::OnNgpopupManualRule ()
{
AfxGetMainWnd ()->PostMessage (WM_COMMAND, ID_OPTIONS_MANUAL_RULE);
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateNgpopupManualRule(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// ------------------------------------------------------------------------
void CNewsView::OnInitialUpdate()
{
CListCtrl & lc = GetListCtrl();
LogString("newsview start initial update");
CNewsApp* pNewsApp = (CNewsApp*) AfxGetApp();
pNewsApp->SetGlobalNewsDoc( GetDocument() );
CNewsDoc::m_pDoc = GetDocument();
CRect rct; GetClientRect( &rct );
// load the widths from the registry
SetupReportColumns (rct.Width());
lc.SetExtendedStyle (LVS_EX_FULLROWSELECT);
// the header control is too tall unless we do this
Resize( rct.Width(), rct.Height() );
// setup columns before initial fill
BASE_CLASS::OnInitialUpdate();
// setup tool tips
VERIFY(m_sToolTips.Create (this, TTS_ALWAYSTIP));
VERIFY(m_sToolTips.AddTool (this, LPSTR_TEXTCALLBACK));
m_sToolTips.SetMaxTipWidth (SHRT_MAX);
m_sToolTips.SetDelayTime (TTDT_AUTOPOP, 10000); // go away after 10 secs
m_sToolTips.SetDelayTime (TTDT_INITIAL, 500);
m_sToolTips.SetDelayTime (TTDT_RESHOW, 1000);
// at this point the splash screen is gone and we are pretty much,
// up and running and willing to load the VCR file from the cmdline
CWnd::FromHandle(ghwndMainFrame)->PostMessage (WMU_READYTO_RUN);
int lastGID = gpGlobalOptions->GetRegUI()->GetLastGroupID();
if (lastGID < 0)
{
if (lc.GetItemCount() > 0)
lastGID = (int) lc.GetItemData( 0 );
}
TServerCountedPtr cpNewsServer;
// find it
bool fFoundValidGroup = false;
{
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, lastGID, &fUseLock, pNG);
if (fUseLock)
{
fFoundValidGroup = true;
// don't wait for mode-1 to load
if (TNewsGroup::kNothing == UtilGetStorageOption (pNG))
fFoundValidGroup = false;
}
}
if (fFoundValidGroup)
{
int tot = lc.GetItemCount();
for (--tot; tot >= 0; --tot)
{
if (lastGID == (int) lc.GetItemData( tot ))
{
if (gpGlobalOptions->GetRegUI()->GetOneClickGroup())
{
SetOneSelection (tot);
// LVN_ITEMCHANGED notification does the rest....
}
else
{
SetOneSelection (tot);
OpenNewsgroup( kOpenNormal, kPreferredFilter, lastGID );
}
break;
}
}
}
LogString("newsview end initial update");
}
///////////////////////////////////////////////////////////////////////////
void CNewsView::SetupReportColumns (int iParentWidth)
{
TRegUI* pRegUI = gpGlobalOptions->GetRegUI();
int riWidths[3];
if (0 != pRegUI->LoadUtilHeaders("NGPane", riWidths, ELEM(riWidths)))
{
int avgChar = LOWORD(GetDialogBaseUnits());
riWidths[1] = avgChar * 6;
riWidths[2] = avgChar * 6;
int remainder = iParentWidth -riWidths[1] -riWidths[2]
-GetSystemMetrics(SM_CXVSCROLL);
riWidths[0] = max(remainder, avgChar*6);
}
CString strNewsgroups; strNewsgroups.LoadString (IDS_HEADER_NEWSGROUPS);
CString strLocal; strLocal.LoadString (IDS_HEADER_LOCAL);
CString strServer; strServer.LoadString (IDS_HEADER_SERVER);
CListCtrl & lc = GetListCtrl();
lc.InsertColumn (0, strNewsgroups, LVCFMT_LEFT, riWidths[0], 0);
lc.InsertColumn (1, strLocal, LVCFMT_RIGHT, riWidths[1], 1);
lc.InsertColumn (2, strServer, LVCFMT_RIGHT, riWidths[2], 2);
}
///////////////////////////////////////////////////////////////////////////
// CloseCurrentNewsgroup - this was factored out of OpenNewsgroup and
// made public so that it could be used by
// CMainFrame::OnDatePurgeAll
///////////////////////////////////////////////////////////////////////////
void CNewsView::CloseCurrentNewsgroup ()
{
BOOL fViewsEmptied = FALSE;
fViewsEmptied = ShutdownOldNewsgroup ();
gpUIMemory->SetLastGroup ( m_curNewsgroupID );
// the intent of this function is that there will be no
// current group afterwards...
SetCurNewsGroupID (0);
if (!fViewsEmptied)
{
EmptyBrowsePointers ();
// clear out TreeView, FlatView, ArtView
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
}
}
///////////////////////////////////////////////////////////////////////////
// OpenNewsgroup
// eOpenMode - kFetchOnZero if you want to Try to GetHeaders
// iInputGroupID - pass in a groupID, or function will use the cur Sel
//
// Changes:
// 4-09-96 For the Dying NG, Empty the View and then Close it.
// also call ::Empty to clean out the thread list
//
// 8-01-97 return 0 if loaded, 1 if started download, -1 for error
//
int CNewsView::OpenNewsgroup(EOpenMode eMode, EUseFilter eFilter, int iInputGroupID/*=-1*/)
{
int iFilterRC = 0;
BOOL fViewsEmptied = FALSE;
LONG newGroupID;
if (iInputGroupID > 0)
newGroupID = iInputGroupID;
else
{
newGroupID = GetSelectedGroupID ();
if (NULL == newGroupID)
return -1;
}
fViewsEmptied = ShutdownOldNewsgroup ();
SetCurNewsGroupID( newGroupID );
// set title on mdi-child
if (0 == m_hCaptionTimer)
m_hCaptionTimer = SetTimer (idCaptionTimer, 250, NULL);
if (!fViewsEmptied)
{
EmptyBrowsePointers ();
// clear out TreeView, FlatView, ArtView
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
fViewsEmptied = TRUE;
}
TServerCountedPtr cpNewsServer;
{
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (fUseLock)
{
// open this guy for business
protected_open ( pNG, TRUE );
if (kPreferredFilter == eFilter && (FALSE==m_fPinFilter))
{
// newsgroup may have a default filter. hand off to the Filterbar
int iWhatFilter = GetPreferredFilter ( pNG );
iFilterRC = ((CMainFrame*)AfxGetMainWnd())->SelectFilter ( iWhatFilter );
}
else
{
// if we are using GotoArticle, skip the preferred filter, use current
// if filters are pinned. Use current
}
// if the newsgrp is devoid of new articles, then Try downloading some
if ((kFetchOnZero == eMode) &&
(TNewsGroup::kHeadersOnly == UtilGetStorageOption (pNG) ||
TNewsGroup::kStoreBodies == UtilGetStorageOption (pNG)))
{
pNG->UpdateFilterCount (true);
TViewFilter * pVF = TNewsGroup::GetpCurViewFilter();
if (0 == pVF)
return -1;
TStatusUnit::ETriad eTri = pVF->GetNew();
if (TStatusUnit::kYes == eTri)
{
int iLocalNew, iServerNew, iLocalTotal;
iLocalNew = iServerNew = 100;
pNG->FormatNewArticles ( iLocalNew, iServerNew, iLocalTotal );
if (0 == iLocalNew)
{
// there's nothing in the DB to load - hit the server
GetHeadersOneGroup ();
return 1;
}
}
if (TStatusUnit::kMaybe == eTri)
{
// they are viewing both New and Read
if (0 == pNG->HdrRangeCount())
{
// there's absolutely nothing in the newgroup - hit server
GetHeadersOneGroup ();
return 1;
}
}
}
// when re-creating a new layout, we just use the old data.
if (m_fLoadFreshData) {
// when in mode 1, do all rule substitution before loading articles
// NOTE: This must be done before the hourglass icon is displayed
// (below)
if (pNG->GetStorageOption () == TNewsGroup::kNothing)
ResetAndPerformRuleSubstitution (NULL /* psHeader */, pNG);
// tell rules that an hourglass icon is going to appear, and not to
// bring up any dialogs (it will queue them and display them later)
RulesHourglassStart ();
// user waits....
{
CHourglass wait = this;
pNG->LoadArticles(FALSE);
}
// now that the hourglass icon is gone, we can let rules display any
// notification dialogs
RulesHourglassEnd ();
}
}
}
// fill thread view
please_update_views();
// allow the layout manager to see this action
CFrameWnd * pDadFrame = GetParentFrame();
if (pDadFrame)
pDadFrame->SendMessage (WMU_USER_ACTION, TGlobalDef::kActionOpenGroup);
if (iFilterRC)
AfxMessageBox (IDS_GRP_FILTERGONE);
return 0;
}
///////////////////////////////////////////////////////////////////////////
// Return TRUE if the views have been Emptied
//
BOOL CNewsView::ShutdownOldNewsgroup (void)
{
// We can't shut down a group if the servers not alive
if (!IsActiveServer())
return TRUE;
// save off status of old?
BOOL fViewsEmptied = FALSE;
TServerCountedPtr cpNewsServer;
LONG oldGroupID = m_curNewsgroupID;
BOOL fUseLock;
TNewsGroup* pOld = 0;
TNewsGroupUseLock useLock(cpNewsServer, oldGroupID, &fUseLock, pOld);
if (fUseLock)
{
TUserDisplay_UIPane sAutoDraw("Clear list...");
if (!fViewsEmptied)
{
// clear the threadview while the pointers are Valid
EmptyBrowsePointers ();
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
fViewsEmptied = TRUE;
}
// if (pOld->GetDirty())
pOld->TextRangeSave();
// Try closing the newsgroup
protected_open (pOld, FALSE);
// this is new (4/9) Empty the threadlist
pOld->Empty();
gpUserDisplay->SetCountFilter ( 0 );
gpUserDisplay->SetCountTotal ( 0 );
}
return fViewsEmptied;
}
void CNewsView::please_update_views(void)
{
TUserDisplay_UIPane sAutoDraw("Loading list...");
// perform a broadcast directed at the threadlist view
GetDocument()->UpdateAllViews(this, VIEWHINT_SHOWGROUP);
}
//-------------------------------------------------------------------------
// msg handler
void CNewsView::OnRefreshCurrentNewsgroup ()
{
RefreshCurrentNewsgroup ( );
}
//-------------------------------------------------------------------------
// Called by filter buttons, tmanrule.cpp
void CNewsView::RefreshCurrentNewsgroup (bool fMoveSelection /* = true */)
{
TServerCountedPtr cpNewsServer;
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (fUseLock)
{
CWaitCursor wait;
TSaveSelHint sSelHint;
if (fMoveSelection)
{
// Try to restore selection after change (do this before Emptying)
GetDocument()->UpdateAllViews (this, VIEWHINT_SAVESEL, &sSelHint);
}
if (true)
{
TUserDisplay_UIPane sAutoDraw("Emptying");
GetDocument()->UpdateAllViews (NULL, VIEWHINT_EMPTY);
}
// do not empty before reloading
pNG->ReloadArticles (FALSE);
TUserDisplay_UIPane sAutoDraw("Loading...");
if (fMoveSelection)
{
// perform a broadcast directed at the threadlist view
GetDocument()->UpdateAllViews (this, VIEWHINT_SHOWGROUP);
// restore selection
GetDocument()->UpdateAllViews (this, VIEWHINT_SAVESEL, &sSelHint);
}
else
{
// perform a broadcast directed at the threadlist view
GetDocument()->UpdateAllViews (this, VIEWHINT_SHOWGROUP_NOSEL);
}
}
}
//-------------------------------------------------------------------------
void CNewsView::OnContextMenu(CWnd* pWnd, CPoint point)
{
//TRACE0("caught WM_CONTEXTMENU\n");
CPoint anchor(point);
// weird coords if menu summoned with Shift-F10
if (-1 == anchor.x && -1 == anchor.y)
{
// do the best we can - top left corner of listbox
anchor.x = anchor.y = 2;
this->ClientToScreen( &anchor );
}
context_menu( anchor );
}
// ------------------------------------------------------------------------
//
void CNewsView::context_menu(CPoint & ptScreen)
{
CListCtrl & lc = GetListCtrl();
// multiple selection is OK for everything except 'Properties...'
if (lc.GetSelectedCount () <= 0)
return;
// get the group name so we can do the op...
int idx = GetSelectedIndex ();
if (idx < 0)
return;
TServerCountedPtr cpNewsServer;
LONG id = (LONG) lc.GetItemData( idx );
BOOL fUseLock;
TNewsGroup * pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, id, &fUseLock, pNG);
if (!fUseLock)
return;
CMenu * pTrackMenu = m_ngPopupMenu.GetSubMenu ( 0 );
ProbeCmdUI (this, pTrackMenu);
pTrackMenu->TrackPopupMenu( TPM_LEFTALIGN | TPM_RIGHTBUTTON, ptScreen.x, ptScreen.y, this);
}
// ------------------------------------------------------------------------
void CNewsView::UnsubscribeGroups (const CPtrArray &vec)
{
TServerCountedPtr cpNewsServer;
TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray();
for (int i = 0; i < vec.GetSize(); i++)
{
TGroupIDPair * pPair = static_cast<TGroupIDPair*>(vec[i]);
bool fDemoted = false; // TRUE if lbx-string is deleted
{
BOOL fUseLock = FALSE;
TNewsGroup* pNG;
TNewsGroupUseLock useLock(cpNewsServer, pPair->id, &fUseLock, pNG);
// kill any queued jobs
if (fUseLock)
fDemoted = demote_newsgroup ( pNG );
}
// Try to get destroy lock on it
if (0 == vNewsGroups.ReserveGroup (pPair->id))
{
cpNewsServer->UnsubscribeGroup (pPair->id);
}
else
{
// yikes. add string back into listbox.
if (fDemoted)
AddStringWithData (pPair->ngName, pPair->id);
CString pattern; pattern.LoadString (IDS_ERR_GROUP_IN_USE);
CString msg; msg.Format (pattern, (LPCTSTR) pPair->ngName);
NewsMessageBox (this, msg, MB_OK | MB_ICONSTOP);
}
}
// find new selection, open next newsgroup etc...
finish_unsubscribe();
}
// ------------------------------------------------------------------------
void CNewsView::DoUnsubscribe (BOOL bAlwaysAsk)
{
CPtrArray vec; // hold data from _prelim function
// confirm unsubscribe
if (unsubscribe_prelim (&vec, bAlwaysAsk))
return;
CWaitCursor cursor;
UnsubscribeGroups (vec);
FreeGroupIDPairs (&vec);
}
// ------------------------------------------------------------------------
void CNewsView::OnNewsgroupUnsubscribe()
{
DoUnsubscribe (FALSE /* bAlwaysAsk */);
}
// ------------------------------------------------------------------------
void CNewsView::OnArticleDeleteSelected()
{
DoUnsubscribe (TRUE /* bAlwaysAsk */);
}
// ------------------------------------------------------------------------
// TRUE indicates the lbx line was deleted
bool CNewsView::demote_newsgroup ( TNewsGroup* pNG )
{
extern TNewsTasker* gpTasker;
CListCtrl & lc = GetListCtrl();
int total = lc.GetItemCount();
for (int i = 0; i < total; ++i)
{
if (pNG->m_GroupID == (int)lc.GetItemData(i))
{
// kill any queued jobs.
gpTasker->UnregisterGroup ( pNG );
// if we are killing the current newsgroup, open some
// other group
if (pNG->m_GroupID == m_curNewsgroupID)
{
m_curNewsgroupID = 0;
}
lc.DeleteItem ( i );
// figure out what to do with the selection
int newsel;
if (i == total - 1)
newsel = i - 1;
else
newsel = i;
if (newsel >= 0)
SetOneSelection (newsel);
return true;
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////
//
// 4-24-96 amc Write changes to disk, reset title to Null
// 11-01-96 amc Clear out views when going from Mode2(dead)->Mode1
int CNewsView::finish_unsubscribe (void)
{
int total;
BOOL fEmptySync = TRUE;
TServerCountedPtr cpNewsServer;
TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray();
total = vNewsGroups->GetSize();
if (total > 0)
{
BOOL fOpenGroup = FALSE;
LONG newGroupID;
// Pull in newly selected newsgroup
// iff we killed the current newsgroup
if (0==m_curNewsgroupID)
{
// However... don't pull a newsgroup in
// if it means doing a Mode-1 suck
{
newGroupID = GetSelectedGroupID ();
if (NULL == newGroupID)
return 0;
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, newGroupID, &fUseLock, pNG);
if (!fUseLock)
return 0;
if (TNewsGroup::kHeadersOnly == UtilGetStorageOption(pNG) ||
TNewsGroup::kStoreBodies == UtilGetStorageOption(pNG))
fOpenGroup = TRUE;
}
if (fOpenGroup)
{
fEmptySync = FALSE;
OpenNewsgroup(kOpenNormal, kPreferredFilter, newGroupID);
}
}
}
if (fEmptySync)
{
// empty all views
GetDocument()->UpdateAllViews ( NULL, VIEWHINT_EMPTY );
sync_caption (); // "no newsgroup selected"
}
return 0;
}
// ------------------------------------------------------------------------
// gets info on multiselect
int CNewsView::multisel_get (CPtrArray * pVec, int* piSel)
{
CListCtrl & lc = GetListCtrl();
int sel = lc.GetSelectedCount();
if (sel <= 0)
return 1;
int* pIdx = new int[sel];
auto_ptr<int> pDeleterIdx(pIdx);
// get selected items
int n = 0;
POSITION pos = lc.GetFirstSelectedItemPosition ();
while (pos)
pIdx[n++] = lc.GetNextSelectedItem (pos);
// get the names and the group-ids
TServerCountedPtr cpNewsServer;
TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray();
// get the each ng name and release
for (int i = 0; i < sel; ++i)
{
int groupId = lc.GetItemData (pIdx[i]);
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, groupId, &fUseLock, pNG);
if (fUseLock)
pVec->Add ( new TGroupIDPair(groupId, pNG->GetBestname()) );
}
*piSel = sel;
return 0;
}
// ------------------------------------------------------------------------
// unsubscribe_prelim - Returns 0 for success. 1 for stop
// Confirm that the user wants to unsubscribe from multiple newsgroups
// Name and id pairs are returned in the PtrArray. Uses nickname if
// it is set.
int CNewsView::unsubscribe_prelim (CPtrArray *pVec, BOOL bAlwaysAsk)
{
int sel = 0;
if (multisel_get (pVec, &sel))
return 1;
int nProtectedArticles = 0;
TServerCountedPtr cpNewsServer;
for (int i = 0; i < pVec->GetSize(); i++)
{
TGroupIDPair * pPair = static_cast<TGroupIDPair*>(pVec->GetAt(i));
{
BOOL fUseLock = FALSE;
TNewsGroup* pNG;
TNewsGroupUseLock useLock(cpNewsServer, pPair->id, &fUseLock, pNG);
if (fUseLock)
{
int nProt = 0;
pNG->StatusCountProtected ( nProt );
nProtectedArticles += nProt;
}
}
}
// see if they really want to kill these groups...
if (gpGlobalOptions->WarnOnUnsubscribe() || bAlwaysAsk || (nProtectedArticles > 0))
{
CString msg;
CString strProtected;
if (1 == sel)
{
if (pVec->GetSize () != 1)
return 1;
AfxFormatString1 (msg, IDS_WARNING_UNSUBSCRIBE,
((TGroupIDPair*)pVec->GetAt(0))->ngName);
}
else
{
char szCount[10];
_itoa (sel, szCount, 10);
AfxFormatString1 (msg, IDS_WARN_UNSUBSCRIBE_MANY1, szCount);
}
if (nProtectedArticles > 0)
{
CString strProtected;
strProtected.Format (IDS_WARNING_PROTCOUNT1, nProtectedArticles);
msg += strProtected;
}
BOOL fDisableWarning = FALSE;
if (WarnWithCBX (msg,
&fDisableWarning,
NULL /* pParentWnd */,
FALSE /* iNotifyOnly */,
FALSE /* bDefaultToNo */,
bAlwaysAsk /* bDisableCheckbox */))
{
if (fDisableWarning)
{
gpGlobalOptions->SetWarnOnUnsubscribe(FALSE);
TRegWarn *pRegWarning = gpGlobalOptions->GetRegWarn ();
pRegWarning->Save();
}
return 0; // it's OK to go on
}
else
{
// free intermediate data
FreeGroupIDPairs (pVec);
return 1;
}
}
return 0; // it's OK to go on
}
/* ----------------------------------------------------------------
Case 1: You are in Mode 1, and you are viewing New & Read
messages. Catching up means marking things Read; After catching
up, you do not want to reload the same headers over your
PPP link (see Bug #68 part 2)
11-26-96 amc User can move to next group after catchup on this one
------------------------------------------------------------------- */
void CNewsView::OnNgpopupCatchupallarticles()
{
// holds a collection of (groupID, name) pairs
CPtrArray vec;
// get info on multisel and allow cancellation
if (catchup_prelim (&vec))
return;
int tot = vec.GetSize();
for (int i = 0; i < tot; i++)
{
BOOL fMoveNext = (i == tot-1);
TGroupIDPair* pPair = static_cast<TGroupIDPair*>(vec[i]);
CatchUp_Helper ( pPair->id, fMoveNext );
}
// free intermediate data
FreeGroupIDPairs (&vec);
}
// ------------------------------------------------------------------------
// Called from :
// OnGetheaderGroup
// OnNgpopupCatchupallarticles
void CNewsView::CatchUp_Helper (int iGroupID, BOOL fAllowMoveNext)
{
TServerCountedPtr cpNewsServer;
TNewsGroup * pNG = 0;
BOOL fUseLock;
// reacquire lock
TNewsGroupUseLock useLock(cpNewsServer, iGroupID, &fUseLock, pNG);
if (!fUseLock)
return;
BOOL fViewing = (pNG->m_GroupID == m_curNewsgroupID);
if (TNewsGroup::kNothing == UtilGetStorageOption ( pNG ))
{
// Since this is Mode 1, avoid going out to the server again
// marks everything as Read
pNG->CatchUpArticles();
OnDisplayArtcount(pNG->m_GroupID, 0);
if (fViewing)
{
int iNextGrpId = -1;
int iNextIdx;
// see if we are moving onward
if (fAllowMoveNext &&
gpGlobalOptions->GetRegSwitch()->GetCatchUpLoadNext() &&
validate_next_newsgroup(&iNextGrpId, &iNextIdx))
{
// clear out
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
// goto next ng
AddOneClickGroupInterference();
SetOneSelection (iNextIdx);
OpenNewsgroup (kOpenNormal, kPreferredFilter, iNextGrpId);
}
else
{
TViewFilter * pFilter = TNewsGroup::GetpCurViewFilter ();
if (0 == pFilter)
return;
TStatusUnit::ETriad eTri = pFilter->GetNew ();
switch (eTri)
{
case TStatusUnit::kMaybe:
case TStatusUnit::kNo:
// this will show the result (all articles marked as Read)
GetDocument()->UpdateAllViews(this, VIEWHINT_SHOWGROUP);
break;
case TStatusUnit::kYes:
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
break;
}
}
}
else
{
// catchup on a group that we are not viewing. No movement
}
}
else
{
// this is Mode 2 or Mode 3
if (fViewing)
// empty out TreeView, FlatView, ArtView
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
pNG->CatchUpArticles();
// newsview should redraw count of new articles (0)
OnDisplayArtcount(pNG->m_GroupID, 0);
if (fViewing)
{
int iNextGrpId = -1;
int iNextIdx;
// see if we are moving onward
if (fAllowMoveNext &&
gpGlobalOptions->GetRegSwitch()->GetCatchUpLoadNext() &&
validate_next_newsgroup(&iNextGrpId, &iNextIdx))
{
EmptyBrowsePointers ();
// goto next ng
AddOneClickGroupInterference();
SetOneSelection (iNextIdx);
OpenNewsgroup (CNewsView::kOpenNormal, kPreferredFilter, iNextGrpId);
}
else
{
EmptyBrowsePointers ();
// reload & update the display
newsview_reload(pNG);
}
}
}
}
// -----------------------------------------------------------------------
// Called from OnNgpopupCatchupallarticles
void CNewsView::newsview_reload(TNewsGroup* pNG)
{
ASSERT(pNG);
CWaitCursor wait;
if (pNG)
{
SetCurNewsGroupID( pNG->m_GroupID );
// TRUE - empty thread list first, then load
pNG->ReloadArticles(TRUE);
// perform a broadcast directed at the threadlist view
GetDocument()->UpdateAllViews(this, VIEWHINT_SHOWGROUP);
}
}
// --------------------------------------------------------------
int CNewsView::catchup_prelim (CPtrArray* pVec)
{
int sel = 0;
if (multisel_get (pVec, &sel))
return 1;
// see if they really want to catchup on these groups...
if (gpGlobalOptions->WarnOnCatchup())
{
CString msg;
if (1 == sel)
{
if (pVec->GetSize () != 1)
return 1;
AfxFormatString1 (msg, IDS_WARNING_CATCHUP,
((TGroupIDPair*)pVec->GetAt(0))->ngName);
}
else
{
char szCount[10];
_itoa (sel, szCount, 10);
AfxFormatString1 (msg, IDS_WARN_CATCHUP_MANY1, szCount);
}
BOOL fDisableWarning = FALSE;
if (WarnWithCBX (msg, &fDisableWarning))
{
if (fDisableWarning)
{
gpGlobalOptions->SetWarnOnCatchup(FALSE);
TRegWarn *pRegWarning = gpGlobalOptions->GetRegWarn ();
pRegWarning->Save();
}
}
else
{
// free intermediate data
FreeGroupIDPairs (pVec);
return 1;
}
}
return 0; // it's OK to go on
}
// --------------------------------------------------------------
void CNewsView::OnUpdateNewsgroupPostarticle(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsNewsgroupDisplayed());
}
// --------------------------------------------------------------
// OnNewsgroupPostarticle -- post an article to the open newsgroup
void CNewsView::OnNewsgroupPostarticle ()
{
if (!check_server_posting_allowed())
return;
ASSERT (m_curNewsgroupID);
TPostTemplate *pTemplate = gptrApp->GetPostTemplate ();
pTemplate->m_iFlags = TPT_TO_NEWSGROUP | TPT_CANCEL_WARNING_ID | TPT_POST;
pTemplate->m_NewsGroupID = GetCurNewsGroupID();
pTemplate->m_iCancelWarningID = IDS_WARNING_POSTCANCEL;
pTemplate->Launch (GetCurNewsGroupID());
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdatePostSelected(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// ------------------------------------------------------------------------
void CNewsView::OnPostSelected()
{
CListCtrl & lc = GetListCtrl();
// check if posting is allowed to this server
if (!check_server_posting_allowed())
return;
// make template
TPostTemplate *pTemplate = gptrApp->GetPostTemplate ();
// get selected group IDs
int iSel = lc.GetSelectedCount ();
if (iSel <= 0)
{
ASSERT (0);
return;
}
int * pIndices = new int [iSel];
auto_ptr<int> pDeleterIndices (pIndices);
// get selected items
int n = 0;
POSITION pos = lc.GetFirstSelectedItemPosition ();
while (pos)
pIndices[n++] = lc.GetNextSelectedItem (pos);
bool fCurGroupInSelection = false;
pTemplate->m_rNewsgroups.RemoveAll ();
for (int i = 0; i < iSel; i++)
{
LONG gid = lc.GetItemData (pIndices [i]);
if (m_curNewsgroupID == gid)
fCurGroupInSelection = true;
pTemplate->m_rNewsgroups.Add (gid);
}
// utilize Per-Group e-mail address override w.r.t. which Group?
if (1 == iSel)
pTemplate->m_NewsGroupID = lc.GetItemData (pIndices[0]);
else
pTemplate->m_NewsGroupID = (fCurGroupInSelection) ? m_curNewsgroupID : 0 ;
// fill in rest of template and launch
pTemplate->m_iFlags = TPT_TO_NEWSGROUPS | TPT_CANCEL_WARNING_ID | TPT_POST;
pTemplate->m_iCancelWarningID = IDS_WARNING_POSTCANCEL;
pTemplate->Launch (pTemplate->m_NewsGroupID);
}
// ------------------------------------------------------------------------
void CNewsView::OnArticleFollowup ()
{
TServerCountedPtr cpNewsServer;
CString followUps;
TArticleText * pArtText = static_cast<TArticleText*>(m_pBrowsePaneText);
// get article on demand if we need it. I would like the TPostDoc to
// get the article, but the check for "followup-to: poster" already
// requires it early.
if (true)
{
int stat;
BOOL fUseLock;
TNewsGroup * pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (!fUseLock)
return;
BOOL fMarkAsRead = gpGlobalOptions->GetRegSwitch()->GetMarkReadFollowup();
if (0 == pArtText)
{
TError sErrorRet;
CPoint ptPartID(0,0);
TArticleText * pReturnArticleText = 0;
stat = fnFetchBody (sErrorRet,
pNG,
(TArticleHeader *) m_pBrowsePaneHeader,
pReturnArticleText,
ptPartID,
fMarkAsRead, // mark-as-read
TRUE); // Try from newsfeed
if (0 == stat)
{
SetBrowseText ( pReturnArticleText );
pArtText = pReturnArticleText;
}
else
{
CString str; str.LoadString (IDS_ERR_COULD_NOT_RETRIEVE);
NewsMessageBox ( this, str, MB_ICONSTOP | MB_OK );
return;
}
}
else
{ // it's local
TArticleHeader* pArtHdr = (TArticleHeader* ) m_pBrowsePaneHeader;
if (pArtHdr && fMarkAsRead)
pNG->ReadRangeAdd ( pArtHdr );
}
}
BOOL fPostWithCC = FALSE;
// check for "followup-to: poster"
pArtText->GetFollowup ( followUps );
followUps.TrimLeft(); followUps.TrimRight();
// Son-of-1036 indicates exact match
if ("poster" == followUps)
{
TAskFollowup dlg(this);
dlg.DoModal();
switch (dlg.m_eAction)
{
case TAskFollowup::kCancel:
return;
case TAskFollowup::kPostWithCC:
fPostWithCC = TRUE;
break;
case TAskFollowup::kSendEmail:
{
OnArticleReplybymail ();
return;
}
}
}
// Verify that server is "Posting Allowed". This check is down here since
// Followup-To: poster can morph to an e-mail message
if (!check_server_posting_allowed())
return;
ASSERT (m_curNewsgroupID);
TPostTemplate *pTemplate = gptrApp->GetFollowTemplate ();
pTemplate->m_iFlags =
TPT_TO_NEWSGROUP |
TPT_INSERT_ARTICLE |
TPT_READ_ARTICLE_HEADER |
TPT_CANCEL_WARNING_ID |
TPT_FOLLOWUP |
TPT_INIT_SUBJECT |
TPT_USE_FOLLOWUP_INTRO |
TPT_POST;
if (fPostWithCC)
pTemplate->m_iFlags |= TPT_POST_CC_AUTHOR;
pTemplate->m_NewsGroupID = m_curNewsgroupID;
pTemplate->m_iCancelWarningID = IDS_WARNING_FOLLOWUPCANCEL;
pTemplate->m_strSubjPrefix.LoadString (IDS_RE);
// lock the group while the article header and text are being accessed
BOOL fUseLock;
TNewsGroup *pNG;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (!fUseLock)
return;
TSyncReadLock sync (pNG);
// $$ MicroPlanet tech-support specific. Turn on CC
if (gpGlobalOptions->GetRegSwitch()->m_fUsePopup &&
("support" == pNG->GetName() ||
"suggest" == pNG->GetName() ||
"regstudio" == pNG->GetName()))
pTemplate->m_iFlags |= TPT_POST_CC_AUTHOR;
pTemplate->m_pArtHdr = (TArticleHeader *) m_pBrowsePaneHeader;
pTemplate->m_pArtText = (TArticleText *) m_pBrowsePaneText;
pTemplate->m_strSubject =
((TArticleHeader *) m_pBrowsePaneHeader)->GetSubject ();
pTemplate->Launch (pTemplate->m_NewsGroupID);
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateArticleFollowup(CCmdUI* pCmdUI)
{
// we must have a current article
BOOL fEnable = FALSE;
if (m_curNewsgroupID && m_pBrowsePaneHeader)
{
if (m_pBrowsePaneText)
fEnable = TRUE;
else
{
// the body is not here. But we can probably get it.
fEnable = gpTasker->IsConnected();
}
}
pCmdUI->Enable ( fEnable );
}
// ------------------------------------------------------------------------
void fnNewsView_ReplyTo (CString& strTo, CString& strFrom, TArticleText* pText)
{
// use the 'Reply-To' field if present
CString fldReplyTo;
if (pText->GetReplyTo (fldReplyTo) && !fldReplyTo.IsEmpty())
{
// RLW : 16/10/08 : The effect of these #ifdefs and
// DecodeElectronicAddress being commented out meant that
// ReplyTo: was being ignored, and the email was getting
// the email of the pervious email sent!!
// So I have removed #ifdef and ASSERT...
//#if defined(_DEBUG)
//ASSERT(0);
// RLW : 16/10/08 : removed commenting from this func...
// this function will handle the rfc2047 encoding
TArticleHeader::DecodeElectronicAddress (fldReplyTo, strTo);
// RLW : 16/10/08 : removed #endif to implement correct behaviour.
//#endif
}
else
strTo = strFrom;
}
///////////////////////////////////////////////////////////////////////////
// amc 4-2-97 Fix a deadlock problem. If you are replying to something
// you haven't read, the Pump gets it on the fly and then
// blocks on a WriteLock as it tries to mark the article
// Read. Solution - release the ReadLock we acquired in this
// function
void CNewsView::OnArticleReplybymail()
{
TServerCountedPtr cpNewsServer;
TPostTemplate *pTemplate = gptrApp->GetReplyTemplate ();
pTemplate->m_iFlags =
TPT_TO_STRING |
TPT_INSERT_ARTICLE |
TPT_READ_ARTICLE_HEADER |
TPT_CANCEL_WARNING_ID |
TPT_INIT_SUBJECT |
TPT_USE_REPLY_INTRO |
TPT_MAIL;
pTemplate->m_iCancelWarningID = IDS_WARNING_REPLYCANCEL;
pTemplate->m_strSubjPrefix.LoadString (IDS_RE);
pTemplate->m_NewsGroupID = m_curNewsgroupID;
// lock the group while the article header and text are being accessed
BOOL fUseLock;
TNewsGroup *pNG;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (!fUseLock)
return;
// protects the header object
pNG->ReadLock ();
pTemplate->m_pArtHdr = (TArticleHeader *) m_pBrowsePaneHeader;
// copy the From field
CString strFrom = pTemplate->m_pArtHdr->GetFrom ();
pTemplate->m_strSubject = pTemplate->m_pArtHdr->GetSubject ();
pTemplate->m_pArtText = (TArticleText *) m_pBrowsePaneText;
if (pTemplate->m_pArtText)
{
pNG->UnlockRead ();
}
else
{
TError sErrorRet;
CPoint ptPartID(0,0);
TArticleHeader tmpHdr(*pTemplate->m_pArtHdr);
TArticleText * pReturnArticleText = 0;
// fMarkRead will need a WriteLock !! Give it up.
pNG->UnlockRead ();
BOOL fMarkAsRead = gpGlobalOptions->GetRegSwitch()->GetMarkReadReply();
int stat = fnFetchBody ( sErrorRet,
pNG,
&tmpHdr,
pReturnArticleText,
ptPartID,
fMarkAsRead /* fMarkRead */,
TRUE /* Try newsfeed */ );
if (stat)
{
NewsMessageBox (this, IDS_ERR_COULD_NOT_RETRIEVE, MB_ICONSTOP | MB_OK);
return;
}
SetBrowseText ( pReturnArticleText );
pTemplate->m_pArtText = pReturnArticleText;
}
// setup the 'To:' field. Use the 'Reply-To' field if present
fnNewsView_ReplyTo ( pTemplate->m_strTo, strFrom,
pTemplate->m_pArtText );
// proceed
pTemplate->Launch (pTemplate->m_NewsGroupID);
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateArticleReplybymail(CCmdUI* pCmdUI)
{
if (!IsActiveServer())
{
pCmdUI->Enable (FALSE);
return;
}
TServerCountedPtr cpNewsServer;
BOOL fArticleBody = m_pBrowsePaneText ? TRUE : gpTasker->IsConnected();
pCmdUI->Enable (
!cpNewsServer->GetSmtpServer ().IsEmpty () &&
m_curNewsgroupID &&
m_pBrowsePaneHeader &&
fArticleBody
);
}
////////////////////////////////////////////////////////////////
static BOOL gbForwardingSelected; // forwarding all selected articles?
void CNewsView::OnArticleForward ()
{
TServerCountedPtr cpNewsServer;
TPostTemplate *pTemplate = gptrApp->GetForwardTemplate ();
pTemplate->m_iFlags =
TPT_CANCEL_WARNING_ID |
TPT_MAIL;
pTemplate->m_NewsGroupID = m_curNewsgroupID;
pTemplate->m_iCancelWarningID = IDS_WARNING_FORWARDCANCEL;
pTemplate->m_strSubjPrefix.LoadString (IDS_FWD);
pTemplate->m_iFlags |=
gbForwardingSelected ? (TPT_INSERT_SELECTED_ARTICLES | TPT_INIT_SUBJECT) :
(TPT_READ_ARTICLE_HEADER | TPT_INSERT_ARTICLE | TPT_INIT_SUBJECT);
// put this newsgroup's name in the template's "extra text file" field
{
BOOL fUseLock;
TNewsGroup *pNG;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (!fUseLock)
return;
pTemplate->m_strExtraTextFile = pNG->GetName ();
}
// when forwarding, don't wrap, don't quote, ignore the line limit, and
// insert the special prefix message
pTemplate->m_iFlags |= TPT_DONT_WRAP | TPT_DONT_QUOTE |
TPT_IGNORE_LINE_LIMIT | TPT_USE_FORWARD_INTRO;
if (!gbForwardingSelected) {
// lock the group while the article header and text are being accessed
BOOL fUseLock;
TNewsGroup *pNG;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (!fUseLock)
return;
TSyncReadLock sync (pNG);
pTemplate->m_pArtHdr = (TArticleHeader *) m_pBrowsePaneHeader;
pTemplate->m_pArtText = (TArticleText *) m_pBrowsePaneText;
pTemplate->m_strSubject =
((TArticleHeader *) m_pBrowsePaneHeader)->GetSubject ();
}
else {
// get the subject from the first selected article
TThreadListView *pView = GetThreadView ();
ASSERT (pView);
TArticleHeader *pHeader = NULL;
pView->GetFirstSelectedHeader ((TPersist822Header *&) pHeader);
ASSERT (pHeader);
pTemplate->m_strSubject = pHeader->GetSubject ();
}
pTemplate->Launch (pTemplate->m_NewsGroupID);
gbForwardingSelected = FALSE;
}
////////////////////////////////////////////////////////////////
void CNewsView::OnForwardSelectedArticles ()
{
gbForwardingSelected = TRUE;
OnArticleForward ();
}
void CNewsView::OnUpdateForwardSelectedArticles (CCmdUI* pCmdUI)
{
TServerCountedPtr cpNewsServer;
const CString & host = cpNewsServer->GetSmtpServer();
if (!host.IsEmpty() && m_curNewsgroupID &&
m_pBrowsePaneHeader && m_pBrowsePaneText)
pCmdUI->Enable (TRUE);
else
pCmdUI->Enable (FALSE);
}
///////////////////////////////////////////////////
void CNewsView::SetBrowseText(TPersist822Text* pText)
{
delete m_pBrowsePaneText;
m_pBrowsePaneText = pText;
}
TPersist822Text * CNewsView::GetBrowseText(void)
{
//ASSERT(m_pBrowsePaneArticle);
return m_pBrowsePaneText;
}
///////////////////////////////////////////////////
void CNewsView::SetBrowseHeader(TPersist822Header* pHdr)
{
m_pBrowsePaneHeader = pHdr;
}
TPersist822Header * CNewsView::GetBrowseHeader(void)
{
//ASSERT(m_pBrowsePaneArticle);
return m_pBrowsePaneHeader;
}
///////////////////////////////////////////////////
void CNewsView::SetCurNewsGroupID(LONG id)
{
m_curNewsgroupID = id;
}
LONG CNewsView::GetCurNewsGroupID(void)
{
return m_curNewsgroupID;
}
void CNewsView::OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView)
{
// TODO: Add your specialized code here and/or call the base class
if (bActivate)
{
SetFocus ();
// let the mdichild window know that we have the focus
((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame()->PostMessage ( WMU_CHILD_FOCUS, 0, 0L );
}
// IMHO this vvv is bullshit -al
//BASE_CLASS::OnActivateView(bActivate, pActivateView, pDeactiveView);
}
// This is public, so the threadView can route msgs through us
BOOL CNewsView::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
{
// TODO: Add your specialized code here and/or call the base class
return BASE_CLASS::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}
////////////////////////////////////////////////////////////////////
// Note: the Deregister also happens when we destroy & recreate the
// layout configuration
void CNewsView::OnDestroy()
{
// save off status before we shut down
{
if (IsActiveServer())
{
TServerCountedPtr cpNewsServer;
BOOL fUseLock;
TNewsGroup* pOld = 0;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pOld);
if (fUseLock)
{
if (pOld && (pOld->GetDirty()) )
pOld->TextRangeSave();
// close the current newsgroup
if (pOld->IsOpen())
pOld->Close();
}
}
}
SaveColumnSettings();
// m_fPinFilter doesn't need to be written. it is saved immediately on Toggl
BASE_CLASS::OnDestroy();
}
//-------------------------------------------------------------------------
// PropertyPage
void CNewsView::OnNgpopupProperties()
{
int idx = GetSelectedIndex ();
if (idx < 0)
return;
LONG id = (LONG)GetListCtrl().GetItemData(idx);
TServerCountedPtr cpNewsServer;
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, id, &fUseLock, pNG);
if (!fUseLock)
return;
TNewsGroup::EStorageOption eOldStorage = UtilGetStorageOption (pNG);
TNewGroupGeneralOptions pgGeneral;
TPurgePage pgPurge;
TNewsGroupOverrideOptions pgOverride;
TNewsGroupFilterPage pgFilter;
TSigPage pgSignature;
pgGeneral.m_kStorageOption = pgGeneral.m_iOriginalMode = (int) eOldStorage;
pNG->GetServerBounds ( pgGeneral.m_iServerLow, pgGeneral.m_iServerHi );
int iHiRead = 0;
if (pNG->GetHighestReadArtInt (&iHiRead))
pgGeneral.m_iHighestArticleRead = iHiRead;
pgGeneral.m_lowWater = pNG->GetLowwaterMark();
pgGeneral.m_nickname = pNG->GetNickname ();
pgGeneral.m_bSample = pNG->IsSampled ();
pgGeneral.m_fInActive = pNG->IsActiveGroup() ? FALSE : TRUE ;
//pgGeneral.m_fUseGlobalStorageOptions = pNG->UseGlobalStorageOptions ();
pgGeneral.m_fCustomNGFont = FALSE;
pgGeneral.m_strGroupName = pNG->GetName ();
if (gpGlobalOptions->IsCustomNGFont())
{
CopyMemory (&pgGeneral.m_ngFont, gpGlobalOptions->GetNewsgroupFont(), sizeof(LOGFONT));
pgGeneral.m_newsgroupColor = gpGlobalOptions->GetRegFonts()->GetNewsgroupFontColor();
pgGeneral.m_fCustomNGFont = TRUE;
}
else
CopyMemory (&pgGeneral.m_ngFont, &gpGlobalOptions->m_defNGFont, sizeof(LOGFONT));
TBackgroundColors *pBackgrounds = gpGlobalOptions->GetBackgroundColors ();
pgGeneral.m_newsgroupBackground = pBackgrounds->GetNewsgroupBackground();
pgGeneral.m_fDefaultBackground = gpGlobalOptions->GetRegSwitch()->IsDefaultNGBG();
pgPurge.m_fOverride = pNG->IsPurgeOverride();
pgPurge.m_fPurgeRead = UtilGetPurgeRead(pNG);
pgPurge.m_iReadLimit = UtilGetPurgeReadLimit(pNG);
pgPurge.m_fPurgeUnread = UtilGetPurgeUnread(pNG);
pgPurge.m_iUnreadLimit = UtilGetPurgeUnreadLimit(pNG);
pgPurge.m_fOnHdr = UtilGetPurgeOnHdrs(pNG);
pgPurge.m_iDaysHdrPurge= UtilGetPurgeOnHdrsEvery(pNG);
pgPurge.m_fShutdown = UtilGetCompactOnExit(pNG);
pgPurge.m_iShutCompact = UtilGetCompactOnExitEvery(pNG);
pgOverride.m_bOverrideCustomHeaders = pNG->GetOverrideCustomHeaders ();
pgOverride.m_bOverrideEmail = pNG->GetOverrideEmail ();
pgOverride.m_bOverrideFullName = pNG->GetOverrideFullName ();
pgOverride.m_bOverrideDecodeDir = pNG->GetOverrideDecodeDir ();
pgOverride.m_fOverrideLimitHeaders = pNG->GetOverrideLimitHeaders ();
pgOverride.m_strDecodeDir = pNG->GetDecodeDir ();
pgOverride.m_strEmail = pNG->GetEmail ();
pgOverride.m_strFullName = pNG->GetFullName ();
CopyCStringList (pgOverride.m_sCustomHeaders, pNG->GetCustomHeaders ());
pgOverride.m_iHeaderLimit = pNG->GetHeadersLimit ();
// newsgroup filter page
pgFilter.m_iFilterID = pNG->GetFilterID();
pgFilter.m_fOverrideFilter = pgFilter.m_iFilterID != 0;
// newsgroup signature page
pgSignature.m_fCustomSig = pNG->GetUseSignature();
pgSignature.m_strShortName = pNG->GetSigShortName();
CPropertySheet newsgroupProperties(pNG->GetName ());
int iRC;
newsgroupProperties.AddPage (&pgGeneral);
newsgroupProperties.AddPage (&pgPurge);
newsgroupProperties.AddPage (&pgOverride);
newsgroupProperties.AddPage (&pgFilter);
newsgroupProperties.AddPage (&pgSignature);
iRC = newsgroupProperties.DoModal ();
if (IDOK == iRC)
{
#if defined(_DEBUG) && defined(VERBOSE)
CString msg; msg.Format("SrHi= %d; SrLo= %d; HiRead=%d",
pgGeneral.m_iServerHi,
pgGeneral.m_iServerLow,
pgGeneral.m_iHighestArticleRead);
MessageBox (msg);
#endif
pNG->SetNickname (pgGeneral.m_nickname);
pNG->Sample (pgGeneral.m_bSample);
sync_caption();
if (pgGeneral.m_iHighestArticleRead != pgGeneral.m_iHighestArticleRead0)
{
// user has chosen to go back!
int iLowWater = pNG->GetLowwaterMark ();
if (pgGeneral.m_iHighestArticleRead < iLowWater)
pNG->SetLowwaterMark (pgGeneral.m_iHighestArticleRead);
pNG->ResetHighestArticleRead (pgGeneral.m_iHighestArticleRead,
pgGeneral.m_iHighestArticleRead0);
// if user changed the GoBack, then we should save this
cpNewsServer->SaveReadRange ();
}
pNG->SetStorageOption (TNewsGroup::EStorageOption(pgGeneral.m_kStorageOption));
pNG->SetUseGlobalStorageOptions (/*pgGeneral.m_fUseGlobalStorageOptions*/FALSE);
gpGlobalOptions->CustomNGFont (pgGeneral.m_fCustomNGFont);
gpGlobalOptions->GetRegSwitch()->SetDefaultNGBG(pgGeneral.m_fDefaultBackground);
pBackgrounds->SetNewsgroupBackground(pgGeneral.m_newsgroupBackground);
gpGlobalOptions->GetRegFonts()->SetNewsgroupFontColor( pgGeneral.m_newsgroupColor );
if (pgGeneral.m_fCustomNGFont)
gpGlobalOptions->SetNewsgroupFont ( &pgGeneral.m_ngFont );
pNG->SetActiveGroup (!pgGeneral.m_fInActive);
pNG->SetPurgeOverride(pgPurge.m_fOverride);
pNG->SetPurgeRead(pgPurge.m_fPurgeRead);
pNG->SetPurgeReadLimit(pgPurge.m_iReadLimit);
pNG->SetPurgeUnread(pgPurge.m_fPurgeUnread);
pNG->SetPurgeUnreadLimit(pgPurge.m_iUnreadLimit);
pNG->SetPurgeOnHdrs(pgPurge.m_fOnHdr);
pNG->SetPurgeOnHdrsEvery(pgPurge.m_iDaysHdrPurge);
pNG->SetCompactOnExit(pgPurge.m_fShutdown);
pNG->SetCompactOnExitEvery(pgPurge.m_iShutCompact);
pNG->SetOverrideCustomHeaders (pgOverride.m_bOverrideCustomHeaders);
pNG->SetOverrideEmail (pgOverride.m_bOverrideEmail);
pNG->SetOverrideFullName (pgOverride.m_bOverrideFullName);
pNG->SetOverrideDecodeDir (pgOverride.m_bOverrideDecodeDir);
pNG->SetOverrideLimitHeaders (pgOverride.m_fOverrideLimitHeaders);
pNG->SetDecodeDir (pgOverride.m_strDecodeDir);
pNG->SetEmail (pgOverride.m_strEmail);
pNG->SetFullName (pgOverride.m_strFullName);
pNG->SetCustomHeaders (pgOverride.m_sCustomHeaders);
pNG->SetHeadersLimit (pgOverride.m_iHeaderLimit);
// destroy stuff if we transition from (Mode 2,3)->(Mode 1)
if ((TNewsGroup::kHeadersOnly == eOldStorage ||
TNewsGroup::kStoreBodies == eOldStorage) &&
TNewsGroup::kNothing == UtilGetStorageOption (pNG))
{
if (pNG->m_GroupID == m_curNewsgroupID)
{
// probably lots of articles have been removed
EmptyBrowsePointers ();
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
// empty out thread list
pNG->Empty ();
}
// destroy headers for which there are no bodies
// -- what do we have to lock down?
pNG->StorageTransition (eOldStorage);
}
// associated filter
if (pgFilter.m_fOverrideFilter)
pNG->SetFilterID (pgFilter.m_iFilterID);
else
pNG->SetFilterID (0);
pNG->SetUseSignature (pgSignature.m_fCustomSig);
pNG->SetSigShortName (pgSignature.m_strShortName);
// if user changed the GoBack, then we should save this
// "this is done above" cpNewsServer->SaveReadRange ();
// make it last
cpNewsServer->SaveIndividualGroup ( pNG );
gpStore->SaveGlobalOptions ();
CMDIChildWnd * pMDIChild;
CMDIFrameWnd * pMDIFrame = (CMDIFrameWnd*) AfxGetMainWnd();
// note this is only 1 of the mdi children. could be more.
// we aren't handling them.
pMDIChild = pMDIFrame->MDIGetActive();
// apply the new ng font
pMDIChild->PostMessage ( WMU_NEWSVIEW_NEWFONT );
GetListCtrl().DeleteItem (idx);
// use name or nickname
if (0==AddStringWithData (pNG->GetBestname(), pNG->m_GroupID, &idx))
SetOneSelection (idx);
} // IDOK == DoModal()
}
// -------------------------------------------------------------------------
static void MicroplanetDoesntLikeSpamBlockingAddresses ()
{
TServerCountedPtr pServer;
CString strAddress = pServer->GetEmailAddress ();
strAddress.MakeUpper ();
if (strAddress.Find ("SPAM") >= 0 ||
strAddress.Find ("REMOVE") >= 0 ||
strAddress.Find ("DELETE") >= 0)
MsgResource (IDS_MICROPLANET_DOESNT_LIKE_SPAM);
}
// -------------------------------------------------------------------------
void CNewsView::ComposeMessage ()
{
// if mailing to microplanet, check the from address for spam-blocking
if (giMessageType == MESSAGE_TYPE_SUGGESTION ||
giMessageType == MESSAGE_TYPE_BUG)
MicroplanetDoesntLikeSpamBlockingAddresses ();
TPostTemplate *pTemplate =
giMessageType == MESSAGE_TYPE_BUG ? gptrApp->GetBugTemplate () :
(giMessageType == MESSAGE_TYPE_SUGGESTION ?
gptrApp->GetSuggestionTemplate () :
gptrApp->GetSendToFriendTemplate ());
pTemplate->m_strSubjPrefix = "";
pTemplate->m_iFlags = TPT_CANCEL_WARNING_ID | TPT_INIT_SUBJECT | TPT_MAIL;
switch (giMessageType) {
case MESSAGE_TYPE_BUG:
pTemplate->m_iFlags |= TPT_TO_STRING | TPT_INSERT_MACHINEINFO;
pTemplate->m_iCancelWarningID = IDS_WARNING_BUGCANCEL;
pTemplate->m_strSubject.LoadString (IDS_BUG_REPORT);
#if defined(KISS) || defined(KISS_TRIAL)
pTemplate->m_strTo.LoadString (IDS_SUPPORT_KISS);
#else
pTemplate->m_strTo.LoadString (IDS_SUPPORT_ADDR);
#endif
break;
case MESSAGE_TYPE_SUGGESTION:
pTemplate->m_iFlags |= TPT_TO_STRING;
pTemplate->m_iCancelWarningID = IDS_WARNING_SUGGESTCANCEL;
pTemplate->m_strSubject.LoadString (IDS_NEWS32_SUGGESTION);
pTemplate->m_strTo.LoadString (IDS_SUGGEST_ADDR);
break;
case MESSAGE_TYPE_SEND_TO_FRIEND:
{
TPath appFilespec;
CString & infoFilename = pTemplate->m_strExtraTextFile;
pTemplate->m_iCancelWarningID = IDS_WARNING_MESSAGECANCEL;
pTemplate->m_strSubject.LoadString (IDS_NEWS32_INFORMATION);
pTemplate->m_iFlags |= TPT_INSERT_FILE;
// look in the App's directory
infoFilename.LoadString (IDS_INFO_FILE);
TFileUtil::UseProgramPath(infoFilename, appFilespec);
pTemplate->m_strExtraTextFile = appFilespec;
break;
}
default:
ASSERT (0);
break;
}
pTemplate->Launch ( 0 /* newsgroupID */);
}
// ------------------------------------------------------------------------
//void CNewsView::OnHelpSendBugReport()
//{
// giMessageType = MESSAGE_TYPE_BUG;
// ComposeMessage ();
//}
// ------------------------------------------------------------------------
//void CNewsView::OnUpdateHelpSendBugReport (CCmdUI* pCmdUI)
//{
// TServerCountedPtr cpNewsServer;
//
// const CString & host = cpNewsServer->GetSmtpServer();
// if (!host.IsEmpty())
// pCmdUI->Enable (TRUE);
// else
// pCmdUI->Enable (FALSE);
//}
// ------------------------------------------------------------------------
//void CNewsView::OnHelpSendSuggestion()
//{
// giMessageType = MESSAGE_TYPE_SUGGESTION;
// ComposeMessage ();
//}
//
//// ------------------------------------------------------------------------
//void CNewsView::OnUpdateHelpSendSuggestion (CCmdUI* pCmdUI)
//{
// OnUpdateHelpSendBugReport(pCmdUI);
//}
// ------------------------------------------------------------------------
void CNewsView::OnSendToFriend()
{
giMessageType = MESSAGE_TYPE_SEND_TO_FRIEND;
ComposeMessage ();
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateSendToFriend (CCmdUI* pCmdUI)
{
TServerCountedPtr cpNewsServer;
const CString & host = cpNewsServer->GetSmtpServer();
if (!host.IsEmpty())
pCmdUI->Enable (TRUE);
else
pCmdUI->Enable (FALSE);
}
// ------------------------------------------------------------------------
// Keep trying to set the Caption on the mdichild
void CNewsView::OnTimer(UINT nIDEvent)
{
if (idCaptionTimer == nIDEvent)
{
if (sync_caption())
{
KillTimer ( m_hCaptionTimer );
m_hCaptionTimer = 0;
}
}
else if (CNewsView::idSelchangeTimer == nIDEvent)
{
// this is related to 1-click open NG
stop_selchange_timer ();
//TRACE("SelchangeTimer popped\n");
PostMessage (WMU_SELCHANGE_OPEN);
}
BASE_CLASS::OnTimer(nIDEvent);
}
///////////////////////////////////////////////////////////////////////////
// Get the name of the current NG and set the CDocument title. This
// will set the caption on the MDI window.
//
BOOL CNewsView::sync_caption()
{
TNewsGroup* pNG = 0;
LONG id = m_curNewsgroupID;
CString title;
TServerCountedPtr cpNewsServer;
TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray();
TNewsGroupArrayReadLock ngMgr(vNewsGroups);
if (0 == vNewsGroups->GetSize() || (0==id))
{
title.Empty ();
}
else
{
BOOL fUseLock;
TNewsGroupUseLock useLock(cpNewsServer, id, &fUseLock, pNG);
if (!fUseLock)
{
title.Empty ();
}
else
{
title = cpNewsServer->GetNewsServerName() + "/" + pNG->GetBestname();
}
}
// Documents have titles too!
GetDocument()->SetTitle ( title );
return TRUE;
}
/////////////////////////////////////////////////////////////////////
// GotoArticle - Jump to a specific group/article pair.
//
// return 0 if loaded, 1 if started download
//
LRESULT CNewsView::GotoArticle (WPARAM wParam, LPARAM lParam)
{
CListCtrl & lc = GetListCtrl ();
TServerCountedPtr cpNewsServer;
// find the newsgroup in the listbox, set selection, and
// call OpenNewsgroup
int iOpenRet = 0;
TGotoArticle *pGoto = (TGotoArticle *) lParam;
BOOL fOpened = FALSE;
int iRet = -1;
int count = lc.GetItemCount ();
for (int i = 0; i < count; i++)
{
if (pGoto->m_groupNumber == (int)lc.GetItemData (i))
{
#if 1
// the search dialog has logic to force a filter change (via
// WMU_FORCE_FILTER_CHANGE
#else
// set the view filter to the least restrictive one... ???? don't need
// to restrict filter if article is compatible with current filter set
gpUIMemory->SetViewFilter (0);
#endif
// ???? might need to optimize for newsgroup is current one somehow
// potentially by passing in the status of the message so
// that it can be compared against the current filter
// if we need to jump to a different NG, or we are about to utilize
// the 'All Articles' filter, then Open the newsgroup
if (m_curNewsgroupID != pGoto->m_groupNumber || pGoto->m_byOpenNG)
{
if (pGoto->m_byDownloadNG)
{
// this is useful for newsurl support. DL a newly subscribed NG.
iRet = iOpenRet = OpenNewsgroup ( kFetchOnZero, kCurrentFilter, pGoto->m_groupNumber);
}
else
iRet = iOpenRet = OpenNewsgroup ( kOpenNormal, kCurrentFilter, pGoto->m_groupNumber);
}
if (iRet >= 0)
{
this->AddOneClickGroupInterference ();
SetOneSelection (i);
}
else
{
SetOneSelection (i);
}
break;
}
}
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (fUseLock)
{
switch (UtilGetStorageOption ( pNG ))
{
case TNewsGroup::kNothing:
m_GotoArticle = *pGoto;
break;
case TNewsGroup::kHeadersOnly:
case TNewsGroup::kStoreBodies:
EmptyBrowsePointers ();
GetDocument()->UpdateAllViews(this, VIEWHINT_GOTOARTICLE, pGoto);
break;
default:
ASSERT(0);
break;
}
}
return iOpenRet;
}
/////////////////////////////////////////////////////////////////////
// ProcessMailTo - Send mail to somebody.
/////////////////////////////////////////////////////////////////////
LRESULT CNewsView::ProcessMailTo (WPARAM wParam, LPARAM lParam)
{
TPostTemplate *pTemplate = gptrApp->GetMailToTemplate ();
pTemplate->m_iFlags = TPT_CANCEL_WARNING_ID | TPT_MAIL | TPT_TO_STRING;
pTemplate->m_iCancelWarningID = IDS_WARNING_MESSAGECANCEL;
pTemplate->m_strTo = (LPCTSTR) lParam;
pTemplate->Launch (GetCurNewsGroupID());
return FALSE;
}
// ---------------------------------------------------------------------
// handles WMU_NEWSVIEW_NEWFONT
void CNewsView::ApplyNewFont(void)
{
TBackgroundColors *pBackgrounds = gpGlobalOptions->GetBackgroundColors ();
if (!gpGlobalOptions->GetRegSwitch()->IsDefaultNGBG())
{
CListCtrl &lc = GetListCtrl();
lc.SetBkColor ( pBackgrounds->GetNewsgroupBackground() );
lc.SetTextBkColor ( pBackgrounds->GetNewsgroupBackground() );
}
GetListCtrl().SetTextColor (
gpGlobalOptions->GetRegFonts()->GetNewsgroupFontColor() );
LOGFONT lfCurrent;
// check against current font.
CFont* pCurCFont = GetFont();
if (pCurCFont)
pCurCFont->GetObject (sizeof(LOGFONT), &lfCurrent);
else
{
// we should always have an explicit font set.
ASSERT(0);
}
const LOGFONT* plfFontNew;
BOOL fCustom = gpGlobalOptions->IsCustomNGFont();
if (fCustom)
plfFontNew = gpGlobalOptions->GetNewsgroupFont();
else
plfFontNew = &gpGlobalOptions->m_defNGFont;
// Only if the newfont is different, do we apply it.
// 9-15-95 this may not work due to non-match on precision,
// clipping and fine points like that
if (memcmp (plfFontNew, &lfCurrent, sizeof(LOGFONT)))
{
if (m_font.m_hObject)
{
m_font.DeleteObject (); // i pray this does the detach
m_font.m_hObject = NULL;
}
m_font.CreateFontIndirect ( plfFontNew );
SetFont (&m_font, TRUE);
// m_font is cleaned up by CFont destructor.
}
}
LRESULT CNewsView::OnDisplayArtcount (WPARAM wParam, LPARAM lParam)
{
int iGroupID = (int) wParam;
if (iGroupID <= 0)
{
// redraw all
this->Invalidate ();
}
else
{
// redraw to show the Total number of new articles
RedrawByGroupID ( iGroupID );
}
return 0;
}
///////////////////////////////////////////////////////////////////////////
// The MDI window does the 4 way routing. If we really do have the focus
// save the article shown is the view pane.
void CNewsView::OnSaveToFile ()
{
BOOL fMax;
TNews3MDIChildWnd *pMDI = (TNews3MDIChildWnd *)
((CMainFrame*) AfxGetMainWnd ())->MDIGetActive (&fMax);
TMdiLayout *pLayout = pMDI->GetLayoutWnd ();
TArticleFormView *pArtView = pLayout->GetArtFormView();
pArtView->SendMessage (WM_COMMAND, ID_ARTICLE_SAVE_AS);
}
void CNewsView::OnUpdateSaveToFile (CCmdUI* pCmdUI)
{
BOOL fValid = (GetBrowseHeader () && GetBrowseText ());
pCmdUI->Enable (fValid);
}
// -------------------------------------------------------------------------
void CNewsView::OnUpdateThreadChangeToRead (CCmdUI* pCmdUI)
{
pCmdUI->Enable (FALSE);
}
// -------------------------------------------------------------------------
// this should always be disabled when the NewsView pane has focus
void CNewsView::OnThreadChangeToRead ()
{
// ChangeThreadStatusTo (TStatusUnit::kNew, FALSE);
}
void CNewsView::EmptyBrowsePointers ()
{
SetBrowseHeader (NULL);
SetBrowseText (NULL);
}
// -------------------------------------------------------------------------
// a newsgroup's headers are displayed
BOOL CNewsView::IsNewsgroupDisplayed ()
{
return m_curNewsgroupID ? TRUE : FALSE;
}
// -------------------------------------------------------------------------
// True if exactly one
bool CNewsView::IsExactlyOneNewsgroupSelected ()
{
return GetListCtrl().GetSelectedCount() == 1;
}
// -------------------------------------------------------------------------
bool CNewsView::IsOneOrMoreNewsgroupSelected ()
{
return GetListCtrl().GetSelectedCount() > 0;
}
// -------------------------------------------------------------------------
void CNewsView::OnUpdateNewsgroupUnsubscribe (CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// -------------------------------------------------------------------------
// 4-19-96 amc Changed catchup alot. So I can use any selected NG.
void CNewsView::OnUpdateNewsgroupCatchup (CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// -------------------------------------------------------------------------
void CNewsView::OnUpdateNewsgroupProperties (CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsExactlyOneNewsgroupSelected ());
}
void CNewsView::OnUpdateDisable(CCmdUI* pCmdUI)
{
pCmdUI->Enable (FALSE);
}
// -------------------------------------------------------------------------
// this is a real accelerator
void CNewsView::OnCmdTabaround()
{
((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame()->
PostMessage (WMU_CHILD_TAB, FALSE, 0);
}
// -------------------------------------------------------------------------
// this is a real accelerator
void CNewsView::OnCmdTabBack()
{
((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame()->
PostMessage (WMU_CHILD_TAB, TRUE, 0);
}
///////////////////////////////////////////////////////////////////////////
// Get articles for all subscribed newsgroups
//
void CNewsView::OnGetheadersAllGroups()
{
// get headers, (force the retrieve cycle, fUserAction)
CNewsDoc::DocGetHeadersAllGroups (true, true);
}
void CNewsView::OnUpdateGetheadersAllGroups(CCmdUI* pCmdUI)
{
BOOL fEnable = FALSE;
if (gpTasker)
fEnable = gpTasker->CanRetrieveCycle ();
pCmdUI->Enable ( fEnable );
}
///////////////////////////////////////////////////////////////////////////
// Get article headers for one group. Function does NOT map to a menu-item
//
void CNewsView::GetHeadersOneGroup()
{
if (0 == gpTasker)
return;
BOOL fCatchUp = gpGlobalOptions->GetRegSwitch()->GetCatchUpOnRetrieve();
int iGroupId = GetSelectedGroupID ();
if (LB_ERR != iGroupId)
get_header_worker (iGroupId, fCatchUp, TRUE /* get all */, 0);
}
// ------------------------------------------------------------------------
// also used by ID_VERIFY_HDRS
void CNewsView::OnUpdateGetHeadersMultiGroup(CCmdUI* pCmdUI)
{
pCmdUI->Enable (gpTasker ? IsOneOrMoreNewsgroupSelected () : false);
}
// ------------------------------------------------------------------------
// Request headers for 1 or more groups
void CNewsView::OnGetHeadersMultiGroup ()
{
// call worker function
get_header_multigroup_worker (TRUE /* fGetAllHdrs */, 0);
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateGetheaderLimited(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
OnUpdateGetHeadersMultiGroup( pCmdUI);
}
// ------------------------------------------------------------------------
// Get 'X' headers
void CNewsView::OnGetheaderLimited()
{
CPromptLimitHeaders sDlg (AfxGetMainWnd());
if (IDOK == sDlg.DoModal())
{
get_header_multigroup_worker (FALSE, sDlg.m_iCount);
}
}
// ------------------------------------------------------------------------
int CNewsView::get_header_multigroup_worker (BOOL fGetAll, int iHdrsLimit)
{
if (0 == gpTasker)
return 1;
BOOL fCatchUp = gpGlobalOptions->GetRegSwitch()->GetCatchUpOnRetrieve();
CPtrArray vec;
int iSelCount = 0;
// get info on multi selection
if (multisel_get (&vec, &iSelCount))
return 1;
for (int i = 0; i < vec.GetSize(); i++)
{
TGroupIDPair * pPair = static_cast<TGroupIDPair*>(vec[i]);
get_header_worker (pPair->id, fCatchUp, fGetAll, iHdrsLimit);
}
FreeGroupIDPairs (&vec);
return 0;
}
// ------------------------------------------------------------------------
//
int CNewsView::get_header_worker (int iGroupId,
BOOL fCatchUp,
BOOL fGetAll,
int iHdrsLimit)
{
if (LB_ERR == iGroupId)
return 1;
BOOL fConnected = gpTasker->IsConnected();
if (!fConnected)
return 1;
TServerCountedPtr cpNewsServer;
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, iGroupId, &fUseLock, pNG);
if (!fUseLock)
return 1;
if (fCatchUp)
{
CatchUp_Helper ( iGroupId, FALSE );
}
// before downloading headers Purge via Date criteria
// Master Plan:
// purge
// get headers
// refresh ui.
// If we are't connected then don't purge either [2-12-97 amc]
if (fConnected && pNG->NeedsPurge())
pNG->PurgeByDate();
gpTasker->PrioritizeNewsgroup ( pNG->GetName(), fGetAll, iHdrsLimit );
return 0;
}
// ------------------------------------------------------------------------
// OnVerifyLocalHeaders -- see if all local headers still exist on the
// server. If any have been expired, remove them from the display (reload)
void CNewsView::OnVerifyLocalHeaders ()
{
try
{
CPtrArray vec;
int iSelCount = 0;
// get info on multi selection
if (multisel_get (&vec, &iSelCount))
return;
TServerCountedPtr cpNewsServer;
for (int i = 0; i < vec.GetSize(); i++)
{
TGroupIDPair * pPair = static_cast<TGroupIDPair*>(vec[i]);
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, pPair->id, &fUseLock, pNG);
if (fUseLock && TNewsGroup::kNothing != UtilGetStorageOption (pNG))
gpTasker->VerifyLocalHeaders (pNG);
}
FreeGroupIDPairs (&vec);
}
catch(...) { /* trap all errors */ }
}
void CNewsView::OnDisplayAllArticleCounts(void)
{
// for listctrl redraw it all
Invalidate ();
}
///////////////////////////////////////////////////////////////////////////
// Created 3-24-96
// Once all the headers have been saved - re-open the newsgroup.
// 1 - this saves the user the effort of opening the NG himself
// 2 - after purging articles (during hdr retrieve) we sorta haveto
// repaint, (some articles showing in the LBX may be gone)
//
LRESULT CNewsView::OnNewsgroupHdrsDone(WPARAM wParam, LPARAM lParam)
{
TServerCountedPtr cpNewsServer;
LONG grpID = (LONG) wParam;
BOOL fUserAction = (BOOL) lParam;
if (grpID == m_curNewsgroupID)
{
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, grpID, &fUseLock, pNG);
if (fUseLock)
{
if (fUserAction)
OpenNewsgroup (kOpenNormal, kPreferredFilter, grpID);
}
}
return 0;
}
//-------------------------------------------------------------------------
//
LRESULT CNewsView::OnMode1HdrsDone(WPARAM wParam, LPARAM lParam)
{
LONG grpID = (LONG) wParam;
BOOL fOld = (lParam & 0x1) ? TRUE : FALSE;
BOOL fNew = (lParam & 0x2) ? TRUE : FALSE;
TServerCountedPtr cpNewsServer;
if (grpID == m_curNewsgroupID)
{
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, grpID, &fUseLock, pNG);
if (fUseLock)
{
if (TNewsGroup::kNothing == UtilGetStorageOption(pNG))
{
// mode 1 - Don't call OpenNewsgroup this would be an infinite loop
pNG->Mode1_Thread (fOld, fNew);
please_update_views ();
// 'GOTO' article from Search Window
if (m_GotoArticle.m_articleNumber >= 0)
{
EmptyBrowsePointers ();
GetDocument()->UpdateAllViews(this, VIEWHINT_GOTOARTICLE,
&m_GotoArticle);
m_GotoArticle.m_articleNumber = -1;
}
return 0;
}
}
}
return 0;
}
// There are no objects in the newsview you can copy
void CNewsView::OnUpdateEditCopy(CCmdUI* pCmdUI)
{
pCmdUI->Enable( FALSE );
}
// ------------------------------------------------------------------------
// subthread forces UI to show a message box
LRESULT CNewsView::OnErrorFromServer (WPARAM wParam, LPARAM lParam)
{
ASSERT(wParam);
if (wParam)
{
PTYP_ERROR_FROM_SERVER psErr = (PTYP_ERROR_FROM_SERVER)(void*)(wParam);
// Response from Server: %s
CString strReason;
strReason.Format (IDS_UTIL_SERVRESP, psErr->iRet, LPCTSTR(psErr->serverString));
TNNTPErrorDialog sDlg(this);
sDlg.m_strWhen = psErr->actionDesc;
sDlg.m_strReason = strReason;
// show fairly polished dlg box
sDlg.DoModal ();
delete psErr;
}
return TRUE;
}
void CNewsView::protected_open(TNewsGroup* pNG, BOOL fOpen)
{
TEnterCSection enter(&m_dbCritSect);
int iCount = 10;
if (fOpen)
{
TUserDisplay_UIPane sAutoDraw("Open group");
pNG->Open ();
++ iLocalOpen;
}
else
{
TUserDisplay_UIPane sAutoDraw("Close group");
ASSERT(iLocalOpen > 0);
if (iLocalOpen > 0)
{
pNG->Close ();
-- iLocalOpen;
}
}
}
//////////////////////////////////////////////////////////////////////////
// Called from OnLbxSelChange(void)
LRESULT CNewsView::OnSelChangeOpen(WPARAM wParam, LPARAM lParam)
{
//TRACE0("Start from SelChange Open\n");
OpenNewsgroup( kFetchOnZero, kPreferredFilter );
//TRACE0("Returning from SelChange Open\n");
return 0;
}
//-------------------------------------------------------------------------
// return TRUE to continue, FALSE to abort
BOOL CNewsView::check_server_posting_allowed()
{
TServerCountedPtr cpNewsServer;
if (cpNewsServer->GetPostingAllowed())
return TRUE;
CString msg;
AfxFormatString1(msg, IDS_WARN_SERVER_NOPOSTALLOWED,
(LPCTSTR) cpNewsServer->GetNewsServerName());
// are you sure you want to continue?
return (IDYES == NewsMessageBox(this, msg, MB_YESNO | MB_ICONQUESTION));
}
//-------------------------------------------------------------------------
// validate_connection -- Suppose the normal pump is busy downloading a
// binary. As the user switches to a mode-1 NG, the emergency-pump
// should be used, since the n-pump is busy. Start it up and it should
// be running when the ArticleBank needs it. It would be GROSS to
// move the connection code to when the ArticleBank calls
// gpTasker->GetRangeFor()
BOOL CNewsView::validate_connection ()
{
TServerCountedPtr cpNewsServer;
if (FALSE == gpTasker->IsConnected())
return TRUE;
else
{
// ok we are connected
if (FALSE == gpTasker->NormalPumpBusy())
return TRUE;
int iTry;
BOOL fConnected;
BOOL fContinueConnect = FALSE;
fConnected = gpTasker->SecondIsConnected ( &fContinueConnect );
if (fConnected)
return TRUE;
else
{
// since the norm-pump is running, we should have permission to
// start the e-pump
if (!fContinueConnect)
return FALSE;
iTry = gpTasker->SecondConnect ( cpNewsServer->GetNewsServerAddress() );
if (0 != iTry)
return FALSE;
return TRUE;
}
}
}
// ------------------------------------------------------------------------
// used for CatchUp and Move to Next newsgroup. Returns grpid.
BOOL CNewsView::validate_next_newsgroup (int * pGrpId, int * pIdx)
{
TServerCountedPtr cpNewsServer;
CListCtrl & lc = GetListCtrl ();
int iNext = -1;
int tot = lc.GetItemCount();
for (int i = 0; i < tot; ++i)
{
// hunt for a newsgroup we can open
if (0 == iNext)
{
int iGrpID = (int) lc.GetItemData(i);
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, iGrpID, &fUseLock, pNG);
if (fUseLock)
{
if (TNewsGroup::kNothing == UtilGetStorageOption (pNG))
{
// if we are not connected keep going
if (gpTasker->IsConnected())
{
*pGrpId = iGrpID;
*pIdx = i;
return TRUE;
}
}
else
{
*pGrpId = iGrpID;
*pIdx = i;
return TRUE;
}
}
}
// find our current guy
if (m_curNewsgroupID == (int) lc.GetItemData(i))
iNext = 0;
}
return FALSE;
}
// ------------------------------------------------------------------------
// A real public func
void CNewsView::OpenNewsgroupEx(CNewsView::EOpenMode eMode)
{
// open the selected one!
OpenNewsgroup ( eMode, kPreferredFilter );
}
// ------------------------------------------------------------------------
int CNewsView::NumSelected ()
{
return GetListCtrl().GetSelectedCount();
}
// ------------------------------------------------------------------------
// GetSelectedIDs -- takes a pointer to an integer array, and returns the
// group IDs for the selected groups
void CNewsView::GetSelectedIDs (int *piIDs, int iSize)
{
// first, fill dest array with zeros
int i = 0;
for (i = 0; i < iSize; i++)
piIDs [i] = 0;
int iNumSelected = NumSelected ();
if (iNumSelected <= 0)
return;
CListCtrl & lc = GetListCtrl();
int * piIndices = new int [iNumSelected];
auto_ptr <int> pIndicesDeleter(piIndices);
int n = 0;
POSITION pos = lc.GetFirstSelectedItemPosition ();
while (pos)
piIndices[n++] = lc.GetNextSelectedItem (pos);
for (i = 0; i < iNumSelected && i < iSize; i++)
piIDs [i] = lc.GetItemData (piIndices [i]);
}
// ------------------------------------------------------------------------
// OnUpdateKeepSampled -- enabled if any selected group is sampled
void CNewsView::OnUpdateKeepSampled(CCmdUI* pCmdUI)
{
TServerCountedPtr cpNewsServer;
BOOL bEnable = FALSE;
CPtrArray sPairs; // holds a collection of (groupID, name) pairs
int iNum = 0;
if (multisel_get (&sPairs, &iNum)) {
pCmdUI->Enable (FALSE);
return;
}
iNum = sPairs.GetSize();
for (int i = 0; i < iNum; i++) {
// get pNG
TGroupIDPair *pPair = static_cast <TGroupIDPair*> (sPairs [i]);
TNewsGroup *pNG;
BOOL fUseLock;
TNewsGroupUseLock useLock (cpNewsServer, pPair->id, &fUseLock, pNG);
if (!fUseLock)
break;
// check it
if (pNG->IsSampled ()) {
bEnable = TRUE;
break;
}
}
FreeGroupIDPairs (&sPairs);
pCmdUI->Enable (bEnable);
}
// ------------------------------------------------------------------------
void CNewsView::OnKeepSampled()
{
TServerCountedPtr cpNewsServer;
CPtrArray sPairs; // holds a collection of (groupID, name) pairs
int iNum = 0;
if (multisel_get (&sPairs, &iNum))
return;
iNum = sPairs.GetSize();
for (int i = 0; i < iNum; i++) {
// get pNG
TGroupIDPair *pPair = static_cast <TGroupIDPair*> (sPairs [i]);
TNewsGroup *pNG;
BOOL fUseLock;
TNewsGroupUseLock useLock (cpNewsServer, pPair->id, &fUseLock, pNG);
if (!fUseLock)
break;
// keep the group
pNG->Sample (FALSE);
}
FreeGroupIDPairs (&sPairs);
// redraw all
Invalidate ();
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateKeepAllSampled(CCmdUI* pCmdUI)
{
TServerCountedPtr cpNewsServer;
BOOL bEnable = FALSE;
TNewsGroupArray &vNewsGroups = cpNewsServer->GetSubscribedArray ();
int iNum = vNewsGroups->GetSize ();
for (int i = 0; i < iNum; i++) {
TNewsGroup *pNG = vNewsGroups [i];
if (pNG->IsSampled ())
bEnable = TRUE;
}
pCmdUI->Enable (bEnable);
}
// ------------------------------------------------------------------------
void CNewsView::OnKeepAllSampled()
{
TServerCountedPtr cpNewsServer;
TNewsGroupArray &vNewsGroups = cpNewsServer->GetSubscribedArray ();
int iNum = vNewsGroups->GetSize ();
for (int i = 0; i < iNum; i++) {
TNewsGroup *pNG = vNewsGroups [i];
pNG->Sample (FALSE);
}
// redraw all
Invalidate ();
}
// ------------------------------------------------------------------------
void CNewsView::OnEditSelectAll()
{
GetListCtrl().SetItemState (-1, LVIS_SELECTED, LVIS_SELECTED);
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateEditSelectAll(CCmdUI* pCmdUI)
{
pCmdUI->Enable (GetListCtrl().GetItemCount () > 0);
}
// ------------------------------------------------------------------------
void CNewsView::EmptyListbox ()
{
GetListCtrl().DeleteAllItems ();
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateDeleteSelected(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// ---------------------------------------------------
void CNewsView::OnHelpResyncStati()
{
//TRACE0("Resyncing...\n");
TServerCountedPtr cpNewsServer;
LONG nGID = GetCurNewsGroupID();
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, nGID, &fUseLock, pNG);
if (!fUseLock)
return;
{
TAutoClose sCloser(pNG);
CWaitCursor cursor;
pNG->ValidateStati ();
}
// redraw all
Invalidate ();
}
// Pindown view filter
void CNewsView::OnNewsgroupPinfilter()
{
m_fPinFilter = !m_fPinFilter;
// save immediately
gpGlobalOptions->GetRegUI()->SetPinFilter( m_fPinFilter );
gpGlobalOptions->GetRegUI()->Save ();
((CMainFrame*)AfxGetMainWnd())->UpdatePinFilter ( m_fPinFilter );
}
void CNewsView::OnUpdateNewsgroupPinfilter(CCmdUI* pCmdUI)
{
pCmdUI->SetCheck ( m_fPinFilter );
}
// -------------------------------------------------------------------------
// Returns 0 for success. On success return the group-id we found.
//
int CNewsView::GetNextGroup (EJmpQuery eQuery, int * pGroupID)
{
CListCtrl & lc = GetListCtrl ();
// depends on the 'sort' order, so we have to ask the UI. ick!
int curGID = GetCurNewsGroupID();
bool fFound = false;
int nextI = 0;
for (int i = 0; i < lc.GetItemCount(); i++)
{
if (lc.GetItemData (i) == curGID)
{
nextI = i + 1;
break;
}
}
if (nextI >= lc.GetItemCount() || 0==nextI)
return 1;
TServerCountedPtr cpNewsServer; // smart pointer
for (; nextI < lc.GetItemCount(); nextI++)
{
int gid = lc.GetItemData (nextI);
BOOL fUseLock;
TNewsGroup * pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, gid, &fUseLock, pNG);
if (pNG)
{
if (pNG->QueryExistArticle (eQuery))
{
*pGroupID = gid;
return 0;
}
}
}
return 1; // no matching group found
}
BOOL CNewsView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Add your specialized code here and/or call the base class
cs.style &= ~(LVS_ICON | LVS_SMALLICON | LVS_LIST);
cs.style |= LVS_REPORT | LVS_NOSORTHEADER | LVS_SORTASCENDING
| LVS_SHOWSELALWAYS;
return BASE_CLASS::PreCreateWindow(cs);
}
// ------------------------------------------------------------------------
int CNewsView::AddStringWithData (const CString & groupName,
LONG lGroupID,
int * pIdxAt /* =NULL */)
{
CListCtrl & lc = GetListCtrl();
int idx;
LVITEM lvi; ZeroMemory (&lvi, sizeof(lvi));
lvi.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE;
lvi.iItem = lc.GetItemCount();
lvi.iSubItem = 0;
lvi.iImage = I_IMAGECALLBACK;
lvi.pszText = LPTSTR(LPCTSTR(groupName));
// lvi.state |= INDEXTOOVERLAYMASK(1);
// lvi.stateMask = LVIS_OVERLAYMASK;
lvi.lParam = lGroupID;
if (-1 == (idx = lc.InsertItem ( &lvi)))
return 1; //fail
// local count, server count
lc.SetItemText (idx, 1, LPSTR_TEXTCALLBACK);
lc.SetItemText (idx, 2, LPSTR_TEXTCALLBACK);
if (pIdxAt)
*pIdxAt = idx;
return 0; // success
}
// ------------------------------------------------------------------------
int CNewsView::SetOneSelection (int idx)
{
CListCtrl & lc = GetListCtrl();
// note: in case the SELCHANGE notification is hooked, do not
// - turn off selection on all
// - turn on selection on the index we want. (It may cause a
// one-click group to re-open)
for (int i = 0; i < lc.GetItemCount(); i++)
{
if (i == idx)
{
// select this guy
lc.SetItemState (idx, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
}
else
{
// deselect all
lc.SetItemState (i, 0, LVIS_SELECTED | LVIS_FOCUSED);
}
}
// this useful thing is provided by MFC
lc.EnsureVisible (idx, TRUE /* fPartialOK */);
// success
return 0;
}
// ---------------------------------------------------------------------
// called from OnCreate
void CNewsView::SetupFont ()
{
TBackgroundColors *pBackgrounds = gpGlobalOptions->GetBackgroundColors ();
COLORREF ngCR = pBackgrounds->GetNewsgroupBackground();
if (!gpGlobalOptions->GetRegSwitch()->IsDefaultNGBG())
{
CListCtrl &lc = GetListCtrl();
lc.SetBkColor ( pBackgrounds->GetNewsgroupBackground() );
lc.SetTextBkColor ( pBackgrounds->GetNewsgroupBackground() );
}
ngCR = gpGlobalOptions->GetRegFonts()->GetNewsgroupFontColor();
GetListCtrl().SetTextColor (ngCR);
if (0 == gpGlobalOptions->m_defNGFont.lfFaceName[0])
{
// show this info in the config dialog box
gpVariableFont->GetObject ( sizeof (LOGFONT), &gpGlobalOptions->m_defNGFont );
}
if (m_font.m_hObject)
{
m_font.DeleteObject (); // i pray this does the detach
m_font.m_hObject = NULL;
}
if (gpGlobalOptions->IsCustomNGFont())
m_font.CreateFontIndirect ( gpGlobalOptions->GetNewsgroupFont() );
else
{
// default to microplanet defined small font
LOGFONT info;
gpVariableFont->GetObject ( sizeof (info), &info );
m_font.CreateFontIndirect ( &info );
}
SetFont ( &m_font );
}
// --------------------------------------------------------------------------
void CNewsView::OnGetDisplayInfo(NMHDR* pNMHDR, LRESULT* pResult)
{
LV_DISPINFO * pDispInfo = (LV_DISPINFO*)pNMHDR;
if (!IsActiveServer())
{
*pResult = 0;
return;
}
LVITEM & lvi = pDispInfo->item;
TServerCountedPtr cpNewsServer;
TNewsGroup * pNG = 0;
BOOL fUseLock;
LONG gid = LONG(GetListCtrl().GetItemData (lvi.iItem));
TNewsGroupUseLock useLock(cpNewsServer, gid, &fUseLock, pNG);
if (fUseLock)
{
if (lvi.mask & LVIF_IMAGE)
{
switch (pNG->GetStorageOption())
{
case TNewsGroup::kNothing:
lvi.iImage = 0;
break;
case TNewsGroup::kHeadersOnly:
lvi.iImage = 1;
break;
case TNewsGroup::kStoreBodies:
lvi.iImage = 2;
break;
}
if (pNG->IsSampled ())
lvi.iImage += 3;
}
if (lvi.mask & LVIF_STATE)
{
if (!pNG->IsActiveGroup())
lvi.state |= INDEXTOOVERLAYMASK(1);
}
if (lvi.mask & LVIF_TEXT)
{
int iLocalNew, iServerNew, nTotal;
pNG->FormatNewArticles ( iLocalNew, iServerNew , nTotal);
if (1 == lvi.iSubItem)
wsprintf (lvi.pszText, "%d", iLocalNew);
else if (2 == lvi.iSubItem)
wsprintf (lvi.pszText, "%d", iServerNew);
// data eventuall is displayed in status bar pane
if (GetCurNewsGroupID() == gid)
gpUserDisplay->SetCountTotal ( nTotal );
}
}
*pResult = 0;
}
///////////////////////////////////////////////////////////////////////////
// Depends on user preference - single click/selchange opens a newsgroup
//
void CNewsView::OnClick (NMHDR* pNMHDR, LRESULT* pResult)
{
//TRACE0("On Click\n");
if (gpGlobalOptions->GetRegUI()->GetOneClickGroup() &&
(1 == GetListCtrl().GetSelectedCount()))
{
// turn off delayed activation. Actually this is futile, since
// NM_ITEMCHANGE will start the timer again
stop_selchange_timer();
AddOneClickGroupInterference();
PostMessage (WMU_SELCHANGE_OPEN);
}
*pResult = 0;
}
///////////////////////////////////////////////////////////////////////////
void CNewsView::AddOneClickGroupInterference ()
{
if (gpGlobalOptions->GetRegUI()->GetOneClickGroup())
{
m_iOneClickInterference ++;
}
}
///////////////////////////////////////////////////////////////////////////
// Substitute for LBN_SELCHANGE,
//
void CNewsView::OnItemChanged (NMHDR* pNMHDR, LRESULT* pResult)
{
*pResult = 1;
LPNMLISTVIEW pnmlv = (LPNMLISTVIEW) pNMHDR;
BOOL fNewSelect = (pnmlv->uNewState & LVIS_SELECTED);
BOOL fOldSelect = (pnmlv->uOldState & LVIS_SELECTED);
if ( fNewSelect && !fOldSelect )
{
//TRACE0("OnItemChanged\n");
if (gpGlobalOptions->GetRegUI()->GetOneClickGroup() &&
(1 == GetListCtrl().GetSelectedCount()))
{
if (m_iOneClickInterference > 0)
{
*pResult = 0;
// do not start timer!
--m_iOneClickInterference;
}
else
{
// this will pop unless:
// a: another selchange comes
// b: this turns out to be a right click
//
start_selchange_timer ();
// OnTimer will call
// PostMessage (WMU_SELCHANGE_OPEN);
// 5-25-96 Rather than calling OpenNewsgroup() directly,
// post a message to myself. That way the processing
// can finish before we start the big fat OpenNewsgroup function
*pResult = 0;
}
}
}
}
///////////////////////////////////////////////////////////////////////////
void CNewsView::OnReturn(NMHDR* pNMHDR, LRESULT* pResult)
{
// We got an VK_RETURN, so open the newsgroup
OpenNewsgroup ( kFetchOnZero, kPreferredFilter );
*pResult = 0;
}
// ------------------------------------------------------------------------
void CNewsView::OnRclick(NMHDR* pNMHDR, LRESULT* pResult)
{
// seems to set selection on Right click
// this is so we can right click on a newsgroup, an put selection on it
// with out actually opening the newsgroup via 1-click
stop_selchange_timer ();
//TRACE("Rclik stopped selchange action\n");
*pResult = 0;
}
///////////////////////////////////////////////////////////////////////////
// Depends on user preference - double click opens a newsgroup
//
void CNewsView::OnDblclk(NMHDR* pNMHDR, LRESULT* pResult)
{
if (FALSE == gpGlobalOptions->GetRegUI()->GetOneClickGroup())
OpenNewsgroup( kFetchOnZero, kPreferredFilter );
*pResult = 0;
}
// ------------------------------------------------------------------------
void CNewsView::RedrawByGroupID (int iGroupID)
{
CListCtrl & lc = GetListCtrl();
RECT rct;
int n = lc.GetItemCount();
for (--n; n >= 0; --n)
{
if (iGroupID == (int) lc.GetItemData (n))
{
lc.GetItemRect (n, &rct, LVIR_BOUNDS);
// we only need to redraw the counters
InvalidateRect (&rct);
break;
}
}
}
// ------------------------------------------------------------------------
void CNewsView::SaveColumnSettings()
{
SaveColumnSettingsTo (m_fTrackZoom ? "NGPaneZ" : "NGPane");
}
// ------------------------------------------------------------------------
void CNewsView::SaveColumnSettingsTo (const CString & strLabel)
{
TRegUI* pRegUI = gpGlobalOptions->GetRegUI();
int riWidths[3];
riWidths[0] = GetListCtrl().GetColumnWidth (0);
riWidths[1] = GetListCtrl().GetColumnWidth (1);
riWidths[2] = GetListCtrl().GetColumnWidth (2);
pRegUI->SaveUtilHeaders(strLabel, riWidths, ELEM(riWidths));
}
// ------------------------------------------------------------------------
// tnews3md.cpp does the real work. Each active view must have a
// handler for this
//
void CNewsView::OnUpdateArticleMore (CCmdUI* pCmdUI)
{
CWnd* pMdiChild = ((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame();
BOOL fOK = ((TNews3MDIChildWnd*) pMdiChild)->CanArticleMore();
pCmdUI->Enable (fOK);
}
// ------------------------------------------------------------------------
BOOL CNewsView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
// let the mdi-child decide which pane will handle this
CWnd* pMdiChild = ((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame();
if (!pMdiChild)
return FALSE;
if (((TNews3MDIChildWnd*) pMdiChild)->handleMouseWheel(nFlags, zDelta, pt))
return TRUE;
else
return handleMouseWheel (nFlags, zDelta, pt);
}
// ------------------------------------------------------------------------
// called from MDI child
BOOL CNewsView::handleMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
return BASE_CLASS::OnMouseWheel (nFlags, zDelta, pt);
}
// ------------------------------------------------------------------------
// zoom mode has its own set of column widths
void CNewsView::handle_zoom (bool fZoom, CObject* pHint)
{
int riWidths[3];
bool fApply = false;
TRegUI* pRegUI = gpGlobalOptions->GetRegUI();
if (fZoom)
{
if (pHint == this)
{
// The roles are the same, but the widths can be different
// save off normal
SaveColumnSettings ();
if (0 != pRegUI->LoadUtilHeaders("NGPaneZ", riWidths, ELEM(riWidths)))
return;
fApply = true;
m_fTrackZoom = true; // passive variable, as a convenienence
}
}
else
{
TUnZoomHintInfo * pUnZoom = static_cast<TUnZoomHintInfo *>(pHint);
if (pUnZoom->m_pTravelView == this)
{
m_fTrackZoom = false;
// save zoomed
SaveColumnSettingsTo ("NGPaneZ");
// load Normal
if (0 != pRegUI->LoadUtilHeaders("NGPane", riWidths, ELEM(riWidths)))
return;
fApply = true;
}
}
if (fApply)
{
GetListCtrl().SetColumnWidth (0, riWidths[0]);
GetListCtrl().SetColumnWidth (1, riWidths[1]);
GetListCtrl().SetColumnWidth (2, riWidths[2]);
}
}
// pCmdUI for ID_GETTAGGED_FOR_GROUPS
void CNewsView::OnUpdateGettaggedForgroups(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// ----------------------------------------------------------
// Retrieve Tagged articles only for the selected groups
void CNewsView::OnGettaggedForgroups()
{
// holds a collection of (groupID, name) pairs
CPtrArray vecPairs;
int sel = 0;
// get info on multisel
if (multisel_get (&vecPairs, &sel))
return;
int tot = vecPairs.GetSize();
// build up CDWordArray that only contains GroupIDs
CDWordArray vecIDs;
for (int i = 0; i < tot; i++)
{
TGroupIDPair* pPair = static_cast<TGroupIDPair*>(vecPairs[i]);
vecIDs.Add (pPair->id);
}
FreeGroupIDPairs (&vecPairs);
TServerCountedPtr cpServer;
cpServer->GetPersistentTags().RetrieveTagged (false, vecIDs);
}
// -------------------------------------------------------------------------
BOOL CNewsView::PreTranslateMessage(MSG* pMsg)
{
if (::IsWindow (m_sToolTips.m_hWnd) && pMsg->hwnd == m_hWnd)
{
switch (pMsg->message)
{
case WM_LBUTTONDOWN:
case WM_MOUSEMOVE:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONUP:
m_sToolTips.RelayEvent (pMsg);
break;
}
}
return BASE_CLASS::PreTranslateMessage(pMsg);
}
// -------------------------------------------------------------------------
void CNewsView::OnMouseMove(UINT nFlags, CPoint point)
{
if (!(nFlags & MK_LBUTTON) || 0 == GetListCtrl().GetSelectedCount ())
{
HandleToolTips (point);
BASE_CLASS::OnMouseMove (nFlags, point);
return;
}
BASE_CLASS::OnMouseMove(nFlags, point);
}
// -------------------------------------------------------------------------
BOOL CNewsView::OnNeedText (UINT, NMHDR *pNMHdr, LRESULT *)
{
// make sure the cursor is in the client area, because the mainframe also
// wants these messages to provide tooltips for the toolbar
CPoint sCursorPoint;
VERIFY (::GetCursorPos (&sCursorPoint));
ScreenToClient (&sCursorPoint);
CRect sClientRect;
GetClientRect (&sClientRect);
if (sClientRect.PtInRect (sCursorPoint))
{
TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *) pNMHdr;
pTTT->lpszText = (LPTSTR)(LPCTSTR) m_strToolTip;
return TRUE;
}
return FALSE;
}
// -------------------------------------------------------------------------
void CNewsView::HandleToolTips (CPoint &point)
{
static bool fDisplayed = false;
static int iDisplayedIndex;
if (!::IsWindow (m_sToolTips.m_hWnd))
return;
// get index of item under mouse
int iIndex = GetListCtrl().HitTest ( point );
if (fDisplayed)
{
if (iIndex != iDisplayedIndex)
{
m_sToolTips.Activate (FALSE);
m_strToolTip.Empty();
fDisplayed = false;
}
}
if (!fDisplayed && iIndex >= 0)
{
try
{
TServerCountedPtr cpNewsServer;
TNewsGroup * pNG = 0;
BOOL fUseLock;
LONG gid = LONG(GetListCtrl().GetItemData (iIndex));
TNewsGroupUseLock useLock(cpNewsServer, gid, &fUseLock, pNG);
if (fUseLock)
{
int nNewHdrs, nServer, nTotalHdrs;
pNG->FormatNewArticles ( nNewHdrs, nServer, nTotalHdrs );
m_strToolTip.Format ("%s\nLocal Unread: %d\nLocal Total: %d\nServer: %d",
GetListCtrl().GetItemText (iIndex, 0),
nNewHdrs, nTotalHdrs, nServer );
}
else
m_strToolTip = GetListCtrl().GetItemText (iIndex, 0);
}
catch(...)
{
m_strToolTip.Empty();
}
m_sToolTips.Activate (TRUE);
iDisplayedIndex = iIndex;
fDisplayed = true;
}
}
// -------------------------------------------------------------------------
void CNewsView::start_selchange_timer ()
{
stop_selchange_timer ();
m_hSelchangeTimer = SetTimer (CNewsView::idSelchangeTimer, 333, NULL);
}
// -------------------------------------------------------------------------
void CNewsView::stop_selchange_timer ()
{
// kill any timer currently running
if (m_hSelchangeTimer)
KillTimer (m_hSelchangeTimer);
m_hSelchangeTimer = 0;
}
// -------------------------------------------------------------------------
int CNewsView::GetPreferredFilter (TNewsGroup * pNG)
{
int iWhatFilter = pNG->GetFilterID();
if (0 == iWhatFilter)
{
TAllViewFilter * pAllFilters = gpStore->GetAllViewFilters();
iWhatFilter = pAllFilters->GetGlobalDefFilterID();
}
return iWhatFilter;
}
| 28.222278 | 152 | 0.61866 |
f98a0cdf5f2a3eee6a87ac19dbb2e18e2198ddcd | 1,283 | cpp | C++ | Tree/BalancedTree/BalancedTree.cpp | PrachieNaik/DSA | 083522bb3c8a0694adec1f2856d4d4cd0fb51722 | [
"MIT"
] | null | null | null | Tree/BalancedTree/BalancedTree.cpp | PrachieNaik/DSA | 083522bb3c8a0694adec1f2856d4d4cd0fb51722 | [
"MIT"
] | null | null | null | Tree/BalancedTree/BalancedTree.cpp | PrachieNaik/DSA | 083522bb3c8a0694adec1f2856d4d4cd0fb51722 | [
"MIT"
] | null | null | null | /*
Problem statement: Given a binary tree, find if it is height balanced or not. A tree is height balanced if difference between heights of left and right subtrees is
not more than one for all nodes of tree.
Constraints:
1<= N <= 10^4
Approach: To check if a tree is height-balanced, get the height of left and right subtrees. Return true if difference between heights is not more than 1 and left
and right subtrees are balanced, otherwise return false. Calculate the height in the same recursion rather than calling a height() function separately.
Time complexity – O(n)
*/
bool isBalancedUtil(Node *root, int *height) {
int leftHeight = 0, rightHeight = 0;
bool leftBalanced = 0, rightBalanced = 0;
if(root == NULL)
{
*height = 0;
return 1;
}
leftBalanced = isBalancedUtil(root->left, &leftHeight);
rightBalanced = isBalancedUtil(root->right, &rightHeight);
*height = max(leftHeight,rightHeight) + 1;
if( abs(leftHeight - rightHeight) >= 2 || !leftBalanced || !rightBalanced)
return 0;
return 1;
}
// This function should return tree if passed tree
// is balanced, else false.
bool isBalanced(Node *root)
{
int height = 0;
return isBalancedUtil(root,&height);
}
| 27.891304 | 163 | 0.681216 |
f98b56f403871a3056dd8284deee2b49b92ca23d | 4,718 | cpp | C++ | src/model_loading/model.cpp | clsrfish/learnogl | 3e1cc42a595dd12779268ba587ef68fa4991e1f5 | [
"Apache-2.0"
] | null | null | null | src/model_loading/model.cpp | clsrfish/learnogl | 3e1cc42a595dd12779268ba587ef68fa4991e1f5 | [
"Apache-2.0"
] | null | null | null | src/model_loading/model.cpp | clsrfish/learnogl | 3e1cc42a595dd12779268ba587ef68fa4991e1f5 | [
"Apache-2.0"
] | null | null | null | //
// model.cpp
//
// Created by Clsrfish on 08/10/2020
//
#include "./model.h"
#include "../gl/gl_utils.h"
model_loading::Model::Model(const std::string &modelPath)
{
loadModel(modelPath);
}
void model_loading::Model::Draw(const Shader &shader)
{
for (unsigned int i = 0; i < Meshes.size(); i++)
{
Meshes[i].Draw(shader);
}
}
void model_loading::Model::loadModel(const std::string &modelPath)
{
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile(modelPath.c_str(), aiProcess_Triangulate | aiProcess_FlipUVs);
if (scene == nullptr || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || scene->mRootNode == nullptr)
{
LOG_E("ASSMIP::%s", importer.GetErrorString());
return;
}
directory = modelPath.substr(0, modelPath.find_last_of('/'));
processNode(scene->mRootNode, scene);
}
void model_loading::Model::processNode(aiNode *node, const aiScene *scene)
{
for (unsigned int i = 0; i < node->mNumMeshes; i++)
{
aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
Meshes.push_back(processMesh(mesh, scene));
}
for (unsigned int i = 0; i < node->mNumChildren; i++)
{
processNode(node->mChildren[i], scene);
}
}
model_loading::Mesh model_loading::Model::processMesh(aiMesh *mesh, const aiScene *scene)
{
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
std::vector<Texture> textures;
for (unsigned int i = 0; i < mesh->mNumVertices; i++)
{
Vertex vertex;
glm::vec3 pos;
pos.x = mesh->mVertices[i].x;
pos.y = mesh->mVertices[i].y;
pos.z = mesh->mVertices[i].z;
vertex.Position = pos;
glm::vec3 normal;
normal.x = mesh->mNormals[i].x;
normal.y = mesh->mNormals[i].y;
normal.z = mesh->mNormals[i].z;
vertex.Normal = normal;
if (mesh->mTextureCoords[0])
{
glm::vec2 texCoord;
texCoord.x = mesh->mTextureCoords[0][i].x;
texCoord.y = mesh->mTextureCoords[0][i].y;
vertex.TexCoords = texCoord;
}
else
{
vertex.TexCoords = glm::vec2(0.0f, 0.0f);
}
vertices.push_back(vertex);
}
for (unsigned int i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; j++)
{
indices.push_back(face.mIndices[j]);
}
}
if (mesh->mMaterialIndex >= 0)
{
// process all materials
aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];
// 1. diffuse maps
std::vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "u_TextureDiffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
// 2. specular maps
std::vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "u_TextureSpecular");
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
// 3. normal maps
std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_NORMALS, "u_TextureNormal");
textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
// 4. height maps
std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "u_TextureHeight");
textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
}
return model_loading::Mesh(vertices, indices, textures);
}
std::vector<model_loading::Texture> model_loading::Model::loadMaterialTextures(aiMaterial *material, aiTextureType texType, const std::string &typeName)
{
std::vector<model_loading::Texture> textures;
for (unsigned int i = 0; i < material->GetTextureCount(texType); ++i)
{
aiString str;
material->GetTexture(texType, i, &str);
auto file = std::string(str.C_Str());
bool useCache = false;
for (unsigned int j = 0; j < loadedTextures.size(); j++)
{
if (file.compare(loadedTextures[j].path) == 0)
{
LOG_I("Texture loaded preciously: %s", file.c_str());
textures.push_back(loadedTextures[j]);
useCache = true;
break;
}
}
if (!useCache)
{
model_loading::Texture texture;
texture.id = TextureFromFile(file, directory);
texture.type = typeName;
texture.path = file;
textures.push_back(texture);
loadedTextures.push_back(texture);
}
}
return textures;
}
| 31.453333 | 152 | 0.602798 |
f98fc6fe889504295cefaf5aa7436bc071f81e98 | 7,042 | hpp | C++ | src/Utilities/NMatrix/NLine.hpp | fcaillaud/SARAH | ca79c7d9449cf07eec9d5cc13293ec0c128defc1 | [
"MIT"
] | null | null | null | src/Utilities/NMatrix/NLine.hpp | fcaillaud/SARAH | ca79c7d9449cf07eec9d5cc13293ec0c128defc1 | [
"MIT"
] | null | null | null | src/Utilities/NMatrix/NLine.hpp | fcaillaud/SARAH | ca79c7d9449cf07eec9d5cc13293ec0c128defc1 | [
"MIT"
] | null | null | null | /**
* \file NLine.hpp
* \author fcaillaud
* \version 1.0
* \date 2 Avril 2014
* \brief Fichier décrivant la classe NLine.
* \details Classe utilisée pour représenter une ligne ou colonne de matrice (plus ou moins un vecteur).
* \todo Réfléchir à une meilleure approche pour toute la classe.
*/
#ifndef NMATRIX_NLINE
#define NMATRIX_NLINE
#include <vector>
#include <stdlib.h>
/**
* \namespace alg
* \brief Nom de domaine tertiaire, partie utilitaire.
* \todo Migrer vers le namespace gu.
*/
namespace alg
{
/**
* \enum LineState
* \brief Type de vecteur, soit ligne, soit colonne.
*/
enum LineState
{
LS_ROW, /*!< Vecteur de type ligne. */
LS_COLUMN /*!< Vecteur de type colonne. */
};
/**
* \class NLine
* \brief Classe représentant un vecteur de matrice (soit ligne, soit colonne).
* \details Classe template avec le type Mtype qui sera le type des valeurs contenues dans le vecteur.
*/
template<class MType = double>
class NLine
{
public:
/**
* Constructeur par défaut.
* \details Construit un vecteur de taille 0.
*/
NLine():
mSize(),
mLine(),
mHasToBeAllDeleted(false)
{
//EMPTY
}
/**
* Constructeur paramétré.
* \param pSize La taille du vecteur voulu.
* \details Construit un vecteur de taille pSize.
*/
NLine(unsigned int pSize):
mSize(pSize),
mLine(new MType *[pSize]),
mHasToBeAllDeleted(true)
{
for(unsigned int i = 0; i < mSize; ++i)
mLine[i] = new MType();
}
/**
* Constructeur par copie.
* \param pLine Le vecteur à copier.
*/
NLine(const NLine & pLine):
mSize(pLine.mSize),
mLine(new MType *[pLine.mSize]),
mHasToBeAllDeleted(false)
{
for(unsigned int i = 0; i < mSize; ++i)
mLine[i] = pLine.mLine[i];
}
/**
* Constructeur par copie.
* \param pMatrixData La matrice cotenant le vecteur à copier.
* \param pInd L'indice de la ligne ou de la colonne dans la matrice.
* \param pSize Les dimensions de la matrice à copier.
* \param pLineState Le type de vecteur à copier (ligne ou colonne).
* \todo Enlever pSize, pas besoin, utiliser les dimensions de la matrice à copier.
*/
NLine(MType * pMatrixData, int pInd, std::pair<unsigned int, unsigned int> pSize, LineState pLineState):
mSize(),
mLine(),
mHasToBeAllDeleted(false)
{
if(pLineState == LS_ROW){
mSize = pSize.first;
mLine = new MType *[mSize];
for(unsigned int i = 0; i < mSize; ++i)
mLine[i] = pMatrixData + (pInd * pSize.first + i);
}else{
mSize = pSize.second;
mLine = new MType *[mSize];
for(unsigned int i = 0; i < mSize; ++i)
mLine[i] = pMatrixData + (i * pSize.first + pInd);
}
}
/**
* Destructeur
* \details Si mHasToBeAllDeleted est à false, il n'efface pas les pointeurs
* sur les valeurs stockées.
*/
~NLine()
{
if(mHasToBeAllDeleted)
for(unsigned int i = 0; i < mSize; ++i)
delete mLine[i];
delete [] mLine;
}
/**
* Récupération de la valeur à l'indice souhaité.
* \param pInd L'indice de la valeur à récupérer dans le vecteur.
* \return La valeur à l'indice pInd dans le vecteur.
*/
const MType GetAt(int pInd)
{
return *mLine[pInd];
}
/**
* Change la valeur à l'indice souhaité.
* \param pInd L'indice de la valeur à changer dans le vecteur.
* \param pData La nouvelle valeur.
*/
void SetAt(int pInd, MType pData)
{
*mLine[pInd] = pData;
}
/**
* Récupération de la valeur à l'indice souhaité.
* \param pInd L'indice de la valeur à récupérer dans le vecteur.
* \return La valeur à l'indice pInd dans le vecteur.
*/
MType operator[] (int pInd)
{
return *mLine[pInd];
}
/**
* Addition de deux vecteurs.
* \param pLine L'autre vecteur à additionner.
* \return Le vecteur résultant de l'addition.
* \details Additionne valeur par valeur.
*/
NLine operator+ (NLine pLine)
{
if(mSize != pLine.mSize){
std::cerr << "ERROR : In NLine +, the addition between two lines with different size (" << mSize << ", " << pLine.mSize << ") can't be done." << std::endl;
exit(-1);
}
NLine<MType> vLine(mSize);
for(unsigned int i = 0; i < mSize; ++i)
*(vLine.mLine[i]) = *mLine[i] + pLine[i];
return vLine;
}
/**
* Soustraction de deux vecteurs.
* \param pLine Le vecteur que l'on soustrait.
* \return Le vecteur résultant de la soustraction.
* \details Soustrait valeur par valeur.
*/
NLine operator- (NLine pLine)
{
if(mSize != pLine.mSize){
std::cerr << "ERROR : In NLine -, the substraction between two lines with different size (" << mSize << ", " << pLine.mSize << ") can't be done." << std::endl;
exit(-1);
}
NLine<MType> vLine(mSize);
for(unsigned int i = 0; i < mSize; ++i)
*(vLine.mLine[i]) = *mLine[i] - pLine[i];
return vLine;
}
/**
* Multiplication de deux vecteurs.
* \param pLine L'autre vecteur à multiplier.
* \return Le vecteur résultant de la multiplication.
* \details Multiplie valeur par valeur.
*/
double operator* (NLine pLine)
{
unsigned int vSize = pLine.mSize;
double vRes = 0.0;
if(mSize != vSize){
std::cerr << "ERROR : In NLine *, the substraction between two lines with different size (" << mSize << ", " << pLine.mSize << ") can't be done." << std::endl;
exit(-1);
}
for(unsigned int i = 0; i < vSize; ++i)
vRes += (*mLine[i]) * (*(pLine.mLine[i]));
return vRes;
}
/**
* Récupère la taille du vecteur.
* \return La taille du vecteur.
* \todo Changer le nom de la fonction pour GetSize(), plus cohérent.
*/
unsigned int Size()
{
return mSize;
}
/**
* Récupère le pointeur sur les éléments du vecteur.
* \return Le pointeur sur les éléments du vecteur.
*/
MType ** SData()
{
return mLine;
}
/**
* Ajout d'un pointeur sur valeur dans le vecteur.
* \param pData Le pointeur sur valeur à ajouter.
* \details Le vecteur s'agrandit et sa taille s'incrémente.
*/
void Add(MType * pData)
{
mSize++;
mLine = (MType *) realloc(mLine, mSize * sizeof(MType *));
mLine[mSize - 1] = pData;
}
/**
* Affichage du vecteur.
* \details Affiche sur la sortie standard les valeurs du vecteur.
* \todo Utiliser Msg (dans les autres fonction également) ET
* différencier l'affichage en colonne et en ligne.
*/
void Print()
{
for(unsigned int i = 0; i < mSize; ++i)
std::cout << *mLine[i] << " ";
}
private:
/**
* \brief Taille du vecteur.
*/
unsigned int mSize;
/**
* \brief Tableau des pointeurs sur les valeurs.
*/
MType ** mLine;
/**
* \brief État de suppression des pointeurs sur les valeurs.
*/
bool mHasToBeAllDeleted;
};
}
#endif
| 24.883392 | 164 | 0.598268 |
f9904cef11f7c0fc417b9e9970c01d5137aa5af5 | 173 | cc | C++ | HelloNDK/app/src/main/jni/hello.cc | omo/hello | 6671d45d407edfecc97520d8e652690f0e831ce8 | [
"Artistic-2.0"
] | null | null | null | HelloNDK/app/src/main/jni/hello.cc | omo/hello | 6671d45d407edfecc97520d8e652690f0e831ce8 | [
"Artistic-2.0"
] | 25 | 2015-03-30T17:49:03.000Z | 2015-10-20T19:38:32.000Z | HelloNDK/app/src/main/jni/hello.cc | omo/hello | 6671d45d407edfecc97520d8e652690f0e831ce8 | [
"Artistic-2.0"
] | null | null | null | #include <jni.h>
extern "C" jstring
Java_com_example_morrita_hellondk_MainActivity_hello(
JNIEnv* env, jobject thiz) {
return env->NewStringUTF("Hello from JNI!");
}
| 21.625 | 53 | 0.751445 |
f9950c4c127eed8eb765a4f79dff18707a5a927e | 1,141 | cpp | C++ | libs/charconv/src/charconv/fcppt_string_to_utf8_file.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/charconv/src/charconv/fcppt_string_to_utf8_file.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/charconv/src/charconv/fcppt_string_to_utf8_file.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/charconv/fcppt_string_to_utf8.hpp>
#include <sge/charconv/fcppt_string_to_utf8_file.hpp>
#include <sge/charconv/utf8_string.hpp>
#include <fcppt/string.hpp>
#include <fcppt/cast/size.hpp>
#include <fcppt/cast/to_char_ptr.hpp>
#include <fcppt/cast/to_signed.hpp>
#include <fcppt/config/external_begin.hpp>
#include <filesystem>
#include <fstream>
#include <ios>
#include <fcppt/config/external_end.hpp>
bool sge::charconv::fcppt_string_to_utf8_file(
fcppt::string const &_string, std::filesystem::path const &_path)
{
std::ofstream file(_path);
if (!file.is_open())
{
return false;
}
sge::charconv::utf8_string const result(sge::charconv::fcppt_string_to_utf8(_string));
return !file.write(
fcppt::cast::to_char_ptr<char const *>(result.c_str()),
fcppt::cast::size<std::streamsize>(fcppt::cast::to_signed(result.size())))
.fail();
}
| 31.694444 | 92 | 0.69851 |
f995a5ef4619ff65e37e0210dd58371372442922 | 158 | cpp | C++ | MathTools/Point.cpp | richardchien/math-tools-ios | 956b77d91afd7bb78dd02a5027180de72d9d6a29 | [
"MIT"
] | null | null | null | MathTools/Point.cpp | richardchien/math-tools-ios | 956b77d91afd7bb78dd02a5027180de72d9d6a29 | [
"MIT"
] | null | null | null | MathTools/Point.cpp | richardchien/math-tools-ios | 956b77d91afd7bb78dd02a5027180de72d9d6a29 | [
"MIT"
] | null | null | null | //
// Point.cpp
// MathTools
//
// Created by Richard Chien on 14-1-31.
// Copyright (c) 2014年 Richard Chien. All rights reserved.
//
#include "Point.h"
| 15.8 | 59 | 0.64557 |
f99782ab8ce1e2647442e9105642be7e009deddd | 2,724 | cpp | C++ | tcp/compute_server.cpp | sakulkar/SocketLab | 046b8cfaab66e7e037352b40793d33f8da63a68b | [
"MIT"
] | null | null | null | tcp/compute_server.cpp | sakulkar/SocketLab | 046b8cfaab66e7e037352b40793d33f8da63a68b | [
"MIT"
] | null | null | null | tcp/compute_server.cpp | sakulkar/SocketLab | 046b8cfaab66e7e037352b40793d33f8da63a68b | [
"MIT"
] | null | null | null | #include <cstdio> // perror
#include <iostream> // cout, cin
#include <cstdlib> // exit, EXIT_FAILURE
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // inet_ntoa()
#include <arpa/inet.h> // inet_ntoa()
#include <cstring> // memset() - zero padding
#include <unistd.h> // close() - closing the socket
using namespace std;
#define ERROR -1
#define MAXBUFFER 1024
#define MAX_CLIENTS 5
int main(int argc, char* argv[])
{
int port = (argc>1)?atoi(argv[1]):12345; // server port number
int parent_sock, child_sock;
struct sockaddr_in server, client;
// Create parent socket at the server
if( (parent_sock = socket(AF_INET, SOCK_STREAM, 0)) == ERROR)
{
perror("Socket error");
exit(EXIT_FAILURE);
}
// Create server adderess data structure
server.sin_family = AF_INET; // IPv4
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY; // All interfaces
memset(&server.sin_zero, 0, 8); // last 8 bytes
/*
* Bind phase
*/
unsigned int len = sizeof(sockaddr_in);
if ((bind(parent_sock, (struct sockaddr *) &server, len)) ==ERROR )
{
perror("Bind error");
exit(EXIT_FAILURE);
}
/*
* Listen phase
*/
if((listen(parent_sock, MAX_CLIENTS) == ERROR))
{
perror("Listen error");
exit(EXIT_FAILURE);
}
cout << "Sum server started on port " << port << endl; // server screen message
char msg[] = "Hi client! Welcome to the sum server!"; // client screen message
while(1)
{
if(((child_sock = accept(parent_sock, (struct sockaddr *) &client, &len)) == ERROR))
{
perror("Accpet error");
exit(EXIT_FAILURE);
}
cout << "Client with IP address " << inet_ntoa(client.sin_addr) << " and port " << ntohs(client.sin_port) << " connected" << endl;
int sent_bytes = send(child_sock, &msg, sizeof msg, 0); // send first message "Hi client"
char recv_buffer[MAXBUFFER]; // Buffer to receive the data from client
int recv_bytes; // number of received bytes
if((recv_bytes = recv(child_sock, &recv_buffer, sizeof recv_buffer, 0)))
{
unsigned int recv_count = *recv_buffer;
cout << "Recieved count: " << recv_count << endl;
recv_bytes = recv(child_sock, &recv_buffer, sizeof recv_buffer, 0);
short int *recv_numbers = reinterpret_cast<short int*>(recv_buffer);
cout << "Recieved following numbers:" << endl;
short int sum = 0;
for (unsigned int idx = 0; idx < recv_count; idx++)
{
cout << "Number: " << recv_numbers[idx] << endl;
sum = sum + recv_numbers[idx]; // compute sum
}
cout << "Sum of these numbers is " << sum << endl;
sent_bytes = send(child_sock, &sum, sizeof sum, 0);
}
cout << "Client disconnected" << endl << endl;
close(child_sock);
}
close(parent_sock);
return 0;
} | 27.24 | 132 | 0.662261 |
f99ccbcf7cb99a16654eacebaf9f4850000193f9 | 1,233 | cpp | C++ | src/QBtAuxFunctions.cpp | ftylitak/QBluetoothZero | 3e4a018a5e62705b62fa2cbc64a27c3f66059982 | [
"Apache-2.0"
] | 2 | 2018-02-05T13:22:49.000Z | 2019-01-19T12:04:20.000Z | src/QBtAuxFunctions.cpp | ftylitak/QBluetoothZero | 3e4a018a5e62705b62fa2cbc64a27c3f66059982 | [
"Apache-2.0"
] | 1 | 2018-02-04T18:37:50.000Z | 2018-02-05T23:16:31.000Z | src/QBtAuxFunctions.cpp | ftylitak/QBluetoothZero | 3e4a018a5e62705b62fa2cbc64a27c3f66059982 | [
"Apache-2.0"
] | 3 | 2018-05-24T02:35:43.000Z | 2019-02-28T16:38:52.000Z | #include "QBtAuxFunctions.h"
#ifdef Q_OS_WIN32
bool QBtAuxFunctions::InitBthSdk()
{
if ( sdkInitializationCounter == 0) /* not connected with BlueSoleil */
{
if (Btsdk_Init() != BTSDK_OK)
return false;
if (Btsdk_IsBluetoothReady() == BTSDK_FALSE)
Btsdk_StartBluetooth();
BTUINT16 discoveryFlags = BTSDK_CONNECTABLE | BTSDK_PAIRABLE | BTSDK_GENERAL_DISCOVERABLE;
Btsdk_SetDiscoveryMode(discoveryFlags);
Btsdk_SetLocalDeviceClass(BTSDK_COMPCLS_DESKTOP);
}
sdkInitializationCounter++;
return true;
}
void QBtAuxFunctions::DeinitBthSdk()
{
if(Btsdk_IsSDKInitialized() && sdkInitializationCounter > 0)
{
sdkInitializationCounter--;
if(sdkInitializationCounter == 0)
Btsdk_Done();
}
}
BTDEVHDL QBtAuxFunctions::GetDeviceHandle(const QBtAddress& address)
{
//get device handle
BTDEVHDL devHandle = BTSDK_INVALID_HANDLE;
BTUINT8 btAddr [6]= {0};
QByteArray btAddrQt = address.toReversedByteArray();
memcpy(btAddr, btAddrQt.constData(), btAddrQt.size());
devHandle = Btsdk_GetRemoteDeviceHandle(btAddr);
return devHandle;
}
#endif //WIN32
| 27.4 | 99 | 0.665856 |
f9a02a599df97e56a3b57d258939f6fc32e01d64 | 610 | cpp | C++ | source/343.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | 2 | 2017-02-28T11:39:13.000Z | 2019-12-07T17:23:20.000Z | source/343.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | source/343.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | //
// 343.cpp
// LeetCode
//
// Created by Narikbi on 23.02.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <cmath>
using namespace std;
int integerBreak(int n) {
vector <int> dp(n+1, 0);
dp[1] = 0;
for (int i = 2; i <= n; i++) {
for (int j = 1; j < i; j++) {
dp[i] = max(dp[i], max(j, dp[j]) * max(i-j, dp[i-j]));
}
}
return dp[n];
}
| 16.052632 | 66 | 0.539344 |
f9a413b98940eca59f60296c27675bf0b29f1a73 | 1,456 | cpp | C++ | pico-cnn/layers/pooling/pooling.cpp | ekut-es/pico-cnn | 18ef2ae0afd7ac9c0e18c293f2f2478a5f78c66c | [
"BSD-3-Clause"
] | 43 | 2019-06-18T13:53:24.000Z | 2021-12-24T17:37:56.000Z | pico-cnn/layers/pooling/pooling.cpp | ekut-es/pico-cnn | 18ef2ae0afd7ac9c0e18c293f2f2478a5f78c66c | [
"BSD-3-Clause"
] | 12 | 2020-06-01T00:54:37.000Z | 2022-02-10T01:40:23.000Z | pico-cnn/layers/pooling/pooling.cpp | ekut-es/pico-cnn | 18ef2ae0afd7ac9c0e18c293f2f2478a5f78c66c | [
"BSD-3-Clause"
] | 6 | 2020-11-02T19:58:55.000Z | 2021-12-24T17:38:02.000Z | #include "pooling.h"
pico_cnn::naive::Pooling::Pooling(std::string name, uint32_t id, pico_cnn::op_type op, uint32_t *kernel_size,
uint32_t *stride, uint32_t *padding) : Layer(name, id, op) {
if (kernel_size) {
kernel_size_ = new uint32_t[2]();
std::memcpy(kernel_size_, kernel_size, 2 * sizeof(uint32_t));
} else {
kernel_size_ = kernel_size;
}
if (stride) {
stride_ = new uint32_t[2]();
std::memcpy(stride_, stride, 2 * sizeof(uint32_t));
} else {
stride_ = stride;
}
if (padding) {
padding_ = new uint32_t[4]();
std::memcpy(padding_, padding, 4 * sizeof(uint32_t));
} else {
padding_ = padding;
}
}
pico_cnn::naive::Pooling::~Pooling() {
delete [] kernel_size_;
delete [] stride_;
delete [] padding_;
}
void pico_cnn::naive::Pooling::run(pico_cnn::naive::Tensor *input, pico_cnn::naive::Tensor *output) {
if (input->num_dimensions() == 4 || input->num_dimensions() == 3) {
Tensor *input_tensor;
if (padding_) {
input_tensor = input->expand_with_padding(padding_);
} else {
input_tensor = input;
}
this->pool(input_tensor, output);
if (padding_) {
delete input_tensor;
}
} else {
PRINT_ERROR_AND_DIE("Not implemented for Tensor with num_dims: " << input->num_dimensions());
}
} | 26.962963 | 109 | 0.574176 |
f9a62c668e2250f899b7b3e209bda4e68f8183bc | 2,605 | cpp | C++ | droneArchitectureRvizInterfaceROSModule/src/source/swarmAgentInterface.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | droneArchitectureRvizInterfaceROSModule/src/source/swarmAgentInterface.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | droneArchitectureRvizInterfaceROSModule/src/source/swarmAgentInterface.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | #include "swarmAgentInterface.h"
#include "RvizInteractiveMarkerDisplay.h"
SwarmAgentInterface::SwarmAgentInterface(int idDrone_in)
{
idDrone = idDrone_in;
return;
}
SwarmAgentInterface::~SwarmAgentInterface()
{
return;
}
void SwarmAgentInterface::open(ros::NodeHandle &nIn)
{
n = nIn;
localizer_pose_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_POSE_SUBSCRIPTION, 1, &SwarmAgentInterface::localizerPoseCallback, this);
mission_planner_mission_point_reference_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_TRAJECTORY_ABS_REF_CMD_SUBSCRIPTION, 1, &SwarmAgentInterface::missionPointCallback, this);
trajectory_planner_trajectory_reference_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_TRAJECTORY_ABS_REF_CMD_SUBSCRIPTION, 1, &SwarmAgentInterface::trajectoryAbsRefCmdCallback, this);
obstacle_processor_obstacle_list_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_OBSTACLE_LIST_SUBSCRIPTION, 1, &SwarmAgentInterface::obstacleListCallback, this);
// this_drone_society_pose_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_SOCIETY_POSE_SUBSCRIPTION, 1, &SwarmAgentInterface::societyPoseSubCallback, this);
return;
}
void SwarmAgentInterface::localizerPoseCallback(const droneMsgsROS::dronePose &pose_euler)
{
Drone.PoseCallback(pose_euler, idDrone);
}
void SwarmAgentInterface::missionPointCallback(const droneMsgsROS::dronePositionTrajectoryRefCommand &point)
{
if (idDrone == Drone.ActiveDroneId())
{
Drone.MissionPointPubCallback(point, idDrone);
}
}
void SwarmAgentInterface::trajectoryAbsRefCmdCallback(const droneMsgsROS::dronePositionTrajectoryRefCommand &trajectory)
{
if (idDrone == Drone.ActiveDroneId())
{
Drone.TrajectoryPubCallback(trajectory, idDrone);
}
}
void SwarmAgentInterface::obstacleListCallback(const droneMsgsROS::obstaclesTwoDim &obstacles)
{
//ROS_INFO("Drone ID %i", Drone.ActiveDroneId());
if (idDrone == Drone.ActiveDroneId())
{
Drone.ObstaclesPubCallback(obstacles, idDrone);
}
}
void SwarmAgentInterface::societyPoseSubCallback(const droneMsgsROS::societyPose::ConstPtr &msg)
{
//std::cout << "SwarmAgentInterface::societyPoseSubCallback drone:" << idDrone << std::endl;
}
| 30.290698 | 250 | 0.761996 |
f9a85337ac0427c6189842eb22ef8534aa49fb95 | 6,279 | cpp | C++ | MakeBuild/MakeBuild/CMakeFile.cpp | mooming/make_builder | e5aa68d4c922b3343cb032c0201126b9ed85ae37 | [
"MIT"
] | 1 | 2018-09-29T01:36:18.000Z | 2018-09-29T01:36:18.000Z | MakeBuild/MakeBuild/CMakeFile.cpp | mooming/make_builder | e5aa68d4c922b3343cb032c0201126b9ed85ae37 | [
"MIT"
] | null | null | null | MakeBuild/MakeBuild/CMakeFile.cpp | mooming/make_builder | e5aa68d4c922b3343cb032c0201126b9ed85ae37 | [
"MIT"
] | null | null | null | //
// CMakeFile.cpp
// mbuild
//
// Created by mooming on 2016. 8. 15..
//
//
#include "CMakeFile.h"
#include "StringUtil.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
using namespace Builder;
namespace
{
void AddFrameworks(ostream& os, string projName, const vector<string>& frameworks)
{
os << "if (APPLE)" << endl;
os << "include_directories ( /System/Library/Frameworks )" << endl;
os << "endif (APPLE)" << endl << endl;
if (!frameworks.empty())
{
for (const auto& element : frameworks)
{
if (Util::EqualsIgnoreCase(element, "opengl"))
{
os << "find_package (OpenGL)" << endl << endl;
os << "if (OPENGL_FOUND)" << endl;
os << "include_directories (${OPENGL_INCLUDE_DIR})" << endl;
os << "target_link_libraries (" << projName << " ${OPENGL_gl_LIBRARY})" << endl;
os << "endif (OPENGL_FOUND)" << endl << endl;
os << "if (OPENGL_GLU_FOUND)" << endl;
os << "target_link_libraries (" << projName << " ${OPENGL_glu_LIBRARY})" << endl;
os << "endif (OPENGL_GLU_FOUND)" << endl << endl;
}
else
{
string libName = element;
libName.append("_LIBRARY");
os << "find_library(" << libName << " " << element << ")" << endl << endl;
os << "if (" << libName << ")" << endl;
os << "target_link_libraries (" << projName << " ${" << libName << "})" << endl;
os << "endif (" << libName << ")" << endl << endl;
}
}
}
}
}
namespace CMake
{
CMakeFile::CMakeFile(const Build& build, const ProjectDir& targetDir)
: build(build), dir(targetDir)
{
}
void CMakeFile::Make()
{
const BuildType buildType = dir.GetBuildType();
const char* basePath = "${CMAKE_SOURCE_DIR}";
using namespace Util;
string filePath(dir.path);
string projName(PathToName(dir.path));
filePath.append("/CMakeLists.txt");
cout << "Creating: " << filePath.c_str() << "(" << BuildTypeStr(buildType) << ")" << endl;
ofstream ofs (filePath.c_str(), ofstream::out);
ofs << "cmake_minimum_required (VERSION 2.6)" << endl;
ofs << "project (" << projName << ")" << endl;
ofs << endl;
ofs << "if(CMAKE_COMPILER_IS_GNUCXX)" << endl;
ofs << " set(CMAKE_CXX_FLAGS \"${ CMAKE_CXX_FLAGS } -Wall -Werror\")" << endl;
ofs << "endif(CMAKE_COMPILER_IS_GNUCXX)" << endl;
auto& definesList = dir.DefinitionsList();
if (!definesList.empty())
{
ofs << "add_definitions (";
for (auto& def : definesList)
{
ofs << def << " ";
}
ofs << ")" << endl;
}
ofs << endl;
ofs << "include_directories (";
ofs << " " << basePath << endl;
ofs << " " << basePath << "/include" << endl;
for (const auto& element : build.includeDirs)
{
ofs << " " << TranslatePath(element) << endl;
}
ofs << " )" << endl;
ofs << endl;
if (buildType != HEADER_ONLY)
{
ofs << "link_directories (" << basePath << "/lib)" << endl;
ofs << endl;
}
ofs << endl;
for (const auto& subDir : dir.ProjDirList())
{
if (!subDir.SrcFileList().empty())
{
ofs << "add_subdirectory (" << PathToName(subDir.path.c_str()) << ")" << endl;
}
}
ofs << endl;
switch(buildType)
{
case EXECUTABLE:
ofs << "add_executable (" << projName.c_str() << endl;
for (const auto& element : dir.SrcFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
for (const auto& element : dir.HeaderFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
ofs << ")" << endl << endl;
AddFrameworks(ofs, projName, dir.FrameworkList());
ofs << "install (TARGETS " << projName << " DESTINATION " << basePath << "/bin)" << endl;
break;
case STATIC_LIBRARY:
ofs << "add_library (" << projName.c_str() << " STATIC " << endl;
for (const auto& element : dir.SrcFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
for (const auto& element : dir.HeaderFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
ofs << ")" << endl << endl;
AddFrameworks(ofs, projName, dir.FrameworkList());
ofs << "install (TARGETS " << projName << " DESTINATION " << basePath << "/lib)" << endl;
break;
case SHARED_LIBRARY:
ofs << "add_library (" << projName.c_str() << " SHARED " << endl;
for (const auto& element : dir.SrcFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
for (const auto& element : dir.HeaderFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
ofs << ")" << endl << endl;
AddFrameworks(ofs, projName, dir.FrameworkList());
ofs << "install (TARGETS " << projName << " DESTINATION " << basePath << "/bin)" << endl;
break;
case HEADER_ONLY:
ofs << "add_library (" << projName.c_str() << " INTERFACE)" << endl;
ofs << "target_sources (" << projName.c_str() << " INTERFACE " << endl;
for (const auto& element : dir.HeaderFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
ofs << ")" << endl;
break;
default:
break;
};
ofs << endl << endl;
auto& dependencyList = dir.DependencyList();
auto& libList = dir.LibraryList();
if (!dependencyList.empty() || !libList.empty())
{
ofs << "target_link_libraries (" << projName;
for (const auto& dependency : dependencyList)
{
if (dependency.empty())
continue;
ofs << " " << dependency;
}
for (const auto& library : libList)
{
if (library.empty())
continue;
ofs << " " << library;
}
ofs << ")" << endl << endl;
for (const auto& dependency : dependencyList)
{
if (dependency.empty())
continue;
ofs << "add_dependencies (" << projName.c_str() << " " << dependency << ")" << endl;
}
ofs << endl;
}
ofs << endl;
ofs.close();
}
string CMakeFile::TranslatePath(string path)
{
using namespace Util;
path = TrimPath(path);
if (StartsWithIgnoreCase(path, build.baseDir.path))
{
string newPath = string("${CMAKE_SOURCE_DIR}");
newPath.append(path.substr(build.baseDir.path.length()));
return newPath;
}
return path;
}
}
| 23.965649 | 93 | 0.563306 |
e2fe893b9533c1deaf371e183092fa7daf7e13ea | 3,980 | cxx | C++ | sprokit/processes/core/unwrap_detections_process.cxx | neal-siekierski/kwiver | 1c97ad72c8b6237cb4b9618665d042be16825005 | [
"BSD-3-Clause"
] | null | null | null | sprokit/processes/core/unwrap_detections_process.cxx | neal-siekierski/kwiver | 1c97ad72c8b6237cb4b9618665d042be16825005 | [
"BSD-3-Clause"
] | null | null | null | sprokit/processes/core/unwrap_detections_process.cxx | neal-siekierski/kwiver | 1c97ad72c8b6237cb4b9618665d042be16825005 | [
"BSD-3-Clause"
] | null | null | null | /*ckwg +29
* Copyright 2018 by Kitware, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither name of Kitware, Inc. nor the names of any contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS 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.
*/
/**
* \file
* \brief Unwrap the object detections from object tracks.
*/
#include "unwrap_detections_process.h"
#include <vital/vital_types.h>
#include <kwiver_type_traits.h>
#include <sprokit/pipeline/process_exception.h>
namespace kwiver
{
//----------------------------------------------------------------
// Private implementation class
class unwrap_detections_process::priv
{
public:
priv();
~priv();
vital::frame_id_t m_current_idx;
};
// ===============================================================================
unwrap_detections_process
::unwrap_detections_process( kwiver::vital::config_block_sptr const& config )
: process( config ),
d( new unwrap_detections_process::priv )
{
make_ports();
make_config();
}
unwrap_detections_process
::~unwrap_detections_process()
{
}
// -------------------------------------------------------------------------------
void
unwrap_detections_process
::_configure()
{
}
// -------------------------------------------------------------------------------
void
unwrap_detections_process
::_step()
{
auto object_tracks = grab_from_port_using_trait( object_track_set );
auto detected_objects = std::make_shared< kwiver::vital::detected_object_set >();
for( auto& trk : object_tracks->tracks() )
{
for( auto& state : *trk )
{
auto obj_state = std::static_pointer_cast< kwiver::vital::object_track_state >( state );
if( state->frame() == d->m_current_idx )
{
detected_objects->add( obj_state->detection() );
}
}
}
push_to_port_using_trait( detected_object_set, detected_objects );
d->m_current_idx++;
}
// -------------------------------------------------------------------------------
void
unwrap_detections_process
::make_ports()
{
// Set up for required ports
sprokit::process::port_flags_t required;
required.insert( flag_required );
// -- input --
declare_input_port_using_trait( object_track_set, required );
// -- output --
declare_output_port_using_trait( detected_object_set, required );
}
// -------------------------------------------------------------------------------
void
unwrap_detections_process
::make_config()
{
}
// ===============================================================================
unwrap_detections_process::priv
::priv()
: m_current_idx( 0 )
{
}
unwrap_detections_process::priv
::~priv()
{
}
} // end namespace
| 26.533333 | 94 | 0.631407 |
e2fffc29f48d61bbb1fd0392d17ef7142a1b37af | 3,606 | hh | C++ | include/maxscale/response_distribution.hh | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | null | null | null | include/maxscale/response_distribution.hh | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | null | null | null | include/maxscale/response_distribution.hh | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2021 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2025-12-13
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#pragma once
#include <maxscale/ccdefs.hh>
#include <maxbase/stopwatch.hh>
#include <map>
using namespace std::chrono_literals;
namespace maxscale
{
/**
* Distribution of queries into buckets of response time, similar to
* the Query Response Time Plugin in mariadb.
* https://mariadb.com/kb/en/query-response-time-plugin/
*
* From Query Response Time Plugin documentation:
* The user can define time intervals that divide the range 0 to positive infinity into smaller
* intervals and then collect the number of commands whose execution times fall into each of
* those intervals.
* Each interval is described as:
* (range_base ^ n; range_base ^ (n+1)]
*
* SELECT * FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME;
* +----------------+-------+----------------+
* | TIME | COUNT | TOTAL |
* +----------------+-------+----------------+
* | 0.000001 | 0 | 0.000000 |
* | 0.000010 | 17 | 0.000094 |
* | 0.000100 | 4301 0.236555 |
* | 0.001000 | 1499 | 0.824450 |
* | 0.010000 | 14851 | 81.680502 |
* | 0.100000 | 8066 | 443.635693 |
* | 1.000000 | 0 | 0.000000 |
* | 10.000000 | 0 | 0.000000 |
* | 100.000000 | 1 | 55.937094 |
* | 1000.000000 | 0 | 0.000000 |
* | 10000.000000 | 0 | 0.000000 |
* | 100000.000000 | 0 | 0.000000 |
* | 1000000.000000 | 0 | 0.000000 |
* | TOO LONG | 0 | TOO LONG |
* +----------------+-------+----------------+
*
* This class tallies the response times added to it maintaining
* a vector of the results.
*
* The limits are rounded to microseconds (a bit differently than the plugin).
* The first limit is >= 1us, depends on the given range_base.
* The last limit < 10'000'000 (1M for range_base=10, 11.6 days). In the server
* the last limit is followed by a "TOO LONG" entry. There is no too-long entry
* in class ResponseDistribution (not needed, can't convert to consistent json).
*/
class ResponseDistribution
{
public:
/**
* @brief ResponseDistribution
* @param range_base - minimum 2
*/
ResponseDistribution(int range_base = 10);
struct Element
{
// These are all "atomic" sizes (64 bits).
mxb::Duration limit; // upper limit for a bucket
int64_t count;
mxb::Duration total;
};
int range_base() const;
void add(mxb::Duration dur);
const std::vector<Element>& get() const;
// Get an initial copy for summing up using operator+=
ResponseDistribution with_stats_reset() const;
ResponseDistribution& operator+(const ResponseDistribution& rhs);
ResponseDistribution& operator+=(const ResponseDistribution& rhs);
private:
int m_range_base;
// initialized in the constructor after which
// the underlying array (size) remains unchanged
std::vector<Element> m_elements;
};
inline void ResponseDistribution::add(mxb::Duration dur)
{
for (auto& element : m_elements)
{
if (dur <= element.limit)
{
++element.count;
element.total += dur;
break;
}
}
}
}
| 31.356522 | 95 | 0.602329 |
390256ec44b496ef5a71c4b2e584dc48afee9a61 | 2,706 | hpp | C++ | example/client_console/client_console.hpp | wo3kie/server | 63e93c88c04db792b6d3fcb20591f07e5c1ae4f0 | [
"MIT"
] | 20 | 2015-09-14T01:38:56.000Z | 2020-11-20T13:01:34.000Z | example/client_console/client_console.hpp | wo3kie/server | 63e93c88c04db792b6d3fcb20591f07e5c1ae4f0 | [
"MIT"
] | null | null | null | example/client_console/client_console.hpp | wo3kie/server | 63e93c88c04db792b6d3fcb20591f07e5c1ae4f0 | [
"MIT"
] | 12 | 2017-01-23T18:46:32.000Z | 2019-06-20T02:22:09.000Z | #ifndef _CLIENT_CONSOLE_
#define _CLIENT_CONSOLE_
#include "core/client.hpp"
struct Writer : Task
{
Writer(
asio::io_service & ioService,
#ifdef SERVER_SSL
ssl::stream< ip::tcp::socket > & socket,
#else
ip::tcp::socket & socket,
#endif
int argc,
char* argv[]
)
: Task( ioService, socket )
{
}
protected:
void runImpl() override
{
auto const onRequestWritten = [ this ](
sys::error_code const & errorCode,
size_t const bytesTransferred
)
{
this->onRequestWritten( errorCode );
};
while( std::cin.getline( m_request, m_maxLength ) )
{
std::size_t const size = strlen( m_request );
asio::async_write(
m_socket,
asio::buffer( m_request, size ),
onRequestWritten
);
}
}
private:
void onRequestWritten(
sys::error_code const & errorCode
)
{
if( errorCode )
{
std::cerr
<< "ClientConsole::onRequestWritten Error: "
<< errorCode.message() << std::endl;
}
}
private:
enum { m_maxLength = 1024 + 2 };
char m_request[ m_maxLength ];
};
struct Reader : Task
{
Reader(
asio::io_service & ioService,
#ifdef SERVER_SSL
ssl::stream< ip::tcp::socket > & socket,
#else
ip::tcp::socket & socket,
#endif
int argc,
char* argv[]
)
: Task( ioService, socket )
{
}
protected:
void runImpl() override
{
auto const onResponseRead = [ this ](
sys::error_code const & errorCode,
size_t const bytesTransferred
)
{
this->onResponseRead( errorCode, bytesTransferred );
};
m_socket.async_read_some(
asio::buffer( m_response, m_maxLength ),
onResponseRead
);
}
private:
void onResponseRead(
sys::error_code const & errorCode,
size_t const bytesTransferred
)
{
if( errorCode )
{
std::cerr
<< "ClientConsole::onResponseRead Error: "
<< errorCode.message() << std::endl;
}
else
{
std::cout << "> ";
std::cout.write( m_response, bytesTransferred );
std::cout << std::endl;
m_ioService.post(
[ this ](){ this->runImpl(); }
);
}
}
private:
enum { m_maxLength = 1024 };
char m_response[ m_maxLength ];
};
#endif
| 19.751825 | 64 | 0.4915 |
390abeb5824edd87d529070e13d838c0c2467c31 | 17,059 | cpp | C++ | engine/src/ph/util/GltfLoader.cpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/src/ph/util/GltfLoader.cpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/src/ph/util/GltfLoader.cpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | // Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se)
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#include "ph/util/GltfLoader.hpp"
#include <sfz/Logging.hpp>
#include <sfz/strings/StackString.hpp>
#define TINYGLTF_NOEXCEPTION
#define JSON_NOEXCEPTION
#define TINYGLTF_IMPLEMENTATION
#define TINYGLTF_NO_STB_IMAGE
#define TINYGLTF_NO_STB_IMAGE_WRITE
#include <sfz/PushWarnings.hpp>
#include "tiny_gltf.h"
#include <sfz/PopWarnings.hpp>
#include <sfz/Assert.hpp>
#include <ph/Context.hpp>
namespace ph {
using sfz::str320;
using sfz::vec2;
using sfz::vec3;
using sfz::vec3_u8;
using sfz::vec4;
using sfz::vec4_u8;
// Statics
// ------------------------------------------------------------------------------------------------
static bool dummyLoadImageDataFunction(
tinygltf::Image*, const int, std::string*, std::string*, int, int, const unsigned char*, int, void*)
{
return true;
}
static str320 calculateBasePath(const char* path) noexcept
{
str320 str("%s", path);
// Go through path until the path separator is found
bool success = false;
for (uint32_t i = str.size() - 1; i > 0; i--) {
const char c = str.str[i - 1];
if (c == '\\' || c == '/') {
str.str[i] = '\0';
success = true;
break;
}
}
// If no path separator is found, assume we have no base path
if (!success) str.printf("");
return str;
}
enum class ComponentType : uint32_t {
INT8 = 5120,
UINT8 = 5121,
INT16 = 5122,
UINT16 = 5123,
UINT32 = 5125,
FLOAT32 = 5126,
};
static uint32_t numBytes(ComponentType type)
{
switch (type) {
case ComponentType::INT8: return 1;
case ComponentType::UINT8: return 1;
case ComponentType::INT16: return 2;
case ComponentType::UINT16: return 2;
case ComponentType::UINT32: return 4;
case ComponentType::FLOAT32: return 4;
}
return 0;
}
enum class ComponentDimensions : uint32_t {
SCALAR = TINYGLTF_TYPE_SCALAR,
VEC2 = TINYGLTF_TYPE_VEC2,
VEC3 = TINYGLTF_TYPE_VEC3,
VEC4 = TINYGLTF_TYPE_VEC4,
MAT2 = TINYGLTF_TYPE_MAT2,
MAT3 = TINYGLTF_TYPE_MAT3,
MAT4 = TINYGLTF_TYPE_MAT4,
};
static uint32_t numDimensions(ComponentDimensions dims)
{
switch (dims) {
case ComponentDimensions::SCALAR: return 1;
case ComponentDimensions::VEC2: return 2;
case ComponentDimensions::VEC3: return 3;
case ComponentDimensions::VEC4: return 4;
case ComponentDimensions::MAT2: return 4;
case ComponentDimensions::MAT3: return 9;
case ComponentDimensions::MAT4: return 16;
}
return 0;
}
struct DataAccess final {
const uint8_t* rawPtr = nullptr;
uint32_t numElements = 0;
ComponentType compType = ComponentType::UINT8;
ComponentDimensions compDims = ComponentDimensions::SCALAR;
template<typename T>
const T& at(uint32_t index) const noexcept
{
return reinterpret_cast<const T*>(rawPtr)[index];
}
};
static DataAccess accessData(
const tinygltf::Model& model, int accessorIdx) noexcept
{
// Access Accessor
if (accessorIdx < 0) return DataAccess();
if (accessorIdx >= int32_t(model.accessors.size())) return DataAccess();
const tinygltf::Accessor& accessor = model.accessors[accessorIdx];
// Access BufferView
if (accessor.bufferView < 0) return DataAccess();
if (accessor.bufferView >= int32_t(model.bufferViews.size())) return DataAccess();
const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView];
// Access Buffer
if (bufferView.buffer < 0) return DataAccess();
if (bufferView.buffer >= int32_t(model.buffers.size())) return DataAccess();
const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer];
// Fill DataAccess struct
DataAccess tmp;
tmp.rawPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset];
tmp.numElements = uint32_t(accessor.count);
tmp.compType = ComponentType(accessor.componentType);
tmp.compDims = ComponentDimensions(accessor.type);
// For now we require that that there is no padding between elements in buffer
sfz_assert_hard(
bufferView.byteStride == 0 ||
bufferView.byteStride == size_t(numDimensions(tmp.compDims) * numBytes(tmp.compType)));
return tmp;
}
static DataAccess accessData(
const tinygltf::Model& model, const tinygltf::Primitive& primitive, const char* type) noexcept
{
const auto& itr = primitive.attributes.find(type);
if (itr == primitive.attributes.end()) return DataAccess();
return accessData(model, itr->second);
}
static uint8_t toU8(float val) noexcept
{
return uint8_t(std::roundf(val * 255.0f));
}
static vec4_u8 toSfz(const tinygltf::ColorValue& val) noexcept
{
vec4_u8 tmp;
tmp.x = toU8(float(val[0]));
tmp.y = toU8(float(val[1]));
tmp.z = toU8(float(val[2]));
tmp.w = toU8(float(val[3]));
return tmp;
}
static bool extractAssets(
const char* basePath,
const tinygltf::Model& model,
Mesh& meshOut,
DynArray<ImageAndPath>& texturesOut,
bool (*checkIfTextureIsLoaded)(StringID id, void* userPtr),
void* userPtr,
sfz::Allocator* allocator) noexcept
{
StringCollection& resStrings = getResourceStrings();
// Load textures
texturesOut.init(uint32_t(model.textures.size()), allocator, sfz_dbg(""));
for (uint32_t i = 0; i < model.textures.size(); i++) {
const tinygltf::Texture& tex = model.textures[i];
if (tex.source < 0 || int(model.images.size()) <= tex.source) {
SFZ_ERROR("tinygltf", "Bad texture source: %i", tex.source);
return false;
}
const tinygltf::Image& img = model.images[tex.source];
// Create global path (path relative to game executable)
const str320 globalPath("%s%s", basePath, img.uri.c_str());
StringID globalPathId = resStrings.getStringID(globalPath.str);
// Check if texture is already loaded, skip it if it is
if (checkIfTextureIsLoaded != nullptr) {
if (checkIfTextureIsLoaded(globalPathId, userPtr)) continue;
}
// Load and store image
ImageAndPath pack;
pack.globalPathId = globalPathId;
pack.image = loadImage("", globalPath);
if (pack.image.rawData.data() == nullptr) {
SFZ_ERROR("tinygltf", "Could not load texture: \"%s\"", globalPath.str);
return false;
}
texturesOut.add(std::move(pack));
// TODO: We need to store these two values somewhere. Likely in material (because it does
// not make perfect sense that everything should access the texture the same way)
//const tinygltf::Sampler& sampler = model.samplers[tex.sampler];
//int wrapS = sampler.wrapS; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT", "REPEAT"], default "REPEAT"
//int wrapT = sampler.wrapT; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT", "REPEAT"], default "REPEAT"
}
// Lambda for getting the StringID from a material
auto getStringID = [&](int texIndex) -> StringID {
const tinygltf::Texture& tex = model.textures[texIndex];
const tinygltf::Image& img = model.images[tex.source];
str320 globalPath("%s%s", basePath, img.uri.c_str());
StringID globalPathId = resStrings.getStringID(globalPath.str);
return globalPathId;
};
// Load materials
meshOut.materials.init(uint32_t(model.materials.size()), allocator, sfz_dbg(""));
for (uint32_t i = 0; i < model.materials.size(); i++) {
const tinygltf::Material& material = model.materials[i];
Material phMat;
// Lambda for checking if parameter exists
auto hasParamValues = [&](const char* key) {
return material.values.find(key) != material.values.end();
};
auto hasParamAdditionalValues = [&](const char* key) {
return material.additionalValues.find(key) != material.additionalValues.end();
};
// Albedo value
if (hasParamValues("baseColorFactor")) {
const tinygltf::Parameter& param = material.values.find("baseColorFactor")->second;
tinygltf::ColorValue color = param.ColorFactor();
phMat.albedo = toSfz(color);
}
// Albedo texture
if (hasParamValues("baseColorTexture")) {
const tinygltf::Parameter& param = material.values.find("baseColorTexture")->second;
int texIndex = param.TextureIndex();
if (texIndex < 0 || int(model.textures.size()) <= texIndex) {
SFZ_ERROR("tinygltf", "Bad texture index for material %u", i);
continue;
}
phMat.albedoTex = getStringID(texIndex);
// TODO: Store which texcoords to use
}
// Roughness Value
if (hasParamValues("roughnessFactor")) {
const tinygltf::Parameter& param = material.values.find("roughnessFactor")->second;
phMat.roughness = toU8(float(param.Factor()));
}
// Metallic Value
if (hasParamValues("metallicFactor")) {
const tinygltf::Parameter& param = material.values.find("metallicFactor")->second;
phMat.metallic = toU8(float(param.Factor()));
}
// Emissive value
if (hasParamAdditionalValues("emissiveFactor")) {
const tinygltf::Parameter& param = material.additionalValues.find("emissiveFactor")->second;
phMat.emissive.x = float(param.ColorFactor()[0]);
phMat.emissive.y = float(param.ColorFactor()[1]);
phMat.emissive.z = float(param.ColorFactor()[2]);
}
// Roughness and Metallic texture
if (hasParamValues("metallicRoughnessTexture")) {
const tinygltf::Parameter& param = material.values.find("metallicRoughnessTexture")->second;
int texIndex = param.TextureIndex();
if (texIndex < 0 || int(model.textures.size()) <= texIndex) {
SFZ_ERROR("tinygltf", "Bad texture index for material %u", i);
continue;
}
phMat.metallicRoughnessTex = getStringID(texIndex);
// TODO: Store which texcoords to use
}
// Normal texture
if (hasParamAdditionalValues("normalTexture")) {
const tinygltf::Parameter& param = material.additionalValues.find("normalTexture")->second;
int texIndex = param.TextureIndex();
if (texIndex < 0 || int(model.textures.size()) <= texIndex) {
SFZ_ERROR("tinygltf", "Bad texture index for material %u", i);
continue;
}
phMat.normalTex = getStringID(texIndex);
// TODO: Store which texcoords to use
}
// Occlusion texture
if (hasParamAdditionalValues("occlusionTexture")) {
const tinygltf::Parameter& param = material.additionalValues.find("occlusionTexture")->second;
int texIndex = param.TextureIndex();
if (texIndex < 0 || int(model.textures.size()) <= texIndex) {
SFZ_ERROR("tinygltf", "Bad texture index for material %u", i);
continue;
}
phMat.occlusionTex = getStringID(texIndex);
// TODO: Store which texcoords to use
}
// Emissive texture
if (hasParamAdditionalValues("emissiveTexture")) {
const tinygltf::Parameter& param = material.additionalValues.find("emissiveTexture")->second;
int texIndex = param.TextureIndex();
if (texIndex < 0 || int(model.textures.size()) <= texIndex) {
SFZ_ERROR("tinygltf", "Bad texture index for material %u", i);
continue;
}
phMat.emissiveTex = getStringID(texIndex);
// TODO: Store which texcoords to use
}
// Remove default emissive factor if no emissive is specified
if (phMat.emissiveTex == StringID::invalid() && !hasParamAdditionalValues("emissiveFactor")) {
phMat.emissive = vec3(0.0f);
}
// Add material to assets
meshOut.materials.add(phMat);
}
// Add single default material if no materials
if (meshOut.materials.size() == 0) {
ph::Material defaultMaterial;
defaultMaterial.emissive = vec3(1.0, 0.0, 0.0);
meshOut.materials.add(defaultMaterial);
}
// Add meshes
uint32_t numVertexGuess = uint32_t(model.meshes.size()) * 256;
meshOut.vertices.init(numVertexGuess, allocator, sfz_dbg(""));
meshOut.indices.init(numVertexGuess * 2, allocator, sfz_dbg(""));
meshOut.components.init(uint32_t(model.meshes.size()), allocator, sfz_dbg(""));
for (uint32_t i = 0; i < uint32_t(model.meshes.size()); i++) {
const tinygltf::Mesh& mesh = model.meshes[i];
MeshComponent phMeshComp;
// TODO: For now, stupidly assume each mesh only have one primitive
const tinygltf::Primitive& primitive = mesh.primitives[0];
// Mode can be:
// TINYGLTF_MODE_POINTS (0)
// TINYGLTF_MODE_LINE (1)
// TINYGLTF_MODE_LINE_LOOP (2)
// TINYGLTF_MODE_TRIANGLES (4)
// TINYGLTF_MODE_TRIANGLE_STRIP (5)
// TINYGLTF_MODE_TRIANGLE_FAN (6)
sfz_assert_hard(primitive.mode == TINYGLTF_MODE_TRIANGLES);
sfz_assert_hard(
primitive.indices >= 0 && primitive.indices < int(model.accessors.size()));
// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
//
// Allowed attributes:
// POSITION, NORMAL, TANGENT, TEXCOORD_0, TEXCOORD_1, COLOR_0, JOINTS_0, WEIGHTS_0
//
// Stupidly assume positions, normals, and texcoord_0 exists
DataAccess posAccess = accessData(model, primitive, "POSITION");
sfz_assert_hard(posAccess.rawPtr != nullptr);
sfz_assert_hard(posAccess.compType == ComponentType::FLOAT32);
sfz_assert_hard(posAccess.compDims == ComponentDimensions::VEC3);
DataAccess normalAccess = accessData(model, primitive, "NORMAL");
sfz_assert_hard(normalAccess.rawPtr != nullptr);
sfz_assert_hard(normalAccess.compType == ComponentType::FLOAT32);
sfz_assert_hard(normalAccess.compDims == ComponentDimensions::VEC3);
DataAccess texcoord0Access = accessData(model, primitive, "TEXCOORD_0");
sfz_assert_hard(texcoord0Access.rawPtr != nullptr)
sfz_assert_hard(texcoord0Access.compType == ComponentType::FLOAT32);
sfz_assert_hard(texcoord0Access.compDims == ComponentDimensions::VEC2);
// Assume texcoord_1 does NOT exist
DataAccess texcoord1Access = accessData(model, primitive, "TEXCOORD_1");
sfz_assert_hard(texcoord1Access.rawPtr == nullptr);
// Create vertices from positions and normals
// TODO: Texcoords
sfz_assert_hard(posAccess.numElements == normalAccess.numElements);
uint32_t compVertexOffset = meshOut.vertices.size();
for (uint32_t j = 0; j < posAccess.numElements; j++) {
Vertex vertex;
vertex.pos = posAccess.at<vec3>(j);
vertex.normal = normalAccess.at<vec3>(j);
vertex.texcoord = texcoord0Access.at<vec2>(j);
meshOut.vertices.add(vertex);
}
// Create indices
DataAccess idxAccess = accessData(model, primitive.indices);
sfz_assert_hard(idxAccess.rawPtr != nullptr);
sfz_assert_hard(idxAccess.compDims == ComponentDimensions::SCALAR);
phMeshComp.firstIndex = meshOut.indices.size();
phMeshComp.numIndices = idxAccess.numElements;
if (idxAccess.compType == ComponentType::UINT32) {
for (uint32_t j = 0; j < idxAccess.numElements; j++) {
meshOut.indices.add(compVertexOffset + idxAccess.at<uint32_t>(j));
}
}
else if (idxAccess.compType == ComponentType::UINT16) {
for (uint32_t j = 0; j < idxAccess.numElements; j++) {
meshOut.indices.add(compVertexOffset + uint32_t(idxAccess.at<uint16_t>(j)));
}
}
else {
sfz_assert_hard(false);
}
// Material
uint32_t materialIdx = primitive.material < 0 ? 0 : primitive.material;
sfz_assert_hard(materialIdx < meshOut.materials.size());
phMeshComp.materialIdx = materialIdx;
// Add component to mesh
meshOut.components.add(phMeshComp);
}
return true;
}
// Function for loading from gltf
// ------------------------------------------------------------------------------------------------
bool loadAssetsFromGltf(
const char* gltfPath,
Mesh& meshOut,
DynArray<ImageAndPath>& texturesOut,
sfz::Allocator* allocator,
bool (*checkIfTextureIsLoaded)(StringID id, void* userPtr),
void* userPtr) noexcept
{
str320 basePath = calculateBasePath(gltfPath);
// Initializing loader with dummy image loader function
tinygltf::TinyGLTF loader;
loader.SetImageLoader(dummyLoadImageDataFunction, nullptr);
// Read model from file
tinygltf::Model model;
std::string error;
std::string warnings;
bool result = loader.LoadASCIIFromFile(&model, &error, &warnings, gltfPath);
// Check error string
if (!warnings.empty()) {
SFZ_WARNING("tinygltf", "Warnings loading \"%s\": %s", gltfPath, warnings.c_str());
}
if (!error.empty()) {
SFZ_ERROR("tinygltf", "Error loading \"%s\": %s", gltfPath, error.c_str());
return false;
}
// Check return code
if (!result) {
SFZ_ERROR("tinygltf", "Error loading \"%s\"", gltfPath);
return false;
}
// Log that model was succesfully loaded
SFZ_INFO_NOISY("tinygltf", "Model \"%s\" loaded succesfully", gltfPath);
// Extract assets from results
bool extractSuccess = extractAssets(
basePath.str, model, meshOut, texturesOut, checkIfTextureIsLoaded, userPtr, allocator);
if (!extractSuccess) {
SFZ_ERROR("tinygltf", "Failed to create ph::Mesh from gltf: \"%s\"", gltfPath);
return false;
}
return true;
}
} // namespace ph
| 33.318359 | 101 | 0.712762 |
390ff228cd4db2d07d9236a1271bdac3a64c1706 | 4,848 | cpp | C++ | src/loaders/PE.cpp | LucasDblt/QBDL | fc873087740f10ac56c023cad8b1c8ca42aa8d28 | [
"Apache-2.0"
] | 52 | 2021-05-21T20:17:13.000Z | 2022-03-26T11:08:44.000Z | src/loaders/PE.cpp | LucasDblt/QBDL | fc873087740f10ac56c023cad8b1c8ca42aa8d28 | [
"Apache-2.0"
] | 2 | 2021-06-06T09:32:09.000Z | 2021-09-03T10:25:19.000Z | src/loaders/PE.cpp | LucasDblt/QBDL | fc873087740f10ac56c023cad8b1c8ca42aa8d28 | [
"Apache-2.0"
] | 7 | 2021-05-22T02:17:20.000Z | 2022-01-25T16:21:07.000Z | #include "logging.hpp"
#include <LIEF/PE.hpp>
#include <QBDL/Engine.hpp>
#include <QBDL/arch.hpp>
#include <QBDL/loaders/PE.hpp>
#include <QBDL/utils.hpp>
using namespace LIEF::PE;
namespace QBDL::Loaders {
std::unique_ptr<PE> PE::from_file(const char *path, TargetSystem &engines,
BIND binding) {
Logger::info("Loading {}", path);
if (!is_pe(path)) {
Logger::err("{} is not an PE file", path);
return {};
}
std::unique_ptr<Binary> bin = Parser::parse(path);
if (bin == nullptr) {
Logger::err("Can't parse {}", path);
return {};
}
return from_binary(std::move(bin), engines, binding);
}
std::unique_ptr<PE> PE::from_binary(std::unique_ptr<Binary> bin,
TargetSystem &engines, BIND binding) {
if (!engines.supports(*bin)) {
return {};
}
std::unique_ptr<PE> loader(new PE{std::move(bin), engines});
loader->load(binding);
return loader;
}
PE::PE(std::unique_ptr<Binary> bin, TargetSystem &engines)
: Loader::Loader(engines), bin_{std::move(bin)} {}
uint64_t PE::get_address(const std::string &sym) const {
const Binary &binary = get_binary();
const LIEF::Symbol *symbol = nullptr;
if (binary.has_symbol(sym)) {
symbol = &binary.get_symbol(sym);
}
if (symbol == nullptr) {
return 0;
}
return base_address_ + get_rva(binary, symbol->value());
}
uint64_t PE::get_address(uint64_t offset) const {
return base_address_ + offset;
}
uint64_t PE::entrypoint() const {
const Binary &binary = get_binary();
return base_address_ +
(binary.entrypoint() - binary.optional_header().imagebase());
}
void PE::load(BIND binding) {
Binary &binary = get_binary();
const uint64_t imagebase = binary.optional_header().imagebase();
uint64_t virtual_size = binary.virtual_size();
virtual_size = page_align(virtual_size);
mem_size_ = virtual_size;
Logger::debug("Virtual size: 0x{:x}", virtual_size);
const uint64_t base_address_hint =
engine_->base_address_hint(imagebase, virtual_size);
const uint64_t base_address =
engine_->mem().mmap(base_address_hint, virtual_size);
if (base_address == 0 || base_address == -1ull) {
Logger::err("mmap() failed! Abort.");
return;
}
base_address_ = base_address;
// Map sections
// =======================================================
for (const Section §ion : binary.sections()) {
QBDL_DEBUG("Mapping: {:<10}: (0x{:06x} - 0x{:06x})", section.name(),
section.virtual_address(),
section.virtual_address() + section.virtual_size());
const uint64_t rva = section.virtual_address();
const std::vector<uint8_t> &content = section.content();
if (!content.empty()) {
engine_->mem().write(base_address_ + rva, content.data(), content.size());
}
}
// Perform relocations
// =======================================================
if (binary.has_relocations()) {
const Arch binarch = arch();
const uint64_t fixup = base_address_ - imagebase;
for (const Relocation &relocation : binary.relocations()) {
const uint64_t rva = relocation.virtual_address();
for (const RelocationEntry &entry : relocation.entries()) {
switch (entry.type()) {
case RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_DIR64: {
const uint64_t relocation_addr =
base_address_ + rva + entry.position();
const uint64_t value =
engine_->mem().read_ptr(binarch, relocation_addr);
engine_->mem().write_ptr(binarch, relocation_addr, value + fixup);
break;
}
default: {
QBDL_ERROR("PE relocation {} is not supported!",
to_string(entry.type()));
break;
}
}
}
}
}
// Perform symbol resolution
// =======================================================
// TODO(romain): Find a mechanism to support import by ordinal
if (binary.has_imports()) {
const Arch binarch = arch();
for (const Import &imp : binary.imports()) {
for (const ImportEntry &entry : imp.entries()) {
const uint64_t iat_addr = entry.iat_address();
QBDL_DEBUG("Resolving: {}:{} (0x{:x})", imp.name(), entry.name(),
iat_addr);
LIEF::Symbol sym{entry.name()};
const uintptr_t sym_addr = engine_->symlink(*this, sym);
// Write the value in the IAT:
engine_->mem().write_ptr(binarch, base_address_ + iat_addr, sym_addr);
}
}
}
}
Arch PE::arch() const { return Arch::from_bin(get_binary()); }
uint64_t PE::get_rva(const Binary &bin, uint64_t addr) const {
const uint64_t imagebase = bin.optional_header().imagebase();
if (addr >= imagebase) {
return addr - imagebase;
}
return addr;
}
PE::~PE() = default;
} // namespace QBDL::Loaders
| 31.277419 | 80 | 0.607673 |
391258a61b2f516878fedbf96255bda38df9868f | 3,927 | cpp | C++ | qt-4.8.4/src/gui/kernel/qdesktopwidget_gix.cpp | easion/qt_for_gix | f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8 | [
"Apache-2.0"
] | null | null | null | qt-4.8.4/src/gui/kernel/qdesktopwidget_gix.cpp | easion/qt_for_gix | f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8 | [
"Apache-2.0"
] | null | null | null | qt-4.8.4/src/gui/kernel/qdesktopwidget_gix.cpp | easion/qt_for_gix | f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** Copyright (C) 2011 www.hanxuantech.com. The Gix parts.
** Written by Easion <easion@hanxuantech.com>
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdesktopwidget.h"
#include <stdio.h>
#include <gi/gi.h>
QDesktopWidget::QDesktopWidget()
: QWidget(0, Qt::Desktop)
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::QDesktopWidget\n");
}
QDesktopWidget::~QDesktopWidget()
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::~QDesktopWidget\n");
}
void
QDesktopWidget::resizeEvent(QResizeEvent*)
{
fprintf(stderr, "Unimplemented: QDesktopWidget::resizeEvent\n");
}
const QRect QDesktopWidget::availableGeometry(int screen) const
{
int workarea[4];
int rv;
QRect workArea;
rv = gi_wm_get_workarea(workarea);
if (!rv)
{
workArea = QRect(workarea[0], workarea[1], workarea[2], workarea[3]);
}
else{
workArea = screenGeometry(0);
}
return workArea;//QRect(0,0,info.scr_width,info.scr_height);
}
const QRect QDesktopWidget::screenGeometry(int screen) const
{
gi_screen_info_t info;
gi_get_screen_info(&info);
return QRect(0,0,info.scr_width,info.scr_height);
}
int QDesktopWidget::screenNumber(const QWidget *widget) const
{
Q_UNUSED(widget);
//fprintf(stderr, "Reimplemented: QDesktopWidget::screenNumber(widget) \n");
return 0;
}
int QDesktopWidget::screenNumber(const QPoint &point) const
{
Q_UNUSED(point);
//fprintf(stderr, "Reimplemented: QDesktopWidget::screenNumber\n");
return 0;
}
bool QDesktopWidget::isVirtualDesktop() const
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::isVirtualDesktop\n");
return true;
}
int QDesktopWidget::primaryScreen() const
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::primaryScreen\n");
return 0;
}
int QDesktopWidget::numScreens() const
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::numScreens\n");
return 1;
}
QWidget *QDesktopWidget::screen(int /* screen */)
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::screen\n");
// It seems that a Qt::WType_Desktop cannot be moved?
return this;
}
| 29.30597 | 77 | 0.718615 |
3912b1cc54d2b24986c1b54851f0b0eb1ce44980 | 637 | cpp | C++ | Problems/codility/CyclicRotation/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | Problems/codility/CyclicRotation/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | 1 | 2019-05-09T19:17:00.000Z | 2019-05-09T19:17:00.000Z | Problems/codility/CyclicRotation/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
vector<int> solution(vector<int> &A, int K) {
const int size = A.size();
if(size != 0 && K % size != 0) {
vector<int> result(size);
for (int i = 0; i < size; i++) {
result[(i + K) % size] = A[i];
}
return result;
}
return A;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "rt", stdin);
#endif
int n,k;
cin >> n >> k;
vector<int> b(n);
for (int i = 0; i < n; i++)
cin >> b[i];
vector<int> a = solution(b, k);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
} | 18.735294 | 45 | 0.467818 |
391449c54ac2eb65638f066f0aac0f97bc9e7d18 | 1,017 | cpp | C++ | cpp/gstreamer_raspberrypi/Window_control.cpp | windowsair/Archive | 83d605756031768efefe3f77cf33f4a944d975bf | [
"MIT"
] | null | null | null | cpp/gstreamer_raspberrypi/Window_control.cpp | windowsair/Archive | 83d605756031768efefe3f77cf33f4a944d975bf | [
"MIT"
] | null | null | null | cpp/gstreamer_raspberrypi/Window_control.cpp | windowsair/Archive | 83d605756031768efefe3f77cf33f4a944d975bf | [
"MIT"
] | null | null | null | //
// Created by 30349 on 2021/11/7.
//
#include "Window_control.h"
#include "opencv2/opencv.hpp"
#include "SafeQueue.hpp"
namespace wc {
SafeQueue<cv::Mat> queue_ch1;
SafeQueue<cv::Mat> queue_ch2;
std::mutex cv_mtx;
[[noreturn]] void onFrame_ch1() {
cv::Mat frame;
// blocking
while (true) {
while(queue_ch1.Consume(frame)) {
printf("got 1\n");
// Process the message
cv_mtx.lock();
cv::imshow("1", frame);
cv::waitKey(1);
cv_mtx.unlock();
}
}
}
[[noreturn]] void onFrame_ch2() {
cv::Mat frame;
// blocking
while (true) {
while(queue_ch2.Consume(frame)) {
// Process the message
printf("got 2\n");
cv_mtx.lock();
cv::imshow("2", frame);
cv::waitKey(1);
cv_mtx.unlock();
}
}
}
} | 22.108696 | 45 | 0.450344 |
3915750d1eb18c97faa2696719710f45cb2ef94d | 916 | cpp | C++ | Codeforces/731A - Night at the Museum.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/731A - Night at the Museum.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/731A - Night at the Museum.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | #include <iostream>
#include <cctype>
#include <cmath>
#include <string>
using namespace std;
int get_minimum_distance(char src, char dest) {
int distance;
src = tolower(src);
dest = tolower(dest);
// if the distance between the pointed charecter and the destination charecter is greater than 13, then we want make our movement to the opposite side
if (abs(src - dest) > 13)
distance = 26 - abs(src - dest);
// else the distance is the differce between the source and the dest
else
distance = abs(src-dest);
return distance;
}
int main() {
string input;
cin >> input;
int minimum_rotations = get_minimum_distance('a', input.at(0));
char pointer = input.at(0);
for (int i = 0, j = 1; i < input.length() - 1; i++, j++)
minimum_rotations += get_minimum_distance(input.at(i), input.at(j));
cout << minimum_rotations << endl;
} | 26.171429 | 154 | 0.644105 |
39186a85e96ca0f5d099d05e8241ea93483e058a | 5,307 | cpp | C++ | src/gui/pen.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | 1 | 2020-12-28T01:41:35.000Z | 2020-12-28T01:41:35.000Z | src/gui/pen.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | null | null | null | src/gui/pen.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | null | null | null | // Copyright (C) 2018 Vincent Chambrin
// This file is part of the Yasl project
// For conditions of distribution and use, see copyright notice in LICENSE
#include "yasl/gui/pen.h"
#include "yasl/common/binding/class.h"
#include "yasl/common/binding/default_arguments.h"
#include "yasl/common/binding/namespace.h"
#include "yasl/common/genericvarianthandler.h"
#include "yasl/core/datastream.h"
#include "yasl/core/enums.h"
#include "yasl/gui/brush.h"
#include "yasl/gui/color.h"
#include "yasl/gui/pen.h"
#include <script/classbuilder.h>
static void register_pen_class(script::Namespace ns)
{
using namespace script;
Class pen = ns.newClass("Pen").setId(script::Type::QPen).get();
// QPen();
bind::default_constructor<QPen>(pen).create();
// QPen(Qt::PenStyle);
bind::constructor<QPen, Qt::PenStyle>(pen).create();
// QPen(const QColor &);
bind::constructor<QPen, const QColor &>(pen).create();
// QPen(const QBrush &, qreal, Qt::PenStyle = Qt::SolidLine, Qt::PenCapStyle = Qt::SquareCap, Qt::PenJoinStyle = Qt::BevelJoin);
bind::constructor<QPen, const QBrush &, qreal, Qt::PenStyle, Qt::PenCapStyle, Qt::PenJoinStyle>(pen)
.apply(bind::default_arguments(Qt::BevelJoin, Qt::SquareCap, Qt::SolidLine)).create();
// QPen(const QPen &);
bind::constructor<QPen, const QPen &>(pen).create();
// ~QPen();
bind::destructor<QPen>(pen).create();
// QPen & operator=(const QPen &);
bind::memop_assign<QPen, const QPen &>(pen);
// QPen(QPen &&);
bind::constructor<QPen, QPen &&>(pen).create();
// QPen & operator=(QPen &&);
bind::memop_assign<QPen, QPen &&>(pen);
// void swap(QPen &);
bind::void_member_function<QPen, QPen &, &QPen::swap>(pen, "swap").create();
// Qt::PenStyle style() const;
bind::member_function<QPen, Qt::PenStyle, &QPen::style>(pen, "style").create();
// void setStyle(Qt::PenStyle);
bind::void_member_function<QPen, Qt::PenStyle, &QPen::setStyle>(pen, "setStyle").create();
// QVector<qreal> dashPattern() const;
/// TODO: QVector<qreal> dashPattern() const;
// void setDashPattern(const QVector<qreal> &);
/// TODO: void setDashPattern(const QVector<qreal> &);
// qreal dashOffset() const;
bind::member_function<QPen, qreal, &QPen::dashOffset>(pen, "dashOffset").create();
// void setDashOffset(qreal);
bind::void_member_function<QPen, qreal, &QPen::setDashOffset>(pen, "setDashOffset").create();
// qreal miterLimit() const;
bind::member_function<QPen, qreal, &QPen::miterLimit>(pen, "miterLimit").create();
// void setMiterLimit(qreal);
bind::void_member_function<QPen, qreal, &QPen::setMiterLimit>(pen, "setMiterLimit").create();
// qreal widthF() const;
bind::member_function<QPen, qreal, &QPen::widthF>(pen, "widthF").create();
// void setWidthF(qreal);
bind::void_member_function<QPen, qreal, &QPen::setWidthF>(pen, "setWidthF").create();
// int width() const;
bind::member_function<QPen, int, &QPen::width>(pen, "width").create();
// void setWidth(int);
bind::void_member_function<QPen, int, &QPen::setWidth>(pen, "setWidth").create();
// QColor color() const;
bind::member_function<QPen, QColor, &QPen::color>(pen, "color").create();
// void setColor(const QColor &);
bind::void_member_function<QPen, const QColor &, &QPen::setColor>(pen, "setColor").create();
// QBrush brush() const;
bind::member_function<QPen, QBrush, &QPen::brush>(pen, "brush").create();
// void setBrush(const QBrush &);
bind::void_member_function<QPen, const QBrush &, &QPen::setBrush>(pen, "setBrush").create();
// bool isSolid() const;
bind::member_function<QPen, bool, &QPen::isSolid>(pen, "isSolid").create();
// Qt::PenCapStyle capStyle() const;
bind::member_function<QPen, Qt::PenCapStyle, &QPen::capStyle>(pen, "capStyle").create();
// void setCapStyle(Qt::PenCapStyle);
bind::void_member_function<QPen, Qt::PenCapStyle, &QPen::setCapStyle>(pen, "setCapStyle").create();
// Qt::PenJoinStyle joinStyle() const;
bind::member_function<QPen, Qt::PenJoinStyle, &QPen::joinStyle>(pen, "joinStyle").create();
// void setJoinStyle(Qt::PenJoinStyle);
bind::void_member_function<QPen, Qt::PenJoinStyle, &QPen::setJoinStyle>(pen, "setJoinStyle").create();
// bool isCosmetic() const;
bind::member_function<QPen, bool, &QPen::isCosmetic>(pen, "isCosmetic").create();
// void setCosmetic(bool);
bind::void_member_function<QPen, bool, &QPen::setCosmetic>(pen, "setCosmetic").create();
// bool operator==(const QPen &) const;
bind::memop_eq<QPen, const QPen &>(pen);
// bool operator!=(const QPen &) const;
bind::memop_neq<QPen, const QPen &>(pen);
// bool isDetached();
bind::member_function<QPen, bool, &QPen::isDetached>(pen, "isDetached").create();
// QPen::DataPtr & data_ptr();
/// TODO: QPen::DataPtr & data_ptr();
yasl::registerVariantHandler<yasl::GenericVariantHandler<QPen, QMetaType::QPen>>();
}
void register_pen_file(script::Namespace gui)
{
using namespace script;
Namespace ns = gui;
register_pen_class(ns);
// QDataStream & operator<<(QDataStream &, const QPen &);
bind::op_put_to<QDataStream &, const QPen &>(ns);
// QDataStream & operator>>(QDataStream &, QPen &);
bind::op_read_from<QDataStream &, QPen &>(ns);
// QDebug operator<<(QDebug, const QPen &);
/// TODO: QDebug operator<<(QDebug, const QPen &);
}
| 43.5 | 130 | 0.689278 |
391c0b1db60f0ee832b02ec7d5d68bf8ce29d2e2 | 2,958 | cpp | C++ | src/coreclr/pal/tests/palsuite/threading/SetThreadDescription/test1/test1.cpp | msallin/runtime | d99ddd0699dc209714ca8d5e9ff1f5706604911a | [
"MIT"
] | 2 | 2019-11-06T16:30:23.000Z | 2019-11-26T01:48:54.000Z | src/coreclr/pal/tests/palsuite/threading/SetThreadDescription/test1/test1.cpp | msallin/runtime | d99ddd0699dc209714ca8d5e9ff1f5706604911a | [
"MIT"
] | 1 | 2020-05-15T17:23:38.000Z | 2020-05-26T18:47:59.000Z | src/coreclr/pal/tests/palsuite/threading/SetThreadDescription/test1/test1.cpp | msallin/runtime | d99ddd0699dc209714ca8d5e9ff1f5706604911a | [
"MIT"
] | 1 | 2020-01-20T07:14:53.000Z | 2020-01-20T07:14:53.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================
**
** Source: test1.cpp
**
** Purpose: Test for SetThreadDescription. Create a thread, call
** SetThreadDescription, and then verify that the name of the thread
** matches what was set.
**
**=========================================================*/
#include <palsuite.h>
#include "pthread_helpers.hpp"
char * threadName;
char * expectedThreadName;
char * actualThreadName;
DWORD PALAPI SetThreadDescriptionTestThread(LPVOID lpParameter)
{
HANDLE palThread = GetCurrentThread();
WCHAR wideThreadName[256];
MultiByteToWideChar(CP_ACP, 0, threadName, strlen(threadName)+1, wideThreadName, 256);
SetThreadDescription(palThread, wideThreadName);
actualThreadName = GetThreadName();
return 0;
}
BOOL SetThreadDescriptionTest(char* name, char* expected)
{
BOOL bResult = FALSE;
LPSECURITY_ATTRIBUTES lpThreadAttributes = NULL;
DWORD dwStackSize = 0;
LPTHREAD_START_ROUTINE lpStartAddress = &SetThreadDescriptionTestThread;
LPVOID lpParameter = (LPVOID)SetThreadDescriptionTestThread;
DWORD dwCreationFlags = 0;
DWORD dwThreadId = 0;
threadName = name;
expectedThreadName = expected;
HANDLE hThread = CreateThread(lpThreadAttributes,
dwStackSize, lpStartAddress, lpParameter,
dwCreationFlags, &dwThreadId );
if (hThread != INVALID_HANDLE_VALUE)
{
WaitForSingleObject(hThread, INFINITE);
bResult = strcmp(actualThreadName, expectedThreadName) == 0;
}
else
{
Trace("Unable to create SetThreadDescription test thread");
}
return bResult;
}
BOOL SetThreadDescriptionTests()
{
if (!SetThreadDescriptionTest("Hello, World", "Hello, World"))
{
Trace("Setting thread name failed");
return FAIL;
}
// verify that thread name truncations works correctly on linux on macOS.
char * threadName = "aaaaaaa_15chars_aaaaaaa_31chars_aaaaaaaaaaaaaaaaaaaaaaa_63chars_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
char * expected;
#if defined(__APPLE__)
expected = "aaaaaaa_15chars_aaaaaaa_31chars_aaaaaaaaaaaaaaaaaaaaaaa_63chars";
#else
expected = "aaaaaaa_15chars";
#endif
if (!SetThreadDescriptionTest(threadName, expected))
{
return PASS;
}
return FAIL;
}
PALTEST(threading_SetThreadDescription_test1_paltest_setthreaddescription_test1, "threading/SetThreadDescription/test1/paltest_setthreaddescription_test1")
{
if (0 != (PAL_Initialize(argc, argv)))
{
return FAIL;
}
BOOL result = SetThreadDescriptionTests();
if(actualThreadName) free(actualThreadName);
if (!result)
{
Fail("Test Failed");
}
PAL_Terminate();
return PASS;
}
| 27.90566 | 155 | 0.670047 |
391da41161d8c93e6cd163901fb74d288ce51d8d | 12,227 | cpp | C++ | src/mesh.cpp | mohawkjohn/projected_area | d7c65d3d5b2a46a8f0d6d949dab04c2ac70ed1c2 | [
"Unlicense"
] | 1 | 2020-06-28T19:46:40.000Z | 2020-06-28T19:46:40.000Z | src/mesh.cpp | autumnsault/projected_area | d7c65d3d5b2a46a8f0d6d949dab04c2ac70ed1c2 | [
"Unlicense"
] | null | null | null | src/mesh.cpp | autumnsault/projected_area | d7c65d3d5b2a46a8f0d6d949dab04c2ac70ed1c2 | [
"Unlicense"
] | null | null | null | /*
* Copyright (c) 2014 - 2017, John O. Woods, Ph.D.
* West Virginia University Applied Space Exploration Lab (2014 - 2015)
* West Virginia Robotic Technology Center (2014 - 2015)
* Intuitive Machines (2017)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
/** @file
**
** @brief Implementation for Assimp-loaded Mesh. See notes on mesh.hpp.
**/
#include "../include/mesh.hpp"
void Mesh::render(Shader* shader_program) {
shader_program->bind();
check_gl_error();
GLuint position_loc = glGetAttribLocation(shader_program->id(), "position");
//GLuint normal_loc = glGetAttribLocation(shader_program->id(), "normal");
check_gl_error();
glEnableVertexAttribArray(position_loc);
check_gl_error();
//glEnableVertexAttribArray(normal_loc);
//check_gl_error();
for (size_t i = 0; i < entries.size(); ++i) {
glBindBuffer(GL_ARRAY_BUFFER, entries[i].vb);
// I think this tells it where to look for the vertex information we've loaded.
glVertexAttribPointer(position_loc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
//glVertexAttribPointer(normal_loc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)28); // makes room for 7 floats
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, entries[i].ib);
//glColor4f(1.0, 1.0, 1.0, 1.0);
glDrawElements(GL_TRIANGLES, entries[i].num_indices, GL_UNSIGNED_INT, 0);
}
check_gl_error();
glDisableVertexAttribArray(position_loc);
//glDisableVertexAttribArray(normal_loc);
check_gl_error();
shader_program->unbind();
glFlush(); // replaces glfwSwapBuffers()
}
void Mesh::init_mesh(const aiScene* scene, const aiMesh* mesh, size_t index) {
std::cerr << "Loading mesh named '" << mesh->mName.C_Str() << "'" << std::endl;
if (!mesh->HasNormals()) {
std::cerr << "Mesh has no normals!" << std::endl;
} else {
if (mesh->mNumVertices > 0)
std::cerr << "First normal:" << mesh->mNormals[0].x << "," << mesh->mNormals[0].y << "," << mesh->mNormals[0].z << std::endl;
}
// Create vectors to store the transformed position and normals; initialize them to the origin.
std::vector<aiVector3D> final_pos(mesh->mNumVertices);
// final_normal(mesh->mNumVertices);
for (size_t i = 0; i < mesh->mNumVertices; ++i) {
final_pos[i] = aiVector3D(0.0, 0.0, 0.0); // final_normal[i] =
}
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
const aiVector3D zero_3d(0.0, 0.0, 0.0);
if (mesh->mNumBones) {
std::vector<aiMatrix4x4> bone_matrices(mesh->mNumBones);
// Calculate bone matrices.
for (size_t i = 0; i < mesh->mNumBones; ++i) {
const aiBone* bone = mesh->mBones[i];
bone_matrices[i] = bone->mOffsetMatrix;
std::cerr << "Bone '" << bone->mName.C_Str() << "' includes " << bone->mNumWeights << " vertices:" << std::endl;
for (size_t j = 0; j < bone->mNumWeights; ++j) {
std::cerr << ' ' << bone->mWeights[j].mVertexId;
}
std::cerr << std::endl;
const aiNode* node = scene->mRootNode->FindNode(bone->mName.C_Str());
const aiNode* temp_node = node;
while (temp_node != NULL) {
bone_matrices[i] = temp_node->mTransformation * bone_matrices[i];
temp_node = temp_node->mParent;
}
}
// Update vertex positions according to calculated matrices
for (size_t i = 0; i < mesh->mNumBones; ++i) {
const aiBone* bone = mesh->mBones[i];
//aiMatrix3x3 normal_matrix = aiMatrix3x3(bone_matrices[i]);
for (size_t j = 0; j < bone->mNumWeights; ++j) {
const aiVertexWeight *vertex_weight = &(bone->mWeights[j]);
size_t v = (size_t)(vertex_weight->mVertexId);
float w = vertex_weight->mWeight;
const aiVector3D *src_pos = &(mesh->mVertices[v]);
//const aiVector3D *src_normal = &(mesh->mNormals[v]);
final_pos[v] += w * (bone_matrices[i] * (*src_pos));
//final_normal[v] += w * (normal_matrix * (*src_normal));
}
std::cerr << "bone " << i << ":" << std::endl;
std::cerr << bone_matrices[i].a1 << ' ' << bone_matrices[i].a2 << ' ' << bone_matrices[i].a3 << ' ' << bone_matrices[i].a4 << std::endl;
std::cerr << bone_matrices[i].b1 << ' ' << bone_matrices[i].b2 << ' ' << bone_matrices[i].b3 << ' ' << bone_matrices[i].b4 << std::endl;
std::cerr << bone_matrices[i].c1 << ' ' << bone_matrices[i].c2 << ' ' << bone_matrices[i].c3 << ' ' << bone_matrices[i].c4 << std::endl;
std::cerr << bone_matrices[i].d1 << ' ' << bone_matrices[i].d2 << ' ' << bone_matrices[i].d3 << ' ' << bone_matrices[i].d4 << std::endl;
}
// initialize our dimension trackers.
if (mesh->mNumVertices != 0) {
min_extremities.x = final_pos[0].x;
min_extremities.y = final_pos[0].y;
min_extremities.z = final_pos[0].z;
max_extremities = min_extremities;
}
// Add each updated vertex and calculate its extremities.
for (size_t i = 0; i < mesh->mNumVertices; ++i) {
// Find the extremities of this mesh so we can get a measurement for the object in object units.
if (final_pos[i].x < min_extremities.x) min_extremities.x = final_pos[i].x;
else if (final_pos[i].x > max_extremities.x) max_extremities.x = final_pos[i].x;
if (final_pos[i].y < min_extremities.y) min_extremities.y = final_pos[i].y;
else if (final_pos[i].y > max_extremities.y) max_extremities.y = final_pos[i].y;
if (final_pos[i].z < min_extremities.z) min_extremities.z = final_pos[i].z;
else if (final_pos[i].z > max_extremities.z) max_extremities.z = final_pos[i].z;
Vertex vertex(glm::vec3(final_pos[i].x, final_pos[i].y, final_pos[i].z));
// glm::vec3(final_normal[i].x, final_normal[i].y, final_normal[i].z));
std::cerr << "Adding vertex " << i << ": " << final_pos[i].x << "," << final_pos[i].y << "," << final_pos[i].z;
// std::cerr << "\t" << final_normal[i].x << "," << final_normal[i].y << "," << final_normal[i].z << std::endl;
std::cerr << " was: " << mesh->mVertices[i].x << "," << mesh->mVertices[i].y << "," << mesh->mVertices[i].z << std::endl;
// std::cerr << mesh->mNormals[i].x << "," << mesh->mNormals[i].y << "," << mesh->mNormals[i].z << std::endl;
// Accumulate the centroid_ of the object.
centroid_ += vertex.pos;
vertices.push_back(vertex);
}
} else {
for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
const aiVector3D* pos = &(mesh->mVertices[i]);
//const aiVector3D* normal = &(mesh->mNormals[i]);
// Find the extremities of this mesh so we can get a measurement for the object in object units.
if (pos->x < min_extremities.x) min_extremities.x = pos->x;
else if (pos->x > max_extremities.x) max_extremities.x = pos->x;
if (pos->y < min_extremities.y) min_extremities.y = pos->y;
else if (pos->y > max_extremities.y) max_extremities.y = pos->y;
if (pos->z < min_extremities.z) min_extremities.z = pos->z;
else if (pos->z > max_extremities.z) max_extremities.z = pos->z;
Vertex v(glm::vec3(pos->x, pos->y, pos->z));
// glm::vec3(normal->x, normal->y, normal->z));
// Accumulate the centroid_ of the object.
centroid_ += v.pos;
vertices.push_back(v);
}
}
centroid_ /= mesh->mNumVertices;
// Add vertices for each face
for (size_t i = 0; i < mesh->mNumFaces; ++i) {
const aiFace& face = mesh->mFaces[i];
if (face.mNumIndices != 3) {
std::cerr << "Face has " << face.mNumIndices << " indices; skipping" << std::endl;
continue;
}
indices.push_back(face.mIndices[0]);
indices.push_back(face.mIndices[1]);
indices.push_back(face.mIndices[2]);
}
// Create index buffer.
entries[index].init(vertices, indices);
}
bool Mesh::load_mesh(const std::string& filename)
{
bool ret = false;
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(filename.c_str(), aiProcess_Triangulate | aiProcess_GenNormals );
if (scene) ret = init_from_scene(scene, filename);
else std::cerr << "Error parsing '" << filename << "': " << importer.GetErrorString() << std::endl;
return ret;
}
/** @brief Find the nearest point among all the meshes to some point p.
*
* @param[in] query point.
* @param[out] result point.
*
* @returns a distance.
*/
float Mesh::nearest_point(const glm::vec4& p, glm::vec4& result) const {
float d = entries[0].nearest_point(p, result);
for (size_t i = 1; i < entries.size(); ++i) {
glm::vec4 tmp_result;
float tmp_distance;
tmp_distance = entries[i].nearest_point(p, tmp_result);
if (tmp_distance < d) {
d = tmp_distance;
result = tmp_result;
}
}
return d;
}
/** @brief Find the ideal location of the near plane.
*
* @param[in] model coordinate matrix.
* @param[in] camera position.
*
* @returns The distance from the camera to the ideal near plane if we didn't mind the plane intersecting the nearest point.
*/
float Mesh::near_plane_bound(const glm::mat4& model_to_object_coords, const glm::vec4& camera_pos) const {
glm::vec4 nearest;
// Find the nearest point in the mesh.
nearest_point(camera_pos, nearest);
nearest.w = 0.0;
float bound = (model_to_object_coords * (camera_pos - nearest)).z;
if (bound <= 0) {
std::cerr << "WARNING: Nearest point on object is behind the sensor, which makes for an invalid near plane setting. Using MIN_NEAR_PLANE="
<< MIN_NEAR_PLANE << " distance units for the bound. Actual near plane will be slightly closer, depending on your value for NEAR_PLANE_FACTOR."
<< std::endl;
bound = MIN_NEAR_PLANE;
}
return bound;
}
/** @brief Find the ideal location of the far plane.
*
* @param[in] model coordinate matrix.
* @param[in] camera position.
*
* @returns The distance from the camera to the ideal far plane if we didn't mind the plane intersecting the farthest point.
*/
float Mesh::far_plane_bound(const glm::mat4& model_to_object_coords, const glm::vec4& camera_pos) const {
// Find the farthest point in the mesh
glm::vec4 negative_camera_pos(-camera_pos);
glm::vec4 farthest;
nearest_point(negative_camera_pos, farthest);
farthest.w = 0.0;
return (model_to_object_coords * (camera_pos - farthest)).z;
}
bool Mesh::init_from_scene(const aiScene* scene, const std::string& filename) {
entries.resize(scene->mNumMeshes);
std::cerr << "Reading " << entries.size() << " meshes" << std::endl;
// Initialize the meshes in the scene one by one
for (size_t i = 0; i < entries.size(); ++i) {
const aiMesh* mesh = scene->mMeshes[i];
init_mesh(scene, mesh, i);
}
return true;
}
| 37.391437 | 158 | 0.649301 |
3920af713b3a1c2f83dd434fb1f913cdc16794c4 | 2,096 | cpp | C++ | API/ReconDemo/Geometry/Rect2D.cpp | PengJinFa/YAPNew | fafee8031669b24d0cc74876a477c97d0d7ebadc | [
"MIT"
] | null | null | null | API/ReconDemo/Geometry/Rect2D.cpp | PengJinFa/YAPNew | fafee8031669b24d0cc74876a477c97d0d7ebadc | [
"MIT"
] | null | null | null | API/ReconDemo/Geometry/Rect2D.cpp | PengJinFa/YAPNew | fafee8031669b24d0cc74876a477c97d0d7ebadc | [
"MIT"
] | null | null | null |
#include "Rect2D.h"
#include <utility>
#include <assert.h>
using namespace Geometry;
/**
Default constructor. All members initialized to zero.
*/
CRect2D::CRect2D()
{
_left = _right = _top = _bottom = 0.0;
}
/**
Constructs an object from the four side of the rectangle.
*/
CRect2D::CRect2D(double left,
double top,
double right,
double bottom)
{
_left = left;
_right = right;
_top = top;
_bottom = bottom;
}
/**
Normalize the rectangle, that is, to make sure the left side of rectangle
is less than the right and the top is less than the bottom.
*/
void CRect2D::Normalize()
{
if (_left > _right)
{
std::swap(_left, _right);
}
if (_top > _bottom)
{
std::swap(_top, _bottom);
}
}
/**
Check to see if a given point is in the rectangle.
@param pt Point to test.
\pre The rectangle must be normalized before calling this function.
You can call NormallizeRect() to normalize the rectangle.
*/
bool CRect2D::Contains(const Point2D& pt)
{
// the rectangle must be normalized before calling this function.
assert((_left <= _right) && (_top <= _bottom));
return (pt.x >= _left && pt.x < _right && pt.y >= _top && pt.y < _bottom);
}
/**
Inflate the rectangle by the given value.
@param dDeltaX Amount to inflate on left and right side.
@param dDeltaY Amount to inflate on top and bottom side.
\pre The rectangle must be normalized before calling this function.
*/
void CRect2D::InflateRect(double delta_x, double delta_y)
{
// the rectangle must be normalized before calling this function.
assert((_left <= _right) && (_top <= _bottom));
_left -= delta_x;
_right += delta_x;
_top -= delta_y;
_bottom += delta_y;
}
/// Constructor.
/**
This function constructs a CGenericRect from its top left corner and size.
@param point Coordinate ot the top left corner of the rectangle.
@param size Size of the rectangle.
*/
CRect2D::CRect2D(const Point2D& point,
const Vector2D& size)
{
_left = point.x;
_right = point.x + size.cx;
_top = point.y;
_bottom = point.y + size.cy;
}
| 23.032967 | 75 | 0.671756 |
392427e59bed278479a35b3e6ff5951f21cb75ed | 2,802 | cpp | C++ | unit_tests/test_playable_moves.cpp | julienlopez/Aronda | 8fb6625bc037736dc2926f97f46a59441d7dc221 | [
"MIT"
] | null | null | null | unit_tests/test_playable_moves.cpp | julienlopez/Aronda | 8fb6625bc037736dc2926f97f46a59441d7dc221 | [
"MIT"
] | 4 | 2018-02-21T15:38:56.000Z | 2019-04-03T07:57:22.000Z | unit_tests/test_playable_moves.cpp | julienlopez/Aronda | 8fb6625bc037736dc2926f97f46a59441d7dc221 | [
"MIT"
] | null | null | null | #include <catch.hpp>
#include "game.hpp"
#include <numeric_range.hpp>
#include <boost/optional/optional_io.hpp>
using Aronda::Board;
using Aronda::Game;
using Aronda::InvalidMove;
using Aronda::Square;
using Aronda::SquareState;
template <class T> bool contains(const std::vector<T>& container, const T& value)
{
return std::find(begin(container), end(container), value) != end(container);
}
TEST_CASE("Testing playable moves throughout the game", "[board]")
{
SECTION("Only the outside squares are playable on an empty board")
{
Board g;
const std::vector<std::size_t> playable_moves = {17, 18, 19, 20, 21, 22, 23, 24};
for(const auto square : range<std::size_t>(0, Aronda::c_number_of_squares))
{
const auto res = g.placeStone({Square{square}, Aronda::black, 1});
if(contains(playable_moves, square))
{
CHECK(res.has_value());
}
else
{
REQUIRE_FALSE(res.has_value());
CHECK(res.error() == InvalidMove::SquareUnreachable);
}
}
}
SECTION("Only the outside squares are playable for white's first move")
{
Board b;
const auto res = b.placeStone({Square{24}, Aronda::black, 1});
REQUIRE(res.has_value());
b = res.value();
const std::vector<std::size_t> playable_moves = {17, 18, 19, 20, 21, 22, 23, 24};
for(const auto square : range<std::size_t>(0, Aronda::c_number_of_squares))
{
const auto res = b.placeStone({Square{square}, Aronda::white, 1});
if(contains(playable_moves, square))
{
CHECK(res.has_value());
}
else
{
REQUIRE_FALSE(res.has_value());
CHECK(res.error() == InvalidMove::SquareUnreachable);
}
}
}
SECTION("Playing one stone on an outside square unlocks all underlying squares")
{
Game g;
auto res = g.placeStone({Square{24}, Aronda::black, 1});
REQUIRE(res.has_value());
res = g.placeStone({Square{24}, Aronda::white, 1});
REQUIRE(res.has_value());
const std::vector<std::size_t> playable_moves = {9, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24};
for(const auto square : range<std::size_t>(0, Aronda::c_number_of_squares))
{
const auto res = g.currentState().placeStone({Square{square}, Aronda::white, 1});
if(contains(playable_moves, square))
{
CHECK(res.has_value());
}
else
{
REQUIRE_FALSE(res.has_value());
CHECK(res.error() == InvalidMove::SquareUnreachable);
}
}
}
}
| 32.206897 | 100 | 0.557459 |
3925abaa7badfff6e1e3812a0746619d5ddfbaa4 | 132 | cpp | C++ | OpenGLTutorial/src/physics/collisionmodel.cpp | michaelg29/OpenGLTutorial | e1db34109eca435581c4224976d669e0fe44afd4 | [
"CC-BY-4.0"
] | 2 | 2022-03-20T11:20:19.000Z | 2022-03-23T01:58:25.000Z | OpenGLTutorial/src/physics/collisionmodel.cpp | michaelg29/OpenGLTutorial | e1db34109eca435581c4224976d669e0fe44afd4 | [
"CC-BY-4.0"
] | 12 | 2020-02-17T05:19:01.000Z | 2022-03-17T14:56:38.000Z | OpenGLTutorial/src/physics/collisionmodel.cpp | michaelg29/OpenGLTutorial | e1db34109eca435581c4224976d669e0fe44afd4 | [
"CC-BY-4.0"
] | 1 | 2022-01-25T16:48:21.000Z | 2022-01-25T16:48:21.000Z | #include "collisionmodel.h"
#include "../graphics/objects/model.h"
CollisionModel::CollisionModel(Model* model)
: model(model) {} | 22 | 44 | 0.742424 |
3927538b461a290b31713b17dcd1b427bbf1a297 | 736 | cpp | C++ | tests/test18.cpp | varnie/giraffe | 0448536cdca5dad66110aa64fdf24688b2a0050a | [
"MIT"
] | null | null | null | tests/test18.cpp | varnie/giraffe | 0448536cdca5dad66110aa64fdf24688b2a0050a | [
"MIT"
] | 1 | 2020-06-16T14:25:17.000Z | 2020-06-16T14:25:17.000Z | tests/test18.cpp | varnie/giraffe | 0448536cdca5dad66110aa64fdf24688b2a0050a | [
"MIT"
] | null | null | null | //
// Created by varnie on 2/23/16.
//
#include <gtest/gtest.h>
#include "../include/Giraffe.h"
TEST(StorageTest, CheckRetrievingAllEntities) {
struct Foo {
Foo() { }
};
using StorageT = Giraffe::Storage<>;
using EntityT = Giraffe::Entity<StorageT>;
StorageT storage;
for (int i = 0; i < 5; ++i) {
EntityT e = storage.addEntity();
}
std::size_t count1 = 0, count2 = 0;
for (const auto &entity: storage.range()) {
++count1;
}
EXPECT_EQ(count1, 5);
storage.process([&](const EntityT &entity) {
++count2;
});
EXPECT_EQ(count2, 5);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 17.52381 | 48 | 0.576087 |
392770182075de0f956a67a461d133ca273fc07b | 1,231 | cpp | C++ | Notes_Week3/composition.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | 1 | 2019-01-06T22:36:01.000Z | 2019-01-06T22:36:01.000Z | Notes_Week3/composition.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | Notes_Week3/composition.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double width;
public:
void setLength(double len) {
length = len;
}
void setWidth(double wid) {
width = wid;
}
double getLength() {
return length;
}
double getWidth() {
return width;
}
double calcArea() {
return length * width;
}
};
class Carpet {
private:
double pricePerSqYd;
Rectangle size; // Instance of the Rentangle class
public:
void setPricePerYd(double p) {
pricePerSqYd = p;
}
void setDimensions(double len, double wid) {
size.setLength(len/3);
size.setWidth(wid/3);
}
double getTotalPrice() {
return (size.calcArea() * pricePerSqYd);
}
};
int main() {
Carpet purchase;
double pricePerSqYd;
double length;
double width;
cout << "Room length in feat: ";
cin >> length;
cout << "Room width in feet: ";
cin >> width;
cout << "Carpet price per sq. yard: ";
cin >> pricePerSqYd;
purchase.setDimensions(length, width);
purchase.setPricePerYd(pricePerSqYd);
cout << "\n The total price of my new carpet is $" << purchase.getTotalPrice() << endl;
return 0;
}
| 17.84058 | 89 | 0.607636 |
392b50d729fc87eed2c45f0554e10b2f27e19709 | 1,949 | cpp | C++ | texture-packer/src/main/Functions/main.cpp | ii887522/texture-packer | 0dc2b6656329f427881c36ddafc0196447c74926 | [
"MIT"
] | null | null | null | texture-packer/src/main/Functions/main.cpp | ii887522/texture-packer | 0dc2b6656329f427881c36ddafc0196447c74926 | [
"MIT"
] | null | null | null | texture-packer/src/main/Functions/main.cpp | ii887522/texture-packer | 0dc2b6656329f427881c36ddafc0196447c74926 | [
"MIT"
] | null | null | null | // Copyright ii887522
#ifndef TEST
#define ALLOCATOR_IMPLEMENTATIONS
#include <nitro/nitro.h>
#include <SDL.h>
#include <viewify/viewify.h>
#include <iostream>
#include <stdexcept>
#include <filesystem>
#include "../ViewGroupFactory/TexturePackerViewGroupFactory.h"
#include "../Any/CommandLine.h"
#include <SDL_image.h>
using ii887522::viewify::App;
using ii887522::viewify::Subsystems;
using ii887522::viewify::Size;
using ii887522::viewify::Color;
using ii887522::viewify::eventLoop;
using std::cerr;
using std::invalid_argument;
using std::filesystem::directory_iterator;
namespace ii887522::texturePacker {
static int main(int argc, char** argv) try {
const CommandLine commandLine{ argc, argv };
commandLine.validate();
const Subsystems subsystems;
TexturePackerViewGroupFactory texturePackerViewGroupFactory{ commandLine.getInputDirPath(), commandLine.getOutputDirPath(), commandLine.getAtlasSize() };
// See also ../ViewGroupFactory/TexturePackerViewGroupFactory.h for more details
eventLoop(App{ "Texture Packer", commandLine.getAtlasSize(), Color{ 0u, 0u, 0u, 0u }, &texturePackerViewGroupFactory, SDL_WINDOW_MINIMIZED });
return EXIT_SUCCESS;
} catch (const invalid_argument&) {
cerr << "Command Line: texture-packer <input-directory-path> <output-directory-path> <atlas-width> <atlas-height>\n";
cerr << "Param <input-directory-path>: it must exists, has at least 1 png file and ends with either '/' or '\\'\n";
cerr << "Param <output-directory-path>: it must ends with either '/' or '\\'\n";
cerr << "Param <atlas-width>: it must be equal to 2^n where n is a non-negative integer, and big enough to fill sprites\n";
cerr << "Param <atlas-height>: it must be equal to 2^n where n is a non-negative integer, and big enough to fill sprites\n";
return EXIT_FAILURE;
}
} // namespace ii887522::texturePacker
int main(int argc, char** argv) {
return ii887522::texturePacker::main(argc, argv);
}
#endif
| 37.480769 | 155 | 0.746537 |
3930edb38c8069acc6af05d921b0fc3c51491186 | 982 | cpp | C++ | LoveLiveWallpaper/src/Interactable.cpp | Juvwxyz/LoveLiveWallpaper | a0eeac941b5ccd53af538192cb92b7df049839c4 | [
"MIT"
] | 2 | 2020-05-09T00:13:06.000Z | 2020-05-25T05:49:40.000Z | LoveLiveWallpaper/src/Interactable.cpp | Juvwxyz/LoveLiveWallpaper | a0eeac941b5ccd53af538192cb92b7df049839c4 | [
"MIT"
] | null | null | null | LoveLiveWallpaper/src/Interactable.cpp | Juvwxyz/LoveLiveWallpaper | a0eeac941b5ccd53af538192cb92b7df049839c4 | [
"MIT"
] | 1 | 2020-05-25T05:49:44.000Z | 2020-05-25T05:49:44.000Z | #include "Interactable.h"
#include "Component.h"
#include "Mouse.h"
#include "MouseEventArg.h"
#include "Transform.h"
namespace LLWP
{
Interactable::Interactable()
{
Mouse::OnHitTest += (*this, &Interactable::OnHitTest);
}
bool Interactable::OnHitTest(Interactable*& hitted, const MouseEventArg& arg)
{
Component* thisComponent = dynamic_cast<Component*>(this);
if (thisComponent->transform().HitTest(arg.position().x, arg.position().y))
{
if (hitted == nullptr)
{
hitted = this;
return true;
}
else if (dynamic_cast<Component*>(hitted)->transform().position().z() <= thisComponent->transform().position().z())
{
hitted = this;
return true;
}
}
return false;
}
Interactable::~Interactable()
{
Mouse::OnHitTest -= (*this, &Interactable::OnHitTest);
}
}
| 26.540541 | 127 | 0.550916 |
3932962e99e15a87428393817850c8fb38c73874 | 1,441 | hpp | C++ | include/argot/concepts/reference.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | 49 | 2018-05-09T23:17:45.000Z | 2021-07-21T10:05:19.000Z | include/argot/concepts/reference.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | null | null | null | include/argot/concepts/reference.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | 2 | 2019-08-04T03:51:36.000Z | 2020-12-28T06:53:29.000Z | /*==============================================================================
Copyright (c) 2017, 2018, 2019 Matt Calabrese
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef ARGOT_CONCEPTS_REFERENCE_HPP_
#define ARGOT_CONCEPTS_REFERENCE_HPP_
//[description
/*`
Reference is an [argot_gen_concept] that is satisfied by reference types.
*/
//]
#include <argot/concepts/detail/concepts_preprocessing_helpers.hpp>
#include <argot/gen/explicit_concept.hpp>
#include <argot/gen/make_concept_map.hpp>
namespace argot {
#define ARGOT_DETAIL_PREPROCESSED_CONCEPT_HEADER_NAME() \
s/reference.h
#ifdef ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER
#include ARGOT_CONCEPTS_DETAIL_PREPROCESSED_HEADER
#else
#include <argot/concepts/detail/preprocess_header_begin.hpp>
ARGOT_CONCEPTS_DETAIL_CREATE_LINE_DIRECTIVE( __LINE__ )
template< class T >
ARGOT_EXPLICIT_CONCEPT( Reference )
(
);
#include <argot/concepts/detail/preprocess_header_end.hpp>
#endif // ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER
template< class T >
struct make_concept_map< Reference< T& > > {};
template< class T >
struct make_concept_map< Reference< T&& > > {};
} // namespace argot
#endif // ARGOT_CONCEPTS_REFERENCE_HPP_
| 27.711538 | 80 | 0.700902 |
39410f0a0e8766d77f03a940a2f9f9f063b966d9 | 4,968 | cpp | C++ | test/path_append_test.cpp | abdes/asap_filesystem | 44b8ab19900db6ce58a8802817a5b42d6ab6a4b3 | [
"BSD-3-Clause"
] | 3 | 2019-05-20T14:21:11.000Z | 2019-05-21T19:09:13.000Z | test/path_append_test.cpp | abdes/asap_filesystem | 44b8ab19900db6ce58a8802817a5b42d6ab6a4b3 | [
"BSD-3-Clause"
] | null | null | null | test/path_append_test.cpp | abdes/asap_filesystem | 44b8ab19900db6ce58a8802817a5b42d6ab6a4b3 | [
"BSD-3-Clause"
] | null | null | null | // Copyright The Authors 2018.
// Distributed under the 3-Clause BSD License.
// (See accompanying file LICENSE or copy at
// https://opensource.org/licenses/BSD-3-Clause)
#if defined(__clang__)
#pragma clang diagnostic push
// Catch2 uses a lot of macro names that will make clang go crazy
#if (__clang_major__ >= 13) && !defined(__APPLE__)
#pragma clang diagnostic ignored "-Wreserved-identifier"
#endif
// Big mess created because of the way spdlog is organizing its source code
// based on header only builds vs library builds. The issue is that spdlog
// places the template definitions in a separate file and explicitly
// instantiates them, so we have no problem at link, but we do have a problem
// with clang (rightfully) complaining that the template definitions are not
// available when the template needs to be instantiated here.
#pragma clang diagnostic ignored "-Wundefined-func-template"
#endif // __clang__
#include <catch2/catch.hpp>
#include "fs_testsuite.h"
using testing::ComparePaths;
using testing::TEST_PATHS;
// path::operator/=(const path&)
namespace {
auto Append(fs::path l, const fs::path &r) -> fs::path {
l /= r;
return l;
}
} // namespace
// -----------------------------------------------------------------------------
// Append
// -----------------------------------------------------------------------------
TEST_CASE("Path / append / path", "[common][filesystem][path][append]") {
ComparePaths(Append("/foo/bar", "/foo/"), "/foo/");
ComparePaths(Append("baz", "baz"), "baz/baz");
ComparePaths(Append("baz/", "baz"), "baz/baz");
ComparePaths(Append("baz", "/foo/bar"), "/foo/bar");
ComparePaths(Append("baz/", "/foo/bar"), "/foo/bar");
REQUIRE(Append("", "").empty());
REQUIRE(!Append("", "rel").is_absolute());
ComparePaths(Append("dir/", "/file"), "/file");
ComparePaths(Append("dir/", "file"), "dir/file");
// path("foo") / ""; // yields "foo/"
ComparePaths(Append("foo", ""), "foo/");
// path("foo") / "/bar"; // yields "/bar"
ComparePaths(Append("foo", "/bar"), "/bar");
// path("foo") / ""; // yields "foo/"
ComparePaths(Append("foo", ""), "foo/");
// path("foo") / "/bar"; // yields "/bar"
ComparePaths(Append("foo", "/bar"), "/bar");
#if defined(ASAP_WINDOWS)
ComparePaths(Append("//host", "foo"), "//host/foo");
ComparePaths(Append("//host/", "foo"), "//host/foo");
ComparePaths(Append("//host/bar", "foo"), "//host/bar/foo");
ComparePaths(Append("//host", "/foo"), "//host/foo");
ComparePaths(Append("//host", "//other/foo"), "//other/foo");
ComparePaths(Append("//host/bar", "//other/foo"), "//other/foo");
ComparePaths(Append("c:/foo", "/bar"), "c:/bar");
// path("c:") / ""; // yields "c:"
ComparePaths(Append("c:", ""), "c:");
// path("c:foo") / "/bar"; // yields "c:/bar"
ComparePaths(Append("c:foo", "/bar"), "c:/bar");
// path("c:foo") / "c:bar"; // yields "c:foo/bar"
ComparePaths(Append("c:foo", "c:bar"), "c:foo/bar");
// path("foo") / "c:/bar"; // yields "c:/bar"
ComparePaths(Append("foo", "c:/bar"), "c:/bar");
// path("foo") / "c:"; // yields "c:"
ComparePaths(Append("foo", "c:"), "c:");
#endif // ASAP_WINDOWS
}
// path::operator/=(const Source& source)
// path::Append(const Source& source)
// Equivalent to: return operator/=(path(source));
// path::Append(InputIterator first, InputIterator last)
// Equivalent to: return operator/=(path(first, last));
template <typename Char> void test(const fs::path &p, const Char *s) {
fs::path expected = p;
expected /= fs::path(s);
fs::path oper = p;
oper /= s;
fs::path func = p;
func.append(s);
std::vector<char> input_range(s, s + std::char_traits<Char>::length(s));
fs::path range = p;
range.append(input_range.begin(), input_range.end());
ComparePaths(oper, expected);
ComparePaths(func, expected);
ComparePaths(range, expected);
}
TEST_CASE("Path / append / source", "[common][filesystem][fs::path][append]") {
test("/foo/bar", "/foo/");
test("baz", "baz");
test("baz/", "baz");
test("baz", "/foo/bar");
test("baz/", "/foo/bar");
test("", "");
test("", "rel");
test("dir/", "/file");
test("dir/", "file");
// C++17 [fs.fs::path.append] p4
test("//host", "foo");
test("//host/", "foo");
test("foo", "");
test("foo", "/bar");
test("foo", "c:/bar");
test("foo", "c:");
test("c:", "");
test("c:foo", "/bar");
test("foo", "c:\\bar");
}
TEST_CASE("Path / append / source / TEST_PATHS", "[common][filesystem][fs::path][append]") {
for (const fs::path p : TEST_PATHS()) {
for (const fs::path q : TEST_PATHS()) {
test(p, q.c_str());
}
}
}
// TODO(abdessattar): figure later wstring vs string correct impl
/*
TEST_CASE("Path / append / source / wstring",
"[common][filesystem][path][append]") {
test( "foo", L"/bar" );
test( L"foo", "/bar" );
test( L"foo", L"/bar" );
}
*/
#if defined(__clang__)
#pragma clang diagnostic pop
#endif // __clang__
| 29.748503 | 92 | 0.589171 |
39433c5976e200b3378b2be19c3359b991cabfee | 436 | cpp | C++ | Colour.cpp | sbarrettCC/allegro_wrapper_functions | 4dab88455e83d65de6dd0749998fdf6db8b5d6d6 | [
"MIT"
] | null | null | null | Colour.cpp | sbarrettCC/allegro_wrapper_functions | 4dab88455e83d65de6dd0749998fdf6db8b5d6d6 | [
"MIT"
] | null | null | null | Colour.cpp | sbarrettCC/allegro_wrapper_functions | 4dab88455e83d65de6dd0749998fdf6db8b5d6d6 | [
"MIT"
] | 1 | 2022-03-02T20:28:38.000Z | 2022-03-02T20:28:38.000Z | /*
Allegro Wrapper Functions
Written by Adel Talhouk in FA21
Colour.cpp
*/
#include "Colour.h"
//Constructor - without alpha
Colour::Colour(unsigned __int8 r, unsigned __int8 g, unsigned __int8 b)
{
mR = r;
mG = g;
mB = b;
mA = 255;
}
//Constructor - with alpha
Colour::Colour(unsigned __int8 r, unsigned __int8 g, unsigned __int8 b, unsigned __int8 a)
{
mR = r;
mG = g;
mB = b;
mA = a;
}
//Destructor
Colour::~Colour()
{
} | 14.064516 | 90 | 0.669725 |
3944cbb3e9853cc8dcee395ce7b63ca6fcc45742 | 5,847 | cc | C++ | gem5-gpu/src/graphics/graphic_calls.cc | ayoubg/gem5-graphics_v1 | d74a968d5854dc02797139558430ccda1f71108e | [
"BSD-3-Clause"
] | 1 | 2019-01-26T10:34:02.000Z | 2019-01-26T10:34:02.000Z | gem5-gpu/src/graphics/graphic_calls.cc | ayoubg/gem5-graphics_v1 | d74a968d5854dc02797139558430ccda1f71108e | [
"BSD-3-Clause"
] | null | null | null | gem5-gpu/src/graphics/graphic_calls.cc | ayoubg/gem5-graphics_v1 | d74a968d5854dc02797139558430ccda1f71108e | [
"BSD-3-Clause"
] | 1 | 2021-07-06T10:40:34.000Z | 2021-07-06T10:40:34.000Z | #include "graphics/libOpenglRender/dll.h"
#include "graphics/graphic_calls.hh"
#include "base/misc.hh"
#include <pthread.h>
#include<ctime>
#include<X11/Xlib.h>
#include <SDL/SDL.h>
#include <SDL/SDL_syswm.h>
#include "graphics/serialize_graphics.hh"
#define RENDER_API_NO_PROTOTYPES 1
#include "graphics/libOpenglRender/render_api.h"
/* These definitions *must* match those under:
* development/tools/emulator/opengl/host/include/libOpenglRender/render_api.h
*/
#define DYNLINK_FUNCTIONS \
DYNLINK_FUNC(initLibrary) \
DYNLINK_FUNC(setStreamMode) \
DYNLINK_FUNC(initOpenGLRenderer) \
DYNLINK_FUNC(setPostCallback) \
DYNLINK_FUNC(getHardwareStrings) \
DYNLINK_FUNC(createOpenGLSubwindow) \
DYNLINK_FUNC(destroyOpenGLSubwindow) \
DYNLINK_FUNC(repaintOpenGLDisplay) \
DYNLINK_FUNC(stopOpenGLRenderer) \
DYNLINK_FUNC(gem5GetOpenGLContexts) \
DYNLINK_FUNC(gem5CreateOpenGLContext)
#define RENDERER_LIB_NAME "lib64OpenglRender"
static ADynamicLibrary* rendererLib;
static int rendererStarted =0;
static char rendererAddress[256];
/* Define the function pointers */
#define DYNLINK_FUNC(name) \
static name##Fn name = NULL;
DYNLINK_FUNCTIONS
#undef DYNLINK_FUNC
int initOpenglesEmulationFuncs(ADynamicLibrary* rendererLib)
{
void* symbol;
char* error;
#define DYNLINK_FUNC(name) \
symbol = adynamicLibrary_findSymbol(rendererLib, #name, &error); \
if (symbol != NULL) { \
name = reinterpret_cast<name##Fn>(reinterpret_cast<long long>(symbol)); \
} else { \
inform("GLES emulation: Could not find required symbol (%s): %s", #name, error); \
free(error); \
return -1; \
}
DYNLINK_FUNCTIONS
#undef DYNLINK_FUNC
return 0;
}
int android_initOpenglesEmulation(void)
{
char* error = NULL;
if (rendererLib != NULL)
return 0;
DPRINTF(GraphicsCalls,"Initializing hardware OpenGLES emulation support\n");
rendererLib = adynamicLibrary_open(RENDERER_LIB_NAME, &error);
if (rendererLib == NULL) {
fatal("Error: Could not load OpenGLES emulation library: %s", error);
}
/* Resolve the functions */
if (initOpenglesEmulationFuncs(rendererLib) < 0) {
inform("Error: OpenGLES emulation library mismatch. Be sure to use the correct version!");
goto BAD_EXIT;
}
if (!initLibrary()) {
inform("Error: OpenGLES initialization failed!");
goto BAD_EXIT;
}
setStreamMode(STREAM_MODE_UNIX); //should not have a real effect as TCP mode will be used anyway
return 0;
BAD_EXIT:
inform("Error: OpenGLES emulation library could not be initialized!");
adynamicLibrary_close(rendererLib);
rendererLib = NULL;
return -1;
}
int android_startOpenglesRenderer(int width, int height)
{
if (!rendererLib) {
inform("Can't start OpenGLES renderer without support libraries");
return -1;
}
if (rendererStarted) {
return 0;
}
if (!initOpenGLRenderer(width, height, rendererAddress, sizeof(rendererAddress))) {
fatal("Can't start OpenGLES renderer?");
} else {inform("rendererAddress=%s\n",rendererAddress);}
setPostCallback(NULL,NULL); //disabling it
rendererStarted = 1;
return 0;
}
int android_showOpenglesWindow(FBNativeWindowType window, int x, int y, int width, int height, float rotation)
{
if (rendererStarted) {
int success = createOpenGLSubwindow(window, x, y, width, height, rotation);
return success ? 0 : -1;
} else {
return -1;
}
}
int android_hideOpenglesWindow(void)
{
if (rendererStarted) {
int success = destroyOpenGLSubwindow();
return success ? 0 : -1;
} else {
return -1;
}
}
void android_gles_server_path(char* buff, size_t buffsize)
{
strncpy(buff, rendererAddress, buffsize);
}
SDL_Surface * surface;
void android_showWindow() {
#ifdef __linux__
// some OpenGL implementations may call X functions
// it is safer to synchronize all X calls made by all the
// rendering threads. (although the calls we do are locked
// in the FrameBuffer singleton object).
XInitThreads();
#endif
// initialize SDL window
if (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_VIDEO)) {
fatal("SDL init failed: %s\n", SDL_GetError());
}
const SDL_VideoInfo* info = SDL_GetVideoInfo( );
info = info; //to not complain about unused variable
DPRINTF(GraphicsCalls,"android_showWindow: bpp is %d \n",info->vfmt->BitsPerPixel);
surface = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_SWSURFACE);
if (surface == NULL) {
fatal("Failed to set video mode: %s\n", SDL_GetError());
}
FBNativeWindowType windowId = (FBNativeWindowType)NULL;
SDL_SysWMinfo wminfo;
memset(&wminfo, 0, sizeof(wminfo));
SDL_GetWMInfo(&wminfo);
windowId = wminfo.info.x11.window;
DPRINTF(GraphicsCalls,"initializing renderer process\n");
if(!(0==android_initOpenglesEmulation() and 0==android_startOpenglesRenderer(SCREEN_WIDTH, SCREEN_HEIGHT)))
{
fatal("couldn't initialize openglesEmulation and/or starting openglesRenderer");
}
android_showOpenglesWindow(windowId,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,0.0);
}
void* android_repaint_t(void * arg) {
//repaintOpenGLDisplay();
//SDL_Flip(surface);
return NULL;
}
void android_repaint() {
android_repaint_t(NULL);
}
void init_gem5_graphics(){
static bool init= false;
if(!init){
android_showWindow();
init=true;
}
}
void get_android_OpenGL_contexts(void** list, int* n){
gem5GetOpenGLContexts((gem5Ctx**)list, n);
}
void* create_android_OpenGL_context(int config, int isGl2){
return gem5CreateOpenGLContext(config, isGl2);
}
| 26.337838 | 111 | 0.687532 |
394ed15fdfce934a47f9793194eb0550087ba44b | 10,260 | cc | C++ | modules/loader-grub/arch/x86_64/mmu-loader.cc | eryjus/centuryos2 | 526a39c0f434b29a43d85e6b5b1ffa1ced885b25 | [
"BSD-3-Clause"
] | null | null | null | modules/loader-grub/arch/x86_64/mmu-loader.cc | eryjus/centuryos2 | 526a39c0f434b29a43d85e6b5b1ffa1ced885b25 | [
"BSD-3-Clause"
] | null | null | null | modules/loader-grub/arch/x86_64/mmu-loader.cc | eryjus/centuryos2 | 526a39c0f434b29a43d85e6b5b1ffa1ced885b25 | [
"BSD-3-Clause"
] | null | null | null | //===================================================================================================================
//
// mmu-loader.cc -- Functions related to managing the Paging Tables
//
// Copyright (c) 2017-2021 -- Adam Clark
// Licensed under "THE BEER-WARE LICENSE"
// See License.md for details.
//
// -----------------------------------------------------------------------------------------------------------------
//
// Date Tracker Version Pgmr Description
// ----------- ------- ------- ---- ---------------------------------------------------------------------------
// 2021-Jan-03 Initial v0.0.1 ADCL Initial version
//
//===================================================================================================================
#define USE_SERIAL
#include "types.h"
#include "serial.h"
#include "mmu.h"
#define PG_NONE (0)
#define PG_WRT (1<<0)
#define PG_KRN (1<<1)
#define PG_DEV (1<<15)
//
// -- This is a 64-bit page entry for all levels of the page tables
// -------------------------------------------------------------
typedef struct PageEntry_t {
unsigned int p : 1; // Is the page present?
unsigned int rw : 1; // set to 1 to allow writes
unsigned int us : 1; // 0=Supervisor; 1=user
unsigned int pwt : 1; // Page Write Through
unsigned int pcd : 1; // Page-level cache disable
unsigned int a : 1; // accessed
unsigned int d : 1; // dirty (needs to be written for a swap)
unsigned int pat : 1; // set to 0 for tables, page Page Attribute Table (set to 0)
unsigned int g : 1; // Global (set to 0)
unsigned int k : 1; // Is this a kernel page?
unsigned int avl : 2; // Available for software use
Frame_t frame : 36; // This is the 4K aligned page frame address (or table address)
unsigned int reserved : 4; // reserved bits
unsigned int software : 11; // software use bits
unsigned int xd : 1; // execute disable
} __attribute__((packed)) PageEntry_t;
//
// -- some inline functions to handle access to Page Table Entries
// ------------------------------------------------------------
PageEntry_t *GetPML4Entry(Addr_t a)
{
PageEntry_t *t = (PageEntry_t *)0xfffffffffffff000;
uint64_t idx = (a >> (12 + (9 * 3))) & 0x1ff;
#if DEBUG_ENABLED(GetPML4Entry)
SerialPutString("PML4 idx = ");
SerialPutHex64(idx);
SerialPutChar('\n');
#endif
return &t[idx];
}
PageEntry_t *GetPDPTEntry(Addr_t a)
{
PageEntry_t *t = (PageEntry_t *)0xffffffffffe00000;
uint64_t idx = (a >> (12 + (9 * 2))) & 0x3ffff;
#if DEBUG_ENABLED(GetPDPTEntry)
SerialPutString("PDPT idx = ");
SerialPutHex64(idx);
SerialPutChar('\n');
#endif
return &t[idx];
}
PageEntry_t *GetPDEntry(Addr_t a)
{
PageEntry_t *t = (PageEntry_t *)0xffffffffc0000000;
uint64_t idx = (a >> (12 + (9 * 1))) & 0x7ffffff;
#if DEBUG_ENABLED(GetPDEntry)
SerialPutString("PD idx = ");
SerialPutHex64(idx);
SerialPutChar('\n');
#endif
return &t[idx];
}
PageEntry_t *GetPTEntry(Addr_t a)
{
PageEntry_t *t = (PageEntry_t *)0xffffff8000000000;
uint64_t idx = (a >> (12 + (9 * 0))) & 0xfffffffff;
#if DEBUG_ENABLED(GetPTEntry)
SerialPutString("PT idx = ");
SerialPutHex64(idx);
SerialPutChar('\n');
#endif
return &t[idx];
}
//
// -- Some assembly CPU instructions
// ------------------------------
static inline void INVLPG(Addr_t a) { __asm volatile("invlpg (%0)" :: "r"(a) : "memory"); }
//
// -- allocate a new frame
// --------------------
Frame_t MmuGetTable(void)
{
extern Frame_t earlyFrame;
return earlyFrame ++;
}
//
// -- Some wrapper functions
// ----------------------
//void MmuMapPage(Addr_t a, Frame_t f, int flags) { ldr_MmuMapPage(a, f, flags); }
//void MmuUnmapPage(Addr_t a) { ldr_MmuUnmapPage(a); }
//
// -- Check if an address is mapped
// -----------------------------
bool MmuIsMapped(Addr_t a)
{
#if DEBUG_ENABLED(MmuIsMapped)
SerialPutString("Checking if address ");
SerialPutHex64(a);
SerialPutString(" is mapped\n");
#endif
INVLPG((Addr_t)GetPML4Entry(a));
INVLPG((Addr_t)GetPDPTEntry(a));
INVLPG((Addr_t)GetPDEntry(a));
INVLPG((Addr_t)GetPTEntry(a));
#if DEBUG_ENABLED(MmuIsMapped)
SerialPutString("Mapped? PML4 at ");
SerialPutHex64((Addr_t)GetPML4Entry(a));
SerialPutChar('\n');
#endif
if (!GetPML4Entry(a)->p) return false;
#if DEBUG_ENABLED(MmuIsMapped)
SerialPutString("mapped? PDPT at ");
SerialPutHex64((Addr_t)GetPDPTEntry(a));
SerialPutChar('\n');
#endif
if (!GetPDPTEntry(a)->p) return false;
#if DEBUG_ENABLED(MmuIsMapped)
SerialPutString("mapped? PD at ");
SerialPutHex64((Addr_t)GetPDEntry(a));
SerialPutChar('\n');
#endif
if (!GetPDEntry(a)->p) return false;
#if DEBUG_ENABLED(MmuIsMapped)
SerialPutString("mapped? PT at ");
SerialPutHex64((Addr_t)GetPTEntry(a));
SerialPutChar('\n');
#endif
if (!GetPTEntry(a)->p) return false;
#if DEBUG_ENABLED(MmuIsMapped)
SerialPutString("mapped.\n");
#endif
return true;
}
//
// -- Safely Unmap a page
// -------------------
void ldr_MmuUnmapPage(Addr_t a)
{
#if DEBUG_ENABLED(ldr_MmuUnmapPage)
SerialPutString("In address space ");
SerialPutHex64(GetCr3());
SerialPutString(", Unmapping page at address ");
SerialPutHex64(a);
SerialPutChar('\n');
#endif
if (MmuIsMapped(a)) {
*(uint64_t *)GetPTEntry(a) = 0;
INVLPG(a);
}
}
//
// -- Map a page to a frame
// ---------------------
void ldr_MmuMapPage(Addr_t a, Frame_t f, int flags)
{
#if DEBUG_ENABLED(ldr_MmuMapPage)
SerialPutString("In address space ");
SerialPutHex64(GetCr3());
SerialPutString(", request was made to map address ");
SerialPutHex64(a);
SerialPutString(" to frame ");
SerialPutHex64(f);
SerialPutChar('\n');
SerialPutString("Checking if the page is mapped\n");
#endif
if (MmuIsMapped(a)) ldr_MmuUnmapPage(a);
#if DEBUG_ENABLED(ldr_MmuMapPage)
SerialPutString(".. Done -- guaranteed unmapped\n");
#endif
Frame_t t;
PageEntry_t *ent = GetPML4Entry(a);
#if DEBUG_ENABLED(ldr_MmuMapPage)
SerialPutString(".. Mapping PML4 @ ");
SerialPutHex64((Addr_t)ent);
SerialPutChar('\n');
#endif
if (!ent->p) {
t = MmuGetTable();
ent->frame = t;
ent->rw = 1;
ent->p = 1;
__asm volatile ("wbnoinvd" ::: "memory");
INVLPG((Addr_t)GetPDPTEntry(a));
uint64_t *tbl = (uint64_t *)((Addr_t)GetPDPTEntry(a) & 0xfffffffffffff000);
for (int i = 0; i < 512; i ++) {
tbl[i] = 0;
}
}
#if DEBUG_ENABLED(ldr_MmuMapPage)
SerialPutString(".... [hex ");
SerialPutHex64(*(uint64_t *)ent);
SerialPutString("]\n");
#endif
ent = GetPDPTEntry(a);
#if DEBUG_ENABLED(ldr_MmuMapPage)
SerialPutString(".. Mapping PDPT @ ");
SerialPutHex64((Addr_t)ent);
SerialPutChar('\n');
#endif
if (!ent->p) {
t = MmuGetTable();
ent->frame = t;
ent->rw = 1;
ent->p = 1;
__asm volatile ("wbnoinvd" ::: "memory");
INVLPG((Addr_t)GetPDEntry(a));
uint64_t *tbl = (uint64_t *)((Addr_t)GetPDEntry(a) & 0xfffffffffffff000);
for (int i = 0; i < 512; i ++) tbl[i] = 0;
}
#if DEBUG_ENABLED(ldr_MmuMapPage)
SerialPutString(".... [hex ");
SerialPutHex64(*(uint64_t *)ent);
SerialPutString("]\n");
#endif
ent = GetPDEntry(a);
#if DEBUG_ENABLED(ldr_MmuMapPage)
SerialPutString(".. Mapping PD @ ");
SerialPutHex64((Addr_t)ent);
SerialPutChar('\n');
#endif
if (!ent->p) {
t = MmuGetTable();
ent->frame = t;
ent->rw = 1;
ent->p = 1;
__asm volatile ("wbnoinvd" ::: "memory");
INVLPG((Addr_t)GetPTEntry(a));
uint64_t *tbl = (uint64_t *)((Addr_t)GetPTEntry(a) & 0xfffffffffffff000);
for (int i = 0; i < 512; i ++) tbl[i] = 0;
#if DEBUG_ENABLED(ldr_MmuMapPage)
SerialPutString("Address: ");
SerialPutHex64((uint64_t)ent);
SerialPutString(" .... [hex ");
SerialPutHex64(*((uint64_t *)ent));
SerialPutString("]\n");
#endif
}
#if DEBUG_ENABLED(ldr_MmuMapPage)
SerialPutString(".... [hex ");
SerialPutHex64(*(uint64_t *)ent);
SerialPutString("]\n");
#endif
ent = GetPTEntry(a);
#if DEBUG_ENABLED(ldr_MmuMapPage)
SerialPutString(".. Mapping PT @ ");
SerialPutHex64((Addr_t)ent);
SerialPutChar('\n');
#endif
ent->frame = f;
ent->rw = (flags&PG_WRT?1:0);
ent->pcd = (flags&PG_DEV?1:0);
ent->pwt = (flags&PG_DEV?1:0);
ent->us = (flags&PG_DEV?1:0);
ent->p = 1;
__asm volatile ("wbnoinvd" ::: "memory");
INVLPG((Addr_t)a);
#if DEBUG_ENABLED(ldr_MmuMapPage)
SerialPutString("Mapping complete!!\n");
#endif
}
//
// -- Create an empty PDPT Table
// --------------------------
void MmuEmptyPdpt(int index)
{
extern Frame_t earlyFrame;
#if DEBUG_ENABLED(MmuEmptyPdpt)
SerialPutString("Creating a PDPT table for PML4 index: ");
SerialPutHex64(index);
SerialPutChar('\n');
#endif
PageEntry_t *ent = &((PageEntry_t *)0xfffffffffffff000)[index];
if (!ent->p) {
ent->frame = earlyFrame ++;
#if DEBUG_ENABLED(MmuEmptyPdpt)
SerialPutString("Next frame is: ");
SerialPutHex64(ent->frame);
SerialPutChar('\n');
#endif
ent->rw = 1;
ent->p = 1;
uint64_t *tbl = (uint64_t *)(0xffffffffffe00000 | (index << 12));
INVLPG((Addr_t)tbl);
#if DEBUG_ENABLED(MmuEmptyPdpt)
SerialPutString("Clearing the table starting at: ");
SerialPutHex64((Addr_t)tbl);
SerialPutChar('\n');
#endif
for (int i = 0; i < 512; i ++) {
#if DEBUG_ENABLED(MmuEmptyPdpt)
SerialPutString("At address: ");
SerialPutHex64((Addr_t)&tbl[i]);
SerialPutChar('\n');
#endif
tbl[i] = 0;
}
}
} | 22.649007 | 117 | 0.552729 |
39503020253aa1fc8bd888aea2ab04ff9816e6bc | 49 | hpp | C++ | src/agl/opengl/function/vertex_attribute/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/opengl/function/vertex_attribute/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/opengl/function/vertex_attribute/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | #pragma once
#include "get_vertex_location.hpp"
| 12.25 | 34 | 0.795918 |
39514b46fc36f061eaefc57aff06033acea5d384 | 1,023 | cpp | C++ | src/homework/tic_tac_toe/tic_tac_toe_manager.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez | 52f01b57eea81445f5ef13325969a8a1bd868c50 | [
"MIT"
] | null | null | null | src/homework/tic_tac_toe/tic_tac_toe_manager.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez | 52f01b57eea81445f5ef13325969a8a1bd868c50 | [
"MIT"
] | null | null | null | src/homework/tic_tac_toe/tic_tac_toe_manager.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez | 52f01b57eea81445f5ef13325969a8a1bd868c50 | [
"MIT"
] | null | null | null | #include "tic_tac_toe_manager.h"
void TicTacToeManager::save_game(std::unique_ptr<TicTacToe> & b)
{
update_winner_count(b->get_winner());
games.push_back(std::move(b));
}
ostream& operator << (ostream& out, const TicTacToeManager& manager)
{
for(auto& x : manager.games)
{
out << *x;
}
out << "X won: " << manager.x_win << "\n";
out << "O won: " << manager.o_win << "\n";
out << "Ties: " << manager.tie << "\n";
return out;
}
void TicTacToeManager :: get_winner_total(int& o, int& x, int& t)
{
cout << endl
<< "X Wins =" << x << endl
<< "O Wins =" << o << endl
<< "Ties =" << t << endl
<< endl;
}
void TicTacToeManager :: update_winner_count(string winner)
{
if(winner== "X")
x_win++;
else if(winner =="O")
o_win++;
else
tie++;
}
TicTacToeManager::TicTacToeManager(TicTacToeData& d)
{
games = d.get_games();
for(auto& g : games)
{
update_winner_count(g->get_winner());
}
}
| 21.3125 | 68 | 0.545455 |
395242967db1c79c99f873570497994265193717 | 671 | hpp | C++ | src/input.hpp | MaemiKozue/hexceed | 11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a | [
"MIT"
] | null | null | null | src/input.hpp | MaemiKozue/hexceed | 11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a | [
"MIT"
] | null | null | null | src/input.hpp | MaemiKozue/hexceed | 11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a | [
"MIT"
] | null | null | null | #ifndef INPUT_H
#define INPUT_H
#include <iostream>
typedef enum InputType {
MOUSE, KEYBOARD
} InputType;
typedef enum KEY {
KEY_ENTER
} KEY;
typedef enum MOUSE_BUTTON {
MB_MIDDLE, MB_LEFT, MB_RIGHT
} MOUSE_BUTTON;
class Input
{
private:
InputType type;
int x, y; // mouse position
MOUSE_BUTTON mb; // mouse button
KEY key; // key press
public:
Input(MOUSE_BUTTON mb, int x, int y);
Input(KEY key);
~Input();
InputType getType() const;
int getX() const;
int getY() const;
MOUSE_BUTTON getButton() const;
KEY getKey() const;
};
std::ostream& operator<<(std::ostream& out, Input in);
#endif // INPUT_H
| 15.97619 | 54 | 0.654247 |
39552ab957f0e29367375be85c5dd153557f0466 | 604 | hpp | C++ | Autoclicker GUI/Autoclicker GUI/GUI/Elements/Element/Element.hpp | CovERUshKA/Autoclicker | 2f7f7cc3924495440c8afa797abadb92dba07faa | [
"MIT"
] | 6 | 2020-07-05T05:52:30.000Z | 2021-12-19T11:03:00.000Z | Autoclicker GUI/Autoclicker GUI/GUI/Elements/Element/Element.hpp | CovERUshKA/Autoclicker | 2f7f7cc3924495440c8afa797abadb92dba07faa | [
"MIT"
] | null | null | null | Autoclicker GUI/Autoclicker GUI/GUI/Elements/Element/Element.hpp | CovERUshKA/Autoclicker | 2f7f7cc3924495440c8afa797abadb92dba07faa | [
"MIT"
] | null | null | null | #pragma once
#include <Windows.h>
#include <string>
#include "../../Def.hpp"
class Element
{
public:
// Type of the element( Button, TextEdit and etc. )
INT type;
// Visible element or not
bool visible;
// ID of the element
INT ID;
// Position of the lement
FLOAT x, y;
// Size of the element
FLOAT width, height;
// Additional parameters for the element
UINT params = 0;
// Name of the element
std::wstring wchElementName;
Element();
virtual void Init(COGUI_ElementCreateStruct createStruct);
virtual BOOL Render() = 0;
virtual BOOL ApplyMessage(LPVOID lpCOGUIWndProc) = 0;
}; | 17.257143 | 59 | 0.701987 |
395693c05065645deeca76b1e0fbb8443b352707 | 2,080 | hpp | C++ | ext/src/java/awt/BasicStroke.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/awt/BasicStroke.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/awt/BasicStroke.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#pragma once
#include <fwd-POI.hpp>
#include <java/awt/fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <java/lang/Object.hpp>
#include <java/awt/Stroke.hpp>
struct default_init_tag;
class java::awt::BasicStroke
: public virtual ::java::lang::Object
, public virtual Stroke
{
public:
typedef ::java::lang::Object super;
static constexpr int32_t CAP_BUTT { int32_t(0) };
static constexpr int32_t CAP_ROUND { int32_t(1) };
static constexpr int32_t CAP_SQUARE { int32_t(2) };
static constexpr int32_t JOIN_BEVEL { int32_t(2) };
static constexpr int32_t JOIN_MITER { int32_t(0) };
static constexpr int32_t JOIN_ROUND { int32_t(1) };
public: /* package */
int32_t cap { };
::floatArray* dash { };
float dash_phase { };
int32_t join { };
float miterlimit { };
float width { };
protected:
void ctor();
void ctor(float width);
void ctor(float width, int32_t cap, int32_t join);
void ctor(float width, int32_t cap, int32_t join, float miterlimit);
void ctor(float width, int32_t cap, int32_t join, float miterlimit, ::floatArray* dash, float dash_phase);
public:
Shape* createStrokedShape(Shape* s) override;
bool equals(::java::lang::Object* obj) override;
virtual ::floatArray* getDashArray_();
virtual float getDashPhase();
virtual int32_t getEndCap();
virtual int32_t getLineJoin();
virtual float getLineWidth();
virtual float getMiterLimit();
int32_t hashCode() override;
// Generated
BasicStroke();
BasicStroke(float width);
BasicStroke(float width, int32_t cap, int32_t join);
BasicStroke(float width, int32_t cap, int32_t join, float miterlimit);
BasicStroke(float width, int32_t cap, int32_t join, float miterlimit, ::floatArray* dash, float dash_phase);
protected:
BasicStroke(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
};
| 30.144928 | 112 | 0.694231 |
39599126185e37194126c4ae8f0c418c2f957a66 | 487 | hpp | C++ | EntitySystemGenerator/Include/ComponentMapsSourceGenerator.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | EntitySystemGenerator/Include/ComponentMapsSourceGenerator.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | EntitySystemGenerator/Include/ComponentMapsSourceGenerator.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | #pragma once
#ifndef _ENTITYSYSTEMGENERATOR_COMPONENTMAPSSOURCEGENERATOR_HPP_
#define _ENTITYSYSTEMGENERATOR_COMPONENTMAPSSOURCEGENERATOR_HPP_
#include "CodeGenerator.hpp"
#include "ComponentDefinitions.hpp"
namespace Fnd
{
namespace EntitySystemCodeGeneration
{
class ComponentMapsSourceGenerator:
public CodeGenerator
{
public:
bool Generate( const ComponentDefinitions& component_definitions,
const std::string& output_file );
};
}
}
#endif | 18.037037 | 68 | 0.780287 |
395b252c334d240cbe37b6be91d0904cb2f834af | 349 | cpp | C++ | cpp/cpp_primer/chapter10/ex_10_42.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | 2 | 2019-12-21T00:53:47.000Z | 2020-01-01T10:36:30.000Z | cpp/cpp_primer/chapter10/ex_10_42.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | null | null | null | cpp/cpp_primer/chapter10/ex_10_42.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | null | null | null | //
// Created by kaiser on 18-12-17.
//
#include <algorithm>
#include <iostream>
#include <list>
#include <string>
void elim_dups(std::list<std::string>& words) {
words.sort();
words.unique();
}
int main() {
std::list<std::string> vs{"a", "a", "c", "c", "b"};
elim_dups(vs);
for (const auto& s : vs) {
std::cout << s << '\n';
}
}
| 15.863636 | 53 | 0.56447 |
395f6301e153f9d9d7d2dd3428f88d665133c104 | 850 | cpp | C++ | PTA-B/right/1013-right.cpp | chiangyung/PTA | c8e6bcbc9e552dad5ab71679d861a235b8ad0730 | [
"MIT"
] | 2 | 2018-08-23T06:58:56.000Z | 2018-09-04T02:07:44.000Z | PTA-B/right/1013-right.cpp | chiangyung/PTA | c8e6bcbc9e552dad5ab71679d861a235b8ad0730 | [
"MIT"
] | null | null | null | PTA-B/right/1013-right.cpp | chiangyung/PTA | c8e6bcbc9e552dad5ab71679d861a235b8ad0730 | [
"MIT"
] | null | null | null | #include <iostream>
#include <math.h>
using namespace std;
const int INTMAX = pow(2, 30);
bool is_prime(const int n)
{
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main(int argc, char *argv[])
{
int m, n;
int count1 = 0, count2 = 0;
cin >> m >> n;
for (int i = 2; i < INTMAX; i++) {
if (is_prime(i)) {
count1++;
if (count1 >= m && count1 <= n) {
cout << i;
count2++;
if (count1 == n) {
cout << endl;
break;
}
if (count2 % 10 == 0) {
cout << endl;
} else {
cout << " ";
}
}
}
}
return 0;
}
| 18.888889 | 45 | 0.342353 |
395f7c953cc08a36d29401fb4b839e28b84b46d3 | 531 | cpp | C++ | test/Model/Header.cpp | jxx-project/JXXRS | 0d788e3aba5231ec1782699c9d397b9d81fdb1fd | [
"BSL-1.0"
] | null | null | null | test/Model/Header.cpp | jxx-project/JXXRS | 0d788e3aba5231ec1782699c9d397b9d81fdb1fd | [
"BSL-1.0"
] | null | null | null | test/Model/Header.cpp | jxx-project/JXXRS | 0d788e3aba5231ec1782699c9d397b9d81fdb1fd | [
"BSL-1.0"
] | null | null | null | //
// Copyright (C) 2018 Dr. Michael Steffens
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Model/Header.h"
namespace Model {
Header::Header()
{
}
Header::Header(const std::string& name, const std::string& value) : name(name), value(value)
{
}
Header::Header(const JXXON::Json& json) : name(json.get<decltype(name)>("name")), value(json.get<decltype(value)>("value"))
{
}
JXXON::Json Header::toJson() const
{
JXXON::Json json;
json.set("name", name);
json.set("value", value);
return json;
}
} // namespace Model
| 16.090909 | 123 | 0.661017 |
396289f2ff22620325ab55248496538c6b002707 | 3,553 | cpp | C++ | src/caffe/test/test_training_utils.cpp | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 933 | 2016-08-29T14:29:20.000Z | 2022-03-20T09:03:49.000Z | src/caffe/test/test_training_utils.cpp | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 286 | 2016-08-30T01:33:01.000Z | 2021-08-22T08:34:19.000Z | src/caffe/test/test_training_utils.cpp | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 611 | 2016-08-30T07:22:04.000Z | 2021-12-18T11:53:08.000Z | /*
All modification made by Intel Corporation: © 2016 Intel Corporation
All contributions by the University of California:
Copyright (c) 2014, 2015, The Regents of the University of California (Regents)
All rights reserved.
All other contributions:
Copyright (c) 2014, 2015, the respective contributors
All rights reserved.
For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <string>
#include <utility>
#include "boost/algorithm/string.hpp"
#include "boost/lexical_cast.hpp"
#include "google/protobuf/text_format.h"
#include "gtest/gtest.h"
#include "caffe/solver.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/upgrade_proto.hpp"
#include "caffe/training_utils.hpp"
namespace caffe {
class TrainingUtilsTest : public ::testing::Test {
protected:
TrainingUtilsTest()
: topology_file_name_(
CMAKE_SOURCE_DIR "caffe/test/test_data/test_topology.prototxt") {
}
string topology_file_name_;
};
TEST_F(TrainingUtilsTest, GetStagesFromFlags) {
string stages_flag = "stage1,stage2, stage3";
EXPECT_EQ(get_stages_from_flags(stages_flag).size(), 3);
}
TEST_F(TrainingUtilsTest, SetSolverParamsFromFlags) {
caffe::SolverParameter solver_param;
string solver;
string engine = "new engine";
string stages = "stage1,stage2";
int level = 1;
use_flags(&solver_param, solver, engine, level, stages);
EXPECT_EQ(solver_param.engine(), engine);
EXPECT_EQ(solver_param.train_state().stage_size(), 2);
EXPECT_EQ(solver_param.train_state().level(), 1);
}
TEST_F(TrainingUtilsTest, MultiphaseTrainNegativeCpuMode) {
caffe::MultiPhaseSolverParameter multi_solver_param;
caffe::SolverBatchSizePair* solver_param_pair =
multi_solver_param.add_params_pair();
solver_param_pair->mutable_solver_params()->set_solver_mode(
caffe::SolverParameter_SolverMode_GPU);
solver_param_pair->mutable_solver_params()->set_net(
this->topology_file_name_);
EXPECT_EQ(multiphase_train(&multi_solver_param, "", "", 0, ""), -1);
}
} // namespace caffe
| 35.178218 | 92 | 0.777934 |
39644976619fc7b047dc5bfb77f4732ad44a2038 | 621 | cxx | C++ | test_code/test_fdstream_simple.cxx | m-renaud/posix-lib | 0296999e252e2b40a80bcc01ea6a1742e8ef1c49 | [
"BSD-2-Clause"
] | 1 | 2020-11-11T12:50:30.000Z | 2020-11-11T12:50:30.000Z | test_code/test_fdstream_simple.cxx | m-renaud/posix-lib | 0296999e252e2b40a80bcc01ea6a1742e8ef1c49 | [
"BSD-2-Clause"
] | null | null | null | test_code/test_fdstream_simple.cxx | m-renaud/posix-lib | 0296999e252e2b40a80bcc01ea6a1742e8ef1c49 | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include "../fdstream.hxx"
#include "../pipe.hxx"
int main()
{
try
{
mrr::posix::pipe successful_auth;
mrr::posix::fd_ostream write_end(successful_auth.write_end());
mrr::posix::fd_istream read_end(successful_auth.read_end());
int received[2];
write_end << 5 << std::endl;
write_end << 8 << std::endl;
read_end >> received[0];
read_end >> received[1];
std::cout << received[0] << std::endl
<< received[1] << std::endl;
successful_auth.close();
}
catch(std::system_error const& except)
{
mrr::posix::output_system_error_msg();
exit(1);
}
return 0;
}
| 17.25 | 64 | 0.639291 |
396aeaba14dfb506f287778ba27e13dd0c0d77f0 | 1,473 | hpp | C++ | include/sprout/predef/compiler/sgi_mipspro.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | 4 | 2021-12-29T22:17:40.000Z | 2022-03-23T11:53:44.000Z | dsp/lib/sprout/sprout/predef/compiler/sgi_mipspro.hpp | TheSlowGrowth/TapeLooper | ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264 | [
"MIT"
] | 16 | 2021-10-31T21:41:09.000Z | 2022-01-22T10:51:34.000Z | include/sprout/predef/compiler/sgi_mipspro.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | null | null | null | /*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the sprout Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.sprout.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_PREDEF_COMPILER_SGI_MIPSPRO_HPP
#define SPROUT_PREDEF_COMPILER_SGI_MIPSPRO_HPP
#include <sprout/config.hpp>
#include <sprout/predef/make.hpp>
#define SPROUT_COMP_SGI 0
#if defined(__sgi) || defined(sgi)
# if !defined(SPROUT_COMP_SGI_DETECTION) && defined(_SGI_COMPILER_VERSION)
# define SPROUT_COMP_SGI_DETECTION SPROUT_PREDEF_MAKE_10_VRP(_SGI_COMPILER_VERSION)
# endif
# if !defined(SPROUT_COMP_SGI_DETECTION) && defined(_COMPILER_VERSION)
# define SPROUT_COMP_SGI_DETECTION SPROUT_PREDEF_MAKE_10_VRP(_COMPILER_VERSION)
# endif
# if !defined(SPROUT_COMP_SGI_DETECTION)
# define SPROUT_COMP_SGI_DETECTION 1
# endif
#endif
#ifdef SPROUT_COMP_SGI_DETECTION
# if defined(SPROUT_PREDEF_DETAIL_COMP_DETECTED)
# define SPROUT_COMP_SGI_EMULATED SPROUT_COMP_SGI_DETECTION
# else
# undef SPROUT_COMP_SGI
# define SPROUT_COMP_SGI SPROUT_COMP_SGI_DETECTION
# endif
# define SPROUT_COMP_SGI_AVAILABLE
# include <sprout/predef/detail/comp_detected.hpp>
#endif
#define SPROUT_COMP_SGI_NAME "SGI MIPSpro"
#endif //#ifndef SPROUT_PREDEF_COMPILER_SGI_MIPSPRO_HPP
| 35.071429 | 84 | 0.739308 |
396b1304f779670ccebfe8e01a457de7da6c4d38 | 1,764 | hpp | C++ | tasks/FrameFilter.hpp | PhischDotOrg/stm32f4-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | 1 | 2022-01-31T01:59:52.000Z | 2022-01-31T01:59:52.000Z | tasks/FrameFilter.hpp | PhischDotOrg/stm32-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | 5 | 2020-04-13T21:55:12.000Z | 2020-06-27T17:44:44.000Z | tasks/FrameFilter.hpp | PhischDotOrg/stm32f4-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | null | null | null | /*-
* $Copyright$
-*/
#ifndef _FRAME_FILTER_HPP_3532115b_b86b_48e5_a4c1_810606f79dfe
#define _FRAME_FILTER_HPP_3532115b_b86b_48e5_a4c1_810606f79dfe
#include <tasks/Task.hpp>
#if defined(__cplusplus)
extern "C" {
#endif /* defined(__cplusplus) */
#include "FreeRTOS/FreeRTOS.h"
#include "FreeRTOS/queue.h"
#if defined(__cplusplus)
} /* extern "C" */
#endif /* defined(__cplusplus) */
namespace tasks {
template<typename InputBufferT, typename OutputBufferT, size_t N, typename FilterChainT, typename PinT, typename UartT>
class FrameFilterT : public Task {
private:
UartT & m_uart;
OutputBufferT (&m_frames)[N];
FilterChainT & m_filter;
PinT * m_activeIndicationPin;
unsigned m_current;
QueueHandle_t * m_rxQueue;
QueueHandle_t * m_txQueue;
virtual void run(void);
public:
FrameFilterT(const char * const p_name, const unsigned p_priority,
UartT &p_uart, OutputBufferT (&p_frames)[N], FilterChainT &p_filter);
virtual ~FrameFilterT();
void setTxQueue(QueueHandle_t* p_txQueue) {
m_txQueue = p_txQueue;
}
QueueHandle_t* getTxQueue() const {
return m_txQueue;
}
void setRxQueue(QueueHandle_t* p_rxQueue) {
m_rxQueue = p_rxQueue;
}
QueueHandle_t* getRxQueue() const {
return m_rxQueue;
}
void setActiveIndicationPin(PinT* p_activeIndicationPin) {
m_activeIndicationPin = p_activeIndicationPin;
}
PinT* getActiveIndicationPin() const {
return m_activeIndicationPin;
}
typedef OutputBufferT Buffer_t;
};
}; /* namespace tasks */
#include "FrameFilter.cpp"
#endif /* _FRAME_FILTER_HPP_3532115b_b86b_48e5_a4c1_810606f79dfe */ | 25.2 | 119 | 0.679705 |
396b3b879ceeafa68fd880dd22e30b04d2b335db | 1,180 | cpp | C++ | SPOJ/MFLAR10 - Flowers Flourish From France/mflar10.cpp | Zubieta/CPP | fb4a3cbf2e4edcc590df15663cd28fb9ecab679c | [
"MIT"
] | 8 | 2017-03-02T07:56:45.000Z | 2021-08-07T20:20:19.000Z | SPOJ/MFLAR10 - Flowers Flourish From France/mflar10.cpp | zubie7a/Algorithms | fb4a3cbf2e4edcc590df15663cd28fb9ecab679c | [
"MIT"
] | null | null | null | SPOJ/MFLAR10 - Flowers Flourish From France/mflar10.cpp | zubie7a/Algorithms | fb4a3cbf2e4edcc590df15663cd28fb9ecab679c | [
"MIT"
] | 1 | 2021-08-07T20:20:20.000Z | 2021-08-07T20:20:20.000Z | /*Santiago Zubieta*/
#include <iostream>
#include <numeric>
#include <fstream>
#include <climits>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <deque>
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>
using namespace std;
int main(){
bool worda=true,meg=false;
char mega;
int j;
string word="";
while(word!="*"){
worda=true;
meg=false;
getline(cin,word);
if (word=="*"){
break;
}
for(int i=0; i < word.size(); ++i){
word[i] = tolower(word[i]);
}
for(j=0;(j<word.size())&&(meg==false);++j){
if(word[j]!=' '){
mega=word[j];
meg=true;
}
}
for(int i=j;(i<word.size())&&(worda==true);++i){
if((mega==word[i])&&(word[i-1]==' ')){
worda=true;
}
if((mega!=word[i])&&(word[i-1]==' ')){
worda=false;
}
}
if(worda==true){
cout<<"Y"<<endl;
}
else{
cout<<"N"<<endl;
}
}
}
| 18.730159 | 56 | 0.499153 |
396c73354d9d9ef8cf18366a2a474450ef4f9501 | 1,774 | cc | C++ | map-structure/vi-map/test/test_map_get_vertex_ids_in_mission_test.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 1,936 | 2017-11-27T23:11:37.000Z | 2022-03-30T14:24:14.000Z | map-structure/vi-map/test/test_map_get_vertex_ids_in_mission_test.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 353 | 2017-11-29T18:40:39.000Z | 2022-03-30T15:53:46.000Z | map-structure/vi-map/test/test_map_get_vertex_ids_in_mission_test.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 661 | 2017-11-28T07:20:08.000Z | 2022-03-28T08:06:29.000Z | #include <Eigen/Core>
#include <gtest/gtest.h>
#include <maplab-common/test/testing-entrypoint.h>
#include "vi-map/test/vi-map-generator.h"
namespace vi_map {
class VIMapTest : public ::testing::Test {
protected:
VIMapTest() : map_(), generator_(map_, 42) {}
virtual void SetUp() {
pose::Transformation T_G_V;
pose::Transformation T_G_M;
missions_[0] = generator_.createMission(T_G_M);
missions_[1] = generator_.createMission(T_G_M);
vertices_[0] = generator_.createVertex(missions_[0], T_G_V);
vertices_[1] = generator_.createVertex(missions_[0], T_G_V);
vertices_[2] = generator_.createVertex(missions_[0], T_G_V);
vertices_[3] = generator_.createVertex(missions_[1], T_G_V);
vertices_[4] = generator_.createVertex(missions_[1], T_G_V);
vertices_[5] = generator_.createVertex(missions_[1], T_G_V);
generator_.generateMap();
}
vi_map::MissionId missions_[2];
pose_graph::VertexId vertices_[6];
VIMap map_;
VIMapGenerator generator_;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
TEST_F(VIMapTest, TestGetAllVertexIdsInMission) {
pose_graph::VertexIdList vertex_ids;
map_.getAllVertexIdsInMission(missions_[0], &vertex_ids);
for (const pose_graph::VertexId& vertex_id : vertex_ids) {
EXPECT_EQ(map_.getVertex(vertex_id).getMissionId(), missions_[0]);
}
}
TEST_F(VIMapTest, TestGetAllVertexIdsInMissionAlongGraph) {
pose_graph::VertexIdList vertex_ids;
map_.getAllVertexIdsInMissionAlongGraph(missions_[0], &vertex_ids);
EXPECT_FALSE(vertex_ids.empty());
for (size_t i = 0; i < vertex_ids.size(); ++i) {
EXPECT_EQ(map_.getVertex(vertex_ids[i]).getMissionId(), missions_[0]);
EXPECT_EQ(vertex_ids[i], vertices_[i]);
}
}
} // namespace vi_map
MAPLAB_UNITTEST_ENTRYPOINT
| 27.71875 | 74 | 0.73168 |
397170c480ab89b57d5c1d86eefd61c9657a072d | 10,484 | cc | C++ | src/io/scene_loader.cc | hyungman/SpRay | 96380740dd88e6fbc21c0fdbf232cff357b1235d | [
"Apache-2.0"
] | 7 | 2018-10-22T17:13:36.000Z | 2020-04-17T08:28:55.000Z | src/io/scene_loader.cc | hyungman/SpRay | 96380740dd88e6fbc21c0fdbf232cff357b1235d | [
"Apache-2.0"
] | null | null | null | src/io/scene_loader.cc | hyungman/SpRay | 96380740dd88e6fbc21c0fdbf232cff357b1235d | [
"Apache-2.0"
] | 1 | 2018-11-01T14:53:22.000Z | 2018-11-01T14:53:22.000Z | // ========================================================================== //
// Copyright (c) 2017-2018 The University of Texas at Austin. //
// All rights reserved. //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// A copy of the License is included with this software in the file LICENSE. //
// If your copy does not contain the License, you may obtain a copy of the //
// License at: //
// //
// https://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 "io/scene_loader.h"
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glog/logging.h"
#include "render/aabb.h"
#include "render/light.h"
#include "render/reflection.h"
#include "render/spray.h"
// #define SPRAY_PRINT_LINES
// #define SPRAY_PRINT_TOKENS
namespace spray {
SceneLoader::DomainTokenType SceneLoader::getTokenType(const std::string& tag) {
DomainTokenType type;
if (tag[0] == '#') {
type = DomainTokenType::kComment;
} else if (tag == "domain") {
type = DomainTokenType::kDomain;
} else if (tag == "file") {
type = DomainTokenType::kFile;
} else if (tag == "mtl") {
type = DomainTokenType::kMaterial;
} else if (tag == "bound") {
type = DomainTokenType::kBound;
} else if (tag == "scale") {
type = DomainTokenType::kScale;
} else if (tag == "rotate") {
type = DomainTokenType::kRotate;
} else if (tag == "translate") {
type = DomainTokenType::kTranslate;
} else if (tag == "face") {
type = DomainTokenType::kFace;
} else if (tag == "vertex") {
type = DomainTokenType::kVertex;
} else if (tag == "light") {
type = DomainTokenType::kLight;
} else {
LOG(FATAL) << "unknown tag name " << tag;
}
return type;
}
void SceneLoader::parseDomain(const std::vector<std::string>& tokens) {
nextDomain();
Domain& d = currentDomain();
d.id = domain_id_;
d.transform = glm::mat4(1.f);
}
void SceneLoader::parseFile(const std::string& ply_path,
const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 2);
d.filename = ply_path.empty() ? tokens[1] : ply_path + "/" + tokens[1];
}
void SceneLoader::parseMaterial(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
if (tokens[1] == "diffuse") {
// mtl diffuse albedo<r g b>
CHECK_EQ(tokens.size(), 5);
glm::vec3 albedo;
albedo[0] = atof(tokens[2].c_str());
albedo[1] = atof(tokens[3].c_str());
albedo[2] = atof(tokens[4].c_str());
d.bsdf = new DiffuseBsdf(albedo);
} else if (tokens[1] == "mirror") {
// mtl mirror reflectance<r g b>
CHECK_EQ(tokens.size(), 5);
glm::vec3 reflectance;
reflectance[0] = atof(tokens[2].c_str());
reflectance[1] = atof(tokens[3].c_str());
reflectance[2] = atof(tokens[4].c_str());
d.bsdf = new MirrorBsdf(reflectance);
} else if (tokens[1] == "glass") {
// mtl mirror etaA etaB
CHECK_EQ(tokens.size(), 4);
float eta_a = atof(tokens[2].c_str());
float eta_b = atof(tokens[3].c_str());
d.bsdf = new GlassBsdf(eta_a, eta_b);
} else if (tokens[1] == "transmission") {
// mtl transmission etaA etaB
CHECK_EQ(tokens.size(), 4);
float eta_a = atof(tokens[2].c_str());
float eta_b = atof(tokens[3].c_str());
d.bsdf = new TransmissionBsdf(eta_a, eta_b);
} else {
LOG(FATAL) << "unknown material type " << tokens[1];
}
}
void SceneLoader::parseBound(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 7);
glm::vec3 min(atof(tokens[1].c_str()), atof(tokens[2].c_str()),
atof(tokens[3].c_str()));
glm::vec3 max(atof(tokens[4].c_str()), atof(tokens[5].c_str()),
atof(tokens[6].c_str()));
d.object_aabb.bounds[0] = min;
d.object_aabb.bounds[1] = max;
}
void SceneLoader::parseScale(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 4);
d.transform = glm::scale(
d.transform, glm::vec3(atof(tokens[1].c_str()), atof(tokens[2].c_str()),
atof(tokens[3].c_str())));
}
void SceneLoader::parseRotate(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 3);
glm::vec3 axis;
if (tokens[1] == "x") {
axis = glm::vec3(1.f, 0.f, 0.f);
} else if (tokens[1] == "y") {
axis = glm::vec3(0.f, 1.f, 0.f);
} else if (tokens[1] == "z") {
axis = glm::vec3(0.f, 0.f, 1.f);
} else {
LOG(FATAL) << "invalid axis name " << tokens[1];
}
d.transform = glm::rotate(d.transform,
(float)glm::radians(atof(tokens[2].c_str())), axis);
}
void SceneLoader::parseTranslate(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 4);
d.transform = glm::translate(
d.transform, glm::vec3(atof(tokens[1].c_str()), atof(tokens[2].c_str()),
atof(tokens[3].c_str())));
}
void SceneLoader::parseFace(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 2);
d.num_faces = std::stoul(tokens[1]);
}
void SceneLoader::parseVertex(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 2);
d.num_vertices = std::stoul(tokens[1]);
}
void SceneLoader::parseLight(const std::vector<std::string>& tokens) {
if (tokens[1] == "point") {
CHECK_EQ(tokens.size(), 8);
glm::vec3 position, radiance;
position[0] = atof(tokens[2].c_str());
position[1] = atof(tokens[3].c_str());
position[2] = atof(tokens[4].c_str());
radiance[0] = atof(tokens[5].c_str());
radiance[1] = atof(tokens[6].c_str());
radiance[2] = atof(tokens[7].c_str());
addLight(new PointLight(position, radiance));
} else if (tokens[1] == "diffuse") {
CHECK_EQ(tokens.size(), 5);
glm::vec3 position, radiance;
radiance[0] = atof(tokens[2].c_str());
radiance[1] = atof(tokens[3].c_str());
radiance[2] = atof(tokens[4].c_str());
addLight(new DiffuseHemisphereLight(radiance));
} else {
LOG(FATAL) << "unknown light source " << tokens[1];
}
}
void SceneLoader::parseLineTokens(const std::string& ply_path,
const std::vector<std::string>& tokens) {
DomainTokenType type = getTokenType(tokens[0]);
switch (type) {
case DomainTokenType::kDomain:
parseDomain(tokens);
break;
case DomainTokenType::kFile:
parseFile(ply_path, tokens);
break;
case DomainTokenType::kMaterial:
parseMaterial(tokens);
break;
case DomainTokenType::kBound:
parseBound(tokens);
break;
case DomainTokenType::kScale:
parseScale(tokens);
break;
case DomainTokenType::kRotate:
parseRotate(tokens);
break;
case DomainTokenType::kTranslate:
parseTranslate(tokens);
break;
case DomainTokenType::kFace:
parseFace(tokens);
break;
case DomainTokenType::kVertex:
parseVertex(tokens);
break;
case DomainTokenType::kLight:
parseLight(tokens);
break;
default:
break;
}
}
void SceneLoader::countAndAllocate(std::ifstream& infile) {
int ndomains = 0;
int nlights = 0;
std::string line;
while (infile.good()) {
getline(infile, line);
char* token = std::strtok(&line[0], " ");
if (token != NULL) {
if (strcmp(token, "domain") == 0) {
++ndomains;
} else if (strcmp(token, "light") == 0) {
++nlights;
}
}
}
CHECK_GT(ndomains, 0);
domains_->resize(ndomains);
if (nlights)
lights_->resize(nlights);
else
std::cout << "[WARNING] no lights detected\n";
std::cout << "[INFO] number of domains: " << ndomains << "\n";
std::cout << "[INFO] number of lights: " << nlights << "\n";
}
// # domain 0
// domain
// file CornellBox-Original.obj
// mtl 1
// bound -1 -1 -1 1 1 1
// scale 1 1 1
// rotate 0 0 0
// translate 0 0 0
//
// # domain 1
// # tbd
void SceneLoader::load(const std::string& filename, const std::string& ply_path,
std::vector<Domain>* domains_out,
std::vector<Light*>* lights_out) {
reset(domains_out, lights_out);
std::ifstream infile(filename);
CHECK(infile.is_open()) << "unable to open input file " << filename;
countAndAllocate(infile);
infile.clear();
infile.seekg(infile.beg);
char delim[] = " ";
std::vector<std::string> tokens;
while (infile.good()) {
std::string line;
getline(infile, line);
#ifdef SPRAY_PRINT_LINES
std::cout << line << "\n";
#endif
char* token = std::strtok(&line[0], delim);
tokens.clear();
while (token != NULL) {
#ifdef SPRAY_PRINT_TOKENS
std::cout << token << " token len:" << std::string(token).size() << "\n";
#endif
tokens.push_back(token);
token = std::strtok(NULL, delim);
}
if (tokens.size()) parseLineTokens(ply_path, tokens);
}
infile.close();
// apply transformation matrix
for (auto& d : (*domains_out)) {
glm::vec4 min = d.transform * glm::vec4(d.object_aabb.bounds[0], 1.0f);
glm::vec4 max = d.transform * glm::vec4(d.object_aabb.bounds[1], 1.0f);
d.world_aabb.bounds[0] = glm::vec3(min);
d.world_aabb.bounds[1] = glm::vec3(max);
}
}
} // namespace spray
| 29.041551 | 80 | 0.572778 |
3974218429c4050238314f3d62724d1d653797df | 10,436 | hpp | C++ | OpenAutoItParser/include/OpenAutoIt/TokenKind.hpp | OpenAutoit/OpenAutoit | f58c98c6e2a706ba7f06dcbc08a54a5a6440063e | [
"MIT"
] | null | null | null | OpenAutoItParser/include/OpenAutoIt/TokenKind.hpp | OpenAutoit/OpenAutoit | f58c98c6e2a706ba7f06dcbc08a54a5a6440063e | [
"MIT"
] | 6 | 2022-02-01T04:07:12.000Z | 2022-03-01T04:43:49.000Z | OpenAutoItParser/include/OpenAutoIt/TokenKind.hpp | OpenAutoit/OpenAutoit | f58c98c6e2a706ba7f06dcbc08a54a5a6440063e | [
"MIT"
] | null | null | null | #pragma once
namespace OpenAutoIt
{
enum class TokenKind
{
NotAToken,
EndOfFile, // '\0'
NewLine, // '\n'
Comment, // ; Comment
VariableIdentifier, // $var
FunctionIdentifier, // my_func
/* Literals */
IntegerLiteral, // 123
FloatLiteral, // 0.123
StringLiteral, // "String"
/* Punctioation */
Comma, // ,
LParen, // (
RParen, // )
Dot, // .
LSquare, // [
RSquare, // ]
/* Macros */
// https://www.autoitscript.com/autoit3/docs/macros.htm
MK_AppDataCommonDir, // @AppDataCommonDir
MK_AppDataDir, // @AppDataDir
MK_AutoItExe, // @AutoItExe
MK_AutoItPID, // @AutoItPID
MK_AutoItVersion, // @AutoItVersion
MK_AutoItX64, // @AutoItX64
MK_COM_EventObj, // @COM_EventObj
MK_CommonFilesDir, // @CommonFilesDir
MK_Compiled, // @Compiled
MK_ComputerName, // @ComputerName
MK_ComSpec, // @ComSpec
MK_CPUArch, // @CPUArch
MK_CR, // @CR
MK_CRLF, // @CRLF
MK_DesktopCommonDir, // @DesktopCommonDir
MK_DesktopDepth, // @DesktopDepth
MK_DesktopDir, // @DesktopDir
MK_DesktopHeight, // @DesktopHeight
MK_DesktopRefresh, // @DesktopRefresh
MK_DesktopWidth, // @DesktopWidth
MK_DocumentsCommonDir, // @DocumentsCommonDir
MK_error, // @error
MK_exitCode, // @exitCode
MK_exitMethod, // @exitMethod
MK_extended, // @extended
MK_FavoritesCommonDir, // @FavoritesCommonDir
MK_FavoritesDir, // @FavoritesDir
MK_GUI_CtrlHandle, // @GUI_CtrlHandle
MK_GUI_CtrlId, // @GUI_CtrlId
MK_GUI_DragFile, // @GUI_DragFile
MK_GUI_DragId, // @GUI_DragId
MK_GUI_DropId, // @GUI_DropId
MK_GUI_WinHandle, // @GUI_WinHandle
MK_HomeDrive, // @HomeDrive
MK_HomePath, // @HomePath
MK_HomeShare, // @HomeShare
MK_HotKeyPressed, // @HotKeyPressed
MK_HOUR, // @HOUR
MK_IPAddress1, // @IPAddress1
MK_IPAddress2, // @IPAddress2
MK_IPAddress3, // @IPAddress3
MK_IPAddress4, // @IPAddress4
MK_KBLayout, // @KBLayout
MK_LF, // @LF
MK_LocalAppDataDir, // @LocalAppDataDir
MK_LogonDNSDomain, // @LogonDNSDomain
MK_LogonDomain, // @LogonDomain
MK_LogonServer, // @LogonServer
MK_MDAY, // @MDAY
MK_MIN, // @MIN
MK_MON, // @MON
MK_MSEC, // @MSEC
MK_MUILang, // @MUILang
MK_MyDocumentsDir, // @MyDocumentsDir
MK_NumParams, // @NumParams
MK_OSArch, // @OSArch
MK_OSBuild, // @OSBuild
MK_OSLang, // @OSLang
MK_OSServicePack, // @OSServicePack
MK_OSType, // @OSType
MK_OSVersion, // @OSVersion
MK_ProgramFilesDir, // @ProgramFilesDir
MK_ProgramsCommonDir, // @ProgramsCommonDir
MK_ProgramsDir, // @ProgramsDir
MK_ScriptDir, // @ScriptDir
MK_ScriptFullPath, // @ScriptFullPath
MK_ScriptLineNumber, // @ScriptLineNumber
MK_ScriptName, // @ScriptName
MK_SEC, // @SEC
MK_StartMenuCommonDir, // @StartMenuCommonDir
MK_StartMenuDir, // @StartMenuDir
MK_StartupCommonDir, // @StartupCommonDir
MK_StartupDir, // @StartupDir
MK_SW_DISABLE, // @SW_DISABLE
MK_SW_ENABLE, // @SW_ENABLE
MK_SW_HIDE, // @SW_HIDE
MK_SW_LOCK, // @SW_LOCK
MK_SW_MAXIMIZE, // @SW_MAXIMIZE
MK_SW_MINIMIZE, // @SW_MINIMIZE
MK_SW_RESTORE, // @SW_RESTORE
MK_SW_SHOW, // @SW_SHOW
MK_SW_SHOWDEFAULT, // @SW_SHOWDEFAULT
MK_SW_SHOWMAXIMIZED, // @SW_SHOWMAXIMIZED
MK_SW_SHOWMINIMIZED, // @SW_SHOWMINIMIZED
MK_SW_SHOWMINNOACTIVE, // @SW_SHOWMINNOACTIVE
MK_SW_SHOWNA, // @SW_SHOWNA
MK_SW_SHOWNOACTIVATE, // @SW_SHOWNOACTIVATE
MK_SW_SHOWNORMAL, // @SW_SHOWNORMAL
MK_SW_UNLOCK, // @SW_UNLOCK
MK_SystemDir, // @SystemDir
MK_TAB, // @TAB
MK_TempDir, // @TempDir
MK_TRAY_ID, // @TRAY_ID
MK_TrayIconFlashing, // @TrayIconFlashing
MK_TrayIconVisible, // @TrayIconVisible
MK_UserName, // @UserName
MK_UserProfileDir, // @UserProfileDir
MK_WDAY, // @WDAY
MK_WindowsDir, // @WindowsDir
MK_WorkingDir, // @WorkingDir
MK_YDAY, // @YDAY
MK_YEAR, // @YEAR
/* Preprocessor identifiers */
// https://www.autoitscript.com/autoit3/docs/intro/lang_directives.htm
// https://www.autoitscript.com/autoit3/docs/keywords/comments-start.htm
// TODO: Do we really need both variants as seperate tokens?
PP_CommentsStart, // #Comments-Start
PP_CommentsEnd, // #Comments-End
PP_CS, // #cs
PP_CE, // #ce
// https://www.autoitscript.com/autoit3/docs/keywords/include.htm
PP_Include, // #include
// https://www.autoitscript.com/autoit3/docs/keywords/include-once.htm
PP_IncludeOnce, // #include-once
// https://www.autoitscript.com/autoit3/docs/keywords/NoTrayIcon.htm
PP_NoTrayIcon, // #NoTrayIcon
// https://www.autoitscript.com/autoit3/docs/keywords/OnAutoItStartRegister.htm
PP_OnAutoItStartRegister, // #OnAutoitStartRegister
// https://www.autoitscript.com/autoit3/docs/keywords/pragma.htm
PP_Pragma, // #pragma
// https://www.autoitscript.com/autoit3/docs/keywords/RequireAdmin.htm
PP_RequireAdmin, // # RequireAdmin
/* Keywords */
// https://www.autoitscript.com/autoit3/docs/keywords.htm
// https://www.autoitscript.com/autoit3/docs/intro/lang_operators.htm
// https://www.autoitscript.com/autoit3/docs/keywords/Booleans.htm
KW_False, // False
KW_True, // True
// https://www.autoitscript.com/autoit3/docs/keywords/ContinueCase.htm
KW_ContinueCase, // ContinueCase
// https://www.autoitscript.com/autoit3/docs/keywords/ContinueLoop.htm
KW_ContinueLoop, // ContinueLoop
// https://www.autoitscript.com/autoit3/docs/keywords/Default.htm
KW_Default, // Default
// https://www.autoitscript.com/autoit3/docs/keywords/Dim.htm
KW_Dim, // Dim
KW_Local, // Local
KW_Global, // Global
KW_Const, // Const
// https://www.autoitscript.com/autoit3/docs/keywords/Do.htm
KW_Do, // Do
KW_Until, // Until
// https://www.autoitscript.com/autoit3/docs/keywords/Enum.htm
KW_Enum, // Enum
// https://www.autoitscript.com/autoit3/docs/keywords/Exit.htm
KW_Exit, // Exit
// https://www.autoitscript.com/autoit3/docs/keywords/ExitLoop.htm
KW_ExitLoop, // ExitLoop
// https://www.autoitscript.com/autoit3/docs/keywords/For.htm
KW_For, // For
KW_To, // To
KW_Step, // Step
KW_Next, // Next
// https://www.autoitscript.com/autoit3/docs/keywords/ForInNext.htm
KW_In, // In
// https://www.autoitscript.com/autoit3/docs/keywords/Func.htm
KW_Func, // Func
KW_Return, // Return
KW_EndFunc, // EndFunc
// https://www.autoitscript.com/autoit3/docs/keywords/If.htm
KW_If, // If
KW_Then, // Then
KW_EndIf, // EndIf
// https://www.autoitscript.com/autoit3/docs/keywords/IfElseEndIf.htm
KW_ElseIf, // ElseIf
KW_Else, // Else
// https://www.autoitscript.com/autoit3/docs/keywords/Null.htm
KW_Null, // Null
// https://www.autoitscript.com/autoit3/docs/keywords/ReDim.htm
KW_ReDim, // ReDim
// https://www.autoitscript.com/autoit3/docs/keywords/Select.htm
KW_Select, // Select
KW_Case, // Case
KW_EndSelect, // EndSelect
// https://www.autoitscript.com/autoit3/docs/keywords/Static.htm
KW_Static, // Static
// https://www.autoitscript.com/autoit3/docs/keywords/Switch.htm
KW_Switch, // Switch
KW_EndSwitch, // EndSwitch
// https://www.autoitscript.com/autoit3/docs/keywords/Volatile.htm
KW_Volatile, // Volatile
// https://www.autoitscript.com/autoit3/docs/keywords/While.htm
KW_While, // While
KW_WEnd, // WEnd
// https://www.autoitscript.com/autoit3/docs/keywords/With.htm
KW_With, // With
KW_EndWith, // EndWith
// https://www.autoitscript.com/autoit3/docs/intro/lang_operators.htm
KW_And, // And
KW_Or, // Or
KW_Not, // Not
/* Operator */
// https://www.autoitscript.com/autoit3/docs/intro/lang_operators.htm
OP_Equals, // = (Note includes assignment and case insensitive comparision)
OP_PlusEquals, // +=
OP_MinusEquals, // -=
OP_MultiplyEquals, // *=
OP_DivideEquals, // /=
OP_Concatenate, // &
OP_ConcatenateEquals, // &=
OP_Plus, // +
OP_Minus, // -
OP_Multiply, // *
OP_Divide, // /
OP_Raise, // ^
OP_EqualsEquals, // ==
OP_NotEqual, // <>
OP_GreaterThan, // >
OP_GreaterThanEqual, // >=
OP_LessThan, // <
OP_LessThanEqual, // <=
OP_TernaryIf, // ?
OP_TernaryElse, // :
};
} // namespace OpenAutoIt
| 41.412698 | 94 | 0.542353 |
3976a580c60f6c867eaa81ee34c727b5c0186dbd | 2,118 | cxx | C++ | STEER/STEERBase/AliGenEposEventHeader.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | STEER/STEERBase/AliGenEposEventHeader.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | STEER/STEERBase/AliGenEposEventHeader.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/*
* AliGenEposEventHeader.h
*
* Header for EPOS generated event.
*
* Author: Piotr Ostrowski
*/
#include "AliGenEposEventHeader.h"
ClassImp(AliGenEposEventHeader)
AliGenEposEventHeader::AliGenEposEventHeader(const char* name):
AliGenEventHeader(name),
fBimevt(0),
fPhievt(0),
fKolevt(0),
fKoievt(0),
fPmxevt(0),
fEgyevt(0),
fNpjevt(0),
fNtgevt(0),
fNpnevt(0),
fNppevt(0),
fNtnevt(0),
fNtpevt(0),
fJpnevt(0),
fJppevt(0),
fJtnevt(0),
fJtpevt(0),
fXbjevt(0),
fQsqevt(0),
fNglevt(0),
fZppevt(0),
fZptevt(0)
{
// Constructor
}
AliGenEposEventHeader::AliGenEposEventHeader() : fBimevt(0),
fPhievt(0),
fKolevt(0),
fKoievt(0),
fPmxevt(0),
fEgyevt(0),
fNpjevt(0),
fNtgevt(0),
fNpnevt(0),
fNppevt(0),
fNtnevt(0),
fNtpevt(0),
fJpnevt(0),
fJppevt(0),
fJtnevt(0),
fJtpevt(0),
fXbjevt(0),
fQsqevt(0),
fNglevt(0),
fZppevt(0),
fZptevt(0)
{
// Default constructor
}
| 25.518072 | 76 | 0.531161 |
397909e5ff617b46401a0c2a6bf3af3550b1f4c6 | 344 | cpp | C++ | Problemset/climbing-stairs/climbing-stairs.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | 1 | 2020-10-06T01:06:45.000Z | 2020-10-06T01:06:45.000Z | Problemset/climbing-stairs/climbing-stairs.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | null | null | null | Problemset/climbing-stairs/climbing-stairs.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | 1 | 2021-11-17T13:52:51.000Z | 2021-11-17T13:52:51.000Z |
// @Title: 爬楼梯 (Climbing Stairs)
// @Author: Singularity0909
// @Date: 2020-06-11 21:10:10
// @Runtime: 0 ms
// @Memory: 5.6 MB
class Solution {
public:
int ans[50] = { 0 };
int climbStairs(int n) {
if (n <= 3)
return n;
return ans[n] ? ans[n] : ans[n] = climbStairs(n - 1) + climbStairs(n - 2);
}
};
| 19.111111 | 82 | 0.52907 |
397adea56a014b5fc6911d96ffdb6695d6a84410 | 2,181 | hpp | C++ | VcppBits/Settings/SettingsException.hpp | faesong/vcppbits | 9ad70f8e398110df48e4e2640a06fca09ef994f9 | [
"MIT"
] | null | null | null | VcppBits/Settings/SettingsException.hpp | faesong/vcppbits | 9ad70f8e398110df48e4e2640a06fca09ef994f9 | [
"MIT"
] | null | null | null | VcppBits/Settings/SettingsException.hpp | faesong/vcppbits | 9ad70f8e398110df48e4e2640a06fca09ef994f9 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
// Copyright 2015-2020 Vitalii Minnakhmetov <restlessmonkey@ya.ru>
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef VcppBits_SETTINGS_EXCEPTION_HPP_INCLUDED__
#define VcppBits_SETTINGS_EXCEPTION_HPP_INCLUDED__
#include <string>
#include <stdexcept>
#include "VcppBits/Settings/SettingsStringUtils.hpp"
namespace VcppBits {
class SettingsException : std::exception {
public:
enum TYPE { ALREADY_LOADED, NOT_FOUND, OUT_OF_RANGE };
SettingsException (const std::string &setting_name, TYPE t)
: settingName(setting_name),
type (t) {
}
~SettingsException () throw () {}
const std::string& getFullDescription () const {
_errorMessage = std::string("Setting Error ")
+ SettingsStringUtils::toString(this->type) + ": \""
+ settingName + "\"";
return _errorMessage;
}
const char *what () const throw() {
return this->getFullDescription().c_str();
}
const std::string settingName;
mutable std::string _errorMessage;
const TYPE type;
};
} // namespace VcppBits
#endif // VcppBits_SETTINGS_EXCEPTION_HPP_INCLUDED__
| 34.619048 | 76 | 0.727648 |
397c9213cf3e3a4a6135912c2a1bfeec42dd44f7 | 51,295 | cc | C++ | c/test/cpp/auto_check_sbp_tracking_MsgMeasurementState.cc | Patrick-Luo-THR/libsbp | d42e4a1e3cedf6a82b1d993b82e0da148401f80d | [
"MIT"
] | 65 | 2015-03-25T10:28:10.000Z | 2022-02-24T12:36:49.000Z | c/test/cpp/auto_check_sbp_tracking_MsgMeasurementState.cc | Patrick-Luo-THR/libsbp | d42e4a1e3cedf6a82b1d993b82e0da148401f80d | [
"MIT"
] | 654 | 2015-03-24T17:43:55.000Z | 2022-03-31T21:42:49.000Z | c/test/cpp/auto_check_sbp_tracking_MsgMeasurementState.cc | Patrick-Luo-THR/libsbp | d42e4a1e3cedf6a82b1d993b82e0da148401f80d | [
"MIT"
] | 110 | 2015-03-24T17:38:35.000Z | 2022-03-21T02:05:19.000Z | /*
* Copyright (C) 2015-2021 Swift Navigation Inc.
* Contact: https://support.swiftnav.com
*
* This source is subject to the license found in the file 'LICENSE' which must
* be be distributed together with this source. All other rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*/
// This file was auto-generated from
// spec/tests/yaml/swiftnav/sbp/tracking/test_MsgMeasurementState.yaml by
// generate.py. Do not modify by hand!
#include <gtest/gtest.h>
#include <libsbp/cpp/message_handler.h>
#include <libsbp/cpp/message_traits.h>
#include <libsbp/cpp/state.h>
#include <cstring>
class Test_auto_check_sbp_tracking_MsgMeasurementState0
: public ::testing::Test,
public sbp::State,
public sbp::IReader,
public sbp::IWriter,
sbp::MessageHandler<sbp_msg_measurement_state_t> {
public:
Test_auto_check_sbp_tracking_MsgMeasurementState0()
: ::testing::Test(),
sbp::State(),
sbp::IReader(),
sbp::IWriter(),
sbp::MessageHandler<sbp_msg_measurement_state_t>(this),
last_msg_(),
last_msg_len_(),
last_sender_id_(),
n_callbacks_logged_(),
dummy_wr_(),
dummy_rd_(),
dummy_buff_() {
set_reader(this);
set_writer(this);
}
s32 read(uint8_t *buf, const uint32_t n) override {
uint32_t real_n = n;
memcpy(buf, dummy_buff_ + dummy_rd_, real_n);
dummy_rd_ += real_n;
return (s32)real_n;
}
s32 write(const uint8_t *buf, uint32_t n) override {
uint32_t real_n = n;
memcpy(dummy_buff_ + dummy_wr_, buf, real_n);
dummy_wr_ += real_n;
return (s32)real_n;
}
protected:
void handle_sbp_msg(uint16_t sender_id,
const sbp_msg_measurement_state_t &msg) override {
last_msg_ = msg;
last_sender_id_ = sender_id;
n_callbacks_logged_++;
}
sbp_msg_measurement_state_t last_msg_;
uint8_t last_msg_len_;
uint16_t last_sender_id_;
size_t n_callbacks_logged_;
uint32_t dummy_wr_;
uint32_t dummy_rd_;
uint8_t dummy_buff_[1024];
};
TEST_F(Test_auto_check_sbp_tracking_MsgMeasurementState0, Test) {
uint8_t encoded_frame[] = {
85, 97, 0, 207, 121, 237, 29, 0, 162, 0, 0, 0, 0, 0, 0,
27, 0, 201, 20, 0, 168, 32, 0, 184, 15, 0, 187, 0, 0, 0,
18, 0, 210, 16, 0, 167, 0, 0, 0, 23, 0, 213, 10, 0, 223,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 131, 2, 202,
27, 1, 192, 15, 1, 165, 29, 1, 146, 32, 1, 170, 18, 1, 201,
0, 0, 0, 0, 0, 0, 0, 0, 0, 23, 1, 212, 10, 1, 205,
0, 0, 0, 96, 3, 230, 0, 0, 0, 101, 3, 214, 103, 3, 212,
104, 3, 209, 106, 3, 157, 102, 3, 230, 0, 0, 0, 0, 0, 0,
101, 4, 189, 96, 4, 207, 106, 4, 164, 104, 4, 193, 0, 0, 0,
102, 4, 208, 0, 0, 0, 27, 12, 212, 29, 12, 161, 32, 12, 216,
30, 12, 216, 20, 12, 178, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
36, 14, 203, 0, 0, 0, 5, 14, 158, 4, 14, 194, 11, 14, 192,
9, 14, 207, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 20, 218,
5, 20, 176, 36, 20, 217, 11, 20, 200, 4, 20, 205, 0, 0, 0,
0, 0, 0, 35, 54,
};
sbp_msg_measurement_state_t test_msg{};
test_msg.n_states = 79;
test_msg.states[0].cn0 = 162;
test_msg.states[0].mesid.code = 0;
test_msg.states[0].mesid.sat = 29;
test_msg.states[1].cn0 = 0;
test_msg.states[1].mesid.code = 0;
test_msg.states[1].mesid.sat = 0;
test_msg.states[2].cn0 = 0;
test_msg.states[2].mesid.code = 0;
test_msg.states[2].mesid.sat = 0;
test_msg.states[3].cn0 = 201;
test_msg.states[3].mesid.code = 0;
test_msg.states[3].mesid.sat = 27;
test_msg.states[4].cn0 = 168;
test_msg.states[4].mesid.code = 0;
test_msg.states[4].mesid.sat = 20;
test_msg.states[5].cn0 = 184;
test_msg.states[5].mesid.code = 0;
test_msg.states[5].mesid.sat = 32;
test_msg.states[6].cn0 = 187;
test_msg.states[6].mesid.code = 0;
test_msg.states[6].mesid.sat = 15;
test_msg.states[7].cn0 = 0;
test_msg.states[7].mesid.code = 0;
test_msg.states[7].mesid.sat = 0;
test_msg.states[8].cn0 = 210;
test_msg.states[8].mesid.code = 0;
test_msg.states[8].mesid.sat = 18;
test_msg.states[9].cn0 = 167;
test_msg.states[9].mesid.code = 0;
test_msg.states[9].mesid.sat = 16;
test_msg.states[10].cn0 = 0;
test_msg.states[10].mesid.code = 0;
test_msg.states[10].mesid.sat = 0;
test_msg.states[11].cn0 = 213;
test_msg.states[11].mesid.code = 0;
test_msg.states[11].mesid.sat = 23;
test_msg.states[12].cn0 = 223;
test_msg.states[12].mesid.code = 0;
test_msg.states[12].mesid.sat = 10;
test_msg.states[13].cn0 = 0;
test_msg.states[13].mesid.code = 0;
test_msg.states[13].mesid.sat = 0;
test_msg.states[14].cn0 = 0;
test_msg.states[14].mesid.code = 0;
test_msg.states[14].mesid.sat = 0;
test_msg.states[15].cn0 = 0;
test_msg.states[15].mesid.code = 0;
test_msg.states[15].mesid.sat = 0;
test_msg.states[16].cn0 = 0;
test_msg.states[16].mesid.code = 0;
test_msg.states[16].mesid.sat = 0;
test_msg.states[17].cn0 = 202;
test_msg.states[17].mesid.code = 2;
test_msg.states[17].mesid.sat = 131;
test_msg.states[18].cn0 = 192;
test_msg.states[18].mesid.code = 1;
test_msg.states[18].mesid.sat = 27;
test_msg.states[19].cn0 = 165;
test_msg.states[19].mesid.code = 1;
test_msg.states[19].mesid.sat = 15;
test_msg.states[20].cn0 = 146;
test_msg.states[20].mesid.code = 1;
test_msg.states[20].mesid.sat = 29;
test_msg.states[21].cn0 = 170;
test_msg.states[21].mesid.code = 1;
test_msg.states[21].mesid.sat = 32;
test_msg.states[22].cn0 = 201;
test_msg.states[22].mesid.code = 1;
test_msg.states[22].mesid.sat = 18;
test_msg.states[23].cn0 = 0;
test_msg.states[23].mesid.code = 0;
test_msg.states[23].mesid.sat = 0;
test_msg.states[24].cn0 = 0;
test_msg.states[24].mesid.code = 0;
test_msg.states[24].mesid.sat = 0;
test_msg.states[25].cn0 = 0;
test_msg.states[25].mesid.code = 0;
test_msg.states[25].mesid.sat = 0;
test_msg.states[26].cn0 = 212;
test_msg.states[26].mesid.code = 1;
test_msg.states[26].mesid.sat = 23;
test_msg.states[27].cn0 = 205;
test_msg.states[27].mesid.code = 1;
test_msg.states[27].mesid.sat = 10;
test_msg.states[28].cn0 = 0;
test_msg.states[28].mesid.code = 0;
test_msg.states[28].mesid.sat = 0;
test_msg.states[29].cn0 = 230;
test_msg.states[29].mesid.code = 3;
test_msg.states[29].mesid.sat = 96;
test_msg.states[30].cn0 = 0;
test_msg.states[30].mesid.code = 0;
test_msg.states[30].mesid.sat = 0;
test_msg.states[31].cn0 = 214;
test_msg.states[31].mesid.code = 3;
test_msg.states[31].mesid.sat = 101;
test_msg.states[32].cn0 = 212;
test_msg.states[32].mesid.code = 3;
test_msg.states[32].mesid.sat = 103;
test_msg.states[33].cn0 = 209;
test_msg.states[33].mesid.code = 3;
test_msg.states[33].mesid.sat = 104;
test_msg.states[34].cn0 = 157;
test_msg.states[34].mesid.code = 3;
test_msg.states[34].mesid.sat = 106;
test_msg.states[35].cn0 = 230;
test_msg.states[35].mesid.code = 3;
test_msg.states[35].mesid.sat = 102;
test_msg.states[36].cn0 = 0;
test_msg.states[36].mesid.code = 0;
test_msg.states[36].mesid.sat = 0;
test_msg.states[37].cn0 = 0;
test_msg.states[37].mesid.code = 0;
test_msg.states[37].mesid.sat = 0;
test_msg.states[38].cn0 = 189;
test_msg.states[38].mesid.code = 4;
test_msg.states[38].mesid.sat = 101;
test_msg.states[39].cn0 = 207;
test_msg.states[39].mesid.code = 4;
test_msg.states[39].mesid.sat = 96;
test_msg.states[40].cn0 = 164;
test_msg.states[40].mesid.code = 4;
test_msg.states[40].mesid.sat = 106;
test_msg.states[41].cn0 = 193;
test_msg.states[41].mesid.code = 4;
test_msg.states[41].mesid.sat = 104;
test_msg.states[42].cn0 = 0;
test_msg.states[42].mesid.code = 0;
test_msg.states[42].mesid.sat = 0;
test_msg.states[43].cn0 = 208;
test_msg.states[43].mesid.code = 4;
test_msg.states[43].mesid.sat = 102;
test_msg.states[44].cn0 = 0;
test_msg.states[44].mesid.code = 0;
test_msg.states[44].mesid.sat = 0;
test_msg.states[45].cn0 = 212;
test_msg.states[45].mesid.code = 12;
test_msg.states[45].mesid.sat = 27;
test_msg.states[46].cn0 = 161;
test_msg.states[46].mesid.code = 12;
test_msg.states[46].mesid.sat = 29;
test_msg.states[47].cn0 = 216;
test_msg.states[47].mesid.code = 12;
test_msg.states[47].mesid.sat = 32;
test_msg.states[48].cn0 = 216;
test_msg.states[48].mesid.code = 12;
test_msg.states[48].mesid.sat = 30;
test_msg.states[49].cn0 = 178;
test_msg.states[49].mesid.code = 12;
test_msg.states[49].mesid.sat = 20;
test_msg.states[50].cn0 = 0;
test_msg.states[50].mesid.code = 0;
test_msg.states[50].mesid.sat = 0;
test_msg.states[51].cn0 = 0;
test_msg.states[51].mesid.code = 0;
test_msg.states[51].mesid.sat = 0;
test_msg.states[52].cn0 = 0;
test_msg.states[52].mesid.code = 0;
test_msg.states[52].mesid.sat = 0;
test_msg.states[53].cn0 = 0;
test_msg.states[53].mesid.code = 0;
test_msg.states[53].mesid.sat = 0;
test_msg.states[54].cn0 = 0;
test_msg.states[54].mesid.code = 0;
test_msg.states[54].mesid.sat = 0;
test_msg.states[55].cn0 = 0;
test_msg.states[55].mesid.code = 0;
test_msg.states[55].mesid.sat = 0;
test_msg.states[56].cn0 = 0;
test_msg.states[56].mesid.code = 0;
test_msg.states[56].mesid.sat = 0;
test_msg.states[57].cn0 = 0;
test_msg.states[57].mesid.code = 0;
test_msg.states[57].mesid.sat = 0;
test_msg.states[58].cn0 = 0;
test_msg.states[58].mesid.code = 0;
test_msg.states[58].mesid.sat = 0;
test_msg.states[59].cn0 = 0;
test_msg.states[59].mesid.code = 0;
test_msg.states[59].mesid.sat = 0;
test_msg.states[60].cn0 = 0;
test_msg.states[60].mesid.code = 0;
test_msg.states[60].mesid.sat = 0;
test_msg.states[61].cn0 = 0;
test_msg.states[61].mesid.code = 0;
test_msg.states[61].mesid.sat = 0;
test_msg.states[62].cn0 = 0;
test_msg.states[62].mesid.code = 0;
test_msg.states[62].mesid.sat = 0;
test_msg.states[63].cn0 = 203;
test_msg.states[63].mesid.code = 14;
test_msg.states[63].mesid.sat = 36;
test_msg.states[64].cn0 = 0;
test_msg.states[64].mesid.code = 0;
test_msg.states[64].mesid.sat = 0;
test_msg.states[65].cn0 = 158;
test_msg.states[65].mesid.code = 14;
test_msg.states[65].mesid.sat = 5;
test_msg.states[66].cn0 = 194;
test_msg.states[66].mesid.code = 14;
test_msg.states[66].mesid.sat = 4;
test_msg.states[67].cn0 = 192;
test_msg.states[67].mesid.code = 14;
test_msg.states[67].mesid.sat = 11;
test_msg.states[68].cn0 = 207;
test_msg.states[68].mesid.code = 14;
test_msg.states[68].mesid.sat = 9;
test_msg.states[69].cn0 = 0;
test_msg.states[69].mesid.code = 0;
test_msg.states[69].mesid.sat = 0;
test_msg.states[70].cn0 = 0;
test_msg.states[70].mesid.code = 0;
test_msg.states[70].mesid.sat = 0;
test_msg.states[71].cn0 = 0;
test_msg.states[71].mesid.code = 0;
test_msg.states[71].mesid.sat = 0;
test_msg.states[72].cn0 = 218;
test_msg.states[72].mesid.code = 20;
test_msg.states[72].mesid.sat = 9;
test_msg.states[73].cn0 = 176;
test_msg.states[73].mesid.code = 20;
test_msg.states[73].mesid.sat = 5;
test_msg.states[74].cn0 = 217;
test_msg.states[74].mesid.code = 20;
test_msg.states[74].mesid.sat = 36;
test_msg.states[75].cn0 = 200;
test_msg.states[75].mesid.code = 20;
test_msg.states[75].mesid.sat = 11;
test_msg.states[76].cn0 = 205;
test_msg.states[76].mesid.code = 20;
test_msg.states[76].mesid.sat = 4;
test_msg.states[77].cn0 = 0;
test_msg.states[77].mesid.code = 0;
test_msg.states[77].mesid.sat = 0;
test_msg.states[78].cn0 = 0;
test_msg.states[78].mesid.code = 0;
test_msg.states[78].mesid.sat = 0;
EXPECT_EQ(send_message(31183, test_msg), SBP_OK);
EXPECT_EQ(dummy_wr_, sizeof(encoded_frame));
EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0);
while (dummy_rd_ < dummy_wr_) {
process();
}
EXPECT_EQ(n_callbacks_logged_, 1);
EXPECT_EQ(last_sender_id_, 31183);
EXPECT_EQ(last_msg_, test_msg);
EXPECT_EQ(last_msg_.n_states, 79)
<< "incorrect value for last_msg_.n_states, expected 79, is "
<< last_msg_.n_states;
EXPECT_EQ(last_msg_.states[0].cn0, 162)
<< "incorrect value for last_msg_.states[0].cn0, expected 162, is "
<< last_msg_.states[0].cn0;
EXPECT_EQ(last_msg_.states[0].mesid.code, 0)
<< "incorrect value for last_msg_.states[0].mesid.code, expected 0, is "
<< last_msg_.states[0].mesid.code;
EXPECT_EQ(last_msg_.states[0].mesid.sat, 29)
<< "incorrect value for last_msg_.states[0].mesid.sat, expected 29, is "
<< last_msg_.states[0].mesid.sat;
EXPECT_EQ(last_msg_.states[1].cn0, 0)
<< "incorrect value for last_msg_.states[1].cn0, expected 0, is "
<< last_msg_.states[1].cn0;
EXPECT_EQ(last_msg_.states[1].mesid.code, 0)
<< "incorrect value for last_msg_.states[1].mesid.code, expected 0, is "
<< last_msg_.states[1].mesid.code;
EXPECT_EQ(last_msg_.states[1].mesid.sat, 0)
<< "incorrect value for last_msg_.states[1].mesid.sat, expected 0, is "
<< last_msg_.states[1].mesid.sat;
EXPECT_EQ(last_msg_.states[2].cn0, 0)
<< "incorrect value for last_msg_.states[2].cn0, expected 0, is "
<< last_msg_.states[2].cn0;
EXPECT_EQ(last_msg_.states[2].mesid.code, 0)
<< "incorrect value for last_msg_.states[2].mesid.code, expected 0, is "
<< last_msg_.states[2].mesid.code;
EXPECT_EQ(last_msg_.states[2].mesid.sat, 0)
<< "incorrect value for last_msg_.states[2].mesid.sat, expected 0, is "
<< last_msg_.states[2].mesid.sat;
EXPECT_EQ(last_msg_.states[3].cn0, 201)
<< "incorrect value for last_msg_.states[3].cn0, expected 201, is "
<< last_msg_.states[3].cn0;
EXPECT_EQ(last_msg_.states[3].mesid.code, 0)
<< "incorrect value for last_msg_.states[3].mesid.code, expected 0, is "
<< last_msg_.states[3].mesid.code;
EXPECT_EQ(last_msg_.states[3].mesid.sat, 27)
<< "incorrect value for last_msg_.states[3].mesid.sat, expected 27, is "
<< last_msg_.states[3].mesid.sat;
EXPECT_EQ(last_msg_.states[4].cn0, 168)
<< "incorrect value for last_msg_.states[4].cn0, expected 168, is "
<< last_msg_.states[4].cn0;
EXPECT_EQ(last_msg_.states[4].mesid.code, 0)
<< "incorrect value for last_msg_.states[4].mesid.code, expected 0, is "
<< last_msg_.states[4].mesid.code;
EXPECT_EQ(last_msg_.states[4].mesid.sat, 20)
<< "incorrect value for last_msg_.states[4].mesid.sat, expected 20, is "
<< last_msg_.states[4].mesid.sat;
EXPECT_EQ(last_msg_.states[5].cn0, 184)
<< "incorrect value for last_msg_.states[5].cn0, expected 184, is "
<< last_msg_.states[5].cn0;
EXPECT_EQ(last_msg_.states[5].mesid.code, 0)
<< "incorrect value for last_msg_.states[5].mesid.code, expected 0, is "
<< last_msg_.states[5].mesid.code;
EXPECT_EQ(last_msg_.states[5].mesid.sat, 32)
<< "incorrect value for last_msg_.states[5].mesid.sat, expected 32, is "
<< last_msg_.states[5].mesid.sat;
EXPECT_EQ(last_msg_.states[6].cn0, 187)
<< "incorrect value for last_msg_.states[6].cn0, expected 187, is "
<< last_msg_.states[6].cn0;
EXPECT_EQ(last_msg_.states[6].mesid.code, 0)
<< "incorrect value for last_msg_.states[6].mesid.code, expected 0, is "
<< last_msg_.states[6].mesid.code;
EXPECT_EQ(last_msg_.states[6].mesid.sat, 15)
<< "incorrect value for last_msg_.states[6].mesid.sat, expected 15, is "
<< last_msg_.states[6].mesid.sat;
EXPECT_EQ(last_msg_.states[7].cn0, 0)
<< "incorrect value for last_msg_.states[7].cn0, expected 0, is "
<< last_msg_.states[7].cn0;
EXPECT_EQ(last_msg_.states[7].mesid.code, 0)
<< "incorrect value for last_msg_.states[7].mesid.code, expected 0, is "
<< last_msg_.states[7].mesid.code;
EXPECT_EQ(last_msg_.states[7].mesid.sat, 0)
<< "incorrect value for last_msg_.states[7].mesid.sat, expected 0, is "
<< last_msg_.states[7].mesid.sat;
EXPECT_EQ(last_msg_.states[8].cn0, 210)
<< "incorrect value for last_msg_.states[8].cn0, expected 210, is "
<< last_msg_.states[8].cn0;
EXPECT_EQ(last_msg_.states[8].mesid.code, 0)
<< "incorrect value for last_msg_.states[8].mesid.code, expected 0, is "
<< last_msg_.states[8].mesid.code;
EXPECT_EQ(last_msg_.states[8].mesid.sat, 18)
<< "incorrect value for last_msg_.states[8].mesid.sat, expected 18, is "
<< last_msg_.states[8].mesid.sat;
EXPECT_EQ(last_msg_.states[9].cn0, 167)
<< "incorrect value for last_msg_.states[9].cn0, expected 167, is "
<< last_msg_.states[9].cn0;
EXPECT_EQ(last_msg_.states[9].mesid.code, 0)
<< "incorrect value for last_msg_.states[9].mesid.code, expected 0, is "
<< last_msg_.states[9].mesid.code;
EXPECT_EQ(last_msg_.states[9].mesid.sat, 16)
<< "incorrect value for last_msg_.states[9].mesid.sat, expected 16, is "
<< last_msg_.states[9].mesid.sat;
EXPECT_EQ(last_msg_.states[10].cn0, 0)
<< "incorrect value for last_msg_.states[10].cn0, expected 0, is "
<< last_msg_.states[10].cn0;
EXPECT_EQ(last_msg_.states[10].mesid.code, 0)
<< "incorrect value for last_msg_.states[10].mesid.code, expected 0, is "
<< last_msg_.states[10].mesid.code;
EXPECT_EQ(last_msg_.states[10].mesid.sat, 0)
<< "incorrect value for last_msg_.states[10].mesid.sat, expected 0, is "
<< last_msg_.states[10].mesid.sat;
EXPECT_EQ(last_msg_.states[11].cn0, 213)
<< "incorrect value for last_msg_.states[11].cn0, expected 213, is "
<< last_msg_.states[11].cn0;
EXPECT_EQ(last_msg_.states[11].mesid.code, 0)
<< "incorrect value for last_msg_.states[11].mesid.code, expected 0, is "
<< last_msg_.states[11].mesid.code;
EXPECT_EQ(last_msg_.states[11].mesid.sat, 23)
<< "incorrect value for last_msg_.states[11].mesid.sat, expected 23, is "
<< last_msg_.states[11].mesid.sat;
EXPECT_EQ(last_msg_.states[12].cn0, 223)
<< "incorrect value for last_msg_.states[12].cn0, expected 223, is "
<< last_msg_.states[12].cn0;
EXPECT_EQ(last_msg_.states[12].mesid.code, 0)
<< "incorrect value for last_msg_.states[12].mesid.code, expected 0, is "
<< last_msg_.states[12].mesid.code;
EXPECT_EQ(last_msg_.states[12].mesid.sat, 10)
<< "incorrect value for last_msg_.states[12].mesid.sat, expected 10, is "
<< last_msg_.states[12].mesid.sat;
EXPECT_EQ(last_msg_.states[13].cn0, 0)
<< "incorrect value for last_msg_.states[13].cn0, expected 0, is "
<< last_msg_.states[13].cn0;
EXPECT_EQ(last_msg_.states[13].mesid.code, 0)
<< "incorrect value for last_msg_.states[13].mesid.code, expected 0, is "
<< last_msg_.states[13].mesid.code;
EXPECT_EQ(last_msg_.states[13].mesid.sat, 0)
<< "incorrect value for last_msg_.states[13].mesid.sat, expected 0, is "
<< last_msg_.states[13].mesid.sat;
EXPECT_EQ(last_msg_.states[14].cn0, 0)
<< "incorrect value for last_msg_.states[14].cn0, expected 0, is "
<< last_msg_.states[14].cn0;
EXPECT_EQ(last_msg_.states[14].mesid.code, 0)
<< "incorrect value for last_msg_.states[14].mesid.code, expected 0, is "
<< last_msg_.states[14].mesid.code;
EXPECT_EQ(last_msg_.states[14].mesid.sat, 0)
<< "incorrect value for last_msg_.states[14].mesid.sat, expected 0, is "
<< last_msg_.states[14].mesid.sat;
EXPECT_EQ(last_msg_.states[15].cn0, 0)
<< "incorrect value for last_msg_.states[15].cn0, expected 0, is "
<< last_msg_.states[15].cn0;
EXPECT_EQ(last_msg_.states[15].mesid.code, 0)
<< "incorrect value for last_msg_.states[15].mesid.code, expected 0, is "
<< last_msg_.states[15].mesid.code;
EXPECT_EQ(last_msg_.states[15].mesid.sat, 0)
<< "incorrect value for last_msg_.states[15].mesid.sat, expected 0, is "
<< last_msg_.states[15].mesid.sat;
EXPECT_EQ(last_msg_.states[16].cn0, 0)
<< "incorrect value for last_msg_.states[16].cn0, expected 0, is "
<< last_msg_.states[16].cn0;
EXPECT_EQ(last_msg_.states[16].mesid.code, 0)
<< "incorrect value for last_msg_.states[16].mesid.code, expected 0, is "
<< last_msg_.states[16].mesid.code;
EXPECT_EQ(last_msg_.states[16].mesid.sat, 0)
<< "incorrect value for last_msg_.states[16].mesid.sat, expected 0, is "
<< last_msg_.states[16].mesid.sat;
EXPECT_EQ(last_msg_.states[17].cn0, 202)
<< "incorrect value for last_msg_.states[17].cn0, expected 202, is "
<< last_msg_.states[17].cn0;
EXPECT_EQ(last_msg_.states[17].mesid.code, 2)
<< "incorrect value for last_msg_.states[17].mesid.code, expected 2, is "
<< last_msg_.states[17].mesid.code;
EXPECT_EQ(last_msg_.states[17].mesid.sat, 131)
<< "incorrect value for last_msg_.states[17].mesid.sat, expected 131, is "
<< last_msg_.states[17].mesid.sat;
EXPECT_EQ(last_msg_.states[18].cn0, 192)
<< "incorrect value for last_msg_.states[18].cn0, expected 192, is "
<< last_msg_.states[18].cn0;
EXPECT_EQ(last_msg_.states[18].mesid.code, 1)
<< "incorrect value for last_msg_.states[18].mesid.code, expected 1, is "
<< last_msg_.states[18].mesid.code;
EXPECT_EQ(last_msg_.states[18].mesid.sat, 27)
<< "incorrect value for last_msg_.states[18].mesid.sat, expected 27, is "
<< last_msg_.states[18].mesid.sat;
EXPECT_EQ(last_msg_.states[19].cn0, 165)
<< "incorrect value for last_msg_.states[19].cn0, expected 165, is "
<< last_msg_.states[19].cn0;
EXPECT_EQ(last_msg_.states[19].mesid.code, 1)
<< "incorrect value for last_msg_.states[19].mesid.code, expected 1, is "
<< last_msg_.states[19].mesid.code;
EXPECT_EQ(last_msg_.states[19].mesid.sat, 15)
<< "incorrect value for last_msg_.states[19].mesid.sat, expected 15, is "
<< last_msg_.states[19].mesid.sat;
EXPECT_EQ(last_msg_.states[20].cn0, 146)
<< "incorrect value for last_msg_.states[20].cn0, expected 146, is "
<< last_msg_.states[20].cn0;
EXPECT_EQ(last_msg_.states[20].mesid.code, 1)
<< "incorrect value for last_msg_.states[20].mesid.code, expected 1, is "
<< last_msg_.states[20].mesid.code;
EXPECT_EQ(last_msg_.states[20].mesid.sat, 29)
<< "incorrect value for last_msg_.states[20].mesid.sat, expected 29, is "
<< last_msg_.states[20].mesid.sat;
EXPECT_EQ(last_msg_.states[21].cn0, 170)
<< "incorrect value for last_msg_.states[21].cn0, expected 170, is "
<< last_msg_.states[21].cn0;
EXPECT_EQ(last_msg_.states[21].mesid.code, 1)
<< "incorrect value for last_msg_.states[21].mesid.code, expected 1, is "
<< last_msg_.states[21].mesid.code;
EXPECT_EQ(last_msg_.states[21].mesid.sat, 32)
<< "incorrect value for last_msg_.states[21].mesid.sat, expected 32, is "
<< last_msg_.states[21].mesid.sat;
EXPECT_EQ(last_msg_.states[22].cn0, 201)
<< "incorrect value for last_msg_.states[22].cn0, expected 201, is "
<< last_msg_.states[22].cn0;
EXPECT_EQ(last_msg_.states[22].mesid.code, 1)
<< "incorrect value for last_msg_.states[22].mesid.code, expected 1, is "
<< last_msg_.states[22].mesid.code;
EXPECT_EQ(last_msg_.states[22].mesid.sat, 18)
<< "incorrect value for last_msg_.states[22].mesid.sat, expected 18, is "
<< last_msg_.states[22].mesid.sat;
EXPECT_EQ(last_msg_.states[23].cn0, 0)
<< "incorrect value for last_msg_.states[23].cn0, expected 0, is "
<< last_msg_.states[23].cn0;
EXPECT_EQ(last_msg_.states[23].mesid.code, 0)
<< "incorrect value for last_msg_.states[23].mesid.code, expected 0, is "
<< last_msg_.states[23].mesid.code;
EXPECT_EQ(last_msg_.states[23].mesid.sat, 0)
<< "incorrect value for last_msg_.states[23].mesid.sat, expected 0, is "
<< last_msg_.states[23].mesid.sat;
EXPECT_EQ(last_msg_.states[24].cn0, 0)
<< "incorrect value for last_msg_.states[24].cn0, expected 0, is "
<< last_msg_.states[24].cn0;
EXPECT_EQ(last_msg_.states[24].mesid.code, 0)
<< "incorrect value for last_msg_.states[24].mesid.code, expected 0, is "
<< last_msg_.states[24].mesid.code;
EXPECT_EQ(last_msg_.states[24].mesid.sat, 0)
<< "incorrect value for last_msg_.states[24].mesid.sat, expected 0, is "
<< last_msg_.states[24].mesid.sat;
EXPECT_EQ(last_msg_.states[25].cn0, 0)
<< "incorrect value for last_msg_.states[25].cn0, expected 0, is "
<< last_msg_.states[25].cn0;
EXPECT_EQ(last_msg_.states[25].mesid.code, 0)
<< "incorrect value for last_msg_.states[25].mesid.code, expected 0, is "
<< last_msg_.states[25].mesid.code;
EXPECT_EQ(last_msg_.states[25].mesid.sat, 0)
<< "incorrect value for last_msg_.states[25].mesid.sat, expected 0, is "
<< last_msg_.states[25].mesid.sat;
EXPECT_EQ(last_msg_.states[26].cn0, 212)
<< "incorrect value for last_msg_.states[26].cn0, expected 212, is "
<< last_msg_.states[26].cn0;
EXPECT_EQ(last_msg_.states[26].mesid.code, 1)
<< "incorrect value for last_msg_.states[26].mesid.code, expected 1, is "
<< last_msg_.states[26].mesid.code;
EXPECT_EQ(last_msg_.states[26].mesid.sat, 23)
<< "incorrect value for last_msg_.states[26].mesid.sat, expected 23, is "
<< last_msg_.states[26].mesid.sat;
EXPECT_EQ(last_msg_.states[27].cn0, 205)
<< "incorrect value for last_msg_.states[27].cn0, expected 205, is "
<< last_msg_.states[27].cn0;
EXPECT_EQ(last_msg_.states[27].mesid.code, 1)
<< "incorrect value for last_msg_.states[27].mesid.code, expected 1, is "
<< last_msg_.states[27].mesid.code;
EXPECT_EQ(last_msg_.states[27].mesid.sat, 10)
<< "incorrect value for last_msg_.states[27].mesid.sat, expected 10, is "
<< last_msg_.states[27].mesid.sat;
EXPECT_EQ(last_msg_.states[28].cn0, 0)
<< "incorrect value for last_msg_.states[28].cn0, expected 0, is "
<< last_msg_.states[28].cn0;
EXPECT_EQ(last_msg_.states[28].mesid.code, 0)
<< "incorrect value for last_msg_.states[28].mesid.code, expected 0, is "
<< last_msg_.states[28].mesid.code;
EXPECT_EQ(last_msg_.states[28].mesid.sat, 0)
<< "incorrect value for last_msg_.states[28].mesid.sat, expected 0, is "
<< last_msg_.states[28].mesid.sat;
EXPECT_EQ(last_msg_.states[29].cn0, 230)
<< "incorrect value for last_msg_.states[29].cn0, expected 230, is "
<< last_msg_.states[29].cn0;
EXPECT_EQ(last_msg_.states[29].mesid.code, 3)
<< "incorrect value for last_msg_.states[29].mesid.code, expected 3, is "
<< last_msg_.states[29].mesid.code;
EXPECT_EQ(last_msg_.states[29].mesid.sat, 96)
<< "incorrect value for last_msg_.states[29].mesid.sat, expected 96, is "
<< last_msg_.states[29].mesid.sat;
EXPECT_EQ(last_msg_.states[30].cn0, 0)
<< "incorrect value for last_msg_.states[30].cn0, expected 0, is "
<< last_msg_.states[30].cn0;
EXPECT_EQ(last_msg_.states[30].mesid.code, 0)
<< "incorrect value for last_msg_.states[30].mesid.code, expected 0, is "
<< last_msg_.states[30].mesid.code;
EXPECT_EQ(last_msg_.states[30].mesid.sat, 0)
<< "incorrect value for last_msg_.states[30].mesid.sat, expected 0, is "
<< last_msg_.states[30].mesid.sat;
EXPECT_EQ(last_msg_.states[31].cn0, 214)
<< "incorrect value for last_msg_.states[31].cn0, expected 214, is "
<< last_msg_.states[31].cn0;
EXPECT_EQ(last_msg_.states[31].mesid.code, 3)
<< "incorrect value for last_msg_.states[31].mesid.code, expected 3, is "
<< last_msg_.states[31].mesid.code;
EXPECT_EQ(last_msg_.states[31].mesid.sat, 101)
<< "incorrect value for last_msg_.states[31].mesid.sat, expected 101, is "
<< last_msg_.states[31].mesid.sat;
EXPECT_EQ(last_msg_.states[32].cn0, 212)
<< "incorrect value for last_msg_.states[32].cn0, expected 212, is "
<< last_msg_.states[32].cn0;
EXPECT_EQ(last_msg_.states[32].mesid.code, 3)
<< "incorrect value for last_msg_.states[32].mesid.code, expected 3, is "
<< last_msg_.states[32].mesid.code;
EXPECT_EQ(last_msg_.states[32].mesid.sat, 103)
<< "incorrect value for last_msg_.states[32].mesid.sat, expected 103, is "
<< last_msg_.states[32].mesid.sat;
EXPECT_EQ(last_msg_.states[33].cn0, 209)
<< "incorrect value for last_msg_.states[33].cn0, expected 209, is "
<< last_msg_.states[33].cn0;
EXPECT_EQ(last_msg_.states[33].mesid.code, 3)
<< "incorrect value for last_msg_.states[33].mesid.code, expected 3, is "
<< last_msg_.states[33].mesid.code;
EXPECT_EQ(last_msg_.states[33].mesid.sat, 104)
<< "incorrect value for last_msg_.states[33].mesid.sat, expected 104, is "
<< last_msg_.states[33].mesid.sat;
EXPECT_EQ(last_msg_.states[34].cn0, 157)
<< "incorrect value for last_msg_.states[34].cn0, expected 157, is "
<< last_msg_.states[34].cn0;
EXPECT_EQ(last_msg_.states[34].mesid.code, 3)
<< "incorrect value for last_msg_.states[34].mesid.code, expected 3, is "
<< last_msg_.states[34].mesid.code;
EXPECT_EQ(last_msg_.states[34].mesid.sat, 106)
<< "incorrect value for last_msg_.states[34].mesid.sat, expected 106, is "
<< last_msg_.states[34].mesid.sat;
EXPECT_EQ(last_msg_.states[35].cn0, 230)
<< "incorrect value for last_msg_.states[35].cn0, expected 230, is "
<< last_msg_.states[35].cn0;
EXPECT_EQ(last_msg_.states[35].mesid.code, 3)
<< "incorrect value for last_msg_.states[35].mesid.code, expected 3, is "
<< last_msg_.states[35].mesid.code;
EXPECT_EQ(last_msg_.states[35].mesid.sat, 102)
<< "incorrect value for last_msg_.states[35].mesid.sat, expected 102, is "
<< last_msg_.states[35].mesid.sat;
EXPECT_EQ(last_msg_.states[36].cn0, 0)
<< "incorrect value for last_msg_.states[36].cn0, expected 0, is "
<< last_msg_.states[36].cn0;
EXPECT_EQ(last_msg_.states[36].mesid.code, 0)
<< "incorrect value for last_msg_.states[36].mesid.code, expected 0, is "
<< last_msg_.states[36].mesid.code;
EXPECT_EQ(last_msg_.states[36].mesid.sat, 0)
<< "incorrect value for last_msg_.states[36].mesid.sat, expected 0, is "
<< last_msg_.states[36].mesid.sat;
EXPECT_EQ(last_msg_.states[37].cn0, 0)
<< "incorrect value for last_msg_.states[37].cn0, expected 0, is "
<< last_msg_.states[37].cn0;
EXPECT_EQ(last_msg_.states[37].mesid.code, 0)
<< "incorrect value for last_msg_.states[37].mesid.code, expected 0, is "
<< last_msg_.states[37].mesid.code;
EXPECT_EQ(last_msg_.states[37].mesid.sat, 0)
<< "incorrect value for last_msg_.states[37].mesid.sat, expected 0, is "
<< last_msg_.states[37].mesid.sat;
EXPECT_EQ(last_msg_.states[38].cn0, 189)
<< "incorrect value for last_msg_.states[38].cn0, expected 189, is "
<< last_msg_.states[38].cn0;
EXPECT_EQ(last_msg_.states[38].mesid.code, 4)
<< "incorrect value for last_msg_.states[38].mesid.code, expected 4, is "
<< last_msg_.states[38].mesid.code;
EXPECT_EQ(last_msg_.states[38].mesid.sat, 101)
<< "incorrect value for last_msg_.states[38].mesid.sat, expected 101, is "
<< last_msg_.states[38].mesid.sat;
EXPECT_EQ(last_msg_.states[39].cn0, 207)
<< "incorrect value for last_msg_.states[39].cn0, expected 207, is "
<< last_msg_.states[39].cn0;
EXPECT_EQ(last_msg_.states[39].mesid.code, 4)
<< "incorrect value for last_msg_.states[39].mesid.code, expected 4, is "
<< last_msg_.states[39].mesid.code;
EXPECT_EQ(last_msg_.states[39].mesid.sat, 96)
<< "incorrect value for last_msg_.states[39].mesid.sat, expected 96, is "
<< last_msg_.states[39].mesid.sat;
EXPECT_EQ(last_msg_.states[40].cn0, 164)
<< "incorrect value for last_msg_.states[40].cn0, expected 164, is "
<< last_msg_.states[40].cn0;
EXPECT_EQ(last_msg_.states[40].mesid.code, 4)
<< "incorrect value for last_msg_.states[40].mesid.code, expected 4, is "
<< last_msg_.states[40].mesid.code;
EXPECT_EQ(last_msg_.states[40].mesid.sat, 106)
<< "incorrect value for last_msg_.states[40].mesid.sat, expected 106, is "
<< last_msg_.states[40].mesid.sat;
EXPECT_EQ(last_msg_.states[41].cn0, 193)
<< "incorrect value for last_msg_.states[41].cn0, expected 193, is "
<< last_msg_.states[41].cn0;
EXPECT_EQ(last_msg_.states[41].mesid.code, 4)
<< "incorrect value for last_msg_.states[41].mesid.code, expected 4, is "
<< last_msg_.states[41].mesid.code;
EXPECT_EQ(last_msg_.states[41].mesid.sat, 104)
<< "incorrect value for last_msg_.states[41].mesid.sat, expected 104, is "
<< last_msg_.states[41].mesid.sat;
EXPECT_EQ(last_msg_.states[42].cn0, 0)
<< "incorrect value for last_msg_.states[42].cn0, expected 0, is "
<< last_msg_.states[42].cn0;
EXPECT_EQ(last_msg_.states[42].mesid.code, 0)
<< "incorrect value for last_msg_.states[42].mesid.code, expected 0, is "
<< last_msg_.states[42].mesid.code;
EXPECT_EQ(last_msg_.states[42].mesid.sat, 0)
<< "incorrect value for last_msg_.states[42].mesid.sat, expected 0, is "
<< last_msg_.states[42].mesid.sat;
EXPECT_EQ(last_msg_.states[43].cn0, 208)
<< "incorrect value for last_msg_.states[43].cn0, expected 208, is "
<< last_msg_.states[43].cn0;
EXPECT_EQ(last_msg_.states[43].mesid.code, 4)
<< "incorrect value for last_msg_.states[43].mesid.code, expected 4, is "
<< last_msg_.states[43].mesid.code;
EXPECT_EQ(last_msg_.states[43].mesid.sat, 102)
<< "incorrect value for last_msg_.states[43].mesid.sat, expected 102, is "
<< last_msg_.states[43].mesid.sat;
EXPECT_EQ(last_msg_.states[44].cn0, 0)
<< "incorrect value for last_msg_.states[44].cn0, expected 0, is "
<< last_msg_.states[44].cn0;
EXPECT_EQ(last_msg_.states[44].mesid.code, 0)
<< "incorrect value for last_msg_.states[44].mesid.code, expected 0, is "
<< last_msg_.states[44].mesid.code;
EXPECT_EQ(last_msg_.states[44].mesid.sat, 0)
<< "incorrect value for last_msg_.states[44].mesid.sat, expected 0, is "
<< last_msg_.states[44].mesid.sat;
EXPECT_EQ(last_msg_.states[45].cn0, 212)
<< "incorrect value for last_msg_.states[45].cn0, expected 212, is "
<< last_msg_.states[45].cn0;
EXPECT_EQ(last_msg_.states[45].mesid.code, 12)
<< "incorrect value for last_msg_.states[45].mesid.code, expected 12, is "
<< last_msg_.states[45].mesid.code;
EXPECT_EQ(last_msg_.states[45].mesid.sat, 27)
<< "incorrect value for last_msg_.states[45].mesid.sat, expected 27, is "
<< last_msg_.states[45].mesid.sat;
EXPECT_EQ(last_msg_.states[46].cn0, 161)
<< "incorrect value for last_msg_.states[46].cn0, expected 161, is "
<< last_msg_.states[46].cn0;
EXPECT_EQ(last_msg_.states[46].mesid.code, 12)
<< "incorrect value for last_msg_.states[46].mesid.code, expected 12, is "
<< last_msg_.states[46].mesid.code;
EXPECT_EQ(last_msg_.states[46].mesid.sat, 29)
<< "incorrect value for last_msg_.states[46].mesid.sat, expected 29, is "
<< last_msg_.states[46].mesid.sat;
EXPECT_EQ(last_msg_.states[47].cn0, 216)
<< "incorrect value for last_msg_.states[47].cn0, expected 216, is "
<< last_msg_.states[47].cn0;
EXPECT_EQ(last_msg_.states[47].mesid.code, 12)
<< "incorrect value for last_msg_.states[47].mesid.code, expected 12, is "
<< last_msg_.states[47].mesid.code;
EXPECT_EQ(last_msg_.states[47].mesid.sat, 32)
<< "incorrect value for last_msg_.states[47].mesid.sat, expected 32, is "
<< last_msg_.states[47].mesid.sat;
EXPECT_EQ(last_msg_.states[48].cn0, 216)
<< "incorrect value for last_msg_.states[48].cn0, expected 216, is "
<< last_msg_.states[48].cn0;
EXPECT_EQ(last_msg_.states[48].mesid.code, 12)
<< "incorrect value for last_msg_.states[48].mesid.code, expected 12, is "
<< last_msg_.states[48].mesid.code;
EXPECT_EQ(last_msg_.states[48].mesid.sat, 30)
<< "incorrect value for last_msg_.states[48].mesid.sat, expected 30, is "
<< last_msg_.states[48].mesid.sat;
EXPECT_EQ(last_msg_.states[49].cn0, 178)
<< "incorrect value for last_msg_.states[49].cn0, expected 178, is "
<< last_msg_.states[49].cn0;
EXPECT_EQ(last_msg_.states[49].mesid.code, 12)
<< "incorrect value for last_msg_.states[49].mesid.code, expected 12, is "
<< last_msg_.states[49].mesid.code;
EXPECT_EQ(last_msg_.states[49].mesid.sat, 20)
<< "incorrect value for last_msg_.states[49].mesid.sat, expected 20, is "
<< last_msg_.states[49].mesid.sat;
EXPECT_EQ(last_msg_.states[50].cn0, 0)
<< "incorrect value for last_msg_.states[50].cn0, expected 0, is "
<< last_msg_.states[50].cn0;
EXPECT_EQ(last_msg_.states[50].mesid.code, 0)
<< "incorrect value for last_msg_.states[50].mesid.code, expected 0, is "
<< last_msg_.states[50].mesid.code;
EXPECT_EQ(last_msg_.states[50].mesid.sat, 0)
<< "incorrect value for last_msg_.states[50].mesid.sat, expected 0, is "
<< last_msg_.states[50].mesid.sat;
EXPECT_EQ(last_msg_.states[51].cn0, 0)
<< "incorrect value for last_msg_.states[51].cn0, expected 0, is "
<< last_msg_.states[51].cn0;
EXPECT_EQ(last_msg_.states[51].mesid.code, 0)
<< "incorrect value for last_msg_.states[51].mesid.code, expected 0, is "
<< last_msg_.states[51].mesid.code;
EXPECT_EQ(last_msg_.states[51].mesid.sat, 0)
<< "incorrect value for last_msg_.states[51].mesid.sat, expected 0, is "
<< last_msg_.states[51].mesid.sat;
EXPECT_EQ(last_msg_.states[52].cn0, 0)
<< "incorrect value for last_msg_.states[52].cn0, expected 0, is "
<< last_msg_.states[52].cn0;
EXPECT_EQ(last_msg_.states[52].mesid.code, 0)
<< "incorrect value for last_msg_.states[52].mesid.code, expected 0, is "
<< last_msg_.states[52].mesid.code;
EXPECT_EQ(last_msg_.states[52].mesid.sat, 0)
<< "incorrect value for last_msg_.states[52].mesid.sat, expected 0, is "
<< last_msg_.states[52].mesid.sat;
EXPECT_EQ(last_msg_.states[53].cn0, 0)
<< "incorrect value for last_msg_.states[53].cn0, expected 0, is "
<< last_msg_.states[53].cn0;
EXPECT_EQ(last_msg_.states[53].mesid.code, 0)
<< "incorrect value for last_msg_.states[53].mesid.code, expected 0, is "
<< last_msg_.states[53].mesid.code;
EXPECT_EQ(last_msg_.states[53].mesid.sat, 0)
<< "incorrect value for last_msg_.states[53].mesid.sat, expected 0, is "
<< last_msg_.states[53].mesid.sat;
EXPECT_EQ(last_msg_.states[54].cn0, 0)
<< "incorrect value for last_msg_.states[54].cn0, expected 0, is "
<< last_msg_.states[54].cn0;
EXPECT_EQ(last_msg_.states[54].mesid.code, 0)
<< "incorrect value for last_msg_.states[54].mesid.code, expected 0, is "
<< last_msg_.states[54].mesid.code;
EXPECT_EQ(last_msg_.states[54].mesid.sat, 0)
<< "incorrect value for last_msg_.states[54].mesid.sat, expected 0, is "
<< last_msg_.states[54].mesid.sat;
EXPECT_EQ(last_msg_.states[55].cn0, 0)
<< "incorrect value for last_msg_.states[55].cn0, expected 0, is "
<< last_msg_.states[55].cn0;
EXPECT_EQ(last_msg_.states[55].mesid.code, 0)
<< "incorrect value for last_msg_.states[55].mesid.code, expected 0, is "
<< last_msg_.states[55].mesid.code;
EXPECT_EQ(last_msg_.states[55].mesid.sat, 0)
<< "incorrect value for last_msg_.states[55].mesid.sat, expected 0, is "
<< last_msg_.states[55].mesid.sat;
EXPECT_EQ(last_msg_.states[56].cn0, 0)
<< "incorrect value for last_msg_.states[56].cn0, expected 0, is "
<< last_msg_.states[56].cn0;
EXPECT_EQ(last_msg_.states[56].mesid.code, 0)
<< "incorrect value for last_msg_.states[56].mesid.code, expected 0, is "
<< last_msg_.states[56].mesid.code;
EXPECT_EQ(last_msg_.states[56].mesid.sat, 0)
<< "incorrect value for last_msg_.states[56].mesid.sat, expected 0, is "
<< last_msg_.states[56].mesid.sat;
EXPECT_EQ(last_msg_.states[57].cn0, 0)
<< "incorrect value for last_msg_.states[57].cn0, expected 0, is "
<< last_msg_.states[57].cn0;
EXPECT_EQ(last_msg_.states[57].mesid.code, 0)
<< "incorrect value for last_msg_.states[57].mesid.code, expected 0, is "
<< last_msg_.states[57].mesid.code;
EXPECT_EQ(last_msg_.states[57].mesid.sat, 0)
<< "incorrect value for last_msg_.states[57].mesid.sat, expected 0, is "
<< last_msg_.states[57].mesid.sat;
EXPECT_EQ(last_msg_.states[58].cn0, 0)
<< "incorrect value for last_msg_.states[58].cn0, expected 0, is "
<< last_msg_.states[58].cn0;
EXPECT_EQ(last_msg_.states[58].mesid.code, 0)
<< "incorrect value for last_msg_.states[58].mesid.code, expected 0, is "
<< last_msg_.states[58].mesid.code;
EXPECT_EQ(last_msg_.states[58].mesid.sat, 0)
<< "incorrect value for last_msg_.states[58].mesid.sat, expected 0, is "
<< last_msg_.states[58].mesid.sat;
EXPECT_EQ(last_msg_.states[59].cn0, 0)
<< "incorrect value for last_msg_.states[59].cn0, expected 0, is "
<< last_msg_.states[59].cn0;
EXPECT_EQ(last_msg_.states[59].mesid.code, 0)
<< "incorrect value for last_msg_.states[59].mesid.code, expected 0, is "
<< last_msg_.states[59].mesid.code;
EXPECT_EQ(last_msg_.states[59].mesid.sat, 0)
<< "incorrect value for last_msg_.states[59].mesid.sat, expected 0, is "
<< last_msg_.states[59].mesid.sat;
EXPECT_EQ(last_msg_.states[60].cn0, 0)
<< "incorrect value for last_msg_.states[60].cn0, expected 0, is "
<< last_msg_.states[60].cn0;
EXPECT_EQ(last_msg_.states[60].mesid.code, 0)
<< "incorrect value for last_msg_.states[60].mesid.code, expected 0, is "
<< last_msg_.states[60].mesid.code;
EXPECT_EQ(last_msg_.states[60].mesid.sat, 0)
<< "incorrect value for last_msg_.states[60].mesid.sat, expected 0, is "
<< last_msg_.states[60].mesid.sat;
EXPECT_EQ(last_msg_.states[61].cn0, 0)
<< "incorrect value for last_msg_.states[61].cn0, expected 0, is "
<< last_msg_.states[61].cn0;
EXPECT_EQ(last_msg_.states[61].mesid.code, 0)
<< "incorrect value for last_msg_.states[61].mesid.code, expected 0, is "
<< last_msg_.states[61].mesid.code;
EXPECT_EQ(last_msg_.states[61].mesid.sat, 0)
<< "incorrect value for last_msg_.states[61].mesid.sat, expected 0, is "
<< last_msg_.states[61].mesid.sat;
EXPECT_EQ(last_msg_.states[62].cn0, 0)
<< "incorrect value for last_msg_.states[62].cn0, expected 0, is "
<< last_msg_.states[62].cn0;
EXPECT_EQ(last_msg_.states[62].mesid.code, 0)
<< "incorrect value for last_msg_.states[62].mesid.code, expected 0, is "
<< last_msg_.states[62].mesid.code;
EXPECT_EQ(last_msg_.states[62].mesid.sat, 0)
<< "incorrect value for last_msg_.states[62].mesid.sat, expected 0, is "
<< last_msg_.states[62].mesid.sat;
EXPECT_EQ(last_msg_.states[63].cn0, 203)
<< "incorrect value for last_msg_.states[63].cn0, expected 203, is "
<< last_msg_.states[63].cn0;
EXPECT_EQ(last_msg_.states[63].mesid.code, 14)
<< "incorrect value for last_msg_.states[63].mesid.code, expected 14, is "
<< last_msg_.states[63].mesid.code;
EXPECT_EQ(last_msg_.states[63].mesid.sat, 36)
<< "incorrect value for last_msg_.states[63].mesid.sat, expected 36, is "
<< last_msg_.states[63].mesid.sat;
EXPECT_EQ(last_msg_.states[64].cn0, 0)
<< "incorrect value for last_msg_.states[64].cn0, expected 0, is "
<< last_msg_.states[64].cn0;
EXPECT_EQ(last_msg_.states[64].mesid.code, 0)
<< "incorrect value for last_msg_.states[64].mesid.code, expected 0, is "
<< last_msg_.states[64].mesid.code;
EXPECT_EQ(last_msg_.states[64].mesid.sat, 0)
<< "incorrect value for last_msg_.states[64].mesid.sat, expected 0, is "
<< last_msg_.states[64].mesid.sat;
EXPECT_EQ(last_msg_.states[65].cn0, 158)
<< "incorrect value for last_msg_.states[65].cn0, expected 158, is "
<< last_msg_.states[65].cn0;
EXPECT_EQ(last_msg_.states[65].mesid.code, 14)
<< "incorrect value for last_msg_.states[65].mesid.code, expected 14, is "
<< last_msg_.states[65].mesid.code;
EXPECT_EQ(last_msg_.states[65].mesid.sat, 5)
<< "incorrect value for last_msg_.states[65].mesid.sat, expected 5, is "
<< last_msg_.states[65].mesid.sat;
EXPECT_EQ(last_msg_.states[66].cn0, 194)
<< "incorrect value for last_msg_.states[66].cn0, expected 194, is "
<< last_msg_.states[66].cn0;
EXPECT_EQ(last_msg_.states[66].mesid.code, 14)
<< "incorrect value for last_msg_.states[66].mesid.code, expected 14, is "
<< last_msg_.states[66].mesid.code;
EXPECT_EQ(last_msg_.states[66].mesid.sat, 4)
<< "incorrect value for last_msg_.states[66].mesid.sat, expected 4, is "
<< last_msg_.states[66].mesid.sat;
EXPECT_EQ(last_msg_.states[67].cn0, 192)
<< "incorrect value for last_msg_.states[67].cn0, expected 192, is "
<< last_msg_.states[67].cn0;
EXPECT_EQ(last_msg_.states[67].mesid.code, 14)
<< "incorrect value for last_msg_.states[67].mesid.code, expected 14, is "
<< last_msg_.states[67].mesid.code;
EXPECT_EQ(last_msg_.states[67].mesid.sat, 11)
<< "incorrect value for last_msg_.states[67].mesid.sat, expected 11, is "
<< last_msg_.states[67].mesid.sat;
EXPECT_EQ(last_msg_.states[68].cn0, 207)
<< "incorrect value for last_msg_.states[68].cn0, expected 207, is "
<< last_msg_.states[68].cn0;
EXPECT_EQ(last_msg_.states[68].mesid.code, 14)
<< "incorrect value for last_msg_.states[68].mesid.code, expected 14, is "
<< last_msg_.states[68].mesid.code;
EXPECT_EQ(last_msg_.states[68].mesid.sat, 9)
<< "incorrect value for last_msg_.states[68].mesid.sat, expected 9, is "
<< last_msg_.states[68].mesid.sat;
EXPECT_EQ(last_msg_.states[69].cn0, 0)
<< "incorrect value for last_msg_.states[69].cn0, expected 0, is "
<< last_msg_.states[69].cn0;
EXPECT_EQ(last_msg_.states[69].mesid.code, 0)
<< "incorrect value for last_msg_.states[69].mesid.code, expected 0, is "
<< last_msg_.states[69].mesid.code;
EXPECT_EQ(last_msg_.states[69].mesid.sat, 0)
<< "incorrect value for last_msg_.states[69].mesid.sat, expected 0, is "
<< last_msg_.states[69].mesid.sat;
EXPECT_EQ(last_msg_.states[70].cn0, 0)
<< "incorrect value for last_msg_.states[70].cn0, expected 0, is "
<< last_msg_.states[70].cn0;
EXPECT_EQ(last_msg_.states[70].mesid.code, 0)
<< "incorrect value for last_msg_.states[70].mesid.code, expected 0, is "
<< last_msg_.states[70].mesid.code;
EXPECT_EQ(last_msg_.states[70].mesid.sat, 0)
<< "incorrect value for last_msg_.states[70].mesid.sat, expected 0, is "
<< last_msg_.states[70].mesid.sat;
EXPECT_EQ(last_msg_.states[71].cn0, 0)
<< "incorrect value for last_msg_.states[71].cn0, expected 0, is "
<< last_msg_.states[71].cn0;
EXPECT_EQ(last_msg_.states[71].mesid.code, 0)
<< "incorrect value for last_msg_.states[71].mesid.code, expected 0, is "
<< last_msg_.states[71].mesid.code;
EXPECT_EQ(last_msg_.states[71].mesid.sat, 0)
<< "incorrect value for last_msg_.states[71].mesid.sat, expected 0, is "
<< last_msg_.states[71].mesid.sat;
EXPECT_EQ(last_msg_.states[72].cn0, 218)
<< "incorrect value for last_msg_.states[72].cn0, expected 218, is "
<< last_msg_.states[72].cn0;
EXPECT_EQ(last_msg_.states[72].mesid.code, 20)
<< "incorrect value for last_msg_.states[72].mesid.code, expected 20, is "
<< last_msg_.states[72].mesid.code;
EXPECT_EQ(last_msg_.states[72].mesid.sat, 9)
<< "incorrect value for last_msg_.states[72].mesid.sat, expected 9, is "
<< last_msg_.states[72].mesid.sat;
EXPECT_EQ(last_msg_.states[73].cn0, 176)
<< "incorrect value for last_msg_.states[73].cn0, expected 176, is "
<< last_msg_.states[73].cn0;
EXPECT_EQ(last_msg_.states[73].mesid.code, 20)
<< "incorrect value for last_msg_.states[73].mesid.code, expected 20, is "
<< last_msg_.states[73].mesid.code;
EXPECT_EQ(last_msg_.states[73].mesid.sat, 5)
<< "incorrect value for last_msg_.states[73].mesid.sat, expected 5, is "
<< last_msg_.states[73].mesid.sat;
EXPECT_EQ(last_msg_.states[74].cn0, 217)
<< "incorrect value for last_msg_.states[74].cn0, expected 217, is "
<< last_msg_.states[74].cn0;
EXPECT_EQ(last_msg_.states[74].mesid.code, 20)
<< "incorrect value for last_msg_.states[74].mesid.code, expected 20, is "
<< last_msg_.states[74].mesid.code;
EXPECT_EQ(last_msg_.states[74].mesid.sat, 36)
<< "incorrect value for last_msg_.states[74].mesid.sat, expected 36, is "
<< last_msg_.states[74].mesid.sat;
EXPECT_EQ(last_msg_.states[75].cn0, 200)
<< "incorrect value for last_msg_.states[75].cn0, expected 200, is "
<< last_msg_.states[75].cn0;
EXPECT_EQ(last_msg_.states[75].mesid.code, 20)
<< "incorrect value for last_msg_.states[75].mesid.code, expected 20, is "
<< last_msg_.states[75].mesid.code;
EXPECT_EQ(last_msg_.states[75].mesid.sat, 11)
<< "incorrect value for last_msg_.states[75].mesid.sat, expected 11, is "
<< last_msg_.states[75].mesid.sat;
EXPECT_EQ(last_msg_.states[76].cn0, 205)
<< "incorrect value for last_msg_.states[76].cn0, expected 205, is "
<< last_msg_.states[76].cn0;
EXPECT_EQ(last_msg_.states[76].mesid.code, 20)
<< "incorrect value for last_msg_.states[76].mesid.code, expected 20, is "
<< last_msg_.states[76].mesid.code;
EXPECT_EQ(last_msg_.states[76].mesid.sat, 4)
<< "incorrect value for last_msg_.states[76].mesid.sat, expected 4, is "
<< last_msg_.states[76].mesid.sat;
EXPECT_EQ(last_msg_.states[77].cn0, 0)
<< "incorrect value for last_msg_.states[77].cn0, expected 0, is "
<< last_msg_.states[77].cn0;
EXPECT_EQ(last_msg_.states[77].mesid.code, 0)
<< "incorrect value for last_msg_.states[77].mesid.code, expected 0, is "
<< last_msg_.states[77].mesid.code;
EXPECT_EQ(last_msg_.states[77].mesid.sat, 0)
<< "incorrect value for last_msg_.states[77].mesid.sat, expected 0, is "
<< last_msg_.states[77].mesid.sat;
EXPECT_EQ(last_msg_.states[78].cn0, 0)
<< "incorrect value for last_msg_.states[78].cn0, expected 0, is "
<< last_msg_.states[78].cn0;
EXPECT_EQ(last_msg_.states[78].mesid.code, 0)
<< "incorrect value for last_msg_.states[78].mesid.code, expected 0, is "
<< last_msg_.states[78].mesid.code;
EXPECT_EQ(last_msg_.states[78].mesid.sat, 0)
<< "incorrect value for last_msg_.states[78].mesid.sat, expected 0, is "
<< last_msg_.states[78].mesid.sat;
}
| 44.838287 | 80 | 0.666673 |
302a65d5a1b2de8810875e5cf049bac9efdda89e | 1,680 | cpp | C++ | S3DWrapper10/Commands/DsSetShaderWithIfaces11_0.cpp | bo3b/iZ3D | ced8b3a4b0a152d0177f2e94008918efc76935d5 | [
"MIT"
] | 27 | 2020-11-12T19:24:54.000Z | 2022-03-27T23:10:45.000Z | S3DWrapper10/Commands/DsSetShaderWithIfaces11_0.cpp | bo3b/iZ3D | ced8b3a4b0a152d0177f2e94008918efc76935d5 | [
"MIT"
] | 2 | 2020-11-02T06:30:39.000Z | 2022-02-23T18:39:55.000Z | S3DWrapper10/Commands/DsSetShaderWithIfaces11_0.cpp | bo3b/iZ3D | ced8b3a4b0a152d0177f2e94008918efc76935d5 | [
"MIT"
] | 3 | 2021-08-16T00:21:08.000Z | 2022-02-23T19:19:36.000Z | #include "stdafx.h"
#include "DsSetShaderWithIfaces11_0.h"
#include "..\Streamer\CodeGenerator.h"
#include "D3DDeviceWrapper.h"
#include "ShaderWrapper.h"
namespace Commands
{
void DsSetShaderWithIfaces11_0::UpdateDeviceState( D3DDeviceWrapper *pWrapper, D3DDeviceState* pState )
{
pState->DS.m_Shader = this;
pState->DS.m_IsStereoShader = false;
if (hShader_.pDrvPrivate)
{
ShaderWrapper* pDSWrp = NULL;
InitWrapper(hShader_, pDSWrp);
if ( pDSWrp->IsMatrixFounded() )
pState->DS.m_IsStereoShader = true;
}
}
void DsSetShaderWithIfaces11_0::Execute( D3DDeviceWrapper *pWrapper )
{
BEFORE_EXECUTE(this);
pWrapper->OriginalDeviceFuncs11.pfnDsSetShaderWithIfaces( pWrapper->hDevice, GET_SHADER_HANDLE(hShader_),
NumClassInstances_, GetPointerToVector(pIfaces_), GetPointerToVector(pPointerData_) );
AFTER_EXECUTE(this);
}
bool DsSetShaderWithIfaces11_0::WriteToFile( D3DDeviceWrapper *pWrapper ) const
{
return WriteToFileEx(pWrapper, "DsSetShaderWithIfaces11_0");
}
}
VOID ( APIENTRY DsSetShaderWithIfaces11_0 )( D3D10DDI_HDEVICE hDevice, D3D10DDI_HSHADER hShader,
UINT NumClassInstances, const UINT* pIfaces, const D3D11DDIARG_POINTERDATA* pPointerData )
{
_ASSERT(D3D10_GET_WRAPPER()->GetD3DVersion() >= TD3DVersion_11_0);
#ifndef EXECUTE_IMMEDIATELY_G1
Commands::DsSetShaderWithIfaces11_0* command = new Commands::DsSetShaderWithIfaces11_0(hShader,
NumClassInstances, pIfaces, pPointerData);
D3D10_GET_WRAPPER()->AddCommand(command);
#else
{
THREAD_GUARD_D3D10();
D3D11_GET_ORIG().pfnDsSetShaderWithIfaces( D3D10_DEVICE, GET_SHADER_HANDLE( hShader ),
NumClassInstances, pIfaces, pPointerData );
}
#endif
} | 31.698113 | 107 | 0.780952 |
302aac1280b7be982666485af5edd0c478eac7cd | 57,052 | cpp | C++ | frameworks/compile/slang/slang_rs_object_ref_count.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2022-01-07T01:53:19.000Z | 2022-01-07T01:53:19.000Z | frameworks/compile/slang/slang_rs_object_ref_count.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | null | null | null | frameworks/compile/slang/slang_rs_object_ref_count.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2020-02-28T02:48:42.000Z | 2020-02-28T02:48:42.000Z | /*
* Copyright 2010, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "slang_rs_object_ref_count.h"
#include <list>
#include "clang/AST/DeclGroup.h"
#include "clang/AST/Expr.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtVisitor.h"
#include "slang_assert.h"
#include "slang_rs.h"
#include "slang_rs_ast_replace.h"
#include "slang_rs_export_type.h"
namespace slang {
clang::FunctionDecl *RSObjectRefCount::
RSSetObjectFD[RSExportPrimitiveType::LastRSObjectType -
RSExportPrimitiveType::FirstRSObjectType + 1];
clang::FunctionDecl *RSObjectRefCount::
RSClearObjectFD[RSExportPrimitiveType::LastRSObjectType -
RSExportPrimitiveType::FirstRSObjectType + 1];
void RSObjectRefCount::GetRSRefCountingFunctions(clang::ASTContext &C) {
for (unsigned i = 0;
i < (sizeof(RSClearObjectFD) / sizeof(clang::FunctionDecl*));
i++) {
RSSetObjectFD[i] = NULL;
RSClearObjectFD[i] = NULL;
}
clang::TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
for (clang::DeclContext::decl_iterator I = TUDecl->decls_begin(),
E = TUDecl->decls_end(); I != E; I++) {
if ((I->getKind() >= clang::Decl::firstFunction) &&
(I->getKind() <= clang::Decl::lastFunction)) {
clang::FunctionDecl *FD = static_cast<clang::FunctionDecl*>(*I);
// points to RSSetObjectFD or RSClearObjectFD
clang::FunctionDecl **RSObjectFD;
if (FD->getName() == "rsSetObject") {
slangAssert((FD->getNumParams() == 2) &&
"Invalid rsSetObject function prototype (# params)");
RSObjectFD = RSSetObjectFD;
} else if (FD->getName() == "rsClearObject") {
slangAssert((FD->getNumParams() == 1) &&
"Invalid rsClearObject function prototype (# params)");
RSObjectFD = RSClearObjectFD;
} else {
continue;
}
const clang::ParmVarDecl *PVD = FD->getParamDecl(0);
clang::QualType PVT = PVD->getOriginalType();
// The first parameter must be a pointer like rs_allocation*
slangAssert(PVT->isPointerType() &&
"Invalid rs{Set,Clear}Object function prototype (pointer param)");
// The rs object type passed to the FD
clang::QualType RST = PVT->getPointeeType();
RSExportPrimitiveType::DataType DT =
RSExportPrimitiveType::GetRSSpecificType(RST.getTypePtr());
slangAssert(RSExportPrimitiveType::IsRSObjectType(DT)
&& "must be RS object type");
RSObjectFD[(DT - RSExportPrimitiveType::FirstRSObjectType)] = FD;
}
}
}
namespace {
// This function constructs a new CompoundStmt from the input StmtList.
static clang::CompoundStmt* BuildCompoundStmt(clang::ASTContext &C,
std::list<clang::Stmt*> &StmtList, clang::SourceLocation Loc) {
unsigned NewStmtCount = StmtList.size();
unsigned CompoundStmtCount = 0;
clang::Stmt **CompoundStmtList;
CompoundStmtList = new clang::Stmt*[NewStmtCount];
std::list<clang::Stmt*>::const_iterator I = StmtList.begin();
std::list<clang::Stmt*>::const_iterator E = StmtList.end();
for ( ; I != E; I++) {
CompoundStmtList[CompoundStmtCount++] = *I;
}
slangAssert(CompoundStmtCount == NewStmtCount);
clang::CompoundStmt *CS =
new(C) clang::CompoundStmt(C,
llvm::makeArrayRef(CompoundStmtList,
CompoundStmtCount),
Loc,
Loc);
delete [] CompoundStmtList;
return CS;
}
static void AppendAfterStmt(clang::ASTContext &C,
clang::CompoundStmt *CS,
clang::Stmt *S,
std::list<clang::Stmt*> &StmtList) {
slangAssert(CS);
clang::CompoundStmt::body_iterator bI = CS->body_begin();
clang::CompoundStmt::body_iterator bE = CS->body_end();
clang::Stmt **UpdatedStmtList =
new clang::Stmt*[CS->size() + StmtList.size()];
unsigned UpdatedStmtCount = 0;
unsigned Once = 0;
for ( ; bI != bE; bI++) {
if (!S && ((*bI)->getStmtClass() == clang::Stmt::ReturnStmtClass)) {
// If we come across a return here, we don't have anything we can
// reasonably replace. We should have already inserted our destructor
// code in the proper spot, so we just clean up and return.
delete [] UpdatedStmtList;
return;
}
UpdatedStmtList[UpdatedStmtCount++] = *bI;
if ((*bI == S) && !Once) {
Once++;
std::list<clang::Stmt*>::const_iterator I = StmtList.begin();
std::list<clang::Stmt*>::const_iterator E = StmtList.end();
for ( ; I != E; I++) {
UpdatedStmtList[UpdatedStmtCount++] = *I;
}
}
}
slangAssert(Once <= 1);
// When S is NULL, we are appending to the end of the CompoundStmt.
if (!S) {
slangAssert(Once == 0);
std::list<clang::Stmt*>::const_iterator I = StmtList.begin();
std::list<clang::Stmt*>::const_iterator E = StmtList.end();
for ( ; I != E; I++) {
UpdatedStmtList[UpdatedStmtCount++] = *I;
}
}
CS->setStmts(C, UpdatedStmtList, UpdatedStmtCount);
delete [] UpdatedStmtList;
return;
}
// This class visits a compound statement and inserts DtorStmt
// in proper locations. This includes inserting it before any
// return statement in any sub-block, at the end of the logical enclosing
// scope (compound statement), and/or before any break/continue statement that
// would resume outside the declared scope. We will not handle the case for
// goto statements that leave a local scope.
//
// To accomplish these goals, it collects a list of sub-Stmt's that
// correspond to scope exit points. It then uses an RSASTReplace visitor to
// transform the AST, inserting appropriate destructors before each of those
// sub-Stmt's (and also before the exit of the outermost containing Stmt for
// the scope).
class DestructorVisitor : public clang::StmtVisitor<DestructorVisitor> {
private:
clang::ASTContext &mCtx;
// The loop depth of the currently visited node.
int mLoopDepth;
// The switch statement depth of the currently visited node.
// Note that this is tracked separately from the loop depth because
// SwitchStmt-contained ContinueStmt's should have destructors for the
// corresponding loop scope.
int mSwitchDepth;
// The outermost statement block that we are currently visiting.
// This should always be a CompoundStmt.
clang::Stmt *mOuterStmt;
// The destructor to execute for this scope/variable.
clang::Stmt* mDtorStmt;
// The stack of statements which should be replaced by a compound statement
// containing the new destructor call followed by the original Stmt.
std::stack<clang::Stmt*> mReplaceStmtStack;
// The source location for the variable declaration that we are trying to
// insert destructors for. Note that InsertDestructors() will not generate
// destructor calls for source locations that occur lexically before this
// location.
clang::SourceLocation mVarLoc;
public:
DestructorVisitor(clang::ASTContext &C,
clang::Stmt* OuterStmt,
clang::Stmt* DtorStmt,
clang::SourceLocation VarLoc);
// This code walks the collected list of Stmts to replace and actually does
// the replacement. It also finishes up by appending the destructor to the
// current outermost CompoundStmt.
void InsertDestructors() {
clang::Stmt *S = NULL;
clang::SourceManager &SM = mCtx.getSourceManager();
std::list<clang::Stmt *> StmtList;
StmtList.push_back(mDtorStmt);
while (!mReplaceStmtStack.empty()) {
S = mReplaceStmtStack.top();
mReplaceStmtStack.pop();
// Skip all source locations that occur before the variable's
// declaration, since it won't have been initialized yet.
if (SM.isBeforeInTranslationUnit(S->getLocStart(), mVarLoc)) {
continue;
}
StmtList.push_back(S);
clang::CompoundStmt *CS =
BuildCompoundStmt(mCtx, StmtList, S->getLocEnd());
StmtList.pop_back();
RSASTReplace R(mCtx);
R.ReplaceStmt(mOuterStmt, S, CS);
}
clang::CompoundStmt *CS =
llvm::dyn_cast<clang::CompoundStmt>(mOuterStmt);
slangAssert(CS);
AppendAfterStmt(mCtx, CS, NULL, StmtList);
}
void VisitStmt(clang::Stmt *S);
void VisitCompoundStmt(clang::CompoundStmt *CS);
void VisitBreakStmt(clang::BreakStmt *BS);
void VisitCaseStmt(clang::CaseStmt *CS);
void VisitContinueStmt(clang::ContinueStmt *CS);
void VisitDefaultStmt(clang::DefaultStmt *DS);
void VisitDoStmt(clang::DoStmt *DS);
void VisitForStmt(clang::ForStmt *FS);
void VisitIfStmt(clang::IfStmt *IS);
void VisitReturnStmt(clang::ReturnStmt *RS);
void VisitSwitchCase(clang::SwitchCase *SC);
void VisitSwitchStmt(clang::SwitchStmt *SS);
void VisitWhileStmt(clang::WhileStmt *WS);
};
DestructorVisitor::DestructorVisitor(clang::ASTContext &C,
clang::Stmt *OuterStmt,
clang::Stmt *DtorStmt,
clang::SourceLocation VarLoc)
: mCtx(C),
mLoopDepth(0),
mSwitchDepth(0),
mOuterStmt(OuterStmt),
mDtorStmt(DtorStmt),
mVarLoc(VarLoc) {
return;
}
void DestructorVisitor::VisitStmt(clang::Stmt *S) {
for (clang::Stmt::child_iterator I = S->child_begin(), E = S->child_end();
I != E;
I++) {
if (clang::Stmt *Child = *I) {
Visit(Child);
}
}
return;
}
void DestructorVisitor::VisitCompoundStmt(clang::CompoundStmt *CS) {
VisitStmt(CS);
return;
}
void DestructorVisitor::VisitBreakStmt(clang::BreakStmt *BS) {
VisitStmt(BS);
if ((mLoopDepth == 0) && (mSwitchDepth == 0)) {
mReplaceStmtStack.push(BS);
}
return;
}
void DestructorVisitor::VisitCaseStmt(clang::CaseStmt *CS) {
VisitStmt(CS);
return;
}
void DestructorVisitor::VisitContinueStmt(clang::ContinueStmt *CS) {
VisitStmt(CS);
if (mLoopDepth == 0) {
// Switch statements can have nested continues.
mReplaceStmtStack.push(CS);
}
return;
}
void DestructorVisitor::VisitDefaultStmt(clang::DefaultStmt *DS) {
VisitStmt(DS);
return;
}
void DestructorVisitor::VisitDoStmt(clang::DoStmt *DS) {
mLoopDepth++;
VisitStmt(DS);
mLoopDepth--;
return;
}
void DestructorVisitor::VisitForStmt(clang::ForStmt *FS) {
mLoopDepth++;
VisitStmt(FS);
mLoopDepth--;
return;
}
void DestructorVisitor::VisitIfStmt(clang::IfStmt *IS) {
VisitStmt(IS);
return;
}
void DestructorVisitor::VisitReturnStmt(clang::ReturnStmt *RS) {
mReplaceStmtStack.push(RS);
return;
}
void DestructorVisitor::VisitSwitchCase(clang::SwitchCase *SC) {
slangAssert(false && "Both case and default have specialized handlers");
VisitStmt(SC);
return;
}
void DestructorVisitor::VisitSwitchStmt(clang::SwitchStmt *SS) {
mSwitchDepth++;
VisitStmt(SS);
mSwitchDepth--;
return;
}
void DestructorVisitor::VisitWhileStmt(clang::WhileStmt *WS) {
mLoopDepth++;
VisitStmt(WS);
mLoopDepth--;
return;
}
clang::Expr *ClearSingleRSObject(clang::ASTContext &C,
clang::Expr *RefRSVar,
clang::SourceLocation Loc) {
slangAssert(RefRSVar);
const clang::Type *T = RefRSVar->getType().getTypePtr();
slangAssert(!T->isArrayType() &&
"Should not be destroying arrays with this function");
clang::FunctionDecl *ClearObjectFD = RSObjectRefCount::GetRSClearObjectFD(T);
slangAssert((ClearObjectFD != NULL) &&
"rsClearObject doesn't cover all RS object types");
clang::QualType ClearObjectFDType = ClearObjectFD->getType();
clang::QualType ClearObjectFDArgType =
ClearObjectFD->getParamDecl(0)->getOriginalType();
// Example destructor for "rs_font localFont;"
//
// (CallExpr 'void'
// (ImplicitCastExpr 'void (*)(rs_font *)' <FunctionToPointerDecay>
// (DeclRefExpr 'void (rs_font *)' FunctionDecl='rsClearObject'))
// (UnaryOperator 'rs_font *' prefix '&'
// (DeclRefExpr 'rs_font':'rs_font' Var='localFont')))
// Get address of targeted RS object
clang::Expr *AddrRefRSVar =
new(C) clang::UnaryOperator(RefRSVar,
clang::UO_AddrOf,
ClearObjectFDArgType,
clang::VK_RValue,
clang::OK_Ordinary,
Loc);
clang::Expr *RefRSClearObjectFD =
clang::DeclRefExpr::Create(C,
clang::NestedNameSpecifierLoc(),
clang::SourceLocation(),
ClearObjectFD,
false,
ClearObjectFD->getLocation(),
ClearObjectFDType,
clang::VK_RValue,
NULL);
clang::Expr *RSClearObjectFP =
clang::ImplicitCastExpr::Create(C,
C.getPointerType(ClearObjectFDType),
clang::CK_FunctionToPointerDecay,
RefRSClearObjectFD,
NULL,
clang::VK_RValue);
llvm::SmallVector<clang::Expr*, 1> ArgList;
ArgList.push_back(AddrRefRSVar);
clang::CallExpr *RSClearObjectCall =
new(C) clang::CallExpr(C,
RSClearObjectFP,
ArgList,
ClearObjectFD->getCallResultType(),
clang::VK_RValue,
Loc);
return RSClearObjectCall;
}
static int ArrayDim(const clang::Type *T) {
if (!T || !T->isArrayType()) {
return 0;
}
const clang::ConstantArrayType *CAT =
static_cast<const clang::ConstantArrayType *>(T);
return static_cast<int>(CAT->getSize().getSExtValue());
}
static clang::Stmt *ClearStructRSObject(
clang::ASTContext &C,
clang::DeclContext *DC,
clang::Expr *RefRSStruct,
clang::SourceLocation StartLoc,
clang::SourceLocation Loc);
static clang::Stmt *ClearArrayRSObject(
clang::ASTContext &C,
clang::DeclContext *DC,
clang::Expr *RefRSArr,
clang::SourceLocation StartLoc,
clang::SourceLocation Loc) {
const clang::Type *BaseType = RefRSArr->getType().getTypePtr();
slangAssert(BaseType->isArrayType());
int NumArrayElements = ArrayDim(BaseType);
// Actually extract out the base RS object type for use later
BaseType = BaseType->getArrayElementTypeNoTypeQual();
clang::Stmt *StmtArray[2] = {NULL};
int StmtCtr = 0;
if (NumArrayElements <= 0) {
return NULL;
}
// Example destructor loop for "rs_font fontArr[10];"
//
// (CompoundStmt
// (DeclStmt "int rsIntIter")
// (ForStmt
// (BinaryOperator 'int' '='
// (DeclRefExpr 'int' Var='rsIntIter')
// (IntegerLiteral 'int' 0))
// (BinaryOperator 'int' '<'
// (DeclRefExpr 'int' Var='rsIntIter')
// (IntegerLiteral 'int' 10)
// NULL << CondVar >>
// (UnaryOperator 'int' postfix '++'
// (DeclRefExpr 'int' Var='rsIntIter'))
// (CallExpr 'void'
// (ImplicitCastExpr 'void (*)(rs_font *)' <FunctionToPointerDecay>
// (DeclRefExpr 'void (rs_font *)' FunctionDecl='rsClearObject'))
// (UnaryOperator 'rs_font *' prefix '&'
// (ArraySubscriptExpr 'rs_font':'rs_font'
// (ImplicitCastExpr 'rs_font *' <ArrayToPointerDecay>
// (DeclRefExpr 'rs_font [10]' Var='fontArr'))
// (DeclRefExpr 'int' Var='rsIntIter')))))))
// Create helper variable for iterating through elements
clang::IdentifierInfo& II = C.Idents.get("rsIntIter");
clang::VarDecl *IIVD =
clang::VarDecl::Create(C,
DC,
StartLoc,
Loc,
&II,
C.IntTy,
C.getTrivialTypeSourceInfo(C.IntTy),
clang::SC_None);
clang::Decl *IID = (clang::Decl *)IIVD;
clang::DeclGroupRef DGR = clang::DeclGroupRef::Create(C, &IID, 1);
StmtArray[StmtCtr++] = new(C) clang::DeclStmt(DGR, Loc, Loc);
// Form the actual destructor loop
// for (Init; Cond; Inc)
// RSClearObjectCall;
// Init -> "rsIntIter = 0"
clang::DeclRefExpr *RefrsIntIter =
clang::DeclRefExpr::Create(C,
clang::NestedNameSpecifierLoc(),
clang::SourceLocation(),
IIVD,
false,
Loc,
C.IntTy,
clang::VK_RValue,
NULL);
clang::Expr *Int0 = clang::IntegerLiteral::Create(C,
llvm::APInt(C.getTypeSize(C.IntTy), 0), C.IntTy, Loc);
clang::BinaryOperator *Init =
new(C) clang::BinaryOperator(RefrsIntIter,
Int0,
clang::BO_Assign,
C.IntTy,
clang::VK_RValue,
clang::OK_Ordinary,
Loc,
/* fpContractable */false);
// Cond -> "rsIntIter < NumArrayElements"
clang::Expr *NumArrayElementsExpr = clang::IntegerLiteral::Create(C,
llvm::APInt(C.getTypeSize(C.IntTy), NumArrayElements), C.IntTy, Loc);
clang::BinaryOperator *Cond =
new(C) clang::BinaryOperator(RefrsIntIter,
NumArrayElementsExpr,
clang::BO_LT,
C.IntTy,
clang::VK_RValue,
clang::OK_Ordinary,
Loc,
/* fpContractable */false);
// Inc -> "rsIntIter++"
clang::UnaryOperator *Inc =
new(C) clang::UnaryOperator(RefrsIntIter,
clang::UO_PostInc,
C.IntTy,
clang::VK_RValue,
clang::OK_Ordinary,
Loc);
// Body -> "rsClearObject(&VD[rsIntIter]);"
// Destructor loop operates on individual array elements
clang::Expr *RefRSArrPtr =
clang::ImplicitCastExpr::Create(C,
C.getPointerType(BaseType->getCanonicalTypeInternal()),
clang::CK_ArrayToPointerDecay,
RefRSArr,
NULL,
clang::VK_RValue);
clang::Expr *RefRSArrPtrSubscript =
new(C) clang::ArraySubscriptExpr(RefRSArrPtr,
RefrsIntIter,
BaseType->getCanonicalTypeInternal(),
clang::VK_RValue,
clang::OK_Ordinary,
Loc);
RSExportPrimitiveType::DataType DT =
RSExportPrimitiveType::GetRSSpecificType(BaseType);
clang::Stmt *RSClearObjectCall = NULL;
if (BaseType->isArrayType()) {
RSClearObjectCall =
ClearArrayRSObject(C, DC, RefRSArrPtrSubscript, StartLoc, Loc);
} else if (DT == RSExportPrimitiveType::DataTypeUnknown) {
RSClearObjectCall =
ClearStructRSObject(C, DC, RefRSArrPtrSubscript, StartLoc, Loc);
} else {
RSClearObjectCall = ClearSingleRSObject(C, RefRSArrPtrSubscript, Loc);
}
clang::ForStmt *DestructorLoop =
new(C) clang::ForStmt(C,
Init,
Cond,
NULL, // no condVar
Inc,
RSClearObjectCall,
Loc,
Loc,
Loc);
StmtArray[StmtCtr++] = DestructorLoop;
slangAssert(StmtCtr == 2);
clang::CompoundStmt *CS =
new(C) clang::CompoundStmt(C, StmtArray, Loc, Loc);
return CS;
}
static unsigned CountRSObjectTypes(clang::ASTContext &C,
const clang::Type *T,
clang::SourceLocation Loc) {
slangAssert(T);
unsigned RSObjectCount = 0;
if (T->isArrayType()) {
return CountRSObjectTypes(C, T->getArrayElementTypeNoTypeQual(), Loc);
}
RSExportPrimitiveType::DataType DT =
RSExportPrimitiveType::GetRSSpecificType(T);
if (DT != RSExportPrimitiveType::DataTypeUnknown) {
return (RSExportPrimitiveType::IsRSObjectType(DT) ? 1 : 0);
}
if (T->isUnionType()) {
clang::RecordDecl *RD = T->getAsUnionType()->getDecl();
RD = RD->getDefinition();
for (clang::RecordDecl::field_iterator FI = RD->field_begin(),
FE = RD->field_end();
FI != FE;
FI++) {
const clang::FieldDecl *FD = *FI;
const clang::Type *FT = RSExportType::GetTypeOfDecl(FD);
if (CountRSObjectTypes(C, FT, Loc)) {
slangAssert(false && "can't have unions with RS object types!");
return 0;
}
}
}
if (!T->isStructureType()) {
return 0;
}
clang::RecordDecl *RD = T->getAsStructureType()->getDecl();
RD = RD->getDefinition();
for (clang::RecordDecl::field_iterator FI = RD->field_begin(),
FE = RD->field_end();
FI != FE;
FI++) {
const clang::FieldDecl *FD = *FI;
const clang::Type *FT = RSExportType::GetTypeOfDecl(FD);
if (CountRSObjectTypes(C, FT, Loc)) {
// Sub-structs should only count once (as should arrays, etc.)
RSObjectCount++;
}
}
return RSObjectCount;
}
static clang::Stmt *ClearStructRSObject(
clang::ASTContext &C,
clang::DeclContext *DC,
clang::Expr *RefRSStruct,
clang::SourceLocation StartLoc,
clang::SourceLocation Loc) {
const clang::Type *BaseType = RefRSStruct->getType().getTypePtr();
slangAssert(!BaseType->isArrayType());
// Structs should show up as unknown primitive types
slangAssert(RSExportPrimitiveType::GetRSSpecificType(BaseType) ==
RSExportPrimitiveType::DataTypeUnknown);
unsigned FieldsToDestroy = CountRSObjectTypes(C, BaseType, Loc);
unsigned StmtCount = 0;
clang::Stmt **StmtArray = new clang::Stmt*[FieldsToDestroy];
for (unsigned i = 0; i < FieldsToDestroy; i++) {
StmtArray[i] = NULL;
}
// Populate StmtArray by creating a destructor for each RS object field
clang::RecordDecl *RD = BaseType->getAsStructureType()->getDecl();
RD = RD->getDefinition();
for (clang::RecordDecl::field_iterator FI = RD->field_begin(),
FE = RD->field_end();
FI != FE;
FI++) {
// We just look through all field declarations to see if we find a
// declaration for an RS object type (or an array of one).
bool IsArrayType = false;
clang::FieldDecl *FD = *FI;
const clang::Type *FT = RSExportType::GetTypeOfDecl(FD);
const clang::Type *OrigType = FT;
while (FT && FT->isArrayType()) {
FT = FT->getArrayElementTypeNoTypeQual();
IsArrayType = true;
}
if (RSExportPrimitiveType::IsRSObjectType(FT)) {
clang::DeclAccessPair FoundDecl =
clang::DeclAccessPair::make(FD, clang::AS_none);
clang::MemberExpr *RSObjectMember =
clang::MemberExpr::Create(C,
RefRSStruct,
false,
clang::NestedNameSpecifierLoc(),
clang::SourceLocation(),
FD,
FoundDecl,
clang::DeclarationNameInfo(),
NULL,
OrigType->getCanonicalTypeInternal(),
clang::VK_RValue,
clang::OK_Ordinary);
slangAssert(StmtCount < FieldsToDestroy);
if (IsArrayType) {
StmtArray[StmtCount++] = ClearArrayRSObject(C,
DC,
RSObjectMember,
StartLoc,
Loc);
} else {
StmtArray[StmtCount++] = ClearSingleRSObject(C,
RSObjectMember,
Loc);
}
} else if (FT->isStructureType() && CountRSObjectTypes(C, FT, Loc)) {
// In this case, we have a nested struct. We may not end up filling all
// of the spaces in StmtArray (sub-structs should handle themselves
// with separate compound statements).
clang::DeclAccessPair FoundDecl =
clang::DeclAccessPair::make(FD, clang::AS_none);
clang::MemberExpr *RSObjectMember =
clang::MemberExpr::Create(C,
RefRSStruct,
false,
clang::NestedNameSpecifierLoc(),
clang::SourceLocation(),
FD,
FoundDecl,
clang::DeclarationNameInfo(),
NULL,
OrigType->getCanonicalTypeInternal(),
clang::VK_RValue,
clang::OK_Ordinary);
if (IsArrayType) {
StmtArray[StmtCount++] = ClearArrayRSObject(C,
DC,
RSObjectMember,
StartLoc,
Loc);
} else {
StmtArray[StmtCount++] = ClearStructRSObject(C,
DC,
RSObjectMember,
StartLoc,
Loc);
}
}
}
slangAssert(StmtCount > 0);
clang::CompoundStmt *CS =
new(C) clang::CompoundStmt(C,
llvm::makeArrayRef(StmtArray, StmtCount),
Loc,
Loc);
delete [] StmtArray;
return CS;
}
static clang::Stmt *CreateSingleRSSetObject(clang::ASTContext &C,
clang::Expr *DstExpr,
clang::Expr *SrcExpr,
clang::SourceLocation StartLoc,
clang::SourceLocation Loc) {
const clang::Type *T = DstExpr->getType().getTypePtr();
clang::FunctionDecl *SetObjectFD = RSObjectRefCount::GetRSSetObjectFD(T);
slangAssert((SetObjectFD != NULL) &&
"rsSetObject doesn't cover all RS object types");
clang::QualType SetObjectFDType = SetObjectFD->getType();
clang::QualType SetObjectFDArgType[2];
SetObjectFDArgType[0] = SetObjectFD->getParamDecl(0)->getOriginalType();
SetObjectFDArgType[1] = SetObjectFD->getParamDecl(1)->getOriginalType();
clang::Expr *RefRSSetObjectFD =
clang::DeclRefExpr::Create(C,
clang::NestedNameSpecifierLoc(),
clang::SourceLocation(),
SetObjectFD,
false,
Loc,
SetObjectFDType,
clang::VK_RValue,
NULL);
clang::Expr *RSSetObjectFP =
clang::ImplicitCastExpr::Create(C,
C.getPointerType(SetObjectFDType),
clang::CK_FunctionToPointerDecay,
RefRSSetObjectFD,
NULL,
clang::VK_RValue);
llvm::SmallVector<clang::Expr*, 2> ArgList;
ArgList.push_back(new(C) clang::UnaryOperator(DstExpr,
clang::UO_AddrOf,
SetObjectFDArgType[0],
clang::VK_RValue,
clang::OK_Ordinary,
Loc));
ArgList.push_back(SrcExpr);
clang::CallExpr *RSSetObjectCall =
new(C) clang::CallExpr(C,
RSSetObjectFP,
ArgList,
SetObjectFD->getCallResultType(),
clang::VK_RValue,
Loc);
return RSSetObjectCall;
}
static clang::Stmt *CreateStructRSSetObject(clang::ASTContext &C,
clang::Expr *LHS,
clang::Expr *RHS,
clang::SourceLocation StartLoc,
clang::SourceLocation Loc);
/*static clang::Stmt *CreateArrayRSSetObject(clang::ASTContext &C,
clang::Expr *DstArr,
clang::Expr *SrcArr,
clang::SourceLocation StartLoc,
clang::SourceLocation Loc) {
clang::DeclContext *DC = NULL;
const clang::Type *BaseType = DstArr->getType().getTypePtr();
slangAssert(BaseType->isArrayType());
int NumArrayElements = ArrayDim(BaseType);
// Actually extract out the base RS object type for use later
BaseType = BaseType->getArrayElementTypeNoTypeQual();
clang::Stmt *StmtArray[2] = {NULL};
int StmtCtr = 0;
if (NumArrayElements <= 0) {
return NULL;
}
// Create helper variable for iterating through elements
clang::IdentifierInfo& II = C.Idents.get("rsIntIter");
clang::VarDecl *IIVD =
clang::VarDecl::Create(C,
DC,
StartLoc,
Loc,
&II,
C.IntTy,
C.getTrivialTypeSourceInfo(C.IntTy),
clang::SC_None,
clang::SC_None);
clang::Decl *IID = (clang::Decl *)IIVD;
clang::DeclGroupRef DGR = clang::DeclGroupRef::Create(C, &IID, 1);
StmtArray[StmtCtr++] = new(C) clang::DeclStmt(DGR, Loc, Loc);
// Form the actual loop
// for (Init; Cond; Inc)
// RSSetObjectCall;
// Init -> "rsIntIter = 0"
clang::DeclRefExpr *RefrsIntIter =
clang::DeclRefExpr::Create(C,
clang::NestedNameSpecifierLoc(),
IIVD,
Loc,
C.IntTy,
clang::VK_RValue,
NULL);
clang::Expr *Int0 = clang::IntegerLiteral::Create(C,
llvm::APInt(C.getTypeSize(C.IntTy), 0), C.IntTy, Loc);
clang::BinaryOperator *Init =
new(C) clang::BinaryOperator(RefrsIntIter,
Int0,
clang::BO_Assign,
C.IntTy,
clang::VK_RValue,
clang::OK_Ordinary,
Loc);
// Cond -> "rsIntIter < NumArrayElements"
clang::Expr *NumArrayElementsExpr = clang::IntegerLiteral::Create(C,
llvm::APInt(C.getTypeSize(C.IntTy), NumArrayElements), C.IntTy, Loc);
clang::BinaryOperator *Cond =
new(C) clang::BinaryOperator(RefrsIntIter,
NumArrayElementsExpr,
clang::BO_LT,
C.IntTy,
clang::VK_RValue,
clang::OK_Ordinary,
Loc);
// Inc -> "rsIntIter++"
clang::UnaryOperator *Inc =
new(C) clang::UnaryOperator(RefrsIntIter,
clang::UO_PostInc,
C.IntTy,
clang::VK_RValue,
clang::OK_Ordinary,
Loc);
// Body -> "rsSetObject(&Dst[rsIntIter], Src[rsIntIter]);"
// Loop operates on individual array elements
clang::Expr *DstArrPtr =
clang::ImplicitCastExpr::Create(C,
C.getPointerType(BaseType->getCanonicalTypeInternal()),
clang::CK_ArrayToPointerDecay,
DstArr,
NULL,
clang::VK_RValue);
clang::Expr *DstArrPtrSubscript =
new(C) clang::ArraySubscriptExpr(DstArrPtr,
RefrsIntIter,
BaseType->getCanonicalTypeInternal(),
clang::VK_RValue,
clang::OK_Ordinary,
Loc);
clang::Expr *SrcArrPtr =
clang::ImplicitCastExpr::Create(C,
C.getPointerType(BaseType->getCanonicalTypeInternal()),
clang::CK_ArrayToPointerDecay,
SrcArr,
NULL,
clang::VK_RValue);
clang::Expr *SrcArrPtrSubscript =
new(C) clang::ArraySubscriptExpr(SrcArrPtr,
RefrsIntIter,
BaseType->getCanonicalTypeInternal(),
clang::VK_RValue,
clang::OK_Ordinary,
Loc);
RSExportPrimitiveType::DataType DT =
RSExportPrimitiveType::GetRSSpecificType(BaseType);
clang::Stmt *RSSetObjectCall = NULL;
if (BaseType->isArrayType()) {
RSSetObjectCall = CreateArrayRSSetObject(C, DstArrPtrSubscript,
SrcArrPtrSubscript,
StartLoc, Loc);
} else if (DT == RSExportPrimitiveType::DataTypeUnknown) {
RSSetObjectCall = CreateStructRSSetObject(C, DstArrPtrSubscript,
SrcArrPtrSubscript,
StartLoc, Loc);
} else {
RSSetObjectCall = CreateSingleRSSetObject(C, DstArrPtrSubscript,
SrcArrPtrSubscript,
StartLoc, Loc);
}
clang::ForStmt *DestructorLoop =
new(C) clang::ForStmt(C,
Init,
Cond,
NULL, // no condVar
Inc,
RSSetObjectCall,
Loc,
Loc,
Loc);
StmtArray[StmtCtr++] = DestructorLoop;
slangAssert(StmtCtr == 2);
clang::CompoundStmt *CS =
new(C) clang::CompoundStmt(C, StmtArray, StmtCtr, Loc, Loc);
return CS;
} */
static clang::Stmt *CreateStructRSSetObject(clang::ASTContext &C,
clang::Expr *LHS,
clang::Expr *RHS,
clang::SourceLocation StartLoc,
clang::SourceLocation Loc) {
clang::QualType QT = LHS->getType();
const clang::Type *T = QT.getTypePtr();
slangAssert(T->isStructureType());
slangAssert(!RSExportPrimitiveType::IsRSObjectType(T));
// Keep an extra slot for the original copy (memcpy)
unsigned FieldsToSet = CountRSObjectTypes(C, T, Loc) + 1;
unsigned StmtCount = 0;
clang::Stmt **StmtArray = new clang::Stmt*[FieldsToSet];
for (unsigned i = 0; i < FieldsToSet; i++) {
StmtArray[i] = NULL;
}
clang::RecordDecl *RD = T->getAsStructureType()->getDecl();
RD = RD->getDefinition();
for (clang::RecordDecl::field_iterator FI = RD->field_begin(),
FE = RD->field_end();
FI != FE;
FI++) {
bool IsArrayType = false;
clang::FieldDecl *FD = *FI;
const clang::Type *FT = RSExportType::GetTypeOfDecl(FD);
const clang::Type *OrigType = FT;
if (!CountRSObjectTypes(C, FT, Loc)) {
// Skip to next if we don't have any viable RS object types
continue;
}
clang::DeclAccessPair FoundDecl =
clang::DeclAccessPair::make(FD, clang::AS_none);
clang::MemberExpr *DstMember =
clang::MemberExpr::Create(C,
LHS,
false,
clang::NestedNameSpecifierLoc(),
clang::SourceLocation(),
FD,
FoundDecl,
clang::DeclarationNameInfo(),
NULL,
OrigType->getCanonicalTypeInternal(),
clang::VK_RValue,
clang::OK_Ordinary);
clang::MemberExpr *SrcMember =
clang::MemberExpr::Create(C,
RHS,
false,
clang::NestedNameSpecifierLoc(),
clang::SourceLocation(),
FD,
FoundDecl,
clang::DeclarationNameInfo(),
NULL,
OrigType->getCanonicalTypeInternal(),
clang::VK_RValue,
clang::OK_Ordinary);
if (FT->isArrayType()) {
FT = FT->getArrayElementTypeNoTypeQual();
IsArrayType = true;
}
RSExportPrimitiveType::DataType DT =
RSExportPrimitiveType::GetRSSpecificType(FT);
if (IsArrayType) {
clang::DiagnosticsEngine &DiagEngine = C.getDiagnostics();
DiagEngine.Report(
clang::FullSourceLoc(Loc, C.getSourceManager()),
DiagEngine.getCustomDiagID(
clang::DiagnosticsEngine::Error,
"Arrays of RS object types within structures cannot be copied"));
// TODO(srhines): Support setting arrays of RS objects
// StmtArray[StmtCount++] =
// CreateArrayRSSetObject(C, DstMember, SrcMember, StartLoc, Loc);
} else if (DT == RSExportPrimitiveType::DataTypeUnknown) {
StmtArray[StmtCount++] =
CreateStructRSSetObject(C, DstMember, SrcMember, StartLoc, Loc);
} else if (RSExportPrimitiveType::IsRSObjectType(DT)) {
StmtArray[StmtCount++] =
CreateSingleRSSetObject(C, DstMember, SrcMember, StartLoc, Loc);
} else {
slangAssert(false);
}
}
slangAssert(StmtCount > 0 && StmtCount < FieldsToSet);
// We still need to actually do the overall struct copy. For simplicity,
// we just do a straight-up assignment (which will still preserve all
// the proper RS object reference counts).
clang::BinaryOperator *CopyStruct =
new(C) clang::BinaryOperator(LHS, RHS, clang::BO_Assign, QT,
clang::VK_RValue, clang::OK_Ordinary, Loc,
/* fpContractable */false);
StmtArray[StmtCount++] = CopyStruct;
clang::CompoundStmt *CS =
new(C) clang::CompoundStmt(C, llvm::makeArrayRef(StmtArray, StmtCount),
Loc, Loc);
delete [] StmtArray;
return CS;
}
} // namespace
void RSObjectRefCount::Scope::ReplaceRSObjectAssignment(
clang::BinaryOperator *AS) {
clang::QualType QT = AS->getType();
clang::ASTContext &C = RSObjectRefCount::GetRSSetObjectFD(
RSExportPrimitiveType::DataTypeRSFont)->getASTContext();
clang::SourceLocation Loc = AS->getExprLoc();
clang::SourceLocation StartLoc = AS->getLHS()->getExprLoc();
clang::Stmt *UpdatedStmt = NULL;
if (!RSExportPrimitiveType::IsRSObjectType(QT.getTypePtr())) {
// By definition, this is a struct assignment if we get here
UpdatedStmt =
CreateStructRSSetObject(C, AS->getLHS(), AS->getRHS(), StartLoc, Loc);
} else {
UpdatedStmt =
CreateSingleRSSetObject(C, AS->getLHS(), AS->getRHS(), StartLoc, Loc);
}
RSASTReplace R(C);
R.ReplaceStmt(mCS, AS, UpdatedStmt);
return;
}
void RSObjectRefCount::Scope::AppendRSObjectInit(
clang::VarDecl *VD,
clang::DeclStmt *DS,
RSExportPrimitiveType::DataType DT,
clang::Expr *InitExpr) {
slangAssert(VD);
if (!InitExpr) {
return;
}
clang::ASTContext &C = RSObjectRefCount::GetRSSetObjectFD(
RSExportPrimitiveType::DataTypeRSFont)->getASTContext();
clang::SourceLocation Loc = RSObjectRefCount::GetRSSetObjectFD(
RSExportPrimitiveType::DataTypeRSFont)->getLocation();
clang::SourceLocation StartLoc = RSObjectRefCount::GetRSSetObjectFD(
RSExportPrimitiveType::DataTypeRSFont)->getInnerLocStart();
if (DT == RSExportPrimitiveType::DataTypeIsStruct) {
const clang::Type *T = RSExportType::GetTypeOfDecl(VD);
clang::DeclRefExpr *RefRSVar =
clang::DeclRefExpr::Create(C,
clang::NestedNameSpecifierLoc(),
clang::SourceLocation(),
VD,
false,
Loc,
T->getCanonicalTypeInternal(),
clang::VK_RValue,
NULL);
clang::Stmt *RSSetObjectOps =
CreateStructRSSetObject(C, RefRSVar, InitExpr, StartLoc, Loc);
std::list<clang::Stmt*> StmtList;
StmtList.push_back(RSSetObjectOps);
AppendAfterStmt(C, mCS, DS, StmtList);
return;
}
clang::FunctionDecl *SetObjectFD = RSObjectRefCount::GetRSSetObjectFD(DT);
slangAssert((SetObjectFD != NULL) &&
"rsSetObject doesn't cover all RS object types");
clang::QualType SetObjectFDType = SetObjectFD->getType();
clang::QualType SetObjectFDArgType[2];
SetObjectFDArgType[0] = SetObjectFD->getParamDecl(0)->getOriginalType();
SetObjectFDArgType[1] = SetObjectFD->getParamDecl(1)->getOriginalType();
clang::Expr *RefRSSetObjectFD =
clang::DeclRefExpr::Create(C,
clang::NestedNameSpecifierLoc(),
clang::SourceLocation(),
SetObjectFD,
false,
Loc,
SetObjectFDType,
clang::VK_RValue,
NULL);
clang::Expr *RSSetObjectFP =
clang::ImplicitCastExpr::Create(C,
C.getPointerType(SetObjectFDType),
clang::CK_FunctionToPointerDecay,
RefRSSetObjectFD,
NULL,
clang::VK_RValue);
const clang::Type *T = RSExportType::GetTypeOfDecl(VD);
clang::DeclRefExpr *RefRSVar =
clang::DeclRefExpr::Create(C,
clang::NestedNameSpecifierLoc(),
clang::SourceLocation(),
VD,
false,
Loc,
T->getCanonicalTypeInternal(),
clang::VK_RValue,
NULL);
llvm::SmallVector<clang::Expr*, 2> ArgList;
ArgList.push_back(new(C) clang::UnaryOperator(RefRSVar,
clang::UO_AddrOf,
SetObjectFDArgType[0],
clang::VK_RValue,
clang::OK_Ordinary,
Loc));
ArgList.push_back(InitExpr);
clang::CallExpr *RSSetObjectCall =
new(C) clang::CallExpr(C,
RSSetObjectFP,
ArgList,
SetObjectFD->getCallResultType(),
clang::VK_RValue,
Loc);
std::list<clang::Stmt*> StmtList;
StmtList.push_back(RSSetObjectCall);
AppendAfterStmt(C, mCS, DS, StmtList);
return;
}
void RSObjectRefCount::Scope::InsertLocalVarDestructors() {
for (std::list<clang::VarDecl*>::const_iterator I = mRSO.begin(),
E = mRSO.end();
I != E;
I++) {
clang::VarDecl *VD = *I;
clang::Stmt *RSClearObjectCall = ClearRSObject(VD, VD->getDeclContext());
if (RSClearObjectCall) {
DestructorVisitor DV((*mRSO.begin())->getASTContext(),
mCS,
RSClearObjectCall,
VD->getSourceRange().getBegin());
DV.Visit(mCS);
DV.InsertDestructors();
}
}
return;
}
clang::Stmt *RSObjectRefCount::Scope::ClearRSObject(
clang::VarDecl *VD,
clang::DeclContext *DC) {
slangAssert(VD);
clang::ASTContext &C = VD->getASTContext();
clang::SourceLocation Loc = VD->getLocation();
clang::SourceLocation StartLoc = VD->getInnerLocStart();
const clang::Type *T = RSExportType::GetTypeOfDecl(VD);
// Reference expr to target RS object variable
clang::DeclRefExpr *RefRSVar =
clang::DeclRefExpr::Create(C,
clang::NestedNameSpecifierLoc(),
clang::SourceLocation(),
VD,
false,
Loc,
T->getCanonicalTypeInternal(),
clang::VK_RValue,
NULL);
if (T->isArrayType()) {
return ClearArrayRSObject(C, DC, RefRSVar, StartLoc, Loc);
}
RSExportPrimitiveType::DataType DT =
RSExportPrimitiveType::GetRSSpecificType(T);
if (DT == RSExportPrimitiveType::DataTypeUnknown ||
DT == RSExportPrimitiveType::DataTypeIsStruct) {
return ClearStructRSObject(C, DC, RefRSVar, StartLoc, Loc);
}
slangAssert((RSExportPrimitiveType::IsRSObjectType(DT)) &&
"Should be RS object");
return ClearSingleRSObject(C, RefRSVar, Loc);
}
bool RSObjectRefCount::InitializeRSObject(clang::VarDecl *VD,
RSExportPrimitiveType::DataType *DT,
clang::Expr **InitExpr) {
slangAssert(VD && DT && InitExpr);
const clang::Type *T = RSExportType::GetTypeOfDecl(VD);
// Loop through array types to get to base type
while (T && T->isArrayType()) {
T = T->getArrayElementTypeNoTypeQual();
}
bool DataTypeIsStructWithRSObject = false;
*DT = RSExportPrimitiveType::GetRSSpecificType(T);
if (*DT == RSExportPrimitiveType::DataTypeUnknown) {
if (RSExportPrimitiveType::IsStructureTypeWithRSObject(T)) {
*DT = RSExportPrimitiveType::DataTypeIsStruct;
DataTypeIsStructWithRSObject = true;
} else {
return false;
}
}
bool DataTypeIsRSObject = false;
if (DataTypeIsStructWithRSObject) {
DataTypeIsRSObject = true;
} else {
DataTypeIsRSObject = RSExportPrimitiveType::IsRSObjectType(*DT);
}
*InitExpr = VD->getInit();
if (!DataTypeIsRSObject && *InitExpr) {
// If we already have an initializer for a matrix type, we are done.
return DataTypeIsRSObject;
}
clang::Expr *ZeroInitializer =
CreateZeroInitializerForRSSpecificType(*DT,
VD->getASTContext(),
VD->getLocation());
if (ZeroInitializer) {
ZeroInitializer->setType(T->getCanonicalTypeInternal());
VD->setInit(ZeroInitializer);
}
return DataTypeIsRSObject;
}
clang::Expr *RSObjectRefCount::CreateZeroInitializerForRSSpecificType(
RSExportPrimitiveType::DataType DT,
clang::ASTContext &C,
const clang::SourceLocation &Loc) {
clang::Expr *Res = NULL;
switch (DT) {
case RSExportPrimitiveType::DataTypeIsStruct:
case RSExportPrimitiveType::DataTypeRSElement:
case RSExportPrimitiveType::DataTypeRSType:
case RSExportPrimitiveType::DataTypeRSAllocation:
case RSExportPrimitiveType::DataTypeRSSampler:
case RSExportPrimitiveType::DataTypeRSScript:
case RSExportPrimitiveType::DataTypeRSMesh:
case RSExportPrimitiveType::DataTypeRSPath:
case RSExportPrimitiveType::DataTypeRSProgramFragment:
case RSExportPrimitiveType::DataTypeRSProgramVertex:
case RSExportPrimitiveType::DataTypeRSProgramRaster:
case RSExportPrimitiveType::DataTypeRSProgramStore:
case RSExportPrimitiveType::DataTypeRSFont: {
// (ImplicitCastExpr 'nullptr_t'
// (IntegerLiteral 0)))
llvm::APInt Zero(C.getTypeSize(C.IntTy), 0);
clang::Expr *Int0 = clang::IntegerLiteral::Create(C, Zero, C.IntTy, Loc);
clang::Expr *CastToNull =
clang::ImplicitCastExpr::Create(C,
C.NullPtrTy,
clang::CK_IntegralToPointer,
Int0,
NULL,
clang::VK_RValue);
llvm::SmallVector<clang::Expr*, 1>InitList;
InitList.push_back(CastToNull);
Res = new(C) clang::InitListExpr(C, Loc, InitList, Loc);
break;
}
case RSExportPrimitiveType::DataTypeRSMatrix2x2:
case RSExportPrimitiveType::DataTypeRSMatrix3x3:
case RSExportPrimitiveType::DataTypeRSMatrix4x4: {
// RS matrix is not completely an RS object. They hold data by themselves.
// (InitListExpr rs_matrix2x2
// (InitListExpr float[4]
// (FloatingLiteral 0)
// (FloatingLiteral 0)
// (FloatingLiteral 0)
// (FloatingLiteral 0)))
clang::QualType FloatTy = C.FloatTy;
// Constructor sets value to 0.0f by default
llvm::APFloat Val(C.getFloatTypeSemantics(FloatTy));
clang::FloatingLiteral *Float0Val =
clang::FloatingLiteral::Create(C,
Val,
/* isExact = */true,
FloatTy,
Loc);
unsigned N = 0;
if (DT == RSExportPrimitiveType::DataTypeRSMatrix2x2)
N = 2;
else if (DT == RSExportPrimitiveType::DataTypeRSMatrix3x3)
N = 3;
else if (DT == RSExportPrimitiveType::DataTypeRSMatrix4x4)
N = 4;
unsigned N_2 = N * N;
// Assume we are going to be allocating 16 elements, since 4x4 is max.
llvm::SmallVector<clang::Expr*, 16> InitVals;
for (unsigned i = 0; i < N_2; i++)
InitVals.push_back(Float0Val);
clang::Expr *InitExpr =
new(C) clang::InitListExpr(C, Loc, InitVals, Loc);
InitExpr->setType(C.getConstantArrayType(FloatTy,
llvm::APInt(32, N_2),
clang::ArrayType::Normal,
/* EltTypeQuals = */0));
llvm::SmallVector<clang::Expr*, 1> InitExprVec;
InitExprVec.push_back(InitExpr);
Res = new(C) clang::InitListExpr(C, Loc, InitExprVec, Loc);
break;
}
case RSExportPrimitiveType::DataTypeUnknown:
case RSExportPrimitiveType::DataTypeFloat16:
case RSExportPrimitiveType::DataTypeFloat32:
case RSExportPrimitiveType::DataTypeFloat64:
case RSExportPrimitiveType::DataTypeSigned8:
case RSExportPrimitiveType::DataTypeSigned16:
case RSExportPrimitiveType::DataTypeSigned32:
case RSExportPrimitiveType::DataTypeSigned64:
case RSExportPrimitiveType::DataTypeUnsigned8:
case RSExportPrimitiveType::DataTypeUnsigned16:
case RSExportPrimitiveType::DataTypeUnsigned32:
case RSExportPrimitiveType::DataTypeUnsigned64:
case RSExportPrimitiveType::DataTypeBoolean:
case RSExportPrimitiveType::DataTypeUnsigned565:
case RSExportPrimitiveType::DataTypeUnsigned5551:
case RSExportPrimitiveType::DataTypeUnsigned4444:
case RSExportPrimitiveType::DataTypeMax: {
slangAssert(false && "Not RS object type!");
}
// No default case will enable compiler detecting the missing cases
}
return Res;
}
void RSObjectRefCount::VisitDeclStmt(clang::DeclStmt *DS) {
for (clang::DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
I != E;
I++) {
clang::Decl *D = *I;
if (D->getKind() == clang::Decl::Var) {
clang::VarDecl *VD = static_cast<clang::VarDecl*>(D);
RSExportPrimitiveType::DataType DT =
RSExportPrimitiveType::DataTypeUnknown;
clang::Expr *InitExpr = NULL;
if (InitializeRSObject(VD, &DT, &InitExpr)) {
getCurrentScope()->addRSObject(VD);
getCurrentScope()->AppendRSObjectInit(VD, DS, DT, InitExpr);
}
}
}
return;
}
void RSObjectRefCount::VisitCompoundStmt(clang::CompoundStmt *CS) {
if (!CS->body_empty()) {
// Push a new scope
Scope *S = new Scope(CS);
mScopeStack.push(S);
VisitStmt(CS);
// Destroy the scope
slangAssert((getCurrentScope() == S) && "Corrupted scope stack!");
S->InsertLocalVarDestructors();
mScopeStack.pop();
delete S;
}
return;
}
void RSObjectRefCount::VisitBinAssign(clang::BinaryOperator *AS) {
clang::QualType QT = AS->getType();
if (CountRSObjectTypes(mCtx, QT.getTypePtr(), AS->getExprLoc())) {
getCurrentScope()->ReplaceRSObjectAssignment(AS);
}
return;
}
void RSObjectRefCount::VisitStmt(clang::Stmt *S) {
for (clang::Stmt::child_iterator I = S->child_begin(), E = S->child_end();
I != E;
I++) {
if (clang::Stmt *Child = *I) {
Visit(Child);
}
}
return;
}
// This function walks the list of global variables and (potentially) creates
// a single global static destructor function that properly decrements
// reference counts on the contained RS object types.
clang::FunctionDecl *RSObjectRefCount::CreateStaticGlobalDtor() {
Init();
clang::DeclContext *DC = mCtx.getTranslationUnitDecl();
clang::SourceLocation loc;
llvm::StringRef SR(".rs.dtor");
clang::IdentifierInfo &II = mCtx.Idents.get(SR);
clang::DeclarationName N(&II);
clang::FunctionProtoType::ExtProtoInfo EPI;
clang::QualType T = mCtx.getFunctionType(mCtx.VoidTy,
llvm::ArrayRef<clang::QualType>(),
EPI);
clang::FunctionDecl *FD = NULL;
// Generate rsClearObject() call chains for every global variable
// (whether static or extern).
std::list<clang::Stmt *> StmtList;
for (clang::DeclContext::decl_iterator I = DC->decls_begin(),
E = DC->decls_end(); I != E; I++) {
clang::VarDecl *VD = llvm::dyn_cast<clang::VarDecl>(*I);
if (VD) {
if (CountRSObjectTypes(mCtx, VD->getType().getTypePtr(), loc)) {
if (!FD) {
// Only create FD if we are going to use it.
FD = clang::FunctionDecl::Create(mCtx, DC, loc, loc, N, T, NULL,
clang::SC_None);
}
// Make sure to create any helpers within the function's DeclContext,
// not the one associated with the global translation unit.
clang::Stmt *RSClearObjectCall = Scope::ClearRSObject(VD, FD);
StmtList.push_back(RSClearObjectCall);
}
}
}
// Nothing needs to be destroyed, so don't emit a dtor.
if (StmtList.empty()) {
return NULL;
}
clang::CompoundStmt *CS = BuildCompoundStmt(mCtx, StmtList, loc);
FD->setBody(CS);
return FD;
}
} // namespace slang
| 36.200508 | 80 | 0.552864 |
302fe2d3f3f102b03543aea9ee36bd7b982fb4a3 | 8,462 | cpp | C++ | ConnectOptionDialog.cpp | hyo0913/MQTT-Client-with-QMQTT | d9974d755dcc4f16c1e89b426c45be3854bcdbb5 | [
"MIT"
] | 1 | 2021-02-10T08:56:12.000Z | 2021-02-10T08:56:12.000Z | ConnectOptionDialog.cpp | hyo0913/MQTT-Client-using-qmqtt | d9974d755dcc4f16c1e89b426c45be3854bcdbb5 | [
"MIT"
] | null | null | null | ConnectOptionDialog.cpp | hyo0913/MQTT-Client-using-qmqtt | d9974d755dcc4f16c1e89b426c45be3854bcdbb5 | [
"MIT"
] | null | null | null | #include "ConnectOptionDialog.h"
#include "ui_ConnectOptionDialog.h"
#include "QFileDialog"
#include "QApplication"
ConnectOptionDialog::ConnectOptionDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ConnectOptionDialog)
{
ui->setupUi(this);
connect(ui->checkBoxWillFlag, SIGNAL(toggled(bool)), this, SLOT(willFlagToggled(bool)));
willFlagToggled(false);
connect(ui->checkBoxUserNameFlag, SIGNAL(toggled(bool)), this, SLOT(userNameFlagToggled(bool)));
userNameFlagToggled(false);
connect(ui->checkBoxAutoReconnect, SIGNAL(toggled(bool)), this, SLOT(autoReconnectToggled(bool)));
autoReconnectToggled(false);
connect(ui->checkBoxSsl, SIGNAL(toggled(bool)), this, SLOT(useSslToggled(bool)));
useSslToggled(false);
connect(ui->toolButtonCertifiacte, SIGNAL(clicked(bool)), this, SLOT(btnCertificateClicked()));
connect(ui->toolButtonPrivateKey, SIGNAL(clicked(bool)), this, SLOT(btnPriavteKeyClicked()));
}
ConnectOptionDialog::~ConnectOptionDialog()
{
delete ui;
}
bool ConnectOptionDialog::needWebsocket() const
{
bool result = false;
if( ui->comboBoxNetwork->currentIndex() == 1 )
{
result = true;
}
return result;
}
quint32 ConnectOptionDialog::port() const
{
return ui->spinBoxPort->value();
}
bool ConnectOptionDialog::cleanSession() const
{
return ui->checkBoxCleanSession->isChecked();
}
bool ConnectOptionDialog::willFlag() const
{
return ui->checkBoxWillFlag->isChecked();
}
bool ConnectOptionDialog::willQosFlag() const
{
return ui->checkBoxWillQoS->isChecked();
}
const QString ConnectOptionDialog::willTopic() const
{
return ui->lineEditWillTopic->text();
}
const QByteArray ConnectOptionDialog::willMessage() const
{
return ui->lineEditWillMessage->text().toUtf8();
}
quint8 ConnectOptionDialog::willQoS() const
{
return static_cast<quint8>(ui->spinBoxWillQoS->value());
}
bool ConnectOptionDialog::willRetainFlag() const
{
return ui->checkBoxWillRetain->isChecked();
}
bool ConnectOptionDialog::userNameFlag() const
{
return ui->checkBoxUserNameFlag->isChecked();
}
const QString ConnectOptionDialog::userName() const
{
return ui->lineEditUserName->text();
}
bool ConnectOptionDialog::passwordFlag() const
{
return ui->checkBoxPasswordFlag->isChecked();
}
const QByteArray ConnectOptionDialog::password() const
{
return ui->lineEditPassword->text().toUtf8();
}
quint16 ConnectOptionDialog::keepAlive() const
{
return static_cast<quint16>(ui->spinBoxKeepAlive->value());
}
bool ConnectOptionDialog::autoReconnect() const
{
return ui->checkBoxAutoReconnect->isChecked();
}
int ConnectOptionDialog::autoReconnectInterval() const
{
return ui->spinBoxAutoReconnectInterval->value();
}
bool ConnectOptionDialog::useSsl() const
{
return ui->checkBoxSsl->isChecked();
}
QSslCertificate ConnectOptionDialog::certificate() const
{
// QSslCertificate result;
// QString certFileName = ui->lineEditCertifiacte->text();
// if( certFileName.isEmpty() ) return QSslCertificate();
// QFile file(certFileName);
// if( file.open(QIODevice::ReadOnly) )
// {
// QByteArray data = file.readAll();
// file.close();
// if( certFileName.contains(".pem") )
// {
// result = QSslCertificate(data, QSsl::Pem);
// }
// else if( certFileName.contains(".der") )
// {
// result = QSslCertificate(data, QSsl::Der);
// }
// }
// return result;
QList<QSslCertificate> lstCerts;
QString certFileName = ui->lineEditCertifiacte->text();
if( certFileName.isEmpty() ) return QSslCertificate();
lstCerts = QSslCertificate::fromPath(certFileName);
if( lstCerts.count() <= 0 ) return QSslCertificate();
return lstCerts.first();
}
QSslKey ConnectOptionDialog::privateKey() const
{
QSslKey result;
QString keyFileName = ui->lineEditPrivateKey->text();
if( keyFileName.isEmpty() ) return QSslKey();
QFile file(keyFileName);
if( file.open(QIODevice::ReadOnly) )
{
result = QSslKey(file.readAll(), QSsl::Rsa);
}
return result;
}
bool ConnectOptionDialog::ignoreSelfSigned() const
{
return ui->checkBoxIgnoreSelfSigned->isChecked();
}
void ConnectOptionDialog::setEditable(bool editable)
{
ui->labelNetwork->setEnabled(editable);
ui->comboBoxNetwork->setEnabled(editable);
ui->labelPort->setEnabled(editable);
ui->spinBoxPort->setEnabled(editable);
ui->checkBoxCleanSession->setEnabled(editable);
ui->checkBoxWillFlag->setEnabled(editable);
ui->labelWillTopic->setEnabled(editable);
ui->lineEditWillTopic->setEnabled(editable);
ui->labelWillMessage->setEnabled(editable);
ui->lineEditWillMessage->setEnabled(editable);
ui->checkBoxWillQoS->setEnabled(editable);
ui->spinBoxWillQoS->setEnabled(editable);
ui->checkBoxWillRetain->setEnabled(editable);
ui->checkBoxUserNameFlag->setEnabled(editable);
ui->lineEditUserName->setEnabled(editable);
ui->checkBoxPasswordFlag->setEnabled(editable);
ui->lineEditPassword->setEnabled(editable);
ui->labelKeepAlive->setEnabled(editable);
ui->spinBoxKeepAlive->setEnabled(editable);
ui->labelKeepAliveSec->setEnabled(editable);
ui->checkBoxAutoReconnect->setEnabled(editable);
ui->labelAutoReconnectInterval->setEnabled(editable);
ui->spinBoxAutoReconnectInterval->setEnabled(editable);
ui->labelAutoReconnectIntervalSec->setEnabled(editable);
ui->checkBoxSsl->setEnabled(editable);
ui->labelCertificate->setEnabled(editable);
ui->lineEditCertifiacte->setEnabled(editable);
ui->toolButtonCertifiacte->setEnabled(editable);
ui->labelPrivateKey->setEnabled(editable);
ui->lineEditPrivateKey->setEnabled(editable);
ui->toolButtonPrivateKey->setEnabled(editable);
ui->checkBoxIgnoreSelfSigned->setEnabled(editable);
if( editable )
{
willFlagToggled(ui->checkBoxWillFlag->isChecked());
userNameFlagToggled(ui->checkBoxUserNameFlag->isChecked());
autoReconnectToggled(ui->checkBoxAutoReconnect->isChecked());
useSslToggled(ui->checkBoxSsl->isChecked());
}
}
void ConnectOptionDialog::willFlagToggled(bool toggled)
{
if( toggled == false )
{
ui->checkBoxWillQoS->setChecked(false);
ui->checkBoxWillRetain->setChecked(false);
}
ui->labelWillTopic->setEnabled(toggled);
ui->labelWillMessage->setEnabled(toggled);
ui->lineEditWillTopic->setEnabled(toggled);
ui->lineEditWillMessage->setEnabled(toggled);
ui->checkBoxWillQoS->setEnabled(toggled);
ui->spinBoxWillQoS->setEnabled(toggled);
ui->checkBoxWillRetain->setEnabled(toggled);
}
void ConnectOptionDialog::userNameFlagToggled(bool toggled)
{
if( toggled == false )
{
ui->checkBoxPasswordFlag->setChecked(false);
}
ui->checkBoxPasswordFlag->setEnabled(toggled);
ui->lineEditPassword->setEnabled(toggled);
}
void ConnectOptionDialog::autoReconnectToggled(bool toggled)
{
ui->labelAutoReconnectInterval->setEnabled(toggled);
ui->spinBoxAutoReconnectInterval->setEnabled(toggled);
ui->labelAutoReconnectIntervalSec->setEnabled(toggled);
}
void ConnectOptionDialog::useSslToggled(bool toggled)
{
ui->labelCertificate->setEnabled(toggled);
ui->lineEditCertifiacte->setEnabled(toggled);
ui->toolButtonCertifiacte->setEnabled(toggled);
ui->labelPrivateKey->setEnabled(toggled);
ui->lineEditPrivateKey->setEnabled(toggled);
ui->toolButtonPrivateKey->setEnabled(toggled);
ui->checkBoxIgnoreSelfSigned->setEnabled(toggled);
}
void ConnectOptionDialog::btnCertificateClicked()
{
QFileDialog dialog(this, "Certificate", QApplication::applicationDirPath(), "Certificate (*.pem *.der)");
if( dialog.exec() )
{
ui->lineEditCertifiacte->setText(dialog.selectedFiles().first());
}
}
void ConnectOptionDialog::btnPriavteKeyClicked()
{
QFileDialog dialog(this, "Private Key", QApplication::applicationDirPath(), "Private Key (*.pem)");
if( dialog.exec() )
{
ui->lineEditPrivateKey->setText(dialog.selectedFiles().first());
}
}
| 28.979452 | 110 | 0.69109 |
3030085cec3c16ba6b029381746dd0a63baff54c | 1,446 | cc | C++ | test/config_test.cc | lilialexlee/kit | 94492e04832749fcdfb7f9fb8a778bb949d5e7d6 | [
"MIT"
] | 1 | 2015-09-22T15:33:30.000Z | 2015-09-22T15:33:30.000Z | test/config_test.cc | lilialexlee/kit | 94492e04832749fcdfb7f9fb8a778bb949d5e7d6 | [
"MIT"
] | null | null | null | test/config_test.cc | lilialexlee/kit | 94492e04832749fcdfb7f9fb8a778bb949d5e7d6 | [
"MIT"
] | null | null | null | /*
* config_test.cc
*
*/
#include "util/config.h"
#include <iostream>
int main() {
kit::Config config;
config.Init("./test/example_conf");
std::string str_value;
int ret = config.GetStr("str", &str_value);
if (ret == 0) {
std::cout << "get str: " << str_value << "\n";
} else {
std::cerr << "get str failed.\n";
}
std::vector<std::string> str_values;
ret = config.GetStrs("strs", &str_values);
if (ret == 0) {
std::cout << "get strs:";
for (size_t i = 0; i < str_values.size(); ++i) {
std::cout << " " << str_values[i];
}
std::cout << "\n";
} else {
std::cerr << "get strs failed.\n";
}
int int_value;
ret = config.GetInt("int", &int_value);
if (ret == 0) {
std::cout << "get int: " << int_value << "\n";
} else {
std::cerr << "get int failed.\n";
}
std::vector<int> int_values;
ret = config.GetInts("ints", &int_values);
if (ret == 0) {
std::cout << "get ints:";
for (size_t i = 0; i < int_values.size(); ++i) {
std::cout << " " << int_values[i];
}
std::cout << "\n";
} else {
std::cerr << "get ints failed.\n";
}
ret = config.GetStr("not_exist", &str_value);
if (ret == 0) {
std::cerr << "get not exist config.\n";
}
ret = config.GetStr("comments", &str_value);
if (ret == 0) {
std::cerr << "get not exist config.\n";
}
return 0;
}
| 21.909091 | 53 | 0.502766 |
30315f2c2da15598ac8a5ff4725bec76120052dd | 2,307 | hxx | C++ | src/tcl_iface/array.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | null | null | null | src/tcl_iface/array.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | null | null | null | src/tcl_iface/array.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | 1 | 2022-01-29T11:54:41.000Z | 2022-01-29T11:54:41.000Z | /**
* @file
* @author Jason Lingle
* @brief Makes C automatic/static arrays accessible to trusted Tcl.
*/
/*
* array.hxx
* Make C arrays accessible to trusted Tcl.
*
* Created on: 12.07.2010
* Author: jason
*/
#ifndef ARRAY_HXX_
#define ARRAY_HXX_
#include <stdexcept>
#include <exception>
#include "src/core/aobject.hxx"
/** Represents an automatically-allocated array of fixed
* size. Tcl can also create them, in which case the data
* is automatically deleted.
* Uses of this in the definition must always be C++-outgoing,
* immediate, and steal.
*/
template<typename T, unsigned S>
class StaticArray: public AObject {
T* data;
bool del;
public:
/** Tcl constructor */
StaticArray() : data(new T[S]), del(true) {}
/** Construct the array on the given array */
StaticArray(T* d) : data(d), del(false) {}
virtual ~StaticArray() { if (del) delete[] data; }
operator T*() { return data; }
/** Array read */
T at(unsigned i) {
if (i>=0 && i<S) return data[i];
throw std::range_error("Out of bounds");
}
/** Array set */
T set(unsigned i, T t) {
if (i>=0 && i<S) return data[i]=t;
throw std::range_error("Out of bounds");
}
/** Array size */
unsigned size() { return S; }
/** Equality is determined solely by comparing the pointers. */
bool eq(StaticArray<T,S>* other) { return data==other->data; }
};
/** Represents a dynamically-allocated array.
*
* The glue
* definition should ensure that Tcl always has control
* over this class. Tcl is responsible for knowing whether
* to delete the contents.
*
* The array does not keep track of allocation size.
* If Tcl "allocates" an array of size 0, a NULL array
* is actually created.
*/
template<typename T>
class DynArray: public AObject {
T* data;
public:
/** Constructs a DynArray on the given array */
DynArray(T* d) : data(d) {}
/** Allocates an array of the given size */
explicit DynArray(unsigned sz) : data(sz? new T[sz] : 0) {}
operator T*() { return data; }
T at(unsigned i) { return data[i]; } ///< Array read
T set(unsigned i, T t) { return data[i]=t; } ///< Array write
bool eq(DynArray<T>* other) { return other->data==data; } ///< Pointer equality
void del() { delete[] data; } ///< Deallocation
};
#endif /* ARRAY_HXX_ */
| 24.806452 | 81 | 0.647161 |
30351cdc1536feb813463363d184c60765f63aa0 | 799 | cpp | C++ | 20-Valid_Parentheses.cpp | elsdrium/LeetCode-practice | a3b1fa5dd200155a636d36cd570e2454f7194e10 | [
"MIT"
] | null | null | null | 20-Valid_Parentheses.cpp | elsdrium/LeetCode-practice | a3b1fa5dd200155a636d36cd570e2454f7194e10 | [
"MIT"
] | null | null | null | 20-Valid_Parentheses.cpp | elsdrium/LeetCode-practice | a3b1fa5dd200155a636d36cd570e2454f7194e10 | [
"MIT"
] | null | null | null | class Solution {
public:
bool isValid(string s) {
list<char> stack;
for( char c : s ) {
switch ( c ) {
case '(':
case '{':
case '[':
stack.push_back(c);
break;
case ')':
if ( stack.back() != '(' ) return false;
stack.pop_back();
break;
case '}':
if ( stack.back() != '{' ) return false;
stack.pop_back();
break;
case ']':
if ( stack.back() != '[' ) return false;
stack.pop_back();
break;
}
}
return stack.empty();
}
};
| 27.551724 | 60 | 0.307885 |
3037f5e0b45bf4e649a6f55f8b430cc7717b11be | 6,782 | cc | C++ | gnuradio-3.7.13.4/gr-atsc/lib/atsci_trellis_encoder.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | 1 | 2021-03-09T07:32:37.000Z | 2021-03-09T07:32:37.000Z | gnuradio-3.7.13.4/gr-atsc/lib/atsci_trellis_encoder.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | gnuradio-3.7.13.4/gr-atsc/lib/atsci_trellis_encoder.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | /* -*- c++ -*- */
/*
* Copyright 2002,2006 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio 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, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include <gnuradio/atsc/trellis_encoder_impl.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
static const int DIBITS_PER_BYTE = 4;
#define SEGOF(x) ( (x) / ((SEGMENT_SIZE+1) * DIBITS_PER_BYTE))
#define SYMOF(x) (((x) % ((SEGMENT_SIZE+1) * DIBITS_PER_BYTE))-4)
/* How many separate Trellis encoders / Viterbi decoders run in parallel */
static const int NCODERS = 12;
#define ENCODER_SEG_BUMP 4
/* A Segment sync symbol is an 8VSB +5,-5,-5,+5 sequence that occurs at
the start of each 207-byte segment (including field sync segments). */
#define DSEG_SYNC_SYM1 0x06 /* +5 */
#define DSEG_SYNC_SYM2 0x01 /* -5 */
#define DSEG_SYNC_SYM3 0x01 /* -5 */
#define DSEG_SYNC_SYM4 0x06 /* +5 */
/* Shift counts to bit numbers (high order, low order); 9x entries unused */
static const int bit1[8] = {1, 99, 3, 98, 5, 97, 7, 96};
static const int bit2[8] = {0, 99, 2, 98, 4, 97, 6, 96};
atsci_trellis_encoder::atsci_trellis_encoder ()
{
debug = false;
reset ();
}
atsci_trellis_encoder::~atsci_trellis_encoder ()
{
}
void
atsci_trellis_encoder::reset ()
{
for (int i = 0; i < NCODERS; i++)
enc[i].reset ();
}
void
atsci_trellis_encoder::encode (atsc_data_segment out[NCODERS],
const atsc_mpeg_packet_rs_encoded in[NCODERS])
{
unsigned char out_copy[OUTPUT_SIZE];
unsigned char in_copy[INPUT_SIZE];
assert (sizeof (in_copy) == sizeof (in[0].data) * NCODERS);
assert (sizeof (out_copy) == sizeof (out[0].data) * NCODERS);
// copy input into continguous temporary buffer
for (int i = 0; i < NCODERS; i++){
assert (in[i].pli.regular_seg_p ());
plinfo::sanity_check (in[i].pli);
memcpy (&in_copy[i * INPUT_SIZE/NCODERS],
&in[i].data[0],
ATSC_MPEG_RS_ENCODED_LENGTH * sizeof (in_copy[0]));
}
memset (out_copy, 0, sizeof (out_copy)); // FIXME, sanity check
// do the deed...
encode_helper (out_copy, in_copy);
// copy output from contiguous temp buffer into final output
for (int i = 0; i < NCODERS; i++){
memcpy (&out[i].data[0],
&out_copy[i * OUTPUT_SIZE/NCODERS],
ATSC_DATA_SEGMENT_LENGTH * sizeof (out_copy[0]));
// copy pipeline info
out[i].pli = in[i].pli;
plinfo::sanity_check (out[i].pli);
assert (out[i].pli.regular_seg_p ());
}
}
/*
* This code expects contiguous arrrays. Use it as is, it computes
* the correct answer. Maybe someday, when we've run out of better
* things to do, rework to avoid the copying in encode.
*/
void
atsci_trellis_encoder::encode_helper (unsigned char output[OUTPUT_SIZE],
const unsigned char input[INPUT_SIZE])
{
int i;
int encoder;
unsigned char trellis_buffer[NCODERS];
int trellis_wherefrom[NCODERS];
unsigned char *out, *next_out_seg;
int chunk;
int shift;
unsigned char dibit;
unsigned char symbol;
int skip_encoder_bump;
/* FIXME, we may want special processing here
for a flag byte to keep track of which part of the field we're in? */
encoder = NCODERS - ENCODER_SEG_BUMP;
skip_encoder_bump = 0;
out = output;
next_out_seg = out;
for (chunk = 0;
chunk < INPUT_SIZE;
chunk += NCODERS) {
/* Load a new chunk of bytes into the Trellis encoder buffers.
They get loaded in an order that depends on where we are in the
segment sync progress (sigh).
GRR! When the chunk reload happens at the same time as the
segment boundary, we should bump the encoder NOW for the reload,
rather than LATER during the bitshift transition!!! */
if (out >= next_out_seg) {
encoder = (encoder + ENCODER_SEG_BUMP) % NCODERS;
skip_encoder_bump = 1;
}
for (i = 0; i < NCODERS; i++) {
/* for debug */ trellis_wherefrom[encoder] = chunk+i;
trellis_buffer[encoder] = input [chunk+i];
encoder++;
if (encoder >= NCODERS) encoder = 0;
}
for (shift = 6; shift >= 0; shift -= 2) {
/* Segment boundaries happen to occur on some bitshift transitions. */
if (out >= next_out_seg) {
/* Segment transition. Output a data segment sync symbol, and
mess with the trellis encoder mux. */
*out++ = DSEG_SYNC_SYM1;
*out++ = DSEG_SYNC_SYM2;
*out++ = DSEG_SYNC_SYM3;
*out++ = DSEG_SYNC_SYM4;
if (debug) printf ("SYNC SYNC SYNC SYNC\n");
next_out_seg = out + (SEGMENT_SIZE * DIBITS_PER_BYTE);
if (!skip_encoder_bump)
encoder = (encoder + ENCODER_SEG_BUMP) % NCODERS;
skip_encoder_bump = 0;
}
/* Now run each of the 12 Trellis encoders to spit out 12 symbols.
Each encoder takes input from the same byte of the chunk, but the
outputs of the encoders come out in various orders.
NOPE -- this is false. The encoders take input from various
bytes of the chunk (which changes at segment sync time), AND
they also come out in various orders. You really do have to
keep separate track of: the input bytes, the encoders, and
the output bytes -- because they're all moving with respect to
each other!!! */
for (i = 0; i < NCODERS; i++) {
dibit = 0x03 & (trellis_buffer[encoder] >> shift);
if (debug)
printf ("Seg %ld Symb %3ld Trell %2d Byte %6d Bits %d-%d = dibit %d ",
(long) SEGOF(out-output), (long) SYMOF(out-output),
encoder, trellis_wherefrom[encoder],
bit1[shift], bit2[shift], dibit);
symbol = enc[encoder].encode (dibit);
*out++ = symbol;
encoder++; if (encoder >= NCODERS) encoder = 0;
if (debug) printf ("sym %d\n", symbol);
} /* Encoders */
} /* Bit shifts */
} /* Chunks */
/* Check up on ourselves */
#if 0
assertIntsEqual (0, (INPUT_SIZE * DIBITS_PER_BYTE) % NCODERS, "not %");
assertIntsEqual (OUTPUT_SIZE, out - output, "outptr");
assertIntsEqual (NCODERS - ENCODER_SEG_BUMP, encoder, "mux sync");
#else
assert (0 == (INPUT_SIZE * DIBITS_PER_BYTE) % NCODERS);
assert (OUTPUT_SIZE == out - output);
assert (NCODERS - ENCODER_SEG_BUMP == encoder);
#endif
}
| 32.449761 | 76 | 0.664406 |
303880210283d85be75660b6f91578dee964ab52 | 4,210 | cpp | C++ | 002_disparity_panorama.cpp | DreamVu/Code-Samples | 2fccd9e649fbe7d9895df7d799cb1ec33066d1c2 | [
"MIT"
] | null | null | null | 002_disparity_panorama.cpp | DreamVu/Code-Samples | 2fccd9e649fbe7d9895df7d799cb1ec33066d1c2 | [
"MIT"
] | null | null | null | 002_disparity_panorama.cpp | DreamVu/Code-Samples | 2fccd9e649fbe7d9895df7d799cb1ec33066d1c2 | [
"MIT"
] | null | null | null | /*
CODE SAMPLE # 002: Disparity panorama
This code will grab the basic stereo panoramas (left and right images) and ALSO the Disparity panorama, and all these 3 images are displayed in an opencv window
>>>>>> Compile this code using the following command....
g++ 002_disparity_panorama.cpp ../lib/libPAL.so `pkg-config --libs --cflags opencv` -g -o 002_disparity_panorama.out -I../include/ -lv4l2 -lpthread -std=c++11
>>>>>> Execute the binary file by typing the following command...
./002_disparity_panorama.out
>>>>>> KEYBOARD CONTROLS:
ESC key closes the window
Press v/V key to toggle the vertical flip of panorama
Press f/F to toggle filter rgb property.
Press d/D to toggle fast depth property
Press r/R to toggle near range property
*/
# include <stdio.h>
# include <opencv2/opencv.hpp>
# include <chrono>
# include <bits/stdc++.h>
# include "PAL.h"
using namespace cv;
using namespace std;
using namespace std::chrono;
int main(int argc, char *argv[])
{
namedWindow("PAL Disparity Panorama", WINDOW_NORMAL); // Create a window for display.
int width, height;
if (PAL::Init(width, height, -1) != PAL::SUCCESS) //Connect to the PAL camera
{
printf("Init failed\n");
return 1;
}
PAL::CameraProperties data;
PAL::Acknowledgement ack = PAL::LoadProperties("../Explorer/SavedPalProperties.txt", &data);
if(ack != PAL::SUCCESS)
{
printf("Error Loading settings\n");
}
PAL::CameraProperties prop;
unsigned int flag = PAL::MODE;
flag = flag | PAL::FD;
flag = flag | PAL::NR;
flag = flag | PAL::FILTER_SPOTS;
flag = flag | PAL::VERTICAL_FLIP;
prop.mode = PAL::Mode::FAST_DEPTH; // The other available option is PAL::Mode::HIGH_QUALITY_DEPTH
prop.fd = 1;
prop.nr = 0;
prop.filter_spots = 1;
prop.vertical_flip =0;
PAL::SetCameraProperties(&prop, &flag);
bool isDisparityNormalized = true;
//width and height are the dimensions of each panorama.
//Each of the panoramas are displayed at quarter their original resolution.
//Since the left+right+disparity are vertically stacked, the window height should be thrice the quarter-height
resizeWindow("PAL Disparity Panorama", width / 4, (height / 4) * 3);
int key = ' ';
printf("Press ESC to close the window\n");
printf("Press v/V key to toggle the vertical flip of panorama\n");
printf("Press f/F to toggle filter rgb property.\n");
printf("Press d/D to toggle fast depth property\n");
printf("Press r/R to toggle near range property\n");
size_t currentResolution = 0;
bool flip = false;
bool filter_spots = true;
bool nr = false;
bool fd = true;
//27 = esc key. Run the loop until the ESC key is pressed
while (key != 27)
{
PAL::Image left, right, depth, disparity;
PAL::GrabFrames(&left, &right, &depth);
Mat output;
//Convert PAL::Image to Mat
Mat l = Mat(left.rows, left.cols, CV_8UC3, left.Raw.u8_data);
Mat r = Mat(right.rows, right.cols, CV_8UC3, right.Raw.u8_data);
Mat d = Mat(depth.rows, depth.cols, CV_32FC1, depth.Raw.f32_data);
d.convertTo(d, CV_8UC1);
cvtColor(d, d, cv::COLOR_GRAY2BGR);
//Vertical concatenation of temp and disparity into the final output
vconcat(l, d, output);
//Display the final output image
imshow("PAL Disparity Panorama", output);
//Wait for the keypress - with a timeout of 1 ms
key = waitKey(1) & 255;
if (key == 'v' || key == 'V')
{
PAL::CameraProperties prop;
flip = !flip;
prop.vertical_flip = flip;
unsigned int flags = PAL::VERTICAL_FLIP;
PAL::SetCameraProperties(&prop, &flags);
}
if (key == 'f' || key == 'F')
{
PAL::CameraProperties prop;
filter_spots = !filter_spots;
prop.filter_spots = filter_spots;
unsigned int flags = PAL::FILTER_SPOTS;
PAL::SetCameraProperties(&prop, &flags);
}
if(key == 'd' || key == 'D')
{
PAL::CameraProperties prop;
fd = !fd;
prop.fd = fd;
unsigned int flags = PAL::FD;
PAL::SetCameraProperties(&prop, &flags);
}
if(key == 'r' || key == 'R')
{
PAL::CameraProperties prop;
nr = !nr;
prop.nr = nr;
unsigned int flags = PAL::NR;
PAL::SetCameraProperties(&prop, &flags);
}
}
printf("exiting the application\n");
PAL::Destroy();
return 0;
}
| 26.3125 | 162 | 0.676485 |
303cbece338cb8a60e1ccda8430c5e1b98e53dcb | 2,493 | cpp | C++ | src/Common/Instruction_test.cpp | skyzh/RISCV-Simulator | 8989a09c357a69b68612f653380d60816f5176c2 | [
"MIT"
] | 106 | 2019-07-04T12:20:25.000Z | 2022-03-20T10:50:52.000Z | src/Common/Instruction_test.cpp | qshan/RISCV-Simulator | 8989a09c357a69b68612f653380d60816f5176c2 | [
"MIT"
] | 2 | 2019-07-02T13:38:42.000Z | 2019-09-06T02:09:30.000Z | src/Common/Instruction_test.cpp | qshan/RISCV-Simulator | 8989a09c357a69b68612f653380d60816f5176c2 | [
"MIT"
] | 12 | 2020-01-02T05:41:28.000Z | 2022-03-10T11:57:46.000Z | //
// Created by Alex Chi on 2019-07-01.
//
#include "gtest/gtest.h"
#include "Instruction.hpp"
TEST(Instruction, CorrectSize) {
EXPECT_EQ(sizeof(Instruction), 4);
}
TEST(Instruction, InstructionR) {
// 10987654321098765432109876543210
InstructionR inst(0b10101010101010101010101010101010);
// 10987654321098765432109876543210
EXPECT_EQ(inst.opcode, 0b0101010);
EXPECT_EQ(inst.rd, 0b10101);
EXPECT_EQ(inst.rs1, 0b10101);
EXPECT_EQ(inst.rs2, 0b01010);
EXPECT_EQ(inst.funct3, 0b010);
}
TEST(Instruction, InstructionI) {
// 10987654321098765432109876543210
InstructionI inst(0b10101010101010101010101010101010);
// 10987654321098765432109876543210
EXPECT_EQ(inst.imm, 0b11111111111111111111101010101010);
EXPECT_EQ(inst.opcode, 0b0101010);
EXPECT_EQ(inst.rd, 0b10101);
EXPECT_EQ(inst.rs1, 0b10101);
EXPECT_EQ(inst.funct3, 0b010);
}
TEST(Instruction, InstructionS) {
// 10987654321098765432109876543210
InstructionS inst(0b10101010101010101010101010101010);
// 10987654321098765432109876543210
EXPECT_EQ(inst.imm, 0b11111111111111111111101010110101);
EXPECT_EQ(inst.opcode, 0b0101010);
EXPECT_EQ(inst.rs1, 0b10101);
EXPECT_EQ(inst.rs2, 0b01010);
EXPECT_EQ(inst.funct3, 0b010);
}
TEST(Instruction, InstructionB) {
// 10987654321098765432109876543210
InstructionB inst(0b10101010101010101010101010101010);
// 10987654321098765432109876543210
EXPECT_EQ(inst.imm, 0b11111111111111111111101010110100);
EXPECT_EQ(inst.opcode, 0b0101010);
EXPECT_EQ(inst.rs1, 0b10101);
EXPECT_EQ(inst.rs2, 0b01010);
EXPECT_EQ(inst.funct3, 0b010);
}
TEST(Instruction, InstructionU) {
// 10987654321098765432109876543210
InstructionU inst(0b10101010101010101010101010101010);
// 10987654321098765432109876543210
EXPECT_EQ(inst.imm, 0b10101010101010101010000000000000);
EXPECT_EQ(inst.opcode, 0b0101010);
EXPECT_EQ(inst.rd, 0b10101);
}
TEST(Instruction, InstructionJ) {
// 10987654321098765432109876543210
InstructionJ inst(0b10101010101010101010101010101010);
// 10987654321098765432109876543210
EXPECT_EQ(inst.imm, 0b11111111111110101010001010101010);
EXPECT_EQ(inst.opcode, 0b0101010);
EXPECT_EQ(inst.rd, 0b10101);
}
| 34.150685 | 60 | 0.69274 |
303fb3bc53beaf5ea5c43b46203287c27e904f92 | 13,179 | hpp | C++ | sources/RenderSystem/spShaderClass.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 14 | 2015-08-16T21:05:20.000Z | 2019-08-21T17:22:01.000Z | sources/RenderSystem/spShaderClass.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | null | null | null | sources/RenderSystem/spShaderClass.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 3 | 2020-02-15T09:17:41.000Z | 2020-05-21T14:10:40.000Z | /*
* Shader class header
*
* This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
* See "SoftPixelEngine.hpp" for license information.
*/
#ifndef __SP_SHADER_CLASS_H__
#define __SP_SHADER_CLASS_H__
#include "Base/spStandard.hpp"
#include "Base/spInputOutput.hpp"
#include "Base/spBaseObject.hpp"
#include "RenderSystem/spShaderConfigTypes.hpp"
namespace sp
{
namespace scene { class MaterialNode; }
namespace video
{
class Shader;
class ShaderResource;
class VertexFormat;
class ConstantBuffer;
/**
Build shader flags. This is used for the two static functions "ShaderClass::getShaderVersion" and "ShaderClass::build".
\since Version 3.2
*/
enum EBuildShaderFlags
{
SHADERBUILD_CG = 0x0002,
SHADERBUILD_GLSL = 0x0004,
SHADERBUILD_HLSL3 = 0x0008,
SHADERBUILD_HLSL5 = 0x0010,
SHADERBUILD_VERTEX = 0x0100,
SHADERBUILD_PIXEL = 0x0200,
SHADERBUILD_GEOMETRY = 0x0400,
SHADERBUILD_HULL = 0x0800,
SHADERBUILD_DOMAIN = 0x1000,
};
/**
C-pre-processor directives used for shading languages.
\todo Move this to a token parser/ lexer or something like that.
\since Version 3.3
*/
enum ECPPDirectives
{
CPPDIRECTIVE_NONE, //!< Invalid CPP directive.
CPPDIRECTIVE_INCLUDE_STRING, //!< #include "HeaderFile.h"
CPPDIRECTIVE_INCLUDE_BRACE, //!< #include <core>
};
//! Shader resource binding structure.
struct SShaderResourceBinding
{
SShaderResourceBinding() :
Resource (0),
AccessFlags (0)
{
}
SShaderResourceBinding(ShaderResource* BindResource, u8 BindAccessFlags) :
Resource (BindResource ),
AccessFlags (BindAccessFlags)
{
}
~SShaderResourceBinding()
{
}
/* Members */
ShaderResource* Resource;
u8 AccessFlags; //!< \see EResourceAccess
};
/**
Shader classes are used to link several shaders (Vertex-, Pixel shaders etc.) to one shader program.
Modern graphics hardware has the following shader stages:
- Vertex Shader
- Hull Shader (In OpenGL "Tessellation Control" Shader)
- Domain Shader (In OpenGL "Tessellation Evaluation" Shader)
- Geometry Shader
- Pixel Shader (In OpenGL "Fragment" Shader)
- Compute Shader (This is seperated from the graphics pipeline)
\ingroup group_shader
*/
class SP_EXPORT ShaderClass : public BaseObject
{
public:
virtual ~ShaderClass();
/* === Functions === */
/**
Binds the table with its shaders.
\param[in] Object Pointer to a MaterialNode object which shall be used for the shader callback if set.
*/
virtual void bind(const scene::MaterialNode* Object = 0) = 0;
//! Unbinds the table with its shaders.
virtual void unbind() = 0;
//! Compiles and links the whole shader class.
virtual bool compile() = 0;
/**
Adds the specified shader resource object.
\param[in] Resource Pointer to the shader resource object which is to be added.
\param[in] AccessFlags Specifies which access parts of the shader resources are to be added.
By default RESOURCE_ACCESS_READ_WRITE which means that the read- and write access resources will be added.
For HLSL the shader-resource-view (SRV) for read access and the unordered-access-view (UAV) for write access will be added.
Use RESOURCE_ACCESS_READ or RESOURCE_ACCESS_WRITE to only bind the SRV or UAV.
\note At first all textures are bound to a shader and then all shader resources.
This is order is important for the resource registers in the shader.
\see ShaderResource
\see addRWTexture
\see EResourceAccess
\since Version 3.3
*/
virtual void addShaderResource(ShaderResource* Resource, u8 AccessFlags = RESOURCE_ACCESS_READ_WRITE);
/**
Removes the specified shader resource object.
\see addShaderResource
\since Version 3.3
*/
virtual void removeShaderResource(ShaderResource* Resource);
virtual void clearShaderResources();
/**
Adds the specified shader R/W texture object.
\param[in] Tex Pointer to the R/W texture object which is to be added.
In this case the texture must be an R/W texture, i.e. from the type TEXTURE_*_RW.
\see addShaderResource
\see Texture
\see ETextureTypes
\since Version 3.3
*/
virtual void addRWTexture(Texture* Tex);
/**
Removes the specified shader R/W texture object.
\see addRWTexture
\since Version 3.3
*/
virtual void removeRWTexture(Texture* Tex);
virtual void clearRWTextures();
/* === Static functions === */
/**
Returns the shader version used for the specified flags.
\param[in] Flags Specifies the build flags. This can be a combination
of the values in the "EBuildShaderFlags" enumeration.
\return Shader version specified in the "EShaderVersions" enumeration.
If no version could be found "DUMMYSHADER_VERSION" will be returned.
\see EBuildShaderFlags
\since Version 3.2
*/
static EShaderVersions getShaderVersion(s32 Flags);
/**
Builds a complete shader class with the specified vertex-format,
shader source code and build flags.
This is particularly used internally for the deferred-renderer and post-processing effects.
\param[in] Name Specifies the shader name and is used for possible error messages.
\param[out] ShdClass Specifies the resulting shader class object.
\param[in] VertFmt Constant pointer to the vertex format used for the shader class.
\param[in] ShdBufferVertex Constant pointer to the vertex shader source code (std::list<io::stringc>).
\param[in] ShdBufferPixel Constant pointer to the pixel shader source code (std::list<io::stringc>).
\param[in] VertexMain Specifies the name of the vertex shader main function.
\param[in] PixelMain Specifies the name of the pixel shader main function.
\param[in] Flags Specifies the compilation flags. This can be one of the following values:
SHADERBUILD_CG, SHADERBUILD_GLSL, SHADERBUILD_HLSL3 or SHADERBUILD_HLSL5.
\return True if the shader class could be created successful.
\note This function always failes if "ShdBufferVertex" is null pointers.
\see VertexFormat
\see EBuildShaderFlags
\since Version 3.2
*/
static bool build(
const io::stringc &Name,
ShaderClass* &ShdClass,
const VertexFormat* VertFmt,
const std::list<io::stringc>* ShdBufferVertex,
const std::list<io::stringc>* ShdBufferPixel,
const io::stringc &VertexMain = "VertexMain",
const io::stringc &PixelMain = "PixelMain",
s32 Flags = SHADERBUILD_CG
);
/**
Loads a shader resource file and parses it for '#include' directives.
\param[in] FileSys Specifies the file system you want to use.
\param[in] Filename Specifies the filename of the shader resource which is to be loaded.
\param[in,out] ShaderBuffer Specifies the shader source code container which is to be filled.
\param[in] UseCg Specifies whether Cg shaders are to be used or not. By default false.
\since Version 3.3
*/
static bool loadShaderResourceFile(
io::FileSystem &FileSys, const io::stringc &Filename, std::list<io::stringc> &ShaderBuffer, bool UseCg = false
);
/**
Determines whether the given string has an '#include' directive.
\param[in] Line Specifies the string (or rather source code line) which is to be parsed.
\param[out] Filename Specifies the output filename which can be expressed between the
quotation marks inside the '#include' directive (e.g. #include "HeaderFile.h" -> will
result in the string "HeaderFile.h").
\return CPPDIRECTIVE_INCLUDE_STRING if the given string has an '#include' directive with a string,
CPPDIRECTIVE_INCLUDE_BRACE if the given string has an '#include' directive with brace or CPPDIRECTIVE_NONE otherwise.
\note This is actually only used by the "loadShaderResourceFile" function.
\see ECPPDirectives
\see loadShaderResourceFile
\since Version 3.3
*/
static ECPPDirectives parseIncludeDirective(const io::stringc &Line, io::stringc &Filename);
/* === Inline functions === */
/**
Sets the shader object callback function.
\param CallbackProc: Callback function in the form of
"void Callback(ShaderClass* Table, const scene::MaterialNode* Object);".
This callback normally is used to update the world- view matrix. In GLSL these matrices
are integrated but in HLSL you have to set these shader-constants manually.
*/
inline void setObjectCallback(const ShaderObjectCallback &CallbackProc)
{
ObjectCallback_ = CallbackProc;
}
/**
Sets the shader surface callback function.
\param[in] CallbackProc Specifies the surface callback function.
This callback normally is used to update texture settings for each surface.
\see ShaderSurfaceCallback
*/
inline void setSurfaceCallback(const ShaderSurfaceCallback &CallbackProc)
{
SurfaceCallback_ = CallbackProc;
}
inline Shader* getVertexShader() const
{
return VertexShader_;
}
inline Shader* getPixelShader() const
{
return PixelShader_;
}
inline Shader* getGeometryShader() const
{
return GeometryShader_;
}
inline Shader* getHullShader() const
{
return HullShader_;
}
inline Shader* getDomainShader() const
{
return DomainShader_;
}
inline Shader* getComputeShader() const
{
return ComputeShader_;
}
/**
Returns the list of all shader constant buffers used in the shader-class.
To get the list of all shader constant buffers used in a single shader object,
use the equivalent function of the respective shader.
\see Shader::getConstantBufferList
*/
inline const std::vector<ConstantBuffer*>& getConstantBufferList() const
{
return ConstBufferList_;
}
//! Returns the count of shader constant buffers.
inline size_t getConstantBufferCount() const
{
return ConstBufferList_.size();
}
/**
Returns the list of all shader resources.
\see SShaderResourceBinding
*/
inline const std::vector<SShaderResourceBinding>& getShaderResourceList() const
{
return ShaderResources_;
}
//! Returns the count of shader resources.
inline size_t getShaderResourceCount() const
{
return ShaderResources_.size();
}
//! Returns the list of all R/W textures.
inline const std::vector<Texture*>& getRWTextureList() const
{
return RWTextures_;
}
//! Returns the count of R/W textures.
inline size_t getRWTextureCount() const
{
return RWTextures_.size();
}
//! Returns true if the shader is a high level shader.
inline bool isHighLevel() const
{
return HighLevel_;
}
//! Returns true if the shader class has been compiled successfully.
inline bool valid() const
{
return CompiledSuccessfully_;
}
protected:
friend class Shader;
ShaderClass();
/* === Functions === */
void printError(const io::stringc &Message);
void printWarning(const io::stringc &Message);
/* === Members === */
ShaderObjectCallback ObjectCallback_;
ShaderSurfaceCallback SurfaceCallback_;
Shader* VertexShader_;
Shader* PixelShader_;
Shader* GeometryShader_;
Shader* HullShader_;
Shader* DomainShader_;
Shader* ComputeShader_;
std::vector<ConstantBuffer*> ConstBufferList_; //!< List of constant buffers of all shaders in the shader-class.
std::vector<SShaderResourceBinding> ShaderResources_;
std::vector<Texture*> RWTextures_;
bool HighLevel_;
bool CompiledSuccessfully_;
};
} // /namespace scene
} // /namespace sp
#endif
// ================================================================================
| 34.865079 | 131 | 0.629866 |
303fd170eef267427715ae2218bd05a1403ec51d | 3,942 | hpp | C++ | examples/accumulator/accumulators/stubs/template_function_accumulator.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | examples/accumulator/accumulators/stubs/template_function_accumulator.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | examples/accumulator/accumulators/stubs/template_function_accumulator.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2012 Hartmut Kaiser
// Copyright (c) 2011 Bryce Adelstein-Lelbach
//
// 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)
#if !defined(HPX_EXAMPLES_STUBS_TEMPLATE_FUNCTION_ACCUMULATOR_JUL_12_2012_1056AM)
#define HPX_EXAMPLES_STUBS_TEMPLATE_FUNCTION_ACCUMULATOR_JUL_12_2012_1056AM
#include <hpx/hpx_fwd.hpp>
#include <hpx/include/components.hpp>
#include <hpx/include/applier.hpp>
#include <hpx/include/async.hpp>
#include "../server/template_function_accumulator.hpp"
namespace examples { namespace stubs
{
///////////////////////////////////////////////////////////////////////////
struct managed_accumulator
: hpx::components::stub_base<server::template_function_accumulator>
{
///////////////////////////////////////////////////////////////////////
/// Reset the accumulator's value to 0.
///
/// \note This function has fire-and-forget semantics. It will not wait
/// for the action to be executed. Instead, it will return
/// immediately after the action has has been dispatched.
static void reset_non_blocking(hpx::naming::id_type const& gid)
{
typedef server::template_function_accumulator::reset_action action_type;
hpx::apply<action_type>(gid);
}
/// Reset the accumulator's value to 0.
///
/// \note This function is fully synchronous.
static void reset_sync(hpx::naming::id_type const& gid)
{
typedef server::template_function_accumulator::reset_action action_type;
hpx::async<action_type>(gid).get();
}
///////////////////////////////////////////////////////////////////////
/// Add \p arg to the accumulator's value.
///
/// \note This function has fire-and-forget semantics. It will not wait
/// for the action to be executed. Instead, it will return
/// immediately after the action has has been dispatched.
template <typename T>
static void
add_non_blocking(hpx::naming::id_type const& gid, T arg)
{
typedef server::template_function_accumulator::add_action<T> action_type;
hpx::apply<action_type>(gid, arg);
}
/// Add \p arg to the accumulator's value.
///
/// \note This function is fully synchronous.
//[managed_accumulator_stubs_add_sync
template <typename T>
static void
add_sync(hpx::naming::id_type const& gid, T arg)
{
typedef typename server::template_function_accumulator::add_action<T> action_type;
hpx::async<action_type>(gid, arg).get();
}
///////////////////////////////////////////////////////////////////////
/// Asynchronously query the current value of the accumulator.
///
/// \returns This function returns an \a hpx::lcos::future. When the
/// value of this computation is needed, the get() method of
/// the future should be called. If the value is available,
/// get() will return immediately; otherwise, it will block
/// until the value is ready.
static hpx::lcos::future<double>
query_async(hpx::naming::id_type const& gid)
{
typedef server::template_function_accumulator::query_action action_type;
return hpx::async<action_type>(gid);
}
/// Query the current value of the accumulator.
///
/// \note This function is fully synchronous.
static double query_sync(hpx::naming::id_type const& gid)
{
// The following get yields control while the action is executed.
return query_async(gid).get();
}
};
}}
#endif
| 40.22449 | 94 | 0.58067 |
3044e789aeef2de9d1302d7043c1282d0b844e00 | 7,189 | cc | C++ | kernel/fat32/fat32_dirent.cc | mit-pdos/ward | 91b598932d161f907590b9ad21d7df395e5d6712 | [
"MIT-0"
] | 29 | 2019-12-12T02:30:35.000Z | 2022-01-06T17:13:09.000Z | kernel/fat32/fat32_dirent.cc | mit-pdos/ward | 91b598932d161f907590b9ad21d7df395e5d6712 | [
"MIT-0"
] | 47 | 2019-12-11T02:34:13.000Z | 2020-06-08T19:26:59.000Z | kernel/fat32/fat32_dirent.cc | mit-pdos/ward | 91b598932d161f907590b9ad21d7df395e5d6712 | [
"MIT-0"
] | 4 | 2020-12-08T13:46:55.000Z | 2022-01-04T20:25:10.000Z | #include "types.h"
#include "fat32.hh"
static void
strip_char(char *buf, char s)
{
assert(buf);
char *lastch = buf;
while (*lastch)
lastch++;
lastch--;
while (lastch >= buf && *lastch == s) {
*lastch = '\0';
lastch--;
}
}
u32
fat32_dirent::cluster_id()
{
return ((u32) cluster_id_high << 16u) | cluster_id_low;
}
void
fat32_dirent::set_cluster_id(u32 id)
{
cluster_id_high = (u16) (id >> 16u);
cluster_id_low = (u16) id;
}
strbuf<12>
fat32_dirent::extract_filename()
{
strbuf<sizeof(filename) + 1 + sizeof(extension)> out;
// TODO: make this code less sketchy
static_assert(sizeof(filename) + 1 + sizeof(extension) + 1 <= FILENAME_MAX, "8.3 filename must fit in FILENAME_MAX");
memcpy(out.buf_, filename, sizeof(filename));
out.buf_[sizeof(filename)] = '\0';
strip_char(out.buf_, ' ');
memcpy(&out.buf_[strlen(out.buf_)], ".", 2);
out.buf_[strlen(out.buf_)+sizeof(extension)] = '\0';
memcpy(&out.buf_[strlen(out.buf_)], extension, sizeof(extension));
strip_char(out.buf_, ' ');
strip_char(out.buf_, '.');
if (strlen(out.ptr()) == 0)
panic("file had zero-length filename constructed from '%8s.%3s' (first byte %2x, attributes %2x)\n", filename, extension, filename[0], attributes);
return out;
}
u8
fat32_dirent::checksum()
{
// based on https://en.wikipedia.org/wiki/Design_of_the_FAT_file_system#VFAT_long_file_names
u8 checksum = 0;
for (u8 c : filename)
checksum = ((checksum & 1u) << 7u) + (checksum >> 1u) + c;
for (u8 c : extension)
checksum = ((checksum & 1u) << 7u) + (checksum >> 1u) + c;
return checksum;
}
static u32
count_char(const char *s, char c)
{
u32 count = 0;
for (; *s; s++)
if (*s == c)
count++;
return count;
}
// TODO: check all this filename manipulation code for appropriate bounds checks and correctness
u32
fat32_dirent::count_filename_entries(const char *name)
{
strbuf<FILENAME_MAX> nbuf = name;
strip_char(nbuf.buf_, '.');
if (!*nbuf.ptr())
return 0; // too short; empty
u32 dots = count_char(nbuf.ptr(), '.');
if (dots == 0) {
if (strlen(nbuf.ptr()) <= sizeof(fat32_dirent::filename))
return 1;
} else if (dots == 1) {
const char *dot = strchr(nbuf.ptr(), '.');
const char *last = nbuf.ptr() + strlen(nbuf.ptr()) - 1;
if (last - dot <= sizeof(fat32_dirent::extension) && dot - nbuf.ptr() <= sizeof(fat32_dirent::filename))
return 1;
}
// otherwise, we need to use a long filename
// 13 to match max number of characters in fat32_dirent_lfn; 12 is to round up; 1 is because we need a \0 at the end.
u32 long_entries = (strlen(nbuf.ptr()) + 1 + 12) / 13;
if (long_entries > 20 || strlen(nbuf.ptr()) > 255)
return 0; // too long
return long_entries + 1; // plus one because we need a guard entry
}
fat32_dirent
fat32_dirent::short_filename(const char *name)
{
strbuf<FILENAME_MAX> nbuf = name;
strip_char(nbuf.buf_, '.');
assert(*nbuf.ptr()); // non-empty
fat32_dirent out = {};
char *dot = (char*)strchr(nbuf.ptr(), '.');
if (!dot) {
memset((char*) out.extension, ' ', sizeof(out.extension));
} else {
assert(*dot == '.');
*dot = '\0'; // just changing nbuf, so this is fine
u32 elen = strlen(dot+1);
assert(elen <= sizeof(out.extension));
memcpy((char*) out.extension, dot+1, elen);
memset((char*) &out.extension[elen], ' ', sizeof(out.extension) - elen);
}
// populate filename
u32 len = strlen(nbuf.ptr());
assert(len <= sizeof(out.filename));
memcpy((char*) out.filename, nbuf.ptr(), len);
memset((char*) &out.filename[len], ' ', sizeof(out.filename) - len);
return out;
}
fat32_dirent
fat32_dirent::guard_filename(const char *name)
{
// FIXME: it isn't clear whether this is supposed to be something specific, but it's probably not supposed to be this
// format, which is just <first eight filename letters>.<first three extension letters>.
strbuf<FILENAME_MAX> nbuf = name;
strip_char(nbuf.buf_, '.');
assert(*nbuf.ptr()); // non-empty
char *dot = (char*)strchr(nbuf.ptr(), '.');
if (dot)
*dot = '\0';
strbuf<sizeof(filename) + sizeof(extension) + 1> buf;
strncpy(buf.buf_, nbuf.ptr(), sizeof(filename));
buf.buf_[sizeof(filename)] = '\0'; // just in case not otherwise terminated
if (dot) {
char *wptr = buf.buf_ + strlen(buf.buf_);
*wptr++ = '.';
strncpy(wptr, dot+1, sizeof(extension));
wptr[sizeof(extension)] = '\0'; // just in case not otherwise terminated
}
return short_filename(buf.ptr());
}
unsigned int
fat32_dirent_lfn::index()
{
return sequence_number & 0x1Fu;
}
bool
fat32_dirent_lfn::is_continuation()
{
return (sequence_number & 0x40u) == 0;
}
bool
fat32_dirent_lfn::validate()
{
return zero_cluster == 0 && attributes == ATTR_LFN && vfat_type == 0x00 && (sequence_number & 0xA0u) == 0 && convert_char(name_a[0]) != 0;
}
strbuf<13>
fat32_dirent_lfn::extract_name_segment()
{
strbuf<(sizeof(name_a) + sizeof(name_b) + sizeof(name_c)) / sizeof(u16)> out;
int oi = 0;
for (int i = 0; i < sizeof(name_a) / sizeof(u16); i++)
out.buf_[oi++] = convert_char(name_a[i]);
for (int i = 0; i < sizeof(name_b) / sizeof(u16); i++)
out.buf_[oi++] = convert_char(name_b[i]);
for (int i = 0; i < sizeof(name_c) / sizeof(u16); i++)
out.buf_[oi++] = convert_char(name_c[i]);
out.buf_[oi++] = '\0';
assert(oi == sizeof(out.buf_));
return out;
}
fat32_dirent
fat32_dirent_lfn::filename_fragment(const char *name, u32 index, u8 checksum)
{
strbuf<FILENAME_MAX> nbuf = name;
strip_char(nbuf.buf_, '.');
assert(*nbuf.ptr()); // non-empty
u32 total_len = strlen(nbuf.ptr()) + 1; // plus one for NUL terminator
u32 len_of_my_part = MIN(total_len - index * 13, 13);
assert(len_of_my_part >= 1);
bool last_entry = (total_len <= (index + 1) * 13);
assert(index < 0x1Fu);
fat32_dirent_lfn l = {};
l.sequence_number = (u8) ((last_entry ? 0x40u : 0x00u) | ((index + 1) & 0x1Fu));
l.checksum = checksum;
l.attributes = ATTR_LFN;
l.vfat_type = 0;
l.zero_cluster = 0;
u32 ri = index * 13;
u32 rend = ri + len_of_my_part;
for (int i = 0; i < sizeof(name_a) / sizeof(u16); i++)
l.name_a[i] = ri < rend ? unconvert_char(nbuf.ptr()[ri++]) : 0xFFFF;
for (int i = 0; i < sizeof(name_b) / sizeof(u16); i++)
l.name_b[i] = ri < rend ? unconvert_char(nbuf.ptr()[ri++]) : 0xFFFF;
for (int i = 0; i < sizeof(name_c) / sizeof(u16); i++)
l.name_c[i] = ri < rend ? unconvert_char(nbuf.ptr()[ri++]) : 0xFFFF;
assert(ri == rend);
fat32_dirent out = {};
static_assert(sizeof(l) == sizeof(out), "expected directory entries to be the same size");
memcpy(&out, &l, sizeof(fat32_dirent));
return out;
}
u8
fat32_dirent_lfn::convert_char(u16 ucs_2)
{
if (ucs_2 == 0xFFFF) // used as padding
return '\0';
if (ucs_2 > 0xFF) {
static bool has_reported_warning = false;
if (!has_reported_warning) {
has_reported_warning = true;
cprintf("warning: FAT32 driver does not support non-ASCII characters, but found %u in long filename entry [not reporting future unsupported characters]\n", ucs_2);
}
}
return (u8) ucs_2;
}
u16
fat32_dirent_lfn::unconvert_char(u8 ascii)
{
return (u16) ascii;
}
| 29.829876 | 169 | 0.641953 |
30492562f44dbe9294a88209c703116a098d00bd | 7,356 | cpp | C++ | srm 195 div1/FanFailure.cpp | emiliot/topcoder | c58e105424b484a4e5600bad2c58d664cdcae935 | [
"MIT"
] | null | null | null | srm 195 div1/FanFailure.cpp | emiliot/topcoder | c58e105424b484a4e5600bad2c58d664cdcae935 | [
"MIT"
] | null | null | null | srm 195 div1/FanFailure.cpp | emiliot/topcoder | c58e105424b484a4e5600bad2c58d664cdcae935 | [
"MIT"
] | null | null | null | // Paste me into the FileEdit configuration dialog
#include "assert.h"
#include "ctype.h"
#include "float.h"
#include "math.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "stdarg.h"
#include "time.h"
#include "algorithm"
#include "numeric"
#include "functional"
#include "utility"
#include "bitset"
#include "vector"
#include "list"
#include "set"
#include "map"
#include "queue"
#include "stack"
#include "string"
#include "sstream"
#include "iostream"
using namespace std;
#define all(v) (v).begin(), (v).end()
typedef long long i64;
template <class T> void make_unique(T& v) {sort(all(v)); v.resize(unique(all(v)) - v.begin());}
int memo[51][50001];
bool mark[51][50001];
const int INF = 0x3f3f3f3f;
int f(vector <int> &v, int low, int i, int cap){
if(i >= (int)v.size()){
return 0;
}
int &best = memo[i][cap];
if(mark[i][cap])return best;
mark[i][cap] = true;
best = f(v, low, i+1, cap);
if(cap - v[i] >= low){
best = max(best, f(v, low, i+1, cap - v[i]) + 1);
}
return best;
}
int g(vector <int> &v, int low, int i, int cap){
if(i >= (int)v.size()){
if(cap < low)return 0;
else return INF;
}
int &best = memo[i][cap];
if(mark[i][cap])return best;
mark[i][cap] = true;
best = g(v, low, i+1, cap);
best = min(best, g(v, low, i+1, cap - v[i]) + 1);
return best;
}
class FanFailure {
public:
vector <int> getRange( vector <int> capacities, int minCooling ) {
vector <int> res(2, 0);
int cap = 0;
for(int i=0, n=capacities.size(); i<n; ++i)
cap += capacities[i];
memset(mark, false, sizeof(mark));
res[0] = f(capacities, minCooling, 0, cap);
memset(mark, false, sizeof(mark));
res[1] = g(capacities, minCooling, 0, cap)-1;
return res;
}
};
// BEGIN CUT HERE
namespace moj_harness {
int run_test_case(int);
void run_test(int casenum = -1, bool quiet = false) {
if (casenum != -1) {
if (run_test_case(casenum) == -1 && !quiet) {
cerr << "Illegal input! Test case " << casenum << " does not exist." << endl;
}
return;
}
int correct = 0, total = 0;
for (int i=0;; ++i) {
int x = run_test_case(i);
if (x == -1) {
if (i >= 100) break;
continue;
}
correct += x;
++total;
}
if (total == 0) {
cerr << "No test cases run." << endl;
} else if (correct < total) {
cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl;
} else {
cerr << "All " << total << " tests passed!" << endl;
}
}
template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << "{"; for (typename vector<T>::const_iterator vi=v.begin(); vi!=v.end(); ++vi) { if (vi != v.begin()) os << ","; os << " " << *vi; } os << " }"; return os; }
int verify_case(int casenum, const vector <int> &expected, const vector <int> &received, clock_t elapsed) {
cerr << "Example " << casenum << "... ";
string verdict;
vector<string> info;
char buf[100];
if (elapsed > CLOCKS_PER_SEC / 200) {
sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC));
info.push_back(buf);
}
if (expected == received) {
verdict = "PASSED";
} else {
verdict = "FAILED";
}
cerr << verdict;
if (!info.empty()) {
cerr << " (";
for (int i=0; i<(int)info.size(); ++i) {
if (i > 0) cerr << ", ";
cerr << info[i];
}
cerr << ")";
}
cerr << endl;
if (verdict == "FAILED") {
cerr << " Expected: " << expected << endl;
cerr << " Received: " << received << endl;
}
return verdict == "PASSED";
}
int run_test_case(int casenum__) {
switch (casenum__) {
case 0: {
int capacities[] = {1,2,3};
int minCooling = 2;
int expected__[] = { 2, 1 };
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
case 1: {
int capacities[] = {8,5,6,7};
int minCooling = 22;
int expected__[] = { 0, 0 };
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
case 2: {
int capacities[] = {676, 11, 223, 413, 823, 122, 547, 187, 28};
int minCooling = 1000;
int expected__[] = { 7, 2 };
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
case 3: {
int capacities[] = {955, 96, 161, 259, 642, 242, 772, 369, 311, 785, 92, 991, 620, 394, 128, 774, 973, 94, 681, 771, 916, 373, 523, 100, 220, 993, 472, 798, 132, 361, 33, 362, 573, 624, 722, 520, 451, 231, 37, 921, 408, 170, 303, 559, 866, 412, 339, 757, 822, 192};
int minCooling = 3619;
int expected__[] = { 46, 30 };
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
// custom cases
/* case 4: {
int capacities[] = ;
int minCooling = ;
int expected__[] = ;
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}*/
/* case 5: {
int capacities[] = ;
int minCooling = ;
int expected__[] = ;
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}*/
/* case 6: {
int capacities[] = ;
int minCooling = ;
int expected__[] = ;
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}*/
default:
return -1;
}
}
}
int main(int argc, char *argv[]) {
if (argc == 1) {
moj_harness::run_test();
} else {
for (int i=1; i<argc; ++i)
moj_harness::run_test(atoi(argv[i]));
}
}
// END CUT HERE
| 30.396694 | 277 | 0.592577 |
304ca01da15122c17a533bad4bf5c6afe013c09a | 4,046 | cpp | C++ | OverEngine/src/OverEngine/Scene/Components.cpp | gitter-badger/OverEngine | 7ade00f120ccc62804f1bfdeb34daf7e179d33bb | [
"MIT"
] | 1 | 2020-11-24T06:13:34.000Z | 2020-11-24T06:13:34.000Z | OverEngine/src/OverEngine/Scene/Components.cpp | gitter-badger/OverEngine | 7ade00f120ccc62804f1bfdeb34daf7e179d33bb | [
"MIT"
] | null | null | null | OverEngine/src/OverEngine/Scene/Components.cpp | gitter-badger/OverEngine | 7ade00f120ccc62804f1bfdeb34daf7e179d33bb | [
"MIT"
] | null | null | null | #include "pcheader.h"
#include "Components.h"
namespace OverEngine
{
SerializationContext* SpriteRendererComponent::Reflect()
{
static bool initialized = false;
static SerializationContext ctx;
if (!initialized)
{
initialized = true;
if (!Serializer::GlobalEnumExists("TextureWrapping"))
{
Serializer::DefineGlobalEnum("TextureWrapping", {
{ 0, "None" },
{ 1, "Repeat" },
{ 2, "MirroredRepeat" },
{ 3, "ClampToEdge" },
{ 4, "ClampToBorder" }
});
}
if (!Serializer::GlobalEnumExists("TextureFiltering"))
{
Serializer::DefineGlobalEnum("TextureFiltering", {
{ 0, "None" },
{ 1, "Nearest" },
{ 2, "Linear" }
});
}
ctx.AddField(SerializableType::Float4, SERIALIZE_FIELD(SpriteRendererComponent, Tint));
ctx.AddField(SerializableType::Float2, SERIALIZE_FIELD(SpriteRendererComponent, Tiling));
ctx.AddField(SerializableType::Float2, SERIALIZE_FIELD(SpriteRendererComponent, Offset));
ctx.AddField(SerializableType::Bool, OffsetOf(&SpriteRendererComponent::Flip), "Flip.x");
ctx.AddField(SerializableType::Bool, OffsetOf(&SpriteRendererComponent::Flip) + sizeof(bool), "Flip.y");
ctx.AddEnumField(SerializableType::Int8Enum, "TextureWrapping", OffsetOf(&SpriteRendererComponent::Wrapping), "Wrapping.x");
ctx.AddEnumField(SerializableType::Int8Enum, "TextureWrapping", OffsetOf(&SpriteRendererComponent::Wrapping) + sizeof(TextureWrapping), "Wrapping.y");
ctx.AddEnumField(SerializableType::Int8Enum, "TextureFiltering", SERIALIZE_FIELD(SpriteRendererComponent, Filtering));
ctx.AddField(SerializableType::Float, SERIALIZE_FIELD(SpriteRendererComponent, AlphaClipThreshold));
ctx.AddField(SerializableType::Bool, OffsetOf(&SpriteRendererComponent::TextureBorderColor) + OffsetOf(&std::pair<bool, Color>::first), "IsOverridingTextureBorderColor");
ctx.AddField(SerializableType::Float4, OffsetOf(&SpriteRendererComponent::TextureBorderColor) + OffsetOf(&std::pair<bool, Color>::second), "TextureBorderColor");
}
return &ctx;
}
SerializationContext* CameraComponent::Reflect()
{
static bool initialized = false;
static SerializationContext ctx;
if (!initialized)
{
initialized = true;
auto& cameraReflection = *SceneCamera::Reflect();
for (const auto& elem : cameraReflection.Elements)
{
ctx.Elements.push_back(elem);
(ctx.Elements.end() - 1)->Offset += OffsetOf(&CameraComponent::Camera);
}
}
return &ctx;
}
SerializationContext* RigidBody2DComponent::Reflect()
{
static bool initialized = false;
static SerializationContext ctx;
if (!initialized)
{
initialized = true;
if (!Serializer::GlobalEnumExists("RigidBody2DType"))
{
Serializer::DefineGlobalEnum("RigidBody2DType", {
{ 0, "Static" },
{ 1, "Kinematic" },
{ 2, "Dynamic" }
});
}
auto offset = OffsetOf(&RigidBody2DComponent::Initializer);
ctx.AddEnumField(SerializableType::UInt8Enum, "RigidBody2DType", offset + OffsetOf(&RigidBody2DProps::Type), "Type");
ctx.AddField(SerializableType::Float2, offset + OffsetOf(&RigidBody2DProps::LinearVelocity), "LinearVelocity");
ctx.AddField(SerializableType::Float, offset + OffsetOf(&RigidBody2DProps::AngularVelocity), "AngularVelocity");
ctx.AddField(SerializableType::Float, offset + OffsetOf(&RigidBody2DProps::LinearDamping), "LinearDamping");
ctx.AddField(SerializableType::Float, offset + OffsetOf(&RigidBody2DProps::AngularDamping), "AngularDamping");
ctx.AddField(SerializableType::Bool, offset + OffsetOf(&RigidBody2DProps::AllowSleep), "AllowSleep");
ctx.AddField(SerializableType::Bool, offset + OffsetOf(&RigidBody2DProps::Awake), "Awake");
ctx.AddField(SerializableType::Bool, offset + OffsetOf(&RigidBody2DProps::FixedRotation), "FixedRotation");
ctx.AddField(SerializableType::Float, offset + OffsetOf(&RigidBody2DProps::GravityScale), "GravityScale");
ctx.AddField(SerializableType::Bool, offset + OffsetOf(&RigidBody2DProps::Bullet), "Bullet");
}
return &ctx;
}
}
| 34.87931 | 173 | 0.726149 |
304f206ea3efb19f7470a6edb5116fce5b896372 | 552 | hpp | C++ | src/Type.hpp | pawelprazak/jeff-native-agent | 1554a8f69d0f0ca719ae5a794564e0e155b82545 | [
"Apache-2.0"
] | 7 | 2017-12-10T16:37:18.000Z | 2021-01-19T06:33:23.000Z | src/Type.hpp | pawelprazak/jeff-native-agent | 1554a8f69d0f0ca719ae5a794564e0e155b82545 | [
"Apache-2.0"
] | 3 | 2016-01-13T13:39:50.000Z | 2016-02-19T18:08:38.000Z | src/Type.hpp | pawelprazak/jeff-native-agent | 1554a8f69d0f0ca719ae5a794564e0e155b82545 | [
"Apache-2.0"
] | 5 | 2015-12-08T09:03:10.000Z | 2019-07-29T16:13:13.000Z | #ifndef JEFF_NATIVE_AGENT_TYPE_HPP
#define JEFF_NATIVE_AGENT_TYPE_HPP
#include <jni.h>
#include <jvmti.h>
#include "Object.hpp"
class Type : Object {
public:
Type();
Type(const std::string signature);
virtual ~Type();
private:
const std::string signature;
public:
static const Type *const from(jvmtiEnv &jvmti, JNIEnv &jni, std::string signature);
static const Type *const from(jvmtiEnv &jvmti, JNIEnv &jni, char primitive_signature);
const std::string getSignature() const;
};
#endif //JEFF_NATIVE_AGENT_TYPE_HPP
| 19.034483 | 90 | 0.721014 |
30513d53b2a1b4498bffe6aa1f399aff96408a17 | 657 | hpp | C++ | RainbowNoise/src/Library/ColorTransformer.hpp | 1iyiwei/noise | 0d1be2030518517199dff5c7e7514ee072037d59 | [
"MIT"
] | 24 | 2016-12-13T09:48:17.000Z | 2022-01-13T03:24:45.000Z | RainbowNoise/src/Library/ColorTransformer.hpp | 1iyiwei/noise | 0d1be2030518517199dff5c7e7514ee072037d59 | [
"MIT"
] | 2 | 2019-03-29T06:44:41.000Z | 2019-11-12T03:14:25.000Z | RainbowNoise/src/Library/ColorTransformer.hpp | 1iyiwei/noise | 0d1be2030518517199dff5c7e7514ee072037d59 | [
"MIT"
] | 8 | 2016-11-09T15:54:19.000Z | 2021-04-08T14:04:17.000Z | /*
ColorTransformer.hpp
the base class for all color transfomers
Li-Yi Wei
09/26/2009
*/
#ifndef _COLOR_TRANSFORMER_HPP
#define _COLOR_TRANSFORMER_HPP
#include <vector>
using namespace std;
class ColorTransformer
{
public:
typedef vector<float> Vector;
// each basis vector component can be either 0 or a fixed positive value
ColorTransformer(const int input_dimension, const vector<Vector> & output_basis);
virtual ~ColorTransformer(void) = 0;
virtual int Transform(const Vector & input_color, Vector & output_weight) const;
protected:
const int _input_dimension;
const vector<Vector> _output_basis;
};
#endif
| 19.323529 | 85 | 0.747336 |
30534b9793b2207074a3d48925d19d11f017d241 | 142 | cpp | C++ | src/app/camera/camera.cpp | JonCG90/Goby | da1bfcea23c058427e6bad1c58f1cd5405fe4c5f | [
"MIT"
] | null | null | null | src/app/camera/camera.cpp | JonCG90/Goby | da1bfcea23c058427e6bad1c58f1cd5405fe4c5f | [
"MIT"
] | null | null | null | src/app/camera/camera.cpp | JonCG90/Goby | da1bfcea23c058427e6bad1c58f1cd5405fe4c5f | [
"MIT"
] | null | null | null | //
// camera.cpp
// Goby
//
// Created by Jonathan Graham on 8/18/19.
//
#include "camera.hpp"
namespace Goby
{
} // namespace Goby
| 10.142857 | 42 | 0.598592 |
3054fbf14a79cbdc41baa36817c2127adc340035 | 12,908 | cpp | C++ | test/diamond_complex.cpp | rwols/yaml-archive | 4afec73e557c15350c5e068c010f4e378edc95ef | [
"BSL-1.0"
] | 1 | 2018-01-27T23:35:21.000Z | 2018-01-27T23:35:21.000Z | test/diamond_complex.cpp | rwols/yaml-archive | 4afec73e557c15350c5e068c010f4e378edc95ef | [
"BSL-1.0"
] | 2 | 2019-08-17T05:37:36.000Z | 2019-08-17T22:57:26.000Z | test/diamond_complex.cpp | rwols/yaml-archive | 4afec73e557c15350c5e068c010f4e378edc95ef | [
"BSL-1.0"
] | 1 | 2021-03-19T11:53:53.000Z | 2021-03-19T11:53:53.000Z | #include "io_count_fixture.hpp"
#include <boost/serialization/export.hpp>
#include <boost/serialization/map.hpp>
#include <boost/test/unit_test.hpp>
#define NVP(name) BOOST_SERIALIZATION_NVP(name)
using boost::serialization::make_nvp;
namespace {
// used to detect when base_diamond class is saved multiple times
int diamond_save_count = 0;
// used to detect when base_diamond class is loaded multiple times
int diamond_load_count = 0;
}
class EX1Level1
{
public:
EX1Level1() : i(0) {}
EX1Level1(int i) : i(i) { m[i] = "text"; }
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level1");
ar << BOOST_SERIALIZATION_NVP(i);
ar << BOOST_SERIALIZATION_NVP(m);
++diamond_save_count;
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level1");
ar >> BOOST_SERIALIZATION_NVP(i);
ar >> BOOST_SERIALIZATION_NVP(m);
++diamond_load_count;
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
bool operator==(const EX1Level1& another) const
{
return i == another.i && m == another.m;
}
// make polymorphic by marking at least one function virtual
virtual ~EX1Level1(){};
private:
int i;
std::map<int, std::string> m;
};
// note: the default is for object tracking to be performed if and only
// if and object of the corresponding class is anywhere serialized
// through a pointer. In this example, that doesn't occur so
// by default, the shared EX1Level1 object wouldn't normally be tracked.
// This would leave to multiple save/load operation of the data in
// this shared EX1Level1 class. This wouldn't cause an error, but it would
// be a waste of time. So set the tracking behavior trait of the EX1Level1
// class to always track serialized objects of that class. This permits
// the system to detect and elminate redundent save/load operations.
// (It is concievable that this might someday be detected automatically
// but for now, this is not done so we have to rely on the programmer
// to specify this trait)
BOOST_CLASS_TRACKING(EX1Level1, track_always)
class EX1Level2_A : virtual public EX1Level1
{
public:
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level2_A");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level2_A");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX1Level2_B : virtual public EX1Level1
{
public:
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level2_B");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level2_B");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX1Level3_A : public EX1Level2_A, public EX1Level2_B
{
public:
EX1Level3_A() {}
EX1Level3_A(int i) : EX1Level1(i) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level3_A");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A);
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level3_A");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A);
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX1Level3_B : public EX1Level2_A, public EX1Level2_B
{
public:
EX1Level3_B() {}
EX1Level3_B(int) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level3_B");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A);
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level3_B");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A);
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX1Level4 : public EX1Level3_B
{
public:
EX1Level4() {}
EX1Level4(int i) : EX1Level1(i) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level4");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level3_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level4");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level3_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX2Level1
{
public:
EX2Level1() : i(0) {}
EX2Level1(int i) : i(i) { m[i] = "text"; }
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level1");
ar << BOOST_SERIALIZATION_NVP(i);
ar << BOOST_SERIALIZATION_NVP(m);
++diamond_save_count;
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level1");
ar >> BOOST_SERIALIZATION_NVP(i);
ar >> BOOST_SERIALIZATION_NVP(m);
++diamond_load_count;
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
bool operator==(const EX2Level1& another) const
{
return i == another.i && m == another.m;
}
// make polymorphic by marking at least one function virtual
virtual ~EX2Level1(){};
private:
int i;
std::map<int, std::string> m;
};
// note: the default is for object tracking to be performed if and only
// if and object of the corresponding class is anywhere serialized
// through a pointer. In this example, that doesn't occur so
// by default, the shared EX2Level1 object wouldn't normally be tracked.
// This would leave to multiple save/load operation of the data in
// this shared EX2Level1 class. This wouldn't cause an error, but it would
// be a waste of time. So set the tracking behavior trait of the EX2Level1
// class to always track serialized objects of that class. This permits
// the system to detect and elminate redundent save/load operations.
// (It is concievable that this might someday be detected automatically
// but for now, this is not done so we have to rely on the programmer
// to specify this trait)
BOOST_CLASS_TRACKING(EX2Level1, track_always)
class EX2Level2_A : virtual public EX2Level1
{
public:
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level2_A");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level2_A");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX2Level2_B : virtual public EX2Level1
{
public:
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level2_B");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level2_B");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX2Level3_A : public EX2Level2_A, public EX2Level2_B
{
public:
EX2Level3_A() {}
EX2Level3_A(int i) : EX2Level1(i) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level3_A");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A);
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level3_A");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A);
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX2Level3_B : public EX2Level2_A, public EX2Level2_B
{
public:
EX2Level3_B() {}
EX2Level3_B(int i) : EX2Level1(i) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level3_B");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A);
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level3_B");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A);
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX2Level4 : public EX2Level3_B
{
public:
EX2Level4() {}
EX2Level4(int i) : EX2Level1(i) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level4");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level3_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level4");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level3_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
BOOST_CLASS_EXPORT(EX1Level4)
BOOST_CLASS_EXPORT(EX1Level3_A)
BOOST_CLASS_EXPORT(EX2Level3_A)
BOOST_CLASS_EXPORT(EX2Level4)
BOOST_FIXTURE_TEST_CASE(diamond_complex1, io_count_fixture)
{
diamond_save_count = 0;
diamond_load_count = 0;
const EX1Level3_A ex1L3a_save(3);
const EX1Level1* ex1L1_save = &ex1L3a_save;
{
output() << make_nvp("ex1L1", ex1L1_save);
}
EX1Level1* ex1L1_load;
{
input() >> make_nvp("ex1L1", ex1L1_load);
}
BOOST_CHECK(1 == diamond_save_count);
BOOST_CHECK(1 == diamond_load_count);
BOOST_CHECK(*ex1L1_save == *ex1L1_load);
}
BOOST_FIXTURE_TEST_CASE(diamond_complex2, io_count_fixture)
{
diamond_save_count = 0;
diamond_load_count = 0;
const EX1Level4 ex1L4_save(3);
const EX1Level1* ex1L1_save = &ex1L4_save;
{
output() << make_nvp("ex1L1", ex1L1_save);
}
EX1Level1* ex1L1_load;
{
input() >> make_nvp("ex1L1", ex1L1_load);
}
BOOST_CHECK(1 == diamond_save_count);
BOOST_CHECK(1 == diamond_load_count);
BOOST_CHECK(*ex1L1_save == *ex1L1_load);
}
BOOST_FIXTURE_TEST_CASE(diamond_complex3, io_count_fixture)
{
diamond_save_count = 0;
diamond_load_count = 0;
const EX2Level3_A ex2L3a_save(3);
const EX2Level1* ex2L1_save = &ex2L3a_save;
{
output() << make_nvp("ex2L1", ex2L1_save);
}
EX2Level1* ex2L1_load;
{
input() >> make_nvp("ex2L1", ex2L1_load);
}
BOOST_CHECK(1 == diamond_save_count);
BOOST_CHECK(1 == diamond_load_count);
BOOST_CHECK(*ex2L1_save == *ex2L1_load);
}
BOOST_FIXTURE_TEST_CASE(diamond_complex4, io_count_fixture)
{
diamond_save_count = 0;
diamond_load_count = 0;
const EX2Level4 ex2L4_save(3);
const EX2Level1* ex2L1_save = &ex2L4_save;
{
output() << make_nvp("ex2L1", ex2L1_save);
}
EX2Level1* ex2L1_load;
{
input() >> make_nvp("ex2L1", ex2L1_load);
}
// {
// test_ostream ofs(testfile, TEST_STREAM_FLAGS);
// test_oarchive oa(ofs);
// oa << boost::serialization::make_nvp("ex2L1", ex2L1_save);
// }
// {
// test_istream ifs(testfile, TEST_STREAM_FLAGS);
// test_iarchive ia(ifs);
// ia >> boost::serialization::make_nvp("ex2L1", ex2L1_load);
// }
BOOST_CHECK(1 == diamond_save_count);
BOOST_CHECK(1 == diamond_load_count);
BOOST_CHECK(*ex2L1_save == *ex2L1_load);
}
| 29.47032 | 75 | 0.68353 |
305b0147381455dd98f6417efd6da68f5d915c91 | 2,275 | cpp | C++ | C++/Brute Force Password Cracker.cpp | CyanCoding/Brute-Force-Password-Cracker | dcc753618e1de8294b118721adca35f87eb2bfe7 | [
"MIT"
] | 30 | 2019-02-07T23:41:24.000Z | 2022-03-13T15:39:37.000Z | C++/Brute Force Password Cracker.cpp | CyanCoding/Brute-Force-Password-Cracker | dcc753618e1de8294b118721adca35f87eb2bfe7 | [
"MIT"
] | 3 | 2020-09-22T19:55:16.000Z | 2021-10-01T19:48:13.000Z | C++/Brute Force Password Cracker.cpp | CyanCoding/Brute-Force-Password-Cracker | dcc753618e1de8294b118721adca35f87eb2bfe7 | [
"MIT"
] | 28 | 2018-06-08T15:27:03.000Z | 2022-02-07T05:40:29.000Z | #include <iostream>
#include <string> // to_string
#include <iomanip> // setprecision
using namespace std;
bool stop = false;
long long amount = 0;
string password;
clock_t start;
const char Alphabet[62] = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U','V', 'W', 'X', 'Y', 'Z'
};
string separateWithCommas(long long num) {
string s = to_string(num);
int thousands = s.length() - 3;
while (thousands > 0) {
s.insert(thousands, ",");
thousands -= 3;
}
return s;
}
void inline crack(unsigned int length, string current) {
if (length == 0 && stop == false) {
amount++;
if (amount % 10000000 == 0) {
cout << '\r' << separateWithCommas(amount) << " - " << current << " - " << separateWithCommas(amount / ((float)(clock() - start) / CLOCKS_PER_SEC)) << " p/sec";
cout.flush();
}
if (current == password) {
stop = true;
}
return;
}
if (stop == false) {
for (unsigned int i = 0; i < 62; i++) {
crack(length - 1, current + Alphabet[i]);
}
}
}
int main() {
// Greet the user
cout << "Welcome to CyanCoding's Brute Force Password Cracker!" << endl << endl;
cout << "What do you want your password to be? > ";
cin >> password;
cout << "\rAttempting to crack " << password << "..." << endl;
start = clock();
while (stop == false) {
static unsigned int pwLength = 1;
crack(pwLength, "");
pwLength++;
if (stop == true) {
break;
}
}
cout << "\rCyanCoding's C++ BFPC cracked the password \"" << password << "\" in " <<
separateWithCommas(amount) << " attempts and " << setprecision(2) << fixed <<
(float)(clock() - start) / CLOCKS_PER_SEC << " seconds." << endl << endl <<
"That's about " << setprecision(0) <<
separateWithCommas(amount / ((float)(clock() - start) / CLOCKS_PER_SEC)) <<
" passwords per second!" << endl << endl;
return 0;
}
| 30.333333 | 311 | 0.487912 |
305e00e4be433b098a54686754f91b0d53e16b0f | 336 | hpp | C++ | include/mil/utils/index_sequence.hpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | include/mil/utils/index_sequence.hpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | include/mil/utils/index_sequence.hpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | #pragma once
#include <cstddef>
#include "detail/index_sequence.hpp"
namespace mil {
namespace utils {
template <std::size_t... Idx>
using index_sequnece = detail::index_sequnece<Idx...>;
template <std::size_t N>
using make_index_sequence = typename detail::make_index_sequence<N>::type;
} // namespace utils
} // namespace mil
| 18.666667 | 74 | 0.738095 |
305e1854791154a3b617f08dda01e2fada435e2f | 4,627 | cpp | C++ | src/platform/mbino_critical.cpp | tkem/mbino | 6fa2251048a8409170602049f29b231c67f5b8fe | [
"Apache-2.0"
] | 10 | 2017-10-06T14:27:03.000Z | 2021-11-08T11:18:58.000Z | src/platform/mbino_critical.cpp | tkem/mbino | 6fa2251048a8409170602049f29b231c67f5b8fe | [
"Apache-2.0"
] | 49 | 2017-08-12T13:45:55.000Z | 2018-12-22T21:35:54.000Z | src/platform/mbino_critical.cpp | tkem/mbino | 6fa2251048a8409170602049f29b231c67f5b8fe | [
"Apache-2.0"
] | 2 | 2018-07-15T11:06:47.000Z | 2019-05-25T01:10:32.000Z | /* mbino - mbed APIs for the Arduino platform
* Copyright (c) 2017, 2018 Thomas Kemmer
*
* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "platform/mbed_critical.h"
#include "platform/mbed_toolchain.h"
#include "hal/critical_section_api.h"
// mbino limits this to 8 bit for atomic access on AVR, and since 255
// recursive invocations should be enough...
static volatile uint8_t critical_section_reentrancy_counter = 0;
// no matching Arduino API, therefore moved to target
//bool core_util_are_interrupts_enabled(void);
//bool core_util_is_isr_active(void);
bool core_util_in_critical_section(void)
{
return hal_in_critical_section();
}
void core_util_critical_section_enter(void)
{
hal_critical_section_enter();
++critical_section_reentrancy_counter;
}
void core_util_critical_section_exit(void)
{
if (--critical_section_reentrancy_counter == 0) {
hal_critical_section_exit();
}
}
// TODO: MBED_WEAK doesn't work for symbols redefined in the same library - move all to HAL?
template<typename T>
static bool core_util_atomic_cas(volatile T* ptr, T* expectedCurrentValue, T desiredValue)
{
bool success;
T currentValue;
core_util_critical_section_enter();
currentValue = *ptr;
if (currentValue == *expectedCurrentValue) {
*ptr = desiredValue;
success = true;
} else {
*expectedCurrentValue = currentValue;
success = false;
}
core_util_critical_section_exit();
return success;
}
template<typename T, typename U>
static T core_util_atomic_incr(volatile T* valuePtr, U delta)
{
T newValue;
core_util_critical_section_enter();
newValue = *valuePtr + delta;
*valuePtr = newValue;
core_util_critical_section_exit();
return newValue;
}
template<typename T, typename U>
static T core_util_atomic_decr(volatile T* valuePtr, U delta)
{
T newValue;
core_util_critical_section_enter();
newValue = *valuePtr - delta;
*valuePtr = newValue;
core_util_critical_section_exit();
return newValue;
}
MBED_WEAK bool core_util_atomic_cas_u8(volatile uint8_t* ptr, uint8_t* expectedCurrentValue, uint8_t desiredValue)
{
return core_util_atomic_cas(ptr, expectedCurrentValue, desiredValue);
}
MBED_WEAK bool core_util_atomic_cas_u16(volatile uint16_t* ptr, uint16_t* expectedCurrentValue, uint16_t desiredValue)
{
return core_util_atomic_cas(ptr, expectedCurrentValue, desiredValue);
}
MBED_WEAK bool core_util_atomic_cas_u32(volatile uint32_t* ptr, uint32_t* expectedCurrentValue, uint32_t desiredValue)
{
return core_util_atomic_cas(ptr, expectedCurrentValue, desiredValue);
}
MBED_WEAK bool core_util_atomic_cas_ptr(void* volatile* ptr, void** expectedCurrentValue, void* desiredValue)
{
return core_util_atomic_cas(ptr, expectedCurrentValue, desiredValue);
}
MBED_WEAK uint8_t core_util_atomic_incr_u8(volatile uint8_t* valuePtr, uint8_t delta)
{
return core_util_atomic_incr(valuePtr, delta);
}
MBED_WEAK uint16_t core_util_atomic_incr_u16(volatile uint16_t* valuePtr, uint16_t delta)
{
return core_util_atomic_incr(valuePtr, delta);
}
MBED_WEAK uint32_t core_util_atomic_incr_u32(volatile uint32_t* valuePtr, uint32_t delta)
{
return core_util_atomic_incr(valuePtr, delta);
}
MBED_WEAK void* core_util_atomic_incr_ptr(void* volatile* valuePtr, ptrdiff_t delta)
{
return core_util_atomic_incr(reinterpret_cast<char* volatile*>(valuePtr), delta);
}
MBED_WEAK uint8_t core_util_atomic_decr_u8(volatile uint8_t* valuePtr, uint8_t delta)
{
return core_util_atomic_decr(valuePtr, delta);
}
MBED_WEAK uint16_t core_util_atomic_decr_u16(volatile uint16_t* valuePtr, uint16_t delta)
{
return core_util_atomic_decr(valuePtr, delta);
}
MBED_WEAK uint32_t core_util_atomic_decr_u32(volatile uint32_t* valuePtr, uint32_t delta)
{
return core_util_atomic_decr(valuePtr, delta);
}
MBED_WEAK void* core_util_atomic_decr_ptr(void* volatile* valuePtr, ptrdiff_t delta)
{
return core_util_atomic_decr(reinterpret_cast<char* volatile*>(valuePtr), delta);
}
| 30.846667 | 118 | 0.770478 |
30608a5bc5e5b05a736a10130fb51f16f51e84ee | 3,614 | cxx | C++ | FIT/FITcalib/AliFITCalibTimeEq.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | FIT/FITcalib/AliFITCalibTimeEq.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | FIT/FITcalib/AliFITCalibTimeEq.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z |
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// class for FIT calibration TM-AC-AM_6-02-2006
// equalize time shift for each time CFD channel
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliFITCalibTimeEq.h"
#include "AliLog.h"
#include <TFile.h>
#include <TMath.h>
#include <TF1.h>
#include <TSpectrum.h>
#include <TProfile.h>
#include <iostream>
ClassImp(AliFITCalibTimeEq)
//________________________________________________________________
AliFITCalibTimeEq::AliFITCalibTimeEq():TNamed()
{
//
for(Int_t i=0; i<200; i++) {
fTimeEq[i] = 0; // Time Equalized for OCDB
fCFDvalue[i] = 0;
}
}
//________________________________________________________________
AliFITCalibTimeEq::AliFITCalibTimeEq(const char* name):TNamed()
{
//constructor
TString namst = "Calib_";
namst += name;
SetName(namst.Data());
SetTitle(namst.Data());
for(Int_t i=0; i<200; i++) {
fTimeEq[i] = 0; // Time Equalized for OCDB
fCFDvalue[i] = 0;
}
}
//________________________________________________________________
AliFITCalibTimeEq::AliFITCalibTimeEq(const AliFITCalibTimeEq& calibda):TNamed(calibda)
{
// copy constructor
SetName(calibda.GetName());
SetTitle(calibda.GetName());
((AliFITCalibTimeEq &) calibda).Copy(*this);
}
//________________________________________________________________
AliFITCalibTimeEq &AliFITCalibTimeEq::operator =(const AliFITCalibTimeEq& calibda)
{
// assignment operator
SetName(calibda.GetName());
SetTitle(calibda.GetName());
if (this != &calibda) (( AliFITCalibTimeEq &) calibda).Copy(*this);
return *this;
}
//________________________________________________________________
AliFITCalibTimeEq::~AliFITCalibTimeEq()
{
//
// destrictor
}
//________________________________________________________________
void AliFITCalibTimeEq::Reset()
{
//reset values
memset(fCFDvalue,0,200*sizeof(Float_t));
memset(fTimeEq,1,200*sizeof(Float_t));
}
//________________________________________________________________
void AliFITCalibTimeEq::Print(Option_t*) const
{
// print time values
printf("\n ---- PM Arrays ----\n\n");
printf(" Time delay CFD \n");
for (Int_t i=0; i<200; i++)
printf(" CFD %f diff %f \n",fCFDvalue[i],fTimeEq[i]);
}
| 31.982301 | 91 | 0.57969 |
30657cd12bea49e681cd2756206affac7f565829 | 4,202 | cpp | C++ | src/drive.cpp | sizeofvoid/openbsdisks2 | 4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c | [
"BSD-3-Clause"
] | 7 | 2021-05-13T07:43:10.000Z | 2022-01-09T12:18:48.000Z | src/drive.cpp | sizeofvoid/openbsdisks2 | 4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c | [
"BSD-3-Clause"
] | null | null | null | src/drive.cpp | sizeofvoid/openbsdisks2 | 4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright 2016 Gleb Popov <6yearold@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <fcntl.h>
#include <sys/cdio.h>
#include <sys/ioctl.h>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusObjectPath>
#include <QUuid>
#include "bsdisks.h"
#include "drive.h"
Drive::Drive(const QString& devName)
: QDBusContext()
, m_deviceName(devName)
, m_dbusPath(QDBusObjectPath(UDisksDrives + devName))
{
}
const QDBusObjectPath Drive::getDbusPath() const
{
return m_dbusPath;
}
QString Drive::getDeviceName() const
{
return m_deviceName;
}
void Drive::setVendor(const QString& vendor)
{
m_Vendor = vendor;
}
void Drive::setRemovable(bool r)
{
isRemovable = r;
}
void Drive::addBlock(const TBlock& block)
{
qDebug() << "Disk " << getDeviceName() << " add block: " << block->getName();
m_blocks.push_back(block);
}
const TBlockVec Drive::getBlocks() const
{
return m_blocks;
}
void Drive::Eject(const QVariantMap& options)
{
if (!optical())
return;
int fd = open((QStringLiteral("/dev/") + getDeviceName()).toLocal8Bit().constData(), O_RDONLY);
if (fd < 0 && errno != ENXIO) {
QString errorMessage = ::strerror(errno);
connection().send(
message().createErrorReply("org.freedesktop.UDisks2.Error.Failed", errorMessage));
qDebug() << "Eject failed: " << errorMessage;
return;
}
::ioctl(fd, CDIOCALLOW);
int rc = ::ioctl(fd, CDIOCEJECT);
if (rc < 0) {
QString errorMessage = ::strerror(errno);
connection().send(
message().createErrorReply("org.freedesktop.UDisks2.Error.Failed", errorMessage));
qDebug() << "Eject failed: " << errorMessage;
return;
}
}
Configuration Drive::configuration() const
{
Configuration c;
return c;
}
bool Drive::optical() const
{
return getDeviceName().startsWith("cd");
}
QStringList Drive::mediaCompatibility() const
{
if (optical())
return {QStringLiteral("optical_cd")};
return QStringList();
}
QString Drive::vendor() const
{
return m_Vendor;
}
qulonglong Drive::driveSize() const
{
return size;
}
void Drive::setId(const QString& id)
{
m_Id = id;
}
QString Drive::id() const
{
return m_Id;
}
QString Drive::serial() const
{
return m_Duid.toString();
}
void Drive::setSize(qulonglong s)
{
size = s;
}
void Drive::setDuid(const QUuid& duid)
{
m_Duid = duid;
}
bool Drive::ejectable() const
{
return removable();
}
bool Drive::removable() const
{
return optical() || isRemovable;
}
bool Drive::mediaRemovable() const
{
return optical() || removable();
}
QString Drive::connectionBus() const
{
return QString();
}
| 24.011429 | 99 | 0.694669 |
3065e0634838c6a4728f0c0528a5fc7a269dc115 | 675 | cpp | C++ | src/cbtCore/Rendering/Buffer/cbtBufferLayout.cpp | TypeDefinition/cbtEngine | 9ddbc6a5436cc31efc475f6d1c37fade4a003c0d | [
"MIT"
] | null | null | null | src/cbtCore/Rendering/Buffer/cbtBufferLayout.cpp | TypeDefinition/cbtEngine | 9ddbc6a5436cc31efc475f6d1c37fade4a003c0d | [
"MIT"
] | null | null | null | src/cbtCore/Rendering/Buffer/cbtBufferLayout.cpp | TypeDefinition/cbtEngine | 9ddbc6a5436cc31efc475f6d1c37fade4a003c0d | [
"MIT"
] | null | null | null | // Include CBT
#include "cbtBufferLayout.h"
NS_CBT_BEGIN
cbtU32 GetByteSize(cbtBufferDataType _dataType)
{
switch (_dataType)
{
case cbtBufferDataType::CBT_S8:
case cbtBufferDataType::CBT_U8:
return 1;
case cbtBufferDataType::CBT_S16:
case cbtBufferDataType::CBT_U16:
case cbtBufferDataType::CBT_F16:
return 2;
case cbtBufferDataType::CBT_S32:
case cbtBufferDataType::CBT_U32:
case cbtBufferDataType::CBT_F32:
return 4;
case cbtBufferDataType::CBT_F64:
return 8;
default:
return 0;
}
}
NS_CBT_END | 24.107143 | 51 | 0.6 |